Files
LightlessClient/LightlessSync/PlayerData/Handlers/GameObjectHandler.cs

409 lines
13 KiB
C#

using Dalamud.Game.ClientState.Objects.Types;
using LightlessSync.Services;
using LightlessSync.Services.Mediator;
using Microsoft.Extensions.Logging;
using ObjectKind = LightlessSync.API.Data.Enum.ObjectKind;
using Dalamud.Game.ClientState.Objects.Enums;
using Dalamud.Plugin.Services;
namespace LightlessSync.PlayerData.Handlers;
public sealed class GameObjectHandler : DisposableMediatorSubscriberBase, IHighPriorityMediatorSubscriber
{
private readonly DalamudUtilService _dalamudUtil;
private readonly IObjectTable _objectTable;
private readonly Func<IntPtr> _getAddress;
private readonly bool _isOwnedObject;
private readonly PerformanceCollectorService _performanceCollector;
private readonly object _frameworkUpdateGate = new();
private bool _frameworkUpdateSubscribed;
private byte _classJob = 0;
private Task? _delayedZoningTask;
private bool _haltProcessing = false;
private CancellationTokenSource _zoningCts = new();
public GameObjectHandler(ILogger<GameObjectHandler> logger, PerformanceCollectorService performanceCollector,
LightlessMediator mediator, DalamudUtilService dalamudUtil, ObjectKind objectKind, Func<IntPtr> getAddress, IObjectTable objectTable, bool ownedObject = true) : base(logger, mediator)
{
_performanceCollector = performanceCollector;
ObjectKind = objectKind;
_dalamudUtil = dalamudUtil;
_getAddress = () =>
{
_dalamudUtil.EnsureIsOnFramework();
return getAddress.Invoke();
};
_isOwnedObject = ownedObject;
Name = string.Empty;
if (ownedObject)
{
Mediator.Subscribe<TransientResourceChangedMessage>(this, (msg) =>
{
if (_delayedZoningTask?.IsCompleted ?? true)
{
if (msg.Address != Address) return;
Mediator.Publish(new CreateCacheForObjectMessage(this));
}
});
}
if (_isOwnedObject)
{
EnableFrameworkUpdates();
}
Mediator.Subscribe<ZoneSwitchEndMessage>(this, (_) => ZoneSwitchEnd());
Mediator.Subscribe<ZoneSwitchStartMessage>(this, (_) => ZoneSwitchStart());
Mediator.Subscribe<CutsceneStartMessage>(this, (_) =>
{
_haltProcessing = true;
});
Mediator.Subscribe<CutsceneEndMessage>(this, (_) =>
{
_haltProcessing = false;
ZoneSwitchEnd();
});
Mediator.Subscribe<PenumbraStartRedrawMessage>(this, (msg) =>
{
if (msg.Address == Address)
{
_haltProcessing = true;
}
});
Mediator.Subscribe<PenumbraEndRedrawMessage>(this, (msg) =>
{
if (msg.Address == Address)
{
_haltProcessing = false;
}
});
Mediator.Publish(new GameObjectHandlerCreatedMessage(this, _isOwnedObject));
_objectTable = objectTable;
_dalamudUtil.RunOnFrameworkThread(CheckAndUpdateObject).GetAwaiter().GetResult();
}
public enum DrawCondition
{
None,
ObjectZero,
DrawObjectZero,
RenderFlags,
ModelInSlotLoaded,
ModelFilesInSlotLoaded
}
public IntPtr Address { get; private set; }
public DrawCondition CurrentDrawCondition { get; set; } = DrawCondition.None;
public byte Gender { get; private set; }
public string Name { get; private set; }
public uint EntityId { get; private set; } = uint.MaxValue;
public ObjectKind ObjectKind { get; }
public byte RaceId { get; private set; }
public byte TribeId { get; private set; }
private byte[] CustomizeData { get; set; } = new byte[26];
private IntPtr DrawObjectAddress { get; set; }
private byte[] EquipSlotData { get; set; } = new byte[40];
private ushort[] MainHandData { get; set; } = new ushort[3];
private ushort[] OffHandData { get; set; } = new ushort[3];
public async Task ActOnFrameworkAfterEnsureNoDrawAsync(Action<ICharacter> act, CancellationToken token)
{
while (await _dalamudUtil.RunOnFrameworkThread(() =>
{
EnsureLatestObjectState();
if (CurrentDrawCondition != DrawCondition.None) return true;
var gameObj = _dalamudUtil.CreateGameObject(Address);
if (gameObj is ICharacter chara)
{
act.Invoke(chara);
}
return false;
}).ConfigureAwait(false))
{
await Task.Delay(250, token).ConfigureAwait(false);
}
}
public void CompareNameAndThrow(string name)
{
if (!string.Equals(Name, name, StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException("Player name not equal to requested name, pointer invalid");
}
if (Address == IntPtr.Zero)
{
throw new InvalidOperationException("Player pointer is zero, pointer invalid");
}
}
public IGameObject? GetGameObject()
{
return _dalamudUtil.CreateGameObject(Address);
}
public void Invalidate()
{
Address = IntPtr.Zero;
DrawObjectAddress = IntPtr.Zero;
EntityId = uint.MaxValue;
_haltProcessing = false;
}
public void Refresh()
{
_dalamudUtil.RunOnFrameworkThread(CheckAndUpdateObject).GetAwaiter().GetResult();
}
public async Task<bool> IsBeingDrawnRunOnFrameworkAsync()
{
return await _dalamudUtil.RunOnFrameworkThread(IsBeingDrawn).ConfigureAwait(false);
}
public override string ToString()
{
var owned = _isOwnedObject ? "Self" : "Other";
return $"{owned}/{ObjectKind}:{Name} ({Address:X},{DrawObjectAddress:X})";
}
private IGameObject? TryGetObjectByAddress(nint address)
{
if (address == nint.Zero) return null;
foreach (var obj in _objectTable)
{
if (obj is null) continue;
if (obj.Address == address)
return obj;
}
return null;
}
private void CheckAndUpdateObject() => CheckAndUpdateObject(allowPublish: true);
private void CheckAndUpdateObject(bool allowPublish)
{
var prevAddr = Address;
var prevDrawObj = DrawObjectAddress;
string? nameString = null;
Address = _getAddress();
IGameObject? obj = null;
ICharacter? chara = null;
if (Address != nint.Zero)
{
obj = TryGetObjectByAddress(Address);
if (obj is not null)
{
EntityId = obj.EntityId;
DrawObjectAddress = Address;
nameString = obj.Name.TextValue ?? string.Empty;
if (!string.IsNullOrEmpty(nameString) && !string.Equals(nameString, Name, StringComparison.Ordinal))
Name = nameString;
chara = obj as ICharacter;
}
else
{
DrawObjectAddress = nint.Zero;
EntityId = uint.MaxValue;
}
}
else
{
DrawObjectAddress = nint.Zero;
EntityId = uint.MaxValue;
}
CurrentDrawCondition = IsBeingDrawnSafe(obj, chara);
if (_haltProcessing || !allowPublish) return;
bool drawObjDiff = DrawObjectAddress != prevDrawObj;
bool addrDiff = Address != prevAddr;
bool nameChange = false;
if (nameString is not null)
{
nameChange = !string.Equals(nameString, Name, StringComparison.Ordinal);
if (nameChange) Name = nameString;
}
bool customizeDiff = false;
if (chara is not null)
{
var classJob = chara.ClassJob.RowId;
if (classJob != _classJob)
{
Logger.LogTrace("[{this}] classjob changed from {old} to {new}", this, _classJob, classJob);
_classJob = (byte)classJob;
Mediator.Publish(new ClassJobChangedMessage(this));
}
customizeDiff = CompareAndUpdateCustomizeData(chara.Customize);
if (_isOwnedObject && ObjectKind == ObjectKind.Player && chara.Customize.Length > (int)CustomizeIndex.Tribe)
{
var gender = chara.Customize[(int)CustomizeIndex.Gender];
var raceId = chara.Customize[(int)CustomizeIndex.Race];
var tribeId = chara.Customize[(int)CustomizeIndex.Tribe];
if (gender != Gender || raceId != RaceId || tribeId != TribeId)
{
Mediator.Publish(new CensusUpdateMessage(gender, raceId, tribeId));
Gender = gender;
RaceId = raceId;
TribeId = tribeId;
}
}
}
if ((addrDiff || drawObjDiff || customizeDiff || nameChange) && _isOwnedObject)
{
Logger.LogDebug("[{this}] Changed, Sending CreateCacheObjectMessage", this);
Mediator.Publish(new CreateCacheForObjectMessage(this));
}
else if (addrDiff || drawObjDiff)
{
if (Address == nint.Zero)
CurrentDrawCondition = DrawCondition.ObjectZero;
else if (DrawObjectAddress == nint.Zero)
CurrentDrawCondition = DrawCondition.DrawObjectZero;
Logger.LogTrace("[{this}] Changed", this);
if (_isOwnedObject && ObjectKind != ObjectKind.Player)
Mediator.Publish(new ClearCacheForObjectMessage(this));
}
}
private DrawCondition IsBeingDrawnSafe(IGameObject? obj, ICharacter? chara)
{
if (Address == nint.Zero) return DrawCondition.ObjectZero;
if (obj is null) return DrawCondition.DrawObjectZero;
if (chara is not null && (chara.Customize is null || chara.Customize.Length == 0))
return DrawCondition.DrawObjectZero;
return DrawCondition.None;
}
private bool CompareAndUpdateCustomizeData(ReadOnlySpan<byte> customizeData)
{
bool hasChanges = false;
var len = Math.Min(customizeData.Length, CustomizeData.Length);
for (int i = 0; i < len; i++)
{
var data = customizeData[i];
if (CustomizeData[i] != data)
{
CustomizeData[i] = data;
hasChanges = true;
}
}
return hasChanges;
}
private void FrameworkUpdate()
{
try
{
var zoningDelayActive = !(_delayedZoningTask?.IsCompleted ?? true);
_performanceCollector.LogPerformance(this, $"CheckAndUpdateObject>{(_isOwnedObject ? "Self" : "Other")}+{ObjectKind}/{(string.IsNullOrEmpty(Name) ? "Unk" : Name)}", () => CheckAndUpdateObject(allowPublish: !zoningDelayActive));
}
catch (Exception ex)
{
Logger.LogWarning(ex, "Error during FrameworkUpdate of {this}", this);
}
}
private bool IsBeingDrawn()
{
EnsureLatestObjectState();
if (_dalamudUtil.IsAnythingDrawing)
{
Logger.LogTrace("[{this}] IsBeingDrawn, Global draw block", this);
return true;
}
Logger.LogTrace("[{this}] IsBeingDrawn, Condition: {cond}", this, CurrentDrawCondition);
return CurrentDrawCondition != DrawCondition.None;
}
private void EnsureLatestObjectState()
{
if (_haltProcessing || !_frameworkUpdateSubscribed)
{
CheckAndUpdateObject();
}
}
private void EnableFrameworkUpdates()
{
lock (_frameworkUpdateGate)
{
if (_frameworkUpdateSubscribed)
{
return;
}
Mediator.Subscribe<FrameworkUpdateMessage>(this, _ => FrameworkUpdate());
_frameworkUpdateSubscribed = true;
}
}
private void ZoneSwitchEnd()
{
if (!_isOwnedObject) return;
try
{
_zoningCts?.CancelAfter(2500);
}
catch (ObjectDisposedException)
{
// ignore
}
catch (Exception ex)
{
Logger.LogWarning(ex, "Zoning CTS cancel issue");
}
}
private void ZoneSwitchStart()
{
if (!_isOwnedObject) return;
_zoningCts = new();
Logger.LogDebug("[{obj}] Starting Delay After Zoning", this);
_delayedZoningTask = Task.Run(async () =>
{
try
{
await Task.Delay(TimeSpan.FromSeconds(120), _zoningCts.Token).ConfigureAwait(false);
}
catch
{
// ignore cancelled
}
finally
{
Logger.LogDebug("[{this}] Delay after zoning complete", this);
_zoningCts.Dispose();
}
}, _zoningCts.Token);
}
}