Show messages related to the client followtag received from the metaserver.
[freeciv.git] / server / cityturn.c
blob3307f65df3c618b504cc83f9c29ec76b05ce1943
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 fc_assert_ret_val(size >= 0 && size <= MAX_CITY_SIZE, TRUE);
920 if (change != 0 && reason != NULL) {
921 script_server_signal_emit("city_size_change", 3,
922 API_TYPE_CITY, pcity,
923 API_TYPE_INT, size - city_size_get(pcity),
924 API_TYPE_STRING, reason);
927 if (change > 0) {
928 /* Increase city size until size reached, or increase fails */
929 while (size > city_size_get(pcity)
930 && city_increase_size(pcity, nationality)) {
931 /* city_increase_size() does all the work. */
933 } else if (change < 0) {
934 /* We assume that city_change_size() is never called because
935 * of enemy actions. If that changes, enemy must be passed
936 * to city_reduce_size() */
937 return city_reduce_size(pcity, -change, NULL, NULL);
940 map_claim_border(pcity->tile, pcity->owner, -1);
942 return TRUE;
945 /**************************************************************************
946 Check whether the population can be increased or
947 if the city is unable to support a 'settler'...
948 **************************************************************************/
949 static void city_populate(struct city *pcity, struct player *nationality)
951 int saved_id = pcity->id;
952 int granary_size = city_granary_size(city_size_get(pcity));
954 pcity->food_stock += pcity->surplus[O_FOOD];
955 if (pcity->food_stock >= granary_size || city_rapture_grow(pcity)) {
956 if (city_had_recent_plague(pcity)) {
957 notify_player(city_owner(pcity), city_tile(pcity),
958 E_CITY_PLAGUE, ftc_server,
959 _("A recent plague outbreak prevents growth in %s."),
960 city_link(pcity));
961 /* Lose excess food */
962 pcity->food_stock = MIN(pcity->food_stock, granary_size);
963 } else {
964 city_increase_size(pcity, nationality);
965 map_claim_border(pcity->tile, pcity->owner, -1);
966 script_server_signal_emit("city_size_change", 3,
967 API_TYPE_CITY, pcity,
968 API_TYPE_INT, 1,
969 API_TYPE_STRING, "growth");
971 } else if (pcity->food_stock < 0) {
972 /* FIXME: should this depend on units with ability to build
973 * cities or on units that require food in upkeep?
974 * I'll assume citybuilders (units that 'contain' 1 pop) -- sjolie
975 * The above may make more logical sense, but in game terms
976 * you want to disband a unit that is draining your food
977 * reserves. Hence, I'll assume food upkeep > 0 units. -- jjm
979 unit_list_iterate_safe(pcity->units_supported, punit) {
980 if (punit->upkeep[O_FOOD] > 0
981 && !unit_has_type_flag(punit, UTYF_UNDISBANDABLE)) {
983 notify_player(city_owner(pcity), city_tile(pcity),
984 E_UNIT_LOST_MISC, ftc_server,
985 _("Famine feared in %s, %s lost!"),
986 city_link(pcity), unit_tile_link(punit));
988 wipe_unit(punit, ULR_STARVED, NULL);
990 if (city_exist(saved_id)) {
991 city_reset_foodbox(pcity, city_size_get(pcity));
993 return;
995 } unit_list_iterate_safe_end;
996 if (city_size_get(pcity) > 1) {
997 notify_player(city_owner(pcity), city_tile(pcity),
998 E_CITY_FAMINE, ftc_server,
999 _("Famine causes population loss in %s."),
1000 city_link(pcity));
1001 } else {
1002 notify_player(city_owner(pcity), city_tile(pcity),
1003 E_CITY_FAMINE, ftc_server,
1004 _("Famine destroys %s entirely."),
1005 city_link(pcity));
1007 city_reset_foodbox(pcity, city_size_get(pcity) - 1);
1008 city_reduce_size(pcity, 1, NULL, "famine");
1012 /**************************************************************************
1013 Examine the worklist and change the build target. Return 0 if no
1014 targets are available to change to. Otherwise return non-zero. Has
1015 the side-effect of removing from the worklist any no-longer-available
1016 targets as well as the target actually selected, if any.
1017 **************************************************************************/
1018 static bool worklist_change_build_target(struct player *pplayer,
1019 struct city *pcity)
1021 struct universal target;
1022 bool success = FALSE;
1023 int i;
1024 int saved_id = pcity->id;
1025 bool city_checked = TRUE; /* This is used to avoid spurious city_exist() calls */
1026 struct worklist *pwl = &pcity->worklist;
1028 if (worklist_is_empty(pwl)) {
1029 /* Nothing in the worklist; bail now. */
1030 return FALSE;
1033 i = 0;
1034 while (!success && i < worklist_length(pwl)) {
1036 if (!city_checked) {
1037 if (!city_exist(saved_id)) {
1038 /* Some script has removed useless city that cannot build
1039 * what it is told to! */
1040 return FALSE;
1042 city_checked = TRUE;
1045 if (worklist_peek_ith(pwl, &target, i)) {
1046 success = can_city_build_now(pcity, &target);
1047 } else {
1048 success = FALSE;
1050 i++;
1052 if (success) {
1053 break; /* while */
1056 switch (target.kind) {
1057 case VUT_UTYPE:
1059 struct unit_type *ptarget = target.value.utype;
1060 struct unit_type *pupdate = unit_upgrades_to(pcity, ptarget);
1062 /* Maybe we can just upgrade the target to what the city /can/ build. */
1063 if (U_NOT_OBSOLETED == pupdate) {
1064 /* Nope, we're stuck. Skip this item from the worklist. */
1065 if (ptarget->need_government != NULL
1066 && ptarget->need_government != government_of_player(pplayer)) {
1067 notify_player(pplayer, city_tile(pcity),
1068 E_CITY_CANTBUILD, ftc_server,
1069 _("%s can't build %s from the worklist; "
1070 "it needs %s government. Postponing..."),
1071 city_link(pcity), utype_name_translation(ptarget),
1072 government_name_translation(ptarget->need_government));
1073 script_server_signal_emit("unit_cant_be_built", 3,
1074 API_TYPE_BUILDING_TYPE, ptarget,
1075 API_TYPE_CITY, pcity,
1076 API_TYPE_STRING, "need_government");
1077 } else if (ptarget->need_improvement != NULL
1078 && !city_has_building(pcity, ptarget->need_improvement)) {
1079 notify_player(pplayer, city_tile(pcity),
1080 E_CITY_CANTBUILD, ftc_server,
1081 _("%s can't build %s from the worklist; "
1082 "need to have %s first. Postponing..."),
1083 city_link(pcity), utype_name_translation(ptarget),
1084 city_improvement_name_translation(pcity,
1085 ptarget->need_improvement));
1086 script_server_signal_emit("unit_cant_be_built", 3,
1087 API_TYPE_UNIT_TYPE, ptarget,
1088 API_TYPE_CITY, pcity,
1089 API_TYPE_STRING, "need_building");
1090 } else if (ptarget->require_advance != NULL
1091 && TECH_KNOWN != research_invention_state
1092 (research_get(pplayer),
1093 advance_number(ptarget->require_advance))) {
1094 notify_player(pplayer, city_tile(pcity),
1095 E_CITY_CANTBUILD, ftc_server,
1096 _("%s can't build %s from the worklist; "
1097 "tech %s not yet available. Postponing..."),
1098 city_link(pcity), utype_name_translation(ptarget),
1099 advance_name_translation(ptarget->require_advance));
1100 script_server_signal_emit("unit_cant_be_built", 3,
1101 API_TYPE_UNIT_TYPE, ptarget,
1102 API_TYPE_CITY, pcity,
1103 API_TYPE_STRING, "need_tech");
1104 } else {
1105 /* This shouldn't happen, but in case it does... */
1106 notify_player(pplayer, city_tile(pcity),
1107 E_CITY_CANTBUILD, ftc_server,
1108 _("%s can't build %s from the worklist; "
1109 "reason unknown! Postponing..."),
1110 city_link(pcity), utype_name_translation(ptarget));
1112 city_checked = FALSE;
1113 break;
1115 success = can_city_build_unit_later(pcity, pupdate);
1116 if (!success) {
1117 /* If the city can never build this unit or its descendants,
1118 * drop it. */
1119 notify_player(pplayer, city_tile(pcity),
1120 E_CITY_CANTBUILD, ftc_server,
1121 _("%s can't build %s from the worklist. Purging..."),
1122 city_link(pcity),
1123 /* Yes, warn about the targets that's actually
1124 in the worklist, not its obsolete-closure
1125 pupdate. */
1126 utype_name_translation(ptarget));
1127 script_server_signal_emit("unit_cant_be_built", 3,
1128 API_TYPE_UNIT_TYPE, ptarget,
1129 API_TYPE_CITY, pcity,
1130 API_TYPE_STRING, "never");
1131 if (city_exist(saved_id)) {
1132 city_checked = TRUE;
1133 /* Purge this worklist item. */
1134 i--;
1135 worklist_remove(pwl, i);
1136 } else {
1137 city_checked = FALSE;
1139 } else {
1140 /* Yep, we can go after pupdate instead. Joy! */
1141 notify_player(pplayer, city_tile(pcity), E_WORKLIST, ftc_server,
1142 _("Production of %s is upgraded to %s in %s."),
1143 utype_name_translation(ptarget),
1144 utype_name_translation(pupdate),
1145 city_link(pcity));
1146 target.value.utype = pupdate;
1148 break;
1150 case VUT_IMPROVEMENT:
1152 struct impr_type *ptarget = target.value.building;
1153 struct impr_type *pupdate = building_upgrades_to(pcity, ptarget);
1155 /* If the city can never build this improvement, drop it. */
1156 success = can_city_build_improvement_later(pcity, pupdate);
1158 /* Maybe this improvement has been obsoleted by something that
1159 we can build. */
1160 if (success && pupdate == ptarget) {
1161 bool known = FALSE;
1163 /* Nope, no use. *sigh* */
1164 requirement_vector_iterate(&ptarget->reqs, preq) {
1165 if (!is_req_active(pplayer, NULL, pcity, NULL, NULL, NULL, NULL,
1166 NULL, NULL, preq, RPT_POSSIBLE)) {
1167 known = TRUE;
1168 switch (preq->source.kind) {
1169 case VUT_ADVANCE:
1170 if (preq->present) {
1171 notify_player(pplayer, city_tile(pcity),
1172 E_CITY_CANTBUILD, ftc_server,
1173 _("%s can't build %s from the worklist; "
1174 "tech %s not yet available. Postponing..."),
1175 city_link(pcity),
1176 city_improvement_name_translation(pcity, ptarget),
1177 advance_name_translation
1178 (preq->source.value.advance));
1179 script_server_signal_emit("building_cant_be_built", 3,
1180 API_TYPE_BUILDING_TYPE, ptarget,
1181 API_TYPE_CITY, pcity,
1182 API_TYPE_STRING, "need_tech");
1183 } else {
1184 /* While techs can be unlearned, this isn't useful feedback */
1185 success = FALSE;
1187 break;
1188 case VUT_TECHFLAG:
1189 if (preq->present) {
1190 notify_player(pplayer, city_tile(pcity),
1191 E_CITY_CANTBUILD, ftc_server,
1192 _("%s can't build %s from the worklist; "
1193 "no tech with flag \"%s\" yet available. "
1194 "Postponing..."),
1195 city_link(pcity),
1196 city_improvement_name_translation(pcity, ptarget),
1197 tech_flag_id_name(preq->source.value.techflag));
1198 script_server_signal_emit("building_cant_be_built", 3,
1199 API_TYPE_BUILDING_TYPE, ptarget,
1200 API_TYPE_CITY, pcity,
1201 API_TYPE_STRING, "need_techflag");
1202 } else {
1203 /* While techs can be unlearned, this isn't useful feedback */
1204 success = FALSE;
1206 break;
1207 case VUT_IMPROVEMENT:
1208 if (preq->present) {
1209 notify_player(pplayer, city_tile(pcity),
1210 E_CITY_CANTBUILD, ftc_server,
1211 _("%s can't build %s from the worklist; "
1212 "need to have %s first. Postponing..."),
1213 city_link(pcity),
1214 city_improvement_name_translation(pcity, ptarget),
1215 city_improvement_name_translation(pcity,
1216 preq->source.value.building));
1217 script_server_signal_emit("building_cant_be_built", 3,
1218 API_TYPE_BUILDING_TYPE, ptarget,
1219 API_TYPE_CITY, pcity,
1220 API_TYPE_STRING, "need_building");
1221 } else {
1222 notify_player(pplayer, city_tile(pcity),
1223 E_CITY_CANTBUILD, ftc_server,
1224 _("%s can't build %s from the worklist; "
1225 "need to not have %s. Postponing..."),
1226 city_link(pcity),
1227 city_improvement_name_translation(pcity, ptarget),
1228 city_improvement_name_translation(pcity,
1229 preq->source.value.building));
1230 script_server_signal_emit("building_cant_be_built", 3,
1231 API_TYPE_BUILDING_TYPE, ptarget,
1232 API_TYPE_CITY, pcity,
1233 API_TYPE_STRING, "have_building");
1235 break;
1236 case VUT_GOVERNMENT:
1237 if (preq->present) {
1238 notify_player(pplayer, city_tile(pcity),
1239 E_CITY_CANTBUILD, ftc_server,
1240 _("%s can't build %s from the worklist; "
1241 "it needs %s government. Postponing..."),
1242 city_link(pcity),
1243 city_improvement_name_translation(pcity, ptarget),
1244 government_name_translation(preq->source.value.govern));
1245 script_server_signal_emit("building_cant_be_built", 3,
1246 API_TYPE_BUILDING_TYPE, ptarget,
1247 API_TYPE_CITY, pcity,
1248 API_TYPE_STRING, "need_government");
1249 } else {
1250 notify_player(pplayer, city_tile(pcity),
1251 E_CITY_CANTBUILD, ftc_server,
1252 _("%s can't build %s from the worklist; "
1253 "it cannot have %s government. Postponing..."),
1254 city_link(pcity),
1255 city_improvement_name_translation(pcity, ptarget),
1256 government_name_translation(preq->source.value.govern));
1257 script_server_signal_emit("building_cant_be_built", 3,
1258 API_TYPE_BUILDING_TYPE, ptarget,
1259 API_TYPE_CITY, pcity,
1260 API_TYPE_STRING, "have_government");
1262 break;
1263 case VUT_ACHIEVEMENT:
1264 if (preq->present) {
1265 notify_player(pplayer, city_tile(pcity),
1266 E_CITY_CANTBUILD, ftc_server,
1267 _("%s can't build %s from the worklist; "
1268 "it needs \"%s\" achievement. Postponing..."),
1269 city_link(pcity),
1270 city_improvement_name_translation(pcity, ptarget),
1271 achievement_name_translation(preq->source.value.achievement));
1272 script_server_signal_emit("building_cant_be_built", 3,
1273 API_TYPE_BUILDING_TYPE, ptarget,
1274 API_TYPE_CITY, pcity,
1275 API_TYPE_STRING, "need_achievement");
1276 } else {
1277 /* Can't unachieve things. */
1278 success = FALSE;
1280 break;
1281 case VUT_EXTRA:
1282 if (preq->present) {
1283 notify_player(pplayer, city_tile(pcity),
1284 E_CITY_CANTBUILD, ftc_server,
1285 Q_("?extra:%s can't build %s from the worklist; "
1286 "%s is required. Postponing..."),
1287 city_link(pcity),
1288 city_improvement_name_translation(pcity, ptarget),
1289 extra_name_translation(preq->source.value.extra));
1290 script_server_signal_emit("building_cant_be_built", 3,
1291 API_TYPE_BUILDING_TYPE, ptarget,
1292 API_TYPE_CITY, pcity,
1293 API_TYPE_STRING, "need_extra");
1294 } else {
1295 notify_player(pplayer, city_tile(pcity),
1296 E_CITY_CANTBUILD, ftc_server,
1297 Q_("?extra:%s can't build %s from the worklist; "
1298 "%s is prohibited. Postponing..."),
1299 city_link(pcity),
1300 city_improvement_name_translation(pcity, ptarget),
1301 extra_name_translation(preq->source.value.extra));
1302 script_server_signal_emit("building_cant_be_built", 3,
1303 API_TYPE_BUILDING_TYPE, ptarget,
1304 API_TYPE_CITY, pcity,
1305 API_TYPE_STRING, "have_extra");
1307 break;
1308 case VUT_TERRAIN:
1309 if (preq->present) {
1310 notify_player(pplayer, city_tile(pcity),
1311 E_CITY_CANTBUILD, ftc_server,
1312 Q_("?terrain:%s can't build %s from the worklist; "
1313 "%s terrain is required. Postponing..."),
1314 city_link(pcity),
1315 city_improvement_name_translation(pcity, ptarget),
1316 terrain_name_translation(preq->source.value.terrain));
1317 script_server_signal_emit("building_cant_be_built", 3,
1318 API_TYPE_BUILDING_TYPE, ptarget,
1319 API_TYPE_CITY, pcity,
1320 API_TYPE_STRING, "need_terrain");
1321 } else {
1322 notify_player(pplayer, city_tile(pcity),
1323 E_CITY_CANTBUILD, ftc_server,
1324 Q_("?terrain:%s can't build %s from the worklist; "
1325 "%s terrain is prohibited. Postponing..."),
1326 city_link(pcity),
1327 city_improvement_name_translation(pcity, ptarget),
1328 terrain_name_translation(preq->source.value.terrain));
1329 script_server_signal_emit("building_cant_be_built", 3,
1330 API_TYPE_BUILDING_TYPE, ptarget,
1331 API_TYPE_CITY, pcity,
1332 API_TYPE_STRING, "have_terrain");
1334 break;
1335 case VUT_RESOURCE:
1336 if (preq->present) {
1337 notify_player(pplayer, city_tile(pcity),
1338 E_CITY_CANTBUILD, ftc_server,
1339 Q_("?resource:%s can't build %s from the worklist; "
1340 "%s is required. Postponing..."),
1341 city_link(pcity),
1342 city_improvement_name_translation(pcity, ptarget),
1343 resource_name_translation(preq->source.value.resource));
1344 script_server_signal_emit("building_cant_be_built", 3,
1345 API_TYPE_BUILDING_TYPE, ptarget,
1346 API_TYPE_CITY, pcity,
1347 API_TYPE_STRING, "need_resource");
1348 } else {
1349 /* FIXME: Yes, it's possible to destroy a resource, but the
1350 * player probably wanted us to have purged, rather than
1351 * postponed. Purging should be separate from impossible. */
1352 notify_player(pplayer, city_tile(pcity),
1353 E_CITY_CANTBUILD, ftc_server,
1354 Q_("?resource:%s can't build %s from the worklist; "
1355 "%s is prohibited. Postponing..."),
1356 city_link(pcity),
1357 city_improvement_name_translation(pcity, ptarget),
1358 resource_name_translation(preq->source.value.resource));
1359 script_server_signal_emit("building_cant_be_built", 3,
1360 API_TYPE_BUILDING_TYPE, ptarget,
1361 API_TYPE_CITY, pcity,
1362 API_TYPE_STRING, "have_resource");
1364 break;
1365 case VUT_NATION:
1366 /* Nation can be required at Alliance range, which may change. */
1367 if (preq->present) {
1368 notify_player(pplayer, city_tile(pcity),
1369 E_CITY_CANTBUILD, ftc_server,
1370 /* TRANS: "%s nation" is adjective */
1371 Q_("?nation:%s can't build %s from the worklist; "
1372 "%s nation is required. Postponing..."),
1373 city_link(pcity),
1374 city_improvement_name_translation(pcity, ptarget),
1375 nation_adjective_translation(preq->source.value.nation));
1376 script_server_signal_emit("building_cant_be_built", 3,
1377 API_TYPE_BUILDING_TYPE, ptarget,
1378 API_TYPE_CITY, pcity,
1379 API_TYPE_STRING, "need_nation");
1380 } else {
1381 notify_player(pplayer, city_tile(pcity),
1382 E_CITY_CANTBUILD, ftc_server,
1383 Q_("?nation:%s can't build %s from the worklist; "
1384 "%s nation is prohibited. Postponing..."),
1385 city_link(pcity),
1386 city_improvement_name_translation(pcity, ptarget),
1387 nation_adjective_translation(preq->source.value.nation));
1388 script_server_signal_emit("building_cant_be_built", 3,
1389 API_TYPE_BUILDING_TYPE, ptarget,
1390 API_TYPE_CITY, pcity,
1391 API_TYPE_STRING, "have_nation");
1393 break;
1394 case VUT_NATIONGROUP:
1395 /* Nation group can be required at Alliance range, which may
1396 * change. */
1397 if (preq->present) {
1398 notify_player(pplayer, city_tile(pcity),
1399 E_CITY_CANTBUILD, ftc_server,
1400 /* TRANS: "%s nation" is adjective */
1401 Q_("?ngroup:%s can't build %s from the worklist; "
1402 "%s nation is required. Postponing..."),
1403 city_link(pcity),
1404 city_improvement_name_translation(pcity, ptarget),
1405 nation_group_name_translation(preq->source.value.nationgroup));
1406 script_server_signal_emit("building_cant_be_built", 3,
1407 API_TYPE_BUILDING_TYPE, ptarget,
1408 API_TYPE_CITY, pcity,
1409 API_TYPE_STRING, "need_nationgroup");
1410 } else {
1411 notify_player(pplayer, city_tile(pcity),
1412 E_CITY_CANTBUILD, ftc_server,
1413 Q_("?ngroup:%s can't build %s from the worklist; "
1414 "%s nation is prohibited. Postponing..."),
1415 city_link(pcity),
1416 city_improvement_name_translation(pcity, ptarget),
1417 nation_group_name_translation(preq->source.value.nationgroup));
1418 script_server_signal_emit("building_cant_be_built", 3,
1419 API_TYPE_BUILDING_TYPE, ptarget,
1420 API_TYPE_CITY, pcity,
1421 API_TYPE_STRING, "have_nationgroup");
1423 break;
1424 case VUT_STYLE:
1425 /* FIXME: City styles sometimes change over time, but it isn't
1426 * entirely under player control. Probably better to purge
1427 * with useful explanation. */
1428 if (preq->present) {
1429 notify_player(pplayer, city_tile(pcity),
1430 E_CITY_CANTBUILD, ftc_server,
1431 _("%s can't build %s from the worklist; "
1432 "only %s style cities may build this. Postponing..."),
1433 city_link(pcity),
1434 city_improvement_name_translation(pcity, ptarget),
1435 style_name_translation(preq->source.value.style));
1436 script_server_signal_emit("building_cant_be_built", 3,
1437 API_TYPE_BUILDING_TYPE, ptarget,
1438 API_TYPE_CITY, pcity,
1439 API_TYPE_STRING, "need_style");
1440 } else {
1441 notify_player(pplayer, city_tile(pcity),
1442 E_CITY_CANTBUILD, ftc_server,
1443 _("%s can't build %s from the worklist; "
1444 "%s style cities may not build this. Postponing..."),
1445 city_link(pcity),
1446 city_improvement_name_translation(pcity, ptarget),
1447 style_name_translation(preq->source.value.style));
1448 script_server_signal_emit("building_cant_be_built", 3,
1449 API_TYPE_BUILDING_TYPE, ptarget,
1450 API_TYPE_CITY, pcity,
1451 API_TYPE_STRING, "have_style");
1453 break;
1454 case VUT_NATIONALITY:
1455 /* FIXME: Changing citizen nationality is hard: purging might be
1456 * more useful in this case. */
1457 if (preq->present) {
1458 notify_player(pplayer, city_tile(pcity),
1459 E_CITY_CANTBUILD, ftc_server,
1460 /* TRANS: Latter %s is citizen nationality */
1461 _("%s can't build %s from the worklist; "
1462 "only city with %s may build this. Postponing..."),
1463 city_link(pcity),
1464 city_improvement_name_translation(pcity, ptarget),
1465 nation_plural_translation(preq->source.value.nationality));
1466 script_server_signal_emit("building_cant_be_built", 3,
1467 API_TYPE_BUILDING_TYPE, ptarget,
1468 API_TYPE_CITY, pcity,
1469 API_TYPE_STRING, "need_nationality");
1470 } else {
1471 notify_player(pplayer, city_tile(pcity),
1472 E_CITY_CANTBUILD, ftc_server,
1473 /* TRANS: Latter %s is citizen nationality */
1474 _("%s can't build %s from the worklist; "
1475 "only city without %s may build this. Postponing..."),
1476 city_link(pcity),
1477 city_improvement_name_translation(pcity, ptarget),
1478 nation_plural_translation(preq->source.value.nationality));
1479 script_server_signal_emit("building_cant_be_built", 3,
1480 API_TYPE_BUILDING_TYPE, ptarget,
1481 API_TYPE_CITY, pcity,
1482 API_TYPE_STRING, "have_nationality");
1484 break;
1485 case VUT_DIPLREL:
1486 if (preq->present) {
1487 notify_player(pplayer, city_tile(pcity),
1488 E_CITY_CANTBUILD, ftc_server,
1489 /* TRANS: '%s' is a wide range of relationships;
1490 * e.g., 'Peace', 'Never met', 'Is foreign',
1491 * 'Hosts embassy', 'Provided Casus Belli' */
1492 _("%s can't build %s from the worklist; "
1493 "the relationship '%s' is required."
1494 " Postponing..."),
1495 city_link(pcity),
1496 city_improvement_name_translation(pcity,
1497 ptarget),
1498 diplrel_name_translation(
1499 preq->source.value.diplrel));
1500 script_server_signal_emit("building_cant_be_built", 3,
1501 API_TYPE_BUILDING_TYPE, ptarget,
1502 API_TYPE_CITY, pcity,
1503 API_TYPE_STRING, "need_diplrel");
1504 } else {
1505 notify_player(pplayer, city_tile(pcity),
1506 E_CITY_CANTBUILD, ftc_server,
1507 _("%s can't build %s from the worklist; "
1508 "the relationship '%s' is prohibited."
1509 " Postponing..."),
1510 city_link(pcity),
1511 city_improvement_name_translation(pcity,
1512 ptarget),
1513 diplrel_name_translation(
1514 preq->source.value.diplrel));
1515 script_server_signal_emit("building_cant_be_built", 3,
1516 API_TYPE_BUILDING_TYPE, ptarget,
1517 API_TYPE_CITY, pcity,
1518 API_TYPE_STRING, "have_diplrel");
1520 break;
1521 case VUT_MINSIZE:
1522 if (preq->present) {
1523 notify_player(pplayer, city_tile(pcity),
1524 E_CITY_CANTBUILD, ftc_server,
1525 _("%s can't build %s from the worklist; "
1526 "city must be of size %d or larger. "
1527 "Postponing..."),
1528 city_link(pcity),
1529 city_improvement_name_translation(pcity, ptarget),
1530 preq->source.value.minsize);
1531 script_server_signal_emit("building_cant_be_built", 3,
1532 API_TYPE_BUILDING_TYPE, ptarget,
1533 API_TYPE_CITY, pcity,
1534 API_TYPE_STRING, "need_minsize");
1535 } else {
1536 notify_player(pplayer, city_tile(pcity),
1537 E_CITY_CANTBUILD, ftc_server,
1538 _("%s can't build %s from the worklist; "
1539 "city must be of size %d or smaller."
1540 "Postponing..."),
1541 city_link(pcity),
1542 city_improvement_name_translation(pcity, ptarget),
1543 (preq->source.value.minsize - 1));
1544 script_server_signal_emit("building_cant_be_built", 3,
1545 API_TYPE_BUILDING_TYPE, ptarget,
1546 API_TYPE_CITY, pcity,
1547 API_TYPE_STRING, "need_minsize");
1549 break;
1550 case VUT_MINCULTURE:
1551 if (preq->present) {
1552 notify_player(pplayer, city_tile(pcity),
1553 E_CITY_CANTBUILD, ftc_server,
1554 _("%s can't build %s from the worklist; "
1555 "city must have culture of %d. Postponing..."),
1556 city_link(pcity),
1557 city_improvement_name_translation(pcity, ptarget),
1558 preq->source.value.minculture);
1559 script_server_signal_emit("building_cant_be_built", 3,
1560 API_TYPE_BUILDING_TYPE, ptarget,
1561 API_TYPE_CITY, pcity,
1562 API_TYPE_STRING, "need_minculture");
1563 } else {
1564 /* What has been written may not be unwritten. */
1565 success = FALSE;
1567 break;
1568 case VUT_MAXTILEUNITS:
1569 if (preq->present) {
1570 notify_player(pplayer, city_tile(pcity),
1571 E_CITY_CANTBUILD, ftc_server,
1572 PL_("%s can't build %s from the worklist; "
1573 "more than %d unit on tile."
1574 " Postponing...",
1575 "%s can't build %s from the worklist; "
1576 "more than %d units on tile."
1577 " Postponing...",
1578 preq->source.value.max_tile_units),
1579 city_link(pcity),
1580 city_improvement_name_translation(pcity,
1581 ptarget),
1582 preq->source.value.max_tile_units);
1583 script_server_signal_emit("building_cant_be_built", 3,
1584 API_TYPE_BUILDING_TYPE, ptarget,
1585 API_TYPE_CITY, pcity,
1586 API_TYPE_STRING, "need_tileunits");
1587 } else {
1588 notify_player(pplayer, city_tile(pcity),
1589 E_CITY_CANTBUILD, ftc_server,
1590 PL_("%s can't build %s from the worklist; "
1591 "fewer than %d unit on tile."
1592 " Postponing...",
1593 "%s can't build %s from the worklist; "
1594 "fewer than %d units on tile."
1595 " Postponing...",
1596 preq->source.value.max_tile_units + 1),
1597 city_link(pcity),
1598 city_improvement_name_translation(pcity,
1599 ptarget),
1600 preq->source.value.max_tile_units + 1);
1601 script_server_signal_emit("building_cant_be_built", 3,
1602 API_TYPE_BUILDING_TYPE, ptarget,
1603 API_TYPE_CITY, pcity,
1604 API_TYPE_STRING, "need_tileunits");
1606 break;
1607 case VUT_AI_LEVEL:
1608 /* Can't change AI level. */
1609 success = FALSE;
1610 break;
1611 case VUT_TERRAINCLASS:
1612 if (preq->present) {
1613 notify_player(pplayer, city_tile(pcity),
1614 E_CITY_CANTBUILD, ftc_server,
1615 Q_("?terrainclass:%s can't build %s from the "
1616 "worklist; %s terrain is required."
1617 " Postponing..."),
1618 city_link(pcity),
1619 city_improvement_name_translation(pcity, ptarget),
1620 terrain_class_name_translation(preq->source.value.terrainclass));
1621 script_server_signal_emit("building_cant_be_built", 3,
1622 API_TYPE_BUILDING_TYPE, ptarget,
1623 API_TYPE_CITY, pcity,
1624 API_TYPE_STRING, "need_terrainclass");
1625 } else {
1626 notify_player(pplayer, city_tile(pcity),
1627 E_CITY_CANTBUILD, ftc_server,
1628 Q_("?terrainclass:%s can't build %s from the "
1629 "worklist; %s terrain is prohibited."
1630 " Postponing..."),
1631 city_link(pcity),
1632 city_improvement_name_translation(pcity, ptarget),
1633 terrain_class_name_translation(preq->source.value.terrainclass));
1634 script_server_signal_emit("building_cant_be_built", 3,
1635 API_TYPE_BUILDING_TYPE, ptarget,
1636 API_TYPE_CITY, pcity,
1637 API_TYPE_STRING, "have_terrainclass");
1639 break;
1640 case VUT_TERRFLAG:
1641 if (preq->present) {
1642 notify_player(pplayer, city_tile(pcity),
1643 E_CITY_CANTBUILD, ftc_server,
1644 _("%s can't build %s from the worklist; "
1645 "terrain with \"%s\" flag is required. "
1646 "Postponing..."),
1647 city_link(pcity),
1648 city_improvement_name_translation(pcity, ptarget),
1649 terrain_flag_id_name(preq->source.value.terrainflag));
1650 script_server_signal_emit("building_cant_be_built", 3,
1651 API_TYPE_BUILDING_TYPE, ptarget,
1652 API_TYPE_CITY, pcity,
1653 API_TYPE_STRING, "need_terrainflag");
1654 } else {
1655 notify_player(pplayer, city_tile(pcity),
1656 E_CITY_CANTBUILD, ftc_server,
1657 _("%s can't build %s from the worklist; "
1658 "terrain with \"%s\" flag is prohibited. "
1659 "Postponing..."),
1660 city_link(pcity),
1661 city_improvement_name_translation(pcity, ptarget),
1662 terrain_flag_id_name(preq->source.value.terrainflag));
1663 script_server_signal_emit("building_cant_be_built", 3,
1664 API_TYPE_BUILDING_TYPE, ptarget,
1665 API_TYPE_CITY, pcity,
1666 API_TYPE_STRING, "have_terrainflag");
1668 break;
1669 case VUT_BASEFLAG:
1670 if (preq->present) {
1671 notify_player(pplayer, city_tile(pcity),
1672 E_CITY_CANTBUILD, ftc_server,
1673 _("%s can't build %s from the worklist; "
1674 "base with \"%s\" flag is required. "
1675 "Postponing..."),
1676 city_link(pcity),
1677 city_improvement_name_translation(pcity, ptarget),
1678 base_flag_id_name(preq->source.value.baseflag));
1679 script_server_signal_emit("building_cant_be_built", 3,
1680 API_TYPE_BUILDING_TYPE, ptarget,
1681 API_TYPE_CITY, pcity,
1682 API_TYPE_STRING, "need_baseflag");
1683 } else {
1684 notify_player(pplayer, city_tile(pcity),
1685 E_CITY_CANTBUILD, ftc_server,
1686 _("%s can't build %s from the worklist; "
1687 "base with \"%s\" flag is prohibited. "
1688 "Postponing..."),
1689 city_link(pcity),
1690 city_improvement_name_translation(pcity, ptarget),
1691 base_flag_id_name(preq->source.value.baseflag));
1692 script_server_signal_emit("building_cant_be_built", 3,
1693 API_TYPE_BUILDING_TYPE, ptarget,
1694 API_TYPE_CITY, pcity,
1695 API_TYPE_STRING, "have_baseflag");
1697 break;
1698 case VUT_ROADFLAG:
1699 if (preq->present) {
1700 notify_player(pplayer, city_tile(pcity),
1701 E_CITY_CANTBUILD, ftc_server,
1702 _("%s can't build %s from the worklist; "
1703 "road with \"%s\" flag is required. "
1704 "Postponing..."),
1705 city_link(pcity),
1706 city_improvement_name_translation(pcity, ptarget),
1707 road_flag_id_name(preq->source.value.roadflag));
1708 script_server_signal_emit("building_cant_be_built", 3,
1709 API_TYPE_BUILDING_TYPE, ptarget,
1710 API_TYPE_CITY, pcity,
1711 API_TYPE_STRING, "need_roadflag");
1712 } else {
1713 notify_player(pplayer, city_tile(pcity),
1714 E_CITY_CANTBUILD, ftc_server,
1715 _("%s can't build %s from the worklist; "
1716 "road with \"%s\" flag is prohibited. "
1717 "Postponing..."),
1718 city_link(pcity),
1719 city_improvement_name_translation(pcity, ptarget),
1720 road_flag_id_name(preq->source.value.roadflag));
1721 script_server_signal_emit("building_cant_be_built", 3,
1722 API_TYPE_BUILDING_TYPE, ptarget,
1723 API_TYPE_CITY, pcity,
1724 API_TYPE_STRING, "have_roadflag");
1726 break;
1727 case VUT_EXTRAFLAG:
1728 if (preq->present) {
1729 notify_player(pplayer, city_tile(pcity),
1730 E_CITY_CANTBUILD, ftc_server,
1731 _("%s can't build %s from the worklist; "
1732 "extra with \"%s\" flag is required. "
1733 "Postponing..."),
1734 city_link(pcity),
1735 city_improvement_name_translation(pcity, ptarget),
1736 extra_flag_id_translated_name(preq->source.value.extraflag));
1737 script_server_signal_emit("building_cant_be_built", 3,
1738 API_TYPE_BUILDING_TYPE, ptarget,
1739 API_TYPE_CITY, pcity,
1740 API_TYPE_STRING, "need_extraflag");
1741 } else {
1742 notify_player(pplayer, city_tile(pcity),
1743 E_CITY_CANTBUILD, ftc_server,
1744 _("%s can't build %s from the worklist; "
1745 "extra with \"%s\" flag is prohibited. "
1746 "Postponing..."),
1747 city_link(pcity),
1748 city_improvement_name_translation(pcity, ptarget),
1749 extra_flag_id_translated_name(preq->source.value.extraflag));
1750 script_server_signal_emit("building_cant_be_built", 3,
1751 API_TYPE_BUILDING_TYPE, ptarget,
1752 API_TYPE_CITY, pcity,
1753 API_TYPE_STRING, "have_extraflag");
1755 break;
1756 case VUT_UTYPE:
1757 case VUT_UTFLAG:
1758 case VUT_UCLASS:
1759 case VUT_UCFLAG:
1760 case VUT_MINVETERAN:
1761 case VUT_UNITSTATE:
1762 case VUT_MINMOVES:
1763 case VUT_MINHP:
1764 case VUT_OTYPE:
1765 case VUT_SPECIALIST:
1766 case VUT_TERRAINALTER: /* XXX could do this in principle */
1767 case VUT_CITYTILE:
1768 /* Will only happen with a bogus ruleset. */
1769 log_error("worklist_change_build_target() has bogus preq");
1770 break;
1771 case VUT_MINYEAR:
1772 if (preq->present) {
1773 notify_player(pplayer, city_tile(pcity),
1774 E_CITY_CANTBUILD, ftc_server,
1775 /* TRANS: last %s is a date */
1776 _("%s can't build %s from the worklist; "
1777 "only available from %s. Postponing..."),
1778 city_link(pcity),
1779 city_improvement_name_translation(pcity, ptarget),
1780 textyear(preq->source.value.minyear));
1781 script_server_signal_emit("building_cant_be_built", 3,
1782 API_TYPE_BUILDING_TYPE, ptarget,
1783 API_TYPE_CITY, pcity,
1784 API_TYPE_STRING, "need_minyear");
1785 } else {
1786 /* Can't go back in time. */
1787 success = FALSE;
1789 break;
1790 case VUT_TOPO:
1791 if (preq->present) {
1792 notify_player(pplayer, city_tile(pcity),
1793 E_CITY_CANTBUILD, ftc_server,
1794 _("%s can't build %s from the workist; "
1795 "only available in worlds with %s map."),
1796 city_link(pcity),
1797 city_improvement_name_translation(pcity, ptarget),
1798 _(topo_flag_name(preq->source.value.topo_property)));
1799 script_server_signal_emit("building_cant_be_built", 3,
1800 API_TYPE_BUILDING_TYPE, ptarget,
1801 API_TYPE_CITY, pcity,
1802 API_TYPE_STRING, "need_topo");
1804 success = FALSE;
1805 break;
1806 case VUT_AGE:
1807 if (preq->present) {
1808 notify_player(pplayer, city_tile(pcity),
1809 E_CITY_CANTBUILD, ftc_server,
1810 _("%s can't build %s from the worklist; "
1811 "only available once %d turns old. Postponing..."),
1812 city_link(pcity),
1813 city_improvement_name_translation(pcity, ptarget),
1814 preq->source.value.age);
1815 script_server_signal_emit("building_cant_be_built", 3,
1816 API_TYPE_BUILDING_TYPE, ptarget,
1817 API_TYPE_CITY, pcity,
1818 API_TYPE_STRING, "need_age");
1819 } else {
1820 /* Can't go back in time. */
1821 success = FALSE;
1823 break;
1824 case VUT_NONE:
1825 case VUT_COUNT:
1826 fc_assert_ret_val_msg(FALSE, TRUE,
1827 "worklist_change_build_target() "
1828 "called with invalid preq");
1829 break;
1830 /* No default handling here, as we want compiler warning
1831 * if new requirement type is added to enum and it's not handled
1832 * here. */
1834 break;
1837 /* Almost all cases emit signal in the end, so city check needed. */
1838 if (!city_exist(saved_id)) {
1839 /* Some script has removed city */
1840 return FALSE;
1842 city_checked = TRUE;
1844 } requirement_vector_iterate_end;
1846 if (!known) {
1847 /* This shouldn't happen...
1848 FIXME: make can_city_build_improvement_now() return a reason enum. */
1849 notify_player(pplayer, city_tile(pcity),
1850 E_CITY_CANTBUILD, ftc_server,
1851 _("%s can't build %s from the worklist; "
1852 "reason unknown! Postponing..."),
1853 city_link(pcity),
1854 city_improvement_name_translation(pcity, ptarget));
1856 } else if (success) {
1857 /* Hey, we can upgrade the improvement! */
1858 notify_player(pplayer, city_tile(pcity), E_WORKLIST, ftc_server,
1859 _("Production of %s is upgraded to %s in %s."),
1860 city_improvement_name_translation(pcity, ptarget),
1861 city_improvement_name_translation(pcity, pupdate),
1862 city_link(pcity));
1863 target.value.building = pupdate;
1864 success = TRUE;
1867 if (!success) {
1868 /* Never in a million years. */
1869 notify_player(pplayer, city_tile(pcity),
1870 E_CITY_CANTBUILD, ftc_server,
1871 _("%s can't build %s from the worklist. Purging..."),
1872 city_link(pcity),
1873 city_improvement_name_translation(pcity, ptarget));
1874 script_server_signal_emit("building_cant_be_built", 3,
1875 API_TYPE_BUILDING_TYPE, ptarget,
1876 API_TYPE_CITY, pcity,
1877 API_TYPE_STRING, "never");
1878 if (city_exist(saved_id)) {
1879 city_checked = TRUE;
1880 /* Purge this worklist item. */
1881 i--;
1882 worklist_remove(pwl, i);
1883 } else {
1884 city_checked = FALSE;
1887 break;
1889 default:
1890 /* skip useless target */
1891 log_error("worklist_change_build_target() has unrecognized "
1892 "target kind (%d)", target.kind);
1893 break;
1895 } /* while */
1897 if (success) {
1898 /* All okay. Switch targets. */
1899 change_build_target(pplayer, pcity, &target, E_WORKLIST);
1901 /* i is the index immediately _after_ the item we're changing to.
1902 Remove the (i-1)th item from the worklist. */
1903 worklist_remove(pwl, i - 1);
1906 if (worklist_is_empty(pwl)) {
1907 /* There *was* something in the worklist, but it's empty now. Bug the
1908 player about it. */
1909 notify_player(pplayer, city_tile(pcity), E_WORKLIST, ftc_server,
1910 /* TRANS: The <city> worklist .... */
1911 _("The %s worklist is now empty."),
1912 city_link(pcity));
1915 return success;
1918 /**************************************************************************
1919 Assuming we just finished building something, find something new to
1920 build. The policy is: use the worklist if we can; if not, try not
1921 changing; if we must change, get desparate and use the AI advisor.
1922 **************************************************************************/
1923 void choose_build_target(struct player *pplayer, struct city *pcity)
1925 /* Pick the next thing off the worklist. */
1926 if (worklist_change_build_target(pplayer, pcity)) {
1927 return;
1930 /* Try building the same thing again. Repeat building doesn't require a
1931 * call to change_build_target, so just return. */
1932 switch (pcity->production.kind) {
1933 case VUT_UTYPE:
1934 /* We can build a unit again unless it's unique or we have lost the tech. */
1935 if (!utype_has_flag(pcity->production.value.utype, UTYF_UNIQUE)
1936 && can_city_build_unit_now(pcity, pcity->production.value.utype)) {
1937 log_debug("%s repeats building %s", city_name_get(pcity),
1938 utype_rule_name(pcity->production.value.utype));
1939 return;
1941 break;
1942 case VUT_IMPROVEMENT:
1943 if (can_city_build_improvement_now(pcity, pcity->production.value.building)) {
1944 /* We can build space and coinage again, and possibly others. */
1945 log_debug("%s repeats building %s", city_name_get(pcity),
1946 improvement_rule_name(pcity->production.value.building));
1947 return;
1949 break;
1950 default:
1951 /* fallthru */
1952 break;
1955 /* Find *something* to do! */
1956 log_debug("Trying advisor_choose_build.");
1957 advisor_choose_build(pplayer, pcity);
1958 log_debug("Advisor_choose_build didn't kill us.");
1961 /**************************************************************************
1962 Follow the list of replacement buildings until we hit something that
1963 we can build. Returns NULL if we can't upgrade at all (including if the
1964 original building is unbuildable).
1965 **************************************************************************/
1966 static struct impr_type *building_upgrades_to(struct city *pcity,
1967 struct impr_type *pimprove)
1969 struct impr_type *check = pimprove;
1970 struct impr_type *best_upgrade = NULL;
1972 if (!can_city_build_improvement_direct(pcity, check)) {
1973 return NULL;
1975 while (valid_improvement(check = improvement_replacement(check))) {
1976 if (can_city_build_improvement_direct(pcity, check)) {
1977 best_upgrade = check;
1981 return best_upgrade;
1984 /**************************************************************************
1985 Try to upgrade production in pcity.
1986 **************************************************************************/
1987 static void upgrade_building_prod(struct city *pcity)
1989 struct impr_type *producing = pcity->production.value.building;
1990 struct impr_type *upgrading = building_upgrades_to(pcity, producing);
1992 if (upgrading && can_city_build_improvement_now(pcity, upgrading)) {
1993 notify_player(city_owner(pcity), city_tile(pcity),
1994 E_UNIT_UPGRADED, ftc_server,
1995 _("Production of %s is upgraded to %s in %s."),
1996 improvement_name_translation(producing),
1997 improvement_name_translation(upgrading),
1998 city_link(pcity));
1999 pcity->production.kind = VUT_IMPROVEMENT;
2000 pcity->production.value.building = upgrading;
2004 /**************************************************************************
2005 Follow the list of obsoleted_by units until we hit something that
2006 we can build. Return NULL when we can't upgrade at all. NB: returning
2007 something doesn't guarantee that pcity really _can_ build it; just that
2008 pcity can't build whatever _obsoletes_ it.
2010 FIXME: this function is a duplicate of can_upgrade_unittype.
2011 **************************************************************************/
2012 static struct unit_type *unit_upgrades_to(struct city *pcity,
2013 struct unit_type *punittype)
2015 struct unit_type *check = punittype;
2016 struct unit_type *best_upgrade = U_NOT_OBSOLETED;
2018 if (!can_city_build_unit_direct(pcity, punittype)) {
2019 return U_NOT_OBSOLETED;
2021 while ((check = check->obsoleted_by) != U_NOT_OBSOLETED) {
2022 if (can_city_build_unit_direct(pcity, check)) {
2023 best_upgrade = check;
2027 return best_upgrade;
2030 /**************************************************************************
2031 Try to upgrade production in pcity.
2032 **************************************************************************/
2033 static void upgrade_unit_prod(struct city *pcity)
2035 struct unit_type *producing = pcity->production.value.utype;
2036 struct unit_type *upgrading = unit_upgrades_to(pcity, producing);
2038 if (upgrading && can_city_build_unit_direct(pcity, upgrading)) {
2039 notify_player(city_owner(pcity), city_tile(pcity),
2040 E_UNIT_UPGRADED, ftc_server,
2041 _("Production of %s is upgraded to %s in %s."),
2042 utype_name_translation(producing),
2043 utype_name_translation(upgrading),
2044 city_link(pcity));
2045 pcity->production.value.utype = upgrading;
2049 /**************************************************************************
2050 Disband units if we don't have enough shields to support them. Returns
2051 FALSE if the _city_ is disbanded as a result.
2052 **************************************************************************/
2053 static bool city_distribute_surplus_shields(struct player *pplayer,
2054 struct city *pcity)
2056 if (pcity->surplus[O_SHIELD] < 0) {
2057 unit_list_iterate_safe(pcity->units_supported, punit) {
2058 if (utype_upkeep_cost(unit_type_get(punit), pplayer, O_SHIELD) > 0
2059 && pcity->surplus[O_SHIELD] < 0
2060 && !unit_has_type_flag(punit, UTYF_UNDISBANDABLE)) {
2061 notify_player(pplayer, city_tile(pcity),
2062 E_UNIT_LOST_MISC, ftc_server,
2063 _("%s can't upkeep %s, unit disbanded."),
2064 city_link(pcity), unit_link(punit));
2065 handle_unit_disband(pplayer, punit->id);
2066 /* pcity->surplus[O_SHIELD] is automatically updated. */
2068 } unit_list_iterate_safe_end;
2071 if (pcity->surplus[O_SHIELD] < 0) {
2072 /* Special case: UTYF_UNDISBANDABLE. This nasty unit won't go so easily.
2073 * It'd rather make the citizens pay in blood for their failure to upkeep
2074 * it! If we make it here all normal units are already disbanded, so only
2075 * undisbandable ones remain. */
2076 unit_list_iterate_safe(pcity->units_supported, punit) {
2077 int upkeep = utype_upkeep_cost(unit_type_get(punit), pplayer, O_SHIELD);
2079 if (upkeep > 0 && pcity->surplus[O_SHIELD] < 0) {
2080 fc_assert_action(unit_has_type_flag(punit, UTYF_UNDISBANDABLE),
2081 continue);
2082 notify_player(pplayer, city_tile(pcity),
2083 E_UNIT_LOST_MISC, ftc_server,
2084 _("Citizens in %s perish for their failure to "
2085 "upkeep %s!"),
2086 city_link(pcity), unit_link(punit));
2087 if (!city_reduce_size(pcity, 1, NULL, "upkeep_failure")) {
2088 return FALSE;
2091 /* No upkeep for the unit this turn. */
2092 pcity->surplus[O_SHIELD] += upkeep;
2094 } unit_list_iterate_safe_end;
2097 /* Now we confirm changes made last turn. */
2098 pcity->shield_stock += pcity->surplus[O_SHIELD];
2099 pcity->before_change_shields = pcity->shield_stock;
2100 pcity->last_turns_shield_surplus = pcity->surplus[O_SHIELD];
2102 return TRUE;
2105 /**************************************************************************
2106 Returns FALSE when the city is removed, TRUE otherwise.
2107 **************************************************************************/
2108 static bool city_build_building(struct player *pplayer, struct city *pcity)
2110 bool space_part;
2111 int mod;
2112 struct impr_type *pimprove = pcity->production.value.building;
2113 int saved_id = pcity->id;
2115 if (city_production_has_flag(pcity, IF_GOLD)) {
2116 fc_assert(pcity->surplus[O_SHIELD] >= 0);
2117 /* pcity->before_change_shields already contains the surplus from
2118 * this turn. */
2119 pplayer->economic.gold += pcity->before_change_shields;
2120 pcity->before_change_shields = 0;
2121 pcity->shield_stock = 0;
2122 choose_build_target(pplayer, pcity);
2123 return TRUE;
2125 upgrade_building_prod(pcity);
2127 if (!can_city_build_improvement_now(pcity, pimprove)) {
2128 notify_player(pplayer, city_tile(pcity), E_CITY_CANTBUILD, ftc_server,
2129 _("%s is building %s, which is no longer available."),
2130 city_link(pcity),
2131 city_improvement_name_translation(pcity, pimprove));
2132 script_server_signal_emit("building_cant_be_built", 3,
2133 API_TYPE_BUILDING_TYPE, pimprove,
2134 API_TYPE_CITY, pcity,
2135 API_TYPE_STRING, "unavailable");
2136 return TRUE;
2138 if (pcity->shield_stock >= impr_build_shield_cost(pimprove)) {
2139 if (is_small_wonder(pimprove)) {
2140 city_list_iterate(pplayer->cities, wcity) {
2141 if (city_has_building(wcity, pimprove)) {
2142 city_remove_improvement(wcity, pimprove);
2143 break;
2145 } city_list_iterate_end;
2148 space_part = TRUE;
2149 if (get_current_construction_bonus(pcity, EFT_SS_STRUCTURAL,
2150 RPT_CERTAIN) > 0) {
2151 pplayer->spaceship.structurals++;
2152 } else if (get_current_construction_bonus(pcity, EFT_SS_COMPONENT,
2153 RPT_CERTAIN) > 0) {
2154 pplayer->spaceship.components++;
2155 } else if (get_current_construction_bonus(pcity, EFT_SS_MODULE,
2156 RPT_CERTAIN) > 0) {
2157 pplayer->spaceship.modules++;
2158 } else {
2159 space_part = FALSE;
2160 city_add_improvement(pcity, pimprove);
2162 pcity->before_change_shields -= impr_build_shield_cost(pimprove);
2163 pcity->shield_stock -= impr_build_shield_cost(pimprove);
2164 pcity->turn_last_built = game.info.turn;
2165 /* to eliminate micromanagement */
2166 if (is_great_wonder(pimprove)) {
2167 notify_player(NULL, city_tile(pcity), E_WONDER_BUILD, ftc_server,
2168 _("The %s have finished building %s in %s."),
2169 nation_plural_for_player(pplayer),
2170 city_improvement_name_translation(pcity, pimprove),
2171 city_link(pcity));
2174 notify_player(pplayer, city_tile(pcity), E_IMP_BUILD, ftc_server,
2175 _("%s has finished building %s."),
2176 city_link(pcity), improvement_name_translation(pimprove));
2177 script_server_signal_emit("building_built", 2,
2178 API_TYPE_BUILDING_TYPE, pimprove,
2179 API_TYPE_CITY, pcity);
2181 if (!city_exist(saved_id)) {
2182 /* Script removed city */
2183 return FALSE;
2186 /* Call this function since some buildings may change the
2187 * the vision range of a city */
2188 city_refresh_vision(pcity);
2190 if ((mod = get_current_construction_bonus(pcity, EFT_GIVE_IMM_TECH,
2191 RPT_CERTAIN))) {
2192 struct research *presearch = research_get(pplayer);
2193 char research_name[MAX_LEN_NAME * 2];
2194 int i;
2195 const char *provider = improvement_name_translation(pimprove);
2197 notify_research(presearch, NULL, E_TECH_GAIN, ftc_server,
2198 PL_("%s boosts research; you gain %d immediate "
2199 "advance.",
2200 "%s boosts research; you gain %d immediate "
2201 "advances.",
2202 mod), provider, mod);
2204 research_pretty_name(presearch, research_name, sizeof(research_name));
2205 for (i = 0; i < mod; i++) {
2206 Tech_type_id tech = give_immediate_free_tech(presearch);
2207 const char *adv_name = research_advance_name_translation(presearch, tech);
2209 notify_research(presearch, NULL, E_TECH_GAIN, ftc_server,
2210 /* TRANS: Tech from building (Darwin's Voyage) */
2211 Q_("?frombldg:Acquired %s from %s."), adv_name,
2212 provider);
2214 notify_research_embassies(presearch, NULL, E_TECH_EMBASSY, ftc_server,
2215 /* TRANS: Tech from building (Darwin's
2216 * Voyage) */
2217 Q_("?frombldg:The %s have acquired %s "
2218 "from %s."),
2219 research_name, adv_name, provider);
2222 if (space_part && pplayer->spaceship.state == SSHIP_NONE) {
2223 notify_player(NULL, city_tile(pcity), E_SPACESHIP, ftc_server,
2224 _("The %s have started building a spaceship!"),
2225 nation_plural_for_player(pplayer));
2226 pplayer->spaceship.state = SSHIP_STARTED;
2228 if (space_part) {
2229 /* space ship part build */
2230 send_spaceship_info(pplayer, NULL);
2231 } else {
2232 /* Update city data. */
2233 if (city_refresh(pcity)) {
2234 auto_arrange_workers(pcity);
2238 /* Move to the next thing in the worklist */
2239 choose_build_target(pplayer, pcity);
2242 return TRUE;
2245 /**************************************************************************
2246 Build city units. Several units can be built in one turn if the effect
2247 City_Build_Slots is used.
2248 **************************************************************************/
2249 static bool city_build_unit(struct player *pplayer, struct city *pcity)
2251 struct unit_type *utype;
2252 struct worklist *pwl = &pcity->worklist;;
2253 int unit_shield_cost, num_units, i;
2255 fc_assert_ret_val(pcity->production.kind == VUT_UTYPE, FALSE);
2257 /* If the city has already bought a unit which is now obsolete, don't try
2258 * to upgrade the production. The new unit might require more shields, which
2259 * would be bad if it was bought to urgently defend a city. (Equally it
2260 * might be the same cost or cheaper, but tough; you hurried the unit so
2261 * you miss out on technological advances.) */
2262 if (city_can_change_build(pcity)) {
2263 upgrade_unit_prod(pcity);
2266 utype = pcity->production.value.utype;
2267 unit_shield_cost = utype_build_shield_cost(utype);
2269 /* We must make a special case for barbarians here, because they are
2270 so dumb. Really. They don't know the prerequisite techs for units
2271 they build!! - Per */
2272 if (!can_city_build_unit_direct(pcity, utype)
2273 && !is_barbarian(pplayer)) {
2274 notify_player(pplayer, city_tile(pcity), E_CITY_CANTBUILD, ftc_server,
2275 _("%s is building %s, which is no longer available."),
2276 city_link(pcity), utype_name_translation(utype));
2278 /* Log before signal emitting, so pointers are certainly valid */
2279 log_verbose("%s %s tried to build %s, which is not available.",
2280 nation_rule_name(nation_of_city(pcity)),
2281 city_name_get(pcity), utype_rule_name(utype));
2282 script_server_signal_emit("unit_cant_be_built", 3,
2283 API_TYPE_UNIT_TYPE, utype,
2284 API_TYPE_CITY, pcity,
2285 API_TYPE_STRING, "unavailable");
2286 return TRUE;
2289 if (pcity->shield_stock >= unit_shield_cost) {
2290 int pop_cost = utype_pop_value(utype);
2291 struct unit *punit;
2292 int saved_city_id = pcity->id;
2294 /* Should we disband the city? -- Massimo */
2295 if (city_size_get(pcity) == pop_cost
2296 && is_city_option_set(pcity, CITYO_DISBAND)) {
2297 return !disband_city(pcity);
2300 if (city_size_get(pcity) <= pop_cost) {
2301 notify_player(pplayer, city_tile(pcity), E_CITY_CANTBUILD, ftc_server,
2302 _("%s can't build %s yet."),
2303 city_link(pcity), utype_name_translation(utype));
2304 script_server_signal_emit("unit_cant_be_built", 3,
2305 API_TYPE_UNIT_TYPE, utype,
2306 API_TYPE_CITY, pcity,
2307 API_TYPE_STRING, "pop_cost");
2308 return TRUE;
2311 fc_assert(pop_cost == 0 || city_size_get(pcity) >= pop_cost);
2313 /* don't update turn_last_built if we returned above */
2314 pcity->turn_last_built = game.info.turn;
2316 /* check if we can build more than one unit (effect City_Build_Slots) */
2317 (void) city_production_build_units(pcity, FALSE, &num_units);
2319 /* We should be able to build at least one (by checks above) */
2320 fc_assert(num_units >= 1);
2322 for (i = 0; i < num_units; i++) {
2323 punit = create_unit(pplayer, pcity->tile, utype,
2324 do_make_unit_veteran(pcity, utype),
2325 pcity->id, 0);
2326 pplayer->score.units_built++;
2328 /* After we created the unit remove the citizen. This will also
2329 * rearrange the worker to take into account the extra resources
2330 * (food) needed. */
2331 if (pop_cost > 0) {
2332 city_reduce_size(pcity, pop_cost, NULL, "unit_built");
2335 /* to eliminate micromanagement, we only subtract the unit's cost */
2336 pcity->before_change_shields -= unit_shield_cost;
2337 pcity->shield_stock -= unit_shield_cost;
2339 notify_player(pplayer, city_tile(pcity), E_UNIT_BUILT, ftc_server,
2340 /* TRANS: <city> is finished building <unit/building>. */
2341 _("%s is finished building %s."),
2342 city_link(pcity), utype_name_translation(utype));
2344 if (pop_cost > 0) {
2345 /* Additional message if the unit has population cost. */
2346 notify_player(pplayer, city_tile(pcity), E_UNIT_BUILT_POP_COST,
2347 ftc_server,
2348 /* TRANS: "<unit> cost... <city> shrinks..."
2349 * Plural in "%d population", not "size %d". */
2350 PL_("%s cost %d population. %s shrinks to size %d.",
2351 "%s cost %d population. %s shrinks to size %d.",
2352 pop_cost),
2353 utype_name_translation(utype), pop_cost,
2354 city_link(pcity), city_size_get(pcity));
2357 script_server_signal_emit("unit_built", 2,
2358 API_TYPE_UNIT, punit,
2359 API_TYPE_CITY, pcity);
2361 /* check if the city still exists */
2362 if (!city_exist(saved_city_id)) {
2363 break;
2366 if (i != 0 && worklist_length(pwl) > 0) {
2367 /* remove the build unit from the worklist; it has to be one less
2368 * than units build to preserve the next build target from the
2369 * worklist */
2370 worklist_remove(pwl, 0);
2374 if (city_exist(saved_city_id)) {
2375 /* Done building this unit; time to move on to the next. */
2376 choose_build_target(pplayer, pcity);
2380 return TRUE;
2383 /**************************************************************************
2384 Returns FALSE when the city is removed, TRUE otherwise.
2385 **************************************************************************/
2386 static bool city_build_stuff(struct player *pplayer, struct city *pcity)
2388 if (!city_distribute_surplus_shields(pplayer, pcity)) {
2389 return FALSE;
2392 nullify_caravan_and_disband_plus(pcity);
2393 define_orig_production_values(pcity);
2395 switch (pcity->production.kind) {
2396 case VUT_IMPROVEMENT:
2397 return city_build_building(pplayer, pcity);
2398 case VUT_UTYPE:
2399 return city_build_unit(pplayer, pcity);
2400 default:
2401 /* must never happen! */
2402 fc_assert(FALSE);
2403 break;
2405 return FALSE;
2408 /**************************************************************************
2409 Randomly sell a building from the given list. Returns TRUE if a building
2410 was sold.
2412 NB: It is assumed that gold upkeep for the buildings has already been
2413 paid this turn, hence when a building is sold its upkeep is given back
2414 to the player.
2415 NB: The contents of 'imprs' are usually mangled by this function.
2416 NB: It is assumed that all buildings in 'imprs' can be sold.
2417 **************************************************************************/
2418 static bool sell_random_building(struct player *pplayer,
2419 struct cityimpr_list *imprs)
2421 struct cityimpr *pcityimpr;
2422 int r;
2424 fc_assert_ret_val(pplayer != NULL, FALSE);
2426 if (!imprs || cityimpr_list_size(imprs) == 0) {
2427 return FALSE;
2430 r = fc_rand(cityimpr_list_size(imprs));
2431 pcityimpr = cityimpr_list_get(imprs, r);
2433 notify_player(pplayer, city_tile(pcityimpr->pcity), E_IMP_AUCTIONED,
2434 ftc_server,
2435 _("Can't afford to maintain %s in %s, building sold!"),
2436 improvement_name_translation(pcityimpr->pimprove),
2437 city_link(pcityimpr->pcity));
2438 log_debug("%s: sold building (%s)", player_name(pplayer),
2439 improvement_name_translation(pcityimpr->pimprove));
2441 do_sell_building(pplayer, pcityimpr->pcity, pcityimpr->pimprove);
2443 cityimpr_list_remove(imprs, pcityimpr);
2445 /* Get back the gold upkeep that was already paid this turn. */
2446 pplayer->economic.gold += city_improvement_upkeep(pcityimpr->pcity,
2447 pcityimpr->pimprove);
2449 city_refresh_queue_add(pcityimpr->pcity);
2451 FC_FREE(pcityimpr);
2453 return TRUE;
2456 /**************************************************************************
2457 Randomly "sell" a unit from the given list. Returns pointer to sold unit.
2458 This pointer is not valid any more, but can be removed from the lists.
2460 NB: It is assumed that gold upkeep for the units has already been paid
2461 this turn, hence when a unit is "sold" its upkeep is given back to the
2462 player.
2463 NB: The contents of 'units' are usually mangled by this function.
2464 NB: It is assumed that all units in 'units' have positive gold upkeep.
2465 **************************************************************************/
2466 static struct unit *sell_random_unit(struct player *pplayer,
2467 struct unit_list *punitlist)
2469 struct unit *punit;
2470 int gold_upkeep, r;
2471 struct unit_list *cargo;
2473 fc_assert_ret_val(pplayer != NULL, FALSE);
2475 if (!punitlist || unit_list_size(punitlist) == 0) {
2476 return FALSE;
2479 r = fc_rand(unit_list_size(punitlist));
2480 punit = unit_list_get(punitlist, r);
2482 cargo = unit_list_new();
2484 /* Check if unit is transporting other units from punitlist,
2485 * and sell one of those (recursively) instead. */
2486 unit_list_iterate(unit_transport_cargo(punit), pcargo) {
2487 if (pcargo->upkeep[O_GOLD] > 0) { /* Optimization, do not iterate over punitlist
2488 * if we are sure that pcargo is not in it. */
2489 unit_list_iterate(punitlist, p2) {
2490 if (pcargo == p2) {
2491 unit_list_append(cargo, pcargo);
2493 } unit_list_iterate_end;
2495 } unit_list_iterate_end;
2497 if (unit_list_size(cargo) > 0) {
2498 struct unit *ret = sell_random_unit(pplayer, cargo);
2500 if (ret != NULL) {
2501 /* Remove from original list too */
2502 unit_list_remove(punitlist, ret);
2505 unit_list_destroy(cargo);
2507 return ret;
2510 unit_list_destroy(cargo);
2512 gold_upkeep = punit->upkeep[O_GOLD];
2514 /* All units in punitlist should have gold upkeep! */
2515 fc_assert_ret_val(gold_upkeep > 0, NULL);
2517 notify_player(pplayer, unit_tile(punit), E_UNIT_LOST_MISC, ftc_server,
2518 _("Not enough gold. %s disbanded."),
2519 unit_tile_link(punit));
2520 log_debug("%s: unit sold (%s)", player_name(pplayer),
2521 unit_name_translation(punit));
2523 unit_list_remove(punitlist, punit);
2524 wipe_unit(punit, ULR_SOLD, NULL);
2526 /* Get the upkeep gold back. */
2527 pplayer->economic.gold += gold_upkeep;
2529 return punit;
2532 /**************************************************************************
2533 Balance the gold of a nation by selling some random units and buildings.
2534 **************************************************************************/
2535 static bool player_balance_treasury_units_and_buildings
2536 (struct player *pplayer)
2538 struct cityimpr_list *pimprlist;
2539 struct unit_list *punitlist;
2540 bool sell_unit = TRUE;
2542 if (!pplayer) {
2543 return FALSE;
2546 pimprlist = cityimpr_list_new();
2547 punitlist = unit_list_new();
2549 city_list_iterate(pplayer->cities, pcity) {
2550 city_built_iterate(pcity, pimprove) {
2551 if (can_city_sell_building(pcity, pimprove)) {
2552 struct cityimpr *ci = fc_malloc(sizeof(*ci));
2554 ci->pcity = pcity;
2555 ci->pimprove = pimprove;
2556 cityimpr_list_append(pimprlist, ci);
2558 } city_built_iterate_end;
2560 unit_list_iterate(pcity->units_supported, punit) {
2561 if (punit->upkeep[O_GOLD] > 0) {
2562 unit_list_append(punitlist, punit);
2564 } unit_list_iterate_end;
2565 } city_list_iterate_end;
2567 while (pplayer->economic.gold < 0
2568 && (cityimpr_list_size(pimprlist) > 0
2569 || unit_list_size(punitlist) > 0)) {
2570 if ((!sell_unit && cityimpr_list_size(pimprlist) > 0)
2571 || unit_list_size(punitlist) == 0) {
2572 sell_random_building(pplayer, pimprlist);
2573 } else {
2574 sell_random_unit(pplayer, punitlist);
2576 sell_unit = !sell_unit;
2579 /* Free remaining entries from list */
2580 cityimpr_list_iterate(pimprlist, pimpr) {
2581 FC_FREE(pimpr);
2582 } cityimpr_list_iterate_end;
2584 if (pplayer->economic.gold < 0) {
2585 /* If we get here it means the player has
2586 * negative gold. This should never happen. */
2587 fc_assert_msg(FALSE, "Player %s (nb %d) cannot have negative gold!",
2588 player_name(pplayer), player_number(pplayer));
2591 cityimpr_list_destroy(pimprlist);
2592 unit_list_destroy(punitlist);
2594 return pplayer->economic.gold >= 0;
2597 /**************************************************************************
2598 Balance the gold of a nation by selling some units which need gold upkeep.
2599 **************************************************************************/
2600 static bool player_balance_treasury_units(struct player *pplayer)
2602 struct unit_list *punitlist;
2604 if (!pplayer) {
2605 return FALSE;
2608 punitlist = unit_list_new();
2610 city_list_iterate(pplayer->cities, pcity) {
2611 unit_list_iterate(pcity->units_supported, punit) {
2612 if (punit->upkeep[O_GOLD] > 0) {
2613 unit_list_append(punitlist, punit);
2615 } unit_list_iterate_end;
2616 } city_list_iterate_end;
2618 while (pplayer->economic.gold < 0
2619 && sell_random_unit(pplayer, punitlist)) {
2620 /* all done in sell_random_unit() */
2623 if (pplayer->economic.gold < 0) {
2624 /* If we get here it means the player has
2625 * negative gold. This should never happen. */
2626 fc_assert_msg(FALSE, "Player %s (nb %d) cannot have negative gold!",
2627 player_name(pplayer), player_number(pplayer));
2630 unit_list_destroy(punitlist);
2632 return pplayer->economic.gold >= 0;
2635 /**************************************************************************
2636 Balance the gold of one city by randomly selling some buildings.
2637 **************************************************************************/
2638 static bool city_balance_treasury_buildings(struct city *pcity)
2640 struct player *pplayer;
2641 struct cityimpr_list *pimprlist;
2643 if (!pcity) {
2644 return TRUE;
2647 pplayer = city_owner(pcity);
2648 pimprlist = cityimpr_list_new();
2650 /* Create a vector of all buildings that can be sold. */
2651 city_built_iterate(pcity, pimprove) {
2652 if (can_city_sell_building(pcity, pimprove)) {
2653 struct cityimpr *ci = fc_malloc(sizeof(*ci));
2655 ci->pcity = pcity;
2656 ci->pimprove = pimprove;
2657 cityimpr_list_append(pimprlist, ci);
2659 } city_built_iterate_end;
2661 /* Try to sell some buildings. */
2662 while (pplayer->economic.gold < 0
2663 && sell_random_building(pplayer, pimprlist)) {
2664 /* all done in sell_random_building */
2667 /* Free remaining entries from list */
2668 cityimpr_list_iterate(pimprlist, pimpr) {
2669 FC_FREE(pimpr);
2670 } cityimpr_list_iterate_end;
2672 cityimpr_list_destroy(pimprlist);
2674 return pplayer->economic.gold >= 0;
2677 /**************************************************************************
2678 Balance the gold of one city by randomly selling some units which need
2679 gold upkeep.
2681 NB: This function adds the gold upkeep of disbanded units back to the
2682 player's gold. Hence it assumes that this gold was previously taken
2683 from the player (i.e. in update_city_activity()).
2684 **************************************************************************/
2685 static bool city_balance_treasury_units(struct city *pcity)
2687 struct player *pplayer;
2688 struct unit_list *punitlist;
2690 if (!pcity) {
2691 return TRUE;
2694 pplayer = city_owner(pcity);
2695 punitlist = unit_list_new();
2697 /* Create a vector of all supported units with gold upkeep. */
2698 unit_list_iterate(pcity->units_supported, punit) {
2699 if (punit->upkeep[O_GOLD] > 0) {
2700 unit_list_append(punitlist, punit);
2702 } unit_list_iterate_end;
2704 /* Still not enough gold, so try "selling" some units. */
2705 while (pplayer->economic.gold < 0
2706 && sell_random_unit(pplayer, punitlist)) {
2707 /* all done in sell_random_unit() */
2710 /* If we get here the player has negative gold, but hopefully
2711 * another city will be able to pay the deficit, so continue. */
2713 unit_list_destroy(punitlist);
2715 return pplayer->economic.gold >= 0;
2718 /**************************************************************************
2719 Add some Pollution if we have waste
2720 **************************************************************************/
2721 static bool place_pollution(struct city *pcity, enum extra_cause cause)
2723 struct tile *ptile;
2724 struct tile *pcenter = city_tile(pcity);
2725 int city_radius_sq = city_map_radius_sq_get(pcity);
2726 int k = 100;
2728 while (k > 0) {
2729 /* place pollution on a random city tile */
2730 int cx, cy;
2731 int tile_id = fc_rand(city_map_tiles(city_radius_sq));
2732 struct extra_type *pextra;
2734 city_tile_index_to_xy(&cx, &cy, tile_id, city_radius_sq);
2736 /* check for a a real map position */
2737 if (!(ptile = city_map_to_tile(pcenter, city_radius_sq, cx, cy))) {
2738 continue;
2741 pextra = rand_extra_for_tile(ptile, cause);
2743 if (pextra != NULL && !tile_has_extra(ptile, pextra)) {
2744 tile_add_extra(ptile, pextra);
2745 update_tile_knowledge(ptile);
2747 return TRUE;
2749 k--;
2751 log_debug("pollution not placed: city: %s", city_name_get(pcity));
2753 return FALSE;
2756 /**************************************************************************
2757 Add some Pollution if we have waste
2758 **************************************************************************/
2759 static void check_pollution(struct city *pcity)
2761 if (pcity->pollution != 0 && fc_rand(100) <= pcity->pollution) {
2762 if (place_pollution(pcity, EC_POLLUTION)) {
2763 notify_player(city_owner(pcity), city_tile(pcity), E_POLLUTION, ftc_server,
2764 _("Pollution near %s."), city_link(pcity));
2769 /**************************************************************************
2770 Returns the cost to incite a city. This depends on the size of the city,
2771 the number of happy, unhappy and angry citizens, whether it is
2772 celebrating, how close it is to the capital, how many units it has and
2773 upkeeps, presence of courthouse, its buildings and wonders, and who
2774 originally built it.
2775 **************************************************************************/
2776 int city_incite_cost(struct player *pplayer, struct city *pcity)
2778 struct city *capital;
2779 int dist, size;
2780 double cost; /* Intermediate values can get very large */
2782 /* Gold factor */
2783 cost = city_owner(pcity)->economic.gold + game.server.base_incite_cost;
2785 unit_list_iterate(pcity->tile->units, punit) {
2786 cost += (unit_build_shield_cost(punit)
2787 * game.server.incite_unit_factor);
2788 } unit_list_iterate_end;
2790 /* Buildings */
2791 city_built_iterate(pcity, pimprove) {
2792 cost += impr_build_shield_cost(pimprove)
2793 * game.server.incite_improvement_factor;
2794 } city_built_iterate_end;
2796 /* Stability bonuses */
2797 if (!city_unhappy(pcity)) {
2798 cost *= 2;
2800 if (city_celebrating(pcity)) {
2801 cost *= 2;
2804 /* Buy back is cheap, conquered cities are also cheap */
2805 if (!game.info.citizen_nationality) {
2806 if (city_owner(pcity) != pcity->original) {
2807 if (pplayer == pcity->original) {
2808 cost /= 2; /* buy back: 50% price reduction */
2809 } else {
2810 cost = cost * 2 / 3; /* buy conquered: 33% price reduction */
2815 /* Distance from capital */
2816 capital = player_capital(city_owner(pcity));
2817 if (capital) {
2818 int tmp = map_distance(capital->tile, pcity->tile);
2819 dist = MIN(32, tmp);
2820 } else {
2821 /* No capital? Take max penalty! */
2822 dist = 32;
2825 size = MAX(1, city_size_get(pcity)
2826 + pcity->feel[CITIZEN_HAPPY][FEELING_FINAL]
2827 - pcity->feel[CITIZEN_UNHAPPY][FEELING_FINAL]
2828 - pcity->feel[CITIZEN_ANGRY][FEELING_FINAL] * 3);
2829 cost *= size;
2830 cost *= game.server.incite_total_factor;
2831 cost = cost / (dist + 3);
2833 if (game.info.citizen_nationality) {
2834 int cost_per_citizen = cost / pcity->size;
2835 int natives = citizens_nation_get(pcity, city_owner(pcity)->slot);
2836 int tgt_cit = citizens_nation_get(pcity, pplayer->slot);
2837 int third_party = pcity->size - natives - tgt_cit;
2839 cost = cost_per_citizen * (natives + 0.7 * third_party + 0.5 * tgt_cit);
2842 cost += (cost * get_city_bonus(pcity, EFT_INCITE_COST_PCT)) / 100;
2843 cost /= 100;
2845 if (cost >= INCITE_IMPOSSIBLE_COST) {
2846 return INCITE_IMPOSSIBLE_COST;
2847 } else {
2848 return cost;
2852 /**************************************************************************
2853 Called every turn, at beginning of turn, for every city.
2854 **************************************************************************/
2855 static void define_orig_production_values(struct city *pcity)
2857 /* Remember what this city is building last turn, so that on the next turn
2858 * the player can switch production to something else and then change it
2859 * back without penalty. This has to be updated _before_ production for
2860 * this turn is calculated, so that the penalty will apply if the player
2861 * changes production away from what has just been completed. This makes
2862 * sense if you consider what this value means: all the shields in the
2863 * city have been dedicated toward the project that was chosen last turn,
2864 * so the player shouldn't be penalized if the governor has to pick
2865 * something different. See city_change_production_penalty(). */
2866 pcity->changed_from = pcity->production;
2868 log_debug("In %s, building %s. Beg of Turn shields = %d",
2869 city_name_get(pcity), universal_rule_name(&pcity->changed_from),
2870 pcity->before_change_shields);
2873 /**************************************************************************
2874 Let the advisor set up city building target.
2875 **************************************************************************/
2876 static void nullify_caravan_and_disband_plus(struct city *pcity)
2878 pcity->disbanded_shields=0;
2879 pcity->caravan_shields=0;
2882 /**************************************************************************
2883 Initialize all variables containing information about production
2884 before it was changed.
2885 **************************************************************************/
2886 void nullify_prechange_production(struct city *pcity)
2888 nullify_caravan_and_disband_plus(pcity);
2889 pcity->before_change_shields=0;
2892 /**************************************************************************
2893 Called every turn, at end of turn, for every city.
2894 **************************************************************************/
2895 static void update_city_activity(struct city *pcity)
2897 struct player *pplayer;
2898 struct government *gov;
2900 if (!pcity) {
2901 return;
2904 pplayer = city_owner(pcity);
2905 gov = government_of_city(pcity);
2907 if (city_refresh(pcity)) {
2908 auto_arrange_workers(pcity);
2911 /* Reporting of celebrations rewritten, copying the treatment of disorder below,
2912 with the added rapture rounds count. 991219 -- Jing */
2913 if (city_build_stuff(pplayer, pcity)) {
2914 int saved_id;
2915 int revolution_turns;
2917 pcity->history += city_history_gain(pcity);
2919 /* History can decrease, but never go below zero */
2920 pcity->history = MAX(pcity->history, 0);
2922 if (city_celebrating(pcity)) {
2923 pcity->rapture++;
2924 if (pcity->rapture == 1) {
2925 notify_player(pplayer, city_tile(pcity), E_CITY_LOVE, ftc_server,
2926 _("Celebrations in your honor in %s."),
2927 city_link(pcity));
2929 } else {
2930 if (pcity->rapture != 0) {
2931 notify_player(pplayer, city_tile(pcity), E_CITY_NORMAL, ftc_server,
2932 _("Celebrations canceled in %s."),
2933 city_link(pcity));
2935 pcity->rapture = 0;
2937 pcity->was_happy = city_happy(pcity);
2939 /* Handle the illness. */
2940 if (game.info.illness_on) {
2941 /* recalculate city illness; illness due to trade has to be saved
2942 * within the city struct as the client has not all data to
2943 * calculate it */
2944 pcity->server.illness
2945 = city_illness_calc(pcity, NULL, NULL, &(pcity->illness_trade), NULL);
2947 if (city_illness_check(pcity)) {
2948 notify_player(pplayer, city_tile(pcity), E_CITY_PLAGUE, ftc_server,
2949 _("%s has been struck by a plague! Population lost!"),
2950 city_link(pcity));
2951 city_reduce_size(pcity, 1, NULL, "plague");
2952 pcity->turn_plague = game.info.turn;
2954 /* recalculate illness */
2955 pcity->server.illness
2956 = city_illness_calc(pcity, NULL, NULL, &(pcity->illness_trade),
2957 NULL);
2961 /* City population updated here, after the rapture stuff above. --Jing */
2962 saved_id = pcity->id;
2963 city_populate(pcity, pplayer);
2964 if (NULL == player_city_by_number(pplayer, saved_id)) {
2965 return;
2968 pcity->did_sell = FALSE;
2969 pcity->did_buy = FALSE;
2970 pcity->airlift = city_airlift_max(pcity);
2971 update_bulbs(pplayer, pcity->prod[O_SCIENCE], FALSE);
2973 /* Update the treasury. */
2974 pplayer->economic.gold += pcity->prod[O_GOLD];
2975 pplayer->economic.gold -= city_total_impr_gold_upkeep(pcity);
2976 pplayer->economic.gold -= city_total_unit_gold_upkeep(pcity);
2978 if (pplayer->economic.gold < 0) {
2979 /* Not enough gold - we have to sell some buildings, and if that
2980 * is not enough, disband units with gold upkeep, taking into
2981 * account the setting of 'game.info.gold_upkeep_style':
2982 * GOLD_UPKEEP_CITY: Cities pay for buildings and units.
2983 * GOLD_UPKEEP_MIXED: Cities pay only for buildings; the nation pays
2984 * for units.
2985 * GOLD_UPKEEP_NATION: The nation pays for buildings and units. */
2986 switch (game.info.gold_upkeep_style) {
2987 case GOLD_UPKEEP_CITY:
2988 case GOLD_UPKEEP_MIXED:
2989 if (!city_balance_treasury_buildings(pcity)
2990 && game.info.gold_upkeep_style == GOLD_UPKEEP_CITY) {
2991 city_balance_treasury_units(pcity);
2993 break;
2994 case GOLD_UPKEEP_NATION:
2995 break;
2999 if (city_unhappy(pcity)) {
3000 pcity->anarchy++;
3001 if (pcity->anarchy == 1) {
3002 notify_player(pplayer, city_tile(pcity), E_CITY_DISORDER, ftc_server,
3003 _("Civil disorder in %s."),
3004 city_link(pcity));
3005 } else {
3006 notify_player(pplayer, city_tile(pcity), E_CITY_DISORDER, ftc_server,
3007 _("CIVIL DISORDER CONTINUES in %s."),
3008 city_link(pcity));
3010 } else {
3011 if (pcity->anarchy != 0) {
3012 notify_player(pplayer, city_tile(pcity), E_CITY_NORMAL, ftc_server,
3013 _("Order restored in %s."),
3014 city_link(pcity));
3016 pcity->anarchy = 0;
3018 check_pollution(pcity);
3020 send_city_info(NULL, pcity);
3022 revolution_turns = get_city_bonus(pcity, EFT_REVOLUTION_UNHAPPINESS);
3023 if (revolution_turns > 0 && pcity->anarchy > revolution_turns) {
3024 notify_player(pplayer, city_tile(pcity), E_ANARCHY, ftc_server,
3025 _("The people have overthrown your %s, "
3026 "your country is in turmoil."),
3027 government_name_translation(gov));
3028 handle_player_change_government(pplayer, government_number(gov));
3030 if (city_refresh(pcity)) {
3031 auto_arrange_workers(pcity);
3033 sanity_check_city(pcity);
3037 /*****************************************************************************
3038 check if city suffers from a plague. Return TRUE if it does, FALSE if not.
3039 ****************************************************************************/
3040 static bool city_illness_check(const struct city * pcity)
3042 if (fc_rand(1000) < pcity->server.illness) {
3043 return TRUE;
3046 return FALSE;
3049 /**************************************************************************
3050 Disband a city into the built unit, supported by the closest city.
3051 **************************************************************************/
3052 static bool disband_city(struct city *pcity)
3054 struct player *pplayer = city_owner(pcity);
3055 struct tile *ptile = pcity->tile;
3056 struct city *rcity=NULL;
3057 struct unit_type *utype = pcity->production.value.utype;
3058 int saved_id = pcity->id;
3060 /* find closest city other than pcity */
3061 rcity = find_closest_city(ptile, pcity, pplayer, FALSE, FALSE, FALSE, TRUE,
3062 FALSE, NULL);
3064 if (!rcity) {
3065 /* What should we do when we try to disband our only city? */
3066 notify_player(pplayer, ptile, E_CITY_CANTBUILD, ftc_server,
3067 _("%s can't build %s yet, "
3068 "and we can't disband our only city."),
3069 city_link(pcity), utype_name_translation(utype));
3070 script_server_signal_emit("unit_cant_be_built", 3,
3071 API_TYPE_UNIT_TYPE, utype,
3072 API_TYPE_CITY, pcity,
3073 API_TYPE_STRING, "pop_cost");
3074 if (!city_exist(saved_id)) {
3075 /* Script decided to remove even the last city */
3076 return TRUE;
3077 } else {
3078 return FALSE;
3082 (void) create_unit(pplayer, ptile, utype,
3083 do_make_unit_veteran(pcity, utype),
3084 pcity->id, 0);
3085 pplayer->score.units_built++;
3087 /* Shift all the units supported by pcity (including the new unit)
3088 * to rcity. transfer_city_units does not make sure no units are
3089 * left floating without a transport, but since all units are
3090 * transferred this is not a problem. */
3091 transfer_city_units(pplayer, pplayer, pcity->units_supported, rcity,
3092 pcity, -1, TRUE);
3094 notify_player(pplayer, ptile, E_UNIT_BUILT, ftc_server,
3095 /* TRANS: "<city> is disbanded into Settler." */
3096 _("%s is disbanded into %s."),
3097 city_tile_link(pcity), utype_name_translation(utype));
3099 script_server_signal_emit("city_destroyed", 3,
3100 API_TYPE_CITY, pcity,
3101 API_TYPE_PLAYER, pcity->owner,
3102 API_TYPE_PLAYER, NULL);
3104 remove_city(pcity);
3105 return TRUE;
3108 /***************************************************************************
3109 Helper function to calculate a "score" of a city. The score is used to get
3110 an estimate of the "migration desirability" of the city. The higher the
3111 score the more likely citizens will migrate to it.
3113 The score depends on the city size, the feeling of its citizens, the cost
3114 of all buildings in the city, and the surplus of trade, luxury and
3115 science.
3117 formula:
3118 score = ([city size] + feeling) * factors
3120 * feeling of the citizens
3121 feeling = 1.00 * happy citizens
3122 + 0.00 * content citizens
3123 - 0.25 * unhappy citizens
3124 - 0.50 * angry citizens
3126 * factors
3127 * the build costs of all buildings
3128 f = (1 + (1 - exp(-[build shield cost]/1000))/5)
3129 * the trade of the city
3130 f = (1 + (1 - exp(-[city surplus trade]/100))/5)
3131 * the luxury within the city
3132 f = (1 + (1 - exp(-[city surplus luxury]/100))/5)
3133 * the science within the city
3134 f = (1 + (1 - exp(-[city surplus science]/100))/5)
3136 all factors f have values between 1 and 1.2; the overall factor will be
3137 between 1.0 (smaller cities) and 2.0 (bigger cities)
3139 [build shield cost], [city surplus trade], [city surplus luxury] and
3140 [city surplus science] _must_ be >= 0!
3142 The food furplus is considered by an additional factor
3144 * the food surplus of the city
3145 f = (1 + [city surplus food; interval -10..20]/10)
3147 The health factor is defined as:
3149 * the health of the city
3150 f = (100 - [city illness; tenth of %]/25)
3152 * if the city has at least one wonder a factor of 1.25 is added
3153 * for the capital an additional factor of 1.25 is used
3154 * the score is also modified by the effect EFT_MIGRATION_PCT
3155 **************************************************************************/
3156 static float city_migration_score(struct city *pcity)
3158 float score = 0.0;
3159 int build_shield_cost = 0;
3160 bool has_wonder = FALSE;
3162 if (!pcity) {
3163 return score;
3166 if (pcity->server.mgr_score_calc_turn == game.info.turn) {
3167 /* up-to-date migration score */
3168 return pcity->server.migration_score;
3171 /* feeling of the citizens */
3172 score = (city_size_get(pcity)
3173 + 1.00 * pcity->feel[CITIZEN_HAPPY][FEELING_FINAL]
3174 + 0.00 * pcity->feel[CITIZEN_CONTENT][FEELING_FINAL]
3175 - 0.25 * pcity->feel[CITIZEN_UNHAPPY][FEELING_FINAL]
3176 - 0.50 * pcity->feel[CITIZEN_ANGRY][FEELING_FINAL]);
3178 /* calculate shield build cost for all buildings */
3179 city_built_iterate(pcity, pimprove) {
3180 build_shield_cost += impr_build_shield_cost(pimprove);
3181 if (is_wonder(pimprove)) {
3182 /* this city has a wonder */
3183 has_wonder = TRUE;
3185 } city_built_iterate_end;
3187 /* take shield costs of all buidings into account; normalized by 1000 */
3188 score *= (1 + (1 - exp(- (float) MAX(0, build_shield_cost) / 1000)) / 5);
3189 /* take trade into account; normalized by 100 */
3190 score *= (1 + (1 - exp(- (float) MAX(0, pcity->surplus[O_TRADE]) / 100))
3191 / 5);
3192 /* take luxury into account; normalized by 100 */
3193 score *= (1 + (1 - exp(- (float) MAX(0, pcity->surplus[O_LUXURY]) / 100))
3194 / 5);
3195 /* take science into account; normalized by 100 */
3196 score *= (1 + (1 - exp(- (float) MAX(0, pcity->surplus[O_SCIENCE]) / 100))
3197 / 5);
3199 score += city_culture(pcity) * game.info.culture_migration_pml / 1000;
3201 /* Take food into account; the food surplus is clipped to values between
3202 * -10..20 and normalize by 10. Thus, the factor is between 0.9 and 1.2. */
3203 score *= (1 + (float) CLIP(-10, pcity->surplus[O_FOOD], 20) / 10 );
3205 /* Reduce the score due to city illness (plague). The illness is given in
3206 * tenth of percent (0..1000) and normalized by 25. Thus, this factor is
3207 * between 0.6 (ill city) and 1.0 (health city). */
3208 score *= (100 - (float)city_illness_calc(pcity, NULL, NULL, NULL, NULL)
3209 / 25);
3211 if (has_wonder) {
3212 /* people like wonders */
3213 score *= 1.25;
3216 if (is_capital(pcity)) {
3217 /* the capital is a magnet for the citizens */
3218 score *= 1.25;
3221 /* take into account effects */
3222 score *= (1.0 + get_city_bonus(pcity, EFT_MIGRATION_PCT) / 100.0);
3224 log_debug("[M] %s score: %.3f", city_name_get(pcity), score);
3226 /* set migration score for the city */
3227 pcity->server.migration_score = score;
3228 /* set the turn, when the score was calculated */
3229 pcity->server.mgr_score_calc_turn = game.info.turn;
3231 return score;
3234 /**************************************************************************
3235 Do the migrations between the cities that overlap, if the growth of the
3236 target city is not blocked due to a missing improvement or missing food.
3238 Returns TRUE if migration occurred.
3239 **************************************************************************/
3240 static bool do_city_migration(struct city *pcity_from,
3241 struct city *pcity_to)
3243 struct player *pplayer_from, *pplayer_to, *pplayer_citizen;
3244 struct tile *ptile_from, *ptile_to;
3245 char name_from[MAX_LEN_LINK], name_to[MAX_LEN_LINK];
3246 const char *nation_from, *nation_to;
3247 struct city *rcity = NULL;
3249 if (!pcity_from || !pcity_to) {
3250 return FALSE;
3253 pplayer_from = city_owner(pcity_from);
3254 pplayer_citizen = pplayer_from;
3255 pplayer_to = city_owner(pcity_to);
3256 /* We copy that, because city_link always returns the same pointer. */
3257 sz_strlcpy(name_from, city_link(pcity_from));
3258 sz_strlcpy(name_to, city_link(pcity_to));
3259 nation_from = nation_adjective_for_player(pplayer_from);
3260 nation_to = nation_adjective_for_player(pplayer_to);
3261 ptile_from = city_tile(pcity_from);
3262 ptile_to = city_tile(pcity_to);
3264 /* check food supply in the receiver city */
3265 if (game.server.mgr_foodneeded) {
3266 bool migration = FALSE;
3268 if (pcity_to->surplus[O_FOOD] >= game.info.food_cost) {
3269 migration = TRUE;
3270 } else {
3271 /* check if there is a free tile for the new citizen which, when worked,
3272 * leads to zero or positive food surplus for the enlarged city */
3273 int max_food_tile = -1; /* no free tile */
3274 city_tile_iterate(city_map_radius_sq_get(pcity_to),
3275 city_tile(pcity_to), ptile) {
3276 if (city_can_work_tile(pcity_to, ptile)
3277 && tile_worked(ptile) != pcity_to) {
3278 /* Safest assumption is that city won't be celebrating once an
3279 * additional citizen is added */
3280 max_food_tile = MAX(max_food_tile,
3281 city_tile_output(pcity_to, ptile, FALSE, O_FOOD));
3283 } city_tile_iterate_end;
3284 if (max_food_tile >= 0
3285 && pcity_to->surplus[O_FOOD] + max_food_tile >= game.info.food_cost) {
3286 migration = TRUE;
3290 if (!migration) {
3291 /* insufficiency food in receiver city; no additional citizens */
3292 if (pplayer_from == pplayer_to) {
3293 /* migration between one nation */
3294 notify_player(pplayer_to, ptile_to, E_CITY_TRANSFER, ftc_server,
3295 /* TRANS: From <city1> to <city2>. */
3296 _("Migrants from %s can't go to %s because there is "
3297 "not enough food available!"),
3298 name_from, name_to);
3299 } else {
3300 /* migration between different nations */
3301 notify_player(pplayer_from, ptile_to, E_CITY_TRANSFER, ftc_server,
3302 /* TRANS: From <city1> to <city2> (<city2 nation adjective>). */
3303 _("Migrants from %s can't go to %s (%s) because there "
3304 "is not enough food available!"),
3305 name_from, name_to, nation_to);
3306 notify_player(pplayer_to, ptile_to, E_CITY_TRANSFER, ftc_server,
3307 /* TRANS: From <city1> (<city1 nation adjective>) to <city2>. */
3308 _("Migrants from %s (%s) can't go to %s because there "
3309 "is not enough food available!"),
3310 name_from, nation_from, name_to);
3313 return FALSE;
3317 if (!city_can_grow_to(pcity_to, city_size_get(pcity_to) + 1)) {
3318 /* receiver city can't grow */
3319 if (pplayer_from == pplayer_to) {
3320 /* migration between one nation */
3321 notify_player(pplayer_to, ptile_to, E_CITY_TRANSFER, ftc_server,
3322 /* TRANS: From <city1> to <city2>. */
3323 _("Migrants from %s can't go to %s because it needs "
3324 "an improvement to grow!"),
3325 name_from, name_to);
3326 } else {
3327 /* migration between different nations */
3328 notify_player(pplayer_from, ptile_to, E_CITY_TRANSFER, ftc_server,
3329 /* TRANS: From <city1> to <city2> of <city2 nation adjective>. */
3330 _("Migrants from %s can't go to %s (%s) because it "
3331 "needs an improvement to grow!"),
3332 name_from, name_to, nation_to);
3333 notify_player(pplayer_to, ptile_to, E_CITY_TRANSFER, ftc_server,
3334 /* TRANS: From <city1> (<city1 nation adjective>) to <city2>. */
3335 _("Migrants from %s (%s) can't go to %s because it "
3336 "needs an improvement to grow!"),
3337 name_from, nation_from, name_to);
3340 return FALSE;
3343 /* reduce size of giver */
3344 if (city_size_get(pcity_from) == 1) {
3346 if (game.info.citizen_nationality) {
3347 /* Preserve nationality of city's only citizen */
3348 pplayer_citizen = player_slot_get_player(citizens_random(pcity_from));
3351 /* do not destroy wonders */
3352 city_built_iterate(pcity_from, pimprove) {
3353 if (is_wonder(pimprove)) {
3354 return FALSE;
3356 } city_built_iterate_end;
3358 /* find closest city other of the same player than pcity_from */
3359 rcity = find_closest_city(ptile_from, pcity_from, pplayer_from, FALSE,
3360 FALSE, FALSE, TRUE, FALSE, NULL);
3362 if (rcity) {
3363 /* transfer all units to the closest city */
3364 transfer_city_units(pplayer_from, pplayer_from,
3365 pcity_from->units_supported, rcity, pcity_from,
3366 -1, TRUE);
3367 sz_strlcpy(name_from, city_tile_link(pcity_from));
3369 script_server_signal_emit("city_size_change", 3,
3370 API_TYPE_CITY, pcity_from,
3371 API_TYPE_INT, -1,
3372 API_TYPE_STRING, "migration_from");
3373 script_server_signal_emit("city_destroyed", 3,
3374 API_TYPE_CITY, pcity_from,
3375 API_TYPE_PLAYER, pcity_from->owner,
3376 API_TYPE_PLAYER, NULL);
3378 remove_city(pcity_from);
3380 notify_player(pplayer_from, ptile_from, E_CITY_LOST, ftc_server,
3381 _("%s was disbanded by its citizens."),
3382 name_from);
3383 } else {
3384 /* it's the only city of the nation */
3385 return FALSE;
3387 } else {
3388 /* the migrants take half of the food box with them (this prevents
3389 * migration -> grow -> migration -> ... cycles) */
3390 pcity_from->food_stock /= 2;
3392 if (game.info.citizen_nationality) {
3393 /* Those citizens that are from the target nation are most
3394 * ones migrating. */
3395 if (citizens_nation_get(pcity_from, pplayer_to->slot) > 0) {
3396 pplayer_citizen = pplayer_to;
3397 } else if (!citizens_nation_get(pcity_from, pplayer_citizen->slot)) {
3398 /* No native citizens at all in the city, choose random foreigner */
3399 struct player_slot *cit_slot = citizens_random(pcity_from);
3401 pplayer_citizen = player_slot_get_player(cit_slot);
3403 /* This should be followed by city_reduce_size(). */
3404 citizens_nation_add(pcity_from, pplayer_citizen->slot, -1);
3406 city_reduce_size(pcity_from, 1, pplayer_from, "migration_from");
3407 city_refresh_vision(pcity_from);
3408 if (city_refresh(pcity_from)) {
3409 auto_arrange_workers(pcity_from);
3413 /* This should be _before_ the size of the city is increased. Thus, the
3414 * order of the messages is correct (1: migration; 2: increased size). */
3415 if (pplayer_from == pplayer_to) {
3416 /* migration between one nation */
3417 notify_player(pplayer_from, ptile_to, E_CITY_TRANSFER, ftc_server,
3418 /* TRANS: From <city1> to <city2>. */
3419 _("Migrants from %s moved to %s in search of a better "
3420 "life."), name_from, name_to);
3421 } else {
3422 /* migration between different nations */
3423 notify_player(pplayer_from, ptile_to, E_CITY_TRANSFER, ftc_server,
3424 /* TRANS: From <city1> to <city2> (<city2 nation adjective>). */
3425 _("Migrants from %s moved to %s (%s) in search of a "
3426 "better life."),
3427 name_from, name_to, nation_to);
3428 notify_player(pplayer_to, ptile_to, E_CITY_TRANSFER, ftc_server,
3429 /* TRANS: From <city1> (<city1 nation adjective>) to <city2>. */
3430 _("Migrants from %s (%s) moved to %s in search of a "
3431 "better life."),
3432 name_from, nation_from, name_to);
3435 /* raise size of receiver city */
3436 city_increase_size(pcity_to, pplayer_citizen);
3437 city_refresh_vision(pcity_to);
3438 if (city_refresh(pcity_to)) {
3439 auto_arrange_workers(pcity_to);
3441 script_server_signal_emit("city_size_change", 3,
3442 API_TYPE_CITY, pcity_to,
3443 API_TYPE_INT, 1,
3444 API_TYPE_STRING, "migration_to");
3446 log_debug("[M] T%d migration successful (%s -> %s)",
3447 game.info.turn, name_from, name_to);
3449 return TRUE;
3452 /**************************************************************************
3453 Check for citizens who want to migrate between the cities that overlap.
3454 Migrants go to the city with higher score, if the growth of the target
3455 city is not blocked due to a missing improvement.
3457 The following setting are used:
3459 'game.server.mgr_turninterval' controls the number of turns between
3460 migration checks for one city (counted from the founding). If this
3461 setting is zero, or it is the first turn (T0), migration does no occur.
3463 'game.server.mgr_distance' is the maximal distance for migration.
3465 'game.server.mgr_nationchance' gives the chance for migration within one
3466 nation.
3468 'game.server.mgr_worldchance' gives the chance for migration between all
3469 nations.
3471 Returns TRUE iff there has been INTERNATIONAL migration.
3472 **************************************************************************/
3473 bool check_city_migrations(void)
3475 bool internat = FALSE;
3477 if (!game.server.migration) {
3478 return FALSE;
3481 if (game.server.mgr_turninterval <= 0
3482 || (game.server.mgr_worldchance <= 0
3483 && game.server.mgr_nationchance <= 0)) {
3484 return FALSE;
3487 /* check for migration */
3488 players_iterate(pplayer) {
3489 if (!pplayer->cities) {
3490 continue;
3493 if (check_city_migrations_player(pplayer)) {
3494 internat = TRUE;
3496 } players_iterate_end;
3498 return internat;
3501 /**************************************************************************
3502 Disaster has hit a city. Apply its effects.
3503 **************************************************************************/
3504 static void apply_disaster(struct city *pcity, struct disaster_type *pdis)
3506 struct player *pplayer = city_owner(pcity);
3507 struct tile *ptile = city_tile(pcity);
3508 bool had_internal_effect = FALSE;
3510 log_debug("%s at %s", disaster_rule_name(pdis), city_name_get(pcity));
3512 notify_player(pplayer, ptile, E_DISASTER,
3513 ftc_server,
3514 /* TRANS: Disasters such as Earthquake */
3515 _("%s was hit by %s."), city_name_get(pcity),
3516 disaster_name_translation(pdis));
3518 if (disaster_has_effect(pdis, DE_POLLUTION)) {
3519 if (place_pollution(pcity, EC_POLLUTION)) {
3520 notify_player(pplayer, ptile, E_DISASTER, ftc_server,
3521 _("Pollution near %s."), city_link(pcity));
3522 had_internal_effect = TRUE;
3526 if (disaster_has_effect(pdis, DE_FALLOUT)) {
3527 if (place_pollution(pcity, EC_FALLOUT)) {
3528 notify_player(pplayer, ptile, E_DISASTER, ftc_server,
3529 _("Fallout near %s."), city_link(pcity));
3530 had_internal_effect = TRUE;
3534 if (disaster_has_effect(pdis, DE_REDUCE_DESTROY)
3535 || (disaster_has_effect(pdis, DE_REDUCE_POP)
3536 && pcity->size > 1)) {
3537 if (!city_reduce_size(pcity, 1, NULL, "disaster")) {
3538 notify_player(pplayer, ptile, E_DISASTER, ftc_server,
3539 /* TRANS: "Industrial Accident destroys Bogota entirely." */
3540 _("%s destroys %s entirely."),
3541 disaster_name_translation(pdis), city_link(pcity));
3542 pcity = NULL;
3543 } else {
3544 notify_player(pplayer, ptile, E_DISASTER, ftc_server,
3545 /* TRANS: "Nuclear Accident ... Montreal." */
3546 _("%s causes population loss in %s."),
3547 disaster_name_translation(pdis), city_link(pcity));
3550 had_internal_effect = TRUE;
3553 if (pcity && disaster_has_effect(pdis, DE_DESTROY_BUILDING)) {
3554 int total = 0;
3555 struct impr_type *imprs[B_LAST];
3557 city_built_iterate(pcity, pimprove) {
3558 if (is_improvement(pimprove)) {
3559 imprs[total++] = pimprove;
3561 } city_built_iterate_end;
3563 if (total > 0) {
3564 int num = fc_rand(total);
3566 building_lost(pcity, imprs[num]);
3568 notify_player(pplayer, ptile, E_DISASTER, ftc_server,
3569 /* TRANS: second %s is the name of a city improvement */
3570 _("%s destroys %s in %s."),
3571 disaster_name_translation(pdis),
3572 improvement_name_translation(imprs[num]),
3573 city_link(pcity));
3575 had_internal_effect = TRUE;
3579 if (pcity && disaster_has_effect(pdis, DE_EMPTY_FOODSTOCK)) {
3580 if (pcity->food_stock > 0) {
3581 pcity->food_stock = 0;
3583 notify_player(pplayer, ptile, E_DISASTER, ftc_server,
3584 /* TRANS: %s is a city name */
3585 _("All stored food destroyed in %s."), city_link(pcity));
3587 had_internal_effect = TRUE;
3591 if (pcity && disaster_has_effect(pdis, DE_EMPTY_PRODSTOCK)) {
3592 if (pcity->shield_stock > 0) {
3593 char prod[256];
3595 pcity->shield_stock = 0;
3596 nullify_prechange_production(pcity); /* Make it impossible to recover */
3598 universal_name_translation(&pcity->production, prod, sizeof(prod));
3599 notify_player(pplayer, ptile, E_DISASTER, ftc_server,
3600 /* TRANS: "Production of Colossus in Rhodes destroyed." */
3601 _("Production of %s in %s destroyed."),
3602 prod, city_link(pcity));
3604 had_internal_effect = TRUE;
3608 script_server_signal_emit("disaster_occurred", 3,
3609 API_TYPE_DISASTER, pdis,
3610 API_TYPE_CITY, pcity,
3611 API_TYPE_BOOL, had_internal_effect);
3612 script_server_signal_emit("disaster", 2,
3613 API_TYPE_DISASTER, pdis,
3614 API_TYPE_CITY, pcity);
3617 /**************************************************************************
3618 Check for any disasters hitting any city, and apply those disasters.
3619 **************************************************************************/
3620 void check_disasters(void)
3622 if (game.info.disasters == 0) {
3623 /* Shortcut out as no disaster is possible. */
3624 return;
3627 players_iterate(pplayer) {
3628 /* Safe city iterator needed as disaster may destroy city */
3629 city_list_iterate_safe(pplayer->cities, pcity) {
3630 int id = pcity->id;
3632 disaster_type_iterate(pdis) {
3633 if (city_exist(id)) {
3634 /* City survived earlier disasters. */
3635 int probability = game.info.disasters * pdis->frequency;
3636 int result = fc_rand(DISASTER_BASE_RARITY);
3638 if (result < probability) {
3639 if (can_disaster_happen(pdis, pcity)) {
3640 apply_disaster(pcity, pdis);
3644 } disaster_type_iterate_end;
3645 } city_list_iterate_safe_end;
3646 } players_iterate_end;
3649 /**************************************************************************
3650 Check for migration for each city of one player.
3652 For each city of the player do:
3653 * check each tile within GAME_MAX_MGR_DISTANCE for a city
3654 * if a city is found check the distance
3655 * compare the migration score
3656 **************************************************************************/
3657 static bool check_city_migrations_player(const struct player *pplayer)
3659 char city_link_text[MAX_LEN_LINK];
3660 float best_city_player_score, best_city_world_score;
3661 struct city *best_city_player, *best_city_world, *acity;
3662 float score_from, score_tmp, weight;
3663 int dist, mgr_dist;
3664 bool internat = FALSE;
3666 /* check for each city
3667 * city_list_iterate_safe_end must be used because we could
3668 * remove one city from the list */
3669 city_list_iterate_safe(pplayer->cities, pcity) {
3670 /* no migration out of the capital */
3671 if (is_capital(pcity)) {
3672 continue;
3675 /* check only each (game.server.mgr_turninterval) turn
3676 * (counted from the funding turn) and do not migrate
3677 * the same turn a city is founded */
3678 if (game.info.turn == pcity->turn_founded
3679 || ((game.info.turn - pcity->turn_founded)
3680 % game.server.mgr_turninterval) != 0) {
3681 continue;
3684 best_city_player_score = 0.0;
3685 best_city_world_score = 0.0;
3686 best_city_player = NULL;
3687 best_city_world = NULL;
3689 /* score of the actual city
3690 * taking into account a persistence factor of 3 */
3691 score_from = city_migration_score(pcity) * 3;
3693 log_debug("[M] T%d check city: %s score: %6.3f (%s)",
3694 game.info.turn, city_name_get(pcity), score_from,
3695 player_name(pplayer));
3697 /* consider all cities within the maximal possible distance
3698 * (= CITY_MAP_MAX_RADIUS + GAME_MAX_MGR_DISTANCE) */
3699 iterate_outward(city_tile(pcity), CITY_MAP_MAX_RADIUS
3700 + GAME_MAX_MGR_DISTANCE, ptile) {
3701 acity = tile_city(ptile);
3703 if (!acity || acity == pcity) {
3704 /* no city or the city in the center */
3705 continue;
3708 /* Calculate the migration distance. The value of
3709 * game.server.mgr_distance is added to the current city radius. If the
3710 * distance between both cities is lower or equal than this value,
3711 * migration is possible. */
3712 mgr_dist = (int)sqrt((double)MAX(city_map_radius_sq_get(acity),0))
3713 + game.server.mgr_distance;
3715 /* distance between the two cities */
3716 dist = real_map_distance(city_tile(pcity), city_tile(acity));
3718 if (dist > mgr_dist) {
3719 /* to far away */
3720 continue;
3723 /* score of the second city, weighted by the distance */
3724 weight = ((float) (mgr_dist + 1 - dist) / (float) (mgr_dist + 1));
3725 score_tmp = city_migration_score(acity) * weight;
3727 log_debug("[M] T%d - compare city: %s (%s) dist: %d mgr_dist: %d "
3728 "score: %6.3f", game.info.turn, city_name_get(acity),
3729 player_name(city_owner(acity)), dist, mgr_dist, score_tmp);
3731 if (game.server.mgr_nationchance > 0 && city_owner(acity) == pplayer) {
3732 /* migration between cities of the same owner */
3733 if (score_tmp > score_from && score_tmp > best_city_player_score) {
3734 /* select the best! */
3735 best_city_player_score = score_tmp;
3736 best_city_player = acity;
3738 log_debug("[M] T%d - best city (player): %s (%s) score: "
3739 "%6.3f (> %6.3f)", game.info.turn,
3740 city_name_get(best_city_player), player_name(pplayer),
3741 best_city_player_score, score_from);
3743 } else if (game.server.mgr_worldchance > 0
3744 && city_owner(acity) != pplayer) {
3745 /* migration between cities of different owners */
3746 if (game.info.citizen_nationality) {
3747 /* Modify the score if citizens could migrate to a city of their
3748 * original nation. */
3749 if (citizens_nation_get(pcity, city_owner(acity)->slot) > 0) {
3750 score_tmp *= 2;
3754 if (score_tmp > score_from && score_tmp > best_city_world_score) {
3755 /* select the best! */
3756 best_city_world_score = score_tmp;
3757 best_city_world = acity;
3759 log_debug("[M] T%d - best city (world): %s (%s) score: "
3760 "%6.3f (> %6.3f)", game.info.turn,
3761 city_name_get(best_city_world),
3762 player_name(city_owner(best_city_world)),
3763 best_city_world_score, score_from);
3766 } iterate_outward_end;
3768 if (best_city_player_score > 0) {
3769 /* first, do the migration within one nation */
3770 if (fc_rand(100) >= game.server.mgr_nationchance) {
3771 /* no migration */
3772 /* N.B.: city_link always returns the same pointer. */
3773 sz_strlcpy(city_link_text, city_link(pcity));
3774 notify_player(pplayer, city_tile(pcity), E_CITY_TRANSFER, ftc_server,
3775 _("Citizens of %s are thinking about migrating to %s "
3776 "for a better life."),
3777 city_link_text, city_link(best_city_player));
3778 } else {
3779 do_city_migration(pcity, best_city_player);
3782 /* stop here */
3783 continue;
3786 if (best_city_world_score > 0) {
3787 /* second, do the migration between all nations */
3788 if (fc_rand(100) >= game.server.mgr_worldchance) {
3789 const char *nname;
3791 nname = nation_adjective_for_player(city_owner(best_city_world));
3792 /* no migration */
3793 /* N.B.: city_link always returns the same pointer. */
3794 sz_strlcpy(city_link_text, city_link(pcity));
3795 notify_player(pplayer, city_tile(pcity), E_CITY_TRANSFER, ftc_server,
3796 /* TRANS: <city1> to <city2> (<city2 nation adjective>). */
3797 _("Citizens of %s are thinking about migrating to %s "
3798 "(%s) for a better life."),
3799 city_link_text, city_link(best_city_world), nname);
3800 } else {
3801 do_city_migration(pcity, best_city_world);
3802 internat = TRUE;
3805 /* stop here */
3806 continue;
3808 } city_list_iterate_safe_end;
3810 return internat;
3813 /**************************************************************************
3814 Recheck and store style of the city.
3815 **************************************************************************/
3816 void city_style_refresh(struct city *pcity)
3818 pcity->style = city_style(pcity);