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

XFEEDToolBox

【WinUI】XFE精英危险工具箱

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Buffers.Binary;
using System.Text;

namespace XFEEDToolBox.Plugin;

internal static unsafe partial class Navigation
{
    internal sealed record GalaxyCurrentTradeFlow(ulong fromSystemAddress,ulong toSystemAddress,ushort commodityToken,string? commodityName,
        float npcAmount,float playerAmount,ulong timestamp);
    internal sealed record GalaxyCurrentTradeFlows(ulong tick,ulong entity,ulong originalClock,ulong lifetimeSeconds,ulong refreshSeconds,
        uint revision,GalaxyCurrentTradeFlow[] items,int unresolvedCount)
    {
        internal bool complete=>false;
        internal string source=>"original-current-trade-flow-cache";
    }

    static string GalaxyTradeFlowSymbol(GalaxyCommodityCopy copy,nuint pointer)
    {
        var bytes=new List<byte>();
        for(nuint offset=0;offset<=256;offset++)
        {
            var value=copy.Bytes(pointer+offset,1)[0];
            if(value==0)
            {
                var text=new UTF8Encoding(false,true).GetString(bytes.ToArray());
                if(string.IsNullOrWhiteSpace(text)||text.Any(char.IsControl))throw new InvalidDataException();
                return text;
            }
            if(offset==256)break;
            bytes.Add(value);
        }
        throw new InvalidDataException();
    }

    // The TradeRoutes publisher's real short-token -> leaf-index map binds
    // names to frozen original definitions. These tokens are NOT commodity
    // UIDs, market IDs, or leaf indices. An absent publisher leaves names null.
    static Dictionary<ushort,string> CopyGalaxyCurrentTradeNames(GalaxyCommodityCopy copy,nuint component,nuint expectedImage)
    {
        if(component==0)return [];
        if(component<0x10058||copy.Ptr(component)!=expectedImage+0x552CF58||
           copy.Ptr(component-0x58)!=expectedImage+0x552CE28||copy.Ptr(component-0x50)!=expectedImage+0x552CE58||
           copy.Ptr(component-0x48)<0x10000)throw new InvalidDataException();
        var instance=component-0x58;
        var leafCount=copy.U64(instance+0x130);var leaves=copy.Ptr(instance+0x138);
        var buckets=copy.Ptr(instance+0x140);var capacity=copy.U64(instance+0x148);var count=copy.U64(instance+0x158);
        if(leafCount>4096||capacity is 0 or >65536||count>leafCount||leafCount>0&&leaves<0x10000)throw new InvalidDataException();
        var heads=copy.Bytes(buckets,checked((int)capacity*8));
        var rows=copy.Bytes(leaves,checked((int)leafCount*16));
        var result=new Dictionary<ushort,string>();var seen=new HashSet<nuint>();
        for(nuint bucket=0;bucket<(nuint)capacity;bucket++)
        {
            var sentinel=buckets+bucket*8;var node=(nuint)BinaryPrimitives.ReadUInt64LittleEndian(heads.AsSpan((int)bucket*8,8));
            while(node!=sentinel)
            {
                if(node<0x10000||!seen.Add(node)||seen.Count>(long)count)throw new InvalidDataException();
                var bytes=copy.Bytes(node,16);var token=BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(8,2));
                var index=BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(12,4));
                if(token==0||index>=leafCount||GalaxyCommodityHash(token)%capacity!=(ulong)bucket)throw new InvalidDataException();
                var definition=(nuint)BinaryPrimitives.ReadUInt64LittleEndian(rows.AsSpan(checked((int)index*16),8));
                if(!result.TryAdd(token,GalaxyTradeFlowSymbol(copy,copy.Ptr(definition))))throw new InvalidDataException();
                node=(nuint)BinaryPrimitives.ReadUInt64LittleEndian(bytes.AsSpan(0,8));
            }
        }
        if((ulong)result.Count!=count)throw new InvalidDataException();
        return result;
    }

    // Pure bounded copying only. Current ED5A tables/slots are paired with the
    // pinned6891 ctor/parser/expiry functions in current-trade-compatibility.json.
    // The original3AF8980 cutoff is unsigned(clock - lifetime), including its
    // underflow semantics. No setter, acquire, refresh or network method runs.
    static bool CopyGalaxyCurrentTradeFlows(nuint manager,nuint owner,nuint clock,nuint expectedImage,nuint publisher,
        out GalaxyCurrentTradeFlows result,out Func<bool> stable)
    {
        result=new(0,0,0,0,0,0,[],0);stable=()=>false;
        try
        {
            var copy=new GalaxyCommodityCopy();
            if(manager<0x10000||owner<0x10000||clock<0x10000||
               copy.Ptr(manager)!=expectedImage+0x552EA70||copy.Ptr(manager+8)!=expectedImage+0x552EAA0||
               copy.Ptr(manager+0x58)!=expectedImage+0x552EBA0||copy.Ptr(manager+0x10)!=owner||
               copy.Ptr(manager+0x80)!=clock||copy.Ptr(clock)!=expectedImage+0x5134AE0)return false;
            var now=copy.U64(clock+0x1F8);var ttl=copy.U64(manager+0xD0);var refresh=copy.U64(manager+0xD8);var revision=copy.U32(manager+0x100);
            var buckets=copy.Ptr(manager+0xE0);var capacity=copy.U64(manager+0xE8);var count=copy.U64(manager+0xF8);
            if(now==0||ttl==0||capacity is 0 or >65536||count>65536)return false;
            var heads=copy.Bytes(buckets,checked((int)capacity*8));
            // The publisher is optional. Invalid or unready definitions must
            // never assign invented names to otherwise real cached flows.
            Dictionary<ushort,string> names;
            try{names=CopyGalaxyCurrentTradeNames(copy,publisher,expectedImage);}
            catch{names=[];}
            var cutoff=unchecked(now-ttl);var resultRows=new List<GalaxyCurrentTradeFlow>();var seen=new HashSet<nuint>();
            var keys=new HashSet<(ulong,ulong,ushort)>();var unresolved=0;
            for(nuint bucket=0;bucket<(nuint)capacity;bucket++)
            {
                var sentinel=buckets+bucket*8;var node=(nuint)BinaryPrimitives.ReadUInt64LittleEndian(heads.AsSpan((int)bucket*8,8));
                while(node!=sentinel)
                {
                    if(node<0x10000||!seen.Add(node)||seen.Count>(long)count)return false;
                    var bytes=copy.Bytes(node,0x30);var from=BinaryPrimitives.ReadUInt64LittleEndian(bytes.AsSpan(8,8));
                    var to=BinaryPrimitives.ReadUInt64LittleEndian(bytes.AsSpan(0x10,8));var token=BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(0x18,2));
                    var npc=BitConverter.Int32BitsToSingle(BinaryPrimitives.ReadInt32LittleEndian(bytes.AsSpan(0x20,4)));
                    var player=BitConverter.Int32BitsToSingle(BinaryPrimitives.ReadInt32LittleEndian(bytes.AsSpan(0x24,4)));
                    var timestamp=BinaryPrimitives.ReadUInt64LittleEndian(bytes.AsSpan(0x28,8));
                    if(from==0||to==0||from>=0x80000000000000UL||to>=0x80000000000000UL||from==to||token==0||
                       !float.IsFinite(npc)||npc<0||npc>1||!float.IsFinite(player)||!keys.Add((from,to,token)))return false;
                    // ==cutoff is valid. Future timestamps are not accepted by
                    // the original parser and cannot be presented as current.
                    if(timestamp>=cutoff&&timestamp<=now)
                    {
                        names.TryGetValue(token,out var name);if(name is null)unresolved++;
                        resultRows.Add(new(from,to,token,name,npc,player,timestamp));
                    }
                    node=(nuint)BinaryPrimitives.ReadUInt64LittleEndian(bytes.AsSpan(0,8));
                }
            }
            if((ulong)seen.Count!=count||!copy.Stable())return false;
            stable=copy.Stable;result=new(0,0,now,ttl,refresh,revision,resultRows.ToArray(),unresolved);return true;
        }
        catch{return false;}
    }

    static bool TryReadGalaxyCurrentTradeFlows(Snapshot frame,out GalaxyCurrentTradeFlows result)
    {
        result=new(0,0,0,0,0,0,[],0);
        if(!Enabled()||!inGame||!frame.valid||frame.physics==0||owningThread==0||GetCurrentThreadId()!=owningThread||GetTickCount64()-frame.tick>500)return false;
        try
        {
            if(!TryGetGalaxyAccountRegistry(frame,out var registry))return false;
            var cacheType=Read<uint>(image+0x5F856E0);var clockType=Read<uint>(image+0x5F05CA8);var publisherType=Read<uint>(image+0x5F87B20);
            var component=RegisteredComponent(registry,cacheType);var clock=RegisteredComponent(registry,clockType);
            var publisher=RegisteredComponent(registry,publisherType);
            if(component<0x10058)return false;var manager=component-0x58;var owner=Pointer(manager+0x10);
            if(!CopyGalaxyCurrentTradeFlows(manager,owner,clock,image,publisher,out var snapshot,out var stable)||!stable()||
               !TryGetGalaxyAccountRegistry(frame,out var current)||current!=registry||RegisteredComponent(registry,cacheType)!=component||
               RegisteredComponent(registry,clockType)!=clock||RegisteredComponent(registry,publisherType)!=publisher||
               Read<uint>(image+0x5F856E0)!=cacheType||Read<uint>(image+0x5F05CA8)!=clockType||Read<uint>(image+0x5F87B20)!=publisherType||
               Current().entity!=frame.entity||Current().referenceWorld!=frame.referenceWorld)return false;
            result=snapshot with{tick=frame.tick,entity=frame.entity};return true;
        }
        catch{return false;}
    }
}