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 <string.h>
19 #include <math.h> /* pow */
20 
21 /* utility */
22 #include "rand.h"
23 #include "registry.h"
24 
25 /* common */
26 #include "actions.h"
27 #include "game.h"
28 #include "government.h"
29 #include "research.h"
30 #include "specialist.h"
31 
32 /* server */
33 #include "cityhand.h"
34 #include "citytools.h"
35 #include "cityturn.h"
36 #include "notify.h"
37 #include "plrhand.h"
38 #include "srv_log.h"
39 #include "unithand.h"
40 
41 /* server/advisors */
42 #include "advdata.h"
43 #include "advtools.h"
44 #include "autosettlers.h"
45 #include "advbuilding.h"
46 #include "infracache.h"
47 
48 /* ai */
49 #include "aitraits.h"
50 #include "difficulty.h"
51 #include "handicaps.h"
52 
53 /* ai/default */
54 #include "aidata.h"
55 #include "aihand.h"
56 #include "ailog.h"
57 #include "aiplayer.h"
58 #include "aisettler.h"
59 #include "aitools.h"
60 #include "aiunit.h"
61 #include "daidiplomacy.h"
62 #include "daidomestic.h"
63 #include "daimilitary.h"
64 #include "daieffects.h"
65 
66 #include "aicity.h"
67 
68 #define LOG_BUY LOG_DEBUG
69 #define LOG_EMERGENCY LOG_VERBOSE
70 #define LOG_WANT LOG_VERBOSE
71 
72 /* TODO:  AI_CITY_RECALC_SPEED should be configurable to ai difficulty.
73           -kauf  */
74 #define AI_CITY_RECALC_SPEED 5
75 
76 #define AI_BA_RECALC_SPEED 5
77 
78 #define SPECVEC_TAG tech
79 #define SPECVEC_TYPE struct advance *
80 #include "specvec.h"
81 
82 #define SPECVEC_TAG impr
83 #define SPECVEC_TYPE struct impr_type *
84 #include "specvec.h"
85 
86 /* Iterate over cities within a certain range around a given city
87  * (city_here) that exist within a given city list. */
88 #define city_range_iterate(city_here, list, range, city)		\
89 {									\
90   city_list_iterate(list, city) {					\
91     if (range == REQ_RANGE_PLAYER					\
92         || range == REQ_RANGE_TEAM					\
93         || range == REQ_RANGE_ALLIANCE                                  \
94         || (range == REQ_RANGE_TRADEROUTE                               \
95          && (city == city_here                                          \
96              || have_cities_trade_route(city, city_here)))              \
97      || ((range == REQ_RANGE_CITY || range == REQ_RANGE_LOCAL)		\
98       && city == city_here)						\
99      || (range == REQ_RANGE_CONTINENT					\
100       && tile_continent(city->tile) ==					\
101 	 tile_continent(city_here->tile))) {
102 
103 #define city_range_iterate_end						\
104     }									\
105   } city_list_iterate_end;						\
106 }
107 
108 #define CITY_EMERGENCY(pcity)						\
109  (pcity->surplus[O_SHIELD] < 0 || city_unhappy(pcity)			\
110   || pcity->food_stock + pcity->surplus[O_FOOD] < 0)
111 
112 #ifdef FREECIV_NDEBUG
113 #define ASSERT_CHOICE(c) /* Do nothing. */
114 #else  /* FREECIV_NDEBUG */
115 #define ASSERT_CHOICE(c)                                                 \
116   do {                                                                   \
117     if ((c).want > 0) {                                                  \
118       fc_assert((c).type > CT_NONE && (c).type < CT_LAST);               \
119       if ((c).type == CT_BUILDING) {                                     \
120         int _iindex = improvement_index((c).value.building);             \
121         fc_assert(_iindex >= 0 && _iindex < improvement_count());        \
122       } else {                                                           \
123         int _uindex = utype_index((c).value.utype);                      \
124         fc_assert(_uindex >= 0 && _uindex < utype_count());              \
125       }                                                                  \
126     }                                                                    \
127   } while(FALSE);
128 #endif /* FREECIV_NDEBUG */
129 
130 static void dai_city_sell_noncritical(struct city *pcity, bool redundant_only);
131 static void resolve_city_emergency(struct ai_type *ait, struct player *pplayer,
132                                    struct city *pcity);
133 
134 /**************************************************************************
135   Increase want for a technology because of the value of that technology
136   in providing an improvement effect.
137 
138   The input building_want gives the desire for the improvement;
139   the value may be negative for technologies that produce undesirable
140   effects.
141 
142   This function must convert from units of 'building want' to 'tech want'.
143   We put this conversion in a function because the 'want' scales are
144   unclear and kludged. Consequently, this conversion might require tweaking.
145 **************************************************************************/
want_tech_for_improvement_effect(struct ai_type * ait,struct player * pplayer,const struct city * pcity,const struct impr_type * pimprove,const struct advance * tech,adv_want building_want)146 static void want_tech_for_improvement_effect(struct ai_type *ait,
147                                              struct player *pplayer,
148                                              const struct city *pcity,
149                                              const struct impr_type *pimprove,
150                                              const struct advance *tech,
151                                              adv_want building_want)
152 {
153   /* The conversion factor was determined by experiment,
154    * and might need adjustment. See also dai_tech_effect_values()
155    */
156   const adv_want tech_want = building_want * def_ai_city_data(pcity, ait)->building_wait
157                              * 14 / 8;
158 #if 0
159   /* This logging is relatively expensive,
160    * so activate it only while necessary. */
161   TECH_LOG(LOG_DEBUG, pplayer, tech,
162     "wanted by %s for building: %d -> %d",
163     city_name_get(pcity), improvement_rule_name(pimprove),
164     building_want, tech_want);
165 #endif /* 0 */
166   if (tech) {
167     def_ai_player_data(pplayer, ait)->tech_want[advance_index(tech)] += tech_want;
168   }
169 }
170 
171 /**************************************************************************
172   Increase want for a technologies because of the value of that technology
173   in providing an improvement effect.
174 **************************************************************************/
want_techs_for_improvement_effect(struct ai_type * ait,struct player * pplayer,const struct city * pcity,const struct impr_type * pimprove,struct tech_vector * needed_techs,adv_want building_want)175 void want_techs_for_improvement_effect(struct ai_type *ait,
176                                        struct player *pplayer,
177                                        const struct city *pcity,
178                                        const struct impr_type *pimprove,
179                                        struct tech_vector *needed_techs,
180                                        adv_want building_want)
181 {
182   int t;
183   int n_needed_techs = tech_vector_size(needed_techs);
184 
185   for (t = 0; t < n_needed_techs; t++) {
186     want_tech_for_improvement_effect(ait, pplayer, pcity, pimprove,
187                                      *tech_vector_get(needed_techs, t),
188                                      building_want);
189   }
190 }
191 
192 /**************************************************************************
193   Decrease want for a technology because of the value of that technology
194   in obsoleting an improvement effect.
195 **************************************************************************/
dont_want_tech_obsoleting_impr(struct ai_type * ait,struct player * pplayer,const struct city * pcity,const struct impr_type * pimprove,adv_want building_want)196 void dont_want_tech_obsoleting_impr(struct ai_type *ait,
197                                     struct player *pplayer,
198                                     const struct city *pcity,
199                                     const struct impr_type *pimprove,
200                                     adv_want building_want)
201 {
202   requirement_vector_iterate(&pimprove->obsolete_by, pobs) {
203     if (pobs->source.kind == VUT_ADVANCE && pobs->present) {
204       want_tech_for_improvement_effect(ait, pplayer, pcity, pimprove,
205                                        pobs->source.value.advance,
206                                        -building_want);
207     }
208   } requirement_vector_iterate_end;
209 }
210 
211 /**************************************************************************
212   Choose a build for the barbarian player.
213 
214   TODO: Move this into daimilitary.c
215   TODO: It will be called for each city but doesn't depend on the city,
216   maybe cache it?  Although barbarians don't normally have many cities,
217   so can be a bigger bother to cache it.
218 **************************************************************************/
dai_barbarian_choose_build(struct player * pplayer,struct city * pcity,struct adv_choice * choice)219 static void dai_barbarian_choose_build(struct player *pplayer,
220                                        struct city *pcity,
221                                        struct adv_choice *choice)
222 {
223   struct unit_type *bestunit = NULL;
224   int i, bestattack = 0;
225 
226   /* Choose the best unit among the basic ones */
227   for(i = 0; i < num_role_units(L_BARBARIAN_BUILD); i++) {
228     struct unit_type *iunit = get_role_unit(L_BARBARIAN_BUILD, i);
229 
230     if (iunit->attack_strength > bestattack
231         && can_city_build_unit_now(pcity, iunit)) {
232       bestunit = iunit;
233       bestattack = iunit->attack_strength;
234     }
235   }
236 
237   /* Choose among those made available through other civ's research */
238   for(i = 0; i < num_role_units(L_BARBARIAN_BUILD_TECH); i++) {
239     struct unit_type *iunit = get_role_unit(L_BARBARIAN_BUILD_TECH, i);
240 
241     if (iunit->attack_strength > bestattack
242         && can_city_build_unit_now(pcity, iunit)) {
243       bestunit = iunit;
244       bestattack = iunit->attack_strength;
245     }
246   }
247 
248   /* If found anything, put it into the choice */
249   if (bestunit) {
250     choice->value.utype = bestunit;
251     /* FIXME: 101 is the "overriding military emergency" indicator */
252     choice->want   = 101;
253     choice->type   = CT_ATTACKER;
254   } else {
255     log_base(LOG_WANT, "Barbarians don't know what to build!");
256   }
257 }
258 
259 /**************************************************************************
260   Chooses what the city will build.  Is called after the military advisor
261   put it's choice into pcity->server.ai.choice and "settler advisor" put
262   settler want into pcity->founder_*.
263 
264   Note that AI cheats -- it suffers no penalty for switching from unit to
265   improvement, etc.
266 **************************************************************************/
dai_city_choose_build(struct ai_type * ait,struct player * pplayer,struct city * pcity)267 static void dai_city_choose_build(struct ai_type *ait, struct player *pplayer,
268                                   struct city *pcity)
269 {
270   struct adv_choice newchoice;
271   struct adv_data *adv = adv_data_get(pplayer, NULL);
272   struct ai_city *city_data = def_ai_city_data(pcity, ait);
273 
274   adv_init_choice(&newchoice);
275 
276   if (has_handicap(pplayer, H_AWAY)
277       && !city_built_last_turn(pcity)
278       && city_data->urgency == 0) {
279     /* Don't change existing productions unless we have to. */
280     return;
281   }
282 
283   if (is_barbarian(pplayer)) {
284     dai_barbarian_choose_build(pplayer, pcity, &(city_data->choice));
285   } else {
286     /* FIXME: 101 is the "overriding military emergency" indicator */
287     if ((city_data->choice.want <= 100
288          || city_data->urgency == 0)
289         && !(dai_on_war_footing(ait, pplayer) && city_data->choice.want > 0
290              && pcity->id != adv->wonder_city)) {
291       domestic_advisor_choose_build(ait, pplayer, pcity, &newchoice);
292       copy_if_better_choice(&newchoice, &(city_data->choice));
293     }
294   }
295 
296   /* Fallbacks */
297   if (city_data->choice.want == 0) {
298     /* Fallbacks do happen with techlevel 0, which is now default. -- Per */
299     CITY_LOG(LOG_WANT, pcity, "Falling back - didn't want to build soldiers,"
300 	     " workers, caravans, settlers, or buildings!");
301     city_data->choice.want = 1;
302     if (best_role_unit(pcity, action_get_role(ACTION_TRADE_ROUTE))) {
303       city_data->choice.value.utype
304         = best_role_unit(pcity, action_get_role(ACTION_TRADE_ROUTE));
305       city_data->choice.type = CT_CIVILIAN;
306     } else {
307       unsigned int our_def = assess_defense_quadratic(ait, pcity);
308 
309       if (our_def == 0
310           && dai_process_defender_want(ait, pplayer, pcity, 1, &(city_data->choice))) {
311         CITY_LOG(LOG_DEBUG, pcity, "Building fallback defender");
312       } else if (best_role_unit(pcity, UTYF_SETTLERS)) {
313         city_data->choice.value.utype
314           = dai_role_utype_for_terrain_class(pcity, UTYF_SETTLERS, TC_LAND);
315         city_data->choice.type = CT_CIVILIAN;
316       } else {
317         CITY_LOG(LOG_ERROR, pcity, "Cannot even build a fallback "
318                  "(caravan/coinage/settlers). Fix the ruleset!");
319         city_data->choice.want = 0;
320       }
321     }
322   }
323 
324   if (city_data->choice.want != 0) {
325     struct universal build_new;
326 
327     ASSERT_CHOICE(city_data->choice);
328 
329     CITY_LOG(LOG_DEBUG, pcity, "wants %s with desire " ADV_WANT_PRINTF ".",
330              dai_choice_rule_name(&city_data->choice),
331              city_data->choice.want);
332 
333     switch (city_data->choice.type) {
334     case CT_CIVILIAN:
335     case CT_ATTACKER:
336     case CT_DEFENDER:
337       build_new.kind = VUT_UTYPE;
338       build_new.value.utype = city_data->choice.value.utype;
339       break;
340     case CT_BUILDING:
341       build_new.kind = VUT_IMPROVEMENT;
342       build_new.value.building = city_data->choice.value.building;
343       break;
344     case CT_NONE:
345       build_new.kind = VUT_NONE;
346       break;
347     case CT_LAST:
348       build_new.kind = universals_n_invalid();
349       break;
350     };
351 
352     change_build_target(pplayer, pcity, &build_new, E_CITY_PRODUCTION_CHANGED);
353   }
354 }
355 
356 /**************************************************************************
357   Sell building from city
358 **************************************************************************/
try_to_sell_stuff(struct player * pplayer,struct city * pcity)359 static void try_to_sell_stuff(struct player *pplayer, struct city *pcity)
360 {
361   improvement_iterate(pimprove) {
362     if (can_city_sell_building(pcity, pimprove)
363 	&& !building_has_effect(pimprove, EFT_DEFEND_BONUS)) {
364 /* selling walls to buy defenders is counterproductive -- Syela */
365       really_handle_city_sell(pplayer, pcity, pimprove);
366       break;
367     }
368   } improvement_iterate_end;
369 }
370 
371 /**************************************************************************
372   Increase maxbuycost.  This variable indicates (via ai_gold_reserve) to
373   the tax selection code how much money do we need for buying stuff.
374 **************************************************************************/
increase_maxbuycost(struct player * pplayer,int new_value)375 static void increase_maxbuycost(struct player *pplayer, int new_value)
376 {
377   pplayer->ai_common.maxbuycost = MAX(pplayer->ai_common.maxbuycost, new_value);
378 }
379 
380 /**************************************************************************
381   Try to upgrade a city's units. limit is the last amount of gold we can
382   end up with after the upgrade. military is if we want to upgrade non-
383   military or military units.
384 **************************************************************************/
dai_upgrade_units(struct city * pcity,int limit,bool military)385 static void dai_upgrade_units(struct city *pcity, int limit, bool military)
386 {
387   struct player *pplayer = city_owner(pcity);
388   int expenses;
389 
390   dai_calc_data(pplayer, NULL, &expenses, NULL);
391 
392   unit_list_iterate(pcity->tile->units, punit) {
393     if (pcity->owner == punit->owner) {
394       /* Only upgrade units you own, not allied ones */
395 
396       struct unit_type *old_type = unit_type_get(punit);
397       struct unit_type *punittype = can_upgrade_unittype(pplayer, old_type);
398 
399       if (military && !IS_ATTACKER(old_type)) {
400         /* Only upgrade military units this round */
401         continue;
402       } else if (!military && IS_ATTACKER(old_type)) {
403         /* Only civilians or tranports this round */
404         continue;
405       }
406 
407       if (punittype) {
408         int cost = unit_upgrade_price(pplayer, old_type, punittype);
409         int real_limit = limit;
410 
411         /* Triremes are DANGEROUS!! We'll do anything to upgrade 'em. */
412         if (unit_has_type_flag(punit, UTYF_TRIREME)) {
413           real_limit = expenses;
414         }
415         if (pplayer->economic.gold - cost > real_limit) {
416           CITY_LOG(LOG_BUY, pcity, "Upgraded %s to %s for %d (%s)",
417                    unit_rule_name(punit),
418                    utype_rule_name(punittype),
419                    cost,
420                    military ? "military" : "civilian");
421           handle_unit_upgrade(city_owner(pcity), punit->id);
422         } else {
423           increase_maxbuycost(pplayer, cost);
424         }
425       }
426     }
427   } unit_list_iterate_end;
428 }
429 
430 /**************************************************************************
431   Buy and upgrade stuff!
432 **************************************************************************/
dai_spend_gold(struct ai_type * ait,struct player * pplayer)433 static void dai_spend_gold(struct ai_type *ait, struct player *pplayer)
434 {
435   struct adv_choice bestchoice;
436   int cached_limit = dai_gold_reserve(pplayer);
437   int expenses;
438   bool war_footing = dai_on_war_footing(ait, pplayer);
439 
440   /* Disband explorers that are at home but don't serve a purpose.
441    * FIXME: This is a hack, and should be removed once we
442    * learn how to ferry explorers to new land. */
443   city_list_iterate(pplayer->cities, pcity) {
444     struct tile *ptile = pcity->tile;
445     unit_list_iterate_safe(ptile->units, punit) {
446       if (unit_has_type_role(punit, L_EXPLORER)
447           && pcity->id == punit->homecity
448           && def_ai_city_data(pcity, ait)->urgency == 0) {
449         CITY_LOG(LOG_BUY, pcity, "disbanding %s to increase production",
450                  unit_rule_name(punit));
451 	handle_unit_disband(pplayer,punit->id);
452       }
453     } unit_list_iterate_safe_end;
454   } city_list_iterate_end;
455 
456   dai_calc_data(pplayer, NULL, &expenses, NULL);
457 
458   do {
459     bool expensive; /* don't buy when it costs x2 unless we must */
460     int buycost;
461     int limit = cached_limit; /* cached_limit is our gold reserve */
462     struct city *pcity = NULL;
463     struct ai_city *city_data;
464 
465     /* Find highest wanted item on the buy list */
466     adv_init_choice(&bestchoice);
467     city_list_iterate(pplayer->cities, acity) {
468       struct ai_city *acity_data = def_ai_city_data(acity, ait);
469 
470       if (acity_data->choice.want
471           > bestchoice.want && ai_fuzzy(pplayer, TRUE)) {
472         bestchoice.value = acity_data->choice.value;
473         bestchoice.want = acity_data->choice.want;
474         bestchoice.type = acity_data->choice.type;
475         pcity = acity;
476       }
477     } city_list_iterate_end;
478 
479     /* We found nothing, so we're done */
480     if (bestchoice.want == 0) {
481       break;
482     }
483 
484     city_data = def_ai_city_data(pcity, ait);
485 
486     /* Not dealing with this city a second time */
487     city_data->choice.want = 0;
488 
489     ASSERT_CHOICE(bestchoice);
490 
491     /* Try upgrade units at danger location (high want is usually danger) */
492     if (city_data->urgency > 1) {
493       if (bestchoice.type == CT_BUILDING
494        && is_wonder(bestchoice.value.building)) {
495         CITY_LOG(LOG_BUY, pcity, "Wonder being built in dangerous position!");
496       } else {
497         /* If we have urgent want, spend more */
498         int upgrade_limit = limit;
499 
500         if (city_data->urgency > 1) {
501           upgrade_limit = expenses;
502         }
503         /* Upgrade only military units now */
504         dai_upgrade_units(pcity, upgrade_limit, TRUE);
505       }
506     }
507 
508     if (pcity->anarchy != 0 && bestchoice.type != CT_BUILDING) {
509       continue; /* Nothing we can do */
510     }
511 
512     /* Cost to complete production */
513     buycost = city_production_buy_gold_cost(pcity);
514 
515     if (buycost <= 0) {
516       continue; /* Already completed */
517     }
518 
519     if (is_unit_choice_type(bestchoice.type)
520         && utype_is_cityfounder(bestchoice.value.utype)) {
521       if (get_city_bonus(pcity, EFT_GROWTH_FOOD) == 0
522           && bestchoice.value.utype->pop_cost > 0
523           && city_size_get(pcity) <= bestchoice.value.utype->pop_cost) {
524         /* Don't buy settlers in cities that cannot afford the population cost. */
525         /* This used to check also if city is about to grow to required size
526          * next turn and allow buying of settlers in that case, but current
527          * order of end/start turn activities is such that settler building
528          * fails already before city grows. */
529         continue;
530       } else if (city_list_size(pplayer->cities) > 6) {
531         /* Don't waste precious money buying settlers late game
532          * since this raises taxes, and we want science. Adjust this
533          * again when our tax algorithm is smarter. */
534         continue;
535       } else if (war_footing) {
536         continue;
537       }
538     } else {
539       /* We are not a settler. Therefore we increase the cash need we
540        * balance our buy desire with to keep cash at hand for emergencies
541        * and for upgrades */
542       limit *= 2;
543     }
544 
545     /* It costs x2 to buy something with no shields contributed */
546     expensive = (pcity->shield_stock == 0)
547                 || (pplayer->economic.gold - buycost < limit);
548 
549     if (bestchoice.type == CT_ATTACKER
550 	&& buycost
551            > utype_build_shield_cost(bestchoice.value.utype) * 2
552         && !war_footing) {
553        /* Too expensive for an offensive unit */
554        continue;
555     }
556 
557     /* FIXME: Here Syela wanted some code to check if
558      * pcity was doomed, and we should therefore attempt
559      * to sell everything in it of non-military value */
560 
561     if (pplayer->economic.gold - expenses >= buycost
562         && (!expensive
563             || (city_data->grave_danger != 0
564                 && assess_defense(ait, pcity) == 0)
565             || (bestchoice.want > 200 && city_data->urgency > 1))) {
566       /* Buy stuff */
567       CITY_LOG(LOG_BUY, pcity, "Crash buy of %s for %d (want " ADV_WANT_PRINTF ")",
568                dai_choice_rule_name(&bestchoice),
569                buycost,
570                bestchoice.want);
571       really_handle_city_buy(pplayer, pcity);
572     } else if (city_data->grave_danger != 0
573                && bestchoice.type == CT_DEFENDER
574                && assess_defense(ait, pcity) == 0) {
575       /* We have no gold but MUST have a defender */
576       CITY_LOG(LOG_BUY, pcity, "must have %s but can't afford it (%d < %d)!",
577                dai_choice_rule_name(&bestchoice),
578                pplayer->economic.gold,
579                buycost);
580       try_to_sell_stuff(pplayer, pcity);
581       if (pplayer->economic.gold - expenses >= buycost) {
582         CITY_LOG(LOG_BUY, pcity, "now we can afford it (sold something)");
583         really_handle_city_buy(pplayer, pcity);
584       }
585       increase_maxbuycost(pplayer, buycost);
586     }
587   } while (TRUE);
588 
589   if (!war_footing) {
590     /* Civilian upgrades now */
591     city_list_iterate(pplayer->cities, pcity) {
592       dai_upgrade_units(pcity, cached_limit, FALSE);
593     } city_list_iterate_end;
594   }
595 
596   log_base(LOG_BUY, "%s wants to keep %d in reserve (tax factor %d)",
597            player_name(pplayer), cached_limit, pplayer->ai_common.maxbuycost);
598 }
599 
600 /**************************************************************************
601   Calculates a unit's food upkeep (per turn).
602 **************************************************************************/
unit_food_upkeep(struct unit * punit)603 static int unit_food_upkeep(struct unit *punit)
604 {
605   struct player *pplayer = unit_owner(punit);
606   int upkeep = utype_upkeep_cost(unit_type_get(punit), pplayer, O_FOOD);
607 
608   if (punit->id != 0 && punit->homecity == 0)
609     upkeep = 0; /* thanks, Peter */
610 
611   return upkeep;
612 }
613 
614 
615 /**************************************************************************
616   Returns how much food a settler will consume out of the city's foodbox
617   when created. If unit has id zero it is assumed to be a virtual unit
618   inside a city.
619 
620   FIXME: This function should be generalised and then moved into
621   common/unittype.c - Per
622 **************************************************************************/
unit_foodbox_cost(struct unit * punit)623 static int unit_foodbox_cost(struct unit *punit)
624 {
625   int pop_cost = unit_type_get(punit)->pop_cost;
626 
627   if (pop_cost <= 0) {
628     return 0;
629   }
630 
631   if (punit->id == 0) {
632     /* It is a virtual unit, so must start in a city... */
633     struct city *pcity = tile_city(unit_tile(punit));
634     int size = city_size_get(pcity);
635     int cost = 0;
636     int i;
637 
638     /* The default is to lose 100%.  The growth bonus reduces this. */
639     int foodloss_pct = 100 - get_city_bonus(pcity, EFT_GROWTH_FOOD);
640 
641     foodloss_pct = CLIP(0, foodloss_pct, 100);
642     fc_assert_ret_val(pcity != NULL, -1);
643     fc_assert(size >= pop_cost);
644 
645     for (i = pop_cost; i > 0 ; i--) {
646       cost += city_granary_size(size--);
647     }
648     cost = cost * foodloss_pct / 100;
649 
650     return cost;
651   }
652 
653   return 30;
654 }
655 
656 /**************************************************************************
657   Estimates the want for a terrain improver (aka worker) by creating a
658   virtual unit and feeding it to settler_evaluate_improvements.
659 
660   TODO: AI does not ship UTYF_SETTLERS around, only UTYF_CITIES - Per
661 **************************************************************************/
contemplate_terrain_improvements(struct ai_type * ait,struct city * pcity)662 static void contemplate_terrain_improvements(struct ai_type *ait,
663                                              struct city *pcity)
664 {
665   struct unit *virtualunit;
666   int want;
667   enum unit_activity best_act;
668   struct extra_type *best_target;
669   struct tile *best_tile = NULL; /* May be accessed by log_*() calls. */
670   struct tile *pcenter = city_tile(pcity);
671   struct player *pplayer = city_owner(pcity);
672   struct adv_data *adv = adv_data_get(pplayer, NULL);
673   struct ai_plr *ai = dai_plr_data_get(ait, pplayer, NULL);
674   struct unit_type *utype
675            = dai_role_utype_for_terrain_class(pcity, UTYF_SETTLERS, TC_LAND);
676   Continent_id place = tile_continent(pcenter);
677   struct ai_city *city_data = def_ai_city_data(pcity, ait);
678 
679   city_data->settler_want = 0; /* Make sure old want does not stay if we don't want now */
680 
681   if (utype == NULL) {
682     log_debug("No UTYF_SETTLERS role unit available");
683     return;
684   }
685 
686   /* Create a localized "virtual" unit to do operations with. */
687   virtualunit = unit_virtual_create(pplayer, pcity, utype, 0);
688   /* Advisors data space not allocated as it's not needed in the
689      lifetime of the virtualunit. */
690   unit_tile_set(virtualunit, pcenter);
691   want = settler_evaluate_improvements(virtualunit, &best_act, &best_target,
692                                        &best_tile,
693                                        NULL, NULL);
694   if (unit_type_get(virtualunit)->pop_cost >= city_size_get(pcity)) {
695     /* We don't like disbanding the city as a side effect */
696     unit_virtual_destroy(virtualunit);
697 
698     return;
699   }
700   /* We consider unit_food_upkeep with only half FOOD_WEIGHTING to
701    * balance the fact that unit can improve many tiles during its
702    * lifetime, and want is calculated for just one of them.
703    * Having full FOOD_WEIGHT here would mean that tile improvement of
704    * +1 food would give just zero want for settler. Other weights
705    * are lower, so +1 shield - unit food upkeep would be negative. */
706   want = (want - unit_food_upkeep(virtualunit) * FOOD_WEIGHTING / 2) * 100
707          / (40 + unit_foodbox_cost(virtualunit));
708   unit_virtual_destroy(virtualunit);
709 
710   /* Massage our desire based on available statistics to prevent
711    * overflooding with worker type units if they come cheap in
712    * the ruleset */
713   if (place >= 0) {
714     want /= MAX(1, ai->stats.workers[place] / (adv->stats.cities[place] + 1));
715     want -= ai->stats.workers[place];
716   } else {
717     /* TODO: Handle Oceans with cities sensibly */
718   }
719   want = MAX(want, 0);
720 
721   if (place >= 0) {
722     CITY_LOG(LOG_DEBUG, pcity, "wants %s with want %d to do %s at (%d,%d), "
723              "we have %d workers and %d cities on the continent",
724              utype_rule_name(utype),
725              want,
726              get_activity_text(best_act),
727              TILE_XY(best_tile),
728              ai->stats.workers[place],
729              adv->stats.cities[place]);
730   } else {
731     CITY_LOG(LOG_DEBUG, pcity, "wants %s with want %d to do %s at (%d,%d)",
732              utype_rule_name(utype),
733              want,
734              get_activity_text(best_act),
735              TILE_XY(best_tile));
736   }
737 
738   fc_assert(want >= 0);
739 
740   city_data->settler_want = want;
741 }
742 
743 /**************************************************************************
744   One of the top level AI functions.  It does (by calling other functions):
745   worker allocations,
746   build choices,
747   extra gold spending.
748 **************************************************************************/
dai_manage_cities(struct ai_type * ait,struct player * pplayer)749 void dai_manage_cities(struct ai_type *ait, struct player *pplayer)
750 {
751   pplayer->ai_common.maxbuycost = 0;
752 
753   TIMING_LOG(AIT_EMERGENCY, TIMER_START);
754   city_list_iterate(pplayer->cities, pcity) {
755     if (CITY_EMERGENCY(pcity)
756         || city_granary_size(city_size_get(pcity)) == pcity->food_stock) {
757       /* Having a full granary isn't an emergency, but we want to rearrange */
758       auto_arrange_workers(pcity); /* this usually helps */
759     }
760     if (CITY_EMERGENCY(pcity)) {
761       /* Fix critical shortages or unhappiness */
762       resolve_city_emergency(ait, pplayer, pcity);
763     }
764     dai_city_sell_noncritical(pcity, TRUE);
765     sync_cities();
766   } city_list_iterate_end;
767   if (pplayer->economic.tax >= 30 /* Otherwise expect it to increase tax */
768       && player_get_expected_income(pplayer) < -(pplayer->economic.gold)) {
769     int count = city_list_size(pplayer->cities);
770     struct city *sellers[count + 1];
771     int i;
772 
773     /* Randomized order */
774     i = 0;
775     city_list_iterate(pplayer->cities, pcity) {
776       sellers[i++] = pcity;
777     } city_list_iterate_end;
778     for (i = 0; i < count; i++) {
779       int replace = fc_rand(count);
780       struct city *tmp;
781 
782       tmp = sellers[i];
783       sellers[i] = sellers[replace];
784       sellers[replace] = tmp;
785     }
786 
787     i = 0;
788     while (player_get_expected_income(pplayer) < -(pplayer->economic.gold)
789            && i < count) {
790       dai_city_sell_noncritical(sellers[i++], FALSE);
791     }
792   }
793   TIMING_LOG(AIT_EMERGENCY, TIMER_STOP);
794 
795   TIMING_LOG(AIT_BUILDINGS, TIMER_START);
796   building_advisor(pplayer);
797   TIMING_LOG(AIT_BUILDINGS, TIMER_STOP);
798 
799   /* Initialize the infrastructure cache, which is used shortly. */
800   initialize_infrastructure_cache(pplayer);
801   city_list_iterate(pplayer->cities, pcity) {
802     struct ai_city *city_data = def_ai_city_data(pcity, ait);
803     /* Note that this function mungs the seamap, but we don't care */
804     TIMING_LOG(AIT_CITY_MILITARY, TIMER_START);
805     military_advisor_choose_build(ait, pplayer, pcity, &city_data->choice);
806     TIMING_LOG(AIT_CITY_MILITARY, TIMER_STOP);
807     if (dai_on_war_footing(ait, pplayer) && city_data->choice.want > 0) {
808       city_data->settler_want = 0;
809       city_data->founder_want = 0;
810       city_data->founder_turn = game.info.turn; /* Do not consider zero we set here
811                                                  * valid value, if real want is needed.
812                                                  * Recalculate immediately in such situation. */
813       continue; /* Go, soldiers! */
814     }
815     /* Will record its findings in pcity->settler_want */
816     TIMING_LOG(AIT_CITY_TERRAIN, TIMER_START);
817     contemplate_terrain_improvements(ait, pcity);
818     TIMING_LOG(AIT_CITY_TERRAIN, TIMER_STOP);
819 
820     TIMING_LOG(AIT_CITY_SETTLERS, TIMER_START);
821     if (city_data->founder_turn <= game.info.turn) {
822       /* Will record its findings in pcity->founder_want */
823       contemplate_new_city(ait, pcity);
824       /* Avoid recalculating all the time.. */
825       /* This means AI is not very opportunistic if there happens to open up spot for
826        * a new city. */
827       city_data->founder_turn =
828         game.info.turn + fc_rand(AI_CITY_RECALC_SPEED) + AI_CITY_RECALC_SPEED;
829     } else if (pcity->server.debug) {
830       /* recalculate every turn */
831       contemplate_new_city(ait, pcity);
832     }
833     TIMING_LOG(AIT_CITY_SETTLERS, TIMER_STOP);
834     ASSERT_CHOICE(city_data->choice);
835   } city_list_iterate_end;
836   /* Reset auto settler state for the next run. */
837   dai_auto_settler_reset(ait, pplayer);
838 
839   city_list_iterate(pplayer->cities, pcity) {
840     dai_city_choose_build(ait, pplayer, pcity);
841   } city_list_iterate_end;
842 
843   dai_spend_gold(ait, pplayer);
844 }
845 
846 /**************************************************************************
847   Are effects provided by this building not needed?
848 
849   If this function is called for a building that has not yet been
850   constructed, side effect benefits may not be accurately calculated
851   (see improvement.c for details).
852 **************************************************************************/
building_crucial(const struct player * plr,struct impr_type * pimprove,const struct city * pcity)853 static bool building_crucial(const struct player *plr,
854                              struct impr_type *pimprove,
855                              const struct city *pcity)
856 {
857 #if 0 /* This check will become more complicated now. */
858   if (ai_wants_no_science(plr)
859       && building_has_effect(pimprove, EFT_SCIENCE_BONUS)) {
860     return FALSE;
861   }
862 #endif
863   if (building_has_effect(pimprove, EFT_DEFEND_BONUS)
864         /* selling city walls is really, really dumb -- Syela */
865       || is_improvement_productive(pcity, pimprove)) {
866     return TRUE;
867   }
868 
869   return FALSE;
870 }
871 
872 /**************************************************************************
873   Sell an noncritical building if there are any in the city.
874 **************************************************************************/
dai_city_sell_noncritical(struct city * pcity,bool redundant_only)875 static void dai_city_sell_noncritical(struct city *pcity,
876                                       bool redundant_only)
877 {
878   struct player *pplayer = city_owner(pcity);
879 
880   city_built_iterate(pcity, pimprove) {
881     if (can_city_sell_building(pcity, pimprove)
882         && !building_crucial(pplayer, pimprove, pcity)
883         && (!redundant_only || is_improvement_redundant(pcity, pimprove))) {
884       int gain = impr_sell_gold(pimprove);
885 
886       do_sell_building(pplayer, pcity, pimprove);
887       notify_player(pplayer, pcity->tile, E_IMP_SOLD, ftc_server,
888                     PL_("%s is selling %s for %d.",
889                         "%s is selling %s for %d.", gain),
890                     city_link(pcity),
891                     improvement_name_translation(pimprove),
892                     gain);
893       return; /* max 1 building each turn */
894     }
895   } city_built_iterate_end;
896 }
897 
898 /**************************************************************************
899   This function tries desperately to save a city from going under by
900   revolt or starvation of food or resources. We do this by taking
901   over resources held by nearby cities and disbanding units.
902 
903   TODO: Try to move units into friendly cities to reduce unhappiness
904   instead of disbanding. Also rather starve city than keep it in
905   revolt, as long as we don't lose settlers.
906 
907   TODO: Make function that tries to save units by moving them into
908   cities that can upkeep them and change homecity rather than just
909   disband. This means we'll have to move this function to beginning
910   of AI turn sequence (before moving units).
911 
912   "I don't care how slow this is; it will very rarely be used." -- Syela
913 
914   Syela is wrong. It happens quite too often, mostly due to unhappiness.
915   Also, most of the time we are unable to resolve the situation.
916 **************************************************************************/
resolve_city_emergency(struct ai_type * ait,struct player * pplayer,struct city * pcity)917 static void resolve_city_emergency(struct ai_type *ait, struct player *pplayer,
918                                    struct city *pcity)
919 {
920   struct tile *pcenter = city_tile(pcity);
921 
922   log_base(LOG_EMERGENCY,
923            "Emergency in %s (%s, angry%d, unhap%d food%d, prod%d)",
924            city_name_get(pcity),
925            city_unhappy(pcity) ? "unhappy" : "content",
926            pcity->feel[CITIZEN_ANGRY][FEELING_FINAL],
927            pcity->feel[CITIZEN_UNHAPPY][FEELING_FINAL],
928            pcity->surplus[O_FOOD],
929            pcity->surplus[O_SHIELD]);
930 
931   city_tile_iterate(city_map_radius_sq_get(pcity), pcenter, atile) {
932     struct city *acity = tile_worked(atile);
933 
934     if (acity && acity != pcity && city_owner(acity) == city_owner(pcity))  {
935       log_base(LOG_EMERGENCY, "%s taking over %s square in (%d, %d)",
936                city_name_get(pcity), city_name_get(acity), TILE_XY(atile));
937 
938       int ax, ay;
939       fc_assert_action(city_base_to_city_map(&ax, &ay, acity, atile),
940                        continue);
941 
942       if (is_free_worked(acity, atile)) {
943         /* Can't remove a worker here. */
944         continue;
945       }
946 
947       city_map_update_empty(acity, atile);
948       acity->specialists[DEFAULT_SPECIALIST]++;
949       city_freeze_workers_queue(acity);
950     }
951   } city_tile_iterate_end;
952 
953   auto_arrange_workers(pcity);
954 
955   if (!CITY_EMERGENCY(pcity)) {
956     log_base(LOG_EMERGENCY, "Emergency in %s resolved", city_name_get(pcity));
957     goto cleanup;
958   }
959 
960   unit_list_iterate_safe(pcity->units_supported, punit) {
961     if (city_unhappy(pcity)
962         && (utype_happy_cost(unit_type_get(punit), pplayer) > 0
963             && (unit_being_aggressive(punit) || is_field_unit(punit)))
964         && def_ai_unit_data(punit, ait)->passenger == 0) {
965       UNIT_LOG(LOG_EMERGENCY, punit, "is causing unrest, disbanded");
966       handle_unit_disband(pplayer, punit->id);
967       city_refresh(pcity);
968     }
969   } unit_list_iterate_safe_end;
970 
971   if (CITY_EMERGENCY(pcity)) {
972     log_base(LOG_EMERGENCY, "Emergency in %s remains unresolved",
973              city_name_get(pcity));
974   } else {
975     log_base(LOG_EMERGENCY,
976              "Emergency in %s resolved by disbanding unit(s)",
977              city_name_get(pcity));
978   }
979 
980   cleanup:
981   city_thaw_workers_queue();
982   sync_cities();
983 }
984 
985 /**************************************************************************
986   Initialize city for use with default AI.
987 **************************************************************************/
dai_city_alloc(struct ai_type * ait,struct city * pcity)988 void dai_city_alloc(struct ai_type *ait, struct city *pcity)
989 {
990   struct ai_city *city_data = fc_calloc(1, sizeof(struct ai_city));
991 
992   city_data->building_wait = BUILDING_WAIT_MINIMUM;
993   adv_init_choice(&(city_data->choice));
994 
995   city_set_ai_data(pcity, ait, city_data);
996 }
997 
998 /**************************************************************************
999   Free city from use with default AI.
1000 **************************************************************************/
dai_city_free(struct ai_type * ait,struct city * pcity)1001 void dai_city_free(struct ai_type *ait, struct city *pcity)
1002 {
1003   struct ai_city *city_data = def_ai_city_data(pcity, ait);
1004 
1005   if (city_data != NULL) {
1006     city_set_ai_data(pcity, ait, NULL);
1007     FC_FREE(city_data);
1008   }
1009 }
1010 
1011 /**************************************************************************
1012   Write ai city segments to savefile
1013 **************************************************************************/
dai_city_save(struct ai_type * ait,const char * aitstr,struct section_file * file,const struct city * pcity,const char * citystr)1014 void dai_city_save(struct ai_type *ait, const char *aitstr,
1015                    struct section_file *file, const struct city *pcity,
1016                    const char *citystr)
1017 {
1018   struct ai_city *city_data = def_ai_city_data(pcity, ait);
1019 
1020   /* FIXME: remove this when the urgency is properly recalculated. */
1021   secfile_insert_int(file, city_data->urgency, "%s.%s.urgency", citystr, aitstr);
1022 
1023   /* avoid fc_rand recalculations on subsequent reload. */
1024   secfile_insert_int(file, city_data->building_turn, "%s.%s.building_turn",
1025                      citystr, aitstr);
1026   secfile_insert_int(file, city_data->building_wait, "%s.%s.building_wait",
1027                      citystr, aitstr);
1028 
1029   /* avoid fc_rand and expensive recalculations on subsequent reload. */
1030   secfile_insert_int(file, city_data->founder_turn, "%s.%s.founder_turn",
1031                      citystr, aitstr);
1032   secfile_insert_int(file, city_data->founder_want, "%s.%s.founder_want",
1033                      citystr, aitstr);
1034   secfile_insert_bool(file, city_data->founder_boat, "%s.%s.founder_boat",
1035                       citystr, aitstr);
1036 }
1037 
1038 /**************************************************************************
1039   Load ai city segment from savefile
1040 **************************************************************************/
dai_city_load(struct ai_type * ait,const char * aitstr,const struct section_file * file,struct city * pcity,const char * citystr)1041 void dai_city_load(struct ai_type *ait, const char *aitstr,
1042                    const struct section_file *file,
1043                    struct city *pcity, const char *citystr)
1044 {
1045   struct ai_city *city_data = def_ai_city_data(pcity, ait);
1046 
1047   /* FIXME: remove this when the urgency is properly recalculated. */
1048   city_data->urgency
1049     = secfile_lookup_int_default(file, 0, "%s.%s.urgency", citystr, aitstr);
1050 
1051   /* avoid fc_rand recalculations on subsequent reload. */
1052   city_data->building_turn
1053     = secfile_lookup_int_default(file, 0, "%s.%s.building_turn", citystr,
1054                                  aitstr);
1055   city_data->building_wait
1056     = secfile_lookup_int_default(file, BUILDING_WAIT_MINIMUM,
1057                                  "%s.%s.building_wait", citystr, aitstr);
1058 
1059   /* avoid fc_rand and expensive recalculations on subsequent reload. */
1060   city_data->founder_turn
1061     = secfile_lookup_int_default(file, 0, "%s.%s.founder_turn", citystr,
1062                                  aitstr);
1063   city_data->founder_want
1064     = secfile_lookup_int_default(file, 0, "%s.%s.founder_want", citystr,
1065                                  aitstr);
1066   city_data->founder_boat
1067     = secfile_lookup_bool_default(file, (city_data->founder_want < 0),
1068                                   "%s.%s.founder_boat", citystr, aitstr);
1069 }
1070 
1071 /**************************************************************************
1072   How undesirable for the owner of a particular city is the fact that it
1073   can be a target of a particular action?
1074 
1075   The negative utility (how undesirable it is) is given as a positive
1076   number. If it is desirable to be the target of an action make the
1077   negative utility a negative number since double negative is positive.
1078 
1079   Examples:
1080    * action_target_neg_util(Add to population) = -50
1081    * action_target_neg_util(Subtract from population) = 50
1082 **************************************************************************/
action_target_neg_util(int act_id,const struct city * pcity)1083 static int action_target_neg_util(int act_id,
1084                                   const struct city *pcity)
1085 {
1086   switch ((enum gen_action)act_id) {
1087   case ACTION_SPY_INCITE_CITY:
1088     /* Copied from the evaluation of the No_Incite effect */
1089     return MAX((game.server.diplchance * 2
1090                 - game.server.incite_total_factor) / 2
1091                - game.server.incite_improvement_factor * 5
1092                - game.server.incite_unit_factor * 5, 0);
1093 
1094   /* Bad for the city owner. */
1095   case ACTION_SPY_POISON:
1096   case ACTION_SPY_SABOTAGE_CITY:
1097   case ACTION_SPY_TARGETED_SABOTAGE_CITY:
1098   case ACTION_SPY_STEAL_GOLD:
1099     /* TODO: Individual and well balanced values */
1100     return 10;
1101 
1102   /* Good for an enemy */
1103   case ACTION_SPY_STEAL_TECH:
1104   case ACTION_SPY_TARGETED_STEAL_TECH:
1105     /* TODO: Individual and well balanced values */
1106     return 8;
1107 
1108   /* Could be worse */
1109   case ACTION_ESTABLISH_EMBASSY:
1110   case ACTION_SPY_INVESTIGATE_CITY:
1111   case ACTION_MARKETPLACE:
1112     /* TODO: Individual and well balanced values */
1113     return 1;
1114 
1115   /* Good for the ciy owner in most cases. */
1116   case ACTION_TRADE_ROUTE:
1117   case ACTION_HELP_WONDER:
1118     /* TODO: Individual and well balanced values */
1119     return -1;
1120 
1121   /* Shouldn't happen. */
1122   case ACTION_SPY_BRIBE_UNIT:
1123   case ACTION_SPY_SABOTAGE_UNIT:
1124   case ACTION_COUNT:
1125     fc_assert_msg(action_id_get_target_kind(act_id) == ATK_CITY,
1126                   "Action not aimed at cities");
1127   }
1128 
1129   fc_assert_msg(action_id_is_valid(act_id),
1130                 "Action %d don't exist.", act_id);
1131 
1132   /* Wrong action. Ignore it. */
1133   return 0;
1134 }
1135 
1136 /**************************************************************************
1137   Increase the degree to which we want to meet a set of requirements,
1138   because they will enable construction of an improvement
1139   with desirable effects.
1140 
1141   v is the desire for the improvement.
1142 
1143   Returns whether all the requirements are met.
1144 **************************************************************************/
adjust_wants_for_reqs(struct ai_type * ait,struct player * pplayer,struct city * pcity,struct impr_type * pimprove,const adv_want v)1145 static bool adjust_wants_for_reqs(struct ai_type *ait,
1146                                   struct player *pplayer,
1147                                   struct city *pcity,
1148                                   struct impr_type *pimprove,
1149                                   const adv_want v)
1150 {
1151   bool all_met = TRUE;
1152   int n_needed_techs = 0;
1153   int n_needed_improvements = 0;
1154   struct tech_vector needed_techs;
1155   struct impr_vector needed_improvements;
1156 
1157   tech_vector_init(&needed_techs);
1158   impr_vector_init(&needed_improvements);
1159 
1160   requirement_vector_iterate(&pimprove->reqs, preq) {
1161     const bool active = is_req_active(pplayer, NULL, pcity, pimprove,
1162                                       pcity->tile, NULL, NULL, NULL, NULL,
1163                                       preq, RPT_POSSIBLE);
1164 
1165     if (VUT_ADVANCE == preq->source.kind && preq->present && !active) {
1166       /* Found a missing technology requirement for this improvement. */
1167       tech_vector_append(&needed_techs, preq->source.value.advance);
1168     } else if (VUT_IMPROVEMENT == preq->source.kind && preq->present && !active) {
1169       /* Found a missing improvement requirement for this improvement.
1170        * For example, in the default ruleset a city must have a Library
1171        * before it can have a University. */
1172       impr_vector_append(&needed_improvements, preq->source.value.building);
1173     }
1174     all_met = all_met && active;
1175   } requirement_vector_iterate_end;
1176 
1177   /* If v is negative, the improvement is not worth building,
1178    * but there is no need to punish research of the technologies
1179    * that would make it available.
1180    */
1181   n_needed_techs = tech_vector_size(&needed_techs);
1182   if (0 < v && 0 < n_needed_techs) {
1183     /* Tell AI module how much we want this improvement and what techs are
1184      * required to get it. */
1185     const adv_want dv = v / n_needed_techs;
1186 
1187     want_techs_for_improvement_effect(ait, pplayer, pcity, pimprove,
1188                                       &needed_techs, dv);
1189   }
1190 
1191   /* If v is negative, the improvement is not worth building,
1192    * but there is no need to punish building the improvements
1193    * that would make it available.
1194    */
1195   n_needed_improvements = impr_vector_size(&needed_improvements);
1196   if (0 < v && 0 < n_needed_improvements) {
1197     /* Because we want this improvement,
1198      * we want the improvements that will make it possible */
1199     const adv_want dv = v / (n_needed_improvements * 4); /* WAG */
1200     int i;
1201 
1202     for (i = 0; i < n_needed_improvements; i++) {
1203       struct impr_type *needed_impr = *impr_vector_get(&needed_improvements, i);
1204       /* TODO: increase the want for the needed_impr,
1205        * if we can build it now */
1206       /* Recurse */
1207       (void) adjust_wants_for_reqs(ait, pplayer, pcity, needed_impr, dv);
1208     }
1209   }
1210 
1211   /* TODO: use a similar method to increase wants for governments
1212    * that will make this improvement possible? */
1213 
1214   tech_vector_free(&needed_techs);
1215   impr_vector_free(&needed_improvements);
1216 
1217   return all_met;
1218 }
1219 
1220 
1221 /**************************************************************************
1222   Calculates city want from some input values.  Set pimprove to NULL when
1223   nothing in the city has changed, and you just want to know the
1224   base want of a city.
1225 **************************************************************************/
dai_city_want(struct player * pplayer,struct city * acity,struct adv_data * adv,struct impr_type * pimprove)1226 adv_want dai_city_want(struct player *pplayer, struct city *acity,
1227                        struct adv_data *adv, struct impr_type *pimprove)
1228 {
1229   adv_want want = 0;
1230   int prod[O_LAST], bonus[O_LAST], waste[O_LAST];
1231   int i;
1232 
1233   memset(prod, 0, O_LAST * sizeof(*prod));
1234   if (NULL != pimprove
1235       && adv->impr_calc[improvement_index(pimprove)] == ADV_IMPR_CALCULATE_FULL) {
1236     struct tile *acenter = city_tile(acity);
1237     bool celebrating = base_city_celebrating(acity);
1238 
1239     /* The below calculation mostly duplicates get_worked_tile_output().
1240      * We do this only for buildings that we know may change tile
1241      * outputs. */
1242     city_tile_iterate(city_map_radius_sq_get(acity), acenter, ptile) {
1243       if (tile_worked(ptile) == acity) {
1244         output_type_iterate(o) {
1245           prod[o] += city_tile_output(acity, ptile, celebrating, o);
1246         } output_type_iterate_end;
1247       }
1248     } city_tile_iterate_end;
1249 
1250     add_specialist_output(acity, prod);
1251   } else {
1252     fc_assert(sizeof(*prod) == sizeof(*acity->citizen_base));
1253     memcpy(prod, acity->citizen_base, O_LAST * sizeof(*prod));
1254   }
1255 
1256   for (i = 0; i < MAX_TRADE_ROUTES; i++) {
1257     prod[O_TRADE] += acity->trade_value[i];
1258   }
1259   prod[O_GOLD] += get_city_tithes_bonus(acity);
1260   output_type_iterate(o) {
1261     bonus[o] = get_final_city_output_bonus(acity, o);
1262     waste[o] = city_waste(acity, o, prod[o] * bonus[o] / 100, NULL);
1263   } output_type_iterate_end;
1264   add_tax_income(pplayer,
1265 		 prod[O_TRADE] * bonus[O_TRADE] / 100 - waste[O_TRADE],
1266 		 prod);
1267   output_type_iterate(o) {
1268     prod[o] = prod[o] * bonus[o] / 100 - waste[o];
1269   } output_type_iterate_end;
1270 
1271   city_built_iterate(acity, upkept) {
1272     prod[O_GOLD] -= city_improvement_upkeep(acity, upkept);
1273   } city_built_iterate_end;
1274   /* Unit upkeep isn't handled here.  Unless we do a full city_refresh it
1275    * won't be changed anyway. */
1276 
1277   want += prod[O_FOOD] * adv->food_priority;
1278   if (prod[O_SHIELD] != 0) {
1279     want += prod[O_SHIELD] * adv->shield_priority;
1280     want -= city_pollution(acity, prod[O_SHIELD]) * adv->pollution_priority;
1281   }
1282   want += prod[O_LUXURY] * adv->luxury_priority;
1283   want += prod[O_SCIENCE] * adv->science_priority;
1284   if (pplayer->economic.tax > 50) {
1285     /* Increased tax rate indicates that we've had gold shortage which
1286      * we are trying to fill with taxes. Consider gold more critical
1287      * than usually.
1288      * Smallest tax rate we can have here is 60% -> factor (60 - 40) / 14.0 = 1.43 */
1289     want += prod[O_GOLD] * adv->gold_priority * (pplayer->economic.tax - 40) / 14.0;
1290   } else {
1291     want += prod[O_GOLD] * adv->gold_priority;
1292   }
1293 
1294   return want;
1295 }
1296 
1297 /**************************************************************************
1298   Calculates want for some buildings by actually adding the building and
1299   measuring the effect.
1300 **************************************************************************/
base_want(struct ai_type * ait,struct player * pplayer,struct city * pcity,struct impr_type * pimprove)1301 static adv_want base_want(struct ai_type *ait, struct player *pplayer,
1302                           struct city *pcity, struct impr_type *pimprove)
1303 {
1304   struct adv_data *adv = adv_data_get(pplayer, NULL);
1305   adv_want final_want = 0;
1306   int wonder_player_id = WONDER_NOT_OWNED;
1307   int wonder_city_id = WONDER_NOT_BUILT;
1308 
1309   if (adv->impr_calc[improvement_index(pimprove)] == ADV_IMPR_ESTIMATE) {
1310     return 0; /* Nothing to calculate here. */
1311   }
1312 
1313   if (!can_city_build_improvement_now(pcity, pimprove)
1314       || (is_small_wonder(pimprove)
1315           && NULL != city_from_small_wonder(pplayer, pimprove))) {
1316     return 0;
1317   }
1318 
1319   if (is_wonder(pimprove)) {
1320     if (is_great_wonder(pimprove)) {
1321       wonder_player_id =
1322           game.info.great_wonder_owners[improvement_index(pimprove)];
1323     }
1324     wonder_city_id = pplayer->wonders[improvement_index(pimprove)];
1325   }
1326   /* Add the improvement */
1327   city_add_improvement(pcity, pimprove);
1328 
1329   /* Stir, then compare notes */
1330   city_range_iterate(pcity, pplayer->cities,
1331                      adv->impr_range[improvement_index(pimprove)], acity) {
1332     final_want += dai_city_want(pplayer, acity, adv, pimprove)
1333       - def_ai_city_data(acity, ait)->worth;
1334   } city_range_iterate_end;
1335 
1336   /* Restore */
1337   city_remove_improvement(pcity, pimprove);
1338   if (is_wonder(pimprove)) {
1339     if (is_great_wonder(pimprove)) {
1340       game.info.great_wonder_owners[improvement_index(pimprove)] =
1341           wonder_player_id;
1342     }
1343 
1344     pplayer->wonders[improvement_index(pimprove)] = wonder_city_id;
1345   }
1346 
1347   return final_want;
1348 }
1349 
1350 /**************************************************************************
1351   Calculate effects of possible improvements and extra effects of existing
1352   improvements. Consequently adjust the desirability of those improvements
1353   or the technologies that would make them possible.
1354 
1355   This function may (indeed, should) be called even for improvements that a city
1356   already has, or can not (yet) build. For existing improvements,
1357   it will discourage research of technologies that would make the improvement
1358   obsolete or reduce its effectiveness, and encourages technologies that would
1359   improve its effectiveness. For improvements that the city can not yet build
1360   it will encourage research of the techs and building of the improvements
1361   that will make the improvement possible.
1362 
1363   A complexity is that there are two sets of requirements to consider:
1364   the requirements for the building itself, and the requirements for
1365   the effects for the building.
1366 
1367   A few base variables:
1368     c - number of cities we have in current range
1369     u - units we have of currently affected type
1370     v - the want for the improvement we are considering
1371 
1372   This function contains a whole lot of WAGs. We ignore cond_* for now,
1373   thinking that one day we may fulfil the cond_s anyway. In general, we
1374   first add bonus for city improvements, then for wonders.
1375 
1376   IDEA: Calculate per-continent aggregates of various data, and use this
1377   for wonders below for better wonder placements.
1378 **************************************************************************/
adjust_improvement_wants_by_effects(struct ai_type * ait,struct player * pplayer,struct city * pcity,struct impr_type * pimprove,const bool already)1379 static void adjust_improvement_wants_by_effects(struct ai_type *ait,
1380                                                 struct player *pplayer,
1381                                                 struct city *pcity,
1382                                                 struct impr_type *pimprove,
1383                                                 const bool already)
1384 {
1385   adv_want v = 0;
1386   int cities[REQ_RANGE_COUNT];
1387   int nplayers = normal_player_count();
1388   struct adv_data *ai = adv_data_get(pplayer, NULL);
1389   bool capital = is_capital(pcity);
1390   bool can_build = TRUE;
1391   struct government *gov = government_of_player(pplayer);
1392   struct universal source = {
1393     .kind = VUT_IMPROVEMENT,
1394     .value = {.building = pimprove}
1395   };
1396   const bool is_coinage = improvement_has_flag(pimprove, IF_GOLD);
1397   int turns = 9999;
1398   int place = tile_continent(pcity->tile);
1399 
1400   /* Remove team members from the equation */
1401   players_iterate(aplayer) {
1402     if (aplayer->team
1403         && aplayer->team == pplayer->team
1404         && aplayer != pplayer) {
1405       nplayers--;
1406     }
1407   } players_iterate_end;
1408 
1409   if (is_coinage) {
1410     /* Since coinage contains some entirely spurious ruleset values,
1411      * we need to hard-code a sensible want.
1412      * We must otherwise handle the special IF_GOLD improvement
1413      * like the others, so the AI will research techs that make it available,
1414      * for rulesets that do not provide it from the start.
1415      */
1416     v += TRADE_WEIGHTING / 10;
1417   } else {
1418     /* Base want is calculated above using a more direct approach. */
1419     v += base_want(ait, pplayer, pcity, pimprove);
1420     if (v != 0) {
1421       CITY_LOG(LOG_DEBUG, pcity, "%s base_want is " ADV_WANT_PRINTF " (range=%d)",
1422                improvement_rule_name(pimprove),
1423                v,
1424                ai->impr_range[improvement_index(pimprove)]);
1425     }
1426   }
1427 
1428   if (!is_coinage) {
1429     /* Adjust by building cost */
1430     /* FIXME: ought to reduce by upkeep cost and amortise by building cost */
1431     v -= (impr_build_shield_cost(pimprove)
1432          / (pcity->surplus[O_SHIELD] * 10 + 1));
1433   }
1434 
1435   /* Find number of cities per range.  */
1436   cities[REQ_RANGE_PLAYER] = city_list_size(pplayer->cities);
1437   /* kludge -- Number of *our* cities in these ranges. */
1438   cities[REQ_RANGE_WORLD] = cities[REQ_RANGE_ALLIANCE] = cities[REQ_RANGE_TEAM]
1439     = cities[REQ_RANGE_PLAYER];
1440 
1441   if (place < 0) {
1442     cities[REQ_RANGE_CONTINENT] = 1;
1443   } else {
1444     cities[REQ_RANGE_CONTINENT] = ai->stats.cities[place];
1445   }
1446 
1447   /* All the trade partners and the city being considered. */
1448   cities[REQ_RANGE_TRADEROUTE] = city_num_trade_routes(pcity)+1;
1449 
1450   cities[REQ_RANGE_CITY] = cities[REQ_RANGE_LOCAL] = 1;
1451 
1452   /* Invalid building range */
1453   cities[REQ_RANGE_ADJACENT] = cities[REQ_RANGE_CADJACENT] = 0;
1454 
1455   players_iterate(aplayer) {
1456     int potential = (aplayer->server.bulbs_last_turn
1457                      + city_list_size(aplayer->cities) + 1);
1458 
1459     if (potential > 0) {
1460       requirement_vector_iterate(&pimprove->obsolete_by, pobs) {
1461         if (pobs->source.kind == VUT_ADVANCE && pobs->present) {
1462           turns = MIN(turns,
1463                       research_goal_bulbs_required(research_get(aplayer),
1464                           advance_number(pobs->source.value.advance))
1465                       / (potential + 1));
1466         }
1467       } requirement_vector_iterate_end;
1468     }
1469   } players_iterate_end;
1470 
1471   effect_list_iterate(get_req_source_effects(&source), peffect) {
1472     struct requirement *mypreq = NULL;
1473     bool active = TRUE;
1474     int n_needed_techs = 0;
1475     struct tech_vector needed_techs;
1476     bool present = TRUE;
1477     bool impossible_to_get = FALSE;
1478 
1479     tech_vector_init(&needed_techs);
1480 
1481     requirement_vector_iterate(&peffect->reqs, preq) {
1482       /* Check if all the requirements for the currently evaluated effect
1483        * are met, except for having the building that we are evaluating. */
1484       if (VUT_IMPROVEMENT == preq->source.kind
1485 	  && preq->source.value.building == pimprove) {
1486 	mypreq = preq;
1487         present = preq->present;
1488         continue;
1489       }
1490       if (!is_req_active(pplayer, NULL, pcity, pimprove, NULL, NULL, NULL,
1491                          NULL, NULL, preq, RPT_POSSIBLE)) {
1492 	active = FALSE;
1493 	if (VUT_ADVANCE == preq->source.kind && preq->present) {
1494           /* This missing requirement is a missing tech requirement.
1495            * This will be for some additional effect
1496            * (For example, in the default ruleset, Mysticism increases
1497            * the effect of Temples). */
1498           tech_vector_append(&needed_techs, preq->source.value.advance);
1499         } else if (!dai_can_requirement_be_met_in_city(preq, pplayer, pcity)) {
1500           impossible_to_get = TRUE;
1501         }
1502       }
1503     } requirement_vector_iterate_end;
1504 
1505     n_needed_techs = tech_vector_size(&needed_techs);
1506     if ((active || n_needed_techs) && !impossible_to_get) {
1507       adv_want v1 = dai_effect_value(pplayer, gov, ai, pcity, capital,
1508                                      turns, peffect, cities[mypreq->range],
1509                                      nplayers);
1510       /* v1 could be negative (the effect could be undesirable),
1511        * although it is usually positive.
1512        * For example, in the default ruleset, Communism decreases the
1513        * effectiveness of a Cathedral. */
1514 
1515       if (!present) {
1516         /* Building removes the effect */
1517         /* Currently v1 is (v + delta). Make it (v - delta) instead */
1518         v1 = -v1;
1519       }
1520 
1521       if (active) {
1522 	v += v1;
1523       } else if (v1 > 0) {
1524         /* If value of the effect is negative, do not hold it against
1525          * the tech - having the tech wont force one to build the
1526          * building. */
1527 
1528 	/* We might want the technology that will enable this
1529 	 * (additional) effect.
1530 	 * The better the effect, the more we want the technology.
1531          * We are more interested in (additional) effects that enhance
1532 	 * buildings we already have.
1533 	 */
1534         const int a = already? 5: 4; /* WAG */
1535         const adv_want dv = v1 * a / (4 * n_needed_techs);
1536 
1537         want_techs_for_improvement_effect(ait, pplayer, pcity, pimprove,
1538                                           &needed_techs, dv);
1539       }
1540     }
1541 
1542     tech_vector_free(&needed_techs);
1543   } effect_list_iterate_end;
1544 
1545   /* Can the city be the target of an action? */
1546   action_iterate (act_id) {
1547     bool is_possible;
1548     bool will_be_possible = FALSE;
1549     enum req_range max_range;
1550     int act_neg_util;
1551 
1552     /* Is the action relevant? */
1553     if (action_id_get_target_kind(act_id) != ATK_CITY) {
1554       continue;
1555     }
1556 
1557     /* No range found yet. Local is the most narrow range. */
1558     max_range = REQ_RANGE_LOCAL;
1559 
1560     /* Is it possible to do the action to the city right now?
1561      *
1562      * (DiplRel requirements are ignored since actor_player is NULL) */
1563     is_possible = is_action_possible_on_city(act_id, NULL, pcity);
1564 
1565     /* Will it be possible to do the action to the city if the building is
1566      * built? */
1567     action_enabler_list_iterate(action_enablers_for_action(act_id),
1568                                 enabler) {
1569       bool active = TRUE;
1570       enum req_range range = REQ_RANGE_LOCAL;
1571 
1572       requirement_vector_iterate(&(enabler->target_reqs), preq) {
1573         if (VUT_IMPROVEMENT == preq->source.kind
1574             && preq->source.value.building == pimprove) {
1575           /* Pretend the building is there */
1576           if (preq->present) {
1577             range = preq->range; /* Assumption: Max one pr vector */
1578             continue;
1579           } else {
1580             active = FALSE;
1581             break;
1582           }
1583         }
1584 
1585         if (!is_req_active(pplayer, NULL, pcity, pimprove,
1586                            city_tile(pcity), NULL, NULL, NULL, NULL,
1587                            preq, RPT_POSSIBLE)) {
1588           active = FALSE;
1589           break;
1590         }
1591       } requirement_vector_iterate_end;
1592 
1593       if (active) {
1594         will_be_possible = TRUE;
1595 
1596         /* Store the widest range that enables the action. */
1597         if (max_range < range) {
1598           max_range = range;
1599         }
1600 
1601         /* Don't break the iteration even if the action is enabled. There
1602          * could be a wider range in an active action enabler not yet seen.
1603          */
1604       }
1605     } action_enabler_list_iterate_end;
1606 
1607     /* Will the building significantly change the ability to target
1608      * the city? */
1609     if (is_possible == will_be_possible) {
1610       continue;
1611     }
1612 
1613     /* How undersireable is it that the city may be a target? */
1614     act_neg_util = action_target_neg_util(act_id, pcity);
1615 
1616     /* Multiply the desire by number of cities in range.
1617      * Note: This is a simplification. If the action can be done or not
1618      * _may_ be uncanged or changed in the opposite direction in the other
1619      * cities in the range. */
1620     act_neg_util = cities[max_range] * act_neg_util;
1621 
1622     /* Consider the utility of being a potential target.
1623      * Remember: act_util is the negative utility of being a target. */
1624     if (will_be_possible) {
1625       v -= act_neg_util;
1626     } else {
1627       v += act_neg_util;
1628     }
1629   } action_iterate_end;
1630 
1631   if (already) {
1632     /* Discourage research of the technology that would make this building
1633      * obsolete. The bigger the desire for this building, the more
1634      * we want to discourage the technology. */
1635     dont_want_tech_obsoleting_impr(ait, pplayer, pcity, pimprove, v);
1636   } else {
1637     /* Increase the want for technologies that will enable
1638      * construction of this improvement, if necessary.
1639      */
1640     const bool all_met = adjust_wants_for_reqs(ait, pplayer, pcity, pimprove, v);
1641     can_build = can_build && all_met;
1642   }
1643 
1644   if (is_coinage && can_build) {
1645     /* Could have a negative want for coinage,
1646      * if we have some stock in a building already. */
1647     pcity->server.adv->building_want[improvement_index(pimprove)] += v;
1648   } else if (!already && can_build) {
1649     const struct research *presearch = research_get(pplayer);
1650 
1651     /* Convert the base 'want' into a building want
1652      * by applying various adjustments */
1653 
1654     /* Would it mean losing shields? */
1655     if ((VUT_UTYPE == pcity->production.kind
1656          || (is_wonder(pcity->production.value.building)
1657              && !is_wonder(pimprove))
1658          || (!is_wonder(pcity->production.value.building)
1659              && is_wonder(pimprove)))
1660         && pcity->turn_last_built != game.info.turn) {
1661       v -= pcity->shield_stock * SHIELD_WEIGHTING / 10;
1662     }
1663 
1664     /* Reduce want if building gets obsoleted soon */
1665     requirement_vector_iterate(&pimprove->obsolete_by, pobs) {
1666       if (pobs->source.kind == VUT_ADVANCE && pobs->present) {
1667         v -= v / MAX(1, research_goal_unknown_techs(presearch,
1668                             advance_number(pobs->source.value.advance)));
1669       }
1670     } requirement_vector_iterate_end;
1671 
1672     /* Are we wonder city? Try to avoid building non-wonders very much. */
1673     if (pcity->id == ai->wonder_city && !is_wonder(pimprove)) {
1674       v /= 5;
1675     }
1676 
1677     /* Set */
1678     pcity->server.adv->building_want[improvement_index(pimprove)] += v;
1679   }
1680   /* Else we either have the improvement already,
1681    * or we can not build it (yet) */
1682 }
1683 
1684 /**************************************************************************
1685   Whether the AI should calculate the building wants for this city
1686   this turn, ahead of schedule.
1687 
1688   Always recalculate if the city just finished building,
1689   so we can make a sensible choice for the next thing to build.
1690   Perhaps the improvement we were building has become obsolete,
1691   or a different player built the Great Wonder we were building.
1692 **************************************************************************/
should_force_recalc(struct city * pcity)1693 static bool should_force_recalc(struct city *pcity)
1694 {
1695   return city_built_last_turn(pcity)
1696       || (VUT_IMPROVEMENT == pcity->production.kind
1697        && !improvement_has_flag(pcity->production.value.building, IF_GOLD)
1698        && !can_city_build_improvement_later(pcity, pcity->production.value.building));
1699 }
1700 
1701 /**************************************************************************
1702   Initialize building advisor. Calculates data of all players, not
1703   only of those controlled by current ai type.
1704 **************************************************************************/
dai_build_adv_init(struct ai_type * ait,struct player * pplayer)1705 void dai_build_adv_init(struct ai_type *ait, struct player *pplayer)
1706 {
1707   struct adv_data *ai = adv_data_get(pplayer, NULL);
1708 
1709   /* Find current worth of cities and cache this. */
1710   city_list_iterate(pplayer->cities, pcity) {
1711     def_ai_city_data(pcity, ait)->worth = dai_city_want(pplayer, pcity, ai, NULL);
1712   } city_list_iterate_end;
1713 }
1714 
1715 /**************************************************************************
1716   Calculate how much an AI player should want to build particular
1717   improvements, because of the effects of those improvements, and
1718   increase the want for technologies that will enable buildings with
1719   desirable effects.
1720 **************************************************************************/
dai_build_adv_adjust(struct ai_type * ait,struct player * pplayer,struct city * wonder_city)1721 void dai_build_adv_adjust(struct ai_type *ait, struct player *pplayer,
1722                           struct city *wonder_city)
1723 {
1724   /* Clear old building wants.
1725    * Do this separately from the iteration over improvement types
1726    * because each iteration could actually update more than one improvement,
1727    * if improvements have improvements as requirements.
1728    */
1729   city_list_iterate(pplayer->cities, pcity) {
1730     struct ai_city *city_data = def_ai_city_data(pcity, ait);
1731 
1732     if (city_data->building_turn <= game.info.turn) {
1733       /* Do a scheduled recalculation this turn */
1734       improvement_iterate(pimprove) {
1735         pcity->server.adv->building_want[improvement_index(pimprove)] = 0;
1736       } improvement_iterate_end;
1737     } else if (should_force_recalc(pcity)) {
1738       /* Do an emergency recalculation this turn. */
1739       city_data->building_wait = city_data->building_turn
1740                                         - game.info.turn;
1741       city_data->building_turn = game.info.turn;
1742 
1743       improvement_iterate(pimprove) {
1744         pcity->server.adv->building_want[improvement_index(pimprove)] = 0;
1745       } improvement_iterate_end;
1746     }
1747   } city_list_iterate_end;
1748 
1749   improvement_iterate(pimprove) {
1750     const bool is_coinage = improvement_has_flag(pimprove, IF_GOLD);
1751 
1752     /* Handle coinage specially because you can never complete coinage */
1753     if (is_coinage
1754         || can_player_build_improvement_later(pplayer, pimprove)) {
1755       city_list_iterate(pplayer->cities, pcity) {
1756         struct ai_city *city_data = def_ai_city_data(pcity, ait);
1757 
1758         if (pcity != wonder_city && is_wonder(pimprove)) {
1759           /* Only wonder city should build wonders! */
1760           pcity->server.adv->building_want[improvement_index(pimprove)] = 0;
1761         } else if (city_data->building_turn <= game.info.turn) {
1762           /* Building wants vary relatively slowly, so not worthwhile
1763            * recalculating them every turn.
1764            * We DO want to calculate (tech) wants because of buildings
1765            * we already have. */
1766           const bool already = city_has_building(pcity, pimprove);
1767           int idx = improvement_index(pimprove);
1768 
1769           adjust_improvement_wants_by_effects(ait, pplayer, pcity,
1770                                               pimprove, already);
1771 
1772           fc_assert(!(already
1773                       && 0 < pcity->server.adv->building_want[idx]));
1774 
1775           if (is_great_wonder(pimprove)) {
1776             /* Not only would we get the wonder, but we would also prevent
1777              * opponents from getting it. */
1778             pcity->server.adv->building_want[idx] *= 1.5;
1779 
1780             if (pcity->production.kind == VUT_IMPROVEMENT
1781                 && is_great_wonder(pcity->production.value.building)) {
1782               /* If we already are building a great wonder, prefer continuing
1783                * to do so over stopping it */
1784               pcity->server.adv->building_want[idx] *= 1.25;
1785             }
1786           }
1787 
1788           /* If I am not an expansionist, I want buildings more than units */
1789           if (pcity->server.adv->building_want[idx] > 0) {
1790             pcity->server.adv->building_want[idx]
1791               = pcity->server.adv->building_want[idx]
1792                   * TRAIT_DEFAULT_VALUE
1793                   / ai_trait_get_value(TRAIT_EXPANSIONIST, pplayer);
1794           }
1795         }
1796         /* else wait until a later turn */
1797       } city_list_iterate_end;
1798     } else {
1799       /* An impossible improvement */
1800       city_list_iterate(pplayer->cities, pcity) {
1801         pcity->server.adv->building_want[improvement_index(pimprove)] = 0;
1802       } city_list_iterate_end;
1803     }
1804   } improvement_iterate_end;
1805 
1806 #ifdef FREECIV_DEBUG
1807   /* This logging is relatively expensive, so activate only if necessary */
1808   city_list_iterate(pplayer->cities, pcity) {
1809     improvement_iterate(pimprove) {
1810       if (pcity->server.adv->building_want[improvement_index(pimprove)] != 0) {
1811         CITY_LOG(LOG_DEBUG, pcity, "want to build %s with " ADV_WANT_PRINTF,
1812                  improvement_rule_name(pimprove),
1813                  pcity->server.adv->building_want[improvement_index(pimprove)]);
1814       }
1815     } improvement_iterate_end;
1816   } city_list_iterate_end;
1817 #endif /* FREECIV_DEBUG */
1818 
1819   /* Reset recalc counter */
1820   city_list_iterate(pplayer->cities, pcity) {
1821     struct ai_city *city_data = def_ai_city_data(pcity, ait);
1822 
1823     if (city_data->building_turn <= game.info.turn) {
1824       /* This will spread recalcs out so that no one turn end is
1825        * much longer than others */
1826       city_data->building_wait = fc_rand(AI_BA_RECALC_SPEED) + AI_BA_RECALC_SPEED;
1827       city_data->building_turn = game.info.turn
1828         + city_data->building_wait;
1829     }
1830   } city_list_iterate_end;
1831 }
1832 
1833 /**************************************************************************
1834   Is it ok for advisor code to consider given city as wonder city?
1835 **************************************************************************/
dai_consider_wonder_city(struct ai_type * ait,struct city * pcity,bool * result)1836 void dai_consider_wonder_city(struct ai_type *ait, struct city *pcity, bool *result)
1837 {
1838   if (def_ai_city_data(pcity, ait)->grave_danger > 0) {
1839     *result = FALSE;
1840   } else {
1841     *result = TRUE;
1842   }
1843 }
1844 
1845 /**************************************************************************
1846   Returns a buildable, non-obsolete building that can provide the effect.
1847 
1848   Note: this function is an inefficient hack to be used by the old AI.  It
1849   will never find wonders, since that's not what the AI wants.
1850 **************************************************************************/
dai_find_source_building(struct city * pcity,enum effect_type effect_type,struct unit_type * utype)1851 Impr_type_id dai_find_source_building(struct city *pcity,
1852                                       enum effect_type effect_type,
1853                                       struct unit_type *utype)
1854 {
1855   int greatest_value = 0;
1856   struct impr_type *best_building = NULL;
1857 
1858   effect_list_iterate(get_effects(effect_type), peffect) {
1859     if (peffect->value > greatest_value) {
1860       struct impr_type *building = NULL;
1861       bool wrong_unit = FALSE;
1862 
1863       requirement_vector_iterate(&peffect->reqs, preq) {
1864         if (VUT_IMPROVEMENT == preq->source.kind && preq->present) {
1865           building = preq->source.value.building;
1866 
1867           if (!can_city_build_improvement_now(pcity, building)
1868               || !is_improvement(building)) {
1869             building = NULL;
1870             break;
1871           }
1872         } else if (utype != NULL
1873                    && !is_req_active(city_owner(pcity), NULL, pcity, NULL, city_tile(pcity),
1874                                      NULL, utype, NULL, NULL, preq, RPT_POSSIBLE)) {
1875           /* Effect requires other kind of unit than what we are interested about */
1876           wrong_unit = TRUE;
1877           break;
1878         }
1879       } requirement_vector_iterate_end;
1880       if (!wrong_unit && building != NULL) {
1881         best_building = building;
1882 	greatest_value = peffect->value;
1883       }
1884     }
1885   } effect_list_iterate_end;
1886 
1887   if (best_building) {
1888     return improvement_number(best_building);
1889   }
1890   return B_LAST;
1891 }
1892