high_level_multiplayer.rst 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. .. _doc_high_level_multiplayer:
  2. High level multiplayer
  3. ======================
  4. Why high level?
  5. ----------------
  6. Godot always supported standard networking via UDP, TCP and some high level protocols such as SSL and HTTP.
  7. These protocols are very flexible and should support everything. However, for games themselves (or unless you are working
  8. with a custom server), using them to synchronize game state manually can be an enormous amount of work.
  9. This is due to the inherent limitations of the protocols:
  10. - TCP ensures packets will always arrive, but latency is generally high due to error correction.
  11. It's also quite a complex protocol because it understands what a "connection" is.
  12. - UDP is a simpler protocol which only sends packets (no connection required). The fact it does no error correction
  13. makes it pretty quick (low latency), but it has the disadvantage that packets may be lost along the way.
  14. Added to that, the MTU (maximum packet size) for UDP is generally low (only a few hundred bytes), so transmitting
  15. larger packets means splitting them, reorganizing them, retrying if a part fails, etc.
  16. Mid level abstraction
  17. ---------------------
  18. Before going into how we would like to synchronize a game across the network, it would be wise to understand how the base network API
  19. for synchronization works. Godot uses a mid-level object :ref:`NetworkedMultiplayerPeer <class_NetworkedMultiplayerPeer>`.
  20. This object is not meant to be created directly, but is designed so that several implementations can provide it:
  21. .. image:: /img/nmpeer.png
  22. This object extends from :ref:`PacketPeer <class_PacketPeer>`, so it has all the useful methods for serializing data you are used to, thanks to
  23. Godot's beautiful object-oriented design. It adds methods to set a peer, transfer mode, etc. It also includes signals that will let you know
  24. when peers connect or disconnect.
  25. The idea is that this class interface can abstract most types of network layers, topologies and libraries. By default Godot
  26. provides an implementation based on ENet (:ref:`NetworkedMultiplayerEnet <class_NetworkedMultiplayerENet>`), but the plan
  27. is that this could support mobile APIs (for adhoc WiFi, Bluetooth), custom device/console networking APIs, etc.
  28. For most common cases, using this object directly is discouraged, as Godot provides even higher level networking facilities.
  29. Yet it is made available to scripting in case a game has specific needs for a lower level API.
  30. Initializing the network
  31. ------------------------
  32. The object that controls networking in Godot is the same one that controls everything tree-related: :ref:`SceneTree <class_SceneTree>`.
  33. To initialize high level networking, SceneTree must be provided a NetworkedMultiplayerPeer object.
  34. Initializing as a server, listening on the given port, with a given maximum of 4 peers:
  35. ::
  36. var host = NetworkedMultiplayerENet.new()
  37. host.create_server(SERVER_PORT, 4)
  38. get_tree().set_network_peer(host)
  39. Initializing as a client, connecting to a given IP and port:
  40. ::
  41. var host = NetworkedMultiplayerENet.new()
  42. host.create_client(ip, SERVER_PORT)
  43. get_tree().set_network_peer(host)
  44. Terminating the networking feature:
  45. ::
  46. get_tree().set_network_peer(null)
  47. Managing connections
  48. --------------------
  49. Some games accept connections at any time, others during the lobby phase. Godot can be requested to no longer accept
  50. connections at any point. To manage who connects, Godot provides the following signals in SceneTree:
  51. Server and Clients:
  52. - `network_peer_connected(int id)`
  53. - `network_peer_disconnected(int id)`
  54. The above signals are called in every peer connected to the server when a new one connects or disconnects.
  55. It is very useful to keep track of the IDs above (clients will connect with non-zero and non-one unique ID),
  56. while the server is warranted to always use ID=1. These IDs will be useful mostly for lobby management.
  57. Clients:
  58. - `connected_to_server`
  59. - `connection_failed`
  60. - `server_disconnected`
  61. Again, all these functions are mainly useful for lobby management, or for adding/removing players on the fly.
  62. For these tasks, the server clearly has to work as a server and you have do tasks manually such as sending a new
  63. player that connected information about other already connected players (e.g. their names, stats, etc).
  64. Lobby can be implemented any way you want, but the most common way is to use a node with the same name across scenes in all peers.
  65. Generally, an autoloaded node/singleton is a great fit for this, to always have access to e.g. "/root/lobby".
  66. RPC
  67. ---
  68. To communicate between peers, the easiest way is to use RPC (remote procedure call). This is implemented as a set of functions
  69. in :ref:`Node <class_Node>`:
  70. - `rpc("function_name", <optional_args>)`
  71. - `rpc_id(<peer_id>,"function_name", <optional_args>)`
  72. - `rpc_unreliable("function_name", <optional_args>)`
  73. - `rpc_unreliable_id(<peer_id>, "function_name", <optional_args>)`
  74. Synchronizing member variables is also possible:
  75. - `rset("variable", value)`
  76. - `rset_id(<peer_id>, "variable", value)`
  77. - `rset_unreliable("variable", value)`
  78. - `rset_unreliable_id(<peer_id>, "variable", value)`
  79. Functions can be called in two fashions:
  80. - Reliable: the function call will arrive no matter what, but may take longer because it will be re-transmitted in case of failure.
  81. - Unreliable: if the function call does not arrive, it will not be re-transmitted, but if it arrives it will do it quickly.
  82. In most cases, Reliable is desired. Unreliable is mostly useful when synchronizing objects that move (sync must happen constantly,
  83. and if a packet is lost, it's not that bad because a new one will eventually arrive).
  84. Back to lobby
  85. -------------
  86. Let's get back to the lobby. Imagine that each player that connects to the server will tell everyone about it.
  87. ::
  88. # Typical lobby implementation, imagine this being in /root/lobby
  89. extends Node
  90. # Connect all functions
  91. func _ready():
  92. get_tree().connect("network_peer_connected", self, "_player_connected")
  93. get_tree().connect("network_peer_disconnected", self, "_player_disconnected")
  94. get_tree().connect("connected_to_server", self, "_connected_ok")
  95. get_tree().connect("connection_failed", self, "_connected_fail")
  96. get_tree().connect("server_disconnected", self, "_server_disconnected")
  97. # Player info, associate ID to data
  98. var player_info = {}
  99. # Info we send to other players
  100. var my_info = { name = "Johnson Magenta", favorite_color = Color8(255, 0, 255) }
  101. func _player_connected(id):
  102. pass # Will go unused, not useful here
  103. func _player_disconnected(id):
  104. player_info.erase(id) # Erase player from info
  105. func _connected_ok():
  106. # Only called on clients, not server. Send my ID and info to all the other peers
  107. rpc("register_player", get_tree().get_network_unique_id(), my_info)
  108. func _server_disconnected():
  109. pass # Server kicked us, show error and abort
  110. func _connected_fail():
  111. pass # Could not even connect to server, abort
  112. remote func register_player(id, info):
  113. # Store the info
  114. player_info[id] = info
  115. # If I'm the server, let the new guy know about existing players
  116. if (get_tree().is_network_server()):
  117. # Send my info to new player
  118. rpc_id(id, "register_player", 1, my_info)
  119. # Send the info of existing players
  120. for peer_id in player_info:
  121. rpc_id(id, "register_player", peer_id, player_info[peer_id])
  122. # Call function to update lobby UI here
  123. You might have noticed already something different, which is the usage of the `remote` keyword on the `register_player` function:
  124. ::
  125. remote func register_player(id, info):
  126. This keyword has two main uses. The first is to let Godot know that this function can be called from RPC. If no keywords are added,
  127. Godot will block any attempts to call functions for security. This makes security work a lot easier (so a client can't call a function
  128. to delete a file on another client's system).
  129. The second use is to specify how the function will be called via RPC. There are four different keywords:
  130. - `remote`
  131. - `sync`
  132. - `master`
  133. - `slave`
  134. The `remote` keyword means that the `rpc()` call will go via network and execute remotely.
  135. The `sync` keyword means that the `rpc()` call will go via network and execute remotely, but will also execute locally (do a normal function call).
  136. The others will be explained further down.
  137. With this, lobby management should be more or less explained. Once you have your game going, you will most likely want to add some
  138. extra security to make sure clients don't do anything funny (just validate the info they send from time to time, or before
  139. game start). For the sake of simplicity and the fact each game will share different information, this was not done here.
  140. Starting the game
  141. -----------------
  142. Once enough people has gathered in the lobby, the server will most likely want to start the game. This is honestly nothing
  143. special in itself, but we'll explain a few nice tricks that can be done at this point to make your life much easier.
  144. Player scenes
  145. ^^^^^^^^^^^^^
  146. In most games, each player will likely have its own scene. Remember that this is a multiplayer game, so in every peer
  147. you need to instance **one scene for each player connected to it**. For a 4 player game, each peer needs to instance 4 player nodes.
  148. So, how to name such nodes? In Godot nodes need to have an unique name. It must also be relatively easy for a player to tell which
  149. nodes represent each player id.
  150. The solution is to simply name the *root nodes of the instanced player scenes as their network ID*. This way, they will be the same in
  151. every peer and RPC will work great! Here is an example:
  152. ::
  153. remote func pre_configure_game():
  154. # Load world
  155. var world = load(which_level).instance()
  156. get_node("/root").add_child(world)
  157. # Load my player
  158. var my_player = preload("res://player.tscn").instance()
  159. my_player.set_name(str(get_tree().get_network_unique_id()))
  160. my_player.set_network_mode(NETWORK_MODE_MASTER) # Will be explained later
  161. get_node("/root/world/players").add_child(my_player)
  162. # Load other players
  163. for p in player_info:
  164. var player = preload("res://player.tscn").instance()
  165. player.set_name(str(p))
  166. player.set_network_mode(NETWORK_MODE_SLAVE) # Will be explained later
  167. get_node("/root/world/players").add_child(player)
  168. # Tell server (remember, server is always ID=1) that this peer is done pre-configuring
  169. rpc_id(1, "done_preconfiguring", get_tree().get_network_unique_id())
  170. Synchronized game start
  171. ^^^^^^^^^^^^^^^^^^^^^^^
  172. Setting up players might take different amount of time on every peer due to lag and any large number of reasons.
  173. To make sure the game will actually start when everyone is ready, pausing the game can be very useful:
  174. ::
  175. remote func pre_configure_game():
  176. get_tree().set_pause(true) # Pre-pause
  177. # The rest is the same as in the code in the previous section (look above)
  178. When the server gets the OK from all the peers, it can tell them to start, as for example:
  179. ::
  180. var players_done = []
  181. remote func done_preconfiguring(who):
  182. # Here is some checks you can do, as example
  183. assert(get_tree().is_network_server())
  184. assert(who in player_info) # Exists
  185. assert(not who in players_done) # Was not added yet
  186. players_done.append(who)
  187. if (players_done.size() == player_info.size()):
  188. rpc("post_configure_game")
  189. remote func post_configure_game():
  190. get_tree().set_pause(false)
  191. # Game starts now!
  192. Synchronizing the game
  193. ----------------------
  194. In most games, the goal of supporting multiplayer neworking is to make sure that the game runs synchronized in all the peers playing it.
  195. Besides supplying an RPC and remote member variable set implementation, Godot adds the concept of master and slave network modes.
  196. Master and slave modes
  197. ^^^^^^^^^^^^^^^^^^^^^^
  198. Very similarly to how the pause mode works in regular nodes (with pause, process, inherit modes), nodes can be set a "network mode"
  199. with the function :ref:`Node.set_network_mode(mode) <class_Node_set_network_mode>`. The mode can be: Master, Slave and Inherit.
  200. The Inherit mode assumes the value of the parent node. If the parent node is also in this mode, it will go up in the parenthood chain until it finds a specific mode.
  201. If no non-inherit mode is found, Master will be assumed for the server and Slave for clients.
  202. This means that, upon loading scenes, the server is by default the master and clients are the slaves. Checking that a node is in master mode is done by calling:
  203. ::
  204. is_network_master()
  205. If you have paid attention to the previous example, it's possible you noticed each node being set a role when being loaded in each peer:
  206. ::
  207. [...]
  208. # Load my player
  209. var my_player = preload("res://player.tscn").instance()
  210. my_player.set_name(str(get_tree().get_network_unique_id()))
  211. my_player.set_network_mode(NETWORK_MODE_MASTER)
  212. get_node("/root/world/players").add_child(my_player)
  213. # Load other players
  214. for p in player_info:
  215. var player = preload("res://player.tscn").instance()
  216. player.set_name(str(p))
  217. player.set_network_mode(NETWORK_MODE_SLAVE)
  218. get_node("/root/world/players").add_child(player)
  219. [...]
  220. Here, each time this piece of code is executed on each peer, the peer makes the node it controls master, and the ones it does not slaves.
  221. The modes for each are different on each peer. To clarify, here is an example of how this looks in the
  222. `bomber demo <https://github.com/godotengine/godot-demo-projects/tree/master/networking/simple_multiplayer>`_:
  223. .. image:: /img/nmms.png
  224. Master and slave keywords
  225. ^^^^^^^^^^^^^^^^^^^^^^^^^
  226. .. FIXME: Clarify the equivalents to the GDScript keywords in C# and Visual Script.
  227. The real advantage of this model is when used with the `master`/`slave` keywords in GDScript (or their equivalent in C# and Visual Script).
  228. Similarly to the `remote` keyword, functions can also be tagged with them:
  229. Example bomb code:
  230. ::
  231. for p in bodies_in_area:
  232. if (p.has_method("exploded")):
  233. p.rpc("exploded", bomb_owner)
  234. Example player code:
  235. ::
  236. slave func stun():
  237. stunned = true
  238. master func exploded(by_who):
  239. if (stunned):
  240. return # Already stunned
  241. rpc("stun")
  242. stun() # Stun myself, could have used sync keyword too.
  243. In the above example, a bomb explodes somewhere (likely managed by whoever is master). The bomb knows the bodies in the area, so it checks them
  244. and checks that they contain an `exploded` function.
  245. If they do, the bomb calls `exploded` on it. However, the `exploded` method in the player has a `master` keyword. This means that only the player
  246. who is master for that instance will actually get the function.
  247. This instance, then, calls the `stun` function in the same instances of that same player (but in different peers), and only those which are set as slave,
  248. making the player look stunned in all the peers (as well as the current, master one).
  249. .. FIXME: Document the sync keyword