diff options
32 files changed, 976 insertions, 155 deletions
diff --git a/core/global_constants.cpp b/core/global_constants.cpp index fb90403226..671b3c545b 100644 --- a/core/global_constants.cpp +++ b/core/global_constants.cpp @@ -425,6 +425,16 @@ void register_global_constants() { BIND_GLOBAL_ENUM_CONSTANT(JOY_DS_X); BIND_GLOBAL_ENUM_CONSTANT(JOY_DS_Y); + BIND_GLOBAL_ENUM_CONSTANT(JOY_VR_GRIP); + BIND_GLOBAL_ENUM_CONSTANT(JOY_VR_PAD); + BIND_GLOBAL_ENUM_CONSTANT(JOY_VR_TRIGGER); + + BIND_GLOBAL_ENUM_CONSTANT(JOY_OCULUS_AX); + BIND_GLOBAL_ENUM_CONSTANT(JOY_OCULUS_BY); + BIND_GLOBAL_ENUM_CONSTANT(JOY_OCULUS_MENU); + + BIND_GLOBAL_ENUM_CONSTANT(JOY_OPENVR_MENU); + BIND_GLOBAL_ENUM_CONSTANT(JOY_SELECT); BIND_GLOBAL_ENUM_CONSTANT(JOY_START); BIND_GLOBAL_ENUM_CONSTANT(JOY_DPAD_UP); @@ -459,6 +469,12 @@ void register_global_constants() { BIND_GLOBAL_ENUM_CONSTANT(JOY_ANALOG_L2); BIND_GLOBAL_ENUM_CONSTANT(JOY_ANALOG_R2); + BIND_GLOBAL_ENUM_CONSTANT(JOY_VR_ANALOG_TRIGGER); + BIND_GLOBAL_ENUM_CONSTANT(JOY_VR_ANALOG_GRIP); + + BIND_GLOBAL_ENUM_CONSTANT(JOY_OPENVR_TOUCHPADX); + BIND_GLOBAL_ENUM_CONSTANT(JOY_OPENVR_TOUCHPADY); + // midi BIND_GLOBAL_ENUM_CONSTANT(MIDI_MESSAGE_NOTE_OFF); BIND_GLOBAL_ENUM_CONSTANT(MIDI_MESSAGE_NOTE_ON); diff --git a/core/math/a_star.cpp b/core/math/a_star.cpp index 3d71e66f80..0b6e9ae929 100644 --- a/core/math/a_star.cpp +++ b/core/math/a_star.cpp @@ -99,14 +99,22 @@ void AStar::remove_point(int p_id) { Point *p = points[p_id]; - Map<int, Point *>::Element *PE = points.front(); - while (PE) { - for (Set<Point *>::Element *E = PE->get()->neighbours.front(); E; E = E->next()) { - Segment s(p_id, E->get()->id); - segments.erase(s); - E->get()->neighbours.erase(p); - } - PE = PE->next(); + for (Set<Point *>::Element *E = p->neighbours.front(); E; E = E->next()) { + + Segment s(p_id, E->get()->id); + segments.erase(s); + + E->get()->neighbours.erase(p); + E->get()->unlinked_neighbours.erase(p); + } + + for (Set<Point *>::Element *E = p->unlinked_neighbours.front(); E; E = E->next()) { + + Segment s(p_id, E->get()->id); + segments.erase(s); + + E->get()->neighbours.erase(p); + E->get()->unlinked_neighbours.erase(p); } memdelete(p); @@ -125,6 +133,8 @@ void AStar::connect_points(int p_id, int p_with_id, bool bidirectional) { if (bidirectional) b->neighbours.insert(a); + else + b->unlinked_neighbours.insert(a); Segment s(p_id, p_with_id); if (s.from == p_id) { @@ -147,7 +157,9 @@ void AStar::disconnect_points(int p_id, int p_with_id) { Point *a = points[p_id]; Point *b = points[p_with_id]; a->neighbours.erase(b); + a->unlinked_neighbours.erase(b); b->neighbours.erase(a); + b->unlinked_neighbours.erase(a); } bool AStar::has_point(int p_id) const { diff --git a/core/math/a_star.h b/core/math/a_star.h index fac8a9d312..ba35d929b3 100644 --- a/core/math/a_star.h +++ b/core/math/a_star.h @@ -54,6 +54,7 @@ class AStar : public Reference { bool enabled; Set<Point *> neighbours; + Set<Point *> unlinked_neighbours; // Used for pathfinding Point *prev_point; diff --git a/core/os/input_event.h b/core/os/input_event.h index 7a9a1f71c3..2eb321f134 100644 --- a/core/os/input_event.h +++ b/core/os/input_event.h @@ -117,6 +117,16 @@ enum JoystickList { JOY_WII_MINUS = JOY_BUTTON_10, JOY_WII_PLUS = JOY_BUTTON_11, + JOY_VR_GRIP = JOY_BUTTON_2, + JOY_VR_PAD = JOY_BUTTON_14, + JOY_VR_TRIGGER = JOY_BUTTON_15, + + JOY_OCULUS_AX = JOY_BUTTON_7, + JOY_OCULUS_BY = JOY_BUTTON_1, + JOY_OCULUS_MENU = JOY_BUTTON_3, + + JOY_OPENVR_MENU = JOY_BUTTON_1, + // end of history JOY_AXIS_0 = 0, @@ -139,6 +149,12 @@ enum JoystickList { JOY_ANALOG_L2 = JOY_AXIS_6, JOY_ANALOG_R2 = JOY_AXIS_7, + + JOY_VR_ANALOG_TRIGGER = JOY_AXIS_2, + JOY_VR_ANALOG_GRIP = JOY_AXIS_4, + + JOY_OPENVR_TOUCHPADX = JOY_AXIS_0, + JOY_OPENVR_TOUCHPADY = JOY_AXIS_1, }; enum MidiMessageList { diff --git a/doc/classes/@GlobalScope.xml b/doc/classes/@GlobalScope.xml index 760287e1b8..eb612191e7 100644 --- a/doc/classes/@GlobalScope.xml +++ b/doc/classes/@GlobalScope.xml @@ -1003,6 +1003,27 @@ <constant name="JOY_DS_Y" value="2" enum="JoystickList"> DualShock controller Y button </constant> + <constant name="JOY_VR_GRIP" value="2" enum="JoystickList"> + Grip (side) buttons on a VR controller + </constant> + <constant name="JOY_VR_PAD" value="14" enum="JoystickList"> + Push down on the touchpad or main joystick on a VR controller + </constant> + <constant name="JOY_VR_TRIGGER" value="15" enum="JoystickList"> + Trigger on a VR controller + </constant> + <constant name="JOY_OCULUS_AX" value="7" enum="JoystickList"> + A button on the right Oculus Touch controller, X button on the left controller (also when used in OpenVR) + </constant> + <constant name="JOY_OCULUS_BY" value="1" enum="JoystickList"> + B button on the right Oculus Touch controller, Y button on the left controller (also when used in OpenVR) + </constant> + <constant name="JOY_OCULUS_MENU" value="3" enum="JoystickList"> + Menu button on either Oculus Touch controller. + </constant> + <constant name="JOY_OPENVR_MENU" value="1" enum="JoystickList"> + Menu button in OpenVR (Except when Oculus Touch controllers are used) + </constant> <constant name="JOY_SELECT" value="10" enum="JoystickList"> Joypad Button Select </constant> @@ -1085,6 +1106,18 @@ <constant name="JOY_ANALOG_R2" value="7" enum="JoystickList"> Joypad Right Analog Trigger </constant> + <constant name="JOY_VR_ANALOG_TRIGGER" value="2" enum="JoystickList"> + VR Controller Analog Trigger + </constant> + <constant name="JOY_VR_ANALOG_GRIP" value="4" enum="JoystickList"> + VR Controller Analog Grip (side buttons) + </constant> + <constant name="JOY_OPENVR_TOUCHPADX" value="0" enum="JoystickList"> + OpenVR touchpad X axis (Joystick axis on Oculus Touch and Windows MR controllers) + </constant> + <constant name="JOY_OPENVR_TOUCHPADY" value="1" enum="JoystickList"> + OpenVR touchpad Y axis (Joystick axis on Oculus Touch and Windows MR controllers) + </constant> <constant name="MIDI_MESSAGE_NOTE_OFF" value="8" enum="MidiMessageList"> </constant> <constant name="MIDI_MESSAGE_NOTE_ON" value="9" enum="MidiMessageList"> diff --git a/doc/classes/CPUParticles.xml b/doc/classes/CPUParticles.xml index 599c067328..5458a87a9e 100644 --- a/doc/classes/CPUParticles.xml +++ b/doc/classes/CPUParticles.xml @@ -116,6 +116,12 @@ </member> <member name="one_shot" type="bool" setter="set_one_shot" getter="get_one_shot"> </member> + <member name="orbit_velocity" type="float" setter="set_param" getter="get_param"> + </member> + <member name="orbit_velocity_curve" type="Curve" setter="set_param_curve" getter="get_param_curve"> + </member> + <member name="orbit_velocity_random" type="float" setter="set_param_randomness" getter="get_param_randomness"> + </member> <member name="preprocess" type="float" setter="set_pre_process_time" getter="get_pre_process_time"> </member> <member name="radial_accel" type="float" setter="set_param" getter="get_param"> @@ -154,30 +160,34 @@ </constant> <constant name="PARAM_ANGULAR_VELOCITY" value="1" enum="Parameter"> </constant> - <constant name="PARAM_LINEAR_ACCEL" value="2" enum="Parameter"> + <constant name="PARAM_ORBIT_VELOCITY" value="2" enum="Parameter"> </constant> - <constant name="PARAM_RADIAL_ACCEL" value="3" enum="Parameter"> + <constant name="PARAM_LINEAR_ACCEL" value="3" enum="Parameter"> </constant> - <constant name="PARAM_TANGENTIAL_ACCEL" value="4" enum="Parameter"> + <constant name="PARAM_RADIAL_ACCEL" value="4" enum="Parameter"> </constant> - <constant name="PARAM_DAMPING" value="5" enum="Parameter"> + <constant name="PARAM_TANGENTIAL_ACCEL" value="5" enum="Parameter"> </constant> - <constant name="PARAM_ANGLE" value="6" enum="Parameter"> + <constant name="PARAM_DAMPING" value="6" enum="Parameter"> </constant> - <constant name="PARAM_SCALE" value="7" enum="Parameter"> + <constant name="PARAM_ANGLE" value="7" enum="Parameter"> </constant> - <constant name="PARAM_HUE_VARIATION" value="8" enum="Parameter"> + <constant name="PARAM_SCALE" value="8" enum="Parameter"> </constant> - <constant name="PARAM_ANIM_SPEED" value="9" enum="Parameter"> + <constant name="PARAM_HUE_VARIATION" value="9" enum="Parameter"> </constant> - <constant name="PARAM_ANIM_OFFSET" value="10" enum="Parameter"> + <constant name="PARAM_ANIM_SPEED" value="10" enum="Parameter"> </constant> - <constant name="PARAM_MAX" value="11" enum="Parameter"> + <constant name="PARAM_ANIM_OFFSET" value="11" enum="Parameter"> + </constant> + <constant name="PARAM_MAX" value="12" enum="Parameter"> </constant> <constant name="FLAG_ALIGN_Y_TO_VELOCITY" value="0" enum="Flags"> </constant> <constant name="FLAG_ROTATE_Y" value="1" enum="Flags"> </constant> + <constant name="FLAG_DISABLE_Z" value="2" enum="Flags"> + </constant> <constant name="FLAG_MAX" value="3" enum="Flags"> </constant> <constant name="EMISSION_SHAPE_POINT" value="0" enum="EmissionShape"> diff --git a/doc/classes/CPUParticles2D.xml b/doc/classes/CPUParticles2D.xml index e1f71e3600..17c68ccb87 100644 --- a/doc/classes/CPUParticles2D.xml +++ b/doc/classes/CPUParticles2D.xml @@ -111,6 +111,12 @@ </member> <member name="one_shot" type="bool" setter="set_one_shot" getter="get_one_shot"> </member> + <member name="orbit_velocity" type="float" setter="set_param" getter="get_param"> + </member> + <member name="orbit_velocity_curve" type="Curve" setter="set_param_curve" getter="get_param_curve"> + </member> + <member name="orbit_velocity_random" type="float" setter="set_param_randomness" getter="get_param_randomness"> + </member> <member name="preprocess" type="float" setter="set_pre_process_time" getter="get_pre_process_time"> </member> <member name="radial_accel" type="float" setter="set_param" getter="get_param"> @@ -173,7 +179,11 @@ </constant> <constant name="FLAG_ALIGN_Y_TO_VELOCITY" value="0" enum="Flags"> </constant> - <constant name="FLAG_MAX" value="1" enum="Flags"> + <constant name="FLAG_ROTATE_Y" value="1" enum="Flags"> + </constant> + <constant name="FLAG_DISABLE_Z" value="2" enum="Flags"> + </constant> + <constant name="FLAG_MAX" value="3" enum="Flags"> </constant> <constant name="EMISSION_SHAPE_POINT" value="0" enum="EmissionShape"> </constant> diff --git a/drivers/gles3/rasterizer_storage_gles3.cpp b/drivers/gles3/rasterizer_storage_gles3.cpp index 561a3cae2d..01b85458c2 100644 --- a/drivers/gles3/rasterizer_storage_gles3.cpp +++ b/drivers/gles3/rasterizer_storage_gles3.cpp @@ -3501,7 +3501,7 @@ void RasterizerStorageGLES3::mesh_add_surface(RID p_mesh, uint32_t p_format, VS: if (p_vertex_count < (1 << 16)) { //read 16 bit indices const uint16_t *src_idx = (const uint16_t *)ir.ptr(); - for (int i = 0; i < index_count; i += 6) { + for (int i = 0; i + 5 < index_count; i += 6) { wr[i + 0] = src_idx[i / 2]; wr[i + 1] = src_idx[i / 2 + 1]; @@ -3515,7 +3515,7 @@ void RasterizerStorageGLES3::mesh_add_surface(RID p_mesh, uint32_t p_format, VS: //read 16 bit indices const uint32_t *src_idx = (const uint32_t *)ir.ptr(); - for (int i = 0; i < index_count; i += 6) { + for (int i = 0; i + 5 < index_count; i += 6) { wr[i + 0] = src_idx[i / 2]; wr[i + 1] = src_idx[i / 2 + 1]; @@ -3531,7 +3531,7 @@ void RasterizerStorageGLES3::mesh_add_surface(RID p_mesh, uint32_t p_format, VS: index_count = p_vertex_count * 2; wf_indices.resize(index_count); PoolVector<uint32_t>::Write wr = wf_indices.write(); - for (int i = 0; i < index_count; i += 6) { + for (int i = 0; i + 5 < index_count; i += 6) { wr[i + 0] = i / 2; wr[i + 1] = i / 2 + 1; diff --git a/editor/connections_dialog.cpp b/editor/connections_dialog.cpp index 82fc8e5cfa..569ad0297e 100644 --- a/editor/connections_dialog.cpp +++ b/editor/connections_dialog.cpp @@ -126,7 +126,6 @@ void ConnectDialog::ok_pressed() { } } emit_signal("connected"); - hide(); } void ConnectDialog::_cancel_pressed() { @@ -458,7 +457,7 @@ ConnectDialog::~ConnectDialog() { memdelete(cdbinds); } -//ConnectionsDock ========================== +////////////////////////////////////////// struct _ConnectionsDockMethodInfoSort { @@ -490,11 +489,11 @@ void ConnectionsDock::_make_or_edit_connection() { bool oshot = connect_dialog->get_oneshot(); cToMake.flags = CONNECT_PERSIST | (defer ? CONNECT_DEFERRED : 0) | (oshot ? CONNECT_ONESHOT : 0); - //conditions to add function, must have a script and must have a method + // Conditions to add function, must have a script and must have a method. bool add_script_function = !target->get_script().is_null() && !ClassDB::has_method(target->get_class(), cToMake.method); PoolStringArray script_function_args; if (add_script_function) { - // pick up args here before "it" is deleted by update_tree + // Pick up args here before "it" is deleted by update_tree. script_function_args = it->get_metadata(0).operator Dictionary()["args"]; for (int i = 0; i < cToMake.binds.size(); i++) { script_function_args.append("extra_arg_" + itos(i)); @@ -509,7 +508,7 @@ void ConnectionsDock::_make_or_edit_connection() { } // IMPORTANT NOTE: _disconnect and _connect cause an update_tree, - // which will delete the object "it" is pointing to + // which will delete the object "it" is pointing to. it = NULL; if (add_script_function) { @@ -549,7 +548,7 @@ Break single connection w/ undo-redo functionality. void ConnectionsDock::_disconnect(TreeItem &item) { Connection c = item.get_metadata(0); - ERR_FAIL_COND(c.source != selectedNode); //shouldn't happen but...bugcheck + ERR_FAIL_COND(c.source != selectedNode); // Shouldn't happen but... Bugcheck. undo_redo->create_action(vformat(TTR("Disconnect '%s' from '%s'"), c.signal, c.method)); @@ -557,7 +556,7 @@ void ConnectionsDock::_disconnect(TreeItem &item) { undo_redo->add_undo_method(selectedNode, "connect", c.signal, c.target, c.method, c.binds, c.flags); undo_redo->add_do_method(this, "update_tree"); undo_redo->add_undo_method(this, "update_tree"); - undo_redo->add_do_method(EditorNode::get_singleton()->get_scene_tree_dock()->get_tree_editor(), "update_tree"); //to force redraw of scene tree + undo_redo->add_do_method(EditorNode::get_singleton()->get_scene_tree_dock()->get_tree_editor(), "update_tree"); // To force redraw of scene tree. undo_redo->add_undo_method(EditorNode::get_singleton()->get_scene_tree_dock()->get_tree_editor(), "update_tree"); undo_redo->commit_action(); @@ -596,7 +595,7 @@ void ConnectionsDock::_disconnect_all() { void ConnectionsDock::_tree_item_selected() { TreeItem *item = tree->get_selected(); - if (!item) { //Unlikely. Disable button just in case. + if (!item) { // Unlikely. Disable button just in case. connect_button->set_text(TTR("Connect...")); connect_button->set_disabled(true); } else if (_is_item_signal(*item)) { @@ -608,7 +607,7 @@ void ConnectionsDock::_tree_item_selected() { } } -void ConnectionsDock::_tree_item_activated() { //"Activation" on double-click. +void ConnectionsDock::_tree_item_activated() { // "Activation" on double-click. TreeItem *item = tree->get_selected(); @@ -630,7 +629,6 @@ bool ConnectionsDock::_is_item_signal(TreeItem &item) { /* Open connection dialog with TreeItem data to CREATE a brand-new connection. */ - void ConnectionsDock::_open_connection_dialog(TreeItem &item) { String signal = item.get_metadata(0).operator Dictionary()["name"]; @@ -640,10 +638,10 @@ void ConnectionsDock::_open_connection_dialog(TreeItem &item) { CharType c = midname[i]; if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_')) { if (c == ' ') { - //Replace spaces with underlines. + // Replace spaces with underlines. c = '_'; } else { - //Remove any other characters. + // Remove any other characters. midname.remove(i); i--; continue; @@ -828,7 +826,6 @@ void ConnectionsDock::update_tree() { selectedNode->get_signal_list(&node_signals); - //node_signals.sort_custom<_ConnectionsDockMethodInfoSort>(); bool did_script = false; StringName base = selectedNode->get_class(); @@ -955,7 +952,7 @@ void ConnectionsDock::update_tree() { } } - connect_button->set_text(TTR("Connect")); + connect_button->set_text(TTR("Connect...")); connect_button->set_disabled(true); } @@ -975,7 +972,6 @@ ConnectionsDock::ConnectionsDock(EditorNode *p_editor) { tree->set_allow_rmb_select(true); connect_button = memnew(Button); - connect_button->set_text(TTR("Connect")); HBoxContainer *hb = memnew(HBoxContainer); vbc->add_child(hb); hb->add_spacer(); @@ -1005,15 +1001,6 @@ ConnectionsDock::ConnectionsDock(EditorNode *p_editor) { slot_menu->add_item(TTR("Go To Method"), GO_TO_SCRIPT); slot_menu->add_item(TTR("Disconnect"), DISCONNECT); - /* - node_only->set_anchor( MARGIN_TOP, ANCHOR_END ); - node_only->set_anchor( MARGIN_BOTTOM, ANCHOR_END ); - node_only->set_anchor( MARGIN_RIGHT, ANCHOR_END ); - - node_only->set_begin( Point2( 20,51) ); - node_only->set_end( Point2( 10,44) ); - */ - connect_dialog->connect("connected", this, "_make_or_edit_connection"); tree->connect("item_selected", this, "_tree_item_selected"); tree->connect("item_activated", this, "_tree_item_activated"); diff --git a/editor/connections_dialog.h b/editor/connections_dialog.h index 94f1510810..195c9e1e7d 100644 --- a/editor/connections_dialog.h +++ b/editor/connections_dialog.h @@ -104,7 +104,7 @@ public: ~ConnectDialog(); }; -//======================================== +////////////////////////////////////////// class ConnectionsDock : public VBoxContainer { diff --git a/editor/editor_file_dialog.cpp b/editor/editor_file_dialog.cpp index 1a293adb4b..8025fc9795 100644 --- a/editor/editor_file_dialog.cpp +++ b/editor/editor_file_dialog.cpp @@ -63,6 +63,7 @@ void EditorFileDialog::_notification(int p_what) { dir_up->set_icon(get_icon("ArrowUp", "EditorIcons")); refresh->set_icon(get_icon("Reload", "EditorIcons")); favorite->set_icon(get_icon("Favorites", "EditorIcons")); + show_hidden->set_icon(get_icon("GuiVisibilityVisible", "EditorIcons")); fav_up->set_icon(get_icon("MoveUp", "EditorIcons")); fav_down->set_icon(get_icon("MoveDown", "EditorIcons")); @@ -86,9 +87,9 @@ void EditorFileDialog::_notification(int p_what) { } else if (p_what == EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED) { - bool show_hidden = EditorSettings::get_singleton()->get("filesystem/file_dialog/show_hidden_files"); - if (show_hidden_files != show_hidden) - set_show_hidden_files(show_hidden); + bool is_showing_hidden = EditorSettings::get_singleton()->get("filesystem/file_dialog/show_hidden_files"); + if (show_hidden_files != is_showing_hidden) + set_show_hidden_files(is_showing_hidden); set_display_mode((DisplayMode)EditorSettings::get_singleton()->get("filesystem/file_dialog/display_mode").operator int()); // update icons @@ -140,7 +141,7 @@ void EditorFileDialog::_unhandled_input(const Ref<InputEvent> &p_event) { handled = true; } if (ED_IS_SHORTCUT("file_dialog/toggle_favorite", p_event)) { - _favorite_toggled(favorite->is_pressed()); + _favorite_pressed(); handled = true; } if (ED_IS_SHORTCUT("file_dialog/toggle_mode", p_event)) { @@ -231,6 +232,7 @@ void EditorFileDialog::_file_entered(const String &p_file) { } void EditorFileDialog::_save_confirm_pressed() { + String f = dir_access->get_current_dir().plus_file(file->get_text()); _save_to_recent(); hide(); @@ -717,20 +719,19 @@ void EditorFileDialog::update_file_list() { List<String> files; List<String> dirs; - bool isdir; - bool ishidden; - bool show_hidden = show_hidden_files; + bool is_dir; + bool is_hidden; String item; - while ((item = dir_access->get_next(&isdir)) != "") { + while ((item = dir_access->get_next(&is_dir)) != "") { if (item == "." || item == "..") continue; - ishidden = dir_access->current_is_hidden(); + is_hidden = dir_access->current_is_hidden(); - if (show_hidden || !ishidden) { - if (!isdir) + if (show_hidden_files || !is_hidden) { + if (!is_dir) files.push_back(item); else dirs.push_back(item); @@ -1130,6 +1131,7 @@ void EditorFileDialog::_update_drives() { } void EditorFileDialog::_favorite_selected(int p_idx) { + dir_access->change_dir(favorites->get_item_metadata(p_idx)); file->set_text(""); update_dir(); @@ -1210,7 +1212,7 @@ void EditorFileDialog::_update_favorites() { favorites->add_item(name, folder_icon); } else { - continue; // We don't handle favorite files here + continue; // We don't handle favorite files here. } favorites->set_item_metadata(favorites->get_item_count() - 1, favorited[i]); @@ -1218,11 +1220,12 @@ void EditorFileDialog::_update_favorites() { if (setthis) { favorite->set_pressed(true); favorites->set_current(favorites->get_item_count() - 1); + recent->unselect_all(); } } } -void EditorFileDialog::_favorite_toggled(bool p_toggle) { +void EditorFileDialog::_favorite_pressed() { bool res = access == ACCESS_RESOURCES; String cd = get_current_dir(); @@ -1253,12 +1256,6 @@ void EditorFileDialog::_favorite_toggled(bool p_toggle) { _update_favorites(); } -void EditorFileDialog::_favorite_pressed() { - - favorite->set_pressed(!favorite->is_pressed()); - _favorite_toggled(favorite->is_pressed()); -} - void EditorFileDialog::_recent_selected(int p_idx) { Vector<String> recentd = EditorSettings::get_singleton()->get_recent_dirs(); @@ -1381,7 +1378,6 @@ void EditorFileDialog::_bind_methods() { ClassDB::bind_method(D_METHOD("_go_forward"), &EditorFileDialog::_go_forward); ClassDB::bind_method(D_METHOD("_go_up"), &EditorFileDialog::_go_up); - ClassDB::bind_method(D_METHOD("_favorite_toggled"), &EditorFileDialog::_favorite_toggled); ClassDB::bind_method(D_METHOD("_favorite_pressed"), &EditorFileDialog::_favorite_pressed); ClassDB::bind_method(D_METHOD("_favorite_selected"), &EditorFileDialog::_favorite_selected); ClassDB::bind_method(D_METHOD("_favorite_move_up"), &EditorFileDialog::_favorite_move_up); @@ -1418,6 +1414,7 @@ void EditorFileDialog::_bind_methods() { void EditorFileDialog::set_show_hidden_files(bool p_show) { show_hidden_files = p_show; + show_hidden->set_pressed(p_show); invalidate(); } @@ -1523,17 +1520,23 @@ EditorFileDialog::EditorFileDialog() { pathhb->add_child(refresh); favorite = memnew(ToolButton); - favorite->set_flat(true); favorite->set_toggle_mode(true); favorite->set_tooltip(TTR("(Un)favorite current folder.")); favorite->connect("pressed", this, "_favorite_pressed"); pathhb->add_child(favorite); - Ref<ButtonGroup> view_mode_group; - view_mode_group.instance(); + show_hidden = memnew(ToolButton); + show_hidden->set_toggle_mode(true); + show_hidden->set_pressed(is_showing_hidden_files()); + show_hidden->set_tooltip(TTR("Toggle visibility of hidden files.")); + show_hidden->connect("toggled", this, "set_show_hidden_files"); + pathhb->add_child(show_hidden); pathhb->add_child(memnew(VSeparator)); + Ref<ButtonGroup> view_mode_group; + view_mode_group.instance(); + mode_thumbnails = memnew(ToolButton); mode_thumbnails->connect("pressed", this, "set_display_mode", varray(DISPLAY_THUMBNAILS)); mode_thumbnails->set_toggle_mode(true); @@ -1593,6 +1596,7 @@ EditorFileDialog::EditorFileDialog() { rec_vb->set_custom_minimum_size(Size2(150, 100) * EDSCALE); rec_vb->set_v_size_flags(SIZE_EXPAND_FILL); recent = memnew(ItemList); + recent->set_allow_reselect(true); rec_vb->add_margin_child(TTR("Recent:"), recent, true); recent->connect("item_selected", this, "_recent_selected"); @@ -1609,7 +1613,7 @@ EditorFileDialog::EditorFileDialog() { list_vb->add_child(memnew(Label(TTR("Directories & Files:")))); preview_hb->add_child(list_vb); - // Item (files and folders) list with context menu + // Item (files and folders) list with context menu. item_list = memnew(ItemList); item_list->set_v_size_flags(SIZE_EXPAND_FILL); @@ -1622,7 +1626,7 @@ EditorFileDialog::EditorFileDialog() { item_menu->connect("id_pressed", this, "_item_menu_id_pressed"); add_child(item_menu); - // Other stuff + // Other stuff. preview_vb = memnew(VBoxContainer); preview_hb->add_child(preview_vb); @@ -1641,7 +1645,7 @@ EditorFileDialog::EditorFileDialog() { filter = memnew(OptionButton); filter->set_stretch_ratio(3); filter->set_h_size_flags(SIZE_EXPAND_FILL); - filter->set_clip_text(true); // too many extensions overflow it + filter->set_clip_text(true); // Too many extensions overflow it. filename_hbc->add_child(filter); filename_hbc->set_h_size_flags(SIZE_EXPAND_FILL); item_vb->add_child(filename_hbc); diff --git a/editor/editor_file_dialog.h b/editor/editor_file_dialog.h index 529aaa71de..6578be8563 100644 --- a/editor/editor_file_dialog.h +++ b/editor/editor_file_dialog.h @@ -116,11 +116,13 @@ private: DirAccess *dir_access; ConfirmationDialog *confirm_save; DependencyRemoveDialog *remove_dialog; + ToolButton *mode_thumbnails; ToolButton *mode_list; ToolButton *refresh; ToolButton *favorite; + ToolButton *show_hidden; ToolButton *fav_up; ToolButton *fav_down; @@ -150,7 +152,6 @@ private: void update_filters(); void _update_favorites(); - void _favorite_toggled(bool p_toggle); void _favorite_pressed(); void _favorite_selected(int p_idx); void _favorite_move_up(); diff --git a/editor/editor_settings.cpp b/editor/editor_settings.cpp index c7fac07ba2..a6746c6d25 100644 --- a/editor/editor_settings.cpp +++ b/editor/editor_settings.cpp @@ -699,6 +699,10 @@ bool EditorSettings::_save_text_editor_theme(String p_file) { return false; } +bool EditorSettings::_is_default_text_editor_theme(String p_theme_name) { + return p_theme_name == "default" || p_theme_name == "adaptive" || p_theme_name == "custom"; +} + static Dictionary _get_builtin_script_templates() { Dictionary templates; @@ -1291,7 +1295,7 @@ void EditorSettings::list_text_editor_themes() { d->list_dir_begin(); String file = d->get_next(); while (file != String()) { - if (file.get_extension() == "tet" && file.get_basename().to_lower() != "default" && file.get_basename().to_lower() != "adaptive" && file.get_basename().to_lower() != "custom") { + if (file.get_extension() == "tet" && !_is_default_text_editor_theme(file.get_basename().to_lower())) { custom_themes.push_back(file.get_basename()); } file = d->get_next(); @@ -1308,14 +1312,16 @@ void EditorSettings::list_text_editor_themes() { } void EditorSettings::load_text_editor_theme() { - if (get("text_editor/theme/color_theme") == "Default" || get("text_editor/theme/color_theme") == "Adaptive" || get("text_editor/theme/color_theme") == "Custom") { - if (get("text_editor/theme/color_theme") == "Default") { + String p_file = get("text_editor/theme/color_theme"); + + if (_is_default_text_editor_theme(p_file.get_file().to_lower())) { + if (p_file == "Default") { _load_default_text_editor_theme(); } return; // sorry for "Settings changed" console spam } - String theme_path = get_text_editor_themes_dir().plus_file((String)get("text_editor/theme/color_theme") + ".tet"); + String theme_path = get_text_editor_themes_dir().plus_file(p_file + ".tet"); Ref<ConfigFile> cf = memnew(ConfigFile); Error err = cf->load(theme_path); @@ -1367,7 +1373,7 @@ bool EditorSettings::save_text_editor_theme() { String p_file = get("text_editor/theme/color_theme"); - if (p_file.get_file().to_lower() == "default" || p_file.get_file().to_lower() == "adaptive" || p_file.get_file().to_lower() == "custom") { + if (_is_default_text_editor_theme(p_file.get_file().to_lower())) { return false; } String theme_path = get_text_editor_themes_dir().plus_file(p_file + ".tet"); @@ -1379,7 +1385,7 @@ bool EditorSettings::save_text_editor_theme_as(String p_file) { p_file += ".tet"; } - if (p_file.get_file().to_lower() == "default.tet" || p_file.get_file().to_lower() == "adaptive.tet" || p_file.get_file().to_lower() == "custom.tet") { + if (_is_default_text_editor_theme(p_file.get_file().to_lower().trim_suffix(".tet"))) { return false; } if (_save_text_editor_theme(p_file)) { @@ -1397,6 +1403,11 @@ bool EditorSettings::save_text_editor_theme_as(String p_file) { return false; } +bool EditorSettings::is_default_text_editor_theme() { + String p_file = get("text_editor/theme/color_theme"); + return _is_default_text_editor_theme(p_file.get_file().to_lower()); +} + Vector<String> EditorSettings::get_script_templates(const String &p_extension) { Vector<String> templates; diff --git a/editor/editor_settings.h b/editor/editor_settings.h index 43a8cbf739..2ee8dd805b 100644 --- a/editor/editor_settings.h +++ b/editor/editor_settings.h @@ -123,6 +123,7 @@ private: void _load_defaults(Ref<ConfigFile> p_extra_config = NULL); void _load_default_text_editor_theme(); bool _save_text_editor_theme(String p_file); + bool _is_default_text_editor_theme(String p_file); protected: static void _bind_methods(); @@ -187,6 +188,7 @@ public: bool import_text_editor_theme(String p_file); bool save_text_editor_theme(); bool save_text_editor_theme_as(String p_file); + bool is_default_text_editor_theme(); Vector<String> get_script_templates(const String &p_extension); String get_editor_layouts_config() const; diff --git a/editor/plugins/script_editor_plugin.cpp b/editor/plugins/script_editor_plugin.cpp index 6bf916cdfc..7456c5d016 100644 --- a/editor/plugins/script_editor_plugin.cpp +++ b/editor/plugins/script_editor_plugin.cpp @@ -1311,23 +1311,29 @@ void ScriptEditor::_theme_option(int p_option) { EditorSettings::get_singleton()->load_text_editor_theme(); } break; case THEME_SAVE: { - if (!EditorSettings::get_singleton()->save_text_editor_theme()) { + if (EditorSettings::get_singleton()->is_default_text_editor_theme()) { + ScriptEditor::_show_save_theme_as_dialog(); + } else if (!EditorSettings::get_singleton()->save_text_editor_theme()) { editor->show_warning(TTR("Error while saving theme"), TTR("Error saving")); } } break; case THEME_SAVE_AS: { - file_dialog->set_mode(EditorFileDialog::MODE_SAVE_FILE); - file_dialog->set_access(EditorFileDialog::ACCESS_FILESYSTEM); - file_dialog_option = THEME_SAVE_AS; - file_dialog->clear_filters(); - file_dialog->add_filter("*.tet"); - file_dialog->set_current_path(EditorSettings::get_singleton()->get_text_editor_themes_dir().plus_file(EditorSettings::get_singleton()->get("text_editor/theme/color_theme"))); - file_dialog->popup_centered_ratio(); - file_dialog->set_title(TTR("Save Theme As...")); + ScriptEditor::_show_save_theme_as_dialog(); } break; } } +void ScriptEditor::_show_save_theme_as_dialog() { + file_dialog->set_mode(EditorFileDialog::MODE_SAVE_FILE); + file_dialog->set_access(EditorFileDialog::ACCESS_FILESYSTEM); + file_dialog_option = THEME_SAVE_AS; + file_dialog->clear_filters(); + file_dialog->add_filter("*.tet"); + file_dialog->set_current_path(EditorSettings::get_singleton()->get_text_editor_themes_dir().plus_file(EditorSettings::get_singleton()->get("text_editor/theme/color_theme"))); + file_dialog->popup_centered_ratio(); + file_dialog->set_title(TTR("Save Theme As...")); +} + void ScriptEditor::_tab_changed(int p_which) { ensure_select_current(); diff --git a/editor/plugins/script_editor_plugin.h b/editor/plugins/script_editor_plugin.h index fae98d6ec8..7cd347e2d0 100644 --- a/editor/plugins/script_editor_plugin.h +++ b/editor/plugins/script_editor_plugin.h @@ -264,6 +264,7 @@ class ScriptEditor : public PanelContainer { void _tab_changed(int p_which); void _menu_option(int p_option); void _theme_option(int p_option); + void _show_save_theme_as_dialog(); Tree *disk_changed_list; ConfirmationDialog *disk_changed; diff --git a/editor/project_manager.cpp b/editor/project_manager.cpp index 7b521aba13..3fd497ed7b 100644 --- a/editor/project_manager.cpp +++ b/editor/project_manager.cpp @@ -961,9 +961,25 @@ void ProjectManager::_notification(int p_what) { set_process_unhandled_input(is_visible_in_tree()); } break; + case NOTIFICATION_WM_QUIT_REQUEST: { + + _dim_window(); + } break; } } +void ProjectManager::_dim_window() { + + // This method must be called before calling `get_tree()->quit()`. + // Otherwise, its effect won't be visible + + // Dim the project manager window while it's quitting to make it clearer that it's busy. + // No transition is applied, as the effect needs to be visible immediately + float c = 1.0f - float(EDITOR_GET("interface/editor/dim_amount")); + Color dim_color = Color(c, c, c); + gui_base->set_modulate(dim_color); +} + void ProjectManager::_panel_draw(Node *p_hb) { HBoxContainer *hb = Object::cast_to<HBoxContainer>(p_hb); @@ -1514,6 +1530,7 @@ void ProjectManager::_open_selected_projects() { ERR_FAIL_COND(err); } + _dim_window(); get_tree()->quit(); } @@ -1780,11 +1797,13 @@ void ProjectManager::_restart_confirm() { Error err = OS::get_singleton()->execute(exec, args, false, &pid); ERR_FAIL_COND(err); + _dim_window(); get_tree()->quit(); } void ProjectManager::_exit_dialog() { + _dim_window(); get_tree()->quit(); } diff --git a/editor/project_manager.h b/editor/project_manager.h index fa878e75a6..a7cc6549f5 100644 --- a/editor/project_manager.h +++ b/editor/project_manager.h @@ -110,6 +110,7 @@ class ProjectManager : public Control { void _install_project(const String &p_zip_path, const String &p_title); + void _dim_window(); void _panel_draw(Node *p_hb); void _panel_input(const Ref<InputEvent> &p_ev, Node *p_hb); void _unhandled_input(const Ref<InputEvent> &p_ev); diff --git a/modules/csg/csg_shape.h b/modules/csg/csg_shape.h index a5b2238e6b..2171f27f96 100644 --- a/modules/csg/csg_shape.h +++ b/modules/csg/csg_shape.h @@ -116,9 +116,9 @@ protected: virtual void _validate_property(PropertyInfo &property) const; +public: Array get_meshes() const; -public: void set_operation(Operation p_operation); Operation get_operation() const; diff --git a/modules/recast/navigation_mesh_generator.cpp b/modules/recast/navigation_mesh_generator.cpp index 0cac07e3e7..14467dc5c7 100644 --- a/modules/recast/navigation_mesh_generator.cpp +++ b/modules/recast/navigation_mesh_generator.cpp @@ -45,6 +45,10 @@ #include "scene/resources/shape.h" #include "scene/resources/sphere_shape.h" +#ifdef MODULE_CSG_ENABLED +#include "modules/csg/csg_shape.h" +#endif + EditorNavigationMeshGenerator *EditorNavigationMeshGenerator::singleton = NULL; void EditorNavigationMeshGenerator::_add_vertex(const Vector3 &p_vec3, Vector<float> &p_verticies) { @@ -134,6 +138,20 @@ void EditorNavigationMeshGenerator::_parse_geometry(Transform p_accumulated_tran } } +#ifdef MODULE_CSG_ENABLED + if (Object::cast_to<CSGShape>(p_node) && p_generate_from != NavigationMesh::PARSED_GEOMETRY_STATIC_COLLIDERS) { + + CSGShape *csg_shape = Object::cast_to<CSGShape>(p_node); + Array meshes = csg_shape->get_meshes(); + if (!meshes.empty()) { + Ref<Mesh> mesh = meshes[1]; + if (mesh.is_valid()) { + _add_mesh(mesh, p_accumulated_transform * csg_shape->get_transform(), p_verticies, p_indices); + } + } + } +#endif + if (Object::cast_to<StaticBody>(p_node) && p_generate_from != NavigationMesh::PARSED_GEOMETRY_MESH_INSTANCES) { StaticBody *static_body = Object::cast_to<StaticBody>(p_node); diff --git a/modules/webrtc/config.py b/modules/webrtc/config.py index 2e3a18ad0e..48b4c33c5d 100644 --- a/modules/webrtc/config.py +++ b/modules/webrtc/config.py @@ -7,7 +7,8 @@ def configure(env): def get_doc_classes(): return [ "WebRTCPeerConnection", - "WebRTCDataChannel" + "WebRTCDataChannel", + "WebRTCMultiplayer" ] def get_doc_path(): diff --git a/modules/webrtc/doc_classes/WebRTCDataChannel.xml b/modules/webrtc/doc_classes/WebRTCDataChannel.xml index dcc14d4ddb..f03ae864f8 100644 --- a/modules/webrtc/doc_classes/WebRTCDataChannel.xml +++ b/modules/webrtc/doc_classes/WebRTCDataChannel.xml @@ -11,85 +11,106 @@ <return type="void"> </return> <description> + Closes this data channel, notifying the other peer. </description> </method> <method name="get_id" qualifiers="const"> <return type="int"> </return> <description> + Returns the id assigned to this channel during creation (or auto-assigned during negotiation). + If the channel is not negotiated out-of-band the id will only be available after the connection is established (will return [code]65535[/code] until then). </description> </method> <method name="get_label" qualifiers="const"> <return type="String"> </return> <description> + Returns the label assigned to this channel during creation. </description> </method> <method name="get_max_packet_life_time" qualifiers="const"> <return type="int"> </return> <description> + Returns the maxPacketLifeTime value assigned to this channel during creation. + Will be [code]65535[/code] if not specified. </description> </method> <method name="get_max_retransmits" qualifiers="const"> <return type="int"> </return> <description> + Returns the maxRetransmits value assigned to this channel during creation. + Will be [code]65535[/code] if not specified. </description> </method> <method name="get_protocol" qualifiers="const"> <return type="String"> </return> <description> + Returns the sub-proctocol assigned to this channel during creation. An empty string if not specified. </description> </method> <method name="get_ready_state" qualifiers="const"> <return type="int" enum="WebRTCDataChannel.ChannelState"> </return> <description> + Returns the current state of this channel, see [enum WebRTCDataChannel.ChannelState]. </description> </method> <method name="is_negotiated" qualifiers="const"> <return type="bool"> </return> <description> + Returns [code]true[/code] if this channel was created with out-of-band configuration. </description> </method> <method name="is_ordered" qualifiers="const"> <return type="bool"> </return> <description> + Returns [code]true[/code] if this channel was created with ordering enabled (default). </description> </method> <method name="poll"> <return type="int" enum="Error"> </return> <description> + Reserved, but not used for now. </description> </method> <method name="was_string_packet" qualifiers="const"> <return type="bool"> </return> <description> + Returns [code]true[/code] if the last received packet was transfered as text. See [property write_mode]. </description> </method> </methods> <members> <member name="write_mode" type="int" setter="set_write_mode" getter="get_write_mode" enum="WebRTCDataChannel.WriteMode"> + The transfer mode to use when sending outgoing packet. Either text or binary. </member> </members> <constants> <constant name="WRITE_MODE_TEXT" value="0" enum="WriteMode"> + Tells the channel to send data over this channel as text. An external peer (non-godot) would receive this as a string. </constant> <constant name="WRITE_MODE_BINARY" value="1" enum="WriteMode"> + Tells the channel to send data over this channel as binary. An external peer (non-godot) would receive this as arraybuffer or blob. </constant> <constant name="STATE_CONNECTING" value="0" enum="ChannelState"> + The channel was created, but it's still trying to connect. </constant> <constant name="STATE_OPEN" value="1" enum="ChannelState"> + The channel is currently open, and data can flow over it. </constant> <constant name="STATE_CLOSING" value="2" enum="ChannelState"> + The channel is being closed, no new messages will be accepted, but those already in queue will be flushed. </constant> <constant name="STATE_CLOSED" value="3" enum="ChannelState"> + The channel was closed, or connection failed. </constant> </constants> </class> diff --git a/modules/webrtc/doc_classes/WebRTCMultiplayer.xml b/modules/webrtc/doc_classes/WebRTCMultiplayer.xml new file mode 100644 index 0000000000..2b0622fffa --- /dev/null +++ b/modules/webrtc/doc_classes/WebRTCMultiplayer.xml @@ -0,0 +1,85 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="WebRTCMultiplayer" inherits="NetworkedMultiplayerPeer" category="Core" version="3.2"> + <brief_description> + A simple interface to create a peer-to-peer mesh network composed of [WebRTCPeerConnection] that is compatible with the [MultiplayerAPI]. + </brief_description> + <description> + This class constructs a full mesh of [WebRTCPeerConnection] (one connection for each peer) that can be used as a [member MultiplayerAPI.network_peer]. + You can add each [WebRTCPeerConnection] via [method add_peer] or remove them via [method remove_peer]. Peers must be added in [constant WebRTCPeerConnection.STATE_NEW] state to allow it to create the appropriate channels. This class will not create offers nor set descriptions, it will only poll them, and notify connections and disconnections. + [signal NetworkedMultiplayerPeer.connection_succeeded] and [signal NetworkedMultiplayerPeer.server_disconnected] will not be emitted unless [code]server_compatibility[/code] is [code]true[/code] in [method initialize]. Beside that data transfer works like in a [NetworkedMultiplayerPeer]. + </description> + <tutorials> + </tutorials> + <methods> + <method name="add_peer"> + <return type="int" enum="Error"> + </return> + <argument index="0" name="peer" type="WebRTCPeerConnection"> + </argument> + <argument index="1" name="peer_id" type="int"> + </argument> + <argument index="2" name="unreliable_lifetime" type="int" default="1"> + </argument> + <description> + Add a new peer to the mesh with the given [code]peer_id[/code]. The [WebRTCPeerConnection] must be in state [constant WebRTCPeerConnection.STATE_NEW]. + Three channels will be created for reliable, unreliable, and ordered transport. The value of [code]unreliable_lifetime[/code] will be passed to the [code]maxPacketLifetime[/code] option when creating unreliable and ordered channels (see [method WebRTCPeerConnection.create_data_channel]). + </description> + </method> + <method name="close"> + <return type="void"> + </return> + <description> + Close all the add peer connections and channels, freeing all resources. + </description> + </method> + <method name="get_peer"> + <return type="Dictionary"> + </return> + <argument index="0" name="peer_id" type="int"> + </argument> + <description> + Return a dictionary representation of the peer with given [code]peer_id[/code] with three keys. [code]connection[/code] containing the [WebRTCPeerConnection] to this peer, [code]channels[/code] an array of three [WebRTCDataChannel], and [code]connected[/code] a boolean representing if the peer connection is currently connected (all three channels are open). + </description> + </method> + <method name="get_peers"> + <return type="Dictionary"> + </return> + <description> + Returns a dictionary which keys are the peer ids and values the peer representation as in [method get_peer] + </description> + </method> + <method name="has_peer"> + <return type="bool"> + </return> + <argument index="0" name="peer_id" type="int"> + </argument> + <description> + Returns [code]true[/code] if the given [code]peer_id[/code] is in the peers map (it might not be connected though). + </description> + </method> + <method name="initialize"> + <return type="int" enum="Error"> + </return> + <argument index="0" name="peer_id" type="int"> + </argument> + <argument index="1" name="server_compatibility" type="bool" default="false"> + </argument> + <description> + Initialize the multiplayer peer with the given [code]peer_id[/code] (must be between 1 and 2147483647). + If [code]server_compatibilty[/code] is [code]false[/code] (default), the multiplayer peer will be immediately in state [constant NetworkedMultiplayerPeer.CONNECTION_CONNECTED] and [signal NetworkedMultiplayerPeer.connection_succeeded] will not be emitted. + If [code]server_compatibilty[/code] is [code]true[/code] the peer will suppress all [signal NetworkedMultiplayerPeer.peer_connected] signals until a peer with id [constant NetworkedMultiplayerPeer.TARGET_PEER_SERVER] connects and then emit [signal NetworkedMultiplayerPeer.connection_succeeded]. After that the signal [signal NetworkedMultiplayerPeer.peer_connected] will be emitted for every already connected peer, and any new peer that might connect. If the server peer disconnects after that, signal [signal NetworkedMultiplayerPeer.server_disconnected] will be emitted and state will become [constant NetworkedMultiplayerPeer.CONNECTION_CONNECTED]. + </description> + </method> + <method name="remove_peer"> + <return type="void"> + </return> + <argument index="0" name="peer_id" type="int"> + </argument> + <description> + Remove the peer with given [code]peer_id[/code] from the mesh. If the peer was connected, and [signal NetworkedMultiplayerPeer.peer_connected] was emitted for it, then [signal NetworkedMultiplayerPeer.peer_disconnected] will be emitted. + </description> + </method> + </methods> + <constants> + </constants> +</class> diff --git a/modules/webrtc/doc_classes/WebRTCPeerConnection.xml b/modules/webrtc/doc_classes/WebRTCPeerConnection.xml index 8b14c60deb..aa2c856b6e 100644 --- a/modules/webrtc/doc_classes/WebRTCPeerConnection.xml +++ b/modules/webrtc/doc_classes/WebRTCPeerConnection.xml @@ -1,8 +1,17 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="WebRTCPeerConnection" inherits="Reference" category="Core" version="3.2"> <brief_description> + Interface to a WebRTC peer connection. </brief_description> <description> + A WebRTC connection between the local computer and a remote peer. Provides an interface to connect, maintain and monitor the connection. + + Setting up a WebRTC connection between two peers from now on) may not seem a trival task, but it can be broken down into 3 main steps: + - The peer that wants to initiate the connection ([code]A[/code] from now on) creates an offer and send it to the other peer ([code]B[/code] from now on). + - [code]B[/code] receives the offer, generate and answer, and sends it to [code]B[/code]). + - [code]A[/code] and [code]B[/code] then generates and exchange ICE candiates with each other. + + After these steps, the connection should become connected. Keep on reading or look into the tutorial for more information. </description> <tutorials> </tutorials> @@ -17,12 +26,14 @@ <argument index="2" name="name" type="String"> </argument> <description> + Add an ice candidate generated by a remote peer (and received over the signaling server). See [signal ice_candidate_created]. </description> </method> <method name="close"> <return type="void"> </return> <description> + Close the peer connection and all data channels associated with it. Note, you cannot reuse this object for a new connection unless you call [method initialize]. </description> </method> <method name="create_data_channel"> @@ -35,18 +46,38 @@ }"> </argument> <description> + Returns a new [WebRTCDataChannel] (or [code]null[/code] on failure) with given [code]label[/code] and optionally configured via the [code]options[/code] dictionary. This method can only be called when the connection is in state [constant STATE_NEW]. + There are two ways to create a working data channel: either call [method create_data_channel] on only one of the peer and listen to [signal data_channel_received] on the other, or call [method create_data_channel] on both peers, with the same values, and the [code]negotiated[/code] option set to [code]true[/code]. + Valid [code]options[/code] are: + [code] + { + "negotiated": true, # When set to true (default off), means the channel is negotiated out of band. "id" must be set too. data_channel_received will not be called. + "id": 1, # When "negotiated" is true this value must also be set to the same value on both peer. + + # Only one of maxRetransmits and maxPacketLifeTime can be specified, not both. They make the channel unreliable (but also better at real time). + "maxRetransmits": 1, # Specify the maximum number of attempt the peer will make to retransmits packets if they are not acknowledged. + "maxPacketLifeTime": 100, # Specify the maximum amount of time before giving up retransmitions of unacknowledged packets (in milliseconds). + "ordered": true, # When in unreliable mode (i.e. either "maxRetransmits" or "maxPacketLifetime" is set), "ordered" (true by default) specify if packet ordering is to be enforced. + + "protocol": "my-custom-protocol", # A custom sub-protocol string for this channel. + } + [/code] + NOTE: You must keep a reference to channels created this way, or it will be closed. </description> </method> <method name="create_offer"> <return type="int" enum="Error"> </return> <description> + Creates a new SDP offer to start a WebRTC connection with a remote peer. At least one [WebRTCDataChannel] must have been created before calling this method. + If this functions returns [code]OK[/code], [signal session_description_created] will be called when the session is ready to be sent. </description> </method> <method name="get_connection_state" qualifiers="const"> <return type="int" enum="WebRTCPeerConnection.ConnectionState"> </return> <description> + Returns the connection state. See [enum ConnectionState]. </description> </method> <method name="initialize"> @@ -57,12 +88,29 @@ }"> </argument> <description> + Re-initialize this peer connection, closing any previously active connection, and going back to state [constant STATE_NEW]. A dictionary of [code]options[/code] can be passed to configure the peer connection. + Valid [code]options[/code] are: + [code] + { + "iceServers": [ + { + "urls": [ "stun:stun.example.com:3478" ], # One or more STUN servers. + }, + { + "urls": [ "turn:turn.example.com:3478" ], # One or more TURN servers. + "username": "a_username", # Optional username for the TURN server. + "credentials": "a_password", # Optional password for the TURN server. + } + ] + } + [/code] </description> </method> <method name="poll"> <return type="int" enum="Error"> </return> <description> + Call this method frequently (e.g. in [method Node._process] or [method Node._fixed_process]) to properly receive signals. </description> </method> <method name="set_local_description"> @@ -73,6 +121,8 @@ <argument index="1" name="sdp" type="String"> </argument> <description> + Sets the SDP description of the local peer. This should be called in response to [signal session_description_created]. + If [code]type[/code] is [code]answer[/code] the peer will start emitting [signal ice_candidate_created]. </description> </method> <method name="set_remote_description"> @@ -83,6 +133,9 @@ <argument index="1" name="sdp" type="String"> </argument> <description> + Sets the SDP description of the remote peer. This should be called with the values generated by a remote peer and received over the signaling server. + If [code]type[/code] is [code]offer[/code] the peer will emit [signal session_description_created] with the appropriate answer. + If [code]type[/code] is [code]answer[/code] the peer will start emitting [signal ice_candidate_created]. </description> </method> </methods> @@ -91,6 +144,8 @@ <argument index="0" name="channel" type="Object"> </argument> <description> + Emitted when a new in-band channel is received, i.e. when the channel was created with [code]negotiated: false[/code] (default). + The object will be an instance of [WebRTCDataChannel]. You must keep a reference of it or it will be closed automatically. See [method create_data_channel] </description> </signal> <signal name="ice_candidate_created"> @@ -101,6 +156,7 @@ <argument index="2" name="name" type="String"> </argument> <description> + Emitted when a new ICE candidate has been created. The three parameters are meant to be passed to the remote peer over the signaling server. </description> </signal> <signal name="session_description_created"> @@ -109,21 +165,28 @@ <argument index="1" name="sdp" type="String"> </argument> <description> + Emitted after a successful call to [method create_offer] or [method set_remote_description] (when it generates an answer). The parameters are meant to be passed to [method set_local_description] on this object, and sent to the remote peer over the signaling server. </description> </signal> </signals> <constants> <constant name="STATE_NEW" value="0" enum="ConnectionState"> + The connection is new, data channels and an offer can be created in this state. </constant> <constant name="STATE_CONNECTING" value="1" enum="ConnectionState"> + The peer is connecting, ICE is in progress, non of the transports has failed. </constant> <constant name="STATE_CONNECTED" value="2" enum="ConnectionState"> + The peer is connected, all ICE transports are connected. </constant> <constant name="STATE_DISCONNECTED" value="3" enum="ConnectionState"> + At least one ICE transport is disconnected. </constant> <constant name="STATE_FAILED" value="4" enum="ConnectionState"> + One or more of the ICE transports failed. </constant> <constant name="STATE_CLOSED" value="5" enum="ConnectionState"> + The peer connection is closed (after calling [method close] for example). </constant> </constants> </class> diff --git a/modules/webrtc/register_types.cpp b/modules/webrtc/register_types.cpp index 44e072cc89..58b68d926b 100644 --- a/modules/webrtc/register_types.cpp +++ b/modules/webrtc/register_types.cpp @@ -40,6 +40,7 @@ #include "webrtc_data_channel_gdnative.h" #include "webrtc_peer_connection_gdnative.h" #endif +#include "webrtc_multiplayer.h" void register_webrtc_types() { #ifdef JAVASCRIPT_ENABLED @@ -54,6 +55,7 @@ void register_webrtc_types() { ClassDB::register_class<WebRTCDataChannelGDNative>(); #endif ClassDB::register_virtual_class<WebRTCDataChannel>(); + ClassDB::register_class<WebRTCMultiplayer>(); } void unregister_webrtc_types() {} diff --git a/modules/webrtc/webrtc_data_channel_js.cpp b/modules/webrtc/webrtc_data_channel_js.cpp index 2e7c64aa72..ce2fada634 100644 --- a/modules/webrtc/webrtc_data_channel_js.cpp +++ b/modules/webrtc/webrtc_data_channel_js.cpp @@ -205,30 +205,45 @@ String WebRTCDataChannelJS::get_label() const { } /* clang-format off */ -#define _JS_GET(PROP) \ +#define _JS_GET(PROP, DEF) \ EM_ASM_INT({ \ var dict = Module.IDHandler.get($0); \ if (!dict || !dict["channel"]) { \ - return 0; \ - }; \ - return dict["channel"].PROP; \ + return DEF; \ + } \ + var out = dict["channel"].PROP; \ + return out === null ? DEF : out; \ }, _js_id) /* clang-format on */ bool WebRTCDataChannelJS::is_ordered() const { - return _JS_GET(ordered); + return _JS_GET(ordered, true); } int WebRTCDataChannelJS::get_id() const { - return _JS_GET(id); + return _JS_GET(id, 65535); } int WebRTCDataChannelJS::get_max_packet_life_time() const { - return _JS_GET(maxPacketLifeTime); + // Can't use macro, webkit workaround. + /* clang-format off */ + return EM_ASM_INT({ + var dict = Module.IDHandler.get($0); + if (!dict || !dict["channel"]) { + return 65535; + } + if (dict["channel"].maxRetransmitTime !== undefined) { + // Guess someone didn't appreciate the standardization process. + return dict["channel"].maxRetransmitTime; + } + var out = dict["channel"].maxPacketLifeTime; + return out === null ? 65535 : out; + }, _js_id); + /* clang-format on */ } int WebRTCDataChannelJS::get_max_retransmits() const { - return _JS_GET(maxRetransmits); + return _JS_GET(maxRetransmits, 65535); } String WebRTCDataChannelJS::get_protocol() const { @@ -236,7 +251,7 @@ String WebRTCDataChannelJS::get_protocol() const { } bool WebRTCDataChannelJS::is_negotiated() const { - return _JS_GET(negotiated); + return _JS_GET(negotiated, false); } WebRTCDataChannelJS::WebRTCDataChannelJS() { diff --git a/modules/webrtc/webrtc_multiplayer.cpp b/modules/webrtc/webrtc_multiplayer.cpp new file mode 100644 index 0000000000..17dafff93a --- /dev/null +++ b/modules/webrtc/webrtc_multiplayer.cpp @@ -0,0 +1,384 @@ +/*************************************************************************/ +/* webrtc_multiplayer.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#include "webrtc_multiplayer.h" + +#include "core/io/marshalls.h" +#include "core/os/os.h" + +void WebRTCMultiplayer::_bind_methods() { + ClassDB::bind_method(D_METHOD("initialize", "peer_id", "server_compatibility"), &WebRTCMultiplayer::initialize, DEFVAL(false)); + ClassDB::bind_method(D_METHOD("add_peer", "peer", "peer_id", "unreliable_lifetime"), &WebRTCMultiplayer::add_peer, DEFVAL(1)); + ClassDB::bind_method(D_METHOD("remove_peer", "peer_id"), &WebRTCMultiplayer::remove_peer); + ClassDB::bind_method(D_METHOD("has_peer", "peer_id"), &WebRTCMultiplayer::has_peer); + ClassDB::bind_method(D_METHOD("get_peer", "peer_id"), &WebRTCMultiplayer::get_peer); + ClassDB::bind_method(D_METHOD("get_peers"), &WebRTCMultiplayer::get_peers); + ClassDB::bind_method(D_METHOD("close"), &WebRTCMultiplayer::close); +} + +void WebRTCMultiplayer::set_transfer_mode(TransferMode p_mode) { + transfer_mode = p_mode; +} + +NetworkedMultiplayerPeer::TransferMode WebRTCMultiplayer::get_transfer_mode() const { + return transfer_mode; +} + +void WebRTCMultiplayer::set_target_peer(int p_peer_id) { + target_peer = p_peer_id; +} + +/* Returns the ID of the NetworkedMultiplayerPeer who sent the most recent packet: */ +int WebRTCMultiplayer::get_packet_peer() const { + return next_packet_peer; +} + +bool WebRTCMultiplayer::is_server() const { + return unique_id == TARGET_PEER_SERVER; +} + +void WebRTCMultiplayer::poll() { + if (peer_map.size() == 0) + return; + + List<int> remove; + List<int> add; + for (Map<int, Ref<ConnectedPeer> >::Element *E = peer_map.front(); E; E = E->next()) { + Ref<ConnectedPeer> peer = E->get(); + peer->connection->poll(); + // Check peer state + switch (peer->connection->get_connection_state()) { + case WebRTCPeerConnection::STATE_NEW: + case WebRTCPeerConnection::STATE_CONNECTING: + // Go to next peer, not ready yet. + continue; + case WebRTCPeerConnection::STATE_CONNECTED: + // Good to go, go ahead and check channel state. + break; + default: + // Peer is closed or in error state. Got to next peer. + remove.push_back(E->key()); + continue; + } + // Check channels state + int ready = 0; + for (List<Ref<WebRTCDataChannel> >::Element *C = peer->channels.front(); C && C->get().is_valid(); C = C->next()) { + Ref<WebRTCDataChannel> ch = C->get(); + switch (ch->get_ready_state()) { + case WebRTCDataChannel::STATE_CONNECTING: + continue; + case WebRTCDataChannel::STATE_OPEN: + ready++; + continue; + default: + // Channel was closed or in error state, remove peer id. + remove.push_back(E->key()); + } + // We got a closed channel break out, the peer will be removed. + break; + } + // This peer has newly connected, and all channels are now open. + if (ready == peer->channels.size() && !peer->connected) { + peer->connected = true; + add.push_back(E->key()); + } + } + // Remove disconnected peers + for (List<int>::Element *E = remove.front(); E; E = E->next()) { + remove_peer(E->get()); + if (next_packet_peer == E->get()) + next_packet_peer = 0; + } + // Signal newly connected peers + for (List<int>::Element *E = add.front(); E; E = E->next()) { + // Already connected to server: simply notify new peer. + // NOTE: Mesh is always connected. + if (connection_status == CONNECTION_CONNECTED) + emit_signal("peer_connected", E->get()); + + // Server emulation mode suppresses peer_conencted until server connects. + if (server_compat && E->get() == TARGET_PEER_SERVER) { + // Server connected. + connection_status = CONNECTION_CONNECTED; + emit_signal("peer_connected", TARGET_PEER_SERVER); + emit_signal("connection_succeeded"); + // Notify of all previously connected peers + for (Map<int, Ref<ConnectedPeer> >::Element *F = peer_map.front(); F; F = F->next()) { + if (F->key() != 1 && F->get()->connected) + emit_signal("peer_connected", F->key()); + } + break; // Because we already notified of all newly added peers. + } + } + // Fetch next packet + if (next_packet_peer == 0) + _find_next_peer(); +} + +void WebRTCMultiplayer::_find_next_peer() { + Map<int, Ref<ConnectedPeer> >::Element *E = peer_map.find(next_packet_peer); + if (E) E = E->next(); + // After last. + while (E) { + for (List<Ref<WebRTCDataChannel> >::Element *F = E->get()->channels.front(); F; F = F->next()) { + if (F->get()->get_available_packet_count()) { + next_packet_peer = E->key(); + return; + } + } + E = E->next(); + } + E = peer_map.front(); + // Before last + while (E) { + for (List<Ref<WebRTCDataChannel> >::Element *F = E->get()->channels.front(); F; F = F->next()) { + if (F->get()->get_available_packet_count()) { + next_packet_peer = E->key(); + return; + } + } + if (E->key() == (int)next_packet_peer) + break; + E = E->next(); + } + // No packet found + next_packet_peer = 0; +} + +void WebRTCMultiplayer::set_refuse_new_connections(bool p_enable) { + refuse_connections = p_enable; +} + +bool WebRTCMultiplayer::is_refusing_new_connections() const { + return refuse_connections; +} + +NetworkedMultiplayerPeer::ConnectionStatus WebRTCMultiplayer::get_connection_status() const { + return connection_status; +} + +Error WebRTCMultiplayer::initialize(int p_self_id, bool p_server_compat) { + ERR_FAIL_COND_V(p_self_id < 0 || p_self_id > ~(1 << 31), ERR_INVALID_PARAMETER); + unique_id = p_self_id; + server_compat = p_server_compat; + + // Mesh and server are always connected + if (!server_compat || p_self_id == 1) + connection_status = CONNECTION_CONNECTED; + else + connection_status = CONNECTION_CONNECTING; + return OK; +} + +int WebRTCMultiplayer::get_unique_id() const { + ERR_FAIL_COND_V(connection_status == CONNECTION_DISCONNECTED, 1); + return unique_id; +} + +void WebRTCMultiplayer::_peer_to_dict(Ref<ConnectedPeer> p_connected_peer, Dictionary &r_dict) { + Array channels; + for (List<Ref<WebRTCDataChannel> >::Element *F = p_connected_peer->channels.front(); F; F = F->next()) { + channels.push_back(F->get()); + } + r_dict["connection"] = p_connected_peer->connection; + r_dict["connected"] = p_connected_peer->connected; + r_dict["channels"] = channels; +} + +bool WebRTCMultiplayer::has_peer(int p_peer_id) { + return peer_map.has(p_peer_id); +} + +Dictionary WebRTCMultiplayer::get_peer(int p_peer_id) { + ERR_FAIL_COND_V(!peer_map.has(p_peer_id), Dictionary()); + Dictionary out; + _peer_to_dict(peer_map[p_peer_id], out); + return out; +} + +Dictionary WebRTCMultiplayer::get_peers() { + Dictionary out; + for (Map<int, Ref<ConnectedPeer> >::Element *E = peer_map.front(); E; E = E->next()) { + Dictionary d; + _peer_to_dict(E->get(), d); + out[E->key()] = d; + } + return out; +} + +Error WebRTCMultiplayer::add_peer(Ref<WebRTCPeerConnection> p_peer, int p_peer_id, int p_unreliable_lifetime) { + ERR_FAIL_COND_V(p_peer_id < 0 || p_peer_id > ~(1 << 31), ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(p_unreliable_lifetime < 0, ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(refuse_connections, ERR_UNAUTHORIZED); + // Peer must be valid, and in new state (to create data channels) + ERR_FAIL_COND_V(!p_peer.is_valid(), ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(p_peer->get_connection_state() != WebRTCPeerConnection::STATE_NEW, ERR_INVALID_PARAMETER); + + Ref<ConnectedPeer> peer = memnew(ConnectedPeer); + peer->connection = p_peer; + + // Initialize data channels + Dictionary cfg; + cfg["negotiated"] = true; + cfg["ordered"] = true; + + cfg["id"] = 1; + peer->channels[CH_RELIABLE] = p_peer->create_data_channel("reliable", cfg); + ERR_FAIL_COND_V(!peer->channels[CH_RELIABLE].is_valid(), FAILED); + + cfg["id"] = 2; + cfg["maxPacketLifetime"] = p_unreliable_lifetime; + peer->channels[CH_ORDERED] = p_peer->create_data_channel("ordered", cfg); + ERR_FAIL_COND_V(!peer->channels[CH_ORDERED].is_valid(), FAILED); + + cfg["id"] = 3; + cfg["ordered"] = false; + peer->channels[CH_UNRELIABLE] = p_peer->create_data_channel("unreliable", cfg); + ERR_FAIL_COND_V(!peer->channels[CH_UNRELIABLE].is_valid(), FAILED); + + peer_map[p_peer_id] = peer; // add the new peer connection to the peer_map + + return OK; +} + +void WebRTCMultiplayer::remove_peer(int p_peer_id) { + ERR_FAIL_COND(!peer_map.has(p_peer_id)); + Ref<ConnectedPeer> peer = peer_map[p_peer_id]; + peer_map.erase(p_peer_id); + if (peer->connected) { + peer->connected = false; + emit_signal("peer_disconnected", p_peer_id); + if (server_compat && p_peer_id == TARGET_PEER_SERVER) { + emit_signal("server_disconnected"); + connection_status = CONNECTION_DISCONNECTED; + } + } +} + +Error WebRTCMultiplayer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) { + // Peer not available + if (next_packet_peer == 0 || !peer_map.has(next_packet_peer)) { + _find_next_peer(); + ERR_FAIL_V(ERR_UNAVAILABLE); + } + for (List<Ref<WebRTCDataChannel> >::Element *E = peer_map[next_packet_peer]->channels.front(); E; E = E->next()) { + if (E->get()->get_available_packet_count()) { + Error err = E->get()->get_packet(r_buffer, r_buffer_size); + _find_next_peer(); + return err; + } + } + // Channels for that peer were empty. Bug? + _find_next_peer(); + ERR_FAIL_V(ERR_BUG); +} + +Error WebRTCMultiplayer::put_packet(const uint8_t *p_buffer, int p_buffer_size) { + ERR_FAIL_COND_V(connection_status == CONNECTION_DISCONNECTED, ERR_UNCONFIGURED); + + int ch = CH_RELIABLE; + switch (transfer_mode) { + case TRANSFER_MODE_RELIABLE: + ch = CH_RELIABLE; + break; + case TRANSFER_MODE_UNRELIABLE_ORDERED: + ch = CH_ORDERED; + break; + case TRANSFER_MODE_UNRELIABLE: + ch = CH_UNRELIABLE; + break; + } + + Map<int, Ref<ConnectedPeer> >::Element *E = NULL; + + if (target_peer > 0) { + + E = peer_map.find(target_peer); + if (!E) { + ERR_EXPLAIN("Invalid Target Peer: " + itos(target_peer)); + ERR_FAIL_V(ERR_INVALID_PARAMETER); + } + ERR_FAIL_COND_V(E->value()->channels.size() <= ch, ERR_BUG); + ERR_FAIL_COND_V(!E->value()->channels[ch].is_valid(), ERR_BUG); + return E->value()->channels[ch]->put_packet(p_buffer, p_buffer_size); + + } else { + int exclude = -target_peer; + + for (Map<int, Ref<ConnectedPeer> >::Element *F = peer_map.front(); F; F = F->next()) { + + // Exclude packet. If target_peer == 0 then don't exclude any packets + if (target_peer != 0 && F->key() == exclude) + continue; + + ERR_CONTINUE(F->value()->channels.size() <= ch || !F->value()->channels[ch].is_valid()); + F->value()->channels[ch]->put_packet(p_buffer, p_buffer_size); + } + } + return OK; +} + +int WebRTCMultiplayer::get_available_packet_count() const { + if (next_packet_peer == 0) + return 0; // To be sure next call to get_packet works if size > 0 . + int size = 0; + for (Map<int, Ref<ConnectedPeer> >::Element *E = peer_map.front(); E; E = E->next()) { + for (List<Ref<WebRTCDataChannel> >::Element *F = E->get()->channels.front(); F; F = F->next()) { + size += F->get()->get_available_packet_count(); + } + } + return size; +} + +int WebRTCMultiplayer::get_max_packet_size() const { + return 1200; +} + +void WebRTCMultiplayer::close() { + peer_map.clear(); + unique_id = 0; + next_packet_peer = 0; + target_peer = 0; + connection_status = CONNECTION_DISCONNECTED; +} + +WebRTCMultiplayer::WebRTCMultiplayer() { + unique_id = 0; + next_packet_peer = 0; + target_peer = 0; + transfer_mode = TRANSFER_MODE_RELIABLE; + refuse_connections = false; + connection_status = CONNECTION_DISCONNECTED; + server_compat = false; +} + +WebRTCMultiplayer::~WebRTCMultiplayer() { + close(); +} diff --git a/modules/webrtc/webrtc_multiplayer.h b/modules/webrtc/webrtc_multiplayer.h new file mode 100644 index 0000000000..82bbfd4f68 --- /dev/null +++ b/modules/webrtc/webrtc_multiplayer.h @@ -0,0 +1,116 @@ +/*************************************************************************/ +/* webrtc_multiplayer.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#ifndef WEBRTC_MULTIPLAYER_H +#define WEBRTC_MULTIPLAYER_H + +#include "core/io/networked_multiplayer_peer.h" +#include "webrtc_peer_connection.h" + +class WebRTCMultiplayer : public NetworkedMultiplayerPeer { + + GDCLASS(WebRTCMultiplayer, NetworkedMultiplayerPeer); + +protected: + static void _bind_methods(); + +private: + enum { + CH_RELIABLE = 0, + CH_ORDERED = 1, + CH_UNRELIABLE = 2, + CH_RESERVED_MAX = 3 + }; + + class ConnectedPeer : public Reference { + + public: + Ref<WebRTCPeerConnection> connection; + List<Ref<WebRTCDataChannel> > channels; + bool connected; + + ConnectedPeer() { + connected = false; + for (int i = 0; i < CH_RESERVED_MAX; i++) + channels.push_front(Ref<WebRTCDataChannel>()); + } + }; + + uint32_t unique_id; + int target_peer; + int client_count; + bool refuse_connections; + ConnectionStatus connection_status; + TransferMode transfer_mode; + int next_packet_peer; + bool server_compat; + + Map<int, Ref<ConnectedPeer> > peer_map; + + void _peer_to_dict(Ref<ConnectedPeer> p_connected_peer, Dictionary &r_dict); + void _find_next_peer(); + +public: + WebRTCMultiplayer(); + ~WebRTCMultiplayer(); + + Error initialize(int p_self_id, bool p_server_compat = false); + Error add_peer(Ref<WebRTCPeerConnection> p_peer, int p_peer_id, int p_unreliable_lifetime = 1); + void remove_peer(int p_peer_id); + bool has_peer(int p_peer_id); + Dictionary get_peer(int p_peer_id); + Dictionary get_peers(); + void close(); + + // PacketPeer + Error get_packet(const uint8_t **r_buffer, int &r_buffer_size); ///< buffer is GONE after next get_packet + Error put_packet(const uint8_t *p_buffer, int p_buffer_size); + int get_available_packet_count() const; + int get_max_packet_size() const; + + // NetworkedMultiplayerPeer + void set_transfer_mode(TransferMode p_mode); + TransferMode get_transfer_mode() const; + void set_target_peer(int p_peer_id); + + int get_unique_id() const; + int get_packet_peer() const; + + bool is_server() const; + + void poll(); + + void set_refuse_new_connections(bool p_enable); + bool is_refusing_new_connections() const; + + ConnectionStatus get_connection_status() const; +}; + +#endif diff --git a/scene/2d/cpu_particles_2d.cpp b/scene/2d/cpu_particles_2d.cpp index 2b1009a2d1..536a05dceb 100644 --- a/scene/2d/cpu_particles_2d.cpp +++ b/scene/2d/cpu_particles_2d.cpp @@ -29,8 +29,9 @@ /*************************************************************************/ #include "cpu_particles_2d.h" -#include "particles_2d.h" + #include "scene/2d/canvas_item.h" +#include "scene/2d/particles_2d.h" #include "scene/resources/particles_material.h" #include "servers/visual_server.h" @@ -324,9 +325,9 @@ void CPUParticles2D::set_param_curve(Parameter p_param, const Ref<Curve> &p_curv case PARAM_ANGULAR_VELOCITY: { _adjust_curve_range(p_curve, -360, 360); } break; - /*case PARAM_ORBIT_VELOCITY: { + case PARAM_ORBIT_VELOCITY: { _adjust_curve_range(p_curve, -500, 500); - } break;*/ + } break; case PARAM_LINEAR_ACCEL: { _adjust_curve_range(p_curve, -200, 200); } break; @@ -489,12 +490,6 @@ void CPUParticles2D::_validate_property(PropertyInfo &property) const { if (property.name == "emission_colors" && emission_shape != EMISSION_SHAPE_POINTS && emission_shape != EMISSION_SHAPE_DIRECTED_POINTS) { property.usage = 0; } - - /* - if (property.name.begins_with("orbit_") && !flags[FLAG_DISABLE_Z]) { - property.usage = 0; - } - */ } static uint32_t idhash(uint32_t x) { @@ -695,16 +690,12 @@ void CPUParticles2D::_particles_process(float p_delta) { if (curve_parameters[PARAM_INITIAL_LINEAR_VELOCITY].is_valid()) { tex_linear_velocity = curve_parameters[PARAM_INITIAL_LINEAR_VELOCITY]->interpolate(p.custom[1]); } - /* - float tex_orbit_velocity = 0.0; - if (flags[FLAG_DISABLE_Z]) { - - if (curve_parameters[PARAM_INITIAL_ORBIT_VELOCITY].is_valid()) { - tex_orbit_velocity = curve_parameters[PARAM_INITIAL_ORBIT_VELOCITY]->interpolate(p.custom[1]); - } + float tex_orbit_velocity = 0.0; + if (curve_parameters[PARAM_ORBIT_VELOCITY].is_valid()) { + tex_orbit_velocity = curve_parameters[PARAM_ORBIT_VELOCITY]->interpolate(p.custom[1]); } -*/ + float tex_angular_velocity = 0.0; if (curve_parameters[PARAM_ANGULAR_VELOCITY].is_valid()) { tex_angular_velocity = curve_parameters[PARAM_ANGULAR_VELOCITY]->interpolate(p.custom[1]); @@ -759,18 +750,15 @@ void CPUParticles2D::_particles_process(float p_delta) { //apply attractor forces p.velocity += force * local_delta; //orbit velocity -#if 0 - if (flags[FLAG_DISABLE_Z]) { - - float orbit_amount = (orbit_velocity + tex_orbit_velocity) * mix(1.0, rand_from_seed(alt_seed), orbit_velocity_random); - if (orbit_amount != 0.0) { - float ang = orbit_amount * DELTA * pi * 2.0; - mat2 rot = mat2(vec2(cos(ang), -sin(ang)), vec2(sin(ang), cos(ang))); - TRANSFORM[3].xy -= diff.xy; - TRANSFORM[3].xy += rot * diff.xy; - } + float orbit_amount = (parameters[PARAM_ORBIT_VELOCITY] + tex_orbit_velocity) * Math::lerp(1.0f, rand_from_seed(alt_seed), randomness[PARAM_ORBIT_VELOCITY]); + if (orbit_amount != 0.0) { + float ang = orbit_amount * local_delta * Math_PI * 2.0; + // Not sure why the ParticlesMaterial code uses a clockwise rotation matrix, + // but we use -ang here to reproduce its behavior. + Transform2D rot = Transform2D(-ang, Vector2()); + p.transform[2] -= diff; + p.transform[2] += rot.basis_xform(diff); } -#endif if (curve_parameters[PARAM_INITIAL_LINEAR_VELOCITY].is_valid()) { p.velocity = p.velocity.normalized() * tex_linear_velocity; } @@ -1271,12 +1259,10 @@ void CPUParticles2D::_bind_methods() { ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_velocity", PROPERTY_HINT_RANGE, "-720,720,0.01,or_lesser,or_greater"), "set_param", "get_param", PARAM_ANGULAR_VELOCITY); ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_velocity_random", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_param_randomness", "get_param_randomness", PARAM_ANGULAR_VELOCITY); ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "angular_velocity_curve", PROPERTY_HINT_RESOURCE_TYPE, "Curve"), "set_param_curve", "get_param_curve", PARAM_ANGULAR_VELOCITY); - /* ADD_GROUP("Orbit Velocity", "orbit_"); ADD_PROPERTYI(PropertyInfo(Variant::REAL, "orbit_velocity", PROPERTY_HINT_RANGE, "-1000,1000,0.01,or_lesser,or_greater"), "set_param", "get_param", PARAM_ORBIT_VELOCITY); ADD_PROPERTYI(PropertyInfo(Variant::REAL, "orbit_velocity_random", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_param_randomness", "get_param_randomness", PARAM_ORBIT_VELOCITY); ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "orbit_velocity_curve", PROPERTY_HINT_RESOURCE_TYPE, "Curve"), "set_param_curve", "get_param_curve", PARAM_ORBIT_VELOCITY); -*/ ADD_GROUP("Linear Accel", "linear_"); ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_accel", PROPERTY_HINT_RANGE, "-100,100,0.01,or_lesser,or_greater"), "set_param", "get_param", PARAM_LINEAR_ACCEL); ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_accel_random", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_param_randomness", "get_param_randomness", PARAM_LINEAR_ACCEL); @@ -1332,6 +1318,8 @@ void CPUParticles2D::_bind_methods() { BIND_ENUM_CONSTANT(PARAM_MAX); BIND_ENUM_CONSTANT(FLAG_ALIGN_Y_TO_VELOCITY); + BIND_ENUM_CONSTANT(FLAG_ROTATE_Y); // Unused, but exposed for consistency with 3D. + BIND_ENUM_CONSTANT(FLAG_DISABLE_Z); // Unused, but exposed for consistency with 3D. BIND_ENUM_CONSTANT(FLAG_MAX); BIND_ENUM_CONSTANT(EMISSION_SHAPE_POINT); @@ -1370,7 +1358,7 @@ CPUParticles2D::CPUParticles2D() { set_spread(45); set_flatness(0); set_param(PARAM_INITIAL_LINEAR_VELOCITY, 1); - //set_param(PARAM_ORBIT_VELOCITY, 0); + set_param(PARAM_ORBIT_VELOCITY, 0); set_param(PARAM_LINEAR_ACCEL, 0); set_param(PARAM_ANGULAR_VELOCITY, 0); set_param(PARAM_RADIAL_ACCEL, 0); diff --git a/scene/2d/cpu_particles_2d.h b/scene/2d/cpu_particles_2d.h index 81343a4604..79444407ee 100644 --- a/scene/2d/cpu_particles_2d.h +++ b/scene/2d/cpu_particles_2d.h @@ -68,6 +68,8 @@ public: enum Flags { FLAG_ALIGN_Y_TO_VELOCITY, + FLAG_ROTATE_Y, // Unused, but exposed for consistency with 3D. + FLAG_DISABLE_Z, // Unused, but exposed for consistency with 3D. FLAG_MAX }; diff --git a/scene/3d/cpu_particles.cpp b/scene/3d/cpu_particles.cpp index a81071492b..b42649b35a 100644 --- a/scene/3d/cpu_particles.cpp +++ b/scene/3d/cpu_particles.cpp @@ -302,9 +302,9 @@ void CPUParticles::set_param_curve(Parameter p_param, const Ref<Curve> &p_curve) case PARAM_ANGULAR_VELOCITY: { _adjust_curve_range(p_curve, -360, 360); } break; - /*case PARAM_ORBIT_VELOCITY: { + case PARAM_ORBIT_VELOCITY: { _adjust_curve_range(p_curve, -500, 500); - } break;*/ + } break; case PARAM_LINEAR_ACCEL: { _adjust_curve_range(p_curve, -200, 200); } break; @@ -461,11 +461,10 @@ void CPUParticles::_validate_property(PropertyInfo &property) const { if (property.name == "emission_normals" && emission_shape != EMISSION_SHAPE_DIRECTED_POINTS) { property.usage = 0; } - /* + if (property.name.begins_with("orbit_") && !flags[FLAG_DISABLE_Z]) { property.usage = 0; } - */ } static uint32_t idhash(uint32_t x) { @@ -698,16 +697,14 @@ void CPUParticles::_particles_process(float p_delta) { if (curve_parameters[PARAM_INITIAL_LINEAR_VELOCITY].is_valid()) { tex_linear_velocity = curve_parameters[PARAM_INITIAL_LINEAR_VELOCITY]->interpolate(p.custom[1]); } - /* - float tex_orbit_velocity = 0.0; + float tex_orbit_velocity = 0.0; if (flags[FLAG_DISABLE_Z]) { - - if (curve_parameters[PARAM_INITIAL_ORBIT_VELOCITY].is_valid()) { - tex_orbit_velocity = curve_parameters[PARAM_INITIAL_ORBIT_VELOCITY]->interpolate(p.custom[1]); + if (curve_parameters[PARAM_ORBIT_VELOCITY].is_valid()) { + tex_orbit_velocity = curve_parameters[PARAM_ORBIT_VELOCITY]->interpolate(p.custom[1]); } } -*/ + float tex_angular_velocity = 0.0; if (curve_parameters[PARAM_ANGULAR_VELOCITY].is_valid()) { tex_angular_velocity = curve_parameters[PARAM_ANGULAR_VELOCITY]->interpolate(p.custom[1]); @@ -772,18 +769,18 @@ void CPUParticles::_particles_process(float p_delta) { //apply attractor forces p.velocity += force * local_delta; //orbit velocity -#if 0 if (flags[FLAG_DISABLE_Z]) { - - float orbit_amount = (orbit_velocity + tex_orbit_velocity) * mix(1.0, rand_from_seed(alt_seed), orbit_velocity_random); + float orbit_amount = (parameters[PARAM_ORBIT_VELOCITY] + tex_orbit_velocity) * Math::lerp(1.0f, rand_from_seed(alt_seed), randomness[PARAM_ORBIT_VELOCITY]); if (orbit_amount != 0.0) { - float ang = orbit_amount * DELTA * pi * 2.0; - mat2 rot = mat2(vec2(cos(ang), -sin(ang)), vec2(sin(ang), cos(ang))); - TRANSFORM[3].xy -= diff.xy; - TRANSFORM[3].xy += rot * diff.xy; + float ang = orbit_amount * local_delta * Math_PI * 2.0; + // Not sure why the ParticlesMaterial code uses a clockwise rotation matrix, + // but we use -ang here to reproduce its behavior. + Transform2D rot = Transform2D(-ang, Vector2()); + Vector2 rotv = rot.basis_xform(Vector2(diff.x, diff.y)); + p.transform.origin -= Vector3(diff.x, diff.y, 0); + p.transform.origin += Vector3(rotv.x, rotv.y, 0); } } -#endif if (curve_parameters[PARAM_INITIAL_LINEAR_VELOCITY].is_valid()) { p.velocity = p.velocity.normalized() * tex_linear_velocity; } @@ -1179,7 +1176,7 @@ void CPUParticles::convert_from_particles(Node *p_particles) { CONVERT_PARAM(PARAM_INITIAL_LINEAR_VELOCITY); CONVERT_PARAM(PARAM_ANGULAR_VELOCITY); - // CONVERT_PARAM(PARAM_ORBIT_VELOCITY); + CONVERT_PARAM(PARAM_ORBIT_VELOCITY); CONVERT_PARAM(PARAM_LINEAR_ACCEL); CONVERT_PARAM(PARAM_RADIAL_ACCEL); CONVERT_PARAM(PARAM_TANGENTIAL_ACCEL); @@ -1322,12 +1319,10 @@ void CPUParticles::_bind_methods() { ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_velocity", PROPERTY_HINT_RANGE, "-720,720,0.01,or_lesser,or_greater"), "set_param", "get_param", PARAM_ANGULAR_VELOCITY); ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_velocity_random", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_param_randomness", "get_param_randomness", PARAM_ANGULAR_VELOCITY); ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "angular_velocity_curve", PROPERTY_HINT_RESOURCE_TYPE, "Curve"), "set_param_curve", "get_param_curve", PARAM_ANGULAR_VELOCITY); - /* ADD_GROUP("Orbit Velocity", "orbit_"); ADD_PROPERTYI(PropertyInfo(Variant::REAL, "orbit_velocity", PROPERTY_HINT_RANGE, "-1000,1000,0.01,or_lesser,or_greater"), "set_param", "get_param", PARAM_ORBIT_VELOCITY); ADD_PROPERTYI(PropertyInfo(Variant::REAL, "orbit_velocity_random", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_param_randomness", "get_param_randomness", PARAM_ORBIT_VELOCITY); ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "orbit_velocity_curve", PROPERTY_HINT_RESOURCE_TYPE, "Curve"), "set_param_curve", "get_param_curve", PARAM_ORBIT_VELOCITY); -*/ ADD_GROUP("Linear Accel", "linear_"); ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_accel", PROPERTY_HINT_RANGE, "-100,100,0.01,or_lesser,or_greater"), "set_param", "get_param", PARAM_LINEAR_ACCEL); ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_accel_random", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_param_randomness", "get_param_randomness", PARAM_LINEAR_ACCEL); @@ -1370,7 +1365,7 @@ void CPUParticles::_bind_methods() { BIND_ENUM_CONSTANT(PARAM_INITIAL_LINEAR_VELOCITY); BIND_ENUM_CONSTANT(PARAM_ANGULAR_VELOCITY); - //BIND_ENUM_CONSTANT(PARAM_ORBIT_VELOCITY); + BIND_ENUM_CONSTANT(PARAM_ORBIT_VELOCITY); BIND_ENUM_CONSTANT(PARAM_LINEAR_ACCEL); BIND_ENUM_CONSTANT(PARAM_RADIAL_ACCEL); BIND_ENUM_CONSTANT(PARAM_TANGENTIAL_ACCEL); @@ -1384,6 +1379,7 @@ void CPUParticles::_bind_methods() { BIND_ENUM_CONSTANT(FLAG_ALIGN_Y_TO_VELOCITY); BIND_ENUM_CONSTANT(FLAG_ROTATE_Y); + BIND_ENUM_CONSTANT(FLAG_DISABLE_Z); BIND_ENUM_CONSTANT(FLAG_MAX); BIND_ENUM_CONSTANT(EMISSION_SHAPE_POINT); @@ -1422,7 +1418,7 @@ CPUParticles::CPUParticles() { set_spread(45); set_flatness(0); set_param(PARAM_INITIAL_LINEAR_VELOCITY, 1); - //set_param(PARAM_ORBIT_VELOCITY, 0); + set_param(PARAM_ORBIT_VELOCITY, 0); set_param(PARAM_LINEAR_ACCEL, 0); set_param(PARAM_RADIAL_ACCEL, 0); set_param(PARAM_TANGENTIAL_ACCEL, 0); diff --git a/scene/3d/cpu_particles.h b/scene/3d/cpu_particles.h index b863a3cb3f..6a989251f1 100644 --- a/scene/3d/cpu_particles.h +++ b/scene/3d/cpu_particles.h @@ -53,7 +53,7 @@ public: PARAM_INITIAL_LINEAR_VELOCITY, PARAM_ANGULAR_VELOCITY, - //PARAM_ORBIT_VELOCITY, + PARAM_ORBIT_VELOCITY, PARAM_LINEAR_ACCEL, PARAM_RADIAL_ACCEL, PARAM_TANGENTIAL_ACCEL, |