#if PLUGIN_CRUISE_OBSERVATION using System.IO.Pipes; using System.Text; namespace XFEEDToolBox.Plugin; // Only observes the original SCO update. This module cannot start, stop, // renew or redirect an overcharge, alter a flight axis or select a target. internal static class CruiseObservationRuntime { private const nuint Update=0x2EADB40; private const string Service="CruiseObservation0514c"; private static readonly object sync=new(); private static bool started,enabled; private static nuint image,original; private static uint thread; private static ulong entity,world,watchAt,calls,matches,errors; private static ulong lastSampleTick; private static Navigation.RecoveryCruiseBinding? binding; private static string? issue; private static JsonObject? latest; private static async Task NativeReadAsync(string operation) { using var timeout=new CancellationTokenSource(TimeSpan.FromMilliseconds(150)); using var pipe=new NamedPipeClientStream(".",$"XFEEDToolBox.Navigation.{ProcessId}",PipeDirection.InOut,PipeOptions.Asynchronous); await pipe.ConnectAsync(timeout.Token);await pipe.WriteAsync(Encoding.UTF8.GetBytes(Obj(("op",operation)).ToJsonString()+"\n"),timeout.Token);await pipe.FlushAsync(timeout.Token); var bytes=new byte[65536];var count=0; while(countat<=now&&now-at<=300; private static JsonObject Describe() { lock(sync) { var observed=latest?["observedAtUnixMilliseconds"]?.GetValue()??0;var fresh=observed!=0&&Fresh(observed,Utc()); return Obj(("schema",1),("service",Service),("processId",ProcessId),("gameSha256",GameHash),("enabled",enabled),("owningThread",thread), ("watchEntityId",entity.ToString()),("watchReferenceWorld",world.ToString()),("watchInterface",binding?.component.ToString("x")),("watchAtUnixMilliseconds",watchAt),("calls",calls),("matches",matches),("errors",errors),("issue",issue), ("sampleReady",fresh),("sample",latest?.DeepClone()),("overchargeControl",false),("gameInputsSent",0),("overchargeCommandsSent",0)); } } private static JsonNode Handle(JsonElement request) { var operation=request.Str("op"); if(operation is "describe" or "read")return Describe(); if(operation=="watch") { var frame=NativeReadAsync("read").GetAwaiter().GetResult();var health=NativeReadAsync("health.read").GetAwaiter().GetResult();var now=Utc(); if(!frame.GetProperty("inGame").GetBoolean()||!frame.GetProperty("localPlayerShipVerified").GetBoolean()||!health.GetProperty("localPlayerShipVerified").GetBoolean() ||!Fresh(frame.GetProperty("observedAtUnixMilliseconds").GetUInt64(),now)||!Fresh(health.GetProperty("observedAtUnixMilliseconds").GetUInt64(),now) ||!health.GetProperty("shipHealth").GetProperty("verified").GetBoolean()||frame.GetProperty("entityId").GetString()!=health.GetProperty("entityId").GetString()) throw new InvalidOperationException("Current original main-ship identity is unavailable"); var next=ulong.Parse(frame.GetProperty("entityId").GetString()!);var reference=ulong.Parse(frame.GetProperty("referenceWorldAddress").GetString()!); var nextBinding=Navigation.BindRecoveryCruise(next); lock(sync){if(entity!=next||world!=reference||binding?.component!=nextBinding.component)latest=null;entity=next;world=reference;binding=nextBinding;watchAt=now; issue=nextBinding.component==0?"current-entity-has-no-SCO-interface":"awaiting-current-main-ship-SCO-update";} return Describe(); } if(operation=="deactivate") { lock(sync)enabled=false;HookDisable(image+Update);return Describe(); } throw new InvalidOperationException("This read-only module cannot execute cruise commands"); } [UnmanagedCallersOnly]private static unsafe ulong Observe(nuint sco,float delta,double time) { ulong result;try{result=Call(original,(ulong)sco,F32(delta),F64(time));}catch{return 0;} try { ulong wanted,reference;uint expected;Navigation.RecoveryCruiseBinding? selected; lock(sync){calls++;if(!enabled)return result;wanted=entity;reference=world;expected=thread;selected=binding;} if(wanted==0||selected==null||selected.component!=sco||GetCurrentThreadId()!=expected)return result; var now=GetTickCount64();if(now-lastSampleTick<20)return result;lastSampleTick=now; var observed=Navigation.ObserveRecoveryCruise(selected,sco);if(observed==null)return result; if(observed["referenceWorldAddress"]!.GetValue()!=reference.ToString())return result; lock(sync){if(enabled&&entity==wanted&&world==reference){latest=observed;matches++;issue=null;}} } catch(Exception error){lock(sync){errors++;issue=error.GetType().Name+": "+error.Message;}} return result; } internal static unsafe uint Start(nuint owningThread) { lock(sync) { if(started)return thread==owningThread?1u:0u; if(owningThread is 0 or >uint.MaxValue||ImageHash(ModulePath())!=GameHash)return 0; image=ImageBase;thread=(uint)owningThread;Navigation.ConfigureRecoveryReadOnlyImage(); if(!ReadBytes(image+Update,10).AsSpan().SequenceEqual(new byte[]{0x48,0x89,0x5C,0x24,0x18,0x57,0x48,0x83,0xEC,0x40}))return 0; var status=HookInitialize();if(status is not(0 or 1))return 0; if(HookCreate(image+Update,(nuint)(delegate* unmanaged)&Observe,out original)!=0)return 0; if(!Pin((nuint)(delegate* unmanaged)&Observe)||HookEnable(image+Update)!=0)return 0; started=enabled=true;PipeServer.StartJson(Service,32768,Handle);return 1; } } internal static uint SelfTest() { if(started||ImageHash(ModulePath())==GameHash)return 0;uint result=0; if(Fresh(100,400)&&!Fresh(100,401)&&!Fresh(100,99))result|=1; var value=Describe();if(!value["overchargeControl"]!.GetValue()&&value["gameInputsSent"]!.GetValue()==0)result|=2; if(!value["sampleReady"]!.GetValue())result|=4; foreach(var op in new[]{"activate","cruise.overcharge.set","input.set","local.select"}) {using var request=JsonDocument.Parse(Obj(("op",op)).ToJsonString());try{Handle(request.RootElement);return result;}catch(InvalidOperationException){}} result|=8; if(XFEEDToolBox.Core.Navigation.OriginalCurveBounds.TryBound([new(0,0,1,-12),new(1,0,0,-12)],2,0,1,out var bounds)&&bounds.Maximum>=1.5&&bounds.Maximum<1.501)result|=16; if(!XFEEDToolBox.Core.Navigation.OriginalCurveBounds.TryBound([],2,0,1,out _))result|=32; if(!XFEEDToolBox.Core.Navigation.OriginalCurveBounds.TryBound([new(0,double.NaN,1,0)],2,0,1,out _))result|=64; if(value["overchargeCommandsSent"]!.GetValue()==0&&value["service"]!.GetValue()==Service)result|=128; return result; } } internal static class CruiseObservationExports { [UnmanagedCallersOnly(EntryPoint="XFEInteractionStart")]internal static uint Start(nuint thread){try{return CruiseObservationRuntime.Start(thread);}catch{return 0;}} [UnmanagedCallersOnly(EntryPoint="XFECruiseObservationSelfTest")]internal static uint SelfTest(){try{return CruiseObservationRuntime.SelfTest();}catch{return 0;}} } #endif