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