using System;
using System.Buffers;
using System.Collections.Generic;
using MoonSharp.Interpreter;
namespace RynthCore.Plugin.RynthLua;
///
/// game.World (UtilityBelt's World): object lookup and search, the selected object, the
/// player's inventory, and the world events (objects created/released, chat, tells,
/// selection). WorldObject properties live in GameWorldObject.cs.
///
/// The SDK has no "every object the client knows" call, so World keeps its own set of
/// known ids: OnCreateObject/OnDeleteObject, the player's inventory (seeded after login,
/// and after a hot reload), and any id a script or the selection proves exists.
/// Everything runs on the plugin pump thread; the SDK reads used here are served from the
/// engine's snapshots (names, types, positions) or guarded reads (ownership, bitfield).
///
public sealed partial class RynthLuaPlugin
{
private readonly HashSet _worldKnown = new();
/// Ids released recently (id → when): the engine's name snapshot can lag a delete.
private readonly Dictionary _worldReleased = new();
private bool _worldSeedPending = true; // true at load too: a hot reload mid-session seeds the inventory
private int _worldSeedTries;
private long _worldNextSeedAt;
private long _worldNextPruneAt;
private long _worldNextSnapshotAt;
private int _worldChangeSeq; // bumped on create/delete: invalidates the inventory cache
private readonly uint[] _worldContentsBuf = new uint[1024];
private uint[]? _worldInventoryCache;
private long _worldInventoryCacheTick = -1;
private int _worldInventoryCacheSeq = -1;
private const long WorldReleasedKeepMs = 10_000;
private const int WorldMaxSeedTries = 15;
// ── Lifecycle ───────────────────────────────────────────────────────────
partial void WorldOnLogin()
{
WorldReset();
_worldSeedPending = true;
}
partial void WorldOnLogout()
{
WorldReset();
_worldSeedPending = false;
}
private void WorldReset()
{
_worldKnown.Clear();
_worldReleased.Clear();
_worldClass.Clear();
_worldInventoryCache = null;
_worldSeedTries = 0;
_worldNextSeedAt = 0;
_worldChangeSeq++;
}
partial void WorldTick()
{
long now = Environment.TickCount64;
// Seed the known set with the player and everything they carry. Retried: right
// after login the engine's object snapshot may not be warm yet.
if (_worldSeedPending && now >= _worldNextSeedAt)
{
_worldNextSeedAt = now + 1000;
uint pid = Host.GetPlayerId();
if (pid != 0)
{
_worldKnown.Add(pid);
uint[] inv = WorldInventoryIds();
foreach (uint id in inv) _worldKnown.Add(id);
if (inv.Length > 0 || ++_worldSeedTries >= WorldMaxSeedTries) _worldSeedPending = false;
}
}
// Engine v69+: pick up everything in the client's object table, so objects that
// existed before this plugin loaded (hot reload, late start) are found too.
if (now >= _worldNextSnapshotAt && Host.HasGetLiveObjectIds && Host.GetPlayerId() != 0)
{
_worldNextSnapshotAt = now + 1000;
int before = _worldKnown.Count;
foreach (uint id in Host.GetLiveObjectIds())
if (!_worldReleased.ContainsKey(id)) _worldKnown.Add(id);
if (_worldKnown.Count != before) _worldChangeSeq++;
}
WorldPollPositions();
WorldPollOpenContainer();
if (now >= _worldNextPruneAt && _worldReleased.Count > 0)
{
_worldNextPruneAt = now + 2000;
List? old = null;
foreach (var kv in _worldReleased)
if (now - kv.Value > WorldReleasedKeepMs) (old ??= new()).Add(kv.Key);
if (old != null)
foreach (uint id in old) _worldReleased.Remove(id);
}
}
// ── Engine events ───────────────────────────────────────────────────────
partial void WorldOnCreateObject(uint objectId)
{
if (objectId == 0) return;
_worldKnown.Add(objectId);
_worldReleased.Remove(objectId);
_worldClass.Remove(objectId); // ids get reused: classify the new object afresh
_worldChangeSeq++;
FireWorld("World.OnObjectCreated", (s, ctx) =>
{
var t = new Table(s);
t["ObjectId"] = (double)objectId;
t["Object"] = WrapObject(s, ctx, objectId);
return DynValue.NewTable(t);
});
}
partial void WorldOnDeleteObject(uint objectId)
{
if (objectId == 0) return;
_worldKnown.Remove(objectId);
_worldClass.Remove(objectId);
_worldReleased[objectId] = Environment.TickCount64;
_worldChangeSeq++;
FireAll("World.OnObjectReleased", s =>
{
var t = new Table(s);
t["ObjectId"] = (double)objectId;
return DynValue.NewTable(t);
});
WorldFireDestroyed(objectId);
}
partial void WorldOnChatText(string text, int chatType)
{
string message = text.TrimEnd('\r', '\n');
ChatKind kind = ClassifyChat(message, chatType, out int room, out string senderName, out uint senderId, out string body);
// UB's ChatEventArgs: SenderId, SenderName, Message, Room (ChatChannel), Type
// (ChatMessageType), Eat. Incoming lines can't be eaten here (the engine hands them
// over after AC showed them), so Eat is always false.
DynValue Args(Script s, string msg)
{
var t = new Table(s);
t["Message"] = msg;
t["Type"] = (double)chatType;
t["SenderName"] = senderName;
t["SenderId"] = (double)senderId;
t["Room"] = (double)room;
t["Eat"] = false;
return DynValue.NewTable(t);
}
FireAll("World.OnChatText", s => Args(s, message));
string? specific = kind switch
{
ChatKind.Tell => "World.OnTell",
ChatKind.Local => "World.OnLocalMessage",
ChatKind.Channel => "World.OnChannelMessage",
ChatKind.Fellow => "World.OnFellowMessage",
ChatKind.Emote => "World.OnEmote",
_ => null,
};
if (specific != null) FireAll(specific, s => Args(s, kind == ChatKind.Emote ? message : body));
}
partial void WorldOnSelected(uint currentId, uint previousId)
{
if (currentId != 0)
{
_worldKnown.Add(currentId);
_worldReleased.Remove(currentId);
}
FireWorld("World.OnSelected", (s, ctx) =>
{
var t = new Table(s);
t["ObjectId"] = (double)currentId;
t["PreviousId"] = (double)previousId;
t["Object"] = WrapObject(s, ctx, currentId);
return DynValue.NewTable(t);
});
}
///
/// Like FireAll, for args that hold WorldObjects (WrapObject needs the script's context).
/// Cheap when nobody listens: the scripts are only copied once one has a handler.
///
private void FireWorld(string key, Func