Removed silencing of gtk warning logs from gtk3.22-client.
[freeciv.git] / common / city.c
blobbc2b54b91d4b6200efd317ded1fc0ada8e8986a9
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 <stdlib.h>
19 #include <string.h>
20 #include <math.h> /* pow, sqrt, exp */
22 /* utility */
23 #include "distribute.h"
24 #include "fcintl.h"
25 #include "log.h"
26 #include "mem.h"
27 #include "support.h"
29 /* common */
30 #include "ai.h"
31 #include "citizens.h"
32 #include "effects.h"
33 #include "game.h"
34 #include "government.h"
35 #include "improvement.h"
36 #include "map.h"
37 #include "movement.h"
38 #include "packets.h"
39 #include "specialist.h"
40 #include "traderoutes.h"
41 #include "unit.h"
43 /* aicore */
44 #include "cm.h"
46 #include "city.h"
48 /* Define this to add in extra (very slow) assertions for the city code. */
49 #undef CITY_DEBUGGING
51 static char *citylog_map_line(int y, int city_radius_sq, int *city_map_data);
52 #ifdef DEBUG
53 /* only used for debugging */
54 static void citylog_map_index(enum log_level level);
55 static void citylog_map_radius_sq(enum log_level level);
56 #endif
58 /* Get city tile informations using the city tile index. */
59 static struct iter_index *city_map_index = NULL;
60 /* Get city tile informations using the city tile coordinates. This is an
61 * [x][y] array of integer values corresponding to city_map_index. The
62 * coordinates x and y are in the range [0, CITY_MAP_MAX_SIZE] */
63 static int city_map_xy[CITY_MAP_MAX_SIZE][CITY_MAP_MAX_SIZE];
65 /* number of tiles of a city; depends on the squared city radius */
66 static int city_map_numtiles[CITY_MAP_MAX_RADIUS_SQ + 1];
68 /* definitions and functions for the tile_cache */
69 struct tile_cache {
70 int output[O_LAST];
73 static inline void city_tile_cache_update(struct city *pcity);
74 static inline int city_tile_cache_get_output(const struct city *pcity,
75 int city_tile_index,
76 enum output_type_id o);
78 struct citystyle *city_styles = NULL;
80 /* One day these values may be read in from the ruleset. In the meantime
81 * they're just an easy way to access information about each output type. */
82 struct output_type output_types[O_LAST] = {
83 {O_FOOD, N_("Food"), "food", TRUE, UNHAPPY_PENALTY_SURPLUS},
84 {O_SHIELD, N_("Shield"), "shield", TRUE, UNHAPPY_PENALTY_SURPLUS},
85 {O_TRADE, N_("Trade"), "trade", TRUE, UNHAPPY_PENALTY_NONE},
86 {O_GOLD, N_("Gold"), "gold", FALSE, UNHAPPY_PENALTY_ALL_PRODUCTION},
87 {O_LUXURY, N_("Luxury"), "luxury", FALSE, UNHAPPY_PENALTY_NONE},
88 {O_SCIENCE, N_("Science"), "science", FALSE, UNHAPPY_PENALTY_ALL_PRODUCTION}
91 /**************************************************************************
92 Returns the coordinates for the given city tile index taking into account
93 the squared city radius.
94 **************************************************************************/
95 bool city_tile_index_to_xy(int *city_map_x, int *city_map_y,
96 int city_tile_index, int city_radius_sq)
98 fc_assert_ret_val(city_radius_sq >= CITY_MAP_MIN_RADIUS_SQ, FALSE);
99 fc_assert_ret_val(city_radius_sq <= CITY_MAP_MAX_RADIUS_SQ, FALSE);
101 /* tile indices are sorted from smallest to largest city radius */
102 if (city_tile_index < 0
103 || city_tile_index >= city_map_tiles(city_radius_sq)) {
104 return FALSE;
107 *city_map_x = CITY_REL2ABS(city_map_index[city_tile_index].dx);
108 *city_map_y = CITY_REL2ABS(city_map_index[city_tile_index].dy);
110 return TRUE;
113 /**************************************************************************
114 Returns the index for the given city tile coordinates taking into account
115 the squared city radius.
116 **************************************************************************/
117 int city_tile_xy_to_index(int city_map_x, int city_map_y,
118 int city_radius_sq)
120 fc_assert_ret_val(city_radius_sq >= CITY_MAP_MIN_RADIUS_SQ, 0);
121 fc_assert_ret_val(city_radius_sq <= CITY_MAP_MAX_RADIUS_SQ, 0);
122 fc_assert_ret_val(is_valid_city_coords(city_radius_sq, city_map_x,
123 city_map_y), 0);
125 return city_map_xy[city_map_x][city_map_y];
128 /**************************************************************************
129 Returns the current squared radius of the city.
130 **************************************************************************/
131 int city_map_radius_sq_get(const struct city *pcity)
133 /* a save return value is only the minimal squared radius */
134 fc_assert_ret_val(pcity != NULL, CITY_MAP_MIN_RADIUS_SQ);
136 return pcity->city_radius_sq;
139 /**************************************************************************
140 Returns the current squared radius of the city.
141 **************************************************************************/
142 void city_map_radius_sq_set(struct city *pcity, int radius_sq)
144 fc_assert_ret(radius_sq >= CITY_MAP_MIN_RADIUS_SQ);
145 fc_assert_ret(radius_sq <= CITY_MAP_MAX_RADIUS_SQ);
147 pcity->city_radius_sq = radius_sq;
150 /**************************************************************************
151 Maximum city radius in this ruleset.
152 **************************************************************************/
153 int rs_max_city_radius_sq(void)
155 int max_rad = game.info.init_city_radius_sq
156 + effect_cumulative_max(EFT_CITY_RADIUS_SQ, NULL);
158 return MIN(max_rad, CITY_MAP_MAX_RADIUS_SQ);
161 /**************************************************************************
162 Return the number of tiles for the given city radius. Special case is
163 the value -1 for no city tiles.
164 **************************************************************************/
165 int city_map_tiles(int city_radius_sq)
167 if (city_radius_sq == CITY_MAP_CENTER_RADIUS_SQ) {
168 /* special case: city center; first tile of the city map */
169 return 0;
172 fc_assert_ret_val(city_radius_sq >= CITY_MAP_MIN_RADIUS_SQ, -1);
173 fc_assert_ret_val(city_radius_sq <= CITY_MAP_MAX_RADIUS_SQ, -1);
175 return city_map_numtiles[city_radius_sq];
178 /**************************************************************************
179 Return TRUE if the given city coordinate pair is "valid"; that is, if it
180 is a part of the citymap and thus is workable by the city.
181 **************************************************************************/
182 bool is_valid_city_coords(const int city_radius_sq, const int city_map_x,
183 const int city_map_y)
185 /* The city's valid positions are in a circle around the city center.
186 * Depending on the value for the squared city radius the circle will be:
188 * - rectangular (max radius = 5; max squared radius = 26)
190 * 0 1 2 3 4 5 6 7 8 9 10
192 * 0 26 25 26 -5
193 * 1 25 20 17 16 17 20 25 -4
194 * 2 25 18 13 10 9 10 13 18 25 -3
195 * 3 20 13 8 5 4 5 8 13 20 -2
196 * 4 26 17 10 5 2 1 2 5 10 17 26 -1
197 * 5 25 16 9 4 1 0 1 4 9 16 25 +0
198 * 6 26 17 10 5 2 1 2 5 10 17 26 +1
199 * 7 20 13 8 5 4 5 8 13 20 +2
200 * 8 25 18 13 10 9 10 13 18 25 +3
201 * 9 25 20 17 16 17 20 25 +4
202 * 10 26 25 26 +5
204 * -5 -4 -3 -2 -1 +0 +1 +2 +3 +4 +5
206 * - hexagonal (max radius = 5; max squared radius = 26)
208 * 0 1 2 3 4 5 6 7 8 9 10
210 * 0 25 25 25 25 25 25 -5
211 * 1 25 16 16 16 16 16 25 -4
212 * 2 25 16 9 9 9 9 16 25 -3
213 * 3 25 16 9 4 4 4 9 16 25 -2
214 * 4 25 16 9 4 1 1 4 9 16 25 -1
215 * 5 25 16 9 4 1 0 1 4 9 16 25 +0
216 * 6 25 16 9 4 1 1 4 9 16 25 +1
217 * 7 25 16 9 4 4 4 9 16 25 +2
218 * 8 25 16 9 9 9 9 16 25 +3
219 * 9 25 16 16 16 16 16 25 +4
220 * 10 25 25 25 25 25 25 +5
222 * -5 -4 -3 -2 -1 +0 +1 +2 +3 +4 +5
224 * The following tabes show the tiles per city radii / squared city radii.
225 * '-' indicates no change compared to the previous value
227 * radius | 0 | 1 | | | 2 | | | | | 3
228 * radius_sq | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10
229 * ------------------+----+----+----+----+----+----+----+----+----+----
230 * tiles rectangular | 5 | 9 | - | 13 | 21 | - | - | 25 | 29 | 37
231 * tiles hexagonal | 7 | - | - | 19 | - | - | - | - | 37 | -
233 * radius | | | | | | | 4 | | |
234 * radius_sq | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20
235 * ------------------+----+----+----+----+----+----+----+----+----+----
236 * tiles rectangular | - | - | 45 | - | - | - | 49 | 57 | 61 | 69
237 * tiles hexagonal | - | - | - | - | - | 61 | - | - | - | -
239 * radius | | | | | | 5
240 * radius_sq | 21 | 22 | 23 | 24 | 25 | 26
241 * ------------------+----+----+----+----+----+----
242 * tiles rectangular | - | - | - | - | 81 | 89
243 * tiles hexagonal | - | - | - | - | 91 | -
245 * So radius_sq == 5 (radius == 2) corresponds to the "traditional"
246 * used city map.
248 int dist = map_vector_to_sq_distance(CITY_ABS2REL(city_map_x),
249 CITY_ABS2REL(city_map_y));
251 return dist <= city_radius_sq;
254 /**************************************************************************
255 Finds the city map coordinate for a given map position and a city
256 center. Returns whether the map position is inside of the city map.
257 **************************************************************************/
258 bool city_tile_to_city_map(int *city_map_x, int *city_map_y,
259 const int city_radius_sq,
260 const struct tile *city_center,
261 const struct tile *map_tile)
263 map_distance_vector(city_map_x, city_map_y, city_center, map_tile);
265 *city_map_x += CITY_MAP_MAX_RADIUS;
266 *city_map_y += CITY_MAP_MAX_RADIUS;
268 return is_valid_city_coords(city_radius_sq, *city_map_x, *city_map_y);
271 /**************************************************************************
272 Finds the city map coordinate for a given map position and a
273 city. Returns whether the map position is inside of the city map.
274 **************************************************************************/
275 bool city_base_to_city_map(int *city_map_x, int *city_map_y,
276 const struct city *const pcity,
277 const struct tile *map_tile)
279 return city_tile_to_city_map(city_map_x, city_map_y,
280 city_map_radius_sq_get(pcity), pcity->tile,
281 map_tile);
284 /**************************************************************************
285 Finds the map position for a given city map coordinate of a certain
286 city. Returns true if the map position found is real.
287 **************************************************************************/
288 struct tile *city_map_to_tile(const struct tile *city_center,
289 int city_radius_sq, int city_map_x,
290 int city_map_y)
292 int tile_x, tile_y;
294 fc_assert_ret_val(is_valid_city_coords(city_radius_sq, city_map_x,
295 city_map_y), NULL);
297 index_to_map_pos(&tile_x, &tile_y, tile_index(city_center));
298 tile_x += CITY_ABS2REL(city_map_x);
299 tile_y += CITY_ABS2REL(city_map_y);
301 return map_pos_to_tile(tile_x, tile_y);
304 /**************************************************************************
305 Compare two integer values, as required by qsort.
306 ***************************************************************************/
307 static int cmp(int v1, int v2)
309 if (v1 == v2) {
310 return 0;
311 } else if (v1 > v2) {
312 return 1;
313 } else {
314 return -1;
318 /**************************************************************************
319 Compare two iter_index values from the city_map_index.
321 This function will be passed to qsort(). It should never return zero,
322 or the sort order will be left up to qsort and will be undefined. This
323 would mean that server execution would not be reproducable.
324 ***************************************************************************/
325 int compare_iter_index(const void *a, const void *b)
327 const struct iter_index *index1 = a, *index2 = b;
328 int value;
330 value = cmp(index1->dist, index2->dist);
331 if (value != 0) {
332 return value;
335 value = cmp(index1->dx, index2->dx);
336 if (value != 0) {
337 return value;
340 value = cmp(index1->dy, index2->dy);
341 fc_assert(0 != value);
342 return value;
345 /****************************************************************************
346 Return one line (y coordinate) of a city map. *city_map_data is a pointer
347 to an array containing the data which should be printed. Its size is
348 defined by city_map_tiles(city_radius_sq).
349 *****************************************************************************/
350 #define CITYLOG_MAX_VAL 9999 /* maximal value displayed in the citylog */
351 static char *citylog_map_line(int y, int city_radius_sq, int *city_map_data)
353 int x, mindex;
354 static char citylog[128], tmp[8];
356 fc_assert_ret_val(city_map_data != NULL, NULL);
358 /* print y coordinates (absolut) */
359 fc_snprintf(citylog, sizeof(citylog), "%2d ", y);
361 /* print values */
362 for (x = 0; x < CITY_MAP_MAX_SIZE; x++) {
363 if (is_valid_city_coords(city_radius_sq, x, y)) {
364 mindex = city_tile_xy_to_index(x, y, city_radius_sq);
365 /* show values between -10000 and +10000 */
366 if (city_map_data[mindex] >= -CITYLOG_MAX_VAL
367 && city_map_data[mindex] <= CITYLOG_MAX_VAL) {
368 fc_snprintf(tmp, sizeof(tmp), "%5d", city_map_data[mindex]);
369 sz_strlcat(citylog, tmp);
370 } else {
371 fc_snprintf(tmp, sizeof(tmp), " ####");
372 sz_strlcat(citylog, tmp);
374 } else {
375 fc_snprintf(tmp, sizeof(tmp), " ");
376 sz_strlcat(citylog, tmp);
380 /* print y coordinates (relativ) */
381 fc_snprintf(tmp, sizeof(tmp), " %+4d", CITY_ABS2REL(y));
382 sz_strlcat(citylog, tmp);
384 return citylog;
386 #undef CITYLOG_MAX_VAL
388 /****************************************************************************
389 Display 'map_data' on a city map with the given radius 'radius_sq' for the
390 requested log level. The size of 'map_data' is defined by
391 city_map_tiles(radius_sq).
392 *****************************************************************************/
393 void citylog_map_data(enum log_level level, int radius_sq, int *map_data)
395 int x, y;
396 char line[128], tmp[8];
398 if (!log_do_output_for_level(level)) {
399 return;
402 log_base(level, "(max squared city radius = %d)", CITY_MAP_MAX_RADIUS_SQ);
404 /* print x coordinates (absolut) */
405 fc_snprintf(line, sizeof(line), " ");
406 for (x = 0; x < CITY_MAP_MAX_SIZE; x++) {
407 fc_snprintf(tmp, sizeof(tmp), "%+5d", x);
408 sz_strlcat(line, tmp);
410 log_base(level, "%s", line);
412 for (y = 0; y < CITY_MAP_MAX_SIZE; y++) {
413 log_base(level, "%s", citylog_map_line(y, radius_sq, map_data));
416 /* print x coordinates (relativ) */
417 fc_snprintf(line, sizeof(line), " ");
418 for (x = 0; x < CITY_MAP_MAX_SIZE; x++) {
419 fc_snprintf(tmp, sizeof(tmp), "%+5d", CITY_ABS2REL(x));
420 sz_strlcat(line, tmp);
422 log_base(level, "%s", line);
425 /****************************************************************************
426 Display the location of the workers within the city map of pcity.
427 *****************************************************************************/
428 void citylog_map_workers(enum log_level level, struct city *pcity)
430 int *city_map_data = NULL;
432 fc_assert_ret(pcity != NULL);
434 if (!log_do_output_for_level(level)) {
435 return;
438 city_map_data = fc_calloc(city_map_tiles(city_map_radius_sq_get(pcity)),
439 sizeof(*city_map_data));
441 city_map_iterate(city_map_radius_sq_get(pcity), cindex, x, y) {
442 struct tile *ptile = city_map_to_tile(city_tile(pcity),
443 city_map_radius_sq_get(pcity),
444 x, y);
445 city_map_data[cindex] = (ptile && tile_worked(ptile) == pcity)
446 ? (is_free_worked_index(cindex) ? 2 : 1) : 0;
447 } city_map_iterate_end;
449 log_base(level, "[%s (%d)] workers map:", city_name_get(pcity), pcity->id);
450 citylog_map_data(level, city_map_radius_sq_get(pcity), city_map_data);
451 FC_FREE(city_map_data);
454 #ifdef FREECIV_DEBUG
455 /****************************************************************************
456 Log the index of all tiles of the city map.
457 *****************************************************************************/
458 static void citylog_map_index(enum log_level level)
460 int *city_map_data = NULL;
462 if (!log_do_output_for_level(level)) {
463 return;
466 city_map_data = fc_calloc(city_map_tiles(CITY_MAP_MAX_RADIUS_SQ),
467 sizeof(*city_map_data));
469 city_map_iterate(CITY_MAP_MAX_RADIUS_SQ, cindex, x, y) {
470 city_map_data[cindex] = cindex;
471 } city_map_iterate_end;
473 log_debug("city map index:");
474 citylog_map_data(level, CITY_MAP_MAX_RADIUS_SQ, city_map_data);
475 FC_FREE(city_map_data);
478 /****************************************************************************
479 Log the radius of all tiles of the city map.
480 *****************************************************************************/
481 static void citylog_map_radius_sq(enum log_level level)
483 int *city_map_data = NULL;
485 if (!log_do_output_for_level(level)) {
486 return;
489 city_map_data = fc_calloc(city_map_tiles(CITY_MAP_MAX_RADIUS_SQ),
490 sizeof(*city_map_data));
492 city_map_iterate(CITY_MAP_MAX_RADIUS_SQ, cindex, x, y) {
493 city_map_data[cindex] = map_vector_to_sq_distance(CITY_ABS2REL(x),
494 CITY_ABS2REL(y));
495 } city_map_iterate_end;
497 log_debug("city map squared radius:");
498 citylog_map_data(level, CITY_MAP_MAX_RADIUS_SQ, city_map_data);
499 FC_FREE(city_map_data);
501 #endif /* FREECIV_DEBUG */
503 /**************************************************************************
504 Fill the arrays city_map_index, city_map_xy and city_map_numtiles. This
505 may depend on topology and ruleset settings.
506 ***************************************************************************/
507 void generate_city_map_indices(void)
509 int i, dx, dy, city_x, city_y, dist, city_count_tiles = 0;
510 struct iter_index city_map_index_tmp[CITY_MAP_MAX_SIZE
511 * CITY_MAP_MAX_SIZE];
513 /* initialise map information for each city radii */
514 for (i = 0; i <= CITY_MAP_MAX_RADIUS_SQ; i++) {
515 city_map_numtiles[i] = 0; /* will be set below */
518 /* We don't use city-map iterators in this function because they may
519 * rely on the indices that have not yet been generated. Furthermore,
520 * we don't know the number of tiles within the city radius, so we need
521 * an temporary city_map_index array. Its content will be copied into
522 * the real array below. */
523 for (dx = -CITY_MAP_MAX_RADIUS; dx <= CITY_MAP_MAX_RADIUS; dx++) {
524 for (dy = -CITY_MAP_MAX_RADIUS; dy <= CITY_MAP_MAX_RADIUS; dy++) {
525 dist = map_vector_to_sq_distance(dx, dy);
527 if (dist <= CITY_MAP_MAX_RADIUS_SQ) {
528 city_map_index_tmp[city_count_tiles].dx = dx;
529 city_map_index_tmp[city_count_tiles].dy = dy;
530 city_map_index_tmp[city_count_tiles].dist = dist;
532 for (i = CITY_MAP_MAX_RADIUS_SQ; i >= 0; i--) {
533 if (dist <= i) {
534 /* increase number of tiles within this squared city radius */
535 city_map_numtiles[i]++;
539 city_count_tiles++;
542 /* Initialise city_map_xy. -1 defines a invalid city map positions. */
543 city_map_xy[CITY_REL2ABS(dx)][CITY_REL2ABS(dy)] = -1;
547 fc_assert(NULL == city_map_index);
548 city_map_index = fc_malloc(city_count_tiles * sizeof(*city_map_index));
550 /* copy the index numbers from city_map_index_tmp into city_map_index */
551 for (i = 0; i < city_count_tiles; i++) {
552 city_map_index[i] = city_map_index_tmp[i];
555 qsort(city_map_index, city_count_tiles, sizeof(*city_map_index),
556 compare_iter_index);
558 /* set the static variable city_map_xy */
559 for (i = 0; i < city_count_tiles; i++) {
560 city_x = CITY_REL2ABS(city_map_index[i].dx);
561 city_y = CITY_REL2ABS(city_map_index[i].dy);
562 city_map_xy[city_x][city_y] = i;
565 #ifdef DEBUG
566 citylog_map_radius_sq(LOG_DEBUG);
567 citylog_map_index(LOG_DEBUG);
569 for (i = CITY_MAP_MIN_RADIUS_SQ; i <= CITY_MAP_MAX_RADIUS_SQ; i++) {
570 log_debug("radius_sq = %2d, tiles = %2d", i, city_map_tiles(i));
573 for (i = 0; i < city_count_tiles; i++) {
574 city_x = CITY_REL2ABS(city_map_index[i].dx);
575 city_y = CITY_REL2ABS(city_map_index[i].dy);
576 log_debug("[%2d]: (dx,dy) = (%+2d,%+2d), (x,y) = (%2d,%2d), "
577 "dist = %2d, check = %2d", i,
578 city_map_index[i].dx, city_map_index[i].dy, city_x, city_y,
579 city_map_index[i].dist, city_map_xy[city_x][city_y]);
581 #endif /* DEBUG */
583 cm_init_citymap();
586 /****************************************************************************
587 Free memory allocated by generate_citymap_index
588 *****************************************************************************/
589 void free_city_map_index(void)
591 FC_FREE(city_map_index);
594 /****************************************************************************
595 Return an id string for the output type. This string can be used
596 internally by rulesets and tilesets and should not be changed or
597 translated.
598 *****************************************************************************/
599 const char *get_output_identifier(Output_type_id output)
601 fc_assert_ret_val(output >= 0 && output < O_LAST, NULL);
602 return output_types[output].id;
605 /****************************************************************************
606 Return a translated name for the output type. This name should only be
607 used for user display.
608 *****************************************************************************/
609 const char *get_output_name(Output_type_id output)
611 fc_assert_ret_val(output >= 0 && output < O_LAST, NULL);
612 return _(output_types[output].name);
615 /****************************************************************************
616 Return the output type for this index.
617 ****************************************************************************/
618 struct output_type *get_output_type(Output_type_id output)
620 fc_assert_ret_val(output >= 0 && output < O_LAST, NULL);
621 return &output_types[output];
624 /**************************************************************************
625 Find the output type for this output identifier.
626 **************************************************************************/
627 Output_type_id output_type_by_identifier(const char *id)
629 Output_type_id o;
631 for (o = 0; o < O_LAST; o++) {
632 if (fc_strcasecmp(output_types[o].name, id) == 0) {
633 return o;
637 return O_LAST;
640 /**************************************************************************
641 Return the extended name of the building.
642 **************************************************************************/
643 const char *city_improvement_name_translation(const struct city *pcity,
644 struct impr_type *pimprove)
646 static char buffer[256];
647 const char *state = NULL;
649 if (is_great_wonder(pimprove)) {
650 if (great_wonder_is_available(pimprove)) {
651 state = Q_("?wonder:W");
652 } else if (great_wonder_is_destroyed(pimprove)) {
653 state = Q_("?destroyed:D");
654 } else {
655 state = Q_("?built:B");
658 if (pcity) {
659 struct player *pplayer = city_owner(pcity);
661 if (improvement_obsolete(pplayer, pimprove, pcity)) {
662 state = Q_("?obsolete:O");
663 } else if (is_improvement_redundant(pcity, pimprove)) {
664 state = Q_("?redundant:*");
668 if (state) {
669 fc_snprintf(buffer, sizeof(buffer), "%s(%s)",
670 improvement_name_translation(pimprove), state);
671 return buffer;
672 } else {
673 return improvement_name_translation(pimprove);
677 /**************************************************************************
678 Return the extended name of the current production.
679 **************************************************************************/
680 const char *city_production_name_translation(const struct city *pcity)
682 static char buffer[256];
684 switch (pcity->production.kind) {
685 case VUT_IMPROVEMENT:
686 return city_improvement_name_translation(pcity, pcity->production.value.building);
687 default:
688 /* fallthru */
689 break;
691 return universal_name_translation(&pcity->production, buffer, sizeof(buffer));
694 /**************************************************************************
695 Return TRUE when the current production has this flag.
696 **************************************************************************/
697 bool city_production_has_flag(const struct city *pcity,
698 enum impr_flag_id flag)
700 return VUT_IMPROVEMENT == pcity->production.kind
701 && improvement_has_flag(pcity->production.value.building, flag);
704 /**************************************************************************
705 Return the number of shields it takes to build current city production.
706 **************************************************************************/
707 int city_production_build_shield_cost(const struct city *pcity)
709 return universal_build_shield_cost(&pcity->production);
712 /**************************************************************************
713 Return TRUE if the city could use the additional build slots provided by
714 the effect City_Build_Slots. Within 'num_units' the total number of units
715 the city can build considering the current shield stock is returned.
716 **************************************************************************/
717 bool city_production_build_units(const struct city *pcity,
718 bool add_production, int *num_units)
720 struct unit_type *utype;
721 struct universal target;
722 int build_slots = city_build_slots(pcity);
723 int shields_left = pcity->shield_stock;
724 int unit_shield_cost, i;
726 fc_assert_ret_val(num_units != NULL, FALSE);
727 (*num_units) = 0;
729 if (pcity->production.kind != VUT_UTYPE) {
730 /* not a unit as the current production */
731 return FALSE;
734 utype = pcity->production.value.utype;
735 if (utype_pop_value(utype) != 0 || utype_has_flag(utype, UTYF_UNIQUE)) {
736 /* unit with population cost or unique unit means that only one unit can
737 * be build */
738 (*num_units)++;
739 return FALSE;
742 if (add_production) {
743 shields_left += pcity->prod[O_SHIELD];
746 unit_shield_cost = utype_build_shield_cost(utype);
748 for (i = 0; i < build_slots; i++) {
749 if (shields_left < unit_shield_cost) {
750 /* not enough shields */
751 break;
754 (*num_units)++;
755 shields_left -= unit_shield_cost;
757 if (worklist_length(&pcity->worklist) > i) {
758 (void) worklist_peek_ith(&pcity->worklist, &target, i);
759 if (target.kind != VUT_UTYPE
760 || utype_index(target.value.utype) != utype_index(utype)) {
761 /* stop if there is a build target in the worklist not equal to the
762 * unit we build */
763 break;
768 return TRUE;
771 /**************************************************************************
772 Return the cost (gold) to buy the current city production.
773 **************************************************************************/
774 int city_production_buy_gold_cost(const struct city *pcity)
776 int build = pcity->shield_stock;
778 switch (pcity->production.kind) {
779 case VUT_IMPROVEMENT:
780 return impr_buy_gold_cost(pcity->production.value.building,
781 build);
782 case VUT_UTYPE:
783 return utype_buy_gold_cost(pcity->production.value.utype,
784 build);
785 default:
786 break;
788 return FC_INFINITY;
791 /**************************************************************************
792 Calculates the turns which are needed to build the requested
793 production in the city. GUI Independent.
794 **************************************************************************/
795 int city_production_turns_to_build(const struct city *pcity,
796 bool include_shield_stock)
798 return city_turns_to_build(pcity, &pcity->production, include_shield_stock);
801 /**************************************************************************
802 Return whether given city can build given building, ignoring whether
803 it is obsolete.
804 **************************************************************************/
805 bool can_city_build_improvement_direct(const struct city *pcity,
806 struct impr_type *pimprove)
808 if (!can_player_build_improvement_direct(city_owner(pcity), pimprove)) {
809 return FALSE;
812 if (city_has_building(pcity, pimprove)) {
813 return FALSE;
816 return are_reqs_active(city_owner(pcity), NULL, pcity, NULL,
817 pcity->tile, NULL, NULL, NULL, NULL,
818 &(pimprove->reqs), RPT_CERTAIN);
821 /**************************************************************************
822 Return whether given city can build given building; returns FALSE if
823 the building is obsolete.
824 **************************************************************************/
825 bool can_city_build_improvement_now(const struct city *pcity,
826 struct impr_type *pimprove)
828 if (!can_city_build_improvement_direct(pcity, pimprove)) {
829 return FALSE;
831 if (improvement_obsolete(city_owner(pcity), pimprove, pcity)) {
832 return FALSE;
834 return TRUE;
837 /**************************************************************************
838 Return whether player can eventually build given building in the city;
839 returns FALSE if improvement can never possibly be built in this city.
840 **************************************************************************/
841 bool can_city_build_improvement_later(const struct city *pcity,
842 struct impr_type *pimprove)
844 /* Can the _player_ ever build this improvement? */
845 if (!can_player_build_improvement_later(city_owner(pcity), pimprove)) {
846 return FALSE;
849 /* Check for requirements that aren't met and that are unchanging (so
850 * they can never be met). */
851 requirement_vector_iterate(&pimprove->reqs, preq) {
852 if (is_req_unchanging(preq)
853 && !is_req_active(city_owner(pcity), NULL, pcity, NULL,
854 pcity->tile, NULL, NULL, NULL, NULL,
855 preq, RPT_POSSIBLE)) {
856 return FALSE;
858 } requirement_vector_iterate_end;
859 return TRUE;
862 /**************************************************************************
863 Return whether given city can build given unit, ignoring whether unit
864 is obsolete.
865 **************************************************************************/
866 bool can_city_build_unit_direct(const struct city *pcity,
867 const struct unit_type *punittype)
869 if (!can_player_build_unit_direct(city_owner(pcity), punittype)) {
870 return FALSE;
873 /* Check to see if the unit has a building requirement. */
874 if (punittype->need_improvement
875 && !city_has_building(pcity, punittype->need_improvement)) {
876 return FALSE;
879 /* You can't build naval units inland. */
880 if (!uclass_has_flag(utype_class(punittype), UCF_BUILD_ANYWHERE)
881 && !is_native_near_tile(utype_class(punittype), pcity->tile)) {
882 return FALSE;
884 return TRUE;
887 /**************************************************************************
888 Return whether given city can build given unit; returns FALSE if unit is
889 obsolete.
890 **************************************************************************/
891 bool can_city_build_unit_now(const struct city *pcity,
892 const struct unit_type *punittype)
894 if (!can_city_build_unit_direct(pcity, punittype)) {
895 return FALSE;
897 while ((punittype = punittype->obsoleted_by) != U_NOT_OBSOLETED) {
898 if (can_player_build_unit_direct(city_owner(pcity), punittype)) {
899 return FALSE;
902 return TRUE;
905 /**************************************************************************
906 Returns whether player can eventually build given unit in the city;
907 returns FALSE if unit can never possibly be built in this city.
908 **************************************************************************/
909 bool can_city_build_unit_later(const struct city *pcity,
910 const struct unit_type *punittype)
912 /* Can the _player_ ever build this unit? */
913 if (!can_player_build_unit_later(city_owner(pcity), punittype)) {
914 return FALSE;
917 /* Some units can be built only in certain cities -- for instance,
918 ships may be built only in cities adjacent to ocean. */
919 if (!uclass_has_flag(utype_class(punittype), UCF_BUILD_ANYWHERE)
920 && !is_native_near_tile(utype_class(punittype), pcity->tile)) {
921 return FALSE;
924 return TRUE;
927 /**************************************************************************
928 Returns whether city can immediately build given target,
929 unit or improvement. This considers obsolete targets still buildable.
930 **************************************************************************/
931 bool can_city_build_direct(const struct city *pcity,
932 const struct universal *target)
934 switch (target->kind) {
935 case VUT_UTYPE:
936 return can_city_build_unit_direct(pcity, target->value.utype);
937 case VUT_IMPROVEMENT:
938 return can_city_build_improvement_direct(pcity, target->value.building);
939 default:
940 break;
942 return FALSE;
945 /**************************************************************************
946 Returns whether city can immediately build given target,
947 unit or improvement. This considers obsolete targets no longer buildable.
948 **************************************************************************/
949 bool can_city_build_now(const struct city *pcity,
950 const struct universal *target)
952 switch (target->kind) {
953 case VUT_UTYPE:
954 return can_city_build_unit_now(pcity, target->value.utype);
955 case VUT_IMPROVEMENT:
956 return can_city_build_improvement_now(pcity, target->value.building);
957 default:
958 break;
960 return FALSE;
963 /**************************************************************************
964 Returns whether city can ever build given target, unit or improvement.
965 **************************************************************************/
966 bool can_city_build_later(const struct city *pcity,
967 const struct universal *target)
969 switch (target->kind) {
970 case VUT_UTYPE:
971 return can_city_build_unit_later(pcity, target->value.utype);
972 case VUT_IMPROVEMENT:
973 return can_city_build_improvement_later(pcity, target->value.building);
974 default:
975 break;
977 return FALSE;
980 /****************************************************************************
981 Returns TRUE iff the given city can use this kind of specialist.
982 ****************************************************************************/
983 bool city_can_use_specialist(const struct city *pcity,
984 Specialist_type_id type)
986 return are_reqs_active(city_owner(pcity), NULL, pcity, NULL,
987 NULL, NULL, NULL, NULL, NULL,
988 &specialist_by_number(type)->reqs, RPT_POSSIBLE);
991 /****************************************************************************
992 Returns TRUE iff the given city can change what it is building
993 ****************************************************************************/
994 bool city_can_change_build(const struct city *pcity)
996 return !pcity->did_buy || pcity->shield_stock <= 0;
999 /**************************************************************************
1000 Always tile_set_owner(ptile, pplayer) sometime before this!
1001 **************************************************************************/
1002 void city_choose_build_default(struct city *pcity)
1004 if (NULL == city_tile(pcity)) {
1005 /* When a "dummy" city is created with no tile, then choosing a build
1006 * target could fail. This currently might happen during map editing.
1007 * FIXME: assumes the first unit is always "valid", so check for
1008 * obsolete units elsewhere. */
1009 pcity->production.kind = VUT_UTYPE;
1010 pcity->production.value.utype = utype_by_number(0);
1011 } else {
1012 struct unit_type *u = best_role_unit(pcity, L_FIRSTBUILD);
1014 if (u) {
1015 pcity->production.kind = VUT_UTYPE;
1016 pcity->production.value.utype = u;
1017 } else {
1018 bool found = FALSE;
1020 /* Just pick the first available item. */
1022 improvement_iterate(pimprove) {
1023 if (can_city_build_improvement_direct(pcity, pimprove)) {
1024 found = TRUE;
1025 pcity->production.kind = VUT_IMPROVEMENT;
1026 pcity->production.value.building = pimprove;
1027 break;
1029 } improvement_iterate_end;
1031 if (!found) {
1032 unit_type_iterate(punittype) {
1033 if (can_city_build_unit_direct(pcity, punittype)) {
1034 found = TRUE;
1035 pcity->production.kind = VUT_UTYPE;
1036 pcity->production.value.utype = punittype;
1038 } unit_type_iterate_end;
1041 fc_assert_msg(found, "No production found for city %s!",
1042 city_name_get(pcity));
1047 #ifndef city_name_get
1048 /**************************************************************************
1049 Return the name of the city.
1050 **************************************************************************/
1051 const char *city_name_get(const struct city *pcity)
1053 return pcity->name;
1055 #endif /* city_name_get */
1057 /**************************************************************************
1058 Return the owner of the city.
1059 **************************************************************************/
1060 struct player *city_owner(const struct city *pcity)
1062 fc_assert_ret_val(NULL != pcity, NULL);
1063 fc_assert(NULL != pcity->owner);
1064 return pcity->owner;
1067 #ifndef city_tile
1068 /**************************************************************************
1069 Return the tile location of the city.
1070 Not (yet) always used, mostly for debugging.
1071 **************************************************************************/
1072 struct tile *city_tile(const struct city *pcity)
1074 return pcity->tile;
1076 #endif
1079 /*****************************************************************************
1080 Get the city size.
1081 *****************************************************************************/
1082 citizens city_size_get(const struct city *pcity)
1084 fc_assert_ret_val(pcity != NULL, 0);
1086 return pcity->size;
1089 /*****************************************************************************
1090 Add a (positive or negative) value to the city size. As citizens is an
1091 unsigned value use int for the parameter 'add'.
1092 *****************************************************************************/
1093 void city_size_add(struct city *pcity, int add)
1095 citizens size = city_size_get(pcity);
1097 fc_assert_ret(pcity != NULL);
1098 fc_assert_ret(MAX_CITY_SIZE - size > add);
1099 fc_assert_ret(size >= -add);
1101 city_size_set(pcity, city_size_get(pcity) + add);
1104 /*****************************************************************************
1105 Set the city size.
1106 *****************************************************************************/
1107 void city_size_set(struct city *pcity, citizens size)
1109 fc_assert_ret(pcity != NULL);
1111 /* Set city size. */
1112 pcity->size = size;
1115 /**************************************************************************
1116 Returns how many thousand citizen live in this city.
1117 **************************************************************************/
1118 int city_population(const struct city *pcity)
1120 /* Sum_{i=1}^{n} i == n*(n+1)/2 */
1121 return city_size_get(pcity) * (city_size_get(pcity) + 1) * 5;
1124 /**************************************************************************
1125 Returns the total amount of gold needed to pay for all buildings in the
1126 city.
1127 **************************************************************************/
1128 int city_total_impr_gold_upkeep(const struct city *pcity)
1130 int gold_needed = 0;
1132 if (!pcity) {
1133 return 0;
1136 city_built_iterate(pcity, pimprove) {
1137 gold_needed += city_improvement_upkeep(pcity, pimprove);
1138 } city_built_iterate_end;
1140 return gold_needed;
1143 /***************************************************************************
1144 Get the total amount of gold needed to pay upkeep costs for all supported
1145 units of the city. Takes into account EFT_UNIT_UPKEEP_FREE_PER_CITY.
1146 ***************************************************************************/
1147 int city_total_unit_gold_upkeep(const struct city *pcity)
1149 int gold_needed = 0;
1151 if (!pcity || !pcity->units_supported
1152 || unit_list_size(pcity->units_supported) < 1) {
1153 return 0;
1156 unit_list_iterate(pcity->units_supported, punit) {
1157 gold_needed += punit->upkeep[O_GOLD];
1158 } unit_list_iterate_end;
1160 return gold_needed;
1163 /**************************************************************************
1164 Return TRUE iff the city has this building in it.
1165 **************************************************************************/
1166 bool city_has_building(const struct city *pcity,
1167 const struct impr_type *pimprove)
1169 if (NULL == pimprove) {
1170 /* callers should ensure that any external data is tested with
1171 * valid_improvement_by_number() */
1172 return FALSE;
1174 return (pcity->built[improvement_index(pimprove)].turn > I_NEVER);
1177 /**************************************************************************
1178 Return the upkeep (gold) needed each turn to upkeep the given improvement
1179 in the given city.
1180 **************************************************************************/
1181 int city_improvement_upkeep(const struct city *pcity,
1182 const struct impr_type *b)
1184 int upkeep;
1186 if (NULL == b)
1187 return 0;
1188 if (is_wonder(b))
1189 return 0;
1191 upkeep = b->upkeep;
1192 if (upkeep <= get_building_bonus(pcity, b, EFT_UPKEEP_FREE)) {
1193 return 0;
1196 return upkeep;
1199 /**************************************************************************
1200 Calculate the output for the tile.
1201 pcity may be NULL.
1202 is_celebrating may be speculative.
1203 otype is the output type (generally O_FOOD, O_TRADE, or O_SHIELD).
1205 This can be used to calculate the benefits celebration would give.
1206 **************************************************************************/
1207 int city_tile_output(const struct city *pcity, const struct tile *ptile,
1208 bool is_celebrating, Output_type_id otype)
1210 int prod;
1211 struct terrain *pterrain = tile_terrain(ptile);
1212 const struct output_type *output = &output_types[otype];
1213 struct player *pplayer = NULL;
1215 fc_assert_ret_val(otype >= 0 && otype < O_LAST, 0);
1217 if (T_UNKNOWN == pterrain) {
1218 /* Special case for the client. The server doesn't allow unknown tiles
1219 * to be worked but we don't necessarily know what player is involved. */
1220 return 0;
1223 prod = pterrain->output[otype];
1224 if (tile_resource_is_valid(ptile)) {
1225 prod += tile_resource(ptile)->output[otype];
1228 if (pcity != NULL) {
1229 pplayer = city_owner(pcity);
1232 switch (otype) {
1233 case O_SHIELD:
1234 if (pterrain->mining_shield_incr != 0) {
1235 prod += pterrain->mining_shield_incr
1236 * get_target_bonus_effects(NULL, pplayer, NULL, pcity, NULL,
1237 ptile, NULL, NULL, NULL, NULL,
1238 EFT_MINING_PCT)
1239 / 100;
1241 break;
1242 case O_FOOD:
1243 if (pterrain->irrigation_food_incr != 0) {
1244 prod += pterrain->irrigation_food_incr
1245 * get_target_bonus_effects(NULL, pplayer, NULL, pcity, NULL,
1246 ptile, NULL, NULL, NULL, NULL,
1247 EFT_IRRIGATION_PCT)
1248 / 100;
1250 break;
1251 case O_TRADE:
1252 case O_GOLD:
1253 case O_SCIENCE:
1254 case O_LUXURY:
1255 case O_LAST:
1256 break;
1259 prod += tile_roads_output_incr(ptile, otype);
1260 prod += (prod * tile_roads_output_bonus(ptile, otype) / 100);
1262 if (pcity) {
1263 prod += get_city_tile_output_bonus(pcity, ptile, output,
1264 EFT_OUTPUT_ADD_TILE);
1265 if (prod > 0) {
1266 int penalty_limit = get_city_tile_output_bonus(pcity, ptile, output,
1267 EFT_OUTPUT_PENALTY_TILE);
1269 if (is_celebrating) {
1270 prod += get_city_tile_output_bonus(pcity, ptile, output,
1271 EFT_OUTPUT_INC_TILE_CELEBRATE);
1272 penalty_limit = 0; /* no penalty if celebrating */
1274 prod += get_city_tile_output_bonus(pcity, ptile, output,
1275 EFT_OUTPUT_INC_TILE);
1276 prod += (prod
1277 * get_city_tile_output_bonus(pcity, ptile, output,
1278 EFT_OUTPUT_PER_TILE))
1279 / 100;
1280 if (!is_celebrating && penalty_limit > 0 && prod > penalty_limit) {
1281 prod--;
1286 prod -= (prod
1287 * get_target_bonus_effects(NULL, pplayer, NULL, pcity, NULL,
1288 ptile, NULL, NULL, output, NULL,
1289 EFT_OUTPUT_TILE_PUNISH_PCT))
1290 / 100;
1292 if (NULL != pcity && is_city_center(pcity, ptile)) {
1293 prod = MAX(prod, game.info.min_city_center_output[otype]);
1296 return prod;
1299 /**************************************************************************
1300 Calculate the production output the given tile is capable of producing
1301 for the city. The output type is given by 'otype' (generally O_FOOD,
1302 O_SHIELD, or O_TRADE).
1303 **************************************************************************/
1304 int city_tile_output_now(const struct city *pcity, const struct tile *ptile,
1305 Output_type_id otype)
1307 return city_tile_output(pcity, ptile, city_celebrating(pcity), otype);
1310 /****************************************************************************
1311 Returns TRUE when a tile is available to be worked, or the city itself is
1312 currently working the tile (and can continue).
1314 The paramter 'restriction', which is usually client_player(), allow a
1315 player to handle with its real knownledge to guess it the work of this
1316 tile is possible.
1318 This function shouldn't be called directly, but with city_can_work_tile()
1319 (common/city.[ch]) or client_city_can_work_tile() (client/climap.[ch]).
1320 ****************************************************************************/
1321 bool base_city_can_work_tile(const struct player *restriction,
1322 const struct city *pcity,
1323 const struct tile *ptile)
1325 struct player *powner = city_owner(pcity);
1326 int city_map_x, city_map_y;
1328 if (NULL == ptile) {
1329 return FALSE;
1332 if (!city_base_to_city_map(&city_map_x, &city_map_y, pcity, ptile)) {
1333 return FALSE;
1336 if (NULL != restriction
1337 && TILE_UNKNOWN == tile_get_known(ptile, restriction)) {
1338 return FALSE;
1341 if (NULL != tile_owner(ptile) && tile_owner(ptile) != powner) {
1342 return FALSE;
1344 /* TODO: civ3-like option for borders */
1346 if (NULL != tile_worked(ptile) && tile_worked(ptile) != pcity) {
1347 return FALSE;
1350 if (powner == restriction
1351 && TILE_KNOWN_SEEN != tile_get_known(ptile, powner)) {
1352 return FALSE;
1355 if (!is_free_worked(pcity, ptile)
1356 && NULL != unit_occupies_tile(ptile, powner)) {
1357 return FALSE;
1360 if (get_city_tile_output_bonus(pcity, ptile, NULL, EFT_TILE_WORKABLE) <= 0) {
1361 return FALSE;
1364 return TRUE;
1367 /**************************************************************************
1368 Returns TRUE when a tile is available to be worked, or the city itself is
1369 currently working the tile (and can continue).
1371 See also client_city_can_work_tile() (client/climap.[ch]).
1372 **************************************************************************/
1373 bool city_can_work_tile(const struct city *pcity, const struct tile *ptile)
1375 return base_city_can_work_tile(city_owner(pcity), pcity, ptile);
1378 /****************************************************************************
1379 Returns TRUE if the given unit can build a city at the given map
1380 coordinates.
1382 punit is the founding unit. It may be NULL if a city is built out of the
1383 blue (e.g., through editing).
1384 ****************************************************************************/
1385 bool city_can_be_built_here(const struct tile *ptile,
1386 const struct unit *punit)
1388 return (CB_OK == city_build_here_test(ptile, punit));
1391 /****************************************************************************
1392 Returns CB_OK if the given unit can build a city at the given map
1393 coordinates. Else, returns the reason of the failure.
1395 punit is the founding unit. It may be NULL if a city is built out of the
1396 blue (e.g., through editing).
1397 ****************************************************************************/
1398 enum city_build_result city_build_here_test(const struct tile *ptile,
1399 const struct unit *punit)
1401 int citymindist;
1403 if (terrain_has_flag(tile_terrain(ptile), TER_NO_CITIES)) {
1404 /* No cities on this terrain. */
1405 return CB_BAD_CITY_TERRAIN;
1408 if (punit && !can_unit_exist_at_tile(punit, ptile)) {
1409 /* We allow land units to build land cities and sea units to build
1410 * ocean cities. Air units can build cities anywhere. */
1411 return CB_BAD_UNIT_TERRAIN;
1414 if (punit && tile_owner(ptile) && tile_owner(ptile) != unit_owner(punit)) {
1415 /* Cannot steal borders by settling. This has to be settled by
1416 * force of arms. */
1417 return CB_BAD_BORDERS;
1420 /* citymindist minimum is 1, meaning adjacent is okay */
1421 citymindist = game.info.citymindist;
1422 square_iterate(ptile, citymindist - 1, ptile1) {
1423 if (tile_city(ptile1)) {
1424 return CB_NO_MIN_DIST;
1426 } square_iterate_end;
1428 return CB_OK;
1431 /**************************************************************************
1432 Return TRUE iff this city is its nation's capital. The capital city is
1433 special-cased in a number of ways.
1434 **************************************************************************/
1435 bool is_capital(const struct city *pcity)
1437 return (get_city_bonus(pcity, EFT_CAPITAL_CITY) > 0);
1440 /**************************************************************************
1441 Return TRUE iff this city is governmental center.
1442 **************************************************************************/
1443 bool is_gov_center(const struct city *pcity)
1445 return (get_city_bonus(pcity, EFT_GOV_CENTER) > 0);
1448 /**************************************************************************
1449 This can be City Walls, Coastal defense... depending on attacker type.
1450 If attacker type is not given, just any defense effect will do.
1451 **************************************************************************/
1452 bool city_got_defense_effect(const struct city *pcity,
1453 const struct unit_type *attacker)
1455 if (!attacker) {
1456 /* Any defense building will do */
1457 return get_city_bonus(pcity, EFT_DEFEND_BONUS) > 0;
1460 return get_unittype_bonus(city_owner(pcity), pcity->tile, attacker,
1461 EFT_DEFEND_BONUS) > 0;
1464 /**************************************************************************
1465 Return TRUE iff the city is happy. A happy city will start celebrating
1466 soon.
1467 A city can only be happy if half or more of the population is happy,
1468 none of the population is unhappy or angry, and it has sufficient size.
1469 **************************************************************************/
1470 bool city_happy(const struct city *pcity)
1472 return (city_size_get(pcity) >= game.info.celebratesize
1473 && pcity->feel[CITIZEN_ANGRY][FEELING_FINAL] == 0
1474 && pcity->feel[CITIZEN_UNHAPPY][FEELING_FINAL] == 0
1475 && pcity->feel[CITIZEN_HAPPY][FEELING_FINAL] >= (city_size_get(pcity) + 1) / 2);
1478 /**************************************************************************
1479 Return TRUE iff the city is unhappy. An unhappy city will fall
1480 into disorder soon.
1481 **************************************************************************/
1482 bool city_unhappy(const struct city *pcity)
1484 return (pcity->feel[CITIZEN_HAPPY][FEELING_FINAL]
1485 < pcity->feel[CITIZEN_UNHAPPY][FEELING_FINAL]
1486 + 2 * pcity->feel[CITIZEN_ANGRY][FEELING_FINAL]);
1489 /**************************************************************************
1490 Return TRUE if the city was celebrating at the start of the turn,
1491 and it still has sufficient size to be in rapture.
1492 **************************************************************************/
1493 bool base_city_celebrating(const struct city *pcity)
1495 return (city_size_get(pcity) >= game.info.celebratesize && pcity->was_happy);
1498 /**************************************************************************
1499 cities celebrate only after consecutive happy turns
1500 **************************************************************************/
1501 bool city_celebrating(const struct city *pcity)
1503 return base_city_celebrating(pcity) && city_happy(pcity);
1506 /**************************************************************************
1507 Returns whether city is growing by rapture.
1508 **************************************************************************/
1509 bool city_rapture_grow(const struct city *pcity)
1511 /* .rapture is checked instead of city_celebrating() because this
1512 function is called after .was_happy was updated. */
1513 return (pcity->rapture > 0 && pcity->surplus[O_FOOD] > 0
1514 && (pcity->rapture % game.info.rapturedelay) == 0
1515 && get_city_bonus(pcity, EFT_RAPTURE_GROW) > 0);
1518 /**************************************************************************
1519 Find city with given id from list.
1520 **************************************************************************/
1521 struct city *city_list_find_number(struct city_list *This, int id)
1523 if (id != 0) {
1524 city_list_iterate(This, pcity) {
1525 if (pcity->id == id) {
1526 return pcity;
1528 } city_list_iterate_end;
1531 return NULL;
1534 /**************************************************************************
1535 Find city with given name from list.
1536 **************************************************************************/
1537 struct city *city_list_find_name(struct city_list *This, const char *name)
1539 city_list_iterate(This, pcity) {
1540 if (fc_strcasecmp(name, pcity->name) == 0) {
1541 return pcity;
1543 } city_list_iterate_end;
1545 return NULL;
1548 /**************************************************************************
1549 Comparison function for qsort for city _pointers_, sorting by city name.
1550 Args are really (struct city**), to sort an array of pointers.
1551 (Compare with old_city_name_compare() in game.c, which use city_id's)
1552 **************************************************************************/
1553 int city_name_compare(const void *p1, const void *p2)
1555 return fc_strcasecmp((*(const struct city **) p1)->name,
1556 (*(const struct city **) p2)->name);
1559 /****************************************************************************
1560 Returns the city style that has the given (translated) name.
1561 Returns -1 if none match.
1562 ****************************************************************************/
1563 int city_style_by_translated_name(const char *s)
1565 int i;
1567 for (i = 0; i < game.control.styles_count; i++) {
1568 if (0 == strcmp(city_style_name_translation(i), s)) {
1569 return i;
1573 return -1;
1576 /****************************************************************************
1577 Returns the city style that has the given (untranslated) rule name.
1578 Returns -1 if none match.
1579 ****************************************************************************/
1580 int city_style_by_rule_name(const char *s)
1582 const char *qs = Qn_(s);
1583 int i;
1585 for (i = 0; i < game.control.styles_count; i++) {
1586 if (0 == fc_strcasecmp(city_style_rule_name(i), qs)) {
1587 return i;
1591 return -1;
1594 /****************************************************************************
1595 Return the (translated) name of the given city style.
1596 You don't have to free the return pointer.
1597 ****************************************************************************/
1598 const char *city_style_name_translation(const int style)
1600 return name_translation_get(&city_styles[style].name);
1603 /****************************************************************************
1604 Return the (untranslated) rule name of the city style.
1605 You don't have to free the return pointer.
1606 ****************************************************************************/
1607 const char *city_style_rule_name(const int style)
1609 return rule_name_get(&city_styles[style].name);
1612 /**************************************************************************
1613 Compute and optionally apply the change-production penalty for the given
1614 production change (to target) in the given city (pcity).
1615 Always returns the number of shields which would be in the stock if
1616 the penalty had been applied.
1618 If we switch the "class" of the target sometime after a city has produced
1619 (i.e., not on the turn immediately after), then there's a shield loss.
1620 But only on the first switch that turn. Also, if ever change back to
1621 original improvement class of this turn, restore lost production.
1622 **************************************************************************/
1623 int city_change_production_penalty(const struct city *pcity,
1624 const struct universal *target)
1626 int shield_stock_after_adjustment;
1627 enum production_class_type orig_class;
1628 enum production_class_type new_class;
1629 int unpenalized_shields = 0, penalized_shields = 0;
1631 switch (pcity->changed_from.kind) {
1632 case VUT_IMPROVEMENT:
1633 if (is_wonder(pcity->changed_from.value.building)) {
1634 orig_class = PCT_WONDER;
1635 } else {
1636 orig_class = PCT_NORMAL_IMPROVEMENT;
1638 break;
1639 case VUT_UTYPE:
1640 orig_class = PCT_UNIT;
1641 break;
1642 default:
1643 orig_class = PCT_LAST;
1644 break;
1647 switch (target->kind) {
1648 case VUT_IMPROVEMENT:
1649 if (is_wonder(target->value.building)) {
1650 new_class = PCT_WONDER;
1651 } else {
1652 new_class = PCT_NORMAL_IMPROVEMENT;
1654 break;
1655 case VUT_UTYPE:
1656 new_class = PCT_UNIT;
1657 break;
1658 default:
1659 new_class = PCT_LAST;
1660 break;
1663 /* Changing production is penalized under certain circumstances. */
1664 if (orig_class == new_class
1665 || orig_class == PCT_LAST) {
1666 /* There's never a penalty for building something of the same class. */
1667 unpenalized_shields = pcity->before_change_shields;
1668 } else if (city_built_last_turn(pcity)) {
1669 /* Surplus shields from the previous production won't be penalized if
1670 * you change production on the very next turn. But you can only use
1671 * up to the city's surplus amount of shields in this way. */
1672 unpenalized_shields = MIN(pcity->last_turns_shield_surplus,
1673 pcity->before_change_shields);
1674 penalized_shields = pcity->before_change_shields - unpenalized_shields;
1675 } else {
1676 /* Penalize 50% of the production. */
1677 penalized_shields = pcity->before_change_shields;
1680 /* Do not put penalty on these. It shouldn't matter whether you disband unit
1681 before or after changing production...*/
1682 unpenalized_shields += pcity->disbanded_shields;
1684 /* Caravan shields are penalized (just as if you disbanded the caravan)
1685 * if you're not building a wonder. */
1686 if (new_class == PCT_WONDER) {
1687 unpenalized_shields += pcity->caravan_shields;
1688 } else {
1689 penalized_shields += pcity->caravan_shields;
1692 shield_stock_after_adjustment =
1693 unpenalized_shields + penalized_shields / 2;
1695 return shield_stock_after_adjustment;
1698 /**************************************************************************
1699 Calculates the turns which are needed to build the requested
1700 improvement in the city. GUI Independent.
1701 **************************************************************************/
1702 int city_turns_to_build(const struct city *pcity,
1703 const struct universal *target,
1704 bool include_shield_stock)
1706 int city_shield_surplus = pcity->surplus[O_SHIELD];
1707 int city_shield_stock = include_shield_stock ?
1708 city_change_production_penalty(pcity, target) : 0;
1709 int cost = universal_build_shield_cost(target);
1711 if (target->kind == VUT_IMPROVEMENT
1712 && is_great_wonder(target->value.building)
1713 && !great_wonder_is_available(target->value.building)) {
1714 return FC_INFINITY;
1717 if (include_shield_stock && (city_shield_stock >= cost)) {
1718 return 1;
1719 } else if (city_shield_surplus > 0) {
1720 return (cost - city_shield_stock - 1) / city_shield_surplus + 1;
1721 } else {
1722 return FC_INFINITY;
1726 /**************************************************************************
1727 Calculates the turns which are needed for the city to grow. A value
1728 of FC_INFINITY means the city will never grow. A value of 0 means
1729 city growth is blocked. A negative value of -x means the city will
1730 shrink in x turns. A positive value of x means the city will grow in
1731 x turns.
1732 **************************************************************************/
1733 int city_turns_to_grow(const struct city *pcity)
1735 if (pcity->surplus[O_FOOD] > 0) {
1736 return (city_granary_size(city_size_get(pcity)) - pcity->food_stock +
1737 pcity->surplus[O_FOOD] - 1) / pcity->surplus[O_FOOD];
1738 } else if (pcity->surplus[O_FOOD] < 0) {
1739 /* turns before famine loss */
1740 return -1 + (pcity->food_stock / pcity->surplus[O_FOOD]);
1741 } else {
1742 return FC_INFINITY;
1746 /****************************************************************************
1747 Return TRUE iff the city can grow to the given size.
1748 ****************************************************************************/
1749 bool city_can_grow_to(const struct city *pcity, int pop_size)
1751 return (get_city_bonus(pcity, EFT_SIZE_UNLIMIT) > 0
1752 || pop_size <= get_city_bonus(pcity, EFT_SIZE_ADJ));
1755 /**************************************************************************
1756 is there an enemy city on this tile?
1757 **************************************************************************/
1758 struct city *is_enemy_city_tile(const struct tile *ptile,
1759 const struct player *pplayer)
1761 struct city *pcity = tile_city(ptile);
1763 if (pcity && pplayers_at_war(pplayer, city_owner(pcity)))
1764 return pcity;
1765 else
1766 return NULL;
1769 /**************************************************************************
1770 is there an friendly city on this tile?
1771 **************************************************************************/
1772 struct city *is_allied_city_tile(const struct tile *ptile,
1773 const struct player *pplayer)
1775 struct city *pcity = tile_city(ptile);
1777 if (pcity && pplayers_allied(pplayer, city_owner(pcity)))
1778 return pcity;
1779 else
1780 return NULL;
1783 /**************************************************************************
1784 is there an enemy city on this tile?
1785 **************************************************************************/
1786 struct city *is_non_attack_city_tile(const struct tile *ptile,
1787 const struct player *pplayer)
1789 struct city *pcity = tile_city(ptile);
1791 if (pcity && pplayers_non_attack(pplayer, city_owner(pcity)))
1792 return pcity;
1793 else
1794 return NULL;
1797 /**************************************************************************
1798 is there an non_allied city on this tile?
1799 **************************************************************************/
1800 struct city *is_non_allied_city_tile(const struct tile *ptile,
1801 const struct player *pplayer)
1803 struct city *pcity = tile_city(ptile);
1805 if (pcity && !pplayers_allied(pplayer, city_owner(pcity)))
1806 return pcity;
1807 else
1808 return NULL;
1811 /**************************************************************************
1812 Return TRUE if there is a friendly city near to this unit (within 3
1813 steps).
1814 **************************************************************************/
1815 bool is_unit_near_a_friendly_city(const struct unit *punit)
1817 return is_friendly_city_near(unit_owner(punit), unit_tile(punit));
1820 /**************************************************************************
1821 Return TRUE if there is a friendly city near to this tile (within 3
1822 steps).
1823 **************************************************************************/
1824 bool is_friendly_city_near(const struct player *owner,
1825 const struct tile *ptile)
1827 square_iterate(ptile, 3, ptile1) {
1828 struct city *pcity = tile_city(ptile1);
1829 if (pcity && pplayers_allied(owner, city_owner(pcity))) {
1830 return TRUE;
1832 } square_iterate_end;
1834 return FALSE;
1837 /**************************************************************************
1838 Return true iff a city exists within a city radius of the given
1839 location. may_be_on_center determines if a city at x,y counts.
1840 **************************************************************************/
1841 bool city_exists_within_max_city_map(const struct tile *ptile,
1842 bool may_be_on_center)
1844 city_tile_iterate(CITY_MAP_MAX_RADIUS_SQ, ptile, ptile1) {
1845 if (may_be_on_center || !same_pos(ptile, ptile1)) {
1846 if (tile_city(ptile1)) {
1847 return TRUE;
1850 } city_tile_iterate_end;
1852 return FALSE;
1855 /****************************************************************************
1856 Generalized formula used to calculate granary size.
1858 The AI may not deal well with non-default settings. See food_weighting().
1859 ****************************************************************************/
1860 int city_granary_size(int city_size)
1862 int food_inis = game.info.granary_num_inis;
1863 int food_inc = game.info.granary_food_inc;
1864 int base_value;
1866 /* If the city has no citizens, there is no granary. */
1867 if (city_size == 0) {
1868 return 0;
1871 /* Granary sizes for the first food_inis citizens are given directly.
1872 * After that we increase the granary size by food_inc per citizen. */
1873 if (city_size > food_inis) {
1874 base_value = game.info.granary_food_ini[food_inis - 1];
1875 base_value += food_inc * (city_size - food_inis);
1876 } else {
1877 base_value = game.info.granary_food_ini[city_size - 1];
1880 return MAX(base_value * game.info.foodbox / 100, 1);
1883 /****************************************************************************
1884 Give base happiness in any city owned by pplayer.
1885 A positive number is a number of content citizens. A negative number is
1886 a number of angry citizens (a city never starts with both).
1887 ****************************************************************************/
1888 static int player_base_citizen_happiness(const struct player *pplayer)
1890 int cities = city_list_size(pplayer->cities);
1891 int content = get_player_bonus(pplayer, EFT_CITY_UNHAPPY_SIZE);
1892 int basis = get_player_bonus(pplayer, EFT_EMPIRE_SIZE_BASE);
1893 int step = get_player_bonus(pplayer, EFT_EMPIRE_SIZE_STEP);
1895 if (basis + step <= 0) {
1896 /* Value of zero means effect is inactive */
1897 return content;
1900 if (cities > basis) {
1901 content--;
1902 if (step != 0) {
1903 /* the first penalty is at (basis + 1) cities;
1904 the next is at (basis + step + 1), _not_ (basis + step) */
1905 content -= (cities - basis - 1) / step;
1908 return content;
1911 /****************************************************************************
1912 Give base number of content citizens in any city owned by pplayer.
1913 ****************************************************************************/
1914 citizens player_content_citizens(const struct player *pplayer)
1916 int content = player_base_citizen_happiness(pplayer);
1918 return CLIP(0, content, MAX_CITY_SIZE);
1921 /****************************************************************************
1922 Give base number of angry citizens in any city owned by pplayer.
1923 ****************************************************************************/
1924 citizens player_angry_citizens(const struct player *pplayer)
1926 if (!game.info.angrycitizen) {
1927 return 0;
1928 } else {
1929 /* Create angry citizens only if we have a negative number of possible
1930 * content citizens. This can happen when empires grow really big. */
1931 int content = player_base_citizen_happiness(pplayer);
1933 return CLIP(0, -content, MAX_CITY_SIZE);
1937 /**************************************************************************
1938 Return the factor (in %) by which the city's output should be multiplied.
1939 **************************************************************************/
1940 int get_final_city_output_bonus(const struct city *pcity, Output_type_id otype)
1942 struct output_type *output = &output_types[otype];
1943 int bonus1 = 100 + get_city_tile_output_bonus(pcity, NULL, output,
1944 EFT_OUTPUT_BONUS);
1945 int bonus2 = 100 + get_city_tile_output_bonus(pcity, NULL, output,
1946 EFT_OUTPUT_BONUS_2);
1948 return MAX(bonus1 * bonus2 / 100, 0);
1951 /**************************************************************************
1952 Return the amount of gold generated by buildings under "tithe" attribute
1953 governments.
1954 **************************************************************************/
1955 int get_city_tithes_bonus(const struct city *pcity)
1957 int tithes_bonus = 0;
1959 if (get_city_bonus(pcity, EFT_HAPPINESS_TO_GOLD) <= 0) {
1960 return 0;
1963 tithes_bonus += get_city_bonus(pcity, EFT_MAKE_CONTENT);
1964 tithes_bonus += get_city_bonus(pcity, EFT_FORCE_CONTENT);
1966 return tithes_bonus;
1969 /**************************************************************************
1970 Add the incomes of a city according to the taxrates (ignore # of
1971 specialists). trade should be in output[O_TRADE].
1972 **************************************************************************/
1973 void add_tax_income(const struct player *pplayer, int trade, int *output)
1975 const int SCIENCE = 0, TAX = 1, LUXURY = 2;
1976 int rates[3], result[3];
1978 if (game.info.changable_tax) {
1979 rates[SCIENCE] = pplayer->economic.science;
1980 rates[LUXURY] = pplayer->economic.luxury;
1981 rates[TAX] = 100 - rates[SCIENCE] - rates[LUXURY];
1982 } else {
1983 rates[SCIENCE] = game.info.forced_science;
1984 rates[LUXURY] = game.info.forced_luxury;
1985 rates[TAX] = game.info.forced_gold;
1988 /* ANARCHY */
1989 if (government_of_player(pplayer) == game.government_during_revolution) {
1990 rates[SCIENCE] = 0;
1991 rates[LUXURY] = 100;
1992 rates[TAX] = 0;
1995 distribute(trade, 3, rates, result);
1997 output[O_SCIENCE] += result[SCIENCE];
1998 output[O_GOLD] += result[TAX];
1999 output[O_LUXURY] += result[LUXURY];
2002 /**************************************************************************
2003 Return TRUE if the city built something last turn (meaning production
2004 was completed between last turn and this).
2005 **************************************************************************/
2006 bool city_built_last_turn(const struct city *pcity)
2008 return pcity->turn_last_built + 1 >= game.info.turn;
2011 /****************************************************************************
2012 Calculate output (food, trade and shields) generated by the worked tiles
2013 of a city. This will completely overwrite the output[] array.
2015 'workers_map' is an boolean array which defines the placement of the
2016 workers within the city map. It uses the tile index and its size is
2017 defined by city_map_tiles_from_city(_pcity). See also cm_state_init().
2018 ****************************************************************************/
2019 static inline void get_worked_tile_output(const struct city *pcity,
2020 int *output, bool *workers_map)
2022 bool is_worked;
2023 #ifdef CITY_DEBUGGING
2024 bool is_celebrating = base_city_celebrating(pcity);
2025 #endif
2026 struct tile *pcenter = city_tile(pcity);
2028 memset(output, 0, O_LAST * sizeof(*output));
2030 city_tile_iterate_index(city_map_radius_sq_get(pcity), pcenter, ptile,
2031 city_tile_index) {
2032 if (workers_map == NULL) {
2033 struct city *pwork = tile_worked(ptile);
2035 is_worked = (NULL != pwork && pwork == pcity);
2036 } else {
2037 is_worked = workers_map[city_tile_index];
2040 if (is_worked) {
2041 output_type_iterate(o) {
2042 #ifdef CITY_DEBUGGING
2043 /* This assertion never fails, but it's so slow that we disable
2044 * it by default. */
2045 fc_assert(city_tile_cache_get_output(pcity, city_tile_index, o)
2046 == city_tile_output(pcity, ptile, is_celebrating, o));
2047 #endif
2048 output[o] += city_tile_cache_get_output(pcity, city_tile_index, o);
2049 } output_type_iterate_end;
2051 } city_tile_iterate_index_end;
2054 /****************************************************************************
2055 Calculate output (gold, science, and luxury) generated by the specialists
2056 of a city. The output[] array is not cleared but is just added to.
2057 ****************************************************************************/
2058 void add_specialist_output(const struct city *pcity, int *output)
2060 specialist_type_iterate(sp) {
2061 int count = pcity->specialists[sp];
2063 output_type_iterate(stat_index) {
2064 int amount = get_specialist_output(pcity, sp, stat_index);
2066 output[stat_index] += count * amount;
2067 } output_type_iterate_end;
2068 } specialist_type_iterate_end;
2071 /****************************************************************************
2072 This function sets all the values in the pcity->bonus[] array.
2073 Called near the beginning of city_refresh_from_main_map().
2075 It doesn't depend on anything else in the refresh and doesn't change
2076 as workers are moved around, but does change when buildings are built,
2077 etc.
2078 ****************************************************************************/
2079 static inline void set_city_bonuses(struct city *pcity)
2081 output_type_iterate(o) {
2082 pcity->bonus[o] = get_final_city_output_bonus(pcity, o);
2083 } output_type_iterate_end;
2086 /****************************************************************************
2087 This function sets the cache for the tile outputs, the pcity->tile_cache[]
2088 array. It is called near the beginning of city_refresh_from_main_map().
2090 It doesn't depend on anything else in the refresh and doesn't change
2091 as workers are moved around, but does change when buildings are built,
2092 etc.
2094 TODO: use the cached values elsethere in the code!
2095 ****************************************************************************/
2096 static inline void city_tile_cache_update(struct city *pcity)
2098 bool is_celebrating = base_city_celebrating(pcity);
2099 int radius_sq = city_map_radius_sq_get(pcity);
2101 /* initialize tile_cache if needed */
2102 if (pcity->tile_cache == NULL || pcity->tile_cache_radius_sq == -1
2103 || pcity->tile_cache_radius_sq != radius_sq) {
2104 pcity->tile_cache = fc_realloc(pcity->tile_cache,
2105 city_map_tiles(radius_sq)
2106 * sizeof(*(pcity->tile_cache)));
2107 pcity->tile_cache_radius_sq = radius_sq;
2110 /* Any unreal tiles are skipped - these values should have been memset
2111 * to 0 when the city was created. */
2112 city_tile_iterate_index(radius_sq, pcity->tile, ptile, city_tile_index) {
2113 output_type_iterate(o) {
2114 (pcity->tile_cache[city_tile_index]).output[o]
2115 = city_tile_output(pcity, ptile, is_celebrating, o);
2116 } output_type_iterate_end;
2117 } city_tile_iterate_index_end;
2120 /****************************************************************************
2121 This function returns the output of 'o' for the city tile 'city_tile_index'
2122 of 'pcity'.
2123 ****************************************************************************/
2124 static inline int city_tile_cache_get_output(const struct city *pcity,
2125 int city_tile_index,
2126 enum output_type_id o)
2128 fc_assert_ret_val(pcity->tile_cache_radius_sq
2129 == city_map_radius_sq_get(pcity), 0);
2130 fc_assert_ret_val(city_tile_index < city_map_tiles_from_city(pcity), 0);
2132 return (pcity->tile_cache[city_tile_index]).output[o];
2135 /**************************************************************************
2136 Set the final surplus[] array from the prod[] and usage[] values.
2137 **************************************************************************/
2138 static void set_surpluses(struct city *pcity)
2140 output_type_iterate(o) {
2141 pcity->surplus[o] = pcity->prod[o] - pcity->usage[o];
2142 } output_type_iterate_end;
2145 /**************************************************************************
2146 Copy the happyness array in the city to index i from index i-1.
2147 **************************************************************************/
2148 static void happy_copy(struct city *pcity, enum citizen_feeling i)
2150 int c = 0;
2152 for (; c < CITIZEN_LAST; c++) {
2153 pcity->feel[c][i] = pcity->feel[c][i - 1];
2157 /**************************************************************************
2158 Create content, unhappy and angry citizens.
2159 **************************************************************************/
2160 static void citizen_base_mood(struct city *pcity)
2162 struct player *pplayer = city_owner(pcity);
2163 citizens *happy = &pcity->feel[CITIZEN_HAPPY][FEELING_BASE];
2164 citizens *content = &pcity->feel[CITIZEN_CONTENT][FEELING_BASE];
2165 citizens *unhappy = &pcity->feel[CITIZEN_UNHAPPY][FEELING_BASE];
2166 citizens *angry = &pcity->feel[CITIZEN_ANGRY][FEELING_BASE];
2167 citizens size = city_size_get(pcity);
2168 citizens spes = city_specialists(pcity);
2170 /* This is the number of citizens that may start out content, depending
2171 * on empire size and game's city unhappysize. This may be bigger than
2172 * the size of the city, since this is a potential. */
2173 citizens base_content = player_content_citizens(pplayer);
2174 /* Similarly, this is the potential number of angry citizens. */
2175 citizens base_angry = player_angry_citizens(pplayer);
2177 /* Create content citizens. Take specialists from their ranks. */
2178 *content = MAX(0, MIN(size, base_content) - spes);
2180 /* Create angry citizens. Specialists never become angry. */
2181 fc_assert_action(base_content == 0 || base_angry == 0, *content = 0);
2182 *angry = MIN(base_angry, size - spes);
2184 /* Create unhappy citizens. In the beginning, all who are not content,
2185 * specialists or angry are unhappy. This is changed by luxuries and
2186 * buildings later. */
2187 *unhappy = (size - spes - *content - *angry);
2189 /* No one is born happy. */
2190 *happy = 0;
2193 /**************************************************************************
2194 Make people happy:
2195 * angry citizen are eliminated first
2196 * then content are made happy, then unhappy content, etc.
2197 * each conversions costs 2 or 4 luxuries.
2198 **************************************************************************/
2199 static inline void citizen_luxury_happy(struct city *pcity, int *luxuries)
2201 citizens *happy = &pcity->feel[CITIZEN_HAPPY][FEELING_LUXURY];
2202 citizens *content = &pcity->feel[CITIZEN_CONTENT][FEELING_LUXURY];
2203 citizens *unhappy = &pcity->feel[CITIZEN_UNHAPPY][FEELING_LUXURY];
2204 citizens *angry = &pcity->feel[CITIZEN_ANGRY][FEELING_LUXURY];
2206 while (*luxuries >= game.info.happy_cost && *angry > 0) {
2207 /* Upgrade angry to unhappy: costs HAPPY_COST each. */
2208 (*angry)--;
2209 (*unhappy)++;
2210 *luxuries -= game.info.happy_cost;
2212 while (*luxuries >= game.info.happy_cost && *content > 0) {
2213 /* Upgrade content to happy: costs HAPPY_COST each. */
2214 (*content)--;
2215 (*happy)++;
2216 *luxuries -= game.info.happy_cost;
2218 while (*luxuries >= 2 * game.info.happy_cost && *unhappy > 0) {
2219 /* Upgrade unhappy to happy. Note this is a 2-level upgrade with
2220 * double the cost. */
2221 (*unhappy)--;
2222 (*happy)++;
2223 *luxuries -= 2 * game.info.happy_cost;
2225 if (*luxuries >= game.info.happy_cost && *unhappy > 0) {
2226 /* Upgrade unhappy to content: costs HAPPY_COST each. */
2227 (*unhappy)--;
2228 (*content)++;
2229 *luxuries -= game.info.happy_cost;
2233 /**************************************************************************
2234 Make citizens happy due to luxury.
2235 **************************************************************************/
2236 static inline void citizen_happy_luxury(struct city *pcity)
2238 int x = pcity->prod[O_LUXURY];
2240 citizen_luxury_happy(pcity, &x);
2243 /**************************************************************************
2244 Make citizens content due to city improvements.
2245 **************************************************************************/
2246 static inline void citizen_content_buildings(struct city *pcity)
2248 citizens *content = &pcity->feel[CITIZEN_CONTENT][FEELING_EFFECT];
2249 citizens *unhappy = &pcity->feel[CITIZEN_UNHAPPY][FEELING_EFFECT];
2250 citizens *angry = &pcity->feel[CITIZEN_ANGRY][FEELING_EFFECT];
2251 int faces = get_city_bonus(pcity, EFT_MAKE_CONTENT);
2253 /* make people content (but not happy):
2254 get rid of angry first, then make unhappy content. */
2255 while (faces > 0 && *angry > 0) {
2256 (*angry)--;
2257 (*unhappy)++;
2258 faces--;
2260 while (faces > 0 && *unhappy > 0) {
2261 (*unhappy)--;
2262 (*content)++;
2263 faces--;
2267 /**************************************************************************
2268 Apply effects of citizen nationality to happiness
2269 **************************************************************************/
2270 static inline void citizen_happiness_nationality(struct city *pcity)
2272 citizens *happy = &pcity->feel[CITIZEN_HAPPY][FEELING_NATIONALITY];
2273 citizens *content = &pcity->feel[CITIZEN_CONTENT][FEELING_NATIONALITY];
2274 citizens *unhappy = &pcity->feel[CITIZEN_UNHAPPY][FEELING_NATIONALITY];
2276 if (game.info.citizen_nationality) {
2277 int pct = get_city_bonus(pcity, EFT_ENEMY_CITIZEN_UNHAPPY_PCT);
2279 if (pct > 0) {
2280 int enemies = 0;
2281 int unhappy_inc;
2282 struct player *owner = city_owner(pcity);
2284 citizens_foreign_iterate(pcity, pslot, nationality) {
2285 if (pplayers_at_war(owner, player_slot_get_player(pslot))) {
2286 enemies += nationality;
2288 } citizens_foreign_iterate_end;
2290 unhappy_inc = enemies * pct / 100;
2292 /* First make content => unhappy, then happy => unhappy,
2293 * then happy => content. No-one becomes angry. */
2294 while (unhappy_inc > 0 && *content > 0) {
2295 (*content)--;
2296 (*unhappy)++;
2297 unhappy_inc--;
2299 while (unhappy_inc > 1 && *happy > 0) {
2300 (*happy)--;
2301 (*unhappy)++;
2302 unhappy_inc -= 2;
2304 while (unhappy_inc > 0 && *happy > 0) {
2305 (*happy)--;
2306 (*content)++;
2307 unhappy_inc--;
2313 /**************************************************************************
2314 Make citizens happy/unhappy due to units.
2316 This function requires that pcity->martial_law and
2317 pcity->unit_happy_cost have already been set in city_support().
2318 **************************************************************************/
2319 static inline void citizen_happy_units(struct city *pcity)
2321 citizens *happy = &pcity->feel[CITIZEN_HAPPY][FEELING_MARTIAL];
2322 citizens *content = &pcity->feel[CITIZEN_CONTENT][FEELING_MARTIAL];
2323 citizens *unhappy = &pcity->feel[CITIZEN_UNHAPPY][FEELING_MARTIAL];
2324 citizens *angry = &pcity->feel[CITIZEN_ANGRY][FEELING_MARTIAL];
2325 citizens amt = pcity->martial_law;
2327 /* Pacify discontent citizens through martial law. First convert
2328 * angry => unhappy, then unhappy => content. */
2329 while (amt > 0 && *angry > 0) {
2330 (*angry)--;
2331 (*unhappy)++;
2332 amt--;
2334 while (amt > 0 && *unhappy > 0) {
2335 (*unhappy)--;
2336 (*content)++;
2337 amt--;
2340 /* Now make citizens unhappier because of military units away from home.
2341 * First make content => unhappy, then happy => unhappy,
2342 * then happy => content. */
2343 amt = pcity->unit_happy_upkeep;
2344 while (amt > 0 && *content > 0) {
2345 (*content)--;
2346 (*unhappy)++;
2347 amt--;
2349 while (amt > 1 && *happy > 0) {
2350 (*happy)--;
2351 (*unhappy)++;
2352 amt -= 2;
2354 while (amt > 0 && *happy > 0) {
2355 (*happy)--;
2356 (*content)++;
2357 amt--;
2359 /* Any remaining unhappiness is lost since angry citizens aren't created
2360 * here. */
2361 /* FIXME: Why not? - Per */
2364 /**************************************************************************
2365 Make citizens happy due to wonders.
2366 **************************************************************************/
2367 static inline void citizen_happy_wonders(struct city *pcity)
2369 citizens *happy = &pcity->feel[CITIZEN_HAPPY][FEELING_FINAL];
2370 citizens *content = &pcity->feel[CITIZEN_CONTENT][FEELING_FINAL];
2371 citizens *unhappy = &pcity->feel[CITIZEN_UNHAPPY][FEELING_FINAL];
2372 citizens *angry = &pcity->feel[CITIZEN_ANGRY][FEELING_FINAL];
2373 int bonus = get_city_bonus(pcity, EFT_MAKE_HAPPY);
2375 /* First create happy citizens from content, then from unhappy
2376 * citizens; we cannot help angry citizens here. */
2377 while (bonus > 0 && *content > 0) {
2378 (*content)--;
2379 (*happy)++;
2380 bonus--;
2382 while (bonus > 1 && *unhappy > 0) {
2383 (*unhappy)--;
2384 (*happy)++;
2385 bonus -= 2;
2387 /* The rest falls through and lets unhappy people become content. */
2389 if (get_city_bonus(pcity, EFT_NO_UNHAPPY) > 0) {
2390 *content += *unhappy + *angry;
2391 *unhappy = 0;
2392 *angry = 0;
2393 return;
2396 bonus += get_city_bonus(pcity, EFT_FORCE_CONTENT);
2398 /* get rid of angry first, then make unhappy content */
2399 while (bonus > 0 && *angry > 0) {
2400 (*angry)--;
2401 (*unhappy)++;
2402 bonus--;
2404 while (bonus > 0 && *unhappy > 0) {
2405 (*unhappy)--;
2406 (*content)++;
2407 bonus--;
2411 /**************************************************************************
2412 Set food, tax, science and shields production to zero if city is in
2413 disorder.
2414 **************************************************************************/
2415 static inline void unhappy_city_check(struct city *pcity)
2417 if (city_unhappy(pcity)) {
2418 output_type_iterate(o) {
2419 switch (output_types[o].unhappy_penalty) {
2420 case UNHAPPY_PENALTY_NONE:
2421 pcity->unhappy_penalty[o] = 0;
2422 break;
2423 case UNHAPPY_PENALTY_SURPLUS:
2424 pcity->unhappy_penalty[o] = MAX(pcity->prod[o] - pcity->usage[o], 0);
2425 break;
2426 case UNHAPPY_PENALTY_ALL_PRODUCTION:
2427 pcity->unhappy_penalty[o] = pcity->prod[o];
2428 break;
2431 pcity->prod[o] -= pcity->unhappy_penalty[o];
2432 } output_type_iterate_end;
2433 } else {
2434 memset(pcity->unhappy_penalty, 0,
2435 O_LAST * sizeof(*pcity->unhappy_penalty));
2439 /**************************************************************************
2440 Calculate the pollution from production and population in the city.
2441 **************************************************************************/
2442 int city_pollution_types(const struct city *pcity, int shield_total,
2443 int *pollu_prod, int *pollu_pop, int *pollu_mod)
2445 int prod, pop, mod;
2447 /* Add one one pollution per shield, multipled by the bonus. */
2448 prod = 100 + get_city_bonus(pcity, EFT_POLLU_PROD_PCT);
2449 prod = shield_total * MAX(prod, 0) / 100;
2451 /* Add one pollution per citizen for baseline combined bonus (100%). */
2452 pop = (100 + get_city_bonus(pcity, EFT_POLLU_POP_PCT))
2453 * (100 + get_city_bonus(pcity, EFT_POLLU_POP_PCT_2))
2454 / 100;
2455 pop = (city_size_get(pcity) * MAX(pop, 0)) / 100;
2457 /* Then there is base pollution (usually a negative number). */
2458 mod = game.info.base_pollution;
2460 if (pollu_prod) {
2461 *pollu_prod = prod;
2463 if (pollu_pop) {
2464 *pollu_pop = pop;
2466 if (pollu_mod) {
2467 *pollu_mod = mod;
2469 return MAX(prod + pop + mod, 0);
2472 /**************************************************************************
2473 Calculate pollution for the city. The shield_total must be passed in
2474 (most callers will want to pass pcity->shield_prod).
2475 **************************************************************************/
2476 int city_pollution(const struct city *pcity, int shield_total)
2478 return city_pollution_types(pcity, shield_total, NULL, NULL, NULL);
2481 /**************************************************************************
2482 Gets whether cities that pcity trades with had the plague. If so, it
2483 returns the health penalty in tenth of percent which depends on the size
2484 of both cities. The health penalty is given as the product of the ruleset
2485 option 'game.info.illness_trade_infection' (in percent) and the square
2486 root of the product of the size of both cities.
2487 *************************************************************************/
2488 static int get_trade_illness(const struct city *pcity)
2490 float illness_trade = 0.0;
2492 trade_routes_iterate(pcity, trade_city) {
2493 if (trade_city->turn_plague != -1
2494 && game.info.turn - trade_city->turn_plague < 5) {
2495 illness_trade += (float)game.info.illness_trade_infection
2496 * sqrt(1.0 * city_size_get(pcity)
2497 * city_size_get(trade_city)) / 100.0;
2499 } trade_routes_iterate_end;
2501 return (int)illness_trade;
2504 /**************************************************************************
2505 Get any effects regarding health from the buildings of the city. The
2506 effect defines the reduction of the possibility of an illness in percent.
2507 **************************************************************************/
2508 static int get_city_health(const struct city *pcity)
2510 return get_city_bonus(pcity, EFT_HEALTH_PCT);
2513 /**************************************************************************
2514 Calculate city's illness in tenth of percent:
2516 base illness (the maximum value for illness in percent is given by
2517 'game.info.illness_base_factor')
2518 + trade illness (see get_trade_illness())
2519 + pollution illness (the pollution in the city times
2520 'game.info.illness_pollution_factor')
2522 The illness is reduced by the percentage given by the health effect.
2523 Illness cannot exceed 999 (= 99.9%), or be less then 0
2524 *************************************************************************/
2525 int city_illness_calc(const struct city *pcity, int *ill_base,
2526 int *ill_size, int *ill_trade, int *ill_pollution)
2528 int illness_size = 0, illness_trade = 0, illness_pollution = 0;
2529 int illness_base, illness_percent;
2531 if (game.info.illness_on
2532 && city_size_get(pcity) > game.info.illness_min_size) {
2533 /* offset the city size by game.info.illness_min_size */
2534 int use_size = city_size_get(pcity) - game.info.illness_min_size;
2536 illness_size = (int)((1.0 - exp(- (float)use_size / 10.0))
2537 * 10.0 * game.info.illness_base_factor);
2538 if (is_server()) {
2539 /* on the server we recalculate the illness due to trade as we have
2540 * all informations */
2541 illness_trade = get_trade_illness(pcity);
2542 } else {
2543 /* on the client we have to rely on the value saved within the city
2544 * struct */
2545 illness_trade = pcity->illness_trade;
2548 illness_pollution = pcity->pollution
2549 * game.info.illness_pollution_factor / 100;
2552 illness_base = illness_size + illness_trade + illness_pollution;
2553 illness_percent = 100 - get_city_health(pcity);
2555 /* returning other data */
2556 if (ill_size) {
2557 *ill_size = illness_size;
2560 if (ill_trade) {
2561 *ill_trade = illness_trade;
2564 if (ill_pollution) {
2565 *ill_pollution = illness_pollution;
2568 if (ill_base) {
2569 *ill_base = illness_base;
2572 return CLIP(0, illness_base * illness_percent / 100 , 999);
2575 /****************************************************************************
2576 Returns whether city had a plague outbreak this turn.
2577 ****************************************************************************/
2578 bool city_had_recent_plague(const struct city *pcity)
2580 /* Correctly handles special case turn_plague == -1 (never) */
2581 return (pcity->turn_plague == game.info.turn);
2584 /****************************************************************************
2585 The maximum number of units a city can build per turn.
2586 ****************************************************************************/
2587 int city_build_slots(const struct city *pcity)
2589 return get_city_bonus(pcity, EFT_CITY_BUILD_SLOTS);
2592 /****************************************************************************
2593 A city's maximum airlift capacity.
2594 (Note, this still returns a finite number even if airliftingstyle allows
2595 unlimited airlifts)
2596 ****************************************************************************/
2597 int city_airlift_max(const struct city *pcity)
2599 return get_city_bonus(pcity, EFT_AIRLIFT);
2602 /**************************************************************************
2603 Set food, trade and shields production in a city.
2605 This initializes the prod[] and waste[] arrays. It assumes that
2606 the bonus[] and citizen_base[] arrays are alread built.
2607 **************************************************************************/
2608 inline void set_city_production(struct city *pcity)
2610 int i;
2612 /* Calculate city production!
2614 * This is a rather complicated process if we allow rules to become
2615 * more generalized. We can assume that there are no recursive dependency
2616 * loops, but there are some dependencies that do not follow strict
2617 * ordering. For instance corruption must be calculated before
2618 * trade taxes can be counted up, which must occur before the science bonus
2619 * is added on. But the calculation of corruption must include the
2620 * trade bonus. To do this without excessive special casing means that in
2621 * this case the bonuses are multiplied on twice (but only saved the second
2622 * time).
2625 output_type_iterate(o) {
2626 pcity->prod[o] = pcity->citizen_base[o];
2627 } output_type_iterate_end;
2629 /* Add on special extra incomes: trade routes and tithes. */
2630 for (i = 0; i < MAX_TRADE_ROUTES; i++) {
2631 struct city *tcity = game_city_by_number(pcity->trade[i]);
2633 if (tcity != NULL) {
2634 bool can_trade = can_cities_trade(pcity, tcity);
2636 if (!can_trade) {
2637 enum trade_route_type type = cities_trade_route_type(pcity, tcity);
2638 struct trade_route_settings *settings = trade_route_settings_by_type(type);
2640 if (settings->cancelling == TRI_ACTIVE) {
2641 can_trade = TRUE;
2645 if (can_trade) {
2646 pcity->trade_value[i] =
2647 trade_between_cities(pcity, game_city_by_number(pcity->trade[i]));
2648 pcity->prod[O_TRADE] += pcity->trade_value[i]
2649 * (100 + get_city_bonus(pcity, EFT_TRADEROUTE_PCT)) / 100;
2650 } else {
2651 pcity->trade_value[i] = 0;
2655 pcity->prod[O_GOLD] += get_city_tithes_bonus(pcity);
2657 /* Account for waste. Note that waste is calculated before tax income is
2658 * calculated, so if you had "science waste" it would not include taxed
2659 * science. However waste is calculated after the bonuses are multiplied
2660 * on, so shield waste will include shield bonuses. */
2661 output_type_iterate(o) {
2662 pcity->waste[o] = city_waste(pcity, o,
2663 pcity->prod[o] * pcity->bonus[o] / 100,
2664 NULL);
2665 } output_type_iterate_end;
2667 /* Convert trade into science/luxury/gold, and add this on to whatever
2668 * science/luxury/gold is already there. */
2669 add_tax_income(city_owner(pcity),
2670 pcity->prod[O_TRADE] * pcity->bonus[O_TRADE] / 100
2671 - pcity->waste[O_TRADE] - pcity->usage[O_TRADE],
2672 pcity->prod);
2674 /* Add on effect bonuses and waste. Note that the waste calculation
2675 * (above) already includes the bonus multiplier. */
2676 output_type_iterate(o) {
2677 pcity->prod[o] = pcity->prod[o] * pcity->bonus[o] / 100;
2678 pcity->prod[o] -= pcity->waste[o];
2679 } output_type_iterate_end;
2682 /**************************************************************************
2683 Query unhappiness caused by a given unit.
2684 **************************************************************************/
2685 int city_unit_unhappiness(struct unit *punit, int *free_unhappy)
2687 struct city *pcity;
2688 struct unit_type *ut;
2689 struct player *plr;
2690 int happy_cost;
2692 if (!punit || !free_unhappy) {
2693 return 0;
2696 pcity = game_city_by_number(punit->homecity);
2697 if (pcity == NULL) {
2698 return 0;
2701 ut = unit_type_get(punit);
2702 plr = unit_owner(punit);
2703 happy_cost = utype_happy_cost(ut, plr);
2705 if (happy_cost <= 0) {
2706 return 0;
2709 fc_assert_ret_val(0 <= *free_unhappy, 0);
2711 if (!unit_being_aggressive(punit) && !is_field_unit(punit)) {
2712 return 0;
2715 happy_cost -= get_city_bonus(pcity, EFT_MAKE_CONTENT_MIL_PER);
2716 if (happy_cost <= 0) {
2717 return 0;
2720 if (*free_unhappy >= happy_cost) {
2721 *free_unhappy -= happy_cost;
2722 return 0;
2723 } else {
2724 happy_cost -= *free_unhappy;
2725 *free_unhappy = 0;
2728 return happy_cost;
2731 /**************************************************************************
2732 Calculate upkeep costs. This builds the pcity->usage[] array as well
2733 as setting some happiness values.
2734 **************************************************************************/
2735 static inline void city_support(struct city *pcity)
2737 int free_unhappy, martial_law_each;
2739 /* Clear all usage values. */
2740 memset(pcity->usage, 0, O_LAST * sizeof(*pcity->usage));
2741 pcity->martial_law = 0;
2742 pcity->unit_happy_upkeep = 0;
2744 /* Building and unit gold upkeep depends on the setting
2745 * 'game.info.gold_upkeep_style':
2746 * GOLD_UPKEEP_CITY: The upkeep for buildings and units is paid by the
2747 * city.
2748 * GOLD_UPKEEP_MIXED: The upkeep for buildings is paid by the city.
2749 * The upkeep for units is paid by the nation.
2750 * GOLD_UPKEEP_NATION: The upkeep for buildings and units is paid by the
2751 * nation. */
2752 fc_assert_msg(gold_upkeep_style_is_valid(game.info.gold_upkeep_style),
2753 "Invalid gold_upkeep_style %d", game.info.gold_upkeep_style);
2754 switch (game.info.gold_upkeep_style) {
2755 case GOLD_UPKEEP_CITY:
2756 pcity->usage[O_GOLD] += city_total_unit_gold_upkeep(pcity);
2757 /* no break */
2758 case GOLD_UPKEEP_MIXED:
2759 pcity->usage[O_GOLD] += city_total_impr_gold_upkeep(pcity);
2760 break;
2761 case GOLD_UPKEEP_NATION:
2762 /* nothing */
2763 break;
2765 /* Food consumption by citizens. */
2766 pcity->usage[O_FOOD] += game.info.food_cost * city_size_get(pcity);
2768 /* military units in this city (need _not_ be home city) can make
2769 * unhappy citizens content */
2770 martial_law_each = get_city_bonus(pcity, EFT_MARTIAL_LAW_EACH);
2771 if (martial_law_each > 0) {
2772 int count = 0;
2773 int martial_law_max = get_city_bonus(pcity, EFT_MARTIAL_LAW_MAX);
2775 unit_list_iterate(pcity->tile->units, punit) {
2776 if ((count < martial_law_max || martial_law_max == 0)
2777 && is_military_unit(punit)
2778 && unit_owner(punit) == city_owner(pcity)) {
2779 count++;
2781 } unit_list_iterate_end;
2783 pcity->martial_law = CLIP(0, count * martial_law_each, MAX_CITY_SIZE);
2786 free_unhappy = get_city_bonus(pcity, EFT_MAKE_CONTENT_MIL);
2787 unit_list_iterate(pcity->units_supported, punit) {
2788 pcity->unit_happy_upkeep += city_unit_unhappiness(punit, &free_unhappy);
2789 output_type_iterate(o) {
2790 if (O_GOLD != o) {
2791 /* O_GOLD is handled with "game.info.gold_upkeep_style", see over. */
2792 pcity->usage[o] += punit->upkeep[o];
2794 } output_type_iterate_end;
2795 } unit_list_iterate_end;
2798 /**************************************************************************
2799 Refreshes the internal cached data in the city structure.
2801 !full_refresh will not update tile_cache[] or bonus[]. These two
2802 values do not need to be recalculated for AI CMA testing.
2804 'workers_map' is an boolean array which defines the placement of the
2805 workers within the city map. It uses the tile index and its size is
2806 defined by city_map_tiles_from_city(_pcity). See also cm_state_init().
2808 If 'workers_map' is set, only basic updates are needed.
2809 **************************************************************************/
2810 void city_refresh_from_main_map(struct city *pcity, bool *workers_map)
2812 if (workers_map == NULL) {
2813 /* do a full refresh */
2815 /* Calculate the bonus[] array values. */
2816 set_city_bonuses(pcity);
2817 /* Calculate the tile_cache[] values. */
2818 city_tile_cache_update(pcity);
2819 /* manage settlers, and units */
2820 city_support(pcity);
2823 /* Calculate output from citizens (uses city_tile_cache_get_output()). */
2824 get_worked_tile_output(pcity, pcity->citizen_base, workers_map);
2825 add_specialist_output(pcity, pcity->citizen_base);
2827 set_city_production(pcity);
2828 citizen_base_mood(pcity);
2829 /* Note that pollution is calculated before unhappy_city_check() makes
2830 * deductions for disorder; so a city in disorder still causes pollution */
2831 pcity->pollution = city_pollution(pcity, pcity->prod[O_SHIELD]);
2833 happy_copy(pcity, FEELING_LUXURY);
2834 citizen_happy_luxury(pcity); /* with our new found luxuries */
2836 happy_copy(pcity, FEELING_EFFECT);
2837 citizen_content_buildings(pcity);
2839 happy_copy(pcity, FEELING_NATIONALITY);
2840 citizen_happiness_nationality(pcity);
2842 /* Martial law & unrest from units */
2843 happy_copy(pcity, FEELING_MARTIAL);
2844 citizen_happy_units(pcity);
2846 /* Building (including wonder) happiness effects */
2847 happy_copy(pcity, FEELING_FINAL);
2848 citizen_happy_wonders(pcity);
2850 unhappy_city_check(pcity);
2851 set_surpluses(pcity);
2854 /**************************************************************************
2855 Give corruption/waste generated by city. otype gives the output type
2856 (O_SHIELD/O_TRADE). 'total' gives the total output of this type in the
2857 city. If non-NULL, 'breakdown' should be an OLOSS_LAST-sized array
2858 which will be filled in with a breakdown of the kinds of waste
2859 (not cumulative).
2860 **************************************************************************/
2861 int city_waste(const struct city *pcity, Output_type_id otype, int total,
2862 int *breakdown)
2864 int penalty_waste = 0;
2865 int penalty_size = 0; /* separate notradesize/fulltradesize from normal
2866 * corruption */
2867 int total_eft = total; /* normal corruption calculated on total reduced by
2868 * possible size penalty */
2869 int waste_level = get_city_output_bonus(pcity, get_output_type(otype),
2870 EFT_OUTPUT_WASTE);
2871 bool waste_all = FALSE;
2873 if (otype == O_TRADE) {
2874 /* FIXME: special case for trade: it is affected by notradesize and
2875 * fulltradesize server settings.
2877 * If notradesize and fulltradesize are equal then the city gets no
2878 * trade at that size. */
2879 int notradesize = MIN(game.info.notradesize, game.info.fulltradesize);
2880 int fulltradesize = MAX(game.info.notradesize, game.info.fulltradesize);
2882 if (city_size_get(pcity) <= notradesize) {
2883 penalty_size = total_eft; /* Then no trade income. */
2884 } else if (city_size_get(pcity) >= fulltradesize) {
2885 penalty_size = 0;
2886 } else {
2887 penalty_size = total_eft * (fulltradesize - city_size_get(pcity))
2888 / (fulltradesize - notradesize);
2892 /* Apply corruption only to anything left after tradesize */
2893 total_eft -= penalty_size;
2895 /* Distance-based waste.
2896 * Don't bother calculating if there's nothing left to lose. */
2897 if (total_eft > 0) {
2898 int waste_by_dist = get_city_output_bonus(pcity, get_output_type(otype),
2899 EFT_OUTPUT_WASTE_BY_DISTANCE);
2900 if (waste_by_dist > 0) {
2901 const struct city *gov_center = NULL;
2902 int min_dist = FC_INFINITY;
2904 /* Check the special case that city itself is gov center
2905 * before expensive iteration through all cities. */
2906 if (is_gov_center(pcity)) {
2907 gov_center = pcity;
2908 min_dist = 0;
2909 } else {
2910 city_list_iterate(city_owner(pcity)->cities, gc) {
2911 /* Do not recheck current city */
2912 if (gc != pcity && is_gov_center(gc)) {
2913 int dist = real_map_distance(gc->tile, pcity->tile);
2915 if (dist < min_dist) {
2916 gov_center = gc;
2917 min_dist = dist;
2920 } city_list_iterate_end;
2923 if (gov_center == NULL) {
2924 waste_all = TRUE; /* no gov center - no income */
2925 } else {
2926 waste_level += waste_by_dist * min_dist;
2931 if (waste_all) {
2932 penalty_waste = total_eft;
2933 } else {
2934 int waste_pct = get_city_output_bonus(pcity, get_output_type(otype),
2935 EFT_OUTPUT_WASTE_PCT);
2937 /* corruption/waste calculated only for the actually produced amount */
2938 if (waste_level > 0) {
2939 penalty_waste = total_eft * waste_level / 100;
2942 /* bonus calculated only for the actually produced amount */
2943 penalty_waste -= penalty_waste * waste_pct / 100;
2945 /* Clip */
2946 penalty_waste = MIN(MAX(penalty_waste, 0), total_eft);
2949 if (breakdown) {
2950 breakdown[OLOSS_WASTE] = penalty_waste;
2951 breakdown[OLOSS_SIZE] = penalty_size;
2954 /* add up total penalty */
2955 return penalty_waste + penalty_size;
2958 /**************************************************************************
2959 Give the number of specialists in a city.
2960 **************************************************************************/
2961 citizens city_specialists(const struct city *pcity)
2963 citizens count = 0;
2965 specialist_type_iterate(sp) {
2966 fc_assert_ret_val(MAX_CITY_SIZE - count > pcity->specialists[sp], 0);
2967 count += pcity->specialists[sp];
2968 } specialist_type_iterate_end;
2970 return count;
2973 /****************************************************************************
2974 Return the "best" specialist available in the game. This specialist will
2975 have the most of the given type of output. If pcity is given then only
2976 specialists usable by pcity will be considered.
2977 ****************************************************************************/
2978 Specialist_type_id best_specialist(Output_type_id otype,
2979 const struct city *pcity)
2981 int best = DEFAULT_SPECIALIST;
2982 int val = get_specialist_output(pcity, best, otype);
2984 specialist_type_iterate(i) {
2985 if (!pcity || city_can_use_specialist(pcity, i)) {
2986 int val2 = get_specialist_output(pcity, i, otype);
2988 if (val2 > val) {
2989 best = i;
2990 val = val2;
2993 } specialist_type_iterate_end;
2995 return best;
2998 /**************************************************************************
2999 Adds an improvement (and its effects) to a city.
3000 **************************************************************************/
3001 void city_add_improvement(struct city *pcity,
3002 const struct impr_type *pimprove)
3004 pcity->built[improvement_index(pimprove)].turn = game.info.turn; /*I_ACTIVE*/
3006 if (is_server() && is_wonder(pimprove)) {
3007 /* Client just read the info from the packets. */
3008 wonder_built(pcity, pimprove);
3012 /**************************************************************************
3013 Removes an improvement (and its effects) from a city.
3014 **************************************************************************/
3015 void city_remove_improvement(struct city *pcity,
3016 const struct impr_type *pimprove)
3018 log_debug("Improvement %s removed from city %s",
3019 improvement_rule_name(pimprove), pcity->name);
3021 pcity->built[improvement_index(pimprove)].turn = I_DESTROYED;
3023 if (is_server() && is_wonder(pimprove)) {
3024 /* Client just read the info from the packets. */
3025 wonder_destroyed(pcity, pimprove);
3029 /**************************************************************************
3030 Returns TRUE iff the city has set the given option.
3031 **************************************************************************/
3032 bool is_city_option_set(const struct city *pcity, enum city_options option)
3034 return BV_ISSET(pcity->city_options, option);
3037 /**************************************************************************
3038 Allocate memory for this amount of city styles.
3039 **************************************************************************/
3040 void city_styles_alloc(int num)
3042 int i;
3044 city_styles = fc_calloc(num, sizeof(*city_styles));
3045 game.control.styles_count = num;
3047 for (i = 0; i < game.control.styles_count; i++) {
3048 requirement_vector_init(&city_styles[i].reqs);
3052 /**************************************************************************
3053 De-allocate the memory used by the city styles.
3054 **************************************************************************/
3055 void city_styles_free(void)
3057 int i;
3059 for (i = 0; i < game.control.styles_count; i++) {
3060 requirement_vector_free(&city_styles[i].reqs);
3063 free(city_styles);
3064 city_styles = NULL;
3065 game.control.styles_count = 0;
3068 /**************************************************************************
3069 Create virtual skeleton for a city.
3070 Values are mostly sane defaults.
3072 Always tile_set_owner(ptile, pplayer) sometime after this!
3073 **************************************************************************/
3074 struct city *create_city_virtual(struct player *pplayer,
3075 struct tile *ptile, const char *name)
3077 int i;
3079 /* Make sure that contents of city structure are correctly initialized,
3080 * if you ever allocate it by some other mean than fc_calloc() */
3081 struct city *pcity = fc_calloc(1, sizeof(*pcity));
3083 fc_assert_ret_val(NULL != name, NULL); /* No unnamed cities! */
3084 sz_strlcpy(pcity->name, name);
3086 pcity->tile = ptile;
3087 fc_assert_ret_val(NULL != pplayer, NULL); /* No unowned cities! */
3088 pcity->owner = pplayer;
3089 pcity->original = pplayer;
3091 /* City structure was allocated with fc_calloc(), so contents are initially
3092 * zero. There is no need to initialize it a second time. */
3094 /* Now set some usefull default values. */
3095 city_size_set(pcity, 1);
3096 pcity->specialists[DEFAULT_SPECIALIST] = 1;
3098 output_type_iterate(o) {
3099 pcity->bonus[o] = 100;
3100 } output_type_iterate_end;
3102 pcity->turn_plague = -1; /* -1 = never */
3103 pcity->did_buy = FALSE;
3104 pcity->city_radius_sq = game.info.init_city_radius_sq;
3105 pcity->turn_founded = game.info.turn;
3106 pcity->turn_last_built = game.info.turn;
3108 pcity->tile_cache_radius_sq = -1; /* -1 = tile_cache must be initialised */
3110 /* pcity->ai.act_cache: worker activities on the city map */
3112 /* Initialise improvements list */
3113 for (i = 0; i < ARRAY_SIZE(pcity->built); i++) {
3114 pcity->built[i].turn = I_NEVER;
3117 /* Set up the worklist */
3118 worklist_init(&pcity->worklist);
3120 pcity->units_supported = unit_list_new();
3121 pcity->task_reqs = worker_task_list_new();
3123 if (is_server()) {
3124 pcity->server.mgr_score_calc_turn = -1; /* -1 = never */
3126 CALL_FUNC_EACH_AI(city_alloc, pcity);
3127 } else {
3128 pcity->client.info_units_supported =
3129 unit_list_new_full(unit_virtual_destroy);
3130 pcity->client.info_units_present =
3131 unit_list_new_full(unit_virtual_destroy);
3132 /* collecting_info_units_supported set by fc_calloc().
3133 * collecting_info_units_present set by fc_calloc(). */
3136 return pcity;
3139 /**************************************************************************
3140 Removes the virtual skeleton of a city. You should already have removed
3141 all buildings and units you have added to the city before this.
3142 **************************************************************************/
3143 void destroy_city_virtual(struct city *pcity)
3145 CALL_FUNC_EACH_AI(city_free, pcity);
3147 citizens_free(pcity);
3149 worker_task_list_destroy(pcity->task_reqs);
3151 unit_list_destroy(pcity->units_supported);
3152 if (pcity->tile_cache != NULL) {
3153 free(pcity->tile_cache);
3156 if (!is_server()) {
3157 unit_list_destroy(pcity->client.info_units_supported);
3158 unit_list_destroy(pcity->client.info_units_present);
3159 /* Handle a rare case where the game is freed in the middle of a
3160 * spy/diplomat investigate cycle. */
3161 if (pcity->client.collecting_info_units_supported != NULL) {
3162 unit_list_destroy(pcity->client.collecting_info_units_supported);
3164 if (pcity->client.collecting_info_units_present != NULL) {
3165 unit_list_destroy(pcity->client.collecting_info_units_present);
3169 memset(pcity, 0, sizeof(*pcity)); /* ensure no pointers remain */
3170 free(pcity);
3173 /**************************************************************************
3174 Check if city with given id still exist. Use this before using
3175 old city pointers when city might have disappeared.
3176 **************************************************************************/
3177 bool city_exist(int id)
3179 /* Check if city exist in game */
3180 if (game_city_by_number(id)) {
3181 return TRUE;
3184 return FALSE;
3187 /**************************************************************************
3188 Return TRUE if the city is a virtual city. That is, it is a valid city
3189 pointer but does not correspond to a city that exists in the game.
3191 NB: A return value of FALSE implies that either the pointer is NULL or
3192 that the city exists in the game.
3193 **************************************************************************/
3194 bool city_is_virtual(const struct city *pcity)
3196 if (!pcity) {
3197 return FALSE;
3200 return pcity != game_city_by_number(pcity->id);
3203 /**************************************************************************
3204 Return TRUE if the city is centered at the given tile.
3206 NB: This doesn't simply check whether pcity->tile == ptile because that
3207 would miss virtual clones made of city center tiles, which are used by
3208 autosettler to judge whether improvements are worthwhile. The upshot is
3209 that city centers would appear to lose their irrigation/farmland bonuses
3210 as well as their minimum outputs of one food and one shield, and thus
3211 autosettler would rarely transform or mine them.
3212 **************************************************************************/
3213 bool is_city_center(const struct city *pcity, const struct tile *ptile)
3215 if (!pcity || !pcity->tile || !ptile) {
3216 return FALSE;
3219 return tile_index(city_tile(pcity)) == tile_index(ptile);
3222 /**************************************************************************
3223 Return TRUE if the city is worked without using up a citizen.
3224 **************************************************************************/
3225 bool is_free_worked(const struct city *pcity, const struct tile *ptile)
3227 return is_city_center(pcity, ptile);
3230 /**************************************************************************
3231 Return pointer to ai data of given city and ai type.
3232 **************************************************************************/
3233 void *city_ai_data(const struct city *pcity, const struct ai_type *ai)
3235 return pcity->server.ais[ai_type_number(ai)];
3238 /**************************************************************************
3239 Attach ai data to city
3240 **************************************************************************/
3241 void city_set_ai_data(struct city *pcity, const struct ai_type *ai,
3242 void *data)
3244 pcity->server.ais[ai_type_number(ai)] = data;