Dynamic Variables/ru: Difference between revisions

From Resonite Wiki
Created page with "Динамические переменные также по умолчанию являются глобальными. Если вы управляете динамической переменной, значение переменной становится локальным. Если у вас есть другая версия этой перменной где-либо, которой вы не управляете, это приведет к синх..."
Updating to match new version of source page
 
Line 1: Line 1:
<languages/>
<languages/>


== Обзор ==
<div lang="en" dir="ltr" class="mw-content-ltr">
'''Dynamic variables''', commonly shorted to '''dyn vars''' or '''dynvars''', is a system of data storage wherein one can store arbitrary, scoped data under slot hierarchies with arbitrary names, akin to that of an [https://en.wikipedia.org/wiki/Associative_array associative array]. Their usage is usually found in large systems with many moving parts, but can nonetheless be useful as easy "global" values that can be changed on an object.
</div>


'''Динамические переменные''' позволяют вам читать и писать данные по имени в контексте иерархии [[Slot|слотов]]. Это упрощает управление данными в больших системах; каждый бит данных четко помечен, и вы можете разбивать данные на несколько '''пространств''', чтобы разделять ваши системы.
<div lang="en" dir="ltr" class="mw-content-ltr">
For a quick-start guide on using dynamic variables, the [[How To Use Dynamic Variables]] page serves to be a how-to.
</div>


== Ограничения именования ==
<div lang="en" dir="ltr" class="mw-content-ltr">
При использовании динамических переменных существуют некоторые ограничения на именование пространств и переменных внутри этих пространств.
== Overview ==
Dynamic variables are managed with two parts: ''dynamic variable spaces'' and ''dynamic variables''. Dynamic variables live under a dynamic variable space, and can be created, modified, and destroyed dynamically.
</div>


Пространства и имена переменных '''не могут содержать''':
<div lang="en" dir="ltr" class="mw-content-ltr">
* Любые символы
=== Variable Spaces ===
** Как определено в C# [https://docs.microsoft.com/en-us/dotnet/api/system.char.issymbol?view=net-5.0 Char.IsSymbol]
By adding a [[Component:DynamicVariableSpace|DynamicVariableSpace]] to a slot, the slot and all of its children become a part of the named variable space. This does not necessarily mean that every dynamic variable under this slot is "attached" to the space. This is explained further in [[#Binding]].
* Любую пунктуацию / Пустые строки
</div>
** Как определено в C# [https://docs.microsoft.com/en-us/dotnet/api/system.char.ispunctuation?view=net-5.0 Char.IsPunctuation] и C# [https://docs.microsoft.com/en-us/dotnet/api/system.char.iswhitespace?view=net-5.0 Char.IsWhiteSpace]
* '''За исключением''' точки (.), нижнего подчеркивания (_) и пробела ( ).


{{Note|Какую концепцию или свойства предоставляют ваши пространства и переменные? Не торопитесь и назовите их как следует!<br/> Эти имена будут использоваться в разных местах или даже другими пользователями. Изменения этих имен потом может оказаться довольно сложной задачей. |suggestion}}
<div lang="en" dir="ltr" class="mw-content-ltr">
A slot can be part of multiple spaces at once. Spaces under child slots are <em>not</em> nested with respect to parent spaces in any form, meaning it is advised to make unique names for variable spaces.
</div>


== Использование ==
<div lang="en" dir="ltr" class="mw-content-ltr">
=== Dynamic Variables ===
To create a dynamic variable, attach any one of the following components to a slot that is part of a variable space:
</div>


При желании к имени может быть добавлен префикс в виде '''пространства''' заканчивающийся символом '''/''', чтобы выбрать конкретное пространство для использования переменной. Это полезно для того, что различать несвязанные системы, в которых используют динамические переменные.
<div lang="en" dir="ltr" class="mw-content-ltr">
* [[Component:DynamicValueVariable|DynamicValueVariable]], for working with [[Value Types|value types]] ([[Type:int|int]], [[Type:string|string]], [[Type:float3|float3]], etc.).
* [[Component:DynamicReferenceVariable|DynamicReferenceVariable]], for working with [[Reference Types|reference types]] ([[Type:Slot|Slot]], [[Type:User|User]], etc.).
* [[Component:DynamicTypeVariable|DynamicTypeVariable]], for working with the [[Type:Type|Type]] type.
</div>


Некоторые допустимые имена:
<div lang="en" dir="ltr" class="mw-content-ltr">
Dynamic variables have a name and a value. A variable's name is its unique identifier within the variable space, while its value is the value of the dynamic variable.
</div>


* Health -- нет определенного пространства, имя Health
<div lang="en" dir="ltr" class="mw-content-ltr">
* World/Color -- имя Color, в пространстве World
=== Dynamic Fields ===
* MyCoolSystem/Score -- имя Score, в пространстве MyCoolSystem
It is possible to "transform" an existing [[Type:IField|IField]] on a component into a dynamic variable. This is done by any one of the following components:
</div>


=== Пространства ===
<div lang="en" dir="ltr" class="mw-content-ltr">
* [[Component:DynamicField|DynamicField]], for working with [[Value Types|value types]].
* [[Component:DynamicReference|DynamicReference]], for working with [[Reference Types|reference types]].
* [[Component:DynamicTypeField|DynamicTypeField]], for working with the [[Type:Type|Type]] type.
</div>


Динамические переменные могут находиться в слоте содержащий компонент [[DynamicVariableSpace (Component)|DynamicVariableSpace]] или в его дочерних слотах.
<div lang="en" dir="ltr" class="mw-content-ltr">
Upon attaching the component and dragging the field to convert into <code>TargetField</code>, the pointed field can then be interfaced with like any other dynamic variable.
</div>


Таким образом, пространство для переменных находящиеся в корневом слоте мира можно использовать из любого места, но пространство для переменных на вашем аватаре можно использовать из всех слотов, что хранятся в вашем аватаре.
<div lang="en" dir="ltr" class="mw-content-ltr">
=== Naming Restrictions ===
The names of dynamic variables and dynamic variable spaces must not contain symbols, punctuation, or whitespace, <em>except</em> for period (<code>.</code>), underscore (<code>_</code>), and space (<code> </code>). To check if a character is unable to be used in a dynamic variable name, one can use the [[ProtoFlux:Is Symbol|Is Symbol]], [[ProtoFlux:Is Punctuation|Is Punctuation]], and [[ProtoFlux:Is White Space|Is White Space]] ProtoFlux nodes, taking care of the three exceptions above.
</div>


=== Переменные ===
<div lang="en" dir="ltr" class="mw-content-ltr">
== Binding ==
The process of a dynamic variable being associated with a given space is called ''binding''. A dynamic variable component will traverse up the slot hierarchy, including its current slot, looking for an applicable variable space to bind to. If a dynamic variable does not find a dynamic variable space that it can bind to, it will not be accessible outside of the component itself, essentially reducing to a glorified [[Component:ValueField|ValueField]]. A dynamic variable will go through this binding process every time any part of the component changes.
</div>


Самый простой способ использовать динамические переменные - это использовать компоненты [[Component:DynamicValueVariable|DynamicValueVariable<T>]] и [[Component:DynamicReferenceVariable|DynamicReferenceVariable<T>]]. Они предназначены для значимых (int, float, String, etc.) и ссылочных (Slot, User, etc.) типов, соответственно. Компонент [[Component:DynamicTypeVariable|DynamicTypeVariable]] существует для хранения [[Type:Type|типов]].
<div lang="en" dir="ltr" class="mw-content-ltr">
=== Direct Vs Indirect Binding ===
Эти компоненты хранят значение или непосредственно ссылку на него. Если два компонента содержат одинаковые имена, то они будут иметь одинаковое содержимое.
When making a dynamic variable, the <code>VariableName</code> of a dynamic variable component can be one of the following two forms: <code>VariableName</code> or <code>VariableSpaceName/VariableName</code>. The former represents ''indirect binding'', while the latter represents ''direct binding''.
</div>


=== Поля ===
<div lang="en" dir="ltr" class="mw-content-ltr">
If a dynamic variable is indirectly binding, it will bind to the first dynamic variable space that does not have <code>OnlyDirectBinding</code> set to <code>True</code>. If a dynamic variable is directly binding, it will bind to the first dynamic variable space that matches <code>VariableSpaceName</code>.
</div>


Если вы хотите использовать существующее поле или ссылку на него в качестве содержимого динамической переменной, вы можете использовать компоненты [[Component:DynamicField|DynamicField<T>]] или [[Component:DynamicReference|DynamicReference<T>]]. Вместо того чтобы сохранять что-либо напрямую, они указывают на поле, содержащее значение или ссылочный тип, соответственно.
<div lang="en" dir="ltr" class="mw-content-ltr">
=== Binding Examples ===
In the following setup:
</div>


Как и в случае с переменными, существует вариант для полей содержащие <code>Тип</code> : [[Component:DynamicTypeField|DynamicTypeField]]
└─ Foo - Variable Space "test"
    └─ Bar - Variable Space "test2"
      └─ Baz - Dynamic Variable "test/var"


(TODO: уточнить разницу между значимыми и ссылочными типами)
<div lang="en" dir="ltr" class="mw-content-ltr">
The dynamic variable <code>test/var</code> will bind to the variable space <code>test</code>. If the variable was instead named <code>var</code>, it will bind to the variable space <code>test2</code>. If the variable was named <code>var</code> and <code>test2</code> has <code>OnlyDirectBinding</code> enabled, it would bind to <code>test</code>.
</div>


=== "Драйверы" ===
<div lang="en" dir="ltr" class="mw-content-ltr">
=== Binding Delay Warning ===
As of the time of writing, there exist a few instances where created variables do not instantly bind/rebind to a dynamic variable space, requiring a [[ProtoFlux:Delay Updates|Delay Updates]] of 2 or more updates. These include:
</div>


Вы можете использовать содержимое динамической переменной для управления полем или ссылкой, используя компоненты [[Component:DynamicValueVariableDriver|DynamicValueVariableDriver<T>]] и [[Component:DynamicReferenceVariableDriver|DynamicReferenceVariableDriver<T>]].
<div lang="en" dir="ltr" class="mw-content-ltr">
* [https://github.com/Yellow-Dog-Man/Resonite-Issues/issues/1394 Creating new dynamic reference variables].
* [https://github.com/Yellow-Dog-Man/Resonite-Issues/issues/2717 Deleting dynamic variables].
* Changing the name of a dynamic variable or dynamic variable space.
* Any instance where there is a dynamic variable space change without a component update, such as:
** [https://github.com/Yellow-Dog-Man/Resonite-Issues/issues/1690 duplicating slots containing a dynamic variable space].
** Reparenting a slot containing a dynamic variable under a new dynamic variable space.
</div>


=== Не представленные типы ===
<div lang="en" dir="ltr" class="mw-content-ltr">
If you find dynamic variables to be behaving weirdly, and you are doing any of these operations, try adding a delay of 2 or more updates between such operations.
</div>


При создании компонента динамической переменной вам будет предоставлен список "распространённых типов". Если нужного вам типа нету в этом списке, вам придется ввести его вручную. Смотрите [[Complex Types in Components|Сложные типы в компонентах]].
<div lang="en" dir="ltr" class="mw-content-ltr">
== Interfacing ==
A variable space can be interfaced with any slot that resides within the variable space, even if the slot is not part of the hierarchy containing the exact dynamic variable being interfaced with.
</div>


=== Привязка ===
<div lang="en" dir="ltr" class="mw-content-ltr">
=== Reading Dynvars ===
In ProtoFlux, the [[ProtoFlux:Read Dynamic Variable|Read Dynamic Variable]] node and [[ProtoFlux:Dynamic Variable Input|Dynamic Variable Input]] nodes exist to read dynamic variables from a slot.
</div>


Создание, дублирование или перемещение динамической переменной требует '''привязки''' этой переменной к пространству.
<div lang="en" dir="ltr" class="mw-content-ltr">
Это процесс, который выполняется автоматически, но пока что еще не совершенен. (cмотри [[#Warning|Предупреждение]])
The Read Dynamic Variable node takes in a <code>Source</code> [[Slot]] and a <code>Path</code> variable name, and is marked as [[ContinuouslyChanging]]. The Dynamic Variable Input node uses a [[Global]] for <code>Path</code> and binds to spaces in the slot hierarchy it exists in. Therefore, when reading constant-name dynamic variables within the same dynamic variable space of the slot the node exists in, the Dynamic Variable Input node is preferred. When reading dynamic variables from a space outside the node's slot hierarchy, the Read Dynamic Variable node must be used.
</div>


По сути, компонент начинает поиск подходящего пространства для динамической переменной в слоте в котором находится переменная.
<div lang="en" dir="ltr" class="mw-content-ltr">
Если совпадений нет, он попробует поискать в родительском слоте, затем в родителе родителя и так далее, пока подходящее пространство не будет найдено.
It is also possible to read dynamic variables by sourcing the <code>Value</code> or <code>Reference</code> field of the component directly. This is not recommended, as if the dynamic variable ever gets deleted and remade, the source will break, removing half the functionality of a dynamic variable.
Переменные с явно заданными именами динамического пространства соответствуют только пространствам с таким же именем.
</div>
Переменные без явного указания имени пространства соответствуют всем пространствам, в которых не включен <code>OnlyDirectBinding</code>.


На следующем изображении показаны различия в привязке:
<div lang="en" dir="ltr" class="mw-content-ltr">
=== Driving from Dynvars ===
By using a [[Component:DynamicValueVariableDriver|DynamicValueVariableDriver]] or [[Component:DynamicReferenceVariableDriver|DynamicReferenceVariableDriver]] component, fields can be driven using the value of a dynamic variable. This is recommended over traditional methods of driving by virtue of its flexibility and compactness.
</div>


[[File:Dynamic_Variables.svg|border|изображение, демонстрирующее, что пространства для динамических переменных с включенным OnlyDirectBinding игнорируются, за исключением переменных, которые явно объявили одно и тоже имя пространства]]
<div lang="en" dir="ltr" class="mw-content-ltr">
=== Writing to Dynvars ===
Dynamic variables should be written to via the [[ProtoFlux:Write Dynamic Variable|Write Dynamic Variable]] or [[ProtoFlux:Write Or Create Dynamic Variable|Write Or Create Dynamic Variable]] ProtoFlux nodes. The former will write to existing dynamic variables, while the latter will create the dynamic variable if it doesn't exist already.
</div>


* I: <code>A</code> связана с <code>Inner</code> потому что в пространстве <code>Inner</code> <u>не включен</u> <code>OnlyDirectBinding</code>.
<div lang="en" dir="ltr" class="mw-content-ltr">
* II/III: Обе переменных привязаны явно.
=== Driving Dynvars ===
* IV: <code>A</code> игнорирует пространство <code>Inner</code> потому что в пространстве <code>Inner</code> включен <code>OnlyDirectBinding</code>.
Driving dynamic variables must be done with caution. If a dynamic variable is being driven, it is <em>crucial</em> that <em>all</em> instances of the same dynamic variable are driven by the same value. Otherwise, clients will fight over which value is the "true" value of the dynamic variable and cause inconsistent behavior. The other caution relates to how driving is essentially a local write each frame, which is expanded on in [[#Writing/Driving_Delay_Warning]].
* V/VI: Обе переменных привязаны явно.
</div>
* VII/IX: Нет соответствующего пространства для динамических переменных. Обе переменных не привязаны.
* VIII: Переменная привязана к пространству <code>World</code>.
* I и II имеют одно и тоже значение.
* III, IV и VI имеют одно и тоже значение.


{{#mermaid:flowchart BT
<div lang="en" dir="ltr" class="mw-content-ltr">
    subgraph outside
=== Writing/Driving Delay Warning ===
       
If dynamic variables are written to via sourcing the component field and writing, it will incur a delay of 1 frame before the value is propagated to any read nodes. As such, it is highly not recommended to directly write to dynamic variable components, and always recommended to use the proper ProtoFlux nodes.
        InvalidSpace["Invalid, not linked"]
</div>
        RootSlot
    end
    subgraph RootSlot [RootSlot]
        World["Space #34;World#34;"]
        color["World/Color1"] --> World
       
       
        UserRootSlot
       
    end
    subgraph UserRootSlot
        UserSpace["Space #34;User#34;"]
        AvatarRootSlot
        V["User/Voice"] --> UserSpace
        V2["User/Color"] --> UserSpace
    end
   
    subgraph AvatarRootSlot
        avatar["User/Avatar"]
        avatarworld["World/Avatar.U-myid"]
        hips["HipsSlot"] --> AvatarSpace
        invalid["None/float"]
       
        AvatarSpace["Space #34;Avatar#34;"]
       
        Flux2_node0(["DynamicVariableInput#60;ColorX#62;#12;#34;World/Color1#34;"])
        Flux2_node0 -. points to .-> color
    end
   


   
<div lang="en" dir="ltr" class="mw-content-ltr">
    avatarworld --> World
When driving the value of a dynamic variable, it is essentially a local write to the component every frame. As such, the 1 frame of delay will apply there too. There is currently no good way to avoid this.
    avatar --> UserSpace
</div>
    subgraph Flux1
        Flux1_node0(["User Root Slot"]) -. automatically points to .-> UserRootSlot
        Flux1_node1(["Read #34;User/Avatar#34;"]) --> Flux1_node0
        Flux1_node1 -. points to .-> AvatarRootSlot
        Flux1_node2(["Read Variable #34;Avatar/Hips#34;"]) --> Flux1_node1
        Flux1_node2 -. points to .-> hips
    end
    invalid --> InvalidSpace
   
   
   
   
}}


=== Предупреждение ===
<div lang="en" dir="ltr" class="mw-content-ltr">
== Best Practices ==
Even though dynamic variables allow for a wide array of freedom, there are a few practices generally considered to be favorable when working with dynamic variables:
</div>


В некоторых случаях привязка может занять небольшое время, до истечения которого динамическая переменная может казаться существующей, но недоступной для чтения или записи.
<div lang="en" dir="ltr" class="mw-content-ltr">
Таким образом, если вы создаете динамическую переменную с помощью [[ProtoFlux:Create Dynamic Variable|Create Dynamic Variable]] или [[ProtoFlux:Write Or Create Dynamic Variable|Write Or Create Dynamic Variable]] ProtoFlux нод, или дублируете её с помощью [[ProtoFlux:Duplicate Slot |Duplicate Slot]] ProtoFlux ноды, или перемещаете её с помощью [[ProtoFlux:Set Parent|Set Parent]] ProtoFlux ноды, возможно, вам потребуется добавить [[ProtoFlux:Updates Delay|Updates Delay]] или [[ProtoFlux:Updates Delay With Value|Updates Delay With Value]] ProtoFlux ноду после действия, чтобы убедиться, что динамические переменные были привязаны к моменту их использования. Обычно достаточно задержки на 1-3 обновления. Создание [[Component:DynamicValueVariable|DynamicValueVariable]] на уже существующих [[Component:DynamicVariableSpace|Dynamic Variable Space]] не требует каких-либо задержек.
* It is highly recommended to have only one instance of a dynamic variable (dynamic variable component with the same name) at any given time.
** There aren't any huge problems with having multiple dynamic variable instances if none or all of the instances are being driven, but it allows for cleaner organization of variables.
* Using variable names that directly bind allows for a clearer overview of what space the variables should be bound to. Indirectly binding variable names are more suited for variables that are dynamically created and/or destroyed as part of an object's function.
** Using <code>OnlyDirectBinding</code> on a DynamicVariableSpace strictly enforces this behavior, which can prevent misbindings and catch errors earlier.
* Dynamic variable spaces are not nested. If a system is complex enough, or if a DynamicVariableSpace is being shared by multiple objects, using periods (<code>.</code>) to pseudo-isolate objects or systems from one another is encouraged.
** e.g. an avatar and all of its features could contain the dynamic variables <code>User/Avatar.Systems.Grabbable.Enabled</code>, <code>User/Avatar.Blendshapes.Blep.MaxClamp</code>, <code>User/Avatar.Systems.Flight.Drag</code>, etc.
</div>


Динамические переменные также по умолчанию являются глобальными. Если вы [[drive|управляете]] динамической переменной, значение переменной становится локальным. Если у вас есть другая версия этой перменной где-либо, которой вы не управляете, это приведет к синхронизации значения переменной между всеми клиентами в сессии, что заставит значение этой переменной скакать между разными значениями хаотично.
<div lang="en" dir="ltr" class="mw-content-ltr">
== Default Spaces ==
As of the time of writing, there are three dynamic spaces that exist "by default":
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
* <code>World</code>, which exists under the [[Root]] of any created world. This space is marked as <code>OnlyDirectBinding</code>.
** Useful for things that should globally affect the world or broadcast information throughout the world. Example items that use this space include [[BeatLink]] and the [[Redprint]] manager.
* <code>User</code>, which exists under every [[User]]'s [[ProtoFlux:User Root Slot|User Root Slot]]. This space is <code>OnlyDirectBinding</code>.
** Useful for systems that affect avatars, as outside objects can rely on a standardized space being available for each user to read and write variables on.
* <code>Dash</code>, which exists under the slot containing the [[Component:UserspaceRadiantDash|UserspaceRadiantDash]] in userspace.
</div>


<!-- TODO: more precise list of problematic uses cases (e.g. <code>Duplicate Slot</code> of a whole space works totally fine.) -->
<div lang="en" dir="ltr" class="mw-content-ltr">
== Example Usage ==
</div>


== Примеры использования ==
<div lang="en" dir="ltr" class="mw-content-ltr">
=== One Contained System ===
Say you are working on a large and complicated system. In lieu of trying to manage "global" settings by sourcing ValueField components, you can use dynamic variables to help assign names to settings or other useful values. This is usually accomplished by placing a DynamicVariableSpace on the root of your object (or root of your "library") and having a specialized dynamic variable slot for containing the dynamic variables. Depending on how many dynamic variables are used, it may be beneficial to delegate them to multiple slots.
</div>


В следующих примерах будет продемонстрировано несколько вариантов использования динамических переменных.
<div lang="en" dir="ltr" class="mw-content-ltr">
Основное внимание уделяется тому, как использовать их для создания отдельных объектов
A screenshot showing a simple setup like this is shown below. Note the use of [[ProtoFlux:Dynamic Variable Input|Dynamic Variable Input]] nodes for performance sake.
</div>


=== Модули внутри объекта  ===
<div lang="en" dir="ltr" class="mw-content-ltr">
[[File:Dynamic Variable Example Internal System.webp|800px]]
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
=== Controlling Another System ===
Say that you want to make an external controller for a system on an avatar. This system uses the default <code>User</code> dynamic variable space and namespaces itself with <code>User/CoolAvatarSystem.</code>.
</div>


Динамические переменные внутри объекта допускают модульность.
<div lang="en" dir="ltr" class="mw-content-ltr">
Различные модули будут соединены с помощью динамических переменных в пространстве, расположенном в корне объекта.
The simplest way to get a slot to interface with this system can be obtained by getting the [[User]] in some fashion and plugging it into the [[ProtoFlux:User Root Slot|User Root Slot]] node. Reading with this system should be done with the [[ProtoFlux:Read Dynamic Variable|Read Dynamic Variable]] node, as the controller is not part of the dynamic variable space on the user.
Если все жестко запрограммированные ссылки, входящие в модуль или исходящие из него, удалены, вы можете заменить его другим вариантом/версий без дополнительной настройки.
</div>
Модуль-локальные переменные могут быть созданы так же с помощью динамических переменных, с расположенном в корне модуля пространством. Используете различное наименование пространств, чтобы отличить их друг от друга.
Чтобы сделать доступные переменные более очевидными для других людей, в том числе и для вас через 6 месяцев, рекомендуется поместить все динамические переменные в специальную иерархию слотов.


<!--T:42-->
<div lang="en" dir="ltr" class="mw-content-ltr">
Обычно для таких иерархий используются следующие названия:
From there, it's simply a matter of knowing the right variable names and types (e.g. <code>User/CoolAvatarSystem.Enabled</code> being a <code>bool</code>). Plugging the previously obtained slot into the <code>Source</code> of a Read Dynamic Variable of the matching type and path will get you the current value, while using a Write Dynamic Variable will allow you to write to it.
* DV
</div>
* DynVar
* Vars
* etc.


Модульный объект мог бы выглядеть следующим образом:
<div lang="en" dir="ltr" class="mw-content-ltr">
* Project (Пространство: <code>MyProject</code>)
== See Also ==
** Dynamic Variables
* [[Dynamic Impulses]]
*** projectVar: String (Dynamic variable <code>projectVar</code> of type [[Type:String|String]])
</div>
** Module: UI (например [[Component:MeshRenderer|MeshRenderer]] или [[Component:Canvas|Canvas]] а так же [[Collider|Коллайдеры]]), может содержать:
*** Dynamic Variable Drivers → Visuals
*** [[:Category:Components:Common_UI:Button_Interactions|Button Interactions]] → Dynamic Variables
*** [[:Category:Components:Common_UI:Editors|Editors]] ↔ Dynamic Variables
** Module: Logic (Space: <code>Logic</code>)
*** Dynamic Variables
**** logicVar: int (Dynamic variable <code>logicVar</code> of type [[Type:Int|int]])
**** MyProject/Logic: Slot (Dynamic variable <code>Logic</code> of type [[Slot]] for space <code>MyProject</code>, driven with reference to Slot of module to make it accessible to other modules)
*** [[ProtoFlux]] (может читать, записывать или даже управлять динамическими переменными пространства <code>MyProject</code>)
 
=== Настраиваемые объекты  ===
 
Динамические переменные позволяют получать доступ к свойствам других объектов.
 
Предположим, что у объектов есть динамическое пространство, коллайдер и строковая переменная с именем <code>Описание</code>. Тогда, вы могли бы создать отдельный инструмент, который считывает и отображает <code>Описание</code> в объекте на который применяется инструмент. Этот же инструмент можно было бы расширить для редактирования описаний.
 
Эта же концепция может быть применена и к шаблонам слотов, используемым в рамках проекта.
С их экземплярами можно взаимодействовать с помощью динамических переменных.
 
=== Мировые и Пользовательские переменные  ===
 
Уже существуют заранее созданные пространства для динамических переменных:
* <code>World</code> в [[Root|Корне мира]] (<code>OnlyDirectBinding</code>)
* <code>User</code> в каждом слоте [[Component:UserRoot|Корня Пользователя]] (<code>OnlyDirectBinding</code>)
* <code>Dash</code> в слоте из [[Component:UserspaceRadiantDash|UserSpaceRadiantDash]]
Они могут использоваться для определения состояний, которые являются общими для многих объектов (например, переключение для и ночи, статистика производительности), или для трансляции информации в окружающий мир. ([[BeatLink]], объекты "библиотеки", например такие как менеджер [[Redprint]])
 
 
Смотрите [[Dynamic Variable Naming Standard|Стандарт именования динамических переменных]] для большой информации.

Latest revision as of 01:20, 6 September 2024

Dynamic variables, commonly shorted to dyn vars or dynvars, is a system of data storage wherein one can store arbitrary, scoped data under slot hierarchies with arbitrary names, akin to that of an associative array. Their usage is usually found in large systems with many moving parts, but can nonetheless be useful as easy "global" values that can be changed on an object.

For a quick-start guide on using dynamic variables, the How To Use Dynamic Variables page serves to be a how-to.

Overview

Dynamic variables are managed with two parts: dynamic variable spaces and dynamic variables. Dynamic variables live under a dynamic variable space, and can be created, modified, and destroyed dynamically.

Variable Spaces

By adding a DynamicVariableSpace to a slot, the slot and all of its children become a part of the named variable space. This does not necessarily mean that every dynamic variable under this slot is "attached" to the space. This is explained further in #Binding.

A slot can be part of multiple spaces at once. Spaces under child slots are not nested with respect to parent spaces in any form, meaning it is advised to make unique names for variable spaces.

Dynamic Variables

To create a dynamic variable, attach any one of the following components to a slot that is part of a variable space:

Dynamic variables have a name and a value. A variable's name is its unique identifier within the variable space, while its value is the value of the dynamic variable.

Dynamic Fields

It is possible to "transform" an existing IField on a component into a dynamic variable. This is done by any one of the following components:

Upon attaching the component and dragging the field to convert into TargetField, the pointed field can then be interfaced with like any other dynamic variable.

Naming Restrictions

The names of dynamic variables and dynamic variable spaces must not contain symbols, punctuation, or whitespace, except for period (.), underscore (_), and space ( ). To check if a character is unable to be used in a dynamic variable name, one can use the Is Symbol, Is Punctuation, and Is White Space ProtoFlux nodes, taking care of the three exceptions above.

Binding

The process of a dynamic variable being associated with a given space is called binding. A dynamic variable component will traverse up the slot hierarchy, including its current slot, looking for an applicable variable space to bind to. If a dynamic variable does not find a dynamic variable space that it can bind to, it will not be accessible outside of the component itself, essentially reducing to a glorified ValueField. A dynamic variable will go through this binding process every time any part of the component changes.

Direct Vs Indirect Binding

When making a dynamic variable, the VariableName of a dynamic variable component can be one of the following two forms: VariableName or VariableSpaceName/VariableName. The former represents indirect binding, while the latter represents direct binding.

If a dynamic variable is indirectly binding, it will bind to the first dynamic variable space that does not have OnlyDirectBinding set to True. If a dynamic variable is directly binding, it will bind to the first dynamic variable space that matches VariableSpaceName.

Binding Examples

In the following setup:

└─ Foo - Variable Space "test"
   └─ Bar - Variable Space "test2"
      └─ Baz - Dynamic Variable "test/var"

The dynamic variable test/var will bind to the variable space test. If the variable was instead named var, it will bind to the variable space test2. If the variable was named var and test2 has OnlyDirectBinding enabled, it would bind to test.

Binding Delay Warning

As of the time of writing, there exist a few instances where created variables do not instantly bind/rebind to a dynamic variable space, requiring a Delay Updates of 2 or more updates. These include:

If you find dynamic variables to be behaving weirdly, and you are doing any of these operations, try adding a delay of 2 or more updates between such operations.

Interfacing

A variable space can be interfaced with any slot that resides within the variable space, even if the slot is not part of the hierarchy containing the exact dynamic variable being interfaced with.

Reading Dynvars

In ProtoFlux, the Read Dynamic Variable node and Dynamic Variable Input nodes exist to read dynamic variables from a slot.

The Read Dynamic Variable node takes in a Source Slot and a Path variable name, and is marked as ContinuouslyChanging. The Dynamic Variable Input node uses a Global for Path and binds to spaces in the slot hierarchy it exists in. Therefore, when reading constant-name dynamic variables within the same dynamic variable space of the slot the node exists in, the Dynamic Variable Input node is preferred. When reading dynamic variables from a space outside the node's slot hierarchy, the Read Dynamic Variable node must be used.

It is also possible to read dynamic variables by sourcing the Value or Reference field of the component directly. This is not recommended, as if the dynamic variable ever gets deleted and remade, the source will break, removing half the functionality of a dynamic variable.

Driving from Dynvars

By using a DynamicValueVariableDriver or DynamicReferenceVariableDriver component, fields can be driven using the value of a dynamic variable. This is recommended over traditional methods of driving by virtue of its flexibility and compactness.

Writing to Dynvars

Dynamic variables should be written to via the Write Dynamic Variable or Write Or Create Dynamic Variable ProtoFlux nodes. The former will write to existing dynamic variables, while the latter will create the dynamic variable if it doesn't exist already.

Driving Dynvars

Driving dynamic variables must be done with caution. If a dynamic variable is being driven, it is crucial that all instances of the same dynamic variable are driven by the same value. Otherwise, clients will fight over which value is the "true" value of the dynamic variable and cause inconsistent behavior. The other caution relates to how driving is essentially a local write each frame, which is expanded on in #Writing/Driving_Delay_Warning.

Writing/Driving Delay Warning

If dynamic variables are written to via sourcing the component field and writing, it will incur a delay of 1 frame before the value is propagated to any read nodes. As such, it is highly not recommended to directly write to dynamic variable components, and always recommended to use the proper ProtoFlux nodes.

When driving the value of a dynamic variable, it is essentially a local write to the component every frame. As such, the 1 frame of delay will apply there too. There is currently no good way to avoid this.

Best Practices

Even though dynamic variables allow for a wide array of freedom, there are a few practices generally considered to be favorable when working with dynamic variables:

  • It is highly recommended to have only one instance of a dynamic variable (dynamic variable component with the same name) at any given time.
    • There aren't any huge problems with having multiple dynamic variable instances if none or all of the instances are being driven, but it allows for cleaner organization of variables.
  • Using variable names that directly bind allows for a clearer overview of what space the variables should be bound to. Indirectly binding variable names are more suited for variables that are dynamically created and/or destroyed as part of an object's function.
    • Using OnlyDirectBinding on a DynamicVariableSpace strictly enforces this behavior, which can prevent misbindings and catch errors earlier.
  • Dynamic variable spaces are not nested. If a system is complex enough, or if a DynamicVariableSpace is being shared by multiple objects, using periods (.) to pseudo-isolate objects or systems from one another is encouraged.
    • e.g. an avatar and all of its features could contain the dynamic variables User/Avatar.Systems.Grabbable.Enabled, User/Avatar.Blendshapes.Blep.MaxClamp, User/Avatar.Systems.Flight.Drag, etc.

Default Spaces

As of the time of writing, there are three dynamic spaces that exist "by default":

  • World, which exists under the Root of any created world. This space is marked as OnlyDirectBinding.
    • Useful for things that should globally affect the world or broadcast information throughout the world. Example items that use this space include BeatLink and the Redprint manager.
  • User, which exists under every User's User Root Slot. This space is OnlyDirectBinding.
    • Useful for systems that affect avatars, as outside objects can rely on a standardized space being available for each user to read and write variables on.
  • Dash, which exists under the slot containing the UserspaceRadiantDash in userspace.

Example Usage

One Contained System

Say you are working on a large and complicated system. In lieu of trying to manage "global" settings by sourcing ValueField components, you can use dynamic variables to help assign names to settings or other useful values. This is usually accomplished by placing a DynamicVariableSpace on the root of your object (or root of your "library") and having a specialized dynamic variable slot for containing the dynamic variables. Depending on how many dynamic variables are used, it may be beneficial to delegate them to multiple slots.

A screenshot showing a simple setup like this is shown below. Note the use of Dynamic Variable Input nodes for performance sake.

Controlling Another System

Say that you want to make an external controller for a system on an avatar. This system uses the default User dynamic variable space and namespaces itself with User/CoolAvatarSystem..

The simplest way to get a slot to interface with this system can be obtained by getting the User in some fashion and plugging it into the User Root Slot node. Reading with this system should be done with the Read Dynamic Variable node, as the controller is not part of the dynamic variable space on the user.

From there, it's simply a matter of knowing the right variable names and types (e.g. User/CoolAvatarSystem.Enabled being a bool). Plugging the previously obtained slot into the Source of a Read Dynamic Variable of the matching type and path will get you the current value, while using a Write Dynamic Variable will allow you to write to it.

See Also