webperimental: killstack decides stack protects.
[freeciv.git] / server / srv_main.c
blobc60a60e2c56b18e77069824d29448724f6a6f695
1 /***********************************************************************
2 Freeciv - Copyright (C) 1996 - A Kjeldberg, L Gregersen, P Unold
3 This program is free software; you can redistribute it and/or modify
4 it under the terms of the GNU General Public License as published by
5 the Free Software Foundation; either version 2, or (at your option)
6 any later version.
8 This program is distributed in the hope that it will be useful,
9 but WITHOUT ANY WARRANTY; without even the implied warranty of
10 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 GNU General Public License for more details.
12 ***********************************************************************/
14 #ifdef HAVE_CONFIG_H
15 #include <fc_config.h>
16 #endif
18 #include "fc_prehdrs.h"
20 #include <ctype.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <time.h>
26 #ifdef HAVE_NETDB_H
27 #include <netdb.h>
28 #endif
29 #ifdef HAVE_SYS_IOCTL_H
30 #include <sys/ioctl.h>
31 #endif
32 #ifdef HAVE_SYS_TERMIO_H
33 #include <sys/termio.h>
34 #endif
35 #ifdef FREECIV_HAVE_SYS_TYPES_H
36 #include <sys/types.h>
37 #endif
38 #ifdef HAVE_TERMIOS_H
39 #include <termios.h>
40 #endif
41 #ifdef HAVE_UNISTD_H
42 #include <unistd.h>
43 #endif
45 /* utility */
46 #include "astring.h"
47 #include "bitvector.h"
48 #include "bugs.h"
49 #include "capability.h"
50 #include "fc_cmdline.h"
51 #include "fciconv.h"
52 #include "fcintl.h"
53 #include "log.h"
54 #include "mem.h"
55 #include "netintf.h"
56 #include "rand.h"
57 #include "registry.h"
58 #include "support.h"
59 #include "timing.h"
61 /* common/aicore */
62 #include "citymap.h"
64 /* common */
65 #include "achievements.h"
66 #include "calendar.h"
67 #include "capstr.h"
68 #include "city.h"
69 #include "culture.h"
70 #include "dataio.h"
71 #include "effects.h"
72 #include "events.h"
73 #include "fc_interface.h"
74 #include "government.h"
75 #include "map.h"
76 #include "mapimg.h"
77 #include "nation.h"
78 #include "packets.h"
79 #include "player.h"
80 #include "research.h"
81 #include "tech.h"
82 #include "unitlist.h"
83 #include "version.h"
84 #include "victory.h"
86 /* server */
87 #include "aiiface.h"
88 #include "animals.h"
89 #include "auth.h"
90 #include "barbarian.h"
91 #include "cityhand.h"
92 #include "citytools.h"
93 #include "cityturn.h"
94 #include "connecthand.h"
95 #include "console.h"
96 #include "fcdb.h"
97 #include "diplhand.h"
98 #include "edithand.h"
99 #include "gamehand.h"
100 #include "handchat.h"
101 #include "maphand.h"
102 #include "meta.h"
103 #include "notify.h"
104 #include "plrhand.h"
105 #include "report.h"
106 #include "ruleset.h"
107 #include "sanitycheck.h"
108 #include "savegame.h"
109 #include "score.h"
110 #include "sernet.h"
111 #include "settings.h"
112 #include "spacerace.h"
113 #include "srv_log.h"
114 #include "stdinhand.h"
115 #include "techtools.h"
116 #include "unithand.h"
117 #include "unittools.h"
118 #include "voting.h"
120 /* server/advisors */
121 #include "advdata.h"
122 #include "autosettlers.h"
123 #include "advbuilding.h"
124 #include "advspace.h"
125 #include "infracache.h"
127 /* server/scripting */
128 #include "script_server.h"
129 #include "luascript_types.h"
131 /* server/generator */
132 #include "mapgen.h"
133 #include "mapgen_utils.h"
135 /* ai */
136 #include "aitraits.h"
137 #include "difficulty.h"
139 #include "srv_main.h"
141 static void end_turn(void);
142 static void announce_player(struct player *pplayer);
143 static void fc_interface_init_server(void);
145 static enum known_type mapimg_server_tile_known(const struct tile *ptile,
146 const struct player *pplayer,
147 bool knowledge);
148 static struct terrain
149 *mapimg_server_tile_terrain(const struct tile *ptile,
150 const struct player *pplayer, bool knowledge);
151 static struct player *mapimg_server_tile_owner(const struct tile *ptile,
152 const struct player *pplayer,
153 bool knowledge);
154 static struct player *mapimg_server_tile_city(const struct tile *ptile,
155 const struct player *pplayer,
156 bool knowledge);
157 static struct player *mapimg_server_tile_unit(const struct tile *ptile,
158 const struct player *pplayer,
159 bool knowledge);
161 static int mapimg_server_plrcolor_count(void);
162 static struct rgbcolor *mapimg_server_plrcolor_get(int i);
164 static void handle_observer_ready(struct connection *pconn);
166 /* command-line arguments to server */
167 struct server_arguments srvarg;
169 /* server aggregate information */
170 struct civserver server;
172 /* server state information */
173 static enum server_states civserver_state = S_S_INITIAL;
175 /* this global is checked deep down the netcode.
176 packets handling functions can set it to none-zero, to
177 force end-of-tick asap
179 bool force_end_of_sniff;
181 #define IDENTITY_NUMBER_SIZE 250000
182 BV_DEFINE(bv_identity_numbers, IDENTITY_NUMBER_SIZE);
183 bv_identity_numbers identity_numbers_used;
185 /* server initialized flag */
186 static bool has_been_srv_init = FALSE;
188 /* time server processing at end-of-turn */
189 static struct timer *eot_timer = NULL;
191 static struct timer *between_turns = NULL;
193 /**************************************************************************
194 Initialize the game seed. This may safely be called multiple times.
195 **************************************************************************/
196 void init_game_seed(void)
198 if (game.server.seed_setting == 0) {
199 /* We strip the high bit for now because neither game file nor
200 server options can handle unsigned ints yet. - Cedric */
201 game.server.seed = time(NULL) & (MAX_UINT32 >> 1);
202 #ifdef FREECIV_TESTMATIC
203 /* Log command to reproduce the gameseed */
204 log_testmatic("set gameseed %d", game.server.seed);
205 #else /* FREECIV_TESTMATIC */
206 log_debug("Setting game.seed:%d", game.server.seed);
207 #endif /* FREECIV_TESTMATIC */
208 } else {
209 game.server.seed = game.server.seed_setting;
212 if (!fc_rand_is_init()) {
213 fc_srand(game.server.seed);
217 /**************************************************************************
218 Initialize freeciv server.
219 **************************************************************************/
220 void srv_init(void)
222 i_am_server(); /* Tell to libfreeciv that we are server */
224 /* NLS init */
225 init_nls();
226 #ifdef ENABLE_NLS
227 (void) bindtextdomain("freeciv-nations", get_locale_dir());
228 #endif
230 /* This is before ai module initializations so that if ai module
231 * wants to use registry files, it can. */
232 registry_module_init();
234 /* We want this before any AI stuff */
235 timing_log_init();
237 /* This must be before command line argument parsing.
238 This allocates default ai, and we want that to take place before
239 loading additional ai modules from command line. */
240 ai_init();
242 /* init server arguments... */
244 srvarg.metaserver_no_send = DEFAULT_META_SERVER_NO_SEND;
245 sz_strlcpy(srvarg.metaserver_addr, DEFAULT_META_SERVER_ADDR);
246 srvarg.metaconnection_persistent = FALSE;
247 srvarg.identity_name[0] = '\0';
248 srvarg.serverid[0] = '\0';
250 srvarg.bind_addr = NULL;
251 #ifdef FREECIV_JSON_CONNECTION
252 srvarg.port = FREECIV_JSON_PORT;
253 #else /* FREECIV_JSON_CONNECTION */
254 srvarg.port = DEFAULT_SOCK_PORT;
255 #endif /* FREECIV_JSON_CONNECTION */
257 srvarg.bind_meta_addr = NULL;
259 srvarg.loglevel = LOG_NORMAL;
261 srvarg.log_filename = NULL;
262 srvarg.fatal_assertions = -1;
263 srvarg.ranklog_filename = NULL;
264 srvarg.load_filename[0] = '\0';
265 srvarg.script_filename = NULL;
266 srvarg.saves_pathname = "";
267 srvarg.scenarios_pathname = "";
268 srvarg.ruleset = NULL;
270 srvarg.quitidle = 0;
272 srvarg.fcdb_enabled = FALSE;
273 srvarg.fcdb_conf = NULL;
274 srvarg.auth_enabled = FALSE;
275 srvarg.auth_allow_guests = FALSE;
276 srvarg.auth_allow_newusers = FALSE;
278 /* mark as initialized */
279 has_been_srv_init = TRUE;
281 /* init character encodings. */
282 init_character_encodings(FC_DEFAULT_DATA_ENCODING, FALSE);
283 #ifdef ENABLE_NLS
284 bind_textdomain_codeset("freeciv-nations", get_internal_encoding());
285 #endif
287 /* Initialize callbacks. */
288 game.callbacks.unit_deallocate = identity_number_release;
290 /* Initialize global mutexes */
291 fc_init_mutex(&game.server.mutexes.city_list);
293 /* done */
294 return;
297 /**************************************************************************
298 Handle client info packet
299 **************************************************************************/
300 void handle_client_info(struct connection *pc, enum gui_type gui,
301 const char *distribution)
303 pc->client_gui = gui;
304 log_debug("%s's client has %s gui.", pc->username, gui_type_name(gui));
305 if (strcmp(distribution, "")) {
306 log_debug("It comes from %s distribution.", distribution);
310 /**************************************************************************
311 Return current server state.
312 **************************************************************************/
313 enum server_states server_state(void)
315 return civserver_state;
318 /**************************************************************************
319 Set current server state.
320 **************************************************************************/
321 void set_server_state(enum server_states newstate)
323 civserver_state = newstate;
326 /**************************************************************************
327 Returns iff the game was started once upon a time.
328 **************************************************************************/
329 bool game_was_started(void)
331 return (!game.info.is_new_game || S_S_INITIAL != server_state());
334 /****************************************************************************
335 Returns TRUE if any one game end condition is fulfilled, FALSE otherwise.
337 This function will notify players but will not set the server_state(). The
338 caller must set the server state to S_S_OVER if the function
339 returns TRUE.
340 ****************************************************************************/
341 bool check_for_game_over(void)
343 int candidates, defeated;
344 struct player *victor;
345 int winners = 0;
346 struct astring str = ASTRING_INIT;
348 /* Check for scenario victory; dead players can win if they are on a team
349 * with the winners. */
350 players_iterate(pplayer) {
351 if (player_status_check(pplayer, PSTATUS_WINNER)
352 || get_player_bonus(pplayer, EFT_VICTORY) > 0) {
353 if (winners) {
354 /* TRANS: Another entry in winners list (", the Tibetans") */
355 astr_add(&str, Q_("?winners:, the %s"),
356 nation_plural_for_player(pplayer));
357 } else {
358 /* TRANS: Beginning of the winners list ("the French") */
359 astr_add(&str, Q_("?winners:the %s"),
360 nation_plural_for_player(pplayer));
362 pplayer->is_winner = TRUE;
363 winners++;
365 } players_iterate_end;
366 if (winners) {
367 notify_conn(game.est_connections, NULL, E_GAME_END, ftc_server,
368 /* TRANS: There can be several winners listed */
369 _("Scenario victory to %s."), astr_str(&str));
370 astr_free(&str);
371 return TRUE;
373 astr_free(&str);
375 /* Count candidates for the victory. */
376 candidates = 0;
377 defeated = 0;
378 victor = NULL;
379 /* Do not use player_iterate_alive here - dead player must be counted as
380 * defeated to end the game with a victory. */
381 players_iterate(pplayer) {
382 if (is_barbarian(pplayer)) {
383 continue;
386 if ((pplayer)->is_alive
387 && !player_status_check((pplayer), PSTATUS_SURRENDER)) {
388 candidates++;
389 victor = pplayer;
390 } else {
391 defeated++;
393 } players_iterate_end;
395 if (0 == candidates) {
396 notify_conn(game.est_connections, NULL, E_GAME_END, ftc_server,
397 _("Game is over."));
398 return TRUE;
399 } else if (0 < defeated) {
400 /* If nobody conceded the game, it mays be a solo game or a single team
401 * game. */
402 fc_assert(NULL != victor);
404 /* Quit if we have team victory. */
405 if (1 < team_count()) {
406 teams_iterate(pteam) {
407 const struct player_list *members = team_members(pteam);
408 int team_candidates = 0, team_defeated = 0;
410 if (1 == player_list_size(members)) {
411 /* This is not really a team, single players are handled below. */
412 continue;
415 player_list_iterate(members, pplayer) {
416 if (pplayer->is_alive
417 && !player_status_check((pplayer), PSTATUS_SURRENDER)) {
418 team_candidates++;
419 } else {
420 team_defeated++;
422 } player_list_iterate_end;
424 fc_assert(team_candidates + team_defeated
425 == player_list_size(members));
427 if (team_candidates == candidates && team_defeated < defeated) {
428 /* We need a player in a other team to conced the game here. */
429 notify_conn(game.est_connections, NULL, E_GAME_END, ftc_server,
430 _("Team victory to %s."),
431 team_name_translation(pteam));
432 /* All players of the team win, even dead and surrended ones. */
433 player_list_iterate(members, pplayer) {
434 pplayer->is_winner = TRUE;
435 } player_list_iterate_end;
436 return TRUE;
438 } teams_iterate_end;
441 /* Check for allied victory. */
442 if (1 < candidates && victory_enabled(VC_ALLIED)) {
443 struct player_list *winner_list = player_list_new();
445 /* Try to build a winner list. */
446 players_iterate_alive(pplayer) {
447 if (is_barbarian(pplayer)
448 || player_status_check((pplayer), PSTATUS_SURRENDER)) {
449 continue;
452 player_list_iterate(winner_list, aplayer) {
453 if (!pplayers_allied(aplayer, pplayer)) {
454 player_list_destroy(winner_list);
455 winner_list = NULL;
456 break;
458 } player_list_iterate_end;
460 if (NULL == winner_list) {
461 break;
463 player_list_append(winner_list, pplayer);
464 } players_iterate_alive_end;
466 if (NULL != winner_list) {
467 bool first = TRUE;
469 fc_assert(candidates == player_list_size(winner_list));
471 astr_init(&str);
472 player_list_iterate(winner_list, pplayer) {
473 if (first) {
474 /* TRANS: Beginning of the winners list ("the French") */
475 astr_add(&str, Q_("?winners:the %s"),
476 nation_plural_for_player(pplayer));
477 first = FALSE;
478 } else {
479 /* TRANS: Another entry in winners list (", the Tibetans") */
480 astr_add(&str, Q_("?winners:, the %s"),
481 nation_plural_for_player(pplayer));
483 pplayer->is_winner = TRUE;
484 } player_list_iterate_end;
485 notify_conn(game.est_connections, NULL, E_GAME_END, ftc_server,
486 /* TRANS: There can be several winners listed */
487 _("Allied victory to %s."), astr_str(&str));
488 astr_free(&str);
489 player_list_destroy(winner_list);
490 return TRUE;
494 /* Check for single player victory. */
495 if (1 == candidates && NULL != victor) {
496 bool found = FALSE; /* We need at least one enemy defeated. */
498 players_iterate(pplayer) {
499 if (pplayer != victor
500 && !is_barbarian(pplayer)
501 && (!pplayer->is_alive
502 || player_status_check((pplayer), PSTATUS_SURRENDER))
503 && pplayer->team != victor->team
504 && (!victory_enabled(VC_ALLIED)
505 || !pplayers_allied(victor, pplayer))) {
506 found = TRUE;
507 break;
509 } players_iterate_end;
511 if (found) {
512 notify_conn(game.est_connections, NULL, E_GAME_END, ftc_server,
513 _("Game ended in conquest victory for %s."), player_name(victor));
514 victor->is_winner = TRUE;
515 return TRUE;
520 /* Check for culture victory */
521 if (victory_enabled(VC_CULTURE)) {
522 struct player *best = NULL;
523 int best_value = -1;
524 int second_value = -1;
526 players_iterate(pplayer) {
527 if (is_barbarian(pplayer) || !pplayer->is_alive) {
528 continue;
531 if (pplayer->score.culture > best_value) {
532 best = pplayer;
533 second_value = best_value;
534 best_value = pplayer->score.culture;
535 } else if (pplayer->score.culture > second_value) {
536 second_value = pplayer->score.culture;
538 } players_iterate_end;
540 if (best != NULL && best_value >= game.info.culture_vic_points
541 && best_value > second_value * (100 + game.info.culture_vic_lead) / 100) {
542 notify_conn(game.est_connections, NULL, E_GAME_END, ftc_server,
543 _("Game ended in cultural domination victory for %s."),
544 player_name(best));
545 best->is_winner = TRUE;
547 return TRUE;
551 /* Quit if we are past the turn limit. */
552 if (game.info.turn > game.server.end_turn) {
553 notify_conn(game.est_connections, NULL, E_GAME_END, ftc_server,
554 _("Game ended as the turn limit was exceeded."));
555 return TRUE;
558 /* Check for a spacerace win. */
559 while ((victor = check_spaceship_arrival())) {
560 const struct player_list *members;
561 bool win;
563 notify_player(NULL, NULL, E_SPACESHIP, ftc_server,
564 _("The %s spaceship has arrived at Alpha Centauri."),
565 nation_adjective_for_player(victor));
567 if (!game.server.endspaceship) {
568 /* Games does not end on spaceship arrival. At least print all the
569 * arrival messages. */
570 continue;
573 /* This guy has won, now check if anybody else wins with him. */
574 members = team_members(victor->team);
575 win = FALSE;
576 player_list_iterate(members, pplayer) {
577 if (pplayer->is_alive
578 && !player_status_check((pplayer), PSTATUS_SURRENDER)) {
579 /* We need at least one player to be a winner candidate in the
580 * team. */
581 win = TRUE;
582 break;
584 } player_list_iterate_end;
586 if (!win) {
587 /* Let's try next arrival. */
588 continue;
591 if (1 < player_list_size(members)) {
592 notify_conn(NULL, NULL, E_GAME_END, ftc_server,
593 _("Team victory to %s."),
594 team_name_translation(victor->team));
595 /* All players of the team win, even dead and surrended ones. */
596 player_list_iterate(members, pplayer) {
597 pplayer->is_winner = TRUE;
598 } player_list_iterate_end;
599 } else {
600 notify_conn(NULL, NULL, E_GAME_END, ftc_server,
601 _("Game ended in victory for %s."), player_name(victor));
602 victor->is_winner = TRUE;
604 return TRUE;
607 return FALSE;
610 /**************************************************************************
611 Send all information for when game starts or client reconnects.
612 Initial packets should have been sent before calling this function.
613 See comment in connecthand.c::establish_new_connection().
614 **************************************************************************/
615 void send_all_info(struct conn_list *dest)
617 conn_list_iterate(dest, pconn) {
618 if (conn_controls_player(pconn)) {
619 send_attribute_block(pconn->playing, pconn);
621 } conn_list_iterate_end;
623 /* Resend player info because it could have more infos (e.g. embassy). */
624 send_player_all_c(NULL, dest);
625 researches_iterate(presearch) {
626 send_research_info(presearch, dest);
627 } researches_iterate_end;
628 send_map_info(dest);
629 send_all_known_tiles(dest);
630 send_all_known_cities(dest);
631 send_all_known_units(dest);
632 send_spaceship_info(NULL, dest);
634 cities_iterate(pcity) {
635 package_and_send_worker_tasks(pcity);
636 } cities_iterate_end;
639 /**************************************************************************
640 Give map information to players with EFT_REVEAL_CITIES or
641 EFT_REVEAL_MAP effects (traditionally from the Apollo Program).
642 **************************************************************************/
643 static void do_reveal_effects(void)
645 phase_players_iterate(pplayer) {
646 if (get_player_bonus(pplayer, EFT_REVEAL_CITIES) > 0) {
647 players_iterate(other_player) {
648 city_list_iterate(other_player->cities, pcity) {
649 map_show_tile(pplayer, pcity->tile);
650 } city_list_iterate_end;
651 } players_iterate_end;
653 if (get_player_bonus(pplayer, EFT_REVEAL_MAP) > 0) {
654 /* map_know_all will mark all unknown tiles as known and send
655 * tile, unit, and city updates as necessary. No other actions are
656 * needed. */
657 map_show_all(pplayer);
659 } phase_players_iterate_end;
662 /**************************************************************************
663 Give contact to players with the EFT_HAVE_CONTACTS effect (traditionally
664 from Marco Polo's Embassy).
665 **************************************************************************/
666 static void do_have_contacts_effect(void)
668 phase_players_iterate(pplayer) {
669 if (get_player_bonus(pplayer, EFT_HAVE_CONTACTS) > 0) {
670 players_iterate(pother) {
671 /* Note this gives pplayer contact with pother, but doesn't give
672 * pother contact with pplayer. This may cause problems in other
673 * parts of the code if we're not careful. */
674 make_contact(pplayer, pother, NULL);
675 } players_iterate_end;
677 } phase_players_iterate_end;
680 /**************************************************************************
681 Handle the vision granting effect EFT_BORDER_VISION
682 **************************************************************************/
683 static void do_border_vision_effect(void)
685 if (game.info.borders != BORDERS_ENABLED) {
686 /* Border_Vision is useless. If borders are disabled there are no
687 * borders to see inside. If borders are seen they are seen already.
688 * The borders setting can't change after the game has started. */
689 return;
692 phase_players_iterate(plr) {
693 bool new_border_vision;
695 /* Check the Border_Vision effect for this player. */
696 new_border_vision = (0 < get_player_bonus(plr, EFT_BORDER_VISION));
698 if (new_border_vision != plr->server.border_vision) {
699 /* Border vision changed. */
701 /* Update the map */
702 map_set_border_vision(plr, new_border_vision);
704 } phase_players_iterate_end;
707 /**************************************************************************
708 Handle environmental upsets, meaning currently pollution or fallout.
709 **************************************************************************/
710 static void update_environmental_upset(enum environment_upset_type type,
711 int *current, int *accum, int *level,
712 void (*upset_action_fn)(int))
714 int count;
716 count = 0;
717 extra_type_iterate(cause) {
718 if (extra_causes_env_upset(cause, type)) {
719 whole_map_iterate(&(wld.map), ptile) {
720 if (tile_has_extra(ptile, cause)) {
721 count++;
723 } whole_map_iterate_end;
725 } extra_type_iterate_end;
727 *current = count;
728 *accum += count;
729 if (*accum < *level) {
730 *accum = 0;
731 } else {
732 *accum -= *level;
733 if (fc_rand((map_num_tiles() + 19) / 20) <= *accum) {
734 upset_action_fn((wld.map.xsize / 10) + (wld.map.ysize / 10) + ((*accum) * 5));
735 *accum = 0;
736 *level += (map_num_tiles() + 999) / 1000;
740 log_debug("environmental_upset: type=%-4d current=%-2d "
741 "level=%-2d accum=%-2d", type, *current, *level, *accum);
744 /**************************************************************************
745 Remove illegal units when armistice turns into peace treaty.
746 **************************************************************************/
747 static void remove_illegal_armistice_units(struct player *plr1,
748 struct player *plr2)
750 /* Remove illegal units */
751 unit_list_iterate_safe(plr1->units, punit) {
752 if (tile_owner(unit_tile(punit)) == plr2
753 && is_military_unit(punit)) {
754 notify_player(plr1, unit_tile(punit), E_DIPLOMACY, ftc_server,
755 _("Your %s was disbanded in accordance with "
756 "your peace treaty with the %s."),
757 unit_tile_link(punit),
758 nation_plural_for_player(plr2));
759 wipe_unit(punit, ULR_ARMISTICE, NULL);
761 } unit_list_iterate_safe_end;
762 unit_list_iterate_safe(plr2->units, punit) {
763 if (tile_owner(unit_tile(punit)) == plr1
764 && is_military_unit(punit)) {
765 notify_player(plr2, unit_tile(punit), E_DIPLOMACY, ftc_server,
766 _("Your %s was disbanded in accordance with "
767 "your peace treaty with the %s."),
768 unit_tile_link(punit),
769 nation_plural_for_player(plr1));
770 wipe_unit(punit, ULR_ARMISTICE, NULL);
772 } unit_list_iterate_safe_end;
775 /**************************************************************************
776 Check for cease-fires and armistices running out; update cancelling
777 reasons and contact information.
778 **************************************************************************/
779 static void update_diplomatics(void)
781 players_iterate(plr1) {
782 players_iterate(plr2) {
783 struct player_diplstate *state = player_diplstate_get(plr1, plr2);
785 /* Players might just met when first of them was being handled
786 * (pact with third player changed and units got bounced next
787 * to second unit to form first contact)
788 * Do not decrease the counters for the other player yet in this turn */
789 if (state->first_contact_turn != game.info.turn) {
790 struct player_diplstate *state2 = player_diplstate_get(plr2, plr1);
792 state->has_reason_to_cancel = MAX(state->has_reason_to_cancel - 1, 0);
793 state->contact_turns_left = MAX(state->contact_turns_left - 1, 0);
795 if (state->type == DS_ARMISTICE
796 /* Don't count down if auto canceled this turn. Auto canceling
797 * happens in this loop. */
798 && state->auto_cancel_turn != game.info.turn) {
799 state->turns_left--;
800 if (state->turns_left <= 0) {
801 state->type = DS_PEACE;
802 state2->type = DS_PEACE;
803 state->turns_left = 0;
804 state2->turns_left = 0;
805 remove_illegal_armistice_units(plr1, plr2);
809 if (state->type == DS_CEASEFIRE) {
810 state->turns_left--;
811 switch(state->turns_left) {
812 case 1:
813 notify_player(plr1, NULL, E_DIPLOMACY, ftc_server,
814 _("Concerned citizens point out that the cease-fire "
815 "with %s will run out soon."), player_name(plr2));
816 /* Message to plr2 will be done when plr1 and plr2 will be swapped.
817 * Else, we will get a message duplication. Note the case is not
818 * the below, because the state will be changed for both players to
819 * war. */
820 break;
821 case 0:
822 notify_player(plr1, NULL, E_DIPLOMACY, ftc_server,
823 _("The cease-fire with %s has run out. "
824 "You are now at war with the %s."),
825 player_name(plr2),
826 nation_plural_for_player(plr2));
827 notify_player(plr2, NULL, E_DIPLOMACY, ftc_server,
828 _("The cease-fire with %s has run out. "
829 "You are now at war with the %s."),
830 player_name(plr1),
831 nation_plural_for_player(plr1));
832 state->type = DS_WAR;
833 state2->type = DS_WAR;
834 state->turns_left = 0;
835 state2->turns_left = 0;
837 enter_war(plr1, plr2);
839 city_map_update_all_cities_for_player(plr1);
840 city_map_update_all_cities_for_player(plr2);
841 sync_cities();
843 /* Avoid love-love-hate triangles */
844 players_iterate_alive(plr3) {
845 if (plr3 != plr1 && plr3 != plr2
846 && pplayers_allied(plr3, plr1)
847 && pplayers_allied(plr3, plr2)) {
848 struct player_diplstate *to1
849 = player_diplstate_get(plr3, plr1);
850 struct player_diplstate *from1
851 = player_diplstate_get(plr1, plr3);
852 struct player_diplstate *to2
853 = player_diplstate_get(plr3, plr2);
854 struct player_diplstate *from2
855 = player_diplstate_get(plr2, plr3);
856 const char *plr1name = player_name(plr1);
857 const char *plr2name = player_name(plr2);
858 bool cancel1;
859 bool cancel2;
861 if (players_on_same_team(plr3, plr1)) {
862 fc_assert(!players_on_same_team(plr3, plr2));
864 cancel1 = FALSE;
865 cancel2 = TRUE;
867 notify_player(plr3, NULL, E_TREATY_BROKEN, ftc_server,
868 _("The cease-fire between %s and %s has run out. "
869 "They are at war. You cancel your alliance "
870 "with %s."),
871 plr1name, plr2name, plr2name);
872 } else if (players_on_same_team(plr3, plr2)) {
874 cancel1 = TRUE;
875 cancel2 = FALSE;
877 notify_player(plr3, NULL, E_TREATY_BROKEN, ftc_server,
878 _("The cease-fire between %s and %s has run out. "
879 "They are at war. You cancel your alliance "
880 "with %s."),
881 plr1name, plr2name, plr1name);
882 } else {
884 cancel1 = TRUE;
885 cancel2 = TRUE;
887 notify_player(plr3, NULL, E_TREATY_BROKEN, ftc_server,
888 _("The cease-fire between %s and %s has run out. "
889 "They are at war. You cancel your alliance "
890 "with both."),
891 player_name(plr1),
892 player_name(plr2));
895 if (cancel1) {
896 /* Cancel the alliance. */
897 to1->has_reason_to_cancel = TRUE;
898 handle_diplomacy_cancel_pact(plr3, player_number(plr1), CLAUSE_ALLIANCE);
900 /* Avoid asymmetric turns_left for the armistice. */
901 to1->auto_cancel_turn = game.info.turn;
902 from1->auto_cancel_turn = game.info.turn;
904 /* Count down for this turn. */
905 to1->turns_left--;
906 from1->turns_left--;
909 if (cancel2) {
910 /* Cancel the alliance. */
911 to2->has_reason_to_cancel = TRUE;
912 handle_diplomacy_cancel_pact(plr3, player_number(plr2), CLAUSE_ALLIANCE);
914 /* Avoid asymmetric turns_left for the armistice. */
915 to2->auto_cancel_turn = game.info.turn;
916 from2->auto_cancel_turn = game.info.turn;
918 /* Count down for this turn. */
919 to2->turns_left--;
920 from2->turns_left--;
923 } players_iterate_alive_end;
924 break;
928 } players_iterate_end;
929 } players_iterate_end;
932 /****************************************************************************
933 Check all players to see whether they are dying.
935 WARNING: do not call this while doing any handling of players, units,
936 etc. If a player dies, all his units will be wiped and other data will
937 be overwritten.
938 ****************************************************************************/
939 static void kill_dying_players(void)
941 bool voter_died = FALSE;
943 players_iterate_alive(pplayer) {
944 /* cities or units remain? */
945 if (0 == city_list_size(pplayer->cities)
946 && 0 == unit_list_size(pplayer->units)) {
947 player_status_add(pplayer, PSTATUS_DYING);
949 /* also UTYF_GAMELOSS in unittools server_remove_unit() */
950 if (player_status_check(pplayer, PSTATUS_DYING)) {
951 /* Can't get more dead than this. */
952 voter_died = voter_died || pplayer->is_connected;
953 kill_player(pplayer);
955 } players_iterate_alive_end;
957 if (voter_died) {
958 send_updated_vote_totals(NULL);
962 /**************************************************************************
963 Called at the start of each (new) phase to do AI activities.
964 **************************************************************************/
965 static void ai_start_phase(void)
967 phase_players_iterate(pplayer) {
968 if (is_ai(pplayer)) {
969 CALL_PLR_AI_FUNC(first_activities, pplayer, pplayer);
971 } phase_players_iterate_end;
972 kill_dying_players();
975 /**************************************************************************
976 Handle the beginning of each turn.
977 Note: This does not give "time" to any player;
978 it is solely for updating turn-dependent data.
979 **************************************************************************/
980 static void begin_turn(bool is_new_turn)
982 log_debug("Begin turn");
984 event_cache_remove_old();
986 /* Reset this each turn. */
987 if (is_new_turn) {
988 if (game.info.phase_mode != game.server.phase_mode_stored) {
989 event_cache_phases_invalidate();
990 game.info.phase_mode = game.server.phase_mode_stored;
994 /* NB: Phase logic must match is_player_phase(). */
995 switch (game.info.phase_mode) {
996 case PMT_CONCURRENT:
997 game.server.num_phases = 1;
998 break;
999 case PMT_PLAYERS_ALTERNATE:
1000 game.server.num_phases = player_count();
1001 break;
1002 case PMT_TEAMS_ALTERNATE:
1003 game.server.num_phases = team_count();
1004 break;
1005 default:
1006 log_error("Unrecognized phase mode %d in begin_turn().",
1007 game.info.phase_mode);
1008 game.server.num_phases = 1;
1009 break;
1011 send_game_info(NULL);
1013 if (is_new_turn) {
1014 script_server_signal_emit("turn_begin", 2,
1015 API_TYPE_INT, game.info.turn,
1016 API_TYPE_INT, game.info.year);
1017 script_server_signal_emit("turn_started", 2,
1018 API_TYPE_INT, game.info.turn > 0 ? game.info.turn - 1: game.info.turn,
1019 API_TYPE_INT, game.info.year);
1021 /* We build scores at the beginning of every turn. We have to
1022 * build them at the beginning so that the AI can use the data,
1023 * and we are sure to have it when we need it. */
1024 players_iterate(pplayer) {
1025 calc_civ_score(pplayer);
1026 } players_iterate_end;
1027 log_civ_score_now();
1029 /* Retire useless barbarian units */
1030 players_iterate(pplayer) {
1031 unit_list_iterate_safe(pplayer->units, punit) {
1032 struct tile *ptile = punit->tile;
1034 if (unit_can_be_retired(punit)
1035 && fc_rand(100) < get_unit_bonus(punit, EFT_RETIRE_PCT)) {
1036 notify_player(pplayer, ptile, E_UNIT_LOST_MISC, ftc_server,
1037 /* TRANS: %s is a unit type */
1038 _("%s retired!"), unit_tile_link(punit));
1039 wipe_unit(punit, ULR_RETIRED, NULL);
1040 continue;
1042 } unit_list_iterate_safe_end;
1043 } players_iterate_end;
1046 /* find out if users attached to players have been attached to those players
1047 * for long enough. The first user to do so becomes "associated" to that
1048 * player for ranking purposes. */
1049 players_iterate(pplayer) {
1050 if (pplayer->unassigned_ranked
1051 && pplayer->user_turns++ > TURNS_NEEDED_TO_RANK
1052 && pplayer->is_alive) {
1053 sz_strlcpy(pplayer->ranked_username, pplayer->username);
1054 pplayer->unassigned_ranked = pplayer->unassigned_user;
1056 } players_iterate_end;
1058 if (is_new_turn) {
1059 /* See if the value of fog of war has changed */
1060 if (game.info.fogofwar != game.server.fogofwar_old) {
1061 if (game.info.fogofwar) {
1062 enable_fog_of_war();
1063 game.server.fogofwar_old = TRUE;
1064 } else {
1065 disable_fog_of_war();
1066 game.server.fogofwar_old = FALSE;
1070 if (game.info.phase_mode == PMT_CONCURRENT) {
1071 log_debug("Shuffleplayers");
1072 shuffle_players();
1075 game.info.phase = 0;
1078 sanity_check();
1081 /**************************************************************************
1082 Begin a phase of movement. This handles all beginning-of-phase actions
1083 for one or more players.
1084 **************************************************************************/
1085 static void begin_phase(bool is_new_phase)
1087 log_debug("Begin phase");
1089 conn_list_do_buffer(game.est_connections);
1091 phase_players_iterate(pplayer) {
1092 if (is_new_phase || !game.server.turnblock) {
1093 /* Otherwise respect what was loaded from the savegame. */
1094 pplayer->phase_done = FALSE;
1096 pplayer->ai_phase_done = FALSE;
1097 } phase_players_iterate_end;
1098 send_player_all_c(NULL, NULL);
1100 dlsend_packet_start_phase(game.est_connections, game.info.phase);
1102 if (!is_new_phase) {
1103 conn_list_iterate(game.est_connections, pconn) {
1104 send_diplomatic_meetings(pconn);
1105 } conn_list_iterate_end;
1108 /* Must be the first thing as it is needed for lots of functions below! */
1109 phase_players_iterate(pplayer) {
1110 /* human players also need this for building advice */
1111 adv_data_phase_init(pplayer, is_new_phase);
1112 CALL_PLR_AI_FUNC(phase_begin, pplayer, pplayer, is_new_phase);
1113 } phase_players_iterate_end;
1115 if (is_new_phase) {
1116 /* Unit "end of turn" activities - of course these actually go at
1117 * the start of the turn! */
1118 phase_players_iterate(pplayer) {
1119 update_unit_activities(pplayer);
1120 flush_packets();
1121 } phase_players_iterate_end;
1122 /* Execute orders after activities have been completed (roads built,
1123 * pillage done, etc.). */
1124 phase_players_iterate(pplayer) {
1125 execute_unit_orders(pplayer);
1126 flush_packets();
1127 } phase_players_iterate_end;
1128 phase_players_iterate(pplayer) {
1129 finalize_unit_phase_beginning(pplayer);
1130 } phase_players_iterate_end;
1131 flush_packets();
1134 phase_players_iterate(pplayer) {
1135 log_debug("beginning player turn for #%d (%s)",
1136 player_number(pplayer), player_name(pplayer));
1137 if (is_human(pplayer)) {
1138 building_advisor(pplayer);
1140 } phase_players_iterate_end;
1142 phase_players_iterate(pplayer) {
1143 send_player_cities(pplayer);
1144 } phase_players_iterate_end;
1146 flush_packets(); /* to curb major city spam */
1147 conn_list_do_unbuffer(game.est_connections);
1149 alive_phase_players_iterate(pplayer) {
1150 update_revolution(pplayer);
1151 } alive_phase_players_iterate_end;
1153 if (is_new_phase) {
1154 /* Try to avoid hiding events under a diplomacy dialog */
1155 phase_players_iterate(pplayer) {
1156 if (is_ai(pplayer)) {
1157 CALL_PLR_AI_FUNC(diplomacy_actions, pplayer, pplayer);
1159 } phase_players_iterate_end;
1161 log_debug("Aistartturn");
1162 ai_start_phase();
1163 } else {
1164 phase_players_iterate(pplayer) {
1165 if (is_ai(pplayer)) {
1166 CALL_PLR_AI_FUNC(restart_phase, pplayer, pplayer);
1168 } phase_players_iterate_end;
1171 sanity_check();
1173 game.tinfo.last_turn_change_time = (float)game.server.turn_change_time;
1174 game.tinfo.seconds_to_phasedone = (double)current_turn_timeout();
1175 game.server.phase_timer = timer_renew(game.server.phase_timer,
1176 TIMER_USER, TIMER_ACTIVE);
1177 timer_start(game.server.phase_timer);
1178 send_game_info(NULL);
1180 if (game.server.num_phases == 1) {
1181 /* All players in the same phase.
1182 * This means that AI has been handled above, and server
1183 * will be responsive again */
1184 lsend_packet_begin_turn(game.est_connections);
1188 /**************************************************************************
1189 End a phase of movement. This handles all end-of-phase actions
1190 for one or more players.
1191 **************************************************************************/
1192 static void end_phase(void)
1194 log_debug("Endphase");
1197 * This empties the client Messages window; put this before
1198 * everything else below, since otherwise any messages from the
1199 * following parts get wiped out before the user gets a chance to
1200 * see them. --dwp
1202 phase_players_iterate(pplayer) {
1203 /* Unlike the start_phase packet we only send this one to the active
1204 * player. */
1205 lsend_packet_end_phase(pplayer->connections);
1206 } phase_players_iterate_end;
1208 /* Enact any policy changes.
1209 * Do this first so that following end-phase activities take the
1210 * change into account. */
1211 phase_players_iterate(pplayer) {
1212 multipliers_iterate(pmul) {
1213 pplayer->multipliers[multiplier_index(pmul)] =
1214 pplayer->multipliers_target[multiplier_index(pmul)];
1215 } multipliers_iterate_end;
1216 } phase_players_iterate_end;
1218 phase_players_iterate(pplayer) {
1219 struct research *presearch = research_get(pplayer);
1221 if (A_UNSET == presearch->researching) {
1222 Tech_type_id next_tech = research_goal_step(presearch,
1223 presearch->tech_goal);
1225 if (A_UNSET != next_tech) {
1226 choose_tech(presearch, next_tech);
1227 } else {
1228 choose_random_tech(presearch);
1230 /* add the researched bulbs to the pool; do *NOT* checvk for finished
1231 * research */
1232 update_bulbs(pplayer, 0, FALSE);
1234 } phase_players_iterate_end;
1236 /* Freeze sending of cities. */
1237 send_city_suppression(TRUE);
1239 /* AI end of turn activities */
1240 players_iterate(pplayer) {
1241 unit_list_iterate(pplayer->units, punit) {
1242 CALL_PLR_AI_FUNC(unit_turn_end, pplayer, punit);
1243 } unit_list_iterate_end;
1244 } players_iterate_end;
1245 phase_players_iterate(pplayer) {
1246 auto_settlers_player(pplayer);
1247 if (is_ai(pplayer)) {
1248 CALL_PLR_AI_FUNC(last_activities, pplayer, pplayer);
1250 } phase_players_iterate_end;
1252 /* Refresh cities */
1253 phase_players_iterate(pplayer) {
1254 research_get(pplayer)->got_tech = FALSE;
1255 } phase_players_iterate_end;
1257 phase_players_iterate(pplayer) {
1258 do_tech_parasite_effect(pplayer);
1259 player_restore_units(pplayer);
1261 /* If player finished spaceship parts last turn already, and didn't place them
1262 * during this entire turn, autoplace them. */
1263 if (adv_spaceship_autoplace(pplayer, &pplayer->spaceship)) {
1264 notify_player(pplayer, NULL, E_SPACESHIP, ftc_server,
1265 _("Automatically placed spaceship parts that were still not placed."));
1268 update_city_activities(pplayer);
1269 city_thaw_workers_queue();
1270 pplayer->culture += nation_history_gain(pplayer);
1271 research_get(pplayer)->researching_saved = A_UNKNOWN;
1272 /* reduce the number of bulbs by the amount needed for tech upkeep and
1273 * check for finished research */
1274 update_bulbs(pplayer, -player_tech_upkeep(pplayer), TRUE);
1275 flush_packets();
1276 } phase_players_iterate_end;
1278 /* Some player/global effect may have changed cities' vision range */
1279 phase_players_iterate(pplayer) {
1280 refresh_player_cities_vision(pplayer);
1281 } phase_players_iterate_end;
1283 kill_dying_players();
1285 /* Unfreeze sending of cities. */
1286 send_city_suppression(FALSE);
1288 phase_players_iterate(pplayer) {
1289 send_player_cities(pplayer);
1290 } phase_players_iterate_end;
1291 flush_packets(); /* to curb major city spam */
1293 do_reveal_effects();
1294 do_have_contacts_effect();
1295 do_border_vision_effect();
1297 phase_players_iterate(pplayer) {
1298 CALL_PLR_AI_FUNC(phase_finished, pplayer, pplayer);
1299 /* This has to be after all access to advisor data. */
1300 /* We used to run this for ai players only, but data phase
1301 is initialized for human players also. */
1302 adv_data_phase_done(pplayer);
1303 } phase_players_iterate_end;
1306 /**************************************************************************
1307 Handle the end of each turn.
1308 **************************************************************************/
1309 static void end_turn(void)
1311 int food = 0, shields = 0, trade = 0, settlers = 0;
1313 log_debug("Endturn");
1315 /* Hack: because observer players never get an end-phase packet we send
1316 * one here. */
1317 conn_list_iterate(game.est_connections, pconn) {
1318 if (NULL == pconn->playing) {
1319 send_packet_end_phase(pconn);
1321 } conn_list_iterate_end;
1323 lsend_packet_end_turn(game.est_connections);
1325 map_calculate_borders();
1327 /* Output some AI measurement information */
1328 players_iterate(pplayer) {
1329 if (!is_ai(pplayer) || is_barbarian(pplayer)) {
1330 continue;
1332 unit_list_iterate(pplayer->units, punit) {
1333 if (unit_is_cityfounder(punit)) {
1334 settlers++;
1336 } unit_list_iterate_end;
1337 city_list_iterate(pplayer->cities, pcity) {
1338 shields += pcity->prod[O_SHIELD];
1339 food += pcity->prod[O_FOOD];
1340 trade += pcity->prod[O_TRADE];
1341 } city_list_iterate_end;
1342 log_debug("%s T%d cities:%d pop:%d food:%d prod:%d "
1343 "trade:%d settlers:%d units:%d", player_name(pplayer),
1344 game.info.turn, city_list_size(pplayer->cities),
1345 total_player_citizens(pplayer), food, shields, trade,
1346 settlers, unit_list_size(pplayer->units));
1347 } players_iterate_end;
1349 log_debug("Season of native unrests");
1350 summon_barbarians(); /* wild guess really, no idea where to put it, but
1351 * I want to give them chance to move their units */
1353 if (game.server.migration) {
1354 log_debug("Season of migrations");
1355 if (check_city_migrations()) {
1356 /* Make sure everyone has updated information about BOTH ends of the
1357 * migration movements. */
1358 players_iterate(plr) {
1359 city_list_iterate(plr->cities, pcity) {
1360 send_city_info(NULL, pcity);
1361 } city_list_iterate_end;
1362 } players_iterate_end;
1366 check_disasters();
1368 /* Check for new achievements during the turn.
1369 * This is not within phase, as multiple players may
1370 * achieve at the same turn and everyone deserves equal opportunity
1371 * to win. */
1372 achievements_iterate(ach) {
1373 struct player_list *achievers = player_list_new();
1374 struct player *first = achievement_plr(ach, achievers);
1375 struct packet_achievement_info pack;
1377 pack.id = achievement_index(ach);
1378 pack.gained = TRUE;
1380 if (first != NULL) {
1381 notify_player(first, NULL, E_ACHIEVEMENT, ftc_server,
1382 "%s", achievement_first_msg(ach));
1384 pack.first = TRUE;
1386 lsend_packet_achievement_info(first->connections, &pack);
1388 script_server_signal_emit("achievement_gained", 3,
1389 API_TYPE_ACHIEVEMENT, ach,
1390 API_TYPE_PLAYER, first,
1391 API_TYPE_BOOL, TRUE);
1395 pack.first = FALSE;
1397 if (!ach->unique) {
1398 player_list_iterate(achievers, pplayer) {
1399 /* Message already sent to first one */
1400 if (pplayer != first) {
1401 notify_player(pplayer, NULL, E_ACHIEVEMENT, ftc_server,
1402 "%s", achievement_later_msg(ach));
1404 lsend_packet_achievement_info(pplayer->connections, &pack);
1406 script_server_signal_emit("achievement_gained", 3,
1407 API_TYPE_ACHIEVEMENT, ach,
1408 API_TYPE_PLAYER, pplayer,
1409 API_TYPE_BOOL, FALSE);
1411 } player_list_iterate_end;
1414 player_list_destroy(achievers);
1415 } achievements_iterate_end;
1417 if (game.info.global_warming) {
1418 update_environmental_upset(EUT_GLOBAL_WARMING, &game.info.heating,
1419 &game.info.globalwarming,
1420 &game.info.warminglevel, global_warming);
1423 if (game.info.nuclear_winter) {
1424 update_environmental_upset(EUT_NUCLEAR_WINTER, &game.info.cooling,
1425 &game.info.nuclearwinter,
1426 &game.info.coolinglevel, nuclear_winter);
1429 /* Handle disappearing extras before appearing extras ->
1430 * Extra never appears only to disappear at the same turn,
1431 * but it can disappear and reappear. */
1432 extra_type_by_rmcause_iterate(ERM_DISAPPEARANCE, pextra) {
1433 whole_map_iterate(&(wld.map), ptile) {
1434 if (tile_has_extra(ptile, pextra)
1435 && fc_rand(10000) < pextra->disappearance_chance
1436 && can_extra_disappear(pextra, ptile)) {
1437 tile_extra_rm_apply(ptile, pextra);
1439 update_tile_knowledge(ptile);
1441 if (tile_owner(ptile) != NULL) {
1442 /* TODO: Should notify players nearby even when borders disabled,
1443 * like in case of barbarian uprising */
1444 notify_player(tile_owner(ptile), ptile,
1445 E_SPONTANEOUS_EXTRA, ftc_server,
1446 /* TRANS: Small Fish disappears from (32, 72). */
1447 _("%s disappears from %s."),
1448 extra_name_translation(pextra),
1449 tile_link(ptile));
1452 /* Unit activities at the target tile and its neighbors may now
1453 * be illegal because of present reqs. */
1454 unit_activities_cancel_all_illegal(ptile);
1455 adjc_iterate(&(wld.map), ptile, n_tile) {
1456 unit_activities_cancel_all_illegal(n_tile);
1457 } adjc_iterate_end;
1459 } whole_map_iterate_end;
1460 } extra_type_by_rmcause_iterate_end;
1462 extra_type_by_cause_iterate(EC_APPEARANCE, pextra) {
1463 whole_map_iterate(&(wld.map), ptile) {
1464 if (!tile_has_extra(ptile, pextra)
1465 && fc_rand(10000) < pextra->appearance_chance
1466 && can_extra_appear(pextra, ptile)) {
1468 tile_extra_apply(ptile, pextra);
1470 update_tile_knowledge(ptile);
1472 if (tile_owner(ptile) != NULL) {
1473 /* TODO: Should notify players nearby even when borders disabled,
1474 * like in case of barbarian uprising */
1475 notify_player(tile_owner(ptile), ptile,
1476 E_SPONTANEOUS_EXTRA, ftc_server,
1477 /* TRANS: Small Fish appears to (32, 72). */
1478 _("%s appears to %s."),
1479 extra_name_translation(pextra),
1480 tile_link(ptile));
1483 /* Unit activities at the target tile and its neighbors may now
1484 * be illegal because of !present reqs. */
1485 unit_activities_cancel_all_illegal(ptile);
1486 adjc_iterate(&(wld.map), ptile, n_tile) {
1487 unit_activities_cancel_all_illegal(n_tile);
1488 } adjc_iterate_end;
1490 } whole_map_iterate_end;
1491 } extra_type_by_cause_iterate_end;
1493 update_diplomatics();
1494 make_history_report();
1495 settings_turn();
1496 stdinhand_turn();
1497 voting_turn();
1498 send_city_turn_notifications(NULL);
1500 log_debug("Gamenextyear");
1501 game_advance_year();
1502 players_iterate_alive(pplayer) {
1503 pplayer->turns_alive++;
1504 } players_iterate_alive_end;
1506 log_debug("Updatetimeout");
1507 update_timeout();
1509 log_debug("Sendgameinfo");
1510 send_game_info(NULL);
1512 log_debug("Sendplayerinfo");
1513 send_player_all_c(NULL, NULL);
1515 log_debug("Sendresearchinfo");
1516 researches_iterate(presearch) {
1517 send_research_info(presearch, NULL);
1518 } researches_iterate_end;
1520 log_debug("Sendyeartoclients");
1521 send_year_to_clients();
1524 /**************************************************************************
1525 Save game with autosave filename
1526 **************************************************************************/
1527 void save_game_auto(const char *save_reason, enum autosave_type type)
1529 char filename[512];
1530 const char *reason_filename = NULL;
1532 if (!(game.server.autosaves & (1 << type))) {
1533 return;
1536 switch (type) {
1537 case AS_TURN:
1538 reason_filename = NULL;
1539 break;
1540 case AS_GAME_OVER:
1541 reason_filename = "final";
1542 break;
1543 case AS_QUITIDLE:
1544 reason_filename = "quitidle";
1545 break;
1546 case AS_INTERRUPT:
1547 reason_filename = "interrupted";
1548 break;
1549 case AS_TIMER:
1550 reason_filename = "timer";
1551 break;
1554 fc_assert(256 > strlen(game.server.save_name));
1556 if (type != AS_TIMER) {
1557 generate_save_name(game.server.save_name, filename, sizeof(filename),
1558 reason_filename);
1559 } else {
1560 fc_snprintf(filename, sizeof(filename), "%s-timer", game.server.save_name);
1562 save_game(filename, save_reason, FALSE);
1565 /**************************************************************************
1566 Start actual game. Everything has been set up already.
1567 **************************************************************************/
1568 void start_game(void)
1570 if (S_S_INITIAL != server_state()) {
1571 con_puts(C_SYNTAX, _("The game is already running."));
1572 return;
1575 /* Remove ALLOW_CTRL from whoever has it (gotten from 'first'). */
1576 conn_list_iterate(game.est_connections, pconn) {
1577 if (pconn->access_level == ALLOW_CTRL) {
1578 notify_conn(NULL, NULL, E_SETTING, ftc_server,
1579 _("%s lost control cmdlevel on "
1580 "game start. Use voting from now on."),
1581 pconn->username);
1582 conn_set_access(pconn, ALLOW_BASIC, FALSE);
1584 } conn_list_iterate_end;
1585 set_running_game_access_level();
1587 con_puts(C_OK, _("Starting game."));
1589 /* Prevent problems with commands that only make sense in pregame. */
1590 clear_all_votes();
1592 /* This value defines if the player data should be saved for a scenario. It
1593 * is only FALSE if the editor was used to set it to this value. For
1594 * such scenarios it has to be resetted at game start so that player data
1595 * is saved. */
1596 game.scenario.players = TRUE;
1598 force_end_of_sniff = TRUE;
1599 /* There's no stateful packet set to client until srv_ready(). */
1602 /**************************************************************************
1603 Quit the server and exit.
1604 **************************************************************************/
1605 void server_quit(void)
1607 if (server_state() == S_S_RUNNING) {
1608 /* Quitting mid-game. */
1610 phase_players_iterate(pplayer) {
1611 CALL_PLR_AI_FUNC(phase_finished, pplayer, pplayer);
1612 /* This has to be after all access to advisor data. */
1613 /* We used to run this for ai players only, but data phase
1614 is initialized for human players also. */
1615 adv_data_phase_done(pplayer);
1616 } phase_players_iterate_end;
1619 if (game.server.save_timer != NULL) {
1620 timer_destroy(game.server.save_timer);
1621 game.server.save_timer = NULL;
1623 if (between_turns != NULL) {
1624 timer_destroy(between_turns);
1625 between_turns = NULL;
1627 if (eot_timer != NULL) {
1628 timer_destroy(eot_timer);
1630 set_server_state(S_S_OVER);
1631 mapimg_free();
1632 server_game_free();
1633 diplhand_free();
1634 voting_free();
1635 adv_settlers_free();
1636 ai_timer_free();
1637 if (game.server.phase_timer != NULL) {
1638 timer_destroy(game.server.phase_timer);
1639 game.server.phase_timer = NULL;
1641 if (game.server.save_timer != NULL) {
1642 timer_destroy(game.server.save_timer);
1643 game.server.save_timer = NULL;
1646 #ifdef HAVE_FCDB
1647 if (srvarg.fcdb_enabled) {
1648 /* If freeciv database has been initialized */
1649 fcdb_free();
1651 #endif /* HAVE_FCDB */
1653 settings_free();
1654 stdinhand_free();
1655 edithand_free();
1656 voting_free();
1657 generator_free();
1658 close_connections_and_socket();
1659 rulesets_deinit();
1660 ruleset_choices_free();
1661 CALL_FUNC_EACH_AI(module_close);
1662 timing_log_free();
1663 registry_module_close();
1664 fc_destroy_mutex(&game.server.mutexes.city_list);
1665 free_libfreeciv();
1666 free_nls();
1667 con_log_close();
1668 cmdline_option_values_free();
1669 exit(EXIT_SUCCESS);
1672 /**************************************************************************
1673 Handle request asking report to be sent to client.
1674 **************************************************************************/
1675 void handle_report_req(struct connection *pconn, enum report_type type)
1677 struct conn_list *dest = pconn->self;
1679 if (S_S_RUNNING != server_state() && S_S_OVER != server_state()) {
1680 log_error("Got a report request %d before game start", type);
1681 return;
1684 if (NULL == pconn->playing && !pconn->observer) {
1685 log_error("Got a report request %d from detached connection", type);
1686 return;
1689 switch(type) {
1690 case REPORT_WONDERS_OF_THE_WORLD:
1691 report_wonders_of_the_world(dest);
1692 return;
1693 case REPORT_TOP_5_CITIES:
1694 report_top_five_cities(dest);
1695 return;
1696 case REPORT_DEMOGRAPHIC:
1697 report_demographics(pconn);
1698 return;
1699 case REPORT_ACHIEVEMENTS:
1700 report_achievements(pconn);
1701 return;
1704 notify_conn(dest, NULL, E_BAD_COMMAND, ftc_server,
1705 _("request for unknown report (type %d)"), type);
1708 /**************************************************************************
1709 Mark identity number free.
1710 **************************************************************************/
1711 void identity_number_release(int id)
1713 BV_CLR(identity_numbers_used, id);
1716 /**************************************************************************
1717 Mark identity number allocated.
1718 **************************************************************************/
1719 void identity_number_reserve(int id)
1721 BV_SET(identity_numbers_used, id);
1724 /**************************************************************************
1725 Check whether identity number is currently allocated.
1726 **************************************************************************/
1727 static bool identity_number_is_used(int id)
1729 return BV_ISSET(identity_numbers_used, id);
1732 /**************************************************************************
1733 Increment identity_number and return result.
1734 **************************************************************************/
1735 static int increment_identity_number(void)
1737 server.identity_number = (server.identity_number + 1) % IDENTITY_NUMBER_SIZE;
1738 return server.identity_number;
1741 /**************************************************************************
1742 Identity ids wrap at IDENTITY_NUMBER_SIZE, skipping IDENTITY_NUMBER_ZERO
1743 Setup in server_game_init()
1744 **************************************************************************/
1745 int identity_number(void)
1747 int retries = 0;
1749 while (identity_number_is_used(increment_identity_number())) {
1750 /* try again */
1751 if (++retries >= IDENTITY_NUMBER_SIZE) {
1752 /* Always fails. */
1753 fc_assert_exit_msg(IDENTITY_NUMBER_SIZE > retries,
1754 "Exhausted city and unit numbers!");
1757 identity_number_reserve(server.identity_number);
1758 return server.identity_number;
1761 /**************************************************************************
1762 Returns TRUE if the packet type is an edit packet sent by the client.
1764 NB: The first and last client edit packets here must match those
1765 defined in common/packets.def.
1766 **************************************************************************/
1767 static bool is_client_edit_packet(int type)
1769 return PACKET_EDIT_MODE <= type && type <= PACKET_EDIT_GAME;
1772 /**************************************************************************
1773 Returns FALSE if connection should be closed (because the clients was
1774 rejected). Returns TRUE else.
1775 **************************************************************************/
1776 bool server_packet_input(struct connection *pconn, void *packet, int type)
1778 struct player *pplayer;
1780 /* a NULL packet can be returned from receive_packet_goto_route() */
1781 if (!packet) {
1782 return TRUE;
1786 * Old pre-delta clients (before 2003-11-28) send a
1787 * PACKET_LOGIN_REQUEST (type 0) to the server. We catch this and
1788 * reply with an old reject packet. Since there is no struct for
1789 * this old packet anymore we build it by hand.
1791 if (type == 0) {
1792 unsigned char buffer[4096];
1793 struct raw_data_out dout;
1795 log_normal(_("Warning: rejecting old client %s"),
1796 conn_description(pconn));
1798 dio_output_init(&dout, buffer, sizeof(buffer));
1799 dio_put_uint16_raw(&dout, 0);
1801 /* 1 == PACKET_LOGIN_REPLY in the old client */
1802 dio_put_uint8_raw(&dout, 1);
1804 dio_put_bool32_raw(&dout, FALSE);
1805 dio_put_string_raw(&dout,
1806 _("Your client is too old. To use this server, "
1807 "please upgrade your client to a "
1808 "Freeciv 2.2 or later."));
1809 dio_put_string_raw(&dout, "");
1812 size_t size = dio_output_used(&dout);
1813 dio_output_rewind(&dout);
1814 dio_put_uint16_raw(&dout, size);
1817 * Use send_connection_data instead of send_packet_data to avoid
1818 * compression.
1820 connection_send_data(pconn, buffer, size);
1823 return FALSE;
1826 if (type == PACKET_SERVER_JOIN_REQ) {
1827 return handle_login_request(pconn,
1828 (struct packet_server_join_req *) packet);
1831 /* May be received on a non-established connection. */
1832 if (type == PACKET_AUTHENTICATION_REPLY) {
1833 return auth_handle_reply(pconn,
1834 ((struct packet_authentication_reply *)
1835 packet)->password);
1838 if (type == PACKET_CONN_PONG) {
1839 handle_conn_pong(pconn);
1840 return TRUE;
1843 if (!pconn->established) {
1844 log_error("Received game packet %s(%d) from unaccepted connection %s.",
1845 packet_name(type), type, conn_description(pconn));
1846 return TRUE;
1849 /* valid packets from established connections but non-players */
1850 if (type == PACKET_CHAT_MSG_REQ
1851 || type == PACKET_SINGLE_WANT_HACK_REQ
1852 || type == PACKET_NATION_SELECT_REQ
1853 || type == PACKET_REPORT_REQ
1854 || type == PACKET_CLIENT_INFO
1855 || type == PACKET_CONN_PONG
1856 || type == PACKET_CLIENT_HEARTBEAT
1857 || type == PACKET_SAVE_SCENARIO
1858 || is_client_edit_packet(type)) {
1860 /* Except for PACKET_EDIT_MODE (used to set edit mode), check
1861 * that the client is allowed to send the given edit packet. */
1862 if (is_client_edit_packet(type) && type != PACKET_EDIT_MODE
1863 && !can_conn_edit(pconn)) {
1864 notify_conn(pconn->self, NULL, E_BAD_COMMAND, ftc_editor,
1865 _("You are not allowed to edit."));
1866 return TRUE;
1869 if (!server_handle_packet(type, packet, NULL, pconn)) {
1870 log_error("Received unknown packet %d from %s.",
1871 type, conn_description(pconn));
1873 return TRUE;
1876 pplayer = pconn->playing;
1878 if (NULL == pplayer || pconn->observer) {
1879 if (type == PACKET_PLAYER_READY && pconn->observer) {
1880 handle_observer_ready(pconn);
1881 return TRUE;
1883 /* don't support these yet */
1884 log_error("Received packet %s(%d) from non-player connection %s.",
1885 packet_name(type), type, conn_description(pconn));
1886 return TRUE;
1889 if (S_S_RUNNING != server_state()
1890 && type != PACKET_NATION_SELECT_REQ
1891 && type != PACKET_PLAYER_READY
1892 && type != PACKET_VOTE_SUBMIT) {
1893 if (S_S_OVER == server_state()) {
1894 /* This can happen by accident, so we don't want to print
1895 * out lots of error messages. Ie, we use log_debug(). */
1896 log_debug("Got a packet of type %s(%d) in %s.",
1897 packet_name(type), type, server_states_name(S_S_OVER));
1898 } else {
1899 log_error("Got a packet of type %s(%d) outside %s.",
1900 packet_name(type), type, server_states_name(S_S_RUNNING));
1902 return TRUE;
1905 pplayer->nturns_idle = 0;
1907 if (!pplayer->is_alive && type != PACKET_REPORT_REQ) {
1908 log_error("Got a packet of type %s(%d) from a dead player.",
1909 packet_name(type), type);
1910 return TRUE;
1913 /* Make sure to set this back to NULL before leaving this function: */
1914 pplayer->current_conn = pconn;
1916 if (!server_handle_packet(type, packet, pplayer, pconn)) {
1917 log_error("Received unknown packet %d from %s.",
1918 type, conn_description(pconn));
1921 if (S_S_RUNNING == server_state()
1922 && type != PACKET_PLAYER_READY) {
1923 /* handle_player_ready() calls start_game(), but the game isn't started
1924 * until the main loop is re-entered, so kill_dying_players would think
1925 * all players are dead. This should be solved by adding a new
1926 * game state (now S_S_GENERATING_WAITING). */
1927 kill_dying_players();
1930 pplayer->current_conn = NULL;
1931 return TRUE;
1934 /**************************************************************************
1935 Check if turn is really done. Returns nothing, but as a side effect sets
1936 force_end_of_sniff if no more input is expected this turn (i.e. turn done)
1937 **************************************************************************/
1938 void check_for_full_turn_done(void)
1940 bool connected = FALSE;
1942 if (S_S_RUNNING != server_state()) {
1943 /* Not in a running state, no turn done. */
1944 return;
1947 /* fixedlength is only applicable if we have a timeout set */
1948 if (game.server.fixedlength && current_turn_timeout() != 0) {
1949 return;
1952 /* If there are no connected players, don't automatically advance. This is
1953 * a hack to prevent all-AI games from running rampant. Note that if
1954 * timeout is set to -1 this function call is skipped entirely and the
1955 * server will run rampant. */
1956 players_iterate_alive(pplayer) {
1957 if (pplayer->is_connected && (is_human(pplayer) || pplayer->phase_done)) {
1958 connected = TRUE;
1959 break;
1961 } players_iterate_alive_end;
1963 if (!connected) {
1964 return;
1967 phase_players_iterate(pplayer) {
1968 if (!pplayer->phase_done && pplayer->is_alive) {
1969 if (pplayer->is_connected) {
1970 /* In all cases, we wait for any connected players. */
1971 return;
1973 if (game.server.turnblock && is_human(pplayer)) {
1974 /* If turnblock is enabled check for human players, connected
1975 * or not. */
1976 return;
1978 if (is_ai(pplayer) && !pplayer->ai_phase_done) {
1979 /* AI player has not finished */
1980 return;
1983 } phase_players_iterate_end;
1985 force_end_of_sniff = TRUE;
1988 /****************************************************************************
1989 Update information about which nations have start positions on the map.
1991 Call this on server start, or when loading a scenario.
1992 ****************************************************************************/
1993 void update_nations_with_startpos(void)
1995 if (!game_was_started() && 0 < map_startpos_count()) {
1996 /* Restrict nations to those for which start positions are defined. */
1997 nations_iterate(pnation) {
1998 fc_assert_action_msg(NULL == pnation->player,
1999 if (pnation->player->nation == pnation) {
2000 /* At least assignment is consistent. Leave nation assigned,
2001 * and make sure that nation is also marked pickable. */
2002 pnation->server.no_startpos = FALSE;
2003 continue;
2004 } else if (NULL != pnation->player->nation) {
2005 /* Not consistent. Just initialize the pointer and hope for the
2006 * best. */
2007 pnation->player->nation->player = NULL;
2008 pnation->player = NULL;
2009 } else {
2010 /* Not consistent. Just initialize the pointer and hope for the
2011 * best. */
2012 pnation->player = NULL;
2013 }, "Player assigned to nation before %s()!", __FUNCTION__);
2015 if (nation_barbarian_type(pnation) != NOT_A_BARBARIAN) {
2016 /* Always allow land and sea barbarians regardless of start
2017 * positions. */
2018 pnation->server.no_startpos = FALSE;
2019 } else {
2020 /* Restrict the set of nations offered to players, based on
2021 * start positions.
2022 * If there are no start positions for a nation, remove it from the
2023 * available set. */
2024 pnation->server.no_startpos = TRUE;
2025 map_startpos_iterate(psp) {
2026 if (startpos_nation_allowed(psp, pnation)) {
2027 /* There is at least one start position that allows this nation,
2028 * so allow it to be picked.
2029 * (Depending on what nations players actually pick, it's not
2030 * guaranteed that the server can always find a match between
2031 * nations in this subset and start positions, in which case the
2032 * server may create mismatches.) */
2033 pnation->server.no_startpos = FALSE;
2034 break;
2036 } map_startpos_iterate_end;
2038 } nations_iterate_end;
2039 } else {
2040 /* Not restricting nations by start positions. */
2041 nations_iterate(pnation) {
2042 pnation->server.no_startpos = FALSE;
2043 } nations_iterate_end;
2047 /**************************************************************************
2048 Handles a pick-nation packet from the client. These packets are
2049 handled by connection because ctrl users may edit anyone's nation in
2050 pregame, and editing is possible during a running game.
2051 **************************************************************************/
2052 void handle_nation_select_req(struct connection *pc, int player_no,
2053 Nation_type_id nation_no, bool is_male,
2054 const char *name, int style)
2056 struct nation_type *new_nation;
2057 struct player *pplayer = player_by_number(player_no);
2059 if (!pplayer || !can_conn_edit_players_nation(pc, pplayer)) {
2060 return;
2063 new_nation = nation_by_number(nation_no);
2065 if (new_nation != NO_NATION_SELECTED) {
2066 char message[1024];
2068 /* check sanity of the packet sent by client */
2069 if (style < 0 || style >= game.control.num_styles) {
2070 return;
2073 if (!client_can_pick_nation(new_nation)) {
2074 notify_player(pplayer, NULL, E_NATION_SELECTED, ftc_server,
2075 _("%s nation is not available for user selection."),
2076 nation_adjective_translation(new_nation));
2077 return;
2079 if (new_nation->player && new_nation->player != pplayer) {
2080 notify_player(pplayer, NULL, E_NATION_SELECTED, ftc_server,
2081 _("%s nation is already in use."),
2082 nation_adjective_translation(new_nation));
2083 return;
2086 if (!server_player_set_name_full(pc, pplayer, new_nation, name,
2087 message, sizeof(message))) {
2088 notify_player(pplayer, NULL, E_NATION_SELECTED,
2089 ftc_server, "%s", message);
2090 return;
2093 /* Should be caught by is_nation_pickable() */
2094 fc_assert_ret(nation_is_in_current_set(new_nation));
2096 notify_conn(NULL, NULL, E_NATION_SELECTED, ftc_server,
2097 _("%s is the %s ruler %s."),
2098 pplayer->username,
2099 nation_adjective_translation(new_nation),
2100 player_name(pplayer));
2102 pplayer->is_male = is_male;
2103 pplayer->style = style_by_number(style);
2104 } else if (name[0] == '\0') {
2105 char message[1024];
2107 server_player_set_name_full(pc, pplayer, NULL, ANON_PLAYER_NAME,
2108 message, sizeof(message));
2111 (void) player_set_nation(pplayer, new_nation);
2112 send_player_info_c(pplayer, game.est_connections);
2115 /****************************************************************************
2116 Handle a player-ready packet from global observer.
2117 ****************************************************************************/
2118 static void handle_observer_ready(struct connection *pconn)
2120 if (pconn->access_level == ALLOW_HACK) {
2121 players_iterate(plr) {
2122 if (is_human(plr)) {
2123 return;
2125 } players_iterate_end;
2127 start_command(NULL, FALSE, TRUE);
2131 /****************************************************************************
2132 Handle a player-ready packet.
2133 ****************************************************************************/
2134 void handle_player_ready(struct player *requestor,
2135 int player_no,
2136 bool is_ready)
2138 struct player *pplayer = player_by_number(player_no);
2140 if (NULL == pplayer || S_S_INITIAL != server_state()) {
2141 return;
2144 if (pplayer != requestor) {
2145 /* Currently you can only change your own readiness. */
2146 return;
2149 pplayer->is_ready = is_ready;
2150 send_player_info_c(pplayer, NULL);
2152 /* Note this is called even if the player has pressed /start once
2153 * before. For instance, when a player leaves everyone remaining
2154 * might have pressed /start already but the start won't happen
2155 * until someone presses it again. Also you can press start more
2156 * than once to remind other people to start (which is a good thing
2157 * until somebody does it too much and it gets labeled as spam). */
2158 if (is_ready) {
2159 int num_ready = 0, num_unready = 0;
2161 players_iterate(other_player) {
2162 if (other_player->is_connected) {
2163 if (other_player->is_ready) {
2164 num_ready++;
2165 } else {
2166 num_unready++;
2169 } players_iterate_end;
2170 if (num_unready > 0) {
2171 notify_conn(NULL, NULL, E_SETTING, ftc_server,
2172 _("Waiting to start game: %d out of %d players "
2173 "are ready to start."),
2174 num_ready, num_ready + num_unready);
2175 } else {
2176 /* Check minplayers etc. and then start */
2177 start_command(NULL, FALSE, TRUE);
2182 /****************************************************************************
2183 Fill or remove players to meet the given aifill.
2184 If return is non-NULL, points to a translated string explaining why
2185 the total number of players is less than 'amount'.
2186 ****************************************************************************/
2187 const char *aifill(int amount)
2189 char *limitreason = NULL;
2190 int limit;
2192 if (game_was_started()) {
2193 return NULL;
2196 limit = MIN(amount, game.server.max_players);
2197 if (limit < amount) {
2198 limitreason = _("requested more than 'maxplayers' setting");
2201 /* Limit to nations provided by ruleset */
2202 if (limit > server.playable_nations) {
2203 limit = server.playable_nations;
2204 if (nation_set_count() > 1) {
2205 limitreason = _("not enough playable nations in this nation set "
2206 "(see 'nationset' setting)");
2207 } else {
2208 limitreason = _("not enough playable nations");
2212 if (limit < player_count()) {
2213 int removal = player_slot_count() - 1;
2215 while (limit < player_count() && 0 <= removal) {
2216 struct player *pplayer = player_by_number(removal);
2218 removal--;
2219 if (!pplayer) {
2220 continue;
2223 if (!pplayer->is_connected && !pplayer->was_created) {
2224 server_remove_player(pplayer);
2228 /* 'limit' can be different from 'player_count()' at this point if
2229 * there are more human or created players than the 'limit'. */
2230 return limitreason;
2233 while (limit > player_count()) {
2234 char leader_name[MAX_LEN_NAME];
2235 int filled = 1;
2236 struct player *pplayer;
2238 pplayer = server_create_player(-1, default_ai_type_name(),
2239 NULL, FALSE);
2240 /* !game_was_started() so no need to assign_player_colors() */
2241 if (!pplayer) {
2242 break;
2244 server_player_init(pplayer, FALSE, TRUE);
2246 player_set_nation(pplayer, NULL);
2248 do {
2249 fc_snprintf(leader_name, sizeof(leader_name), "AI*%d", filled++);
2250 } while (player_by_name(leader_name));
2251 server_player_set_name(pplayer, leader_name);
2252 pplayer->random_name = TRUE;
2253 sz_strlcpy(pplayer->username, _(ANON_USER_NAME));
2254 pplayer->unassigned_user = TRUE;
2256 pplayer->ai_common.skill_level = game.info.skill_level;
2257 set_as_ai(pplayer);
2258 set_ai_level_directer(pplayer, game.info.skill_level);
2260 CALL_PLR_AI_FUNC(gained_control, pplayer, pplayer);
2262 log_normal(_("%s has been added as %s level AI-controlled player (%s)."),
2263 player_name(pplayer),
2264 ai_level_translated_name(pplayer->ai_common.skill_level),
2265 ai_name(pplayer->ai));
2266 notify_conn(NULL, NULL, E_SETTING, ftc_server,
2267 _("%s has been added as %s level AI-controlled player (%s)."),
2268 player_name(pplayer),
2269 ai_level_translated_name(pplayer->ai_common.skill_level),
2270 ai_name(pplayer->ai));
2272 send_player_info_c(pplayer, NULL);
2275 return limitreason;
2278 /****************************************************************************
2279 Tool for generate_players().
2280 ****************************************************************************/
2281 #define SPECHASH_TAG startpos
2282 #define SPECHASH_IKEY_TYPE struct startpos *
2283 #define SPECHASH_INT_DATA_TYPE
2284 #include "spechash.h"
2285 #define startpos_hash_iterate(hash, psp, c) \
2286 TYPED_HASH_ITERATE(struct startpos *, intptr_t, hash, psp, c)
2287 #define startpos_hash_iterate_end HASH_ITERATE_END
2289 /****************************************************************************
2290 Tool for generate_players().
2291 ****************************************************************************/
2292 static void player_set_nation_full(struct player *pplayer,
2293 struct nation_type *pnation)
2295 /* Don't change the name of a created player. */
2296 player_nation_defaults(pplayer, pnation, pplayer->random_name);
2299 /****************************************************************************
2300 Set nation for player with nation default values.
2301 ****************************************************************************/
2302 void player_nation_defaults(struct player *pplayer, struct nation_type *pnation,
2303 bool set_name)
2305 struct nation_leader *pleader;
2307 fc_assert(NO_NATION_SELECTED != pnation);
2308 player_set_nation(pplayer, pnation);
2309 fc_assert(pnation == pplayer->nation);
2311 pplayer->style = style_of_nation(pnation);
2313 if (set_name) {
2314 server_player_set_name(pplayer, pick_random_player_name(pnation));
2317 if ((pleader = nation_leader_by_name(pnation, player_name(pplayer)))) {
2318 pplayer->is_male = nation_leader_is_male(pleader);
2319 } else {
2320 pplayer->is_male = (fc_rand(2) == 1);
2323 ai_traits_init(pplayer);
2326 /****************************************************************************
2327 Assign random nations to players at game start. This includes human
2328 players, AI players created with "set aifill <X>", and players created
2329 with "create <PlayerName>".
2331 If a player's name matches one of the leader names for some nation, and
2332 that nation is available, choose that nation, and set the player sex
2333 appropriately. For example, when the Britons have not been chosen by
2334 anyone else, a player called Boudica whose nation has not been specified
2335 (for instance if they were created with "create Boudica") will become
2336 the Britons, and their sex will be female. Otherwise, the sex is chosen
2337 randomly, and the nation is chosen as below.
2339 If this is a scenario and the scenario has specific start positions for
2340 some nations, try to pick those nations, favouring those with start
2341 positions which already-assigned players can't use. (Note that it's
2342 possible that we can't find enough nations with available start positions,
2343 depending on what nations players have already picked; in this case,
2344 it's OK to pick nations without start positions, as init_new_game() will
2345 fall back to mismatched start positions.)
2347 Otherwise, pick available nations using pick_a_nation(), which tries to
2348 pick nations that look good with nations already in the game.
2350 For 'aifill' players, the player name/sex is then reset to that of a
2351 random leader for the chosen nation.
2352 ****************************************************************************/
2353 static void generate_players(void)
2355 int nations_to_assign = 0;
2357 /* Announce players who already have nations, and select nations based
2358 * on player names. */
2359 players_iterate(pplayer) {
2360 if (pplayer->nation != NO_NATION_SELECTED) {
2361 /* Traits are initialized here, and not already when nation gets picked,
2362 * as player may change his/her mind after picking one nation, and picks
2363 * another and we want to init traits only once, for the correct nation. */
2364 ai_traits_init(pplayer);
2365 announce_player(pplayer);
2366 continue;
2369 /* See if the player name matches a known leader name.
2370 * If more than one nation has this leader name, pick one at random.
2371 * No attempt is made to avoid clashes to maximise the number of
2372 * nations that can be assigned in this way. */
2374 struct nation_list *candidates = nation_list_new();
2375 int n = 0;
2377 allowed_nations_iterate(pnation) {
2378 if (is_nation_playable(pnation)
2379 && client_can_pick_nation(pnation)
2380 && NULL == pnation->player
2381 && (nation_leader_by_name(pnation, player_name(pplayer)))) {
2382 nation_list_append(candidates, pnation);
2383 n++;
2385 } allowed_nations_iterate_end;
2386 if (n > 0) {
2387 player_set_nation_full(pplayer,
2388 nation_list_get(candidates, fc_rand(n)));
2390 nation_list_destroy(candidates);
2392 if (pplayer->nation != NO_NATION_SELECTED) {
2393 announce_player(pplayer);
2394 } else {
2395 nations_to_assign++;
2397 } players_iterate_end;
2399 if (0 < nations_to_assign && 0 < map_startpos_count()) {
2400 /* We're running a scenario game with specified start positions.
2401 * Prefer nations assigned to those positions (but we can fall back
2402 * to others, even if game.scenario.startpos_nations is set). */
2403 struct startpos_hash *hash = startpos_hash_new();
2404 struct nation_type *picked;
2405 int c, max = -1;
2406 int i, min;
2408 /* Initialization. */
2409 map_startpos_iterate(psp) {
2410 if (startpos_allows_all(psp)) {
2411 continue;
2414 /* Count the already-assigned players whose nations can use this
2415 * start position. */
2416 c = 0;
2417 players_iterate(pplayer) {
2418 if (NO_NATION_SELECTED != pplayer->nation
2419 && startpos_nation_allowed(psp, pplayer->nation)) {
2420 c++;
2422 } players_iterate_end;
2424 startpos_hash_insert(hash, psp, c);
2425 if (c > max) {
2426 max = c;
2428 } map_startpos_iterate_end;
2430 /* Try to assign nations with start positions to the unassigned
2431 * players, preferring nations whose start positions aren't usable
2432 * by already-assigned players. */
2433 players_iterate(pplayer) {
2434 if (NO_NATION_SELECTED != pplayer->nation) {
2435 continue;
2438 picked = NO_NATION_SELECTED;
2439 min = max;
2440 i = 0;
2442 allowed_nations_iterate(pnation) {
2443 if (!is_nation_playable(pnation)
2444 || NULL != pnation->player) {
2445 /* Not available. */
2446 continue;
2449 startpos_hash_iterate(hash, psp, val) {
2450 if (!startpos_nation_allowed(psp, pnation)) {
2451 continue;
2454 if (val < min) {
2455 /* Pick this nation, as fewer nations already in the game
2456 * can use this start position. */
2457 picked = pnation;
2458 min = val;
2459 i = 1;
2460 } else if (val == min && 0 == fc_rand(++i)) {
2461 /* More than one nation is equally desirable. Pick one at
2462 * random. */
2463 picked = pnation;
2465 } startpos_hash_iterate_end;
2466 } allowed_nations_iterate_end;
2468 if (NO_NATION_SELECTED != picked) {
2469 player_set_nation_full(pplayer, picked);
2470 nations_to_assign--;
2471 announce_player(pplayer);
2472 /* Update the counts for the newly assigned nation. */
2473 startpos_hash_iterate(hash, psp, val) {
2474 if (startpos_nation_allowed(psp, picked)) {
2475 startpos_hash_replace(hash, psp, val + 1);
2477 } startpos_hash_iterate_end;
2478 } else {
2479 /* No need to continue; we failed to pick a nation this time,
2480 * so we're not going to succeed next time. Fall back to
2481 * standard nation selection. */
2482 break;
2484 } players_iterate_end;
2486 startpos_hash_destroy(hash);
2489 if (0 < nations_to_assign) {
2490 /* Pick random races. Try to select from the set permitted by
2491 * starting positions -- if we fell through here after failing to
2492 * match start positions, this will at least keep the picked
2493 * nations vaguely in keeping with the scenario.
2494 * However, even this may fail (if there are start positions that
2495 * can only be filled by nations outside the current nationset),
2496 * in which case we fall back to completely random nations. */
2497 bool needs_startpos = TRUE;
2498 players_iterate(pplayer) {
2499 if (NO_NATION_SELECTED == pplayer->nation) {
2500 struct nation_type *pnation = pick_a_nation(NULL, FALSE, needs_startpos,
2501 NOT_A_BARBARIAN);
2502 if (pnation == NO_NATION_SELECTED && needs_startpos) {
2503 needs_startpos = FALSE;
2504 pnation = pick_a_nation(NULL, FALSE, needs_startpos, NOT_A_BARBARIAN);
2506 fc_assert(pnation != NO_NATION_SELECTED);
2507 player_set_nation_full(pplayer, pnation);
2508 nations_to_assign--;
2509 announce_player(pplayer);
2511 } players_iterate_end;
2514 fc_assert(0 == nations_to_assign);
2516 (void) send_server_info_to_metaserver(META_INFO);
2519 /****************************************************************************
2520 Returns a random ruler name picked from given nation's ruler names
2521 that is not already in use.
2522 May return NULL if no unique name is available.
2523 ****************************************************************************/
2524 const char *pick_random_player_name(const struct nation_type *pnation)
2526 const char *choice = NULL;
2527 struct nation_leader_list *candidates = nation_leader_list_new();
2528 int n;
2530 nation_leader_list_iterate(nation_leaders(pnation), pleader) {
2531 const char *name = nation_leader_name(pleader);
2533 if (NULL == player_by_name(name)
2534 && NULL == player_by_user(name)) {
2535 nation_leader_list_append(candidates, pleader);
2537 } nation_leader_list_iterate_end;
2539 n = nation_leader_list_size(candidates);
2540 if (n > 0) {
2541 choice = nation_leader_name(nation_leader_list_get(candidates,
2542 fc_rand(n)));
2544 nation_leader_list_destroy(candidates);
2546 return choice;
2549 /*************************************************************************
2550 Announce what nation player rules to everyone.
2551 *************************************************************************/
2552 static void announce_player(struct player *pplayer)
2554 log_normal(_("%s rules the %s."),
2555 player_name(pplayer), nation_plural_for_player(pplayer));
2557 notify_conn(game.est_connections, NULL, E_GAME_START,
2558 ftc_server, _("%s rules the %s."),
2559 player_name(pplayer), nation_plural_for_player(pplayer));
2561 /* Let the clients knows the nation of the players as soon as possible.
2562 * When a player's nation is server assigned its client will think of it
2563 * as NULL until informed about the assigned nation. */
2564 send_player_info_c(pplayer, NULL);
2567 /**************************************************************************
2568 Play the game! Returns when S_S_RUNNING != server_state().
2569 **************************************************************************/
2570 static void srv_running(void)
2572 int i;
2573 bool is_new_turn = game.info.is_new_game;
2574 bool skip_mapimg = !game.info.is_new_game; /* Do not overwrite start-of-turn image */
2575 bool need_send_pending_events = !game.info.is_new_game;
2576 int save_counter = game.info.is_new_game ? 1 : 0;
2578 /* We may as well reset is_new_game now. */
2579 game.info.is_new_game = FALSE;
2581 log_verbose("srv_running() mostly redundant send_server_settings()");
2582 send_server_settings(NULL);
2584 timer_start(eot_timer);
2586 if (game.server.autosaves & (1 << AS_TIMER)) {
2587 game.server.save_timer = timer_renew(game.server.save_timer,
2588 TIMER_USER, TIMER_ACTIVE);
2589 timer_start(game.server.save_timer);
2593 * This will freeze the reports and agents at the client.
2595 * Do this before the body so that the PACKET_THAW_CLIENT packet is
2596 * balanced.
2598 lsend_packet_freeze_client(game.est_connections);
2600 fc_assert(S_S_RUNNING == server_state());
2601 while (S_S_RUNNING == server_state()) {
2602 /* The beginning of a turn.
2604 * We have to initialize data as well as do some actions. However when
2605 * loading a game we don't want to do these actions (like AI unit
2606 * movement and AI diplomacy). */
2607 begin_turn(is_new_turn);
2609 if (game.server.num_phases != 1) {
2610 /* We allow everyone to begin adjusting cities and such
2611 * from the beginning of the turn.
2612 * With simultaneous movement we send begin_turn packet in
2613 * begin_phase() only after AI players have finished their actions. */
2614 lsend_packet_begin_turn(game.est_connections);
2617 for (; game.info.phase < game.server.num_phases; game.info.phase++) {
2618 log_debug("Starting phase %d/%d.", game.info.phase,
2619 game.server.num_phases);
2620 begin_phase(is_new_turn);
2621 if (need_send_pending_events) {
2622 /* When loading a savegame, we need to send loaded events, after
2623 * the clients switched to the game page (after the first
2624 * packet_start_phase is received). */
2625 conn_list_iterate(game.est_connections, pconn) {
2626 send_pending_events(pconn, TRUE);
2627 } conn_list_iterate_end;
2628 need_send_pending_events = FALSE;
2631 is_new_turn = TRUE;
2633 force_end_of_sniff = FALSE;
2636 * This will thaw the reports and agents at the client.
2638 lsend_packet_thaw_client(game.est_connections);
2640 #ifdef LOG_TIMERS
2641 /* Before sniff (human player activites), report time to now: */
2642 log_verbose("End/start-turn server/ai activities: %g seconds",
2643 timer_read_seconds(eot_timer));
2644 #endif
2646 /* Do auto-saves just before starting server_sniff_all_input(), so that
2647 * autosave happens effectively "at the same time" as manual
2648 * saves, from the point of view of restarting and AI players.
2649 * Post-increment so we don't count the first loop. */
2650 if (game.info.phase == 0) {
2651 /* Create autosaves if requested. */
2652 if (save_counter >= game.server.save_nturns
2653 && game.server.save_nturns > 0) {
2654 save_counter = 0;
2655 save_game_auto("Autosave", AS_TURN);
2657 save_counter++;
2659 if (!skip_mapimg) {
2660 /* Save map image(s). */
2661 for (i = 0; i < mapimg_count(); i++) {
2662 struct mapdef *pmapdef = mapimg_isvalid(i);
2663 if (pmapdef != NULL) {
2664 mapimg_create(pmapdef, FALSE, game.server.save_name,
2665 srvarg.saves_pathname);
2666 } else {
2667 log_error("%s", mapimg_error());
2670 } else {
2671 skip_mapimg = FALSE;
2675 log_debug("sniffingpackets");
2676 check_for_full_turn_done(); /* HACK: don't wait during AI phases */
2678 if (between_turns != NULL) {
2679 game.server.turn_change_time = timer_read_seconds(between_turns);
2680 log_debug("Inresponsive between turns %g seconds", game.server.turn_change_time);
2683 while (server_sniff_all_input() == S_E_OTHERWISE) {
2684 /* nothing */
2687 between_turns = timer_renew(between_turns, TIMER_USER, TIMER_ACTIVE);
2688 timer_start(between_turns);
2690 /* After sniff, re-zero the timer: (read-out above on next loop) */
2691 timer_clear(eot_timer);
2692 timer_start(eot_timer);
2694 conn_list_do_buffer(game.est_connections);
2696 sanity_check();
2699 * This will freeze the reports and agents at the client.
2701 lsend_packet_freeze_client(game.est_connections);
2703 end_phase();
2705 conn_list_do_unbuffer(game.est_connections);
2707 if (S_S_OVER == server_state()) {
2708 break;
2711 end_turn();
2712 log_debug("Sendinfotometaserver");
2713 (void) send_server_info_to_metaserver(META_REFRESH);
2715 if (S_S_OVER != server_state() && check_for_game_over()) {
2716 set_server_state(S_S_OVER);
2717 if (game.info.turn > game.server.end_turn) {
2718 /* endturn was reached - rank users based on team scores */
2719 rank_users(TRUE);
2720 } else {
2721 /* game ended for victory conditions - rank users based on survival */
2722 rank_users(FALSE);
2724 } else if ((check_for_game_over() && game.info.turn > game.server.end_turn)
2725 || S_S_OVER == server_state()) {
2726 /* game terminated by /endgame command - calculate team scores */
2727 rank_users(TRUE);
2731 /* This will thaw the reports and agents at the client. */
2732 lsend_packet_thaw_client(game.est_connections);
2734 if (game.server.save_timer != NULL) {
2735 timer_destroy(game.server.save_timer);
2736 game.server.save_timer = NULL;
2738 if (between_turns != NULL) {
2739 timer_destroy(between_turns);
2740 between_turns = NULL;
2742 timer_clear(eot_timer);
2745 /**************************************************************************
2746 Server initialization.
2747 **************************************************************************/
2748 static void srv_prepare(void)
2750 #ifdef HAVE_FCDB
2751 if (!srvarg.auth_enabled) {
2752 con_write(C_COMMENT, _("This freeciv-server program has player "
2753 "authentication support, but it's currently not "
2754 "in use."));
2756 #endif /* HAVE_FCDB */
2758 /* make sure it's initialized */
2759 if (!has_been_srv_init) {
2760 srv_init();
2763 fc_init_network();
2765 /* must be before con_log_init() */
2766 init_connections();
2767 con_log_init(srvarg.log_filename, srvarg.loglevel,
2768 srvarg.fatal_assertions);
2769 /* logging available after this point */
2771 server_open_socket();
2773 #if IS_BETA_VERSION
2774 con_puts(C_COMMENT, "");
2775 con_puts(C_COMMENT, beta_message());
2776 con_puts(C_COMMENT, "");
2777 #endif
2779 con_flush();
2781 settings_init(TRUE);
2782 stdinhand_init();
2783 edithand_init();
2784 voting_init();
2785 diplhand_init();
2786 voting_init();
2787 ai_timer_init();
2789 server_game_init(FALSE);
2790 mapimg_init(mapimg_server_tile_known, mapimg_server_tile_terrain,
2791 mapimg_server_tile_owner, mapimg_server_tile_city,
2792 mapimg_server_tile_unit, mapimg_server_plrcolor_count,
2793 mapimg_server_plrcolor_get);
2795 #ifdef HAVE_FCDB
2796 if (srvarg.fcdb_enabled) {
2797 bool success;
2799 success = fcdb_init(srvarg.fcdb_conf);
2800 free(srvarg.fcdb_conf); /* Never needed again */
2801 srvarg.fcdb_conf = NULL;
2802 if (!success) {
2803 exit(EXIT_FAILURE);
2806 #endif /* HAVE_FCDB */
2808 if (srvarg.ruleset != NULL) {
2809 const char *testfilename;
2811 testfilename = fileinfoname(get_data_dirs(), srvarg.ruleset);
2812 if (testfilename == NULL) {
2813 log_fatal(_("Ruleset directory \"%s\" not found"), srvarg.ruleset);
2814 exit(EXIT_FAILURE);
2816 sz_strlcpy(game.server.rulesetdir, srvarg.ruleset);
2819 /* load a saved game */
2820 if ('\0' == srvarg.load_filename[0]
2821 || !load_command(NULL, srvarg.load_filename, FALSE, TRUE)) {
2822 /* Rulesets are loaded on game initialization, but may be changed later
2823 * if /load or /rulesetdir is done. */
2824 load_rulesets(NULL, FALSE, TRUE, FALSE);
2827 maybe_automatic_meta_message(default_meta_message_string());
2829 if (!(srvarg.metaserver_no_send)) {
2830 log_normal(_("Sending info to metaserver <%s>."), meta_addr_port());
2831 /* Open socket for meta server */
2832 if (!server_open_meta(srvarg.metaconnection_persistent)
2833 || !send_server_info_to_metaserver(META_INFO)) {
2834 con_write(C_FAIL, _("Not starting without explicitly requested metaserver connection."));
2835 exit(EXIT_FAILURE);
2839 eot_timer = timer_new(TIMER_CPU, TIMER_ACTIVE);
2842 /**************************************************************************
2843 Score calculation.
2844 **************************************************************************/
2845 static void srv_scores(void)
2847 /* Recalculate the scores in case of a spaceship victory */
2848 players_iterate(pplayer) {
2849 calc_civ_score(pplayer);
2850 } players_iterate_end;
2852 log_civ_score_now();
2854 report_final_scores(NULL);
2855 show_map_to_all();
2856 notify_player(NULL, NULL, E_GAME_END, ftc_server,
2857 _("The game is over..."));
2858 send_server_info_to_metaserver(META_INFO);
2860 if (game.server.save_nturns > 0
2861 && conn_list_size(game.est_connections) > 0) {
2862 /* Save game on game_over, but not when the gameover was caused by
2863 * the -q parameter. */
2864 save_game_auto("Game over", AS_GAME_OVER);
2868 /**************************************************************************
2869 Apply some final adjustments from the ruleset on to the game state.
2870 We cannot do this during ruleset loading, since some players may be
2871 added later than that.
2872 **************************************************************************/
2873 static void final_ruleset_adjustments(void)
2875 players_iterate(pplayer) {
2876 struct nation_type *pnation = nation_of_player(pplayer);
2878 pplayer->government = init_government_of_nation(pnation);
2880 if (pnation->init_government == game.government_during_revolution) {
2881 /* If we do not do this, an assertion will trigger. This enables us to
2882 * select a valid government on game start. */
2883 pplayer->revolution_finishes = 0;
2886 multipliers_iterate(pmul) {
2887 pplayer->multipliers[multiplier_index(pmul)]
2888 = pplayer->multipliers_target[multiplier_index(pmul)]
2889 = pmul->def;
2890 } multipliers_iterate_end;
2891 } players_iterate_end;
2894 /**************************************************************************
2895 Set up one game.
2896 **************************************************************************/
2897 static void srv_ready(void)
2899 (void) send_server_info_to_metaserver(META_INFO);
2901 if (game.server.auto_ai_toggle) {
2902 players_iterate(pplayer) {
2903 if (!pplayer->is_connected && is_human(pplayer)) {
2904 toggle_ai_player_direct(NULL, pplayer);
2906 } players_iterate_end;
2909 init_game_seed();
2911 #ifdef TEST_RANDOM /* not defined anywhere, set it if you want it */
2912 test_random1(200);
2913 test_random1(2000);
2914 test_random1(20000);
2915 test_random1(200000);
2916 #endif
2918 if (game.info.is_new_game) {
2919 game.info.turn++; /* pregame T0 -> game T1 */
2920 fc_assert(game.info.turn == 1);
2921 game.info.year = game.server.start_year;
2922 /* Must come before assign_player_colors() */
2923 generate_players();
2924 final_ruleset_adjustments();
2927 /* If we have a tile map, and MAPGEN_SCENARIO == map.server.generator,
2928 * call map_fractal_generate anyway to make the specials, huts and
2929 * continent numbers. */
2930 if (map_is_empty()
2931 || (MAPGEN_SCENARIO == wld.map.server.generator
2932 && game.info.is_new_game)) {
2933 struct {
2934 const char *name;
2935 char value[MAX_LEN_NAME * 2];
2936 char pretty[MAX_LEN_NAME * 2];
2937 } mapgen_settings[] = {
2938 { "generator", },
2939 { "startpos", },
2940 { "teamplacement", }
2942 int i;
2943 /* If a specific seed has been requested, there's no point retrying,
2944 * as the map will be the same every time. */
2945 bool retry_ok = (wld.map.server.seed_setting == 0
2946 && wld.map.server.generator != MAPGEN_SCENARIO);
2947 int max = retry_ok ? 3 : 1;
2948 bool created = FALSE;
2949 struct unit_type *utype = NULL;
2950 int sucount = strlen(game.server.start_units);
2952 if (sucount > 0) {
2953 for (i = 0; utype == NULL && i < sucount; i++) {
2954 utype = crole_to_unit_type(game.server.start_units[i], NULL);
2956 } else {
2957 /* First unit the initial city might build. */
2958 utype = get_role_unit(L_FIRSTBUILD, 0);
2960 fc_assert(utype != NULL);
2962 /* Register map generator setting main values. */
2963 for (i = 0; i < ARRAY_SIZE(mapgen_settings); i++) {
2964 const struct setting *pset = setting_by_name(mapgen_settings[i].name);
2966 fc_assert_action(pset != NULL, continue);
2967 (void) setting_value_name(pset, FALSE,
2968 mapgen_settings[i].value,
2969 sizeof(mapgen_settings[i].value));
2970 (void) setting_value_name(pset, TRUE,
2971 mapgen_settings[i].pretty,
2972 sizeof(mapgen_settings[i].pretty));
2975 for (i = 0; !created && i < max ; i++) {
2976 created = map_fractal_generate(TRUE, utype);
2977 if (!created && max > 1) {
2978 int set;
2980 /* If we're retrying, seed_setting == 0, which will yield a new map
2981 * next time */
2982 fc_assert(wld.map.server.seed_setting == 0);
2983 if (i == 0) {
2984 /* We will retry only if max attempts allow it */
2985 log_normal(_("Failed to create suitable map, retrying with another mapseed."));
2986 } else {
2987 /* +1 - start human readable count from 1 and not from 0
2988 * +1 - refers to next round, not to one we just did
2989 * ==
2990 * +2 */
2991 log_normal(_("Attempt %d/%d"), i + 2, max);
2993 wld.map.server.have_resources = FALSE;
2995 /* Remove old information already present in tiles */
2996 map_free(&(wld.map));
2997 free_city_map_index();
2998 /* Restore the settings. */
2999 for (set = 0; set < ARRAY_SIZE(mapgen_settings); set++) {
3000 struct setting *pset = setting_by_name(mapgen_settings[set].name);
3001 #ifdef FREECIV_NDEBUG
3002 setting_enum_set(pset, mapgen_settings[set].value, NULL, NULL, 0);
3003 #else /* FREECIV_NDEBUG */
3004 char error[128];
3005 bool success;
3007 fc_assert_action(pset != NULL, continue);
3008 success = setting_enum_set(pset, mapgen_settings[set].value,
3009 NULL, error, sizeof(error));
3010 fc_assert_msg(success == TRUE,
3011 "Failed to restore '%s': %s",
3012 mapgen_settings[set].name,
3013 error);
3014 #endif /* FREECIV_NDEBUG */
3016 main_map_allocate(); /* NOT map_init() as that would overwrite settings */
3019 if (!created) {
3020 bugreport_request(_("Cannot create suitable map with given settings."));
3022 exit(EXIT_FAILURE);
3025 if (wld.map.server.generator != MAPGEN_SCENARIO) {
3026 script_server_signal_emit("map_generated", 0);
3029 game_map_init();
3031 /* Test if main map generator settings have changed. */
3032 for (i = 0; i < ARRAY_SIZE(mapgen_settings); i++) {
3033 const struct setting *pset = setting_by_name(mapgen_settings[i].name);
3034 char pretty[sizeof(mapgen_settings[i].pretty)];
3036 fc_assert_action(pset != NULL, continue);
3037 if (0 == strcmp(setting_value_name(pset, TRUE, pretty,
3038 sizeof(pretty)),
3039 mapgen_settings[i].pretty)) {
3040 continue; /* Setting didn't change. */
3042 notify_conn(NULL, NULL, E_SETTING, ftc_server,
3043 _("Setting '%s' has been adjusted from %s to %s."),
3044 setting_name(pset),
3045 mapgen_settings[i].pretty,
3046 pretty);
3047 log_normal(_("Setting '%s' has been adjusted from %s to %s."),
3048 setting_name(pset),
3049 mapgen_settings[i].pretty,
3050 pretty);
3054 /* start the game */
3055 set_server_state(S_S_RUNNING);
3056 (void) send_server_info_to_metaserver(META_INFO);
3058 if (game.info.is_new_game) {
3059 /* If we're starting a new game, reset the max_players to be at
3060 * least the number of players currently in the game. */
3061 game.server.max_players = MAX(normal_player_count(), game.server.max_players);
3063 /* Before the player map is allocated (and initialized)! */
3064 game.server.fogofwar_old = game.info.fogofwar;
3066 players_iterate(pplayer) {
3067 player_map_init(pplayer);
3068 pplayer->economic = player_limit_to_max_rates(pplayer);
3069 pplayer->economic.gold = game.info.gold;
3070 } players_iterate_end;
3072 /* Give initial technologies, as specified in the ruleset and the
3073 * settings. */
3074 researches_iterate(presearch) {
3075 init_tech(presearch, TRUE);
3076 give_initial_techs(presearch, game.info.tech);
3077 } researches_iterate_end;
3079 /* Set up alliances based on team selections */
3080 players_iterate(pplayer) {
3081 players_iterate(pdest) {
3082 if (players_on_same_team(pplayer, pdest)
3083 && player_number(pplayer) != player_number(pdest)) {
3084 player_diplstate_get(pplayer, pdest)->type = DS_TEAM;
3085 give_shared_vision(pplayer, pdest);
3086 BV_SET(pplayer->real_embassy, player_index(pdest));
3088 } players_iterate_end;
3089 } players_iterate_end;
3091 /* Assign colors from the ruleset for any players who weren't
3092 * explicitly assigned colors during the pregame.
3093 * This must come after generate_players() since it can depend on
3094 * assigned nations. */
3095 assign_player_colors();
3097 /* Save all settings for the 'reset game' command. */
3098 settings_game_start();
3101 /* FIXME: can this be moved? */
3102 players_iterate(pplayer) {
3103 adv_data_analyze_rulesets(pplayer);
3104 } players_iterate_end;
3106 if (!game.info.is_new_game) {
3107 players_iterate(pplayer) {
3108 if (is_ai(pplayer)) {
3109 set_ai_level_direct(pplayer, pplayer->ai_common.skill_level);
3111 } players_iterate_end;
3112 } else {
3113 players_iterate(pplayer) {
3114 /* Initialize this again to be sure */
3115 adv_data_default(pplayer);
3116 } players_iterate_end;
3119 conn_list_compression_freeze(game.est_connections);
3120 send_all_info(game.est_connections);
3121 conn_list_compression_thaw(game.est_connections);
3123 if (game.info.is_new_game) {
3124 /* Place players' initial units, etc */
3125 init_new_game();
3126 create_animals();
3128 if (game.server.revealmap & REVEAL_MAP_START) {
3129 players_iterate(pplayer) {
3130 map_show_all(pplayer);
3131 } players_iterate_end;
3135 if (game.scenario.is_scenario && game.scenario.players) {
3136 /* This is a heavy scenario. It may include research. The sciencebox
3137 * setting may have been changed. A change to the sciencebox setting
3138 * may have caused the stored amount of bulbs to be enough to finish
3139 * the current research. */
3141 players_iterate(pplayer) {
3142 /* Check for finished research. */
3143 update_bulbs(pplayer, 0, TRUE);
3144 } players_iterate_end;
3147 CALL_FUNC_EACH_AI(game_start);
3150 /**************************************************************************
3151 Initialize game data for the server (corresponds to server_game_free).
3152 **************************************************************************/
3153 void server_game_init(bool keep_ruleset_value)
3155 /* was redundantly in game_load() */
3156 server.playable_nations = 0;
3157 server.nbarbarians = 0;
3158 server.identity_number = IDENTITY_NUMBER_SKIP;
3160 BV_CLR_ALL(identity_numbers_used);
3161 identity_number_reserve(IDENTITY_NUMBER_ZERO);
3163 event_cache_init();
3164 game_init(keep_ruleset_value);
3165 /* game_init() set game.server.plr_colors to NULL. So we need to
3166 * initialize the colors after. */
3167 playercolor_init();
3169 game.server.turn_change_time = 0;
3172 /**************************************************************************
3173 Free game data that we reinitialize as part of a server soft restart.
3174 Bear in mind that this function is called when the 'load' command is
3175 used, for instance.
3176 **************************************************************************/
3177 void server_game_free(void)
3179 CALL_FUNC_EACH_AI(game_free);
3181 /* Free all the treaties that were left open when game finished. */
3182 free_treaties();
3184 /* Free the vision data, without sending updates. */
3185 players_iterate(pplayer) {
3186 unit_list_iterate(pplayer->units, punit) {
3187 /* don't bother using vision_clear_sight() */
3188 vision_layer_iterate(v) {
3189 punit->server.vision->radius_sq[v] = -1;
3190 } vision_layer_iterate_end;
3191 vision_free(punit->server.vision);
3192 punit->server.vision = NULL;
3193 } unit_list_iterate_end;
3195 city_list_iterate(pplayer->cities, pcity) {
3196 /* don't bother using vision_clear_sight() */
3197 vision_layer_iterate(v) {
3198 pcity->server.vision->radius_sq[v] = -1;
3199 } vision_layer_iterate_end;
3200 vision_free(pcity->server.vision);
3201 pcity->server.vision = NULL;
3202 adv_city_free(pcity);
3203 } city_list_iterate_end;
3204 } players_iterate_end;
3206 /* Destroy all players; with must be separate as the player information is
3207 * needed above. This also sends the information to the clients. */
3208 players_iterate(pplayer) {
3209 server_remove_player(pplayer);
3210 } players_iterate_end;
3212 event_cache_free();
3213 log_civ_score_free();
3214 playercolor_free();
3215 citymap_free();
3216 game_free();
3219 /**************************************************************************
3220 Server main loop.
3221 **************************************************************************/
3222 void srv_main(void)
3224 fc_interface_init_server();
3225 advisors_init();
3227 srv_prepare();
3229 /* Run server loop */
3230 do {
3231 set_server_state(S_S_INITIAL);
3233 /* Load a script file. */
3234 if (NULL != srvarg.script_filename) {
3235 /* Adding an error message more here will duplicate them. */
3236 (void) read_init_script(NULL, srvarg.script_filename, TRUE, FALSE);
3239 (void) aifill(game.info.aifill);
3240 if (!game_was_started()) {
3241 event_cache_clear();
3244 log_normal(_("Now accepting new client connections on port %d."),
3245 srvarg.port);
3246 /* Remain in S_S_INITIAL until all players are ready. */
3247 while (S_E_FORCE_END_OF_SNIFF != server_sniff_all_input()) {
3248 /* When force_end_of_sniff is used in pregame, it means that the server
3249 * is ready to start (usually set within start_game()). */
3252 if (S_S_RUNNING > server_state()) {
3253 /* If restarting for lack of players, the state is S_S_OVER,
3254 * so don't try to start the game. */
3255 srv_ready(); /* srv_ready() sets server state to S_S_RUNNING. */
3256 srv_running();
3257 srv_scores();
3260 /* Remain in S_S_OVER until players log out */
3261 while (conn_list_size(game.est_connections) > 0) {
3262 server_sniff_all_input();
3265 /* Close it even between games. */
3266 save_system_close();
3268 if (game.info.timeout == -1 || srvarg.exit_on_end) {
3269 /* For autogames or if the -e option is specified, exit the server. */
3270 server_quit();
3273 /* Reset server */
3274 server_game_free();
3275 server_game_init(FALSE);
3276 mapimg_reset();
3277 load_rulesets(NULL, FALSE, TRUE, FALSE);
3278 game.info.is_new_game = TRUE;
3279 } while (TRUE);
3281 /* Technically, we won't ever get here. We exit via server_quit. */
3284 /***************************************************************
3285 Initialize client specific functions.
3286 ***************************************************************/
3287 struct color;
3288 static inline void server_gui_color_free(struct color *pcolor)
3290 fc_assert_ret(pcolor == NULL);
3292 return;
3295 /***************************************************************************
3296 Returns the id of the city the player map of 'pplayer' has at 'ptile' or
3297 IDENTITY_NUMBER_ZERO if the player map don't have a city there.
3298 ***************************************************************************/
3299 static int server_plr_tile_city_id_get(const struct tile *ptile,
3300 const struct player *pplayer)
3302 const struct player_tile *plrtile = map_get_player_tile(ptile, pplayer);
3304 return plrtile && plrtile->site ? plrtile->site->identity
3305 : IDENTITY_NUMBER_ZERO;
3308 /***************************************************************************
3309 Returns the id of the server setting with the specified name.
3310 ***************************************************************************/
3311 server_setting_id server_ss_by_name(const char *name)
3313 struct setting *pset = setting_by_name(name);
3315 if (pset) {
3316 return setting_number(pset);
3317 } else {
3318 log_error("No server setting named %s exists.", name);
3319 return SERVER_SETTING_NONE;
3323 /***************************************************************************
3324 Returns the name of the server setting with the specified id.
3325 ***************************************************************************/
3326 const char *server_ss_name_get(server_setting_id id)
3328 struct setting *pset = setting_by_number(id);
3330 if (pset) {
3331 return setting_name(pset);
3332 } else {
3333 log_error("No server setting with the id %d exists.", id);
3334 return NULL;
3338 /***************************************************************************
3339 Returns the type of the server setting with the specified id.
3340 ***************************************************************************/
3341 enum sset_type server_ss_type_get(server_setting_id id)
3343 struct setting *pset = setting_by_number(id);
3345 if (pset) {
3346 return setting_type(pset);
3347 } else {
3348 log_error("No server setting with the id %d exists.", id);
3349 return sset_type_invalid();
3353 /***************************************************************************
3354 Returns the value of the boolean server setting with the specified id.
3355 ***************************************************************************/
3356 bool server_ss_val_bool_get(server_setting_id id)
3358 struct setting *pset = setting_by_number(id);
3360 if (pset) {
3361 return setting_bool_get(pset);
3362 } else {
3363 log_error("No server setting with the id %d exists.", id);
3364 return FALSE;
3368 /***************************************************************
3369 Initialize server specific functions.
3370 ***************************************************************/
3371 static void fc_interface_init_server(void)
3373 struct functions *funcs = fc_interface_funcs();
3375 funcs->server_setting_by_name = server_ss_by_name;
3376 funcs->server_setting_name_get = server_ss_name_get;
3377 funcs->server_setting_type_get = server_ss_type_get;
3378 funcs->server_setting_val_bool_get = server_ss_val_bool_get;
3379 funcs->create_extra = create_extra;
3380 funcs->destroy_extra = destroy_extra;
3381 funcs->player_tile_vision_get = map_is_known_and_seen;
3382 funcs->player_tile_city_id_get = server_plr_tile_city_id_get;
3383 funcs->gui_color_free = server_gui_color_free;
3385 /* Keep this function call at the end. It checks if all required functions
3386 are defined. */
3387 fc_interface_init();
3390 /***************************************************************************
3391 Helper function for the mapimg module - tile knowledge.
3392 ****************************************************************************/
3393 static enum known_type mapimg_server_tile_known(const struct tile *ptile,
3394 const struct player *pplayer,
3395 bool knowledge)
3397 if (knowledge && pplayer) {
3398 return tile_get_known(ptile, pplayer);
3401 return TILE_KNOWN_SEEN;
3404 /****************************************************************************
3405 Helper function for the mapimg module - tile terrain.
3406 ****************************************************************************/
3407 static struct terrain
3408 *mapimg_server_tile_terrain(const struct tile *ptile,
3409 const struct player *pplayer, bool knowledge)
3411 if (knowledge && pplayer) {
3412 struct player_tile *plrtile = map_get_player_tile(ptile, pplayer);
3413 return plrtile->terrain;
3416 return tile_terrain(ptile);
3419 /****************************************************************************
3420 Helper function for the mapimg module - tile owner.
3421 ****************************************************************************/
3422 static struct player *mapimg_server_tile_owner(const struct tile *ptile,
3423 const struct player *pplayer,
3424 bool knowledge)
3426 if (knowledge && pplayer
3427 && tile_get_known(ptile, pplayer) != TILE_KNOWN_SEEN) {
3428 struct player_tile *plrtile = map_get_player_tile(ptile, pplayer);
3429 return plrtile->owner;
3432 return tile_owner(ptile);
3435 /****************************************************************************
3436 Helper function for the mapimg module - city owner.
3437 ****************************************************************************/
3438 static struct player *mapimg_server_tile_city(const struct tile *ptile,
3439 const struct player *pplayer,
3440 bool knowledge)
3442 struct city *pcity = tile_city(ptile);
3444 if (!pcity) {
3445 return NULL;
3448 if (knowledge && pplayer) {
3449 struct vision_site *pdcity = map_get_player_city(ptile, pplayer);
3451 if (pdcity) {
3452 return pdcity->owner;
3453 } else {
3454 return NULL;
3458 return city_owner(tile_city(ptile));
3461 /****************************************************************************
3462 Helper function for the mapimg module - unit owner.
3463 ****************************************************************************/
3464 static struct player *mapimg_server_tile_unit(const struct tile *ptile,
3465 const struct player *pplayer,
3466 bool knowledge)
3468 int unit_count = unit_list_size(ptile->units);
3470 if (unit_count == 0) {
3471 return NULL;
3474 if (knowledge && pplayer
3475 && tile_get_known(ptile, pplayer) != TILE_KNOWN_SEEN) {
3476 return NULL;
3479 return unit_owner(unit_list_get(ptile->units, 0));
3482 /****************************************************************************
3483 Helper function for the mapimg module - number of player colors.
3484 ****************************************************************************/
3485 static int mapimg_server_plrcolor_count(void)
3487 return playercolor_count();
3490 /****************************************************************************
3491 Helper function for the mapimg module - one player color.
3492 ****************************************************************************/
3493 static struct rgbcolor *mapimg_server_plrcolor_get(int i)
3495 return playercolor_get(i);