Line data Source code
1 : /* Copyright (C) 2026 Wildfire Games. 2 : * This file is part of 0 A.D. 3 : * 4 : * 0 A.D. is free software: you can redistribute it and/or modify 5 : * it under the terms of the GNU General Public License as published by 6 : * the Free Software Foundation, either version 2 of the License, or 7 : * (at your option) any later version. 8 : * 9 : * 0 A.D. is distributed in the hope that it will be useful, 10 : * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 : * GNU General Public License for more details. 13 : * 14 : * You should have received a copy of the GNU General Public License 15 : * along with 0 A.D. If not, see <http://www.gnu.org/licenses/>. 16 : */ 17 : 18 : #ifndef INCLUDED_TURNMANAGER 19 : #define INCLUDED_TURNMANAGER 20 : 21 : #include "lib/code_annotation.h" 22 : #include "ps/CStr.h" 23 : #include "simulation2/helpers/SimulationCommand.h" 24 : 25 : #include <cstddef> 26 : #include <deque> 27 : #include <js/RootingAPI.h> 28 : #include <js/TypeDecls.h> 29 : #include <js/Value.h> 30 : #include <js/ValueArray.h> 31 : #include <list> 32 : #include <map> 33 : #include <optional> 34 : #include <string> 35 : #include <vector> 36 : 37 : class CSimulation2; 38 : class CSimulationMessage; 39 : class IReplayLogger; 40 : 41 : /** 42 : * This file defines the base class of the turn managers for clients, local games and replays. 43 : * The basic idea of our turn managing system across a network is as in this article: 44 : * http://www.gamasutra.com/view/feature/3094/1500_archers_on_a_288_network_.php?print=1 45 : * 46 : * Each player performs the simulation for turn N. 47 : * User input is translated into commands scheduled for execution in turn N+2 which are 48 : * distributed to all other clients. 49 : * After a while, a client wants to perform the simulation for turn N+1, 50 : * which first requires that it has all the other clients' commands for turn N+1. 51 : * In that case, it does the simulation and tells all the other clients (via the server) 52 : * it has finished sending commands for turn N+2, and it starts sending commands for turn N+3. 53 : * 54 : * Commands are redistributed immediately by the server. 55 : * To ensure a consistent execution of commands, they are each associated with a 56 : * client session ID (which is globally unique and consistent), which is used to sort them. 57 : */ 58 : 59 : /** 60 : * Default turn length in SP & MP. 61 : * This value should be as low as possible, while not introducing un-necessary lag. 62 : */ 63 : inline constexpr std::uint32_t DEFAULT_TURN_LENGTH = 200; 64 : 65 : /** 66 : * In single-player, commands are directly scheduled for the next turn. 67 : */ 68 : inline constexpr std::uint32_t COMMAND_DELAY_SP = 1; 69 : 70 : /** 71 : * In multi-player, clients can only compute turn N if all clients have finished sending commands for it, 72 : * i.e. N < CurrentTurn + COMMAND_DELAY for all clients. 73 : * Commands are sent from client to server to client, and both client and network can lag. 74 : * If a client reaches turn CURRENT_TURN + COMMAND_DELAY - 1, it'll freeze while waiting for commands. 75 : * To avoid that, we increase the command-delay to make sure that in general players will have received all commands 76 : * by the time they reach a given turn. Keep in mind the minimum delay is one turn. 77 : * This value should be as low as possible while avoiding 'freezing' in general usage. 78 : * TODO: 79 : * - this command-delay could vary based on server-client pings 80 : * - it ought be possible to send commands in a P2P fashion (with server verification), which would lower the ping. 81 : */ 82 : inline constexpr std::uint32_t COMMAND_DELAY_MP = 4; 83 : 84 : /** 85 : * Common turn system (used by clients and offline games). 86 : */ 87 : class CTurnManager 88 : { 89 : NONCOPYABLE(CTurnManager); 90 : public: 91 : using UpdateCallback = 92 : std::function<void(const std::string&, const std::optional<JS::HandleValueArray>)>; 93 : 94 : static const CStr EventNameSavegameLoaded; 95 : 96 : /** 97 : * Construct for a given network session ID. 98 : */ 99 : CTurnManager(CSimulation2& simulation, std::uint32_t defaultTurnLength, std::uint32_t commandDelay, 100 : int clientId, IReplayLogger& replay); 101 : 102 6 : virtual ~CTurnManager() { } 103 : 104 : void ResetState(turn_id_t newCurrentTurn, turn_id_t newReadyTurn); 105 : 106 : /** 107 : * Set the current user's player ID, which will be added into command messages. 108 : */ 109 : void SetPlayerID(int playerId); 110 : 111 : /** 112 : * Advance the simulation by a certain time. If this brings us past the current 113 : * turn length, the next turns are processed and the function returns true. 114 : * Otherwise, nothing happens and it returns false. 115 : * 116 : * @param simFrameLength Length of the previous frame, in simulation seconds 117 : * @param maxTurns Maximum number of turns to simulate at once 118 : */ 119 : bool Update(float simFrameLength, size_t maxTurns, const UpdateCallback& sendEventToAll); 120 : 121 : /** 122 : * Advance the simulation by as much as possible. Intended for catching up 123 : * over a small number of turns when rejoining a multiplayer match. 124 : * Returns true if it advanced by at least one turn. 125 : */ 126 : bool UpdateFastForward(); 127 : 128 : /** 129 : * Advance the graphics by a certain time. 130 : * @param simFrameLength Length of the previous frame, in simulation seconds 131 : * @param realFrameLength Length of the previous frame, in real time seconds 132 : */ 133 : void Interpolate(float simFrameLength, float realFrameLength); 134 : 135 : /** 136 : * Called by networking code when a simulation message is received. 137 : */ 138 : virtual void OnSimulationMessage(CSimulationMessage* msg) = 0; 139 : 140 : /** 141 : * Called by simulation code, to add a new command to be distributed to all clients and executed soon. 142 : */ 143 : virtual void PostCommand(JS::HandleValue data) = 0; 144 : 145 : /** 146 : * Called when all commands for a given turn have been received. 147 : * This allows Update to progress to that turn. 148 : */ 149 : void FinishedAllCommands(turn_id_t turn, std::uint32_t turnLength); 150 : 151 : /** 152 : * Enables the recording of state snapshots every @p numTurns, 153 : * which can be jumped back to via RewindTimeWarp(). 154 : * If @p numTurns is 0 then recording is disabled. 155 : */ 156 : void EnableTimeWarpRecording(size_t numTurns); 157 : 158 : /** 159 : * Jumps back to the latest recorded state snapshot (if any). 160 : */ 161 : void RewindTimeWarp(); 162 : 163 : void QuickSave(JS::HandleValue GUIMetadata); 164 : std::optional<JS::Value> TryQuickLoad(); 165 : 166 226 : turn_id_t GetCurrentTurn() const { return m_CurrentTurn; } 167 : 168 : /** 169 : * @return how many turns are ready to be computed. 170 : * (used to detect players/observers that fall behind the live game. 171 : */ 172 0 : turn_id_t GetPendingTurns() const { return m_ReadyTurn - m_CurrentTurn; } 173 : 174 : protected: 175 : /** 176 : * Store a command to be executed at a given turn. 177 : */ 178 : void AddCommand(int client, int player, JS::HandleValue data, turn_id_t turn); 179 : 180 : /** 181 : * Called when this client has finished sending all its commands scheduled for the given turn. 182 : */ 183 : virtual void NotifyFinishedOwnCommands(turn_id_t turn) = 0; 184 : 185 : /** 186 : * Called when this client has finished a simulation update. 187 : */ 188 : virtual void NotifyFinishedUpdate(turn_id_t turn, const UpdateCallback& sendEventToAll) = 0; 189 : 190 : /** 191 : * Returns whether we should compute a complete state hash for the given turn, 192 : * instead of a quick less-complete hash. 193 : */ 194 : bool TurnNeedsFullHash(turn_id_t turn) const; 195 : 196 : CSimulation2& m_Simulation2; 197 : 198 : /// The turn that we have most recently executed 199 : turn_id_t m_CurrentTurn; 200 : 201 : // Current command delay (commands are scheduled for m_CurrentTurn + m_CommandDelay) 202 : std::uint32_t m_CommandDelay; 203 : 204 : /// The latest turn for which we have received all commands from all clients 205 : turn_id_t m_ReadyTurn; 206 : 207 : // Current turn length 208 : std::uint32_t m_TurnLength; 209 : 210 : /// Commands queued at each turn (index 0 is for m_CurrentTurn+1) 211 : std::deque<std::map<turn_id_t, std::vector<SimulationCommand>>> m_QueuedCommands; 212 : 213 : int m_PlayerId; 214 : unsigned int m_ClientId; 215 : 216 : /// Simulation time remaining until we ought to execute the next turn (as a negative value to 217 : /// add elapsed time increments to until we reach 0). 218 : float m_DeltaSimTime; 219 : 220 : IReplayLogger& m_Replay; 221 : 222 : // The number of the last turn that is allowed to be executed (used for replays) 223 : turn_id_t m_FinalTurn; 224 : 225 : private: 226 : size_t m_TimeWarpNumTurns; // 0 if disabled 227 : std::list<std::string> m_TimeWarpStates; 228 : std::string m_QuickSaveState; // TODO: should implement a proper disk-based quicksave system 229 : JS::PersistentRootedValue m_QuickSaveMetadata; 230 : }; 231 : 232 : #endif // INCLUDED_TURNMANAGER