Stop sharing requirement_unit_state_ereq().
[freeciv.git] / common / city.c
blob4a8e3cf139d587b630dc9037ea65e98531d2ddfb
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 FREECIV_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 /* FREECIV_DEBUG */
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 FREECIV_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 /* FREECIV_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, 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;
835 return TRUE;
838 /**************************************************************************
839 Return whether player can eventually build given building in the city;
840 returns FALSE if improvement can never possibly be built in this city.
841 **************************************************************************/
842 bool can_city_build_improvement_later(const struct city *pcity,
843 struct impr_type *pimprove)
845 /* Can the _player_ ever build this improvement? */
846 if (!can_player_build_improvement_later(city_owner(pcity), pimprove)) {
847 return FALSE;
850 /* Check for requirements that aren't met and that are unchanging (so
851 * they can never be met). */
852 requirement_vector_iterate(&pimprove->reqs, preq) {
853 if (is_req_unchanging(preq)
854 && !is_req_active(city_owner(pcity), NULL, pcity, NULL,
855 pcity->tile, NULL, NULL, NULL, NULL, NULL,
856 preq, RPT_POSSIBLE)) {
857 return FALSE;
859 } requirement_vector_iterate_end;
861 return TRUE;
864 /**************************************************************************
865 Return whether given city can build given unit, ignoring whether unit
866 is obsolete.
867 **************************************************************************/
868 bool can_city_build_unit_direct(const struct city *pcity,
869 const struct unit_type *punittype)
871 if (!can_player_build_unit_direct(city_owner(pcity), punittype)) {
872 return FALSE;
875 /* Check to see if the unit has a building requirement. */
876 if (punittype->need_improvement
877 && !city_has_building(pcity, punittype->need_improvement)) {
878 return FALSE;
881 /* You can't build naval units inland. */
882 if (!uclass_has_flag(utype_class(punittype), UCF_BUILD_ANYWHERE)
883 && !is_native_near_tile(utype_class(punittype), pcity->tile)) {
884 return FALSE;
887 if (punittype->city_slots > 0
888 && city_unit_slots_available(pcity) < punittype->city_slots) {
889 return FALSE;
892 return TRUE;
895 /**************************************************************************
896 Return whether given city can build given unit; returns FALSE if unit is
897 obsolete.
898 **************************************************************************/
899 bool can_city_build_unit_now(const struct city *pcity,
900 const struct unit_type *punittype)
902 if (!can_city_build_unit_direct(pcity, punittype)) {
903 return FALSE;
905 while ((punittype = punittype->obsoleted_by) != U_NOT_OBSOLETED) {
906 if (can_player_build_unit_direct(city_owner(pcity), punittype)) {
907 return FALSE;
910 return TRUE;
913 /**************************************************************************
914 Returns whether player can eventually build given unit in the city;
915 returns FALSE if unit can never possibly be built in this city.
916 **************************************************************************/
917 bool can_city_build_unit_later(const struct city *pcity,
918 const struct unit_type *punittype)
920 /* Can the _player_ ever build this unit? */
921 if (!can_player_build_unit_later(city_owner(pcity), punittype)) {
922 return FALSE;
925 /* Some units can be built only in certain cities -- for instance,
926 ships may be built only in cities adjacent to ocean. */
927 if (!uclass_has_flag(utype_class(punittype), UCF_BUILD_ANYWHERE)
928 && !is_native_near_tile(utype_class(punittype), pcity->tile)) {
929 return FALSE;
932 return TRUE;
935 /**************************************************************************
936 Returns whether city can immediately build given target,
937 unit or improvement. This considers obsolete targets still buildable.
938 **************************************************************************/
939 bool can_city_build_direct(const struct city *pcity,
940 const struct universal *target)
942 switch (target->kind) {
943 case VUT_UTYPE:
944 return can_city_build_unit_direct(pcity, target->value.utype);
945 case VUT_IMPROVEMENT:
946 return can_city_build_improvement_direct(pcity, target->value.building);
947 default:
948 break;
950 return FALSE;
953 /**************************************************************************
954 Returns whether city can immediately build given target,
955 unit or improvement. This considers obsolete targets no longer buildable.
956 **************************************************************************/
957 bool can_city_build_now(const struct city *pcity,
958 const struct universal *target)
960 switch (target->kind) {
961 case VUT_UTYPE:
962 return can_city_build_unit_now(pcity, target->value.utype);
963 case VUT_IMPROVEMENT:
964 return can_city_build_improvement_now(pcity, target->value.building);
965 default:
966 break;
968 return FALSE;
971 /**************************************************************************
972 Returns whether city can ever build given target, unit or improvement.
973 **************************************************************************/
974 bool can_city_build_later(const struct city *pcity,
975 const struct universal *target)
977 switch (target->kind) {
978 case VUT_UTYPE:
979 return can_city_build_unit_later(pcity, target->value.utype);
980 case VUT_IMPROVEMENT:
981 return can_city_build_improvement_later(pcity, target->value.building);
982 default:
983 break;
985 return FALSE;
988 /****************************************************************************
989 Return number of free unit slots in a city.
990 ****************************************************************************/
991 int city_unit_slots_available(const struct city *pcity)
993 int max = get_city_bonus(pcity, EFT_UNIT_SLOTS);
994 int current;
996 current = 0;
997 unit_list_iterate(pcity->units_supported, punit) {
998 current += unit_type_get(punit)->city_slots;
999 } unit_list_iterate_end;
1001 return max - current;
1004 /****************************************************************************
1005 Returns TRUE iff the given city can use this kind of specialist.
1006 ****************************************************************************/
1007 bool city_can_use_specialist(const struct city *pcity,
1008 Specialist_type_id type)
1010 return are_reqs_active(city_owner(pcity), NULL, pcity, NULL,
1011 NULL, NULL, NULL, NULL, NULL, NULL,
1012 &specialist_by_number(type)->reqs, RPT_POSSIBLE);
1015 /****************************************************************************
1016 Returns TRUE iff the given city can change what it is building
1017 ****************************************************************************/
1018 bool city_can_change_build(const struct city *pcity)
1020 return !pcity->did_buy || pcity->shield_stock <= 0;
1023 /**************************************************************************
1024 Always tile_set_owner(ptile, pplayer) sometime before this!
1025 **************************************************************************/
1026 void city_choose_build_default(struct city *pcity)
1028 if (NULL == city_tile(pcity)) {
1029 /* When a "dummy" city is created with no tile, then choosing a build
1030 * target could fail. This currently might happen during map editing.
1031 * FIXME: assumes the first unit is always "valid", so check for
1032 * obsolete units elsewhere. */
1033 pcity->production.kind = VUT_UTYPE;
1034 pcity->production.value.utype = utype_by_number(0);
1035 } else {
1036 struct unit_type *u = best_role_unit(pcity, L_FIRSTBUILD);
1038 if (u) {
1039 pcity->production.kind = VUT_UTYPE;
1040 pcity->production.value.utype = u;
1041 } else {
1042 bool found = FALSE;
1044 /* Just pick the first available item. */
1046 improvement_iterate(pimprove) {
1047 if (can_city_build_improvement_direct(pcity, pimprove)) {
1048 found = TRUE;
1049 pcity->production.kind = VUT_IMPROVEMENT;
1050 pcity->production.value.building = pimprove;
1051 break;
1053 } improvement_iterate_end;
1055 if (!found) {
1056 unit_type_iterate(punittype) {
1057 if (can_city_build_unit_direct(pcity, punittype)) {
1058 found = TRUE;
1059 pcity->production.kind = VUT_UTYPE;
1060 pcity->production.value.utype = punittype;
1062 } unit_type_iterate_end;
1065 fc_assert_msg(found, "No production found for city %s!",
1066 city_name_get(pcity));
1071 #ifndef city_name_get
1072 /**************************************************************************
1073 Return the name of the city.
1074 **************************************************************************/
1075 const char *city_name_get(const struct city *pcity)
1077 return pcity->name;
1079 #endif /* city_name_get */
1081 /**************************************************************************
1082 Return the owner of the city.
1083 **************************************************************************/
1084 struct player *city_owner(const struct city *pcity)
1086 fc_assert_ret_val(NULL != pcity, NULL);
1087 fc_assert(NULL != pcity->owner);
1088 return pcity->owner;
1091 #ifndef city_tile
1092 /**************************************************************************
1093 Return the tile location of the city.
1094 Not (yet) always used, mostly for debugging.
1095 **************************************************************************/
1096 struct tile *city_tile(const struct city *pcity)
1098 return pcity->tile;
1100 #endif
1103 /*****************************************************************************
1104 Get the city size.
1105 *****************************************************************************/
1106 citizens city_size_get(const struct city *pcity)
1108 fc_assert_ret_val(pcity != NULL, 0);
1110 return pcity->size;
1113 /*****************************************************************************
1114 Add a (positive or negative) value to the city size. As citizens is an
1115 unsigned value use int for the parameter 'add'.
1116 *****************************************************************************/
1117 void city_size_add(struct city *pcity, int add)
1119 citizens size = city_size_get(pcity);
1121 fc_assert_ret(pcity != NULL);
1122 fc_assert_ret(MAX_CITY_SIZE - size > add);
1123 fc_assert_ret(size >= -add);
1125 city_size_set(pcity, city_size_get(pcity) + add);
1128 /*****************************************************************************
1129 Set the city size.
1130 *****************************************************************************/
1131 void city_size_set(struct city *pcity, citizens size)
1133 fc_assert_ret(pcity != NULL);
1135 /* Set city size. */
1136 pcity->size = size;
1139 /**************************************************************************
1140 Returns how many thousand citizen live in this city.
1141 **************************************************************************/
1142 int city_population(const struct city *pcity)
1144 /* Sum_{i=1}^{n} i == n*(n+1)/2 */
1145 return city_size_get(pcity) * (city_size_get(pcity) + 1) * 5;
1148 /**************************************************************************
1149 Returns the total amount of gold needed to pay for all buildings in the
1150 city.
1151 **************************************************************************/
1152 int city_total_impr_gold_upkeep(const struct city *pcity)
1154 int gold_needed = 0;
1156 if (!pcity) {
1157 return 0;
1160 city_built_iterate(pcity, pimprove) {
1161 gold_needed += city_improvement_upkeep(pcity, pimprove);
1162 } city_built_iterate_end;
1164 return gold_needed;
1167 /***************************************************************************
1168 Get the total amount of gold needed to pay upkeep costs for all supported
1169 units of the city. Takes into account EFT_UNIT_UPKEEP_FREE_PER_CITY.
1170 ***************************************************************************/
1171 int city_total_unit_gold_upkeep(const struct city *pcity)
1173 int gold_needed = 0;
1175 if (!pcity || !pcity->units_supported
1176 || unit_list_size(pcity->units_supported) < 1) {
1177 return 0;
1180 unit_list_iterate(pcity->units_supported, punit) {
1181 gold_needed += punit->upkeep[O_GOLD];
1182 } unit_list_iterate_end;
1184 return gold_needed;
1187 /**************************************************************************
1188 Return TRUE iff the city has this building in it.
1189 **************************************************************************/
1190 bool city_has_building(const struct city *pcity,
1191 const struct impr_type *pimprove)
1193 if (NULL == pimprove) {
1194 /* callers should ensure that any external data is tested with
1195 * valid_improvement_by_number() */
1196 return FALSE;
1198 return (pcity->built[improvement_index(pimprove)].turn > I_NEVER);
1201 /**************************************************************************
1202 Return the upkeep (gold) needed each turn to upkeep the given improvement
1203 in the given city.
1204 **************************************************************************/
1205 int city_improvement_upkeep(const struct city *pcity,
1206 const struct impr_type *b)
1208 int upkeep;
1210 if (NULL == b)
1211 return 0;
1212 if (is_wonder(b))
1213 return 0;
1215 upkeep = b->upkeep;
1216 if (upkeep <= get_building_bonus(pcity, b, EFT_UPKEEP_FREE)) {
1217 return 0;
1220 return upkeep;
1223 /**************************************************************************
1224 Calculate the output for the tile.
1225 pcity may be NULL.
1226 is_celebrating may be speculative.
1227 otype is the output type (generally O_FOOD, O_TRADE, or O_SHIELD).
1229 This can be used to calculate the benefits celebration would give.
1230 **************************************************************************/
1231 int city_tile_output(const struct city *pcity, const struct tile *ptile,
1232 bool is_celebrating, Output_type_id otype)
1234 int prod;
1235 struct terrain *pterrain = tile_terrain(ptile);
1236 const struct output_type *output = &output_types[otype];
1237 struct player *pplayer = NULL;
1239 fc_assert_ret_val(otype >= 0 && otype < O_LAST, 0);
1241 if (T_UNKNOWN == pterrain) {
1242 /* Special case for the client. The server doesn't allow unknown tiles
1243 * to be worked but we don't necessarily know what player is involved. */
1244 return 0;
1247 prod = pterrain->output[otype];
1248 if (tile_resource_is_valid(ptile)) {
1249 prod += tile_resource(ptile)->data.resource->output[otype];
1252 if (pcity != NULL) {
1253 pplayer = city_owner(pcity);
1256 switch (otype) {
1257 case O_SHIELD:
1258 if (pterrain->mining_shield_incr != 0) {
1259 prod += pterrain->mining_shield_incr
1260 * get_target_bonus_effects(NULL, pplayer, NULL, pcity, NULL,
1261 ptile, NULL, NULL, NULL, NULL, NULL,
1262 EFT_MINING_PCT)
1263 / 100;
1265 break;
1266 case O_FOOD:
1267 if (pterrain->irrigation_food_incr != 0) {
1268 prod += pterrain->irrigation_food_incr
1269 * get_target_bonus_effects(NULL, pplayer, NULL, pcity, NULL,
1270 ptile, NULL, NULL, NULL, NULL, NULL,
1271 EFT_IRRIGATION_PCT)
1272 / 100;
1274 break;
1275 case O_TRADE:
1276 case O_GOLD:
1277 case O_SCIENCE:
1278 case O_LUXURY:
1279 case O_LAST:
1280 break;
1283 prod += tile_roads_output_incr(ptile, otype);
1284 prod += (prod * tile_roads_output_bonus(ptile, otype) / 100);
1286 if (pcity) {
1287 prod += get_city_tile_output_bonus(pcity, ptile, output,
1288 EFT_OUTPUT_ADD_TILE);
1289 if (prod > 0) {
1290 int penalty_limit = get_city_tile_output_bonus(pcity, ptile, output,
1291 EFT_OUTPUT_PENALTY_TILE);
1293 if (is_celebrating) {
1294 prod += get_city_tile_output_bonus(pcity, ptile, output,
1295 EFT_OUTPUT_INC_TILE_CELEBRATE);
1296 penalty_limit = 0; /* no penalty if celebrating */
1298 prod += get_city_tile_output_bonus(pcity, ptile, output,
1299 EFT_OUTPUT_INC_TILE);
1300 prod += (prod
1301 * get_city_tile_output_bonus(pcity, ptile, output,
1302 EFT_OUTPUT_PER_TILE))
1303 / 100;
1304 if (!is_celebrating && penalty_limit > 0 && prod > penalty_limit) {
1305 prod--;
1310 prod -= (prod
1311 * get_target_bonus_effects(NULL, pplayer, NULL, pcity, NULL,
1312 ptile, NULL, NULL, output, NULL, NULL,
1313 EFT_OUTPUT_TILE_PUNISH_PCT))
1314 / 100;
1316 if (NULL != pcity && is_city_center(pcity, ptile)) {
1317 prod = MAX(prod, game.info.min_city_center_output[otype]);
1320 return prod;
1323 /**************************************************************************
1324 Calculate the production output the given tile is capable of producing
1325 for the city. The output type is given by 'otype' (generally O_FOOD,
1326 O_SHIELD, or O_TRADE).
1327 **************************************************************************/
1328 int city_tile_output_now(const struct city *pcity, const struct tile *ptile,
1329 Output_type_id otype)
1331 return city_tile_output(pcity, ptile, city_celebrating(pcity), otype);
1334 /****************************************************************************
1335 Returns TRUE when a tile is available to be worked, or the city itself is
1336 currently working the tile (and can continue).
1338 The paramter 'restriction', which is usually client_player(), allow a
1339 player to handle with its real knownledge to guess it the work of this
1340 tile is possible.
1342 This function shouldn't be called directly, but with city_can_work_tile()
1343 (common/city.[ch]) or client_city_can_work_tile() (client/climap.[ch]).
1344 ****************************************************************************/
1345 bool base_city_can_work_tile(const struct player *restriction,
1346 const struct city *pcity,
1347 const struct tile *ptile)
1349 struct player *powner = city_owner(pcity);
1350 int city_map_x, city_map_y;
1352 if (NULL == ptile) {
1353 return FALSE;
1356 if (!city_base_to_city_map(&city_map_x, &city_map_y, pcity, ptile)) {
1357 return FALSE;
1360 if (NULL != restriction
1361 && TILE_UNKNOWN == tile_get_known(ptile, restriction)) {
1362 return FALSE;
1365 if (NULL != tile_owner(ptile) && tile_owner(ptile) != powner) {
1366 return FALSE;
1368 /* TODO: civ3-like option for borders */
1370 if (NULL != tile_worked(ptile) && tile_worked(ptile) != pcity) {
1371 return FALSE;
1374 if (powner == restriction
1375 && TILE_KNOWN_SEEN != tile_get_known(ptile, powner)) {
1376 return FALSE;
1379 if (!is_free_worked(pcity, ptile)
1380 && NULL != unit_occupies_tile(ptile, powner)) {
1381 return FALSE;
1384 if (get_city_tile_output_bonus(pcity, ptile, NULL, EFT_TILE_WORKABLE) <= 0) {
1385 return FALSE;
1388 return TRUE;
1391 /**************************************************************************
1392 Returns TRUE when a tile is available to be worked, or the city itself is
1393 currently working the tile (and can continue).
1395 See also client_city_can_work_tile() (client/climap.[ch]).
1396 **************************************************************************/
1397 bool city_can_work_tile(const struct city *pcity, const struct tile *ptile)
1399 return base_city_can_work_tile(city_owner(pcity), pcity, ptile);
1402 /****************************************************************************
1403 Returns TRUE if the given unit can build a city at the given map
1404 coordinates.
1406 punit is the founding unit. It may be NULL if a city is built out of the
1407 blue (e.g., through editing).
1408 ****************************************************************************/
1409 bool city_can_be_built_here(const struct tile *ptile,
1410 const struct unit *punit)
1412 return (CB_OK == city_build_here_test(ptile, punit));
1415 /**************************************************************************
1416 Return TRUE iff the ruleset allows founding a city at a tile claimed by
1417 someone else.
1419 Since a local DiplRel requirement can be against something else than a
1420 tile an unclaimed tile can't always contradict a local DiplRel
1421 requirement. With knowledge about what entities each requirement in a
1422 requirement vector is evaluated against a contradiction can be
1423 introduced.
1425 TODO: Get rid of this together with CB_BAD_BORDERS.
1426 Maybe get rid of it before if the problem above is solved.
1427 **************************************************************************/
1428 static bool city_on_foreign_tile_is_legal(struct unit_type *punit_type)
1430 struct requirement tile_is_claimed;
1431 struct requirement tile_is_foreign;
1433 if (!utype_may_act_at_all(punit_type)) {
1434 /* Not an actor unit type. */
1435 return FALSE;
1438 /* Tile is claimed as a requirement. */
1439 tile_is_claimed.range = REQ_RANGE_LOCAL;
1440 tile_is_claimed.survives = FALSE;
1441 tile_is_claimed.source.kind = VUT_CITYTILE;
1442 tile_is_claimed.present = TRUE;
1443 tile_is_claimed.source.value.citytile = CITYT_CLAIMED;
1445 /* Tile is foreign as a requirement. */
1446 tile_is_foreign.range = REQ_RANGE_LOCAL;
1447 tile_is_foreign.survives = FALSE;
1448 tile_is_foreign.source.kind = VUT_DIPLREL;
1449 tile_is_foreign.present = TRUE;
1450 tile_is_foreign.source.value.diplrel = DRO_FOREIGN;
1452 action_enabler_list_iterate(
1453 action_enablers_for_action(ACTION_FOUND_CITY), enabler) {
1454 if (!requirement_fulfilled_by_unit_type(punit_type,
1455 &(enabler->actor_reqs))) {
1456 /* This action enabler isn't for this unit type at all. */
1457 continue;
1460 if (!(does_req_contradicts_reqs(&tile_is_claimed,
1461 &(enabler->target_reqs))
1462 || does_req_contradicts_reqs(&tile_is_foreign,
1463 &(enabler->actor_reqs)))) {
1464 /* This ruleset permits city founding on foreign tiles. */
1465 return TRUE;
1467 } action_enabler_list_iterate_end;
1469 /* This ruleset forbids city founding on foreign tiles. */
1470 return FALSE;
1473 /****************************************************************************
1474 Returns CB_OK if the given unit can build a city at the given map
1475 coordinates. Else, returns the reason of the failure.
1477 punit is the founding unit. It may be NULL if a city is built out of the
1478 blue (e.g., through editing).
1479 ****************************************************************************/
1480 enum city_build_result city_build_here_test(const struct tile *ptile,
1481 const struct unit *punit)
1483 int citymindist;
1485 if (terrain_has_flag(tile_terrain(ptile), TER_NO_CITIES)) {
1486 /* No cities on this terrain. */
1487 return CB_BAD_CITY_TERRAIN;
1490 if (punit && !can_unit_exist_at_tile(punit, ptile)
1491 /* TODO: remove CB_BAD_UNIT_TERRAIN and CB_BAD_UNIT_TERRAIN when it
1492 * can be done without regressions. */
1493 /* The ruleset may allow founding cities on non native terrain. */
1494 && !utype_can_do_act_when_ustate(unit_type_get(punit), ACTION_FOUND_CITY,
1495 USP_LIVABLE_TILE, FALSE)) {
1496 /* Many rulesets allow land units to build land cities and sea units to
1497 * build ocean cities. Air units can build cities anywhere. */
1498 return CB_BAD_UNIT_TERRAIN;
1501 if (punit && tile_owner(ptile) && tile_owner(ptile) != unit_owner(punit)
1502 /* TODO: remove CB_BAD_BORDERS when it can be done without
1503 * regressions. */
1504 /* The ruleset may allow founding cities on foreign terrain. */
1505 && !city_on_foreign_tile_is_legal(unit_type_get(punit))) {
1506 /* Cannot steal borders by settling. This has to be settled by
1507 * force of arms. */
1508 return CB_BAD_BORDERS;
1511 /* citymindist minimum is 1, meaning adjacent is okay */
1512 citymindist = game.info.citymindist;
1513 square_iterate(ptile, citymindist - 1, ptile1) {
1514 if (tile_city(ptile1)) {
1515 return CB_NO_MIN_DIST;
1517 } square_iterate_end;
1519 return CB_OK;
1522 /**************************************************************************
1523 Return TRUE iff this city is its nation's capital. The capital city is
1524 special-cased in a number of ways.
1525 **************************************************************************/
1526 bool is_capital(const struct city *pcity)
1528 return (get_city_bonus(pcity, EFT_CAPITAL_CITY) > 0);
1531 /**************************************************************************
1532 Return TRUE iff this city is governmental center.
1533 **************************************************************************/
1534 bool is_gov_center(const struct city *pcity)
1536 return (get_city_bonus(pcity, EFT_GOV_CENTER) > 0);
1539 /**************************************************************************
1540 This can be City Walls, Coastal defense... depending on attacker type.
1541 If attacker type is not given, just any defense effect will do.
1542 **************************************************************************/
1543 bool city_got_defense_effect(const struct city *pcity,
1544 const struct unit_type *attacker)
1546 if (!attacker) {
1547 /* Any defense building will do */
1548 return get_city_bonus(pcity, EFT_DEFEND_BONUS) > 0;
1551 return get_unittype_bonus(city_owner(pcity), pcity->tile, attacker,
1552 EFT_DEFEND_BONUS) > 0;
1555 /**************************************************************************
1556 Return TRUE iff the city is happy. A happy city will start celebrating
1557 soon.
1558 A city can only be happy if half or more of the population is happy,
1559 none of the population is unhappy or angry, and it has sufficient size.
1560 **************************************************************************/
1561 bool city_happy(const struct city *pcity)
1563 return (city_size_get(pcity) >= game.info.celebratesize
1564 && pcity->feel[CITIZEN_ANGRY][FEELING_FINAL] == 0
1565 && pcity->feel[CITIZEN_UNHAPPY][FEELING_FINAL] == 0
1566 && pcity->feel[CITIZEN_HAPPY][FEELING_FINAL] >= (city_size_get(pcity) + 1) / 2);
1569 /**************************************************************************
1570 Return TRUE iff the city is unhappy. An unhappy city will fall
1571 into disorder soon.
1572 **************************************************************************/
1573 bool city_unhappy(const struct city *pcity)
1575 return (pcity->feel[CITIZEN_HAPPY][FEELING_FINAL]
1576 < pcity->feel[CITIZEN_UNHAPPY][FEELING_FINAL]
1577 + 2 * pcity->feel[CITIZEN_ANGRY][FEELING_FINAL]);
1580 /**************************************************************************
1581 Return TRUE if the city was celebrating at the start of the turn,
1582 and it still has sufficient size to be in rapture.
1583 **************************************************************************/
1584 bool base_city_celebrating(const struct city *pcity)
1586 return (city_size_get(pcity) >= game.info.celebratesize && pcity->was_happy);
1589 /**************************************************************************
1590 cities celebrate only after consecutive happy turns
1591 **************************************************************************/
1592 bool city_celebrating(const struct city *pcity)
1594 return base_city_celebrating(pcity) && city_happy(pcity);
1597 /**************************************************************************
1598 Returns whether city is growing by rapture.
1599 **************************************************************************/
1600 bool city_rapture_grow(const struct city *pcity)
1602 /* .rapture is checked instead of city_celebrating() because this
1603 function is called after .was_happy was updated. */
1604 return (pcity->rapture > 0 && pcity->surplus[O_FOOD] > 0
1605 && (pcity->rapture % game.info.rapturedelay) == 0
1606 && get_city_bonus(pcity, EFT_RAPTURE_GROW) > 0);
1609 /**************************************************************************
1610 Returns TRUE iff the city is occupied.
1611 **************************************************************************/
1612 bool city_is_occupied(const struct city *pcity)
1614 if (is_server()) {
1615 /* The server sees the units inside the city. */
1616 return (unit_list_size(city_tile(pcity)->units) > 0);
1617 } else {
1618 /* The client gets the occupied property from the server. */
1619 return pcity->client.occupied;
1623 /**************************************************************************
1624 Find city with given id from list.
1625 **************************************************************************/
1626 struct city *city_list_find_number(struct city_list *This, int id)
1628 if (id != 0) {
1629 city_list_iterate(This, pcity) {
1630 if (pcity->id == id) {
1631 return pcity;
1633 } city_list_iterate_end;
1636 return NULL;
1639 /**************************************************************************
1640 Find city with given name from list.
1641 **************************************************************************/
1642 struct city *city_list_find_name(struct city_list *This, const char *name)
1644 city_list_iterate(This, pcity) {
1645 if (fc_strcasecmp(name, pcity->name) == 0) {
1646 return pcity;
1648 } city_list_iterate_end;
1650 return NULL;
1653 /**************************************************************************
1654 Comparison function for qsort for city _pointers_, sorting by city name.
1655 Args are really (struct city**), to sort an array of pointers.
1656 (Compare with old_city_name_compare() in game.c, which use city_id's)
1657 **************************************************************************/
1658 int city_name_compare(const void *p1, const void *p2)
1660 return fc_strcasecmp((*(const struct city **) p1)->name,
1661 (*(const struct city **) p2)->name);
1664 /****************************************************************************
1665 Returns the city style that has the given (translated) name.
1666 Returns -1 if none match.
1667 ****************************************************************************/
1668 int city_style_by_translated_name(const char *s)
1670 int i;
1672 for (i = 0; i < game.control.styles_count; i++) {
1673 if (0 == strcmp(city_style_name_translation(i), s)) {
1674 return i;
1678 return -1;
1681 /****************************************************************************
1682 Returns the city style that has the given (untranslated) rule name.
1683 Returns -1 if none match.
1684 ****************************************************************************/
1685 int city_style_by_rule_name(const char *s)
1687 const char *qs = Qn_(s);
1688 int i;
1690 for (i = 0; i < game.control.styles_count; i++) {
1691 if (0 == fc_strcasecmp(city_style_rule_name(i), qs)) {
1692 return i;
1696 return -1;
1699 /****************************************************************************
1700 Return the (translated) name of the given city style.
1701 You don't have to free the return pointer.
1702 ****************************************************************************/
1703 const char *city_style_name_translation(const int style)
1705 return name_translation_get(&city_styles[style].name);
1708 /****************************************************************************
1709 Return the (untranslated) rule name of the city style.
1710 You don't have to free the return pointer.
1711 ****************************************************************************/
1712 const char *city_style_rule_name(const int style)
1714 return rule_name_get(&city_styles[style].name);
1717 /* Cache of what city production caravan shields are allowed to help. */
1718 static bv_imprs caravan_helped_impr;
1719 static bv_unit_types caravan_helped_utype;
1721 /**************************************************************************
1722 Initialize the cache of what city production can use shields from
1723 caravans.
1724 **************************************************************************/
1725 void city_production_caravan_shields_init(void)
1727 struct requirement prod_as_req;
1729 /* Remove old data. */
1730 BV_CLR_ALL(caravan_helped_impr);
1731 BV_CLR_ALL(caravan_helped_utype);
1733 /* Common for all production kinds. */
1734 prod_as_req.range = REQ_RANGE_LOCAL;
1735 prod_as_req.survives = FALSE;
1736 prod_as_req.present = TRUE;
1738 /* Check improvements */
1739 prod_as_req.source.kind = VUT_IMPROVEMENT;
1741 improvement_iterate(itype) {
1742 if (!is_wonder(itype)) {
1743 /* Only wonders can currently use caravan shields. Next! */
1744 continue;
1747 /* Check this improvement. */
1748 prod_as_req.source.value.building = itype;
1750 action_enabler_list_iterate(action_enablers_for_action(
1751 ACTION_HELP_WONDER),
1752 enabler) {
1753 if (!does_req_contradicts_reqs(&prod_as_req,
1754 &(enabler->target_reqs))) {
1755 /* This improvement kind can receive caravan shields. */
1757 BV_SET(caravan_helped_impr, improvement_index(itype));
1759 /* Move on to the next improvment */
1760 break;
1762 } action_enabler_list_iterate_end;
1763 } improvement_iterate_end;
1765 /* Units can't currently use caravan shields. */
1768 /**************************************************************************
1769 Returns TRUE iff the specified production should get shields from
1770 units that has done ACTION_HELP_WONDER.
1771 **************************************************************************/
1772 bool city_production_gets_caravan_shields(const struct universal *tgt)
1774 switch (tgt->kind) {
1775 case VUT_IMPROVEMENT:
1776 return BV_ISSET(caravan_helped_impr,
1777 improvement_index(tgt->value.building));
1778 case VUT_UTYPE:
1779 return BV_ISSET(caravan_helped_utype,
1780 utype_index(tgt->value.utype));
1781 default:
1782 fc_assert(FALSE);
1783 return FALSE;
1787 /**************************************************************************
1788 Compute and optionally apply the change-production penalty for the given
1789 production change (to target) in the given city (pcity).
1790 Always returns the number of shields which would be in the stock if
1791 the penalty had been applied.
1793 If we switch the "class" of the target sometime after a city has produced
1794 (i.e., not on the turn immediately after), then there's a shield loss.
1795 But only on the first switch that turn. Also, if ever change back to
1796 original improvement class of this turn, restore lost production.
1797 **************************************************************************/
1798 int city_change_production_penalty(const struct city *pcity,
1799 const struct universal *target)
1801 int shield_stock_after_adjustment;
1802 enum production_class_type orig_class;
1803 enum production_class_type new_class;
1804 int unpenalized_shields = 0, penalized_shields = 0;
1806 switch (pcity->changed_from.kind) {
1807 case VUT_IMPROVEMENT:
1808 if (is_wonder(pcity->changed_from.value.building)) {
1809 orig_class = PCT_WONDER;
1810 } else {
1811 orig_class = PCT_NORMAL_IMPROVEMENT;
1813 break;
1814 case VUT_UTYPE:
1815 orig_class = PCT_UNIT;
1816 break;
1817 default:
1818 orig_class = PCT_LAST;
1819 break;
1822 switch (target->kind) {
1823 case VUT_IMPROVEMENT:
1824 if (is_wonder(target->value.building)) {
1825 new_class = PCT_WONDER;
1826 } else {
1827 new_class = PCT_NORMAL_IMPROVEMENT;
1829 break;
1830 case VUT_UTYPE:
1831 new_class = PCT_UNIT;
1832 break;
1833 default:
1834 new_class = PCT_LAST;
1835 break;
1838 /* Changing production is penalized under certain circumstances. */
1839 if (orig_class == new_class
1840 || orig_class == PCT_LAST) {
1841 /* There's never a penalty for building something of the same class. */
1842 unpenalized_shields = pcity->before_change_shields;
1843 } else if (city_built_last_turn(pcity)) {
1844 /* Surplus shields from the previous production won't be penalized if
1845 * you change production on the very next turn. But you can only use
1846 * up to the city's surplus amount of shields in this way. */
1847 unpenalized_shields = MIN(pcity->last_turns_shield_surplus,
1848 pcity->before_change_shields);
1849 penalized_shields = pcity->before_change_shields - unpenalized_shields;
1850 } else {
1851 /* Penalize 50% of the production. */
1852 penalized_shields = pcity->before_change_shields;
1855 /* Do not put penalty on these. It shouldn't matter whether you disband unit
1856 before or after changing production...*/
1857 unpenalized_shields += pcity->disbanded_shields;
1859 /* Caravan shields are penalized (just as if you disbanded the caravan)
1860 * if you're not building a wonder. */
1861 if (city_production_gets_caravan_shields(target)) {
1862 unpenalized_shields += pcity->caravan_shields;
1863 } else {
1864 penalized_shields += pcity->caravan_shields;
1867 shield_stock_after_adjustment =
1868 unpenalized_shields + penalized_shields / 2;
1870 return shield_stock_after_adjustment;
1873 /**************************************************************************
1874 Calculates the turns which are needed to build the requested
1875 improvement in the city. GUI Independent.
1876 **************************************************************************/
1877 int city_turns_to_build(const struct city *pcity,
1878 const struct universal *target,
1879 bool include_shield_stock)
1881 int city_shield_surplus = pcity->surplus[O_SHIELD];
1882 int city_shield_stock = include_shield_stock ?
1883 city_change_production_penalty(pcity, target) : 0;
1884 int cost = universal_build_shield_cost(target);
1886 if (target->kind == VUT_IMPROVEMENT
1887 && is_great_wonder(target->value.building)
1888 && !great_wonder_is_available(target->value.building)) {
1889 return FC_INFINITY;
1892 if (include_shield_stock && (city_shield_stock >= cost)) {
1893 return 1;
1894 } else if (city_shield_surplus > 0) {
1895 return (cost - city_shield_stock - 1) / city_shield_surplus + 1;
1896 } else {
1897 return FC_INFINITY;
1901 /**************************************************************************
1902 Calculates the turns which are needed for the city to grow. A value
1903 of FC_INFINITY means the city will never grow. A value of 0 means
1904 city growth is blocked. A negative value of -x means the city will
1905 shrink in x turns. A positive value of x means the city will grow in
1906 x turns.
1907 **************************************************************************/
1908 int city_turns_to_grow(const struct city *pcity)
1910 if (pcity->surplus[O_FOOD] > 0) {
1911 return (city_granary_size(city_size_get(pcity)) - pcity->food_stock +
1912 pcity->surplus[O_FOOD] - 1) / pcity->surplus[O_FOOD];
1913 } else if (pcity->surplus[O_FOOD] < 0) {
1914 /* turns before famine loss */
1915 return -1 + (pcity->food_stock / pcity->surplus[O_FOOD]);
1916 } else {
1917 return FC_INFINITY;
1921 /****************************************************************************
1922 Return TRUE iff the city can grow to the given size.
1923 ****************************************************************************/
1924 bool city_can_grow_to(const struct city *pcity, int pop_size)
1926 return (get_city_bonus(pcity, EFT_SIZE_UNLIMIT) > 0
1927 || pop_size <= get_city_bonus(pcity, EFT_SIZE_ADJ));
1930 /**************************************************************************
1931 is there an enemy city on this tile?
1932 **************************************************************************/
1933 struct city *is_enemy_city_tile(const struct tile *ptile,
1934 const struct player *pplayer)
1936 struct city *pcity = tile_city(ptile);
1938 if (pcity && pplayers_at_war(pplayer, city_owner(pcity)))
1939 return pcity;
1940 else
1941 return NULL;
1944 /**************************************************************************
1945 is there an friendly city on this tile?
1946 **************************************************************************/
1947 struct city *is_allied_city_tile(const struct tile *ptile,
1948 const struct player *pplayer)
1950 struct city *pcity = tile_city(ptile);
1952 if (pcity && pplayers_allied(pplayer, city_owner(pcity)))
1953 return pcity;
1954 else
1955 return NULL;
1958 /**************************************************************************
1959 is there an enemy city on this tile?
1960 **************************************************************************/
1961 struct city *is_non_attack_city_tile(const struct tile *ptile,
1962 const struct player *pplayer)
1964 struct city *pcity = tile_city(ptile);
1966 if (pcity && pplayers_non_attack(pplayer, city_owner(pcity)))
1967 return pcity;
1968 else
1969 return NULL;
1972 /**************************************************************************
1973 is there an non_allied city on this tile?
1974 **************************************************************************/
1975 struct city *is_non_allied_city_tile(const struct tile *ptile,
1976 const struct player *pplayer)
1978 struct city *pcity = tile_city(ptile);
1980 if (pcity && !pplayers_allied(pplayer, city_owner(pcity)))
1981 return pcity;
1982 else
1983 return NULL;
1986 /**************************************************************************
1987 Return TRUE if there is a friendly city near to this unit (within 3
1988 steps).
1989 **************************************************************************/
1990 bool is_unit_near_a_friendly_city(const struct unit *punit)
1992 return is_friendly_city_near(unit_owner(punit), unit_tile(punit));
1995 /**************************************************************************
1996 Return TRUE if there is a friendly city near to this tile (within 3
1997 steps).
1998 **************************************************************************/
1999 bool is_friendly_city_near(const struct player *owner,
2000 const struct tile *ptile)
2002 square_iterate(ptile, 3, ptile1) {
2003 struct city *pcity = tile_city(ptile1);
2004 if (pcity && pplayers_allied(owner, city_owner(pcity))) {
2005 return TRUE;
2007 } square_iterate_end;
2009 return FALSE;
2012 /**************************************************************************
2013 Return true iff a city exists within a city radius of the given
2014 location. may_be_on_center determines if a city at x,y counts.
2015 **************************************************************************/
2016 bool city_exists_within_max_city_map(const struct tile *ptile,
2017 bool may_be_on_center)
2019 city_tile_iterate(CITY_MAP_MAX_RADIUS_SQ, ptile, ptile1) {
2020 if (may_be_on_center || !same_pos(ptile, ptile1)) {
2021 if (tile_city(ptile1)) {
2022 return TRUE;
2025 } city_tile_iterate_end;
2027 return FALSE;
2030 /****************************************************************************
2031 Generalized formula used to calculate granary size.
2033 The AI may not deal well with non-default settings. See food_weighting().
2034 ****************************************************************************/
2035 int city_granary_size(int city_size)
2037 int food_inis = game.info.granary_num_inis;
2038 int food_inc = game.info.granary_food_inc;
2039 int base_value;
2041 /* If the city has no citizens, there is no granary. */
2042 if (city_size == 0) {
2043 return 0;
2046 /* Granary sizes for the first food_inis citizens are given directly.
2047 * After that we increase the granary size by food_inc per citizen. */
2048 if (city_size > food_inis) {
2049 base_value = game.info.granary_food_ini[food_inis - 1];
2050 base_value += food_inc * (city_size - food_inis);
2051 } else {
2052 base_value = game.info.granary_food_ini[city_size - 1];
2055 return MAX(base_value * game.info.foodbox / 100, 1);
2058 /****************************************************************************
2059 Give base happiness in any city owned by pplayer.
2060 A positive number is a number of content citizens. A negative number is
2061 a number of angry citizens (a city never starts with both).
2062 ****************************************************************************/
2063 static int player_base_citizen_happiness(const struct player *pplayer)
2065 int cities = city_list_size(pplayer->cities);
2066 int content = get_player_bonus(pplayer, EFT_CITY_UNHAPPY_SIZE);
2067 int basis = get_player_bonus(pplayer, EFT_EMPIRE_SIZE_BASE);
2068 int step = get_player_bonus(pplayer, EFT_EMPIRE_SIZE_STEP);
2070 if (basis + step <= 0) {
2071 /* Value of zero means effect is inactive */
2072 return content;
2075 if (cities > basis) {
2076 content--;
2077 if (step != 0) {
2078 /* the first penalty is at (basis + 1) cities;
2079 the next is at (basis + step + 1), _not_ (basis + step) */
2080 content -= (cities - basis - 1) / step;
2083 return content;
2086 /****************************************************************************
2087 Give base number of content citizens in any city owned by pplayer.
2088 ****************************************************************************/
2089 citizens player_content_citizens(const struct player *pplayer)
2091 int content = player_base_citizen_happiness(pplayer);
2093 return CLIP(0, content, MAX_CITY_SIZE);
2096 /****************************************************************************
2097 Give base number of angry citizens in any city owned by pplayer.
2098 ****************************************************************************/
2099 citizens player_angry_citizens(const struct player *pplayer)
2101 if (!game.info.angrycitizen) {
2102 return 0;
2103 } else {
2104 /* Create angry citizens only if we have a negative number of possible
2105 * content citizens. This can happen when empires grow really big. */
2106 int content = player_base_citizen_happiness(pplayer);
2108 return CLIP(0, -content, MAX_CITY_SIZE);
2112 /**************************************************************************
2113 Return the factor (in %) by which the city's output should be multiplied.
2114 **************************************************************************/
2115 int get_final_city_output_bonus(const struct city *pcity, Output_type_id otype)
2117 struct output_type *output = &output_types[otype];
2118 int bonus1 = 100 + get_city_tile_output_bonus(pcity, NULL, output,
2119 EFT_OUTPUT_BONUS);
2120 int bonus2 = 100 + get_city_tile_output_bonus(pcity, NULL, output,
2121 EFT_OUTPUT_BONUS_2);
2123 return MAX(bonus1 * bonus2 / 100, 0);
2126 /**************************************************************************
2127 Return the amount of gold generated by buildings under "tithe" attribute
2128 governments.
2129 **************************************************************************/
2130 int get_city_tithes_bonus(const struct city *pcity)
2132 int tithes_bonus = 0;
2134 if (get_city_bonus(pcity, EFT_HAPPINESS_TO_GOLD) <= 0) {
2135 return 0;
2138 tithes_bonus += get_city_bonus(pcity, EFT_MAKE_CONTENT);
2139 tithes_bonus += get_city_bonus(pcity, EFT_FORCE_CONTENT);
2141 return tithes_bonus;
2144 /**************************************************************************
2145 Add the incomes of a city according to the taxrates (ignore # of
2146 specialists). trade should be in output[O_TRADE].
2147 **************************************************************************/
2148 void add_tax_income(const struct player *pplayer, int trade, int *output)
2150 const int SCIENCE = 0, TAX = 1, LUXURY = 2;
2151 int rates[3], result[3];
2153 if (game.info.changable_tax) {
2154 rates[SCIENCE] = pplayer->economic.science;
2155 rates[LUXURY] = pplayer->economic.luxury;
2156 rates[TAX] = 100 - rates[SCIENCE] - rates[LUXURY];
2157 } else {
2158 rates[SCIENCE] = game.info.forced_science;
2159 rates[LUXURY] = game.info.forced_luxury;
2160 rates[TAX] = game.info.forced_gold;
2163 /* ANARCHY */
2164 if (government_of_player(pplayer) == game.government_during_revolution) {
2165 rates[SCIENCE] = 0;
2166 rates[LUXURY] = 100;
2167 rates[TAX] = 0;
2170 distribute(trade, 3, rates, result);
2172 output[O_SCIENCE] += result[SCIENCE];
2173 output[O_GOLD] += result[TAX];
2174 output[O_LUXURY] += result[LUXURY];
2177 /**************************************************************************
2178 Return TRUE if the city built something last turn (meaning production
2179 was completed between last turn and this).
2180 **************************************************************************/
2181 bool city_built_last_turn(const struct city *pcity)
2183 return pcity->turn_last_built + 1 >= game.info.turn;
2186 /****************************************************************************
2187 Calculate output (food, trade and shields) generated by the worked tiles
2188 of a city. This will completely overwrite the output[] array.
2190 'workers_map' is an boolean array which defines the placement of the
2191 workers within the city map. It uses the tile index and its size is
2192 defined by city_map_tiles_from_city(_pcity). See also cm_state_init().
2193 ****************************************************************************/
2194 static inline void get_worked_tile_output(const struct city *pcity,
2195 int *output, bool *workers_map)
2197 bool is_worked;
2198 #ifdef CITY_DEBUGGING
2199 bool is_celebrating = base_city_celebrating(pcity);
2200 #endif
2201 struct tile *pcenter = city_tile(pcity);
2203 memset(output, 0, O_LAST * sizeof(*output));
2205 city_tile_iterate_index(city_map_radius_sq_get(pcity), pcenter, ptile,
2206 city_tile_index) {
2207 if (workers_map == NULL) {
2208 struct city *pwork = tile_worked(ptile);
2210 is_worked = (NULL != pwork && pwork == pcity);
2211 } else {
2212 is_worked = workers_map[city_tile_index];
2215 if (is_worked) {
2216 output_type_iterate(o) {
2217 #ifdef CITY_DEBUGGING
2218 /* This assertion never fails, but it's so slow that we disable
2219 * it by default. */
2220 fc_assert(city_tile_cache_get_output(pcity, city_tile_index, o)
2221 == city_tile_output(pcity, ptile, is_celebrating, o));
2222 #endif /* CITY_DEBUGGING */
2223 output[o] += city_tile_cache_get_output(pcity, city_tile_index, o);
2224 } output_type_iterate_end;
2226 } city_tile_iterate_index_end;
2229 /****************************************************************************
2230 Calculate output (gold, science, and luxury) generated by the specialists
2231 of a city. The output[] array is not cleared but is just added to.
2232 ****************************************************************************/
2233 void add_specialist_output(const struct city *pcity, int *output)
2235 specialist_type_iterate(sp) {
2236 int count = pcity->specialists[sp];
2238 output_type_iterate(stat_index) {
2239 int amount = get_specialist_output(pcity, sp, stat_index);
2241 output[stat_index] += count * amount;
2242 } output_type_iterate_end;
2243 } specialist_type_iterate_end;
2246 /****************************************************************************
2247 This function sets all the values in the pcity->bonus[] array.
2248 Called near the beginning of city_refresh_from_main_map().
2250 It doesn't depend on anything else in the refresh and doesn't change
2251 as workers are moved around, but does change when buildings are built,
2252 etc.
2253 ****************************************************************************/
2254 static inline void set_city_bonuses(struct city *pcity)
2256 output_type_iterate(o) {
2257 pcity->bonus[o] = get_final_city_output_bonus(pcity, o);
2258 } output_type_iterate_end;
2261 /****************************************************************************
2262 This function sets the cache for the tile outputs, the pcity->tile_cache[]
2263 array. It is called near the beginning of city_refresh_from_main_map().
2265 It doesn't depend on anything else in the refresh and doesn't change
2266 as workers are moved around, but does change when buildings are built,
2267 etc.
2269 TODO: use the cached values elsethere in the code!
2270 ****************************************************************************/
2271 static inline void city_tile_cache_update(struct city *pcity)
2273 bool is_celebrating = base_city_celebrating(pcity);
2274 int radius_sq = city_map_radius_sq_get(pcity);
2276 /* initialize tile_cache if needed */
2277 if (pcity->tile_cache == NULL || pcity->tile_cache_radius_sq == -1
2278 || pcity->tile_cache_radius_sq != radius_sq) {
2279 pcity->tile_cache = fc_realloc(pcity->tile_cache,
2280 city_map_tiles(radius_sq)
2281 * sizeof(*(pcity->tile_cache)));
2282 pcity->tile_cache_radius_sq = radius_sq;
2285 /* Any unreal tiles are skipped - these values should have been memset
2286 * to 0 when the city was created. */
2287 city_tile_iterate_index(radius_sq, pcity->tile, ptile, city_tile_index) {
2288 output_type_iterate(o) {
2289 (pcity->tile_cache[city_tile_index]).output[o]
2290 = city_tile_output(pcity, ptile, is_celebrating, o);
2291 } output_type_iterate_end;
2292 } city_tile_iterate_index_end;
2295 /****************************************************************************
2296 This function returns the output of 'o' for the city tile 'city_tile_index'
2297 of 'pcity'.
2298 ****************************************************************************/
2299 static inline int city_tile_cache_get_output(const struct city *pcity,
2300 int city_tile_index,
2301 enum output_type_id o)
2303 fc_assert_ret_val(pcity->tile_cache_radius_sq
2304 == city_map_radius_sq_get(pcity), 0);
2305 fc_assert_ret_val(city_tile_index < city_map_tiles_from_city(pcity), 0);
2307 return (pcity->tile_cache[city_tile_index]).output[o];
2310 /**************************************************************************
2311 Set the final surplus[] array from the prod[] and usage[] values.
2312 **************************************************************************/
2313 static void set_surpluses(struct city *pcity)
2315 output_type_iterate(o) {
2316 pcity->surplus[o] = pcity->prod[o] - pcity->usage[o];
2317 } output_type_iterate_end;
2320 /**************************************************************************
2321 Copy the happyness array in the city to index i from index i-1.
2322 **************************************************************************/
2323 static void happy_copy(struct city *pcity, enum citizen_feeling i)
2325 int c = 0;
2327 for (; c < CITIZEN_LAST; c++) {
2328 pcity->feel[c][i] = pcity->feel[c][i - 1];
2332 /**************************************************************************
2333 Create content, unhappy and angry citizens.
2334 **************************************************************************/
2335 static void citizen_base_mood(struct city *pcity)
2337 struct player *pplayer = city_owner(pcity);
2338 citizens *happy = &pcity->feel[CITIZEN_HAPPY][FEELING_BASE];
2339 citizens *content = &pcity->feel[CITIZEN_CONTENT][FEELING_BASE];
2340 citizens *unhappy = &pcity->feel[CITIZEN_UNHAPPY][FEELING_BASE];
2341 citizens *angry = &pcity->feel[CITIZEN_ANGRY][FEELING_BASE];
2342 citizens size = city_size_get(pcity);
2343 citizens spes = city_specialists(pcity);
2345 /* This is the number of citizens that may start out content, depending
2346 * on empire size and game's city unhappysize. This may be bigger than
2347 * the size of the city, since this is a potential. */
2348 citizens base_content = player_content_citizens(pplayer);
2349 /* Similarly, this is the potential number of angry citizens. */
2350 citizens base_angry = player_angry_citizens(pplayer);
2352 /* Create content citizens. Take specialists from their ranks. */
2353 *content = MAX(0, MIN(size, base_content) - spes);
2355 /* Create angry citizens. Specialists never become angry. */
2356 fc_assert_action(base_content == 0 || base_angry == 0, *content = 0);
2357 *angry = MIN(base_angry, size - spes);
2359 /* Create unhappy citizens. In the beginning, all who are not content,
2360 * specialists or angry are unhappy. This is changed by luxuries and
2361 * buildings later. */
2362 *unhappy = (size - spes - *content - *angry);
2364 /* No one is born happy. */
2365 *happy = 0;
2368 /**************************************************************************
2369 Make people happy:
2370 * angry citizen are eliminated first
2371 * then content are made happy, then unhappy content, etc.
2372 * each conversions costs 2 or 4 luxuries.
2373 **************************************************************************/
2374 static inline void citizen_luxury_happy(struct city *pcity, int *luxuries)
2376 citizens *happy = &pcity->feel[CITIZEN_HAPPY][FEELING_LUXURY];
2377 citizens *content = &pcity->feel[CITIZEN_CONTENT][FEELING_LUXURY];
2378 citizens *unhappy = &pcity->feel[CITIZEN_UNHAPPY][FEELING_LUXURY];
2379 citizens *angry = &pcity->feel[CITIZEN_ANGRY][FEELING_LUXURY];
2381 while (*luxuries >= game.info.happy_cost && *angry > 0) {
2382 /* Upgrade angry to unhappy: costs HAPPY_COST each. */
2383 (*angry)--;
2384 (*unhappy)++;
2385 *luxuries -= game.info.happy_cost;
2387 while (*luxuries >= game.info.happy_cost && *content > 0) {
2388 /* Upgrade content to happy: costs HAPPY_COST each. */
2389 (*content)--;
2390 (*happy)++;
2391 *luxuries -= game.info.happy_cost;
2393 while (*luxuries >= 2 * game.info.happy_cost && *unhappy > 0) {
2394 /* Upgrade unhappy to happy. Note this is a 2-level upgrade with
2395 * double the cost. */
2396 (*unhappy)--;
2397 (*happy)++;
2398 *luxuries -= 2 * game.info.happy_cost;
2400 if (*luxuries >= game.info.happy_cost && *unhappy > 0) {
2401 /* Upgrade unhappy to content: costs HAPPY_COST each. */
2402 (*unhappy)--;
2403 (*content)++;
2404 *luxuries -= game.info.happy_cost;
2408 /**************************************************************************
2409 Make citizens happy due to luxury.
2410 **************************************************************************/
2411 static inline void citizen_happy_luxury(struct city *pcity)
2413 int x = pcity->prod[O_LUXURY];
2415 citizen_luxury_happy(pcity, &x);
2418 /**************************************************************************
2419 Make citizens content due to city improvements.
2420 **************************************************************************/
2421 static inline void citizen_content_buildings(struct city *pcity)
2423 citizens *content = &pcity->feel[CITIZEN_CONTENT][FEELING_EFFECT];
2424 citizens *unhappy = &pcity->feel[CITIZEN_UNHAPPY][FEELING_EFFECT];
2425 citizens *angry = &pcity->feel[CITIZEN_ANGRY][FEELING_EFFECT];
2426 int faces = get_city_bonus(pcity, EFT_MAKE_CONTENT);
2428 /* make people content (but not happy):
2429 get rid of angry first, then make unhappy content. */
2430 while (faces > 0 && *angry > 0) {
2431 (*angry)--;
2432 (*unhappy)++;
2433 faces--;
2435 while (faces > 0 && *unhappy > 0) {
2436 (*unhappy)--;
2437 (*content)++;
2438 faces--;
2442 /**************************************************************************
2443 Apply effects of citizen nationality to happiness
2444 **************************************************************************/
2445 static inline void citizen_happiness_nationality(struct city *pcity)
2447 citizens *happy = &pcity->feel[CITIZEN_HAPPY][FEELING_NATIONALITY];
2448 citizens *content = &pcity->feel[CITIZEN_CONTENT][FEELING_NATIONALITY];
2449 citizens *unhappy = &pcity->feel[CITIZEN_UNHAPPY][FEELING_NATIONALITY];
2451 if (game.info.citizen_nationality) {
2452 int pct = get_city_bonus(pcity, EFT_ENEMY_CITIZEN_UNHAPPY_PCT);
2454 if (pct > 0) {
2455 int enemies = 0;
2456 int unhappy_inc;
2457 struct player *owner = city_owner(pcity);
2459 citizens_foreign_iterate(pcity, pslot, nationality) {
2460 if (pplayers_at_war(owner, player_slot_get_player(pslot))) {
2461 enemies += nationality;
2463 } citizens_foreign_iterate_end;
2465 unhappy_inc = enemies * pct / 100;
2467 /* First make content => unhappy, then happy => unhappy,
2468 * then happy => content. No-one becomes angry. */
2469 while (unhappy_inc > 0 && *content > 0) {
2470 (*content)--;
2471 (*unhappy)++;
2472 unhappy_inc--;
2474 while (unhappy_inc > 1 && *happy > 0) {
2475 (*happy)--;
2476 (*unhappy)++;
2477 unhappy_inc -= 2;
2479 while (unhappy_inc > 0 && *happy > 0) {
2480 (*happy)--;
2481 (*content)++;
2482 unhappy_inc--;
2488 /**************************************************************************
2489 Make citizens happy/unhappy due to units.
2491 This function requires that pcity->martial_law and
2492 pcity->unit_happy_cost have already been set in city_support().
2493 **************************************************************************/
2494 static inline void citizen_happy_units(struct city *pcity)
2496 citizens *happy = &pcity->feel[CITIZEN_HAPPY][FEELING_MARTIAL];
2497 citizens *content = &pcity->feel[CITIZEN_CONTENT][FEELING_MARTIAL];
2498 citizens *unhappy = &pcity->feel[CITIZEN_UNHAPPY][FEELING_MARTIAL];
2499 citizens *angry = &pcity->feel[CITIZEN_ANGRY][FEELING_MARTIAL];
2500 citizens amt = pcity->martial_law;
2502 /* Pacify discontent citizens through martial law. First convert
2503 * angry => unhappy, then unhappy => content. */
2504 while (amt > 0 && *angry > 0) {
2505 (*angry)--;
2506 (*unhappy)++;
2507 amt--;
2509 while (amt > 0 && *unhappy > 0) {
2510 (*unhappy)--;
2511 (*content)++;
2512 amt--;
2515 /* Now make citizens unhappier because of military units away from home.
2516 * First make content => unhappy, then happy => unhappy,
2517 * then happy => content. */
2518 amt = pcity->unit_happy_upkeep;
2519 while (amt > 0 && *content > 0) {
2520 (*content)--;
2521 (*unhappy)++;
2522 amt--;
2524 while (amt > 1 && *happy > 0) {
2525 (*happy)--;
2526 (*unhappy)++;
2527 amt -= 2;
2529 while (amt > 0 && *happy > 0) {
2530 (*happy)--;
2531 (*content)++;
2532 amt--;
2534 /* Any remaining unhappiness is lost since angry citizens aren't created
2535 * here. */
2536 /* FIXME: Why not? - Per */
2539 /**************************************************************************
2540 Make citizens happy due to wonders.
2541 **************************************************************************/
2542 static inline void citizen_happy_wonders(struct city *pcity)
2544 citizens *happy = &pcity->feel[CITIZEN_HAPPY][FEELING_FINAL];
2545 citizens *content = &pcity->feel[CITIZEN_CONTENT][FEELING_FINAL];
2546 citizens *unhappy = &pcity->feel[CITIZEN_UNHAPPY][FEELING_FINAL];
2547 citizens *angry = &pcity->feel[CITIZEN_ANGRY][FEELING_FINAL];
2548 int bonus = get_city_bonus(pcity, EFT_MAKE_HAPPY);
2550 /* First create happy citizens from content, then from unhappy
2551 * citizens; we cannot help angry citizens here. */
2552 while (bonus > 0 && *content > 0) {
2553 (*content)--;
2554 (*happy)++;
2555 bonus--;
2557 while (bonus > 1 && *unhappy > 0) {
2558 (*unhappy)--;
2559 (*happy)++;
2560 bonus -= 2;
2562 /* The rest falls through and lets unhappy people become content. */
2564 if (get_city_bonus(pcity, EFT_NO_UNHAPPY) > 0) {
2565 *content += *unhappy + *angry;
2566 *unhappy = 0;
2567 *angry = 0;
2568 return;
2571 bonus += get_city_bonus(pcity, EFT_FORCE_CONTENT);
2573 /* get rid of angry first, then make unhappy content */
2574 while (bonus > 0 && *angry > 0) {
2575 (*angry)--;
2576 (*unhappy)++;
2577 bonus--;
2579 while (bonus > 0 && *unhappy > 0) {
2580 (*unhappy)--;
2581 (*content)++;
2582 bonus--;
2586 /**************************************************************************
2587 Set food, tax, science and shields production to zero if city is in
2588 disorder.
2589 **************************************************************************/
2590 static inline void unhappy_city_check(struct city *pcity)
2592 if (city_unhappy(pcity)) {
2593 output_type_iterate(o) {
2594 switch (output_types[o].unhappy_penalty) {
2595 case UNHAPPY_PENALTY_NONE:
2596 pcity->unhappy_penalty[o] = 0;
2597 break;
2598 case UNHAPPY_PENALTY_SURPLUS:
2599 pcity->unhappy_penalty[o] = MAX(pcity->prod[o] - pcity->usage[o], 0);
2600 break;
2601 case UNHAPPY_PENALTY_ALL_PRODUCTION:
2602 pcity->unhappy_penalty[o] = pcity->prod[o];
2603 break;
2606 pcity->prod[o] -= pcity->unhappy_penalty[o];
2607 } output_type_iterate_end;
2608 } else {
2609 memset(pcity->unhappy_penalty, 0,
2610 O_LAST * sizeof(*pcity->unhappy_penalty));
2614 /**************************************************************************
2615 Calculate the pollution from production and population in the city.
2616 **************************************************************************/
2617 int city_pollution_types(const struct city *pcity, int shield_total,
2618 int *pollu_prod, int *pollu_pop, int *pollu_mod)
2620 int prod, pop, mod;
2622 /* Add one one pollution per shield, multipled by the bonus. */
2623 prod = 100 + get_city_bonus(pcity, EFT_POLLU_PROD_PCT);
2624 prod = shield_total * MAX(prod, 0) / 100;
2626 /* Add one pollution per citizen for baseline combined bonus (100%). */
2627 pop = (100 + get_city_bonus(pcity, EFT_POLLU_POP_PCT))
2628 * (100 + get_city_bonus(pcity, EFT_POLLU_POP_PCT_2))
2629 / 100;
2630 pop = (city_size_get(pcity) * MAX(pop, 0)) / 100;
2632 /* Then there is base pollution (usually a negative number). */
2633 mod = game.info.base_pollution;
2635 if (pollu_prod) {
2636 *pollu_prod = prod;
2638 if (pollu_pop) {
2639 *pollu_pop = pop;
2641 if (pollu_mod) {
2642 *pollu_mod = mod;
2644 return MAX(prod + pop + mod, 0);
2647 /**************************************************************************
2648 Calculate pollution for the city. The shield_total must be passed in
2649 (most callers will want to pass pcity->shield_prod).
2650 **************************************************************************/
2651 int city_pollution(const struct city *pcity, int shield_total)
2653 return city_pollution_types(pcity, shield_total, NULL, NULL, NULL);
2656 /**************************************************************************
2657 Gets whether cities that pcity trades with had the plague. If so, it
2658 returns the health penalty in tenth of percent which depends on the size
2659 of both cities. The health penalty is given as the product of the ruleset
2660 option 'game.info.illness_trade_infection' (in percent) and the square
2661 root of the product of the size of both cities.
2662 *************************************************************************/
2663 static int get_trade_illness(const struct city *pcity)
2665 float illness_trade = 0.0;
2667 trade_partners_iterate(pcity, trade_city) {
2668 if (trade_city->turn_plague != -1
2669 && game.info.turn - trade_city->turn_plague < 5) {
2670 illness_trade += (float)game.info.illness_trade_infection
2671 * sqrt(1.0 * city_size_get(pcity)
2672 * city_size_get(trade_city)) / 100.0;
2674 } trade_partners_iterate_end;
2676 return (int)illness_trade;
2679 /**************************************************************************
2680 Get any effects regarding health from the buildings of the city. The
2681 effect defines the reduction of the possibility of an illness in percent.
2682 **************************************************************************/
2683 static int get_city_health(const struct city *pcity)
2685 return get_city_bonus(pcity, EFT_HEALTH_PCT);
2688 /**************************************************************************
2689 Calculate city's illness in tenth of percent:
2691 base illness (the maximum value for illness in percent is given by
2692 'game.info.illness_base_factor')
2693 + trade illness (see get_trade_illness())
2694 + pollution illness (the pollution in the city times
2695 'game.info.illness_pollution_factor')
2697 The illness is reduced by the percentage given by the health effect.
2698 Illness cannot exceed 999 (= 99.9%), or be less then 0
2699 *************************************************************************/
2700 int city_illness_calc(const struct city *pcity, int *ill_base,
2701 int *ill_size, int *ill_trade, int *ill_pollution)
2703 int illness_size = 0, illness_trade = 0, illness_pollution = 0;
2704 int illness_base, illness_percent;
2706 if (game.info.illness_on
2707 && city_size_get(pcity) > game.info.illness_min_size) {
2708 /* offset the city size by game.info.illness_min_size */
2709 int use_size = city_size_get(pcity) - game.info.illness_min_size;
2711 illness_size = (int)((1.0 - exp(- (float)use_size / 10.0))
2712 * 10.0 * game.info.illness_base_factor);
2713 if (is_server()) {
2714 /* on the server we recalculate the illness due to trade as we have
2715 * all informations */
2716 illness_trade = get_trade_illness(pcity);
2717 } else {
2718 /* on the client we have to rely on the value saved within the city
2719 * struct */
2720 illness_trade = pcity->illness_trade;
2723 illness_pollution = pcity->pollution
2724 * game.info.illness_pollution_factor / 100;
2727 illness_base = illness_size + illness_trade + illness_pollution;
2728 illness_percent = 100 - get_city_health(pcity);
2730 /* returning other data */
2731 if (ill_size) {
2732 *ill_size = illness_size;
2735 if (ill_trade) {
2736 *ill_trade = illness_trade;
2739 if (ill_pollution) {
2740 *ill_pollution = illness_pollution;
2743 if (ill_base) {
2744 *ill_base = illness_base;
2747 return CLIP(0, illness_base * illness_percent / 100 , 999);
2750 /****************************************************************************
2751 Returns whether city had a plague outbreak this turn.
2752 ****************************************************************************/
2753 bool city_had_recent_plague(const struct city *pcity)
2755 /* Correctly handles special case turn_plague == -1 (never) */
2756 return (pcity->turn_plague == game.info.turn);
2759 /****************************************************************************
2760 The maximum number of units a city can build per turn.
2761 ****************************************************************************/
2762 int city_build_slots(const struct city *pcity)
2764 return get_city_bonus(pcity, EFT_CITY_BUILD_SLOTS);
2767 /****************************************************************************
2768 A city's maximum airlift capacity.
2769 (Note, this still returns a finite number even if airliftingstyle allows
2770 unlimited airlifts)
2771 ****************************************************************************/
2772 int city_airlift_max(const struct city *pcity)
2774 return get_city_bonus(pcity, EFT_AIRLIFT);
2777 /**************************************************************************
2778 Set food, trade and shields production in a city.
2780 This initializes the prod[] and waste[] arrays. It assumes that
2781 the bonus[] and citizen_base[] arrays are alread built.
2782 **************************************************************************/
2783 inline void set_city_production(struct city *pcity)
2785 /* Calculate city production!
2787 * This is a rather complicated process if we allow rules to become
2788 * more generalized. We can assume that there are no recursive dependency
2789 * loops, but there are some dependencies that do not follow strict
2790 * ordering. For instance corruption must be calculated before
2791 * trade taxes can be counted up, which must occur before the science bonus
2792 * is added on. But the calculation of corruption must include the
2793 * trade bonus. To do this without excessive special casing means that in
2794 * this case the bonuses are multiplied on twice (but only saved the second
2795 * time).
2798 output_type_iterate(o) {
2799 pcity->prod[o] = pcity->citizen_base[o];
2800 } output_type_iterate_end;
2802 /* Add on special extra incomes: trade routes and tithes. */
2803 trade_routes_iterate(pcity, proute) {
2804 struct city *tcity = game_city_by_number(proute->partner);
2805 bool can_trade;
2807 fc_assert_action(tcity != NULL, continue);
2809 can_trade = can_cities_trade(pcity, tcity);
2811 if (!can_trade) {
2812 enum trade_route_type type = cities_trade_route_type(pcity, tcity);
2813 struct trade_route_settings *settings = trade_route_settings_by_type(type);
2815 if (settings->cancelling == TRI_ACTIVE) {
2816 can_trade = TRUE;
2820 if (can_trade) {
2821 int value;
2823 value =
2824 trade_base_between_cities(pcity, game_city_by_number(proute->partner));
2825 proute->value = trade_from_route(pcity, proute, value);
2826 pcity->prod[O_TRADE] += proute->value
2827 * (100 + get_city_bonus(pcity, EFT_TRADEROUTE_PCT)) / 100;
2828 } else {
2829 proute->value = 0;
2831 } trade_routes_iterate_end;
2832 pcity->prod[O_GOLD] += get_city_tithes_bonus(pcity);
2834 /* Account for waste. Note that waste is calculated before tax income is
2835 * calculated, so if you had "science waste" it would not include taxed
2836 * science. However waste is calculated after the bonuses are multiplied
2837 * on, so shield waste will include shield bonuses. */
2838 output_type_iterate(o) {
2839 pcity->waste[o] = city_waste(pcity, o,
2840 pcity->prod[o] * pcity->bonus[o] / 100,
2841 NULL);
2842 } output_type_iterate_end;
2844 /* Convert trade into science/luxury/gold, and add this on to whatever
2845 * science/luxury/gold is already there. */
2846 add_tax_income(city_owner(pcity),
2847 pcity->prod[O_TRADE] * pcity->bonus[O_TRADE] / 100
2848 - pcity->waste[O_TRADE] - pcity->usage[O_TRADE],
2849 pcity->prod);
2851 /* Add on effect bonuses and waste. Note that the waste calculation
2852 * (above) already includes the bonus multiplier. */
2853 output_type_iterate(o) {
2854 pcity->prod[o] = pcity->prod[o] * pcity->bonus[o] / 100;
2855 pcity->prod[o] -= pcity->waste[o];
2856 } output_type_iterate_end;
2859 /**************************************************************************
2860 Query unhappiness caused by a given unit.
2861 **************************************************************************/
2862 int city_unit_unhappiness(struct unit *punit, int *free_unhappy)
2864 struct city *pcity;
2865 struct unit_type *ut;
2866 struct player *plr;
2867 int happy_cost;
2869 if (!punit || !free_unhappy) {
2870 return 0;
2873 pcity = game_city_by_number(punit->homecity);
2874 if (pcity == NULL) {
2875 return 0;
2878 ut = unit_type_get(punit);
2879 plr = unit_owner(punit);
2880 happy_cost = utype_happy_cost(ut, plr);
2882 if (happy_cost <= 0) {
2883 return 0;
2886 fc_assert_ret_val(0 <= *free_unhappy, 0);
2888 if (!unit_being_aggressive(punit) && !is_field_unit(punit)) {
2889 return 0;
2892 happy_cost -= get_city_bonus(pcity, EFT_MAKE_CONTENT_MIL_PER);
2893 if (happy_cost <= 0) {
2894 return 0;
2897 if (*free_unhappy >= happy_cost) {
2898 *free_unhappy -= happy_cost;
2899 return 0;
2900 } else {
2901 happy_cost -= *free_unhappy;
2902 *free_unhappy = 0;
2905 return happy_cost;
2908 /**************************************************************************
2909 Calculate upkeep costs. This builds the pcity->usage[] array as well
2910 as setting some happiness values.
2911 **************************************************************************/
2912 static inline void city_support(struct city *pcity)
2914 int free_unhappy, martial_law_each;
2916 /* Clear all usage values. */
2917 memset(pcity->usage, 0, O_LAST * sizeof(*pcity->usage));
2918 pcity->martial_law = 0;
2919 pcity->unit_happy_upkeep = 0;
2921 /* Building and unit gold upkeep depends on the setting
2922 * 'game.info.gold_upkeep_style':
2923 * GOLD_UPKEEP_CITY: The upkeep for buildings and units is paid by the
2924 * city.
2925 * GOLD_UPKEEP_MIXED: The upkeep for buildings is paid by the city.
2926 * The upkeep for units is paid by the nation.
2927 * GOLD_UPKEEP_NATION: The upkeep for buildings and units is paid by the
2928 * nation. */
2929 fc_assert_msg(gold_upkeep_style_is_valid(game.info.gold_upkeep_style),
2930 "Invalid gold_upkeep_style %d", game.info.gold_upkeep_style);
2931 switch (game.info.gold_upkeep_style) {
2932 case GOLD_UPKEEP_CITY:
2933 pcity->usage[O_GOLD] += city_total_unit_gold_upkeep(pcity);
2934 /* no break */
2935 case GOLD_UPKEEP_MIXED:
2936 pcity->usage[O_GOLD] += city_total_impr_gold_upkeep(pcity);
2937 break;
2938 case GOLD_UPKEEP_NATION:
2939 /* nothing */
2940 break;
2942 /* Food consumption by citizens. */
2943 pcity->usage[O_FOOD] += game.info.food_cost * city_size_get(pcity);
2945 /* military units in this city (need _not_ be home city) can make
2946 * unhappy citizens content */
2947 martial_law_each = get_city_bonus(pcity, EFT_MARTIAL_LAW_EACH);
2948 if (martial_law_each > 0) {
2949 int count = 0;
2950 int martial_law_max = get_city_bonus(pcity, EFT_MARTIAL_LAW_MAX);
2952 unit_list_iterate(pcity->tile->units, punit) {
2953 if ((count < martial_law_max || martial_law_max == 0)
2954 && is_military_unit(punit)
2955 && unit_owner(punit) == city_owner(pcity)) {
2956 count++;
2958 } unit_list_iterate_end;
2960 pcity->martial_law = CLIP(0, count * martial_law_each, MAX_CITY_SIZE);
2963 free_unhappy = get_city_bonus(pcity, EFT_MAKE_CONTENT_MIL);
2964 unit_list_iterate(pcity->units_supported, punit) {
2965 pcity->unit_happy_upkeep += city_unit_unhappiness(punit, &free_unhappy);
2966 output_type_iterate(o) {
2967 if (O_GOLD != o) {
2968 /* O_GOLD is handled with "game.info.gold_upkeep_style", see over. */
2969 pcity->usage[o] += punit->upkeep[o];
2971 } output_type_iterate_end;
2972 } unit_list_iterate_end;
2975 /**************************************************************************
2976 Refreshes the internal cached data in the city structure.
2978 !full_refresh will not update tile_cache[] or bonus[]. These two
2979 values do not need to be recalculated for AI CMA testing.
2981 'workers_map' is an boolean array which defines the placement of the
2982 workers within the city map. It uses the tile index and its size is
2983 defined by city_map_tiles_from_city(_pcity). See also cm_state_init().
2985 If 'workers_map' is set, only basic updates are needed.
2986 **************************************************************************/
2987 void city_refresh_from_main_map(struct city *pcity, bool *workers_map)
2989 if (workers_map == NULL) {
2990 /* do a full refresh */
2992 /* Calculate the bonus[] array values. */
2993 set_city_bonuses(pcity);
2994 /* Calculate the tile_cache[] values. */
2995 city_tile_cache_update(pcity);
2996 /* manage settlers, and units */
2997 city_support(pcity);
3000 /* Calculate output from citizens (uses city_tile_cache_get_output()). */
3001 get_worked_tile_output(pcity, pcity->citizen_base, workers_map);
3002 add_specialist_output(pcity, pcity->citizen_base);
3004 set_city_production(pcity);
3005 citizen_base_mood(pcity);
3006 /* Note that pollution is calculated before unhappy_city_check() makes
3007 * deductions for disorder; so a city in disorder still causes pollution */
3008 pcity->pollution = city_pollution(pcity, pcity->prod[O_SHIELD]);
3010 happy_copy(pcity, FEELING_LUXURY);
3011 citizen_happy_luxury(pcity); /* with our new found luxuries */
3013 happy_copy(pcity, FEELING_EFFECT);
3014 citizen_content_buildings(pcity);
3016 happy_copy(pcity, FEELING_NATIONALITY);
3017 citizen_happiness_nationality(pcity);
3019 /* Martial law & unrest from units */
3020 happy_copy(pcity, FEELING_MARTIAL);
3021 citizen_happy_units(pcity);
3023 /* Building (including wonder) happiness effects */
3024 happy_copy(pcity, FEELING_FINAL);
3025 citizen_happy_wonders(pcity);
3027 unhappy_city_check(pcity);
3028 set_surpluses(pcity);
3031 /**************************************************************************
3032 Give corruption/waste generated by city. otype gives the output type
3033 (O_SHIELD/O_TRADE). 'total' gives the total output of this type in the
3034 city. If non-NULL, 'breakdown' should be an OLOSS_LAST-sized array
3035 which will be filled in with a breakdown of the kinds of waste
3036 (not cumulative).
3037 **************************************************************************/
3038 int city_waste(const struct city *pcity, Output_type_id otype, int total,
3039 int *breakdown)
3041 int penalty_waste = 0;
3042 int penalty_size = 0; /* separate notradesize/fulltradesize from normal
3043 * corruption */
3044 int total_eft = total; /* normal corruption calculated on total reduced by
3045 * possible size penalty */
3046 int waste_level = get_city_output_bonus(pcity, get_output_type(otype),
3047 EFT_OUTPUT_WASTE);
3048 bool waste_all = FALSE;
3050 if (otype == O_TRADE) {
3051 /* FIXME: special case for trade: it is affected by notradesize and
3052 * fulltradesize server settings.
3054 * If notradesize and fulltradesize are equal then the city gets no
3055 * trade at that size. */
3056 int notradesize = MIN(game.info.notradesize, game.info.fulltradesize);
3057 int fulltradesize = MAX(game.info.notradesize, game.info.fulltradesize);
3059 if (city_size_get(pcity) <= notradesize) {
3060 penalty_size = total_eft; /* Then no trade income. */
3061 } else if (city_size_get(pcity) >= fulltradesize) {
3062 penalty_size = 0;
3063 } else {
3064 penalty_size = total_eft * (fulltradesize - city_size_get(pcity))
3065 / (fulltradesize - notradesize);
3069 /* Apply corruption only to anything left after tradesize */
3070 total_eft -= penalty_size;
3072 /* Distance-based waste.
3073 * Don't bother calculating if there's nothing left to lose. */
3074 if (total_eft > 0) {
3075 int waste_by_dist = get_city_output_bonus(pcity, get_output_type(otype),
3076 EFT_OUTPUT_WASTE_BY_DISTANCE);
3077 int waste_by_rel_dist = get_city_output_bonus(pcity, get_output_type(otype),
3078 EFT_OUTPUT_WASTE_BY_REL_DISTANCE);
3079 if (waste_by_dist > 0 || waste_by_rel_dist > 0) {
3080 const struct city *gov_center = NULL;
3081 int min_dist = FC_INFINITY;
3083 /* Check the special case that city itself is gov center
3084 * before expensive iteration through all cities. */
3085 if (is_gov_center(pcity)) {
3086 gov_center = pcity;
3087 min_dist = 0;
3088 } else {
3089 city_list_iterate(city_owner(pcity)->cities, gc) {
3090 /* Do not recheck current city */
3091 if (gc != pcity && is_gov_center(gc)) {
3092 int dist = real_map_distance(gc->tile, pcity->tile);
3094 if (dist < min_dist) {
3095 gov_center = gc;
3096 min_dist = dist;
3099 } city_list_iterate_end;
3102 if (gov_center == NULL) {
3103 waste_all = TRUE; /* no gov center - no income */
3104 } else {
3105 waste_level += waste_by_dist * min_dist;
3106 if (waste_by_rel_dist > 0) {
3107 /* Multiply by 50 as an "standard size" for which EFT_OUTPUT_WASTE_BY_DISTANCE
3108 * and EFT_OUTPUT_WASTE_BY_REL_DISTANCE would give same result. */
3109 waste_level += waste_by_rel_dist * 50 * min_dist
3110 / MAX(wld.map.xsize, wld.map.ysize);
3116 if (waste_all) {
3117 penalty_waste = total_eft;
3118 } else {
3119 int waste_pct = get_city_output_bonus(pcity, get_output_type(otype),
3120 EFT_OUTPUT_WASTE_PCT);
3122 /* corruption/waste calculated only for the actually produced amount */
3123 if (waste_level > 0) {
3124 penalty_waste = total_eft * waste_level / 100;
3127 /* bonus calculated only for the actually produced amount */
3128 penalty_waste -= penalty_waste * waste_pct / 100;
3130 /* Clip */
3131 penalty_waste = MIN(MAX(penalty_waste, 0), total_eft);
3134 if (breakdown) {
3135 breakdown[OLOSS_WASTE] = penalty_waste;
3136 breakdown[OLOSS_SIZE] = penalty_size;
3139 /* add up total penalty */
3140 return penalty_waste + penalty_size;
3143 /**************************************************************************
3144 Give the number of specialists in a city.
3145 **************************************************************************/
3146 citizens city_specialists(const struct city *pcity)
3148 citizens count = 0;
3150 specialist_type_iterate(sp) {
3151 fc_assert_ret_val(MAX_CITY_SIZE - count > pcity->specialists[sp], 0);
3152 count += pcity->specialists[sp];
3153 } specialist_type_iterate_end;
3155 return count;
3158 /****************************************************************************
3159 Return the "best" specialist available in the game. This specialist will
3160 have the most of the given type of output. If pcity is given then only
3161 specialists usable by pcity will be considered.
3162 ****************************************************************************/
3163 Specialist_type_id best_specialist(Output_type_id otype,
3164 const struct city *pcity)
3166 int best = DEFAULT_SPECIALIST;
3167 int val = get_specialist_output(pcity, best, otype);
3169 specialist_type_iterate(i) {
3170 if (!pcity || city_can_use_specialist(pcity, i)) {
3171 int val2 = get_specialist_output(pcity, i, otype);
3173 if (val2 > val) {
3174 best = i;
3175 val = val2;
3178 } specialist_type_iterate_end;
3180 return best;
3183 /**************************************************************************
3184 Adds an improvement (and its effects) to a city.
3185 **************************************************************************/
3186 void city_add_improvement(struct city *pcity,
3187 const struct impr_type *pimprove)
3189 pcity->built[improvement_index(pimprove)].turn = game.info.turn; /*I_ACTIVE*/
3191 if (is_server() && is_wonder(pimprove)) {
3192 /* Client just read the info from the packets. */
3193 wonder_built(pcity, pimprove);
3197 /**************************************************************************
3198 Removes an improvement (and its effects) from a city.
3199 **************************************************************************/
3200 void city_remove_improvement(struct city *pcity,
3201 const struct impr_type *pimprove)
3203 log_debug("Improvement %s removed from city %s",
3204 improvement_rule_name(pimprove), pcity->name);
3206 pcity->built[improvement_index(pimprove)].turn = I_DESTROYED;
3208 if (is_server() && is_wonder(pimprove)) {
3209 /* Client just read the info from the packets. */
3210 wonder_destroyed(pcity, pimprove);
3214 /**************************************************************************
3215 Returns TRUE iff the city has set the given option.
3216 **************************************************************************/
3217 bool is_city_option_set(const struct city *pcity, enum city_options option)
3219 return BV_ISSET(pcity->city_options, option);
3222 /**************************************************************************
3223 Allocate memory for this amount of city styles.
3224 **************************************************************************/
3225 void city_styles_alloc(int num)
3227 int i;
3229 city_styles = fc_calloc(num, sizeof(*city_styles));
3230 game.control.styles_count = num;
3232 for (i = 0; i < game.control.styles_count; i++) {
3233 requirement_vector_init(&city_styles[i].reqs);
3237 /**************************************************************************
3238 De-allocate the memory used by the city styles.
3239 **************************************************************************/
3240 void city_styles_free(void)
3242 int i;
3244 for (i = 0; i < game.control.styles_count; i++) {
3245 requirement_vector_free(&city_styles[i].reqs);
3248 free(city_styles);
3249 city_styles = NULL;
3250 game.control.styles_count = 0;
3253 /**************************************************************************
3254 Create virtual skeleton for a city.
3255 Values are mostly sane defaults.
3257 Always tile_set_owner(ptile, pplayer) sometime after this!
3258 **************************************************************************/
3259 struct city *create_city_virtual(struct player *pplayer,
3260 struct tile *ptile, const char *name)
3262 int i;
3264 /* Make sure that contents of city structure are correctly initialized,
3265 * if you ever allocate it by some other mean than fc_calloc() */
3266 struct city *pcity = fc_calloc(1, sizeof(*pcity));
3268 fc_assert_ret_val(NULL != name, NULL); /* No unnamed cities! */
3269 sz_strlcpy(pcity->name, name);
3271 pcity->tile = ptile;
3272 fc_assert_ret_val(NULL != pplayer, NULL); /* No unowned cities! */
3273 pcity->owner = pplayer;
3274 pcity->original = pplayer;
3276 /* City structure was allocated with fc_calloc(), so contents are initially
3277 * zero. There is no need to initialize it a second time. */
3279 /* Now set some usefull default values. */
3280 city_size_set(pcity, 1);
3281 pcity->specialists[DEFAULT_SPECIALIST] = 1;
3283 output_type_iterate(o) {
3284 pcity->bonus[o] = 100;
3285 } output_type_iterate_end;
3287 pcity->turn_plague = -1; /* -1 = never */
3288 pcity->did_buy = FALSE;
3289 pcity->city_radius_sq = game.info.init_city_radius_sq;
3290 pcity->turn_founded = game.info.turn;
3291 pcity->turn_last_built = game.info.turn;
3293 pcity->tile_cache_radius_sq = -1; /* -1 = tile_cache must be initialised */
3295 /* pcity->ai.act_cache: worker activities on the city map */
3297 /* Initialise improvements list */
3298 for (i = 0; i < ARRAY_SIZE(pcity->built); i++) {
3299 pcity->built[i].turn = I_NEVER;
3302 /* Set up the worklist */
3303 worklist_init(&pcity->worklist);
3305 pcity->units_supported = unit_list_new();
3306 pcity->routes = trade_route_list_new();
3307 pcity->task_reqs = worker_task_list_new();
3309 if (is_server()) {
3310 pcity->server.mgr_score_calc_turn = -1; /* -1 = never */
3312 CALL_FUNC_EACH_AI(city_alloc, pcity);
3313 } else {
3314 pcity->client.info_units_supported =
3315 unit_list_new_full(unit_virtual_destroy);
3316 pcity->client.info_units_present =
3317 unit_list_new_full(unit_virtual_destroy);
3318 /* collecting_info_units_supported set by fc_calloc().
3319 * collecting_info_units_present set by fc_calloc(). */
3322 return pcity;
3325 /**************************************************************************
3326 Removes the virtual skeleton of a city. You should already have removed
3327 all buildings and units you have added to the city before this.
3328 **************************************************************************/
3329 void destroy_city_virtual(struct city *pcity)
3331 CALL_FUNC_EACH_AI(city_free, pcity);
3333 citizens_free(pcity);
3335 worker_task_list_destroy(pcity->task_reqs);
3337 unit_list_destroy(pcity->units_supported);
3338 trade_route_list_destroy(pcity->routes);
3339 if (pcity->tile_cache != NULL) {
3340 free(pcity->tile_cache);
3343 if (!is_server()) {
3344 unit_list_destroy(pcity->client.info_units_supported);
3345 unit_list_destroy(pcity->client.info_units_present);
3346 /* Handle a rare case where the game is freed in the middle of a
3347 * spy/diplomat investigate cycle. */
3348 if (pcity->client.collecting_info_units_supported != NULL) {
3349 unit_list_destroy(pcity->client.collecting_info_units_supported);
3351 if (pcity->client.collecting_info_units_present != NULL) {
3352 unit_list_destroy(pcity->client.collecting_info_units_present);
3356 memset(pcity, 0, sizeof(*pcity)); /* ensure no pointers remain */
3357 free(pcity);
3360 /**************************************************************************
3361 Check if city with given id still exist. Use this before using
3362 old city pointers when city might have disappeared.
3363 **************************************************************************/
3364 bool city_exist(int id)
3366 /* Check if city exist in game */
3367 if (game_city_by_number(id)) {
3368 return TRUE;
3371 return FALSE;
3374 /**************************************************************************
3375 Return TRUE if the city is a virtual city. That is, it is a valid city
3376 pointer but does not correspond to a city that exists in the game.
3378 NB: A return value of FALSE implies that either the pointer is NULL or
3379 that the city exists in the game.
3380 **************************************************************************/
3381 bool city_is_virtual(const struct city *pcity)
3383 if (!pcity) {
3384 return FALSE;
3387 return pcity != game_city_by_number(pcity->id);
3390 /**************************************************************************
3391 Return TRUE if the city is centered at the given tile.
3393 NB: This doesn't simply check whether pcity->tile == ptile because that
3394 would miss virtual clones made of city center tiles, which are used by
3395 autosettler to judge whether improvements are worthwhile. The upshot is
3396 that city centers would appear to lose their irrigation/farmland bonuses
3397 as well as their minimum outputs of one food and one shield, and thus
3398 autosettler would rarely transform or mine them.
3399 **************************************************************************/
3400 bool is_city_center(const struct city *pcity, const struct tile *ptile)
3402 if (!pcity || !pcity->tile || !ptile) {
3403 return FALSE;
3406 return tile_index(city_tile(pcity)) == tile_index(ptile);
3409 /**************************************************************************
3410 Return TRUE if the city is worked without using up a citizen.
3411 **************************************************************************/
3412 bool is_free_worked(const struct city *pcity, const struct tile *ptile)
3414 return is_city_center(pcity, ptile);
3417 /**************************************************************************
3418 Return pointer to ai data of given city and ai type.
3419 **************************************************************************/
3420 void *city_ai_data(const struct city *pcity, const struct ai_type *ai)
3422 return pcity->server.ais[ai_type_number(ai)];
3425 /**************************************************************************
3426 Attach ai data to city
3427 **************************************************************************/
3428 void city_set_ai_data(struct city *pcity, const struct ai_type *ai,
3429 void *data)
3431 pcity->server.ais[ai_type_number(ai)] = data;