Turn

:This manual is mostly about Freeciv 2.5 server. Things may get different in newer versions.
Freeciv is a turn-based strategy. A turn is a period of the game when all "live" players (human and AI) are allowed to make an amount of game actions; some events that drive the game ahead happen once in a turn. Most notably, all units once in a turn refresh their counters of available movement points; they can spend obtained points within a turn, unused ones will be lost. Also, cities can produce limited number of items (usually only one) within a turn; taxes and worked tile outputs are collected once in a turn; etc. The running server is executing a loop in function srv_running() in server/srv_main.c, each pass of this loop is a turn; server may stop it without halting only when the game ends.
The period of a turn when specific player or player group can act in a game is called phase. Most often Freeciv is played in the concurrent mode - there is only one phase per turn for everybody (AIs do units moving only at phase beginning though). But in the server options another modes available: all players move in a queue, or all teams move in a queue. Most things happen to an empire either at the start or at the end of its phase (since the default mode is one-phase, these periods are commonly referred as "turn start" or "turn end", but in alternate playing they will happen to different players in different time)There are "mini-phases" that don't do most of the turn-specific things, like, when you enter a hut and get barbarians, they have a mini-phase to move out.. Understanding the order in which things happen can give a player considerable advantage.
Turns are enumerated from T1. In older versions of the game (or in compatibility mode) first turn may be T0.
== Turn start ==
Function: begin_turn()
* "turn_started" signal (turn, year) is emitted.
* Player scores are calculated.
* If fog of war setting was changed, the change is applied.
* In the concurrent mode, random sequence of players is defined for the things that happen to them in a queue. Below, "for each player" (FEP) means iterating players in this order (phase_players_iterate(pplayer) macro). In tems-alternating mode, player sequence within a team is permanent through the game.
After the procedure exits, "begin_turn" packet is sent to the clients (only if there is more than one phase). Then, the phases of the game follow in the order of teams' or players' numbers.
== Phase start ==
Function: begin_phase()
* All players get available info on each other (without contact or embassy, it's at least dead/alive and great wonders, and maybe diplomatic states with players you are in contact with).
* "start_phase" packet is sent to the clients.
* FEP: units activities (mining etc.) are updated for each playef's units in their default order:
** Unit activity rate is calculated (if the unit has at least one movement fragment, the rate is proportional to its basic move rate and veteranship power factor) that is added to its activity counter.
** For performing certain activities, the unit might have a chance to become veteran.
** Unit's movepoints are restored.
** Autoexplorers explore.
** Counters of the units on the tile that do the same are summed to look if the activity is done (for pillaging, in 2.5 you need only 1 activity, but it may trigger diplomatic incident). If so, changes are applied to the tile with side effects like bouncing ships from ocean converted to swamp.
*** Units doing the same changing activity on the tile become idle 2.5: even if we have irrigated swamp to grassland and could irrigate more.
*** Adjacent units are also checked for like haven't they lost their only irrigation source here.
*** Fortifying and converting units do the thing.
* FEP: unit orders are executed, units are processed by the default player's unit list (not necessarily in command order). 
* FEP (human only): building advisor prepares advice for cities.
* FEP, city data are sent.
* FEP (alive): revolution finishes, if it's the time and target gov is specified (if not, a notification is sent).
* FEP (AI): diplomatic meetings are considered.
* FEP (AI): do turn-begin activities (move units etc.)
* Players that don't have units or cities die from the game.
* The phase timer is started.
* Global game info is sent to the clients.
* "begin_turn" packet is sent for a one-phase mode.
Since this moment, turn is considered new even if the game was restarted from savegame. If turn autosaves of game/map image are enabled, now one happens.
== Running a phase ==
Function: server_sniff_all_input()
Server sniffs all packages clients send to it. Phase players can play until phase time runs off/every human presses "Turn done". After that moment, timer is cleared and phase end starts.
== Phase end ==
Function: phase_end()
During phase end, server-client packages go to a buffer, that is unbuffered when the phase ends to end.
* "end_phase" packet is sent
* FEP: Techs updated:
** If a player has not set what to research, a tech towards his or her goal is selected, or random tech (by game random tech setting) if no goal.
** If a tech is going to be lost, future techs are reduced (if any), or random losable tech (holes allowed/not) is lost.
* At this moment, city state updates are stopped due to many things that leave them in intermediate out-of-the-game state.
* FEP (AI): unit end turn AI activities (no movement)
* FEP:
** Auto-settlers do their move to work terrain.
** For AIs, governments, techs, taxes, cities and space program are handled.
* FEP:
** "Tech_Parasite" (Great Library) effect may bring techs known to others.
** Auto-upgrade (Leonardo's Workshop)
** For each player's unit:
*** Hitponts regenerate/shrink;
*** If they shrink to zero or below, the unit dies;
*** Fueled units running out of fuel try to seek a resort automatically within left movepoints.
** Fueled units are refueled if possible, or their fuel is reduced, and they crash if it goes zero or below.'
** Spaceship parts autoplaced.
** Cities are updated. For cities in their normal order:
*** Citizen assimilation handled;
*** Traderoutes that no longer can exist are cancelled.
** Now, for the player's cities in a randomized order:
*** City is refreshed. Workers are auto-arranged if radius has changed significantly.
*** Unit upkeep is recalculated bug in fc2.5?
*** If something changes, the workers are arranged by some default manager.
*** If not enough shields, units upkept with them are disbanded (in city units list order). If it does not balance without touching undisbandable units, a citizen is spent on the upkeep of each such unit. The city may be destroyed in effect. If, otherwise, some surplus shields remain, they are added to the shield stock.
*** The production is remebered for the case it is changed to another genus.
*** City tries to produce something:
**** For Mint-like buildings, remained shields are converted to gold, then, if something else is on the plan, the production changes.
**** For other improvements, here production target is upgraded if it becomes obsolete (to the replaced_by building).
**** If you still can't in principle build the improvement any more (your techs don't allow it, your spaceship is finished etc.), here you get a notification and a signal is emitted.
**** Otherwise, if your shield stockActually, shields are stored in several numbers to know how they behave on different changes. For this article, the full value in city.shield_stock is important. is greater or equal to the improvement cost:
***** For small wonders that can be built, another instance of this small wonder in the player's empire is removed.
***** For space parts, they are producedEffects are checked in the order "SS_Structural"→"SS_Component"→"SS_Module". Other improvements appear in the city; wonders are updated right this moment to the cache used by requirements; for global wonders, notifications are sent to everybody. Then shield stocks are reduced on the used cost, and the "building_built" signal is emitted (as any signal, might potentially destroy the city right here).
***** City vision radius is updated.
***** Darwin's Voyage effect for the building may give techs.
***** If it was a space part, corresponding information is sent around. Otherwise, the city is refreshed and the workers are auto-arranged if the radius has changed.
***** Production is changed according to the worklist. If no worklist, then, if the building is a special one that can be built again (Gold, SS_*), it is started again, otherwise new one is chosen by the advisor.
*** If a unit is produced:
**** If the production can be changed (the city has not bought the former turn) and the unit is obsolete, city switches to the obsoleting unit.
**** If the city does not fulfil the units requirements (tech, improvement, unit has no "NoBuild" flag...) and the player is not barbarian, it is notified and a signal is emitted 2.5 bug: city surival is not checked.
**** Otherwise, if we have enough shields to build the unit:
***** If it is a settler consuming last population, we have at least two cities and the city setting enabling this is on, the city is disbanded (otherwise, a notification and a signal of not being able to produce happen), its units, including the newly created one, are transferred to the nearest city, and the city processing is finished here.
***** Otherwise, the city remembers that we have built last this turn.
***** If some population cost is paid, the city size is reduced and the city is updated (citizens, borders...) and refreshedcity_refresh():
* Working radius is calculated.
* If the workable area is changed, vision radius is updated. If the area has reduced, workers are assigned to free tiles or, if none more, to the default specialists. AI gets a hook to update its data. Player is notified about the change.
* Units upkeep is calculated.
* Tiles output is calculated.
* If the workable tiles have been changed, send city info and return true, otherwise return false. with workers auto-arranging if the workable tiles change.
***** Shields are reduced on paid cost. Notifications and "unit_built" signal are emitted.
***** If we have additional building slots, the unit we build does not cost pop and is not unique, it can be produced more than one time. If the city has worklist, to use the full "City_Build_Slots" effect, the unit should be repeated at the top of the list so many times (the positions will be removed). For floor(shield_stock / unit_cost), similar units are built with corresponding shield stock reduction (cycle breaks only if the city is destroyed in process).
***: Notes:
***# A granary influents food stock if built on the growing turn. Barracks won't regenerate all hp of units resting in the city the turn they are built.
***# "City_Build_Slots" effect works for making units only.
***# Units that obsolete another but have fallen not available for e.g. government change are not "downgraded" (but also are not produced, even if you have paid for them!).
***# "unit_built" signal is not emitted if you disband a city; "city_destroyed" with nil as the destroyer parameter is instead. By the way, the unit will have the former city's "Veteran_Build" rank as a last memory of it.
***# City happiness is not immediately updated with building a unit unless it costs population.
*** Here it's checked if the game is over and it's time to leave the
*** If the city is big enough and was happy before, it celebrates and gets its rapture counter up, otherwise any celebrations are cancelled and the counter is zeroed. Then, the city's "was happy" switch is updated from its feeling level.
*** Plague is checked.
*** City gets its food surplus into its granaries.
*** If the full granary size is achieved or overdone and the plague has not just struck, or the city has rapture grow this turn, the city tries to grow. If no necessary aqueduct, it just loses some food (but granary building effect reduces this loss); any way, all that does not fit into the (new) food stock is lost. A grown city is refreshed.
*** City claimed borders are updated.
*** Food in the city is balanced. If not enough, food-upkept units are disbanded, then a citizen is lost (may destroy the city). Granary food left after a shrink is calculated from the granary size of the reduced city but with granary preserving effect of the city before shrink.
*** Sell, buy and airlift counters are cleared.
*** Bulbs are harvested to the player's research. (If it has negative bulbs, a tech can be lost here, but unlikely unless a queer save involved).
*** Gold is harvested to the player's treasury, then gold upkeep to buildings and units is paid. If the treasury appears in debt after this calculation, balancing happens according to gold upkeep style (not here in style 2).
*** If the city is in disorder, notification is sent and disorder turns counter is increased.
*** Pollution is checked (peoduction is calculated without disorder fine)
*** If you rebel turns enough to overthrow your government, it happens.
*** The city is finally refreshed and workers are auto-arranged.
** National gold upkeeps are balanced, according to the upkeep style. Nationally supported improvements (not wonders) are put on list, and a random one is sold until the gold is positive. The same happens to gold-upkept units (transports are disbanded only after all their cargo is checked for disbanding, units that can not be "sold" don't return their upkeep into the treasury).
* If expenses exceed 150% of the treasury, warning "LOW on FUNDS!" is sent to the player.
** Thaw city workers queues clarify?
** Pay tech upkeep and check for obtaining/losing techs.
** Flush the packets clarify?
* FEP: refresh cities vision.
* At this moment, the players in "dying" state leave the gameboard.
* City sending is unfrozen, and cities are sent.
* Internet or Apollo Program revealing effects show things.
* Marco Polo's Embassy effect gives contact to other players.
* FEP: Phase finished AI function (for human players, also needed to initialize advisors).
Now connections are unbuffered. If the game is over for this moment, other phases of the turn are not started. After done with phases, the turn begins to end.
== Turn end ==
Function: end_turn()
* End phase packet is sent to the observers.
* Borders are updated over the map.
* For AI non-barbarian players, some weird, probably buggy in 2.5 debug stats are calculated.
* Barbarians are summoned. clarify from here on
* If migrations are enabled, they happen, and all cities are sent to players.
* City disasters.
* Global warming.
* Nuclear winter.
* Diplomatic states are updated (e.g. ceasefires run out). Players are iterated in a two-floor loop, on both levels in their main order. This includes moving or destroying illegally positioned units.
* Historians may do their reports.
* Settings turn.
* Stdin turn.
* Voting turn.
* In-game date advances.
* Timeout is updated.
* Game and players info is sent to the clients.
* Year is sent to the clients.
Then, the metaserver info is sent. The game is checked to be over by rules or stopped manually; if so, players are ranked. 
== Game over ==
Client connections are thawed, and the turn timer is cleared. The scores are calculated and go to the scorelog. Map is shown to everybody. Server resends info to the metaserver, and saves the game on gameover.
== Difference with commercial games ==
In Civilization III, worker terrain activities are executed immediately, and cities produce at phase start (so for emergency getting a defender you can't buy it, only use draft mechanics of the game). Also, CivIII's production is forced to change after a turn if the wonder you build is obsolete. Also, military law pacifies city only after a turn.
== Notes ==