custom_godot_servers.rst 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. .. _doc_custom_godot_servers:
  2. Custom Godot servers
  3. ====================
  4. Introduction
  5. ------------
  6. Godot implements multi-threading as servers. Servers are daemons which
  7. manage data, process it, and push the result. Servers implement the
  8. mediator pattern which interprets resource ID and process data for the
  9. engine and other modules. In addition, the server claims ownership for
  10. its RID allocations.
  11. This guide assumes the reader knows how to create C++ modules and Godot
  12. data types. If not, refer to :ref:`doc_custom_modules_in_c++`.
  13. References
  14. ~~~~~~~~~~~
  15. - `Why does Godot use servers and RIDs? <https://godotengine.org/article/why-does-godot-use-servers-and-rids>`__
  16. - `Singleton pattern <https://en.wikipedia.org/wiki/Singleton_pattern>`__
  17. - `Mediator pattern <https://en.wikipedia.org/wiki/Mediator_pattern>`__
  18. What for?
  19. ---------
  20. - Adding artificial intelligence.
  21. - Adding custom asynchronous threads.
  22. - Adding support for a new input device.
  23. - Adding writing threads.
  24. - Adding a custom VoIP protocol.
  25. - And more...
  26. Creating a Godot server
  27. -----------------------
  28. At minimum, a server must have a static instance, a sleep timer, a thread loop,
  29. an initialization state and a cleanup procedure.
  30. .. code-block:: cpp
  31. #ifndef HILBERT_HOTEL_H
  32. #define HILBERT_HOTEL_H
  33. #include "core/object/object.h"
  34. #include "core/os/thread.h"
  35. #include "core/os/mutex.h"
  36. #include "core/templates/list.h"
  37. #include "core/templates/rid.h"
  38. #include "core/templates/set.h"
  39. #include "core/variant/variant.h"
  40. class HilbertHotel : public Object {
  41. GDCLASS(HilbertHotel, Object);
  42. static HilbertHotel *singleton;
  43. static void thread_func(void *p_udata);
  44. private:
  45. bool thread_exited;
  46. mutable bool exit_thread;
  47. Thread *thread;
  48. Mutex *mutex;
  49. public:
  50. static HilbertHotel *get_singleton();
  51. Error init();
  52. void lock();
  53. void unlock();
  54. void finish();
  55. protected:
  56. static void _bind_methods();
  57. private:
  58. uint64_t counter;
  59. RID_Owner<InfiniteBus> bus_owner;
  60. // https://github.com/godotengine/godot/blob/master/core/templates/rid.h
  61. Set<RID> buses;
  62. void _emit_occupy_room(uint64_t room, RID rid);
  63. public:
  64. RID create_bus();
  65. Variant get_bus_info(RID id);
  66. bool empty();
  67. bool delete_bus(RID id);
  68. void clear();
  69. void register_rooms();
  70. HilbertHotel();
  71. };
  72. #endif
  73. .. code-block:: cpp
  74. #include "hilbert_hotel.h"
  75. #include "core/variant/dictionary.h"
  76. #include "core/os/os.h"
  77. #include "prime_225.h"
  78. void HilbertHotel::thread_func(void *p_udata) {
  79. HilbertHotel *ac = (HilbertHotel *) p_udata;
  80. uint64_t msdelay = 1000;
  81. while (!ac->exit_thread) {
  82. if (!ac->empty()) {
  83. ac->lock();
  84. ac->register_rooms();
  85. ac->unlock();
  86. }
  87. OS::get_singleton()->delay_usec(msdelay * 1000);
  88. }
  89. }
  90. Error HilbertHotel::init() {
  91. thread_exited = false;
  92. counter = 0;
  93. mutex = Mutex::create();
  94. thread = Thread::create(HilbertHotel::thread_func, this);
  95. return OK;
  96. }
  97. HilbertHotel *HilbertHotel::singleton = NULL;
  98. HilbertHotel *HilbertHotel::get_singleton() {
  99. return singleton;
  100. }
  101. void HilbertHotel::register_rooms() {
  102. for (Set<RID>::Element *e = buses.front(); e; e = e->next()) {
  103. auto bus = bus_owner.getornull(e->get());
  104. if (bus) {
  105. uint64_t room = bus->next_room();
  106. _emit_occupy_room(room, bus->get_self());
  107. }
  108. }
  109. }
  110. void HilbertHotel::unlock() {
  111. if (!thread || !mutex) {
  112. return;
  113. }
  114. mutex->unlock();
  115. }
  116. void HilbertHotel::lock() {
  117. if (!thread || !mutex) {
  118. return;
  119. }
  120. mutex->lock();
  121. }
  122. void HilbertHotel::_emit_occupy_room(uint64_t room, RID rid) {
  123. _HilbertHotel::get_singleton()->_occupy_room(room, rid);
  124. }
  125. Variant HilbertHotel::get_bus_info(RID id) {
  126. InfiniteBus *bus = bus_owner.getornull(id);
  127. if (bus) {
  128. Dictionary d;
  129. d["prime"] = bus->get_bus_num();
  130. d["current_room"] = bus->get_current_room();
  131. return d;
  132. }
  133. return Variant();
  134. }
  135. void HilbertHotel::finish() {
  136. if (!thread) {
  137. return;
  138. }
  139. exit_thread = true;
  140. Thread::wait_to_finish(thread);
  141. memdelete(thread);
  142. if (mutex) {
  143. memdelete(mutex);
  144. }
  145. thread = NULL;
  146. }
  147. RID HilbertHotel::create_bus() {
  148. lock();
  149. InfiniteBus *ptr = memnew(InfiniteBus(PRIME[counter++]));
  150. RID ret = bus_owner.make_rid(ptr);
  151. ptr->set_self(ret);
  152. buses.insert(ret);
  153. unlock();
  154. return ret;
  155. }
  156. // https://github.com/godotengine/godot/blob/master/core/templates/rid.h
  157. bool HilbertHotel::delete_bus(RID id) {
  158. if (bus_owner.owns(id)) {
  159. lock();
  160. InfiniteBus *b = bus_owner.get(id);
  161. bus_owner.free(id);
  162. buses.erase(id);
  163. memdelete(b);
  164. unlock();
  165. return true;
  166. }
  167. return false;
  168. }
  169. void HilbertHotel::clear() {
  170. for (Set<RID>::Element *e = buses.front(); e; e = e->next()) {
  171. delete_bus(e->get());
  172. }
  173. }
  174. bool HilbertHotel::empty() {
  175. return buses.size() <= 0;
  176. }
  177. void HilbertHotel::_bind_methods() {
  178. }
  179. HilbertHotel::HilbertHotel() {
  180. singleton = this;
  181. }
  182. .. code-block:: cpp
  183. /* prime_225.h */
  184. const uint64_t PRIME[225] = {
  185. 2,3,5,7,11,13,17,19,23,
  186. 29,31,37,41,43,47,53,59,61,
  187. 67,71,73,79,83,89,97,101,103,
  188. 107,109,113,127,131,137,139,149,151,
  189. 157,163,167,173,179,181,191,193,197,
  190. 199,211,223,227,229,233,239,241,251,
  191. 257,263,269,271,277,281,283,293,307,
  192. 311,313,317,331,337,347,349,353,359,
  193. 367,373,379,383,389,397,401,409,419,
  194. 421,431,433,439,443,449,457,461,463,
  195. 467,479,487,491,499,503,509,521,523,
  196. 541,547,557,563,569,571,577,587,593,
  197. 599,601,607,613,617,619,631,641,643,
  198. 647,653,659,661,673,677,683,691,701,
  199. 709,719,727,733,739,743,751,757,761,
  200. 769,773,787,797,809,811,821,823,827,
  201. 829,839,853,857,859,863,877,881,883,
  202. 887,907,911,919,929,937,941,947,953,
  203. 967,971,977,983,991,997,1009,1013,1019,
  204. 1021,1031,1033,1039,1049,1051,1061,1063,1069,
  205. 1087,1091,1093,1097,1103,1109,1117,1123,1129,
  206. 1151,1153,1163,1171,1181,1187,1193,1201,1213,
  207. 1217,1223,1229,1231,1237,1249,1259,1277,1279,
  208. 1283,1289,1291,1297,1301,1303,1307,1319,1321,
  209. 1327,1361,1367,1373,1381,1399,1409,1423,1427
  210. };
  211. Custom managed resource data
  212. ----------------------------
  213. Godot servers implement a mediator pattern. All data types inherit ``RID_Data``.
  214. ``RID_Owner<MyRID_Data>`` owns the object when ``make_rid`` is called. During debug mode only,
  215. RID_Owner maintains a list of RIDs. In practice, RIDs are similar to writing
  216. object-oriented C code.
  217. .. code-block:: cpp
  218. class InfiniteBus : public RID_Data {
  219. RID self;
  220. private:
  221. uint64_t prime_num;
  222. uint64_t num;
  223. public:
  224. uint64_t next_room() {
  225. return prime_num * num++;
  226. }
  227. uint64_t get_bus_num() const {
  228. return prime_num;
  229. }
  230. uint64_t get_current_room() const {
  231. return prime_num * num;
  232. }
  233. _FORCE_INLINE_ void set_self(const RID &p_self) {
  234. self = p_self;
  235. }
  236. _FORCE_INLINE_ RID get_self() const {
  237. return self;
  238. }
  239. InfiniteBus(uint64_t prime) : prime_num(prime), num(1) {};
  240. ~InfiniteBus() {};
  241. }
  242. References
  243. ~~~~~~~~~~~
  244. - :ref:`RID<class_rid>`
  245. - `core/templates/rid.h <https://github.com/godotengine/godot/blob/master/core/templates/rid.h>`__
  246. Registering the class in GDScript
  247. ---------------------------------
  248. Servers are allocated in ``register_types.cpp``. The constructor sets the static
  249. instance and ``init()`` creates the managed thread; ``unregister_types.cpp``
  250. cleans up the server.
  251. Since a Godot server class creates an instance and binds it to a static singleton,
  252. binding the class might not reference the correct instance. Therefore, a dummy
  253. class must be created to reference the proper Godot server.
  254. In ``register_server_types()``, ``Engine::get_singleton()->add_singleton``
  255. is used to register the dummy class in GDScript.
  256. .. code-block:: cpp
  257. /* register_types.cpp */
  258. #include "register_types.h"
  259. #include "core/object/class_db.h"
  260. #include "core/config/engine.h"
  261. #include "hilbert_hotel.h"
  262. static HilbertHotel *hilbert_hotel = NULL;
  263. static _HilbertHotel *_hilbert_hotel = NULL;
  264. void register_hilbert_hotel_types() {
  265. hilbert_hotel = memnew(HilbertHotel);
  266. hilbert_hotel->init();
  267. _hilbert_hotel = memnew(_HilbertHotel);
  268. ClassDB::register_class<_HilbertHotel>();
  269. Engine::get_singleton()->add_singleton(Engine::Singleton("HilbertHotel", _HilbertHotel::get_singleton()));
  270. }
  271. void unregister_hilbert_hotel_types() {
  272. if (hilbert_hotel) {
  273. hilbert_hotel->finish();
  274. memdelete(hilbert_hotel);
  275. }
  276. if (_hilbert_hotel) {
  277. memdelete(_hilbert_hotel);
  278. }
  279. }
  280. .. code-block:: cpp
  281. /* register_types.h */
  282. /* Yes, the word in the middle must be the same as the module folder name */
  283. void register_hilbert_hotel_types();
  284. void unregister_hilbert_hotel_types();
  285. - `servers/register_server_types.cpp <https://github.com/godotengine/godot/blob/master/servers/register_server_types.cpp>`__
  286. Bind methods
  287. ~~~~~~~~~~~~
  288. The dummy class binds singleton methods to GDScript. In most cases, the dummy class methods wraps around.
  289. .. code-block:: cpp
  290. Variant _HilbertHotel::get_bus_info(RID id) {
  291. return HilbertHotel::get_singleton()->get_bus_info(id);
  292. }
  293. Binding Signals
  294. It is possible to emit signals to GDScript by calling the GDScript dummy object.
  295. .. code-block:: cpp
  296. void HilbertHotel::_emit_occupy_room(uint64_t room, RID rid) {
  297. _HilbertHotel::get_singleton()->_occupy_room(room, rid);
  298. }
  299. .. code-block:: cpp
  300. class _HilbertHotel : public Object {
  301. GDCLASS(_HilbertHotel, Object);
  302. friend class HilbertHotel;
  303. static _HilbertHotel *singleton;
  304. protected:
  305. static void _bind_methods();
  306. private:
  307. void _occupy_room(int room_number, RID bus);
  308. public:
  309. RID create_bus();
  310. void connect_signals();
  311. bool delete_bus(RID id);
  312. static _HilbertHotel *get_singleton();
  313. Variant get_bus_info(RID id);
  314. _HilbertHotel();
  315. ~_HilbertHotel();
  316. };
  317. #endif
  318. .. code-block:: cpp
  319. _HilbertHotel *_HilbertHotel::singleton = NULL;
  320. _HilbertHotel *_HilbertHotel::get_singleton() { return singleton; }
  321. RID _HilbertHotel::create_bus() {
  322. return HilbertHotel::get_singleton()->create_bus();
  323. }
  324. bool _HilbertHotel::delete_bus(RID rid) {
  325. return HilbertHotel::get_singleton()->delete_bus(rid);
  326. }
  327. void _HilbertHotel::_occupy_room(int room_number, RID bus) {
  328. emit_signal("occupy_room", room_number, bus);
  329. }
  330. Variant _HilbertHotel::get_bus_info(RID id) {
  331. return HilbertHotel::get_singleton()->get_bus_info(id);
  332. }
  333. void _HilbertHotel::_bind_methods() {
  334. ClassDB::bind_method(D_METHOD("get_bus_info", "r_id"), &_HilbertHotel::get_bus_info);
  335. ClassDB::bind_method(D_METHOD("create_bus"), &_HilbertHotel::create_bus);
  336. ClassDB::bind_method(D_METHOD("delete_bus"), &_HilbertHotel::delete_bus);
  337. ADD_SIGNAL(MethodInfo("occupy_room", PropertyInfo(Variant::INT, "room_number"), PropertyInfo(Variant::_RID, "r_id")));
  338. }
  339. void _HilbertHotel::connect_signals() {
  340. HilbertHotel::get_singleton()->connect("occupy_room", _HilbertHotel::get_singleton(), "_occupy_room");
  341. }
  342. _HilbertHotel::_HilbertHotel() {
  343. singleton = this;
  344. }
  345. _HilbertHotel::~_HilbertHotel() {
  346. }
  347. MessageQueue
  348. ------------
  349. In order to send commands into SceneTree, MessageQueue is a thread-safe buffer
  350. to queue set and call methods for other threads. To queue a command, obtain
  351. the target object RID and use either ``push_call``, ``push_set``, or ``push_notification``
  352. to execute the desired behavior. The queue will be flushed whenever either
  353. ``SceneTree::idle`` or ``SceneTree::iteration`` is executed.
  354. References:
  355. ~~~~~~~~~~~
  356. - `core/object/message_queue.cpp <https://github.com/godotengine/godot/blob/master/core/object/message_queue.cpp>`__
  357. Summing it up
  358. -------------
  359. Here is the GDScript sample code:
  360. ::
  361. extends Node
  362. func _ready():
  363. print("Start debugging")
  364. HilbertHotel.connect("occupy_room", self, "_print_occupy_room")
  365. var rid = HilbertHotel.create_bus()
  366. OS.delay_msec(2000)
  367. HilbertHotel.create_bus()
  368. OS.delay_msec(2000)
  369. HilbertHotel.create_bus()
  370. OS.delay_msec(2000)
  371. print(HilbertHotel.get_bus_info(rid))
  372. HilbertHotel.delete_bus(rid)
  373. print("Ready done")
  374. func _print_occupy_room(room_number, r_id):
  375. print("Room number: " + str(room_number) + ", RID: " + str(r_id))
  376. print(HilbertHotel.get_bus_info(r_id))
  377. Notes
  378. ~~~~~
  379. - The actual `Hilbert Hotel <https://en.wikipedia.org/wiki/Hilbert%27s_paradox_of_the_Grand_Hotel>`__ is impossible.
  380. - Connecting signal example code is pretty hacky.