| 1 | /**************************************************************************/ |
| 2 | /* editor_import_blend_runner.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 "editor_import_blend_runner.h" |
| 32 | |
| 33 | #include "core/io/http_client.h" |
| 34 | #include "editor/editor_node.h" |
| 35 | #include "editor/file_system/editor_file_system.h" |
| 36 | #include "editor/settings/editor_settings.h" |
| 37 | |
| 38 | static constexpr char PYTHON_SCRIPT_RPC[] = R"( |
| 39 | import bpy, sys, threading |
| 40 | from xmlrpc.server import SimpleXMLRPCServer |
| 41 | req = threading.Condition() |
| 42 | res = threading.Condition() |
| 43 | info = None |
| 44 | export_err = None |
| 45 | def xmlrpc_server(): |
| 46 | server = SimpleXMLRPCServer(('127.0.0.1', %d)) |
| 47 | server.register_function(export_gltf) |
| 48 | server.serve_forever() |
| 49 | def export_gltf(opts): |
| 50 | with req: |
| 51 | global info |
| 52 | info = ('export_gltf', opts) |
| 53 | req.notify() |
| 54 | with res: |
| 55 | res.wait() |
| 56 | if export_err: |
| 57 | raise export_err |
| 58 | # Important to return a value to prevent the error 'cannot marshal None unless allow_none is enabled'. |
| 59 | return 'BLENDER_GODOT_EXPORT_SUCCESSFUL' |
| 60 | if bpy.app.version < (3, 0, 0): |
| 61 | print('Blender 3.0 or higher is required.', file=sys.stderr) |
| 62 | threading.Thread(target=xmlrpc_server).start() |
| 63 | while True: |
| 64 | with req: |
| 65 | while info is None: |
| 66 | req.wait() |
| 67 | method, opts = info |
| 68 | if method == 'export_gltf': |
| 69 | try: |
| 70 | export_err = None |
| 71 | bpy.ops.wm.open_mainfile(filepath=opts['path']) |
| 72 | if opts['unpack_all']: |
| 73 | bpy.ops.file.unpack_all(method='USE_LOCAL') |
| 74 | bpy.ops.export_scene.gltf(**opts['gltf_options']) |
| 75 | except Exception as e: |
| 76 | export_err = e |
| 77 | info = None |
| 78 | with res: |
| 79 | res.notify() |
| 80 | )"; |
| 81 | |
| 82 | static constexpr char PYTHON_SCRIPT_DIRECT[] = R"( |
| 83 | import bpy, sys |
| 84 | opts = %s |
| 85 | if bpy.app.version < (3, 0, 0): |
| 86 | print('Blender 3.0 or higher is required.', file=sys.stderr) |
| 87 | bpy.ops.wm.open_mainfile(filepath=opts['path']) |
| 88 | if opts['unpack_all']: |
| 89 | bpy.ops.file.unpack_all(method='USE_LOCAL') |
| 90 | bpy.ops.export_scene.gltf(**opts['gltf_options']) |
| 91 | )"; |
| 92 | |
| 93 | String dict_to_python(const Dictionary &p_dict) { |
| 94 | String entries; |
| 95 | for (const KeyValue<Variant, Variant> &kv : p_dict) { |
| 96 | const String &key = kv.key; |
| 97 | String value; |
| 98 | const Variant &raw_value = kv.value; |
| 99 | |
| 100 | switch (raw_value.get_type()) { |
| 101 | case Variant::Type::BOOL: { |
| 102 | value = raw_value ? "True" : "False"; |
| 103 | break; |
| 104 | } |
| 105 | case Variant::Type::STRING: |
| 106 | case Variant::Type::STRING_NAME: { |
| 107 | value = raw_value; |
| 108 | value = vformat("'%s'", value.c_escape()); |
| 109 | break; |
| 110 | } |
| 111 | case Variant::Type::DICTIONARY: { |
| 112 | value = dict_to_python(raw_value); |
| 113 | break; |
| 114 | } |
| 115 | default: { |
| 116 | ERR_FAIL_V_MSG("", vformat("Unhandled Variant type %s for python dictionary", Variant::get_type_name(raw_value.get_type()))); |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | entries += vformat("'%s': %s,", key, value); |
| 121 | } |
| 122 | return vformat("{%s}", entries); |
| 123 | } |
| 124 | |
| 125 | String dict_to_xmlrpc(const Dictionary &p_dict) { |
| 126 | String members; |
| 127 | for (const KeyValue<Variant, Variant> &kv : p_dict) { |
| 128 | const String &key = kv.key; |
| 129 | String value; |
| 130 | const Variant &raw_value = kv.value; |
| 131 | |
| 132 | switch (raw_value.get_type()) { |
| 133 | case Variant::Type::BOOL: { |
| 134 | value = vformat("<boolean>%d</boolean>", raw_value ? 1 : 0); |
| 135 | break; |
| 136 | } |
| 137 | case Variant::Type::STRING: |
| 138 | case Variant::Type::STRING_NAME: { |
| 139 | value = raw_value; |
| 140 | value = vformat("<string>%s</string>", value.xml_escape()); |
| 141 | break; |
| 142 | } |
| 143 | case Variant::Type::DICTIONARY: { |
| 144 | value = dict_to_xmlrpc(raw_value); |
| 145 | break; |
| 146 | } |
| 147 | default: { |
| 148 | ERR_FAIL_V_MSG("", vformat("Unhandled Variant type %s for XMLRPC", Variant::get_type_name(raw_value.get_type()))); |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | members += vformat("<member><name>%s</name><value>%s</value></member>", key, value); |
| 153 | } |
| 154 | return vformat("<struct>%s</struct>", members); |
| 155 | } |
| 156 | |
| 157 | Error EditorImportBlendRunner::start_blender(const String &p_python_script, bool p_blocking) { |
| 158 | String blender_path = EDITOR_GET("filesystem/import/blender/blender_path"); |
| 159 | |
| 160 | List<String> args; |
| 161 | args.push_back("--background"); |
| 162 | args.push_back("--python-exit-code"); |
| 163 | args.push_back("1"); |
| 164 | args.push_back("--python-expr"); |
| 165 | args.push_back(p_python_script); |
| 166 | |
| 167 | Error err; |
| 168 | String str; |
| 169 | if (p_blocking) { |
| 170 | int exitcode = 0; |
| 171 | err = OS::get_singleton()->execute(blender_path, args, &str, &exitcode, true); |
| 172 | if (exitcode != 0) { |
| 173 | print_error(vformat("Blender import failed: %s.", str)); |
| 174 | return FAILED; |
| 175 | } |
| 176 | } else { |
| 177 | err = OS::get_singleton()->create_process(blender_path, args, &blender_pid); |
| 178 | } |
| 179 | return err; |
| 180 | } |
| 181 | |
| 182 | Error EditorImportBlendRunner::do_import(const Dictionary &p_options) { |
| 183 | if (is_using_rpc()) { |
| 184 | Error err = do_import_rpc(p_options); |
| 185 | if (err != OK) { |
| 186 | // Retry without using RPC (slow, but better than the import failing completely). |
| 187 | if (err == ERR_CONNECTION_ERROR) { |
| 188 | // Disable RPC if the connection could not be established. |
| 189 | print_error(vformat("Failed to connect to Blender via RPC, switching to direct imports of .blend files. Check your proxy and firewall settings, then RPC can be re-enabled by changing the editor setting `filesystem/import/blender/rpc_port` to %d.", rpc_port)); |
| 190 | EditorSettings::get_singleton()->set_manually("filesystem/import/blender/rpc_port", 0); |
| 191 | rpc_port = 0; |
| 192 | } |
| 193 | if (err != ERR_QUERY_FAILED) { |
| 194 | err = do_import_direct(p_options); |
| 195 | } |
| 196 | } |
| 197 | return err; |
| 198 | } else { |
| 199 | return do_import_direct(p_options); |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | HTTPClient::Status EditorImportBlendRunner::connect_blender_rpc(const Ref<HTTPClient> &p_client, int p_timeout_usecs) { |
| 204 | p_client->connect_to_host("127.0.0.1", rpc_port); |
| 205 | HTTPClient::Status status = p_client->get_status(); |
| 206 | |
| 207 | int attempts = 1; |
| 208 | int wait_usecs = 1000; |
| 209 | |
| 210 | bool done = false; |
| 211 | while (!done) { |
| 212 | OS::get_singleton()->delay_usec(wait_usecs); |
| 213 | attempts++; |
| 214 | status = p_client->get_status(); |
| 215 | switch (status) { |
| 216 | case HTTPClient::STATUS_RESOLVING: |
| 217 | case HTTPClient::STATUS_CONNECTING: { |
| 218 | p_client->poll(); |
| 219 | break; |
| 220 | } |
| 221 | case HTTPClient::STATUS_CONNECTED: { |
| 222 | done = true; |
| 223 | break; |
| 224 | } |
| 225 | default: { |
| 226 | if (attempts * wait_usecs < p_timeout_usecs) { |
| 227 | p_client->connect_to_host("127.0.0.1", rpc_port); |
| 228 | } else { |
| 229 | return status; |
| 230 | } |
| 231 | } |
| 232 | } |
| 233 | } |
| 234 | |
| 235 | return status; |
| 236 | } |
| 237 | |
| 238 | Error EditorImportBlendRunner::do_import_rpc(const Dictionary &p_options) { |
| 239 | kill_timer->stop(); |
| 240 | |
| 241 | // Start Blender if not already running. |
| 242 | if (!is_running()) { |
| 243 | // Start an XML RPC server on the given port. |
| 244 | String python = vformat(PYTHON_SCRIPT_RPC, rpc_port); |
| 245 | Error err = start_blender(python, false); |
| 246 | if (err != OK || blender_pid == 0) { |
| 247 | return FAILED; |
| 248 | } |
| 249 | } |
| 250 | |
| 251 | // Convert options to XML body. |
| 252 | String xml_options = dict_to_xmlrpc(p_options); |
| 253 | String xml_body = vformat("<?xml version=\"1.0\"?><methodCall><methodName>export_gltf</methodName><params><param><value>%s</value></param></params></methodCall>", xml_options); |
| 254 | |
| 255 | // Connect to RPC server. |
| 256 | Ref<HTTPClient> client = HTTPClient::create(); |
| 257 | HTTPClient::Status status = connect_blender_rpc(client, 1000000); |
| 258 | if (status != HTTPClient::STATUS_CONNECTED) { |
| 259 | ERR_FAIL_V_MSG(ERR_CONNECTION_ERROR, vformat("Unexpected status during RPC connection: %d", status)); |
| 260 | } |
| 261 | |
| 262 | // Send XML request. |
| 263 | PackedByteArray xml_buffer = xml_body.to_utf8_buffer(); |
| 264 | Error err = client->request(HTTPClient::METHOD_POST, "/", Vector<String>(), xml_buffer.ptr(), xml_buffer.size()); |
| 265 | if (err != OK) { |
| 266 | ERR_FAIL_V_MSG(err, vformat("Unable to send RPC request: %d", err)); |
| 267 | } |
| 268 | |
| 269 | // Wait for response. |
| 270 | bool done = false; |
| 271 | PackedByteArray response; |
| 272 | while (!done) { |
| 273 | status = client->get_status(); |
| 274 | switch (status) { |
| 275 | case HTTPClient::STATUS_REQUESTING: { |
| 276 | client->poll(); |
| 277 | break; |
| 278 | } |
| 279 | case HTTPClient::STATUS_BODY: { |
| 280 | client->poll(); |
| 281 | response.append_array(client->read_response_body_chunk()); |
| 282 | break; |
| 283 | } |
| 284 | case HTTPClient::STATUS_CONNECTED: { |
| 285 | done = true; |
| 286 | break; |
| 287 | } |
| 288 | default: { |
| 289 | ERR_FAIL_V_MSG(ERR_CONNECTION_ERROR, vformat("Unexpected status during RPC response: %d", status)); |
| 290 | } |
| 291 | } |
| 292 | } |
| 293 | |
| 294 | String response_text = "No response from Blender."; |
| 295 | if (response.size() > 0) { |
| 296 | response_text = String::utf8((const char *)response.ptr(), response.size()); |
| 297 | } |
| 298 | |
| 299 | if (client->get_response_code() != HTTPClient::RESPONSE_OK) { |
| 300 | ERR_FAIL_V_MSG(ERR_QUERY_FAILED, vformat("Error received from Blender - status code: %s, error: %s", client->get_response_code(), response_text)); |
| 301 | } else if (response_text.find("BLENDER_GODOT_EXPORT_SUCCESSFUL") < 0) { |
| 302 | // Previous versions of Godot used a Python script where the RPC function did not return |
| 303 | // a value, causing the error 'cannot marshal None unless allow_none is enabled'. |
| 304 | // If an older version of Godot is running and has started Blender with this script, |
| 305 | // we will receive the error, but there's a good chance that the import was successful. |
| 306 | // We are discarding this error to maintain backward compatibility and prevent situations |
| 307 | // where the user needs to close the older version of Godot or kill Blender. |
| 308 | if (response_text.find("cannot marshal None unless allow_none is enabled") < 0) { |
| 309 | String error_message; |
| 310 | if (_extract_error_message_xml(response, error_message)) { |
| 311 | ERR_FAIL_V_MSG(ERR_QUERY_FAILED, vformat("Blender exportation failed: %s", error_message)); |
| 312 | } else { |
| 313 | ERR_FAIL_V_MSG(ERR_QUERY_FAILED, vformat("Blender exportation failed: %s", response_text)); |
| 314 | } |
| 315 | } |
| 316 | } |
| 317 | |
| 318 | return OK; |
| 319 | } |
| 320 | |
| 321 | bool EditorImportBlendRunner::_extract_error_message_xml(const Vector<uint8_t> &p_response_data, String &r_error_message) { |
| 322 | // Based on RPC Xml spec from: https://xmlrpc.com/spec.md |
| 323 | Ref<XMLParser> parser = memnew(XMLParser); |
| 324 | Error err = parser->open_buffer(p_response_data); |
| 325 | if (err) { |
| 326 | return false; |
| 327 | } |
| 328 | |
| 329 | r_error_message = String(); |
| 330 | while (parser->read() == OK) { |
| 331 | if (parser->get_node_type() == XMLParser::NODE_TEXT) { |
| 332 | if (parser->get_node_data().size()) { |
| 333 | if (r_error_message.size()) { |
| 334 | r_error_message += " "; |
| 335 | } |
| 336 | r_error_message += parser->get_node_data().trim_suffix("\n"); |
| 337 | } |
| 338 | } |
| 339 | } |
| 340 | |
| 341 | return r_error_message.size(); |
| 342 | } |
| 343 | |
| 344 | Error EditorImportBlendRunner::do_import_direct(const Dictionary &p_options) { |
| 345 | // Export glTF directly. |
| 346 | String python = vformat(PYTHON_SCRIPT_DIRECT, dict_to_python(p_options)); |
| 347 | Error err = start_blender(python, true); |
| 348 | if (err != OK) { |
| 349 | return err; |
| 350 | } |
| 351 | |
| 352 | return OK; |
| 353 | } |
| 354 | |
| 355 | void EditorImportBlendRunner::_resources_reimported(const PackedStringArray &p_files) { |
| 356 | if (is_running()) { |
| 357 | // After a batch of imports is done, wait a few seconds before trying to kill blender, |
| 358 | // in case of having multiple imports trigger in quick succession. |
| 359 | kill_timer->start(); |
| 360 | } |
| 361 | } |
| 362 | |
| 363 | void EditorImportBlendRunner::_kill_blender() { |
| 364 | kill_timer->stop(); |
| 365 | if (is_running()) { |
| 366 | OS::get_singleton()->kill(blender_pid); |
| 367 | } |
| 368 | blender_pid = 0; |
| 369 | } |
| 370 | |
| 371 | void EditorImportBlendRunner::_notification(int p_what) { |
| 372 | switch (p_what) { |
| 373 | case NOTIFICATION_PREDELETE: { |
| 374 | _kill_blender(); |
| 375 | break; |
| 376 | } |
| 377 | } |
| 378 | } |
| 379 | |
| 380 | EditorImportBlendRunner *EditorImportBlendRunner::singleton = nullptr; |
| 381 | |
| 382 | EditorImportBlendRunner::EditorImportBlendRunner() { |
| 383 | ERR_FAIL_COND_MSG(singleton != nullptr, "EditorImportBlendRunner already created."); |
| 384 | singleton = this; |
| 385 | |
| 386 | rpc_port = EDITOR_GET("filesystem/import/blender/rpc_port"); |
| 387 | |
| 388 | kill_timer = memnew(Timer); |
| 389 | add_child(kill_timer); |
| 390 | kill_timer->set_one_shot(true); |
| 391 | kill_timer->set_wait_time(EDITOR_GET("filesystem/import/blender/rpc_server_uptime")); |
| 392 | kill_timer->connect("timeout", callable_mp(this, &EditorImportBlendRunner::_kill_blender)); |
| 393 | |
| 394 | EditorFileSystem::get_singleton()->connect("resources_reimported", callable_mp(this, &EditorImportBlendRunner::_resources_reimported)); |
| 395 | } |