refactor: simple radial menu for easier creation (#34639)

* it works! kinda

* so it works now

* minor cleanup

* central button now is useful too

* more cleanup

* minor cleanup

* more cleanup

* refactor: migrated code from toolbox (as it was rejected as too specific)

* feat: moved border drawing for radial menu into RadialMenuTextureButton. Radial menu position setting into was moved to OverrideArrange to not being called on every frame

* refactor: major reworks!

* renamed DrawBagleSector to DrawAnnulusSector

* Remove strange indexing

* Regularize math

* refactor: re-orienting segment elements to be Y-mirrored

* refactor: extracted radial menu radius multiplier property, changed color pallet for radial menu button

* refactor: removed icon backgrounds on textures used in current radial menu buttons with sectors, RadialContainer Radius renamed and now actually changed control radius.

* refactor: in RadialMenuTextureButtonWithSector all sector colors are converted to and from sRGB in property getter-setters

* refactor: renamed srgb to include Srgb suffix so devs gonna see that its srgb clearly

* fix: enabled any functional keys pressed when pushing radial menu buttons

* fix: radial menu sector now scales with UIScale

* fix: accept only one event when clicking on radial menu ContextualButton

* fix: now radial menu buttons accepts only click/alt-click, now clicks outside menu closes menu always

* feat: simple radial menu prototype for easier creation

* refactor: cleanup, restored emote filtering, button models now have class hierarchy

* refactor: remove usage of closure from 'outside code'

* refactor: remove non existing type from UiControlTest

* refactor: remove unused using

* refactor: revert ability to declare radial menu layers in xaml, scale 32px sprites using scale in radial menu

* refactor: whitespaces

* refactor: subscribe for dispose on existing radial menus

* feat: now simple radial menu button models can have custom color for each sector background (and hover background color). Also added OpenOverMouseScreenPosition inside SimpleRadialMenu

* fix: AI door menu now can be closed by verb if it gets unpowered

* refactor: simplify hiding border, extended xml-doc for simple radial menu settings

* refactor: remove linq

* fix: fix AI radial action serialization using invalid type

* refactor: fix duplicate ShowDeviceNotRespondingPopup for AI by properly checking if it can interact

* refactor: whitespaces, changed list to array in simple radial button preparing methods

---------

Co-authored-by: pa.pecherskij <pa.pecherskij@interfax.ru>
Co-authored-by: Eoin Mcloughlin <helloworld@eoinrul.es>
This commit is contained in:
Fildrance
2025-03-31 12:57:47 +03:00
committed by GitHub
parent 86e4365438
commit 19f3497b35
14 changed files with 559 additions and 573 deletions

View File

@@ -1,10 +1,10 @@
using Robust.Client.UserInterface;
using Robust.Client.UserInterface.Controls;
using Robust.Client.UserInterface.CustomControls;
using System.Linq;
using System.Numerics;
using Content.Shared.Input;
using Robust.Client.Graphics;
using Robust.Client.UserInterface;
using Robust.Client.UserInterface.Controls;
using Robust.Client.UserInterface.CustomControls;
using Robust.Shared.Input;
namespace Content.Client.UserInterface.Controls;
@@ -143,11 +143,8 @@ public class RadialMenu : BaseWindow
return children.First(x => x.Visible);
}
public bool TryToMoveToNewLayer(string newLayer)
public bool TryToMoveToNewLayer(Control newLayer)
{
if (newLayer == string.Empty)
return false;
var currentLayer = GetCurrentActiveLayer();
if (currentLayer == null)
@@ -161,7 +158,7 @@ public class RadialMenu : BaseWindow
continue;
// Hide layers which are not of interest
if (result == true || child.Name != newLayer)
if (result == true || child != newLayer)
{
child.Visible = false;
}
@@ -186,6 +183,19 @@ public class RadialMenu : BaseWindow
return result;
}
public bool TryToMoveToNewLayer(string targetLayerControlName)
{
foreach (var child in Children)
{
if (child.Name == targetLayerControlName && child is RadialContainer)
{
return TryToMoveToNewLayer(child);
}
}
return false;
}
public void ReturnToPreviousLayer()
{
// Close the menu if the traversal path is empty
@@ -296,9 +306,15 @@ public sealed class RadialMenuOuterAreaButton : RadialMenuTextureButtonBase
public class RadialMenuTextureButton : RadialMenuTextureButtonBase
{
/// <summary>
/// Upon clicking this button the radial menu will be moved to the named layer
/// Upon clicking this button the radial menu will be moved to the layer of this control.
/// </summary>
public string TargetLayer { get; set; } = string.Empty;
public Control? TargetLayer { get; set; }
/// <summary>
/// Other way to set navigation to other container, as <see cref="TargetLayer"/>,
/// but using <see cref="Control.Name"/> property of target <see cref="RadialContainer"/>.
/// </summary>
public string? TargetLayerControlName { get; set; }
/// <summary>
/// A simple texture button that can move the user to a different layer within a radial menu
@@ -311,7 +327,7 @@ public class RadialMenuTextureButton : RadialMenuTextureButtonBase
private void OnClicked(ButtonEventArgs args)
{
if (TargetLayer == string.Empty)
if (TargetLayer == null && TargetLayerControlName == null)
return;
var parent = FindParentMultiLayerContainer(this);
@@ -319,7 +335,14 @@ public class RadialMenuTextureButton : RadialMenuTextureButtonBase
if (parent == null)
return;
parent.TryToMoveToNewLayer(TargetLayer);
if (TargetLayer != null)
{
parent.TryToMoveToNewLayer(TargetLayer);
}
else
{
parent.TryToMoveToNewLayer(TargetLayerControlName!);
}
}
private RadialMenu? FindParentMultiLayerContainer(Control control)
@@ -387,7 +410,7 @@ public class RadialMenuTextureButtonWithSector : RadialMenuTextureButton, IRadia
private Color _hoverBorderColorSrgb = Color.ToSrgb(new Color(87, 91, 127, 128));
/// <summary>
/// Marker, that control should render border of segment. Is false by default.
/// Marker, that controls if border of segment should be rendered. Is false by default.
/// </summary>
/// <remarks>
/// By default color of border is same as color of background. Use <see cref="BorderColor"/>
@@ -400,13 +423,6 @@ public class RadialMenuTextureButtonWithSector : RadialMenuTextureButton, IRadia
/// </summary>
public bool DrawBackground { get; set; } = true;
/// <summary>
/// Marker, that control should render separator lines.
/// Separator lines are used to visually separate sector of radial menu items.
/// Is true by default
/// </summary>
public bool DrawSeparators { get; set; } = true;
/// <summary>
/// Color of background in non-hovered state. Accepts RGB color, works with sRGB for DrawPrimitive internally.
/// </summary>
@@ -520,7 +536,7 @@ public class RadialMenuTextureButtonWithSector : RadialMenuTextureButton, IRadia
DrawAnnulusSector(handle, containerCenter, _innerRadius * UIScale, _outerRadius * UIScale, angleFrom, angleTo, borderColor, false);
}
if (!_isWholeCircle && DrawSeparators)
if (!_isWholeCircle && DrawBorder)
{
DrawSeparatorLines(handle, containerCenter, _innerRadius * UIScale, _outerRadius * UIScale, angleFrom, angleTo, SeparatorColor);
}

View File

@@ -0,0 +1,8 @@
<ui:SimpleRadialMenu xmlns="https://spacestation14.io"
xmlns:ui="clr-namespace:Content.Client.UserInterface.Controls"
BackButtonStyleClass="RadialMenuBackButton"
CloseButtonStyleClass="RadialMenuCloseButton"
VerticalExpand="True"
HorizontalExpand="True"
MinSize="450 450">
</ui:SimpleRadialMenu>

View File

@@ -0,0 +1,279 @@
using Robust.Client.UserInterface;
using System.Numerics;
using Robust.Client.AutoGenerated;
using Robust.Client.Graphics;
using Robust.Shared.Utility;
using Robust.Client.GameObjects;
using Robust.Shared.Timing;
using Robust.Client.UserInterface.XAML;
using Robust.Client.Input;
namespace Content.Client.UserInterface.Controls;
[GenerateTypedNameReferences]
public partial class SimpleRadialMenu : RadialMenu
{
private EntityUid? _attachMenuToEntity;
[Dependency] private readonly IClyde _clyde = default!;
[Dependency] private readonly IEntityManager _entManager = default!;
[Dependency] private readonly IInputManager _inputManager = default!;
public SimpleRadialMenu()
{
IoCManager.InjectDependencies(this);
RobustXamlLoader.Load(this);
}
public void Track(EntityUid owner)
{
_attachMenuToEntity = owner;
}
public void SetButtons(IEnumerable<RadialMenuOption> models, SimpleRadialMenuSettings? settings = null)
{
ClearExistingChildrenRadialButtons();
var sprites = _entManager.System<SpriteSystem>();
Fill(models, sprites, Children, settings ?? new SimpleRadialMenuSettings());
}
public void OpenOverMouseScreenPosition()
{
var vpSize = _clyde.ScreenSize;
OpenCenteredAt(_inputManager.MouseScreenPosition.Position / vpSize);
}
private void Fill(
IEnumerable<RadialMenuOption> models,
SpriteSystem sprites,
ICollection<Control> rootControlChildren,
SimpleRadialMenuSettings settings
)
{
var rootContainer = new RadialContainer
{
HorizontalExpand = true,
VerticalExpand = true,
InitialRadius = settings.DefaultContainerRadius,
ReserveSpaceForHiddenChildren = false,
Visible = true
};
rootControlChildren.Add(rootContainer);
foreach (var model in models)
{
if (model is RadialMenuNestedLayerOption nestedMenuModel)
{
var linkButton = RecursiveContainerExtraction(sprites, rootControlChildren, nestedMenuModel, settings);
linkButton.Visible = true;
rootContainer.AddChild(linkButton);
}
else
{
var rootButtons = ConvertToButton(model, sprites, settings, false);
rootContainer.AddChild(rootButtons);
}
}
}
private RadialMenuTextureButton RecursiveContainerExtraction(
SpriteSystem sprites,
ICollection<Control> rootControlChildren,
RadialMenuNestedLayerOption model,
SimpleRadialMenuSettings settings
)
{
var container = new RadialContainer
{
HorizontalExpand = true,
VerticalExpand = true,
InitialRadius = model.ContainerRadius!.Value,
ReserveSpaceForHiddenChildren = false,
Visible = false
};
foreach (var nested in model.Nested)
{
if (nested is RadialMenuNestedLayerOption nestedMenuModel)
{
var linkButton = RecursiveContainerExtraction(sprites, rootControlChildren, nestedMenuModel, settings);
container.AddChild(linkButton);
}
else
{
var button = ConvertToButton(nested, sprites, settings, false);
container.AddChild(button);
}
}
rootControlChildren.Add(container);
var thisLayerLinkButton = ConvertToButton(model, sprites, settings, true);
thisLayerLinkButton.TargetLayer = container;
return thisLayerLinkButton;
}
private RadialMenuTextureButton ConvertToButton(
RadialMenuOption model,
SpriteSystem sprites,
SimpleRadialMenuSettings settings,
bool haveNested
)
{
var button = settings.UseSectors
? ConvertToButtonWithSector(model, settings)
: new RadialMenuTextureButton();
button.SetSize = new Vector2(64f, 64f);
button.ToolTip = model.ToolTip;
if (model.Sprite != null)
{
var scale = Vector2.One;
var texture = sprites.Frame0(model.Sprite);
if (texture.Width <= 32)
{
scale *= 2;
}
button.TextureNormal = texture;
button.Scale = scale;
}
if (model is RadialMenuActionOption actionOption)
{
button.OnPressed += _ =>
{
actionOption.OnPressed?.Invoke();
if(!haveNested)
Close();
};
}
return button;
}
private static RadialMenuTextureButtonWithSector ConvertToButtonWithSector(RadialMenuOption model, SimpleRadialMenuSettings settings)
{
var button = new RadialMenuTextureButtonWithSector
{
DrawBorder = settings.DisplayBorders,
DrawBackground = !settings.NoBackground
};
if (model.BackgroundColor.HasValue)
{
button.BackgroundColor = model.BackgroundColor.Value;
}
if (model.HoverBackgroundColor.HasValue)
{
button.HoverBackgroundColor = model.HoverBackgroundColor.Value;
}
return button;
}
private void ClearExistingChildrenRadialButtons()
{
var toRemove = new List<Control>(ChildCount);
foreach (var child in Children)
{
if (child != ContextualButton && child != MenuOuterAreaButton)
{
toRemove.Add(child);
}
}
foreach (var control in toRemove)
{
Children.Remove(control);
}
}
#region target entity tracking
protected override void FrameUpdate(FrameEventArgs args)
{
base.FrameUpdate(args);
if (_attachMenuToEntity != null)
{
UpdatePosition();
}
}
private void UpdatePosition()
{
if (!_entManager.TryGetComponent(_attachMenuToEntity, out TransformComponent? xform))
{
Close();
return;
}
if (!xform.Coordinates.IsValid(_entManager))
{
Close();
return;
}
var coords = _entManager.System<SpriteSystem>().GetSpriteScreenCoordinates((_attachMenuToEntity.Value, null, xform));
if (!coords.IsValid)
{
Close();
return;
}
OpenScreenAt(coords.Position, _clyde);
}
#endregion
}
public abstract class RadialMenuOption
{
public string? ToolTip { get; init; }
public SpriteSpecifier? Sprite { get; init; }
public Color? BackgroundColor { get; set; }
public Color? HoverBackgroundColor { get; set; }
}
public class RadialMenuActionOption(Action onPressed) : RadialMenuOption
{
public Action OnPressed { get; } = onPressed;
}
public class RadialMenuActionOption<T>(Action<T> onPressed, T data)
: RadialMenuActionOption(onPressed: () => onPressed(data));
public class RadialMenuNestedLayerOption(IReadOnlyCollection<RadialMenuOption> nested, float containerRadius = 100)
: RadialMenuOption
{
public float? ContainerRadius { get; } = containerRadius;
public IReadOnlyCollection<RadialMenuOption> Nested { get; } = nested;
}
public class SimpleRadialMenuSettings
{
/// <summary>
/// Default container draw radius. Is going to be further affected by per sector increment.
/// </summary>
public int DefaultContainerRadius = 100;
/// <summary>
/// Marker, if sector-buttons should be used.
/// </summary>
public bool UseSectors = true;
/// <summary>
/// Marker, if border of buttons should be rendered. Can only be used when <see cref="UseSectors"/> = true.
/// </summary>
public bool DisplayBorders = true;
/// <summary>
/// Marker, if sector background should not be rendered. Can only be used when <see cref="UseSectors"/> = true.
/// </summary>
public bool NoBackground = false;
}

View File

@@ -1,16 +1,17 @@
using Content.Client.Chat.UI;
using Content.Client.Gameplay;
using Content.Client.UserInterface.Controls;
using Content.Shared.Chat;
using Content.Shared.Chat.Prototypes;
using Content.Shared.Input;
using Content.Shared.Speech;
using Content.Shared.Whitelist;
using JetBrains.Annotations;
using Robust.Client.Graphics;
using Robust.Client.Input;
using Robust.Client.Player;
using Robust.Client.UserInterface.Controllers;
using Robust.Client.UserInterface.Controls;
using Robust.Shared.Input.Binding;
using Robust.Shared.Prototypes;
using Robust.Shared.Utility;
namespace Content.Client.UserInterface.Systems.Emotes;
@@ -18,11 +19,19 @@ namespace Content.Client.UserInterface.Systems.Emotes;
public sealed class EmotesUIController : UIController, IOnStateChanged<GameplayState>
{
[Dependency] private readonly IEntityManager _entityManager = default!;
[Dependency] private readonly IClyde _displayManager = default!;
[Dependency] private readonly IInputManager _inputManager = default!;
[Dependency] private readonly IPrototypeManager _prototypeManager = default!;
[Dependency] private readonly IPlayerManager _playerManager = default!;
private MenuButton? EmotesButton => UIManager.GetActiveUIWidgetOrNull<MenuBar.Widgets.GameTopMenuBar>()?.EmotesButton;
private EmotesMenu? _menu;
private SimpleRadialMenu? _menu;
private static readonly Dictionary<EmoteCategory, (string Tooltip, SpriteSpecifier Sprite)> EmoteGroupingInfo
= new Dictionary<EmoteCategory, (string Tooltip, SpriteSpecifier Sprite)>
{
[EmoteCategory.General] = ("emote-menu-category-general", new SpriteSpecifier.Texture(new ResPath("/Textures/Clothing/Head/Soft/mimesoft.rsi/icon.png"))),
[EmoteCategory.Hands] = ("emote-menu-category-hands", new SpriteSpecifier.Texture(new ResPath("/Textures/Clothing/Hands/Gloves/latex.rsi/icon.png"))),
[EmoteCategory.Vocal] = ("emote-menu-category-vocal", new SpriteSpecifier.Texture(new ResPath("/Textures/Interface/Emotes/vocal.png"))),
};
public void OnStateEntered(GameplayState state)
{
@@ -42,10 +51,16 @@ public sealed class EmotesUIController : UIController, IOnStateChanged<GameplayS
if (_menu == null)
{
// setup window
_menu = UIManager.CreateWindow<EmotesMenu>();
var prototypes = _prototypeManager.EnumeratePrototypes<EmotePrototype>();
var models = ConvertToButtons(prototypes);
_menu = new SimpleRadialMenu();
_menu.SetButtons(models);
_menu.Open();
_menu.OnClose += OnWindowClosed;
_menu.OnOpen += OnWindowOpen;
_menu.OnPlayEmote += OnPlayEmote;
if (EmotesButton != null)
EmotesButton.SetClickPressed(true);
@@ -56,16 +71,13 @@ public sealed class EmotesUIController : UIController, IOnStateChanged<GameplayS
}
else
{
// Open the menu, centered on the mouse
var vpSize = _displayManager.ScreenSize;
_menu.OpenCenteredAt(_inputManager.MouseScreenPosition.Position / vpSize);
_menu.OpenOverMouseScreenPosition();
}
}
else
{
_menu.OnClose -= OnWindowClosed;
_menu.OnOpen -= OnWindowOpen;
_menu.OnPlayEmote -= OnPlayEmote;
if (EmotesButton != null)
EmotesButton.SetClickPressed(false);
@@ -118,8 +130,62 @@ public sealed class EmotesUIController : UIController, IOnStateChanged<GameplayS
_menu = null;
}
private void OnPlayEmote(ProtoId<EmotePrototype> protoId)
private IEnumerable<RadialMenuOption> ConvertToButtons(IEnumerable<EmotePrototype> emotePrototypes)
{
_entityManager.RaisePredictiveEvent(new PlayEmoteMessage(protoId));
var whitelistSystem = EntitySystemManager.GetEntitySystem<EntityWhitelistSystem>();
var player = _playerManager.LocalSession?.AttachedEntity;
Dictionary<EmoteCategory, List<RadialMenuOption>> emotesByCategory = new();
foreach (var emote in emotePrototypes)
{
if(emote.Category == EmoteCategory.Invalid)
continue;
// only valid emotes that have ways to be triggered by chat and player have access / no restriction on
if (emote.Category == EmoteCategory.Invalid
|| emote.ChatTriggers.Count == 0
|| !(player.HasValue && whitelistSystem.IsWhitelistPassOrNull(emote.Whitelist, player.Value))
|| whitelistSystem.IsBlacklistPass(emote.Blacklist, player.Value))
continue;
if (!emote.Available
&& EntityManager.TryGetComponent<SpeechComponent>(player.Value, out var speech)
&& !speech.AllowedEmotes.Contains(emote.ID))
continue;
if (!emotesByCategory.TryGetValue(emote.Category, out var list))
{
list = new List<RadialMenuOption>();
emotesByCategory.Add(emote.Category, list);
}
var actionOption = new RadialMenuActionOption<EmotePrototype>(HandleRadialButtonClick, emote)
{
Sprite = emote.Icon,
ToolTip = Loc.GetString(emote.Name)
};
list.Add(actionOption);
}
var models = new RadialMenuOption[emotesByCategory.Count];
var i = 0;
foreach (var (key, list) in emotesByCategory)
{
var tuple = EmoteGroupingInfo[key];
models[i] = new RadialMenuNestedLayerOption(list)
{
Sprite = tuple.Sprite,
ToolTip = Loc.GetString(tuple.Tooltip)
};
i++;
}
return models;
}
private void HandleRadialButtonClick(EmotePrototype prototype)
{
_entityManager.RaisePredictiveEvent(new PlayEmoteMessage(prototype.ID));
}
}