Snapshot for release 2026.10.23.1 (internal 7581cff)
This commit is contained in:
parent
893973d0dd
commit
92f28bd243
73 changed files with 12203 additions and 308 deletions
237
Plugins/RynthCore.Plugin.RynthDefective/DefSession.cs
Normal file
237
Plugins/RynthCore.Plugin.RynthDefective/DefSession.cs
Normal file
|
|
@ -0,0 +1,237 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using RynthCore.Plugin.RynthDefective.Items;
|
||||
using RynthCore.Plugin.RynthDefective.Model;
|
||||
using RynthCore.Plugin.RynthDefective.Use;
|
||||
|
||||
namespace RynthCore.Plugin.RynthDefective;
|
||||
|
||||
/// <summary>
|
||||
/// What the windows and the commands act on: the character's data, the use controller, and the
|
||||
/// things a player does to slots (set one from the selected item, clear, move, bind a key). The
|
||||
/// host-facing parts are delegates, so all of it runs offline in the tests.
|
||||
/// </summary>
|
||||
internal sealed class DefSession
|
||||
{
|
||||
public DefData Data = new();
|
||||
public readonly UseController Use = new();
|
||||
public readonly HotkeyLookup Keys;
|
||||
|
||||
/// <summary>Everything carried now (cached by the plugin; at most a moment old).</summary>
|
||||
public Func<IReadOnlyList<CarriedItem>> Items = () => Array.Empty<CarriedItem>();
|
||||
public Func<uint> SelectedId = () => 0;
|
||||
public Func<long> Now = () => Environment.TickCount64;
|
||||
/// <summary>Types a line to the engine's chat parser ("/rc hotkey add F9 /rdef use 3"); false when it can't.</summary>
|
||||
public Func<string, bool> RunChat = _ => false;
|
||||
/// <summary>Asks for the character's file to be written soon.</summary>
|
||||
public Action Save = () => { };
|
||||
/// <summary>The pictures and bar buttons need op level 2 script windows.</summary>
|
||||
public bool IconsAvailable;
|
||||
public bool LoggedIn;
|
||||
public string Character = string.Empty;
|
||||
|
||||
// The line under the bar: the last thing that happened.
|
||||
private string _status = string.Empty;
|
||||
private long _statusAtMs;
|
||||
private bool _statusIsWarning;
|
||||
public const long StatusShownMs = 9000;
|
||||
|
||||
public DefSession(HotkeyLookup keys) => Keys = keys;
|
||||
|
||||
public DefSettings Settings => Data.Settings;
|
||||
|
||||
public void SetStatus(string text, bool warning = false)
|
||||
{
|
||||
_status = text;
|
||||
_statusIsWarning = warning;
|
||||
_statusAtMs = Now();
|
||||
}
|
||||
|
||||
/// <summary>The status line while it is fresh; empty after <see cref="StatusShownMs"/>.</summary>
|
||||
public string Status(out bool warning)
|
||||
{
|
||||
warning = _statusIsWarning;
|
||||
return _status.Length > 0 && Now() - _statusAtMs < StatusShownMs ? _status : string.Empty;
|
||||
}
|
||||
|
||||
// ── Using ───────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>The slot's button or key: use what it holds. Returns what to tell the player when nothing could be queued.</summary>
|
||||
public string? UseSlot(int slotNumber)
|
||||
{
|
||||
if (slotNumber < 1 || slotNumber > DefSettings.SlotsMax) return $"There is no slot {slotNumber}.";
|
||||
DefSlot slot = Data.Slots[slotNumber - 1];
|
||||
if (slot.Item == null) return $"Slot {slotNumber} is empty. Set it from the bar (Edit slots) or with /rdef set {slotNumber}.";
|
||||
Use.Request(new UseRequest(slot.Item, null, slot.Mode, "slot " + slotNumber, Now()));
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>/rdef use <name>: an item by what the player typed.</summary>
|
||||
public void UseByName(string name) =>
|
||||
Use.Request(new UseRequest(null, name, UseMode.Auto, "name '" + name + "'", Now()));
|
||||
|
||||
/// <summary>The picker: wield this weapon.</summary>
|
||||
public void Wield(ItemRef item) =>
|
||||
Use.Request(new UseRequest(item, null, UseMode.Equip, "picker", Now()));
|
||||
|
||||
// ── Slots ───────────────────────────────────────────────────────────────
|
||||
|
||||
public string SetFromSelected(int slotNumber)
|
||||
{
|
||||
uint sel = SelectedId();
|
||||
if (sel == 0) return "Select the item in the game first (click it in your pack), then set the slot.";
|
||||
CarriedItem? it = FindById(sel);
|
||||
if (it == null) return "The selected object isn't in your pack, so it can't go in a slot.";
|
||||
return SetSlot(slotNumber, it);
|
||||
}
|
||||
|
||||
/// <summary>An item dragged onto the slot (its object id).</summary>
|
||||
public string SetFromId(int slotNumber, uint objectId)
|
||||
{
|
||||
CarriedItem? it = FindById(objectId);
|
||||
if (it == null) return "That isn't in your pack, so it can't go in a slot.";
|
||||
return SetSlot(slotNumber, it);
|
||||
}
|
||||
|
||||
public string SetFromName(int slotNumber, string name)
|
||||
{
|
||||
CarriedItem? it = ItemMatcher.FindByName(name, Items());
|
||||
if (it == null) return $"No item named '{name}' in your pack.";
|
||||
return SetSlot(slotNumber, it);
|
||||
}
|
||||
|
||||
public string SetSlot(int slotNumber, CarriedItem it)
|
||||
{
|
||||
if (slotNumber < 1 || slotNumber > DefSettings.SlotsMax) return $"There is no slot {slotNumber}.";
|
||||
DefSlot slot = Data.Slots[slotNumber - 1];
|
||||
slot.Item = ItemRef.From(it);
|
||||
slot.Mode = UseMode.Auto;
|
||||
Save();
|
||||
ItemKind kind = ItemKinds.Classify(it);
|
||||
return $"Slot {slotNumber}: {it.FullName} ({UseModes.Describe(ItemKinds.DefaultAction(kind))} when pressed).";
|
||||
}
|
||||
|
||||
public string ClearSlot(int slotNumber)
|
||||
{
|
||||
if (slotNumber < 1 || slotNumber > DefSettings.SlotsMax) return $"There is no slot {slotNumber}.";
|
||||
Data.Slots[slotNumber - 1] = new DefSlot();
|
||||
Save();
|
||||
return $"Slot {slotNumber} cleared.";
|
||||
}
|
||||
|
||||
/// <summary>Swaps slot <paramref name="a"/> with <paramref name="b"/> (1-based), as moving one place.</summary>
|
||||
public bool SwapSlots(int a, int b)
|
||||
{
|
||||
int max = Settings.SlotCount;
|
||||
if (a < 1 || b < 1 || a > max || b > max || a == b) return false;
|
||||
(Data.Slots[a - 1], Data.Slots[b - 1]) = (Data.Slots[b - 1], Data.Slots[a - 1]);
|
||||
Save();
|
||||
return true;
|
||||
}
|
||||
|
||||
public void SetSlotMode(int slotNumber, UseMode mode)
|
||||
{
|
||||
Data.Slots[slotNumber - 1].Mode = mode;
|
||||
Save();
|
||||
}
|
||||
|
||||
public void SetSlotCount(int count)
|
||||
{
|
||||
Settings.SlotCount = Math.Clamp(count, DefSettings.SlotsMin, DefSettings.SlotsMax);
|
||||
Save();
|
||||
}
|
||||
|
||||
public CarriedItem? FindById(uint id)
|
||||
{
|
||||
foreach (CarriedItem it in Items())
|
||||
if (it.Id == id) return it;
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// After an inventory read: every slot, favourite and recent entry follows the item it stands for
|
||||
/// (a used-up stack's replacement, a new picture). Never clears anything. Returns whether a
|
||||
/// save is due. Skipped while nothing at all is carried (the inventory isn't loaded yet).
|
||||
/// </summary>
|
||||
public bool Maintain(IReadOnlyList<CarriedItem> items)
|
||||
{
|
||||
if (items.Count == 0) return false;
|
||||
bool changed = false;
|
||||
foreach (DefSlot s in Data.Slots)
|
||||
if (s.Item != null && ItemMatcher.Maintain(s.Item, items)) changed = true;
|
||||
foreach (ItemRef f in Data.Favourites)
|
||||
if (ItemMatcher.Maintain(f, items)) changed = true;
|
||||
foreach (ItemRef r in Data.Recent)
|
||||
if (ItemMatcher.Maintain(r, items)) changed = true;
|
||||
return changed;
|
||||
}
|
||||
|
||||
// ── Keys ────────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>The key bound to slot <paramref name="slotNumber"/> or to its item by name, or null.</summary>
|
||||
public string? KeyOfSlot(int slotNumber)
|
||||
{
|
||||
long now = Now();
|
||||
string? key = Keys.KeyFor(DefCommandParser.UseCommand(slotNumber), now);
|
||||
if (key != null) return key;
|
||||
ItemRef? item = Data.Slots[slotNumber - 1].Item;
|
||||
return item == null ? null : Keys.KeyFor(NameCommand(item), now);
|
||||
}
|
||||
|
||||
public static string NameCommand(ItemRef item) => "/rdef use " + item.FullName;
|
||||
|
||||
/// <summary>Binds a key to the slot ("/rdef use 3") or, with <paramref name="byName"/>, to its item's name ("/rdef use Stamina Kit"). Returns the message.</summary>
|
||||
public string BindKey(int slotNumber, string combo, bool byName)
|
||||
{
|
||||
combo = (combo ?? string.Empty).Trim();
|
||||
if (combo.Length == 0) return "Type the key first, e.g. F9 or Ctrl+1.";
|
||||
if (combo.IndexOf(' ') >= 0) return "A key has no spaces, e.g. Ctrl+F9.";
|
||||
if (slotNumber < 1 || slotNumber > DefSettings.SlotsMax) return $"There is no slot {slotNumber}.";
|
||||
ItemRef? item = Data.Slots[slotNumber - 1].Item;
|
||||
if (byName && item == null) return $"Slot {slotNumber} is empty: nothing to bind by name.";
|
||||
|
||||
string command = byName ? NameCommand(item!) : DefCommandParser.UseCommand(slotNumber);
|
||||
UnbindQuiet(slotNumber);
|
||||
if (!RunChat($"/rc hotkey add {combo} {command}"))
|
||||
return $"This engine can't bind keys from here. Type: /rc hotkey add {combo} {command}";
|
||||
Keys.Invalidate();
|
||||
return $"Binding {combo} to {command} (the engine confirms in chat; Settings > Hotkeys lists it).";
|
||||
}
|
||||
|
||||
public string UnbindKey(int slotNumber)
|
||||
{
|
||||
if (slotNumber < 1 || slotNumber > DefSettings.SlotsMax) return $"There is no slot {slotNumber}.";
|
||||
string? key = UnbindQuiet(slotNumber);
|
||||
Keys.Invalidate();
|
||||
return key == null ? $"Slot {slotNumber} has no key." : $"Key {key} removed from slot {slotNumber}.";
|
||||
}
|
||||
|
||||
/// <summary>Removes the slot's current key (either way of binding); returns it.</summary>
|
||||
private string? UnbindQuiet(int slotNumber)
|
||||
{
|
||||
string? key = KeyOfSlot(slotNumber);
|
||||
if (key == null) return null;
|
||||
string combo = key.EndsWith(" (off)", StringComparison.Ordinal) ? key[..^6] : key;
|
||||
RunChat($"/rc hotkey remove {combo}");
|
||||
return combo;
|
||||
}
|
||||
|
||||
// ── Favourites ──────────────────────────────────────────────────────────
|
||||
|
||||
public string ToggleFavourite(ItemRef r)
|
||||
{
|
||||
bool now = Data.ToggleFavourite(r);
|
||||
Save();
|
||||
return now ? $"{r.FullName} is a favourite." : $"{r.FullName} is no longer a favourite.";
|
||||
}
|
||||
|
||||
/// <summary>/rdef fav: the item selected in the game.</summary>
|
||||
public string ToggleSelectedFavourite()
|
||||
{
|
||||
uint sel = SelectedId();
|
||||
if (sel == 0) return "Select a weapon in the game first.";
|
||||
CarriedItem? it = FindById(sel);
|
||||
if (it == null) return "The selected object isn't in your pack.";
|
||||
return ToggleFavourite(ItemRef.From(it));
|
||||
}
|
||||
}
|
||||
42
Plugins/RynthCore.Plugin.RynthDefective/Items/CarriedItem.cs
Normal file
42
Plugins/RynthCore.Plugin.RynthDefective/Items/CarriedItem.cs
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
using System;
|
||||
|
||||
namespace RynthCore.Plugin.RynthDefective.Items;
|
||||
|
||||
/// <summary>
|
||||
/// One thing the character carries or wears, as the client reports it. A plain data holder: the
|
||||
/// reader (HostInventory) fills it, everything else (slot matching, item kinds, the weapon picker)
|
||||
/// works on it without the host, so it can be tested offline.
|
||||
/// </summary>
|
||||
internal sealed class CarriedItem
|
||||
{
|
||||
public uint Id;
|
||||
public string Name = string.Empty;
|
||||
public uint Wcid;
|
||||
/// <summary>MaterialType (int 131): "Silver" in "Silver Wand"; 0 = none / unknown.</summary>
|
||||
public int Material;
|
||||
/// <summary>ItemType flags (the client's TryGetItemType).</summary>
|
||||
public uint ItemType;
|
||||
/// <summary>PublicWeenieDesc bitfield (healer, food ...); 0 when the engine can't read it.</summary>
|
||||
public uint Bitfield;
|
||||
/// <summary>Stack size (at least 1) and the largest stack (1 = not stackable).</summary>
|
||||
public int Stack = 1, MaxStack = 1;
|
||||
/// <summary>Uses left / most uses (Structure 92 / MaxStructure 91): kits, essences; MaxUses 0 = none.</summary>
|
||||
public int Uses, MaxUses;
|
||||
/// <summary>ValidLocations (int 9): the EquipMask slots it can go into; 0 = it can't be worn or wielded.</summary>
|
||||
public int ValidLocations;
|
||||
/// <summary>The slot it is wielded in now (0 = in a pack).</summary>
|
||||
public int WieldedLocation;
|
||||
/// <summary>CombatUse (int 51): 1 melee, 2 missile, 3 ammo, 4 shield, 5 two-handed.</summary>
|
||||
public int CombatUse;
|
||||
/// <summary>DamageType (int 45) and UiEffects (int 18): the element of a caster.</summary>
|
||||
public int DamageType, UiEffects;
|
||||
/// <summary>Icon, underlay and overlay texture ids (0x06......), 0 = none.</summary>
|
||||
public uint Icon, Underlay, Overlay;
|
||||
|
||||
public bool Wielded => WieldedLocation != 0;
|
||||
|
||||
/// <summary>The name with the material in front ("Silver Wand"), as the character sees it in the game.</summary>
|
||||
public string FullName => ItemNames.Full(Name, Material);
|
||||
|
||||
public override string ToString() => $"0x{Id:X8} {FullName}";
|
||||
}
|
||||
169
Plugins/RynthCore.Plugin.RynthDefective/Items/HostInventory.cs
Normal file
169
Plugins/RynthCore.Plugin.RynthDefective/Items/HostInventory.cs
Normal file
|
|
@ -0,0 +1,169 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
namespace RynthCore.Plugin.RynthDefective.Items;
|
||||
|
||||
/// <summary>
|
||||
/// Reads what the character carries and wears from the client into <see cref="CarriedItem"/>s.
|
||||
/// Plugin pump thread only. Everything comes from what the client already has (the engine's
|
||||
/// object snapshot and its property caches); nothing is sent to the server.
|
||||
/// GetContainerContents(player) returns the main pack's items, the side packs and the worn and
|
||||
/// wielded items; each side pack's items come from GetContainerContents(pack). What an item IS
|
||||
/// (name, wcid, material, kind, picture) is kept per object id once read; what changes (stack,
|
||||
/// uses left, whether it is in hand) is read every time.
|
||||
/// </summary>
|
||||
internal sealed class HostInventory
|
||||
{
|
||||
// STypeInt
|
||||
private const uint StackSize = 12, MaxStackSize = 11, ValidLocations = 9, CurrentWieldedLocation = 10, UiEffects = 18,
|
||||
DamageType = 45, CombatUse = 51, MaterialType = 131, Structure = 92, MaxStructure = 91;
|
||||
// STypeDID
|
||||
private const uint DidIcon = 8, DidIconOverlay = 50, DidIconUnderlay = 52;
|
||||
|
||||
private const int MaxContents = 1024;
|
||||
private const int MaxNesting = 3;
|
||||
private const uint ItemTypeContainer = 0x200;
|
||||
/// <summary>A caster whose damage type has not arrived (it comes with an identify) is read again after this.</summary>
|
||||
private const long RecheckMs = 15_000;
|
||||
|
||||
private sealed class Static
|
||||
{
|
||||
public string Name = string.Empty;
|
||||
public uint Wcid;
|
||||
public int Material;
|
||||
public uint ItemType, Bitfield;
|
||||
public int MaxStack = 1, MaxUses, ValidLocations, CombatUse, DamageType, UiEffects;
|
||||
public uint Icon, Underlay, Overlay;
|
||||
public bool IsContainer;
|
||||
public long ReadMs;
|
||||
}
|
||||
|
||||
private readonly Dictionary<uint, Static> _static = new();
|
||||
private readonly uint[] _contents = new uint[MaxContents];
|
||||
|
||||
public void Reset() => _static.Clear();
|
||||
|
||||
/// <summary>Everything carried and worn; empty when the character or its inventory isn't readable yet.</summary>
|
||||
public List<CarriedItem> Read(RynthCoreHost host, long nowMs)
|
||||
{
|
||||
var items = new List<CarriedItem>();
|
||||
if (!host.HasGetPlayerId || !host.HasGetContainerContents) return items;
|
||||
uint player = host.GetPlayerId();
|
||||
if (player == 0) return items;
|
||||
ScanInto(host, player, player, items, 0, nowMs);
|
||||
return items;
|
||||
}
|
||||
|
||||
private void ScanInto(RynthCoreHost host, uint container, uint player, List<CarriedItem> items, int depth, long nowMs)
|
||||
{
|
||||
int n = host.GetContainerContents(container, _contents);
|
||||
if (n <= 0) return;
|
||||
uint[] ids = new uint[n];
|
||||
Array.Copy(_contents, ids, n);
|
||||
var packs = new List<uint>();
|
||||
foreach (uint id in ids)
|
||||
{
|
||||
if (id == 0) continue;
|
||||
Ownership(host, id, out uint c, out uint w, out uint loc);
|
||||
bool worn = w == player && w != 0;
|
||||
if (!worn && c != container && c != 0) continue; // moved away since the engine's snapshot
|
||||
CarriedItem? it = ReadItem(host, id, nowMs, out Static? st);
|
||||
if (it == null) continue;
|
||||
if (worn)
|
||||
{
|
||||
if (loc == 0 && host.TryGetObjectIntProperty(id, CurrentWieldedLocation, out int l)) loc = unchecked((uint)l);
|
||||
it.WieldedLocation = loc == 0 ? 1 : unchecked((int)loc); // worn but the slot unreadable: still "in hand"
|
||||
}
|
||||
else if (st!.IsContainer && depth < MaxNesting)
|
||||
{
|
||||
packs.Add(id);
|
||||
continue; // a pack is not something to use or wield
|
||||
}
|
||||
items.Add(it);
|
||||
}
|
||||
foreach (uint pack in packs)
|
||||
ScanInto(host, pack, player, items, depth + 1, nowMs);
|
||||
}
|
||||
|
||||
/// <summary>One item as the client has it now (null if it has no name yet or is gone).</summary>
|
||||
public CarriedItem? ReadOne(RynthCoreHost host, uint id, long nowMs)
|
||||
{
|
||||
uint player = host.HasGetPlayerId ? host.GetPlayerId() : 0;
|
||||
CarriedItem? it = ReadItem(host, id, nowMs, out _);
|
||||
if (it == null) return null;
|
||||
Ownership(host, id, out _, out uint w, out uint loc);
|
||||
if (w != 0 && w == player)
|
||||
{
|
||||
if (loc == 0 && host.TryGetObjectIntProperty(id, CurrentWieldedLocation, out int l)) loc = unchecked((uint)l);
|
||||
it.WieldedLocation = loc == 0 ? 1 : unchecked((int)loc);
|
||||
}
|
||||
return it;
|
||||
}
|
||||
|
||||
private CarriedItem? ReadItem(RynthCoreHost host, uint id, long nowMs, out Static? st)
|
||||
{
|
||||
st = null;
|
||||
if (!_static.TryGetValue(id, out st) || Stale(st, nowMs))
|
||||
{
|
||||
st = ReadStatic(host, id, nowMs);
|
||||
if (st == null) return null;
|
||||
_static[id] = st;
|
||||
}
|
||||
var it = new CarriedItem
|
||||
{
|
||||
Id = id,
|
||||
Name = st.Name,
|
||||
Wcid = st.Wcid,
|
||||
Material = st.Material,
|
||||
ItemType = st.ItemType,
|
||||
Bitfield = st.Bitfield,
|
||||
MaxStack = st.MaxStack,
|
||||
MaxUses = st.MaxUses,
|
||||
ValidLocations = st.ValidLocations,
|
||||
CombatUse = st.CombatUse,
|
||||
DamageType = st.DamageType,
|
||||
UiEffects = st.UiEffects,
|
||||
Icon = st.Icon,
|
||||
Underlay = st.Underlay,
|
||||
Overlay = st.Overlay,
|
||||
};
|
||||
if (host.TryGetObjectIntProperty(id, StackSize, out int stack) && stack > 0) it.Stack = stack;
|
||||
if (st.MaxUses > 0 && host.TryGetObjectIntProperty(id, Structure, out int uses)) it.Uses = Math.Max(0, uses);
|
||||
return it;
|
||||
}
|
||||
|
||||
private static bool Stale(Static st, long nowMs) =>
|
||||
(st.ItemType & ItemKinds.TypeCaster) != 0 && st.DamageType == 0 && nowMs - st.ReadMs >= RecheckMs;
|
||||
|
||||
private static Static? ReadStatic(RynthCoreHost host, uint id, long nowMs)
|
||||
{
|
||||
if (!host.TryGetObjectName(id, out string name) || string.IsNullOrWhiteSpace(name)) return null;
|
||||
var st = new Static { Name = name.Trim(), ReadMs = nowMs };
|
||||
if (host.TryGetItemType(id, out uint type)) st.ItemType = type;
|
||||
st.IsContainer = (st.ItemType & ItemTypeContainer) != 0;
|
||||
if (host.HasGetObjectWcid && host.TryGetObjectWcid(id, out uint wcid)) st.Wcid = wcid;
|
||||
if (host.HasGetObjectBitfield && host.TryGetObjectBitfield(id, out uint bf)) st.Bitfield = bf;
|
||||
if (host.TryGetObjectIntProperty(id, MaterialType, out int material)) st.Material = Math.Max(0, material);
|
||||
if (host.TryGetObjectIntProperty(id, MaxStackSize, out int maxStack)) st.MaxStack = Math.Max(1, maxStack);
|
||||
if (host.TryGetObjectIntProperty(id, MaxStructure, out int maxUses) && maxUses > 0) st.MaxUses = maxUses;
|
||||
if (host.TryGetObjectIntProperty(id, ValidLocations, out int valid)) st.ValidLocations = valid;
|
||||
if (host.TryGetObjectIntProperty(id, CombatUse, out int use)) st.CombatUse = use;
|
||||
if (host.TryGetObjectIntProperty(id, DamageType, out int dt)) st.DamageType = dt;
|
||||
if (host.TryGetObjectIntProperty(id, UiEffects, out int fx)) st.UiEffects = fx;
|
||||
if (host.HasGetObjectDataIdProperty)
|
||||
{
|
||||
if (host.TryGetObjectDataIdProperty(id, DidIcon, out uint icon)) st.Icon = icon;
|
||||
if (host.TryGetObjectDataIdProperty(id, DidIconUnderlay, out uint under)) st.Underlay = under;
|
||||
if (host.TryGetObjectDataIdProperty(id, DidIconOverlay, out uint over)) st.Overlay = over;
|
||||
}
|
||||
return st;
|
||||
}
|
||||
|
||||
private static void Ownership(RynthCoreHost host, uint id, out uint container, out uint wielder, out uint location)
|
||||
{
|
||||
container = wielder = location = 0;
|
||||
if (host.HasGetObjectOwnershipInfo && host.TryGetObjectOwnershipInfo(id, out container, out wielder, out location)) return;
|
||||
if (host.HasGetObjectWielderInfo && host.TryGetObjectWielderInfo(id, out uint w, out uint loc)) { wielder = w; location = loc; }
|
||||
}
|
||||
}
|
||||
145
Plugins/RynthCore.Plugin.RynthDefective/Items/ItemKinds.cs
Normal file
145
Plugins/RynthCore.Plugin.RynthDefective/Items/ItemKinds.cs
Normal file
|
|
@ -0,0 +1,145 @@
|
|||
using System;
|
||||
|
||||
namespace RynthCore.Plugin.RynthDefective.Items;
|
||||
|
||||
/// <summary>What an item is, as far as using it goes.</summary>
|
||||
internal enum ItemKind
|
||||
{
|
||||
/// <summary>Anything used by itself: potions, scrolls, food, gems, summons ...</summary>
|
||||
Other,
|
||||
/// <summary>A healing or stamina kit: used on yourself.</summary>
|
||||
Kit,
|
||||
Melee,
|
||||
Missile,
|
||||
/// <summary>A wand, staff or orb that casts war magic (any element but Nether).</summary>
|
||||
WarWand,
|
||||
/// <summary>A caster of Nether: void magic.</summary>
|
||||
VoidWand,
|
||||
Shield,
|
||||
Armor,
|
||||
Jewelry,
|
||||
Ammo,
|
||||
}
|
||||
|
||||
/// <summary>What pressing an item's slot does with it.</summary>
|
||||
internal enum UseAction
|
||||
{
|
||||
/// <summary>UseObject: double-clicking it (potions, scrolls, food).</summary>
|
||||
Use,
|
||||
/// <summary>UseObjectOn(item, you): healing and stamina kits.</summary>
|
||||
UseOnSelf,
|
||||
/// <summary>UseObjectOn(item, the selected target).</summary>
|
||||
UseOnSelected,
|
||||
/// <summary>Wield or wear it (UseObject: the client's double-click takes what is in the way off).</summary>
|
||||
Equip,
|
||||
}
|
||||
|
||||
/// <summary>The weapon picker's groups, in the order they are listed.</summary>
|
||||
internal enum WeaponGroup { Melee, Missile, WarMagic, VoidMagic, Shield, Ammo }
|
||||
|
||||
internal static class ItemKinds
|
||||
{
|
||||
// ItemType flags
|
||||
public const uint TypeMelee = 0x1, TypeArmor = 0x2, TypeClothing = 0x4, TypeJewelry = 0x8, TypeMissile = 0x100, TypeCaster = 0x8000;
|
||||
// PublicWeenieDesc bitfield: the healer bit
|
||||
public const uint BitfieldHealer = 0x10000;
|
||||
// EquipMask slots
|
||||
public const int ShieldSlot = 0x00200000, AmmoSlot = 0x00800000;
|
||||
// CombatUse values
|
||||
public const int CombatUseAmmo = 3, CombatUseShield = 4;
|
||||
// DamageType / UiEffects bits of Nether
|
||||
public const int DamageNether = 0x400, EffectNether = 0x1000;
|
||||
|
||||
public static ItemKind Classify(CarriedItem it)
|
||||
{
|
||||
bool equippable = it.ValidLocations != 0;
|
||||
if (!equippable)
|
||||
{
|
||||
if ((it.Bitfield & BitfieldHealer) != 0) return ItemKind.Kit;
|
||||
// The engine couldn't read the bitfield: RynthAi's own test for the kits it uses.
|
||||
if (it.Bitfield == 0 && it.Name.EndsWith(" Kit", StringComparison.OrdinalIgnoreCase)) return ItemKind.Kit;
|
||||
return ItemKind.Other;
|
||||
}
|
||||
|
||||
bool weaponClass = (it.ItemType & (TypeMelee | TypeMissile | TypeCaster)) != 0 || IsWandName(it.Name);
|
||||
if (it.CombatUse == CombatUseAmmo || (it.ValidLocations & AmmoSlot) != 0) return ItemKind.Ammo;
|
||||
if (it.CombatUse == CombatUseShield || (!weaponClass && (it.ValidLocations & ShieldSlot) != 0)) return ItemKind.Shield;
|
||||
if ((it.ItemType & TypeCaster) != 0 || (weaponClass && (it.ItemType & (TypeMelee | TypeMissile)) == 0))
|
||||
return IsNether(it) ? ItemKind.VoidWand : ItemKind.WarWand;
|
||||
if ((it.ItemType & TypeMissile) != 0) return ItemKind.Missile;
|
||||
if ((it.ItemType & TypeMelee) != 0) return ItemKind.Melee;
|
||||
if ((it.ItemType & TypeJewelry) != 0) return ItemKind.Jewelry;
|
||||
return ItemKind.Armor; // armor, clothing and anything else that is worn
|
||||
}
|
||||
|
||||
/// <summary>What a slot does with the item when the player has set nothing else.</summary>
|
||||
public static UseAction DefaultAction(ItemKind kind) => kind switch
|
||||
{
|
||||
ItemKind.Kit => UseAction.UseOnSelf,
|
||||
ItemKind.Other => UseAction.Use,
|
||||
_ => UseAction.Equip,
|
||||
};
|
||||
|
||||
public static bool IsWeapon(ItemKind k) => k is ItemKind.Melee or ItemKind.Missile or ItemKind.WarWand or ItemKind.VoidWand;
|
||||
|
||||
/// <summary>The picker group of a kind, or null when the picker doesn't list it.</summary>
|
||||
public static WeaponGroup? GroupOf(ItemKind k) => k switch
|
||||
{
|
||||
ItemKind.Melee => WeaponGroup.Melee,
|
||||
ItemKind.Missile => WeaponGroup.Missile,
|
||||
ItemKind.WarWand => WeaponGroup.WarMagic,
|
||||
ItemKind.VoidWand => WeaponGroup.VoidMagic,
|
||||
ItemKind.Shield => WeaponGroup.Shield,
|
||||
ItemKind.Ammo => WeaponGroup.Ammo,
|
||||
_ => null,
|
||||
};
|
||||
|
||||
public static string Label(WeaponGroup g) => g switch
|
||||
{
|
||||
WeaponGroup.Melee => "Melee",
|
||||
WeaponGroup.Missile => "Missile",
|
||||
WeaponGroup.WarMagic => "War Magic",
|
||||
WeaponGroup.VoidMagic => "Void Magic",
|
||||
WeaponGroup.Shield => "Shields",
|
||||
_ => "Ammunition",
|
||||
};
|
||||
|
||||
/// <summary>A caster whose element is Nether (the damage type, the icon's glow, or the name).</summary>
|
||||
public static bool IsNether(CarriedItem it) =>
|
||||
(it.DamageType & DamageNether) != 0
|
||||
|| (it.DamageType == 0 && (it.UiEffects & EffectNether) != 0)
|
||||
|| (it.DamageType == 0 && it.UiEffects == 0 && HasWord(it.Name, "Nether", "Void"));
|
||||
|
||||
/// <summary>The element a caster is named or glows for, for the picker's second column ("" = none known).</summary>
|
||||
public static string Element(CarriedItem it)
|
||||
{
|
||||
if ((it.DamageType & 0x400) != 0) return "Nether";
|
||||
if ((it.DamageType & 0x10) != 0) return "Fire";
|
||||
if ((it.DamageType & 0x08) != 0) return "Cold";
|
||||
if ((it.DamageType & 0x40) != 0) return "Lightning";
|
||||
if ((it.DamageType & 0x20) != 0) return "Acid";
|
||||
int fx = it.UiEffects;
|
||||
if ((fx & 0x1000) != 0) return "Nether";
|
||||
if ((fx & 0x0020) != 0) return "Fire";
|
||||
if ((fx & 0x0080) != 0) return "Cold";
|
||||
if ((fx & 0x0040) != 0) return "Lightning";
|
||||
if ((fx & 0x0100) != 0) return "Acid";
|
||||
if ((fx & 0x0400) != 0) return "Slash";
|
||||
if ((fx & 0x0800) != 0) return "Pierce";
|
||||
if ((fx & 0x0200) != 0) return "Bludgeon";
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
public static bool IsWandName(string? name) => HasWord(name, "Orb", "Staff", "Wand", "Scepter", "Sceptre", "Baton", "Crozier");
|
||||
|
||||
private static bool HasWord(string? name, params string[] words)
|
||||
{
|
||||
if (string.IsNullOrEmpty(name)) return false;
|
||||
foreach (string w in words)
|
||||
if (name.IndexOf(w, StringComparison.OrdinalIgnoreCase) >= 0) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>A launcher needs ammunition in hand; a thrown weapon (a stack of darts) does not.</summary>
|
||||
public static bool NeedsAmmo(CarriedItem it) => it.MaxStack <= 1;
|
||||
}
|
||||
33
Plugins/RynthCore.Plugin.RynthDefective/Items/ItemNames.cs
Normal file
33
Plugins/RynthCore.Plugin.RynthDefective/Items/ItemNames.cs
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
using System;
|
||||
|
||||
namespace RynthCore.Plugin.RynthDefective.Items;
|
||||
|
||||
/// <summary>Display names: a weapon's material in front of the base name the client reports.</summary>
|
||||
internal static class ItemNames
|
||||
{
|
||||
/// <summary>ACE's MaterialType names, index = the id (0 = none).</summary>
|
||||
private static readonly string[] Materials =
|
||||
{
|
||||
"", "Ceramic", "Porcelain", "Cloth", "Linen", "Satin", "Silk", "Velvet", "Wool", "Gem",
|
||||
"Agate", "Amber", "Amethyst", "Aquamarine", "Azurite", "Black Garnet", "Black Opal", "Bloodstone", "Carnelian", "Citrine",
|
||||
"Diamond", "Emerald", "Fire Opal", "Green Garnet", "Green Jade", "Hematite", "Imperial Topaz", "Jet", "Lapis Lazuli", "Lavender Jade",
|
||||
"Malachite", "Moonstone", "Onyx", "Opal", "Peridot", "Red Garnet", "Red Jade", "Rose Quartz", "Ruby", "Sapphire",
|
||||
"Smokey Quartz", "Sunstone", "Tiger Eye", "Tourmaline", "Turquoise", "White Jade", "White Quartz", "White Sapphire", "Yellow Garnet", "Yellow Topaz",
|
||||
"Zircon", "Ivory", "Leather", "Armoredillo Hide", "Gromnie Hide", "Reed Shark Hide", "Metal", "Brass", "Bronze", "Copper",
|
||||
"Gold", "Iron", "Pyreal", "Silver", "Steel", "Stone", "Alabaster", "Granite", "Marble", "Obsidian",
|
||||
"Sandstone", "Serpentine", "Wood", "Ebony", "Mahogany", "Oak", "Pine", "Teak",
|
||||
};
|
||||
|
||||
public static string Material(int id) => id > 0 && id < Materials.Length ? Materials[id] : string.Empty;
|
||||
|
||||
/// <summary>"Silver Wand": the material in front, unless the name already starts with it.</summary>
|
||||
public static string Full(string? baseName, int material)
|
||||
{
|
||||
string name = (baseName ?? string.Empty).Trim();
|
||||
string mat = Material(material);
|
||||
if (mat.Length == 0 || name.Length == 0) return name;
|
||||
if (name.StartsWith(mat + " ", StringComparison.OrdinalIgnoreCase) || name.Equals(mat, StringComparison.OrdinalIgnoreCase))
|
||||
return name;
|
||||
return mat + " " + name;
|
||||
}
|
||||
}
|
||||
85
Plugins/RynthCore.Plugin.RynthDefective/Model/DefCommand.cs
Normal file
85
Plugins/RynthCore.Plugin.RynthDefective/Model/DefCommand.cs
Normal file
|
|
@ -0,0 +1,85 @@
|
|||
using System;
|
||||
|
||||
namespace RynthCore.Plugin.RynthDefective.Model;
|
||||
|
||||
internal enum DefVerb { Toggle, Help, Use, Set, Clear, Bind, Unbind, Weapons, Favourite, Slots, List, Status, Error, Panels, Selection }
|
||||
|
||||
/// <summary>A parsed "/rdef ..." line. Use: <see cref="Slot"/> (1-based) or <see cref="Text"/> (an item name).</summary>
|
||||
internal sealed record DefCommand(DefVerb Verb, int Slot = 0, string Text = "", string Error = "");
|
||||
|
||||
internal static class DefCommandParser
|
||||
{
|
||||
public const string Usage =
|
||||
"/rdef [use <slot or item name> | set <slot> [item name] | clear <slot> | bind <slot> <key> | unbind <slot> | "
|
||||
+ "weapons [search] | fav | slots <count> | list | status | panels (the game panel buttons) | selection]";
|
||||
|
||||
/// <summary>Parses the arguments after "/rdef" (blank = show or hide the bar).</summary>
|
||||
public static DefCommand Parse(string? args)
|
||||
{
|
||||
string a = (args ?? string.Empty).Trim();
|
||||
if (a.Length == 0) return new DefCommand(DefVerb.Toggle);
|
||||
int sp = a.IndexOf(' ');
|
||||
string verb = (sp < 0 ? a : a[..sp]).ToLowerInvariant();
|
||||
string rest = sp < 0 ? string.Empty : a[(sp + 1)..].Trim();
|
||||
|
||||
switch (verb)
|
||||
{
|
||||
case "help": case "?": return new DefCommand(DefVerb.Help);
|
||||
case "list": case "ls": return new DefCommand(DefVerb.List);
|
||||
case "status": return new DefCommand(DefVerb.Status);
|
||||
case "panels": case "panel": return new DefCommand(DefVerb.Panels);
|
||||
case "selection": case "target":
|
||||
// "/rdef selection 0x80001234": select that object (a test hook for the Selection window).
|
||||
return new DefCommand(DefVerb.Selection, Text: rest);
|
||||
case "fav": case "favourite": case "favorite": return new DefCommand(DefVerb.Favourite);
|
||||
case "weapons": case "weapon": case "picker": return new DefCommand(DefVerb.Weapons, Text: rest);
|
||||
case "use": case "wield": case "equip":
|
||||
if (rest.Length == 0) return Fail($"Use which slot or item? e.g. /rdef use 1 or /rdef use Peerless Healing Kit");
|
||||
return TrySlot(rest, out int n) ? new DefCommand(DefVerb.Use, n) : new DefCommand(DefVerb.Use, Text: rest);
|
||||
case "set":
|
||||
{
|
||||
SplitSlot(rest, out string? slotText, out string tail);
|
||||
if (slotText == null || !TrySlot(slotText, out int slot)) return Fail("Which slot? e.g. /rdef set 3 (the item selected in the game goes in slot 3) or /rdef set 3 Peerless Healing Kit");
|
||||
return new DefCommand(DefVerb.Set, slot, tail);
|
||||
}
|
||||
case "clear":
|
||||
{
|
||||
return TrySlot(rest, out int slot) ? new DefCommand(DefVerb.Clear, slot) : Fail("Which slot? e.g. /rdef clear 3");
|
||||
}
|
||||
case "bind":
|
||||
{
|
||||
SplitSlot(rest, out string? slotText, out string key);
|
||||
if (slotText == null || !TrySlot(slotText, out int slot) || key.Length == 0)
|
||||
return Fail("Usage: /rdef bind <slot> <key>, e.g. /rdef bind 3 F9 or /rdef bind 3 Ctrl+1");
|
||||
return new DefCommand(DefVerb.Bind, slot, key);
|
||||
}
|
||||
case "unbind":
|
||||
return TrySlot(rest, out int us) ? new DefCommand(DefVerb.Unbind, us) : Fail("Which slot? e.g. /rdef unbind 3");
|
||||
case "slots":
|
||||
return int.TryParse(rest, out int count) && count >= DefSettings.SlotsMin && count <= DefSettings.SlotsMax
|
||||
? new DefCommand(DefVerb.Slots, count)
|
||||
: Fail($"How many slots? {DefSettings.SlotsMin} to {DefSettings.SlotsMax}, e.g. /rdef slots 10");
|
||||
default:
|
||||
// "/rdef Stamina Kit" is a shorthand for use.
|
||||
return new DefCommand(DefVerb.Use, Text: a);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The slot number a hotkey runs for slot <paramref name="slot"/> (1-based).</summary>
|
||||
public static string UseCommand(int slot) => "/rdef use " + slot;
|
||||
|
||||
private static bool TrySlot(string text, out int slot)
|
||||
{
|
||||
slot = 0;
|
||||
return int.TryParse(text.Trim(), out slot) && slot >= 1 && slot <= DefSettings.SlotsMax;
|
||||
}
|
||||
|
||||
private static void SplitSlot(string rest, out string? first, out string tail)
|
||||
{
|
||||
int sp = rest.IndexOf(' ');
|
||||
first = rest.Length == 0 ? null : (sp < 0 ? rest : rest[..sp]);
|
||||
tail = sp < 0 ? string.Empty : rest[(sp + 1)..].Trim();
|
||||
}
|
||||
|
||||
private static DefCommand Fail(string error) => new(DefVerb.Error, Error: error);
|
||||
}
|
||||
146
Plugins/RynthCore.Plugin.RynthDefective/Model/DefData.cs
Normal file
146
Plugins/RynthCore.Plugin.RynthDefective/Model/DefData.cs
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using RynthCore.Plugin.RynthDefective.Items;
|
||||
|
||||
namespace RynthCore.Plugin.RynthDefective.Model;
|
||||
|
||||
/// <summary>One slot of the bar: an item (or nothing) and how pressing it uses that item.</summary>
|
||||
internal sealed class DefSlot
|
||||
{
|
||||
/// <summary>The item the slot holds; null = empty.</summary>
|
||||
public ItemRef? Item;
|
||||
/// <summary>How pressing it uses the item. <see cref="UseMode.Auto"/> picks by what the item is.</summary>
|
||||
public UseMode Mode = UseMode.Auto;
|
||||
|
||||
public bool Empty => Item == null;
|
||||
|
||||
public DefSlot Clone() => new() { Item = Item?.Clone(), Mode = Mode };
|
||||
}
|
||||
|
||||
/// <summary>The "use as" choice of a slot.</summary>
|
||||
internal enum UseMode { Auto, Use, OnSelf, OnSelected, Equip }
|
||||
|
||||
internal static class UseModes
|
||||
{
|
||||
public static readonly string[] Labels =
|
||||
{
|
||||
"Automatic (by item)", "Use it", "Use it on me", "Use it on the selected target", "Wield / wear it",
|
||||
};
|
||||
|
||||
/// <summary>The action for a slot's mode and the item's kind.</summary>
|
||||
public static UseAction ActionFor(UseMode mode, ItemKind kind) => mode switch
|
||||
{
|
||||
UseMode.Use => UseAction.Use,
|
||||
UseMode.OnSelf => UseAction.UseOnSelf,
|
||||
UseMode.OnSelected => UseAction.UseOnSelected,
|
||||
UseMode.Equip => UseAction.Equip,
|
||||
_ => ItemKinds.DefaultAction(kind),
|
||||
};
|
||||
|
||||
public static string Describe(UseAction a) => a switch
|
||||
{
|
||||
UseAction.Use => "used",
|
||||
UseAction.UseOnSelf => "used on you",
|
||||
UseAction.UseOnSelected => "used on the selected target",
|
||||
_ => "wielded",
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>The kind of weapon the picker is narrowed to.</summary>
|
||||
internal enum KindFilter { All, Melee, Missile, War, Void }
|
||||
|
||||
/// <summary>RynthDefective's settings for one character.</summary>
|
||||
internal sealed class DefSettings
|
||||
{
|
||||
public const int SlotsMin = 1, SlotsMax = 24, PerRowMin = 1, PerRowMax = 12, ButtonMin = 20, ButtonMax = 64,
|
||||
PickerIconMin = 20, PickerIconMax = 48;
|
||||
|
||||
/// <summary>
|
||||
/// The shortcut bar (2026-10-22, plugin API v90): its first 18 slots are AC's own (the retail
|
||||
/// toolbar's, its keys AC's keymap), the rest this plugin's own slots (Slots, keys the engine's
|
||||
/// hotkeys). The player picks how many it shows.
|
||||
/// </summary>
|
||||
public const int RetailSlots = 18, BarSlotsMin = 1, BarSlotsMax = RetailSlots + SlotsMax;
|
||||
public int BarSlots = RetailSlots;
|
||||
|
||||
public int SlotCount = 8;
|
||||
public int SlotsPerRow = 8;
|
||||
/// <summary>Icon size of the slot buttons, in logical units.</summary>
|
||||
public int ButtonSize = 36;
|
||||
/// <summary>Icon size in the weapon picker's rows.</summary>
|
||||
public int PickerIconSize = 32;
|
||||
public bool ShowIcons = true;
|
||||
/// <summary>Counts and uses left under the slot buttons.</summary>
|
||||
public bool ShowCounts = true;
|
||||
/// <summary>The weapon kind the picker shows; All = every kind.</summary>
|
||||
public KindFilter PreferredKind = KindFilter.All;
|
||||
/// <summary>Weapon swaps are refused while RynthAi's macro runs (it picks the weapon itself); this lets them through.</summary>
|
||||
public bool SwapWhileBotRuns;
|
||||
public bool BarOpen;
|
||||
public bool PickerOpen;
|
||||
|
||||
public void Clamp()
|
||||
{
|
||||
SlotCount = Math.Clamp(SlotCount, SlotsMin, SlotsMax);
|
||||
BarSlots = Math.Clamp(BarSlots, BarSlotsMin, BarSlotsMax);
|
||||
SlotsPerRow = Math.Clamp(SlotsPerRow, PerRowMin, PerRowMax);
|
||||
ButtonSize = Math.Clamp(ButtonSize, ButtonMin, ButtonMax);
|
||||
PickerIconSize = Math.Clamp(PickerIconSize, PickerIconMin, PickerIconMax);
|
||||
if (!Enum.IsDefined(PreferredKind)) PreferredKind = KindFilter.All;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One character's slots, favourites, recent weapons and settings.</summary>
|
||||
internal sealed class DefData
|
||||
{
|
||||
public const int MaxFavourites = 64, MaxRecent = 8;
|
||||
|
||||
public DefSettings Settings = new();
|
||||
/// <summary>Always <see cref="DefSettings.SlotsMax"/> entries: shrinking the bar hides slots, it doesn't forget them.</summary>
|
||||
public List<DefSlot> Slots = NewSlots();
|
||||
public List<ItemRef> Favourites = new();
|
||||
/// <summary>The weapons wielded from the picker or a slot, newest first.</summary>
|
||||
public List<ItemRef> Recent = new();
|
||||
|
||||
public static List<DefSlot> NewSlots()
|
||||
{
|
||||
var l = new List<DefSlot>(DefSettings.SlotsMax);
|
||||
for (int i = 0; i < DefSettings.SlotsMax; i++) l.Add(new DefSlot());
|
||||
return l;
|
||||
}
|
||||
|
||||
/// <summary>Pads or cuts the slot list to the fixed length.</summary>
|
||||
public void FixLength()
|
||||
{
|
||||
while (Slots.Count < DefSettings.SlotsMax) Slots.Add(new DefSlot());
|
||||
if (Slots.Count > DefSettings.SlotsMax) Slots.RemoveRange(DefSettings.SlotsMax, Slots.Count - DefSettings.SlotsMax);
|
||||
}
|
||||
|
||||
public bool IsFavourite(ItemRef r) => Favourites.Exists(f => f.SameAs(r));
|
||||
|
||||
/// <summary>Adds or removes a favourite; returns whether it is one now.</summary>
|
||||
public bool ToggleFavourite(ItemRef r)
|
||||
{
|
||||
int i = Favourites.FindIndex(f => f.SameAs(r));
|
||||
if (i >= 0) { Favourites.RemoveAt(i); return false; }
|
||||
if (Favourites.Count >= MaxFavourites) return false;
|
||||
Favourites.Add(r.Clone());
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Puts a weapon first in the recent list (once), at most <see cref="MaxRecent"/>.</summary>
|
||||
public void NoteRecent(ItemRef r)
|
||||
{
|
||||
Recent.RemoveAll(x => x.SameAs(r));
|
||||
Recent.Insert(0, r.Clone());
|
||||
if (Recent.Count > MaxRecent) Recent.RemoveRange(MaxRecent, Recent.Count - MaxRecent);
|
||||
}
|
||||
|
||||
/// <summary>The slot (1-based number) that holds an item of this identity, or 0.</summary>
|
||||
public int SlotOf(ItemRef r)
|
||||
{
|
||||
for (int i = 0; i < Slots.Count; i++)
|
||||
if (Slots[i].Item is { } x && x.SameAs(r)) return i + 1;
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
246
Plugins/RynthCore.Plugin.RynthDefective/Model/DefStore.cs
Normal file
246
Plugins/RynthCore.Plugin.RynthDefective/Model/DefStore.cs
Normal file
|
|
@ -0,0 +1,246 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace RynthCore.Plugin.RynthDefective.Model;
|
||||
|
||||
/// <summary>
|
||||
/// Per-character files: <SuiteDir>\RynthDefective\characters\<server_character>.json, written by
|
||||
/// hand and read with JsonDocument (plugin types never go through System.Text.Json's serializer,
|
||||
/// which roots them across hot reloads). A broken or odd file reads as defaults for whatever is
|
||||
/// wrong in it; the next save rewrites it.
|
||||
/// </summary>
|
||||
internal sealed class DefStore
|
||||
{
|
||||
/// <summary>RynthDefective's folder (tests point it at a temp folder).</summary>
|
||||
public string Root;
|
||||
|
||||
public DefStore()
|
||||
{
|
||||
Root = Path.Combine(RynthCore.Install.RynthInstallPaths.SuiteDir, "RynthDefective");
|
||||
}
|
||||
|
||||
public DefStore(string root) => Root = root;
|
||||
|
||||
/// <summary>"server_character" made safe as a file name (the same rule RynthSort and RynthLua use).</summary>
|
||||
public static string FileStem(string server, string character) => SafeFileName($"{server}_{character}");
|
||||
|
||||
public string PathFor(string server, string character) => Path.Combine(Root, "characters", FileStem(server, character) + ".json");
|
||||
|
||||
/// <summary>The character's data; defaults for a new character or a broken file (<paramref name="problem"/> says which).</summary>
|
||||
public DefData Load(string server, string character, out string? problem)
|
||||
{
|
||||
problem = null;
|
||||
string path = PathFor(server, character);
|
||||
if (!File.Exists(path)) return new DefData();
|
||||
try
|
||||
{
|
||||
using JsonDocument doc = JsonDocument.Parse(File.ReadAllBytes(path),
|
||||
new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip });
|
||||
return Parse(doc.RootElement);
|
||||
}
|
||||
catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException or InvalidOperationException)
|
||||
{
|
||||
problem = $"{Path.GetFileName(path)}: {ex.Message}";
|
||||
return new DefData();
|
||||
}
|
||||
}
|
||||
|
||||
internal static DefData Parse(JsonElement root)
|
||||
{
|
||||
if (root.ValueKind != JsonValueKind.Object) throw new JsonException("the file isn't a JSON object");
|
||||
var d = new DefData();
|
||||
|
||||
if (root.TryGetProperty("settings", out JsonElement s) && s.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
DefSettings st = d.Settings;
|
||||
st.SlotCount = Int(s, "slotCount", st.SlotCount);
|
||||
st.BarSlots = Int(s, "barSlots", st.BarSlots);
|
||||
st.SlotsPerRow = Int(s, "slotsPerRow", st.SlotsPerRow);
|
||||
st.ButtonSize = Int(s, "buttonSize", st.ButtonSize);
|
||||
st.PickerIconSize = Int(s, "pickerIconSize", st.PickerIconSize);
|
||||
st.ShowIcons = Bool(s, "showIcons", st.ShowIcons);
|
||||
st.ShowCounts = Bool(s, "showCounts", st.ShowCounts);
|
||||
st.PreferredKind = (KindFilter)Int(s, "preferredKind", (int)st.PreferredKind);
|
||||
st.SwapWhileBotRuns = Bool(s, "swapWhileBotRuns", st.SwapWhileBotRuns);
|
||||
st.BarOpen = Bool(s, "barOpen", st.BarOpen);
|
||||
st.PickerOpen = Bool(s, "pickerOpen", st.PickerOpen);
|
||||
st.Clamp();
|
||||
}
|
||||
|
||||
if (root.TryGetProperty("slots", out JsonElement slots) && slots.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
int i = 0;
|
||||
foreach (JsonElement e in slots.EnumerateArray())
|
||||
{
|
||||
if (i >= DefSettings.SlotsMax) break;
|
||||
DefSlot slot = d.Slots[i++];
|
||||
if (e.ValueKind != JsonValueKind.Object) continue;
|
||||
slot.Item = ParseRef(e, "item");
|
||||
int mode = Int(e, "mode", 0);
|
||||
slot.Mode = mode >= 0 && mode <= (int)UseMode.Equip ? (UseMode)mode : UseMode.Auto;
|
||||
}
|
||||
}
|
||||
ParseRefs(root, "favourites", d.Favourites, DefData.MaxFavourites);
|
||||
ParseRefs(root, "recent", d.Recent, DefData.MaxRecent);
|
||||
return d;
|
||||
}
|
||||
|
||||
private static void ParseRefs(JsonElement root, string name, List<ItemRef> into, int max)
|
||||
{
|
||||
if (!root.TryGetProperty(name, out JsonElement arr) || arr.ValueKind != JsonValueKind.Array) return;
|
||||
foreach (JsonElement e in arr.EnumerateArray())
|
||||
{
|
||||
if (into.Count >= max) break;
|
||||
ItemRef? r = ParseRefObject(e);
|
||||
if (r != null) into.Add(r);
|
||||
}
|
||||
}
|
||||
|
||||
private static ItemRef? ParseRef(JsonElement owner, string name) =>
|
||||
owner.TryGetProperty(name, out JsonElement e) ? ParseRefObject(e) : null;
|
||||
|
||||
private static ItemRef? ParseRefObject(JsonElement e)
|
||||
{
|
||||
if (e.ValueKind != JsonValueKind.Object) return null;
|
||||
string name = Str(e, "name");
|
||||
if (name.Length == 0) return null; // an item with no name can't be found again
|
||||
return new ItemRef
|
||||
{
|
||||
Id = UInt(e, "id"),
|
||||
Name = name,
|
||||
Wcid = UInt(e, "wcid"),
|
||||
Material = Int(e, "material", 0),
|
||||
Icon = UInt(e, "icon"),
|
||||
Underlay = UInt(e, "underlay"),
|
||||
Overlay = UInt(e, "overlay"),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Writes the character's file (temp file, then moved over the old one). Returns an error or null.</summary>
|
||||
public string? Save(string server, string character, DefData d)
|
||||
{
|
||||
string path = PathFor(server, character);
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
string tmp = path + "." + Environment.ProcessId.ToString(CultureInfo.InvariantCulture) + ".tmp";
|
||||
File.WriteAllText(tmp, ToJson(d), new UTF8Encoding(false));
|
||||
File.Move(tmp, path, overwrite: true);
|
||||
return null;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return ex.Message;
|
||||
}
|
||||
}
|
||||
|
||||
internal static string ToJson(DefData d)
|
||||
{
|
||||
using var ms = new MemoryStream();
|
||||
using (var w = new Utf8JsonWriter(ms, new JsonWriterOptions { Indented = true }))
|
||||
{
|
||||
w.WriteStartObject();
|
||||
w.WriteNumber("version", 1);
|
||||
w.WriteStartObject("settings");
|
||||
DefSettings s = d.Settings;
|
||||
w.WriteNumber("slotCount", s.SlotCount);
|
||||
w.WriteNumber("barSlots", s.BarSlots);
|
||||
w.WriteNumber("slotsPerRow", s.SlotsPerRow);
|
||||
w.WriteNumber("buttonSize", s.ButtonSize);
|
||||
w.WriteNumber("pickerIconSize", s.PickerIconSize);
|
||||
w.WriteBoolean("showIcons", s.ShowIcons);
|
||||
w.WriteBoolean("showCounts", s.ShowCounts);
|
||||
w.WriteNumber("preferredKind", (int)s.PreferredKind);
|
||||
w.WriteBoolean("swapWhileBotRuns", s.SwapWhileBotRuns);
|
||||
w.WriteBoolean("barOpen", s.BarOpen);
|
||||
w.WriteBoolean("pickerOpen", s.PickerOpen);
|
||||
w.WriteEndObject();
|
||||
|
||||
w.WriteStartArray("slots");
|
||||
foreach (DefSlot slot in d.Slots)
|
||||
{
|
||||
w.WriteStartObject();
|
||||
if (slot.Item != null) WriteRef(w, "item", slot.Item);
|
||||
w.WriteNumber("mode", (int)slot.Mode);
|
||||
w.WriteEndObject();
|
||||
}
|
||||
w.WriteEndArray();
|
||||
|
||||
w.WriteStartArray("favourites");
|
||||
foreach (ItemRef r in d.Favourites) WriteRefValue(w, r);
|
||||
w.WriteEndArray();
|
||||
w.WriteStartArray("recent");
|
||||
foreach (ItemRef r in d.Recent) WriteRefValue(w, r);
|
||||
w.WriteEndArray();
|
||||
w.WriteEndObject();
|
||||
}
|
||||
return Encoding.UTF8.GetString(ms.ToArray()) + "\n";
|
||||
}
|
||||
|
||||
private static void WriteRef(Utf8JsonWriter w, string name, ItemRef r)
|
||||
{
|
||||
w.WritePropertyName(name);
|
||||
WriteRefValue(w, r);
|
||||
}
|
||||
|
||||
private static void WriteRefValue(Utf8JsonWriter w, ItemRef r)
|
||||
{
|
||||
w.WriteStartObject();
|
||||
w.WriteNumber("id", r.Id);
|
||||
w.WriteString("name", r.Name);
|
||||
if (r.Wcid != 0) w.WriteNumber("wcid", r.Wcid);
|
||||
if (r.Material != 0) w.WriteNumber("material", r.Material);
|
||||
if (r.Icon != 0) w.WriteNumber("icon", r.Icon);
|
||||
if (r.Underlay != 0) w.WriteNumber("underlay", r.Underlay);
|
||||
if (r.Overlay != 0) w.WriteNumber("overlay", r.Overlay);
|
||||
w.WriteEndObject();
|
||||
}
|
||||
|
||||
private static bool Bool(JsonElement o, string name, bool fallback) =>
|
||||
o.TryGetProperty(name, out JsonElement v) && (v.ValueKind == JsonValueKind.True || v.ValueKind == JsonValueKind.False)
|
||||
? v.GetBoolean()
|
||||
: fallback;
|
||||
|
||||
private static string Str(JsonElement o, string name) =>
|
||||
o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? (v.GetString() ?? string.Empty).Trim() : string.Empty;
|
||||
|
||||
private static uint UInt(JsonElement o, string name)
|
||||
{
|
||||
if (!o.TryGetProperty(name, out JsonElement v) || v.ValueKind != JsonValueKind.Number) return 0;
|
||||
if (v.TryGetUInt32(out uint u)) return u;
|
||||
return v.TryGetDouble(out double dbl) && dbl >= 0 && dbl <= uint.MaxValue && dbl == Math.Floor(dbl) ? (uint)dbl : 0;
|
||||
}
|
||||
|
||||
private static int Int(JsonElement o, string name, int fallback)
|
||||
{
|
||||
if (!o.TryGetProperty(name, out JsonElement v) || v.ValueKind != JsonValueKind.Number) return fallback;
|
||||
if (v.TryGetInt32(out int i)) return i;
|
||||
return v.TryGetDouble(out double dbl) && dbl >= int.MinValue && dbl <= int.MaxValue ? (int)Math.Round(dbl) : fallback;
|
||||
}
|
||||
|
||||
private static readonly HashSet<string> ReservedNames = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
"CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$",
|
||||
"COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
|
||||
"LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
|
||||
};
|
||||
|
||||
/// <summary>RynthLua's LibraryStorage.SafeFileName, so the suite names a character's file one way.</summary>
|
||||
public static string SafeFileName(string? name)
|
||||
{
|
||||
var invalid = Path.GetInvalidFileNameChars();
|
||||
var chars = (name ?? string.Empty).Trim().ToCharArray();
|
||||
for (int i = 0; i < chars.Length; i++)
|
||||
if (Array.IndexOf(invalid, chars[i]) >= 0 || chars[i] < 32) chars[i] = '_';
|
||||
string n = new string(chars).TrimEnd('.', ' ');
|
||||
if (n.Length > 80) n = n[..80].TrimEnd('.', ' ');
|
||||
if (n.Length == 0 || n.Trim('.').Length == 0) n = "_" + n;
|
||||
string stem = n.Split('.')[0];
|
||||
if (ReservedNames.Contains(stem)) n = "_" + n;
|
||||
return n;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,93 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
|
||||
namespace RynthCore.Plugin.RynthDefective.Model;
|
||||
|
||||
/// <summary>
|
||||
/// Which keys the engine's hotkey system has bound to a chat command, read from its file
|
||||
/// (%LOCALAPPDATA%\RynthCore\hotkeys.txt, one binding a line: "on|off TAB combo TAB command TAB text",
|
||||
/// the action "command" for a chat command). Read only: the plugin adds and removes bindings by
|
||||
/// typing "/rc hotkey add|remove ..." to the engine, never by writing the file. The file is
|
||||
/// shared by every client on the PC and the engine picks up changes within 2 s, so a binding
|
||||
/// shows here a moment after it was made.
|
||||
/// </summary>
|
||||
internal sealed class HotkeyLookup
|
||||
{
|
||||
public const string EnvOverride = "RYNTHCORE_HOTKEYS_FILE";
|
||||
|
||||
private readonly Func<string> _path;
|
||||
private DateTime _stamp = DateTime.MinValue;
|
||||
private long _nextCheckMs;
|
||||
private List<(string Combo, string Command, bool On)> _bindings = new();
|
||||
|
||||
public HotkeyLookup() : this(DefaultPath) { }
|
||||
public HotkeyLookup(Func<string> path) => _path = path;
|
||||
|
||||
public static string DefaultPath()
|
||||
{
|
||||
if (Environment.GetEnvironmentVariable(EnvOverride) is { Length: > 0 } p) return p;
|
||||
string root = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
|
||||
return Path.Combine(root, "RynthCore", "hotkeys.txt");
|
||||
}
|
||||
|
||||
/// <summary>The combo bound to exactly this chat command ("/rdef use 3"), or null. Looks at the file at most once a second.</summary>
|
||||
public string? KeyFor(string command, long nowMs)
|
||||
{
|
||||
Refresh(nowMs);
|
||||
string want = Normalize(command);
|
||||
foreach (var b in _bindings)
|
||||
if (b.On && b.Command == want) return b.Combo;
|
||||
foreach (var b in _bindings)
|
||||
if (b.Command == want) return b.Combo + " (off)";
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Forget what was read: the next lookup reads the file again.</summary>
|
||||
public void Invalidate() { _stamp = DateTime.MinValue; _nextCheckMs = 0; }
|
||||
|
||||
private void Refresh(long nowMs)
|
||||
{
|
||||
if (nowMs < _nextCheckMs) return;
|
||||
_nextCheckMs = nowMs + 1000;
|
||||
try
|
||||
{
|
||||
string path = _path();
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
_bindings = new();
|
||||
_stamp = DateTime.MinValue;
|
||||
return;
|
||||
}
|
||||
DateTime stamp = File.GetLastWriteTimeUtc(path);
|
||||
if (stamp == _stamp) return;
|
||||
_stamp = stamp;
|
||||
_bindings = Parse(File.ReadAllText(path));
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
// The engine is writing it right now: the old list stays, the next look tries again.
|
||||
}
|
||||
}
|
||||
|
||||
internal static List<(string Combo, string Command, bool On)> Parse(string? text)
|
||||
{
|
||||
var list = new List<(string, string, bool)>();
|
||||
if (string.IsNullOrEmpty(text)) return list;
|
||||
foreach (string raw in text.Split('\n'))
|
||||
{
|
||||
string line = raw.TrimEnd('\r');
|
||||
if (line.Trim().Length == 0 || line.TrimStart().StartsWith('#')) continue;
|
||||
string[] f = line.Split('\t', 4);
|
||||
if (f.Length < 4) continue;
|
||||
if (!f[2].Trim().Equals("command", StringComparison.OrdinalIgnoreCase)) continue;
|
||||
string combo = f[1].Trim();
|
||||
if (combo.Length == 0) continue;
|
||||
list.Add((combo, Normalize(f[3]), !f[0].Trim().Equals("off", StringComparison.OrdinalIgnoreCase)));
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
private static string Normalize(string command) =>
|
||||
string.Join(' ', (command ?? string.Empty).Split(' ', StringSplitOptions.RemoveEmptyEntries)).ToLowerInvariant();
|
||||
}
|
||||
164
Plugins/RynthCore.Plugin.RynthDefective/Model/ItemRef.cs
Normal file
164
Plugins/RynthCore.Plugin.RynthDefective/Model/ItemRef.cs
Normal file
|
|
@ -0,0 +1,164 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using RynthCore.Plugin.RynthDefective.Items;
|
||||
|
||||
namespace RynthCore.Plugin.RynthDefective.Model;
|
||||
|
||||
/// <summary>
|
||||
/// One item identity, as a slot, a favourite or a recent weapon keeps it: the object id it was
|
||||
/// last seen with, and what the item IS (name, wcid, material) so another carried item of the same
|
||||
/// identity can stand in when the object is gone (a used-up kit stack, a replaced weapon). The
|
||||
/// icon ids are the last ones seen, to draw the item dimmed while none is carried.
|
||||
/// </summary>
|
||||
internal sealed class ItemRef
|
||||
{
|
||||
public uint Id;
|
||||
public string Name = string.Empty;
|
||||
public uint Wcid;
|
||||
public int Material;
|
||||
public uint Icon, Underlay, Overlay;
|
||||
|
||||
public static ItemRef From(CarriedItem it)
|
||||
{
|
||||
var r = new ItemRef();
|
||||
r.CopyFrom(it);
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>Takes the item's identity and picture (the slot follows the item it is bound to).</summary>
|
||||
public void CopyFrom(CarriedItem it)
|
||||
{
|
||||
Id = it.Id;
|
||||
Name = it.Name;
|
||||
Wcid = it.Wcid;
|
||||
Material = it.Material;
|
||||
if (it.Icon != 0) { Icon = it.Icon; Underlay = it.Underlay; Overlay = it.Overlay; }
|
||||
}
|
||||
|
||||
public ItemRef Clone() => (ItemRef)MemberwiseClone();
|
||||
|
||||
public string FullName => ItemNames.Full(Name, Material);
|
||||
|
||||
/// <summary>
|
||||
/// Whether <paramref name="it"/> is this item or another of the same kind: the same name (any
|
||||
/// case), and the same wcid and material wherever both sides know them. The id is not part of
|
||||
/// it - that is how a stack that was used up is replaced by the next one.
|
||||
/// </summary>
|
||||
public bool Matches(CarriedItem it)
|
||||
{
|
||||
if (!string.Equals(Name, it.Name, StringComparison.OrdinalIgnoreCase)) return false;
|
||||
if (Wcid != 0 && it.Wcid != 0 && Wcid != it.Wcid) return false;
|
||||
if (Material != 0 && it.Material != 0 && Material != it.Material) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Two references to the same thing (the same id, or the same identity).</summary>
|
||||
public bool SameAs(ItemRef other) =>
|
||||
(Id != 0 && Id == other.Id) || (string.Equals(Name, other.Name, StringComparison.OrdinalIgnoreCase)
|
||||
&& Wcid == other.Wcid && Material == other.Material);
|
||||
}
|
||||
|
||||
/// <summary>What a slot shows: the item it is bound to now, how many of it there are, and its state.</summary>
|
||||
internal readonly record struct SlotStatus(CarriedItem? Item, int Count, int Uses, bool Rebound)
|
||||
{
|
||||
public bool Missing => Item == null;
|
||||
}
|
||||
|
||||
/// <summary>Finding the carried item for a reference, and the counts a slot shows.</summary>
|
||||
internal static class ItemMatcher
|
||||
{
|
||||
/// <summary>
|
||||
/// The carried item for <paramref name="r"/>: the very object when it is still carried (and still
|
||||
/// the same kind of item - an id can be reused), else another item of the same identity:
|
||||
/// not wielded before wielded, then the smaller stack (a used-up stack is gone sooner and the
|
||||
/// pack stays tidier), then the lower id. Null when nothing matches.
|
||||
/// </summary>
|
||||
public static CarriedItem? Find(ItemRef r, IReadOnlyList<CarriedItem> items, out bool rebound)
|
||||
{
|
||||
rebound = false;
|
||||
if (string.IsNullOrEmpty(r.Name)) return null;
|
||||
CarriedItem? best = null;
|
||||
foreach (CarriedItem it in items)
|
||||
{
|
||||
if (!r.Matches(it)) continue;
|
||||
if (it.Id == r.Id) return it;
|
||||
if (best == null || Better(it, best)) best = it;
|
||||
}
|
||||
rebound = best != null;
|
||||
return best;
|
||||
}
|
||||
|
||||
private static bool Better(CarriedItem a, CarriedItem b)
|
||||
{
|
||||
if (a.Wielded != b.Wielded) return !a.Wielded;
|
||||
if (a.Stack != b.Stack) return a.Stack < b.Stack;
|
||||
return a.Id < b.Id;
|
||||
}
|
||||
|
||||
/// <summary>The slot's item, how many of it are carried (stack sizes added up) and the uses left on them all.</summary>
|
||||
public static SlotStatus Status(ItemRef r, IReadOnlyList<CarriedItem> items)
|
||||
{
|
||||
CarriedItem? it = Find(r, items, out bool rebound);
|
||||
if (it == null) return new SlotStatus(null, 0, 0, false);
|
||||
int count = 0, uses = 0;
|
||||
foreach (CarriedItem other in items)
|
||||
{
|
||||
if (!r.Matches(other)) continue;
|
||||
count += Math.Max(1, other.Stack);
|
||||
if (other.MaxUses > 0) uses += Math.Max(0, other.Uses);
|
||||
}
|
||||
return new SlotStatus(it, count, uses, rebound);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Keeps a slot's reference up to date with what is carried: bound to the object found (a
|
||||
/// replacement after the old one is gone), with that object's name, picture and so on. A
|
||||
/// missing item changes nothing. Returns whether the reference changed (the caller saves).
|
||||
/// </summary>
|
||||
public static bool Maintain(ItemRef r, IReadOnlyList<CarriedItem> items)
|
||||
{
|
||||
CarriedItem? it = Find(r, items, out _);
|
||||
if (it == null) return false;
|
||||
uint id = r.Id, icon = r.Icon, under = r.Underlay, over = r.Overlay;
|
||||
int material = r.Material;
|
||||
uint wcid = r.Wcid;
|
||||
r.CopyFrom(it);
|
||||
return id != r.Id || icon != r.Icon || under != r.Underlay || over != r.Overlay || material != r.Material || wcid != r.Wcid;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds an item by what the player typed (/rdef use Peerless Healing Kit): the full name, the
|
||||
/// name, then names that start with the text, then ones that contain it (every word); the
|
||||
/// first by the same order as <see cref="Find"/>.
|
||||
/// </summary>
|
||||
public static CarriedItem? FindByName(string text, IReadOnlyList<CarriedItem> items)
|
||||
{
|
||||
string q = (text ?? string.Empty).Trim();
|
||||
if (q.Length == 0) return null;
|
||||
string[] words = q.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
CarriedItem? best = null;
|
||||
int bestRank = int.MaxValue;
|
||||
foreach (CarriedItem it in items)
|
||||
{
|
||||
int rank = NameRank(it, q, words);
|
||||
if (rank == int.MaxValue) continue;
|
||||
if (best == null || rank < bestRank || (rank == bestRank && Better(it, best)))
|
||||
{
|
||||
best = it;
|
||||
bestRank = rank;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
private static int NameRank(CarriedItem it, string q, string[] words)
|
||||
{
|
||||
string full = it.FullName;
|
||||
if (string.Equals(full, q, StringComparison.OrdinalIgnoreCase)) return 0;
|
||||
if (string.Equals(it.Name, q, StringComparison.OrdinalIgnoreCase)) return 1;
|
||||
if (full.StartsWith(q, StringComparison.OrdinalIgnoreCase) || it.Name.StartsWith(q, StringComparison.OrdinalIgnoreCase)) return 2;
|
||||
foreach (string w in words)
|
||||
if (full.IndexOf(w, StringComparison.OrdinalIgnoreCase) < 0) return int.MaxValue;
|
||||
return 3;
|
||||
}
|
||||
}
|
||||
45
Plugins/RynthCore.Plugin.RynthDefective/Model/PackList.cs
Normal file
45
Plugins/RynthCore.Plugin.RynthDefective/Model/PackList.cs
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using RynthCore.Plugin.RynthDefective.Items;
|
||||
|
||||
namespace RynthCore.Plugin.RynthDefective.Model;
|
||||
|
||||
/// <summary>One line of the "pick from your pack" list: an item kind and how many of it are carried.</summary>
|
||||
internal sealed record PackChoice(CarriedItem Item, int Count);
|
||||
|
||||
internal static class PackList
|
||||
{
|
||||
/// <summary>
|
||||
/// The carried items for a slot to choose from: one line per kind of item (the same name, wcid
|
||||
/// and material), with the stack sizes added up, A-Z, narrowed by the search words (all of them
|
||||
/// must be in the name). At most <paramref name="max"/> lines; <paramref name="total"/> says how many matched.
|
||||
/// </summary>
|
||||
public static List<PackChoice> Build(IReadOnlyList<CarriedItem> items, string search, int max, out int total)
|
||||
{
|
||||
string[] words = (search ?? string.Empty).Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
var byKind = new Dictionary<string, (CarriedItem Rep, int Count)>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (CarriedItem it in items)
|
||||
{
|
||||
string full = it.FullName;
|
||||
bool all = true;
|
||||
foreach (string w in words)
|
||||
if (full.IndexOf(w, StringComparison.OrdinalIgnoreCase) < 0) { all = false; break; }
|
||||
if (!all) continue;
|
||||
string key = $"{full}|{it.Wcid}";
|
||||
if (byKind.TryGetValue(key, out var have))
|
||||
{
|
||||
// The representative: not in hand, then the smaller stack (what a slot would pick).
|
||||
CarriedItem rep = have.Rep;
|
||||
if ((rep.Wielded && !it.Wielded) || (rep.Wielded == it.Wielded && it.Stack < rep.Stack)) rep = it;
|
||||
byKind[key] = (rep, have.Count + Math.Max(1, it.Stack));
|
||||
}
|
||||
else byKind[key] = (it, Math.Max(1, it.Stack));
|
||||
}
|
||||
var list = new List<PackChoice>(byKind.Count);
|
||||
foreach (var kv in byKind) list.Add(new PackChoice(kv.Value.Rep, kv.Value.Count));
|
||||
list.Sort((a, b) => string.Compare(a.Item.FullName, b.Item.FullName, StringComparison.OrdinalIgnoreCase));
|
||||
total = list.Count;
|
||||
if (list.Count > max) list.RemoveRange(max, list.Count - max);
|
||||
return list;
|
||||
}
|
||||
}
|
||||
126
Plugins/RynthCore.Plugin.RynthDefective/Model/WeaponPicker.cs
Normal file
126
Plugins/RynthCore.Plugin.RynthDefective/Model/WeaponPicker.cs
Normal file
|
|
@ -0,0 +1,126 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using RynthCore.Plugin.RynthDefective.Items;
|
||||
|
||||
namespace RynthCore.Plugin.RynthDefective.Model;
|
||||
|
||||
/// <summary>One row of the weapon picker.</summary>
|
||||
internal sealed record PickerRow(CarriedItem Item, WeaponGroup Group, string Element, bool InHand, bool Favourite);
|
||||
|
||||
/// <summary>A picker group: a kind of weapon and the rows under it.</summary>
|
||||
internal sealed record PickerGroup(WeaponGroup Group, List<PickerRow> Rows);
|
||||
|
||||
/// <summary>What the picker shows: favourites and recent weapons first, then every kind.</summary>
|
||||
internal sealed class PickerModel
|
||||
{
|
||||
public List<PickerRow> Favourites = new();
|
||||
public List<PickerRow> Recent = new();
|
||||
public List<PickerGroup> Groups = new();
|
||||
/// <summary>Weapons carried (before the search and kind filter).</summary>
|
||||
public int Total;
|
||||
/// <summary>Rows that passed the search and the kind filter.</summary>
|
||||
public int Shown;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The weapon picker's list, pure: the carried weapons and wands grouped by kind (melee, missile,
|
||||
/// war magic, void magic, then shields and ammunition), narrowed by the search words and the kind
|
||||
/// filter. Favourites and the recently wielded come first, as shortcuts: they are also listed under
|
||||
/// their kind, so a weapon is always where its kind says. Inside a group, A-Z by full name.
|
||||
/// </summary>
|
||||
internal static class WeaponPicker
|
||||
{
|
||||
public static PickerModel Build(IReadOnlyList<CarriedItem> items, IReadOnlyList<ItemRef> favourites,
|
||||
IReadOnlyList<ItemRef> recent, string search, KindFilter filter)
|
||||
{
|
||||
var model = new PickerModel();
|
||||
string[] words = (search ?? string.Empty).Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
|
||||
var rows = new List<PickerRow>();
|
||||
foreach (CarriedItem it in items)
|
||||
{
|
||||
ItemKind kind = ItemKinds.Classify(it);
|
||||
if (ItemKinds.GroupOf(kind) is not { } group) continue;
|
||||
model.Total++;
|
||||
if (!PassesFilter(group, filter)) continue;
|
||||
if (!MatchesSearch(it, group, words)) continue;
|
||||
rows.Add(new PickerRow(it, group, ItemKinds.Element(it), it.Wielded, IsFavourite(it, favourites)));
|
||||
}
|
||||
model.Shown = rows.Count;
|
||||
rows.Sort(CompareRows);
|
||||
|
||||
foreach (WeaponGroup g in Enum.GetValues<WeaponGroup>())
|
||||
{
|
||||
var inGroup = rows.Where(r => r.Group == g).ToList();
|
||||
if (inGroup.Count > 0) model.Groups.Add(new PickerGroup(g, inGroup));
|
||||
}
|
||||
|
||||
// Shortcuts keep their own order: favourites as the player listed them, recent newest first.
|
||||
foreach (ItemRef f in favourites)
|
||||
AddFirstMatch(model.Favourites, rows, f);
|
||||
foreach (ItemRef r in recent)
|
||||
AddFirstMatch(model.Recent, rows, r);
|
||||
return model;
|
||||
}
|
||||
|
||||
private static void AddFirstMatch(List<PickerRow> into, List<PickerRow> rows, ItemRef r)
|
||||
{
|
||||
PickerRow? best = null;
|
||||
foreach (PickerRow row in rows)
|
||||
{
|
||||
if (!r.Matches(row.Item)) continue;
|
||||
if (row.Item.Id == r.Id) { best = row; break; }
|
||||
best ??= row;
|
||||
}
|
||||
if (best != null && !into.Contains(best)) into.Add(best);
|
||||
}
|
||||
|
||||
public static bool IsFavourite(CarriedItem it, IReadOnlyList<ItemRef> favourites)
|
||||
{
|
||||
foreach (ItemRef f in favourites)
|
||||
if (f.Id == it.Id || f.Matches(it)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool PassesFilter(WeaponGroup g, KindFilter f) => f switch
|
||||
{
|
||||
KindFilter.Melee => g == WeaponGroup.Melee,
|
||||
KindFilter.Missile => g == WeaponGroup.Missile || g == WeaponGroup.Ammo,
|
||||
KindFilter.War => g == WeaponGroup.WarMagic,
|
||||
KindFilter.Void => g == WeaponGroup.VoidMagic,
|
||||
_ => true,
|
||||
};
|
||||
|
||||
/// <summary>Every search word is in the weapon's full name, its element or its kind's label.</summary>
|
||||
private static bool MatchesSearch(CarriedItem it, WeaponGroup group, string[] words)
|
||||
{
|
||||
if (words.Length == 0) return true;
|
||||
string full = it.FullName;
|
||||
string element = ItemKinds.Element(it);
|
||||
string label = ItemKinds.Label(group);
|
||||
foreach (string w in words)
|
||||
{
|
||||
if (full.IndexOf(w, StringComparison.OrdinalIgnoreCase) >= 0) continue;
|
||||
if (element.Length > 0 && element.IndexOf(w, StringComparison.OrdinalIgnoreCase) >= 0) continue;
|
||||
if (label.IndexOf(w, StringComparison.OrdinalIgnoreCase) >= 0) continue;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static int CompareRows(PickerRow a, PickerRow b)
|
||||
{
|
||||
int c = string.Compare(a.Item.FullName, b.Item.FullName, StringComparison.OrdinalIgnoreCase);
|
||||
return c != 0 ? c : a.Item.Id.CompareTo(b.Item.Id);
|
||||
}
|
||||
|
||||
public static string KindLabel(KindFilter f) => f switch
|
||||
{
|
||||
KindFilter.Melee => "Melee",
|
||||
KindFilter.Missile => "Missile",
|
||||
KindFilter.War => "War",
|
||||
KindFilter.Void => "Void",
|
||||
_ => "All",
|
||||
};
|
||||
}
|
||||
103
Plugins/RynthCore.Plugin.RynthDefective/PluginExports.cs
Normal file
103
Plugins/RynthCore.Plugin.RynthDefective/PluginExports.cs
Normal file
|
|
@ -0,0 +1,103 @@
|
|||
using System;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using RynthCore.PluginCore;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
namespace RynthCore.Plugin.RynthDefective;
|
||||
|
||||
/// <summary>
|
||||
/// C ABI exports. Nothing may throw out of an [UnmanagedCallersOnly] method (it would take
|
||||
/// acclient.exe down): every export goes through RynthPluginRuntime, which catches and logs.
|
||||
/// RynthDefective draws through the engine's script windows (host calls from its own tick), so it
|
||||
/// exports no render callback and keeps no buffer the engine reads later.
|
||||
/// </summary>
|
||||
public static unsafe class PluginExports
|
||||
{
|
||||
private static readonly RynthPluginRuntime<RynthDefectivePlugin> Runtime = new();
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginInit", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int Init(RynthCoreApiNative* api) => Runtime.Init(api);
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginShutdown", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static void Shutdown() => Runtime.Shutdown();
|
||||
|
||||
// UTF-8 literals live in the module's read-only data: nothing to allocate or free.
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static IntPtr GetName() => LiteralPointer("RynthDefective"u8);
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static IntPtr GetVersion() => LiteralPointer("0.1.0"u8);
|
||||
|
||||
private static IntPtr LiteralPointer(ReadOnlySpan<byte> literal)
|
||||
{
|
||||
fixed (byte* p = literal)
|
||||
return (IntPtr)p;
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginTick", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static void Tick() => Runtime.OnTick();
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLoginComplete", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static void OnLoginComplete() => Runtime.OnLoginComplete();
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnUpdateHealth", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth) =>
|
||||
Runtime.OnUpdateHealth(targetId, healthRatio, currentHealth, maxHealth);
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLogout", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static void OnLogout() => Runtime.OnLogout();
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatBarEnter", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static void OnChatBarEnter(IntPtr textUtf16, IntPtr eatFlag) => Runtime.OnChatBarEnter(textUtf16, eatFlag);
|
||||
|
||||
// ── The shortcut bar's window (plugin API v90; RynthDefectivePlugin.Bar.cs) ──
|
||||
|
||||
private static string? _sectionsJson;
|
||||
private static IntPtr _sectionsPtr;
|
||||
|
||||
/// <summary>The sections manifest (polled every ~2 s): the bar's window. Kept until it changes.</summary>
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginGetSectionsJson", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static IntPtr GetSectionsJson()
|
||||
{
|
||||
try
|
||||
{
|
||||
RynthDefectivePlugin? plugin = Runtime.Plugin;
|
||||
if (plugin == null) return IntPtr.Zero;
|
||||
string json = plugin.SectionsJson();
|
||||
if (json == _sectionsJson && _sectionsPtr != IntPtr.Zero) return _sectionsPtr;
|
||||
_sectionsJson = json;
|
||||
IntPtr fresh = Marshal.StringToCoTaskMemUTF8(json);
|
||||
IntPtr old = System.Threading.Interlocked.Exchange(ref _sectionsPtr, fresh);
|
||||
if (old != IntPtr.Zero) Marshal.FreeCoTaskMem(old);
|
||||
return fresh;
|
||||
}
|
||||
catch { return IntPtr.Zero; }
|
||||
}
|
||||
|
||||
/// <summary>The bar's and the panel buttons' window bodies ("window:bar", "window:panels"; ":popout" when popped out). 1 drawn, 0 not ready, -2 failed.</summary>
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginRenderEmbed", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static int RenderEmbed(byte* surface, float width, float height, float* wantWidth, float* wantHeight)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (surface == null) return 0;
|
||||
string name = Marshal.PtrToStringUTF8((IntPtr)surface) ?? string.Empty;
|
||||
bool popped = name.EndsWith(":popout", StringComparison.Ordinal);
|
||||
if (popped) name = name[..^":popout".Length];
|
||||
RynthDefectivePlugin? plugin = Runtime.Plugin;
|
||||
if (plugin == null) return 0;
|
||||
int result;
|
||||
float wantH;
|
||||
if (name == RynthDefectivePlugin.BarSurface) result = plugin.RenderBar(popped, out wantH);
|
||||
else if (name == RynthDefectivePlugin.PanelsSurface) result = plugin.RenderPanels(out wantH);
|
||||
else if (name == RynthDefectivePlugin.SelectionSurface) result = plugin.RenderSelection(out wantH);
|
||||
else return 0;
|
||||
if (result != 1) return result;
|
||||
if (wantWidth != null) *wantWidth = width;
|
||||
if (wantHeight != null) *wantHeight = wantH > 0 ? wantH : height;
|
||||
return 1;
|
||||
}
|
||||
catch { return 0; }
|
||||
}
|
||||
}
|
||||
93
Plugins/RynthCore.Plugin.RynthDefective/README.md
Normal file
93
Plugins/RynthCore.Plugin.RynthDefective/README.md
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
# RynthDefective
|
||||
|
||||
An item bar for RynthCore with one-touch use, and a fast weapon picker. Version 0.1.0.
|
||||
|
||||
Credit: RynthDefective is an independent implementation of the ideas of **Defective**, the Decal
|
||||
item-bar plugin written by Hazridi and modified by Aun (<https://github.com/aunrela/Defective>). It
|
||||
contains no code from it: it was written from the plugin's public feature description
|
||||
against RynthCore's own APIs. (Defective's repository states no licence; ask Aun if you want a
|
||||
literal port or shared code.)
|
||||
|
||||
## What it does
|
||||
|
||||
**Slots.** The bar is a row (or grid) of slots, each holding one item: a healing kit, a stamina kit,
|
||||
a potion, a scroll, a weapon, a wand, a shield... Click a slot, or press its key, and the item is used
|
||||
**without selecting anything in the game**:
|
||||
|
||||
| Item | What a press does |
|
||||
| --- | --- |
|
||||
| Healing / stamina kit | used on yourself |
|
||||
| Potion, scroll, food, gem, anything else | used (a double-click) |
|
||||
| Weapon, wand, shield, armor, jewelry | wielded / worn (a double-click); an item already in hand is left alone |
|
||||
|
||||
A slot can be set to another way: use it, use it on me, use it on the selected target, or wield it.
|
||||
|
||||
**Put an item in a slot** (Edit slots in the bar): *Set from selected* takes the item you have selected
|
||||
in the game, or *Pick from pack* chooses from a searchable list of what you carry. `/rdef set 3` does the
|
||||
first, `/rdef set 3 Health Potion` the second.
|
||||
|
||||
**A slot keeps the item's identity, not just the object.** It remembers the item's name, wcid and
|
||||
material as well as its object id. When the exact object is gone (a used-up stack, a replaced weapon)
|
||||
the slot uses another carried item of the same identity: not in hand before in hand, the smaller stack
|
||||
first. A slot with nothing to use shows the last picture seen, dimmed, and "none"; it fills itself again
|
||||
when you carry another.
|
||||
|
||||
**Counts.** Under each slot: the uses left on all the kits of that kind (28), the stack count (x120), "in
|
||||
hand" for the weapon you hold, "none" when none is carried, and the slot's key.
|
||||
|
||||
**Keys.** Keys are the engine's hotkeys running `/rdef use <slot>`. Type a key in the slot editor (F9,
|
||||
Ctrl+1, Alt+Shift+Num3) and press *Bind to this slot* (follows the slot) or *Bind to this item* (runs
|
||||
`/rdef use <the item's name>`, works for every character on this PC). The same from chat: `/rdef bind 3 F9`.
|
||||
Any item can also be bound by name straight from Settings > Hotkeys or `/rc hotkey add F9 /rdef use Stamina Kit`.
|
||||
`/rdef use <name>` takes a full name, the start of a name or words in it ("Greater Stamina Kit",
|
||||
"stamina kit"); of several matches the one not in hand, with the smaller stack, then the lower id, is used.
|
||||
|
||||
**The weapon picker** (the *Weapons* button, `/rdef weapons [search]`): every weapon, wand, shield and ammunition
|
||||
stack you carry, as big rows with the item's picture, grouped by kind (melee, missile, war magic, void
|
||||
magic, shields, ammunition), A-Z. Type words in the search box ("fire wand", "axe", "void"); the kind
|
||||
buttons (All, Melee, Missile, War, Void) narrow it, and the one you leave pressed is remembered. The weapon in
|
||||
hand is highlighted. **One click wields.** `+` in front of a row adds a favourite; favourites and the last
|
||||
weapons you wielded are listed first (they are also in their kind's group).
|
||||
|
||||
## Busy, combat and RynthAi
|
||||
|
||||
* One item action at a time: a request waits while the client is busy, a gesture animates, RynthAi waits on
|
||||
the server, or the last action is unanswered (the server's UseDone; a wield is answered by the item
|
||||
reading in hand). Pressing again while one waits does not queue a second; pressing another slot replaces the
|
||||
waiting one. A request not sent within 6 s gives up and says why.
|
||||
* After a wield from a fighting stance the stance follows the weapon (wand: magic, melee weapon: melee,
|
||||
launcher with ammunition in hand: missile) once the character is still. At peace you stay at peace. A bow
|
||||
without arrows in hand returns you to peace rather than leaving a stance it can't use. Shields, armor and
|
||||
rings leave the stance alone.
|
||||
* While RynthAi's macro runs, weapons/wands/shields are **not** wielded (it picks the weapon itself and would
|
||||
swap back) unless *Allow weapon swaps while RynthAi's macro runs* is on. Kits, potions and the rest always work.
|
||||
|
||||
## Commands
|
||||
|
||||
```
|
||||
/rdef show / hide the bar
|
||||
/rdef use <slot | item name> use the slot's item, or the carried item with that name
|
||||
/rdef set <slot> [item name] put the selected item (or the named one) in a slot
|
||||
/rdef clear <slot> empty a slot
|
||||
/rdef bind <slot> <key> bind a key (F9, Ctrl+1 ...) to the slot; /rdef unbind <slot>
|
||||
/rdef weapons [search] show the weapon picker
|
||||
/rdef fav make the selected weapon a favourite (or take it out)
|
||||
/rdef slots <n> how many slots (1-24)
|
||||
/rdef list | status | help
|
||||
```
|
||||
|
||||
## Settings
|
||||
|
||||
Slots (1-24), slots per row, button size, picker row icon size, item icons on/off, counts and keys on/off,
|
||||
allow weapon swaps under RynthAi. Kept per character with the slots, favourites and recent weapons in
|
||||
`<RynthSuite>\RynthDefective\characters\<server>_<character>.json`.
|
||||
|
||||
## Not in 0.1
|
||||
|
||||
Pages, spell slots, arrow auto-equip, gear highlight, summon cooldown counters and the war-magic element
|
||||
changer (Defective has them).
|
||||
|
||||
## Needs
|
||||
|
||||
RynthCore engine API 71 with ImGui for the windows (op level 2 for pictures; text buttons without it).
|
||||
`/rdef use` works on any engine with UseObject.
|
||||
|
|
@ -0,0 +1,64 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!--
|
||||
RynthDefective: an item bar with one-touch use, and a fast weapon picker. Slots hold one
|
||||
item each (a kit, a potion, a weapon...): clicking a slot or pressing its key uses it without
|
||||
selecting anything in the game; a slot that loses its exact item takes another carried item
|
||||
of the same name. The picker lists every carried weapon and wand by kind, with a search box,
|
||||
favourites and the recently used, and wields one with one click. Keys are the engine's
|
||||
hotkeys running /rdef use <slot or item name>; /rdef. An independent implementation of the
|
||||
ideas of Defective, the Decal plugin by Hazridi / Aun (no code from it). UI: the engine's
|
||||
script windows (ImGui), no Avalonia.
|
||||
-->
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows</TargetFramework>
|
||||
<PlatformTarget>x86</PlatformTarget>
|
||||
<RuntimeIdentifier>win-x86</RuntimeIdentifier>
|
||||
<OutputType>Library</OutputType>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<Nullable>enable</Nullable>
|
||||
<PublishAot>true</PublishAot>
|
||||
<NativeLib>Shared</NativeLib>
|
||||
<InvariantGlobalization>true</InvariantGlobalization>
|
||||
<IlcOptimizationPreference>Size</IlcOptimizationPreference>
|
||||
<StripSymbols>false</StripSymbols>
|
||||
<RootNamespace>RynthCore.Plugin.RynthDefective</RootNamespace>
|
||||
<AssemblyName>RynthCore.Plugin.RynthDefective</AssemblyName>
|
||||
<Platforms>x86</Platforms>
|
||||
<!-- Plugin manifest (embedded in the DLL; Plugins\Directory.Build.targets). minEngineApi is the
|
||||
highest API use NOT behind a Has*/version check. Script windows (v71, HasUi, op level 2 for
|
||||
pictures) are checked first; so are the UseDone count (v63), wield/refusal info (v70) and
|
||||
the chat parser the key binding goes through. Below v71 it still uses items (/rdef use). -->
|
||||
<RynthPluginMinEngineApi>66</RynthPluginMinEngineApi>
|
||||
<RynthPluginDescription>Item bar: one-touch use of kits, potions and weapons by slot or key, and a fast weapon picker.</RynthPluginDescription>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- What RynthAi is doing (read only), so a weapon swap stays out of its way. -->
|
||||
<Compile Include="..\Shared\RynthAiActivityApi.cs" Link="Shared\RynthAiActivityApi.cs" />
|
||||
<!-- An older RynthAi without RynthAi.Activity: its RynthAi.Status macro bit instead. -->
|
||||
<Compile Include="..\Shared\RynthAiStatusApi.cs" Link="Shared\RynthAiStatusApi.cs" />
|
||||
<!-- Install-folder resolver (env, HKCU, HKLM, default C:\Games). Read only; same file as RynthCore src\Shared. -->
|
||||
<Compile Include="..\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<!-- The shortcut bar (2026-10-22): drawn with ImGui.NET bound to the engine's cimgui, in the
|
||||
engine's look (Shared\RynthUi; plugin API v90 hosts the frameless window and gives AC's
|
||||
shortcut slots, keys and item pictures). -->
|
||||
<Compile Include="..\Shared\ImGuiNativeBinding.cs" Link="Shared\ImGuiNativeBinding.cs" />
|
||||
<Compile Include="..\Shared\SafeImGui.cs" Link="Shared\SafeImGui.cs" />
|
||||
<Compile Include="..\Shared\RynthUi\RynthUi.cs" Link="Shared\RynthUi\RynthUi.cs" />
|
||||
<Compile Include="..\Shared\RynthUi\RynthIcons.cs" Link="Shared\RynthUi\RynthIcons.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="ImGui.NET" Version="1.91.6.1" />
|
||||
<TrimmerRootAssembly Include="ImGui.NET" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginCore\RynthCore.PluginCore.csproj" />
|
||||
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginSdk\RynthCore.PluginSdk.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
@ -0,0 +1,195 @@
|
|||
// ============================================================================
|
||||
// RynthDefective - RynthDefectivePlugin.Bar.cs
|
||||
// The shortcut bar (2026-10-22), in place of AC's retail toolbar: RynthCore
|
||||
// hosts a frameless window (sections manifest, plugin API v90) and RynthDefective
|
||||
// draws it (ShortcutBar/ShortcutBarWindow.cs). Its first 18 slots are AC's own
|
||||
// (the retail toolbar's items and AC's keys, so both always agree), the rest
|
||||
// this plugin's slots. On an engine without v90's shortcuts the old script
|
||||
// window bar stays.
|
||||
//
|
||||
// The tick: the window's clicks (queued from the render thread), the snapshot
|
||||
// it draws (4 times a second while it shows).
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Globalization;
|
||||
using RynthCore.Plugin.RynthDefective.Model;
|
||||
using RynthCore.Plugin.RynthDefective.ShortcutBar;
|
||||
using RynthCore.Plugin.Shared.RynthUi;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
namespace RynthCore.Plugin.RynthDefective;
|
||||
|
||||
public sealed partial class RynthDefectivePlugin : IBarActions
|
||||
{
|
||||
internal const string BarSurface = "window:bar", PanelsSurface = "window:panels";
|
||||
|
||||
private BarSnapshotBuilder? _barBuilder;
|
||||
private ShortcutBarWindow? _shortcutBar; // render thread
|
||||
private PanelButtonsWindow? _panelButtons; // render thread
|
||||
private int _panelsFailures;
|
||||
private volatile BarSnapshot _barView = BarSnapshot.NotReady; // tick writes, render reads
|
||||
private readonly ConcurrentQueue<Action> _barActions = new();
|
||||
private long _barDrawnMs = long.MinValue / 2, _nextBarBuildMs;
|
||||
private int _barFailures;
|
||||
|
||||
/// <summary>The engine has v90's shortcuts and frameless windows: the new bar, not the script window one.</summary>
|
||||
internal bool UsesShortcutBar => Host.HasShortcuts && Host.HasFramelessWindows;
|
||||
|
||||
/// <summary>AC's panels can be opened from here: the engine has v90's AcPanel (the buttons in the corner).</summary>
|
||||
internal bool UsesPanelButtons => UsesShortcutBar && Host.HasAcPanels;
|
||||
|
||||
/// <summary>The sections manifest: the bar's window and the panel buttons' (only on an engine that has what they need).</summary>
|
||||
internal string SectionsJson()
|
||||
{
|
||||
if (!UsesShortcutBar) return "{\"version\":1}";
|
||||
string bar = "{\"id\":\"bar\",\"title\":\"" + ShortcutBarWindow.Title + "\",\"surface\":\"" + BarSurface +
|
||||
"\",\"icon\":\"\\u" + ((int)RynthIcons.Lightning[0]).ToString("X4", CultureInfo.InvariantCulture) +
|
||||
"\",\"width\":420,\"height\":120,\"minWidth\":90,\"minHeight\":40,\"bar\":true,\"edgeToEdge\":true," +
|
||||
"\"chrome\":\"none\",\"fitHeight\":true,\"scale\":\"draw\"}";
|
||||
// Nine 22-unit buttons and the grip in a row, first in the bottom-right corner.
|
||||
string panels = !UsesPanelButtons ? "" :
|
||||
",{\"id\":\"panels\",\"title\":\"" + PanelButtonsWindow.Title + "\",\"surface\":\"" + PanelsSurface +
|
||||
"\",\"icon\":\"\\u" + ((int)RynthIcons.SquaresFour[0]).ToString("X4", CultureInfo.InvariantCulture) +
|
||||
"\",\"width\":236,\"height\":30,\"minWidth\":30,\"minHeight\":20,\"bar\":false,\"edgeToEdge\":true," +
|
||||
"\"chrome\":\"none\",\"fitHeight\":true,\"corner\":\"bottomRight\",\"scale\":\"draw\"}";
|
||||
// What is selected and its health, first at the top centre.
|
||||
string selection = ",{\"id\":\"selection\",\"title\":\"" + SelectionWindow.Title + "\",\"surface\":\"" + SelectionSurface +
|
||||
"\",\"icon\":\"\\u" + ((int)RynthIcons.Crosshair[0]).ToString("X4", CultureInfo.InvariantCulture) +
|
||||
"\",\"width\":280,\"height\":46,\"minWidth\":120,\"minHeight\":24,\"bar\":false,\"edgeToEdge\":true," +
|
||||
"\"chrome\":\"none\",\"fitHeight\":true,\"corner\":\"top\",\"scale\":\"draw\"}";
|
||||
return "{\"version\":1,\"windows\":[" + bar + panels + selection + "]}";
|
||||
}
|
||||
|
||||
/// <summary>RynthPluginRenderEmbed "window:panels". 1 drawn, 0 not ready, -2 failed (three in a row). Render thread.</summary>
|
||||
internal int RenderPanels(out float wantHeight)
|
||||
{
|
||||
wantHeight = 0;
|
||||
if (!UsesPanelButtons) return 0;
|
||||
try
|
||||
{
|
||||
_panelButtons ??= new PanelButtonsWindow(Host);
|
||||
wantHeight = _panelButtons.Draw();
|
||||
_panelsFailures = 0;
|
||||
return 1;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Host.Log($"[RynthDefective] panel buttons draw failed: {ex.GetType().Name}: {ex.Message}");
|
||||
return ++_panelsFailures >= 3 ? -2 : 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>RynthPluginRenderEmbed "window:bar". 1 drawn, 0 not ready, -2 failed (three in a row). Render thread.</summary>
|
||||
internal int RenderBar(bool popped, out float wantHeight)
|
||||
{
|
||||
wantHeight = 0;
|
||||
if (!UsesShortcutBar) return 0;
|
||||
System.Threading.Volatile.Write(ref _barDrawnMs, Environment.TickCount64);
|
||||
try
|
||||
{
|
||||
_shortcutBar ??= new ShortcutBarWindow(Host, this);
|
||||
wantHeight = _shortcutBar.Draw(_barView, popped);
|
||||
_barFailures = 0;
|
||||
return 1;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Host.Log($"[RynthDefective] shortcut bar draw failed: {ex.GetType().Name}: {ex.Message}");
|
||||
return ++_barFailures >= 3 ? -2 : 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Plugin tick: the bar's clicks, then its snapshot while it shows.</summary>
|
||||
private void TickBar(long now)
|
||||
{
|
||||
while (_barActions.TryDequeue(out Action? act))
|
||||
{
|
||||
try { act(); }
|
||||
catch (Exception ex) { Host.Log($"[RynthDefective] bar action failed: {ex.GetType().Name}: {ex.Message}"); }
|
||||
}
|
||||
if (!UsesShortcutBar || !_identityKnown) return;
|
||||
bool shown = now - System.Threading.Volatile.Read(ref _barDrawnMs) < 2000;
|
||||
if (!shown || now < _nextBarBuildMs) return;
|
||||
_nextBarBuildMs = now + 250;
|
||||
_barBuilder ??= new BarSnapshotBuilder(Host);
|
||||
_barView = _barBuilder.Build(_session, _session.Items(), now);
|
||||
}
|
||||
|
||||
private void QueueBar(Action action)
|
||||
{
|
||||
if (_barActions.Count < 32) _barActions.Enqueue(action);
|
||||
}
|
||||
|
||||
private static bool IsRetail(int number) => number <= DefSettings.RetailSlots;
|
||||
|
||||
// ── IBarActions (render thread: queue only) ─────────────────────────────
|
||||
|
||||
public void Use(int number) => QueueBar(() =>
|
||||
{
|
||||
if (IsRetail(number))
|
||||
{
|
||||
if (!Host.ShortcutAction(RynthShortcutOp.Use, number - 1)) _session.SetStatus($"Slot {number} can't be used now.", warning: true);
|
||||
return;
|
||||
}
|
||||
string? problem = _session.UseSlot(number - DefSettings.RetailSlots);
|
||||
if (problem != null) { _session.SetStatus(problem, warning: true); Print(problem); }
|
||||
});
|
||||
|
||||
public void SetFromSelected(int number) => QueueBar(() =>
|
||||
{
|
||||
if (IsRetail(number))
|
||||
{
|
||||
uint sel = Host.HasGetSelectedItemId ? Host.GetSelectedItemId() : 0;
|
||||
if (sel == 0) { Print("Select the item in the game first, then put it in the slot."); return; }
|
||||
if (!Host.ShortcutAction(RynthShortcutOp.Set, number - 1, sel)) Print($"Slot {number} can't be changed now.");
|
||||
_nextBarBuildMs = 0;
|
||||
return;
|
||||
}
|
||||
Print(_session.SetFromSelected(number - DefSettings.RetailSlots));
|
||||
_nextBarBuildMs = 0;
|
||||
});
|
||||
|
||||
public void Clear(int number) => QueueBar(() =>
|
||||
{
|
||||
if (IsRetail(number))
|
||||
{
|
||||
if (!Host.ShortcutAction(RynthShortcutOp.Clear, number - 1)) Print($"Slot {number} can't be changed now.");
|
||||
_nextBarBuildMs = 0;
|
||||
return;
|
||||
}
|
||||
Print(_session.ClearSlot(number - DefSettings.RetailSlots));
|
||||
_nextBarBuildMs = 0;
|
||||
});
|
||||
|
||||
public void DropItem(int number, uint objectId) => QueueBar(() =>
|
||||
{
|
||||
if (IsRetail(number))
|
||||
{
|
||||
// The retail toolbar's own "make a shortcut": AC checks the item (and says why not).
|
||||
if (!Host.ShortcutAction(RynthShortcutOp.Set, number - 1, objectId)) Print($"Slot {number} can't be changed now.");
|
||||
}
|
||||
else Print(_session.SetFromId(number - DefSettings.RetailSlots, objectId));
|
||||
_nextBarBuildMs = 0;
|
||||
});
|
||||
|
||||
public void ChangeSlotCount(int delta) => QueueBar(() =>
|
||||
{
|
||||
DefSettings st = _session.Settings;
|
||||
st.BarSlots = Math.Clamp(st.BarSlots + delta, DefSettings.BarSlotsMin, DefSettings.BarSlotsMax);
|
||||
RequestSave();
|
||||
_nextBarBuildMs = 0;
|
||||
});
|
||||
|
||||
public void KeysChanged() => QueueBar(() =>
|
||||
{
|
||||
_barBuilder?.InvalidateKeys();
|
||||
_session.Keys.Invalidate();
|
||||
_nextBarBuildMs = 0;
|
||||
});
|
||||
|
||||
public void ShowWeapons() => QueueBar(() => ShowPicker(true));
|
||||
|
||||
public void Hide() => QueueBar(() => Host.SetPanelOpen(ShortcutBarWindow.Title, RynthPanelOpen.Close));
|
||||
}
|
||||
|
|
@ -0,0 +1,120 @@
|
|||
// ============================================================================
|
||||
// RynthDefective - RynthDefectivePlugin.Selection.cs
|
||||
// The Selection window (2026-10-22): what is selected, how far and which way,
|
||||
// and a creature's health, as the retail toolbar showed it
|
||||
// (ShortcutBar/SelectionWindow.cs draws it).
|
||||
//
|
||||
// The tick builds the view 10 times a second: the selected object
|
||||
// (GetSelectedItemId), its name, where it is from the player (positions in
|
||||
// landblock coordinates: 192 units a landblock; the facing from the player's
|
||||
// pose, as RynthAi's combat turns), and its health from AC's health updates
|
||||
// (OnUpdateHealth), asked for when a creature is selected and every 2 s after.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using RynthCore.Plugin.RynthDefective.ShortcutBar;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
namespace RynthCore.Plugin.RynthDefective;
|
||||
|
||||
public sealed partial class RynthDefectivePlugin
|
||||
{
|
||||
internal const string SelectionSurface = "window:selection";
|
||||
|
||||
private SelectionWindow? _selectionWindow; // render thread
|
||||
private volatile SelectionView _selectionView = SelectionView.NotReady;
|
||||
private long _selectionDrawnMs = long.MinValue / 2, _nextSelectionMs, _nextHealthQueryMs;
|
||||
private uint _selectionId;
|
||||
private int _selectionFailures;
|
||||
|
||||
// The last health AC sent for the selected object (game thread writes, tick reads).
|
||||
private volatile HealthSeen? _health;
|
||||
private sealed record HealthSeen(uint Id, float Ratio, uint Current, uint Max);
|
||||
|
||||
private const uint CreatureType = 0x10; // ItemType.Creature
|
||||
|
||||
public override void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth)
|
||||
{
|
||||
if (targetId != 0 && targetId == _selectionId)
|
||||
_health = new HealthSeen(targetId, healthRatio, currentHealth, maxHealth);
|
||||
}
|
||||
|
||||
/// <summary>RynthPluginRenderEmbed "window:selection". 1 drawn, 0 not ready, -2 failed (three in a row). Render thread.</summary>
|
||||
internal int RenderSelection(out float wantHeight)
|
||||
{
|
||||
wantHeight = 0;
|
||||
if (!UsesShortcutBar) return 0;
|
||||
System.Threading.Volatile.Write(ref _selectionDrawnMs, Environment.TickCount64);
|
||||
try
|
||||
{
|
||||
_selectionWindow ??= new SelectionWindow(Host, id => QueueBar(() => { if (!Host.UseObject(id)) Print("That can't be used now."); }));
|
||||
wantHeight = _selectionWindow.Draw(_selectionView);
|
||||
_selectionFailures = 0;
|
||||
return 1;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Host.Log($"[RynthDefective] selection draw failed: {ex.GetType().Name}: {ex.Message}");
|
||||
return ++_selectionFailures >= 3 ? -2 : 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Plugin tick: the selection's view while its window shows.</summary>
|
||||
private void TickSelection(long now)
|
||||
{
|
||||
if (!UsesShortcutBar || !_identityKnown) return;
|
||||
if (now - System.Threading.Volatile.Read(ref _selectionDrawnMs) > 2000 || now < _nextSelectionMs) return;
|
||||
_nextSelectionMs = now + 100;
|
||||
try { _selectionView = BuildSelection(now); }
|
||||
catch (Exception ex) { Host.Log($"[RynthDefective] selection read failed: {ex.GetType().Name}: {ex.Message}"); }
|
||||
}
|
||||
|
||||
private SelectionView BuildSelection(long now)
|
||||
{
|
||||
uint sel = Host.HasGetSelectedItemId ? Host.GetSelectedItemId() : 0;
|
||||
bool changed = sel != _selectionId;
|
||||
_selectionId = sel;
|
||||
if (changed) _health = null;
|
||||
if (sel == 0) return new SelectionView(true, 0, string.Empty, string.Empty, float.NaN, -1f, 0, 0);
|
||||
|
||||
string name = Host.TryGetObjectName(sel, out string n) && n.Length > 0 ? n : $"0x{sel:X8}";
|
||||
bool creature = Host.TryGetItemType(sel, out uint type) && (type & CreatureType) != 0;
|
||||
if (creature && (changed || now >= _nextHealthQueryMs))
|
||||
{
|
||||
_nextHealthQueryMs = now + 2000;
|
||||
Host.QueryHealth(sel);
|
||||
}
|
||||
|
||||
string where = string.Empty;
|
||||
float relative = float.NaN;
|
||||
bool carried = false;
|
||||
foreach (var it in _session.Items()) if (it.Id == sel) { carried = true; break; }
|
||||
if (carried) where = "in your pack";
|
||||
else if (Host.TryGetObjectPosition(sel, out uint oc, out float ox, out float oy, out float oz) && oc != 0
|
||||
&& Host.TryGetPlayerPose(out uint pc, out float px, out float py, out float pz, out float qw, out _, out _, out float qz) && pc != 0)
|
||||
{
|
||||
double dx = Global(oc, ox, true) - Global(pc, px, true), dy = Global(oc, oy, false) - Global(pc, py, false), dz = oz - pz;
|
||||
double dist = Math.Sqrt(dx * dx + dy * dy + dz * dz);
|
||||
double bearing = Math.Atan2(dx, dy) * 180.0 / Math.PI;
|
||||
if (bearing < 0) bearing += 360.0;
|
||||
double facing = ((-2.0 * Math.Atan2(qz, qw) * 180.0 / Math.PI) % 360.0 + 720.0) % 360.0;
|
||||
double rel = bearing - facing;
|
||||
while (rel > 180) rel -= 360;
|
||||
while (rel < -180) rel += 360;
|
||||
if (dist >= 0.5) relative = (float)rel;
|
||||
where = $"{dist.ToString(dist < 10 ? "0.0" : "0", CultureInfo.InvariantCulture)} yd {Compass(bearing)}";
|
||||
}
|
||||
|
||||
HealthSeen? h = _health;
|
||||
float health = h != null && h.Id == sel ? h.Ratio : -1f;
|
||||
return new SelectionView(true, sel, name, where, relative, health, h?.Current ?? 0, h?.Max ?? 0);
|
||||
}
|
||||
|
||||
/// <summary>A landblock coordinate as a world one: 192 units a landblock (the cell's high bytes).</summary>
|
||||
private static double Global(uint cell, float local, bool x) =>
|
||||
((x ? cell >> 24 : cell >> 16) & 0xFF) * 192.0 + local;
|
||||
|
||||
private static readonly string[] Points = { "N", "NE", "E", "SE", "S", "SW", "W", "NW" };
|
||||
private static string Compass(double bearing) => Points[(int)Math.Round(bearing / 45.0) % 8];
|
||||
}
|
||||
429
Plugins/RynthCore.Plugin.RynthDefective/RynthDefectivePlugin.cs
Normal file
429
Plugins/RynthCore.Plugin.RynthDefective/RynthDefectivePlugin.cs
Normal file
|
|
@ -0,0 +1,429 @@
|
|||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using RynthCore.Plugin.RynthDefective.Items;
|
||||
using RynthCore.Plugin.RynthDefective.Model;
|
||||
using RynthCore.Plugin.RynthDefective.Ui;
|
||||
using RynthCore.Plugin.RynthDefective.Use;
|
||||
using RynthCore.Plugin.RynthDefective.Views;
|
||||
using RynthCore.PluginCore;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
namespace RynthCore.Plugin.RynthDefective;
|
||||
|
||||
/// <summary>
|
||||
/// RynthDefective: an item bar with one-touch use, and a fast weapon picker.
|
||||
///
|
||||
/// A slot holds one item identity (Model/ItemRef.cs: the object id, plus name, wcid and material).
|
||||
/// Pressing the slot, or the key the engine's hotkeys bind to "/rdef use N", uses the item without
|
||||
/// anything selected in the game: a kit on yourself, a potion or scroll by itself, a weapon or wand
|
||||
/// wielded (Use/UseController.cs has the rules, the busy handling and the stance). When the exact
|
||||
/// object is gone the slot follows another carried item of the same identity.
|
||||
///
|
||||
/// The weapon picker window lists the carried weapons and wands by kind, with search, favourites and
|
||||
/// the recently wielded, and wields one with one click.
|
||||
///
|
||||
/// Everything runs on the plugin pump (OnTick and the events the engine drains into it) except
|
||||
/// OnChatBarEnter, which the engine may call on AC's thread: it only queues the command.
|
||||
/// </summary>
|
||||
public sealed partial class RynthDefectivePlugin : RynthPluginBase
|
||||
{
|
||||
public const string Version = "0.1.0";
|
||||
private const long IdentityRetryMs = 1000;
|
||||
private const long SaveDelayMs = 750;
|
||||
private const long PassIntervalMs = 400;
|
||||
private const long InventoryAgeMs = 700;
|
||||
|
||||
private readonly DefStore _store = new();
|
||||
private readonly DefSession _session;
|
||||
private readonly UiHost _ui = new();
|
||||
private readonly ConcurrentQueue<string> _commands = new();
|
||||
private HostDefWorld? _world;
|
||||
private BarView? _bar;
|
||||
private PickerView? _picker;
|
||||
private UiWindow? _barWindow, _pickerWindow;
|
||||
|
||||
private bool _inWorld;
|
||||
private bool _identityKnown;
|
||||
private long _nextIdentityTryMs;
|
||||
private string _server = string.Empty;
|
||||
private string _character = string.Empty;
|
||||
private long _saveDueMs;
|
||||
private bool _noUiLogged;
|
||||
private int _revisionSeen = -1;
|
||||
|
||||
public RynthDefectivePlugin()
|
||||
{
|
||||
_session = new DefSession(new HotkeyLookup());
|
||||
}
|
||||
|
||||
public override int Initialize()
|
||||
{
|
||||
_ui.Log = msg => Host.Log(msg);
|
||||
// The shortcut bar (plugin API v90) draws with ImGui.NET bound to the engine's cimgui, in its look.
|
||||
RynthCore.Plugin.Shared.ImGuiNativeBinding.Ensure(msg => Host.Log("[RynthDefective] " + msg));
|
||||
RynthCore.Plugin.Shared.RynthUi.RynthUi.Init(Host);
|
||||
_world = new HostDefWorld(Host);
|
||||
_session.Items = () => _world.Snapshot(InventoryAgeMs);
|
||||
_session.SelectedId = () => Host.HasGetSelectedItemId ? Host.GetSelectedItemId() : 0;
|
||||
_session.RunChat = line => Host.HasInvokeChatParser && Host.InvokeChatParser(line);
|
||||
_session.Save = RequestSave;
|
||||
|
||||
_session.Use.Say = text => { _session.SetStatus(text); Host.Log("[RynthDefective] " + text); };
|
||||
_session.Use.Warn = text => { _session.SetStatus(text, warning: true); Print(text); };
|
||||
_session.Use.Log = line => Host.Log(line);
|
||||
_session.Use.Wielded = OnWielded;
|
||||
|
||||
_bar = new BarView(_session);
|
||||
_picker = new PickerView(_session);
|
||||
_barWindow = _ui.Add(new UiWindow("RynthDefective/Bar", "Defective") { DefaultWidth = 330f, DefaultHeight = 160f, MinWidth = 220f, MinHeight = 100f });
|
||||
_pickerWindow = _ui.Add(new UiWindow("RynthDefective/Weapons", "Defective Weapons") { DefaultWidth = 360f, DefaultHeight = 480f, MinWidth = 260f, MinHeight = 160f });
|
||||
_bar.RequestFit = FitBar;
|
||||
_bar.ShowPicker = () => ShowPicker(true);
|
||||
Host.Log($"[RynthDefective] {Version} initialized. /rdef shows or hides the bar; /rdef use <slot or item name>; /rdef help. Files: {_store.Root}");
|
||||
return 0;
|
||||
}
|
||||
|
||||
// The engine calls this on a real login and on a freshly (re)loaded plugin already in game.
|
||||
public override void OnLoginComplete()
|
||||
{
|
||||
_inWorld = true;
|
||||
_identityKnown = false;
|
||||
_nextIdentityTryMs = Environment.TickCount64;
|
||||
_session.Use.Reset();
|
||||
_world?.Reset();
|
||||
}
|
||||
|
||||
public override void OnLogout()
|
||||
{
|
||||
SaveNow();
|
||||
_inWorld = false;
|
||||
_identityKnown = false;
|
||||
_session.LoggedIn = false;
|
||||
_session.Use.Reset();
|
||||
_world?.Reset();
|
||||
_barView = RynthCore.Plugin.RynthDefective.ShortcutBar.BarSnapshot.NotReady;
|
||||
foreach (UiWindow? w in new[] { _barWindow, _pickerWindow })
|
||||
if (w != null) { w.Visible = false; w.NeedsPass = true; }
|
||||
_ui.SubmitEmpty(Host);
|
||||
}
|
||||
|
||||
public override void Shutdown()
|
||||
{
|
||||
SaveNow();
|
||||
_session.Use.Reset();
|
||||
_ui.SubmitEmpty(Host);
|
||||
}
|
||||
|
||||
// ── Chat ────────────────────────────────────────────────────────────────
|
||||
|
||||
// May run on AC's thread: classify and queue only.
|
||||
public override void OnChatBarEnter(string? text, ref int eat)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(text)) return;
|
||||
string t = text.Trim();
|
||||
if (!t.StartsWith("/rdef", StringComparison.OrdinalIgnoreCase) || (t.Length > 5 && !char.IsWhiteSpace(t[5])))
|
||||
return;
|
||||
eat = 1;
|
||||
_commands.Enqueue(t.Length > 5 ? t.Substring(5).Trim() : string.Empty);
|
||||
}
|
||||
|
||||
private void RunCommand(string arg)
|
||||
{
|
||||
DefCommand c = DefCommandParser.Parse(arg);
|
||||
if (c.Verb == DefVerb.Help)
|
||||
{
|
||||
PrintHelp();
|
||||
return;
|
||||
}
|
||||
if (c.Verb == DefVerb.Error)
|
||||
{
|
||||
Print(c.Error);
|
||||
return;
|
||||
}
|
||||
if (!_identityKnown)
|
||||
{
|
||||
Print("Log in first.");
|
||||
return;
|
||||
}
|
||||
|
||||
switch (c.Verb)
|
||||
{
|
||||
case DefVerb.Toggle:
|
||||
if (UsesShortcutBar)
|
||||
Host.SetPanelOpen(RynthCore.Plugin.RynthDefective.ShortcutBar.ShortcutBarWindow.Title, RynthPanelOpen.Toggle);
|
||||
else if (_barWindow != null) { _barWindow.Visible = !_barWindow.Visible; _barWindow.NeedsPass = true; NoteNoUi(_barWindow.Visible); }
|
||||
break;
|
||||
case DefVerb.Selection when c.Text.Length > 0:
|
||||
if (uint.TryParse(c.Text.Replace("0x", "", StringComparison.OrdinalIgnoreCase), System.Globalization.NumberStyles.HexNumber, null, out uint pick))
|
||||
Host.SelectItem(pick);
|
||||
break;
|
||||
case DefVerb.Selection:
|
||||
if (UsesShortcutBar) Host.SetPanelOpen(RynthCore.Plugin.RynthDefective.ShortcutBar.SelectionWindow.Title, RynthPanelOpen.Toggle);
|
||||
else Print("This RynthCore can't show the selection window (it needs plugin API v90).");
|
||||
break;
|
||||
case DefVerb.Panels:
|
||||
if (UsesPanelButtons) Host.SetPanelOpen(RynthCore.Plugin.RynthDefective.ShortcutBar.PanelButtonsWindow.Title, RynthPanelOpen.Toggle);
|
||||
else Print("This RynthCore can't open the game's panels from buttons (it needs plugin API v90).");
|
||||
break;
|
||||
case DefVerb.Weapons:
|
||||
if (c.Text.Length > 0 && _picker != null) _picker.Search = c.Text;
|
||||
ShowPicker(c.Text.Length > 0 || _pickerWindow?.Visible != true);
|
||||
break;
|
||||
case DefVerb.Use:
|
||||
if (c.Slot > 0)
|
||||
{
|
||||
string? problem = _session.UseSlot(c.Slot);
|
||||
if (problem != null) { _session.SetStatus(problem, warning: true); Print(problem); }
|
||||
}
|
||||
else _session.UseByName(c.Text);
|
||||
break;
|
||||
case DefVerb.Set:
|
||||
Print(c.Text.Length > 0 ? _session.SetFromName(c.Slot, c.Text) : _session.SetFromSelected(c.Slot));
|
||||
break;
|
||||
case DefVerb.Clear:
|
||||
Print(_session.ClearSlot(c.Slot));
|
||||
break;
|
||||
case DefVerb.Bind:
|
||||
Print(_session.BindKey(c.Slot, c.Text, byName: false));
|
||||
break;
|
||||
case DefVerb.Unbind:
|
||||
Print(_session.UnbindKey(c.Slot));
|
||||
break;
|
||||
case DefVerb.Favourite:
|
||||
Print(_session.ToggleSelectedFavourite());
|
||||
break;
|
||||
case DefVerb.Slots:
|
||||
_session.SetSlotCount(c.Slot);
|
||||
FitBar();
|
||||
Print($"{_session.Settings.SlotCount} slots.");
|
||||
break;
|
||||
case DefVerb.List:
|
||||
PrintSlots();
|
||||
break;
|
||||
case DefVerb.Status:
|
||||
PrintStatus();
|
||||
break;
|
||||
}
|
||||
MarkAllForPass();
|
||||
}
|
||||
|
||||
private void PrintHelp()
|
||||
{
|
||||
Print(DefCommandParser.Usage);
|
||||
Print("A key for a slot: /rdef bind 1 F9 (or Edit slots in the bar). Any item by name from Settings > Hotkeys: /rc hotkey add F9 /rdef use Stamina Kit.");
|
||||
}
|
||||
|
||||
private void PrintSlots()
|
||||
{
|
||||
IReadOnlyList<CarriedItem> items = _session.Items();
|
||||
var sb = new StringBuilder();
|
||||
for (int i = 1; i <= _session.Settings.SlotCount; i++)
|
||||
{
|
||||
DefSlot slot = _session.Data.Slots[i - 1];
|
||||
if (slot.Item == null) { Print($"{i}: (empty)"); continue; }
|
||||
SlotStatus s = ItemMatcher.Status(slot.Item, items);
|
||||
sb.Clear();
|
||||
sb.Append(i).Append(": ").Append(slot.Item.FullName);
|
||||
string count = SlotText.Count(s, out _);
|
||||
if (count.Length > 0) sb.Append(" (").Append(count).Append(')');
|
||||
if (_session.KeyOfSlot(i) is { } key) sb.Append(" [").Append(key).Append(']');
|
||||
Print(sb.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
private void PrintStatus()
|
||||
{
|
||||
int filled = 0;
|
||||
for (int i = 0; i < _session.Settings.SlotCount; i++) if (!_session.Data.Slots[i].Empty) filled++;
|
||||
Print($"{_character}: {filled}/{_session.Settings.SlotCount} slots set, {_session.Data.Favourites.Count} favourite weapons; "
|
||||
+ $"{(_session.Use.InFlight ? "an action is in flight" : _session.Use.HasPending ? "an action is waiting" : "idle")}; file {_store.PathFor(_server, _character)}");
|
||||
}
|
||||
|
||||
private void Print(string text)
|
||||
{
|
||||
if (!Host.WriteToChat("[RynthDefective] " + text, 1))
|
||||
Host.Log("[RynthDefective] " + text);
|
||||
}
|
||||
|
||||
private void NoteNoUi(bool shown)
|
||||
{
|
||||
if (shown && !Host.HasUi && !_noUiLogged)
|
||||
{
|
||||
_noUiLogged = true;
|
||||
Print("This RynthCore engine can't show plugin windows (it needs script windows, API v71, with ImGui on). /rdef use <slot or item name> still works.");
|
||||
}
|
||||
}
|
||||
|
||||
// ── Windows ─────────────────────────────────────────────────────────────
|
||||
|
||||
private void ShowPicker(bool visible)
|
||||
{
|
||||
if (_pickerWindow == null) return;
|
||||
_pickerWindow.Visible = visible;
|
||||
_pickerWindow.NeedsPass = true;
|
||||
NoteNoUi(visible);
|
||||
}
|
||||
|
||||
private void FitBar()
|
||||
{
|
||||
if (_barWindow == null || _bar == null) return;
|
||||
(float w, float h) = _bar.WantedSize();
|
||||
_barWindow.RequestWidth = w;
|
||||
_barWindow.RequestHeight = h;
|
||||
_barWindow.NeedsPass = true;
|
||||
}
|
||||
|
||||
private void MarkAllForPass()
|
||||
{
|
||||
if (_barWindow != null) _barWindow.NeedsPass = true;
|
||||
if (_pickerWindow != null) _pickerWindow.NeedsPass = true;
|
||||
}
|
||||
|
||||
/// <summary>A weapon (or shield) went into the hands: first in the picker's recent list.</summary>
|
||||
private void OnWielded(CarriedItem it)
|
||||
{
|
||||
ItemKind kind = ItemKinds.Classify(it);
|
||||
if (!ItemKinds.IsWeapon(kind) && kind != ItemKind.Shield) return;
|
||||
_session.Data.NoteRecent(ItemRef.From(it));
|
||||
RequestSave();
|
||||
}
|
||||
|
||||
// ── Tick ────────────────────────────────────────────────────────────────
|
||||
|
||||
public override void OnTick()
|
||||
{
|
||||
long now = Environment.TickCount64;
|
||||
while (_commands.TryDequeue(out string? cmd))
|
||||
{
|
||||
try { RunCommand(cmd); }
|
||||
catch (Exception ex) { Host.Log($"[RynthDefective] /rdef {cmd} failed: {ex.GetType().Name}: {ex.Message}"); }
|
||||
}
|
||||
_ui.Poll(Host);
|
||||
|
||||
if (_inWorld)
|
||||
{
|
||||
if (!_identityKnown && now >= _nextIdentityTryMs) TryStartCharacter(now);
|
||||
if (_identityKnown && _world != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
TickInventory();
|
||||
_session.Use.Tick(_world);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Host.Log($"[RynthDefective] tick failed: {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
if (_saveDueMs != 0 && now >= _saveDueMs) SaveNow();
|
||||
TickBar(now);
|
||||
TickSelection(now);
|
||||
|
||||
// With the shortcut bar the old script-window bar stays shut (the weapon picker is still one).
|
||||
if (UsesShortcutBar && _barWindow != null && _barWindow.Visible) { _barWindow.Visible = false; _barWindow.NeedsPass = true; }
|
||||
|
||||
if (!Host.HasUi || _barWindow == null || _pickerWindow == null || _bar == null || _picker == null) return;
|
||||
if (_session.Use.HasPending || _session.Use.InFlight) _barWindow.NeedsPass = _pickerWindow.NeedsPass = true;
|
||||
if (!_session.IconsAvailable) RefreshIconSupport();
|
||||
Record(_barWindow, now, _bar.Draw);
|
||||
Record(_pickerWindow, now, _picker.Draw);
|
||||
_ui.Submit(Host, now);
|
||||
|
||||
if (_identityKnown)
|
||||
{
|
||||
DefSettings st = _session.Settings;
|
||||
if (_barWindow.Visible != st.BarOpen || _pickerWindow.Visible != st.PickerOpen)
|
||||
{
|
||||
st.BarOpen = _barWindow.Visible;
|
||||
st.PickerOpen = _pickerWindow.Visible;
|
||||
RequestSave();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Re-reads the inventory while a window shows or an action waits; slots follow their items.</summary>
|
||||
private void TickInventory()
|
||||
{
|
||||
bool barShown = Environment.TickCount64 - System.Threading.Volatile.Read(ref _barDrawnMs) < 2000;
|
||||
bool wanted = (_barWindow?.Visible ?? false) || (_pickerWindow?.Visible ?? false) || barShown || _session.Use.HasPending;
|
||||
if (!wanted || _world == null) return;
|
||||
List<CarriedItem> items = _world.Snapshot(InventoryAgeMs);
|
||||
if (_world.Revision == _revisionSeen) return;
|
||||
_revisionSeen = _world.Revision;
|
||||
if (_session.Maintain(items)) RequestSave();
|
||||
MarkAllForPass();
|
||||
}
|
||||
|
||||
private void TryStartCharacter(long now)
|
||||
{
|
||||
_nextIdentityTryMs = now + IdentityRetryMs;
|
||||
uint player = Host.GetPlayerId();
|
||||
if (player == 0 || !Host.TryGetObjectName(player, out string name) || string.IsNullOrWhiteSpace(name)) return;
|
||||
string server = Host.TryGetWorldName(out string w) ? w : string.Empty;
|
||||
|
||||
_server = server;
|
||||
_character = name;
|
||||
DefData data = _store.Load(server, name, out string? problem);
|
||||
if (problem != null) Host.Log($"[RynthDefective] couldn't read the saved slots ({problem}); using defaults.");
|
||||
_session.Data = data;
|
||||
_session.Use.Settings = data.Settings;
|
||||
_session.Character = name;
|
||||
_session.LoggedIn = true;
|
||||
_identityKnown = true;
|
||||
_revisionSeen = -1;
|
||||
RefreshIconSupport();
|
||||
if (_barWindow != null && _bar != null)
|
||||
{
|
||||
_barWindow.Visible = data.Settings.BarOpen;
|
||||
(float bw, float bh) = _bar.WantedSize();
|
||||
_barWindow.DefaultWidth = bw;
|
||||
_barWindow.DefaultHeight = bh;
|
||||
_barWindow.NeedsPass = true;
|
||||
}
|
||||
if (_pickerWindow != null) { _pickerWindow.Visible = data.Settings.PickerOpen; _pickerWindow.NeedsPass = true; }
|
||||
Host.Log($"[RynthDefective] item bar for {name} on {server}: {data.Slots.FindAll(s => !s.Empty).Count} slots set; file {_store.PathFor(server, name)}");
|
||||
}
|
||||
|
||||
private void RefreshIconSupport()
|
||||
{
|
||||
_session.IconsAvailable = Host.HasUi && Host.TryGetUiInfo(out UiInfoNative info) && info.OpLevel >= 2;
|
||||
}
|
||||
|
||||
private void RequestSave()
|
||||
{
|
||||
MarkAllForPass();
|
||||
if (_saveDueMs == 0) _saveDueMs = Environment.TickCount64 + SaveDelayMs;
|
||||
}
|
||||
|
||||
private void SaveNow()
|
||||
{
|
||||
_saveDueMs = 0;
|
||||
if (!_identityKnown) return;
|
||||
_session.Settings.Clamp();
|
||||
string? error = _store.Save(_server, _character, _session.Data);
|
||||
if (error != null) Host.Log("[RynthDefective] save failed: " + error);
|
||||
}
|
||||
|
||||
/// <summary>A pass when one is wanted, or on the refresh interval while visible (counts and the status tick on).</summary>
|
||||
private void Record(UiWindow w, long now, Action<UiWindow> draw)
|
||||
{
|
||||
bool due = w.NeedsPass || (w.Visible && now >= w.NextPassMs);
|
||||
if (!due) return;
|
||||
w.NeedsPass = false;
|
||||
w.NextPassMs = now + PassIntervalMs;
|
||||
w.Begin();
|
||||
try
|
||||
{
|
||||
draw(w);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
w.TextWrapped($"Something went wrong drawing this window: {ex.GetType().Name}: {ex.Message}");
|
||||
Host.Log($"[RynthDefective] {w.Key} pass failed: {ex}");
|
||||
}
|
||||
w.End();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,148 @@
|
|||
// ============================================================================
|
||||
// RynthDefective - ShortcutBar/BarSnapshot.cs
|
||||
// What the shortcut bar shows, built on the plugin tick (BarSnapshotBuilder)
|
||||
// and drawn on the render thread (ShortcutBarWindow): one immutable record per
|
||||
// slot, swapped whole.
|
||||
//
|
||||
// Slots 1-18 are AC's own shortcut slots (RynthCoreHost.GetShortcuts, plugin
|
||||
// API v90): the items the retail toolbar holds, the keys AC's keymap gives
|
||||
// UseQuickSlot_1-18. Slots 19 and on are this plugin's own (DefData.Slots),
|
||||
// their keys the engine's hotkeys (/rdef use N). The player chooses how many
|
||||
// the bar shows (DefSettings.BarSlots).
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using RynthCore.Plugin.RynthDefective.Items;
|
||||
using RynthCore.Plugin.RynthDefective.Model;
|
||||
using RynthCore.Plugin.RynthDefective.Views;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
namespace RynthCore.Plugin.RynthDefective.ShortcutBar;
|
||||
|
||||
/// <summary>How a slot's count line reads: plain, in hand / worn, or nothing carried.</summary>
|
||||
internal enum CountTone { Plain, InHand, Missing }
|
||||
|
||||
/// <summary>One slot as drawn.</summary>
|
||||
internal sealed record BarSlot(
|
||||
int Number,
|
||||
bool Retail,
|
||||
uint ObjectId,
|
||||
uint SpellId,
|
||||
string Name,
|
||||
string Count,
|
||||
CountTone Tone,
|
||||
string Key,
|
||||
string AllKeys,
|
||||
string Tooltip)
|
||||
{
|
||||
public bool Empty => ObjectId == 0 && SpellId == 0 && Name.Length == 0;
|
||||
}
|
||||
|
||||
internal sealed record BarSnapshot(BarSlot[] Slots, bool Ready, int IconSize)
|
||||
{
|
||||
public static readonly BarSnapshot NotReady = new(Array.Empty<BarSlot>(), false, 36);
|
||||
}
|
||||
|
||||
/// <summary>Builds the snapshot on the plugin tick (reads the host and the carried items).</summary>
|
||||
internal sealed class BarSnapshotBuilder
|
||||
{
|
||||
private readonly RynthCoreHost _host;
|
||||
private readonly uint[] _ids = new uint[DefSettings.RetailSlots], _spells = new uint[DefSettings.RetailSlots];
|
||||
private readonly string[] _keys = new string[DefSettings.RetailSlots];
|
||||
private long _keysReadMs = long.MinValue / 2, _fastKeysUntilMs;
|
||||
|
||||
public BarSnapshotBuilder(RynthCoreHost host)
|
||||
{
|
||||
_host = host;
|
||||
Array.Fill(_keys, string.Empty);
|
||||
}
|
||||
|
||||
/// <summary>A key was changed from the bar: ask again often for a few seconds (the change is made on the game's tick).</summary>
|
||||
public void InvalidateKeys()
|
||||
{
|
||||
_keysReadMs = long.MinValue / 2;
|
||||
_fastKeysUntilMs = Environment.TickCount64 + 4000;
|
||||
}
|
||||
|
||||
/// <summary>AC's keys for the 18 retail slots (re-asked every 2 s: the keymap can change, from any client).</summary>
|
||||
private void RefreshKeys(long now)
|
||||
{
|
||||
if (now - _keysReadMs < (now < _fastKeysUntilMs ? 250 : 2000)) return;
|
||||
_keysReadMs = now;
|
||||
for (int i = 0; i < _keys.Length; i++) _keys[i] = _host.GetActionKeys("UseQuickSlot_" + (i + 1));
|
||||
}
|
||||
|
||||
public BarSnapshot Build(DefSession session, IReadOnlyList<CarriedItem> items, long now)
|
||||
{
|
||||
if (!_host.HasShortcuts || _host.GetShortcuts(_ids, _spells) == 0) return BarSnapshot.NotReady;
|
||||
RefreshKeys(now);
|
||||
DefSettings st = session.Settings;
|
||||
var byId = new Dictionary<uint, CarriedItem>(items.Count);
|
||||
foreach (CarriedItem it in items) byId[it.Id] = it;
|
||||
|
||||
var slots = new BarSlot[st.BarSlots];
|
||||
for (int n = 1; n <= st.BarSlots; n++)
|
||||
slots[n - 1] = n <= DefSettings.RetailSlots ? Retail(n, byId) : Own(n, session, items, _host);
|
||||
return new BarSnapshot(slots, true, st.ButtonSize);
|
||||
}
|
||||
|
||||
private BarSlot Retail(int n, Dictionary<uint, CarriedItem> byId)
|
||||
{
|
||||
uint id = _ids[n - 1], spell = _spells[n - 1];
|
||||
string allKeys = _keys[n - 1];
|
||||
string key = FirstKey(allKeys);
|
||||
if (id == 0 && spell == 0)
|
||||
return new BarSlot(n, true, 0, 0, string.Empty, string.Empty, CountTone.Plain, key, allKeys,
|
||||
$"Slot {n} (the game's own): empty.{KeysLine(allKeys)}\nRight-click: put the selected item here, or change its keys.");
|
||||
string name;
|
||||
string count = string.Empty;
|
||||
CountTone tone = CountTone.Plain;
|
||||
if (id != 0 && byId.TryGetValue(id, out CarriedItem? it))
|
||||
{
|
||||
name = it.FullName;
|
||||
count = SlotText.Count(new SlotStatus(it, it.Stack, it.Uses, false), out uint color);
|
||||
tone = color == SlotText.InHand ? CountTone.InHand : color == SlotText.Missing ? CountTone.Missing : CountTone.Plain;
|
||||
}
|
||||
else if (id != 0)
|
||||
{
|
||||
name = _host.TryGetObjectName(id, out string n2) && n2.Length > 0 ? n2 : $"0x{id:X8}";
|
||||
count = "none";
|
||||
tone = CountTone.Missing;
|
||||
}
|
||||
else name = $"Spell {spell}";
|
||||
string tip = $"Slot {n} (the game's own): {name}{(count.Length > 0 ? " - " + count : "")}.{KeysLine(allKeys)}\n" +
|
||||
"Click: use it, as its key does. Right-click: change the slot or its keys.";
|
||||
return new BarSlot(n, true, id, id == 0 ? spell : 0, name, count, tone, key, allKeys, tip);
|
||||
}
|
||||
|
||||
private static BarSlot Own(int n, DefSession session, IReadOnlyList<CarriedItem> items, RynthCoreHost host)
|
||||
{
|
||||
int own = n - DefSettings.RetailSlots;
|
||||
DefSlot slot = own <= session.Data.Slots.Count ? session.Data.Slots[own - 1] : new DefSlot();
|
||||
// Every key of "/rdef use N" (the engine's hotkeys), else the one bound to the item by name.
|
||||
string all = host.HasKeyBinding ? host.GetActionKeys(DefCommandParser.UseCommand(own)) : string.Empty;
|
||||
string key = all.Length > 0 ? FirstKey(all) : session.KeyOfSlot(own) ?? string.Empty;
|
||||
if (all.Length == 0) all = key;
|
||||
if (slot.Item == null)
|
||||
return new BarSlot(n, false, 0, 0, string.Empty, string.Empty, CountTone.Plain, SlotText.ShortKey(key), all,
|
||||
$"Slot {n} (RynthCore's: the game holds 18): empty.{KeysLine(all)}\nRight-click: put the selected item here, or change its keys.");
|
||||
SlotStatus s = ItemMatcher.Status(slot.Item, items);
|
||||
string count = SlotText.Count(s, out uint color);
|
||||
CountTone tone = color == SlotText.InHand ? CountTone.InHand : color == SlotText.Missing ? CountTone.Missing : CountTone.Plain;
|
||||
string tip = SlotText.Tooltip(n, slot.Item, s, slot.Mode, key.Length > 0 ? key : null)
|
||||
+ "\n(RynthCore's slot: the game's toolbar holds 18.)";
|
||||
return new BarSlot(n, false, s.Item?.Id ?? 0, 0, s.Item?.FullName ?? slot.Item.FullName, count, tone,
|
||||
SlotText.ShortKey(key), all, tip);
|
||||
}
|
||||
|
||||
/// <summary>The first of "1, Ctrl+1": what fits on the slot.</summary>
|
||||
private static string FirstKey(string keys)
|
||||
{
|
||||
int comma = keys.IndexOf(',');
|
||||
return comma < 0 ? keys : keys[..comma];
|
||||
}
|
||||
|
||||
private static string KeysLine(string keys) => keys.Length > 0 ? "\nKeys: " + keys : "\nNo key yet.";
|
||||
}
|
||||
|
|
@ -0,0 +1,155 @@
|
|||
// ============================================================================
|
||||
// RynthDefective - ShortcutBar/PanelButtonsWindow.cs
|
||||
// Tiny buttons for AC's own panels, in the bottom-right corner (Tom
|
||||
// 2026-10-22: with the retail toolbar hidden, its panel buttons go with it).
|
||||
// RynthCore hosts the frameless window (sections manifest "corner":
|
||||
// "bottomRight", plugin API v90) and opens and closes the panels the way AC's
|
||||
// toolbar and keys do (RynthCoreHost.AcPanel): one main panel at a time.
|
||||
//
|
||||
// grip the dots on the left: drag the strip; Ctrl+wheel: bigger or
|
||||
// smaller; right-click: hide it (/rdef panels shows it again).
|
||||
// buttons the pack, attributes & skills, the spellbook, fellowship &
|
||||
// allegiance, the map, quests, spells on you, character info,
|
||||
// options. Lit while their panel is open. They fill the window's
|
||||
// width and wrap: drag it narrow for a column.
|
||||
//
|
||||
// AC's render thread; the panel calls are queued by the engine.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Numerics;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.Plugin.Shared.RynthUi;
|
||||
using RynthCore.PluginSdk;
|
||||
using static RynthCore.Plugin.Shared.RynthUi.RynthUi;
|
||||
|
||||
namespace RynthCore.Plugin.RynthDefective.ShortcutBar;
|
||||
|
||||
internal sealed class PanelButtonsWindow
|
||||
{
|
||||
public const string Title = "Game Panels";
|
||||
|
||||
private readonly RynthCoreHost _host;
|
||||
private float _k = 1f, _r = 1f;
|
||||
|
||||
public PanelButtonsWindow(RynthCoreHost host) => _host = host;
|
||||
|
||||
private readonly record struct Button(RynthAcPanel Panel, string Icon, string Tip);
|
||||
|
||||
private static readonly Button[] Buttons =
|
||||
[
|
||||
new(RynthAcPanel.Inventory, RynthIcons.Backpack, "Pack"),
|
||||
new(RynthAcPanel.Character, RynthIcons.User, "Attributes and skills"),
|
||||
new(RynthAcPanel.Spellbook, RynthIcons.MagicWand, "Spellbook"),
|
||||
new(RynthAcPanel.Social, RynthIcons.UsersThree, "Fellowship, allegiance and friends"),
|
||||
new(RynthAcPanel.Map, RynthIcons.MapTrifold, "Map"),
|
||||
new(RynthAcPanel.Quests, RynthIcons.Scroll, "Contracts and journal"),
|
||||
new(RynthAcPanel.HelpfulSpells, RynthIcons.Sparkle, "Spells on you"),
|
||||
new(RynthAcPanel.CharacterInfo, RynthIcons.Info, "Character information"),
|
||||
new(RynthAcPanel.Options, RynthIcons.Gear, "Options"),
|
||||
];
|
||||
|
||||
private const float Pad = 4, Cell = 22, Gap = 2, GripW = 9, Radius = 4;
|
||||
|
||||
private float Px(float v) => v * _k;
|
||||
|
||||
/// <summary>
|
||||
/// The layout's scale and the text's against the baked font: the window's own size (Settings > UI >
|
||||
/// Toolbar, Ctrl+wheel: 30-250%, PanelScale) or, unset, the text size the engine baked for it.
|
||||
/// </summary>
|
||||
private void Scale()
|
||||
{
|
||||
float fontK = Math.Max(0.5f, Font(RynthUiFont.Ui10).FontSize / 10f);
|
||||
int pct = _host.PanelScale(Title);
|
||||
_k = pct > 0 ? pct / 100f : fontK;
|
||||
_r = _k / fontK;
|
||||
}
|
||||
|
||||
private uint _bg, _key, _line, _text, _faint, _accent;
|
||||
private static uint A(uint c, float alpha) => WithAlpha(c, (uint)Math.Clamp(MathF.Round(alpha * 255f), 0f, 255f));
|
||||
|
||||
/// <summary>Draws the strip into the host's window; returns the height it needs (pixels). Render thread.</summary>
|
||||
public float Draw()
|
||||
{
|
||||
Scale();
|
||||
_bg = Color(RynthUiColor.Background);
|
||||
_key = Color(RynthUiColor.KeyFace);
|
||||
_line = Color(RynthUiColor.Hairline);
|
||||
_text = Color(RynthUiColor.Text);
|
||||
_faint = Color(RynthUiColor.Faint);
|
||||
_accent = Color(RynthUiColor.Accent);
|
||||
|
||||
Vector2 origin = ImGui.GetCursorScreenPos();
|
||||
origin = new Vector2(MathF.Round(origin.X), MathF.Round(origin.Y));
|
||||
float width = MathF.Floor(ImGui.GetContentRegionAvail().X);
|
||||
if (width < 20) return Px(Cell + 2 * Pad);
|
||||
ImDrawListPtr dl = ImGui.GetWindowDrawList();
|
||||
|
||||
float cell = Px(Cell), gap = Px(Gap), pad = Px(Pad), grip = Px(GripW);
|
||||
float room = width - 2 * pad - grip - gap;
|
||||
int perRow = Math.Max(1, (int)MathF.Floor((room + gap) / (cell + gap)));
|
||||
int rows = (Buttons.Length + perRow - 1) / perRow;
|
||||
float height = MathF.Ceiling(2 * pad + rows * cell + (rows - 1) * gap);
|
||||
|
||||
// The frame, as the shortcut bar's.
|
||||
Vector2 max = origin + new Vector2(width, height);
|
||||
dl.AddRectFilled(origin, max, A(_bg, 0.94f), Px(Radius));
|
||||
dl.AddRect(origin, max, _line, Px(Radius));
|
||||
|
||||
// The grip: drag, Ctrl+wheel, right-click to hide.
|
||||
Vector2 gp = origin + new Vector2(pad, pad);
|
||||
ImGui.SetCursorScreenPos(gp);
|
||||
ImGui.InvisibleButton("##gp_grip", new Vector2(grip, height - 2 * pad));
|
||||
_host.PanelDragWithLastItem();
|
||||
bool gripHot = ImGui.IsItemHovered();
|
||||
if (ImGui.IsItemClicked(ImGuiMouseButton.Right)) _host.SetPanelOpen(Title, RynthPanelOpen.Close);
|
||||
SafeImGui.SetItemTooltip("Drag to move. Ctrl+wheel: bigger or smaller. Right-click: hide (/rdef panels shows it again).\nDrag the window's edge narrower for a column.");
|
||||
DrawIcon(dl, RynthIcons.DotsSixVertical, gp, new Vector2(grip, height - 2 * pad), Px(11), gripHot ? _text : _faint);
|
||||
|
||||
float x0 = gp.X + grip + gap;
|
||||
for (int i = 0; i < Buttons.Length; i++)
|
||||
{
|
||||
int col = i % perRow, row = i / perRow;
|
||||
Vector2 p = new(MathF.Round(x0 + col * (cell + gap)), MathF.Round(origin.Y + pad + row * (cell + gap)));
|
||||
DrawButton(dl, Buttons[i], p, cell);
|
||||
}
|
||||
|
||||
ImGui.SetCursorScreenPos(origin);
|
||||
ImGui.Dummy(new Vector2(width, height));
|
||||
return height;
|
||||
}
|
||||
|
||||
private void DrawButton(ImDrawListPtr dl, in Button b, Vector2 p, float cell)
|
||||
{
|
||||
Vector2 size = new(cell, cell);
|
||||
ImGui.SetCursorScreenPos(p);
|
||||
bool clicked = ImGui.InvisibleButton("##gp_" + (int)b.Panel, size);
|
||||
bool hot = ImGui.IsItemHovered();
|
||||
bool? open = _host.IsAcPanelOpen(b.Panel);
|
||||
SafeImGui.SetItemTooltip(open == null ? b.Tip + " (not in this client)" : b.Tip + (open == true ? " - open: click to close" : ""));
|
||||
float r = Px(3);
|
||||
if (hot || open == true) dl.AddRectFilled(p, p + size, _key, r);
|
||||
if (open == true) dl.AddLine(new Vector2(p.X + Px(4), p.Y + cell - Px(1.5f)), new Vector2(p.X + cell - Px(4), p.Y + cell - Px(1.5f)), _accent, Px(1.5f));
|
||||
uint color = open == null ? A(_faint, 0.5f) : open == true ? _accent : hot ? _text : A(_text, 0.72f);
|
||||
DrawIcon(dl, b.Icon, p, size, Px(14), color);
|
||||
if (clicked && open != null) _host.AcPanel(b.Panel, RynthAcPanelOp.Toggle);
|
||||
}
|
||||
|
||||
/// <summary>A Phosphor glyph centred in the box, <paramref name="px"/> across its em (from Ui18's bake).</summary>
|
||||
private static unsafe void DrawIcon(ImDrawListPtr dl, string glyph, Vector2 min, Vector2 size, float px, uint color)
|
||||
{
|
||||
if (string.IsNullOrEmpty(glyph)) return;
|
||||
ImFontPtr font = Font(RynthUiFont.Ui18);
|
||||
if (font.NativePtr == null) return;
|
||||
byte* g = (byte*)ImGuiNative.ImFont_FindGlyphNoFallback(font.NativePtr, glyph[0]);
|
||||
if (g == null) return;
|
||||
float advance = *(float*)(g + 4);
|
||||
if (advance <= 0) return;
|
||||
float* box = (float*)(g + 8);
|
||||
float scale = px / advance;
|
||||
Vector2 centre = new((box[0] + box[2]) * 0.5f * scale, (box[1] + box[3]) * 0.5f * scale);
|
||||
Vector2 at = min + size * 0.5f - centre;
|
||||
dl.AddText(font, font.FontSize * scale, new Vector2(MathF.Round(at.X), MathF.Round(at.Y)), color, glyph);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,196 @@
|
|||
// ============================================================================
|
||||
// RynthDefective - ShortcutBar/SelectionWindow.cs
|
||||
// What is selected, as the retail toolbar showed it (Tom 2026-10-22: "people
|
||||
// use it all the time to find things near them: doors, monsters"): its
|
||||
// picture and name, how far and which way it is (an arrow from where you
|
||||
// face, and the compass point), and the health bar of a creature or player.
|
||||
// USE uses it (opens a door, talks to an NPC). AC's own selection keys still
|
||||
// pick what is selected; this only shows it.
|
||||
//
|
||||
// the name row drag to move; Ctrl+wheel: bigger or smaller (30-250%);
|
||||
// right-click: hide it (Settings > UI > Toolbar, /rdef selection).
|
||||
//
|
||||
// AC's render thread; reads the view the tick built (SelectionView).
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Numerics;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.Plugin.Shared.RynthUi;
|
||||
using RynthCore.PluginSdk;
|
||||
using static RynthCore.Plugin.Shared.RynthUi.RynthUi;
|
||||
|
||||
namespace RynthCore.Plugin.RynthDefective.ShortcutBar;
|
||||
|
||||
/// <summary>The selected object as drawn (built on the plugin tick).</summary>
|
||||
internal sealed record SelectionView(
|
||||
bool Ready,
|
||||
uint Id,
|
||||
string Name,
|
||||
string Where,
|
||||
float Relative, // degrees from where the player faces (0 ahead, + to the right); NaN = unknown
|
||||
float Health, // 0-1, or -1 when it has none known
|
||||
uint Current,
|
||||
uint Max)
|
||||
{
|
||||
public static readonly SelectionView NotReady = new(false, 0, string.Empty, string.Empty, float.NaN, -1f, 0, 0);
|
||||
}
|
||||
|
||||
internal sealed class SelectionWindow
|
||||
{
|
||||
public const string Title = "Selection";
|
||||
|
||||
private readonly RynthCoreHost _host;
|
||||
private readonly Action<uint> _use;
|
||||
private float _k = 1f, _r = 1f;
|
||||
|
||||
public SelectionWindow(RynthCoreHost host, Action<uint> use)
|
||||
{
|
||||
_host = host;
|
||||
_use = use;
|
||||
}
|
||||
|
||||
private float Px(float v) => v * _k;
|
||||
private float Fs(ImFontPtr f) => f.FontSize * _r;
|
||||
|
||||
private void Scale()
|
||||
{
|
||||
float fontK = Math.Max(0.5f, Font(RynthUiFont.Ui10).FontSize / 10f);
|
||||
int pct = _host.PanelScale(Title);
|
||||
_k = pct > 0 ? pct / 100f : fontK;
|
||||
_r = _k / fontK;
|
||||
}
|
||||
|
||||
private const float Pad = 6, Icon = 30, Gap = 6, Radius = 4, BarH = 6, UseW = 34, UseH = 16;
|
||||
|
||||
private uint _bg, _key, _inset, _line, _text, _dim, _faint, _accent;
|
||||
private static readonly uint HealthColor = Argb(0xFFE0564E), HealthHigh = Argb(0xFF73D885), White = Argb(0xFFFFFFFF);
|
||||
private static uint A(uint c, float alpha) => WithAlpha(c, (uint)Math.Clamp(MathF.Round(alpha * 255f), 0f, 255f));
|
||||
|
||||
/// <summary>Draws the selection into the host's window; returns the height it needs (pixels). Render thread.</summary>
|
||||
public float Draw(SelectionView v)
|
||||
{
|
||||
Scale();
|
||||
_bg = Color(RynthUiColor.Background);
|
||||
_key = Color(RynthUiColor.KeyFace);
|
||||
_inset = Color(RynthUiColor.Inset);
|
||||
_line = Color(RynthUiColor.Hairline);
|
||||
_text = Color(RynthUiColor.Text);
|
||||
_dim = Color(RynthUiColor.Muted);
|
||||
_faint = Color(RynthUiColor.Faint);
|
||||
_accent = Color(RynthUiColor.Accent);
|
||||
|
||||
Vector2 origin = ImGui.GetCursorScreenPos();
|
||||
origin = new Vector2(MathF.Round(origin.X), MathF.Round(origin.Y));
|
||||
float width = MathF.Floor(ImGui.GetContentRegionAvail().X);
|
||||
if (width < 40) return Px(40);
|
||||
ImDrawListPtr dl = ImGui.GetWindowDrawList();
|
||||
|
||||
float pad = Px(Pad), icon = Px(Icon);
|
||||
float height = MathF.Ceiling(2 * pad + icon);
|
||||
Vector2 max = origin + new Vector2(width, height);
|
||||
dl.AddRectFilled(origin, max, A(_bg, 0.94f), Px(Radius));
|
||||
dl.AddRect(origin, max, _line, Px(Radius));
|
||||
|
||||
bool hasUse = v.Ready && v.Id != 0;
|
||||
float useW = hasUse ? Px(UseW) : 0f;
|
||||
|
||||
// The drag surface: everything but USE.
|
||||
ImGui.SetCursorScreenPos(origin);
|
||||
ImGui.InvisibleButton("##sel_drag", new Vector2(Math.Max(1, width - useW - (hasUse ? pad : 0)), height));
|
||||
_host.PanelDragWithLastItem();
|
||||
if (ImGui.IsItemClicked(ImGuiMouseButton.Right)) _host.SetPanelOpen(Title, RynthPanelOpen.Close);
|
||||
SafeImGui.SetItemTooltip(v.Id == 0
|
||||
? "Nothing selected. Select with a click or the game's selection keys (- and = go through what's near you).\nDrag to move; Ctrl+wheel: bigger or smaller; right-click: hide."
|
||||
: $"{v.Name}{(v.Where.Length > 0 ? " - " + v.Where : "")}\nDrag to move; Ctrl+wheel: bigger or smaller; right-click: hide.");
|
||||
|
||||
// The picture.
|
||||
Vector2 ip = origin + new Vector2(pad, pad);
|
||||
dl.AddRectFilled(ip, ip + new Vector2(icon, icon), v.Id == 0 ? _inset : _key, Px(3));
|
||||
IntPtr tex = v.Id != 0 ? _host.GetIconTexture(RynthIconKind.Object, v.Id) : IntPtr.Zero;
|
||||
if (tex != IntPtr.Zero)
|
||||
dl.AddImageRounded(tex, ip + new Vector2(Px(2), Px(2)), ip + new Vector2(icon - Px(2), icon - Px(2)), Vector2.Zero, Vector2.One, White, Px(2));
|
||||
dl.AddRect(ip, ip + new Vector2(icon, icon), _line, Px(3));
|
||||
|
||||
float tx = ip.X + icon + Px(Gap);
|
||||
float right = origin.X + width - pad - (hasUse ? useW + Px(Gap) : 0f);
|
||||
ImFontPtr nf = Font(RynthUiFont.NarrowBold11), sf = Font(RynthUiFont.Narrow9);
|
||||
if (!v.Ready || v.Id == 0)
|
||||
{
|
||||
Clip(dl, nf, Fs(nf), new Vector2(tx, ip.Y + Px(1)), _faint, v.Ready ? "Nothing selected" : "Selection", right - tx);
|
||||
Clip(dl, sf, Fs(sf), new Vector2(tx, ip.Y + icon - Fs(sf)), _faint, "- and = go through what's near you", right - tx);
|
||||
ImGui.SetCursorScreenPos(origin);
|
||||
ImGui.Dummy(new Vector2(width, height));
|
||||
return height;
|
||||
}
|
||||
|
||||
// Name, then the health bar (a creature or player) and where it is.
|
||||
Clip(dl, nf, Fs(nf), new Vector2(tx, ip.Y), _text, v.Name, right - tx);
|
||||
float lineY = ip.Y + icon - Fs(sf);
|
||||
float x = tx;
|
||||
if (!float.IsNaN(v.Relative))
|
||||
{
|
||||
float s = Fs(sf);
|
||||
Arrow(dl, new Vector2(x + s * 0.5f, lineY + s * 0.5f), s * 0.5f, v.Relative, _accent);
|
||||
x += s + Px(3);
|
||||
}
|
||||
if (v.Health >= 0f)
|
||||
{
|
||||
float barY = ip.Y + Fs(nf) + Px(3);
|
||||
float barW = right - tx, barH = Px(BarH);
|
||||
Vector2 b0 = new(tx, barY), b1 = new(tx + barW, barY + barH);
|
||||
dl.AddRectFilled(b0, b1, _inset, Px(2));
|
||||
float f = Math.Clamp(v.Health, 0f, 1f);
|
||||
if (f > 0f) dl.AddRectFilled(b0, new Vector2(tx + barW * f, barY + barH), f > 0.6f ? A(HealthHigh, 0.9f) : HealthColor, Px(2));
|
||||
dl.AddRect(b0, b1, _line, Px(2));
|
||||
string pct = (v.Max > 0 ? $"{v.Current}/{v.Max} " : "") + MathF.Round(f * 100f).ToString(CultureInfo.InvariantCulture) + "%";
|
||||
float pw = sf.CalcTextSizeA(Fs(sf), float.MaxValue, 0f, pct).X;
|
||||
dl.AddText(sf, Fs(sf), new Vector2(right - pw, lineY), _dim, pct);
|
||||
Clip(dl, sf, Fs(sf), new Vector2(x, lineY), _dim, v.Where, right - pw - Px(6) - x);
|
||||
}
|
||||
else Clip(dl, sf, Fs(sf), new Vector2(x, lineY), _dim, v.Where, right - x);
|
||||
|
||||
// USE.
|
||||
Vector2 up = new(origin.X + width - pad - useW, origin.Y + (height - Px(UseH)) * 0.5f);
|
||||
ImGui.SetCursorScreenPos(up);
|
||||
bool use = ImGui.InvisibleButton("##sel_use", new Vector2(useW, Px(UseH)));
|
||||
bool hot = ImGui.IsItemHovered();
|
||||
SafeImGui.SetItemTooltip("Use it, as a double-click does (open a door, talk, pick up, use an item).");
|
||||
dl.AddRectFilled(up, up + new Vector2(useW, Px(UseH)), hot ? _key : A(_key, 0.6f), Px(3));
|
||||
dl.AddRect(up, up + new Vector2(useW, Px(UseH)), hot ? _accent : _line, Px(3));
|
||||
ImFontPtr uf = Font(RynthUiFont.Dash9);
|
||||
float uw = uf.CalcTextSizeA(Fs(uf), float.MaxValue, 0f, "USE").X;
|
||||
dl.AddText(uf, Fs(uf), new Vector2(MathF.Round(up.X + (useW - uw) * 0.5f), MathF.Round(up.Y + (Px(UseH) - Fs(uf)) * 0.5f)), hot ? _text : _dim, "USE");
|
||||
if (use) _use(v.Id);
|
||||
|
||||
ImGui.SetCursorScreenPos(origin);
|
||||
ImGui.Dummy(new Vector2(width, height));
|
||||
return height;
|
||||
}
|
||||
|
||||
/// <summary>Text cut with "..." to <paramref name="room"/> pixels.</summary>
|
||||
private static void Clip(ImDrawListPtr dl, ImFontPtr f, float size, Vector2 pos, uint color, string text, float room)
|
||||
{
|
||||
if (text.Length == 0 || room <= 4) return;
|
||||
float w = f.CalcTextSizeA(size, float.MaxValue, 0f, text).X;
|
||||
if (w > room)
|
||||
{
|
||||
int n = text.Length;
|
||||
while (n > 1 && f.CalcTextSizeA(size, float.MaxValue, 0f, text[..n] + "...").X > room) n--;
|
||||
text = text[..n] + "...";
|
||||
}
|
||||
dl.AddText(f, size, new Vector2(MathF.Round(pos.X), MathF.Round(pos.Y)), color, text);
|
||||
}
|
||||
|
||||
/// <summary>A small arrow pointing <paramref name="degrees"/> from straight up (where the player faces), clockwise.</summary>
|
||||
private static void Arrow(ImDrawListPtr dl, Vector2 c, float r, float degrees, uint color)
|
||||
{
|
||||
float a = degrees * MathF.PI / 180f;
|
||||
Vector2 Dir(float t) => new(MathF.Sin(t), -MathF.Cos(t));
|
||||
Vector2 tip = c + Dir(a) * r;
|
||||
Vector2 left = c + Dir(a + 2.45f) * r * 0.85f, rightP = c + Dir(a - 2.45f) * r * 0.85f;
|
||||
dl.AddTriangleFilled(tip, left, rightP, color);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,539 @@
|
|||
// ============================================================================
|
||||
// RynthDefective - ShortcutBar/ShortcutBarWindow.cs
|
||||
// The shortcut bar, drawn by RynthDefective in its own frameless window
|
||||
// (plugin API v90: RynthCore hosts it, "chrome": "none" + "fitHeight"), in
|
||||
// the instrument look of RynthAi's dashboard and the player's colour theme.
|
||||
//
|
||||
// header SHORTCUTS and the slot count (the drag handle; Ctrl+wheel: the
|
||||
// size), then Edit, Weapons (the weapon picker) and Hide.
|
||||
// slots the item's picture, its key in the top-left corner (AC's keymap
|
||||
// for slots 1-18, the engine's hotkeys after), the count or "in
|
||||
// hand" under it. They fill the window's width and wrap: drag the
|
||||
// window wider or narrower for one row or several.
|
||||
// edit the slot numbers show, and - / + at the end take a slot off or
|
||||
// add one (the player picks how many; 1-18 are the game's).
|
||||
// Drag an item from AC's pack onto a slot: it goes there, as on the retail
|
||||
// toolbar (the item stays in the pack). Click a slot: it is used as its key
|
||||
// would. Right-click: put the selected item there, or empty it, and its keys: remove one, or add one by pressing
|
||||
// it. A slot 1-18 key is AC's own (its keymap, so the retail toolbar answers
|
||||
// to it too, in every client); a key past 18 is an engine hotkey running
|
||||
// /rdef use N. A key comes off whatever had it, after the player says so.
|
||||
//
|
||||
// AC's render thread. Reads the snapshot the tick built; every click is
|
||||
// queued for the tick (IBarActions).
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Numerics;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Plugin.RynthDefective.Model;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.Plugin.Shared.RynthUi;
|
||||
using RynthCore.PluginSdk;
|
||||
using static RynthCore.Plugin.Shared.RynthUi.RynthUi;
|
||||
|
||||
namespace RynthCore.Plugin.RynthDefective.ShortcutBar;
|
||||
|
||||
/// <summary>What the bar asks of the plugin: everything runs on its tick.</summary>
|
||||
internal interface IBarActions
|
||||
{
|
||||
void Use(int number);
|
||||
void SetFromSelected(int number);
|
||||
void Clear(int number);
|
||||
void ChangeSlotCount(int delta);
|
||||
/// <summary>An item dragged out of AC's UI was let go over slot <paramref name="number"/>.</summary>
|
||||
void DropItem(int number, uint objectId);
|
||||
/// <summary>A key was bound or removed: the bar asks for its keys again.</summary>
|
||||
void KeysChanged();
|
||||
void ShowWeapons();
|
||||
void Hide();
|
||||
}
|
||||
|
||||
internal sealed class ShortcutBarWindow
|
||||
{
|
||||
public const string Title = "Shortcuts";
|
||||
|
||||
private readonly RynthCoreHost _host;
|
||||
private readonly IBarActions _act;
|
||||
private bool _edit;
|
||||
private float _k = 1f, _r = 1f;
|
||||
|
||||
public ShortcutBarWindow(RynthCoreHost host, IBarActions actions)
|
||||
{
|
||||
_host = host;
|
||||
_act = actions;
|
||||
}
|
||||
|
||||
private float Px(float v) => v * _k;
|
||||
|
||||
/// <summary>A font's size at this scale (its baked size times the text ratio).</summary>
|
||||
private float Fs(ImFontPtr f) => f.FontSize * _r;
|
||||
|
||||
/// <summary>
|
||||
/// The layout's scale and the text's against the baked font: the window's own size (Settings > UI >
|
||||
/// Toolbar, Ctrl+wheel: 30-250%, PanelScale) or, unset, the text size the engine baked for it.
|
||||
/// </summary>
|
||||
private void Scale()
|
||||
{
|
||||
float fontK = Math.Max(0.5f, Font(RynthUiFont.Ui10).FontSize / 10f);
|
||||
int pct = _host.PanelScale(Title);
|
||||
_k = pct > 0 ? pct / 100f : fontK;
|
||||
_r = _k / fontK;
|
||||
}
|
||||
|
||||
private const float PadX = 7, PadTop = 6, PadBottom = 7, Radius = 4, HeaderH = 18, Gap = 3, ChipSize = 16;
|
||||
|
||||
private uint _bg, _key, _inset, _line, _text, _dim, _faint, _accent;
|
||||
private static readonly uint InHandColor = Argb(0xFF73D885), MissingColor = Argb(0xFFF98075),
|
||||
Black = Argb(0xFF000000), White = Argb(0xFFFFFFFF);
|
||||
|
||||
private static uint A(uint c, float alpha) => WithAlpha(c, (uint)Math.Clamp(MathF.Round(alpha * 255f), 0f, 255f));
|
||||
|
||||
/// <summary>Draws the bar into the host's window; returns the height it needs (pixels). Render thread.</summary>
|
||||
public float Draw(BarSnapshot view, bool popped)
|
||||
{
|
||||
Scale();
|
||||
_bg = Color(RynthUiColor.Background);
|
||||
_key = Color(RynthUiColor.KeyFace);
|
||||
_inset = Color(RynthUiColor.Inset);
|
||||
_line = Color(RynthUiColor.Hairline);
|
||||
_text = Color(RynthUiColor.Text);
|
||||
_dim = Color(RynthUiColor.Muted);
|
||||
_faint = Color(RynthUiColor.Faint);
|
||||
_accent = Color(RynthUiColor.Accent);
|
||||
|
||||
Vector2 origin = ImGui.GetCursorScreenPos();
|
||||
origin = new Vector2(MathF.Round(origin.X), MathF.Round(origin.Y));
|
||||
float width = MathF.Floor(ImGui.GetContentRegionAvail().X);
|
||||
if (width < 40) return Px(60);
|
||||
ImDrawListPtr dl = ImGui.GetWindowDrawList();
|
||||
|
||||
float height;
|
||||
dl.ChannelsSplit(2);
|
||||
bool merged = false;
|
||||
try
|
||||
{
|
||||
dl.ChannelsSetCurrent(1);
|
||||
float x0 = origin.X + Px(PadX), w = width - 2 * Px(PadX);
|
||||
float y = origin.Y + Px(PadTop);
|
||||
y = Header(dl, view, x0, y, w);
|
||||
y += Px(5);
|
||||
y = Slots(dl, view, x0, y, w);
|
||||
y += Px(PadBottom);
|
||||
height = MathF.Ceiling(y - origin.Y);
|
||||
dl.ChannelsSetCurrent(0);
|
||||
Frame(dl, origin, new Vector2(width, height));
|
||||
dl.ChannelsMerge();
|
||||
merged = true;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (!merged) dl.ChannelsMerge();
|
||||
}
|
||||
ImGui.SetCursorScreenPos(origin);
|
||||
ImGui.Dummy(new Vector2(width, height));
|
||||
SlotMenu(view);
|
||||
if (_openKeyPopup)
|
||||
{
|
||||
_openKeyPopup = false;
|
||||
ImGui.OpenPopup(KeyPopupId);
|
||||
}
|
||||
KeyPopup();
|
||||
return height;
|
||||
}
|
||||
|
||||
private void Frame(ImDrawListPtr dl, Vector2 min, Vector2 size)
|
||||
{
|
||||
Vector2 max = min + size;
|
||||
float r = Px(Radius);
|
||||
dl.AddRectFilled(min, max, A(_bg, 0.94f), r);
|
||||
dl.AddLine(new Vector2(min.X + r, min.Y + 1.5f), new Vector2(max.X - r, min.Y + 1.5f), A(White, 0.05f));
|
||||
dl.AddRect(min, max, _line, r);
|
||||
}
|
||||
|
||||
// ── Header ────────────────────────────────────────────────────────────
|
||||
|
||||
private float Header(ImDrawListPtr dl, BarSnapshot view, float x0, float y, float w)
|
||||
{
|
||||
float h = Px(HeaderH), chip = Px(ChipSize);
|
||||
const int chips = 3;
|
||||
float chipsW = chips * chip + (chips - 1) * Px(1);
|
||||
|
||||
ImGui.SetCursorScreenPos(new Vector2(x0, y));
|
||||
ImGui.InvisibleButton("##sb_drag", new Vector2(Math.Max(1, w - chipsW - Px(4)), h));
|
||||
_host.PanelDragWithLastItem();
|
||||
SafeImGui.SetItemTooltip("Drag to move the bar. Ctrl+wheel here: bigger or smaller.\nDrag the window's edge to change how many slots fit in a row.");
|
||||
|
||||
ImFontPtr tf = Font(RynthUiFont.NarrowBold11);
|
||||
float size = Fs(tf) * 10f / 11f;
|
||||
float tx = Tracked(dl, tf, size, new Vector2(x0, MathF.Round(y + (h - size) * 0.5f)), _text, "SHORTCUTS", 0.18f * size);
|
||||
ImFontPtr nf = Font(RynthUiFont.Dash9);
|
||||
string count = view.Ready ? view.Slots.Length.ToString(System.Globalization.CultureInfo.InvariantCulture) : "";
|
||||
dl.AddText(nf, Fs(nf), new Vector2(MathF.Round(tx + Px(6)), MathF.Round(y + (h - Fs(nf)) * 0.5f + Px(1))), _faint, count);
|
||||
|
||||
float cx = x0 + w - chipsW, cy = y + (h - chip) * 0.5f;
|
||||
if (Chip("##sb_edit", RynthIcons.PencilSimple, new Vector2(cx, cy), _edit ? _accent : _faint,
|
||||
_edit ? "Done editing." : "Edit: the slot numbers, and - / + to take a slot off or add one.", _edit))
|
||||
_edit = !_edit;
|
||||
cx += chip + Px(1);
|
||||
if (Chip("##sb_weapons", RynthIcons.Sword, new Vector2(cx, cy), _faint, "Weapons: every weapon and wand you carry, wield one with a click."))
|
||||
_act.ShowWeapons();
|
||||
cx += chip + Px(1);
|
||||
if (Chip("##sb_hide", RynthIcons.X, new Vector2(cx, cy), _faint, "Hide the bar (/rdef shows it again). Its keys keep working."))
|
||||
_act.Hide();
|
||||
return y + h;
|
||||
}
|
||||
|
||||
private bool Chip(string id, string icon, Vector2 pos, uint color, string tip, bool held = false)
|
||||
{
|
||||
Vector2 size = new(Px(ChipSize), Px(ChipSize));
|
||||
ImGui.SetCursorScreenPos(pos);
|
||||
bool clicked = ImGui.InvisibleButton(id, size);
|
||||
bool hot = ImGui.IsItemHovered();
|
||||
SafeImGui.SetItemTooltip(tip);
|
||||
ImDrawListPtr dl = ImGui.GetWindowDrawList();
|
||||
if (hot || held) dl.AddRectFilled(pos, pos + size, _key, Px(3));
|
||||
DrawIcon(dl, icon, pos, size, Px(11), hot ? _text : color);
|
||||
return clicked;
|
||||
}
|
||||
|
||||
// ── Slots ─────────────────────────────────────────────────────────────
|
||||
|
||||
private int _menuSlot;
|
||||
private const string MenuId = "##sb_slot_menu";
|
||||
|
||||
private float Slots(ImDrawListPtr dl, BarSnapshot view, float x0, float y, float w)
|
||||
{
|
||||
if (!view.Ready)
|
||||
{
|
||||
ImFontPtr f = Font(RynthUiFont.Narrow10);
|
||||
dl.AddText(f, Fs(f), new Vector2(x0, y), _faint, "Your shortcuts show once you're in the world.");
|
||||
return y + Fs(f) + Px(2);
|
||||
}
|
||||
float cell = Px(Math.Clamp(view.IconSize, 20, 64)), gap = Px(Gap);
|
||||
int cells = view.Slots.Length + (_edit ? 2 : 0);
|
||||
int perRow = Math.Max(1, (int)MathF.Floor((w + gap) / (cell + gap)));
|
||||
int rows = (cells + perRow - 1) / perRow;
|
||||
|
||||
// Items dragged out of AC's UI: the slots' area takes them (the engine keeps the drop from AC).
|
||||
Vector2 areaMin = new(x0, y), areaMax = new(x0 + perRow * (cell + gap), y + rows * (cell + gap));
|
||||
uint dropped = _host.HasDropTargets ? _host.DropTarget(Title, areaMin, areaMax, true, out _dragging) : 0;
|
||||
int under = SlotAt(ImGui.GetIO().MousePos, x0, y, cell, gap, perRow, view.Slots.Length);
|
||||
_dropSlot = _dragging ? under : 0;
|
||||
if (dropped != 0 && under > 0) _act.DropItem(under, dropped);
|
||||
|
||||
for (int i = 0; i < cells; i++)
|
||||
{
|
||||
int col = i % perRow, row = i / perRow;
|
||||
Vector2 p = new(MathF.Round(x0 + col * (cell + gap)), MathF.Round(y + row * (cell + gap)));
|
||||
if (i < view.Slots.Length) Slot(dl, view.Slots[i], p, cell);
|
||||
else EditButton(dl, i == view.Slots.Length ? -1 : 1, p, cell, view.Slots.Length);
|
||||
}
|
||||
return y + rows * (cell + gap) - gap;
|
||||
}
|
||||
|
||||
private bool _dragging;
|
||||
private int _dropSlot;
|
||||
|
||||
/// <summary>The slot number (1-based) under <paramref name="m"/>, or 0.</summary>
|
||||
private static int SlotAt(Vector2 m, float x0, float y0, float cell, float gap, int perRow, int count)
|
||||
{
|
||||
if (m.X < x0 || m.Y < y0) return 0;
|
||||
int col = (int)((m.X - x0) / (cell + gap)), row = (int)((m.Y - y0) / (cell + gap));
|
||||
if (col >= perRow || m.X - x0 - col * (cell + gap) > cell || m.Y - y0 - row * (cell + gap) > cell) return 0;
|
||||
int i = row * perRow + col;
|
||||
return i < count ? i + 1 : 0;
|
||||
}
|
||||
|
||||
private void Slot(ImDrawListPtr dl, BarSlot s, Vector2 p, float cell)
|
||||
{
|
||||
Vector2 size = new(cell, cell);
|
||||
ImGui.SetCursorScreenPos(p);
|
||||
bool clicked = ImGui.InvisibleButton(Id("##sb_slot", s.Number), size, ImGuiButtonFlags.MouseButtonLeft | ImGuiButtonFlags.MouseButtonRight)
|
||||
&& ImGui.IsMouseReleased(ImGuiMouseButton.Left);
|
||||
bool right = ImGui.IsItemClicked(ImGuiMouseButton.Right);
|
||||
bool hot = ImGui.IsItemHovered();
|
||||
SafeImGui.SetItemTooltip(s.Tooltip);
|
||||
float r = Px(3);
|
||||
|
||||
// The well, the picture, a hairline (the accent under the mouse; green while in hand).
|
||||
dl.AddRectFilled(p, p + size, s.Empty ? _inset : _key, r);
|
||||
if (!s.Empty)
|
||||
{
|
||||
uint id = s.ObjectId != 0 ? s.ObjectId : s.SpellId;
|
||||
IntPtr tex = id == 0 ? IntPtr.Zero : _host.GetIconTexture(s.ObjectId != 0 ? RynthIconKind.Object : RynthIconKind.Spell, id);
|
||||
float inset = Px(2);
|
||||
if (tex != IntPtr.Zero)
|
||||
dl.AddImageRounded(tex, p + new Vector2(inset, inset), p + size - new Vector2(inset, inset), Vector2.Zero, Vector2.One,
|
||||
s.Tone == CountTone.Missing ? A(White, 0.35f) : White, Px(2));
|
||||
else
|
||||
{
|
||||
ImFontPtr af = Font(RynthUiFont.Narrow9);
|
||||
string abbr = Abbrev(s.Name);
|
||||
float aw = af.CalcTextSizeA(Fs(af), float.MaxValue, 0f, abbr).X;
|
||||
dl.AddText(af, Fs(af), new Vector2(MathF.Round(p.X + (cell - aw) * 0.5f), MathF.Round(p.Y + (cell - Fs(af)) * 0.5f)), _dim, abbr);
|
||||
}
|
||||
}
|
||||
uint border = hot || _dropSlot == s.Number ? _accent : s.Tone == CountTone.InHand ? A(InHandColor, 0.8f) : _line;
|
||||
dl.AddRect(p, p + size, border, r, ImDrawFlags.None, _dropSlot == s.Number ? Px(2) : 1f);
|
||||
|
||||
// The key, top left (a dark plate under it so it reads over any picture); edit: the slot number.
|
||||
ImFontPtr kf = Font(RynthUiFont.Dash9);
|
||||
string label = _edit ? s.Number.ToString(System.Globalization.CultureInfo.InvariantCulture) : s.Key;
|
||||
if (label.Length > 0)
|
||||
{
|
||||
float lw = kf.CalcTextSizeA(Fs(kf), float.MaxValue, 0f, label).X;
|
||||
Vector2 lp = p + new Vector2(Px(2), Px(1));
|
||||
dl.AddRectFilled(lp - new Vector2(Px(1), 0), lp + new Vector2(lw + Px(1), Fs(kf)), A(Black, 0.55f), Px(2));
|
||||
dl.AddText(kf, Fs(kf), lp, _edit ? _accent : s.Retail ? _text : _accent, label);
|
||||
}
|
||||
// The count, bottom right.
|
||||
if (!_edit && s.Count.Length > 0)
|
||||
{
|
||||
string c = s.Count == "in hand" ? "hand" : s.Count;
|
||||
float cw = kf.CalcTextSizeA(Fs(kf), float.MaxValue, 0f, c).X;
|
||||
Vector2 cp = p + new Vector2(cell - cw - Px(2), cell - Fs(kf) - Px(1));
|
||||
dl.AddRectFilled(cp - new Vector2(Px(1), 0), cp + new Vector2(cw + Px(1), Fs(kf)), A(Black, 0.55f), Px(2));
|
||||
uint cc = s.Tone == CountTone.InHand ? InHandColor : s.Tone == CountTone.Missing ? MissingColor : _text;
|
||||
dl.AddText(kf, Fs(kf), cp, cc, c);
|
||||
}
|
||||
|
||||
if (clicked && !s.Empty) _act.Use(s.Number);
|
||||
if (right)
|
||||
{
|
||||
_menuSlot = s.Number;
|
||||
ImGui.OpenPopup(MenuId);
|
||||
}
|
||||
}
|
||||
|
||||
private void EditButton(ImDrawListPtr dl, int delta, Vector2 p, float cell, int count)
|
||||
{
|
||||
Vector2 size = new(cell, cell);
|
||||
bool can = delta < 0 ? count > DefSettings.BarSlotsMin : count < DefSettings.BarSlotsMax;
|
||||
ImGui.SetCursorScreenPos(p);
|
||||
bool clicked = ImGui.InvisibleButton(delta < 0 ? "##sb_less" : "##sb_more", size);
|
||||
bool hot = can && ImGui.IsItemHovered();
|
||||
SafeImGui.SetItemTooltip(delta < 0
|
||||
? "One slot fewer (the last one's item stays: add the slot back and it is there)."
|
||||
: count < DefSettings.RetailSlots ? "One more slot (the game's own, up to 18)."
|
||||
: "One more slot (RynthCore's: the game's toolbar holds 18).");
|
||||
float r = Px(3);
|
||||
dl.AddRect(p, p + size, hot ? _accent : A(_line, can ? 1f : 0.4f), r);
|
||||
DrawIcon(dl, delta < 0 ? RynthIcons.Minus : RynthIcons.Plus, p, size, Px(12), can ? (hot ? _text : _dim) : A(_faint, 0.5f));
|
||||
if (clicked && can) _act.ChangeSlotCount(delta);
|
||||
}
|
||||
|
||||
private void SlotMenu(BarSnapshot view)
|
||||
{
|
||||
if (!ImGui.IsPopupOpen(MenuId)) return;
|
||||
ImGui.PushStyleColor(ImGuiCol.PopupBg, WithAlpha(_bg, 0xFA));
|
||||
ImGui.PushStyleColor(ImGuiCol.Border, _line);
|
||||
ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, Px(4));
|
||||
ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(Px(6), Px(5)));
|
||||
bool open = ImGui.BeginPopup(MenuId);
|
||||
ImGui.PopStyleVar(2);
|
||||
ImGui.PopStyleColor(2);
|
||||
if (!open) return;
|
||||
try
|
||||
{
|
||||
BarSlot? s = _menuSlot >= 1 && _menuSlot <= view.Slots.Length ? view.Slots[_menuSlot - 1] : null;
|
||||
if (s == null) { ImGui.CloseCurrentPopup(); return; }
|
||||
ImGui.TextDisabled($"Slot {s.Number}{(s.Retail ? " (the game's own)" : " (RynthCore's)")}");
|
||||
if (s.Name.Length > 0) SafeImGui.Text(s.Name);
|
||||
ImGui.Separator();
|
||||
bool hasSelection = _host.HasGetSelectedItemId && _host.GetSelectedItemId() != 0;
|
||||
if (ImGui.MenuItem("Put the selected item here", null, false, hasSelection)) _act.SetFromSelected(s.Number);
|
||||
if (ImGui.MenuItem("Empty this slot", null, false, !s.Empty)) _act.Clear(s.Number);
|
||||
ImGui.Separator();
|
||||
if (!_host.HasKeyBinding)
|
||||
{
|
||||
ImGui.TextDisabled(s.AllKeys.Length > 0 ? "Keys: " + s.AllKeys
|
||||
: s.Retail ? "No key: bind UseQuickSlot_" + s.Number + " in Configure Keyboard." : "No key: /rdef bind " + (s.Number - DefSettings.RetailSlots) + " F9");
|
||||
return;
|
||||
}
|
||||
string[] keys = SplitKeys(s.AllKeys);
|
||||
ImGui.TextDisabled(keys.Length == 0 ? "No key yet" : keys.Length == 1 ? "Key" : "Keys");
|
||||
foreach (string key in keys)
|
||||
{
|
||||
if (!ImGui.MenuItem("Remove " + key)) continue;
|
||||
if (_host.UnbindActionKey(KeyAction(s.Number), key, out string why)) _act.KeysChanged();
|
||||
else ShowKeyMessage(s.Number, why);
|
||||
}
|
||||
if (ImGui.MenuItem(keys.Length == 0 ? "Add a key..." : "Add another key..."))
|
||||
StartKeyCapture(s.Number);
|
||||
SafeImGui.SetItemTooltip(s.Retail
|
||||
? "Press the key: it becomes this slot's in the game's own keymap, so the retail toolbar and every client use it too."
|
||||
: "Press the key: a RynthCore hotkey for this slot (the game's toolbar holds 18).");
|
||||
}
|
||||
finally { ImGui.EndPopup(); }
|
||||
}
|
||||
|
||||
// ── Keys: "press a key" ───────────────────────────────────────────────
|
||||
|
||||
private enum KeyStep { Waiting, Confirm, Message }
|
||||
|
||||
private const string KeyPopupId = "##sb_key_popup";
|
||||
private bool _openKeyPopup;
|
||||
private int _keySlot;
|
||||
private KeyStep _keyStep;
|
||||
private string _keyName = string.Empty, _keyText = string.Empty;
|
||||
|
||||
/// <summary>The action a slot's keys run: AC's UseQuickSlot_N for 1-18, the engine command for the rest.</summary>
|
||||
public static string KeyAction(int number) =>
|
||||
number <= DefSettings.RetailSlots ? "UseQuickSlot_" + number : DefCommandParser.UseCommand(number - DefSettings.RetailSlots);
|
||||
|
||||
private static string[] SplitKeys(string keys) =>
|
||||
keys.Length == 0 ? Array.Empty<string>() : keys.Split(", ", StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||||
|
||||
private void StartKeyCapture(int number)
|
||||
{
|
||||
_keySlot = number;
|
||||
_keyStep = KeyStep.Waiting;
|
||||
_keyName = _keyText = string.Empty;
|
||||
_host.BeginKeyCapture();
|
||||
_openKeyPopup = true;
|
||||
}
|
||||
|
||||
private void ShowKeyMessage(int number, string text)
|
||||
{
|
||||
_keySlot = number;
|
||||
_keyStep = KeyStep.Message;
|
||||
_keyText = text;
|
||||
_openKeyPopup = true;
|
||||
}
|
||||
|
||||
private void KeyPopup()
|
||||
{
|
||||
if (!ImGui.IsPopupOpen(KeyPopupId))
|
||||
{
|
||||
if (_keyStep == KeyStep.Waiting && _keySlot != 0) { _host.CancelKeyCapture(); _keySlot = 0; } // clicked away
|
||||
return;
|
||||
}
|
||||
ImGui.PushStyleColor(ImGuiCol.PopupBg, WithAlpha(_bg, 0xFA));
|
||||
ImGui.PushStyleColor(ImGuiCol.Border, _line);
|
||||
ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, Px(4));
|
||||
ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(Px(8), Px(7)));
|
||||
bool open = ImGui.BeginPopup(KeyPopupId);
|
||||
ImGui.PopStyleVar(2);
|
||||
ImGui.PopStyleColor(2);
|
||||
if (!open) return;
|
||||
try
|
||||
{
|
||||
ImGui.PushTextWrapPos(ImGui.GetCursorPosX() + Px(230));
|
||||
ImGui.TextDisabled($"Slot {_keySlot}{(_keySlot <= DefSettings.RetailSlots ? " (the game's own)" : " (RynthCore's)")}");
|
||||
switch (_keyStep)
|
||||
{
|
||||
case KeyStep.Waiting:
|
||||
SafeImGui.Text("Press the key for this slot.");
|
||||
ImGui.TextDisabled("Hold Ctrl, Alt or Shift with it if you like. Esc cancels.");
|
||||
RynthKeyCapture got = _host.PollKeyCapture(out string text);
|
||||
if (got == RynthKeyCapture.Waiting)
|
||||
{
|
||||
if (text.Length > 0) ImGui.TextColored(new Vector4(0.98f, 0.5f, 0.46f, 1f), text);
|
||||
break;
|
||||
}
|
||||
if (got == RynthKeyCapture.Cancelled) { _keySlot = 0; ImGui.CloseCurrentPopup(); break; }
|
||||
_keyName = text;
|
||||
RynthKeyCheck check = _host.CheckActionKey(KeyAction(_keySlot), _keyName, out string msg);
|
||||
if (check == RynthKeyCheck.Free) Bind();
|
||||
else
|
||||
{
|
||||
_keyStep = check == RynthKeyCheck.Taken ? KeyStep.Confirm : KeyStep.Message;
|
||||
_keyText = msg;
|
||||
}
|
||||
break;
|
||||
case KeyStep.Confirm:
|
||||
SafeImGui.Text(_keyText);
|
||||
ImGui.TextDisabled($"Use it for slot {_keySlot} instead? It comes off those.");
|
||||
if (ImGui.Button($"Use {_keyName} here")) Bind();
|
||||
ImGui.SameLine();
|
||||
if (ImGui.Button("Another key")) StartKeyCapture(_keySlot);
|
||||
ImGui.SameLine();
|
||||
if (ImGui.Button("Cancel")) { _keySlot = 0; ImGui.CloseCurrentPopup(); }
|
||||
break;
|
||||
case KeyStep.Message:
|
||||
SafeImGui.Text(_keyText);
|
||||
if (ImGui.Button("Another key")) StartKeyCapture(_keySlot);
|
||||
ImGui.SameLine();
|
||||
if (ImGui.Button("Close")) { _keySlot = 0; ImGui.CloseCurrentPopup(); }
|
||||
break;
|
||||
}
|
||||
ImGui.PopTextWrapPos();
|
||||
}
|
||||
finally { ImGui.EndPopup(); }
|
||||
}
|
||||
|
||||
private void Bind()
|
||||
{
|
||||
if (_host.BindActionKey(KeyAction(_keySlot), _keyName, out string why))
|
||||
{
|
||||
_act.KeysChanged();
|
||||
_keySlot = 0;
|
||||
ImGui.CloseCurrentPopup();
|
||||
return;
|
||||
}
|
||||
_keyStep = KeyStep.Message;
|
||||
_keyText = why;
|
||||
}
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────
|
||||
|
||||
private static readonly System.Collections.Generic.Dictionary<(string, int), string> Ids = new();
|
||||
|
||||
private static string Id(string prefix, int n)
|
||||
{
|
||||
if (!Ids.TryGetValue((prefix, n), out string? id)) Ids[(prefix, n)] = id = prefix + n;
|
||||
return id;
|
||||
}
|
||||
|
||||
private static string Abbrev(string name)
|
||||
{
|
||||
if (name.Length == 0) return "?";
|
||||
string[] words = name.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (words.Length >= 2) return string.Concat(char.ToUpperInvariant(words[0][0]), char.ToUpperInvariant(words[^1][0]));
|
||||
return name.Length <= 3 ? name : name[..3];
|
||||
}
|
||||
|
||||
private static readonly string[] Chars = BuildChars();
|
||||
|
||||
private static string[] BuildChars()
|
||||
{
|
||||
var a = new string[128];
|
||||
for (int i = 32; i < 127; i++) a[i] = ((char)i).ToString();
|
||||
return a;
|
||||
}
|
||||
|
||||
/// <summary>Text with <paramref name="spacing"/> pixels between its letters. Returns the x after it.</summary>
|
||||
private static float Tracked(ImDrawListPtr dl, ImFontPtr font, float size, Vector2 pos, uint color, string text, float spacing)
|
||||
{
|
||||
unsafe { if (font.NativePtr == null || text.Length == 0) return pos.X; }
|
||||
float scale = size / font.FontSize;
|
||||
float x = pos.X;
|
||||
for (int i = 0; i < text.Length; i++)
|
||||
{
|
||||
char c = text[i];
|
||||
string s = c < 128 && Chars[c] != null ? Chars[c] : c.ToString();
|
||||
dl.AddText(font, size, new Vector2(MathF.Round(x), pos.Y), color, s);
|
||||
x += font.GetCharAdvance(c) * scale;
|
||||
if (i < text.Length - 1) x += spacing;
|
||||
}
|
||||
return x;
|
||||
}
|
||||
|
||||
/// <summary>A Phosphor glyph centred in the box, <paramref name="px"/> across its em (from Ui18's bake).</summary>
|
||||
private static unsafe void DrawIcon(ImDrawListPtr dl, string glyph, Vector2 min, Vector2 size, float px, uint color)
|
||||
{
|
||||
if (string.IsNullOrEmpty(glyph)) return;
|
||||
ImFontPtr font = Font(RynthUiFont.Ui18);
|
||||
if (font.NativePtr == null) return;
|
||||
byte* g = (byte*)ImGuiNative.ImFont_FindGlyphNoFallback(font.NativePtr, glyph[0]);
|
||||
if (g == null) return;
|
||||
float advance = *(float*)(g + 4);
|
||||
if (advance <= 0) return;
|
||||
float* box = (float*)(g + 8);
|
||||
float scale = px / advance;
|
||||
Vector2 centre = new((box[0] + box[2]) * 0.5f * scale, (box[1] + box[3]) * 0.5f * scale);
|
||||
Vector2 at = min + size * 0.5f - centre;
|
||||
dl.AddText(font, font.FontSize * scale, new Vector2(MathF.Round(at.X), MathF.Round(at.Y)), color, glyph);
|
||||
}
|
||||
}
|
||||
132
Plugins/RynthCore.Plugin.RynthDefective/Ui/UiFormat.cs
Normal file
132
Plugins/RynthCore.Plugin.RynthDefective/Ui/UiFormat.cs
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
using System;
|
||||
|
||||
namespace RynthCore.Plugin.RynthDefective.Ui;
|
||||
|
||||
/// <summary>
|
||||
/// Display-list format 1 for the engine's script windows (RynthSuite
|
||||
/// Docs/RYNTHLUA_WINDOWS_DESIGN.md §4.2-4.3; the engine's DisplayListParser.cs is the source of
|
||||
/// truth). Little-endian. Only the ops RynthDefective draws are listed.
|
||||
/// </summary>
|
||||
internal static class UiFormat
|
||||
{
|
||||
public const uint Magic = 0x31575352; // 'RSW1'
|
||||
public const ushort FormatVersion = 1;
|
||||
public const uint BodyUnchanged = 0xFFFFFFFF;
|
||||
public const int MaxString = 4096;
|
||||
public const int MaxStr8 = 128;
|
||||
public const int MaxOps = 1500; // engine limit per window
|
||||
public const int MaxBodyBytes = 64 * 1024; // engine limit per window
|
||||
public const byte OpHasBlock = 1;
|
||||
|
||||
// Ops
|
||||
public const byte OpEnd = 0x00;
|
||||
public const byte OpText = 0x01;
|
||||
public const byte OpTextColored = 0x02;
|
||||
public const byte OpTextWrapped = 0x03;
|
||||
public const byte OpTextDisabled = 0x04;
|
||||
public const byte OpBulletText = 0x05;
|
||||
public const byte OpSeparatorText = 0x06;
|
||||
public const byte OpSeparator = 0x10;
|
||||
public const byte OpSameLine = 0x11;
|
||||
public const byte OpSpacing = 0x13;
|
||||
public const byte OpDummy = 0x14;
|
||||
public const byte OpIndent = 0x15;
|
||||
public const byte OpUnindent = 0x16;
|
||||
public const byte OpButton = 0x20;
|
||||
public const byte OpCheckbox = 0x21;
|
||||
public const byte OpSliderInt = 0x22;
|
||||
public const byte OpInputText = 0x24;
|
||||
public const byte OpCombo = 0x25;
|
||||
public const byte OpSelectable = 0x26;
|
||||
public const byte OpProgressBar = 0x27;
|
||||
public const byte OpImage = 0x28; // op level 2 (engines from 2026-09-30)
|
||||
public const byte OpImageButton = 0x29;
|
||||
public const byte OpPushID = 0x30;
|
||||
public const byte OpPopID = 0x31;
|
||||
public const byte OpPushStyleColor = 0x32;
|
||||
public const byte OpPopStyleColor = 0x33;
|
||||
public const byte OpSetItemTooltip = 0x38;
|
||||
public const byte OpChild = 0x40;
|
||||
public const byte OpCollapsingHeader = 0x41;
|
||||
|
||||
// Window flags
|
||||
public const uint FlagVisible = 1u << 0;
|
||||
public const uint FlagShowInBar = 1u << 1;
|
||||
/// <summary>With ShowInBar: a bar button of its own instead of a Scripts menu line (engines from
|
||||
/// 2026-10-11; older ones ignore it and list the window in the Scripts menu).</summary>
|
||||
public const uint FlagBarButton = 1u << 11;
|
||||
public const uint FlagNoScrollbar = 1u << 5;
|
||||
|
||||
// Image icon kinds (op level 2)
|
||||
public const byte IconKindIcon = 0; // a 0x06 texture id
|
||||
public const byte IconKindObject = 1; // a live object's icon with underlay and overlay
|
||||
|
||||
// Selectable flags
|
||||
public const uint SelectableAllowDoubleClick = 4;
|
||||
|
||||
// Event types
|
||||
public const ushort EvClicked = 1;
|
||||
public const ushort EvBool = 2;
|
||||
public const ushort EvInt = 3;
|
||||
public const ushort EvText = 5;
|
||||
public const ushort EvOpen = 6;
|
||||
public const ushort EvVisibility = 8;
|
||||
public const ushort EvError = 10;
|
||||
|
||||
// ImGuiCol ids the engine accepts in PushStyleColor (ImGui.NET 1.91.6.1)
|
||||
public const int ColText = 0;
|
||||
public const int ColButton = 21;
|
||||
public const int ColButtonActive = 23;
|
||||
public const int ColButtonHovered = 22;
|
||||
public const int ColHeader = 24;
|
||||
|
||||
// InputText flags
|
||||
public const uint InputAutoSelectAll = 4096;
|
||||
/// <summary>The text box reports Enter (its event carries submitted = true).</summary>
|
||||
public const uint InputEnterReturnsTrue = 32;
|
||||
|
||||
// CollapsingHeader flags
|
||||
public const uint TreeDefaultOpen = 32;
|
||||
|
||||
public static uint Fnv1a(ReadOnlySpan<byte> bytes, uint hash = 2166136261)
|
||||
{
|
||||
foreach (byte b in bytes)
|
||||
{
|
||||
hash ^= b;
|
||||
hash *= 16777619;
|
||||
}
|
||||
return hash;
|
||||
}
|
||||
|
||||
/// <summary>The length of <paramref name="s"/> cut to at most <paramref name="max"/> bytes without splitting a character.</summary>
|
||||
public static int CutUtf8(ReadOnlySpan<byte> s, int max)
|
||||
{
|
||||
if (s.Length <= max) return s.Length;
|
||||
int n = Math.Max(0, max);
|
||||
while (n > 0 && (s[n] & 0xC0) == 0x80) n--;
|
||||
return n;
|
||||
}
|
||||
|
||||
/// <summary>An ImGui U32 colour (0xAABBGGRR) from RGB bytes.</summary>
|
||||
public static uint Rgb(byte r, byte g, byte b, byte a = 255) =>
|
||||
((uint)a << 24) | ((uint)b << 16) | ((uint)g << 8) | r;
|
||||
}
|
||||
|
||||
/// <summary>Colours RynthDefective uses (0xAABBGGRR).</summary>
|
||||
internal static class UiColors
|
||||
{
|
||||
public static readonly uint Green = UiFormat.Rgb(110, 210, 110);
|
||||
public static readonly uint Red = UiFormat.Rgb(225, 95, 95);
|
||||
public static readonly uint Yellow = UiFormat.Rgb(235, 205, 90);
|
||||
public static readonly uint Grey = UiFormat.Rgb(150, 150, 150);
|
||||
public static readonly uint Gold = UiFormat.Rgb(230, 180, 60);
|
||||
/// <summary>Upstream's "destruction" highlight: deep pink brightened by half (255, 30, 220).</summary>
|
||||
public static readonly uint Destruction = UiFormat.Rgb(255, 30, 220);
|
||||
public static readonly uint TabActive = UiFormat.Rgb(60, 110, 170);
|
||||
public static readonly uint TabActiveHover = UiFormat.Rgb(75, 130, 195);
|
||||
public static readonly uint OtherServer = UiFormat.Rgb(150, 185, 235);
|
||||
public static readonly uint Stale = UiFormat.Rgb(225, 150, 80);
|
||||
public static readonly uint White = UiFormat.Rgb(255, 255, 255);
|
||||
/// <summary>The Lua script's amber (paused, full packs): 1.0, 0.75, 0.25.</summary>
|
||||
public static readonly uint Amber = UiFormat.Rgb(255, 191, 64);
|
||||
}
|
||||
202
Plugins/RynthCore.Plugin.RynthDefective/Ui/UiHost.cs
Normal file
202
Plugins/RynthCore.Plugin.RynthDefective/Ui/UiHost.cs
Normal file
|
|
@ -0,0 +1,202 @@
|
|||
using System;
|
||||
using System.Buffers.Binary;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
namespace RynthCore.Plugin.RynthDefective.Ui;
|
||||
|
||||
/// <summary>
|
||||
/// The plugin's side of the engine's script windows (API v71): polls the engine's events into
|
||||
/// the windows' handlers and submits the window set when something changed. Plugin pump thread
|
||||
/// only (inside the plugin's own tick), as the engine requires.
|
||||
/// </summary>
|
||||
internal sealed class UiHost
|
||||
{
|
||||
private readonly List<UiWindow> _windows = new();
|
||||
private readonly Dictionary<uint, UiWindow> _byHash = new();
|
||||
private byte[] _events = new byte[8192];
|
||||
private byte[] _submit = new byte[64 * 1024];
|
||||
private uint _lastSeq;
|
||||
private bool _submittedSomething;
|
||||
private long _retryAtMs;
|
||||
private long _lastErrorLogMs;
|
||||
|
||||
public Action<string>? Log;
|
||||
|
||||
public IReadOnlyList<UiWindow> Windows => _windows;
|
||||
|
||||
public UiWindow Add(UiWindow w)
|
||||
{
|
||||
_windows.Add(w);
|
||||
_byHash[w.Hash] = w;
|
||||
return w;
|
||||
}
|
||||
|
||||
/// <summary>Drains the engine's queued events into the windows' handlers.</summary>
|
||||
public void Poll(RynthCoreHost host)
|
||||
{
|
||||
if (!host.HasUi || !_submittedSomething) return;
|
||||
for (int round = 0; round < 8; round++)
|
||||
{
|
||||
int n = host.UiPollEvents(_events, out int remaining);
|
||||
if (n > 0) Apply(_events.AsSpan(0, n));
|
||||
if (remaining == 0) break;
|
||||
if (n == 0) Array.Resize(ref _events, _events.Length * 2); // one event didn't fit
|
||||
}
|
||||
}
|
||||
|
||||
private void Apply(ReadOnlySpan<byte> data)
|
||||
{
|
||||
int pos = 0;
|
||||
while (data.Length - pos >= 16)
|
||||
{
|
||||
ushort type = BinaryPrimitives.ReadUInt16LittleEndian(data[pos..]);
|
||||
int size = BinaryPrimitives.ReadUInt16LittleEndian(data[(pos + 2)..]);
|
||||
if (size < 16 || size > data.Length - pos) break;
|
||||
uint seq = BinaryPrimitives.ReadUInt32LittleEndian(data[(pos + 4)..]);
|
||||
uint window = BinaryPrimitives.ReadUInt32LittleEndian(data[(pos + 8)..]);
|
||||
uint key = BinaryPrimitives.ReadUInt32LittleEndian(data[(pos + 12)..]);
|
||||
ReadOnlySpan<byte> p = data.Slice(pos + 16, size - 16);
|
||||
pos += size;
|
||||
if (seq > _lastSeq) _lastSeq = seq;
|
||||
|
||||
_byHash.TryGetValue(window, out UiWindow? w);
|
||||
switch (type)
|
||||
{
|
||||
case UiFormat.EvClicked when w != null && p.Length >= 2:
|
||||
int count = BinaryPrimitives.ReadUInt16LittleEndian(p);
|
||||
for (int i = 0; i < Math.Min(count, 4); i++) w.Dispatch(key, new UiEvent(type));
|
||||
break;
|
||||
case UiFormat.EvBool when w != null && p.Length >= 1:
|
||||
w.Dispatch(key, new UiEvent(type, b: p[0] != 0));
|
||||
break;
|
||||
case UiFormat.EvInt when w != null && p.Length >= 4:
|
||||
w.Dispatch(key, new UiEvent(type, i: BinaryPrimitives.ReadInt32LittleEndian(p)));
|
||||
break;
|
||||
case UiFormat.EvText when w != null && p.Length >= 3:
|
||||
{
|
||||
int n = Math.Min(BinaryPrimitives.ReadUInt16LittleEndian(p[1..]), p.Length - 3);
|
||||
w.Dispatch(key, new UiEvent(type, text: Encoding.UTF8.GetString(p.Slice(3, n)), submitted: p[0] != 0));
|
||||
break;
|
||||
}
|
||||
case UiFormat.EvOpen when w != null && p.Length >= 1:
|
||||
w.Dispatch(key, new UiEvent(type, b: p[0] != 0));
|
||||
break;
|
||||
case UiFormat.EvVisibility when w != null && p.Length >= 1:
|
||||
// The player closed it (X) or opened it (bar menu / command): theirs wins.
|
||||
w.Visible = p[0] != 0;
|
||||
w.NeedsPass = true;
|
||||
break;
|
||||
case UiFormat.EvError when p.Length >= 2:
|
||||
{
|
||||
int n = Math.Min(BinaryPrimitives.ReadUInt16LittleEndian(p), p.Length - 2);
|
||||
Log?.Invoke("[RynthDefective] window error: " + Encoding.UTF8.GetString(p.Slice(2, n)));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Sends the window set when any window's list or header changed.</summary>
|
||||
public void Submit(RynthCoreHost host, long nowMs)
|
||||
{
|
||||
if (!host.HasUi || nowMs < _retryAtMs) return;
|
||||
bool changed = !_submittedSomething && _windows.Count > 0;
|
||||
foreach (UiWindow w in _windows)
|
||||
if (w.BodyDirty || w.HeaderDirty) { changed = true; break; }
|
||||
if (!changed) return;
|
||||
|
||||
int pos = Write();
|
||||
int rc = host.UiSubmit(_submit.AsSpan(0, pos));
|
||||
if (rc == 0)
|
||||
{
|
||||
foreach (UiWindow w in _windows) w.MarkSubmitted(w.BodyDirty);
|
||||
_submittedSomething = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Nothing was applied; the engine keeps the previous lists. Try again in a second.
|
||||
_retryAtMs = nowMs + 1000;
|
||||
if (nowMs - _lastErrorLogMs > 10_000)
|
||||
{
|
||||
_lastErrorLogMs = nowMs;
|
||||
Log?.Invoke($"[RynthDefective] the engine refused the window list ({rc}).");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Removes every window from the engine (logout, shutdown). Their placement is kept by the engine.</summary>
|
||||
public void SubmitEmpty(RynthCoreHost host)
|
||||
{
|
||||
if (!host.HasUi || !_submittedSomething) return;
|
||||
Span<byte> b = stackalloc byte[16];
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(b, UiFormat.Magic);
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(b[4..], UiFormat.FormatVersion);
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(b[6..], 0);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(b[8..], _lastSeq);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(b[12..], 16);
|
||||
if (host.UiSubmit(b) == 0)
|
||||
{
|
||||
_submittedSomething = false;
|
||||
foreach (UiWindow w in _windows) w.ForgetSubmitted();
|
||||
}
|
||||
}
|
||||
|
||||
private int Write()
|
||||
{
|
||||
int size = 16;
|
||||
foreach (UiWindow w in _windows) size += 2 * (1 + UiFormat.MaxStr8) + 4 + 32 + 8 + (w.BodyDirty ? w.Body.Length : 0);
|
||||
if (_submit.Length < size) _submit = new byte[Math.Max(size, _submit.Length * 2)];
|
||||
Span<byte> b = _submit;
|
||||
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(b, UiFormat.Magic);
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(b[4..], UiFormat.FormatVersion);
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(b[6..], (ushort)_windows.Count);
|
||||
// Every event polled so far has been applied (handlers run as they arrive).
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(b[8..], _lastSeq);
|
||||
int pos = 16;
|
||||
foreach (UiWindow w in _windows)
|
||||
{
|
||||
pos = Str8(b, pos, w.KeyUtf8);
|
||||
pos = Str8(b, pos, Encoding.UTF8.GetBytes(w.Title ?? string.Empty));
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(b[pos..], w.Flags); pos += 4;
|
||||
pos = F32(b, pos, w.DefaultWidth);
|
||||
pos = F32(b, pos, w.DefaultHeight);
|
||||
pos = F32(b, pos, w.MinWidth);
|
||||
pos = F32(b, pos, w.MinHeight);
|
||||
pos = F32(b, pos, w.RequestWidth); // RequestSize: a one-shot, else none
|
||||
pos = F32(b, pos, w.RequestHeight);
|
||||
pos = F32(b, pos, float.NaN); // RequestPos: none
|
||||
pos = F32(b, pos, float.NaN);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(b[pos..], w.ListSeq); pos += 4;
|
||||
if (w.BodyDirty)
|
||||
{
|
||||
ReadOnlySpan<byte> body = w.Body;
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(b[pos..], (uint)body.Length); pos += 4;
|
||||
body.CopyTo(b[pos..]);
|
||||
pos += body.Length;
|
||||
}
|
||||
else
|
||||
{
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(b[pos..], UiFormat.BodyUnchanged); pos += 4;
|
||||
}
|
||||
}
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(b[12..], (uint)pos);
|
||||
return pos;
|
||||
}
|
||||
|
||||
private static int Str8(Span<byte> b, int pos, ReadOnlySpan<byte> s)
|
||||
{
|
||||
int n = UiFormat.CutUtf8(s, UiFormat.MaxStr8);
|
||||
b[pos] = (byte)n;
|
||||
s[..n].CopyTo(b[(pos + 1)..]);
|
||||
return pos + 1 + n;
|
||||
}
|
||||
|
||||
private static int F32(Span<byte> b, int pos, float v)
|
||||
{
|
||||
BinaryPrimitives.WriteSingleLittleEndian(b[pos..], v);
|
||||
return pos + 4;
|
||||
}
|
||||
}
|
||||
543
Plugins/RynthCore.Plugin.RynthDefective/Ui/UiWindow.cs
Normal file
543
Plugins/RynthCore.Plugin.RynthDefective/Ui/UiWindow.cs
Normal file
|
|
@ -0,0 +1,543 @@
|
|||
using System;
|
||||
using System.Buffers.Binary;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace RynthCore.Plugin.RynthDefective.Ui;
|
||||
|
||||
/// <summary>One input from the engine for a widget (a click, a new value, an open state).</summary>
|
||||
internal readonly struct UiEvent
|
||||
{
|
||||
public readonly ushort Type;
|
||||
public readonly bool Bool;
|
||||
public readonly int Int;
|
||||
public readonly string Text;
|
||||
public readonly bool Submitted;
|
||||
|
||||
public UiEvent(ushort type, bool b = false, int i = 0, string? text = null, bool submitted = false)
|
||||
{
|
||||
Type = type;
|
||||
Bool = b;
|
||||
Int = i;
|
||||
Text = text ?? string.Empty;
|
||||
Submitted = submitted;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One script window (engine API v71) and its recorder. A render pass records ImGui-style calls
|
||||
/// into a display list; every widget's handler (click, value change) is kept by its widget key
|
||||
/// until the next pass, so an event from the engine runs the code that drew that widget.
|
||||
///
|
||||
/// Widget keys are FNV-1a(id, window hash): RynthDefective names every widget itself, so it needs
|
||||
/// no ID stack. ImGui sees "label###id": its ID comes from the id alone, so labels can change.
|
||||
/// The engine echoes the key in events and keys its per-widget local values by it.
|
||||
/// </summary>
|
||||
internal sealed class UiWindow
|
||||
{
|
||||
public readonly string Key;
|
||||
public readonly byte[] KeyUtf8;
|
||||
public readonly uint Hash;
|
||||
|
||||
public string Title;
|
||||
public bool Visible;
|
||||
public bool ShowInBar = true;
|
||||
/// <summary>With ShowInBar: the window has its own button on the RynthCore bar (title as the
|
||||
/// tooltip) rather than a line in the Scripts menu.</summary>
|
||||
public bool BarButton = true;
|
||||
public float DefaultWidth, DefaultHeight, MinWidth, MinHeight;
|
||||
|
||||
/// <summary>
|
||||
/// A one-shot request for the window's size (logical units; NaN = none). Sent with the next
|
||||
/// submit and then forgotten: the engine re-applies a standing request on every re-recorded
|
||||
/// list, which would undo the player's own resizing.
|
||||
/// </summary>
|
||||
public float RequestWidth = float.NaN, RequestHeight = float.NaN;
|
||||
|
||||
/// <summary>A pass is wanted at the next chance (input arrived, it was just shown, data changed).</summary>
|
||||
public bool NeedsPass = true;
|
||||
public long NextPassMs;
|
||||
|
||||
// The list as recorded by the last pass, and what the engine last accepted.
|
||||
private byte[] _body = new byte[16 * 1024];
|
||||
private int _len;
|
||||
private int _ops;
|
||||
private bool _cut;
|
||||
private byte[] _sentBody = Array.Empty<byte>();
|
||||
private int _sentLen = -1;
|
||||
public uint ListSeq { get; private set; }
|
||||
internal bool BodyDirty;
|
||||
|
||||
// Header as last accepted by the engine.
|
||||
private string? _sentTitle;
|
||||
private uint _sentFlags;
|
||||
private float _sentDw = float.NaN, _sentDh, _sentMw, _sentMh;
|
||||
|
||||
private Dictionary<uint, Action<UiEvent>> _handlers = new();
|
||||
private Dictionary<uint, Action<UiEvent>> _next = new();
|
||||
private readonly Dictionary<uint, bool> _openStates = new();
|
||||
|
||||
// Child blocks: where each open block's u32 length sits, or -1 when the block was dropped.
|
||||
private readonly int[] _blocks = new int[16];
|
||||
private int _blockDepth;
|
||||
private byte[] _tmp = new byte[512];
|
||||
|
||||
public UiWindow(string key, string title)
|
||||
{
|
||||
Key = key;
|
||||
KeyUtf8 = Encoding.UTF8.GetBytes(key);
|
||||
Hash = UiFormat.Fnv1a(KeyUtf8);
|
||||
Title = title;
|
||||
}
|
||||
|
||||
public uint Flags => (Visible ? UiFormat.FlagVisible : 0) | (ShowInBar ? UiFormat.FlagShowInBar : 0)
|
||||
| (ShowInBar && BarButton ? UiFormat.FlagBarButton : 0);
|
||||
|
||||
public bool HeaderDirty =>
|
||||
_sentTitle != Title || _sentFlags != Flags || _sentDw != DefaultWidth || _sentDh != DefaultHeight
|
||||
|| _sentMw != MinWidth || _sentMh != MinHeight || !float.IsNaN(RequestWidth);
|
||||
|
||||
public ReadOnlySpan<byte> Body => _body.AsSpan(0, _len);
|
||||
|
||||
// ── Pass ────────────────────────────────────────────────────────────────
|
||||
|
||||
public void Begin()
|
||||
{
|
||||
_len = 0;
|
||||
_ops = 0;
|
||||
_cut = false;
|
||||
_blockDepth = 0;
|
||||
_next.Clear();
|
||||
}
|
||||
|
||||
/// <summary>Ends the pass: closes open blocks, writes End, and notes whether the list changed.</summary>
|
||||
public void End()
|
||||
{
|
||||
while (_blockDepth > 0) EndChild();
|
||||
if (_cut)
|
||||
{
|
||||
// Room was kept for this line (see Room).
|
||||
int p = BeginOp(UiFormat.OpTextDisabled);
|
||||
Str("(more than fits in one window; narrow the list)");
|
||||
EndOp(p);
|
||||
}
|
||||
Ensure(4);
|
||||
_body[_len++] = UiFormat.OpEnd;
|
||||
_body[_len++] = 0;
|
||||
_body[_len++] = 0;
|
||||
_body[_len++] = 0;
|
||||
|
||||
(_handlers, _next) = (_next, _handlers);
|
||||
bool differs = _sentLen != _len || !_body.AsSpan(0, _len).SequenceEqual(_sentBody.AsSpan(0, _sentLen));
|
||||
if (differs && !BodyDirty) ListSeq++;
|
||||
BodyDirty = differs;
|
||||
}
|
||||
|
||||
/// <summary>The engine accepted the last submit: remember what it now has.</summary>
|
||||
internal void MarkSubmitted(bool bodySent)
|
||||
{
|
||||
if (bodySent)
|
||||
{
|
||||
if (_sentBody.Length < _len) _sentBody = new byte[_body.Length];
|
||||
_body.AsSpan(0, _len).CopyTo(_sentBody);
|
||||
_sentLen = _len;
|
||||
BodyDirty = false;
|
||||
}
|
||||
_sentTitle = Title;
|
||||
_sentFlags = Flags;
|
||||
_sentDw = DefaultWidth; _sentDh = DefaultHeight; _sentMw = MinWidth; _sentMh = MinHeight;
|
||||
RequestWidth = RequestHeight = float.NaN; // sent once
|
||||
}
|
||||
|
||||
/// <summary>The engine dropped every window (logout, empty submit): send everything again next time.</summary>
|
||||
internal void ForgetSubmitted()
|
||||
{
|
||||
_sentLen = -1;
|
||||
_sentTitle = null;
|
||||
BodyDirty = _len > 0;
|
||||
}
|
||||
|
||||
internal void Dispatch(uint widgetKey, in UiEvent e)
|
||||
{
|
||||
if (_handlers.TryGetValue(widgetKey, out Action<UiEvent>? h))
|
||||
h(e);
|
||||
NeedsPass = true;
|
||||
}
|
||||
|
||||
// ── Widgets ─────────────────────────────────────────────────────────────
|
||||
|
||||
public uint KeyOf(string id)
|
||||
{
|
||||
int max = Encoding.UTF8.GetMaxByteCount(id.Length);
|
||||
if (_tmp.Length < max) _tmp = new byte[Math.Max(max, _tmp.Length * 2)];
|
||||
int n = Encoding.UTF8.GetBytes(id, _tmp);
|
||||
return UiFormat.Fnv1a(_tmp.AsSpan(0, n), Hash);
|
||||
}
|
||||
|
||||
public void Text(string text) => WriteText(UiFormat.OpText, text);
|
||||
public void TextDisabled(string text) => WriteText(UiFormat.OpTextDisabled, text);
|
||||
public void TextWrapped(string text) => WriteText(UiFormat.OpTextWrapped, text);
|
||||
public void BulletText(string text) => WriteText(UiFormat.OpBulletText, text);
|
||||
public void SeparatorText(string text) => WriteText(UiFormat.OpSeparatorText, text);
|
||||
|
||||
public void TextColored(uint abgr, string text)
|
||||
{
|
||||
if (!Room()) return;
|
||||
int p = BeginOp(UiFormat.OpTextColored);
|
||||
U32(abgr);
|
||||
Str(text);
|
||||
EndOp(p);
|
||||
}
|
||||
|
||||
public void Separator()
|
||||
{
|
||||
if (!Room()) return;
|
||||
EndOp(BeginOp(UiFormat.OpSeparator));
|
||||
}
|
||||
|
||||
public void Spacing()
|
||||
{
|
||||
if (!Room()) return;
|
||||
EndOp(BeginOp(UiFormat.OpSpacing));
|
||||
}
|
||||
|
||||
/// <summary>Next item on the same line, <paramref name="x"/> logical units from the content start (0 = right after).</summary>
|
||||
public void SameLine(float x = 0f, float spacing = -1f)
|
||||
{
|
||||
if (!Room()) return;
|
||||
int p = BeginOp(UiFormat.OpSameLine);
|
||||
F32(x);
|
||||
F32(spacing);
|
||||
EndOp(p);
|
||||
}
|
||||
|
||||
public void Dummy(float w, float h)
|
||||
{
|
||||
if (!Room()) return;
|
||||
int p = BeginOp(UiFormat.OpDummy);
|
||||
F32(w);
|
||||
F32(h);
|
||||
EndOp(p);
|
||||
}
|
||||
|
||||
/// <summary>Moves the following items right by <paramref name="w"/> logical units, until <see cref="Unindent"/>.</summary>
|
||||
public void Indent(float w)
|
||||
{
|
||||
if (!Room()) return;
|
||||
int p = BeginOp(UiFormat.OpIndent);
|
||||
F32(w);
|
||||
EndOp(p);
|
||||
}
|
||||
|
||||
public void Unindent(float w)
|
||||
{
|
||||
if (!Room()) return;
|
||||
int p = BeginOp(UiFormat.OpUnindent);
|
||||
F32(w);
|
||||
EndOp(p);
|
||||
}
|
||||
|
||||
public void Button(string label, string id, Action onClick, float w = 0f, float h = 0f, bool small = false)
|
||||
{
|
||||
if (!Room()) return;
|
||||
uint key = KeyOf(id);
|
||||
int p = BeginOp(UiFormat.OpButton);
|
||||
U32(key);
|
||||
Str(label + "###" + id);
|
||||
F32(w);
|
||||
F32(h);
|
||||
U8(small ? (byte)1 : (byte)0);
|
||||
EndOp(p);
|
||||
_next[key] = e => { if (e.Type == UiFormat.EvClicked) onClick(); };
|
||||
}
|
||||
|
||||
public void SmallButton(string label, string id, Action onClick) => Button(label, id, onClick, small: true);
|
||||
|
||||
/// <summary>A button drawn highlighted when <paramref name="active"/> (tabs, toggles).</summary>
|
||||
public void ToggleButton(string label, string id, bool active, Action onClick, bool small = false)
|
||||
{
|
||||
if (active)
|
||||
{
|
||||
PushStyleColor(UiFormat.ColButton, UiColors.TabActive);
|
||||
PushStyleColor(UiFormat.ColButtonHovered, UiColors.TabActiveHover);
|
||||
}
|
||||
Button(label, id, onClick, small: small);
|
||||
if (active) PopStyleColor(2);
|
||||
}
|
||||
|
||||
public void Checkbox(string label, string id, bool value, Action<bool> set)
|
||||
{
|
||||
if (!Room()) return;
|
||||
uint key = KeyOf(id);
|
||||
int p = BeginOp(UiFormat.OpCheckbox);
|
||||
U32(key);
|
||||
Str(label + "###" + id);
|
||||
U8(value ? (byte)1 : (byte)0);
|
||||
EndOp(p);
|
||||
_next[key] = e => { if (e.Type == UiFormat.EvBool) set(e.Bool); };
|
||||
}
|
||||
|
||||
/// <summary>An integer slider from <paramref name="min"/> to <paramref name="max"/> (clamped by the engine).</summary>
|
||||
public void SliderInt(string label, string id, int value, int min, int max, Action<int> set, string format = "%d")
|
||||
{
|
||||
if (!Room()) return;
|
||||
uint key = KeyOf(id);
|
||||
int p = BeginOp(UiFormat.OpSliderInt);
|
||||
U32(key);
|
||||
Str(label + "###" + id);
|
||||
I32(value);
|
||||
I32(min);
|
||||
I32(max);
|
||||
Str(format);
|
||||
EndOp(p);
|
||||
_next[key] = e => { if (e.Type == UiFormat.EvInt) set(Math.Clamp(e.Int, min, max)); };
|
||||
}
|
||||
|
||||
/// <summary>A text box; <paramref name="set"/> gets every edit (submitted = Enter was pressed).</summary>
|
||||
public void InputText(string label, string id, string value, int maxLen, Action<string> set, uint flags = 0) =>
|
||||
InputText(label, id, value, maxLen, (text, _) => set(text), flags);
|
||||
|
||||
/// <summary>A text box; <paramref name="set"/> gets every edit and whether Enter was pressed.</summary>
|
||||
public void InputText(string label, string id, string value, int maxLen, Action<string, bool> set, uint flags = 0)
|
||||
{
|
||||
if (!Room()) return;
|
||||
maxLen = Math.Clamp(maxLen, 1, UiFormat.MaxString);
|
||||
uint key = KeyOf(id);
|
||||
int p = BeginOp(UiFormat.OpInputText);
|
||||
U32(key);
|
||||
Str(label + "###" + id);
|
||||
Str(value ?? string.Empty, maxLen);
|
||||
U16((ushort)maxLen);
|
||||
U32(flags);
|
||||
EndOp(p);
|
||||
_next[key] = e => { if (e.Type == UiFormat.EvText) set(e.Text, e.Submitted); };
|
||||
}
|
||||
|
||||
public void Combo(string label, string id, int index, IReadOnlyList<string> items, Action<int> set)
|
||||
{
|
||||
if (!Room()) return;
|
||||
uint key = KeyOf(id);
|
||||
int count = Math.Min(items.Count, 512);
|
||||
int p = BeginOp(UiFormat.OpCombo);
|
||||
U32(key);
|
||||
Str(label + "###" + id);
|
||||
I32(index);
|
||||
U16((ushort)count);
|
||||
for (int i = 0; i < count; i++) Str(items[i]);
|
||||
EndOp(p);
|
||||
_next[key] = e => { if (e.Type == UiFormat.EvInt) set(e.Int); };
|
||||
}
|
||||
|
||||
public void Selectable(string label, string id, bool selected, Action onClick, float w = 0f, float h = 0f)
|
||||
{
|
||||
if (!Room()) return;
|
||||
uint key = KeyOf(id);
|
||||
int p = BeginOp(UiFormat.OpSelectable);
|
||||
U32(key);
|
||||
Str(label + "###" + id);
|
||||
U8(selected ? (byte)1 : (byte)0);
|
||||
U32(0);
|
||||
F32(w);
|
||||
F32(h);
|
||||
EndOp(p);
|
||||
_next[key] = e => { if (e.Type == UiFormat.EvClicked) onClick(); };
|
||||
}
|
||||
|
||||
public void ProgressBar(float fraction, float w, float h, string overlay)
|
||||
{
|
||||
if (!Room()) return;
|
||||
int p = BeginOp(UiFormat.OpProgressBar);
|
||||
F32(float.IsFinite(fraction) ? Math.Clamp(fraction, 0f, 1f) : 0f);
|
||||
F32(w);
|
||||
F32(h);
|
||||
Str(overlay ?? string.Empty);
|
||||
EndOp(p);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An icon (op level 2): <paramref name="kind"/> <see cref="UiFormat.IconKindIcon"/> = a 0x06
|
||||
/// texture id, <see cref="UiFormat.IconKindObject"/> = a live object (its icon with underlay and
|
||||
/// overlay). Engines without op level 2 skip it (the caller checks first so the layout doesn't shift).
|
||||
/// </summary>
|
||||
public void Image(byte kind, uint id, float w, float h, uint tint = 0xFFFFFFFFu)
|
||||
{
|
||||
if (!Room()) return;
|
||||
int p = BeginOp(UiFormat.OpImage);
|
||||
U8(kind);
|
||||
U32(id);
|
||||
F32(w);
|
||||
F32(h);
|
||||
F32(0f); F32(0f); // uv0
|
||||
F32(1f); F32(1f); // uv1
|
||||
U32(tint);
|
||||
U32(0u); // border: none
|
||||
EndOp(p);
|
||||
}
|
||||
|
||||
/// <summary>A button with an icon on it (op level 2); <paramref name="tint"/> dims or colours the picture, <paramref name="background"/> fills behind it.</summary>
|
||||
public void ImageButton(byte kind, uint iconId, string id, Action onClick, float w, float h, uint tint = 0xFFFFFFFFu, uint background = 0u)
|
||||
{
|
||||
if (!Room()) return;
|
||||
uint key = KeyOf(id);
|
||||
int p = BeginOp(UiFormat.OpImageButton);
|
||||
U32(key);
|
||||
Str(id);
|
||||
U8(kind);
|
||||
U32(iconId);
|
||||
F32(w);
|
||||
F32(h);
|
||||
F32(0f); F32(0f); // uv0
|
||||
F32(1f); F32(1f); // uv1
|
||||
U32(background); // background fill behind the picture (0 = none)
|
||||
U32(tint);
|
||||
EndOp(p);
|
||||
_next[key] = e => { if (e.Type == UiFormat.EvClicked) onClick(); };
|
||||
}
|
||||
|
||||
/// <summary>Tooltip for the item just drawn.</summary>
|
||||
public void Tooltip(string text)
|
||||
{
|
||||
if (!Room() || string.IsNullOrEmpty(text)) return;
|
||||
int p = BeginOp(UiFormat.OpSetItemTooltip);
|
||||
Str(text);
|
||||
EndOp(p);
|
||||
}
|
||||
|
||||
public void PushStyleColor(int colId, uint abgr)
|
||||
{
|
||||
if (!Room()) return;
|
||||
int p = BeginOp(UiFormat.OpPushStyleColor);
|
||||
U16((ushort)colId);
|
||||
U32(abgr);
|
||||
EndOp(p);
|
||||
}
|
||||
|
||||
/// <summary>Pops are dropped when the list is cut short; the engine pops leftovers at the scope's end.</summary>
|
||||
public void PopStyleColor(int count = 1)
|
||||
{
|
||||
if (!Room()) return;
|
||||
int p = BeginOp(UiFormat.OpPopStyleColor);
|
||||
U8((byte)Math.Clamp(count, 1, 255));
|
||||
EndOp(p);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A collapsing header; returns whether to record its contents. The open state is the
|
||||
/// player's (kept from the engine's Open events), so a header stays as they left it.
|
||||
/// </summary>
|
||||
public bool CollapsingHeader(string label, string id, bool defaultOpen = false)
|
||||
{
|
||||
uint key = KeyOf(id);
|
||||
bool open = _openStates.TryGetValue(key, out bool o) ? o : defaultOpen;
|
||||
if (!Room()) return false;
|
||||
int p = BeginOp(UiFormat.OpCollapsingHeader);
|
||||
U32(key);
|
||||
Str(label + "###" + id);
|
||||
U32(defaultOpen ? UiFormat.TreeDefaultOpen : 0);
|
||||
U8(open ? (byte)1 : (byte)0);
|
||||
EndOp(p);
|
||||
_next[key] = e => { if (e.Type == UiFormat.EvOpen) _openStates[key] = e.Bool; };
|
||||
return open;
|
||||
}
|
||||
|
||||
/// <summary>A scrolling region; h 0 = fill the rest of the window. Must be closed with <see cref="EndChild"/>.</summary>
|
||||
public void BeginChild(string id, float w = 0f, float h = 0f, bool border = true)
|
||||
{
|
||||
if (_blockDepth >= _blocks.Length) throw new InvalidOperationException("child regions nested too deep");
|
||||
if (!Room())
|
||||
{
|
||||
_blocks[_blockDepth++] = -1;
|
||||
return;
|
||||
}
|
||||
uint key = KeyOf(id);
|
||||
int p = BeginOp(UiFormat.OpChild, UiFormat.OpHasBlock);
|
||||
U32(key);
|
||||
Str(id);
|
||||
F32(w);
|
||||
F32(h);
|
||||
U8(border ? (byte)1 : (byte)0);
|
||||
U32(0);
|
||||
EndOp(p);
|
||||
_blocks[_blockDepth++] = _len;
|
||||
U32(0); // BlockLength, patched by EndChild
|
||||
}
|
||||
|
||||
public void EndChild()
|
||||
{
|
||||
if (_blockDepth == 0) return;
|
||||
int at = _blocks[--_blockDepth];
|
||||
if (at < 0) return;
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(_body.AsSpan(at), (uint)(_len - (at + 4)));
|
||||
}
|
||||
|
||||
// ── Writing ─────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Whether another op fits. Room is kept for the closing "list cut short" line and the End
|
||||
/// op, so the list never goes over the engine's limits (it refuses an over-limit list whole).
|
||||
/// </summary>
|
||||
private bool Room()
|
||||
{
|
||||
if (_cut) return false;
|
||||
if (_ops < UiFormat.MaxOps - 8 && _len < UiFormat.MaxBodyBytes - 4096) return true;
|
||||
_cut = true;
|
||||
return false;
|
||||
}
|
||||
|
||||
private void WriteText(byte code, string text)
|
||||
{
|
||||
if (!Room()) return;
|
||||
int p = BeginOp(code);
|
||||
Str(text);
|
||||
EndOp(p);
|
||||
}
|
||||
|
||||
private int BeginOp(byte code, byte opFlags = 0)
|
||||
{
|
||||
_ops++;
|
||||
Ensure(4);
|
||||
_body[_len++] = code;
|
||||
_body[_len++] = opFlags;
|
||||
_len += 2; // PayloadLength, patched by EndOp
|
||||
return _len;
|
||||
}
|
||||
|
||||
private void EndOp(int payloadStart)
|
||||
{
|
||||
int length = _len - payloadStart;
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(_body.AsSpan(payloadStart - 2), (ushort)Math.Min(length, ushort.MaxValue));
|
||||
}
|
||||
|
||||
private void Ensure(int extra)
|
||||
{
|
||||
if (_len + extra <= _body.Length) return;
|
||||
int size = _body.Length;
|
||||
while (size < _len + extra) size *= 2;
|
||||
Array.Resize(ref _body, size);
|
||||
}
|
||||
|
||||
private void U8(byte v) { Ensure(1); _body[_len++] = v; }
|
||||
private void U16(ushort v) { Ensure(2); BinaryPrimitives.WriteUInt16LittleEndian(_body.AsSpan(_len), v); _len += 2; }
|
||||
private void U32(uint v) { Ensure(4); BinaryPrimitives.WriteUInt32LittleEndian(_body.AsSpan(_len), v); _len += 4; }
|
||||
private void I32(int v) { Ensure(4); BinaryPrimitives.WriteInt32LittleEndian(_body.AsSpan(_len), v); _len += 4; }
|
||||
|
||||
private void F32(float v)
|
||||
{
|
||||
Ensure(4);
|
||||
BinaryPrimitives.WriteSingleLittleEndian(_body.AsSpan(_len), float.IsFinite(v) ? v : 0f);
|
||||
_len += 4;
|
||||
}
|
||||
|
||||
/// <summary>str: u16 length + UTF-8, cut to <paramref name="maxBytes"/> on a character boundary.</summary>
|
||||
private void Str(string s, int maxBytes = UiFormat.MaxString)
|
||||
{
|
||||
s ??= string.Empty;
|
||||
ReadOnlySpan<char> src = s.Length > maxBytes ? s.AsSpan(0, maxBytes) : s.AsSpan();
|
||||
Ensure(2 + Encoding.UTF8.GetMaxByteCount(src.Length));
|
||||
int at = _len + 2;
|
||||
Span<byte> dst = _body.AsSpan(at);
|
||||
int n = UiFormat.CutUtf8(dst[..Encoding.UTF8.GetBytes(src, dst)], maxBytes);
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(_body.AsSpan(_len), (ushort)n);
|
||||
_len = at + n;
|
||||
}
|
||||
}
|
||||
126
Plugins/RynthCore.Plugin.RynthDefective/Use/HostDefWorld.cs
Normal file
126
Plugins/RynthCore.Plugin.RynthDefective/Use/HostDefWorld.cs
Normal file
|
|
@ -0,0 +1,126 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text.Json;
|
||||
using RynthCore.Plugin.RynthDefective.Items;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
namespace RynthCore.Plugin.RynthDefective.Use;
|
||||
|
||||
/// <summary>
|
||||
/// The controller's view of the game through the engine host. Plugin pump thread only (the
|
||||
/// plugin's tick), which is also where RynthAi's interfaces may be called.
|
||||
/// </summary>
|
||||
internal sealed unsafe class HostDefWorld : IDefWorld
|
||||
{
|
||||
private const long SnapshotMaxAgeMs = 250;
|
||||
|
||||
private readonly RynthCoreHost _host;
|
||||
private readonly HostInventory _reader = new();
|
||||
private List<CarriedItem> _items = new();
|
||||
private long _itemsAtMs = long.MinValue / 4;
|
||||
private int _revision;
|
||||
|
||||
public HostDefWorld(RynthCoreHost host) => _host = host;
|
||||
|
||||
public long NowMs => Environment.TickCount64;
|
||||
|
||||
public bool InWorld => _host.HasGetPlayerId && _host.GetPlayerId() != 0 && !(_host.HasIsPortaling && _host.IsPortaling());
|
||||
public uint PlayerId => _host.HasGetPlayerId ? _host.GetPlayerId() : 0;
|
||||
public uint SelectedId => _host.HasGetSelectedItemId ? _host.GetSelectedItemId() : 0;
|
||||
public bool ClientBusy => _host.HasGetBusyState && _host.GetBusyState() != 0;
|
||||
public bool Animating => _host.HasGetCastBusyState && _host.GetCastBusyState() != 0;
|
||||
public int UseDoneSeq => _host.HasUseDoneSeq ? _host.GetUseDoneSeq() : 0;
|
||||
public int CombatMode => _host.GetCurrentCombatMode();
|
||||
|
||||
public bool? BotWaitingOnServer => BotActivity.Read(_host) is { } a ? (a & RynthAiActivity.ServerAction) != 0 : null;
|
||||
public bool? BotMacroRunning => BotActivity.Read(_host) is { } a ? (a & RynthAiActivity.MacroRunning) != 0 : null;
|
||||
|
||||
public int RefusalSeq => _host.HasGetLastWeenieError && _host.TryGetLastWeenieError(out int seq, out _, out _, out _) ? seq : 0;
|
||||
|
||||
public bool RefusalNamed(uint objectId) =>
|
||||
_host.HasGetLastWeenieError && _host.TryGetLastWeenieError(out _, out _, out _, out uint obj) && obj == objectId;
|
||||
|
||||
/// <summary>The inventory, re-read when it is older than a quarter second.</summary>
|
||||
public IReadOnlyList<CarriedItem> Items() => Snapshot(SnapshotMaxAgeMs);
|
||||
|
||||
/// <summary>The inventory, re-read when it is older than <paramref name="maxAgeMs"/>.</summary>
|
||||
public List<CarriedItem> Snapshot(long maxAgeMs)
|
||||
{
|
||||
long now = NowMs;
|
||||
if (now - _itemsAtMs >= maxAgeMs)
|
||||
{
|
||||
_items = _reader.Read(_host, now);
|
||||
_itemsAtMs = now;
|
||||
_revision++;
|
||||
}
|
||||
return _items;
|
||||
}
|
||||
|
||||
/// <summary>Counts re-reads (the plugin redraws and re-binds slots when it moved).</summary>
|
||||
public int Revision => _revision;
|
||||
|
||||
public CarriedItem? Live(uint id) => _reader.ReadOne(_host, id, NowMs);
|
||||
|
||||
public bool UseObject(uint id) => _host.HasUseObject && _host.UseObject(id);
|
||||
public bool UseObjectOn(uint id, uint target) => _host.HasUseObjectOn && _host.UseObjectOn(id, target);
|
||||
public bool SetCombatMode(int mode) => _host.HasChangeCombatMode && _host.ChangeCombatMode(mode);
|
||||
|
||||
public void Reset()
|
||||
{
|
||||
_reader.Reset();
|
||||
_items = new List<CarriedItem>();
|
||||
_itemsAtMs = long.MinValue / 4;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// RynthAi's activity bits: its "RynthAi.Activity" interface; on an older RynthAi without it, the
|
||||
/// macro bit from "RynthAi.Status"; null when RynthAi isn't loaded or not ready. Resolved again every
|
||||
/// call: a RynthAi reload frees the tables. Read only: nothing here changes what RynthAi does.
|
||||
/// </summary>
|
||||
internal static unsafe class BotActivity
|
||||
{
|
||||
public static RynthAiActivity? Read(RynthCoreHost host)
|
||||
{
|
||||
if (!host.HasGetPluginInterface) return null;
|
||||
try
|
||||
{
|
||||
var act = (RynthAiActivityApiV1*)host.GetPluginInterface("RynthAi", RynthAiActivityApiV1.InterfaceName, RynthAiActivityApiV1.InterfaceVersion);
|
||||
if (act != null && act->Version >= 1 && act->StructSize >= (uint)sizeof(RynthAiActivityApiV1) && act->GetActivityFlags != null)
|
||||
{
|
||||
uint flags = 0;
|
||||
return act->GetActivityFlags(&flags) != 0 ? (RynthAiActivity)flags : null;
|
||||
}
|
||||
var status = (RynthAiStatusApiV1*)host.GetPluginInterface("RynthAi", RynthAiStatusApiV1.InterfaceName, RynthAiStatusApiV1.InterfaceVersion);
|
||||
if (status != null && status->Version >= 1 && status->StructSize >= (uint)sizeof(RynthAiStatusApiV1) && status->GetStatusJson != null)
|
||||
{
|
||||
byte* r = null;
|
||||
if (status->GetStatusJson(&r) != 0 && r != null)
|
||||
return FromStatusJson(Marshal.PtrToStringUTF8((IntPtr)r));
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// A RynthAi mid-reload: treat as not there this tick.
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>The macro bit an older RynthAi's status JSON ({macro, action, ...}) gives (no server-wait bit).</summary>
|
||||
internal static RynthAiActivity? FromStatusJson(string? json)
|
||||
{
|
||||
if (string.IsNullOrEmpty(json) || json[0] != '{') return null;
|
||||
try
|
||||
{
|
||||
using JsonDocument doc = JsonDocument.Parse(json);
|
||||
bool macro = doc.RootElement.TryGetProperty("macro", out JsonElement m) && m.ValueKind == JsonValueKind.True;
|
||||
return macro ? RynthAiActivity.MacroRunning : RynthAiActivity.None;
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
382
Plugins/RynthCore.Plugin.RynthDefective/Use/UseController.cs
Normal file
382
Plugins/RynthCore.Plugin.RynthDefective/Use/UseController.cs
Normal file
|
|
@ -0,0 +1,382 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using RynthCore.Plugin.RynthDefective.Items;
|
||||
using RynthCore.Plugin.RynthDefective.Model;
|
||||
|
||||
namespace RynthCore.Plugin.RynthDefective.Use;
|
||||
|
||||
/// <summary>
|
||||
/// What the controller needs from the game. The host implements it (HostDefWorld); the tests
|
||||
/// script it. Plugin pump thread only.
|
||||
/// </summary>
|
||||
internal interface IDefWorld
|
||||
{
|
||||
long NowMs { get; }
|
||||
/// <summary>A character is in the world and not in portal space.</summary>
|
||||
bool InWorld { get; }
|
||||
uint PlayerId { get; }
|
||||
uint SelectedId { get; }
|
||||
/// <summary>The client's busy count is above zero (an item action it sent has not been answered).</summary>
|
||||
bool ClientBusy { get; }
|
||||
/// <summary>A cast or use gesture is animating.</summary>
|
||||
bool Animating { get; }
|
||||
/// <summary>RynthAi is waiting on the server for an action it sent (null = RynthAi isn't there).</summary>
|
||||
bool? BotWaitingOnServer { get; }
|
||||
/// <summary>RynthAi's macro is running (null = RynthAi isn't there).</summary>
|
||||
bool? BotMacroRunning { get; }
|
||||
/// <summary>Count of the server's UseDone events; 0 when the engine can't report them.</summary>
|
||||
int UseDoneSeq { get; }
|
||||
/// <summary>1 NonCombat, 2 Melee, 4 Missile, 8 Magic.</summary>
|
||||
int CombatMode { get; }
|
||||
/// <summary>The server's refusals so far (0x028A / 0x00A0 ... count), to tell a new one.</summary>
|
||||
int RefusalSeq { get; }
|
||||
/// <summary>The newest refusal named this object (a refused wield: InventoryServerSaveFailed).</summary>
|
||||
bool RefusalNamed(uint objectId);
|
||||
|
||||
/// <summary>Everything carried and worn, as the client has it now.</summary>
|
||||
IReadOnlyList<CarriedItem> Items();
|
||||
/// <summary>The item as the client has it this instant (wielded or not); null if it is gone.</summary>
|
||||
CarriedItem? Live(uint id);
|
||||
|
||||
bool UseObject(uint id);
|
||||
bool UseObjectOn(uint id, uint target);
|
||||
bool SetCombatMode(int mode);
|
||||
}
|
||||
|
||||
/// <summary>One thing the player asked to use: an exact item (a slot's) or a name typed in a command.</summary>
|
||||
internal sealed record UseRequest(ItemRef? Item, string? Name, UseMode Mode, string Source, long AtMs)
|
||||
{
|
||||
/// <summary>Same item, same way: pressing the key again must not queue a second one.</summary>
|
||||
public bool SameAs(UseRequest o) =>
|
||||
Mode == o.Mode
|
||||
&& ((Item != null && o.Item != null && Item.SameAs(o.Item))
|
||||
|| (Name != null && o.Name != null && string.Equals(Name, o.Name, StringComparison.OrdinalIgnoreCase)));
|
||||
|
||||
public string Label => Item?.FullName ?? Name ?? "item";
|
||||
}
|
||||
|
||||
/// <summary>The combat stance a weapon swap leaves the character in.</summary>
|
||||
internal static class Stance
|
||||
{
|
||||
public const int NonCombat = 1, Melee = 2, Missile = 4, Magic = 8;
|
||||
|
||||
/// <summary>
|
||||
/// The stance to ask for after <paramref name="weapon"/> was wielded, 0 = leave it alone.
|
||||
/// A character at peace stays at peace. One in a fighting stance goes to the new weapon's:
|
||||
/// Melee, Missile (a launcher needs its ammunition in hand: without it the client refuses the
|
||||
/// stance, so the character goes to peace rather than being left in a stance the weapon can't
|
||||
/// use), or Magic for a caster. Shields, armor and ammunition keep the stance they are in.
|
||||
/// </summary>
|
||||
public static int Wanted(ItemKind kind, bool launcherNeedsAmmo, bool ammoInHand, int modeBefore)
|
||||
{
|
||||
if (modeBefore == NonCombat || modeBefore == 0) return 0;
|
||||
switch (kind)
|
||||
{
|
||||
case ItemKind.Melee: return Melee;
|
||||
case ItemKind.WarWand:
|
||||
case ItemKind.VoidWand: return Magic;
|
||||
case ItemKind.Missile: return launcherNeedsAmmo && !ammoInHand ? NonCombat : Missile;
|
||||
default: return 0;
|
||||
}
|
||||
}
|
||||
|
||||
public static string Name(int mode) => mode switch
|
||||
{
|
||||
NonCombat => "peace",
|
||||
Melee => "melee",
|
||||
Missile => "missile",
|
||||
Magic => "magic",
|
||||
_ => "mode " + mode,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One use at a time. A request (a slot pressed, /rdef use, the picker) is held until the
|
||||
/// character is free, then sent; the next waits for the server's answer. A second request while one
|
||||
/// is waiting replaces it (the newest wish wins) unless it is the same one (a key held down does
|
||||
/// not queue twice). Nothing is retried in a loop: a refused or unanswered action is reported once.
|
||||
///
|
||||
/// What is sent (the host calls RynthAi's own one-touch heal and weapon swap use):
|
||||
/// kits UseObjectOn(kit, you) answered by the server's UseDone
|
||||
/// consumables UseObject(item) answered by UseDone
|
||||
/// weapons etc. UseObject(item): the client's double-click, which takes what is in the way off;
|
||||
/// answered when the item reads wielded (a wield sends no UseDone), then the stance
|
||||
/// is put right (<see cref="Stance.Wanted"/>) once the character is still.
|
||||
/// Busy: nothing is sent while the client's busy count is up, a gesture animates, RynthAi waits on
|
||||
/// the server, the last action is unanswered, or for <see cref="MinGapMs"/> after it - the "one item
|
||||
/// action at a time" rule RynthAi's ActionPacer keeps. Weapon swaps also wait out a running RynthAi
|
||||
/// macro unless the player allowed them (it would swap straight back).
|
||||
/// </summary>
|
||||
internal sealed class UseController
|
||||
{
|
||||
/// <summary>How long a request waits for the character to be free before it gives up and says why.</summary>
|
||||
public const long WaitLimitMs = 6000;
|
||||
/// <summary>A use with no UseDone by now is let go (RynthAi waits 8 s for a kit's result).</summary>
|
||||
public const long UseTimeoutMs = 8000;
|
||||
/// <summary>A use the client no longer holds busy, with no UseDone, is let go after this.</summary>
|
||||
public const long UseQuietMs = 1500;
|
||||
public const long WieldTimeoutMs = 3500;
|
||||
public const long MinGapMs = 250;
|
||||
public const long StanceSettleMs = 500;
|
||||
public const long StanceTimeoutMs = 4000;
|
||||
|
||||
private enum Stage { Sent, WaitWield, Stance }
|
||||
|
||||
private sealed class Flight
|
||||
{
|
||||
public UseRequest Request = null!;
|
||||
public CarriedItem Item = null!;
|
||||
public UseAction Action;
|
||||
public ItemKind Kind;
|
||||
public long SentMs;
|
||||
public int UseDoneAtSend, RefusalAtSend, ModeBefore;
|
||||
public Stage Stage;
|
||||
public long StageMs;
|
||||
}
|
||||
|
||||
private UseRequest? _pending;
|
||||
private Flight? _flight;
|
||||
private long _lastDoneMs = long.MinValue / 4;
|
||||
private string _lastWait = string.Empty;
|
||||
|
||||
/// <summary>Plain information ("Using Peerless Healing Kit ..."): the status line, not the chat.</summary>
|
||||
public Action<string>? Say;
|
||||
/// <summary>Something went wrong or didn't happen: the status line and the chat.</summary>
|
||||
public Action<string>? Warn;
|
||||
public Action<string>? Log;
|
||||
/// <summary>A weapon was wielded (the picker's recent list).</summary>
|
||||
public Action<CarriedItem>? Wielded;
|
||||
|
||||
public bool HasPending => _pending != null;
|
||||
public bool InFlight => _flight != null;
|
||||
public UseRequest? Pending => _pending;
|
||||
|
||||
/// <summary>The item a request in flight or waiting is about, for highlighting its slot.</summary>
|
||||
public bool Involves(ItemRef r) =>
|
||||
(_pending?.Item != null && _pending.Item.SameAs(r)) || (_flight?.Request.Item != null && _flight.Request.Item.SameAs(r));
|
||||
|
||||
public DefSettings Settings = new();
|
||||
|
||||
/// <summary>Queues a request. False when it is the one already waiting or in flight (a held key).</summary>
|
||||
public bool Request(UseRequest r)
|
||||
{
|
||||
if (_pending != null && _pending.SameAs(r)) return false;
|
||||
if (_flight != null && _flight.Action == UseAction.Equip && _flight.Request.SameAs(r)) return false; // already wielding it
|
||||
_pending = r;
|
||||
_lastWait = string.Empty;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Drops what is waiting and forgets what is in flight (logout, portal space, shutdown).</summary>
|
||||
public void Reset()
|
||||
{
|
||||
_pending = null;
|
||||
_flight = null;
|
||||
_lastWait = string.Empty;
|
||||
}
|
||||
|
||||
public void Tick(IDefWorld w)
|
||||
{
|
||||
if (!w.InWorld)
|
||||
{
|
||||
if (_pending != null || _flight != null) Reset();
|
||||
return;
|
||||
}
|
||||
long now = w.NowMs;
|
||||
if (_flight != null && !AdvanceFlight(w, now)) return; // still in flight: nothing new goes out
|
||||
if (_pending == null) return;
|
||||
|
||||
UseRequest req = _pending;
|
||||
string? wait = WaitReason(w, now);
|
||||
if (wait != null)
|
||||
{
|
||||
_lastWait = wait;
|
||||
if (now - req.AtMs >= WaitLimitMs)
|
||||
{
|
||||
_pending = null;
|
||||
Warn?.Invoke($"{req.Label}: not used, {wait}.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
_pending = null;
|
||||
Send(w, req, now);
|
||||
}
|
||||
|
||||
private string? WaitReason(IDefWorld w, long now)
|
||||
{
|
||||
if (now - _lastDoneMs < MinGapMs) return "the last action just finished";
|
||||
if (w.ClientBusy) return "the character is busy";
|
||||
if (w.Animating) return "an animation is playing";
|
||||
if (w.BotWaitingOnServer == true) return "RynthAi is waiting on the server";
|
||||
return null;
|
||||
}
|
||||
|
||||
// ── Sending ─────────────────────────────────────────────────────────────
|
||||
|
||||
private void Send(IDefWorld w, UseRequest req, long now)
|
||||
{
|
||||
IReadOnlyList<CarriedItem> items = w.Items();
|
||||
CarriedItem? item = req.Item != null
|
||||
? ItemMatcher.Find(req.Item, items, out _)
|
||||
: ItemMatcher.FindByName(req.Name ?? string.Empty, items);
|
||||
if (item == null)
|
||||
{
|
||||
Warn?.Invoke(req.Item != null
|
||||
? $"{req.Label}: you aren't carrying one."
|
||||
: $"No item named '{req.Name}' in your pack.");
|
||||
return;
|
||||
}
|
||||
|
||||
ItemKind kind = ItemKinds.Classify(item);
|
||||
UseAction action = UseModes.ActionFor(req.Mode, kind);
|
||||
string name = item.FullName;
|
||||
|
||||
if (action == UseAction.Equip)
|
||||
{
|
||||
if (item.Wielded)
|
||||
{
|
||||
Say?.Invoke($"{name} is already in your hands.");
|
||||
return;
|
||||
}
|
||||
if (ItemKinds.IsWeapon(kind) && !Settings.SwapWhileBotRuns && w.BotMacroRunning == true)
|
||||
{
|
||||
Warn?.Invoke($"{name}: not wielded, RynthAi's macro is running and picks the weapon itself (stop it, or allow swaps in the Defective settings).");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
uint target = 0;
|
||||
if (action == UseAction.UseOnSelf) target = w.PlayerId;
|
||||
else if (action == UseAction.UseOnSelected)
|
||||
{
|
||||
target = w.SelectedId;
|
||||
if (target == 0)
|
||||
{
|
||||
Warn?.Invoke($"{name}: select a target first.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
if ((action == UseAction.UseOnSelf || action == UseAction.UseOnSelected) && target == 0)
|
||||
{
|
||||
Warn?.Invoke($"{name}: the character isn't ready.");
|
||||
return;
|
||||
}
|
||||
|
||||
bool sent = target != 0 ? w.UseObjectOn(item.Id, target) : w.UseObject(item.Id);
|
||||
if (!sent)
|
||||
{
|
||||
Warn?.Invoke($"{name}: the client didn't take the request (nothing was sent).");
|
||||
return;
|
||||
}
|
||||
|
||||
_flight = new Flight
|
||||
{
|
||||
Request = req,
|
||||
Item = item,
|
||||
Action = action,
|
||||
Kind = kind,
|
||||
SentMs = now,
|
||||
StageMs = now,
|
||||
UseDoneAtSend = w.UseDoneSeq,
|
||||
RefusalAtSend = w.RefusalSeq,
|
||||
ModeBefore = w.CombatMode,
|
||||
Stage = action == UseAction.Equip ? Stage.WaitWield : Stage.Sent,
|
||||
};
|
||||
Log?.Invoke($"[RynthDefective] {req.Source}: {(action == UseAction.Equip ? "wield" : target != 0 ? "use on " + (target == w.PlayerId ? "you" : "0x" + target.ToString("X8")) : "use")} {item} (stack {item.Stack}, mode {Stance.Name(w.CombatMode)})");
|
||||
Say?.Invoke(action == UseAction.Equip ? $"Wielding {name}..." : $"Using {name}...");
|
||||
}
|
||||
|
||||
// ── In flight ───────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Steps the action in flight; true when it is finished (a new one may go out this tick).</summary>
|
||||
private bool AdvanceFlight(IDefWorld w, long now)
|
||||
{
|
||||
Flight f = _flight!;
|
||||
long age = now - f.SentMs;
|
||||
switch (f.Stage)
|
||||
{
|
||||
case Stage.Sent:
|
||||
{
|
||||
bool answered = w.UseDoneSeq != f.UseDoneAtSend;
|
||||
bool quiet = age >= UseQuietMs && !w.ClientBusy && !w.Animating;
|
||||
if (answered || quiet || age >= UseTimeoutMs)
|
||||
{
|
||||
if (!answered && age >= UseTimeoutMs) Log?.Invoke($"[RynthDefective] no UseDone for {f.Item} after {age} ms; carrying on");
|
||||
Finish(now);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
case Stage.WaitWield:
|
||||
{
|
||||
CarriedItem? live = w.Live(f.Item.Id);
|
||||
if (live != null && live.Wielded)
|
||||
{
|
||||
Wielded?.Invoke(live);
|
||||
f.Item = live;
|
||||
f.Stage = Stage.Stance;
|
||||
f.StageMs = now;
|
||||
return AdvanceStance(w, f, now);
|
||||
}
|
||||
if (w.RefusalSeq != f.RefusalAtSend && w.RefusalNamed(f.Item.Id))
|
||||
{
|
||||
Warn?.Invoke($"{f.Item.FullName}: the server wouldn't let you wield it (a skill, level or slot requirement?).");
|
||||
Finish(now);
|
||||
return true;
|
||||
}
|
||||
if (age >= WieldTimeoutMs)
|
||||
{
|
||||
Warn?.Invoke($"{f.Item.FullName}: not in your hands after {age / 1000.0:0.0} s - something may be in the way, or the character was busy. Try again.");
|
||||
Finish(now);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
default:
|
||||
return AdvanceStance(w, f, now);
|
||||
}
|
||||
}
|
||||
|
||||
private bool AdvanceStance(IDefWorld w, Flight f, long now)
|
||||
{
|
||||
bool launcher = f.Kind == ItemKind.Missile && ItemKinds.NeedsAmmo(f.Item);
|
||||
int want = Stance.Wanted(f.Kind, launcher, AmmoInHand(w), f.ModeBefore);
|
||||
if (want == 0 || w.CombatMode == want)
|
||||
{
|
||||
Say?.Invoke($"{f.Item.FullName} is in your hands.");
|
||||
Finish(now);
|
||||
return true;
|
||||
}
|
||||
long since = now - f.StageMs;
|
||||
if (since >= StanceTimeoutMs)
|
||||
{
|
||||
Warn?.Invoke($"{f.Item.FullName} is wielded but the {Stance.Name(want)} stance wasn't taken ({Stance.Name(w.CombatMode)} now).");
|
||||
Finish(now);
|
||||
return true;
|
||||
}
|
||||
if (since < StanceSettleMs || w.ClientBusy || w.Animating) return false;
|
||||
if (w.SetCombatMode(want))
|
||||
{
|
||||
Log?.Invoke($"[RynthDefective] stance {Stance.Name(w.CombatMode)} -> {Stance.Name(want)} for {f.Item}");
|
||||
Say?.Invoke(want == Stance.NonCombat && f.ModeBefore != Stance.NonCombat
|
||||
? $"{f.Item.FullName} is in your hands; no ammunition in hand, so you are back at peace."
|
||||
: $"{f.Item.FullName} is in your hands, {Stance.Name(want)} stance.");
|
||||
Finish(now);
|
||||
return true;
|
||||
}
|
||||
return false; // the engine turned the request away this tick (a teleport, a pending action): ask again
|
||||
}
|
||||
|
||||
private static bool AmmoInHand(IDefWorld w)
|
||||
{
|
||||
foreach (CarriedItem it in w.Items())
|
||||
if (it.Wielded && ItemKinds.Classify(it) == ItemKind.Ammo) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
private void Finish(long now)
|
||||
{
|
||||
_flight = null;
|
||||
_lastDoneMs = now;
|
||||
}
|
||||
}
|
||||
195
Plugins/RynthCore.Plugin.RynthDefective/Views/BarView.cs
Normal file
195
Plugins/RynthCore.Plugin.RynthDefective/Views/BarView.cs
Normal file
|
|
@ -0,0 +1,195 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using RynthCore.Plugin.RynthDefective.Items;
|
||||
using RynthCore.Plugin.RynthDefective.Model;
|
||||
using RynthCore.Plugin.RynthDefective.Ui;
|
||||
using RynthCore.Plugin.RynthDefective.Use;
|
||||
|
||||
namespace RynthCore.Plugin.RynthDefective.Views;
|
||||
|
||||
/// <summary>
|
||||
/// The item bar window: a grid of slot buttons (the item's picture, its count or uses left, its key
|
||||
/// under it), a row with Edit, Settings and Weapons, and the status line. Edit opens the slot editor
|
||||
/// below (set a slot from the item selected in the game, pick one from the pack, how it is used,
|
||||
/// its key); Settings the sizes and switches. Recorded on the pump thread, replayed by the engine.
|
||||
/// </summary>
|
||||
internal sealed class BarView
|
||||
{
|
||||
/// <summary>Logical units a button needs besides its picture: the frame padding and the gap to the next.</summary>
|
||||
public const float CellExtra = 16f;
|
||||
|
||||
private readonly DefSession _s;
|
||||
private readonly SlotEditor _editor;
|
||||
private readonly SettingsPanel _settings;
|
||||
|
||||
public bool EditOpen, SettingsOpen;
|
||||
|
||||
/// <summary>The window should be sized to its content (a setting changed, a section opened).</summary>
|
||||
public Action RequestFit = () => { };
|
||||
/// <summary>Show the weapon picker window.</summary>
|
||||
public Action ShowPicker = () => { };
|
||||
|
||||
public BarView(DefSession session)
|
||||
{
|
||||
_s = session;
|
||||
_editor = new SlotEditor(session);
|
||||
_settings = new SettingsPanel(session, () => RequestFit());
|
||||
}
|
||||
|
||||
public SlotEditor Editor => _editor;
|
||||
|
||||
/// <summary>The window size that fits the grid (and the sections that are open), in logical units.</summary>
|
||||
public (float W, float H) WantedSize()
|
||||
{
|
||||
DefSettings st = _s.Settings;
|
||||
int perRow = Math.Min(st.SlotsPerRow, st.SlotCount);
|
||||
int rows = (st.SlotCount + st.SlotsPerRow - 1) / st.SlotsPerRow;
|
||||
float cell = st.ButtonSize + CellExtra;
|
||||
float w = Math.Max(250f, perRow * cell + 28f);
|
||||
float h = rows * (st.ButtonSize + (st.ShowCounts ? 50f : 14f)) + 70f;
|
||||
if (EditOpen) { h += 330f; w = Math.Max(w, 330f); }
|
||||
if (SettingsOpen) h += 230f;
|
||||
return (w, h);
|
||||
}
|
||||
|
||||
public void Draw(UiWindow w)
|
||||
{
|
||||
if (!_s.LoggedIn)
|
||||
{
|
||||
w.TextDisabled("Log in to use the item bar.");
|
||||
return;
|
||||
}
|
||||
IReadOnlyList<CarriedItem> items = _s.Items();
|
||||
DrawGrid(w, items);
|
||||
DrawToolbar(w);
|
||||
DrawStatus(w);
|
||||
if (EditOpen)
|
||||
{
|
||||
w.Separator();
|
||||
_editor.Draw(w, items);
|
||||
}
|
||||
if (SettingsOpen)
|
||||
{
|
||||
w.Separator();
|
||||
_settings.Draw(w);
|
||||
}
|
||||
}
|
||||
|
||||
// ── The grid ────────────────────────────────────────────────────────────
|
||||
|
||||
private void DrawGrid(UiWindow w, IReadOnlyList<CarriedItem> items)
|
||||
{
|
||||
DefSettings st = _s.Settings;
|
||||
float size = st.ButtonSize;
|
||||
float pitch = size + CellExtra;
|
||||
var labels = new List<(string Text, uint Color)>();
|
||||
var keys = new List<string>();
|
||||
for (int rowStart = 0; rowStart < st.SlotCount; rowStart += st.SlotsPerRow)
|
||||
{
|
||||
int end = Math.Min(st.SlotCount, rowStart + st.SlotsPerRow);
|
||||
labels.Clear();
|
||||
keys.Clear();
|
||||
for (int i = rowStart; i < end; i++)
|
||||
{
|
||||
if (i > rowStart) w.SameLine();
|
||||
DrawSlotButton(w, i + 1, items, size, out string text, out uint color, out string key);
|
||||
labels.Add((text, color));
|
||||
keys.Add(key);
|
||||
}
|
||||
if (!st.ShowCounts) continue;
|
||||
for (int j = 0; j < labels.Count; j++)
|
||||
{
|
||||
if (j > 0) w.SameLine(j * pitch);
|
||||
w.TextColored(labels[j].Color, labels[j].Text.Length > 0 ? labels[j].Text : " ");
|
||||
}
|
||||
for (int j = 0; j < keys.Count; j++)
|
||||
{
|
||||
if (j > 0) w.SameLine(j * pitch);
|
||||
w.TextColored(SlotText.KeyColor, keys[j].Length > 0 ? keys[j] : " ");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void DrawSlotButton(UiWindow w, int number, IReadOnlyList<CarriedItem> items, float size,
|
||||
out string text, out uint color, out string key)
|
||||
{
|
||||
DefSlot slot = _s.Data.Slots[number - 1];
|
||||
string id = "slot" + number;
|
||||
string? keyFull = _s.KeyOfSlot(number);
|
||||
key = SlotText.ShortKey(keyFull);
|
||||
text = string.Empty;
|
||||
color = SlotText.Plain;
|
||||
bool icons = _s.Settings.ShowIcons && _s.IconsAvailable;
|
||||
|
||||
if (slot.Item == null)
|
||||
{
|
||||
w.Button("+", id, () => Choose(number), size + 8f, size + 8f);
|
||||
w.Tooltip(SlotText.Tooltip(number, null, default, slot.Mode, keyFull));
|
||||
return;
|
||||
}
|
||||
|
||||
SlotStatus s = ItemMatcher.Status(slot.Item, items);
|
||||
text = SlotText.Count(s, out color);
|
||||
string tip = SlotText.Tooltip(number, slot.Item, s, slot.Mode, keyFull);
|
||||
bool busy = _s.Use.Involves(slot.Item);
|
||||
bool inHand = s.Item is { Wielded: true };
|
||||
uint? fill = busy ? SlotText.Waiting : inHand ? UiFormat.Rgb(40, 110, 40) : null;
|
||||
|
||||
if (icons && s.Item != null)
|
||||
{
|
||||
w.ImageButton(UiFormat.IconKindObject, s.Item.Id, id, () => Press(number), size, size, 0xFFFFFFFFu, fill ?? 0u);
|
||||
}
|
||||
else if (icons && slot.Item.Icon != 0)
|
||||
{
|
||||
// Not carried: the last picture seen, dimmed.
|
||||
w.ImageButton(UiFormat.IconKindIcon, slot.Item.Icon, id, () => Press(number), size, size, UiFormat.Rgb(255, 255, 255, 90));
|
||||
}
|
||||
else
|
||||
{
|
||||
if (fill != null) w.PushStyleColor(UiFormat.ColButton, fill.Value);
|
||||
else if (s.Item == null) w.PushStyleColor(UiFormat.ColText, SlotText.Missing);
|
||||
w.Button(SlotText.Abbreviation(slot.Item.FullName), id, () => Press(number), size + 8f, size + 8f);
|
||||
if (fill != null) w.PopStyleColor();
|
||||
else if (s.Item == null) w.PopStyleColor();
|
||||
}
|
||||
w.Tooltip(tip);
|
||||
}
|
||||
|
||||
private void Press(int number)
|
||||
{
|
||||
string? problem = _s.UseSlot(number);
|
||||
if (problem != null) _s.SetStatus(problem, warning: true);
|
||||
}
|
||||
|
||||
/// <summary>An empty slot's button: open the editor on it.</summary>
|
||||
private void Choose(int number)
|
||||
{
|
||||
if (!EditOpen) { EditOpen = true; RequestFit(); }
|
||||
_editor.Select(number);
|
||||
}
|
||||
|
||||
// ── Toolbar and status ──────────────────────────────────────────────────
|
||||
|
||||
private void DrawToolbar(UiWindow w)
|
||||
{
|
||||
w.ToggleButton("Edit slots", "tb.edit", EditOpen, () => { EditOpen = !EditOpen; RequestFit(); }, small: true);
|
||||
w.SameLine();
|
||||
w.ToggleButton("Settings", "tb.settings", SettingsOpen, () => { SettingsOpen = !SettingsOpen; RequestFit(); }, small: true);
|
||||
w.SameLine();
|
||||
w.SmallButton("Weapons", "tb.weapons", () => ShowPicker());
|
||||
w.Tooltip("The weapon picker: every weapon and wand you carry, one click to wield (/rdef weapons)");
|
||||
}
|
||||
|
||||
private void DrawStatus(UiWindow w)
|
||||
{
|
||||
UseRequest? pending = _s.Use.Pending;
|
||||
if (pending != null)
|
||||
{
|
||||
w.TextColored(SlotText.Waiting, $"Waiting to use {pending.Label}...");
|
||||
return;
|
||||
}
|
||||
string status = _s.Status(out bool warning);
|
||||
if (status.Length > 0) w.TextColored(warning ? SlotText.Missing : SlotText.Plain, status);
|
||||
else w.TextDisabled("Click a slot, or press its key.");
|
||||
}
|
||||
}
|
||||
118
Plugins/RynthCore.Plugin.RynthDefective/Views/PickerView.cs
Normal file
118
Plugins/RynthCore.Plugin.RynthDefective/Views/PickerView.cs
Normal file
|
|
@ -0,0 +1,118 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using RynthCore.Plugin.RynthDefective.Items;
|
||||
using RynthCore.Plugin.RynthDefective.Model;
|
||||
using RynthCore.Plugin.RynthDefective.Ui;
|
||||
using RynthCore.Plugin.RynthDefective.Use;
|
||||
|
||||
namespace RynthCore.Plugin.RynthDefective.Views;
|
||||
|
||||
/// <summary>
|
||||
/// The weapon picker window, for picking among dozens of weapons while playing by hand: a search
|
||||
/// box, a row of kind buttons (All, Melee, Missile, War, Void - the kind the player prefers is kept),
|
||||
/// then the carried weapons and wands as big rows with their picture. Favourites and the recently
|
||||
/// wielded come first; below them every kind, A-Z. One click on a row wields it; the weapon in hand
|
||||
/// is highlighted. The "+" / "-" in front of a row adds or takes out a favourite.
|
||||
/// </summary>
|
||||
internal sealed class PickerView
|
||||
{
|
||||
private static readonly uint InHandColor = UiFormat.Rgb(110, 210, 110);
|
||||
private static readonly uint ElementColor = UiFormat.Rgb(150, 185, 235);
|
||||
|
||||
private readonly DefSession _s;
|
||||
|
||||
public string Search = string.Empty;
|
||||
|
||||
public PickerView(DefSession session) => _s = session;
|
||||
|
||||
public void Draw(UiWindow w)
|
||||
{
|
||||
if (!_s.LoggedIn)
|
||||
{
|
||||
w.TextDisabled("Log in to pick a weapon.");
|
||||
return;
|
||||
}
|
||||
DefSettings st = _s.Settings;
|
||||
IReadOnlyList<CarriedItem> items = _s.Items();
|
||||
PickerModel m = WeaponPicker.Build(items, _s.Data.Favourites, _s.Data.Recent, Search, st.PreferredKind);
|
||||
|
||||
w.InputText("Search", "pk.search", Search, 48, v => Search = v);
|
||||
w.Tooltip("Words in the name, the element or the kind: \"fire wand\", \"axe\", \"void\".");
|
||||
foreach (KindFilter f in Enum.GetValues<KindFilter>())
|
||||
{
|
||||
KindFilter kind = f;
|
||||
w.ToggleButton(WeaponPicker.KindLabel(f), "pk.kind" + (int)f, st.PreferredKind == f, () =>
|
||||
{
|
||||
st.PreferredKind = kind;
|
||||
_s.Save();
|
||||
}, small: true);
|
||||
w.SameLine();
|
||||
}
|
||||
w.SmallButton("Clear", "pk.clear", () => Search = string.Empty);
|
||||
w.Tooltip("Clears the search. The kind button you leave pressed is remembered.");
|
||||
|
||||
DrawHand(w, items);
|
||||
if (st.PreferredKind != KindFilter.All || Search.Length > 0)
|
||||
w.TextDisabled($"{m.Shown} of {m.Total} shown");
|
||||
|
||||
w.BeginChild("pk.list", 0f, 0f, true);
|
||||
float icon = st.PickerIconSize;
|
||||
bool icons = st.ShowIcons && _s.IconsAvailable;
|
||||
if (m.Favourites.Count > 0)
|
||||
{
|
||||
w.SeparatorText("Favourites");
|
||||
foreach (PickerRow r in m.Favourites) DrawRow(w, r, "f", icon, icons, showElement: true);
|
||||
}
|
||||
if (m.Recent.Count > 0)
|
||||
{
|
||||
w.SeparatorText("Recent");
|
||||
foreach (PickerRow r in m.Recent) DrawRow(w, r, "r", icon, icons, showElement: true);
|
||||
}
|
||||
foreach (PickerGroup g in m.Groups)
|
||||
{
|
||||
w.SeparatorText($"{ItemKinds.Label(g.Group)} ({g.Rows.Count})");
|
||||
foreach (PickerRow r in g.Rows) DrawRow(w, r, "g", icon, icons, showElement: g.Group is WeaponGroup.WarMagic or WeaponGroup.VoidMagic);
|
||||
}
|
||||
if (m.Groups.Count == 0)
|
||||
w.TextDisabled(m.Total == 0 ? "No weapons or wands in your pack." : "Nothing matches. Clear the search or pick All.");
|
||||
w.EndChild();
|
||||
}
|
||||
|
||||
/// <summary>What is in the hands now, and the item's name for the title line.</summary>
|
||||
private void DrawHand(UiWindow w, IReadOnlyList<CarriedItem> items)
|
||||
{
|
||||
string hand = string.Empty;
|
||||
foreach (CarriedItem it in items)
|
||||
{
|
||||
if (!it.Wielded) continue;
|
||||
ItemKind k = ItemKinds.Classify(it);
|
||||
if (!ItemKinds.IsWeapon(k) && k != ItemKind.Shield) continue;
|
||||
hand += (hand.Length > 0 ? ", " : string.Empty) + it.FullName;
|
||||
}
|
||||
UseRequest? pending = _s.Use.Pending;
|
||||
if (pending != null) w.TextColored(SlotText.Waiting, $"Waiting to wield {pending.Label}...");
|
||||
else w.TextColored(hand.Length > 0 ? InHandColor : SlotText.Plain, "In hand: " + (hand.Length > 0 ? hand : "nothing"));
|
||||
}
|
||||
|
||||
private void DrawRow(UiWindow w, PickerRow r, string section, float icon, bool icons, bool showElement)
|
||||
{
|
||||
CarriedItem it = r.Item;
|
||||
string idKey = section + it.Id;
|
||||
ItemRef reference = ItemRef.From(it);
|
||||
|
||||
w.SmallButton(r.Favourite ? "-" : "+", "fav" + idKey, () => _s.SetStatus(_s.ToggleFavourite(reference)));
|
||||
w.Tooltip(r.Favourite ? "Take out of the favourites" : "Add to the favourites (listed first)");
|
||||
w.SameLine();
|
||||
if (icons)
|
||||
{
|
||||
w.Image(UiFormat.IconKindObject, it.Id, icon, icon);
|
||||
w.SameLine();
|
||||
}
|
||||
string label = it.FullName;
|
||||
if (showElement && r.Element.Length > 0) label += $" ({r.Element})";
|
||||
if (r.InHand) label += " [in hand]";
|
||||
if (r.InHand) w.PushStyleColor(UiFormat.ColText, InHandColor);
|
||||
w.Selectable(label, "pk" + idKey, r.InHand, () => _s.Wield(reference), 0f, icons ? icon : 0f);
|
||||
if (r.InHand) w.PopStyleColor();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,49 @@
|
|||
using System;
|
||||
using RynthCore.Plugin.RynthDefective.Model;
|
||||
using RynthCore.Plugin.RynthDefective.Ui;
|
||||
|
||||
namespace RynthCore.Plugin.RynthDefective.Views;
|
||||
|
||||
/// <summary>The settings under the bar: how many slots and how big, what is shown, and the credit.</summary>
|
||||
internal sealed class SettingsPanel
|
||||
{
|
||||
/// <summary>The credit line, in the plugin's about text and the README.</summary>
|
||||
public const string Credit =
|
||||
"RynthDefective is an independent implementation of the ideas of Defective, the Decal item-bar plugin written by "
|
||||
+ "Hazridi and modified by Aun (github.com/aunrela/Defective). It contains no code from it.";
|
||||
|
||||
private readonly DefSession _s;
|
||||
private readonly Action _fit;
|
||||
|
||||
public SettingsPanel(DefSession session, Action fit)
|
||||
{
|
||||
_s = session;
|
||||
_fit = fit;
|
||||
}
|
||||
|
||||
public void Draw(UiWindow w)
|
||||
{
|
||||
DefSettings st = _s.Settings;
|
||||
void Changed(bool fit)
|
||||
{
|
||||
st.Clamp();
|
||||
_s.Save();
|
||||
if (fit) _fit();
|
||||
}
|
||||
|
||||
w.SeparatorText("Settings");
|
||||
w.SliderInt("Slots", "set.slots", st.SlotCount, DefSettings.SlotsMin, DefSettings.SlotsMax, v => { st.SlotCount = v; Changed(true); });
|
||||
w.SliderInt("Slots per row", "set.perrow", st.SlotsPerRow, DefSettings.PerRowMin, DefSettings.PerRowMax, v => { st.SlotsPerRow = v; Changed(true); });
|
||||
w.SliderInt("Button size", "set.button", st.ButtonSize, DefSettings.ButtonMin, DefSettings.ButtonMax, v => { st.ButtonSize = v; Changed(true); });
|
||||
w.SliderInt("Picker row icon", "set.picker", st.PickerIconSize, DefSettings.PickerIconMin, DefSettings.PickerIconMax, v => { st.PickerIconSize = v; Changed(false); });
|
||||
w.Checkbox("Show item icons", "set.icons", st.ShowIcons, v => { st.ShowIcons = v; Changed(false); });
|
||||
w.Tooltip(_s.IconsAvailable ? "Off: the slots are text buttons." : "This engine can't draw item pictures (it needs script window op level 2): the slots are text buttons.");
|
||||
w.Checkbox("Show counts and keys under the slots", "set.counts", st.ShowCounts, v => { st.ShowCounts = v; Changed(true); });
|
||||
w.Checkbox("Allow weapon swaps while RynthAi's macro runs", "set.swap", st.SwapWhileBotRuns, v => { st.SwapWhileBotRuns = v; Changed(false); });
|
||||
w.Tooltip("Off (the default): a weapon, wand or shield is not wielded while the RynthAi macro runs - it picks the weapon itself and would swap back. Kits, potions and other items always work.");
|
||||
|
||||
w.SeparatorText("About");
|
||||
w.TextWrapped(Credit);
|
||||
w.TextDisabled("Commands: /rdef (show or hide), /rdef use <slot or name>, /rdef weapons, /rdef help.");
|
||||
}
|
||||
}
|
||||
172
Plugins/RynthCore.Plugin.RynthDefective/Views/SlotEditor.cs
Normal file
172
Plugins/RynthCore.Plugin.RynthDefective/Views/SlotEditor.cs
Normal file
|
|
@ -0,0 +1,172 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using RynthCore.Plugin.RynthDefective.Items;
|
||||
using RynthCore.Plugin.RynthDefective.Model;
|
||||
using RynthCore.Plugin.RynthDefective.Ui;
|
||||
|
||||
namespace RynthCore.Plugin.RynthDefective.Views;
|
||||
|
||||
/// <summary>
|
||||
/// The slot editor under the bar: every slot as a row (picture, name, key), and for the one picked
|
||||
/// its buttons - Set from selected (the item selected in the game goes in the slot), Pick from pack
|
||||
/// (a searchable list of what is carried), Clear, move up and down - how pressing it uses the item,
|
||||
/// and its key (typed here, bound through the engine's hotkeys as "/rdef use N" or by the item's name).
|
||||
/// </summary>
|
||||
internal sealed class SlotEditor
|
||||
{
|
||||
private const float RowIcon = 22f;
|
||||
private const int PackRows = 40;
|
||||
|
||||
private readonly DefSession _s;
|
||||
private int _selected = 1;
|
||||
private bool _picking;
|
||||
private string _packSearch = string.Empty;
|
||||
private string _keyDraft = string.Empty;
|
||||
private string _note = string.Empty;
|
||||
|
||||
public SlotEditor(DefSession session) => _s = session;
|
||||
|
||||
public int SelectedSlot => _selected;
|
||||
public bool Picking => _picking;
|
||||
public string Note => _note;
|
||||
|
||||
public void Select(int number)
|
||||
{
|
||||
_selected = Math.Clamp(number, 1, DefSettings.SlotsMax);
|
||||
_picking = false;
|
||||
_keyDraft = string.Empty;
|
||||
_note = string.Empty;
|
||||
}
|
||||
|
||||
private void Say(string text)
|
||||
{
|
||||
_note = text;
|
||||
_s.SetStatus(text);
|
||||
}
|
||||
|
||||
public void Draw(UiWindow w, IReadOnlyList<CarriedItem> items)
|
||||
{
|
||||
DefSettings st = _s.Settings;
|
||||
if (_selected > st.SlotCount) _selected = st.SlotCount;
|
||||
bool icons = st.ShowIcons && _s.IconsAvailable;
|
||||
|
||||
w.TextDisabled("Pick a slot, then set it from the item selected in the game or from your pack.");
|
||||
w.BeginChild("slotlist", 0f, Math.Min(st.SlotCount, 6) * (RowIcon + 6f) + 8f, true);
|
||||
for (int n = 1; n <= st.SlotCount; n++)
|
||||
{
|
||||
DefSlot slot = _s.Data.Slots[n - 1];
|
||||
int number = n;
|
||||
string? key = _s.KeyOfSlot(n);
|
||||
string name = slot.Item == null ? "(empty)" : slot.Item.FullName;
|
||||
if (icons)
|
||||
{
|
||||
CarriedItem? have = slot.Item == null ? null : ItemMatcher.Find(slot.Item, items, out _);
|
||||
if (have != null) w.Image(UiFormat.IconKindObject, have.Id, RowIcon, RowIcon);
|
||||
else if (slot.Item != null && slot.Item.Icon != 0) w.Image(UiFormat.IconKindIcon, slot.Item.Icon, RowIcon, RowIcon, UiFormat.Rgb(255, 255, 255, 90));
|
||||
else w.Dummy(RowIcon, RowIcon);
|
||||
w.SameLine();
|
||||
}
|
||||
string label = $"{n}. {name}" + (key != null ? $" [{key}]" : string.Empty);
|
||||
w.Selectable(label, "row" + n, _selected == n, () => Select(number), 0f, icons ? RowIcon : 0f);
|
||||
}
|
||||
w.EndChild();
|
||||
|
||||
DrawSlot(w, items);
|
||||
}
|
||||
|
||||
private void DrawSlot(UiWindow w, IReadOnlyList<CarriedItem> items)
|
||||
{
|
||||
int n = _selected;
|
||||
DefSlot slot = _s.Data.Slots[n - 1];
|
||||
w.TextColored(UiColors.Gold, $"Slot {n}: " + (slot.Item == null ? "(empty)" : slot.Item.FullName));
|
||||
|
||||
w.Button("Set from selected", "ed.set", () => Say(_s.SetFromSelected(n)));
|
||||
w.Tooltip("Select an item in the game (click it in your pack), then press this: it goes in this slot.");
|
||||
w.SameLine();
|
||||
w.ToggleButton("Pick from pack", "ed.pick", _picking, () => { _picking = !_picking; _packSearch = string.Empty; });
|
||||
w.Tooltip("Choose from a list of what you carry.");
|
||||
w.SameLine();
|
||||
w.Button("Clear", "ed.clear", () => Say(_s.ClearSlot(n)));
|
||||
|
||||
w.SmallButton("Move up", "ed.up", () => { if (_s.SwapSlots(n, n - 1)) _selected = n - 1; });
|
||||
w.SameLine();
|
||||
w.SmallButton("Move down", "ed.down", () => { if (_s.SwapSlots(n, n + 1)) _selected = n + 1; });
|
||||
|
||||
uint sel = _s.SelectedId();
|
||||
CarriedItem? selItem = sel == 0 ? null : _s.FindById(sel);
|
||||
w.TextDisabled("Selected in the game: " + (sel == 0 ? "nothing" : selItem != null ? selItem.FullName : "(not in your pack)"));
|
||||
if (_note.Length > 0) w.TextWrapped(_note);
|
||||
|
||||
if (_picking) DrawPackPicker(w, items, n);
|
||||
|
||||
if (slot.Item == null) return;
|
||||
|
||||
int mode = (int)slot.Mode;
|
||||
w.Combo("Pressing it", "ed.mode", mode, UseModes.Labels, i => _s.SetSlotMode(n, (UseMode)Math.Clamp(i, 0, (int)UseMode.Equip)));
|
||||
SlotStatus status = ItemMatcher.Status(slot.Item, items);
|
||||
if (status.Item != null)
|
||||
{
|
||||
ItemKind kind = ItemKinds.Classify(status.Item);
|
||||
UseAction action = UseModes.ActionFor(slot.Mode, kind);
|
||||
w.TextDisabled($"It is {Describe(kind)}: pressing the slot has it {UseModes.Describe(action)}.");
|
||||
}
|
||||
else
|
||||
{
|
||||
w.TextColored(SlotText.Missing, "Not in your pack right now. The slot keeps the name and fills itself when you carry another.");
|
||||
}
|
||||
|
||||
DrawKey(w, n, slot);
|
||||
}
|
||||
|
||||
private void DrawKey(UiWindow w, int n, DefSlot slot)
|
||||
{
|
||||
string? key = _s.KeyOfSlot(n);
|
||||
w.Text("Key: " + (key ?? "none"));
|
||||
w.InputText("Key to bind", "ed.key", _keyDraft, 24, v => _keyDraft = v, UiFormat.InputEnterReturnsTrue);
|
||||
w.Tooltip("A key with Ctrl, Alt or Shift if you like: F9, Ctrl+1, Alt+Shift+Num3.");
|
||||
w.Button("Bind to this slot", "ed.bind", () => Say(_s.BindKey(n, _keyDraft, byName: false)));
|
||||
w.Tooltip($"Runs {DefCommandParser.UseCommand(n)}. If you move or re-set the slot, the key follows the slot.");
|
||||
w.SameLine();
|
||||
w.Button("Bind to this item", "ed.bindname", () => Say(_s.BindKey(n, _keyDraft, byName: true)));
|
||||
w.Tooltip("Runs /rdef use <the item's name>, whichever slot (or none) holds it. Works for every character on this PC.");
|
||||
w.SameLine();
|
||||
w.Button("Unbind", "ed.unbind", () => Say(_s.UnbindKey(n)));
|
||||
w.TextDisabled("Any item can be bound by name from Settings > Hotkeys too: /rdef use <name>.");
|
||||
}
|
||||
|
||||
private void DrawPackPicker(UiWindow w, IReadOnlyList<CarriedItem> items, int n)
|
||||
{
|
||||
bool icons = _s.Settings.ShowIcons && _s.IconsAvailable;
|
||||
w.InputText("Search your pack", "ed.packsearch", _packSearch, 48, v => _packSearch = v);
|
||||
List<PackChoice> choices = PackList.Build(items, _packSearch, PackRows, out int total);
|
||||
w.BeginChild("packlist", 0f, 150f, true);
|
||||
foreach (PackChoice c in choices)
|
||||
{
|
||||
CarriedItem it = c.Item;
|
||||
if (icons) { w.Image(UiFormat.IconKindObject, it.Id, RowIcon, RowIcon); w.SameLine(); }
|
||||
string label = it.FullName + (c.Count > 1 ? $" x{c.Count}" : string.Empty);
|
||||
w.Selectable(label, "pk" + it.Id, false, () =>
|
||||
{
|
||||
Say(_s.SetSlot(n, it));
|
||||
_picking = false;
|
||||
}, 0f, icons ? RowIcon : 0f);
|
||||
}
|
||||
if (choices.Count == 0) w.TextDisabled("Nothing matches.");
|
||||
if (total > choices.Count) w.TextDisabled($"{total - choices.Count} more - type to narrow the list.");
|
||||
w.EndChild();
|
||||
}
|
||||
|
||||
private static string Describe(ItemKind k) => k switch
|
||||
{
|
||||
ItemKind.Kit => "a healing or stamina kit",
|
||||
ItemKind.Melee => "a melee weapon",
|
||||
ItemKind.Missile => "a missile weapon",
|
||||
ItemKind.WarWand => "a war magic wand",
|
||||
ItemKind.VoidWand => "a void magic wand",
|
||||
ItemKind.Shield => "a shield",
|
||||
ItemKind.Armor => "armor or clothing",
|
||||
ItemKind.Jewelry => "jewelry",
|
||||
ItemKind.Ammo => "ammunition",
|
||||
_ => "an item",
|
||||
};
|
||||
}
|
||||
80
Plugins/RynthCore.Plugin.RynthDefective/Views/SlotText.cs
Normal file
80
Plugins/RynthCore.Plugin.RynthDefective/Views/SlotText.cs
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
using System;
|
||||
using System.Text;
|
||||
using RynthCore.Plugin.RynthDefective.Items;
|
||||
using RynthCore.Plugin.RynthDefective.Model;
|
||||
using RynthCore.Plugin.RynthDefective.Ui;
|
||||
|
||||
namespace RynthCore.Plugin.RynthDefective.Views;
|
||||
|
||||
/// <summary>The words a slot shows: the count under its button, its key, and its tooltip. Pure.</summary>
|
||||
internal static class SlotText
|
||||
{
|
||||
public static readonly uint Missing = UiFormat.Rgb(225, 95, 95);
|
||||
public static readonly uint InHand = UiFormat.Rgb(110, 210, 110);
|
||||
public static readonly uint Plain = UiFormat.Rgb(220, 220, 220);
|
||||
public static readonly uint KeyColor = UiFormat.Rgb(150, 185, 235);
|
||||
public static readonly uint Waiting = UiFormat.Rgb(255, 191, 64);
|
||||
|
||||
/// <summary>The line under a slot button: uses left (kits), the count (stacks, several of a kind), "in hand", or "none".</summary>
|
||||
public static string Count(SlotStatus s, out uint color)
|
||||
{
|
||||
color = Plain;
|
||||
if (s.Item == null)
|
||||
{
|
||||
color = Missing;
|
||||
return "none";
|
||||
}
|
||||
CarriedItem it = s.Item;
|
||||
if (it.Wielded)
|
||||
{
|
||||
color = InHand;
|
||||
return ItemKinds.IsWeapon(ItemKinds.Classify(it)) ? "in hand" : "worn";
|
||||
}
|
||||
if (it.MaxUses > 0) return s.Uses.ToString();
|
||||
if (it.MaxStack > 1 || s.Count > 1) return "x" + s.Count;
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>A key as the cell under a slot has room for: "Ctrl+F9" is "C+F9".</summary>
|
||||
public static string ShortKey(string? key)
|
||||
{
|
||||
if (string.IsNullOrEmpty(key)) return string.Empty;
|
||||
string k = key.EndsWith(" (off)", StringComparison.Ordinal) ? key[..^6] : key;
|
||||
return k.Replace("Ctrl+", "C+").Replace("Alt+", "A+").Replace("Shift+", "S+");
|
||||
}
|
||||
|
||||
/// <summary>Up to <paramref name="max"/> letters for a slot drawn as text (icons off): "Peerless Healing Kit" is "PHK".</summary>
|
||||
public static string Abbreviation(string name, int max = 4)
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
foreach (string word in (name ?? string.Empty).Split(' ', StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
if (word.Length == 0 || !char.IsLetterOrDigit(word[0])) continue;
|
||||
sb.Append(char.ToUpperInvariant(word[0]));
|
||||
if (sb.Length >= max) break;
|
||||
}
|
||||
return sb.Length == 0 ? "?" : sb.ToString();
|
||||
}
|
||||
|
||||
public static string Tooltip(int number, ItemRef? item, SlotStatus s, UseMode mode, string? key)
|
||||
{
|
||||
if (item == null) return $"Slot {number}: empty. Click to set it up.";
|
||||
var sb = new StringBuilder();
|
||||
sb.Append("Slot ").Append(number).Append(": ").Append(s.Item?.FullName ?? item.FullName);
|
||||
if (s.Item == null)
|
||||
{
|
||||
sb.Append("\nNot in your pack - nothing to use. It comes back by itself when you carry one of the same name.");
|
||||
}
|
||||
else
|
||||
{
|
||||
ItemKind kind = ItemKinds.Classify(s.Item);
|
||||
UseAction action = UseModes.ActionFor(mode, kind);
|
||||
sb.Append("\nClick or press the key: ").Append(UseModes.Describe(action).Replace("used", "use it").Replace("wielded", "wield it"));
|
||||
if (s.Item.MaxUses > 0) sb.Append("\n").Append(s.Uses).Append(" uses left");
|
||||
if (s.Count > 1 || s.Item.MaxStack > 1) sb.Append(s.Item.MaxUses > 0 ? ", " : "\n").Append(s.Count).Append(" carried");
|
||||
if (s.Item.Wielded) sb.Append("\nIn your hands now.");
|
||||
}
|
||||
sb.Append(key != null ? "\nKey: " + key : "\nNo key yet (Edit slots).");
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue