webperimental: ally share J.S. Bach's Cathedral.
[freeciv.git] / common / unittype.c
blob5a29bf4a8cefc9ec9d86eb55726bc5a30c0754e4
1 /***********************************************************************
2 Freeciv - Copyright (C) 1996 - A Kjeldberg, L Gregersen, P Unold
3 This program is free software; you can redistribute it and/or modify
4 it under the terms of the GNU General Public License as published by
5 the Free Software Foundation; either version 2, or (at your option)
6 any later version.
8 This program is distributed in the hope that it will be useful,
9 but WITHOUT ANY WARRANTY; without even the implied warranty of
10 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 GNU General Public License for more details.
12 ***********************************************************************/
14 #ifdef HAVE_CONFIG_H
15 #include <fc_config.h>
16 #endif
18 #include <string.h>
19 #include <math.h> /* ceil */
21 /* utility */
22 #include "astring.h"
23 #include "fcintl.h"
24 #include "log.h"
25 #include "mem.h"
26 #include "shared.h"
27 #include "string_vector.h"
28 #include "support.h"
30 /* common */
31 #include "ai.h"
32 #include "combat.h"
33 #include "game.h"
34 #include "government.h"
35 #include "movement.h"
36 #include "player.h"
37 #include "research.h"
38 #include "unitlist.h"
40 #include "unittype.h"
42 #define MAX_UNIT_ROLES L_LAST + ACTION_COUNT
44 static struct unit_type unit_types[U_LAST];
45 static struct unit_class unit_classes[UCL_LAST];
46 /* the unit_types and unit_classes arrays are now setup in:
47 server/ruleset.c (for the server)
48 client/packhand.c (for the client)
51 static struct user_flag user_type_flags[MAX_NUM_USER_UNIT_FLAGS];
53 static struct user_flag user_class_flags[MAX_NUM_USER_UCLASS_FLAGS];
55 /**************************************************************************
56 Return the first item of unit_types.
57 **************************************************************************/
58 struct unit_type *unit_type_array_first(void)
60 if (game.control.num_unit_types > 0) {
61 return unit_types;
63 return NULL;
66 /**************************************************************************
67 Return the last item of unit_types.
68 **************************************************************************/
69 const struct unit_type *unit_type_array_last(void)
71 if (game.control.num_unit_types > 0) {
72 return &unit_types[game.control.num_unit_types - 1];
74 return NULL;
77 /**************************************************************************
78 Return the number of unit types.
79 **************************************************************************/
80 Unit_type_id utype_count(void)
82 return game.control.num_unit_types;
85 /**************************************************************************
86 Return the unit type index.
88 Currently same as utype_number(), paired with utype_count()
89 indicates use as an array index.
90 **************************************************************************/
91 Unit_type_id utype_index(const struct unit_type *punittype)
93 fc_assert_ret_val(punittype, -1);
94 return punittype - unit_types;
97 /**************************************************************************
98 Return the unit type index.
99 **************************************************************************/
100 Unit_type_id utype_number(const struct unit_type *punittype)
102 fc_assert_ret_val(punittype, -1);
103 return punittype->item_number;
106 /**************************************************************************
107 Return a pointer for the unit type struct for the given unit type id.
109 This function returns NULL for invalid unit pointers (some callers
110 rely on this).
111 **************************************************************************/
112 struct unit_type *utype_by_number(const Unit_type_id id)
114 if (id < 0 || id >= game.control.num_unit_types) {
115 return NULL;
117 return &unit_types[id];
120 /**************************************************************************
121 Return the unit type for this unit.
122 **************************************************************************/
123 struct unit_type *unit_type_get(const struct unit *punit)
125 fc_assert_ret_val(NULL != punit, NULL);
126 return punit->utype;
130 /**************************************************************************
131 Returns the upkeep of a unit of this type under the given government.
132 **************************************************************************/
133 int utype_upkeep_cost(const struct unit_type *ut, struct player *pplayer,
134 Output_type_id otype)
136 int val = ut->upkeep[otype], gold_upkeep_factor;
138 if (BV_ISSET(ut->flags, UTYF_FANATIC)
139 && get_player_bonus(pplayer, EFT_FANATICS) > 0) {
140 /* Special case: fanatics have no upkeep under fanaticism. */
141 return 0;
144 /* switch shield upkeep to gold upkeep if
145 - the effect 'EFT_SHIELD2GOLD_FACTOR' is non-zero (it gives the
146 conversion factor in percent) and
147 - the unit has the corresponding flag set (UTYF_SHIELD2GOLD)
148 FIXME: Should the ai know about this? */
149 if (utype_has_flag(ut, UTYF_SHIELD2GOLD)
150 && (otype == O_GOLD || otype == O_SHIELD)) {
151 gold_upkeep_factor = get_player_bonus(pplayer, EFT_SHIELD2GOLD_FACTOR);
152 if (gold_upkeep_factor > 0) {
153 switch (otype) {
154 case O_GOLD:
155 val = ceil((0.01 * gold_upkeep_factor) * ut->upkeep[O_SHIELD]);
156 break;
157 case O_SHIELD:
158 val = 0;
159 break;
160 default:
161 fc_assert(otype == O_GOLD || otype == O_SHIELD);
162 break;
167 val *= get_player_output_bonus(pplayer, get_output_type(otype),
168 EFT_UPKEEP_FACTOR);
169 return val;
172 /**************************************************************************
173 Return the "happy cost" (the number of citizens who are discontented)
174 for this unit.
175 **************************************************************************/
176 int utype_happy_cost(const struct unit_type *ut,
177 const struct player *pplayer)
179 return ut->happy_cost * get_player_bonus(pplayer, EFT_UNHAPPY_FACTOR);
182 /**************************************************************************
183 Return whether the unit has the given flag.
184 **************************************************************************/
185 bool unit_has_type_flag(const struct unit *punit, enum unit_type_flag_id flag)
187 return utype_has_flag(unit_type_get(punit), flag);
190 /**************************************************************************
191 Return whether the given unit type has the role. Roles are like
192 flags but have no meaning except to the AI.
193 **************************************************************************/
194 bool utype_has_role(const struct unit_type *punittype, int role)
196 fc_assert_ret_val(role >= L_FIRST && role < L_LAST, FALSE);
197 return BV_ISSET(punittype->roles, role - L_FIRST);
200 /**************************************************************************
201 Return whether the unit has the given role.
202 **************************************************************************/
203 bool unit_has_type_role(const struct unit *punit, enum unit_role_id role)
205 return utype_has_role(unit_type_get(punit), role);
208 /****************************************************************************
209 Return whether the unit can take over enemy cities.
210 ****************************************************************************/
211 bool unit_can_take_over(const struct unit *punit)
213 /* TODO: Should unit state dependent action enablers be considered?
214 * Some callers aren't yet ready for changeable unit state (like current
215 * location) playing a role. */
216 return unit_owner(punit)->ai_common.barbarian_type != ANIMAL_BARBARIAN
217 && utype_can_take_over(unit_type_get(punit));
220 /****************************************************************************
221 Return whether the unit type can take over enemy cities.
222 ****************************************************************************/
223 bool utype_can_take_over(const struct unit_type *punittype)
225 /* FIXME: "Paradrop Unit" can in certain circumstances result in city
226 * conquest. */
227 return utype_can_do_action(punittype, ACTION_CONQUER_CITY);
230 /****************************************************************************
231 Return TRUE iff the given cargo type has no restrictions on when it can
232 load onto the given transporter.
233 (Does not check that cargo is valid for transport!)
234 ****************************************************************************/
235 bool utype_can_freely_load(const struct unit_type *pcargotype,
236 const struct unit_type *ptranstype)
238 return BV_ISSET(pcargotype->embarks,
239 uclass_index(utype_class(ptranstype)));
242 /****************************************************************************
243 Return TRUE iff the given cargo type has no restrictions on when it can
244 unload from the given transporter.
245 (Does not check that cargo is valid for transport!)
246 ****************************************************************************/
247 bool utype_can_freely_unload(const struct unit_type *pcargotype,
248 const struct unit_type *ptranstype)
250 return BV_ISSET(pcargotype->disembarks,
251 uclass_index(utype_class(ptranstype)));
254 /* Fake action representing any hostile action. */
255 #define ACTION_HOSTILE ACTION_COUNT + 1
257 /* Number of real and fake actions. */
258 #define ACTION_AND_FAKES ACTION_HOSTILE + 1
260 /* Cache of what generalized (ruleset defined) action enabler controlled
261 * actions units of each type can perform. Checking if any action can be
262 * done at all is done via the fake action ACTION_ANY. If any hostile
263 * action can be performed is done via ACTION_HOSTILE. */
264 static bv_unit_types unit_can_act_cache[ACTION_AND_FAKES];
266 /**************************************************************************
267 Cache what generalized (ruleset defined) action enabler controlled
268 actions a unit of the given type can perform.
269 **************************************************************************/
270 static void unit_can_act_cache_set(struct unit_type *putype)
272 /* Clear old values. */
273 action_iterate(act_id) {
274 BV_CLR(unit_can_act_cache[act_id], utype_index(putype));
275 } action_iterate_end;
276 BV_CLR(unit_can_act_cache[ACTION_ANY], utype_index(putype));
277 BV_CLR(unit_can_act_cache[ACTION_HOSTILE], utype_index(putype));
279 /* See if the unit type can do an action controlled by generalized action
280 * enablers */
281 action_enablers_iterate(enabler) {
282 if (action_id_get_actor_kind(enabler->action) == AAK_UNIT
283 && action_actor_utype_hard_reqs_ok(enabler->action, putype)
284 && requirement_fulfilled_by_unit_type(putype,
285 &(enabler->actor_reqs))) {
286 log_debug("act_cache: %s can %s",
287 utype_rule_name(putype), gen_action_name(enabler->action));
288 BV_SET(unit_can_act_cache[enabler->action], utype_index(putype));
289 BV_SET(unit_can_act_cache[ACTION_ANY], utype_index(putype));
290 if (action_is_hostile(enabler->action)) {
291 BV_SET(unit_can_act_cache[ACTION_HOSTILE], utype_index(putype));
294 } action_enablers_iterate_end;
297 /**************************************************************************
298 Return TRUE iff units of this type can do actions controlled by
299 generalized (ruleset defined) action enablers.
300 **************************************************************************/
301 bool utype_may_act_at_all(const struct unit_type *putype)
303 return utype_can_do_action(putype, ACTION_ANY);
306 /**************************************************************************
307 Return TRUE iff units of the given type can do the specified generalized
308 (ruleset defined) action enabler controlled action.
309 **************************************************************************/
310 bool utype_can_do_action(const struct unit_type *putype,
311 const int action_id)
313 return BV_ISSET(unit_can_act_cache[action_id], utype_index(putype));
316 /**************************************************************************
317 Return TRUE iff the unit type can perform the action corresponding to
318 the unit type role.
319 **************************************************************************/
320 static bool utype_can_do_action_role(const struct unit_type *putype,
321 const int role)
323 return utype_can_do_action(putype, role - L_LAST);
326 /**************************************************************************
327 Return TRUE iff units of this type can do hostile actions controlled by
328 generalized (ruleset defined) action enablers.
329 **************************************************************************/
330 bool utype_acts_hostile(const struct unit_type *putype)
332 return utype_can_do_action(putype, ACTION_HOSTILE);
335 /* Cache if any action at all may be possible when the actor unit's state
336 * is...
337 * bit 0 to USP_COUNT - 1: Possible when the corresponding property is TRUE
338 * bit USP_COUNT to ((USP_COUNT * 2) - 1): Possible when the corresponding
339 * property is FALSE
341 BV_DEFINE(bv_ustate_act_cache, USP_COUNT * 2);
343 /* Cache what actions may be possible when the target's local citytile state
344 * is
345 * bit 0 to CITYT_LAST - 1: Possible when the corresponding property is TRUE
346 * bit USP_COUNT to ((CITYT_LAST * 2) - 1): Possible when the corresponding
347 * property is FALSE
349 BV_DEFINE(bv_citytile_cache, CITYT_LAST * 2);
351 /* Cache position lookup functions */
352 #define requirement_unit_state_ereq(_id_, _present_) \
353 requirement_kind_ereq(_id_, REQ_RANGE_LOCAL, _present_, USP_COUNT)
354 #define requirement_citytile_ereq(_id_, _present_) \
355 requirement_kind_ereq(_id_, REQ_RANGE_LOCAL, _present_, CITYT_LAST)
357 /* Caches for each unit type */
358 static bv_ustate_act_cache ustate_act_cache[U_LAST][ACTION_AND_FAKES];
359 static bv_diplrel_all_reqs dipl_rel_action_cache[U_LAST][ACTION_AND_FAKES];
360 static bv_citytile_cache ctile_tgt_act_cache[U_LAST][ACTION_AND_FAKES];
362 /**************************************************************************
363 Cache if any action may be possible for a unit of the type putype for
364 each unit state property. Since a unit state property could be ignored
365 both present and !present must be checked.
366 **************************************************************************/
367 static void unit_state_action_cache_set(struct unit_type *putype)
369 struct requirement req;
370 int uidx = utype_index(putype);
372 /* The unit is not yet known to be allowed to perform any actions no
373 * matter what its unit state is. */
374 action_iterate(action_id) {
375 BV_CLR_ALL(ustate_act_cache[uidx][action_id]);
376 } action_iterate_end;
377 BV_CLR_ALL(ustate_act_cache[uidx][ACTION_ANY]);
378 BV_CLR_ALL(ustate_act_cache[uidx][ACTION_HOSTILE]);
380 if (!utype_may_act_at_all(putype)) {
381 /* Not an actor unit. */
382 return;
385 /* Common for every situation */
386 req.range = REQ_RANGE_LOCAL;
387 req.survives = FALSE;
388 req.source.kind = VUT_UNITSTATE;
390 for (req.source.value.unit_state = ustate_prop_begin();
391 req.source.value.unit_state != ustate_prop_end();
392 req.source.value.unit_state = ustate_prop_next(
393 req.source.value.unit_state)) {
395 /* No action will ever be possible in a specific unit state if the
396 * opposite unit state is required in all action enablers.
397 * No unit state except present and !present of the same property
398 * implies or conflicts with another so the tests can be simple. */
399 action_enablers_iterate(enabler) {
400 if (requirement_fulfilled_by_unit_type(putype,
401 &(enabler->actor_reqs))
402 && action_id_get_actor_kind(enabler->action) == AAK_UNIT) {
403 /* Not required to be absent, so OK if present */
404 req.present = FALSE;
405 if (!is_req_in_vec(&req, &(enabler->actor_reqs))) {
406 BV_SET(ustate_act_cache[utype_index(putype)][enabler->action],
407 requirement_unit_state_ereq(req.source.value.unit_state,
408 TRUE));
409 if (action_is_hostile(enabler->action)) {
410 BV_SET(ustate_act_cache[utype_index(putype)][ACTION_HOSTILE],
411 requirement_unit_state_ereq(req.source.value.unit_state,
412 TRUE));
414 BV_SET(ustate_act_cache[utype_index(putype)][ACTION_ANY],
415 requirement_unit_state_ereq(req.source.value.unit_state,
416 TRUE));
419 /* Not required to be present, so OK if absent */
420 req.present = TRUE;
421 if (!is_req_in_vec(&req, &(enabler->actor_reqs))) {
422 BV_SET(ustate_act_cache[utype_index(putype)][enabler->action],
423 requirement_unit_state_ereq(req.source.value.unit_state,
424 FALSE));
425 if (action_is_hostile(enabler->action)) {
426 BV_SET(ustate_act_cache[utype_index(putype)][ACTION_HOSTILE],
427 requirement_unit_state_ereq(req.source.value.unit_state,
428 FALSE));
430 BV_SET(ustate_act_cache[utype_index(putype)][ACTION_ANY],
431 requirement_unit_state_ereq(req.source.value.unit_state,
432 FALSE));
435 } action_enablers_iterate_end;
439 /**************************************************************************
440 Cache what actions may be possible for a unit of the type putype for
441 each local DiplRel variation. Since a diplomatic relationship could be
442 ignored both present and !present must be checked.
444 Note: since can_unit_act_when_local_diplrel_is() only supports querying
445 the local range no values for the other ranges are set.
446 **************************************************************************/
447 static void local_dipl_rel_action_cache_set(struct unit_type *putype)
449 struct requirement req;
450 int uidx = utype_index(putype);
452 /* The unit is not yet known to be allowed to perform any actions no
453 * matter what the diplomatic state is. */
454 action_iterate(action_id) {
455 BV_CLR_ALL(dipl_rel_action_cache[uidx][action_id]);
456 } action_iterate_end;
457 BV_CLR_ALL(dipl_rel_action_cache[uidx][ACTION_ANY]);
458 BV_CLR_ALL(dipl_rel_action_cache[uidx][ACTION_HOSTILE]);
460 if (!utype_may_act_at_all(putype)) {
461 /* Not an actor unit. */
462 return;
465 /* Common for every situation */
466 req.range = REQ_RANGE_LOCAL;
467 req.survives = FALSE;
468 req.source.kind = VUT_DIPLREL;
470 /* DiplRel starts with diplstate_type and ends with diplrel_other */
471 for (req.source.value.diplrel = diplstate_type_begin();
472 req.source.value.diplrel != DRO_LAST;
473 req.source.value.diplrel++) {
475 /* No action will ever be possible in a specific diplomatic relation if
476 * its presence contradicts all action enablers.
477 * Everything was set to false above. It is therefore OK to only change
478 * the cache when units can do an action given a certain diplomatic
479 * relationship property value. */
480 action_enablers_iterate(enabler) {
481 if (requirement_fulfilled_by_unit_type(putype,
482 &(enabler->actor_reqs))
483 && action_id_get_actor_kind(enabler->action) == AAK_UNIT) {
484 req.present = TRUE;
485 if (!does_req_contradicts_reqs(&req, &(enabler->actor_reqs))) {
486 BV_SET(dipl_rel_action_cache[uidx][enabler->action],
487 requirement_diplrel_ereq(req.source.value.diplrel,
488 REQ_RANGE_LOCAL, TRUE));
489 if (action_is_hostile(enabler->action)) {
490 BV_SET(dipl_rel_action_cache[uidx][ACTION_HOSTILE],
491 requirement_diplrel_ereq(req.source.value.diplrel,
492 REQ_RANGE_LOCAL, TRUE));
494 BV_SET(dipl_rel_action_cache[uidx][ACTION_ANY],
495 requirement_diplrel_ereq(req.source.value.diplrel,
496 REQ_RANGE_LOCAL, TRUE));
499 req.present = FALSE;
500 if (!does_req_contradicts_reqs(&req, &(enabler->actor_reqs))) {
501 BV_SET(dipl_rel_action_cache[uidx][enabler->action],
502 requirement_diplrel_ereq(req.source.value.diplrel,
503 REQ_RANGE_LOCAL, FALSE));
504 if (action_is_hostile(enabler->action)) {
505 BV_SET(dipl_rel_action_cache[uidx][ACTION_HOSTILE],
506 requirement_diplrel_ereq(req.source.value.diplrel,
507 REQ_RANGE_LOCAL, FALSE));
509 BV_SET(dipl_rel_action_cache[uidx][ACTION_ANY],
510 requirement_diplrel_ereq(req.source.value.diplrel,
511 REQ_RANGE_LOCAL, FALSE));
514 } action_enablers_iterate_end;
518 /**************************************************************************
519 Cache if any action may be possible for a unit of the type putype for
520 each target local city tile property. Both present and !present must be
521 checked since a city tile property could be ignored.
522 **************************************************************************/
523 static void tgt_citytile_act_cache_set(struct unit_type *putype)
525 struct requirement req;
526 int uidx = utype_index(putype);
528 /* The unit is not yet known to be allowed to perform any actions no
529 * matter what its target's CityTile state is. */
530 action_iterate(action_id) {
531 BV_CLR_ALL(ctile_tgt_act_cache[uidx][action_id]);
532 } action_iterate_end;
533 BV_CLR_ALL(ctile_tgt_act_cache[uidx][ACTION_ANY]);
534 BV_CLR_ALL(ctile_tgt_act_cache[uidx][ACTION_HOSTILE]);
536 if (!utype_may_act_at_all(putype)) {
537 /* Not an actor unit. */
538 return;
541 /* Common for every situation */
542 req.range = REQ_RANGE_LOCAL;
543 req.survives = FALSE;
544 req.source.kind = VUT_CITYTILE;
546 for (req.source.value.citytile = citytile_type_begin();
547 req.source.value.citytile != citytile_type_end();
548 req.source.value.citytile = citytile_type_next(
549 req.source.value.citytile)) {
551 /* No action will ever be possible in a target CityTile state if the
552 * opposite target CityTile state is required in all action enablers.
553 * No CityTile property state except present and !present of the same
554 * property implies or conflicts with another so the tests can be
555 * simple. */
556 action_enablers_iterate(enabler) {
557 if (requirement_fulfilled_by_unit_type(putype,
558 &(enabler->target_reqs))
559 && action_id_get_actor_kind(enabler->action) == AAK_UNIT) {
560 /* Not required to be absent, so OK if present */
561 req.present = FALSE;
562 if (!is_req_in_vec(&req, &(enabler->target_reqs))) {
563 BV_SET(ctile_tgt_act_cache[utype_index(putype)][enabler->action],
564 requirement_citytile_ereq(req.source.value.citytile,
565 TRUE));
566 if (action_is_hostile(enabler->action)) {
567 BV_SET(ctile_tgt_act_cache[utype_index(putype)][ACTION_HOSTILE],
568 requirement_citytile_ereq(req.source.value.citytile,
569 TRUE));
571 BV_SET(ctile_tgt_act_cache[utype_index(putype)][ACTION_ANY],
572 requirement_citytile_ereq(req.source.value.citytile,
573 TRUE));
576 /* Not required to be present, so OK if absent */
577 req.present = TRUE;
578 if (!is_req_in_vec(&req, &(enabler->target_reqs))) {
579 BV_SET(ctile_tgt_act_cache[utype_index(putype)][enabler->action],
580 requirement_citytile_ereq(req.source.value.citytile,
581 FALSE));
582 if (action_is_hostile(enabler->action)) {
583 BV_SET(ctile_tgt_act_cache[utype_index(putype)][ACTION_HOSTILE],
584 requirement_citytile_ereq(req.source.value.citytile,
585 FALSE));
587 BV_SET(ctile_tgt_act_cache[utype_index(putype)][ACTION_ANY],
588 requirement_citytile_ereq(req.source.value.citytile,
589 FALSE));
592 } action_enablers_iterate_end;
596 struct range {
597 int min;
598 int max;
601 #define MOVES_LEFT_INFINITY -1
603 /**************************************************************************
604 Get the legal range of move fragments left of the specified requirement
605 vector.
606 **************************************************************************/
607 static struct range *moves_left_range(struct requirement_vector *reqs)
609 struct range *prange = fc_malloc(sizeof(prange));
611 prange->min = 0;
612 prange->max = MOVES_LEFT_INFINITY;
614 requirement_vector_iterate(reqs, preq) {
615 if (preq->source.kind == VUT_MINMOVES) {
616 if (preq->present) {
617 prange->min = preq->source.value.minmoves;
618 } else {
619 prange->max = preq->source.value.minmoves;
622 } requirement_vector_iterate_end;
624 return prange;
627 /**************************************************************************
628 Cache if any action may be possible for a unit of the type putype given
629 the property tested for. Since a it could be ignored both present and
630 !present must be checked.
631 **************************************************************************/
632 void unit_type_action_cache_set(struct unit_type *ptype)
634 unit_can_act_cache_set(ptype);
635 unit_state_action_cache_set(ptype);
636 local_dipl_rel_action_cache_set(ptype);
637 tgt_citytile_act_cache_set(ptype);
640 /**************************************************************************
641 Cache what unit types may be allowed do what actions, both at all and
642 when certain properties are true.
643 **************************************************************************/
644 void unit_type_action_cache_init(void)
646 unit_type_iterate(u) {
647 unit_type_action_cache_set(u);
648 } unit_type_iterate_end;
651 /**************************************************************************
652 Return TRUE iff there exists an (action enabler controlled) action that a
653 unit of the type punit_type can perform while its unit state property
654 prop has the value is_there.
655 **************************************************************************/
656 bool can_unit_act_when_ustate_is(const struct unit_type *punit_type,
657 const enum ustate_prop prop,
658 const bool is_there)
660 return utype_can_do_act_when_ustate(punit_type, ACTION_ANY, prop, is_there);
663 /**************************************************************************
664 Return TRUE iff the unit type can do the specified (action enabler
665 controlled) action while its unit state property prop has the value
666 is_there.
667 **************************************************************************/
668 bool utype_can_do_act_when_ustate(const struct unit_type *punit_type,
669 const int action_id,
670 const enum ustate_prop prop,
671 const bool is_there)
673 return BV_ISSET(ustate_act_cache[utype_index(punit_type)][action_id],
674 requirement_unit_state_ereq(prop, is_there));
677 /**************************************************************************
678 Returns TRUE iff the unit type can do the specified (action enabler
679 controlled) action while its target's CityTile property state has the
680 value is_there.
681 **************************************************************************/
682 bool utype_can_do_act_if_tgt_citytile(const struct unit_type *punit_type,
683 const int action_id,
684 const enum citytile_type prop,
685 const bool is_there)
687 return BV_ISSET(ctile_tgt_act_cache[utype_index(punit_type)][action_id],
688 requirement_citytile_ereq(prop, is_there));
691 /**************************************************************************
692 Return TRUE iff the given (action enabler controlled) action can be
693 performed by a unit of the given type while the given property of its
694 owner's diplomatic relationship to the target's owner has the given
695 value.
697 Note: since this only supports the local range no information for other
698 ranges are stored in dipl_rel_action_cache.
699 **************************************************************************/
700 bool can_utype_do_act_if_tgt_diplrel(const struct unit_type *punit_type,
701 const int action_id,
702 const int prop,
703 const bool is_there)
705 int utype_id = utype_index(punit_type);
707 return BV_ISSET(dipl_rel_action_cache[utype_id][action_id],
708 requirement_diplrel_ereq(prop, REQ_RANGE_LOCAL, is_there));
711 /**************************************************************************
712 Return TRUE iff the given (action enabler controlled) action may be
713 performed by a unit of the given type that has the given number of move
714 fragments left.
716 Note: Values aren't cached. If a performance critical user appears it
717 would be a good idea to cache the (merged) ranges of move fragments
718 where a unit of the given type can perform the specified action.
719 **************************************************************************/
720 bool utype_may_act_move_frags(struct unit_type *punit_type,
721 const int action_id,
722 const int move_fragments)
724 struct range *ml_range;
726 fc_assert(action_id_exists(action_id) || action_id == ACTION_ANY);
728 if (!utype_may_act_at_all(punit_type)) {
729 /* Not an actor unit. */
730 return FALSE;
733 if (action_id == ACTION_ANY) {
734 /* Any action is OK. */
735 action_iterate(alt_act) {
736 if (utype_may_act_move_frags(punit_type, alt_act,
737 move_fragments)) {
738 /* It only has to be true for one action. */
739 return TRUE;
741 } action_iterate_end;
743 /* No action enabled. */
744 return FALSE;
747 if (action_id_get_actor_kind(action_id) != AAK_UNIT) {
748 /* This action isn't performed by any unit at all so this unit type
749 * can't do it. */
750 return FALSE;
753 action_enabler_list_iterate(action_enablers_for_action(action_id),
754 enabler) {
755 if (!requirement_fulfilled_by_unit_type(punit_type,
756 &(enabler->actor_reqs))) {
757 /* This action enabler isn't for this unit type at all. */
758 continue;
761 ml_range = moves_left_range(&(enabler->actor_reqs));
762 if (ml_range->min <= move_fragments
763 && (ml_range->max == MOVES_LEFT_INFINITY
764 || ml_range->max > move_fragments)) {
765 /* The number of move fragments is in range of the action enabler. */
767 free(ml_range);
769 return TRUE;
772 free(ml_range);
773 } action_enabler_list_iterate_end;
775 return FALSE;
778 /**************************************************************************
779 Return TRUE iff the given (action enabler controlled) action may be
780 performed by a unit of the given type if the target tile has the given
781 property.
783 Note: Values aren't cached. If a performance critical user appears it
784 would be a good idea to cache the result.
785 **************************************************************************/
786 bool utype_may_act_tgt_city_tile(struct unit_type *punit_type,
787 const int action_id,
788 const enum citytile_type prop,
789 const bool is_there)
791 struct requirement req;
793 if (!utype_may_act_at_all(punit_type)) {
794 /* Not an actor unit. */
795 return FALSE;
798 if (action_id == ACTION_ANY) {
799 /* Any action is OK. */
800 action_iterate(alt_act) {
801 if (utype_may_act_tgt_city_tile(punit_type, alt_act,
802 prop, is_there)) {
803 /* It only has to be true for one action. */
804 return TRUE;
806 } action_iterate_end;
808 /* No action enabled. */
809 return FALSE;
812 if (action_id_get_actor_kind(action_id) != AAK_UNIT) {
813 /* This action isn't performed by any unit at all so this unit type
814 * can't do it. */
815 return FALSE;
818 /* Common for every situation */
819 req.range = REQ_RANGE_LOCAL;
820 req.survives = FALSE;
821 req.source.kind = VUT_CITYTILE;
823 /* Will only check for the specified is_there */
824 req.present = is_there;
826 /* Will only check the specified property */
827 req.source.value.citytile = prop;
829 action_enabler_list_iterate(action_enablers_for_action(action_id),
830 enabler) {
831 if (!requirement_fulfilled_by_unit_type(punit_type,
832 &(enabler->actor_reqs))) {
833 /* This action enabler isn't for this unit type at all. */
834 continue;
837 if (!does_req_contradicts_reqs(&req, &(enabler->target_reqs))) {
838 /* This action isn't blocked by the given target tile property. */
839 return TRUE;
841 } action_enabler_list_iterate_end;
843 return FALSE;
846 /**************************************************************************
847 Returns TRUE iff performing the specified action will consume an actor
848 unit of the specified type.
849 **************************************************************************/
850 bool utype_is_consumed_by_action(const struct action *paction,
851 const struct unit_type *utype)
853 if (paction->actor_consuming_always) {
854 /* This action will always consume the unit no matter who it is. */
855 return TRUE;
858 /* FIXME: Since the actions listed below can be predicted to always
859 * consume the actor unit based on unit type alone they should probably
860 * be split in an actor consuming and a non actor consuming version. */
861 switch (paction->id) {
862 case ACTION_SPY_POISON:
863 case ACTION_SPY_SABOTAGE_UNIT:
864 case ACTION_SPY_STEAL_TECH:
865 case ACTION_SPY_TARGETED_STEAL_TECH:
866 case ACTION_SPY_INCITE_CITY:
867 case ACTION_SPY_SABOTAGE_CITY:
868 case ACTION_SPY_TARGETED_SABOTAGE_CITY:
869 case ACTION_SPY_STEAL_GOLD:
870 case ACTION_STEAL_MAPS:
871 case ACTION_SPY_NUKE:
872 /* A Spy has a chance to escape after performing the action. */
873 return !utype_has_flag(utype, UTYF_SPY);
874 case ACTION_ATTACK:
875 return uclass_has_flag(utype->uclass, UCF_MISSILE);
876 default:
877 return FALSE;
881 /****************************************************************************
882 Returns the number of shields it takes to build this unit type.
883 ****************************************************************************/
884 int utype_build_shield_cost(const struct unit_type *punittype)
886 return MAX(punittype->build_cost * game.info.shieldbox / 100, 1);
889 /****************************************************************************
890 Returns the number of shields it takes to build this unit.
891 ****************************************************************************/
892 int unit_build_shield_cost(const struct unit *punit)
894 return utype_build_shield_cost(unit_type_get(punit));
897 /****************************************************************************
898 Returns the amount of gold it takes to rush this unit.
899 ****************************************************************************/
900 int utype_buy_gold_cost(const struct unit_type *punittype,
901 int shields_in_stock)
903 int cost = 0;
904 const int missing = utype_build_shield_cost(punittype) - shields_in_stock;
906 if (missing > 0) {
907 cost = 2 * missing + (missing * missing) / 20;
909 if (shields_in_stock == 0) {
910 cost *= 2;
912 return cost;
915 /****************************************************************************
916 Returns the number of shields received when this unit type is disbanded.
917 ****************************************************************************/
918 int utype_disband_shields(const struct unit_type *punittype)
920 return utype_build_shield_cost(punittype) / 2;
923 /****************************************************************************
924 Returns the number of shields received when this unit is disbanded.
925 ****************************************************************************/
926 int unit_disband_shields(const struct unit *punit)
928 return utype_disband_shields(unit_type_get(punit));
931 /**************************************************************************
932 How much city shrinks when it builds unit of this type.
933 **************************************************************************/
934 int utype_pop_value(const struct unit_type *punittype)
936 return (punittype->pop_cost);
939 /**************************************************************************
940 How much population is put to building this unit.
941 **************************************************************************/
942 int unit_pop_value(const struct unit *punit)
944 return utype_pop_value(unit_type_get(punit));
947 /**************************************************************************
948 Return move type of the unit type
949 **************************************************************************/
950 enum unit_move_type utype_move_type(const struct unit_type *punittype)
952 return utype_class(punittype)->move_type;
955 /**************************************************************************
956 Return the (translated) name of the unit type.
957 You don't have to free the return pointer.
958 **************************************************************************/
959 const char *utype_name_translation(const struct unit_type *punittype)
961 return name_translation_get(&punittype->name);
964 /**************************************************************************
965 Return the (translated) name of the unit.
966 You don't have to free the return pointer.
967 **************************************************************************/
968 const char *unit_name_translation(const struct unit *punit)
970 return utype_name_translation(unit_type_get(punit));
973 /**************************************************************************
974 Return the (untranslated) rule name of the unit type.
975 You don't have to free the return pointer.
976 **************************************************************************/
977 const char *utype_rule_name(const struct unit_type *punittype)
979 return rule_name_get(&punittype->name);
982 /**************************************************************************
983 Return the (untranslated) rule name of the unit.
984 You don't have to free the return pointer.
985 **************************************************************************/
986 const char *unit_rule_name(const struct unit *punit)
988 return utype_rule_name(unit_type_get(punit));
991 /**************************************************************************
992 Return string describing unit type values.
993 String is static buffer that gets reused when function is called again.
994 **************************************************************************/
995 const char *utype_values_string(const struct unit_type *punittype)
997 static char buffer[256];
999 /* Print in two parts as move_points_text() returns a static buffer */
1000 fc_snprintf(buffer, sizeof(buffer), "%d/%d/%s",
1001 punittype->attack_strength,
1002 punittype->defense_strength,
1003 move_points_text(punittype->move_rate, TRUE));
1004 if (utype_fuel(punittype)) {
1005 cat_snprintf(buffer, sizeof(buffer), "(%s)",
1006 move_points_text(punittype->move_rate * utype_fuel(punittype),
1007 TRUE));
1009 return buffer;
1012 /**************************************************************************
1013 Return string with translated unit name and list of its values.
1014 String is static buffer that gets reused when function is called again.
1015 **************************************************************************/
1016 const char *utype_values_translation(const struct unit_type *punittype)
1018 static char buffer[256];
1020 fc_snprintf(buffer, sizeof(buffer),
1021 "%s [%s]",
1022 utype_name_translation(punittype),
1023 utype_values_string(punittype));
1024 return buffer;
1027 /**************************************************************************
1028 Return the (translated) name of the unit class.
1029 You don't have to free the return pointer.
1030 **************************************************************************/
1031 const char *uclass_name_translation(const struct unit_class *pclass)
1033 return name_translation_get(&pclass->name);
1036 /**************************************************************************
1037 Return the (untranslated) rule name of the unit class.
1038 You don't have to free the return pointer.
1039 **************************************************************************/
1040 const char *uclass_rule_name(const struct unit_class *pclass)
1042 return rule_name_get(&pclass->name);
1045 /****************************************************************************
1046 Return a string with all the names of units with this flag. If "alts" is
1047 set, separate with "or", otherwise "and". Return FALSE if no unit with
1048 this flag exists.
1049 ****************************************************************************/
1050 bool role_units_translations(struct astring *astr, int flag, bool alts)
1052 const int count = num_role_units(flag);
1054 if (4 < count) {
1055 if (alts) {
1056 astr_set(astr, _("%s or similar units"),
1057 utype_name_translation(get_role_unit(flag, 0)));
1058 } else {
1059 astr_set(astr, _("%s and similar units"),
1060 utype_name_translation(get_role_unit(flag, 0)));
1062 return TRUE;
1063 } else if (0 < count) {
1064 const char *vec[count];
1065 int i;
1067 for (i = 0; i < count; i++) {
1068 vec[i] = utype_name_translation(get_role_unit(flag, i));
1071 if (alts) {
1072 astr_build_or_list(astr, vec, count);
1073 } else {
1074 astr_build_and_list(astr, vec, count);
1076 return TRUE;
1078 return FALSE;
1081 /**************************************************************************
1082 Return whether this player can upgrade this unit type (to any other
1083 unit type). Returns NULL if no upgrade is possible.
1084 **************************************************************************/
1085 struct unit_type *can_upgrade_unittype(const struct player *pplayer,
1086 struct unit_type *punittype)
1088 struct unit_type *upgrade = punittype;
1089 struct unit_type *best_upgrade = NULL;
1091 /* For some reason this used to check
1092 * can_player_build_unit_direct() for the unittype
1093 * we're updating from.
1094 * That check is now removed as it prevented legal updates
1095 * of units player had acquired via bribing, capturing,
1096 * diplomatic treaties, or lua script. */
1098 while ((upgrade = upgrade->obsoleted_by) != U_NOT_OBSOLETED) {
1099 if (can_player_build_unit_direct(pplayer, upgrade)) {
1100 best_upgrade = upgrade;
1104 return best_upgrade;
1107 /**************************************************************************
1108 Return the cost (gold) of upgrading a single unit of the specified type
1109 to the new type. This price could (but currently does not) depend on
1110 other attributes (like nation or government type) of the player the unit
1111 belongs to.
1112 **************************************************************************/
1113 int unit_upgrade_price(const struct player *pplayer,
1114 const struct unit_type *from,
1115 const struct unit_type *to)
1117 int base_cost = utype_buy_gold_cost(to, utype_disband_shields(from));
1119 return base_cost
1120 * (100 + get_player_bonus(pplayer, EFT_UPGRADE_PRICE_PCT))
1121 / 100;
1124 /**************************************************************************
1125 Returns the unit type that has the given (translated) name.
1126 Returns NULL if none match.
1127 **************************************************************************/
1128 struct unit_type *unit_type_by_translated_name(const char *name)
1130 unit_type_iterate(punittype) {
1131 if (0 == strcmp(utype_name_translation(punittype), name)) {
1132 return punittype;
1134 } unit_type_iterate_end;
1136 return NULL;
1139 /**************************************************************************
1140 Returns the unit type that has the given (untranslated) rule name.
1141 Returns NULL if none match.
1142 **************************************************************************/
1143 struct unit_type *unit_type_by_rule_name(const char *name)
1145 const char *qname = Qn_(name);
1147 unit_type_iterate(punittype) {
1148 if (0 == fc_strcasecmp(utype_rule_name(punittype), qname)) {
1149 return punittype;
1151 } unit_type_iterate_end;
1153 return NULL;
1156 /**************************************************************************
1157 Returns the unit class that has the given (untranslated) rule name.
1158 Returns NULL if none match.
1159 **************************************************************************/
1160 struct unit_class *unit_class_by_rule_name(const char *s)
1162 const char *qs = Qn_(s);
1164 unit_class_iterate(pclass) {
1165 if (0 == fc_strcasecmp(uclass_rule_name(pclass), qs)) {
1166 return pclass;
1168 } unit_class_iterate_end;
1170 return NULL;
1173 /**************************************************************************
1174 Initialize user unit class flags.
1175 **************************************************************************/
1176 void user_unit_class_flags_init(void)
1178 int i;
1180 for (i = 0; i < MAX_NUM_USER_UCLASS_FLAGS; i++) {
1181 user_flag_init(&user_class_flags[i]);
1185 /**************************************************************************
1186 Sets user defined name for unit class flag.
1187 **************************************************************************/
1188 void set_user_unit_class_flag_name(enum unit_class_flag_id id,
1189 const char *name,
1190 const char *helptxt)
1192 int ufid = id - UCF_USER_FLAG_1;
1194 fc_assert_ret(id >= UCF_USER_FLAG_1 && id <= UCF_LAST_USER_FLAG);
1196 if (user_class_flags[ufid].name != NULL) {
1197 FC_FREE(user_class_flags[ufid].name);
1198 user_class_flags[ufid].name = NULL;
1201 if (name && name[0] != '\0') {
1202 user_class_flags[ufid].name = fc_strdup(name);
1205 if (user_class_flags[ufid].helptxt != NULL) {
1206 free(user_class_flags[ufid].helptxt);
1207 user_class_flags[ufid].helptxt = NULL;
1210 if (helptxt && helptxt[0] != '\0') {
1211 user_class_flags[ufid].helptxt = fc_strdup(helptxt);
1215 /**************************************************************************
1216 Unit class flag name callback, called from specenum code.
1217 **************************************************************************/
1218 const char *unit_class_flag_id_name_cb(enum unit_class_flag_id flag)
1220 if (flag < UCF_USER_FLAG_1 || flag > UCF_LAST_USER_FLAG) {
1221 return NULL;
1224 return user_class_flags[flag - UCF_USER_FLAG_1].name;
1227 /**************************************************************************
1228 Return the (untranslated) help text of the user unit class flag.
1229 **************************************************************************/
1230 const char *unit_class_flag_helptxt(enum unit_class_flag_id id)
1232 fc_assert(id >= UCF_USER_FLAG_1 && id <= UCF_LAST_USER_FLAG);
1234 return user_class_flags[id - UCF_USER_FLAG_1].helptxt;
1237 /**************************************************************************
1238 Initialize user unit type flags.
1239 **************************************************************************/
1240 void user_unit_type_flags_init(void)
1242 int i;
1244 for (i = 0; i < MAX_NUM_USER_UNIT_FLAGS; i++) {
1245 user_flag_init(&user_type_flags[i]);
1249 /**************************************************************************
1250 Sets user defined name for unit flag.
1251 **************************************************************************/
1252 void set_user_unit_type_flag_name(enum unit_type_flag_id id, const char *name,
1253 const char *helptxt)
1255 int ufid = id - UTYF_USER_FLAG_1;
1257 fc_assert_ret(id >= UTYF_USER_FLAG_1 && id <= UTYF_LAST_USER_FLAG);
1259 if (user_type_flags[ufid].name != NULL) {
1260 FC_FREE(user_type_flags[ufid].name);
1261 user_type_flags[ufid].name = NULL;
1264 if (name && name[0] != '\0') {
1265 user_type_flags[ufid].name = fc_strdup(name);
1268 if (user_type_flags[ufid].helptxt != NULL) {
1269 free(user_type_flags[ufid].helptxt);
1270 user_type_flags[ufid].helptxt = NULL;
1273 if (helptxt && helptxt[0] != '\0') {
1274 user_type_flags[ufid].helptxt = fc_strdup(helptxt);
1278 /**************************************************************************
1279 Unit type flag name callback, called from specenum code.
1280 **************************************************************************/
1281 const char *unit_type_flag_id_name_cb(enum unit_type_flag_id flag)
1283 if (flag < UTYF_USER_FLAG_1 || flag > UTYF_LAST_USER_FLAG) {
1284 return NULL;
1287 return user_type_flags[flag - UTYF_USER_FLAG_1].name;
1290 /**************************************************************************
1291 Return the (untranslated) helptxt of the user unit flag.
1292 **************************************************************************/
1293 const char *unit_type_flag_helptxt(enum unit_type_flag_id id)
1295 fc_assert(id >= UTYF_USER_FLAG_1 && id <= UTYF_LAST_USER_FLAG);
1297 return user_type_flags[id - UTYF_USER_FLAG_1].helptxt;
1300 /**************************************************************************
1301 Returns TRUE iff the unit type is unique and the player already has one.
1302 **************************************************************************/
1303 bool utype_player_already_has_this_unique(const struct player *pplayer,
1304 const struct unit_type *putype)
1306 if (!utype_has_flag(putype, UTYF_UNIQUE)) {
1307 /* This isn't a unique unit type. */
1308 return FALSE;
1311 unit_list_iterate(pplayer->units, existing_unit) {
1312 if (putype == unit_type_get(existing_unit)) {
1313 /* FIXME: This could be slow if we have lots of units. We could
1314 * consider keeping an array of unittypes updated with this info
1315 * instead. */
1317 return TRUE;
1319 } unit_list_iterate_end;
1321 /* The player doesn't already have one. */
1322 return FALSE;
1325 /**************************************************************************
1326 Whether player can build given unit somewhere,
1327 ignoring whether unit is obsolete and assuming the
1328 player has a coastal city.
1329 **************************************************************************/
1330 bool can_player_build_unit_direct(const struct player *p,
1331 const struct unit_type *punittype)
1333 fc_assert_ret_val(NULL != punittype, FALSE);
1335 if (is_barbarian(p)
1336 && !utype_has_role(punittype, L_BARBARIAN_BUILD)
1337 && !utype_has_role(punittype, L_BARBARIAN_BUILD_TECH)) {
1338 /* Barbarians can build only role units */
1339 return FALSE;
1342 if (utype_can_do_action(punittype, ACTION_NUKE)
1343 && get_player_bonus(p, EFT_ENABLE_NUKE) <= 0) {
1344 return FALSE;
1346 if (utype_has_flag(punittype, UTYF_NOBUILD)) {
1347 return FALSE;
1350 if (utype_has_flag(punittype, UTYF_BARBARIAN_ONLY)
1351 && !is_barbarian(p)) {
1352 /* Unit can be built by barbarians only and this player is
1353 * not barbarian */
1354 return FALSE;
1357 if (utype_has_flag(punittype, UTYF_NEWCITY_GAMES_ONLY)
1358 && game.scenario.prevent_new_cities) {
1359 /* Unit is usable only in games where founding of new cities is allowed. */
1360 return FALSE;
1363 if (punittype->need_government
1364 && punittype->need_government != government_of_player(p)) {
1365 return FALSE;
1367 if (research_invention_state(research_get(p),
1368 advance_number(punittype->require_advance))
1369 != TECH_KNOWN) {
1370 if (!is_barbarian(p)) {
1371 /* Normal players can never build units without knowing tech
1372 * requirements. */
1373 return FALSE;
1375 if (!utype_has_role(punittype, L_BARBARIAN_BUILD)) {
1376 /* Even barbarian cannot build this unit without tech */
1378 /* Unit has to have L_BARBARIAN_BUILD_TECH role
1379 * In the beginning of this function we checked that
1380 * barbarian player tries to build only role
1381 * L_BARBARIAN_BUILD or L_BARBARIAN_BUILD_TECH units. */
1382 fc_assert_ret_val(utype_has_role(punittype, L_BARBARIAN_BUILD_TECH),
1383 FALSE);
1385 /* Client does not know all the advances other players have
1386 * got. So following gives wrong answer in the client.
1387 * This is called at the client when received create_city
1388 * packet for a barbarian city. City initialization tries
1389 * to find L_FIRSTBUILD unit. */
1391 if (!game.info.global_advances[advance_index(punittype->require_advance)]) {
1392 /* Nobody knows required tech */
1393 return FALSE;
1398 if (utype_player_already_has_this_unique(p, punittype)) {
1399 /* A player can only have one unit of each unique unit type. */
1400 return FALSE;
1403 /* If the unit has a building requirement, we check to see if the player
1404 * can build that building. Note that individual cities may not have
1405 * that building, so they still may not be able to build the unit. */
1406 if (punittype->need_improvement) {
1407 if (is_great_wonder(punittype->need_improvement)
1408 && (great_wonder_is_built(punittype->need_improvement)
1409 || great_wonder_is_destroyed(punittype->need_improvement))) {
1410 /* It's already built great wonder */
1411 if (great_wonder_owner(punittype->need_improvement) != p) {
1412 /* Not owned by this player. Either destroyed or owned by somebody
1413 * else. */
1414 return FALSE;
1416 } else {
1417 if (!can_player_build_improvement_direct(p,
1418 punittype->need_improvement)) {
1419 return FALSE;
1424 return TRUE;
1427 /**************************************************************************
1428 Whether player can build given unit somewhere;
1429 returns FALSE if unit is obsolete.
1430 **************************************************************************/
1431 bool can_player_build_unit_now(const struct player *p,
1432 const struct unit_type *punittype)
1434 if (!can_player_build_unit_direct(p, punittype)) {
1435 return FALSE;
1437 while ((punittype = punittype->obsoleted_by) != U_NOT_OBSOLETED) {
1438 if (can_player_build_unit_direct(p, punittype)) {
1439 return FALSE;
1442 return TRUE;
1445 /**************************************************************************
1446 Whether player can _eventually_ build given unit somewhere -- ie,
1447 returns TRUE if unit is available with current tech OR will be available
1448 with future tech. Returns FALSE if unit is obsolete.
1449 **************************************************************************/
1450 bool can_player_build_unit_later(const struct player *p,
1451 const struct unit_type *punittype)
1453 fc_assert_ret_val(NULL != punittype, FALSE);
1454 if (utype_has_flag(punittype, UTYF_NOBUILD)) {
1455 return FALSE;
1457 while ((punittype = punittype->obsoleted_by) != U_NOT_OBSOLETED) {
1458 if (can_player_build_unit_direct(p, punittype)) {
1459 return FALSE;
1462 return TRUE;
1465 /**************************************************************************
1466 The following functions use static variables so we can quickly look up
1467 which unit types have given flag or role.
1468 For these functions flags and roles are considered to be in the same "space",
1469 and any "role" argument can also be a "flag".
1470 Unit order is in terms of the order in the units ruleset.
1471 **************************************************************************/
1472 static bool first_init = TRUE;
1473 static int n_with_role[MAX_UNIT_ROLES];
1474 static struct unit_type **with_role[MAX_UNIT_ROLES];
1476 /**************************************************************************
1477 Do the real work for role_unit_precalcs, for one role (or flag), given by i.
1478 **************************************************************************/
1479 static void precalc_one(int i,
1480 bool (*func_has)(const struct unit_type *, int))
1482 int j;
1484 /* Count: */
1485 fc_assert(n_with_role[i] == 0);
1486 unit_type_iterate(u) {
1487 if (func_has(u, i)) {
1488 n_with_role[i]++;
1490 } unit_type_iterate_end;
1492 if (n_with_role[i] > 0) {
1493 with_role[i] = fc_malloc(n_with_role[i] * sizeof(*with_role[i]));
1494 j = 0;
1495 unit_type_iterate(u) {
1496 if (func_has(u, i)) {
1497 with_role[i][j++] = u;
1499 } unit_type_iterate_end;
1500 fc_assert(j == n_with_role[i]);
1504 /****************************************************************************
1505 Free memory allocated by role_unit_precalcs().
1506 ****************************************************************************/
1507 void role_unit_precalcs_free(void)
1509 int i;
1511 for (i = 0; i < MAX_UNIT_ROLES; i++) {
1512 free(with_role[i]);
1513 with_role[i] = NULL;
1514 n_with_role[i] = 0;
1518 /****************************************************************************
1519 Initialize; it is safe to call this multiple times (e.g., if units have
1520 changed due to rulesets in client).
1521 ****************************************************************************/
1522 void role_unit_precalcs(void)
1524 int i;
1526 if (first_init) {
1527 for (i = 0; i < MAX_UNIT_ROLES; i++) {
1528 with_role[i] = NULL;
1529 n_with_role[i] = 0;
1531 } else {
1532 role_unit_precalcs_free();
1535 for (i = 0; i <= UTYF_LAST_USER_FLAG; i++) {
1536 precalc_one(i, utype_has_flag);
1538 for (i = L_FIRST; i < L_LAST; i++) {
1539 precalc_one(i, utype_has_role);
1541 for (i = L_LAST; i < MAX_UNIT_ROLES; i++) {
1542 precalc_one(i, utype_can_do_action_role);
1544 first_init = FALSE;
1547 /**************************************************************************
1548 How many unit types have specified role/flag.
1549 **************************************************************************/
1550 int num_role_units(int role)
1552 fc_assert_ret_val((role >= 0 && role <= UTYF_LAST_USER_FLAG)
1553 || (role >= L_FIRST && role < L_LAST)
1554 || (role >= L_LAST && role < MAX_UNIT_ROLES), -1);
1555 fc_assert_ret_val(!first_init, -1);
1556 return n_with_role[role];
1559 /**************************************************************************
1560 Iterate over all the role units and feed them to callback.
1561 Once callback returns TRUE, no further units are feeded to it and
1562 we return the unit that caused callback to return TRUE
1563 **************************************************************************/
1564 struct unit_type *role_units_iterate(int role, role_unit_callback cb, void *data)
1566 int i;
1568 for (i = 0; i < n_with_role[role]; i++) {
1569 if (cb(with_role[role][i], data)) {
1570 return with_role[role][i];
1574 return NULL;
1577 /**************************************************************************
1578 Iterate over all the role units and feed them to callback, starting
1579 from the last one.
1580 Once callback returns TRUE, no further units are feeded to it and
1581 we return the unit that caused callback to return TRUE
1582 **************************************************************************/
1583 struct unit_type *role_units_iterate_backwards(int role, role_unit_callback cb, void *data)
1585 int i;
1587 for (i = n_with_role[role] - 1; i >= 0; i--) {
1588 if (cb(with_role[role][i], data)) {
1589 return with_role[role][i];
1593 return NULL;
1596 /**************************************************************************
1597 Return index-th unit with specified role/flag.
1598 Index -1 means (n-1), ie last one.
1599 **************************************************************************/
1600 struct unit_type *get_role_unit(int role, int role_index)
1602 fc_assert_ret_val((role >= 0 && role <= UTYF_LAST_USER_FLAG)
1603 || (role >= L_FIRST && role < L_LAST)
1604 || (role >= L_LAST && role < MAX_UNIT_ROLES), NULL);
1605 fc_assert_ret_val(!first_init, NULL);
1606 if (role_index == -1) {
1607 role_index = n_with_role[role] - 1;
1609 fc_assert_ret_val(role_index >= 0 && role_index < n_with_role[role], NULL);
1611 return with_role[role][role_index];
1614 /**************************************************************************
1615 Return "best" unit this city can build, with given role/flag.
1616 Returns NULL if none match. "Best" means highest unit type id.
1617 **************************************************************************/
1618 struct unit_type *best_role_unit(const struct city *pcity, int role)
1620 struct unit_type *u;
1621 int j;
1623 fc_assert_ret_val((role >= 0 && role <= UTYF_LAST_USER_FLAG)
1624 || (role >= L_FIRST && role < L_LAST)
1625 || (role >= L_LAST && role < MAX_UNIT_ROLES), NULL);
1626 fc_assert_ret_val(!first_init, NULL);
1628 for (j = n_with_role[role] - 1; j >= 0; j--) {
1629 u = with_role[role][j];
1630 if ((1 != utype_fuel(u) || uclass_has_flag(utype_class(u), UCF_MISSILE))
1631 && can_city_build_unit_now(pcity, u)) {
1632 /* Allow fuel == 1 units when pathfinding can handle them. */
1633 return u;
1637 return NULL;
1640 /**************************************************************************
1641 Return "best" unit the player can build, with given role/flag.
1642 Returns NULL if none match. "Best" means highest unit type id.
1644 TODO: Cache the result per player?
1645 **************************************************************************/
1646 struct unit_type *best_role_unit_for_player(const struct player *pplayer,
1647 int role)
1649 int j;
1651 fc_assert_ret_val((role >= 0 && role <= UTYF_LAST_USER_FLAG)
1652 || (role >= L_FIRST && role < L_LAST)
1653 || (role >= L_LAST && role < MAX_UNIT_ROLES), NULL);
1654 fc_assert_ret_val(!first_init, NULL);
1656 for (j = n_with_role[role] - 1; j >= 0; j--) {
1657 struct unit_type *utype = with_role[role][j];
1659 if (can_player_build_unit_now(pplayer, utype)) {
1660 return utype;
1664 return NULL;
1667 /**************************************************************************
1668 Return first unit the player can build, with given role/flag.
1669 Returns NULL if none match. Used eg when placing starting units.
1670 **************************************************************************/
1671 struct unit_type *first_role_unit_for_player(const struct player *pplayer,
1672 int role)
1674 int j;
1676 fc_assert_ret_val((role >= 0 && role <= UTYF_LAST_USER_FLAG)
1677 || (role >= L_FIRST && role < L_LAST)
1678 || (role >= L_LAST && role < MAX_UNIT_ROLES), NULL);
1679 fc_assert_ret_val(!first_init, NULL);
1681 for (j = 0; j < n_with_role[role]; j++) {
1682 struct unit_type *utype = with_role[role][j];
1684 if (can_player_build_unit_now(pplayer, utype)) {
1685 return utype;
1689 return NULL;
1692 /****************************************************************************
1693 Inialize unit-type structures.
1694 ****************************************************************************/
1695 void unit_types_init(void)
1697 int i;
1699 /* Can't use unit_type_iterate or utype_by_number here because
1700 * num_unit_types isn't known yet. */
1701 for (i = 0; i < ARRAY_SIZE(unit_types); i++) {
1702 unit_types[i].item_number = i;
1703 unit_types[i].helptext = NULL;
1704 unit_types[i].veteran = NULL;
1705 unit_types[i].bonuses = combat_bonus_list_new();
1706 unit_types[i].disabled = FALSE;
1710 /**************************************************************************
1711 Frees the memory associated with this unit type.
1712 **************************************************************************/
1713 static void unit_type_free(struct unit_type *punittype)
1715 if (NULL != punittype->helptext) {
1716 strvec_destroy(punittype->helptext);
1717 punittype->helptext = NULL;
1720 veteran_system_destroy(punittype->veteran);
1721 combat_bonus_list_iterate(punittype->bonuses, pbonus) {
1722 FC_FREE(pbonus);
1723 } combat_bonus_list_iterate_end;
1724 combat_bonus_list_destroy(punittype->bonuses);
1727 /***************************************************************
1728 Frees the memory associated with all unit types.
1729 ***************************************************************/
1730 void unit_types_free(void)
1732 int i;
1734 /* Can't use unit_type_iterate or utype_by_number here because
1735 * we want to free what unit_types_init() has allocated. */
1736 for (i = 0; i < ARRAY_SIZE(unit_types); i++) {
1737 unit_type_free(unit_types + i);
1741 /***************************************************************
1742 Frees the memory associated with all unit type flags
1743 ***************************************************************/
1744 void unit_type_flags_free(void)
1746 int i;
1748 for (i = 0; i < MAX_NUM_USER_UNIT_FLAGS; i++) {
1749 user_flag_free(&user_type_flags[i]);
1753 /***************************************************************
1754 Frees the memory associated with all unit class flags
1755 ***************************************************************/
1756 void unit_class_flags_free(void)
1758 int i;
1760 for (i = 0; i < MAX_NUM_USER_UCLASS_FLAGS; i++) {
1761 user_flag_free(&user_class_flags[i]);
1765 /**************************************************************************
1766 Return the first item of unit_classes.
1767 **************************************************************************/
1768 struct unit_class *unit_class_array_first(void)
1770 if (game.control.num_unit_classes > 0) {
1771 return unit_classes;
1773 return NULL;
1776 /**************************************************************************
1777 Return the last item of unit_classes.
1778 **************************************************************************/
1779 const struct unit_class *unit_class_array_last(void)
1781 if (game.control.num_unit_classes > 0) {
1782 return &unit_classes[game.control.num_unit_classes - 1];
1784 return NULL;
1787 /**************************************************************************
1788 Return the unit_class count.
1789 **************************************************************************/
1790 Unit_Class_id uclass_count(void)
1792 return game.control.num_unit_classes;
1795 #ifndef uclass_index
1796 /**************************************************************************
1797 Return the unit_class index.
1799 Currently same as uclass_number(), paired with uclass_count()
1800 indicates use as an array index.
1801 **************************************************************************/
1802 Unit_Class_id uclass_index(const struct unit_class *pclass)
1804 fc_assert_ret_val(pclass, -1);
1805 return pclass - unit_classes;
1807 #endif /* uclass_index */
1809 /**************************************************************************
1810 Return the unit_class index.
1811 **************************************************************************/
1812 Unit_Class_id uclass_number(const struct unit_class *pclass)
1814 fc_assert_ret_val(pclass, -1);
1815 return pclass->item_number;
1818 /****************************************************************************
1819 Returns unit class pointer for an ID value.
1820 ****************************************************************************/
1821 struct unit_class *uclass_by_number(const Unit_Class_id id)
1823 if (id < 0 || id >= game.control.num_unit_classes) {
1824 return NULL;
1826 return &unit_classes[id];
1829 #ifndef utype_class
1830 /***************************************************************
1831 Returns unit class pointer for a unit type.
1832 ***************************************************************/
1833 struct unit_class *utype_class(const struct unit_type *punittype)
1835 fc_assert(NULL != punittype->uclass);
1836 return punittype->uclass;
1838 #endif /* utype_class */
1840 /***************************************************************
1841 Returns unit class pointer for a unit.
1842 ***************************************************************/
1843 struct unit_class *unit_class_get(const struct unit *punit)
1845 return utype_class(unit_type_get(punit));
1848 /****************************************************************************
1849 Initialize unit_class structures.
1850 ****************************************************************************/
1851 void unit_classes_init(void)
1853 int i;
1855 /* Can't use unit_class_iterate or uclass_by_number here because
1856 * num_unit_classes isn't known yet. */
1857 for (i = 0; i < ARRAY_SIZE(unit_classes); i++) {
1858 unit_classes[i].item_number = i;
1859 unit_classes[i].cache.refuel_bases = NULL;
1860 unit_classes[i].cache.native_tile_extras = NULL;
1861 unit_classes[i].cache.bonus_roads = NULL;
1862 unit_classes[i].cache.subset_movers = NULL;
1863 unit_classes[i].helptext = NULL;
1864 unit_classes[i].disabled = FALSE;
1868 /****************************************************************************
1869 Free resources allocated for unit classes.
1870 ****************************************************************************/
1871 void unit_classes_free(void)
1873 int i;
1875 for (i = 0; i < ARRAY_SIZE(unit_classes); i++) {
1876 if (unit_classes[i].cache.refuel_bases != NULL) {
1877 extra_type_list_destroy(unit_classes[i].cache.refuel_bases);
1878 unit_classes[i].cache.refuel_bases = NULL;
1880 if (unit_classes[i].cache.native_tile_extras != NULL) {
1881 extra_type_list_destroy(unit_classes[i].cache.native_tile_extras);
1882 unit_classes[i].cache.native_tile_extras = NULL;
1884 if (unit_classes[i].cache.bonus_roads != NULL) {
1885 extra_type_list_destroy(unit_classes[i].cache.bonus_roads);
1886 unit_classes[i].cache.bonus_roads = NULL;
1888 if (unit_classes[i].cache.subset_movers != NULL) {
1889 unit_class_list_destroy(unit_classes[i].cache.subset_movers);
1891 if (unit_classes[i].helptext != NULL) {
1892 strvec_destroy(unit_classes[i].helptext);
1893 unit_classes[i].helptext = NULL;
1898 /****************************************************************************
1899 Return veteran system used for this unit type.
1900 ****************************************************************************/
1901 const struct veteran_system *
1902 utype_veteran_system(const struct unit_type *punittype)
1904 fc_assert_ret_val(punittype != NULL, NULL);
1906 if (punittype->veteran) {
1907 return punittype->veteran;
1910 fc_assert_ret_val(game.veteran != NULL, NULL);
1911 return game.veteran;
1914 /****************************************************************************
1915 Return veteran level properties of given unit in given veterancy level.
1916 ****************************************************************************/
1917 const struct veteran_level *
1918 utype_veteran_level(const struct unit_type *punittype, int level)
1920 const struct veteran_system *vsystem = utype_veteran_system(punittype);
1922 fc_assert_ret_val(vsystem != NULL, NULL);
1923 fc_assert_ret_val(vsystem->definitions != NULL, NULL);
1924 fc_assert_ret_val(vsystem->levels > level, NULL);
1926 return (vsystem->definitions + level);
1929 /****************************************************************************
1930 Return translated name of the given veteran level.
1931 NULL if this unit type doesn't have different veteran levels.
1932 ****************************************************************************/
1933 const char *utype_veteran_name_translation(const struct unit_type *punittype,
1934 int level)
1936 if (utype_veteran_levels(punittype) <= 1) {
1937 return NULL;
1938 } else {
1939 const struct veteran_level *vlvl = utype_veteran_level(punittype, level);
1941 return name_translation_get(&vlvl->name);
1945 /****************************************************************************
1946 Return veteran levels of the given unit type.
1947 ****************************************************************************/
1948 int utype_veteran_levels(const struct unit_type *punittype)
1950 const struct veteran_system *vsystem = utype_veteran_system(punittype);
1952 fc_assert_ret_val(vsystem != NULL, 1);
1954 return vsystem->levels;
1957 /****************************************************************************
1958 Return whether this unit type's veteran system, if any, confers a power
1959 factor bonus at any level (it could just add extra moves).
1960 ****************************************************************************/
1961 bool utype_veteran_has_power_bonus(const struct unit_type *punittype)
1963 int i, initial_power_fact = utype_veteran_level(punittype, 0)->power_fact;
1964 for (i = 1; i < utype_veteran_levels(punittype); i++) {
1965 if (utype_veteran_level(punittype, i)->power_fact > initial_power_fact) {
1966 return TRUE;
1969 return FALSE;
1972 /****************************************************************************
1973 Allocate new veteran system structure with given veteran level count.
1974 ****************************************************************************/
1975 struct veteran_system *veteran_system_new(int count)
1977 struct veteran_system *vsystem;
1979 /* There must be at least one level. */
1980 fc_assert_ret_val(count > 0, NULL);
1982 vsystem = fc_calloc(1, sizeof(*vsystem));
1983 vsystem->levels = count;
1984 vsystem->definitions = fc_calloc(vsystem->levels,
1985 sizeof(*vsystem->definitions));
1987 return vsystem;
1990 /****************************************************************************
1991 Free veteran system
1992 ****************************************************************************/
1993 void veteran_system_destroy(struct veteran_system *vsystem)
1995 if (vsystem) {
1996 if (vsystem->definitions) {
1997 free(vsystem->definitions);
1999 free(vsystem);
2003 /****************************************************************************
2004 Fill veteran level in given veteran system with given information.
2005 ****************************************************************************/
2006 void veteran_system_definition(struct veteran_system *vsystem, int level,
2007 const char *vlist_name, int vlist_power,
2008 int vlist_move, int vlist_raise,
2009 int vlist_wraise)
2011 struct veteran_level *vlevel;
2013 fc_assert_ret(vsystem != NULL);
2014 fc_assert_ret(vsystem->levels > level);
2016 vlevel = vsystem->definitions + level;
2018 names_set(&vlevel->name, NULL, vlist_name, NULL);
2019 vlevel->power_fact = vlist_power;
2020 vlevel->move_bonus = vlist_move;
2021 vlevel->raise_chance = vlist_raise;
2022 vlevel->work_raise_chance = vlist_wraise;
2025 /**************************************************************************
2026 Return pointer to ai data of given unit type and ai type.
2027 **************************************************************************/
2028 void *utype_ai_data(const struct unit_type *ptype, const struct ai_type *ai)
2030 return ptype->ais[ai_type_number(ai)];
2033 /**************************************************************************
2034 Attach ai data to unit type
2035 **************************************************************************/
2036 void utype_set_ai_data(struct unit_type *ptype, const struct ai_type *ai,
2037 void *data)
2039 ptype->ais[ai_type_number(ai)] = data;
2042 /****************************************************************************
2043 Set caches for unit class.
2044 ****************************************************************************/
2045 void set_unit_class_caches(struct unit_class *pclass)
2047 pclass->cache.refuel_bases = extra_type_list_new();
2048 pclass->cache.native_tile_extras = extra_type_list_new();
2049 pclass->cache.bonus_roads = extra_type_list_new();
2050 pclass->cache.subset_movers = unit_class_list_new();
2052 extra_type_iterate(pextra) {
2053 if (is_native_extra_to_uclass(pextra, pclass)) {
2054 struct road_type *proad = extra_road_get(pextra);
2056 if (extra_has_flag(pextra, EF_REFUEL)) {
2057 extra_type_list_append(pclass->cache.refuel_bases, pextra);
2059 if (extra_has_flag(pextra, EF_NATIVE_TILE)) {
2060 extra_type_list_append(pclass->cache.native_tile_extras, pextra);
2062 if (proad != NULL && road_provides_move_bonus(proad)) {
2063 extra_type_list_append(pclass->cache.bonus_roads, pextra);
2066 } extra_type_iterate_end;
2068 unit_class_iterate(pcharge) {
2069 bool subset_mover = TRUE;
2071 terrain_type_iterate(pterrain) {
2072 if (BV_ISSET(pterrain->native_to, uclass_index(pcharge))
2073 && !BV_ISSET(pterrain->native_to, uclass_index(pclass))) {
2074 subset_mover = FALSE;
2076 } terrain_type_iterate_end;
2078 if (subset_mover) {
2079 extra_type_iterate(pextra) {
2080 if (is_native_extra_to_uclass(pextra, pcharge)
2081 && !is_native_extra_to_uclass(pextra, pclass)) {
2082 subset_mover = FALSE;
2084 } extra_type_list_iterate_end;
2087 if (subset_mover) {
2088 unit_class_list_append(pclass->cache.subset_movers, pcharge);
2090 } unit_class_iterate_end;
2093 /****************************************************************************
2094 Set caches for unit types.
2095 ****************************************************************************/
2096 void set_unit_type_caches(struct unit_type *ptype)
2098 ptype->cache.max_defense_mp = -FC_INFINITY;
2100 unit_type_iterate(utype) {
2101 int idx = utype_index(utype);
2103 ptype->cache.defense_mp_bonuses[idx] = combat_bonus_against(ptype->bonuses, utype,
2104 CBONUS_DEFENSE_MULTIPLIER);
2105 if (ptype->cache.defense_mp_bonuses[idx] > ptype->cache.max_defense_mp) {
2106 ptype->cache.max_defense_mp = ptype->cache.defense_mp_bonuses[idx];
2108 } unit_type_iterate_end;
2111 /**************************************************************************
2112 What move types nativity of this extra will give?
2113 **************************************************************************/
2114 static enum unit_move_type move_type_from_extra(struct extra_type *pextra,
2115 struct unit_class *puc)
2117 bool land_allowed = TRUE;
2118 bool sea_allowed = TRUE;
2120 if (!extra_has_flag(pextra, EF_NATIVE_TILE)) {
2121 return unit_move_type_invalid();
2123 if (!is_native_extra_to_uclass(pextra, puc)) {
2124 return unit_move_type_invalid();
2127 if (is_extra_caused_by(pextra, EC_ROAD)
2128 && road_has_flag(extra_road_get(pextra), RF_RIVER)) {
2129 /* Natural rivers are created to land only */
2130 sea_allowed = FALSE;
2133 requirement_vector_iterate(&pextra->reqs, preq) {
2134 if (preq->source.kind == VUT_TERRAINCLASS) {
2135 if (!preq->present) {
2136 if (preq->source.value.terrainclass == TC_LAND) {
2137 land_allowed = FALSE;
2138 } else if (preq->source.value.terrainclass == TC_OCEAN) {
2139 sea_allowed = FALSE;
2141 } else {
2142 if (preq->source.value.terrainclass == TC_LAND) {
2143 sea_allowed = FALSE;
2144 } else if (preq->source.value.terrainclass == TC_OCEAN) {
2145 land_allowed = FALSE;
2148 } else if (preq->source.kind == VUT_TERRAIN) {
2149 if (!preq->present) {
2150 if (preq->source.value.terrain->tclass == TC_LAND) {
2151 land_allowed = FALSE;
2152 } else if (preq->source.value.terrain->tclass == TC_OCEAN) {
2153 sea_allowed = FALSE;
2155 } else {
2156 if (preq->source.value.terrain->tclass == TC_LAND) {
2157 sea_allowed = FALSE;
2158 } else if (preq->source.value.terrain->tclass == TC_OCEAN) {
2159 land_allowed = FALSE;
2163 } requirement_vector_iterate_end;
2165 if (land_allowed && sea_allowed) {
2166 return UMT_BOTH;
2168 if (land_allowed && !sea_allowed) {
2169 return UMT_LAND;
2171 if (!land_allowed && sea_allowed) {
2172 return UMT_SEA;
2175 return unit_move_type_invalid();
2178 /****************************************************************************
2179 Set move_type for unit class.
2180 ****************************************************************************/
2181 void set_unit_move_type(struct unit_class *puclass)
2183 bool land_moving = FALSE;
2184 bool sea_moving = FALSE;
2186 extra_type_iterate(pextra) {
2187 enum unit_move_type eut = move_type_from_extra(pextra, puclass);
2189 if (eut == UMT_BOTH) {
2190 land_moving = TRUE;
2191 sea_moving = TRUE;
2192 } else if (eut == UMT_LAND) {
2193 land_moving = TRUE;
2194 } else if (eut == UMT_SEA) {
2195 sea_moving = TRUE;
2197 } extra_type_iterate_end;
2199 terrain_type_iterate(pterrain) {
2200 if (is_native_to_class(puclass, pterrain, NULL)) {
2201 if (is_ocean(pterrain)) {
2202 sea_moving = TRUE;
2203 } else {
2204 land_moving = TRUE;
2207 } terrain_type_iterate_end;
2209 if (land_moving && sea_moving) {
2210 puclass->move_type = UMT_BOTH;
2211 } else if (sea_moving) {
2212 puclass->move_type = UMT_SEA;
2213 } else {
2214 /* If unit has no native terrains, it is considered land moving */
2215 puclass->move_type = UMT_LAND;
2219 /****************************************************************************
2220 Is cityfounder type
2221 ****************************************************************************/
2222 bool utype_is_cityfounder(struct unit_type *utype)
2224 if (game.scenario.prevent_new_cities) {
2225 /* No unit is allowed to found new cities */
2226 return FALSE;
2229 return utype_can_do_action(utype, ACTION_FOUND_CITY);