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.
7
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 ***********************************************************************/
13
14 #ifdef HAVE_CONFIG_H
15 #include <fc_config.h>
16 #endif
17
18 #include <stdlib.h>
19 #include <string.h>
20 #include <math.h> /* pow, sqrt, exp */
21
22 /* utility */
23 #include "distribute.h"
24 #include "fcintl.h"
25 #include "log.h"
26 #include "mem.h"
27 #include "support.h"
28
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"
42
43 /* aicore */
44 #include "cm.h"
45
46 #include "city.h"
47
48 /* Define this to add in extra (very slow) assertions for the city code. */
49 #undef CITY_DEBUGGING
50
51 static char *citylog_map_line(int y, int city_radius_sq, int *city_map_data);
52 #ifdef DEBUG
53 /* only used for debugging */
54 static void citylog_map_index(enum log_level level);
55 static void citylog_map_radius_sq(enum log_level level);
56 #endif
57
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];
64
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];
67
68 /* definitions and functions for the tile_cache */
69 struct tile_cache {
70 int output[O_LAST];
71 };
72
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);
77
78 struct citystyle *city_styles = NULL;
79
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}
89 };
90
91 /**************************************************************************
92 Returns the coordinates for the given city tile index taking into account
93 the squared city radius.
94 **************************************************************************/
city_tile_index_to_xy(int * city_map_x,int * city_map_y,int city_tile_index,int city_radius_sq)95 bool city_tile_index_to_xy(int *city_map_x, int *city_map_y,
96 int city_tile_index, int city_radius_sq)
97 {
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);
100
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;
105 }
106
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);
109
110 return TRUE;
111 }
112
113 /**************************************************************************
114 Returns the index for the given city tile coordinates taking into account
115 the squared city radius.
116 **************************************************************************/
city_tile_xy_to_index(int city_map_x,int city_map_y,int city_radius_sq)117 int city_tile_xy_to_index(int city_map_x, int city_map_y,
118 int city_radius_sq)
119 {
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);
124
125 return city_map_xy[city_map_x][city_map_y];
126 }
127
128 /**************************************************************************
129 Returns the current squared radius of the city.
130 **************************************************************************/
city_map_radius_sq_get(const struct city * pcity)131 int city_map_radius_sq_get(const struct city *pcity)
132 {
133 /* a save return value is only the minimal squared radius */
134 fc_assert_ret_val(pcity != NULL, CITY_MAP_MIN_RADIUS_SQ);
135
136 return pcity->city_radius_sq;
137 }
138
139 /**************************************************************************
140 Returns the current squared radius of the city.
141 **************************************************************************/
city_map_radius_sq_set(struct city * pcity,int radius_sq)142 void city_map_radius_sq_set(struct city *pcity, int radius_sq)
143 {
144 fc_assert_ret(radius_sq >= CITY_MAP_MIN_RADIUS_SQ);
145 fc_assert_ret(radius_sq <= CITY_MAP_MAX_RADIUS_SQ);
146
147 pcity->city_radius_sq = radius_sq;
148 }
149
150 /**************************************************************************
151 Maximum city radius in this ruleset.
152 **************************************************************************/
rs_max_city_radius_sq(void)153 int rs_max_city_radius_sq(void)
154 {
155 int max_rad = game.info.init_city_radius_sq
156 + effect_cumulative_max(EFT_CITY_RADIUS_SQ, NULL);
157
158 return MIN(max_rad, CITY_MAP_MAX_RADIUS_SQ);
159 }
160
161 /**************************************************************************
162 Return the number of tiles for the given city radius. Special case is
163 the value -1 for no city tiles.
164 **************************************************************************/
city_map_tiles(int city_radius_sq)165 int city_map_tiles(int city_radius_sq)
166 {
167 if (city_radius_sq == CITY_MAP_CENTER_RADIUS_SQ) {
168 /* special case: city center; first tile of the city map */
169 return 0;
170 }
171
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);
174
175 return city_map_numtiles[city_radius_sq];
176 }
177
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 **************************************************************************/
is_valid_city_coords(const int city_radius_sq,const int city_map_x,const int city_map_y)182 bool is_valid_city_coords(const int city_radius_sq, const int city_map_x,
183 const int city_map_y)
184 {
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:
187 *
188 * - rectangular (max radius = 5; max squared radius = 26)
189 *
190 * 0 1 2 3 4 5 6 7 8 9 10
191 *
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
203 *
204 * -5 -4 -3 -2 -1 +0 +1 +2 +3 +4 +5
205 *
206 * - hexagonal (max radius = 5; max squared radius = 26)
207 *
208 * 0 1 2 3 4 5 6 7 8 9 10
209 *
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
221 *
222 * -5 -4 -3 -2 -1 +0 +1 +2 +3 +4 +5
223 *
224 * The following tables show the tiles per city radii / squared city radii.
225 * '-' indicates no change compared to the previous value
226 *
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 | -
232 *
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 | - | - | - | -
238 *
239 * radius | | | | | | 5
240 * radius_sq | 21 | 22 | 23 | 24 | 25 | 26
241 * ------------------+----+----+----+----+----+----
242 * tiles rectangular | - | - | - | - | 81 | 89
243 * tiles hexagonal | - | - | - | - | 91 | -
244 *
245 * So radius_sq == 5 (radius == 2) corresponds to the "traditional"
246 * used city map.
247 */
248 int dist = map_vector_to_sq_distance(CITY_ABS2REL(city_map_x),
249 CITY_ABS2REL(city_map_y));
250
251 return dist <= city_radius_sq;
252 }
253
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 **************************************************************************/
city_tile_to_city_map(int * city_map_x,int * city_map_y,const int city_radius_sq,const struct tile * city_center,const struct tile * map_tile)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)
262 {
263 map_distance_vector(city_map_x, city_map_y, city_center, map_tile);
264
265 *city_map_x += CITY_MAP_MAX_RADIUS;
266 *city_map_y += CITY_MAP_MAX_RADIUS;
267
268 return is_valid_city_coords(city_radius_sq, *city_map_x, *city_map_y);
269 }
270
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 **************************************************************************/
city_base_to_city_map(int * city_map_x,int * city_map_y,const struct city * const pcity,const struct tile * map_tile)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)
278 {
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);
282 }
283
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 **************************************************************************/
city_map_to_tile(const struct tile * city_center,int city_radius_sq,int city_map_x,int city_map_y)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)
291 {
292 int tile_x, tile_y;
293
294 fc_assert_ret_val(is_valid_city_coords(city_radius_sq, city_map_x,
295 city_map_y), NULL);
296
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);
300
301 return map_pos_to_tile(tile_x, tile_y);
302 }
303
304 /**************************************************************************
305 Compare two integer values, as required by qsort.
306 ***************************************************************************/
cmp(int v1,int v2)307 static int cmp(int v1, int v2)
308 {
309 if (v1 == v2) {
310 return 0;
311 } else if (v1 > v2) {
312 return 1;
313 } else {
314 return -1;
315 }
316 }
317
318 /**************************************************************************
319 Compare two iter_index values from the city_map_index.
320
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 ***************************************************************************/
compare_iter_index(const void * a,const void * b)325 int compare_iter_index(const void *a, const void *b)
326 {
327 const struct iter_index *index1 = a, *index2 = b;
328 int value;
329
330 value = cmp(index1->dist, index2->dist);
331 if (value != 0) {
332 return value;
333 }
334
335 value = cmp(index1->dx, index2->dx);
336 if (value != 0) {
337 return value;
338 }
339
340 value = cmp(index1->dy, index2->dy);
341 fc_assert(0 != value);
342 return value;
343 }
344
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 */
citylog_map_line(int y,int city_radius_sq,int * city_map_data)351 static char *citylog_map_line(int y, int city_radius_sq, int *city_map_data)
352 {
353 int x, mindex;
354 static char citylog[128], tmp[8];
355
356 fc_assert_ret_val(city_map_data != NULL, NULL);
357
358 /* print y coordinates (absolut) */
359 fc_snprintf(citylog, sizeof(citylog), "%2d ", y);
360
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);
373 }
374 } else {
375 fc_snprintf(tmp, sizeof(tmp), " ");
376 sz_strlcat(citylog, tmp);
377 }
378 }
379
380 /* print y coordinates (relativ) */
381 fc_snprintf(tmp, sizeof(tmp), " %+4d", CITY_ABS2REL(y));
382 sz_strlcat(citylog, tmp);
383
384 return citylog;
385 }
386 #undef CITYLOG_MAX_VAL
387
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 *****************************************************************************/
citylog_map_data(enum log_level level,int radius_sq,int * map_data)393 void citylog_map_data(enum log_level level, int radius_sq, int *map_data)
394 {
395 int x, y;
396 char line[128], tmp[8];
397
398 if (!log_do_output_for_level(level)) {
399 return;
400 }
401
402 log_base(level, "(max squared city radius = %d)", CITY_MAP_MAX_RADIUS_SQ);
403
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);
409 }
410 log_base(level, "%s", line);
411
412 for (y = 0; y < CITY_MAP_MAX_SIZE; y++) {
413 log_base(level, "%s", citylog_map_line(y, radius_sq, map_data));
414 }
415
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);
421 }
422 log_base(level, "%s", line);
423 }
424
425 /****************************************************************************
426 Display the location of the workers within the city map of pcity.
427 *****************************************************************************/
citylog_map_workers(enum log_level level,struct city * pcity)428 void citylog_map_workers(enum log_level level, struct city *pcity)
429 {
430 int *city_map_data = NULL;
431
432 fc_assert_ret(pcity != NULL);
433
434 if (!log_do_output_for_level(level)) {
435 return;
436 }
437
438 city_map_data = fc_calloc(city_map_tiles(city_map_radius_sq_get(pcity)),
439 sizeof(*city_map_data));
440
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;
448
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);
452 }
453
454 #ifdef FREECIV_DEBUG
455 /****************************************************************************
456 Log the index of all tiles of the city map.
457 *****************************************************************************/
citylog_map_index(enum log_level level)458 static void citylog_map_index(enum log_level level)
459 {
460 int *city_map_data = NULL;
461
462 if (!log_do_output_for_level(level)) {
463 return;
464 }
465
466 city_map_data = fc_calloc(city_map_tiles(CITY_MAP_MAX_RADIUS_SQ),
467 sizeof(*city_map_data));
468
469 city_map_iterate(CITY_MAP_MAX_RADIUS_SQ, cindex, x, y) {
470 city_map_data[cindex] = cindex;
471 } city_map_iterate_end;
472
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);
476 }
477
478 /****************************************************************************
479 Log the radius of all tiles of the city map.
480 *****************************************************************************/
citylog_map_radius_sq(enum log_level level)481 static void citylog_map_radius_sq(enum log_level level)
482 {
483 int *city_map_data = NULL;
484
485 if (!log_do_output_for_level(level)) {
486 return;
487 }
488
489 city_map_data = fc_calloc(city_map_tiles(CITY_MAP_MAX_RADIUS_SQ),
490 sizeof(*city_map_data));
491
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;
496
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);
500 }
501 #endif /* FREECIV_DEBUG */
502
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 ***************************************************************************/
generate_city_map_indices(void)507 void generate_city_map_indices(void)
508 {
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];
512
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 */
516 }
517
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);
526
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;
531
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]++;
536 }
537 }
538
539 city_count_tiles++;
540 }
541
542 /* Initialise city_map_xy. -1 defines a invalid city map positions. */
543 city_map_xy[CITY_REL2ABS(dx)][CITY_REL2ABS(dy)] = -1;
544 }
545 }
546
547 fc_assert(NULL == city_map_index);
548 city_map_index = fc_malloc(city_count_tiles * sizeof(*city_map_index));
549
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];
553 }
554
555 qsort(city_map_index, city_count_tiles, sizeof(*city_map_index),
556 compare_iter_index);
557
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;
563 }
564
565 #ifdef DEBUG
566 citylog_map_radius_sq(LOG_DEBUG);
567 citylog_map_index(LOG_DEBUG);
568
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));
571 }
572
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]);
580 }
581 #endif /* DEBUG */
582
583 cm_init_citymap();
584 }
585
586 /****************************************************************************
587 Free memory allocated by generate_citymap_index
588 *****************************************************************************/
free_city_map_index(void)589 void free_city_map_index(void)
590 {
591 FC_FREE(city_map_index);
592 }
593
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 *****************************************************************************/
get_output_identifier(Output_type_id output)599 const char *get_output_identifier(Output_type_id output)
600 {
601 fc_assert_ret_val(output >= 0 && output < O_LAST, NULL);
602 return output_types[output].id;
603 }
604
605 /****************************************************************************
606 Return a translated name for the output type. This name should only be
607 used for user display.
608 *****************************************************************************/
get_output_name(Output_type_id output)609 const char *get_output_name(Output_type_id output)
610 {
611 fc_assert_ret_val(output >= 0 && output < O_LAST, NULL);
612 return _(output_types[output].name);
613 }
614
615 /****************************************************************************
616 Return the output type for this index.
617 ****************************************************************************/
get_output_type(Output_type_id output)618 struct output_type *get_output_type(Output_type_id output)
619 {
620 fc_assert_ret_val(output >= 0 && output < O_LAST, NULL);
621 return &output_types[output];
622 }
623
624 /**************************************************************************
625 Find the output type for this output identifier.
626 **************************************************************************/
output_type_by_identifier(const char * id)627 Output_type_id output_type_by_identifier(const char *id)
628 {
629 Output_type_id o;
630
631 for (o = 0; o < O_LAST; o++) {
632 if (fc_strcasecmp(output_types[o].id, id) == 0) {
633 return o;
634 }
635 }
636
637 return O_LAST;
638 }
639
640 /**************************************************************************
641 Return the extended name of the building.
642 **************************************************************************/
city_improvement_name_translation(const struct city * pcity,struct impr_type * pimprove)643 const char *city_improvement_name_translation(const struct city *pcity,
644 struct impr_type *pimprove)
645 {
646 static char buffer[256];
647 const char *state = NULL;
648
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");
656 }
657 }
658 if (pcity) {
659 struct player *pplayer = city_owner(pcity);
660
661 if (improvement_obsolete(pplayer, pimprove, pcity)) {
662 state = Q_("?obsolete:O");
663 } else if (is_improvement_redundant(pcity, pimprove)) {
664 state = Q_("?redundant:*");
665 }
666 }
667
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);
674 }
675 }
676
677 /**************************************************************************
678 Return the extended name of the current production.
679 **************************************************************************/
city_production_name_translation(const struct city * pcity)680 const char *city_production_name_translation(const struct city *pcity)
681 {
682 static char buffer[256];
683
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;
690 };
691 return universal_name_translation(&pcity->production, buffer, sizeof(buffer));
692 }
693
694 /**************************************************************************
695 Return TRUE when the current production has this flag.
696 **************************************************************************/
city_production_has_flag(const struct city * pcity,enum impr_flag_id flag)697 bool city_production_has_flag(const struct city *pcity,
698 enum impr_flag_id flag)
699 {
700 return VUT_IMPROVEMENT == pcity->production.kind
701 && improvement_has_flag(pcity->production.value.building, flag);
702 }
703
704 /**************************************************************************
705 Return the number of shields it takes to build current city production.
706 **************************************************************************/
city_production_build_shield_cost(const struct city * pcity)707 int city_production_build_shield_cost(const struct city *pcity)
708 {
709 return universal_build_shield_cost(&pcity->production);
710 }
711
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 **************************************************************************/
city_production_build_units(const struct city * pcity,bool add_production,int * num_units)717 bool city_production_build_units(const struct city *pcity,
718 bool add_production, int *num_units)
719 {
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;
725
726 fc_assert_ret_val(num_units != NULL, FALSE);
727 (*num_units) = 0;
728
729 if (pcity->production.kind != VUT_UTYPE) {
730 /* not a unit as the current production */
731 return FALSE;
732 }
733
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;
740 }
741
742 if (add_production) {
743 shields_left += pcity->prod[O_SHIELD];
744 }
745
746 unit_shield_cost = utype_build_shield_cost(utype);
747
748 for (i = 0; i < build_slots; i++) {
749 if (shields_left < unit_shield_cost) {
750 /* not enough shields */
751 break;
752 }
753
754 (*num_units)++;
755 shields_left -= unit_shield_cost;
756
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;
764 }
765 }
766 }
767
768 return TRUE;
769 }
770
771 /**************************************************************************
772 Return the cost (gold) to buy the current city production.
773 **************************************************************************/
city_production_buy_gold_cost(const struct city * pcity)774 int city_production_buy_gold_cost(const struct city *pcity)
775 {
776 int build = pcity->shield_stock;
777
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;
787 };
788 return FC_INFINITY;
789 }
790
791 /**************************************************************************
792 Calculates the turns which are needed to build the requested
793 production in the city. GUI Independent.
794 **************************************************************************/
city_production_turns_to_build(const struct city * pcity,bool include_shield_stock)795 int city_production_turns_to_build(const struct city *pcity,
796 bool include_shield_stock)
797 {
798 return city_turns_to_build(pcity, &pcity->production, include_shield_stock);
799 }
800
801 /**************************************************************************
802 Return whether given city can build given building, ignoring whether
803 it is obsolete.
804 **************************************************************************/
can_city_build_improvement_direct(const struct city * pcity,struct impr_type * pimprove)805 bool can_city_build_improvement_direct(const struct city *pcity,
806 struct impr_type *pimprove)
807 {
808 if (!can_player_build_improvement_direct(city_owner(pcity), pimprove)) {
809 return FALSE;
810 }
811
812 if (city_has_building(pcity, pimprove)) {
813 return FALSE;
814 }
815
816 return are_reqs_active(city_owner(pcity), NULL, pcity, NULL,
817 pcity->tile, NULL, NULL, NULL, NULL,
818 &(pimprove->reqs), RPT_CERTAIN);
819 }
820
821 /**************************************************************************
822 Return whether given city can build given building; returns FALSE if
823 the building is obsolete.
824 **************************************************************************/
can_city_build_improvement_now(const struct city * pcity,struct impr_type * pimprove)825 bool can_city_build_improvement_now(const struct city *pcity,
826 struct impr_type *pimprove)
827 {
828 if (!can_city_build_improvement_direct(pcity, pimprove)) {
829 return FALSE;
830 }
831 if (improvement_obsolete(city_owner(pcity), pimprove, pcity)) {
832 return FALSE;
833 }
834 return TRUE;
835 }
836
837 /**************************************************************************
838 Return whether player can eventually build given building in the city;
839 returns FALSE if improvement can never possibly be built in this city.
840 **************************************************************************/
can_city_build_improvement_later(const struct city * pcity,struct impr_type * pimprove)841 bool can_city_build_improvement_later(const struct city *pcity,
842 struct impr_type *pimprove)
843 {
844 /* Can the _player_ ever build this improvement? */
845 if (!can_player_build_improvement_later(city_owner(pcity), pimprove)) {
846 return FALSE;
847 }
848
849 /* Check for requirements that aren't met and that are unchanging (so
850 * they can never be met). */
851 requirement_vector_iterate(&pimprove->reqs, preq) {
852 if (is_req_unchanging(preq)
853 && !is_req_active(city_owner(pcity), NULL, pcity, NULL,
854 pcity->tile, NULL, NULL, NULL, NULL,
855 preq, RPT_POSSIBLE)) {
856 return FALSE;
857 }
858 } requirement_vector_iterate_end;
859 return TRUE;
860 }
861
862 /**************************************************************************
863 Return whether given city can build given unit, ignoring whether unit
864 is obsolete.
865 **************************************************************************/
can_city_build_unit_direct(const struct city * pcity,const struct unit_type * punittype)866 bool can_city_build_unit_direct(const struct city *pcity,
867 const struct unit_type *punittype)
868 {
869 if (!can_player_build_unit_direct(city_owner(pcity), punittype)) {
870 return FALSE;
871 }
872
873 /* Check to see if the unit has a building requirement. */
874 if (punittype->need_improvement
875 && !city_has_building(pcity, punittype->need_improvement)) {
876 return FALSE;
877 }
878
879 /* You can't build naval units inland. */
880 if (!uclass_has_flag(utype_class(punittype), UCF_BUILD_ANYWHERE)
881 && !is_native_near_tile(utype_class(punittype), pcity->tile)) {
882 return FALSE;
883 }
884 return TRUE;
885 }
886
887 /**************************************************************************
888 Return whether given city can build given unit; returns FALSE if unit is
889 obsolete.
890 **************************************************************************/
can_city_build_unit_now(const struct city * pcity,const struct unit_type * punittype)891 bool can_city_build_unit_now(const struct city *pcity,
892 const struct unit_type *punittype)
893 {
894 if (!can_city_build_unit_direct(pcity, punittype)) {
895 return FALSE;
896 }
897 while ((punittype = punittype->obsoleted_by) != U_NOT_OBSOLETED) {
898 if (can_player_build_unit_direct(city_owner(pcity), punittype)) {
899 return FALSE;
900 }
901 }
902 return TRUE;
903 }
904
905 /**************************************************************************
906 Returns whether player can eventually build given unit in the city;
907 returns FALSE if unit can never possibly be built in this city.
908 **************************************************************************/
can_city_build_unit_later(const struct city * pcity,const struct unit_type * punittype)909 bool can_city_build_unit_later(const struct city *pcity,
910 const struct unit_type *punittype)
911 {
912 /* Can the _player_ ever build this unit? */
913 if (!can_player_build_unit_later(city_owner(pcity), punittype)) {
914 return FALSE;
915 }
916
917 /* Some units can be built only in certain cities -- for instance,
918 ships may be built only in cities adjacent to ocean. */
919 if (!uclass_has_flag(utype_class(punittype), UCF_BUILD_ANYWHERE)
920 && !is_native_near_tile(utype_class(punittype), pcity->tile)) {
921 return FALSE;
922 }
923
924 return TRUE;
925 }
926
927 /**************************************************************************
928 Returns whether city can immediately build given target,
929 unit or improvement. This considers obsolete targets still buildable.
930 **************************************************************************/
can_city_build_direct(const struct city * pcity,const struct universal * target)931 bool can_city_build_direct(const struct city *pcity,
932 const struct universal *target)
933 {
934 switch (target->kind) {
935 case VUT_UTYPE:
936 return can_city_build_unit_direct(pcity, target->value.utype);
937 case VUT_IMPROVEMENT:
938 return can_city_build_improvement_direct(pcity, target->value.building);
939 default:
940 break;
941 };
942 return FALSE;
943 }
944
945 /**************************************************************************
946 Returns whether city can immediately build given target,
947 unit or improvement. This considers obsolete targets no longer buildable.
948 **************************************************************************/
can_city_build_now(const struct city * pcity,const struct universal * target)949 bool can_city_build_now(const struct city *pcity,
950 const struct universal *target)
951 {
952 switch (target->kind) {
953 case VUT_UTYPE:
954 return can_city_build_unit_now(pcity, target->value.utype);
955 case VUT_IMPROVEMENT:
956 return can_city_build_improvement_now(pcity, target->value.building);
957 default:
958 break;
959 };
960 return FALSE;
961 }
962
963 /**************************************************************************
964 Returns whether city can ever build given target, unit or improvement.
965 **************************************************************************/
can_city_build_later(const struct city * pcity,const struct universal * target)966 bool can_city_build_later(const struct city *pcity,
967 const struct universal *target)
968 {
969 switch (target->kind) {
970 case VUT_UTYPE:
971 return can_city_build_unit_later(pcity, target->value.utype);
972 case VUT_IMPROVEMENT:
973 return can_city_build_improvement_later(pcity, target->value.building);
974 default:
975 break;
976 };
977 return FALSE;
978 }
979
980 /****************************************************************************
981 Returns TRUE iff the given city can use this kind of specialist.
982 ****************************************************************************/
city_can_use_specialist(const struct city * pcity,Specialist_type_id type)983 bool city_can_use_specialist(const struct city *pcity,
984 Specialist_type_id type)
985 {
986 return are_reqs_active(city_owner(pcity), NULL, pcity, NULL,
987 NULL, NULL, NULL, NULL, NULL,
988 &specialist_by_number(type)->reqs, RPT_POSSIBLE);
989 }
990
991 /****************************************************************************
992 Returns TRUE iff the given city can change what it is building
993 ****************************************************************************/
city_can_change_build(const struct city * pcity)994 bool city_can_change_build(const struct city *pcity)
995 {
996 return !pcity->did_buy || pcity->shield_stock <= 0;
997 }
998
999 /**************************************************************************
1000 Always tile_set_owner(ptile, pplayer) sometime before this!
1001 **************************************************************************/
city_choose_build_default(struct city * pcity)1002 void city_choose_build_default(struct city *pcity)
1003 {
1004 if (NULL == city_tile(pcity)) {
1005 /* When a "dummy" city is created with no tile, then choosing a build
1006 * target could fail. This currently might happen during map editing.
1007 * FIXME: assumes the first unit is always "valid", so check for
1008 * obsolete units elsewhere. */
1009 pcity->production.kind = VUT_UTYPE;
1010 pcity->production.value.utype = utype_by_number(0);
1011 } else {
1012 struct unit_type *u = best_role_unit(pcity, L_FIRSTBUILD);
1013
1014 if (u) {
1015 pcity->production.kind = VUT_UTYPE;
1016 pcity->production.value.utype = u;
1017 } else {
1018 bool found = FALSE;
1019
1020 /* Just pick the first available item. */
1021
1022 improvement_iterate(pimprove) {
1023 if (can_city_build_improvement_direct(pcity, pimprove)) {
1024 found = TRUE;
1025 pcity->production.kind = VUT_IMPROVEMENT;
1026 pcity->production.value.building = pimprove;
1027 break;
1028 }
1029 } improvement_iterate_end;
1030
1031 if (!found) {
1032 unit_type_iterate(punittype) {
1033 if (can_city_build_unit_direct(pcity, punittype)) {
1034 found = TRUE;
1035 pcity->production.kind = VUT_UTYPE;
1036 pcity->production.value.utype = punittype;
1037 }
1038 } unit_type_iterate_end;
1039 }
1040
1041 fc_assert_msg(found, "No production found for city %s!",
1042 city_name_get(pcity));
1043 }
1044 }
1045 }
1046
1047 #ifndef city_name_get
1048 /**************************************************************************
1049 Return the name of the city.
1050 **************************************************************************/
city_name_get(const struct city * pcity)1051 const char *city_name_get(const struct city *pcity)
1052 {
1053 return pcity->name;
1054 }
1055 #endif /* city_name_get */
1056
1057 /**************************************************************************
1058 Return the owner of the city.
1059 **************************************************************************/
city_owner(const struct city * pcity)1060 struct player *city_owner(const struct city *pcity)
1061 {
1062 fc_assert_ret_val(NULL != pcity, NULL);
1063 fc_assert(NULL != pcity->owner);
1064 return pcity->owner;
1065 }
1066
1067 /*****************************************************************************
1068 Get the city size.
1069 *****************************************************************************/
city_size_get(const struct city * pcity)1070 citizens city_size_get(const struct city *pcity)
1071 {
1072 fc_assert_ret_val(pcity != NULL, 0);
1073
1074 return pcity->size;
1075 }
1076
1077 /*****************************************************************************
1078 Add a (positive or negative) value to the city size. As citizens is an
1079 unsigned value use int for the parameter 'add'.
1080 *****************************************************************************/
city_size_add(struct city * pcity,int add)1081 void city_size_add(struct city *pcity, int add)
1082 {
1083 citizens size = city_size_get(pcity);
1084
1085 fc_assert_ret(pcity != NULL);
1086 fc_assert_ret(MAX_CITY_SIZE - size > add);
1087 fc_assert_ret(size >= -add);
1088
1089 city_size_set(pcity, city_size_get(pcity) + add);
1090 }
1091
1092 /*****************************************************************************
1093 Set the city size.
1094 *****************************************************************************/
city_size_set(struct city * pcity,citizens size)1095 void city_size_set(struct city *pcity, citizens size)
1096 {
1097 fc_assert_ret(pcity != NULL);
1098
1099 /* Set city size. */
1100 pcity->size = size;
1101 }
1102
1103 /**************************************************************************
1104 Returns how many thousand citizen live in this city.
1105 **************************************************************************/
city_population(const struct city * pcity)1106 int city_population(const struct city *pcity)
1107 {
1108 /* Sum_{i=1}^{n} i == n*(n+1)/2 */
1109 return city_size_get(pcity) * (city_size_get(pcity) + 1) * 5;
1110 }
1111
1112 /**************************************************************************
1113 Returns the total amount of gold needed to pay for all buildings in the
1114 city.
1115 **************************************************************************/
city_total_impr_gold_upkeep(const struct city * pcity)1116 int city_total_impr_gold_upkeep(const struct city *pcity)
1117 {
1118 int gold_needed = 0;
1119
1120 if (!pcity) {
1121 return 0;
1122 }
1123
1124 city_built_iterate(pcity, pimprove) {
1125 gold_needed += city_improvement_upkeep(pcity, pimprove);
1126 } city_built_iterate_end;
1127
1128 return gold_needed;
1129 }
1130
1131 /***************************************************************************
1132 Get the total amount of gold needed to pay upkeep costs for all supported
1133 units of the city. Takes into account EFT_UNIT_UPKEEP_FREE_PER_CITY.
1134 ***************************************************************************/
city_total_unit_gold_upkeep(const struct city * pcity)1135 int city_total_unit_gold_upkeep(const struct city *pcity)
1136 {
1137 int gold_needed = 0;
1138
1139 if (!pcity || !pcity->units_supported
1140 || unit_list_size(pcity->units_supported) < 1) {
1141 return 0;
1142 }
1143
1144 unit_list_iterate(pcity->units_supported, punit) {
1145 gold_needed += punit->upkeep[O_GOLD];
1146 } unit_list_iterate_end;
1147
1148 return gold_needed;
1149 }
1150
1151 /**************************************************************************
1152 Return TRUE iff the city has this building in it.
1153 **************************************************************************/
city_has_building(const struct city * pcity,const struct impr_type * pimprove)1154 bool city_has_building(const struct city *pcity,
1155 const struct impr_type *pimprove)
1156 {
1157 if (NULL == pimprove) {
1158 /* callers should ensure that any external data is tested with
1159 * valid_improvement_by_number() */
1160 return FALSE;
1161 }
1162 return (pcity->built[improvement_index(pimprove)].turn > I_NEVER);
1163 }
1164
1165 /**************************************************************************
1166 Return the upkeep (gold) needed each turn to upkeep the given improvement
1167 in the given city.
1168 **************************************************************************/
city_improvement_upkeep(const struct city * pcity,const struct impr_type * b)1169 int city_improvement_upkeep(const struct city *pcity,
1170 const struct impr_type *b)
1171 {
1172 int upkeep;
1173
1174 if (NULL == b)
1175 return 0;
1176 if (is_wonder(b))
1177 return 0;
1178
1179 upkeep = b->upkeep;
1180 if (upkeep <= get_building_bonus(pcity, b, EFT_UPKEEP_FREE)) {
1181 return 0;
1182 }
1183
1184 return upkeep;
1185 }
1186
1187 /**************************************************************************
1188 Calculate the output for the tile.
1189 pcity may be NULL.
1190 is_celebrating may be speculative.
1191 otype is the output type (generally O_FOOD, O_TRADE, or O_SHIELD).
1192
1193 This can be used to calculate the benefits celebration would give.
1194 **************************************************************************/
city_tile_output(const struct city * pcity,const struct tile * ptile,bool is_celebrating,Output_type_id otype)1195 int city_tile_output(const struct city *pcity, const struct tile *ptile,
1196 bool is_celebrating, Output_type_id otype)
1197 {
1198 int prod;
1199 struct terrain *pterrain = tile_terrain(ptile);
1200 const struct output_type *output = &output_types[otype];
1201 struct player *pplayer = NULL;
1202
1203 fc_assert_ret_val(otype >= 0 && otype < O_LAST, 0);
1204
1205 if (T_UNKNOWN == pterrain) {
1206 /* Special case for the client. The server doesn't allow unknown tiles
1207 * to be worked but we don't necessarily know what player is involved. */
1208 return 0;
1209 }
1210
1211 prod = pterrain->output[otype];
1212 if (tile_resource_is_valid(ptile)) {
1213 prod += tile_resource(ptile)->output[otype];
1214 }
1215
1216 if (pcity != NULL) {
1217 pplayer = city_owner(pcity);
1218 }
1219
1220 switch (otype) {
1221 case O_SHIELD:
1222 if (pterrain->mining_shield_incr != 0) {
1223 prod += pterrain->mining_shield_incr
1224 * get_target_bonus_effects(NULL, pplayer, NULL, pcity, NULL,
1225 ptile, NULL, NULL, NULL, NULL,
1226 EFT_MINING_PCT)
1227 / 100;
1228 }
1229 break;
1230 case O_FOOD:
1231 if (pterrain->irrigation_food_incr != 0) {
1232 prod += pterrain->irrigation_food_incr
1233 * get_target_bonus_effects(NULL, pplayer, NULL, pcity, NULL,
1234 ptile, NULL, NULL, NULL, NULL,
1235 EFT_IRRIGATION_PCT)
1236 / 100;
1237 }
1238 break;
1239 case O_TRADE:
1240 case O_GOLD:
1241 case O_SCIENCE:
1242 case O_LUXURY:
1243 case O_LAST:
1244 break;
1245 }
1246
1247 prod += tile_roads_output_incr(ptile, otype);
1248 prod += (prod * tile_roads_output_bonus(ptile, otype) / 100);
1249
1250 prod += get_tile_output_bonus(pcity, ptile, output, EFT_OUTPUT_ADD_TILE);
1251 if (prod > 0) {
1252 int penalty_limit = get_tile_output_bonus(pcity, ptile, output,
1253 EFT_OUTPUT_PENALTY_TILE);
1254
1255 if (is_celebrating) {
1256 prod += get_tile_output_bonus(pcity, ptile, output,
1257 EFT_OUTPUT_INC_TILE_CELEBRATE);
1258 penalty_limit = 0; /* no penalty if celebrating */
1259 }
1260 prod += get_tile_output_bonus(pcity, ptile, output,
1261 EFT_OUTPUT_INC_TILE);
1262 prod += (prod
1263 * get_tile_output_bonus(pcity, ptile, output,
1264 EFT_OUTPUT_PER_TILE))
1265 / 100;
1266 if (!is_celebrating && penalty_limit > 0 && prod > penalty_limit) {
1267 prod--;
1268 }
1269 }
1270
1271 prod -= (prod
1272 * get_tile_output_bonus(pcity, ptile, output,
1273 EFT_OUTPUT_TILE_PUNISH_PCT))
1274 / 100;
1275
1276 if (NULL != pcity && is_city_center(pcity, ptile)) {
1277 prod = MAX(prod, game.info.min_city_center_output[otype]);
1278 }
1279
1280 return prod;
1281 }
1282
1283 /**************************************************************************
1284 Calculate the production output the given tile is capable of producing
1285 for the city. The output type is given by 'otype' (generally O_FOOD,
1286 O_SHIELD, or O_TRADE).
1287
1288 NOTE: As of now, return value does not represent output on end of turn
1289 if city stops celebrating, because the server side tile output cache
1290 uses base_city_celebrating() instead of city_celebrating() on
1291 city_tile_cache_update().
1292 **************************************************************************/
city_tile_output_now(const struct city * pcity,const struct tile * ptile,Output_type_id otype)1293 int city_tile_output_now(const struct city *pcity, const struct tile *ptile,
1294 Output_type_id otype)
1295 {
1296 return city_tile_output(pcity, ptile, city_celebrating(pcity), otype);
1297 }
1298
1299 /****************************************************************************
1300 Returns TRUE when a tile is available to be worked, or the city itself is
1301 currently working the tile (and can continue).
1302
1303 The paramter 'restriction', which is usually client_player(), allow a
1304 player to handle with its real knownledge to guess it the work of this
1305 tile is possible.
1306
1307 This function shouldn't be called directly, but with city_can_work_tile()
1308 (common/city.[ch]) or client_city_can_work_tile() (client/climap.[ch]).
1309 ****************************************************************************/
base_city_can_work_tile(const struct player * restriction,const struct city * pcity,const struct tile * ptile)1310 bool base_city_can_work_tile(const struct player *restriction,
1311 const struct city *pcity,
1312 const struct tile *ptile)
1313 {
1314 struct player *powner = city_owner(pcity);
1315 int city_map_x, city_map_y;
1316
1317 if (NULL == ptile) {
1318 return FALSE;
1319 }
1320
1321 if (!city_base_to_city_map(&city_map_x, &city_map_y, pcity, ptile)) {
1322 return FALSE;
1323 }
1324
1325 if (NULL != restriction
1326 && TILE_UNKNOWN == tile_get_known(ptile, restriction)) {
1327 return FALSE;
1328 }
1329
1330 if (NULL != tile_owner(ptile) && tile_owner(ptile) != powner) {
1331 return FALSE;
1332 }
1333 /* TODO: civ3-like option for borders */
1334
1335 if (NULL != tile_worked(ptile) && tile_worked(ptile) != pcity) {
1336 return FALSE;
1337 }
1338
1339 if (powner == restriction
1340 && TILE_KNOWN_SEEN != tile_get_known(ptile, powner)) {
1341 return FALSE;
1342 }
1343
1344 if (!is_free_worked(pcity, ptile)
1345 && NULL != unit_occupies_tile(ptile, powner)) {
1346 return FALSE;
1347 }
1348
1349 if (get_city_tile_output_bonus(pcity, ptile, NULL, EFT_TILE_WORKABLE) <= 0) {
1350 return FALSE;
1351 }
1352
1353 return TRUE;
1354 }
1355
1356 /**************************************************************************
1357 Returns TRUE when a tile is available to be worked, or the city itself is
1358 currently working the tile (and can continue).
1359
1360 See also client_city_can_work_tile() (client/climap.[ch]).
1361 **************************************************************************/
city_can_work_tile(const struct city * pcity,const struct tile * ptile)1362 bool city_can_work_tile(const struct city *pcity, const struct tile *ptile)
1363 {
1364 return base_city_can_work_tile(city_owner(pcity), pcity, ptile);
1365 }
1366
1367 /****************************************************************************
1368 Returns TRUE if the given unit can build a city at the given map
1369 coordinates.
1370
1371 punit is the founding unit. It may be NULL if a city is built out of the
1372 blue (e.g., through editing).
1373 ****************************************************************************/
city_can_be_built_here(const struct tile * ptile,const struct unit * punit)1374 bool city_can_be_built_here(const struct tile *ptile,
1375 const struct unit *punit)
1376 {
1377 return (CB_OK == city_build_here_test(ptile, punit));
1378 }
1379
1380 /****************************************************************************
1381 Returns CB_OK if the given unit can build a city at the given map
1382 coordinates. Else, returns the reason of the failure.
1383
1384 punit is the founding unit. It may be NULL if a city is built out of the
1385 blue (e.g., through editing).
1386 ****************************************************************************/
city_build_here_test(const struct tile * ptile,const struct unit * punit)1387 enum city_build_result city_build_here_test(const struct tile *ptile,
1388 const struct unit *punit)
1389 {
1390 int citymindist;
1391
1392 if (terrain_has_flag(tile_terrain(ptile), TER_NO_CITIES)) {
1393 /* No cities on this terrain. */
1394 return CB_BAD_CITY_TERRAIN;
1395 }
1396
1397 if (punit && !can_unit_exist_at_tile(punit, ptile)) {
1398 /* We allow land units to build land cities and sea units to build
1399 * ocean cities. Air units can build cities anywhere. */
1400 return CB_BAD_UNIT_TERRAIN;
1401 }
1402
1403 if (punit && tile_owner(ptile) && tile_owner(ptile) != unit_owner(punit)) {
1404 /* Cannot steal borders by settling. This has to be settled by
1405 * force of arms. */
1406 return CB_BAD_BORDERS;
1407 }
1408
1409 /* citymindist minimum is 1, meaning adjacent is okay */
1410 citymindist = game.info.citymindist;
1411 square_iterate(ptile, citymindist - 1, ptile1) {
1412 if (tile_city(ptile1)) {
1413 return CB_NO_MIN_DIST;
1414 }
1415 } square_iterate_end;
1416
1417 return CB_OK;
1418 }
1419
1420 /**************************************************************************
1421 Return TRUE iff this city is its nation's capital. The capital city is
1422 special-cased in a number of ways.
1423 **************************************************************************/
is_capital(const struct city * pcity)1424 bool is_capital(const struct city *pcity)
1425 {
1426 return (get_city_bonus(pcity, EFT_CAPITAL_CITY) > 0);
1427 }
1428
1429 /**************************************************************************
1430 Return TRUE iff this city is governmental center.
1431 **************************************************************************/
is_gov_center(const struct city * pcity)1432 bool is_gov_center(const struct city *pcity)
1433 {
1434 return (get_city_bonus(pcity, EFT_GOV_CENTER) > 0);
1435 }
1436
1437 /**************************************************************************
1438 This can be City Walls, Coastal defense... depending on attacker type.
1439 If attacker type is not given, just any defense effect will do.
1440 **************************************************************************/
city_got_defense_effect(const struct city * pcity,const struct unit_type * attacker)1441 bool city_got_defense_effect(const struct city *pcity,
1442 const struct unit_type *attacker)
1443 {
1444 if (!attacker) {
1445 /* Any defense building will do */
1446 return get_city_bonus(pcity, EFT_DEFEND_BONUS) > 0;
1447 }
1448
1449 return get_unittype_bonus(city_owner(pcity), pcity->tile, attacker,
1450 EFT_DEFEND_BONUS) > 0;
1451 }
1452
1453 /**************************************************************************
1454 Return TRUE iff the city is happy. A happy city will start celebrating
1455 soon.
1456 A city can only be happy if half or more of the population is happy,
1457 none of the population is unhappy or angry, and it has sufficient size.
1458 **************************************************************************/
city_happy(const struct city * pcity)1459 bool city_happy(const struct city *pcity)
1460 {
1461 return (city_size_get(pcity) >= game.info.celebratesize
1462 && pcity->feel[CITIZEN_ANGRY][FEELING_FINAL] == 0
1463 && pcity->feel[CITIZEN_UNHAPPY][FEELING_FINAL] == 0
1464 && pcity->feel[CITIZEN_HAPPY][FEELING_FINAL] >= (city_size_get(pcity) + 1) / 2);
1465 }
1466
1467 /**************************************************************************
1468 Return TRUE iff the city is unhappy. An unhappy city will fall
1469 into disorder soon.
1470 **************************************************************************/
city_unhappy(const struct city * pcity)1471 bool city_unhappy(const struct city *pcity)
1472 {
1473 return (pcity->feel[CITIZEN_HAPPY][FEELING_FINAL]
1474 < pcity->feel[CITIZEN_UNHAPPY][FEELING_FINAL]
1475 + 2 * pcity->feel[CITIZEN_ANGRY][FEELING_FINAL]);
1476 }
1477
1478 /**************************************************************************
1479 Return TRUE if the city was celebrating at the start of the turn,
1480 and it still has sufficient size to be in rapture.
1481 **************************************************************************/
base_city_celebrating(const struct city * pcity)1482 bool base_city_celebrating(const struct city *pcity)
1483 {
1484 return (city_size_get(pcity) >= game.info.celebratesize && pcity->was_happy);
1485 }
1486
1487 /**************************************************************************
1488 cities celebrate only after consecutive happy turns
1489 **************************************************************************/
city_celebrating(const struct city * pcity)1490 bool city_celebrating(const struct city *pcity)
1491 {
1492 return base_city_celebrating(pcity) && city_happy(pcity);
1493 }
1494
1495 /**************************************************************************
1496 Returns whether city is growing by rapture.
1497 **************************************************************************/
city_rapture_grow(const struct city * pcity)1498 bool city_rapture_grow(const struct city *pcity)
1499 {
1500 /* .rapture is checked instead of city_celebrating() because this
1501 function is called after .was_happy was updated. */
1502 return (pcity->rapture > 0 && pcity->surplus[O_FOOD] > 0
1503 && (pcity->rapture % game.info.rapturedelay) == 0
1504 && get_city_bonus(pcity, EFT_RAPTURE_GROW) > 0);
1505 }
1506
1507 /**************************************************************************
1508 Find city with given id from list.
1509 **************************************************************************/
city_list_find_number(struct city_list * This,int id)1510 struct city *city_list_find_number(struct city_list *This, int id)
1511 {
1512 if (id != 0) {
1513 city_list_iterate(This, pcity) {
1514 if (pcity->id == id) {
1515 return pcity;
1516 }
1517 } city_list_iterate_end;
1518 }
1519
1520 return NULL;
1521 }
1522
1523 /**************************************************************************
1524 Find city with given name from list.
1525 **************************************************************************/
city_list_find_name(struct city_list * This,const char * name)1526 struct city *city_list_find_name(struct city_list *This, const char *name)
1527 {
1528 city_list_iterate(This, pcity) {
1529 if (fc_strcasecmp(name, pcity->name) == 0) {
1530 return pcity;
1531 }
1532 } city_list_iterate_end;
1533
1534 return NULL;
1535 }
1536
1537 /**************************************************************************
1538 Comparison function for qsort for city _pointers_, sorting by city name.
1539 Args are really (struct city**), to sort an array of pointers.
1540 (Compare with old_city_name_compare() in game.c, which use city_id's)
1541 **************************************************************************/
city_name_compare(const void * p1,const void * p2)1542 int city_name_compare(const void *p1, const void *p2)
1543 {
1544 return fc_strcasecmp((*(const struct city **) p1)->name,
1545 (*(const struct city **) p2)->name);
1546 }
1547
1548 /****************************************************************************
1549 Returns the city style that has the given (translated) name.
1550 Returns -1 if none match.
1551 ****************************************************************************/
city_style_by_translated_name(const char * s)1552 int city_style_by_translated_name(const char *s)
1553 {
1554 int i;
1555
1556 for (i = 0; i < game.control.styles_count; i++) {
1557 if (0 == strcmp(city_style_name_translation(i), s)) {
1558 return i;
1559 }
1560 }
1561
1562 return -1;
1563 }
1564
1565 /****************************************************************************
1566 Returns the city style that has the given (untranslated) rule name.
1567 Returns -1 if none match.
1568 ****************************************************************************/
city_style_by_rule_name(const char * s)1569 int city_style_by_rule_name(const char *s)
1570 {
1571 const char *qs = Qn_(s);
1572 int i;
1573
1574 for (i = 0; i < game.control.styles_count; i++) {
1575 if (0 == fc_strcasecmp(city_style_rule_name(i), qs)) {
1576 return i;
1577 }
1578 }
1579
1580 return -1;
1581 }
1582
1583 /****************************************************************************
1584 Return the (translated) name of the given city style.
1585 You don't have to free the return pointer.
1586 ****************************************************************************/
city_style_name_translation(const int style)1587 const char *city_style_name_translation(const int style)
1588 {
1589 return name_translation_get(&city_styles[style].name);
1590 }
1591
1592 /****************************************************************************
1593 Return the (untranslated) rule name of the city style.
1594 You don't have to free the return pointer.
1595 ****************************************************************************/
city_style_rule_name(const int style)1596 const char *city_style_rule_name(const int style)
1597 {
1598 return rule_name_get(&city_styles[style].name);
1599 }
1600
1601 /**************************************************************************
1602 Compute and optionally apply the change-production penalty for the given
1603 production change (to target) in the given city (pcity).
1604 Always returns the number of shields which would be in the stock if
1605 the penalty had been applied.
1606
1607 If we switch the "class" of the target sometime after a city has produced
1608 (i.e., not on the turn immediately after), then there's a shield loss.
1609 But only on the first switch that turn. Also, if ever change back to
1610 original improvement class of this turn, restore lost production.
1611 **************************************************************************/
city_change_production_penalty(const struct city * pcity,const struct universal * target)1612 int city_change_production_penalty(const struct city *pcity,
1613 const struct universal *target)
1614 {
1615 int shield_stock_after_adjustment;
1616 enum production_class_type orig_class;
1617 enum production_class_type new_class;
1618 int unpenalized_shields = 0, penalized_shields = 0;
1619
1620 switch (pcity->changed_from.kind) {
1621 case VUT_IMPROVEMENT:
1622 if (is_wonder(pcity->changed_from.value.building)) {
1623 orig_class = PCT_WONDER;
1624 } else {
1625 orig_class = PCT_NORMAL_IMPROVEMENT;
1626 }
1627 break;
1628 case VUT_UTYPE:
1629 orig_class = PCT_UNIT;
1630 break;
1631 default:
1632 orig_class = PCT_LAST;
1633 break;
1634 };
1635
1636 switch (target->kind) {
1637 case VUT_IMPROVEMENT:
1638 if (is_wonder(target->value.building)) {
1639 new_class = PCT_WONDER;
1640 } else {
1641 new_class = PCT_NORMAL_IMPROVEMENT;
1642 }
1643 break;
1644 case VUT_UTYPE:
1645 new_class = PCT_UNIT;
1646 break;
1647 default:
1648 new_class = PCT_LAST;
1649 break;
1650 };
1651
1652 /* Changing production is penalized under certain circumstances. */
1653 if (orig_class == new_class
1654 || orig_class == PCT_LAST) {
1655 /* There's never a penalty for building something of the same class. */
1656 unpenalized_shields = pcity->before_change_shields;
1657 } else if (city_built_last_turn(pcity)) {
1658 /* Surplus shields from the previous production won't be penalized if
1659 * you change production on the very next turn. But you can only use
1660 * up to the city's surplus amount of shields in this way. */
1661 unpenalized_shields = MIN(pcity->last_turns_shield_surplus,
1662 pcity->before_change_shields);
1663 penalized_shields = pcity->before_change_shields - unpenalized_shields;
1664 } else {
1665 /* Penalize 50% of the production. */
1666 penalized_shields = pcity->before_change_shields;
1667 }
1668
1669 /* Do not put penalty on these. It shouldn't matter whether you disband unit
1670 before or after changing production...*/
1671 unpenalized_shields += pcity->disbanded_shields;
1672
1673 /* Caravan shields are penalized (just as if you disbanded the caravan)
1674 * if you're not building a wonder. */
1675 if (new_class == PCT_WONDER) {
1676 unpenalized_shields += pcity->caravan_shields;
1677 } else {
1678 penalized_shields += pcity->caravan_shields;
1679 }
1680
1681 shield_stock_after_adjustment =
1682 unpenalized_shields + penalized_shields / 2;
1683
1684 return shield_stock_after_adjustment;
1685 }
1686
1687 /**************************************************************************
1688 Calculates the turns which are needed to build the requested
1689 improvement in the city. GUI Independent.
1690 **************************************************************************/
city_turns_to_build(const struct city * pcity,const struct universal * target,bool include_shield_stock)1691 int city_turns_to_build(const struct city *pcity,
1692 const struct universal *target,
1693 bool include_shield_stock)
1694 {
1695 int city_shield_surplus = pcity->surplus[O_SHIELD];
1696 int city_shield_stock = include_shield_stock ?
1697 city_change_production_penalty(pcity, target) : 0;
1698 int cost = universal_build_shield_cost(target);
1699
1700 if (target->kind == VUT_IMPROVEMENT
1701 && is_great_wonder(target->value.building)
1702 && !great_wonder_is_available(target->value.building)) {
1703 return FC_INFINITY;
1704 }
1705
1706 if (include_shield_stock && (city_shield_stock >= cost)) {
1707 return 1;
1708 } else if (city_shield_surplus > 0) {
1709 return (cost - city_shield_stock - 1) / city_shield_surplus + 1;
1710 } else {
1711 return FC_INFINITY;
1712 }
1713 }
1714
1715 /**************************************************************************
1716 Calculates the turns which are needed for the city to grow. A value
1717 of FC_INFINITY means the city will never grow. A value of 0 means
1718 city growth is blocked. A negative value of -x means the city will
1719 shrink in x turns. A positive value of x means the city will grow in
1720 x turns.
1721 **************************************************************************/
city_turns_to_grow(const struct city * pcity)1722 int city_turns_to_grow(const struct city *pcity)
1723 {
1724 if (pcity->surplus[O_FOOD] > 0) {
1725 return (city_granary_size(city_size_get(pcity)) - pcity->food_stock +
1726 pcity->surplus[O_FOOD] - 1) / pcity->surplus[O_FOOD];
1727 } else if (pcity->surplus[O_FOOD] < 0) {
1728 /* turns before famine loss */
1729 return -1 + (pcity->food_stock / pcity->surplus[O_FOOD]);
1730 } else {
1731 return FC_INFINITY;
1732 }
1733 }
1734
1735 /****************************************************************************
1736 Return TRUE iff the city can grow to the given size.
1737 ****************************************************************************/
city_can_grow_to(const struct city * pcity,int pop_size)1738 bool city_can_grow_to(const struct city *pcity, int pop_size)
1739 {
1740 return (get_city_bonus(pcity, EFT_SIZE_UNLIMIT) > 0
1741 || pop_size <= get_city_bonus(pcity, EFT_SIZE_ADJ));
1742 }
1743
1744 /**************************************************************************
1745 is there an enemy city on this tile?
1746 **************************************************************************/
is_enemy_city_tile(const struct tile * ptile,const struct player * pplayer)1747 struct city *is_enemy_city_tile(const struct tile *ptile,
1748 const struct player *pplayer)
1749 {
1750 struct city *pcity = tile_city(ptile);
1751
1752 if (pcity && pplayers_at_war(pplayer, city_owner(pcity)))
1753 return pcity;
1754 else
1755 return NULL;
1756 }
1757
1758 /**************************************************************************
1759 is there an friendly city on this tile?
1760 **************************************************************************/
is_allied_city_tile(const struct tile * ptile,const struct player * pplayer)1761 struct city *is_allied_city_tile(const struct tile *ptile,
1762 const struct player *pplayer)
1763 {
1764 struct city *pcity = tile_city(ptile);
1765
1766 if (pcity && pplayers_allied(pplayer, city_owner(pcity)))
1767 return pcity;
1768 else
1769 return NULL;
1770 }
1771
1772 /**************************************************************************
1773 is there an enemy city on this tile?
1774 **************************************************************************/
is_non_attack_city_tile(const struct tile * ptile,const struct player * pplayer)1775 struct city *is_non_attack_city_tile(const struct tile *ptile,
1776 const struct player *pplayer)
1777 {
1778 struct city *pcity = tile_city(ptile);
1779
1780 if (pcity && pplayers_non_attack(pplayer, city_owner(pcity)))
1781 return pcity;
1782 else
1783 return NULL;
1784 }
1785
1786 /**************************************************************************
1787 is there an non_allied city on this tile?
1788 **************************************************************************/
is_non_allied_city_tile(const struct tile * ptile,const struct player * pplayer)1789 struct city *is_non_allied_city_tile(const struct tile *ptile,
1790 const struct player *pplayer)
1791 {
1792 struct city *pcity = tile_city(ptile);
1793
1794 if (pcity && !pplayers_allied(pplayer, city_owner(pcity)))
1795 return pcity;
1796 else
1797 return NULL;
1798 }
1799
1800 /**************************************************************************
1801 Return TRUE if there is a friendly city near to this unit (within 3
1802 steps).
1803 **************************************************************************/
is_unit_near_a_friendly_city(const struct unit * punit)1804 bool is_unit_near_a_friendly_city(const struct unit *punit)
1805 {
1806 return is_friendly_city_near(unit_owner(punit), unit_tile(punit));
1807 }
1808
1809 /**************************************************************************
1810 Return TRUE if there is a friendly city near to this tile (within 3
1811 steps).
1812 **************************************************************************/
is_friendly_city_near(const struct player * owner,const struct tile * ptile)1813 bool is_friendly_city_near(const struct player *owner,
1814 const struct tile *ptile)
1815 {
1816 square_iterate(ptile, 3, ptile1) {
1817 struct city *pcity = tile_city(ptile1);
1818 if (pcity && pplayers_allied(owner, city_owner(pcity))) {
1819 return TRUE;
1820 }
1821 } square_iterate_end;
1822
1823 return FALSE;
1824 }
1825
1826 /**************************************************************************
1827 Return true iff a city exists within a city radius of the given
1828 location. may_be_on_center determines if a city at x,y counts.
1829 **************************************************************************/
city_exists_within_max_city_map(const struct tile * ptile,bool may_be_on_center)1830 bool city_exists_within_max_city_map(const struct tile *ptile,
1831 bool may_be_on_center)
1832 {
1833 city_tile_iterate(CITY_MAP_MAX_RADIUS_SQ, ptile, ptile1) {
1834 if (may_be_on_center || !same_pos(ptile, ptile1)) {
1835 if (tile_city(ptile1)) {
1836 return TRUE;
1837 }
1838 }
1839 } city_tile_iterate_end;
1840
1841 return FALSE;
1842 }
1843
1844 /****************************************************************************
1845 Generalized formula used to calculate granary size.
1846
1847 The AI may not deal well with non-default settings. See food_weighting().
1848 ****************************************************************************/
city_granary_size(int city_size)1849 int city_granary_size(int city_size)
1850 {
1851 int food_inis = game.info.granary_num_inis;
1852 int food_inc = game.info.granary_food_inc;
1853 int base_value;
1854
1855 /* If the city has no citizens, there is no granary. */
1856 if (city_size == 0) {
1857 return 0;
1858 }
1859
1860 /* Granary sizes for the first food_inis citizens are given directly.
1861 * After that we increase the granary size by food_inc per citizen. */
1862 if (city_size > food_inis) {
1863 base_value = game.info.granary_food_ini[food_inis - 1];
1864 base_value += food_inc * (city_size - food_inis);
1865 } else {
1866 base_value = game.info.granary_food_ini[city_size - 1];
1867 }
1868
1869 return MAX(base_value * game.info.foodbox / 100, 1);
1870 }
1871
1872 /****************************************************************************
1873 Give base happiness in any city owned by pplayer.
1874 A positive number is a number of content citizens. A negative number is
1875 a number of angry citizens (a city never starts with both).
1876 ****************************************************************************/
player_base_citizen_happiness(const struct player * pplayer)1877 static int player_base_citizen_happiness(const struct player *pplayer)
1878 {
1879 int cities = city_list_size(pplayer->cities);
1880 int content = get_player_bonus(pplayer, EFT_CITY_UNHAPPY_SIZE);
1881 int basis = get_player_bonus(pplayer, EFT_EMPIRE_SIZE_BASE);
1882 int step = get_player_bonus(pplayer, EFT_EMPIRE_SIZE_STEP);
1883
1884 if (basis + step <= 0) {
1885 /* Value of zero means effect is inactive */
1886 return content;
1887 }
1888
1889 if (cities > basis) {
1890 content--;
1891 if (step != 0) {
1892 /* the first penalty is at (basis + 1) cities;
1893 the next is at (basis + step + 1), _not_ (basis + step) */
1894 content -= (cities - basis - 1) / step;
1895 }
1896 }
1897 return content;
1898 }
1899
1900 /****************************************************************************
1901 Give base number of content citizens in any city owned by pplayer.
1902 ****************************************************************************/
player_content_citizens(const struct player * pplayer)1903 citizens player_content_citizens(const struct player *pplayer)
1904 {
1905 int content = player_base_citizen_happiness(pplayer);
1906
1907 return CLIP(0, content, MAX_CITY_SIZE);
1908 }
1909
1910 /****************************************************************************
1911 Give base number of angry citizens in any city owned by pplayer.
1912 ****************************************************************************/
player_angry_citizens(const struct player * pplayer)1913 citizens player_angry_citizens(const struct player *pplayer)
1914 {
1915 if (!game.info.angrycitizen) {
1916 return 0;
1917 } else {
1918 /* Create angry citizens only if we have a negative number of possible
1919 * content citizens. This can happen when empires grow really big. */
1920 int content = player_base_citizen_happiness(pplayer);
1921
1922 return CLIP(0, -content, MAX_CITY_SIZE);
1923 }
1924 }
1925
1926 /**************************************************************************
1927 Return the factor (in %) by which the city's output should be multiplied.
1928 **************************************************************************/
get_final_city_output_bonus(const struct city * pcity,Output_type_id otype)1929 int get_final_city_output_bonus(const struct city *pcity, Output_type_id otype)
1930 {
1931 struct output_type *output = &output_types[otype];
1932 int bonus1 = 100 + get_city_tile_output_bonus(pcity, NULL, output,
1933 EFT_OUTPUT_BONUS);
1934 int bonus2 = 100 + get_city_tile_output_bonus(pcity, NULL, output,
1935 EFT_OUTPUT_BONUS_2);
1936
1937 return MAX(bonus1 * bonus2 / 100, 0);
1938 }
1939
1940 /**************************************************************************
1941 Return the amount of gold generated by buildings under "tithe" attribute
1942 governments.
1943 **************************************************************************/
get_city_tithes_bonus(const struct city * pcity)1944 int get_city_tithes_bonus(const struct city *pcity)
1945 {
1946 int tithes_bonus = 0;
1947
1948 if (get_city_bonus(pcity, EFT_HAPPINESS_TO_GOLD) <= 0) {
1949 return 0;
1950 }
1951
1952 tithes_bonus += get_city_bonus(pcity, EFT_MAKE_CONTENT);
1953 tithes_bonus += get_city_bonus(pcity, EFT_FORCE_CONTENT);
1954
1955 return tithes_bonus;
1956 }
1957
1958 /**************************************************************************
1959 Add the incomes of a city according to the taxrates (ignore # of
1960 specialists). trade should be in output[O_TRADE].
1961 **************************************************************************/
add_tax_income(const struct player * pplayer,int trade,int * output)1962 void add_tax_income(const struct player *pplayer, int trade, int *output)
1963 {
1964 const int SCIENCE = 0, TAX = 1, LUXURY = 2;
1965 int rates[3], result[3];
1966
1967 if (game.info.changable_tax) {
1968 rates[SCIENCE] = pplayer->economic.science;
1969 rates[LUXURY] = pplayer->economic.luxury;
1970 rates[TAX] = 100 - rates[SCIENCE] - rates[LUXURY];
1971 } else {
1972 rates[SCIENCE] = game.info.forced_science;
1973 rates[LUXURY] = game.info.forced_luxury;
1974 rates[TAX] = game.info.forced_gold;
1975 }
1976
1977 /* ANARCHY */
1978 if (government_of_player(pplayer) == game.government_during_revolution) {
1979 rates[SCIENCE] = 0;
1980 rates[LUXURY] = 100;
1981 rates[TAX] = 0;
1982 }
1983
1984 distribute(trade, 3, rates, result);
1985
1986 output[O_SCIENCE] += result[SCIENCE];
1987 output[O_GOLD] += result[TAX];
1988 output[O_LUXURY] += result[LUXURY];
1989 }
1990
1991 /**************************************************************************
1992 Return TRUE if the city built something last turn (meaning production
1993 was completed between last turn and this).
1994 **************************************************************************/
city_built_last_turn(const struct city * pcity)1995 bool city_built_last_turn(const struct city *pcity)
1996 {
1997 return pcity->turn_last_built + 1 >= game.info.turn;
1998 }
1999
2000 /****************************************************************************
2001 Calculate output (food, trade and shields) generated by the worked tiles
2002 of a city. This will completely overwrite the output[] array.
2003
2004 'workers_map' is an boolean array which defines the placement of the
2005 workers within the city map. It uses the tile index and its size is
2006 defined by city_map_tiles_from_city(_pcity). See also cm_state_init().
2007 ****************************************************************************/
get_worked_tile_output(const struct city * pcity,int * output,bool * workers_map)2008 static inline void get_worked_tile_output(const struct city *pcity,
2009 int *output, bool *workers_map)
2010 {
2011 bool is_worked;
2012 #ifdef CITY_DEBUGGING
2013 bool is_celebrating = base_city_celebrating(pcity);
2014 #endif
2015 struct tile *pcenter = city_tile(pcity);
2016
2017 memset(output, 0, O_LAST * sizeof(*output));
2018
2019 city_tile_iterate_index(city_map_radius_sq_get(pcity), pcenter, ptile,
2020 city_tile_index) {
2021 if (workers_map == NULL) {
2022 struct city *pwork = tile_worked(ptile);
2023
2024 is_worked = (NULL != pwork && pwork == pcity);
2025 } else {
2026 is_worked = workers_map[city_tile_index];
2027 }
2028
2029 if (is_worked) {
2030 output_type_iterate(o) {
2031 #ifdef CITY_DEBUGGING
2032 /* This assertion never fails, but it's so slow that we disable
2033 * it by default. */
2034 fc_assert(city_tile_cache_get_output(pcity, city_tile_index, o)
2035 == city_tile_output(pcity, ptile, is_celebrating, o));
2036 #endif
2037 output[o] += city_tile_cache_get_output(pcity, city_tile_index, o);
2038 } output_type_iterate_end;
2039 }
2040 } city_tile_iterate_index_end;
2041 }
2042
2043 /****************************************************************************
2044 Calculate output (gold, science, and luxury) generated by the specialists
2045 of a city. The output[] array is not cleared but is just added to.
2046 ****************************************************************************/
add_specialist_output(const struct city * pcity,int * output)2047 void add_specialist_output(const struct city *pcity, int *output)
2048 {
2049 specialist_type_iterate(sp) {
2050 int count = pcity->specialists[sp];
2051
2052 output_type_iterate(stat_index) {
2053 int amount = get_specialist_output(pcity, sp, stat_index);
2054
2055 output[stat_index] += count * amount;
2056 } output_type_iterate_end;
2057 } specialist_type_iterate_end;
2058 }
2059
2060 /****************************************************************************
2061 This function sets all the values in the pcity->bonus[] array.
2062 Called near the beginning of city_refresh_from_main_map().
2063
2064 It doesn't depend on anything else in the refresh and doesn't change
2065 as workers are moved around, but does change when buildings are built,
2066 etc.
2067 ****************************************************************************/
set_city_bonuses(struct city * pcity)2068 static inline void set_city_bonuses(struct city *pcity)
2069 {
2070 output_type_iterate(o) {
2071 pcity->bonus[o] = get_final_city_output_bonus(pcity, o);
2072 } output_type_iterate_end;
2073 }
2074
2075 /****************************************************************************
2076 This function sets the cache for the tile outputs, the pcity->tile_cache[]
2077 array. It is called near the beginning of city_refresh_from_main_map().
2078
2079 It doesn't depend on anything else in the refresh and doesn't change
2080 as workers are moved around, but does change when buildings are built,
2081 etc.
2082
2083 TODO: use the cached values elsewhere in the code!
2084 ****************************************************************************/
city_tile_cache_update(struct city * pcity)2085 static inline void city_tile_cache_update(struct city *pcity)
2086 {
2087 bool is_celebrating = base_city_celebrating(pcity);
2088 int radius_sq = city_map_radius_sq_get(pcity);
2089
2090 /* initialize tile_cache if needed */
2091 if (pcity->tile_cache == NULL || pcity->tile_cache_radius_sq == -1
2092 || pcity->tile_cache_radius_sq != radius_sq) {
2093 pcity->tile_cache = fc_realloc(pcity->tile_cache,
2094 city_map_tiles(radius_sq)
2095 * sizeof(*(pcity->tile_cache)));
2096 pcity->tile_cache_radius_sq = radius_sq;
2097 }
2098
2099 /* Any unreal tiles are skipped - these values should have been memset
2100 * to 0 when the city was created. */
2101 city_tile_iterate_index(radius_sq, pcity->tile, ptile, city_tile_index) {
2102 output_type_iterate(o) {
2103 (pcity->tile_cache[city_tile_index]).output[o]
2104 = city_tile_output(pcity, ptile, is_celebrating, o);
2105 } output_type_iterate_end;
2106 } city_tile_iterate_index_end;
2107 }
2108
2109 /****************************************************************************
2110 This function returns the output of 'o' for the city tile 'city_tile_index'
2111 of 'pcity'.
2112 ****************************************************************************/
city_tile_cache_get_output(const struct city * pcity,int city_tile_index,enum output_type_id o)2113 static inline int city_tile_cache_get_output(const struct city *pcity,
2114 int city_tile_index,
2115 enum output_type_id o)
2116 {
2117 fc_assert_ret_val(pcity->tile_cache_radius_sq
2118 == city_map_radius_sq_get(pcity), 0);
2119 fc_assert_ret_val(city_tile_index < city_map_tiles_from_city(pcity), 0);
2120
2121 return (pcity->tile_cache[city_tile_index]).output[o];
2122 }
2123
2124 /**************************************************************************
2125 Set the final surplus[] array from the prod[] and usage[] values.
2126 **************************************************************************/
set_surpluses(struct city * pcity)2127 static void set_surpluses(struct city *pcity)
2128 {
2129 output_type_iterate(o) {
2130 pcity->surplus[o] = pcity->prod[o] - pcity->usage[o];
2131 } output_type_iterate_end;
2132 }
2133
2134 /**************************************************************************
2135 Copy the happyness array in the city to index i from index i-1.
2136 **************************************************************************/
happy_copy(struct city * pcity,enum citizen_feeling i)2137 static void happy_copy(struct city *pcity, enum citizen_feeling i)
2138 {
2139 int c = 0;
2140
2141 for (; c < CITIZEN_LAST; c++) {
2142 pcity->feel[c][i] = pcity->feel[c][i - 1];
2143 }
2144 }
2145
2146 /**************************************************************************
2147 Create content, unhappy and angry citizens.
2148 **************************************************************************/
citizen_base_mood(struct city * pcity)2149 static void citizen_base_mood(struct city *pcity)
2150 {
2151 struct player *pplayer = city_owner(pcity);
2152 citizens *happy = &pcity->feel[CITIZEN_HAPPY][FEELING_BASE];
2153 citizens *content = &pcity->feel[CITIZEN_CONTENT][FEELING_BASE];
2154 citizens *unhappy = &pcity->feel[CITIZEN_UNHAPPY][FEELING_BASE];
2155 citizens *angry = &pcity->feel[CITIZEN_ANGRY][FEELING_BASE];
2156 citizens size = city_size_get(pcity);
2157 citizens spes = city_specialists(pcity);
2158
2159 /* This is the number of citizens that may start out content, depending
2160 * on empire size and game's city unhappysize. This may be bigger than
2161 * the size of the city, since this is a potential. */
2162 citizens base_content = player_content_citizens(pplayer);
2163 /* Similarly, this is the potential number of angry citizens. */
2164 citizens base_angry = player_angry_citizens(pplayer);
2165
2166 /* Create content citizens. Take specialists from their ranks. */
2167 *content = MAX(0, MIN(size, base_content) - spes);
2168
2169 /* Create angry citizens. Specialists never become angry. */
2170 fc_assert_action(base_content == 0 || base_angry == 0, *content = 0);
2171 *angry = MIN(base_angry, size - spes);
2172
2173 /* Create unhappy citizens. In the beginning, all who are not content,
2174 * specialists or angry are unhappy. This is changed by luxuries and
2175 * buildings later. */
2176 *unhappy = (size - spes - *content - *angry);
2177
2178 /* No one is born happy. */
2179 *happy = 0;
2180 }
2181
2182 /**************************************************************************
2183 Make people happy:
2184 * angry citizen are eliminated first
2185 * then content are made happy, then unhappy content, etc.
2186 * each conversions costs 2 or 4 luxuries.
2187 **************************************************************************/
citizen_luxury_happy(struct city * pcity,int * luxuries)2188 static inline void citizen_luxury_happy(struct city *pcity, int *luxuries)
2189 {
2190 citizens *happy = &pcity->feel[CITIZEN_HAPPY][FEELING_LUXURY];
2191 citizens *content = &pcity->feel[CITIZEN_CONTENT][FEELING_LUXURY];
2192 citizens *unhappy = &pcity->feel[CITIZEN_UNHAPPY][FEELING_LUXURY];
2193 citizens *angry = &pcity->feel[CITIZEN_ANGRY][FEELING_LUXURY];
2194
2195 while (*luxuries >= game.info.happy_cost && *angry > 0) {
2196 /* Upgrade angry to unhappy: costs HAPPY_COST each. */
2197 (*angry)--;
2198 (*unhappy)++;
2199 *luxuries -= game.info.happy_cost;
2200 }
2201 while (*luxuries >= game.info.happy_cost && *content > 0) {
2202 /* Upgrade content to happy: costs HAPPY_COST each. */
2203 (*content)--;
2204 (*happy)++;
2205 *luxuries -= game.info.happy_cost;
2206 }
2207 while (*luxuries >= 2 * game.info.happy_cost && *unhappy > 0) {
2208 /* Upgrade unhappy to happy. Note this is a 2-level upgrade with
2209 * double the cost. */
2210 (*unhappy)--;
2211 (*happy)++;
2212 *luxuries -= 2 * game.info.happy_cost;
2213 }
2214 if (*luxuries >= game.info.happy_cost && *unhappy > 0) {
2215 /* Upgrade unhappy to content: costs HAPPY_COST each. */
2216 (*unhappy)--;
2217 (*content)++;
2218 *luxuries -= game.info.happy_cost;
2219 }
2220 }
2221
2222 /**************************************************************************
2223 Make citizens happy due to luxury.
2224 **************************************************************************/
citizen_happy_luxury(struct city * pcity)2225 static inline void citizen_happy_luxury(struct city *pcity)
2226 {
2227 int x = pcity->prod[O_LUXURY];
2228
2229 citizen_luxury_happy(pcity, &x);
2230 }
2231
2232 /**************************************************************************
2233 Make citizens content due to city improvements.
2234 **************************************************************************/
citizen_content_buildings(struct city * pcity)2235 static inline void citizen_content_buildings(struct city *pcity)
2236 {
2237 citizens *content = &pcity->feel[CITIZEN_CONTENT][FEELING_EFFECT];
2238 citizens *unhappy = &pcity->feel[CITIZEN_UNHAPPY][FEELING_EFFECT];
2239 citizens *angry = &pcity->feel[CITIZEN_ANGRY][FEELING_EFFECT];
2240 int faces = get_city_bonus(pcity, EFT_MAKE_CONTENT);
2241
2242 /* make people content (but not happy):
2243 get rid of angry first, then make unhappy content. */
2244 while (faces > 0 && *angry > 0) {
2245 (*angry)--;
2246 (*unhappy)++;
2247 faces--;
2248 }
2249 while (faces > 0 && *unhappy > 0) {
2250 (*unhappy)--;
2251 (*content)++;
2252 faces--;
2253 }
2254 }
2255
2256 /**************************************************************************
2257 Apply effects of citizen nationality to happiness
2258 **************************************************************************/
citizen_happiness_nationality(struct city * pcity)2259 static inline void citizen_happiness_nationality(struct city *pcity)
2260 {
2261 citizens *happy = &pcity->feel[CITIZEN_HAPPY][FEELING_NATIONALITY];
2262 citizens *content = &pcity->feel[CITIZEN_CONTENT][FEELING_NATIONALITY];
2263 citizens *unhappy = &pcity->feel[CITIZEN_UNHAPPY][FEELING_NATIONALITY];
2264
2265 if (game.info.citizen_nationality) {
2266 int pct = get_city_bonus(pcity, EFT_ENEMY_CITIZEN_UNHAPPY_PCT);
2267
2268 if (pct > 0) {
2269 int enemies = 0;
2270 int unhappy_inc;
2271 struct player *owner = city_owner(pcity);
2272
2273 citizens_foreign_iterate(pcity, pslot, nationality) {
2274 if (pplayers_at_war(owner, player_slot_get_player(pslot))) {
2275 enemies += nationality;
2276 }
2277 } citizens_foreign_iterate_end;
2278
2279 unhappy_inc = enemies * pct / 100;
2280
2281 /* First make content => unhappy, then happy => unhappy,
2282 * then happy => content. No-one becomes angry. */
2283 while (unhappy_inc > 0 && *content > 0) {
2284 (*content)--;
2285 (*unhappy)++;
2286 unhappy_inc--;
2287 }
2288 while (unhappy_inc > 1 && *happy > 0) {
2289 (*happy)--;
2290 (*unhappy)++;
2291 unhappy_inc -= 2;
2292 }
2293 while (unhappy_inc > 0 && *happy > 0) {
2294 (*happy)--;
2295 (*content)++;
2296 unhappy_inc--;
2297 }
2298 }
2299 }
2300 }
2301
2302 /**************************************************************************
2303 Make citizens happy/unhappy due to units.
2304
2305 This function requires that pcity->martial_law and
2306 pcity->unit_happy_cost have already been set in city_support().
2307 **************************************************************************/
citizen_happy_units(struct city * pcity)2308 static inline void citizen_happy_units(struct city *pcity)
2309 {
2310 citizens *happy = &pcity->feel[CITIZEN_HAPPY][FEELING_MARTIAL];
2311 citizens *content = &pcity->feel[CITIZEN_CONTENT][FEELING_MARTIAL];
2312 citizens *unhappy = &pcity->feel[CITIZEN_UNHAPPY][FEELING_MARTIAL];
2313 citizens *angry = &pcity->feel[CITIZEN_ANGRY][FEELING_MARTIAL];
2314 citizens amt = pcity->martial_law;
2315
2316 /* Pacify discontent citizens through martial law. First convert
2317 * angry => unhappy, then unhappy => content. */
2318 while (amt > 0 && *angry > 0) {
2319 (*angry)--;
2320 (*unhappy)++;
2321 amt--;
2322 }
2323 while (amt > 0 && *unhappy > 0) {
2324 (*unhappy)--;
2325 (*content)++;
2326 amt--;
2327 }
2328
2329 /* Now make citizens unhappier because of military units away from home.
2330 * First make content => unhappy, then happy => unhappy,
2331 * then happy => content. */
2332 amt = pcity->unit_happy_upkeep;
2333 while (amt > 0 && *content > 0) {
2334 (*content)--;
2335 (*unhappy)++;
2336 amt--;
2337 }
2338 while (amt > 1 && *happy > 0) {
2339 (*happy)--;
2340 (*unhappy)++;
2341 amt -= 2;
2342 }
2343 while (amt > 0 && *happy > 0) {
2344 (*happy)--;
2345 (*content)++;
2346 amt--;
2347 }
2348 /* Any remaining unhappiness is lost since angry citizens aren't created
2349 * here. */
2350 /* FIXME: Why not? - Per */
2351 }
2352
2353 /**************************************************************************
2354 Make citizens happy due to wonders.
2355 **************************************************************************/
citizen_happy_wonders(struct city * pcity)2356 static inline void citizen_happy_wonders(struct city *pcity)
2357 {
2358 citizens *happy = &pcity->feel[CITIZEN_HAPPY][FEELING_FINAL];
2359 citizens *content = &pcity->feel[CITIZEN_CONTENT][FEELING_FINAL];
2360 citizens *unhappy = &pcity->feel[CITIZEN_UNHAPPY][FEELING_FINAL];
2361 citizens *angry = &pcity->feel[CITIZEN_ANGRY][FEELING_FINAL];
2362 int bonus = get_city_bonus(pcity, EFT_MAKE_HAPPY);
2363
2364 /* First create happy citizens from content, then from unhappy
2365 * citizens; we cannot help angry citizens here. */
2366 while (bonus > 0 && *content > 0) {
2367 (*content)--;
2368 (*happy)++;
2369 bonus--;
2370 }
2371 while (bonus > 1 && *unhappy > 0) {
2372 (*unhappy)--;
2373 (*happy)++;
2374 bonus -= 2;
2375 }
2376 /* The rest falls through and lets unhappy people become content. */
2377
2378 if (get_city_bonus(pcity, EFT_NO_UNHAPPY) > 0) {
2379 *content += *unhappy + *angry;
2380 *unhappy = 0;
2381 *angry = 0;
2382 return;
2383 }
2384
2385 bonus += get_city_bonus(pcity, EFT_FORCE_CONTENT);
2386
2387 /* get rid of angry first, then make unhappy content */
2388 while (bonus > 0 && *angry > 0) {
2389 (*angry)--;
2390 (*unhappy)++;
2391 bonus--;
2392 }
2393 while (bonus > 0 && *unhappy > 0) {
2394 (*unhappy)--;
2395 (*content)++;
2396 bonus--;
2397 }
2398 }
2399
2400 /**************************************************************************
2401 Set food, tax, science and shields production to zero if city is in
2402 disorder.
2403 **************************************************************************/
unhappy_city_check(struct city * pcity)2404 static inline void unhappy_city_check(struct city *pcity)
2405 {
2406 if (city_unhappy(pcity)) {
2407 output_type_iterate(o) {
2408 switch (output_types[o].unhappy_penalty) {
2409 case UNHAPPY_PENALTY_NONE:
2410 pcity->unhappy_penalty[o] = 0;
2411 break;
2412 case UNHAPPY_PENALTY_SURPLUS:
2413 pcity->unhappy_penalty[o] = MAX(pcity->prod[o] - pcity->usage[o], 0);
2414 break;
2415 case UNHAPPY_PENALTY_ALL_PRODUCTION:
2416 pcity->unhappy_penalty[o] = pcity->prod[o];
2417 break;
2418 }
2419
2420 pcity->prod[o] -= pcity->unhappy_penalty[o];
2421 } output_type_iterate_end;
2422 } else {
2423 memset(pcity->unhappy_penalty, 0,
2424 O_LAST * sizeof(*pcity->unhappy_penalty));
2425 }
2426 }
2427
2428 /**************************************************************************
2429 Calculate the pollution from production and population in the city.
2430 **************************************************************************/
city_pollution_types(const struct city * pcity,int shield_total,int * pollu_prod,int * pollu_pop,int * pollu_mod)2431 int city_pollution_types(const struct city *pcity, int shield_total,
2432 int *pollu_prod, int *pollu_pop, int *pollu_mod)
2433 {
2434 int prod, pop, mod;
2435
2436 /* Add one one pollution per shield, multipled by the bonus. */
2437 prod = 100 + get_city_bonus(pcity, EFT_POLLU_PROD_PCT);
2438 prod = shield_total * MAX(prod, 0) / 100;
2439
2440 /* Add one pollution per citizen for baseline combined bonus (100%). */
2441 pop = (100 + get_city_bonus(pcity, EFT_POLLU_POP_PCT))
2442 * (100 + get_city_bonus(pcity, EFT_POLLU_POP_PCT_2))
2443 / 100;
2444 pop = (city_size_get(pcity) * MAX(pop, 0)) / 100;
2445
2446 /* Then there is base pollution (usually a negative number). */
2447 mod = game.info.base_pollution;
2448
2449 if (pollu_prod) {
2450 *pollu_prod = prod;
2451 }
2452 if (pollu_pop) {
2453 *pollu_pop = pop;
2454 }
2455 if (pollu_mod) {
2456 *pollu_mod = mod;
2457 }
2458 return MAX(prod + pop + mod, 0);
2459 }
2460
2461 /**************************************************************************
2462 Calculate pollution for the city. The shield_total must be passed in
2463 (most callers will want to pass pcity->shield_prod).
2464 **************************************************************************/
city_pollution(const struct city * pcity,int shield_total)2465 int city_pollution(const struct city *pcity, int shield_total)
2466 {
2467 return city_pollution_types(pcity, shield_total, NULL, NULL, NULL);
2468 }
2469
2470 /**************************************************************************
2471 Gets whether cities that pcity trades with had the plague. If so, it
2472 returns the health penalty in tenth of percent which depends on the size
2473 of both cities. The health penalty is given as the product of the ruleset
2474 option 'game.info.illness_trade_infection' (in percent) and the square
2475 root of the product of the size of both cities.
2476 *************************************************************************/
get_trade_illness(const struct city * pcity)2477 static int get_trade_illness(const struct city *pcity)
2478 {
2479 float illness_trade = 0.0;
2480
2481 trade_routes_iterate(pcity, trade_city) {
2482 if (trade_city->turn_plague != -1
2483 && game.info.turn - trade_city->turn_plague < 5) {
2484 illness_trade += (float)game.info.illness_trade_infection
2485 * sqrt(1.0 * city_size_get(pcity)
2486 * city_size_get(trade_city)) / 100.0;
2487 }
2488 } trade_routes_iterate_end;
2489
2490 return (int)illness_trade;
2491 }
2492
2493 /**************************************************************************
2494 Get any effects regarding health from the buildings of the city. The
2495 effect defines the reduction of the possibility of an illness in percent.
2496 **************************************************************************/
get_city_health(const struct city * pcity)2497 static int get_city_health(const struct city *pcity)
2498 {
2499 return get_city_bonus(pcity, EFT_HEALTH_PCT);
2500 }
2501
2502 /**************************************************************************
2503 Calculate city's illness in tenth of percent:
2504
2505 base illness (the maximum value for illness in percent is given by
2506 'game.info.illness_base_factor')
2507 + trade illness (see get_trade_illness())
2508 + pollution illness (the pollution in the city times
2509 'game.info.illness_pollution_factor')
2510
2511 The illness is reduced by the percentage given by the health effect.
2512 Illness cannot exceed 999 (= 99.9%), or be less then 0
2513 *************************************************************************/
city_illness_calc(const struct city * pcity,int * ill_base,int * ill_size,int * ill_trade,int * ill_pollution)2514 int city_illness_calc(const struct city *pcity, int *ill_base,
2515 int *ill_size, int *ill_trade, int *ill_pollution)
2516 {
2517 int illness_size = 0, illness_trade = 0, illness_pollution = 0;
2518 int illness_base, illness_percent;
2519
2520 if (game.info.illness_on
2521 && city_size_get(pcity) > game.info.illness_min_size) {
2522 /* offset the city size by game.info.illness_min_size */
2523 int use_size = city_size_get(pcity) - game.info.illness_min_size;
2524
2525 illness_size = (int)((1.0 - exp(- (float)use_size / 10.0))
2526 * 10.0 * game.info.illness_base_factor);
2527 if (is_server()) {
2528 /* on the server we recalculate the illness due to trade as we have
2529 * all informations */
2530 illness_trade = get_trade_illness(pcity);
2531 } else {
2532 /* on the client we have to rely on the value saved within the city
2533 * struct */
2534 illness_trade = pcity->illness_trade;
2535 }
2536
2537 illness_pollution = pcity->pollution
2538 * game.info.illness_pollution_factor / 100;
2539 }
2540
2541 illness_base = illness_size + illness_trade + illness_pollution;
2542 illness_percent = 100 - get_city_health(pcity);
2543
2544 /* returning other data */
2545 if (ill_size) {
2546 *ill_size = illness_size;
2547 }
2548
2549 if (ill_trade) {
2550 *ill_trade = illness_trade;
2551 }
2552
2553 if (ill_pollution) {
2554 *ill_pollution = illness_pollution;
2555 }
2556
2557 if (ill_base) {
2558 *ill_base = illness_base;
2559 }
2560
2561 return CLIP(0, illness_base * illness_percent / 100 , 999);
2562 }
2563
2564 /****************************************************************************
2565 Returns whether city had a plague outbreak this turn.
2566 ****************************************************************************/
city_had_recent_plague(const struct city * pcity)2567 bool city_had_recent_plague(const struct city *pcity)
2568 {
2569 /* Correctly handles special case turn_plague == -1 (never) */
2570 return (pcity->turn_plague == game.info.turn);
2571 }
2572
2573 /****************************************************************************
2574 The maximum number of units a city can build per turn.
2575 ****************************************************************************/
city_build_slots(const struct city * pcity)2576 int city_build_slots(const struct city *pcity)
2577 {
2578 return get_city_bonus(pcity, EFT_CITY_BUILD_SLOTS);
2579 }
2580
2581 /****************************************************************************
2582 A city's maximum airlift capacity.
2583 (Note, this still returns a finite number even if airliftingstyle allows
2584 unlimited airlifts)
2585 ****************************************************************************/
city_airlift_max(const struct city * pcity)2586 int city_airlift_max(const struct city *pcity)
2587 {
2588 return get_city_bonus(pcity, EFT_AIRLIFT);
2589 }
2590
2591 /**************************************************************************
2592 Set food, trade and shields production in a city.
2593
2594 This initializes the prod[] and waste[] arrays. It assumes that
2595 the bonus[] and citizen_base[] arrays are alread built.
2596 **************************************************************************/
set_city_production(struct city * pcity)2597 inline void set_city_production(struct city *pcity)
2598 {
2599 int i;
2600
2601 /* Calculate city production!
2602 *
2603 * This is a rather complicated process if we allow rules to become
2604 * more generalized. We can assume that there are no recursive dependency
2605 * loops, but there are some dependencies that do not follow strict
2606 * ordering. For instance corruption must be calculated before
2607 * trade taxes can be counted up, which must occur before the science bonus
2608 * is added on. But the calculation of corruption must include the
2609 * trade bonus. To do this without excessive special casing means that in
2610 * this case the bonuses are multiplied on twice (but only saved the second
2611 * time).
2612 */
2613
2614 output_type_iterate(o) {
2615 pcity->prod[o] = pcity->citizen_base[o];
2616 } output_type_iterate_end;
2617
2618 /* Add on special extra incomes: trade routes and tithes. */
2619 for (i = 0; i < MAX_TRADE_ROUTES; i++) {
2620 struct city *tcity = game_city_by_number(pcity->trade[i]);
2621
2622 /* Partner city may have not yet been sent to the client, or
2623 * there's just a placeholder city with a placeholder owner
2624 * created for some tile->worked. */
2625 if (tcity != NULL && city_owner(tcity)->slot != NULL) {
2626 bool can_trade = can_cities_trade(pcity, tcity);
2627
2628 if (!can_trade) {
2629 enum trade_route_type type = cities_trade_route_type(pcity, tcity);
2630 struct trade_route_settings *settings = trade_route_settings_by_type(type);
2631
2632 if (settings->cancelling == TRI_ACTIVE) {
2633 can_trade = TRUE;
2634 }
2635 }
2636
2637 if (can_trade) {
2638 pcity->trade_value[i] =
2639 trade_between_cities(pcity, game_city_by_number(pcity->trade[i]));
2640 pcity->prod[O_TRADE] += pcity->trade_value[i]
2641 * (100 + get_city_bonus(pcity, EFT_TRADEROUTE_PCT)) / 100;
2642 } else {
2643 pcity->trade_value[i] = 0;
2644 }
2645 }
2646 }
2647 pcity->prod[O_GOLD] += get_city_tithes_bonus(pcity);
2648
2649 /* Account for waste. Note that waste is calculated before tax income is
2650 * calculated, so if you had "science waste" it would not include taxed
2651 * science. However waste is calculated after the bonuses are multiplied
2652 * on, so shield waste will include shield bonuses. */
2653 output_type_iterate(o) {
2654 pcity->waste[o] = city_waste(pcity, o,
2655 pcity->prod[o] * pcity->bonus[o] / 100,
2656 NULL);
2657 } output_type_iterate_end;
2658
2659 /* Convert trade into science/luxury/gold, and add this on to whatever
2660 * science/luxury/gold is already there. */
2661 add_tax_income(city_owner(pcity),
2662 pcity->prod[O_TRADE] * pcity->bonus[O_TRADE] / 100
2663 - pcity->waste[O_TRADE] - pcity->usage[O_TRADE],
2664 pcity->prod);
2665
2666 /* Add on effect bonuses and waste. Note that the waste calculation
2667 * (above) already includes the bonus multiplier. */
2668 output_type_iterate(o) {
2669 pcity->prod[o] = pcity->prod[o] * pcity->bonus[o] / 100;
2670 pcity->prod[o] -= pcity->waste[o];
2671 } output_type_iterate_end;
2672 }
2673
2674 /**************************************************************************
2675 Query unhappiness caused by a given unit.
2676 **************************************************************************/
city_unit_unhappiness(struct unit * punit,int * free_unhappy)2677 int city_unit_unhappiness(struct unit *punit, int *free_unhappy)
2678 {
2679 struct city *pcity;
2680 struct unit_type *ut;
2681 struct player *plr;
2682 int happy_cost;
2683
2684 if (!punit || !free_unhappy) {
2685 return 0;
2686 }
2687
2688 pcity = game_city_by_number(punit->homecity);
2689 if (pcity == NULL) {
2690 return 0;
2691 }
2692
2693 ut = unit_type_get(punit);
2694 plr = unit_owner(punit);
2695 happy_cost = utype_happy_cost(ut, plr);
2696
2697 if (happy_cost <= 0) {
2698 return 0;
2699 }
2700
2701 fc_assert_ret_val(0 <= *free_unhappy, 0);
2702
2703 if (!unit_being_aggressive(punit) && !is_field_unit(punit)) {
2704 return 0;
2705 }
2706
2707 happy_cost -= get_city_bonus(pcity, EFT_MAKE_CONTENT_MIL_PER);
2708 if (happy_cost <= 0) {
2709 return 0;
2710 }
2711
2712 if (*free_unhappy >= happy_cost) {
2713 *free_unhappy -= happy_cost;
2714 return 0;
2715 } else {
2716 happy_cost -= *free_unhappy;
2717 *free_unhappy = 0;
2718 }
2719
2720 return happy_cost;
2721 }
2722
2723 /**************************************************************************
2724 Calculate upkeep costs. This builds the pcity->usage[] array as well
2725 as setting some happiness values.
2726 **************************************************************************/
city_support(struct city * pcity)2727 static inline void city_support(struct city *pcity)
2728 {
2729 int free_unhappy, martial_law_each;
2730
2731 /* Clear all usage values. */
2732 memset(pcity->usage, 0, O_LAST * sizeof(*pcity->usage));
2733 pcity->martial_law = 0;
2734 pcity->unit_happy_upkeep = 0;
2735
2736 /* Building and unit gold upkeep depends on the setting
2737 * 'game.info.gold_upkeep_style':
2738 * GOLD_UPKEEP_CITY: The upkeep for buildings and units is paid by the
2739 * city.
2740 * GOLD_UPKEEP_MIXED: The upkeep for buildings is paid by the city.
2741 * The upkeep for units is paid by the nation.
2742 * GOLD_UPKEEP_NATION: The upkeep for buildings and units is paid by the
2743 * nation. */
2744 fc_assert_msg(gold_upkeep_style_is_valid(game.info.gold_upkeep_style),
2745 "Invalid gold_upkeep_style %d", game.info.gold_upkeep_style);
2746 switch (game.info.gold_upkeep_style) {
2747 case GOLD_UPKEEP_CITY:
2748 pcity->usage[O_GOLD] += city_total_unit_gold_upkeep(pcity);
2749 fc__fallthrough; /* No break */
2750 case GOLD_UPKEEP_MIXED:
2751 pcity->usage[O_GOLD] += city_total_impr_gold_upkeep(pcity);
2752 break;
2753 case GOLD_UPKEEP_NATION:
2754 /* nothing */
2755 break;
2756 }
2757 /* Food consumption by citizens. */
2758 pcity->usage[O_FOOD] += game.info.food_cost * city_size_get(pcity);
2759
2760 /* military units in this city (need _not_ be home city) can make
2761 * unhappy citizens content */
2762 martial_law_each = get_city_bonus(pcity, EFT_MARTIAL_LAW_EACH);
2763 if (martial_law_each > 0) {
2764 int count = 0;
2765 int martial_law_max = get_city_bonus(pcity, EFT_MARTIAL_LAW_MAX);
2766
2767 unit_list_iterate(pcity->tile->units, punit) {
2768 if ((count < martial_law_max || martial_law_max == 0)
2769 && is_military_unit(punit)
2770 && unit_owner(punit) == city_owner(pcity)) {
2771 count++;
2772 }
2773 } unit_list_iterate_end;
2774
2775 pcity->martial_law = CLIP(0, count * martial_law_each, MAX_CITY_SIZE);
2776 }
2777
2778 free_unhappy = get_city_bonus(pcity, EFT_MAKE_CONTENT_MIL);
2779 unit_list_iterate(pcity->units_supported, punit) {
2780 pcity->unit_happy_upkeep += city_unit_unhappiness(punit, &free_unhappy);
2781 output_type_iterate(o) {
2782 if (O_GOLD != o) {
2783 /* O_GOLD is handled with "game.info.gold_upkeep_style", see over. */
2784 pcity->usage[o] += punit->upkeep[o];
2785 }
2786 } output_type_iterate_end;
2787 } unit_list_iterate_end;
2788 }
2789
2790 /**************************************************************************
2791 Refreshes the internal cached data in the city structure.
2792
2793 !full_refresh will not update tile_cache[] or bonus[]. These two
2794 values do not need to be recalculated for AI CMA testing.
2795
2796 'workers_map' is an boolean array which defines the placement of the
2797 workers within the city map. It uses the tile index and its size is
2798 defined by city_map_tiles_from_city(_pcity). See also cm_state_init().
2799
2800 If 'workers_map' is set, only basic updates are needed.
2801 **************************************************************************/
city_refresh_from_main_map(struct city * pcity,bool * workers_map)2802 void city_refresh_from_main_map(struct city *pcity, bool *workers_map)
2803 {
2804 if (workers_map == NULL) {
2805 /* do a full refresh */
2806
2807 /* Calculate the bonus[] array values. */
2808 set_city_bonuses(pcity);
2809 /* Calculate the tile_cache[] values. */
2810 city_tile_cache_update(pcity);
2811 /* manage settlers, and units */
2812 city_support(pcity);
2813 }
2814
2815 /* Calculate output from citizens (uses city_tile_cache_get_output()). */
2816 get_worked_tile_output(pcity, pcity->citizen_base, workers_map);
2817 add_specialist_output(pcity, pcity->citizen_base);
2818
2819 set_city_production(pcity);
2820 citizen_base_mood(pcity);
2821 /* Note that pollution is calculated before unhappy_city_check() makes
2822 * deductions for disorder; so a city in disorder still causes pollution */
2823 pcity->pollution = city_pollution(pcity, pcity->prod[O_SHIELD]);
2824
2825 happy_copy(pcity, FEELING_LUXURY);
2826 citizen_happy_luxury(pcity); /* with our new found luxuries */
2827
2828 happy_copy(pcity, FEELING_EFFECT);
2829 citizen_content_buildings(pcity);
2830
2831 happy_copy(pcity, FEELING_NATIONALITY);
2832 citizen_happiness_nationality(pcity);
2833
2834 /* Martial law & unrest from units */
2835 happy_copy(pcity, FEELING_MARTIAL);
2836 citizen_happy_units(pcity);
2837
2838 /* Building (including wonder) happiness effects */
2839 happy_copy(pcity, FEELING_FINAL);
2840 citizen_happy_wonders(pcity);
2841
2842 unhappy_city_check(pcity);
2843 set_surpluses(pcity);
2844 }
2845
2846 /**************************************************************************
2847 Give corruption/waste generated by city. otype gives the output type
2848 (O_SHIELD/O_TRADE). 'total' gives the total output of this type in the
2849 city. If non-NULL, 'breakdown' should be an OLOSS_LAST-sized array
2850 which will be filled in with a breakdown of the kinds of waste
2851 (not cumulative).
2852 **************************************************************************/
city_waste(const struct city * pcity,Output_type_id otype,int total,int * breakdown)2853 int city_waste(const struct city *pcity, Output_type_id otype, int total,
2854 int *breakdown)
2855 {
2856 int penalty_waste = 0;
2857 int penalty_size = 0; /* separate notradesize/fulltradesize from normal
2858 * corruption */
2859 int total_eft = total; /* normal corruption calculated on total reduced by
2860 * possible size penalty */
2861 int waste_level = get_city_output_bonus(pcity, get_output_type(otype),
2862 EFT_OUTPUT_WASTE);
2863 bool waste_all = FALSE;
2864
2865 if (otype == O_TRADE) {
2866 /* FIXME: special case for trade: it is affected by notradesize and
2867 * fulltradesize server settings.
2868 *
2869 * If notradesize and fulltradesize are equal then the city gets no
2870 * trade at that size. */
2871 int notradesize = MIN(game.info.notradesize, game.info.fulltradesize);
2872 int fulltradesize = MAX(game.info.notradesize, game.info.fulltradesize);
2873
2874 if (city_size_get(pcity) <= notradesize) {
2875 penalty_size = total_eft; /* Then no trade income. */
2876 } else if (city_size_get(pcity) >= fulltradesize) {
2877 penalty_size = 0;
2878 } else {
2879 penalty_size = total_eft * (fulltradesize - city_size_get(pcity))
2880 / (fulltradesize - notradesize);
2881 }
2882 }
2883
2884 /* Apply corruption only to anything left after tradesize */
2885 total_eft -= penalty_size;
2886
2887 /* Distance-based waste.
2888 * Don't bother calculating if there's nothing left to lose. */
2889 if (total_eft > 0) {
2890 int waste_by_dist = get_city_output_bonus(pcity, get_output_type(otype),
2891 EFT_OUTPUT_WASTE_BY_DISTANCE);
2892 if (waste_by_dist > 0) {
2893 const struct city *gov_center = NULL;
2894 int min_dist = FC_INFINITY;
2895
2896 /* Check the special case that city itself is gov center
2897 * before expensive iteration through all cities. */
2898 if (is_gov_center(pcity)) {
2899 gov_center = pcity;
2900 min_dist = 0;
2901 } else {
2902 city_list_iterate(city_owner(pcity)->cities, gc) {
2903 /* Do not recheck current city */
2904 if (gc != pcity && is_gov_center(gc)) {
2905 int dist = real_map_distance(gc->tile, pcity->tile);
2906
2907 if (dist < min_dist) {
2908 gov_center = gc;
2909 min_dist = dist;
2910 }
2911 }
2912 } city_list_iterate_end;
2913 }
2914
2915 if (gov_center == NULL) {
2916 waste_all = TRUE; /* no gov center - no income */
2917 } else {
2918 waste_level += waste_by_dist * min_dist;
2919 }
2920 }
2921 }
2922
2923 if (waste_all) {
2924 penalty_waste = total_eft;
2925 } else {
2926 int waste_pct = get_city_output_bonus(pcity, get_output_type(otype),
2927 EFT_OUTPUT_WASTE_PCT);
2928
2929 /* corruption/waste calculated only for the actually produced amount */
2930 if (waste_level > 0) {
2931 penalty_waste = total_eft * waste_level / 100;
2932 }
2933
2934 /* bonus calculated only for the actually produced amount */
2935 penalty_waste -= penalty_waste * waste_pct / 100;
2936
2937 /* Clip */
2938 penalty_waste = MIN(MAX(penalty_waste, 0), total_eft);
2939 }
2940
2941 if (breakdown) {
2942 breakdown[OLOSS_WASTE] = penalty_waste;
2943 breakdown[OLOSS_SIZE] = penalty_size;
2944 }
2945
2946 /* add up total penalty */
2947 return penalty_waste + penalty_size;
2948 }
2949
2950 /**************************************************************************
2951 Give the number of specialists in a city.
2952 **************************************************************************/
city_specialists(const struct city * pcity)2953 citizens city_specialists(const struct city *pcity)
2954 {
2955 citizens count = 0;
2956
2957 specialist_type_iterate(sp) {
2958 fc_assert_ret_val(MAX_CITY_SIZE - count > pcity->specialists[sp], 0);
2959 count += pcity->specialists[sp];
2960 } specialist_type_iterate_end;
2961
2962 return count;
2963 }
2964
2965 /****************************************************************************
2966 Return the "best" specialist available in the game. This specialist will
2967 have the most of the given type of output. If pcity is given then only
2968 specialists usable by pcity will be considered.
2969 ****************************************************************************/
best_specialist(Output_type_id otype,const struct city * pcity)2970 Specialist_type_id best_specialist(Output_type_id otype,
2971 const struct city *pcity)
2972 {
2973 int best = DEFAULT_SPECIALIST;
2974 int val = get_specialist_output(pcity, best, otype);
2975
2976 specialist_type_iterate(i) {
2977 if (!pcity || city_can_use_specialist(pcity, i)) {
2978 int val2 = get_specialist_output(pcity, i, otype);
2979
2980 if (val2 > val) {
2981 best = i;
2982 val = val2;
2983 }
2984 }
2985 } specialist_type_iterate_end;
2986
2987 return best;
2988 }
2989
2990 /**************************************************************************
2991 Adds an improvement (and its effects) to a city.
2992 **************************************************************************/
city_add_improvement(struct city * pcity,const struct impr_type * pimprove)2993 void city_add_improvement(struct city *pcity,
2994 const struct impr_type *pimprove)
2995 {
2996 pcity->built[improvement_index(pimprove)].turn = game.info.turn; /*I_ACTIVE*/
2997
2998 if (is_server() && is_wonder(pimprove)) {
2999 /* Client just read the info from the packets. */
3000 wonder_built(pcity, pimprove);
3001 }
3002 }
3003
3004 /**************************************************************************
3005 Removes an improvement (and its effects) from a city.
3006 **************************************************************************/
city_remove_improvement(struct city * pcity,const struct impr_type * pimprove)3007 void city_remove_improvement(struct city *pcity,
3008 const struct impr_type *pimprove)
3009 {
3010 log_debug("Improvement %s removed from city %s",
3011 improvement_rule_name(pimprove), pcity->name);
3012
3013 pcity->built[improvement_index(pimprove)].turn = I_DESTROYED;
3014
3015 if (is_server() && is_wonder(pimprove)) {
3016 /* Client just read the info from the packets. */
3017 wonder_destroyed(pcity, pimprove);
3018 }
3019 }
3020
3021 /**************************************************************************
3022 Returns TRUE iff the city has set the given option.
3023 **************************************************************************/
is_city_option_set(const struct city * pcity,enum city_options option)3024 bool is_city_option_set(const struct city *pcity, enum city_options option)
3025 {
3026 return BV_ISSET(pcity->city_options, option);
3027 }
3028
3029 /**************************************************************************
3030 Allocate memory for this amount of city styles.
3031 **************************************************************************/
city_styles_alloc(int num)3032 void city_styles_alloc(int num)
3033 {
3034 int i;
3035
3036 city_styles = fc_calloc(num, sizeof(*city_styles));
3037 game.control.styles_count = num;
3038
3039 for (i = 0; i < game.control.styles_count; i++) {
3040 requirement_vector_init(&city_styles[i].reqs);
3041 }
3042 }
3043
3044 /**************************************************************************
3045 De-allocate the memory used by the city styles.
3046 **************************************************************************/
city_styles_free(void)3047 void city_styles_free(void)
3048 {
3049 int i;
3050
3051 for (i = 0; i < game.control.styles_count; i++) {
3052 requirement_vector_free(&city_styles[i].reqs);
3053 }
3054
3055 free(city_styles);
3056 city_styles = NULL;
3057 game.control.styles_count = 0;
3058 }
3059
3060 /**************************************************************************
3061 Create virtual skeleton for a city.
3062 Values are mostly sane defaults.
3063
3064 Always tile_set_owner(ptile, pplayer) sometime after this!
3065 **************************************************************************/
create_city_virtual(struct player * pplayer,struct tile * ptile,const char * name)3066 struct city *create_city_virtual(struct player *pplayer,
3067 struct tile *ptile, const char *name)
3068 {
3069 int i;
3070
3071 /* Make sure that contents of city structure are correctly initialized,
3072 * if you ever allocate it by some other mean than fc_calloc() */
3073 struct city *pcity = fc_calloc(1, sizeof(*pcity));
3074
3075 fc_assert_ret_val(NULL != name, NULL); /* No unnamed cities! */
3076 sz_strlcpy(pcity->name, name);
3077
3078 pcity->tile = ptile;
3079 fc_assert_ret_val(NULL != pplayer, NULL); /* No unowned cities! */
3080 pcity->owner = pplayer;
3081 pcity->original = pplayer;
3082
3083 /* City structure was allocated with fc_calloc(), so contents are initially
3084 * zero. There is no need to initialize it a second time. */
3085
3086 /* Now set some usefull default values. */
3087 city_size_set(pcity, 1);
3088 pcity->specialists[DEFAULT_SPECIALIST] = 1;
3089
3090 output_type_iterate(o) {
3091 pcity->bonus[o] = 100;
3092 } output_type_iterate_end;
3093
3094 pcity->turn_plague = -1; /* -1 = never */
3095 pcity->did_buy = FALSE;
3096 pcity->city_radius_sq = game.info.init_city_radius_sq;
3097 pcity->turn_founded = game.info.turn;
3098 pcity->turn_last_built = game.info.turn;
3099
3100 pcity->tile_cache_radius_sq = -1; /* -1 = tile_cache must be initialised */
3101
3102 /* pcity->ai.act_cache: worker activities on the city map */
3103
3104 /* Initialise improvements list */
3105 for (i = 0; i < ARRAY_SIZE(pcity->built); i++) {
3106 pcity->built[i].turn = I_NEVER;
3107 }
3108
3109 /* Set up the worklist */
3110 worklist_init(&pcity->worklist);
3111
3112 pcity->units_supported = unit_list_new();
3113 pcity->task_reqs = worker_task_list_new();
3114
3115 if (is_server()) {
3116 pcity->server.mgr_score_calc_turn = -1; /* -1 = never */
3117
3118 CALL_FUNC_EACH_AI(city_alloc, pcity);
3119 } else {
3120 pcity->client.info_units_supported =
3121 unit_list_new_full(unit_virtual_destroy);
3122 pcity->client.info_units_present =
3123 unit_list_new_full(unit_virtual_destroy);
3124 /* collecting_info_units_supported set by fc_calloc().
3125 * collecting_info_units_present set by fc_calloc(). */
3126 }
3127
3128 return pcity;
3129 }
3130
3131 /**************************************************************************
3132 Removes the virtual skeleton of a city. You should already have removed
3133 all buildings and units you have added to the city before this.
3134 **************************************************************************/
destroy_city_virtual(struct city * pcity)3135 void destroy_city_virtual(struct city *pcity)
3136 {
3137 CALL_FUNC_EACH_AI(city_free, pcity);
3138
3139 citizens_free(pcity);
3140
3141 while (worker_task_list_size(pcity->task_reqs) > 0) {
3142 struct worker_task *ptask = worker_task_list_get(pcity->task_reqs, 0);
3143
3144 worker_task_list_remove(pcity->task_reqs, ptask);
3145
3146 free(ptask);
3147 }
3148 worker_task_list_destroy(pcity->task_reqs);
3149
3150 unit_list_destroy(pcity->units_supported);
3151 if (pcity->tile_cache != NULL) {
3152 free(pcity->tile_cache);
3153 }
3154
3155 if (!is_server()) {
3156 unit_list_destroy(pcity->client.info_units_supported);
3157 unit_list_destroy(pcity->client.info_units_present);
3158 /* Handle a rare case where the game is freed in the middle of a
3159 * spy/diplomat investigate cycle. */
3160 if (pcity->client.collecting_info_units_supported != NULL) {
3161 unit_list_destroy(pcity->client.collecting_info_units_supported);
3162 }
3163 if (pcity->client.collecting_info_units_present != NULL) {
3164 unit_list_destroy(pcity->client.collecting_info_units_present);
3165 }
3166 }
3167
3168 memset(pcity, 0, sizeof(*pcity)); /* ensure no pointers remain */
3169 free(pcity);
3170 }
3171
3172 /**************************************************************************
3173 Check if city with given id still exist. Use this before using
3174 old city pointers when city might have disappeared.
3175 **************************************************************************/
city_exist(int id)3176 bool city_exist(int id)
3177 {
3178 /* Check if city exist in game */
3179 if (game_city_by_number(id)) {
3180 return TRUE;
3181 }
3182
3183 return FALSE;
3184 }
3185
3186 /**************************************************************************
3187 Return TRUE if the city is a virtual city. That is, it is a valid city
3188 pointer but does not correspond to a city that exists in the game.
3189
3190 NB: A return value of FALSE implies that either the pointer is NULL or
3191 that the city exists in the game.
3192 **************************************************************************/
city_is_virtual(const struct city * pcity)3193 bool city_is_virtual(const struct city *pcity)
3194 {
3195 if (!pcity) {
3196 return FALSE;
3197 }
3198
3199 return pcity != game_city_by_number(pcity->id);
3200 }
3201
3202 /**************************************************************************
3203 Return TRUE if the city is worked without using up a citizen.
3204 **************************************************************************/
is_free_worked(const struct city * pcity,const struct tile * ptile)3205 bool is_free_worked(const struct city *pcity, const struct tile *ptile)
3206 {
3207 return is_city_center(pcity, ptile);
3208 }
3209
3210 /**************************************************************************
3211 Return pointer to ai data of given city and ai type.
3212 **************************************************************************/
city_ai_data(const struct city * pcity,const struct ai_type * ai)3213 void *city_ai_data(const struct city *pcity, const struct ai_type *ai)
3214 {
3215 return pcity->server.ais[ai_type_number(ai)];
3216 }
3217
3218 /**************************************************************************
3219 Attach ai data to city
3220 **************************************************************************/
city_set_ai_data(struct city * pcity,const struct ai_type * ai,void * data)3221 void city_set_ai_data(struct city *pcity, const struct ai_type *ai,
3222 void *data)
3223 {
3224 pcity->server.ais[ai_type_number(ai)] = data;
3225 }
3226