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

XFEEDToolBox

【WinUI】XFE精英危险工具箱

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using static XFEEDToolBox.Plugin.JsonWire;

namespace XFEEDToolBox.Plugin;

internal static unsafe partial class Navigation
{
    internal struct GalaxyServices {public nuint galaxy,names,registry;public int[] origin;}
    internal struct GalaxyItem {public ulong id;public double[] position;public uint starClass;public string name;public GalaxyAppearance? appearance;}
    sealed class GalaxyWork
    {
        internal ulong generation,expires,address;
        internal string query="",error="";
        internal bool suggest,started,done,region,cancelRequested,cancelled,cellMode;
        internal nuint[] search=new nuint[2];
        internal List<GalaxyItem> items=[];
        internal double[] centre=new double[3];
        internal double radius;
        internal uint minimumMass,entry;
        internal List<ulong> cells=[];
        internal int cellIndex,failedCells,failedRows;
        internal ulong cellStartedAt;
        internal nuint cellObject;
        internal double[] massRadii=[];
        internal double[]? origin;
    }
    const int GalaxyBatchRowLimit=24000,GalaxySingleCellRowLimit=131072;
    // A source cell is the indivisible unit. Splitting a capped batch cannot
    // refine a single cell, so that case must retain its full validated array.
    static int GalaxyRowLimit(GalaxyWork work)=>work.cellMode&&work.cells.Count==1?GalaxySingleCellRowLimit:GalaxyBatchRowLimit;
    static readonly object galaxyMutex=new();
    static GalaxyWork galaxyWork=new();
    static ulong galaxyGenerationValue;
    static ulong galaxyGeneration {get=>Volatile.Read(ref galaxyGenerationValue);set=>Volatile.Write(ref galaxyGenerationValue,value);}
    static bool GalaxyCString(nuint address,int capacity,out string value)
    {
        value="";if(address==0)return false;
        var bytes=new byte[capacity];
        for(var i=0;i<capacity;i++)
        {
            var c=Read<byte>(address+(nuint)i);
            if(c==0){value=new UTF8Encoding(false,true).GetString(bytes,0,i);return true;}
            bytes[i]=c;
        }
        return false;
    }
    static bool GalaxyName(GalaxyServices services,nuint compact,nuint fallback,out string output)
    {
        output="";nuint generated=0;
        try
        {
            var name=Pointer(compact+8);
            if(name==0&&fallback!=0&&Read<byte>(fallback)!=0)name=fallback;
            if(name==0)
            {
                Call(image+0x3CF1430,services.names,(nuint)(&generated),Read<ulong>(compact),Read<ushort>(compact+0x42),Read<ushort>(compact+0x44),Read<ushort>(compact+0x46),1);
                if(generated!=0)name=generated+20;
            }
            var valid=GalaxyCString(name,160,out output);
            return valid&&output.Length!=0;
        }
        catch{return false;}
        finally
        {
            if(generated!=0)try
            {if(Platform.AtomicDecrement(generated+16)==0)Call(image+0x549D90,generated,Read<ulong>(generated+8)+21);}
            catch{}
        }
    }
    static bool CopyGalaxyCompact(GalaxyServices services,nuint compact,nuint fallback,out GalaxyItem item)
    {
        item=default;
        try
        {
            var id=Read<ulong>(compact);if(id==0||id>=0x80000000000000UL)return false;
            var m=(int)(id&7);
            var x=(((id>>(30-2*m))<<m)&0x3FFF)*320+Read<ushort>(compact+0x42);
            var y=(((id>>(17-m))<<m)&0x1FFF)*320+Read<ushort>(compact+0x44);
            var z=(((id>>3)<<m)&0x3FFF)*320+Read<ushort>(compact+0x46);
            item.id=id;item.position=[((double)x-services.origin[0])/32,((double)y-services.origin[1])/32,((double)z-services.origin[2])/32];
            item.starClass=(uint)(Read<byte>(compact+0x40)&63);
            var named=GalaxyName(services,compact,fallback,out item.name);
            if(named&&TryCopyGalaxyAppearance(services,compact,out var appearance))item.appearance=appearance;
            if(named)RememberNativeGalaxyItem(item);return named;
        }
        catch{return false;}
    }
    static bool FindGalaxyServices(Snapshot frame,out GalaxyServices result)
    {
        result=default;
        try
        {
            var route=GameRoute(frame,out _);if(route==0)return false;
            var source=Leaf(route-0x58+8,image+0x541C70);if(source==0||Pointer(Pointer(source)+0x20)!=image+0x8C51E0)return false;
            source=Leaf(source,image+0x8C51E0);if(source==0||Pointer(Pointer(source))!=image+0x5299D0)return false;
            var count=Read<ulong>(source+0x28);var buckets=Pointer(source+0x20);
            if(buckets==0||count<1||count>1024||Read<uint>(image+0x5F05AB8)!=1)return false;
            nuint context=0;
            for(ulong i=0;i<count;i++)
            {
                var sentinel=buckets+(nuint)(i*8);var node=Pointer(sentinel);
                for(uint guard=0;node!=0&&node!=sentinel&&guard<1024;guard++,node=Pointer(node))
                    if(Read<uint>(node+8)==1){if(context!=0)return false;context=Pointer(node+16);break;}
            }
            if(context==0||Pointer(Pointer(context)+0x18)!=image+0x1F3150)return false;
            var life=Pointer(context+0x568);if(life==0||Read<uint>(life+0xC0)!=8)return false;
            var components=Pointer(life+0xC8);if(components==0)return false;
            var galaxy=RegisteredComponent(components-0x30,Read<uint>(image+0x5F05C1C));
            var names=RegisteredComponent(components-0x30,Read<uint>(image+0x5F05C20));
            if(galaxy==0||names==0||Pointer(galaxy)!=image+0x5539C28||Pointer(names)!=image+0x553FC38||Pointer(Pointer(galaxy)+0x20)!=image+0x3C33140||
               Pointer(Pointer(names)+0x28)!=image+0x3CEE000||Pointer(Pointer(names)+0x38)!=image+0x3CEB720)return false;
            var origin=Pointer(galaxy+0x188);if(origin==0)return false;
            result=new(){galaxy=galaxy,names=names,registry=components-0x30,origin=new int[3]};
            for(var i=0;i<3;i++){var value=Read<int>(origin+(nuint)(i*4));if(value< -32000000||value>32000000)return false;result.origin[i]=value;}
            return true;
        }
        catch{return false;}
    }
    static bool TryGetGalaxyAccountRegistry(Snapshot frame,out nuint registry)
    {
        registry=0;
        if(!FindGalaxyServices(frame,out var services))return false;
        registry=services.registry;return registry!=0;
    }
    static void DropGalaxyObject(nuint obj)
    {if(obj!=0&&Platform.AtomicDecrement(obj)==0)Call(image+0x3C448E0,obj);}
    static bool CopyGalaxyItem(GalaxyServices services,ulong id,nuint fallback,out GalaxyItem item)
    {
        item=default;nuint obj=0;
        try
        {
            if(id==0||id>=0x80000000000000UL)return false;
            Call(image+0x3C33140,services.galaxy,(nuint)(&obj),id);if(obj==0)return false;
            if(Read<uint>(obj+0x20)==1)Call(image+0x3C35900,obj);
            if(Read<uint>(obj+0x20)!=2)return false;
            var compact=Pointer(obj+0x38);if(compact==0||Read<ulong>(compact)!=id)return false;
            return CopyGalaxyCompact(services,compact,fallback,out item);
        }
        catch{return false;}
        finally{if(obj!=0)try{DropGalaxyObject(obj);}catch{}}
    }
    static bool LookupGalaxy(GalaxyServices services,string name,out GalaxyItem item)
    {
        item=default;
        try
        {
            ulong id=0;var text=Encoding.UTF8.GetBytes(name+"\0");
            fixed(byte* pointer=text)
            {Call(image+0x3CEE000,services.names,(nuint)(&id),(nuint)pointer,0,1,0);return CopyGalaxyItem(services,id,(nuint)pointer,out item);}
        }
        catch{return false;}
    }
    static bool BeginGalaxySuggestions(GalaxyServices services,string query,ulong current,nuint[] search)
    {
        try
        {
            var text=Encoding.UTF8.GetBytes(query+"\0");var length=text.Length-1;if(length<2||length>128)return false;
            var str=(nuint)Call(image+0x541380,(ulong)length+21);if(str==0)return false;
            Write(str,(ulong)length);Write(str+8,(ulong)length);Write(str+16,1);Platform.WriteBytes(str+20,text);
            nuint* result=stackalloc nuint[2];result[0]=result[1]=0;
            Call(image+0x3CEB720,services.names,(nuint)result,(nuint)(&str),20,current,0x4E);
            search[0]=result[0];search[1]=result[1];return search[0]!=0&&search[1]!=0;
        }
        catch{return false;}
    }
    static void DropGalaxySuggestions(nuint[] search)
    {
        try
        {
            var block=search[0];search[0]=search[1]=0;if(block==0)return;
            if(Platform.AtomicDecrement(block+12)==0)Call(Pointer(Pointer(block)+0x10),block);
            if(Platform.AtomicDecrement(block+8)==0)Call(Pointer(Pointer(block)+0x18),block);
        }
        catch{}
    }
    static List<GalaxyItem> CopyGalaxySuggestions(GalaxyServices services,nuint[] search,out bool done)
    {
        done=false;List<GalaxyItem> items=[];
        try
        {
            var payload=search[1];if(payload==0||search[0]==0)return items;
            var limit=Read<uint>(payload+8);if(limit>20)return items;
            var rows=Pointer(payload);if(rows==0)return items;done=Read<byte>(payload+16)!=0;
            for(uint i=0;i<limit;i++)
            {
                var row=rows+i*24;if(Read<byte>(row+16)==0)continue;
                var text=Pointer(row);var id=Read<ulong>(row+8);
                if(CopyGalaxyItem(services,id,text!=0?text+20:0,out var item))items.Add(item);
            }
        }
        catch{items.Clear();}
        return items;
    }
    static void BuildGalaxyRegionCells(GalaxyWork work,GalaxyServices services)
    {
        for(var minimum=0;minimum<8;minimum++)
        {
            List<ulong> cells=[];
            for(var m=minimum;m<8;m++)
            {
                var size=(double)(10u<<m);var low=new int[3];var high=new int[3];
                for(var axis=0;axis<3;axis++)
                {
                    var maxCell=(1<<(axis==1?13-m:14-m))-1;
                    low[axis]=Math.Clamp((int)Math.Floor((work.centre[axis]+services.origin[axis]/32.0-work.radius)/size),0,maxCell);
                    high[axis]=Math.Clamp((int)Math.Floor((work.centre[axis]+services.origin[axis]/32.0+work.radius)/size),0,maxCell);
                }
                for(var x=low[0];x<=high[0]&&cells.Count<=512;x++)for(var y=low[1];y<=high[1]&&cells.Count<=512;y++)for(var z=low[2];z<=high[2]&&cells.Count<=512;z++)
                    cells.Add(((ulong)x<<(30-2*m))|((ulong)y<<(17-m))|((ulong)z<<3)|(uint)m);
            }
            if(cells.Count<=512){work.minimumMass=(uint)minimum;work.cells=cells;return;}
        }
        throw new InvalidOperationException("Galaxy detail viewport exceeds the bounded sector budget");
    }
    static bool StartGalaxyRegionCell(GalaxyServices services,ulong id,out nuint obj)
    {
        nuint result=0;obj=0;
        try
        {
            Call(image+0x3C33140,services.galaxy,(nuint)(&result),id);obj=result;if(result==0)return false;
            // Lookup returns an owned handle, which may still need the same
            // generation/load step used by the original single-system lookup.
            // A pending cell must not be skipped and cached as an empty region.
            if(Read<uint>(result+0x20)==1)Call(image+0x3C35900,result);
            return true;
        }
        catch{obj=result;return false;}
    }
    static bool CopyGalaxyRegionRows(GalaxyServices services,GalaxyWork work,List<GalaxyItem> output,out bool finished)
    {
        finished=false;
        try
        {
            var cell=Pointer(work.cellObject+0x30);var rows=Pointer(cell+0x30);var count=Read<ulong>(cell+0x38);
            if(count>GalaxySingleCellRowLimit||(rows==0&&count!=0))return false;
            var stop=Math.Min((ulong)work.entry+256,count);
            var firstEntry=work.entry;var began=GetTickCount64();var maximum=work.cellMode?256:64;
            for(;work.entry<stop&&output.Count<maximum;work.entry++)
            {
                // Host scheduling policy: progress faster than64 rows per game
                // tick, while yielding after2ms between individual records.
                if(work.cellMode&&work.entry>firstEntry&&GetTickCount64()-began>=2)break;
                var compact=Pointer(rows+work.entry*8);if(compact==0)return false;
                var id=Read<ulong>(compact);var m=(int)(id&7);
                var x=((double)((((id>>(30-2*m))<<m)&0x3FFF)*320+Read<ushort>(compact+0x42))-services.origin[0])/32;
                var y=((double)((((id>>(17-m))<<m)&0x1FFF)*320+Read<ushort>(compact+0x44))-services.origin[1])/32;
                var z=((double)((((id>>3)<<m)&0x3FFF)*320+Read<ushort>(compact+0x46))-services.origin[2])/32;
                var dx=x-work.centre[0];var dy=y-work.centre[1];var dz=z-work.centre[2];
                if(GalaxyRegionIncludesRow(work,id,dx,dy,dz))
                {if(CopyGalaxyCompact(services,compact,0,out var item))output.Add(item);else work.failedRows++;}
            }
            finished=work.entry>=count;return true;
        }
        catch{return false;}
    }
    static bool GalaxyRegionOriginMatches(GalaxyServices services,GalaxyWork work)
        =>services.origin is{Length:3}&&work.origin is{Length:3}&&
          work.origin[0]==services.origin[0]/32d&&work.origin[1]==services.origin[1]/32d&&work.origin[2]==services.origin[2]/32d;

    static void StepGalaxyRegion(GalaxyServices services,GalaxyWork work)
    {
        // A single source cell may now span many owning-thread polls. Never
        // reinterpret its remaining rows against a different galaxy origin.
        // Already published rows retain their original identity; this query
        // fails explicitly and cannot subsequently claim complete coverage.
        if(work.started&&!GalaxyRegionOriginMatches(services,work))
        {
            if(work.cellObject!=0){DropGalaxyObject(work.cellObject);work.cellObject=0;}
            work.error="游戏银河坐标原点在读取时变化";work.done=true;return;
        }
        if(!work.started)
        {
            work.started=true;
            work.origin=services.origin.Select(value=>value/32d).ToArray();
            if(work.cellMode)
            {
                if(!ValidateGalaxyRequestedCells(work,services))
                {work.error="请求星区与原质量层范围不相交";work.done=true;return;}
            }
            else BuildGalaxyRegionCells(work,services);
        }
        var rowLimit=GalaxyRowLimit(work);
        if(work.cellIndex>=work.cells.Count||work.items.Count>=rowLimit){work.done=true;return;}
        if(work.cellObject==0&&!StartGalaxyRegionCell(services,work.cells[work.cellIndex],out work.cellObject))
        {if(work.cellObject!=0)DropGalaxyObject(work.cellObject);work.cellObject=0;work.failedCells++;++work.cellIndex;return;}
        if(work.cellStartedAt==0)work.cellStartedAt=GetTickCount64();
        // The original reader advances asynchronous metadata generation on each
        // owning-thread update (3C359A0 -> 3C35750); polling D0 alone never does.
        Call(image+0x3C35900,work.cellObject);
        var cell=Pointer(work.cellObject+0x30);
        if(cell==0||Read<uint>(cell+0xD0)!=4)
        {
            if(GetTickCount64()-work.cellStartedAt<2000)return;
            DropGalaxyObject(work.cellObject);work.cellObject=0;work.cellStartedAt=0;work.failedCells++;work.entry=0;work.cellIndex++;return;
        }
        List<GalaxyItem> rows=[];
        if(!CopyGalaxyRegionRows(services,work,rows,out var finished)){work.failedCells++;work.error="游戏星区数据在读取时变化";work.done=true;finished=true;}
        foreach(var row in rows){if(work.items.Count>=rowLimit)break;work.items.Add(row);}
        if(finished){DropGalaxyObject(work.cellObject);work.cellObject=0;work.cellStartedAt=0;work.entry=0;++work.cellIndex;}
        if(work.cellIndex>=work.cells.Count||work.items.Count>=rowLimit)
        {if(work.cellObject!=0){DropGalaxyObject(work.cellObject);work.cellObject=0;}work.done=true;}
    }
    static void PollGalaxyCatalogue(Snapshot frame)
    {
        PollGalaxyCatalogueProfile(frame);
        if(!Enabled()||!inGame||!frame.valid||fsdOwned||Read<byte>(frame.fsd+0x758)!=2)return;
        ulong expires;lock(leaseLock)expires=Math.Max(lease.expires,fsdLease.expires);if(expires>GetTickCount64())return;
        if(!Monitor.TryEnter(galaxyMutex))return;
        try
        {
            var work=galaxyWork;if(work.generation==0||work.done)return;
            if(work.cancelRequested)
            {
                DropGalaxySuggestions(work.search);if(work.cellObject!=0){DropGalaxyObject(work.cellObject);work.cellObject=0;}
                work.cancelled=true;work.done=true;return;
            }
            if(GetTickCount64()>work.expires)
            {DropGalaxySuggestions(work.search);if(work.cellObject!=0){DropGalaxyObject(work.cellObject);work.cellObject=0;}work.error="游戏星系查询超时";work.done=true;return;}
            if(!FindGalaxyServices(frame,out var services))return;
            if(work.region){StepGalaxyRegion(services,work);return;}
            if(!work.started)
            {
                work.started=true;
                if(!work.suggest)
                {
                    GalaxyItem item;var found=work.address!=0?CopyGalaxyItem(services,work.address,0,out item):LookupGalaxy(services,work.query,out item);
                    if(found)work.items.Add(item);work.done=true;return;
                }
                var current=Read<ulong>(frame.transform+0xE8)&0x7FFFFFFFFFFFFFUL;
                if(!BeginGalaxySuggestions(services,work.query,current,work.search)){work.error="游戏星系补全尚不可用";work.done=true;return;}
            }
            work.items=CopyGalaxySuggestions(services,work.search,out var done);
            if(done){DropGalaxySuggestions(work.search);work.done=true;}
        }
        finally{Monitor.Exit(galaxyMutex);}
    }
    static readonly string[] galaxyStarClasses=["O","B","A","F","G","K","M","L","T","TTS","AeBe","Y","W","WN","WNC","WC","WO","CS","C","CN","CJ","CH","CHd","MS","S","D","DA","DAB","DAO","DAZ","DAV","DB","DBZ","DBV","DO","DOV","DQ","DC","DCV","DX","N","H","SupermassiveBlackHole","X","Nebula","RemnantNebula","BigText","NoSystem"];
    static string GalaxyStarClass(uint value)=>value<galaxyStarClasses.Length?galaxyStarClasses[value]:"Unknown";
    static JsonObject GalaxyCatalogueRequest(string op,JsonElement request)
    {
        lock(galaxyMutex)
        {
            var work=galaxyWork;
            if(op is "galaxy.lookup" or "galaxy.suggest" or "galaxy.region" or "galaxy.resolve" or "galaxy.cells")
            {
                var cellMode=op=="galaxy.cells";var region=op=="galaxy.region"||cellMode;var resolve=op=="galaxy.resolve";
                ulong address=0;
                if(resolve)
                {
                    var field=request.Required("systemAddress");
                    var valid=field.ValueKind==JsonValueKind.String
                        ?ulong.TryParse(field.GetString(),System.Globalization.NumberStyles.None,System.Globalization.CultureInfo.InvariantCulture,out address)
                        :field.ValueKind==JsonValueKind.Number&&field.TryGetUInt64(out address);
                    if(!valid)throw new InvalidDataException("Invalid galaxy system address");
                }
                if(resolve&&(address==0||address>=0x80000000000000UL))throw new InvalidDataException("Invalid galaxy system address");
                var query=region||resolve?"":request.Required("query").GetString()??throw new InvalidDataException("Invalid galaxy name query");
                if(!region&&!resolve&&(query.Length==0||Encoding.UTF8.GetByteCount(query)>128||query.Contains('\0')))throw new InvalidOperationException("Invalid galaxy name query");
                var centre=new double[3];double radius=0;
                if(region)
                {
                    var position=request.Required("centre");if(position.ValueKind!=JsonValueKind.Array||position.GetArrayLength()!=3)throw new InvalidDataException("Invalid galaxy detail position");
                    for(var i=0;i<3;i++)centre[i]=position[i].GetDouble();
                    if(!cellMode)
                    {
                        radius=request.Required("radius").GetDouble();
                        if(!double.IsFinite(radius)||radius<.05||radius>700)throw new InvalidOperationException("Invalid galaxy detail radius");
                    }
                    if(centre.Any(value=>!double.IsFinite(value)||Math.Abs(value)>200000))throw new InvalidOperationException("Invalid galaxy detail position");
                }
                if(work.generation!=0&&!work.done)throw new InvalidOperationException("A galaxy catalogue query is already pending");
                DropGalaxySuggestions(work.search);
                var next=new GalaxyWork{expires=GetTickCount64()+(region?30000UL:10000UL),query=query,suggest=op=="galaxy.suggest",region=region,centre=centre,radius=radius,address=address,cellMode=cellMode};
                if(cellMode)ParseGalaxyRequestedCells(next,request);
                if(cellMode&&next.cells.Count==1)next.expires=GetTickCount64()+90000;
                next.generation=++galaxyGeneration;galaxyWork=work=next;
            }
            else if(op=="galaxy.cancel")
            {
                if(request.U64("generation")!=work.generation)throw new InvalidOperationException("No matching galaxy query");
                work.cancelRequested=true;
                // Handles created by the game are released only by its verified
                // owning-thread poll. Unstarted/handle-free work retires now.
                if(work.cellObject==0&&work.search[0]==0){work.cancelled=true;work.done=true;}
            }
            else if(op!="galaxy.result"||request.U64("generation")!=work.generation)throw new InvalidOperationException("No matching galaxy query");
            var items=new JsonArray();var offset=request.U64("offset");var limit=Math.Min(request.U64("limit",20),96UL);
            var wireBytes=0;
            for(var i=offset;i<(ulong)work.items.Count&&i-offset<limit;i++)
            {
                var item=work.items[(int)i];JsonObject? original=null;
                if(item.appearance is {} a)original=Obj(("typeRgba",a.typeRgba),("realisticRgba",a.realisticRgba),("colourBlend",a.colourBlend),
                    ("rawScale",a.rawScale),("classification",a.classification),("size",a.size),("smallSize",a.smallSize),("smallSizeActive",a.smallSizeActive),
                    ("navRouteMembership",a.navRouteMembership),("navRouteMembershipMode",a.navRouteMembershipMode),("navRouteViewMode",a.navRouteViewMode));
                var row=Obj(("name",item.name),("systemAddress",item.id.ToString(System.Globalization.CultureInfo.InvariantCulture)),
                    ("position",Arr(item.position[0],item.position[1],item.position[2])),("starClass",GalaxyStarClass(item.starClass)),("originalAppearance",original));
                var bytes=Encoding.UTF8.GetByteCount(row.ToJsonString());if(i>offset&&wireBytes+bytes>48000)break;
                wireBytes+=bytes;items.Add((JsonNode)row);
            }
            var rowLimit=GalaxyRowLimit(work);
            var truncated=work.region&&(work.items.Count>rowLimit||work.items.Count==rowLimit&&!(work.cellMode&&work.cells.Count==1&&work.cellIndex==1)||work.cellIndex<work.cells.Count&&work.done);
            var complete=work.region&&work.done&&!work.cancelled&&!truncated&&work.error.Length==0&&(work.cellMode||work.minimumMass==0)&&work.failedCells==0&&work.failedRows==0&&work.cellIndex==work.cells.Count&&work.cells.Count>0;
            return Obj(("generation",work.generation),("done",work.done),("cancelled",work.cancelled),("error",work.error),("items",items),("total",work.items.Count),
                ("processedCells",work.cellIndex),("totalCells",work.cells.Count),("minimumMassCode",work.minimumMass),("failedCells",work.failedCells+work.failedRows),("failedRows",work.failedRows),
                ("truncated",truncated),("complete",complete),("source","Stellar Forge"),
                ("scope",work.cellMode?"requested-cells":work.region?"region-sphere":""),("requestedCells",work.cellMode?work.cells.Count:-1),
                ("rowLimit",rowLimit),
                ("origin",work.origin is{} origin?Arr(origin[0],origin[1],origin[2]):null));
        }
    }
    static bool DensityLayout(GalaxyServices services,out nuint grid,out uint width,out uint height,out double extentX,out double extentZ)
    {
        grid=0;width=height=0;extentX=extentZ=0;
        try
        {
            var data=Pointer(services.galaxy+0x100);if(data==0)return false;grid=Pointer(data+0x38);if(grid==0)return false;
            width=Read<uint>(grid);height=Read<uint>(grid+4);var x=Read<uint>(data+4);var z=Read<uint>(data+0x10);
            if(x==0||z==0||width<16||height<16||width>8192||height>8192||(ulong)width*height>16777216)return false;
            extentX=width*2147483648.0*10/x;extentZ=height*2147483648.0*10/z;
            return extentX>=1000&&extentX<=1000000&&extentZ>=1000&&extentZ<=1000000;
        }
        catch{return false;}
    }
    static bool CopyDensityCells(nuint grid,uint width,uint height,uint[] pixels)
    {
        try
        {
            var rows=Pointer(grid+0x10);if(rows==0)return false;
            for(uint y=0;y<height;y++)
            {
                var row=Pointer(rows+y*8);if(row==0)return false;uint x=0,blocks=0;
                while(x<width&&blocks++<=width)
                {
                    var header=Read<uint>(row);row+=4;var length=header&0x7FFFFFFF;if(length==0||length>width-x)return false;
                    if((header&0x80000000)!=0){var value=Read<uint>(row);row+=4;pixels.AsSpan((int)(y*width+x),(int)length).Fill(value);x+=length;}
                    else
                    {
                        MemoryMarshal.Cast<byte,uint>(Platform.ReadBytes(row,(int)length*4)).CopyTo(pixels.AsSpan((int)(y*width+x),(int)length));
                        x+=length;row+=length*4;
                    }
                }
                if(x!=width)return false;
            }
            return true;
        }
        catch{return false;}
    }
    [DllImport("kernel32.dll",CharSet=CharSet.Unicode,SetLastError=true)]
    [return:MarshalAs(UnmanagedType.Bool)]
    static extern bool MoveFileExW(string source,string destination,uint flags);
    static JsonObject ExportGalaxyOverview(Snapshot frame)
    {
        ulong expiry;lock(leaseLock)expiry=Math.Max(lease.expires,fsdLease.expires);
        if(fsdOwned||expiry>GetTickCount64())throw new InvalidOperationException("Stop automatic flight before reading the complete galaxy display map");
        if(!FindGalaxyServices(frame,out var services)||!DensityLayout(services,out var grid,out var width,out var height,out var x,out var z))throw new InvalidOperationException("Original galaxy density resource unavailable");
        var cells=new uint[checked((int)(width*height))];if(!CopyDensityCells(grid,width,height,cells))throw new InvalidOperationException("Original galaxy density rows were not complete");
        var local=Environment.GetEnvironmentVariable("LOCALAPPDATA");if(string.IsNullOrEmpty(local)||local.Length>=32768)throw new InvalidOperationException("Local galaxy display cache unavailable");
        var folder=Path.Combine(local,"XFEstudio","XFEEDToolBox","galaxy");Directory.CreateDirectory(folder);var path=Path.Combine(folder,"galaxy-density.bin");var temporary=path+".partial";
        var maximum=cells.Max();if(maximum==0)throw new InvalidOperationException("Original galaxy density raster was empty");
        double[] coordinates=[services.origin[0]/32.0,services.origin[2]/32.0,x,z];
        using(var stream=new FileStream(temporary,FileMode.Create,FileAccess.Write,FileShare.None))
        using(var output=new BinaryWriter(stream,Encoding.UTF8,leaveOpen:false))
        {
            output.Write("XFEGDM2\0"u8);output.Write(width);output.Write(height);foreach(var coordinate in coordinates)output.Write(coordinate);
            foreach(var cell in cells)output.Write((float)((double)cell/maximum));output.Flush();stream.Flush(true);
        }
        if(!MoveFileExW(temporary,path,9))throw new InvalidOperationException("Galaxy display cache could not be committed");
        return Obj(("width",width),("height",height),("origin",Arr(coordinates[0],coordinates[1],coordinates[2],coordinates[3])),
            ("source","Original Stellar Forge galaxy density resource"),("file","galaxy-density.bin"),("gameSha256",GameHash));
    }
}