using System.Diagnostics;
using System.Numerics;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Runtime.CompilerServices;
using Microsoft.UI.Composition;
using Microsoft.UI.Xaml.Hosting;
using Microsoft.UI.Xaml.Input;
using Microsoft.UI.Xaml.Media;
using Windows.Foundation;
using XFEEDToolBox.Core.Galaxy;
using XFEEDToolBox.Core.Models;
using XFEEDToolBox.Core.Navigation;
using XFEEDToolBox.Rendering;
namespace XFEEDToolBox.Controls;
/// <summary>Retained GPU vector map of measured Galactic XYZ coordinates. Pointer input is coalesced per composition frame.</summary>
public sealed partial class GalaxyMapView : UserControl
{
public static readonly DependencyProperty SystemsProperty = DependencyProperty.Register(nameof(Systems), typeof(IReadOnlyList<GalacticSystem>), typeof(GalaxyMapView), new PropertyMetadata(null, Changed));
public static readonly DependencyProperty RouteProperty = DependencyProperty.Register(nameof(Route), typeof(IReadOnlyList<NavWaypoint>), typeof(GalaxyMapView), new PropertyMetadata(null, Changed));
public static readonly DependencyProperty CentreProperty = DependencyProperty.Register(nameof(Centre), typeof(Coordinates), typeof(GalaxyMapView), new PropertyMetadata(null, CentreChanged));
public static readonly DependencyProperty CurrentSystemProperty = DependencyProperty.Register(nameof(CurrentSystem), typeof(string), typeof(GalaxyMapView), new PropertyMetadata("", Changed));
public static readonly DependencyProperty SelectionProperty = DependencyProperty.Register(nameof(Selection), typeof(GalacticSystem), typeof(GalaxyMapView), new PropertyMetadata(null, SelectionChanged));
public static readonly DependencyProperty FilterProperty = DependencyProperty.Register(nameof(Filter), typeof(GalaxyMapFilter), typeof(GalaxyMapView), new PropertyMetadata(null, Changed));
public GalaxyMapFilter? Filter { get => (GalaxyMapFilter?)GetValue(FilterProperty); set => SetValue(FilterProperty, value); }
public static readonly DependencyProperty CatalogueSelectionProperty=DependencyProperty.Register(nameof(CatalogueSelection),typeof(GalaxyCatalogueSelection),typeof(GalaxyMapView),new PropertyMetadata(null,Changed));
public GalaxyCatalogueSelection? CatalogueSelection {get=>(GalaxyCatalogueSelection?)GetValue(CatalogueSelectionProperty);set=>SetValue(CatalogueSelectionProperty,value);}
public static readonly DependencyProperty PointsOfInterestProperty=DependencyProperty.Register(nameof(PointsOfInterest),typeof(IReadOnlyList<GalacticPlace>),typeof(GalaxyMapView),new PropertyMetadata(null,Changed));
public static readonly DependencyProperty PlanningProperty=DependencyProperty.Register(nameof(Planning),typeof(bool),typeof(GalaxyMapView),new PropertyMetadata(false,PlanningChanged));
public static readonly DependencyProperty CanPlanRouteProperty=DependencyProperty.Register(nameof(CanPlanRoute),typeof(bool),typeof(GalaxyMapView),new PropertyMetadata(true));
public IReadOnlyList<GalacticPlace>? PointsOfInterest {get=>(IReadOnlyList<GalacticPlace>?)GetValue(PointsOfInterestProperty);set=>SetValue(PointsOfInterestProperty,value);}
public bool Planning {get=>(bool)GetValue(PlanningProperty);set=>SetValue(PlanningProperty,value);}
public bool CanPlanRoute {get=>(bool)GetValue(CanPlanRouteProperty);set=>SetValue(CanPlanRouteProperty,value);}
public static readonly DependencyProperty PlottedDestinationProperty=DependencyProperty.Register(nameof(PlottedDestination),typeof(long),typeof(GalaxyMapView),new PropertyMetadata(0L,Changed));
public static readonly DependencyProperty CanCancelRouteProperty=DependencyProperty.Register(nameof(CanCancelRoute),typeof(bool),typeof(GalaxyMapView),new PropertyMetadata(false,Changed));
public long PlottedDestination{get=>(long)GetValue(PlottedDestinationProperty);set=>SetValue(PlottedDestinationProperty,value);}
public bool CanCancelRoute{get=>(bool)GetValue(CanCancelRouteProperty);set=>SetValue(CanCancelRouteProperty,value);}
internal bool HoldingCancelsRoute(GalacticSystem target)=>CanCancelRoute&&PlottedDestination>0&&target.SystemAddress==PlottedDestination;
public static readonly DependencyProperty FuelOverlayProperty = DependencyProperty.Register(nameof(FuelOverlay),typeof(NavigationFuelOverlay),typeof(GalaxyMapView),new PropertyMetadata(null,Changed));
public NavigationFuelOverlay? FuelOverlay { get=>(NavigationFuelOverlay?)GetValue(FuelOverlayProperty);set=>SetValue(FuelOverlayProperty,value); }
public IReadOnlyList<GalacticSystem>? Systems { get => (IReadOnlyList<GalacticSystem>?)GetValue(SystemsProperty); set => SetValue(SystemsProperty, value); }
public IReadOnlyList<NavWaypoint>? Route { get => (IReadOnlyList<NavWaypoint>?)GetValue(RouteProperty); set => SetValue(RouteProperty, value); }
public Coordinates? Centre { get => (Coordinates?)GetValue(CentreProperty); set => SetValue(CentreProperty, value); }
public string CurrentSystem { get => (string)GetValue(CurrentSystemProperty); set => SetValue(CurrentSystemProperty, value); }
public GalacticSystem? Selection { get => (GalacticSystem?)GetValue(SelectionProperty); set => SetValue(SelectionProperty, value); }
public bool IsInteractive { get; set; } = true;
public static readonly DependencyProperty ReverseMouseCraneProperty=DependencyProperty.Register(nameof(ReverseMouseCrane),typeof(bool),typeof(GalaxyMapView),new PropertyMetadata(false));
public bool ReverseMouseCrane {get=>(bool)GetValue(ReverseMouseCraneProperty);set=>SetValue(ReverseMouseCraneProperty,value);}
public event EventHandler<GalacticSystem>? SystemSelected;
public event EventHandler<GalacticSystem>? TargetChosen;
public event Action<GalaxyViewport>? ViewportSettled;
public event Action? SelectionCleared;
private readonly StarHoldGesture holdGesture=new();
private readonly Microsoft.UI.Dispatching.DispatcherQueueTimer holdTimer;
private readonly Microsoft.UI.Dispatching.DispatcherQueueTimer viewportTimer;
private readonly GalaxyViewportThrottle viewportThrottle=new();
private GalacticSystem? holdCandidate;
private GalacticSystem? planningCandidate;
private readonly ProgressRing holdProgress=new(){Width=48,Height=48,Minimum=0,Maximum=100,Foreground=Brush(255,174,72),IsIndeterminate=false,IsHitTestVisible=false,Visibility=Visibility.Collapsed};
private readonly TextBlock planningLabel=new(){Text="规划中…",FontSize=12,Foreground=Brush(255,174,72),Visibility=Visibility.Collapsed};
private readonly List<(TextBlock Text,TranslateTransform Position)> placeLabels=[];
private readonly Microsoft.UI.Dispatching.DispatcherQueueTimer cameraTimer;
private readonly Microsoft.UI.Dispatching.DispatcherQueueTimer keyboardTimer;
private readonly HashSet<Windows.System.VirtualKey> cameraKeys=[];
private double lastKeyboardTick;
private (double X,double Y,double Scale,double EndScale,double At)? cameraAnimation;
private bool holdInvoked;
private bool planningCancellation;
private static double MonotonicMilliseconds=>Stopwatch.GetTimestamp()*1000.0/Stopwatch.Frequency;
private const int MaximumStars = GalaxyGraphics.StarCapacity, MaximumLabels = 40;
private readonly Grid host = new() { Background = Brush(10, 20, 32) };
private readonly Canvas labels = new() { IsHitTestVisible = false };
private readonly RectangleGeometry clip = new();
private readonly TextBlock emptyText = new() { Text = "等待真实星系坐标", FontSize = 14, Foreground = Brush(145, 163, 185) };
private Compositor? compositor;
private ContainerVisual? scene;
private GalaxyGraphics? graphics;
private SpriteVisual? pixelsVisual;
private readonly GalaxyStar[] starInstances=new GalaxyStar[MaximumStars];
private readonly GalaxyLineVertex[] lineVertices=new GalaxyLineVertex[GalaxyGraphics.LineVertexCapacity];
private readonly GalaxyOriginalGridLine[] originalGridLines=new GalaxyOriginalGridLine[GalaxyOriginalGrid.MaximumLines];
private long skyCameraChanges;
private (double W,double H,double Yaw,double Pitch) skyCamera;
private ShapeVisual? glows;
private ShapeVisual? vectors;
private CompositionColorBrush[] colors = [];
private CompositionColorBrush[] spectralColours=[];
private CompositionRadialGradientBrush[] spectralGlows=[];
private readonly Dictionary<(StarColour Colour,byte Alpha),CompositionColorBrush> stellarBrushes=[];
private readonly Dictionary<(StarColour Colour,byte Alpha),CompositionRadialGradientBrush> stellarGlows=[];
private readonly SolidColorBrush[] labelColors = [Brush(138, 177, 211), Brush(255, 174, 72), Brush(255, 174, 72), Brush(84, 222, 200)];
private CompositionColorBrush? gridBrush;
private readonly List<LineVisual> grid = [], routes = [];
private readonly List<StarVisual> stars = [];
private readonly List<LabelVisual> names = [];
private CompositionSpriteShape? currentRing, selectedRing;
private Sample[] ordered = [];
private readonly GalaxyMapLod stellarLod=new();
private readonly ConditionalWeakTable<GalacticSystem,NameLayout> nameLayouts=new();
private readonly HashSet<string> regionLabelNames=new(StringComparer.OrdinalIgnoreCase);
private NavWaypoint[] cachedRoute = [];
private HashSet<long> dashedLegs=[],supplySites=[];
private readonly List<(TextBlock Text,TranslateTransform Position)> supplyLabels=[];
private readonly (Point Point, GalacticSystem System)[] hits = new (Point, GalacticSystem)[MaximumStars];
private readonly Rect[] labelRects = new Rect[MaximumLabels];
private int hitCount;
private bool loaded, pageActive = true, scheduled, sceneDirty = true, dragging, panning;
private GalaxyMouseButtons mouseButtons;
private bool mouseGesture, suppressPointerSelection;
private double yaw = -.3, pitch = .45, scale = 4, panX, panY, travel;
private Point previous;
public long FrameCount { get; private set; }
public long SceneRebuilds { get; private set; }
public int VectorNodesCreated { get; private set; }
public int TextNodesCreated => names.Count * 2 + 1;
public double LastFrameMilliseconds { get; private set; }
internal int VisibleStars => hitCount;
internal int CandidateStars {get;private set;}
internal bool StellarLodActive {get;private set;}
internal int StellarLodOccupiedCells {get;private set;}
internal int VisibleNameLabels=>names.Count(n=>n.Visible);
internal int VisibleLinkSegments {get;private set;}
internal int VisibleRouteSegments {get;private set;}
internal int VisibleGridConnectors {get;private set;}
internal double HoldProgress=>holdProgress.Value;
internal bool ShowsPlanning=>planningCandidate is not null&&holdProgress.Visibility==Visibility.Visible&&holdProgress.IsIndeterminate;
internal bool ShowsHold=>holdProgress.Visibility==Visibility.Visible;
internal long SkyboxRebuilds=>skyCameraChanges;
internal string MapGraphicsBackend=>graphics is null?"Composition vectors":"Direct3D 11 · instanced stars";
internal string GraphicsError { get; private set; }="";
internal int GraphicsDrawCalls=>graphics?.DrawCalls??0;
internal int VisibleNebulae=>graphics?.VisibleNebulae??0;
internal int PendingNebulaLoads=>graphics?.PendingNebulaLoads??0;
internal int ResidentNebulaTextures=>graphics?.ResidentNebulaTextures??0;
internal bool GalaxyDensityReady=>graphics?.Overview is not null;
internal long NebulaGpuBytes=>graphics?.NebulaGpuBytes??0;
internal void EnableNebulaeForProbe(bool value){if(graphics is not null)graphics.NebulaeEnabled=value;Invalidate();}
internal (int Width,int Height,byte[] Pixels) CapturePixelsForProbe()=>graphics?.ReadPixels()??throw new InvalidOperationException(GraphicsError);
internal async Task<IDisposable> FreezeForXamlProbeAsync()
{
RenderNowForProbe();var frame=CapturePixelsForProbe();
var bitmap=new Microsoft.UI.Xaml.Media.Imaging.WriteableBitmap(frame.Width,frame.Height);
using(var stream=bitmap.PixelBuffer.AsStream())await stream.WriteAsync(frame.Pixels);bitmap.Invalidate();
var snapshot=new Image{Source=bitmap,Stretch=Stretch.Fill,IsHitTestVisible=false};
ElementCompositionPreview.SetElementChildVisual(host,null);host.Children.Add(snapshot);
return new MapSnapshotScope(()=>{host.Children.Remove(snapshot);ElementCompositionPreview.SetElementChildVisual(host,scene);Invalidate();});
}
private sealed class MapSnapshotScope(Action restore):IDisposable{public void Dispose()=>restore();}
internal string SkyboxSource=>graphics?.SkyboxSource??"";
internal int GridLinesVisible { get; private set; }
internal int GlowingStars=>hitCount;
internal bool QueryBackgroundStarsSuppressed=>Filter?.IsQueryActive==true&&graphics?.UnresolvedStarBackgroundEnabled!=true;
internal bool VisibleModelsMatchFilter=>ordered.All(s=>Filter?.Matches(s.System)!=false);
internal int FilteredModels=>ordered.Length;
internal GalaxyViewport RequestedViewportForProbe=>Camera.ToViewport();
internal void FlushViewportForProbe()=>FlushViewport();
internal long ViewportNotifications {get;private set;}
internal (double Yaw, double Pitch, double Scale, double PanX, double PanY) CameraState => (yaw, pitch, scale, panX, panY);
private static SolidColorBrush Brush(byte r, byte g, byte b) => new(Windows.UI.Color.FromArgb(255, r, g, b));
public GalaxyMapView()
{
holdTimer=DispatcherQueue.CreateTimer();holdTimer.Interval=TimeSpan.FromMilliseconds(16);holdTimer.IsRepeating=true;
holdTimer.Tick+=(_,_)=>ConfirmHold();
cameraTimer=DispatcherQueue.CreateTimer();cameraTimer.Interval=TimeSpan.FromMilliseconds(16);cameraTimer.Tick+=(_,_)=>AnimateCamera();
cameraMotionTimer=DispatcherQueue.CreateTimer();cameraMotionTimer.Interval=TimeSpan.FromMilliseconds(16);cameraMotionTimer.Tick+=(_,_)=>AdvanceCameraMotion();
keyboardTimer=DispatcherQueue.CreateTimer();keyboardTimer.Interval=TimeSpan.FromMilliseconds(16);keyboardTimer.Tick+=(_,_)=>UpdateKeyboardCamera();
viewportTimer=DispatcherQueue.CreateTimer();viewportTimer.Interval=TimeSpan.FromMilliseconds(200);viewportTimer.IsRepeating=false;
viewportTimer.Tick+=(_,_)=>PublishPendingViewport();
var root = new Grid { Clip = clip }; root.Children.Add(host); root.Children.Add(labels); Content = root;
labels.Children.Add(emptyText);
labels.Children.Add(holdProgress);labels.Children.Add(planningLabel);
ManipulationMode = ManipulationModes.None;
Loaded += (_, _) => { loaded = true; EnsureGraphics(); Resize(); Invalidate();ScheduleViewport(); };
Unloaded += (_, _) => { loaded = false; StopScheduling(); StopOriginalFrameFade();CancelCameraInput();viewportTimer.Stop();viewportThrottle.Reset(); };
SizeChanged += (_, _) => { Resize(); Invalidate();ScheduleViewport(); };
PointerPressed += Pressed; PointerMoved += Moved; PointerReleased += Released;
PointerCanceled += (_, _) => {var moving=dragging;if(moving)CancelCameraInput();if(moving)FlushViewport();};PointerCaptureLost += (_, _) => {var moving=dragging;if(moving)CancelCameraInput();if(moving)FlushViewport();};
IsTabStop=true;
KeyDown+=CameraKeyDown;
KeyUp+=(_,e)=>{if(cameraKeys.Remove(e.Key)){e.Handled=true;FinishCameraInput();if(cameraKeys.Count==0){keyboardTimer.Stop();FlushViewport();}}};
LostFocus+=(_,_)=>{CancelCameraInput();FlushViewport();};
DoubleTapped+=(_,e)=>{if(IsInteractive&&FindAt(e.GetPosition(this)) is {} selected){FocusSystem(selected);e.Handled=true;}};
PointerWheelChanged += (_, e) =>
{
if (!IsInteractive) return;
var point = e.GetCurrentPoint(this); ApplyOriginalWheelInput(point.Properties.MouseWheelDelta); e.Handled = true;
};
Microsoft.UI.Xaml.Automation.AutomationProperties.SetName(this, "银河星图:点击选择,双击聚焦;左键旋转,右键水平偏航与垂直升降,双键平面移动,滚轮缩放;WASD 平面移动,R/F 升降,T/G 俯仰,Q/E 偏航,Z/X 缩放,Home 返回导航中心,Esc 取消选择;长按恒星规划航线");
}
private void EnsureGraphics()
{
if (vectors is not null) return;
compositor = ElementCompositionPreview.GetElementVisual(host).Compositor;
scene=compositor.CreateContainerVisual();glows=compositor.CreateShapeVisual();
vectors = compositor.CreateShapeVisual();
try
{
graphics=new(compositor);graphics.ResourcesChanged+=Invalidate;pixelsVisual=compositor.CreateSpriteVisual();pixelsVisual.RelativeSizeAdjustment=Vector2.One;
var surface=compositor.CreateSurfaceBrush(graphics.Surface);surface.Stretch=CompositionStretch.Fill;pixelsVisual.Brush=surface;scene.Children.InsertAtBottom(pixelsVisual);
}
catch(Exception error){GraphicsError=error.ToString();App.Runtime.Log("星图渲染",error.Message);graphics?.Dispose();graphics=null;}
scene.Children.InsertAtTop(glows);scene.Children.InsertAtTop(vectors);
colors = [compositor.CreateColorBrush(Windows.UI.Color.FromArgb(255, 138, 177, 211)), compositor.CreateColorBrush(Windows.UI.Color.FromArgb(255, 255, 174, 72)), compositor.CreateColorBrush(Windows.UI.Color.FromArgb(255, 255, 174, 72)), compositor.CreateColorBrush(Windows.UI.Color.FromArgb(255, 84, 222, 200))];
var gridSource=GalaxyOriginalGrid.Colour;var gridColour=gridSource.DisplayColour();
gridBrush = compositor.CreateColorBrush(Windows.UI.Color.FromArgb((byte)Math.Round(gridSource.A*255),gridColour.R,gridColour.G,gridColour.B));
spectralColours=StellarAppearance.Palette.Select(c=>compositor.CreateColorBrush(Windows.UI.Color.FromArgb(255,c.R,c.G,c.B))).ToArray();
spectralGlows=StellarAppearance.Palette.Select(c=>GalaxySkybox.Radial(compositor,Windows.UI.Color.FromArgb(145,c.R,c.G,c.B))).ToArray();
for(var i=0;i<StellarAppearance.Palette.Count;i++){stellarBrushes[(StellarAppearance.Palette[i],255)]=spectralColours[i];stellarGlows[(StellarAppearance.Palette[i],145)]=spectralGlows[i];}
if(graphics is null)for (var i = 0; i < InfiniteGalaxyGrid.MaximumLines; i++) grid.Add(CreateLine(gridBrush, 1));
currentRing = CreateRing(colors[3]); selectedRing = CreateRing(colors[2]);
ElementCompositionPreview.SetElementChildVisual(host, scene);
}
private LineVisual CreateLine(CompositionBrush color, float width, int at = -1)
{
var geometry = compositor!.CreateLineGeometry(); var shape = compositor.CreateSpriteShape(geometry);
shape.StrokeBrush = color; shape.StrokeThickness = width; if (at < 0) vectors!.Shapes.Add(shape); else vectors!.Shapes.Insert(at, shape); VectorNodesCreated++;
return new(geometry, shape);
}
private CompositionSpriteShape CreateRing(CompositionBrush color)
{
var geometry = compositor!.CreateEllipseGeometry(); geometry.Radius = new(14, 14);
var shape = compositor.CreateSpriteShape(geometry); shape.StrokeBrush = color; shape.StrokeThickness = 1; shape.Scale = Vector2.Zero;
vectors!.Shapes.Add(shape); VectorNodesCreated++; return shape;
}
private void Resize()
{
clip.Rect = new Rect(0, 0, Math.Max(0, ActualWidth), Math.Max(0, ActualHeight));
if (vectors is not null) vectors.Size = new((float)ActualWidth, (float)ActualHeight);
if(scene is not null)scene.Size=glows!.Size=new((float)ActualWidth,(float)ActualHeight);
Canvas.SetLeft(emptyText, Math.Max(16, ActualWidth / 2 - 65)); Canvas.SetTop(emptyText, ActualHeight / 2);
}
private static void Changed(DependencyObject d, DependencyPropertyChangedEventArgs e) { var view = (GalaxyMapView)d; view.sceneDirty = true; view.Invalidate(); }
private static void SelectionChanged(DependencyObject d,DependencyPropertyChangedEventArgs e)
{
var view=(GalaxyMapView)d;
if(view.holdCandidate is {} held&&e.NewValue is GalacticSystem changed&&
(!held.Name.Equals(changed.Name,StringComparison.OrdinalIgnoreCase)||held.SystemAddress!=changed.SystemAddress))view.CancelHold();
if(e.NewValue is null)view.CancelHold();
view.SelectionFloorChanged(e.NewValue as GalacticSystem);
// Selecting a marker must not move the camera or move a neighbour under
// the pointer. Explicit search/double-click performs the focus motion.
view.sceneDirty=true;view.Invalidate();view.ScheduleViewport();
}
private static void PlanningChanged(DependencyObject d,DependencyPropertyChangedEventArgs e)
{
var view=(GalaxyMapView)d;
if((bool)e.NewValue){view.planningCandidate??=view.Selection;view.planningCancellation=view.PlottedDestination>0&&view.planningCandidate?.SystemAddress==view.PlottedDestination;view.holdProgress.IsIndeterminate=true;view.holdProgress.IsActive=true;}
else{view.planningCandidate=null;view.holdProgress.IsActive=false;view.holdProgress.Visibility=view.planningLabel.Visibility=Visibility.Collapsed;}
view.Invalidate();
}
private static void CentreChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var view = (GalaxyMapView)d;if(!view.applyingCameraPose){view.CancelCameraInput();view.panX=view.panY=0;view.ResetFloorSelector();}view.Invalidate();view.ScheduleViewport(); }
public void ResumePage() { pageActive = true; Invalidate();ScheduleViewport(); }
public void SuspendPage() { pageActive = false;StopOriginalFrameFade();CancelCameraInput();StopScheduling();viewportTimer.Stop();viewportThrottle.Reset(); }
private void Invalidate()
{
if (scheduled || !loaded || !pageActive) return;
scheduled = true; CompositionTarget.Rendering += RenderFrame;
}
private void StopScheduling() { if (!scheduled) return; CompositionTarget.Rendering -= RenderFrame; scheduled = false; }
private void RenderFrame(object? sender, object e) { StopScheduling(); if (loaded && pageActive) Draw(); }
// Explicit application reset, independent of the original game's optional
// saved camera pose (not imported here).
public void ResetCamera() { CancelCameraInput();yaw = -.3; pitch = .45; scale = 4; panX = panY = 0; Invalidate();ScheduleViewport(); }
public void ClearSelection(){CancelCameraInput();Selection=null;SelectionCleared?.Invoke();Invalidate();}
public void FocusSystem(GalacticSystem system,bool zoom=true)
{
if(!system.Position.IsValid)return;
CancelCameraInput();
Selection=system;SystemSelected?.Invoke(this,system);
if(Centre!=system.Position){Centre=system.Position;sceneDirty=true;}
cameraAnimation=(panX,panY,scale,zoom?Math.Clamp(Math.Max(6,scale*2),.001,1000):scale,MonotonicMilliseconds);cameraTimer.Start();
}
private void AnimateCamera()
{
if(cameraAnimation is not {} a){cameraTimer.Stop();return;}
var t=Math.Clamp((MonotonicMilliseconds-a.At)/260,0,1);var eased=1-Math.Pow(1-t,3);
panX=a.X*(1-eased);panY=a.Y*(1-eased);scale=a.Scale+(a.EndScale-a.Scale)*eased;Invalidate();ScheduleViewport();
if(t>=1){cameraAnimation=null;cameraTimer.Stop();FlushViewport();}
}
public void RefreshDisplay(){Invalidate();ScheduleViewport();}
private GalaxyCamera Camera
{
get
{
var camera=GalaxyCamera.Create(Centre??new(0,0,0),Math.Max(1,ActualWidth),Math.Max(1,ActualHeight),yaw,pitch,scale,panX,panY);
return CatalogueSelection?.ApplyTo(camera)??camera;
}
}
private static bool IsCameraKey(Windows.System.VirtualKey key)=>key is Windows.System.VirtualKey.W or Windows.System.VirtualKey.S or Windows.System.VirtualKey.A or Windows.System.VirtualKey.D
or Windows.System.VirtualKey.R or Windows.System.VirtualKey.F or Windows.System.VirtualKey.T or Windows.System.VirtualKey.G or Windows.System.VirtualKey.Q or Windows.System.VirtualKey.E
or Windows.System.VirtualKey.Z or Windows.System.VirtualKey.X;
private void CameraKeyDown(object sender,KeyRoutedEventArgs e)
{
if(!IsInteractive)return;
if(e.Key==Windows.System.VirtualKey.Escape){ClearSelection();e.Handled=true;return;}
if(e.Key==Windows.System.VirtualKey.Home){ReturnCameraHome();e.Handled=true;return;}
if(!IsCameraKey(e.Key))return;
cameraTimer.Stop();cameraAnimation=null;CancelHold();
if(cameraKeys.Add(e.Key)&&cameraKeys.Count==1){lastKeyboardTick=MonotonicMilliseconds;keyboardTimer.Start();}
e.Handled=true;
}
private void StopKeyboard(){var moving=cameraKeys.Count>0;cameraKeys.Clear();keyboardTimer.Stop();if(moving){FinishCameraInput();FlushViewport();}}
private void UpdateKeyboardCamera()
{
if(!IsInteractive||!loaded||!pageActive||cameraKeys.Count==0){StopKeyboard();return;}
var now=MonotonicMilliseconds;var seconds=Math.Clamp((now-lastKeyboardTick)/1000,0,.05);lastKeyboardTick=now;
ApplyKeyboardForProbe(seconds,cameraKeys);
}
internal void ApplyKeyboardForProbe(double seconds,IReadOnlySet<Windows.System.VirtualKey> keys)
{
ApplyOriginalKeyboardInput(seconds,keys);
}
public void ShowGalaxyOverview()
{
var map=graphics?.Overview;if(map is null)return;
CancelCameraInput();
Centre=new(map.ExtentX/2-map.OriginX,0,map.ExtentZ/2-map.OriginZ);yaw=-.08;pitch=1.15;panX=panY=0;
scale=Math.Min(Math.Max(80,ActualWidth-100)/map.ExtentX,Math.Max(80,ActualHeight-100)/(map.ExtentZ*Math.Abs(Math.Sin(pitch))))*.65;Invalidate();ScheduleViewport();
}
private void ScheduleViewport()
{
if(!pageActive||!loaded)return;
viewportThrottle.Changed();
// Repeated input leaves the deadline intact; a debounce that restarts on
// every pointer delta starves catalogue loads throughout a long drag.
if(!viewportTimer.IsRunning){viewportTimer.Interval=TimeSpan.FromMilliseconds(Math.Max(1,viewportThrottle.Delay(MonotonicMilliseconds)));viewportTimer.Start();}
}
private void PublishPendingViewport()
{
if(viewportThrottle.TryPublish(MonotonicMilliseconds))PublishViewport();
if(viewportThrottle.Pending&&pageActive&&loaded){viewportTimer.Interval=TimeSpan.FromMilliseconds(Math.Max(1,viewportThrottle.Delay(MonotonicMilliseconds)));viewportTimer.Start();}
}
private void FlushViewport()
{
viewportTimer.Stop();if(!pageActive||!loaded)return;
viewportThrottle.Changed();if(viewportThrottle.TryPublish(MonotonicMilliseconds,true))PublishViewport();
}
private void PublishViewport()
{
if(!pageActive||!loaded||scale<=0||ActualWidth<1||ActualHeight<1)return;
ViewportNotifications++;ViewportSettled?.Invoke(Camera.ToViewport());
}
public void Zoom(double factor) => ZoomAt(factor, new(ActualWidth / 2, ActualHeight / 2));
public void FitRoute(double rightInset=0)
{
var route=Route;if(route is null||route.Count<2||ActualWidth<1||ActualHeight<1)return;
var points=route.Select(w=>w.Position).Where(p=>p.IsValid).ToArray();if(points.Length<2)return;
CancelCameraInput();
Centre=new((points.Min(p=>p.X)+points.Max(p=>p.X))/2,(points.Min(p=>p.Y)+points.Max(p=>p.Y))/2,(points.Min(p=>p.Z)+points.Max(p=>p.Z))/2);
rightInset=Math.Clamp(rightInset,0,ActualWidth*.55);
var span=Math.Max(10,Math.Max(points.Max(p=>p.X)-points.Min(p=>p.X),Math.Max(points.Max(p=>p.Y)-points.Min(p=>p.Y),points.Max(p=>p.Z)-points.Min(p=>p.Z))));
scale=Math.Clamp(Math.Min(ActualWidth-rightInset-80,ActualHeight-160)/span,.001,1000);panX=-rightInset/2;panY=0;
for(var attempt=0;attempt<40;attempt++)
{
var camera=Camera;
if(points.All(p=>{var at=camera.Project(p);return at.IsVisible&&at.X>=36&&at.X<=ActualWidth-rightInset-36&&at.Y>=50&&at.Y<=ActualHeight-75;}))break;
scale=Math.Max(.001,scale*.8);
}
Invalidate();ScheduleViewport();
}
private void ZoomAt(double factor, Point anchor)
{
if (!double.IsFinite(factor) || factor <= 0) return;
if(!pageActive)return;
ZoomCameraTarget(factor,anchor);
}
internal void ApplyDragDelta(double dx, double dy, bool pan)
{
if (!IsInteractive||!pageActive) return;
var target=EnsureCameraTarget();
if(pan)target=target with{Focus=TargetCamera(target).Pan(dx,dy)};
else target=target with{Yaw=target.Yaw+dx*.006,Pitch=target.Pitch+dy*.006};
SetCameraTarget(target,pan||CameraCraneActive,pan?1:0);
}
internal void ApplyMouseDragDelta(double dx,double dy,GalaxyMouseButtons buttons)
{
ApplyOriginalMouseInput(dx,dy,buttons);
}
private void RebuildScene()
{
sceneDirty = false; SceneRebuilds++;
var centre = Centre; var cx = centre?.X ?? 0; var cy = centre?.Y ?? 0; var cz = centre?.Z ?? 0;
cachedRoute = (Route ?? []).ToArray(); var routeNames = cachedRoute.Select(w => w.Name).ToHashSet(StringComparer.OrdinalIgnoreCase);
dashedLegs=(FuelOverlay?.DashedLegs??[]).ToHashSet();supplySites=(FuelOverlay?.SupplySites??[]).ToHashSet();
ordered = (Systems ?? []).Where(s => s.Position.IsValid&&Filter?.Matches(s)!=false&&CatalogueSelection?.Contains(s)!=false).Select(s =>
{
var kind = s.Name.Equals(CurrentSystem, StringComparison.OrdinalIgnoreCase) ? 3 : s.Name.Equals(Selection?.Name, StringComparison.OrdinalIgnoreCase) ? 2 : routeNames.Contains(s.Name) ? 1 : 0;
var name=nameLayouts.GetValue(s,static system=>
{
var display=system.DisplayName;var original=display==system.Name?"":system.Name;
return new(display,original,Math.Max(60,Math.Max(system.Name.Length*7,display.Length*12)),original.Length>0?32:18);
});
if(Filter is {Category:GalaxyFilterCategory.Markers,Values.Count:1} regionFilter&®ionFilter.Values.Contains("galacticregion"))
{
var display=regionFilter.LabelFor(s);
name=new(display,"",Math.Max(60,display.Length*12),18);
}
var spectral=StellarAppearance.ColourIndex(s.StarClass);var colour=Filter?.GetColour(s)??StellarAppearance.Palette[spectral];
var realistic=Filter is null||Filter.Mode==GalaxyMapMode.Realistic;
var opacity=Filter?.GetOpacity(s)??1;
if(realistic&&s.OriginalAppearance is {} original)
{var rgba=original.RealisticRgba??original.TypeRgba;colour=GalaxyOriginalStellarAppearance.Colour(rgba);opacity*=((rgba>>24)&255)/255f;}
var relative=realistic?CurrentOriginalSize(s) is{} actualSize?actualSize>0?1:0:StellarAppearance.PhysicalRadius(s.StarClass):Filter!.RelativeSize(s);
return new Sample(s, s.Position.X - cx, s.Position.Y - cy, s.Position.Z - cz, kind,spectral,name,colour,relative,opacity,Filter?.GetOriginalRgba(s),GalaxyMapLod.IsPriority(s,CatalogueSelection,true,kind>0));
}).Where(s=>s.RelativeSize>0&&s.Opacity>0&&s.OriginalColour is not{W:<=0})
.OrderByDescending(s => s.Kind).ThenByDescending(s=>s.LodPriority).ThenBy(s => s.X * s.X + s.Y * s.Y + s.Z * s.Z).ToArray();
floorCandidates=ordered.Select(s=>new GalaxyFloorCandidate(s.System.SystemAddress,s.System.Position)).ToArray();
RebuildConstellations();
while (graphics is null&&stars.Count < Math.Min(1800, ordered.Length))
{
var geometry = compositor!.CreateEllipseGeometry(); geometry.Radius = new(2.2f, 2.2f);
var shape = compositor.CreateSpriteShape(geometry); shape.FillBrush = colors[0]; shape.Scale = Vector2.Zero;
var auraGeometry=compositor.CreateEllipseGeometry();auraGeometry.Radius=new(15,15);
var aura=compositor.CreateSpriteShape(auraGeometry);aura.FillBrush=spectralGlows[13];aura.Scale=Vector2.Zero;glows!.Shapes.Add(aura);
vectors!.Shapes.Insert(InfiniteGalaxyGrid.MaximumLines + routes.Count + stars.Count, shape); stars.Add(new(geometry, shape,auraGeometry,aura)); VectorNodesCreated+=2;
}
while (graphics is null&&routes.Count < Math.Max(0, cachedRoute.Length - 1)) routes.Add(CreateLine(colors[1], 2, InfiniteGalaxyGrid.MaximumLines + routes.Count));
for (var i = 0; i < routes.Count; i++)
{
routes[i].Shape.Scale = i < cachedRoute.Length - 1 ? Vector2.One : Vector2.Zero;
routes[i].Shape.StrokeDashArray.Clear();
if(i<cachedRoute.Length-1&&dashedLegs.Contains(cachedRoute[i+1].SystemAddress)){routes[i].Shape.StrokeDashArray.Add(6);routes[i].Shape.StrokeDashArray.Add(4);}
}
while(supplyLabels.Count<Math.Min(24,supplySites.Count))
{
var position=new TranslateTransform();var text=new TextBlock{FontSize=11,Foreground=labelColors[3],RenderTransform=position,Opacity=0};
labels.Children.Add(text);supplyLabels.Add((text,position));
}
while(placeLabels.Count<Math.Min(20,PointsOfInterest?.Count??0))
{
var position=new TranslateTransform();var text=new TextBlock{FontSize=12,FontWeight=Microsoft.UI.Text.FontWeights.SemiBold,Foreground=labelColors[1],RenderTransform=position,Opacity=0};
labels.Children.Add(text);placeLabels.Add((text,position));
}
while (names.Count < Math.Min(MaximumLabels, ordered.Length))
{
var text = new TextBlock { FontSize = 11, Foreground = Brush(138, 177, 211) };
var original = new TextBlock { FontSize = 9, Foreground = Brush(145, 163, 185) };
var panel = new StackPanel { Opacity = 0, RenderTransform = new TranslateTransform() };
panel.Children.Add(text); panel.Children.Add(original); labels.Children.Add(panel); names.Add(new(panel, text, original, (TranslateTransform)panel.RenderTransform));
}
RebuildWorldMarkers();
emptyText.Text=(Systems?.Count??0)>0?"当前筛选条件下没有星系":"等待真实星系坐标";
emptyText.Opacity = ordered.Length == 0 ? 1 : 0;
}
private void Draw()
{
var viewWidth=ActualWidth;var viewHeight=ActualHeight;
if (vectors is null || viewWidth < 1 || viewHeight < 1) return;
var started = Stopwatch.GetTimestamp(); if (sceneDirty) RebuildScene();
var camera=Camera;
PrepareOriginalFrameFade();FrameFadedStarsForProbe=0;
var renderCapacity=graphics is null?1800:MaximumStars;
var useLod=ordered.Length>renderCapacity;
StellarLodActive=false;StellarLodOccupiedCells=0;CandidateStars=0;
if(useLod)
{
stellarLod.Begin(viewWidth,viewHeight,renderCapacity);
foreach(var sample in ordered){if(PointFrameOpacity(sample)<=0)continue;var at=camera.ProjectForCatalogue(sample.System.Position);if(at.IsVisible)stellarLod.Count(at.X,at.Y,sample.LodPriority);}
stellarLod.Seal();CandidateStars=stellarLod.Candidates;StellarLodActive=stellarLod.Active;StellarLodOccupiedCells=stellarLod.OccupiedCells;
}
if(graphics is not null&&skyCamera!=(viewWidth,viewHeight,yaw,pitch)){skyCamera=(viewWidth,viewHeight,yaw,pitch);skyCameraChanges++;}
var lineCount=0;
void GpuLine(Point a,Point b,Vector4 colour,bool dashed=false)
{
if(lineCount+2>lineVertices.Length)return;
// Skip wholly invisible edges before upload. The hardware clips the rest.
if(a.X<0&&b.X<0||a.Y<0&&b.Y<0||a.X>viewWidth&&b.X>viewWidth||a.Y>viewHeight&&b.Y>viewHeight)return;
var length=Math.Sqrt((b.X-a.X)*(b.X-a.X)+(b.Y-a.Y)*(b.Y-a.Y));if(length<.3)return;
lineVertices[lineCount++]=new(new((float)a.X,(float)a.Y),0,dashed?1:0,colour);
lineVertices[lineCount++]=new(new((float)b.X,(float)b.Y),(float)length,dashed?1:0,colour);
}
Span<MapSegment> segments=stackalloc MapSegment[InfiniteGalaxyGrid.MaximumLines];
GridLinesVisible=Filter?.ShowGrid==false?0:GalaxyMapGeometry.WriteOriginalGrid(segments,camera,out var step);
if(graphics is not null)
{
var originalCount=Filter?.ShowGrid==false?0:GalaxyOriginalGrid.Write(originalGridLines,camera.Focus,camera.Distance);
graphics.SetOriginalGrid(originalGridLines.AsSpan(0,originalCount));
}
for (var i = 0; i < grid.Count; i++)
{
grid[i].Shape.Scale=graphics is null&&i<GridLinesVisible?Vector2.One:Vector2.Zero;
if(i<GridLinesVisible){var line=segments[i];grid[i].Move(new(line.X1,line.Y1),new(line.X2,line.Y2));}
}
var floorCount=WriteFloorSelector(segments,camera);
if(graphics is not null)for(var i=0;i<floorCount;i++){var line=segments[i];GpuLine(new(line.X1,line.Y1),new(line.X2,line.Y2),new(.05f,.72f,.86f,.8f));}
else
{
while(floorLines.Count<floorCount)floorLines.Add(CreateLine(compositor!.CreateColorBrush(Windows.UI.Color.FromArgb(204,13,184,219)),1.2f));
for(var i=0;i<floorLines.Count;i++){floorLines[i].Shape.Scale=i<floorCount?Vector2.One:Vector2.Zero;if(i<floorCount){var line=segments[i];floorLines[i].Move(new(line.X1,line.Y1),new(line.X2,line.Y2));}}
}
var centre = Centre; var cx = centre?.X ?? 0; var cy = centre?.Y ?? 0; var cz = centre?.Z ?? 0;
VisibleLinkSegments=VisibleRouteSegments=VisibleGridConnectors=0;
DrawConstellations(camera,ref lineCount);
if(Filter is {ShowLinks:true} filter)
{
var origin=Systems?.FirstOrDefault(s=>s.Name.Equals(CurrentSystem,StringComparison.OrdinalIgnoreCase))??Selection;
if(origin is not null)
{
var linkLimit=Math.Max(0,(lineVertices.Length-lineCount-Math.Min(cachedRoute.Length*2,lineVertices.Length/4)-8192)/2);
foreach(var sample in ordered)
{
if(VisibleLinkSegments>=linkLimit)break;
if(sample.System.Name==origin.Name||sample.System.Position.DistanceTo(origin.Position)>filter.JumpRange)continue;
if(GalaxyMapGeometry.TryProjectSegment(camera,origin.Position,sample.System.Position,out var link))
{GpuLine(new(link.X1,link.Y1),new(link.X2,link.Y2),new(.13f,.56f,.62f,.22f));VisibleLinkSegments++;}
}
}
}
if(graphics is null)foreach(var route in routes)route.Shape.Scale=Vector2.Zero;
for (var i = 1; i < cachedRoute.Length&&Filter?.ShowRoute!=false; i++)
{
var a = cachedRoute[i - 1].Position; var b = cachedRoute[i].Position;
if(!GalaxyMapGeometry.TryProjectSegment(camera,a,b,out var segment))continue;
VisibleRouteSegments++;
var from=new Point(segment.X1,segment.Y1);var to=new Point(segment.X2,segment.Y2);
if(graphics is null){routes[i-1].Move(from,to);routes[i-1].Shape.Scale=Vector2.One;}else GpuLine(from,to,new(1,.67f,.26f,.88f),dashedLegs.Contains(cachedRoute[i].SystemAddress));
}
DrawHistoricalTradeFlows(camera,ref lineCount);
hitCount = 0; var labelCount = 0; currentRing!.Scale = selectedRing!.Scale = Vector2.Zero;
regionLabelNames.Clear();
var regionLabels=Filter is {Category:GalaxyFilterCategory.Markers,Values.Count:1} regionFilter&®ionFilter.Values.Contains("galacticregion");
for (var i = 0; i < names.Count; i++) names[i].Wanted = false;
for (var index = 0; index < ordered.Length; index++)
{
var s = ordered[index];var projected=camera.ProjectForCatalogue(s.System.Position);if(!projected.IsVisible)continue;
var frameOpacity=PointFrameOpacity(s);if(frameOpacity<=0){FrameFadedStarsForProbe++;continue;}
var p = new Point(projected.X,projected.Y);
if(useLod&&!stellarLod.Accept(p.X,p.Y,s.LodPriority))continue;
if (hitCount == renderCapacity) break;
if(graphics is not null&&Filter is {ShowGridStalks:true,ShowGrid:true}&&VisibleGridConnectors<4000
&&GalaxyMapGeometry.TryProjectStalk(camera,s.System.Position,out var stalk))
{GpuLine(new(stalk.X1,stalk.Y1),new(stalk.X2,stalk.Y2),new(.2f,.42f,.49f,.12f));VisibleGridConnectors++;}
if(graphics is not null)
{
var colour=s.Colour;
var kind=Filter?.ShowMarkers==false||s.Kind==1&&Filter?.ShowRoute==false?0:s.Kind;
var realistic=Filter is null||Filter.Mode==GalaxyMapMode.Realistic;
var sprite=realistic&&s.System.OriginalAppearance is {} original?StellarAppearance.OriginalSprite(original.Classification):Filter?.SpriteLayerFor(s.System)??13;
var originalColour=s.OriginalColour is{} sourceColour?sourceColour with{W=sourceColour.W*frameOpacity}:(Vector4?)null;
starInstances[hitCount]=new(new((float)p.X,(float)p.Y),s.RelativeSize,kind,new(colour.R/255f,colour.G/255f,colour.B/255f,s.Opacity*frameOpacity),new((float)s.System.Position.X,(float)s.System.Position.Y,(float)s.System.Position.Z,s.Spectral+1),realistic?CurrentOriginalSize(s.System)??0:0,Filter is {UsesPowerTerritory:true}&&Filter.PowerTerritoryStyle(s.System) is not null,sprite,originalColour,
realistic&&s.System.OriginalAppearance is{} source&&XFEEDToolBox.Core.Rendering.GalaxyOriginalBlackHole.IsSpecial(source.Classification));
}
else
{
var dot = stars[hitCount]; dot.Shape.Offset = new((float)p.X, (float)p.Y);
dot.Aura.Offset=dot.Shape.Offset;
if (!dot.Visible) { dot.Shape.Scale = dot.Aura.Scale=Vector2.One; dot.Visible = true; }
var realistic=Filter is null||Filter.Mode==GalaxyMapMode.Realistic;
var dx=s.System.Position.X-camera.Focus.X;var dy=s.System.Position.Y-camera.Focus.Y;var dz=s.System.Position.Z-camera.Focus.Z;
var profile=StellarAppearance.Sprite(s.Spectral,Math.Sqrt(dx*dx+dy*dy+dz*dz),projected.Scale,s.Kind,realistic,CurrentOriginalSize(s.System)??0);
var relativeSize=s.RelativeSize;
if(!realistic&&Filter is {UsesPowerTerritory:true}&&Filter.PowerTerritoryStyle(s.System) is not null)
{var ex=s.System.Position.X-camera.Eye.X;var ey=s.System.Position.Y-camera.Eye.Y;var ez=s.System.Position.Z-camera.Eye.Z;relativeSize*=StellarAppearance.PowerTerritoryDistanceScale(Math.Sqrt(ex*ex+ey*ey+ez*ez));}
var radius=profile.CoreRadius*relativeSize;
dot.Geometry.Radius=new(radius,radius);dot.AuraGeometry.Radius=new(radius*5,radius*5);dot.Aura.Scale=realistic?Vector2.One:Vector2.Zero;
var opacity=s.Opacity*frameOpacity;
if (dot.Kind != s.Kind||dot.Spectral!=s.Spectral||dot.Colour!=s.Colour||dot.Opacity!=opacity)
{
dot.Kind = s.Kind;dot.Spectral=s.Spectral;dot.Colour=s.Colour;dot.Opacity=opacity;
var alpha=(byte)Math.Clamp(Math.Round(255*opacity),0,255);var glowAlpha=(byte)Math.Clamp(Math.Round(145*opacity),0,255);
if(!stellarBrushes.TryGetValue((s.Colour,alpha),out var stellarBrush))stellarBrushes[(s.Colour,alpha)]=stellarBrush=compositor!.CreateColorBrush(Windows.UI.Color.FromArgb(alpha,s.Colour.R,s.Colour.G,s.Colour.B));
if(!stellarGlows.TryGetValue((s.Colour,glowAlpha),out var stellarGlow))stellarGlows[(s.Colour,glowAlpha)]=stellarGlow=GalaxySkybox.Radial(compositor!,Windows.UI.Color.FromArgb(glowAlpha,s.Colour.R,s.Colour.G,s.Colour.B));
dot.Shape.FillBrush=stellarBrush;dot.Aura.FillBrush=stellarGlow;
}
if (Filter?.ShowMarkers!=false&&s.Kind is 2 or 3) { var ring = s.Kind == 3 ? currentRing : selectedRing; ring.Offset = dot.Shape.Offset; ring.Scale = Vector2.One; }
}
hits[hitCount++] = (p, s.System);
if (Filter?.ShowLabels==false||labelCount >= names.Count) continue;
var displayName=s.Label.Display;var originalName=s.Label.Original;
if(regionLabels&®ionLabelNames.Contains(displayName))continue;
var boxWidth=s.Label.Width;var boxHeight=s.Label.Height;
var labelOffset=Filter?.ShowMarkers!=false&&s.Kind is 2 or 3?24:10;
var rect = new Rect(p.X + labelOffset, p.Y - 9, boxWidth, boxHeight); var collides = false;
if(rect.Right>viewWidth-6||rect.Bottom>viewHeight-6||rect.Top<6)continue;
for (var j = 0; j < labelCount; j++) { var r = labelRects[j]; if (r.X < rect.Right && r.Right > rect.X && r.Y < rect.Bottom && r.Bottom > rect.Y) { collides = true; break; } }
if(collides)continue;
if(regionLabels)regionLabelNames.Add(displayName);
// Reject occluded candidates before changing XAML text. Otherwise a
// dense field can mutate this same label thousands of times per frame.
var label = names[labelCount];
var query=Filter?.IsQueryActive==true;
if (!ReferenceEquals(label.System, s.System) || label.Kind != s.Kind||label.Colour!=s.Colour||label.Query!=query||label.Name.Text!=displayName)
{
label.System = s.System; label.Kind = s.Kind;label.Colour=s.Colour;label.Query=query;
label.Name.Text = displayName; label.Name.FontSize = s.Kind == 3 ? 14 : 11; label.Name.Foreground = query&&s.Kind==0?Brush(s.Colour.R,s.Colour.G,s.Colour.B):labelColors[s.Kind]; label.Original.Text = originalName;
label.BoxWidth = boxWidth;label.BoxHeight = boxHeight;
}
label.Transform.X = rect.X;label.Transform.Y = rect.Y;label.Wanted = true;labelRects[labelCount++] = rect;
}
for (var i = 0; i < names.Count; i++) { var label = names[i]; if (label.Visible != label.Wanted) { label.Visible = label.Wanted; label.Panel.Opacity = label.Visible ? 1 : 0; } }
for (var i = hitCount; i < stars.Count; i++) if (stars[i].Visible) { stars[i].Shape.Scale = stars[i].Aura.Scale=Vector2.Zero; stars[i].Visible = false; }
DrawSupplementalLabels(camera);
UpdateHoldVisual();
if(!useLod)CandidateStars=hitCount;
if(graphics is not null)graphics.ShowGalacticZonesPlane=Filter?.ShowGalacticZonesPlane==true;
UpdatePowerContours();
UpdatePowerActivityRing(camera);
graphics?.SetCurrentTradeFlows(Filter?.ShowCurrentTradeFlows==true?CurrentTradeFlows:null);
graphics?.Draw(starInstances.AsSpan(0,hitCount),lineVertices.AsSpan(0,lineCount),viewWidth,viewHeight,XamlRoot?.RasterizationScale??1,yaw,pitch,new((float)cx,(float)cy,(float)cz),(float)scale,(float)panX,(float)panY,Filter is null||Filter.Mode==GalaxyMapMode.Realistic,Filter?.ShowBackground!=false,Filter?.IsQueryActive!=true,Filter?.ShowRoute!=false);
DrawWorldMarkers(camera);
FrameCount++; LastFrameMilliseconds = (Stopwatch.GetTimestamp() - started) * 1000.0 / Stopwatch.Frequency;
if(graphics?.HasOriginalCurrentTradeAnimation==true)Invalidate();
}
private void Pressed(object sender, PointerRoutedEventArgs e)
{
if (!IsInteractive) return; var p = e.GetCurrentPoint(this);
if (!p.Properties.IsLeftButtonPressed && !p.Properties.IsRightButtonPressed && e.Pointer.PointerDeviceType == Microsoft.UI.Input.PointerDeviceType.Mouse) return;
if(e.Pointer.PointerDeviceType==Microsoft.UI.Input.PointerDeviceType.Mouse)
BeginMousePointer(p.Position,Buttons(p.Properties.IsLeftButtonPressed,p.Properties.IsRightButtonPressed));
else BeginPointer(p.Position,false);
dragging=CapturePointer(e.Pointer);if(!dragging)CancelHold();Focus(FocusState.Pointer);e.Handled=true;
}
private void Moved(object sender, PointerRoutedEventArgs e)
{
if (!dragging || !IsInteractive) return; var p = e.GetCurrentPoint(this);
if(mouseGesture)ChangeMouseButtons(p.Position,Buttons(p.Properties.IsLeftButtonPressed,p.Properties.IsRightButtonPressed));
MovePointer(p.Position);e.Handled = true;
}
private void Released(object sender, PointerRoutedEventArgs e)
{
if (!dragging) return;var p=e.GetCurrentPoint(this);
var remaining=Buttons(p.Properties.IsLeftButtonPressed,p.Properties.IsRightButtonPressed);
if(mouseGesture&&remaining!=GalaxyMouseButtons.None){ChangeMouseButtons(p.Position,remaining);e.Handled=true;return;}
EndPointer(p.Position);ReleasePointerCapture(e.Pointer);e.Handled=true;
}
private static GalaxyMouseButtons Buttons(bool left,bool right)=>(left?GalaxyMouseButtons.Left:0)|(right?GalaxyMouseButtons.Right:0);
internal void BeginMousePointer(Point point,GalaxyMouseButtons buttons)
{
if(dragging&&mouseGesture){ChangeMouseButtons(point,buttons);return;}
BeginPointer(point,buttons!=GalaxyMouseButtons.Left);mouseGesture=true;mouseButtons=buttons;
suppressPointerSelection=buttons!=GalaxyMouseButtons.Left;
}
internal void ChangeMouseButtons(Point point,GalaxyMouseButtons buttons)
{
if(!mouseGesture||mouseButtons==buttons)return;
// A chord transition cancels the click/hold even when the last button
// remaining is the left one. Keep capture until all buttons are up.
CancelHold();suppressPointerSelection=true;panning=buttons!=GalaxyMouseButtons.Left;
mouseButtons=buttons;previous=point;
FinishCameraInput();
}
private void CancelHold(){holdTimer.Stop();holdGesture.Cancel();holdCandidate=null;if(!Planning&&planningCandidate is null){holdProgress.IsActive=false;holdProgress.Visibility=Visibility.Collapsed;}}
private void UpdateHoldVisual()
{
var target=planningCandidate??holdCandidate;
var projected=target is null?default:Camera.ProjectForCatalogue(target.Position);
if(target is null||!projected.IsVisible||Filter?.Matches(target)==false||!IsRendered(target))
{holdProgress.Visibility=planningLabel.Visibility=Visibility.Collapsed;return;}
holdProgress.Visibility=Visibility.Visible;
planningLabel.Text=planningCancellation?"取消中…":"规划中…";
var point=new Point(projected.X,projected.Y);Canvas.SetLeft(holdProgress,point.X-24);Canvas.SetTop(holdProgress,point.Y-24);
Canvas.SetLeft(planningLabel,point.X+30);Canvas.SetTop(planningLabel,point.Y-10);
planningLabel.Visibility=planningCandidate is null?Visibility.Collapsed:Visibility.Visible;
}
internal void BeginPointer(Point point,bool pan)
{
CancelCameraInput();
CancelHold();previous=point;travel=0;panning=pan;dragging=true;holdInvoked=false;mouseGesture=false;mouseButtons=GalaxyMouseButtons.None;suppressPointerSelection=false;
// Freeze the displayed pose before picking. An in-flight focus animation
// must not move a neighbouring star under an already pressed pointer.
cameraTimer.Stop();cameraAnimation=null;
holdCandidate=pan?null:FindAt(point);if(holdCandidate is {} candidate&&!CanPlanRoute&&!HoldingCancelsRoute(candidate))holdCandidate=null;
holdGesture.Begin(point.X,point.Y,MonotonicMilliseconds,holdCandidate is not null);
if(holdCandidate is not null){Selection=holdCandidate;SystemSelected?.Invoke(this,holdCandidate);holdProgress.IsIndeterminate=false;holdProgress.Value=0;holdProgress.IsActive=true;holdProgress.Visibility=Visibility.Visible;UpdateHoldVisual();holdTimer.Start();}
}
internal void MovePointer(Point point)
{
holdGesture.Move(point.X,point.Y);
if(holdGesture.Progress(MonotonicMilliseconds)<=0&&holdCandidate is not null)CancelHold();
var dx=point.X-previous.X;var dy=point.Y-previous.Y;travel+=Math.Abs(dx)+Math.Abs(dy);previous=point;
if(!holdInvoked){if(mouseGesture)ApplyMouseDragDelta(dx,dy,mouseButtons);else ApplyDragDelta(dx,dy,panning);}
}
internal void EndPointer(Point point)
{
var chosen=holdInvoked;dragging=false;CancelHold();if(!chosen&&!panning&&!suppressPointerSelection&&travel<=5)SelectAt(point);mouseGesture=false;mouseButtons=GalaxyMouseButtons.None;FinishCameraInput();if(travel>5)FlushViewport();
}
private void ConfirmHold()
{
if(!dragging||!IsInteractive||holdCandidate is not {} target||!CanPlanRoute&&!HoldingCancelsRoute(target)){CancelHold();return;}
if(vectors is not null&&(sceneDirty||scheduled)){StopScheduling();Draw();}
if(Filter?.Matches(target)==false||!Camera.ProjectForCatalogue(target.Position).IsVisible||!IsRendered(target)){CancelHold();return;}
var now=MonotonicMilliseconds;holdProgress.Value=holdGesture.Progress(now)*100;UpdateHoldVisual();
if(!holdGesture.TryConfirm(now))return;
holdTimer.Stop();holdInvoked=true;planningCandidate=target;planningCancellation=HoldingCancelsRoute(target);Selection=target;SystemSelected?.Invoke(this,target);
holdProgress.IsIndeterminate=true;holdProgress.IsActive=true;holdProgress.Visibility=Visibility.Visible;UpdateHoldVisual();TargetChosen?.Invoke(this,target);
}
private GalacticSystem? FindAt(Point p)
{
if(vectors is not null&&(sceneDirty||scheduled)){StopScheduling();Draw();}
// The selected star owns its visible ring and caption. Otherwise a dot
// behind either can silently replace a search result at long-press time.
if(Selection is {Position.IsValid:true} selected&&Filter?.Matches(selected)!=false&&IsRendered(selected))
{
var pose=Camera.ProjectForCatalogue(selected.Position);var centre=new Point(pose.X,pose.Y);var sx=centre.X-p.X;var sy=centre.Y-p.Y;
if(pose.IsVisible&&sx*sx+sy*sy<=24*24)return selected;
var caption=names.FirstOrDefault(n=>n.Visible&&n.System?.Name.Equals(selected.Name,StringComparison.OrdinalIgnoreCase)==true);
if(pose.IsVisible&&caption is not null&&new Rect(caption.Transform.X,caption.Transform.Y,caption.BoxWidth,caption.BoxHeight).Contains(p))return selected;
}
if(FindWorldMarkerAt(p) is {} markerTarget)return markerTarget;
var best=225d;GalacticSystem? found=null;
// Pick the actual retained stars. Overflow LOD must not make a hidden
// neighbour selectable simply because it exists in the source catalogue.
var camera=Camera;var closestDepth=double.PositiveInfinity;
for(var i=0;i<hitCount;i++){var system=hits[i].System;var at=camera.ProjectForCatalogue(system.Position);if(!at.IsVisible)continue;var dx=at.X-p.X;var dy=at.Y-p.Y;var distance=dx*dx+dy*dy;if(distance<best-.01||Math.Abs(distance-best)<.01&&at.Depth<closestDepth){best=distance;closestDepth=at.Depth;found=system;}}
return found;
}
private bool IsRendered(GalacticSystem system)
{
for(var i=0;i<hitCount;i++)if(hits[i].System.Name.Equals(system.Name,StringComparison.OrdinalIgnoreCase))return true;
return false;
}
internal void SelectAt(Point p)
{
var found=FindAt(p);
if (found is not null) { Selection = found; SystemSelected?.Invoke(this, found); }
else ClearSelection();
}
// Geometric observation only. Catalogue visibility and picking require
// ProjectForCatalogue plus an actually retained rendered-star hit.
internal Point ProjectForProbe(Coordinates p)
{
var projected=Camera.Project(p);return new(projected.X,projected.Y);
}
internal void RenderNowForProbe() { StopScheduling(); EnsureGraphics(); Draw(); }
private sealed record NameLayout(string Display,string Original,double Width,double Height);
private sealed record Sample(GalacticSystem System, double X, double Y, double Z, int Kind,int Spectral,NameLayout Label,StarColour Colour,float RelativeSize,float Opacity,Vector4? OriginalColour,bool LodPriority);
private sealed record LineVisual(CompositionLineGeometry Geometry, CompositionSpriteShape Shape)
{
public void Move(Point a, Point b) { Geometry.Start = new((float)a.X, (float)a.Y); Geometry.End = new((float)b.X, (float)b.Y); }
}
private sealed class StarVisual(CompositionEllipseGeometry geometry, CompositionSpriteShape shape,CompositionEllipseGeometry auraGeometry,CompositionSpriteShape aura)
{ public CompositionEllipseGeometry Geometry = geometry,AuraGeometry=auraGeometry; public CompositionSpriteShape Shape = shape,Aura=aura; public int Kind = -1,Spectral=-1; public bool Visible;public StarColour Colour;public float Opacity=-1; }
private sealed class LabelVisual(StackPanel panel, TextBlock name, TextBlock original, TranslateTransform transform)
{ public StackPanel Panel = panel; public TextBlock Name = name, Original = original; public TranslateTransform Transform = transform; public double BoxWidth, BoxHeight; public bool Visible, Wanted,Query; public GalacticSystem? System; public int Kind = -1;public StarColour Colour; }
}
using System.Diagnostics;
using System.Numerics;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Runtime.CompilerServices;
using Microsoft.UI.Composition;
using Microsoft.UI.Xaml.Hosting;
using Microsoft.UI.Xaml.Input;
using Microsoft.UI.Xaml.Media;
using Windows.Foundation;
using XFEEDToolBox.Core.Galaxy;
using XFEEDToolBox.Core.Models;
using XFEEDToolBox.Core.Navigation;
using XFEEDToolBox.Rendering;
namespace XFEEDToolBox.Controls;
/// <summary>Retained GPU vector map of measured Galactic XYZ coordinates. Pointer input is coalesced per composition frame.</summary>
public sealed partial class GalaxyMapView : UserControl
{
public static readonly DependencyProperty SystemsProperty = DependencyProperty.Register(nameof(Systems), typeof(IReadOnlyList<GalacticSystem>), typeof(GalaxyMapView), new PropertyMetadata(null, Changed));
public static readonly DependencyProperty RouteProperty = DependencyProperty.Register(nameof(Route), typeof(IReadOnlyList<NavWaypoint>), typeof(GalaxyMapView), new PropertyMetadata(null, Changed));
public static readonly DependencyProperty CentreProperty = DependencyProperty.Register(nameof(Centre), typeof(Coordinates), typeof(GalaxyMapView), new PropertyMetadata(null, CentreChanged));
public static readonly DependencyProperty CurrentSystemProperty = DependencyProperty.Register(nameof(CurrentSystem), typeof(string), typeof(GalaxyMapView), new PropertyMetadata("", Changed));
public static readonly DependencyProperty SelectionProperty = DependencyProperty.Register(nameof(Selection), typeof(GalacticSystem), typeof(GalaxyMapView), new PropertyMetadata(null, SelectionChanged));
public static readonly DependencyProperty FilterProperty = DependencyProperty.Register(nameof(Filter), typeof(GalaxyMapFilter), typeof(GalaxyMapView), new PropertyMetadata(null, Changed));
public GalaxyMapFilter? Filter { get => (GalaxyMapFilter?)GetValue(FilterProperty); set => SetValue(FilterProperty, value); }
public static readonly DependencyProperty CatalogueSelectionProperty=DependencyProperty.Register(nameof(CatalogueSelection),typeof(GalaxyCatalogueSelection),typeof(GalaxyMapView),new PropertyMetadata(null,Changed));
public GalaxyCatalogueSelection? CatalogueSelection {get=>(GalaxyCatalogueSelection?)GetValue(CatalogueSelectionProperty);set=>SetValue(CatalogueSelectionProperty,value);}
public static readonly DependencyProperty PointsOfInterestProperty=DependencyProperty.Register(nameof(PointsOfInterest),typeof(IReadOnlyList<GalacticPlace>),typeof(GalaxyMapView),new PropertyMetadata(null,Changed));
public static readonly DependencyProperty PlanningProperty=DependencyProperty.Register(nameof(Planning),typeof(bool),typeof(GalaxyMapView),new PropertyMetadata(false,PlanningChanged));
public static readonly DependencyProperty CanPlanRouteProperty=DependencyProperty.Register(nameof(CanPlanRoute),typeof(bool),typeof(GalaxyMapView),new PropertyMetadata(true));
public IReadOnlyList<GalacticPlace>? PointsOfInterest {get=>(IReadOnlyList<GalacticPlace>?)GetValue(PointsOfInterestProperty);set=>SetValue(PointsOfInterestProperty,value);}
public bool Planning {get=>(bool)GetValue(PlanningProperty);set=>SetValue(PlanningProperty,value);}
public bool CanPlanRoute {get=>(bool)GetValue(CanPlanRouteProperty);set=>SetValue(CanPlanRouteProperty,value);}
public static readonly DependencyProperty PlottedDestinationProperty=DependencyProperty.Register(nameof(PlottedDestination),typeof(long),typeof(GalaxyMapView),new PropertyMetadata(0L,Changed));
public static readonly DependencyProperty CanCancelRouteProperty=DependencyProperty.Register(nameof(CanCancelRoute),typeof(bool),typeof(GalaxyMapView),new PropertyMetadata(false,Changed));
public long PlottedDestination{get=>(long)GetValue(PlottedDestinationProperty);set=>SetValue(PlottedDestinationProperty,value);}
public bool CanCancelRoute{get=>(bool)GetValue(CanCancelRouteProperty);set=>SetValue(CanCancelRouteProperty,value);}
internal bool HoldingCancelsRoute(GalacticSystem target)=>CanCancelRoute&&PlottedDestination>0&&target.SystemAddress==PlottedDestination;
public static readonly DependencyProperty FuelOverlayProperty = DependencyProperty.Register(nameof(FuelOverlay),typeof(NavigationFuelOverlay),typeof(GalaxyMapView),new PropertyMetadata(null,Changed));
public NavigationFuelOverlay? FuelOverlay { get=>(NavigationFuelOverlay?)GetValue(FuelOverlayProperty);set=>SetValue(FuelOverlayProperty,value); }
public IReadOnlyList<GalacticSystem>? Systems { get => (IReadOnlyList<GalacticSystem>?)GetValue(SystemsProperty); set => SetValue(SystemsProperty, value); }
public IReadOnlyList<NavWaypoint>? Route { get => (IReadOnlyList<NavWaypoint>?)GetValue(RouteProperty); set => SetValue(RouteProperty, value); }
public Coordinates? Centre { get => (Coordinates?)GetValue(CentreProperty); set => SetValue(CentreProperty, value); }
public string CurrentSystem { get => (string)GetValue(CurrentSystemProperty); set => SetValue(CurrentSystemProperty, value); }
public GalacticSystem? Selection { get => (GalacticSystem?)GetValue(SelectionProperty); set => SetValue(SelectionProperty, value); }
public bool IsInteractive { get; set; } = true;
public static readonly DependencyProperty ReverseMouseCraneProperty=DependencyProperty.Register(nameof(ReverseMouseCrane),typeof(bool),typeof(GalaxyMapView),new PropertyMetadata(false));
public bool ReverseMouseCrane {get=>(bool)GetValue(ReverseMouseCraneProperty);set=>SetValue(ReverseMouseCraneProperty,value);}
public event EventHandler<GalacticSystem>? SystemSelected;
public event EventHandler<GalacticSystem>? TargetChosen;
public event Action<GalaxyViewport>? ViewportSettled;
public event Action? SelectionCleared;
private readonly StarHoldGesture holdGesture=new();
private readonly Microsoft.UI.Dispatching.DispatcherQueueTimer holdTimer;
private readonly Microsoft.UI.Dispatching.DispatcherQueueTimer viewportTimer;
private readonly GalaxyViewportThrottle viewportThrottle=new();
private GalacticSystem? holdCandidate;
private GalacticSystem? planningCandidate;
private readonly ProgressRing holdProgress=new(){Width=48,Height=48,Minimum=0,Maximum=100,Foreground=Brush(255,174,72),IsIndeterminate=false,IsHitTestVisible=false,Visibility=Visibility.Collapsed};
private readonly TextBlock planningLabel=new(){Text="规划中…",FontSize=12,Foreground=Brush(255,174,72),Visibility=Visibility.Collapsed};
private readonly List<(TextBlock Text,TranslateTransform Position)> placeLabels=[];
private readonly Microsoft.UI.Dispatching.DispatcherQueueTimer cameraTimer;
private readonly Microsoft.UI.Dispatching.DispatcherQueueTimer keyboardTimer;
private readonly HashSet<Windows.System.VirtualKey> cameraKeys=[];
private double lastKeyboardTick;
private (double X,double Y,double Scale,double EndScale,double At)? cameraAnimation;
private bool holdInvoked;
private bool planningCancellation;
private static double MonotonicMilliseconds=>Stopwatch.GetTimestamp()*1000.0/Stopwatch.Frequency;
private const int MaximumStars = GalaxyGraphics.StarCapacity, MaximumLabels = 40;
private readonly Grid host = new() { Background = Brush(10, 20, 32) };
private readonly Canvas labels = new() { IsHitTestVisible = false };
private readonly RectangleGeometry clip = new();
private readonly TextBlock emptyText = new() { Text = "等待真实星系坐标", FontSize = 14, Foreground = Brush(145, 163, 185) };
private Compositor? compositor;
private ContainerVisual? scene;
private GalaxyGraphics? graphics;
private SpriteVisual? pixelsVisual;
private readonly GalaxyStar[] starInstances=new GalaxyStar[MaximumStars];
private readonly GalaxyLineVertex[] lineVertices=new GalaxyLineVertex[GalaxyGraphics.LineVertexCapacity];
private readonly GalaxyOriginalGridLine[] originalGridLines=new GalaxyOriginalGridLine[GalaxyOriginalGrid.MaximumLines];
private long skyCameraChanges;
private (double W,double H,double Yaw,double Pitch) skyCamera;
private ShapeVisual? glows;
private ShapeVisual? vectors;
private CompositionColorBrush[] colors = [];
private CompositionColorBrush[] spectralColours=[];
private CompositionRadialGradientBrush[] spectralGlows=[];
private readonly Dictionary<(StarColour Colour,byte Alpha),CompositionColorBrush> stellarBrushes=[];
private readonly Dictionary<(StarColour Colour,byte Alpha),CompositionRadialGradientBrush> stellarGlows=[];
private readonly SolidColorBrush[] labelColors = [Brush(138, 177, 211), Brush(255, 174, 72), Brush(255, 174, 72), Brush(84, 222, 200)];
private CompositionColorBrush? gridBrush;
private readonly List<LineVisual> grid = [], routes = [];
private readonly List<StarVisual> stars = [];
private readonly List<LabelVisual> names = [];
private CompositionSpriteShape? currentRing, selectedRing;
private Sample[] ordered = [];
private readonly GalaxyMapLod stellarLod=new();
private readonly ConditionalWeakTable<GalacticSystem,NameLayout> nameLayouts=new();
private readonly HashSet<string> regionLabelNames=new(StringComparer.OrdinalIgnoreCase);
private NavWaypoint[] cachedRoute = [];
private HashSet<long> dashedLegs=[],supplySites=[];
private readonly List<(TextBlock Text,TranslateTransform Position)> supplyLabels=[];
private readonly (Point Point, GalacticSystem System)[] hits = new (Point, GalacticSystem)[MaximumStars];
private readonly Rect[] labelRects = new Rect[MaximumLabels];
private int hitCount;
private bool loaded, pageActive = true, scheduled, sceneDirty = true, dragging, panning;
private GalaxyMouseButtons mouseButtons;
private bool mouseGesture, suppressPointerSelection;
private double yaw = -.3, pitch = .45, scale = 4, panX, panY, travel;
private Point previous;
public long FrameCount { get; private set; }
public long SceneRebuilds { get; private set; }
public int VectorNodesCreated { get; private set; }
public int TextNodesCreated => names.Count * 2 + 1;
public double LastFrameMilliseconds { get; private set; }
internal int VisibleStars => hitCount;
internal int CandidateStars {get;private set;}
internal bool StellarLodActive {get;private set;}
internal int StellarLodOccupiedCells {get;private set;}
internal int VisibleNameLabels=>names.Count(n=>n.Visible);
internal int VisibleLinkSegments {get;private set;}
internal int VisibleRouteSegments {get;private set;}
internal int VisibleGridConnectors {get;private set;}
internal double HoldProgress=>holdProgress.Value;
internal bool ShowsPlanning=>planningCandidate is not null&&holdProgress.Visibility==Visibility.Visible&&holdProgress.IsIndeterminate;
internal bool ShowsHold=>holdProgress.Visibility==Visibility.Visible;
internal long SkyboxRebuilds=>skyCameraChanges;
internal string MapGraphicsBackend=>graphics is null?"Composition vectors":"Direct3D 11 · instanced stars";
internal string GraphicsError { get; private set; }="";
internal int GraphicsDrawCalls=>graphics?.DrawCalls??0;
internal int VisibleNebulae=>graphics?.VisibleNebulae??0;
internal int PendingNebulaLoads=>graphics?.PendingNebulaLoads??0;
internal int ResidentNebulaTextures=>graphics?.ResidentNebulaTextures??0;
internal bool GalaxyDensityReady=>graphics?.Overview is not null;
internal long NebulaGpuBytes=>graphics?.NebulaGpuBytes??0;
internal void EnableNebulaeForProbe(bool value){if(graphics is not null)graphics.NebulaeEnabled=value;Invalidate();}
internal (int Width,int Height,byte[] Pixels) CapturePixelsForProbe()=>graphics?.ReadPixels()??throw new InvalidOperationException(GraphicsError);
internal async Task<IDisposable> FreezeForXamlProbeAsync()
{
RenderNowForProbe();var frame=CapturePixelsForProbe();
var bitmap=new Microsoft.UI.Xaml.Media.Imaging.WriteableBitmap(frame.Width,frame.Height);
using(var stream=bitmap.PixelBuffer.AsStream())await stream.WriteAsync(frame.Pixels);bitmap.Invalidate();
var snapshot=new Image{Source=bitmap,Stretch=Stretch.Fill,IsHitTestVisible=false};
ElementCompositionPreview.SetElementChildVisual(host,null);host.Children.Add(snapshot);
return new MapSnapshotScope(()=>{host.Children.Remove(snapshot);ElementCompositionPreview.SetElementChildVisual(host,scene);Invalidate();});
}
private sealed class MapSnapshotScope(Action restore):IDisposable{public void Dispose()=>restore();}
internal string SkyboxSource=>graphics?.SkyboxSource??"";
internal int GridLinesVisible { get; private set; }
internal int GlowingStars=>hitCount;
internal bool QueryBackgroundStarsSuppressed=>Filter?.IsQueryActive==true&&graphics?.UnresolvedStarBackgroundEnabled!=true;
internal bool VisibleModelsMatchFilter=>ordered.All(s=>Filter?.Matches(s.System)!=false);
internal int FilteredModels=>ordered.Length;
internal GalaxyViewport RequestedViewportForProbe=>Camera.ToViewport();
internal void FlushViewportForProbe()=>FlushViewport();
internal long ViewportNotifications {get;private set;}
internal (double Yaw, double Pitch, double Scale, double PanX, double PanY) CameraState => (yaw, pitch, scale, panX, panY);
private static SolidColorBrush Brush(byte r, byte g, byte b) => new(Windows.UI.Color.FromArgb(255, r, g, b));
public GalaxyMapView()
{
holdTimer=DispatcherQueue.CreateTimer();holdTimer.Interval=TimeSpan.FromMilliseconds(16);holdTimer.IsRepeating=true;
holdTimer.Tick+=(_,_)=>ConfirmHold();
cameraTimer=DispatcherQueue.CreateTimer();cameraTimer.Interval=TimeSpan.FromMilliseconds(16);cameraTimer.Tick+=(_,_)=>AnimateCamera();
cameraMotionTimer=DispatcherQueue.CreateTimer();cameraMotionTimer.Interval=TimeSpan.FromMilliseconds(16);cameraMotionTimer.Tick+=(_,_)=>AdvanceCameraMotion();
keyboardTimer=DispatcherQueue.CreateTimer();keyboardTimer.Interval=TimeSpan.FromMilliseconds(16);keyboardTimer.Tick+=(_,_)=>UpdateKeyboardCamera();
viewportTimer=DispatcherQueue.CreateTimer();viewportTimer.Interval=TimeSpan.FromMilliseconds(200);viewportTimer.IsRepeating=false;
viewportTimer.Tick+=(_,_)=>PublishPendingViewport();
var root = new Grid { Clip = clip }; root.Children.Add(host); root.Children.Add(labels); Content = root;
labels.Children.Add(emptyText);
labels.Children.Add(holdProgress);labels.Children.Add(planningLabel);
ManipulationMode = ManipulationModes.None;
Loaded += (_, _) => { loaded = true; EnsureGraphics(); Resize(); Invalidate();ScheduleViewport(); };
Unloaded += (_, _) => { loaded = false; StopScheduling(); StopOriginalFrameFade();CancelCameraInput();viewportTimer.Stop();viewportThrottle.Reset(); };
SizeChanged += (_, _) => { Resize(); Invalidate();ScheduleViewport(); };
PointerPressed += Pressed; PointerMoved += Moved; PointerReleased += Released;
PointerCanceled += (_, _) => {var moving=dragging;if(moving)CancelCameraInput();if(moving)FlushViewport();};PointerCaptureLost += (_, _) => {var moving=dragging;if(moving)CancelCameraInput();if(moving)FlushViewport();};
IsTabStop=true;
KeyDown+=CameraKeyDown;
KeyUp+=(_,e)=>{if(cameraKeys.Remove(e.Key)){e.Handled=true;FinishCameraInput();if(cameraKeys.Count==0){keyboardTimer.Stop();FlushViewport();}}};
LostFocus+=(_,_)=>{CancelCameraInput();FlushViewport();};
DoubleTapped+=(_,e)=>{if(IsInteractive&&FindAt(e.GetPosition(this)) is {} selected){FocusSystem(selected);e.Handled=true;}};
PointerWheelChanged += (_, e) =>
{
if (!IsInteractive) return;
var point = e.GetCurrentPoint(this); ApplyOriginalWheelInput(point.Properties.MouseWheelDelta); e.Handled = true;
};
Microsoft.UI.Xaml.Automation.AutomationProperties.SetName(this, "银河星图:点击选择,双击聚焦;左键旋转,右键水平偏航与垂直升降,双键平面移动,滚轮缩放;WASD 平面移动,R/F 升降,T/G 俯仰,Q/E 偏航,Z/X 缩放,Home 返回导航中心,Esc 取消选择;长按恒星规划航线");
}
private void EnsureGraphics()
{
if (vectors is not null) return;
compositor = ElementCompositionPreview.GetElementVisual(host).Compositor;
scene=compositor.CreateContainerVisual();glows=compositor.CreateShapeVisual();
vectors = compositor.CreateShapeVisual();
try
{
graphics=new(compositor);graphics.ResourcesChanged+=Invalidate;pixelsVisual=compositor.CreateSpriteVisual();pixelsVisual.RelativeSizeAdjustment=Vector2.One;
var surface=compositor.CreateSurfaceBrush(graphics.Surface);surface.Stretch=CompositionStretch.Fill;pixelsVisual.Brush=surface;scene.Children.InsertAtBottom(pixelsVisual);
}
catch(Exception error){GraphicsError=error.ToString();App.Runtime.Log("星图渲染",error.Message);graphics?.Dispose();graphics=null;}
scene.Children.InsertAtTop(glows);scene.Children.InsertAtTop(vectors);
colors = [compositor.CreateColorBrush(Windows.UI.Color.FromArgb(255, 138, 177, 211)), compositor.CreateColorBrush(Windows.UI.Color.FromArgb(255, 255, 174, 72)), compositor.CreateColorBrush(Windows.UI.Color.FromArgb(255, 255, 174, 72)), compositor.CreateColorBrush(Windows.UI.Color.FromArgb(255, 84, 222, 200))];
var gridSource=GalaxyOriginalGrid.Colour;var gridColour=gridSource.DisplayColour();
gridBrush = compositor.CreateColorBrush(Windows.UI.Color.FromArgb((byte)Math.Round(gridSource.A*255),gridColour.R,gridColour.G,gridColour.B));
spectralColours=StellarAppearance.Palette.Select(c=>compositor.CreateColorBrush(Windows.UI.Color.FromArgb(255,c.R,c.G,c.B))).ToArray();
spectralGlows=StellarAppearance.Palette.Select(c=>GalaxySkybox.Radial(compositor,Windows.UI.Color.FromArgb(145,c.R,c.G,c.B))).ToArray();
for(var i=0;i<StellarAppearance.Palette.Count;i++){stellarBrushes[(StellarAppearance.Palette[i],255)]=spectralColours[i];stellarGlows[(StellarAppearance.Palette[i],145)]=spectralGlows[i];}
if(graphics is null)for (var i = 0; i < InfiniteGalaxyGrid.MaximumLines; i++) grid.Add(CreateLine(gridBrush, 1));
currentRing = CreateRing(colors[3]); selectedRing = CreateRing(colors[2]);
ElementCompositionPreview.SetElementChildVisual(host, scene);
}
private LineVisual CreateLine(CompositionBrush color, float width, int at = -1)
{
var geometry = compositor!.CreateLineGeometry(); var shape = compositor.CreateSpriteShape(geometry);
shape.StrokeBrush = color; shape.StrokeThickness = width; if (at < 0) vectors!.Shapes.Add(shape); else vectors!.Shapes.Insert(at, shape); VectorNodesCreated++;
return new(geometry, shape);
}
private CompositionSpriteShape CreateRing(CompositionBrush color)
{
var geometry = compositor!.CreateEllipseGeometry(); geometry.Radius = new(14, 14);
var shape = compositor.CreateSpriteShape(geometry); shape.StrokeBrush = color; shape.StrokeThickness = 1; shape.Scale = Vector2.Zero;
vectors!.Shapes.Add(shape); VectorNodesCreated++; return shape;
}
private void Resize()
{
clip.Rect = new Rect(0, 0, Math.Max(0, ActualWidth), Math.Max(0, ActualHeight));
if (vectors is not null) vectors.Size = new((float)ActualWidth, (float)ActualHeight);
if(scene is not null)scene.Size=glows!.Size=new((float)ActualWidth,(float)ActualHeight);
Canvas.SetLeft(emptyText, Math.Max(16, ActualWidth / 2 - 65)); Canvas.SetTop(emptyText, ActualHeight / 2);
}
private static void Changed(DependencyObject d, DependencyPropertyChangedEventArgs e) { var view = (GalaxyMapView)d; view.sceneDirty = true; view.Invalidate(); }
private static void SelectionChanged(DependencyObject d,DependencyPropertyChangedEventArgs e)
{
var view=(GalaxyMapView)d;
if(view.holdCandidate is {} held&&e.NewValue is GalacticSystem changed&&
(!held.Name.Equals(changed.Name,StringComparison.OrdinalIgnoreCase)||held.SystemAddress!=changed.SystemAddress))view.CancelHold();
if(e.NewValue is null)view.CancelHold();
view.SelectionFloorChanged(e.NewValue as GalacticSystem);
// Selecting a marker must not move the camera or move a neighbour under
// the pointer. Explicit search/double-click performs the focus motion.
view.sceneDirty=true;view.Invalidate();view.ScheduleViewport();
}
private static void PlanningChanged(DependencyObject d,DependencyPropertyChangedEventArgs e)
{
var view=(GalaxyMapView)d;
if((bool)e.NewValue){view.planningCandidate??=view.Selection;view.planningCancellation=view.PlottedDestination>0&&view.planningCandidate?.SystemAddress==view.PlottedDestination;view.holdProgress.IsIndeterminate=true;view.holdProgress.IsActive=true;}
else{view.planningCandidate=null;view.holdProgress.IsActive=false;view.holdProgress.Visibility=view.planningLabel.Visibility=Visibility.Collapsed;}
view.Invalidate();
}
private static void CentreChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var view = (GalaxyMapView)d;if(!view.applyingCameraPose){view.CancelCameraInput();view.panX=view.panY=0;view.ResetFloorSelector();}view.Invalidate();view.ScheduleViewport(); }
public void ResumePage() { pageActive = true; Invalidate();ScheduleViewport(); }
public void SuspendPage() { pageActive = false;StopOriginalFrameFade();CancelCameraInput();StopScheduling();viewportTimer.Stop();viewportThrottle.Reset(); }
private void Invalidate()
{
if (scheduled || !loaded || !pageActive) return;
scheduled = true; CompositionTarget.Rendering += RenderFrame;
}
private void StopScheduling() { if (!scheduled) return; CompositionTarget.Rendering -= RenderFrame; scheduled = false; }
private void RenderFrame(object? sender, object e) { StopScheduling(); if (loaded && pageActive) Draw(); }
// Explicit application reset, independent of the original game's optional
// saved camera pose (not imported here).
public void ResetCamera() { CancelCameraInput();yaw = -.3; pitch = .45; scale = 4; panX = panY = 0; Invalidate();ScheduleViewport(); }
public void ClearSelection(){CancelCameraInput();Selection=null;SelectionCleared?.Invoke();Invalidate();}
public void FocusSystem(GalacticSystem system,bool zoom=true)
{
if(!system.Position.IsValid)return;
CancelCameraInput();
Selection=system;SystemSelected?.Invoke(this,system);
if(Centre!=system.Position){Centre=system.Position;sceneDirty=true;}
cameraAnimation=(panX,panY,scale,zoom?Math.Clamp(Math.Max(6,scale*2),.001,1000):scale,MonotonicMilliseconds);cameraTimer.Start();
}
private void AnimateCamera()
{
if(cameraAnimation is not {} a){cameraTimer.Stop();return;}
var t=Math.Clamp((MonotonicMilliseconds-a.At)/260,0,1);var eased=1-Math.Pow(1-t,3);
panX=a.X*(1-eased);panY=a.Y*(1-eased);scale=a.Scale+(a.EndScale-a.Scale)*eased;Invalidate();ScheduleViewport();
if(t>=1){cameraAnimation=null;cameraTimer.Stop();FlushViewport();}
}
public void RefreshDisplay(){Invalidate();ScheduleViewport();}
private GalaxyCamera Camera
{
get
{
var camera=GalaxyCamera.Create(Centre??new(0,0,0),Math.Max(1,ActualWidth),Math.Max(1,ActualHeight),yaw,pitch,scale,panX,panY);
return CatalogueSelection?.ApplyTo(camera)??camera;
}
}
private static bool IsCameraKey(Windows.System.VirtualKey key)=>key is Windows.System.VirtualKey.W or Windows.System.VirtualKey.S or Windows.System.VirtualKey.A or Windows.System.VirtualKey.D
or Windows.System.VirtualKey.R or Windows.System.VirtualKey.F or Windows.System.VirtualKey.T or Windows.System.VirtualKey.G or Windows.System.VirtualKey.Q or Windows.System.VirtualKey.E
or Windows.System.VirtualKey.Z or Windows.System.VirtualKey.X;
private void CameraKeyDown(object sender,KeyRoutedEventArgs e)
{
if(!IsInteractive)return;
if(e.Key==Windows.System.VirtualKey.Escape){ClearSelection();e.Handled=true;return;}
if(e.Key==Windows.System.VirtualKey.Home){ReturnCameraHome();e.Handled=true;return;}
if(!IsCameraKey(e.Key))return;
cameraTimer.Stop();cameraAnimation=null;CancelHold();
if(cameraKeys.Add(e.Key)&&cameraKeys.Count==1){lastKeyboardTick=MonotonicMilliseconds;keyboardTimer.Start();}
e.Handled=true;
}
private void StopKeyboard(){var moving=cameraKeys.Count>0;cameraKeys.Clear();keyboardTimer.Stop();if(moving){FinishCameraInput();FlushViewport();}}
private void UpdateKeyboardCamera()
{
if(!IsInteractive||!loaded||!pageActive||cameraKeys.Count==0){StopKeyboard();return;}
var now=MonotonicMilliseconds;var seconds=Math.Clamp((now-lastKeyboardTick)/1000,0,.05);lastKeyboardTick=now;
ApplyKeyboardForProbe(seconds,cameraKeys);
}
internal void ApplyKeyboardForProbe(double seconds,IReadOnlySet<Windows.System.VirtualKey> keys)
{
ApplyOriginalKeyboardInput(seconds,keys);
}
public void ShowGalaxyOverview()
{
var map=graphics?.Overview;if(map is null)return;
CancelCameraInput();
Centre=new(map.ExtentX/2-map.OriginX,0,map.ExtentZ/2-map.OriginZ);yaw=-.08;pitch=1.15;panX=panY=0;
scale=Math.Min(Math.Max(80,ActualWidth-100)/map.ExtentX,Math.Max(80,ActualHeight-100)/(map.ExtentZ*Math.Abs(Math.Sin(pitch))))*.65;Invalidate();ScheduleViewport();
}
private void ScheduleViewport()
{
if(!pageActive||!loaded)return;
viewportThrottle.Changed();
// Repeated input leaves the deadline intact; a debounce that restarts on
// every pointer delta starves catalogue loads throughout a long drag.
if(!viewportTimer.IsRunning){viewportTimer.Interval=TimeSpan.FromMilliseconds(Math.Max(1,viewportThrottle.Delay(MonotonicMilliseconds)));viewportTimer.Start();}
}
private void PublishPendingViewport()
{
if(viewportThrottle.TryPublish(MonotonicMilliseconds))PublishViewport();
if(viewportThrottle.Pending&&pageActive&&loaded){viewportTimer.Interval=TimeSpan.FromMilliseconds(Math.Max(1,viewportThrottle.Delay(MonotonicMilliseconds)));viewportTimer.Start();}
}
private void FlushViewport()
{
viewportTimer.Stop();if(!pageActive||!loaded)return;
viewportThrottle.Changed();if(viewportThrottle.TryPublish(MonotonicMilliseconds,true))PublishViewport();
}
private void PublishViewport()
{
if(!pageActive||!loaded||scale<=0||ActualWidth<1||ActualHeight<1)return;
ViewportNotifications++;ViewportSettled?.Invoke(Camera.ToViewport());
}
public void Zoom(double factor) => ZoomAt(factor, new(ActualWidth / 2, ActualHeight / 2));
public void FitRoute(double rightInset=0)
{
var route=Route;if(route is null||route.Count<2||ActualWidth<1||ActualHeight<1)return;
var points=route.Select(w=>w.Position).Where(p=>p.IsValid).ToArray();if(points.Length<2)return;
CancelCameraInput();
Centre=new((points.Min(p=>p.X)+points.Max(p=>p.X))/2,(points.Min(p=>p.Y)+points.Max(p=>p.Y))/2,(points.Min(p=>p.Z)+points.Max(p=>p.Z))/2);
rightInset=Math.Clamp(rightInset,0,ActualWidth*.55);
var span=Math.Max(10,Math.Max(points.Max(p=>p.X)-points.Min(p=>p.X),Math.Max(points.Max(p=>p.Y)-points.Min(p=>p.Y),points.Max(p=>p.Z)-points.Min(p=>p.Z))));
scale=Math.Clamp(Math.Min(ActualWidth-rightInset-80,ActualHeight-160)/span,.001,1000);panX=-rightInset/2;panY=0;
for(var attempt=0;attempt<40;attempt++)
{
var camera=Camera;
if(points.All(p=>{var at=camera.Project(p);return at.IsVisible&&at.X>=36&&at.X<=ActualWidth-rightInset-36&&at.Y>=50&&at.Y<=ActualHeight-75;}))break;
scale=Math.Max(.001,scale*.8);
}
Invalidate();ScheduleViewport();
}
private void ZoomAt(double factor, Point anchor)
{
if (!double.IsFinite(factor) || factor <= 0) return;
if(!pageActive)return;
ZoomCameraTarget(factor,anchor);
}
internal void ApplyDragDelta(double dx, double dy, bool pan)
{
if (!IsInteractive||!pageActive) return;
var target=EnsureCameraTarget();
if(pan)target=target with{Focus=TargetCamera(target).Pan(dx,dy)};
else target=target with{Yaw=target.Yaw+dx*.006,Pitch=target.Pitch+dy*.006};
SetCameraTarget(target,pan||CameraCraneActive,pan?1:0);
}
internal void ApplyMouseDragDelta(double dx,double dy,GalaxyMouseButtons buttons)
{
ApplyOriginalMouseInput(dx,dy,buttons);
}
private void RebuildScene()
{
sceneDirty = false; SceneRebuilds++;
var centre = Centre; var cx = centre?.X ?? 0; var cy = centre?.Y ?? 0; var cz = centre?.Z ?? 0;
cachedRoute = (Route ?? []).ToArray(); var routeNames = cachedRoute.Select(w => w.Name).ToHashSet(StringComparer.OrdinalIgnoreCase);
dashedLegs=(FuelOverlay?.DashedLegs??[]).ToHashSet();supplySites=(FuelOverlay?.SupplySites??[]).ToHashSet();
ordered = (Systems ?? []).Where(s => s.Position.IsValid&&Filter?.Matches(s)!=false&&CatalogueSelection?.Contains(s)!=false).Select(s =>
{
var kind = s.Name.Equals(CurrentSystem, StringComparison.OrdinalIgnoreCase) ? 3 : s.Name.Equals(Selection?.Name, StringComparison.OrdinalIgnoreCase) ? 2 : routeNames.Contains(s.Name) ? 1 : 0;
var name=nameLayouts.GetValue(s,static system=>
{
var display=system.DisplayName;var original=display==system.Name?"":system.Name;
return new(display,original,Math.Max(60,Math.Max(system.Name.Length*7,display.Length*12)),original.Length>0?32:18);
});
if(Filter is {Category:GalaxyFilterCategory.Markers,Values.Count:1} regionFilter&®ionFilter.Values.Contains("galacticregion"))
{
var display=regionFilter.LabelFor(s);
name=new(display,"",Math.Max(60,display.Length*12),18);
}
var spectral=StellarAppearance.ColourIndex(s.StarClass);var colour=Filter?.GetColour(s)??StellarAppearance.Palette[spectral];
var realistic=Filter is null||Filter.Mode==GalaxyMapMode.Realistic;
var opacity=Filter?.GetOpacity(s)??1;
if(realistic&&s.OriginalAppearance is {} original)
{var rgba=original.RealisticRgba??original.TypeRgba;colour=GalaxyOriginalStellarAppearance.Colour(rgba);opacity*=((rgba>>24)&255)/255f;}
var relative=realistic?CurrentOriginalSize(s) is{} actualSize?actualSize>0?1:0:StellarAppearance.PhysicalRadius(s.StarClass):Filter!.RelativeSize(s);
return new Sample(s, s.Position.X - cx, s.Position.Y - cy, s.Position.Z - cz, kind,spectral,name,colour,relative,opacity,Filter?.GetOriginalRgba(s),GalaxyMapLod.IsPriority(s,CatalogueSelection,true,kind>0));
}).Where(s=>s.RelativeSize>0&&s.Opacity>0&&s.OriginalColour is not{W:<=0})
.OrderByDescending(s => s.Kind).ThenByDescending(s=>s.LodPriority).ThenBy(s => s.X * s.X + s.Y * s.Y + s.Z * s.Z).ToArray();
floorCandidates=ordered.Select(s=>new GalaxyFloorCandidate(s.System.SystemAddress,s.System.Position)).ToArray();
RebuildConstellations();
while (graphics is null&&stars.Count < Math.Min(1800, ordered.Length))
{
var geometry = compositor!.CreateEllipseGeometry(); geometry.Radius = new(2.2f, 2.2f);
var shape = compositor.CreateSpriteShape(geometry); shape.FillBrush = colors[0]; shape.Scale = Vector2.Zero;
var auraGeometry=compositor.CreateEllipseGeometry();auraGeometry.Radius=new(15,15);
var aura=compositor.CreateSpriteShape(auraGeometry);aura.FillBrush=spectralGlows[13];aura.Scale=Vector2.Zero;glows!.Shapes.Add(aura);
vectors!.Shapes.Insert(InfiniteGalaxyGrid.MaximumLines + routes.Count + stars.Count, shape); stars.Add(new(geometry, shape,auraGeometry,aura)); VectorNodesCreated+=2;
}
while (graphics is null&&routes.Count < Math.Max(0, cachedRoute.Length - 1)) routes.Add(CreateLine(colors[1], 2, InfiniteGalaxyGrid.MaximumLines + routes.Count));
for (var i = 0; i < routes.Count; i++)
{
routes[i].Shape.Scale = i < cachedRoute.Length - 1 ? Vector2.One : Vector2.Zero;
routes[i].Shape.StrokeDashArray.Clear();
if(i<cachedRoute.Length-1&&dashedLegs.Contains(cachedRoute[i+1].SystemAddress)){routes[i].Shape.StrokeDashArray.Add(6);routes[i].Shape.StrokeDashArray.Add(4);}
}
while(supplyLabels.Count<Math.Min(24,supplySites.Count))
{
var position=new TranslateTransform();var text=new TextBlock{FontSize=11,Foreground=labelColors[3],RenderTransform=position,Opacity=0};
labels.Children.Add(text);supplyLabels.Add((text,position));
}
while(placeLabels.Count<Math.Min(20,PointsOfInterest?.Count??0))
{
var position=new TranslateTransform();var text=new TextBlock{FontSize=12,FontWeight=Microsoft.UI.Text.FontWeights.SemiBold,Foreground=labelColors[1],RenderTransform=position,Opacity=0};
labels.Children.Add(text);placeLabels.Add((text,position));
}
while (names.Count < Math.Min(MaximumLabels, ordered.Length))
{
var text = new TextBlock { FontSize = 11, Foreground = Brush(138, 177, 211) };
var original = new TextBlock { FontSize = 9, Foreground = Brush(145, 163, 185) };
var panel = new StackPanel { Opacity = 0, RenderTransform = new TranslateTransform() };
panel.Children.Add(text); panel.Children.Add(original); labels.Children.Add(panel); names.Add(new(panel, text, original, (TranslateTransform)panel.RenderTransform));
}
RebuildWorldMarkers();
emptyText.Text=(Systems?.Count??0)>0?"当前筛选条件下没有星系":"等待真实星系坐标";
emptyText.Opacity = ordered.Length == 0 ? 1 : 0;
}
private void Draw()
{
var viewWidth=ActualWidth;var viewHeight=ActualHeight;
if (vectors is null || viewWidth < 1 || viewHeight < 1) return;
var started = Stopwatch.GetTimestamp(); if (sceneDirty) RebuildScene();
var camera=Camera;
PrepareOriginalFrameFade();FrameFadedStarsForProbe=0;
var renderCapacity=graphics is null?1800:MaximumStars;
var useLod=ordered.Length>renderCapacity;
StellarLodActive=false;StellarLodOccupiedCells=0;CandidateStars=0;
if(useLod)
{
stellarLod.Begin(viewWidth,viewHeight,renderCapacity);
foreach(var sample in ordered){if(PointFrameOpacity(sample)<=0)continue;var at=camera.ProjectForCatalogue(sample.System.Position);if(at.IsVisible)stellarLod.Count(at.X,at.Y,sample.LodPriority);}
stellarLod.Seal();CandidateStars=stellarLod.Candidates;StellarLodActive=stellarLod.Active;StellarLodOccupiedCells=stellarLod.OccupiedCells;
}
if(graphics is not null&&skyCamera!=(viewWidth,viewHeight,yaw,pitch)){skyCamera=(viewWidth,viewHeight,yaw,pitch);skyCameraChanges++;}
var lineCount=0;
void GpuLine(Point a,Point b,Vector4 colour,bool dashed=false)
{
if(lineCount+2>lineVertices.Length)return;
// Skip wholly invisible edges before upload. The hardware clips the rest.
if(a.X<0&&b.X<0||a.Y<0&&b.Y<0||a.X>viewWidth&&b.X>viewWidth||a.Y>viewHeight&&b.Y>viewHeight)return;
var length=Math.Sqrt((b.X-a.X)*(b.X-a.X)+(b.Y-a.Y)*(b.Y-a.Y));if(length<.3)return;
lineVertices[lineCount++]=new(new((float)a.X,(float)a.Y),0,dashed?1:0,colour);
lineVertices[lineCount++]=new(new((float)b.X,(float)b.Y),(float)length,dashed?1:0,colour);
}
Span<MapSegment> segments=stackalloc MapSegment[InfiniteGalaxyGrid.MaximumLines];
GridLinesVisible=Filter?.ShowGrid==false?0:GalaxyMapGeometry.WriteOriginalGrid(segments,camera,out var step);
if(graphics is not null)
{
var originalCount=Filter?.ShowGrid==false?0:GalaxyOriginalGrid.Write(originalGridLines,camera.Focus,camera.Distance);
graphics.SetOriginalGrid(originalGridLines.AsSpan(0,originalCount));
}
for (var i = 0; i < grid.Count; i++)
{
grid[i].Shape.Scale=graphics is null&&i<GridLinesVisible?Vector2.One:Vector2.Zero;
if(i<GridLinesVisible){var line=segments[i];grid[i].Move(new(line.X1,line.Y1),new(line.X2,line.Y2));}
}
var floorCount=WriteFloorSelector(segments,camera);
if(graphics is not null)for(var i=0;i<floorCount;i++){var line=segments[i];GpuLine(new(line.X1,line.Y1),new(line.X2,line.Y2),new(.05f,.72f,.86f,.8f));}
else
{
while(floorLines.Count<floorCount)floorLines.Add(CreateLine(compositor!.CreateColorBrush(Windows.UI.Color.FromArgb(204,13,184,219)),1.2f));
for(var i=0;i<floorLines.Count;i++){floorLines[i].Shape.Scale=i<floorCount?Vector2.One:Vector2.Zero;if(i<floorCount){var line=segments[i];floorLines[i].Move(new(line.X1,line.Y1),new(line.X2,line.Y2));}}
}
var centre = Centre; var cx = centre?.X ?? 0; var cy = centre?.Y ?? 0; var cz = centre?.Z ?? 0;
VisibleLinkSegments=VisibleRouteSegments=VisibleGridConnectors=0;
DrawConstellations(camera,ref lineCount);
if(Filter is {ShowLinks:true} filter)
{
var origin=Systems?.FirstOrDefault(s=>s.Name.Equals(CurrentSystem,StringComparison.OrdinalIgnoreCase))??Selection;
if(origin is not null)
{
var linkLimit=Math.Max(0,(lineVertices.Length-lineCount-Math.Min(cachedRoute.Length*2,lineVertices.Length/4)-8192)/2);
foreach(var sample in ordered)
{
if(VisibleLinkSegments>=linkLimit)break;
if(sample.System.Name==origin.Name||sample.System.Position.DistanceTo(origin.Position)>filter.JumpRange)continue;
if(GalaxyMapGeometry.TryProjectSegment(camera,origin.Position,sample.System.Position,out var link))
{GpuLine(new(link.X1,link.Y1),new(link.X2,link.Y2),new(.13f,.56f,.62f,.22f));VisibleLinkSegments++;}
}
}
}
if(graphics is null)foreach(var route in routes)route.Shape.Scale=Vector2.Zero;
for (var i = 1; i < cachedRoute.Length&&Filter?.ShowRoute!=false; i++)
{
var a = cachedRoute[i - 1].Position; var b = cachedRoute[i].Position;
if(!GalaxyMapGeometry.TryProjectSegment(camera,a,b,out var segment))continue;
VisibleRouteSegments++;
var from=new Point(segment.X1,segment.Y1);var to=new Point(segment.X2,segment.Y2);
if(graphics is null){routes[i-1].Move(from,to);routes[i-1].Shape.Scale=Vector2.One;}else GpuLine(from,to,new(1,.67f,.26f,.88f),dashedLegs.Contains(cachedRoute[i].SystemAddress));
}
DrawHistoricalTradeFlows(camera,ref lineCount);
hitCount = 0; var labelCount = 0; currentRing!.Scale = selectedRing!.Scale = Vector2.Zero;
regionLabelNames.Clear();
var regionLabels=Filter is {Category:GalaxyFilterCategory.Markers,Values.Count:1} regionFilter&®ionFilter.Values.Contains("galacticregion");
for (var i = 0; i < names.Count; i++) names[i].Wanted = false;
for (var index = 0; index < ordered.Length; index++)
{
var s = ordered[index];var projected=camera.ProjectForCatalogue(s.System.Position);if(!projected.IsVisible)continue;
var frameOpacity=PointFrameOpacity(s);if(frameOpacity<=0){FrameFadedStarsForProbe++;continue;}
var p = new Point(projected.X,projected.Y);
if(useLod&&!stellarLod.Accept(p.X,p.Y,s.LodPriority))continue;
if (hitCount == renderCapacity) break;
if(graphics is not null&&Filter is {ShowGridStalks:true,ShowGrid:true}&&VisibleGridConnectors<4000
&&GalaxyMapGeometry.TryProjectStalk(camera,s.System.Position,out var stalk))
{GpuLine(new(stalk.X1,stalk.Y1),new(stalk.X2,stalk.Y2),new(.2f,.42f,.49f,.12f));VisibleGridConnectors++;}
if(graphics is not null)
{
var colour=s.Colour;
var kind=Filter?.ShowMarkers==false||s.Kind==1&&Filter?.ShowRoute==false?0:s.Kind;
var realistic=Filter is null||Filter.Mode==GalaxyMapMode.Realistic;
var sprite=realistic&&s.System.OriginalAppearance is {} original?StellarAppearance.OriginalSprite(original.Classification):Filter?.SpriteLayerFor(s.System)??13;
var originalColour=s.OriginalColour is{} sourceColour?sourceColour with{W=sourceColour.W*frameOpacity}:(Vector4?)null;
starInstances[hitCount]=new(new((float)p.X,(float)p.Y),s.RelativeSize,kind,new(colour.R/255f,colour.G/255f,colour.B/255f,s.Opacity*frameOpacity),new((float)s.System.Position.X,(float)s.System.Position.Y,(float)s.System.Position.Z,s.Spectral+1),realistic?CurrentOriginalSize(s.System)??0:0,Filter is {UsesPowerTerritory:true}&&Filter.PowerTerritoryStyle(s.System) is not null,sprite,originalColour,
realistic&&s.System.OriginalAppearance is{} source&&XFEEDToolBox.Core.Rendering.GalaxyOriginalBlackHole.IsSpecial(source.Classification));
}
else
{
var dot = stars[hitCount]; dot.Shape.Offset = new((float)p.X, (float)p.Y);
dot.Aura.Offset=dot.Shape.Offset;
if (!dot.Visible) { dot.Shape.Scale = dot.Aura.Scale=Vector2.One; dot.Visible = true; }
var realistic=Filter is null||Filter.Mode==GalaxyMapMode.Realistic;
var dx=s.System.Position.X-camera.Focus.X;var dy=s.System.Position.Y-camera.Focus.Y;var dz=s.System.Position.Z-camera.Focus.Z;
var profile=StellarAppearance.Sprite(s.Spectral,Math.Sqrt(dx*dx+dy*dy+dz*dz),projected.Scale,s.Kind,realistic,CurrentOriginalSize(s.System)??0);
var relativeSize=s.RelativeSize;
if(!realistic&&Filter is {UsesPowerTerritory:true}&&Filter.PowerTerritoryStyle(s.System) is not null)
{var ex=s.System.Position.X-camera.Eye.X;var ey=s.System.Position.Y-camera.Eye.Y;var ez=s.System.Position.Z-camera.Eye.Z;relativeSize*=StellarAppearance.PowerTerritoryDistanceScale(Math.Sqrt(ex*ex+ey*ey+ez*ez));}
var radius=profile.CoreRadius*relativeSize;
dot.Geometry.Radius=new(radius,radius);dot.AuraGeometry.Radius=new(radius*5,radius*5);dot.Aura.Scale=realistic?Vector2.One:Vector2.Zero;
var opacity=s.Opacity*frameOpacity;
if (dot.Kind != s.Kind||dot.Spectral!=s.Spectral||dot.Colour!=s.Colour||dot.Opacity!=opacity)
{
dot.Kind = s.Kind;dot.Spectral=s.Spectral;dot.Colour=s.Colour;dot.Opacity=opacity;
var alpha=(byte)Math.Clamp(Math.Round(255*opacity),0,255);var glowAlpha=(byte)Math.Clamp(Math.Round(145*opacity),0,255);
if(!stellarBrushes.TryGetValue((s.Colour,alpha),out var stellarBrush))stellarBrushes[(s.Colour,alpha)]=stellarBrush=compositor!.CreateColorBrush(Windows.UI.Color.FromArgb(alpha,s.Colour.R,s.Colour.G,s.Colour.B));
if(!stellarGlows.TryGetValue((s.Colour,glowAlpha),out var stellarGlow))stellarGlows[(s.Colour,glowAlpha)]=stellarGlow=GalaxySkybox.Radial(compositor!,Windows.UI.Color.FromArgb(glowAlpha,s.Colour.R,s.Colour.G,s.Colour.B));
dot.Shape.FillBrush=stellarBrush;dot.Aura.FillBrush=stellarGlow;
}
if (Filter?.ShowMarkers!=false&&s.Kind is 2 or 3) { var ring = s.Kind == 3 ? currentRing : selectedRing; ring.Offset = dot.Shape.Offset; ring.Scale = Vector2.One; }
}
hits[hitCount++] = (p, s.System);
if (Filter?.ShowLabels==false||labelCount >= names.Count) continue;
var displayName=s.Label.Display;var originalName=s.Label.Original;
if(regionLabels&®ionLabelNames.Contains(displayName))continue;
var boxWidth=s.Label.Width;var boxHeight=s.Label.Height;
var labelOffset=Filter?.ShowMarkers!=false&&s.Kind is 2 or 3?24:10;
var rect = new Rect(p.X + labelOffset, p.Y - 9, boxWidth, boxHeight); var collides = false;
if(rect.Right>viewWidth-6||rect.Bottom>viewHeight-6||rect.Top<6)continue;
for (var j = 0; j < labelCount; j++) { var r = labelRects[j]; if (r.X < rect.Right && r.Right > rect.X && r.Y < rect.Bottom && r.Bottom > rect.Y) { collides = true; break; } }
if(collides)continue;
if(regionLabels)regionLabelNames.Add(displayName);
// Reject occluded candidates before changing XAML text. Otherwise a
// dense field can mutate this same label thousands of times per frame.
var label = names[labelCount];
var query=Filter?.IsQueryActive==true;
if (!ReferenceEquals(label.System, s.System) || label.Kind != s.Kind||label.Colour!=s.Colour||label.Query!=query||label.Name.Text!=displayName)
{
label.System = s.System; label.Kind = s.Kind;label.Colour=s.Colour;label.Query=query;
label.Name.Text = displayName; label.Name.FontSize = s.Kind == 3 ? 14 : 11; label.Name.Foreground = query&&s.Kind==0?Brush(s.Colour.R,s.Colour.G,s.Colour.B):labelColors[s.Kind]; label.Original.Text = originalName;
label.BoxWidth = boxWidth;label.BoxHeight = boxHeight;
}
label.Transform.X = rect.X;label.Transform.Y = rect.Y;label.Wanted = true;labelRects[labelCount++] = rect;
}
for (var i = 0; i < names.Count; i++) { var label = names[i]; if (label.Visible != label.Wanted) { label.Visible = label.Wanted; label.Panel.Opacity = label.Visible ? 1 : 0; } }
for (var i = hitCount; i < stars.Count; i++) if (stars[i].Visible) { stars[i].Shape.Scale = stars[i].Aura.Scale=Vector2.Zero; stars[i].Visible = false; }
DrawSupplementalLabels(camera);
UpdateHoldVisual();
if(!useLod)CandidateStars=hitCount;
if(graphics is not null)graphics.ShowGalacticZonesPlane=Filter?.ShowGalacticZonesPlane==true;
UpdatePowerContours();
UpdatePowerActivityRing(camera);
graphics?.SetCurrentTradeFlows(Filter?.ShowCurrentTradeFlows==true?CurrentTradeFlows:null);
graphics?.Draw(starInstances.AsSpan(0,hitCount),lineVertices.AsSpan(0,lineCount),viewWidth,viewHeight,XamlRoot?.RasterizationScale??1,yaw,pitch,new((float)cx,(float)cy,(float)cz),(float)scale,(float)panX,(float)panY,Filter is null||Filter.Mode==GalaxyMapMode.Realistic,Filter?.ShowBackground!=false,Filter?.IsQueryActive!=true,Filter?.ShowRoute!=false);
DrawWorldMarkers(camera);
FrameCount++; LastFrameMilliseconds = (Stopwatch.GetTimestamp() - started) * 1000.0 / Stopwatch.Frequency;
if(graphics?.HasOriginalCurrentTradeAnimation==true)Invalidate();
}
private void Pressed(object sender, PointerRoutedEventArgs e)
{
if (!IsInteractive) return; var p = e.GetCurrentPoint(this);
if (!p.Properties.IsLeftButtonPressed && !p.Properties.IsRightButtonPressed && e.Pointer.PointerDeviceType == Microsoft.UI.Input.PointerDeviceType.Mouse) return;
if(e.Pointer.PointerDeviceType==Microsoft.UI.Input.PointerDeviceType.Mouse)
BeginMousePointer(p.Position,Buttons(p.Properties.IsLeftButtonPressed,p.Properties.IsRightButtonPressed));
else BeginPointer(p.Position,false);
dragging=CapturePointer(e.Pointer);if(!dragging)CancelHold();Focus(FocusState.Pointer);e.Handled=true;
}
private void Moved(object sender, PointerRoutedEventArgs e)
{
if (!dragging || !IsInteractive) return; var p = e.GetCurrentPoint(this);
if(mouseGesture)ChangeMouseButtons(p.Position,Buttons(p.Properties.IsLeftButtonPressed,p.Properties.IsRightButtonPressed));
MovePointer(p.Position);e.Handled = true;
}
private void Released(object sender, PointerRoutedEventArgs e)
{
if (!dragging) return;var p=e.GetCurrentPoint(this);
var remaining=Buttons(p.Properties.IsLeftButtonPressed,p.Properties.IsRightButtonPressed);
if(mouseGesture&&remaining!=GalaxyMouseButtons.None){ChangeMouseButtons(p.Position,remaining);e.Handled=true;return;}
EndPointer(p.Position);ReleasePointerCapture(e.Pointer);e.Handled=true;
}
private static GalaxyMouseButtons Buttons(bool left,bool right)=>(left?GalaxyMouseButtons.Left:0)|(right?GalaxyMouseButtons.Right:0);
internal void BeginMousePointer(Point point,GalaxyMouseButtons buttons)
{
if(dragging&&mouseGesture){ChangeMouseButtons(point,buttons);return;}
BeginPointer(point,buttons!=GalaxyMouseButtons.Left);mouseGesture=true;mouseButtons=buttons;
suppressPointerSelection=buttons!=GalaxyMouseButtons.Left;
}
internal void ChangeMouseButtons(Point point,GalaxyMouseButtons buttons)
{
if(!mouseGesture||mouseButtons==buttons)return;
// A chord transition cancels the click/hold even when the last button
// remaining is the left one. Keep capture until all buttons are up.
CancelHold();suppressPointerSelection=true;panning=buttons!=GalaxyMouseButtons.Left;
mouseButtons=buttons;previous=point;
FinishCameraInput();
}
private void CancelHold(){holdTimer.Stop();holdGesture.Cancel();holdCandidate=null;if(!Planning&&planningCandidate is null){holdProgress.IsActive=false;holdProgress.Visibility=Visibility.Collapsed;}}
private void UpdateHoldVisual()
{
var target=planningCandidate??holdCandidate;
var projected=target is null?default:Camera.ProjectForCatalogue(target.Position);
if(target is null||!projected.IsVisible||Filter?.Matches(target)==false||!IsRendered(target))
{holdProgress.Visibility=planningLabel.Visibility=Visibility.Collapsed;return;}
holdProgress.Visibility=Visibility.Visible;
planningLabel.Text=planningCancellation?"取消中…":"规划中…";
var point=new Point(projected.X,projected.Y);Canvas.SetLeft(holdProgress,point.X-24);Canvas.SetTop(holdProgress,point.Y-24);
Canvas.SetLeft(planningLabel,point.X+30);Canvas.SetTop(planningLabel,point.Y-10);
planningLabel.Visibility=planningCandidate is null?Visibility.Collapsed:Visibility.Visible;
}
internal void BeginPointer(Point point,bool pan)
{
CancelCameraInput();
CancelHold();previous=point;travel=0;panning=pan;dragging=true;holdInvoked=false;mouseGesture=false;mouseButtons=GalaxyMouseButtons.None;suppressPointerSelection=false;
// Freeze the displayed pose before picking. An in-flight focus animation
// must not move a neighbouring star under an already pressed pointer.
cameraTimer.Stop();cameraAnimation=null;
holdCandidate=pan?null:FindAt(point);if(holdCandidate is {} candidate&&!CanPlanRoute&&!HoldingCancelsRoute(candidate))holdCandidate=null;
holdGesture.Begin(point.X,point.Y,MonotonicMilliseconds,holdCandidate is not null);
if(holdCandidate is not null){Selection=holdCandidate;SystemSelected?.Invoke(this,holdCandidate);holdProgress.IsIndeterminate=false;holdProgress.Value=0;holdProgress.IsActive=true;holdProgress.Visibility=Visibility.Visible;UpdateHoldVisual();holdTimer.Start();}
}
internal void MovePointer(Point point)
{
holdGesture.Move(point.X,point.Y);
if(holdGesture.Progress(MonotonicMilliseconds)<=0&&holdCandidate is not null)CancelHold();
var dx=point.X-previous.X;var dy=point.Y-previous.Y;travel+=Math.Abs(dx)+Math.Abs(dy);previous=point;
if(!holdInvoked){if(mouseGesture)ApplyMouseDragDelta(dx,dy,mouseButtons);else ApplyDragDelta(dx,dy,panning);}
}
internal void EndPointer(Point point)
{
var chosen=holdInvoked;dragging=false;CancelHold();if(!chosen&&!panning&&!suppressPointerSelection&&travel<=5)SelectAt(point);mouseGesture=false;mouseButtons=GalaxyMouseButtons.None;FinishCameraInput();if(travel>5)FlushViewport();
}
private void ConfirmHold()
{
if(!dragging||!IsInteractive||holdCandidate is not {} target||!CanPlanRoute&&!HoldingCancelsRoute(target)){CancelHold();return;}
if(vectors is not null&&(sceneDirty||scheduled)){StopScheduling();Draw();}
if(Filter?.Matches(target)==false||!Camera.ProjectForCatalogue(target.Position).IsVisible||!IsRendered(target)){CancelHold();return;}
var now=MonotonicMilliseconds;holdProgress.Value=holdGesture.Progress(now)*100;UpdateHoldVisual();
if(!holdGesture.TryConfirm(now))return;
holdTimer.Stop();holdInvoked=true;planningCandidate=target;planningCancellation=HoldingCancelsRoute(target);Selection=target;SystemSelected?.Invoke(this,target);
holdProgress.IsIndeterminate=true;holdProgress.IsActive=true;holdProgress.Visibility=Visibility.Visible;UpdateHoldVisual();TargetChosen?.Invoke(this,target);
}
private GalacticSystem? FindAt(Point p)
{
if(vectors is not null&&(sceneDirty||scheduled)){StopScheduling();Draw();}
// The selected star owns its visible ring and caption. Otherwise a dot
// behind either can silently replace a search result at long-press time.
if(Selection is {Position.IsValid:true} selected&&Filter?.Matches(selected)!=false&&IsRendered(selected))
{
var pose=Camera.ProjectForCatalogue(selected.Position);var centre=new Point(pose.X,pose.Y);var sx=centre.X-p.X;var sy=centre.Y-p.Y;
if(pose.IsVisible&&sx*sx+sy*sy<=24*24)return selected;
var caption=names.FirstOrDefault(n=>n.Visible&&n.System?.Name.Equals(selected.Name,StringComparison.OrdinalIgnoreCase)==true);
if(pose.IsVisible&&caption is not null&&new Rect(caption.Transform.X,caption.Transform.Y,caption.BoxWidth,caption.BoxHeight).Contains(p))return selected;
}
if(FindWorldMarkerAt(p) is {} markerTarget)return markerTarget;
var best=225d;GalacticSystem? found=null;
// Pick the actual retained stars. Overflow LOD must not make a hidden
// neighbour selectable simply because it exists in the source catalogue.
var camera=Camera;var closestDepth=double.PositiveInfinity;
for(var i=0;i<hitCount;i++){var system=hits[i].System;var at=camera.ProjectForCatalogue(system.Position);if(!at.IsVisible)continue;var dx=at.X-p.X;var dy=at.Y-p.Y;var distance=dx*dx+dy*dy;if(distance<best-.01||Math.Abs(distance-best)<.01&&at.Depth<closestDepth){best=distance;closestDepth=at.Depth;found=system;}}
return found;
}
private bool IsRendered(GalacticSystem system)
{
for(var i=0;i<hitCount;i++)if(hits[i].System.Name.Equals(system.Name,StringComparison.OrdinalIgnoreCase))return true;
return false;
}
internal void SelectAt(Point p)
{
var found=FindAt(p);
if (found is not null) { Selection = found; SystemSelected?.Invoke(this, found); }
else ClearSelection();
}
// Geometric observation only. Catalogue visibility and picking require
// ProjectForCatalogue plus an actually retained rendered-star hit.
internal Point ProjectForProbe(Coordinates p)
{
var projected=Camera.Project(p);return new(projected.X,projected.Y);
}
internal void RenderNowForProbe() { StopScheduling(); EnsureGraphics(); Draw(); }
private sealed record NameLayout(string Display,string Original,double Width,double Height);
private sealed record Sample(GalacticSystem System, double X, double Y, double Z, int Kind,int Spectral,NameLayout Label,StarColour Colour,float RelativeSize,float Opacity,Vector4? OriginalColour,bool LodPriority);
private sealed record LineVisual(CompositionLineGeometry Geometry, CompositionSpriteShape Shape)
{
public void Move(Point a, Point b) { Geometry.Start = new((float)a.X, (float)a.Y); Geometry.End = new((float)b.X, (float)b.Y); }
}
private sealed class StarVisual(CompositionEllipseGeometry geometry, CompositionSpriteShape shape,CompositionEllipseGeometry auraGeometry,CompositionSpriteShape aura)
{ public CompositionEllipseGeometry Geometry = geometry,AuraGeometry=auraGeometry; public CompositionSpriteShape Shape = shape,Aura=aura; public int Kind = -1,Spectral=-1; public bool Visible;public StarColour Colour;public float Opacity=-1; }
private sealed class LabelVisual(StackPanel panel, TextBlock name, TextBlock original, TranslateTransform transform)
{ public StackPanel Panel = panel; public TextBlock Name = name, Original = original; public TranslateTransform Transform = transform; public double BoxWidth, BoxHeight; public bool Visible, Wanted,Query; public GalacticSystem? System; public int Kind = -1;public StarColour Colour; }
}