From 87bf85c2e482a3bfbfec0642c76f15bf01166c23 Mon Sep 17 00:00:00 2001 From: Robert Date: Wed, 14 Sep 2022 19:34:36 +0200 Subject: [PATCH 1/7] Sidebar - Reorganized buttons and context menus --- .../Screens/Sidebar/SidebarCategoryView.axaml | 50 ++++++++++++------- .../Sidebar/SidebarCategoryViewModel.cs | 28 ++++++++--- 2 files changed, 53 insertions(+), 25 deletions(-) diff --git a/src/Artemis.UI/Screens/Sidebar/SidebarCategoryView.axaml b/src/Artemis.UI/Screens/Sidebar/SidebarCategoryView.axaml index d8d5e44f2..18af04054 100644 --- a/src/Artemis.UI/Screens/Sidebar/SidebarCategoryView.axaml +++ b/src/Artemis.UI/Screens/Sidebar/SidebarCategoryView.axaml @@ -15,23 +15,6 @@ - - - - - - - - - - - - - - - - - @@ -48,12 +31,29 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/Artemis.UI/Ninject/UiModule.cs b/src/Artemis.UI/Ninject/UiModule.cs index 0c9816eb7..41a355fbb 100644 --- a/src/Artemis.UI/Ninject/UiModule.cs +++ b/src/Artemis.UI/Ninject/UiModule.cs @@ -2,8 +2,10 @@ using Artemis.UI.Ninject.Factories; using Artemis.UI.Ninject.InstanceProviders; using Artemis.UI.Screens; +using Artemis.UI.Screens.VisualScripting; using Artemis.UI.Services.Interfaces; using Artemis.UI.Shared; +using Artemis.UI.Shared.Services.NodeEditor; using Artemis.UI.Shared.Services.ProfileEditor; using Avalonia.Platform; using Avalonia.Shared.PlatformSupport; @@ -57,6 +59,7 @@ public class UIModule : NinjectModule .BindToFactory(); }); + Kernel.Bind().To(); Kernel.Bind().ToFactory(() => new LayerPropertyViewModelInstanceProvider()); // Bind all UI services as singletons diff --git a/src/Artemis.UI/Screens/ProfileEditor/Panels/Properties/PropertiesViewModel.cs b/src/Artemis.UI/Screens/ProfileEditor/Panels/Properties/PropertiesViewModel.cs index 0c172200c..6471d49c8 100644 --- a/src/Artemis.UI/Screens/ProfileEditor/Panels/Properties/PropertiesViewModel.cs +++ b/src/Artemis.UI/Screens/ProfileEditor/Panels/Properties/PropertiesViewModel.cs @@ -76,18 +76,23 @@ public class PropertiesViewModel : ActivatableViewModelBase }); // Subscribe to events of the latest selected profile element - borrowed from https://stackoverflow.com/a/63950940 - this.WhenAnyValue(vm => vm.ProfileElement) - .Select(p => p is Layer l - ? Observable.FromEventPattern(x => l.LayerBrushUpdated += x, x => l.LayerBrushUpdated -= x) - : Observable.Never>()) - .Switch() - .Subscribe(_ => UpdatePropertyGroups()); - this.WhenAnyValue(vm => vm.ProfileElement) - .Select(p => p != null - ? Observable.FromEventPattern(x => p.LayerEffectsUpdated += x, x => p.LayerEffectsUpdated -= x) - : Observable.Never>()) - .Switch() - .Subscribe(_ => UpdatePropertyGroups()); + this.WhenActivated(d => + { + this.WhenAnyValue(vm => vm.ProfileElement) + .Select(p => p is Layer l + ? Observable.FromEventPattern(x => l.LayerBrushUpdated += x, x => l.LayerBrushUpdated -= x) + : Observable.Never>()) + .Switch() + .Subscribe(_ => UpdatePropertyGroups()) + .DisposeWith(d); + this.WhenAnyValue(vm => vm.ProfileElement) + .Select(p => p != null + ? Observable.FromEventPattern(x => p.LayerEffectsUpdated += x, x => p.LayerEffectsUpdated -= x) + : Observable.Never>()) + .Switch() + .Subscribe(_ => UpdatePropertyGroups()) + .DisposeWith(d); + }); this.WhenAnyValue(vm => vm.ProfileElement).Subscribe(_ => UpdatePropertyGroups()); this.WhenAnyValue(vm => vm.LayerProperty).Subscribe(_ => UpdateTimelineViewModel()); } diff --git a/src/Artemis.UI/Screens/VisualScripting/NodeScriptWindowViewModel.cs b/src/Artemis.UI/Screens/VisualScripting/NodeScriptWindowViewModel.cs index 19eefefb8..911835000 100644 --- a/src/Artemis.UI/Screens/VisualScripting/NodeScriptWindowViewModel.cs +++ b/src/Artemis.UI/Screens/VisualScripting/NodeScriptWindowViewModel.cs @@ -8,7 +8,6 @@ using System.Threading.Tasks; using Artemis.Core; using Artemis.Core.Services; using Artemis.UI.Ninject.Factories; -using Artemis.UI.Shared; using Artemis.UI.Shared.Services; using Artemis.UI.Shared.Services.NodeEditor; using Artemis.UI.Shared.Services.NodeEditor.Commands; @@ -20,7 +19,7 @@ using ReactiveUI; namespace Artemis.UI.Screens.VisualScripting; -public class NodeScriptWindowViewModel : DialogViewModelBase +public class NodeScriptWindowViewModel : NodeScriptWindowViewModelBase { private readonly INodeEditorService _nodeEditorService; private readonly INodeService _nodeService; @@ -34,7 +33,7 @@ public class NodeScriptWindowViewModel : DialogViewModelBase INodeVmFactory vmFactory, ISettingsService settingsService, IProfileService profileService, - IWindowService windowService) + IWindowService windowService) : base(nodeScript) { NodeScript = nodeScript; NodeScriptViewModel = vmFactory.NodeScriptViewModel(NodeScript, false); @@ -77,7 +76,6 @@ public class NodeScriptWindowViewModel : DialogViewModelBase }); } - public NodeScript NodeScript { get; } public NodeScriptViewModel NodeScriptViewModel { get; set; } public NodeEditorHistory History { get; } diff --git a/src/Artemis.VisualScripting/Nodes/DataModel/DataModelEventNode.cs b/src/Artemis.VisualScripting/Nodes/DataModel/DataModelEventNode.cs index 054977e8b..9dec85f4c 100644 --- a/src/Artemis.VisualScripting/Nodes/DataModel/DataModelEventNode.cs +++ b/src/Artemis.VisualScripting/Nodes/DataModel/DataModelEventNode.cs @@ -1,29 +1,25 @@ -using System.Linq.Expressions; -using System.Reflection; -using Artemis.Core; -using Artemis.Core.Modules; +using Artemis.Core; using Artemis.Storage.Entities.Profile; using Artemis.VisualScripting.Nodes.DataModel.Screens; -using Humanizer; namespace Artemis.VisualScripting.Nodes.DataModel; [Node("Data Model-Event", "Outputs the latest values of a data model event.", "Data Model", OutputType = typeof(object))] public class DataModelEventNode : Node, IDisposable { - private readonly Dictionary, OutputPin> _propertyPins; - private DataModelPath? _dataModelPath; + private readonly ObjectOutputPins _objectOutputPins; private IDataModelEvent? _dataModelEvent; - private OutputPin? _oldValuePin; - private OutputPin? _newValuePin; + private DataModelPath? _dataModelPath; private DateTime _lastTrigger; private object? _lastValue; + private OutputPin? _newValuePin; + private OutputPin? _oldValuePin; private int _valueChangeCount; public DataModelEventNode() : base("Data Model-Event", "Outputs the latest values of a data model event.") { - _propertyPins = new Dictionary, OutputPin>(); - + _objectOutputPins = new ObjectOutputPins(this); + TimeSinceLastTrigger = CreateOutputPin("Time since trigger"); TriggerCount = CreateOutputPin("Trigger count"); @@ -48,20 +44,14 @@ public class DataModelEventNode : Node propertyAccessor, OutputPin outputPin) in _propertyPins) - { - if (!outputPin.ConnectedTo.Any()) - continue; - object value = dataModelEvent.LastEventArgumentsUntyped != null ? propertyAccessor(dataModelEvent.LastEventArgumentsUntyped) : outputPin.Type.GetDefault()!; - outputPin.Value = outputPin.IsNumeric ? new Numeric(value) : value; - } + _objectOutputPins.SetCurrentValue(dataModelEvent.LastEventArgumentsUntyped); } // If the path is a regular value, evaluate the current value else if (_oldValuePin != null && _newValuePin != null) @@ -71,13 +61,13 @@ public class DataModelEventNode : Node p.CustomAttributes.All(a => a.AttributeType != typeof(DataModelIgnoreAttribute)))) - { - // Expect an IDataModelEvent - ParameterExpression eventParameter = Expression.Parameter(typeof(DataModelEventArgs), "event"); - // Cast it to the actual event type - UnaryExpression eventCast = Expression.Convert(eventParameter, propertyInfo.DeclaringType!); - // Access the property - MemberExpression accessor = Expression.Property(eventCast, propertyInfo); - // Cast the property to an object (sadly boxing) - UnaryExpression objectCast = Expression.Convert(accessor, typeof(object)); - // Compile the resulting expression - Func expression = Expression.Lambda>(objectCast, eventParameter).Compile(); - - _propertyPins.Add(expression, CreateOrAddOutputPin(propertyInfo.PropertyType, propertyInfo.Name.Humanize())); - } + _objectOutputPins.ChangeType(dataModelEvent.ArgumentsType); } private void CreateValuePins() @@ -142,24 +118,31 @@ public class DataModelEventNode : Node pins = Pins.Skip(2).ToList(); - foreach (IPin pin in pins) - RemovePin((Pin) pin); - - _propertyPins.Clear(); - _oldValuePin = null; - _newValuePin = null; + // Clear the output pins by changing the type to null + _objectOutputPins.ChangeType(null); + + if (_oldValuePin != null) + { + RemovePin(_oldValuePin); + _oldValuePin = null; + } + + if (_newValuePin != null) + { + RemovePin(_newValuePin); + _newValuePin = null; + } } - + private void DataModelPathOnPathValidated(object? sender, EventArgs e) { // Update the output pin now that the type is known and attempt to restore the connection that was likely missing diff --git a/src/Artemis.VisualScripting/Nodes/List/ListOperatorEntity.cs b/src/Artemis.VisualScripting/Nodes/List/ListOperatorEntity.cs new file mode 100644 index 000000000..515f8be2e --- /dev/null +++ b/src/Artemis.VisualScripting/Nodes/List/ListOperatorEntity.cs @@ -0,0 +1,9 @@ +using Artemis.Storage.Entities.Profile.Nodes; + +namespace Artemis.VisualScripting.Nodes.List; + +public class ListOperatorEntity +{ + public NodeScriptEntity? Script { get; set; } + public ListOperator Operator { get; set; } +} \ No newline at end of file diff --git a/src/Artemis.VisualScripting/Nodes/List/ListOperatorNode.cs b/src/Artemis.VisualScripting/Nodes/List/ListOperatorNode.cs index 7a7d4e056..29ee2391a 100644 --- a/src/Artemis.VisualScripting/Nodes/List/ListOperatorNode.cs +++ b/src/Artemis.VisualScripting/Nodes/List/ListOperatorNode.cs @@ -4,37 +4,37 @@ using Artemis.VisualScripting.Nodes.List.Screens; namespace Artemis.VisualScripting.Nodes.List; -[Node("List Operator (Simple)", "Checks if any/all/no value in the input list matches the input value", "List", InputType = typeof(IEnumerable), OutputType = typeof(bool))] +[Node("List Operator (Simple)", "Checks if any/all/no values in the input list match the input value", "List", InputType = typeof(IEnumerable), OutputType = typeof(bool))] public class ListOperatorNode : Node { - public ListOperatorNode() : base("List Operator", "Checks if any/all/no value in the input list matches the input value") + public ListOperatorNode() : base("List Operator (Simple)", "Checks if any/all/no values in the input list match the input value") { InputList = CreateInputPin(); InputValue = CreateInputPin(); - Ouput = CreateOutputPin(); + Output = CreateOutputPin(); } public InputPin InputList { get; } public InputPin InputValue { get; } - public OutputPin Ouput { get; } + public OutputPin Output { get; } /// public override void Evaluate() { if (InputList.Value == null) { - Ouput.Value = Storage == ListOperator.None; + Output.Value = Storage == ListOperator.None; return; } object? input = InputValue.Value; if (Storage == ListOperator.Any) - Ouput.Value = InputList.Value.Cast().Any(v => v.Equals(input)); + Output.Value = InputList.Value.Cast().Any(v => v.Equals(input)); else if (Storage == ListOperator.All) - Ouput.Value = InputList.Value.Cast().All(v => v.Equals(input)); - else if (Storage == ListOperator.All) - Ouput.Value = InputList.Value.Cast().All(v => !v.Equals(input)); + Output.Value = InputList.Value.Cast().All(v => v.Equals(input)); + else if (Storage == ListOperator.None) + Output.Value = InputList.Value.Cast().All(v => !v.Equals(input)); } } diff --git a/src/Artemis.VisualScripting/Nodes/List/ListOperatorPredicateNode.cs b/src/Artemis.VisualScripting/Nodes/List/ListOperatorPredicateNode.cs new file mode 100644 index 000000000..571eedc83 --- /dev/null +++ b/src/Artemis.VisualScripting/Nodes/List/ListOperatorPredicateNode.cs @@ -0,0 +1,118 @@ +using System.Collections; +using Artemis.Core; +using Artemis.Core.Events; +using Artemis.VisualScripting.Nodes.List.Screens; + +namespace Artemis.VisualScripting.Nodes.List; + +[Node("List Operator (Advanced)", "Checks if any/all/no values in the input list match a condition", "List", InputType = typeof(IEnumerable), OutputType = typeof(bool))] +public class ListOperatorPredicateNode : Node, IDisposable +{ + private readonly object _scriptLock = new(); + private ListOperatorPredicateStartNode? _startNode; + + public ListOperatorPredicateNode() : base("List Operator (Advanced)", "Checks if any/all/no values in the input list match a condition") + { + + InputList = CreateInputPin(); + Output = CreateOutputPin(); + + InputList.PinConnected += InputListOnPinConnected; + } + + public InputPin InputList { get; } + public OutputPin Output { get; } + public NodeScript? Script { get; private set; } + + public override void Initialize(INodeScript script) + { + Storage ??= new ListOperatorEntity(); + + lock (_scriptLock) + { + Script = Storage?.Script != null + ? new NodeScript("Is match", "Determines whether the current list item is a match", Storage.Script, script.Context) + : new NodeScript("Is match", "Determines whether the current list item is a match", script.Context); + + // The load action may have created an event node, use that one over the one we have here + INode? existingEventNode = Script.Nodes.FirstOrDefault(n => n.Id == ListOperatorPredicateStartNode.NodeId); + if (existingEventNode != null) + _startNode = (ListOperatorPredicateStartNode) existingEventNode; + else + { + _startNode = new ListOperatorPredicateStartNode {X = -200}; + Script.AddNode(_startNode); + } + + UpdateStartNode(); + Script.LoadConnections(); + } + } + + /// + public override void Evaluate() + { + if (Storage == null) + return; + + if (InputList.Value == null) + { + Output.Value = Storage.Operator == ListOperator.None; + return; + } + + lock (_scriptLock) + { + if (Script == null) + return; + + if (Storage.Operator == ListOperator.Any) + Output.Value = InputList.Value.Cast().Any(EvaluateItem); + else if (Storage.Operator == ListOperator.All) + Output.Value = InputList.Value.Cast().All(EvaluateItem); + else if (Storage.Operator == ListOperator.None) + Output.Value = InputList.Value.Cast().All(v => !EvaluateItem(v)); + } + } + + private bool EvaluateItem(object item) + { + if (Script == null || _startNode == null) + return false; + + _startNode.Item = item; + Script.Run(); + return Script.Result; + } + + private void UpdateStartNode() + { + Type? type = InputList.ConnectedTo.FirstOrDefault()?.Type; + // List must be generic or there's no way to tell what objects it contains in advance, that's not supported for now + if (type is not {IsGenericType: true}) + return; + + Type listType = type.GetGenericArguments().Single(); + _startNode?.ChangeType(listType); + } + + private void InputListOnPinConnected(object? sender, SingleValueEventArgs e) + { + lock (_scriptLock) + { + UpdateStartNode(); + } + } + + #region IDisposable + + /// + public void Dispose() + { + Script?.Dispose(); + Script = null; + _startNode = null; + } + + #endregion +} \ No newline at end of file diff --git a/src/Artemis.VisualScripting/Nodes/List/ListOperatorPredicateStartNode.cs b/src/Artemis.VisualScripting/Nodes/List/ListOperatorPredicateStartNode.cs new file mode 100644 index 000000000..ca37fb237 --- /dev/null +++ b/src/Artemis.VisualScripting/Nodes/List/ListOperatorPredicateStartNode.cs @@ -0,0 +1,27 @@ +using Artemis.Core; + +namespace Artemis.VisualScripting.Nodes.List; + +public class ListOperatorPredicateStartNode : DefaultNode +{ + internal static readonly Guid NodeId = new("9A714CF3-8D02-4CC3-A1AC-73833F82D7C6"); + private readonly ObjectOutputPins _objectOutputPins; + + public ListOperatorPredicateStartNode() : base(NodeId, "List item", "Contains the current list item") + { + _objectOutputPins = new ObjectOutputPins(this); + } + + public object? Item { get; set; } + + public override void Evaluate() + { + if (Item != null) + _objectOutputPins.SetCurrentValue(Item); + } + + public void ChangeType(Type? type) + { + _objectOutputPins.ChangeType(type); + } +} \ No newline at end of file diff --git a/src/Artemis.VisualScripting/Nodes/List/Screens/ListOperatorPredicateNodeCustomView.axaml b/src/Artemis.VisualScripting/Nodes/List/Screens/ListOperatorPredicateNodeCustomView.axaml new file mode 100644 index 000000000..dbc6728a7 --- /dev/null +++ b/src/Artemis.VisualScripting/Nodes/List/Screens/ListOperatorPredicateNodeCustomView.axaml @@ -0,0 +1,14 @@ + + + + + + diff --git a/src/Artemis.VisualScripting/Nodes/List/Screens/ListOperatorPredicateNodeCustomView.axaml.cs b/src/Artemis.VisualScripting/Nodes/List/Screens/ListOperatorPredicateNodeCustomView.axaml.cs new file mode 100644 index 000000000..ab950da39 --- /dev/null +++ b/src/Artemis.VisualScripting/Nodes/List/Screens/ListOperatorPredicateNodeCustomView.axaml.cs @@ -0,0 +1,19 @@ +using Avalonia; +using Avalonia.Controls; +using Avalonia.Markup.Xaml; +using Avalonia.ReactiveUI; + +namespace Artemis.VisualScripting.Nodes.List.Screens; + +public partial class ListOperatorPredicateNodeCustomView : ReactiveUserControl +{ + public ListOperatorPredicateNodeCustomView() + { + InitializeComponent(); + } + + private void InitializeComponent() + { + AvaloniaXamlLoader.Load(this); + } +} \ No newline at end of file diff --git a/src/Artemis.VisualScripting/Nodes/List/Screens/ListOperatorPredicateNodeCustomViewModel.cs b/src/Artemis.VisualScripting/Nodes/List/Screens/ListOperatorPredicateNodeCustomViewModel.cs new file mode 100644 index 000000000..5add4895d --- /dev/null +++ b/src/Artemis.VisualScripting/Nodes/List/Screens/ListOperatorPredicateNodeCustomViewModel.cs @@ -0,0 +1,43 @@ +using System.Reactive; +using Artemis.Core; +using Artemis.UI.Shared.Services; +using Artemis.UI.Shared.Services.NodeEditor; +using Artemis.UI.Shared.VisualScripting; +using ReactiveUI; + +namespace Artemis.VisualScripting.Nodes.List.Screens; + +public class ListOperatorPredicateNodeCustomViewModel : CustomNodeViewModel +{ + private readonly ListOperatorPredicateNode _node; + private readonly IWindowService _windowService; + private ListOperator _operator; + + public ListOperatorPredicateNodeCustomViewModel(ListOperatorPredicateNode node, INodeScript script, IWindowService windowService) : base(node, script) + { + _node = node; + _windowService = windowService; + + OpenEditor = ReactiveCommand.CreateFromTask(ExecuteOpenEditor); + } + + public ReactiveCommand OpenEditor { get; } + + public ListOperator Operator + { + get => _operator; + set => this.RaiseAndSetIfChanged(ref _operator, value); + } + + private async Task ExecuteOpenEditor() + { + if (_node.Script == null) + return; + + await _windowService.ShowDialogAsync(("nodeScript", _node.Script)); + _node.Script.Save(); + + _node.Storage ??= new ListOperatorEntity(); + _node.Storage.Script = _node.Script.Entity; + } +} \ No newline at end of file From b779a86d139cacf71c1aa86f5afb2ff54e3fb642 Mon Sep 17 00:00:00 2001 From: Robert Date: Fri, 16 Sep 2022 19:40:06 +0200 Subject: [PATCH 4/7] Event conditions - Fix start-node disconnecting Input - Performance optimizations --- .../Profile/Conditions/EventCondition.cs | 294 +++++++----------- .../Profile/Conditions/EventOverlapMode.cs | 23 ++ .../Profile/Conditions/EventToggleOffMode.cs | 18 ++ .../Profile/Conditions/EventTriggerMode.cs | 17 + .../Services/Input/InputProvider.cs | 7 + .../Services/Input/InputService.cs | 74 +++-- .../Internal/EventConditionEventStartNode.cs | 7 +- .../EventConditionValueChangedStartNode.cs | 2 +- .../Internal/IEventConditionNode.cs | 5 - src/Artemis.Core/VisualScripting/Node.cs | 2 +- .../VisualScripting/NodeScript.cs | 25 +- .../Commands/UpdateEventConditionPath.cs | 4 +- .../Providers/Input/WindowsInputProvider.cs | 16 +- .../Nodes/List/ListOperatorPredicateNode.cs | 21 +- ...istOperatorPredicateNodeCustomViewModel.cs | 34 +- 15 files changed, 298 insertions(+), 251 deletions(-) create mode 100644 src/Artemis.Core/Models/Profile/Conditions/EventOverlapMode.cs create mode 100644 src/Artemis.Core/Models/Profile/Conditions/EventToggleOffMode.cs create mode 100644 src/Artemis.Core/Models/Profile/Conditions/EventTriggerMode.cs delete mode 100644 src/Artemis.Core/VisualScripting/Internal/IEventConditionNode.cs diff --git a/src/Artemis.Core/Models/Profile/Conditions/EventCondition.cs b/src/Artemis.Core/Models/Profile/Conditions/EventCondition.cs index cc342e12c..f198b5397 100644 --- a/src/Artemis.Core/Models/Profile/Conditions/EventCondition.cs +++ b/src/Artemis.Core/Models/Profile/Conditions/EventCondition.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Linq; using Artemis.Core.Internal; using Artemis.Storage.Entities.Profile.Abstract; @@ -13,12 +14,12 @@ public class EventCondition : CorePropertyChanged, INodeScriptCondition { private readonly string _displayName; private readonly EventConditionEntity _entity; + private NodeScript _script; + private DefaultNode _startNode; private DataModelPath? _eventPath; private DateTime _lastProcessedTrigger; private object? _lastProcessedValue; private EventOverlapMode _overlapMode; - private NodeScript _script; - private IEventConditionNode _startNode; private EventToggleOffMode _toggleOffMode; private EventTriggerMode _triggerMode; private bool _wasMet; @@ -33,7 +34,7 @@ public class EventCondition : CorePropertyChanged, INodeScriptCondition _entity = new EventConditionEntity(); _displayName = profileElement.GetType().Name; _startNode = new EventConditionEventStartNode {X = -300}; - _script = new NodeScript($"Activate {_displayName}", $"Whether or not the event should activate the {_displayName}", ProfileElement.Profile); + _script = new NodeScript($"Activate {_displayName}", $"Whether or not the event should activate the {_displayName}", ProfileElement.Profile, new List {_startNode}); } internal EventCondition(EventConditionEntity entity, RenderProfileElement profileElement) @@ -95,109 +96,6 @@ public class EventCondition : CorePropertyChanged, INodeScriptCondition set => SetAndNotify(ref _toggleOffMode, value); } - /// - /// Updates the event node, applying the selected event - /// - public void UpdateEventNode() - { - if (EventPath == null) - return; - - Type? pathType = EventPath.GetPropertyType(); - if (pathType == null) - return; - - // Create an event node if the path type is a data model event - if (pathType.IsAssignableTo(typeof(IDataModelEvent))) - { - EventConditionEventStartNode eventNode; - // Ensure the start node is an event node - if (_startNode is not EventConditionEventStartNode node) - { - eventNode = new EventConditionEventStartNode(); - ReplaceStartNode(eventNode); - _startNode = eventNode; - } - else - { - eventNode = node; - } - - IDataModelEvent? dataModelEvent = EventPath?.GetValue() as IDataModelEvent; - eventNode.CreatePins(dataModelEvent); - } - // Create a value changed node if the path type is a regular value - else - { - // Ensure the start nod is a value changed node - EventConditionValueChangedStartNode valueChangedNode; - // Ensure the start node is an event node - if (_startNode is not EventConditionValueChangedStartNode node) - { - valueChangedNode = new EventConditionValueChangedStartNode(); - ReplaceStartNode(valueChangedNode); - } - else - { - valueChangedNode = node; - } - - valueChangedNode.UpdateOutputPins(EventPath); - } - - if (!Script.Nodes.Contains(_startNode)) - Script.AddNode(_startNode); - Script.Save(); - } - - /// - /// Gets the start node of the event script, if any - /// - /// The start node of the event script, if any. - public INode GetStartNode() - { - return _startNode; - } - - private void ReplaceStartNode(IEventConditionNode newStartNode) - { - if (Script.Nodes.Contains(_startNode)) - Script.RemoveNode(_startNode); - - _startNode = newStartNode; - if (!Script.Nodes.Contains(_startNode)) - Script.AddNode(_startNode); - } - - private bool Evaluate() - { - if (EventPath == null) - return false; - - object? value = EventPath.GetValue(); - if (_startNode is EventConditionEventStartNode) - { - if (value is not IDataModelEvent dataModelEvent || dataModelEvent.LastTrigger <= _lastProcessedTrigger) - return false; - - _lastProcessedTrigger = dataModelEvent.LastTrigger; - } - else if (_startNode is EventConditionValueChangedStartNode valueChangedNode) - { - if (Equals(value, _lastProcessedValue)) - return false; - - valueChangedNode.UpdateValues(value, _lastProcessedValue); - _lastProcessedValue = value; - } - - if (!Script.ExitNodeConnected) - return true; - - Script.Run(); - return Script.Result; - } - /// public IConditionEntity Entity => _entity; @@ -263,6 +161,116 @@ public class EventCondition : CorePropertyChanged, INodeScriptCondition Script?.Dispose(); EventPath?.Dispose(); } + + /// + /// Updates the event node, applying the selected event + /// + public void UpdateEventNode(bool updateScript) + { + if (EventPath == null) + return; + + Type? pathType = EventPath.GetPropertyType(); + if (pathType == null) + return; + + // Create an event node if the path type is a data model event + if (pathType.IsAssignableTo(typeof(IDataModelEvent))) + { + EventConditionEventStartNode eventNode; + // Ensure the start node is an event node + if (_startNode is not EventConditionEventStartNode node) + { + eventNode = new EventConditionEventStartNode(); + if (updateScript) + ReplaceStartNode(eventNode); + _startNode = eventNode; + } + else + { + eventNode = node; + } + + IDataModelEvent? dataModelEvent = EventPath?.GetValue() as IDataModelEvent; + eventNode.CreatePins(dataModelEvent); + } + // Create a value changed node if the path type is a regular value + else + { + // Ensure the start nod is a value changed node + EventConditionValueChangedStartNode valueChangedNode; + // Ensure the start node is an event node + if (_startNode is not EventConditionValueChangedStartNode node) + { + valueChangedNode = new EventConditionValueChangedStartNode(); + if (updateScript) + ReplaceStartNode(valueChangedNode); + _startNode = valueChangedNode; + } + else + { + valueChangedNode = node; + } + + valueChangedNode.UpdateOutputPins(EventPath); + } + + // Script can be null if called before load + if (!updateScript) + return; + if (!Script.Nodes.Contains(_startNode)) + { + Script.AddNode(_startNode); + Script.LoadConnections(); + } + Script.Save(); + } + + /// + /// Gets the start node of the event script, if any + /// + /// The start node of the event script, if any. + public INode GetStartNode() + { + return _startNode; + } + + private void ReplaceStartNode(DefaultNode newStartNode) + { + if (Script.Nodes.Contains(_startNode)) + Script.RemoveNode(_startNode); + if (!Script.Nodes.Contains(newStartNode)) + Script.AddNode(newStartNode); + } + + private bool Evaluate() + { + if (EventPath == null) + return false; + + object? value = EventPath.GetValue(); + if (_startNode is EventConditionEventStartNode) + { + if (value is not IDataModelEvent dataModelEvent || dataModelEvent.LastTrigger <= _lastProcessedTrigger) + return false; + + _lastProcessedTrigger = dataModelEvent.LastTrigger; + } + else if (_startNode is EventConditionValueChangedStartNode valueChangedNode) + { + if (Equals(value, _lastProcessedValue)) + return false; + + valueChangedNode.UpdateValues(value, _lastProcessedValue); + _lastProcessedValue = value; + } + + if (!Script.ExitNodeConnected) + return true; + + Script.Run(); + return Script.Result; + } #region Storage @@ -275,11 +283,13 @@ public class EventCondition : CorePropertyChanged, INodeScriptCondition if (_entity.EventPath != null) EventPath = new DataModelPath(_entity.EventPath); - + UpdateEventNode(false); + + string name = $"Activate {_displayName}"; + string description = $"Whether or not the event should activate the {_displayName}"; Script = _entity.Script != null - ? new NodeScript($"Activate {_displayName}", $"Whether or not the event should activate the {_displayName}", _entity.Script, ProfileElement.Profile) - : new NodeScript($"Activate {_displayName}", $"Whether or not the event should activate the {_displayName}", ProfileElement.Profile); - UpdateEventNode(); + ? new NodeScript(name, description, _entity.Script, ProfileElement.Profile, new List {_startNode}) + : new NodeScript(name, description, ProfileElement.Profile, new List {_startNode}); } /// @@ -310,71 +320,9 @@ public class EventCondition : CorePropertyChanged, INodeScriptCondition /// public void LoadNodeScript() { + UpdateEventNode(true); Script.Load(); - - // The load action may have created an event node, use that one over the one we have here - INode? existingEventNode = Script.Nodes.FirstOrDefault(n => n.Id == EventConditionEventStartNode.NodeId || n.Id == EventConditionValueChangedStartNode.NodeId); - if (existingEventNode != null) - _startNode = (IEventConditionNode) existingEventNode; - - UpdateEventNode(); - Script.LoadConnections(); } #endregion -} - -/// -/// Represents a mode for render elements to start their timeline when display conditions events are fired. -/// -public enum EventTriggerMode -{ - /// - /// Play the timeline once. - /// - Play, - - /// - /// Toggle repeating the timeline. - /// - Toggle -} - -/// -/// Represents a mode for render elements to configure the behaviour of events that overlap i.e. trigger again before -/// the timeline finishes. -/// -public enum EventOverlapMode -{ - /// - /// Stop the current run and restart the timeline - /// - Restart, - - /// - /// Play another copy of the timeline on top of the current run - /// - Copy, - - /// - /// Ignore subsequent event fires until the timeline finishes - /// - Ignore -} - -/// -/// Represents a mode for render elements when toggling off the event when using -/// . -/// -public enum EventToggleOffMode -{ - /// - /// When the event toggles the condition off, finish the the current run of the main timeline - /// - Finish, - - /// - /// When the event toggles the condition off, skip to the end segment of the timeline - /// - SkipToEnd } \ No newline at end of file diff --git a/src/Artemis.Core/Models/Profile/Conditions/EventOverlapMode.cs b/src/Artemis.Core/Models/Profile/Conditions/EventOverlapMode.cs new file mode 100644 index 000000000..56068a797 --- /dev/null +++ b/src/Artemis.Core/Models/Profile/Conditions/EventOverlapMode.cs @@ -0,0 +1,23 @@ +namespace Artemis.Core; + +/// +/// Represents a mode for render elements to configure the behaviour of events that overlap i.e. trigger again before +/// the timeline finishes. +/// +public enum EventOverlapMode +{ + /// + /// Stop the current run and restart the timeline + /// + Restart, + + /// + /// Play another copy of the timeline on top of the current run + /// + Copy, + + /// + /// Ignore subsequent event fires until the timeline finishes + /// + Ignore +} \ No newline at end of file diff --git a/src/Artemis.Core/Models/Profile/Conditions/EventToggleOffMode.cs b/src/Artemis.Core/Models/Profile/Conditions/EventToggleOffMode.cs new file mode 100644 index 000000000..c8db3aa6a --- /dev/null +++ b/src/Artemis.Core/Models/Profile/Conditions/EventToggleOffMode.cs @@ -0,0 +1,18 @@ +namespace Artemis.Core; + +/// +/// Represents a mode for render elements when toggling off the event when using +/// . +/// +public enum EventToggleOffMode +{ + /// + /// When the event toggles the condition off, finish the the current run of the main timeline + /// + Finish, + + /// + /// When the event toggles the condition off, skip to the end segment of the timeline + /// + SkipToEnd +} \ No newline at end of file diff --git a/src/Artemis.Core/Models/Profile/Conditions/EventTriggerMode.cs b/src/Artemis.Core/Models/Profile/Conditions/EventTriggerMode.cs new file mode 100644 index 000000000..cfe31816d --- /dev/null +++ b/src/Artemis.Core/Models/Profile/Conditions/EventTriggerMode.cs @@ -0,0 +1,17 @@ +namespace Artemis.Core; + +/// +/// Represents a mode for render elements to start their timeline when display conditions events are fired. +/// +public enum EventTriggerMode +{ + /// + /// Play the timeline once. + /// + Play, + + /// + /// Toggle repeating the timeline. + /// + Toggle +} \ No newline at end of file diff --git a/src/Artemis.Core/Services/Input/InputProvider.cs b/src/Artemis.Core/Services/Input/InputProvider.cs index f04b1a1f9..c51a25d63 100644 --- a/src/Artemis.Core/Services/Input/InputProvider.cs +++ b/src/Artemis.Core/Services/Input/InputProvider.cs @@ -8,6 +8,13 @@ namespace Artemis.Core.Services; /// public abstract class InputProvider : IDisposable { + public InputProvider() + { + ProviderName = GetType().FullName ?? throw new InvalidOperationException("Input provider must have a type with a name"); + } + + internal string ProviderName { get; set; } + /// /// Called when the input service requests a event /// diff --git a/src/Artemis.Core/Services/Input/InputService.cs b/src/Artemis.Core/Services/Input/InputService.cs index 187f0db4b..48ae607f6 100644 --- a/src/Artemis.Core/Services/Input/InputService.cs +++ b/src/Artemis.Core/Services/Input/InputService.cs @@ -10,12 +10,18 @@ internal class InputService : IInputService { private readonly ILogger _logger; private readonly IRgbService _rgbService; + private ArtemisDevice? _firstKeyboard; + private ArtemisDevice? _firstMouse; + private int _keyboardCount; + private int _mouseCount; public InputService(ILogger logger, IRgbService rgbService) { _logger = logger; _rgbService = rgbService; + _rgbService.DeviceAdded += RgbServiceOnDevicesModified; + _rgbService.DeviceRemoved += RgbServiceOnDevicesModified; BustIdentifierCache(); } @@ -132,8 +138,6 @@ internal class InputService : IInputService private readonly Dictionary, ArtemisDevice> _deviceCache = new(); private List _devices = new(); - private ArtemisDevice? _cachedFallbackKeyboard; - private ArtemisDevice? _cachedFallbackMouse; private ArtemisDevice? _identifyingDevice; public void IdentifyDevice(ArtemisDevice device) @@ -164,13 +168,29 @@ internal class InputService : IInputService if (provider == null) throw new ArgumentNullException(nameof(provider)); if (identifier == null) throw new ArgumentNullException(nameof(identifier)); + // We will almost always only have zero or one of each + if (type == InputDeviceType.Keyboard) + { + if (_keyboardCount == 0) + return null; + if (_keyboardCount == 1) + return _firstKeyboard; + } + + if (type == InputDeviceType.Mouse) + { + if (_mouseCount == 0) + return null; + if (_mouseCount == 1) + return _firstMouse; + } + // Try cache first ArtemisDevice? cacheMatch = GetDeviceFromCache(provider, identifier); if (cacheMatch != null) return cacheMatch; - string providerName = provider.GetType().FullName!; - ArtemisDevice? match = _devices.FirstOrDefault(m => m.InputIdentifiers.Any(i => Equals(i.InputProvider, providerName) && Equals(i.Identifier, identifier))); + ArtemisDevice? match = _devices.FirstOrDefault(m => m.InputIdentifiers.Any(i => Equals(i.InputProvider, provider.ProviderName) && Equals(i.Identifier, identifier))); // If a match was found cache it to speed up the next event and return the match if (match != null) @@ -179,34 +199,16 @@ internal class InputService : IInputService return match; } - // If there is no match, apply our fallback type - if (type == InputDeviceType.None) - return null; if (type == InputDeviceType.Keyboard) - { - if (_cachedFallbackKeyboard != null) - return _cachedFallbackKeyboard; - _cachedFallbackKeyboard = _rgbService.EnabledDevices.FirstOrDefault(d => d.DeviceType == RGBDeviceType.Keyboard); - return _cachedFallbackKeyboard; - } - + return _firstKeyboard; if (type == InputDeviceType.Mouse) - { - if (_cachedFallbackMouse != null) - return _cachedFallbackMouse; - _cachedFallbackMouse = _rgbService.EnabledDevices.FirstOrDefault(d => d.DeviceType == RGBDeviceType.Mouse); - return _cachedFallbackMouse; - } - + return _firstMouse; return null; } public void BustIdentifierCache() { _deviceCache.Clear(); - _cachedFallbackKeyboard = null; - _cachedFallbackMouse = null; - _devices = _rgbService.EnabledDevices.Where(d => d.InputIdentifiers.Any()).ToList(); } @@ -220,12 +222,7 @@ internal class InputService : IInputService _deviceCache.TryGetValue(new Tuple(provider, identifier), out ArtemisDevice? device); return device; } - - private void SurfaceConfigurationChanged(object? sender, SurfaceConfigurationEventArgs e) - { - BustIdentifierCache(); - } - + private void InputProviderOnIdentifierReceived(object? sender, InputProviderIdentifierEventArgs e) { // Don't match if there is no device or if the device type differs from the event device type @@ -236,16 +233,24 @@ internal class InputService : IInputService if (!(sender is InputProvider inputProvider)) return; - string providerName = inputProvider.GetType().FullName!; - // Remove existing identification - _identifyingDevice.InputIdentifiers.RemoveAll(i => i.InputProvider == providerName); - _identifyingDevice.InputIdentifiers.Add(new ArtemisDeviceInputIdentifier(providerName, e.Identifier)); + _identifyingDevice.InputIdentifiers.RemoveAll(i => i.InputProvider == inputProvider.ProviderName); + _identifyingDevice.InputIdentifiers.Add(new ArtemisDeviceInputIdentifier(inputProvider.ProviderName, e.Identifier)); StopIdentify(); OnDeviceIdentified(); } + private void RgbServiceOnDevicesModified(object? sender, DeviceEventArgs args) + { + _firstKeyboard = _rgbService.Devices.FirstOrDefault(d => d.DeviceType == RGBDeviceType.Keyboard); + _firstMouse = _rgbService.Devices.FirstOrDefault(d => d.DeviceType == RGBDeviceType.Mouse); + _keyboardCount = _rgbService.Devices.Count(d => d.DeviceType == RGBDeviceType.Keyboard); + _mouseCount = _rgbService.Devices.Count(d => d.DeviceType == RGBDeviceType.Mouse); + + BustIdentifierCache(); + } + #endregion #region Keyboard @@ -379,6 +384,7 @@ internal class InputService : IInputService private readonly HashSet _pressedButtons = new(); + private void InputProviderOnMouseButtonDataReceived(object? sender, InputProviderMouseButtonEventArgs e) { bool foundLedId = InputKeyUtilities.MouseButtonLedIdMap.TryGetValue(e.Button, out LedId ledId); diff --git a/src/Artemis.Core/VisualScripting/Internal/EventConditionEventStartNode.cs b/src/Artemis.Core/VisualScripting/Internal/EventConditionEventStartNode.cs index 7ceadc837..f417e8871 100644 --- a/src/Artemis.Core/VisualScripting/Internal/EventConditionEventStartNode.cs +++ b/src/Artemis.Core/VisualScripting/Internal/EventConditionEventStartNode.cs @@ -2,7 +2,7 @@ namespace Artemis.Core.Internal; -internal class EventConditionEventStartNode : DefaultNode, IEventConditionNode +internal class EventConditionEventStartNode : DefaultNode { internal static readonly Guid NodeId = new("278735FE-69E9-4A73-A6B8-59E83EE19305"); private readonly ObjectOutputPins _objectOutputPins; @@ -13,6 +13,11 @@ internal class EventConditionEventStartNode : DefaultNode, IEventConditionNode _objectOutputPins = new ObjectOutputPins(this); } + public void SetDataModelEvent(IDataModelEvent? dataModelEvent) + { + + } + public void CreatePins(IDataModelEvent? dataModelEvent) { if (_dataModelEvent == dataModelEvent) diff --git a/src/Artemis.Core/VisualScripting/Internal/EventConditionValueChangedStartNode.cs b/src/Artemis.Core/VisualScripting/Internal/EventConditionValueChangedStartNode.cs index 2b98acbf6..c334681bc 100644 --- a/src/Artemis.Core/VisualScripting/Internal/EventConditionValueChangedStartNode.cs +++ b/src/Artemis.Core/VisualScripting/Internal/EventConditionValueChangedStartNode.cs @@ -2,7 +2,7 @@ namespace Artemis.Core.Internal; -internal class EventConditionValueChangedStartNode : DefaultNode, IEventConditionNode +internal class EventConditionValueChangedStartNode : DefaultNode { internal static readonly Guid NodeId = new("F9A270DB-A231-4800-BAB3-DC1F96856756"); private object? _newValue; diff --git a/src/Artemis.Core/VisualScripting/Internal/IEventConditionNode.cs b/src/Artemis.Core/VisualScripting/Internal/IEventConditionNode.cs deleted file mode 100644 index 87d45f50a..000000000 --- a/src/Artemis.Core/VisualScripting/Internal/IEventConditionNode.cs +++ /dev/null @@ -1,5 +0,0 @@ -namespace Artemis.Core.Internal; - -internal interface IEventConditionNode : INode -{ -} \ No newline at end of file diff --git a/src/Artemis.Core/VisualScripting/Node.cs b/src/Artemis.Core/VisualScripting/Node.cs index 70e02fa12..f212524de 100644 --- a/src/Artemis.Core/VisualScripting/Node.cs +++ b/src/Artemis.Core/VisualScripting/Node.cs @@ -339,7 +339,7 @@ public abstract class Node : BreakableModel, INode } /// - /// Called when the node was loaded from storage or newly created + /// Called when the node was loaded from storage or newly created, at this point pin connections aren't reestablished yet. /// /// The script the node is contained in public virtual void Initialize(INodeScript script) diff --git a/src/Artemis.Core/VisualScripting/NodeScript.cs b/src/Artemis.Core/VisualScripting/NodeScript.cs index e98dafcf3..9bfb08011 100644 --- a/src/Artemis.Core/VisualScripting/NodeScript.cs +++ b/src/Artemis.Core/VisualScripting/NodeScript.cs @@ -80,7 +80,8 @@ public abstract class NodeScript : CorePropertyChanged, INodeScript /// The context of the node script, usually a or /// /// - protected NodeScript(string name, string description, object? context = null) + /// A list of default nodes to add to the node script. + protected NodeScript(string name, string description, object? context = null, List? defaultNodes = null) { Name = name; Description = description; @@ -90,9 +91,15 @@ public abstract class NodeScript : CorePropertyChanged, INodeScript NodeTypeStore.NodeTypeAdded += NodeTypeStoreOnNodeTypeAdded; NodeTypeStore.NodeTypeRemoved += NodeTypeStoreOnNodeTypeRemoved; + + if (defaultNodes != null) + { + foreach (DefaultNode defaultNode in defaultNodes) + AddNode(defaultNode); + } } - internal NodeScript(string name, string description, NodeScriptEntity entity, object? context = null) + internal NodeScript(string name, string description, NodeScriptEntity entity, object? context = null, List? defaultNodes = null) { Name = name; Description = description; @@ -102,6 +109,12 @@ public abstract class NodeScript : CorePropertyChanged, INodeScript NodeTypeStore.NodeTypeAdded += NodeTypeStoreOnNodeTypeAdded; NodeTypeStore.NodeTypeRemoved += NodeTypeStoreOnNodeTypeRemoved; + + if (defaultNodes != null) + { + foreach (DefaultNode defaultNode in defaultNodes) + AddNode(defaultNode); + } } #endregion @@ -414,8 +427,8 @@ public class NodeScript : NodeScript, INodeScript #region Constructors /// - public NodeScript(string name, string description, NodeScriptEntity entity, object? context = null) - : base(name, description, entity, context) + public NodeScript(string name, string description, NodeScriptEntity entity, object? context = null, List? defaultNodes = null) + : base(name, description, entity, context, defaultNodes) { ExitNode = new ExitNode(name, description); AddNode(ExitNode); @@ -424,8 +437,8 @@ public class NodeScript : NodeScript, INodeScript } /// - public NodeScript(string name, string description, object? context = null) - : base(name, description, context) + public NodeScript(string name, string description, object? context = null, List? defaultNodes = null) + : base(name, description, context, defaultNodes) { ExitNode = new ExitNode(name, description); AddNode(ExitNode); diff --git a/src/Artemis.UI.Shared/Services/ProfileEditor/Commands/UpdateEventConditionPath.cs b/src/Artemis.UI.Shared/Services/ProfileEditor/Commands/UpdateEventConditionPath.cs index d424de4ae..d103772cd 100644 --- a/src/Artemis.UI.Shared/Services/ProfileEditor/Commands/UpdateEventConditionPath.cs +++ b/src/Artemis.UI.Shared/Services/ProfileEditor/Commands/UpdateEventConditionPath.cs @@ -49,7 +49,7 @@ public class UpdateEventConditionPath : IProfileEditorCommand, IDisposable // Change the end node _eventCondition.EventPath = _value; - _eventCondition.UpdateEventNode(); + _eventCondition.UpdateEventNode(true); _executed = true; } @@ -59,7 +59,7 @@ public class UpdateEventConditionPath : IProfileEditorCommand, IDisposable { // Change the end node _eventCondition.EventPath = _oldValue; - _eventCondition.UpdateEventNode(); + _eventCondition.UpdateEventNode(true); // Restore old connections _store?.Restore(); diff --git a/src/Artemis.UI.Windows/Providers/Input/WindowsInputProvider.cs b/src/Artemis.UI.Windows/Providers/Input/WindowsInputProvider.cs index d834c3002..1091fca54 100644 --- a/src/Artemis.UI.Windows/Providers/Input/WindowsInputProvider.cs +++ b/src/Artemis.UI.Windows/Providers/Input/WindowsInputProvider.cs @@ -19,7 +19,6 @@ public class WindowsInputProvider : InputProvider private readonly ILogger _logger; private readonly SpongeWindow _sponge; private readonly Timer _taskManagerTimer; - private DateTime _lastMouseUpdate; private int _lastProcessId; public WindowsInputProvider(ILogger logger, IInputService inputService) @@ -160,8 +159,8 @@ public class WindowsInputProvider : InputProvider #region Mouse - private int _mouseDeltaX; - private int _mouseDeltaY; + private int _previousMouseX; + private int _previousMouseY; private void HandleMouseData(RawInputData data, RawInputMouseData mouseData) { @@ -169,10 +168,8 @@ public class WindowsInputProvider : InputProvider // This can create a small inaccuracy of course, but Artemis is not a shooter :') if (mouseData.Mouse.Buttons == RawMouseButtonFlags.None) { - _mouseDeltaX += mouseData.Mouse.LastX; - _mouseDeltaY += mouseData.Mouse.LastY; - if (DateTime.Now - _lastMouseUpdate < TimeSpan.FromMilliseconds(40)) - return; + _previousMouseX += mouseData.Mouse.LastX; + _previousMouseY += mouseData.Mouse.LastY; } ArtemisDevice? device = null; @@ -193,10 +190,7 @@ public class WindowsInputProvider : InputProvider if (mouseData.Mouse.Buttons == RawMouseButtonFlags.None) { Win32Point cursorPosition = GetCursorPosition(); - OnMouseMoveDataReceived(device, cursorPosition.X, cursorPosition.Y, _mouseDeltaX, _mouseDeltaY); - _mouseDeltaX = 0; - _mouseDeltaY = 0; - _lastMouseUpdate = DateTime.Now; + OnMouseMoveDataReceived(device, cursorPosition.X, cursorPosition.Y, cursorPosition.X - _previousMouseX, cursorPosition.Y - _previousMouseY); return; } diff --git a/src/Artemis.VisualScripting/Nodes/List/ListOperatorPredicateNode.cs b/src/Artemis.VisualScripting/Nodes/List/ListOperatorPredicateNode.cs index 571eedc83..e6d811e88 100644 --- a/src/Artemis.VisualScripting/Nodes/List/ListOperatorPredicateNode.cs +++ b/src/Artemis.VisualScripting/Nodes/List/ListOperatorPredicateNode.cs @@ -9,10 +9,11 @@ namespace Artemis.VisualScripting.Nodes.List; public class ListOperatorPredicateNode : Node, IDisposable { private readonly object _scriptLock = new(); - private ListOperatorPredicateStartNode? _startNode; + private ListOperatorPredicateStartNode _startNode; public ListOperatorPredicateNode() : base("List Operator (Advanced)", "Checks if any/all/no values in the input list match a condition") { + _startNode = new ListOperatorPredicateStartNode {X = -200}; InputList = CreateInputPin(); Output = CreateOutputPin(); @@ -31,21 +32,8 @@ public class ListOperatorPredicateNode : Node("Is match", "Determines whether the current list item is a match", Storage.Script, script.Context) - : new NodeScript("Is match", "Determines whether the current list item is a match", script.Context); - - // The load action may have created an event node, use that one over the one we have here - INode? existingEventNode = Script.Nodes.FirstOrDefault(n => n.Id == ListOperatorPredicateStartNode.NodeId); - if (existingEventNode != null) - _startNode = (ListOperatorPredicateStartNode) existingEventNode; - else - { - _startNode = new ListOperatorPredicateStartNode {X = -200}; - Script.AddNode(_startNode); - } - - UpdateStartNode(); - Script.LoadConnections(); + ? new NodeScript("Is match", "Determines whether the current list item is a match", Storage.Script, script.Context, new List {_startNode}) + : new NodeScript("Is match", "Determines whether the current list item is a match", script.Context, new List {_startNode}); } } @@ -101,6 +89,7 @@ public class ListOperatorPredicateNode : Node vm.CanOpenEditor)); + CanOpenEditor = node.InputList.ConnectedTo.Any(); + + this.WhenActivated(d => + { + node.InputList.PinConnected += InputListOnPinConnected; + node.InputList.PinDisconnected += InputListOnPinDisconnected; + + Disposable.Create(() => + { + node.InputList.PinConnected -= InputListOnPinConnected; + node.InputList.PinDisconnected -= InputListOnPinDisconnected; + }).DisposeWith(d); + }); } public ReactiveCommand OpenEditor { get; } + private bool CanOpenEditor + { + get => _canOpenEditor; + set => this.RaiseAndSetIfChanged(ref _canOpenEditor, value); + } + public ListOperator Operator { get => _operator; @@ -40,4 +62,14 @@ public class ListOperatorPredicateNodeCustomViewModel : CustomNodeViewModel _node.Storage ??= new ListOperatorEntity(); _node.Storage.Script = _node.Script.Entity; } + + private void InputListOnPinDisconnected(object? sender, SingleValueEventArgs e) + { + CanOpenEditor = false; + } + + private void InputListOnPinConnected(object? sender, SingleValueEventArgs e) + { + CanOpenEditor = true; + } } \ No newline at end of file From 654863e0decff8b802df2d0ca919e33054417f53 Mon Sep 17 00:00:00 2001 From: Robert Date: Fri, 16 Sep 2022 19:50:35 +0200 Subject: [PATCH 5/7] Event conditions - Disable edit script button before picking an event --- .../ConditionTypes/EventConditionViewModel.cs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/Artemis.UI/Screens/ProfileEditor/Panels/DisplayCondition/ConditionTypes/EventConditionViewModel.cs b/src/Artemis.UI/Screens/ProfileEditor/Panels/DisplayCondition/ConditionTypes/EventConditionViewModel.cs index 916cf53b7..570c2391c 100644 --- a/src/Artemis.UI/Screens/ProfileEditor/Panels/DisplayCondition/ConditionTypes/EventConditionViewModel.cs +++ b/src/Artemis.UI/Screens/ProfileEditor/Panels/DisplayCondition/ConditionTypes/EventConditionViewModel.cs @@ -16,7 +16,6 @@ namespace Artemis.UI.Screens.ProfileEditor.DisplayCondition.ConditionTypes; public class EventConditionViewModel : ActivatableViewModelBase { private readonly EventCondition _eventCondition; - private readonly INodeService _nodeService; private readonly IProfileEditorService _profileEditorService; private readonly ISettingsService _settingsService; private readonly ObservableAsPropertyHelper _showOverlapOptions; @@ -27,11 +26,10 @@ public class EventConditionViewModel : ActivatableViewModelBase private ObservableAsPropertyHelper? _selectedToggleOffMode; private ObservableAsPropertyHelper? _selectedTriggerMode; - public EventConditionViewModel(EventCondition eventCondition, IProfileEditorService profileEditorService, INodeService nodeService, IWindowService windowService, ISettingsService settingsService) + public EventConditionViewModel(EventCondition eventCondition, IProfileEditorService profileEditorService, IWindowService windowService, ISettingsService settingsService) { _eventCondition = eventCondition; _profileEditorService = profileEditorService; - _nodeService = nodeService; _windowService = windowService; _settingsService = settingsService; _showOverlapOptions = this.WhenAnyValue(vm => vm.SelectedTriggerMode).Select(m => m == 0).ToProperty(this, vm => vm.ShowOverlapOptions); @@ -45,7 +43,7 @@ public class EventConditionViewModel : ActivatableViewModelBase _selectedToggleOffMode = eventCondition.WhenAnyValue(c => c.OverlapMode).Select(m => (int) m).ToProperty(this, vm => vm.SelectedOverlapMode).DisposeWith(d); }); - OpenEditor = ReactiveCommand.CreateFromTask(ExecuteOpenEditor); + OpenEditor = ReactiveCommand.CreateFromTask(ExecuteOpenEditor, this.WhenAnyValue(vm => vm.EventPath).Select(p => p != null)); } public ReactiveCommand OpenEditor { get; } From 32a444fbebd08b3c6e9a8fab31d7c37045e5dc75 Mon Sep 17 00:00:00 2001 From: Robert Date: Fri, 16 Sep 2022 20:19:19 +0200 Subject: [PATCH 6/7] Auto-update - Fix URL, restoring auto-update functionality --- src/Artemis.UI.Windows/Providers/UpdateProvider.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Artemis.UI.Windows/Providers/UpdateProvider.cs b/src/Artemis.UI.Windows/Providers/UpdateProvider.cs index fc02a0a6e..42df93619 100644 --- a/src/Artemis.UI.Windows/Providers/UpdateProvider.cs +++ b/src/Artemis.UI.Windows/Providers/UpdateProvider.cs @@ -45,7 +45,7 @@ public class UpdateProvider : IUpdateProvider, IDisposable Url request = API_URL.AppendPathSegments("build", "builds") .SetQueryParam("definitions", buildDefinition) .SetQueryParam("resultFilter", "succeeded") - .SetQueryParam("branchName", "master") + .SetQueryParam("branchName", "refs/heads/master") .SetQueryParam("$top", 1) .SetQueryParam("api-version", "6.1-preview.6"); From 9c117d2773593978584add0002090a856a13bbbb Mon Sep 17 00:00:00 2001 From: Robert Date: Fri, 23 Sep 2022 21:40:30 +0200 Subject: [PATCH 7/7] Nodes - Added gradient nodes Nodes - Added color gradient pin type Data bindings - Changed color gradient data bindings to now take a color gradient --- .../Artemis.Core.csproj.DotSettings | 4 +- .../Properties/ColorGradientLayerProperty.cs | 61 +--------- .../DataBindings/DataBindingProperty.cs | 2 +- .../DataBindings/IDataBindingProperty.cs | 2 +- .../Plugins/PluginFeatureAttribute.cs | 1 + src/Artemis.Core/Plugins/PluginFeatureInfo.cs | 50 +------- .../Internal/DataBindingExitNode.cs | 5 +- .../Internal/EventConditionEventStartNode.cs | 3 +- .../VisualScripting/NodeScript.cs | 6 +- .../{ => Nodes}/CustomNodeViewModel.cs | 0 .../Nodes/CustomNodeViewModelPosition.cs | 32 +++++ .../{ => Nodes}/DefaultNode.cs | 0 .../Nodes/ICustomViewModelNode.cs | 18 +++ .../VisualScripting/{ => Nodes}/Node.cs | 114 +----------------- .../VisualScripting/Nodes/NodeTStorage.cs | 52 ++++++++ .../Nodes/NodeTStorageTViewModel.cs | 58 +++++++++ .../VisualScripting/{ => Pins}/InputPin.cs | 0 .../{ => Pins}/InputPinCollection.cs | 0 .../{ => Pins}/ObjectOutputPins.cs | 0 .../VisualScripting/{ => Pins}/OutputPin.cs | 0 .../{ => Pins}/OutputPinCollection.cs | 0 .../VisualScripting/{ => Pins}/Pin.cs | 0 .../{ => Pins}/PinCollection.cs | 0 .../{ => Pins}/PinDirection.cs | 0 .../Migrations/M0021GradientNodes.cs | 87 +++++++++++++ .../Controls/ArtemisIcon.axaml.cs | 2 +- .../Controls/GradientPicker/GradientPicker.cs | 102 ++++++++++------ .../GradientPicker/GradientPickerButton.cs | 37 ++---- .../Commands/UpdateColorGradient.cs | 32 +++-- .../Styles/Controls/GradientPicker.axaml | 18 +-- .../Screens/Plugins/PluginFeatureView.axaml | 12 +- .../Screens/Plugins/PluginFeatureViewModel.cs | 42 +++++++ .../Panels/Playback/PlaybackViewModel.cs | 24 +++- .../ScriptConfigurationCreateView.axaml | 2 +- .../Screens/Scripting/ScriptsDialogView.axaml | 2 +- .../Sidebar/Dialogs/ProfileModuleViewModel.cs | 2 +- .../Screens/VisualScripting/CableView.axaml | 25 ++-- .../Screens/VisualScripting/NodeView.axaml | 29 +++-- .../Screens/VisualScripting/NodeViewModel.cs | 58 ++++++++- .../Services/RegistrationService.cs | 1 + .../Artemis.VisualScripting.csproj | 3 + .../Nodes/Color/ColorGradientFromPinsNode.cs | 102 ++++++++++++++++ .../Nodes/Color/ColorGradientNode.cs | 108 +++++++++++++++++ .../Nodes/Color/RampSKColorNode.cs | 2 +- .../Screens/ColorGradientNodeCustomView.axaml | 15 +++ .../ColorGradientNodeCustomView.axaml.cs | 27 +++++ .../ColorGradientNodeCustomViewModel.cs | 28 +++++ .../Nodes/DataModel/DataModelEventNode.cs | 6 + 48 files changed, 830 insertions(+), 344 deletions(-) rename src/Artemis.Core/VisualScripting/{ => Nodes}/CustomNodeViewModel.cs (100%) create mode 100644 src/Artemis.Core/VisualScripting/Nodes/CustomNodeViewModelPosition.cs rename src/Artemis.Core/VisualScripting/{ => Nodes}/DefaultNode.cs (100%) create mode 100644 src/Artemis.Core/VisualScripting/Nodes/ICustomViewModelNode.cs rename src/Artemis.Core/VisualScripting/{ => Nodes}/Node.cs (76%) create mode 100644 src/Artemis.Core/VisualScripting/Nodes/NodeTStorage.cs create mode 100644 src/Artemis.Core/VisualScripting/Nodes/NodeTStorageTViewModel.cs rename src/Artemis.Core/VisualScripting/{ => Pins}/InputPin.cs (100%) rename src/Artemis.Core/VisualScripting/{ => Pins}/InputPinCollection.cs (100%) rename src/Artemis.Core/VisualScripting/{ => Pins}/ObjectOutputPins.cs (100%) rename src/Artemis.Core/VisualScripting/{ => Pins}/OutputPin.cs (100%) rename src/Artemis.Core/VisualScripting/{ => Pins}/OutputPinCollection.cs (100%) rename src/Artemis.Core/VisualScripting/{ => Pins}/Pin.cs (100%) rename src/Artemis.Core/VisualScripting/{ => Pins}/PinCollection.cs (100%) rename src/Artemis.Core/VisualScripting/{ => Pins}/PinDirection.cs (100%) create mode 100644 src/Artemis.Storage/Migrations/M0021GradientNodes.cs create mode 100644 src/Artemis.VisualScripting/Nodes/Color/ColorGradientFromPinsNode.cs create mode 100644 src/Artemis.VisualScripting/Nodes/Color/ColorGradientNode.cs create mode 100644 src/Artemis.VisualScripting/Nodes/Color/Screens/ColorGradientNodeCustomView.axaml create mode 100644 src/Artemis.VisualScripting/Nodes/Color/Screens/ColorGradientNodeCustomView.axaml.cs create mode 100644 src/Artemis.VisualScripting/Nodes/Color/Screens/ColorGradientNodeCustomViewModel.cs diff --git a/src/Artemis.Core/Artemis.Core.csproj.DotSettings b/src/Artemis.Core/Artemis.Core.csproj.DotSettings index a18836e5e..c23015925 100644 --- a/src/Artemis.Core/Artemis.Core.csproj.DotSettings +++ b/src/Artemis.Core/Artemis.Core.csproj.DotSettings @@ -93,4 +93,6 @@ True True True - True \ No newline at end of file + True + True + True \ No newline at end of file diff --git a/src/Artemis.Core/DefaultTypes/Properties/ColorGradientLayerProperty.cs b/src/Artemis.Core/DefaultTypes/Properties/ColorGradientLayerProperty.cs index c88cbd625..b108d81f1 100644 --- a/src/Artemis.Core/DefaultTypes/Properties/ColorGradientLayerProperty.cs +++ b/src/Artemis.Core/DefaultTypes/Properties/ColorGradientLayerProperty.cs @@ -1,13 +1,8 @@ -using System.Collections.Specialized; -using SkiaSharp; - -namespace Artemis.Core; +namespace Artemis.Core; /// public class ColorGradientLayerProperty : LayerProperty { - private ColorGradient? _subscribedGradient; - internal ColorGradientLayerProperty() { KeyframesSupported = false; @@ -22,29 +17,6 @@ public class ColorGradientLayerProperty : LayerProperty return p.CurrentValue; } - #region Overrides of LayerProperty - - /// - protected override void OnCurrentValueSet() - { - // Don't allow color gradients to be null - if (BaseValue == null!) - BaseValue = new ColorGradient(DefaultValue); - - if (!ReferenceEquals(_subscribedGradient, BaseValue)) - { - if (_subscribedGradient != null) - _subscribedGradient.CollectionChanged -= SubscribedGradientOnPropertyChanged; - _subscribedGradient = BaseValue; - _subscribedGradient.CollectionChanged += SubscribedGradientOnPropertyChanged; - } - - CreateDataBindingRegistrations(); - base.OnCurrentValueSet(); - } - - #endregion - /// protected override void UpdateCurrentValue(float keyframeProgress, float keyframeProgressEased) { @@ -60,33 +32,12 @@ public class ColorGradientLayerProperty : LayerProperty if (BaseValue == null!) BaseValue = new ColorGradient(DefaultValue); - base.OnInitialize(); + DataBinding.RegisterDataBindingProperty(() => CurrentValue, value => + { + if (value != null) + CurrentValue = value; + }, "Value"); } #endregion - - private void CreateDataBindingRegistrations() - { - DataBinding.ClearDataBindingProperties(); - if (CurrentValue == null!) - return; - - for (int index = 0; index < CurrentValue.Count; index++) - { - int stopIndex = index; - - void Setter(SKColor value) - { - CurrentValue[stopIndex].Color = value; - } - - DataBinding.RegisterDataBindingProperty(() => CurrentValue[stopIndex].Color, Setter, $"Color #{stopIndex + 1}"); - } - } - - private void SubscribedGradientOnPropertyChanged(object? sender, NotifyCollectionChangedEventArgs args) - { - if (CurrentValue.Count != DataBinding.Properties.Count) - CreateDataBindingRegistrations(); - } } \ No newline at end of file diff --git a/src/Artemis.Core/Models/Profile/DataBindings/DataBindingProperty.cs b/src/Artemis.Core/Models/Profile/DataBindings/DataBindingProperty.cs index 13a5c9e27..81c4b719a 100644 --- a/src/Artemis.Core/Models/Profile/DataBindings/DataBindingProperty.cs +++ b/src/Artemis.Core/Models/Profile/DataBindings/DataBindingProperty.cs @@ -35,7 +35,7 @@ public class DataBindingProperty : IDataBindingProperty } /// - public void SetValue(object? value) + public void SetValue(object value) { // Numeric has a bunch of conversion, this seems the cheapest way to use them :) switch (value) diff --git a/src/Artemis.Core/Models/Profile/DataBindings/IDataBindingProperty.cs b/src/Artemis.Core/Models/Profile/DataBindings/IDataBindingProperty.cs index 7d5dc49bd..7e4ce8d06 100644 --- a/src/Artemis.Core/Models/Profile/DataBindings/IDataBindingProperty.cs +++ b/src/Artemis.Core/Models/Profile/DataBindings/IDataBindingProperty.cs @@ -27,5 +27,5 @@ public interface IDataBindingProperty /// Sets the value of the property this registration points to /// /// A value matching the type of - void SetValue(object? value); + void SetValue(object value); } \ No newline at end of file diff --git a/src/Artemis.Core/Plugins/PluginFeatureAttribute.cs b/src/Artemis.Core/Plugins/PluginFeatureAttribute.cs index 19acfa645..cf36770e1 100644 --- a/src/Artemis.Core/Plugins/PluginFeatureAttribute.cs +++ b/src/Artemis.Core/Plugins/PluginFeatureAttribute.cs @@ -22,6 +22,7 @@ public class PluginFeatureAttribute : Attribute /// The plugins display icon that's shown in the settings see for /// available icons /// + [Obsolete("Feature icons are no longer shown in the UI.")] public string? Icon { get; set; } /// diff --git a/src/Artemis.Core/Plugins/PluginFeatureInfo.cs b/src/Artemis.Core/Plugins/PluginFeatureInfo.cs index 35798a064..32d5775ec 100644 --- a/src/Artemis.Core/Plugins/PluginFeatureInfo.cs +++ b/src/Artemis.Core/Plugins/PluginFeatureInfo.cs @@ -31,20 +31,7 @@ public class PluginFeatureInfo : CorePropertyChanged, IPrerequisitesSubject Name = attribute?.Name ?? featureType.Name.Humanize(LetterCasing.Title); Description = attribute?.Description; - Icon = attribute?.Icon; AlwaysEnabled = attribute?.AlwaysEnabled ?? false; - - if (Icon != null) return; - if (typeof(DeviceProvider).IsAssignableFrom(featureType)) - Icon = "Devices"; - else if (typeof(Module).IsAssignableFrom(featureType)) - Icon = "VectorRectangle"; - else if (typeof(LayerBrushProvider).IsAssignableFrom(featureType)) - Icon = "Brush"; - else if (typeof(LayerEffectProvider).IsAssignableFrom(featureType)) - Icon = "AutoAwesome"; - else - Icon = "Plugin"; } internal PluginFeatureInfo(Plugin plugin, PluginFeatureAttribute? attribute, PluginFeature instance) @@ -56,19 +43,8 @@ public class PluginFeatureInfo : CorePropertyChanged, IPrerequisitesSubject Name = attribute?.Name ?? instance.GetType().Name.Humanize(LetterCasing.Title); Description = attribute?.Description; - Icon = attribute?.Icon; AlwaysEnabled = attribute?.AlwaysEnabled ?? false; Instance = instance; - - if (Icon != null) return; - Icon = Instance switch - { - DeviceProvider => "Devices", - Module => "VectorRectangle", - LayerBrushProvider => "Brush", - LayerEffectProvider => "AutoAwesome", - _ => "Plugin" - }; } /// @@ -110,17 +86,6 @@ public class PluginFeatureInfo : CorePropertyChanged, IPrerequisitesSubject set => SetAndNotify(ref _description, value); } - /// - /// The plugins display icon that's shown in the settings see for - /// available icons - /// - [JsonProperty] - public string? Icon - { - get => _icon; - set => SetAndNotify(ref _icon, value); - } - /// /// Marks the feature to always be enabled as long as the plugin is enabled and cannot be disabled. /// Note: always if this is the plugin's only feature @@ -142,20 +107,7 @@ public class PluginFeatureInfo : CorePropertyChanged, IPrerequisitesSubject get => _instance; internal set => SetAndNotify(ref _instance, value); } - - /// - /// Gets a string representing either a full path pointing to an svg or the markdown icon - /// - public string? ResolvedIcon - { - get - { - if (Icon == null) - return null; - return Icon.Contains('.') ? Plugin.ResolveRelativePath(Icon) : Icon; - } - } - + internal PluginFeatureEntity Entity { get; } /// diff --git a/src/Artemis.Core/VisualScripting/Internal/DataBindingExitNode.cs b/src/Artemis.Core/VisualScripting/Internal/DataBindingExitNode.cs index 6b4d367f5..7857f533d 100644 --- a/src/Artemis.Core/VisualScripting/Internal/DataBindingExitNode.cs +++ b/src/Artemis.Core/VisualScripting/Internal/DataBindingExitNode.cs @@ -23,7 +23,10 @@ internal class DataBindingExitNode : Node, IExitNode public void ApplyToDataBinding() { foreach ((IDataBindingProperty? property, object? pendingValue) in _propertyValues) - property.SetValue(pendingValue); + { + if (pendingValue != null) + property.SetValue(pendingValue); + } } public override void Evaluate() diff --git a/src/Artemis.Core/VisualScripting/Internal/EventConditionEventStartNode.cs b/src/Artemis.Core/VisualScripting/Internal/EventConditionEventStartNode.cs index f417e8871..14f1e0562 100644 --- a/src/Artemis.Core/VisualScripting/Internal/EventConditionEventStartNode.cs +++ b/src/Artemis.Core/VisualScripting/Internal/EventConditionEventStartNode.cs @@ -15,8 +15,7 @@ internal class EventConditionEventStartNode : DefaultNode public void SetDataModelEvent(IDataModelEvent? dataModelEvent) { - - } + } public void CreatePins(IDataModelEvent? dataModelEvent) { diff --git a/src/Artemis.Core/VisualScripting/NodeScript.cs b/src/Artemis.Core/VisualScripting/NodeScript.cs index 9bfb08011..7a02555ac 100644 --- a/src/Artemis.Core/VisualScripting/NodeScript.cs +++ b/src/Artemis.Core/VisualScripting/NodeScript.cs @@ -93,10 +93,8 @@ public abstract class NodeScript : CorePropertyChanged, INodeScript NodeTypeStore.NodeTypeRemoved += NodeTypeStoreOnNodeTypeRemoved; if (defaultNodes != null) - { foreach (DefaultNode defaultNode in defaultNodes) AddNode(defaultNode); - } } internal NodeScript(string name, string description, NodeScriptEntity entity, object? context = null, List? defaultNodes = null) @@ -109,12 +107,10 @@ public abstract class NodeScript : CorePropertyChanged, INodeScript NodeTypeStore.NodeTypeAdded += NodeTypeStoreOnNodeTypeAdded; NodeTypeStore.NodeTypeRemoved += NodeTypeStoreOnNodeTypeRemoved; - + if (defaultNodes != null) - { foreach (DefaultNode defaultNode in defaultNodes) AddNode(defaultNode); - } } #endregion diff --git a/src/Artemis.Core/VisualScripting/CustomNodeViewModel.cs b/src/Artemis.Core/VisualScripting/Nodes/CustomNodeViewModel.cs similarity index 100% rename from src/Artemis.Core/VisualScripting/CustomNodeViewModel.cs rename to src/Artemis.Core/VisualScripting/Nodes/CustomNodeViewModel.cs diff --git a/src/Artemis.Core/VisualScripting/Nodes/CustomNodeViewModelPosition.cs b/src/Artemis.Core/VisualScripting/Nodes/CustomNodeViewModelPosition.cs new file mode 100644 index 000000000..74616dd8e --- /dev/null +++ b/src/Artemis.Core/VisualScripting/Nodes/CustomNodeViewModelPosition.cs @@ -0,0 +1,32 @@ +namespace Artemis.Core; + +/// +/// Represents the position of a node's custom view model. +/// +public enum CustomNodeViewModelPosition +{ + /// + /// Puts the view model above the pins. + /// + AbovePins, + + /// + /// Puts the view model between the pins, vertically aligned to the top. + /// + BetweenPinsTop, + + /// + /// Puts the view model between the pins, vertically aligned to the center. + /// + BetweenPinsCenter, + + /// + /// Puts the view model between the pins, vertically aligned to the bottom. + /// + BetweenPinsBottom, + + /// + /// Puts the view model below the pins. + /// + BelowPins +} \ No newline at end of file diff --git a/src/Artemis.Core/VisualScripting/DefaultNode.cs b/src/Artemis.Core/VisualScripting/Nodes/DefaultNode.cs similarity index 100% rename from src/Artemis.Core/VisualScripting/DefaultNode.cs rename to src/Artemis.Core/VisualScripting/Nodes/DefaultNode.cs diff --git a/src/Artemis.Core/VisualScripting/Nodes/ICustomViewModelNode.cs b/src/Artemis.Core/VisualScripting/Nodes/ICustomViewModelNode.cs new file mode 100644 index 000000000..b16623935 --- /dev/null +++ b/src/Artemis.Core/VisualScripting/Nodes/ICustomViewModelNode.cs @@ -0,0 +1,18 @@ +namespace Artemis.Core; + +/// +/// Represents a node that has a custom view model. +/// +public interface ICustomViewModelNode +{ + /// + /// Gets or sets the position of the node's custom view model. + /// + CustomNodeViewModelPosition ViewModelPosition { get; } + + /// + /// Called whenever the node must show it's custom view model, if , no custom view model is used + /// + /// The custom view model, if , no custom view model is used + ICustomNodeViewModel? GetCustomViewModel(NodeScript nodeScript); +} \ No newline at end of file diff --git a/src/Artemis.Core/VisualScripting/Node.cs b/src/Artemis.Core/VisualScripting/Nodes/Node.cs similarity index 76% rename from src/Artemis.Core/VisualScripting/Node.cs rename to src/Artemis.Core/VisualScripting/Nodes/Node.cs index f212524de..e451f05aa 100644 --- a/src/Artemis.Core/VisualScripting/Node.cs +++ b/src/Artemis.Core/VisualScripting/Nodes/Node.cs @@ -2,10 +2,7 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; -using System.Reflection; using Artemis.Core.Events; -using Ninject; -using Ninject.Parameters; namespace Artemis.Core; @@ -339,7 +336,8 @@ public abstract class Node : BreakableModel, INode } /// - /// Called when the node was loaded from storage or newly created, at this point pin connections aren't reestablished yet. + /// Called when the node was loaded from storage or newly created, at this point pin connections aren't reestablished + /// yet. /// /// The script the node is contained in public virtual void Initialize(INodeScript script) @@ -374,16 +372,6 @@ public abstract class Node : BreakableModel, INode TryOrBreak(Evaluate, "Failed to evaluate"); } - /// - /// Called whenever the node must show it's custom view model, if , no custom view model is used - /// - /// - /// The custom view model, if , no custom view model is used - public virtual ICustomNodeViewModel? GetCustomViewModel(NodeScript nodeScript) - { - return null; - } - /// /// Serializes the object into a string /// @@ -402,102 +390,4 @@ public abstract class Node : BreakableModel, INode } #endregion -} - -/// -/// Represents a kind of node inside a containing storage value of type -/// . -/// -/// The type of value the node stores -public abstract class Node : Node -{ - private TStorage? _storage; - - /// - protected Node() - { - } - - /// - protected Node(string name, string description) : base(name, description) - { - } - - /// - /// Gets or sets the storage object of this node, this is saved across sessions - /// - public TStorage? Storage - { - get => _storage; - set - { - if (SetAndNotify(ref _storage, value)) - StorageModified?.Invoke(this, EventArgs.Empty); - } - } - - /// - /// Occurs whenever the storage of this node was modified. - /// - public event EventHandler? StorageModified; - - /// - public override string SerializeStorage() - { - return CoreJson.SerializeObject(Storage, true); - } - - /// - public override void DeserializeStorage(string serialized) - { - Storage = CoreJson.DeserializeObject(serialized) ?? default(TStorage); - } -} - -/// -/// Represents a kind of node inside a containing storage value of type -/// and a view model of type . -/// -/// The type of value the node stores -/// The type of view model the node uses -public abstract class Node : Node where TViewModel : ICustomNodeViewModel -{ - /// - protected Node() - { - } - - /// - protected Node(string name, string description) : base(name, description) - { - } - - [Inject] - internal IKernel Kernel { get; set; } = null!; - - /// - /// Called when a view model is required - /// - /// - public virtual TViewModel GetViewModel(NodeScript nodeScript) - { - // Limit to one constructor, there's no need to have more and it complicates things anyway - ConstructorInfo[] constructors = typeof(TViewModel).GetConstructors(); - if (constructors.Length != 1) - throw new ArtemisCoreException("Node VMs must have exactly one constructor"); - - // Find the ScriptConfiguration parameter, it is required by the base constructor so its there for sure - ParameterInfo? configurationParameter = constructors.First().GetParameters().FirstOrDefault(p => GetType().IsAssignableFrom(p.ParameterType)); - - if (configurationParameter?.Name == null) - throw new ArtemisCoreException($"Couldn't find a valid constructor argument on {typeof(TViewModel).Name} with type {GetType().Name}"); - return Kernel.Get(new ConstructorArgument(configurationParameter.Name, this), new ConstructorArgument("script", nodeScript)); - } - - /// - /// - public override ICustomNodeViewModel? GetCustomViewModel(NodeScript nodeScript) - { - return GetViewModel(nodeScript); - } } \ No newline at end of file diff --git a/src/Artemis.Core/VisualScripting/Nodes/NodeTStorage.cs b/src/Artemis.Core/VisualScripting/Nodes/NodeTStorage.cs new file mode 100644 index 000000000..81d9e7eac --- /dev/null +++ b/src/Artemis.Core/VisualScripting/Nodes/NodeTStorage.cs @@ -0,0 +1,52 @@ +using System; +using Artemis.Core; + +/// +/// Represents a kind of node inside a containing storage value of type +/// . +/// +/// The type of value the node stores +public abstract class Node : Node +{ + private TStorage? _storage; + + /// + protected Node() + { + } + + /// + protected Node(string name, string description) : base(name, description) + { + } + + /// + /// Gets or sets the storage object of this node, this is saved across sessions + /// + public TStorage? Storage + { + get => _storage; + set + { + if (SetAndNotify(ref _storage, value)) + StorageModified?.Invoke(this, EventArgs.Empty); + } + } + + /// + /// Occurs whenever the storage of this node was modified. + /// + public event EventHandler? StorageModified; + + /// + public override string SerializeStorage() + { + return CoreJson.SerializeObject(Storage, true); + } + + /// + public override void DeserializeStorage(string serialized) + { + Storage = CoreJson.DeserializeObject(serialized) ?? default(TStorage); + } +} \ No newline at end of file diff --git a/src/Artemis.Core/VisualScripting/Nodes/NodeTStorageTViewModel.cs b/src/Artemis.Core/VisualScripting/Nodes/NodeTStorageTViewModel.cs new file mode 100644 index 000000000..1b4109714 --- /dev/null +++ b/src/Artemis.Core/VisualScripting/Nodes/NodeTStorageTViewModel.cs @@ -0,0 +1,58 @@ +using System.Linq; +using System.Reflection; +using Artemis.Core; +using Ninject; +using Ninject.Parameters; + +/// +/// Represents a kind of node inside a containing storage value of type +/// and a view model of type . +/// +/// The type of value the node stores +/// The type of view model the node uses +public abstract class Node : Node, ICustomViewModelNode where TViewModel : ICustomNodeViewModel +{ + /// + protected Node() + { + } + + /// + protected Node(string name, string description) : base(name, description) + { + } + + [Inject] + internal IKernel Kernel { get; set; } = null!; + + /// + /// Called when a view model is required + /// + /// + public virtual TViewModel GetViewModel(NodeScript nodeScript) + { + // Limit to one constructor, there's no need to have more and it complicates things anyway + ConstructorInfo[] constructors = typeof(TViewModel).GetConstructors(); + if (constructors.Length != 1) + throw new ArtemisCoreException("Node VMs must have exactly one constructor"); + + // Find the ScriptConfiguration parameter, it is required by the base constructor so its there for sure + ParameterInfo? configurationParameter = constructors.First().GetParameters().FirstOrDefault(p => GetType().IsAssignableFrom(p.ParameterType)); + + if (configurationParameter?.Name == null) + throw new ArtemisCoreException($"Couldn't find a valid constructor argument on {typeof(TViewModel).Name} with type {GetType().Name}"); + return Kernel.Get(new ConstructorArgument(configurationParameter.Name, this), new ConstructorArgument("script", nodeScript)); + } + + /// + /// Gets or sets the position of the node's custom view model. + /// + public CustomNodeViewModelPosition ViewModelPosition { get; protected set; } = CustomNodeViewModelPosition.BetweenPinsTop; + + /// + /// + public ICustomNodeViewModel GetCustomViewModel(NodeScript nodeScript) + { + return GetViewModel(nodeScript); + } +} \ No newline at end of file diff --git a/src/Artemis.Core/VisualScripting/InputPin.cs b/src/Artemis.Core/VisualScripting/Pins/InputPin.cs similarity index 100% rename from src/Artemis.Core/VisualScripting/InputPin.cs rename to src/Artemis.Core/VisualScripting/Pins/InputPin.cs diff --git a/src/Artemis.Core/VisualScripting/InputPinCollection.cs b/src/Artemis.Core/VisualScripting/Pins/InputPinCollection.cs similarity index 100% rename from src/Artemis.Core/VisualScripting/InputPinCollection.cs rename to src/Artemis.Core/VisualScripting/Pins/InputPinCollection.cs diff --git a/src/Artemis.Core/VisualScripting/ObjectOutputPins.cs b/src/Artemis.Core/VisualScripting/Pins/ObjectOutputPins.cs similarity index 100% rename from src/Artemis.Core/VisualScripting/ObjectOutputPins.cs rename to src/Artemis.Core/VisualScripting/Pins/ObjectOutputPins.cs diff --git a/src/Artemis.Core/VisualScripting/OutputPin.cs b/src/Artemis.Core/VisualScripting/Pins/OutputPin.cs similarity index 100% rename from src/Artemis.Core/VisualScripting/OutputPin.cs rename to src/Artemis.Core/VisualScripting/Pins/OutputPin.cs diff --git a/src/Artemis.Core/VisualScripting/OutputPinCollection.cs b/src/Artemis.Core/VisualScripting/Pins/OutputPinCollection.cs similarity index 100% rename from src/Artemis.Core/VisualScripting/OutputPinCollection.cs rename to src/Artemis.Core/VisualScripting/Pins/OutputPinCollection.cs diff --git a/src/Artemis.Core/VisualScripting/Pin.cs b/src/Artemis.Core/VisualScripting/Pins/Pin.cs similarity index 100% rename from src/Artemis.Core/VisualScripting/Pin.cs rename to src/Artemis.Core/VisualScripting/Pins/Pin.cs diff --git a/src/Artemis.Core/VisualScripting/PinCollection.cs b/src/Artemis.Core/VisualScripting/Pins/PinCollection.cs similarity index 100% rename from src/Artemis.Core/VisualScripting/PinCollection.cs rename to src/Artemis.Core/VisualScripting/Pins/PinCollection.cs diff --git a/src/Artemis.Core/VisualScripting/PinDirection.cs b/src/Artemis.Core/VisualScripting/Pins/PinDirection.cs similarity index 100% rename from src/Artemis.Core/VisualScripting/PinDirection.cs rename to src/Artemis.Core/VisualScripting/Pins/PinDirection.cs diff --git a/src/Artemis.Storage/Migrations/M0021GradientNodes.cs b/src/Artemis.Storage/Migrations/M0021GradientNodes.cs new file mode 100644 index 000000000..11f062bd7 --- /dev/null +++ b/src/Artemis.Storage/Migrations/M0021GradientNodes.cs @@ -0,0 +1,87 @@ +using System; +using System.Linq; +using Artemis.Storage.Entities.Profile; +using Artemis.Storage.Entities.Profile.Nodes; +using Artemis.Storage.Migrations.Interfaces; +using LiteDB; + +namespace Artemis.Storage.Migrations; + +public class M0021GradientNodes : IStorageMigration +{ + private void MigrateDataBinding(PropertyEntity property) + { + NodeScriptEntity script = property.DataBinding.NodeScript; + NodeEntity exitNode = script.Nodes.FirstOrDefault(s => s.IsExitNode); + if (exitNode == null) + return; + + // Create a new node at the same position of the exit node + NodeEntity gradientNode = new() + { + Id = Guid.NewGuid(), + Type = "ColorGradientNode", + PluginId = Guid.Parse("ffffffff-ffff-ffff-ffff-ffffffffffff"), + Name = "Color Gradient", + Description = "Outputs a color gradient with the given colors", + X = exitNode.X, + Y = exitNode.Y, + Storage = property.Value // Copy the value of the property into the node storage + }; + script.Nodes.Add(gradientNode); + + // Move all connections of the exit node to the new node + foreach (NodeConnectionEntity connection in script.Connections) + { + if (connection.SourceNode == exitNode.Id) + { + connection.SourceNode = gradientNode.Id; + connection.SourcePinId++; + } + } + + // Connect the data binding node to the source node + script.Connections.Add(new NodeConnectionEntity + { + SourceType = "ColorGradient", + SourceNode = exitNode.Id, + SourcePinCollectionId = -1, + SourcePinId = 0, + TargetType = "ColorGradient", + TargetNode = gradientNode.Id, + TargetPinCollectionId = -1, + TargetPinId = 0, + }); + + // Move the exit node to the right + exitNode.X += 300; + exitNode.Y += 30; + } + + public int UserVersion => 21; + + public void Apply(LiteRepository repository) + { + // Find all color gradient data bindings, there's no really good way to do this so infer it from the value + ILiteCollection collection = repository.Database.GetCollection(); + foreach (ProfileEntity profileEntity in collection.FindAll()) + { + foreach (LayerEntity layer in profileEntity.Layers) + MigrateDataBinding(layer.LayerBrush.PropertyGroup); + + collection.Update(profileEntity); + } + } + + private void MigrateDataBinding(PropertyGroupEntity propertyGroup) + { + foreach (PropertyGroupEntity propertyGroupPropertyGroup in propertyGroup.PropertyGroups) + MigrateDataBinding(propertyGroupPropertyGroup); + + foreach (PropertyEntity property in propertyGroup.Properties) + { + if (property.Value.StartsWith("[{\"Color\":\"") && property.DataBinding?.NodeScript != null && property.DataBinding.IsEnabled) + MigrateDataBinding(property); + } + } +} \ No newline at end of file diff --git a/src/Artemis.UI.Shared/Controls/ArtemisIcon.axaml.cs b/src/Artemis.UI.Shared/Controls/ArtemisIcon.axaml.cs index e60e2e73b..1e3e47a1d 100644 --- a/src/Artemis.UI.Shared/Controls/ArtemisIcon.axaml.cs +++ b/src/Artemis.UI.Shared/Controls/ArtemisIcon.axaml.cs @@ -129,7 +129,7 @@ public class ArtemisIcon : UserControl /// theme /// public static readonly StyledProperty FillProperty = - AvaloniaProperty.Register(nameof(Icon), true, notifying: IconChanging); + AvaloniaProperty.Register(nameof(Icon), false, notifying: IconChanging); /// /// Gets or sets a boolean indicating whether or not the icon should be filled in with the primary text color of the diff --git a/src/Artemis.UI.Shared/Controls/GradientPicker/GradientPicker.cs b/src/Artemis.UI.Shared/Controls/GradientPicker/GradientPicker.cs index e98be34a9..0066ad760 100644 --- a/src/Artemis.UI.Shared/Controls/GradientPicker/GradientPicker.cs +++ b/src/Artemis.UI.Shared/Controls/GradientPicker/GradientPicker.cs @@ -59,22 +59,29 @@ public class GradientPicker : TemplatedControl public static readonly DirectProperty DeleteStopProperty = AvaloniaProperty.RegisterDirect(nameof(DeleteStop), g => g.DeleteStop); + /// + /// Gets the color gradient currently being edited, for internal use only + /// + public static readonly DirectProperty EditingColorGradientProperty = + AvaloniaProperty.RegisterDirect(nameof(EditingColorGradient), g => g.EditingColorGradient); + private readonly ICommand _deleteStop; private ColorPicker? _colorPicker; private Button? _flipStops; private Border? _gradient; - private ColorGradient? _lastColorGradient; private Button? _randomize; private Button? _rotateStops; private bool _shiftDown; private Button? _spreadStops; private Button? _toggleSeamless; + private ColorGradient _colorGradient = null!; /// /// Creates a new instance of the class. /// public GradientPicker() { + EditingColorGradient = ColorGradient.GetUnicornBarf(); _deleteStop = ReactiveCommand.Create(s => { if (ColorGradient.Count <= 2) @@ -143,6 +150,15 @@ public class GradientPicker : TemplatedControl get => _deleteStop; private init => SetAndRaise(DeleteStopProperty, ref _deleteStop, value); } + + /// + /// Gets the color gradient backing the editor, this is a copy of . + /// + public ColorGradient EditingColorGradient + { + get => _colorGradient; + private set => SetAndRaise(EditingColorGradientProperty, ref _colorGradient, value); + } /// protected override void OnApplyTemplate(TemplateAppliedEventArgs e) @@ -167,7 +183,7 @@ public class GradientPicker : TemplatedControl _flipStops = e.NameScope.Find