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)
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 ***********************************************************************/
15 #include <fc_config.h>
21 #include "bitvector.h"
31 #include "diptreaty.h"
32 #include "government.h"
35 #include "multipliers.h"
44 /* common/scriptcore */
45 #include "luascript_types.h"
49 #include "barbarian.h"
50 #include "citytools.h"
52 #include "connecthand.h"
61 #include "stdinhand.h"
62 #include "spaceship.h"
63 #include "spacerace.h"
64 #include "techtools.h"
65 #include "unittools.h"
70 #include "autosettlers.h"
72 /* server/scripting */
73 #include "script_server.h"
77 #include "difficulty.h"
78 #include "handicaps.h"
83 static void package_player_common(struct player
*plr
,
84 struct packet_player_info
*packet
);
86 static void package_player_diplstate(struct player
*plr1
,
88 struct packet_player_diplstate
*packet_ds
,
89 struct player
*receiver
,
90 enum plr_info_level min_info_level
);
91 static void package_player_info(struct player
*plr
,
92 struct packet_player_info
*packet
,
93 struct player
*receiver
,
94 enum plr_info_level min_info_level
);
95 static enum plr_info_level
player_info_level(struct player
*plr
,
96 struct player
*receiver
);
98 static void send_player_remove_info_c(const struct player_slot
*pslot
,
99 struct conn_list
*dest
);
100 static void send_player_info_c_real(struct player
*src
,
101 struct conn_list
*dest
);
102 static void send_player_diplstate_c_real(struct player
*src
,
103 struct conn_list
*dest
);
105 static void send_nation_availability_real(struct conn_list
*dest
,
106 bool nationset_change
);
108 /* Used by shuffle_players() and shuffled_player(). */
109 static int shuffled_order
[MAX_NUM_PLAYER_SLOTS
];
111 /* Used by player_info_freeze() and player_info_thaw(). */
112 static int player_info_frozen_level
= 0;
114 /**************************************************************************
115 Murder a player in cold blood.
117 Called from srv_main kill_dying_players() and edit packet handler
118 handle_edit_player_remove().
119 **************************************************************************/
120 void kill_player(struct player
*pplayer
)
123 struct player
*barbarians
= NULL
;
125 pplayer
->is_alive
= FALSE
;
127 /* reset player status */
128 player_status_reset(pplayer
);
130 /* Remove shared vision from dead player to friends. */
131 players_iterate(aplayer
) {
132 if (gives_shared_vision(pplayer
, aplayer
)) {
133 remove_shared_vision(pplayer
, aplayer
);
135 } players_iterate_end
;
137 cancel_all_meetings(pplayer
);
139 /* Show entire map for players who are *not* in a team if revealmap is set
140 * to REVEAL_MAP_DEAD. */
141 if (game
.server
.revealmap
& REVEAL_MAP_DEAD
142 && player_list_size(team_members(pplayer
->team
)) == 1) {
143 map_know_and_see_all(pplayer
);
146 if (!is_barbarian(pplayer
)) {
147 notify_player(NULL
, NULL
, E_DESTROYED
, ftc_server
,
148 _("The %s are no more!"),
149 nation_plural_for_player(pplayer
));
152 /* Transfer back all cities not originally owned by player to their
153 rightful owners, if they are still around */
154 save_palace
= game
.server
.savepalace
;
155 game
.server
.savepalace
= FALSE
; /* moving it around is dumb */
156 city_list_iterate_safe(pplayer
->cities
, pcity
) {
157 if (pcity
->original
!= pplayer
&& pcity
->original
->is_alive
) {
158 /* Transfer city to original owner, kill all its units outside of
159 a radius of 3, give verbose messages of every unit transferred,
160 and raze buildings according to raze chance (also removes palace) */
161 if (transfer_city(pcity
->original
, pcity
, 3, TRUE
, TRUE
, TRUE
,
163 script_server_signal_emit("city_transferred", 4,
164 API_TYPE_CITY
, pcity
,
165 API_TYPE_PLAYER
, pplayer
,
166 API_TYPE_PLAYER
, pcity
->original
,
167 API_TYPE_STRING
, "death-back_to_original");
170 } city_list_iterate_safe_end
;
171 game
.server
.savepalace
= save_palace
;
173 /* let there be civil war */
174 if (game
.info
.gameloss_style
& GAMELOSS_STYLE_CWAR
) {
175 if (city_list_size(pplayer
->cities
) >= 2 + MIN(GAME_MIN_CIVILWARSIZE
, 2)) {
176 log_verbose("Civil war strikes the remaining empire of %s",
178 /* out of sheer cruelty we reanimate the player
179 * so he can behold what happens to his empire */
180 pplayer
->is_alive
= TRUE
;
181 (void) civil_war(pplayer
);
183 log_verbose("The empire of %s is too small for civil war.",
187 pplayer
->is_alive
= FALSE
;
189 if (game
.info
.gameloss_style
& GAMELOSS_STYLE_BARB
) {
190 /* if parameter, create a barbarian, if possible */
191 barbarians
= create_barbarian_player(LAND_BARBARIAN
);
194 /* if there are barbarians around, they will take the remaining cities */
197 /* Moving victim's palace around is a waste of time, as they're dead */
198 bool palace
= game
.server
.savepalace
;
200 game
.server
.savepalace
= FALSE
;
202 log_verbose("Barbarians take the empire of %s", pplayer
->name
);
203 adv_data_phase_init(barbarians
, TRUE
);
205 /* Transfer any remaining cities */
206 city_list_iterate_safe(pplayer
->cities
, pcity
) {
207 if (transfer_city(barbarians
, pcity
, -1, FALSE
, FALSE
, FALSE
,
209 script_server_signal_emit("city_transferred", 4,
210 API_TYPE_CITY
, pcity
,
211 API_TYPE_PLAYER
, pplayer
,
212 API_TYPE_PLAYER
, barbarians
,
213 API_TYPE_STRING
, "death-barbarians_get");
215 } city_list_iterate_safe_end
;
217 game
.server
.savepalace
= palace
;
219 resolve_unit_stacks(pplayer
, barbarians
, FALSE
);
221 /* Barbarians don't get free buildings like Palaces, so we don't
222 * call city_build_free_buildings().
223 * FIXME: maybe this should be a ruleset option? */
225 /* Destroy any remaining cities */
226 city_list_iterate(pplayer
->cities
, pcity
) {
228 } city_list_iterate_end
;
231 /* Remove all units that are still ours */
232 unit_list_iterate_safe(pplayer
->units
, punit
) {
233 wipe_unit(punit
, ULR_PLAYER_DIED
, NULL
);
234 } unit_list_iterate_safe_end
;
236 /* Remove ownership of tiles */
237 whole_map_iterate(&(wld
.map
), ptile
) {
238 if (tile_owner(ptile
) == pplayer
) {
239 map_claim_ownership(ptile
, NULL
, NULL
, FALSE
);
241 if (extra_owner(ptile
) == pplayer
) {
242 ptile
->extras_owner
= NULL
;
244 } whole_map_iterate_end
;
246 /* Ensure this dead player doesn't win with a spaceship.
247 * Now that would be truly unbelievably dumb - Per */
248 spaceship_init(&pplayer
->spaceship
);
249 send_spaceship_info(pplayer
, NULL
);
251 send_player_info_c(pplayer
, game
.est_connections
);
254 /**************************************************************************
255 Return player maxrate in legal range.
256 **************************************************************************/
257 static int get_player_maxrate(struct player
*pplayer
)
259 int maxrate
= get_player_bonus(pplayer
, EFT_MAX_RATES
);
262 return 100; /* effects not initialized yet */
265 /* 34 + 33 + 33 = 100 */
266 return CLIP(34, maxrate
, 100);
269 /**************************************************************************
270 Handle a client or AI request to change the tax/luxury/science rates.
271 This function does full sanity checking.
272 **************************************************************************/
273 void handle_player_rates(struct player
*pplayer
,
274 int tax
, int luxury
, int science
)
278 if (S_S_RUNNING
!= server_state()) {
279 log_error("received player_rates packet from %s before start",
280 player_name(pplayer
));
281 notify_player(pplayer
, NULL
, E_BAD_COMMAND
, ftc_server
,
282 _("Cannot change rates before game start."));
286 if (tax
+ luxury
+ science
!= 100) {
289 if (tax
< 0 || tax
> 100 || luxury
< 0 || luxury
> 100 || science
< 0
293 maxrate
= get_player_maxrate(pplayer
);
294 if (tax
> maxrate
|| luxury
> maxrate
|| science
> maxrate
) {
299 } else if (luxury
> maxrate
) {
302 rtype
= _("Science");
305 notify_player(pplayer
, NULL
, E_BAD_COMMAND
, ftc_server
,
306 _("%s rate exceeds the max rate for %s."),
308 government_name_for_player(pplayer
));
310 pplayer
->economic
.tax
= tax
;
311 pplayer
->economic
.luxury
= luxury
;
312 pplayer
->economic
.science
= science
;
314 city_refresh_for_player(pplayer
);
315 send_player_info_c(pplayer
, pplayer
->connections
);
319 /**************************************************************************
320 Finish the revolution and set the player's government. Call this as soon
321 as the player has set a target_government and the revolution_finishes
323 **************************************************************************/
324 void government_change(struct player
*pplayer
, struct government
*gov
,
325 bool revolution_finished
)
327 struct research
*presearch
;
329 if (revolution_finished
) {
330 fc_assert_ret(pplayer
->target_government
331 != game
.government_during_revolution
332 && NULL
!= pplayer
->target_government
);
333 fc_assert_ret(pplayer
->revolution_finishes
<= game
.info
.turn
);
335 gov
->changed_to_times
++;
338 pplayer
->government
= gov
;
339 pplayer
->target_government
= NULL
;
341 if (revolution_finished
) {
342 log_debug("Revolution finished for %s. Government is %s. "
343 "Revofin %d (%d).", player_name(pplayer
),
344 government_rule_name(gov
),
345 pplayer
->revolution_finishes
, game
.info
.turn
);
348 notify_player(pplayer
, NULL
, E_REVOLT_DONE
, ftc_server
,
349 _("%s now governs the %s as a %s."),
350 player_name(pplayer
),
351 nation_plural_for_player(pplayer
),
352 government_name_translation(gov
));
354 if (is_human(pplayer
)) {
355 /* Keep luxuries if we have any. Try to max out science. -GJW */
356 int max
= get_player_maxrate(pplayer
);
358 /* only change rates if one exceeds the maximal rate */
359 if (pplayer
->economic
.science
> max
|| pplayer
->economic
.tax
> max
360 || pplayer
->economic
.luxury
> max
) {
361 int save_science
= pplayer
->economic
.science
;
362 int save_tax
= pplayer
->economic
.tax
;
363 int save_luxury
= pplayer
->economic
.luxury
;
365 pplayer
->economic
.science
= MIN(100 - pplayer
->economic
.luxury
, max
);
366 pplayer
->economic
.tax
= MIN(100 - pplayer
->economic
.luxury
367 - pplayer
->economic
.science
, max
);
368 pplayer
->economic
.luxury
= 100 - pplayer
->economic
.science
369 - pplayer
->economic
.tax
;
371 notify_player(pplayer
, NULL
, E_REVOLT_DONE
, ftc_server
,
372 _("The tax rates for the %s are changed from "
373 "%3d%%/%3d%%/%3d%% (tax/luxury/science) to "
374 "%3d%%/%3d%%/%3d%%."),
375 nation_plural_for_player(pplayer
),
376 save_tax
, save_luxury
, save_science
,
377 pplayer
->economic
.tax
, pplayer
->economic
.luxury
,
378 pplayer
->economic
.science
);
382 check_player_max_rates(pplayer
);
383 city_refresh_for_player(pplayer
);
384 send_player_info_c(pplayer
, pplayer
->connections
);
386 presearch
= research_get(pplayer
);
387 research_update(presearch
);
388 send_research_info(presearch
, NULL
);
391 /**************************************************************************
392 Get length of a revolution.
393 **************************************************************************/
394 int revolution_length(struct government
*gov
, struct player
*plr
)
398 if (!untargeted_revolution_allowed()
399 && gov
== game
.government_during_revolution
) {
400 /* Targetless revolution not acceptable */
401 notify_player(plr
, NULL
, E_REVOLT_DONE
, ftc_server
,
402 _("You can't revolt without selecting target government."));
406 turns
= GAME_DEFAULT_REVOLUTION_LENGTH
; /* To avoid compiler warning */
407 switch (game
.info
.revolentype
) {
409 turns
= game
.server
.revolution_length
;
412 turns
= fc_rand(game
.server
.revolution_length
) + 1;
414 case REVOLEN_QUICKENING
:
415 case REVOLEN_RANDQUICK
:
416 turns
= game
.server
.revolution_length
- gov
->changed_to_times
;
417 turns
= MAX(1, turns
);
418 if (game
.info
.revolentype
== REVOLEN_RANDQUICK
) {
419 turns
= fc_rand(turns
) + 1;
427 /**************************************************************************
428 Called by the client or AI to change government.
429 **************************************************************************/
430 void handle_player_change_government(struct player
*pplayer
,
431 Government_type_id government
)
434 struct government
*gov
= government_by_number(government
);
437 if (!gov
|| !can_change_to_government(pplayer
, gov
)) {
441 log_debug("Government changed for %s. Target government is %s; "
442 "old %s. Revofin %d, Turn %d.", player_name(pplayer
),
443 government_rule_name(gov
),
444 government_rule_name(government_of_player(pplayer
)),
445 pplayer
->revolution_finishes
, game
.info
.turn
);
447 anarchy
= get_player_bonus(pplayer
, EFT_NO_ANARCHY
) <= 0;
449 /* Set revolution_finishes value. */
450 if (pplayer
->revolution_finishes
> 0) {
451 /* Player already has an active revolution. Note that the finish time
452 * may be in the future (we're waiting for it to finish), the current
453 * turn (it just finished - but isn't reset until the end of the turn)
454 * or even in the past (if the player is in anarchy and hasn't chosen
456 turns
= pplayer
->revolution_finishes
- game
.info
.turn
;
457 } else if ((is_ai(pplayer
) && !has_handicap(pplayer
, H_REVOLUTION
))
459 /* AI players without the H_REVOLUTION handicap can skip anarchy */
462 turns
= revolution_length(gov
, pplayer
);
468 if (anarchy
&& turns
<= 0
469 && pplayer
->government
!= game
.government_during_revolution
) {
470 /* Multiple changes attempted after single anarchy period */
471 if (game
.info
.revolentype
== REVOLEN_QUICKENING
) {
472 notify_player(pplayer
, NULL
, E_REVOLT_DONE
, ftc_server
,
473 _("You can't revolt the same turn you finished previous revolution."));
478 pplayer
->government
= game
.government_during_revolution
;
479 pplayer
->target_government
= gov
;
480 pplayer
->revolution_finishes
= game
.info
.turn
+ turns
;
482 log_debug("Revolution started for %s. Target government is %s. "
483 "Revofin %d (%d).", player_name(pplayer
),
484 government_rule_name(pplayer
->target_government
),
485 pplayer
->revolution_finishes
, game
.info
.turn
);
487 /* Now see if the revolution is instantaneous. */
489 && pplayer
->target_government
!= game
.government_during_revolution
) {
490 government_change(pplayer
, pplayer
->target_government
, TRUE
);
492 } else if (turns
> 0) {
493 notify_player(pplayer
, NULL
, E_REVOLT_START
, ftc_server
,
494 /* TRANS: this is a message event so don't make it
496 PL_("The %s have incited a revolt! "
497 "%d turn of anarchy will ensue! "
498 "Target government is %s.",
499 "The %s have incited a revolt! "
500 "%d turns of anarchy will ensue! "
501 "Target government is %s.",
503 nation_plural_for_player(pplayer
),
505 government_name_translation(pplayer
->target_government
));
507 fc_assert(pplayer
->target_government
== game
.government_during_revolution
);
508 notify_player(pplayer
, NULL
, E_REVOLT_START
, ftc_server
,
509 _("Revolution: returning to anarchy."));
512 check_player_max_rates(pplayer
);
513 city_refresh_for_player(pplayer
);
514 send_player_info_c(pplayer
, pplayer
->connections
);
516 log_debug("Government change complete for %s. Target government is %s; "
517 "now %s. Turn %d; revofin %d.", player_name(pplayer
),
518 government_rule_name(pplayer
->target_government
),
519 government_rule_name(government_of_player(pplayer
)),
520 game
.info
.turn
, pplayer
->revolution_finishes
);
523 /**************************************************************************
524 See if the player has finished their revolution. This function should
525 be called at the beginning of a player's phase.
526 **************************************************************************/
527 void update_revolution(struct player
*pplayer
)
529 struct government
*current_gov
;
531 /* The player's revolution counter is stored in the revolution_finishes
532 * field. This value has the following meanings:
533 * - If negative (-1), then the player is not in a revolution. In this
534 * case the player should never be in anarchy.
535 * - If positive, the player is in the middle of a revolution. In this
536 * case the value indicates the turn in which the revolution finishes.
537 * * If this value is > than the current turn, then the revolution is
538 * in progress. In this case the player should always be in anarchy.
539 * * If the value is == to the current turn, then the revolution is
540 * finished. The player may now choose a government. However the
541 * value isn't reset until the end of the turn. If the player has
542 * chosen a government by the end of the turn, then the revolution is
543 * over and the value is reset to -1.
544 * * If the player doesn't pick a government then the revolution
545 * continues. At this point the value is <= to the current turn,
546 * and the player can leave the revolution at any time. The value
547 * is reset at the end of any turn when a non-anarchy government is
550 log_debug("Update revolution for %s. Current government %s, "
551 "target %s, revofin %d, turn %d.", player_name(pplayer
),
552 government_rule_name(government_of_player(pplayer
)),
553 pplayer
->target_government
554 ? government_rule_name(pplayer
->target_government
) : "(none)",
555 pplayer
->revolution_finishes
, game
.info
.turn
);
557 current_gov
= government_of_player(pplayer
);
559 if (current_gov
== game
.government_during_revolution
560 && pplayer
->revolution_finishes
<= game
.info
.turn
) {
561 if (pplayer
->target_government
!= game
.government_during_revolution
) {
562 /* If the revolution is over and a target government is set, go into
563 * the new government. */
564 log_debug("Update: finishing revolution for %s.", player_name(pplayer
));
565 government_change(pplayer
, pplayer
->target_government
, TRUE
);
567 /* If the revolution is over but there's no target government set,
568 * alert the player. */
569 notify_player(pplayer
, NULL
, E_REVOLT_DONE
, ftc_any
,
570 _("You should choose a new government from the "
571 "government menu."));
573 } else if (government_of_player(pplayer
) != game
.government_during_revolution
574 && pplayer
->revolution_finishes
< game
.info
.turn
) {
575 /* Reset the revolution counter. If the player has another revolution
576 * they'll have to re-enter anarchy. */
577 log_debug("Update: resetting revofin for %s.", player_name(pplayer
));
578 pplayer
->revolution_finishes
= -1;
579 send_player_info_c(pplayer
, pplayer
->connections
);
583 /**************************************************************************
584 The following checks that government rates are acceptable for the present
585 form of government. Has to be called when switching governments or when
586 toggling from AI to human.
587 **************************************************************************/
588 void check_player_max_rates(struct player
*pplayer
)
590 struct player_economic old_econ
= pplayer
->economic
;
592 pplayer
->economic
= player_limit_to_max_rates(pplayer
);
593 if (old_econ
.tax
> pplayer
->economic
.tax
) {
594 notify_player(pplayer
, NULL
, E_NEW_GOVERNMENT
, ftc_server
,
595 _("Tax rate exceeded the max rate; adjusted."));
597 if (old_econ
.science
> pplayer
->economic
.science
) {
598 notify_player(pplayer
, NULL
, E_NEW_GOVERNMENT
, ftc_server
,
599 _("Science rate exceeded the max rate; adjusted."));
601 if (old_econ
.luxury
> pplayer
->economic
.luxury
) {
602 notify_player(pplayer
, NULL
, E_NEW_GOVERNMENT
, ftc_server
,
603 _("Luxury rate exceeded the max rate; adjusted."));
607 /****************************************************************************
608 After the alliance is breaken, we need to do two things:
609 - Inform clients that they cannot see units inside the former's ally
611 - Remove units stacked together
612 Note that you shouldn't use the units listed in 'pplayer_seen_units'
613 and 'pplayer2_seen_units' after calling this function because these
614 units might have died during the process.
615 ****************************************************************************/
616 void update_players_after_alliance_breakup(struct player
*pplayer
,
617 struct player
*pplayer2
,
618 const struct unit_list
620 const struct unit_list
621 *pplayer2_seen_units
)
623 /* The client needs updated diplomatic state, because it is used
624 * during calculation of new states of occupied flags in cities */
625 send_player_all_c(pplayer
, NULL
);
626 send_player_all_c(pplayer2
, NULL
);
627 remove_allied_visibility(pplayer
, pplayer2
, pplayer_seen_units
);
628 remove_allied_visibility(pplayer2
, pplayer
, pplayer2_seen_units
);
629 resolve_unit_stacks(pplayer
, pplayer2
, TRUE
);
632 /**************************************************************************
633 If there's any units of new_owner on tile, they claim bases.
634 **************************************************************************/
635 static void maybe_claim_base(struct tile
*ptile
, struct player
*new_owner
,
636 struct player
*old_owner
)
640 unit_list_iterate(ptile
->units
, punit
) {
641 if (unit_owner(punit
) == new_owner
642 && tile_has_claimable_base(ptile
, unit_type_get(punit
))) {
646 } unit_list_iterate_end
;
649 extra_type_by_cause_iterate(EC_BASE
, pextra
) {
650 map_claim_base(ptile
, pextra
, new_owner
, old_owner
);
651 } extra_type_by_cause_iterate_end
;
653 ptile
->extras_owner
= new_owner
;
657 /**************************************************************************
658 Two players enter war.
659 **************************************************************************/
660 void enter_war(struct player
*pplayer
, struct player
*pplayer2
)
662 /* Claim bases where units are already standing */
663 whole_map_iterate(&(wld
.map
), ptile
) {
664 struct player
*old_owner
= extra_owner(ptile
);
666 if (old_owner
== pplayer2
) {
667 maybe_claim_base(ptile
, pplayer
, old_owner
);
668 } else if (old_owner
== pplayer
) {
669 maybe_claim_base(ptile
, pplayer2
, old_owner
);
671 } whole_map_iterate_end
;
674 /**************************************************************************
675 Handles a player cancelling a "pact" with another player.
677 packet.id is id of player we want to cancel a pact with
678 packet.val1 is a special value indicating what kind of treaty we want
679 to break. If this is CLAUSE_VISION we break shared vision. If it is
680 a pact treaty type, we break one pact level. If it is CLAUSE_LAST
681 we break _all_ treaties and go straight to war.
682 **************************************************************************/
683 void handle_diplomacy_cancel_pact(struct player
*pplayer
,
685 enum clause_type clause
)
687 enum diplstate_type old_type
;
688 enum diplstate_type new_type
;
689 enum dipl_reason diplcheck
;
691 struct player
*pplayer2
= player_by_number(other_player_id
);
692 struct player_diplstate
*ds_plrplr2
, *ds_plr2plr
;
693 struct unit_list
*pplayer_seen_units
, *pplayer2_seen_units
;
695 if (NULL
== pplayer2
|| players_on_same_team(pplayer
, pplayer2
)) {
699 old_type
= player_diplstate_get(pplayer
, pplayer2
)->type
;
701 if (clause
== CLAUSE_VISION
) {
702 if (!gives_shared_vision(pplayer
, pplayer2
)) {
705 remove_shared_vision(pplayer
, pplayer2
);
706 notify_player(pplayer2
, NULL
, E_TREATY_BROKEN
, ftc_server
,
707 _("%s no longer gives us shared vision!"),
708 player_name(pplayer
));
712 diplcheck
= pplayer_can_cancel_treaty(pplayer
, pplayer2
);
714 /* The senate may not allow you to break the treaty. In this case you
715 * must first dissolve the senate then you can break it. */
716 if (diplcheck
== DIPL_SENATE_BLOCKING
) {
717 notify_player(pplayer
, NULL
, E_TREATY_BROKEN
, ftc_server
,
718 _("The senate will not allow you to break treaty "
719 "with the %s. You must either dissolve the senate "
720 "or wait until a more timely moment."),
721 nation_plural_for_player(pplayer2
));
725 if (diplcheck
!= DIPL_OK
) {
729 reject_all_treaties(pplayer
);
730 reject_all_treaties(pplayer2
);
731 /* else, breaking a treaty */
733 /* check what the new status will be */
734 new_type
= cancel_pact_result(old_type
);
736 ds_plrplr2
= player_diplstate_get(pplayer
, pplayer2
);
737 ds_plr2plr
= player_diplstate_get(pplayer2
, pplayer
);
739 if (old_type
== DS_ALLIANCE
) {
740 pplayer_seen_units
= get_units_seen_via_ally(pplayer
, pplayer2
);
741 pplayer2_seen_units
= get_units_seen_via_ally(pplayer2
, pplayer
);
743 pplayer_seen_units
= NULL
;
744 pplayer2_seen_units
= NULL
;
748 ds_plrplr2
->type
= ds_plr2plr
->type
= new_type
;
749 ds_plrplr2
->turns_left
= ds_plr2plr
->turns_left
= 16;
751 if (new_type
== DS_WAR
) {
752 pplayer
->last_war_action
= game
.info
.turn
;
753 pplayer2
->last_war_action
= game
.info
.turn
;
756 /* If the old state was alliance, the players' units can share tiles
757 illegally, and we need to call resolve_unit_stacks() */
758 if (old_type
== DS_ALLIANCE
) {
760 fc_assert(pplayer_seen_units
!= NULL
);
761 fc_assert(pplayer2_seen_units
!= NULL
);
763 update_players_after_alliance_breakup(pplayer
, pplayer2
,
765 pplayer2_seen_units
);
766 unit_list_destroy(pplayer_seen_units
);
767 unit_list_destroy(pplayer2_seen_units
);
770 /* if there's a reason to cancel the pact, do it without penalty */
771 /* FIXME: in the current implementation if you break more than one
772 * treaty simultaneously it may partially succed: the first treaty-breaking
773 * will happen but the second one will fail. */
774 if (get_player_bonus(pplayer
, EFT_HAS_SENATE
) > 0 && !repeat
) {
775 if (ds_plrplr2
->has_reason_to_cancel
> 0) {
776 notify_player(pplayer
, NULL
, E_TREATY_BROKEN
, ftc_server
,
777 _("The senate passes your bill because of the "
778 "constant provocations of the %s."),
779 nation_plural_for_player(pplayer2
));
780 } else if (new_type
== DS_WAR
) {
781 notify_player(pplayer
, NULL
, E_TREATY_BROKEN
, ftc_server
,
782 _("The senate refuses to break treaty with the %s, "
783 "but you have no trouble finding a new senate."),
784 nation_plural_for_player(pplayer2
));
787 if (new_type
== DS_WAR
) {
788 call_incident(INCIDENT_WAR
, pplayer
, pplayer2
);
790 enter_war(pplayer
, pplayer2
);
792 ds_plrplr2
->has_reason_to_cancel
= 0;
794 send_player_all_c(pplayer
, NULL
);
795 send_player_all_c(pplayer2
, NULL
);
798 * Refresh all cities which have a unit of the other side within
801 city_map_update_all_cities_for_player(pplayer
);
802 city_map_update_all_cities_for_player(pplayer2
);
805 notify_player(pplayer
, NULL
, E_TREATY_BROKEN
, ftc_server
,
806 _("The diplomatic state between the %s "
807 "and the %s is now %s."),
808 nation_plural_for_player(pplayer
),
809 nation_plural_for_player(pplayer2
),
810 diplstate_type_translated_name(new_type
));
811 notify_player(pplayer2
, NULL
, E_TREATY_BROKEN
, ftc_server
,
812 _(" %s canceled the diplomatic agreement! "
813 "The diplomatic state between the %s and the %s "
815 player_name(pplayer
),
816 nation_plural_for_player(pplayer2
),
817 nation_plural_for_player(pplayer
),
818 diplstate_type_translated_name(new_type
));
820 /* Check fall-out of a war declaration. */
821 players_iterate_alive(other
) {
822 if (other
!= pplayer
&& other
!= pplayer2
823 && new_type
== DS_WAR
&& pplayers_allied(pplayer2
, other
)
824 && pplayers_allied(pplayer
, other
)) {
825 if (!players_on_same_team(pplayer
, other
)) {
826 /* If an ally declares war on another ally, break off your alliance
827 * to the aggressor. This prevents in-alliance wars, which are not
829 notify_player(other
, NULL
, E_TREATY_BROKEN
, ftc_server
,
830 _("%s has attacked your ally %s! "
831 "You cancel your alliance to the aggressor."),
832 player_name(pplayer
),
833 player_name(pplayer2
));
834 player_diplstate_get(other
, pplayer
)->has_reason_to_cancel
= 1;
835 handle_diplomacy_cancel_pact(other
, player_number(pplayer
),
838 /* We are in the same team as the agressor; we cannot break
839 * alliance with him. We trust our team mate and break alliance
840 * with the attacked player */
841 notify_player(other
, NULL
, E_TREATY_BROKEN
, ftc_server
,
842 _("Your team mate %s declared war on %s. "
843 "You are obligated to cancel alliance with %s."),
844 player_name(pplayer
),
845 nation_plural_for_player(pplayer2
),
846 player_name(pplayer2
));
847 handle_diplomacy_cancel_pact(other
, player_number(pplayer2
), CLAUSE_ALLIANCE
);
850 } players_iterate_alive_end
;
853 /**************************************************************************
854 Send information about removed (unused) players.
855 **************************************************************************/
856 static void send_player_remove_info_c(const struct player_slot
*pslot
,
857 struct conn_list
*dest
)
860 dest
= game
.est_connections
;
863 fc_assert_ret(!player_slot_is_used(pslot
));
865 conn_list_iterate(dest
, pconn
) {
866 dsend_packet_player_remove(pconn
, player_slot_index(pslot
));
867 } conn_list_iterate_end
;
870 /****************************************************************************
871 Do not compute and send PACKET_PLAYER_INFO or PACKET_NATION_AVAILABILITY
872 until a call to player_info_thaw(). This is used during savegame load
873 or ruleset (re)load cycles, to avoid sending infos to the client that
874 depend on ruleset data it does not yet have.
875 ****************************************************************************/
876 void player_info_freeze(void)
878 player_info_frozen_level
++;
881 /****************************************************************************
882 If the frozen level is back to 0, send all players' infos, and nation
883 availability, to all connections.
884 ****************************************************************************/
885 void player_info_thaw(void)
887 if (0 == --player_info_frozen_level
) {
888 send_nation_availability_real(game
.est_connections
, FALSE
);
889 send_player_info_c(NULL
, NULL
);
891 fc_assert(0 <= player_info_frozen_level
);
894 /**************************************************************************
895 Send all information about a player (player_info and all
896 player_diplstates) to the given connections.
898 Send all players if src is NULL; send to all connections if dest is NULL.
900 This function also sends the diplstate of the player. So take care, that
901 all players are defined in the client and in the server. To create a
902 player without sending the diplstate, use send_player_info_c().
903 **************************************************************************/
904 void send_player_all_c(struct player
*src
, struct conn_list
*dest
)
906 send_player_info_c(src
, dest
);
907 send_player_diplstate_c(src
, dest
);
910 /**************************************************************************
911 Send information about player slot 'src', or all valid (i.e. used and
912 initialized) players if 'src' is NULL, to specified clients 'dest'.
913 If 'dest' is NULL, it is treated as game.est_connections.
915 Note: package_player_info contains incomplete info if it has NULL as a
916 dest arg and and info is < INFO_EMBASSY.
917 NB: If 'src' is NULL (meaning send information about all players) this
918 function will only send info for used players, i.e. player slots with
920 **************************************************************************/
921 void send_player_info_c(struct player
*src
, struct conn_list
*dest
)
923 if (0 < player_info_frozen_level
) {
924 return; /* Discard, see comment for player_info_freeze(). */
928 send_player_info_c_real(src
, dest
);
932 players_iterate(pplayer
) {
933 send_player_info_c_real(pplayer
, dest
);
934 } players_iterate_end
;
937 /**************************************************************************
938 Really send information. If 'dest' is NULL, then it is set to
939 game.est_connections.
940 **************************************************************************/
941 static void send_player_info_c_real(struct player
*src
,
942 struct conn_list
*dest
)
944 struct packet_player_info info
;
946 fc_assert_ret(src
!= NULL
);
949 dest
= game
.est_connections
;
952 package_player_common(src
, &info
);
954 conn_list_iterate(dest
, pconn
) {
955 if (NULL
== pconn
->playing
&& pconn
->observer
) {
956 /* Global observer. */
957 package_player_info(src
, &info
, pconn
->playing
, INFO_FULL
);
958 } else if (NULL
!= pconn
->playing
) {
959 /* Players (including regular observers) */
960 package_player_info(src
, &info
, pconn
->playing
, INFO_MINIMUM
);
962 package_player_info(src
, &info
, NULL
, INFO_MINIMUM
);
964 send_packet_player_info(pconn
, &info
);
965 } conn_list_iterate_end
;
968 /**************************************************************************
969 Identical to send_player_info_c(), but sends the diplstate of the
972 This function solves one problem of using an extra packet for the
973 diplstate. It can only be send if the player exists at the destination.
974 Thus, this function should be called after the player(s) exists on both
975 sides of the connection.
976 **************************************************************************/
977 void send_player_diplstate_c(struct player
*src
, struct conn_list
*dest
)
980 send_player_diplstate_c_real(src
, dest
);
984 players_iterate(pplayer
) {
985 send_player_diplstate_c_real(pplayer
, dest
);
986 } players_iterate_end
;
989 /**************************************************************************
990 Really send information. If 'dest' is NULL, then it is set to
991 game.est_connections.
992 **************************************************************************/
993 static void send_player_diplstate_c_real(struct player
*plr1
,
994 struct conn_list
*dest
)
996 fc_assert_ret(plr1
!= NULL
);
999 dest
= game
.est_connections
;
1002 conn_list_iterate(dest
, pconn
) {
1003 players_iterate(plr2
) {
1004 struct packet_player_diplstate packet_ds
;
1006 if (NULL
== pconn
->playing
&& pconn
->observer
) {
1007 /* Global observer. */
1008 package_player_diplstate(plr1
, plr2
, &packet_ds
, pconn
->playing
,
1010 } else if (NULL
!= pconn
->playing
) {
1011 /* Players (including regular observers) */
1012 package_player_diplstate(plr1
, plr2
, &packet_ds
, pconn
->playing
,
1015 package_player_diplstate(plr1
, plr2
, &packet_ds
, NULL
,
1018 send_packet_player_diplstate(pconn
, &packet_ds
);
1019 } players_iterate_end
;
1020 } conn_list_iterate_end
;
1023 /**************************************************************************
1024 Package player information that is always sent.
1025 **************************************************************************/
1026 static void package_player_common(struct player
*plr
,
1027 struct packet_player_info
*packet
)
1030 struct music_style
*music
;
1032 packet
->playerno
= player_number(plr
);
1033 sz_strlcpy(packet
->name
, player_name(plr
));
1034 sz_strlcpy(packet
->username
, plr
->username
);
1035 packet
->unassigned_user
= plr
->unassigned_user
;
1036 packet
->nation
= plr
->nation
? nation_number(plr
->nation
) : NATION_NONE
;
1037 packet
->is_male
= plr
->is_male
;
1038 packet
->team
= plr
->team
? team_number(plr
->team
) : team_count();
1039 packet
->is_ready
= plr
->is_ready
;
1040 packet
->was_created
= plr
->was_created
;
1041 packet
->style
= plr
->style
? style_number(plr
->style
) : 0;
1043 /* I think we could safely move the music style selection to
1044 * client side to not have it burden server side. Client could
1045 * actually avoid it completely when music disabled from the client options.
1046 * Client has no use for music styles of other players, and there should
1047 * be no such information about the player him/herself needed to determine
1048 * the music style that client does not know. */
1049 music
= player_music_style(plr
);
1050 if (music
!= NULL
) {
1051 packet
->music_style
= music_style_number(music
);
1053 packet
->music_style
= -1; /* No music style available */
1056 packet
->is_alive
= plr
->is_alive
;
1057 packet
->turns_alive
= plr
->turns_alive
;
1058 packet
->is_connected
= plr
->is_connected
;
1059 packet
->flags
= plr
->flags
;
1060 packet
->ai_skill_level
= is_ai(plr
)
1061 ? plr
->ai_common
.skill_level
: 0;
1062 for (i
= 0; i
< player_slot_count(); i
++) {
1063 packet
->love
[i
] = plr
->ai_common
.love
[i
];
1065 packet
->barbarian_type
= plr
->ai_common
.barbarian_type
;
1067 packet
->phase_done
= plr
->phase_done
;
1068 packet
->nturns_idle
=plr
->nturns_idle
;
1070 for (i
= 0; i
< B_LAST
/*improvement_count()*/; i
++) {
1071 packet
->wonders
[i
] = plr
->wonders
[i
];
1073 packet
->science_cost
= plr
->ai_common
.science_cost
;
1076 /**************************************************************************
1077 Package player info depending on info_level. We send everything to
1078 plr's connections, we send almost everything to players with embassy
1079 to plr, we send a little to players we are in contact with and almost
1080 nothing to everyone else.
1082 Receiver may be NULL in which cases dummy values are sent for some
1084 **************************************************************************/
1085 static void package_player_info(struct player
*plr
,
1086 struct packet_player_info
*packet
,
1087 struct player
*receiver
,
1088 enum plr_info_level min_info_level
)
1090 enum plr_info_level info_level
;
1091 enum plr_info_level highest_team_level
;
1092 struct government
*pgov
= NULL
;
1095 info_level
= player_info_level(plr
, receiver
);
1096 info_level
= MAX(min_info_level
, info_level
);
1098 info_level
= min_info_level
;
1102 packet
->multip_count
= multiplier_count();
1103 if (info_level
>= INFO_FULL
) {
1104 multipliers_iterate(pmul
) {
1105 packet
->multiplier
[multiplier_index(pmul
)] =
1106 plr
->multipliers
[multiplier_index(pmul
)];
1107 packet
->multiplier_target
[multiplier_index(pmul
)] =
1108 plr
->multipliers_target
[multiplier_index(pmul
)];
1109 } multipliers_iterate_end
;
1111 multipliers_iterate(pmul
) {
1112 packet
->multiplier
[multiplier_index(pmul
)] = 0;
1113 packet
->multiplier_target
[multiplier_index(pmul
)] = 0;
1114 } multipliers_iterate_end
;
1117 /* We need to send all tech info for all players on the same
1118 * team, even if they are not in contact yet; otherwise we will
1119 * overwrite team research or confuse the client. */
1120 highest_team_level
= info_level
;
1121 players_iterate(aplayer
) {
1122 if (players_on_same_team(plr
, aplayer
) && receiver
) {
1123 highest_team_level
= MAX(highest_team_level
,
1124 player_info_level(aplayer
, receiver
));
1126 } players_iterate_end
;
1128 if (plr
->rgb
!= NULL
) {
1129 packet
->color_valid
= TRUE
;
1130 packet
->color_red
= plr
->rgb
->r
;
1131 packet
->color_green
= plr
->rgb
->g
;
1132 packet
->color_blue
= plr
->rgb
->b
;
1134 /* In pregame, send the color we expect to use, for consistency with
1135 * '/list colors' etc. */
1136 const struct rgbcolor
*preferred
= player_preferred_color(plr
);
1137 if (preferred
!= NULL
) {
1138 packet
->color_valid
= TRUE
;
1139 packet
->color_red
= preferred
->r
;
1140 packet
->color_green
= preferred
->g
;
1141 packet
->color_blue
= preferred
->b
;
1143 fc_assert(game
.info
.turn
< 1);
1144 packet
->color_valid
= FALSE
;
1145 /* Client shouldn't use these dummy values */
1146 packet
->color_red
= 0;
1147 packet
->color_green
= 0;
1148 packet
->color_blue
= 0;
1151 packet
->color_changeable
= player_color_changeable(plr
, NULL
);
1153 /* Only send score if we have contact */
1154 if (info_level
>= INFO_MEETING
) {
1155 packet
->score
= plr
->score
.game
;
1160 if (info_level
>= INFO_MEETING
) {
1161 packet
->gold
= plr
->economic
.gold
;
1162 pgov
= government_of_player(plr
);
1165 pgov
= game
.government_during_revolution
;
1167 packet
->government
= pgov
? government_number(pgov
) : government_count();
1169 /* Send diplomatic status of the player to everyone they are in
1171 if (info_level
>= INFO_EMBASSY
1173 && player_diplstate_get(receiver
, plr
)->contact_turns_left
> 0)) {
1174 packet
->target_government
= plr
->target_government
1175 ? government_number(plr
->target_government
)
1176 : government_count();
1177 memset(&packet
->real_embassy
, 0, sizeof(packet
->real_embassy
));
1178 players_iterate(pother
) {
1179 packet
->real_embassy
[player_index(pother
)] =
1180 player_has_real_embassy(plr
, pother
);
1181 } players_iterate_end
;
1182 packet
->gives_shared_vision
= plr
->gives_shared_vision
;
1184 packet
->target_government
= packet
->government
;
1185 memset(&packet
->real_embassy
, 0, sizeof(packet
->real_embassy
));
1186 if (receiver
&& player_has_real_embassy(plr
, receiver
)) {
1187 packet
->real_embassy
[player_index(receiver
)] = TRUE
;
1190 BV_CLR_ALL(packet
->gives_shared_vision
);
1191 if (receiver
&& gives_shared_vision(plr
, receiver
)) {
1192 BV_SET(packet
->gives_shared_vision
, player_index(receiver
));
1196 /* Make absolutely sure - in case you lose your embassy! */
1197 if (info_level
>= INFO_EMBASSY
1199 && player_diplstate_get(plr
, receiver
)->type
== DS_TEAM
)) {
1200 packet
->tech_upkeep
= player_tech_upkeep(plr
);
1202 packet
->tech_upkeep
= 0;
1205 /* Send most civ info about the player only to players who have an
1207 if (highest_team_level
>= INFO_EMBASSY
) {
1208 packet
->tax
= plr
->economic
.tax
;
1209 packet
->science
= plr
->economic
.science
;
1210 packet
->luxury
= plr
->economic
.luxury
;
1211 packet
->revolution_finishes
= plr
->revolution_finishes
;
1214 packet
->science
= 0;
1216 packet
->revolution_finishes
= -1;
1219 if (info_level
>= INFO_FULL
1221 && player_diplstate_get(plr
, receiver
)->type
== DS_TEAM
)) {
1222 packet
->mood
= player_mood(plr
);
1224 packet
->mood
= MOOD_COUNT
;
1227 if (info_level
>= INFO_FULL
) {
1228 packet
->culture
= plr
->culture
;
1230 packet
->culture
= 0;
1234 /**************************************************************************
1235 Package player diplstate depending on info_level. We send everything to
1236 plr's connections, we send almost everything to players with embassy
1237 to plr, we send a little to players we are in contact with and almost
1238 nothing to everyone else.
1240 Receiver may be NULL in which cases dummy values are sent for some
1242 **************************************************************************/
1243 static void package_player_diplstate(struct player
*plr1
,
1244 struct player
*plr2
,
1245 struct packet_player_diplstate
*packet_ds
,
1246 struct player
*receiver
,
1247 enum plr_info_level min_info_level
)
1249 enum plr_info_level info_level
;
1250 struct player_diplstate
*ds
= player_diplstate_get(plr1
, plr2
);
1253 info_level
= player_info_level(plr1
, receiver
);
1254 info_level
= MAX(min_info_level
, info_level
);
1256 info_level
= min_info_level
;
1259 packet_ds
->plr1
= player_index(plr1
);
1260 packet_ds
->plr2
= player_index(plr2
);
1261 /* A unique id for each combination is calculated here. */
1262 packet_ds
->diplstate_id
= packet_ds
->plr1
* MAX_NUM_PLAYER_SLOTS
1265 /* Send diplomatic status of the player to everyone they are in
1266 * contact with (embassy, remaining contact turns, the receiver). */
1267 if (info_level
>= INFO_EMBASSY
1269 && player_diplstate_get(receiver
, plr1
)->contact_turns_left
> 0)
1270 || (receiver
&& receiver
== plr2
)) {
1271 packet_ds
->type
= ds
->type
;
1272 packet_ds
->turns_left
= ds
->turns_left
;
1273 packet_ds
->has_reason_to_cancel
= ds
->has_reason_to_cancel
;
1274 packet_ds
->contact_turns_left
= ds
->contact_turns_left
;
1276 packet_ds
->type
= DS_WAR
;
1277 packet_ds
->turns_left
= 0;
1278 packet_ds
->has_reason_to_cancel
= 0;
1279 packet_ds
->contact_turns_left
= 0;
1283 /**************************************************************************
1284 Return level of information player should receive about another.
1285 **************************************************************************/
1286 static enum plr_info_level
player_info_level(struct player
*plr
,
1287 struct player
*receiver
)
1289 if (S_S_RUNNING
> server_state()) {
1290 return INFO_MINIMUM
;
1292 if (plr
== receiver
) {
1295 if (receiver
&& player_has_embassy(receiver
, plr
)) {
1296 return INFO_EMBASSY
;
1298 if (receiver
&& could_intel_with_player(receiver
, plr
)) {
1299 return INFO_MEETING
;
1301 return INFO_MINIMUM
;
1304 /**************************************************************************
1305 Convenience function to return "reply" destination connection list
1306 for player: pplayer->current_conn if set, else pplayer->connections.
1307 **************************************************************************/
1308 struct conn_list
*player_reply_dest(struct player
*pplayer
)
1310 return (pplayer
->current_conn
?
1311 pplayer
->current_conn
->self
:
1312 pplayer
->connections
);
1315 /**************************************************************************
1316 Call first_contact function if such is defined for player
1317 **************************************************************************/
1318 static void call_first_contact(struct player
*pplayer
, struct player
*aplayer
)
1320 CALL_PLR_AI_FUNC(first_contact
, pplayer
, pplayer
, aplayer
);
1323 /****************************************************************************
1324 Initialize ANY newly-created player on the server.
1326 The initmap option is used because we don't want to initialize the map
1327 before the x and y sizes have been determined. This should generally
1328 be FALSE in pregame.
1330 The needs_team options should be set for players who should be assigned
1331 a team. They will be put on their own newly-created team.
1332 ****************************************************************************/
1333 void server_player_init(struct player
*pplayer
, bool initmap
,
1336 player_status_reset(pplayer
);
1338 pplayer
->server
.got_first_city
= FALSE
;
1339 BV_CLR_ALL(pplayer
->server
.really_gives_vision
);
1340 BV_CLR_ALL(pplayer
->server
.debug
);
1342 pplayer
->server
.border_vision
= FALSE
;
1344 player_map_free(pplayer
);
1345 pplayer
->server
.private_map
= NULL
;
1348 player_map_init(pplayer
);
1351 team_add_player(pplayer
, NULL
);
1354 /* This must be done after team information is initialised
1355 * as it might be needed to determine max rate effects.
1356 * Sometimes this server_player_init() gets called twice
1357 * with only latter one having needs_team set. We don't
1358 * want to call player_limit_to_max_rates() at first time
1359 * when team is not yet set. It's callers responsibility
1360 * to always have one server_player_init() call with
1361 * needs_team TRUE. */
1363 pplayer
->economic
= player_limit_to_max_rates(pplayer
);
1366 adv_data_default(pplayer
);
1368 /* We don't push this in calc_civ_score(), or it will be reset
1370 pplayer
->score
.units_built
= 0;
1371 pplayer
->score
.units_killed
= 0;
1372 pplayer
->score
.units_lost
= 0;
1374 /* No delegation. */
1375 pplayer
->server
.delegate_to
[0] = '\0';
1376 pplayer
->server
.orig_username
[0] = '\0';
1378 handicaps_init(pplayer
);
1381 /****************************************************************************
1382 If a player's color will be predictable when colors are assigned (or
1383 assignment has already happened), return that color. Otherwise (if the
1384 player's color is yet to be assigned randomly), return NULL.
1385 ****************************************************************************/
1386 const struct rgbcolor
*player_preferred_color(struct player
*pplayer
)
1389 return pplayer
->rgb
;
1390 } else if (playercolor_count() == 0) {
1391 /* If a ruleset isn't loaded, there are no colors to choose from. */
1393 } else if (game
.server
.plrcolormode
== PLRCOL_NATION_ORDER
) {
1394 if (pplayer
->nation
!= NO_NATION_SELECTED
) {
1395 return nation_color(nation_of_player(pplayer
)); /* may be NULL */
1397 return NULL
; /* don't know nation, hence don't know color */
1400 /* Modes indexing into game-defined player colors */
1402 switch (game
.server
.plrcolormode
) {
1403 case PLRCOL_PLR_SET
: /* player color (set) */
1404 case PLRCOL_PLR_RANDOM
: /* player color (random) */
1405 /* These depend on other players and will be assigned at game start. */
1408 log_error("Invalid value for 'game.server.plrcolormode' (%d)!",
1409 game
.server
.plrcolormode
);
1410 /* no break - using 'PLRCOL_PLR_ORDER' as fallback */
1411 case PLRCOL_PLR_ORDER
: /* player color (ordered) */
1412 colorid
= player_number(pplayer
) % playercolor_count();
1414 case PLRCOL_TEAM_ORDER
: /* team color (ordered) */
1415 colorid
= team_number(pplayer
->team
) % playercolor_count();
1418 return playercolor_get(colorid
);
1422 /****************************************************************************
1423 Return whether a player's color can currently be set with the
1424 '/playercolor' command. If not, give a reason why not, if 'reason' is
1425 not NULL (need not be freed).
1426 ****************************************************************************/
1427 bool player_color_changeable(const struct player
*pplayer
, const char **reason
)
1429 if (!game_was_started() && game
.server
.plrcolormode
!= PLRCOL_PLR_SET
) {
1431 *reason
= _("Can only set player color prior to game start if "
1432 "'plrcolormode' is PLR_SET.");
1439 /****************************************************************************
1440 Permanently assign colors to any players that don't already have them.
1441 First assign preferred colors, then assign the rest randomly, trying to
1443 ****************************************************************************/
1444 void assign_player_colors(void)
1446 struct rgbcolor_list
*spare_colors
=
1447 rgbcolor_list_copy(game
.server
.plr_colors
);
1448 int needed
= player_count();
1450 players_iterate(pplayer
) {
1451 const struct rgbcolor
*autocolor
;
1452 /* Assign the deterministic colors. */
1454 && (autocolor
= player_preferred_color(pplayer
))) {
1455 player_set_color(pplayer
, autocolor
);
1458 /* One fewer random color needed. */
1460 /* Try to avoid clashes between explicit and random colors. */
1461 rgbcolor_list_iterate(spare_colors
, prgbcolor
) {
1462 if (rgbcolors_are_equal(pplayer
->rgb
, prgbcolor
)) {
1463 rgbcolor_list_remove(spare_colors
, prgbcolor
);
1465 } rgbcolor_list_iterate_end
;
1467 } players_iterate_end
;
1470 /* No random colors needed */
1471 rgbcolor_list_destroy(spare_colors
);
1475 if (game
.server
.plrcolormode
== PLRCOL_NATION_ORDER
) {
1476 /* Additionally, try to avoid color clashes with certain nations not
1477 * yet in play (barbarians). */
1478 allowed_nations_iterate(pnation
) {
1479 const struct rgbcolor
*ncol
= nation_color(pnation
);
1480 if (ncol
&& nation_barbarian_type(pnation
) != NOT_A_BARBARIAN
) {
1481 /* Don't use this color. */
1482 rgbcolor_list_iterate(spare_colors
, prgbcolor
) {
1483 if (rgbcolors_are_equal(ncol
, prgbcolor
)) {
1484 rgbcolor_list_remove(spare_colors
, ncol
);
1486 } rgbcolor_list_iterate_end
;
1488 } allowed_nations_iterate_end
;
1491 fc_assert(game
.server
.plrcolormode
== PLRCOL_PLR_RANDOM
1492 || game
.server
.plrcolormode
== PLRCOL_PLR_SET
1493 || game
.server
.plrcolormode
== PLRCOL_NATION_ORDER
);
1495 if (needed
> rgbcolor_list_size(spare_colors
)) {
1496 log_verbose("Not enough unique colors for all players; there will be "
1498 /* Fallback: start again from full set of ruleset colors.
1499 * No longer attempt to avoid clashes with explicitly assigned colors. */
1500 rgbcolor_list_destroy(spare_colors
);
1501 spare_colors
= rgbcolor_list_copy(game
.server
.plr_colors
);
1503 /* We may still not have enough, if there are more players than
1504 * ruleset-defined colors. If so, top up with duplicates. */
1505 if (needed
> rgbcolor_list_size(spare_colors
)) {
1506 int i
, origsize
= rgbcolor_list_size(spare_colors
);
1507 /* Shuffle so that duplicates aren't biased to start of list */
1508 rgbcolor_list_shuffle(spare_colors
);
1509 /* Duplication process avoids one color being hit lots of times */
1510 for (i
= origsize
; i
< needed
; i
++) {
1511 rgbcolor_list_append(spare_colors
,
1512 rgbcolor_list_get(spare_colors
, i
- origsize
));
1515 /* Shuffle (including mixing any duplicates up) */
1516 rgbcolor_list_shuffle(spare_colors
);
1518 /* Finally, assign shuffled colors to players. */
1519 players_iterate(pplayer
) {
1520 if (!pplayer
->rgb
) {
1521 player_set_color(pplayer
, rgbcolor_list_front(spare_colors
));
1522 rgbcolor_list_pop_front(spare_colors
);
1524 } players_iterate_end
;
1526 rgbcolor_list_destroy(spare_colors
);
1529 /****************************************************************************
1530 Set the player's color. If 'prgbcolor' is not NULL the caller should free
1531 the pointer, as player_set_color() copies the data.
1532 ****************************************************************************/
1533 void server_player_set_color(struct player
*pplayer
,
1534 const struct rgbcolor
*prgbcolor
)
1536 if (prgbcolor
!= NULL
) {
1537 player_set_color(pplayer
, prgbcolor
);
1539 /* This can legitimately be NULL in pregame. */
1540 fc_assert_ret(!game_was_started());
1541 rgbcolor_destroy(pplayer
->rgb
);
1542 pplayer
->rgb
= NULL
;
1544 /* Update clients */
1545 send_player_info_c(pplayer
, NULL
);
1548 /****************************************************************************
1549 Return the player color as featured text string.
1550 (In pregame, this uses the color the player will take, if known, even if
1552 ****************************************************************************/
1553 const char *player_color_ftstr(struct player
*pplayer
)
1555 static char buf
[64];
1557 const struct rgbcolor
*prgbcolor
;
1559 fc_assert_ret_val(pplayer
!= NULL
, NULL
);
1562 prgbcolor
= player_preferred_color(pplayer
);
1563 if (prgbcolor
!= NULL
1564 && rgbcolor_to_hex(prgbcolor
, hex
, sizeof(hex
))) {
1565 struct ft_color plrcolor
= FT_COLOR("#000000", hex
);
1567 featured_text_apply_tag(hex
, buf
, sizeof(buf
), TTT_COLOR
, 0,
1568 FT_OFFSET_UNSET
, plrcolor
);
1570 cat_snprintf(buf
, sizeof(buf
), _("no color"));
1576 /**********************************************************************
1577 Gives units that every player should have. Usually called for
1578 players created midgame.
1579 ***********************************************************************/
1580 void give_midgame_initial_units(struct player
*pplayer
, struct tile
*ptile
)
1582 int sucount
= strlen(game
.server
.start_units
);
1585 for (i
= 0; i
< sucount
; i
++) {
1586 if (game
.server
.start_units
[i
] == 'k') {
1587 /* Every player should have king */
1588 struct unit_type
*utype
= crole_to_unit_type('k', pplayer
);
1590 if (utype
!= NULL
) {
1591 create_unit(pplayer
, ptile
, utype
, 0, 0, -1);
1597 /**********************************************************************
1598 Creates a new, uninitialized, used player slot. You should probably
1599 call server_player_init() to initialize it, and send_player_info_c()
1600 later to tell clients about it.
1602 May return NULL if creation was not possible.
1603 ***********************************************************************/
1604 struct player
*server_create_player(int player_id
, const char *ai_tname
,
1605 struct rgbcolor
*prgbcolor
,
1606 bool allow_ai_type_fallbacking
)
1608 struct player_slot
*pslot
;
1609 struct player
*pplayer
;
1611 pslot
= player_slot_by_number(player_id
);
1612 fc_assert(NULL
== pslot
|| !player_slot_is_used(pslot
));
1614 pplayer
= player_new(pslot
);
1615 if (NULL
== pplayer
) {
1619 if (allow_ai_type_fallbacking
) {
1620 pplayer
->savegame_ai_type_name
= fc_strdup(ai_tname
);
1621 ai_tname
= ai_type_name_or_fallback(ai_tname
);
1624 pplayer
->ai
= ai_type_by_name(ai_tname
);
1626 if (pplayer
->ai
== NULL
) {
1627 player_destroy(pplayer
);
1631 adv_data_init(pplayer
);
1633 CALL_FUNC_EACH_AI(player_alloc
, pplayer
);
1635 /* TODO: Do we really need this server_player_init() here? All our callers
1636 * will later make another server_player_init() call anyway, with boolean
1637 * parameters set to what they really need. */
1638 server_player_init(pplayer
, FALSE
, FALSE
);
1641 player_set_color(pplayer
, prgbcolor
);
1642 } /* else caller must ensure a color is assigned if game has started */
1647 /**********************************************************************
1648 This function does _not_ close any connections attached to this
1649 player. The function cut_connection() is used for that. Be sure
1650 to send_player_slot_info_c() afterwards to tell clients that the
1651 player slot has become unused.
1652 ***********************************************************************/
1653 void server_remove_player(struct player
*pplayer
)
1655 const struct player_slot
*pslot
;
1657 fc_assert_ret(NULL
!= pplayer
);
1659 /* save player slot */
1660 pslot
= pplayer
->slot
;
1662 log_normal(_("Removing player %s."), player_name(pplayer
));
1664 notify_conn(pplayer
->connections
, NULL
, E_CONNECTION
, ftc_server
,
1665 _("You've been removed from the game!"));
1667 notify_conn(game
.est_connections
, NULL
, E_CONNECTION
, ftc_server
,
1668 _("%s has been removed from the game."),
1669 player_name(pplayer
));
1671 if (is_barbarian(pplayer
)) {
1672 server
.nbarbarians
--;
1675 /* Don't use conn_list_iterate here because connection_detach() can be
1676 * recursive and free the next connection pointer. */
1677 while (conn_list_size(pplayer
->connections
) > 0) {
1678 connection_detach(conn_list_get(pplayer
->connections
, 0), FALSE
);
1681 script_server_remove_exported_object(pplayer
);
1682 /* Clear data saved in the other player structs. */
1683 players_iterate(aplayer
) {
1684 BV_CLR(aplayer
->real_embassy
, player_index(pplayer
));
1685 if (gives_shared_vision(aplayer
, pplayer
)) {
1686 remove_shared_vision(aplayer
, pplayer
);
1688 } players_iterate_end
;
1690 /* Remove citizens of this player from the cities of all other players. */
1691 /* FIXME: add a special case if the server quits - no need to run this for
1692 * each player in that case. */
1693 if (game
.info
.citizen_nationality
) {
1694 cities_iterate(pcity
) {
1695 if (city_owner(pcity
) != pplayer
) {
1696 citizens nationality
= citizens_nation_get(pcity
, pplayer
->slot
);
1698 if (nationality
!= 0) {
1699 /* Change nationality of the citizens to the nationality of the
1701 citizens_nation_move(pcity
, pplayer
->slot
, city_owner(pcity
)->slot
,
1703 city_refresh_queue_add(pcity
);
1706 } cities_iterate_end
1708 city_refresh_queue_processing();
1711 /* AI type lost control of this player */
1712 CALL_PLR_AI_FUNC(lost_control
, pplayer
, pplayer
);
1714 /* Clear all trade routes. This is needed for the other end not
1715 * to point to a city removed by player_clear() */
1716 city_list_iterate(pplayer
->cities
, pcity
) {
1717 trade_routes_iterate_safe(pcity
, proute
) {
1718 struct trade_route
*pback
= remove_trade_route(pcity
, proute
,
1723 } trade_routes_iterate_safe_end
;
1724 } city_list_iterate_end
;
1726 /* We have to clear all player data before the ai memory is freed because
1727 * some function may depend on it. */
1728 player_clear(pplayer
, TRUE
);
1730 if (!map_is_empty()) {
1731 remove_player_from_maps(pplayer
);
1733 player_map_free(pplayer
);
1735 /* Destroy advisor and ai data. */
1736 CALL_FUNC_EACH_AI(player_free
, pplayer
);
1738 handicaps_close(pplayer
);
1739 ai_traits_close(pplayer
);
1740 adv_data_close(pplayer
);
1741 player_destroy(pplayer
);
1743 send_updated_vote_totals(NULL
);
1744 /* must be called after the player was destroyed */
1745 send_player_remove_info_c(pslot
, NULL
);
1747 /* Recalculate borders. */
1748 map_calculate_borders();
1751 /**************************************************************************
1752 The following limits a player's rates to those that are acceptable for the
1753 present form of government. If a rate exceeds maxrate for this government,
1754 it adjusts rates automatically adding the extra to the 2nd highest rate,
1755 preferring science to taxes and taxes to luxuries.
1756 (It assumes that for any government maxrate>=50)
1758 Returns actual max rate used. This function should be called after team
1759 information are defined.
1760 **************************************************************************/
1761 struct player_economic
player_limit_to_max_rates(struct player
*pplayer
)
1763 int maxrate
, surplus
;
1764 struct player_economic economic
;
1766 /* ai players allowed to cheat */
1767 if (is_ai(pplayer
)) {
1768 return pplayer
->economic
;
1771 economic
= pplayer
->economic
;
1773 maxrate
= get_player_maxrate(pplayer
);
1776 if (economic
.luxury
> maxrate
) {
1777 surplus
+= economic
.luxury
- maxrate
;
1778 economic
.luxury
= maxrate
;
1780 if (economic
.tax
> maxrate
) {
1781 surplus
+= economic
.tax
- maxrate
;
1782 economic
.tax
= maxrate
;
1784 if (economic
.science
> maxrate
) {
1785 surplus
+= economic
.science
- maxrate
;
1786 economic
.science
= maxrate
;
1789 fc_assert(surplus
% 10 == 0);
1790 while (surplus
> 0) {
1791 if (economic
.science
< maxrate
) {
1792 economic
.science
+= 10;
1793 } else if (economic
.tax
< maxrate
) {
1795 } else if (economic
.luxury
< maxrate
) {
1796 economic
.luxury
+= 10;
1798 fc_assert_msg(FALSE
, "Failed to distribute the surplus. "
1799 "maxrate = %d.", maxrate
);
1807 /****************************************************************************
1808 Check if this name is allowed for the player. Fill out the error message
1809 (a translated string to be sent to the client) if not.
1810 ****************************************************************************/
1811 static bool server_player_name_is_allowed(const struct connection
*caller
,
1812 const struct player
*pplayer
,
1813 const struct nation_type
*pnation
,
1814 const char *name
, char *error_buf
,
1815 size_t error_buf_len
)
1817 /* An empty name is surely not allowed. */
1818 if (0 == strlen(name
)) {
1819 fc_strlcpy(error_buf
, _("Please choose a non-blank name."),
1824 /* Any name already taken is not allowed. */
1825 players_iterate(other_player
) {
1826 if (other_player
== pplayer
) {
1827 /* We don't care if we're the one using the name/nation. */
1829 } else if (NULL
!= pnation
&& other_player
->nation
== pnation
) {
1830 /* FIXME: currently cannot use nation_of_player(other_player) as the
1831 * nation debug code is buggy and doesn't test nation for NULL. */
1832 fc_strlcpy(error_buf
, _("That nation is already in use."),
1835 } else if (0 == fc_strcasecmp(player_name(other_player
), name
)) {
1836 fc_snprintf(error_buf
, error_buf_len
,
1837 _("Another player already has the name '%s'. Please "
1838 "choose another name."), name
);
1841 } players_iterate_end
;
1843 if (NULL
== pnation
) {
1844 /* FIXME: currently cannot use nation_of_player(other_player) as the
1845 * nation debug code is buggy and doesn't test nation for NULL. */
1846 pnation
= pplayer
->nation
;
1849 /* Any name from the default list is always allowed. */
1850 if (NULL
!= pnation
&& NULL
!= nation_leader_by_name(pnation
, name
)) {
1854 /* To prevent abuse, only players with HACK access (usually local
1855 * connections) can use non-ascii names. Otherwise players could use
1856 * confusing garbage names in multi-player games. */
1858 && caller
->access_level
< ALLOW_HACK
1859 && !is_ascii_name(name
)) {
1860 fc_strlcpy(error_buf
,
1861 _("Please choose a name containing only ASCII characters."),
1869 /****************************************************************************
1870 Try to set the player name to 'name'. Else, find a default name. Returns
1872 ****************************************************************************/
1873 bool server_player_set_name_full(const struct connection
*caller
,
1874 struct player
*pplayer
,
1875 const struct nation_type
*pnation
,
1877 char *error_buf
, size_t error_buf_len
)
1879 char real_name
[MAX_LEN_NAME
];
1883 /* Always provide an error buffer. */
1884 if (NULL
== error_buf
) {
1886 error_buf_len
= sizeof(buf
);
1888 error_buf
[0] = '\0';
1891 /* Ensure this is a correct name. */
1892 sz_strlcpy(real_name
, name
);
1893 remove_leading_trailing_spaces(real_name
);
1894 real_name
[0] = fc_toupper(real_name
[0]);
1896 if (server_player_name_is_allowed(caller
, pplayer
, pnation
, real_name
,
1897 error_buf
, error_buf_len
)) {
1898 log_debug("Name of player nb %d set to \"%s\".",
1899 player_number(pplayer
), real_name
);
1900 fc_strlcpy(pplayer
->name
, real_name
, sizeof(pplayer
->name
));
1901 return TRUE
; /* Success! */
1903 log_verbose("Failed to set the name of the player nb %d to \"%s\": %s",
1904 player_number(pplayer
), real_name
, error_buf
);
1909 if (NULL
!= caller
) {
1910 /* If we want to test, let's fail here. */
1911 fc_assert(NULL
!= name
);
1916 /* Try to append a number to 'real_name'. */
1917 char test
[MAX_LEN_NAME
];
1919 for (i
= 2; i
<= player_slot_count(); i
++) {
1920 fc_snprintf(test
, sizeof(test
), "%s%d", real_name
, i
);
1921 if (server_player_name_is_allowed(caller
, pplayer
, pnation
,
1922 test
, error_buf
, error_buf_len
)) {
1923 log_verbose("Name of player nb %d set to \"%s\" instead.",
1924 player_number(pplayer
), test
);
1925 fc_strlcpy(pplayer
->name
, test
, sizeof(pplayer
->name
));
1928 log_debug("Failed to set the name of the player nb %d to \"%s\": %s",
1929 player_number(pplayer
), test
, error_buf
);
1934 /* Try a default name. */
1935 fc_snprintf(real_name
, sizeof(real_name
),
1936 _("Player no. %d"), player_number(pplayer
));
1937 if (server_player_name_is_allowed(caller
, pplayer
, pnation
,
1938 real_name
, error_buf
, error_buf_len
)) {
1939 log_verbose("Name of player nb %d set to \"%s\".",
1940 player_number(pplayer
), real_name
);
1941 fc_strlcpy(pplayer
->name
, real_name
, sizeof(pplayer
->name
));
1944 log_debug("Failed to set the name of the player nb %d to \"%s\": %s",
1945 player_number(pplayer
), real_name
, error_buf
);
1948 /* Try a very default name... */
1949 for (i
= 0; i
< player_slot_count(); i
++) {
1950 fc_snprintf(real_name
, sizeof(real_name
), _("Player no. %d"), i
);
1951 if (server_player_name_is_allowed(caller
, pplayer
, pnation
,
1952 real_name
, error_buf
, error_buf_len
)) {
1953 log_verbose("Name of player nb %d to \"%s\".",
1954 player_number(pplayer
), real_name
);
1955 fc_strlcpy(pplayer
->name
, real_name
, sizeof(pplayer
->name
));
1958 log_debug("Failed to set the name of the player nb %d to \"%s\": %s",
1959 player_number(pplayer
), real_name
, error_buf
);
1963 /* This is really not normal... Maybe the size of 'real_name'
1964 * is not enough big, or a bug in server_player_name_is_allowed(). */
1965 fc_strlcpy(pplayer
->name
, _("A poorly-named player"),
1966 sizeof(pplayer
->name
));
1967 return FALSE
; /* Let's say it's a failure. */
1970 /****************************************************************************
1971 Try to set the player name to 'name'. Else, find a default name.
1972 ****************************************************************************/
1973 void server_player_set_name(struct player
*pplayer
, const char *name
)
1977 ret
= server_player_set_name_full(NULL
, pplayer
, NULL
, name
, NULL
, 0);
1978 fc_assert(TRUE
== ret
);
1981 /**************************************************************************
1982 Returns the default diplomatic state between 2 players.
1984 Mainly, this returns DS_WAR, but it can also return DS_PEACE if both
1985 players are allied with the same third player.
1986 **************************************************************************/
1987 static enum diplstate_type
1988 get_default_diplstate(const struct player
*pplayer1
,
1989 const struct player
*pplayer2
)
1991 players_iterate_alive(pplayer3
) {
1992 if (pplayer3
!= pplayer1
1993 && pplayer3
!= pplayer2
1994 && pplayers_allied(pplayer3
, pplayer1
)
1995 && pplayers_allied(pplayer3
, pplayer2
)) {
1998 } players_iterate_alive_end
;
2003 /**************************************************************************
2004 Update contact info.
2005 **************************************************************************/
2006 void make_contact(struct player
*pplayer1
, struct player
*pplayer2
,
2009 struct player_diplstate
*ds_plr1plr2
, *ds_plr2plr1
;
2011 if (pplayer1
== pplayer2
2012 || !pplayer1
->is_alive
2013 || !pplayer2
->is_alive
) {
2017 ds_plr1plr2
= player_diplstate_get(pplayer1
, pplayer2
);
2018 ds_plr2plr1
= player_diplstate_get(pplayer2
, pplayer1
);
2020 if (get_player_bonus(pplayer1
, EFT_NO_DIPLOMACY
) <= 0
2021 && get_player_bonus(pplayer2
, EFT_NO_DIPLOMACY
) <= 0) {
2022 ds_plr1plr2
->contact_turns_left
= game
.server
.contactturns
;
2023 ds_plr2plr1
->contact_turns_left
= game
.server
.contactturns
;
2025 if (ds_plr1plr2
->type
== DS_NO_CONTACT
) {
2026 enum diplstate_type new_state
= get_default_diplstate(pplayer1
,
2029 ds_plr1plr2
->type
= new_state
;
2030 ds_plr2plr1
->type
= new_state
;
2031 ds_plr1plr2
->first_contact_turn
= game
.info
.turn
;
2032 ds_plr2plr1
->first_contact_turn
= game
.info
.turn
;
2033 notify_player(pplayer1
, ptile
, E_FIRST_CONTACT
, ftc_server
,
2034 _("You have made contact with the %s, ruled by %s."),
2035 nation_plural_for_player(pplayer2
),
2036 player_name(pplayer2
));
2037 notify_player(pplayer2
, ptile
, E_FIRST_CONTACT
, ftc_server
,
2038 _("You have made contact with the %s, ruled by %s."),
2039 nation_plural_for_player(pplayer1
),
2040 player_name(pplayer1
));
2041 send_player_all_c(pplayer1
, pplayer2
->connections
);
2042 send_player_all_c(pplayer2
, pplayer1
->connections
);
2043 send_player_all_c(pplayer1
, pplayer1
->connections
);
2044 send_player_all_c(pplayer2
, pplayer2
->connections
);
2045 if (is_ai(pplayer1
)) {
2046 call_first_contact(pplayer1
, pplayer2
);
2048 if (is_ai(pplayer2
)) {
2049 call_first_contact(pplayer2
, pplayer1
);
2053 fc_assert(ds_plr2plr1
->type
!= DS_NO_CONTACT
);
2055 if (player_has_embassy(pplayer1
, pplayer2
)
2056 || player_has_embassy(pplayer2
, pplayer1
)) {
2057 return; /* Avoid sending too much info over the network */
2059 send_player_all_c(pplayer1
, pplayer1
->connections
);
2060 send_player_all_c(pplayer2
, pplayer2
->connections
);
2063 /**************************************************************************
2064 Check if we make contact with anyone.
2065 **************************************************************************/
2066 void maybe_make_contact(struct tile
*ptile
, struct player
*pplayer
)
2068 square_iterate(&(wld
.map
), ptile
, 1, tile1
) {
2069 struct city
*pcity
= tile_city(tile1
);
2071 make_contact(pplayer
, city_owner(pcity
), ptile
);
2073 unit_list_iterate_safe(tile1
->units
, punit
) {
2074 make_contact(pplayer
, unit_owner(punit
), ptile
);
2075 } unit_list_iterate_safe_end
;
2076 } square_iterate_end
;
2079 /**************************************************************************
2080 Shuffle or reshuffle the player order, storing in static variables above.
2081 **************************************************************************/
2082 void shuffle_players(void)
2084 /* shuffled_order is defined global */
2085 int n
= player_slot_count();
2088 log_debug("shuffle_players: creating shuffled order");
2090 for (i
= 0; i
< n
; i
++) {
2091 shuffled_order
[i
] = i
;
2095 array_shuffle(shuffled_order
, n
);
2097 #ifdef FREECIV_DEBUG
2098 for (i
= 0; i
< n
; i
++) {
2099 log_debug("shuffled_order[%d] = %d", i
, shuffled_order
[i
]);
2101 #endif /* FREECIV_DEBUG */
2104 /**************************************************************************
2105 Initialize the shuffled players list (as from a loaded savegame).
2106 **************************************************************************/
2107 void set_shuffled_players(int *shuffled_players
)
2111 log_debug("set_shuffled_players: loading shuffled array %p",
2114 for (i
= 0; i
< player_slot_count(); i
++) {
2115 shuffled_order
[i
] = shuffled_players
[i
];
2116 log_debug("shuffled_order[%d] = %d", i
, shuffled_order
[i
]);
2120 /**************************************************************************
2121 Returns the i'th shuffled player, or NULL.
2123 NB: You should never need to call this function directly.
2124 **************************************************************************/
2125 struct player
*shuffled_player(int i
)
2127 struct player
*pplayer
;
2129 pplayer
= player_by_number(shuffled_order
[i
]);
2130 log_debug("shuffled_player(%d) = %d (%s)",
2131 i
, shuffled_order
[i
], player_name(pplayer
));
2135 /****************************************************************************
2136 This function returns a random-ish nation that is suitable for 'barb_type'
2137 and is usable (not already in use by an existing player, and if
2138 needs_startpos is set, would not be prohibited from starting on the map
2139 by the current scenario -- NB this doesn't check that any start position
2142 Unless 'ignore_conflicts' is set, this function tries hard to avoid a
2143 nation marked as "conflicting with" one already in the game. A
2144 conflicting nation will be returned only if the alternative is to return
2145 NO_NATION_SELECTED. Such a return indicates that there are no remaining
2146 nations which match the above criteria.
2148 If 'choices' is non-NULL, nations from the supplied list are preferred;
2149 but if there are no (non-conflicting) nations on the list that match the
2150 criteria, one will be chosen from outside the list (as if the list had
2153 All other things being equal, prefers to pick a nation which returns a
2154 high score from nations_match() relative to any nations already in the
2156 ****************************************************************************/
2157 struct nation_type
*pick_a_nation(const struct nation_list
*choices
,
2158 bool ignore_conflicts
,
2159 bool needs_startpos
,
2160 enum barbarian_type barb_type
)
2163 UNAVAILABLE
, AVAILABLE
, PREFERRED
, UNWANTED
2164 } nations_used
[nation_count()], looking_for
;
2165 int match
[nation_count()], pick
, idx
;
2166 int num_avail_nations
= 0, num_pref_nations
= 0;
2168 /* Values of nations_used:
2169 * UNAVAILABLE - nation is already used or is a special nation.
2170 * AVAILABLE - we can use this nation.
2171 * PREFERRED - we can use this nation and it is on the choices list.
2172 * UNWANTED - we can use this nation, but we really don't want to. */
2173 nations_iterate(pnation
) {
2174 idx
= nation_index(pnation
);
2176 if (!nation_is_in_current_set(pnation
)
2178 || (needs_startpos
&& game
.scenario
.startpos_nations
2179 && pnation
->server
.no_startpos
)
2180 || (barb_type
!= nation_barbarian_type(pnation
))
2181 || (barb_type
== NOT_A_BARBARIAN
&& !is_nation_playable(pnation
))) {
2182 /* Nation is unplayable or already used: don't consider it.
2183 * (If nations aren't currently restricted to those with start
2184 * positions, we do nothing special here, but generate_players() will
2185 * tend to prefer them.) */
2186 nations_used
[idx
] = UNAVAILABLE
;
2191 nations_used
[idx
] = AVAILABLE
;
2193 /* Determine which nations look good with nations already in the game,
2194 * or conflict with them. */
2196 players_iterate(pplayer
) {
2197 if (pplayer
->nation
!= NO_NATION_SELECTED
) {
2198 int x
= nations_match(pnation
, nation_of_player(pplayer
),
2201 log_debug("Nations '%s' (nb %d) and '%s' (nb %d) are in conflict.",
2202 nation_rule_name(pnation
), nation_number(pnation
),
2203 nation_rule_name(nation_of_player(pplayer
)),
2204 nation_number(nation_of_player(pplayer
)));
2205 nations_used
[idx
] = UNWANTED
;
2206 match
[idx
] -= x
* 100;
2209 match
[idx
] += x
* 100;
2212 } players_iterate_end
;
2214 if (AVAILABLE
== nations_used
[idx
]) {
2215 num_avail_nations
+= match
[idx
];
2217 } nations_iterate_end
;
2219 /* Mark as preferred those nations which are on the choices list and
2220 * which are AVAILABLE, but no UNWANTED */
2221 if (NULL
!= choices
) {
2222 nation_list_iterate(choices
, pnation
) {
2223 idx
= nation_index(pnation
);
2224 if (nations_used
[idx
] == AVAILABLE
) {
2225 num_pref_nations
+= match
[idx
];
2226 nations_used
[idx
] = PREFERRED
;
2228 } nation_list_iterate_end
;
2231 if (0 < num_pref_nations
|| 0 < num_avail_nations
) {
2232 if (0 < num_pref_nations
) {
2233 /* Use a preferred nation only. */
2234 pick
= fc_rand(num_pref_nations
);
2235 looking_for
= PREFERRED
;
2236 log_debug("Picking a preferred nation.");
2238 /* Use any available nation. */
2239 fc_assert(0 < num_avail_nations
);
2240 pick
= fc_rand(num_avail_nations
);
2241 looking_for
= AVAILABLE
;
2242 log_debug("Picking an available nation.");
2245 nations_iterate(pnation
) {
2246 idx
= nation_index(pnation
);
2247 if (nations_used
[idx
] == looking_for
) {
2254 } nations_iterate_end
;
2256 /* No available nation: use unwanted nation... */
2257 struct nation_type
*less_worst_nation
= NO_NATION_SELECTED
;
2258 int less_worst_score
= -FC_INFINITY
;
2260 log_debug("Picking an unwanted nation.");
2261 nations_iterate(pnation
) {
2262 idx
= nation_index(pnation
);
2263 if (UNWANTED
== nations_used
[idx
]) {
2264 pick
= -fc_rand(match
[idx
]);
2265 if (pick
> less_worst_score
) {
2266 less_worst_nation
= pnation
;
2267 less_worst_score
= pick
;
2270 } nations_iterate_end
;
2272 if (NO_NATION_SELECTED
!= less_worst_nation
) {
2273 return less_worst_nation
;
2277 log_verbose("No nation found!");
2279 return NO_NATION_SELECTED
;
2282 /****************************************************************************
2283 Return the nationset currently in effect.
2284 ****************************************************************************/
2285 static struct nation_set
*current_nationset(void)
2287 return nation_set_by_setting_value(game
.server
.nationset
);
2290 /****************************************************************************
2291 Is the nation in the currently selected nationset?
2292 If not, it's not allowed to appear in the game.
2293 ****************************************************************************/
2294 bool nation_is_in_current_set(const struct nation_type
*pnation
)
2296 return nation_is_in_set(pnation
, current_nationset());
2299 /****************************************************************************
2300 Update the server's cached number of playable nations.
2301 Call when the nationset changes.
2302 ****************************************************************************/
2303 void count_playable_nations(void)
2305 server
.playable_nations
= 0;
2306 allowed_nations_iterate(pnation
) {
2307 if (is_nation_playable(pnation
)) {
2308 server
.playable_nations
++;
2310 } allowed_nations_iterate_end
;
2313 /****************************************************************************
2314 Return whether a nation is "pickable" -- whether players can select it
2316 (is_nation_pickable() is the equivalent function on the client.)
2317 ****************************************************************************/
2318 bool client_can_pick_nation(const struct nation_type
*pnation
)
2320 fc_assert_ret_val(pnation
!= NULL
, FALSE
);
2321 return nation_is_in_current_set(pnation
)
2322 && is_nation_playable(pnation
)
2323 && (!game
.scenario
.startpos_nations
2324 || !pnation
->server
.no_startpos
);
2327 /****************************************************************************
2328 Helper doing the actual work for send_nation_availability() (q.v.).
2329 ****************************************************************************/
2330 static void send_nation_availability_real(struct conn_list
*dest
,
2331 bool nationset_change
)
2333 struct packet_nation_availability packet
;
2335 packet
.ncount
= nation_count();
2336 packet
.nationset_change
= nationset_change
;
2337 nations_iterate(pnation
) {
2338 packet
.is_pickable
[nation_index(pnation
)] = client_can_pick_nation(pnation
);
2339 } nations_iterate_end
;
2340 lsend_packet_nation_availability(dest
, &packet
);
2343 /****************************************************************************
2344 Tell clients which nations can be picked given current server settings.
2345 ****************************************************************************/
2346 void send_nation_availability(struct conn_list
*dest
,
2347 bool nationset_change
)
2349 if (0 < player_info_frozen_level
) {
2350 return; /* Discard, see comment for player_info_freeze(). */
2352 send_nation_availability_real(dest
, nationset_change
);
2356 /****************************************************************************
2357 Try to select a nation set that fits the current players' nations, or
2358 failing that, unset the nations of some of the players.
2359 To be called when loading an old savegame that predates nationsets.
2360 ****************************************************************************/
2361 void fit_nationset_to_players(void)
2363 int misfits
[nation_set_count()];
2364 nation_sets_iterate(pset
) {
2365 misfits
[nation_set_index(pset
)] = 0;
2366 players_iterate(pplayer
) {
2367 if (pplayer
->nation
!= NO_NATION_SELECTED
2368 && !nation_is_in_set(pplayer
->nation
, pset
)) {
2369 misfits
[nation_set_index(pset
)]++;
2371 } players_iterate_end
;
2372 } nation_sets_iterate_end
;
2374 if (misfits
[nation_set_index(current_nationset())] == 0) {
2375 /* Current set is OK. */
2379 /* Otherwise, pick the least worst set (requires unsetting fewest
2380 * players, possibly none). */
2382 /* Quell compiler warning; but least_misfits initializer won't be used */
2383 int i
, least_misfits
= -1;
2384 const struct nation_set
*best
= NULL
;
2385 fc_assert(nation_set_count() > 0);
2386 for (i
= 0; i
< nation_set_count(); i
++) {
2387 if (best
== NULL
|| misfits
[i
] < least_misfits
) {
2388 best
= nation_set_by_number(i
);
2389 least_misfits
= misfits
[i
];
2390 if (least_misfits
== 0) {
2391 /* Not going to do any better. */
2396 fc_assert(least_misfits
>= 0);
2398 log_verbose("Current nationset \"%s\" doesn't fit all existing players.",
2399 nation_set_rule_name(current_nationset()));
2400 log_verbose("Selected nationset \"%s\".", nation_set_rule_name(best
));
2401 fc_strlcpy(game
.server
.nationset
, nation_set_rule_name(best
),
2402 sizeof(game
.server
.nationset
));
2403 count_playable_nations();
2404 /* No need to refresh clients, as we're assumed to be in the middle of
2405 * loading a savegame and will send new setting/availability later
2406 * along with everything else */
2409 /* The set we chose may not fit all the players; as a last resort,
2410 * unset nations (caller must then arrange new assignments). */
2411 players_iterate(pplayer
) {
2412 if (pplayer
->nation
!= NO_NATION_SELECTED
2413 && !nation_is_in_current_set(pplayer
->nation
)) {
2414 log_verbose("Nation %s of player %s not in nationset \"%s\", unsetting.",
2415 nation_plural_for_player(pplayer
), player_name(pplayer
),
2416 nation_set_rule_name(current_nationset()));
2417 player_set_nation(pplayer
, NO_NATION_SELECTED
);
2419 } players_iterate_end
;
2422 /****************************************************************************
2423 Called when something is changed; this resets everyone's readiness.
2424 ****************************************************************************/
2425 void reset_all_start_commands(bool plrchange
)
2427 if (S_S_INITIAL
!= server_state()) {
2430 players_iterate(pplayer
) {
2431 if (pplayer
->is_ready
) {
2432 bool persistent
= FALSE
;
2435 switch (game
.info
.persistent_ready
)
2437 case PERSISTENTR_DISABLED
:
2440 case PERSISTENTR_CONNECTED
:
2441 persistent
= pplayer
->is_connected
;
2447 pplayer
->is_ready
= FALSE
;
2448 send_player_info_c(pplayer
, game
.est_connections
);
2451 } players_iterate_end
;
2454 /**********************************************************************
2455 This function creates a new player and copies all of it's science
2456 research etc. Players are both thrown into anarchy and gold is
2457 split between both players.
2459 ***********************************************************************/
2460 static struct player
*split_player(struct player
*pplayer
)
2462 struct research
*new_research
, *old_research
;
2463 struct player
*cplayer
;
2464 struct nation_type
*rebel_nation
;
2466 /* make a new player, or not */
2467 cplayer
= server_create_player(-1, ai_name(pplayer
->ai
),
2472 server_player_init(cplayer
, TRUE
, TRUE
);
2474 /* Rebel will always be an AI player */
2475 rebel_nation
= pick_a_nation(nation_of_player(pplayer
)->server
.civilwar_nations
,
2476 TRUE
, FALSE
, NOT_A_BARBARIAN
);
2477 player_nation_defaults(cplayer
, rebel_nation
, TRUE
);
2479 fc_assert(game_was_started());
2480 /* Find a color for the new player. */
2481 assign_player_colors();
2483 /* Send information about the used player slot to all connections. */
2484 send_player_info_c(cplayer
, NULL
);
2486 sz_strlcpy(cplayer
->username
, _(ANON_USER_NAME
));
2487 cplayer
->unassigned_user
= TRUE
;
2488 cplayer
->is_connected
= FALSE
;
2489 cplayer
->government
= init_government_of_nation(nation_of_player(cplayer
));
2490 fc_assert(cplayer
->revolution_finishes
< 0);
2491 /* No capital for the splitted player. */
2492 cplayer
->server
.got_first_city
= FALSE
;
2494 players_iterate(other_player
) {
2495 struct player_diplstate
*ds_co
2496 = player_diplstate_get(cplayer
, other_player
);
2497 struct player_diplstate
*ds_oc
2498 = player_diplstate_get(other_player
, cplayer
);
2500 if (get_player_bonus(other_player
, EFT_NO_DIPLOMACY
) > 0) {
2501 ds_co
->type
= DS_WAR
;
2502 ds_oc
->type
= DS_WAR
;
2504 ds_co
->type
= DS_NO_CONTACT
;
2505 ds_oc
->type
= DS_NO_CONTACT
;
2508 ds_co
->has_reason_to_cancel
= 0;
2509 ds_co
->turns_left
= 0;
2510 ds_co
->contact_turns_left
= 0;
2511 ds_oc
->has_reason_to_cancel
= 0;
2512 ds_oc
->turns_left
= 0;
2513 ds_oc
->contact_turns_left
= 0;
2515 /* Send so that other_player sees updated diplomatic info;
2516 * pplayer will be sent later anyway
2518 if (other_player
!= pplayer
) {
2519 send_player_all_c(other_player
, other_player
->connections
);
2521 } players_iterate_end
;
2523 /* Split the resources */
2524 cplayer
->economic
.gold
= pplayer
->economic
.gold
;
2525 cplayer
->economic
.gold
/= 2;
2526 pplayer
->economic
.gold
-= cplayer
->economic
.gold
;
2528 /* Copy the research */
2529 new_research
= research_get(cplayer
);
2530 old_research
= research_get(pplayer
);
2532 new_research
->bulbs_researched
= 0;
2533 new_research
->techs_researched
= old_research
->techs_researched
;
2534 new_research
->researching
= old_research
->researching
;
2535 new_research
->tech_goal
= old_research
->tech_goal
;
2537 advance_index_iterate(A_NONE
, i
) {
2538 if (TECH_KNOWN
== research_invention_state(old_research
, i
)) {
2539 research_invention_set(new_research
, i
, TECH_KNOWN
);
2541 } advance_index_iterate_end
;
2542 cplayer
->phase_done
= TRUE
; /* Have other things to think
2543 about - paralysis */
2544 BV_CLR_ALL(cplayer
->real_embassy
); /* all embassies destroyed */
2545 research_update(new_research
);
2549 cplayer
->ai_common
.maxbuycost
= pplayer
->ai_common
.maxbuycost
;
2550 cplayer
->ai_common
.warmth
= pplayer
->ai_common
.warmth
;
2551 cplayer
->ai_common
.frost
= pplayer
->ai_common
.frost
;
2552 set_ai_level_direct(cplayer
, game
.info
.skill_level
);
2554 /* change the original player */
2555 if (government_of_player(pplayer
) != game
.government_during_revolution
) {
2556 pplayer
->target_government
= pplayer
->government
;
2557 pplayer
->government
= game
.government_during_revolution
;
2558 pplayer
->revolution_finishes
= game
.info
.turn
+ 1;
2560 old_research
->bulbs_researched
= 0;
2561 old_research
->researching_saved
= A_UNKNOWN
;
2562 BV_CLR_ALL(pplayer
->real_embassy
); /* all embassies destroyed */
2564 /* give splitted player the embassies to his team mates back, if any */
2565 if (pplayer
->team
) {
2566 players_iterate(pdest
) {
2567 if (pplayer
->team
== pdest
->team
2568 && pplayer
!= pdest
) {
2569 establish_embassy(pplayer
, pdest
);
2571 } players_iterate_end
;
2573 research_update(old_research
);
2575 pplayer
->economic
= player_limit_to_max_rates(pplayer
);
2579 give_map_from_player_to_player(pplayer
, cplayer
);
2581 pplayer
->server
.border_vision
= cplayer
->server
.border_vision
;
2583 /* Not sure if this is necessary, but might be a good idea
2584 * to avoid doing some ai calculations with bogus data. */
2585 adv_data_phase_init(cplayer
, TRUE
);
2586 CALL_PLR_AI_FUNC(phase_begin
, cplayer
, cplayer
, TRUE
);
2587 CALL_PLR_AI_FUNC(gained_control
, cplayer
, cplayer
);
2588 CALL_PLR_AI_FUNC(split_by_civil_war
, pplayer
, pplayer
, cplayer
);
2589 CALL_PLR_AI_FUNC(created_by_civil_war
, cplayer
, pplayer
, cplayer
);
2594 /**************************************************************************
2595 Check if civil war is possible for a player.
2596 If conquering_city is TRUE, one of the cities currently in the empire
2597 will shortly not be and shouldn't be considered.
2598 honour_server_option controls whether we honour the 'civilwarsize'
2599 server option. (If we don't, we still enforce a minimum empire size, to
2600 avoid the risk of creating a new player with no cities.)
2601 **************************************************************************/
2602 bool civil_war_possible(struct player
*pplayer
, bool conquering_city
,
2603 bool honour_server_option
)
2607 if (!game
.info
.civil_war_enabled
) {
2611 n
= city_list_size(pplayer
->cities
);
2613 if (n
- (conquering_city
?1:0) < GAME_MIN_CIVILWARSIZE
) {
2616 if (honour_server_option
) {
2617 return game
.server
.civilwarsize
< GAME_MAX_CIVILWARSIZE
2618 && n
>= game
.server
.civilwarsize
;
2624 /**********************************************************************
2625 civil_war_triggered:
2626 * The capture of a capital is not a sure fire way to throw
2627 and empire into civil war. Some governments are more susceptible
2628 than others, here are the base probabilities:
2632 Fundamentalism 60% (Only in civ2 ruleset)
2636 * In addition each city in disorder adds 5%, each celebrating city
2637 subtracts 5% from the probability of a civil war.
2638 * If you have at least 1 turns notice of the impending loss of
2639 your capital, you can hike luxuries up to the hightest value,
2640 and by this reduce the chance of a civil war. In fact by
2641 hiking the luxuries to 100% under Democracy, it is easy to
2642 get massively negative numbers - guaranteeing imunity from
2643 civil war. Likewise, 3 cities in disorder under despotism
2644 guarantees a civil war.
2645 * This routine calculates these probabilities and returns true
2646 if a civil war is triggered.
2648 ***********************************************************************/
2649 bool civil_war_triggered(struct player
*pplayer
)
2651 /* Get base probabilities */
2652 int dice
= fc_rand(100); /* Throw the dice */
2653 int prob
= get_player_bonus(pplayer
, EFT_CIVIL_WAR_CHANCE
);
2655 /* Now compute the contribution of the cities. */
2656 city_list_iterate(pplayer
->cities
, pcity
) {
2657 if (city_unhappy(pcity
)) {
2660 if (city_celebrating(pcity
)) {
2663 } city_list_iterate_end
;
2665 log_verbose("Civil war chance for %s: prob %d, dice %d",
2666 player_name(pplayer
), prob
, dice
);
2668 return (dice
< prob
);
2671 /**********************************************************************
2672 Capturing a nation's capital is a devastating blow. This function
2673 creates a new AI player, and randomly splits the original players
2674 city list into two. Of course this results in a real mix up of
2675 teritory - but since when have civil wars ever been tidy, or civil.
2677 Embassies: All embassies with other players are lost. Other players
2678 retain their embassies with pplayer.
2679 * Units: Units inside cities are assigned to the new owner
2680 of the city. Units outside are transferred along
2681 with the ownership of their supporting city.
2682 If the units are in a unit stack with non rebel units,
2683 then whichever units are nearest an allied city
2684 are teleported to that city. If the stack is a
2685 transport at sea, then all rebel units on the
2686 transport are teleported to their nearest allied city.
2688 Cities: Are split randomly into 2. This results in a real
2689 mix up of teritory - but since when have civil wars
2690 ever been tidy, or for any matter civil?
2692 One caveat, since the spliting of cities is random, you can
2693 conceive that this could result in either the original player
2694 or the rebel getting 0 cities. To prevent this, the hack below
2695 ensures that each side gets roughly half, which ones is still
2696 determined randomly.
2698 ***********************************************************************/
2699 struct player
*civil_war(struct player
*pplayer
)
2702 struct player
*cplayer
;
2703 struct city
*capital
;
2704 struct city_list
*defector_candidates
;
2706 /* It is possible that this function gets called after pplayer
2707 * died. Player pointers are safe even after death. */
2708 if (!pplayer
->is_alive
) {
2712 if (normal_player_count() >= MAX_NUM_PLAYERS
) {
2713 /* No space to make additional player */
2714 log_normal(_("Could not throw %s into civil war - too many players"),
2715 nation_plural_for_player(pplayer
));
2718 if (normal_player_count() >= server
.playable_nations
) {
2719 /* No nation for additional player */
2720 log_normal(_("Could not throw %s into civil war - no available nations"),
2721 nation_plural_for_player(pplayer
));
2725 /* It doesn't make sense to try to split an empire of 1 city.
2726 * This should have been enforced by civil_war_possible(). */
2727 fc_assert_ret_val(city_list_size(pplayer
->cities
) > 1, NULL
);
2729 defector_candidates
= city_list_new();
2730 city_list_iterate(pplayer
->cities
, pcity
) {
2731 bool gameloss_present
= FALSE
;
2733 /* Capital (probably new capital) won't defect */
2734 if (is_capital(pcity
)) {
2738 /* City hosting victim's GameLoss unit won't defect */
2739 unit_list_iterate(city_tile(pcity
)->units
, punit
) {
2740 if (unit_owner(punit
) == pplayer
2741 && unit_has_type_flag(punit
, UTYF_GAMELOSS
)) {
2742 gameloss_present
= TRUE
;
2745 } unit_list_iterate_end
;
2746 if (gameloss_present
) {
2750 city_list_append(defector_candidates
, pcity
);
2751 } city_list_iterate_end
;
2753 if (city_list_size(defector_candidates
) == 0) {
2754 log_verbose(_("Could not throw %s into civil war - no available cities"),
2755 nation_plural_for_player(pplayer
));
2756 city_list_destroy(defector_candidates
);
2760 /* We're definitely going to create a new rebel player. */
2762 if (normal_player_count() == game
.server
.max_players
) {
2763 /* 'maxplayers' must be increased to allow for a new player. */
2765 /* This assert should never be called due to the first check above. */
2766 fc_assert_ret_val(game
.server
.max_players
< MAX_NUM_PLAYERS
, NULL
);
2768 game
.server
.max_players
++;
2769 log_debug("Increased 'maxplayers' to allow the creation of a new player "
2770 "due to civil war.");
2773 cplayer
= split_player(pplayer
);
2775 /* Before units, cities, so clients know name of new nation
2776 * (for debugging etc).
2778 send_player_all_c(cplayer
, NULL
);
2779 send_player_all_c(pplayer
, NULL
);
2781 /* Now split the empire */
2783 log_verbose("%s civil war; created AI %s",
2784 nation_rule_name(nation_of_player(pplayer
)),
2785 nation_rule_name(nation_of_player(cplayer
)));
2786 notify_player(pplayer
, NULL
, E_CIVIL_WAR
, ftc_server
,
2787 _("Your nation is thrust into civil war."));
2789 notify_player(pplayer
, NULL
, E_FIRST_CONTACT
, ftc_server
,
2790 /* TRANS: <leader> ... the Poles. */
2791 _("%s is the rebellious leader of the %s."),
2792 player_name(cplayer
),
2793 nation_plural_for_player(cplayer
));
2795 j
= city_list_size(defector_candidates
); /* number left to process */
2796 /* Number to try to flip; ensure that at least one eligible city is
2799 city_list_iterate(defector_candidates
, pcity
) {
2800 fc_assert_action(!is_capital(pcity
), continue);
2801 if (i
>= j
|| (i
> 0 && fc_rand(2) == 1)) {
2802 /* Transfer city and units supported by this city to the new owner.
2803 * We do NOT resolve stack conflicts here, but rather later.
2804 * Reason: if we have a transporter from one city which is carrying
2805 * a unit from another city, and both cities join the rebellion. If we
2806 * resolved stack conflicts for each city we would teleport the first
2807 * of the units we met since the other would have another owner. */
2808 if (transfer_city(cplayer
, pcity
, -1, FALSE
, FALSE
, FALSE
, FALSE
)) {
2809 log_verbose("%s declares allegiance to the %s.", city_name_get(pcity
),
2810 nation_rule_name(nation_of_player(cplayer
)));
2811 notify_player(pplayer
, pcity
->tile
, E_CITY_LOST
, ftc_server
,
2812 /* TRANS: <city> ... the Poles. */
2813 _("%s declares allegiance to the %s."),
2815 nation_plural_for_player(cplayer
));
2816 script_server_signal_emit("city_transferred", 4,
2817 API_TYPE_CITY
, pcity
,
2818 API_TYPE_PLAYER
, pplayer
,
2819 API_TYPE_PLAYER
, cplayer
,
2820 API_TYPE_STRING
, "civil_war");
2825 } city_list_iterate_end
;
2827 city_list_destroy(defector_candidates
);
2829 resolve_unit_stacks(pplayer
, cplayer
, FALSE
);
2831 i
= city_list_size(cplayer
->cities
);
2832 fc_assert(i
> 0); /* rebels should have got at least one city */
2834 /* Choose a capital (random). */
2835 capital
= city_list_get(cplayer
->cities
, fc_rand(i
));
2836 city_build_free_buildings(capital
);
2837 give_midgame_initial_units(cplayer
, city_tile(capital
));
2839 notify_player(NULL
, NULL
, E_CIVIL_WAR
, ftc_server
,
2840 /* TRANS: ... Danes ... Poles ... <7> cities. */
2841 PL_("Civil war partitions the %s;"
2842 " the %s now hold %d city.",
2843 "Civil war partitions the %s;"
2844 " the %s now hold %d cities.",
2846 nation_plural_for_player(pplayer
),
2847 nation_plural_for_player(cplayer
),
2853 /**************************************************************************
2854 The client has send as a chunk of the attribute block.
2855 **************************************************************************/
2856 void handle_player_attribute_chunk(struct player
*pplayer
,
2857 const struct packet_player_attribute_chunk
2860 generic_handle_player_attribute_chunk(pplayer
, chunk
);
2863 /**************************************************************************
2864 The client request an attribute block.
2865 **************************************************************************/
2866 void handle_player_attribute_block(struct player
*pplayer
)
2868 send_attribute_block(pplayer
, pplayer
->current_conn
);
2871 /**************************************************************************
2873 (Hmm, how should "turn done" work for multi-connected non-observer players?)
2874 **************************************************************************/
2875 void handle_player_phase_done(struct player
*pplayer
,
2878 if (turn
!= game
.info
.turn
) {
2879 /* If this happens then the player actually pressed turn-done on a
2880 * previous turn but we didn't receive it until now. The player
2881 * probably didn't actually mean to end their turn! */
2884 pplayer
->phase_done
= TRUE
;
2886 check_for_full_turn_done();
2888 send_player_all_c(pplayer
, NULL
);
2891 /**************************************************************************
2892 Return the number of barbarian players.
2893 **************************************************************************/
2894 int barbarian_count(void)
2896 return server
.nbarbarians
;
2899 /**************************************************************************
2900 Return the number of non-barbarian players.
2901 **************************************************************************/
2902 int normal_player_count(void)
2904 return player_count() - server
.nbarbarians
;
2907 /****************************************************************************
2908 Add a status flag to a player.
2909 ****************************************************************************/
2910 void player_status_add(struct player
*plr
, enum player_status pstatus
)
2912 BV_SET(plr
->server
.status
, pstatus
);
2915 /****************************************************************************
2916 Check player status flag.
2917 ****************************************************************************/
2918 bool player_status_check(struct player
*plr
, enum player_status pstatus
)
2920 return BV_ISSET(plr
->server
.status
, pstatus
);
2923 /****************************************************************************
2924 Reset player status to 'normal'.
2925 ****************************************************************************/
2926 void player_status_reset(struct player
*plr
)
2928 BV_CLR_ALL(plr
->server
.status
);
2929 player_status_add(plr
, PSTATUS_NORMAL
);
2932 /**************************************************************************
2933 Returns the username that control of the player is delegated to, if any.
2934 **************************************************************************/
2935 const char *player_delegation_get(const struct player
*pplayer
)
2937 if (pplayer
== NULL
|| strlen(pplayer
->server
.delegate_to
) == 0) {
2938 /* No delegation if there is no player. */
2941 return pplayer
->server
.delegate_to
;
2945 /**************************************************************************
2946 Define a delegation. NULL for no delegate.
2947 **************************************************************************/
2948 void player_delegation_set(struct player
*pplayer
, const char *username
)
2950 fc_assert_ret(pplayer
!= NULL
);
2952 if (username
== NULL
|| strlen(username
) == 0) {
2953 pplayer
->server
.delegate_to
[0] = '\0';
2955 sz_strlcpy(pplayer
->server
.delegate_to
, username
);
2959 /*****************************************************************************
2960 Returns TRUE if a delegation is active.
2961 This means that either the player is controlled by a delegate, or the
2962 player has been temporarily 'put aside' by a delegate.
2963 *****************************************************************************/
2964 bool player_delegation_active(const struct player
*pplayer
)
2966 return (pplayer
&& strlen(pplayer
->server
.orig_username
) != 0);
2969 /*****************************************************************************
2970 Send information about delegations to reconnecting users.
2971 *****************************************************************************/
2972 void send_delegation_info(const struct connection
*pconn
)
2974 if (game
.info
.is_new_game
) {
2978 if (!pconn
->observer
2979 && pconn
->playing
&& player_delegation_get(pconn
->playing
) != NULL
) {
2980 notify_conn(pconn
->self
, NULL
, E_CONNECTION
, ftc_server
,
2981 /* TRANS: '/delegate cancel' is a server command and must not
2983 _("User '%s' is currently allowed to take control of your "
2984 "player while you are away. Use '/delegate cancel' to "
2985 "revoke this access."),
2986 player_delegation_get(pconn
->playing
));
2990 bool any_delegations
= FALSE
;
2991 players_iterate(aplayer
) {
2992 if (player_delegation_get(aplayer
) != NULL
2993 && strcmp(player_delegation_get(aplayer
), pconn
->username
) == 0) {
2994 notify_conn(pconn
->self
, NULL
, E_CONNECTION
, ftc_server
,
2995 _("Control of player '%s' is delegated to you."),
2996 player_name(aplayer
));
2997 any_delegations
= TRUE
;
2999 } players_iterate_end
;
3000 if (any_delegations
) {
3001 notify_conn(pconn
->self
, NULL
, E_CONNECTION
, ftc_server
,
3002 /* TRANS: '/delegate take' is a server command and must not
3003 * be translated; but <player> should be translated. */
3004 _("Use '/delegate take <player>' to take control of a "
3005 "delegated player."));
3010 /*****************************************************************************
3011 For a given user, if there is some player that the user originally
3012 controlled but is currently delegated to another user, return that player.
3013 See also player_by_user().
3014 *****************************************************************************/
3015 struct player
*player_by_user_delegated(const char *name
)
3017 players_iterate(pplayer
) {
3018 if (player_delegation_get(pplayer
)
3019 && fc_strcasecmp(name
, pplayer
->server
.orig_username
) == 0) {
3022 } players_iterate_end
;
3027 /****************************************************************************
3028 Initialise the player colors.
3029 ****************************************************************************/
3030 void playercolor_init(void)
3032 fc_assert_ret(game
.server
.plr_colors
== NULL
);
3033 game
.server
.plr_colors
= rgbcolor_list_new();
3036 /****************************************************************************
3037 Free the memory allocated for the player color.
3038 ****************************************************************************/
3039 void playercolor_free(void)
3041 if (game
.server
.plr_colors
== NULL
) {
3045 if (rgbcolor_list_size(game
.server
.plr_colors
) > 0) {
3046 rgbcolor_list_iterate(game
.server
.plr_colors
, prgbcolor
) {
3047 rgbcolor_list_remove(game
.server
.plr_colors
, prgbcolor
);
3048 rgbcolor_destroy(prgbcolor
);
3049 } rgbcolor_list_iterate_end
;
3051 rgbcolor_list_destroy(game
.server
.plr_colors
);
3052 game
.server
.plr_colors
= NULL
;
3055 /****************************************************************************
3056 Add a color to the list of all available player colors.
3057 ****************************************************************************/
3058 void playercolor_add(struct rgbcolor
*prgbcolor
)
3060 fc_assert_ret(game
.server
.plr_colors
!= NULL
);
3062 rgbcolor_list_append(game
.server
.plr_colors
, prgbcolor
);
3065 /****************************************************************************
3066 Get the player color with the index 'id'.
3067 ****************************************************************************/
3068 struct rgbcolor
*playercolor_get(int id
)
3070 fc_assert_ret_val(game
.server
.plr_colors
!= NULL
, NULL
);
3072 return rgbcolor_list_get(game
.server
.plr_colors
, id
);
3075 /****************************************************************************
3076 Number of player colors defined.
3077 ****************************************************************************/
3078 int playercolor_count(void)
3080 fc_assert_ret_val(game
.server
.plr_colors
!= NULL
, -1);
3082 return rgbcolor_list_size(game
.server
.plr_colors
);
3085 /****************************************************************************
3086 Sets player's multipliers.
3087 ****************************************************************************/
3088 void handle_player_multiplier(struct player
*pplayer
, int count
,
3089 const int *multipliers
)
3094 if (count
!= multiplier_count()) {
3095 log_error("Bad number of multipliers %d from client for %s",
3096 count
, player_name(pplayer
));
3100 for (i
= 0; i
< count
; i
++) {
3101 struct multiplier
*pmul
= multiplier_by_number(i
);
3103 if (multipliers
[i
] < pmul
->start
|| multipliers
[i
] > pmul
->stop
) {
3104 log_error("Multiplier value %d for %s out of range for %s",
3105 multipliers
[i
], multiplier_rule_name(pmul
),
3106 player_name(pplayer
));
3110 rval
= (multipliers
[i
] - pmul
->start
) / pmul
->step
* pmul
->step
+ pmul
->start
;
3111 if (rval
!= multipliers
[i
]) {
3112 log_error("Multiplier value %d between valid values for %s for %s",
3113 multipliers
[i
], multiplier_rule_name(pmul
),
3114 player_name(pplayer
));
3119 for (i
= 0; i
< count
; i
++) {
3120 pplayer
->multipliers_target
[i
] = multipliers
[i
];
3123 send_player_info_c(pplayer
, NULL
);
3126 /****************************************************************************
3127 Toggle player to AI mode.
3128 ****************************************************************************/
3129 void player_set_to_ai_mode(struct player
*pplayer
, enum ai_level skill_level
)
3133 set_ai_level_directer(pplayer
, skill_level
);
3134 cancel_all_meetings(pplayer
);
3135 CALL_PLR_AI_FUNC(gained_control
, pplayer
, pplayer
);
3136 if (is_player_phase(pplayer
, game
.info
.phase
)) {
3137 CALL_PLR_AI_FUNC(restart_phase
, pplayer
, pplayer
);
3140 if (S_S_RUNNING
== server_state()) {
3141 /* In case this was last player who has not pressed turn done. */
3142 check_for_full_turn_done();
3145 fc_assert(pplayer
->ai_common
.skill_level
== skill_level
);
3148 /****************************************************************************
3149 Toggle player under human control.
3150 ****************************************************************************/
3151 void player_set_under_human_control(struct player
*pplayer
)
3153 set_as_human(pplayer
);
3155 if (pplayer
->ai_common
.skill_level
== AI_LEVEL_AWAY
) {
3156 pplayer
->ai_common
.skill_level
= ai_level_invalid();
3159 CALL_PLR_AI_FUNC(lost_control
, pplayer
, pplayer
);
3161 /* Because the AI "cheats" with government rates but humans shouldn't. */
3162 if (!game
.info
.is_new_game
) {
3163 check_player_max_rates(pplayer
);
3165 cancel_all_meetings(pplayer
);