summaryrefslogtreecommitdiff
path: root/core/io/multiplayer_peer.cpp
diff options
context:
space:
mode:
authorFabio Alessandrelli <fabio.alessandrelli@gmail.com>2021-07-16 00:43:49 +0200
committerFabio Alessandrelli <fabio.alessandrelli@gmail.com>2021-07-29 10:40:03 +0200
commit1e8bf86379ca818bf7208de5f04f986be95dc102 (patch)
tree58e22020da59410beec75c4b07ef85dfd95f4c4f /core/io/multiplayer_peer.cpp
parent4cfa9bc0f1ef1d584705f36d70ee7f4d37a02b8c (diff)
[Net] Add generate_unique_id to MultiplayerPeer.
Used by ENetMultiplayerPeer and WebSocketServer to generate network IDs, and exposed to the user for p2p networks (e.g. WebRTCMultiplayerPeer) and custom MultiplayerPeer implementations.
Diffstat (limited to 'core/io/multiplayer_peer.cpp')
-rw-r--r--core/io/multiplayer_peer.cpp24
1 files changed, 24 insertions, 0 deletions
diff --git a/core/io/multiplayer_peer.cpp b/core/io/multiplayer_peer.cpp
index 8126b4cea3..8b3b1eef8e 100644
--- a/core/io/multiplayer_peer.cpp
+++ b/core/io/multiplayer_peer.cpp
@@ -30,6 +30,29 @@
#include "multiplayer_peer.h"
+#include "core/os/os.h"
+
+uint32_t MultiplayerPeer::generate_unique_id() const {
+ uint32_t hash = 0;
+
+ while (hash == 0 || hash == 1) {
+ hash = hash_djb2_one_32(
+ (uint32_t)OS::get_singleton()->get_ticks_usec());
+ hash = hash_djb2_one_32(
+ (uint32_t)OS::get_singleton()->get_unix_time(), hash);
+ hash = hash_djb2_one_32(
+ (uint32_t)OS::get_singleton()->get_user_data_dir().hash64(), hash);
+ hash = hash_djb2_one_32(
+ (uint32_t)((uint64_t)this), hash); // Rely on ASLR heap
+ hash = hash_djb2_one_32(
+ (uint32_t)((uint64_t)&hash), hash); // Rely on ASLR stack
+
+ hash = hash & 0x7FFFFFFF; // Make it compatible with unsigned, since negative ID is used for exclusion
+ }
+
+ return hash;
+}
+
void MultiplayerPeer::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_transfer_mode", "mode"), &MultiplayerPeer::set_transfer_mode);
ClassDB::bind_method(D_METHOD("get_transfer_mode"), &MultiplayerPeer::get_transfer_mode);
@@ -41,6 +64,7 @@ void MultiplayerPeer::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_connection_status"), &MultiplayerPeer::get_connection_status);
ClassDB::bind_method(D_METHOD("get_unique_id"), &MultiplayerPeer::get_unique_id);
+ ClassDB::bind_method(D_METHOD("generate_unique_id"), &MultiplayerPeer::generate_unique_id);
ClassDB::bind_method(D_METHOD("set_refuse_new_connections", "enable"), &MultiplayerPeer::set_refuse_new_connections);
ClassDB::bind_method(D_METHOD("is_refusing_new_connections"), &MultiplayerPeer::is_refusing_new_connections);