XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEEDToolBox

【WinUI】XFE精英危险工具箱

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using XFEEDToolBox.Core.Navigation;

namespace XFEEDToolBox.Plugin;

internal static unsafe partial class Navigation
{
    [StructLayout(LayoutKind.Sequential)]
    internal struct ScoThermalNativeSource
    {internal ulong Id;internal double RequestedRate,UpperRate;internal uint VerifiedSco;}
    [InlineArray(64)]
    internal struct ScoThermalNativeSources{private ScoThermalNativeSource first;}
    [StructLayout(LayoutKind.Sequential)]
    internal struct ScoThermalNativeSnapshot
    {
        internal uint Schema,Size,Ready,CoolingActive,SourceCount;
        internal ulong Entity,World,ObservedAtUnixMilliseconds;
        internal nuint HeatManager;
        internal double WindowSimulationSeconds,TotalRequestedRate,ScoObservedInputUpper,OtherInputUpper,HeatCapacity,HeatDisplayScale,
            CoolingPassive,CoolingMaximum,CoolingScale,CoolingHeatLower,CoolingHeatUpper,CoolingActual,StoredEnergy,NativeHeatStepSeconds;
        internal ScoThermalNativeSources Sources;
    }
    private static double ScoThermalEncoded(nuint address)
    {var encoded=Read<ulong>(address);return BitConverter.UInt32BitsToSingle((uint)encoded^(uint)(encoded>>32));}
    private static string ScoThermalSourceLabel(nuint source)
    {
        if(source==0)return "Unidentified source";
        if(!InImage(source))return "Unidentified source @"+source.ToString("x");
        try
        {
            Span<byte> text=stackalloc byte[96];var length=0;
            for(;length<text.Length;length++)
            {var next=Read<byte>(source+(nuint)length);if(next==0)break;if(next is <32 or >126)return "Unidentified image source +"+(source-image).ToString("x");text[length]=next;}
            return length is >0 and <96?System.Text.Encoding.ASCII.GetString(text[..length]):"Unidentified image source +"+(source-image).ToString("x");
        }
        catch{return "Unidentified image source +"+(source-image).ToString("x");}
    }

#if PLUGIN_LOADER
    private static readonly object scoThermalSourceLock=new();
    private static readonly ScoThermalSourceLedger scoThermalLedger=new();
    private static readonly Dictionary<nuint,string> scoThermalLabels=new();
    private static ScoThermalNativeSnapshot scoThermalPublished;
    private static ulong scoThermalEntity,scoThermalWorld,scoThermalLastPublished;
    private static nuint scoThermalManager;
    private static void BindScoThermalLedger(in Snapshot frame)
    {
        if(scoThermalEntity==frame.entity&&scoThermalWorld==frame.referenceWorld&&scoThermalManager==frame.heatManager)return;
        scoThermalLedger.Reset();scoThermalPublished=default;scoThermalLastPublished=0;
        scoThermalEntity=frame.entity;scoThermalWorld=frame.referenceWorld;scoThermalManager=frame.heatManager;
    }
    private static void ObserveScoThermalInput(in Snapshot frame,nuint receiver,float amount,nuint label)
    {
        if(receiver!=frame.heatManager+0x60)return;
        var verifiedSco=false;
        if(label==image+0x533E808)
        {
            var sco=RegisteredComponent(Pointer(frame.life+0xC8)-0x30,Read<uint>(image+0x5F44D00));
            verifiedSco=sco>=0x10000&&Pointer(sco)==image+0x533E6E0&&Pointer(sco-0x58)==image+0x533E5B0
                &&Pointer(Pointer(sco)+0x20)==image+0x2EAACD0&&Pointer(sco-0x58+0x168)==receiver&&Read<byte>(sco+0x228)==2;
        }
        lock(scoThermalSourceLock)
        {
            BindScoThermalLedger(frame);
            if(!scoThermalLabels.TryGetValue(label,out var name))
            {name=ScoThermalSourceLabel(label);if(scoThermalLabels.Count<128)scoThermalLabels.Add(label,name);}
            // The original method may cap or ignore a request. Never claim this pre-call observation is accepted energy.
            scoThermalLedger.ObserveInput((ulong)label,name,amount,verifiedSco);
        }
    }
    private static void ObserveScoThermalTick(in Snapshot frame,float simulationDt)
    {
        lock(scoThermalSourceLock)
        {
            BindScoThermalLedger(frame);var utc=UtcMilliseconds();scoThermalLedger.ObserveTick(simulationDt,utc);
            var now=GetTickCount64();if(scoThermalLastPublished!=0&&now-scoThermalLastPublished<20)return;scoThermalLastPublished=now;
            var sources=scoThermalLedger.Read(utc);var fsd=CurrentFsd();
            var physical=fsd.entity==frame.entity&&fsd.life==frame.life&&fsd.fsd==frame.fsd&&fsd.tick!=0&&fsd.tick<=now&&now-fsd.tick<=200
                &&fsd.driveParametersValid&&fsd.coolingConfigurationValid&&fsd.coolingActive&&frame.heatDisplayScale>0;
            var stored=ScoThermalEncoded(frame.heatManager+0x190);
            var value=new ScoThermalNativeSnapshot{Schema=1,Size=(uint)sizeof(ScoThermalNativeSnapshot),Ready=sources.Ready&&physical&&sources.Sources.Count<=64&&double.IsFinite(stored)&&stored>=0?1u:0u,
                Entity=frame.entity,World=frame.referenceWorld,HeatManager=frame.heatManager,ObservedAtUnixMilliseconds=sources.ObservedAtUnixMilliseconds,
                WindowSimulationSeconds=sources.WindowSimulationSeconds,TotalRequestedRate=sources.TotalRequestedEnergyPerSecond,ScoObservedInputUpper=sources.ScoInputUpper,
                OtherInputUpper=sources.OtherInputUpper,HeatCapacity=fsd.heatCapacity,HeatDisplayScale=frame.heatDisplayScale,CoolingPassive=fsd.coolingPassive,
                CoolingMaximum=fsd.coolingMaximum,CoolingScale=fsd.coolingScale,CoolingHeatLower=fsd.coolingHeatLower,CoolingHeatUpper=fsd.coolingHeatUpper,
                CoolingActual=fsd.coolingActual,CoolingActive=fsd.coolingActive?1u:0u,StoredEnergy=stored,NativeHeatStepSeconds=simulationDt,SourceCount=(uint)Math.Min(sources.Sources.Count,64)};
            for(var index=0;index<value.SourceCount;index++)
            {
                var source=sources.Sources[index];
                value.Sources[index]=new(){Id=source.SourceId,RequestedRate=source.RequestedEnergyPerSecond,UpperRate=source.UpperEnergyPerSecond,VerifiedSco=source.VerifiedSco?1u:0u};
            }
            scoThermalPublished=value;
        }
    }
    internal static bool TryCopyScoThermal(out ScoThermalNativeSnapshot value)
    {
        value=default;if(!Monitor.TryEnter(scoThermalSourceLock))return false;
        try{value=scoThermalPublished;return value.Schema==1;}finally{Monitor.Exit(scoThermalSourceLock);}
    }
#else
    private static void ObserveScoThermalInput(in Snapshot frame,nuint receiver,float amount,nuint label){}
    private static void ObserveScoThermalTick(in Snapshot frame,float simulationDt){}
#endif

#if !PLUGIN_LOADER
    private static nuint scoThermalReader;
    private static ScoThermalNativeSnapshot scoThermalLastRead;
    [DllImport("kernel32.dll",EntryPoint="GetProcAddress",ExactSpelling=true,CharSet=CharSet.Ansi)]
    private static extern nuint ScoThermalGetProcAddress(nint module,string name);
#endif
    internal static bool ReadSharedScoThermal(out ScoThermalNativeSnapshot value)
    {
#if PLUGIN_LOADER
        return TryCopyScoThermal(out value);
#else
        if(scoThermalReader==0)
        {
            // The loader also forwards to System32/dinput8.dll. Resolve the
            // explicitly installed game-directory module rather than a basename.
            var path=Path.Combine(Path.GetDirectoryName(Platform.ModulePath())!,"dinput8.dll");
            var module=Platform.GetModuleHandleW(path);
            if(module!=0)scoThermalReader=ScoThermalGetProcAddress(module,"XFEReadScoThermalSnapshot");
        }
        var next=default(ScoThermalNativeSnapshot);
        if(scoThermalReader!=0&&((delegate* unmanaged<nuint,uint,uint>)scoThermalReader)((nuint)(&next),(uint)sizeof(ScoThermalNativeSnapshot))==1
            &&next.Schema==1&&next.Size==sizeof(ScoThermalNativeSnapshot)&&next.SourceCount<=64)scoThermalLastRead=next;
        value=scoThermalLastRead;return value.Schema==1;
#endif
    }
}

#if PLUGIN_LOADER
internal static unsafe class ScoThermalExports
{
    [UnmanagedCallersOnly(EntryPoint="XFEReadScoThermalSnapshot")]
    internal static uint Read(nuint destination,uint bytes)
    {
        try
        {
            if(destination==0||bytes!=sizeof(Navigation.ScoThermalNativeSnapshot)||!Navigation.TryCopyScoThermal(out var value))return 0;
            Platform.Write(destination,value);return 1;
        }
        catch{return 0;}
    }
}
#endif