Moved make_escapes() and remove_escapes() to support.c.
[freeciv.git] / server / cityturn.c
blob49b777f95ef7b66e672b804384b8c50d37c08dac
1 /***********************************************************************
2 Freeciv - Copyright (C) 1996 - A Kjeldberg, L Gregersen, P Unold
3 This program is free software; you can redistribute it and/or modify
4 it under the terms of the GNU General Public License as published by
5 the Free Software Foundation; either version 2, or (at your option)
6 any later version.
8 This program is distributed in the hope that it will be useful,
9 but WITHOUT ANY WARRANTY; without even the implied warranty of
10 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 GNU General Public License for more details.
12 ***********************************************************************/
14 #ifdef HAVE_CONFIG_H
15 #include <fc_config.h>
16 #endif
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <string.h>
21 #include <math.h> /* exp, sqrt */
23 /* utility */
24 #include "fcintl.h"
25 #include "log.h"
26 #include "mem.h"
27 #include "rand.h"
28 #include "shared.h"
29 #include "support.h"
31 /* common/aicore */
32 #include "cm.h"
34 /* common */
35 #include "achievements.h"
36 #include "borders.h"
37 #include "calendar.h"
38 #include "citizens.h"
39 #include "city.h"
40 #include "culture.h"
41 #include "events.h"
42 #include "disaster.h"
43 #include "game.h"
44 #include "government.h"
45 #include "map.h"
46 #include "player.h"
47 #include "research.h"
48 #include "road.h"
49 #include "specialist.h"
50 #include "tech.h"
51 #include "traderoutes.h"
52 #include "unit.h"
53 #include "unitlist.h"
55 /* common/scriptcore */
56 #include "luascript_types.h"
58 /* server */
59 #include "citizenshand.h"
60 #include "citytools.h"
61 #include "cityturn.h"
62 #include "maphand.h"
63 #include "notify.h"
64 #include "plrhand.h"
65 #include "sanitycheck.h"
66 #include "spacerace.h"
67 #include "srv_log.h"
68 #include "srv_main.h"
69 #include "techtools.h"
70 #include "unittools.h"
71 #include "unithand.h"
73 /* server/advisors */
74 #include "advbuilding.h"
75 #include "advdata.h"
76 #include "autosettlers.h"
78 /* server/scripting */
79 #include "script_server.h"
81 /* Queue for pending city_refresh() */
82 static struct city_list *city_refresh_queue = NULL;
85 static void check_pollution(struct city *pcity);
86 static void city_populate(struct city *pcity, struct player *nationality);
88 static bool worklist_change_build_target(struct player *pplayer,
89 struct city *pcity);
91 static bool city_distribute_surplus_shields(struct player *pplayer,
92 struct city *pcity);
93 static bool city_build_building(struct player *pplayer, struct city *pcity);
94 static bool city_build_unit(struct player *pplayer, struct city *pcity);
95 static bool city_build_stuff(struct player *pplayer, struct city *pcity);
96 static struct impr_type *building_upgrades_to(struct city *pcity,
97 struct impr_type *pimprove);
98 static void upgrade_building_prod(struct city *pcity);
99 static struct unit_type *unit_upgrades_to(struct city *pcity,
100 struct unit_type *id);
101 static void upgrade_unit_prod(struct city *pcity);
103 /* Helper struct for associating a building to a city. */
104 struct cityimpr {
105 struct city *pcity;
106 struct impr_type *pimprove;
109 #define SPECLIST_TAG cityimpr
110 #define SPECLIST_TYPE struct cityimpr
111 #include "speclist.h"
113 #define cityimpr_list_iterate(cityimprlist, pcityimpr) \
114 TYPED_LIST_ITERATE(struct cityimpr, cityimprlist, pcityimpr)
115 #define cityimpr_list_iterate_end LIST_ITERATE_END
117 static bool sell_random_building(struct player *pplayer,
118 struct cityimpr_list *imprs);
119 static struct unit *sell_random_unit(struct player *pplayer,
120 struct unit_list *punitlist);
122 static citizens city_reduce_specialists(struct city *pcity, citizens change);
123 static citizens city_reduce_workers(struct city *pcity, citizens change);
125 static bool city_balance_treasury_buildings(struct city *pcity);
126 static bool city_balance_treasury_units(struct city *pcity);
127 static bool player_balance_treasury_units_and_buildings
128 (struct player *pplayer);
129 static bool player_balance_treasury_units(struct player *pplayer);
131 static bool disband_city(struct city *pcity);
133 static void define_orig_production_values(struct city *pcity);
134 static void update_city_activity(struct city *pcity);
135 static void nullify_caravan_and_disband_plus(struct city *pcity);
136 static bool city_illness_check(const struct city * pcity);
138 static float city_migration_score(struct city *pcity);
139 static bool do_city_migration(struct city *pcity_from,
140 struct city *pcity_to);
141 static bool check_city_migrations_player(const struct player *pplayer);
143 /**************************************************************************
144 Updates unit upkeeps and city internal cached data. Returns whether
145 city radius has changed.
146 **************************************************************************/
147 bool city_refresh(struct city *pcity)
149 bool retval;
151 pcity->server.needs_refresh = FALSE;
153 retval = city_map_update_radius_sq(pcity);
154 city_units_upkeep(pcity); /* update unit upkeep */
155 city_refresh_from_main_map(pcity, NULL);
156 city_style_refresh(pcity);
158 if (retval) {
159 /* Force a sync of the city after the change. */
160 send_city_info(city_owner(pcity), pcity);
163 return retval;
166 /**************************************************************************
167 Called on government change or wonder completion or stuff like that
168 -- Syela
169 **************************************************************************/
170 void city_refresh_for_player(struct player *pplayer)
172 conn_list_do_buffer(pplayer->connections);
173 city_list_iterate(pplayer->cities, pcity) {
174 if (city_refresh(pcity)) {
175 auto_arrange_workers(pcity);
177 send_city_info(pplayer, pcity);
178 } city_list_iterate_end;
179 conn_list_do_unbuffer(pplayer->connections);
182 /****************************************************************************
183 Queue pending city_refresh() for later.
184 ****************************************************************************/
185 void city_refresh_queue_add(struct city *pcity)
187 if (NULL == city_refresh_queue) {
188 city_refresh_queue = city_list_new();
189 } else if (city_list_find_number(city_refresh_queue, pcity->id)) {
190 return;
193 city_list_prepend(city_refresh_queue, pcity);
194 pcity->server.needs_refresh = TRUE;
197 /*************************************************************************
198 Refresh the listed cities.
199 Called after significant changes to borders, and arranging workers.
200 *************************************************************************/
201 void city_refresh_queue_processing(void)
203 if (NULL == city_refresh_queue) {
204 return;
207 city_list_iterate(city_refresh_queue, pcity) {
208 if (pcity->server.needs_refresh) {
209 if (city_refresh(pcity)) {
210 auto_arrange_workers(pcity);
212 send_city_info(city_owner(pcity), pcity);
214 } city_list_iterate_end;
216 city_list_destroy(city_refresh_queue);
217 city_refresh_queue = NULL;
220 /**************************************************************************
221 Automatically sells obsolete buildings from city.
222 **************************************************************************/
223 void remove_obsolete_buildings_city(struct city *pcity, bool refresh)
225 struct player *pplayer = city_owner(pcity);
226 bool sold = FALSE;
228 city_built_iterate(pcity, pimprove) {
229 if (improvement_obsolete(pplayer, pimprove, pcity)
230 && can_city_sell_building(pcity, pimprove)) {
231 int sgold;
233 do_sell_building(pplayer, pcity, pimprove);
234 sgold = impr_sell_gold(pimprove);
235 notify_player(pplayer, city_tile(pcity), E_IMP_SOLD, ftc_server,
236 PL_("%s is selling %s (obsolete) for %d.",
237 "%s is selling %s (obsolete) for %d.",
238 sgold),
239 city_link(pcity),
240 improvement_name_translation(pimprove),
241 sgold);
242 sold = TRUE;
244 } city_built_iterate_end;
246 if (sold && refresh) {
247 if (city_refresh(pcity)) {
248 auto_arrange_workers(pcity);
250 send_city_info(pplayer, pcity);
251 send_player_info_c(pplayer, NULL); /* Send updated gold to all */
255 /**************************************************************************
256 Sell obsolete buildings from all cities of the player
257 **************************************************************************/
258 void remove_obsolete_buildings(struct player *pplayer)
260 city_list_iterate(pplayer->cities, pcity) {
261 remove_obsolete_buildings_city(pcity, FALSE);
262 } city_list_iterate_end;
265 /**************************************************************************
266 Rearrange workers according to a cm_result struct. The caller must make
267 sure that the result is valid.
268 **************************************************************************/
269 void apply_cmresult_to_city(struct city *pcity,
270 const struct cm_result *cmr)
272 struct tile *pcenter = city_tile(pcity);
274 /* Now apply results */
275 city_tile_iterate_skip_free_worked(city_map_radius_sq_get(pcity), pcenter,
276 ptile, idx, x, y) {
277 struct city *pwork = tile_worked(ptile);
279 if (cmr->worker_positions[idx]) {
280 if (NULL == pwork) {
281 city_map_update_worker(pcity, ptile);
282 } else {
283 fc_assert(pwork == pcity);
285 } else {
286 if (pwork == pcity) {
287 city_map_update_empty(pcity, ptile);
290 } city_tile_iterate_skip_free_worked_end;
292 specialist_type_iterate(sp) {
293 pcity->specialists[sp] = cmr->specialists[sp];
294 } specialist_type_iterate_end;
297 /**************************************************************************
298 Call sync_cities() to send the affected cities to the clients.
299 **************************************************************************/
300 void auto_arrange_workers(struct city *pcity)
302 struct cm_parameter cmp;
303 struct cm_result *cmr;
305 /* See comment in freeze_workers(): we can't rearrange while
306 * workers are frozen (i.e. multiple updates need to be done). */
307 if (pcity->server.workers_frozen > 0) {
308 pcity->server.needs_arrange = TRUE;
309 return;
311 TIMING_LOG(AIT_CITIZEN_ARRANGE, TIMER_START);
313 /* Freeze the workers and make sure all the tiles around the city
314 * are up to date. Then thaw, but hackishly make sure that thaw
315 * doesn't call us recursively, which would waste time. */
316 city_freeze_workers(pcity);
317 pcity->server.needs_arrange = FALSE;
319 city_map_update_all(pcity);
321 pcity->server.needs_arrange = FALSE;
322 city_thaw_workers(pcity);
324 /* Now start actually rearranging. */
325 city_refresh(pcity);
327 sanity_check_city(pcity);
328 cm_clear_cache(pcity);
330 cm_init_parameter(&cmp);
331 cmp.require_happy = FALSE;
332 cmp.allow_disorder = FALSE;
333 cmp.allow_specialists = TRUE;
335 /* We used to look at pplayer->ai.xxx_priority to determine the values
336 * to be used here. However that doesn't work at all because those values
337 * are on a different scale. Later the ai may wish to adjust its
338 * priorities - this should be done via a separate set of variables. */
339 if (city_size_get(pcity) > 1) {
340 if (city_size_get(pcity) <= game.info.notradesize) {
341 cmp.factor[O_FOOD] = 15;
342 } else {
343 if (city_granary_size(city_size_get(pcity)) == pcity->food_stock) {
344 /* We don't need more food if the granary is full. */
345 cmp.factor[O_FOOD] = 0;
346 } else {
347 cmp.factor[O_FOOD] = 10;
350 } else {
351 /* Growing to size 2 is the highest priority. */
352 cmp.factor[O_FOOD] = 20;
354 cmp.factor[O_SHIELD] = 5;
355 cmp.factor[O_TRADE] = 0; /* Trade only provides gold/science. */
356 cmp.factor[O_GOLD] = 2;
357 cmp.factor[O_LUXURY] = 0; /* Luxury only influences happiness. */
358 cmp.factor[O_SCIENCE] = 2;
359 cmp.happy_factor = 0;
361 if (city_granary_size(city_size_get(pcity)) == pcity->food_stock) {
362 cmp.minimal_surplus[O_FOOD] = 0;
363 } else {
364 cmp.minimal_surplus[O_FOOD] = 1;
366 cmp.minimal_surplus[O_SHIELD] = 1;
367 cmp.minimal_surplus[O_TRADE] = 0;
368 cmp.minimal_surplus[O_GOLD] = -FC_INFINITY;
369 cmp.minimal_surplus[O_LUXURY] = 0;
370 cmp.minimal_surplus[O_SCIENCE] = 0;
372 /* This must be after city_refresh() so that the result gets created for the right
373 * city radius */
374 cmr = cm_result_new(pcity);
375 cm_query_result(pcity, &cmp, cmr);
377 if (!cmr->found_a_valid) {
378 /* Drop surpluses and try again. */
379 cmp.minimal_surplus[O_FOOD] = 0;
380 cmp.minimal_surplus[O_SHIELD] = 0;
381 cmp.minimal_surplus[O_GOLD] = -FC_INFINITY;
382 cm_query_result(pcity, &cmp, cmr);
384 if (!cmr->found_a_valid) {
385 /* Emergency management. Get _some_ result. This doesn't use
386 * cm_init_emergency_parameter so we can keep the factors from
387 * above. */
388 output_type_iterate(o) {
389 cmp.minimal_surplus[o] = MIN(cmp.minimal_surplus[o],
390 MIN(pcity->surplus[o], 0));
391 } output_type_iterate_end;
392 cmp.require_happy = FALSE;
393 cmp.allow_disorder = city_owner(pcity)->ai_controlled ? FALSE : TRUE;
394 cm_query_result(pcity, &cmp, cmr);
396 if (!cmr->found_a_valid) {
397 /* Should never happen. */
398 CITY_LOG(LOG_DEBUG, pcity, "emergency management");
399 cm_init_emergency_parameter(&cmp);
400 cm_query_result(pcity, &cmp, cmr);
402 fc_assert_ret(cmr->found_a_valid);
404 apply_cmresult_to_city(pcity, cmr);
406 if (pcity->server.debug) {
407 /* Print debug output if requested. */
408 cm_print_city(pcity);
409 cm_print_result(cmr);
412 if (city_refresh(pcity)) {
413 log_error("%s radius changed when already arranged workers.",
414 city_name_get(pcity));
415 /* Can't do anything - don't want to enter infinite recursive loop
416 * by trying to arrange workers more. */
418 sanity_check_city(pcity);
420 cm_result_destroy(cmr);
421 TIMING_LOG(AIT_CITIZEN_ARRANGE, TIMER_STOP);
424 /****************************************************************************
425 Notices about cities that should be sent to all players.
426 ****************************************************************************/
427 static void city_global_turn_notify(struct conn_list *dest)
429 cities_iterate(pcity) {
430 struct impr_type *pimprove = pcity->production.value.building;
432 if (VUT_IMPROVEMENT == pcity->production.kind
433 && is_great_wonder(pimprove)
434 && great_wonder_is_available(pimprove)
435 && (1 >= city_production_turns_to_build(pcity, TRUE))) {
436 notify_conn(dest, city_tile(pcity),
437 E_WONDER_WILL_BE_BUILT, ftc_server,
438 _("Notice: Wonder %s in %s will be finished next turn."),
439 improvement_name_translation(pimprove), city_link(pcity));
441 } cities_iterate_end;
444 /****************************************************************************
445 Send turn notifications for specified city to specified connections.
446 If 'pplayer' is not NULL, the message will be cached for this player.
447 ****************************************************************************/
448 static void city_turn_notify(const struct city *pcity,
449 struct conn_list *dest,
450 const struct player *cache_for_player)
452 struct impr_type *pimprove = pcity->production.value.building;
453 struct packet_chat_msg packet;
454 int turns_growth, turns_granary;
456 if (0 < pcity->surplus[O_FOOD]) {
457 turns_growth = (city_granary_size(city_size_get(pcity))
458 - pcity->food_stock - 1) / pcity->surplus[O_FOOD];
460 if (0 == get_city_bonus(pcity, EFT_GROWTH_FOOD)
461 && 0 < get_current_construction_bonus(pcity, EFT_GROWTH_FOOD,
462 RPT_CERTAIN)
463 && 0 < pcity->surplus[O_SHIELD]) {
464 /* From the check above, the surplus must always be positive. */
465 turns_granary = (impr_build_shield_cost(pimprove)
466 - pcity->shield_stock) / pcity->surplus[O_SHIELD];
467 /* If growth and granary completion occur simultaneously, granary
468 * preserves food. -AJS. */
469 if (5 > turns_growth && 5 > turns_granary
470 && turns_growth < turns_granary) {
471 package_event(&packet, city_tile(pcity),
472 E_CITY_GRAN_THROTTLE, ftc_server,
473 _("Suggest throttling growth in %s to use %s "
474 "(being built) more effectively."),
475 city_link(pcity),
476 improvement_name_translation(pimprove));
477 lsend_packet_chat_msg(dest, &packet);
478 if (NULL != cache_for_player) {
479 event_cache_add_for_player(&packet, cache_for_player);
484 if (0 >= turns_growth && !city_celebrating(pcity)
485 && city_can_grow_to(pcity, city_size_get(pcity) + 1)) {
486 package_event(&packet, city_tile(pcity),
487 E_CITY_MAY_SOON_GROW, ftc_server,
488 _("%s may soon grow to size %i."),
489 city_link(pcity), city_size_get(pcity) + 1);
490 lsend_packet_chat_msg(dest, &packet);
491 if (NULL != cache_for_player) {
492 event_cache_add_for_player(&packet, cache_for_player);
495 } else {
496 if (0 >= pcity->food_stock + pcity->surplus[O_FOOD]
497 && 0 > pcity->surplus[O_FOOD]) {
498 package_event(&packet, city_tile(pcity),
499 E_CITY_FAMINE_FEARED, ftc_server,
500 _("Warning: Famine feared in %s."), city_link(pcity));
501 lsend_packet_chat_msg(dest, &packet);
502 if (NULL != cache_for_player) {
503 event_cache_add_for_player(&packet, cache_for_player);
509 /****************************************************************************
510 Send global and player specific city turn notifications. If 'pconn' is
511 NULL, it will send to all connections and cache the events.
512 ****************************************************************************/
513 void send_city_turn_notifications(struct connection *pconn)
515 if (NULL != pconn) {
516 struct player *pplayer = conn_get_player(pconn);
518 if (NULL != pplayer) {
519 city_list_iterate(pplayer->cities, pcity) {
520 city_turn_notify(pcity, pconn->self, NULL);
521 } city_list_iterate_end;
523 city_global_turn_notify(pconn->self);
524 } else {
525 players_iterate(pplayer) {
526 city_list_iterate(pplayer->cities, pcity) {
527 city_turn_notify(pcity, pplayer->connections, pplayer);
528 } city_list_iterate_end;
529 } players_iterate_end;
530 /* NB: notifications to 'game.est_connections' are automatically
531 * cached. */
532 city_global_turn_notify(game.est_connections);
536 /**************************************************************************
537 Update all cities of one nation (costs for buildings, unit upkeep, ...).
538 **************************************************************************/
539 void update_city_activities(struct player *pplayer)
541 char buf[4 * MAX_LEN_NAME];
542 int n, gold;
544 fc_assert(NULL != pplayer);
545 fc_assert(NULL != pplayer->cities);
547 n = city_list_size(pplayer->cities);
548 gold = pplayer->economic.gold;
549 pplayer->server.bulbs_last_turn = 0;
551 if (n > 0) {
552 struct city *cities[n];
553 int i = 0, r;
555 city_list_iterate(pplayer->cities, pcity) {
556 int ci;
558 citizens_convert(pcity);
560 /* Cancel traderoutes that cannot exist any more */
561 for (ci = 0; ci < MAX_TRADE_ROUTES; ci++) {
562 struct city *tcity = game_city_by_number(pcity->trade[ci]);
564 if (tcity != NULL && !can_cities_trade(pcity, tcity)) {
565 enum trade_route_type type = cities_trade_route_type(pcity, tcity);
566 struct trade_route_settings *settings = trade_route_settings_by_type(type);
568 if (settings->cancelling == TRI_CANCEL) {
569 remove_trade_route(pcity, tcity, TRUE, FALSE);
574 /* Add cities to array for later random order handling */
575 cities[i++] = pcity;
576 } city_list_iterate_end;
578 /* How gold upkeep is handled depends on the setting
579 * 'game.info.gold_upkeep_style':
580 * GOLD_UPKEEP_CITY: Each city tries to balance its upkeep individually
581 * (this is done in update_city_activity()).
582 * GOLD_UPKEEP_MIXED: Each city tries to balance its upkeep for
583 * buildings individually; the upkeep for units is
584 * paid by the nation.
585 * GOLD_UPKEEP_NATION: The nation as a whole balances the treasury. If
586 * the treasury is not balance units and buildings
587 * are sold. */
589 /* Iterate over cities in a random order. */
590 while (i > 0) {
591 r = fc_rand(i);
592 /* update unit upkeep */
593 city_units_upkeep(cities[r]);
594 update_city_activity(cities[r]);
595 cities[r] = cities[--i];
598 if (pplayer->economic.gold < 0) {
599 switch (game.info.gold_upkeep_style) {
600 case GOLD_UPKEEP_CITY:
601 break;
602 case GOLD_UPKEEP_MIXED:
603 /* Nation pays for units. */
604 player_balance_treasury_units(pplayer);
605 break;
606 case GOLD_UPKEEP_NATION:
607 /* Nation pays for units and buildings. */
608 player_balance_treasury_units_and_buildings(pplayer);
609 break;
613 /* Should not happen. */
614 fc_assert(pplayer->economic.gold >= 0);
617 /* This test includes the cost of the units because
618 * units are paid for in update_city_activity() or
619 * player_balance_treasury_units(). */
620 if (gold - (gold - pplayer->economic.gold) * 3 < 0) {
621 notify_player(pplayer, NULL, E_LOW_ON_FUNDS, ftc_server,
622 _("WARNING, we're LOW on FUNDS %s."),
623 ruler_title_for_player(pplayer, buf, sizeof(buf)));
626 #if 0
627 /* Uncomment to unbalance the game, like in civ1 (CLG). */
628 if (pplayer->got_tech && pplayer->research->researched > 0) {
629 pplayer->research->researched = 0;
631 #endif
633 city_refresh_queue_processing();
636 /**************************************************************************
637 Reduce the city specialists by some (positive) value.
638 Return the amount of reduction.
639 **************************************************************************/
640 static citizens city_reduce_specialists(struct city *pcity, citizens change)
642 citizens want = change;
644 fc_assert_ret_val(0 < change, 0);
646 specialist_type_iterate(sp) {
647 citizens fix = MIN(want, pcity->specialists[sp]);
649 pcity->specialists[sp] -= fix;
650 want -= fix;
651 } specialist_type_iterate_end;
653 return change - want;
656 /**************************************************************************
657 Reduce the city workers by some (positive) value.
658 Return the amount of reduction.
659 **************************************************************************/
660 static citizens city_reduce_workers(struct city *pcity, citizens change)
662 struct tile *pcenter = city_tile(pcity);
663 int want = change;
665 fc_assert_ret_val(0 < change, 0);
667 city_tile_iterate_skip_free_worked(city_map_radius_sq_get(pcity), pcenter,
668 ptile, _index, _x, _y) {
669 if (0 < want && tile_worked(ptile) == pcity) {
670 city_map_update_empty(pcity, ptile);
671 want--;
673 } city_tile_iterate_skip_free_worked_end;
675 return change - want;
678 /**************************************************************************
679 Reduce the city size. Return TRUE if the city survives the population
680 loss.
681 **************************************************************************/
682 bool city_reduce_size(struct city *pcity, citizens pop_loss,
683 struct player *destroyer, const char *reason)
685 citizens loss_remain;
686 int old_radius_sq;
688 if (pop_loss == 0) {
689 return TRUE;
692 if (reason != NULL) {
693 script_server_signal_emit("city_size_change", 3,
694 API_TYPE_CITY, pcity,
695 API_TYPE_INT, -pop_loss,
696 API_TYPE_STRING, reason);
699 if (city_size_get(pcity) <= pop_loss) {
701 script_server_signal_emit("city_destroyed", 3,
702 API_TYPE_CITY, pcity,
703 API_TYPE_PLAYER, pcity->owner,
704 API_TYPE_PLAYER, destroyer);
706 remove_city(pcity);
707 return FALSE;
709 old_radius_sq = tile_border_source_radius_sq(pcity->tile);
710 city_size_add(pcity, -pop_loss);
711 map_update_border(pcity->tile, pcity->owner, old_radius_sq,
712 tile_border_source_radius_sq(pcity->tile));
714 /* Cap the food stock at the new granary size. */
715 if (pcity->food_stock > city_granary_size(city_size_get(pcity))) {
716 pcity->food_stock = city_granary_size(city_size_get(pcity));
719 /* First try to kill off the specialists */
720 loss_remain = pop_loss - city_reduce_specialists(pcity, pop_loss);
722 if (loss_remain > 0) {
723 /* Take it out on workers */
724 loss_remain -= city_reduce_workers(pcity, loss_remain);
727 /* Update citizens. */
728 citizens_update(pcity, NULL);
730 /* Update number of people in each feelings category.
731 * This also updates the city radius if needed. */
732 city_refresh(pcity);
734 auto_arrange_workers(pcity);
736 /* Send city data. */
737 sync_cities();
739 fc_assert_ret_val_msg(0 == loss_remain, TRUE,
740 "city_reduce_size() has remaining"
741 "%d of %d for \"%s\"[%d]",
742 loss_remain, pop_loss,
743 city_name_get(pcity), city_size_get(pcity));
745 /* Update cities that have trade routes with us */
746 trade_routes_iterate(pcity, pcity2) {
747 if (city_refresh(pcity2)) {
748 /* This should never happen, but if it does, make sure not to
749 * leave workers outside city radius. */
750 auto_arrange_workers(pcity2);
752 } trade_routes_iterate_end;
754 sanity_check_city(pcity);
755 return TRUE;
758 /**************************************************************************
759 Repair the city population without affecting city size.
760 Used by savegame.c and sanitycheck.c
761 **************************************************************************/
762 void city_repair_size(struct city *pcity, int change)
764 if (change > 0) {
765 pcity->specialists[DEFAULT_SPECIALIST] += change;
766 } else if (change < 0) {
767 int need = change + city_reduce_specialists(pcity, -change);
769 if (0 > need) {
770 need += city_reduce_workers(pcity, -need);
773 fc_assert_msg(0 == need,
774 "city_repair_size() has remaining %d of %d for \"%s\"[%d]",
775 need, change, city_name_get(pcity), city_size_get(pcity));
779 /**************************************************************************
780 Return the percentage of food that is lost in this city.
782 Normally this value is 0% but this can be increased by EFT_GROWTH_FOOD
783 effects.
784 **************************************************************************/
785 static int granary_savings(const struct city *pcity)
787 int savings = get_city_bonus(pcity, EFT_GROWTH_FOOD);
789 return CLIP(0, savings, 100);
792 /**************************************************************************
793 Reset the foodbox, usually when a city grows or shrinks.
794 By default it is reset to zero, but this can be increased by Growth_Food
795 effects.
796 Usually this should be called before the city changes size.
797 **************************************************************************/
798 static void city_reset_foodbox(struct city *pcity, int new_size)
800 fc_assert_ret(pcity != NULL);
801 pcity->food_stock = (city_granary_size(new_size)
802 * granary_savings(pcity)) / 100;
805 /**************************************************************************
806 Increase city size by one. We do not refresh borders or send info about
807 the city to the clients as part of this function. There might be several
808 calls to this function at once, and those actions are needed only once.
809 **************************************************************************/
810 static bool city_increase_size(struct city *pcity, struct player *nationality)
812 int new_food;
813 int savings_pct = granary_savings(pcity);
814 bool have_square = FALSE;
815 bool rapture_grow = city_rapture_grow(pcity); /* check before size increase! */
816 struct tile *pcenter = city_tile(pcity);
817 struct player *powner = city_owner(pcity);
818 struct impr_type *pimprove = pcity->production.value.building;
819 int saved_id = pcity->id;
821 if (!city_can_grow_to(pcity, city_size_get(pcity) + 1)) {
822 /* need improvement */
823 if (get_current_construction_bonus(pcity, EFT_SIZE_ADJ, RPT_CERTAIN) > 0
824 || get_current_construction_bonus(pcity, EFT_SIZE_UNLIMIT, RPT_CERTAIN) > 0) {
825 notify_player(powner, city_tile(pcity), E_CITY_AQ_BUILDING, ftc_server,
826 _("%s needs %s (being built) to grow beyond size %d."),
827 city_link(pcity),
828 improvement_name_translation(pimprove),
829 city_size_get(pcity));
830 } else {
831 notify_player(powner, city_tile(pcity), E_CITY_AQUEDUCT, ftc_server,
832 _("%s needs an improvement to grow beyond size %d."),
833 city_link(pcity), city_size_get(pcity));
835 /* Granary can only hold so much */
836 new_food = (city_granary_size(city_size_get(pcity))
837 * (100 * 100 - game.server.aqueductloss * (100 - savings_pct))
838 / (100 * 100));
839 pcity->food_stock = MIN(pcity->food_stock, new_food);
840 return FALSE;
843 city_size_add(pcity, 1);
845 /* Do not empty food stock if city is growing by celebrating */
846 if (rapture_grow) {
847 new_food = city_granary_size(city_size_get(pcity));
848 } else {
849 new_food = city_granary_size(city_size_get(pcity)) * savings_pct / 100;
851 pcity->food_stock = MIN(pcity->food_stock, new_food);
853 /* If there is enough food, and the city is big enough,
854 * make new citizens into scientists or taxmen -- Massimo */
856 /* Ignore food if no square can be worked */
857 city_tile_iterate_skip_free_worked(city_map_radius_sq_get(pcity), pcenter,
858 ptile, _index, _x, _y) {
859 if (tile_worked(ptile) != pcity /* quick test */
860 && city_can_work_tile(pcity, ptile)) {
861 have_square = TRUE;
863 } city_tile_iterate_skip_free_worked_end;
865 if ((pcity->surplus[O_FOOD] >= 2 || !have_square)
866 && is_city_option_set(pcity, CITYO_NEW_EINSTEIN)) {
867 pcity->specialists[best_specialist(O_SCIENCE, pcity)]++;
868 } else if ((pcity->surplus[O_FOOD] >= 2 || !have_square)
869 && is_city_option_set(pcity, CITYO_NEW_TAXMAN)) {
870 pcity->specialists[best_specialist(O_GOLD, pcity)]++;
871 } else {
872 pcity->specialists[DEFAULT_SPECIALIST]++; /* or else city is !sane */
875 /* Update citizens. */
876 citizens_update(pcity, nationality);
878 /* Refresh the city data; this also checks the squared city radius. */
879 city_refresh(pcity);
881 auto_arrange_workers(pcity);
883 /* Update cities that have trade routes with us */
884 trade_routes_iterate(pcity, pcity2) {
885 if (city_refresh(pcity2)) {
886 /* This should never happen, but if it does, make sure not to
887 * leave workers outside city radius. */
888 auto_arrange_workers(pcity2);
890 } trade_routes_iterate_end;
892 notify_player(powner, city_tile(pcity), E_CITY_GROWTH, ftc_server,
893 _("%s grows to size %d."),
894 city_link(pcity), city_size_get(pcity));
896 /* Deprecated signal. Connect your lua functions to "city_size_change" that's
897 * emitted from calling functions which know the 'reason' of the increase. */
898 script_server_signal_emit("city_growth", 2,
899 API_TYPE_CITY, pcity,
900 API_TYPE_INT, city_size_get(pcity));
901 if (city_exist(saved_id)) {
902 /* Script didn't destroy this city */
903 sanity_check_city(pcity);
905 sync_cities();
907 return TRUE;
910 /****************************************************************************
911 Change the city size. Return TRUE iff the city is still alive afterwards.
912 ****************************************************************************/
913 bool city_change_size(struct city *pcity, citizens size,
914 struct player *nationality, const char *reason)
916 int change = size - city_size_get(pcity);
918 if (change != 0 && reason != NULL) {
919 script_server_signal_emit("city_size_change", 3,
920 API_TYPE_CITY, pcity,
921 API_TYPE_INT, size - city_size_get(pcity),
922 API_TYPE_STRING, reason);
925 if (change > 0) {
926 /* Increase city size until size reached, or increase fails */
927 while (size > city_size_get(pcity)
928 && city_increase_size(pcity, nationality)) {
929 /* city_increase_size() does all the work. */
931 } else if (change < 0) {
932 /* We assume that city_change_size() is never called because
933 * of enemy actions. If that changes, enemy must be passed
934 * to city_reduce_size() */
935 return city_reduce_size(pcity, -change, NULL, NULL);
938 map_claim_border(pcity->tile, pcity->owner, -1);
940 return TRUE;
943 /**************************************************************************
944 Check whether the population can be increased or
945 if the city is unable to support a 'settler'...
946 **************************************************************************/
947 static void city_populate(struct city *pcity, struct player *nationality)
949 int saved_id = pcity->id;
950 int granary_size = city_granary_size(city_size_get(pcity));
952 pcity->food_stock += pcity->surplus[O_FOOD];
953 if (pcity->food_stock >= granary_size || city_rapture_grow(pcity)) {
954 if (city_had_recent_plague(pcity)) {
955 notify_player(city_owner(pcity), city_tile(pcity),
956 E_CITY_PLAGUE, ftc_server,
957 _("A recent plague outbreak prevents growth in %s."),
958 city_link(pcity));
959 /* Lose excess food */
960 pcity->food_stock = MIN(pcity->food_stock, granary_size);
961 } else {
962 city_increase_size(pcity, nationality);
963 map_claim_border(pcity->tile, pcity->owner, -1);
964 script_server_signal_emit("city_size_change", 3,
965 API_TYPE_CITY, pcity,
966 API_TYPE_INT, 1,
967 API_TYPE_STRING, "growth");
969 } else if (pcity->food_stock < 0) {
970 /* FIXME: should this depend on units with ability to build
971 * cities or on units that require food in upkeep?
972 * I'll assume citybuilders (units that 'contain' 1 pop) -- sjolie
973 * The above may make more logical sense, but in game terms
974 * you want to disband a unit that is draining your food
975 * reserves. Hence, I'll assume food upkeep > 0 units. -- jjm
977 unit_list_iterate_safe(pcity->units_supported, punit) {
978 if (punit->upkeep[O_FOOD] > 0
979 && !unit_has_type_flag(punit, UTYF_UNDISBANDABLE)) {
981 notify_player(city_owner(pcity), city_tile(pcity),
982 E_UNIT_LOST_MISC, ftc_server,
983 _("Famine feared in %s, %s lost!"),
984 city_link(pcity), unit_tile_link(punit));
986 wipe_unit(punit, ULR_STARVED, NULL);
988 if (city_exist(saved_id)) {
989 city_reset_foodbox(pcity, city_size_get(pcity));
991 return;
993 } unit_list_iterate_safe_end;
994 if (city_size_get(pcity) > 1) {
995 notify_player(city_owner(pcity), city_tile(pcity),
996 E_CITY_FAMINE, ftc_server,
997 _("Famine causes population loss in %s."),
998 city_link(pcity));
999 } else {
1000 notify_player(city_owner(pcity), city_tile(pcity),
1001 E_CITY_FAMINE, ftc_server,
1002 _("Famine destroys %s entirely."),
1003 city_link(pcity));
1005 city_reset_foodbox(pcity, city_size_get(pcity) - 1);
1006 city_reduce_size(pcity, 1, NULL, "famine");
1010 /**************************************************************************
1011 Examine the worklist and change the build target. Return 0 if no
1012 targets are available to change to. Otherwise return non-zero. Has
1013 the side-effect of removing from the worklist any no-longer-available
1014 targets as well as the target actually selected, if any.
1015 **************************************************************************/
1016 static bool worklist_change_build_target(struct player *pplayer,
1017 struct city *pcity)
1019 struct universal target;
1020 bool success = FALSE;
1021 int i;
1022 int saved_id = pcity->id;
1023 bool city_checked = TRUE; /* This is used to avoid spurious city_exist() calls */
1024 struct worklist *pwl = &pcity->worklist;
1026 if (worklist_is_empty(pwl)) {
1027 /* Nothing in the worklist; bail now. */
1028 return FALSE;
1031 i = 0;
1032 while (!success && i < worklist_length(pwl)) {
1034 if (!city_checked) {
1035 if (!city_exist(saved_id)) {
1036 /* Some script has removed useless city that cannot build
1037 * what it is told to! */
1038 return FALSE;
1040 city_checked = TRUE;
1043 if (worklist_peek_ith(pwl, &target, i)) {
1044 success = can_city_build_now(pcity, &target);
1045 } else {
1046 success = FALSE;
1048 i++;
1050 if (success) {
1051 break; /* while */
1054 switch (target.kind) {
1055 case VUT_UTYPE:
1057 struct unit_type *ptarget = target.value.utype;
1058 struct unit_type *pupdate = unit_upgrades_to(pcity, ptarget);
1060 /* Maybe we can just upgrade the target to what the city /can/ build. */
1061 if (U_NOT_OBSOLETED == pupdate) {
1062 /* Nope, we're stuck. Skip this item from the worklist. */
1063 if (ptarget->need_government != NULL
1064 && ptarget->need_government != government_of_player(pplayer)) {
1065 notify_player(pplayer, city_tile(pcity),
1066 E_CITY_CANTBUILD, ftc_server,
1067 _("%s can't build %s from the worklist; "
1068 "it needs %s government. Postponing..."),
1069 city_link(pcity), utype_name_translation(ptarget),
1070 government_name_translation(ptarget->need_government));
1071 script_server_signal_emit("unit_cant_be_built", 3,
1072 API_TYPE_BUILDING_TYPE, ptarget,
1073 API_TYPE_CITY, pcity,
1074 API_TYPE_STRING, "need_government");
1075 } else if (ptarget->need_improvement != NULL
1076 && !city_has_building(pcity, ptarget->need_improvement)) {
1077 notify_player(pplayer, city_tile(pcity),
1078 E_CITY_CANTBUILD, ftc_server,
1079 _("%s can't build %s from the worklist; "
1080 "need to have %s first. Postponing..."),
1081 city_link(pcity), utype_name_translation(ptarget),
1082 city_improvement_name_translation(pcity,
1083 ptarget->need_improvement));
1084 script_server_signal_emit("unit_cant_be_built", 3,
1085 API_TYPE_UNIT_TYPE, ptarget,
1086 API_TYPE_CITY, pcity,
1087 API_TYPE_STRING, "need_building");
1088 } else if (ptarget->require_advance != NULL
1089 && TECH_KNOWN != research_invention_state
1090 (research_get(pplayer),
1091 advance_number(ptarget->require_advance))) {
1092 notify_player(pplayer, city_tile(pcity),
1093 E_CITY_CANTBUILD, ftc_server,
1094 _("%s can't build %s from the worklist; "
1095 "tech %s not yet available. Postponing..."),
1096 city_link(pcity), utype_name_translation(ptarget),
1097 advance_name_translation(ptarget->require_advance));
1098 script_server_signal_emit("unit_cant_be_built", 3,
1099 API_TYPE_UNIT_TYPE, ptarget,
1100 API_TYPE_CITY, pcity,
1101 API_TYPE_STRING, "need_tech");
1102 } else {
1103 /* This shouldn't happen, but in case it does... */
1104 notify_player(pplayer, city_tile(pcity),
1105 E_CITY_CANTBUILD, ftc_server,
1106 _("%s can't build %s from the worklist; "
1107 "reason unknown! Postponing..."),
1108 city_link(pcity), utype_name_translation(ptarget));
1110 city_checked = FALSE;
1111 break;
1113 success = can_city_build_unit_later(pcity, pupdate);
1114 if (!success) {
1115 /* If the city can never build this unit or its descendants,
1116 * drop it. */
1117 notify_player(pplayer, city_tile(pcity),
1118 E_CITY_CANTBUILD, ftc_server,
1119 _("%s can't build %s from the worklist. Purging..."),
1120 city_link(pcity),
1121 /* Yes, warn about the targets that's actually
1122 in the worklist, not its obsolete-closure
1123 pupdate. */
1124 utype_name_translation(ptarget));
1125 script_server_signal_emit("unit_cant_be_built", 3,
1126 API_TYPE_UNIT_TYPE, ptarget,
1127 API_TYPE_CITY, pcity,
1128 API_TYPE_STRING, "never");
1129 if (city_exist(saved_id)) {
1130 city_checked = TRUE;
1131 /* Purge this worklist item. */
1132 i--;
1133 worklist_remove(pwl, i);
1134 } else {
1135 city_checked = FALSE;
1137 } else {
1138 /* Yep, we can go after pupdate instead. Joy! */
1139 notify_player(pplayer, city_tile(pcity), E_WORKLIST, ftc_server,
1140 _("Production of %s is upgraded to %s in %s."),
1141 utype_name_translation(ptarget),
1142 utype_name_translation(pupdate),
1143 city_link(pcity));
1144 target.value.utype = pupdate;
1146 break;
1148 case VUT_IMPROVEMENT:
1150 struct impr_type *ptarget = target.value.building;
1151 struct impr_type *pupdate = building_upgrades_to(pcity, ptarget);
1153 /* If the city can never build this improvement, drop it. */
1154 success = can_city_build_improvement_later(pcity, pupdate);
1156 /* Maybe this improvement has been obsoleted by something that
1157 we can build. */
1158 if (success && pupdate == ptarget) {
1159 bool known = FALSE;
1161 /* Nope, no use. *sigh* */
1162 requirement_vector_iterate(&ptarget->reqs, preq) {
1163 if (!is_req_active(pplayer, NULL, pcity, NULL, NULL, NULL, NULL,
1164 NULL, NULL, preq, RPT_POSSIBLE)) {
1165 known = TRUE;
1166 switch (preq->source.kind) {
1167 case VUT_ADVANCE:
1168 if (preq->present) {
1169 notify_player(pplayer, city_tile(pcity),
1170 E_CITY_CANTBUILD, ftc_server,
1171 _("%s can't build %s from the worklist; "
1172 "tech %s not yet available. Postponing..."),
1173 city_link(pcity),
1174 city_improvement_name_translation(pcity, ptarget),
1175 advance_name_translation
1176 (preq->source.value.advance));
1177 script_server_signal_emit("building_cant_be_built", 3,
1178 API_TYPE_BUILDING_TYPE, ptarget,
1179 API_TYPE_CITY, pcity,
1180 API_TYPE_STRING, "need_tech");
1181 } else {
1182 /* While techs can be unlearned, this isn't useful feedback */
1183 success = FALSE;
1185 break;
1186 case VUT_TECHFLAG:
1187 if (preq->present) {
1188 notify_player(pplayer, city_tile(pcity),
1189 E_CITY_CANTBUILD, ftc_server,
1190 _("%s can't build %s from the worklist; "
1191 "no tech with flag \"%s\" yet available. "
1192 "Postponing..."),
1193 city_link(pcity),
1194 city_improvement_name_translation(pcity, ptarget),
1195 tech_flag_id_name(preq->source.value.techflag));
1196 script_server_signal_emit("building_cant_be_built", 3,
1197 API_TYPE_BUILDING_TYPE, ptarget,
1198 API_TYPE_CITY, pcity,
1199 API_TYPE_STRING, "need_techflag");
1200 } else {
1201 /* While techs can be unlearned, this isn't useful feedback */
1202 success = FALSE;
1204 break;
1205 case VUT_IMPROVEMENT:
1206 if (preq->present) {
1207 notify_player(pplayer, city_tile(pcity),
1208 E_CITY_CANTBUILD, ftc_server,
1209 _("%s can't build %s from the worklist; "
1210 "need to have %s first. Postponing..."),
1211 city_link(pcity),
1212 city_improvement_name_translation(pcity, ptarget),
1213 city_improvement_name_translation(pcity,
1214 preq->source.value.building));
1215 script_server_signal_emit("building_cant_be_built", 3,
1216 API_TYPE_BUILDING_TYPE, ptarget,
1217 API_TYPE_CITY, pcity,
1218 API_TYPE_STRING, "need_building");
1219 } else {
1220 notify_player(pplayer, city_tile(pcity),
1221 E_CITY_CANTBUILD, ftc_server,
1222 _("%s can't build %s from the worklist; "
1223 "need to not have %s. Postponing..."),
1224 city_link(pcity),
1225 city_improvement_name_translation(pcity, ptarget),
1226 city_improvement_name_translation(pcity,
1227 preq->source.value.building));
1228 script_server_signal_emit("building_cant_be_built", 3,
1229 API_TYPE_BUILDING_TYPE, ptarget,
1230 API_TYPE_CITY, pcity,
1231 API_TYPE_STRING, "have_building");
1233 break;
1234 case VUT_GOVERNMENT:
1235 if (preq->present) {
1236 notify_player(pplayer, city_tile(pcity),
1237 E_CITY_CANTBUILD, ftc_server,
1238 _("%s can't build %s from the worklist; "
1239 "it needs %s government. Postponing..."),
1240 city_link(pcity),
1241 city_improvement_name_translation(pcity, ptarget),
1242 government_name_translation(preq->source.value.govern));
1243 script_server_signal_emit("building_cant_be_built", 3,
1244 API_TYPE_BUILDING_TYPE, ptarget,
1245 API_TYPE_CITY, pcity,
1246 API_TYPE_STRING, "need_government");
1247 } else {
1248 notify_player(pplayer, city_tile(pcity),
1249 E_CITY_CANTBUILD, ftc_server,
1250 _("%s can't build %s from the worklist; "
1251 "it cannot have %s government. Postponing..."),
1252 city_link(pcity),
1253 city_improvement_name_translation(pcity, ptarget),
1254 government_name_translation(preq->source.value.govern));
1255 script_server_signal_emit("building_cant_be_built", 3,
1256 API_TYPE_BUILDING_TYPE, ptarget,
1257 API_TYPE_CITY, pcity,
1258 API_TYPE_STRING, "have_government");
1260 break;
1261 case VUT_ACHIEVEMENT:
1262 if (preq->present) {
1263 notify_player(pplayer, city_tile(pcity),
1264 E_CITY_CANTBUILD, ftc_server,
1265 _("%s can't build %s from the worklist; "
1266 "it needs \"%s\" achievement. Postponing..."),
1267 city_link(pcity),
1268 city_improvement_name_translation(pcity, ptarget),
1269 achievement_name_translation(preq->source.value.achievement));
1270 script_server_signal_emit("building_cant_be_built", 3,
1271 API_TYPE_BUILDING_TYPE, ptarget,
1272 API_TYPE_CITY, pcity,
1273 API_TYPE_STRING, "need_achievement");
1274 } else {
1275 /* Can't unachieve things. */
1276 success = FALSE;
1278 break;
1279 case VUT_EXTRA:
1280 if (preq->present) {
1281 notify_player(pplayer, city_tile(pcity),
1282 E_CITY_CANTBUILD, ftc_server,
1283 Q_("?extra:%s can't build %s from the worklist; "
1284 "%s is required. Postponing..."),
1285 city_link(pcity),
1286 city_improvement_name_translation(pcity, ptarget),
1287 extra_name_translation(preq->source.value.extra));
1288 script_server_signal_emit("building_cant_be_built", 3,
1289 API_TYPE_BUILDING_TYPE, ptarget,
1290 API_TYPE_CITY, pcity,
1291 API_TYPE_STRING, "need_extra");
1292 } else {
1293 notify_player(pplayer, city_tile(pcity),
1294 E_CITY_CANTBUILD, ftc_server,
1295 Q_("?extra:%s can't build %s from the worklist; "
1296 "%s is prohibited. Postponing..."),
1297 city_link(pcity),
1298 city_improvement_name_translation(pcity, ptarget),
1299 extra_name_translation(preq->source.value.extra));
1300 script_server_signal_emit("building_cant_be_built", 3,
1301 API_TYPE_BUILDING_TYPE, ptarget,
1302 API_TYPE_CITY, pcity,
1303 API_TYPE_STRING, "have_extra");
1305 break;
1306 case VUT_TERRAIN:
1307 if (preq->present) {
1308 notify_player(pplayer, city_tile(pcity),
1309 E_CITY_CANTBUILD, ftc_server,
1310 Q_("?terrain:%s can't build %s from the worklist; "
1311 "%s terrain is required. Postponing..."),
1312 city_link(pcity),
1313 city_improvement_name_translation(pcity, ptarget),
1314 terrain_name_translation(preq->source.value.terrain));
1315 script_server_signal_emit("building_cant_be_built", 3,
1316 API_TYPE_BUILDING_TYPE, ptarget,
1317 API_TYPE_CITY, pcity,
1318 API_TYPE_STRING, "need_terrain");
1319 } else {
1320 notify_player(pplayer, city_tile(pcity),
1321 E_CITY_CANTBUILD, ftc_server,
1322 Q_("?terrain:%s can't build %s from the worklist; "
1323 "%s terrain is prohibited. Postponing..."),
1324 city_link(pcity),
1325 city_improvement_name_translation(pcity, ptarget),
1326 terrain_name_translation(preq->source.value.terrain));
1327 script_server_signal_emit("building_cant_be_built", 3,
1328 API_TYPE_BUILDING_TYPE, ptarget,
1329 API_TYPE_CITY, pcity,
1330 API_TYPE_STRING, "have_terrain");
1332 break;
1333 case VUT_RESOURCE:
1334 if (preq->present) {
1335 notify_player(pplayer, city_tile(pcity),
1336 E_CITY_CANTBUILD, ftc_server,
1337 Q_("?resource:%s can't build %s from the worklist; "
1338 "%s is required. Postponing..."),
1339 city_link(pcity),
1340 city_improvement_name_translation(pcity, ptarget),
1341 resource_name_translation(preq->source.value.resource));
1342 script_server_signal_emit("building_cant_be_built", 3,
1343 API_TYPE_BUILDING_TYPE, ptarget,
1344 API_TYPE_CITY, pcity,
1345 API_TYPE_STRING, "need_resource");
1346 } else {
1347 /* FIXME: Yes, it's possible to destroy a resource, but the
1348 * player probably wanted us to have purged, rather than
1349 * postponed. Purging should be separate from impossible. */
1350 notify_player(pplayer, city_tile(pcity),
1351 E_CITY_CANTBUILD, ftc_server,
1352 Q_("?resource:%s can't build %s from the worklist; "
1353 "%s is prohibited. Postponing..."),
1354 city_link(pcity),
1355 city_improvement_name_translation(pcity, ptarget),
1356 resource_name_translation(preq->source.value.resource));
1357 script_server_signal_emit("building_cant_be_built", 3,
1358 API_TYPE_BUILDING_TYPE, ptarget,
1359 API_TYPE_CITY, pcity,
1360 API_TYPE_STRING, "have_resource");
1362 break;
1363 case VUT_NATION:
1364 /* Nation can be required at Alliance range, which may change. */
1365 if (preq->present) {
1366 notify_player(pplayer, city_tile(pcity),
1367 E_CITY_CANTBUILD, ftc_server,
1368 /* TRANS: "%s nation" is adjective */
1369 Q_("?nation:%s can't build %s from the worklist; "
1370 "%s nation is required. Postponing..."),
1371 city_link(pcity),
1372 city_improvement_name_translation(pcity, ptarget),
1373 nation_adjective_translation(preq->source.value.nation));
1374 script_server_signal_emit("building_cant_be_built", 3,
1375 API_TYPE_BUILDING_TYPE, ptarget,
1376 API_TYPE_CITY, pcity,
1377 API_TYPE_STRING, "need_nation");
1378 } else {
1379 notify_player(pplayer, city_tile(pcity),
1380 E_CITY_CANTBUILD, ftc_server,
1381 Q_("?nation:%s can't build %s from the worklist; "
1382 "%s nation is prohibited. Postponing..."),
1383 city_link(pcity),
1384 city_improvement_name_translation(pcity, ptarget),
1385 nation_adjective_translation(preq->source.value.nation));
1386 script_server_signal_emit("building_cant_be_built", 3,
1387 API_TYPE_BUILDING_TYPE, ptarget,
1388 API_TYPE_CITY, pcity,
1389 API_TYPE_STRING, "have_nation");
1391 break;
1392 case VUT_NATIONGROUP:
1393 /* Nation group can be required at Alliance range, which may
1394 * change. */
1395 if (preq->present) {
1396 notify_player(pplayer, city_tile(pcity),
1397 E_CITY_CANTBUILD, ftc_server,
1398 /* TRANS: "%s nation" is adjective */
1399 Q_("?ngroup:%s can't build %s from the worklist; "
1400 "%s nation is required. Postponing..."),
1401 city_link(pcity),
1402 city_improvement_name_translation(pcity, ptarget),
1403 nation_group_name_translation(preq->source.value.nationgroup));
1404 script_server_signal_emit("building_cant_be_built", 3,
1405 API_TYPE_BUILDING_TYPE, ptarget,
1406 API_TYPE_CITY, pcity,
1407 API_TYPE_STRING, "need_nationgroup");
1408 } else {
1409 notify_player(pplayer, city_tile(pcity),
1410 E_CITY_CANTBUILD, ftc_server,
1411 Q_("?ngroup:%s can't build %s from the worklist; "
1412 "%s nation is prohibited. Postponing..."),
1413 city_link(pcity),
1414 city_improvement_name_translation(pcity, ptarget),
1415 nation_group_name_translation(preq->source.value.nationgroup));
1416 script_server_signal_emit("building_cant_be_built", 3,
1417 API_TYPE_BUILDING_TYPE, ptarget,
1418 API_TYPE_CITY, pcity,
1419 API_TYPE_STRING, "have_nationgroup");
1421 break;
1422 case VUT_STYLE:
1423 /* FIXME: City styles sometimes change over time, but it isn't
1424 * entirely under player control. Probably better to purge
1425 * with useful explanation. */
1426 if (preq->present) {
1427 notify_player(pplayer, city_tile(pcity),
1428 E_CITY_CANTBUILD, ftc_server,
1429 _("%s can't build %s from the worklist; "
1430 "only %s style cities may build this. Postponing..."),
1431 city_link(pcity),
1432 city_improvement_name_translation(pcity, ptarget),
1433 style_name_translation(preq->source.value.style));
1434 script_server_signal_emit("building_cant_be_built", 3,
1435 API_TYPE_BUILDING_TYPE, ptarget,
1436 API_TYPE_CITY, pcity,
1437 API_TYPE_STRING, "need_style");
1438 } else {
1439 notify_player(pplayer, city_tile(pcity),
1440 E_CITY_CANTBUILD, ftc_server,
1441 _("%s can't build %s from the worklist; "
1442 "%s style cities may not build this. Postponing..."),
1443 city_link(pcity),
1444 city_improvement_name_translation(pcity, ptarget),
1445 style_name_translation(preq->source.value.style));
1446 script_server_signal_emit("building_cant_be_built", 3,
1447 API_TYPE_BUILDING_TYPE, ptarget,
1448 API_TYPE_CITY, pcity,
1449 API_TYPE_STRING, "have_style");
1451 break;
1452 case VUT_NATIONALITY:
1453 /* FIXME: Changing citizen nationality is hard: purging might be
1454 * more useful in this case. */
1455 if (preq->present) {
1456 notify_player(pplayer, city_tile(pcity),
1457 E_CITY_CANTBUILD, ftc_server,
1458 /* TRANS: Latter %s is citizen nationality */
1459 _("%s can't build %s from the worklist; "
1460 "only city with %s may build this. Postponing..."),
1461 city_link(pcity),
1462 city_improvement_name_translation(pcity, ptarget),
1463 nation_plural_translation(preq->source.value.nationality));
1464 script_server_signal_emit("building_cant_be_built", 3,
1465 API_TYPE_BUILDING_TYPE, ptarget,
1466 API_TYPE_CITY, pcity,
1467 API_TYPE_STRING, "need_nationality");
1468 } else {
1469 notify_player(pplayer, city_tile(pcity),
1470 E_CITY_CANTBUILD, ftc_server,
1471 /* TRANS: Latter %s is citizen nationality */
1472 _("%s can't build %s from the worklist; "
1473 "only city without %s may build this. Postponing..."),
1474 city_link(pcity),
1475 city_improvement_name_translation(pcity, ptarget),
1476 nation_plural_translation(preq->source.value.nationality));
1477 script_server_signal_emit("building_cant_be_built", 3,
1478 API_TYPE_BUILDING_TYPE, ptarget,
1479 API_TYPE_CITY, pcity,
1480 API_TYPE_STRING, "have_nationality");
1482 break;
1483 case VUT_DIPLREL:
1484 if (preq->present) {
1485 notify_player(pplayer, city_tile(pcity),
1486 E_CITY_CANTBUILD, ftc_server,
1487 /* TRANS: '%s' is a wide range of relationships;
1488 * e.g., 'Peace', 'Never met', 'Is foreign',
1489 * 'Hosts embassy', 'Provided Casus Belli' */
1490 _("%s can't build %s from the worklist; "
1491 "the relationship '%s' is required."
1492 " Postponing..."),
1493 city_link(pcity),
1494 city_improvement_name_translation(pcity,
1495 ptarget),
1496 diplrel_name_translation(
1497 preq->source.value.diplrel));
1498 script_server_signal_emit("building_cant_be_built", 3,
1499 API_TYPE_BUILDING_TYPE, ptarget,
1500 API_TYPE_CITY, pcity,
1501 API_TYPE_STRING, "need_diplrel");
1502 } else {
1503 notify_player(pplayer, city_tile(pcity),
1504 E_CITY_CANTBUILD, ftc_server,
1505 _("%s can't build %s from the worklist; "
1506 "the relationship '%s' is prohibited."
1507 " Postponing..."),
1508 city_link(pcity),
1509 city_improvement_name_translation(pcity,
1510 ptarget),
1511 diplrel_name_translation(
1512 preq->source.value.diplrel));
1513 script_server_signal_emit("building_cant_be_built", 3,
1514 API_TYPE_BUILDING_TYPE, ptarget,
1515 API_TYPE_CITY, pcity,
1516 API_TYPE_STRING, "have_diplrel");
1518 break;
1519 case VUT_MINSIZE:
1520 if (preq->present) {
1521 notify_player(pplayer, city_tile(pcity),
1522 E_CITY_CANTBUILD, ftc_server,
1523 _("%s can't build %s from the worklist; "
1524 "city must be of size %d or larger. "
1525 "Postponing..."),
1526 city_link(pcity),
1527 city_improvement_name_translation(pcity, ptarget),
1528 preq->source.value.minsize);
1529 script_server_signal_emit("building_cant_be_built", 3,
1530 API_TYPE_BUILDING_TYPE, ptarget,
1531 API_TYPE_CITY, pcity,
1532 API_TYPE_STRING, "need_minsize");
1533 } else {
1534 notify_player(pplayer, city_tile(pcity),
1535 E_CITY_CANTBUILD, ftc_server,
1536 _("%s can't build %s from the worklist; "
1537 "city must be of size %d or smaller."
1538 "Postponing..."),
1539 city_link(pcity),
1540 city_improvement_name_translation(pcity, ptarget),
1541 (preq->source.value.minsize - 1));
1542 script_server_signal_emit("building_cant_be_built", 3,
1543 API_TYPE_BUILDING_TYPE, ptarget,
1544 API_TYPE_CITY, pcity,
1545 API_TYPE_STRING, "need_minsize");
1547 break;
1548 case VUT_MINCULTURE:
1549 if (preq->present) {
1550 notify_player(pplayer, city_tile(pcity),
1551 E_CITY_CANTBUILD, ftc_server,
1552 _("%s can't build %s from the worklist; "
1553 "city must have culture of %d. Postponing..."),
1554 city_link(pcity),
1555 city_improvement_name_translation(pcity, ptarget),
1556 preq->source.value.minculture);
1557 script_server_signal_emit("building_cant_be_built", 3,
1558 API_TYPE_BUILDING_TYPE, ptarget,
1559 API_TYPE_CITY, pcity,
1560 API_TYPE_STRING, "need_minculture");
1561 } else {
1562 /* What has been written may not be unwritten. */
1563 success = FALSE;
1565 break;
1566 case VUT_MAXTILEUNITS:
1567 if (preq->present) {
1568 notify_player(pplayer, city_tile(pcity),
1569 E_CITY_CANTBUILD, ftc_server,
1570 PL_("%s can't build %s from the worklist; "
1571 "more than %d unit on tile."
1572 " Postponing...",
1573 "%s can't build %s from the worklist; "
1574 "more than %d units on tile."
1575 " Postponing...",
1576 preq->source.value.max_tile_units),
1577 city_link(pcity),
1578 city_improvement_name_translation(pcity,
1579 ptarget),
1580 preq->source.value.max_tile_units);
1581 script_server_signal_emit("building_cant_be_built", 3,
1582 API_TYPE_BUILDING_TYPE, ptarget,
1583 API_TYPE_CITY, pcity,
1584 API_TYPE_STRING, "need_tileunits");
1585 } else {
1586 notify_player(pplayer, city_tile(pcity),
1587 E_CITY_CANTBUILD, ftc_server,
1588 PL_("%s can't build %s from the worklist; "
1589 "fewer than %d unit on tile."
1590 " Postponing...",
1591 "%s can't build %s from the worklist; "
1592 "fewer than %d units on tile."
1593 " Postponing...",
1594 preq->source.value.max_tile_units + 1),
1595 city_link(pcity),
1596 city_improvement_name_translation(pcity,
1597 ptarget),
1598 preq->source.value.max_tile_units + 1);
1599 script_server_signal_emit("building_cant_be_built", 3,
1600 API_TYPE_BUILDING_TYPE, ptarget,
1601 API_TYPE_CITY, pcity,
1602 API_TYPE_STRING, "need_tileunits");
1604 break;
1605 case VUT_AI_LEVEL:
1606 /* Can't change AI level. */
1607 success = FALSE;
1608 break;
1609 case VUT_TERRAINCLASS:
1610 if (preq->present) {
1611 notify_player(pplayer, city_tile(pcity),
1612 E_CITY_CANTBUILD, ftc_server,
1613 Q_("?terrainclass:%s can't build %s from the "
1614 "worklist; %s terrain is required."
1615 " Postponing..."),
1616 city_link(pcity),
1617 city_improvement_name_translation(pcity, ptarget),
1618 terrain_class_name_translation(preq->source.value.terrainclass));
1619 script_server_signal_emit("building_cant_be_built", 3,
1620 API_TYPE_BUILDING_TYPE, ptarget,
1621 API_TYPE_CITY, pcity,
1622 API_TYPE_STRING, "need_terrainclass");
1623 } else {
1624 notify_player(pplayer, city_tile(pcity),
1625 E_CITY_CANTBUILD, ftc_server,
1626 Q_("?terrainclass:%s can't build %s from the "
1627 "worklist; %s terrain is prohibited."
1628 " Postponing..."),
1629 city_link(pcity),
1630 city_improvement_name_translation(pcity, ptarget),
1631 terrain_class_name_translation(preq->source.value.terrainclass));
1632 script_server_signal_emit("building_cant_be_built", 3,
1633 API_TYPE_BUILDING_TYPE, ptarget,
1634 API_TYPE_CITY, pcity,
1635 API_TYPE_STRING, "have_terrainclass");
1637 break;
1638 case VUT_TERRFLAG:
1639 if (preq->present) {
1640 notify_player(pplayer, city_tile(pcity),
1641 E_CITY_CANTBUILD, ftc_server,
1642 _("%s can't build %s from the worklist; "
1643 "terrain with \"%s\" flag is required. "
1644 "Postponing..."),
1645 city_link(pcity),
1646 city_improvement_name_translation(pcity, ptarget),
1647 terrain_flag_id_name(preq->source.value.terrainflag));
1648 script_server_signal_emit("building_cant_be_built", 3,
1649 API_TYPE_BUILDING_TYPE, ptarget,
1650 API_TYPE_CITY, pcity,
1651 API_TYPE_STRING, "need_terrainflag");
1652 } else {
1653 notify_player(pplayer, city_tile(pcity),
1654 E_CITY_CANTBUILD, ftc_server,
1655 _("%s can't build %s from the worklist; "
1656 "terrain with \"%s\" flag is prohibited. "
1657 "Postponing..."),
1658 city_link(pcity),
1659 city_improvement_name_translation(pcity, ptarget),
1660 terrain_flag_id_name(preq->source.value.terrainflag));
1661 script_server_signal_emit("building_cant_be_built", 3,
1662 API_TYPE_BUILDING_TYPE, ptarget,
1663 API_TYPE_CITY, pcity,
1664 API_TYPE_STRING, "have_terrainflag");
1666 break;
1667 case VUT_BASEFLAG:
1668 if (preq->present) {
1669 notify_player(pplayer, city_tile(pcity),
1670 E_CITY_CANTBUILD, ftc_server,
1671 _("%s can't build %s from the worklist; "
1672 "base with \"%s\" flag is required. "
1673 "Postponing..."),
1674 city_link(pcity),
1675 city_improvement_name_translation(pcity, ptarget),
1676 base_flag_id_name(preq->source.value.baseflag));
1677 script_server_signal_emit("building_cant_be_built", 3,
1678 API_TYPE_BUILDING_TYPE, ptarget,
1679 API_TYPE_CITY, pcity,
1680 API_TYPE_STRING, "need_baseflag");
1681 } else {
1682 notify_player(pplayer, city_tile(pcity),
1683 E_CITY_CANTBUILD, ftc_server,
1684 _("%s can't build %s from the worklist; "
1685 "base with \"%s\" flag is prohibited. "
1686 "Postponing..."),
1687 city_link(pcity),
1688 city_improvement_name_translation(pcity, ptarget),
1689 base_flag_id_name(preq->source.value.baseflag));
1690 script_server_signal_emit("building_cant_be_built", 3,
1691 API_TYPE_BUILDING_TYPE, ptarget,
1692 API_TYPE_CITY, pcity,
1693 API_TYPE_STRING, "have_baseflag");
1695 break;
1696 case VUT_ROADFLAG:
1697 if (preq->present) {
1698 notify_player(pplayer, city_tile(pcity),
1699 E_CITY_CANTBUILD, ftc_server,
1700 _("%s can't build %s from the worklist; "
1701 "road with \"%s\" flag is required. "
1702 "Postponing..."),
1703 city_link(pcity),
1704 city_improvement_name_translation(pcity, ptarget),
1705 road_flag_id_name(preq->source.value.roadflag));
1706 script_server_signal_emit("building_cant_be_built", 3,
1707 API_TYPE_BUILDING_TYPE, ptarget,
1708 API_TYPE_CITY, pcity,
1709 API_TYPE_STRING, "need_roadflag");
1710 } else {
1711 notify_player(pplayer, city_tile(pcity),
1712 E_CITY_CANTBUILD, ftc_server,
1713 _("%s can't build %s from the worklist; "
1714 "road with \"%s\" flag is prohibited. "
1715 "Postponing..."),
1716 city_link(pcity),
1717 city_improvement_name_translation(pcity, ptarget),
1718 road_flag_id_name(preq->source.value.roadflag));
1719 script_server_signal_emit("building_cant_be_built", 3,
1720 API_TYPE_BUILDING_TYPE, ptarget,
1721 API_TYPE_CITY, pcity,
1722 API_TYPE_STRING, "have_roadflag");
1724 break;
1725 case VUT_EXTRAFLAG:
1726 if (preq->present) {
1727 notify_player(pplayer, city_tile(pcity),
1728 E_CITY_CANTBUILD, ftc_server,
1729 _("%s can't build %s from the worklist; "
1730 "extra with \"%s\" flag is required. "
1731 "Postponing..."),
1732 city_link(pcity),
1733 city_improvement_name_translation(pcity, ptarget),
1734 extra_flag_id_translated_name(preq->source.value.extraflag));
1735 script_server_signal_emit("building_cant_be_built", 3,
1736 API_TYPE_BUILDING_TYPE, ptarget,
1737 API_TYPE_CITY, pcity,
1738 API_TYPE_STRING, "need_extraflag");
1739 } else {
1740 notify_player(pplayer, city_tile(pcity),
1741 E_CITY_CANTBUILD, ftc_server,
1742 _("%s can't build %s from the worklist; "
1743 "extra with \"%s\" flag is prohibited. "
1744 "Postponing..."),
1745 city_link(pcity),
1746 city_improvement_name_translation(pcity, ptarget),
1747 extra_flag_id_translated_name(preq->source.value.extraflag));
1748 script_server_signal_emit("building_cant_be_built", 3,
1749 API_TYPE_BUILDING_TYPE, ptarget,
1750 API_TYPE_CITY, pcity,
1751 API_TYPE_STRING, "have_extraflag");
1753 break;
1754 case VUT_UTYPE:
1755 case VUT_UTFLAG:
1756 case VUT_UCLASS:
1757 case VUT_UCFLAG:
1758 case VUT_MINVETERAN:
1759 case VUT_UNITSTATE:
1760 case VUT_MINMOVES:
1761 case VUT_MINHP:
1762 case VUT_OTYPE:
1763 case VUT_SPECIALIST:
1764 case VUT_TERRAINALTER: /* XXX could do this in principle */
1765 case VUT_CITYTILE:
1766 /* Will only happen with a bogus ruleset. */
1767 log_error("worklist_change_build_target() has bogus preq");
1768 break;
1769 case VUT_MINYEAR:
1770 if (preq->present) {
1771 notify_player(pplayer, city_tile(pcity),
1772 E_CITY_CANTBUILD, ftc_server,
1773 /* TRANS: last %s is a date */
1774 _("%s can't build %s from the worklist; "
1775 "only available from %s. Postponing..."),
1776 city_link(pcity),
1777 city_improvement_name_translation(pcity, ptarget),
1778 textyear(preq->source.value.minyear));
1779 script_server_signal_emit("building_cant_be_built", 3,
1780 API_TYPE_BUILDING_TYPE, ptarget,
1781 API_TYPE_CITY, pcity,
1782 API_TYPE_STRING, "need_minyear");
1783 } else {
1784 /* Can't go back in time. */
1785 success = FALSE;
1787 break;
1788 case VUT_TOPO:
1789 if (preq->present) {
1790 notify_player(pplayer, city_tile(pcity),
1791 E_CITY_CANTBUILD, ftc_server,
1792 _("%s can't build %s from the workist; "
1793 "only available in worlds with %s map."),
1794 city_link(pcity),
1795 city_improvement_name_translation(pcity, ptarget),
1796 _(topo_flag_name(preq->source.value.topo_property)));
1797 script_server_signal_emit("building_cant_be_built", 3,
1798 API_TYPE_BUILDING_TYPE, ptarget,
1799 API_TYPE_CITY, pcity,
1800 API_TYPE_STRING, "need_topo");
1802 success = FALSE;
1803 break;
1804 case VUT_AGE:
1805 if (preq->present) {
1806 notify_player(pplayer, city_tile(pcity),
1807 E_CITY_CANTBUILD, ftc_server,
1808 _("%s can't build %s from the worklist; "
1809 "only available once %d turns old. Postponing..."),
1810 city_link(pcity),
1811 city_improvement_name_translation(pcity, ptarget),
1812 preq->source.value.age);
1813 script_server_signal_emit("building_cant_be_built", 3,
1814 API_TYPE_BUILDING_TYPE, ptarget,
1815 API_TYPE_CITY, pcity,
1816 API_TYPE_STRING, "need_age");
1817 } else {
1818 /* Can't go back in time. */
1819 success = FALSE;
1821 break;
1822 case VUT_NONE:
1823 case VUT_COUNT:
1824 fc_assert_ret_val_msg(FALSE, TRUE,
1825 "worklist_change_build_target() "
1826 "called with invalid preq");
1827 break;
1828 /* No default handling here, as we want compiler warning
1829 * if new requirement type is added to enum and it's not handled
1830 * here. */
1832 break;
1835 /* Almost all cases emit signal in the end, so city check needed. */
1836 if (!city_exist(saved_id)) {
1837 /* Some script has removed city */
1838 return FALSE;
1840 city_checked = TRUE;
1842 } requirement_vector_iterate_end;
1844 if (!known) {
1845 /* This shouldn't happen...
1846 FIXME: make can_city_build_improvement_now() return a reason enum. */
1847 notify_player(pplayer, city_tile(pcity),
1848 E_CITY_CANTBUILD, ftc_server,
1849 _("%s can't build %s from the worklist; "
1850 "reason unknown! Postponing..."),
1851 city_link(pcity),
1852 city_improvement_name_translation(pcity, ptarget));
1854 } else if (success) {
1855 /* Hey, we can upgrade the improvement! */
1856 notify_player(pplayer, city_tile(pcity), E_WORKLIST, ftc_server,
1857 _("Production of %s is upgraded to %s in %s."),
1858 city_improvement_name_translation(pcity, ptarget),
1859 city_improvement_name_translation(pcity, pupdate),
1860 city_link(pcity));
1861 target.value.building = pupdate;
1862 success = TRUE;
1865 if (!success) {
1866 /* Never in a million years. */
1867 notify_player(pplayer, city_tile(pcity),
1868 E_CITY_CANTBUILD, ftc_server,
1869 _("%s can't build %s from the worklist. Purging..."),
1870 city_link(pcity),
1871 city_improvement_name_translation(pcity, ptarget));
1872 script_server_signal_emit("building_cant_be_built", 3,
1873 API_TYPE_BUILDING_TYPE, ptarget,
1874 API_TYPE_CITY, pcity,
1875 API_TYPE_STRING, "never");
1876 if (city_exist(saved_id)) {
1877 city_checked = TRUE;
1878 /* Purge this worklist item. */
1879 i--;
1880 worklist_remove(pwl, i);
1881 } else {
1882 city_checked = FALSE;
1885 break;
1887 default:
1888 /* skip useless target */
1889 log_error("worklist_change_build_target() has unrecognized "
1890 "target kind (%d)", target.kind);
1891 break;
1893 } /* while */
1895 if (success) {
1896 /* All okay. Switch targets. */
1897 change_build_target(pplayer, pcity, &target, E_WORKLIST);
1899 /* i is the index immediately _after_ the item we're changing to.
1900 Remove the (i-1)th item from the worklist. */
1901 worklist_remove(pwl, i - 1);
1904 if (worklist_is_empty(pwl)) {
1905 /* There *was* something in the worklist, but it's empty now. Bug the
1906 player about it. */
1907 notify_player(pplayer, city_tile(pcity), E_WORKLIST, ftc_server,
1908 /* TRANS: The <city> worklist .... */
1909 _("The %s worklist is now empty."),
1910 city_link(pcity));
1913 return success;
1916 /**************************************************************************
1917 Assuming we just finished building something, find something new to
1918 build. The policy is: use the worklist if we can; if not, try not
1919 changing; if we must change, get desparate and use the AI advisor.
1920 **************************************************************************/
1921 void choose_build_target(struct player *pplayer, struct city *pcity)
1923 /* Pick the next thing off the worklist. */
1924 if (worklist_change_build_target(pplayer, pcity)) {
1925 return;
1928 /* Try building the same thing again. Repeat building doesn't require a
1929 * call to change_build_target, so just return. */
1930 switch (pcity->production.kind) {
1931 case VUT_UTYPE:
1932 /* We can build a unit again unless it's unique or we have lost the tech. */
1933 if (!utype_has_flag(pcity->production.value.utype, UTYF_UNIQUE)
1934 && can_city_build_unit_now(pcity, pcity->production.value.utype)) {
1935 log_debug("%s repeats building %s", city_name_get(pcity),
1936 utype_rule_name(pcity->production.value.utype));
1937 return;
1939 break;
1940 case VUT_IMPROVEMENT:
1941 if (can_city_build_improvement_now(pcity, pcity->production.value.building)) {
1942 /* We can build space and coinage again, and possibly others. */
1943 log_debug("%s repeats building %s", city_name_get(pcity),
1944 improvement_rule_name(pcity->production.value.building));
1945 return;
1947 break;
1948 default:
1949 /* fallthru */
1950 break;
1953 /* Find *something* to do! */
1954 log_debug("Trying advisor_choose_build.");
1955 advisor_choose_build(pplayer, pcity);
1956 log_debug("Advisor_choose_build didn't kill us.");
1959 /**************************************************************************
1960 Follow the list of replacement buildings until we hit something that
1961 we can build. Returns NULL if we can't upgrade at all (including if the
1962 original building is unbuildable).
1963 **************************************************************************/
1964 static struct impr_type *building_upgrades_to(struct city *pcity,
1965 struct impr_type *pimprove)
1967 struct impr_type *check = pimprove;
1968 struct impr_type *best_upgrade = NULL;
1970 if (!can_city_build_improvement_direct(pcity, check)) {
1971 return NULL;
1973 while (valid_improvement(check = improvement_replacement(check))) {
1974 if (can_city_build_improvement_direct(pcity, check)) {
1975 best_upgrade = check;
1979 return best_upgrade;
1982 /**************************************************************************
1983 Try to upgrade production in pcity.
1984 **************************************************************************/
1985 static void upgrade_building_prod(struct city *pcity)
1987 struct impr_type *producing = pcity->production.value.building;
1988 struct impr_type *upgrading = building_upgrades_to(pcity, producing);
1990 if (upgrading && can_city_build_improvement_now(pcity, upgrading)) {
1991 notify_player(city_owner(pcity), city_tile(pcity),
1992 E_UNIT_UPGRADED, ftc_server,
1993 _("Production of %s is upgraded to %s in %s."),
1994 improvement_name_translation(producing),
1995 improvement_name_translation(upgrading),
1996 city_link(pcity));
1997 pcity->production.kind = VUT_IMPROVEMENT;
1998 pcity->production.value.building = upgrading;
2002 /**************************************************************************
2003 Follow the list of obsoleted_by units until we hit something that
2004 we can build. Return NULL when we can't upgrade at all. NB: returning
2005 something doesn't guarantee that pcity really _can_ build it; just that
2006 pcity can't build whatever _obsoletes_ it.
2008 FIXME: this function is a duplicate of can_upgrade_unittype.
2009 **************************************************************************/
2010 static struct unit_type *unit_upgrades_to(struct city *pcity,
2011 struct unit_type *punittype)
2013 struct unit_type *check = punittype;
2014 struct unit_type *best_upgrade = U_NOT_OBSOLETED;
2016 if (!can_city_build_unit_direct(pcity, punittype)) {
2017 return U_NOT_OBSOLETED;
2019 while ((check = check->obsoleted_by) != U_NOT_OBSOLETED) {
2020 if (can_city_build_unit_direct(pcity, check)) {
2021 best_upgrade = check;
2025 return best_upgrade;
2028 /**************************************************************************
2029 Try to upgrade production in pcity.
2030 **************************************************************************/
2031 static void upgrade_unit_prod(struct city *pcity)
2033 struct unit_type *producing = pcity->production.value.utype;
2034 struct unit_type *upgrading = unit_upgrades_to(pcity, producing);
2036 if (upgrading && can_city_build_unit_direct(pcity, upgrading)) {
2037 notify_player(city_owner(pcity), city_tile(pcity),
2038 E_UNIT_UPGRADED, ftc_server,
2039 _("Production of %s is upgraded to %s in %s."),
2040 utype_name_translation(producing),
2041 utype_name_translation(upgrading),
2042 city_link(pcity));
2043 pcity->production.value.utype = upgrading;
2047 /**************************************************************************
2048 Disband units if we don't have enough shields to support them. Returns
2049 FALSE if the _city_ is disbanded as a result.
2050 **************************************************************************/
2051 static bool city_distribute_surplus_shields(struct player *pplayer,
2052 struct city *pcity)
2054 if (pcity->surplus[O_SHIELD] < 0) {
2055 unit_list_iterate_safe(pcity->units_supported, punit) {
2056 if (utype_upkeep_cost(unit_type_get(punit), pplayer, O_SHIELD) > 0
2057 && pcity->surplus[O_SHIELD] < 0
2058 && !unit_has_type_flag(punit, UTYF_UNDISBANDABLE)) {
2059 notify_player(pplayer, city_tile(pcity),
2060 E_UNIT_LOST_MISC, ftc_server,
2061 _("%s can't upkeep %s, unit disbanded."),
2062 city_link(pcity), unit_link(punit));
2063 handle_unit_disband(pplayer, punit->id);
2064 /* pcity->surplus[O_SHIELD] is automatically updated. */
2066 } unit_list_iterate_safe_end;
2069 if (pcity->surplus[O_SHIELD] < 0) {
2070 /* Special case: UTYF_UNDISBANDABLE. This nasty unit won't go so easily.
2071 * It'd rather make the citizens pay in blood for their failure to upkeep
2072 * it! If we make it here all normal units are already disbanded, so only
2073 * undisbandable ones remain. */
2074 unit_list_iterate_safe(pcity->units_supported, punit) {
2075 int upkeep = utype_upkeep_cost(unit_type_get(punit), pplayer, O_SHIELD);
2077 if (upkeep > 0 && pcity->surplus[O_SHIELD] < 0) {
2078 fc_assert_action(unit_has_type_flag(punit, UTYF_UNDISBANDABLE),
2079 continue);
2080 notify_player(pplayer, city_tile(pcity),
2081 E_UNIT_LOST_MISC, ftc_server,
2082 _("Citizens in %s perish for their failure to "
2083 "upkeep %s!"),
2084 city_link(pcity), unit_link(punit));
2085 if (!city_reduce_size(pcity, 1, NULL, "upkeep_failure")) {
2086 return FALSE;
2089 /* No upkeep for the unit this turn. */
2090 pcity->surplus[O_SHIELD] += upkeep;
2092 } unit_list_iterate_safe_end;
2095 /* Now we confirm changes made last turn. */
2096 pcity->shield_stock += pcity->surplus[O_SHIELD];
2097 pcity->before_change_shields = pcity->shield_stock;
2098 pcity->last_turns_shield_surplus = pcity->surplus[O_SHIELD];
2100 return TRUE;
2103 /**************************************************************************
2104 Returns FALSE when the city is removed, TRUE otherwise.
2105 **************************************************************************/
2106 static bool city_build_building(struct player *pplayer, struct city *pcity)
2108 bool space_part;
2109 int mod;
2110 struct impr_type *pimprove = pcity->production.value.building;
2111 int saved_id = pcity->id;
2113 if (city_production_has_flag(pcity, IF_GOLD)) {
2114 fc_assert(pcity->surplus[O_SHIELD] >= 0);
2115 /* pcity->before_change_shields already contains the surplus from
2116 * this turn. */
2117 pplayer->economic.gold += pcity->before_change_shields;
2118 pcity->before_change_shields = 0;
2119 pcity->shield_stock = 0;
2120 choose_build_target(pplayer, pcity);
2121 return TRUE;
2123 upgrade_building_prod(pcity);
2125 if (!can_city_build_improvement_now(pcity, pimprove)) {
2126 notify_player(pplayer, city_tile(pcity), E_CITY_CANTBUILD, ftc_server,
2127 _("%s is building %s, which is no longer available."),
2128 city_link(pcity),
2129 city_improvement_name_translation(pcity, pimprove));
2130 script_server_signal_emit("building_cant_be_built", 3,
2131 API_TYPE_BUILDING_TYPE, pimprove,
2132 API_TYPE_CITY, pcity,
2133 API_TYPE_STRING, "unavailable");
2134 return TRUE;
2136 if (pcity->shield_stock >= impr_build_shield_cost(pimprove)) {
2137 if (is_small_wonder(pimprove)) {
2138 city_list_iterate(pplayer->cities, wcity) {
2139 if (city_has_building(wcity, pimprove)) {
2140 city_remove_improvement(wcity, pimprove);
2141 break;
2143 } city_list_iterate_end;
2146 space_part = TRUE;
2147 if (get_current_construction_bonus(pcity, EFT_SS_STRUCTURAL,
2148 RPT_CERTAIN) > 0) {
2149 pplayer->spaceship.structurals++;
2150 } else if (get_current_construction_bonus(pcity, EFT_SS_COMPONENT,
2151 RPT_CERTAIN) > 0) {
2152 pplayer->spaceship.components++;
2153 } else if (get_current_construction_bonus(pcity, EFT_SS_MODULE,
2154 RPT_CERTAIN) > 0) {
2155 pplayer->spaceship.modules++;
2156 } else {
2157 space_part = FALSE;
2158 city_add_improvement(pcity, pimprove);
2160 pcity->before_change_shields -= impr_build_shield_cost(pimprove);
2161 pcity->shield_stock -= impr_build_shield_cost(pimprove);
2162 pcity->turn_last_built = game.info.turn;
2163 /* to eliminate micromanagement */
2164 if (is_great_wonder(pimprove)) {
2165 notify_player(NULL, city_tile(pcity), E_WONDER_BUILD, ftc_server,
2166 _("The %s have finished building %s in %s."),
2167 nation_plural_for_player(pplayer),
2168 city_improvement_name_translation(pcity, pimprove),
2169 city_link(pcity));
2172 notify_player(pplayer, city_tile(pcity), E_IMP_BUILD, ftc_server,
2173 _("%s has finished building %s."),
2174 city_link(pcity), improvement_name_translation(pimprove));
2175 script_server_signal_emit("building_built", 2,
2176 API_TYPE_BUILDING_TYPE, pimprove,
2177 API_TYPE_CITY, pcity);
2179 if (!city_exist(saved_id)) {
2180 /* Script removed city */
2181 return FALSE;
2184 /* Call this function since some buildings may change the
2185 * the vision range of a city */
2186 city_refresh_vision(pcity);
2188 if ((mod = get_current_construction_bonus(pcity, EFT_GIVE_IMM_TECH,
2189 RPT_CERTAIN))) {
2190 struct research *presearch = research_get(pplayer);
2191 char research_name[MAX_LEN_NAME * 2];
2192 int i;
2193 const char *provider = improvement_name_translation(pimprove);
2195 notify_research(presearch, NULL, E_TECH_GAIN, ftc_server,
2196 PL_("%s boosts research; you gain %d immediate "
2197 "advance.",
2198 "%s boosts research; you gain %d immediate "
2199 "advances.",
2200 mod), provider, mod);
2202 research_pretty_name(presearch, research_name, sizeof(research_name));
2203 for (i = 0; i < mod; i++) {
2204 Tech_type_id tech = give_immediate_free_tech(presearch);
2205 const char *adv_name = research_advance_name_translation(presearch, tech);
2207 notify_research(presearch, NULL, E_TECH_GAIN, ftc_server,
2208 /* TRANS: Tech from building (Darwin's Voyage) */
2209 Q_("?frombldg:Acquired %s from %s."), adv_name,
2210 provider);
2212 notify_research_embassies(presearch, NULL, E_TECH_EMBASSY, ftc_server,
2213 /* TRANS: Tech from building (Darwin's
2214 * Voyage) */
2215 Q_("?frombldg:The %s have acquired %s "
2216 "from %s."),
2217 research_name, adv_name, provider);
2220 if (space_part && pplayer->spaceship.state == SSHIP_NONE) {
2221 notify_player(NULL, city_tile(pcity), E_SPACESHIP, ftc_server,
2222 _("The %s have started building a spaceship!"),
2223 nation_plural_for_player(pplayer));
2224 pplayer->spaceship.state = SSHIP_STARTED;
2226 if (space_part) {
2227 /* space ship part build */
2228 send_spaceship_info(pplayer, NULL);
2229 } else {
2230 /* Update city data. */
2231 if (city_refresh(pcity)) {
2232 auto_arrange_workers(pcity);
2236 /* Move to the next thing in the worklist */
2237 choose_build_target(pplayer, pcity);
2240 return TRUE;
2243 /**************************************************************************
2244 Build city units. Several units can be built in one turn if the effect
2245 City_Build_Slots is used.
2246 **************************************************************************/
2247 static bool city_build_unit(struct player *pplayer, struct city *pcity)
2249 struct unit_type *utype;
2250 struct worklist *pwl = &pcity->worklist;;
2251 int unit_shield_cost, num_units, i;
2253 fc_assert_ret_val(pcity->production.kind == VUT_UTYPE, FALSE);
2255 /* If the city has already bought a unit which is now obsolete, don't try
2256 * to upgrade the production. The new unit might require more shields, which
2257 * would be bad if it was bought to urgently defend a city. (Equally it
2258 * might be the same cost or cheaper, but tough; you hurried the unit so
2259 * you miss out on technological advances.) */
2260 if (city_can_change_build(pcity)) {
2261 upgrade_unit_prod(pcity);
2264 utype = pcity->production.value.utype;
2265 unit_shield_cost = utype_build_shield_cost(utype);
2267 /* We must make a special case for barbarians here, because they are
2268 so dumb. Really. They don't know the prerequisite techs for units
2269 they build!! - Per */
2270 if (!can_city_build_unit_direct(pcity, utype)
2271 && !is_barbarian(pplayer)) {
2272 notify_player(pplayer, city_tile(pcity), E_CITY_CANTBUILD, ftc_server,
2273 _("%s is building %s, which is no longer available."),
2274 city_link(pcity), utype_name_translation(utype));
2276 /* Log before signal emitting, so pointers are certainly valid */
2277 log_verbose("%s %s tried to build %s, which is not available.",
2278 nation_rule_name(nation_of_city(pcity)),
2279 city_name_get(pcity), utype_rule_name(utype));
2280 script_server_signal_emit("unit_cant_be_built", 3,
2281 API_TYPE_UNIT_TYPE, utype,
2282 API_TYPE_CITY, pcity,
2283 API_TYPE_STRING, "unavailable");
2284 return TRUE;
2287 if (pcity->shield_stock >= unit_shield_cost) {
2288 int pop_cost = utype_pop_value(utype);
2289 struct unit *punit;
2290 int saved_city_id = pcity->id;
2292 /* Should we disband the city? -- Massimo */
2293 if (city_size_get(pcity) == pop_cost
2294 && is_city_option_set(pcity, CITYO_DISBAND)) {
2295 return !disband_city(pcity);
2298 if (city_size_get(pcity) <= pop_cost) {
2299 notify_player(pplayer, city_tile(pcity), E_CITY_CANTBUILD, ftc_server,
2300 /* TRANS: city ... utype ... size ... pop_cost */
2301 _("%s can't build %s yet. "
2302 "(city size: %d, unit population cost: %d)"),
2303 city_link(pcity), utype_name_translation(utype),
2304 city_size_get(pcity), pop_cost);
2305 script_server_signal_emit("unit_cant_be_built", 3,
2306 API_TYPE_UNIT_TYPE, utype,
2307 API_TYPE_CITY, pcity,
2308 API_TYPE_STRING, "pop_cost");
2309 return TRUE;
2312 fc_assert(pop_cost == 0 || city_size_get(pcity) >= pop_cost);
2314 /* don't update turn_last_built if we returned above */
2315 pcity->turn_last_built = game.info.turn;
2317 /* check if we can build more than one unit (effect City_Build_Slots) */
2318 (void) city_production_build_units(pcity, FALSE, &num_units);
2320 /* We should be able to build at least one (by checks above) */
2321 fc_assert(num_units >= 1);
2323 for (i = 0; i < num_units; i++) {
2324 punit = create_unit(pplayer, pcity->tile, utype,
2325 do_make_unit_veteran(pcity, utype),
2326 pcity->id, 0);
2327 pplayer->score.units_built++;
2329 /* After we created the unit remove the citizen. This will also
2330 * rearrange the worker to take into account the extra resources
2331 * (food) needed. */
2332 if (pop_cost > 0) {
2333 city_reduce_size(pcity, pop_cost, NULL, "unit_built");
2336 /* to eliminate micromanagement, we only subtract the unit's cost */
2337 pcity->before_change_shields -= unit_shield_cost;
2338 pcity->shield_stock -= unit_shield_cost;
2340 notify_player(pplayer, city_tile(pcity), E_UNIT_BUILT, ftc_server,
2341 /* TRANS: <city> is finished building <unit/building>. */
2342 _("%s is finished building %s."),
2343 city_link(pcity), utype_name_translation(utype));
2345 if (pop_cost > 0) {
2346 /* Additional message if the unit has population cost. */
2347 notify_player(pplayer, city_tile(pcity), E_UNIT_BUILT_POP_COST,
2348 ftc_server,
2349 /* TRANS: "<unit> cost... <city> shrinks..."
2350 * Plural in "%d population", not "size %d". */
2351 PL_("%s cost %d population. %s shrinks to size %d.",
2352 "%s cost %d population. %s shrinks to size %d.",
2353 pop_cost),
2354 utype_name_translation(utype), pop_cost,
2355 city_link(pcity), city_size_get(pcity));
2358 script_server_signal_emit("unit_built", 2,
2359 API_TYPE_UNIT, punit,
2360 API_TYPE_CITY, pcity);
2362 /* check if the city still exists */
2363 if (!city_exist(saved_city_id)) {
2364 break;
2367 if (i != 0 && worklist_length(pwl) > 0) {
2368 /* remove the build unit from the worklist; it has to be one less
2369 * than units build to preserve the next build target from the
2370 * worklist */
2371 worklist_remove(pwl, 0);
2375 if (city_exist(saved_city_id)) {
2376 /* Done building this unit; time to move on to the next. */
2377 choose_build_target(pplayer, pcity);
2381 return TRUE;
2384 /**************************************************************************
2385 Returns FALSE when the city is removed, TRUE otherwise.
2386 **************************************************************************/
2387 static bool city_build_stuff(struct player *pplayer, struct city *pcity)
2389 if (!city_distribute_surplus_shields(pplayer, pcity)) {
2390 return FALSE;
2393 nullify_caravan_and_disband_plus(pcity);
2394 define_orig_production_values(pcity);
2396 switch (pcity->production.kind) {
2397 case VUT_IMPROVEMENT:
2398 return city_build_building(pplayer, pcity);
2399 case VUT_UTYPE:
2400 return city_build_unit(pplayer, pcity);
2401 default:
2402 /* must never happen! */
2403 fc_assert(FALSE);
2404 break;
2406 return FALSE;
2409 /**************************************************************************
2410 Randomly sell a building from the given list. Returns TRUE if a building
2411 was sold.
2413 NB: It is assumed that gold upkeep for the buildings has already been
2414 paid this turn, hence when a building is sold its upkeep is given back
2415 to the player.
2416 NB: The contents of 'imprs' are usually mangled by this function.
2417 NB: It is assumed that all buildings in 'imprs' can be sold.
2418 **************************************************************************/
2419 static bool sell_random_building(struct player *pplayer,
2420 struct cityimpr_list *imprs)
2422 struct cityimpr *pcityimpr;
2423 int r;
2425 fc_assert_ret_val(pplayer != NULL, FALSE);
2427 if (!imprs || cityimpr_list_size(imprs) == 0) {
2428 return FALSE;
2431 r = fc_rand(cityimpr_list_size(imprs));
2432 pcityimpr = cityimpr_list_get(imprs, r);
2434 notify_player(pplayer, city_tile(pcityimpr->pcity), E_IMP_AUCTIONED,
2435 ftc_server,
2436 _("Can't afford to maintain %s in %s, building sold!"),
2437 improvement_name_translation(pcityimpr->pimprove),
2438 city_link(pcityimpr->pcity));
2439 log_debug("%s: sold building (%s)", player_name(pplayer),
2440 improvement_name_translation(pcityimpr->pimprove));
2442 do_sell_building(pplayer, pcityimpr->pcity, pcityimpr->pimprove);
2444 cityimpr_list_remove(imprs, pcityimpr);
2446 /* Get back the gold upkeep that was already paid this turn. */
2447 pplayer->economic.gold += city_improvement_upkeep(pcityimpr->pcity,
2448 pcityimpr->pimprove);
2450 city_refresh_queue_add(pcityimpr->pcity);
2452 FC_FREE(pcityimpr);
2454 return TRUE;
2457 /**************************************************************************
2458 Randomly "sell" a unit from the given list. Returns pointer to sold unit.
2459 This pointer is not valid any more, but can be removed from the lists.
2461 NB: It is assumed that gold upkeep for the units has already been paid
2462 this turn, hence when a unit is "sold" its upkeep is given back to the
2463 player.
2464 NB: The contents of 'units' are usually mangled by this function.
2465 NB: It is assumed that all units in 'units' have positive gold upkeep.
2466 **************************************************************************/
2467 static struct unit *sell_random_unit(struct player *pplayer,
2468 struct unit_list *punitlist)
2470 struct unit *punit;
2471 int gold_upkeep, r;
2472 struct unit_list *cargo;
2474 fc_assert_ret_val(pplayer != NULL, FALSE);
2476 if (!punitlist || unit_list_size(punitlist) == 0) {
2477 return FALSE;
2480 r = fc_rand(unit_list_size(punitlist));
2481 punit = unit_list_get(punitlist, r);
2483 cargo = unit_list_new();
2485 /* Check if unit is transporting other units from punitlist,
2486 * and sell one of those (recursively) instead. */
2487 unit_list_iterate(unit_transport_cargo(punit), pcargo) {
2488 if (pcargo->upkeep[O_GOLD] > 0) { /* Optimization, do not iterate over punitlist
2489 * if we are sure that pcargo is not in it. */
2490 unit_list_iterate(punitlist, p2) {
2491 if (pcargo == p2) {
2492 unit_list_append(cargo, pcargo);
2494 } unit_list_iterate_end;
2496 } unit_list_iterate_end;
2498 if (unit_list_size(cargo) > 0) {
2499 struct unit *ret = sell_random_unit(pplayer, cargo);
2501 if (ret != NULL) {
2502 /* Remove from original list too */
2503 unit_list_remove(punitlist, ret);
2506 unit_list_destroy(cargo);
2508 return ret;
2511 unit_list_destroy(cargo);
2513 gold_upkeep = punit->upkeep[O_GOLD];
2515 /* All units in punitlist should have gold upkeep! */
2516 fc_assert_ret_val(gold_upkeep > 0, NULL);
2518 notify_player(pplayer, unit_tile(punit), E_UNIT_LOST_MISC, ftc_server,
2519 _("Not enough gold. %s disbanded."),
2520 unit_tile_link(punit));
2521 log_debug("%s: unit sold (%s)", player_name(pplayer),
2522 unit_name_translation(punit));
2524 unit_list_remove(punitlist, punit);
2525 wipe_unit(punit, ULR_SOLD, NULL);
2527 /* Get the upkeep gold back. */
2528 pplayer->economic.gold += gold_upkeep;
2530 return punit;
2533 /**************************************************************************
2534 Balance the gold of a nation by selling some random units and buildings.
2535 **************************************************************************/
2536 static bool player_balance_treasury_units_and_buildings
2537 (struct player *pplayer)
2539 struct cityimpr_list *pimprlist;
2540 struct unit_list *punitlist;
2541 bool sell_unit = TRUE;
2543 if (!pplayer) {
2544 return FALSE;
2547 pimprlist = cityimpr_list_new();
2548 punitlist = unit_list_new();
2550 city_list_iterate(pplayer->cities, pcity) {
2551 city_built_iterate(pcity, pimprove) {
2552 if (can_city_sell_building(pcity, pimprove)) {
2553 struct cityimpr *ci = fc_malloc(sizeof(*ci));
2555 ci->pcity = pcity;
2556 ci->pimprove = pimprove;
2557 cityimpr_list_append(pimprlist, ci);
2559 } city_built_iterate_end;
2561 unit_list_iterate(pcity->units_supported, punit) {
2562 if (punit->upkeep[O_GOLD] > 0) {
2563 unit_list_append(punitlist, punit);
2565 } unit_list_iterate_end;
2566 } city_list_iterate_end;
2568 while (pplayer->economic.gold < 0
2569 && (cityimpr_list_size(pimprlist) > 0
2570 || unit_list_size(punitlist) > 0)) {
2571 if ((!sell_unit && cityimpr_list_size(pimprlist) > 0)
2572 || unit_list_size(punitlist) == 0) {
2573 sell_random_building(pplayer, pimprlist);
2574 } else {
2575 sell_random_unit(pplayer, punitlist);
2577 sell_unit = !sell_unit;
2580 /* Free remaining entries from list */
2581 cityimpr_list_iterate(pimprlist, pimpr) {
2582 FC_FREE(pimpr);
2583 } cityimpr_list_iterate_end;
2585 if (pplayer->economic.gold < 0) {
2586 /* If we get here it means the player has
2587 * negative gold. This should never happen. */
2588 fc_assert_msg(FALSE, "Player %s (nb %d) cannot have negative gold!",
2589 player_name(pplayer), player_number(pplayer));
2592 cityimpr_list_destroy(pimprlist);
2593 unit_list_destroy(punitlist);
2595 return pplayer->economic.gold >= 0;
2598 /**************************************************************************
2599 Balance the gold of a nation by selling some units which need gold upkeep.
2600 **************************************************************************/
2601 static bool player_balance_treasury_units(struct player *pplayer)
2603 struct unit_list *punitlist;
2605 if (!pplayer) {
2606 return FALSE;
2609 punitlist = unit_list_new();
2611 city_list_iterate(pplayer->cities, pcity) {
2612 unit_list_iterate(pcity->units_supported, punit) {
2613 if (punit->upkeep[O_GOLD] > 0) {
2614 unit_list_append(punitlist, punit);
2616 } unit_list_iterate_end;
2617 } city_list_iterate_end;
2619 while (pplayer->economic.gold < 0
2620 && sell_random_unit(pplayer, punitlist)) {
2621 /* all done in sell_random_unit() */
2624 if (pplayer->economic.gold < 0) {
2625 /* If we get here it means the player has
2626 * negative gold. This should never happen. */
2627 fc_assert_msg(FALSE, "Player %s (nb %d) cannot have negative gold!",
2628 player_name(pplayer), player_number(pplayer));
2631 unit_list_destroy(punitlist);
2633 return pplayer->economic.gold >= 0;
2636 /**************************************************************************
2637 Balance the gold of one city by randomly selling some buildings.
2638 **************************************************************************/
2639 static bool city_balance_treasury_buildings(struct city *pcity)
2641 struct player *pplayer;
2642 struct cityimpr_list *pimprlist;
2644 if (!pcity) {
2645 return TRUE;
2648 pplayer = city_owner(pcity);
2649 pimprlist = cityimpr_list_new();
2651 /* Create a vector of all buildings that can be sold. */
2652 city_built_iterate(pcity, pimprove) {
2653 if (can_city_sell_building(pcity, pimprove)) {
2654 struct cityimpr *ci = fc_malloc(sizeof(*ci));
2656 ci->pcity = pcity;
2657 ci->pimprove = pimprove;
2658 cityimpr_list_append(pimprlist, ci);
2660 } city_built_iterate_end;
2662 /* Try to sell some buildings. */
2663 while (pplayer->economic.gold < 0
2664 && sell_random_building(pplayer, pimprlist)) {
2665 /* all done in sell_random_building */
2668 /* Free remaining entries from list */
2669 cityimpr_list_iterate(pimprlist, pimpr) {
2670 FC_FREE(pimpr);
2671 } cityimpr_list_iterate_end;
2673 cityimpr_list_destroy(pimprlist);
2675 return pplayer->economic.gold >= 0;
2678 /**************************************************************************
2679 Balance the gold of one city by randomly selling some units which need
2680 gold upkeep.
2682 NB: This function adds the gold upkeep of disbanded units back to the
2683 player's gold. Hence it assumes that this gold was previously taken
2684 from the player (i.e. in update_city_activity()).
2685 **************************************************************************/
2686 static bool city_balance_treasury_units(struct city *pcity)
2688 struct player *pplayer;
2689 struct unit_list *punitlist;
2691 if (!pcity) {
2692 return TRUE;
2695 pplayer = city_owner(pcity);
2696 punitlist = unit_list_new();
2698 /* Create a vector of all supported units with gold upkeep. */
2699 unit_list_iterate(pcity->units_supported, punit) {
2700 if (punit->upkeep[O_GOLD] > 0) {
2701 unit_list_append(punitlist, punit);
2703 } unit_list_iterate_end;
2705 /* Still not enough gold, so try "selling" some units. */
2706 while (pplayer->economic.gold < 0
2707 && sell_random_unit(pplayer, punitlist)) {
2708 /* all done in sell_random_unit() */
2711 /* If we get here the player has negative gold, but hopefully
2712 * another city will be able to pay the deficit, so continue. */
2714 unit_list_destroy(punitlist);
2716 return pplayer->economic.gold >= 0;
2719 /**************************************************************************
2720 Add some Pollution if we have waste
2721 **************************************************************************/
2722 static bool place_pollution(struct city *pcity, enum extra_cause cause)
2724 struct tile *ptile;
2725 struct tile *pcenter = city_tile(pcity);
2726 int city_radius_sq = city_map_radius_sq_get(pcity);
2727 int k = 100;
2729 while (k > 0) {
2730 /* place pollution on a random city tile */
2731 int cx, cy;
2732 int tile_id = fc_rand(city_map_tiles(city_radius_sq));
2733 struct extra_type *pextra;
2735 city_tile_index_to_xy(&cx, &cy, tile_id, city_radius_sq);
2737 /* check for a a real map position */
2738 if (!(ptile = city_map_to_tile(pcenter, city_radius_sq, cx, cy))) {
2739 continue;
2742 pextra = rand_extra_for_tile(ptile, cause);
2744 if (pextra != NULL && !tile_has_extra(ptile, pextra)) {
2745 tile_add_extra(ptile, pextra);
2746 update_tile_knowledge(ptile);
2748 return TRUE;
2750 k--;
2752 log_debug("pollution not placed: city: %s", city_name_get(pcity));
2754 return FALSE;
2757 /**************************************************************************
2758 Add some Pollution if we have waste
2759 **************************************************************************/
2760 static void check_pollution(struct city *pcity)
2762 if (pcity->pollution != 0 && fc_rand(100) <= pcity->pollution) {
2763 if (place_pollution(pcity, EC_POLLUTION)) {
2764 notify_player(city_owner(pcity), city_tile(pcity), E_POLLUTION, ftc_server,
2765 _("Pollution near %s."), city_link(pcity));
2770 /**************************************************************************
2771 Returns the cost to incite a city. This depends on the size of the city,
2772 the number of happy, unhappy and angry citizens, whether it is
2773 celebrating, how close it is to the capital, how many units it has and
2774 upkeeps, presence of courthouse, its buildings and wonders, and who
2775 originally built it.
2776 **************************************************************************/
2777 int city_incite_cost(struct player *pplayer, struct city *pcity)
2779 struct city *capital;
2780 int dist, size;
2781 double cost; /* Intermediate values can get very large */
2783 /* Gold factor */
2784 cost = city_owner(pcity)->economic.gold + game.server.base_incite_cost;
2786 unit_list_iterate(pcity->tile->units, punit) {
2787 cost += (unit_build_shield_cost(punit)
2788 * game.server.incite_unit_factor);
2789 } unit_list_iterate_end;
2791 /* Buildings */
2792 city_built_iterate(pcity, pimprove) {
2793 cost += impr_build_shield_cost(pimprove)
2794 * game.server.incite_improvement_factor;
2795 } city_built_iterate_end;
2797 /* Stability bonuses */
2798 if (!city_unhappy(pcity)) {
2799 cost *= 2;
2801 if (city_celebrating(pcity)) {
2802 cost *= 2;
2805 /* Buy back is cheap, conquered cities are also cheap */
2806 if (!game.info.citizen_nationality) {
2807 if (city_owner(pcity) != pcity->original) {
2808 if (pplayer == pcity->original) {
2809 cost /= 2; /* buy back: 50% price reduction */
2810 } else {
2811 cost = cost * 2 / 3; /* buy conquered: 33% price reduction */
2816 /* Distance from capital */
2817 capital = player_capital(city_owner(pcity));
2818 if (capital) {
2819 int tmp = map_distance(capital->tile, pcity->tile);
2820 dist = MIN(32, tmp);
2821 } else {
2822 /* No capital? Take max penalty! */
2823 dist = 32;
2826 size = MAX(1, city_size_get(pcity)
2827 + pcity->feel[CITIZEN_HAPPY][FEELING_FINAL]
2828 - pcity->feel[CITIZEN_UNHAPPY][FEELING_FINAL]
2829 - pcity->feel[CITIZEN_ANGRY][FEELING_FINAL] * 3);
2830 cost *= size;
2831 cost *= game.server.incite_total_factor;
2832 cost = cost / (dist + 3);
2834 if (game.info.citizen_nationality) {
2835 int cost_per_citizen = cost / pcity->size;
2836 int natives = citizens_nation_get(pcity, city_owner(pcity)->slot);
2837 int tgt_cit = citizens_nation_get(pcity, pplayer->slot);
2838 int third_party = pcity->size - natives - tgt_cit;
2840 cost = cost_per_citizen * (natives + 0.7 * third_party + 0.5 * tgt_cit);
2843 cost += (cost * get_city_bonus(pcity, EFT_INCITE_COST_PCT)) / 100;
2844 cost /= 100;
2846 if (cost >= INCITE_IMPOSSIBLE_COST) {
2847 return INCITE_IMPOSSIBLE_COST;
2848 } else {
2849 return cost;
2853 /**************************************************************************
2854 Called every turn, at beginning of turn, for every city.
2855 **************************************************************************/
2856 static void define_orig_production_values(struct city *pcity)
2858 /* Remember what this city is building last turn, so that on the next turn
2859 * the player can switch production to something else and then change it
2860 * back without penalty. This has to be updated _before_ production for
2861 * this turn is calculated, so that the penalty will apply if the player
2862 * changes production away from what has just been completed. This makes
2863 * sense if you consider what this value means: all the shields in the
2864 * city have been dedicated toward the project that was chosen last turn,
2865 * so the player shouldn't be penalized if the governor has to pick
2866 * something different. See city_change_production_penalty(). */
2867 pcity->changed_from = pcity->production;
2869 log_debug("In %s, building %s. Beg of Turn shields = %d",
2870 city_name_get(pcity), universal_rule_name(&pcity->changed_from),
2871 pcity->before_change_shields);
2874 /**************************************************************************
2875 Let the advisor set up city building target.
2876 **************************************************************************/
2877 static void nullify_caravan_and_disband_plus(struct city *pcity)
2879 pcity->disbanded_shields=0;
2880 pcity->caravan_shields=0;
2883 /**************************************************************************
2884 Initialize all variables containing information about production
2885 before it was changed.
2886 **************************************************************************/
2887 void nullify_prechange_production(struct city *pcity)
2889 nullify_caravan_and_disband_plus(pcity);
2890 pcity->before_change_shields=0;
2893 /**************************************************************************
2894 Called every turn, at end of turn, for every city.
2895 **************************************************************************/
2896 static void update_city_activity(struct city *pcity)
2898 struct player *pplayer;
2899 struct government *gov;
2901 if (!pcity) {
2902 return;
2905 pplayer = city_owner(pcity);
2906 gov = government_of_city(pcity);
2908 if (city_refresh(pcity)) {
2909 auto_arrange_workers(pcity);
2912 /* Reporting of celebrations rewritten, copying the treatment of disorder below,
2913 with the added rapture rounds count. 991219 -- Jing */
2914 if (city_build_stuff(pplayer, pcity)) {
2915 int saved_id;
2916 int revolution_turns;
2918 pcity->history += city_history_gain(pcity);
2920 /* History can decrease, but never go below zero */
2921 pcity->history = MAX(pcity->history, 0);
2923 if (city_celebrating(pcity)) {
2924 pcity->rapture++;
2925 if (pcity->rapture == 1) {
2926 notify_player(pplayer, city_tile(pcity), E_CITY_LOVE, ftc_server,
2927 _("Celebrations in your honor in %s."),
2928 city_link(pcity));
2930 } else {
2931 if (pcity->rapture != 0) {
2932 notify_player(pplayer, city_tile(pcity), E_CITY_NORMAL, ftc_server,
2933 _("Celebrations canceled in %s."),
2934 city_link(pcity));
2936 pcity->rapture = 0;
2938 pcity->was_happy = city_happy(pcity);
2940 /* Handle the illness. */
2941 if (game.info.illness_on) {
2942 /* recalculate city illness; illness due to trade has to be saved
2943 * within the city struct as the client has not all data to
2944 * calculate it */
2945 pcity->server.illness
2946 = city_illness_calc(pcity, NULL, NULL, &(pcity->illness_trade), NULL);
2948 if (city_illness_check(pcity)) {
2949 notify_player(pplayer, city_tile(pcity), E_CITY_PLAGUE, ftc_server,
2950 _("%s has been struck by a plague! Population lost!"),
2951 city_link(pcity));
2952 city_reduce_size(pcity, 1, NULL, "plague");
2953 pcity->turn_plague = game.info.turn;
2955 /* recalculate illness */
2956 pcity->server.illness
2957 = city_illness_calc(pcity, NULL, NULL, &(pcity->illness_trade),
2958 NULL);
2962 /* City population updated here, after the rapture stuff above. --Jing */
2963 saved_id = pcity->id;
2964 city_populate(pcity, pplayer);
2965 if (NULL == player_city_by_number(pplayer, saved_id)) {
2966 return;
2969 pcity->did_sell = FALSE;
2970 pcity->did_buy = FALSE;
2971 pcity->airlift = city_airlift_max(pcity);
2972 update_bulbs(pplayer, pcity->prod[O_SCIENCE], FALSE);
2974 /* Update the treasury. */
2975 pplayer->economic.gold += pcity->prod[O_GOLD];
2976 pplayer->economic.gold -= city_total_impr_gold_upkeep(pcity);
2977 pplayer->economic.gold -= city_total_unit_gold_upkeep(pcity);
2979 if (pplayer->economic.gold < 0) {
2980 /* Not enough gold - we have to sell some buildings, and if that
2981 * is not enough, disband units with gold upkeep, taking into
2982 * account the setting of 'game.info.gold_upkeep_style':
2983 * GOLD_UPKEEP_CITY: Cities pay for buildings and units.
2984 * GOLD_UPKEEP_MIXED: Cities pay only for buildings; the nation pays
2985 * for units.
2986 * GOLD_UPKEEP_NATION: The nation pays for buildings and units. */
2987 switch (game.info.gold_upkeep_style) {
2988 case GOLD_UPKEEP_CITY:
2989 case GOLD_UPKEEP_MIXED:
2990 if (!city_balance_treasury_buildings(pcity)
2991 && game.info.gold_upkeep_style == GOLD_UPKEEP_CITY) {
2992 city_balance_treasury_units(pcity);
2994 break;
2995 case GOLD_UPKEEP_NATION:
2996 break;
3000 if (city_unhappy(pcity)) {
3001 pcity->anarchy++;
3002 if (pcity->anarchy == 1) {
3003 notify_player(pplayer, city_tile(pcity), E_CITY_DISORDER, ftc_server,
3004 _("Civil disorder in %s."),
3005 city_link(pcity));
3006 } else {
3007 notify_player(pplayer, city_tile(pcity), E_CITY_DISORDER, ftc_server,
3008 _("CIVIL DISORDER CONTINUES in %s."),
3009 city_link(pcity));
3011 } else {
3012 if (pcity->anarchy != 0) {
3013 notify_player(pplayer, city_tile(pcity), E_CITY_NORMAL, ftc_server,
3014 _("Order restored in %s."),
3015 city_link(pcity));
3017 pcity->anarchy = 0;
3019 check_pollution(pcity);
3021 send_city_info(NULL, pcity);
3023 revolution_turns = get_city_bonus(pcity, EFT_REVOLUTION_UNHAPPINESS);
3024 if (revolution_turns > 0 && pcity->anarchy > revolution_turns) {
3025 notify_player(pplayer, city_tile(pcity), E_ANARCHY, ftc_server,
3026 _("The people have overthrown your %s, "
3027 "your country is in turmoil."),
3028 government_name_translation(gov));
3029 handle_player_change_government(pplayer, government_number(gov));
3031 if (city_refresh(pcity)) {
3032 auto_arrange_workers(pcity);
3034 sanity_check_city(pcity);
3038 /*****************************************************************************
3039 check if city suffers from a plague. Return TRUE if it does, FALSE if not.
3040 ****************************************************************************/
3041 static bool city_illness_check(const struct city * pcity)
3043 if (fc_rand(1000) < pcity->server.illness) {
3044 return TRUE;
3047 return FALSE;
3050 /**************************************************************************
3051 Disband a city into the built unit, supported by the closest city.
3052 **************************************************************************/
3053 static bool disband_city(struct city *pcity)
3055 struct player *pplayer = city_owner(pcity);
3056 struct tile *ptile = pcity->tile;
3057 struct city *rcity=NULL;
3058 struct unit_type *utype = pcity->production.value.utype;
3059 int saved_id = pcity->id;
3061 /* find closest city other than pcity */
3062 rcity = find_closest_city(ptile, pcity, pplayer, FALSE, FALSE, FALSE, TRUE,
3063 FALSE, NULL);
3065 if (!rcity) {
3066 /* What should we do when we try to disband our only city? */
3067 notify_player(pplayer, ptile, E_CITY_CANTBUILD, ftc_server,
3068 _("%s can't build %s yet, "
3069 "and we can't disband our only city."),
3070 city_link(pcity), utype_name_translation(utype));
3071 script_server_signal_emit("unit_cant_be_built", 3,
3072 API_TYPE_UNIT_TYPE, utype,
3073 API_TYPE_CITY, pcity,
3074 API_TYPE_STRING, "pop_cost");
3075 if (!city_exist(saved_id)) {
3076 /* Script decided to remove even the last city */
3077 return TRUE;
3078 } else {
3079 return FALSE;
3083 (void) create_unit(pplayer, ptile, utype,
3084 do_make_unit_veteran(pcity, utype),
3085 pcity->id, 0);
3086 pplayer->score.units_built++;
3088 /* Shift all the units supported by pcity (including the new unit)
3089 * to rcity. transfer_city_units does not make sure no units are
3090 * left floating without a transport, but since all units are
3091 * transferred this is not a problem. */
3092 transfer_city_units(pplayer, pplayer, pcity->units_supported, rcity,
3093 pcity, -1, TRUE);
3095 notify_player(pplayer, ptile, E_UNIT_BUILT, ftc_server,
3096 /* TRANS: "<city> is disbanded into Settler." */
3097 _("%s is disbanded into %s."),
3098 city_tile_link(pcity), utype_name_translation(utype));
3100 script_server_signal_emit("city_destroyed", 3,
3101 API_TYPE_CITY, pcity,
3102 API_TYPE_PLAYER, pcity->owner,
3103 API_TYPE_PLAYER, NULL);
3105 remove_city(pcity);
3106 return TRUE;
3109 /***************************************************************************
3110 Helper function to calculate a "score" of a city. The score is used to get
3111 an estimate of the "migration desirability" of the city. The higher the
3112 score the more likely citizens will migrate to it.
3114 The score depends on the city size, the feeling of its citizens, the cost
3115 of all buildings in the city, and the surplus of trade, luxury and
3116 science.
3118 formula:
3119 score = ([city size] + feeling) * factors
3121 * feeling of the citizens
3122 feeling = 1.00 * happy citizens
3123 + 0.00 * content citizens
3124 - 0.25 * unhappy citizens
3125 - 0.50 * angry citizens
3127 * factors
3128 * the build costs of all buildings
3129 f = (1 + (1 - exp(-[build shield cost]/1000))/5)
3130 * the trade of the city
3131 f = (1 + (1 - exp(-[city surplus trade]/100))/5)
3132 * the luxury within the city
3133 f = (1 + (1 - exp(-[city surplus luxury]/100))/5)
3134 * the science within the city
3135 f = (1 + (1 - exp(-[city surplus science]/100))/5)
3137 all factors f have values between 1 and 1.2; the overall factor will be
3138 between 1.0 (smaller cities) and 2.0 (bigger cities)
3140 [build shield cost], [city surplus trade], [city surplus luxury] and
3141 [city surplus science] _must_ be >= 0!
3143 The food furplus is considered by an additional factor
3145 * the food surplus of the city
3146 f = (1 + [city surplus food; interval -10..20]/10)
3148 The health factor is defined as:
3150 * the health of the city
3151 f = (100 - [city illness; tenth of %]/25)
3153 * if the city has at least one wonder a factor of 1.25 is added
3154 * for the capital an additional factor of 1.25 is used
3155 * the score is also modified by the effect EFT_MIGRATION_PCT
3156 **************************************************************************/
3157 static float city_migration_score(struct city *pcity)
3159 float score = 0.0;
3160 int build_shield_cost = 0;
3161 bool has_wonder = FALSE;
3163 if (!pcity) {
3164 return score;
3167 if (pcity->server.mgr_score_calc_turn == game.info.turn) {
3168 /* up-to-date migration score */
3169 return pcity->server.migration_score;
3172 /* feeling of the citizens */
3173 score = (city_size_get(pcity)
3174 + 1.00 * pcity->feel[CITIZEN_HAPPY][FEELING_FINAL]
3175 + 0.00 * pcity->feel[CITIZEN_CONTENT][FEELING_FINAL]
3176 - 0.25 * pcity->feel[CITIZEN_UNHAPPY][FEELING_FINAL]
3177 - 0.50 * pcity->feel[CITIZEN_ANGRY][FEELING_FINAL]);
3179 /* calculate shield build cost for all buildings */
3180 city_built_iterate(pcity, pimprove) {
3181 build_shield_cost += impr_build_shield_cost(pimprove);
3182 if (is_wonder(pimprove)) {
3183 /* this city has a wonder */
3184 has_wonder = TRUE;
3186 } city_built_iterate_end;
3188 /* take shield costs of all buidings into account; normalized by 1000 */
3189 score *= (1 + (1 - exp(- (float) MAX(0, build_shield_cost) / 1000)) / 5);
3190 /* take trade into account; normalized by 100 */
3191 score *= (1 + (1 - exp(- (float) MAX(0, pcity->surplus[O_TRADE]) / 100))
3192 / 5);
3193 /* take luxury into account; normalized by 100 */
3194 score *= (1 + (1 - exp(- (float) MAX(0, pcity->surplus[O_LUXURY]) / 100))
3195 / 5);
3196 /* take science into account; normalized by 100 */
3197 score *= (1 + (1 - exp(- (float) MAX(0, pcity->surplus[O_SCIENCE]) / 100))
3198 / 5);
3200 score += city_culture(pcity) * game.info.culture_migration_pml / 1000;
3202 /* Take food into account; the food surplus is clipped to values between
3203 * -10..20 and normalize by 10. Thus, the factor is between 0.9 and 1.2. */
3204 score *= (1 + (float) CLIP(-10, pcity->surplus[O_FOOD], 20) / 10 );
3206 /* Reduce the score due to city illness (plague). The illness is given in
3207 * tenth of percent (0..1000) and normalized by 25. Thus, this factor is
3208 * between 0.6 (ill city) and 1.0 (health city). */
3209 score *= (100 - (float)city_illness_calc(pcity, NULL, NULL, NULL, NULL)
3210 / 25);
3212 if (has_wonder) {
3213 /* people like wonders */
3214 score *= 1.25;
3217 if (is_capital(pcity)) {
3218 /* the capital is a magnet for the citizens */
3219 score *= 1.25;
3222 /* take into account effects */
3223 score *= (1.0 + get_city_bonus(pcity, EFT_MIGRATION_PCT) / 100.0);
3225 log_debug("[M] %s score: %.3f", city_name_get(pcity), score);
3227 /* set migration score for the city */
3228 pcity->server.migration_score = score;
3229 /* set the turn, when the score was calculated */
3230 pcity->server.mgr_score_calc_turn = game.info.turn;
3232 return score;
3235 /**************************************************************************
3236 Do the migrations between the cities that overlap, if the growth of the
3237 target city is not blocked due to a missing improvement or missing food.
3239 Returns TRUE if migration occurred.
3240 **************************************************************************/
3241 static bool do_city_migration(struct city *pcity_from,
3242 struct city *pcity_to)
3244 struct player *pplayer_from, *pplayer_to, *pplayer_citizen;
3245 struct tile *ptile_from, *ptile_to;
3246 char name_from[MAX_LEN_LINK], name_to[MAX_LEN_LINK];
3247 const char *nation_from, *nation_to;
3248 struct city *rcity = NULL;
3250 if (!pcity_from || !pcity_to) {
3251 return FALSE;
3254 pplayer_from = city_owner(pcity_from);
3255 pplayer_citizen = pplayer_from;
3256 pplayer_to = city_owner(pcity_to);
3257 /* We copy that, because city_link always returns the same pointer. */
3258 sz_strlcpy(name_from, city_link(pcity_from));
3259 sz_strlcpy(name_to, city_link(pcity_to));
3260 nation_from = nation_adjective_for_player(pplayer_from);
3261 nation_to = nation_adjective_for_player(pplayer_to);
3262 ptile_from = city_tile(pcity_from);
3263 ptile_to = city_tile(pcity_to);
3265 /* check food supply in the receiver city */
3266 if (game.server.mgr_foodneeded) {
3267 bool migration = FALSE;
3269 if (pcity_to->surplus[O_FOOD] >= game.info.food_cost) {
3270 migration = TRUE;
3271 } else {
3272 /* check if there is a free tile for the new citizen which, when worked,
3273 * leads to zero or positive food surplus for the enlarged city */
3274 int max_food_tile = -1; /* no free tile */
3275 city_tile_iterate(city_map_radius_sq_get(pcity_to),
3276 city_tile(pcity_to), ptile) {
3277 if (city_can_work_tile(pcity_to, ptile)
3278 && tile_worked(ptile) != pcity_to) {
3279 /* Safest assumption is that city won't be celebrating once an
3280 * additional citizen is added */
3281 max_food_tile = MAX(max_food_tile,
3282 city_tile_output(pcity_to, ptile, FALSE, O_FOOD));
3284 } city_tile_iterate_end;
3285 if (max_food_tile >= 0
3286 && pcity_to->surplus[O_FOOD] + max_food_tile >= game.info.food_cost) {
3287 migration = TRUE;
3291 if (!migration) {
3292 /* insufficiency food in receiver city; no additional citizens */
3293 if (pplayer_from == pplayer_to) {
3294 /* migration between one nation */
3295 notify_player(pplayer_to, ptile_to, E_CITY_TRANSFER, ftc_server,
3296 /* TRANS: From <city1> to <city2>. */
3297 _("Migrants from %s can't go to %s because there is "
3298 "not enough food available!"),
3299 name_from, name_to);
3300 } else {
3301 /* migration between different nations */
3302 notify_player(pplayer_from, ptile_to, E_CITY_TRANSFER, ftc_server,
3303 /* TRANS: From <city1> to <city2> (<city2 nation adjective>). */
3304 _("Migrants from %s can't go to %s (%s) because there "
3305 "is not enough food available!"),
3306 name_from, name_to, nation_to);
3307 notify_player(pplayer_to, ptile_to, E_CITY_TRANSFER, ftc_server,
3308 /* TRANS: From <city1> (<city1 nation adjective>) to <city2>. */
3309 _("Migrants from %s (%s) can't go to %s because there "
3310 "is not enough food available!"),
3311 name_from, nation_from, name_to);
3314 return FALSE;
3318 if (!city_can_grow_to(pcity_to, city_size_get(pcity_to) + 1)) {
3319 /* receiver city can't grow */
3320 if (pplayer_from == pplayer_to) {
3321 /* migration between one nation */
3322 notify_player(pplayer_to, ptile_to, E_CITY_TRANSFER, ftc_server,
3323 /* TRANS: From <city1> to <city2>. */
3324 _("Migrants from %s can't go to %s because it needs "
3325 "an improvement to grow!"),
3326 name_from, name_to);
3327 } else {
3328 /* migration between different nations */
3329 notify_player(pplayer_from, ptile_to, E_CITY_TRANSFER, ftc_server,
3330 /* TRANS: From <city1> to <city2> of <city2 nation adjective>. */
3331 _("Migrants from %s can't go to %s (%s) because it "
3332 "needs an improvement to grow!"),
3333 name_from, name_to, nation_to);
3334 notify_player(pplayer_to, ptile_to, E_CITY_TRANSFER, ftc_server,
3335 /* TRANS: From <city1> (<city1 nation adjective>) to <city2>. */
3336 _("Migrants from %s (%s) can't go to %s because it "
3337 "needs an improvement to grow!"),
3338 name_from, nation_from, name_to);
3341 return FALSE;
3344 /* reduce size of giver */
3345 if (city_size_get(pcity_from) == 1) {
3347 if (game.info.citizen_nationality) {
3348 /* Preserve nationality of city's only citizen */
3349 pplayer_citizen = player_slot_get_player(citizens_random(pcity_from));
3352 /* do not destroy wonders */
3353 city_built_iterate(pcity_from, pimprove) {
3354 if (is_wonder(pimprove)) {
3355 return FALSE;
3357 } city_built_iterate_end;
3359 /* find closest city other of the same player than pcity_from */
3360 rcity = find_closest_city(ptile_from, pcity_from, pplayer_from, FALSE,
3361 FALSE, FALSE, TRUE, FALSE, NULL);
3363 if (rcity) {
3364 /* transfer all units to the closest city */
3365 transfer_city_units(pplayer_from, pplayer_from,
3366 pcity_from->units_supported, rcity, pcity_from,
3367 -1, TRUE);
3368 sz_strlcpy(name_from, city_tile_link(pcity_from));
3370 script_server_signal_emit("city_size_change", 3,
3371 API_TYPE_CITY, pcity_from,
3372 API_TYPE_INT, -1,
3373 API_TYPE_STRING, "migration_from");
3374 script_server_signal_emit("city_destroyed", 3,
3375 API_TYPE_CITY, pcity_from,
3376 API_TYPE_PLAYER, pcity_from->owner,
3377 API_TYPE_PLAYER, NULL);
3379 remove_city(pcity_from);
3381 notify_player(pplayer_from, ptile_from, E_CITY_LOST, ftc_server,
3382 _("%s was disbanded by its citizens."),
3383 name_from);
3384 } else {
3385 /* it's the only city of the nation */
3386 return FALSE;
3388 } else {
3389 /* the migrants take half of the food box with them (this prevents
3390 * migration -> grow -> migration -> ... cycles) */
3391 pcity_from->food_stock /= 2;
3393 if (game.info.citizen_nationality) {
3394 /* Those citizens that are from the target nation are most
3395 * ones migrating. */
3396 if (citizens_nation_get(pcity_from, pplayer_to->slot) > 0) {
3397 pplayer_citizen = pplayer_to;
3398 } else if (!citizens_nation_get(pcity_from, pplayer_citizen->slot)) {
3399 /* No native citizens at all in the city, choose random foreigner */
3400 struct player_slot *cit_slot = citizens_random(pcity_from);
3402 pplayer_citizen = player_slot_get_player(cit_slot);
3404 /* This should be followed by city_reduce_size(). */
3405 citizens_nation_add(pcity_from, pplayer_citizen->slot, -1);
3407 city_reduce_size(pcity_from, 1, pplayer_from, "migration_from");
3408 city_refresh_vision(pcity_from);
3409 if (city_refresh(pcity_from)) {
3410 auto_arrange_workers(pcity_from);
3414 /* This should be _before_ the size of the city is increased. Thus, the
3415 * order of the messages is correct (1: migration; 2: increased size). */
3416 if (pplayer_from == pplayer_to) {
3417 /* migration between one nation */
3418 notify_player(pplayer_from, ptile_to, E_CITY_TRANSFER, ftc_server,
3419 /* TRANS: From <city1> to <city2>. */
3420 _("Migrants from %s moved to %s in search of a better "
3421 "life."), name_from, name_to);
3422 } else {
3423 /* migration between different nations */
3424 notify_player(pplayer_from, ptile_to, E_CITY_TRANSFER, ftc_server,
3425 /* TRANS: From <city1> to <city2> (<city2 nation adjective>). */
3426 _("Migrants from %s moved to %s (%s) in search of a "
3427 "better life."),
3428 name_from, name_to, nation_to);
3429 notify_player(pplayer_to, ptile_to, E_CITY_TRANSFER, ftc_server,
3430 /* TRANS: From <city1> (<city1 nation adjective>) to <city2>. */
3431 _("Migrants from %s (%s) moved to %s in search of a "
3432 "better life."),
3433 name_from, nation_from, name_to);
3436 /* raise size of receiver city */
3437 city_increase_size(pcity_to, pplayer_citizen);
3438 city_refresh_vision(pcity_to);
3439 if (city_refresh(pcity_to)) {
3440 auto_arrange_workers(pcity_to);
3442 script_server_signal_emit("city_size_change", 3,
3443 API_TYPE_CITY, pcity_to,
3444 API_TYPE_INT, 1,
3445 API_TYPE_STRING, "migration_to");
3447 log_debug("[M] T%d migration successful (%s -> %s)",
3448 game.info.turn, name_from, name_to);
3450 return TRUE;
3453 /**************************************************************************
3454 Check for citizens who want to migrate between the cities that overlap.
3455 Migrants go to the city with higher score, if the growth of the target
3456 city is not blocked due to a missing improvement.
3458 The following setting are used:
3460 'game.server.mgr_turninterval' controls the number of turns between
3461 migration checks for one city (counted from the founding). If this
3462 setting is zero, or it is the first turn (T0), migration does no occur.
3464 'game.server.mgr_distance' is the maximal distance for migration.
3466 'game.server.mgr_nationchance' gives the chance for migration within one
3467 nation.
3469 'game.server.mgr_worldchance' gives the chance for migration between all
3470 nations.
3472 Returns TRUE iff there has been INTERNATIONAL migration.
3473 **************************************************************************/
3474 bool check_city_migrations(void)
3476 bool internat = FALSE;
3478 if (!game.server.migration) {
3479 return FALSE;
3482 if (game.server.mgr_turninterval <= 0
3483 || (game.server.mgr_worldchance <= 0
3484 && game.server.mgr_nationchance <= 0)) {
3485 return FALSE;
3488 /* check for migration */
3489 players_iterate(pplayer) {
3490 if (!pplayer->cities) {
3491 continue;
3494 if (check_city_migrations_player(pplayer)) {
3495 internat = TRUE;
3497 } players_iterate_end;
3499 return internat;
3502 /**************************************************************************
3503 Disaster has hit a city. Apply its effects.
3504 **************************************************************************/
3505 static void apply_disaster(struct city *pcity, struct disaster_type *pdis)
3507 struct player *pplayer = city_owner(pcity);
3508 struct tile *ptile = city_tile(pcity);
3509 bool had_internal_effect = FALSE;
3511 log_debug("%s at %s", disaster_rule_name(pdis), city_name_get(pcity));
3513 notify_player(pplayer, ptile, E_DISASTER,
3514 ftc_server,
3515 /* TRANS: Disasters such as Earthquake */
3516 _("%s was hit by %s."), city_name_get(pcity),
3517 disaster_name_translation(pdis));
3519 if (disaster_has_effect(pdis, DE_POLLUTION)) {
3520 if (place_pollution(pcity, EC_POLLUTION)) {
3521 notify_player(pplayer, ptile, E_DISASTER, ftc_server,
3522 _("Pollution near %s."), city_link(pcity));
3523 had_internal_effect = TRUE;
3527 if (disaster_has_effect(pdis, DE_FALLOUT)) {
3528 if (place_pollution(pcity, EC_FALLOUT)) {
3529 notify_player(pplayer, ptile, E_DISASTER, ftc_server,
3530 _("Fallout near %s."), city_link(pcity));
3531 had_internal_effect = TRUE;
3535 if (disaster_has_effect(pdis, DE_REDUCE_DESTROY)
3536 || (disaster_has_effect(pdis, DE_REDUCE_POP)
3537 && pcity->size > 1)) {
3538 if (!city_reduce_size(pcity, 1, NULL, "disaster")) {
3539 notify_player(pplayer, ptile, E_DISASTER, ftc_server,
3540 /* TRANS: "Industrial Accident destroys Bogota entirely." */
3541 _("%s destroys %s entirely."),
3542 disaster_name_translation(pdis), city_link(pcity));
3543 pcity = NULL;
3544 } else {
3545 notify_player(pplayer, ptile, E_DISASTER, ftc_server,
3546 /* TRANS: "Nuclear Accident ... Montreal." */
3547 _("%s causes population loss in %s."),
3548 disaster_name_translation(pdis), city_link(pcity));
3551 had_internal_effect = TRUE;
3554 if (pcity && disaster_has_effect(pdis, DE_DESTROY_BUILDING)) {
3555 int total = 0;
3556 struct impr_type *imprs[B_LAST];
3558 city_built_iterate(pcity, pimprove) {
3559 if (is_improvement(pimprove)) {
3560 imprs[total++] = pimprove;
3562 } city_built_iterate_end;
3564 if (total > 0) {
3565 int num = fc_rand(total);
3567 building_lost(pcity, imprs[num]);
3569 notify_player(pplayer, ptile, E_DISASTER, ftc_server,
3570 /* TRANS: second %s is the name of a city improvement */
3571 _("%s destroys %s in %s."),
3572 disaster_name_translation(pdis),
3573 improvement_name_translation(imprs[num]),
3574 city_link(pcity));
3576 had_internal_effect = TRUE;
3580 if (pcity && disaster_has_effect(pdis, DE_EMPTY_FOODSTOCK)) {
3581 if (pcity->food_stock > 0) {
3582 pcity->food_stock = 0;
3584 notify_player(pplayer, ptile, E_DISASTER, ftc_server,
3585 /* TRANS: %s is a city name */
3586 _("All stored food destroyed in %s."), city_link(pcity));
3588 had_internal_effect = TRUE;
3592 if (pcity && disaster_has_effect(pdis, DE_EMPTY_PRODSTOCK)) {
3593 if (pcity->shield_stock > 0) {
3594 char prod[256];
3596 pcity->shield_stock = 0;
3597 nullify_prechange_production(pcity); /* Make it impossible to recover */
3599 universal_name_translation(&pcity->production, prod, sizeof(prod));
3600 notify_player(pplayer, ptile, E_DISASTER, ftc_server,
3601 /* TRANS: "Production of Colossus in Rhodes destroyed." */
3602 _("Production of %s in %s destroyed."),
3603 prod, city_link(pcity));
3605 had_internal_effect = TRUE;
3609 script_server_signal_emit("disaster_occurred", 3,
3610 API_TYPE_DISASTER, pdis,
3611 API_TYPE_CITY, pcity,
3612 API_TYPE_BOOL, had_internal_effect);
3613 script_server_signal_emit("disaster", 2,
3614 API_TYPE_DISASTER, pdis,
3615 API_TYPE_CITY, pcity);
3618 /**************************************************************************
3619 Check for any disasters hitting any city, and apply those disasters.
3620 **************************************************************************/
3621 void check_disasters(void)
3623 if (game.info.disasters == 0) {
3624 /* Shortcut out as no disaster is possible. */
3625 return;
3628 players_iterate(pplayer) {
3629 /* Safe city iterator needed as disaster may destroy city */
3630 city_list_iterate_safe(pplayer->cities, pcity) {
3631 int id = pcity->id;
3633 disaster_type_iterate(pdis) {
3634 if (city_exist(id)) {
3635 /* City survived earlier disasters. */
3636 int probability = game.info.disasters * pdis->frequency;
3637 int result = fc_rand(DISASTER_BASE_RARITY);
3639 if (result < probability) {
3640 if (can_disaster_happen(pdis, pcity)) {
3641 apply_disaster(pcity, pdis);
3645 } disaster_type_iterate_end;
3646 } city_list_iterate_safe_end;
3647 } players_iterate_end;
3650 /**************************************************************************
3651 Check for migration for each city of one player.
3653 For each city of the player do:
3654 * check each tile within GAME_MAX_MGR_DISTANCE for a city
3655 * if a city is found check the distance
3656 * compare the migration score
3657 **************************************************************************/
3658 static bool check_city_migrations_player(const struct player *pplayer)
3660 char city_link_text[MAX_LEN_LINK];
3661 float best_city_player_score, best_city_world_score;
3662 struct city *best_city_player, *best_city_world, *acity;
3663 float score_from, score_tmp, weight;
3664 int dist, mgr_dist;
3665 bool internat = FALSE;
3667 /* check for each city
3668 * city_list_iterate_safe_end must be used because we could
3669 * remove one city from the list */
3670 city_list_iterate_safe(pplayer->cities, pcity) {
3671 /* no migration out of the capital */
3672 if (is_capital(pcity)) {
3673 continue;
3676 /* check only each (game.server.mgr_turninterval) turn
3677 * (counted from the funding turn) and do not migrate
3678 * the same turn a city is founded */
3679 if (game.info.turn == pcity->turn_founded
3680 || ((game.info.turn - pcity->turn_founded)
3681 % game.server.mgr_turninterval) != 0) {
3682 continue;
3685 best_city_player_score = 0.0;
3686 best_city_world_score = 0.0;
3687 best_city_player = NULL;
3688 best_city_world = NULL;
3690 /* score of the actual city
3691 * taking into account a persistence factor of 3 */
3692 score_from = city_migration_score(pcity) * 3;
3694 log_debug("[M] T%d check city: %s score: %6.3f (%s)",
3695 game.info.turn, city_name_get(pcity), score_from,
3696 player_name(pplayer));
3698 /* consider all cities within the maximal possible distance
3699 * (= CITY_MAP_MAX_RADIUS + GAME_MAX_MGR_DISTANCE) */
3700 iterate_outward(city_tile(pcity), CITY_MAP_MAX_RADIUS
3701 + GAME_MAX_MGR_DISTANCE, ptile) {
3702 acity = tile_city(ptile);
3704 if (!acity || acity == pcity) {
3705 /* no city or the city in the center */
3706 continue;
3709 /* Calculate the migration distance. The value of
3710 * game.server.mgr_distance is added to the current city radius. If the
3711 * distance between both cities is lower or equal than this value,
3712 * migration is possible. */
3713 mgr_dist = (int)sqrt((double)MAX(city_map_radius_sq_get(acity),0))
3714 + game.server.mgr_distance;
3716 /* distance between the two cities */
3717 dist = real_map_distance(city_tile(pcity), city_tile(acity));
3719 if (dist > mgr_dist) {
3720 /* to far away */
3721 continue;
3724 /* score of the second city, weighted by the distance */
3725 weight = ((float) (mgr_dist + 1 - dist) / (float) (mgr_dist + 1));
3726 score_tmp = city_migration_score(acity) * weight;
3728 log_debug("[M] T%d - compare city: %s (%s) dist: %d mgr_dist: %d "
3729 "score: %6.3f", game.info.turn, city_name_get(acity),
3730 player_name(city_owner(acity)), dist, mgr_dist, score_tmp);
3732 if (game.server.mgr_nationchance > 0 && city_owner(acity) == pplayer) {
3733 /* migration between cities of the same owner */
3734 if (score_tmp > score_from && score_tmp > best_city_player_score) {
3735 /* select the best! */
3736 best_city_player_score = score_tmp;
3737 best_city_player = acity;
3739 log_debug("[M] T%d - best city (player): %s (%s) score: "
3740 "%6.3f (> %6.3f)", game.info.turn,
3741 city_name_get(best_city_player), player_name(pplayer),
3742 best_city_player_score, score_from);
3744 } else if (game.server.mgr_worldchance > 0
3745 && city_owner(acity) != pplayer) {
3746 /* migration between cities of different owners */
3747 if (game.info.citizen_nationality) {
3748 /* Modify the score if citizens could migrate to a city of their
3749 * original nation. */
3750 if (citizens_nation_get(pcity, city_owner(acity)->slot) > 0) {
3751 score_tmp *= 2;
3755 if (score_tmp > score_from && score_tmp > best_city_world_score) {
3756 /* select the best! */
3757 best_city_world_score = score_tmp;
3758 best_city_world = acity;
3760 log_debug("[M] T%d - best city (world): %s (%s) score: "
3761 "%6.3f (> %6.3f)", game.info.turn,
3762 city_name_get(best_city_world),
3763 player_name(city_owner(best_city_world)),
3764 best_city_world_score, score_from);
3767 } iterate_outward_end;
3769 if (best_city_player_score > 0) {
3770 /* first, do the migration within one nation */
3771 if (fc_rand(100) >= game.server.mgr_nationchance) {
3772 /* no migration */
3773 /* N.B.: city_link always returns the same pointer. */
3774 sz_strlcpy(city_link_text, city_link(pcity));
3775 notify_player(pplayer, city_tile(pcity), E_CITY_TRANSFER, ftc_server,
3776 _("Citizens of %s are thinking about migrating to %s "
3777 "for a better life."),
3778 city_link_text, city_link(best_city_player));
3779 } else {
3780 do_city_migration(pcity, best_city_player);
3783 /* stop here */
3784 continue;
3787 if (best_city_world_score > 0) {
3788 /* second, do the migration between all nations */
3789 if (fc_rand(100) >= game.server.mgr_worldchance) {
3790 const char *nname;
3792 nname = nation_adjective_for_player(city_owner(best_city_world));
3793 /* no migration */
3794 /* N.B.: city_link always returns the same pointer. */
3795 sz_strlcpy(city_link_text, city_link(pcity));
3796 notify_player(pplayer, city_tile(pcity), E_CITY_TRANSFER, ftc_server,
3797 /* TRANS: <city1> to <city2> (<city2 nation adjective>). */
3798 _("Citizens of %s are thinking about migrating to %s "
3799 "(%s) for a better life."),
3800 city_link_text, city_link(best_city_world), nname);
3801 } else {
3802 do_city_migration(pcity, best_city_world);
3803 internat = TRUE;
3806 /* stop here */
3807 continue;
3809 } city_list_iterate_safe_end;
3811 return internat;
3814 /**************************************************************************
3815 Recheck and store style of the city.
3816 **************************************************************************/
3817 void city_style_refresh(struct city *pcity)
3819 pcity->style = city_style(pcity);