diff options
Diffstat (limited to 'modules')
23 files changed, 3544 insertions, 2991 deletions
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 |