diff options
120 files changed, 4941 insertions, 3425 deletions
diff --git a/core/core_bind.cpp b/core/core_bind.cpp index 46f05bdaf5..a84a208050 100644 --- a/core/core_bind.cpp +++ b/core/core_bind.cpp @@ -587,10 +587,7 @@ void _OS::print_resources_by_type(const Vector<String> &p_types) { List<Ref<Resource>> resources; ResourceCache::get_cached_resources(&resources); - List<Ref<Resource>> rsrc; - ResourceCache::get_cached_resources(&rsrc); - - for (List<Ref<Resource>>::Element *E = rsrc.front(); E; E = E->next()) { + for (List<Ref<Resource>>::Element *E = resources.front(); E; E = E->next()) { Ref<Resource> r = E->get(); bool found = false; diff --git a/doc/classes/@GlobalScope.xml b/doc/classes/@GlobalScope.xml index c8f216e199..b40ae65a61 100644 --- a/doc/classes/@GlobalScope.xml +++ b/doc/classes/@GlobalScope.xml @@ -944,6 +944,22 @@ [/codeblock] </description> </method> + <method name="snapped"> + <return type="float"> + </return> + <argument index="0" name="x" type="float"> + </argument> + <argument index="1" name="step" type="float"> + </argument> + <description> + Snaps float value [code]x[/code] to a given [code]step[/code]. This can also be used to round a floating point number to an arbitrary number of decimals. + [codeblock] + snapped(100, 32) # Returns 96 + snapped(3.14159, 0.01) # Returns 3.14 + [/codeblock] + See also [method ceil], [method floor], and [method round]. + </description> + </method> <method name="sqrt"> <return type="float"> </return> @@ -974,22 +990,6 @@ [/codeblock] </description> </method> - <method name="snapped"> - <return type="float"> - </return> - <argument index="0" name="x" type="float"> - </argument> - <argument index="1" name="step" type="float"> - </argument> - <description> - Snaps float value [code]x[/code] to a given [code]step[/code]. This can also be used to round a floating point number to an arbitrary number of decimals. - [codeblock] - snapped(100, 32) # Returns 96 - snapped(3.14159, 0.01) # Returns 3.14 - [/codeblock] - See also [method ceil], [method floor], and [method round]. - </description> - </method> <method name="str" qualifiers="vararg"> <return type="String"> </return> diff --git a/doc/classes/AABB.xml b/doc/classes/AABB.xml index baea84df65..8cd7e6f5fa 100644 --- a/doc/classes/AABB.xml +++ b/doc/classes/AABB.xml @@ -219,7 +219,7 @@ <argument index="0" name="aabb" type="AABB"> </argument> <description> - Returns [code]true[/code] if this [AABB] and [code]aabb[/code] are approximately equal, by calling [method @GDScript.is_equal_approx] on each component. + Returns [code]true[/code] if this [AABB] and [code]aabb[/code] are approximately equal, by calling [method @GlobalScope.is_equal_approx] on each component. </description> </method> <method name="merge"> diff --git a/doc/classes/Animation.xml b/doc/classes/Animation.xml index 3e33a879b3..d26c0e8605 100644 --- a/doc/classes/Animation.xml +++ b/doc/classes/Animation.xml @@ -409,7 +409,7 @@ <argument index="1" name="key_idx" type="int"> </argument> <description> - Returns the transition curve (easing) for a specific key (see the built-in math function [method @GDScript.ease]). + Returns the transition curve (easing) for a specific key (see the built-in math function [method @GlobalScope.ease]). </description> </method> <method name="track_get_key_value" qualifiers="const"> @@ -592,7 +592,7 @@ <argument index="2" name="transition" type="float"> </argument> <description> - Sets the transition curve (easing) for a specific key (see the built-in math function [method @GDScript.ease]). + Sets the transition curve (easing) for a specific key (see the built-in math function [method @GlobalScope.ease]). </description> </method> <method name="track_set_key_value"> diff --git a/doc/classes/AnimationNodeStateMachinePlayback.xml b/doc/classes/AnimationNodeStateMachinePlayback.xml index 4dc88ffa56..c8468f9c8f 100644 --- a/doc/classes/AnimationNodeStateMachinePlayback.xml +++ b/doc/classes/AnimationNodeStateMachinePlayback.xml @@ -21,18 +21,17 @@ <link title="AnimationTree">https://docs.godotengine.org/en/latest/tutorials/animation/animation_tree.html</link> </tutorials> <methods> - <method name="get_current_node" qualifiers="const"> - <return type="StringName"> + <method name="get_current_length" qualifiers="const"> + <return type="float"> </return> <description> - Returns the currently playing animation state. </description> </method> - <method name="get_travel_path" qualifiers="const"> - <return type="PackedStringArray"> + <method name="get_current_node" qualifiers="const"> + <return type="StringName"> </return> <description> - Returns the current travel path as computed internally by the A* algorithm. + Returns the currently playing animation state. </description> </method> <method name="get_current_play_position" qualifiers="const"> @@ -42,6 +41,13 @@ Returns the playback position within the current animation state. </description> </method> + <method name="get_travel_path" qualifiers="const"> + <return type="PackedStringArray"> + </return> + <description> + Returns the current travel path as computed internally by the A* algorithm. + </description> + </method> <method name="is_playing" qualifiers="const"> <return type="bool"> </return> diff --git a/doc/classes/Array.xml b/doc/classes/Array.xml index e4f9dcf993..db5d377c62 100644 --- a/doc/classes/Array.xml +++ b/doc/classes/Array.xml @@ -228,13 +228,6 @@ If [code]deep[/code] is [code]true[/code], a deep copy is performed: all nested arrays and dictionaries are duplicated and will not be shared with the original array. If [code]false[/code], a shallow copy is made and references to the original nested arrays and dictionaries are kept, so that modifying a sub-array or dictionary in the copy will also impact those referenced in the source array. </description> </method> - <method name="is_empty"> - <return type="bool"> - </return> - <description> - Returns [code]true[/code] if the array is empty. - </description> - </method> <method name="erase"> <return type="void"> </return> @@ -339,6 +332,13 @@ Reverses the order of the elements in the array. </description> </method> + <method name="is_empty"> + <return type="bool"> + </return> + <description> + Returns [code]true[/code] if the array is empty. + </description> + </method> <method name="max"> <return type="Variant"> </return> @@ -482,7 +482,7 @@ <return type="void"> </return> <description> - Shuffles the array such that the items will have a random order. This method uses the global random number generator common to methods such as [method @GDScript.randi]. Call [method @GDScript.randomize] to ensure that a new seed will be used each time if you want non-reproducible shuffling. + Shuffles the array such that the items will have a random order. This method uses the global random number generator common to methods such as [method @GlobalScope.randi]. Call [method @GlobalScope.randomize] to ensure that a new seed will be used each time if you want non-reproducible shuffling. </description> </method> <method name="size"> diff --git a/doc/classes/ArrayMesh.xml b/doc/classes/ArrayMesh.xml index 59502e7017..1f532f4843 100644 --- a/doc/classes/ArrayMesh.xml +++ b/doc/classes/ArrayMesh.xml @@ -209,19 +209,13 @@ </method> </methods> <members> - <member name="blend_shape_mode" type="int" setter="set_blend_shape_mode" getter="get_blend_shape_mode" enum="ArrayMesh.BlendShapeMode" default="1"> - Sets the blend shape mode to one of [enum ArrayMesh.BlendShapeMode]. + <member name="blend_shape_mode" type="int" setter="set_blend_shape_mode" getter="get_blend_shape_mode" enum="Mesh.BlendShapeMode" default="1"> + Sets the blend shape mode to one of [enum Mesh.BlendShapeMode]. </member> <member name="custom_aabb" type="AABB" setter="set_custom_aabb" getter="get_custom_aabb" default="AABB( 0, 0, 0, 0, 0, 0 )"> Overrides the [AABB] with one defined by user for use with frustum culling. Especially useful to avoid unexpected culling when using a shader to offset vertices. </member> </members> <constants> - <constant name="BLEND_SHAPE_MODE_NORMALIZED" value="0" enum="BlendShapeMode"> - Blend shapes are normalized. - </constant> - <constant name="BLEND_SHAPE_MODE_RELATIVE" value="1" enum="BlendShapeMode"> - Blend shapes are relative to base weight. - </constant> </constants> </class> diff --git a/doc/classes/Camera2D.xml b/doc/classes/Camera2D.xml index f17c56fb11..2a4e726d43 100644 --- a/doc/classes/Camera2D.xml +++ b/doc/classes/Camera2D.xml @@ -52,7 +52,7 @@ <method name="get_drag_margin" qualifiers="const"> <return type="float"> </return> - <argument index="0" name="side" type="int" enum="Side"> + <argument index="0" name="margin" type="int" enum="Side"> </argument> <description> Returns the specified [enum Side]'s margin. See also [member drag_bottom_margin], [member drag_top_margin], [member drag_left_margin], and [member drag_right_margin]. @@ -61,7 +61,7 @@ <method name="get_limit" qualifiers="const"> <return type="int"> </return> - <argument index="0" name="side" type="int" enum="Side"> + <argument index="0" name="margin" type="int" enum="Side"> </argument> <description> Returns the camera limit for the specified [enum Side]. See also [member limit_bottom], [member limit_top], [member limit_left], and [member limit_right]. @@ -85,7 +85,7 @@ <method name="set_drag_margin"> <return type="void"> </return> - <argument index="0" name="side" type="int" enum="Side"> + <argument index="0" name="margin" type="int" enum="Side"> </argument> <argument index="1" name="drag_margin" type="float"> </argument> @@ -96,7 +96,7 @@ <method name="set_limit"> <return type="void"> </return> - <argument index="0" name="side" type="int" enum="Side"> + <argument index="0" name="margin" type="int" enum="Side"> </argument> <argument index="1" name="limit" type="int"> </argument> @@ -118,10 +118,10 @@ <member name="drag_bottom_margin" type="float" setter="set_drag_margin" getter="get_drag_margin" default="0.2"> Bottom margin needed to drag the camera. A value of [code]1[/code] makes the camera move only when reaching the bottom edge of the screen. </member> - <member name="drag_horizontal_enabled" type="bool" setter="set_h_drag_enabled" getter="is_h_drag_enabled" default="false"> + <member name="drag_horizontal_enabled" type="bool" setter="set_drag_horizontal_enabled" getter="is_drag_horizontal_enabled" default="false"> If [code]true[/code], the camera only moves when reaching the horizontal (left and right) drag margins. If [code]false[/code], the camera moves horizontally regardless of margins. </member> - <member name="drag_horizontal_offset" type="float" setter="set_h_offset" getter="get_h_offset" default="0.0"> + <member name="drag_horizontal_offset" type="float" setter="set_drag_horizontal_offset" getter="get_drag_horizontal_offset" default="0.0"> The relative horizontal drag offset of the camera between the right ([code]-1[/code]) and left ([code]1[/code]) drag margins. [b]Note:[/b] Used to set the initial horizontal drag offset; determine the current offset; or force the current offset. It's not automatically updated when the horizontal drag margin is enabled or the drag margins are changed. </member> @@ -137,7 +137,7 @@ <member name="drag_vertical_enabled" type="bool" setter="set_drag_vertical_enabled" getter="is_drag_vertical_enabled" default="false"> If [code]true[/code], the camera only moves when reaching the vertical (top and bottom) drag margins. If [code]false[/code], the camera moves vertically regardless of the drag margins. </member> - <member name="drag_vertical_offset" type="float" setter="set_drag_verticaloffset" getter="get_drag_vertical_offset" default="0.0"> + <member name="drag_vertical_offset" type="float" setter="set_drag_vertical_offset" getter="get_drag_vertical_offset" default="0.0"> The relative vertical drag offset of the camera between the bottom ([code]-1[/code]) and top ([code]1[/code]) drag margins. [b]Note:[/b] Used to set the initial vertical drag offset; determine the current offset; or force the current offset. It's not automatically updated when the vertical drag margin is enabled or the drag margins are changed. </member> diff --git a/doc/classes/CanvasItem.xml b/doc/classes/CanvasItem.xml index fcdd072c80..d13f431a16 100644 --- a/doc/classes/CanvasItem.xml +++ b/doc/classes/CanvasItem.xml @@ -9,7 +9,7 @@ Canvas items are drawn in tree order. By default, children are on top of their parents so a root [CanvasItem] will be drawn behind everything. This behavior can be changed on a per-item basis. A [CanvasItem] can also be hidden, which will also hide its children. It provides many ways to change parameters such as modulation (for itself and its children) and self modulation (only for itself), as well as its blend mode. Ultimately, a transform notification can be requested, which will notify the node that its global position changed in case the parent tree changed. - [b]Note:[/b] Unless otherwise specified, all methods that have angle parameters must have angles specified as [i]radians[/i]. To convert degrees to radians, use [method @GDScript.deg2rad]. + [b]Note:[/b] Unless otherwise specified, all methods that have angle parameters must have angles specified as [i]radians[/i]. To convert degrees to radians, use [method @GlobalScope.deg2rad]. </description> <tutorials> <link title="Viewport and canvas transforms">https://docs.godotengine.org/en/latest/tutorials/2d/2d_transforms.html</link> diff --git a/doc/classes/Color.xml b/doc/classes/Color.xml index 755fd7eea2..8af5f29b65 100644 --- a/doc/classes/Color.xml +++ b/doc/classes/Color.xml @@ -5,7 +5,7 @@ </brief_description> <description> A color represented by red, green, blue, and alpha (RGBA) components. The alpha component is often used for transparency. Values are in floating-point and usually range from 0 to 1. Some properties (such as CanvasItem.modulate) may accept values greater than 1 (overbright or HDR colors). - You can also create a color from standardized color names by using [method @GDScript.ColorN] or directly using the color constants defined here. The standardized color set is based on the [url=https://en.wikipedia.org/wiki/X11_color_names]X11 color names[/url]. + You can also create a color from standardized color names by using [code]ColorN[/code] ([b]FIXME:[/b] No longer true, a Color(String) constructor should be re-implemented for that) or directly using the color constants defined here. The standardized color set is based on the [url=https://en.wikipedia.org/wiki/X11_color_names]X11 color names[/url]. If you want to supply values in a range of 0 to 255, you should use [method @GDScript.Color8]. [b]Note:[/b] In a boolean context, a Color will evaluate to [code]false[/code] if it's equal to [code]Color(0, 0, 0, 1)[/code] (opaque black). Otherwise, a Color will always evaluate to [code]true[/code]. [url=https://raw.githubusercontent.com/godotengine/godot-docs/master/img/color_constants.png]Color constants cheatsheet[/url] @@ -158,7 +158,7 @@ <argument index="0" name="to" type="Color"> </argument> <description> - Returns [code]true[/code] if this color and [code]color[/code] are approximately equal, by running [method @GDScript.is_equal_approx] on each component. + Returns [code]true[/code] if this color and [code]color[/code] are approximately equal, by running [method @GlobalScope.is_equal_approx] on each component. </description> </method> <method name="lerp"> diff --git a/doc/classes/Control.xml b/doc/classes/Control.xml index c3db716d3a..533748aced 100644 --- a/doc/classes/Control.xml +++ b/doc/classes/Control.xml @@ -213,17 +213,6 @@ Overrides the icon with given [code]name[/code] in the [member theme] resource the control uses. If [code]icon[/code] is [code]null[/code] or invalid, the override is cleared and the icon from assigned [Theme] is used. </description> </method> - <method name="add_theme_shader_override"> - <return type="void"> - </return> - <argument index="0" name="name" type="StringName"> - </argument> - <argument index="1" name="shader" type="Shader"> - </argument> - <description> - Overrides the [Shader] with given [code]name[/code] in the [member theme] resource the control uses. If [code]shader[/code] is [code]null[/code] or invalid, the override is cleared and the shader from assigned [Theme] is used. - </description> - </method> <method name="add_theme_stylebox_override"> <return type="void"> </return> @@ -417,20 +406,20 @@ Returns the position and size of the control relative to the top-left corner of the screen. See [member rect_position] and [member rect_size]. </description> </method> - <method name="get_offset" qualifiers="const"> - <return type="float"> + <method name="get_minimum_size" qualifiers="const"> + <return type="Vector2"> </return> - <argument index="0" name="side" type="int" enum="Side"> - </argument> <description> - Returns the anchor for the specified [enum Side]. A getter method for [member offset_bottom], [member offset_left], [member offset_right] and [member offset_top]. + Returns the minimum size for this control. See [member rect_min_size]. </description> </method> - <method name="get_minimum_size" qualifiers="const"> - <return type="Vector2"> + <method name="get_offset" qualifiers="const"> + <return type="float"> </return> + <argument index="0" name="offset" type="int" enum="Side"> + </argument> <description> - Returns the minimum size for this control. See [member rect_min_size]. + Returns the anchor for the specified [enum Side]. A getter method for [member offset_bottom], [member offset_left], [member offset_right] and [member offset_top]. </description> </method> <method name="get_parent_area_size" qualifiers="const"> @@ -685,15 +674,6 @@ Returns [code]true[/code] if icon with given [code]name[/code] has a valid override in this [Control] node. </description> </method> - <method name="has_theme_shader_override" qualifiers="const"> - <return type="bool"> - </return> - <argument index="0" name="name" type="StringName"> - </argument> - <description> - Returns [code]true[/code] if [Shader] with given [code]name[/code] has a valid override in this [Control] node. - </description> - </method> <method name="has_theme_stylebox" qualifiers="const"> <return type="bool"> </return> @@ -1063,6 +1043,13 @@ <member name="layout_direction" type="int" setter="set_layout_direction" getter="get_layout_direction" enum="Control.LayoutDirection" default="0"> Controls layout direction and text writing direction. Right-to-left layouts are necessary for certain languages (e.g. Arabic and Hebrew). </member> + <member name="mouse_default_cursor_shape" type="int" setter="set_default_cursor_shape" getter="get_default_cursor_shape" enum="Control.CursorShape" default="0"> + The default cursor shape for this control. Useful for Godot plugins and applications or games that use the system's mouse cursors. + [b]Note:[/b] On Linux, shapes may vary depending on the cursor theme of the system. + </member> + <member name="mouse_filter" type="int" setter="set_mouse_filter" getter="get_mouse_filter" enum="Control.MouseFilter" default="0"> + Controls whether the control will be able to receive mouse button input events through [method _gui_input] and how these events should be handled. Also controls whether the control can receive the [signal mouse_entered], and [signal mouse_exited] signals. See the constants to learn what each does. + </member> <member name="offset_bottom" type="float" setter="set_offset" getter="get_offset" default="0.0"> Distance between the node's bottom edge and its parent control, based on [member anchor_bottom]. Offsets are often controlled by one or multiple parent [Container] nodes, so you should not modify them manually if your node is a direct child of a [Container]. Offsets update automatically when you move or resize the node. @@ -1079,13 +1066,6 @@ Distance between the node's top edge and its parent control, based on [member anchor_top]. Offsets are often controlled by one or multiple parent [Container] nodes, so you should not modify them manually if your node is a direct child of a [Container]. Offsets update automatically when you move or resize the node. </member> - <member name="mouse_default_cursor_shape" type="int" setter="set_default_cursor_shape" getter="get_default_cursor_shape" enum="Control.CursorShape" default="0"> - The default cursor shape for this control. Useful for Godot plugins and applications or games that use the system's mouse cursors. - [b]Note:[/b] On Linux, shapes may vary depending on the cursor theme of the system. - </member> - <member name="mouse_filter" type="int" setter="set_mouse_filter" getter="get_mouse_filter" enum="Control.MouseFilter" default="0"> - Controls whether the control will be able to receive mouse button input events through [method _gui_input] and how these events should be handled. Also controls whether the control can receive the [signal mouse_entered], and [signal mouse_exited] signals. See the constants to learn what each does. - </member> <member name="rect_clip_content" type="bool" setter="set_clip_contents" getter="is_clipping_contents" default="false"> Enables whether rendering of [CanvasItem] based children should be clipped to this control's rectangle. If [code]true[/code], parts of a child which would be visibly outside of this control's rectangle will not be rendered. </member> diff --git a/doc/classes/Dictionary.xml b/doc/classes/Dictionary.xml index 2ca705cec7..d3fcbc9f64 100644 --- a/doc/classes/Dictionary.xml +++ b/doc/classes/Dictionary.xml @@ -215,13 +215,6 @@ Creates a copy of the dictionary, and returns it. The [code]deep[/code] parameter causes inner dictionaries and arrays to be copied recursively, but does not apply to objects. </description> </method> - <method name="is_empty"> - <return type="bool"> - </return> - <description> - Returns [code]true[/code] if the dictionary is empty. - </description> - </method> <method name="erase"> <return type="bool"> </return> @@ -299,6 +292,13 @@ [b]Note:[/b] Dictionaries with the same keys/values but in a different order will have a different hash. </description> </method> + <method name="is_empty"> + <return type="bool"> + </return> + <description> + Returns [code]true[/code] if the dictionary is empty. + </description> + </method> <method name="keys"> <return type="Array"> </return> diff --git a/doc/classes/EditorInterface.xml b/doc/classes/EditorInterface.xml index 5a61c05cee..b01af71852 100644 --- a/doc/classes/EditorInterface.xml +++ b/doc/classes/EditorInterface.xml @@ -40,13 +40,6 @@ Returns the edited (current) scene's root [Node]. </description> </method> - <method name="get_editor_settings"> - <return type="EditorSettings"> - </return> - <description> - Returns the editor's [EditorSettings] instance. - </description> - </method> <method name="get_editor_main_control"> <return type="Control"> </return> @@ -55,6 +48,13 @@ [b]Note:[/b] This returns the main editor control containing the whole editor, not the 2D or 3D viewports specifically. </description> </method> + <method name="get_editor_settings"> + <return type="EditorSettings"> + </return> + <description> + Returns the editor's [EditorSettings] instance. + </description> + </method> <method name="get_file_system_dock"> <return type="FileSystemDock"> </return> diff --git a/doc/classes/EditorSceneImporterAssimp.xml b/doc/classes/EditorSceneImporterAssimp.xml deleted file mode 100644 index c72d4ee25a..0000000000 --- a/doc/classes/EditorSceneImporterAssimp.xml +++ /dev/null @@ -1,36 +0,0 @@ -<?xml version="1.0" encoding="UTF-8" ?> -<class name="EditorSceneImporterAssimp" inherits="EditorSceneImporter" version="4.0"> - <brief_description> - FBX 3D asset importer based on [url=http://assimp.org/]Assimp[/url]. - </brief_description> - <description> - This is an FBX 3D asset importer based on [url=http://assimp.org/]Assimp[/url]. It currently has many known limitations and works best with static meshes. Most animated meshes won't import correctly. - If exporting a FBX scene from Autodesk Maya, use these FBX export settings: - [codeblock] - - Smoothing Groups - - Smooth Mesh - - Triangluate (for meshes with blend shapes) - - Bake Animation - - Resample All - - Deformed Models - - Skins - - Blend Shapes - - Curve Filters - - Constant Key Reducer - - Auto Tangents Only - - *Do not check* Constraints (as it will break the file) - - Can check Embed Media (embeds textures into the exported FBX file) - - Note that when importing embedded media, the texture and mesh will be a single immutable file. - - You will have to re-export then re-import the FBX if the texture has changed. - - Units: Centimeters - - Up Axis: Y - - Binary format in FBX 2017 - [/codeblock] - </description> - <tutorials> - </tutorials> - <methods> - </methods> - <constants> - </constants> -</class> diff --git a/doc/classes/EditorSceneImporterGLTF.xml b/doc/classes/EditorSceneImporterGLTF.xml new file mode 100644 index 0000000000..e717b30f73 --- /dev/null +++ b/doc/classes/EditorSceneImporterGLTF.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="EditorSceneImporterGLTF" inherits="EditorSceneImporter" version="4.0"> + <brief_description> + </brief_description> + <description> + </description> + <tutorials> + </tutorials> + <methods> + </methods> + <constants> + </constants> +</class> diff --git a/doc/classes/EditorSceneImporterMesh.xml b/doc/classes/EditorSceneImporterMesh.xml new file mode 100644 index 0000000000..1c903bd889 --- /dev/null +++ b/doc/classes/EditorSceneImporterMesh.xml @@ -0,0 +1,160 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="EditorSceneImporterMesh" inherits="Resource" version="4.0"> + <brief_description> + </brief_description> + <description> + </description> + <tutorials> + </tutorials> + <methods> + <method name="add_blend_shape"> + <return type="void"> + </return> + <argument index="0" name="name" type="String"> + </argument> + <description> + </description> + </method> + <method name="add_surface"> + <return type="void"> + </return> + <argument index="0" name="primitive" type="int" enum="Mesh.PrimitiveType"> + </argument> + <argument index="1" name="arrays" type="Array"> + </argument> + <argument index="2" name="blend_shapes" type="Array" default="[ ]"> + </argument> + <argument index="3" name="lods" type="Dictionary" default="{ +}"> + </argument> + <argument index="4" name="material" type="Material" default="null"> + </argument> + <argument index="5" name="arg5" type="String" default=""""> + </argument> + <description> + </description> + </method> + <method name="clear"> + <return type="void"> + </return> + <description> + </description> + </method> + <method name="get_blend_shape_count" qualifiers="const"> + <return type="int"> + </return> + <description> + </description> + </method> + <method name="get_blend_shape_mode" qualifiers="const"> + <return type="int" enum="Mesh.BlendShapeMode"> + </return> + <description> + </description> + </method> + <method name="get_blend_shape_name" qualifiers="const"> + <return type="String"> + </return> + <argument index="0" name="blend_shape_idx" type="int"> + </argument> + <description> + </description> + </method> + <method name="get_mesh"> + <return type="ArrayMesh"> + </return> + <description> + </description> + </method> + <method name="get_surface_arrays" qualifiers="const"> + <return type="Array"> + </return> + <argument index="0" name="surface_idx" type="int"> + </argument> + <description> + </description> + </method> + <method name="get_surface_blend_shape_arrays" qualifiers="const"> + <return type="Array"> + </return> + <argument index="0" name="surface_idx" type="int"> + </argument> + <argument index="1" name="blend_shape_idx" type="int"> + </argument> + <description> + </description> + </method> + <method name="get_surface_count" qualifiers="const"> + <return type="int"> + </return> + <description> + </description> + </method> + <method name="get_surface_lod_count" qualifiers="const"> + <return type="int"> + </return> + <argument index="0" name="surface_idx" type="int"> + </argument> + <description> + </description> + </method> + <method name="get_surface_lod_indices" qualifiers="const"> + <return type="PackedInt32Array"> + </return> + <argument index="0" name="surface_idx" type="int"> + </argument> + <argument index="1" name="lod_idx" type="int"> + </argument> + <description> + </description> + </method> + <method name="get_surface_lod_size" qualifiers="const"> + <return type="float"> + </return> + <argument index="0" name="surface_idx" type="int"> + </argument> + <argument index="1" name="lod_idx" type="int"> + </argument> + <description> + </description> + </method> + <method name="get_surface_material" qualifiers="const"> + <return type="Material"> + </return> + <argument index="0" name="surface_idx" type="int"> + </argument> + <description> + </description> + </method> + <method name="get_surface_name" qualifiers="const"> + <return type="String"> + </return> + <argument index="0" name="surface_idx" type="int"> + </argument> + <description> + </description> + </method> + <method name="get_surface_primitive_type"> + <return type="int" enum="Mesh.PrimitiveType"> + </return> + <argument index="0" name="surface_idx" type="int"> + </argument> + <description> + </description> + </method> + <method name="set_blend_shape_mode"> + <return type="void"> + </return> + <argument index="0" name="mode" type="int" enum="Mesh.BlendShapeMode"> + </argument> + <description> + </description> + </method> + </methods> + <members> + <member name="_data" type="Dictionary" setter="_set_data" getter="_get_data" default="{"surfaces": [ ]}"> + </member> + </members> + <constants> + </constants> +</class> diff --git a/doc/classes/EditorSceneImporterMeshNode3D.xml b/doc/classes/EditorSceneImporterMeshNode3D.xml new file mode 100644 index 0000000000..1e459c1cee --- /dev/null +++ b/doc/classes/EditorSceneImporterMeshNode3D.xml @@ -0,0 +1,21 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="EditorSceneImporterMeshNode3D" inherits="Node3D" version="4.0"> + <brief_description> + </brief_description> + <description> + </description> + <tutorials> + </tutorials> + <methods> + </methods> + <members> + <member name="mesh" type="EditorSceneImporterMesh" setter="set_mesh" getter="get_mesh"> + </member> + <member name="skeleton_path" type="NodePath" setter="set_skeleton_path" getter="get_skeleton_path" default="NodePath("")"> + </member> + <member name="skin" type="Skin" setter="set_skin" getter="get_skin"> + </member> + </members> + <constants> + </constants> +</class> diff --git a/doc/classes/EncodedObjectAsID.xml b/doc/classes/EncodedObjectAsID.xml index fc68b47645..1e4fde453b 100644 --- a/doc/classes/EncodedObjectAsID.xml +++ b/doc/classes/EncodedObjectAsID.xml @@ -4,7 +4,7 @@ Holds a reference to an [Object]'s instance ID. </brief_description> <description> - Utility class which holds a reference to the internal identifier of an [Object] instance, as given by [method Object.get_instance_id]. This ID can then be used to retrieve the object instance with [method @GDScript.instance_from_id]. + Utility class which holds a reference to the internal identifier of an [Object] instance, as given by [method Object.get_instance_id]. This ID can then be used to retrieve the object instance with [method @GlobalScope.instance_from_id]. This class is used internally by the editor inspector and script debugger, but can also be used in plugins to pass and display objects as their IDs. </description> <tutorials> @@ -13,7 +13,7 @@ </methods> <members> <member name="object_id" type="int" setter="set_object_id" getter="get_object_id" default="0"> - The [Object] identifier stored in this [EncodedObjectAsID] instance. The object instance can be retrieved with [method @GDScript.instance_from_id]. + The [Object] identifier stored in this [EncodedObjectAsID] instance. The object instance can be retrieved with [method @GlobalScope.instance_from_id]. </member> </members> <constants> diff --git a/doc/classes/Engine.xml b/doc/classes/Engine.xml index c079085fb3..02b81ee9b7 100644 --- a/doc/classes/Engine.xml +++ b/doc/classes/Engine.xml @@ -51,13 +51,6 @@ Returns the frames per second of the running game. </description> </method> - <method name="get_process_frames" qualifiers="const"> - <return type="int"> - </return> - <description> - Returns the total number of frames passed since engine initialization which is advanced on each [b]process frame[/b], regardless of whether the render loop is enabled. See also [method get_frames_drawn]. - </description> - </method> <method name="get_license_info" qualifiers="const"> <return type="Dictionary"> </return> @@ -93,6 +86,13 @@ Returns the fraction through the current physics tick we are at the time of rendering the frame. This can be used to implement fixed timestep interpolation. </description> </method> + <method name="get_process_frames" qualifiers="const"> + <return type="int"> + </return> + <description> + Returns the total number of frames passed since engine initialization which is advanced on each [b]process frame[/b], regardless of whether the render loop is enabled. See also [method get_frames_drawn]. + </description> + </method> <method name="get_singleton" qualifiers="const"> <return type="Object"> </return> diff --git a/doc/classes/GLTFAccessor.xml b/doc/classes/GLTFAccessor.xml new file mode 100644 index 0000000000..a1f596f7dd --- /dev/null +++ b/doc/classes/GLTFAccessor.xml @@ -0,0 +1,43 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="GLTFAccessor" inherits="Resource" version="4.0"> + <brief_description> + </brief_description> + <description> + </description> + <tutorials> + </tutorials> + <methods> + </methods> + <members> + <member name="buffer_view" type="int" setter="set_buffer_view" getter="get_buffer_view" default="0"> + </member> + <member name="byte_offset" type="int" setter="set_byte_offset" getter="get_byte_offset" default="0"> + </member> + <member name="component_type" type="int" setter="set_component_type" getter="get_component_type" default="0"> + </member> + <member name="count" type="int" setter="set_count" getter="get_count" default="0"> + </member> + <member name="max" type="PackedFloat64Array" setter="set_max" getter="get_max" default="PackedFloat64Array( )"> + </member> + <member name="min" type="PackedFloat64Array" setter="set_min" getter="get_min" default="PackedFloat64Array( )"> + </member> + <member name="normalized" type="bool" setter="set_normalized" getter="get_normalized" default="false"> + </member> + <member name="sparse_count" type="int" setter="set_sparse_count" getter="get_sparse_count" default="0"> + </member> + <member name="sparse_indices_buffer_view" type="int" setter="set_sparse_indices_buffer_view" getter="get_sparse_indices_buffer_view" default="0"> + </member> + <member name="sparse_indices_byte_offset" type="int" setter="set_sparse_indices_byte_offset" getter="get_sparse_indices_byte_offset" default="0"> + </member> + <member name="sparse_indices_component_type" type="int" setter="set_sparse_indices_component_type" getter="get_sparse_indices_component_type" default="0"> + </member> + <member name="sparse_values_buffer_view" type="int" setter="set_sparse_values_buffer_view" getter="get_sparse_values_buffer_view" default="0"> + </member> + <member name="sparse_values_byte_offset" type="int" setter="set_sparse_values_byte_offset" getter="get_sparse_values_byte_offset" default="0"> + </member> + <member name="type" type="int" setter="set_type" getter="get_type" default="0"> + </member> + </members> + <constants> + </constants> +</class> diff --git a/doc/classes/GLTFAnimation.xml b/doc/classes/GLTFAnimation.xml new file mode 100644 index 0000000000..5c1fa02f11 --- /dev/null +++ b/doc/classes/GLTFAnimation.xml @@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="GLTFAnimation" inherits="Resource" version="4.0"> + <brief_description> + </brief_description> + <description> + </description> + <tutorials> + </tutorials> + <methods> + </methods> + <members> + <member name="loop" type="bool" setter="set_loop" getter="get_loop" default="false"> + </member> + </members> + <constants> + </constants> +</class> diff --git a/doc/classes/GLTFBufferView.xml b/doc/classes/GLTFBufferView.xml new file mode 100644 index 0000000000..edaad85e0a --- /dev/null +++ b/doc/classes/GLTFBufferView.xml @@ -0,0 +1,25 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="GLTFBufferView" inherits="Resource" version="4.0"> + <brief_description> + </brief_description> + <description> + </description> + <tutorials> + </tutorials> + <methods> + </methods> + <members> + <member name="buffer" type="int" setter="set_buffer" getter="get_buffer" default="-1"> + </member> + <member name="byte_length" type="int" setter="set_byte_length" getter="get_byte_length" default="0"> + </member> + <member name="byte_offset" type="int" setter="set_byte_offset" getter="get_byte_offset" default="0"> + </member> + <member name="byte_stride" type="int" setter="set_byte_stride" getter="get_byte_stride" default="-1"> + </member> + <member name="indices" type="bool" setter="set_indices" getter="get_indices" default="false"> + </member> + </members> + <constants> + </constants> +</class> diff --git a/doc/classes/GLTFCamera.xml b/doc/classes/GLTFCamera.xml new file mode 100644 index 0000000000..0b95f2c802 --- /dev/null +++ b/doc/classes/GLTFCamera.xml @@ -0,0 +1,23 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="GLTFCamera" inherits="Resource" version="4.0"> + <brief_description> + </brief_description> + <description> + </description> + <tutorials> + </tutorials> + <methods> + </methods> + <members> + <member name="fov_size" type="float" setter="set_fov_size" getter="get_fov_size" default="75.0"> + </member> + <member name="perspective" type="bool" setter="set_perspective" getter="get_perspective" default="true"> + </member> + <member name="zfar" type="float" setter="set_zfar" getter="get_zfar" default="4000.0"> + </member> + <member name="znear" type="float" setter="set_znear" getter="get_znear" default="0.05"> + </member> + </members> + <constants> + </constants> +</class> diff --git a/doc/classes/GLTFDocument.xml b/doc/classes/GLTFDocument.xml new file mode 100644 index 0000000000..04c40dd752 --- /dev/null +++ b/doc/classes/GLTFDocument.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="GLTFDocument" inherits="Resource" version="4.0"> + <brief_description> + </brief_description> + <description> + </description> + <tutorials> + </tutorials> + <methods> + </methods> + <constants> + </constants> +</class> diff --git a/doc/classes/GLTFLight.xml b/doc/classes/GLTFLight.xml new file mode 100644 index 0000000000..bfeaf9a86e --- /dev/null +++ b/doc/classes/GLTFLight.xml @@ -0,0 +1,27 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="GLTFLight" inherits="Resource" version="4.0"> + <brief_description> + </brief_description> + <description> + </description> + <tutorials> + </tutorials> + <methods> + </methods> + <members> + <member name="color" type="Color" setter="set_color" getter="get_color" default="Color( 0, 0, 0, 1 )"> + </member> + <member name="inner_cone_angle" type="float" setter="set_inner_cone_angle" getter="get_inner_cone_angle" default="0.0"> + </member> + <member name="intensity" type="float" setter="set_intensity" getter="get_intensity" default="0.0"> + </member> + <member name="outer_cone_angle" type="float" setter="set_outer_cone_angle" getter="get_outer_cone_angle" default="0.0"> + </member> + <member name="range" type="float" setter="set_range" getter="get_range" default="0.0"> + </member> + <member name="type" type="String" setter="set_type" getter="get_type" default=""""> + </member> + </members> + <constants> + </constants> +</class> diff --git a/doc/classes/GLTFMesh.xml b/doc/classes/GLTFMesh.xml new file mode 100644 index 0000000000..55f79d2c55 --- /dev/null +++ b/doc/classes/GLTFMesh.xml @@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="GLTFMesh" inherits="Resource" version="4.0"> + <brief_description> + </brief_description> + <description> + </description> + <tutorials> + </tutorials> + <methods> + </methods> + <members> + <member name="blend_weights" type="PackedFloat32Array" setter="set_blend_weights" getter="get_blend_weights" default="PackedFloat32Array( )"> + </member> + <member name="mesh" type="EditorSceneImporterMesh" setter="set_mesh" getter="get_mesh"> + </member> + </members> + <constants> + </constants> +</class> diff --git a/doc/classes/GLTFNode.xml b/doc/classes/GLTFNode.xml new file mode 100644 index 0000000000..5b7d4fadec --- /dev/null +++ b/doc/classes/GLTFNode.xml @@ -0,0 +1,43 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="GLTFNode" inherits="Resource" version="4.0"> + <brief_description> + </brief_description> + <description> + </description> + <tutorials> + </tutorials> + <methods> + </methods> + <members> + <member name="camera" type="int" setter="set_camera" getter="get_camera" default="-1"> + </member> + <member name="children" type="PackedInt32Array" setter="set_children" getter="get_children" default="PackedInt32Array( )"> + </member> + <member name="fake_joint_parent" type="int" setter="set_fake_joint_parent" getter="get_fake_joint_parent" default="-1"> + </member> + <member name="height" type="int" setter="set_height" getter="get_height" default="-1"> + </member> + <member name="joint" type="bool" setter="set_joint" getter="get_joint" default="false"> + </member> + <member name="light" type="int" setter="set_light" getter="get_light" default="-1"> + </member> + <member name="mesh" type="int" setter="set_mesh" getter="get_mesh" default="-1"> + </member> + <member name="parent" type="int" setter="set_parent" getter="get_parent" default="-1"> + </member> + <member name="rotation" type="Quat" setter="set_rotation" getter="get_rotation" default="Quat( 0, 0, 0, 1 )"> + </member> + <member name="scale" type="Vector3" setter="set_scale" getter="get_scale" default="Vector3( 1, 1, 1 )"> + </member> + <member name="skeleton" type="int" setter="set_skeleton" getter="get_skeleton" default="-1"> + </member> + <member name="skin" type="int" setter="set_skin" getter="get_skin" default="-1"> + </member> + <member name="translation" type="Vector3" setter="set_translation" getter="get_translation" default="Vector3( 0, 0, 0 )"> + </member> + <member name="xform" type="Transform" setter="set_xform" getter="get_xform" default="Transform( 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0 )"> + </member> + </members> + <constants> + </constants> +</class> diff --git a/doc/classes/GLTFSkeleton.xml b/doc/classes/GLTFSkeleton.xml new file mode 100644 index 0000000000..e27c838648 --- /dev/null +++ b/doc/classes/GLTFSkeleton.xml @@ -0,0 +1,67 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="GLTFSkeleton" inherits="Resource" version="4.0"> + <brief_description> + </brief_description> + <description> + </description> + <tutorials> + </tutorials> + <methods> + <method name="get_bone_attachment"> + <return type="BoneAttachment3D"> + </return> + <argument index="0" name="arg0" type="int"> + </argument> + <description> + </description> + </method> + <method name="get_bone_attachment_count"> + <return type="int"> + </return> + <description> + </description> + </method> + <method name="get_godot_bone_node"> + <return type="Dictionary"> + </return> + <description> + </description> + </method> + <method name="get_godot_skeleton"> + <return type="Skeleton3D"> + </return> + <description> + </description> + </method> + <method name="get_unique_names"> + <return type="Array"> + </return> + <description> + </description> + </method> + <method name="set_godot_bone_node"> + <return type="void"> + </return> + <argument index="0" name="godot_bone_node" type="Dictionary"> + </argument> + <description> + </description> + </method> + <method name="set_unique_names"> + <return type="void"> + </return> + <argument index="0" name="unique_names" type="Array"> + </argument> + <description> + </description> + </method> + </methods> + <members> + <member name="joints" type="PackedInt32Array" setter="set_joints" getter="get_joints" default="PackedInt32Array( )"> + </member> + <member name="roots" type="PackedInt32Array" setter="set_roots" getter="get_roots" default="PackedInt32Array( )"> + </member> + </members> + <constants> + </constants> +</class> diff --git a/doc/classes/GLTFSkin.xml b/doc/classes/GLTFSkin.xml new file mode 100644 index 0000000000..5a80c7097a --- /dev/null +++ b/doc/classes/GLTFSkin.xml @@ -0,0 +1,71 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="GLTFSkin" inherits="Resource" version="4.0"> + <brief_description> + </brief_description> + <description> + </description> + <tutorials> + </tutorials> + <methods> + <method name="get_inverse_binds"> + <return type="Array"> + </return> + <description> + </description> + </method> + <method name="get_joint_i_to_bone_i"> + <return type="Dictionary"> + </return> + <description> + </description> + </method> + <method name="get_joint_i_to_name"> + <return type="Dictionary"> + </return> + <description> + </description> + </method> + <method name="set_inverse_binds"> + <return type="void"> + </return> + <argument index="0" name="inverse_binds" type="Array"> + </argument> + <description> + </description> + </method> + <method name="set_joint_i_to_bone_i"> + <return type="void"> + </return> + <argument index="0" name="joint_i_to_bone_i" type="Dictionary"> + </argument> + <description> + </description> + </method> + <method name="set_joint_i_to_name"> + <return type="void"> + </return> + <argument index="0" name="joint_i_to_name" type="Dictionary"> + </argument> + <description> + </description> + </method> + </methods> + <members> + <member name="godot_skin" type="Skin" setter="set_godot_skin" getter="get_godot_skin"> + </member> + <member name="joints" type="PackedInt32Array" setter="set_joints" getter="get_joints" default="PackedInt32Array( )"> + </member> + <member name="joints_original" type="PackedInt32Array" setter="set_joints_original" getter="get_joints_original" default="PackedInt32Array( )"> + </member> + <member name="non_joints" type="PackedInt32Array" setter="set_non_joints" getter="get_non_joints" default="PackedInt32Array( )"> + </member> + <member name="roots" type="PackedInt32Array" setter="set_roots" getter="get_roots" default="PackedInt32Array( )"> + </member> + <member name="skeleton" type="int" setter="set_skeleton" getter="get_skeleton" default="-1"> + </member> + <member name="skin_root" type="int" setter="set_skin_root" getter="get_skin_root" default="-1"> + </member> + </members> + <constants> + </constants> +</class> diff --git a/doc/classes/GLTFSpecGloss.xml b/doc/classes/GLTFSpecGloss.xml new file mode 100644 index 0000000000..68cc7c845d --- /dev/null +++ b/doc/classes/GLTFSpecGloss.xml @@ -0,0 +1,25 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="GLTFSpecGloss" inherits="Resource" version="4.0"> + <brief_description> + </brief_description> + <description> + </description> + <tutorials> + </tutorials> + <methods> + </methods> + <members> + <member name="diffuse_factor" type="Color" setter="set_diffuse_factor" getter="get_diffuse_factor" default="Color( 1, 1, 1, 1 )"> + </member> + <member name="diffuse_img" type="Image" setter="set_diffuse_img" getter="get_diffuse_img"> + </member> + <member name="gloss_factor" type="float" setter="set_gloss_factor" getter="get_gloss_factor" default="1.0"> + </member> + <member name="spec_gloss_img" type="Image" setter="set_spec_gloss_img" getter="get_spec_gloss_img"> + </member> + <member name="specular_factor" type="Color" setter="set_specular_factor" getter="get_specular_factor" default="Color( 1, 1, 1, 1 )"> + </member> + </members> + <constants> + </constants> +</class> diff --git a/doc/classes/GLTFState.xml b/doc/classes/GLTFState.xml new file mode 100644 index 0000000000..f7763efdb1 --- /dev/null +++ b/doc/classes/GLTFState.xml @@ -0,0 +1,251 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="GLTFState" inherits="Resource" version="4.0"> + <brief_description> + </brief_description> + <description> + </description> + <tutorials> + </tutorials> + <methods> + <method name="get_accessors"> + <return type="Array"> + </return> + <description> + </description> + </method> + <method name="get_animation_player"> + <return type="AnimationPlayer"> + </return> + <argument index="0" name="arg0" type="int"> + </argument> + <description> + </description> + </method> + <method name="get_animation_players_count"> + <return type="int"> + </return> + <argument index="0" name="arg0" type="int"> + </argument> + <description> + </description> + </method> + <method name="get_animations"> + <return type="Array"> + </return> + <description> + </description> + </method> + <method name="get_buffer_views"> + <return type="Array"> + </return> + <description> + </description> + </method> + <method name="get_cameras"> + <return type="Array"> + </return> + <description> + </description> + </method> + <method name="get_images"> + <return type="Array"> + </return> + <description> + </description> + </method> + <method name="get_lights"> + <return type="Array"> + </return> + <description> + </description> + </method> + <method name="get_materials"> + <return type="Array"> + </return> + <description> + </description> + </method> + <method name="get_meshes"> + <return type="Array"> + </return> + <description> + </description> + </method> + <method name="get_nodes"> + <return type="Array"> + </return> + <description> + </description> + </method> + <method name="get_scene_node"> + <return type="Node"> + </return> + <argument index="0" name="arg0" type="int"> + </argument> + <description> + </description> + </method> + <method name="get_skeleton_to_node"> + <return type="Dictionary"> + </return> + <description> + </description> + </method> + <method name="get_skeletons"> + <return type="Array"> + </return> + <description> + </description> + </method> + <method name="get_skins"> + <return type="Array"> + </return> + <description> + </description> + </method> + <method name="get_textures"> + <return type="Array"> + </return> + <description> + </description> + </method> + <method name="get_unique_names"> + <return type="Array"> + </return> + <description> + </description> + </method> + <method name="set_accessors"> + <return type="void"> + </return> + <argument index="0" name="accessors" type="Array"> + </argument> + <description> + </description> + </method> + <method name="set_animations"> + <return type="void"> + </return> + <argument index="0" name="animations" type="Array"> + </argument> + <description> + </description> + </method> + <method name="set_buffer_views"> + <return type="void"> + </return> + <argument index="0" name="buffer_views" type="Array"> + </argument> + <description> + </description> + </method> + <method name="set_cameras"> + <return type="void"> + </return> + <argument index="0" name="cameras" type="Array"> + </argument> + <description> + </description> + </method> + <method name="set_images"> + <return type="void"> + </return> + <argument index="0" name="images" type="Array"> + </argument> + <description> + </description> + </method> + <method name="set_lights"> + <return type="void"> + </return> + <argument index="0" name="lights" type="Array"> + </argument> + <description> + </description> + </method> + <method name="set_materials"> + <return type="void"> + </return> + <argument index="0" name="materials" type="Array"> + </argument> + <description> + </description> + </method> + <method name="set_meshes"> + <return type="void"> + </return> + <argument index="0" name="meshes" type="Array"> + </argument> + <description> + </description> + </method> + <method name="set_nodes"> + <return type="void"> + </return> + <argument index="0" name="nodes" type="Array"> + </argument> + <description> + </description> + </method> + <method name="set_skeleton_to_node"> + <return type="void"> + </return> + <argument index="0" name="skeleton_to_node" type="Dictionary"> + </argument> + <description> + </description> + </method> + <method name="set_skeletons"> + <return type="void"> + </return> + <argument index="0" name="skeletons" type="Array"> + </argument> + <description> + </description> + </method> + <method name="set_skins"> + <return type="void"> + </return> + <argument index="0" name="skins" type="Array"> + </argument> + <description> + </description> + </method> + <method name="set_textures"> + <return type="void"> + </return> + <argument index="0" name="textures" type="Array"> + </argument> + <description> + </description> + </method> + <method name="set_unique_names"> + <return type="void"> + </return> + <argument index="0" name="unique_names" type="Array"> + </argument> + <description> + </description> + </method> + </methods> + <members> + <member name="buffers" type="Array" setter="set_buffers" getter="get_buffers" default="[ ]"> + </member> + <member name="glb_data" type="PackedByteArray" setter="set_glb_data" getter="get_glb_data" default="PackedByteArray( )"> + </member> + <member name="json" type="Dictionary" setter="set_json" getter="get_json" default="{}"> + </member> + <member name="major_version" type="int" setter="set_major_version" getter="get_major_version" default="0"> + </member> + <member name="minor_version" type="int" setter="set_minor_version" getter="get_minor_version" default="0"> + </member> + <member name="root_nodes" type="Array" setter="set_root_nodes" getter="get_root_nodes" default="[ ]"> + </member> + <member name="scene_name" type="String" setter="set_scene_name" getter="get_scene_name" default=""""> + </member> + <member name="use_named_skin_binds" type="bool" setter="set_use_named_skin_binds" getter="get_use_named_skin_binds" default="false"> + </member> + </members> + <constants> + </constants> +</class> diff --git a/doc/classes/GLTFTexture.xml b/doc/classes/GLTFTexture.xml new file mode 100644 index 0000000000..c7f94ab0da --- /dev/null +++ b/doc/classes/GLTFTexture.xml @@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="GLTFTexture" inherits="Resource" version="4.0"> + <brief_description> + </brief_description> + <description> + </description> + <tutorials> + </tutorials> + <methods> + </methods> + <members> + <member name="src_image" type="int" setter="set_src_image" getter="get_src_image" default="4"> + </member> + </members> + <constants> + </constants> +</class> diff --git a/doc/classes/GeometryInstance3D.xml b/doc/classes/GeometryInstance3D.xml index cc85ce295b..631a30abab 100644 --- a/doc/classes/GeometryInstance3D.xml +++ b/doc/classes/GeometryInstance3D.xml @@ -48,6 +48,8 @@ </member> <member name="gi_mode" type="int" setter="set_gi_mode" getter="get_gi_mode" enum="GeometryInstance3D.GIMode" default="0"> </member> + <member name="lod_bias" type="float" setter="set_lod_bias" getter="get_lod_bias" default="1.0"> + </member> <member name="lod_max_distance" type="float" setter="set_lod_max_distance" getter="get_lod_max_distance" default="0.0"> The GeometryInstance3D's max LOD distance. [b]Note:[/b] This property currently has no effect. diff --git a/doc/classes/GraphEdit.xml b/doc/classes/GraphEdit.xml index 2347627c31..10afa4c339 100644 --- a/doc/classes/GraphEdit.xml +++ b/doc/classes/GraphEdit.xml @@ -281,17 +281,17 @@ Emitted at the end of a GraphNode movement. </description> </signal> - <signal name="node_selected"> + <signal name="node_deselected"> <argument index="0" name="node" type="Node"> </argument> <description> - Emitted when a GraphNode is selected. </description> </signal> - <signal name="node_deselected"> + <signal name="node_selected"> <argument index="0" name="node" type="Node"> </argument> <description> + Emitted when a GraphNode is selected. </description> </signal> <signal name="paste_nodes_request"> diff --git a/doc/classes/ItemList.xml b/doc/classes/ItemList.xml index 8542cdaca4..6e5ff83a35 100644 --- a/doc/classes/ItemList.xml +++ b/doc/classes/ItemList.xml @@ -52,6 +52,22 @@ Removes all OpenType features from the item's text. </description> </method> + <method name="deselect"> + <return type="void"> + </return> + <argument index="0" name="idx" type="int"> + </argument> + <description> + Ensures the item associated with the specified index is not selected. + </description> + </method> + <method name="deselect_all"> + <return type="void"> + </return> + <description> + Ensures there are no items selected. + </description> + </method> <method name="ensure_current_is_visible"> <return type="void"> </return> @@ -471,22 +487,6 @@ Sorts items in the list by their text. </description> </method> - <method name="deselect"> - <return type="void"> - </return> - <argument index="0" name="idx" type="int"> - </argument> - <description> - Ensures the item associated with the specified index is not selected. - </description> - </method> - <method name="deselect_all"> - <return type="void"> - </return> - <description> - Ensures there are no items selected. - </description> - </method> </methods> <members> <member name="allow_reselect" type="bool" setter="set_allow_reselect" getter="get_allow_reselect" default="false"> diff --git a/doc/classes/JSONParseResult.xml b/doc/classes/JSONParseResult.xml index 991ebcd7a0..bc94f74b07 100644 --- a/doc/classes/JSONParseResult.xml +++ b/doc/classes/JSONParseResult.xml @@ -21,7 +21,7 @@ The error message if the JSON source was not successfully parsed. See the [enum Error] constants. </member> <member name="result" type="Variant" setter="set_result" getter="get_result"> - A [Variant] containing the parsed JSON. Use [method @GDScript.typeof] or the [code]is[/code] keyword to check if it is what you expect. For example, if the JSON source starts with curly braces ([code]{}[/code]), a [Dictionary] will be returned. If the JSON source starts with brackets ([code][][/code]), an [Array] will be returned. + A [Variant] containing the parsed JSON. Use [method @GlobalScope.typeof] or the [code]is[/code] keyword to check if it is what you expect. For example, if the JSON source starts with curly braces ([code]{}[/code]), a [Dictionary] will be returned. If the JSON source starts with brackets ([code][][/code]), an [Array] will be returned. [b]Note:[/b] The JSON specification does not define integer or float types, but only a [i]number[/i] type. Therefore, parsing a JSON text will convert all numerical values to [float] types. [b]Note:[/b] JSON objects do not preserve key order like Godot dictionaries, thus, you should not rely on keys being in a certain order if a dictionary is constructed from JSON. In contrast, JSON arrays retain the order of their elements: [codeblocks] diff --git a/doc/classes/MainLoop.xml b/doc/classes/MainLoop.xml index 7682379b64..9e976babcf 100644 --- a/doc/classes/MainLoop.xml +++ b/doc/classes/MainLoop.xml @@ -19,7 +19,7 @@ print("Initialized:") print(" Starting time: %s" % str(time_elapsed)) - func _idle(delta): + func _process(delta): time_elapsed += delta # Return true to end the main loop. return quit @@ -51,16 +51,6 @@ Called before the program exits. </description> </method> - <method name="_idle" qualifiers="virtual"> - <return type="bool"> - </return> - <argument index="0" name="delta" type="float"> - </argument> - <description> - Called each idle frame with the time since the last idle frame as argument (in seconds). Equivalent to [method Node._process]. - If implemented, the method must return a boolean value. [code]true[/code] ends the main loop, while [code]false[/code] lets it proceed to the next frame. - </description> - </method> <method name="_initialize" qualifiers="virtual"> <return type="void"> </return> @@ -68,7 +58,7 @@ Called once during initialization. </description> </method> - <method name="_iteration" qualifiers="virtual"> + <method name="_physics_process" qualifiers="virtual"> <return type="bool"> </return> <argument index="0" name="delta" type="float"> @@ -78,6 +68,16 @@ If implemented, the method must return a boolean value. [code]true[/code] ends the main loop, while [code]false[/code] lets it proceed to the next frame. </description> </method> + <method name="_process" qualifiers="virtual"> + <return type="bool"> + </return> + <argument index="0" name="delta" type="float"> + </argument> + <description> + Called each process (idle) frame with the time since the last process frame as argument (in seconds). Equivalent to [method Node._process]. + If implemented, the method must return a boolean value. [code]true[/code] ends the main loop, while [code]false[/code] lets it proceed to the next frame. + </description> + </method> </methods> <signals> <signal name="on_request_permissions_result"> diff --git a/doc/classes/Mesh.xml b/doc/classes/Mesh.xml index dff4b4f7ab..ed7c39d4d9 100644 --- a/doc/classes/Mesh.xml +++ b/doc/classes/Mesh.xml @@ -242,5 +242,11 @@ </constant> <constant name="ARRAY_FLAG_USE_8_BONE_WEIGHTS" value="134217728" enum="ArrayFormat"> </constant> + <constant name="BLEND_SHAPE_MODE_NORMALIZED" value="0" enum="BlendShapeMode"> + Blend shapes are normalized. + </constant> + <constant name="BLEND_SHAPE_MODE_RELATIVE" value="1" enum="BlendShapeMode"> + Blend shapes are relative to base weight. + </constant> </constants> </class> diff --git a/doc/classes/NinePatchRect.xml b/doc/classes/NinePatchRect.xml index f4b9d75e91..d6de0ef4cf 100644 --- a/doc/classes/NinePatchRect.xml +++ b/doc/classes/NinePatchRect.xml @@ -12,7 +12,7 @@ <method name="get_patch_margin" qualifiers="const"> <return type="int"> </return> - <argument index="0" name="side" type="int" enum="Side"> + <argument index="0" name="margin" type="int" enum="Side"> </argument> <description> Returns the size of the margin on the specified [enum Side]. @@ -21,7 +21,7 @@ <method name="set_patch_margin"> <return type="void"> </return> - <argument index="0" name="side" type="int" enum="Side"> + <argument index="0" name="margin" type="int" enum="Side"> </argument> <argument index="1" name="value" type="int"> </argument> diff --git a/doc/classes/Node.xml b/doc/classes/Node.xml index 62d88afa51..90966faa02 100644 --- a/doc/classes/Node.xml +++ b/doc/classes/Node.xml @@ -590,7 +590,7 @@ <return type="void"> </return> <description> - Moves this node to the bottom of parent node's children hierarchy. This is often useful in GUIs ([Control] nodes), because their order of drawing depends on their order in the tree, i.e. the further they are on the node list, the higher they are drawn. After using [code]raise[/code], a Control will be drawn on top of their siblings. + Moves this node to the bottom of parent node's children hierarchy. This is often useful in GUIs ([Control] nodes), because their order of drawing depends on their order in the tree. The top Node is drawn first, then any siblings below the top Node in the hierarchy are successively drawn on top of it. After using [code]raise[/code], a Control will be drawn on top of its siblings. </description> </method> <method name="remove_and_skip"> diff --git a/doc/classes/Node3D.xml b/doc/classes/Node3D.xml index f6ff514474..fe3a9c5d39 100644 --- a/doc/classes/Node3D.xml +++ b/doc/classes/Node3D.xml @@ -6,7 +6,7 @@ <description> Most basic 3D game object, with a 3D [Transform] and visibility settings. All other 3D game objects inherit from Node3D. Use [Node3D] as a parent node to move, scale, rotate and show/hide children in a 3D project. Affine operations (rotate, scale, translate) happen in parent's local coordinate system, unless the [Node3D] object is set as top-level. Affine operations in this coordinate system correspond to direct affine operations on the [Node3D]'s transform. The word local below refers to this coordinate system. The coordinate system that is attached to the [Node3D] object itself is referred to as object-local coordinate system. - [b]Note:[/b] Unless otherwise specified, all methods that have angle parameters must have angles specified as [i]radians[/i]. To convert degrees to radians, use [method @GDScript.deg2rad]. + [b]Note:[/b] Unless otherwise specified, all methods that have angle parameters must have angles specified as [i]radians[/i]. To convert degrees to radians, use [method @GlobalScope.deg2rad]. </description> <tutorials> <link title="Introduction to 3D">https://docs.godotengine.org/en/latest/tutorials/3d/introduction_to_3d.html</link> diff --git a/doc/classes/Object.xml b/doc/classes/Object.xml index 50d91c7943..6ff7e34194 100644 --- a/doc/classes/Object.xml +++ b/doc/classes/Object.xml @@ -242,7 +242,7 @@ </return> <description> Returns the object's unique instance ID. - This ID can be saved in [EncodedObjectAsID], and can be used to retrieve the object instance with [method @GDScript.instance_from_id]. + This ID can be saved in [EncodedObjectAsID], and can be used to retrieve the object instance with [method @GlobalScope.instance_from_id]. </description> </method> <method name="get_meta" qualifiers="const"> diff --git a/doc/classes/PackedByteArray.xml b/doc/classes/PackedByteArray.xml index b00c59ade9..75fb7c1465 100644 --- a/doc/classes/PackedByteArray.xml +++ b/doc/classes/PackedByteArray.xml @@ -92,13 +92,6 @@ Creates a copy of the array, and returns it. </description> </method> - <method name="is_empty"> - <return type="bool"> - </return> - <description> - Returns [code]true[/code] if the array is empty. - </description> - </method> <method name="get_string_from_ascii"> <return type="String"> </return> @@ -171,6 +164,13 @@ Reverses the order of the elements in the array. </description> </method> + <method name="is_empty"> + <return type="bool"> + </return> + <description> + Returns [code]true[/code] if the array is empty. + </description> + </method> <method name="operator !=" qualifiers="operator"> <return type="bool"> </return> diff --git a/doc/classes/PackedColorArray.xml b/doc/classes/PackedColorArray.xml index d6cd5196e4..48d5822f7c 100644 --- a/doc/classes/PackedColorArray.xml +++ b/doc/classes/PackedColorArray.xml @@ -59,13 +59,6 @@ Creates a copy of the array, and returns it. </description> </method> - <method name="is_empty"> - <return type="bool"> - </return> - <description> - Returns [code]true[/code] if the array is empty. - </description> - </method> <method name="has"> <return type="bool"> </return> @@ -93,6 +86,13 @@ Reverses the order of the elements in the array. </description> </method> + <method name="is_empty"> + <return type="bool"> + </return> + <description> + Returns [code]true[/code] if the array is empty. + </description> + </method> <method name="operator !=" qualifiers="operator"> <return type="bool"> </return> diff --git a/doc/classes/PackedFloat32Array.xml b/doc/classes/PackedFloat32Array.xml index 52f6ece158..6598828089 100644 --- a/doc/classes/PackedFloat32Array.xml +++ b/doc/classes/PackedFloat32Array.xml @@ -60,13 +60,6 @@ Creates a copy of the array, and returns it. </description> </method> - <method name="is_empty"> - <return type="bool"> - </return> - <description> - Returns [code]true[/code] if the array is empty. - </description> - </method> <method name="has"> <return type="bool"> </return> @@ -94,6 +87,13 @@ Reverses the order of the elements in the array. </description> </method> + <method name="is_empty"> + <return type="bool"> + </return> + <description> + Returns [code]true[/code] if the array is empty. + </description> + </method> <method name="operator !=" qualifiers="operator"> <return type="bool"> </return> diff --git a/doc/classes/PackedFloat64Array.xml b/doc/classes/PackedFloat64Array.xml index 2f317d4b8c..d116c6756b 100644 --- a/doc/classes/PackedFloat64Array.xml +++ b/doc/classes/PackedFloat64Array.xml @@ -60,13 +60,6 @@ Creates a copy of the array, and returns it. </description> </method> - <method name="is_empty"> - <return type="bool"> - </return> - <description> - Returns [code]true[/code] if the array is empty. - </description> - </method> <method name="has"> <return type="bool"> </return> @@ -94,6 +87,13 @@ Reverses the order of the elements in the array. </description> </method> + <method name="is_empty"> + <return type="bool"> + </return> + <description> + Returns [code]true[/code] if the array is empty. + </description> + </method> <method name="operator !=" qualifiers="operator"> <return type="bool"> </return> diff --git a/doc/classes/PackedInt32Array.xml b/doc/classes/PackedInt32Array.xml index bda902b15f..2ac7a67b4b 100644 --- a/doc/classes/PackedInt32Array.xml +++ b/doc/classes/PackedInt32Array.xml @@ -60,13 +60,6 @@ Creates a copy of the array, and returns it. </description> </method> - <method name="is_empty"> - <return type="bool"> - </return> - <description> - Returns [code]true[/code] if the array is empty. - </description> - </method> <method name="has"> <return type="bool"> </return> @@ -94,6 +87,13 @@ Reverses the order of the elements in the array. </description> </method> + <method name="is_empty"> + <return type="bool"> + </return> + <description> + Returns [code]true[/code] if the array is empty. + </description> + </method> <method name="operator !=" qualifiers="operator"> <return type="bool"> </return> diff --git a/doc/classes/PackedInt64Array.xml b/doc/classes/PackedInt64Array.xml index 9c52ec808b..a7b6bf0a0f 100644 --- a/doc/classes/PackedInt64Array.xml +++ b/doc/classes/PackedInt64Array.xml @@ -60,13 +60,6 @@ Creates a copy of the array, and returns it. </description> </method> - <method name="is_empty"> - <return type="bool"> - </return> - <description> - Returns [code]true[/code] if the array is empty. - </description> - </method> <method name="has"> <return type="bool"> </return> @@ -94,6 +87,13 @@ Reverses the order of the elements in the array. </description> </method> + <method name="is_empty"> + <return type="bool"> + </return> + <description> + Returns [code]true[/code] if the array is empty. + </description> + </method> <method name="operator !=" qualifiers="operator"> <return type="bool"> </return> diff --git a/doc/classes/PackedSceneGLTF.xml b/doc/classes/PackedSceneGLTF.xml new file mode 100644 index 0000000000..a04c6ef0b6 --- /dev/null +++ b/doc/classes/PackedSceneGLTF.xml @@ -0,0 +1,58 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="PackedSceneGLTF" inherits="PackedScene" version="4.0"> + <brief_description> + </brief_description> + <description> + </description> + <tutorials> + </tutorials> + <methods> + <method name="export_gltf"> + <return type="int" enum="Error"> + </return> + <argument index="0" name="node" type="Node"> + </argument> + <argument index="1" name="path" type="String"> + </argument> + <argument index="2" name="flags" type="int" default="0"> + </argument> + <argument index="3" name="bake_fps" type="float" default="1000.0"> + </argument> + <description> + </description> + </method> + <method name="import_gltf_scene"> + <return type="Node"> + </return> + <argument index="0" name="path" type="String"> + </argument> + <argument index="1" name="flags" type="int" default="0"> + </argument> + <argument index="2" name="bake_fps" type="float" default="1000.0"> + </argument> + <argument index="3" name="state" type="GLTFState" default="null"> + </argument> + <description> + </description> + </method> + <method name="pack_gltf"> + <return type="void"> + </return> + <argument index="0" name="path" type="String"> + </argument> + <argument index="1" name="flags" type="int" default="0"> + </argument> + <argument index="2" name="bake_fps" type="float" default="1000.0"> + </argument> + <argument index="3" name="state" type="GLTFState" default="null"> + </argument> + <description> + </description> + </method> + </methods> + <members> + <member name="_bundled" type="Dictionary" setter="_set_bundled_scene" getter="_get_bundled_scene" override="true" default="{"conn_count": 0,"conns": PackedInt32Array( ),"editable_instances": [ ],"names": PackedStringArray( ),"node_count": 0,"node_paths": [ ],"nodes": PackedInt32Array( ),"variants": [ ],"version": 2}" /> + </members> + <constants> + </constants> +</class> diff --git a/doc/classes/PackedStringArray.xml b/doc/classes/PackedStringArray.xml index 24406c53d4..fb7ed2a906 100644 --- a/doc/classes/PackedStringArray.xml +++ b/doc/classes/PackedStringArray.xml @@ -60,13 +60,6 @@ Creates a copy of the array, and returns it. </description> </method> - <method name="is_empty"> - <return type="bool"> - </return> - <description> - Returns [code]true[/code] if the array is empty. - </description> - </method> <method name="has"> <return type="bool"> </return> @@ -94,6 +87,13 @@ Reverses the order of the elements in the array. </description> </method> + <method name="is_empty"> + <return type="bool"> + </return> + <description> + Returns [code]true[/code] if the array is empty. + </description> + </method> <method name="operator !=" qualifiers="operator"> <return type="bool"> </return> diff --git a/doc/classes/PackedVector2Array.xml b/doc/classes/PackedVector2Array.xml index 2f583e2b9b..eb364ddb18 100644 --- a/doc/classes/PackedVector2Array.xml +++ b/doc/classes/PackedVector2Array.xml @@ -60,13 +60,6 @@ Creates a copy of the array, and returns it. </description> </method> - <method name="is_empty"> - <return type="bool"> - </return> - <description> - Returns [code]true[/code] if the array is empty. - </description> - </method> <method name="has"> <return type="bool"> </return> @@ -94,6 +87,13 @@ Reverses the order of the elements in the array. </description> </method> + <method name="is_empty"> + <return type="bool"> + </return> + <description> + Returns [code]true[/code] if the array is empty. + </description> + </method> <method name="operator !=" qualifiers="operator"> <return type="bool"> </return> diff --git a/doc/classes/PackedVector3Array.xml b/doc/classes/PackedVector3Array.xml index 6004454dc9..08ce187b5c 100644 --- a/doc/classes/PackedVector3Array.xml +++ b/doc/classes/PackedVector3Array.xml @@ -59,13 +59,6 @@ Creates a copy of the array, and returns it. </description> </method> - <method name="is_empty"> - <return type="bool"> - </return> - <description> - Returns [code]true[/code] if the array is empty. - </description> - </method> <method name="has"> <return type="bool"> </return> @@ -93,6 +86,13 @@ Reverses the order of the elements in the array. </description> </method> + <method name="is_empty"> + <return type="bool"> + </return> + <description> + Returns [code]true[/code] if the array is empty. + </description> + </method> <method name="operator !=" qualifiers="operator"> <return type="bool"> </return> diff --git a/doc/classes/Plane.xml b/doc/classes/Plane.xml index e3242512c4..ed96f753c2 100644 --- a/doc/classes/Plane.xml +++ b/doc/classes/Plane.xml @@ -142,7 +142,7 @@ <argument index="0" name="to_plane" type="Plane"> </argument> <description> - Returns [code]true[/code] if this plane and [code]plane[/code] are approximately equal, by running [method @GDScript.is_equal_approx] on each component. + Returns [code]true[/code] if this plane and [code]plane[/code] are approximately equal, by running [method @GlobalScope.is_equal_approx] on each component. </description> </method> <method name="is_point_over"> diff --git a/doc/classes/ProjectSettings.xml b/doc/classes/ProjectSettings.xml index d623b0432f..ec380ddc54 100644 --- a/doc/classes/ProjectSettings.xml +++ b/doc/classes/ProjectSettings.xml @@ -1153,6 +1153,12 @@ <member name="rendering/quality/intended_usage/framebuffer_allocation.mobile" type="int" setter="" getter="" default="3"> Lower-end override for [member rendering/quality/intended_usage/framebuffer_allocation] on mobile devices, due to performance concerns or driver support. </member> + <member name="rendering/quality/mesh_lod/threshold_pixels" type="float" setter="" getter="" default="1.0"> + </member> + <member name="rendering/quality/rd_renderer/use_low_end_renderer" type="bool" setter="" getter="" default="false"> + </member> + <member name="rendering/quality/rd_renderer/use_low_end_renderer.mobile" type="bool" setter="" getter="" default="true"> + </member> <member name="rendering/quality/reflection_atlas/reflection_count" type="int" setter="" getter="" default="64"> Number of cubemaps to store in the reflection atlas. The number of [ReflectionProbe]s in a scene will be limited by this amount. A higher number requires more VRAM. </member> @@ -1281,6 +1287,8 @@ </member> <member name="rendering/sdfgi/probe_ray_count" type="int" setter="" getter="" default="2"> </member> + <member name="rendering/spatial_indexer/update_iterations_per_frame" type="int" setter="" getter="" default="10"> + </member> <member name="rendering/threads/thread_model" type="int" setter="" getter="" default="1"> Thread model for rendering. Rendering on a thread can vastly improve performance, but synchronizing to the main thread can cause a bit more jitter. </member> diff --git a/doc/classes/Quat.xml b/doc/classes/Quat.xml index 425e82c744..ef83ae7fb9 100644 --- a/doc/classes/Quat.xml +++ b/doc/classes/Quat.xml @@ -127,7 +127,7 @@ <argument index="0" name="to" type="Quat"> </argument> <description> - Returns [code]true[/code] if this quaterion and [code]quat[/code] are approximately equal, by running [method @GDScript.is_equal_approx] on each component. + Returns [code]true[/code] if this quaterion and [code]quat[/code] are approximately equal, by running [method @GlobalScope.is_equal_approx] on each component. </description> </method> <method name="is_normalized"> diff --git a/doc/classes/Rect2.xml b/doc/classes/Rect2.xml index 3d2852f393..5d7ff39587 100644 --- a/doc/classes/Rect2.xml +++ b/doc/classes/Rect2.xml @@ -72,16 +72,6 @@ Returns a [Rect2] with equivalent position and area, modified so that the top-left corner is the origin and [code]width[/code] and [code]height[/code] are positive. </description> </method> - <method name="intersection"> - <return type="Rect2"> - </return> - <argument index="0" name="b" type="Rect2"> - </argument> - <description> - Returns the intersection of this [Rect2] and [code]b[/code]. - If the rectangles do not intersect, an empty [Rect2] is returned. - </description> - </method> <method name="encloses"> <return type="bool"> </return> @@ -134,7 +124,7 @@ <method name="grow_side"> <return type="Rect2"> </return> - <argument index="0" name="side" type="int" enum="Side"> + <argument index="0" name="side" type="int"> </argument> <argument index="1" name="amount" type="float"> </argument> @@ -158,6 +148,16 @@ Returns [code]true[/code] if the [Rect2] contains a point. </description> </method> + <method name="intersection"> + <return type="Rect2"> + </return> + <argument index="0" name="b" type="Rect2"> + </argument> + <description> + Returns the intersection of this [Rect2] and [code]b[/code]. + If the rectangles do not intersect, an empty [Rect2] is returned. + </description> + </method> <method name="intersects"> <return type="bool"> </return> diff --git a/doc/classes/Rect2i.xml b/doc/classes/Rect2i.xml index 66e5dae78a..e581ccdb11 100644 --- a/doc/classes/Rect2i.xml +++ b/doc/classes/Rect2i.xml @@ -70,16 +70,6 @@ Returns a [Rect2i] with equivalent position and area, modified so that the top-left corner is the origin and [code]width[/code] and [code]height[/code] are positive. </description> </method> - <method name="intersection"> - <return type="Rect2i"> - </return> - <argument index="0" name="b" type="Rect2i"> - </argument> - <description> - Returns the intersection of this [Rect2i] and [code]b[/code]. - If the rectangles do not intersect, an empty [Rect2i] is returned. - </description> - </method> <method name="encloses"> <return type="bool"> </return> @@ -132,7 +122,7 @@ <method name="grow_side"> <return type="Rect2i"> </return> - <argument index="0" name="side" type="int" enum="Side"> + <argument index="0" name="side" type="int"> </argument> <argument index="1" name="amount" type="int"> </argument> @@ -156,6 +146,16 @@ Returns [code]true[/code] if the [Rect2i] contains a point. </description> </method> + <method name="intersection"> + <return type="Rect2i"> + </return> + <argument index="0" name="b" type="Rect2i"> + </argument> + <description> + Returns the intersection of this [Rect2i] and [code]b[/code]. + If the rectangles do not intersect, an empty [Rect2i] is returned. + </description> + </method> <method name="intersects"> <return type="bool"> </return> diff --git a/doc/classes/ReflectionProbe.xml b/doc/classes/ReflectionProbe.xml index 5458b496da..cd08778c89 100644 --- a/doc/classes/ReflectionProbe.xml +++ b/doc/classes/ReflectionProbe.xml @@ -37,6 +37,8 @@ <member name="interior" type="bool" setter="set_as_interior" getter="is_set_as_interior" default="false"> If [code]true[/code], reflections will ignore sky contribution. </member> + <member name="lod_threshold" type="float" setter="set_lod_threshold" getter="get_lod_threshold" default="1.0"> + </member> <member name="max_distance" type="float" setter="set_max_distance" getter="get_max_distance" default="0.0"> Sets the max distance away from the probe an object can be before it is culled. </member> diff --git a/doc/classes/RenderingDevice.xml b/doc/classes/RenderingDevice.xml index 7e5df9c40d..7cdc9ffaca 100644 --- a/doc/classes/RenderingDevice.xml +++ b/doc/classes/RenderingDevice.xml @@ -730,6 +730,8 @@ </argument> <argument index="1" name="data" type="PackedByteArray" default="PackedByteArray( )"> </argument> + <argument index="2" name="use_as_storage" type="bool" default="false"> + </argument> <description> </description> </method> diff --git a/doc/classes/RenderingServer.xml b/doc/classes/RenderingServer.xml index 036b50f0ed..4be97b7d3d 100644 --- a/doc/classes/RenderingServer.xml +++ b/doc/classes/RenderingServer.xml @@ -859,6 +859,12 @@ Tries to free an object in the RenderingServer. </description> </method> + <method name="get_frame_setup_time_cpu" qualifiers="const"> + <return type="float"> + </return> + <description> + </description> + </method> <method name="get_render_info"> <return type="int"> </return> @@ -1354,7 +1360,7 @@ <argument index="1" name="scenario" type="RID"> </argument> <description> - Returns an array of object IDs intersecting with the provided AABB. Only visual 3D nodes are considered, such as [MeshInstance3D] or [DirectionalLight3D]. Use [method @GDScript.instance_from_id] to obtain the actual nodes. A scenario RID must be provided, which is available in the [World3D] you want to query. This forces an update for all resources queued to update. + Returns an array of object IDs intersecting with the provided AABB. Only visual 3D nodes are considered, such as [MeshInstance3D] or [DirectionalLight3D]. Use [method @GlobalScope.instance_from_id] to obtain the actual nodes. A scenario RID must be provided, which is available in the [World3D] you want to query. This forces an update for all resources queued to update. [b]Warning:[/b] This function is primarily intended for editor usage. For in-game use cases, prefer physics collision. </description> </method> @@ -1366,7 +1372,7 @@ <argument index="1" name="scenario" type="RID"> </argument> <description> - Returns an array of object IDs intersecting with the provided convex shape. Only visual 3D nodes are considered, such as [MeshInstance3D] or [DirectionalLight3D]. Use [method @GDScript.instance_from_id] to obtain the actual nodes. A scenario RID must be provided, which is available in the [World3D] you want to query. This forces an update for all resources queued to update. + Returns an array of object IDs intersecting with the provided convex shape. Only visual 3D nodes are considered, such as [MeshInstance3D] or [DirectionalLight3D]. Use [method @GlobalScope.instance_from_id] to obtain the actual nodes. A scenario RID must be provided, which is available in the [World3D] you want to query. This forces an update for all resources queued to update. [b]Warning:[/b] This function is primarily intended for editor usage. For in-game use cases, prefer physics collision. </description> </method> @@ -1380,7 +1386,7 @@ <argument index="2" name="scenario" type="RID"> </argument> <description> - Returns an array of object IDs intersecting with the provided 3D ray. Only visual 3D nodes are considered, such as [MeshInstance3D] or [DirectionalLight3D]. Use [method @GDScript.instance_from_id] to obtain the actual nodes. A scenario RID must be provided, which is available in the [World3D] you want to query. This forces an update for all resources queued to update. + Returns an array of object IDs intersecting with the provided 3D ray. Only visual 3D nodes are considered, such as [MeshInstance3D] or [DirectionalLight3D]. Use [method @GlobalScope.instance_from_id] to obtain the actual nodes. A scenario RID must be provided, which is available in the [World3D] you want to query. This forces an update for all resources queued to update. [b]Warning:[/b] This function is primarily intended for editor usage. For in-game use cases, prefer physics collision. </description> </method> @@ -2715,6 +2721,22 @@ Once finished with your RID, you will want to free the RID using the RenderingServer's [method free_rid] static method. </description> </method> + <method name="viewport_get_measured_render_time_cpu" qualifiers="const"> + <return type="float"> + </return> + <argument index="0" name="viewport" type="RID"> + </argument> + <description> + </description> + </method> + <method name="viewport_get_measured_render_time_gpu" qualifiers="const"> + <return type="float"> + </return> + <argument index="0" name="viewport" type="RID"> + </argument> + <description> + </description> + </method> <method name="viewport_get_render_info"> <return type="int"> </return> @@ -2852,6 +2874,16 @@ Currently unimplemented in Godot 3.x. </description> </method> + <method name="viewport_set_measure_render_time"> + <return type="void"> + </return> + <argument index="0" name="viewport" type="RID"> + </argument> + <argument index="1" name="enable" type="bool"> + </argument> + <description> + </description> + </method> <method name="viewport_set_msaa"> <return type="void"> </return> diff --git a/doc/classes/SceneTree.xml b/doc/classes/SceneTree.xml index 5fc1d0b895..2c99815abf 100644 --- a/doc/classes/SceneTree.xml +++ b/doc/classes/SceneTree.xml @@ -260,7 +260,7 @@ The default [MultiplayerAPI] instance for this [SceneTree]. </member> <member name="multiplayer_poll" type="bool" setter="set_multiplayer_poll_enabled" getter="is_multiplayer_poll_enabled" default="true"> - If [code]true[/code] (default value), enables automatic polling of the [MultiplayerAPI] for this SceneTree during [signal idle_frame]. + If [code]true[/code] (default value), enables automatic polling of the [MultiplayerAPI] for this SceneTree during [signal process_frame]. If [code]false[/code], you need to manually call [method MultiplayerAPI.poll] to process network packets and deliver RPCs/RSETs. This allows running RPCs/RSETs in a different loop (e.g. physics, thread, specific time step) and for manual [Mutex] protection when accessing the [MultiplayerAPI] from threads. </member> <member name="network_peer" type="NetworkedMultiplayerPeer" setter="set_network_peer" getter="get_network_peer"> @@ -298,11 +298,6 @@ Emitted when files are dragged from the OS file manager and dropped in the game window. The arguments are a list of file paths and the identifier of the screen where the drag originated. </description> </signal> - <signal name="idle_frame"> - <description> - Emitted immediately before [method Node._process] is called on every node in the [SceneTree]. - </description> - </signal> <signal name="network_peer_connected"> <argument index="0" name="id" type="int"> </argument> @@ -350,6 +345,11 @@ Emitted immediately before [method Node._physics_process] is called on every node in the [SceneTree]. </description> </signal> + <signal name="process_frame"> + <description> + Emitted immediately before [method Node._process] is called on every node in the [SceneTree]. + </description> + </signal> <signal name="server_disconnected"> <description> Emitted whenever this [SceneTree]'s [member network_peer] disconnected from server. Only emitted on clients. diff --git a/doc/classes/String.xml b/doc/classes/String.xml index cbaf1196e3..79f21a0e70 100644 --- a/doc/classes/String.xml +++ b/doc/classes/String.xml @@ -135,13 +135,6 @@ Returns a copy of the string with indentation (leading tabs and spaces) removed. </description> </method> - <method name="is_empty"> - <return type="bool"> - </return> - <description> - Returns [code]true[/code] if the length of the string equals [code]0[/code]. - </description> - </method> <method name="ends_with"> <return type="bool"> </return> @@ -276,6 +269,13 @@ If the string is a path to a file or directory, returns [code]true[/code] if the path is absolute. </description> </method> + <method name="is_empty"> + <return type="bool"> + </return> + <description> + Returns [code]true[/code] if the length of the string equals [code]0[/code]. + </description> + </method> <method name="is_rel_path"> <return type="bool"> </return> diff --git a/doc/classes/StyleBox.xml b/doc/classes/StyleBox.xml index 525dba0549..a01dfbd4b8 100644 --- a/doc/classes/StyleBox.xml +++ b/doc/classes/StyleBox.xml @@ -39,7 +39,7 @@ <method name="get_default_margin" qualifiers="const"> <return type="float"> </return> - <argument index="0" name="side" type="int" enum="Side"> + <argument index="0" name="margin" type="int" enum="Side"> </argument> <description> Returns the default margin of the specified [enum Side]. @@ -48,7 +48,7 @@ <method name="get_margin" qualifiers="const"> <return type="float"> </return> - <argument index="0" name="side" type="int" enum="Side"> + <argument index="0" name="margin" type="int" enum="Side"> </argument> <description> Returns the content margin offset for the specified [enum Side]. @@ -72,7 +72,7 @@ <method name="set_default_margin"> <return type="void"> </return> - <argument index="0" name="side" type="int" enum="Side"> + <argument index="0" name="margin" type="int" enum="Side"> </argument> <argument index="1" name="offset" type="float"> </argument> diff --git a/doc/classes/StyleBoxFlat.xml b/doc/classes/StyleBoxFlat.xml index 71f227dfb0..13ea7df294 100644 --- a/doc/classes/StyleBoxFlat.xml +++ b/doc/classes/StyleBoxFlat.xml @@ -27,7 +27,7 @@ <method name="get_border_width" qualifiers="const"> <return type="int"> </return> - <argument index="0" name="side" type="int" enum="Side"> + <argument index="0" name="margin" type="int" enum="Side"> </argument> <description> Returns the specified [enum Side]'s border width. @@ -52,7 +52,7 @@ <method name="get_expand_margin" qualifiers="const"> <return type="float"> </return> - <argument index="0" name="side" type="int" enum="Side"> + <argument index="0" name="margin" type="int" enum="Side"> </argument> <description> Returns the size of the specified [enum Side]'s expand margin. @@ -61,7 +61,7 @@ <method name="set_border_width"> <return type="void"> </return> - <argument index="0" name="side" type="int" enum="Side"> + <argument index="0" name="margin" type="int" enum="Side"> </argument> <argument index="1" name="width" type="int"> </argument> @@ -116,7 +116,7 @@ <method name="set_expand_margin"> <return type="void"> </return> - <argument index="0" name="side" type="int" enum="Side"> + <argument index="0" name="margin" type="int" enum="Side"> </argument> <argument index="1" name="size" type="float"> </argument> diff --git a/doc/classes/StyleBoxTexture.xml b/doc/classes/StyleBoxTexture.xml index 5b17f25978..895d0c357d 100644 --- a/doc/classes/StyleBoxTexture.xml +++ b/doc/classes/StyleBoxTexture.xml @@ -12,7 +12,7 @@ <method name="get_expand_margin_size" qualifiers="const"> <return type="float"> </return> - <argument index="0" name="side" type="int" enum="Side"> + <argument index="0" name="margin" type="int" enum="Side"> </argument> <description> Returns the expand margin size of the specified [enum Side]. @@ -21,7 +21,7 @@ <method name="get_margin_size" qualifiers="const"> <return type="float"> </return> - <argument index="0" name="side" type="int" enum="Side"> + <argument index="0" name="margin" type="int" enum="Side"> </argument> <description> Returns the margin size of the specified [enum Side]. @@ -54,7 +54,7 @@ <method name="set_expand_margin_size"> <return type="void"> </return> - <argument index="0" name="side" type="int" enum="Side"> + <argument index="0" name="margin" type="int" enum="Side"> </argument> <argument index="1" name="size" type="float"> </argument> @@ -65,7 +65,7 @@ <method name="set_margin_size"> <return type="void"> </return> - <argument index="0" name="side" type="int" enum="Side"> + <argument index="0" name="margin" type="int" enum="Side"> </argument> <argument index="1" name="size" type="float"> </argument> diff --git a/doc/classes/SurfaceTool.xml b/doc/classes/SurfaceTool.xml index 82ffe86251..e10b65e309 100644 --- a/doc/classes/SurfaceTool.xml +++ b/doc/classes/SurfaceTool.xml @@ -31,15 +31,6 @@ Adds an index to index array if you are using indexed vertices. Does not need to be called before adding vertices. </description> </method> - <method name="add_smooth_group"> - <return type="void"> - </return> - <argument index="0" name="smooth" type="bool"> - </argument> - <description> - Specifies whether the current vertex (if using only vertex arrays) or current index (if also using index arrays) should use smooth normals for normal calculation. - </description> - </method> <method name="add_triangle_fan"> <return type="void"> </return> @@ -148,6 +139,16 @@ Removes the index array by expanding the vertex array. </description> </method> + <method name="generate_lod"> + <return type="PackedInt32Array"> + </return> + <argument index="0" name="nd_threshold" type="float"> + </argument> + <argument index="1" name="target_index_count" type="int" default="3"> + </argument> + <description> + </description> + </method> <method name="generate_normals"> <return type="void"> </return> @@ -173,6 +174,12 @@ <description> </description> </method> + <method name="get_max_axis_length" qualifiers="const"> + <return type="float"> + </return> + <description> + </description> + </method> <method name="get_skin_weight_count" qualifiers="const"> <return type="int" enum="SurfaceTool.SkinWeightCount"> </return> @@ -186,6 +193,12 @@ Shrinks the vertex array by creating an index array (avoids reusing vertices). </description> </method> + <method name="optimize_indices_for_cache"> + <return type="void"> + </return> + <description> + </description> + </method> <method name="set_bones"> <return type="void"> </return> @@ -251,6 +264,15 @@ <description> </description> </method> + <method name="set_smooth_group"> + <return type="void"> + </return> + <argument index="0" name="index" type="int"> + </argument> + <description> + Specifies whether the current vertex (if using only vertex arrays) or current index (if also using index arrays) should use smooth normals for normal calculation. + </description> + </method> <method name="set_tangent"> <return type="void"> </return> diff --git a/doc/classes/TabContainer.xml b/doc/classes/TabContainer.xml index c9ed1aaec9..10cdd0eade 100644 --- a/doc/classes/TabContainer.xml +++ b/doc/classes/TabContainer.xml @@ -137,6 +137,9 @@ </method> </methods> <members> + <member name="all_tabs_in_front" type="bool" setter="set_all_tabs_in_front" getter="is_all_tabs_in_front" default="false"> + If [code]true[/code], all tabs are drawn in front of the panel. If [code]false[/code], inactive tabs are drawn behind the panel. + </member> <member name="current_tab" type="int" setter="set_current_tab" getter="get_current_tab" default="0"> The current tab index. When set, this index's [Control] node's [code]visible[/code] property is set to [code]true[/code] and all others are set to [code]false[/code]. </member> @@ -149,9 +152,6 @@ <member name="tabs_visible" type="bool" setter="set_tabs_visible" getter="are_tabs_visible" default="true"> If [code]true[/code], tabs are visible. If [code]false[/code], tabs' content and titles are hidden. </member> - <member name="all_tabs_in_front" type="bool" setter="set_all_tabs_in_front" getter="is_all_tabs_in_front" default="false"> - If [code]true[/code], all tabs are drawn in front of the panel. If [code]false[/code], inactive tabs are drawn behind the panel. - </member> <member name="use_hidden_tabs_for_min_size" type="bool" setter="set_use_hidden_tabs_for_min_size" getter="get_use_hidden_tabs_for_min_size" default="false"> If [code]true[/code], children [Control] nodes that are hidden have their minimum size take into account in the total, instead of only the currently visible one. </member> diff --git a/doc/classes/TextureProgressBar.xml b/doc/classes/TextureProgressBar.xml index cfc8f16648..b40759578f 100644 --- a/doc/classes/TextureProgressBar.xml +++ b/doc/classes/TextureProgressBar.xml @@ -12,7 +12,7 @@ <method name="get_stretch_margin" qualifiers="const"> <return type="int"> </return> - <argument index="0" name="side" type="int" enum="Side"> + <argument index="0" name="margin" type="int" enum="Side"> </argument> <description> </description> @@ -20,7 +20,7 @@ <method name="set_stretch_margin"> <return type="void"> </return> - <argument index="0" name="side" type="int" enum="Side"> + <argument index="0" name="margin" type="int" enum="Side"> </argument> <argument index="1" name="value" type="int"> </argument> diff --git a/doc/classes/Variant.xml b/doc/classes/Variant.xml index cd76689ffe..775bd58bcf 100644 --- a/doc/classes/Variant.xml +++ b/doc/classes/Variant.xml @@ -17,7 +17,7 @@ - VisualScript tracks properties inside Variants as well, but it also uses static typing. The GUI interface enforces that properties have a particular type that doesn't change over time. - C# is statically typed, but uses the Mono [code]object[/code] type in place of Godot's Variant class when it needs to represent a dynamic value. [code]object[/code] is the Mono runtime's equivalent of the same concept. - The statically-typed language NativeScript C++ does not define a built-in Variant-like class. Godot's GDNative bindings provide their own godot::Variant class for users; Any point at which the C++ code starts interacting with the Godot runtime is a place where you might have to start wrapping data inside Variant objects. - The global [method @GDScript.typeof] function returns the enumerated value of the Variant type stored in the current variable (see [enum Variant.Type]). + The global [method @GlobalScope.typeof] function returns the enumerated value of the Variant type stored in the current variable (see [enum Variant.Type]). [codeblock] var foo = 2 match typeof(foo): diff --git a/doc/classes/Vector2.xml b/doc/classes/Vector2.xml index fef2d7cedd..4159a38d96 100644 --- a/doc/classes/Vector2.xml +++ b/doc/classes/Vector2.xml @@ -66,7 +66,7 @@ <description> Returns this vector's angle with respect to the positive X axis, or [code](1, 0)[/code] vector, in radians. For example, [code]Vector2.RIGHT.angle()[/code] will return zero, [code]Vector2.DOWN.angle()[/code] will return [code]PI / 2[/code] (a quarter turn, or 90 degrees), and [code]Vector2(1, -1).angle()[/code] will return [code]-PI / 4[/code] (a negative eighth turn, or -45 degrees). - Equivalent to the result of [method @GDScript.atan2] when called with the vector's [member y] and [member x] as parameters: [code]atan2(y, x)[/code]. + Equivalent to the result of [method @GlobalScope.atan2] when called with the vector's [member y] and [member x] as parameters: [code]atan2(y, x)[/code]. </description> </method> <method name="angle_to"> @@ -196,7 +196,7 @@ <argument index="0" name="to" type="Vector2"> </argument> <description> - Returns [code]true[/code] if this vector and [code]v[/code] are approximately equal, by running [method @GDScript.is_equal_approx] on each component. + Returns [code]true[/code] if this vector and [code]v[/code] are approximately equal, by running [method @GlobalScope.is_equal_approx] on each component. </description> </method> <method name="is_normalized"> @@ -390,13 +390,20 @@ <description> </description> </method> + <method name="orthogonal"> + <return type="Vector2"> + </return> + <description> + Returns a perpendicular vector rotated 90 degrees counter-clockwise compared to the original, with the same length. + </description> + </method> <method name="posmod"> <return type="Vector2"> </return> <argument index="0" name="mod" type="float"> </argument> <description> - Returns a vector composed of the [method @GDScript.fposmod] of this vector's components and [code]mod[/code]. + Returns a vector composed of the [method @GlobalScope.fposmod] of this vector's components and [code]mod[/code]. </description> </method> <method name="posmodv"> @@ -405,7 +412,7 @@ <argument index="0" name="modv" type="Vector2"> </argument> <description> - Returns a vector composed of the [method @GDScript.fposmod] of this vector's components and [code]modv[/code]'s components. + Returns a vector composed of the [method @GlobalScope.fposmod] of this vector's components and [code]modv[/code]'s components. </description> </method> <method name="project"> @@ -432,7 +439,7 @@ <argument index="0" name="phi" type="float"> </argument> <description> - Returns the vector rotated by [code]phi[/code] radians. See also [method @GDScript.deg2rad]. + Returns the vector rotated by [code]phi[/code] radians. See also [method @GlobalScope.deg2rad]. </description> </method> <method name="round"> @@ -446,7 +453,7 @@ <return type="Vector2"> </return> <description> - Returns the vector with each component set to one or negative one, depending on the signs of the components, or zero if the component is zero, by calling [method @GDScript.sign] on each component. + Returns the vector with each component set to one or negative one, depending on the signs of the components, or zero if the component is zero, by calling [method @GlobalScope.sign] on each component. </description> </method> <method name="slerp"> @@ -479,13 +486,6 @@ Returns this vector with each component snapped to the nearest multiple of [code]step[/code]. This can also be used to round to an arbitrary number of decimals. </description> </method> - <method name="orthogonal"> - <return type="Vector2"> - </return> - <description> - Returns a perpendicular vector rotated 90 degrees counter-clockwise compared to the original, with the same length. - </description> - </method> </methods> <members> <member name="x" type="float" setter="" getter="" default="0.0"> diff --git a/doc/classes/Vector3.xml b/doc/classes/Vector3.xml index 46fd45f85f..2d129a2c86 100644 --- a/doc/classes/Vector3.xml +++ b/doc/classes/Vector3.xml @@ -171,7 +171,7 @@ <argument index="0" name="to" type="Vector3"> </argument> <description> - Returns [code]true[/code] if this vector and [code]v[/code] are approximately equal, by running [method @GDScript.is_equal_approx] on each component. + Returns [code]true[/code] if this vector and [code]v[/code] are approximately equal, by running [method @GlobalScope.is_equal_approx] on each component. </description> </method> <method name="is_normalized"> @@ -410,7 +410,7 @@ <argument index="0" name="mod" type="float"> </argument> <description> - Returns a vector composed of the [method @GDScript.fposmod] of this vector's components and [code]mod[/code]. + Returns a vector composed of the [method @GlobalScope.fposmod] of this vector's components and [code]mod[/code]. </description> </method> <method name="posmodv"> @@ -419,7 +419,7 @@ <argument index="0" name="modv" type="Vector3"> </argument> <description> - Returns a vector composed of the [method @GDScript.fposmod] of this vector's components and [code]modv[/code]'s components. + Returns a vector composed of the [method @GlobalScope.fposmod] of this vector's components and [code]modv[/code]'s components. </description> </method> <method name="project"> @@ -462,7 +462,7 @@ <return type="Vector3"> </return> <description> - Returns a vector with each component set to one or negative one, depending on the signs of this vector's components, or zero if the component is zero, by calling [method @GDScript.sign] on each component. + Returns a vector with each component set to one or negative one, depending on the signs of this vector's components, or zero if the component is zero, by calling [method @GlobalScope.sign] on each component. </description> </method> <method name="slerp"> diff --git a/doc/classes/Viewport.xml b/doc/classes/Viewport.xml index 7b513d56c3..e66b8353a8 100644 --- a/doc/classes/Viewport.xml +++ b/doc/classes/Viewport.xml @@ -222,6 +222,8 @@ </member> <member name="handle_input_locally" type="bool" setter="set_handle_input_locally" getter="is_handling_input_locally" default="true"> </member> + <member name="lod_threshold" type="float" setter="set_lod_threshold" getter="get_lod_threshold" default="1.0"> + </member> <member name="msaa" type="int" setter="set_msaa" getter="get_msaa" enum="Viewport.MSAA" default="0"> The multisample anti-aliasing mode. A higher number results in smoother edges at the cost of significantly worse performance. A value of 4 is best unless targeting very high-end systems. </member> @@ -405,6 +407,8 @@ </constant> <constant name="DEBUG_DRAW_GI_BUFFER" value="17" enum="DebugDraw"> </constant> + <constant name="DEBUG_DRAW_DISABLE_LOD" value="18" enum="DebugDraw"> + </constant> <constant name="DEFAULT_CANVAS_ITEM_TEXTURE_FILTER_NEAREST" value="0" enum="DefaultCanvasItemTextureFilter"> The texture filter reads from the nearest pixel only. The simplest and fastest method of filtering, but the texture will look pixelized. </constant> diff --git a/doc/classes/WeakRef.xml b/doc/classes/WeakRef.xml index 07d82289a3..4140df5828 100644 --- a/doc/classes/WeakRef.xml +++ b/doc/classes/WeakRef.xml @@ -4,7 +4,7 @@ Holds an [Object], but does not contribute to the reference count if the object is a reference. </brief_description> <description> - A weakref can hold a [Reference], without contributing to the reference counter. A weakref can be created from an [Object] using [method @GDScript.weakref]. If this object is not a reference, weakref still works, however, it does not have any effect on the object. Weakrefs are useful in cases where multiple classes have variables that refer to each other. Without weakrefs, using these classes could lead to memory leaks, since both references keep each other from being released. Making part of the variables a weakref can prevent this cyclic dependency, and allows the references to be released. + A weakref can hold a [Reference], without contributing to the reference counter. A weakref can be created from an [Object] using [method @GlobalScope.weakref]. If this object is not a reference, weakref still works, however, it does not have any effect on the object. Weakrefs are useful in cases where multiple classes have variables that refer to each other. Without weakrefs, using these classes could lead to memory leaks, since both references keep each other from being released. Making part of the variables a weakref can prevent this cyclic dependency, and allows the references to be released. </description> <tutorials> </tutorials> diff --git a/doc/classes/XRController3D.xml b/doc/classes/XRController3D.xml index 345e5efdee..a4a86cc22a 100644 --- a/doc/classes/XRController3D.xml +++ b/doc/classes/XRController3D.xml @@ -19,13 +19,6 @@ If active, returns the name of the associated controller if provided by the AR/VR SDK used. </description> </method> - <method name="get_tracker_hand" qualifiers="const"> - <return type="int" enum="XRPositionalTracker.TrackerHand"> - </return> - <description> - Returns the hand holding this controller, if known. See [enum XRPositionalTracker.TrackerHand]. - </description> - </method> <method name="get_is_active" qualifiers="const"> <return type="bool"> </return> @@ -56,6 +49,13 @@ If provided by the [XRInterface], this returns a mesh associated with the controller. This can be used to visualize the controller. </description> </method> + <method name="get_tracker_hand" qualifiers="const"> + <return type="int" enum="XRPositionalTracker.TrackerHand"> + </return> + <description> + Returns the hand holding this controller, if known. See [enum XRPositionalTracker.TrackerHand]. + </description> + </method> <method name="is_button_pressed" qualifiers="const"> <return type="bool"> </return> diff --git a/doc/classes/XRPositionalTracker.xml b/doc/classes/XRPositionalTracker.xml index 36ff312e4d..36cd6e2ea0 100644 --- a/doc/classes/XRPositionalTracker.xml +++ b/doc/classes/XRPositionalTracker.xml @@ -12,13 +12,6 @@ <link title="VR tutorial index">https://docs.godotengine.org/en/latest/tutorials/vr/index.html</link> </tutorials> <methods> - <method name="get_tracker_hand" qualifiers="const"> - <return type="int" enum="XRPositionalTracker.TrackerHand"> - </return> - <description> - Returns the hand holding this tracker, if known. See [enum TrackerHand] constants. - </description> - </method> <method name="get_joy_id" qualifiers="const"> <return type="int"> </return> @@ -47,6 +40,13 @@ Returns the world-space controller position. </description> </method> + <method name="get_tracker_hand" qualifiers="const"> + <return type="int" enum="XRPositionalTracker.TrackerHand"> + </return> + <description> + Returns the hand holding this tracker, if known. See [enum TrackerHand] constants. + </description> + </method> <method name="get_tracker_id" qualifiers="const"> <return type="int"> </return> @@ -68,6 +68,15 @@ Returns the tracker's type, which will be one of the values from the [enum XRServer.TrackerType] enum. </description> </method> + <method name="get_transform" qualifiers="const"> + <return type="Transform"> + </return> + <argument index="0" name="adjust_by_reference_frame" type="bool"> + </argument> + <description> + Returns the transform combining this device's orientation and position. + </description> + </method> <method name="is_tracking_orientation" qualifiers="const"> <return type="bool"> </return> @@ -82,15 +91,6 @@ Returns [code]true[/code] if this device is tracking position. </description> </method> - <method name="get_transform" qualifiers="const"> - <return type="Transform"> - </return> - <argument index="0" name="adjust_by_reference_frame" type="bool"> - </argument> - <description> - Returns the transform combining this device's orientation and position. - </description> - </method> </methods> <members> <member name="rumble" type="float" setter="set_rumble" getter="get_rumble" default="0.0"> diff --git a/drivers/vulkan/rendering_device_vulkan.cpp b/drivers/vulkan/rendering_device_vulkan.cpp index 474e801146..52e090e4ed 100644 --- a/drivers/vulkan/rendering_device_vulkan.cpp +++ b/drivers/vulkan/rendering_device_vulkan.cpp @@ -2134,7 +2134,16 @@ RID RenderingDeviceVulkan::texture_create_shared_from_slice(const TextureView &p VK_IMAGE_VIEW_TYPE_2D, }; - image_view_create_info.viewType = p_slice_type == TEXTURE_SLICE_CUBEMAP ? VK_IMAGE_VIEW_TYPE_CUBE : (p_slice_type == TEXTURE_SLICE_3D ? VK_IMAGE_VIEW_TYPE_3D : view_types[texture.type]); + image_view_create_info.viewType = view_types[texture.type]; + + if (p_slice_type == TEXTURE_SLICE_CUBEMAP) { + image_view_create_info.viewType = VK_IMAGE_VIEW_TYPE_CUBE; + } else if (p_slice_type == TEXTURE_SLICE_3D) { + image_view_create_info.viewType = VK_IMAGE_VIEW_TYPE_3D; + } else if (p_slice_type == TEXTURE_SLICE_2D_ARRAY) { + image_view_create_info.viewType = VK_IMAGE_VIEW_TYPE_2D_ARRAY; + } + if (p_view.format_override == DATA_FORMAT_MAX || p_view.format_override == texture.format) { image_view_create_info.format = vulkan_formats[texture.format]; } else { diff --git a/editor/editor_log.cpp b/editor/editor_log.cpp index 859292c573..7b94016fb6 100644 --- a/editor/editor_log.cpp +++ b/editor/editor_log.cpp @@ -101,8 +101,6 @@ void EditorLog::copy() { } void EditorLog::add_message(const String &p_msg, MessageType p_type) { - log->add_newline(); - bool restore = p_type != MSG_TYPE_STD; switch (p_type) { case MSG_TYPE_STD: { @@ -128,6 +126,7 @@ void EditorLog::add_message(const String &p_msg, MessageType p_type) { } log->add_text(p_msg); + log->add_newline(); if (restore) { log->pop(); diff --git a/editor/import/resource_importer_texture.cpp b/editor/import/resource_importer_texture.cpp index ea7b05dff3..eb16e873e6 100644 --- a/editor/import/resource_importer_texture.cpp +++ b/editor/import/resource_importer_texture.cpp @@ -201,7 +201,7 @@ void ResourceImporterTexture::get_import_options(List<ImportOption> *r_options, r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "compress/bptc_ldr", PROPERTY_HINT_ENUM, "Disabled,Enabled,RGBA Only"), 0)); r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "compress/normal_map", PROPERTY_HINT_ENUM, "Detect,Enable,Disabled"), 0)); r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "compress/channel_pack", PROPERTY_HINT_ENUM, "sRGB Friendly,Optimized"), 0)); - r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "compress/streamed"), false)); + r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "compress/streamed"), false)); r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "mipmaps/generate"), (p_preset == PRESET_3D ? true : false))); r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "mipmaps/limit", PROPERTY_HINT_RANGE, "-1,256"), -1)); r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "roughness/mode", PROPERTY_HINT_ENUM, "Detect,Disabled,Red,Green,Blue,Alpha,Gray"), 0)); diff --git a/editor/plugins/node_3d_editor_plugin.cpp b/editor/plugins/node_3d_editor_plugin.cpp index 9f710d218c..3e8547439f 100644 --- a/editor/plugins/node_3d_editor_plugin.cpp +++ b/editor/plugins/node_3d_editor_plugin.cpp @@ -4141,6 +4141,10 @@ Node3DEditorViewport::Node3DEditorViewport(Node3DEditor *p_spatial_editor, Edito EditorSettings::get_singleton()->connect("settings_changed", callable_mp(this, &Node3DEditorViewport::update_transform_gizmo_view)); } +Node3DEditorViewport::~Node3DEditorViewport() { + memdelete(frame_time_gradient); +} + ////////////////////////////////////////////////////////////// void Node3DEditorViewportContainer::_gui_input(const Ref<InputEvent> &p_event) { diff --git a/editor/plugins/node_3d_editor_plugin.h b/editor/plugins/node_3d_editor_plugin.h index 624bc2d88a..0cefaa6557 100644 --- a/editor/plugins/node_3d_editor_plugin.h +++ b/editor/plugins/node_3d_editor_plugin.h @@ -483,6 +483,7 @@ public: Camera3D *get_camera() { return camera; } // return the default camera object. Node3DEditorViewport(Node3DEditor *p_spatial_editor, EditorNode *p_editor, int p_index); + ~Node3DEditorViewport(); }; class Node3DEditorSelectedItem : public Object { diff --git a/editor/plugins/tile_map_editor_plugin.cpp b/editor/plugins/tile_map_editor_plugin.cpp index dffa796e8d..6a16aa28a9 100644 --- a/editor/plugins/tile_map_editor_plugin.cpp +++ b/editor/plugins/tile_map_editor_plugin.cpp @@ -39,7 +39,10 @@ #include "scene/gui/split_container.h" void TileMapEditor::_node_removed(Node *p_node) { - if (p_node == node) { + if (p_node == node && node) { + // Fixes #44824, which describes a situation where you can reselect a TileMap node without first de-selecting it when switching scenes. + node->disconnect("settings_changed", callable_mp(this, &TileMapEditor::_tileset_settings_changed)); + node = nullptr; } } diff --git a/modules/fbx/doc_classes/EditorSceneImporterFBX.xml b/modules/fbx/doc_classes/EditorSceneImporterFBX.xml index 72b6e0f5fd..da1a68c27c 100644 --- a/modules/fbx/doc_classes/EditorSceneImporterFBX.xml +++ b/modules/fbx/doc_classes/EditorSceneImporterFBX.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="EditorSceneImporterFBX" inherits="EditorSceneImporter" version="3.2"> +<class name="EditorSceneImporterFBX" inherits="EditorSceneImporter" version="4.0"> <brief_description> FBX 3D asset importer. </brief_description> diff --git a/modules/gdnative/gdnative/string.cpp b/modules/gdnative/gdnative/string.cpp index f704d6c169..734bbe0d16 100644 --- a/modules/gdnative/gdnative/string.cpp +++ b/modules/gdnative/gdnative/string.cpp @@ -1112,7 +1112,7 @@ godot_string GDAPI godot_string_get_file(const godot_string *p_self) { return result; } -godot_string GDAPI godot_string_humanize_size(size_t p_size) { +godot_string GDAPI godot_string_humanize_size(uint64_t p_size) { godot_string result; String return_value = String::humanize_size(p_size); memnew_placement(&result, String(return_value)); diff --git a/modules/gdnative/gdnative_api.json b/modules/gdnative/gdnative_api.json index e104c77eae..a29a0808ca 100644 --- a/modules/gdnative/gdnative_api.json +++ b/modules/gdnative/gdnative_api.json @@ -5029,7 +5029,7 @@ "name": "godot_string_humanize_size", "return_type": "godot_string", "arguments": [ - ["size_t", "p_size"] + ["uint64_t", "p_size"] ] }, { diff --git a/modules/gdnative/include/gdnative/string.h b/modules/gdnative/include/gdnative/string.h index 8f249792bb..e58be18b21 100644 --- a/modules/gdnative/include/gdnative/string.h +++ b/modules/gdnative/include/gdnative/string.h @@ -261,7 +261,7 @@ godot_bool godot_string_is_empty(const godot_string *p_self); // path functions godot_string GDAPI godot_string_get_base_dir(const godot_string *p_self); godot_string GDAPI godot_string_get_file(const godot_string *p_self); -godot_string GDAPI godot_string_humanize_size(size_t p_size); +godot_string GDAPI godot_string_humanize_size(uint64_t p_size); godot_bool GDAPI godot_string_is_abs_path(const godot_string *p_self); godot_bool GDAPI godot_string_is_rel_path(const godot_string *p_self); godot_bool GDAPI godot_string_is_resource_file(const godot_string *p_self); diff --git a/modules/gdscript/doc_classes/@GDScript.xml b/modules/gdscript/doc_classes/@GDScript.xml index d60ed8c60c..9e974b6fdc 100644 --- a/modules/gdscript/doc_classes/@GDScript.xml +++ b/modules/gdscript/doc_classes/@GDScript.xml @@ -32,59 +32,6 @@ [/codeblock] </description> </method> - <method name="ColorN"> - <return type="Color"> - </return> - <argument index="0" name="name" type="String"> - </argument> - <argument index="1" name="alpha" type="float" default="1.0"> - </argument> - <description> - Returns a color according to the standardized [code]name[/code] with [code]alpha[/code] ranging from 0 to 1. - [codeblock] - red = ColorN("red", 1) - [/codeblock] - Supported color names are the same as the constants defined in [Color]. - </description> - </method> - <method name="abs"> - <return type="float"> - </return> - <argument index="0" name="s" type="float"> - </argument> - <description> - Returns the absolute value of parameter [code]s[/code] (i.e. positive value). - [codeblock] - a = abs(-1) # a is 1 - [/codeblock] - </description> - </method> - <method name="acos"> - <return type="float"> - </return> - <argument index="0" name="s" type="float"> - </argument> - <description> - Returns the arc cosine of [code]s[/code] in radians. Use to get the angle of cosine [code]s[/code]. - [codeblock] - # c is 0.523599 or 30 degrees if converted with rad2deg(s) - c = acos(0.866025) - [/codeblock] - </description> - </method> - <method name="asin"> - <return type="float"> - </return> - <argument index="0" name="s" type="float"> - </argument> - <description> - Returns the arc sine of [code]s[/code] in radians. Use to get the angle of sine [code]s[/code]. - [codeblock] - # s is 0.523599 or 30 degrees if converted with rad2deg(s) - s = asin(0.5) - [/codeblock] - </description> - </method> <method name="assert"> <return type="void"> </return> @@ -93,7 +40,7 @@ <argument index="1" name="message" type="String" default=""""> </argument> <description> - Asserts that the [code]condition[/code] is [code]true[/code]. If the [code]condition[/code] is [code]false[/code], an error is generated. When running from the editor, the running project will also be paused until you resume it. This can be used as a stronger form of [method push_error] for reporting errors to project developers or add-on users. + Asserts that the [code]condition[/code] is [code]true[/code]. If the [code]condition[/code] is [code]false[/code], an error is generated. When running from the editor, the running project will also be paused until you resume it. This can be used as a stronger form of [method @GlobalScope.push_error] for reporting errors to project developers or add-on users. [b]Note:[/b] For performance reasons, the code inside [method assert] is only executed in debug builds or when running the project from the editor. Don't include code that has side effects in an [method assert] call. Otherwise, the project will behave differently when exported in release mode. The optional [code]message[/code] argument, if given, is shown in addition to the generic "Assertion failed" message. You can use this to provide additional details about why the assertion failed. [codeblock] @@ -106,75 +53,10 @@ [/codeblock] </description> </method> - <method name="atan"> - <return type="float"> - </return> - <argument index="0" name="s" type="float"> - </argument> - <description> - Returns the arc tangent of [code]s[/code] in radians. Use it to get the angle from an angle's tangent in trigonometry: [code]atan(tan(angle)) == angle[/code]. - The method cannot know in which quadrant the angle should fall. See [method atan2] if you have both [code]y[/code] and [code]x[/code]. - [codeblock] - a = atan(0.5) # a is 0.463648 - [/codeblock] - </description> - </method> - <method name="atan2"> - <return type="float"> - </return> - <argument index="0" name="y" type="float"> - </argument> - <argument index="1" name="x" type="float"> - </argument> - <description> - Returns the arc tangent of [code]y/x[/code] in radians. Use to get the angle of tangent [code]y/x[/code]. To compute the value, the method takes into account the sign of both arguments in order to determine the quadrant. - Important note: The Y coordinate comes first, by convention. - [codeblock] - a = atan2(0, -1) # a is 3.141593 - [/codeblock] - </description> - </method> - <method name="bytes2var"> - <return type="Variant"> - </return> - <argument index="0" name="bytes" type="PackedByteArray"> - </argument> - <argument index="1" name="allow_objects" type="bool" default="false"> - </argument> - <description> - Decodes a byte array back to a value. When [code]allow_objects[/code] is [code]true[/code] decoding objects is allowed. - [b]WARNING:[/b] Deserialized object can contain code which gets executed. Do not use this option if the serialized object comes from untrusted sources to avoid potential security threats (remote code execution). - </description> - </method> - <method name="cartesian2polar"> - <return type="Vector2"> - </return> - <argument index="0" name="x" type="float"> - </argument> - <argument index="1" name="y" type="float"> - </argument> - <description> - Converts a 2D point expressed in the cartesian coordinate system (X and Y axis) to the polar coordinate system (a distance from the origin and an angle). - </description> - </method> - <method name="ceil"> - <return type="float"> - </return> - <argument index="0" name="s" type="float"> - </argument> - <description> - Rounds [code]s[/code] upward (towards positive infinity), returning the smallest whole number that is not less than [code]s[/code]. - [codeblock] - a = ceil(1.45) # a is 2.0 - a = ceil(1.001) # a is 2.0 - [/codeblock] - See also [method floor], [method round], [method snapped], and [int]. - </description> - </method> <method name="char"> <return type="String"> </return> - <argument index="0" name="code" type="int"> + <argument index="0" name="char" type="int"> </argument> <description> Returns a character as a String of the given Unicode code point (which is compatible with ASCII code). @@ -183,25 +65,6 @@ a = char(65 + 32) # a is "a" a = char(8364) # a is "€" [/codeblock] - This is the inverse of [method ord]. - </description> - </method> - <method name="clamp"> - <return type="float"> - </return> - <argument index="0" name="value" type="float"> - </argument> - <argument index="1" name="min" type="float"> - </argument> - <argument index="2" name="max" type="float"> - </argument> - <description> - Clamps [code]value[/code] and returns a value not less than [code]min[/code] and not more than [code]max[/code]. - [codeblock] - a = clamp(1000, 1, 20) # a is 20 - a = clamp(-10, 1, 20) # a is 1 - a = clamp(15, 1, 20) # a is 15 - [/codeblock] </description> </method> <method name="convert"> @@ -223,159 +86,15 @@ [/codeblock] </description> </method> - <method name="cos"> - <return type="float"> - </return> - <argument index="0" name="s" type="float"> - </argument> - <description> - Returns the cosine of angle [code]s[/code] in radians. - [codeblock] - a = cos(TAU) # a is 1.0 - a = cos(PI) # a is -1.0 - [/codeblock] - </description> - </method> - <method name="cosh"> - <return type="float"> - </return> - <argument index="0" name="s" type="float"> - </argument> - <description> - Returns the hyperbolic cosine of [code]s[/code] in radians. - [codeblock] - print(cosh(1)) # Prints 1.543081 - [/codeblock] - </description> - </method> - <method name="db2linear"> - <return type="float"> - </return> - <argument index="0" name="db" type="float"> - </argument> - <description> - Converts from decibels to linear energy (audio). - </description> - </method> - <method name="dectime"> - <return type="float"> - </return> - <argument index="0" name="value" type="float"> - </argument> - <argument index="1" name="amount" type="float"> - </argument> - <argument index="2" name="step" type="float"> - </argument> - <description> - Returns the result of [code]value[/code] decreased by [code]step[/code] * [code]amount[/code]. - [codeblock] - a = dectime(60, 10, 0.1)) # a is 59.0 - [/codeblock] - </description> - </method> - <method name="deg2rad"> - <return type="float"> - </return> - <argument index="0" name="deg" type="float"> - </argument> - <description> - Converts an angle expressed in degrees to radians. - [codeblock] - r = deg2rad(180) # r is 3.141593 - [/codeblock] - </description> - </method> <method name="dict2inst"> <return type="Object"> </return> - <argument index="0" name="dict" type="Dictionary"> + <argument index="0" name="dictionary" type="Dictionary"> </argument> <description> Converts a dictionary (previously created with [method inst2dict]) back to an instance. Useful for deserializing. </description> </method> - <method name="ease"> - <return type="float"> - </return> - <argument index="0" name="s" type="float"> - </argument> - <argument index="1" name="curve" type="float"> - </argument> - <description> - Easing function, based on exponent. The curve values are: 0 is constant, 1 is linear, 0 to 1 is ease-in, 1+ is ease out. Negative values are in-out/out in. - </description> - </method> - <method name="exp"> - <return type="float"> - </return> - <argument index="0" name="s" type="float"> - </argument> - <description> - The natural exponential function. It raises the mathematical constant [b]e[/b] to the power of [code]s[/code] and returns it. - [b]e[/b] has an approximate value of 2.71828, and can be obtained with [code]exp(1)[/code]. - For exponents to other bases use the method [method pow]. - [codeblock] - a = exp(2) # Approximately 7.39 - [/codeblock] - </description> - </method> - <method name="floor"> - <return type="float"> - </return> - <argument index="0" name="s" type="float"> - </argument> - <description> - Rounds [code]s[/code] downward (towards negative infinity), returning the largest whole number that is not more than [code]s[/code]. - [codeblock] - a = floor(2.45) # a is 2.0 - a = floor(2.99) # a is 2.0 - a = floor(-2.99) # a is -3.0 - [/codeblock] - See also [method ceil], [method round], [method snapped], and [int]. - [b]Note:[/b] This method returns a float. If you need an integer and [code]s[/code] is a non-negative number, you can use [code]int(s)[/code] directly. - </description> - </method> - <method name="fmod"> - <return type="float"> - </return> - <argument index="0" name="a" type="float"> - </argument> - <argument index="1" name="b" type="float"> - </argument> - <description> - Returns the floating-point remainder of [code]a/b[/code], keeping the sign of [code]a[/code]. - [codeblock] - r = fmod(7, 5.5) # r is 1.5 - [/codeblock] - For the integer remainder operation, use the % operator. - </description> - </method> - <method name="fposmod"> - <return type="float"> - </return> - <argument index="0" name="a" type="float"> - </argument> - <argument index="1" name="b" type="float"> - </argument> - <description> - Returns the floating-point modulus of [code]a/b[/code] that wraps equally in positive and negative. - [codeblock] - for i in 7: - var x = 0.5 * i - 1.5 - print("%4.1f %4.1f %4.1f" % [x, fmod(x, 1.5), fposmod(x, 1.5)]) - [/codeblock] - Produces: - [codeblock] - -1.5 -0.0 0.0 - -1.0 -1.0 0.5 - -0.5 -0.5 1.0 - 0.0 0.0 0.0 - 0.5 0.5 0.5 - 1.0 1.0 1.0 - 1.5 0.0 0.0 - [/codeblock] - </description> - </method> <method name="get_stack"> <return type="Array"> </return> @@ -397,22 +116,10 @@ [/codeblock] </description> </method> - <method name="hash"> - <return type="int"> - </return> - <argument index="0" name="var" type="Variant"> - </argument> - <description> - Returns the integer hash of the variable passed. - [codeblock] - print(hash("a")) # Prints 177670 - [/codeblock] - </description> - </method> <method name="inst2dict"> <return type="Dictionary"> </return> - <argument index="0" name="inst" type="Object"> + <argument index="0" name="instance" type="Object"> </argument> <description> Returns the passed instance converted to a dictionary (useful for serializing). @@ -430,92 +137,6 @@ [/codeblock] </description> </method> - <method name="instance_from_id"> - <return type="Object"> - </return> - <argument index="0" name="instance_id" type="int"> - </argument> - <description> - Returns the Object that corresponds to [code]instance_id[/code]. All Objects have a unique instance ID. - [codeblock] - var foo = "bar" - func _ready(): - var id = get_instance_id() - var inst = instance_from_id(id) - print(inst.foo) # Prints bar - [/codeblock] - </description> - </method> - <method name="inverse_lerp"> - <return type="float"> - </return> - <argument index="0" name="from" type="float"> - </argument> - <argument index="1" name="to" type="float"> - </argument> - <argument index="2" name="weight" type="float"> - </argument> - <description> - Returns a normalized value considering the given range. This is the opposite of [method lerp]. - [codeblock] - var middle = lerp(20, 30, 0.75) - # `middle` is now 27.5. - # Now, we pretend to have forgotten the original ratio and want to get it back. - var ratio = inverse_lerp(20, 30, 27.5) - # `ratio` is now 0.75. - [/codeblock] - </description> - </method> - <method name="is_equal_approx"> - <return type="bool"> - </return> - <argument index="0" name="a" type="float"> - </argument> - <argument index="1" name="b" type="float"> - </argument> - <description> - Returns [code]true[/code] if [code]a[/code] and [code]b[/code] are approximately equal to each other. - Here, approximately equal means that [code]a[/code] and [code]b[/code] are within a small internal epsilon of each other, which scales with the magnitude of the numbers. - Infinity values of the same sign are considered equal. - </description> - </method> - <method name="is_inf"> - <return type="bool"> - </return> - <argument index="0" name="s" type="float"> - </argument> - <description> - Returns whether [code]s[/code] is an infinity value (either positive infinity or negative infinity). - </description> - </method> - <method name="is_instance_valid"> - <return type="bool"> - </return> - <argument index="0" name="instance" type="Object"> - </argument> - <description> - Returns whether [code]instance[/code] is a valid object (e.g. has not been deleted from memory). - </description> - </method> - <method name="is_nan"> - <return type="bool"> - </return> - <argument index="0" name="s" type="float"> - </argument> - <description> - Returns whether [code]s[/code] is a NaN ("Not a Number" or invalid) value. - </description> - </method> - <method name="is_zero_approx"> - <return type="bool"> - </return> - <argument index="0" name="s" type="float"> - </argument> - <description> - Returns [code]true[/code] if [code]s[/code] is zero or almost zero. - This method is faster than using [method is_equal_approx] with one value as zero. - </description> - </method> <method name="len"> <return type="int"> </return> @@ -530,63 +151,6 @@ [/codeblock] </description> </method> - <method name="lerp"> - <return type="Variant"> - </return> - <argument index="0" name="from" type="Variant"> - </argument> - <argument index="1" name="to" type="Variant"> - </argument> - <argument index="2" name="weight" type="float"> - </argument> - <description> - Linearly interpolates between two values by a normalized value. This is the opposite of [method inverse_lerp]. - If the [code]from[/code] and [code]to[/code] arguments are of type [int] or [float], the return value is a [float]. - If both are of the same vector type ([Vector2], [Vector3] or [Color]), the return value will be of the same type ([code]lerp[/code] then calls the vector type's [code]lerp[/code] method). - [codeblock] - lerp(0, 4, 0.75) # Returns 3.0 - lerp(Vector2(1, 5), Vector2(3, 2), 0.5) # Returns Vector2(2, 3.5) - [/codeblock] - </description> - </method> - <method name="lerp_angle"> - <return type="float"> - </return> - <argument index="0" name="from" type="float"> - </argument> - <argument index="1" name="to" type="float"> - </argument> - <argument index="2" name="weight" type="float"> - </argument> - <description> - Linearly interpolates between two angles (in radians) by a normalized value. - Similar to [method lerp], but interpolates correctly when the angles wrap around [constant @GDScript.TAU]. - [codeblock] - extends Sprite - var elapsed = 0.0 - func _process(delta): - var min_angle = deg2rad(0.0) - var max_angle = deg2rad(90.0) - rotation = lerp_angle(min_angle, max_angle, elapsed) - elapsed += delta - [/codeblock] - </description> - </method> - <method name="linear2db"> - <return type="float"> - </return> - <argument index="0" name="nrg" type="float"> - </argument> - <description> - Converts from linear energy to decibels (audio). This can be used to implement volume sliders that behave as expected (since volume isn't linear). Example: - [codeblock] - # "Slider" refers to a node that inherits Range such as HSlider or VSlider. - # Its range must be configured to go from 0 to 1. - # Change the bus name if you'd like to change the volume of a specific bus only. - AudioServer.set_bus_volume_db(AudioServer.get_bus_index("Master"), linear2db($Slider.value)) - [/codeblock] - </description> - </method> <method name="load"> <return type="Resource"> </return> @@ -603,172 +167,6 @@ This method is a simplified version of [method ResourceLoader.load], which can be used for more advanced scenarios. </description> </method> - <method name="log"> - <return type="float"> - </return> - <argument index="0" name="s" type="float"> - </argument> - <description> - Natural logarithm. The amount of time needed to reach a certain level of continuous growth. - [b]Note:[/b] This is not the same as the "log" function on most calculators, which uses a base 10 logarithm. - [codeblock] - log(10) # Returns 2.302585 - [/codeblock] - [b]Note:[/b] The logarithm of [code]0[/code] returns [code]-inf[/code], while negative values return [code]-nan[/code]. - </description> - </method> - <method name="max"> - <return type="float"> - </return> - <argument index="0" name="a" type="float"> - </argument> - <argument index="1" name="b" type="float"> - </argument> - <description> - Returns the maximum of two values. - [codeblock] - max(1, 2) # Returns 2 - max(-3.99, -4) # Returns -3.99 - [/codeblock] - </description> - </method> - <method name="min"> - <return type="float"> - </return> - <argument index="0" name="a" type="float"> - </argument> - <argument index="1" name="b" type="float"> - </argument> - <description> - Returns the minimum of two values. - [codeblock] - min(1, 2) # Returns 1 - min(-3.99, -4) # Returns -4 - [/codeblock] - </description> - </method> - <method name="move_toward"> - <return type="float"> - </return> - <argument index="0" name="from" type="float"> - </argument> - <argument index="1" name="to" type="float"> - </argument> - <argument index="2" name="delta" type="float"> - </argument> - <description> - Moves [code]from[/code] toward [code]to[/code] by the [code]delta[/code] value. - Use a negative [code]delta[/code] value to move away. - [codeblock] - move_toward(5, 10, 4) # Returns 9 - move_toward(10, 5, 4) # Returns 6 - move_toward(10, 5, -1.5) # Returns 11.5 - [/codeblock] - </description> - </method> - <method name="nearest_po2"> - <return type="int"> - </return> - <argument index="0" name="value" type="int"> - </argument> - <description> - Returns the nearest equal or larger power of 2 for integer [code]value[/code]. - In other words, returns the smallest value [code]a[/code] where [code]a = pow(2, n)[/code] such that [code]value <= a[/code] for some non-negative integer [code]n[/code]. - [codeblock] - nearest_po2(3) # Returns 4 - nearest_po2(4) # Returns 4 - nearest_po2(5) # Returns 8 - - nearest_po2(0) # Returns 0 (this may not be what you expect) - nearest_po2(-1) # Returns 0 (this may not be what you expect) - [/codeblock] - [b]WARNING:[/b] Due to the way it is implemented, this function returns [code]0[/code] rather than [code]1[/code] for non-positive values of [code]value[/code] (in reality, 1 is the smallest integer power of 2). - </description> - </method> - <method name="ord"> - <return type="int"> - </return> - <argument index="0" name="char" type="String"> - </argument> - <description> - Returns an integer representing the Unicode code point of the given Unicode character [code]char[/code]. - [codeblock] - a = ord("A") # a is 65 - a = ord("a") # a is 97 - a = ord("€") # a is 8364 - [/codeblock] - This is the inverse of [method char]. - </description> - </method> - <method name="parse_json"> - <return type="Variant"> - </return> - <argument index="0" name="json" type="String"> - </argument> - <description> - Parse JSON text to a Variant. (Use [method typeof] to check if the Variant's type is what you expect.) - [b]Note:[/b] The JSON specification does not define integer or float types, but only a [i]number[/i] type. Therefore, parsing a JSON text will convert all numerical values to [float] types. - [b]Note:[/b] JSON objects do not preserve key order like Godot dictionaries, thus, you should not rely on keys being in a certain order if a dictionary is constructed from JSON. In contrast, JSON arrays retain the order of their elements: - [codeblock] - var p = JSON.parse('["hello", "world", "!"]') - if typeof(p.result) == TYPE_ARRAY: - print(p.result[0]) # Prints "hello" - else: - push_error("Unexpected results.") - [/codeblock] - See also [JSON] for an alternative way to parse JSON text. - </description> - </method> - <method name="polar2cartesian"> - <return type="Vector2"> - </return> - <argument index="0" name="r" type="float"> - </argument> - <argument index="1" name="th" type="float"> - </argument> - <description> - Converts a 2D point expressed in the polar coordinate system (a distance from the origin [code]r[/code] and an angle [code]th[/code]) to the cartesian coordinate system (X and Y axis). - </description> - </method> - <method name="posmod"> - <return type="int"> - </return> - <argument index="0" name="a" type="int"> - </argument> - <argument index="1" name="b" type="int"> - </argument> - <description> - Returns the integer modulus of [code]a/b[/code] that wraps equally in positive and negative. - [codeblock] - for i in range(-3, 4): - print("%2d %2d %2d" % [i, i % 3, posmod(i, 3)]) - [/codeblock] - Produces: - [codeblock] - -3 0 0 - -2 -2 1 - -1 -1 2 - 0 0 0 - 1 1 1 - 2 2 2 - 3 0 0 - [/codeblock] - </description> - </method> - <method name="pow"> - <return type="float"> - </return> - <argument index="0" name="base" type="float"> - </argument> - <argument index="1" name="exp" type="float"> - </argument> - <description> - Returns the result of [code]base[/code] raised to the power of [code]exp[/code]. - [codeblock] - pow(2, 5) # Returns 32.0 - [/codeblock] - </description> - </method> <method name="preload"> <return type="Resource"> </return> @@ -783,23 +181,11 @@ [/codeblock] </description> </method> - <method name="print" qualifiers="vararg"> - <return type="void"> - </return> - <description> - Converts one or more arguments to strings in the best way possible and prints them to the console. - [codeblock] - a = [1, 2, 3] - print("a", "=", a) # Prints a=[1, 2, 3] - [/codeblock] - [b]Note:[/b] Consider using [method push_error] and [method push_warning] to print error and warning messages instead of [method print]. This distinguishes them from print messages used for debugging purposes, while also displaying a stack trace when an error or warning is printed. - </description> - </method> <method name="print_debug" qualifiers="vararg"> <return type="void"> </return> <description> - Like [method print], but prints only when used in debug mode. + Like [method @GlobalScope.print], but prints only when used in debug mode. </description> </method> <method name="print_stack"> @@ -813,158 +199,6 @@ [/codeblock] </description> </method> - <method name="printerr" qualifiers="vararg"> - <return type="void"> - </return> - <description> - Prints one or more arguments to strings in the best way possible to standard error line. - [codeblock] - printerr("prints to stderr") - [/codeblock] - </description> - </method> - <method name="printraw" qualifiers="vararg"> - <return type="void"> - </return> - <description> - Prints one or more arguments to strings in the best way possible to console. No newline is added at the end. - [codeblock] - printraw("A") - printraw("B") - # Prints AB - [/codeblock] - [b]Note:[/b] Due to limitations with Godot's built-in console, this only prints to the terminal. If you need to print in the editor, use another method, such as [method print]. - </description> - </method> - <method name="prints" qualifiers="vararg"> - <return type="void"> - </return> - <description> - Prints one or more arguments to the console with a space between each argument. - [codeblock] - prints("A", "B", "C") # Prints A B C - [/codeblock] - </description> - </method> - <method name="printt" qualifiers="vararg"> - <return type="void"> - </return> - <description> - Prints one or more arguments to the console with a tab between each argument. - [codeblock] - printt("A", "B", "C") # Prints A B C - [/codeblock] - </description> - </method> - <method name="push_error"> - <return type="void"> - </return> - <argument index="0" name="message" type="String"> - </argument> - <description> - Pushes an error message to Godot's built-in debugger and to the OS terminal. - [codeblock] - push_error("test error") # Prints "test error" to debugger and terminal as error call - [/codeblock] - [b]Note:[/b] Errors printed this way will not pause project execution. To print an error message and pause project execution in debug builds, use [code]assert(false, "test error")[/code] instead. - </description> - </method> - <method name="push_warning"> - <return type="void"> - </return> - <argument index="0" name="message" type="String"> - </argument> - <description> - Pushes a warning message to Godot's built-in debugger and to the OS terminal. - [codeblock] - push_warning("test warning") # Prints "test warning" to debugger and terminal as warning call - [/codeblock] - </description> - </method> - <method name="rad2deg"> - <return type="float"> - </return> - <argument index="0" name="rad" type="float"> - </argument> - <description> - Converts an angle expressed in radians to degrees. - [codeblock] - rad2deg(0.523599) # Returns 30.0 - [/codeblock] - </description> - </method> - <method name="rand_seed"> - <return type="Array"> - </return> - <argument index="0" name="seed" type="int"> - </argument> - <description> - Random from seed: pass a [code]seed[/code], and an array with both number and new seed is returned. "Seed" here refers to the internal state of the pseudo random number generator. The internal state of the current implementation is 64 bits. - </description> - </method> - <method name="randf"> - <return type="float"> - </return> - <description> - Returns a random floating point value on the interval [code][0, 1][/code]. - [codeblock] - randf() # Returns e.g. 0.375671 - [/codeblock] - </description> - </method> - <method name="randf_range"> - <return type="float"> - </return> - <argument index="0" name="from" type="float"> - </argument> - <argument index="1" name="to" type="float"> - </argument> - <description> - Random range, any floating point value between [code]from[/code] and [code]to[/code]. - [codeblock] - prints(randf_range(-10, 10), randf_range(-10, 10)) # Prints e.g. -3.844535 7.45315 - [/codeblock] - </description> - </method> - <method name="randi"> - <return type="int"> - </return> - <description> - Returns a random unsigned 32 bit integer. Use remainder to obtain a random value in the interval [code][0, N - 1][/code] (where N is smaller than 2^32). - [codeblock] - randi() # Returns random integer between 0 and 2^32 - 1 - randi() % 20 # Returns random integer between 0 and 19 - randi() % 100 # Returns random integer between 0 and 99 - randi() % 100 + 1 # Returns random integer between 1 and 100 - [/codeblock] - </description> - </method> - <method name="randi_range"> - <return type="int"> - </return> - <argument index="0" name="from" type="int"> - </argument> - <argument index="1" name="to" type="int"> - </argument> - <description> - Random range, any 32-bit integer value between [code]from[/code] and [code]to[/code] (inclusive). If [code]to[/code] is lesser than [code]from[/code] they are swapped. - [codeblock] - print(randi_range(0, 1)) # Prints 0 or 1 - print(randi_range(-10, 1000)) # Prints any number from -10 to 1000 - [/codeblock] - </description> - </method> - <method name="randomize"> - <return type="void"> - </return> - <description> - Randomizes the seed (or the internal state) of the random number generator. Current implementation reseeds using a number based on time. - [codeblock] - func _ready(): - randomize() - [/codeblock] - </description> - </method> <method name="range" qualifiers="vararg"> <return type="Array"> </return> @@ -983,157 +217,6 @@ [/codeblock] </description> </method> - <method name="range_lerp"> - <return type="float"> - </return> - <argument index="0" name="value" type="float"> - </argument> - <argument index="1" name="istart" type="float"> - </argument> - <argument index="2" name="istop" type="float"> - </argument> - <argument index="3" name="ostart" type="float"> - </argument> - <argument index="4" name="ostop" type="float"> - </argument> - <description> - Maps a [code]value[/code] from range [code][istart, istop][/code] to [code][ostart, ostop][/code]. - [codeblock] - range_lerp(75, 0, 100, -1, 1) # Returns 0.5 - [/codeblock] - </description> - </method> - <method name="round"> - <return type="float"> - </return> - <argument index="0" name="s" type="float"> - </argument> - <description> - Rounds [code]s[/code] to the nearest whole number, with halfway cases rounded away from zero. - [codeblock] - a = round(2.49) # a is 2.0 - a = round(2.5) # a is 3.0 - a = round(2.51) # a is 3.0 - [/codeblock] - See also [method floor], [method ceil], [method snapped], and [int]. - </description> - </method> - <method name="seed"> - <return type="void"> - </return> - <argument index="0" name="seed" type="int"> - </argument> - <description> - Sets seed for the random number generator. - [codeblock] - my_seed = "Godot Rocks" - seed(my_seed.hash()) - [/codeblock] - </description> - </method> - <method name="sign"> - <return type="float"> - </return> - <argument index="0" name="s" type="float"> - </argument> - <description> - Returns the sign of [code]s[/code]: -1 or 1. Returns 0 if [code]s[/code] is 0. - [codeblock] - sign(-6) # Returns -1 - sign(0) # Returns 0 - sign(6) # Returns 1 - [/codeblock] - </description> - </method> - <method name="sin"> - <return type="float"> - </return> - <argument index="0" name="s" type="float"> - </argument> - <description> - Returns the sine of angle [code]s[/code] in radians. - [codeblock] - sin(0.523599) # Returns 0.5 - [/codeblock] - </description> - </method> - <method name="sinh"> - <return type="float"> - </return> - <argument index="0" name="s" type="float"> - </argument> - <description> - Returns the hyperbolic sine of [code]s[/code]. - [codeblock] - a = log(2.0) # Returns 0.693147 - sinh(a) # Returns 0.75 - [/codeblock] - </description> - </method> - <method name="smoothstep"> - <return type="float"> - </return> - <argument index="0" name="from" type="float"> - </argument> - <argument index="1" name="to" type="float"> - </argument> - <argument index="2" name="s" type="float"> - </argument> - <description> - Returns the result of smoothly interpolating the value of [code]s[/code] between [code]0[/code] and [code]1[/code], based on the where [code]s[/code] lies with respect to the edges [code]from[/code] and [code]to[/code]. - The return value is [code]0[/code] if [code]s <= from[/code], and [code]1[/code] if [code]s >= to[/code]. If [code]s[/code] lies between [code]from[/code] and [code]to[/code], the returned value follows an S-shaped curve that maps [code]s[/code] between [code]0[/code] and [code]1[/code]. - This S-shaped curve is the cubic Hermite interpolator, given by [code]f(s) = 3*s^2 - 2*s^3[/code]. - [codeblock] - smoothstep(0, 2, -5.0) # Returns 0.0 - smoothstep(0, 2, 0.5) # Returns 0.15625 - smoothstep(0, 2, 1.0) # Returns 0.5 - smoothstep(0, 2, 2.0) # Returns 1.0 - [/codeblock] - </description> - </method> - <method name="sqrt"> - <return type="float"> - </return> - <argument index="0" name="s" type="float"> - </argument> - <description> - Returns the square root of [code]s[/code], where [code]s[/code] is a non-negative number. - [codeblock] - sqrt(9) # Returns 3 - [/codeblock] - [b]Note:[/b]Negative values of [code]s[/code] return NaN. If you need negative inputs, use [code]System.Numerics.Complex[/code] in C#. - </description> - </method> - <method name="step_decimals"> - <return type="int"> - </return> - <argument index="0" name="step" type="float"> - </argument> - <description> - Returns the position of the first non-zero digit, after the decimal point. Note that the maximum return value is 10, which is a design decision in the implementation. - [codeblock] - n = step_decimals(5) # n is 0 - n = step_decimals(1.0005) # n is 4 - n = step_decimals(0.000000005) # n is 9 - [/codeblock] - </description> - </method> - <method name="snapped"> - <return type="float"> - </return> - <argument index="0" name="s" type="float"> - </argument> - <argument index="1" name="step" type="float"> - </argument> - <description> - Snaps float value [code]s[/code] to a given [code]step[/code]. This can also be used to round a floating point number to an arbitrary number of decimals. - [codeblock] - snapped(100, 32) # Returns 96.0 - snapped(3.14159, 0.01) # Returns 3.14 - [/codeblock] - See also [method ceil], [method floor], [method round], and [int]. - </description> - </method> <method name="str" qualifiers="vararg"> <return type="String"> </return> @@ -1147,200 +230,12 @@ [/codeblock] </description> </method> - <method name="str2var"> - <return type="Variant"> - </return> - <argument index="0" name="string" type="String"> - </argument> - <description> - Converts a formatted string that was returned by [method var2str] to the original value. - [codeblock] - a = '{ "a": 1, "b": 2 }' - b = str2var(a) - print(b["a"]) # Prints 1 - [/codeblock] - </description> - </method> - <method name="tan"> - <return type="float"> - </return> - <argument index="0" name="s" type="float"> - </argument> - <description> - Returns the tangent of angle [code]s[/code] in radians. - [codeblock] - tan(deg2rad(45)) # Returns 1 - [/codeblock] - </description> - </method> - <method name="tanh"> - <return type="float"> - </return> - <argument index="0" name="s" type="float"> - </argument> - <description> - Returns the hyperbolic tangent of [code]s[/code]. - [codeblock] - a = log(2.0) # a is 0.693147 - b = tanh(a) # b is 0.6 - [/codeblock] - </description> - </method> - <method name="to_json"> - <return type="String"> - </return> - <argument index="0" name="var" type="Variant"> - </argument> - <description> - Converts a [Variant] [code]var[/code] to JSON text and return the result. Useful for serializing data to store or send over the network. - [codeblock] - # Both numbers below are integers. - a = { "a": 1, "b": 2 } - b = to_json(a) - print(b) # {"a":1, "b":2} - # Both numbers above are floats, even if they display without any decimal places. - [/codeblock] - [b]Note:[/b] The JSON specification does not define integer or float types, but only a [i]number[/i] type. Therefore, converting a [Variant] to JSON text will convert all numerical values to [float] types. - See also [JSON] for an alternative way to convert a [Variant] to JSON text. - </description> - </method> <method name="type_exists"> <return type="bool"> </return> - <argument index="0" name="type" type="String"> - </argument> - <description> - Returns whether the given class exists in [ClassDB]. - [codeblock] - type_exists("Sprite2D") # Returns true - type_exists("Variant") # Returns false - [/codeblock] - </description> - </method> - <method name="typeof"> - <return type="int"> - </return> - <argument index="0" name="what" type="Variant"> - </argument> - <description> - Returns the internal type of the given Variant object, using the [enum Variant.Type] values. - [codeblock] - p = parse_json('["a", "b", "c"]') - if typeof(p) == TYPE_ARRAY: - print(p[0]) # Prints a - else: - print("unexpected results") - [/codeblock] - </description> - </method> - <method name="validate_json"> - <return type="String"> - </return> - <argument index="0" name="json" type="String"> - </argument> - <description> - Checks that [code]json[/code] is valid JSON data. Returns an empty string if valid, or an error message otherwise. - [codeblock] - j = to_json([1, 2, 3]) - v = validate_json(j) - if not v: - print("Valid JSON.") - else: - push_error("Invalid JSON: " + v) - [/codeblock] - </description> - </method> - <method name="var2bytes"> - <return type="PackedByteArray"> - </return> - <argument index="0" name="var" type="Variant"> - </argument> - <argument index="1" name="full_objects" type="bool" default="false"> - </argument> - <description> - Encodes a variable value to a byte array. When [code]full_objects[/code] is [code]true[/code] encoding objects is allowed (and can potentially include code). - </description> - </method> - <method name="var2str"> - <return type="String"> - </return> - <argument index="0" name="var" type="Variant"> - </argument> - <description> - Converts a Variant [code]var[/code] to a formatted string that can later be parsed using [method str2var]. - [codeblock] - a = { "a": 1, "b": 2 } - print(var2str(a)) - [/codeblock] - prints - [codeblock] - { - "a": 1, - "b": 2 - } - [/codeblock] - </description> - </method> - <method name="weakref"> - <return type="WeakRef"> - </return> - <argument index="0" name="obj" type="Object"> - </argument> - <description> - Returns a weak reference to an object. - A weak reference to an object is not enough to keep the object alive: when the only remaining references to a referent are weak references, garbage collection is free to destroy the referent and reuse its memory for something else. However, until the object is actually destroyed the weak reference may return the object even if there are no strong references to it. - </description> - </method> - <method name="wrapf"> - <return type="float"> - </return> - <argument index="0" name="value" type="float"> - </argument> - <argument index="1" name="min" type="float"> - </argument> - <argument index="2" name="max" type="float"> + <argument index="0" name="type" type="StringName"> </argument> <description> - Wraps float [code]value[/code] between [code]min[/code] and [code]max[/code]. - Usable for creating loop-alike behavior or infinite surfaces. - [codeblock] - # Infinite loop between 5.0 and 9.9 - value = wrapf(value + 0.1, 5.0, 10.0) - [/codeblock] - [codeblock] - # Infinite rotation (in radians) - angle = wrapf(angle + 0.1, 0.0, TAU) - [/codeblock] - [codeblock] - # Infinite rotation (in radians) - angle = wrapf(angle + 0.1, -PI, PI) - [/codeblock] - [b]Note:[/b] If [code]min[/code] is [code]0[/code], this is equivalent to [method fposmod], so prefer using that instead. - [code]wrapf[/code] is more flexible than using the [method fposmod] approach by giving the user control over the minimum value. - </description> - </method> - <method name="wrapi"> - <return type="int"> - </return> - <argument index="0" name="value" type="int"> - </argument> - <argument index="1" name="min" type="int"> - </argument> - <argument index="2" name="max" type="int"> - </argument> - <description> - Wraps integer [code]value[/code] between [code]min[/code] and [code]max[/code]. - Usable for creating loop-alike behavior or infinite surfaces. - [codeblock] - # Infinite loop between 5 and 9 - frame = wrapi(frame + 1, 5, 10) - [/codeblock] - [codeblock] - # result is -2 - var result = wrapi(-6, -5, -1) - [/codeblock] - [b]Note:[/b] If [code]min[/code] is [code]0[/code], this is equivalent to [method posmod], so prefer using that instead. - [code]wrapi[/code] is more flexible than using the [method posmod] approach by giving the user control over the minimum value. </description> </method> </methods> diff --git a/modules/visual_script/doc_classes/VisualScript.xml b/modules/visual_script/doc_classes/VisualScript.xml index 088d84d2ec..5112ea43a7 100644 --- a/modules/visual_script/doc_classes/VisualScript.xml +++ b/modules/visual_script/doc_classes/VisualScript.xml @@ -26,23 +26,23 @@ </return> <argument index="0" name="name" type="StringName"> </argument> + <argument index="1" name="func_node_id" type="int"> + </argument> <description> - Add a function with the specified name to the VisualScript. + Add a function with the specified name to the VisualScript, and assign the root [VisualScriptFunction] node's id as [code]func_node_id[/code]. </description> </method> <method name="add_node"> <return type="void"> </return> - <argument index="0" name="func" type="StringName"> - </argument> - <argument index="1" name="id" type="int"> + <argument index="0" name="id" type="int"> </argument> - <argument index="2" name="node" type="VisualScriptNode"> + <argument index="1" name="node" type="VisualScriptNode"> </argument> - <argument index="3" name="position" type="Vector2" default="Vector2( 0, 0 )"> + <argument index="2" name="position" type="Vector2" default="Vector2( 0, 0 )"> </argument> <description> - Add a node to a function of the VisualScript. + Add a node to the VisualScript. </description> </method> <method name="add_variable"> @@ -157,15 +157,13 @@ <method name="data_connect"> <return type="void"> </return> - <argument index="0" name="func" type="StringName"> - </argument> - <argument index="1" name="from_node" type="int"> + <argument index="0" name="from_node" type="int"> </argument> - <argument index="2" name="from_port" type="int"> + <argument index="1" name="from_port" type="int"> </argument> - <argument index="3" name="to_node" type="int"> + <argument index="2" name="to_node" type="int"> </argument> - <argument index="4" name="to_port" type="int"> + <argument index="3" name="to_port" type="int"> </argument> <description> Connect two data ports. The value of [code]from_node[/code]'s [code]from_port[/code] would be fed into [code]to_node[/code]'s [code]to_port[/code]. @@ -174,15 +172,13 @@ <method name="data_disconnect"> <return type="void"> </return> - <argument index="0" name="func" type="StringName"> + <argument index="0" name="from_node" type="int"> </argument> - <argument index="1" name="from_node" type="int"> + <argument index="1" name="from_port" type="int"> </argument> - <argument index="2" name="from_port" type="int"> + <argument index="2" name="to_node" type="int"> </argument> - <argument index="3" name="to_node" type="int"> - </argument> - <argument index="4" name="to_port" type="int"> + <argument index="3" name="to_port" type="int"> </argument> <description> Disconnect two data ports previously connected with [method data_connect]. @@ -197,37 +193,31 @@ Returns the id of a function's entry point node. </description> </method> - <method name="get_function_scroll" qualifiers="const"> - <return type="Vector2"> - </return> - <argument index="0" name="name" type="StringName"> - </argument> - <description> - Returns the position of the center of the screen for a given function. - </description> - </method> <method name="get_node" qualifiers="const"> <return type="VisualScriptNode"> </return> - <argument index="0" name="func" type="StringName"> - </argument> - <argument index="1" name="id" type="int"> + <argument index="0" name="id" type="int"> </argument> <description> - Returns a node given its id and its function. + Returns a node given its id. </description> </method> <method name="get_node_position" qualifiers="const"> <return type="Vector2"> </return> - <argument index="0" name="func" type="StringName"> - </argument> - <argument index="1" name="id" type="int"> + <argument index="0" name="id" type="int"> </argument> <description> Returns a node's position in pixels. </description> </method> + <method name="get_scroll" qualifiers="const"> + <return type="Vector2"> + </return> + <description> + Returns the current position of the center of the screen. + </description> + </method> <method name="get_variable_default_value" qualifiers="const"> <return type="Variant"> </return> @@ -267,15 +257,13 @@ <method name="has_data_connection" qualifiers="const"> <return type="bool"> </return> - <argument index="0" name="func" type="StringName"> - </argument> - <argument index="1" name="from_node" type="int"> + <argument index="0" name="from_node" type="int"> </argument> - <argument index="2" name="from_port" type="int"> + <argument index="1" name="from_port" type="int"> </argument> - <argument index="3" name="to_node" type="int"> + <argument index="2" name="to_node" type="int"> </argument> - <argument index="4" name="to_port" type="int"> + <argument index="3" name="to_port" type="int"> </argument> <description> Returns whether the specified data ports are connected. @@ -293,9 +281,7 @@ <method name="has_node" qualifiers="const"> <return type="bool"> </return> - <argument index="0" name="func" type="StringName"> - </argument> - <argument index="1" name="id" type="int"> + <argument index="0" name="id" type="int"> </argument> <description> Returns whether a node exists with the given id. @@ -304,13 +290,11 @@ <method name="has_sequence_connection" qualifiers="const"> <return type="bool"> </return> - <argument index="0" name="func" type="StringName"> - </argument> - <argument index="1" name="from_node" type="int"> + <argument index="0" name="from_node" type="int"> </argument> - <argument index="2" name="from_output" type="int"> + <argument index="1" name="from_output" type="int"> </argument> - <argument index="3" name="to_node" type="int"> + <argument index="2" name="to_node" type="int"> </argument> <description> Returns whether the specified sequence ports are connected. @@ -346,12 +330,10 @@ <method name="remove_node"> <return type="void"> </return> - <argument index="0" name="func" type="StringName"> - </argument> - <argument index="1" name="id" type="int"> + <argument index="0" name="id" type="int"> </argument> <description> - Remove a specific node. + Remove the node with the specified id. </description> </method> <method name="remove_variable"> @@ -399,13 +381,11 @@ <method name="sequence_connect"> <return type="void"> </return> - <argument index="0" name="func" type="StringName"> + <argument index="0" name="from_node" type="int"> </argument> - <argument index="1" name="from_node" type="int"> + <argument index="1" name="from_output" type="int"> </argument> - <argument index="2" name="from_output" type="int"> - </argument> - <argument index="3" name="to_node" type="int"> + <argument index="2" name="to_node" type="int"> </argument> <description> Connect two sequence ports. The execution will flow from of [code]from_node[/code]'s [code]from_output[/code] into [code]to_node[/code]. @@ -415,29 +395,16 @@ <method name="sequence_disconnect"> <return type="void"> </return> - <argument index="0" name="func" type="StringName"> - </argument> - <argument index="1" name="from_node" type="int"> + <argument index="0" name="from_node" type="int"> </argument> - <argument index="2" name="from_output" type="int"> + <argument index="1" name="from_output" type="int"> </argument> - <argument index="3" name="to_node" type="int"> + <argument index="2" name="to_node" type="int"> </argument> <description> Disconnect two sequence ports previously connected with [method sequence_connect]. </description> </method> - <method name="set_function_scroll"> - <return type="void"> - </return> - <argument index="0" name="name" type="StringName"> - </argument> - <argument index="1" name="ofs" type="Vector2"> - </argument> - <description> - Position the center of the screen for a function. - </description> - </method> <method name="set_instance_base_type"> <return type="void"> </return> @@ -450,14 +417,21 @@ <method name="set_node_position"> <return type="void"> </return> - <argument index="0" name="func" type="StringName"> + <argument index="0" name="id" type="int"> </argument> - <argument index="1" name="id" type="int"> + <argument index="1" name="position" type="Vector2"> </argument> - <argument index="2" name="position" type="Vector2"> + <description> + Set the node position in the VisualScript graph. + </description> + </method> + <method name="set_scroll"> + <return type="void"> + </return> + <argument index="0" name="ofs" type="Vector2"> </argument> <description> - Position a node on the screen. + Set the screen center to the given position. </description> </method> <method name="set_variable_default_value"> @@ -496,9 +470,7 @@ </methods> <signals> <signal name="node_ports_changed"> - <argument index="0" name="function" type="String"> - </argument> - <argument index="1" name="id" type="int"> + <argument index="0" name="id" type="int"> </argument> <description> Emitted when the ports of a node are changed. diff --git a/modules/visual_script/doc_classes/VisualScriptBuiltinFunc.xml b/modules/visual_script/doc_classes/VisualScriptBuiltinFunc.xml index 000fbd0140..4004f1a04c 100644 --- a/modules/visual_script/doc_classes/VisualScriptBuiltinFunc.xml +++ b/modules/visual_script/doc_classes/VisualScriptBuiltinFunc.xml @@ -92,7 +92,7 @@ <constant name="MATH_STEP_DECIMALS" value="24" enum="BuiltinFunc"> Return the number of digit places after the decimal that the first non-zero digit occurs. </constant> - <constant name="MATH_STEPIFY" value="25" enum="BuiltinFunc"> + <constant name="MATH_SNAPPED" value="25" enum="BuiltinFunc"> Return the input snapped to a given step. </constant> <constant name="MATH_LERP" value="26" enum="BuiltinFunc"> diff --git a/modules/visual_script/visual_script.cpp b/modules/visual_script/visual_script.cpp index 1ea2a80788..fe92f59179 100644 --- a/modules/visual_script/visual_script.cpp +++ b/modules/visual_script/visual_script.cpp @@ -36,7 +36,7 @@ #include "scene/main/node.h" #include "visual_script_nodes.h" -//used by editor, this is not really saved +// Used by editor, this is not really saved. void VisualScriptNode::set_breakpoint(bool p_breakpoint) { breakpoint = p_breakpoint; } @@ -55,8 +55,8 @@ void VisualScriptNode::set_default_input_value(int p_port, const Variant &p_valu default_input_values[p_port] = p_value; #ifdef TOOLS_ENABLED - for (Set<VisualScript *>::Element *E = scripts_used.front(); E; E = E->next()) { - E->get()->set_edited(true); + if (script_used.is_valid()) { + script_used->set_edited(true); } #endif } @@ -73,14 +73,14 @@ void VisualScriptNode::_set_default_input_values(Array p_values) { void VisualScriptNode::validate_input_default_values() { default_input_values.resize(MAX(default_input_values.size(), get_input_value_port_count())); //let it grow as big as possible, we don't want to lose values on resize - //actually validate on save + // Actually validate on save. for (int i = 0; i < get_input_value_port_count(); i++) { Variant::Type expected = get_input_value_port_info(i).type; if (expected == Variant::NIL || expected == default_input_values[i].get_type()) { continue; } else { - //not the same, reconvert + // Not the same, reconvert. Callable::CallError ce; Variant existing = default_input_values[i]; const Variant *existingp = &existing; @@ -94,7 +94,7 @@ void VisualScriptNode::validate_input_default_values() { } Array VisualScriptNode::_get_default_input_values() const { - //validate on save, since on load there is little info about this + // Validate on save, since on load there is little info about this. Array values = default_input_values; values.resize(get_input_value_port_count()); @@ -118,6 +118,8 @@ void VisualScriptNode::_bind_methods() { } VisualScriptNode::TypeGuess VisualScriptNode::guess_output_type(TypeGuess *p_inputs, int p_output) const { + ERR_FAIL_COND_V(get_output_value_port_count() <= p_output, TypeGuess()); + PropertyInfo pinfo = get_output_value_port_info(p_output); TypeGuess tg; @@ -131,11 +133,7 @@ VisualScriptNode::TypeGuess VisualScriptNode::guess_output_type(TypeGuess *p_inp } Ref<VisualScript> VisualScriptNode::get_visual_script() const { - if (scripts_used.size()) { - return Ref<VisualScript>(scripts_used.front()->get()); - } - - return Ref<VisualScript>(); + return script_used; } VisualScriptNode::VisualScriptNode() { @@ -165,13 +163,15 @@ VisualScriptNodeInstance::~VisualScriptNodeInstance() { } } -void VisualScript::add_function(const StringName &p_name) { +void VisualScript::add_function(const StringName &p_name, int p_func_node_id) { ERR_FAIL_COND(instances.size()); ERR_FAIL_COND(!String(p_name).is_valid_identifier()); ERR_FAIL_COND(functions.has(p_name)); + ERR_FAIL_COND(variables.has(p_name)); + ERR_FAIL_COND(custom_signals.has(p_name)); functions[p_name] = Function(); - functions[p_name].scroll = Vector2(-50, -100); + functions[p_name].func_id = p_func_node_id; } bool VisualScript::has_function(const StringName &p_name) const { @@ -182,11 +182,7 @@ void VisualScript::remove_function(const StringName &p_name) { ERR_FAIL_COND(instances.size()); ERR_FAIL_COND(!functions.has(p_name)); - for (Map<int, Function::NodeData>::Element *E = functions[p_name].nodes.front(); E; E = E->next()) { - E->get().node->disconnect("ports_changed", callable_mp(this, &VisualScript::_node_ports_changed)); - E->get().node->scripts_used.erase(this); - } - + // Let the editor handle the node removal. functions.erase(p_name); } @@ -207,53 +203,36 @@ void VisualScript::rename_function(const StringName &p_name, const StringName &p functions.erase(p_name); } -void VisualScript::set_function_scroll(const StringName &p_name, const Vector2 &p_scroll) { - ERR_FAIL_COND(!functions.has(p_name)); - functions[p_name].scroll = p_scroll; +void VisualScript::set_scroll(const Vector2 &p_scroll) { + scroll = p_scroll; } -Vector2 VisualScript::get_function_scroll(const StringName &p_name) const { - ERR_FAIL_COND_V(!functions.has(p_name), Vector2()); - return functions[p_name].scroll; +Vector2 VisualScript::get_scroll() const { + return scroll; } void VisualScript::get_function_list(List<StringName> *r_functions) const { - for (const Map<StringName, Function>::Element *E = functions.front(); E; E = E->next()) { - r_functions->push_back(E->key()); - } - - r_functions->sort_custom<StringName::AlphCompare>(); + functions.get_key_list(r_functions); + // r_functions->sort_custom<StringName::AlphCompare>(); // Don't force sorting. } int VisualScript::get_function_node_id(const StringName &p_name) const { ERR_FAIL_COND_V(!functions.has(p_name), -1); - return functions[p_name].function_id; + return functions[p_name].func_id; } void VisualScript::_node_ports_changed(int p_id) { - StringName function; - - for (Map<StringName, Function>::Element *E = functions.front(); E; E = E->next()) { - if (E->get().nodes.has(p_id)) { - function = E->key(); - break; - } - } - - ERR_FAIL_COND(function == StringName()); - - Function &func = functions[function]; - Ref<VisualScriptNode> vsn = func.nodes[p_id].node; + Ref<VisualScriptNode> vsn = nodes[p_id].node; vsn->validate_input_default_values(); - //must revalidate all the functions + // Must revalidate all the functions. { List<SequenceConnection> to_remove; - for (Set<SequenceConnection>::Element *E = func.sequence_connections.front(); E; E = E->next()) { + for (Set<SequenceConnection>::Element *E = sequence_connections.front(); E; E = E->next()) { if (E->get().from_node == p_id && E->get().from_output >= vsn->get_output_sequence_port_count()) { to_remove.push_back(E->get()); } @@ -263,7 +242,7 @@ void VisualScript::_node_ports_changed(int p_id) { } while (to_remove.size()) { - func.sequence_connections.erase(to_remove.front()->get()); + sequence_connections.erase(to_remove.front()->get()); to_remove.pop_front(); } } @@ -271,7 +250,7 @@ void VisualScript::_node_ports_changed(int p_id) { { List<DataConnection> to_remove; - for (Set<DataConnection>::Element *E = func.data_connections.front(); E; E = E->next()) { + for (Set<DataConnection>::Element *E = data_connections.front(); E; E = E->next()) { if (E->get().from_node == p_id && E->get().from_port >= vsn->get_output_value_port_count()) { to_remove.push_back(E->get()); } @@ -281,63 +260,47 @@ void VisualScript::_node_ports_changed(int p_id) { } while (to_remove.size()) { - func.data_connections.erase(to_remove.front()->get()); + data_connections.erase(to_remove.front()->get()); to_remove.pop_front(); } } #ifdef TOOLS_ENABLED - set_edited(true); //something changed, let's set as edited - emit_signal("node_ports_changed", function, p_id); + set_edited(true); // Something changed, let's set as edited. + emit_signal("node_ports_changed", p_id); #endif } -void VisualScript::add_node(const StringName &p_func, int p_id, const Ref<VisualScriptNode> &p_node, const Point2 &p_pos) { +void VisualScript::add_node(int p_id, const Ref<VisualScriptNode> &p_node, const Point2 &p_pos) { ERR_FAIL_COND(instances.size()); - ERR_FAIL_COND(!functions.has(p_func)); - - for (Map<StringName, Function>::Element *E = functions.front(); E; E = E->next()) { - ERR_FAIL_COND(E->get().nodes.has(p_id)); //id can exist only one in script, even for different functions - } + ERR_FAIL_COND(nodes.has(p_id)); // ID can exist only one in script. - Function &func = functions[p_func]; - - if (Object::cast_to<VisualScriptFunction>(*p_node)) { - //the function indeed - ERR_FAIL_COND_MSG(func.function_id >= 0, "A function node has already been set here."); - - func.function_id = p_id; - } - - Function::NodeData nd; + NodeData nd; nd.node = p_node; nd.pos = p_pos; Ref<VisualScriptNode> vsn = p_node; vsn->connect("ports_changed", callable_mp(this, &VisualScript::_node_ports_changed), varray(p_id)); - vsn->scripts_used.insert(this); - vsn->validate_input_default_values(); // Validate when fully loaded + vsn->script_used = Ref<VisualScript>(this); + vsn->validate_input_default_values(); // Validate when fully loaded. - func.nodes[p_id] = nd; + nodes[p_id] = nd; } -void VisualScript::remove_node(const StringName &p_func, int p_id) { +void VisualScript::remove_node(int p_id) { ERR_FAIL_COND(instances.size()); - ERR_FAIL_COND(!functions.has(p_func)); - Function &func = functions[p_func]; - - ERR_FAIL_COND(!func.nodes.has(p_id)); + ERR_FAIL_COND(!nodes.has(p_id)); { List<SequenceConnection> to_remove; - for (Set<SequenceConnection>::Element *E = func.sequence_connections.front(); E; E = E->next()) { + for (Set<SequenceConnection>::Element *E = sequence_connections.front(); E; E = E->next()) { if (E->get().from_node == p_id || E->get().to_node == p_id) { to_remove.push_back(E->get()); } } while (to_remove.size()) { - func.sequence_connections.erase(to_remove.front()->get()); + sequence_connections.erase(to_remove.front()->get()); to_remove.pop_front(); } } @@ -345,122 +308,88 @@ void VisualScript::remove_node(const StringName &p_func, int p_id) { { List<DataConnection> to_remove; - for (Set<DataConnection>::Element *E = func.data_connections.front(); E; E = E->next()) { + for (Set<DataConnection>::Element *E = data_connections.front(); E; E = E->next()) { if (E->get().from_node == p_id || E->get().to_node == p_id) { to_remove.push_back(E->get()); } } while (to_remove.size()) { - func.data_connections.erase(to_remove.front()->get()); + data_connections.erase(to_remove.front()->get()); to_remove.pop_front(); } } - if (Object::cast_to<VisualScriptFunction>(func.nodes[p_id].node.ptr())) { - func.function_id = -1; //revert to invalid - } + nodes[p_id].node->disconnect("ports_changed", callable_mp(this, &VisualScript::_node_ports_changed)); + nodes[p_id].node->script_used.unref(); - func.nodes[p_id].node->disconnect("ports_changed", callable_mp(this, &VisualScript::_node_ports_changed)); - func.nodes[p_id].node->scripts_used.erase(this); - - func.nodes.erase(p_id); + nodes.erase(p_id); } -bool VisualScript::has_node(const StringName &p_func, int p_id) const { - ERR_FAIL_COND_V(!functions.has(p_func), false); - const Function &func = functions[p_func]; - - return func.nodes.has(p_id); +bool VisualScript::has_node(int p_id) const { + return nodes.has(p_id); } -Ref<VisualScriptNode> VisualScript::get_node(const StringName &p_func, int p_id) const { - ERR_FAIL_COND_V(!functions.has(p_func), Ref<VisualScriptNode>()); - const Function &func = functions[p_func]; - - ERR_FAIL_COND_V(!func.nodes.has(p_id), Ref<VisualScriptNode>()); +Ref<VisualScriptNode> VisualScript::get_node(int p_id) const { + ERR_FAIL_COND_V(!nodes.has(p_id), Ref<VisualScriptNode>()); - return func.nodes[p_id].node; + return nodes[p_id].node; } -void VisualScript::set_node_position(const StringName &p_func, int p_id, const Point2 &p_pos) { +void VisualScript::set_node_position(int p_id, const Point2 &p_pos) { ERR_FAIL_COND(instances.size()); - ERR_FAIL_COND(!functions.has(p_func)); - Function &func = functions[p_func]; - - ERR_FAIL_COND(!func.nodes.has(p_id)); - func.nodes[p_id].pos = p_pos; + ERR_FAIL_COND(!nodes.has(p_id)); + nodes[p_id].pos = p_pos; } -Point2 VisualScript::get_node_position(const StringName &p_func, int p_id) const { - ERR_FAIL_COND_V(!functions.has(p_func), Point2()); - const Function &func = functions[p_func]; - - ERR_FAIL_COND_V(!func.nodes.has(p_id), Point2()); - return func.nodes[p_id].pos; +Point2 VisualScript::get_node_position(int p_id) const { + ERR_FAIL_COND_V(!nodes.has(p_id), Point2()); + return nodes[p_id].pos; } -void VisualScript::get_node_list(const StringName &p_func, List<int> *r_nodes) const { - ERR_FAIL_COND(!functions.has(p_func)); - const Function &func = functions[p_func]; - - for (const Map<int, Function::NodeData>::Element *E = func.nodes.front(); E; E = E->next()) { - r_nodes->push_back(E->key()); - } +void VisualScript::get_node_list(List<int> *r_nodes) const { + nodes.get_key_list(r_nodes); } -void VisualScript::sequence_connect(const StringName &p_func, int p_from_node, int p_from_output, int p_to_node) { +void VisualScript::sequence_connect(int p_from_node, int p_from_output, int p_to_node) { ERR_FAIL_COND(instances.size()); - ERR_FAIL_COND(!functions.has(p_func)); - Function &func = functions[p_func]; SequenceConnection sc; sc.from_node = p_from_node; sc.from_output = p_from_output; sc.to_node = p_to_node; - ERR_FAIL_COND(func.sequence_connections.has(sc)); + ERR_FAIL_COND(sequence_connections.has(sc)); - func.sequence_connections.insert(sc); + sequence_connections.insert(sc); } -void VisualScript::sequence_disconnect(const StringName &p_func, int p_from_node, int p_from_output, int p_to_node) { - ERR_FAIL_COND(!functions.has(p_func)); - Function &func = functions[p_func]; - +void VisualScript::sequence_disconnect(int p_from_node, int p_from_output, int p_to_node) { SequenceConnection sc; sc.from_node = p_from_node; sc.from_output = p_from_output; sc.to_node = p_to_node; - ERR_FAIL_COND(!func.sequence_connections.has(sc)); + ERR_FAIL_COND(!sequence_connections.has(sc)); - func.sequence_connections.erase(sc); + sequence_connections.erase(sc); } -bool VisualScript::has_sequence_connection(const StringName &p_func, int p_from_node, int p_from_output, int p_to_node) const { - ERR_FAIL_COND_V(!functions.has(p_func), false); - const Function &func = functions[p_func]; - +bool VisualScript::has_sequence_connection(int p_from_node, int p_from_output, int p_to_node) const { SequenceConnection sc; sc.from_node = p_from_node; sc.from_output = p_from_output; sc.to_node = p_to_node; - return func.sequence_connections.has(sc); + return sequence_connections.has(sc); } -void VisualScript::get_sequence_connection_list(const StringName &p_func, List<SequenceConnection> *r_connection) const { - ERR_FAIL_COND(!functions.has(p_func)); - const Function &func = functions[p_func]; - - for (const Set<SequenceConnection>::Element *E = func.sequence_connections.front(); E; E = E->next()) { +void VisualScript::get_sequence_connection_list(List<SequenceConnection> *r_connection) const { + for (const Set<SequenceConnection>::Element *E = sequence_connections.front(); E; E = E->next()) { r_connection->push_back(E->get()); } } -void VisualScript::data_connect(const StringName &p_func, int p_from_node, int p_from_port, int p_to_node, int p_to_port) { +void VisualScript::data_connect(int p_from_node, int p_from_port, int p_to_node, int p_to_port) { ERR_FAIL_COND(instances.size()); - ERR_FAIL_COND(!functions.has(p_func)); - Function &func = functions[p_func]; DataConnection dc; dc.from_node = p_from_node; @@ -468,72 +397,55 @@ void VisualScript::data_connect(const StringName &p_func, int p_from_node, int p dc.to_node = p_to_node; dc.to_port = p_to_port; - ERR_FAIL_COND(func.data_connections.has(dc)); + ERR_FAIL_COND(data_connections.has(dc)); - func.data_connections.insert(dc); + data_connections.insert(dc); } -void VisualScript::data_disconnect(const StringName &p_func, int p_from_node, int p_from_port, int p_to_node, int p_to_port) { - ERR_FAIL_COND(!functions.has(p_func)); - Function &func = functions[p_func]; - +void VisualScript::data_disconnect(int p_from_node, int p_from_port, int p_to_node, int p_to_port) { DataConnection dc; dc.from_node = p_from_node; dc.from_port = p_from_port; dc.to_node = p_to_node; dc.to_port = p_to_port; - ERR_FAIL_COND(!func.data_connections.has(dc)); + ERR_FAIL_COND(!data_connections.has(dc)); - func.data_connections.erase(dc); + data_connections.erase(dc); } -bool VisualScript::has_data_connection(const StringName &p_func, int p_from_node, int p_from_port, int p_to_node, int p_to_port) const { - ERR_FAIL_COND_V(!functions.has(p_func), false); - const Function &func = functions[p_func]; - +bool VisualScript::has_data_connection(int p_from_node, int p_from_port, int p_to_node, int p_to_port) const { DataConnection dc; dc.from_node = p_from_node; dc.from_port = p_from_port; dc.to_node = p_to_node; dc.to_port = p_to_port; - return func.data_connections.has(dc); + return data_connections.has(dc); } -bool VisualScript::is_input_value_port_connected(const StringName &p_func, int p_node, int p_port) const { - ERR_FAIL_COND_V(!functions.has(p_func), false); - const Function &func = functions[p_func]; - - for (const Set<DataConnection>::Element *E = func.data_connections.front(); E; E = E->next()) { +bool VisualScript::is_input_value_port_connected(int p_node, int p_port) const { + for (const Set<DataConnection>::Element *E = data_connections.front(); E; E = E->next()) { if (E->get().to_node == p_node && E->get().to_port == p_port) { return true; } } - return false; } -bool VisualScript::get_input_value_port_connection_source(const StringName &p_func, int p_node, int p_port, int *r_node, int *r_port) const { - ERR_FAIL_COND_V(!functions.has(p_func), false); - const Function &func = functions[p_func]; - - for (const Set<DataConnection>::Element *E = func.data_connections.front(); E; E = E->next()) { +bool VisualScript::get_input_value_port_connection_source(int p_node, int p_port, int *r_node, int *r_port) const { + for (const Set<DataConnection>::Element *E = data_connections.front(); E; E = E->next()) { if (E->get().to_node == p_node && E->get().to_port == p_port) { *r_node = E->get().from_node; *r_port = E->get().from_port; return true; } } - return false; } -void VisualScript::get_data_connection_list(const StringName &p_func, List<DataConnection> *r_connection) const { - ERR_FAIL_COND(!functions.has(p_func)); - const Function &func = functions[p_func]; - - for (const Set<DataConnection>::Element *E = func.data_connections.front(); E; E = E->next()) { +void VisualScript::get_data_connection_list(List<DataConnection> *r_connection) const { + for (const Set<DataConnection>::Element *E = data_connections.front(); E; E = E->next()) { r_connection->push_back(E->get()); } } @@ -653,11 +565,8 @@ Dictionary VisualScript::_get_variable_info(const StringName &p_name) const { } void VisualScript::get_variable_list(List<StringName> *r_variables) const { - for (Map<StringName, Variable>::Element *E = variables.front(); E; E = E->next()) { - r_variables->push_back(E->key()); - } - - r_variables->sort_custom<StringName::AlphCompare>(); + variables.get_key_list(r_variables); + // r_variables->sort_custom<StringName::AlphCompare>(); // Don't force it. } void VisualScript::set_instance_base_type(const StringName &p_type) { @@ -680,24 +589,19 @@ void VisualScript::rename_variable(const StringName &p_name, const StringName &p variables[p_new_name] = variables[p_name]; variables.erase(p_name); - - List<StringName> funcs; - get_function_list(&funcs); - for (List<StringName>::Element *F = funcs.front(); F; F = F->next()) { // loop through all the functions - List<int> ids; - get_node_list(F->get(), &ids); - for (List<int>::Element *E = ids.front(); E; E = E->next()) { - Ref<VisualScriptVariableGet> nodeget = get_node(F->get(), E->get()); - if (nodeget.is_valid()) { - if (nodeget->get_variable() == p_name) { - nodeget->set_variable(p_new_name); - } - } else { - Ref<VisualScriptVariableSet> nodeset = get_node(F->get(), E->get()); - if (nodeset.is_valid()) { - if (nodeset->get_variable() == p_name) { - nodeset->set_variable(p_new_name); - } + List<int> ids; + get_node_list(&ids); + for (List<int>::Element *E = ids.front(); E; E = E->next()) { + Ref<VisualScriptVariableGet> nodeget = get_node(E->get()); + if (nodeget.is_valid()) { + if (nodeget->get_variable() == p_name) { + nodeget->set_variable(p_new_name); + } + } else { + Ref<VisualScriptVariableSet> nodeset = get_node(E->get()); + if (nodeset.is_valid()) { + if (nodeset->get_variable() == p_name) { + nodeset->set_variable(p_new_name); } } } @@ -808,23 +712,24 @@ void VisualScript::get_custom_signal_list(List<StringName> *r_custom_signals) co } int VisualScript::get_available_id() const { - int max_id = 0; - for (Map<StringName, Function>::Element *E = functions.front(); E; E = E->next()) { - if (E->get().nodes.is_empty()) { - continue; + // This is infinitely increasing, + // so one might want to implement a better solution, + // if the there is a case for huge number of nodes to be added to visual script. + List<int> nds; + nodes.get_key_list(&nds); + int max = -1; + for (const List<int>::Element *E = nds.front(); E; E = E->next()) { + if (E->get() > max) { + max = E->get(); } - - int last_id = E->get().nodes.back()->key(); - max_id = MAX(max_id, last_id + 1); } - - return max_id; + return (max + 1); } ///////////////////////////////// bool VisualScript::can_instance() const { - return true; //ScriptServer::is_scripting_enabled(); + return true; // ScriptServer::is_scripting_enabled(); } StringName VisualScript::get_instance_base_type() const { @@ -832,7 +737,7 @@ StringName VisualScript::get_instance_base_type() const { } Ref<Script> VisualScript::get_base_script() const { - return Ref<Script>(); // no inheritance in visual script + return Ref<Script>(); // No inheritance in visual script. } #ifdef TOOLS_ENABLED @@ -842,20 +747,23 @@ void VisualScript::_placeholder_erased(PlaceHolderScriptInstance *p_placeholder) void VisualScript::_update_placeholders() { if (placeholders.size() == 0) { - return; //no bother if no placeholders + return; // No bother if no placeholders. } List<PropertyInfo> pinfo; Map<StringName, Variant> values; - for (Map<StringName, Variable>::Element *E = variables.front(); E; E = E->next()) { - if (!E->get()._export) { + List<StringName> keys; + variables.get_key_list(&keys); + + for (List<StringName>::Element *E = keys.front(); E; E = E->next()) { + if (!variables[E->get()]._export) { continue; } - PropertyInfo p = E->get().info; - p.name = String(E->key()); + PropertyInfo p = variables[E->get()].info; + p.name = String(E->get()); pinfo.push_back(p); - values[p.name] = E->get().default_value; + values[p.name] = variables[E->get()].default_value; } for (Set<PlaceHolderScriptInstance *>::Element *E = placeholders.front(); E; E = E->next()) { @@ -875,17 +783,18 @@ ScriptInstance *VisualScript::instance_create(Object *p_this) { List<PropertyInfo> pinfo; Map<StringName, Variant> values; - for (Map<StringName, Variable>::Element *E = variables.front(); E; E = E->next()) { - if (!E->get()._export) { + List<StringName> keys; + variables.get_key_list(&keys); + + for (const List<StringName>::Element *E = keys.front(); E; E = E->next()) { + if (!variables[E->get()]._export) continue; - } - PropertyInfo p = E->get().info; - p.name = String(E->key()); + PropertyInfo p = variables[E->get()].info; + p.name = String(E->get()); pinfo.push_back(p); - values[p.name] = E->get().default_value; + values[p.name] = variables[E->get()].default_value; } - sins->update(pinfo, values); return sins; @@ -928,7 +837,7 @@ bool VisualScript::is_tool() const { } bool VisualScript::is_valid() const { - return true; //always valid + return true; // Always valid. } ScriptLanguage *VisualScript::get_language() const { @@ -964,11 +873,14 @@ bool VisualScript::get_property_default_value(const StringName &p_property, Vari } void VisualScript::get_script_method_list(List<MethodInfo> *p_list) const { - for (Map<StringName, Function>::Element *E = functions.front(); E; E = E->next()) { + List<StringName> funcs; + functions.get_key_list(&funcs); + + for (List<StringName>::Element *E = funcs.front(); E; E = E->next()) { MethodInfo mi; - mi.name = E->key(); - if (E->get().function_id >= 0) { - Ref<VisualScriptFunction> func = E->get().nodes[E->get().function_id].node; + mi.name = E->get(); + if (functions[E->get()].func_id >= 0) { + Ref<VisualScriptFunction> func = nodes[functions[E->get()].func_id].node; if (func.is_valid()) { for (int i = 0; i < func->get_argument_count(); i++) { PropertyInfo arg; @@ -988,15 +900,15 @@ bool VisualScript::has_method(const StringName &p_method) const { } MethodInfo VisualScript::get_method_info(const StringName &p_method) const { - const Map<StringName, Function>::Element *E = functions.find(p_method); - if (!E) { + const Function funct = functions[p_method]; + if (funct.func_id == -1) { return MethodInfo(); } MethodInfo mi; - mi.name = E->key(); - if (E->get().function_id >= 0) { - Ref<VisualScriptFunction> func = E->get().nodes[E->get().function_id].node; + mi.name = p_method; + if (funct.func_id >= 0) { + Ref<VisualScriptFunction> func = nodes[funct.func_id].node; if (func.is_valid()) { for (int i = 0; i < func->get_argument_count(); i++) { PropertyInfo arg; @@ -1028,28 +940,18 @@ void VisualScript::get_script_property_list(List<PropertyInfo> *p_list) const { } int VisualScript::get_member_line(const StringName &p_member) const { -#ifdef TOOLS_ENABLED - if (has_function(p_member)) { - for (Map<int, Function::NodeData>::Element *E = functions[p_member].nodes.front(); E; E = E->next()) { - if (Object::cast_to<VisualScriptFunction>(E->get().node.ptr())) { - return E->key(); - } - } - } -#endif - return -1; + return functions[p_member].func_id; // will be -1 if not found } #ifdef TOOLS_ENABLED bool VisualScript::are_subnodes_edited() const { - for (const Map<StringName, Function>::Element *E = functions.front(); E; E = E->next()) { - for (const Map<int, Function::NodeData>::Element *F = E->get().nodes.front(); F; F = F->next()) { - if (F->get().node->is_edited()) { - return true; - } + List<int> keys; + nodes.get_key_list(&keys); + for (const List<int>::Element *F = keys.front(); F; F = F->next()) { + if (nodes[F->get()].node->is_edited()) { + return true; } } - return false; } #endif @@ -1140,85 +1042,41 @@ void VisualScript::_set_data(const Dictionary &p_data) { Array funcs = d["functions"]; functions.clear(); - Vector2 last_pos = Vector2(-100 * funcs.size(), -100 * funcs.size()); // this is the center of the last fn box - Vector2 last_size = Vector2(0.0, 0.0); - for (int i = 0; i < funcs.size(); i++) { Dictionary func = funcs[i]; - - StringName name = func["name"]; - //int id=func["function_id"]; - add_function(name); - - set_function_scroll(name, func["scroll"]); - - Array nodes = func["nodes"]; - - if (!d.has("vs_unify") && nodes.size() > 0) { - Vector2 top_left = nodes[1]; - Vector2 bottom_right = nodes[1]; - - for (int j = 0; j < nodes.size(); j += 3) { - Point2 pos = nodes[j + 1]; - if (pos.y > top_left.y) { - top_left.y = pos.y; - } - if (pos.y < bottom_right.y) { - bottom_right.y = pos.y; - } - if (pos.x > bottom_right.x) { - bottom_right.x = pos.x; - } - if (pos.x < top_left.x) { - top_left.x = pos.x; - } - } - - Vector2 size = Vector2(bottom_right.x - top_left.x, top_left.y - bottom_right.y); - - Vector2 offset = last_pos + (last_size / 2.0) + (size / 2.0); // dunno I might just keep it in one axis but diagonal feels better.... - - last_pos = offset; - last_size = size; - - for (int j = 0; j < nodes.size(); j += 3) { - add_node(name, nodes[j], nodes[j + 2], offset + nodes[j + 1]); // also add an additional buffer if you want to - } - - } else { - for (int j = 0; j < nodes.size(); j += 3) { - add_node(name, nodes[j], nodes[j + 2], nodes[j + 1]); - } + add_function(func["name"], func["function_id"]); + } + { + Array nodes = d["nodes"]; + for (int i = 0; i < nodes.size(); i += 3) { + add_node(nodes[i], nodes[i + 2], nodes[i + 1]); } - Array sequence_connections = func["sequence_connections"]; + Array sequence_connections = d["sequence_connections"]; for (int j = 0; j < sequence_connections.size(); j += 3) { - sequence_connect(name, sequence_connections[j + 0], sequence_connections[j + 1], sequence_connections[j + 2]); + sequence_connect(sequence_connections[j + 0], sequence_connections[j + 1], sequence_connections[j + 2]); } - Array data_connections = func["data_connections"]; - + Array data_connections = d["data_connections"]; for (int j = 0; j < data_connections.size(); j += 4) { - data_connect(name, data_connections[j + 0], data_connections[j + 1], data_connections[j + 2], data_connections[j + 3]); + data_connect(data_connections[j + 0], data_connections[j + 1], data_connections[j + 2], data_connections[j + 3]); } } + is_tool_script = d["is_tool_script"]; + scroll = d["scroll"]; - if (d.has("is_tool_script")) { - is_tool_script = d["is_tool_script"]; - } else { - is_tool_script = false; - } - - // Takes all the rpc methods + // Takes all the rpc methods. rpc_functions.clear(); rpc_variables.clear(); - for (Map<StringName, Function>::Element *E = functions.front(); E; E = E->next()) { - if (E->get().function_id >= 0 && E->get().nodes.find(E->get().function_id)) { - Ref<VisualScriptFunction> vsf = E->get().nodes[E->get().function_id].node; + List<StringName> fns; + functions.get_key_list(&fns); + for (const List<StringName>::Element *E = fns.front(); E; E = E->next()) { + if (functions[E->get()].func_id >= 0 && nodes.has(functions[E->get()].func_id)) { + Ref<VisualScriptFunction> vsf = nodes[functions[E->get()].func_id].node; if (vsf.is_valid()) { if (vsf->get_rpc_mode() != MultiplayerAPI::RPC_MODE_DISABLED) { ScriptNetData nd; - nd.name = E->key(); + nd.name = E->get(); nd.mode = vsf->get_rpc_mode(); if (rpc_functions.find(nd) == -1) { rpc_functions.push_back(nd); @@ -1228,8 +1086,6 @@ void VisualScript::_set_data(const Dictionary &p_data) { } } - // Visual script doesn't have rset :( - // Sort so we are 100% that they are always the same. rpc_functions.sort_custom<SortNetData>(); } @@ -1237,12 +1093,15 @@ void VisualScript::_set_data(const Dictionary &p_data) { Dictionary VisualScript::_get_data() const { Dictionary d; d["base_type"] = base_type; + Array vars; - for (const Map<StringName, Variable>::Element *E = variables.front(); E; E = E->next()) { - Dictionary var = _get_variable_info(E->key()); - var["name"] = E->key(); //make sure it's the right one - var["default_value"] = E->get().default_value; - var["export"] = E->get()._export; + List<StringName> var_names; + variables.get_key_list(&var_names); + for (const List<StringName>::Element *E = var_names.front(); E; E = E->next()) { + Dictionary var = _get_variable_info(E->get()); + var["name"] = E->get(); // Make sure it's the right one. + var["default_value"] = variables[E->get()].default_value; + var["export"] = variables[E->get()]._export; vars.push_back(var); } d["variables"] = vars; @@ -1264,78 +1123,73 @@ Dictionary VisualScript::_get_data() const { d["signals"] = sigs; Array funcs; - - for (const Map<StringName, Function>::Element *E = functions.front(); E; E = E->next()) { + List<StringName> func_names; + functions.get_key_list(&func_names); + for (const List<StringName>::Element *E = func_names.front(); E; E = E->next()) { Dictionary func; - func["name"] = E->key(); - func["function_id"] = E->get().function_id; - func["scroll"] = E->get().scroll; - - Array nodes; - - for (const Map<int, Function::NodeData>::Element *F = E->get().nodes.front(); F; F = F->next()) { - nodes.push_back(F->key()); - nodes.push_back(F->get().pos); - nodes.push_back(F->get().node); - } - - func["nodes"] = nodes; - - Array sequence_connections; - - for (const Set<SequenceConnection>::Element *F = E->get().sequence_connections.front(); F; F = F->next()) { - sequence_connections.push_back(F->get().from_node); - sequence_connections.push_back(F->get().from_output); - sequence_connections.push_back(F->get().to_node); - } - - func["sequence_connections"] = sequence_connections; - - Array data_connections; + func["name"] = E->get(); + func["function_id"] = functions[E->get()].func_id; + funcs.push_back(func); + } + d["functions"] = funcs; - for (const Set<DataConnection>::Element *F = E->get().data_connections.front(); F; F = F->next()) { - data_connections.push_back(F->get().from_node); - data_connections.push_back(F->get().from_port); - data_connections.push_back(F->get().to_node); - data_connections.push_back(F->get().to_port); - } + Array nds; + List<int> node_ids; + nodes.get_key_list(&node_ids); + for (const List<int>::Element *F = node_ids.front(); F; F = F->next()) { + nds.push_back(F->get()); + nds.push_back(nodes[F->get()].pos); + nds.push_back(nodes[F->get()].node); + } + d["nodes"] = nds; - func["data_connections"] = data_connections; + Array seqconns; + for (const Set<SequenceConnection>::Element *F = sequence_connections.front(); F; F = F->next()) { + seqconns.push_back(F->get().from_node); + seqconns.push_back(F->get().from_output); + seqconns.push_back(F->get().to_node); + } + d["sequence_connections"] = seqconns; - funcs.push_back(func); + Array dataconns; + for (const Set<DataConnection>::Element *F = data_connections.front(); F; F = F->next()) { + dataconns.push_back(F->get().from_node); + dataconns.push_back(F->get().from_port); + dataconns.push_back(F->get().to_node); + dataconns.push_back(F->get().to_port); } + d["data_connections"] = dataconns; - d["functions"] = funcs; d["is_tool_script"] = is_tool_script; - d["vs_unify"] = true; + d["scroll"] = scroll; return d; } void VisualScript::_bind_methods() { - ClassDB::bind_method(D_METHOD("add_function", "name"), &VisualScript::add_function); + ClassDB::bind_method(D_METHOD("add_function", "name", "func_node_id"), &VisualScript::add_function); ClassDB::bind_method(D_METHOD("has_function", "name"), &VisualScript::has_function); ClassDB::bind_method(D_METHOD("remove_function", "name"), &VisualScript::remove_function); ClassDB::bind_method(D_METHOD("rename_function", "name", "new_name"), &VisualScript::rename_function); - ClassDB::bind_method(D_METHOD("set_function_scroll", "name", "ofs"), &VisualScript::set_function_scroll); - ClassDB::bind_method(D_METHOD("get_function_scroll", "name"), &VisualScript::get_function_scroll); + ClassDB::bind_method(D_METHOD("set_scroll", "ofs"), &VisualScript::set_scroll); + ClassDB::bind_method(D_METHOD("get_scroll"), &VisualScript::get_scroll); - ClassDB::bind_method(D_METHOD("add_node", "func", "id", "node", "position"), &VisualScript::add_node, DEFVAL(Point2())); - ClassDB::bind_method(D_METHOD("remove_node", "func", "id"), &VisualScript::remove_node); + ClassDB::bind_method(D_METHOD("add_node", "id", "node", "position"), &VisualScript::add_node, DEFVAL(Point2())); + ClassDB::bind_method(D_METHOD("remove_node", "id"), &VisualScript::remove_node); ClassDB::bind_method(D_METHOD("get_function_node_id", "name"), &VisualScript::get_function_node_id); - ClassDB::bind_method(D_METHOD("get_node", "func", "id"), &VisualScript::get_node); - ClassDB::bind_method(D_METHOD("has_node", "func", "id"), &VisualScript::has_node); - ClassDB::bind_method(D_METHOD("set_node_position", "func", "id", "position"), &VisualScript::set_node_position); - ClassDB::bind_method(D_METHOD("get_node_position", "func", "id"), &VisualScript::get_node_position); + ClassDB::bind_method(D_METHOD("get_node", "id"), &VisualScript::get_node); + ClassDB::bind_method(D_METHOD("has_node", "id"), &VisualScript::has_node); + ClassDB::bind_method(D_METHOD("set_node_position", "id", "position"), &VisualScript::set_node_position); + ClassDB::bind_method(D_METHOD("get_node_position", "id"), &VisualScript::get_node_position); - ClassDB::bind_method(D_METHOD("sequence_connect", "func", "from_node", "from_output", "to_node"), &VisualScript::sequence_connect); - ClassDB::bind_method(D_METHOD("sequence_disconnect", "func", "from_node", "from_output", "to_node"), &VisualScript::sequence_disconnect); - ClassDB::bind_method(D_METHOD("has_sequence_connection", "func", "from_node", "from_output", "to_node"), &VisualScript::has_sequence_connection); + ClassDB::bind_method(D_METHOD("sequence_connect", "from_node", "from_output", "to_node"), &VisualScript::sequence_connect); + ClassDB::bind_method(D_METHOD("sequence_disconnect", "from_node", "from_output", "to_node"), &VisualScript::sequence_disconnect); + ClassDB::bind_method(D_METHOD("has_sequence_connection", "from_node", "from_output", "to_node"), &VisualScript::has_sequence_connection); - ClassDB::bind_method(D_METHOD("data_connect", "func", "from_node", "from_port", "to_node", "to_port"), &VisualScript::data_connect); - ClassDB::bind_method(D_METHOD("data_disconnect", "func", "from_node", "from_port", "to_node", "to_port"), &VisualScript::data_disconnect); - ClassDB::bind_method(D_METHOD("has_data_connection", "func", "from_node", "from_port", "to_node", "to_port"), &VisualScript::has_data_connection); + ClassDB::bind_method(D_METHOD("data_connect", "from_node", "from_port", "to_node", "to_port"), &VisualScript::data_connect); + ClassDB::bind_method(D_METHOD("data_disconnect", "from_node", "from_port", "to_node", "to_port"), &VisualScript::data_disconnect); + ClassDB::bind_method(D_METHOD("has_data_connection", "from_node", "from_port", "to_node", "to_port"), &VisualScript::has_data_connection); ClassDB::bind_method(D_METHOD("add_variable", "name", "default_value", "export"), &VisualScript::add_variable, DEFVAL(Variant()), DEFVAL(false)); ClassDB::bind_method(D_METHOD("has_variable", "name"), &VisualScript::has_variable); @@ -1371,7 +1225,7 @@ void VisualScript::_bind_methods() { ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL), "_set_data", "_get_data"); - ADD_SIGNAL(MethodInfo("node_ports_changed", PropertyInfo(Variant::STRING, "function"), PropertyInfo(Variant::INT, "id"))); + ADD_SIGNAL(MethodInfo("node_ports_changed", PropertyInfo(Variant::INT, "id"))); } VisualScript::VisualScript() { @@ -1380,16 +1234,12 @@ VisualScript::VisualScript() { } bool VisualScript::inherits_script(const Ref<Script> &p_script) const { - return this == p_script.ptr(); //there is no inheritance in visual scripts, so this is enough -} - -StringName VisualScript::get_default_func() const { - return StringName("f_312843592"); + return this == p_script.ptr(); // There is no inheritance in visual scripts, so this is enough. } -Set<int> VisualScript::get_output_sequence_ports_connected(const String &edited_func, int from_node) { +Set<int> VisualScript::get_output_sequence_ports_connected(int from_node) { List<VisualScript::SequenceConnection> *sc = memnew(List<VisualScript::SequenceConnection>); - get_sequence_connection_list(edited_func, sc); + get_sequence_connection_list(sc); Set<int> connected; for (List<VisualScript::SequenceConnection>::Element *E = sc->front(); E; E = E->next()) { if (E->get().from_node == from_node) { @@ -1401,8 +1251,11 @@ Set<int> VisualScript::get_output_sequence_ports_connected(const String &edited_ } VisualScript::~VisualScript() { - while (!functions.is_empty()) { - remove_function(functions.front()->key()); + // Remove all nodes and stuff that hold data refs. + List<int> nds; + nodes.get_key_list(&nds); + for (const List<int>::Element *E = nds.front(); E; E = E->next()) { + remove_node(E->get()); } } @@ -1430,20 +1283,21 @@ bool VisualScriptInstance::get(const StringName &p_name, Variant &r_ret) const { } void VisualScriptInstance::get_property_list(List<PropertyInfo> *p_properties) const { - for (const Map<StringName, VisualScript::Variable>::Element *E = script->variables.front(); E; E = E->next()) { - if (!E->get()._export) { + List<StringName> vars; + script->variables.get_key_list(&vars); + for (const List<StringName>::Element *E = vars.front(); E; E = E->next()) { + if (!script->variables[E->get()]._export) { continue; } - PropertyInfo p = E->get().info; - p.name = String(E->key()); + PropertyInfo p = script->variables[E->get()].info; + p.name = String(E->get()); p.usage |= PROPERTY_USAGE_SCRIPT_VARIABLE; p_properties->push_back(p); } } Variant::Type VisualScriptInstance::get_property_type(const StringName &p_name, bool *r_is_valid) const { - const Map<StringName, VisualScript::Variable>::Element *E = script->variables.find(p_name); - if (!E) { + if (!script->variables.has(p_name)) { if (r_is_valid) { *r_is_valid = false; } @@ -1454,19 +1308,17 @@ Variant::Type VisualScriptInstance::get_property_type(const StringName &p_name, *r_is_valid = true; } - return E->get().info.type; + return script->variables[p_name].info.type; } void VisualScriptInstance::get_method_list(List<MethodInfo> *p_list) const { - for (const Map<StringName, VisualScript::Function>::Element *E = script->functions.front(); E; E = E->next()) { - if (E->key() == script->get_default_func()) { - continue; - } - + List<StringName> fns; + script->functions.get_key_list(&fns); + for (const List<StringName>::Element *E = fns.front(); E; E = E->next()) { MethodInfo mi; - mi.name = E->key(); - if (E->get().function_id >= 0 && E->get().nodes.has(E->get().function_id)) { - Ref<VisualScriptFunction> vsf = E->get().nodes[E->get().function_id].node; + mi.name = E->get(); + if (script->functions[E->get()].func_id >= 0 && script->nodes.has(script->functions[E->get()].func_id)) { + Ref<VisualScriptFunction> vsf = script->nodes[script->functions[E->get()].func_id].node; if (vsf.is_valid()) { for (int i = 0; i < vsf->get_argument_count(); i++) { PropertyInfo arg; @@ -1476,21 +1328,16 @@ void VisualScriptInstance::get_method_list(List<MethodInfo> *p_list) const { mi.arguments.push_back(arg); } - if (!vsf->is_sequenced()) { //assumed constant if not sequenced + if (!vsf->is_sequenced()) { // Assumed constant if not sequenced. mi.flags |= METHOD_FLAG_CONST; } } } - p_list->push_back(mi); } } bool VisualScriptInstance::has_method(const StringName &p_method) const { - if (p_method == script->get_default_func()) { - return false; - } - return script->functions.has(p_method); } @@ -1522,10 +1369,10 @@ void VisualScriptInstance::_dependency_step(VisualScriptNodeInstance *node, int int index = node->input_ports[i] & VisualScriptNodeInstance::INPUT_MASK; if (node->input_ports[i] & VisualScriptNodeInstance::INPUT_DEFAULT_VALUE_BIT) { - //is a default value (unassigned input port) + // Is a default value (unassigned input port). input_args[i] = &default_values[index]; } else { - //regular temporary in stack + // Rregular temporary in stack. input_args[i] = &variant_stack[index]; } } @@ -1536,7 +1383,7 @@ void VisualScriptInstance::_dependency_step(VisualScriptNodeInstance *node, int Variant *working_mem = node->working_mem_idx >= 0 ? &variant_stack[node->working_mem_idx] : (Variant *)nullptr; node->step(input_args, output_args, VisualScriptNodeInstance::START_MODE_BEGIN_SEQUENCE, working_mem, r_error, error_str); - //ignore return + // Ignore return. if (r_error.error != Callable::CallError::CALL_OK) { *r_error_node = node; } @@ -1547,7 +1394,7 @@ Variant VisualScriptInstance::_call_internal(const StringName &p_method, void *p ERR_FAIL_COND_V(!F, Variant()); Function *f = &F->get(); - //this call goes separate, so it can e yielded and suspended + // This call goes separate, so it can e yielded and suspended. Variant *variant_stack = (Variant *)p_stack; bool *sequence_bits = (bool *)(variant_stack + f->max_stack); const Variant **input_args = (const Variant **)(sequence_bits + f->node_count); @@ -1573,25 +1420,25 @@ Variant VisualScriptInstance::_call_internal(const StringName &p_method, void *p #endif while (true) { - p_pass++; //increment pass + p_pass++; // Increment pass. current_node_id = node->get_id(); VSDEBUG("==========AT NODE: " + itos(current_node_id) + " base: " + node->get_base_node()->get_class_name()); VSDEBUG("AT STACK POS: " + itos(flow_stack_pos)); - //setup working mem + // Setup working mem. working_mem = node->working_mem_idx >= 0 ? &variant_stack[node->working_mem_idx] : (Variant *)nullptr; VSDEBUG("WORKING MEM: " + itos(node->working_mem_idx)); if (current_node_id == f->node) { - //if function node, set up function arguments from beginning of stack + // If function node, set up function arguments from beginning of stack. for (int i = 0; i < f->argument_count; i++) { input_args[i] = &variant_stack[i]; } } else { - //run dependencies first + // Run dependencies first. if (!node->dependencies.is_empty()) { int dc = node->dependencies.size(); @@ -1608,18 +1455,18 @@ Variant VisualScriptInstance::_call_internal(const StringName &p_method, void *p } if (!error) { - //setup input pointers normally + // Setup input pointers normally. VSDEBUG("INPUT PORTS: " + itos(node->input_port_count)); for (int i = 0; i < node->input_port_count; i++) { int index = node->input_ports[i] & VisualScriptNodeInstance::INPUT_MASK; if (node->input_ports[i] & VisualScriptNodeInstance::INPUT_DEFAULT_VALUE_BIT) { - //is a default value (unassigned input port) + // Is a default value (unassigned input port). input_args[i] = &default_values[index]; VSDEBUG("\tPORT " + itos(i) + " DEFAULT VAL"); } else { - //regular temporary in stack + // Regular temporary in stack. input_args[i] = &variant_stack[index]; VSDEBUG("PORT " + itos(i) + " AT STACK " + itos(index)); } @@ -1631,7 +1478,7 @@ Variant VisualScriptInstance::_call_internal(const StringName &p_method, void *p break; } - //setup output pointers + // Setup output pointers. VSDEBUG("OUTPUT PORTS: " + itos(node->output_port_count)); for (int i = 0; i < node->output_port_count; i++) { @@ -1639,15 +1486,15 @@ Variant VisualScriptInstance::_call_internal(const StringName &p_method, void *p VSDEBUG("PORT " + itos(i) + " AT STACK " + itos(node->output_ports[i])); } - //do step + // Do step. VisualScriptNodeInstance::StartMode start_mode; { if (p_resuming_yield) { start_mode = VisualScriptNodeInstance::START_MODE_RESUME_YIELD; - p_resuming_yield = false; // should resume only the first time + p_resuming_yield = false; // Should resume only the first time. } else if (flow_stack && (flow_stack[flow_stack_pos] & VisualScriptNodeInstance::FLOW_STACK_PUSHED_BIT)) { - //if there is a push bit, it means we are continuing a sequence + // If there is a push bit, it means we are continuing a sequence. start_mode = VisualScriptNodeInstance::START_MODE_CONTINUE_SEQUENCE; } else { start_mode = VisualScriptNodeInstance::START_MODE_BEGIN_SEQUENCE; @@ -1659,13 +1506,13 @@ Variant VisualScriptInstance::_call_internal(const StringName &p_method, void *p int ret = node->step(input_args, output_args, start_mode, working_mem, r_error, error_str); if (r_error.error != Callable::CallError::CALL_OK) { - //use error from step + // Use error from step. error = true; break; } if (ret & VisualScriptNodeInstance::STEP_YIELD_BIT) { - //yielded! + // Yielded! if (node->get_working_memory_size() == 0) { r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; error_str = RTR("A node yielded without working memory, please read the docs on how to yield properly!"); @@ -1681,7 +1528,7 @@ Variant VisualScriptInstance::_call_internal(const StringName &p_method, void *p break; } - //step 1, capture all state + // Step 1, capture all state. state->instance_id = get_owner_ptr()->get_instance_id(); state->script_id = get_script()->get_instance_id(); state->instance = this; @@ -1693,11 +1540,11 @@ Variant VisualScriptInstance::_call_internal(const StringName &p_method, void *p state->stack.resize(p_stack_size); state->pass = p_pass; copymem(state->stack.ptrw(), p_stack, p_stack_size); - //step 2, run away, return directly + // Step 2, run away, return directly. r_error.error = Callable::CallError::CALL_OK; #ifdef DEBUG_ENABLED - //will re-enter later, so exiting + // Will re-enter later, so exiting. if (EngineDebugger::is_active()) { VisualScriptLanguage::singleton->exit_function(); } @@ -1742,18 +1589,18 @@ Variant VisualScriptInstance::_call_internal(const StringName &p_method, void *p error_str = RTR("Return value must be assigned to first element of node working memory! Fix your node please."); error = true; } else { - //assign from working memory, first element + // Assign from working memory, first element. return_value = *working_mem; } VSDEBUG("EXITING FUNCTION - VALUE " + String(return_value)); - break; //exit function requested, bye + break; // Exit function requested, bye } - VisualScriptNodeInstance *next = nullptr; //next node + VisualScriptNodeInstance *next = nullptr; // Next node. if ((ret == output || ret & VisualScriptNodeInstance::STEP_FLAG_PUSH_STACK_BIT) && node->sequence_output_count) { - //if no exit bit was set, and has sequence outputs, guess next node + // If no exit bit was set, and has sequence outputs, guess next node. if (output >= node->sequence_output_count) { r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; error_str = RTR("Node returned an invalid sequence output: ") + itos(output); @@ -1766,21 +1613,21 @@ Variant VisualScriptInstance::_call_internal(const StringName &p_method, void *p } if (flow_stack) { - //update flow stack pos (may have changed) + // Update flow stack pos (may have changed). flow_stack[flow_stack_pos] = current_node_id; - //add stack push bit if requested + // Add stack push bit if requested. if (ret & VisualScriptNodeInstance::STEP_FLAG_PUSH_STACK_BIT) { flow_stack[flow_stack_pos] |= VisualScriptNodeInstance::FLOW_STACK_PUSHED_BIT; - sequence_bits[node->sequence_index] = true; //remember sequence bit + sequence_bits[node->sequence_index] = true; // Remember sequence bit. VSDEBUG("NEXT SEQ - FLAG BIT"); } else { - sequence_bits[node->sequence_index] = false; //forget sequence bit + sequence_bits[node->sequence_index] = false; // Forget sequence bit. VSDEBUG("NEXT SEQ - NORMAL"); } if (ret & VisualScriptNodeInstance::STEP_FLAG_GO_BACK_BIT) { - //go back request + // Go back request. if (flow_stack_pos > 0) { flow_stack_pos--; @@ -1788,20 +1635,20 @@ Variant VisualScriptInstance::_call_internal(const StringName &p_method, void *p VSDEBUG("NEXT IS GO BACK"); } else { VSDEBUG("NEXT IS GO BACK, BUT NO NEXT SO EXIT"); - break; //simply exit without value or error + break; // Simply exit without value or error. } } else if (next) { if (sequence_bits[next->sequence_index]) { - // what happened here is that we are entering a node that is in the middle of doing a sequence (pushed stack) from the front + // What happened here is that we are entering a node that is in the middle of doing a sequence (pushed stack) from the front // because each node has a working memory, we can't really do a sub-sequence // as a result, the sequence will be restarted and the stack will roll back to find where this node - // started the sequence + // started the sequence. bool found = false; for (int i = flow_stack_pos; i >= 0; i--) { if ((flow_stack[i] & VisualScriptNodeInstance::FLOW_STACK_MASK) == next->get_id()) { - flow_stack_pos = i; //roll back and remove bit + flow_stack_pos = i; // Roll back and remove bit. flow_stack[i] = next->get_id(); sequence_bits[next->sequence_index] = false; found = true; @@ -1819,7 +1666,7 @@ Variant VisualScriptInstance::_call_internal(const StringName &p_method, void *p VSDEBUG("RE-ENTERED A LOOP, RETURNED STACK POS TO - " + itos(flow_stack_pos)); } else { - // check for stack overflow + // Check for stack overflow. if (flow_stack_pos + 1 >= flow_max) { r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; error_str = RTR("Stack overflow with stack depth: ") + itos(output); @@ -1836,7 +1683,7 @@ Variant VisualScriptInstance::_call_internal(const StringName &p_method, void *p } } else { - //no next node, try to go back in stack to pushed bit + // No next node, try to go back in stack to pushed bit. bool found = false; @@ -1852,22 +1699,22 @@ Variant VisualScriptInstance::_call_internal(const StringName &p_method, void *p if (!found) { VSDEBUG("NO NEXT NODE, NO GO BACK, EXITING"); - break; //done, couldn't find a push stack bit + break; // Done, couldn't find a push stack bit. } VSDEBUG("NO NEXT NODE, GO BACK TO: " + itos(flow_stack_pos)); } } else { - node = next; //stackless mode, simply assign next node + node = next; // Stackless mode, simply assign next node. } } if (error) { - //error - // function, file, line, error, explanation + // Error + // Function, file, line, error, explanation. String err_file = script->get_path(); String err_func = p_method; - int err_line = current_node_id; //not a line but it works as one + int err_line = current_node_id; // Not a line but it works as one. if (node && (r_error.error != Callable::CallError::CALL_ERROR_INVALID_METHOD || error_str == String())) { if (error_str != String()) { @@ -1906,7 +1753,7 @@ Variant VisualScriptInstance::_call_internal(const StringName &p_method, void *p } #endif - //clean up variant stack + // Clean up variant stack. for (int i = 0; i < f->max_stack; i++) { variant_stack[i].~Variant(); } @@ -1954,7 +1801,7 @@ Variant VisualScriptInstance::call(const StringName &p_method, const Variant **p int *pass_stack = flow_stack ? (int *)(flow_stack + flow_max) : (int *)nullptr; for (int i = 0; i < f->node_count; i++) { - sequence_bits[i] = false; //all starts as false + sequence_bits[i] = false; // All starts as false. } zeromem(pass_stack, f->pass_stack_size * sizeof(int)); @@ -1988,12 +1835,12 @@ Variant VisualScriptInstance::call(const StringName &p_method, const Variant **p return Variant(); } - //allocate variant stack + // Allocate variant stack. for (int i = 0; i < f->max_stack; i++) { memnew_placement(&variant_stack[i], Variant); } - //allocate function arguments (must be copied for yield to work properly) + // Allocate function arguments (must be copied for yield to work properly). for (int i = 0; i < p_argcount; i++) { variant_stack[i] = *p_args[i]; } @@ -2002,12 +1849,12 @@ Variant VisualScriptInstance::call(const StringName &p_method, const Variant **p } void VisualScriptInstance::notification(int p_notification) { - //do nothing as this is called using virtual + // Do nothing as this is called using virtual. Variant what = p_notification; const Variant *whatp = &what; Callable::CallError ce; - call(VisualScriptLanguage::singleton->notification, &whatp, 1, ce); //do as call + call(VisualScriptLanguage::singleton->notification, &whatp, 1, ce); // Do as call. } String VisualScriptInstance::to_string(bool *r_valid) { @@ -2086,7 +1933,7 @@ void VisualScriptInstance::create(const Ref<VisualScript> &p_script, Object *p_o max_output_args = 0; if (Object::cast_to<Node>(p_owner)) { - //turn on these if they exist and base is a node + // Turn on these if they exist and base is a node. Node *node = Object::cast_to<Node>(p_owner); if (p_script->functions.has("_process")) { node->set_process(true); @@ -2105,190 +1952,236 @@ void VisualScriptInstance::create(const Ref<VisualScript> &p_script, Object *p_o } } - for (const Map<StringName, VisualScript::Variable>::Element *E = script->variables.front(); E; E = E->next()) { - variables[E->key()] = E->get().default_value; - } - - for (const Map<StringName, VisualScript::Function>::Element *E = script->functions.front(); E; E = E->next()) { - if (E->key() == script->get_default_func()) { - continue; - } - - Function function; - function.node = E->get().function_id; - function.max_stack = 0; - function.flow_stack_size = 0; - function.pass_stack_size = 0; - function.node_count = 0; - - Map<StringName, int> local_var_indices; - - if (function.node < 0) { - VisualScriptLanguage::singleton->debug_break_parse(get_script()->get_path(), 0, "No start node in function: " + String(E->key())); - - ERR_CONTINUE(function.node < 0); + // Setup variables. + { + List<StringName> keys; + script->variables.get_key_list(&keys); + for (const List<StringName>::Element *E = keys.front(); E; E = E->next()) { + variables[E->get()] = script->variables[E->get()].default_value; } + } - { - Ref<VisualScriptFunction> func_node = script->get_node(E->key(), E->get().function_id); - - if (func_node.is_null()) { - VisualScriptLanguage::singleton->debug_break_parse(get_script()->get_path(), 0, "No VisualScriptFunction typed start node in function: " + String(E->key())); + // Setup functions from sequence trees. + { + List<StringName> keys; + script->functions.get_key_list(&keys); + for (const List<StringName>::Element *E = keys.front(); E; E = E->next()) { + const VisualScript::Function vsfn = p_script->functions[E->get()]; + Function function; + function.node = vsfn.func_id; + function.max_stack = 0; + function.flow_stack_size = 0; + function.pass_stack_size = 0; + function.node_count = 0; + + Map<StringName, int> local_var_indices; + + if (function.node < 0) { + VisualScriptLanguage::singleton->debug_break_parse(get_script()->get_path(), 0, "No start node in function: " + String(E->get())); + ERR_CONTINUE(function.node < 0); } - ERR_CONTINUE(!func_node.is_valid()); - - function.argument_count = func_node->get_argument_count(); - function.max_stack += function.argument_count; - function.flow_stack_size = func_node->is_stack_less() ? 0 : func_node->get_stack_size(); - max_input_args = MAX(max_input_args, function.argument_count); - } - - //multiple passes are required to set up this complex thing.. - - //first create the nodes - for (const Map<int, VisualScript::Function::NodeData>::Element *F = E->get().nodes.front(); F; F = F->next()) { - Ref<VisualScriptNode> node = F->get().node; - - VisualScriptNodeInstance *instance = node->instance(this); //create instance - ERR_FAIL_COND(!instance); + { + Ref<VisualScriptFunction> func_node = script->get_node(vsfn.func_id); - instance->base = node.ptr(); + if (func_node.is_null()) { + VisualScriptLanguage::singleton->debug_break_parse(get_script()->get_path(), 0, "No VisualScriptFunction typed start node in function: " + String(E->get())); + } - instance->id = F->key(); - instance->input_port_count = node->get_input_value_port_count(); - instance->input_ports = nullptr; - instance->output_port_count = node->get_output_value_port_count(); - instance->output_ports = nullptr; - instance->sequence_output_count = node->get_output_sequence_port_count(); - instance->sequence_index = function.node_count++; - instance->sequence_outputs = nullptr; - instance->pass_idx = -1; + ERR_CONTINUE(!func_node.is_valid()); - if (instance->input_port_count) { - instance->input_ports = memnew_arr(int, instance->input_port_count); - for (int i = 0; i < instance->input_port_count; i++) { - instance->input_ports[i] = -1; //if not assigned, will become default value - } + function.argument_count = func_node->get_argument_count(); + function.max_stack += function.argument_count; + function.flow_stack_size = func_node->is_stack_less() ? 0 : func_node->get_stack_size(); + max_input_args = MAX(max_input_args, function.argument_count); } - - if (instance->output_port_count) { - instance->output_ports = memnew_arr(int, instance->output_port_count); - for (int i = 0; i < instance->output_port_count; i++) { - instance->output_ports[i] = -1; //if not assigned, will output to trash + // Function nodes graphs. + Set<VisualScript::SequenceConnection> seqconns; + Set<VisualScript::DataConnection> dataconns; + Set<int> node_ids; + node_ids.insert(function.node); + { + List<int> nd_queue; + nd_queue.push_back(function.node); + while (!nd_queue.is_empty()) { + for (const Set<VisualScript::SequenceConnection>::Element *F = script->sequence_connections.front(); F; F = F->next()) { + if (nd_queue.front()->get() == F->get().from_node && !node_ids.has(F->get().to_node)) { + nd_queue.push_back(F->get().to_node); + node_ids.insert(F->get().to_node); + } + if (nd_queue.front()->get() == F->get().from_node && !seqconns.has(F->get())) { + seqconns.insert(F->get()); + } + } + nd_queue.pop_front(); } - } - - if (instance->sequence_output_count) { - instance->sequence_outputs = memnew_arr(VisualScriptNodeInstance *, instance->sequence_output_count); - for (int i = 0; i < instance->sequence_output_count; i++) { - instance->sequence_outputs[i] = nullptr; //if it remains null, flow ends here + HashMap<int, HashMap<int, Pair<int, int>>> dc_lut; // :: to -> to_port -> (from, from_port) + for (const Set<VisualScript::DataConnection>::Element *F = script->data_connections.front(); F; F = F->next()) { + dc_lut[F->get().to_node][F->get().to_port] = Pair<int, int>(F->get().from_node, F->get().from_port); + } + for (const Set<int>::Element *F = node_ids.front(); F; F = F->next()) { + nd_queue.push_back(F->get()); + } + List<int> dc_keys; + while (!nd_queue.is_empty()) { + int ky = nd_queue.front()->get(); + dc_lut[ky].get_key_list(&dc_keys); + for (const List<int>::Element *F = dc_keys.front(); F; F = F->next()) { + VisualScript::DataConnection dc; + dc.from_node = dc_lut[ky][F->get()].first; + dc.from_port = dc_lut[ky][F->get()].second; + dc.to_node = ky; + dc.to_port = F->get(); + dataconns.insert(dc); + nd_queue.push_back(dc.from_node); + node_ids.insert(dc.from_node); + } + dc_keys.clear(); // Necessary as get_key_list does a push_back not a set. + nd_queue.pop_front(); } } - if (Object::cast_to<VisualScriptLocalVar>(node.ptr()) || Object::cast_to<VisualScriptLocalVarSet>(*node)) { - //working memory is shared only for this node, for the same variables - Ref<VisualScriptLocalVar> vslv = node; - - StringName var_name; + //Multiple passes are required to set up this complex thing.. + //First create the nodes. + for (const Set<int>::Element *F = node_ids.front(); F; F = F->next()) { + Ref<VisualScriptNode> node = script->nodes[F->get()].node; + + VisualScriptNodeInstance *instance = node->instance(this); // Create instance. + ERR_FAIL_COND(!instance); + + instance->base = node.ptr(); + + instance->id = F->get(); + instance->input_port_count = node->get_input_value_port_count(); + instance->input_ports = NULL; + instance->output_port_count = node->get_output_value_port_count(); + instance->output_ports = NULL; + instance->sequence_output_count = node->get_output_sequence_port_count(); + instance->sequence_index = function.node_count++; + instance->sequence_outputs = NULL; + instance->pass_idx = -1; + + if (instance->input_port_count) { + instance->input_ports = memnew_arr(int, instance->input_port_count); + for (int i = 0; i < instance->input_port_count; i++) { + instance->input_ports[i] = -1; // If not assigned, will become default value. + } + } - if (Object::cast_to<VisualScriptLocalVar>(*node)) { - var_name = String(Object::cast_to<VisualScriptLocalVar>(*node)->get_var_name()).strip_edges(); - } else { - var_name = String(Object::cast_to<VisualScriptLocalVarSet>(*node)->get_var_name()).strip_edges(); + if (instance->output_port_count) { + instance->output_ports = memnew_arr(int, instance->output_port_count); + for (int i = 0; i < instance->output_port_count; i++) { + instance->output_ports[i] = -1; // If not assigned, will output to trash. + } } - if (!local_var_indices.has(var_name)) { - local_var_indices[var_name] = function.max_stack; - function.max_stack++; + if (instance->sequence_output_count) { + instance->sequence_outputs = memnew_arr(VisualScriptNodeInstance *, instance->sequence_output_count); + for (int i = 0; i < instance->sequence_output_count; i++) { + instance->sequence_outputs[i] = NULL; // If it remains null, flow ends here. + } } - instance->working_mem_idx = local_var_indices[var_name]; + if (Object::cast_to<VisualScriptLocalVar>(node.ptr()) || Object::cast_to<VisualScriptLocalVarSet>(*node)) { + // Working memory is shared only for this node, for the same variables. + Ref<VisualScriptLocalVar> vslv = node; - } else if (instance->get_working_memory_size()) { - instance->working_mem_idx = function.max_stack; - function.max_stack += instance->get_working_memory_size(); - } else { - instance->working_mem_idx = -1; //no working mem - } + StringName var_name; - max_input_args = MAX(max_input_args, instance->input_port_count); - max_output_args = MAX(max_output_args, instance->output_port_count); + if (Object::cast_to<VisualScriptLocalVar>(*node)) + var_name = String(Object::cast_to<VisualScriptLocalVar>(*node)->get_var_name()).strip_edges(); + else + var_name = String(Object::cast_to<VisualScriptLocalVarSet>(*node)->get_var_name()).strip_edges(); - instances[F->key()] = instance; - } + if (!local_var_indices.has(var_name)) { + local_var_indices[var_name] = function.max_stack; + function.max_stack++; + } - function.trash_pos = function.max_stack++; //create pos for trash + instance->working_mem_idx = local_var_indices[var_name]; - //second pass, do data connections + } else if (instance->get_working_memory_size()) { + instance->working_mem_idx = function.max_stack; + function.max_stack += instance->get_working_memory_size(); + } else { + instance->working_mem_idx = -1; //no working mem + } - for (const Set<VisualScript::DataConnection>::Element *F = E->get().data_connections.front(); F; F = F->next()) { - VisualScript::DataConnection dc = F->get(); - ERR_CONTINUE(!instances.has(dc.from_node)); - VisualScriptNodeInstance *from = instances[dc.from_node]; - ERR_CONTINUE(!instances.has(dc.to_node)); - VisualScriptNodeInstance *to = instances[dc.to_node]; - ERR_CONTINUE(dc.from_port >= from->output_port_count); - ERR_CONTINUE(dc.to_port >= to->input_port_count); + max_input_args = MAX(max_input_args, instance->input_port_count); + max_output_args = MAX(max_output_args, instance->output_port_count); - if (from->output_ports[dc.from_port] == -1) { - int stack_pos = function.max_stack++; - from->output_ports[dc.from_port] = stack_pos; + instances[F->get()] = instance; } - if (from->get_sequence_output_count() == 0 && to->dependencies.find(from) == -1) { - //if the node we are reading from has no output sequence, we must call step() before reading from it. - if (from->pass_idx == -1) { - from->pass_idx = function.pass_stack_size; - function.pass_stack_size++; + function.trash_pos = function.max_stack++; // create pos for trash + + // Second pass, do data connections. + for (const Set<VisualScript::DataConnection>::Element *F = dataconns.front(); F; F = F->next()) { + VisualScript::DataConnection dc = F->get(); + ERR_CONTINUE(!instances.has(dc.from_node)); + VisualScriptNodeInstance *from = instances[dc.from_node]; + ERR_CONTINUE(!instances.has(dc.to_node)); + VisualScriptNodeInstance *to = instances[dc.to_node]; + ERR_CONTINUE(dc.from_port >= from->output_port_count); + ERR_CONTINUE(dc.to_port >= to->input_port_count); + + if (from->output_ports[dc.from_port] == -1) { + int stack_pos = function.max_stack++; + from->output_ports[dc.from_port] = stack_pos; } - to->dependencies.push_back(from); - } - to->input_ports[dc.to_port] = from->output_ports[dc.from_port]; //read from wherever the stack is - } - - //third pass, do sequence connections + if (from->get_sequence_output_count() == 0 && to->dependencies.find(from) == -1) { + // If the node we are reading from has no output sequence, we must call step() before reading from it. + if (from->pass_idx == -1) { + from->pass_idx = function.pass_stack_size; + function.pass_stack_size++; + } + to->dependencies.push_back(from); + } - for (const Set<VisualScript::SequenceConnection>::Element *F = E->get().sequence_connections.front(); F; F = F->next()) { - VisualScript::SequenceConnection sc = F->get(); - ERR_CONTINUE(!instances.has(sc.from_node)); - VisualScriptNodeInstance *from = instances[sc.from_node]; - ERR_CONTINUE(!instances.has(sc.to_node)); - VisualScriptNodeInstance *to = instances[sc.to_node]; - ERR_CONTINUE(sc.from_output >= from->sequence_output_count); + to->input_ports[dc.to_port] = from->output_ports[dc.from_port]; // Read from wherever the stack is. + } - from->sequence_outputs[sc.from_output] = to; - } + // Third pass, do sequence connections. + for (const Set<VisualScript::SequenceConnection>::Element *F = seqconns.front(); F; F = F->next()) { + VisualScript::SequenceConnection sc = F->get(); + ERR_CONTINUE(!instances.has(sc.from_node)); + VisualScriptNodeInstance *from = instances[sc.from_node]; + ERR_CONTINUE(!instances.has(sc.to_node)); + VisualScriptNodeInstance *to = instances[sc.to_node]; + ERR_CONTINUE(sc.from_output >= from->sequence_output_count); - //fourth pass: - // 1) unassigned input ports to default values - // 2) connect unassigned output ports to trash + from->sequence_outputs[sc.from_output] = to; + } - for (const Map<int, VisualScript::Function::NodeData>::Element *F = E->get().nodes.front(); F; F = F->next()) { - ERR_CONTINUE(!instances.has(F->key())); + //fourth pass: + // 1) unassigned input ports to default values + // 2) connect unassigned output ports to trash + for (const Set<int>::Element *F = node_ids.front(); F; F = F->next()) { + ERR_CONTINUE(!instances.has(F->get())); - Ref<VisualScriptNode> node = F->get().node; - VisualScriptNodeInstance *instance = instances[F->key()]; + Ref<VisualScriptNode> node = script->nodes[F->get()].node; + VisualScriptNodeInstance *instance = instances[F->get()]; - // connect to default values - for (int i = 0; i < instance->input_port_count; i++) { - if (instance->input_ports[i] == -1) { - //unassigned, connect to default val - instance->input_ports[i] = default_values.size() | VisualScriptNodeInstance::INPUT_DEFAULT_VALUE_BIT; - default_values.push_back(node->get_default_input_value(i)); + // Connect to default values. + for (int i = 0; i < instance->input_port_count; i++) { + if (instance->input_ports[i] == -1) { + // Unassigned, connect to default val. + instance->input_ports[i] = default_values.size() | VisualScriptNodeInstance::INPUT_DEFAULT_VALUE_BIT; + default_values.push_back(node->get_default_input_value(i)); + } } - } - // connect to trash - for (int i = 0; i < instance->output_port_count; i++) { - if (instance->output_ports[i] == -1) { - instance->output_ports[i] = function.trash_pos; //trash is same for all + // Connect to trash. + for (int i = 0; i < instance->output_port_count; i++) { + if (instance->output_ports[i] == -1) { + instance->output_ports[i] = function.trash_pos; //trash is same for all + } } } - } - functions[E->key()] = function; + functions[E->get()] = function; + } } } @@ -2354,7 +2247,7 @@ Variant VisualScriptFunctionState::_signal_callback(const Variant **p_args, int Variant *working_mem = ((Variant *)stack.ptr()) + working_mem_index; - *working_mem = args; //arguments go to working mem. + *working_mem = args; // Arguments go to working mem. Variant ret = instance->_call_internal(function, stack.ptrw(), stack.size(), node, flow_stack_pos, pass, true, r_error); function = StringName(); //invalidate @@ -2388,7 +2281,7 @@ Variant VisualScriptFunctionState::resume(Array p_args) { Variant *working_mem = ((Variant *)stack.ptr()) + working_mem_index; - *working_mem = p_args; //arguments go to working mem. + *working_mem = p_args; // Arguments go to working mem. Variant ret = instance->_call_internal(function, stack.ptrw(), stack.size(), node, flow_stack_pos, pass, true, r_error); function = StringName(); //invalidate @@ -2498,7 +2391,7 @@ void VisualScriptLanguage::add_global_constant(const StringName &p_variable, con /* DEBUGGER FUNCTIONS */ bool VisualScriptLanguage::debug_break_parse(const String &p_file, int p_node, const String &p_error) { - //break because of parse error + // Break because of parse error. if (EngineDebugger::is_active() && Thread::get_caller_id() == Thread::get_main_id()) { _debug_parse_err_node = p_node; @@ -2666,7 +2559,7 @@ void VisualScriptLanguage::debug_get_stack_level_members(int p_level, List<Strin } void VisualScriptLanguage::debug_get_globals(List<String> *p_locals, List<Variant> *p_values, int p_max_subitems, int p_max_depth) { - //no globals are really reachable in gdscript + // No globals are really reachable in gdscript. } String VisualScriptLanguage::debug_parse_stack_level_expression(int p_level, const String &p_expression, int p_max_subitems, int p_max_depth) { @@ -2742,7 +2635,7 @@ VisualScriptLanguage::VisualScriptLanguage() { ProjectSettings::get_singleton()->set_custom_property_info("debug/settings/visual_script/max_call_stack", PropertyInfo(Variant::INT, "debug/settings/visual_script/max_call_stack", PROPERTY_HINT_RANGE, "1024,4096,1,or_greater")); //minimum is 1024 if (EngineDebugger::is_active()) { - //debugging enabled! + // Debugging enabled! _debug_max_call_stack = dmcs; _call_stack = memnew_arr(CallLevel, _debug_max_call_stack + 1); diff --git a/modules/visual_script/visual_script.h b/modules/visual_script/visual_script.h index 3b634a3e13..bdb3c3a16b 100644 --- a/modules/visual_script/visual_script.h +++ b/modules/visual_script/visual_script.h @@ -46,7 +46,7 @@ class VisualScriptNode : public Resource { friend class VisualScript; - Set<VisualScript *> scripts_used; + Ref<VisualScript> script_used; Array default_input_values; bool breakpoint; @@ -83,7 +83,7 @@ public: virtual String get_text() const; virtual String get_category() const = 0; - //used by editor, this is not really saved + // Used by editor, this is not really saved. void set_breakpoint(bool p_breakpoint); bool is_breakpoint() const; @@ -106,9 +106,9 @@ public: class VisualScriptNodeInstance { friend class VisualScriptInstance; - friend class VisualScriptLanguage; //for debugger + friend class VisualScriptLanguage; // For debugger. - enum { //input argument addressing + enum { // Input argument addressing. INPUT_SHIFT = 1 << 24, INPUT_MASK = INPUT_SHIFT - 1, INPUT_DEFAULT_VALUE_BIT = INPUT_SHIFT, // from unassigned input port, using default value (edited by user) @@ -138,13 +138,13 @@ public: enum { STEP_SHIFT = 1 << 24, STEP_MASK = STEP_SHIFT - 1, - STEP_FLAG_PUSH_STACK_BIT = STEP_SHIFT, //push bit to stack - STEP_FLAG_GO_BACK_BIT = STEP_SHIFT << 1, //go back to previous node - STEP_NO_ADVANCE_BIT = STEP_SHIFT << 2, //do not advance past this node - STEP_EXIT_FUNCTION_BIT = STEP_SHIFT << 3, //return from function - STEP_YIELD_BIT = STEP_SHIFT << 4, //yield (will find VisualScriptFunctionState state in first working memory) + STEP_FLAG_PUSH_STACK_BIT = STEP_SHIFT, // push bit to stack + STEP_FLAG_GO_BACK_BIT = STEP_SHIFT << 1, // go back to previous node + STEP_NO_ADVANCE_BIT = STEP_SHIFT << 2, // do not advance past this node + STEP_EXIT_FUNCTION_BIT = STEP_SHIFT << 3, // return from function + STEP_YIELD_BIT = STEP_SHIFT << 4, // yield (will find VisualScriptFunctionState state in first working memory) - FLOW_STACK_PUSHED_BIT = 1 << 30, //in flow stack, means bit was pushed (must go back here if end of sequence) + FLOW_STACK_PUSHED_BIT = 1 << 30, // in flow stack, means bit was pushed (must go back here if end of sequence) FLOW_STACK_MASK = FLOW_STACK_PUSHED_BIT - 1 }; @@ -157,7 +157,7 @@ public: virtual int get_working_memory_size() const { return 0; } - virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) = 0; //do a step, return which sequence port to go out + virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) = 0; // Do a step, return which sequence port to go out. Ref<VisualScriptNode> get_base_node() { return Ref<VisualScriptNode>(base); } @@ -211,34 +211,32 @@ private: Variant::Type type; }; - struct Function { - struct NodeData { - Point2 pos; - Ref<VisualScriptNode> node; - }; - - Map<int, NodeData> nodes; - - Set<SequenceConnection> sequence_connections; + struct NodeData { + Point2 pos; + Ref<VisualScriptNode> node; + }; - Set<DataConnection> data_connections; + HashMap<int, NodeData> nodes; // Can be a sparse map. - int function_id; + Set<SequenceConnection> sequence_connections; + Set<DataConnection> data_connections; - Vector2 scroll; + Vector2 scroll; - Function() { function_id = -1; } + struct Function { + int func_id; + Function() { func_id = -1; } }; struct Variable { PropertyInfo info; Variant default_value; bool _export; - // add getter & setter options here + // Add getter & setter options here. }; - Map<StringName, Function> functions; - Map<StringName, Variable> variables; + HashMap<StringName, Function> functions; + HashMap<StringName, Variable> variables; Map<StringName, Vector<Argument>> custom_signals; Vector<ScriptNetData> rpc_functions; Vector<ScriptNetData> rpc_variables; @@ -249,7 +247,7 @@ private: #ifdef TOOLS_ENABLED Set<PlaceHolderScriptInstance *> placeholders; - //void _update_placeholder(PlaceHolderScriptInstance *p_placeholder); + // void _update_placeholder(PlaceHolderScriptInstance *p_placeholder); virtual void _placeholder_erased(PlaceHolderScriptInstance *p_placeholder) override; void _update_placeholders(); #endif @@ -267,37 +265,38 @@ protected: public: bool inherits_script(const Ref<Script> &p_script) const override; - // TODO: Remove it in future when breaking changes are acceptable - StringName get_default_func() const; - void add_function(const StringName &p_name); + void set_scroll(const Vector2 &p_scroll); + Vector2 get_scroll() const; + + void add_function(const StringName &p_name, int p_func_node_id); bool has_function(const StringName &p_name) const; void remove_function(const StringName &p_name); void rename_function(const StringName &p_name, const StringName &p_new_name); - void set_function_scroll(const StringName &p_name, const Vector2 &p_scroll); - Vector2 get_function_scroll(const StringName &p_name) const; void get_function_list(List<StringName> *r_functions) const; int get_function_node_id(const StringName &p_name) const; void set_tool_enabled(bool p_enabled); - void add_node(const StringName &p_func, int p_id, const Ref<VisualScriptNode> &p_node, const Point2 &p_pos = Point2()); - void remove_node(const StringName &p_func, int p_id); - bool has_node(const StringName &p_func, int p_id) const; - Ref<VisualScriptNode> get_node(const StringName &p_func, int p_id) const; - void set_node_position(const StringName &p_func, int p_id, const Point2 &p_pos); - Point2 get_node_position(const StringName &p_func, int p_id) const; - void get_node_list(const StringName &p_func, List<int> *r_nodes) const; - - void sequence_connect(const StringName &p_func, int p_from_node, int p_from_output, int p_to_node); - void sequence_disconnect(const StringName &p_func, int p_from_node, int p_from_output, int p_to_node); - bool has_sequence_connection(const StringName &p_func, int p_from_node, int p_from_output, int p_to_node) const; - void get_sequence_connection_list(const StringName &p_func, List<SequenceConnection> *r_connection) const; - - void data_connect(const StringName &p_func, int p_from_node, int p_from_port, int p_to_node, int p_to_port); - void data_disconnect(const StringName &p_func, int p_from_node, int p_from_port, int p_to_node, int p_to_port); - bool has_data_connection(const StringName &p_func, int p_from_node, int p_from_port, int p_to_node, int p_to_port) const; - void get_data_connection_list(const StringName &p_func, List<DataConnection> *r_connection) const; - bool is_input_value_port_connected(const StringName &p_func, int p_node, int p_port) const; - bool get_input_value_port_connection_source(const StringName &p_func, int p_node, int p_port, int *r_node, int *r_port) const; + void add_node(int p_id, const Ref<VisualScriptNode> &p_node, const Point2 &p_pos = Point2()); + void remove_node(int p_id); + bool has_node(int p_id) const; + Ref<VisualScriptNode> get_node(int p_id) const; + void set_node_position(int p_id, const Point2 &p_pos); + Point2 get_node_position(int p_id) const; + void get_node_list(List<int> *r_nodes) const; + + void sequence_connect(int p_from_node, int p_from_output, int p_to_node); + void sequence_disconnect(int p_from_node, int p_from_output, int p_to_node); + bool has_sequence_connection(int p_from_node, int p_from_output, int p_to_node) const; + void get_sequence_connection_list(List<SequenceConnection> *r_connection) const; + Set<int> get_output_sequence_ports_connected(int from_node); + + void data_connect(int p_from_node, int p_from_port, int p_to_node, int p_to_port); + void data_disconnect(int p_from_node, int p_from_port, int p_to_node, int p_to_port); + bool has_data_connection(int p_from_node, int p_from_port, int p_to_node, int p_to_port) const; + void get_data_connection_list(List<DataConnection> *r_connection) const; + + bool is_input_value_port_connected(int p_node, int p_port) const; + bool get_input_value_port_connection_source(int p_node, int p_port, int *r_node, int *r_port) const; void add_variable(const StringName &p_name, const Variant &p_default_value = Variant(), bool p_export = false); bool has_variable(const StringName &p_name) const; @@ -392,7 +391,7 @@ class VisualScriptInstance : public ScriptInstance { Object *owner; Ref<VisualScript> script; - Map<StringName, Variant> variables; //using variable path, not script + Map<StringName, Variant> variables; // Using variable path, not script. Map<int, VisualScriptNodeInstance *> instances; struct Function { @@ -415,9 +414,8 @@ class VisualScriptInstance : public ScriptInstance { void _dependency_step(VisualScriptNodeInstance *node, int p_pass, int *pass_stack, const Variant **input_args, Variant **output_args, Variant *variant_stack, Callable::CallError &r_error, String &error_str, VisualScriptNodeInstance **r_error_node); Variant _call_internal(const StringName &p_method, void *p_stack, int p_stack_size, VisualScriptNodeInstance *p_node, int p_flow_stack_pos, int p_pass, bool p_resuming_yield, Callable::CallError &r_error); - //Map<StringName,Function> functions; - friend class VisualScriptFunctionState; //for yield - friend class VisualScriptLanguage; //for debugger + friend class VisualScriptFunctionState; // For yield. + friend class VisualScriptLanguage; // For debugger. public: virtual bool set(const StringName &p_name, const Variant &p_value); virtual bool get(const StringName &p_name, Variant &r_ret) const; @@ -538,7 +536,7 @@ public: _FORCE_INLINE_ void enter_function(VisualScriptInstance *p_instance, const StringName *p_function, Variant *p_stack, Variant **p_work_mem, int *current_id) { if (Thread::get_main_id() != Thread::get_caller_id()) { - return; //no support for other threads than main for now + return; // No support for other threads than main for now. } if (EngineDebugger::get_script_debugger()->get_lines_left() > 0 && EngineDebugger::get_script_debugger()->get_depth() >= 0) { @@ -546,7 +544,7 @@ public: } if (_debug_call_stack_pos >= _debug_max_call_stack) { - //stack overflow + // Stack overflow. _debug_error = "Stack Overflow (Stack Size: " + itos(_debug_max_call_stack) + ")"; EngineDebugger::get_script_debugger()->debug(this); return; @@ -562,7 +560,7 @@ public: _FORCE_INLINE_ void exit_function() { if (Thread::get_main_id() != Thread::get_caller_id()) { - return; //no support for other threads than main for now + return; // No support for other threads than main for now. } if (EngineDebugger::get_script_debugger()->get_lines_left() > 0 && EngineDebugger::get_script_debugger()->get_depth() >= 0) { @@ -640,7 +638,7 @@ public: ~VisualScriptLanguage(); }; -//aid for registering +// Aid for registering. template <class T> static Ref<VisualScriptNode> create_node_generic(const String &p_name) { Ref<T> node; diff --git a/modules/visual_script/visual_script_editor.cpp b/modules/visual_script/visual_script_editor.cpp index e46c4638b1..3fbf19a48d 100644 --- a/modules/visual_script/visual_script_editor.cpp +++ b/modules/visual_script/visual_script_editor.cpp @@ -199,7 +199,7 @@ protected: emit_signal("changed"); } void _var_value_changed() { - _change_notify("value"); //so the whole tree is not redrawn, makes editing smoother in general + _change_notify("value"); // So the whole tree is not redrawn, makes editing smoother in general. emit_signal("changed"); } @@ -309,7 +309,7 @@ protected: } p_list->push_back(PropertyInfo(Variant::INT, "type", PROPERTY_HINT_ENUM, argt)); p_list->push_back(PropertyInfo(script->get_variable_info(var).type, "value", script->get_variable_info(var).hint, script->get_variable_info(var).hint_string, PROPERTY_USAGE_DEFAULT)); - // Update this when PropertyHint changes + // Update this when PropertyHint changes. p_list->push_back(PropertyInfo(Variant::INT, "hint", PROPERTY_HINT_ENUM, "None,Range,ExpRange,Enum,ExpEasing,Length,SpriteFrame,KeyAccel,Flags,Layers2dRender,Layers2dPhysics,Layer3dRender,Layer3dPhysics,File,Dir,GlobalFile,GlobalDir,ResourceType,MultilineText,PlaceholderText,ColorNoAlpha,ImageCompressLossy,ImageCompressLossLess,ObjectId,String,NodePathToEditedNode,MethodOfVariantType,MethodOfBaseType,MethodOfInstance,MethodOfScript,PropertyOfVariantType,PropertyOfBaseType,PropertyOfInstance,PropertyOfScript,ObjectTooBig,NodePathValidTypes")); p_list->push_back(PropertyInfo(Variant::STRING, "hint_string")); p_list->push_back(PropertyInfo(Variant::BOOL, "export")); @@ -546,39 +546,29 @@ static Color _color_from_type(Variant::Type p_type, bool dark_theme = true) { void VisualScriptEditor::_update_graph_connections() { graph->clear_connections(); - List<StringName> funcs; - script->get_function_list(&funcs); + List<VisualScript::SequenceConnection> sequence_conns; + script->get_sequence_connection_list(&sequence_conns); - if (funcs.size() <= 0) { - updating_graph = false; - return; + for (List<VisualScript::SequenceConnection>::Element *E = sequence_conns.front(); E; E = E->next()) { + graph->connect_node(itos(E->get().from_node), E->get().from_output, itos(E->get().to_node), 0); } - for (List<StringName>::Element *F = funcs.front(); F; F = F->next()) { - List<VisualScript::SequenceConnection> sequence_conns; - script->get_sequence_connection_list(F->get(), &sequence_conns); - - for (List<VisualScript::SequenceConnection>::Element *E = sequence_conns.front(); E; E = E->next()) { - graph->connect_node(itos(E->get().from_node), E->get().from_output, itos(E->get().to_node), 0); - } - - List<VisualScript::DataConnection> data_conns; - script->get_data_connection_list(F->get(), &data_conns); + List<VisualScript::DataConnection> data_conns; + script->get_data_connection_list(&data_conns); - for (List<VisualScript::DataConnection>::Element *E = data_conns.front(); E; E = E->next()) { - VisualScript::DataConnection dc = E->get(); + for (List<VisualScript::DataConnection>::Element *E = data_conns.front(); E; E = E->next()) { + VisualScript::DataConnection dc = E->get(); - Ref<VisualScriptNode> from_node = script->get_node(F->get(), E->get().from_node); - Ref<VisualScriptNode> to_node = script->get_node(F->get(), E->get().to_node); + Ref<VisualScriptNode> from_node = script->get_node(E->get().from_node); + Ref<VisualScriptNode> to_node = script->get_node(E->get().to_node); - if (to_node->has_input_sequence_port()) { - dc.to_port++; - } + if (to_node->has_input_sequence_port()) { + dc.to_port++; + } - dc.from_port += from_node->get_output_sequence_port_count(); + dc.from_port += from_node->get_output_sequence_port_count(); - graph->connect_node(itos(E->get().from_node), dc.from_port, itos(E->get().to_node), dc.to_port); - } + graph->connect_node(itos(E->get().from_node), dc.from_port, itos(E->get().to_node), dc.to_port); } } @@ -605,17 +595,6 @@ void VisualScriptEditor::_update_graph(int p_only_id) { } } } - - List<StringName> funcs; - script->get_function_list(&funcs); - - if (funcs.size() <= 0) { - graph->hide(); - select_func_text->show(); - updating_graph = false; - return; - } - graph->show(); select_func_text->hide(); @@ -655,348 +634,347 @@ void VisualScriptEditor::_update_graph(int p_only_id) { }; Ref<Texture2D> seq_port = Control::get_theme_icon("VisualShaderPort", "EditorIcons"); + List<int> node_ids; + script->get_node_list(&node_ids); - for (List<StringName>::Element *F = funcs.front(); F; F = F->next()) { // loop through all the functions - - List<int> ids; - script->get_node_list(F->get(), &ids); - StringName editor_icons = "EditorIcons"; + List<int> ids; + script->get_node_list(&ids); + StringName editor_icons = "EditorIcons"; - for (List<int>::Element *E = ids.front(); E; E = E->next()) { - if (p_only_id >= 0 && p_only_id != E->get()) { - continue; - } + for (List<int>::Element *E = ids.front(); E; E = E->next()) { + if (p_only_id >= 0 && p_only_id != E->get()) { + continue; + } - Ref<VisualScriptNode> node = script->get_node(F->get(), E->get()); - Vector2 pos = script->get_node_position(F->get(), E->get()); + Ref<VisualScriptNode> node = script->get_node(E->get()); + Vector2 pos = script->get_node_position(E->get()); - GraphNode *gnode = memnew(GraphNode); - gnode->set_title(node->get_caption()); - gnode->set_position_offset(pos * EDSCALE); - if (error_line == E->get()) { - gnode->set_overlay(GraphNode::OVERLAY_POSITION); - } else if (node->is_breakpoint()) { - gnode->set_overlay(GraphNode::OVERLAY_BREAKPOINT); - } + GraphNode *gnode = memnew(GraphNode); + gnode->set_title(node->get_caption()); + gnode->set_position_offset(pos * EDSCALE); + if (error_line == E->get()) { + gnode->set_overlay(GraphNode::OVERLAY_POSITION); + } else if (node->is_breakpoint()) { + gnode->set_overlay(GraphNode::OVERLAY_BREAKPOINT); + } - gnode->set_meta("__vnode", node); - gnode->set_name(itos(E->get())); - gnode->connect("dragged", callable_mp(this, &VisualScriptEditor::_node_moved), varray(E->get())); - gnode->connect("close_request", callable_mp(this, &VisualScriptEditor::_remove_node), varray(E->get()), CONNECT_DEFERRED); + gnode->set_meta("__vnode", node); + gnode->set_name(itos(E->get())); + gnode->connect("dragged", callable_mp(this, &VisualScriptEditor::_node_moved), varray(E->get())); + gnode->connect("close_request", callable_mp(this, &VisualScriptEditor::_remove_node), varray(E->get()), CONNECT_DEFERRED); - if (E->get() != script->get_function_node_id(F->get())) { - //function can't be erased + { + Ref<VisualScriptFunction> v = node; + if (!v.is_valid()) { gnode->set_show_close_button(true); } + } - bool has_gnode_text = false; + bool has_gnode_text = false; - Ref<VisualScriptLists> nd_list = node; - bool is_vslist = nd_list.is_valid(); - if (is_vslist) { - HBoxContainer *hbnc = memnew(HBoxContainer); + Ref<VisualScriptLists> nd_list = node; + bool is_vslist = nd_list.is_valid(); + if (is_vslist) { + HBoxContainer *hbnc = memnew(HBoxContainer); + if (nd_list->is_input_port_editable()) { + has_gnode_text = true; + Button *btn = memnew(Button); + btn->set_text(TTR("Add Input Port")); + hbnc->add_child(btn); + btn->connect("pressed", callable_mp(this, &VisualScriptEditor::_add_input_port), varray(E->get()), CONNECT_DEFERRED); + } + if (nd_list->is_output_port_editable()) { if (nd_list->is_input_port_editable()) { - has_gnode_text = true; - Button *btn = memnew(Button); - btn->set_text(TTR("Add Input Port")); - hbnc->add_child(btn); - btn->connect("pressed", callable_mp(this, &VisualScriptEditor::_add_input_port), varray(E->get()), CONNECT_DEFERRED); - } - if (nd_list->is_output_port_editable()) { - if (nd_list->is_input_port_editable()) { - hbnc->add_spacer(); - } - has_gnode_text = true; - Button *btn = memnew(Button); - btn->set_text(TTR("Add Output Port")); - hbnc->add_child(btn); - btn->connect("pressed", callable_mp(this, &VisualScriptEditor::_add_output_port), varray(E->get()), CONNECT_DEFERRED); + hbnc->add_spacer(); } - gnode->add_child(hbnc); - } else if (Object::cast_to<VisualScriptExpression>(node.ptr())) { has_gnode_text = true; - LineEdit *line_edit = memnew(LineEdit); - line_edit->set_text(node->get_text()); - line_edit->set_expand_to_text_length(true); - line_edit->add_theme_font_override("font", get_theme_font("source", "EditorFonts")); - line_edit->add_theme_font_size_override("font_size", get_theme_font_size("source_size", "EditorFonts")); - gnode->add_child(line_edit); - line_edit->connect("text_changed", callable_mp(this, &VisualScriptEditor::_expression_text_changed), varray(E->get())); - } else { - String text = node->get_text(); - if (!text.is_empty()) { - has_gnode_text = true; - Label *label = memnew(Label); - label->set_text(text); - gnode->add_child(label); - } + Button *btn = memnew(Button); + btn->set_text(TTR("Add Output Port")); + hbnc->add_child(btn); + btn->connect("pressed", callable_mp(this, &VisualScriptEditor::_add_output_port), varray(E->get()), CONNECT_DEFERRED); } - - if (Object::cast_to<VisualScriptComment>(node.ptr())) { - Ref<VisualScriptComment> vsc = node; - gnode->set_comment(true); - gnode->set_resizable(true); - gnode->set_custom_minimum_size(vsc->get_size() * EDSCALE); - gnode->connect("resize_request", callable_mp(this, &VisualScriptEditor::_comment_node_resized), varray(E->get())); + gnode->add_child(hbnc); + } else if (Object::cast_to<VisualScriptExpression>(node.ptr())) { + has_gnode_text = true; + LineEdit *line_edit = memnew(LineEdit); + line_edit->set_text(node->get_text()); + line_edit->set_expand_to_text_length(true); + line_edit->add_theme_font_override("font", get_theme_font("source", "EditorFonts")); + gnode->add_child(line_edit); + line_edit->connect("text_changed", callable_mp(this, &VisualScriptEditor::_expression_text_changed), varray(E->get())); + } else { + String text = node->get_text(); + if (!text.is_empty()) { + has_gnode_text = true; + Label *label = memnew(Label); + label->set_text(text); + gnode->add_child(label); } + } - if (node_styles.has(node->get_category())) { - Ref<StyleBoxFlat> sbf = node_styles[node->get_category()]; - if (gnode->is_comment()) { - sbf = EditorNode::get_singleton()->get_theme_base()->get_theme()->get_stylebox("comment", "GraphNode"); - } + if (Object::cast_to<VisualScriptComment>(node.ptr())) { + Ref<VisualScriptComment> vsc = node; + gnode->set_comment(true); + gnode->set_resizable(true); + gnode->set_custom_minimum_size(vsc->get_size() * EDSCALE); + gnode->connect("resize_request", callable_mp(this, &VisualScriptEditor::_comment_node_resized), varray(E->get())); + } - Color c = sbf->get_border_color(); - Color ic = c; - c.a = 1; - if (EditorSettings::get_singleton()->get("interface/theme/use_graph_node_headers")) { - Color mono_color; - if (((c.r + c.g + c.b) / 3) < 0.7) { - mono_color = Color(1.0, 1.0, 1.0); - ic = Color(0.0, 0.0, 0.0, 0.7); - } else { - mono_color = Color(0.0, 0.0, 0.0); - ic = Color(1.0, 1.0, 1.0, 0.7); - } - mono_color.a = 0.85; - c = mono_color; + if (node_styles.has(node->get_category())) { + Ref<StyleBoxFlat> sbf = node_styles[node->get_category()]; + if (gnode->is_comment()) { + sbf = EditorNode::get_singleton()->get_theme_base()->get_theme()->get_stylebox("comment", "GraphNode"); + } + + Color c = sbf->get_border_color(); + Color ic = c; + c.a = 1; + if (EditorSettings::get_singleton()->get("interface/theme/use_graph_node_headers")) { + Color mono_color; + if (((c.r + c.g + c.b) / 3) < 0.7) { + mono_color = Color(1.0, 1.0, 1.0); + ic = Color(0.0, 0.0, 0.0, 0.7); + } else { + mono_color = Color(0.0, 0.0, 0.0); + ic = Color(1.0, 1.0, 1.0, 0.7); } - gnode->add_theme_color_override("title_color", c); - c.a = 0.7; - gnode->add_theme_color_override("close_color", c); - gnode->add_theme_color_override("resizer_color", ic); - gnode->add_theme_style_override("frame", sbf); + mono_color.a = 0.85; + c = mono_color; } + gnode->add_theme_color_override("title_color", c); + c.a = 0.7; + gnode->add_theme_color_override("close_color", c); + gnode->add_theme_color_override("resizer_color", ic); + gnode->add_theme_style_override("frame", sbf); + } - const Color mono_color = get_theme_color("mono_color", "Editor"); + const Color mono_color = get_theme_color("mono_color", "Editor"); - int slot_idx = 0; + int slot_idx = 0; - bool single_seq_output = node->get_output_sequence_port_count() == 1 && node->get_output_sequence_port_text(0) == String(); - if ((node->has_input_sequence_port() || single_seq_output) || has_gnode_text) { - // IF has_gnode_text is true BUT we have no sequence ports to draw (in here), - // we still draw the disabled default ones to shift up the slots by one, - // so the slots DON'T start with the content text. + bool single_seq_output = node->get_output_sequence_port_count() == 1 && node->get_output_sequence_port_text(0) == String(); + if ((node->has_input_sequence_port() || single_seq_output) || has_gnode_text) { + // IF has_gnode_text is true BUT we have no sequence ports to draw (in here), + // we still draw the disabled default ones to shift up the slots by one, + // so the slots DON'T start with the content text. - // IF has_gnode_text is false, but we DO want to draw default sequence ports, - // we draw a dummy text to take up the position of the sequence nodes, so all the other ports are still aligned correctly. - if (!has_gnode_text) { - Label *dummy = memnew(Label); - dummy->set_text(" "); - gnode->add_child(dummy); - } - gnode->set_slot(0, node->has_input_sequence_port(), TYPE_SEQUENCE, mono_color, single_seq_output, TYPE_SEQUENCE, mono_color, seq_port, seq_port); - slot_idx++; + // IF has_gnode_text is false, but we DO want to draw default sequence ports, + // we draw a dummy text to take up the position of the sequence nodes, so all the other ports are still aligned correctly. + if (!has_gnode_text) { + Label *dummy = memnew(Label); + dummy->set_text(" "); + gnode->add_child(dummy); } + gnode->set_slot(0, node->has_input_sequence_port(), TYPE_SEQUENCE, mono_color, single_seq_output, TYPE_SEQUENCE, mono_color, seq_port, seq_port); + slot_idx++; + } - int mixed_seq_ports = 0; + int mixed_seq_ports = 0; - if (!single_seq_output) { - if (node->has_mixed_input_and_sequence_ports()) { - mixed_seq_ports = node->get_output_sequence_port_count(); - } else { - for (int i = 0; i < node->get_output_sequence_port_count(); i++) { - Label *text2 = memnew(Label); - text2->set_text(node->get_output_sequence_port_text(i)); - text2->set_align(Label::ALIGN_RIGHT); - gnode->add_child(text2); - gnode->set_slot(slot_idx, false, 0, Color(), true, TYPE_SEQUENCE, mono_color, seq_port, seq_port); - slot_idx++; - } + if (!single_seq_output) { + if (node->has_mixed_input_and_sequence_ports()) { + mixed_seq_ports = node->get_output_sequence_port_count(); + } else { + for (int i = 0; i < node->get_output_sequence_port_count(); i++) { + Label *text2 = memnew(Label); + text2->set_text(node->get_output_sequence_port_text(i)); + text2->set_align(Label::ALIGN_RIGHT); + gnode->add_child(text2); + gnode->set_slot(slot_idx, false, 0, Color(), true, TYPE_SEQUENCE, mono_color, seq_port, seq_port); + slot_idx++; } } + } - for (int i = 0; i < MAX(node->get_output_value_port_count(), MAX(mixed_seq_ports, node->get_input_value_port_count())); i++) { - bool left_ok = false; - Variant::Type left_type = Variant::NIL; - String left_name; + for (int i = 0; i < MAX(node->get_output_value_port_count(), MAX(mixed_seq_ports, node->get_input_value_port_count())); i++) { + bool left_ok = false; + Variant::Type left_type = Variant::NIL; + String left_name; - if (i < node->get_input_value_port_count()) { - PropertyInfo pi = node->get_input_value_port_info(i); - left_ok = true; - left_type = pi.type; - left_name = pi.name; - } + if (i < node->get_input_value_port_count()) { + PropertyInfo pi = node->get_input_value_port_info(i); + left_ok = true; + left_type = pi.type; + left_name = pi.name; + } - bool right_ok = false; - Variant::Type right_type = Variant::NIL; - String right_name; + bool right_ok = false; + Variant::Type right_type = Variant::NIL; + String right_name; - if (i >= mixed_seq_ports && i < node->get_output_value_port_count() + mixed_seq_ports) { - PropertyInfo pi = node->get_output_value_port_info(i - mixed_seq_ports); - right_ok = true; - right_type = pi.type; - right_name = pi.name; + if (i >= mixed_seq_ports && i < node->get_output_value_port_count() + mixed_seq_ports) { + PropertyInfo pi = node->get_output_value_port_info(i - mixed_seq_ports); + right_ok = true; + right_type = pi.type; + right_name = pi.name; + } + VBoxContainer *vbc = memnew(VBoxContainer); + HBoxContainer *hbc = memnew(HBoxContainer); + HBoxContainer *hbc2 = memnew(HBoxContainer); + vbc->add_child(hbc); + vbc->add_child(hbc2); + if (left_ok) { + Ref<Texture2D> t; + if (left_type >= 0 && left_type < Variant::VARIANT_MAX) { + t = type_icons[left_type]; + } + if (t.is_valid()) { + TextureRect *tf = memnew(TextureRect); + tf->set_texture(t); + tf->set_stretch_mode(TextureRect::STRETCH_KEEP_CENTERED); + hbc->add_child(tf); } - VBoxContainer *vbc = memnew(VBoxContainer); - HBoxContainer *hbc = memnew(HBoxContainer); - HBoxContainer *hbc2 = memnew(HBoxContainer); - vbc->add_child(hbc); - vbc->add_child(hbc2); - if (left_ok) { - Ref<Texture2D> t; - if (left_type >= 0 && left_type < Variant::VARIANT_MAX) { - t = type_icons[left_type]; - } - if (t.is_valid()) { - TextureRect *tf = memnew(TextureRect); - tf->set_texture(t); - tf->set_stretch_mode(TextureRect::STRETCH_KEEP_CENTERED); - hbc->add_child(tf); - } - - if (is_vslist) { - if (nd_list->is_input_port_name_editable()) { - LineEdit *name_box = memnew(LineEdit); - hbc->add_child(name_box); - name_box->set_custom_minimum_size(Size2(60 * EDSCALE, 0)); - name_box->set_text(left_name); - name_box->set_expand_to_text_length(true); - name_box->connect("resized", callable_mp(this, &VisualScriptEditor::_update_node_size), varray(E->get())); - name_box->connect("focus_exited", callable_mp(this, &VisualScriptEditor::_port_name_focus_out), varray(name_box, E->get(), i, true)); - } else { - hbc->add_child(memnew(Label(left_name))); - } - - if (nd_list->is_input_port_type_editable()) { - OptionButton *opbtn = memnew(OptionButton); - for (int j = Variant::NIL; j < Variant::VARIANT_MAX; j++) { - opbtn->add_item(Variant::get_type_name(Variant::Type(j))); - } - opbtn->select(left_type); - opbtn->set_custom_minimum_size(Size2(100 * EDSCALE, 0)); - hbc->add_child(opbtn); - opbtn->connect("item_selected", callable_mp(this, &VisualScriptEditor::_change_port_type), varray(E->get(), i, true), CONNECT_DEFERRED); - } - Button *rmbtn = memnew(Button); - rmbtn->set_icon(EditorNode::get_singleton()->get_gui_base()->get_theme_icon("Remove", "EditorIcons")); - hbc->add_child(rmbtn); - rmbtn->connect("pressed", callable_mp(this, &VisualScriptEditor::_remove_input_port), varray(E->get(), i), CONNECT_DEFERRED); + if (is_vslist) { + if (nd_list->is_input_port_name_editable()) { + LineEdit *name_box = memnew(LineEdit); + hbc->add_child(name_box); + name_box->set_custom_minimum_size(Size2(60 * EDSCALE, 0)); + name_box->set_text(left_name); + name_box->set_expand_to_text_length(true); + name_box->connect("resized", callable_mp(this, &VisualScriptEditor::_update_node_size), varray(E->get())); + name_box->connect("focus_exited", callable_mp(this, &VisualScriptEditor::_port_name_focus_out), varray(name_box, E->get(), i, true)); } else { hbc->add_child(memnew(Label(left_name))); } - if (left_type != Variant::NIL && !script->is_input_value_port_connected(F->get(), E->get(), i)) { - PropertyInfo pi = node->get_input_value_port_info(i); - Button *button = memnew(Button); - Variant value = node->get_default_input_value(i); - if (value.get_type() != left_type) { - //different type? for now convert - //not the same, reconvert - Callable::CallError ce; - const Variant *existingp = &value; - Variant::construct(left_type, value, &existingp, 1, ce); + if (nd_list->is_input_port_type_editable()) { + OptionButton *opbtn = memnew(OptionButton); + for (int j = Variant::NIL; j < Variant::VARIANT_MAX; j++) { + opbtn->add_item(Variant::get_type_name(Variant::Type(j))); } - - if (left_type == Variant::COLOR) { - button->set_custom_minimum_size(Size2(30, 0) * EDSCALE); - button->connect("draw", callable_mp(this, &VisualScriptEditor::_draw_color_over_button), varray(button, value)); - } else if (left_type == Variant::OBJECT && Ref<Resource>(value).is_valid()) { - Ref<Resource> res = value; - Array arr; - arr.push_back(button->get_instance_id()); - arr.push_back(String(value)); - EditorResourcePreview::get_singleton()->queue_edited_resource_preview(res, this, "_button_resource_previewed", arr); - - } else if (pi.type == Variant::INT && pi.hint == PROPERTY_HINT_ENUM) { - button->set_text(pi.hint_string.get_slice(",", value)); - } else { - button->set_text(value); - } - button->connect("pressed", callable_mp(this, &VisualScriptEditor::_default_value_edited), varray(button, E->get(), i)); - hbc2->add_child(button); + opbtn->select(left_type); + opbtn->set_custom_minimum_size(Size2(100 * EDSCALE, 0)); + hbc->add_child(opbtn); + opbtn->connect("item_selected", callable_mp(this, &VisualScriptEditor::_change_port_type), varray(E->get(), i, true), CONNECT_DEFERRED); } + + Button *rmbtn = memnew(Button); + rmbtn->set_icon(EditorNode::get_singleton()->get_gui_base()->get_theme_icon("Remove", "EditorIcons")); + hbc->add_child(rmbtn); + rmbtn->connect("pressed", callable_mp(this, &VisualScriptEditor::_remove_input_port), varray(E->get(), i), CONNECT_DEFERRED); } else { - Control *c = memnew(Control); - c->set_custom_minimum_size(Size2(10, 0) * EDSCALE); - hbc->add_child(c); + hbc->add_child(memnew(Label(left_name))); } - hbc->add_spacer(); - hbc2->add_spacer(); + if (left_type != Variant::NIL && !script->is_input_value_port_connected(E->get(), i)) { + PropertyInfo pi = node->get_input_value_port_info(i); + Button *button = memnew(Button); + Variant value = node->get_default_input_value(i); + if (value.get_type() != left_type) { + //different type? for now convert + //not the same, reconvert + Callable::CallError ce; + const Variant *existingp = &value; + Variant::construct(left_type, value, &existingp, 1, ce); + } - if (i < mixed_seq_ports) { - Label *text2 = memnew(Label); - text2->set_text(node->get_output_sequence_port_text(i)); - text2->set_align(Label::ALIGN_RIGHT); - hbc->add_child(text2); + if (left_type == Variant::COLOR) { + button->set_custom_minimum_size(Size2(30, 0) * EDSCALE); + button->connect("draw", callable_mp(this, &VisualScriptEditor::_draw_color_over_button), varray(button, value)); + } else if (left_type == Variant::OBJECT && Ref<Resource>(value).is_valid()) { + Ref<Resource> res = value; + Array arr; + arr.push_back(button->get_instance_id()); + arr.push_back(String(value)); + EditorResourcePreview::get_singleton()->queue_edited_resource_preview(res, this, "_button_resource_previewed", arr); + + } else if (pi.type == Variant::INT && pi.hint == PROPERTY_HINT_ENUM) { + button->set_text(pi.hint_string.get_slice(",", value)); + } else { + button->set_text(value); + } + button->connect("pressed", callable_mp(this, &VisualScriptEditor::_default_value_edited), varray(button, E->get(), i)); + hbc2->add_child(button); } + } else { + Control *c = memnew(Control); + c->set_custom_minimum_size(Size2(10, 0) * EDSCALE); + hbc->add_child(c); + } - if (right_ok) { - if (is_vslist) { - Button *rmbtn = memnew(Button); - rmbtn->set_icon(EditorNode::get_singleton()->get_gui_base()->get_theme_icon("Remove", "EditorIcons")); - hbc->add_child(rmbtn); - rmbtn->connect("pressed", callable_mp(this, &VisualScriptEditor::_remove_output_port), varray(E->get(), i), CONNECT_DEFERRED); - - if (nd_list->is_output_port_type_editable()) { - OptionButton *opbtn = memnew(OptionButton); - for (int j = Variant::NIL; j < Variant::VARIANT_MAX; j++) { - opbtn->add_item(Variant::get_type_name(Variant::Type(j))); - } - opbtn->select(right_type); - opbtn->set_custom_minimum_size(Size2(100 * EDSCALE, 0)); - hbc->add_child(opbtn); - opbtn->connect("item_selected", callable_mp(this, &VisualScriptEditor::_change_port_type), varray(E->get(), i, false), CONNECT_DEFERRED); - } + hbc->add_spacer(); + hbc2->add_spacer(); + + if (i < mixed_seq_ports) { + Label *text2 = memnew(Label); + text2->set_text(node->get_output_sequence_port_text(i)); + text2->set_align(Label::ALIGN_RIGHT); + hbc->add_child(text2); + } - if (nd_list->is_output_port_name_editable()) { - LineEdit *name_box = memnew(LineEdit); - hbc->add_child(name_box); - name_box->set_custom_minimum_size(Size2(60 * EDSCALE, 0)); - name_box->set_text(right_name); - name_box->set_expand_to_text_length(true); - name_box->connect("resized", callable_mp(this, &VisualScriptEditor::_update_node_size), varray(E->get())); - name_box->connect("focus_exited", callable_mp(this, &VisualScriptEditor::_port_name_focus_out), varray(name_box, E->get(), i, false)); - } else { - hbc->add_child(memnew(Label(right_name))); + if (right_ok) { + if (is_vslist) { + Button *rmbtn = memnew(Button); + rmbtn->set_icon(EditorNode::get_singleton()->get_gui_base()->get_theme_icon("Remove", "EditorIcons")); + hbc->add_child(rmbtn); + rmbtn->connect("pressed", callable_mp(this, &VisualScriptEditor::_remove_output_port), varray(E->get(), i), CONNECT_DEFERRED); + + if (nd_list->is_output_port_type_editable()) { + OptionButton *opbtn = memnew(OptionButton); + for (int j = Variant::NIL; j < Variant::VARIANT_MAX; j++) { + opbtn->add_item(Variant::get_type_name(Variant::Type(j))); } - } else { - hbc->add_child(memnew(Label(right_name))); + opbtn->select(right_type); + opbtn->set_custom_minimum_size(Size2(100 * EDSCALE, 0)); + hbc->add_child(opbtn); + opbtn->connect("item_selected", callable_mp(this, &VisualScriptEditor::_change_port_type), varray(E->get(), i, false), CONNECT_DEFERRED); } - Ref<Texture2D> t; - if (right_type >= 0 && right_type < Variant::VARIANT_MAX) { - t = type_icons[right_type]; - } - if (t.is_valid()) { - TextureRect *tf = memnew(TextureRect); - tf->set_texture(t); - tf->set_stretch_mode(TextureRect::STRETCH_KEEP_CENTERED); - hbc->add_child(tf); + if (nd_list->is_output_port_name_editable()) { + LineEdit *name_box = memnew(LineEdit); + hbc->add_child(name_box); + name_box->set_custom_minimum_size(Size2(60 * EDSCALE, 0)); + name_box->set_text(right_name); + name_box->set_expand_to_text_length(true); + name_box->connect("resized", callable_mp(this, &VisualScriptEditor::_update_node_size), varray(E->get())); + name_box->connect("focus_exited", callable_mp(this, &VisualScriptEditor::_port_name_focus_out), varray(name_box, E->get(), i, false)); + } else { + hbc->add_child(memnew(Label(right_name))); } - } - - gnode->add_child(vbc); - - bool dark_theme = get_theme_constant("dark_theme", "Editor"); - if (i < mixed_seq_ports) { - gnode->set_slot(slot_idx, left_ok, left_type, _color_from_type(left_type, dark_theme), true, TYPE_SEQUENCE, mono_color, Ref<Texture2D>(), seq_port); } else { - gnode->set_slot(slot_idx, left_ok, left_type, _color_from_type(left_type, dark_theme), right_ok, right_type, _color_from_type(right_type, dark_theme)); + hbc->add_child(memnew(Label(right_name))); } - slot_idx++; + Ref<Texture2D> t; + if (right_type >= 0 && right_type < Variant::VARIANT_MAX) { + t = type_icons[right_type]; + } + if (t.is_valid()) { + TextureRect *tf = memnew(TextureRect); + tf->set_texture(t); + tf->set_stretch_mode(TextureRect::STRETCH_KEEP_CENTERED); + hbc->add_child(tf); + } } - graph->add_child(gnode); + gnode->add_child(vbc); - if (gnode->is_comment()) { - graph->move_child(gnode, 0); + bool dark_theme = get_theme_constant("dark_theme", "Editor"); + if (i < mixed_seq_ports) { + gnode->set_slot(slot_idx, left_ok, left_type, _color_from_type(left_type, dark_theme), true, TYPE_SEQUENCE, mono_color, Ref<Texture2D>(), seq_port); + } else { + gnode->set_slot(slot_idx, left_ok, left_type, _color_from_type(left_type, dark_theme), right_ok, right_type, _color_from_type(right_type, dark_theme)); } + + slot_idx++; + } + + graph->add_child(gnode); + + if (gnode->is_comment()) { + graph->move_child(gnode, 0); } } + _update_graph_connections(); - // use default_func instead of default_func for now I think that should be good stop gap solution to ensure not breaking anything - graph->call_deferred("set_scroll_ofs", script->get_function_scroll(default_func) * EDSCALE); + // Use default_func instead of default_func for now I think that should be good stop gap solution to ensure not breaking anything. + graph->call_deferred("set_scroll_ofs", script->get_scroll() * EDSCALE); updating_graph = false; } void VisualScriptEditor::_change_port_type(int p_select, int p_id, int p_port, bool is_input) { - StringName func = _get_function_of_node(p_id); - - Ref<VisualScriptLists> vsn = script->get_node(func, p_id); + Ref<VisualScriptLists> vsn = script->get_node(p_id); if (!vsn.is_valid()) { return; } @@ -1015,14 +993,12 @@ void VisualScriptEditor::_change_port_type(int p_select, int p_id, int p_port, b void VisualScriptEditor::_update_node_size(int p_id) { Node *node = graph->get_node(itos(p_id)); if (Object::cast_to<Control>(node)) { - Object::cast_to<Control>(node)->set_size(Vector2(1, 1)); //shrink if text is smaller + Object::cast_to<Control>(node)->set_size(Vector2(1, 1)); // Shrink if text is smaller. } } void VisualScriptEditor::_port_name_focus_out(const Node *p_name_box, int p_id, int p_port, bool is_input) { - StringName func = _get_function_of_node(p_id); - - Ref<VisualScriptLists> vsn = script->get_node(func, p_id); + Ref<VisualScriptLists> vsn = script->get_node(p_id); if (!vsn.is_valid()) { return; } @@ -1063,11 +1039,8 @@ void VisualScriptEditor::_update_members() { List<StringName> func_names; script->get_function_list(&func_names); + func_names.sort_custom<StringName::AlphCompare>(); for (List<StringName>::Element *E = func_names.front(); E; E = E->next()) { - if (E->get() == default_func) { - continue; - } - TreeItem *ti = members->create_item(functions); ti->set_text(0, E->get()); ti->set_selectable(0, true); @@ -1200,7 +1173,7 @@ void VisualScriptEditor::_member_selected() { #endif if (held_ctrl) { ERR_FAIL_COND(!script->has_function(selected)); - _center_on_node(selected, script->get_function_node_id(selected)); + _center_on_node(script->get_function_node_id(selected)); } } } @@ -1243,8 +1216,8 @@ void VisualScriptEditor::_member_edited() { int node_id = script->get_function_node_id(name); Ref<VisualScriptFunction> func; - if (script->has_node(name, node_id)) { - func = script->get_node(name, node_id); + if (script->has_node(node_id)) { + func = script->get_node(node_id); } undo_redo->create_action(TTR("Rename Function")); undo_redo->add_do_method(script.ptr(), "rename_function", name, new_name); @@ -1254,21 +1227,17 @@ void VisualScriptEditor::_member_edited() { undo_redo->add_undo_method(func.ptr(), "set_name", name); } - // also fix all function calls - List<StringName> flst; - script->get_function_list(&flst); - for (List<StringName>::Element *E = flst.front(); E; E = E->next()) { - List<int> lst; - script->get_node_list(E->get(), &lst); - for (List<int>::Element *F = lst.front(); F; F = F->next()) { - Ref<VisualScriptFunctionCall> fncall = script->get_node(E->get(), F->get()); - if (!fncall.is_valid()) { - continue; - } - if (fncall->get_function() == name) { - undo_redo->add_do_method(fncall.ptr(), "set_function", new_name); - undo_redo->add_undo_method(fncall.ptr(), "set_function", name); - } + // Also fix all function calls. + List<int> lst; + script->get_node_list(&lst); + for (List<int>::Element *F = lst.front(); F; F = F->next()) { + Ref<VisualScriptFunctionCall> fncall = script->get_node(F->get()); + if (!fncall.is_valid()) { + continue; + } + if (fncall->get_function() == name) { + undo_redo->add_do_method(fncall.ptr(), "set_function", new_name); + undo_redo->add_undo_method(fncall.ptr(), "set_function", name); } } @@ -1280,7 +1249,7 @@ void VisualScriptEditor::_member_edited() { undo_redo->add_undo_method(this, "emit_signal", "edited_script_changed"); undo_redo->commit_action(); - return; //or crash because it will become invalid + return; // Or crash because it will become invalid. } if (ti->get_parent() == root->get_children()->get_next()) { @@ -1296,7 +1265,7 @@ void VisualScriptEditor::_member_edited() { undo_redo->add_undo_method(this, "emit_signal", "edited_script_changed"); undo_redo->commit_action(); - return; //or crash because it will become invalid + return; // Or crash because it will become invalid. } if (ti->get_parent() == root->get_children()->get_next()->get_next()) { @@ -1310,7 +1279,7 @@ void VisualScriptEditor::_member_edited() { undo_redo->add_undo_method(this, "emit_signal", "edited_script_changed"); undo_redo->commit_action(); - return; //or crash because it will become invalid + return; // Or crash because it will become invalid. } } @@ -1344,10 +1313,13 @@ void VisualScriptEditor::_create_function() { func_node->add_argument(arg_type, arg_name); } + int func_node_id = script->get_available_id(); + undo_redo->create_action(TTR("Add Function")); - undo_redo->add_do_method(script.ptr(), "add_function", name); - undo_redo->add_do_method(script.ptr(), "add_node", name, script->get_available_id(), func_node, ofs); + undo_redo->add_do_method(script.ptr(), "add_function", name, func_node_id); undo_redo->add_undo_method(script.ptr(), "remove_function", name); + undo_redo->add_do_method(script.ptr(), "add_node", func_node_id, func_node, ofs); + undo_redo->add_undo_method(script.ptr(), "remove_node", func_node_id); undo_redo->add_do_method(this, "_update_members"); undo_redo->add_undo_method(this, "_update_members"); undo_redo->add_do_method(this, "_update_graph"); @@ -1431,11 +1403,12 @@ void VisualScriptEditor::_member_button(Object *p_item, int p_column, int p_butt if (ti->get_parent() == root) { //main buttons if (ti == root->get_children()) { - //add function, this one uses menu + // Add function, this one uses menu. if (p_button == 1) { + // Ensure script base exists otherwise use custom base type. + ERR_FAIL_COND(script.is_null()); new_virtual_method_select->select_method_from_base_type(script->get_instance_base_type(), String(), true); - return; } else if (p_button == 0) { String name = _validate_name("new_function"); @@ -1445,11 +1418,13 @@ void VisualScriptEditor::_member_button(Object *p_item, int p_column, int p_butt Ref<VisualScriptFunction> func_node; func_node.instance(); func_node->set_name(name); + int fn_id = script->get_available_id(); undo_redo->create_action(TTR("Add Function")); - undo_redo->add_do_method(script.ptr(), "add_function", name); - undo_redo->add_do_method(script.ptr(), "add_node", name, script->get_available_id(), func_node, ofs); + undo_redo->add_do_method(script.ptr(), "add_function", name, fn_id); + undo_redo->add_do_method(script.ptr(), "add_node", fn_id, func_node, ofs); undo_redo->add_undo_method(script.ptr(), "remove_function", name); + undo_redo->add_do_method(script.ptr(), "remove_node", fn_id); undo_redo->add_do_method(this, "_update_members"); undo_redo->add_undo_method(this, "_update_members"); undo_redo->add_do_method(this, "_update_graph"); @@ -1461,11 +1436,11 @@ void VisualScriptEditor::_member_button(Object *p_item, int p_column, int p_butt _update_graph(); } - return; //or crash because it will become invalid + return; // Or crash because it will become invalid. } if (ti == root->get_children()->get_next()) { - //add variable + // Add variable. String name = _validate_name("new_variable"); selected = name; @@ -1477,11 +1452,11 @@ void VisualScriptEditor::_member_button(Object *p_item, int p_column, int p_butt undo_redo->add_do_method(this, "emit_signal", "edited_script_changed"); undo_redo->add_undo_method(this, "emit_signal", "edited_script_changed"); undo_redo->commit_action(); - return; //or crash because it will become invalid + return; // Or crash because it will become invalid. } if (ti == root->get_children()->get_next()->get_next()) { - //add variable + // Add variable. String name = _validate_name("new_signal"); selected = name; @@ -1493,7 +1468,7 @@ void VisualScriptEditor::_member_button(Object *p_item, int p_column, int p_butt undo_redo->add_do_method(this, "emit_signal", "edited_script_changed"); undo_redo->add_undo_method(this, "emit_signal", "edited_script_changed"); undo_redo->commit_action(); - return; //or crash because it will become invalid + return; // Or crash because it will become invalid. } } else if (ti->get_parent() == root->get_children()) { selected = ti->get_text(0); @@ -1505,9 +1480,7 @@ void VisualScriptEditor::_member_button(Object *p_item, int p_column, int p_butt } void VisualScriptEditor::_add_input_port(int p_id) { - StringName func = _get_function_of_node(p_id); - - Ref<VisualScriptLists> vsn = script->get_node(func, p_id); + Ref<VisualScriptLists> vsn = script->get_node(p_id); if (!vsn.is_valid()) { return; } @@ -1527,9 +1500,7 @@ void VisualScriptEditor::_add_input_port(int p_id) { } void VisualScriptEditor::_add_output_port(int p_id) { - StringName func = _get_function_of_node(p_id); - - Ref<VisualScriptLists> vsn = script->get_node(func, p_id); + Ref<VisualScriptLists> vsn = script->get_node(p_id); if (!vsn.is_valid()) { return; } @@ -1549,9 +1520,7 @@ void VisualScriptEditor::_add_output_port(int p_id) { } void VisualScriptEditor::_remove_input_port(int p_id, int p_port) { - StringName func = _get_function_of_node(p_id); - - Ref<VisualScriptLists> vsn = script->get_node(func, p_id); + Ref<VisualScriptLists> vsn = script->get_node(p_id); if (!vsn.is_valid()) { return; } @@ -1561,17 +1530,17 @@ void VisualScriptEditor::_remove_input_port(int p_id, int p_port) { undo_redo->create_action(TTR("Remove Input Port"), UndoRedo::MERGE_ENDS); int conn_from = -1, conn_port = -1; - script->get_input_value_port_connection_source(func, p_id, p_port, &conn_from, &conn_port); + script->get_input_value_port_connection_source(p_id, p_port, &conn_from, &conn_port); if (conn_from != -1) { - undo_redo->add_do_method(script.ptr(), "data_disconnect", func, conn_from, conn_port, p_id, p_port); + undo_redo->add_do_method(script.ptr(), "data_disconnect", conn_from, conn_port, p_id, p_port); } undo_redo->add_do_method(vsn.ptr(), "remove_input_data_port", p_port); undo_redo->add_do_method(this, "_update_graph", p_id); if (conn_from != -1) { - undo_redo->add_undo_method(script.ptr(), "data_connect", func, conn_from, conn_port, p_id, p_port); + undo_redo->add_undo_method(script.ptr(), "data_connect", conn_from, conn_port, p_id, p_port); } undo_redo->add_undo_method(vsn.ptr(), "add_input_data_port", vsn->get_input_value_port_info(p_port).type, vsn->get_input_value_port_info(p_port).name, p_port); @@ -1583,9 +1552,7 @@ void VisualScriptEditor::_remove_input_port(int p_id, int p_port) { } void VisualScriptEditor::_remove_output_port(int p_id, int p_port) { - StringName func = _get_function_of_node(p_id); - - Ref<VisualScriptLists> vsn = script->get_node(func, p_id); + Ref<VisualScriptLists> vsn = script->get_node(p_id); if (!vsn.is_valid()) { return; } @@ -1595,12 +1562,12 @@ void VisualScriptEditor::_remove_output_port(int p_id, int p_port) { undo_redo->create_action(TTR("Remove Output Port"), UndoRedo::MERGE_ENDS); List<VisualScript::DataConnection> data_connections; - script->get_data_connection_list(func, &data_connections); + script->get_data_connection_list(&data_connections); HashMap<int, Set<int>> conn_map; for (const List<VisualScript::DataConnection>::Element *E = data_connections.front(); E; E = E->next()) { if (E->get().from_node == p_id && E->get().from_port == p_port) { - // push into the connections map + // Push into the connections map. if (!conn_map.has(E->get().to_node)) { conn_map.set(E->get().to_node, Set<int>()); } @@ -1615,7 +1582,7 @@ void VisualScriptEditor::_remove_output_port(int p_id, int p_port) { conn_map.get_key_list(&keys); for (const List<int>::Element *E = keys.front(); E; E = E->next()) { for (const Set<int>::Element *F = conn_map[E->get()].front(); F; F = F->next()) { - undo_redo->add_undo_method(script.ptr(), "data_connect", func, p_id, p_port, E->get(), F->get()); + undo_redo->add_undo_method(script.ptr(), "data_connect", p_id, p_port, E->get(), F->get()); } } @@ -1628,9 +1595,7 @@ void VisualScriptEditor::_remove_output_port(int p_id, int p_port) { } void VisualScriptEditor::_expression_text_changed(const String &p_text, int p_id) { - StringName func = _get_function_of_node(p_id); - - Ref<VisualScriptExpression> vse = script->get_node(func, p_id); + Ref<VisualScriptExpression> vse = script->get_node(p_id); if (!vse.is_valid()) { return; } @@ -1646,7 +1611,7 @@ void VisualScriptEditor::_expression_text_changed(const String &p_text, int p_id Node *node = graph->get_node(itos(p_id)); if (Object::cast_to<Control>(node)) { - Object::cast_to<Control>(node)->set_size(Vector2(1, 1)); //shrink if text is smaller + Object::cast_to<Control>(node)->set_size(Vector2(1, 1)); // Shrink if text is smaller. } updating_graph = false; @@ -1666,19 +1631,14 @@ Vector2 VisualScriptEditor::_get_available_pos(bool centered, Vector2 ofs) const while (true) { bool exists = false; - List<StringName> all_fn; - script->get_function_list(&all_fn); - for (List<StringName>::Element *F = all_fn.front(); F; F = F->next()) { - StringName curr_fn = F->get(); - List<int> existing; - script->get_node_list(curr_fn, &existing); - for (List<int>::Element *E = existing.front(); E; E = E->next()) { - Point2 pos = script->get_node_position(curr_fn, E->get()); - if (pos.distance_to(ofs) < 50) { - ofs += Vector2(graph->get_snap(), graph->get_snap()); - exists = true; - break; - } + List<int> existing; + script->get_node_list(&existing); + for (List<int>::Element *E = existing.front(); E; E = E->next()) { + Point2 pos = script->get_node_position(E->get()); + if (pos.distance_to(ofs) < 50) { + ofs += Vector2(graph->get_snap(), graph->get_snap()); + exists = true; + break; } } if (exists) { @@ -1710,7 +1670,7 @@ String VisualScriptEditor::_validate_name(const String &p_name) const { } void VisualScriptEditor::_on_nodes_delete() { - // delete all the selected nodes + // Delete all the selected nodes. List<int> to_erase; @@ -1732,26 +1692,24 @@ void VisualScriptEditor::_on_nodes_delete() { for (List<int>::Element *F = to_erase.front(); F; F = F->next()) { int cr_node = F->get(); - StringName func = _get_function_of_node(cr_node); - - undo_redo->add_do_method(script.ptr(), "remove_node", func, cr_node); - undo_redo->add_undo_method(script.ptr(), "add_node", func, cr_node, script->get_node(func, cr_node), script->get_node_position(func, cr_node)); + undo_redo->add_do_method(script.ptr(), "remove_node", cr_node); + undo_redo->add_undo_method(script.ptr(), "add_node", cr_node, script->get_node(cr_node), script->get_node_position(cr_node)); List<VisualScript::SequenceConnection> sequence_conns; - script->get_sequence_connection_list(func, &sequence_conns); + script->get_sequence_connection_list(&sequence_conns); for (List<VisualScript::SequenceConnection>::Element *E = sequence_conns.front(); E; E = E->next()) { if (E->get().from_node == cr_node || E->get().to_node == cr_node) { - undo_redo->add_undo_method(script.ptr(), "sequence_connect", func, E->get().from_node, E->get().from_output, E->get().to_node); + undo_redo->add_undo_method(script.ptr(), "sequence_connect", E->get().from_node, E->get().from_output, E->get().to_node); } } List<VisualScript::DataConnection> data_conns; - script->get_data_connection_list(func, &data_conns); + script->get_data_connection_list(&data_conns); for (List<VisualScript::DataConnection>::Element *E = data_conns.front(); E; E = E->next()) { if (E->get().from_node == F->get() || E->get().to_node == F->get()) { - undo_redo->add_undo_method(script.ptr(), "data_connect", func, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); + undo_redo->add_undo_method(script.ptr(), "data_connect", E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); } } } @@ -1763,7 +1721,6 @@ void VisualScriptEditor::_on_nodes_delete() { void VisualScriptEditor::_on_nodes_duplicate() { Set<int> to_duplicate; - List<StringName> funcs; for (int i = 0; i < graph->get_child_count(); i++) { GraphNode *gn = Object::cast_to<GraphNode>(graph->get_child(i)); @@ -1771,7 +1728,6 @@ void VisualScriptEditor::_on_nodes_duplicate() { if (gn->is_selected() && gn->is_close_button_visible()) { int id = gn->get_name().operator String().to_int(); to_duplicate.insert(id); - funcs.push_back(_get_function_of_node(id)); } } } @@ -1787,9 +1743,8 @@ void VisualScriptEditor::_on_nodes_duplicate() { HashMap<int, int> remap; for (Set<int>::Element *F = to_duplicate.front(); F; F = F->next()) { - // duplicate from the specific function but place it into the default func as it would lack the connections - StringName func = _get_function_of_node(F->get()); - Ref<VisualScriptNode> node = script->get_node(func, F->get()); + // Duplicate from the specific function but place it into the default func as it would lack the connections. + Ref<VisualScriptNode> node = script->get_node(F->get()); Ref<VisualScriptNode> dupe = node->duplicate(true); @@ -1797,25 +1752,23 @@ void VisualScriptEditor::_on_nodes_duplicate() { remap.set(F->get(), new_id); to_select.insert(new_id); - undo_redo->add_do_method(script.ptr(), "add_node", default_func, new_id, dupe, script->get_node_position(func, F->get()) + Vector2(20, 20)); - undo_redo->add_undo_method(script.ptr(), "remove_node", default_func, new_id); + undo_redo->add_do_method(script.ptr(), "add_node", new_id, dupe, script->get_node_position(F->get()) + Vector2(20, 20)); + undo_redo->add_undo_method(script.ptr(), "remove_node", new_id); } - for (List<StringName>::Element *F = funcs.front(); F; F = F->next()) { - List<VisualScript::SequenceConnection> seqs; - script->get_sequence_connection_list(F->get(), &seqs); - for (List<VisualScript::SequenceConnection>::Element *E = seqs.front(); E; E = E->next()) { - if (to_duplicate.has(E->get().from_node) && to_duplicate.has(E->get().to_node)) { - undo_redo->add_do_method(script.ptr(), "sequence_connect", default_func, remap[E->get().from_node], E->get().from_output, remap[E->get().to_node]); - } + List<VisualScript::SequenceConnection> seqs; + script->get_sequence_connection_list(&seqs); + for (List<VisualScript::SequenceConnection>::Element *E = seqs.front(); E; E = E->next()) { + if (to_duplicate.has(E->get().from_node) && to_duplicate.has(E->get().to_node)) { + undo_redo->add_do_method(script.ptr(), "sequence_connect", remap[E->get().from_node], E->get().from_output, remap[E->get().to_node]); } + } - List<VisualScript::DataConnection> data; - script->get_data_connection_list(F->get(), &data); - for (List<VisualScript::DataConnection>::Element *E = data.front(); E; E = E->next()) { - if (to_duplicate.has(E->get().from_node) && to_duplicate.has(E->get().to_node)) { - undo_redo->add_do_method(script.ptr(), "data_connect", default_func, remap[E->get().from_node], E->get().from_port, remap[E->get().to_node], E->get().to_port); - } + List<VisualScript::DataConnection> data; + script->get_data_connection_list(&data); + for (List<VisualScript::DataConnection>::Element *E = data.front(); E; E = E->next()) { + if (to_duplicate.has(E->get().from_node) && to_duplicate.has(E->get().to_node)) { + undo_redo->add_do_method(script.ptr(), "data_connect", remap[E->get().from_node], E->get().from_port, remap[E->get().to_node], E->get().to_port); } } @@ -1833,7 +1786,7 @@ void VisualScriptEditor::_on_nodes_duplicate() { } if (to_select.size()) { - EditorNode::get_singleton()->push_item(script->get_node(default_func, to_select.front()->get()).ptr()); + EditorNode::get_singleton()->push_item(script->get_node(to_select.front()->get()).ptr()); } } @@ -1846,7 +1799,7 @@ void VisualScriptEditor::_generic_search(String p_base_type, Vector2 pos, bool n new_connect_node_select->select_from_visual_script(p_base_type, false, false); // neither connecting nor reset text - // ensure that the dialog fits inside the graph + // Ensure that the dialog fits inside the graph. Size2 bounds = graph->get_global_position() + graph->get_size() - new_connect_node_select->get_size(); pos.x = pos.x > bounds.x ? bounds.x : pos.x; pos.y = pos.y > bounds.y ? bounds.y : pos.y; @@ -1907,7 +1860,7 @@ void VisualScriptEditor::_members_gui_input(const Ref<InputEvent> &p_event) { if (btn.is_valid() && btn->is_doubleclick()) { TreeItem *ti = members->get_selected(); if (ti && ti->get_parent() == members->get_root()->get_children()) { // to check if it's a function - _center_on_node(ti->get_metadata(0), script->get_function_node_id(ti->get_metadata(0))); + _center_on_node(script->get_function_node_id(ti->get_metadata(0))); } } } @@ -1925,8 +1878,8 @@ void VisualScriptEditor::_rename_function(const String &name, const String &new_ int node_id = script->get_function_node_id(name); Ref<VisualScriptFunction> func; - if (script->has_node(name, node_id)) { - func = script->get_node(name, node_id); + if (script->has_node(node_id)) { + func = script->get_node(node_id); } undo_redo->create_action(TTR("Rename Function")); undo_redo->add_do_method(script.ptr(), "rename_function", name, new_name); @@ -1936,21 +1889,17 @@ void VisualScriptEditor::_rename_function(const String &name, const String &new_ undo_redo->add_undo_method(func.ptr(), "set_name", name); } - // also fix all function calls - List<StringName> flst; - script->get_function_list(&flst); - for (List<StringName>::Element *E = flst.front(); E; E = E->next()) { - List<int> lst; - script->get_node_list(E->get(), &lst); - for (List<int>::Element *F = lst.front(); F; F = F->next()) { - Ref<VisualScriptFunctionCall> fncall = script->get_node(E->get(), F->get()); - if (!fncall.is_valid()) { - continue; - } - if (fncall->get_function() == name) { - undo_redo->add_do_method(fncall.ptr(), "set_function", new_name); - undo_redo->add_undo_method(fncall.ptr(), "set_function", name); - } + // Also fix all function calls. + List<int> lst; + script->get_node_list(&lst); + for (List<int>::Element *F = lst.front(); F; F = F->next()) { + Ref<VisualScriptFunctionCall> fncall = script->get_node(F->get()); + if (!fncall.is_valid()) { + continue; + } + if (fncall->get_function() == name) { + undo_redo->add_do_method(fncall.ptr(), "set_function", new_name); + undo_redo->add_undo_method(fncall.ptr(), "set_function", name); } } @@ -2103,7 +2052,7 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da ofs /= EDSCALE; - int new_id = _create_new_node_from_name(d["node_type"], ofs, default_func); + int new_id = _create_new_node_from_name(d["node_type"], ofs); Node *node = graph->get_node(itos(new_id)); if (node) { @@ -2142,8 +2091,8 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da int new_id = script->get_available_id(); undo_redo->create_action(TTR("Add Node")); - undo_redo->add_do_method(script.ptr(), "add_node", default_func, new_id, vnode, ofs); - undo_redo->add_undo_method(script.ptr(), "remove_node", default_func, new_id); + undo_redo->add_do_method(script.ptr(), "add_node", new_id, vnode, ofs); + undo_redo->add_undo_method(script.ptr(), "remove_node", new_id); undo_redo->add_do_method(this, "_update_graph"); undo_redo->add_undo_method(this, "_update_graph"); undo_redo->commit_action(); @@ -2171,11 +2120,11 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da int new_id = script->get_available_id(); undo_redo->create_action(TTR("Add Node")); - undo_redo->add_do_method(script.ptr(), "add_node", default_func, new_id, vnode, ofs); + undo_redo->add_do_method(script.ptr(), "add_node", new_id, vnode, ofs); undo_redo->add_do_method(vnode.ptr(), "set_base_type", script->get_instance_base_type()); undo_redo->add_do_method(vnode.ptr(), "set_function", d["function"]); - undo_redo->add_undo_method(script.ptr(), "remove_node", default_func, new_id); + undo_redo->add_undo_method(script.ptr(), "remove_node", new_id); undo_redo->add_do_method(this, "_update_graph"); undo_redo->add_undo_method(this, "_update_graph"); undo_redo->commit_action(); @@ -2203,8 +2152,8 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da int new_id = script->get_available_id(); undo_redo->create_action(TTR("Add Node")); - undo_redo->add_do_method(script.ptr(), "add_node", default_func, new_id, vnode, ofs); - undo_redo->add_undo_method(script.ptr(), "remove_node", default_func, new_id); + undo_redo->add_do_method(script.ptr(), "add_node", new_id, vnode, ofs); + undo_redo->add_undo_method(script.ptr(), "remove_node", new_id); undo_redo->add_do_method(this, "_update_graph"); undo_redo->add_undo_method(this, "_update_graph"); undo_redo->commit_action(); @@ -2232,8 +2181,8 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da int new_id = script->get_available_id(); undo_redo->create_action(TTR("Add Preload Node")); - undo_redo->add_do_method(script.ptr(), "add_node", default_func, new_id, prnode, ofs); - undo_redo->add_undo_method(script.ptr(), "remove_node", default_func, new_id); + undo_redo->add_do_method(script.ptr(), "add_node", new_id, prnode, ofs); + undo_redo->add_undo_method(script.ptr(), "remove_node", new_id); undo_redo->add_do_method(this, "_update_graph"); undo_redo->add_undo_method(this, "_update_graph"); undo_redo->commit_action(); @@ -2272,8 +2221,8 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da prnode.instance(); prnode->set_preload(res); - undo_redo->add_do_method(script.ptr(), "add_node", default_func, new_id, prnode, ofs); - undo_redo->add_undo_method(script.ptr(), "remove_node", default_func, new_id); + undo_redo->add_do_method(script.ptr(), "add_node", new_id, prnode, ofs); + undo_redo->add_undo_method(script.ptr(), "remove_node", new_id); new_ids.push_back(new_id); new_id++; ofs += Vector2(20, 20) * EDSCALE; @@ -2339,7 +2288,7 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da scene_node->set_node_path(sn->get_path_to(node)); n = scene_node; } else { - // ! Doesn't work properly + // ! Doesn't work properly. Ref<VisualScriptFunctionCall> call; call.instance(); call->set_call_mode(VisualScriptFunctionCall::CALL_MODE_NODE_PATH); @@ -2350,8 +2299,8 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da selecting_method_id = base_id; } - undo_redo->add_do_method(script.ptr(), "add_node", default_func, base_id, n, ofs); - undo_redo->add_undo_method(script.ptr(), "remove_node", default_func, base_id); + undo_redo->add_do_method(script.ptr(), "add_node", base_id, n, ofs); + undo_redo->add_undo_method(script.ptr(), "remove_node", base_id); base_id++; ofs += Vector2(25, 25); @@ -2420,13 +2369,13 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da vnode = pget; } - undo_redo->add_do_method(script.ptr(), "add_node", default_func, base_id, vnode, ofs); + undo_redo->add_do_method(script.ptr(), "add_node", base_id, vnode, ofs); undo_redo->add_do_method(vnode.ptr(), "set_property", d["property"]); if (!use_get) { undo_redo->add_do_method(vnode.ptr(), "set_default_input_value", 0, d["value"]); } - undo_redo->add_undo_method(script.ptr(), "remove_node", default_func, base_id); + undo_redo->add_undo_method(script.ptr(), "remove_node", base_id); undo_redo->add_do_method(this, "_update_graph"); undo_redo->add_undo_method(this, "_update_graph"); @@ -2465,12 +2414,12 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da } vnode = pget; } - undo_redo->add_do_method(script.ptr(), "add_node", default_func, base_id, vnode, ofs); + undo_redo->add_do_method(script.ptr(), "add_node", base_id, vnode, ofs); undo_redo->add_do_method(vnode.ptr(), "set_property", d["property"]); if (!use_get) { undo_redo->add_do_method(vnode.ptr(), "set_default_input_value", 0, d["value"]); } - undo_redo->add_undo_method(script.ptr(), "remove_node", default_func, base_id); + undo_redo->add_undo_method(script.ptr(), "remove_node", base_id); undo_redo->add_do_method(this, "_update_graph"); undo_redo->add_undo_method(this, "_update_graph"); @@ -2480,7 +2429,7 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da } void VisualScriptEditor::_selected_method(const String &p_method, const String &p_type, const bool p_connecting) { - Ref<VisualScriptFunctionCall> vsfc = script->get_node(default_func, selecting_method_id); + Ref<VisualScriptFunctionCall> vsfc = script->get_node(selecting_method_id); if (!vsfc.is_valid()) { return; } @@ -2538,14 +2487,6 @@ void VisualScriptEditor::set_edited_resource(const RES &p_res) { script->connect("node_ports_changed", callable_mp(this, &VisualScriptEditor::_node_ports_changed)); - default_func = script->get_default_func(); - - if (!script->has_function(default_func)) // this is the supposed default function - { - script->add_function(default_func); - script->set_edited(true); //so that if a function was added it's saved - } - _update_graph(); call_deferred("_update_members"); } @@ -2594,7 +2535,6 @@ bool VisualScriptEditor::is_unsaved() { Variant VisualScriptEditor::get_edit_state() { Dictionary d; - d["function"] = default_func; d["scroll"] = graph->get_scroll_ofs(); d["zoom"] = graph->get_zoom(); d["using_snap"] = graph->is_using_snap(); @@ -2604,9 +2544,6 @@ Variant VisualScriptEditor::get_edit_state() { void VisualScriptEditor::set_edit_state(const Variant &p_state) { Dictionary d = p_state; - if (d.has("function")) { - selected = default_func; - } _update_graph(); _update_members(); @@ -2625,11 +2562,11 @@ void VisualScriptEditor::set_edit_state(const Variant &p_state) { } } -void VisualScriptEditor::_center_on_node(const StringName &p_func, int p_id) { +void VisualScriptEditor::_center_on_node(int p_id) { Node *n = graph->get_node(itos(p_id)); GraphNode *gn = Object::cast_to<GraphNode>(n); - // clear selection + // Clear selection. for (int i = 0; i < graph->get_child_count(); i++) { GraphNode *gnd = Object::cast_to<GraphNode>(graph->get_child(i)); if (gnd) { @@ -2641,13 +2578,13 @@ void VisualScriptEditor::_center_on_node(const StringName &p_func, int p_id) { gn->set_selected(true); Vector2 new_scroll = gn->get_position_offset() - graph->get_size() * 0.5 + gn->get_size() * 0.5; graph->set_scroll_ofs(new_scroll); - script->set_function_scroll(p_func, new_scroll / EDSCALE); + script->set_scroll(new_scroll / EDSCALE); script->set_edited(true); } } void VisualScriptEditor::goto_line(int p_line, bool p_with_error) { - p_line += 1; //add one because script lines begin from 0. + p_line += 1; // Add one because script lines begin from 0. if (p_with_error) { error_line = p_line; @@ -2656,7 +2593,7 @@ void VisualScriptEditor::goto_line(int p_line, bool p_with_error) { List<StringName> functions; script->get_function_list(&functions); for (List<StringName>::Element *E = functions.front(); E; E = E->next()) { - if (script->has_node(E->get(), p_line)) { + if (script->has_node(p_line)) { _update_graph(); _update_members(); @@ -2703,11 +2640,11 @@ Array VisualScriptEditor::get_breakpoints() { script->get_function_list(&functions); for (List<StringName>::Element *E = functions.front(); E; E = E->next()) { List<int> nodes; - script->get_node_list(E->get(), &nodes); + script->get_node_list(&nodes); for (List<int>::Element *F = nodes.front(); F; F = F->next()) { - Ref<VisualScriptNode> vsn = script->get_node(E->get(), F->get()); + Ref<VisualScriptNode> vsn = script->get_node(F->get()); if (vsn->is_breakpoint()) { - breakpoints.push_back(F->get() - 1); //subtract 1 because breakpoints in text start from zero + breakpoints.push_back(F->get() - 1); // Subtract 1 because breakpoints in text start from zero. } } } @@ -2718,7 +2655,7 @@ void VisualScriptEditor::add_callback(const String &p_function, PackedStringArra if (script->has_function(p_function)) { _update_members(); _update_graph(); - _center_on_node(p_function, script->get_function_node_id(p_function)); + _center_on_node(script->get_function_node_id(p_function)); return; } @@ -2742,15 +2679,15 @@ void VisualScriptEditor::add_callback(const String &p_function, PackedStringArra func->add_argument(type, name); } - + int fn_id = script->get_available_id(); func->set_name(p_function); - script->add_function(p_function); - script->add_node(p_function, script->get_available_id(), func); + script->add_function(p_function, fn_id); + script->add_node(fn_id, func); _update_members(); _update_graph(); - _center_on_node(p_function, script->get_function_node_id(p_function)); + _center_on_node(script->get_function_node_id(p_function)); } bool VisualScriptEditor::show_members_overview() { @@ -2844,8 +2781,8 @@ void VisualScriptEditor::_end_node_move() { undo_redo->commit_action(); } -void VisualScriptEditor::_move_node(const StringName &p_func, int p_id, const Vector2 &p_to) { - if (!script->has_function(p_func)) { +void VisualScriptEditor::_move_node(int p_id, const Vector2 &p_to) { + if (!script->has_node(p_id)) { return; } @@ -2855,51 +2792,35 @@ void VisualScriptEditor::_move_node(const StringName &p_func, int p_id, const Ve Object::cast_to<GraphNode>(node)->set_position_offset(p_to); } - script->set_node_position(p_func, p_id, p_to / EDSCALE); -} - -StringName VisualScriptEditor::_get_function_of_node(int p_id) const { - List<StringName> funcs; - script->get_function_list(&funcs); - for (List<StringName>::Element *E = funcs.front(); E; E = E->next()) { - if (script->has_node(E->get(), p_id)) { - return E->get(); - } - } - - return ""; // this is passed to avoid crash and is tested against later + script->set_node_position(p_id, p_to / EDSCALE); } void VisualScriptEditor::_node_moved(Vector2 p_from, Vector2 p_to, int p_id) { - StringName func = _get_function_of_node(p_id); - - undo_redo->add_do_method(this, "_move_node", func, p_id, p_to); - undo_redo->add_undo_method(this, "_move_node", func, p_id, p_from); + undo_redo->add_do_method(this, "_move_node", p_id, p_to); + undo_redo->add_undo_method(this, "_move_node", p_id, p_from); } void VisualScriptEditor::_remove_node(int p_id) { undo_redo->create_action(TTR("Remove VisualScript Node")); - StringName func = _get_function_of_node(p_id); - - undo_redo->add_do_method(script.ptr(), "remove_node", func, p_id); - undo_redo->add_undo_method(script.ptr(), "add_node", func, p_id, script->get_node(func, p_id), script->get_node_position(func, p_id)); + undo_redo->add_do_method(script.ptr(), "remove_node", p_id); + undo_redo->add_undo_method(script.ptr(), "add_node", p_id, script->get_node(p_id), script->get_node_position(p_id)); List<VisualScript::SequenceConnection> sequence_conns; - script->get_sequence_connection_list(func, &sequence_conns); + script->get_sequence_connection_list(&sequence_conns); for (List<VisualScript::SequenceConnection>::Element *E = sequence_conns.front(); E; E = E->next()) { if (E->get().from_node == p_id || E->get().to_node == p_id) { - undo_redo->add_undo_method(script.ptr(), "sequence_connect", func, E->get().from_node, E->get().from_output, E->get().to_node); + undo_redo->add_undo_method(script.ptr(), "sequence_connect", E->get().from_node, E->get().from_output, E->get().to_node); } } List<VisualScript::DataConnection> data_conns; - script->get_data_connection_list(func, &data_conns); + script->get_data_connection_list(&data_conns); for (List<VisualScript::DataConnection>::Element *E = data_conns.front(); E; E = E->next()) { if (E->get().from_node == p_id || E->get().to_node == p_id) { - undo_redo->add_undo_method(script.ptr(), "data_connect", func, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); + undo_redo->add_undo_method(script.ptr(), "data_connect", E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); } } @@ -2909,13 +2830,13 @@ void VisualScriptEditor::_remove_node(int p_id) { undo_redo->commit_action(); } -void VisualScriptEditor::_node_ports_changed(const String &p_func, int p_id) { +void VisualScriptEditor::_node_ports_changed(int p_id) { _update_graph(p_id); } -bool VisualScriptEditor::node_has_sequence_connections(const StringName &p_func, int p_id) { +bool VisualScriptEditor::node_has_sequence_connections(int p_id) { List<VisualScript::SequenceConnection> sequence_conns; - script->get_sequence_connection_list(p_func, &sequence_conns); + script->get_sequence_connection_list(&sequence_conns); for (List<VisualScript::SequenceConnection>::Element *E = sequence_conns.front(); E; E = E->next()) { int from = E->get().from_node; @@ -2930,9 +2851,7 @@ bool VisualScriptEditor::node_has_sequence_connections(const StringName &p_func, } void VisualScriptEditor::_graph_connected(const String &p_from, int p_from_slot, const String &p_to, int p_to_slot) { - StringName from_func = _get_function_of_node(p_from.to_int()); - - Ref<VisualScriptNode> from_node = script->get_node(from_func, p_from.to_int()); + Ref<VisualScriptNode> from_node = script->get_node(p_from.to_int()); ERR_FAIL_COND(!from_node.is_valid()); bool from_seq; @@ -2942,9 +2861,7 @@ void VisualScriptEditor::_graph_connected(const String &p_from, int p_from_slot, return; //can't connect this, it's invalid } - StringName to_func = _get_function_of_node(p_to.to_int()); - - Ref<VisualScriptNode> to_node = script->get_node(to_func, p_to.to_int()); + Ref<VisualScriptNode> to_node = script->get_node(p_to.to_int()); ERR_FAIL_COND(!to_node.is_valid()); bool to_seq; @@ -2956,56 +2873,23 @@ void VisualScriptEditor::_graph_connected(const String &p_from, int p_from_slot, ERR_FAIL_COND(from_seq != to_seq); - // Do all the checks here - StringName func; // this the func where we store the one the nodes at the end of the resolution on having multiple nodes + // Do all the checks here. + StringName func; // This the func where we store the one the nodes at the end of the resolution on having multiple nodes. undo_redo->create_action(TTR("Connect Nodes")); - if (from_func == to_func) { - func = to_func; - } else if (from_seq) { - // this is a sequence connection - _move_nodes_with_rescan(to_func, from_func, p_to.to_int()); // this function moves the nodes from func1 to func2 - func = from_func; - } else { - if (node_has_sequence_connections(to_func, p_to.to_int())) { - if (node_has_sequence_connections(from_func, p_from.to_int())) { - ERR_PRINT("Trying to connect between different sequence node trees"); - return; - } else { - _move_nodes_with_rescan(from_func, to_func, p_from.to_int()); - func = to_func; - } - } else if (node_has_sequence_connections(from_func, p_from.to_int())) { - if (from_func == default_func) { - _move_nodes_with_rescan(from_func, to_func, p_from.to_int()); - func = to_func; - } else { - _move_nodes_with_rescan(to_func, from_func, p_to.to_int()); - func = from_func; - } - } else { - if (to_func == default_func) { - _move_nodes_with_rescan(to_func, from_func, p_to.to_int()); - func = from_func; - } else { - _move_nodes_with_rescan(from_func, to_func, p_from.to_int()); - func = to_func; - } - } - } - if (from_seq) { - undo_redo->add_do_method(script.ptr(), "sequence_connect", func, p_from.to_int(), from_port, p_to.to_int()); - // this undo error on undo after move can't be removed without painful gymnastics - undo_redo->add_undo_method(script.ptr(), "sequence_disconnect", func, p_from.to_int(), from_port, p_to.to_int()); + undo_redo->add_do_method(script.ptr(), "sequence_connect", p_from.to_int(), from_port, p_to.to_int()); + // This undo error on undo after move can't be removed without painful gymnastics + undo_redo->add_undo_method(script.ptr(), "sequence_disconnect", p_from.to_int(), from_port, p_to.to_int()); + undo_redo->add_do_method(this, "_update_graph"); + undo_redo->add_undo_method(this, "_update_graph"); } else { bool converted = false; - int conv_node = -1; Ref<VisualScriptOperator> oper = to_node; if (oper.is_valid() && oper->get_typed() == Variant::NIL) { - // it's an operator Node and if the type is already nil + // It's an operator Node and if the type is already nil if (from_node->get_output_value_port_info(from_port).type != Variant::NIL) { oper->set_typed(from_node->get_output_value_port_info(from_port).type); } @@ -3013,106 +2897,36 @@ void VisualScriptEditor::_graph_connected(const String &p_from, int p_from_slot, Ref<VisualScriptOperator> operf = from_node; if (operf.is_valid() && operf->get_typed() == Variant::NIL) { - // it's an operator Node and if the type is already nil + // It's an operator Node and if the type is already nil if (to_node->get_input_value_port_info(to_port).type != Variant::NIL) { operf->set_typed(to_node->get_input_value_port_info(to_port).type); } } - Variant::Type to_type = to_node->get_input_value_port_info(to_port).type; - Variant::Type from_type = from_node->get_output_value_port_info(from_port).type; - - if (to_type != Variant::NIL && from_type != Variant::NIL && to_type != from_type) { - // add a constructor node between the ports - bool exceptions = false; // true if there are any exceptions - exceptions = exceptions || (to_type == Variant::INT && from_type == Variant::FLOAT); - exceptions = exceptions || (to_type == Variant::FLOAT && from_type == Variant::INT); - if (Variant::can_convert(from_type, to_type) && !exceptions) { - MethodInfo mi; - mi.name = Variant::get_type_name(to_type); - PropertyInfo pi; - pi.name = "from"; - pi.type = from_type; - mi.arguments.push_back(pi); - mi.return_val.type = to_type; - // we know that this is allowed so create a new constructor node - Ref<VisualScriptConstructor> constructor; - constructor.instance(); - constructor->set_constructor_type(to_type); - constructor->set_constructor(mi); - // add the new constructor node - - GraphNode *gn = Object::cast_to<GraphNode>(graph->get_node(p_from)); - GraphNode *gn2 = Object::cast_to<GraphNode>(graph->get_node(p_to)); - if (gn && gn2) { - Vector2 from_node_size = gn->get_rect().get_size(); - Vector2 to_node_size = gn2->get_rect().get_size(); - Vector2 to_node_pos = script->get_node_position(func, p_to.to_int()); - Vector2 from_node_pos = script->get_node_position(func, p_from.to_int()); - Vector2 new_to_node_pos = from_node_pos; - Vector2 constructor_pos; - if ((to_node_pos.x - from_node_pos.x) < 0) { - // to is behind from node - if (to_node_pos.x > (from_node_pos.x - to_node_size.x - 240)) { - new_to_node_pos.x = from_node_pos.x - to_node_size.x - 240; // approx size of constructor node + padding - } else { - new_to_node_pos.x = to_node_pos.x; - } - new_to_node_pos.y = to_node_pos.y; - constructor_pos.x = from_node_pos.x - 210; - constructor_pos.y = to_node_pos.y; - } else { - // to is ahead of from node - if (to_node_pos.x < (from_node_size.x + from_node_pos.x + 240)) { - new_to_node_pos.x = from_node_size.x + from_node_pos.x + 240; // approx size of constructor node + padding - } else { - new_to_node_pos.x = to_node_pos.x; - } - new_to_node_pos.y = to_node_pos.y; - constructor_pos.x = from_node_size.x + from_node_pos.x + 10; - constructor_pos.y = to_node_pos.y; - } - undo_redo->add_do_method(this, "_move_node", func, p_to.to_int(), new_to_node_pos); - undo_redo->add_undo_method(this, "_move_node", func, p_to.to_int(), to_node_pos); - conv_node = script->get_available_id(); - undo_redo->add_do_method(script.ptr(), "add_node", func, conv_node, constructor, _get_available_pos(false, constructor_pos)); - undo_redo->add_undo_method(script.ptr(), "remove_node", func, conv_node); - converted = true; - } - } - } - - // disconnect current, and connect the new one - if (script->is_input_value_port_connected(func, p_to.to_int(), to_port)) { + // Disconnect current, and connect the new one + if (script->is_input_value_port_connected(p_to.to_int(), to_port)) { if (can_swap && data_disconnect_node == p_to.to_int()) { int conn_from; int conn_port; - script->get_input_value_port_connection_source(func, p_to.to_int(), to_port, &conn_from, &conn_port); - undo_redo->add_do_method(script.ptr(), "data_disconnect", func, conn_from, conn_port, p_to.to_int(), to_port); - undo_redo->add_do_method(script.ptr(), "data_connect", func, conn_from, conn_port, data_disconnect_node, data_disconnect_port); - undo_redo->add_undo_method(script.ptr(), "data_disconnect", func, conn_from, conn_port, data_disconnect_node, data_disconnect_port); - undo_redo->add_undo_method(script.ptr(), "data_connect", func, conn_from, conn_port, p_to.to_int(), to_port); + script->get_input_value_port_connection_source(p_to.to_int(), to_port, &conn_from, &conn_port); + undo_redo->add_do_method(script.ptr(), "data_disconnect", conn_from, conn_port, p_to.to_int(), to_port); + undo_redo->add_do_method(script.ptr(), "data_connect", conn_from, conn_port, data_disconnect_node, data_disconnect_port); + undo_redo->add_undo_method(script.ptr(), "data_disconnect", conn_from, conn_port, data_disconnect_node, data_disconnect_port); + undo_redo->add_undo_method(script.ptr(), "data_connect", conn_from, conn_port, p_to.to_int(), to_port); can_swap = false; // swapped } else { int conn_from; int conn_port; - script->get_input_value_port_connection_source(func, p_to.to_int(), to_port, &conn_from, &conn_port); - undo_redo->add_do_method(script.ptr(), "data_disconnect", func, conn_from, conn_port, p_to.to_int(), to_port); - undo_redo->add_undo_method(script.ptr(), "data_connect", func, conn_from, conn_port, p_to.to_int(), to_port); + script->get_input_value_port_connection_source(p_to.to_int(), to_port, &conn_from, &conn_port); + undo_redo->add_do_method(script.ptr(), "data_disconnect", conn_from, conn_port, p_to.to_int(), to_port); + undo_redo->add_undo_method(script.ptr(), "data_connect", conn_from, conn_port, p_to.to_int(), to_port); } } if (!converted) { - undo_redo->add_do_method(script.ptr(), "data_connect", func, p_from.to_int(), from_port, p_to.to_int(), to_port); - undo_redo->add_undo_method(script.ptr(), "data_disconnect", func, p_from.to_int(), from_port, p_to.to_int(), to_port); - } else { - // this is noice - undo_redo->add_do_method(script.ptr(), "data_connect", func, p_from.to_int(), from_port, conv_node, 0); - undo_redo->add_do_method(script.ptr(), "data_connect", func, conv_node, 0, p_to.to_int(), to_port); - // I don't think this is needed but gonna leave it here for now... until I need to finalise it all - undo_redo->add_undo_method(script.ptr(), "data_disconnect", func, p_from.to_int(), from_port, conv_node, 0); - undo_redo->add_undo_method(script.ptr(), "data_disconnect", func, conv_node, 0, p_to.to_int(), to_port); + undo_redo->add_do_method(script.ptr(), "data_connect", p_from.to_int(), from_port, p_to.to_int(), to_port); + undo_redo->add_undo_method(script.ptr(), "data_disconnect", p_from.to_int(), from_port, p_to.to_int(), to_port); } - //update nodes in graph + // Update nodes in graph if (!converted) { undo_redo->add_do_method(this, "_update_graph", p_from.to_int()); undo_redo->add_do_method(this, "_update_graph", p_to.to_int()); @@ -3124,34 +2938,28 @@ void VisualScriptEditor::_graph_connected(const String &p_from, int p_from_slot, } } - undo_redo->add_do_method(this, "_update_graph_connections"); - undo_redo->add_undo_method(this, "_update_graph_connections"); - undo_redo->commit_action(); } void VisualScriptEditor::_graph_disconnected(const String &p_from, int p_from_slot, const String &p_to, int p_to_slot) { - StringName func = _get_function_of_node(p_from.to_int()); - ERR_FAIL_COND(func != _get_function_of_node(p_to.to_int())); - - Ref<VisualScriptNode> from_node = script->get_node(func, p_from.to_int()); + Ref<VisualScriptNode> from_node = script->get_node(p_from.to_int()); ERR_FAIL_COND(!from_node.is_valid()); bool from_seq; int from_port; if (!_get_out_slot(from_node, p_from_slot, from_port, from_seq)) { - return; //can't connect this, it's invalid + return; // Can't connect this, it's invalid. } - Ref<VisualScriptNode> to_node = script->get_node(func, p_to.to_int()); + Ref<VisualScriptNode> to_node = script->get_node(p_to.to_int()); ERR_FAIL_COND(!to_node.is_valid()); bool to_seq; int to_port; if (!_get_in_slot(to_node, p_to_slot, to_port, to_seq)) { - return; //can't connect this, it's invalid + return; // Can't connect this, it's invalid. } ERR_FAIL_COND(from_seq != to_seq); @@ -3159,248 +2967,27 @@ void VisualScriptEditor::_graph_disconnected(const String &p_from, int p_from_sl undo_redo->create_action(TTR("Disconnect Nodes")); if (from_seq) { - undo_redo->add_do_method(script.ptr(), "sequence_disconnect", func, p_from.to_int(), from_port, p_to.to_int()); - undo_redo->add_undo_method(script.ptr(), "sequence_connect", func, p_from.to_int(), from_port, p_to.to_int()); + undo_redo->add_do_method(script.ptr(), "sequence_disconnect", p_from.to_int(), from_port, p_to.to_int()); + undo_redo->add_undo_method(script.ptr(), "sequence_connect", p_from.to_int(), from_port, p_to.to_int()); + undo_redo->add_do_method(this, "_update_graph"); + undo_redo->add_undo_method(this, "_update_graph"); } else { can_swap = true; data_disconnect_node = p_to.to_int(); data_disconnect_port = to_port; - undo_redo->add_do_method(script.ptr(), "data_disconnect", func, p_from.to_int(), from_port, p_to.to_int(), to_port); - undo_redo->add_undo_method(script.ptr(), "data_connect", func, p_from.to_int(), from_port, p_to.to_int(), to_port); - //update relevant nodes in the graph + undo_redo->add_do_method(script.ptr(), "data_disconnect", p_from.to_int(), from_port, p_to.to_int(), to_port); + undo_redo->add_undo_method(script.ptr(), "data_connect", p_from.to_int(), from_port, p_to.to_int(), to_port); + // Update relevant nodes in the graph. undo_redo->add_do_method(this, "_update_graph", p_from.to_int()); undo_redo->add_do_method(this, "_update_graph", p_to.to_int()); undo_redo->add_undo_method(this, "_update_graph", p_from.to_int()); undo_redo->add_undo_method(this, "_update_graph", p_to.to_int()); } - undo_redo->add_do_method(this, "_update_graph_connections"); - undo_redo->add_undo_method(this, "_update_graph_connections"); undo_redo->commit_action(); } -void VisualScriptEditor::_move_nodes_with_rescan(const StringName &p_func_from, const StringName &p_func_to, int p_id) { - Set<int> nodes_to_move; - HashMap<int, Map<int, int>> seqconns_to_move; // from => List(outp, to) - HashMap<int, Map<int, Pair<int, int>>> dataconns_to_move; // to => List(inp_p => from, outp) - - nodes_to_move.insert(p_id); - Set<int> sequence_connections; - { - List<VisualScript::SequenceConnection> sequence_conns; - script->get_sequence_connection_list(p_func_from, &sequence_conns); - - HashMap<int, Map<int, int>> seqcons; // from => List(out_p => to) - - for (List<VisualScript::SequenceConnection>::Element *E = sequence_conns.front(); E; E = E->next()) { - int from = E->get().from_node; - int to = E->get().to_node; - int out_p = E->get().from_output; - if (!seqcons.has(from)) { - seqcons.set(from, Map<int, int>()); - } - seqcons[from].insert(out_p, to); - sequence_connections.insert(to); - sequence_connections.insert(from); - } - - int conn = p_id; - List<int> stack; - HashMap<int, Set<int>> seen; // from, outp - while (seqcons.has(conn)) { - for (auto E = seqcons[conn].front(); E; E = E->next()) { - if (seen.has(conn) && seen[conn].has(E->key())) { - if (!E->next()) { - if (stack.size() > 0) { - conn = stack.back()->get(); - stack.pop_back(); - break; - } - conn = -101; - break; - } - continue; - } - if (!seen.has(conn)) { - seen.set(conn, Set<int>()); - } - seen[conn].insert(E->key()); - stack.push_back(conn); - if (!seqconns_to_move.has(conn)) { - seqconns_to_move.set(conn, Map<int, int>()); - } - seqconns_to_move[conn].insert(E->key(), E->get()); - conn = E->get(); - nodes_to_move.insert(conn); - break; - } - if (!seqcons.has(conn) && stack.size() > 0) { - conn = stack.back()->get(); - stack.pop_back(); - } - } - } - - { - List<VisualScript::DataConnection> data_connections; - script->get_data_connection_list(p_func_from, &data_connections); - int func_from_node_id = script->get_function_node_id(p_func_from); - - HashMap<int, Map<int, Pair<int, int>>> connections; - - for (List<VisualScript::DataConnection>::Element *E = data_connections.front(); E; E = E->next()) { - int from = E->get().from_node; - int to = E->get().to_node; - int out_p = E->get().from_port; - int in_p = E->get().to_port; - - // skip if the from_node is a function node - if (from == func_from_node_id) { - continue; - } - - if (!connections.has(to)) { - connections.set(to, Map<int, Pair<int, int>>()); - } - connections[to].insert(in_p, Pair<int, int>(from, out_p)); - } - - // go through the HashMap and do all sorts of crazy ass stuff now... - Set<int> nodes_to_be_added; - for (Set<int>::Element *F = nodes_to_move.front(); F; F = F->next()) { - HashMap<int, Set<int>> seen; - List<int> stack; - int id = F->get(); - while (connections.has(id)) { - for (auto E = connections[id].front(); E; E = E->next()) { - if (seen.has(id) && seen[id].has(E->key())) { - if (!E->next()) { - if (stack.size() > 0) { - id = stack.back()->get(); - stack.pop_back(); - break; - } - id = -11; // I assume ids can't be negative should confirm it... - break; - } - continue; - } - - if (sequence_connections.has(E->get().first)) { - if (!nodes_to_move.has(E->get().first)) { - if (stack.size() > 0) { - id = stack.back()->get(); - stack.pop_back(); - break; - } - id = -11; // I assume ids can't be negative should confirm it... - break; - } - } - - if (!seen.has(id)) { - seen.set(id, Set<int>()); - } - seen[id].insert(E->key()); - stack.push_back(id); - if (!dataconns_to_move.has(id)) { - dataconns_to_move.set(id, Map<int, Pair<int, int>>()); - } - dataconns_to_move[id].insert(E->key(), Pair<int, int>(E->get().first, E->get().second)); - id = E->get().first; - nodes_to_be_added.insert(id); - break; - } - if (!connections.has(id) && stack.size() > 0) { - id = stack.back()->get(); - stack.pop_back(); - } - } - } - for (Set<int>::Element *E = nodes_to_be_added.front(); E; E = E->next()) { - nodes_to_move.insert(E->get()); - } - } - - // * this is primarily for the sake of the having proper undo - List<VisualScript::SequenceConnection> seqext; - List<VisualScript::DataConnection> dataext; - - List<VisualScript::SequenceConnection> seq_connections; - script->get_sequence_connection_list(p_func_from, &seq_connections); - - for (List<VisualScript::SequenceConnection>::Element *E = seq_connections.front(); E; E = E->next()) { - if (!nodes_to_move.has(E->get().from_node) && nodes_to_move.has(E->get().to_node)) { - seqext.push_back(E->get()); - } else if (nodes_to_move.has(E->get().from_node) && !nodes_to_move.has(E->get().to_node)) { - seqext.push_back(E->get()); - } - } - - List<VisualScript::DataConnection> data_connections; - script->get_data_connection_list(p_func_from, &data_connections); - - for (List<VisualScript::DataConnection>::Element *E = data_connections.front(); E; E = E->next()) { - if (!nodes_to_move.has(E->get().from_node) && nodes_to_move.has(E->get().to_node)) { - dataext.push_back(E->get()); - } else if (nodes_to_move.has(E->get().from_node) && !nodes_to_move.has(E->get().to_node)) { - dataext.push_back(E->get()); - } - } - - // undo_redo->create_action("Rescan Functions"); - - for (Set<int>::Element *E = nodes_to_move.front(); E; E = E->next()) { - int id = E->get(); - - undo_redo->add_do_method(script.ptr(), "remove_node", p_func_from, id); - undo_redo->add_do_method(script.ptr(), "add_node", p_func_to, id, script->get_node(p_func_from, id), script->get_node_position(p_func_from, id)); - - undo_redo->add_undo_method(script.ptr(), "remove_node", p_func_to, id); - undo_redo->add_undo_method(script.ptr(), "add_node", p_func_from, id, script->get_node(p_func_from, id), script->get_node_position(p_func_from, id)); - } - - List<int> skeys; - seqconns_to_move.get_key_list(&skeys); - for (List<int>::Element *E = skeys.front(); E; E = E->next()) { - int from_node = E->get(); - for (Map<int, int>::Element *F = seqconns_to_move[from_node].front(); F; F = F->next()) { - int from_port = F->key(); - int to_node = F->get(); - undo_redo->add_do_method(script.ptr(), "sequence_connect", p_func_to, from_node, from_port, to_node); - undo_redo->add_undo_method(script.ptr(), "sequence_connect", p_func_from, from_node, from_port, to_node); - } - } - - List<int> keys; - dataconns_to_move.get_key_list(&keys); - for (List<int>::Element *E = keys.front(); E; E = E->next()) { - int to_node = E->get(); // to_node - for (Map<int, Pair<int, int>>::Element *F = dataconns_to_move[E->get()].front(); F; F = F->next()) { - int inp_p = F->key(); - Pair<int, int> fro = F->get(); - - undo_redo->add_do_method(script.ptr(), "data_connect", p_func_to, fro.first, fro.second, to_node, inp_p); - undo_redo->add_undo_method(script.ptr(), "data_connect", p_func_from, fro.first, fro.second, to_node, inp_p); - } - } - - // this to have proper undo operations - for (List<VisualScript::SequenceConnection>::Element *E = seqext.front(); E; E = E->next()) { - undo_redo->add_undo_method(script.ptr(), "sequence_connect", p_func_from, E->get().from_node, E->get().from_output, E->get().to_node); - } - for (List<VisualScript::DataConnection>::Element *E = dataext.front(); E; E = E->next()) { - undo_redo->add_undo_method(script.ptr(), "data_connect", p_func_from, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); - } - // this doesn't need do methods as they are handled by the subsequent do calls implicitly - - undo_redo->add_do_method(this, "_update_graph"); - undo_redo->add_undo_method(this, "_update_graph"); - - // undo_redo->commit_action(); -} - void VisualScriptEditor::_graph_connect_to_empty(const String &p_from, int p_from_slot, const Vector2 &p_release_pos) { Node *node = graph->get_node(p_from); GraphNode *gn = Object::cast_to<GraphNode>(node); @@ -3408,23 +2995,22 @@ void VisualScriptEditor::_graph_connect_to_empty(const String &p_from, int p_fro return; } - StringName func = _get_function_of_node(p_from.to_int()); - - Ref<VisualScriptNode> vsn = script->get_node(func, p_from.to_int()); + Ref<VisualScriptNode> vsn = script->get_node(p_from.to_int()); if (!vsn.is_valid()) { return; } + if (vsn->get_output_value_port_count()) - port_action_pos = p_release_pos; + port_action_pos = p_release_pos; if (p_from_slot < vsn->get_output_sequence_port_count()) { port_action_node = p_from.to_int(); port_action_output = p_from_slot; - _port_action_menu(CREATE_ACTION, func); + _port_action_menu(CREATE_ACTION); } else { port_action_output = p_from_slot - vsn->get_output_sequence_port_count(); port_action_node = p_from.to_int(); - _port_action_menu(CREATE_CALL_SET_GET, func); + _port_action_menu(CREATE_CALL_SET_GET); } } @@ -3438,9 +3024,7 @@ VisualScriptNode::TypeGuess VisualScriptEditor::_guess_output_type(int p_port_ac visited_nodes.insert(p_port_action_node); - StringName func = _get_function_of_node(p_port_action_node); - - Ref<VisualScriptNode> node = script->get_node(func, p_port_action_node); + Ref<VisualScriptNode> node = script->get_node(p_port_action_node); if (!node.is_valid()) { return tg; @@ -3454,11 +3038,11 @@ VisualScriptNode::TypeGuess VisualScriptEditor::_guess_output_type(int p_port_ac g.type = pi.type; if (g.type == Variant::NIL || g.type == Variant::OBJECT) { - //any or object input, must further guess what this is + // Any or object input, must further guess what this is. int from_node; int from_port; - if (script->get_input_value_port_connection_source(func, p_port_action_node, i, &from_node, &from_port)) { + if (script->get_input_value_port_connection_source(p_port_action_node, i, &from_node, &from_port)) { g = _guess_output_type(from_node, from_port, visited_nodes); } else { Variant defval = node->get_default_input_value(i); @@ -3480,7 +3064,7 @@ VisualScriptNode::TypeGuess VisualScriptEditor::_guess_output_type(int p_port_ac return node->guess_output_type(in_guesses.ptrw(), p_port_action_output); } -void VisualScriptEditor::_port_action_menu(int p_option, const StringName &func) { +void VisualScriptEditor::_port_action_menu(int p_option) { Vector2 ofs = graph->get_scroll_ofs() + port_action_pos; if (graph->is_using_snap()) { int snap = graph->get_snap(); @@ -3503,8 +3087,8 @@ void VisualScriptEditor::_port_action_menu(int p_option, const StringName &func) n->set_base_type("Object"); } String type_string; - if (script->get_node(func, port_action_node)->get_output_value_port_count() > 0) { - type_string = script->get_node(func, port_action_node)->get_output_value_port_info(port_action_output).hint_string; + if (script->get_node(port_action_node)->get_output_value_port_count() > 0) { + type_string = script->get_node(port_action_node)->get_output_value_port_info(port_action_output).hint_string; } if (tg.type == Variant::OBJECT) { if (tg.script.is_valid()) { @@ -3519,7 +3103,7 @@ void VisualScriptEditor::_port_action_menu(int p_option, const StringName &func) } else { new_connect_node_select->select_from_basic_type(tg.type); } - // ensure that the dialog fits inside the graph + // Ensure that the dialog fits inside the graph. Vector2 pos = mouse_up_position; Size2 bounds = graph->get_global_position() + graph->get_size() - new_connect_node_select->get_size(); pos.x = pos.x > bounds.x ? bounds.x : pos.x; @@ -3529,8 +3113,8 @@ void VisualScriptEditor::_port_action_menu(int p_option, const StringName &func) case CREATE_ACTION: { VisualScriptNode::TypeGuess tg = _guess_output_type(port_action_node, port_action_output, vn); PropertyInfo property_info; - if (script->get_node(func, port_action_node)->get_output_value_port_count() > 0) { - property_info = script->get_node(func, port_action_node)->get_output_value_port_info(port_action_output); + if (script->get_node(port_action_node)->get_output_value_port_count() > 0) { + property_info = script->get_node(port_action_node)->get_output_value_port_info(port_action_output); } if (tg.type == Variant::OBJECT) { if (property_info.type == Variant::OBJECT && property_info.hint_string != String()) { @@ -3543,7 +3127,7 @@ void VisualScriptEditor::_port_action_menu(int p_option, const StringName &func) } else { new_connect_node_select->select_from_action(Variant::get_type_name(tg.type)); } - // ensure that the dialog fits inside the graph + // Ensure that the dialog fits inside the graph. Vector2 pos = mouse_up_position; Size2 bounds = graph->get_global_position() + graph->get_size() - new_connect_node_select->get_size(); pos.x = pos.x > bounds.x ? bounds.x : pos.x; @@ -3572,9 +3156,8 @@ void VisualScriptEditor::connect_data(Ref<VisualScriptNode> vnode_old, Ref<Visua if (port >= value_count) { port = 0; } - StringName func = _get_function_of_node(port_action_node); - undo_redo->add_do_method(script.ptr(), "data_connect", func, port_action_node, port, new_id, 0); - undo_redo->add_undo_method(script.ptr(), "data_disconnect", func, port_action_node, port, new_id, 0); + undo_redo->add_do_method(script.ptr(), "data_connect", port_action_node, port, new_id, 0); + undo_redo->add_undo_method(script.ptr(), "data_disconnect", port_action_node, port, new_id, 0); undo_redo->commit_action(); } @@ -3591,17 +3174,16 @@ void VisualScriptEditor::_selected_connect_node(const String &p_text, const Stri bool port_node_exists = true; - StringName func = _get_function_of_node(port_action_node); - if (func == StringName()) { - func = default_func; - port_node_exists = false; - } + // if (func == StringName()) { + // func = default_func; + // port_node_exists = false; + // } if (p_category == "visualscript") { Ref<VisualScriptNode> vnode_new = VisualScriptLanguage::singleton->create_node_from_name(p_text); Ref<VisualScriptNode> vnode_old; - if (port_node_exists) { - vnode_old = script->get_node(func, port_action_node); + if (port_node_exists && p_connecting) { + vnode_old = script->get_node(port_action_node); } int new_id = script->get_available_id(); @@ -3624,13 +3206,13 @@ void VisualScriptEditor::_selected_connect_node(const String &p_text, const Stri } undo_redo->create_action(TTR("Add Node")); - undo_redo->add_do_method(script.ptr(), "add_node", func, new_id, vnode_new, ofs); + undo_redo->add_do_method(script.ptr(), "add_node", new_id, vnode_new, ofs); if (vnode_old.is_valid() && p_connecting) { connect_seq(vnode_old, vnode_new, new_id); connect_data(vnode_old, vnode_new, new_id); } - undo_redo->add_undo_method(script.ptr(), "remove_node", func, new_id); + undo_redo->add_undo_method(script.ptr(), "remove_node", new_id); undo_redo->add_do_method(this, "_update_graph"); undo_redo->add_undo_method(this, "_update_graph"); undo_redo->commit_action(); @@ -3687,8 +3269,8 @@ void VisualScriptEditor::_selected_connect_node(const String &p_text, const Stri int new_id = script->get_available_id(); undo_redo->create_action(TTR("Add Node")); - undo_redo->add_do_method(script.ptr(), "add_node", func, new_id, vnode, ofs); - undo_redo->add_undo_method(script.ptr(), "remove_node", func, new_id); + undo_redo->add_do_method(script.ptr(), "add_node", new_id, vnode, ofs); + undo_redo->add_undo_method(script.ptr(), "remove_node", new_id); undo_redo->add_do_method(this, "_update_graph", new_id); undo_redo->add_undo_method(this, "_update_graph", new_id); undo_redo->commit_action(); @@ -3699,7 +3281,7 @@ void VisualScriptEditor::_selected_connect_node(const String &p_text, const Stri port_action_new_node = new_id; - Ref<VisualScriptNode> vsn = script->get_node(func, port_action_new_node); + Ref<VisualScriptNode> vsn = script->get_node(port_action_new_node); if (Object::cast_to<VisualScriptFunctionCall>(vsn.ptr())) { Ref<VisualScriptFunctionCall> vsfc = vsn; @@ -3713,10 +3295,9 @@ void VisualScriptEditor::_selected_connect_node(const String &p_text, const Stri vsfc->set_base_type(String("")); if (tg.gdclass != StringName()) { vsfc->set_base_type(tg.gdclass); - - } else if (script->get_node(func, port_action_node).is_valid()) { - PropertyHint hint = script->get_node(func, port_action_node)->get_output_value_port_info(port_action_output).hint; - String base_type = script->get_node(func, port_action_node)->get_output_value_port_info(port_action_output).hint_string; + } else if (script->get_node(port_action_node).is_valid()) { + PropertyHint hint = script->get_node(port_action_node)->get_output_value_port_info(port_action_output).hint; + String base_type = script->get_node(port_action_node)->get_output_value_port_info(port_action_output).hint_string; if (base_type != String() && hint == PROPERTY_HINT_TYPE_STRING) { vsfc->set_base_type(base_type); @@ -3749,9 +3330,9 @@ void VisualScriptEditor::_selected_connect_node(const String &p_text, const Stri if (tg.gdclass != StringName()) { vsp->set_base_type(tg.gdclass); - } else if (script->get_node(func, port_action_node).is_valid()) { - PropertyHint hint = script->get_node(func, port_action_node)->get_output_value_port_info(port_action_output).hint; - String base_type = script->get_node(func, port_action_node)->get_output_value_port_info(port_action_output).hint_string; + } else if (script->get_node(port_action_node).is_valid()) { + PropertyHint hint = script->get_node(port_action_node)->get_output_value_port_info(port_action_output).hint; + String base_type = script->get_node(port_action_node)->get_output_value_port_info(port_action_output).hint_string; if (base_type != String() && hint == PROPERTY_HINT_TYPE_STRING) { vsp->set_base_type(base_type); @@ -3779,9 +3360,9 @@ void VisualScriptEditor::_selected_connect_node(const String &p_text, const Stri if (tg.gdclass != StringName()) { vsp->set_base_type(tg.gdclass); - } else if (script->get_node(func, port_action_node).is_valid()) { - PropertyHint hint = script->get_node(func, port_action_node)->get_output_value_port_info(port_action_output).hint; - String base_type = script->get_node(func, port_action_node)->get_output_value_port_info(port_action_output).hint_string; + } else if (script->get_node(port_action_node).is_valid()) { + PropertyHint hint = script->get_node(port_action_node)->get_output_value_port_info(port_action_output).hint; + String base_type = script->get_node(port_action_node)->get_output_value_port_info(port_action_output).hint_string; if (base_type != String() && hint == PROPERTY_HINT_TYPE_STRING) { vsp->set_base_type(base_type); } @@ -3799,16 +3380,13 @@ void VisualScriptEditor::_selected_connect_node(const String &p_text, const Stri } } if (port_node_exists) { - Ref<VisualScriptNode> vnode_old = script->get_node(func, port_action_node); + Ref<VisualScriptNode> vnode_old = script->get_node(port_action_node); if (vnode_old.is_valid() && p_connecting) { connect_seq(vnode_old, vnode, port_action_new_node); connect_data(vnode_old, vnode, port_action_new_node); } } _update_graph(port_action_new_node); - if (port_node_exists) { - _update_graph_connections(); - } } void VisualScriptEditor::connect_seq(Ref<VisualScriptNode> vnode_old, Ref<VisualScriptNode> vnode_new, int new_id) { @@ -3827,29 +3405,27 @@ void VisualScriptEditor::connect_seq(Ref<VisualScriptNode> vnode_old, Ref<Visual return; } - StringName func = _get_function_of_node(port_action_node); - undo_redo->create_action(TTR("Connect Node Sequence")); int pass_port = -vnode_old->get_output_sequence_port_count() + 1; int return_port = port_action_output - 1; if (vnode_old->get_output_value_port_info(port_action_output).name == String("pass") && - !script->get_output_sequence_ports_connected(func, port_action_node).has(pass_port)) { - undo_redo->add_do_method(script.ptr(), "sequence_connect", func, port_action_node, pass_port, new_id); - undo_redo->add_undo_method(script.ptr(), "sequence_disconnect", func, port_action_node, pass_port, new_id); + !script->get_output_sequence_ports_connected(port_action_node).has(pass_port)) { + undo_redo->add_do_method(script.ptr(), "sequence_connect", port_action_node, pass_port, new_id); + undo_redo->add_undo_method(script.ptr(), "sequence_disconnect", port_action_node, pass_port, new_id); } else if (vnode_old->get_output_value_port_info(port_action_output).name == String("return") && - !script->get_output_sequence_ports_connected(func, port_action_node).has(return_port)) { - undo_redo->add_do_method(script.ptr(), "sequence_connect", func, port_action_node, return_port, new_id); - undo_redo->add_undo_method(script.ptr(), "sequence_disconnect", func, port_action_node, return_port, new_id); + !script->get_output_sequence_ports_connected(port_action_node).has(return_port)) { + undo_redo->add_do_method(script.ptr(), "sequence_connect", port_action_node, return_port, new_id); + undo_redo->add_undo_method(script.ptr(), "sequence_disconnect", port_action_node, return_port, new_id); } else { for (int port = 0; port < vnode_old->get_output_sequence_port_count(); port++) { int count = vnode_old->get_output_sequence_port_count(); - if (port_action_output < count && !script->get_output_sequence_ports_connected(func, port_action_node).has(port_action_output)) { - undo_redo->add_do_method(script.ptr(), "sequence_connect", func, port_action_node, port_action_output, new_id); - undo_redo->add_undo_method(script.ptr(), "sequence_disconnect", func, port_action_node, port_action_output, new_id); + if (port_action_output < count && !script->get_output_sequence_ports_connected(port_action_node).has(port_action_output)) { + undo_redo->add_do_method(script.ptr(), "sequence_connect", port_action_node, port_action_output, new_id); + undo_redo->add_undo_method(script.ptr(), "sequence_disconnect", port_action_node, port_action_output, new_id); break; - } else if (!script->get_output_sequence_ports_connected(func, port_action_node).has(port)) { - undo_redo->add_do_method(script.ptr(), "sequence_connect", func, port_action_node, port, new_id); - undo_redo->add_undo_method(script.ptr(), "sequence_disconnect", func, port_action_node, port, new_id); + } else if (!script->get_output_sequence_ports_connected(port_action_node).has(port)) { + undo_redo->add_do_method(script.ptr(), "sequence_connect", port_action_node, port, new_id); + undo_redo->add_undo_method(script.ptr(), "sequence_disconnect", port_action_node, port, new_id); break; } } @@ -3884,9 +3460,9 @@ void VisualScriptEditor::_selected_new_virtual_method(const String &p_text, cons Ref<VisualScriptFunction> func_node; func_node.instance(); func_node->set_name(name); - + int fn_id = script->get_available_id(); undo_redo->create_action(TTR("Add Function")); - undo_redo->add_do_method(script.ptr(), "add_function", name); + undo_redo->add_do_method(script.ptr(), "add_function", name, fn_id); for (int i = 0; i < minfo.arguments.size(); i++) { func_node->add_argument(minfo.arguments[i].type, minfo.arguments[i].name, -1, minfo.arguments[i].hint, minfo.arguments[i].hint_string); @@ -3894,14 +3470,17 @@ void VisualScriptEditor::_selected_new_virtual_method(const String &p_text, cons Vector2 ofs = _get_available_pos(); - undo_redo->add_do_method(script.ptr(), "add_node", name, script->get_available_id(), func_node, ofs); + undo_redo->add_do_method(script.ptr(), "add_node", fn_id, func_node, ofs); + undo_redo->add_undo_method(script.ptr(), "remove_node", fn_id); if (minfo.return_val.type != Variant::NIL || minfo.return_val.usage & PROPERTY_USAGE_NIL_IS_VARIANT) { Ref<VisualScriptReturn> ret_node; ret_node.instance(); ret_node->set_return_type(minfo.return_val.type); ret_node->set_enable_return_value(true); ret_node->set_name(name); - undo_redo->add_do_method(script.ptr(), "add_node", name, script->get_available_id() + 1, ret_node, _get_available_pos(false, ofs + Vector2(500, 0))); + int nid = script->get_available_id() + 1; + undo_redo->add_do_method(script.ptr(), "add_node", nid, ret_node, _get_available_pos(false, ofs + Vector2(500, 0))); + undo_redo->add_undo_method(script.ptr(), "remove_node", nid); } undo_redo->add_undo_method(script.ptr(), "remove_function", name); @@ -3916,21 +3495,16 @@ void VisualScriptEditor::_selected_new_virtual_method(const String &p_text, cons } void VisualScriptEditor::_cancel_connect_node() { - // ensure the cancel is done + // Ensure the cancel is done. port_action_new_node = -1; } -int VisualScriptEditor::_create_new_node_from_name(const String &p_text, const Vector2 &p_point, const StringName &p_func) { - StringName func = default_func; - if (p_func != StringName()) { - func = p_func; - } - +int VisualScriptEditor::_create_new_node_from_name(const String &p_text, const Vector2 &p_point) { Ref<VisualScriptNode> vnode = VisualScriptLanguage::singleton->create_node_from_name(p_text); int new_id = script->get_available_id(); undo_redo->create_action(TTR("Add Node")); - undo_redo->add_do_method(script.ptr(), "add_node", func, new_id, vnode, p_point); - undo_redo->add_undo_method(script.ptr(), "remove_node", func, new_id); + undo_redo->add_do_method(script.ptr(), "add_node", new_id, vnode, p_point); + undo_redo->add_undo_method(script.ptr(), "remove_node", new_id); undo_redo->add_do_method(this, "_update_graph"); undo_redo->add_undo_method(this, "_update_graph"); undo_redo->commit_action(); @@ -3938,7 +3512,7 @@ int VisualScriptEditor::_create_new_node_from_name(const String &p_text, const V } void VisualScriptEditor::_default_value_changed() { - Ref<VisualScriptNode> vsn = script->get_node(_get_function_of_node(editing_id), editing_id); + Ref<VisualScriptNode> vsn = script->get_node(editing_id); if (vsn.is_null()) { return; } @@ -3953,7 +3527,7 @@ void VisualScriptEditor::_default_value_changed() { } void VisualScriptEditor::_default_value_edited(Node *p_button, int p_id, int p_input_port) { - Ref<VisualScriptNode> vsn = script->get_node(_get_function_of_node(p_id), p_id); + Ref<VisualScriptNode> vsn = script->get_node(p_id); if (vsn.is_null()) { return; } @@ -3972,15 +3546,15 @@ void VisualScriptEditor::_default_value_edited(Node *p_button, int p_id, int p_i if (pinfo.type == Variant::NODE_PATH) { Node *edited_scene = get_tree()->get_edited_scene_root(); - if (edited_scene) { // Fixing an old crash bug ( Visual Script Crashes on editing NodePath with an empty scene open) + if (edited_scene) { // Fixing an old crash bug ( Visual Script Crashes on editing NodePath with an empty scene open). Node *script_node = _find_script_node(edited_scene, edited_scene, script); if (script_node) { - //pick a node relative to the script, IF the script exists + // Pick a node relative to the script, IF the script exists. pinfo.hint = PROPERTY_HINT_NODE_PATH_TO_EDITED_NODE; pinfo.hint_string = script_node->get_path(); } else { - //pick a path relative to edited scene + // Pick a path relative to edited scene. pinfo.hint = PROPERTY_HINT_NODE_PATH_TO_EDITED_NODE; pinfo.hint_string = get_tree()->get_edited_scene_root()->get_path(); } @@ -4078,11 +3652,8 @@ void VisualScriptEditor::_graph_ofs_changed(const Vector2 &p_ofs) { updating_graph = true; - // Just use the default func for all the properties that need to be handled for drawing rather than adding to the Visual Script Class - if (script->has_function(default_func)) { - script->set_function_scroll(default_func, graph->get_scroll_ofs() / EDSCALE); - script->set_edited(true); - } + script->set_scroll(graph->get_scroll_ofs() / EDSCALE); + script->set_edited(true); updating_graph = false; } @@ -4090,10 +3661,7 @@ void VisualScriptEditor::_comment_node_resized(const Vector2 &p_new_size, int p_ if (updating_graph) { return; } - - StringName func = _get_function_of_node(p_node); - - Ref<VisualScriptComment> vsc = script->get_node(func, p_node); + Ref<VisualScriptComment> vsc = script->get_node(p_node); if (vsc.is_null()) { return; } @@ -4131,8 +3699,7 @@ void VisualScriptEditor::_menu_option(int p_what) { if (gn) { if (gn->is_selected()) { int id = String(gn->get_name()).to_int(); - StringName func = _get_function_of_node(id); - Ref<VisualScriptNode> vsn = script->get_node(func, id); + Ref<VisualScriptNode> vsn = script->get_node(id); if (vsn.is_valid()) { vsn->set_breakpoint(!vsn->is_breakpoint()); reselect.push_back(gn->get_name()); @@ -4154,30 +3721,23 @@ void VisualScriptEditor::_menu_option(int p_what) { } break; case EDIT_COPY_NODES: case EDIT_CUT_NODES: { - if (!script->has_function(default_func)) { - break; - } - clipboard->nodes.clear(); clipboard->data_connections.clear(); clipboard->sequence_connections.clear(); - Set<String> funcs; for (int i = 0; i < graph->get_child_count(); i++) { GraphNode *gn = Object::cast_to<GraphNode>(graph->get_child(i)); if (gn) { if (gn->is_selected()) { - int id = String(gn->get_name()).to_int(); - StringName func = _get_function_of_node(id); - Ref<VisualScriptNode> node = script->get_node(func, id); + int id = gn->get_name().operator String().to_int(); + Ref<VisualScriptNode> node = script->get_node(id); if (Object::cast_to<VisualScriptFunction>(*node)) { EditorNode::get_singleton()->show_warning(TTR("Can't copy the function node.")); return; } if (node.is_valid()) { clipboard->nodes[id] = node->duplicate(true); - clipboard->nodes_positions[id] = script->get_node_position(func, id); - funcs.insert(String(func)); + clipboard->nodes_positions[id] = script->get_node_position(id); } } } @@ -4187,25 +3747,21 @@ void VisualScriptEditor::_menu_option(int p_what) { break; } - for (Set<String>::Element *F = funcs.front(); F; F = F->next()) { - List<VisualScript::SequenceConnection> sequence_connections; + List<VisualScript::SequenceConnection> sequence_connections; + script->get_sequence_connection_list(&sequence_connections); - script->get_sequence_connection_list(F->get(), &sequence_connections); - - for (List<VisualScript::SequenceConnection>::Element *E = sequence_connections.front(); E; E = E->next()) { - if (clipboard->nodes.has(E->get().from_node) && clipboard->nodes.has(E->get().to_node)) { - clipboard->sequence_connections.insert(E->get()); - } + for (List<VisualScript::SequenceConnection>::Element *E = sequence_connections.front(); E; E = E->next()) { + if (clipboard->nodes.has(E->get().from_node) && clipboard->nodes.has(E->get().to_node)) { + clipboard->sequence_connections.insert(E->get()); } + } - List<VisualScript::DataConnection> data_connections; - - script->get_data_connection_list(F->get(), &data_connections); + List<VisualScript::DataConnection> data_connections; + script->get_data_connection_list(&data_connections); - for (List<VisualScript::DataConnection>::Element *E = data_connections.front(); E; E = E->next()) { - if (clipboard->nodes.has(E->get().from_node) && clipboard->nodes.has(E->get().to_node)) { - clipboard->data_connections.insert(E->get()); - } + for (List<VisualScript::DataConnection>::Element *E = data_connections.front(); E; E = E->next()) { + if (clipboard->nodes.has(E->get().from_node) && clipboard->nodes.has(E->get().to_node)) { + clipboard->data_connections.insert(E->get()); } } if (p_what == EDIT_CUT_NODES) { @@ -4214,10 +3770,6 @@ void VisualScriptEditor::_menu_option(int p_what) { } break; case EDIT_PASTE_NODES: { - if (!script->has_function(default_func)) { - break; - } - if (clipboard->nodes.is_empty()) { EditorNode::get_singleton()->show_warning(TTR("Clipboard is empty!")); break; @@ -4233,15 +3785,11 @@ void VisualScriptEditor::_menu_option(int p_what) { Set<Vector2> existing_positions; { - List<StringName> functions; - script->get_function_list(&functions); - for (List<StringName>::Element *F = functions.front(); F; F = F->next()) { - List<int> nodes; - script->get_node_list(F->get(), &nodes); - for (List<int>::Element *E = nodes.front(); E; E = E->next()) { - Vector2 pos = script->get_node_position(F->get(), E->get()).snapped(Vector2(2, 2)); - existing_positions.insert(pos); - } + List<int> nodes; + script->get_node_list(&nodes); + for (List<int>::Element *E = nodes.front(); E; E = E->next()) { + Vector2 pos = script->get_node_position(E->get()).snapped(Vector2(2, 2)); + existing_positions.insert(pos); } } @@ -4259,18 +3807,18 @@ void VisualScriptEditor::_menu_option(int p_what) { paste_pos += Vector2(20, 20) * EDSCALE; } - undo_redo->add_do_method(script.ptr(), "add_node", default_func, new_id, node, paste_pos); - undo_redo->add_undo_method(script.ptr(), "remove_node", default_func, new_id); + undo_redo->add_do_method(script.ptr(), "add_node", new_id, node, paste_pos); + undo_redo->add_undo_method(script.ptr(), "remove_node", new_id); } for (Set<VisualScript::SequenceConnection>::Element *E = clipboard->sequence_connections.front(); E; E = E->next()) { - undo_redo->add_do_method(script.ptr(), "sequence_connect", default_func, remap[E->get().from_node], E->get().from_output, remap[E->get().to_node]); - undo_redo->add_undo_method(script.ptr(), "sequence_disconnect", default_func, remap[E->get().from_node], E->get().from_output, remap[E->get().to_node]); + undo_redo->add_do_method(script.ptr(), "sequence_connect", remap[E->get().from_node], E->get().from_output, remap[E->get().to_node]); + undo_redo->add_undo_method(script.ptr(), "sequence_disconnect", remap[E->get().from_node], E->get().from_output, remap[E->get().to_node]); } for (Set<VisualScript::DataConnection>::Element *E = clipboard->data_connections.front(); E; E = E->next()) { - undo_redo->add_do_method(script.ptr(), "data_connect", default_func, remap[E->get().from_node], E->get().from_port, remap[E->get().to_node], E->get().to_port); - undo_redo->add_undo_method(script.ptr(), "data_disconnect", default_func, remap[E->get().from_node], E->get().from_port, remap[E->get().to_node], E->get().to_port); + undo_redo->add_do_method(script.ptr(), "data_connect", remap[E->get().from_node], E->get().from_port, remap[E->get().to_node], E->get().to_port); + undo_redo->add_undo_method(script.ptr(), "data_disconnect", remap[E->get().from_node], E->get().from_port, remap[E->get().to_node], E->get().to_port); } undo_redo->add_do_method(this, "_update_graph"); @@ -4287,7 +3835,7 @@ void VisualScriptEditor::_menu_option(int p_what) { } } break; case EDIT_CREATE_FUNCTION: { - StringName function = ""; + // Create Function. Map<int, Ref<VisualScriptNode>> nodes; Set<int> selections; for (int i = 0; i < graph->get_child_count(); i++) { @@ -4295,20 +3843,14 @@ void VisualScriptEditor::_menu_option(int p_what) { if (gn) { if (gn->is_selected()) { int id = String(gn->get_name()).to_int(); - StringName func = _get_function_of_node(id); - Ref<VisualScriptNode> node = script->get_node(func, id); + Ref<VisualScriptNode> node = script->get_node(id); if (Object::cast_to<VisualScriptFunction>(*node)) { EditorNode::get_singleton()->show_warning(TTR("Can't create function with a function node.")); return; } if (node.is_valid()) { - if (func != function && function != StringName("")) { - EditorNode::get_singleton()->show_warning(TTR("Can't create function of nodes from nodes of multiple functions.")); - return; - } nodes.insert(id, node); selections.insert(id); - function = func; } } } @@ -4327,7 +3869,7 @@ void VisualScriptEditor::_menu_option(int p_what) { int start_node = -1; Set<int> end_nodes; if (nodes.size() == 1) { - Ref<VisualScriptNode> nd = script->get_node(function, nodes.front()->key()); + Ref<VisualScriptNode> nd = script->get_node(nodes.front()->key()); if (nd.is_valid() && nd->has_input_sequence_port()) { start_node = nodes.front()->key(); } else { @@ -4336,29 +3878,29 @@ void VisualScriptEditor::_menu_option(int p_what) { } } else { List<VisualScript::SequenceConnection> seqs; - script->get_sequence_connection_list(function, &seqs); + script->get_sequence_connection_list(&seqs); if (seqs.size() == 0) { - // in case there are no sequence connections - // select the top most node cause that's probably how - // the user wants to connect the nodes + // In case there are no sequence connections, + // select the top most node cause that's probably how, + // the user wants to connect the nodes. int top_nd = -1; Vector2 top; for (Map<int, Ref<VisualScriptNode>>::Element *E = nodes.front(); E; E = E->next()) { - Ref<VisualScriptNode> nd = script->get_node(function, E->key()); + Ref<VisualScriptNode> nd = script->get_node(E->key()); if (nd.is_valid() && nd->has_input_sequence_port()) { if (top_nd < 0) { top_nd = E->key(); - top = script->get_node_position(function, top_nd); + top = script->get_node_position(top_nd); } - Vector2 pos = script->get_node_position(function, E->key()); + Vector2 pos = script->get_node_position(E->key()); if (top.y > pos.y) { top_nd = E->key(); top = pos; } } } - Ref<VisualScriptNode> nd = script->get_node(function, top_nd); + Ref<VisualScriptNode> nd = script->get_node(top_nd); if (nd.is_valid() && nd->has_input_sequence_port()) { start_node = top_nd; } else { @@ -4366,7 +3908,7 @@ void VisualScriptEditor::_menu_option(int p_what) { return; } } else { - // pick the node with input sequence + // Pick the node with input sequence. Set<int> nodes_from; Set<int> nodes_to; for (List<VisualScript::SequenceConnection>::Element *E = seqs.front(); E; E = E->next()) { @@ -4387,13 +3929,13 @@ void VisualScriptEditor::_menu_option(int p_what) { nodes_to.insert(E->get().to_node); } - // to use to add return nodes + // To use to add return nodes. _get_ends(start_node, seqs, selections, end_nodes); if (start_node == -1) { - // if we still don't have a start node then - // run through the nodes and select the first tree node - // ie node without any input sequence but output sequence + // If we still don't have a start node then, + // run through the nodes and select the first tree node, + // ie node without any input sequence but output sequence. for (Set<int>::Element *E = nodes_from.front(); E; E = E->next()) { if (!nodes_to.has(E->get())) { start_node = E->get(); @@ -4404,20 +3946,20 @@ void VisualScriptEditor::_menu_option(int p_what) { } if (start_node == -1) { - return; // this should not happen, but just in case something goes wrong + return; // This should not happen, but just in case something goes wrong. } List<Variant::Type> inputs; // input types List<Pair<int, int>> input_connections; { List<VisualScript::DataConnection> dats; - script->get_data_connection_list(function, &dats); + script->get_data_connection_list(&dats); for (List<VisualScript::DataConnection>::Element *E = dats.front(); E; E = E->next()) { if (nodes.has(E->get().from_node) && nodes.has(E->get().to_node)) { datamove.insert(E->get()); } else if (!nodes.has(E->get().from_node) && nodes.has(E->get().to_node)) { - // add all these as inputs for the Function - Ref<VisualScriptNode> node = script->get_node(function, E->get().to_node); + // Add all these as inputs for the Function. + Ref<VisualScriptNode> node = script->get_node(E->get().to_node); if (node.is_valid()) { dataext.insert(E->get()); PropertyInfo pi = node->get_input_value_port_info(E->get().to_port); @@ -4429,59 +3971,55 @@ void VisualScriptEditor::_menu_option(int p_what) { } } } - - String new_fn = _validate_name("new_function"); - - Vector2 ofs = _get_available_pos(false, script->get_node_position(function, start_node) - Vector2(80, 150)); - - Ref<VisualScriptFunction> func_node; - func_node.instance(); - func_node->set_name(new_fn); - - undo_redo->create_action(TTR("Create Function")); - - undo_redo->add_do_method(script.ptr(), "add_function", new_fn); int fn_id = script->get_available_id(); - undo_redo->add_do_method(script.ptr(), "add_node", new_fn, fn_id, func_node, ofs); - undo_redo->add_undo_method(script.ptr(), "remove_function", new_fn); - undo_redo->add_do_method(this, "_update_members"); - undo_redo->add_undo_method(this, "_update_members"); - undo_redo->add_do_method(this, "emit_signal", "edited_script_changed"); - undo_redo->add_undo_method(this, "emit_signal", "edited_script_changed"); - - // Move the nodes + { + String new_fn = _validate_name("new_function"); - for (Map<int, Ref<VisualScriptNode>>::Element *E = nodes.front(); E; E = E->next()) { - undo_redo->add_do_method(script.ptr(), "remove_node", function, E->key()); - undo_redo->add_do_method(script.ptr(), "add_node", new_fn, E->key(), E->get(), script->get_node_position(function, E->key())); + Vector2 ofs = _get_available_pos(false, script->get_node_position(start_node) - Vector2(80, 150)); - // undo_redo->add_undo_method(script.ptr(), "remove_node", new_fn, E->key()); not needed cause we already remove the function :P - undo_redo->add_undo_method(script.ptr(), "add_node", function, E->key(), E->get(), script->get_node_position(function, E->key())); - } + Ref<VisualScriptFunction> func_node; + func_node.instance(); + func_node->set_name(new_fn); - for (Set<VisualScript::SequenceConnection>::Element *E = seqmove.front(); E; E = E->next()) { - undo_redo->add_do_method(script.ptr(), "sequence_connect", new_fn, E->get().from_node, E->get().from_output, E->get().to_node); - undo_redo->add_undo_method(script.ptr(), "sequence_connect", function, E->get().from_node, E->get().from_output, E->get().to_node); - } + undo_redo->create_action(TTR("Create Function")); - for (Set<VisualScript::DataConnection>::Element *E = datamove.front(); E; E = E->next()) { - undo_redo->add_do_method(script.ptr(), "data_connect", new_fn, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); - undo_redo->add_undo_method(script.ptr(), "data_connect", function, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); + undo_redo->add_do_method(script.ptr(), "add_function", new_fn, fn_id); + undo_redo->add_do_method(script.ptr(), "add_node", fn_id, func_node, ofs); + undo_redo->add_undo_method(script.ptr(), "remove_function", new_fn); + undo_redo->add_undo_method(script.ptr(), "remove_node", fn_id); + undo_redo->add_do_method(this, "_update_members"); + undo_redo->add_undo_method(this, "_update_members"); + undo_redo->add_do_method(this, "emit_signal", "edited_script_changed"); + undo_redo->add_undo_method(this, "emit_signal", "edited_script_changed"); + // Might make the system more intelligent by checking port from info. + int i = 0; + List<Pair<int, int>>::Element *F = input_connections.front(); + for (List<Variant::Type>::Element *E = inputs.front(); E && F; E = E->next(), F = F->next()) { + func_node->add_argument(E->get(), "arg_" + String::num_int64(i), i); + undo_redo->add_do_method(script.ptr(), "data_connect", fn_id, i, F->get().first, F->get().second); + i++; // increment i + } + // Ensure Preview Selection is of newly created function node. + if (selections.size()) { + EditorNode::get_singleton()->push_item(func_node.ptr()); + } } + // Move the nodes. - // Add undo for external connections as well so that it's easier to revert back and forth - // these didn't require do methods as it's already handled internally by other do calls + // Handles reconnection of sequence connections on undo, start here in case of issues. for (Set<VisualScript::SequenceConnection>::Element *E = seqext.front(); E; E = E->next()) { - undo_redo->add_undo_method(script.ptr(), "sequence_connect", function, E->get().from_node, E->get().from_output, E->get().to_node); + undo_redo->add_do_method(script.ptr(), "sequence_disconnect", E->get().from_node, E->get().from_output, E->get().to_node); + undo_redo->add_undo_method(script.ptr(), "sequence_connect", E->get().from_node, E->get().from_output, E->get().to_node); } for (Set<VisualScript::DataConnection>::Element *E = dataext.front(); E; E = E->next()) { - undo_redo->add_undo_method(script.ptr(), "data_connect", function, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); + undo_redo->add_do_method(script.ptr(), "data_disconnect", E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); + undo_redo->add_undo_method(script.ptr(), "data_connect", E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); } - // I don't really think we need support for non sequenced functions at this moment - undo_redo->add_do_method(script.ptr(), "sequence_connect", new_fn, fn_id, 0, start_node); + // I don't really think we need support for non sequenced functions at this moment. + undo_redo->add_do_method(script.ptr(), "sequence_connect", fn_id, 0, start_node); - // end nodes are mapped to the return nodes with data connections if possible + // Could fail with the new changes, start here when searching for bugs in create function shortcut. int m = 1; for (Set<int>::Element *G = end_nodes.front(); G; G = G->next()) { Ref<VisualScriptReturn> ret_node; @@ -4489,36 +4027,27 @@ void VisualScriptEditor::_menu_option(int p_what) { int ret_id = fn_id + (m++); selections.insert(ret_id); - Vector2 ofsi = _get_available_pos(false, script->get_node_position(function, G->get()) + Vector2(80, -100)); - undo_redo->add_do_method(script.ptr(), "add_node", new_fn, ret_id, ret_node, ofsi); - undo_redo->add_undo_method(script.ptr(), "remove_node", new_fn, ret_id); + Vector2 ofsi = _get_available_pos(false, script->get_node_position(G->get()) + Vector2(80, -100)); + undo_redo->add_do_method(script.ptr(), "add_node", ret_id, ret_node, ofsi); + undo_redo->add_undo_method(script.ptr(), "remove_node", ret_id); - undo_redo->add_do_method(script.ptr(), "sequence_connect", new_fn, G->get(), 0, ret_id); - // add data outputs from each of the end_nodes - Ref<VisualScriptNode> vsn = script->get_node(function, G->get()); + undo_redo->add_do_method(script.ptr(), "sequence_connect", G->get(), 0, ret_id); + // Add data outputs from each of the end_nodes. + Ref<VisualScriptNode> vsn = script->get_node(G->get()); if (vsn.is_valid() && vsn->get_output_value_port_count() > 0) { ret_node->set_enable_return_value(true); - // use the zeroth data port cause that's the likely one that is planned to be used + // Use the zeroth data port cause that's the likely one that is planned to be used. ret_node->set_return_type(vsn->get_output_value_port_info(0).type); - undo_redo->add_do_method(script.ptr(), "data_connect", new_fn, G->get(), 0, ret_id, 0); + undo_redo->add_do_method(script.ptr(), "data_connect", G->get(), 0, ret_id, 0); } } - // * might make the system more intelligent by checking port from info. - int i = 0; - List<Pair<int, int>>::Element *F = input_connections.front(); - for (List<Variant::Type>::Element *E = inputs.front(); E && F; E = E->next(), F = F->next()) { - func_node->add_argument(E->get(), "arg_" + String::num_int64(i), i); - undo_redo->add_do_method(script.ptr(), "data_connect", new_fn, fn_id, i, F->get().first, F->get().second); - i++; // increment i - } - undo_redo->add_do_method(this, "_update_graph"); undo_redo->add_undo_method(this, "_update_graph"); undo_redo->commit_action(); - // make sure all Nodes get marked for selection so that they can be moved together + // Make sure all Nodes get marked for selection so that they can be moved together. selections.insert(fn_id); for (int k = 0; k < graph->get_child_count(); k++) { GraphNode *gn = Object::cast_to<GraphNode>(graph->get_child(k)); @@ -4528,11 +4057,6 @@ void VisualScriptEditor::_menu_option(int p_what) { } } - // Ensure Preview Selection is of newly created function node - if (selections.size()) { - EditorNode::get_singleton()->push_item(func_node.ptr()); - } - } break; case REFRESH_GRAPH: { _update_graph(); @@ -4540,16 +4064,16 @@ void VisualScriptEditor::_menu_option(int p_what) { } } -// this is likely going to be very slow and I am not sure if I should keep it -// but I hope that it will not be a problem considering that we won't be creating functions so frequently -// and cyclic connections would be a problem but hopefully we won't let them get to this point +// This is likely going to be very slow and I am not sure if I should keep it, +// but I hope that it will not be a problem considering that we won't be creating functions so frequently, +// and cyclic connections would be a problem but hopefully we won't let them get to this point. void VisualScriptEditor::_get_ends(int p_node, const List<VisualScript::SequenceConnection> &p_seqs, const Set<int> &p_selected, Set<int> &r_end_nodes) { for (const List<VisualScript::SequenceConnection>::Element *E = p_seqs.front(); E; E = E->next()) { int from = E->get().from_node; int to = E->get().to_node; if (from == p_node && p_selected.has(to)) { - // this is an interior connection move forward to the to node + // This is an interior connection move forward to the to node. _get_ends(to, p_seqs, p_selected, r_end_nodes); } else if (from == p_node && !p_selected.has(to)) { r_end_nodes.insert(from); @@ -4609,34 +4133,29 @@ void VisualScriptEditor::_member_option(int p_option) { switch (member_type) { case MEMBER_FUNCTION: { if (p_option == MEMBER_REMOVE) { - //delete the function + // Delete the function. String name = member_name; - + List<String> lst; + int fn_node = script->get_function_node_id(name); undo_redo->create_action(TTR("Remove Function")); undo_redo->add_do_method(script.ptr(), "remove_function", name); - undo_redo->add_undo_method(script.ptr(), "add_function", name); - List<int> nodes; - script->get_node_list(name, &nodes); - for (List<int>::Element *E = nodes.front(); E; E = E->next()) { - undo_redo->add_undo_method(script.ptr(), "add_node", name, E->get(), script->get_node(name, E->get()), script->get_node_position(name, E->get())); - } - - List<VisualScript::SequenceConnection> seq_connections; - - script->get_sequence_connection_list(name, &seq_connections); - - for (List<VisualScript::SequenceConnection>::Element *E = seq_connections.front(); E; E = E->next()) { - undo_redo->add_undo_method(script.ptr(), "sequence_connect", name, E->get().from_node, E->get().from_output, E->get().to_node); + undo_redo->add_do_method(script.ptr(), "remove_node", fn_node); + undo_redo->add_undo_method(script.ptr(), "add_function", name, fn_node); + undo_redo->add_undo_method(script.ptr(), "add_node", fn_node, script->get_node(fn_node), script->get_node_position(fn_node)); + List<VisualScript::SequenceConnection> seqcons; + script->get_sequence_connection_list(&seqcons); + for (const List<VisualScript::SequenceConnection>::Element *E = seqcons.front(); E; E = E->next()) { + if (E->get().from_node == fn_node) { + undo_redo->add_undo_method(script.ptr(), "sequence_connect", fn_node, E->get().from_output, E->get().to_node); + } } - - List<VisualScript::DataConnection> data_connections; - - script->get_data_connection_list(name, &data_connections); - - for (List<VisualScript::DataConnection>::Element *E = data_connections.front(); E; E = E->next()) { - undo_redo->add_undo_method(script.ptr(), "data_connect", name, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); + List<VisualScript::DataConnection> datcons; + script->get_data_connection_list(&datcons); + for (const List<VisualScript::DataConnection>::Element *E = datcons.front(); E; E = E->next()) { + if (E->get().from_node == fn_node) { + undo_redo->add_undo_method(script.ptr(), "data_connect", fn_node, E->get().from_port, E->get().to_node, E->get().to_port); + } } - undo_redo->add_do_method(this, "_update_members"); undo_redo->add_undo_method(this, "_update_members"); undo_redo->add_do_method(this, "_update_graph"); diff --git a/modules/visual_script/visual_script_editor.h b/modules/visual_script/visual_script_editor.h index a788c00c61..bb6f194286 100644 --- a/modules/visual_script/visual_script_editor.h +++ b/modules/visual_script/visual_script_editor.h @@ -136,8 +136,6 @@ class VisualScriptEditor : public ScriptEditorBase { }; HashMap<StringName, Ref<StyleBox>> node_styles; - StringName edited_func; - StringName default_func; void _update_graph_connections(); void _update_graph(int p_only_id = -1); @@ -176,7 +174,7 @@ class VisualScriptEditor : public ScriptEditorBase { Vector2 mouse_up_position; - void _port_action_menu(int p_option, const StringName &p_func); + void _port_action_menu(int p_option); void connect_data(Ref<VisualScriptNode> vnode_old, Ref<VisualScriptNode> vnode, int new_id); @@ -184,13 +182,13 @@ class VisualScriptEditor : public ScriptEditorBase { void connect_seq(Ref<VisualScriptNode> vnode_old, Ref<VisualScriptNode> vnode_new, int new_id); void _cancel_connect_node(); - int _create_new_node_from_name(const String &p_text, const Vector2 &p_point, const StringName &p_func = StringName()); + int _create_new_node_from_name(const String &p_text, const Vector2 &p_point); void _selected_new_virtual_method(const String &p_text, const String &p_category, const bool p_connecting); int error_line; void _node_selected(Node *p_node); - void _center_on_node(const StringName &p_func, int p_id); + void _center_on_node(int p_id); void _node_filter_changed(const String &p_text); void _change_base_type_callback(); @@ -201,7 +199,7 @@ class VisualScriptEditor : public ScriptEditorBase { void _begin_node_move(); void _end_node_move(); - void _move_node(const StringName &p_func, int p_id, const Vector2 &p_to); + void _move_node(int p_id, const Vector2 &p_to); void _get_ends(int p_node, const List<VisualScript::SequenceConnection> &p_seqs, const Set<int> &p_selected, Set<int> &r_end_nodes); @@ -211,7 +209,7 @@ class VisualScriptEditor : public ScriptEditorBase { void _graph_disconnected(const String &p_from, int p_from_slot, const String &p_to, int p_to_slot); void _graph_connect_to_empty(const String &p_from, int p_from_slot, const Vector2 &p_release_pos); - void _node_ports_changed(const String &p_func, int p_id); + void _node_ports_changed(int p_id); void _node_create(); void _update_available_nodes(); @@ -228,10 +226,8 @@ class VisualScriptEditor : public ScriptEditorBase { void _port_name_focus_out(const Node *p_name_box, int p_id, int p_port, bool is_input); Vector2 _get_available_pos(bool centered = true, Vector2 ofs = Vector2()) const; - StringName _get_function_of_node(int p_id) const; - void _move_nodes_with_rescan(const StringName &p_func_from, const StringName &p_func_to, int p_id); - bool node_has_sequence_connections(const StringName &p_func, int p_id); + bool node_has_sequence_connections(int p_id); void _generic_search(String p_base_type = "", Vector2 pos = Vector2(), bool node_centered = false); diff --git a/modules/webxr/SCsub b/modules/webxr/SCsub new file mode 100644 index 0000000000..0a96af0811 --- /dev/null +++ b/modules/webxr/SCsub @@ -0,0 +1,11 @@ +#!/usr/bin/env python + +Import("env") +Import("env_modules") + +if env["platform"] == "javascript": + env.AddJSLibraries(["native/library_godot_webxr.js"]) + env.AddJSExterns(["native/webxr.externs.js"]) + +env_webxr = env_modules.Clone() +env_webxr.add_source_files(env.modules_sources, "*.cpp") diff --git a/modules/webxr/config.py b/modules/webxr/config.py new file mode 100644 index 0000000000..9efebed4e6 --- /dev/null +++ b/modules/webxr/config.py @@ -0,0 +1,14 @@ +def can_build(env, platform): + return True + + +def configure(env): + pass + + +def get_doc_classes(): + return ["WebXRInterface"] + + +def get_doc_path(): + return "doc_classes" diff --git a/modules/webxr/doc_classes/WebXRInterface.xml b/modules/webxr/doc_classes/WebXRInterface.xml new file mode 100644 index 0000000000..f178dc1bd5 --- /dev/null +++ b/modules/webxr/doc_classes/WebXRInterface.xml @@ -0,0 +1,253 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="WebXRInterface" inherits="XRInterface" version="3.2"> + <brief_description> + AR/VR interface using WebXR. + </brief_description> + <description> + WebXR is an open standard that allows creating VR and AR applications that run in the web browser. + As such, this interface is only available when running in an HTML5 export. + WebXR supports a wide range of devices, from the very capable (like Valve Index, HTC Vive, Oculus Rift and Quest) down to the much less capable (like Google Cardboard, Oculus Go, GearVR, or plain smartphones). + Since WebXR is based on Javascript, it makes extensive use of callbacks, which means that [WebXRInterface] is forced to use signals, where other AR/VR interfaces would instead use functions that return a result immediately. This makes [WebXRInterface] quite a bit more complicated to intialize than other AR/VR interfaces. + Here's the minimum code required to start an immersive VR session: + [codeblock] + var webxr_interface + var vr_supported = false + + func _ready(): + # We assume this node has a canvas layer with a button on it as a child. + # This button is for the user to consent to entering immersive VR mode. + $CanvasLayer/Button.connect("pressed", self, "_on_Button_pressed") + + webxr_interface = XRServer.find_interface("WebXR") + if webxr_interface: + # WebXR uses a lot of asynchronous callbacks, so we connect to various + # signals in order to receive them. + webxr_interface.connect("session_supported", self, "_webxr_session_supported") + webxr_interface.connect("session_started", self, "_webxr_session_started") + webxr_interface.connect("session_ended", self, "_webxr_session_ended") + webxr_interface.connect("session_failed", self, "_webxr_session_failed") + + # This returns immediately - our _webxr_session_supported() method + # (which we connected to the "session_supported" signal above) will + # be called sometime later to let us know if it's supported or not. + webxr_interface.is_session_supported("immersive-vr") + + func _webxr_session_supported(session_mode, supported): + if session_mode == 'immersive-vr': + vr_supported = supported + + func _on_Button_pressed(): + if not vr_supported: + OS.alert("Your browser doesn't support VR") + return + + # We want an immersive VR session, as opposed to AR ('immersive-ar') or a + # simple 3DoF viewer ('viewer'). + webxr_interface.session_mode = 'immersive-vr' + # 'bounded-floor' is room scale, 'local-floor' is a standing or sitting + # experience (it puts you 1.6m above the ground if you have 3DoF headset), + # whereas as 'local' puts you down at the XROrigin. + # This list means it'll first try to request 'bounded-floor', then + # fallback on 'local-floor' and ultimately 'local', if nothing else is + # supported. + webxr_interface.requested_reference_space_types = 'bounded-floor, local-floor, local' + # In order to use 'local-floor' or 'bounded-floor' we must also + # mark the features as required or optional. + webxr_interface.required_features = 'local-floor' + webxr_interface.optional_features = 'bounded-floor' + + # This will return false if we're unable to even request the session, + # however, it can still fail asynchronously later in the process, so we + # only know if it's really succeeded or failed when our + # _webxr_session_started() or _webxr_session_failed() methods are called. + if not webxr_interface.initialize(): + OS.alert("Failed to initialize") + return + + func _webxr_session_started(): + # This tells Godot to start rendering to the headset. + get_viewport().arvr = true + # This will be the reference space type you ultimately got, out of the + # types that you requested above. This is useful if you want the game to + # work a little differently in 'bounded-floor' versus 'local-floor'. + print ("Reference space type: " + webxr_interface.reference_space_type) + + func _webxr_session_ended(): + # If the user exits immersive mode, then we tell Godot to render to the web + # page again. + get_viewport().arvr = false + + func _webxr_session_failed(message): + OS.alert("Failed to initialize: " + message) + [/codeblock] + There are several ways to handle "controller" input: + - Using [XRController3D] nodes and their [signal XRController3D.button_pressed] and [signal XRController3D.button_released] signals. This is how controllers are typically handled in AR/VR apps in Godot, however, this will only work with advanced VR controllers like the Oculus Touch or Index controllers, for example. The buttons codes are defined by [url=https://immersive-web.github.io/webxr-gamepads-module/#xr-standard-gamepad-mapping]Section 3.3 of the WebXR Gamepads Module[/url]. + - Using [method Node._unhandled_input] and [InputEventJoypadButton] or [InputEventJoypadMotion]. This works the same as normal joypads, except the [member InputEvent.device] starts at 100, so the left controller is 100 and the right controller is 101, and the button codes are also defined by [url=https://immersive-web.github.io/webxr-gamepads-module/#xr-standard-gamepad-mapping]Section 3.3 of the WebXR Gamepads Module[/url]. + - Using the [signal select], [signal squeeze] and related signals. This method will work for both advanced VR controllers, and non-traditional "controllers" like a tap on the screen, a spoken voice command or a button press on the device itself. The [code]controller_id[/code] passed to these signals is the same id as used in [member XRController3D.controller_id]. + You can use one or all of these methods to allow your game or app to support a wider or narrower set of devices and input methods, or to allow more advanced interations with more advanced devices. + </description> + <tutorials> + <link title="How to make a VR game for WebXR with Godot">https://www.snopekgames.com/blog/2020/how-make-vr-game-webxr-godot</link> + </tutorials> + <methods> + <method name="is_session_supported"> + <return type="void"> + </return> + <argument index="0" name="session_mode" type="String"> + </argument> + <description> + Checks if the given [code]session_mode[/code] is supported by the user's browser. + Possible values come from [url=https://developer.mozilla.org/en-US/docs/Web/API/XRSessionMode]WebXR's XRSessionMode[/url], including: [code]"immersive-vr"[/code], [code]"immersive-ar"[/code], and [code]"inline"[/code]. + This method returns nothing, instead it emits the [signal session_supported] signal with the result. + </description> + </method> + <method name="get_controller"> + <return type="XRPositionalTracker"> + </return> + <argument index="0" name="controller_id" type="int"> + </argument> + <description> + Gets an [XRPositionalTracker] for the given [code]controller_id[/code]. + In the context of WebXR, a "controller" can be an advanced VR controller like the Oculus Touch or Index controllers, or even a tap on the screen, a spoken voice command or a button press on the device itself. When a non-traditional controller is used, interpret the position and orientation of the [XRPositionalTracker] as a ray pointing at the object the user wishes to interact with. + Use this method to get information about the controller that triggered one of these signals: + - [signal selectstart] + - [signal select] + - [signal selectend] + - [signal squeezestart] + - [signal squeeze] + - [signal squeezestart] + </description> + </method> + </methods> + <members> + <member name="session_mode" type="String" setter="set_session_mode" getter="get_session_mode"> + The session mode used by [method XRInterface.initialize] when setting up the WebXR session. + This doesn't have any effect on the interface when already initialized. + Possible values come from [url=https://developer.mozilla.org/en-US/docs/Web/API/XRSessionMode]WebXR's XRSessionMode[/url], including: [code]"immersive-vr"[/code], [code]"immersive-ar"[/code], and [code]"inline"[/code]. + </member> + <member name="required_features" type="String" setter="set_required_features" getter="get_required_features"> + A comma-seperated list of required features used by [method XRInterface.initialize] when setting up the WebXR session. + If a user's browser or device doesn't support one of the given features, initialization will fail and [signal session_failed] will be emitted. + This doesn't have any effect on the interface when already initialized. + Possible values come from [url=https://developer.mozilla.org/en-US/docs/Web/API/XRReferenceSpaceType]WebXR's XRReferenceSpaceType[/url]. If you want to use a particular reference space type, it must be listed in either [member required_features] or [member optional_features]. + </member> + <member name="optional_features" type="String" setter="set_optional_features" getter="get_optional_features"> + A comma-seperated list of optional features used by [method XRInterface.initialize] when setting up the WebXR session. + If a user's browser or device doesn't support one of the given features, initialization will continue, but you won't be able to use the requested feature. + This doesn't have any effect on the interface when already initialized. + Possible values come from [url=https://developer.mozilla.org/en-US/docs/Web/API/XRReferenceSpaceType]WebXR's XRReferenceSpaceType[/url]. If you want to use a particular reference space type, it must be listed in either [member required_features] or [member optional_features]. + </member> + <member name="requested_reference_space_types" type="String" setter="set_requested_reference_space_types" getter="get_requested_reference_space_types"> + A comma-seperated list of reference space types used by [method XRInterface.initialize] when setting up the WebXR session. + The reference space types are requested in order, and the first on supported by the users device or browser will be used. The [member reference_space_type] property contains the reference space type that was ultimately used. + This doesn't have any effect on the interface when already initialized. + Possible values come from [url=https://developer.mozilla.org/en-US/docs/Web/API/XRReferenceSpaceType]WebXR's XRReferenceSpaceType[/url]. If you want to use a particular reference space type, it must be listed in either [member required_features] or [member optional_features]. + </member> + <member name="reference_space_type" type="String" setter="" getter="get_reference_space_type"> + The reference space type (from the list of requested types set in the [member requested_reference_space_types] property), that was ultimately used by [method XRInterface.initialize] when setting up the WebXR session. + Possible values come from [url=https://developer.mozilla.org/en-US/docs/Web/API/XRReferenceSpaceType]WebXR's XRReferenceSpaceType[/url]. If you want to use a particular reference space type, it must be listed in either [member required_features] or [member optional_features]. + </member> + <member name="visibility_state" type="String" setter="" getter="get_visibility_state"> + Indicates if the WebXR session's imagery is visible to the user. + Possible values come from [url=https://developer.mozilla.org/en-US/docs/Web/API/XRVisibilityState]WebXR's XRVisibilityState[/url], including [code]"hidden"[/code], [code]"visible"[/code], and [code]"visible-blurred"[/code]. + </member> + <member name="bounds_geometry" type="PackedVector3Array" setter="" getter="get_bounds_geometry"> + The vertices of a polygon which defines the boundaries of the user's play area. + This will only be available if [member reference_space_type] is [code]"bounded-floor"[/code] and only on certain browsers and devices that support it. + The [signal reference_space_reset] signal may indicate when this changes. + </member> + </members> + <signals> + <signal name="session_supported"> + <argument index="0" name="session_mode" type="String"> + </argument> + <argument index="1" name="supported" type="bool"> + </argument> + <description> + Emitted by [method is_session_supported] to indicate if the given [code]session_mode[/code] is supported or not. + </description> + </signal> + <signal name="session_started"> + <description> + Emitted by [method XRInterface.initialize] if the session is successfully started. + At this point, it's safe to do [code]get_viewport().arvr = true[/code] to instruct Godot to start rendering to the AR/VR device. + </description> + </signal> + <signal name="session_failed"> + <argument index="0" name="message" type="String"> + </argument> + <description> + Emitted by [method XRInterface.initialize] if the session fails to start. + [code]message[/code] may optionally contain an error message from WebXR, or an empty string if no message is available. + </description> + </signal> + <signal name="session_ended"> + <description> + Emitted when the user ends the WebXR session (which can be done using UI from the browser or device). + At this point, you should do [code]get_viewport().arvr = false[/code] to instruct Godot to resume rendering to the screen. + </description> + </signal> + <signal name="selectstart"> + <argument index="0" name="controller_id" type="int"> + </argument> + <description> + Emitted when one of the "controllers" has started its "primary action". + Use [method get_controller] to get more information about the controller. + </description> + </signal> + <signal name="select"> + <argument index="0" name="controller_id" type="int"> + </argument> + <description> + Emitted after one of the "controllers" has finished its "primary action". + Use [method get_controller] to get more information about the controller. + </description> + </signal> + <signal name="selectend"> + <argument index="0" name="controller_id" type="int"> + </argument> + <description> + Emitted when one of the "controllers" has finished its "primary action". + Use [method get_controller] to get more information about the controller. + </description> + </signal> + <signal name="squeezestart"> + <argument index="0" name="controller_id" type="int"> + </argument> + <description> + Emitted when one of the "controllers" has started its "primary squeeze action". + Use [method get_controller] to get more information about the controller. + </description> + </signal> + <signal name="squeeze"> + <argument index="0" name="controller_id" type="int"> + </argument> + <description> + Emitted after one of the "controllers" has finished its "primary squeeze action". + Use [method get_controller] to get more information about the controller. + </description> + </signal> + <signal name="squeezeend"> + <argument index="0" name="controller_id" type="int"> + </argument> + <description> + Emitted when one of the "controllers" has finished its "primary squeeze action". + Use [method get_controller] to get more information about the controller. + </description> + </signal> + <signal name="visibility_state_changed"> + <description> + Emitted when [member visibility_state] has changed. + </description> + </signal> + <signal name="reference_space_reset"> + <description> + Emitted to indicate that the reference space has been reset or reconfigured. + When (or whether) this is emitted depends on the user's browser or device, but may include when the user has changed the dimensions of their play space (which you may be able to access via [member bounds_geometry]) or pressed/held a button to recenter their position. + See [url=https://developer.mozilla.org/en-US/docs/Web/API/XRReferenceSpace/reset_event]WebXR's XRReferenceSpace reset event[/url] for more information. + </description> + </signal> + </signals> + <constants> + </constants> +</class> diff --git a/modules/webxr/godot_webxr.h b/modules/webxr/godot_webxr.h new file mode 100644 index 0000000000..5e50ffde28 --- /dev/null +++ b/modules/webxr/godot_webxr.h @@ -0,0 +1,84 @@ +/*************************************************************************/ +/* godot_webxr.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 GODOT_WEBXR_H +#define GODOT_WEBXR_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include "stddef.h" + +typedef void (*GodotWebXRSupportedCallback)(char *p_session_mode, int p_supported); +typedef void (*GodotWebXRStartedCallback)(char *p_reference_space_type); +typedef void (*GodotWebXREndedCallback)(); +typedef void (*GodotWebXRFailedCallback)(char *p_message); +typedef void (*GodotWebXRControllerCallback)(); +typedef void (*GodotWebXRInputEventCallback)(char *p_signal_name, int p_controller_id); +typedef void (*GodotWebXRSimpleEventCallback)(char *p_signal_name); + +extern int godot_webxr_is_supported(); +extern void godot_webxr_is_session_supported(const char *p_session_mode, GodotWebXRSupportedCallback p_callback); + +extern void godot_webxr_initialize( + const char *p_session_mode, + const char *p_required_features, + const char *p_optional_features, + const char *p_requested_reference_space_types, + GodotWebXRStartedCallback p_on_session_started, + GodotWebXREndedCallback p_on_session_ended, + GodotWebXRFailedCallback p_on_session_failed, + GodotWebXRControllerCallback p_on_controller_changed, + GodotWebXRInputEventCallback p_on_input_event, + GodotWebXRSimpleEventCallback p_on_simple_event); +extern void godot_webxr_uninitialize(); + +extern int *godot_webxr_get_render_targetsize(); +extern float *godot_webxr_get_transform_for_eye(int p_eye); +extern float *godot_webxr_get_projection_for_eye(int p_eye); +extern int godot_webxr_get_external_texture_for_eye(int p_eye); +extern void godot_webxr_commit_for_eye(int p_eye); + +extern void godot_webxr_sample_controller_data(); +extern int godot_webxr_get_controller_count(); +extern int godot_webxr_is_controller_connected(int p_controller); +extern float *godot_webxr_get_controller_transform(int p_controller); +extern int *godot_webxr_get_controller_buttons(int p_controller); +extern int *godot_webxr_get_controller_axes(int p_controller); + +extern char *godot_webxr_get_visibility_state(); +extern int *godot_webxr_get_bounds_geometry(); + +#ifdef __cplusplus +} +#endif + +#endif /* GODOT_WEBXR_H */ diff --git a/modules/webxr/native/library_godot_webxr.js b/modules/webxr/native/library_godot_webxr.js new file mode 100644 index 0000000000..447045ed27 --- /dev/null +++ b/modules/webxr/native/library_godot_webxr.js @@ -0,0 +1,645 @@ +/*************************************************************************/ +/* library_godot_webxr.js */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 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. */ +/*************************************************************************/ +const GodotWebXR = { + $GodotWebXR__deps: ['$Browser', '$GL', '$GodotRuntime'], + $GodotWebXR: { + gl: null, + + texture_ids: [null, null], + textures: [null, null], + + session: null, + space: null, + frame: null, + pose: null, + + // Monkey-patch the requestAnimationFrame() used by Emscripten for the main + // loop, so that we can swap it out for XRSession.requestAnimationFrame() + // when an XR session is started. + orig_requestAnimationFrame: null, + requestAnimationFrame: (callback) => { + if (GodotWebXR.session && GodotWebXR.space) { + const onFrame = function (time, frame) { + GodotWebXR.frame = frame; + GodotWebXR.pose = frame.getViewerPose(GodotWebXR.space); + callback(time); + GodotWebXR.frame = null; + GodotWebXR.pose = null; + }; + GodotWebXR.session.requestAnimationFrame(onFrame); + } else { + GodotWebXR.orig_requestAnimationFrame(callback); + } + }, + monkeyPatchRequestAnimationFrame: (enable) => { + if (GodotWebXR.orig_requestAnimationFrame === null) { + GodotWebXR.orig_requestAnimationFrame = Browser.requestAnimationFrame; + } + Browser.requestAnimationFrame = enable + ? GodotWebXR.requestAnimationFrame : GodotWebXR.orig_requestAnimationFrame; + }, + pauseResumeMainLoop: () => { + // Once both GodotWebXR.session and GodotWebXR.space are set or + // unset, our monkey-patched requestAnimationFrame() should be + // enabled or disabled. When using the WebXR API Emulator, this + // gets picked up automatically, however, in the Oculus Browser + // on the Quest, we need to pause and resume the main loop. + Browser.pauseAsyncCallbacks(); + Browser.mainLoop.pause(); + window.setTimeout(function () { + Browser.resumeAsyncCallbacks(); + Browser.mainLoop.resume(); + }, 0); + }, + + // Some custom WebGL code for blitting our eye textures to the + // framebuffer we get from WebXR. + shaderProgram: null, + programInfo: null, + buffer: null, + // Vertex shader source. + vsSource: ` + const vec2 scale = vec2(0.5, 0.5); + attribute vec4 aVertexPosition; + + varying highp vec2 vTextureCoord; + + void main () { + gl_Position = aVertexPosition; + vTextureCoord = aVertexPosition.xy * scale + scale; + } + `, + // Fragment shader source. + fsSource: ` + varying highp vec2 vTextureCoord; + + uniform sampler2D uSampler; + + void main() { + gl_FragColor = texture2D(uSampler, vTextureCoord); + } + `, + + initShaderProgram: (gl, vsSource, fsSource) => { + const vertexShader = GodotWebXR.loadShader(gl, gl.VERTEX_SHADER, vsSource); + const fragmentShader = GodotWebXR.loadShader(gl, gl.FRAGMENT_SHADER, fsSource); + + const shaderProgram = gl.createProgram(); + gl.attachShader(shaderProgram, vertexShader); + gl.attachShader(shaderProgram, fragmentShader); + gl.linkProgram(shaderProgram); + + if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) { + GodotRuntime.error(`Unable to initialize the shader program: ${gl.getProgramInfoLog(shaderProgram)}`); + return null; + } + + return shaderProgram; + }, + loadShader: (gl, type, source) => { + const shader = gl.createShader(type); + gl.shaderSource(shader, source); + gl.compileShader(shader); + + if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { + GodotRuntime.error(`An error occurred compiling the shader: ${gl.getShaderInfoLog(shader)}`); + gl.deleteShader(shader); + return null; + } + + return shader; + }, + initBuffer: (gl) => { + const positionBuffer = gl.createBuffer(); + gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer); + const positions = [ + -1.0, -1.0, + 1.0, -1.0, + -1.0, 1.0, + 1.0, 1.0, + ]; + gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW); + return positionBuffer; + }, + blitTexture: (gl, texture) => { + if (GodotWebXR.shaderProgram === null) { + GodotWebXR.shaderProgram = GodotWebXR.initShaderProgram(gl, GodotWebXR.vsSource, GodotWebXR.fsSource); + GodotWebXR.programInfo = { + program: GodotWebXR.shaderProgram, + attribLocations: { + vertexPosition: gl.getAttribLocation(GodotWebXR.shaderProgram, 'aVertexPosition'), + }, + uniformLocations: { + uSampler: gl.getUniformLocation(GodotWebXR.shaderProgram, 'uSampler'), + }, + }; + GodotWebXR.buffer = GodotWebXR.initBuffer(gl); + } + + const orig_program = gl.getParameter(gl.CURRENT_PROGRAM); + gl.useProgram(GodotWebXR.shaderProgram); + + gl.bindBuffer(gl.ARRAY_BUFFER, GodotWebXR.buffer); + gl.vertexAttribPointer(GodotWebXR.programInfo.attribLocations.vertexPosition, 2, gl.FLOAT, false, 0, 0); + gl.enableVertexAttribArray(GodotWebXR.programInfo.attribLocations.vertexPosition); + + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, texture); + gl.uniform1i(GodotWebXR.programInfo.uniformLocations.uSampler, 0); + + gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); + + // Restore state. + gl.bindTexture(gl.TEXTURE_2D, null); + gl.disableVertexAttribArray(GodotWebXR.programInfo.attribLocations.vertexPosition); + gl.bindBuffer(gl.ARRAY_BUFFER, null); + gl.useProgram(orig_program); + }, + + // Holds the controllers list between function calls. + controllers: [], + + // Updates controllers array, where the left hand (or sole tracker) is + // the first element, and the right hand is the second element, and any + // others placed at the 3rd position and up. + sampleControllers: () => { + if (!GodotWebXR.session || !GodotWebXR.frame) { + return; + } + + let other_index = 2; + const controllers = []; + GodotWebXR.session.inputSources.forEach((input_source) => { + if (input_source.targetRayMode === 'tracked-pointer') { + if (input_source.handedness === 'right') { + controllers[1] = input_source; + } else if (input_source.handedness === 'left' || !controllers[0]) { + controllers[0] = input_source; + } + } else { + controllers[other_index++] = input_source; + } + }); + GodotWebXR.controllers = controllers; + }, + + getControllerId: (input_source) => GodotWebXR.controllers.indexOf(input_source), + }, + + godot_webxr_is_supported__proxy: 'sync', + godot_webxr_is_supported__sig: 'i', + godot_webxr_is_supported: function () { + return !!navigator.xr; + }, + + godot_webxr_is_session_supported__proxy: 'sync', + godot_webxr_is_session_supported__sig: 'vii', + godot_webxr_is_session_supported: function (p_session_mode, p_callback) { + const session_mode = GodotRuntime.parseString(p_session_mode); + const cb = GodotRuntime.get_func(p_callback); + if (navigator.xr) { + navigator.xr.isSessionSupported(session_mode).then(function (supported) { + const c_str = GodotRuntime.allocString(session_mode); + cb(c_str, supported ? 1 : 0); + GodotRuntime.free(c_str); + }); + } else { + const c_str = GodotRuntime.allocString(session_mode); + cb(c_str, 0); + GodotRuntime.free(c_str); + } + }, + + godot_webxr_initialize__deps: ['emscripten_webgl_get_current_context'], + godot_webxr_initialize__proxy: 'sync', + godot_webxr_initialize__sig: 'viiiiiiiiii', + godot_webxr_initialize: function (p_session_mode, p_required_features, p_optional_features, p_requested_reference_spaces, p_on_session_started, p_on_session_ended, p_on_session_failed, p_on_controller_changed, p_on_input_event, p_on_simple_event) { + GodotWebXR.monkeyPatchRequestAnimationFrame(true); + + const session_mode = GodotRuntime.parseString(p_session_mode); + const required_features = GodotRuntime.parseString(p_required_features).split(',').map((s) => s.trim()).filter((s) => s !== ''); + const optional_features = GodotRuntime.parseString(p_optional_features).split(',').map((s) => s.trim()).filter((s) => s !== ''); + const requested_reference_space_types = GodotRuntime.parseString(p_requested_reference_spaces).split(',').map((s) => s.trim()); + const onstarted = GodotRuntime.get_func(p_on_session_started); + const onended = GodotRuntime.get_func(p_on_session_ended); + const onfailed = GodotRuntime.get_func(p_on_session_failed); + const oncontroller = GodotRuntime.get_func(p_on_controller_changed); + const oninputevent = GodotRuntime.get_func(p_on_input_event); + const onsimpleevent = GodotRuntime.get_func(p_on_simple_event); + + const session_init = {}; + if (required_features.length > 0) { + session_init['requiredFeatures'] = required_features; + } + if (optional_features.length > 0) { + session_init['optionalFeatures'] = optional_features; + } + + navigator.xr.requestSession(session_mode, session_init).then(function (session) { + GodotWebXR.session = session; + + session.addEventListener('end', function (evt) { + onended(); + }); + + session.addEventListener('inputsourceschange', function (evt) { + let controller_changed = false; + [evt.added, evt.removed].forEach((lst) => { + lst.forEach((input_source) => { + if (input_source.targetRayMode === 'tracked-pointer') { + controller_changed = true; + } + }); + }); + if (controller_changed) { + oncontroller(); + } + }); + + ['selectstart', 'select', 'selectend', 'squeezestart', 'squeeze', 'squeezeend'].forEach((input_event) => { + session.addEventListener(input_event, function (evt) { + const c_str = GodotRuntime.allocString(input_event); + oninputevent(c_str, GodotWebXR.getControllerId(evt.inputSource)); + GodotRuntime.free(c_str); + }); + }); + + session.addEventListener('visibilitychange', function (evt) { + const c_str = GodotRuntime.allocString('visibility_state_changed'); + onsimpleevent(c_str); + GodotRuntime.free(c_str); + }); + + const gl_context_handle = _emscripten_webgl_get_current_context(); // eslint-disable-line no-undef + const gl = GL.getContext(gl_context_handle).GLctx; + GodotWebXR.gl = gl; + + gl.makeXRCompatible().then(function () { + session.updateRenderState({ + baseLayer: new XRWebGLLayer(session, gl), + }); + + function onReferenceSpaceSuccess(reference_space, reference_space_type) { + GodotWebXR.space = reference_space; + + // Using reference_space.addEventListener() crashes when + // using the polyfill with the WebXR Emulator extension, + // so we set the event property instead. + reference_space.onreset = function (evt) { + const c_str = GodotRuntime.allocString('reference_space_reset'); + onsimpleevent(c_str); + GodotRuntime.free(c_str); + }; + + // Now that both GodotWebXR.session and GodotWebXR.space are + // set, we need to pause and resume the main loop for the XR + // main loop to kick in. + GodotWebXR.pauseResumeMainLoop(); + + // Call in setTimeout() so that errors in the onstarted() + // callback don't bubble up here and cause Godot to try the + // next reference space. + window.setTimeout(function () { + const c_str = GodotRuntime.allocString(reference_space_type); + onstarted(c_str); + GodotRuntime.free(c_str); + }, 0); + } + + function requestReferenceSpace() { + const reference_space_type = requested_reference_space_types.shift(); + session.requestReferenceSpace(reference_space_type) + .then((refSpace) => { + onReferenceSpaceSuccess(refSpace, reference_space_type); + }) + .catch(() => { + if (requested_reference_space_types.length === 0) { + const c_str = GodotRuntime.allocString('Unable to get any of the requested reference space types'); + onfailed(c_str); + GodotRuntime.free(c_str); + } else { + requestReferenceSpace(); + } + }); + } + + requestReferenceSpace(); + }).catch(function (error) { + const c_str = GodotRuntime.allocString(`Unable to make WebGL context compatible with WebXR: ${error}`); + onfailed(c_str); + GodotRuntime.free(c_str); + }); + }).catch(function (error) { + const c_str = GodotRuntime.allocString(`Unable to start session: ${error}`); + onfailed(c_str); + GodotRuntime.free(c_str); + }); + }, + + godot_webxr_uninitialize__proxy: 'sync', + godot_webxr_uninitialize__sig: 'v', + godot_webxr_uninitialize: function () { + if (GodotWebXR.session) { + GodotWebXR.session.end() + // Prevent exception when session has already ended. + .catch((e) => { }); + } + + // Clean-up the textures we allocated for each view. + const gl = GodotWebXR.gl; + for (let i = 0; i < GodotWebXR.textures.length; i++) { + const texture = GodotWebXR.textures[i]; + if (texture !== null) { + gl.deleteTexture(texture); + } + GodotWebXR.textures[i] = null; + GodotWebXR.texture_ids[i] = null; + } + + GodotWebXR.session = null; + GodotWebXR.space = null; + GodotWebXR.frame = null; + GodotWebXR.pose = null; + + // Disable the monkey-patched window.requestAnimationFrame() and + // pause/restart the main loop to activate it on all platforms. + GodotWebXR.monkeyPatchRequestAnimationFrame(false); + GodotWebXR.pauseResumeMainLoop(); + }, + + godot_webxr_get_render_targetsize__proxy: 'sync', + godot_webxr_get_render_targetsize__sig: 'i', + godot_webxr_get_render_targetsize: function () { + if (!GodotWebXR.session || !GodotWebXR.pose) { + return 0; + } + + const glLayer = GodotWebXR.session.renderState.baseLayer; + const view = GodotWebXR.pose.views[0]; + const viewport = glLayer.getViewport(view); + + const buf = GodotRuntime.malloc(2 * 4); + GodotRuntime.setHeapValue(buf + 0, viewport.width, 'i32'); + GodotRuntime.setHeapValue(buf + 4, viewport.height, 'i32'); + return buf; + }, + + godot_webxr_get_transform_for_eye__proxy: 'sync', + godot_webxr_get_transform_for_eye__sig: 'ii', + godot_webxr_get_transform_for_eye: function (p_eye) { + if (!GodotWebXR.session || !GodotWebXR.pose) { + return 0; + } + + const views = GodotWebXR.pose.views; + let matrix; + if (p_eye === 0) { + matrix = GodotWebXR.pose.transform.matrix; + } else { + matrix = views[p_eye - 1].transform.matrix; + } + const buf = GodotRuntime.malloc(16 * 4); + for (let i = 0; i < 16; i++) { + GodotRuntime.setHeapValue(buf + (i * 4), matrix[i], 'float'); + } + return buf; + }, + + godot_webxr_get_projection_for_eye__proxy: 'sync', + godot_webxr_get_projection_for_eye__sig: 'ii', + godot_webxr_get_projection_for_eye: function (p_eye) { + if (!GodotWebXR.session || !GodotWebXR.pose) { + return 0; + } + + const view_index = (p_eye === 2 /* ARVRInterface::EYE_RIGHT */) ? 1 : 0; + const matrix = GodotWebXR.pose.views[view_index].projectionMatrix; + const buf = GodotRuntime.malloc(16 * 4); + for (let i = 0; i < 16; i++) { + GodotRuntime.setHeapValue(buf + (i * 4), matrix[i], 'float'); + } + return buf; + }, + + godot_webxr_get_external_texture_for_eye__proxy: 'sync', + godot_webxr_get_external_texture_for_eye__sig: 'ii', + godot_webxr_get_external_texture_for_eye: function (p_eye) { + if (!GodotWebXR.session || !GodotWebXR.pose) { + return 0; + } + + const view_index = (p_eye === 2 /* ARVRInterface::EYE_RIGHT */) ? 1 : 0; + if (GodotWebXR.texture_ids[view_index]) { + return GodotWebXR.texture_ids[view_index]; + } + + const glLayer = GodotWebXR.session.renderState.baseLayer; + const view = GodotWebXR.pose.views[view_index]; + const viewport = glLayer.getViewport(view); + const gl = GodotWebXR.gl; + + const texture = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, texture); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, viewport.width, viewport.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); + gl.bindTexture(gl.TEXTURE_2D, null); + + const texture_id = GL.getNewId(GL.textures); + GL.textures[texture_id] = texture; + GodotWebXR.textures[view_index] = texture; + GodotWebXR.texture_ids[view_index] = texture_id; + return texture_id; + }, + + godot_webxr_commit_for_eye__proxy: 'sync', + godot_webxr_commit_for_eye__sig: 'vi', + godot_webxr_commit_for_eye: function (p_eye) { + if (!GodotWebXR.session || !GodotWebXR.pose) { + return; + } + + const view_index = (p_eye === 2 /* ARVRInterface::EYE_RIGHT */) ? 1 : 0; + const glLayer = GodotWebXR.session.renderState.baseLayer; + const view = GodotWebXR.pose.views[view_index]; + const viewport = glLayer.getViewport(view); + const gl = GodotWebXR.gl; + + const orig_framebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING); + const orig_viewport = gl.getParameter(gl.VIEWPORT); + + // Bind to WebXR's framebuffer. + gl.bindFramebuffer(gl.FRAMEBUFFER, glLayer.framebuffer); + gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height); + + GodotWebXR.blitTexture(gl, GodotWebXR.textures[view_index]); + + // Restore state. + gl.bindFramebuffer(gl.FRAMEBUFFER, orig_framebuffer); + gl.viewport(orig_viewport[0], orig_viewport[1], orig_viewport[2], orig_viewport[3]); + }, + + godot_webxr_sample_controller_data__proxy: 'sync', + godot_webxr_sample_controller_data__sig: 'v', + godot_webxr_sample_controller_data: function () { + GodotWebXR.sampleControllers(); + }, + + godot_webxr_get_controller_count__proxy: 'sync', + godot_webxr_get_controller_count__sig: 'i', + godot_webxr_get_controller_count: function () { + if (!GodotWebXR.session || !GodotWebXR.frame) { + return 0; + } + return GodotWebXR.controllers.length; + }, + + godot_webxr_is_controller_connected__proxy: 'sync', + godot_webxr_is_controller_connected__sig: 'ii', + godot_webxr_is_controller_connected: function (p_controller) { + if (!GodotWebXR.session || !GodotWebXR.frame) { + return false; + } + return !!GodotWebXR.controllers[p_controller]; + }, + + godot_webxr_get_controller_transform__proxy: 'sync', + godot_webxr_get_controller_transform__sig: 'ii', + godot_webxr_get_controller_transform: function (p_controller) { + if (!GodotWebXR.session || !GodotWebXR.frame) { + return 0; + } + + const controller = GodotWebXR.controllers[p_controller]; + if (!controller) { + return 0; + } + + const frame = GodotWebXR.frame; + const space = GodotWebXR.space; + + const pose = frame.getPose(controller.targetRaySpace, space); + if (!pose) { + // This can mean that the controller lost tracking. + return 0; + } + const matrix = pose.transform.matrix; + + const buf = GodotRuntime.malloc(16 * 4); + for (let i = 0; i < 16; i++) { + GodotRuntime.setHeapValue(buf + (i * 4), matrix[i], 'float'); + } + return buf; + }, + + godot_webxr_get_controller_buttons__proxy: 'sync', + godot_webxr_get_controller_buttons__sig: 'ii', + godot_webxr_get_controller_buttons: function (p_controller) { + if (GodotWebXR.controllers.length === 0) { + return 0; + } + + const controller = GodotWebXR.controllers[p_controller]; + if (!controller || !controller.gamepad) { + return 0; + } + + const button_count = controller.gamepad.buttons.length; + + const buf = GodotRuntime.malloc((button_count + 1) * 4); + GodotRuntime.setHeapValue(buf, button_count, 'i32'); + for (let i = 0; i < button_count; i++) { + GodotRuntime.setHeapValue(buf + 4 + (i * 4), controller.gamepad.buttons[i].value, 'float'); + } + return buf; + }, + + godot_webxr_get_controller_axes__proxy: 'sync', + godot_webxr_get_controller_axes__sig: 'ii', + godot_webxr_get_controller_axes: function (p_controller) { + if (GodotWebXR.controllers.length === 0) { + return 0; + } + + const controller = GodotWebXR.controllers[p_controller]; + if (!controller || !controller.gamepad) { + return 0; + } + + const axes_count = controller.gamepad.axes.length; + + const buf = GodotRuntime.malloc((axes_count + 1) * 4); + GodotRuntime.setHeapValue(buf, axes_count, 'i32'); + for (let i = 0; i < axes_count; i++) { + GodotRuntime.setHeapValue(buf + 4 + (i * 4), controller.gamepad.axes[i], 'float'); + } + return buf; + }, + + godot_webxr_get_visibility_state__proxy: 'sync', + godot_webxr_get_visibility_state__sig: 'i', + godot_webxr_get_visibility_state: function () { + if (!GodotWebXR.session || !GodotWebXR.session.visibilityState) { + return 0; + } + + return GodotRuntime.allocString(GodotWebXR.session.visibilityState); + }, + + godot_webxr_get_bounds_geometry__proxy: 'sync', + godot_webxr_get_bounds_geometry__sig: 'i', + godot_webxr_get_bounds_geometry: function () { + if (!GodotWebXR.space || !GodotWebXR.space.boundsGeometry) { + return 0; + } + + const point_count = GodotWebXR.space.boundsGeometry.length; + if (point_count === 0) { + return 0; + } + + const buf = GodotRuntime.malloc(((point_count * 3) + 1) * 4); + GodotRuntime.setHeapValue(buf, point_count, 'i32'); + for (let i = 0; i < point_count; i++) { + const point = GodotWebXR.space.boundsGeometry[i]; + GodotRuntime.setHeapValue(buf + ((i * 3) + 1) * 4, point.x, 'float'); + GodotRuntime.setHeapValue(buf + ((i * 3) + 2) * 4, point.y, 'float'); + GodotRuntime.setHeapValue(buf + ((i * 3) + 3) * 4, point.z, 'float'); + } + + return buf; + }, +}; + +autoAddDeps(GodotWebXR, '$GodotWebXR'); +mergeInto(LibraryManager.library, GodotWebXR); diff --git a/modules/webxr/native/webxr.externs.js b/modules/webxr/native/webxr.externs.js new file mode 100644 index 0000000000..03dc05bc83 --- /dev/null +++ b/modules/webxr/native/webxr.externs.js @@ -0,0 +1,499 @@ +/** + * @type {XR} + */ +Navigator.prototype.xr; + +/** + * @constructor + */ +function XRSessionInit() {}; + +/** + * @type {Array<string>} + */ +XRSessionInit.prototype.requiredFeatures; + +/** + * @type {Array<string>} + */ +XRSessionInit.prototype.optionalFeatures; + +/** + * @constructor + */ +function XR() {} + +/** + * @type {?function (Event)} + */ +XR.prototype.ondevicechanged; + +/** + * @param {string} mode + * + * @return {!Promise<boolean>} + */ +XR.prototype.isSessionSupported = function(mode) {} + +/** + * @param {string} mode + * @param {XRSessionInit} options + * + * @return {!Promise<XRSession>} + */ +XR.prototype.requestSession = function(mode, options) {} + +/** + * @constructor + */ +function XRSession() {} + +/** + * @type {XRRenderState} + */ +XRSession.prototype.renderState; + +/** + * @type {Array<XRInputSource>} + */ +XRSession.prototype.inputSources; + +/** + * @type {string} + */ +XRSession.prototype.visibilityState; + +/** + * @type {?function (Event)} + */ +XRSession.prototype.onend; + +/** + * @type {?function (XRInputSourcesChangeEvent)} + */ +XRSession.prototype.oninputsourceschange; + +/** + * @type {?function (XRInputSourceEvent)} + */ +XRSession.prototype.onselectstart; + +/** + * @type {?function (XRInputSourceEvent)} + */ +XRSession.prototype.onselect; + +/** + * @type {?function (XRInputSourceEvent)} + */ +XRSession.prototype.onselectend; + +/** + * @type {?function (XRInputSourceEvent)} + */ +XRSession.prototype.onsqueezestart; + +/** + * @type {?function (XRInputSourceEvent)} + */ +XRSession.prototype.onsqueeze; + +/** + * @type {?function (XRInputSourceEvent)} + */ +XRSession.prototype.onsqueezeend; + +/** + * @type {?function (Event)} + */ +XRSession.prototype.onvisibilitychange; + +/** + * @param {XRRenderStateInit} state + * @return {void} + */ +XRSession.prototype.updateRenderState = function (state) {}; + +/** + * @param {XRFrameRequestCallback} callback + * @return {number} + */ +XRSession.prototype.requestAnimationFrame = function (callback) {}; + +/** + * @param {number} handle + * @return {void} + */ +XRSession.prototype.cancelAnimationFrame = function (handle) {}; + +/** + * @return {Promise<void>} + */ +XRSession.prototype.end = function () {}; + +/** + * @param {string} referenceSpaceType + * @return {Promise<XRReferenceSpace>} + */ +XRSession.prototype.requestReferenceSpace = function (referenceSpaceType) {}; + +/** + * @typedef {function(number, XRFrame): undefined} + */ +var XRFrameRequestCallback; + +/** + * @constructor + */ +function XRRenderStateInit() {} + +/** + * @type {number} + */ +XRRenderStateInit.prototype.depthNear; + +/** + * @type {number} + */ +XRRenderStateInit.prototype.depthFar; + +/** + * @type {number} + */ +XRRenderStateInit.prototype.inlineVerticalFieldOfView; + +/** + * @type {?XRWebGLLayer} + */ +XRRenderStateInit.prototype.baseLayer; + +/** + * @constructor + */ +function XRRenderState() {}; + +/** + * @type {number} + */ +XRRenderState.prototype.depthNear; + +/** + * @type {number} + */ +XRRenderState.prototype.depthFar; + +/** + * @type {?number} + */ +XRRenderState.prototype.inlineVerticalFieldOfView; + +/** + * @type {?XRWebGLLayer} + */ +XRRenderState.prototype.baseLayer; + +/** + * @constructor + */ +function XRFrame() {} + +/** + * @type {XRSession} + */ +XRFrame.prototype.session; + +/** + * @param {XRReferenceSpace} referenceSpace + * @return {?XRViewerPose} + */ +XRFrame.prototype.getViewerPose = function (referenceSpace) {}; + +/** + * + * @param {XRSpace} space + * @param {XRSpace} baseSpace + * @return {XRPose} + */ +XRFrame.prototype.getPose = function (space, baseSpace) {}; + +/** + * @constructor + */ +function XRReferenceSpace() {}; + +/** + * @type {Array<DOMPointReadOnly>} + */ +XRReferenceSpace.prototype.boundsGeometry; + +/** + * @param {XRRigidTransform} originOffset + * @return {XRReferenceSpace} + */ +XRReferenceSpace.prototype.getOffsetReferenceSpace = function(originOffset) {}; + +/** + * @type {?function (Event)} + */ +XRReferenceSpace.prototype.onreset; + +/** + * @constructor + */ +function XRRigidTransform() {}; + +/** + * @type {DOMPointReadOnly} + */ +XRRigidTransform.prototype.position; + +/** + * @type {DOMPointReadOnly} + */ +XRRigidTransform.prototype.orientation; + +/** + * @type {Float32Array} + */ +XRRigidTransform.prototype.matrix; + +/** + * @type {XRRigidTransform} + */ +XRRigidTransform.prototype.inverse; + +/** + * @constructor + */ +function XRView() {} + +/** + * @type {string} + */ +XRView.prototype.eye; + +/** + * @type {Float32Array} + */ +XRView.prototype.projectionMatrix; + +/** + * @type {XRRigidTransform} + */ +XRView.prototype.transform; + +/** + * @constructor + */ +function XRViewerPose() {} + +/** + * @type {Array<XRView>} + */ +XRViewerPose.prototype.views; + +/** + * @constructor + */ +function XRViewport() {} + +/** + * @type {number} + */ +XRViewport.prototype.x; + +/** + * @type {number} + */ +XRViewport.prototype.y; + +/** + * @type {number} + */ +XRViewport.prototype.width; + +/** + * @type {number} + */ +XRViewport.prototype.height; + +/** + * @constructor + */ +function XRWebGLLayerInit() {}; + +/** + * @type {boolean} + */ +XRWebGLLayerInit.prototype.antialias; + +/** + * @type {boolean} + */ +XRWebGLLayerInit.prototype.depth; + +/** + * @type {boolean} + */ +XRWebGLLayerInit.prototype.stencil; + +/** + * @type {boolean} + */ +XRWebGLLayerInit.prototype.alpha; + +/** + * @type {boolean} + */ +XRWebGLLayerInit.prototype.ignoreDepthValues; + +/** + * @type {boolean} + */ +XRWebGLLayerInit.prototype.ignoreDepthValues; + +/** + * @type {number} + */ +XRWebGLLayerInit.prototype.framebufferScaleFactor; + +/** + * @constructor + * + * @param {XRSession} session + * @param {WebGLRenderContext|WebGL2RenderingContext} ctx + * @param {?XRWebGLLayerInit} options + */ +function XRWebGLLayer(session, ctx, options) {} + +/** + * @type {boolean} + */ +XRWebGLLayer.prototype.antialias; + +/** + * @type {boolean} + */ +XRWebGLLayer.prototype.ignoreDepthValues; + +/** + * @type {number} + */ +XRWebGLLayer.prototype.framebufferWidth; + +/** + * @type {number} + */ +XRWebGLLayer.prototype.framebufferHeight; + +/** + * @type {WebGLFramebuffer} + */ +XRWebGLLayer.prototype.framebuffer; + +/** + * @param {XRView} view + * @return {?XRViewport} + */ +XRWebGLLayer.prototype.getViewport = function(view) {}; + +/** + * @param {XRSession} session + * @return {number} + */ +XRWebGLLayer.prototype.getNativeFramebufferScaleFactor = function (session) {}; + +/** + * @constructor + */ +function WebGLRenderingContextBase() {}; + +/** + * @return {Promise<void>} + */ +WebGLRenderingContextBase.prototype.makeXRCompatible = function () {}; + +/** + * @constructor + */ +function XRInputSourcesChangeEvent() {}; + +/** + * @type {Array<XRInputSource>} + */ +XRInputSourcesChangeEvent.prototype.added; + +/** + * @type {Array<XRInputSource>} + */ +XRInputSourcesChangeEvent.prototype.removed; + +/** + * @constructor + */ +function XRInputSourceEvent() {}; + +/** + * @type {XRFrame} + */ +XRInputSourceEvent.prototype.frame; + +/** + * @type {XRInputSource} + */ +XRInputSourceEvent.prototype.inputSource; + +/** + * @constructor + */ +function XRInputSource() {}; + +/** + * @type {Gamepad} + */ +XRInputSource.prototype.gamepad; + +/** + * @type {XRSpace} + */ +XRInputSource.prototype.gripSpace; + +/** + * @type {string} + */ +XRInputSource.prototype.handedness; + +/** + * @type {string} + */ +XRInputSource.prototype.profiles; + +/** + * @type {string} + */ +XRInputSource.prototype.targetRayMode; + +/** + * @type {XRSpace} + */ +XRInputSource.prototype.targetRaySpace; + +/** + * @constructor + */ +function XRSpace() {}; + +/** + * @constructor + */ +function XRPose() {}; + +/** + * @type {XRRigidTransform} + */ +XRPose.prototype.transform; + +/** + * @type {boolean} + */ +XRPose.prototype.emulatedPosition; diff --git a/modules/webxr/register_types.cpp b/modules/webxr/register_types.cpp new file mode 100644 index 0000000000..8baf7e05b8 --- /dev/null +++ b/modules/webxr/register_types.cpp @@ -0,0 +1,47 @@ +/*************************************************************************/ +/* register_types.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 "register_types.h" + +#include "webxr_interface.h" +#include "webxr_interface_js.h" + +void register_webxr_types() { + ClassDB::register_virtual_class<WebXRInterface>(); + +#ifdef JAVASCRIPT_ENABLED + Ref<WebXRInterfaceJS> webxr; + webxr.instance(); + XRServer::get_singleton()->add_interface(webxr); +#endif +} + +void unregister_webxr_types() { +} diff --git a/modules/webxr/register_types.h b/modules/webxr/register_types.h new file mode 100644 index 0000000000..f0c5a4bd79 --- /dev/null +++ b/modules/webxr/register_types.h @@ -0,0 +1,37 @@ +/*************************************************************************/ +/* register_types.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 WEBXR_REGISTER_TYPES_H +#define WEBXR_REGISTER_TYPES_H + +void register_webxr_types(); +void unregister_webxr_types(); + +#endif // WEBXR_REGISTER_TYPES_H diff --git a/modules/webxr/webxr_interface.cpp b/modules/webxr/webxr_interface.cpp new file mode 100644 index 0000000000..2c28ce070f --- /dev/null +++ b/modules/webxr/webxr_interface.cpp @@ -0,0 +1,71 @@ +/*************************************************************************/ +/* webxr_interface.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 "webxr_interface.h" +#include <stdlib.h> + +void WebXRInterface::_bind_methods() { + ClassDB::bind_method(D_METHOD("is_session_supported", "session_mode"), &WebXRInterface::is_session_supported); + ClassDB::bind_method(D_METHOD("set_session_mode", "session_mode"), &WebXRInterface::set_session_mode); + ClassDB::bind_method(D_METHOD("get_session_mode"), &WebXRInterface::get_session_mode); + ClassDB::bind_method(D_METHOD("set_required_features", "required_features"), &WebXRInterface::set_required_features); + ClassDB::bind_method(D_METHOD("get_required_features"), &WebXRInterface::get_required_features); + ClassDB::bind_method(D_METHOD("set_optional_features", "optional_features"), &WebXRInterface::set_optional_features); + ClassDB::bind_method(D_METHOD("get_optional_features"), &WebXRInterface::get_optional_features); + ClassDB::bind_method(D_METHOD("get_reference_space_type"), &WebXRInterface::get_reference_space_type); + ClassDB::bind_method(D_METHOD("set_requested_reference_space_types", "requested_reference_space_types"), &WebXRInterface::set_requested_reference_space_types); + ClassDB::bind_method(D_METHOD("get_requested_reference_space_types"), &WebXRInterface::get_requested_reference_space_types); + ClassDB::bind_method(D_METHOD("get_controller"), &WebXRInterface::get_controller); + ClassDB::bind_method(D_METHOD("get_visibility_state"), &WebXRInterface::get_visibility_state); + ClassDB::bind_method(D_METHOD("get_bounds_geometry"), &WebXRInterface::get_bounds_geometry); + + ADD_PROPERTY(PropertyInfo(Variant::STRING, "session_mode", PROPERTY_HINT_NONE), "set_session_mode", "get_session_mode"); + ADD_PROPERTY(PropertyInfo(Variant::STRING, "required_features", PROPERTY_HINT_NONE), "set_required_features", "get_required_features"); + ADD_PROPERTY(PropertyInfo(Variant::STRING, "optional_features", PROPERTY_HINT_NONE), "set_optional_features", "get_optional_features"); + ADD_PROPERTY(PropertyInfo(Variant::STRING, "requested_reference_space_types", PROPERTY_HINT_NONE), "set_requested_reference_space_types", "get_requested_reference_space_types"); + ADD_PROPERTY(PropertyInfo(Variant::STRING, "reference_space_type", PROPERTY_HINT_NONE), "", "get_reference_space_type"); + ADD_PROPERTY(PropertyInfo(Variant::STRING, "visibility_state", PROPERTY_HINT_NONE), "", "get_visibility_state"); + ADD_PROPERTY(PropertyInfo(Variant::PACKED_VECTOR3_ARRAY, "bounds_geometry", PROPERTY_HINT_NONE), "", "get_bounds_geometry"); + + ADD_SIGNAL(MethodInfo("session_supported", PropertyInfo(Variant::STRING, "session_mode"), PropertyInfo(Variant::BOOL, "supported"))); + ADD_SIGNAL(MethodInfo("session_started")); + ADD_SIGNAL(MethodInfo("session_ended")); + ADD_SIGNAL(MethodInfo("session_failed", PropertyInfo(Variant::STRING, "message"))); + + ADD_SIGNAL(MethodInfo("selectstart", PropertyInfo(Variant::INT, "controller_id"))); + ADD_SIGNAL(MethodInfo("select", PropertyInfo(Variant::INT, "controller_id"))); + ADD_SIGNAL(MethodInfo("selectend", PropertyInfo(Variant::INT, "controller_id"))); + ADD_SIGNAL(MethodInfo("squeezestart", PropertyInfo(Variant::INT, "controller_id"))); + ADD_SIGNAL(MethodInfo("squeeze", PropertyInfo(Variant::INT, "controller_id"))); + ADD_SIGNAL(MethodInfo("squeezeend", PropertyInfo(Variant::INT, "controller_id"))); + + ADD_SIGNAL(MethodInfo("visibility_state_changed")); + ADD_SIGNAL(MethodInfo("reference_space_reset")); +} diff --git a/modules/webxr/webxr_interface.h b/modules/webxr/webxr_interface.h new file mode 100644 index 0000000000..c5b2dc8d73 --- /dev/null +++ b/modules/webxr/webxr_interface.h @@ -0,0 +1,65 @@ +/*************************************************************************/ +/* webxr_interface.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 WEBXR_INTERFACE_H +#define WEBXR_INTERFACE_H + +#include "servers/xr/xr_interface.h" +#include "servers/xr/xr_positional_tracker.h" + +/** + @author David Snopek <david.snopek@snopekgames.com> + + The WebXR interface is a VR/AR interface that can be used on the web. +*/ + +class WebXRInterface : public XRInterface { + GDCLASS(WebXRInterface, XRInterface); + +protected: + static void _bind_methods(); + +public: + virtual void is_session_supported(const String &p_session_mode) = 0; + virtual void set_session_mode(String p_session_mode) = 0; + virtual String get_session_mode() const = 0; + virtual void set_required_features(String p_required_features) = 0; + virtual String get_required_features() const = 0; + virtual void set_optional_features(String p_optional_features) = 0; + virtual String get_optional_features() const = 0; + virtual void set_requested_reference_space_types(String p_requested_reference_space_types) = 0; + virtual String get_requested_reference_space_types() const = 0; + virtual String get_reference_space_type() const = 0; + virtual XRPositionalTracker *get_controller(int p_controller_id) const = 0; + virtual String get_visibility_state() const = 0; + virtual PackedVector3Array get_bounds_geometry() const = 0; +}; + +#endif // WEBXR_INTERFACE_H diff --git a/modules/webxr/webxr_interface_js.cpp b/modules/webxr/webxr_interface_js.cpp new file mode 100644 index 0000000000..72dc4790ac --- /dev/null +++ b/modules/webxr/webxr_interface_js.cpp @@ -0,0 +1,451 @@ +/*************************************************************************/ +/* webxr_interface_js.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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. */ +/*************************************************************************/ + +#ifdef JAVASCRIPT_ENABLED + +#include "webxr_interface_js.h" +#include "core/input/input.h" +#include "core/os/os.h" +#include "emscripten.h" +#include "godot_webxr.h" +#include <stdlib.h> + +void _emwebxr_on_session_supported(char *p_session_mode, int p_supported) { + XRServer *xr_server = XRServer::get_singleton(); + ERR_FAIL_NULL(xr_server); + + Ref<XRInterface> interface = xr_server->find_interface("WebXR"); + ERR_FAIL_COND(interface.is_null()); + + String session_mode = String(p_session_mode); + interface->emit_signal("session_supported", session_mode, p_supported ? true : false); +} + +void _emwebxr_on_session_started(char *p_reference_space_type) { + XRServer *xr_server = XRServer::get_singleton(); + ERR_FAIL_NULL(xr_server); + + Ref<XRInterface> interface = xr_server->find_interface("WebXR"); + ERR_FAIL_COND(interface.is_null()); + + String reference_space_type = String(p_reference_space_type); + ((WebXRInterfaceJS *)interface.ptr())->_set_reference_space_type(reference_space_type); + interface->emit_signal("session_started"); +} + +void _emwebxr_on_session_ended() { + XRServer *xr_server = XRServer::get_singleton(); + ERR_FAIL_NULL(xr_server); + + Ref<XRInterface> interface = xr_server->find_interface("WebXR"); + ERR_FAIL_COND(interface.is_null()); + + interface->uninitialize(); + interface->emit_signal("session_ended"); +} + +void _emwebxr_on_session_failed(char *p_message) { + XRServer *xr_server = XRServer::get_singleton(); + ERR_FAIL_NULL(xr_server); + + Ref<XRInterface> interface = xr_server->find_interface("WebXR"); + ERR_FAIL_COND(interface.is_null()); + + String message = String(p_message); + interface->emit_signal("session_failed", message); +} + +void _emwebxr_on_controller_changed() { + XRServer *xr_server = XRServer::get_singleton(); + ERR_FAIL_NULL(xr_server); + + Ref<XRInterface> interface = xr_server->find_interface("WebXR"); + ERR_FAIL_COND(interface.is_null()); + + ((WebXRInterfaceJS *)interface.ptr())->_on_controller_changed(); +} + +extern "C" EMSCRIPTEN_KEEPALIVE void _emwebxr_on_input_event(char *p_signal_name, int p_input_source) { + XRServer *xr_server = XRServer::get_singleton(); + ERR_FAIL_NULL(xr_server); + + Ref<XRInterface> interface = xr_server->find_interface("WebXR"); + ERR_FAIL_COND(interface.is_null()); + + StringName signal_name = StringName(p_signal_name); + interface->emit_signal(signal_name, p_input_source + 1); +} + +extern "C" EMSCRIPTEN_KEEPALIVE void _emwebxr_on_simple_event(char *p_signal_name) { + XRServer *xr_server = XRServer::get_singleton(); + ERR_FAIL_NULL(xr_server); + + Ref<XRInterface> interface = xr_server->find_interface("WebXR"); + ERR_FAIL_COND(interface.is_null()); + + StringName signal_name = StringName(p_signal_name); + interface->emit_signal(signal_name); +} + +void WebXRInterfaceJS::is_session_supported(const String &p_session_mode) { + godot_webxr_is_session_supported(p_session_mode.utf8().get_data(), &_emwebxr_on_session_supported); +} + +void WebXRInterfaceJS::set_session_mode(String p_session_mode) { + session_mode = p_session_mode; +} + +String WebXRInterfaceJS::get_session_mode() const { + return session_mode; +} + +void WebXRInterfaceJS::set_required_features(String p_required_features) { + required_features = p_required_features; +} + +String WebXRInterfaceJS::get_required_features() const { + return required_features; +} + +void WebXRInterfaceJS::set_optional_features(String p_optional_features) { + optional_features = p_optional_features; +} + +String WebXRInterfaceJS::get_optional_features() const { + return optional_features; +} + +void WebXRInterfaceJS::set_requested_reference_space_types(String p_requested_reference_space_types) { + requested_reference_space_types = p_requested_reference_space_types; +} + +String WebXRInterfaceJS::get_requested_reference_space_types() const { + return requested_reference_space_types; +} + +void WebXRInterfaceJS::_set_reference_space_type(String p_reference_space_type) { + reference_space_type = p_reference_space_type; +} + +String WebXRInterfaceJS::get_reference_space_type() const { + return reference_space_type; +} + +XRPositionalTracker *WebXRInterfaceJS::get_controller(int p_controller_id) const { + XRServer *xr_server = XRServer::get_singleton(); + ERR_FAIL_NULL_V(xr_server, nullptr); + + return xr_server->find_by_type_and_id(XRServer::TRACKER_CONTROLLER, p_controller_id); +} + +String WebXRInterfaceJS::get_visibility_state() const { + char *c_str = godot_webxr_get_visibility_state(); + if (c_str) { + String visibility_state = String(c_str); + free(c_str); + + return visibility_state; + } + return String(); +} + +PackedVector3Array WebXRInterfaceJS::get_bounds_geometry() const { + PackedVector3Array ret; + + int *js_bounds = godot_webxr_get_bounds_geometry(); + if (js_bounds) { + ret.resize(js_bounds[0]); + for (int i = 0; i < js_bounds[0]; i++) { + float *js_vector3 = ((float *)js_bounds) + (i * 3) + 1; + ret.set(i, Vector3(js_vector3[0], js_vector3[1], js_vector3[2])); + } + free(js_bounds); + } + + return ret; +} + +StringName WebXRInterfaceJS::get_name() const { + return "WebXR"; +}; + +int WebXRInterfaceJS::get_capabilities() const { + return XRInterface::XR_STEREO; +}; + +bool WebXRInterfaceJS::is_stereo() { + // @todo WebXR can be mono! So, how do we know? Count the views in the frame? + return true; +}; + +bool WebXRInterfaceJS::is_initialized() const { + return (initialized); +}; + +bool WebXRInterfaceJS::initialize() { + XRServer *xr_server = XRServer::get_singleton(); + ERR_FAIL_NULL_V(xr_server, false); + + if (!initialized) { + if (!godot_webxr_is_supported()) { + return false; + } + + if (requested_reference_space_types.size() == 0) { + return false; + } + + // make this our primary interface + xr_server->set_primary_interface(this); + + initialized = true; + + godot_webxr_initialize( + session_mode.utf8().get_data(), + required_features.utf8().get_data(), + optional_features.utf8().get_data(), + requested_reference_space_types.utf8().get_data(), + &_emwebxr_on_session_started, + &_emwebxr_on_session_ended, + &_emwebxr_on_session_failed, + &_emwebxr_on_controller_changed, + &_emwebxr_on_input_event, + &_emwebxr_on_simple_event); + }; + + return true; +}; + +void WebXRInterfaceJS::uninitialize() { + if (initialized) { + XRServer *xr_server = XRServer::get_singleton(); + if (xr_server != NULL) { + // no longer our primary interface + xr_server->clear_primary_interface_if(this); + } + + godot_webxr_uninitialize(); + + reference_space_type = ""; + initialized = false; + }; +}; + +Transform WebXRInterfaceJS::_js_matrix_to_transform(float *p_js_matrix) { + Transform transform; + + transform.basis.elements[0].x = p_js_matrix[0]; + transform.basis.elements[1].x = p_js_matrix[1]; + transform.basis.elements[2].x = p_js_matrix[2]; + transform.basis.elements[0].y = p_js_matrix[4]; + transform.basis.elements[1].y = p_js_matrix[5]; + transform.basis.elements[2].y = p_js_matrix[6]; + transform.basis.elements[0].z = p_js_matrix[8]; + transform.basis.elements[1].z = p_js_matrix[9]; + transform.basis.elements[2].z = p_js_matrix[10]; + transform.origin.x = p_js_matrix[12]; + transform.origin.y = p_js_matrix[13]; + transform.origin.z = p_js_matrix[14]; + + return transform; +} + +Size2 WebXRInterfaceJS::get_render_targetsize() { + Size2 target_size; + + int *js_size = godot_webxr_get_render_targetsize(); + if (!initialized || js_size == nullptr) { + // As a default, use half the window size. + target_size = DisplayServer::get_singleton()->window_get_size(); + target_size.width /= 2.0; + return target_size; + } + + target_size.width = js_size[0]; + target_size.height = js_size[1]; + + free(js_size); + + return target_size; +}; + +Transform WebXRInterfaceJS::get_transform_for_eye(XRInterface::Eyes p_eye, const Transform &p_cam_transform) { + Transform transform_for_eye; + + XRServer *xr_server = XRServer::get_singleton(); + ERR_FAIL_NULL_V(xr_server, transform_for_eye); + + float *js_matrix = godot_webxr_get_transform_for_eye(p_eye); + if (!initialized || js_matrix == nullptr) { + transform_for_eye = p_cam_transform; + return transform_for_eye; + } + + transform_for_eye = _js_matrix_to_transform(js_matrix); + free(js_matrix); + + return p_cam_transform * xr_server->get_reference_frame() * transform_for_eye; +}; + +CameraMatrix WebXRInterfaceJS::get_projection_for_eye(XRInterface::Eyes p_eye, real_t p_aspect, real_t p_z_near, real_t p_z_far) { + CameraMatrix eye; + + float *js_matrix = godot_webxr_get_projection_for_eye(p_eye); + if (!initialized || js_matrix == nullptr) { + return eye; + } + + int k = 0; + for (int i = 0; i < 4; i++) { + for (int j = 0; j < 4; j++) { + eye.matrix[i][j] = js_matrix[k++]; + } + } + + free(js_matrix); + + // Copied from godot_oculus_mobile's ovr_mobile_session.cpp + eye.matrix[2][2] = -(p_z_far + p_z_near) / (p_z_far - p_z_near); + eye.matrix[3][2] = -(2.0f * p_z_far * p_z_near) / (p_z_far - p_z_near); + + return eye; +} + +unsigned int WebXRInterfaceJS::get_external_texture_for_eye(XRInterface::Eyes p_eye) { + if (!initialized) { + return 0; + } + return godot_webxr_get_external_texture_for_eye(p_eye); +} + +void WebXRInterfaceJS::commit_for_eye(XRInterface::Eyes p_eye, RID p_render_target, const Rect2 &p_screen_rect) { + if (!initialized) { + return; + } + godot_webxr_commit_for_eye(p_eye); +}; + +void WebXRInterfaceJS::process() { + if (initialized) { + godot_webxr_sample_controller_data(); + + int controller_count = godot_webxr_get_controller_count(); + if (controller_count == 0) { + return; + } + + for (int i = 0; i < controller_count; i++) { + _update_tracker(i); + } + }; +}; + +void WebXRInterfaceJS::_update_tracker(int p_controller_id) { + XRServer *xr_server = XRServer::get_singleton(); + ERR_FAIL_NULL(xr_server); + + XRPositionalTracker *tracker = xr_server->find_by_type_and_id(XRServer::TRACKER_CONTROLLER, p_controller_id + 1); + if (godot_webxr_is_controller_connected(p_controller_id)) { + if (tracker == nullptr) { + tracker = memnew(XRPositionalTracker); + tracker->set_type(XRServer::TRACKER_CONTROLLER); + // Controller id's 0 and 1 are always the left and right hands. + if (p_controller_id < 2) { + tracker->set_name(p_controller_id == 0 ? "Left" : "Right"); + tracker->set_hand(p_controller_id == 0 ? XRPositionalTracker::TRACKER_LEFT_HAND : XRPositionalTracker::TRACKER_RIGHT_HAND); + } + // Use the ids we're giving to our "virtual" gamepads. + tracker->set_joy_id(p_controller_id + 100); + xr_server->add_tracker(tracker); + } + + Input *input = Input::get_singleton(); + + float *tracker_matrix = godot_webxr_get_controller_transform(p_controller_id); + if (tracker_matrix) { + Transform transform = _js_matrix_to_transform(tracker_matrix); + tracker->set_position(transform.origin); + tracker->set_orientation(transform.basis); + free(tracker_matrix); + } + + int *buttons = godot_webxr_get_controller_buttons(p_controller_id); + if (buttons) { + for (int i = 0; i < buttons[0]; i++) { + input->joy_button(p_controller_id + 100, i, *((float *)buttons + (i + 1))); + } + free(buttons); + } + + int *axes = godot_webxr_get_controller_axes(p_controller_id); + if (axes) { + for (int i = 0; i < axes[0]; i++) { + Input::JoyAxis joy_axis; + joy_axis.min = -1; + joy_axis.value = *((float *)axes + (i + 1)); + input->joy_axis(p_controller_id + 100, i, joy_axis); + } + free(axes); + } + } else if (tracker) { + xr_server->remove_tracker(tracker); + } +} + +void WebXRInterfaceJS::_on_controller_changed() { + // Register "virtual" gamepads with Godot for the ones we get from WebXR. + godot_webxr_sample_controller_data(); + for (int i = 0; i < 2; i++) { + bool controller_connected = godot_webxr_is_controller_connected(i); + if (controllers_state[i] != controller_connected) { + Input::get_singleton()->joy_connection_changed(i + 100, controller_connected, i == 0 ? "Left" : "Right", ""); + controllers_state[i] = controller_connected; + } + } +} + +void WebXRInterfaceJS::notification(int p_what) { + // Nothing to do here. +} + +WebXRInterfaceJS::WebXRInterfaceJS() { + initialized = false; + session_mode = "inline"; + requested_reference_space_types = "local"; +}; + +WebXRInterfaceJS::~WebXRInterfaceJS() { + // and make sure we cleanup if we haven't already + if (initialized) { + uninitialize(); + }; +}; + +#endif // JAVASCRIPT_ENABLED diff --git a/modules/webxr/webxr_interface_js.h b/modules/webxr/webxr_interface_js.h new file mode 100644 index 0000000000..93da9a6d12 --- /dev/null +++ b/modules/webxr/webxr_interface_js.h @@ -0,0 +1,103 @@ +/*************************************************************************/ +/* webxr_interface_js.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 WEBXR_INTERFACE_JS_H +#define WEBXR_INTERFACE_JS_H + +#ifdef JAVASCRIPT_ENABLED + +#include "webxr_interface.h" + +/** + @author David Snopek <david.snopek@snopekgames.com> + + The WebXR interface is a VR/AR interface that can be used on the web. +*/ + +class WebXRInterfaceJS : public WebXRInterface { + GDCLASS(WebXRInterfaceJS, WebXRInterface); + +private: + bool initialized; + + // @todo Should these really use enums instead of strings? + String session_mode; + String required_features; + String optional_features; + String requested_reference_space_types; + String reference_space_type; + + bool controllers_state[2]; + + Transform _js_matrix_to_transform(float *p_js_matrix); + void _update_tracker(int p_controller_id); + +public: + virtual void is_session_supported(const String &p_session_mode) override; + virtual void set_session_mode(String p_session_mode) override; + virtual String get_session_mode() const override; + virtual void set_required_features(String p_required_features) override; + virtual String get_required_features() const override; + virtual void set_optional_features(String p_optional_features) override; + virtual String get_optional_features() const override; + virtual void set_requested_reference_space_types(String p_requested_reference_space_types) override; + virtual String get_requested_reference_space_types() const override; + void _set_reference_space_type(String p_reference_space_type); + virtual String get_reference_space_type() const override; + virtual XRPositionalTracker *get_controller(int p_controller_id) const override; + virtual String get_visibility_state() const override; + virtual PackedVector3Array get_bounds_geometry() const override; + + virtual StringName get_name() const override; + virtual int get_capabilities() const override; + + virtual bool is_initialized() const override; + virtual bool initialize() override; + virtual void uninitialize() override; + + virtual Size2 get_render_targetsize() override; + virtual bool is_stereo() override; + virtual Transform get_transform_for_eye(XRInterface::Eyes p_eye, const Transform &p_cam_transform) override; + virtual CameraMatrix get_projection_for_eye(XRInterface::Eyes p_eye, real_t p_aspect, real_t p_z_near, real_t p_z_far) override; + virtual unsigned int get_external_texture_for_eye(XRInterface::Eyes p_eye) override; + virtual void commit_for_eye(XRInterface::Eyes p_eye, RID p_render_target, const Rect2 &p_screen_rect) override; + + virtual void process() override; + virtual void notification(int p_what) override; + + void _on_controller_changed(); + + WebXRInterfaceJS(); + ~WebXRInterfaceJS(); +}; + +#endif // JAVASCRIPT_ENABLED + +#endif // WEBXR_INTERFACE_JS_H diff --git a/platform/javascript/.eslintrc.libs.js b/platform/javascript/.eslintrc.libs.js index e5f0c3d147..81b1b8c864 100644 --- a/platform/javascript/.eslintrc.libs.js +++ b/platform/javascript/.eslintrc.libs.js @@ -18,5 +18,8 @@ module.exports = { "GodotRuntime": true, "GodotFS": true, "IDHandler": true, + "Browser": true, + "GL": true, + "XRWebGLLayer": true, }, }; diff --git a/platform/javascript/SCsub b/platform/javascript/SCsub index 7a8005fe30..1d3f96a6b8 100644 --- a/platform/javascript/SCsub +++ b/platform/javascript/SCsub @@ -67,6 +67,16 @@ else: sys_env.Depends(build[0], sys_env["JS_LIBS"]) +if "JS_PRE" in env: + for js in env["JS_PRE"]: + env.Append(LINKFLAGS=["--pre-js", env.File(js).path]) + env.Depends(build, env["JS_PRE"]) + +if "JS_EXTERNS" in env: + for ext in env["JS_EXTERNS"]: + env["ENV"]["EMCC_CLOSURE_ARGS"] += " --externs " + ext.path + env.Depends(build, env["JS_EXTERNS"]) + engine = [ "js/engine/preloader.js", "js/engine/utils.js", diff --git a/platform/javascript/detect.py b/platform/javascript/detect.py index d53c774e77..7d501e94b2 100644 --- a/platform/javascript/detect.py +++ b/platform/javascript/detect.py @@ -1,7 +1,7 @@ import os import sys -from emscripten_helpers import run_closure_compiler, create_engine_file, add_js_libraries +from emscripten_helpers import run_closure_compiler, create_engine_file, add_js_libraries, add_js_pre, add_js_externs from methods import get_compiler_version from SCons.Util import WhereIs @@ -133,6 +133,8 @@ def configure(env): # Add helper method for adding libraries. env.AddMethod(add_js_libraries, "AddJSLibraries") + env.AddMethod(add_js_pre, "AddJSPre") + env.AddMethod(add_js_externs, "AddJSExterns") # Add method that joins/compiles our Engine files. env.AddMethod(create_engine_file, "CreateEngineFile") diff --git a/platform/javascript/emscripten_helpers.py b/platform/javascript/emscripten_helpers.py index cc874c432e..278186e4c0 100644 --- a/platform/javascript/emscripten_helpers.py +++ b/platform/javascript/emscripten_helpers.py @@ -25,3 +25,15 @@ def add_js_libraries(env, libraries): if "JS_LIBS" not in env: env["JS_LIBS"] = [] env.Append(JS_LIBS=env.File(libraries)) + + +def add_js_pre(env, js_pre): + if "JS_PRE" not in env: + env["JS_PRE"] = [] + env.Append(JS_PRE=env.File(js_pre)) + + +def add_js_externs(env, externs): + if "JS_EXTERNS" not in env: + env["JS_EXTERNS"] = [] + env.Append(JS_EXTERNS=env.File(externs)) diff --git a/platform/windows/display_server_windows.cpp b/platform/windows/display_server_windows.cpp index db3d697e05..98ca724655 100644 --- a/platform/windows/display_server_windows.cpp +++ b/platform/windows/display_server_windows.cpp @@ -1876,27 +1876,12 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA break; } - case WM_ACTIVATE: // Watch For Window Activate Message - { - windows[window_id].minimized = HIWORD(wParam) != 0; - - if (LOWORD(wParam) == WA_ACTIVE || LOWORD(wParam) == WA_CLICKACTIVE) { - _send_window_event(windows[window_id], WINDOW_EVENT_FOCUS_IN); - windows[window_id].window_focused = true; - alt_mem = false; - control_mem = false; - shift_mem = false; - } else { // WM_INACTIVE - Input::get_singleton()->release_pressed_events(); - _send_window_event(windows[window_id], WINDOW_EVENT_FOCUS_OUT); - windows[window_id].window_focused = false; - alt_mem = false; - }; - - if ((OS::get_singleton()->get_current_tablet_driver() == "wintab") && wintab_available && windows[window_id].wtctx) { - wintab_WTEnable(windows[window_id].wtctx, GET_WM_ACTIVATE_STATE(wParam, lParam)); - } + case WM_ACTIVATE: { // Watch For Window Activate Message + saved_wparam = wParam; + saved_lparam = lParam; + // Run a timer to prevent event catching warning if the window is closing. + focus_timer_id = SetTimer(windows[window_id].hWnd, 2, USER_TIMER_MINIMUM, (TIMERPROC) nullptr); return 0; // Return To The Message Loop } case WM_GETMINMAXINFO: { @@ -1937,6 +1922,9 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA case WM_CLOSE: // Did We Receive A Close Message? { + if (focus_timer_id != 0U) { + KillTimer(windows[window_id].hWnd, focus_timer_id); + } _send_window_event(windows[window_id], WINDOW_EVENT_CLOSE_REQUEST); return 0; // Jump Back @@ -2630,6 +2618,28 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA if (!Main::is_iterating()) { Main::iteration(); } + } else if (wParam == focus_timer_id) { + windows[window_id].minimized = HIWORD(saved_wparam) != 0; + + if (LOWORD(saved_wparam) == WA_ACTIVE || LOWORD(saved_wparam) == WA_CLICKACTIVE) { + _send_window_event(windows[window_id], WINDOW_EVENT_FOCUS_IN); + windows[window_id].window_focused = true; + alt_mem = false; + control_mem = false; + shift_mem = false; + } else { // WM_INACTIVE + Input::get_singleton()->release_pressed_events(); + _send_window_event(windows[window_id], WINDOW_EVENT_FOCUS_OUT); + windows[window_id].window_focused = false; + alt_mem = false; + }; + + if ((OS::get_singleton()->get_current_tablet_driver() == "wintab") && wintab_available && windows[window_id].wtctx) { + wintab_WTEnable(windows[window_id].wtctx, GET_WM_ACTIVATE_STATE(saved_wparam, saved_lparam)); + } + + KillTimer(windows[window_id].hWnd, focus_timer_id); + focus_timer_id = 0U; } } break; @@ -3213,8 +3223,6 @@ DisplayServerWindows::DisplayServerWindows(const String &p_rendering_driver, Win } #endif - move_timer_id = 1; - //set_ime_active(false); if (!OS::get_singleton()->is_in_low_processor_usage_mode()) { diff --git a/platform/windows/display_server_windows.h b/platform/windows/display_server_windows.h index 89dd927304..722854c538 100644 --- a/platform/windows/display_server_windows.h +++ b/platform/windows/display_server_windows.h @@ -387,7 +387,8 @@ private: WindowID last_focused_window = INVALID_WINDOW_ID; - uint32_t move_timer_id; + uint32_t move_timer_id = 0U; + uint32_t focus_timer_id = 0U; HCURSOR hCursor; @@ -408,6 +409,9 @@ private: bool in_dispatch_input_event = false; bool console_visible = false; + WPARAM saved_wparam; + LPARAM saved_lparam; + WNDCLASSEXW wc; HCURSOR cursors[CURSOR_MAX] = { nullptr }; diff --git a/scene/2d/canvas_group.cpp b/scene/2d/canvas_group.cpp index 0e0aecf224..0f0e583ea7 100644 --- a/scene/2d/canvas_group.cpp +++ b/scene/2d/canvas_group.cpp @@ -84,4 +84,5 @@ CanvasGroup::CanvasGroup() { set_fit_margin(10.0); //sets things } CanvasGroup::~CanvasGroup() { + RS::get_singleton()->canvas_item_set_canvas_group_mode(get_canvas_item(), RS::CANVAS_GROUP_MODE_DISABLED); } diff --git a/scene/gui/popup_menu.cpp b/scene/gui/popup_menu.cpp index ecb5ac0ffc..e777e6c26b 100644 --- a/scene/gui/popup_menu.cpp +++ b/scene/gui/popup_menu.cpp @@ -72,9 +72,7 @@ Size2 PopupMenu::_get_contents_minimum_size() const { } size.width += items[i].text_buf->get_size().x; - if (i > 0) { - size.height += vseparation; - } + size.height += vseparation; if (items[i].accel || (items[i].shortcut.is_valid() && items[i].shortcut->is_valid())) { int accel_w = hseparation * 2; @@ -152,9 +150,7 @@ int PopupMenu::_get_mouse_over(const Point2 &p_over) const { } for (int i = 0; i < items.size(); i++) { - if (i > 0) { - ofs.y += vseparation; - } + ofs.y += i > 0 ? vseparation : (float)vseparation / 2; ofs.y += MAX(items[i].get_icon_size().height, items[i].text_buf->get_size().y); @@ -506,10 +502,8 @@ void PopupMenu::_draw_items() { // Loop through all items and draw each. for (int i = 0; i < items.size(); i++) { - // If not the first item, add the separation space between items. - if (i > 0) { - ofs.y += vseparation; - } + // For the first item only add half a separation. For all other items, add a whole separation to the offset. + ofs.y += i > 0 ? vseparation : (float)vseparation / 2; _shape_item(i); @@ -519,9 +513,9 @@ void PopupMenu::_draw_items() { if (i == mouse_over) { if (rtl) { - hover->draw(ci, Rect2(item_ofs + Point2(-hseparation + scroll_width, -vseparation / 2), Size2(display_width + hseparation * 2, h + vseparation))); + hover->draw(ci, Rect2(item_ofs + Point2(scroll_width, -vseparation / 2), Size2(display_width, h + vseparation))); } else { - hover->draw(ci, Rect2(item_ofs + Point2(-hseparation, -vseparation / 2), Size2(display_width + hseparation * 2, h + vseparation))); + hover->draw(ci, Rect2(item_ofs + Point2(0, -vseparation / 2), Size2(display_width, h + vseparation))); } } @@ -1636,7 +1630,6 @@ void PopupMenu::_bind_methods() { void PopupMenu::popup(const Rect2 &p_bounds) { moved = Vector2(); popup_time_msec = OS::get_singleton()->get_ticks_msec(); - set_as_minsize(); Popup::popup(p_bounds); } diff --git a/servers/rendering/renderer_rd/effects_rd.cpp b/servers/rendering/renderer_rd/effects_rd.cpp index a73eb3782c..6e1d61ff94 100644 --- a/servers/rendering/renderer_rd/effects_rd.cpp +++ b/servers/rendering/renderer_rd/effects_rd.cpp @@ -992,21 +992,21 @@ void EffectsRD::gather_ssao(RD::ComputeListID p_compute_list, const Vector<RID> ssao.gather_push_constant.pass_coord_offset[0] = i % 2; ssao.gather_push_constant.pass_coord_offset[1] = i / 2; - ssao.gather_push_constant.pass_uv_offset[0] = ((i % 2) - 0.0) / p_settings.screen_size.x; - ssao.gather_push_constant.pass_uv_offset[1] = ((i / 2) - 0.0) / p_settings.screen_size.y; + ssao.gather_push_constant.pass_uv_offset[0] = ((i % 2) - 0.0) / p_settings.full_screen_size.x; + ssao.gather_push_constant.pass_uv_offset[1] = ((i / 2) - 0.0) / p_settings.full_screen_size.y; ssao.gather_push_constant.pass = i; RD::get_singleton()->compute_list_bind_uniform_set(p_compute_list, _get_uniform_set_from_image(p_ao_slices[i]), 2); RD::get_singleton()->compute_list_set_push_constant(p_compute_list, &ssao.gather_push_constant, sizeof(SSAOGatherPushConstant)); - int x_groups = ((p_settings.screen_size.x >> (p_settings.half_size ? 2 : 1)) - 1) / 8 + 1; - int y_groups = ((p_settings.screen_size.y >> (p_settings.half_size ? 2 : 1)) - 1) / 8 + 1; + int x_groups = ((p_settings.full_screen_size.x >> (p_settings.half_size ? 2 : 1)) - 1) / 8 + 1; + int y_groups = ((p_settings.full_screen_size.y >> (p_settings.half_size ? 2 : 1)) - 1) / 8 + 1; RD::get_singleton()->compute_list_dispatch(p_compute_list, x_groups, y_groups, 1); } RD::get_singleton()->compute_list_add_barrier(p_compute_list); } -void EffectsRD::generate_ssao(RID p_depth_buffer, RID p_normal_buffer, RID p_depth_mipmaps_texture, const Vector<RID> &depth_mipmaps, RID p_ao, const Vector<RID> p_ao_slices, RID p_ao_pong, const Vector<RID> p_ao_pong_slices, RID p_upscale_buffer, RID p_importance_map, RID p_importance_map_pong, const CameraMatrix &p_projection, const SSAOSettings &p_settings, bool p_invalidate_uniform_sets) { +void EffectsRD::generate_ssao(RID p_depth_buffer, RID p_normal_buffer, RID p_depth_mipmaps_texture, const Vector<RID> &p_depth_mipmaps, RID p_ao, const Vector<RID> p_ao_slices, RID p_ao_pong, const Vector<RID> p_ao_pong_slices, RID p_upscale_buffer, RID p_importance_map, RID p_importance_map_pong, const CameraMatrix &p_projection, const SSAOSettings &p_settings, bool p_invalidate_uniform_sets) { RD::ComputeListID compute_list = RD::get_singleton()->compute_list_begin(); /* FIRST PASS */ @@ -1018,21 +1018,21 @@ void EffectsRD::generate_ssao(RID p_depth_buffer, RID p_normal_buffer, RID p_dep RD::Uniform u; u.uniform_type = RD::UNIFORM_TYPE_IMAGE; u.binding = 0; - u.ids.push_back(depth_mipmaps[1]); + u.ids.push_back(p_depth_mipmaps[1]); uniforms.push_back(u); } { RD::Uniform u; u.uniform_type = RD::UNIFORM_TYPE_IMAGE; u.binding = 1; - u.ids.push_back(depth_mipmaps[2]); + u.ids.push_back(p_depth_mipmaps[2]); uniforms.push_back(u); } { RD::Uniform u; u.uniform_type = RD::UNIFORM_TYPE_IMAGE; u.binding = 2; - u.ids.push_back(depth_mipmaps[3]); + u.ids.push_back(p_depth_mipmaps[3]); uniforms.push_back(u); } ssao.downsample_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, ssao.downsample_shader.version_get_shader(ssao.downsample_shader_version, 2), 2); @@ -1051,8 +1051,8 @@ void EffectsRD::generate_ssao(RID p_depth_buffer, RID p_normal_buffer, RID p_dep ssao.downsample_push_constant.z_near = p_projection.get_z_near(); ssao.downsample_push_constant.z_far = p_projection.get_z_far(); } - ssao.downsample_push_constant.pixel_size[0] = 1.0 / p_settings.screen_size.x; - ssao.downsample_push_constant.pixel_size[1] = 1.0 / p_settings.screen_size.y; + ssao.downsample_push_constant.pixel_size[0] = 1.0 / p_settings.full_screen_size.x; + ssao.downsample_push_constant.pixel_size[1] = 1.0 / p_settings.full_screen_size.y; ssao.downsample_push_constant.radius_sq = p_settings.radius * p_settings.radius; int downsample_pipeline = SSAO_DOWNSAMPLE; @@ -1068,14 +1068,14 @@ void EffectsRD::generate_ssao(RID p_depth_buffer, RID p_normal_buffer, RID p_dep RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, ssao.pipelines[downsample_pipeline]); RD::get_singleton()->compute_list_bind_uniform_set(compute_list, _get_compute_uniform_set_from_texture(p_depth_buffer), 0); - RD::get_singleton()->compute_list_bind_uniform_set(compute_list, _get_uniform_set_from_image(depth_mipmaps[0]), 1); + RD::get_singleton()->compute_list_bind_uniform_set(compute_list, _get_uniform_set_from_image(p_depth_mipmaps[0]), 1); if (p_settings.quality > RS::ENV_SSAO_QUALITY_MEDIUM) { RD::get_singleton()->compute_list_bind_uniform_set(compute_list, ssao.downsample_uniform_set, 2); } RD::get_singleton()->compute_list_set_push_constant(compute_list, &ssao.downsample_push_constant, sizeof(SSAODownsamplePushConstant)); - int x_groups = (MAX(1, p_settings.screen_size.x >> (p_settings.half_size ? 2 : 1)) - 1) / 8 + 1; - int y_groups = (MAX(1, p_settings.screen_size.y >> (p_settings.half_size ? 2 : 1)) - 1) / 8 + 1; + int x_groups = (MAX(1, p_settings.full_screen_size.x >> (p_settings.half_size ? 2 : 1)) - 1) / 8 + 1; + int y_groups = (MAX(1, p_settings.full_screen_size.y >> (p_settings.half_size ? 2 : 1)) - 1) / 8 + 1; RD::get_singleton()->compute_list_dispatch(compute_list, x_groups, y_groups, 1); RD::get_singleton()->compute_list_add_barrier(compute_list); @@ -1084,8 +1084,8 @@ void EffectsRD::generate_ssao(RID p_depth_buffer, RID p_normal_buffer, RID p_dep /* SECOND PASS */ // Sample SSAO { - ssao.gather_push_constant.screen_size[0] = p_settings.screen_size.x; - ssao.gather_push_constant.screen_size[1] = p_settings.screen_size.y; + ssao.gather_push_constant.screen_size[0] = p_settings.full_screen_size.x; + ssao.gather_push_constant.screen_size[1] = p_settings.full_screen_size.y; ssao.gather_push_constant.half_screen_pixel_size[0] = 1.0 / p_settings.half_screen_size.x; ssao.gather_push_constant.half_screen_pixel_size[1] = 1.0 / p_settings.half_screen_size.y; @@ -1122,7 +1122,7 @@ void EffectsRD::generate_ssao(RID p_depth_buffer, RID p_normal_buffer, RID p_dep ssao.gather_push_constant.inv_radius_near_limit = 1.0f / radius_near_limit; ssao.gather_push_constant.neg_inv_radius = -1.0 / ssao.gather_push_constant.radius; - ssao.gather_push_constant.load_counter_avg_div = 9.0 / float((p_settings.quarter_size.x) * (p_settings.quarter_size.y) * 255); + ssao.gather_push_constant.load_counter_avg_div = 9.0 / float((p_settings.quarter_screen_size.x) * (p_settings.quarter_screen_size.y) * 255); ssao.gather_push_constant.adaptive_sample_limit = p_settings.adaptive_target; ssao.gather_push_constant.detail_intensity = p_settings.detail; @@ -1192,8 +1192,8 @@ void EffectsRD::generate_ssao(RID p_depth_buffer, RID p_normal_buffer, RID p_dep RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, ssao.pipelines[SSAO_GATHER_BASE]); gather_ssao(compute_list, p_ao_pong_slices, p_settings, true); //generate importance map - int x_groups = (p_settings.quarter_size.x - 1) / 8 + 1; - int y_groups = (p_settings.quarter_size.y - 1) / 8 + 1; + int x_groups = (p_settings.quarter_screen_size.x - 1) / 8 + 1; + int y_groups = (p_settings.quarter_screen_size.y - 1) / 8 + 1; RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, ssao.pipelines[SSAO_GENERATE_IMPORTANCE_MAP]); RD::get_singleton()->compute_list_bind_uniform_set(compute_list, _get_compute_uniform_set_from_texture(p_ao_pong), 0); @@ -1268,8 +1268,8 @@ void EffectsRD::generate_ssao(RID p_depth_buffer, RID p_normal_buffer, RID p_dep } RD::get_singleton()->compute_list_set_push_constant(compute_list, &ssao.blur_push_constant, sizeof(SSAOBlurPushConstant)); - int x_groups = ((p_settings.screen_size.x >> (p_settings.half_size ? 2 : 1)) - 1) / 8 + 1; - int y_groups = ((p_settings.screen_size.y >> (p_settings.half_size ? 2 : 1)) - 1) / 8 + 1; + int x_groups = ((p_settings.full_screen_size.x >> (p_settings.half_size ? 2 : 1)) - 1) / 8 + 1; + int y_groups = ((p_settings.full_screen_size.y >> (p_settings.half_size ? 2 : 1)) - 1) / 8 + 1; RD::get_singleton()->compute_list_dispatch(compute_list, x_groups, y_groups, 1); } @@ -1285,8 +1285,8 @@ void EffectsRD::generate_ssao(RID p_depth_buffer, RID p_normal_buffer, RID p_dep // back to full size { ssao.interleave_push_constant.inv_sharpness = 1.0 - p_settings.sharpness; - ssao.interleave_push_constant.pixel_size[0] = 1.0 / p_settings.screen_size.x; - ssao.interleave_push_constant.pixel_size[1] = 1.0 / p_settings.screen_size.y; + ssao.interleave_push_constant.pixel_size[0] = 1.0 / p_settings.full_screen_size.x; + ssao.interleave_push_constant.pixel_size[1] = 1.0 / p_settings.full_screen_size.y; ssao.interleave_push_constant.size_modifier = uint32_t(p_settings.half_size ? 4 : 2); int interleave_pipeline = SSAO_INTERLEAVE_HALF; @@ -1307,8 +1307,8 @@ void EffectsRD::generate_ssao(RID p_depth_buffer, RID p_normal_buffer, RID p_dep RD::get_singleton()->compute_list_set_push_constant(compute_list, &ssao.interleave_push_constant, sizeof(SSAOInterleavePushConstant)); - int x_groups = (p_settings.screen_size.x - 1) / 8 + 1; - int y_groups = (p_settings.screen_size.y - 1) / 8 + 1; + int x_groups = (p_settings.full_screen_size.x - 1) / 8 + 1; + int y_groups = (p_settings.full_screen_size.y - 1) / 8 + 1; RD::get_singleton()->compute_list_dispatch(compute_list, x_groups, y_groups, 1); RD::get_singleton()->compute_list_add_barrier(compute_list); diff --git a/servers/rendering/renderer_rd/effects_rd.h b/servers/rendering/renderer_rd/effects_rd.h index ad4a660944..e2cdd0c3d8 100644 --- a/servers/rendering/renderer_rd/effects_rd.h +++ b/servers/rendering/renderer_rd/effects_rd.h @@ -745,9 +745,9 @@ public: float fadeout_from = 50.0; float fadeout_to = 300.0; - Size2i screen_size = Size2i(); + Size2i full_screen_size = Size2i(); Size2i half_screen_size = Size2i(); - Size2i quarter_size = Size2i(); + Size2i quarter_screen_size = Size2i(); }; void tonemapper(RID p_source_color, RID p_dst_framebuffer, const TonemapSettings &p_settings); diff --git a/servers/rendering/renderer_rd/renderer_canvas_render_rd.cpp b/servers/rendering/renderer_rd/renderer_canvas_render_rd.cpp index 508d56cfab..05ffc0086d 100644 --- a/servers/rendering/renderer_rd/renderer_canvas_render_rd.cpp +++ b/servers/rendering/renderer_rd/renderer_canvas_render_rd.cpp @@ -2489,7 +2489,7 @@ RendererCanvasRenderRD::RendererCanvasRenderRD(RendererStorageRD *p_storage) { actions.renames["COLOR"] = "color"; actions.renames["NORMAL"] = "normal"; actions.renames["NORMAL_MAP"] = "normal_map"; - actions.renames["NORMAL_MAP_DEPTH"] = "normal_depth"; + actions.renames["NORMAL_MAP_DEPTH"] = "normal_map_depth"; actions.renames["TEXTURE"] = "color_texture"; actions.renames["TEXTURE_PIXEL_SIZE"] = "draw_data.color_texture_pixel_size"; actions.renames["NORMAL_TEXTURE"] = "normal_texture"; diff --git a/servers/rendering/renderer_rd/renderer_scene_render_forward.cpp b/servers/rendering/renderer_rd/renderer_scene_render_forward.cpp index 248dc3c582..6881d7913f 100644 --- a/servers/rendering/renderer_rd/renderer_scene_render_forward.cpp +++ b/servers/rendering/renderer_rd/renderer_scene_render_forward.cpp @@ -1871,8 +1871,6 @@ void RendererSceneRenderForward::_render_scene(RID p_render_buffer, const Transf clear_color = p_default_bg_color; } - RID rp_uniform_set = _setup_render_pass_uniform_set(p_render_buffer, radiance_texture, p_shadow_atlas, p_reflection_atlas, p_gi_probes); - render_list.sort_by_key(false); _fill_instances(render_list.elements, render_list.element_count, false, false, using_sdfgi || using_giprobe); @@ -1887,6 +1885,8 @@ void RendererSceneRenderForward::_render_scene(RID p_render_buffer, const Transf if (depth_pre_pass) { //depth pre pass RENDER_TIMESTAMP("Render Depth Pre-Pass"); + RID rp_uniform_set = _setup_render_pass_uniform_set(RID(), RID(), RID(), RID(), PagedArray<RID>()); + bool finish_depth = using_ssao || using_sdfgi || using_giprobe; RD::DrawListID draw_list = RD::get_singleton()->draw_list_begin(depth_framebuffer, RD::INITIAL_ACTION_CLEAR, RD::FINAL_ACTION_READ, RD::INITIAL_ACTION_CLEAR, finish_depth ? RD::FINAL_ACTION_READ : RD::FINAL_ACTION_CONTINUE, depth_pass_clear); _render_list(draw_list, RD::get_singleton()->framebuffer_get_format(depth_framebuffer), render_list.elements, render_list.element_count, false, depth_pass_mode, render_buffer == nullptr, rp_uniform_set, get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_WIREFRAME, Vector2(), lod_camera_plane, lod_distance_multiplier, p_screen_lod_threshold); @@ -1917,6 +1917,8 @@ void RendererSceneRenderForward::_render_scene(RID p_render_buffer, const Transf RENDER_TIMESTAMP("Render Opaque Pass"); + RID rp_uniform_set = _setup_render_pass_uniform_set(p_render_buffer, radiance_texture, p_shadow_atlas, p_reflection_atlas, p_gi_probes); + bool can_continue_color = !scene_state.used_screen_texture && !using_ssr && !using_sss; bool can_continue_depth = !scene_state.used_depth_texture && !using_ssr && !using_sss; diff --git a/servers/rendering/renderer_rd/renderer_scene_render_rd.cpp b/servers/rendering/renderer_rd/renderer_scene_render_rd.cpp index 8e55dea2b1..1edabed287 100644 --- a/servers/rendering/renderer_rd/renderer_scene_render_rd.cpp +++ b/servers/rendering/renderer_rd/renderer_scene_render_rd.cpp @@ -5329,9 +5329,9 @@ void RendererSceneRenderRD::_process_ssao(RID p_render_buffers, RID p_environmen settings.blur_passes = ssao_blur_passes; settings.fadeout_from = ssao_fadeout_from; settings.fadeout_to = ssao_fadeout_to; - settings.screen_size = Size2i(rb->width, rb->height); + settings.full_screen_size = Size2i(rb->width, rb->height); settings.half_screen_size = Size2i(buffer_width, buffer_height); - settings.quarter_size = Size2i(half_width, half_height); + settings.quarter_screen_size = Size2i(half_width, half_height); storage->get_effects()->generate_ssao(rb->depth_texture, p_normal_buffer, rb->ssao.depth, rb->ssao.depth_slices, rb->ssao.ao_deinterleaved, rb->ssao.ao_deinterleaved_slices, rb->ssao.ao_pong, rb->ssao.ao_pong_slices, rb->ssao.ao_final, rb->ssao.importance_map[0], rb->ssao.importance_map[1], p_projection, settings, uniform_sets_are_invalid); } diff --git a/servers/rendering/renderer_rd/shaders/canvas.glsl b/servers/rendering/renderer_rd/shaders/canvas.glsl index 2a7cae3b4c..9c4e95a7c2 100644 --- a/servers/rendering/renderer_rd/shaders/canvas.glsl +++ b/servers/rendering/renderer_rd/shaders/canvas.glsl @@ -497,7 +497,7 @@ void main() { vec2 shadow_vertex = vertex; { - float normal_depth = 1.0; + float normal_map_depth = 1.0; #if defined(NORMAL_MAP_USED) vec3 normal_map = vec3(0.0, 0.0, 1.0); @@ -511,7 +511,7 @@ FRAGMENT_SHADER_CODE /* clang-format on */ #if defined(NORMAL_MAP_USED) - normal = mix(vec3(0.0, 0.0, 1.0), normal_map * vec3(2.0, -2.0, 1.0) - vec3(1.0, -1.0, 0.0), normal_depth); + normal = mix(vec3(0.0, 0.0, 1.0), normal_map * vec3(2.0, -2.0, 1.0) - vec3(1.0, -1.0, 0.0), normal_map_depth); #endif } diff --git a/servers/rendering/renderer_rd/shaders/scene_forward.glsl b/servers/rendering/renderer_rd/shaders/scene_forward.glsl index 05f7637478..1c12a8a4c7 100644 --- a/servers/rendering/renderer_rd/shaders/scene_forward.glsl +++ b/servers/rendering/renderer_rd/shaders/scene_forward.glsl @@ -1855,7 +1855,7 @@ void main() { vec3 normal_map = vec3(0.5); #endif - float normal_depth = 1.0; + float normal_map_depth = 1.0; vec2 screen_uv = gl_FragCoord.xy * scene_data.screen_pixel_size + scene_data.screen_pixel_size * 0.5; //account for center @@ -1931,7 +1931,7 @@ FRAGMENT_SHADER_CODE normal_map.xy = normal_map.xy * 2.0 - 1.0; normal_map.z = sqrt(max(0.0, 1.0 - dot(normal_map.xy, normal_map.xy))); //always ignore Z, as it can be RG packed, Z may be pos/neg, etc. - normal = normalize(mix(normal, tangent * normal_map.x + binormal * normal_map.y + normal * normal_map.z, normal_depth)); + normal = normalize(mix(normal, tangent * normal_map.x + binormal * normal_map.y + normal * normal_map.z, normal_map_depth)); #endif diff --git a/servers/rendering/renderer_rd/shaders/ssao.glsl b/servers/rendering/renderer_rd/shaders/ssao.glsl index 315ef8fa13..231f8f91ec 100644 --- a/servers/rendering/renderer_rd/shaders/ssao.glsl +++ b/servers/rendering/renderer_rd/shaders/ssao.glsl @@ -88,7 +88,7 @@ counter; layout(rg8, set = 2, binding = 0) uniform restrict writeonly image2D dest_image; // This push_constant is full - 128 bytes - if you need to add more data, consider adding to the uniform buffer instead -layout(push_constant, binding = 1, std430) uniform Params { +layout(push_constant, binding = 3, std430) uniform Params { ivec2 screen_size; int pass; int quality; |