Compare commits

..

14 Commits

5 changed files with 227 additions and 531 deletions

View File

@@ -3,7 +3,7 @@
<PropertyGroup> <PropertyGroup>
<Authors></Authors> <Authors></Authors>
<Company></Company> <Company></Company>
<Version>2.0.2.75</Version> <Version>2.0.3</Version>
<Description></Description> <Description></Description>
<Copyright></Copyright> <Copyright></Copyright>
<PackageProjectUrl>https://github.com/Light-Public-Syncshells/LightlessClient</PackageProjectUrl> <PackageProjectUrl>https://github.com/Light-Public-Syncshells/LightlessClient</PackageProjectUrl>

View File

@@ -1,5 +1,4 @@
using Dalamud.Utility; using FFXIVClientStructs.FFXIV.Client.Game.Character;
using FFXIVClientStructs.FFXIV.Client.Game.Character;
using LightlessSync.API.Data.Enum; using LightlessSync.API.Data.Enum;
using LightlessSync.FileCache; using LightlessSync.FileCache;
using LightlessSync.Interop.Ipc; using LightlessSync.Interop.Ipc;
@@ -12,8 +11,6 @@ using LightlessSync.Services.Mediator;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Diagnostics; using System.Diagnostics;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
namespace LightlessSync.PlayerData.Factories; namespace LightlessSync.PlayerData.Factories;
@@ -126,10 +123,8 @@ public class PlayerDataFactory
{ {
if (playerPointer == IntPtr.Zero) if (playerPointer == IntPtr.Zero)
return true; return true;
try
if (!IsPointerValid(playerPointer)) {
return true;
var character = (Character*)playerPointer; var character = (Character*)playerPointer;
if (character == null) if (character == null)
return true; return true;
@@ -138,26 +133,12 @@ public class PlayerDataFactory
if (gameObject == null) if (gameObject == null)
return true; return true;
if (!IsPointerValid((IntPtr)gameObject))
return true;
return gameObject->DrawObject == null; return gameObject->DrawObject == null;
} }
catch (AccessViolationException)
private static bool IsPointerValid(IntPtr ptr)
{ {
if (ptr == IntPtr.Zero)
return false;
try
{
_ = Marshal.ReadByte(ptr);
return true; return true;
} }
catch
{
return false;
}
} }
private static bool IsCacheFresh(CacheEntry entry) private static bool IsCacheFresh(CacheEntry entry)
@@ -556,32 +537,14 @@ public class PlayerDataFactory
var hash = g.Key; var hash = g.Key;
var resolvedPath = g.Select(f => f.ResolvedPath).Distinct(StringComparer.OrdinalIgnoreCase);
var papPathSummary = string.Join(", ", resolvedPath);
if (papPathSummary.IsNullOrEmpty())
papPathSummary = "<unknown pap path>";
Dictionary<string, List<ushort>>? papIndices = null; Dictionary<string, List<ushort>>? papIndices = null;
await _papParseLimiter.WaitAsync(ct).ConfigureAwait(false); await _papParseLimiter.WaitAsync(ct).ConfigureAwait(false);
try try
{ {
try papIndices = await Task.Run(() => _modelAnalyzer.GetBoneIndicesFromPap(hash), ct)
{
papIndices = await Task.Run(() => _modelAnalyzer.GetBoneIndicesFromPap(hash, persistToConfig: false), ct)
.ConfigureAwait(false); .ConfigureAwait(false);
} }
catch (SEHException ex)
{
_logger.LogError(ex, "SEH exception while parsing PAP file (hash={hash}, path={path}). Error code: 0x{code:X}. Skipping this animation.", hash, papPathSummary, ex.ErrorCode);
continue;
}
catch (Exception ex)
{
_logger.LogError(ex, "Unexpected error parsing PAP file (hash={hash}, path={path}). Skipping this animation.", hash, papPathSummary);
continue;
}
}
finally finally
{ {
_papParseLimiter.Release(); _papParseLimiter.Release();
@@ -590,26 +553,12 @@ public class PlayerDataFactory
if (papIndices == null || papIndices.Count == 0) if (papIndices == null || papIndices.Count == 0)
continue; continue;
bool hasValidIndices = false; if (papIndices.All(k => k.Value.DefaultIfEmpty().Max() <= 105))
try
{
hasValidIndices = papIndices.All(k => k.Value != null && k.Value.DefaultIfEmpty().Max() <= 105);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Error validating bone indices for PAP (hash={hash}, path={path}). Skipping.", hash, papPathSummary);
continue;
}
if (hasValidIndices)
continue; continue;
if (_logger.IsEnabled(LogLevel.Debug)) if (_logger.IsEnabled(LogLevel.Debug))
{
try
{ {
var papBuckets = papIndices var papBuckets = papIndices
.Where(kvp => kvp.Value is { Count: > 0 })
.Select(kvp => new .Select(kvp => new
{ {
Raw = kvp.Key, Raw = kvp.Key,
@@ -632,33 +581,15 @@ public class PlayerDataFactory
hash, hash,
string.Join(" | ", papBuckets)); string.Join(" | ", papBuckets));
} }
catch (Exception ex)
{
_logger.LogDebug(ex, "Error logging PAP bucket details for hash={hash}", hash);
}
}
bool isCompatible = false; if (XivDataAnalyzer.IsPapCompatible(localBoneSets, papIndices, mode, allowBasedShift, allownNightIndex, out var reason))
string reason = string.Empty;
try
{
isCompatible = XivDataAnalyzer.IsPapCompatible(localBoneSets, papIndices, mode, allowBasedShift, allownNightIndex, out reason);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Error checking PAP compatibility for hash={hash}, path={path}. Treating as incompatible.", hash, papPathSummary);
reason = $"Exception during compatibility check: {ex.Message}";
isCompatible = false;
}
if (isCompatible)
continue; continue;
noValidationFailed++; noValidationFailed++;
_logger.LogWarning( _logger.LogWarning(
"Animation PAP is not compatible with local skeletons; dropping mappings for {papPath}. Reason: {reason}", "Animation PAP hash {hash} is not compatible with local skeletons; dropping all mappings for this hash. Reason: {reason}",
papPathSummary, hash,
reason); reason);
var removedGamePaths = fragment.FileReplacements var removedGamePaths = fragment.FileReplacements

View File

@@ -78,6 +78,7 @@ public sealed class GameObjectHandler : DisposableMediatorSubscriberBase, IHighP
if (msg.Address == Address) if (msg.Address == Address)
{ {
_haltProcessing = false; _haltProcessing = false;
Refresh();
} }
}); });
@@ -169,13 +170,19 @@ public sealed class GameObjectHandler : DisposableMediatorSubscriberBase, IHighP
return $"{owned}/{ObjectKind}:{Name} ({Address:X},{DrawObjectAddress:X})"; return $"{owned}/{ObjectKind}:{Name} ({Address:X},{DrawObjectAddress:X})";
} }
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
Mediator.Publish(new GameObjectHandlerDestroyedMessage(this, _isOwnedObject));
}
private void CheckAndUpdateObject() => CheckAndUpdateObject(allowPublish: true); private void CheckAndUpdateObject() => CheckAndUpdateObject(allowPublish: true);
private unsafe void CheckAndUpdateObject(bool allowPublish) private unsafe void CheckAndUpdateObject(bool allowPublish = true)
{ {
var prevAddr = Address; var prevAddr = Address;
var prevDrawObj = DrawObjectAddress; var prevDrawObj = DrawObjectAddress;
string? nameString = null;
Address = _getAddress(); Address = _getAddress();
@@ -186,9 +193,10 @@ public sealed class GameObjectHandler : DisposableMediatorSubscriberBase, IHighP
EntityId = gameObject->EntityId; EntityId = gameObject->EntityId;
var chara = (Character*)Address; var chara = (Character*)Address;
nameString = chara->GameObject.NameString; var newName = chara->GameObject.NameString;
if (!string.IsNullOrEmpty(nameString) && !string.Equals(nameString, Name, StringComparison.Ordinal))
Name = nameString; if (!string.IsNullOrEmpty(newName) && !string.Equals(newName, Name, StringComparison.Ordinal))
Name = newName;
} }
else else
{ {
@@ -206,18 +214,16 @@ public sealed class GameObjectHandler : DisposableMediatorSubscriberBase, IHighP
if (Address != IntPtr.Zero && DrawObjectAddress != IntPtr.Zero) if (Address != IntPtr.Zero && DrawObjectAddress != IntPtr.Zero)
{ {
var chara = (Character*)Address; var chara = (Character*)Address;
var drawObj = (DrawObject*)DrawObjectAddress; var name = chara->GameObject.NameString;
var objType = drawObj->Object.GetObjectType(); bool nameChange = !string.Equals(name, Name, StringComparison.Ordinal);
var isHuman = objType == ObjectType.CharacterBase if (nameChange)
&& ((CharacterBase*)drawObj)->GetModelType() == CharacterBase.ModelType.Human; {
Name = name;
nameString ??= ((Character*)Address)->GameObject.NameString; }
var nameChange = !string.Equals(nameString, Name, StringComparison.Ordinal);
if (nameChange) Name = nameString;
bool equipDiff = false; bool equipDiff = false;
if (isHuman) if (((DrawObject*)DrawObjectAddress)->Object.GetObjectType() == ObjectType.CharacterBase
&& ((CharacterBase*)DrawObjectAddress)->GetModelType() == CharacterBase.ModelType.Human)
{ {
var classJob = chara->CharacterData.ClassJob; var classJob = chara->CharacterData.ClassJob;
if (classJob != _classJob) if (classJob != _classJob)
@@ -227,7 +233,7 @@ public sealed class GameObjectHandler : DisposableMediatorSubscriberBase, IHighP
Mediator.Publish(new ClassJobChangedMessage(this)); Mediator.Publish(new ClassJobChangedMessage(this));
} }
equipDiff = CompareAndUpdateEquipByteData((byte*)&((Human*)drawObj)->Head); equipDiff = CompareAndUpdateEquipByteData((byte*)&((Human*)DrawObjectAddress)->Head);
ref var mh = ref chara->DrawData.Weapon(WeaponSlot.MainHand); ref var mh = ref chara->DrawData.Weapon(WeaponSlot.MainHand);
ref var oh = ref chara->DrawData.Weapon(WeaponSlot.OffHand); ref var oh = ref chara->DrawData.Weapon(WeaponSlot.OffHand);
@@ -252,11 +258,12 @@ public sealed class GameObjectHandler : DisposableMediatorSubscriberBase, IHighP
bool customizeDiff = false; bool customizeDiff = false;
if (isHuman) if (((DrawObject*)DrawObjectAddress)->Object.GetObjectType() == ObjectType.CharacterBase
&& ((CharacterBase*)DrawObjectAddress)->GetModelType() == CharacterBase.ModelType.Human)
{ {
var gender = ((Human*)drawObj)->Customize.Sex; var gender = ((Human*)DrawObjectAddress)->Customize.Sex;
var raceId = ((Human*)drawObj)->Customize.Race; var raceId = ((Human*)DrawObjectAddress)->Customize.Race;
var tribeId = ((Human*)drawObj)->Customize.Tribe; var tribeId = ((Human*)DrawObjectAddress)->Customize.Tribe;
if (_isOwnedObject && ObjectKind == ObjectKind.Player if (_isOwnedObject && ObjectKind == ObjectKind.Player
&& (gender != Gender || raceId != RaceId || tribeId != TribeId)) && (gender != Gender || raceId != RaceId || tribeId != TribeId))
@@ -267,7 +274,7 @@ public sealed class GameObjectHandler : DisposableMediatorSubscriberBase, IHighP
TribeId = tribeId; TribeId = tribeId;
} }
customizeDiff = CompareAndUpdateCustomizeData(((Human*)drawObj)->Customize.Data); customizeDiff = CompareAndUpdateCustomizeData(((Human*)DrawObjectAddress)->Customize.Data);
if (customizeDiff) if (customizeDiff)
Logger.LogTrace("Checking [{this}] customize data as human from draw obj, result: {diff}", this, customizeDiff); Logger.LogTrace("Checking [{this}] customize data as human from draw obj, result: {diff}", this, customizeDiff);
} }

View File

@@ -705,7 +705,7 @@ public class DalamudUtilService : IHostedService, IMediatorSubscriber
if (location.ServerId is 0 || location.TerritoryId is 0) return String.Empty; if (location.ServerId is 0 || location.TerritoryId is 0) return String.Empty;
var str = WorldData.Value[(ushort)location.ServerId]; var str = WorldData.Value[(ushort)location.ServerId];
if (ContentFinderData.Value.TryGetValue(location.TerritoryId, out var dutyName)) if (ContentFinderData.Value.TryGetValue(location.TerritoryId , out var dutyName))
{ {
str += $" - [In Duty]{dutyName}"; str += $" - [In Duty]{dutyName}";
} }
@@ -881,7 +881,7 @@ public class DalamudUtilService : IHostedService, IMediatorSubscriber
{ {
// ignore // ignore
} }
catch (Exception ex) catch (AccessViolationException ex)
{ {
logger.LogWarning(ex, "Error accessing {handler}, object does not exist anymore?", handler); logger.LogWarning(ex, "Error accessing {handler}, object does not exist anymore?", handler);
} }
@@ -953,70 +953,21 @@ public class DalamudUtilService : IHostedService, IMediatorSubscriber
}); });
} }
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool IsBadReadPtr(IntPtr ptr, UIntPtr size);
private static bool IsValidPointer(nint ptr, int size = 8)
{
if (ptr == nint.Zero)
return false;
try
{
if (!Util.IsWine())
{
return !IsBadReadPtr(ptr, (UIntPtr)size);
}
return ptr != nint.Zero && (ptr % IntPtr.Size) == 0;
}
catch
{
return false;
}
}
private unsafe void CheckCharacterForDrawing(nint address, string characterName) private unsafe void CheckCharacterForDrawing(nint address, string characterName)
{ {
if (address == nint.Zero)
return;
if (!IsValidPointer(address))
{
_logger.LogDebug("Invalid pointer for character {name} at {addr}", characterName, address.ToString("X"));
return;
}
var gameObj = (GameObject*)address; var gameObj = (GameObject*)address;
if (gameObj == null)
return;
if (!_objectTable.Any(o => o?.Address == address))
{
_logger.LogDebug("Character {name} at {addr} no longer in object table", characterName, address.ToString("X"));
return;
}
if (gameObj->ObjectKind == 0)
return;
var drawObj = gameObj->DrawObject; var drawObj = gameObj->DrawObject;
bool isDrawing = false; bool isDrawing = false;
bool isDrawingChanged = false; bool isDrawingChanged = false;
if ((nint)drawObj != IntPtr.Zero)
if ((nint)drawObj != IntPtr.Zero && IsValidPointer((nint)drawObj))
{ {
isDrawing = gameObj->RenderFlags == (VisibilityFlags)0b100000000000; isDrawing = gameObj->RenderFlags == (VisibilityFlags)0b100000000000;
if (!isDrawing) if (!isDrawing)
{ {
var charBase = (CharacterBase*)drawObj; isDrawing = ((CharacterBase*)drawObj)->HasModelInSlotLoaded != 0;
if (charBase != null && IsValidPointer((nint)charBase))
{
isDrawing = charBase->HasModelInSlotLoaded != 0;
if (!isDrawing) if (!isDrawing)
{ {
isDrawing = charBase->HasModelFilesInSlotLoaded != 0; isDrawing = ((CharacterBase*)drawObj)->HasModelFilesInSlotLoaded != 0;
if (isDrawing && !string.Equals(_lastGlobalBlockPlayer, characterName, StringComparison.Ordinal) if (isDrawing && !string.Equals(_lastGlobalBlockPlayer, characterName, StringComparison.Ordinal)
&& !string.Equals(_lastGlobalBlockReason, "HasModelFilesInSlotLoaded", StringComparison.Ordinal)) && !string.Equals(_lastGlobalBlockReason, "HasModelFilesInSlotLoaded", StringComparison.Ordinal))
{ {
@@ -1036,7 +987,6 @@ public class DalamudUtilService : IHostedService, IMediatorSubscriber
} }
} }
} }
}
else else
{ {
if (!string.Equals(_lastGlobalBlockPlayer, characterName, StringComparison.Ordinal) if (!string.Equals(_lastGlobalBlockPlayer, characterName, StringComparison.Ordinal)
@@ -1064,11 +1014,6 @@ public class DalamudUtilService : IHostedService, IMediatorSubscriber
private unsafe void FrameworkOnUpdateInternal() private unsafe void FrameworkOnUpdateInternal()
{ {
if (!_clientState.IsLoggedIn || _objectTable.LocalPlayer == null)
{
return;
}
if ((_objectTable.LocalPlayer?.IsDead ?? false) && _condition[ConditionFlag.BoundByDuty]) if ((_objectTable.LocalPlayer?.IsDead ?? false) && _condition[ConditionFlag.BoundByDuty])
{ {
return; return;
@@ -1088,17 +1033,12 @@ public class DalamudUtilService : IHostedService, IMediatorSubscriber
} }
var playerDescriptors = _actorObjectService.PlayerDescriptors; var playerDescriptors = _actorObjectService.PlayerDescriptors;
var descriptorCount = playerDescriptors.Count; for (var i = 0; i < playerDescriptors.Count; i++)
for (var i = 0; i < descriptorCount; i++)
{ {
if (i >= playerDescriptors.Count)
break;
var actor = playerDescriptors[i]; var actor = playerDescriptors[i];
var playerAddress = actor.Address; var playerAddress = actor.Address;
if (playerAddress == nint.Zero || !IsValidPointer(playerAddress)) if (playerAddress == nint.Zero)
continue; continue;
if (actor.ObjectIndex >= 200) if (actor.ObjectIndex >= 200)
@@ -1112,16 +1052,17 @@ public class DalamudUtilService : IHostedService, IMediatorSubscriber
if (!IsAnythingDrawing) if (!IsAnythingDrawing)
{ {
if (!_objectTable.Any(o => o?.Address == playerAddress)) var gameObj = (GameObject*)playerAddress;
{ var currentName = gameObj != null ? gameObj->NameString ?? string.Empty : string.Empty;
continue; var charaName = string.IsNullOrEmpty(currentName) ? actor.Name : currentName;
} CheckCharacterForDrawing(playerAddress, charaName);
CheckCharacterForDrawing(playerAddress, actor.Name);
if (IsAnythingDrawing) if (IsAnythingDrawing)
break; break;
} }
else
{
break;
}
} }
}); });
@@ -1190,7 +1131,7 @@ public class DalamudUtilService : IHostedService, IMediatorSubscriber
}); });
// Cutscene // Cutscene
HandleStateTransition(() => IsInCutscene, v => IsInCutscene = v, shouldBeInCutscene, "Cutscene", HandleStateTransition(() => IsInCutscene,v => IsInCutscene = v, shouldBeInCutscene, "Cutscene",
onEnter: () => onEnter: () =>
{ {
Mediator.Publish(new CutsceneStartMessage()); Mediator.Publish(new CutsceneStartMessage());

View File

@@ -1,6 +1,5 @@
using FFXIVClientStructs.FFXIV.Client.Game.Character; using FFXIVClientStructs.FFXIV.Client.Game.Character;
using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene;
using FFXIVClientStructs.Havok.Common.Serialize.Resource;
using FFXIVClientStructs.Havok.Animation; using FFXIVClientStructs.Havok.Animation;
using FFXIVClientStructs.Havok.Common.Base.Types; using FFXIVClientStructs.Havok.Common.Base.Types;
using FFXIVClientStructs.Havok.Common.Serialize.Util; using FFXIVClientStructs.Havok.Common.Serialize.Util;
@@ -146,18 +145,10 @@ public sealed partial class XivDataAnalyzer
using var reader = new BinaryReader(fs); using var reader = new BinaryReader(fs);
// PAP header (mostly from vfxeditor) // PAP header (mostly from vfxeditor)
try
{
_ = reader.ReadInt32(); // ignore _ = reader.ReadInt32(); // ignore
_ = reader.ReadInt32(); // ignore _ = reader.ReadInt32(); // ignore
var numAnimations = reader.ReadInt16(); // num animations _ = reader.ReadInt16(); // num animations
var modelId = reader.ReadInt16(); // modelid _ = reader.ReadInt16(); // modelid
if (numAnimations < 0 || numAnimations > 1000)
{
_logger.LogWarning("PAP file {hash} has invalid animation count {count}, skipping", hash, numAnimations);
return null;
}
var type = reader.ReadByte(); // type var type = reader.ReadByte(); // type
if (type != 0) if (type != 0)
@@ -169,94 +160,33 @@ public sealed partial class XivDataAnalyzer
var havokPosition = reader.ReadInt32(); var havokPosition = reader.ReadInt32();
var footerPosition = reader.ReadInt32(); var footerPosition = reader.ReadInt32();
if (havokPosition <= 0 || footerPosition <= havokPosition || // sanity checks
footerPosition > fs.Length || havokPosition >= fs.Length) if (havokPosition <= 0 || footerPosition <= havokPosition || footerPosition > fs.Length)
{
_logger.LogWarning("PAP file {hash} has invalid offsets (havok={havok}, footer={footer}, length={length})",
hash, havokPosition, footerPosition, fs.Length);
return null; return null;
}
var havokDataSizeLong = (long)footerPosition - havokPosition; var havokDataSizeLong = (long)footerPosition - havokPosition;
if (havokDataSizeLong <= 8 || havokDataSizeLong > int.MaxValue) if (havokDataSizeLong <= 8 || havokDataSizeLong > int.MaxValue)
{
_logger.LogWarning("PAP file {hash} has invalid Havok data size {size}", hash, havokDataSizeLong);
return null; return null;
}
var havokDataSize = (int)havokDataSizeLong; var havokDataSize = (int)havokDataSizeLong;
reader.BaseStream.Position = havokPosition; reader.BaseStream.Position = havokPosition;
var havokData = reader.ReadBytes(havokDataSize);
var havokData = new byte[havokDataSize]; if (havokData.Length <= 8)
var bytesRead = reader.Read(havokData, 0, havokDataSize);
if (bytesRead != havokDataSize)
{
_logger.LogWarning("PAP file {hash}: Expected to read {expected} bytes but got {actual}",
hash, havokDataSize, bytesRead);
return null;
}
if (havokData.Length < 8)
return null; return null;
var tempSets = new Dictionary<string, HashSet<ushort>>(StringComparer.OrdinalIgnoreCase); var tempSets = new Dictionary<string, HashSet<ushort>>(StringComparer.OrdinalIgnoreCase);
var tempFileName = $"lightless_pap_{Guid.NewGuid():N}_{hash[..Math.Min(8, hash.Length)]}.hkx"; var tempHavokDataPath = Path.Combine(Path.GetTempPath(), $"lightless_{Guid.NewGuid():N}.hkx");
var tempHavokDataPath = Path.Combine(Path.GetTempPath(), tempFileName);
IntPtr tempHavokDataPathAnsi = IntPtr.Zero; IntPtr tempHavokDataPathAnsi = IntPtr.Zero;
try
{
var tempDir = Path.GetDirectoryName(tempHavokDataPath);
if (!Directory.Exists(tempDir))
{
_logger.LogWarning("Temp directory {dir} doesn't exist", tempDir);
return null;
}
// Write the file with explicit error handling
try try
{ {
File.WriteAllBytes(tempHavokDataPath, havokData); File.WriteAllBytes(tempHavokDataPath, havokData);
}
catch (Exception writeEx)
{
_logger.LogError(writeEx, "Failed to write temporary Havok file to {path}", tempHavokDataPath);
return null;
}
if (!File.Exists(tempHavokDataPath)) if (!File.Exists(tempHavokDataPath))
{ {
_logger.LogWarning("Temporary havok file was not created at {path}", tempHavokDataPath); _logger.LogTrace("Temporary havok file did not exist when attempting to load: {path}", tempHavokDataPath);
return null;
}
var writtenFileInfo = new FileInfo(tempHavokDataPath);
if (writtenFileInfo.Length != havokData.Length)
{
_logger.LogWarning("Written temp file size mismatch: expected {expected}, got {actual}",
havokData.Length, writtenFileInfo.Length);
try { File.Delete(tempHavokDataPath); } catch { }
return null;
}
Thread.Sleep(10); // stabilize file system
try
{
using var testStream = File.OpenRead(tempHavokDataPath);
if (testStream.Length != havokData.Length)
{
_logger.LogWarning("File verification failed: length mismatch after write");
try { File.Delete(tempHavokDataPath); } catch { }
return null;
}
}
catch (Exception readEx)
{
_logger.LogError(readEx, "Cannot read back temporary file at {path}", tempHavokDataPath);
try { File.Delete(tempHavokDataPath); } catch { }
return null; return null;
} }
@@ -270,40 +200,10 @@ public sealed partial class XivDataAnalyzer
Storage = (int)hkSerializeUtil.LoadOptionBits.Default Storage = (int)hkSerializeUtil.LoadOptionBits.Default
}; };
hkResource* resource = null; var resource = hkSerializeUtil.LoadFromFile((byte*)tempHavokDataPathAnsi, null, loadoptions);
try
{
if (tempHavokDataPathAnsi == IntPtr.Zero)
{
_logger.LogError("Failed to allocate ANSI string for path");
return null;
}
resource = hkSerializeUtil.LoadFromFile((byte*)tempHavokDataPathAnsi, null, loadoptions);
}
catch (SEHException ex)
{
_logger.LogError(ex, "SEH exception loading Havok file from {path} (hash={hash}). Native error code: 0x{code:X}. This may indicate a corrupted PAP file or incompatible Havok format.",
tempHavokDataPath, hash, ex.ErrorCode);
return null;
}
catch (Exception ex)
{
_logger.LogError(ex, "Unexpected exception loading Havok file from {path} (hash={hash})",
tempHavokDataPath, hash);
return null;
}
if (resource == null) if (resource == null)
{ {
_logger.LogDebug("Havok resource was null after loading from {path} (hash={hash}). File may be corrupted or in an unsupported format.", _logger.LogWarning("Havok resource was null after loading from {path}", tempHavokDataPath);
tempHavokDataPath, hash);
return null;
}
if ((nint)resource == nint.Zero || !IsValidPointer((IntPtr)resource))
{
_logger.LogDebug("Havok resource pointer is invalid (hash={hash})", hash);
return null; return null;
} }
@@ -312,38 +212,14 @@ public sealed partial class XivDataAnalyzer
{ {
var container = (hkRootLevelContainer*)resource->GetContentsPointer(n1, hkBuiltinTypeRegistry.Instance()->GetTypeInfoRegistry()); var container = (hkRootLevelContainer*)resource->GetContentsPointer(n1, hkBuiltinTypeRegistry.Instance()->GetTypeInfoRegistry());
if (container == null) if (container == null)
{
_logger.LogDebug("hkRootLevelContainer is null (hash={hash})", hash);
return null; return null;
}
if ((nint)container == nint.Zero || !IsValidPointer((IntPtr)container))
{
_logger.LogDebug("hkRootLevelContainer pointer is invalid (hash={hash})", hash);
return null;
}
var animationName = @"hkaAnimationContainer"u8; var animationName = @"hkaAnimationContainer"u8;
fixed (byte* n2 = animationName) fixed (byte* n2 = animationName)
{ {
var animContainer = (hkaAnimationContainer*)container->findObjectByName(n2, null); var animContainer = (hkaAnimationContainer*)container->findObjectByName(n2, null);
if (animContainer == null) if (animContainer == null)
{
_logger.LogDebug("hkaAnimationContainer is null (hash={hash})", hash);
return null; return null;
}
if ((nint)animContainer == nint.Zero || !IsValidPointer((IntPtr)animContainer))
{
_logger.LogDebug("hkaAnimationContainer pointer is invalid (hash={hash})", hash);
return null;
}
if (animContainer->Bindings.Length < 0 || animContainer->Bindings.Length > 10000)
{
_logger.LogDebug("Invalid bindings count {count} (hash={hash})", animContainer->Bindings.Length, hash);
return null;
}
for (int i = 0; i < animContainer->Bindings.Length; i++) for (int i = 0; i < animContainer->Bindings.Length; i++)
{ {
@@ -351,24 +227,14 @@ public sealed partial class XivDataAnalyzer
if (binding == null) if (binding == null)
continue; continue;
if ((nint)binding == nint.Zero || !IsValidPointer((IntPtr)binding))
{
_logger.LogDebug("Skipping invalid binding at index {index} (hash={hash})", i, hash);
continue;
}
var rawSkel = binding->OriginalSkeletonName.String; var rawSkel = binding->OriginalSkeletonName.String;
var skeletonKey = CanonicalizeSkeletonKey(rawSkel); var skeletonKey = CanonicalizeSkeletonKey(rawSkel);
if (string.IsNullOrEmpty(skeletonKey)) if (string.IsNullOrEmpty(skeletonKey))
continue; continue;
var boneTransform = binding->TransformTrackToBoneIndices; var boneTransform = binding->TransformTrackToBoneIndices;
if (boneTransform.Length <= 0 || boneTransform.Length > 10000) if (boneTransform.Length <= 0)
{
_logger.LogDebug("Invalid bone transform length {length} for skeleton {skel} (hash={hash})",
boneTransform.Length, skeletonKey, hash);
continue; continue;
}
if (!tempSets.TryGetValue(skeletonKey, out var set)) if (!tempSets.TryGetValue(skeletonKey, out var set))
{ {
@@ -379,23 +245,16 @@ public sealed partial class XivDataAnalyzer
for (int boneIdx = 0; boneIdx < boneTransform.Length; boneIdx++) for (int boneIdx = 0; boneIdx < boneTransform.Length; boneIdx++)
{ {
var v = boneTransform[boneIdx]; var v = boneTransform[boneIdx];
if (v < 0 || v > ushort.MaxValue) if (v < 0) continue;
continue;
set.Add((ushort)v); set.Add((ushort)v);
} }
} }
} }
} }
} }
catch (SEHException ex)
{
_logger.LogError(ex, "SEH exception processing PAP file {hash} from {path}. Error code: 0x{code:X}",
hash, tempHavokDataPath, ex.ErrorCode);
return null;
}
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Managed exception loading havok file {hash} from {path}", hash, tempHavokDataPath); _logger.LogWarning(ex, "Could not load havok file in {path}", tempHavokDataPath);
return null; return null;
} }
finally finally
@@ -403,39 +262,19 @@ public sealed partial class XivDataAnalyzer
if (tempHavokDataPathAnsi != IntPtr.Zero) if (tempHavokDataPathAnsi != IntPtr.Zero)
Marshal.FreeHGlobal(tempHavokDataPathAnsi); Marshal.FreeHGlobal(tempHavokDataPathAnsi);
int retryCount = 3;
while (retryCount > 0 && File.Exists(tempHavokDataPath))
{
try try
{ {
if (File.Exists(tempHavokDataPath))
File.Delete(tempHavokDataPath); File.Delete(tempHavokDataPath);
break;
}
catch (IOException ex)
{
retryCount--;
if (retryCount == 0)
{
_logger.LogDebug(ex, "Failed to delete temporary havok file after retries: {path}", tempHavokDataPath);
}
else
{
Thread.Sleep(50);
}
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogDebug(ex, "Unexpected error deleting temporary havok file: {path}", tempHavokDataPath); _logger.LogTrace(ex, "Could not delete temporary havok file: {path}", tempHavokDataPath);
break;
}
} }
} }
if (tempSets.Count == 0) if (tempSets.Count == 0)
{
_logger.LogDebug("No bone sets found in PAP file (hash={hash})", hash);
return null; return null;
}
var output = new Dictionary<string, List<ushort>>(tempSets.Count, StringComparer.OrdinalIgnoreCase); var output = new Dictionary<string, List<ushort>>(tempSets.Count, StringComparer.OrdinalIgnoreCase);
foreach (var (key, set) in tempSets) foreach (var (key, set) in tempSets)
@@ -457,28 +296,6 @@ public sealed partial class XivDataAnalyzer
return output; return output;
} }
catch (Exception ex)
{
_logger.LogError(ex, "Outer exception reading PAP file (hash={hash})", hash);
return null;
}
}
private static bool IsValidPointer(IntPtr ptr)
{
if (ptr == IntPtr.Zero)
return false;
try
{
_ = Marshal.ReadByte(ptr);
return true;
}
catch
{
return false;
}
}
public static string CanonicalizeSkeletonKey(string? raw) public static string CanonicalizeSkeletonKey(string? raw)