message_queue.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. /**************************************************************************/
  2. /* message_queue.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "message_queue.h"
  31. #include "core/project_settings.h"
  32. #include "core/script_language.h"
  33. MessageQueue *MessageQueue::singleton = nullptr;
  34. MessageQueue *MessageQueue::get_singleton() {
  35. return singleton;
  36. }
  37. Error MessageQueue::push_call(ObjectID p_id, const StringName &p_method, const Variant **p_args, int p_argcount, bool p_show_error) {
  38. _THREAD_SAFE_METHOD_
  39. int room_needed = sizeof(Message) + sizeof(Variant) * p_argcount;
  40. Buffer &buffer = buffers[write_buffer];
  41. if ((buffer.end + room_needed) > buffer.data.size()) {
  42. if ((buffer.end + room_needed) > max_allowed_buffer_size) {
  43. String type;
  44. if (ObjectDB::get_instance(p_id)) {
  45. type = ObjectDB::get_instance(p_id)->get_class();
  46. }
  47. print_line("Failed method: " + p_method);
  48. statistics();
  49. ERR_FAIL_V_MSG(ERR_OUT_OF_MEMORY, "Message queue out of memory. Try increasing 'memory/limits/message_queue/max_size_mb' in project settings.");
  50. } else {
  51. buffer.data.resize(buffer.end + room_needed);
  52. }
  53. }
  54. Message *msg = memnew_placement(&buffer.data[buffer.end], Message);
  55. msg->args = p_argcount;
  56. msg->instance_id = p_id;
  57. msg->target = p_method;
  58. msg->type = TYPE_CALL;
  59. if (p_show_error) {
  60. msg->type |= FLAG_SHOW_ERROR;
  61. }
  62. buffer.end += sizeof(Message);
  63. for (int i = 0; i < p_argcount; i++) {
  64. Variant *v = memnew_placement(&buffer.data[buffer.end], Variant);
  65. buffer.end += sizeof(Variant);
  66. *v = *p_args[i];
  67. }
  68. return OK;
  69. }
  70. Error MessageQueue::push_call(ObjectID p_id, const StringName &p_method, VARIANT_ARG_DECLARE) {
  71. VARIANT_ARGPTRS;
  72. int argc = 0;
  73. for (int i = 0; i < VARIANT_ARG_MAX; i++) {
  74. if (argptr[i]->get_type() == Variant::NIL) {
  75. break;
  76. }
  77. argc++;
  78. }
  79. return push_call(p_id, p_method, argptr, argc, false);
  80. }
  81. Error MessageQueue::push_set(ObjectID p_id, const StringName &p_prop, const Variant &p_value) {
  82. _THREAD_SAFE_METHOD_
  83. uint8_t room_needed = sizeof(Message) + sizeof(Variant);
  84. Buffer &buffer = buffers[write_buffer];
  85. if ((buffer.end + room_needed) > buffer.data.size()) {
  86. if ((buffer.end + room_needed) > max_allowed_buffer_size) {
  87. String type;
  88. if (ObjectDB::get_instance(p_id)) {
  89. type = ObjectDB::get_instance(p_id)->get_class();
  90. }
  91. print_line("Failed set: " + type + ":" + p_prop + " target ID: " + itos(p_id));
  92. statistics();
  93. ERR_FAIL_V_MSG(ERR_OUT_OF_MEMORY, "Message queue out of memory. Try increasing 'memory/limits/message_queue/max_size_mb' in project settings.");
  94. } else {
  95. buffer.data.resize(buffer.end + room_needed);
  96. }
  97. }
  98. Message *msg = memnew_placement(&buffer.data[buffer.end], Message);
  99. msg->args = 1;
  100. msg->instance_id = p_id;
  101. msg->target = p_prop;
  102. msg->type = TYPE_SET;
  103. buffer.end += sizeof(Message);
  104. Variant *v = memnew_placement(&buffer.data[buffer.end], Variant);
  105. buffer.end += sizeof(Variant);
  106. *v = p_value;
  107. return OK;
  108. }
  109. Error MessageQueue::push_notification(ObjectID p_id, int p_notification) {
  110. _THREAD_SAFE_METHOD_
  111. ERR_FAIL_COND_V(p_notification < 0, ERR_INVALID_PARAMETER);
  112. uint8_t room_needed = sizeof(Message);
  113. Buffer &buffer = buffers[write_buffer];
  114. if ((buffer.end + room_needed) > buffer.data.size()) {
  115. if ((buffer.end + room_needed) > max_allowed_buffer_size) {
  116. String type;
  117. if (ObjectDB::get_instance(p_id)) {
  118. type = ObjectDB::get_instance(p_id)->get_class();
  119. }
  120. print_line("Failed notification: " + itos(p_notification) + " target ID: " + itos(p_id));
  121. statistics();
  122. ERR_FAIL_V_MSG(ERR_OUT_OF_MEMORY, "Message queue out of memory. Try increasing 'memory/limits/message_queue/max_size_mb' in project settings.");
  123. } else {
  124. buffer.data.resize(buffer.end + room_needed);
  125. }
  126. }
  127. Message *msg = memnew_placement(&buffer.data[buffer.end], Message);
  128. msg->type = TYPE_NOTIFICATION;
  129. msg->instance_id = p_id;
  130. //msg->target;
  131. msg->notification = p_notification;
  132. buffer.end += sizeof(Message);
  133. return OK;
  134. }
  135. Error MessageQueue::push_call(Object *p_object, const StringName &p_method, VARIANT_ARG_DECLARE) {
  136. return push_call(p_object->get_instance_id(), p_method, VARIANT_ARG_PASS);
  137. }
  138. Error MessageQueue::push_notification(Object *p_object, int p_notification) {
  139. return push_notification(p_object->get_instance_id(), p_notification);
  140. }
  141. Error MessageQueue::push_set(Object *p_object, const StringName &p_prop, const Variant &p_value) {
  142. return push_set(p_object->get_instance_id(), p_prop, p_value);
  143. }
  144. void MessageQueue::statistics() {
  145. Map<StringName, int> set_count;
  146. Map<int, int> notify_count;
  147. Map<StringName, int> call_count;
  148. int null_count = 0;
  149. Buffer &buffer = buffers[write_buffer];
  150. uint32_t read_pos = 0;
  151. while (read_pos < buffer.end) {
  152. Message *message = (Message *)&buffer.data[read_pos];
  153. Object *target = ObjectDB::get_instance(message->instance_id);
  154. if (target != nullptr) {
  155. switch (message->type & FLAG_MASK) {
  156. case TYPE_CALL: {
  157. if (!call_count.has(message->target)) {
  158. call_count[message->target] = 0;
  159. }
  160. call_count[message->target]++;
  161. } break;
  162. case TYPE_NOTIFICATION: {
  163. if (!notify_count.has(message->notification)) {
  164. notify_count[message->notification] = 0;
  165. }
  166. notify_count[message->notification]++;
  167. } break;
  168. case TYPE_SET: {
  169. if (!set_count.has(message->target)) {
  170. set_count[message->target] = 0;
  171. }
  172. set_count[message->target]++;
  173. } break;
  174. }
  175. } else {
  176. //object was deleted
  177. print_line("Object was deleted while awaiting a callback");
  178. null_count++;
  179. }
  180. read_pos += sizeof(Message);
  181. if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION) {
  182. read_pos += sizeof(Variant) * message->args;
  183. }
  184. }
  185. print_line("TOTAL BYTES: " + itos(buffer.end));
  186. print_line("NULL count: " + itos(null_count));
  187. for (Map<StringName, int>::Element *E = set_count.front(); E; E = E->next()) {
  188. print_line("SET " + E->key() + ": " + itos(E->get()));
  189. }
  190. for (Map<StringName, int>::Element *E = call_count.front(); E; E = E->next()) {
  191. print_line("CALL " + E->key() + ": " + itos(E->get()));
  192. }
  193. for (Map<int, int>::Element *E = notify_count.front(); E; E = E->next()) {
  194. print_line("NOTIFY " + itos(E->key()) + ": " + itos(E->get()));
  195. }
  196. }
  197. int MessageQueue::get_max_buffer_usage() const {
  198. return _buffer_size_monitor.max_size_overall;
  199. }
  200. void MessageQueue::_call_function(Object *p_target, const StringName &p_func, const Variant *p_args, int p_argcount, bool p_show_error) {
  201. const Variant **argptrs = nullptr;
  202. if (p_argcount) {
  203. argptrs = (const Variant **)alloca(sizeof(Variant *) * p_argcount);
  204. for (int i = 0; i < p_argcount; i++) {
  205. argptrs[i] = &p_args[i];
  206. }
  207. }
  208. Variant::CallError ce;
  209. p_target->call(p_func, argptrs, p_argcount, ce);
  210. if (p_show_error && ce.error != Variant::CallError::CALL_OK) {
  211. ERR_PRINT("Error calling deferred method: " + Variant::get_call_error_text(p_target, p_func, argptrs, p_argcount, ce) + ".");
  212. }
  213. }
  214. void MessageQueue::_update_buffer_monitor() {
  215. // The number of flushes is an approximate delay before
  216. // considering shrinking. This is somewhat of a magic number,
  217. // but only acts to prevent excessive oscillations.
  218. if (++_buffer_size_monitor.flush_count == 8192) {
  219. uint32_t max_size = _buffer_size_monitor.max_size;
  220. // Uncomment this define to log message queue sizes and
  221. // auto-shrinking behaviour.
  222. // #define GODOT_DEBUG_MESSAGE_QUEUE_SIZES
  223. #ifdef GODOT_DEBUG_MESSAGE_QUEUE_SIZES
  224. print_line("MessageQueue buffer max size " + itos(max_size) + " bytes.");
  225. #endif
  226. // reset for next time
  227. _buffer_size_monitor.flush_count = 0;
  228. _buffer_size_monitor.max_size = 0;
  229. for (uint32_t n = 0; n < 2; n++) {
  230. uint32_t cap = buffers[n].data.get_capacity();
  231. // Only worry about reducing memory if the capacity is high
  232. // (due to e.g. loading a level or something).
  233. // The shrinking will only take place below 256K, to prevent
  234. // excessive reallocating.
  235. if (cap > (256 * 1024)) {
  236. // Only shrink if we are routinely using a lot less than the capacity.
  237. if ((max_size * 4) < cap) {
  238. buffers[n].data.reserve(cap / 2, true);
  239. #ifdef GODOT_DEBUG_MESSAGE_QUEUE_SIZES
  240. print_line("MessageQueue reducing buffer[" + itos(n) + "] capacity from " + itos(cap) + " bytes to " + itos(cap / 2) + " bytes.");
  241. #endif
  242. }
  243. }
  244. }
  245. }
  246. }
  247. void MessageQueue::flush() {
  248. //using reverse locking strategy
  249. _THREAD_SAFE_LOCK_
  250. if (flushing) {
  251. _THREAD_SAFE_UNLOCK_
  252. ERR_FAIL_MSG("Already flushing"); //already flushing, you did something odd
  253. }
  254. // first flip buffers, in preparation
  255. SWAP(read_buffer, write_buffer);
  256. flushing = true;
  257. _update_buffer_monitor();
  258. _THREAD_SAFE_UNLOCK_
  259. // This loop works by having a read buffer and write buffer.
  260. // While we are reading from one buffer we can be filling another.
  261. // This enables them to be independent, and not require locks per message.
  262. // It also avoids pushing and resizing the write buffer corrupting the read buffer.
  263. // The trade off is that it requires more memory.
  264. // However the peak size of each can be lower, because they do not ADD
  265. // to each other during transit.
  266. while (buffers[read_buffer].data.size()) {
  267. uint32_t read_pos = 0;
  268. Buffer &buffer = buffers[read_buffer];
  269. while (read_pos < buffer.end) {
  270. Message *message = (Message *)&buffer.data[read_pos];
  271. uint32_t advance = sizeof(Message);
  272. if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION) {
  273. advance += sizeof(Variant) * message->args;
  274. }
  275. read_pos += advance;
  276. Object *target = ObjectDB::get_instance(message->instance_id);
  277. if (target != nullptr) {
  278. switch (message->type & FLAG_MASK) {
  279. case TYPE_CALL: {
  280. Variant *args = (Variant *)(message + 1);
  281. // messages don't expect a return value
  282. _call_function(target, message->target, args, message->args, message->type & FLAG_SHOW_ERROR);
  283. } break;
  284. case TYPE_NOTIFICATION: {
  285. // messages don't expect a return value
  286. target->notification(message->notification);
  287. } break;
  288. case TYPE_SET: {
  289. Variant *arg = (Variant *)(message + 1);
  290. // messages don't expect a return value
  291. target->set(message->target, *arg);
  292. } break;
  293. }
  294. }
  295. if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION) {
  296. Variant *args = (Variant *)(message + 1);
  297. for (int i = 0; i < message->args; i++) {
  298. args[i].~Variant();
  299. }
  300. }
  301. message->~Message();
  302. } // while going through buffer
  303. buffer.end = 0; // reset buffer
  304. uint32_t buffer_data_size = buffer.data.size();
  305. buffer.data.clear();
  306. _THREAD_SAFE_LOCK_
  307. // keep track of the maximum used size, so we can downsize buffers when appropriate
  308. _buffer_size_monitor.max_size = MAX(buffer_data_size, _buffer_size_monitor.max_size);
  309. _buffer_size_monitor.max_size_overall = MAX(buffer_data_size, _buffer_size_monitor.max_size_overall);
  310. // flip buffers, this is the only part that requires a lock
  311. SWAP(read_buffer, write_buffer);
  312. _THREAD_SAFE_UNLOCK_
  313. } // while read buffer not empty
  314. _THREAD_SAFE_LOCK_
  315. flushing = false;
  316. _THREAD_SAFE_UNLOCK_
  317. }
  318. bool MessageQueue::is_flushing() const {
  319. return flushing;
  320. }
  321. MessageQueue::MessageQueue() {
  322. ERR_FAIL_COND_MSG(singleton != nullptr, "A MessageQueue singleton already exists.");
  323. singleton = this;
  324. flushing = false;
  325. max_allowed_buffer_size = GLOBAL_DEF_RST("memory/limits/message_queue/max_size_mb", 32);
  326. ProjectSettings::get_singleton()->set_custom_property_info("memory/limits/message_queue/max_size_mb", PropertyInfo(Variant::INT, "memory/limits/message_queue/max_size_mb", PROPERTY_HINT_RANGE, "4,512,1,or_greater"));
  327. max_allowed_buffer_size *= 1024 * 1024;
  328. }
  329. MessageQueue::~MessageQueue() {
  330. for (int which = 0; which < 2; which++) {
  331. Buffer &buffer = buffers[which];
  332. uint32_t read_pos = 0;
  333. while (read_pos < buffer.end) {
  334. Message *message = (Message *)&buffer.data[read_pos];
  335. Variant *args = (Variant *)(message + 1);
  336. int argc = message->args;
  337. if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION) {
  338. for (int i = 0; i < argc; i++) {
  339. args[i].~Variant();
  340. }
  341. }
  342. message->~Message();
  343. read_pos += sizeof(Message);
  344. if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION) {
  345. read_pos += sizeof(Variant) * message->args;
  346. }
  347. }
  348. } // for which
  349. singleton = nullptr;
  350. }