From d3362c83417a7a718dbf88a7cd9a29a6e06ef7a2 Mon Sep 17 00:00:00 2001 From: Elijah Date: Sun, 4 Oct 2026 13:52:01 -0700 Subject: [PATCH] Release 1.1.3: reveal faint nebula structure with human-readable preview modes --- Directory.Build.props | 2 +- README.md | 2 +- docs/analysis-design.md | 6 +- docs/release-notes/1.1.3.md | 10 ++ docs/releases.md | 2 +- .../MainWindow.Verification.cs | 17 +++ src/AstroFrame.Desktop/MainWindow.cs | 7 +- src/AstroFrame.Desktop/Program.cs | 1 + src/AstroFrame.Desktop/Visuals.cs | 59 ++++++++-- src/AstroFrame.Engine/ColorPreview.cs | 106 ++++++++++++++++++ src/AstroFrame.Engine/PreviewRenderer.cs | 49 ++++++-- .../ColorPreviewRegression.cs | 43 +++++++ .../AstroFrame.Validation/ImageRegression.cs | 4 +- .../PreviewRegression.cs | 15 ++- tests/AstroFrame.Validation/Program.cs | 1 + 15 files changed, 300 insertions(+), 24 deletions(-) create mode 100644 docs/release-notes/1.1.3.md create mode 100644 src/AstroFrame.Engine/ColorPreview.cs create mode 100644 tests/AstroFrame.Validation/ColorPreviewRegression.cs diff --git a/Directory.Build.props b/Directory.Build.props index 54d121f..8e42b0b 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,6 +1,6 @@ - 1.1.2 + 1.1.3 Elijah Kuntz AstroFrame diff --git a/README.md b/README.md index a7a83a5..753c30d 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ To analyze another dataset, choose **Analyze lights**, select the folder contain - Select a quality measurement and click the graph to inspect an exposure. One graph shows the selected metric, including stellar flux when selected. Capture order uses UTC timestamps; gaps between sessions are marked rather than drawn to elapsed-time scale. - Filter **REVIEW** or **REJECT**, and sort by concern, star count, stellar flux, or FWHM. - Toggle **Compare nearby** and **Spatial overlay**. Red fill shows transient sky structure in the aligned reference grid. Region outlines show forced stellar flux loss. Previews have independent display stretches; use measured flux to compare transparency. -- Use **Frame view** for an area-averaged exposure preview, or **Nebula view** for additional averaging of faint diffuse structure. Adjust **Stretch** to brighten the display. These controls never affect measurements, classifications or original files. +- Use **Frame view** for an area-averaged exposure preview. **Nebula view** suppresses small stars and noise, then stretches faint structure without reducing the preview dimensions. **Asinh view** offers a different stretch with softer highlights. **Color nebula** uses the FITS Bayer channels, neutralizes the sky and smooths uncertain color; monochrome files fall back to grayscale. Adjust **Preview stretch** to brighten any view. These controls never affect measurements, classifications or original files. Single exposures can still be noisy, and the color is a viewing aid rather than calibrated astrophotography. - Scroll the mouse wheel over either preview to zoom around the cursor, and hold the left mouse button to drag. Zoom and image position persist across frames and are shared with the nearby comparison. **Reset view** restores the fitted, centered image. These display controls do not alter source pixels or analysis. - Press **1**, **2**, **3** for KEEP, REVIEW, REJECT. Decisions save and advance. **J/K** navigates. **Reset** restores the automatic decision. **Ctrl+Z** undoes a manual decision. - Decision evidence and measurements remain visible below the quality graph. Hover over an evidence line to read its full technical detail, and scroll the panel for additional measurements. Preview stretch and manual decisions sit below the image. Existing notes remain in saved projects and exports; the note editor has been removed. Automatic decisions and human overrides remain separate. diff --git a/docs/analysis-design.md b/docs/analysis-design.md index 277f262..2d567d5 100644 --- a/docs/analysis-design.md +++ b/docs/analysis-design.md @@ -57,7 +57,11 @@ Version 1.1.0 selects up to 16 workers from CPU capacity, leaving two logical pr Small JSON metadata stores decisions, notes, evidence and compact masks. Binary versioned caches hold stars, sky maps and forced photometry, validated against source size and modification time and reference identity. A new engine version invalidates analysis without losing human labels. Repeated analysis uses cached measurements and forced apertures when valid. Project writes replace a temporary file atomically. Cancellation leaves analysis incomplete and export disabled. -Display caches have a separate version. They contain compressed, linear, area-averaged thumbnails rather than a permanently stretched byte image. The screen transfer uses a noise-aware black point and adjustable median brightness; **Nebula view** averages neighboring display samples further. This avoids nearest-pixel aliasing and the original excessively bright, noisy stretch. Prepared display statistics are cached in the viewer so slider changes remain responsive. Disk loading and first-time thumbnail creation run off the UI thread, with cancellation and a single preview-loading gate preventing queued FITS reads during rapid navigation. Old projects regenerate only requested displays on demand. +Display caches have a separate version. They contain compressed, linear, area-averaged thumbnails rather than a permanently stretched byte image. **Frame view** retains its noise-aware black point and adjustable median brightness. **Nebula view** applies a 3×3 median and four separable binomial smoothing passes at the existing thumbnail dimensions, suppressing small stars and noise while retaining faint filaments. Its black point also includes the lower background percentile, and its median is displayed slightly brighter. **Asinh view** applies an adjustable inverse-hyperbolic-sine transfer to this same smoothed plane, with a brightness-adjusted gamma fallback when its normalized median already exceeds the requested brightness. + +**Color nebula** reads recognized RGGB, GRBG, GBRG or BGGR Bayer layouts and their offsets through a separate streaming display reader. It bins linear RGB superpixels, uses the same diffuse luminance preview, neutralizes each channel's median sky, smooths chroma and suppresses departures consistent with noise. A linked channel scale limits saturation and preserves neutral black and white highlights. Color is approximate and uncalibrated; no color is invented for monochrome or unknown Bayer layouts, which show the grayscale nebula preview with an explanatory label. Color has a separate fingerprinted linear cache generated only on demand. Neither display reader changes the monochrome analysis path, classifications, or original FITS files. + +Prepared display statistics are cached in the viewer so slider changes remain responsive. Disk loading and first-time thumbnail creation run off the UI thread, with cancellation and a single preview-loading gate preventing queued FITS reads during rapid navigation. Both comparison panes use the selected mode and shared zoom/pan. Old projects regenerate only requested displays on demand. Single-frame previews cannot recover signal absent from the exposure and can remain noisy; these are human-readable viewing aids, not stacked images. The preview is not an input to classification. Source-star inspection reads two originals, maps identical stars through their stored alignment, and displays enlarged source superpixels without interpolation. Crops are independently normalized to judge morphology. See [Siril's screen-transfer discussion](https://siril.readthedocs.io/en/latest/processing/stretching.html) for the distinction between display stretching and linear image data. diff --git a/docs/release-notes/1.1.3.md b/docs/release-notes/1.1.3.md new file mode 100644 index 0000000..c6706bb --- /dev/null +++ b/docs/release-notes/1.1.3.md @@ -0,0 +1,10 @@ +# AstroFrame 1.1.3 + +- Rework **Nebula view** to reveal faint diffuse structure and thin filaments. Suppress small stars and noise at the existing preview resolution, then apply a background-aware stretch. NGC 6960's Veil filaments are now visible in the tested single exposures. +- Add **Asinh view**, an alternative adjustable stretch with softer highlights. +- Add **Color nebula** from recognized FITS Bayer channels. Neutralize the sky, smooth uncertain color and preserve neutral bright highlights. Monochrome and unknown Bayer layouts display the grayscale nebula preview instead of fabricated color. +- Apply every viewing mode to both comparison panes while preserving shared zoom and pan. Linear color previews are cached on demand without invalidating quality measurements. + +These are display-only changes. Original FITS files, analysis, classifications and manual decisions are unaffected. Single exposures can remain noisy; color is a viewing aid rather than calibrated astrophotography. + +Validation: 135 engine, 23 updater, 10 mocked publisher and 63 isolated Windows interaction checks, with rendering at 96 and 144 DPI. Covers faint-filament visibility, stretch brightness, Bayer patterns and offsets, color/cache integrity, monochrome fallback, rapid navigation, cancellation and source-file preservation. Visually inspected 18 real exposures across NGC 6960, NGC 7000, IC 1805, NGC 281, M33 and NGC 1432. Verification uses copied workspace caches and leaves the installed application untouched. The server workflow builds Windows and Linux packages and checks the packaged Linux settings page. diff --git a/docs/releases.md b/docs/releases.md index 4594978..89e5b00 100644 --- a/docs/releases.md +++ b/docs/releases.md @@ -127,7 +127,7 @@ For preview and processing-status changes, build the source and run the isolated ./tools/Verify-Preview.ps1 -FixtureProject 'path/to/saved-project' -Output artifacts/preview-verification ``` -This checks comparison overlays, zoom/pan, processing-memory visibility, elongation crops and guide toggling, absent comparisons, loading cancellation, and native window controls. It renders normal and minimum-size controls at 96 and 144 DPI. Inspect the PNG files in the output's `qa` directory. It launches only the source build in diagnostic mode, which bypasses installed settings and updates. +This checks comparison overlays, zoom/pan, all four preview modes in both panes, Bayer color loading across frame changes, monochrome fallback, processing-memory visibility, elongation crops and guide toggling, absent comparisons, loading cancellation, and native window controls. It renders normal and minimum-size controls at 96 and 144 DPI. Inspect the PNG files in the output's `qa` directory. It launches only the source build in diagnostic mode, which bypasses installed settings and updates. Source `--capture` diagnostics accept `--preview=0` (Frame), `1` (Nebula), `2` (Asinh) or `3` (Color nebula) for real-exposure visual checks against copied workspace projects. `./tools/Verify-ReleaseAutomation.ps1` exercises version/tag mismatch, upload failure, draft resumption, conflicting assets, immutable published releases and package integrity with a mocked release API. It never publishes a real release. diff --git a/src/AstroFrame.Desktop/MainWindow.Verification.cs b/src/AstroFrame.Desktop/MainWindow.Verification.cs index 57a17f5..a54c5d2 100644 --- a/src/AstroFrame.Desktop/MainWindow.Verification.cs +++ b/src/AstroFrame.Desktop/MainWindow.Verification.cs @@ -54,6 +54,23 @@ public sealed partial class MainWindow spatial.IsChecked=true;compare.IsChecked=false;compare.IsChecked=true;Select(visible[0]);await WaitForPreviews();await Task.Delay(150); Check(preview.Spatial&&comparison.Spatial&&comparison.HasImage,"Overlay persists on both panes after toggling comparison and changing frame"); Capture("comparison-fit",144); + double retainedZoom=viewport.Zoom;var retainedPan=viewport.Pan;previewMode.SelectedIndex=2; + Check(preview.Mode==AstroFrame.Engine.PreviewMode.Asinh&&comparison.Mode==preview.Mode&&viewport.Zoom==retainedZoom&&viewport.Pan==retainedPan,"Asinh view switches both panes without changing zoom or pan");Capture("asinh-comparison",144); + previewMode.SelectedIndex=3;await WaitForPreviews();await Task.Delay(100); + Check(preview.Mode==AstroFrame.Engine.PreviewMode.Color&&comparison.Mode==preview.Mode&&preview.HasColor&&comparison.HasColor,"Color nebula loads real Bayer RGB for both comparison frames");Capture("color-comparison",144); + Select(visible[1]);await WaitForPreviews();Check(preview.HasColor&&comparison.HasColor&&preview.Mode==AstroFrame.Engine.PreviewMode.Color,"color mode survives exposure changes and cached previews"); + foreach(var frame in visible.Take(6))Select(frame);previewMode.SelectedIndex=2;previewMode.SelectedIndex=3;await WaitForPreviews(); + Check(preview.HasColor&&comparison.HasColor&&preview.Frame==selected&&preview.Mode==AstroFrame.Engine.PreviewMode.Color,"rapid exposure and mode changes cancel stale color requests and retain the latest preview"); + Select(visible[1]);await WaitForPreviews(); + previewMode.SelectedIndex=0;Check(preview.Mode==AstroFrame.Engine.PreviewMode.Frame&&comparison.Mode==preview.Mode,"Frame view restores both original grayscale previews");previewMode.SelectedIndex=1; + string monoPath=System.IO.Path.Combine(output,"mono-source.fit");var monoBytes=File.ReadAllBytes(selected!.Path); + using(var sourceStream=File.OpenRead(selected.Path)) + { + var(_,headerBytes)=AstroFrame.Engine.Fits.ReadHeader(sourceStream); + for(int offset=0;offsetdisplayStretch.Value=.18;Grid.SetColumn(resetStretch,1);stretchRow.Children.Add(resetStretch);Grid.SetRow(stretchRow,1);displayPanel.Children.Add(stretchRow);previewControls=new(){Child=displayPanel}; // Keep the native slider's input behavior; give its thumb a visible silver face and room for the full circle. Styles.Add(new Style(x=>x.OfType().Template().OfType()){Setters={new Setter(Avalonia.Controls.Primitives.TemplatedControl.TemplateProperty,new FuncControlTemplate((_,_)=>new Border{Width=20,Height=20,CornerRadius=new(10),Background=Palette.Accent,BorderBrush=Palette.Panel,BorderThickness=new(3),HorizontalAlignment=HorizontalAlignment.Center,VerticalAlignment=VerticalAlignment.Center}))}}); - previewMode.SelectionChanged+=(_,_)=>{preview.Nebula=comparison.Nebula=previewMode.SelectedIndex==1;preview.RefreshDisplay();comparison.RefreshDisplay();}; + previewMode.SelectionChanged+=(_,_)=>{preview.SetMode((PreviewMode)Math.Max(0,previewMode.SelectedIndex));comparison.SetMode((PreviewMode)Math.Max(0,previewMode.SelectedIndex));}; + ToolTip.SetTip(previewMode,"Frame: original grayscale stretch. Nebula: smooth faint detail with less star dominance. Asinh: an alternative smooth stretch. Color: sky-neutralized Bayer RGB when available. Display options do not change analysis."); displayStretch.PropertyChanged+=(_,e)=>{if(e.Property==Slider.ValueProperty){stretchValue.Text=displayStretch.Value.ToString("0.00");preview.Stretch=comparison.Stretch=displayStretch.Value;preview.RefreshDisplay();comparison.RefreshDisplay();}}; Title="AstroFrame";Width=1450;Height=940;MinWidth=1120;MinHeight=740;Background=Palette.Background;FontFamily="Inter";FontSize=13; ExtendClientAreaToDecorationsHint=true;ExtendClientAreaChromeHints=Avalonia.Platform.ExtendClientAreaChromeHints.PreferSystemChrome;ExtendClientAreaTitleBarHeightHint=36; @@ -179,6 +180,8 @@ public sealed partial class MainWindow:Window int index=Array.FindIndex(QualityChart.Metrics,m=>m.Name==name); if(index<0)throw new ArgumentException("Unknown quality metric",nameof(name));metric.SelectedIndex=index; } + public void CapturePreviewMode(int mode) + {if(mode<0||mode>3)throw new ArgumentOutOfRangeException(nameof(mode));previewMode.SelectedIndex=mode;} public async Task SmokeTest(string report) { if(project==null)throw new InvalidOperationException("Project not loaded"); diff --git a/src/AstroFrame.Desktop/Program.cs b/src/AstroFrame.Desktop/Program.cs index ed05282..00f35ff 100644 --- a/src/AstroFrame.Desktop/Program.cs +++ b/src/AstroFrame.Desktop/Program.cs @@ -82,6 +82,7 @@ public sealed class App:Application else if(Program.Arguments[3]!="all")window.CaptureSelection(Program.Arguments[3]=="reject"); } string? metricOption=Program.Arguments.FirstOrDefault(a=>a.StartsWith("--metric="));if(metricOption!=null)window.CaptureMetric(metricOption[9..]); + string? previewOption=Program.Arguments.FirstOrDefault(a=>a.StartsWith("--preview="));if(previewOption!=null)window.CapturePreviewMode(int.Parse(previewOption[10..],System.Globalization.CultureInfo.InvariantCulture)); if(Program.Arguments.Length>4&&double.TryParse(Program.Arguments[4],System.Globalization.NumberStyles.Float,System.Globalization.CultureInfo.InvariantCulture,out double width)){window.Width=width;window.Height=740;} await window.WaitForPreviews();await Task.Delay(400); if(window.Content is Control content) diff --git a/src/AstroFrame.Desktop/Visuals.cs b/src/AstroFrame.Desktop/Visuals.cs index b1abf32..01b4be6 100644 --- a/src/AstroFrame.Desktop/Visuals.cs +++ b/src/AstroFrame.Desktop/Visuals.cs @@ -75,6 +75,9 @@ public sealed class ExposureView:Control,IDisposable static readonly SemaphoreSlim LoadGate=new(1); WriteableBitmap? bitmap; PreviewDisplay? frameDisplay,nebulaDisplay; + ColorPreviewDisplay? colorDisplay; + bool colorAttempted; + string directory=""; byte[] overlayMask=[]; CancellationTokenSource? request; string message="Select an exposure"; @@ -82,12 +85,15 @@ public sealed class ExposureView:Control,IDisposable public bool HasImage=>bitmap!=null; public Frame? Frame {get;private set;} public bool Spatial {get;set;} - public bool Nebula {get;set;} + public PreviewMode Mode {get;private set;} + public bool Nebula {get=>Mode==PreviewMode.Nebula;set=>SetMode(value?PreviewMode.Nebula:PreviewMode.Frame);} + public bool HasColor=>colorDisplay!=null; public double Stretch {get;set;}=.18; public string Caption {get;set;}=""; public PreviewViewport Viewport {get;} Point? dragStart;IPointer? dragPointer; - Rect ImageArea=>new(0,(Caption!=""?26:0)+(Spatial?22:0),Math.Max(1,Bounds.Width),Math.Max(1,Bounds.Height-(Caption!=""?26:0)-(Spatial?22:0))); + string ModeNote=>Mode switch{PreviewMode.Nebula=>"Faint detail · smoothed",PreviewMode.Asinh=>"Asinh · smoothed",PreviewMode.Color=>colorDisplay!=null?"Color · neutral sky":colorAttempted?"Color unavailable · grayscale":"Loading color…",_=>""}; + Rect ImageArea=>new(0,(Caption!=""?26:0)+(Spatial?22:0)+(ModeNote!=""?20:0),Math.Max(1,Bounds.Width),Math.Max(1,Bounds.Height-(Caption!=""?26:0)-(Spatial?22:0)-(ModeNote!=""?20:0))); public ExposureView():this(new PreviewViewport()){} public ExposureView(PreviewViewport viewport) { @@ -103,7 +109,7 @@ public sealed class ExposureView:Control,IDisposable void EndDrag(){dragStart=null;dragPointer?.Capture(null);dragPointer=null;Cursor=Cursor.Default;} public void Load(string projectDirectory,Frame? f,IReadOnlyList? frames=null) { - Dispose();Frame=f;message=f==null?"Select an exposure":"Loading preview…";InvalidateVisual(); + Dispose();directory=projectDirectory;Frame=f;message=f==null?"Select an exposure":"Loading preview…";InvalidateVisual(); if(f==null){Loading=Task.CompletedTask;return;} request=new();Loading=LoadCore(projectDirectory,f,frames??[],request.Token); } @@ -125,21 +131,57 @@ public sealed class ExposureView:Control,IDisposable using var memory=await ResourcePolicy.Acquire(ResourcePolicy.EstimateFrameBytes(f.Width,f.Height,f.Bayer!=""?2:1),token); var image=Fits.Read(f.Path,token);token.ThrowIfCancellationRequested();Fits.Preview(image,path,f);plane=PreviewRenderer.Read(path,f); } - token.ThrowIfCancellationRequested();return(PreviewRenderer.Prepare(plane),PreviewRenderer.Prepare(plane,true),SkyOverlay.LoadMask(directory,f,frames,token)); + token.ThrowIfCancellationRequested();return(PreviewRenderer.Prepare(plane,false,token),PreviewRenderer.Prepare(plane,true,token),SkyOverlay.LoadMask(directory,f,frames,token)); },token); } finally{LoadGate.Release();} token.ThrowIfCancellationRequested();frameDisplay=prepared.Frame;nebulaDisplay=prepared.Nebula;overlayMask=prepared.Overlay;RefreshDisplay(); + if(Mode==PreviewMode.Color)await LoadColor(directory,f,token); } catch(OperationCanceledException){} catch(Exception e){if(!token.IsCancellationRequested){message="Preview unavailable: "+e.Message;InvalidateVisual();}} } + public void SetMode(PreviewMode mode) + { + Mode=mode;RefreshDisplay();InvalidateVisual(); + if(mode==PreviewMode.Color&&!colorAttempted&&Frame is {} frame&&request is {} active) + {var previous=Loading;Loading=LoadColorAfter(previous,directory,frame,active.Token);} + } + async Task LoadColorAfter(Task previous,string projectDirectory,Frame frame,CancellationToken token) + {await previous;if(!token.IsCancellationRequested)await LoadColor(projectDirectory,frame,token);} + async Task LoadColor(string projectDirectory,Frame frame,CancellationToken token) + { + try + { + await LoadGate.WaitAsync(token); + try + { + if(colorAttempted)return; + var prepared=await Task.Run(async()=> + { + var info=new FileInfo(frame.Path);if(!info.Exists||info.Length!=frame.Length||info.LastWriteTimeUtc.Ticks!=frame.Modified)throw new IOException("Source changed; reanalyze before inspecting"); + string path=ColorPreview.PathFor(projectDirectory,frame);ColorPreviewPlane? color=null; + try{if(File.Exists(path))color=ColorPreview.Read(path,frame);}catch(IOException){} + if(color==null) + { + using var memory=await ResourcePolicy.Acquire(ResourcePolicy.EstimateFrameBytes(frame.Width,frame.Height,2),token); + color=ColorPreview.ReadFits(frame.Path,token);token.ThrowIfCancellationRequested();if(color!=null)ColorPreview.Write(color,path,frame); + } + return color==null?null:ColorPreview.Prepare(color,token); + },token); + token.ThrowIfCancellationRequested();colorDisplay=prepared;colorAttempted=true;RefreshDisplay();InvalidateVisual(); + } + finally{LoadGate.Release();} + } + catch(OperationCanceledException){} + catch(Exception){if(!token.IsCancellationRequested){colorAttempted=true;RefreshDisplay();InvalidateVisual();}} + } public void RefreshDisplay() { - var display=Nebula?nebulaDisplay:frameDisplay;if(display==null)return; - byte[] pixels=PreviewRenderer.Render(display,Stretch);int w=display.Plane.Width,h=display.Plane.Height;bitmap?.Dispose(); + var display=Mode==PreviewMode.Frame?frameDisplay:nebulaDisplay;if(display==null)return; + bool color=Mode==PreviewMode.Color&&colorDisplay!=null;byte[] pixels=color?ColorPreview.Render(colorDisplay!,Stretch):PreviewRenderer.Render(display,Stretch,Mode==PreviewMode.Asinh);int w=color?colorDisplay!.Luminance.Plane.Width:display.Plane.Width,h=color?colorDisplay!.Luminance.Plane.Height:display.Plane.Height;bitmap?.Dispose(); bitmap=new WriteableBitmap(new PixelSize(w,h),new Vector(96,96),PixelFormat.Bgra8888,AlphaFormat.Opaque); - using var locked=bitmap.Lock();byte[] row=new byte[w*4];for(int y=0;y0)c.DrawText(new FormattedText(Caption+" · "+Frame?.Time,System.Globalization.CultureInfo.CurrentCulture,FlowDirection.LeftToRight,new Typeface("Inter"),10,Palette.Muted),new(8,7)); if(Spatial)c.DrawText(new FormattedText(overlayMask.Length==SkyModel.Count?"Pink: excess sky · Grid: stellar flux":"Sky overlay unavailable · cached reference required",System.Globalization.CultureInfo.CurrentCulture,FlowDirection.LeftToRight,new Typeface("Inter"),10,Palette.Muted){MaxTextWidth=Math.Max(1,Bounds.Width-16)},new(8,captionHeight+5)); + if(ModeNote!="")c.DrawText(new FormattedText(ModeNote,System.Globalization.CultureInfo.CurrentCulture,FlowDirection.LeftToRight,new Typeface("Inter"),10,Palette.Muted){MaxTextWidth=Math.Max(1,Bounds.Width-16)},new(8,header+4)); using var imageClip=c.PushClip(ImageArea); var rect=Viewport.ImageRect(ImageArea,bitmap.Size);double w=rect.Width,h=rect.Height;c.DrawImage(bitmap,new Rect(bitmap.Size),rect); if(Spatial&&Frame!=null&&Frame.Alignment.Length==4) @@ -169,5 +212,5 @@ public sealed class ExposureView:Control,IDisposable } } } - public void Dispose(){EndDrag();request?.Cancel();request?.Dispose();request=null;bitmap?.Dispose();bitmap=null;frameDisplay=nebulaDisplay=null;overlayMask=[];} + public void Dispose(){EndDrag();request?.Cancel();request?.Dispose();request=null;bitmap?.Dispose();bitmap=null;frameDisplay=nebulaDisplay=null;colorDisplay=null;colorAttempted=false;overlayMask=[];} } diff --git a/src/AstroFrame.Engine/ColorPreview.cs b/src/AstroFrame.Engine/ColorPreview.cs new file mode 100644 index 0000000..ad68606 --- /dev/null +++ b/src/AstroFrame.Engine/ColorPreview.cs @@ -0,0 +1,106 @@ +using System.Buffers.Binary; +using System.Globalization; +using System.IO.Compression; +using System.Runtime.InteropServices; + +namespace AstroFrame.Engine; + +public sealed record ColorPreviewPlane(int Width,int Height,float[] Red,float[] Green,float[] Blue); +public sealed record ColorPreviewDisplay(PreviewDisplay Luminance,float[][] Chroma,double ChromaThreshold); +/// Display-only Bayer binning. Does not alter the monochrome analysis reader or caches. +public static class ColorPreview +{ + const int Magic=0x41504331; + public static ColorPreviewPlane? ReadFits(string path,CancellationToken ct=default) + { + using var stream=File.OpenRead(path);var(header,_)=Fits.ReadHeader(stream); + double Number(string key,double fallback=0)=>header.TryGetValue(key,out var value)&&double.TryParse(value.Replace('D','E'),NumberStyles.Float,CultureInfo.InvariantCulture,out double number)?number:fallback; + string pattern=header.GetValueOrDefault("BAYERPAT","").Trim().ToUpperInvariant(); + if(pattern is not ("RGGB" or "GRBG" or "GBRG" or "BGGR"))return null; + int w=(int)Number("NAXIS1"),h=(int)Number("NAXIS2"),bit=(int)Number("BITPIX"); + if(Number("NAXIS")!=2||w<32||h<32||(long)w*h>100_000_000)throw new InvalidDataException("Unsupported color preview dimensions"); + if(bit is not (8 or 16 or 32 or -32 or -64))throw new InvalidDataException("Unsupported FITS BITPIX"); + int bytes=Math.Abs(bit)/8,uw=w/2,uh=h/2,step=Math.Max((uh+899)/900,(int)Math.Ceiling(Math.Sqrt((double)uw*uh/2_000_000))),ow=(uw+step-1)/step,oh=(uh+step-1)/step; + if(stream.Length-stream.Position<(long)w*h*bytes)throw new InvalidDataException("Truncated FITS pixels"); + double zero=Number("BZERO"),factor=Number("BSCALE",1);int ox=((int)Number("XBAYROFF")%2+2)%2,oy=((int)Number("YBAYROFF")%2+2)%2; + double[][] sums=[new double[ow*oh],new double[ow*oh],new double[ow*oh]];byte[] rows=new byte[w*bytes*2]; + for(int y=0;yspan[0],16=>BinaryPrimitives.ReadInt16BigEndian(span),32=>BinaryPrimitives.ReadInt32BigEndian(span),-32=>BitConverter.Int32BitsToSingle(BinaryPrimitives.ReadInt32BigEndian(span)),_=>BitConverter.Int64BitsToDouble(BinaryPrimitives.ReadInt64BigEndian(span))}; + double value=raw*factor+zero;if(!double.IsFinite(value)||Math.Abs(value)>float.MaxValue)throw new InvalidDataException("Nonfinite color preview"); + int channel=pattern[((dy+oy)%2)*2+(dx+ox)%2] switch{'R'=>0,'G'=>1,_=>2};sums[channel][y/step*ow+x/step]+=value; + } + } + float[][] channels=[new float[ow*oh],new float[ow*oh],new float[ow*oh]]; + for(int y=0;y diff=[];for(int y=0;y(double)v));for(int i=0;idisplay.ChromaThreshold?1-Math.Pow(display.ChromaThreshold/maximum,2):0; + double level=Math.Max(.001,display.Luminance.Plane.Pixels[i]-display.Luminance.Black); + // Keep the linked luminance and scale all channels together into gamut. + // Bright star cores tend to neutral white, without clipped colored rings. + double scale=maximum>0?Math.Min(.6*certainty*mono[i]/level,Math.Min(.45*mono[i],255-mono[i])/maximum):0; + for(int c=0;c<3;c++)output[4*i+(2-c)]=(byte)Math.Clamp(mono[i]+scale*display.Chroma[c][i],0,255); + output[4*i+3]=255; + } + return output; + } + public static string PathFor(string directory,Frame frame)=>Path.Combine(directory,"previews",frame.Id+"-color1.bin"); + public static void Write(ColorPreviewPlane color,string path,Frame frame) + { + Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(path))!);string temp=path+".tmp"; + try + { + using(var stream=File.Create(temp)) + { + using(var header=new BinaryWriter(stream,System.Text.Encoding.UTF8,true)){header.Write(Magic);header.Write(frame.Length);header.Write(frame.Modified);header.Write(color.Width);header.Write(color.Height);} + using var compressed=new DeflateStream(stream,CompressionLevel.Fastest,true); + using var writer=new BinaryWriter(compressed); + foreach(var channel in new[]{color.Red,color.Green,color.Blue}) + {if(BitConverter.IsLittleEndian)compressed.Write(MemoryMarshal.AsBytes(channel.AsSpan()));else foreach(float value in channel)writer.Write(value);} + } + File.Move(temp,path,true); + } + finally{if(File.Exists(temp))File.Delete(temp);} + } + public static ColorPreviewPlane Read(string path,Frame frame) + { + using var stream=File.OpenRead(path);using var header=new BinaryReader(stream,System.Text.Encoding.UTF8,true); + if(header.ReadInt32()!=Magic||header.ReadInt64()!=frame.Length||header.ReadInt64()!=frame.Modified)throw new InvalidDataException("Color preview source fingerprint changed"); + int w=header.ReadInt32(),h=header.ReadInt32();if(w<=0||h<=0||(long)w*h>2_000_000)throw new InvalidDataException("Color preview dimensions exceed safety budget"); + float[][] channels=[new float[w*h],new float[w*h],new float[w*h]];using var compressed=new DeflateStream(stream,CompressionMode.Decompress);using var reader=new BinaryReader(compressed); + foreach(var channel in channels) + {if(BitConverter.IsLittleEndian)compressed.ReadExactly(MemoryMarshal.AsBytes(channel.AsSpan()));else for(int i=0;i!float.IsFinite(v)))throw new InvalidDataException("Nonfinite color preview");} + return new(w,h,channels[0],channels[1],channels[2]); + } +} diff --git a/src/AstroFrame.Engine/PreviewRenderer.cs b/src/AstroFrame.Engine/PreviewRenderer.cs index 4fec40e..e43ce54 100644 --- a/src/AstroFrame.Engine/PreviewRenderer.cs +++ b/src/AstroFrame.Engine/PreviewRenderer.cs @@ -3,7 +3,8 @@ using System.Runtime.InteropServices; namespace AstroFrame.Engine; public sealed record PreviewPlane(int Width,int Height,float[] Pixels); -public sealed record PreviewDisplay(PreviewPlane Plane,double Black,double White,double Mid); +public sealed record PreviewDisplay(PreviewPlane Plane,double Black,double White,double Mid,bool Diffuse=false); +public enum PreviewMode { Frame, Nebula, Asinh, Color } /// Display-only area reduction and screen transfer. Never used by a quality detector. public static class PreviewRenderer { @@ -21,20 +22,54 @@ public static class PreviewRenderer } public static byte[] Render(PreviewPlane image,double target=.18,bool nebula=false) =>Render(Prepare(image,nebula),target); - public static PreviewDisplay Prepare(PreviewPlane image,bool nebula=false) + public static PreviewDisplay Prepare(PreviewPlane image,bool nebula=false,CancellationToken ct=default) { - var plane=nebula?Reduce(new(image.Width,image.Height,image.Pixels,1),2):image; + ct.ThrowIfCancellationRequested();var plane=nebula?Diffuse(image,ct):image; var values=plane.Pixels.Select(v=>(double)v).ToArray();double median=Robust.Median(values); List differences=[];for(int y=0;y0?Math.Asinh(strength*v)/Math.Asinh(strength):Math.Pow(v,Math.Log(t)/Math.Log(mid))):(m-1)*v/((2*m-1)*v-m);output[i]=(byte)Math.Clamp(255*result,0,255);} return output; } + static double AsinhStrength(double mid,double target) + { + if(mid>=target)return 0;double lo=.001,hi=1e10; + for(int n=0;n<64;n++){double k=(lo+hi)/2;if(Math.Asinh(k*mid)/Math.Asinh(k) samples=stackalloc float[9]; + for(int y=0;y check) + { + string directory=Path.Combine(Path.GetTempPath(),"AstroFrame-color-"+Guid.NewGuid());Directory.CreateDirectory(directory); + try + { + const int size=128;ColorPreviewPlane? last=null;Frame? frame=null; + foreach(string pattern in new[]{"RGGB","GRBG","GBRG","BGGR"})foreach(var offset in new[]{(X:0,Y:0),(X:1,Y:0),(X:0,Y:1),(X:1,Y:1)}) + { + float[] pixels=new float[size*size];for(int y=0;y600,'G'=>1000,_=>1400}; + string path=Path.Combine(directory,$"{pattern}-{offset.X}-{offset.Y}.fit");ImageRegression.WriteFits(path,pixels,size,size,0,pattern,offset.X,offset.Y); + var color=ColorPreview.ReadFits(path)!;bool correct=color.Red.All(v=>v==600)&&color.Green.All(v=>v==1000)&&color.Blue.All(v=>v==1400); + check(correct,$"Bayer color channels respect {pattern} with offsets {offset.X},{offset.Y}"); + check(Fits.Read(path).Pixels.All(v=>v==1000),$"color support preserves analysis grayscale for {pattern} with offsets {offset.X},{offset.Y}"); + last=color;frame=Fits.Inspect(path); + } + byte[] sourceHash=SHA256.HashData(File.ReadAllBytes(frame!.Path));string cache=ColorPreview.PathFor(directory,frame!);ColorPreview.Write(last!,cache,frame!);var restored=ColorPreview.Read(cache,frame!); + check(restored.Red.SequenceEqual(last!.Red)&&restored.Green.SequenceEqual(last.Green)&&restored.Blue.SequenceEqual(last.Blue),"color caches retain linear RGB samples without losing channel order"); + var neutral=ColorPreview.Render(ColorPreview.Prepare(restored)); + check(Enumerable.Range(0,neutral.Length/4).All(i=>neutral[i*4]==neutral[i*4+1]&&neutral[i*4+1]==neutral[i*4+2]),"sky neutralization does not turn a constant colored pedestal into false nebula color"); + check(sourceHash.SequenceEqual(SHA256.HashData(File.ReadAllBytes(frame.Path))),"color reading, preparing, rendering and caching preserve source FITS bytes"); + bool refused=false;try{ColorPreview.Read(cache,new Frame{Length=frame.Length+1,Modified=frame.Modified});}catch(InvalidDataException){refused=true;} + check(refused,"changed sources invalidate color caches independently of quality data"); + const int w=96,h=96;var random=new Random(1902);float[][] channels=[new float[w*h],new float[w*h],new float[w*h]]; + for(int y=0;youtput[i*4+2]>output[i*4]+30&&output[i*4+2]>output[i*4+1]+30)>20,"color nebula preserves a real red diffuse signal through the linked stretch"); + var extremes=ColorPreview.Render(new(new(new(2,1,[0,10]),0,10,.5,true),[[100,100],[-50,-50],[-50,-50]],1)); + check(extremes.Take(3).All(v=>v==0)&&extremes.Skip(4).Take(3).All(v=>v==255),"linked color stays neutral at black and white instead of clipping individual channels"); + check(channels[0].SequenceEqual(input)&&Enumerable.Range(0,w*h).All(i=>output[i*4+3]==255),"color display leaves linear channels untouched and emits opaque pixels"); + using(var cancel=new CancellationTokenSource()){cancel.Cancel();bool cancelled=false;try{ColorPreview.ReadFits(frame.Path,cancel.Token);}catch(OperationCanceledException){cancelled=true;}check(cancelled,"color FITS reading cancels before processing rows");} + string mono=Path.Combine(directory,"mono.fit");ImageRegression.WriteFits(mono,Enumerable.Repeat(1000f,128*128).ToArray(),128,128,0); + check(ColorPreview.ReadFits(mono)==null,"monochrome FITS files never acquire fabricated color channels"); + string invalid=Path.Combine(directory,"invalid.fit");ImageRegression.WriteFits(invalid,Enumerable.Repeat(1000f,128*128).ToArray(),128,128,0,"XXXX"); + check(ColorPreview.ReadFits(invalid)==null,"unknown Bayer layouts fall back to grayscale instead of guessing color"); + } + finally{Directory.Delete(directory,true);} + } +} diff --git a/tests/AstroFrame.Validation/ImageRegression.cs b/tests/AstroFrame.Validation/ImageRegression.cs index 9d89a35..7219f6e 100644 --- a/tests/AstroFrame.Validation/ImageRegression.cs +++ b/tests/AstroFrame.Validation/ImageRegression.cs @@ -60,11 +60,11 @@ static class ImageRegression } finally{Directory.Delete(directory,true);} } - internal static void WriteFits(string path,float[] pixels,int width,int height,int n) + internal static void WriteFits(string path,float[] pixels,int width,int height,int n,string bayer="",int offsetX=0,int offsetY=0) { string Card(string key,string value)=>(key.PadRight(8)+"= "+value).PadRight(80); string date=new DateTime(2026,9,20,8,0,0,DateTimeKind.Utc).AddSeconds(n*30).ToString("yyyy-MM-ddTHH:mm:ss",CultureInfo.InvariantCulture); - string header=Card("SIMPLE","T")+Card("BITPIX","-32")+Card("NAXIS","2")+Card("NAXIS1",width.ToString())+Card("NAXIS2",height.ToString())+Card("EXPTIME","30")+Card("OBJECT","'Synthetic field'")+Card("DATE-OBS",$"'{date}'")+"END".PadRight(80); + string header=Card("SIMPLE","T")+Card("BITPIX","-32")+Card("NAXIS","2")+Card("NAXIS1",width.ToString())+Card("NAXIS2",height.ToString())+Card("EXPTIME","30")+Card("OBJECT","'Synthetic field'")+Card("DATE-OBS",$"'{date}'")+(bayer==""?"":Card("BAYERPAT",$"'{bayer}'")+Card("XBAYROFF",offsetX.ToString())+Card("YBAYROFF",offsetY.ToString()))+"END".PadRight(80); using var stream=File.Create(path);stream.Write(Encoding.ASCII.GetBytes(header.PadRight((header.Length+2879)/2880*2880))); byte[] row=new byte[width*4];for(int y=0;y diff=[];for(int y=0;yv/255.0))<.25,"preview transfer keeps background grain subordinate to the image"); check(untouched.SequenceEqual(pixels),"preview reduction, stretching and nebula mode never alter analysis pixels"); - check(frame.Max()>frame[0]+80&&diffuse.Lengthframe[0]+80&&diffuse.Length==frame.Length&&!diffuse.SequenceEqual(frame),"frame preview preserves conspicuous stars and diffuse view retains the full preview geometry"); + float[] filament=new float[w*h];random=new Random(8461); + for(int y=0;y core=[],sky=[]; + for(int y=20;y20,"nebula preview makes a faint narrow filament visible above adjacent sky"); + check(original.SequenceEqual(filament),"faint-detail smoothing never modifies the original linear preview samples"); + var alternate=PreviewRenderer.Render(enhanced,.18,true);var brighter=PreviewRenderer.Render(enhanced,.30,true); + check(!alternate.SequenceEqual(enhancedPixels)&&alternate.Zip(brighter).All(pair=>pair.Second>=pair.First),"asinh offers a distinct monotonic stretch and responds to brightness adjustments"); + var highMedian=new PreviewDisplay(new(1,1,[.7f]),0,1,.7,true); + check(Math.Abs(PreviewRenderer.Render(highMedian,.18,true)[0]-255*.25)<2&&PreviewRenderer.Render(highMedian,.30,true)[0]>PreviewRenderer.Render(highMedian,.18,true)[0],"asinh brightness remains adjustable when the source median already exceeds the display target"); + var flat=PreviewRenderer.Prepare(new(32,32,Enumerable.Repeat(1000f,1024).ToArray()),true); + check(PreviewRenderer.Render(flat).Distinct().Count()==1&&PreviewRenderer.Render(flat,.18,true).Distinct().Count()==1,"constant fields remain constant without invented diffuse structure"); + using(var cancel=new CancellationTokenSource()){cancel.Cancel();bool cancelled=false;try{PreviewRenderer.Diffuse(new(w,h,filament),cancel.Token);}catch(OperationCanceledException){cancelled=true;}check(cancelled,"diffuse preview preparation cancels while smoothing");} string path=Path.Combine(Path.GetTempPath(),"AstroFrame-preview-"+Guid.NewGuid()+".bin");var f=new Frame{Length=7654,Modified=4321}; try { diff --git a/tests/AstroFrame.Validation/Program.cs b/tests/AstroFrame.Validation/Program.cs index b814ae0..5a792a3 100644 --- a/tests/AstroFrame.Validation/Program.cs +++ b/tests/AstroFrame.Validation/Program.cs @@ -130,4 +130,5 @@ QualityRegression.Run(Check); OverlayRegression.Run(Check); PreviewRegression.Run(Check); StellarDetailRegression.Run(Check); +ColorPreviewRegression.Run(Check); Console.WriteLine($"{passed} checks passed. Synthetic tests validate mechanics, not astrophotography stack quality.");