snapshot_collector.cpp 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. /**************************************************************************/
  2. /* snapshot_collector.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 "snapshot_collector.h"
  31. #include "core/core_bind.h"
  32. #include "core/debugger/engine_debugger.h"
  33. #include "core/io/compression.h"
  34. #include "core/os/time.h"
  35. #include "core/version.h"
  36. #include "scene/main/node.h"
  37. #include "scene/main/window.h"
  38. void SnapshotCollector::initialize() {
  39. pending_snapshots.clear();
  40. EngineDebugger::register_message_capture("snapshot", EngineDebugger::Capture(nullptr, SnapshotCollector::parse_message));
  41. }
  42. void SnapshotCollector::deinitialize() {
  43. EngineDebugger::unregister_message_capture("snapshot");
  44. pending_snapshots.clear();
  45. }
  46. void SnapshotCollector::snapshot_objects(Array *p_arr, Dictionary &p_snapshot_context) {
  47. print_verbose("Starting to snapshot");
  48. p_arr->clear();
  49. // Gather all ObjectIDs first. The ObjectDB will be locked in debug_objects, so we can't serialize until it exits.
  50. // In rare cases, the object may be deleted as the snapshot is taken. So, we store the object's class name to give users a clue about what went wrong.
  51. LocalVector<Pair<ObjectID, StringName>> debugger_object_ids;
  52. debugger_object_ids.reserve(ObjectDB::get_object_count());
  53. ObjectDB::debug_objects(
  54. [](Object *p_obj, void *p_user_data) {
  55. LocalVector<Pair<ObjectID, StringName>> *debugger_object_ids_ptr = (LocalVector<Pair<ObjectID, StringName>> *)p_user_data;
  56. debugger_object_ids_ptr->push_back(Pair<ObjectID, StringName>(p_obj->get_instance_id(), p_obj->get_class_name()));
  57. },
  58. (void *)&debugger_object_ids);
  59. // Get SnapshotDataTransportObject from ObjectID list now that DB is unlocked.
  60. LocalVector<SnapshotDataTransportObject> debugger_objects;
  61. debugger_objects.reserve(debugger_object_ids.size());
  62. for (Pair<ObjectID, StringName> ids : debugger_object_ids) {
  63. ObjectID oid = ids.first;
  64. Object *obj = ObjectDB::get_instance(oid);
  65. if (unlikely(obj == nullptr)) {
  66. print_verbose(vformat("Object of class '%s' with ID %ud was found to be deleted after ObjectDB was snapshotted.", ids.second, (uint64_t)oid));
  67. continue;
  68. }
  69. if (ids.second == SNAME("EditorInterface")) {
  70. // The EditorInterface + EditorNode is _kind of_ constructed in a debug game, but many properties are null
  71. // We can prevent it from being constructed, but that would break other projects so better to just skip it.
  72. continue;
  73. }
  74. // This is the same way objects in the remote scene tree are serialized,
  75. // but here we add a few extra properties via the extra_debug_data dictionary.
  76. SnapshotDataTransportObject debug_data(obj);
  77. // If we're RefCounted, send over our RefCount too. Could add code here to add a few other interesting properties.
  78. RefCounted *ref = Object::cast_to<RefCounted>(obj);
  79. if (ref) {
  80. debug_data.extra_debug_data["ref_count"] = ref->get_reference_count();
  81. }
  82. Node *node = Object::cast_to<Node>(obj);
  83. if (node) {
  84. debug_data.extra_debug_data["node_name"] = node->get_name();
  85. if (node->get_parent() != nullptr) {
  86. debug_data.extra_debug_data["node_parent"] = node->get_parent()->get_instance_id();
  87. }
  88. debug_data.extra_debug_data["node_is_scene_root"] = SceneTree::get_singleton()->get_root() == node;
  89. Array children;
  90. for (int i = 0; i < node->get_child_count(); i++) {
  91. children.push_back(node->get_child(i)->get_instance_id());
  92. }
  93. debug_data.extra_debug_data["node_children"] = children;
  94. }
  95. debugger_objects.push_back(debug_data);
  96. }
  97. // Add a header to the snapshot with general data about the state of the game, not tied to any particular object.
  98. p_snapshot_context["mem_usage"] = Memory::get_mem_usage();
  99. p_snapshot_context["mem_max_usage"] = Memory::get_mem_max_usage();
  100. p_snapshot_context["timestamp"] = Time::get_singleton()->get_unix_time_from_system();
  101. p_snapshot_context["game_version"] = get_godot_version_string();
  102. p_arr->push_back(p_snapshot_context);
  103. for (SnapshotDataTransportObject &debug_data : debugger_objects) {
  104. debug_data.serialize(*p_arr);
  105. p_arr->push_back(debug_data.extra_debug_data);
  106. }
  107. print_verbose("Snapshot size: " + String::num_uint64(p_arr->size()));
  108. }
  109. Error SnapshotCollector::parse_message(void *p_user, const String &p_msg, const Array &p_args, bool &r_captured) {
  110. r_captured = true;
  111. if (p_msg == "request_prepare_snapshot") {
  112. int request_id = p_args[0];
  113. Dictionary snapshot_context;
  114. snapshot_context["editor_version"] = (String)p_args[1];
  115. Array objects;
  116. snapshot_objects(&objects, snapshot_context);
  117. // Debugger networking has a limit on both how many objects can be queued to send and how
  118. // many bytes can be queued to send. Serializing to a string means we never hit the object
  119. // limit, and only have to deal with the byte limit.
  120. // Compress the snapshot in the game client to make sending the snapshot from game to editor a little faster.
  121. CoreBind::Marshalls *m = CoreBind::Marshalls::get_singleton();
  122. Vector<uint8_t> objs_buffer = m->base64_to_raw(m->variant_to_base64(objects));
  123. Vector<uint8_t> objs_buffer_compressed;
  124. objs_buffer_compressed.resize(objs_buffer.size());
  125. int new_size = Compression::compress(objs_buffer_compressed.ptrw(), objs_buffer.ptrw(), objs_buffer.size(), Compression::MODE_DEFLATE);
  126. objs_buffer_compressed.resize(new_size);
  127. pending_snapshots[request_id] = objs_buffer_compressed;
  128. // Tell the editor how long the snapshot is.
  129. Array resp = { request_id, pending_snapshots[request_id].size() };
  130. EngineDebugger::get_singleton()->send_message("snapshot:snapshot_prepared", resp);
  131. } else if (p_msg == "request_snapshot_chunk") {
  132. int request_id = p_args[0];
  133. int begin = p_args[1];
  134. int end = p_args[2];
  135. Array resp = { request_id, pending_snapshots[request_id].slice(begin, end) };
  136. EngineDebugger::get_singleton()->send_message("snapshot:snapshot_chunk", resp);
  137. // If we sent the last part of the string, delete it locally.
  138. if (end >= pending_snapshots[request_id].size()) {
  139. pending_snapshots.erase(request_id);
  140. }
  141. } else {
  142. r_captured = false;
  143. }
  144. return OK;
  145. }
  146. String SnapshotCollector::get_godot_version_string() {
  147. String hash = String(GODOT_VERSION_HASH);
  148. if (hash.length() != 0) {
  149. hash = " " + vformat("[%s]", hash.left(9));
  150. }
  151. return "v" GODOT_VERSION_FULL_BUILD + hash;
  152. }