diff --git a/.gitignore b/.gitignore
index fb7a75c..b56b024 100644
--- a/.gitignore
+++ b/.gitignore
@@ -8,3 +8,4 @@ artifacts/
TestResults/
.vscode
site/
+.claude
\ No newline at end of file
diff --git a/CLAUDE.md b/CLAUDE.md
index a56cf98..aeb2a6a 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -42,8 +42,8 @@ Source layout under `src/OrthoStreamXP/`. Sub-folders are for navigation only: *
- `Paging/`: `PagingModel`, `PagingMeasurements`, `PagingCalibration`.
- `Prefetch/`: `LoadAheadPrefetcher`, `PrefetchPlanner`, `MipWarmer`.
- `Aircraft/`: `AircraftPositionListener` (X-Plane UDP), `ViewTracker`, `SceneryLoads`.
- - `Colour/`: `ColourMatcher` (evens patchwork), `SeasonClock` (seasonal tint by simulated date/location).
-- `Textures/` — imagery to DDS: `TextureBuilder` (fetch → stitch → resize → mipmaps → BC1 encode → atomic write; own encoder, SkiaSharp is decode-only), `TextureQuality`, `Images` at the root; `Tiles/` (`TileSource`/`TileStore`: download + cache), `Dds/`, `Scheduling/` (priority gates), `Seasons/`, `Colour/` (`ColourMatch`, `Exposure`, `ColourTable` = the shared BC1 lookup-table recolouring, `PhotoColours` = match → season → exposure as X-Plane reads, also used by the Settings preview).
+ - `Colour/`: `SeasonClock` (seasonal tint by simulated date/location), `ObservedSeasons` (loads the satellite record per ~500 km tile for `season = satellite`).
+- `Textures/` — imagery to DDS: `TextureBuilder` (fetch → stitch → resize → sharpen → mipmaps → BC1 encode → atomic write; SkiaSharp is decode-only), `TextureQuality`, `Images`, `Sharpening` (unsharp mask on brightness, not a setting: 100 % for the areas' textures below ZL18, 60 % for the airports' ZL18 and finer) at the root; `Tiles/` (`TileSource`/`TileStore`: download + cache; the low-zoom base is zoom 13 and coarser because Bing's zoom 12 is other, lighter imagery; a tile every provider definitively lacks throws `TileNotAvailableException`, and `TextureBuilder` then makes it from a parent at hand, never coarser than 13), `Dds/` (`Dds` layout/encode/decode; mip levels by `MipFilter` = 2x2 averages in linear light; BC1 by `IspcBc1` = Intel's ISPC `ispc_texcomp.dll` from `native/ispc_texcomp/` (checked in, rebuilt by its `build.ps1`), loaded from the exe's folder, with one-colour blocks and four-colour mode fixed after it and every other block's colours refined by least squares (`Bc1Refinement`); `Dds.EncodeRangeFit` is the fallback without the DLL), `Scheduling/` (priority gates), `Seasons/` (`SeasonModel` calendar, `ObservedSeason` + `GreennessYear`: grass and fields by a place's yearly NDVI against its greenest month, trees by the calendar), `Vegetation/` (`VegetationSource`: NASA GIBS monthly VIIRS NDVI, downloaded and kept under the low-zoom base; `VegetationTile`, `NdviPalette`), `Colour/` (`Exposure`, `Contrast` (fixed 60 % S-curve, always on, not a setting), `ColourTable` = the shared BC1 lookup-table recolouring, `PhotoColours` = season → contrast → exposure as one table (rounded to 565 once) applied as X-Plane reads, also used by the Settings preview).
- `Setup/` — `Settings/` (`SettingsDocument`, ini under `%LOCALAPPDATA%\OrthoStreamXP`, `QualityPreset`, `ConnectionTest`), `Cache/` (inventory, areas, eviction), `Packages/` (downloads AutoOrtho's mesh regions from GitHub into the packages folder as `OrthoStream_*` packages: `MeshCatalog`, `AssetDownload`, `ZipUnpacker`, `OverlayPackage`, `RegionInstaller`), `Installation/` (`AppPaths`, `AppUpdates`, `LegacyNames` migrating older settings/cache locations, `SystemCheck`, Velopack hooks).
- `Tuning/` — flight reports, facts and the preset/setting recommendations.
- Logs go to `%LOCALAPPDATA%\OrthoStreamXP\logs`.
diff --git a/README.md b/README.md
index f512055..742c04a 100644
--- a/README.md
+++ b/README.md
@@ -26,13 +26,14 @@ Traditional photo scenery often requires downloading and building large areas be
- **Less disk space wasted** — keep the areas you fly and automatically remove older scenery when your cache reaches its limit.
- **Better scenery ahead** — OrthoStreamXP follows your aircraft and downloads upcoming areas before you reach them.
- **Simple quality settings** — choose Balanced, Sharp, Ultra, or Extra without learning dozens of technical parameters.
+- **Sharp, crisp textures** — up to 8192 px, keeping all the detail of the imagery, sharpened a little and given a touch of contrast, as aerial photos are often hazy.
- **Settings that adapt to your setup** — test your connection before the first flight to get a recommended preset, and after a sufficiently long flight, get recommendations based on how the scenery performed on your PC and internet connection. You decide whether to apply them.
-- **Even colours** — optionally soften the patchwork look where neighbouring photos were taken on different days, so a grey, hazy patch stands out less.
-- **Seasonal colours** — optionally give summer imagery a more autumnal or winter appearance, based on the simulated date and location.
+- **Seasonal colours** — optionally give summer imagery a more autumnal or winter appearance, based on the simulated date and location, with grass and fields optionally coloured by NASA's satellite record of how green each place really was.
- **Clean photos up close** — X-Plane's procedural grass and dirt speckles are kept off the aerial photos by default, or faded to the strength you like, without changing your scenery packages.
- **Towns lit at night** — optionally give the photo scenery street lamps and the light of the houses along X-Plane's roads, so towns glow after dark as on X-Plane's own scenery. You can also skip the detailed photos at night to save downloads, keeping the lights.
- **Exposure and a live preview** — tone down photos that look too bright next to X-Plane's own scenery, and see any colour change on a photo from your cache before you fly.
- **See what happened during your flight** — review download performance, scenery loading, and your flight route.
+- **Your scenery list, without Notepad** — switch X-Plane's scenery packages on or off and drag them into order on the X-Plane Custom Scenery page, and leave any of your photo scenery packages out of a flight with one switch on the Home page.
### Designed for everyday flying
@@ -87,7 +88,9 @@ OrthoStreamXP provides five presets:
- **Sharp** — the recommended starting point for most systems.
- **Ultra** — for systems with more graphics memory available.
- **Extra** — the highest preset, intended for systems with greater resources.
-- **Dynamic** — Extra near the ground, Sharp from 5,000 ft and Balanced from 25,000 ft above it. High up, X-Plane still asks for full detail it cannot show, so Dynamic saves about half the downloads in a climb and cruise. On a descent it returns to full detail early, before the ground comes close.
+- **Dynamic** — Extra near the ground, Sharp from 5,000 ft and Balanced from 25,000 ft above it. High up, X-Plane still asks for full detail it cannot show, so Dynamic saves about half the downloads in a climb and cruise. On a descent it returns to full detail early, before the ground comes close. Its **Base** can be Ultra or Sharp instead of Extra, for a slower connection.
+
+Each preset also has a **Resolution**: **Full** keeps all the detail of the imagery, **Medium** halves the textures away from airports and **Low** halves them all, to fit a smaller graphics card from the same imagery.
You can change presets in Settings. OrthoStreamXP also reports graphics memory usage from your flights and warns when the measured scenery requirements exceed your card's available memory.
@@ -98,7 +101,7 @@ After flights of at least 10 minutes, OrthoStreamXP may suggest adjustments base
The Cache page helps you manage the imagery stored on your computer.
- Set a cache limit from 25 GB up to 1 TB.
-- View cached areas on a map.
+- View cached areas on a full-width map you can zoom and drag.
- Select and delete areas you no longer need.
- Identify areas you have not flown over recently.
@@ -108,7 +111,7 @@ When the cache exceeds its limit, OrthoStreamXP removes older areas automaticall
Most aerial imagery was captured during warmer months, so a winter flight can otherwise look unexpectedly green.
-Enable **Seasons** to adjust the appearance of vegetation and fields according to X-Plane's simulated date and the location you're flying over.
+Turn on **Colour the scenery for the season** (Settings › Colours) to adjust the appearance of vegetation and fields according to X-Plane's simulated date and the location you're flying over.
- **Spring:** fresh greens return.
- **Summer:** the imagery as it was photographed.
@@ -117,6 +120,8 @@ Enable **Seasons** to adjust the appearance of vegetation and fields according t
Water, roads, buildings, rock, and sand retain their original colours. Seasonal colouring does not generate snow; snow remains part of X-Plane's weather.
+Choose **Satellite** as the season to colour the grass and fields by NASA's satellite record of the last year instead of the calendar alone: Atlantic and Mediterranean coasts stay green in a mild winter, fields dry out in a dry summer, and the tropics show their dry season. Trees keep the calendar. It downloads about 2 MB once a year for each area of about 500 km you fly over.
+
## Known limitations
OrthoStreamXP is currently in beta. Please keep the following in mind:
@@ -131,7 +136,7 @@ OrthoStreamXP is currently in beta. Please keep the following in mind:
## Imagery and licensing
-OrthoStreamXP is free software released under the **GNU General Public License v3 (GPL-3.0)**.
+OrthoStreamXP is free software released under the **GNU General Public License v3 (GPL-3.0)**. It includes Intel's [ISPC Texture Compressor](https://github.com/GameTechDev/ISPCTextureCompressor) (MIT) to encode textures.
The aerial imagery is provided by external services, including Bing Maps, Esri World Imagery, and Geoportal for Poland. The imagery is not part of the OrthoStreamXP software and remains subject to each provider's terms of use.
diff --git a/build-user-guide.ps1 b/build-user-guide.ps1
index 438bee1..1db8e73 100644
--- a/build-user-guide.ps1
+++ b/build-user-guide.ps1
@@ -24,7 +24,7 @@ if (-not $browser) { throw 'Google Chrome or Microsoft Edge is needed to print t
# The order of the guide's contents (docs\README.md). The pages keep their names so that pandoc's --file-scope
# turns the links between them (settings.md#quality) into links inside the PDF.
-$pages = 'README', 'installation', 'first-setup', 'flying', 'settings', 'cache', 'packages', 'troubleshooting', 'faq'
+$pages = 'README', 'installation', 'first-setup', 'flying', 'settings', 'cache', 'packages', 'custom-scenery', 'troubleshooting', 'faq'
$work = 'artifacts\user-guide'
if (Test-Path $work) { Remove-Item $work -Recurse -Force }
New-Item -ItemType Directory $work | Out-Null
diff --git a/docs/OrthoStreamXP-UserGuide.pdf b/docs/OrthoStreamXP-UserGuide.pdf
index e83e8a6..261a096 100644
Binary files a/docs/OrthoStreamXP-UserGuide.pdf and b/docs/OrthoStreamXP-UserGuide.pdf differ
diff --git a/docs/README.md b/docs/README.md
index 988bbce..0eef53d 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -12,8 +12,9 @@ OrthoStreamXP adds real-world aerial photos to your X-Plane 12 scenery while you
4. [Settings](settings.md): quality and ground detail, folders, downloads, colours, seasons and exposure, night lights and photos at night.
5. [Cache](cache.md): how much disk space the scenery uses and how to free it.
6. [Packages](packages.md): downloading the ground mesh of a whole region, the quickest way to get scenery packages.
-7. [Troubleshooting](troubleshooting.md): common problems, the log, updates, uninstalling and reporting a bug.
-8. [Questions and answers](faq.md): what OrthoStreamXP does and does not do, choosing the packages folder, switching from AutoOrtho.
+7. [X-Plane Custom Scenery](custom-scenery.md): switching X-Plane's scenery packages on or off and changing their order.
+8. [Troubleshooting](troubleshooting.md): common problems, the log, updates, uninstalling and reporting a bug.
+9. [Questions and answers](faq.md): what OrthoStreamXP does and does not do, choosing the packages folder, switching from AutoOrtho.
## The short version
diff --git a/docs/cache.md b/docs/cache.md
index 7ee69c4..e1d9b4f 100644
--- a/docs/cache.md
+++ b/docs/cache.md
@@ -18,6 +18,8 @@ The cache holds the pictures OrthoStreamXP downloads and the textures it builds.
The map shows each 1° × 1° area you have flown, pictured from its own textures. Faded squares were not flown for a month; the cache limit removes those first.
+The map uses the full width of the window. Scroll to zoom in and out around the pointer, and drag to move the map. The buttons at its side zoom in, zoom out and **Show all areas**. Latitude and longitude lines, labelled along the top and left edges, help you find a place; they come closer together as you zoom in.
+
To free space by hand:
1. Click the areas you want to remove, or click **Select not flown for a month**.
@@ -32,10 +34,12 @@ Areas can be deleted only while OrthoStreamXP is stopped, because X-Plane may be
Each quality preset keeps its textures in its own folder, so switching presets never throws textures away. This list shows how much each one takes:
- **One row per preset you have flown with** (for example *Extra*), with its texture sizes and number of files. The preset you use now is marked **In use**. Delete a preset you no longer use to free its space.
+- A preset used at a lower [resolution](settings.md#resolution) keeps those textures in a folder of their own, listed as, for example, *Ultra, Medium resolution*.
+- When an update changes a preset's texture sizes (as 1.5.0 did), the textures built before it stay in their old folder. They are listed as a second row for the same preset, with the old sizes, and OrthoStreamXP no longer uses them, so you can delete that row.
- **Low-zoom base:** coarse pictures that distant scenery is drawn from. All presets share it. If you delete it, distant scenery is a plain colour at the start of a flight until these pictures are downloaded again.
- **Logs:** the log files of earlier runs.
- A folder left by an older version of OrthoStreamXP, from before each preset had its own folder, is listed too. OrthoStreamXP no longer uses it, so you can delete it.
Each row has a folder button that opens it in Explorer and a bin button that deletes it after you confirm.
-Next: [Troubleshooting](troubleshooting.md)
+Next: [Packages](packages.md)
diff --git a/docs/custom-scenery.md b/docs/custom-scenery.md
new file mode 100644
index 0000000..44ec0ff
--- /dev/null
+++ b/docs/custom-scenery.md
@@ -0,0 +1,40 @@
+# X-Plane Custom Scenery
+
+[User guide](README.md) › X-Plane Custom Scenery
+
+X-Plane keeps a list of its scenery packages in `Custom Scenery\scenery_packs.ini`. A package higher in the list covers the ones below it: an airport above the photo scenery is drawn on top of the photos. The **X-Plane Custom Scenery** page in the sidebar shows this list, so you can change it without editing the file by hand.
+
+
+
+## The list
+
+- The packages are listed in the file's order, **highest priority first**; the line above the list names the file. Under each name is its folder.
+- While OrthoStreamXP runs, the packages it shows to X-Plane are marked **OrthoStreamXP**.
+- The page needs the **X-Plane folder** to be set in [Settings › Folders](settings.md#folders); until then it says *Choose your X-Plane folder first*. If X-Plane has never started with this folder, the list is empty: X-Plane writes the file the first time it starts.
+- **Open the folder** opens X-Plane's `Custom Scenery` folder in Explorer. **Refresh** reads the file again, for example after you installed scenery while the page was open.
+
+## Switching packages on or off
+
+The switch at the end of each row turns a package on or off in X-Plane. A package switched off stays in its folder and in the list; X-Plane just does not load it. This is the same as X-Plane's own `SCENERY_PACK_DISABLED` lines in the file.
+
+## Changing the order
+
+Drag a package by the handle at the start of its row and drop it where you want it: the other rows move apart to show where it lands. Higher in the list means drawn on top.
+
+Leave the photo scenery near the end, below airports and overlays. With **Keep the photo scenery below airports and overlays** on (see [Settings › Other](settings.md#other)), OrthoStreamXP moves its packages back to the end at every start anyway.
+
+## When changes apply
+
+- The list can be changed **only while OrthoStreamXP is stopped**: starting and stopping change the file too. While it runs, the page says *OrthoStreamXP is running: stop it to change the list.* It shows the list as it is, with the switches greyed out and no drag handles.
+- X-Plane reads the list when it starts, so a change shows from **X-Plane's next start**.
+- Every change is written straight into `scenery_packs.ini`. The other lines of the file stay as they are.
+
+
+
+## The packages OrthoStreamXP adds
+
+When you click **Start**, OrthoStreamXP adds its packages to the end of the list. When you click **Stop**, it takes out again the ones it added, because their folders are gone from `Custom Scenery` until the next start. A package that was already in the list before the start (for example from an earlier version of OrthoStreamXP) stays where it is.
+
+To leave one of your own scenery packages out of OrthoStreamXP's photo scenery, use its switch under **Scenery packages** on the Home page instead (see [Flying › Leaving a package out](flying.md#leaving-a-package-out)).
+
+Next: [Troubleshooting](troubleshooting.md)
diff --git a/docs/faq.md b/docs/faq.md
index 58ffd6b..e923a9b 100644
--- a/docs/faq.md
+++ b/docs/faq.md
@@ -25,7 +25,7 @@ Each scenery file (`.dsf`) says exactly which photo texture goes on which part o
All three put photos on scenery packages, so the base packages are the same. OrthoStreamXP was written to avoid the problems of the others:
- **Speed.** A new area loads in a few minutes (each preset card shows an estimate), and areas you have flown before load from the cache at once.
-- **Quality for free.** There is no paid tier. Textures go up to 4096 px and the imagery up to zoom 19, with no limit on the zoom level or the picture size.
+- **Quality for free.** There is no paid tier. Textures go up to 8192 px and the imagery up to zoom 19, with no limit on the zoom level or the picture size.
- **Settings tuned for you.** **Test my connection** chooses the quality and the number of downloads, and after each flight OrthoStreamXP suggests changes from what it measured (see [Flying](flying.md#tuning-suggestions)).
### I already have ZL17/ZL18 photo scenery on disk. What do I gain?
@@ -81,7 +81,7 @@ No. Move them anywhere else on your PC, for example `D:\OrthoPackages`. OrthoStr
1. Close AutoOrtho.
2. Move your AutoOrtho scenery packages out of `X-Plane 12\Custom Scenery` to any folder on your PC.
-3. Open `X-Plane 12\Custom Scenery\scenery_packs.ini` and remove the lines for the AutoOrtho packages.
+3. Open `X-Plane 12\Custom Scenery\scenery_packs.ini` and remove the lines for the AutoOrtho packages. If you would rather not edit the file, switch them off on OrthoStreamXP's [X-Plane Custom Scenery](custom-scenery.md) page instead.
4. Open OrthoStreamXP **without** starting the scenery. In **Settings › Folders**, set the **Scenery packages folder** to the new place.
5. Click **Start and fly** (or **Start**, then start X-Plane).
@@ -90,7 +90,9 @@ No. Move them anywhere else on your PC, for example `D:\OrthoPackages`. OrthoStr
1. Your packages appear in `X-Plane 12\Custom Scenery`, with the photos added. The packages on disk stay unchanged.
2. OrthoStreamXP adds them to the end of `scenery_packs.ini`, so airports and overlays stay above them. The previous file is kept as `scenery_packs.ini.bak`.
-When you stop OrthoStreamXP, the packages disappear from `Custom Scenery` again.
+When you stop OrthoStreamXP, the packages disappear from `Custom Scenery` again, and the lines it added to `scenery_packs.ini` at the start are taken out.
+
+Packages switched off under **Scenery packages** on the Home page are left out (see [Flying › Leaving a package out](flying.md#leaving-a-package-out)).
### It downloaded a few pictures and then nothing, and the ground looks like X-Plane's own scenery.
diff --git a/docs/first-setup.md b/docs/first-setup.md
index 99bf2a1..ccc13ce 100644
--- a/docs/first-setup.md
+++ b/docs/first-setup.md
@@ -71,14 +71,16 @@ D:\OrthoPackages\
This is where OrthoStreamXP keeps the pictures it downloads and the textures it builds, so areas you fly again load at once.
- Click **Browse…** or type a full path, such as `D:\OrthoStreamXP\Cache`.
-- Choose a folder on a fast SSD with plenty of free space. The page shows how much space is free on that drive. Each new 1° × 1° area takes up to about 2 GB at Balanced, 8 GB at Sharp and 30 GB at Ultra or Extra.
+- Choose a folder on a fast SSD with plenty of free space. The page shows how much space is free on that drive. A new 1° × 1° area, with every texture in it built, takes up to about 8 GB at Balanced, 31 GB at Sharp and 125 GB at Ultra or Extra (Dynamic takes its base's figure), at Full resolution; most flights build only part of an area. [Settings › Folders](settings.md#folders) shows the figure for the quality you choose.
- You can change the folder or set a size limit later on the [Cache page](cache.md).
## 5. Quality

-Pick how sharp the ground should be: **Balanced**, **Sharp**, **Ultra**, **Extra** or **Dynamic** (Extra near the ground, less detail high up, where it cannot be seen). Each card shows the texture size, the imagery zoom level, the metres per pixel, and roughly how long a new area takes to load. See [Settings › Quality](settings.md#quality) for a comparison.
+Pick how sharp the ground should be: **Balanced**, **Sharp**, **Ultra**, **Extra** or **Dynamic** (its **Base** preset near the ground, Extra unless you choose Ultra or Sharp, and less detail high up, where it cannot be seen). Each card shows the texture size, the imagery zoom level, the metres per pixel, roughly how long a new area takes to load, and how much graphics memory the photo textures take. See [Settings › Quality](settings.md#quality) for a comparison.
+
+Each card also has a **Resolution** box: **Full** (the default) keeps all the detail; **Medium** and **Low** shrink the textures to save graphics memory, from the same imagery (see [Settings › Resolution](settings.md#resolution)). The other cards also say whether they would suit your PC too, or why not; a connection test makes that more exact.
**Not sure?** Click **Test my connection** (it says **Test again** if you have tested before). OrthoStreamXP downloads real pictures for about 30 seconds, then:
diff --git a/docs/flying.md b/docs/flying.md
index c939d59..5ac3eec 100644
--- a/docs/flying.md
+++ b/docs/flying.md
@@ -31,10 +31,25 @@ From top to bottom:
- **Status card.** Shows whether OrthoStreamXP is stopped, starting, ready (*Photo scenery is ready*) or in use (*Flying with photo scenery*). The **Start** button becomes **Stop** while it runs. The dot at the bottom of the sidebar shows the same state on every page. Above it, the theme button switches the window between the Windows theme, light and dark.
- **Notices.** Tuning suggestions, updates and problems appear here, each with a button for the next step.
- **Last flight.** A report on your most recent flight, shown while OrthoStreamXP is stopped (see below).
-- **Session figures** (*This session* while it runs, *Last session* after it stops): how many textures X-Plane got, how many of its reads got the real picture, how many textures are being built now, and the download speed or the number of picture tiles downloaded.
-- **X-Plane.** *Waiting for X-Plane* until X-Plane sends the aircraft position, then *Connected* with the aircraft's position and speed. *Paused or in the menu* means X-Plane has stopped sending it for now. There is nothing to set up in X-Plane: OrthoStreamXP finds it on the same PC by itself.
-- **Quality.** Your current preset, with a **Change quality** link.
-- **Scenery packages.** The packages shown in X-Plane while OrthoStreamXP runs.
+- **Session figures** (*This session* while it runs, *Last session* after it stops): *textures given to X-Plane*, how many were *ready before X-Plane asked*, how many are *being built now*, and the download speed with the picture tiles downloaded a second.
+- **X-Plane.** *Not connected* while OrthoStreamXP is stopped. Once it runs: *Waiting for X-Plane* until X-Plane sends the aircraft position, then *Connected* with the aircraft's position and speed. *Paused or in the menu* means X-Plane has stopped sending it for now. There is nothing to set up in X-Plane: OrthoStreamXP finds it on the same PC by itself.
+- **Quality.** Your current preset, with its base for Dynamic and its resolution when it is not Full (for example *Dynamic from Ultra* or *Ultra, Medium resolution*), and a **Change quality** link.
+- **Scenery packages.** The packages shown in X-Plane while OrthoStreamXP runs, each with a switch (see below).
+
+
+
+The sidebar on the left leads to the other pages: **Settings**, **Cache**, **Packages**, **X-Plane Custom Scenery**, **Log** and **About**. Near its bottom, **Support the project** opens the project's PayPal donation page.
+
+### Leaving a package out
+
+
+
+Each package under **Scenery packages** (at the bottom of Home) has a switch. Turn it off to leave that package out of the photo scenery: its row fades, X-Plane does not see it while OrthoStreamXP runs, but it stays in your scenery packages folder and keeps its textures in the cache. Turn it on again to bring it back. This is handy to leave out a region you are not flying today, or to test a flight without one of your packages.
+
+- The switches can be changed only while OrthoStreamXP is stopped, and a change applies from the next start. While it runs, the list shows the packages in use.
+- At least one region must stay on. An overlay package on its own (such as `OrthoStream_Overlays`, with roads, forests and buildings) has no ground to draw on, so OrthoStreamXP does not start with only overlays switched on.
+
+To switch any of X-Plane's scenery on or off, or to change its order, use the [X-Plane Custom Scenery](custom-scenery.md) page.
## During the flight
diff --git a/docs/images/about.png b/docs/images/about.png
index ebc551a..f6fcc62 100644
Binary files a/docs/images/about.png and b/docs/images/about.png differ
diff --git a/docs/images/cache-quality.png b/docs/images/cache-quality.png
index e4db934..96bab52 100644
Binary files a/docs/images/cache-quality.png and b/docs/images/cache-quality.png differ
diff --git a/docs/images/cache.png b/docs/images/cache.png
index 2dcd2e8..99e58e7 100644
Binary files a/docs/images/cache.png and b/docs/images/cache.png differ
diff --git a/docs/images/custom-scenery-running.png b/docs/images/custom-scenery-running.png
new file mode 100644
index 0000000..861184a
Binary files /dev/null and b/docs/images/custom-scenery-running.png differ
diff --git a/docs/images/custom-scenery.png b/docs/images/custom-scenery.png
new file mode 100644
index 0000000..e1f6b55
Binary files /dev/null and b/docs/images/custom-scenery.png differ
diff --git a/docs/images/home-packages.png b/docs/images/home-packages.png
new file mode 100644
index 0000000..573353f
Binary files /dev/null and b/docs/images/home-packages.png differ
diff --git a/docs/images/home-running.png b/docs/images/home-running.png
new file mode 100644
index 0000000..ff4e60d
Binary files /dev/null and b/docs/images/home-running.png differ
diff --git a/docs/images/home.png b/docs/images/home.png
index 2a6d4f8..17f45b3 100644
Binary files a/docs/images/home.png and b/docs/images/home.png differ
diff --git a/docs/images/log.png b/docs/images/log.png
index f6eb54b..f4d327c 100644
Binary files a/docs/images/log.png and b/docs/images/log.png differ
diff --git a/docs/images/packages-downloading.png b/docs/images/packages-downloading.png
index ba56d10..a8dc9a6 100644
Binary files a/docs/images/packages-downloading.png and b/docs/images/packages-downloading.png differ
diff --git a/docs/images/packages.png b/docs/images/packages.png
index ee4fd9a..d7feb6b 100644
Binary files a/docs/images/packages.png and b/docs/images/packages.png differ
diff --git a/docs/images/settings-colours.png b/docs/images/settings-colours.png
index 574c2f0..1b4ed77 100644
Binary files a/docs/images/settings-colours.png and b/docs/images/settings-colours.png differ
diff --git a/docs/images/settings-download.png b/docs/images/settings-download.png
index c37037e..8617e5b 100644
Binary files a/docs/images/settings-download.png and b/docs/images/settings-download.png differ
diff --git a/docs/images/settings-folders.png b/docs/images/settings-folders.png
index cef76d6..ed7bd75 100644
Binary files a/docs/images/settings-folders.png and b/docs/images/settings-folders.png differ
diff --git a/docs/images/settings-night.png b/docs/images/settings-night.png
index 379fa3f..33445aa 100644
Binary files a/docs/images/settings-night.png and b/docs/images/settings-night.png differ
diff --git a/docs/images/settings-other.png b/docs/images/settings-other.png
index 32b7344..ee94d35 100644
Binary files a/docs/images/settings-other.png and b/docs/images/settings-other.png differ
diff --git a/docs/images/settings-quality.png b/docs/images/settings-quality.png
index e12aee1..67f0599 100644
Binary files a/docs/images/settings-quality.png and b/docs/images/settings-quality.png differ
diff --git a/docs/images/settings-tuning.png b/docs/images/settings-tuning.png
index e32311d..cd48edf 100644
Binary files a/docs/images/settings-tuning.png and b/docs/images/settings-tuning.png differ
diff --git a/docs/images/setup-cache.png b/docs/images/setup-cache.png
index 664e955..904d7ad 100644
Binary files a/docs/images/setup-cache.png and b/docs/images/setup-cache.png differ
diff --git a/docs/images/setup-quality.png b/docs/images/setup-quality.png
index c4290cc..cb2a503 100644
Binary files a/docs/images/setup-quality.png and b/docs/images/setup-quality.png differ
diff --git a/docs/images/setup-ready.png b/docs/images/setup-ready.png
index f2a316e..368bb3b 100644
Binary files a/docs/images/setup-ready.png and b/docs/images/setup-ready.png differ
diff --git a/docs/images/setup-scenery-download.png b/docs/images/setup-scenery-download.png
index 2c840ee..cdf5421 100644
Binary files a/docs/images/setup-scenery-download.png and b/docs/images/setup-scenery-download.png differ
diff --git a/docs/images/setup-scenery.png b/docs/images/setup-scenery.png
index 57157bb..f1eba93 100644
Binary files a/docs/images/setup-scenery.png and b/docs/images/setup-scenery.png differ
diff --git a/docs/images/setup-welcome.png b/docs/images/setup-welcome.png
index 2a00344..88793d2 100644
Binary files a/docs/images/setup-welcome.png and b/docs/images/setup-welcome.png differ
diff --git a/docs/images/setup-xplane.png b/docs/images/setup-xplane.png
index 5fb8b04..9d5fd73 100644
Binary files a/docs/images/setup-xplane.png and b/docs/images/setup-xplane.png differ
diff --git a/docs/packages.md b/docs/packages.md
index 321da02..8102863 100644
--- a/docs/packages.md
+++ b/docs/packages.md
@@ -4,7 +4,7 @@
OrthoStreamXP streams photos onto scenery packages: the ground's shape (the mesh) for each area. The quickest way to get them is to download the mesh of a whole region, on the **Packages** page or in the **Scenery packages** step of the setup. You can also use packages of your own; keep them in a folder of their own (see [One folder per source](#one-folder-per-source)).
-
+
The meshes are downloaded from a public collection on [GitHub](https://github.com/kubilus1/autoortho-scenery). Six regions are offered:
@@ -43,7 +43,7 @@ Why:
OrthoStreamXP uses one scenery packages folder at a time, so you fly with one source at a time.
-The **Packages** page installs into the folder chosen at that moment, shown at the top of the page. Before you download a region, check that it is your folder for downloaded regions, not your own packages' folder. Don't have one yet? Choose a new, empty folder in [Settings › Folders](settings.md#folders), then install. Home warns that no scenery packages were found until the first region is in it.
+The **Packages** page installs into the folder chosen at that moment, shown at the top of the page; **Open the folder** opens it in Explorer, and **Refresh** reads the folder and the list of releases again. Before you download a region, check that it is your folder for downloaded regions, not your own packages' folder. Don't have one yet? Choose a new, empty folder in [Settings › Folders](settings.md#folders), then install. Home warns that no scenery packages were found until the first region is in it.
## Roads, forests and buildings
@@ -51,12 +51,15 @@ A square of a downloaded mesh no longer shows X-Plane's own roads, forests and b
## Downloading, stopping and resuming
-
+
- **Install** starts the download. While one region downloads, the others wait: one install runs at a time. The progress and speed show under the region.
- **Stop** stops it. What was downloaded is kept: **Resume** continues from there, even after OrthoStreamXP was closed.
- A region is used from OrthoStreamXP's next start, and never half-installed: it appears in your packages folder only when all of it is there.
- When a newer release comes out, the region says **Update available**. Updating downloads it again in full.
- **Delete** removes the region and its roads, forests and buildings. Another region's stay.
+- To fly without a region for a while, without deleting it, switch it off under **Scenery packages** on the Home page (see [Flying › Leaving a package out](flying.md#leaving-a-package-out)).
You can install a new region while OrthoStreamXP runs. Updating or deleting a region needs OrthoStreamXP stopped, because X-Plane has its files open while it runs.
+
+Next: [X-Plane Custom Scenery](custom-scenery.md)
diff --git a/docs/settings.md b/docs/settings.md
index 750f774..edb636f 100644
--- a/docs/settings.md
+++ b/docs/settings.md
@@ -19,32 +19,61 @@ Choose how sharp the ground is. Each preset comes with settings tested for it an
| Preset | Textures | Imagery zoom | Resolution | Best for |
|---|---|---|---|---|
-| **Balanced** | 1024 px | 15, 16 near airports | ~6.8 m per pixel | High flying, a slower connection or little graphics memory |
-| **Sharp** | 2048 px | 16, 17 near airports | ~3.4 m per pixel | Everyday flying, approaches included |
-| **Ultra** | 4096 px | 17, 18 near airports | ~1.7 m per pixel | Low flight and GA, with plenty of graphics memory |
-| **Extra** | 4096 px | 17, 19 near airports | ~1.7 m per pixel | Low and slow flight and screenshots, on a fast connection |
-| **Dynamic** | Extra's near the ground, less higher up | as Extra below 5,000 ft | follows the height | Climbs, cruise and approaches in one flight, on a fast connection |
+| **Balanced** | 2048 px, 1024 near airports | 15, 16 near airports | ~3.4 m per pixel | High flying, a slower connection or little graphics memory |
+| **Sharp** | 4096 px, 2048 near airports | 16, 17 near airports | ~1.7 m per pixel | Everyday flying, approaches included |
+| **Ultra** | 8192 px, 4096 near airports | 17, 18 near airports | ~0.8 m per pixel | Low flight and GA, with plenty of graphics memory |
+| **Extra** | 8192 px | 17, 19 near airports | ~0.8 m per pixel | Low and slow flight and screenshots, on a fast connection |
+| **Dynamic** | its base's near the ground (Extra, Ultra or Sharp), less higher up | as its base below 5,000 ft | follows the height | Climbs, cruise and approaches in one flight |
-**Extra** is Ultra with the finest imagery (zoom 19) near airports, which often avoids clouds and other artefacts. Elsewhere it is the same as Ultra. Near airports it downloads four times as much as Ultra, and a new area takes a little longer to load: about 4 minutes, then sharp next to the aircraft.
+At **Full** resolution (the default), each texture keeps all the detail of the imagery it is made from: nothing is shrunk. The sizes above are Full's; see [Resolution](#resolution) for less. The resolution is for the wide areas away from airports, at mid latitudes; near airports the textures cover a quarter of the width, so the same size is four times as sharp there. Each new texture is also sharpened a little as it is built, so roofs, field edges and treetops look crisper. This is always on and has no setting.
+
+**Extra** is Ultra with the finest imagery (zoom 19) near airports, as 8192 px textures, twice as sharp as Ultra's there and often without its clouds and other artefacts. Elsewhere it is the same as Ultra. Near airports it downloads four times as much as Ultra, and a new area takes a little longer to load: about 4 minutes, then sharp next to the aircraft.
### Dynamic
**Dynamic** makes the detail follow your height above the ground:
-- **Below 5,000 ft** it is Extra.
+- **Below 5,000 ft** it is its **Base** preset: Extra unless you choose another.
- **From 5,000 ft** the photos are downloaded at Sharp's detail.
- **From 25,000 ft** they are downloaded at Balanced's detail.
High up, X-Plane still asks for the photos in full detail, though from there the detail cannot be seen. Dynamic downloads about half as much in a climb and cruise, which suits airliners and other high flying.
+The **Base** box on Dynamic's card sets the preset it is near the ground:
+
+| Base | Near the ground | Higher up | Best for |
+|---|---|---|---|
+| **Extra** (the default) | Extra | Sharp from 5,000 ft, Balanced from 25,000 ft | a fast connection |
+| **Ultra** | Ultra: zoom 18 near airports instead of 19, a quarter of Extra's downloads there | Sharp from 5,000 ft, Balanced from 25,000 ft | a good connection |
+| **Sharp** | Sharp, through the climb too | Balanced from 25,000 ft | long flights at airliner heights, on an everyday connection |
+
+The card's text follows the base you choose, and Home names it, for example *Dynamic from Ultra*. Dynamic uses its base's textures in the cache and its base's tuning.
+
On a descent, Dynamic looks four minutes ahead and goes back to full detail early, so the ground is sharp again before you come close to it. X-Plane does not load a photo again just because you came lower: one it loaded with less detail high up stays that way while X-Plane keeps it. That is why the switch back comes early.
-Dynamic shares Extra's textures in the cache, so you can switch between the two without downloading anything again, and photos already in the cache are shown as they are at any height. It needs X-Plane to send the aircraft's position, which it does on the same PC by itself. The heights can be changed in the settings file (**Show the file**): `dynamic-sharp-above` and `dynamic-balanced-above`, in feet.
+Dynamic shares its base's textures in the cache (Extra's by default), so you can switch between the two without downloading anything again, and photos already in the cache are shown as they are at any height. It needs X-Plane to send the aircraft's position, which it does on the same PC by itself. The heights can be changed in the settings file (**Show the file**): `dynamic-sharp-above` and `dynamic-balanced-above`, in feet.
+
+### Resolution
+
+The **Resolution** box at the top right of each card shrinks that preset's textures, to save graphics memory:
+
+- **Full** (the default): the textures keep all the detail of their imagery.
+- **Medium**: halves the textures of the wide areas and keeps the airports' textures sharp.
+- **Low**: halves them all, a quarter of Full's graphics memory.
+
+The imagery is the same at every resolution: it is downloaded at the same zoom, so a lower resolution does not download less. It shows the same picture with less detail, and takes less graphics memory, RAM and disk. Below a resolution other than Full, the card gives the sizes it makes, for example *At Medium resolution: 4096 px textures in most areas, 4096 px near airports, from the same imagery.*
+
+Each preset keeps its own resolution, so you can have Ultra at Medium and Extra at Full; the one of the preset you choose is used. Textures of each resolution are kept in their own cache folder: [Cache › By quality](cache.md#by-quality) lists them as, for example, *Ultra, Medium resolution*. Like every setting, a change applies from the next start.
+
+Try a lower resolution when a preset's card warns that its textures would not fit your graphics card, rather than a coarser preset: Medium keeps the airports at full detail.
+
+### The cards
Each card shows the imagery zoom, the metres per pixel, roughly how long a new area takes to load, and how much graphics memory the photo textures take. Until you have flown, that memory figure comes from a test flight; after your first long flight, it is measured on your PC.
-- The **Recommended** badge marks the preset that suits your connection and graphics card, with the reason below it.
-- If a preset's photo textures plus X-Plane's own needs (about 5 GB) would be more than your graphics card has, its card shows a warning. X-Plane may then stutter or lower its texture detail; a smaller preset is safer.
+- The **Recommended** badge marks the preset that suits your connection and graphics card, with the reason below it. When it fits only at a lower resolution, the badge says so, for example **Recommended at Medium**.
+- The other cards say in a line under the title whether they would suit your PC too: *Also suits your PC.* in green (or *Also suits your PC at Medium resolution*, when only a lower resolution fits your graphics card), or in amber why not, such as *Needs about 100 Mbit/s of downloads* or *Too large for your 4 GB graphics card, even at Low resolution*.
+- If a preset's photo textures plus X-Plane's own needs (about 5 GB) would be more than your graphics card has, its card shows a warning. X-Plane may then stutter or lower its texture detail; a lower resolution or a smaller preset is safer.
### Ground detail
@@ -84,14 +113,11 @@ Your scenery packages are not changed: OrthoStreamXP adjusts the terrain files a
### Preview
-The top of the tab shows a photo from your cache twice: **Before** (as downloaded) and **After** (as X-Plane will get it with the settings below). It updates as you change them, and **Another photo** picks a different one. The preview needs a cache folder with at least one flown area in it. It works while the scenery is streaming too.
-
-### Colour matching
+The top of the tab shows a photo from your cache twice: **Before** (as downloaded) and **After** (as X-Plane will get it with the settings below). It updates as you change them, and **Another photo** picks a different one. The preview needs a cache folder with at least one flown area in it. It works while the scenery is streaming too. When you scroll down to the settings, the preview stays at the top of the tab, so you can see each change as you make it.
-Aerial photos are a patchwork of pictures taken on different days, so one patch can look grey and hazy next to a bright green one.
+The line under the pictures says where the photo is and which changes the **After** picture shows, for example *Exposure 80 % · Contrast 60 % (always on)*.
-- **Even out the colours between photos** moves each place towards the colours usual in its area, so the patches stand out less. Fields keep their own colours.
-- **Strength** sets how far the colours move: 100 % is the full correction, and less keeps more of each photo's own look.
+The **After** picture always has a little more contrast than **Before**, even with every setting below off: OrthoStreamXP gives all photos a touch of contrast as X-Plane reads them, because aerial photos are often hazy. That contrast has no setting.
### Seasons
@@ -103,7 +129,10 @@ Most aerial photos are taken in summer.
- **Winter:** deciduous trees look bare and fields turn brown.
Conifers, roofs, roads and water keep their colours, and snow is left to X-Plane's weather.
-- **Season:** *Automatic* follows X-Plane's date and the place; a new date takes effect from the next flight. You can also force one season everywhere: *Early spring*, *Spring*, *Summer* (the pictures as they are), *Early autumn*, *Autumn*, *Late autumn* or *Winter, without snow*.
+- **Season:** *Automatic: X-Plane's date and the place* follows the date of your flight; a new date takes effect from the next flight. You can also force one season everywhere: *Early spring*, *Spring*, *Summer (the pictures as they are)*, *Early autumn*, *Autumn*, *Late autumn* or *Winter, without snow*.
+- **Season: Satellite: grass and fields as they really were** also follows X-Plane's date. Trees keep the calendar's colours and times, but **grass and fields** look as green as NASA's satellites saw the place in that part of the last year, compared with its greenest month. So they stay green through a mild Atlantic or Mediterranean winter, dry out in a dry summer, and turn straw-coloured in the tropics' dry season, where the calendar shows nothing or the opposite. A snowy or ploughed winter rests fully, as with the calendar.
+
+ The satellites see the country around a place at about 4 km, so a whole area changes together, not each field on its own. Towns, rock and sand, which are never very green, keep the calendar. OrthoStreamXP downloads about 2 MB once a year for each area of about 500 km, the first time you fly there, and keeps it with the low-zoom base. Where it has no satellite data (offline, before the first download), it uses the calendar. The colour preview uses only what is already downloaded: for a place you have not flown with Satellite yet, the line under the pictures says *No satellite record of this place yet* and shows the calendar's season.
- **Strength:** how far the colours move towards the season. 100 % is the full change.
### Exposure
@@ -159,7 +188,7 @@ After flights of 10 minutes or more, Home may suggest settings for your preset (

-- **Keep the photo scenery below airports and overlays:** at every start, moves the packages to the end of X-Plane's `scenery_packs.ini`, so airports and overlays draw on top of the photos. Leave it on unless you order that list yourself.
+- **Keep the photo scenery below airports and overlays:** at every start, moves the packages to the end of X-Plane's `scenery_packs.ini`, so airports and overlays draw on top of the photos. Leave it on unless you order that list yourself. To see and change the list, use the [X-Plane Custom Scenery](custom-scenery.md) page.
- **X-Plane address:** needed only when X-Plane runs on another PC.
- **X-Plane start options:** command-line options added when **Start and fly** starts X-Plane, for example `--allow_reshade`. They take effect the next time X-Plane starts.
diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md
index 10805d8..df10747 100644
--- a/docs/troubleshooting.md
+++ b/docs/troubleshooting.md
@@ -12,6 +12,7 @@ When something goes wrong, Home shows a notice that says what happened, usually
| **WinFsp is needed** / **WinFsp could not show the scenery** | Click **Get WinFsp**, install (or repair) WinFsp, restart your computer, then click **Start** again. If you installed WinFsp or OrthoStreamXP and have not restarted Windows since, restart it first. |
| **A scenery folder is in the way** | X-Plane's `Custom Scenery` folder already has a folder with the same name as one of your packages. Usually another streaming tool still shows it there: close that tool before you start OrthoStreamXP and check your scenery_packs.ini file and click **Start** again. If it is a real folder, move or rename it. **Open Custom Scenery** opens the folder. |
| **Your scenery packages were not found** | The packages folder is missing or empty. Click **Open settings** and choose the parent folder that holds your packages |
+| **A setting needs attention**, saying every scenery package is switched off, or only overlay packages are | All your regions are switched off under **Scenery packages** on Home. Switch at least one region back on there, then click **Start** again (see [Flying › Leaving a package out](flying.md#leaving-a-package-out)). |
| **X-Plane was not found** | The X-Plane folder has no `Custom Scenery` folder. Choose the folder X-Plane is installed in. |
| **A folder cannot be written** | Choose a cache folder you can write to, for example one in your user folder. |
| **A setting needs attention** | A value in the settings file is not valid. The notice names it; click **Open settings** to fix it. |
@@ -20,7 +21,6 @@ When something goes wrong, Home shows a notice that says what happened, usually
| **Restart OrthoStreamXP to use your new settings** | The settings file changed while OrthoStreamXP was running. Click **Restart now** to use the new values. |
| **Downloads are failing** | Check your internet connection. OrthoStreamXP keeps trying; **Open log** shows the details. |
| **Blurry ground for a while** | A new area takes a few minutes the first time. If it happens often, try a lower preset or apply the tuning suggestions after your flight (see [Flying](flying.md#tuning-suggestions)). |
-| **Patchy colours between photos** | Turn on **Even out the colours between photos** in [Settings › Colours](settings.md#colours). |
| **Photos look too bright next to X-Plane's own scenery** | Lower **Exposure** in [Settings › Colours](settings.md#exposure). |
| **Noisy, speckled ground up close** | X-Plane's grass and dirt detail is drawn over the photos. Set **Ground detail** to **Off** (or lower it) in [Settings › Quality](settings.md#ground-detail). |
@@ -28,7 +28,7 @@ When something goes wrong, Home shows a notice that says what happened, usually

-The Log page lists the main steps and any problems of this session. Type in **Search the log** to filter the list. **Open log folder** opens the full, detailed logs in `%LOCALAPPDATA%\OrthoStreamXP\logs`.
+The Log page lists the main steps and any problems of this session; it stays empty until you start OrthoStreamXP on the Home page. Type in **Search the log** to filter the list. **Open log folder** opens the full, detailed logs in `%LOCALAPPDATA%\OrthoStreamXP\logs`.
## The About page
diff --git a/installer/license-notice.md b/installer/license-notice.md
index 5ef4ead..47aec53 100644
--- a/installer/license-notice.md
+++ b/installer/license-notice.md
@@ -20,4 +20,23 @@ for using it in accordance with those terms. Use it for your own flight simulati
OrthoStreamXP needs WinFsp, which is installed separately and comes with its own licence.
+## Intel ISPC Texture Compressor
+
+OrthoStreamXP includes ispc_texcomp.dll, built from Intel's ISPC Texture Compressor, under the MIT licence:
+
+Copyright 2017 Intel Corporation
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
+rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
+persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
+Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
By choosing "I accept", you agree to the GNU General Public License version 3 below and to the notices above.
diff --git a/mkdocs.yml b/mkdocs.yml
index 2d70127..57ac94e 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -22,6 +22,7 @@ nav:
- settings.md
- cache.md
- packages.md
+ - custom-scenery.md
- troubleshooting.md
- Questions and answers: faq.md
- User guide (PDF): OrthoStreamXP-UserGuide.pdf
diff --git a/native/ispc_texcomp/LICENSE.txt b/native/ispc_texcomp/LICENSE.txt
new file mode 100644
index 0000000..6c2d710
--- /dev/null
+++ b/native/ispc_texcomp/LICENSE.txt
@@ -0,0 +1,19 @@
+Copyright 2017 Intel Corporation
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+of the Software, and to permit persons to whom the Software is furnished to do
+so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/native/ispc_texcomp/README.md b/native/ispc_texcomp/README.md
new file mode 100644
index 0000000..1d7a473
--- /dev/null
+++ b/native/ispc_texcomp/README.md
@@ -0,0 +1,22 @@
+# ispc_texcomp.dll
+
+Intel's [ISPC Texture Compressor](https://github.com/GameTechDev/ISPCTextureCompressor) (MIT, see `LICENSE.txt`),
+built for x64 Windows. OrthoStreamXP uses only its BC1 encoder (`CompressBlocksBC1`), from
+`src/OrthoStreamXP/Textures/Dds/IspcBc1.cs`; when the DLL cannot be loaded, the program falls back to its own
+encoder.
+
+Why: on 4096 px aerial textures it encodes BC1 6-8 times faster than the built-in range fit (Ryzen 7 9800X3D,
+the 13-level chain on one thread: ~60 ms against ~370 ms; ~12 ms against ~95 ms on 4 threads) and 0.1-0.4 dB PSNR
+better at the full size, 0.4-0.9 dB at the smaller levels. `IspcBc1` replaces its one-colour blocks (ISPC lands up
+to a 565 step off a flat colour) with the endpoint pair that mixes closest, keeps every block in the opaque
+four-colour mode, and refines every other block's two colours by least squares (`Bc1Refinement`, two passes, as
+nvtt's fast mode does; ISPC fits a block once): about 0.4 dB closer on cached Bing imagery, the chain ~46 ms
+instead of ~11 ms on 4 threads.
+
+The DLL is checked in, built by `build.ps1` from pinned sources (compressor commit `79ddbc9`, ISPC v1.31.0), with
+Intel's flags plus an AVX-512 target; ISPC picks SSE2, SSE4, AVX, AVX2 or AVX-512 by the CPU at run time. To
+rebuild, with the Visual Studio C++ build tools (x64) installed:
+
+```powershell
+.\native\ispc_texcomp\build.ps1
+```
diff --git a/native/ispc_texcomp/build.ps1 b/native/ispc_texcomp/build.ps1
new file mode 100644
index 0000000..775cbd1
--- /dev/null
+++ b/native/ispc_texcomp/build.ps1
@@ -0,0 +1,52 @@
+# Rebuilds ispc_texcomp.dll (Intel's ISPC Texture Compressor, MIT) next to this script: the BC1 encoder of the
+# textures (src\OrthoStreamXP\Textures\Dds\IspcBc1.cs). Needs the Visual Studio C++ build tools (x64); downloads the
+# pinned compressor sources and ISPC compiler into a temporary folder.
+#
+# .\native\ispc_texcomp\build.ps1
+$ErrorActionPreference = 'Stop'
+
+$sourceCommit = '79ddbc90334fc31edd438e68ccb0fe99b4e15aab' # GameTechDev/ISPCTextureCompressor, 2024-09-23
+$ispcVersion = 'v1.31.0'
+# Chosen at run time by the CPU; AVX-512 is about a fifth faster than AVX2 where the CPU has it.
+$targets = 'sse2,sse4,avx,avx2,avx512skx-x16'
+
+$vswhere = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe'
+$vs = & $vswhere -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath
+if (-not $vs) { throw 'Visual Studio C++ build tools (x64) not found' }
+$vcvars = Join-Path $vs 'VC\Auxiliary\Build\vcvars64.bat'
+
+$work = Join-Path ([IO.Path]::GetTempPath()) "ispc_texcomp-build-$PID"
+New-Item -ItemType Directory -Force $work | Out-Null
+try {
+ Invoke-WebRequest "https://github.com/GameTechDev/ISPCTextureCompressor/archive/$sourceCommit.zip" -OutFile "$work\src.zip"
+ Invoke-WebRequest "https://github.com/ispc/ispc/releases/download/$ispcVersion/ispc-$ispcVersion-windows.zip" -OutFile "$work\ispc.zip"
+ Expand-Archive "$work\src.zip" "$work\src"
+ Expand-Archive "$work\ispc.zip" "$work\ispc"
+ $src = Join-Path $work "src\ISPCTextureCompressor-$sourceCommit\ispc_texcomp"
+ $ispc = (Get-ChildItem "$work\ispc" -Recurse -Filter ispc.exe | Select-Object -First 1).FullName
+ $out = Join-Path $work 'out'
+ New-Item -ItemType Directory -Force $out | Out-Null
+
+ # The flags of Intel's own project (ispc_texcomp.vcxproj), with the AVX-512 target added. /MT: the C runtime is
+ # inside the DLL, so it needs nothing but KERNEL32 (no Visual C++ redistributable on users' PCs).
+ $script = @"
+@echo off
+call "$vcvars" >nul || exit /b 1
+cd /d "$out" || exit /b 1
+"$ispc" -O2 "$src\kernel.ispc" -o kernel.obj -h kernel_ispc.h --target=$targets --opt=fast-math --woff || exit /b 1
+"$ispc" -O2 "$src\kernel_astc.ispc" -o kernel_astc.obj -h kernel_astc_ispc.h --target=$targets --opt=fast-math --woff || exit /b 1
+cl /nologo /O2 /EHsc /MT /LD /I. "$src\ispc_texcomp.cpp" "$src\ispc_texcomp_astc.cpp" kernel*.obj /Fe:ispc_texcomp.dll /link /DEF:"$src\ispc_texcomp.def" || exit /b 1
+"@
+ Set-Content "$work\build.bat" $script -Encoding ascii
+ # stderr merged inside cmd: vcvars and ISPC write notes there, which Windows PowerShell would raise as errors.
+ $ErrorActionPreference = 'Continue'
+ cmd /c "`"$work\build.bat`" 2>&1"
+ $exit = $LASTEXITCODE
+ $ErrorActionPreference = 'Stop'
+ if ($exit -ne 0) { throw 'ispc_texcomp build failed' }
+ Copy-Item "$out\ispc_texcomp.dll" $PSScriptRoot -Force
+ Write-Host "Built $PSScriptRoot\ispc_texcomp.dll"
+}
+finally {
+ Remove-Item $work -Recurse -Force -ErrorAction SilentlyContinue
+}
diff --git a/native/ispc_texcomp/ispc_texcomp.dll b/native/ispc_texcomp/ispc_texcomp.dll
new file mode 100644
index 0000000..e3a1a36
Binary files /dev/null and b/native/ispc_texcomp/ispc_texcomp.dll differ
diff --git a/release-notes/v1.5.0.md b/release-notes/v1.5.0.md
new file mode 100644
index 0000000..313b20b
--- /dev/null
+++ b/release-notes/v1.5.0.md
@@ -0,0 +1,41 @@
+## What's new
+
+- **Twice as sharp, from the same downloads.** Until now, many textures were shrunk after the photos were downloaded, so part of the detail you downloaded was thrown away. Now every texture keeps all the detail of its photos. Away from airports, every preset is twice as sharp as before: Balanced 2048 px, Sharp 4096 px, and Ultra and Extra 8192 px. With Extra, the textures near airports are twice as sharp too (8192 px from zoom 19). The imagery and the downloads are the same as before.
+- **Resolution for each preset.** Each preset card in **Settings › Quality** (and in the setup) has a **Resolution** box. **Full** keeps all the detail, as above. **Medium** halves the textures away from airports and keeps the airports sharp. **Low** halves them all, for a quarter of Full's graphics memory. The photos downloaded are the same, so a lower resolution does not download less. It fits a smaller graphics card without going down to a coarser preset. Each preset keeps its own resolution.
+- **A Base for Dynamic.** The **Dynamic** card has a **Base** box: the preset it is near the ground. **Extra** is the default, as before. **Ultra** downloads a quarter of Extra's downloads near airports, and **Sharp** suits long flights at airliner heights on an everyday connection. Higher up, Dynamic still drops to Sharp's and then Balanced's detail.
+- **The preset cards tell you what fits.** The cards that are not recommended say in a line under their title whether they would suit your PC too, or why not, for example that they need a faster connection or a bigger graphics card. **Test my connection** makes that more exact. When a preset fits only at a lower resolution, its badge says so, for example **Recommended at Medium**.
+- **Crisper photos.** Each new texture is sharpened a little as it is built, so roofs, field edges and treetops look crisper, without bright or dark outlines. The photos also get a little more contrast as X-Plane reads them, because aerial photos are often hazy. Both are always on and have no setting. The **Colours** preview shows the contrast in its **After** picture.
+- **Smoother flights into new scenery.** When X-Plane loads the next scenery tile in flight, it reads a small version of every photo in that tile and waits for each one. Near airports a tile has hundreds of them, and that wait showed up as stutters. OrthoStreamXP now gets those photos ready up to five minutes ahead, along your path, so X-Plane finds them ready when it gets there.
+- **Less memory.** OrthoStreamXP keeps less in RAM and leaves more for X-Plane. For each scenery package, it keeps at most 512 MB of textures ready for X-Plane, down from 1 GB. Downloaded photos stay compressed until they are needed. Between texture builds, it keeps the memory of only one build, instead of up to 1 GB.
+- **Faster loading.** OrthoStreamXP now packs the photos into textures with Intel's ISPC texture compressor, about six times faster than before. That leaves much more of the processor to X-Plane, and flights with an empty cache load sooner. Water and other even areas also keep their colour more exactly.
+- **Satellite seasons.** A new choice for **Season** in **Settings › Colours**: **Satellite**. The calendar colours every place the same way: green in spring, brown in winter. But a winter on the Atlantic or Mediterranean coast stays green, a dry summer turns the fields to straw, and in the tropics the dry season comes when the calendar says nothing happens. With Satellite, the grass and fields look as green as NASA's satellites saw that place at that time of the last year, compared with its greenest month. Trees keep the calendar, and towns, rock and sand keep their colours.
+- **X-Plane Custom Scenery page.** A new page in the sidebar shows X-Plane's scenery list (`scenery_packs.ini`), highest priority first. Switch packages on or off, and drag them up or down to change which one covers the others. There is no need to edit the file by hand. The packages OrthoStreamXP adds are marked, so you can see where the photo scenery sits.
+- **Switch a package off on Home.** Each package under **Scenery packages** on the Home page has its own switch. Leave out a region you are not flying today, or a package you want to test without, and keep it in the folder. It applies from the next start.
+- **A bigger cache map.** The map on the **Cache** page now uses the full width of the window. Scroll to zoom and drag to move it. The buttons zoom in, zoom out and show all your areas, and the latitude and longitude lines help you find a place.
+- **Colour preview in sight.** On the **Colours** tab, the Before and After preview stays at the top while you scroll to the settings below, so you can see each change as you make it.
+
+## Why flights load faster
+
+When a flight starts, X-Plane asks for thousands of textures at once. For each one, OrthoStreamXP downloads the photos and then packs them into the texture format X-Plane reads. That packing took a large share of the processor during the load, just when X-Plane needs it most.
+
+The new compressor does the same work about six times faster. In cold-start tests over the same scene of about 3,000 textures, with an empty cache, X-Plane finished loading the photo scenery between a quarter and almost half sooner, and the longest wait for a single texture was halved or better. The download speed also differed between those runs, so how much you gain depends on your processor and your connection. Places already in the cache load from it as before.
+
+## Fixes
+
+- When OrthoStreamXP stops, it now takes out of `scenery_packs.ini` the packages it added there at the start. X-Plane no longer lists packages that are only there while OrthoStreamXP runs.
+- **Distant scenery has the same colours as near.** The farther away the ground was, the darker it got, most of all towards the horizon. And far scenery was made from Bing's coarsest pictures, which are other, lighter and yellower imagery than its detailed photos. Distant ground now keeps the brightness and colours of the photos you see up close, so there is no lighter, yellower ring where far scenery meets near.
+- A photo tile that no imagery provider has no longer leaves its texture without its picture: the gap is filled from a coarser photo of the same place.
+
+## Good to know
+
+- **Your first flight in each area downloads its photos again.** The new texture sizes go in a new cache folder for each preset, so every area is built again, sharper. From the second flight, the area comes from the cache as before.
+- Your textures from 1.4 are not used any more. On the **Cache** page, under **By quality**, they are a second row for your preset, showing the old sizes. Delete that row to free the space.
+- The bigger textures take more room in the cache and more graphics memory. The preset cards in **Settings › Quality** show how much graphics memory the photo textures take, and warn you if your graphics card is short. Until you have flown at the new sizes, that figure is an estimate. If X-Plane stutters or turns blurry, set the preset's **Resolution** to **Medium**, or try one preset lower.
+- Your preset and its resolution are not changed by the update: every preset starts at **Full**, and Dynamic at **Extra**. A resolution or base you choose applies from the next start. Textures of each resolution are kept in their own cache folder, listed under **By quality** on the **Cache** page as, for example, *Ultra, Medium resolution*. Dynamic shares its base's textures in the cache.
+- Smoother flights into new scenery needs X-Plane to send the aircraft's position. On the same PC it does this by itself.
+- Your season setting is not changed by the update. To try Satellite, turn on **Colour the scenery for the season** and choose **Satellite** in **Settings › Colours** while OrthoStreamXP is stopped.
+- Satellite downloads about 2 MB once a year for each area of about 500 km, the first time you fly there. Until then, or without an internet connection, that area uses the calendar. The colour preview shows only what is already downloaded.
+- The satellites see the land at about 4 km, so a whole area changes colour together, not each field on its own.
+- The X-Plane Custom Scenery page and the package switches on Home can be changed only while OrthoStreamXP is stopped. X-Plane reads the scenery list when it starts, so a change shows from its next start.
+- If you switch off every region and leave only an overlay package (roads, forests and buildings) on, OrthoStreamXP will not start: overlays need a region's ground to draw on. The notice on Home tells you to switch a region back on under **Scenery packages**.
+- **Even out the colours between photos** has been removed from **Settings › Colours**. If you had it on, the photos are now shown as downloaded, with your season and exposure settings as before. Your settings file still loads as it is.
diff --git a/src/OrthoStreamXP/Configuration/MountSettings.cs b/src/OrthoStreamXP/Configuration/MountSettings.cs
index 80c63c8..b8d7e6a 100644
--- a/src/OrthoStreamXP/Configuration/MountSettings.cs
+++ b/src/OrthoStreamXP/Configuration/MountSettings.cs
@@ -66,10 +66,6 @@ internal sealed record MountSettings
public long CacheLimitBytes { get; init; }
/// Seasonal colours for the photo textures.
public SeasonOptions Seasons { get; init; } = SeasonOptions.Off;
- /// Photo colours evened out between captures, by the low-zoom base.
- public bool MatchColours { get; init; }
- /// How much of the colour matching is made, 0 to 1.
- public double MatchStrength { get; init; } = 1;
/// The photos' exposure in percent, to 100 (100: as they are).
public double Exposure { get; init; } = OrthoStreamXP.Textures.Exposure.Full;
/// Every open and read, and the camera, logged as CSV beside the log.
@@ -87,9 +83,12 @@ public static MountSettings FromValues(SettingValues values, bool console = true
{
string cache = Path.TrimEndingDirectorySeparator(Path.GetFullPath(values.Required("cache")));
int levelChange = values.Int("level-change", 0);
- if (levelChange is < -4 or > 2) throw new SettingsException("level-change must be between -4 and 2");
- // The texture size follows the level (Balanced 512 ... Extra 4096); an older settings file's texture-quality is ignored.
- var texturePlan = new TexturePlan(levelChange);
+ if (Setup.QualityPreset.ForLevel(levelChange) is null)
+ throw new SettingsException("level-change must be one of the quality presets: -2 (Balanced), -1 (Sharp), 0 (Ultra) or 1 (Extra)");
+ Scenery.DynamicOptions? dynamic = ParseDynamic(values);
+ // The texture size follows the level (Balanced 2048/1024 ... Extra 8192), shrunk by the preset's resolution; an
+ // older settings file's texture-quality is ignored.
+ var texturePlan = new TexturePlan(levelChange) { Resolution = ParseResolution(values, Setup.QualityPreset.Current(levelChange, dynamic is not null)) };
// One cache folder for every setup: each texture plan keeps its files in its own subfolder.
string planCache = Path.Join(cache, texturePlan.FolderName);
// The regions an earlier version installed take their new names before the packages are listed (nothing is mounted yet).
@@ -138,10 +137,6 @@ public static MountSettings FromValues(SettingValues values, bool console = true
SeasonOptions seasons = ParseSeasons(values);
double cacheLimitGb = values.Double("cache-limit", 0);
if (cacheLimitGb is < 0 or > 100_000) throw new SettingsException("cache-limit must be 0 (no limit) or a size in GB");
- string matchValue = values.String("match-colours") ?? "off";
- bool matchColours = ParseOnOff(matchValue) ?? throw new SettingsException($"match-colours must be on or off, not '{matchValue}'");
- double matchStrength = values.Double("match-strength", 100);
- if (matchStrength is < 0 or > 100) throw new SettingsException("match-strength must be between 0 and 100");
double exposure = values.Double("exposure", OrthoStreamXP.Textures.Exposure.Full);
if (exposure is < OrthoStreamXP.Textures.Exposure.Min or > OrthoStreamXP.Textures.Exposure.Full)
throw new SettingsException($"exposure must be between {OrthoStreamXP.Textures.Exposure.Min} and {OrthoStreamXP.Textures.Exposure.Full}");
@@ -155,7 +150,6 @@ public static MountSettings FromValues(SettingValues values, bool console = true
bool skipPhotosAtNight = ParseOnOff(skipValue) ?? throw new SettingsException($"skip-photos-at-night must be on or off, not '{skipValue}'");
double skipSunBelow = values.Double("skip-photos-sun-below", -Scenery.Daylight.DefaultDarkBelow);
if (skipSunBelow is < 0 or > 18) throw new SettingsException("skip-photos-sun-below must be between 0 and 18 degrees");
- Scenery.DynamicOptions? dynamic = ParseDynamic(values);
if (downloadWorkers < 1) throw new SettingsException("download-workers must be at least 1");
if (downloadTimeout is < 1 or > 120) throw new SettingsException("download-timeout must be between 1 and 120 seconds");
@@ -220,8 +214,6 @@ public static MountSettings FromValues(SettingValues values, bool console = true
BuildTiles = buildTiles,
PagingK = pagingK,
Seasons = seasons,
- MatchColours = matchColours,
- MatchStrength = matchStrength / 100,
Exposure = exposure,
CacheLimitBytes = (long)(cacheLimitGb * (1L << 30)),
ReadLog = readLog,
@@ -230,7 +222,7 @@ public static MountSettings FromValues(SettingValues values, bool console = true
}
///
- /// The packages to mount: source alone, or every package in base-packages (each with its own cache
+ /// The packages to mount: source alone, or every package in base-packages but those in skip-packages (each with its own cache
/// subfolder), mounted at mountpoint or as X-Plane's Custom Scenery\<name>.
///
/// X-Plane's Custom Scenery folder when xplane is given.
@@ -265,11 +257,20 @@ internal static IReadOnlyList PlanPackages(SettingValues values, st
{
if (!Directory.Exists(basePackages)) throw new SettingsException($"Base packages folder does not exist: {basePackages}");
plan = [];
+ SkippedPackages skipped = SkippedPackages.Parse(values.String(SkippedPackages.Setting));
+ bool anySkipped = false;
foreach (string folder in SceneryPacks.FindPackages(basePackages, out notPackages))
{
string name = Path.GetFileName(folder);
- plan.Add(new PackagePlan(name, folder, Path.Join(cache, name), Path.Join(customScenery, name)));
+ if (skipped.Contains(name)) anySkipped = true;
+ else plan.Add(new PackagePlan(name, folder, Path.Join(cache, name), Path.Join(customScenery, name)));
}
+ if (plan.Count == 0 && anySkipped)
+ throw new SettingsException($"Every scenery package in {basePackages} is switched off: switch one on under Scenery packages on the Home page");
+ // Overlays only draw roads, forests and buildings on a region's ground: on their own they show nothing to stream onto.
+ if (anySkipped && plan.All(p => SceneryPacks.IsOverlays(p.Name)))
+ throw new SettingsException($"Only overlay packages are switched on ({string.Join(", ", plan.Select(p => p.Name))}): " +
+ "switch on at least one region under Scenery packages on the Home page");
if (plan.Count == 0)
throw new SettingsException($"No scenery packages (subfolders with an Earth nav data folder) in {basePackages}");
}
@@ -314,6 +315,13 @@ internal static SeasonOptions ParseSeasons(SettingValues values)
}
/// Dynamic quality's steps, or null when it is off.
+ /// The resolution of the preset the settings are at (resolution-<preset>); Full for a level no preset has.
+ private static TextureResolution ParseResolution(SettingValues values, Setup.QualityPreset? preset)
+ {
+ if (preset is null || values.String(preset.ResolutionKey) is not { } value) return TextureResolution.Full;
+ return TextureResolution.Parse(value) ?? throw new SettingsException($"{preset.ResolutionKey} must be full, medium or low, not '{value}'");
+ }
+
private static Scenery.DynamicOptions? ParseDynamic(SettingValues values)
{
string onValue = values.String("dynamic-quality") ?? "off";
diff --git a/src/OrthoStreamXP/Configuration/SettingsOptions.cs b/src/OrthoStreamXP/Configuration/SettingsOptions.cs
index ab1c77b..254f8d0 100644
--- a/src/OrthoStreamXP/Configuration/SettingsOptions.cs
+++ b/src/OrthoStreamXP/Configuration/SettingsOptions.cs
@@ -11,7 +11,8 @@ internal static class SettingsOptions
public static readonly SettingsSchema Schema = new SettingsSchema()
.Add("source", "Existing scenery package folder (one package; or use base-packages)")
.Add("base-packages", @"Folder of scenery packages: every subfolder with Earth nav data is mounted in X-Plane's Custom Scenery under its own name. Needs xplane")
- .Add("xplane", @"X-Plane folder: packages are mounted as Custom Scenery\ (instead of mountpoint)")
+ .Add(SkippedPackages.Setting, "Packages of base-packages not to mount, by folder name, comma-separated (switched off under Scenery packages on the Home page)")
+ .Add("xplane",@"X-Plane folder: packages are mounted as Custom Scenery\ (instead of mountpoint)")
.Add("scenery-packs", @"on or off: with xplane, move the mounted packages to the end of Custom Scenery\scenery_packs.ini (lowest priority, below airports and overlays), keeping the old file as scenery_packs.ini.bak (default: on)")
.Add("cache", @"Directory for generated/cache files, one for every setup: each level-change and texture size gets its own \ subfolder, and with base-packages each package its own folder in that")
.Add("log-output", "Where the log goes: none, console, log-file or both (default: both)")
@@ -33,7 +34,8 @@ internal static class SettingsOptions
.Add("night-lights", "on or off: light the towns on the photo scenery at night. X-Plane's own scenery glows where it is a town; photo tiles are dark but for X-Plane's roads and buildings. With this on, each photo tile gets a night texture of street lamps, their glow and lit windows along X-Plane's roads (read from the overlay packages), which X-Plane fades in at dusk. Each is painted the first time X-Plane loads it and kept in the cache. The packages' files are not changed. Takes effect at the next start (default: off)")
.Add("skip-photos-at-night", "on or off: at night in X-Plane (the sun lower than skip-photos-sun-below) download no detailed photos: the ground under the night lights is drawn from the low-zoom base, blurry, and what is already in the cache is shown as it is. In twilight, and before X-Plane sends where the sun is, the photos stream as usual. Saves downloads and processor time on night flights; needs mip-streaming. Takes effect at the next start (default: off)")
.Add("skip-photos-sun-below", "Degrees, 0-18: how far below the horizon the sun in X-Plane must be before skip-photos-at-night skips the photos. 6 is the end of civil twilight, when the sky turns dark; 12 the end of nautical twilight, when the horizon fades; 18 full night. Lower skips more of the twilight; higher keeps the photos while the sky still lights the ground, and brings them back sooner at dawn. Takes effect at the next start (default: 9)")
- .Add("dynamic-quality", "on or off: Dynamic quality, the photos' detail follows the height above the ground. X-Plane wants nearly the same full-detail textures at 10,000 ft as at 1,000 ft, though from up there the detail cannot be seen; with this on, above dynamic-sharp-above the photos are fetched no sharper than Sharp's (2048 px), and above dynamic-balanced-above no sharper than Balanced's (1024 px). What is already in the cache is shown as it is. In a descent the height four minutes ahead counts, so the photos are sharp again before the ground comes close. Saves about half of the downloads in a climb and cruise; needs mip-streaming and track-aircraft. The Dynamic preset sets it with Extra's values. Takes effect at the next start (default: off)")
+ .Add("dynamic-quality", "on or off: Dynamic quality, the photos' detail follows the height above the ground. X-Plane wants nearly the same full-detail textures at 10,000 ft as at 1,000 ft, though from up there the detail cannot be seen; with this on, above dynamic-sharp-above the photos are fetched no sharper than Sharp's (2048 px), and above dynamic-balanced-above no sharper than Balanced's (1024 px). What is already in the cache is shown as it is. In a descent the height four minutes ahead counts, so the photos are sharp again before the ground comes close. Saves about half of the downloads in a climb and cruise; needs mip-streaming and track-aircraft. The Dynamic preset sets it with the values of its base (Extra, Ultra or Sharp: level-change); a step no coarser than the base is left out. Takes effect at the next start (default: off)")
+ .Add("dynamic-base", "extra, ultra or sharp: the preset the window's Dynamic card is near the ground, kept here while another preset is chosen. What the photos are near the ground is level-change's (default: extra)")
.Add("dynamic-sharp-above", $"Feet above the ground, 1000-40000: from this height Dynamic quality fetches the photos no sharper than Sharp's; they are sharp again 500 ft below it (default: {Scenery.DynamicOptions.DefaultSharpAboveFt:0})")
.Add("dynamic-balanced-above", $"Feet above the ground, 1000-60000, or off: from this height Dynamic quality fetches the photos no sharper than Balanced's; it must be higher than dynamic-sharp-above (default: {Scenery.DynamicOptions.DefaultBalancedAboveFt:0})")
.Add("lazy-terrain-listing","Show an empty terrain directory listing; DSF-referenced .ter files remain directly accessible", arity: 0)
@@ -45,22 +47,33 @@ internal static class SettingsOptions
.Add("prefetch-radius-km", "Width either side of the predicted path, and the radius around a slow or stationary aircraft (default: 5 km)")
.Add("prefetch-lookahead-seconds", $"How far ahead to prefetch, as flying time at the current ground speed: 120 s is 7.4 km at 120 kt, 28 km at 450 kt (default: {MountSettings.DefaultLookaheadSeconds})")
.Add("prefetch-textures", "Maximum DDS files to queue per position update, nearest along the path first (default: 8)")
- .Add("level-change", "Fetch tiles at (zoom in the .ter/DDS file name + N), -4..2. -1 downloads a quarter of the tiles of 0; +1 four times as many (default: 0). Each level keeps its textures in its own cache subfolder. It also sets the texture size: 4096 px at level 0 and above, half per level below (-2: 1024, -1: 2048, 0 and +1: 4096)")
+ .Add("level-change", "The quality preset: -2 Balanced, -1 Sharp, 0 Ultra, 1 Extra (default: 0). Each downloads fixed zooms for the areas' textures (ZL16/17) and the airports' (ZL18 and finer): Balanced 15/16, Sharp 16/17, Ultra 17/18, Extra 17/19. Each level keeps its textures in its own cache subfolder. It also sets the texture size, the detail the tiles hold, never shrunk: ZL16 textures 2048 px at -2, 4096 at -1, 8192 at 0 and +1; ZL18 textures 1024 at -2, 2048 at -1, 4096 at 0, 8192 at +1 (at most 8192)")
+ .Add("resolution-balanced", ResolutionHelp("Balanced"))
+ .Add("resolution-sharp", ResolutionHelp("Sharp"))
+ .Add("resolution-ultra", ResolutionHelp("Ultra"))
+ .Add("resolution-extra", ResolutionHelp("Extra"))
+ .Add("resolution-dynamic", ResolutionHelp("Dynamic"))
.Add("provisional-lod", "Cold-run speedup: if the full DDS is not ready within provisional-wait seconds, serve a same-size image built from tiles N zoom levels coarser (N=2 downloads 16 tiles instead of 256). 0 disables. Needs background-textures or track-aircraft (default: 2)")
.Add("provisional-wait", "Seconds to wait for the full-detail DDS before serving the provisional one (default: 2.0)")
.Add("mip-streaming", "on or off: serve photo textures level by level, as X-Plane reads them. Each read is answered with the best imagery at hand, and only the levels X-Plane reads are downloaded, at the zoom they need, so a cold start downloads full detail only next to the aircraft. Off builds every texture whole before X-Plane gets it, with provisional-lod (default: on)")
.Add("near-wait", $"Streaming: seconds a read of near or middle scenery may wait for real imagery while a flight starts or X-Plane loads another place (its loading screen and the time parked after it); X-Plane will not read those textures again while the aircraft is parked (default: {MountSettings.DefaultNearWait})")
.Add("max-wait", $"Streaming: seconds such a read may wait in flight before X-Plane gets a stand-in stretched from coarser imagery; the real imagery is fetched behind it for X-Plane's next read (default: {MountSettings.DefaultMaxWait})")
- .Add("build-memory", $"Streaming: MB of memory the builds may hold together while their tiles arrive, each at its own size (about 4.5 x size² bytes: 1.2 MB at 512 px, 19 MB at 2048 px, 75 MB at 4096 px). It limits how many full-size textures build at once, while the small levels far scenery needs run many together, up to {TextureStreamer.DefaultMaxBuilds} (default: {MountSettings.DefaultBuildMemoryMb})")
+ .Add("build-memory", $"Streaming: MB of memory the builds may hold together while their tiles arrive, each at its own size (about 4.6 x size² bytes: 1.2 MB at 512 px, 18 MB at 2048 px, 74 MB at 4096 px, 295 MB at 8192 px). It limits how many full-size textures build at once, while the small levels far scenery needs run many together, up to {TextureStreamer.DefaultMaxBuilds} (default: {MountSettings.DefaultBuildMemoryMb})")
.Add("build-tiles", $"Streaming: tiles the builds may download together. Finer imagery costs more tiles per texture (a ZL16 texture: 1024 at zoom 17, 4096 at zoom 18), so this keeps full-size builds from filling the connection; builds done ahead of X-Plane get half of it, so its own reads always find room. At about 1000 tiles a second the default is half a minute of downloads (default: {TextureStreamer.DefaultBuildTiles})")
.Add("paging-k", $"Streaming: the constant of the paging model (which mip level X-Plane wants at which distance), as the flight tuning measures it in flight (default: auto, a guess from X-Plane's window and field of view, else {PagingModel.DefaultK})")
.Add("cache-limit", "The most the cache's textures may take, in GB: when over it, the areas flown longest ago are removed at the start and the stop, down to 90% of it. The low-zoom base and the logs do not count (default: 0, no limit)")
- .Add("match-colours", @"on or off: even out the colours of photos from different captures (a grey, hazy one next to a bright, green one), place by place against the low-zoom base, brightness and tint only. Needs mip streaming; the cache keeps the imagery as downloaded, and what each area's photos usually look like is learnt in %LOCALAPPDATA%\OrthoStreamXP\history\colour-match.json (default: off)")
- .Add("match-strength", "How strong the colour matching is, 0-100 percent of each correction (default: 100)")
+ .Add("match-colours", "No longer used: the colour matching between photos was removed (accepted so older settings files still load)")
+ .Add("match-strength", "No longer used: the colour matching between photos was removed (accepted so older settings files still load)")
.Add("seasons", "on or off: colour the photo textures for the season of X-Plane's date and the place: autumn leaves, bare trees and resting fields in winter, fresh green in spring; conifers, roofs, roads and water stay. The cache keeps the imagery as downloaded (default: off)")
.Add("season-strength", $"How strong the seasonal colours are, 0-100 percent (default: {SeasonOptions.DefaultStrength})")
- .Add("season", "auto (X-Plane's date and the place), or a season for everywhere: early-spring, spring, summer, early-autumn, autumn, late-autumn, winter (default: auto)")
+ .Add("season", @"auto (X-Plane's date and the place, by the calendar), satellite (the same, but grass and fields as green as NASA's satellite record of the last year shows the place against its greenest month: a coast green in winter, a dry summer, the tropics' dry season; trees keep the calendar; about 2 MB downloaded once a year for each area of 500 km, kept with the low-zoom base, the calendar where there is none), or a season for everywhere: early-spring, spring, summer, early-autumn, autumn, late-autumn, winter (default: auto)")
.Add("exposure", $"How much light the photo textures let through, {Exposure.Min}-{Exposure.Full} percent: less darkens them evenly, as a camera's exposure, where they look brighter than X-Plane's own scenery. The cache keeps the imagery as downloaded (default: {Exposure.Full})")
.Add("season-land-cover", "No longer used: the seasons go by the colours alone (accepted so older settings files still load)")
.Add("read-log", @"on or off: log every open and read X-Plane makes through the mount, the camera position and every streamed build with what it downloaded, as CSV files in the logs folder (reads-*.csv, camera-*.csv, builds-*.csv), for finding a problem; the flight tuning measures the paging model without them (default: off)");
+
+ private static string ResolutionHelp(string preset) =>
+ $"full, medium or low: how much the {preset} preset's textures are shrunk from the detail its imagery holds. Full keeps it; medium halves the textures of " +
+ "the wide ZL16 areas (8192 px: 4096) and keeps the airports' ZL18 ones; low halves them all. From the same downloads, for less graphics memory, RAM and disk " +
+ "(only halving: X-Plane takes no texture whose size is not a power of two). Used while the settings are at that preset; " +
+ "each resolution keeps its textures in its own cache subfolder (default: full)";
}
diff --git a/src/OrthoStreamXP/Configuration/SkippedPackages.cs b/src/OrthoStreamXP/Configuration/SkippedPackages.cs
new file mode 100644
index 0000000..aed1fb9
--- /dev/null
+++ b/src/OrthoStreamXP/Configuration/SkippedPackages.cs
@@ -0,0 +1,26 @@
+namespace OrthoStreamXP;
+
+///
+/// The packages of base-packages left out of the mount, switched off on the Home page: the skip-packages setting, their
+/// folder names separated by commas.
+///
+internal sealed class SkippedPackages
+{
+ public const string Setting = "skip-packages";
+
+ private readonly HashSet _names;
+
+ private SkippedPackages(IEnumerable names) => _names = new HashSet(names, StringComparer.OrdinalIgnoreCase);
+
+ public static SkippedPackages Parse(string? value) =>
+ new((value ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries));
+
+ public bool Contains(string name) => _names.Contains(name);
+
+ /// These, with left out of the mount () or mounted again.
+ public SkippedPackages With(string name, bool skipped) =>
+ new(skipped ? _names.Append(name) : _names.Where(n => !n.Equals(name, StringComparison.OrdinalIgnoreCase)));
+
+ /// The setting's value; null when every package is mounted (the line is then removed).
+ public string? ToValue() => _names.Count == 0 ? null : string.Join(", ", _names.Order(StringComparer.OrdinalIgnoreCase));
+}
diff --git a/src/OrthoStreamXP/Gui/Home/PackageRow.cs b/src/OrthoStreamXP/Gui/Home/PackageRow.cs
index 70efa5f..8e43c8f 100644
--- a/src/OrthoStreamXP/Gui/Home/PackageRow.cs
+++ b/src/OrthoStreamXP/Gui/Home/PackageRow.cs
@@ -1,12 +1,36 @@
-using System.Diagnostics;
-using System.Globalization;
-using System.Windows.Input;
-using System.Windows.Threading;
-using OrthoStreamXP.Setup;
-using OrthoStreamXP.Textures;
-using OrthoStreamXP.Tuning;
-
namespace OrthoStreamXP.Gui;
-/// A mounted (or to-be-mounted) package: its name and where X-Plane sees it.
-internal sealed record PackageRow(string Name, string Where);
+///
+/// A package of the scenery packages folder on the Home page: its name, where X-Plane sees it, and whether it is mounted,
+/// switched in place while OrthoStreamXP is stopped.
+///
+internal sealed class PackageRow : ObservableObject
+{
+ private readonly Func? _switch;
+ private bool _mounted;
+
+ /// Writes the change, false when it could not (the switch goes back); null while it cannot be changed.
+ public PackageRow(string name, string where, bool mounted, Func? switchTo)
+ {
+ Name = name;
+ Where = where;
+ _mounted = mounted;
+ _switch = switchTo;
+ }
+
+ public string Name { get; }
+ public string Where { get; }
+ public bool CanSwitch => _switch is not null;
+
+ /// Whether it is (or at the next start will be) shown to X-Plane.
+ public bool IsMounted
+ {
+ get => _mounted;
+ set
+ {
+ if (_mounted == value || _switch is null) return;
+ if (_switch(this, value)) _mounted = value;
+ Raise();
+ }
+ }
+}
diff --git a/src/OrthoStreamXP/Gui/MainWindow.xaml b/src/OrthoStreamXP/Gui/MainWindow.xaml
index d29c9fc..6b7b49a 100644
--- a/src/OrthoStreamXP/Gui/MainWindow.xaml
+++ b/src/OrthoStreamXP/Gui/MainWindow.xaml
@@ -11,6 +11,7 @@
+
diff --git a/src/OrthoStreamXP/Gui/Map/Graticule.cs b/src/OrthoStreamXP/Gui/Map/Graticule.cs
new file mode 100644
index 0000000..835cda4
--- /dev/null
+++ b/src/OrthoStreamXP/Gui/Map/Graticule.cs
@@ -0,0 +1,134 @@
+using System.Globalization;
+using System.Windows;
+using System.Windows.Media;
+
+namespace OrthoStreamXP.Gui;
+
+///
+/// The latitude and longitude lines over a 's map, across the whole view, every 1, 2, 5 or 10
+/// degrees as the zoom allows, with their labels along the top and left edges.
+///
+internal sealed class Graticule : FrameworkElement
+{
+ public static readonly DependencyProperty ProjectionProperty = DependencyProperty.Register(nameof(Projection), typeof(MapProjection), typeof(Graticule),
+ new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender));
+
+ public static readonly DependencyProperty StrokeProperty = DependencyProperty.Register(nameof(Stroke), typeof(Brush), typeof(Graticule),
+ new FrameworkPropertyMetadata(Brushes.Gray, FrameworkPropertyMetadataOptions.AffectsRender));
+
+ public static readonly DependencyProperty ForegroundProperty = DependencyProperty.Register(nameof(Foreground), typeof(Brush), typeof(Graticule),
+ new FrameworkPropertyMetadata(Brushes.Black, FrameworkPropertyMetadataOptions.AffectsRender));
+
+ public static readonly DependencyProperty LabelBackgroundProperty = DependencyProperty.Register(nameof(LabelBackground), typeof(Brush), typeof(Graticule),
+ new FrameworkPropertyMetadata(Brushes.White, FrameworkPropertyMetadataOptions.AffectsRender));
+
+ private static readonly int[] Steps = [1, 2, 5, 10, 15, 30];
+ private const double MinSpacing = 44, FontSize = 11;
+ private ZoomPanel? _host;
+
+ public Graticule()
+ {
+ IsHitTestVisible = false;
+ Loaded += (_, _) => Attach();
+ Unloaded += (_, _) => Detach();
+ }
+
+ public MapProjection? Projection
+ {
+ get => (MapProjection?)GetValue(ProjectionProperty);
+ set => SetValue(ProjectionProperty, value);
+ }
+
+ public Brush Stroke
+ {
+ get => (Brush)GetValue(StrokeProperty);
+ set => SetValue(StrokeProperty, value);
+ }
+
+ public Brush Foreground
+ {
+ get => (Brush)GetValue(ForegroundProperty);
+ set => SetValue(ForegroundProperty, value);
+ }
+
+ public Brush LabelBackground
+ {
+ get => (Brush)GetValue(LabelBackgroundProperty);
+ set => SetValue(LabelBackgroundProperty, value);
+ }
+
+ protected override void OnRender(DrawingContext drawingContext)
+ {
+ if (Projection is not { } map || _host is null || ActualWidth <= 0 || ActualHeight <= 0) return;
+ MapViewport view = _host.Viewport;
+ double width = ActualWidth, height = ActualHeight;
+ Point topLeft = view.ToMap(new Point(0, 0)), bottomRight = view.ToMap(new Point(width, height));
+ int lonStep = Step(map.DegreeWidth * view.Scale), latStep = Step(map.Unit * view.Scale);
+ var pen = new Pen(Stroke, 1);
+ pen.Freeze();
+ var lines = new List<(Point, Point)>();
+ var labels = new List<(string Text, double X, double Y, bool Vertical)>();
+ for (int lon = FloorTo(map.Lon(topLeft.X), lonStep); lon <= map.Lon(bottomRight.X); lon += lonStep)
+ {
+ double x = Math.Round(view.ToScreen(new Point(map.X(lon), 0)).X) + 0.5;
+ lines.Add((new Point(x, 0), new Point(x, height)));
+ labels.Add((Invariant($"{Math.Abs(lon)}°{(lon >= 0 ? 'E' : 'W')}"), x, 0, false));
+ }
+ for (int lat = FloorTo(map.Lat(bottomRight.Y), latStep); lat <= map.Lat(topLeft.Y); lat += latStep)
+ {
+ double y = Math.Round(view.ToScreen(new Point(0, map.Y(lat))).Y) + 0.5;
+ lines.Add((new Point(0, y), new Point(width, y)));
+ labels.Add((Invariant($"{Math.Abs(lat)}°{(lat >= 0 ? 'N' : 'S')}"), 0, y, true));
+ }
+
+ drawingContext.PushOpacity(0.45);
+ foreach ((Point from, Point to) in lines) drawingContext.DrawLine(pen, from, to);
+ drawingContext.Pop();
+
+ double dip = VisualTreeHelper.GetDpi(this).PixelsPerDip;
+ var typeface = new Typeface(TextElementFont(), FontStyles.Normal, FontWeights.Normal, FontStretches.Normal);
+ foreach ((string text, double x, double y, bool vertical) in labels)
+ {
+ var formatted = new FormattedText(text, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, typeface, FontSize, Foreground, dip);
+ // Latitudes at the left edge on their line, longitudes at the top edge beside theirs; none in the corner.
+ var at = vertical ? new Point(4, y - formatted.Height / 2) : new Point(x + 3, 3);
+ if (vertical ? at.Y < formatted.Height + 6 || at.Y + formatted.Height > height : at.X < 44 || at.X + formatted.Width > width) continue;
+ var box = new Rect(at.X - 3, at.Y - 1, formatted.Width + 6, formatted.Height + 2);
+ drawingContext.PushOpacity(0.85);
+ drawingContext.DrawRoundedRectangle(LabelBackground, null, box, 3, 3);
+ drawingContext.Pop();
+ drawingContext.DrawText(formatted, at);
+ }
+ }
+
+ /// Degrees between lines: the smallest step at least pixels apart.
+ internal static int Step(double pixelsPerDegree)
+ {
+ foreach (int step in Steps)
+ if (step * pixelsPerDegree >= MinSpacing) return step;
+ return Steps[^1];
+ }
+
+ private static int FloorTo(double degrees, int step) => (int)Math.Floor(degrees / step) * step;
+
+ private static string Invariant(FormattableString text) => FormattableString.Invariant(text);
+
+ private FontFamily TextElementFont() => (FontFamily)GetValue(System.Windows.Documents.TextElement.FontFamilyProperty);
+
+ private void Attach()
+ {
+ Detach();
+ _host = MapCanvas.Ancestor(this);
+ if (_host is null) return;
+ _host.ViewChanged += OnViewChanged;
+ InvalidateVisual();
+ }
+
+ private void Detach()
+ {
+ if (_host is not null) _host.ViewChanged -= OnViewChanged;
+ _host = null;
+ }
+
+ private void OnViewChanged(object? sender, EventArgs e) => InvalidateVisual();
+}
diff --git a/src/OrthoStreamXP/Gui/Map/MapCanvas.cs b/src/OrthoStreamXP/Gui/Map/MapCanvas.cs
new file mode 100644
index 0000000..62c2987
--- /dev/null
+++ b/src/OrthoStreamXP/Gui/Map/MapCanvas.cs
@@ -0,0 +1,93 @@
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Media;
+
+namespace OrthoStreamXP.Gui;
+
+///
+/// A layer of a : places each child at its / in map
+/// units, as the panel shows them. A child with a and
+/// covers that much of the map (a picture of an area); one without keeps its own size whatever the zoom (a label).
+///
+internal sealed class MapCanvas : Panel
+{
+ public static readonly DependencyProperty XProperty = DependencyProperty.RegisterAttached("X", typeof(double), typeof(MapCanvas),
+ new FrameworkPropertyMetadata(0.0, FrameworkPropertyMetadataOptions.AffectsParentArrange));
+
+ public static readonly DependencyProperty YProperty = DependencyProperty.RegisterAttached("Y", typeof(double), typeof(MapCanvas),
+ new FrameworkPropertyMetadata(0.0, FrameworkPropertyMetadataOptions.AffectsParentArrange));
+
+ public static readonly DependencyProperty SpanWidthProperty = DependencyProperty.RegisterAttached("SpanWidth", typeof(double), typeof(MapCanvas),
+ new FrameworkPropertyMetadata(double.NaN, FrameworkPropertyMetadataOptions.AffectsParentMeasure));
+
+ public static readonly DependencyProperty SpanHeightProperty = DependencyProperty.RegisterAttached("SpanHeight", typeof(double), typeof(MapCanvas),
+ new FrameworkPropertyMetadata(double.NaN, FrameworkPropertyMetadataOptions.AffectsParentMeasure));
+
+ private ZoomPanel? _host;
+
+ public MapCanvas()
+ {
+ Loaded += (_, _) => Attach();
+ Unloaded += (_, _) => Detach();
+ }
+
+ public static double GetX(UIElement element) => (double)element.GetValue(XProperty);
+ public static void SetX(UIElement element, double value) => element.SetValue(XProperty, value);
+ public static double GetY(UIElement element) => (double)element.GetValue(YProperty);
+ public static void SetY(UIElement element, double value) => element.SetValue(YProperty, value);
+ public static double GetSpanWidth(UIElement element) => (double)element.GetValue(SpanWidthProperty);
+ public static void SetSpanWidth(UIElement element, double value) => element.SetValue(SpanWidthProperty, value);
+ public static double GetSpanHeight(UIElement element) => (double)element.GetValue(SpanHeightProperty);
+ public static void SetSpanHeight(UIElement element, double value) => element.SetValue(SpanHeightProperty, value);
+
+ protected override Size MeasureOverride(Size availableSize)
+ {
+ double scale = _host?.Viewport.Scale ?? 1;
+ foreach (UIElement child in InternalChildren)
+ child.Measure(Span(child, scale) ?? new Size(double.PositiveInfinity, double.PositiveInfinity));
+ return default;
+ }
+
+ protected override Size ArrangeOverride(Size finalSize)
+ {
+ MapViewport? viewport = _host?.Viewport;
+ double scale = viewport?.Scale ?? 1;
+ foreach (UIElement child in InternalChildren)
+ {
+ var at = new Point(GetX(child), GetY(child));
+ Point screen = viewport?.ToScreen(at) ?? at;
+ child.Arrange(new Rect(screen, Span(child, scale) ?? child.DesiredSize));
+ }
+ return finalSize;
+ }
+
+ private static Size? Span(UIElement child, double scale)
+ {
+ double width = GetSpanWidth(child), height = GetSpanHeight(child);
+ return double.IsNaN(width) || double.IsNaN(height) ? null : new Size(width * scale, height * scale);
+ }
+
+ private void Attach()
+ {
+ Detach();
+ _host = Ancestor(this);
+ if (_host is null) return;
+ _host.ViewChanged += OnViewChanged;
+ InvalidateMeasure();
+ }
+
+ private void Detach()
+ {
+ if (_host is not null) _host.ViewChanged -= OnViewChanged;
+ _host = null;
+ }
+
+ private void OnViewChanged(object? sender, EventArgs e) => InvalidateMeasure();
+
+ internal static T? Ancestor(DependencyObject element) where T : DependencyObject
+ {
+ for (DependencyObject? parent = VisualTreeHelper.GetParent(element); parent is not null; parent = VisualTreeHelper.GetParent(parent))
+ if (parent is T found) return found;
+ return null;
+ }
+}
diff --git a/src/OrthoStreamXP/Gui/Map/MapProjection.cs b/src/OrthoStreamXP/Gui/Map/MapProjection.cs
new file mode 100644
index 0000000..98c300c
--- /dev/null
+++ b/src/OrthoStreamXP/Gui/Map/MapProjection.cs
@@ -0,0 +1,19 @@
+namespace OrthoStreamXP.Gui;
+
+///
+/// Where places are on a map laid out in map units, north up from (, ): a degree of
+/// latitude is units, a degree of longitude that narrowed by (the cosine of the
+/// map's middle latitude, as on a map).
+///
+internal sealed record MapProjection(double West, double North, double Unit, double Squeeze)
+{
+ public double DegreeWidth => Unit * Squeeze;
+
+ public double X(double lon) => (lon - West) * DegreeWidth;
+
+ public double Y(double lat) => (North - lat) * Unit;
+
+ public double Lon(double x) => West + x / DegreeWidth;
+
+ public double Lat(double y) => North - y / Unit;
+}
diff --git a/src/OrthoStreamXP/Gui/Map/MapViewport.cs b/src/OrthoStreamXP/Gui/Map/MapViewport.cs
new file mode 100644
index 0000000..ee4b677
--- /dev/null
+++ b/src/OrthoStreamXP/Gui/Map/MapViewport.cs
@@ -0,0 +1,83 @@
+using System.Windows;
+
+namespace OrthoStreamXP.Gui;
+
+///
+/// What a zoomable map shows: its scale from map units to screen pixels and where the map's corner is on screen. The
+/// whole map fits the view at the smallest scale (no zooming out past that), and it cannot be dragged out of sight; a
+/// map smaller than the view on one side stays centred on that side.
+///
+internal sealed class MapViewport
+{
+ public double Scale { get; private set; } = 1;
+ public double OffsetX { get; private set; }
+ public double OffsetY { get; private set; }
+ public Size View { get; private set; }
+ public Size Content { get; private set; }
+
+ /// The largest scale (screen pixels a map unit).
+ public double MaxScale { get; set; } = 4;
+
+ /// Showing the whole map: it refits when the view or the map changes size.
+ public bool IsFitted { get; private set; } = true;
+
+ /// The scale that shows the whole map.
+ public double FitScale =>
+ Content.Width > 0 && Content.Height > 0 && View.Width > 0 && View.Height > 0
+ ? Math.Min(Math.Min(View.Width / Content.Width, View.Height / Content.Height), MaxScale)
+ : 1;
+
+ public bool CanZoomIn => Scale < Math.Max(FitScale, MaxScale) - 1e-9;
+
+ public bool CanZoomOut => Scale > FitScale + 1e-9;
+
+ public void Resize(Size view, Size content)
+ {
+ View = view;
+ Content = content;
+ if (IsFitted) Fit();
+ else Clamp();
+ }
+
+ public void Fit()
+ {
+ Scale = FitScale;
+ IsFitted = true;
+ Clamp();
+ }
+
+ /// Zooms by , keeping the place under (screen) where it is; false when at the limit.
+ public bool ZoomAt(Point at, double factor)
+ {
+ double fit = FitScale;
+ double scale = Math.Clamp(Scale * factor, fit, Math.Max(fit, MaxScale));
+ if (Math.Abs(scale - Scale) < 1e-9) return false;
+ OffsetX = at.X - (at.X - OffsetX) * scale / Scale;
+ OffsetY = at.Y - (at.Y - OffsetY) * scale / Scale;
+ Scale = scale;
+ IsFitted = scale <= fit + 1e-9;
+ Clamp();
+ return true;
+ }
+
+ public void PanBy(Vector by)
+ {
+ OffsetX += by.X;
+ OffsetY += by.Y;
+ Clamp();
+ }
+
+ public Point ToScreen(Point map) => new(OffsetX + map.X * Scale, OffsetY + map.Y * Scale);
+
+ public Point ToMap(Point screen) => new((screen.X - OffsetX) / Scale, (screen.Y - OffsetY) / Scale);
+
+ private void Clamp()
+ {
+ Scale = Math.Max(Scale, FitScale);
+ OffsetX = ClampAxis(OffsetX, View.Width, Content.Width * Scale);
+ OffsetY = ClampAxis(OffsetY, View.Height, Content.Height * Scale);
+ }
+
+ private static double ClampAxis(double offset, double view, double content) =>
+ content <= view ? (view - content) / 2 : Math.Clamp(offset, view - content, 0);
+}
diff --git a/src/OrthoStreamXP/Gui/Map/ZoomPanel.cs b/src/OrthoStreamXP/Gui/Map/ZoomPanel.cs
new file mode 100644
index 0000000..e570fdc
--- /dev/null
+++ b/src/OrthoStreamXP/Gui/Map/ZoomPanel.cs
@@ -0,0 +1,190 @@
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Input;
+
+namespace OrthoStreamXP.Gui;
+
+///
+/// A map that zooms and pans: the mouse wheel zooms around the pointer, dragging moves the map (a drag never clicks what
+/// it started on), and // are for buttons. Its layers
+/// (, ) place themselves by its . It takes the
+/// width it is given and a height that follows the map's shape, between and
+/// .
+///
+internal sealed class ZoomPanel : Grid
+{
+ public static readonly DependencyProperty ContentWidthProperty = DependencyProperty.Register(nameof(ContentWidth), typeof(double), typeof(ZoomPanel),
+ new FrameworkPropertyMetadata(0.0, FrameworkPropertyMetadataOptions.AffectsMeasure));
+
+ public static readonly DependencyProperty ContentHeightProperty = DependencyProperty.Register(nameof(ContentHeight), typeof(double), typeof(ZoomPanel),
+ new FrameworkPropertyMetadata(0.0, FrameworkPropertyMetadataOptions.AffectsMeasure));
+
+ public static readonly DependencyProperty MaxScaleProperty = DependencyProperty.Register(nameof(MaxScale), typeof(double), typeof(ZoomPanel),
+ new FrameworkPropertyMetadata(4.0, FrameworkPropertyMetadataOptions.AffectsArrange));
+
+ public static readonly DependencyProperty MinViewHeightProperty = DependencyProperty.Register(nameof(MinViewHeight), typeof(double), typeof(ZoomPanel),
+ new FrameworkPropertyMetadata(300.0, FrameworkPropertyMetadataOptions.AffectsMeasure));
+
+ public static readonly DependencyProperty MaxViewHeightProperty = DependencyProperty.Register(nameof(MaxViewHeight), typeof(double), typeof(ZoomPanel),
+ new FrameworkPropertyMetadata(520.0, FrameworkPropertyMetadataOptions.AffectsMeasure));
+
+ /// The scale shown (screen pixels a map unit): set by the panel, for a binding to read.
+ public static readonly DependencyProperty ScaleProperty = DependencyProperty.Register(nameof(Scale), typeof(double), typeof(ZoomPanel),
+ new FrameworkPropertyMetadata(1.0));
+
+ private const double WheelStep = 1.25, ButtonStep = 1.6;
+ private Point? _press;
+ private bool _dragging;
+
+ public ZoomPanel()
+ {
+ ClipToBounds = true;
+ ZoomIn = new RelayCommand(() => ZoomBy(ButtonStep), () => Viewport.CanZoomIn);
+ ZoomOut = new RelayCommand(() => ZoomBy(1 / ButtonStep), () => Viewport.CanZoomOut);
+ ShowAll = new RelayCommand(() =>
+ {
+ Viewport.Fit();
+ Changed();
+ }, () => !Viewport.IsFitted);
+ }
+
+ /// The scale or the position changed: the layers place themselves again.
+ public event EventHandler? ViewChanged;
+
+ public MapViewport Viewport { get; } = new();
+
+ public ICommand ZoomIn { get; }
+ public ICommand ZoomOut { get; }
+ public ICommand ShowAll { get; }
+
+ /// The map's size in map units.
+ public double ContentWidth
+ {
+ get => (double)GetValue(ContentWidthProperty);
+ set => SetValue(ContentWidthProperty, value);
+ }
+
+ public double ContentHeight
+ {
+ get => (double)GetValue(ContentHeightProperty);
+ set => SetValue(ContentHeightProperty, value);
+ }
+
+ public double MaxScale
+ {
+ get => (double)GetValue(MaxScaleProperty);
+ set => SetValue(MaxScaleProperty, value);
+ }
+
+ public double MinViewHeight
+ {
+ get => (double)GetValue(MinViewHeightProperty);
+ set => SetValue(MinViewHeightProperty, value);
+ }
+
+ public double MaxViewHeight
+ {
+ get => (double)GetValue(MaxViewHeightProperty);
+ set => SetValue(MaxViewHeightProperty, value);
+ }
+
+ public double Scale
+ {
+ get => (double)GetValue(ScaleProperty);
+ set => SetValue(ScaleProperty, value);
+ }
+
+ protected override Size MeasureOverride(Size constraint)
+ {
+ double width = double.IsInfinity(constraint.Width) ? ContentWidth : constraint.Width;
+ double height = ContentWidth > 0 ? width * ContentHeight / ContentWidth : MinViewHeight;
+ height = Math.Clamp(height, MinViewHeight, Math.Max(MinViewHeight, MaxViewHeight));
+ if (!double.IsInfinity(constraint.Height)) height = Math.Min(height, constraint.Height);
+ var size = new Size(width, height);
+ base.MeasureOverride(size);
+ return size;
+ }
+
+ protected override Size ArrangeOverride(Size arrangeSize)
+ {
+ var before = (Viewport.Scale, Viewport.OffsetX, Viewport.OffsetY, Viewport.View, Viewport.Content);
+ Viewport.MaxScale = MaxScale;
+ Viewport.Resize(arrangeSize, new Size(ContentWidth, ContentHeight));
+ if (before != (Viewport.Scale, Viewport.OffsetX, Viewport.OffsetY, Viewport.View, Viewport.Content)) Changed();
+ return base.ArrangeOverride(arrangeSize);
+ }
+
+ protected override void OnMouseWheel(MouseWheelEventArgs e)
+ {
+ base.OnMouseWheel(e);
+ // At the limit the wheel scrolls the page instead.
+ if (Viewport.ZoomAt(e.GetPosition(this), Math.Pow(WheelStep, e.Delta / 120.0)))
+ {
+ Changed();
+ e.Handled = true;
+ }
+ }
+
+ protected override void OnPreviewMouseLeftButtonDown(MouseButtonEventArgs e)
+ {
+ base.OnPreviewMouseLeftButtonDown(e);
+ _press = e.GetPosition(this);
+ _dragging = false;
+ }
+
+ protected override void OnPreviewMouseMove(MouseEventArgs e)
+ {
+ base.OnPreviewMouseMove(e);
+ if (_press is not { } press || e.LeftButton != MouseButtonState.Pressed)
+ {
+ _press = null;
+ return;
+ }
+ Point now = e.GetPosition(this);
+ if (!_dragging)
+ {
+ if (Math.Abs(now.X - press.X) < SystemParameters.MinimumHorizontalDragDistance
+ && Math.Abs(now.Y - press.Y) < SystemParameters.MinimumVerticalDragDistance) return;
+ // Taking the mouse from the area pressed: its click is cancelled.
+ _dragging = true;
+ CaptureMouse();
+ Cursor = Cursors.SizeAll;
+ }
+ Viewport.PanBy(now - press);
+ _press = now;
+ Changed();
+ e.Handled = true;
+ }
+
+ protected override void OnPreviewMouseLeftButtonUp(MouseButtonEventArgs e)
+ {
+ base.OnPreviewMouseLeftButtonUp(e);
+ _press = null;
+ if (!_dragging) return;
+ ReleaseMouseCapture();
+ e.Handled = true;
+ }
+
+ protected override void OnLostMouseCapture(MouseEventArgs e)
+ {
+ base.OnLostMouseCapture(e);
+ _dragging = false;
+ _press = null;
+ ClearValue(CursorProperty);
+ }
+
+ private void ZoomBy(double factor)
+ {
+ if (Viewport.ZoomAt(new Point(ActualWidth / 2, ActualHeight / 2), factor)) Changed();
+ }
+
+ private void Changed()
+ {
+ if (Math.Abs(Scale - Viewport.Scale) > 1e-9)
+ {
+ SetCurrentValue(ScaleProperty, Viewport.Scale);
+ RelayCommand.Refresh();
+ }
+ ViewChanged?.Invoke(this, EventArgs.Empty);
+ }
+}
diff --git a/src/OrthoStreamXP/Gui/Scenery/SceneryPackRow.cs b/src/OrthoStreamXP/Gui/Scenery/SceneryPackRow.cs
new file mode 100644
index 0000000..8953310
--- /dev/null
+++ b/src/OrthoStreamXP/Gui/Scenery/SceneryPackRow.cs
@@ -0,0 +1,37 @@
+using OrthoStreamXP.Scenery;
+
+namespace OrthoStreamXP.Gui;
+
+/// An entry of scenery_packs.ini on the Scenery page, switched on or off in place.
+internal sealed class SceneryPackRow : ObservableObject
+{
+ private readonly Func _switch;
+ private bool _enabled;
+
+ /// One of the packages the running mount shows to X-Plane.
+ /// Writes the change; false when it could not, and the switch goes back.
+ public SceneryPackRow(SceneryPackEntry entry, bool streamed, Func switchTo)
+ {
+ Entry = entry;
+ Streamed = streamed;
+ _switch = switchTo;
+ _enabled = entry.Enabled;
+ }
+
+ public SceneryPackEntry Entry { get; }
+ public string Name => Entry.Name;
+ public string Path => Entry.Path;
+ public bool Streamed { get; }
+
+ /// Whether X-Plane loads it: written to the file as soon as it is switched.
+ public bool IsEnabled
+ {
+ get => _enabled;
+ set
+ {
+ if (_enabled == value) return;
+ if (_switch(this, value)) _enabled = value;
+ Raise();
+ }
+ }
+}
diff --git a/src/OrthoStreamXP/Gui/Settings/ColourPreview.cs b/src/OrthoStreamXP/Gui/Settings/ColourPreview.cs
index ee6ab08..1666fb9 100644
--- a/src/OrthoStreamXP/Gui/Settings/ColourPreview.cs
+++ b/src/OrthoStreamXP/Gui/Settings/ColourPreview.cs
@@ -7,9 +7,8 @@
namespace OrthoStreamXP.Gui;
/// The colour settings a preview shows, as the Settings page has them.
-/// 0 to 1.
/// In percent, to 100.
-internal sealed record ColourAdjustments(bool MatchColours, double MatchStrength, SeasonOptions Seasons, double Exposure);
+internal sealed record ColourAdjustments(SeasonOptions Seasons, double Exposure);
/// A photo texture of the cache, at its package name.
internal sealed record PreviewPhoto(string Path, TextureName Name);
@@ -20,9 +19,9 @@ internal sealed record PreviewPicture(byte[] Before, byte[] After, int Size, str
///
/// The colour settings' preview: a photo texture from the cache, adjusted the way X-Plane gets it ()
/// on the level nearest . The season is that of the last flight's date at the photo's place
-/// (or the one chosen), and the colour matching uses the low-zoom base and what was learnt of the area, as the next flight will.
+/// (or the one chosen), as the next flight will.
///
-internal sealed class ColourPreview : IDisposable
+internal sealed class ColourPreview
{
/// The size of the pictures shown, in pixels.
public const int PictureSize = 512;
@@ -32,20 +31,13 @@ internal sealed class ColourPreview : IDisposable
private readonly string _cache;
private readonly string _history;
- private readonly TileStore _store;
- private readonly TileSource _tiles;
- private readonly TextureBuilder _builder;
/// The cache folder.
- /// The folder of the flights' history (the last X-Plane date, the areas' colours).
+ /// The folder of the flights' history (the last X-Plane date).
public ColourPreview(string cache, string history)
{
_cache = cache;
_history = history;
- _store = new TileStore(Path.Join(cache, TileStore.FolderName));
- // Only the low-zoom base on disk is read: nothing is downloaded.
- _tiles = new TileSource(ImageryProvider.ParseList("bing", null), 1) { Store = _store };
- _builder = new TextureBuilder(_tiles, 1);
}
/// The photos to show, most recently made first; the finer ground zooms (ZL16 and up) before the coarse far scenery.
@@ -77,42 +69,39 @@ public IReadOnlyList FindPhotos(CancellationToken cancel = default
byte[] before = Dds.DecodeLevel(blocks, levelSize, levelSize);
var notes = new List();
- TextureColour? colour = settings.MatchColours ? MatchColours(photo, file, size, settings.MatchStrength, notes) : null;
- ushort[]? season = settings.Seasons.On ? Season(photo.Name, settings.Seasons, notes) : null;
- ushort[]? exposure = Exposure.TableFor(settings.Exposure);
- if (exposure is not null) notes.Add(FormattableString.Invariant($"Exposure {settings.Exposure:0} %"));
- if (notes.Count == 0) notes.Add("No colour change: the photos are shown as downloaded");
+ // As the mount: one table for the season, the contrast (always on) and the exposure.
+ ushort[] withoutSeason = PhotoColours.TableFor(SeasonState.Summer, settings.Exposure);
+ ushort[] table = settings.Seasons.On ? Season(photo.Name, settings.Seasons, settings.Exposure, withoutSeason, notes) : withoutSeason;
+ if (Exposure.Percent(settings.Exposure) < Exposure.Full) notes.Add(FormattableString.Invariant($"Exposure {settings.Exposure:0} %"));
+ notes.Add(FormattableString.Invariant($"Contrast {Contrast.Strength * 100:0} % (always on)"));
- PhotoColours.Apply(blocks, layout.Offset(mip), 8, size, colour, season, exposure);
+ PhotoColours.Apply(blocks, layout.Offset(mip), 8, table);
return new PreviewPicture(before, Dds.DecodeLevel(blocks, levelSize, levelSize), levelSize, Place(photo.Name), notes);
}
- private TextureColour? MatchColours(PreviewPhoto photo, Microsoft.Win32.SafeHandles.SafeFileHandle file, int size, double strength, List notes)
- {
- if (!_builder.StoreHasRegion(photo.Name, _store.MaxZoom))
- {
- notes.Add("Colour matching: the low-zoom base of this place is not in the cache");
- return null;
- }
- // A new matcher each time: the strength is its own, and nothing it learns is saved.
- var matcher = new ColourMatcher(name => _builder.TryStoredRegion(name, _store.MaxZoom), _builder.ResizeTo,
- Path.Join(_history, ColourMatcher.FileName), strength);
- TextureColour? colour = matcher.ForPhoto(photo.Name, photo.Path, wanted => SceneryFileSystem.FileSample(file, size, wanted));
- notes.Add(colour is null
- ? "Colour matching: this photo already fits its area"
- : FormattableString.Invariant($"Colour matching {strength * 100:0} %"));
- return colour;
- }
-
- private ushort[]? Season(TextureName name, SeasonOptions options, List notes)
+ /// The texture's table for its season and (: the table of summer).
+ private ushort[] Season(TextureName name, SeasonOptions options, double exposurePercent, ushort[] withoutSeason, List notes)
{
string dayFile = Path.Join(_history, SeasonClock.DayFileName);
- var clock = new SeasonClock(options, dayFile);
- string when = options.Choice == SeasonChoice.Auto
+ // The satellite record as the flights kept it: nothing is downloaded.
+ using ObservedSeasons? observed = options.Choice == SeasonChoice.Satellite
+ ? new ObservedSeasons(new VegetationSource(Path.Join(_cache, TileStore.FolderName, VegetationSource.FolderName), TimeProvider.System, download: false), TimeSpan.FromSeconds(5))
+ : null;
+ var clock = new SeasonClock(options, dayFile, observed, exposurePercent);
+ string when = options.FollowsDate
? $"Season of {SeasonClock.Describe(clock.Day)} ({(File.Exists(dayFile) ? "the last flight's date" : "today")}) here"
: $"Season: {SeasonModel.Names.First(n => n.Value == options.Choice).Key.Replace('-', ' ')}";
- ushort[]? table = clock.TableFor(name);
- notes.Add(table is null ? $"{when}: the photo as it is" : FormattableString.Invariant($"{when}, {options.Strength * 100:0} %"));
+ if (observed is not null)
+ {
+ var (lat, lon) = name.Center;
+ notes.Add(observed.YearAt(lat, lon) is { } year
+ ? $"Satellite record here on {SeasonClock.Describe(clock.Day)}: {ObservedSeason.Describe(year, clock.Day)}"
+ : "No satellite record of this place yet (it is downloaded on the first flight there): the calendar's season");
+ }
+ ushort[] table = clock.TableFor(name);
+ // Where the season changes nothing, the table is summer's (PhotoColours.TableFor).
+ bool seasonal = !ReferenceEquals(table, withoutSeason);
+ notes.Add(seasonal ? FormattableString.Invariant($"{when}, {options.Strength * 100:0} %") : $"{when}: the photo as it is");
return table;
}
@@ -122,6 +111,4 @@ private static string Place(TextureName name)
return string.Create(CultureInfo.InvariantCulture,
$"{Math.Abs(lat):0.00}° {(lat >= 0 ? 'N' : 'S')}, {Math.Abs(lon):0.00}° {(lon >= 0 ? 'E' : 'W')} (ZL{name.Zoom})");
}
-
- public void Dispose() => _tiles.Dispose();
}
diff --git a/src/OrthoStreamXP/Gui/Settings/PresetMemory.cs b/src/OrthoStreamXP/Gui/Settings/PresetMemory.cs
index 23b92d1..f94b875 100644
--- a/src/OrthoStreamXP/Gui/Settings/PresetMemory.cs
+++ b/src/OrthoStreamXP/Gui/Settings/PresetMemory.cs
@@ -13,18 +13,26 @@ internal static class PresetMemory
public static long? Card { get; } = Tuning.GraphicsMemory.CardBytes();
- /// The preset for this PC: from the graphics card, and the last flight once there is one.
- public static Tuning.Recommendation Recommended { get; private set; } = Tuning.PresetAdvisor.Recommend(Card, Tuning.GraphicsMemory.TestFlight, [],
- ConnectionResult.Load(ConnectionResult.PathFor(SettingsDocument.DefaultPath)));
-
/// The latest connection test, kept beside the settings file.
public static ConnectionResult? Connection { get; private set; } = ConnectionResult.Load(ConnectionResult.PathFor(SettingsDocument.DefaultPath));
+ /// The preset for this PC: from the graphics card, and the last flight once there is one.
+ public static Tuning.Recommendation Recommended { get; private set; } = Tuning.PresetAdvisor.Recommend(Card, Tuning.GraphicsMemory.TestFlight, [], Connection);
+
+ ///
+ /// How each preset suits this PC, from the same facts as ; Dynamic from each base is among
+ /// them, so its card tells of the base chosen on it.
+ ///
+ public static IReadOnlyList Fits { get; private set; } = Tuning.PresetAdvisor.Assess(Card, Tuning.GraphicsMemory.TestFlight, [], Connection, QualityPreset.Offered);
+
+ public static PresetFit? FitOf(QualityPreset preset) => Fits.FirstOrDefault(f => f.Preset == preset);
+
public static void Load(string? cache)
{
Estimate = Tuning.GraphicsMemory.Load(AppPaths.History);
Connection = ConnectionResult.Load(ConnectionResult.PathFor(SettingsDocument.DefaultPath));
Tuning.FlightReport[] flights = [.. Tuning.FlightReport.History(AppPaths.History)];
Recommended = Tuning.PresetAdvisor.Recommend(Card, Estimate, flights, Connection);
+ Fits = Tuning.PresetAdvisor.Assess(Card, Estimate, flights, Connection, QualityPreset.Offered);
}
}
diff --git a/src/OrthoStreamXP/Gui/Settings/PresetOption.cs b/src/OrthoStreamXP/Gui/Settings/PresetOption.cs
index a03b0e1..2fce47b 100644
--- a/src/OrthoStreamXP/Gui/Settings/PresetOption.cs
+++ b/src/OrthoStreamXP/Gui/Settings/PresetOption.cs
@@ -7,31 +7,110 @@
namespace OrthoStreamXP.Gui;
/// A quality preset as a card on the Settings page and in the setup.
-internal sealed class PresetOption(QualityPreset preset, Action choose) : ObservableObject
+/// Keeps the card's resolution when it is changed; null where the card offers none.
+///
+/// Dynamic's card: its base (Extra, Ultra or Sharp) was changed, and the card is now Dynamic from it; null where the
+/// card offers no base.
+///
+internal sealed class PresetOption(QualityPreset preset, Action choose, Action? saveResolution = null,
+ Action? chooseBase = null)
+ : ObservableObject
{
private bool _isSelected;
+ private TextureResolution _resolution = TextureResolution.Full;
+ private QualityPreset _preset = preset;
- public QualityPreset Preset { get; } = preset;
+ /// The preset the card stands for: on Dynamic's card, Dynamic from the base chosen on it.
+ public QualityPreset Preset => _preset;
public string Title => Preset.Name;
public string Summary => Preset.Summary;
/// The preset the evidence recommends for this PC ().
public bool IsRecommended => Preset == PresetMemory.Recommended.Preset;
+ /// The badge: "Recommended", with the resolution when it is not Full ("Recommended at Medium").
+ public string? RecommendedBadge => !IsRecommended ? null
+ : PresetMemory.Recommended.Resolution.IsFull ? "Recommended" : $"Recommended at {PresetMemory.Recommended.Resolution.Label}";
+
/// Why it is recommended, under its badge.
public string? RecommendedReason => IsRecommended ? PresetMemory.Recommended.Reason : null;
- public string Details => Preset == QualityPreset.Dynamic
- ? $"Below 5,000 ft as Extra: zoom {Preset.Zl16Zoom} in most areas, {Preset.Zl18Zoom} near airports · higher up as Sharp, then Balanced · sharp again before a descent reaches the ground · a new area loads in {Preset.FirstVisit}"
- : $"Zoom {Preset.Zl16Zoom} in most areas, {Preset.Zl18Zoom} near airports · about {Preset.MetresPerPixel:0.#} m per pixel · a new area loads in {Preset.FirstVisit}";
+ /// On the other cards: that it also suits this PC, and at which resolution, or why it does not.
+ public string? FitText => IsRecommended ? null : PresetMemory.FitOf(Preset)?.Text;
+
+ /// It suits this PC (its line in the accent colour; otherwise in the caution colour).
+ public bool Suits => PresetMemory.FitOf(Preset)?.Suits == true;
+
+ public string Details => Preset is { DynamicBase: { } near, DynamicSteps: [var first, ..] steps }
+ ? string.Create(CultureInfo.CurrentCulture,
+ $"Below {first.AboveFt:N0} ft as {near.Name}: zoom {Preset.Zl16Zoom} in most areas, {Preset.Zl18Zoom} near airports · higher up as {string.Join(", then ", steps.Select(t => t.Name))} · sharp again before a descent reaches the ground · a new area loads in {Preset.FirstVisit}")
+ : string.Create(CultureInfo.CurrentCulture,
+ $"Zoom {Preset.Zl16Zoom} in most areas, {Preset.Zl18Zoom} near airports · about {Preset.MetresPerPixelAt(Resolution):0.#} m per pixel · a new area loads in {Preset.FirstVisit}");
public string BestFor => $"Best for: {Preset.BestFor}";
+ /// The bases Dynamic's card offers: Extra, Ultra and Sharp; none on the other cards.
+ public IReadOnlyList Bases { get; } = preset.IsDynamic ? [.. QualityPreset.DynamicChoices.Select(p => p.DynamicBase!)] : [];
+
+ /// The card offers a base (Dynamic's, on the Settings page and in the setup).
+ public bool OffersBase => chooseBase is not null && Bases.Count > 0;
+
+ /// Dynamic's base: the preset it is near the ground. Changing it makes the card Dynamic from that base.
+ public QualityPreset? Base
+ {
+ get => Preset.DynamicBase;
+ set
+ {
+ if (value is null || value == Preset.DynamicBase || QualityPreset.DynamicOn(value) is not { } dynamic) return;
+ _preset = dynamic;
+ RaisePreset();
+ chooseBase?.Invoke(dynamic);
+ }
+ }
+
+ /// Shows Dynamic from the base the settings have, without choosing it (when loading).
+ public void ShowBase(QualityPreset dynamic)
+ {
+ if (!Preset.IsDynamic || !dynamic.IsDynamic || dynamic == Preset) return;
+ _preset = dynamic;
+ RaisePreset();
+ }
+
+ /// The resolutions offered beside the preset.
+ public IReadOnlyList Resolutions { get; } = TextureResolution.All;
+
+ /// The card offers a resolution (the Settings page and the setup).
+ public bool OffersResolution => saveResolution is not null;
+
+ /// How much this preset's textures are shrunk: kept for each preset, used while the settings are at it.
+ public TextureResolution Resolution
+ {
+ get => _resolution;
+ set
+ {
+ if (value is null || !Set(ref _resolution, value)) return;
+ saveResolution?.Invoke(Preset, value);
+ RaiseResolution();
+ }
+ }
+
+ /// The texture sizes a shrunk resolution gives, under the summary's full-resolution ones; null at Full.
+ public string? ResolutionText
+ {
+ get
+ {
+ if (Resolution.IsFull) return null;
+ TexturePlan plan = Preset.PlanAt(Resolution);
+ return string.Create(CultureInfo.CurrentCulture,
+ $"At {Resolution.Label} resolution: {plan.SizeFor(16)} px textures in most areas, {plan.SizeFor(18)} px near airports, from the same imagery.");
+ }
+ }
+
/// The photo textures' graphics memory at this preset, as flown on this PC (or on the test flight).
public string MemoryText
{
get
{
- long bytes = PresetMemory.Estimate.BytesAt(Preset.Size);
+ long bytes = PresetMemory.Estimate.BytesAt(Preset.PlanAt(Resolution));
string source = PresetMemory.Estimate == Tuning.GraphicsMemory.TestFlight ? "on a test flight" : "on your last long flight";
return $"Photo textures take about {CacheInventory.FormatBytes(bytes)} of graphics memory at the most ({source}).";
}
@@ -45,10 +124,10 @@ public string? MemoryWarning
get
{
if (PresetMemory.Card is not { } card) return null;
- long bytes = PresetMemory.Estimate.BytesAt(Preset.Size);
+ long bytes = PresetMemory.Estimate.BytesAt(Preset.PlanAt(Resolution));
return bytes + Tuning.GraphicsMemory.XPlaneOwnBytes <= card ? null
: $"Your graphics card has {CacheInventory.FormatBytes(card)}. With X-Plane's own needs (about 5 GB), {Preset.Name} may run it short: "
- + "X-Plane then stutters, or lowers the detail of its textures. A smaller preset is safer.";
+ + "X-Plane then stutters, or lowers the detail of its textures. A smaller preset or a lower resolution is safer.";
}
}
@@ -58,7 +137,10 @@ public void RefreshMemory()
Raise(nameof(MemoryText));
Raise(nameof(MemoryWarning));
Raise(nameof(IsRecommended));
+ Raise(nameof(RecommendedBadge));
Raise(nameof(RecommendedReason));
+ Raise(nameof(FitText));
+ Raise(nameof(Suits));
}
public bool IsSelected
@@ -76,4 +158,30 @@ public void Show(bool selected)
_isSelected = selected;
Raise(nameof(IsSelected));
}
+
+ /// Shows the resolution the settings have, without saving it again (when loading).
+ public void ShowResolution(TextureResolution resolution)
+ {
+ _resolution = resolution;
+ Raise(nameof(Resolution));
+ RaiseResolution();
+ }
+
+ private void RaisePreset()
+ {
+ Raise(nameof(Preset));
+ Raise(nameof(Base));
+ Raise(nameof(Summary));
+ Raise(nameof(BestFor));
+ RaiseResolution();
+ RefreshMemory();
+ }
+
+ private void RaiseResolution()
+ {
+ Raise(nameof(ResolutionText));
+ Raise(nameof(Details));
+ Raise(nameof(MemoryText));
+ Raise(nameof(MemoryWarning));
+ }
}
diff --git a/src/OrthoStreamXP/Gui/Settings/SettingNames.cs b/src/OrthoStreamXP/Gui/Settings/SettingNames.cs
index 56e1521..1ad8685 100644
--- a/src/OrthoStreamXP/Gui/Settings/SettingNames.cs
+++ b/src/OrthoStreamXP/Gui/Settings/SettingNames.cs
@@ -13,11 +13,10 @@ internal static class SettingNames
["xplane"] = "X-Plane folder",
["base-packages"] = "Scenery packages folder",
["source"] = "Scenery packages folder",
+ [SkippedPackages.Setting] = "Scenery packages switched off",
["cache"] = "Cache folder",
["texture-provider"] = "Where the pictures come from",
["download-workers"] = "Downloads at once",
- ["match-colours"] = "Colour matching",
- ["match-strength"] = "Colour matching",
["seasons"] = "Seasons",
["season"] = "Seasons",
["season-strength"] = "Seasons",
diff --git a/src/OrthoStreamXP/Gui/ViewModels/CacheMapViewModel.cs b/src/OrthoStreamXP/Gui/ViewModels/CacheMapViewModel.cs
index 65c15b8..535482d 100644
--- a/src/OrthoStreamXP/Gui/ViewModels/CacheMapViewModel.cs
+++ b/src/OrthoStreamXP/Gui/ViewModels/CacheMapViewModel.cs
@@ -6,7 +6,7 @@
namespace OrthoStreamXP.Gui;
-/// One area on the cache map: where it is drawn, its picture, and whether it is selected.
+/// One area on the cache map: where it is (in map units), its picture, and whether it is selected.
internal sealed class AreaTile(CacheArea area, double left, double top, double width, double height, Action toggled) : ObservableObject
{
private bool _selected;
@@ -50,26 +50,29 @@ public string ToolTip
}
internal static string QualityName(string setupFolder) =>
- CacheInventory.ParseSetupName(setupFolder) is { } setup && QualityPreset.ForLevel(setup.Level) is { } preset ? preset.Name : setupFolder;
+ CacheInventory.ParseSetupName(setupFolder)?.PresetTitle ?? setupFolder;
}
-/// A label at the edge of the cache map: a latitude or a longitude.
-internal sealed record MapLabel(string Text, double Left, double Top);
-
///
/// The cache map on the Cache page: every cached 1° area where it is on the globe (longitudes narrowed by the cosine of
/// the latitude, as on a map), as a small picture made from its own textures; areas are selected by clicking them and
-/// deleted together.
+/// deleted together. The map is laid out in map units ( a degree of latitude); the view zooms it.
///
internal sealed class CacheMapViewModel : ObservableObject
{
- public const double MaxWidth = 820, MaxHeight = 440;
- private const int PicturePixels = 48;
+ /// Map units a degree of latitude.
+ public const double Unit = 100;
+
+ /// Degrees of map around the areas, so the outer ones are not at the edge.
+ private const double Margin = 0.5;
+
+ private const int PicturePixels = 96;
private readonly CacheViewModel _owner;
private IReadOnlyList _tiles = [];
- private IReadOnlyList _labels = [];
private IReadOnlyList _cities = [];
- private double _width, _height;
+ private MapProjection? _projection;
+ private Setup.GeoBounds _bounds;
+ private double _width, _height, _zoom = 1, _placedZoom;
private bool _confirming, _deleting;
private int _version;
@@ -107,13 +110,14 @@ private set
}
}
- public IReadOnlyList Labels
+ /// Where places are on the map, for its latitude and longitude lines.
+ public MapProjection? Projection
{
- get => _labels;
- private set => Set(ref _labels, value);
+ get => _projection;
+ private set => Set(ref _projection, value);
}
- /// City names over the map, largest first where they would crowd.
+ /// City names over the map, largest first where they would crowd; more of them as the map is zoomed in.
public IReadOnlyList CityLabels
{
get => _cities;
@@ -122,6 +126,19 @@ public IReadOnlyList CityLabels
public bool HasAreas => Tiles.Count > 0;
+ /// The scale the map is shown at (screen pixels a map unit): the city names are placed for it.
+ public double Zoom
+ {
+ get => _zoom;
+ set
+ {
+ if (!(value > 0) || value == _zoom) return;
+ _zoom = value;
+ if (Math.Abs(Math.Log2(_zoom / _placedZoom)) >= 0.3) PlaceCities();
+ }
+ }
+
+ /// The map's size in map units.
public double Width
{
get => _width;
@@ -155,30 +172,17 @@ public void Show(IReadOnlyList areas, string cache)
Confirming = false;
if (areas.Count == 0)
{
- (Tiles, Labels, CityLabels, Width, Height) = ([], [], [], 0, 0);
+ (Tiles, CityLabels, Projection, Width, Height) = ([], [], null, 0, 0);
SelectionChanged();
return;
}
int south = areas.Min(a => a.Name.Lat), north = areas.Max(a => a.Name.Lat) + 1;
int west = areas.Min(a => a.Name.Lon), east = areas.Max(a => a.Name.Lon) + 1;
- double squeeze = Math.Cos((south + north) / 2.0 * Math.PI / 180);
- double cell = Math.Clamp(Math.Min(MaxWidth / ((east - west) * squeeze), MaxHeight / (north - south)), 6, 72);
- double cellWidth = cell * squeeze;
- const double margin = 34;
- var tiles = areas.Select(a => new AreaTile(a, margin + (a.Name.Lon - west) * cellWidth, margin + (north - 1 - a.Name.Lat) * cell, cellWidth, cell, _ => SelectionChanged())).ToList();
- // A label every few degrees, so they never crowd.
- int step = Math.Max(1, (int)Math.Ceiling(28 / cell));
- var labels = new List();
- for (int lat = south; lat < north; lat += step)
- labels.Add(new MapLabel(FormattableString.Invariant($"{Math.Abs(lat)}°{(lat >= 0 ? 'N' : 'S')}"), 0, margin + (north - 1 - lat) * cell + cell / 2 - 8));
- step = Math.Max(1, (int)Math.Ceiling(40 / cellWidth));
- for (int lon = west; lon < east; lon += step)
- labels.Add(new MapLabel(FormattableString.Invariant($"{Math.Abs(lon)}°{(lon >= 0 ? 'E' : 'W')}"), margin + (lon - west) * cellWidth, 8));
- (Tiles, Labels, Width, Height) = (tiles, labels, margin + (east - west) * cellWidth + 4, margin + (north - south) * cell + 4);
- // Names over the map: about 6.5 px a letter at 11 px, on a small tag.
- CityLabels = Cities.Place(new Setup.GeoBounds(south, west, north, east),
- (lat, lon) => new System.Windows.Point(margin + (lon - west) * cellWidth, margin + (north - lat) * cell),
- name => new System.Windows.Size(name.Length * 6.5 + 8, 16), Width, Height, max: 60);
+ var map = new MapProjection(west - Margin, north + Margin, Unit, Math.Cos((south + north) / 2.0 * Math.PI / 180));
+ var tiles = areas.Select(a => new AreaTile(a, map.X(a.Name.Lon), map.Y(a.Name.Lat + 1), map.DegreeWidth, map.Unit, _ => SelectionChanged())).ToList();
+ _bounds = new Setup.GeoBounds(south - Margin, west - Margin, north + Margin, east + Margin);
+ (Tiles, Projection, Width, Height) = (tiles, map, map.X(_bounds.East), map.Y(_bounds.South));
+ PlaceCities();
SelectionChanged();
_ = PaintAsync(tiles, cache, version);
}
@@ -203,9 +207,27 @@ private async Task PaintAsync(IReadOnlyList tiles, string cache, int v
private static readonly System.Collections.Concurrent.ConcurrentDictionary Pictures = new();
+ ///
+ /// Names the cities for the zoom shown: a label keeps its size on screen (about 6.5 px a letter at 11 px, on a small
+ /// tag), so it covers less of the map as the map is zoomed in, and more fit; about one a 90 px square of the map.
+ ///
+ private void PlaceCities()
+ {
+ _placedZoom = _zoom;
+ if (Projection is not { } map)
+ {
+ CityLabels = [];
+ return;
+ }
+ double zoom = _zoom;
+ int max = (int)Math.Clamp(Width * Height * zoom * zoom / 8000, 20, 300);
+ CityLabels = Cities.Place(_bounds, (lat, lon) => new System.Windows.Point(map.X(lon), map.Y(lat)),
+ name => new System.Windows.Size(Math.Max(1, (name.Length * 6.5 + 8) / zoom), Math.Max(1, 16 / zoom)), Width, Height, max);
+ }
+
private static ImageSource? Picture(string cache, string folder, CacheArea area)
{
- string name = $"{area.Name}-{area.Bytes}-v2.png";
+ string name = $"{area.Name}-{area.Bytes}-v3.png";
if (Pictures.TryGetValue(name, out ImageSource? known)) return known;
string file = Path.Join(folder, name);
try
diff --git a/src/OrthoStreamXP/Gui/ViewModels/CacheViewModel.cs b/src/OrthoStreamXP/Gui/ViewModels/CacheViewModel.cs
index a80cd13..326d790 100644
--- a/src/OrthoStreamXP/Gui/ViewModels/CacheViewModel.cs
+++ b/src/OrthoStreamXP/Gui/ViewModels/CacheViewModel.cs
@@ -43,7 +43,7 @@ public string Title
if (Entry.Kind == CacheEntryKind.Logs) return "Logs";
if (Entry.Kind == CacheEntryKind.Base) return "Low-zoom base";
if (Entry.Setup is not { } setup) return $"{Entry.Name} (older layout)";
- if (QualityPreset.ForLevel(setup.Level) is { } preset) return preset.Name;
+ if (setup.PresetTitle is { } preset) return preset;
return $"Level {setup.Level.ToString("+0;−0;0", CultureInfo.InvariantCulture)}";
}
}
diff --git a/src/OrthoStreamXP/Gui/ViewModels/ColourPreviewViewModel.cs b/src/OrthoStreamXP/Gui/ViewModels/ColourPreviewViewModel.cs
index 2ea3bf0..070a07f 100644
--- a/src/OrthoStreamXP/Gui/ViewModels/ColourPreviewViewModel.cs
+++ b/src/OrthoStreamXP/Gui/ViewModels/ColourPreviewViewModel.cs
@@ -9,7 +9,7 @@ namespace OrthoStreamXP.Gui;
/// The Colours tab's before and after pictures (): a photo from the cache, made again off the UI
/// thread whenever a colour setting changes; a change made meanwhile replaces the picture being made.
///
-internal sealed class ColourPreviewViewModel : ObservableObject, IDisposable
+internal sealed class ColourPreviewViewModel : ObservableObject
{
private readonly Func _cache;
private readonly Func _settings;
@@ -96,7 +96,6 @@ public void Refresh()
}
if (!string.Equals(cache, _previewCache, StringComparison.OrdinalIgnoreCase))
{
- _preview?.Dispose();
_preview = new ColourPreview(cache, AppPaths.History);
_previewCache = cache;
_photos = [];
@@ -123,8 +122,7 @@ private async Task RenderAsync(int version, ColourPreview preview, IReadOnlyList
return (found, null, (string?)null);
}).ConfigureAwait(true);
}
- // ObjectDisposedException: the cache folder changed while this picture was being made; a newer one replaces it.
- catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or ObjectDisposedException)
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException)
{
result = (photos, null, $"The preview could not read the cache: {ex.Message}");
}
@@ -153,6 +151,4 @@ private static BitmapSource Bitmap(byte[] rgb, int size)
bitmap.Freeze();
return bitmap;
}
-
- public void Dispose() => _preview?.Dispose();
}
diff --git a/src/OrthoStreamXP/Gui/ViewModels/HomeViewModel.cs b/src/OrthoStreamXP/Gui/ViewModels/HomeViewModel.cs
index 6b0eb2c..1d81414 100644
--- a/src/OrthoStreamXP/Gui/ViewModels/HomeViewModel.cs
+++ b/src/OrthoStreamXP/Gui/ViewModels/HomeViewModel.cs
@@ -57,6 +57,7 @@ public HomeViewModel(MainViewModel main)
Mount.PropertyChanged += (_, e) =>
{
if (e.PropertyName is not (nameof(MountController.State) or nameof(MountController.Problem))) return;
+ if (e.PropertyName == nameof(MountController.State)) LoadPackages(SettingsDocument.Load(SettingsDocument.DefaultPath));
if (Mount.State == MountState.Stopped)
{
LoadReview();
@@ -317,7 +318,9 @@ public IReadOnlyList Packages
private set => Set(ref _packages, value);
}
- public string PackagesCaption => Mount.IsRunning ? "Shown in X-Plane now" : "Shown in X-Plane while OrthoStreamXP runs";
+ public string PackagesCaption => Mount.IsStopped
+ ? "Shown in X-Plane while OrthoStreamXP runs. Switch a package off to leave it out."
+ : Mount.IsRunning ? "Shown in X-Plane now. Stop OrthoStreamXP to change which packages are shown." : "Stop OrthoStreamXP to change which packages are shown.";
public void OnShown()
{
@@ -392,24 +395,60 @@ private void LoadSettingsSummary()
SettingsDocument settings = SettingsDocument.Load(SettingsDocument.DefaultPath);
int? level = settings.GetInt("level-change");
QualityPreset? preset = QualityPreset.Current(level ?? 0, settings.GetBool(QualityPreset.DynamicQualityKey) == true);
- QualityTitle = preset?.Name ?? $"Custom (level {level ?? 0})";
- var plan = new TexturePlan(level ?? 0);
+ TexturePlan plan = QualityPreset.PlanIn(settings);
+ QualityTitle = preset is null ? $"Custom (level {level ?? 0})"
+ : plan.Resolution.IsFull ? preset.Title : $"{preset.Title}, {plan.Resolution.Label} resolution";
string zooms = $"{plan.SizeFor(16)} px textures from zoom {plan.FetchZoom(16)} in most areas and zoom {plan.FetchZoom(18)} near airports";
QualityText = preset is null ? $"{zooms}."
- : preset == QualityPreset.Dynamic ? $"Near the ground {zooms}; higher up as Sharp, then Balanced. A new area loads in {preset.FirstVisit}."
- : $"{zooms}, about {preset.MetresPerPixel:0.#} m per pixel. A new area loads in {preset.FirstVisit}.";
+ : preset.IsDynamic ? $"Near the ground {zooms}; higher up as {string.Join(", then ", preset.DynamicSteps.Select(t => t.Name))}. A new area loads in {preset.FirstVisit}."
+ : $"{zooms}, about {preset.MetresPerPixelAt(plan.Resolution):0.#} m per pixel. A new area loads in {preset.FirstVisit}.";
- if (Mount.Running is { } running)
- Packages = [.. running.Packages.Select(p => new PackageRow(p.Name, p.Mountpoint))];
+ LoadPackages(settings);
+ }
+
+ ///
+ /// Every package of the scenery packages folder, mounted or switched off; switchable only while OrthoStreamXP is stopped
+ /// (with a single source package, the running mount's packages and nothing to switch).
+ ///
+ private void LoadPackages(SettingsDocument settings)
+ {
+ string? xplane = settings.Get("xplane");
+ IReadOnlyList names = SystemCheck.PackagesIn(settings.Get("base-packages"));
+ MountSettings? running = Mount.Running;
+ if (names.Count == 0 && running is not null)
+ {
+ Packages = [.. running.Packages.Select(p => new PackageRow(p.Name, p.Mountpoint, mounted: true, switchTo: null))];
+ }
else
{
- string? xplane = settings.Get("xplane");
- Packages = [.. SystemCheck.PackagesIn(settings.Get("base-packages"))
- .Select(name => new PackageRow(name, xplane is null ? "" : Path.Join(xplane, "Custom Scenery", name)))];
+ SkippedPackages skipped = SkippedPackages.Parse(settings.Get(SkippedPackages.Setting));
+ var mounted = running is null ? null : new HashSet(running.Packages.Select(p => p.Name), StringComparer.OrdinalIgnoreCase);
+ Func? switchTo = Mount.IsStopped ? SwitchPackage : null;
+ Packages = [.. names.Select(name => new PackageRow(name, xplane is null ? "" : Path.Join(xplane, "Custom Scenery", name),
+ mounted?.Contains(name) ?? !skipped.Contains(name), switchTo))];
}
Raise(nameof(PackagesCaption));
}
+ /// Writes a package switched on or off to skip-packages; it takes effect at the next start.
+ private bool SwitchPackage(PackageRow row, bool mounted)
+ {
+ if (!Mount.IsStopped) return false;
+ try
+ {
+ SettingsDocument settings = SettingsDocument.Load(SettingsDocument.DefaultPath);
+ settings.Set(SkippedPackages.Setting, SkippedPackages.Parse(settings.Get(SkippedPackages.Setting)).With(row.Name, skipped: !mounted).ToValue());
+ settings.Save();
+ Log.Info($"{row.Name} {(mounted ? "is mounted again" : "is left out of the mount")} from the next start");
+ return true;
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ Log.Warning($"Could not save {SkippedPackages.Setting} for {row.Name}: {ex.Message}");
+ return false;
+ }
+ }
+
// ---------------------------------------------------------------- the last flight's report
/// The report of the last flight: from the session just stopped, or the one saved in the log folder.
diff --git a/src/OrthoStreamXP/Gui/ViewModels/MainViewModel.cs b/src/OrthoStreamXP/Gui/ViewModels/MainViewModel.cs
index 8705524..92bfece 100644
--- a/src/OrthoStreamXP/Gui/ViewModels/MainViewModel.cs
+++ b/src/OrthoStreamXP/Gui/ViewModels/MainViewModel.cs
@@ -71,6 +71,7 @@ public MainViewModel()
Cache = new CacheViewModel(this);
Packages = new PackagesViewModel(Mount, Preferences, MeshHttp, MeshInstalls,
() => SettingsDocument.Load(SettingsDocument.DefaultPath).Get("base-packages"));
+ Scenery = new SceneryViewModel(Mount, () => SettingsDocument.Load(SettingsDocument.DefaultPath).Get("xplane"));
About = new AboutViewModel();
Navigation =
[
@@ -78,6 +79,7 @@ public MainViewModel()
new NavItem("Settings", "", Settings),
new NavItem("Cache", "", Cache),
new NavItem("Packages", "", Packages),
+ new NavItem("X-Plane Custom Scenery", "", Scenery),
new NavItem("Log", "", LogPage),
new NavItem("About", "", About),
];
@@ -102,6 +104,8 @@ public MainViewModel()
public HttpClient MeshHttp { get; } = PackagesViewModel.CreateHttpClient();
/// One region install or delete at a time, from the Packages page or the setup.
public InstallSlot MeshInstalls { get; } = new();
+ /// X-Plane's scenery_packs.ini, to switch packages on or off.
+ public SceneryViewModel Scenery { get; }
public LogViewModel LogPage { get; }
public AboutViewModel About { get; }
public IReadOnlyList Navigation { get; }
diff --git a/src/OrthoStreamXP/Gui/ViewModels/SceneryViewModel.cs b/src/OrthoStreamXP/Gui/ViewModels/SceneryViewModel.cs
new file mode 100644
index 0000000..a30f6b3
--- /dev/null
+++ b/src/OrthoStreamXP/Gui/ViewModels/SceneryViewModel.cs
@@ -0,0 +1,129 @@
+using System.Collections.ObjectModel;
+using System.Windows.Input;
+using OrthoStreamXP.Scenery;
+
+namespace OrthoStreamXP.Gui;
+
+///
+/// The X-Plane Custom Scenery page: every entry of X-Plane's Custom Scenery\scenery_packs.ini, to switch on or off and reorder.
+/// Read again when the page is shown and when OrthoStreamXP starts or stops, as both change the file; changed only while
+/// OrthoStreamXP is stopped, so the person's changes and the mount's never meet.
+///
+internal sealed class SceneryViewModel : ObservableObject, IPage
+{
+ private readonly MountController _mount;
+ private readonly Func _xplane;
+ private string? _message;
+
+ /// The X-Plane folder of the settings; null while there is none.
+ public SceneryViewModel(MountController mount, Func xplane)
+ {
+ _mount = mount;
+ _xplane = xplane;
+ Refresh = new RelayCommand(Load);
+ OpenFolder = new RelayCommand(() => Shell.Open(CustomScenery!), () => CustomScenery is { } folder && Directory.Exists(folder));
+ _mount.PropertyChanged += (_, e) =>
+ {
+ if (e.PropertyName != nameof(MountController.State)) return;
+ Raise(nameof(CanEdit));
+ Raise(nameof(RunningNote));
+ RelayCommand.Refresh();
+ if (_mount.IsRunning || _mount.IsStopped) Load();
+ };
+ }
+
+ public ObservableCollection Rows { get; } = [];
+ public ICommand Refresh { get; }
+ public ICommand OpenFolder { get; }
+
+ /// The list can be changed only while OrthoStreamXP is stopped: starting and stopping change the file too.
+ public bool CanEdit => _mount.IsStopped;
+
+ public string? RunningNote => CanEdit ? null : "OrthoStreamXP is running: stop it to change the list.";
+
+ public string? CustomScenery => _xplane() is { } xplane ? Path.Join(xplane, "Custom Scenery") : null;
+
+ public string FileText => CustomScenery is { } folder
+ ? $"From {Path.Join(folder, SceneryPacks.FileName)}, highest priority first."
+ : "Choose your X-Plane folder first (in Settings): its scenery list is shown here.";
+
+ public string? Message
+ {
+ get => _message;
+ private set
+ {
+ Set(ref _message, value);
+ Raise(nameof(HasMessage));
+ }
+ }
+
+ public bool HasMessage => Message is not null;
+
+ public void OnShown() => Load();
+
+ private void Load()
+ {
+ Rows.Clear();
+ Message = null;
+ Raise(nameof(FileText));
+ RelayCommand.Refresh();
+ if (CustomScenery is not { } folder) return;
+ var list = new SceneryPackList(folder);
+ try
+ {
+ var streamed = new HashSet(_mount.Running?.Packages.Select(p => p.Name) ?? [], StringComparer.OrdinalIgnoreCase);
+ foreach (SceneryPackEntry entry in list.Read())
+ Rows.Add(new SceneryPackRow(entry, streamed.Contains(entry.Name), Switch));
+ if (Rows.Count == 0) Message = $"{list.FilePath} lists no scenery yet: X-Plane writes it when it starts.";
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ Message = $"Could not read {list.FilePath}: {ex.Message}";
+ }
+ }
+
+ private bool Switch(SceneryPackRow row, bool enabled)
+ {
+ if (!CanEdit || CustomScenery is not { } folder) return false;
+ try
+ {
+ new SceneryPackList(folder).SetEnabled(row.Path, enabled);
+ Message = null;
+ Log.Info($"{(enabled ? "Enabled" : "Disabled")} {row.Path} in {SceneryPacks.FileName}");
+ return true;
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ Message = $"Could not change {row.Name}: {ex.Message}";
+ return false;
+ }
+ }
+
+ ///
+ /// Drops before the row at (the row count puts it last), as dragged on the page.
+ ///
+ public void Drop(SceneryPackRow row, int insertAt)
+ {
+ int from = Rows.IndexOf(row);
+ if (!CanEdit || CustomScenery is not { } folder || from < 0 || insertAt < 0 || insertAt > Rows.Count) return;
+ int to = insertAt > from ? insertAt - 1 : insertAt;
+ if (to == from) return;
+ try
+ {
+ if (new SceneryPackList(folder).MoveTo(row.Path, to) && Rows.Count == new SceneryPackList(folder).Read().Count)
+ {
+ Rows.Move(from, to);
+ Message = null;
+ Log.Info($"Moved {row.Path} to place {to + 1} in {SceneryPacks.FileName}");
+ }
+ else
+ {
+ Load(); // The file changed meanwhile: show it as it is now.
+ }
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ Message = $"Could not move {row.Name}: {ex.Message}";
+ }
+ }
+}
diff --git a/src/OrthoStreamXP/Gui/ViewModels/SettingsViewModel.cs b/src/OrthoStreamXP/Gui/ViewModels/SettingsViewModel.cs
index 0e96a37..0c1e0e8 100644
--- a/src/OrthoStreamXP/Gui/ViewModels/SettingsViewModel.cs
+++ b/src/OrthoStreamXP/Gui/ViewModels/SettingsViewModel.cs
@@ -24,7 +24,7 @@ internal sealed class SettingsViewModel : ObservableObject, IPage
public SettingsViewModel(MainViewModel main)
{
_main = main;
- Presets = [.. QualityPreset.Choices.Select(p => new PresetOption(p, ChoosePreset))];
+ Presets = [.. QualityPreset.Choices.Select(p => new PresetOption(p, ChoosePreset, SaveResolution, ChooseDynamicBase))];
Providers =
[
new Choice("Bing, then Esri where Bing has no picture (recommended)", "bing,esri"),
@@ -93,7 +93,7 @@ public SettingsViewModel(MainViewModel main)
public ColourPreviewViewModel ColourPreview { get; }
/// The colour settings as the page shows them, for the preview.
- private ColourAdjustments ColourSettings => new(MatchColoursOn, MatchStrength / 100,
+ private ColourAdjustments ColourSettings => new(
new Scenery.SeasonOptions(SeasonsOn, SeasonStrength / 100, SeasonModel.Names.GetValueOrDefault(Season?.Value ?? "auto", SeasonChoice.Auto)), Exposure);
public IReadOnlyList Presets { get; }
@@ -148,7 +148,7 @@ public int Tab
/// Reset would change something: a tuned value, or a setting edited in the file.
public bool CanReset => CurrentPreset is { } preset && TunedSettings.DiffersFromDefaults(_document, preset);
- public string ResetQuestion => $"Put every setting back to the {CurrentPreset?.Name} defaults and forget what was tuned for it? The folders, the picture source and Downloads at once stay as they are.";
+ public string ResetQuestion => $"Put every setting back to the {CurrentPreset?.Name} defaults and forget what was tuned for it? The folders, the picture source, the resolutions and Downloads at once stay as they are.";
public bool ConfirmingReset
{
@@ -197,6 +197,7 @@ public double DownloadWorkers
public IReadOnlyList SeasonChoices { get; } =
[
new Choice("Automatic: X-Plane's date and the place", "auto"),
+ new Choice("Satellite: grass and fields as they really were", "satellite"),
new Choice("Early spring", "early-spring"),
new Choice("Spring", "spring"),
new Choice("Summer (the pictures as they are)", "summer"),
@@ -206,35 +207,6 @@ public double DownloadWorkers
new Choice("Winter, without snow", "winter"),
];
- public bool MatchColoursOn
- {
- get => _document.GetBool("match-colours") == true;
- set
- {
- Save("match-colours", value ? "on" : "off");
- Raise();
- Raise(nameof(MatchColoursOnText));
- ColourPreview.Refresh();
- }
- }
-
- public string MatchColoursOnText => MatchColoursOn ? "On" : "Off";
-
- /// The colour matching's strength in percent, for the slider; saved as a whole number.
- public double MatchStrength
- {
- get => _document.GetDouble("match-strength") ?? 100;
- set
- {
- Save("match-strength", Math.Clamp((int)Math.Round(value), 0, 100).ToString(CultureInfo.InvariantCulture));
- Raise();
- Raise(nameof(MatchStrengthText));
- ColourPreview.Refresh();
- }
- }
-
- public string MatchStrengthText => $"{MatchStrength:0} %";
-
public bool SeasonsOn
{
get => _document.GetBool("seasons") == true;
@@ -422,7 +394,7 @@ public string CacheEstimate
{
get
{
- int size = new TexturePlan(_document.GetInt("level-change") ?? 0).SizeFor(16);
+ int size = QualityPreset.PlanIn(_document).SizeFor(16);
return $"Each new area takes up to about {CacheInventory.FormatBytes(3000L * size * size * 2 / 3)} at this texture size.";
}
}
@@ -502,7 +474,13 @@ public void Reload()
_loading = false;
int level = _document.GetInt("level-change") ?? 0;
QualityPreset? current = CurrentPreset;
- foreach (PresetOption option in Presets) option.Show(option.Preset == current);
+ QualityPreset dynamic = QualityPreset.DynamicIn(_document);
+ foreach (PresetOption option in Presets)
+ {
+ option.ShowBase(dynamic);
+ option.Show(option.Preset == current);
+ option.ShowResolution(option.Preset.ResolutionIn(_document));
+ }
CustomLevelNote = QualityPreset.ForLevel(level) is null
? $"Your settings file uses level-change {level}, which is not one of these. Choosing one replaces it."
: null;
@@ -512,7 +490,7 @@ public void Reload()
foreach (string name in new[]
{
nameof(Provider), nameof(DownloadWorkers), nameof(DownloadWorkersText), nameof(FilePath), nameof(CacheEstimate),
- nameof(MatchColoursOn), nameof(MatchColoursOnText), nameof(MatchStrength), nameof(MatchStrengthText), nameof(SeasonsOn), nameof(SeasonsOnText), nameof(Season), nameof(SeasonStrength), nameof(SeasonStrengthText), nameof(Exposure), nameof(ExposureText),
+ nameof(SeasonsOn), nameof(SeasonsOnText), nameof(Season), nameof(SeasonStrength), nameof(SeasonStrengthText), nameof(Exposure), nameof(ExposureText),
nameof(GroundDetail), nameof(GroundDetailText), nameof(NightLightsOn), nameof(NightLightsOnText), nameof(SkipPhotosAtNight), nameof(SkipPhotosAtNightText),
nameof(TunedRows), nameof(TuningText), nameof(CanReset), nameof(ResetQuestion),
})
@@ -530,6 +508,24 @@ private void ChoosePreset(QualityPreset preset)
Reload();
}
+ ///
+ /// Dynamic's base changed on its card: chosen at once while the settings are at Dynamic (its level and that
+ /// preset's values, with what was tuned for it), otherwise kept for when Dynamic is chosen.
+ ///
+ private void ChooseDynamicBase(QualityPreset dynamic)
+ {
+ if (CurrentPreset is { IsDynamic: true }) ChoosePreset(dynamic);
+ else Save(QualityPreset.DynamicBaseKey, dynamic.DynamicBase!.Name.ToLowerInvariant());
+ }
+
+ /// A preset card's resolution changed: kept for that preset, used whenever the settings are at it.
+ private void SaveResolution(QualityPreset preset, TextureResolution resolution)
+ {
+ Save(preset.ResolutionKey, resolution.Value);
+ Raise(nameof(CacheEstimate));
+ Raise(nameof(CacheStatus));
+ }
+
private void ResetToDefaults()
{
if (CurrentPreset is not { } preset) return;
diff --git a/src/OrthoStreamXP/Gui/ViewModels/SetupViewModel.cs b/src/OrthoStreamXP/Gui/ViewModels/SetupViewModel.cs
index e1f5acb..485178b 100644
--- a/src/OrthoStreamXP/Gui/ViewModels/SetupViewModel.cs
+++ b/src/OrthoStreamXP/Gui/ViewModels/SetupViewModel.cs
@@ -60,7 +60,16 @@ public SetupViewModel(MainViewModel main)
XPlaneOptions = [.. SystemCheck.FindXPlaneFolders().Select(f => new FolderOption(f, "X-Plane found here", ChooseXPlane))];
// Which packages to use is the person's own choice: nothing is searched for, only the folder chosen before is offered.
PackageOptions = [];
- Presets = [.. QualityPreset.Choices.Select(p => new PresetOption(p, preset => Preset = preset))];
+ // Each card keeps its own resolution, and Dynamic's its base, until the setup finishes and writes them all;
+ // a base changed while Dynamic is chosen chooses Dynamic from it.
+ Presets = [.. QualityPreset.Choices.Select(p => new PresetOption(p, preset => Preset = preset, (_, _) => Raise(nameof(Summary)),
+ dynamic => { if (Preset.IsDynamic) Preset = dynamic; }))];
+ QualityPreset dynamic = QualityPreset.DynamicIn(existing);
+ foreach (PresetOption option in Presets)
+ {
+ option.ShowBase(dynamic);
+ option.ShowResolution(option.Preset.ResolutionIn(existing));
+ }
// Re-running the setup starts from the current settings; a first setup suggests the cache beside the packages.
_cacheChosen = existing.Get("cache") is not null;
_cache = existing.Get("cache") ?? SystemCheck.SuggestedCacheFolder(null);
@@ -68,9 +77,11 @@ public SetupViewModel(MainViewModel main)
Select(PackageOptions, existing.Get("base-packages"), ChoosePackages, null);
PresetMemory.Load(existing.Get("cache"));
foreach (PresetOption option in Presets) option.RefreshMemory();
- QualityPreset recommended = PresetMemory.Recommended.Preset;
- Preset = QualityPreset.Current(existing.GetInt("level-change") ?? recommended.Level, existing.GetBool(QualityPreset.DynamicQualityKey) == true)
- ?? recommended;
+ // A first setup starts at the recommendation, resolution and all; a rerun at what the settings have.
+ if (existing.GetInt("level-change") is { } level)
+ Preset = QualityPreset.Current(level, existing.GetBool(QualityPreset.DynamicQualityKey) == true) ?? PresetMemory.Recommended.Preset;
+ else
+ ChooseRecommended();
IsRerun = existing.Get("cache") is not null;
ConnectionTest = new ConnectionTestViewModel(
() => existing.Get("texture-provider") ?? "bing,esri",
@@ -81,7 +92,7 @@ public SetupViewModel(MainViewModel main)
// The recommendation follows the measured speed, and is chosen for the person (they may pick another).
PresetMemory.Load(_cache);
foreach (PresetOption option in Presets) option.RefreshMemory();
- Preset = PresetMemory.Recommended.Preset;
+ ChooseRecommended();
});
Back = new RelayCommand(() => Step--, () => Step > 0);
@@ -232,9 +243,20 @@ private set
_preset = value;
foreach (PresetOption option in Presets) option.Show(option.Preset == value);
Raise();
+ Raise(nameof(Summary));
}
}
+ /// The chosen preset's card.
+ private PresetOption Chosen => Presets.First(o => o.Preset == Preset);
+
+ /// Chooses the recommended preset at the recommended resolution (the person may pick another).
+ private void ChooseRecommended()
+ {
+ Preset = PresetMemory.Recommended.Preset;
+ Chosen.Resolution = PresetMemory.Recommended.Resolution;
+ }
+
/// The cache folder; set from the window (typed or browsed), it is the person's choice from then on.
public string CacheFolder
{
@@ -284,7 +306,7 @@ public bool StartNow
public string Summary =>
$"X-Plane: {_xplane}\nScenery packages: {string.Join(", ", SystemCheck.PackagesIn(_packages))} in {_packages}\n" +
- $"Quality: {Preset.Name}\nCache: {CacheFolder}";
+ $"Quality: {Preset.Title}{(Chosen.Resolution.IsFull ? "" : $" at {Chosen.Resolution.Label} resolution")}\nCache: {CacheFolder}";
public string? Error
{
@@ -373,6 +395,11 @@ private async Task FinishAsync()
{
settings = SettingsDocument.CreateNew(path, _xplane!, _packages!, CacheFolder, Preset);
}
+ foreach (PresetOption option in Presets)
+ {
+ settings.Set(option.Preset.ResolutionKey, option.Resolution.Value);
+ if (option.Base is { } near) settings.Set(QualityPreset.DynamicBaseKey, near.Name.ToLowerInvariant());
+ }
if (_testedWorkers is { } workers) settings.Set("download-workers", workers);
Directory.CreateDirectory(CacheFolder);
settings.Save();
diff --git a/src/OrthoStreamXP/Gui/Views/CacheView.xaml b/src/OrthoStreamXP/Gui/Views/CacheView.xaml
index afe5e86..719c488 100644
--- a/src/OrthoStreamXP/Gui/Views/CacheView.xaml
+++ b/src/OrthoStreamXP/Gui/Views/CacheView.xaml
@@ -1,6 +1,7 @@
@@ -53,88 +54,93 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+ Text="Each square is a 1° area you have flown, pictured from its own textures. Faded ones were not flown for a month: the cache limit removes those first. Scroll to zoom, drag to move the map." />
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/OrthoStreamXP/Gui/Views/DragGhost.cs b/src/OrthoStreamXP/Gui/Views/DragGhost.cs
new file mode 100644
index 0000000..3cb870e
--- /dev/null
+++ b/src/OrthoStreamXP/Gui/Views/DragGhost.cs
@@ -0,0 +1,52 @@
+using System.Windows;
+using System.Windows.Documents;
+using System.Windows.Media;
+using System.Windows.Media.Effects;
+using System.Windows.Media.Imaging;
+
+namespace OrthoStreamXP.Gui;
+
+/// A picture of a dragged row that floats with the pointer, lifted by a shadow, drawn over the page.
+internal sealed class DragGhost : Adorner
+{
+ private readonly ImageBrush _picture;
+ private readonly Size _size;
+ private Point _at;
+
+ /// The element the ghost is drawn over; takes points relative to it.
+ /// The row, pictured as it looks now.
+ public DragGhost(UIElement page, FrameworkElement row) : base(page)
+ {
+ IsHitTestVisible = false;
+ _size = new Size(row.ActualWidth, row.ActualHeight);
+ _picture = new ImageBrush(Snapshot(row, _size));
+ _picture.Freeze();
+ Opacity = 0.92;
+ Effect = new DropShadowEffect { BlurRadius = 18, ShadowDepth = 4, Direction = 270, Opacity = 0.35 };
+ }
+
+ /// Puts the ghost's top-left corner at .
+ public void MoveTo(Point topLeft)
+ {
+ _at = topLeft;
+ InvalidateVisual();
+ }
+
+ protected override void OnRender(DrawingContext drawingContext) =>
+ drawingContext.DrawRectangle(_picture, null, new Rect(_at, _size));
+
+ /// The row drawn through a brush, so the picture starts at its own corner, not at its place in the list.
+ private static RenderTargetBitmap Snapshot(FrameworkElement row, Size size)
+ {
+ DpiScale dpi = VisualTreeHelper.GetDpi(row);
+ var drawing = new DrawingVisual();
+ using (DrawingContext context = drawing.RenderOpen())
+ context.DrawRectangle(new VisualBrush(row), null, new Rect(size));
+ var bitmap = new RenderTargetBitmap(
+ Math.Max(1, (int)Math.Ceiling(size.Width * dpi.DpiScaleX)), Math.Max(1, (int)Math.Ceiling(size.Height * dpi.DpiScaleY)),
+ dpi.PixelsPerInchX, dpi.PixelsPerInchY, PixelFormats.Pbgra32);
+ bitmap.Render(drawing);
+ bitmap.Freeze();
+ return bitmap;
+ }
+}
diff --git a/src/OrthoStreamXP/Gui/Views/HomeView.xaml b/src/OrthoStreamXP/Gui/Views/HomeView.xaml
index d419520..e42b4c2 100644
--- a/src/OrthoStreamXP/Gui/Views/HomeView.xaml
+++ b/src/OrthoStreamXP/Gui/Views/HomeView.xaml
@@ -421,12 +421,26 @@
+
+
+
+
+
diff --git a/src/OrthoStreamXP/Gui/Views/ReorderPreview.cs b/src/OrthoStreamXP/Gui/Views/ReorderPreview.cs
new file mode 100644
index 0000000..657f5a1
--- /dev/null
+++ b/src/OrthoStreamXP/Gui/Views/ReorderPreview.cs
@@ -0,0 +1,94 @@
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Media;
+using System.Windows.Media.Animation;
+
+namespace OrthoStreamXP.Gui;
+
+///
+/// Shows, while a row of a list is dragged, the order it would make: the rows between its place and where it would land
+/// slide over to open a gap there, and a faint copy of it sits in the gap. Only render transforms move, so the layout (and
+/// where the pointer is measured from) stays as it was until the drop.
+///
+internal sealed class ReorderPreview
+{
+ private const double PlaceholderOpacity = 0.25;
+ private static readonly Duration Slide = new(TimeSpan.FromMilliseconds(160));
+ private static readonly CubicEase Ease = CreateEase();
+
+ private readonly FrameworkElement[] _rows;
+ private readonly int _from;
+ private int? _insertAt;
+
+ /// A list whose rows are all realised (not virtualised).
+ /// The dragged row.
+ public ReorderPreview(ItemsControl list, int from)
+ {
+ _rows = [.. Enumerable.Range(0, list.Items.Count).Select(i => list.ItemContainerGenerator.ContainerFromIndex(i)).OfType()];
+ _from = from;
+ foreach (FrameworkElement row in _rows)
+ if (row.RenderTransform is not TranslateTransform) row.RenderTransform = new TranslateTransform();
+ if (from >= 0 && from < _rows.Length) _rows[from].Opacity = PlaceholderOpacity;
+ }
+
+ ///
+ /// The row the dragged one would go before (the row count: last), by which half of a row the pointer is over, measured
+ /// on the rows' places before any slid aside, so the gap opening does not move the target under the pointer.
+ ///
+ public int InsertIndex(DragEventArgs e)
+ {
+ if (_rows.Length == 0 || VisualTreeHelper.GetParent(_rows[0]) is not UIElement panel) return 0;
+ double y = e.GetPosition(panel).Y;
+ for (int i = 0; i < _rows.Length; i++)
+ if (y < VisualTreeHelper.GetOffset(_rows[i]).Y + _rows[i].ActualHeight / 2) return i;
+ return _rows.Length;
+ }
+
+ /// Opens the gap before the row at ; null closes it (the pointer left the list).
+ public void Show(int? insertAt)
+ {
+ if (insertAt == _insertAt || _from < 0 || _from >= _rows.Length) return;
+ _insertAt = insertAt;
+ int to = insertAt is not { } at ? _from : at > _from ? at - 1 : at;
+ double placeholder = 0;
+ for (int i = 0; i < _rows.Length; i++)
+ {
+ if (i == _from) continue;
+ double y = to > _from && i > _from && i <= to ? -_rows[_from].ActualHeight
+ : to < _from && i >= to && i < _from ? _rows[_from].ActualHeight
+ : 0;
+ placeholder -= Math.Sign(y) * _rows[i].ActualHeight;
+ Animate(_rows[i], y);
+ }
+ Animate(_rows[_from], placeholder);
+ }
+
+ /// Puts every row back: sliding (the drag was cancelled), or at once (the list is about to take the new order).
+ public void Reset(bool animate)
+ {
+ foreach (FrameworkElement row in _rows)
+ {
+ row.Opacity = 1;
+ if (animate)
+ {
+ Animate(row, 0);
+ }
+ else
+ {
+ var transform = (TranslateTransform)row.RenderTransform;
+ transform.BeginAnimation(TranslateTransform.YProperty, null);
+ transform.Y = 0;
+ }
+ }
+ }
+
+ private static void Animate(FrameworkElement row, double y) =>
+ ((TranslateTransform)row.RenderTransform).BeginAnimation(TranslateTransform.YProperty, new DoubleAnimation(y, Slide) { EasingFunction = Ease });
+
+ private static CubicEase CreateEase()
+ {
+ var ease = new CubicEase { EasingMode = EasingMode.EaseOut };
+ ease.Freeze();
+ return ease;
+ }
+}
diff --git a/src/OrthoStreamXP/Gui/Views/SceneryView.xaml b/src/OrthoStreamXP/Gui/Views/SceneryView.xaml
new file mode 100644
index 0000000..cfd4fef
--- /dev/null
+++ b/src/OrthoStreamXP/Gui/Views/SceneryView.xaml
@@ -0,0 +1,66 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/OrthoStreamXP/Gui/Views/SceneryView.xaml.cs b/src/OrthoStreamXP/Gui/Views/SceneryView.xaml.cs
new file mode 100644
index 0000000..3368181
--- /dev/null
+++ b/src/OrthoStreamXP/Gui/Views/SceneryView.xaml.cs
@@ -0,0 +1,116 @@
+using System.Windows;
+using System.Windows.Controls.Primitives;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+
+namespace OrthoStreamXP.Gui;
+
+///
+/// The X-Plane Custom Scenery page. A row is dragged to a new place (anywhere on it but its switch): a picture of it follows
+/// the pointer, the other rows slide apart where it would land, and the page scrolls while the pointer is near its top or
+/// bottom edge.
+///
+internal sealed partial class SceneryView
+{
+ /// How close to the page's top or bottom edge a drag scrolls it.
+ private const double ScrollEdge = 48;
+
+ private SceneryPackRow? _pressed;
+ private Point _pressedAt;
+ /// Where in the row it was grabbed, so the ghost keeps that spot under the pointer.
+ private Point _grab;
+ private DragGhost? _ghost;
+ private double _ghostLeft;
+ private ReorderPreview? _preview;
+
+ public SceneryView() => InitializeComponent();
+
+ private SceneryViewModel? Model => DataContext as SceneryViewModel;
+
+ private void OnRowMouseDown(object sender, MouseButtonEventArgs e)
+ {
+ _pressed = IsOnButton(e.OriginalSource as DependencyObject) ? null : (sender as FrameworkElement)?.DataContext as SceneryPackRow;
+ _pressedAt = e.GetPosition(this);
+ _grab = e.GetPosition(sender as IInputElement);
+ }
+
+ private void OnRowMouseMove(object sender, MouseEventArgs e)
+ {
+ if (_pressed is not { } row || e.LeftButton != MouseButtonState.Pressed || Model is not { CanEdit: true }) return;
+ Vector moved = e.GetPosition(this) - _pressedAt;
+ if (Math.Abs(moved.X) < SystemParameters.MinimumHorizontalDragDistance && Math.Abs(moved.Y) < SystemParameters.MinimumVerticalDragDistance) return;
+ _pressed = null;
+ int from = List.Items.IndexOf(row);
+ if (List.ItemContainerGenerator.ContainerFromIndex(from) is not FrameworkElement container) return;
+
+ AdornerLayer? layer = AdornerLayer.GetAdornerLayer(this);
+ _ghost = new DragGhost(this, container); // pictured before the preview fades the row
+ _ghostLeft = container.TranslatePoint(default, this).X;
+ layer?.Add(_ghost);
+ MoveGhost(e.GetPosition(this));
+ _preview = new ReorderPreview(List, from);
+ try
+ {
+ DragDrop.DoDragDrop((DependencyObject)sender, new DataObject(typeof(SceneryPackRow), row), DragDropEffects.Move);
+ }
+ finally
+ {
+ _preview?.Reset(animate: true); // not dropped on the list: everything slides back
+ _preview = null;
+ layer?.Remove(_ghost);
+ _ghost = null;
+ }
+ }
+
+ private void OnListDragOver(object sender, DragEventArgs e)
+ {
+ e.Handled = true;
+ if (_preview is null || !e.Data.GetDataPresent(typeof(SceneryPackRow)))
+ {
+ e.Effects = DragDropEffects.None;
+ return;
+ }
+ e.Effects = DragDropEffects.Move;
+ _preview.Show(_preview.InsertIndex(e));
+ }
+
+ private void OnListDrop(object sender, DragEventArgs e)
+ {
+ e.Handled = true;
+ if (_preview is not { } preview || e.Data.GetData(typeof(SceneryPackRow)) is not SceneryPackRow row) return;
+ int insertAt = preview.InsertIndex(e);
+ // The rows go back to their places at once and the list takes the new order in the same frame: no jump.
+ preview.Reset(animate: false);
+ _preview = null;
+ Model?.Drop(row, insertAt);
+ }
+
+ /// Over the page but not over the list: nothing to drop on, so the gap closes.
+ private void OnOutsideDragOver(object sender, DragEventArgs e)
+ {
+ e.Effects = DragDropEffects.None;
+ e.Handled = true;
+ _preview?.Show(null);
+ }
+
+ /// Moves the ghost with the pointer, and scrolls while it is near the page's top or bottom edge (the list can be hundreds long).
+ private void OnScrollerPreviewDragOver(object sender, DragEventArgs e)
+ {
+ MoveGhost(e.GetPosition(this));
+ double y = e.GetPosition(Scroller).Y;
+ if (y < ScrollEdge) Scroller.LineUp();
+ else if (y > Scroller.ActualHeight - ScrollEdge) Scroller.LineDown();
+ }
+
+ /// The ghost stays in the list's column and follows the pointer up and down.
+ private void MoveGhost(Point pointer) => _ghost?.MoveTo(new Point(_ghostLeft, pointer.Y - _grab.Y));
+
+ /// Whether a press started on the row's switch (or another button), which keeps its click.
+ private static bool IsOnButton(DependencyObject? element)
+ {
+ for (; element is not null; element = element is Visual ? VisualTreeHelper.GetParent(element) : LogicalTreeHelper.GetParent(element))
+ if (element is ButtonBase) return true;
+ return false;
+ }
+}
diff --git a/src/OrthoStreamXP/Gui/Views/SettingsView.xaml b/src/OrthoStreamXP/Gui/Views/SettingsView.xaml
index 21405b7..a827de3 100644
--- a/src/OrthoStreamXP/Gui/Views/SettingsView.xaml
+++ b/src/OrthoStreamXP/Gui/Views/SettingsView.xaml
@@ -28,16 +28,54 @@
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
@@ -105,7 +143,7 @@
-
+
@@ -297,9 +335,12 @@
-
-
-
+
+
+
+
+
@@ -338,48 +379,12 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
-
+
@@ -405,7 +410,8 @@
-
+
diff --git a/src/OrthoStreamXP/Gui/Views/SettingsView.xaml.cs b/src/OrthoStreamXP/Gui/Views/SettingsView.xaml.cs
index f738fa1..f6d806f 100644
--- a/src/OrthoStreamXP/Gui/Views/SettingsView.xaml.cs
+++ b/src/OrthoStreamXP/Gui/Views/SettingsView.xaml.cs
@@ -1,6 +1,28 @@
+using System.Windows.Controls;
+
namespace OrthoStreamXP.Gui;
internal sealed partial class SettingsView
{
- public SettingsView() => InitializeComponent();
+ public SettingsView()
+ {
+ InitializeComponent();
+ // The colour preview stays in sight while its settings are changed below it
+ _ = new StickyHeader(Scroller, PreviewPin, ShowPreviewBackdrop);
+ }
+
+ /// Pinned, the preview covers the settings under it: it gets the page's own (opaque) backdrop.
+ private void ShowPreviewBackdrop(bool pinned)
+ {
+ if (pinned)
+ {
+ PreviewPin.SetResourceReference(Border.BackgroundProperty, "SolidBackgroundFillColorBaseBrush");
+ PreviewPinLayer.SetResourceReference(Border.BackgroundProperty, "LayerFillColorDefaultBrush");
+ }
+ else
+ {
+ PreviewPin.ClearValue(Border.BackgroundProperty);
+ PreviewPinLayer.ClearValue(Border.BackgroundProperty);
+ }
+ }
}
diff --git a/src/OrthoStreamXP/Gui/Views/SetupView.xaml b/src/OrthoStreamXP/Gui/Views/SetupView.xaml
index e61585f..54e1556 100644
--- a/src/OrthoStreamXP/Gui/Views/SetupView.xaml
+++ b/src/OrthoStreamXP/Gui/Views/SetupView.xaml
@@ -15,16 +15,54 @@
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/OrthoStreamXP/Gui/Views/StickyHeader.cs b/src/OrthoStreamXP/Gui/Views/StickyHeader.cs
new file mode 100644
index 0000000..a8903ed
--- /dev/null
+++ b/src/OrthoStreamXP/Gui/Views/StickyHeader.cs
@@ -0,0 +1,51 @@
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Media;
+
+namespace OrthoStreamXP.Gui;
+
+///
+/// Keeps an element of a scrolled page in sight: once it reaches the top of the viewport it stays there while
+/// the rest of its panel scrolls under it, until the panel's end pushes it up. Only a render offset: the layout
+/// is untouched, so nothing below it moves.
+///
+internal sealed class StickyHeader
+{
+ private readonly ScrollViewer _scroller;
+ private readonly FrameworkElement _header;
+ private readonly Action _pinnedChanged;
+ private readonly TranslateTransform _shift = new();
+ private bool _pinned;
+
+ /// The page's scroll viewer.
+ /// The element to keep at the top; its parent panel bounds how far it follows.
+ /// Told when the header starts or stops covering content (to give it a backdrop).
+ public StickyHeader(ScrollViewer scroller, FrameworkElement header, Action pinnedChanged)
+ {
+ _scroller = scroller;
+ _header = header;
+ _pinnedChanged = pinnedChanged;
+ header.RenderTransform = _shift;
+ Panel.SetZIndex(header, 1);
+ scroller.ScrollChanged += (_, _) => Update();
+ header.SizeChanged += (_, _) => Update();
+ header.IsVisibleChanged += (_, _) => Update();
+ }
+
+ private void Update()
+ {
+ double shift = 0;
+ if (_header.IsVisible && VisualTreeHelper.GetParent(_header) is FrameworkElement panel && panel.IsDescendantOf(_scroller))
+ {
+ double top = _header.TransformToAncestor(_scroller).Transform(default).Y - _shift.Y;
+ double panelBottom = panel.TransformToAncestor(_scroller).Transform(default).Y + panel.ActualHeight;
+ shift = Math.Clamp(-top, 0, Math.Max(0, panelBottom - (top + _header.ActualHeight)));
+ }
+
+ _shift.Y = shift;
+ bool pinned = shift > 0;
+ if (pinned == _pinned) return;
+ _pinned = pinned;
+ _pinnedChanged(pinned);
+ }
+}
diff --git a/src/OrthoStreamXP/Infrastructure/AtomicFile.cs b/src/OrthoStreamXP/Infrastructure/AtomicFile.cs
index a96a682..08014a4 100644
--- a/src/OrthoStreamXP/Infrastructure/AtomicFile.cs
+++ b/src/OrthoStreamXP/Infrastructure/AtomicFile.cs
@@ -8,7 +8,13 @@ internal static class AtomicFile
private const string PartialSuffix = ".partial";
/// Writes beside the destination and renames over it. Returns the seconds it took.
- public static double Write(string destination, ReadOnlySpan data)
+ public static double Write(string destination, ReadOnlySpan data) => Write(destination, data, []);
+
+ ///
+ /// of followed by ,
+ /// without joining them in one array first (a texture's header and its tens of MB of levels).
+ ///
+ public static double Write(string destination, ReadOnlySpan first, ReadOnlySpan second)
{
long started = Stopwatch.GetTimestamp();
Directory.CreateDirectory(Path.GetDirectoryName(destination)!);
@@ -16,7 +22,10 @@ public static double Write(string destination, ReadOnlySpan data)
try
{
using (var file = new FileStream(temporary, FileMode.CreateNew, FileAccess.Write, FileShare.None))
- file.Write(data);
+ {
+ file.Write(first);
+ file.Write(second);
+ }
File.Move(temporary, destination, overwrite: true);
}
catch
diff --git a/src/OrthoStreamXP/Mounting/MountSession.cs b/src/OrthoStreamXP/Mounting/MountSession.cs
index 014de8f..0021fda 100644
--- a/src/OrthoStreamXP/Mounting/MountSession.cs
+++ b/src/OrthoStreamXP/Mounting/MountSession.cs
@@ -20,6 +20,7 @@ internal sealed class MountSession : IDisposable
private readonly Daylight _daylight;
private readonly FlightRecorder _recorder = new();
private readonly CpuMeter _cpu = new();
+ private BuildBufferPool? _buffers;
private readonly SceneryLoads _loads;
private readonly List _timeline = [];
private readonly DateTime _startedUtc = DateTime.UtcNow;
@@ -29,10 +30,13 @@ internal sealed class MountSession : IDisposable
private AircraftPositionListener? _listener;
private ReadLog? _readLog;
private SeasonClock? _seasons;
- private ColourMatcher? _colours;
+ /// The satellite record the grass and fields are coloured by, with season = satellite.
+ private ObservedSeasons? _observed;
/// The night textures' painting, shared by every package.
private NightPainting? _nightPainting;
private Task? _summaryLoop, _sampleLoop;
+ /// The packages scenery_packs.ini had no entry for at the start: taken out again when this stops, as their folders go with it.
+ private IReadOnlyList _addedToSceneryPacks = [];
private bool _stopped;
private MountSession(MountSettings settings)
@@ -75,7 +79,7 @@ private void StartAll()
foreach (string folder in s.NotPackages) Log.Info($"Skipping {folder}: not a scenery package (it has no Earth nav data folder)");
Log.Info($"Textures at level-change {s.Textures.LevelChange}: {s.Textures.Describe()}; cached in {s.PlanCache}");
if (s.IgnoredTextureQuality is { } quality)
- Log.Info($"texture-quality = {quality} in the settings is no longer used: the texture size follows the level ({s.Textures.SizeLimit} px at level {s.Textures.LevelChange})");
+ Log.Info($"texture-quality = {quality} in the settings is no longer used: the texture size follows the level ({s.Textures.Describe()} at level {s.Textures.LevelChange})");
Directory.CreateDirectory(s.PlanCache);
// Builds await downloads and run CPU work on the pool; keep enough threads ready for bursts.
@@ -92,22 +96,26 @@ private void StartAll()
// The low-zoom base far scenery is drawn from: shared by every setup and package, kept when a setup is deleted.
TileStore? store = streaming && s.Providers![0].Name != ImageryProvider.Synthetic ? new TileStore(Path.Join(s.Cache, TileStore.FolderName)) : null;
_tiles = s.Providers is null ? null : new TileSource(s.Providers, s.DownloadWorkers, s.DownloadTimeout, s.DownloadAttempts) { Store = store };
- // One downloader and one encoder for all packages: the tile downloads and the CPU limits are shared.
- TextureBuilder? builder = _tiles is null ? null : new TextureBuilder(_tiles, s.EncoderWorkers);
- var textureOptions = new TextureOptions(_tiles?.Provider ?? "", s.Textures, s.DdsBuildWorkers, s.Background, s.ProvisionalLod, s.ProvisionalWait);
- var model = new PagingModel(s.PagingK);
// Builds run within two budgets, each counted at its own size: --build-memory for the pictures they hold while their
- // tiles arrive (75 MB at 4096 px; the small levels far scenery needs almost nothing), and --build-tiles for what
+ // tiles arrive (74 MB at 4096 px; the small levels far scenery needs almost nothing), and --build-tiles for what
// they download, so finer imagery (4096 tiles for a ZL16 texture at zoom 18) does not fill the connection.
long buildMemory = (long)s.BuildMemoryMb << 20;
int largest = Math.Max(s.Textures.SizeFor(16), s.Textures.SizeFor(18));
+ // Between builds the pool keeps the pictures of one full-size build for the next (295 MB at 8192 px); more builds
+ // at once take new ones, given back to the garbage collector when they end. Keeping the whole build memory held
+ // up to 1 GB idle that X-Plane could have used.
+ _buffers = new BuildBufferPool(Math.Min(buildMemory, TextureStreamer.BuildWeight(largest)));
+ // One downloader and one encoder for all packages: the tile downloads and the CPU limits are shared.
+ TextureBuilder? builder = _tiles is null ? null : new TextureBuilder(_tiles, s.EncoderWorkers, _buffers);
+ var textureOptions = new TextureOptions(_tiles?.Provider ?? "", s.Textures, s.DdsBuildWorkers, s.Background, s.ProvisionalLod, s.ProvisionalWait);
+ var model = new PagingModel(s.PagingK);
long fullTiles = TextureStreamer.BuildTiles(new TextureName(0, 0, "BI", 16), s.Textures.FetchZoom(16));
long fullAtOnce = Math.Max(1, Math.Min(buildMemory / TextureStreamer.BuildWeight(largest), s.BuildTiles / fullTiles));
long aheadAtOnce = Math.Max(1, Math.Min(fullAtOnce, TextureStreamer.AheadTiles(s.BuildTiles) / fullTiles));
var streamingOptions = new StreamingOptions(s.NearWait, s.MaxWait, BuildMemoryBytes: buildMemory, BuildTiles: s.BuildTiles);
if (_tiles is not null)
- Log.Info($"Texture generation: provider={_tiles.Provider}{(s.Providers!.Count > 1 ? " (tried in this order)" : "")}, DDS build workers={s.DdsBuildWorkers}{(s.Packages.Count > 1 ? " per package" : "")}, " +
+ Log.Info($"Texture generation: BC1 encoder={Dds.Encoder}, provider={_tiles.Provider}{(s.Providers!.Count > 1 ? " (tried in this order)" : "")}, DDS build workers={s.DdsBuildWorkers}{(s.Packages.Count > 1 ? " per package" : "")}, " +
$"download workers={_tiles.DownloadWorkers} (timeout {s.DownloadTimeout:0.#}s x {s.DownloadAttempts} attempts), encoder CPU workers={Math.Clamp(s.EncoderWorkers, 1, 16)}, " +
(streaming ? "mip streaming on" : $"mip streaming off, background={s.Background}"));
if (streaming)
@@ -117,22 +125,17 @@ private void StartAll()
if (s.ReadLog) _readLog = ReadLog.Start(AppPaths.Logs);
if (s.Seasons.On && s.Providers is not null)
{
- _seasons = new SeasonClock(s.Seasons, Path.Join(AppPaths.History, SeasonClock.DayFileName));
+ _observed = s.Seasons.Choice == SeasonChoice.Satellite ? StartSatelliteSeasons(s) : null;
+ _seasons = new SeasonClock(s.Seasons, Path.Join(AppPaths.History, SeasonClock.DayFileName), _observed, s.Exposure);
Log.Step($"Seasons: on at {s.Seasons.Strength:P0}, " +
- (s.Seasons.Choice == SeasonChoice.Auto ? $"by X-Plane's date (until it sends one: {SeasonClock.Describe(_seasons.Day)})" : $"set to {s.Seasons.Choice} everywhere"));
- }
- if (s.MatchColours && store is not null && builder is not null)
- {
- _colours = new ColourMatcher(name => builder.TryStoredRegion(name, store.MaxZoom), builder.ResizeTo,
- Path.Join(AppPaths.History, ColourMatcher.FileName), s.MatchStrength);
- Log.Step($"Colour matching: on at {s.MatchStrength:P0}; photos from different captures are evened out against the low-zoom base");
- }
- else if (s.MatchColours)
- {
- Log.Warning("Colour matching needs mip streaming and an imagery provider with a low-zoom base; it is off for this run");
+ (!s.Seasons.FollowsDate ? $"set to {s.Seasons.Choice} everywhere"
+ : $"by X-Plane's date (until it sends one: {SeasonClock.Describe(_seasons.Day)})" +
+ (_observed is null ? "" : ", grass and fields by each place's satellite record")));
}
- ushort[]? exposure = Exposure.TableFor(s.Exposure);
- if (exposure is not null) Log.Step($"Exposure: {s.Exposure:0} %; the photos are darkened as X-Plane reads them");
+ // The photos' colours with the seasons off: the contrast always, and the exposure.
+ ushort[] colours = PhotoColours.TableFor(SeasonState.Summer, s.Exposure);
+ Log.Info($"Photos: sharpness {Sharpening.AreaStrength:P0} (areas) / {Sharpening.AirportStrength:P0} (airports) as textures are built, contrast {Contrast.Strength:P0} as X-Plane reads them");
+ if (Exposure.Percent(s.Exposure) < Exposure.Full) Log.Step($"Exposure: {s.Exposure:0} %; the photos are darkened as X-Plane reads them");
if (s.TextureStore is not null) Log.Info($"Lazy local DDS store: {s.TextureStore}");
if (s.LazyTerrainListing)
Log.Info("Terrain directory listing is lazy; DSF-referenced definitions remain available by direct path");
@@ -156,7 +159,7 @@ private void StartAll()
Log.Info($"Removed {oldNights} night textures an earlier version kept whole; they are painted again, keeping only what X-Plane reads");
roots.RenameToCacheNames();
_mounts.Add(new PackageMount(package, roots, builder, textureOptions, s.TrackAircraft, s.LoadAhead, s.LazyTerrainListing, decals,
- streaming ? new TextureStreamer(roots, builder!, _view, model, streamingOptions, nightPause, _readLog, package.Name, altitude) : null, _view, _readLog, _seasons, _usage, _colours, _loads, exposure,
+ streaming ? new TextureStreamer(roots, builder!, _view, model, streamingOptions, nightPause, _readLog, package.Name, altitude) : null, _view, _readLog, _seasons, _usage, _loads, colours,
nightPainting is null ? null : new NightTextures(package.Cache, s.Textures.SizeFor, nightPainting)));
Log.Info($"Package {package.Name}: read-only from {package.Source}, cache overlay {package.Cache}, mounted at {package.Mountpoint}");
}
@@ -167,6 +170,7 @@ private void StartAll()
Action? onPosition = null;
foreach (PackageMount mount in _mounts)
if (mount.LoadAhead is { } prefetcher) onPosition += prefetcher.OnAircraftPosition;
+ if (_observed is { } observed) onPosition += observed.Prepare;
SeasonClock? seasons = _seasons;
ReadLog? readLog = _readLog;
TileSource? tiles = _tiles;
@@ -178,13 +182,19 @@ private void StartAll()
readLog?.Camera(camera, tiles?.TilesDownloaded, tiles?.BytesDownloaded);
},
streaming ? model.UseScreen : null,
- seasons is null ? null : day => seasons.OfferDate(day, _view.Starting), _daylight);
+ seasons is null ? null : day =>
+ {
+ if (seasons.OfferDate(day, _view.Starting)) ReloadForTheDate(day);
+ }, _daylight);
}
if (s.CustomScenery is not null && s.UpdateSceneryPacks)
- Log.Info(SceneryPacks.MoveToEnd(s.CustomScenery, [.. s.Packages.Select(p => p.Name)])
+ {
+ bool changed = SceneryPacks.MoveToEnd(s.CustomScenery, [.. s.Packages.Select(p => p.Name)], out _addedToSceneryPacks);
+ Log.Info(changed
? $"Moved {string.Join(", ", s.Packages.Select(p => p.Name))} to the end of {Path.Join(s.CustomScenery, SceneryPacks.FileName)} (previous file kept as {SceneryPacks.FileName}.bak)"
: $"{SceneryPacks.FileName} already lists {string.Join(", ", s.Packages.Select(p => p.Name))} at the end");
+ }
if (_tiles is not null) _ = Task.Run(_tiles.WarmUpAsync);
foreach (PackageMount mount in _mounts) mount.Mount(s.FileSystemThreads);
@@ -236,6 +246,7 @@ private async Task StopAsync(bool hurry, bool summaries)
_stopped = true;
await _summaries.CancelAsync().ConfigureAwait(false);
foreach (PackageMount mount in _mounts) mount.Unmount();
+ RemoveAddedSceneryPacks();
_listener?.Stop();
foreach (PackageMount mount in _mounts)
{
@@ -253,12 +264,12 @@ private async Task StopAsync(bool hurry, bool summaries)
if (mount.Overlay.Night is { } night && night.Counts is var (painted, dark, time, kept) && painted + dark > 0)
Log.Info($"{label}Night lights: {painted} paintings in {time.TotalSeconds:F1} s ({kept / 1048576.0:F0} MB written to the cache, compressed), {dark} places without lights");
}
- Log.Info(_cpu.Summary());
+ Log.Info(LoadSummary());
+ if (_seasons?.Summary() is { } seasons) Log.Info(seasons);
ReviewFlight();
ReportFlight();
}
_usage?.Save();
- _colours?.Save();
// The summaries go to disk before the wait for running builds: a closing window gives only a few seconds.
Log.Flush(TimeSpan.FromSeconds(1));
Task[] shutdowns = [.. _mounts.Select(m => m.Scheduler?.ShutdownAsync() ?? m.Streamer?.ShutdownAsync()).OfType()];
@@ -285,6 +296,7 @@ private async Task StopAsync(bool hurry, bool summaries)
_listener?.Dispose();
foreach (PackageMount mount in _mounts) mount.Dispose();
_nightPainting?.Dispose();
+ _observed?.Dispose();
_tiles?.Dispose();
_readLog?.Dispose();
_summaries.Dispose();
@@ -303,6 +315,37 @@ private NightPainting StartNightLights(MountSettings s)
return _nightPainting = new NightPainting(new NightPainter(roads), Math.Clamp(Environment.ProcessorCount / 4, 1, 4));
}
+ ///
+ /// X-Plane's date came after it had read the scenery for another one (the last flight's): asks X-Plane to load the
+ /// scenery again, so the area already loaded shows the season of its date too.
+ ///
+ private void ReloadForTheDate(int day)
+ {
+ if (_listener?.SendCommand(XPlaneUdp.ReloadSceneryCommand) != true) return;
+ Log.Step($"Seasons: the scenery X-Plane had already loaded was coloured for the last flight's date; X-Plane is asked to reload it for {SeasonClock.Describe(day)}");
+ }
+
+ ///
+ /// The satellite record the grass and fields are coloured by: NASA's monthly vegetation index, kept in the low-zoom base folder;
+ /// null with synthetic imagery (tests), which never goes online.
+ ///
+ private static ObservedSeasons? StartSatelliteSeasons(MountSettings s)
+ {
+ if (s.Providers![0].Name == ImageryProvider.Synthetic)
+ {
+ Log.Info("Seasons: synthetic imagery; the season goes by the calendar, without the satellite record");
+ return null;
+ }
+ var source = new VegetationSource(Path.Join(s.Cache, TileStore.FolderName, VegetationSource.FolderName), TimeProvider.System);
+ source.RemoveOldMonths();
+ IReadOnlyList year = source.Year();
+ Log.Info($"Seasons: satellite record from NASA GIBS ({VegetationSource.Layer}), {year[0]:MMMM yyyy} to {year[^1]:MMMM yyyy}, kept in {source.Folder}");
+ return new ObservedSeasons(source, ObservedSeasonsWait);
+ }
+
+ /// How long the first texture of an area waits for its satellite record (once an area, about 2 MB).
+ private static readonly TimeSpan ObservedSeasonsWait = TimeSpan.FromSeconds(5);
+
///
/// The sun the streaming follows to skip the photos at night, or null when it cannot: the photos are built whole
/// without mip streaming, and without the aircraft's position X-Plane is never asked where the sun is.
@@ -353,10 +396,12 @@ private NightPainting StartNightLights(MountSettings s)
return new AltitudeDetail(tiers, full);
}
- /// "Extra quality", "Dynamic quality": the quality in the words of the window.
+ /// "Extra quality", "Dynamic quality from Ultra": the quality in the words of the window.
private static string QualityName(MountSettings s) =>
- s.Dynamic is not null && s.Textures.LevelChange == QualityPreset.Dynamic.Level ? $"{QualityPreset.Dynamic.Name} quality"
- : QualityPreset.ForLevel(s.Textures.LevelChange) is { } preset ? $"{preset.Name} quality" : $"level {s.Textures.LevelChange:+0;-0;0}";
+ (QualityPreset.Current(s.Textures.LevelChange, s.Dynamic is not null) is { } preset
+ ? preset.IsDynamic ? $"{preset.Name} quality from {preset.DynamicBase!.Name}" : $"{preset.Name} quality"
+ : $"level {s.Textures.LevelChange:+0;-0;0}")
+ + (s.Textures.Resolution.IsFull ? "" : $", {s.Textures.Resolution.Label} resolution");
/// Keeps the cache within --cache-limit, removing the areas flown longest ago.
private void TrimCache()
@@ -390,13 +435,31 @@ private void ReportFlight()
GraphicsMemory memory = _graphics.Result();
memory.Save(AppPaths.History);
Log.Info("Photo textures in graphics memory at the peak: " +
- string.Join(", ", GraphicsMemory.Sizes.Select(s => $"{s} px {CacheInventory.FormatBytes(memory.BytesAt(s))}")));
+ string.Join(", ", GraphicsMemory.Sizes.Select(s => $"{s} px {CacheInventory.FormatBytes(memory.BytesAt(s))}")) +
+ (memory.AirportBySize is { } airports && airports.TryGetValue(memory.FlownSize, out long airportBytes)
+ ? $" (airports {CacheInventory.FormatBytes(airportBytes)} of it at {memory.FlownSize} px)" : ""));
}
Report.Save(FlightReport.PathFor(AppPaths.History));
Log.Step($"Flight report: {Report.Duration.TotalMinutes:F0} min, {Report.DistanceKm:F0} km, {CacheInventory.FormatBytes(Report.Bytes)} downloaded " +
$"(peak {Report.PeakMbits:F0} Mbit/s), {Report.Builds} textures built, {Report.StandIns} reads without their real picture (stand-ins or flat)");
}
+ /// Takes the entries the start added out of scenery_packs.ini: their folders are no longer there for X-Plane.
+ private void RemoveAddedSceneryPacks()
+ {
+ if (_addedToSceneryPacks.Count == 0 || _settings.CustomScenery is not { } customScenery) return;
+ string names = string.Join(", ", _addedToSceneryPacks), file = Path.Join(customScenery, SceneryPacks.FileName);
+ try
+ {
+ if (SceneryPacks.RemoveEntries(customScenery, _addedToSceneryPacks))
+ Log.Info($"Removed {names} from {file} (added at the start)");
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ Log.Warning($"Could not remove {names} from {file}: {ex.Message}");
+ }
+ }
+
/// Stops without the summaries, if was not called.
public void Dispose() => StopAsync(hurry: true, summaries: false).GetAwaiter().GetResult();
@@ -442,11 +505,10 @@ private async Task SampleAsync(CancellationToken stop)
if (_timeline.Count % 60 == 0) // every 5 minutes
{
_usage?.Save();
- _colours?.Save();
}
if (_timeline.Count % 12 == 0 && _mounts.Any(m => m.Streamer is not null)) // every minute
{
- _graphics ??= new GraphicsMemoryMeter(Math.Max(_settings.Textures.SizeFor(16), _settings.Textures.SizeFor(18)));
+ _graphics ??= new GraphicsMemoryMeter(_settings.Textures.SizeFor(16), _settings.Textures.SizeFor(18));
_graphics.Sample(_mounts.SelectMany(m => m.Streamer?.HeldDetail(GraphicsMemory.HeldFor) ?? []));
}
}
@@ -469,7 +531,11 @@ private async Task LogSummariesAsync(CancellationToken stop)
logged[i] = overlay.SummaryVersion;
Log.Info(Label(_mounts[i]) + summary);
}
- Log.Info(_cpu.Summary());
+ Log.Info(LoadSummary());
}
}
+
+ /// The CPU and memory line, with the build pictures in it (in use, and kept for the next builds).
+ private string LoadSummary() =>
+ _cpu.Summary() + (_buffers is { } b ? $"; build pictures {b.RentedBytes >> 20} MB in use, {b.KeptBytes >> 20} MB kept" : "");
}
diff --git a/src/OrthoStreamXP/Mounting/PackageMount.cs b/src/OrthoStreamXP/Mounting/PackageMount.cs
index df761f3..25ed9a5 100644
--- a/src/OrthoStreamXP/Mounting/PackageMount.cs
+++ b/src/OrthoStreamXP/Mounting/PackageMount.cs
@@ -18,7 +18,7 @@ internal sealed class PackageMount : IDisposable
public PackageMount(PackagePlan plan, SceneryRoots roots, TextureBuilder? builder, TextureOptions textureOptions,
bool trackAircraft, bool loadAhead, bool lazyTerrainListing, TerrainDecals decals, TextureStreamer? streamer, ViewTracker view, ReadLog? readLog,
- SeasonClock? seasons, AreaUsage? usage, ColourMatcher? colours, SceneryLoads loads, ushort[]? exposure, NightTextures? night)
+ SeasonClock? seasons, AreaUsage? usage, SceneryLoads loads, ushort[]? colours, NightTextures? night)
{
Plan = plan;
Streamer = streamer;
@@ -28,6 +28,8 @@ public PackageMount(PackagePlan plan, SceneryRoots roots, TextureBuilder? builde
{
// The flight-path prefetch goes through the warmer too, so detailed builds stay limited.
Warmer = Catalog is null ? null : new MipWarmer(Catalog, streamer, view, textureOptions.DdsBuildWorkers, warmLoadedScenery: loadAhead);
+ // The scenery tiles on the way get the level X-Plane reads when it loads them, before it does.
+ Upcoming = Warmer is null || !loadAhead || !trackAircraft ? null : new UpcomingScenery(roots.Source, view, loads, Warmer);
}
else
{
@@ -35,7 +37,7 @@ public PackageMount(PackagePlan plan, SceneryRoots roots, TextureBuilder? builde
LoadAhead = Catalog is null || !loadAhead ? null : new LoadAheadPrefetcher(Catalog, Scheduler!, roots, textureOptions.DdsBuildWorkers * 2);
}
Overlay = new SceneryOverlay(roots, Scheduler, lazyTerrainListing, Catalog, streamer, decals, night);
- _host = new FileSystemHost(new SceneryFileSystem(Overlay, "OrthoStreamXP", readLog, plan.Name, seasons, usage, colours, loads, exposure));
+ _host = new FileSystemHost(new SceneryFileSystem(Overlay, "OrthoStreamXP", readLog, plan.Name, seasons, usage, loads, colours));
}
public PackagePlan Plan { get; }
@@ -44,6 +46,7 @@ public PackageMount(PackagePlan plan, SceneryRoots roots, TextureBuilder? builde
public TextureCatalog? Catalog { get; }
public LoadAheadPrefetcher? LoadAhead { get; }
public MipWarmer? Warmer { get; }
+ public UpcomingScenery? Upcoming { get; }
public SceneryOverlay Overlay { get; }
public void Mount(int fileSystemThreads)
@@ -65,6 +68,7 @@ public void Dispose()
Unmount();
_host.Dispose();
LoadAhead?.Dispose();
+ Upcoming?.Dispose();
Warmer?.Dispose();
Scheduler?.Dispose();
Streamer?.Dispose();
diff --git a/src/OrthoStreamXP/OrthoStreamXP.csproj b/src/OrthoStreamXP/OrthoStreamXP.csproj
index b252560..a55f986 100644
--- a/src/OrthoStreamXP/OrthoStreamXP.csproj
+++ b/src/OrthoStreamXP/OrthoStreamXP.csproj
@@ -27,11 +27,19 @@
-
+
+
+
+
+
+
@@ -42,6 +50,8 @@
+
+
@@ -72,7 +82,7 @@
diff --git a/src/OrthoStreamXP/Scenery/Aircraft/AircraftPositionListener.cs b/src/OrthoStreamXP/Scenery/Aircraft/AircraftPositionListener.cs
index cad0299..5790c53 100644
--- a/src/OrthoStreamXP/Scenery/Aircraft/AircraftPositionListener.cs
+++ b/src/OrthoStreamXP/Scenery/Aircraft/AircraftPositionListener.cs
@@ -106,6 +106,21 @@ private void Subscribe(int timesPerSecond)
}
}
+ /// Asks X-Plane to run a command (); false when it could not be sent.
+ public bool SendCommand(string command)
+ {
+ try
+ {
+ _socket?.SendTo(XPlaneUdp.CommandRequest(command), options.XPlane);
+ return _socket is not null;
+ }
+ catch (Exception ex) when (ex is SocketException or ObjectDisposedException)
+ {
+ Log.Warning($"Could not ask X-Plane to run {command}: {ex.Message}");
+ return false;
+ }
+ }
+
public void Stop()
{
if (_stop.IsCancellationRequested) return;
diff --git a/src/OrthoStreamXP/Scenery/Aircraft/AltitudeDetail.cs b/src/OrthoStreamXP/Scenery/Aircraft/AltitudeDetail.cs
index 34adb1a..f5b0914 100644
--- a/src/OrthoStreamXP/Scenery/Aircraft/AltitudeDetail.cs
+++ b/src/OrthoStreamXP/Scenery/Aircraft/AltitudeDetail.cs
@@ -11,11 +11,14 @@ internal sealed record DynamicOptions(double SharpAboveFt = DynamicOptions.Defau
{
public const double DefaultSharpAboveFt = 5000, DefaultBalancedAboveFt = 25000;
- /// The steps, lowest first, that are coarser than (a step no coarser is no saving).
+ ///
+ /// The steps, lowest first, that are coarser than (a step no coarser is no saving). They
+ /// shrink as the mount's resolution does: Dynamic at Medium holds back to Sharp at Medium.
+ ///
public IReadOnlyList TiersBelow(TexturePlan mount)
{
- var tiers = new List { new("Sharp", SharpAboveFt, new TexturePlan(-1)) };
- if (BalancedAboveFt is { } balanced) tiers.Add(new DetailTier("Balanced", balanced, new TexturePlan(-2)));
+ var tiers = new List { new("Sharp", SharpAboveFt, new TexturePlan(-1) { Resolution = mount.Resolution }) };
+ if (BalancedAboveFt is { } balanced) tiers.Add(new DetailTier("Balanced", balanced, new TexturePlan(-2) { Resolution = mount.Resolution }));
return [.. tiers.Where(t => t.Plan.SizeFor(16) < mount.SizeFor(16) || t.Plan.SizeFor(18) < mount.SizeFor(18))];
}
}
diff --git a/src/OrthoStreamXP/Scenery/Aircraft/SceneryLoads.cs b/src/OrthoStreamXP/Scenery/Aircraft/SceneryLoads.cs
index b4e32ea..5a8a782 100644
--- a/src/OrthoStreamXP/Scenery/Aircraft/SceneryLoads.cs
+++ b/src/OrthoStreamXP/Scenery/Aircraft/SceneryLoads.cs
@@ -20,6 +20,15 @@ public static bool TryParse(VirtualPath path, out SceneryTile tile)
}
public override string ToString() => $"{(Lat < 0 ? '-' : '+')}{Math.Abs(Lat):00}{(Lon < 0 ? '-' : '+')}{Math.Abs(Lon):000}";
+
+ /// The tile's DSF in a package, e.g. "Earth nav data/+40+010/+47+011.dsf".
+ public string DsfPath => Path.Join("Earth nav data", new SceneryTile(FloorTen(Lat), FloorTen(Lon)).ToString(), ToString() + ".dsf");
+
+ /// The tile holding a point.
+ public static SceneryTile At(double lat, double lon) =>
+ new((int)Math.Clamp(Math.Floor(lat), -90, 89), (int)Math.Floor(((lon + 180) % 360 + 360) % 360 - 180));
+
+ private static int FloorTen(int degrees) => (int)Math.Floor(degrees / 10.0) * 10;
}
///
@@ -48,6 +57,12 @@ public void Opened(VirtualPath path, string package)
Log.Info($"X-Plane loads the scenery tile {tile}{(package.Length > 0 ? $" of {package}" : "")}; {Where(view.Latest, now)}");
}
+ /// Whether X-Plane has opened the tile's DSF this session (in any package).
+ public bool Seen(SceneryTile tile)
+ {
+ lock (_gate) return _loaded.ContainsKey(tile);
+ }
+
/// The camera's place, height and motion, or that X-Plane has sent none.
internal static string Where(CameraReport? camera, DateTime now)
{
diff --git a/src/OrthoStreamXP/Scenery/Aircraft/XPlaneUdp.cs b/src/OrthoStreamXP/Scenery/Aircraft/XPlaneUdp.cs
index a94950e..7c4546c 100644
--- a/src/OrthoStreamXP/Scenery/Aircraft/XPlaneUdp.cs
+++ b/src/OrthoStreamXP/Scenery/Aircraft/XPlaneUdp.cs
@@ -55,6 +55,12 @@ public static byte[] SubscribeRequest(string dataref, int index, int timesPerSec
return packet;
}
+ /// X-Plane's command that loads the scenery again, as Developer › Reload scenery does.
+ public const string ReloadSceneryCommand = "sim/operation/reload_scenery";
+
+ /// A CMND request: X-Plane runs the command once. Layout: "CMND\0", then the command's name.
+ public static byte[] CommandRequest(string command) => [.. "CMND\0"u8, .. Encoding.ASCII.GetBytes(command)];
+
/// The (index, value) pairs of an RREF answer: "RREF" + 1 byte, then 8 bytes per value.
public static IEnumerable<(int Index, float Value)> ReadSubscribed(byte[] packet, int length)
{
diff --git a/src/OrthoStreamXP/Scenery/Colour/ColourMatcher.cs b/src/OrthoStreamXP/Scenery/Colour/ColourMatcher.cs
deleted file mode 100644
index a704d75..0000000
--- a/src/OrthoStreamXP/Scenery/Colour/ColourMatcher.cs
+++ /dev/null
@@ -1,153 +0,0 @@
-using System.Collections.Concurrent;
-using System.Text.Json;
-using OrthoStreamXP.Setup;
-using OrthoStreamXP.Textures;
-
-namespace OrthoStreamXP.Scenery;
-
-/// Where a texture's picture comes from at the moment: the photo, or the low-zoom base (stand-ins before the photo arrives).
-internal enum PictureSource
-{
- Base,
- Photo,
-}
-
-///
-/// Each texture's colour correction for the session (), kept per version of its picture, and
-/// the relation of photo to base usual in each 1° area. That relation is learnt from the textures measured there (the
-/// median of their own) and kept in the log folder; until an area has of them it is
-/// . An area's relation is fixed for the session at its first use, so the
-/// textures of a flight never change colour under it.
-///
-internal sealed class ColourMatcher
-{
- public const string FileName = "colour-match.json";
- /// Textures measured before an area's own relation is used.
- public const int LearntFrom = 12;
- private const int MaxTextures = 20_000;
- private static readonly JsonSerializerOptions Indented = new() { WriteIndented = true };
-
- private readonly Func _base;
- private readonly Func _resize;
- private readonly string? _path;
- private readonly float _strength;
- private readonly ConcurrentDictionary _textures = new();
- private readonly ConcurrentDictionary _targets = new();
- private readonly Lock _gate = new();
- /// By area, each measured texture's relation to the base (the median of its cells), as R, G, B.
- private readonly Dictionary> _measured;
- private bool _changed;
-
- /// A texture's area from the low-zoom base, or null when it is not on this PC yet.
- /// Resizes a square RGB picture (picture, its size, the size wanted).
- /// The file the areas' relations are kept in, or null for none.
- /// How much of each correction is made, 0 to 1.
- public ColourMatcher(Func baseRegion, Func resize, string? path, double strength = 1)
- {
- _base = baseRegion;
- _resize = resize;
- _path = path;
- _strength = (float)Math.Clamp(strength, 0, 1);
- _measured = Load(path);
- }
-
- ///
- /// The correction of a texture whose picture is the photo, or null when it changes nothing or its base tile is not
- /// here yet (asked again then).
- ///
- /// Changes when the photo does (a finer level from another capture): the correction is measured again.
- /// The photo at about the size asked, RGB, or null when there is none.
- public TextureColour? ForPhoto(TextureName name, object version, Func sample)
- {
- string key = name.Stem;
- if (_textures.TryGetValue(key, out var known) && known.Version.Equals(version)) return known.Colour;
- int cells = ColourMatch.CellsAcross(name), size = cells * ColourMatch.SamplePerCell;
- if (_base(name) is not { } reference || sample(size) is not { } photo) return null;
- ColourGain?[] relation = ColourMatch.Relation(_resize(photo.Rgb, photo.Size, size), _resize(reference.Rgb, reference.Size, size), size, cells);
- AreaName area = AreaName.Of(name);
- TextureColour? colour = TextureColour.Matching(relation, cells, TargetOf(area), _strength);
- Note(area, key, relation);
- return Keep(key, version, colour);
- }
-
- /// The correction of a texture whose picture is the low-zoom base: its area's usual relation, so it looks like the photo will.
- public TextureColour? ForBase(TextureName name)
- {
- string key = name.Stem;
- if (_textures.TryGetValue(key, out var known) && known.Version is PictureSource.Base) return known.Colour;
- return Keep(key, PictureSource.Base, TextureColour.Uniform(TargetOf(AreaName.Of(name)) * _strength));
- }
-
- /// An area's usual relation of photo to base, fixed for the session at its first use.
- public ColourGain TargetOf(AreaName area) => _targets.GetOrAdd(area, a =>
- {
- lock (_gate)
- {
- if (!_measured.TryGetValue(a.ToString(), out var textures) || textures.Count < LearntFrom) return ColourMatch.DefaultTarget;
- return new ColourGain(Median(textures.Values, 0), Median(textures.Values, 1), Median(textures.Values, 2));
- }
- });
-
- /// Saves the areas' relations when they changed.
- public void Save()
- {
- if (_path is null) return;
- string json;
- lock (_gate)
- {
- if (!_changed) return;
- json = JsonSerializer.Serialize(_measured, Indented);
- _changed = false;
- }
- try
- {
- AtomicFile.Write(_path, System.Text.Encoding.UTF8.GetBytes(json));
- }
- catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
- {
- Log.Warning($"Could not save {_path}: {ex.Message}");
- }
- }
-
- private void Note(AreaName area, string texture, ColourGain?[] relation)
- {
- ColourGain[] known = [.. relation.OfType()];
- if (known.Length == 0) return;
- float[] median = [Median(known.Select(g => new[] { g.R, g.G, g.B }), 0), Median(known.Select(g => new[] { g.R, g.G, g.B }), 1),
- Median(known.Select(g => new[] { g.R, g.G, g.B }), 2)];
- lock (_gate)
- {
- string name = area.ToString();
- if (!_measured.TryGetValue(name, out var textures)) _measured[name] = textures = [];
- textures[texture] = median;
- _changed = true;
- }
- }
-
- private TextureColour? Keep(string key, object version, TextureColour? colour)
- {
- if (_textures.Count >= MaxTextures) _textures.Clear();
- _textures[key] = (version, colour);
- return colour;
- }
-
- private static float Median(IEnumerable values, int channel)
- {
- float[] sorted = [.. values.Select(v => v[channel]).Order()];
- return sorted.Length == 0 ? 0 : sorted.Length % 2 == 1 ? sorted[sorted.Length / 2] : (sorted[sorted.Length / 2 - 1] + sorted[sorted.Length / 2]) / 2;
- }
-
- private static Dictionary> Load(string? path)
- {
- try
- {
- if (path is not null && File.Exists(path) && JsonSerializer.Deserialize>>(File.ReadAllText(path)) is { } data)
- return data;
- }
- catch (Exception ex) when (ex is IOException or JsonException or UnauthorizedAccessException)
- {
- Log.Warning($"Could not read {path}: {ex.Message}; the areas' colours are learnt again");
- }
- return [];
- }
-}
diff --git a/src/OrthoStreamXP/Scenery/Colour/ObservedSeasons.cs b/src/OrthoStreamXP/Scenery/Colour/ObservedSeasons.cs
new file mode 100644
index 0000000..fd65b1d
--- /dev/null
+++ b/src/OrthoStreamXP/Scenery/Colour/ObservedSeasons.cs
@@ -0,0 +1,88 @@
+using System.Collections.Concurrent;
+using System.Diagnostics;
+using OrthoStreamXP.Textures;
+
+namespace OrthoStreamXP.Scenery;
+
+///
+/// The satellite record () of the places a flight sees, loaded a tile (about 500 km) at a
+/// time: ahead of the aircraft (), or when a texture first needs its place. A texture that
+/// needs a tile still on its way waits for it for at most from the start of its download, once
+/// for the tile; after that, places in it go by the calendar until it is there.
+///
+internal sealed class ObservedSeasons : IDisposable
+{
+ /// The degrees around the aircraft whose tiles are loaded ahead of it.
+ private const double AheadDegrees = 1.5;
+
+ private readonly VegetationSource _source;
+ private readonly ConcurrentDictionary _tiles = new();
+ private readonly CancellationTokenSource _cancel = new();
+ private readonly CancellationToken _stopping;
+
+ /// How long the first texture of a tile may wait for its download.
+ public ObservedSeasons(VegetationSource source, TimeSpan wait)
+ {
+ _source = source;
+ Wait = wait;
+ _stopping = _cancel.Token;
+ }
+
+ public TimeSpan Wait { get; }
+
+ /// Tiles whose record is loaded.
+ public int TilesLoaded => _tiles.Values.Count(t => t.Task.IsCompletedSuccessfully && t.Task.Result is not null);
+
+ /// Tiles without a record: not downloadable now, or the sea.
+ public int TilesMissing => _tiles.Values.Count(t => t.Task.IsCompleted && (!t.Task.IsCompletedSuccessfully || t.Task.Result is null));
+
+ /// Starts loading the tiles around a place (the aircraft's), so its textures find them ready.
+ public void Prepare(double lat, double lon)
+ {
+ for (double dLat = -AheadDegrees; dLat <= AheadDegrees; dLat += AheadDegrees)
+ for (double dLon = -AheadDegrees; dLon <= AheadDegrees; dLon += AheadDegrees)
+ Load(VegetationKey.At(Math.Clamp(lat + dLat, -89.9, 89.9), WrapLon(lon + dLon)));
+ }
+
+ /// The year of a place, waiting for its tile as allows; null when there is none (yet).
+ public GreennessYear? YearAt(double lat, double lon)
+ {
+ TileLoad load = Load(VegetationKey.At(lat, lon));
+ if (!load.Task.IsCompleted)
+ {
+ TimeSpan left = Wait - Stopwatch.GetElapsedTime(load.Started);
+ if (left <= TimeSpan.Zero || !((IAsyncResult)load.Task).AsyncWaitHandle.WaitOne(left)) return null;
+ }
+ return load.Task.IsCompletedSuccessfully ? load.Task.Result?.YearAt(lat, lon) : null;
+ }
+
+ private TileLoad Load(VegetationKey key) =>
+ _tiles.GetOrAdd(key, k => new TileLoad(Stopwatch.GetTimestamp(), Task.Run(() => LoadAsync(k))));
+
+ private async Task LoadAsync(VegetationKey key)
+ {
+ try
+ {
+ VegetationTile? tile = await _source.LoadAsync(key, _stopping).ConfigureAwait(false);
+ if (tile is null) Log.Info($"Seasons: no satellite record for the tile with its {key} (offline, or the sea); the calendar's season is used there");
+ else Log.Detail($"Seasons: satellite record of the tile with its {key}: {tile.Months} months");
+ return tile;
+ }
+ catch (OperationCanceledException) when (_stopping.IsCancellationRequested)
+ {
+ return null;
+ }
+ }
+
+ private static double WrapLon(double lon) => ((lon + 180) % 360 + 360) % 360 - 180;
+
+ /// Stops the downloads still running; the record kept on disk stays for the next start.
+ public void Dispose()
+ {
+ _cancel.Cancel();
+ _cancel.Dispose();
+ _source.Dispose();
+ }
+
+ private sealed record TileLoad(long Started, Task Task);
+}
diff --git a/src/OrthoStreamXP/Scenery/Colour/SeasonClock.cs b/src/OrthoStreamXP/Scenery/Colour/SeasonClock.cs
index 43ccad2..30e241a 100644
--- a/src/OrthoStreamXP/Scenery/Colour/SeasonClock.cs
+++ b/src/OrthoStreamXP/Scenery/Colour/SeasonClock.cs
@@ -1,3 +1,4 @@
+using System.Collections.Concurrent;
using System.Globalization;
using OrthoStreamXP.Textures;
@@ -9,13 +10,21 @@ internal sealed record SeasonOptions(bool On, double Strength, SeasonChoice Choi
public const double DefaultStrength = 80;
public static readonly SeasonOptions Off = new(false, DefaultStrength / 100, SeasonChoice.Auto);
+
+ /// The season follows X-Plane's date (by the calendar, or with the satellite record), not a season chosen by hand.
+ public bool FollowsDate => Choice is SeasonChoice.Auto or SeasonChoice.Satellite;
}
///
-/// Which season the photo textures show, and each texture's lookup table for it. The date is X-Plane's
+/// Which season the photo textures show, and each texture's lookup table for it and the exposure (). The date is X-Plane's
/// (sim/time/local_date_days), taken when a flight starts, so every texture of a flight is coloured for the same day:
/// a date changed in X-Plane shows from the next flight or move to another place. Until X-Plane sends a date, the date
/// of the last flight is used (kept in the history folder), else today's.
+///
+/// With each place's grass and fields go by its satellite record
+/// (), where it has one; else by the calendar. A texture keeps the table it first got for the
+/// day, so a record arriving while X-Plane reads it never gives its levels different colours.
+///
///
internal sealed class SeasonClock
{
@@ -23,15 +32,26 @@ internal sealed class SeasonClock
public const string DayFileName = "sim-date.txt";
private readonly SeasonOptions _options;
+ private readonly double _exposure;
private readonly string? _dayFile;
+ private readonly ObservedSeasons? _observed;
+ /// With the satellite record: each texture's table for the day it was first read on.
+ private readonly ConcurrentDictionary _tables = new();
private int _day;
private bool _fromXPlane;
+ private long _bySatellite, _byCalendar;
+ /// Whether a texture has been coloured for the day in use (X-Plane keeps what it has read).
+ private volatile bool _coloured;
/// Where the latest X-Plane date is kept between runs.
- public SeasonClock(SeasonOptions options, string? dayFile)
+ /// The satellite record, with ; null goes by the calendar.
+ /// The exposure in percent, made into the same table as the season and the contrast.
+ public SeasonClock(SeasonOptions options, string? dayFile, ObservedSeasons? observed = null, double exposure = Exposure.Full)
{
_options = options;
+ _exposure = exposure;
_dayFile = dayFile;
+ _observed = options.Choice == SeasonChoice.Satellite ? observed : null;
_day = Remembered(dayFile) ?? DateTime.Now.DayOfYear - 1;
}
@@ -40,18 +60,26 @@ public SeasonClock(SeasonOptions options, string? dayFile)
public SeasonOptions Options => _options;
- /// A date from X-Plane: used if it is the first, or a flight is starting (a new flight, or a move to another place).
- public void OfferDate(int dayOfYear, bool newFlight)
+ ///
+ /// A date from X-Plane: used if it is the first, or a flight is starting (a new flight, or a move to another place).
+ /// Returns true when it changes the season of textures X-Plane has already read: X-Plane sends its date only once a
+ /// flight has loaded, so the first area of a flight on another date than the last one is coloured for the old date
+ /// until X-Plane reads it again.
+ ///
+ public bool OfferDate(int dayOfYear, bool newFlight)
{
- if (dayOfYear is < 0 or > 365 || (_fromXPlane && !newFlight)) return;
+ if (dayOfYear is < 0 or > 365 || (_fromXPlane && !newFlight)) return false;
bool first = !_fromXPlane;
_fromXPlane = true;
- if (dayOfYear == Day && !first) return;
+ if (dayOfYear == Day && !first) return false;
if (first || dayOfYear != Day)
Log.Step($"Seasons: X-Plane's date is {Describe(dayOfYear)}" +
- (_options.Choice == SeasonChoice.Auto ? "" : $" (the season is set by hand: {_options.Choice})"));
- if (dayOfYear == Day) return;
+ (_options.FollowsDate ? "" : $" (the season is set by hand: {_options.Choice})"));
+ if (dayOfYear == Day) return false;
Volatile.Write(ref _day, dayOfYear);
+ _tables.Clear(); // a new flight: every texture is read again
+ bool stale = _coloured && _options.FollowsDate;
+ _coloured = false;
try
{
if (_dayFile is not null) File.WriteAllText(_dayFile, dayOfYear.ToString(CultureInfo.InvariantCulture));
@@ -60,14 +88,32 @@ public void OfferDate(int dayOfYear, bool newFlight)
{
// Only a convenience for the next start.
}
+ return stale;
}
- /// The season at a place in the settings' strength (summer when it changes nothing).
+ /// The season at a place by the calendar (or chosen by hand) in the settings' strength (summer when it changes nothing).
public SeasonState StateAt(double lat) =>
- (_options.Choice == SeasonChoice.Auto ? SeasonModel.For(Day, lat) : SeasonModel.For(_options.Choice)).Scaled(_options.Strength);
+ (_options.FollowsDate ? SeasonModel.For(Day, lat) : SeasonModel.For(_options.Choice)).Scaled(_options.Strength);
+
+ /// A texture's lookup table for the season at its centre, the contrast and the exposure ().
+ public ushort[] TableFor(TextureName name)
+ {
+ if (!_coloured) _coloured = true;
+ if (_observed is null) return PhotoColours.TableFor(StateAt(name.Center.Lat), _exposure);
+ int day = Day;
+ if (_tables.TryGetValue(name, out var kept) && kept.Day == day) return kept.Table;
+ var (lat, lon) = name.Center;
+ GreennessYear? year = _observed.YearAt(lat, lon);
+ Interlocked.Increment(ref year is null ? ref _byCalendar : ref _bySatellite);
+ SeasonState state = year is null ? SeasonModel.For(day, lat) : ObservedSeason.For(year, day, lat);
+ ushort[] table = PhotoColours.TableFor(state.Scaled(_options.Strength), _exposure);
+ // The first table wins: two reads at once of a texture still give X-Plane the same colours.
+ return _tables.GetOrAdd(name, (day, table)) is var (keptDay, keptTable) && keptDay == day ? keptTable : table;
+ }
- /// A texture's lookup table for the season at its centre, or null when nothing in it changes.
- public ushort[]? TableFor(TextureName name) => Seasons.TableFor(StateAt(name.Center.Lat));
+ /// "1,204 textures coloured by the satellite record, 36 by the calendar alone", or null without the record.
+ public string? Summary() => _observed is null ? null : string.Create(CultureInfo.InvariantCulture,
+ $"Seasons: {Interlocked.Read(ref _bySatellite):N0} textures coloured by the satellite record, {Interlocked.Read(ref _byCalendar):N0} by the calendar alone (satellite record of {_observed.TilesLoaded} area(s) of about 500 km, none for {_observed.TilesMissing})");
/// "27 October" for day 299.
public static string Describe(int dayOfYear) =>
diff --git a/src/OrthoStreamXP/Scenery/FileSystem/DsfTerrainTable.cs b/src/OrthoStreamXP/Scenery/FileSystem/DsfTerrainTable.cs
new file mode 100644
index 0000000..567706a
--- /dev/null
+++ b/src/OrthoStreamXP/Scenery/FileSystem/DsfTerrainTable.cs
@@ -0,0 +1,68 @@
+using System.Buffers.Binary;
+using System.Text;
+
+namespace OrthoStreamXP.Scenery;
+
+///
+/// The terrain definitions a DSF uses, from its terrain table (the DEFN atom's TERT strings): what X-Plane opens when
+/// it loads the tile, read without X-Plane. The table sits after the 100-byte header, before the mesh, so only the
+/// first few KB of the file are read (17 KB for a tile of 478 definitions).
+///
+internal static class DsfTerrainTable
+{
+ private const int HeaderBytes = 12; // "XPLNEDSF" and the version
+ private const int AtomHeaderBytes = 8; // id and length, the length counting these 8 bytes
+ // Atom ids are 4 characters stored as a little-endian number, so they appear reversed in the file.
+ private const uint Definitions = 'D' << 24 | 'E' << 16 | 'F' << 8 | 'N';
+ private const uint TerrainTable = 'T' << 24 | 'E' << 16 | 'R' << 8 | 'T';
+ /// A definitions atom larger than this is not a terrain table worth reading (they run to tens of KB).
+ private const int MaxDefinitionsBytes = 16 << 20;
+
+ ///
+ /// The terrain definition names (such as "terrain/22992_34800_BI16.ter"), empty when the file is not an
+ /// uncompressed DSF (a 7-Zip one is never read here) or has no terrain table.
+ ///
+ public static IReadOnlyList Read(string dsfPath)
+ {
+ using var file = new FileStream(dsfPath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 1, FileOptions.RandomAccess);
+ Span header = stackalloc byte[HeaderBytes];
+ if (file.ReadAtLeast(header, HeaderBytes, throwOnEndOfStream: false) < HeaderBytes || !header[..8].SequenceEqual("XPLNEDSF"u8)) return [];
+
+ Span atom = stackalloc byte[AtomHeaderBytes];
+ long at = HeaderBytes;
+ while (at + AtomHeaderBytes <= file.Length)
+ {
+ file.Position = at;
+ if (file.ReadAtLeast(atom, AtomHeaderBytes, throwOnEndOfStream: false) < AtomHeaderBytes) return [];
+ uint id = BinaryPrimitives.ReadUInt32LittleEndian(atom);
+ uint length = BinaryPrimitives.ReadUInt32LittleEndian(atom[4..]);
+ if (length < AtomHeaderBytes) return [];
+ if (id == Definitions)
+ {
+ if (length > MaxDefinitionsBytes) return [];
+ byte[] definitions = new byte[length - AtomHeaderBytes];
+ file.ReadExactly(definitions);
+ return TerrainNames(definitions);
+ }
+ at += length;
+ }
+ return [];
+ }
+
+ /// The TERT strings among the definitions atom's sub-atoms.
+ private static string[] TerrainNames(ReadOnlySpan definitions)
+ {
+ int at = 0;
+ while (at + AtomHeaderBytes <= definitions.Length)
+ {
+ uint id = BinaryPrimitives.ReadUInt32LittleEndian(definitions[at..]);
+ int length = (int)Math.Min(BinaryPrimitives.ReadUInt32LittleEndian(definitions[(at + 4)..]), int.MaxValue);
+ if (length < AtomHeaderBytes || at + length > definitions.Length) return [];
+ if (id == TerrainTable)
+ return Encoding.ASCII.GetString(definitions.Slice(at + AtomHeaderBytes, length - AtomHeaderBytes))
+ .Split('\0', StringSplitOptions.RemoveEmptyEntries);
+ at += length;
+ }
+ return [];
+ }
+}
diff --git a/src/OrthoStreamXP/Scenery/FileSystem/SceneryFileSystem.cs b/src/OrthoStreamXP/Scenery/FileSystem/SceneryFileSystem.cs
index 78a1b61..a264f6d 100644
--- a/src/OrthoStreamXP/Scenery/FileSystem/SceneryFileSystem.cs
+++ b/src/OrthoStreamXP/Scenery/FileSystem/SceneryFileSystem.cs
@@ -11,14 +11,14 @@ namespace OrthoStreamXP.Scenery;
///
/// Read-only WinFsp file system over a . Streamed textures are answered by the
/// overlay's ; with a , every open and read is recorded. Photo textures
-/// get their colours evened out (), then the season's () and the
-/// as they are read ().
+/// get the season's colours, the contrast and the exposure as they are read, one table for all ().
///
/// The package name in the read log.
+/// Each texture's table for its season, the contrast and the exposure; null with the seasons off.
/// Notes the scenery tiles (DSFs) X-Plane loads.
-/// The exposure's lookup table (), or null for the photos as they are.
+/// The photos' table with the seasons off (the contrast and the exposure), or null for the photos as stored.
internal sealed class SceneryFileSystem(SceneryOverlay overlay, string label, ReadLog? readLog = null, string package = "", SeasonClock? seasons = null,
- OrthoStreamXP.Setup.AreaUsage? usage = null, ColourMatcher? colours = null, SceneryLoads? loads = null, ushort[]? exposure = null)
+ OrthoStreamXP.Setup.AreaUsage? usage = null, SceneryLoads? loads = null, ushort[]? colours = null)
: FileSystemBase
{
private const ulong TotalSize = 1UL << 40, FreeSize = 1UL << 39;
@@ -44,12 +44,9 @@ private sealed class Handle(VirtualPath path, string backing, bool isDirectory)
/// A photo texture X-Plane gets as a finished file: its reads are still paging evidence.
public StreamedTexture? Photo { get; init; }
public ReadCursor? Cursor { get; init; }
- /// A photo texture whose colours change as it is read: its name, colour-block size (8 or 16) and width; 0 bytes: left as it is.
+ /// A photo texture whose colours change as it is read: its name and colour-block size (8 or 16); 0 bytes: left as it is.
public TextureName SeasonName { get; init; }
public int SeasonBlockBytes { get; init; }
- public int SeasonSize { get; init; }
- /// The backing file's write time: a new one is measured again for its colours.
- public DateTime FileVersion { get; init; }
}
private static byte[] SecurityFromSddl(string sddl)
@@ -140,7 +137,7 @@ public override int Open(string fileName, uint createOptions, uint grantedAccess
fileNode = new Handle(path, "", false)
{
Streamed = streamed, Cursor = new ReadCursor(), Length = streamed.Layout.Length,
- SeasonName = streamed.Name, SeasonBlockBytes = Recolours ? 8 : 0, SeasonSize = streamed.Layout.Size,
+ SeasonName = streamed.Name, SeasonBlockBytes = Recolours ? 8 : 0,
};
fileInfo = Describe(streamed);
readLog?.Open(package, path, "streamed");
@@ -177,8 +174,6 @@ public override int Open(string fileName, uint createOptions, uint grantedAccess
Cursor = photo is null ? null : new ReadCursor(),
SeasonName = seasonName,
SeasonBlockBytes = blockBytes,
- SeasonSize = size,
- FileVersion = blockBytes > 0 ? System.IO.File.GetLastWriteTimeUtc(backing) : default,
};
fileNode = handle;
fileInfo = Describe(isDirectory ? new DirectoryInfo(backing) : new FileInfo(backing));
@@ -214,13 +209,11 @@ public override unsafe int Read(object fileNode, object fileDesc, IntPtr buffer,
var handle = (Handle)fileNode;
if (offset >= (ulong)handle.Length) return handle.File is null && handle.Streamed is null && handle.Content is null && handle.Night is null ? STATUS_ACCESS_DENIED : STATUS_END_OF_FILE;
var target = new Span((void*)buffer, checked((int)length));
- // Before the read: a photo arriving meanwhile is read with the base's correction until the next read, never the reverse.
- TextureColour? colour = ColourOf(handle);
if (handle.Streamed is { } streamed)
{
ReadAnswer answer = overlay.Streamer!.Read(streamed, handle.Cursor!, (long)offset, target);
bytesTransferred = (uint)answer.Bytes;
- Recolor(handle, target[..answer.Bytes], offset, colour);
+ Recolor(handle, target[..answer.Bytes], offset);
LogTextureRead(handle.Path, (long)offset, answer, streamed);
return STATUS_SUCCESS;
}
@@ -241,7 +234,7 @@ public override unsafe int Read(object fileNode, object fileDesc, IntPtr buffer,
}
if (handle.File is null) return STATUS_ACCESS_DENIED;
bytesTransferred = (uint)RandomAccess.Read(handle.File, target, (long)offset);
- Recolor(handle, target[..(int)bytesTransferred], offset, colour);
+ Recolor(handle, target[..(int)bytesTransferred], offset);
if (handle.Photo is { } photo)
LogTextureRead(handle.Path, (long)offset, overlay.Streamer!.NoteFileRead(photo, handle.Cursor!, (long)offset, (int)bytesTransferred), photo);
else
@@ -250,43 +243,13 @@ public override unsafe int Read(object fileNode, object fileDesc, IntPtr buffer,
}
/// Whether photo textures get any colour adjustment.
- private bool Recolours => seasons is not null || colours is not null || exposure is not null;
+ private bool Recolours => seasons is not null || colours is not null;
- /// The evened-out colours, the season's and the exposure for a photo texture's bytes (the cache keeps the imagery as downloaded).
- private void Recolor(Handle handle, Span data, ulong offset, TextureColour? colour)
+ /// The season's colours, the contrast and the exposure for a photo texture's bytes (the cache keeps the colours as built).
+ private void Recolor(Handle handle, Span data, ulong offset)
{
if (handle.SeasonBlockBytes == 0) return;
- PhotoColours.Apply(data, (long)offset, handle.SeasonBlockBytes, handle.SeasonSize, colour, seasons?.TableFor(handle.SeasonName), exposure);
- }
-
- ///
- /// A photo texture's colour correction: measured on the photo (a streamed texture's real data, or the file), or the
- /// base's while the picture is still the low-zoom base; null when there is none.
- ///
- private TextureColour? ColourOf(Handle handle)
- {
- if (colours is null || handle.SeasonBlockBytes == 0) return null;
- if (handle.Streamed is { } streamed)
- {
- TextureStreamer streamer = overlay.Streamer!;
- var (source, version) = streamer.Picture(streamed);
- return source == PictureSource.Photo
- ? colours.ForPhoto(streamed.Name, version, size => streamer.PhotoSample(streamed, size))
- : colours.ForBase(streamed.Name);
- }
- return handle.SeasonBlockBytes == 8 && handle.File is { } file
- ? colours.ForPhoto(handle.SeasonName, handle.FileVersion, size => FileSample(file, handle.SeasonSize, size))
- : null;
- }
-
- /// The level of a DXT1 file nearest pixels, decoded to RGB; null when the file is not a full chain of levels.
- internal static (byte[] Rgb, int Size)? FileSample(SafeFileHandle file, int fileSize, int size)
- {
- var layout = DdsLayout.For(fileSize);
- if (RandomAccess.GetLength(file) < layout.Length) return null;
- int mip = Math.Clamp((int)Math.Round(Math.Log2((double)fileSize / size)), 0, layout.Levels - 1), levelSize = layout.SizeOf(mip);
- byte[] blocks = new byte[layout.LengthOf(mip)];
- return RandomAccess.Read(file, blocks, layout.Offset(mip)) < blocks.Length ? null : (Dds.DecodeLevel(blocks, levelSize, levelSize), levelSize);
+ PhotoColours.Apply(data, (long)offset, handle.SeasonBlockBytes, seasons is not null ? seasons.TableFor(handle.SeasonName) : colours);
}
/// A photo texture file whose colours can change: square DXT1, DXT3 or DXT5, named like 21904_35824_BI16.dds.
diff --git a/src/OrthoStreamXP/Scenery/FileSystem/SceneryPackEntry.cs b/src/OrthoStreamXP/Scenery/FileSystem/SceneryPackEntry.cs
new file mode 100644
index 0000000..843f1c4
--- /dev/null
+++ b/src/OrthoStreamXP/Scenery/FileSystem/SceneryPackEntry.cs
@@ -0,0 +1,34 @@
+namespace OrthoStreamXP.Scenery;
+
+/// A SCENERY_PACK line of X-Plane's scenery_packs.ini: the package's path as written, and whether X-Plane loads it.
+internal sealed record SceneryPackEntry(string Path, bool Enabled)
+{
+ private const string EnabledPrefix = "SCENERY_PACK ", DisabledPrefix = "SCENERY_PACK_DISABLED ";
+
+ /// The package's folder name (the last part of the path), or the path itself for X-Plane's own entries such as *GLOBAL_AIRPORTS*.
+ public string Name
+ {
+ get
+ {
+ string normalized = Normalize(Path);
+ return normalized[(normalized.LastIndexOf('/') + 1)..];
+ }
+ }
+
+ /// The entry a line holds, or null for the header and other lines.
+ public static SceneryPackEntry? Parse(string line)
+ {
+ string trimmed = line.Trim();
+ if (trimmed.StartsWith(DisabledPrefix, StringComparison.Ordinal)) return new(trimmed[DisabledPrefix.Length..].Trim(), Enabled: false);
+ if (trimmed.StartsWith(EnabledPrefix, StringComparison.Ordinal)) return new(trimmed[EnabledPrefix.Length..].Trim(), Enabled: true);
+ return null;
+ }
+
+ /// The line X-Plane reads for this entry; the path stays as it was written.
+ public string ToLine() => (Enabled ? EnabledPrefix : DisabledPrefix) + Path;
+
+ /// Whether names the same folder, whichever slashes and trailing slash it is written with.
+ public bool IsAt(string path) => Normalize(Path).Equals(Normalize(path), StringComparison.OrdinalIgnoreCase);
+
+ private static string Normalize(string path) => path.Trim().Replace('\\', '/').TrimEnd('/');
+}
diff --git a/src/OrthoStreamXP/Scenery/FileSystem/SceneryPackList.cs b/src/OrthoStreamXP/Scenery/FileSystem/SceneryPackList.cs
new file mode 100644
index 0000000..0bc4c2d
--- /dev/null
+++ b/src/OrthoStreamXP/Scenery/FileSystem/SceneryPackList.cs
@@ -0,0 +1,62 @@
+using System.Text;
+
+namespace OrthoStreamXP.Scenery;
+
+///
+/// The entries of X-Plane's Custom Scenery\scenery_packs.ini, for the person to switch on or off and reorder. The file is read
+/// again for every change, so what changed it meanwhile (X-Plane, a mount starting or stopping) is kept; the other lines and the
+/// line endings stay.
+///
+internal sealed class SceneryPackList(string customScenery)
+{
+ public string FilePath { get; } = Path.Join(customScenery, SceneryPacks.FileName);
+
+ /// The entries in the file's order (highest priority first); none while there is no file.
+ public IReadOnlyList Read() =>
+ File.Exists(FilePath) ? [.. File.ReadAllLines(FilePath).Select(SceneryPackEntry.Parse).OfType()] : [];
+
+ ///
+ /// Switches the entries at on or off in place. Returns whether the file changed (not when there is
+ /// no such entry, or it already is that way).
+ ///
+ public bool SetEnabled(string path, bool enabled) => Change(lines =>
+ {
+ bool changed = false;
+ for (int i = 0; i < lines.Length; i++)
+ {
+ if (SceneryPackEntry.Parse(lines[i]) is not { } entry || entry.Enabled == enabled || !entry.IsAt(path)) continue;
+ lines[i] = (entry with { Enabled = enabled }).ToLine();
+ changed = true;
+ }
+ return changed;
+ });
+
+ ///
+ /// Moves the entry at so it becomes entry number (0 is the first, the highest
+ /// priority in X-Plane); the entries between shift by one, and the lines that are not entries keep their places. Returns
+ /// whether the file changed (not when there is no such entry, it already is there, or is outside the list).
+ ///
+ public bool MoveTo(string path, int to) => Change(lines =>
+ {
+ int[] entries = [.. Enumerable.Range(0, lines.Length).Where(i => SceneryPackEntry.Parse(lines[i]) is not null)];
+ int from = Array.FindIndex(entries, i => SceneryPackEntry.Parse(lines[i])!.IsAt(path));
+ if (from < 0 || to < 0 || to >= entries.Length || from == to) return false;
+ string moved = lines[entries[from]];
+ int step = to < from ? -1 : 1;
+ for (int k = from; k != to; k += step) lines[entries[k]] = lines[entries[k + step]];
+ lines[entries[to]] = moved;
+ return true;
+ });
+
+ /// Reads the file's lines, lets change them in place, and writes them back if it did.
+ private bool Change(Func edit)
+ {
+ if (!File.Exists(FilePath)) return false;
+ string text = File.ReadAllText(FilePath);
+ string newline = text.Contains("\r\n", StringComparison.Ordinal) ? "\r\n" : "\n";
+ string[] lines = text.ReplaceLineEndings("\n").TrimEnd('\n').Split('\n');
+ if (!edit(lines)) return false;
+ AtomicFile.Write(FilePath, Encoding.UTF8.GetBytes(string.Join(newline, lines) + newline));
+ return true;
+ }
+}
diff --git a/src/OrthoStreamXP/Scenery/FileSystem/SceneryPacks.cs b/src/OrthoStreamXP/Scenery/FileSystem/SceneryPacks.cs
index 75808b0..44ae9c8 100644
--- a/src/OrthoStreamXP/Scenery/FileSystem/SceneryPacks.cs
+++ b/src/OrthoStreamXP/Scenery/FileSystem/SceneryPacks.cs
@@ -5,7 +5,7 @@ namespace OrthoStreamXP.Scenery;
///
/// Finds the scenery packages in a folder of base packages, and keeps the mounted ones at the end of
/// X-Plane's Custom Scenery\scenery_packs.ini: the end has the lowest priority, so airports, overlays and
-/// other scenery listed above them stay on top of the photo base.
+/// other scenery listed above them stay on top of the photo base. The entries a mount added are taken out again when it stops.
///
internal static class SceneryPacks
{
@@ -45,11 +45,20 @@ public static bool IsInCustomScenery(string folder, string xplane)
/// scenery_packs.ini, adding the missing ones; a disabled entry stays disabled. The previous file is kept
/// as scenery_packs.ini.bak. Returns whether the file changed.
///
- public static bool MoveToEnd(string customScenery, IReadOnlyList packageNames)
+ public static bool MoveToEnd(string customScenery, IReadOnlyList packageNames) =>
+ MoveToEnd(customScenery, packageNames, out _);
+
+ ///
+ /// The packages the file had no entry for, which this added.
+ public static bool MoveToEnd(string customScenery, IReadOnlyList packageNames, out IReadOnlyList added)
{
string file = Path.Join(customScenery, FileName);
string? text = File.Exists(file) ? File.ReadAllText(file) : null;
string[] lines = text is null ? NewFileHeader : text.ReplaceLineEndings("\n").TrimEnd('\n').Split('\n');
+ var listed = new HashSet(StringComparer.OrdinalIgnoreCase);
+ foreach (string line in lines)
+ if (PackageOf(line, packageNames, out _) is { } name) listed.Add(name);
+ added = [.. packageNames.Where(name => !listed.Contains(name))];
List updated = Reorder(lines, packageNames);
if (lines.SequenceEqual(updated)) return false;
string newline = text is not null && !text.Contains("\r\n", StringComparison.Ordinal) ? "\n" : "\r\n";
@@ -58,6 +67,24 @@ public static bool MoveToEnd(string customScenery, IReadOnlyList package
return true;
}
+ ///
+ /// Takes the entries of out of scenery_packs.ini: the packages a mount added at its start,
+ /// once it stops and their folders are gone. No .bak is written, so the one kept at the start still holds the file from
+ /// before it. Returns whether the file changed.
+ ///
+ public static bool RemoveEntries(string customScenery, IReadOnlyList packageNames)
+ {
+ string file = Path.Join(customScenery, FileName);
+ if (packageNames.Count == 0 || !File.Exists(file)) return false;
+ string text = File.ReadAllText(file);
+ string[] lines = text.ReplaceLineEndings("\n").TrimEnd('\n').Split('\n');
+ string[] kept = [.. lines.Where(line => PackageOf(line, packageNames, out _) is null)];
+ if (kept.Length == lines.Length) return false;
+ string newline = text.Contains("\r\n", StringComparison.Ordinal) ? "\r\n" : "\n";
+ AtomicFile.Write(file, Encoding.UTF8.GetBytes(string.Join(newline, kept) + newline));
+ return true;
+ }
+
///
/// Renames the entries of packages that took a new name (: old and new) in scenery_packs.ini,
/// in place: their position and whether they are disabled stay. The previous file is kept as scenery_packs.ini.bak.
@@ -133,7 +160,8 @@ internal static List Reorder(IReadOnlyList lines, IReadOnlyList<
return packageNames.FirstOrDefault(name => folderName.Equals(name, StringComparison.OrdinalIgnoreCase));
}
- private static bool IsOverlays(string packageName) => packageName.Contains("Overlays", StringComparison.OrdinalIgnoreCase);
+ /// Whether a package holds only overlays (roads, forests, buildings: XPME_Overlays, OrthoStream_Overlays), not a region's ground.
+ internal static bool IsOverlays(string packageName) => packageName.Contains("Overlays", StringComparison.OrdinalIgnoreCase);
private static bool IsDownloadedMesh(string packageName) => packageName.StartsWith(DownloadedPrefix, StringComparison.OrdinalIgnoreCase);
diff --git a/src/OrthoStreamXP/Scenery/Prefetch/MipWarmer.cs b/src/OrthoStreamXP/Scenery/Prefetch/MipWarmer.cs
index 9c8c865..2c18805 100644
--- a/src/OrthoStreamXP/Scenery/Prefetch/MipWarmer.cs
+++ b/src/OrthoStreamXP/Scenery/Prefetch/MipWarmer.cs
@@ -39,6 +39,15 @@ internal sealed class MipWarmer : IDisposable
/// Small builds at once: as many as the streamer lets builds ahead of X-Plane run.
private const int SmallInFlight = TextureStreamer.DefaultMaxBuilds / 2;
+ ///
+ /// The size of the level X-Plane reads of every texture of a DSF it loads, however far away the texture is: in the
+ /// test flight of 17 Nov every such read of the 8192 px ZL16 and ZL18 textures wanted their 512 px level, 100-200 km
+ /// out where the distance asks for 64 px, and read nothing more of 95 % of them. For a ZL16 texture that is the
+ /// low-zoom base; for a ZL18 one four zoom 15 tiles, which X-Plane's loading waited for, 5 s after opening the
+ /// .ter, some 0.3-6 s for each of 400 textures per scenery tile.
+ ///
+ internal const int LoadReadPx = 512;
+
/// The places a load-ahead build takes, each kind with its own limit.
internal enum BuildKind { Base, Small, Heavy }
/// How often the progress is logged while X-Plane loads scenery, and otherwise.
@@ -47,8 +56,9 @@ internal enum BuildKind { Base, Small, Heavy }
///
/// A texture to warm; and fixed for the flight-path prefetch.
/// : queued again because the aircraft moved, not because X-Plane loaded it.
+ /// : of a scenery tile X-Plane has yet to load ().
///
- private readonly record struct Request(VirtualPath Texture, int? Mip = null, int? Priority = null, bool Recheck = false);
+ private readonly record struct Request(VirtualPath Texture, int? Mip = null, int? Priority = null, bool Recheck = false, bool Upcoming = false);
private readonly TextureCatalog _catalog;
private readonly TextureStreamer _streamer;
@@ -62,7 +72,7 @@ internal enum BuildKind { Base, Small, Heavy }
private Task? _loop;
/// Builds running, by .
private readonly int[] _running = new int[3];
- private int _queued, _alreadyHad;
+ private int _queued, _alreadyHad, _upcoming;
private (int Known, int Waiting, int Queued, int AlreadyHad) _reported;
private TimeSpan _reportedAt;
@@ -114,6 +124,28 @@ public int Prefetch(IReadOnlyList textures)
return textures.Count;
}
+ ///
+ /// The textures of a scenery tile X-Plane will load soon: each fetched to the level X-Plane reads when it loads the
+ /// tile (), after everything the loaded scenery needs. Returns how many were queued.
+ ///
+ public int PrepareUpcoming(IReadOnlyList textures)
+ {
+ int added = 0;
+ lock (_gate)
+ foreach (VirtualPath texture in textures)
+ if (_waiting.TryAdd(texture.Key, new Request(texture, Upcoming: true))) added++;
+ Wake();
+ return added;
+ }
+
+ /// The level X-Plane reads of the texture when it loads its scenery tile (), at most the base level.
+ internal static int LoadMip(StreamedTexture t)
+ {
+ int mip = 0;
+ while (mip < t.BaseMip && t.Layout.SizeOf(mip) > LoadReadPx) mip++;
+ return mip;
+ }
+
private void Add(Request request)
{
lock (_gate) _waiting.TryAdd(request.Texture.Key, request);
@@ -125,14 +157,21 @@ private void Wake()
if (_wake.CurrentCount == 0) _wake.Release();
}
- /// The level to fetch and its priority, and the distance (for the order); null when it is not a photo texture.
- internal (StreamedTexture Texture, int Mip, int Priority, double Distance)? Target(VirtualPath path, int? mip = null, int? priority = null)
+ ///
+ /// The level to fetch and its priority, and the distance (for the order); null when it is not a photo texture.
+ /// Never coarser than the level X-Plane reads when it loads the texture's tile (): it reads
+ /// that some seconds after it opens the texture's terrain definition, whatever the distance.
+ ///
+ internal (StreamedTexture Texture, int Mip, int Priority, double Distance)? Target(VirtualPath path, int? mip = null, int? priority = null, bool upcoming = false)
{
if (_streamer.Get(path) is not { } t) return null;
+ int load = LoadMip(t);
if (_view.Current is not { } camera)
- return (t, mip ?? t.BaseMip, priority ?? FetchPriority.Background, double.MaxValue);
+ return (t, mip ?? load, priority ?? FetchPriority.Background, double.MaxValue);
double distance = ViewTracker.DistanceM(camera, t.Lat, t.Lon);
if (mip is int fixedMip) return (t, fixedMip, priority ?? FetchPriority.Warm, distance);
+ // A tile X-Plane has yet to load: minutes ahead, after what the loaded scenery needs.
+ if (upcoming) return (t, load, FetchPriority.Background, distance);
double soon = distance;
if (camera.Motion is { SpeedMps: >= PrefetchPlanner.MovingSpeedMps } motion)
@@ -142,14 +181,15 @@ private void Wake()
soon = Math.Max(0, distance - Math.Max(0, closing) * LeadSeconds);
}
int wanted = _streamer.Model.MipFor(soon, t.SizeM, t.Layout.Size);
- int target = Math.Min(wanted, t.BaseMip);
+ // Raised to the load level, X-Plane reads it within seconds whatever the distance: as soon as a middle-distance level.
+ if (load < wanted) return (t, load, FetchPriority.Warm + load, distance);
int targetPriority = TextureStreamer.BandOf(t, wanted) switch
{
Band.Near => FetchPriority.NearWarm,
Band.Middle => FetchPriority.Warm + wanted,
_ => FetchPriority.Background,
};
- return (t, target, targetPriority, distance);
+ return (t, wanted, targetPriority, distance);
}
private async Task RunAsync()
@@ -177,7 +217,7 @@ internal void StartWhatFits()
lock (_gate) waiting = [.. _waiting.Values];
if (waiting.Length == 0) return;
var ranked = waiting
- .Select(r => (Request: r, Target: Target(r.Texture, r.Mip, r.Priority)))
+ .Select(r => (Request: r, Target: Target(r.Texture, r.Mip, r.Priority, r.Upcoming)))
.OrderBy(x => x.Target?.Priority ?? int.MaxValue).ThenBy(x => x.Target?.Distance ?? double.MaxValue);
foreach (var (request, target) in ranked)
{
@@ -192,7 +232,7 @@ internal void StartWhatFits()
if (_streamer.RealFrom(t.Texture) <= t.Mip)
{
Remove(request);
- if (!request.Recheck) Interlocked.Increment(ref _alreadyHad);
+ if (!request.Recheck && !request.Upcoming) Interlocked.Increment(ref _alreadyHad);
continue;
}
if (_streamer.Warm(request.Texture, t.Mip, t.Priority) is not { } build)
@@ -202,6 +242,7 @@ internal void StartWhatFits()
}
Remove(request);
Interlocked.Increment(ref _queued);
+ if (request.Upcoming) Interlocked.Increment(ref _upcoming);
if (build.IsCompleted) continue;
Interlocked.Increment(ref _running[(int)kind]);
build.ContinueWith(_ =>
@@ -245,7 +286,8 @@ private void ReportProgress()
if (_clock.Elapsed - _reportedAt < interval) return;
(_reported, _reportedAt) = (now, _clock.Elapsed);
Log.Info($"Load-ahead: {Count(now.Known, "texture")} of the loaded scenery known, {now.Waiting} waiting for a place; " +
- $"{Count(now.Queued, "build")} started so far, {now.AlreadyHad} had what they needed when X-Plane loaded them");
+ $"{Count(now.Queued, "build")} started so far ({Volatile.Read(ref _upcoming)} for scenery X-Plane has yet to load), " +
+ $"{now.AlreadyHad} had what they needed when X-Plane loaded them");
}
private static string Count(int n, string noun) => $"{n} {noun}{(n == 1 ? "" : "s")}";
diff --git a/src/OrthoStreamXP/Scenery/Prefetch/UpcomingScenery.cs b/src/OrthoStreamXP/Scenery/Prefetch/UpcomingScenery.cs
new file mode 100644
index 0000000..fc2fed9
--- /dev/null
+++ b/src/OrthoStreamXP/Scenery/Prefetch/UpcomingScenery.cs
@@ -0,0 +1,122 @@
+using OrthoStreamXP.Textures;
+
+namespace OrthoStreamXP.Scenery;
+
+///
+/// Readies the scenery tiles X-Plane will load next, minutes before it does. When X-Plane loads a tile it opens its
+/// terrain definitions and some 5 s later reads one level of every texture in it (),
+/// and its loading waits for each read: in the test flight of 17 Nov the 400 airport textures of each new tile kept it
+/// waiting 0.3-6 s apiece, and the flight stuttered at every tile. Here each tile on the way gets its textures from its
+/// DSF's terrain table () and the warmer fetches that level of each, after everything the
+/// loaded scenery needs, so X-Plane's reads find them done.
+///
+/// Where X-Plane loads: a block of 3 x 4 tiles around the aircraft, the rows of its latitude and one either side, the
+/// columns within 1.5° of its longitude (+46..+48 and +011..+014 at 47.72, 13.05); it moves the block a row or column
+/// some way after the aircraft crosses into the next tile. The tiles of that block along the aircraft's path for
+/// that X-Plane has not opened are the ones readied.
+///
+///
+internal sealed class UpcomingScenery : IDisposable
+{
+ /// How far along its path the aircraft's block of tiles is looked at.
+ public const double LookaheadSeconds = 300;
+ private const double StepSeconds = 30;
+
+ private readonly string _packageSource;
+ private readonly ViewTracker _view;
+ private readonly SceneryLoads _loads;
+ private readonly MipWarmer _warmer;
+ private readonly Lock _gate = new();
+ private readonly HashSet _readied = [];
+ private int _busy;
+ private volatile bool _disposed;
+
+ public UpcomingScenery(string packageSource, ViewTracker view, SceneryLoads loads, MipWarmer warmer)
+ {
+ _packageSource = packageSource;
+ _view = view;
+ _loads = loads;
+ _warmer = warmer;
+ view.Moved += OnMoved;
+ }
+
+ /// The tiles X-Plane keeps loaded with the aircraft at a point.
+ internal static IEnumerable LoadedAround(double lat, double lon)
+ {
+ int row = (int)Math.Floor(lat), firstColumn = (int)Math.Floor(lon - 1.5);
+ for (int r = row - 1; r <= row + 1; r++)
+ for (int c = firstColumn; c <= firstColumn + 3; c++)
+ yield return SceneryTile.At(r, c);
+ }
+
+ /// The tiles X-Plane will load along the path, nearest first; none for a parked or estimated aircraft.
+ internal static List Ahead(CameraReport camera)
+ {
+ if (camera.Inferred || camera.Motion is not { SpeedMps: >= PrefetchPlanner.MovingSpeedMps } motion) return [];
+ var tiles = new List();
+ var now = new HashSet(LoadedAround(camera.Lat, camera.Lon));
+ double track = motion.TrackDeg * Math.PI / 180, metresPerDegLat = 110_574;
+ for (double seconds = StepSeconds; seconds <= LookaheadSeconds; seconds += StepSeconds)
+ {
+ double metres = motion.SpeedMps * seconds;
+ double lat = camera.Lat + metres * Math.Cos(track) / metresPerDegLat;
+ double lon = camera.Lon + metres * Math.Sin(track) / (metresPerDegLat * Math.Max(0.01, Math.Cos(camera.Lat * Math.PI / 180)));
+ foreach (SceneryTile tile in LoadedAround(Math.Clamp(lat, -89.9, 89.9), lon))
+ if (!now.Contains(tile) && !tiles.Contains(tile)) tiles.Add(tile);
+ }
+ return tiles;
+ }
+
+ private void OnMoved(CameraReport camera)
+ {
+ List ahead = Ahead(camera);
+ lock (_gate) ahead.RemoveAll(tile => _readied.Contains(tile) || _loads.Seen(tile));
+ if (ahead.Count == 0 || Interlocked.Exchange(ref _busy, 1) == 1) return;
+ _ = Task.Run(() =>
+ {
+ try
+ {
+ foreach (SceneryTile tile in ahead) Ready(tile);
+ }
+ finally
+ {
+ Volatile.Write(ref _busy, 0);
+ }
+ });
+ }
+
+ /// Queues the textures of one tile's DSF in this package; a tile the package lacks is left alone.
+ internal int Ready(SceneryTile tile)
+ {
+ lock (_gate)
+ if (!_readied.Add(tile)) return 0;
+ string dsf = Path.Join(_packageSource, tile.DsfPath);
+ if (!File.Exists(dsf)) return 0;
+ IReadOnlyList terrain;
+ try
+ {
+ terrain = DsfTerrainTable.Read(dsf);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ Log.Warning($"Could not read the terrain table of {dsf}: {ex.Message}");
+ return 0;
+ }
+
+ var textures = new List();
+ var seen = new HashSet(StringComparer.OrdinalIgnoreCase);
+ foreach (string definition in terrain)
+ if (TerrainDefinitions.TextureOf(Path.GetFileName(definition), out _, out _) is { } name && seen.Add(name.Stem))
+ textures.Add(VirtualPath.Of("textures", name.Stem + ".dds"));
+ if (textures.Count == 0 || _disposed) return 0;
+ int queued = _warmer.PrepareUpcoming(textures);
+ Log.Info($"Scenery tile {tile} is ahead: {textures.Count} textures readied at the level X-Plane reads when it loads the tile");
+ return queued;
+ }
+
+ public void Dispose()
+ {
+ _disposed = true;
+ _view.Moved -= OnMoved;
+ }
+}
diff --git a/src/OrthoStreamXP/Scenery/Streaming/HeldTexture.cs b/src/OrthoStreamXP/Scenery/Streaming/HeldTexture.cs
new file mode 100644
index 0000000..f7d4c39
--- /dev/null
+++ b/src/OrthoStreamXP/Scenery/Streaming/HeldTexture.cs
@@ -0,0 +1,7 @@
+namespace OrthoStreamXP.Scenery;
+
+///
+/// A texture X-Plane holds: the pixels across of the finest level it read (what it takes of the graphics memory), and
+/// whether it is an airport's (ZL18 or finer), whose size a resolution may set apart from the wide areas'.
+///
+internal readonly record struct HeldTexture(int Detail, bool Airport);
diff --git a/src/OrthoStreamXP/Scenery/Streaming/ReadWaitStats.cs b/src/OrthoStreamXP/Scenery/Streaming/ReadWaitStats.cs
index 78bbaab..d1a1440 100644
--- a/src/OrthoStreamXP/Scenery/Streaming/ReadWaitStats.cs
+++ b/src/OrthoStreamXP/Scenery/Streaming/ReadWaitStats.cs
@@ -32,7 +32,10 @@ public void NoteNeeded(bool starting, TimeSpan needed)
if (list.Count < MaxNeededSamples) list.Add(needed.TotalSeconds);
}
- /// The waits at a flight's start and after it. The Far band never waits, so only Near and Middle count.
+ ///
+ /// The waits at a flight's start and after it, for the tuning. Only Near and Middle count: a Far read waits only
+ /// for its low-zoom base tile at a start (a fixed bound, nothing the tuning sets), recorded with starting false.
+ ///
public (long StartWaits, long StartTimedOut, IReadOnlyList StartNeeded, long FlightWaits, long FlightTimedOut, IReadOnlyList FlightNeeded) Snapshot()
{
long waits = Read(_waits, Band.Near) + Read(_waits, Band.Middle);
diff --git a/src/OrthoStreamXP/Scenery/Streaming/StreamedTexture.cs b/src/OrthoStreamXP/Scenery/Streaming/StreamedTexture.cs
index 6978142..c4b6b6e 100644
--- a/src/OrthoStreamXP/Scenery/Streaming/StreamedTexture.cs
+++ b/src/OrthoStreamXP/Scenery/Streaming/StreamedTexture.cs
@@ -40,7 +40,7 @@ public StreamedTexture(VirtualPath path, TextureName name, TexturePlan plan, int
public double Lat { get; }
public double Lon { get; }
public double SizeM { get; }
- /// The first level the low-zoom base covers: one zoom 12 tile for a ZL16 texture.
+ /// The first level the low-zoom base covers: four zoom 13 tiles for a ZL16 texture.
public int BaseMip { get; }
///
diff --git a/src/OrthoStreamXP/Scenery/Streaming/StreamingOptions.cs b/src/OrthoStreamXP/Scenery/Streaming/StreamingOptions.cs
index bc5c9ac..b04f4da 100644
--- a/src/OrthoStreamXP/Scenery/Streaming/StreamingOptions.cs
+++ b/src/OrthoStreamXP/Scenery/Streaming/StreamingOptions.cs
@@ -14,5 +14,10 @@ namespace OrthoStreamXP.Scenery;
/// which never have to wait for an ahead build to finish.
///
/// Builds at once whatever their size: a few dozen already keep every download worker busy.
-internal sealed record StreamingOptions(double NearWaitSeconds, double MaxWaitSeconds, long RamBudgetBytes = 1L << 30,
+///
+/// The texture levels kept in RAM for X-Plane's reads; the least recently read go first, read again from the cache or
+/// made again from the low-zoom base when X-Plane asks. X-Plane reads 95 % of the textures once (test flight of 17 Nov),
+/// so 1 GB of them mostly waited for reads that never came, in memory X-Plane was short of.
+///
+internal sealed record StreamingOptions(double NearWaitSeconds, double MaxWaitSeconds, long RamBudgetBytes = 512L << 20,
long BuildMemoryBytes = 512L << 20, long BuildTiles = TextureStreamer.DefaultBuildTiles, int MaxBuilds = TextureStreamer.DefaultMaxBuilds);
diff --git a/src/OrthoStreamXP/Scenery/Streaming/TextureStreamer.cs b/src/OrthoStreamXP/Scenery/Streaming/TextureStreamer.cs
index 97215b3..da0964b 100644
--- a/src/OrthoStreamXP/Scenery/Streaming/TextureStreamer.cs
+++ b/src/OrthoStreamXP/Scenery/Streaming/TextureStreamer.cs
@@ -7,9 +7,10 @@ namespace OrthoStreamXP.Scenery;
///
/// Serves photo DDS textures the way X-Plane reads them: the header at once, then each read's byte range mapped to
/// mip levels, answered with the best data at that moment. Real data is fetched at exactly the zoom the level
-/// needs (level 4 of a ZL16 texture is one ZL12 tile, not 256 ZL16 tiles). How long a read may wait depends on its
+/// needs (level 3 of a ZL16 texture is four ZL13 tiles, not 256 ZL16 tiles). How long a read may wait depends on its
/// band: next to the aircraft it waits for real imagery (long at the start of a flight, which X-Plane will not
-/// read again while the aircraft is parked), in the middle distance briefly, and far away not at all. A read
+/// read again while the aircraft is parked), in the middle distance briefly, and far away not at all (except, while
+/// a flight starts, a few seconds for the low-zoom base tile when nothing else of the place is at hand). A read
/// that cannot wait gets a stand-in, stretched from the best coarser imagery at hand (the low-zoom base, or one
/// flat colour when there is nothing), and the real data is fetched behind it for X-Plane's next read.
///
@@ -32,6 +33,11 @@ internal sealed class TextureStreamer : IDisposable
{
/// X-Plane wanting level 0 or 1 means the texture is next to the camera.
public const int NearMips = 1;
+ ///
+ /// How long a far read waits for its low-zoom base tile while a flight starts when there is nothing to stretch
+ /// instead (a new cache): a base build is a few tiles and well under a second, so this bounds only a slow connection.
+ ///
+ public const double FarStartWaitSeconds = 10;
private static readonly TimeSpan RetryAfter = TimeSpan.FromSeconds(15);
/// The colour of a level when nothing of the place is at hand: a muted green-brown, like most land from afar.
private static readonly (byte R, byte G, byte B) FlatColor = (96, 102, 80);
@@ -99,10 +105,16 @@ public static long BuildTiles(TextureName name, int zoom)
}
///
- /// The memory a build of a level holds while its tiles arrive: the picture and its resize
- /// and encode buffers, about 1.5 x size² x 3 bytes (1.2 MB at 512 px, 19 MB at 2048 px, 75 MB at 4096).
+ /// The memory a build of a level holds while its tiles arrive and it is encoded, about
+ /// 4.6 x size² bytes (1.2 MB at 512 px, 18 MB at 2048 px, 74 MB at 4096, 295 MB at 8192): the picture (3 bytes a
+ /// pixel), the two pictures its smaller levels take turns in (: a quarter and a
+ /// sixteenth of its pixels) and the BC1 levels it makes (half a byte a pixel, and a third more for the smaller levels).
///
- public static long BuildWeight(int sizePx) => (long)sizePx * sizePx * 9 / 2;
+ public static long BuildWeight(int sizePx)
+ {
+ long pixels = (long)sizePx * sizePx;
+ return pixels * 3 + pixels * 3 * 5 / 16 + DdsLayout.For(sizePx).ChainLength(0);
+ }
public PagingModel Model => _model;
@@ -223,11 +235,14 @@ private ReadAnswer ReadLevels(StreamedTexture t, ReadCursor cursor, long offset,
int target = Math.Max(mip, finest);
if (target < realFrom)
{
+ // A far read while a flight starts with nothing of the place at hand would get one flat colour, and X-Plane
+ // loads the whole area at once and reads few of those textures again: it waits briefly for its base tile.
+ bool flatAtStart = band == Band.Far && _view.Starting && !HasCoarserStored(t);
Task build = StartBuild(t, Math.Min(target, t.BaseMip), band switch
{
Band.Near => FetchPriority.NearRead,
Band.Middle => FetchPriority.ForRead(mip),
- _ => FetchPriority.Background,
+ _ => flatAtStart ? FetchPriority.ForRead(mip) : FetchPriority.Background,
}, byRead: true);
// While a flight starts the aircraft is parked and X-Plane reads none of these textures again for a
// while: a stand-in then stays blurry, so near and middle reads alike may wait near-wait.
@@ -235,7 +250,7 @@ private ReadAnswer ReadLevels(StreamedTexture t, ReadCursor cursor, long offset,
double wait = band switch
{
Band.Near or Band.Middle => starting ? _options.NearWaitSeconds : _options.MaxWaitSeconds,
- _ => 0,
+ _ => flatAtStart ? FarStartWaitSeconds : 0,
};
if (wait > 0 && !build.IsCompleted)
{
@@ -244,7 +259,9 @@ private ReadAnswer ReadLevels(StreamedTexture t, ReadCursor cursor, long offset,
TimeSpan waited = Stopwatch.GetElapsedTime(waitStarted);
waitedMs = waited.TotalMilliseconds;
// A wait for a held-back level says nothing about how long the photos take: the tuning never sees it.
- if (heldBack == HeldBack.No) NoteWait(band!.Value, starting, waitStarted, waited, done, build);
+ // Nor does a far wait: it is for the base tile, not the photos, and its bound is fixed.
+ if (band == Band.Far) _waitStats.Record(Band.Far, starting: false, waited, done);
+ else if (heldBack == HeldBack.No) NoteWait(band!.Value, starting, waitStarted, waited, done, build);
}
}
}
@@ -452,7 +469,7 @@ private static void SetReal(StreamedTexture t, int k, bool fromBase)
if (k == 0 && _roots.CachedFile(t.Path) is { } file)
chain = ReadAfterHeader(file);
else if (t.RealFromBase && _builder.TryStoredRegion(t.Name, t.ZoomFor(k)) is { } region)
- chain = Dds.EncodeChain(_builder.ResizeTo(region.Rgb, region.Size, t.Layout.SizeOf(k)), t.Layout, k, 1);
+ chain = Dds.EncodeChain(_builder.PictureAt(region.Rgb, region.Size, t.Layout.SizeOf(k), t.Name), t.Layout, k, 1);
else if (k > 0 && k < t.Layout.Levels && !t.RealFromBase)
chain = File.ReadAllBytes(ChainPath(t, k));
}
@@ -531,6 +548,18 @@ private void SetChain(StreamedTexture t, int k, byte[] chain)
return null;
}
+ ///
+ /// Whether the low-zoom base holds a coarser tile a stand-in can be stretched from (the zooms
+ /// looks at): a cheap check of the store, nothing is read.
+ ///
+ private bool HasCoarserStored(StreamedTexture t)
+ {
+ for (int zoom = Math.Min(t.ZoomFor(t.BaseMip), _baseZoom) - 1; zoom >= Math.Max(1, t.Name.Zoom - 12); zoom--)
+ if (_builder.StoreHasRegion(t.Name, zoom))
+ return true;
+ return false;
+ }
+
private static void FillFlat(Span output, long fileOffset)
{
byte[] block = Dds.FlatLevel(4, FlatColor.R, FlatColor.G, FlatColor.B);
@@ -642,10 +671,7 @@ private void Save(StreamedTexture t, int k, byte[] chain)
if (k >= t.BaseMip && _builder.Source.Store is not null) return; // made again from the stored tile
if (k == 0)
{
- byte[] file = new byte[t.Layout.Length];
- t.Layout.Header.CopyTo(file);
- chain.CopyTo(file, Dds.HeaderSize);
- AtomicFile.Write(_roots.CachePath(t.Path), file);
+ AtomicFile.Write(_roots.CachePath(t.Path), t.Layout.Header, chain);
}
else if (k < t.BaseMip)
{
@@ -692,35 +718,6 @@ public int RealFrom(StreamedTexture t)
}
}
- ///
- /// Where the texture's picture comes from now, and its version: the photo once it has real data that is not the
- /// low-zoom base's (its stand-ins are stretched from it too), else the base.
- ///
- public (PictureSource Source, DateTime Version) Picture(StreamedTexture t)
- {
- lock (t.Gate)
- {
- Probe(t);
- return (t.RealFrom < t.Layout.Levels && !t.RealFromBase ? PictureSource.Photo : PictureSource.Base, t.Version);
- }
- }
-
- ///
- /// The photo's level nearest pixels (its first real level when that is coarser), decoded to
- /// RGB, or null when the picture is not the photo.
- ///
- public (byte[] Rgb, int Size)? PhotoSample(StreamedTexture t, int size)
- {
- lock (t.Gate)
- {
- Probe(t);
- if (t.RealFrom >= t.Layout.Levels || t.RealFromBase || EnsureChain(t) is not { } chain) return null;
- int mip = Math.Max(t.RealFrom, Math.Clamp((int)Math.Round(Math.Log2((double)t.Layout.Size / size)), 0, t.Layout.Levels - 1));
- int levelSize = t.Layout.SizeOf(mip), start = (int)(t.Layout.Offset(mip) - t.Layout.Offset(t.ChainFrom));
- return (Dds.DecodeLevel(chain.AsSpan(start, t.Layout.LengthOf(mip)), levelSize, levelSize), levelSize);
- }
- }
-
// ---------------------------------------------------------------- RAM
/// Drops the RAM copies of the least recently read textures when over budget; they are on disk or made again.
@@ -759,16 +756,17 @@ private void TrimIfNeeded()
///
/// The detail X-Plane holds of each texture it wanted within : the pixels across of the
- /// finest level it read, which is what that texture takes of the graphics memory.
+ /// finest level it read, which is what that texture takes of the graphics memory, and whether it is an airport's.
///
- public IEnumerable HeldDetail(TimeSpan within)
+ public IEnumerable HeldDetail(TimeSpan within)
{
foreach (StreamedTexture t in _textures.Values)
{
int finest;
long at;
lock (t.Gate) (finest, at) = (t.FinestWanted, t.WantedAt);
- if (finest != StreamedTexture.Unknown && Stopwatch.GetElapsedTime(at) < within) yield return Math.Max(1, t.Layout.Size >> finest);
+ if (finest != StreamedTexture.Unknown && Stopwatch.GetElapsedTime(at) < within)
+ yield return new HeldTexture(Math.Max(1, t.Layout.Size >> finest), TextureResolution.IsAirport(t.Name.Zoom));
}
}
@@ -799,7 +797,7 @@ public string Summary()
: $"; paging k: model {_model.K:F0}{(fit is null ? ", not measured yet" : fitted)}";
return $"Streaming summary: {_textures.Count} textures, {Interlocked.Read(ref _headerChunks)} header chunks; X-Plane's reads of levels: {reads}, " +
$"{RealReads} real{Share(RealReads)}, {Interlocked.Read(ref _standIn)} with stand-ins{Share(Interlocked.Read(ref _standIn))}, " +
- $"{Interlocked.Read(ref _flat)} flat{Share(Interlocked.Read(ref _flat))}; waited: {_waitStats.Describe(Band.Near)}, {_waitStats.Describe(Band.Middle)}; " +
+ $"{Interlocked.Read(ref _flat)} flat{Share(Interlocked.Read(ref _flat))}; waited: {_waitStats.Describe(Band.Near)}, {_waitStats.Describe(Band.Middle)}, {_waitStats.Describe(Band.Far)}; " +
$"builds: {Interlocked.Read(ref _readBuilds)} for reads, {Interlocked.Read(ref _aheadBuilds)} ahead ({Interlocked.Read(ref _warmRequests)} asked), " +
$"{Interlocked.Read(ref _fullBuilds)} at full detail, {Interlocked.Read(ref _failedBuilds)} failed" +
(_nightPause is null ? "" : $", {Interlocked.Read(ref _nightReads)} reads at night kept to the low-zoom base") +
diff --git a/src/OrthoStreamXP/Setup/Cache/CacheAreas.cs b/src/OrthoStreamXP/Setup/Cache/CacheAreas.cs
index 1c74db9..251697f 100644
--- a/src/OrthoStreamXP/Setup/Cache/CacheAreas.cs
+++ b/src/OrthoStreamXP/Setup/Cache/CacheAreas.cs
@@ -54,7 +54,8 @@ public static IReadOnlyList Scan(string cache, AreaUsage? usage, Canc
}
/// The texture plan of a setup folder such as level-1_2048-2048.
- private static TexturePlan PlanOf(string setup) => new(CacheInventory.ParseSetupName(Path.GetFileName(setup))?.Level ?? 0);
+ private static TexturePlan PlanOf(string setup) =>
+ new(CacheInventory.ParseSetupName(Path.GetFileName(setup))?.Level is { } level && TexturePlan.IsKnownLevel(level) ? level : 0);
/// Deletes the areas' files from every setup folder; returns the bytes freed.
public static long Delete(string cache, IReadOnlySet areas, CancellationToken cancel = default)
@@ -159,8 +160,9 @@ public static (IReadOnlyList Removed, long Freed) Trim(string cache, l
}
///
- /// Paints a place from the low-zoom base's tiles (zoom 12: about 11 x 18 tiles a degree at 51°), each decoded at
- /// 1/8 of its size (1/2 when the picture is finer than that); returns whether it had any.
+ /// Paints a place from the low-zoom base's tiles (zoom 13: about 23 x 36 tiles a degree at 51°), each decoded at
+ /// 1/8 of its size (1/2 when the picture is finer than that); returns whether it had any. Where a zoom 13 tile is
+ /// missing, the zoom 12 one of a base made before zoom 13 is painted instead.
///
private static bool PaintBase(byte[] bgra, int width, int height, GeoBounds bounds, string cache, CancellationToken cancel)
{
@@ -175,7 +177,20 @@ double TileY(double lat)
}
// Pixels a tile spans in the picture: at most 32, a 1/8 decode is plenty; more, decode it larger.
float scale = (TileX(bounds.East) - TileX(bounds.West)) * 32 >= width ? 0.125f : 0.5f;
- var tiles = new Dictionary<(int, int), (byte[] Rgb, int Width, int Height)?>();
+ var tiles = new Dictionary<(int, int, int), (byte[] Rgb, int Width, int Height)?>();
+ (byte[] Rgb, int Width, int Height)? Tile(int z, int x, int y)
+ {
+ if (tiles.TryGetValue((z, x, y), out var tile)) return tile;
+ try
+ {
+ tile = store.TryRead(x, y, z) is { } encoded ? Images.Decode(encoded, scale) : null;
+ }
+ catch (InvalidDataException)
+ {
+ tile = null;
+ }
+ return tiles[(z, x, y)] = tile;
+ }
bool any = false;
for (int py = 0; py < height; py++)
{
@@ -184,21 +199,15 @@ double TileY(double lat)
for (int px = 0; px < width; px++)
{
double tx = TileX(bounds.West + (px + 0.5) / width * (bounds.East - bounds.West));
- var key = ((int)tx, (int)ty);
- if (!tiles.TryGetValue(key, out var tile))
+ double x = tx, y = ty;
+ var tile = Tile(zoom, (int)x, (int)y);
+ if (tile is null && zoom > 1)
{
- try
- {
- tile = store.TryRead(key.Item1, key.Item2, zoom) is { } encoded ? Images.Decode(encoded, scale) : null;
- }
- catch (InvalidDataException)
- {
- tile = null;
- }
- tiles[key] = tile;
+ (x, y) = (tx / 2, ty / 2);
+ tile = Tile(zoom - 1, (int)x, (int)y);
}
if (tile is not { } t) continue;
- int sx = Math.Clamp((int)((tx - key.Item1) * t.Width), 0, t.Width - 1), sy = Math.Clamp((int)((ty - key.Item2) * t.Height), 0, t.Height - 1);
+ int sx = Math.Clamp((int)((x - (int)x) * t.Width), 0, t.Width - 1), sy = Math.Clamp((int)((y - (int)y) * t.Height), 0, t.Height - 1);
Set(bgra, (py * width + px) * 4, t.Rgb.AsSpan((sy * t.Width + sx) * 3, 3));
any = true;
}
diff --git a/src/OrthoStreamXP/Setup/Cache/CacheInventory.cs b/src/OrthoStreamXP/Setup/Cache/CacheInventory.cs
index 48e111c..1442137 100644
--- a/src/OrthoStreamXP/Setup/Cache/CacheInventory.cs
+++ b/src/OrthoStreamXP/Setup/Cache/CacheInventory.cs
@@ -24,7 +24,16 @@ internal sealed record CacheEntry(string Name, string Path, CacheEntryKind Kind,
/// Texture size of the ZL16 areas, in pixels.
/// Texture size of the ZL18 (airport) areas, in pixels.
-internal sealed record SetupName(int Level, int Zl16Size, int Zl18Size);
+internal sealed record SetupName(int Level, int Zl16Size, int Zl18Size)
+{
+ /// The resolution its textures were built at, from their sizes; null for sizes none gives.
+ public Textures.TextureResolution? Resolution => !Textures.TexturePlan.IsKnownLevel(Level) ? null : Textures.TextureResolution.All.FirstOrDefault(r =>
+ new Textures.TexturePlan(Level) { Resolution = r } is var plan && plan.SizeFor(16) == Zl16Size && plan.SizeFor(18) == Zl18Size);
+
+ /// Its preset's name, and a resolution below Full ("Ultra, Medium resolution"); null for a level no preset has.
+ public string? PresetTitle => QualityPreset.ForLevel(Level) is not { } preset ? null
+ : Resolution is { IsFull: false } resolution ? $"{preset.Name}, {resolution.Label} resolution" : preset.Name;
+}
/// What the cache folder holds: one entry per setup, the logs and anything else.
internal static partial class CacheInventory
diff --git a/src/OrthoStreamXP/Setup/Installation/LegacyNames.cs b/src/OrthoStreamXP/Setup/Installation/LegacyNames.cs
index cb7ac81..4c714d0 100644
--- a/src/OrthoStreamXP/Setup/Installation/LegacyNames.cs
+++ b/src/OrthoStreamXP/Setup/Installation/LegacyNames.cs
@@ -21,7 +21,7 @@ internal static class LegacyNames
private static readonly string[] SettingsCompanions = [".ini", ".tuned.json", ".connection.json"];
private static readonly string[] CacheFolders = ["logs", "base", "landcover"];
/// The files of the history that sessions left in the cache's logs folder.
- private static readonly string[] HistoryFiles = ["flight-report.json", "flight-review.json", "graphics-memory.json", "colour-match.json", "sim-date.txt"];
+ private static readonly string[] HistoryFiles = ["flight-report.json", "flight-review.json", "graphics-memory.json", "sim-date.txt"];
/// Moves the settings files from (under either name) to and beside it.
public static void MoveSettings(string fromFolder, string settingsPath)
diff --git a/src/OrthoStreamXP/Setup/Settings/QualityPreset.cs b/src/OrthoStreamXP/Setup/Settings/QualityPreset.cs
index 8bb4648..f6d31e4 100644
--- a/src/OrthoStreamXP/Setup/Settings/QualityPreset.cs
+++ b/src/OrthoStreamXP/Setup/Settings/QualityPreset.cs
@@ -13,48 +13,93 @@ internal sealed record QualityPreset(string Name, int Level, string Summary, str
IReadOnlyDictionary Settings)
{
public static readonly QualityPreset Balanced = new("Balanced", -2,
- "1024 px textures from zoom 15-16 imagery: light on graphics memory and the connection, fine from higher up.",
+ "2048 px textures from zoom 15 imagery, 1024 px from zoom 16 near airports: light on graphics memory and the connection, fine from higher up.",
"High flying, a slower connection or little graphics memory", "about 3 min",
Values(buildWorkers: 16, fileSystemThreads: 64, provisionalLod: 0, provisionalWait: null, radiusKm: 6, textures: 16, buildMemoryMb: 512, lookahead: 180));
public static readonly QualityPreset Sharp = new("Sharp", -1,
- "2048 px textures from zoom 16-17 imagery: twice as sharp as Balanced.",
+ "4096 px textures from zoom 16 imagery, 2048 px from zoom 17 near airports: twice as sharp as Balanced.",
"Everyday flying, approaches included", "about 3 min",
Values(buildWorkers: 8, fileSystemThreads: 96, provisionalLod: 2, provisionalWait: 5, radiusKm: 5, textures: 8, buildMemoryMb: 512));
public static readonly QualityPreset Ultra = new("Ultra", 0,
- "4096 px textures from zoom 17-18 imagery: twice as sharp as Sharp.",
+ "8192 px textures from zoom 17 imagery, 4096 px from zoom 18 near airports: twice as sharp as Sharp.",
"Low flight and GA, with plenty of graphics memory", "about 3 min",
Values(buildWorkers: 8, fileSystemThreads: 96, provisionalLod: 3, provisionalWait: 3, radiusKm: 4, textures: 6, buildMemoryMb: 1024));
- // Level +1: ZL18 airports at zoom 19, ZL16 areas at zoom 17 (as Ultra), as 4096 px textures. The finer, newer imagery
+ // Level +1: ZL18 airports at zoom 19 as 8192 px textures, ZL16 areas at zoom 17 as Ultra's. The finer, newer imagery
// of zoom 19 often avoids the clouds and other artifacts of the coarser ones. A ZL18 texture downloads 1024 tiles,
// four times Ultra's; a ZL16 texture the same 1024 as Ultra's.
public static readonly QualityPreset Extra = new("Extra", 1,
- "4096 px textures like Ultra's, with the finest imagery (zoom 19) near airports, which often avoids clouds and other artifacts: four times Ultra's downloads there.",
+ "8192 px textures everywhere: Ultra's, and the finest imagery (zoom 19) near airports, twice as sharp as Ultra's there and often without its clouds and other artifacts: four times Ultra's downloads there.",
"Low and slow flight and screenshots, on a fast connection", "about 4 min, then sharp next to the aircraft",
Values(buildWorkers: 8, fileSystemThreads: 96, provisionalLod: 3, provisionalWait: 3, radiusKm: 4, textures: 6, buildMemoryMb: 1024, lookahead: 90));
// Extra near the ground, Sharp from 5,000 ft and Balanced from 25,000 ft above it: Extra's level and cache, with the
// detail held back high up (dynamic-quality). Measured on a day flight: full-detail textures were 82 % of the
// downloads at every height, and Sharp's detail above 5,000 ft would have saved about half of the climb and cruise.
- public static readonly QualityPreset Dynamic = new("Dynamic", Extra.Level,
+ public static readonly QualityPreset Dynamic = DynamicFrom(Extra,
"Extra near the ground, Sharp from 5,000 ft and Balanced from 25,000 ft above it: full detail where it can be seen, about half the downloads in a climb and cruise.",
- "Climbs, cruise and approaches in one flight, on a fast connection", "about 4 min, then sharp next to the aircraft",
- new Dictionary(Extra.Settings) { [DynamicQualityKey] = "on" });
+ "Climbs, cruise and approaches in one flight, on a fast connection");
- /// The presets by their level change: Dynamic is Extra's level (its cache, tuning and texture size), so it is not among them.
+ // Ultra near the ground: its ZL16 areas are Extra's (zoom 17), the airports zoom 18 instead of 19, so a quarter of
+ // Extra's downloads there; the same steps above.
+ public static readonly QualityPreset DynamicUltra = DynamicFrom(Ultra,
+ "Ultra near the ground, Sharp from 5,000 ft and Balanced from 25,000 ft above it: Ultra's detail where it can be seen, far fewer downloads in a climb and cruise.",
+ "Climbs, cruise and approaches in one flight, on a good connection");
+
+ // Sharp near the ground: Sharp's own step is no saving, so only Balanced's is left, from 25,000 ft.
+ public static readonly QualityPreset DynamicSharp = DynamicFrom(Sharp,
+ "Sharp near the ground and through the climb, Balanced from 25,000 ft above it: fewer downloads at airliner heights.",
+ "Long flights at airliner heights, on an everyday connection");
+
+ /// The presets by their level change: Dynamic is its base's level (its cache, tuning and texture size), so it is not among them.
public static IReadOnlyList All { get; } = [Balanced, Sharp, Ultra, Extra];
- /// The presets offered in the window: every level, and Dynamic.
+ /// The presets offered in the window: every level, and Dynamic (one card; its base is chosen on it).
public static IReadOnlyList Choices { get; } = [.. All, Dynamic];
- /// The preset with this level change, if one has it (Extra for Dynamic's level).
+ /// Dynamic from each base it can have, the sharpest first: Extra (the default), Ultra and Sharp.
+ public static IReadOnlyList DynamicChoices { get; } = [Dynamic, DynamicUltra, DynamicSharp];
+
+ /// Every preset the window can be at: every level, and Dynamic from each base.
+ public static IReadOnlyList Offered { get; } = [.. All, .. DynamicChoices];
+
+ /// For Dynamic, the preset it is near the ground (its level, settings and cache); null for the others.
+ public QualityPreset? DynamicBase { get; private init; }
+
+ public bool IsDynamic => DynamicBase is not null;
+
+ /// Its name in the window's words: "Ultra", or "Dynamic from Ultra".
+ public string Title => DynamicBase is { } near ? $"{Name} from {near.Name}" : Name;
+
+ ///
+ /// Dynamic's steps at the default heights, lowest first: the presets it holds the detail to higher up (Sharp from
+ /// 5,000 ft, Balanced from 25,000 ft), those coarser than its base; empty for the other presets.
+ ///
+ public IReadOnlyList DynamicSteps =>
+ IsDynamic ? new Scenery.DynamicOptions().TiersBelow(new TexturePlan(Level)) : [];
+
+ /// The preset with this level change, if one has it (Extra for Dynamic's default level).
public static QualityPreset? ForLevel(int? level) => All.FirstOrDefault(p => p.Level == level);
- /// The preset the settings are at: Dynamic when dynamic-quality is on at its level, otherwise the level's.
+ ///
+ /// The preset the settings are at: Dynamic from the level's preset when dynamic-quality is on at a level Dynamic
+ /// can have, otherwise the level's.
+ ///
public static QualityPreset? Current(int? level, bool dynamicQuality) =>
- dynamicQuality && level == Dynamic.Level ? Dynamic : ForLevel(level);
+ (dynamicQuality ? DynamicChoices.FirstOrDefault(p => p.Level == level) : null) ?? ForLevel(level);
+
+ /// Dynamic from , or null when Dynamic cannot have that base.
+ public static QualityPreset? DynamicOn(QualityPreset? near) => DynamicChoices.FirstOrDefault(p => p.DynamicBase == near);
+
+ ///
+ /// The Dynamic the settings have: the current one when the settings are at Dynamic, otherwise the base kept in
+ /// dynamic-base (Extra when there is none).
+ ///
+ public static QualityPreset DynamicIn(SettingsDocument settings) =>
+ Current(settings.GetInt("level-change"), settings.GetBool(DynamicQualityKey) == true) is { IsDynamic: true } current ? current
+ : DynamicOn(All.FirstOrDefault(p => string.Equals(p.Name, settings.Get(DynamicBaseKey)?.Trim(), StringComparison.OrdinalIgnoreCase))) ?? Dynamic;
public string? Get(string name) => Settings.TryGetValue(name, out string? value) ? value : null;
@@ -64,24 +109,68 @@ internal sealed record QualityPreset(string Name, int Level, string Summary, str
/// Zoom of the ZL18 textures at this preset (the ones the packages have near airports).
public int Zl18Zoom => new TexturePlan(Level).FetchZoom(18);
- /// Texture size in the ZL16 areas (the size follows the level).
- public int Size => new TexturePlan(Level).SizeFor(16);
+ /// Texture size in the ZL16 areas at full resolution (the size follows the level).
+ public int Size => SizeAt(TextureResolution.Full);
+
+ /// Texture size in the ZL16 areas at .
+ public int SizeAt(TextureResolution resolution) => PlanAt(resolution).SizeFor(16);
+
+ /// The textures this preset builds at .
+ public TexturePlan PlanAt(TextureResolution resolution) => new(Level) { Resolution = resolution };
- /// Ground size of one texture pixel in ZL16 areas at mid latitudes (45°): a ZL16 texture is about 6.9 km across.
- public double MetresPerPixel => 2 * Math.PI * 6_378_137.0 * Math.Cos(Math.PI / 4) * Tiles.TextureSpan / (1 << 16) / Size;
+ /// Ground size of one texture pixel in ZL16 areas at mid latitudes (45°) at full resolution: a ZL16 texture is about 6.9 km across.
+ public double MetresPerPixel => MetresPerPixelAt(TextureResolution.Full);
+
+ public double MetresPerPixelAt(TextureResolution resolution) =>
+ 2 * Math.PI * 6_378_137.0 * Math.Cos(Math.PI / 4) * Tiles.TextureSpan / (1 << 16) / SizeAt(resolution);
+
+ /// The setting of this preset's resolution (resolution-ultra = full, medium or low), kept for each preset.
+ public string ResolutionKey => ResolutionPrefix + Name.ToLowerInvariant();
+
+ public const string ResolutionPrefix = "resolution-";
+
+ /// This preset's resolution in the settings: Full when not set, or not one of the names.
+ public TextureResolution ResolutionIn(SettingsDocument settings) => TextureResolution.Parse(settings.Get(ResolutionKey)) ?? TextureResolution.Full;
+
+ ///
+ /// The textures the settings build: the level, at the current preset's resolution. A level no preset has (an older or
+ /// hand-edited file, which the mount refuses) shows as Ultra's, the default.
+ ///
+ public static TexturePlan PlanIn(SettingsDocument settings)
+ {
+ int level = ForLevel(settings.GetInt("level-change") ?? 0)?.Level ?? Ultra.Level;
+ TextureResolution resolution = Current(level, settings.GetBool(DynamicQualityKey) == true)?.ResolutionIn(settings) ?? TextureResolution.Full;
+ return new TexturePlan(level) { Resolution = resolution };
+ }
/// Writes the preset's values (and its level) into the settings.
public void ApplyTo(SettingsDocument settings)
{
settings.Set("level-change", Level);
+ settings.SetComment("level-change", LevelCommentPrefix, LevelComment);
// Dynamic quality is Dynamic's alone: any other preset turns it off (an older settings file has no line for it).
if (!Settings.ContainsKey(DynamicQualityKey)) settings.Set(DynamicQualityKey, "off");
foreach (var (name, value) in Settings) settings.Set(name, value);
+ if (DynamicBase is { } near) settings.Set(DynamicBaseKey, near.Name.ToLowerInvariant());
}
- /// The setting that makes Extra's level .
+ /// The comment the window keeps above level-change, naming the preset: "# quality preset: Ultra; ...".
+ public string LevelComment =>
+ FormattableString.Invariant($"{LevelCommentPrefix}{Title}; the level also sets the texture size ({Size} px)");
+
+ /// How starts: only a comment that starts so is the window's to rewrite.
+ public const string LevelCommentPrefix = "# quality preset: ";
+
+ /// The setting that makes Extra's, Ultra's or Sharp's level .
public const string DynamicQualityKey = "dynamic-quality";
+ /// The base Dynamic is kept at in the window (extra, ultra or sharp) while another preset is chosen; level-change sets it.
+ public const string DynamicBaseKey = "dynamic-base";
+
+ private static QualityPreset DynamicFrom(QualityPreset near, string summary, string bestFor) =>
+ new("Dynamic", near.Level, summary, bestFor, near.FirstVisit,
+ new Dictionary(near.Settings) { [DynamicQualityKey] = "on" }) { DynamicBase = near };
+
private static Dictionary Values(int buildWorkers, int fileSystemThreads, int provisionalLod,
double? provisionalWait, double radiusKm, int textures, int buildMemoryMb, double lookahead = MountSettings.DefaultLookaheadSeconds) => new()
{
diff --git a/src/OrthoStreamXP/Setup/Settings/SettingsDocument.cs b/src/OrthoStreamXP/Setup/Settings/SettingsDocument.cs
index 35343d4..e772fa0 100644
--- a/src/OrthoStreamXP/Setup/Settings/SettingsDocument.cs
+++ b/src/OrthoStreamXP/Setup/Settings/SettingsDocument.cs
@@ -83,6 +83,21 @@ public void Set(string name, string? value)
_lines.Add($"{name,-18} = {value}");
}
+ ///
+ /// Rewrites the comment line just above a setting (the last line that sets it) when that comment starts with
+ /// : one the window wrote, which would otherwise go stale as the value changes. Any other
+ /// line there - a person's own comment, another setting - stays as it is.
+ ///
+ public void SetComment(string name, string prefix, string comment)
+ {
+ for (int i = _lines.Count - 1; i > 0; i--)
+ {
+ if (Split(_lines[i]) is not { } setting || setting.Name != name) continue;
+ if (_lines[i - 1].TrimStart().StartsWith(prefix, StringComparison.Ordinal)) _lines[i - 1] = comment;
+ return;
+ }
+ }
+
public void Set(string name, int value) => Set(name, value.ToString(CultureInfo.InvariantCulture));
public void Set(string name, double value) => Set(name, value.ToString("0.###", CultureInfo.InvariantCulture));
@@ -129,11 +144,16 @@ public static SettingsDocument CreateNew(string path, string xplane, string base
.AppendLine("# --- Pictures ---------------------------------------------------------------------")
.AppendLine("# bing, esri, or several tried in order for each tile: a tile the first lacks comes from the next")
.AppendLine("texture-provider = bing,esri")
- .AppendLine(CultureInfo.InvariantCulture, $"# quality preset: {preset.Name}; the level also sets the texture size ({preset.Size} px)")
+ .AppendLine(preset.LevelComment)
.AppendLine(CultureInfo.InvariantCulture, $"level-change = {preset.Level.ToString(CultureInfo.InvariantCulture)}")
.AppendLine("# Dynamic quality (the Dynamic preset): less detail high above the ground, where it cannot be seen (on or off)")
.AppendLine(CultureInfo.InvariantCulture, $"{QualityPreset.DynamicQualityKey} = {preset.Get(QualityPreset.DynamicQualityKey) ?? "off"}")
- .AppendLine()
+ .AppendLine("# the preset Dynamic is near the ground, for the window: extra, ultra or sharp (level-change sets it while Dynamic is chosen)")
+ .AppendLine(CultureInfo.InvariantCulture, $"{QualityPreset.DynamicBaseKey,-18} = {(preset.DynamicBase ?? QualityPreset.Extra).Name.ToLowerInvariant()}")
+ .AppendLine("# each preset's resolution, from the same imagery: full; medium halves the textures of most areas, not the airports'; low halves them all");
+ foreach (QualityPreset choice in QualityPreset.Choices)
+ text.AppendLine(CultureInfo.InvariantCulture, $"{choice.ResolutionKey,-18} = {Textures.TextureResolution.Full.Value}");
+ text.AppendLine()
.AppendLine("# --- Speed ------------------------------------------------------------------------")
.AppendLine(CultureInfo.InvariantCulture, $"dds-build-workers = {preset.Get("dds-build-workers")}")
.AppendLine("download-workers = 128")
diff --git a/src/OrthoStreamXP/Textures/BuildBufferPool.cs b/src/OrthoStreamXP/Textures/BuildBufferPool.cs
new file mode 100644
index 0000000..a81cd98
--- /dev/null
+++ b/src/OrthoStreamXP/Textures/BuildBufferPool.cs
@@ -0,0 +1,91 @@
+namespace OrthoStreamXP.Textures;
+
+///
+/// The large pictures a build works in (the stitched texture and its mip-level buffers), reused from build to build at
+/// their exact length, with all of them, rented or kept, held within . Unlike
+/// , nothing is rounded up to a power of two (a 192 MB picture took a
+/// 256 MB array there), and it keeps no more than its capacity however many builds ran at once: a picture that would
+/// not fit is left to the garbage collector, and one not asked for again within is let go.
+///
+internal sealed class BuildBufferPool(long capacityBytes, TimeProvider? time = null)
+{
+ /// The capacity when none is given: the default build memory (build-memory).
+ public const long DefaultCapacityBytes = 512L << 20;
+
+ /// How long a kept picture waits to be asked for again.
+ public const long IdleMilliseconds = 60_000;
+
+ private readonly TimeProvider _time = time ?? TimeProvider.System;
+ private readonly Lock _lock = new();
+ // Kept pictures in the order they came back: the oldest are let go first.
+ private readonly List<(byte[] Array, long ReturnedAt)> _kept = [];
+ private long _keptBytes, _rentedBytes;
+
+ public long CapacityBytes { get; } = capacityBytes > 0 ? capacityBytes : throw new ArgumentOutOfRangeException(nameof(capacityBytes));
+
+ /// Bytes of the pictures kept for the next builds.
+ public long KeptBytes
+ {
+ get { lock (_lock) return _keptBytes; }
+ }
+
+ /// Bytes of the pictures builds hold now.
+ public long RentedBytes
+ {
+ get { lock (_lock) return _rentedBytes; }
+ }
+
+ ///
+ /// An array of exactly bytes, with whatever an earlier build left in it; give it back with
+ /// .
+ ///
+ public byte[] Rent(int length)
+ {
+ ArgumentOutOfRangeException.ThrowIfNegativeOrZero(length);
+ lock (_lock)
+ {
+ LetIdleGo();
+ _rentedBytes += length;
+ for (int i = _kept.Count - 1; i >= 0; i--)
+ {
+ if (_kept[i].Array.Length != length) continue;
+ byte[] array = _kept[i].Array;
+ _kept.RemoveAt(i);
+ _keptBytes -= length;
+ return array;
+ }
+ // A new one: the kept pictures of other sizes make room for it, oldest first.
+ while (_kept.Count > 0 && _keptBytes + _rentedBytes > CapacityBytes)
+ LetGo(0);
+ }
+ // Every byte is written by the build before it is read.
+ return GC.AllocateUninitializedArray(length);
+ }
+
+ /// Gives back an array from ; it is kept when it fits beside what builds hold now.
+ public void Return(byte[] array)
+ {
+ ArgumentNullException.ThrowIfNull(array);
+ lock (_lock)
+ {
+ _rentedBytes -= array.Length;
+ LetIdleGo();
+ if (_keptBytes + _rentedBytes + array.Length > CapacityBytes) return;
+ _kept.Add((array, _time.GetTimestamp()));
+ _keptBytes += array.Length;
+ }
+ }
+
+ private void LetIdleGo()
+ {
+ long now = _time.GetTimestamp();
+ while (_kept.Count > 0 && _time.GetElapsedTime(_kept[0].ReturnedAt, now).TotalMilliseconds > IdleMilliseconds)
+ LetGo(0);
+ }
+
+ private void LetGo(int index)
+ {
+ _keptBytes -= _kept[index].Array.Length;
+ _kept.RemoveAt(index);
+ }
+}
diff --git a/src/OrthoStreamXP/Textures/Colour/ColourMatch.cs b/src/OrthoStreamXP/Textures/Colour/ColourMatch.cs
deleted file mode 100644
index d34da30..0000000
--- a/src/OrthoStreamXP/Textures/Colour/ColourMatch.cs
+++ /dev/null
@@ -1,226 +0,0 @@
-using System.Buffers.Binary;
-
-namespace OrthoStreamXP.Textures;
-
-///
-/// Evens out the colours of photos from different captures. Imagery is a patchwork: next to each other, one capture can
-/// be grey and hazy, another bright and green, and where they meet the scenery shows patches. The low-zoom base (one
-/// satellite mosaic, already downloaded for stand-ins) is even across a whole region, so it is the reference: how a photo
-/// relates to the base is measured place by place (cells about 1.5 km across, a zoom 14 tile, coarser than fields so
-/// they keep their own colours), and each place is moved towards the relation usual in its area. That is brightness and
-/// tint per channel only: a capture that recorded almost no colour does not get colour it never had.
-///
-internal static class ColourMatch
-{
- /// The usual relation of a photo to the base where nothing is known of its area yet (Bing around Wrocław, log per channel).
- public static readonly ColourGain DefaultTarget = new(-0.30f, -0.20f, -0.21f);
-
- /// The largest change, either way (log): about x0.6 to x1.65, so a real difference is never over-corrected.
- public const float MaxChange = 0.5f;
-
- ///
- /// How far a usual capture's cells differ from the base by what grows there on the two days (log, about 13 %):
- /// differences within it are left alone, and only the part beyond it is corrected.
- ///
- public const float Usual = 0.12f;
-
- /// Pixels per cell side in the pictures compared.
- public const int SamplePerCell = 32;
-
- /// Cells across a texture: one per zoom 14 tile (4 on a ZL16 texture, 1 on a ZL18), 1 to 16.
- public static int CellsAcross(TextureName name) =>
- Math.Clamp(name.Zoom <= 14 ? Tiles.TextureSpan << Math.Min(14 - name.Zoom, 4) : Tiles.TextureSpan >> Math.Min(name.Zoom - 14, 4), 1, 16);
-
- ///
- /// How the photo relates to the base in each cell (row by row): the difference of their mean log colours per channel,
- /// or null where too little of either is usable (cloud, deep shadow, glare). Both pictures are
- /// pixels square, RGB.
- ///
- public static ColourGain?[] Relation(byte[] photo, byte[] reference, int size, int cells)
- {
- var result = new ColourGain?[cells * cells];
- int cell = size / cells;
- for (int cy = 0; cy < cells; cy++)
- for (int cx = 0; cx < cells; cx++)
- {
- if (MeanLog(photo, size, cx * cell, cy * cell, cell) is not { } p || MeanLog(reference, size, cx * cell, cy * cell, cell) is not { } b) continue;
- result[cy * cells + cx] = new ColourGain(p.R - b.R, p.G - b.G, p.B - b.B);
- }
- return result;
- }
-
- /// The mean log colour of a square of a picture, over its pixels neither near black nor near white; null when under a quarter are.
- private static ColourGain? MeanLog(byte[] rgb, int size, int left, int top, int side)
- {
- double r = 0, g = 0, b = 0;
- int n = 0;
- for (int y = top; y < top + side; y++)
- for (int x = left; x < left + side; x++)
- {
- int i = (y * size + x) * 3;
- int luminance = (rgb[i] + rgb[i + 1] + rgb[i + 2]) / 3;
- if (luminance is < 16 or > 235) continue;
- r += Log[rgb[i]];
- g += Log[rgb[i + 1]];
- b += Log[rgb[i + 2]];
- n++;
- }
- return n * 4 < side * side ? null : new ColourGain((float)(r / n), (float)(g / n), (float)(b / n));
- }
-
- /// log(value + 8): the offset keeps dark pixels from weighing too much.
- private static readonly float[] Log = [.. Enumerable.Range(0, 256).Select(v => (float)Math.Log(v + 8))];
-}
-
-/// A change of colour per channel, as the log of a factor (0: none).
-internal readonly record struct ColourGain(float R, float G, float B)
-{
- public static readonly ColourGain None = new(0, 0, 0);
-
- public ColourGain Clamped(float limit) => new(Math.Clamp(R, -limit, limit), Math.Clamp(G, -limit, limit), Math.Clamp(B, -limit, limit));
-
- public static ColourGain operator -(ColourGain a, ColourGain b) => new(a.R - b.R, a.G - b.G, a.B - b.B);
-
- /// The change made stronger or weaker: 0.5 is half of it (the square root of the factor).
- public static ColourGain operator *(ColourGain a, float strength) => new(a.R * strength, a.G * strength, a.B * strength);
-
- public override string ToString() => FormattableString.Invariant($"x{Math.Exp(R):0.00} x{Math.Exp(G):0.00} x{Math.Exp(B):0.00}");
-}
-
-///
-/// One texture's colour correction: a factor per channel at the centre of each cell, changing smoothly between them
-/// (bilinear, held at the texture's edges). It is applied to the BC1 blocks of the DDS as X-Plane reads it, like the
-/// seasons and before them: each block's two colours are scaled, which scales the block. The cache keeps the imagery
-/// as downloaded.
-///
-internal sealed class TextureColour
-{
- /// Places across and down that each get one factor: 128 px apart on a 4096 px texture.
- private const int Steps = 32;
- /// A factor is rounded to 1/64 of its log (1.6 %), from - to +.
- private const int Quanta = 64;
- private static readonly int Range = (int)Math.Ceiling(ColourMatch.MaxChange * Quanta);
- /// 5-bit and 6-bit channel values scaled by each rounded factor.
- private static readonly byte[][] Scale5 = Scales(31), Scale6 = Scales(63);
-
- private readonly int _cells;
- private readonly ColourGain[] _gains;
-
- private TextureColour(int cells, ColourGain[] gains)
- {
- _cells = cells;
- _gains = gains;
- }
-
- /// The correction at each cell's centre (row by row), each within .
- public IReadOnlyList Gains => _gains;
-
- /// The same change everywhere; null when it changes nothing.
- public static TextureColour? Uniform(ColourGain gain)
- {
- gain = gain.Clamped(ColourMatch.MaxChange);
- return Index(gain.R) == 0 && Index(gain.G) == 0 && Index(gain.B) == 0 ? null : new TextureColour(1, [gain]);
- }
-
- ///
- /// The correction that moves each cell's relation to the base () to
- /// ; null when it changes nothing or no cell has a relation.
- ///
- /// The base was photographed on another day, so a single cell differs from it by its crops as well (a field green
- /// in one, brown in the other): each cell takes the median of the cells around it, which keeps a capture's edge
- /// sharp but drops an odd cell, and a difference within is left alone. So the
- /// countryside of a usual capture is not touched, and textures next to each other are not changed into patches.
- ///
- ///
- /// How much of the correction is made, 0 to 1.
- public static TextureColour? Matching(ColourGain?[] relation, int cells, ColourGain target, float strength = 1)
- {
- if (!relation.Any(r => r is not null)) return null;
- var gains = new ColourGain[cells * cells];
- bool any = false;
- for (int cy = 0; cy < cells; cy++)
- for (int cx = 0; cx < cells; cx++)
- {
- List around = [];
- for (int y = Math.Max(0, cy - 1); y <= Math.Min(cells - 1, cy + 1); y++)
- for (int x = Math.Max(0, cx - 1); x <= Math.Min(cells - 1, cx + 1); x++)
- if (relation[y * cells + x] is { } r) around.Add(r);
- if (around.Count == 0) continue;
- var median = new ColourGain(Median(around, g => g.R), Median(around, g => g.G), Median(around, g => g.B));
- ColourGain change = Beyond(target - median, ColourMatch.Usual).Clamped(ColourMatch.MaxChange) * strength;
- gains[cy * cells + cx] = change;
- any |= Index(change.R) != 0 || Index(change.G) != 0 || Index(change.B) != 0;
- }
- return any ? new TextureColour(cells, gains) : null;
- }
-
- /// The part of a change beyond (its largest channel shrunk by it, the others in proportion).
- private static ColourGain Beyond(ColourGain change, float usual)
- {
- float largest = Math.Max(Math.Abs(change.R), Math.Max(Math.Abs(change.G), Math.Abs(change.B)));
- if (largest <= usual) return ColourGain.None;
- float keep = (largest - usual) / largest;
- return new ColourGain(change.R * keep, change.G * keep, change.B * keep);
- }
-
- private static float Median(List values, Func channel)
- {
- float[] sorted = [.. values.Select(channel).Order()];
- return sorted.Length % 2 == 1 ? sorted[sorted.Length / 2] : (sorted[sorted.Length / 2 - 1] + sorted[sorted.Length / 2]) / 2;
- }
-
- ///
- /// Changes the whole colour blocks in , which holds the bytes of a square DDS of
- /// pixels from ; blocks cut by either end stay as they are.
- ///
- public void Apply(Span data, long fileOffset, int blockBytes, int size)
- {
- // The factor of each place in a row of places, worked out once per row.
- Span row = stackalloc int[Steps];
- Span done = stackalloc bool[Steps];
- var blocks = new DdsBlocks(fileOffset, data.Length, blockBytes, size, Steps);
- while (blocks.MoveNext())
- {
- if (blocks.NewRow) done.Clear();
- int cx = blocks.PlaceX;
- if (!done[cx])
- {
- ColourGain g = At((cx + 0.5) / Steps, (blocks.PlaceY + 0.5) / Steps);
- row[cx] = Pack(Index(g.R), Index(g.G), Index(g.B));
- done[cx] = true;
- }
- int packed = row[cx];
- if (packed == Pack(0, 0, 0)) continue;
- Span block = data.Slice(blocks.At, 8);
- ushort c0 = BinaryPrimitives.ReadUInt16LittleEndian(block), c1 = BinaryPrimitives.ReadUInt16LittleEndian(block[2..]);
- if (blockBytes == 8 && c0 <= c1) continue; // three colours and transparent: left as made
- ColourTable.WriteColors(block, blockBytes, Scaled(c0, packed), Scaled(c1, packed));
- }
- }
-
- /// The correction at a place in the texture (0-1 across and down), between the four nearest cell centres.
- private ColourGain At(double u, double v)
- {
- if (_cells == 1) return _gains[0];
- double fx = Math.Clamp(u * _cells - 0.5, 0, _cells - 1), fy = Math.Clamp(v * _cells - 0.5, 0, _cells - 1);
- int x0 = (int)fx, y0 = (int)fy, x1 = Math.Min(x0 + 1, _cells - 1), y1 = Math.Min(y0 + 1, _cells - 1);
- float tx = (float)(fx - x0), ty = (float)(fy - y0);
- ColourGain a = _gains[y0 * _cells + x0], b = _gains[y0 * _cells + x1], c = _gains[y1 * _cells + x0], d = _gains[y1 * _cells + x1];
- float Mix(float pa, float pb, float pc, float pd) => (pa * (1 - tx) + pb * tx) * (1 - ty) + (pc * (1 - tx) + pd * tx) * ty;
- return new ColourGain(Mix(a.R, b.R, c.R, d.R), Mix(a.G, b.G, c.G, d.G), Mix(a.B, b.B, c.B, d.B));
- }
-
- private static int Index(float gain) => Math.Clamp((int)Math.Round(gain * Quanta), -Range, Range);
-
- private static int Pack(int r, int g, int b) => ((r + Range) << 16) | ((g + Range) << 8) | (b + Range);
-
- private static ushort Scaled(ushort c, int packed)
- {
- int r = Scale5[(packed >> 16) & 0xFF][(c >> 11) & 31], g = Scale6[(packed >> 8) & 0xFF][(c >> 5) & 63], b = Scale5[packed & 0xFF][c & 31];
- return (ushort)((r << 11) | (g << 5) | b);
- }
-
- private static byte[][] Scales(int max) =>
- [.. Enumerable.Range(-Range, 2 * Range + 1).Select(i => Enumerable.Range(0, max + 1)
- .Select(v => (byte)Math.Clamp((int)Math.Round(v * Math.Exp((double)i / Quanta)), 0, max)).ToArray())];
-}
diff --git a/src/OrthoStreamXP/Textures/Colour/ColourTable.cs b/src/OrthoStreamXP/Textures/Colour/ColourTable.cs
index 8ad7c36..263517e 100644
--- a/src/OrthoStreamXP/Textures/Colour/ColourTable.cs
+++ b/src/OrthoStreamXP/Textures/Colour/ColourTable.cs
@@ -3,8 +3,8 @@
namespace OrthoStreamXP.Textures;
///
-/// Recolouring of BC1 colour blocks by a lookup table over the 65,536 RGB565 colours, as X-Plane reads a DDS: the seasons,
-/// the exposure and the colour matching all change a block by its two colours, which changes every pixel of it.
+/// Recolouring of BC1 colour blocks by a lookup table over the 65,536 RGB565 colours, as X-Plane reads a DDS: the seasons
+/// and the exposure both change a block by its two colours, which changes every pixel of it.
///
internal static class ColourTable
{
diff --git a/src/OrthoStreamXP/Textures/Colour/Contrast.cs b/src/OrthoStreamXP/Textures/Colour/Contrast.cs
new file mode 100644
index 0000000..164d7ff
--- /dev/null
+++ b/src/OrthoStreamXP/Textures/Colour/Contrast.cs
@@ -0,0 +1,22 @@
+namespace OrthoStreamXP.Textures;
+
+///
+/// The contrast of the photos: an S-curve on each sRGB channel round mid-grey (sigmoidal contrast), black and white
+/// kept, nothing clipped. Fixed at 60 % of a scale whose 100 % is a steepness of 6: the mid-tones about 1.26 times as
+/// contrasty, aerial photos being hazy (the samples of 2026-11-18). Always on, whatever the other colour settings; made
+/// into the photos' one lookup table as X-Plane reads them ().
+///
+internal static class Contrast
+{
+ /// The strength in use, of the scale whose 100 % is a steepness of 6.
+ public const double Strength = 0.6;
+
+ private const double Steepness = 6 * Strength;
+ private static readonly double Low = Sigmoid(-Steepness / 2), High = Sigmoid(Steepness / 2);
+
+ /// One channel's value (0-255, clamped) through the curve, unrounded.
+ public static double Apply(double value) =>
+ (Sigmoid(Steepness * (Math.Clamp(value, 0, 255) / 255 - 0.5)) - Low) / (High - Low) * 255;
+
+ private static double Sigmoid(double x) => 1 / (1 + Math.Exp(-x));
+}
diff --git a/src/OrthoStreamXP/Textures/Colour/Exposure.cs b/src/OrthoStreamXP/Textures/Colour/Exposure.cs
index c630fdc..e4dfa4f 100644
--- a/src/OrthoStreamXP/Textures/Colour/Exposure.cs
+++ b/src/OrthoStreamXP/Textures/Colour/Exposure.cs
@@ -1,12 +1,11 @@
-using System.Collections.Concurrent;
-
namespace OrthoStreamXP.Textures;
///
/// The exposure of the photos: the light they let through, as a camera's exposure, from to 100 %.
/// Aerial photos are often brighter than X-Plane's own scenery around them; less exposure darkens them evenly. The
/// light is scaled in linear light and put back into sRGB, so 50 % is one stop darker without crushing the shadows
-/// or greying the highlights. Like the seasons, it is one lookup table over the RGB565 colours, applied as X-Plane reads.
+/// or greying the highlights. Made with the season and the contrast into the photos' one lookup table over the RGB565
+/// colours (), applied as X-Plane reads.
///
internal static class Exposure
{
@@ -16,32 +15,11 @@ internal static class Exposure
/// The least the settings allow, in percent: one stop darker.
public const int Min = 50;
- private static readonly ConcurrentDictionary Tables = new();
-
- /// The lookup table of an exposure in percent (rounded to a whole one); null at 100 %, which changes nothing.
- public static ushort[]? TableFor(double percent)
- {
- int key = (int)Math.Round(Math.Clamp(percent, Min, Full));
- return key == Full ? null : Tables.GetOrAdd(key, k => Build(k / 100.0));
- }
-
- private static ushort[] Build(double factor)
- {
- int[] five = Channel(31, factor), six = Channel(63, factor);
- var table = new ushort[65536];
- for (int c = 0; c < table.Length; c++)
- table[c] = (ushort)((five[(c >> 11) & 31] << 11) | (six[(c >> 5) & 63] << 5) | five[c & 31]);
- return table;
- }
+ /// The exposure a table is made for: within to , rounded to a whole percent.
+ internal static int Percent(double percent) => (int)Math.Round(Math.Clamp(percent, Min, Full));
- /// Each value of a channel of + 1 steps, with its light scaled by .
- private static int[] Channel(int max, double factor)
- {
- int[] values = new int[max + 1];
- for (int v = 0; v <= max; v++)
- values[v] = (int)Math.Round(ToSrgb(ToLinear((double)v / max) * factor) * max);
- return values;
- }
+ /// One channel's value (0-255, clamped) with its light scaled by , unrounded.
+ internal static double Darken(double value, double factor) => ToSrgb(ToLinear(Math.Clamp(value, 0, 255) / 255) * factor) * 255;
internal static double ToLinear(double srgb) => srgb <= 0.04045 ? srgb / 12.92 : Math.Pow((srgb + 0.055) / 1.055, 2.4);
diff --git a/src/OrthoStreamXP/Textures/Colour/PhotoColours.cs b/src/OrthoStreamXP/Textures/Colour/PhotoColours.cs
index 31c8e5a..3824026 100644
--- a/src/OrthoStreamXP/Textures/Colour/PhotoColours.cs
+++ b/src/OrthoStreamXP/Textures/Colour/PhotoColours.cs
@@ -1,21 +1,56 @@
+using System.Collections.Concurrent;
+
namespace OrthoStreamXP.Textures;
///
-/// The colour adjustments of a photo texture, in the order they are made as X-Plane reads it: the colours evened out
-/// between photos (), then the season's (), then the exposure
-/// (). The Settings page's preview makes them the same way, so it shows what X-Plane will.
+/// The colour adjustments of a photo texture as X-Plane reads it: the season's (), the contrast
+/// (, always on) and the exposure (), in that order, as one lookup table
+/// made from all of them at once, so a colour is rounded to 565 once. The Settings page's preview makes them the same
+/// way, so it shows what X-Plane will.
///
internal static class PhotoColours
{
+ private static readonly ConcurrentDictionary<(int Season, int Exposure), ushort[]> Tables = new();
+
+ ///
+ /// The lookup table of a season and an exposure in percent, shared by every texture; with summer and the full
+ /// exposure, the contrast alone.
+ ///
+ public static ushort[] TableFor(SeasonState season, double exposure)
+ {
+ var key = (season.IsSummer ? 0 : Seasons.StateKey(season), Exposure.Percent(exposure));
+ if (Tables.TryGetValue(key, out ushort[]? table)) return table;
+ if (Tables.Count > 1024) Tables.Clear();
+ return Tables.GetOrAdd(key, k => Build(season.IsSummer ? null : Seasons.Quantised(season), k.Exposure / 100.0));
+ }
+
///
- /// Adjusts the whole colour blocks in , which holds the bytes of a square DDS of
- /// pixels from ; blocks cut by either end stay as they are.
+ /// Adjusts the whole colour blocks in , which holds a DDS's bytes from
+ /// , by (); blocks cut by either end stay as they are.
///
/// 8 for DXT1 (BC1), 16 for DXT3 and DXT5.
- public static void Apply(Span data, long fileOffset, int blockBytes, int size, TextureColour? colour, ushort[]? season, ushort[]? exposure)
+ public static void Apply(Span data, long fileOffset, int blockBytes, ushort[]? table)
+ {
+ if (table is not null) ColourTable.Apply(data, fileOffset, blockBytes, table);
+ }
+
+ /// One colour (0-255 per channel) through the season (none in summer), the contrast and the exposure, unrounded.
+ internal static (double R, double G, double B) Adjust(double r, double g, double b, SeasonState? season, double factor)
+ {
+ if (season is { } state) (r, g, b) = Seasons.Recolor(r, g, b, state);
+ (r, g, b) = (Contrast.Apply(r), Contrast.Apply(g), Contrast.Apply(b));
+ return factor < 1 ? (Exposure.Darken(r, factor), Exposure.Darken(g, factor), Exposure.Darken(b, factor)) : (r, g, b);
+ }
+
+ private static ushort[] Build(SeasonState? season, double factor)
{
- colour?.Apply(data, fileOffset, blockBytes, size);
- if (season is not null) ColourTable.Apply(data, fileOffset, blockBytes, season);
- if (exposure is not null) ColourTable.Apply(data, fileOffset, blockBytes, exposure);
+ var table = new ushort[65536];
+ for (int c = 0; c < table.Length; c++)
+ {
+ var (r, g, b) = ColourTable.Decode565(c);
+ (r, g, b) = Adjust(r, g, b, season, factor);
+ table[c] = (ushort)ColourTable.Encode565(r, g, b);
+ }
+ return table;
}
}
diff --git a/src/OrthoStreamXP/Textures/Dds/Bc1Refinement.cs b/src/OrthoStreamXP/Textures/Dds/Bc1Refinement.cs
new file mode 100644
index 0000000..21954a1
--- /dev/null
+++ b/src/OrthoStreamXP/Textures/Dds/Bc1Refinement.cs
@@ -0,0 +1,215 @@
+using System.Buffers.Binary;
+using System.Runtime.CompilerServices;
+using System.Runtime.Intrinsics;
+
+namespace OrthoStreamXP.Textures;
+
+///
+/// Least-squares refinement of a BC1 block's two colours, as nvtt's fast mode does after its first fit: for the
+/// palette colour each pixel chose, solve the two colours that come closest to the pixels, round them to 565, let
+/// every pixel choose again, and keep the result only where the block's error went down. ISPC fits a block once;
+/// two passes bring aerial textures 0.3-0.4 dB closer (cached Bing imagery, 4096 px).
+///
+/// Eight pixels at a time in : X-Plane 12's least CPUs have AVX2, and without it .NET computes
+/// the same in software, only slower.
+///
+///
+internal static class Bc1Refinement
+{
+ /// Passes per block: the second adds about a quarter of the first's gain, a third almost nothing.
+ public const int Passes = 2;
+
+ /// Decoded mixes of two 5-bit values ().
+ private static readonly byte[] Five = MixTable(5);
+
+ /// Decoded mixes of two 6-bit values.
+ private static readonly byte[] Six = MixTable(6);
+
+ ///
+ /// Refines a block in the opaque four-colour mode (left as it is in any other) against its 16 pixels,
+ /// holding them as RGB, row by row. The block stays in the four-colour mode.
+ ///
+ [SkipLocalsInit]
+ public static void Refine(Span block, ReadOnlySpan pixels)
+ {
+ if (pixels.Length < 48) throw new ArgumentException("A block has 16 RGB pixels", nameof(pixels));
+ ushort c0 = BinaryPrimitives.ReadUInt16LittleEndian(block), c1 = BinaryPrimitives.ReadUInt16LittleEndian(block[2..]);
+ if (c0 <= c1) return;
+ var texels = Texels.From(pixels);
+ var choice = Choice.From(BinaryPrimitives.ReadUInt32LittleEndian(block[4..]));
+ Span palette = stackalloc int[12];
+ Palette(c0, c1, palette);
+ int bestError = Error(texels, palette, choice);
+ bool changed = false;
+ for (int pass = 0; pass < Passes && bestError > 0; pass++)
+ {
+ if (!Solve(texels, choice, out int n0, out int n1)) break;
+ Palette(n0, n1, palette);
+ Choice next = Choose(texels, palette, out int error);
+ if (error >= bestError) break;
+ (bestError, c0, c1, choice, changed) = (error, (ushort)n0, (ushort)n1, next, true);
+ }
+ if (!changed) return;
+ BinaryPrimitives.WriteUInt16LittleEndian(block, c0);
+ BinaryPrimitives.WriteUInt16LittleEndian(block[2..], c1);
+ BinaryPrimitives.WriteUInt32LittleEndian(block[4..], choice.Packed());
+ }
+
+ ///
+ /// The two 565 colours (the larger first) that come closest, in least squares, to the pixels for their chosen
+ /// palette colours; false where the choices cannot fix both (every pixel on one colour) or both round to one.
+ ///
+ private static bool Solve(in Texels texels, in Choice choice, out int n0, out int n1)
+ {
+ n0 = n1 = 0;
+ // The normal equations in thirds: a pixel's share of the first colour is a / 3 and of the second (3 - a) / 3,
+ // so aa, ab and bb are 9 times the real sums and the right-hand sides 3 times.
+ Vector256 aLow = Share(choice.Low), aHigh = Share(choice.High), three = Vector256.Create(3);
+ Vector256 bLow = three - aLow, bHigh = three - aHigh;
+ long aa = Vector256.Sum(aLow * aLow + aHigh * aHigh), ab = Vector256.Sum(aLow * bLow + aHigh * bHigh), bb = Vector256.Sum(bLow * bLow + bHigh * bHigh);
+ long det = aa * bb - ab * ab;
+ if (det == 0) return false;
+ long ar = Vector256.Sum(aLow * texels.R0 + aHigh * texels.R1), br = Vector256.Sum(bLow * texels.R0 + bHigh * texels.R1);
+ long ag = Vector256.Sum(aLow * texels.G0 + aHigh * texels.G1), bg = Vector256.Sum(bLow * texels.G0 + bHigh * texels.G1);
+ long ablue = Vector256.Sum(aLow * texels.B0 + aHigh * texels.B1), bblue = Vector256.Sum(bLow * texels.B0 + bHigh * texels.B1);
+ double scale = 3.0 / det;
+ n0 = Quantise((bb * ar - ab * br) * scale, (bb * ag - ab * bg) * scale, (bb * ablue - ab * bblue) * scale);
+ n1 = Quantise((aa * br - ab * ar) * scale, (aa * bg - ab * ag) * scale, (aa * bblue - ab * ablue) * scale);
+ if (n0 == n1) return false;
+ if (n0 < n1) (n0, n1) = (n1, n0);
+ return true;
+ }
+
+ /// Each palette index's share of the first colour, in thirds: 0 is 3, 1 is 0, 2 (2/3 : 1/3) is 2, 3 (1/3 : 2/3) is 1.
+ private static Vector256 Share(Vector256 index) =>
+ Vector256.ConditionalSelect(Vector256.Equals(index, Vector256.Zero), Vector256.Create(3),
+ Vector256.ConditionalSelect(Vector256.Equals(index, Vector256.One), Vector256.Zero, Vector256.Create(4) - index));
+
+ /// The nearest 565 colour of a solved one (0-255 per channel, clamped).
+ private static int Quantise(double r, double g, double b) =>
+ (Level(r, 31) << 11) | (Level(g, 63) << 5) | Level(b, 31);
+
+ private static int Level(double value, int max) => (int)(Math.Clamp(value, 0, 255) * max / 255 + 0.5);
+
+ /// Each pixel's nearest palette colour (of equally near ones, the first) and the block's squared error with them.
+ internal static Choice Choose(in Texels texels, ReadOnlySpan palette, out int error)
+ {
+ var (lowDistance, lowIndex) = Nearest(texels.R0, texels.G0, texels.B0, palette);
+ var (highDistance, highIndex) = Nearest(texels.R1, texels.G1, texels.B1, palette);
+ error = Vector256.Sum(lowDistance + highDistance);
+ return new Choice(lowIndex, highIndex);
+ }
+
+ private static (Vector256 Distance, Vector256 Index) Nearest(Vector256 r, Vector256 g, Vector256 b, ReadOnlySpan palette)
+ {
+ Vector256 best = Distance(r, g, b, palette, 0), index = Vector256.Zero;
+ for (int k = 1; k < 4; k++)
+ {
+ Vector256 distance = Distance(r, g, b, palette, k);
+ index = Vector256.ConditionalSelect(Vector256.LessThan(distance, best), Vector256.Create(k), index);
+ best = Vector256.Min(best, distance);
+ }
+ return (best, index);
+ }
+
+ /// The block's squared error with its pixels' current choices.
+ private static int Error(in Texels texels, ReadOnlySpan palette, in Choice choice) =>
+ Vector256.Sum(Chosen(texels.R0, texels.G0, texels.B0, palette, choice.Low) + Chosen(texels.R1, texels.G1, texels.B1, palette, choice.High));
+
+ private static Vector256 Chosen(Vector256 r, Vector256 g, Vector256 b, ReadOnlySpan palette, Vector256 index)
+ {
+ Vector256 distance = Distance(r, g, b, palette, 0);
+ for (int k = 1; k < 4; k++)
+ distance = Vector256.ConditionalSelect(Vector256.Equals(index, Vector256.Create(k)), Distance(r, g, b, palette, k), distance);
+ return distance;
+ }
+
+ private static Vector256 Distance(Vector256 r, Vector256 g, Vector256 b, ReadOnlySpan palette, int k)
+ {
+ Vector256 dr = r - Vector256.Create(palette[k * 3]), dg = g - Vector256.Create(palette[k * 3 + 1]), db = b - Vector256.Create(palette[k * 3 + 2]);
+ return dr * dr + dg * dg + db * db;
+ }
+
+ /// The four-colour palette of two 565 colours, rounded as decodes it.
+ private static void Palette(int c0, int c1, Span palette)
+ {
+ int r0 = c0 >> 11, g0 = (c0 >> 5) & 63, b0 = c0 & 31, r1 = c1 >> 11, g1 = (c1 >> 5) & 63, b1 = c1 & 31;
+ palette[0] = Five[r0 * 33];
+ palette[1] = Six[g0 * 65];
+ palette[2] = Five[b0 * 33];
+ palette[3] = Five[r1 * 33];
+ palette[4] = Six[g1 * 65];
+ palette[5] = Five[b1 * 33];
+ palette[6] = Five[r0 * 32 + r1];
+ palette[7] = Six[g0 * 64 + g1];
+ palette[8] = Five[b0 * 32 + b1];
+ palette[9] = Five[r1 * 32 + r0];
+ palette[10] = Six[g1 * 64 + g0];
+ palette[11] = Five[b1 * 32 + b0];
+ }
+
+ ///
+ /// For a channel of bits, at [a * levels + b] the decoded value of the mix (2 a + b) / 3,
+ /// rounded from the exact values as does; [a * levels + a] is a itself.
+ ///
+ private static byte[] MixTable(int bits)
+ {
+ int levels = 1 << bits;
+ double max = levels - 1;
+ var table = new byte[levels * levels];
+ for (int a = 0; a < levels; a++)
+ for (int b = 0; b < levels; b++)
+ {
+ double va = a * 255.0 / max, vb = b * 255.0 / max;
+ table[a * levels + b] = (byte)Math.Round(a == b ? va : (2 * va + vb) / 3);
+ }
+ return table;
+ }
+
+ /// A block's 16 pixels as channel vectors of eight: pixels 0-7 and 8-15.
+ internal readonly struct Texels
+ {
+ public Vector256 R0 { get; init; }
+ public Vector256 G0 { get; init; }
+ public Vector256 B0 { get; init; }
+ public Vector256 R1 { get; init; }
+ public Vector256 G1 { get; init; }
+ public Vector256 B1 { get; init; }
+
+ [SkipLocalsInit]
+ public static Texels From(ReadOnlySpan pixels)
+ {
+ Span channels = stackalloc int[48];
+ for (int i = 0; i < 16; i++)
+ {
+ channels[i] = pixels[i * 3];
+ channels[16 + i] = pixels[i * 3 + 1];
+ channels[32 + i] = pixels[i * 3 + 2];
+ }
+ return new Texels
+ {
+ R0 = Vector256.Create(channels[..8]), R1 = Vector256.Create(channels[8..16]),
+ G0 = Vector256.Create(channels[16..24]), G1 = Vector256.Create(channels[24..32]),
+ B0 = Vector256.Create(channels[32..40]), B1 = Vector256.Create(channels[40..48]),
+ };
+ }
+ }
+
+ /// The palette index (0-3) each of a block's 16 pixels takes: pixels 0-7 and 8-15.
+ internal readonly record struct Choice(Vector256 Low, Vector256 High)
+ {
+ /// Each lane's place in the packed indices: times 4^lane moves its index to its 2 bits.
+ private static readonly Vector256 Place = Vector256.Create(1, 4, 16, 64, 256, 1024, 4096, 16384);
+
+ [SkipLocalsInit]
+ public static Choice From(uint indices)
+ {
+ Span lanes = stackalloc int[16];
+ for (int i = 0; i < 16; i++) lanes[i] = (int)(indices >> (2 * i)) & 3;
+ return new Choice(Vector256.Create(lanes[..8]), Vector256.Create(lanes[8..]));
+ }
+
+ /// The indices as BC1 stores them, 2 bits a pixel from the lowest; the lanes' bits never overlap, so their sum is their OR.
+ public uint Packed() => (uint)Vector256.Sum(Low * Place) | (uint)Vector256.Sum(High * Place) << 16;
+ }
+}
diff --git a/src/OrthoStreamXP/Textures/Dds/Dds.cs b/src/OrthoStreamXP/Textures/Dds/Dds.cs
index 563e363..12369ab 100644
--- a/src/OrthoStreamXP/Textures/Dds/Dds.cs
+++ b/src/OrthoStreamXP/Textures/Dds/Dds.cs
@@ -1,4 +1,3 @@
-using System.Buffers;
using System.Buffers.Binary;
using System.Diagnostics;
using System.Text;
@@ -10,7 +9,7 @@ internal static class Dds
{
public const int HeaderSize = 128;
- /// Encodes an RGB image and its 2x2-averaged mip chain into a complete DXT1 .dds file.
+ /// Encodes an RGB image and its mip chain (2x2 averages in linear light, ) into a complete DXT1 .dds file.
public static byte[] Encode(byte[] rgb, int width, int height, int workers, out double mipmapSeconds, out double bc1Seconds)
{
int levels = 1;
@@ -31,7 +30,7 @@ public static byte[] Encode(byte[] rgb, int width, int height, int workers, out
if (level > 0)
{
long mipStarted = Stopwatch.GetTimestamp();
- current = Images.BoxHalf(current, w, h, workers);
+ current = MipFilter.Half(current, w, h, workers);
w = Math.Max(1, w >> 1);
h = Math.Max(1, h >> 1);
mipmapSeconds += Stopwatch.GetElapsedTime(mipStarted).TotalSeconds;
@@ -45,15 +44,15 @@ public static byte[] Encode(byte[] rgb, int width, int height, int workers, out
///
/// The BC1 data of mip levels to the last of a square texture, as they follow each other
- /// in the file: is level itself, the smaller ones are 2x2 averages.
+ /// in the file: is level itself, the smaller ones are 2x2 averages in linear light ().
///
- public static byte[] EncodeChain(byte[] rgb, DdsLayout layout, int firstMip, int workers)
+ /// Where the smaller levels' pictures come from; without it they are new arrays.
+ public static byte[] EncodeChain(byte[] rgb, DdsLayout layout, int firstMip, int workers, BuildBufferPool? buffers = null)
{
byte[] output = new byte[layout.ChainLength(firstMip)];
int offset = 0;
- // The smaller levels take turns in two pooled pictures, the size of the first of them: a 4096 px chain made
- // 16 MB of new large objects per build otherwise.
- int half = layout.SizeOf(Math.Min(firstMip + 1, layout.Levels - 1)), halfBytes = half * half * 3;
+ // The smaller levels take turns in two pictures, each the size of the first level it holds (a quarter and a
+ // sixteenth of the first one's pixels): a 4096 px chain made 16 MB of new large objects per build otherwise.
byte[]? even = null, odd = null;
try
{
@@ -63,10 +62,9 @@ public static byte[] EncodeChain(byte[] rgb, DdsLayout layout, int firstMip, int
int size = layout.SizeOf(mip);
if (mip > firstMip)
{
- byte[] next = (mip - firstMip) % 2 == 1
- ? even ??= ArrayPool.Shared.Rent(halfBytes)
- : odd ??= ArrayPool.Shared.Rent(halfBytes);
- Images.BoxHalfInto(current, size * 2, size * 2, next, workers);
+ int bytes = size * size * 3;
+ byte[] next = (mip - firstMip) % 2 == 1 ? even ??= Rent(bytes) : odd ??= Rent(bytes);
+ MipFilter.HalfInto(current, size * 2, size * 2, next, workers);
current = next;
}
offset += EncodeBC1(current, size, size, output, offset, workers);
@@ -74,10 +72,12 @@ public static byte[] EncodeChain(byte[] rgb, DdsLayout layout, int firstMip, int
}
finally
{
- if (even is not null) ArrayPool.Shared.Return(even);
- if (odd is not null) ArrayPool.Shared.Return(odd);
+ if (even is not null) buffers?.Return(even);
+ if (odd is not null) buffers?.Return(odd);
}
return output;
+
+ byte[] Rent(int bytes) => buffers?.Rent(bytes) ?? new byte[bytes];
}
/// The BC1 data of one square level.
@@ -159,11 +159,20 @@ internal static void WriteHeader(Span h, int width, int height, int levels
static void Put(Span data, int offset, uint value) => BinaryPrimitives.WriteUInt32LittleEndian(data[offset..], value);
}
+ /// The BC1 encoder in use: Intel's ISPC where its DLL loads, else the program's own range fit.
+ public static string Encoder => IspcBc1.IsAvailable ? "ispc" : "range-fit";
+
+ /// BC1 blocks of an RGB image, by or, without it, . Returns the bytes written.
+ private static int EncodeBC1(byte[] input, int width, int height, byte[] output, int offset, int workers) =>
+ IspcBc1.IsAvailable
+ ? IspcBc1.Encode(input, width, height, output, offset, workers)
+ : EncodeRangeFit(input, width, height, output, offset, workers);
+
///
- /// Fast range-fit BC1: endpoints are the per-block min/max inset by 1/16 of the range,
- /// each pixel takes the nearest of the four palette colours. Returns the bytes written.
+ /// Fast range-fit BC1, the fallback when ISPC is missing: endpoints are the per-block min/max inset by 1/16 of the
+ /// range, each pixel takes the nearest of the four palette colours. Returns the bytes written.
///
- private static int EncodeBC1(byte[] input, int width, int height, byte[] output, int offset, int workers)
+ internal static int EncodeRangeFit(byte[] input, int width, int height, byte[] output, int offset, int workers)
{
int blocksX = Math.Max(1, (width + 3) / 4), blocksY = Math.Max(1, (height + 3) / 4);
void BlockRow(int by)
diff --git a/src/OrthoStreamXP/Textures/Dds/DdsBlocks.cs b/src/OrthoStreamXP/Textures/Dds/DdsBlocks.cs
deleted file mode 100644
index deb8c49..0000000
--- a/src/OrthoStreamXP/Textures/Dds/DdsBlocks.cs
+++ /dev/null
@@ -1,89 +0,0 @@
-using System.Collections.Concurrent;
-
-namespace OrthoStreamXP.Textures;
-
-///
-/// Walks the whole colour blocks in a piece of a square DDS (from fileOffset, length bytes), level by
-/// level, with the place each block is in: the texture split into steps x steps places, the same places
-/// at every level. Blocks cut by either end of the piece are skipped, so a block's two halves always match whichever
-/// reads they come in.
-///
-internal ref struct DdsBlocks
-{
- private static readonly ConcurrentDictionary<(int Size, int BlockBytes), long[]> Levels = new();
- private static readonly ConcurrentDictionary<(int Across, int Steps), int[]> PlacesAcross = new();
-
- private readonly long _fileOffset, _end;
- private readonly int _blockBytes, _size, _steps;
- private readonly long[] _levels;
- private long _at;
- private int _level, _across, _bx, _by;
- private int[] _placeOf;
- private bool _started;
-
- public DdsBlocks(long fileOffset, int length, int blockBytes, int size, int steps)
- {
- _fileOffset = fileOffset;
- _blockBytes = blockBytes;
- _size = size;
- _steps = steps;
- _levels = Levels.GetOrAdd((size, blockBytes), key => LevelOffsets(key.Size, key.BlockBytes));
- long from = Math.Max(fileOffset, Dds.HeaderSize) - Dds.HeaderSize;
- _at = Dds.HeaderSize + (from + blockBytes - 1) / blockBytes * blockBytes;
- _end = Math.Min(fileOffset + length, _levels[^1]);
- _placeOf = [];
- }
-
- /// Where the block's colour part starts in the piece (the second half of a 16-byte block).
- public readonly int At => (int)(_at - _fileOffset) + (_blockBytes == 16 ? 8 : 0);
-
- /// The block's place across and down (0 to steps - 1).
- public readonly int PlaceX => _placeOf[_bx];
-
- public readonly int PlaceY => _placeOf[_by];
-
- /// Whether the block starts a new row of places (the places of the previous row are not met again soon).
- public bool NewRow { get; private set; }
-
- public bool MoveNext()
- {
- int previousY = _started ? PlaceY : -1;
- bool newLevel = false;
- if (_started)
- {
- _at += _blockBytes;
- if (++_bx == _across)
- {
- _bx = 0;
- _by++;
- }
- }
- if (_at + _blockBytes > _end) return false;
- if (!_started || _at >= _levels[_level + 1])
- {
- while (_at >= _levels[_level + 1]) _level++;
- _across = Math.Max(1, ((_size >> _level) + 3) / 4);
- long index = (_at - _levels[_level]) / _blockBytes;
- (_bx, _by) = ((int)(index % _across), (int)(index / _across));
- int across = _across, steps = _steps;
- _placeOf = PlacesAcross.GetOrAdd((across, steps), key => [.. Enumerable.Range(0, key.Across).Select(i => (int)((long)i * key.Steps / key.Across))]);
- newLevel = true;
- }
- _started = true;
- NewRow = newLevel || PlaceY != previousY;
- return true;
- }
-
- /// Where each level starts in a square DDS (and, last, where the levels end).
- private static long[] LevelOffsets(int size, int blockBytes)
- {
- var offsets = new List { Dds.HeaderSize };
- for (int s = size; ; s = Math.Max(1, s >> 1))
- {
- long blocks = Math.Max(1, (s + 3) / 4);
- offsets.Add(offsets[^1] + blocks * blocks * blockBytes);
- if (s == 1) break;
- }
- return [.. offsets];
- }
-}
diff --git a/src/OrthoStreamXP/Textures/Dds/IspcBc1.cs b/src/OrthoStreamXP/Textures/Dds/IspcBc1.cs
new file mode 100644
index 0000000..080173a
--- /dev/null
+++ b/src/OrthoStreamXP/Textures/Dds/IspcBc1.cs
@@ -0,0 +1,194 @@
+using System.Buffers;
+using System.Buffers.Binary;
+using System.Runtime.InteropServices;
+
+namespace OrthoStreamXP.Textures;
+
+///
+/// BC1 encoding by Intel's ISPC Texture Compressor (ispc_texcomp.dll, MIT, built by native\ispc_texcomp\build.ps1):
+/// on aerial textures 6-8 times faster than 's own encoder (about twice with the refinement after it,
+/// ) and sharper. The DLL is loaded
+/// from the program's folder once; without it is false and encodes itself.
+///
+internal static unsafe class IspcBc1
+{
+ private const string LibraryName = "ispc_texcomp.dll";
+ /// Block rows converted to RGBA and encoded at a time: 32 pixel rows, 512 KB for a 4096 px level.
+ private const int ChunkBlockRows = 8;
+
+ private static readonly delegate* unmanaged[Cdecl] CompressBlocksBC1 = Load();
+ /// For each 8-bit value, the 5-bit (6-bit for green) endpoint pair whose 2/3 : 1/3 mix comes closest to it.
+ private static readonly (byte E0, byte E1)[] Match5 = SingleColourTable(5), Match6 = SingleColourTable(6);
+
+ /// Whether the DLL was loaded; false where it is missing or not loadable.
+ public static bool IsAvailable => CompressBlocksBC1 != null;
+
+ ///
+ /// Encodes an RGB image into BC1 blocks at of , the same layout and
+ /// edge handling (a partial block repeats its last row and column) as 's own encoder, every block
+ /// in the opaque four-colour mode. Returns the bytes written.
+ ///
+ public static int Encode(byte[] input, int width, int height, byte[] output, int offset, int workers)
+ {
+ if (!IsAvailable) throw new InvalidOperationException($"{LibraryName} is not loaded");
+ int blocksX = Math.Max(1, (width + 3) / 4), blocksY = Math.Max(1, (height + 3) / 4), length = blocksX * blocksY * 8;
+ if (input.Length < width * height * 3) throw new ArgumentException("The image is smaller than its size", nameof(input));
+ if (offset < 0 || output.Length - offset < length) throw new ArgumentException("The output cannot hold the blocks", nameof(output));
+
+ int chunks = (blocksY + ChunkBlockRows - 1) / ChunkBlockRows;
+ void Chunk(int chunk)
+ {
+ int firstRow = chunk * ChunkBlockRows, rows = Math.Min(ChunkBlockRows, blocksY - firstRow);
+ int paddedWidth = blocksX * 4, stride = paddedWidth * 4;
+ byte[] rgba = ArrayPool.Shared.Rent(stride * rows * 4);
+ try
+ {
+ ToRgba(input, width, height, firstRow * 4, rows * 4, rgba, paddedWidth);
+ int at = offset + firstRow * blocksX * 8;
+ fixed (byte* source = rgba, blocks = output)
+ {
+ var surface = new Surface { Pixels = source, Width = paddedWidth, Height = rows * 4, Stride = stride };
+ CompressBlocksBC1(&surface, blocks + at);
+ }
+ Finish(output.AsSpan(at, rows * blocksX * 8), rgba, stride);
+ }
+ finally
+ {
+ ArrayPool.Shared.Return(rgba);
+ }
+ }
+ if (workers <= 1 || blocksY < 16)
+ for (int chunk = 0; chunk < chunks; chunk++) Chunk(chunk);
+ else
+ Parallel.For(0, chunks, new ParallelOptions { MaxDegreeOfParallelism = workers }, Chunk);
+ return length;
+ }
+
+ ///
+ /// Pixel rows on of an RGB image as opaque RGBA, wide; rows
+ /// and columns beyond the image repeat its last ones.
+ ///
+ private static void ToRgba(byte[] input, int width, int height, int firstY, int rows, byte[] rgba, int paddedWidth)
+ {
+ for (int y = 0; y < rows; y++)
+ {
+ int sourceRow = Math.Min(height - 1, firstY + y) * width * 3, o = y * paddedWidth * 4;
+ for (int x = 0; x < paddedWidth; x++, o += 4)
+ {
+ int i = sourceRow + Math.Min(width - 1, x) * 3;
+ rgba[o] = input[i];
+ rgba[o + 1] = input[i + 1];
+ rgba[o + 2] = input[i + 2];
+ rgba[o + 3] = 255;
+ }
+ }
+ }
+
+ ///
+ /// After ISPC, for the blocks of a chunk ( its pixels): a one-colour block gets the endpoint
+ /// pair that mixes closest to its colour (ISPC lands up to a 565 step off: water and flat fields); every other block
+ /// the opaque four-colour mode (first colour the larger), which the recolouring () expects,
+ /// and then the least-squares refinement of its two colours (), which ISPC leaves out.
+ ///
+ private static void Finish(Span blocks, byte[] rgba, int stride)
+ {
+ int blocksX = stride / 16;
+ Span pixels = stackalloc byte[48];
+ for (int index = 0; index * 8 + 8 <= blocks.Length; index++)
+ {
+ Span block = blocks.Slice(index * 8, 8);
+ int first = index / blocksX * 4 * stride + index % blocksX * 16;
+ if (IsOneColour(rgba, first, stride))
+ {
+ WriteOneColour(block, rgba[first], rgba[first + 1], rgba[first + 2]);
+ continue;
+ }
+ ushort c0 = BinaryPrimitives.ReadUInt16LittleEndian(block), c1 = BinaryPrimitives.ReadUInt16LittleEndian(block[2..]);
+ if (c0 <= c1) ColourTable.WriteColors(block, 8, c0, c1);
+ BlockPixels(rgba, first, stride, pixels);
+ Bc1Refinement.Refine(block, pixels);
+ }
+ }
+
+ /// A block's 16 pixels as RGB, row by row, from the RGBA rows of its chunk.
+ private static void BlockPixels(byte[] rgba, int first, int stride, Span pixels)
+ {
+ for (int i = 0; i < 16; i++)
+ {
+ int at = first + (i >> 2) * stride + (i & 3) * 4;
+ pixels[i * 3] = rgba[at];
+ pixels[i * 3 + 1] = rgba[at + 1];
+ pixels[i * 3 + 2] = rgba[at + 2];
+ }
+ }
+
+ private static bool IsOneColour(byte[] rgba, int first, int stride)
+ {
+ // Alpha is always 255, so whole pixels compare as 32-bit words.
+ uint colour = BinaryPrimitives.ReadUInt32LittleEndian(rgba.AsSpan(first));
+ for (int y = 0; y < 4; y++)
+ {
+ ReadOnlySpan row = MemoryMarshal.Cast(rgba.AsSpan(first + y * stride, 16));
+ if (row[0] != colour || row[1] != colour || row[2] != colour || row[3] != colour) return false;
+ }
+ return true;
+ }
+
+ /// A block of one colour: every pixel the 2/3 : 1/3 mix of the best endpoint pair, in the four-colour mode.
+ internal static void WriteOneColour(Span block, byte r, byte g, byte b)
+ {
+ var (r0, r1) = Match5[r];
+ var (g0, g1) = Match6[g];
+ var (b0, b1) = Match5[b];
+ ushort c0 = (ushort)(r0 << 11 | g0 << 5 | b0), c1 = (ushort)(r1 << 11 | g1 << 5 | b1);
+ // Every pixel index 2, the mix (2 c0 + c1) / 3. WriteColors puts the larger colour first, turning the indices to 3
+ // (the same mix) where it swaps them, and makes a pair of equal colours index 0 of that colour.
+ BinaryPrimitives.WriteUInt32LittleEndian(block[4..], 0xAAAAAAAAu);
+ ColourTable.WriteColors(block, 8, c0, c1);
+ }
+
+ ///
+ /// For every 8-bit value, the pair of -bit endpoints (expanded by bit replication, as a GPU
+ /// does) whose palette entry (2 e0 + e1) / 3 is closest; of equally close pairs, the nearest together.
+ ///
+ private static (byte E0, byte E1)[] SingleColourTable(int bits)
+ {
+ int levels = 1 << bits;
+ var table = new (byte, byte)[256];
+ for (int value = 0; value < 256; value++)
+ {
+ int bestError = int.MaxValue, bestSpread = int.MaxValue;
+ for (int e0 = 0; e0 < levels; e0++)
+ for (int e1 = 0; e1 < levels; e1++)
+ {
+ int mix = (2 * Expand(e0, bits) + Expand(e1, bits) + 1) / 3, error = Math.Abs(mix - value), spread = Math.Abs(e0 - e1);
+ if (error < bestError || (error == bestError && spread < bestSpread))
+ {
+ (bestError, bestSpread) = (error, spread);
+ table[value] = ((byte)e0, (byte)e1);
+ }
+ }
+ }
+ return table;
+
+ static int Expand(int e, int bits) => e << (8 - bits) | e >> (2 * bits - 8);
+ }
+
+ private static delegate* unmanaged[Cdecl] Load()
+ {
+ string path = Path.Combine(AppContext.BaseDirectory, LibraryName);
+ return NativeLibrary.TryLoad(path, out nint library) && NativeLibrary.TryGetExport(library, "CompressBlocksBC1", out nint export)
+ ? (delegate* unmanaged[Cdecl])export
+ : null;
+ }
+
+ /// ISPC's rgba_surface.
+ [StructLayout(LayoutKind.Sequential)]
+ private struct Surface
+ {
+ public byte* Pixels;
+ public int Width;
+ public int Height;
+ public int Stride;
+ }
+}
diff --git a/src/OrthoStreamXP/Textures/Dds/MipFilter.cs b/src/OrthoStreamXP/Textures/Dds/MipFilter.cs
new file mode 100644
index 0000000..9c97d36
--- /dev/null
+++ b/src/OrthoStreamXP/Textures/Dds/MipFilter.cs
@@ -0,0 +1,76 @@
+namespace OrthoStreamXP.Textures;
+
+///
+/// The next smaller mip level: each 2x2 average made in linear light, as the GPU filters an sRGB texture, not of the
+/// stored values. Averaging the stored values darkens every level a little more (a bright and a dark pixel average to
+/// a darker grey than the light they give): about 1 step of 255 at 1024 px, 3 at 256 px, 5 at 16 px of a 4096 px
+/// photo texture, so the distant ground was darker than near. Integer tables, no floating point per pixel: about as
+/// fast as the plain average.
+///
+internal static class MipFilter
+{
+ private const int CoarseShift = 10;
+ private const double Scale = 1 << 24;
+
+ /// Linear light of each stored value (sRGB curve), scaled to 2^24.
+ private static readonly uint[] ToLinear = [.. Enumerable.Range(0, 256).Select(c => (uint)Math.Round(Linear(c / 255.0) * Scale))];
+ /// Where each stored value's rounding ends in linear light: the light of value c + 0.5.
+ private static readonly uint[] Threshold =
+ [.. Enumerable.Range(0, 256).Select(c => c == 255 ? uint.MaxValue : (uint)Math.Round(Linear((c + 0.5) / 255.0) * Scale))];
+ /// The stored value at the start of each 2^10-wide stretch of linear light (the search starts there).
+ private static readonly byte[] Coarse = CoarseTable();
+
+ private static byte[] CoarseTable()
+ {
+ var table = new byte[(1 << 24 >> CoarseShift) + 1];
+ int code = 0;
+ for (int i = 0; i < table.Length; i++)
+ {
+ uint start = (uint)i << CoarseShift;
+ while (code < 255 && start >= Threshold[code]) code++;
+ table[i] = (byte)code;
+ }
+ return table;
+ }
+
+ /// The level below an RGB image, a new array; odd edges repeat their last row/column.
+ public static byte[] Half(byte[] src, int w, int h, int workers)
+ {
+ byte[] dst = new byte[Math.Max(1, w >> 1) * Math.Max(1, h >> 1) * 3];
+ HalfInto(src, w, h, dst, workers);
+ return dst;
+ }
+
+ /// into , which may be longer than the half-size image (a pooled array).
+ public static void HalfInto(byte[] src, int w, int h, byte[] dst, int workers)
+ {
+ int nw = Math.Max(1, w >> 1), nh = Math.Max(1, h >> 1);
+ if (dst.Length < nw * nh * 3) throw new ArgumentException("The destination is smaller than the half-size image", nameof(dst));
+ void Row(int ny)
+ {
+ int y0 = Math.Min(h - 1, ny * 2), y1 = Math.Min(h - 1, ny * 2 + 1);
+ for (int nx = 0; nx < nw; nx++)
+ {
+ int x0 = Math.Min(w - 1, nx * 2), x1 = Math.Min(w - 1, nx * 2 + 1);
+ int a = (y0 * w + x0) * 3, b = (y0 * w + x1) * 3, c = (y1 * w + x0) * 3, d = (y1 * w + x1) * 3, o = (ny * nw + nx) * 3;
+ for (int k = 0; k < 3; k++)
+ dst[o + k] = Stored((ToLinear[src[a + k]] + ToLinear[src[b + k]] + ToLinear[src[c + k]] + ToLinear[src[d + k]] + 2) >> 2);
+ }
+ }
+ if (workers <= 1 || nh < 64)
+ for (int ny = 0; ny < nh; ny++) Row(ny);
+ else
+ Parallel.For(0, nh, new ParallelOptions { MaxDegreeOfParallelism = workers }, Row);
+ }
+
+ /// The stored value nearest (on the stored scale) to an amount of linear light.
+ internal static byte Stored(uint linear)
+ {
+ int code = Coarse[linear >> CoarseShift];
+ while (code < 255 && linear >= Threshold[code]) code++;
+ return (byte)code;
+ }
+
+ /// The linear light of a stored value (sRGB curve, 0 to 1).
+ internal static double Linear(double stored) => stored <= 0.04045 ? stored / 12.92 : Math.Pow((stored + 0.055) / 1.055, 2.4);
+}
diff --git a/src/OrthoStreamXP/Textures/Images.cs b/src/OrthoStreamXP/Textures/Images.cs
index a9eddf8..ad6b4b1 100644
--- a/src/OrthoStreamXP/Textures/Images.cs
+++ b/src/OrthoStreamXP/Textures/Images.cs
@@ -1,3 +1,4 @@
+using System.Buffers;
using SkiaSharp;
namespace OrthoStreamXP.Textures;
@@ -11,18 +12,31 @@ internal static class Images
///
/// Below 1: decode at about this fraction of the size, which a JPEG does far faster (1/2, 1/4, 1/8).
public static (byte[] Rgb, int Width, int Height) Decode(byte[] encoded, float scale = 1)
+ {
+ using SKBitmap bitmap = DecodeBitmap(encoded, scale);
+ byte[] rgb = new byte[bitmap.Width * bitmap.Height * 3];
+ ToRgb(bitmap, rgb);
+ return (rgb, bitmap.Width, bitmap.Height);
+ }
+
+ private static SKBitmap DecodeBitmap(byte[] encoded, float scale)
{
using SKData data = SKData.CreateCopy(encoded);
using SKCodec codec = SKCodec.Create(data) ?? throw new InvalidDataException("Not a decodable image");
SKSizeI size = scale < 1 ? codec.GetScaledDimensions(scale) : codec.Info.Size;
var info = new SKImageInfo(size.Width, size.Height, SKColorType.Rgba8888, SKAlphaType.Premul);
- using var bitmap = new SKBitmap(info);
+ var bitmap = new SKBitmap(info);
SKCodecResult result = codec.GetPixels(info, bitmap.GetPixels());
- if (result != SKCodecResult.Success) throw new InvalidDataException($"Image decode failed: {result}");
+ if (result == SKCodecResult.Success) return bitmap;
+ bitmap.Dispose();
+ throw new InvalidDataException($"Image decode failed: {result}");
+ }
- int width = info.Width, height = info.Height, rowBytes = bitmap.RowBytes;
+ /// A decoded bitmap's pixels as tightly packed RGB.
+ private static void ToRgb(SKBitmap bitmap, Span rgb)
+ {
+ int width = bitmap.Width, height = bitmap.Height, rowBytes = bitmap.RowBytes;
ReadOnlySpan rgba = bitmap.GetPixelSpan();
- byte[] rgb = new byte[width * height * 3];
for (int y = 0; y < height; y++)
{
ReadOnlySpan row = rgba.Slice(y * rowBytes, width * 4);
@@ -34,7 +48,6 @@ public static (byte[] Rgb, int Width, int Height) Decode(byte[] encoded, float s
rgb[o + 2] = row[x * 4 + 2];
}
}
- return (rgb, width, height);
}
/// Whether an image has any pixel that is not fully opaque (a JPEG never has; nothing is decoded for one).
@@ -59,8 +72,41 @@ public static bool HasTransparentPixels(byte[] encoded)
/// Decodes a source tile and makes sure it is 256x256 (providers occasionally send other sizes).
public static byte[] DecodeTile(byte[] encoded)
{
- var (rgb, width, height) = Decode(encoded);
- return width == Tiles.TilePx && height == Tiles.TilePx ? rgb : Resize(rgb, width, height, Tiles.TilePx, Tiles.TilePx, 1);
+ byte[] rgb = new byte[Tiles.TileBytes];
+ DecodeTileInto(encoded, rgb);
+ return rgb;
+ }
+
+ ///
+ /// into (at least long): no array of
+ /// its own, except for a tile of another size, which is decoded whole and resized first.
+ ///
+ public static void DecodeTileInto(byte[] encoded, Span rgb)
+ {
+ if (rgb.Length < Tiles.TileBytes) throw new ArgumentException("The destination is smaller than a tile", nameof(rgb));
+ using SKBitmap bitmap = DecodeBitmap(encoded, 1);
+ if (bitmap.Width == Tiles.TilePx && bitmap.Height == Tiles.TilePx)
+ {
+ ToRgb(bitmap, rgb);
+ return;
+ }
+ byte[] whole = new byte[bitmap.Width * bitmap.Height * 3];
+ ToRgb(bitmap, whole);
+ Resize(whole, bitmap.Width, bitmap.Height, Tiles.TilePx, Tiles.TilePx, 1).CopyTo(rgb);
+ }
+
+ /// Throws unless the bytes decode as a tile (error pages, truncated data); nothing is kept.
+ public static void CheckTile(byte[] encoded)
+ {
+ byte[] scratch = ArrayPool.Shared.Rent(Tiles.TileBytes);
+ try
+ {
+ DecodeTileInto(encoded, scratch);
+ }
+ finally
+ {
+ ArrayPool.Shared.Return(scratch);
+ }
}
/// Box-halving while at least 2x too large, then bicubic for whatever ratio remains.
diff --git a/src/OrthoStreamXP/Textures/Scheduling/FetchPriority.cs b/src/OrthoStreamXP/Textures/Scheduling/FetchPriority.cs
index 6c07aa7..bab1ade 100644
--- a/src/OrthoStreamXP/Textures/Scheduling/FetchPriority.cs
+++ b/src/OrthoStreamXP/Textures/Scheduling/FetchPriority.cs
@@ -2,16 +2,18 @@ namespace OrthoStreamXP.Textures;
///
/// How urgent a download is; lower numbers go first. X-Plane waiting next to the aircraft comes before
-/// everything, then X-Plane waiting elsewhere (bigger mip levels first), then work done before X-Plane asks.
+/// everything, then X-Plane waiting elsewhere (bigger mip levels first), then work done before X-Plane asks: a read
+/// X-Plane is blocked on never queues behind work it has not asked for yet (a flight of 17 Nov spent 50 s of its
+/// load with middle reads queued behind the full-size builds ahead of the aircraft).
///
internal static class FetchPriority
{
/// X-Plane is waiting for a texture next to the aircraft.
public const int NearRead = 0;
- /// Next to the aircraft, fetched before X-Plane asks.
- public const int NearWarm = 100;
/// X-Plane is waiting for a mip level farther out; add the level, so bigger levels go first.
- public const int Read = 200;
+ public const int Read = 100;
+ /// Next to the aircraft, fetched before X-Plane asks.
+ public const int NearWarm = 200;
/// Fetched before X-Plane asks: the middle distance, the flight path, a whole texture built ahead.
public const int Warm = 300;
/// Far scenery's low-zoom tile, or the real data behind a stand-in X-Plane already has.
diff --git a/src/OrthoStreamXP/Textures/Seasons/GreennessYear.cs b/src/OrthoStreamXP/Textures/Seasons/GreennessYear.cs
new file mode 100644
index 0000000..af6f61f
--- /dev/null
+++ b/src/OrthoStreamXP/Textures/Seasons/GreennessYear.cs
@@ -0,0 +1,80 @@
+namespace OrthoStreamXP.Textures;
+
+///
+/// How green a place was through a year, month by month, as satellites measure it (NDVI, 0 bare or snow to 1 dense
+/// vegetation; ). A month less green than both its neighbours (a cloudy or flooded
+/// composite, one snowfall: what goes wrong in a satellite's month makes it less green, never more) is raised to the
+/// less green of them, so one odd month does not make a season; the greenest month stays as it was.
+///
+internal sealed class GreennessYear
+{
+ /// The middle of a month, in days of the year.
+ private const double MonthDays = 365.0 / 12;
+
+ /// The most months that may be missing: they are filled from the months either side.
+ public const int MaxMissing = 3;
+
+ private readonly double[] _months;
+
+ private GreennessYear(double[] months)
+ {
+ _months = months;
+ Low = months.Min();
+ Peak = months.Max();
+ }
+
+ /// The least green month (often the snow or the dry season).
+ public double Low { get; }
+
+ /// The greenest month (most aerial photos show the place about then).
+ public double Peak { get; }
+
+ /// How much the greenness changes through the year: about 0.05 for a town or an evergreen jungle, 0.5 or more for snowy fields and broadleaf forest.
+ public double Range => Peak - Low;
+
+ ///
+ /// A year from twelve monthly values, January first; for a month without data. Null when more
+ /// than months are missing.
+ ///
+ public static GreennessYear? From(ReadOnlySpan months)
+ {
+ if (months.Length != 12) throw new ArgumentException("A year has twelve months", nameof(months));
+ int missing = 0;
+ foreach (double m in months)
+ if (double.IsNaN(m)) missing++;
+ if (missing > MaxMissing) return null;
+ double[] filled = Filled(months);
+ double[] even = new double[12];
+ for (int m = 0; m < 12; m++)
+ even[m] = Math.Max(filled[m], Math.Min(filled[(m + 11) % 12], filled[(m + 1) % 12]));
+ return new GreennessYear(even);
+ }
+
+ /// The greenness on a day of the year (0 is 1 January), between the middles of the months either side.
+ public double At(double day)
+ {
+ double t = ((day - MonthDays / 2) / MonthDays % 12 + 12) % 12;
+ int month = (int)t;
+ double f = t - month;
+ return _months[month] + (_months[(month + 1) % 12] - _months[month]) * f;
+ }
+
+ /// The greenness on a day as a share of the greenest month's, 0 to 1; 1 when the place is never green.
+ public double ShareOfPeak(double day) => Peak <= 0 ? 1 : Math.Clamp(At(day) / Peak, 0, 1);
+
+ /// The months with each missing one drawn between the nearest months that have data, around the year's end too.
+ private static double[] Filled(ReadOnlySpan months)
+ {
+ double[] filled = months.ToArray();
+ for (int m = 0; m < 12; m++)
+ {
+ if (!double.IsNaN(months[m])) continue;
+ int back = 1, ahead = 1;
+ while (double.IsNaN(months[(m - back + 12) % 12])) back++;
+ while (double.IsNaN(months[(m + ahead) % 12])) ahead++;
+ double a = months[(m - back + 12) % 12], b = months[(m + ahead) % 12];
+ filled[m] = a + (b - a) * back / (back + ahead);
+ }
+ return filled;
+ }
+}
diff --git a/src/OrthoStreamXP/Textures/Seasons/ObservedSeason.cs b/src/OrthoStreamXP/Textures/Seasons/ObservedSeason.cs
new file mode 100644
index 0000000..4fe6e83
--- /dev/null
+++ b/src/OrthoStreamXP/Textures/Seasons/ObservedSeason.cs
@@ -0,0 +1,40 @@
+namespace OrthoStreamXP.Textures;
+
+///
+/// The season at a place by its satellite record () as well as by the calendar.
+///
+/// The trees keep the calendar's colours and times (): a month's greenness over 1 km of mixed
+/// country is mostly its fields and its snow, and cannot tell when the trees leaf out (Wrocław's winter crops and late
+/// crop growth would put its spring five weeks late).
+///
+///
+/// Grass and fields go by the record: as green as in the place's greenest month (when most photos are taken), they stay
+/// green; much less green, they rest (olive and straw). So a coast green all winter (Brittany: January 85% of June)
+/// stays green, a snowy or ploughed winter (Warsaw: 7%) rests fully, and a dry summer or the tropics' dry season shows
+/// as it was, where the calendar has nothing or the opposite. A place with little vegetation even at its greenest (a
+/// town, rock, sand) keeps the calendar.
+///
+///
+internal static class ObservedSeason
+{
+ /// The season on a day at a place with this record (its strength not yet applied).
+ /// 0 is 1 January.
+ public static SeasonState For(GreennessYear year, int dayOfYear, double lat)
+ {
+ SeasonState calendar = SeasonModel.For(dayOfYear, lat);
+ double sure = Vegetated(year);
+ if (sure <= 0) return calendar;
+ return calendar with { Dormant = calendar.Dormant + (Resting(year, dayOfYear) - calendar.Dormant) * sure };
+ }
+
+ /// How much the grass and fields rest on a day, 0 to 1: none at 90% or more of the greenest month, fully at 60% or less.
+ public static double Resting(GreennessYear year, double dayOfYear) => 1 - SeasonModel.Smooth(0.6, 0.9, year.ShareOfPeak(dayOfYear));
+
+ /// 0 to 1: how much the record is of vegetation, by its greenest month (a town about 0.2, fields and forest 0.5 to 0.9).
+ public static double Vegetated(GreennessYear year) => SeasonModel.Smooth(0.25, 0.45, year.Peak);
+
+ /// "85% as green as in its greenest month: grass resting 7%", for the colour preview.
+ public static string Describe(GreennessYear year, double dayOfYear) => Vegetated(year) <= 0
+ ? "too little vegetation here to tell: the calendar's season"
+ : FormattableString.Invariant($"{year.ShareOfPeak(dayOfYear) * 100:0}% as green as in its greenest month: grass and fields resting {Resting(year, dayOfYear) * 100:0}%");
+}
diff --git a/src/OrthoStreamXP/Textures/Seasons/SeasonChoice.cs b/src/OrthoStreamXP/Textures/Seasons/SeasonChoice.cs
index 573c2c6..26bfcca 100644
--- a/src/OrthoStreamXP/Textures/Seasons/SeasonChoice.cs
+++ b/src/OrthoStreamXP/Textures/Seasons/SeasonChoice.cs
@@ -3,10 +3,14 @@
namespace OrthoStreamXP.Textures;
-/// A season chosen by hand instead of X-Plane's date.
+///
+/// How the season is chosen: by X-Plane's date (), by X-Plane's date with each place's grass and fields
+/// as its satellite record shows them (), or by hand, the same everywhere.
+///
internal enum SeasonChoice
{
Auto,
+ Satellite,
EarlySpring,
Spring,
Summer,
diff --git a/src/OrthoStreamXP/Textures/Seasons/SeasonModel.cs b/src/OrthoStreamXP/Textures/Seasons/SeasonModel.cs
index 90af108..0aedc13 100644
--- a/src/OrthoStreamXP/Textures/Seasons/SeasonModel.cs
+++ b/src/OrthoStreamXP/Textures/Seasons/SeasonModel.cs
@@ -22,6 +22,7 @@ internal static class SeasonModel
["autumn"] = SeasonChoice.Autumn,
["late-autumn"] = SeasonChoice.LateAutumn,
["winter"] = SeasonChoice.Winter,
+ ["satellite"] = SeasonChoice.Satellite,
};
/// 0 is 1 January, as X-Plane's sim/time/local_date_days.
diff --git a/src/OrthoStreamXP/Textures/Seasons/Seasons.cs b/src/OrthoStreamXP/Textures/Seasons/Seasons.cs
index 5e8002c..6608586 100644
--- a/src/OrthoStreamXP/Textures/Seasons/Seasons.cs
+++ b/src/OrthoStreamXP/Textures/Seasons/Seasons.cs
@@ -1,11 +1,10 @@
-using System.Collections.Concurrent;
-
namespace OrthoStreamXP.Textures;
///
/// Seasonal colour for the imagery, applied to the BC1 blocks of a DDS as X-Plane reads it: each 4 x 4 block is two
/// colours and a blend between them per pixel, so recolouring the two colours recolours the block. A BC1 colour has
-/// 65,536 values, so a season is one lookup table, and a 64 KB read takes microseconds. The cache keeps the imagery as
+/// 65,536 values, so a season is made into one lookup table with the other adjustments (),
+/// and a 64 KB read takes microseconds. The cache keeps the imagery as
/// downloaded; a season, a strength or switching it off never costs a download.
///
/// The change is a smooth function of colour alone, so it has no mask edges: greens (vegetation) move with the season,
@@ -15,37 +14,14 @@ namespace OrthoStreamXP.Textures;
///
internal static class Seasons
{
- private static readonly ConcurrentDictionary Tables = new();
-
- /// The lookup table of a season, or null when it changes nothing, shared by every texture.
- public static ushort[]? TableFor(SeasonState state)
- {
- if (state.IsSummer) return null;
- int key = StateKey(state);
- if (Tables.TryGetValue(key, out ushort[]? table)) return table;
- if (Tables.Count > 1024) Tables.Clear();
- return Tables.GetOrAdd(key, _ => Build(Quantised(state)));
- }
-
/// A season quantised to 1/32: neighbouring textures share a table, and a season is still a smooth change.
- private static int StateKey(SeasonState state) => (Q(state.Spring) << 18) | (Q(state.Autumn) << 12) | (Q(state.Bare) << 6) | Q(state.Dormant);
+ internal static int StateKey(SeasonState state) => (Q(state.Spring) << 18) | (Q(state.Autumn) << 12) | (Q(state.Bare) << 6) | Q(state.Dormant);
- private static SeasonState Quantised(SeasonState state) => new(Q(state.Spring) / 32.0, Q(state.Autumn) / 32.0, Q(state.Bare) / 32.0, Q(state.Dormant) / 32.0);
+ /// The season a table of is made for.
+ internal static SeasonState Quantised(SeasonState state) => new(Q(state.Spring) / 32.0, Q(state.Autumn) / 32.0, Q(state.Bare) / 32.0, Q(state.Dormant) / 32.0);
private static int Q(double v) => (int)Math.Round(Math.Clamp(v, 0, 1) * 32);
- private static ushort[] Build(SeasonState state)
- {
- var table = new ushort[65536];
- for (int c = 0; c < table.Length; c++)
- {
- var (r, g, b) = ColourTable.Decode565(c);
- var (r2, g2, b2) = Recolor(r, g, b, state);
- table[c] = (ushort)ColourTable.Encode565(r2, g2, b2);
- }
- return table;
- }
-
/// One colour (0-255 per channel) in a season.
internal static (double R, double G, double B) Recolor(double r, double g, double b, SeasonState s)
{
diff --git a/src/OrthoStreamXP/Textures/Sharpening.cs b/src/OrthoStreamXP/Textures/Sharpening.cs
new file mode 100644
index 0000000..6e3f605
--- /dev/null
+++ b/src/OrthoStreamXP/Textures/Sharpening.cs
@@ -0,0 +1,131 @@
+using System.Buffers;
+
+namespace OrthoStreamXP.Textures;
+
+///
+/// The sharpening of the photos as a texture is built, before its smaller levels and BC1: an unsharp mask on the
+/// brightness (a Gaussian of 1 px), its change added to red, green and blue alike so edges get no colour fringes. The
+/// strength is of a scale whose 100 % is an amount of 1.5, fixed by the kind of texture: the wide areas' (ZL16, from
+/// coarser imagery) at 100 %, the airports' (ZL18 and finer) at 60 %: roofs, field edges and tree crowns crisper, no
+/// visible halos (the samples of 2026-11-18). Integer arithmetic, in place, in bands of rows.
+///
+internal static class Sharpening
+{
+ /// The strength of the wide areas' textures (below ZL18), of the scale whose 100 % is an unsharp-mask amount of 1.5.
+ public const double AreaStrength = 1.0;
+
+ /// The strength of the airports' textures (ZL18 and finer): their finer imagery needs less.
+ public const double AirportStrength = 0.6;
+
+ /// The strength for a texture of .
+ public static double StrengthFor(int fileZoom) => TextureResolution.IsAirport(fileZoom) ? AirportStrength : AreaStrength;
+
+ /// The unsharp-mask amount of 100 % strength.
+ private const double FullAmount = 1.5;
+
+ /// The Gaussian (sigma 1 px) over 7 pixels, in 1/1024.
+ private static readonly int[] Kernel = [5, 55, 248, 408, 248, 55, 5];
+
+ private const int Radius = 3, Taps = 2 * Radius + 1, KernelShift = 10;
+
+ /// Rows per band a worker sharpens at a time.
+ private const int BandRows = 64;
+
+ /// Sharpens a tightly packed RGB image in place at (0 to 1, see ).
+ public static void Apply(byte[] rgb, int width, int height, int workers, double strength)
+ {
+ if (rgb.Length < width * height * 3) throw new ArgumentException("The image is smaller than its size", nameof(rgb));
+ ArgumentOutOfRangeException.ThrowIfLessThan(strength, 0);
+ ArgumentOutOfRangeException.ThrowIfGreaterThan(strength, 1);
+ int amount = (int)Math.Round(FullAmount * strength * 256); // in 1/256: 60 % = 230, 100 % = 384
+ if (width < 1 || height < 1 || amount == 0) return;
+ byte[] luma = ArrayPool.Shared.Rent(width * height);
+ try
+ {
+ // The brightness of every pixel first: a band changes its own rows while its neighbours still read theirs.
+ int bands = (height + BandRows - 1) / BandRows;
+ ForEach(bands, workers, band =>
+ {
+ for (int y = band * BandRows, end = Math.Min(height, y + BandRows); y < end; y++)
+ for (int x = 0, i = y * width; x < width; x++, i++)
+ luma[i] = (byte)((54 * rgb[i * 3] + 183 * rgb[i * 3 + 1] + 19 * rgb[i * 3 + 2] + 128) >> 8);
+ });
+ ForEach(bands, workers, band => Band(rgb, luma, width, height, band * BandRows, Math.Min(height, (band + 1) * BandRows), amount));
+ }
+ finally
+ {
+ ArrayPool.Shared.Return(luma);
+ }
+ }
+
+ private static void ForEach(int count, int workers, Action body)
+ {
+ if (workers <= 1 || count == 1)
+ for (int i = 0; i < count; i++) body(i);
+ else
+ Parallel.For(0, count, new ParallelOptions { MaxDegreeOfParallelism = workers }, body);
+ }
+
+ /// Rows to : the vertical pass over a ring of 7 horizontally blurred rows.
+ private static void Band(byte[] rgb, byte[] luma, int width, int height, int first, int end, int amount)
+ {
+ int[] ring = ArrayPool.Shared.Rent(Taps * width);
+ Span held = stackalloc int[Taps];
+ held.Fill(-1);
+ try
+ {
+ for (int y = first; y < end; y++)
+ {
+ for (int d = -Radius; d <= Radius; d++)
+ {
+ int source = Math.Clamp(y + d, 0, height - 1), slot = source % Taps;
+ if (held[slot] == source) continue;
+ Horizontal(luma.AsSpan(source * width, width), ring.AsSpan(slot * width, width));
+ held[slot] = source;
+ }
+ Sharpen(rgb, luma, ring, width, height, y, amount);
+ }
+ }
+ finally
+ {
+ ArrayPool.Shared.Return(ring);
+ }
+ }
+
+ /// One row of brightness blurred along the row, in 1/1024; the edges repeat their last pixel.
+ private static void Horizontal(ReadOnlySpan row, Span blurred)
+ {
+ int width = row.Length;
+ for (int x = 0; x < width; x++)
+ {
+ int sum = 0;
+ if (x >= Radius && x < width - Radius)
+ for (int k = 0; k < Taps; k++) sum += Kernel[k] * row[x - Radius + k];
+ else
+ for (int k = 0; k < Taps; k++) sum += Kernel[k] * row[Math.Clamp(x - Radius + k, 0, width - 1)];
+ blurred[x] = sum;
+ }
+ }
+
+ /// Row : each pixel moved away from its blurred brightness by the amount (in 1/256), red, green and blue alike.
+ private static void Sharpen(byte[] rgb, byte[] luma, int[] ring, int width, int height, int y, int amount)
+ {
+ Span offsets = stackalloc int[Taps];
+ for (int d = -Radius; d <= Radius; d++) offsets[d + Radius] = Math.Clamp(y + d, 0, height - 1) % Taps * width;
+ int rowStart = y * width;
+ for (int x = 0; x < width; x++)
+ {
+ int blurred = 0; // in 1/2^20
+ for (int k = 0; k < Taps; k++) blurred += Kernel[k] * ring[offsets[k] + x];
+ int difference = (luma[rowStart + x] << (2 * KernelShift)) - blurred;
+ int delta = (int)(((long)difference * amount + (1L << (2 * KernelShift + 7))) >> (2 * KernelShift + 8));
+ if (delta == 0) continue;
+ int at = (rowStart + x) * 3;
+ rgb[at] = Clamp(rgb[at] + delta);
+ rgb[at + 1] = Clamp(rgb[at + 1] + delta);
+ rgb[at + 2] = Clamp(rgb[at + 2] + delta);
+ }
+ }
+
+ private static byte Clamp(int value) => (byte)Math.Clamp(value, 0, 255);
+}
diff --git a/src/OrthoStreamXP/Textures/TextureBuilder.cs b/src/OrthoStreamXP/Textures/TextureBuilder.cs
index 54217a1..1659784 100644
--- a/src/OrthoStreamXP/Textures/TextureBuilder.cs
+++ b/src/OrthoStreamXP/Textures/TextureBuilder.cs
@@ -8,13 +8,16 @@ internal sealed record BuildResult(
double DownloadS, double FetchStitchS, double ResizeS, double MipmapS, double BC1EncodeS,
double EncodeS, double WriteS, double TotalS);
-/// Builds DDS textures from source tiles: fetch, stitch, resize, mipmaps, BC1, atomic write.
-internal sealed class TextureBuilder(TileSource tiles, int encoderWorkers)
+/// Builds DDS textures from source tiles: fetch, stitch, resize, sharpen, mipmaps, BC1, atomic write.
+/// The pictures streamed builds work in (default: ).
+internal sealed class TextureBuilder(TileSource tiles, int encoderWorkers, BuildBufferPool? buffers = null)
{
public int EncoderWorkers { get; } = Math.Clamp(encoderWorkers, 1, 16);
public TileSource Source => tiles;
+ public BuildBufferPool Buffers { get; } = buffers ?? new BuildBufferPool(BuildBufferPool.DefaultCapacityBytes);
+
///
/// Builds from tiles at (file zoom + ).
/// > 0 lowers the fetch zoom further for a fast provisional image.
@@ -40,7 +43,7 @@ public async Task BuildAsync(string textureName, int size, string d
double encodeStarted = total.Elapsed.TotalSeconds;
var resize = Stopwatch.StartNew();
- byte[] baseImage = ResizeTo(stitched, stitchedSize, size);
+ byte[] baseImage = PictureAt(stitched, stitchedSize, size, name);
resize.Stop();
byte[] dds = Dds.Encode(baseImage, size, size, EncoderWorkers, out double mipmapS, out double bc1S);
double writeS = AtomicFile.Write(destination, dds);
@@ -58,15 +61,15 @@ public async Task BuildChainAsync(TextureName name, DdsLayout layout, in
int size = layout.SizeOf(firstMip);
using IDisposable buildScope = tiles.BeginBuild();
// The stitched picture lives only for this build: pooled, so builds reuse it instead of each leaving up to
- // 48 MB of large object behind.
+ // 192 MB of large object behind.
var (image, imageSize, pooled) = await FetchRegionAsync(name, zoom, size, ticket, stats, pool: true).ConfigureAwait(false);
try
{
- return Dds.EncodeChain(ResizeTo(image, imageSize, size), layout, firstMip, EncoderWorkers);
+ return Dds.EncodeChain(PictureAt(image, imageSize, size, name), layout, firstMip, EncoderWorkers, Buffers);
}
finally
{
- if (pooled) ArrayPool.Shared.Return(image);
+ if (pooled) Buffers.Return(image);
}
}
@@ -83,8 +86,7 @@ public async Task BuildChainAsync(TextureName name, DdsLayout layout, in
}
///
- /// Stitch into an array from (it may be longer than the image); when the result
- /// says Pooled, the caller returns it there once done.
+ /// Stitch into an array from ; when the result says Pooled, the caller returns it there once done.
///
private async Task<(byte[] Rgb, int Size, bool Pooled)> FetchRegionAsync(TextureName name, int zoom, int size, FetchTicket ticket, TileStats stats, bool pool)
{
@@ -114,7 +116,7 @@ public async Task BuildChainAsync(TextureName name, DdsLayout layout, in
}
int length = stitchedSize * stitchedSize * 3;
// Every pixel is written by a tile, so a pooled array needs no clearing.
- byte[] stitched = pool ? ArrayPool.Shared.Rent(length) : new byte[length];
+ byte[] stitched = pool ? Buffers.Rent(length) : new byte[length];
try
{
var jobs = new Task[span * span];
@@ -124,7 +126,7 @@ public async Task BuildChainAsync(TextureName name, DdsLayout layout, in
}
catch
{
- if (pool) ArrayPool.Shared.Return(stitched);
+ if (pool) Buffers.Return(stitched);
throw;
}
return (stitched, stitchedSize, pool);
@@ -173,6 +175,18 @@ public bool StoreHasRegion(TextureName name, int zoom)
return true;
}
+ ///
+ /// A texture's picture at , what its levels are made from: , then
+ /// sharpened as 's kind of texture is (). An image already
+ /// that size is sharpened in place.
+ ///
+ public byte[] PictureAt(byte[] image, int imageSize, int size, TextureName name)
+ {
+ byte[] picture = ResizeTo(image, imageSize, size);
+ Sharpening.Apply(picture, size, size, EncoderWorkers, Sharpening.StrengthFor(name.Zoom));
+ return picture;
+ }
+
/// Stretches a square image to : bicubic up, box-halving and bicubic down.
public byte[] ResizeTo(byte[] image, int imageSize, int size) =>
imageSize == size ? image
@@ -190,6 +204,26 @@ public byte[] ResizeTop(byte[] image, int imageSize, int size, int rows) =>
private static int Shift(int value, int shift) => shift >= 0 ? value << shift : value >> -shift;
+ /// Zooms up a missing tile may be made from.
+ private const int MaxParentDepth = 4;
+
+ ///
+ /// A tile no provider has, made from the nearest coarser tile at hand (RAM or the low-zoom base; nothing is
+ /// downloaded): its part of that tile, stretched. Never coarser than the base's zoom 13, Bing's coarser zooms being
+ /// other imagery. Null when there is none.
+ ///
+ private (byte[] Pixels, int Zoom)? FromParent(int x, int y, int zoom)
+ {
+ for (int depth = 1; depth <= MaxParentDepth && zoom - depth >= TileStore.DefaultMaxZoom; depth++)
+ {
+ if (tiles.TryGetStored(x >> depth, y >> depth, zoom - depth) is not { } parent) continue;
+ int part = Tiles.TilePx >> depth, mask = (1 << depth) - 1;
+ byte[] crop = Crop(parent, Tiles.TilePx, (x & mask) * part, (y & mask) * part, part);
+ return (Images.ResizeBicubic(crop, part, part, Tiles.TilePx, Tiles.TilePx, 1), zoom - depth);
+ }
+ return null;
+ }
+
private static byte[] Crop(byte[] tile, int tileSize, int left, int top, int size)
{
byte[] part = new byte[size * size * 3];
@@ -201,15 +235,44 @@ private static byte[] Crop(byte[] tile, int tileSize, int left, int top, int siz
private async Task CopyTileAsync(int column, int row, int originX, int originY, int zoom, FetchTicket ticket,
byte[] destination, int width, int tilePx, TileStats stats)
{
- byte[] pixels = await tiles.GetTileAsync(originX + column, originY + row, zoom, ticket, stats).ConfigureAwait(false);
- int px = Tiles.TilePx;
- while (px > tilePx)
+ int tileX = originX + column, tileY = originY + row;
+ SourceTile tile;
+ try
+ {
+ tile = await tiles.GetSourceTileAsync(tileX, tileY, zoom, ticket, stats).ConfigureAwait(false);
+ }
+ catch (TileNotAvailableException) when (FromParent(tileX, tileY, zoom) is { } parent)
+ {
+ // No provider has this tile (a network failure is not caught: the texture is built again later instead).
+ tile = SourceTile.FromRgb(parent.Pixels);
+ Interlocked.Increment(ref stats.FromParents);
+ Log.Detail($"Tile {zoom}/{tileX}/{tileY} has no imagery: made from its zoom {parent.Zoom} tile");
+ }
+
+ // The pixels and their smaller versions take turns in two pooled buffers: a new 192 KB array per tile is a
+ // large object, collected only in full collections.
+ byte[] full = ArrayPool.Shared.Rent(Tiles.TileBytes);
+ byte[]? half = null;
+ try
+ {
+ tile.CopyPixelsTo(full);
+ byte[] pixels = full;
+ int px = Tiles.TilePx;
+ while (px > tilePx)
+ {
+ byte[] next = pixels == full ? half ??= ArrayPool.Shared.Rent(Tiles.TileBytes / 4) : full;
+ MipFilter.HalfInto(pixels, px, px, next, 1); // in linear light, as the mip levels below it
+ pixels = next;
+ px >>= 1;
+ }
+ int rowBytes = px * 3, left = column * px, top = row * px;
+ for (int y = 0; y < px; y++)
+ Buffer.BlockCopy(pixels, y * rowBytes, destination, ((top + y) * width + left) * 3, rowBytes);
+ }
+ finally
{
- pixels = Images.BoxHalf(pixels, px, px, 1);
- px >>= 1;
+ ArrayPool.Shared.Return(full);
+ if (half is not null) ArrayPool.Shared.Return(half);
}
- int rowBytes = px * 3, left = column * px, top = row * px;
- for (int y = 0; y < px; y++)
- Buffer.BlockCopy(pixels, y * rowBytes, destination, ((top + y) * width + left) * 3, rowBytes);
}
}
diff --git a/src/OrthoStreamXP/Textures/TextureQuality.cs b/src/OrthoStreamXP/Textures/TextureQuality.cs
index 2c18c14..d34f3b1 100644
--- a/src/OrthoStreamXP/Textures/TextureQuality.cs
+++ b/src/OrthoStreamXP/Textures/TextureQuality.cs
@@ -4,44 +4,73 @@
namespace OrthoStreamXP.Textures;
///
-/// How each texture is built from the level-change setting. The zoom depends on the texture's own zoom: ZL18 textures (around
-/// airports) use 18 + level, ZL16 textures one level finer up to level 0, 16 + (level + 1), so at the same setting the
-/// wide ZL16 areas are not left much softer than the airports; above level 0 they use 16 + level (Extra +1: zoom 17,
-/// as Ultra, while the airports get zoom 19). Other zooms use zoom + level.
+/// How each texture is built from the level-change setting. Each level downloads fixed zooms ():
+/// one for the wide areas' textures (ZL16, and ZL17 in finer packages) and one for the airports' (ZL18 and finer):
+/// Balanced 15/16, Sharp 16/17, Ultra 17/18, Extra 17/19, whatever the zoom in the package's file names.
///
-/// The size follows the level too: 4096 px at level 0 and above, half per level below (Balanced -2: 1024, Sharp -1:
-/// 2048, Ultra 0 and Extra +1: 4096), the same for ZL16 and ZL18. Below level 0 ZL16 textures download one zoom more
-/// detail than that, and at level +1 ZL18 ones do, shrunk as it arrives: the finer imagery gives a cleaner picture than
-/// the size alone would.
+/// The size is the detail the tiles hold at : 4096 px when the download zoom is the
+/// file's own (16 x 16 tiles), twice as much one zoom finer, half per zoom coarser. ZL16 textures: Balanced 2048, Sharp
+/// 4096, Ultra and Extra 8192; ZL18 textures: Balanced 1024, Sharp 2048, Ultra 4096, Extra 8192; a ZL17/ZL19 package's
+/// textures are half of those sizes, from the same imagery. A lower halves the textures from the
+/// same tiles (Ultra at Medium: ZL16 4096 px from zoom 17, ZL18 still 4096 px).
///
///
+/// One of the levels: the presets' -2..1 (the settings accept only these), or -3/-4 (quick test builds).
/// A size limit instead of the level's own (tests of the streaming engine at full detail).
internal sealed partial record TexturePlan(int LevelChange, int? Limit = null)
{
- /// Finer than the downloaded 4096 px detail at the file zoom; BuildAsync accepts up to +3.
+ /// Levels finer than the file zoom; BuildAsync accepts up to +3.
public const int MaxLevel = 3;
- /// The largest texture at this level.
- public int SizeLimit => Limit ?? TextureSizing.LimitFor(LevelChange);
+ ///
+ /// The zooms each level downloads: (the areas' textures, below ZL18; the airports', ZL18 and finer). -3 and -4 are no
+ /// preset and the settings refuse them: they are coarse, quick builds for the tests.
+ ///
+ private static readonly Dictionary Zooms = new()
+ {
+ [-4] = (13, 14),
+ [-3] = (14, 15),
+ [-2] = (15, 16), // Balanced
+ [-1] = (16, 17), // Sharp
+ [0] = (17, 18), // Ultra
+ [1] = (17, 19), // Extra
+ };
+
+ public int LevelChange { get; } = Zooms.ContainsKey(LevelChange) ? LevelChange
+ : throw new ArgumentOutOfRangeException(nameof(LevelChange), LevelChange, "No texture zooms for this level");
+
+ /// Whether a level has its texture zooms (the presets' -2..1, and the tests' -3/-4).
+ public static bool IsKnownLevel(int levelChange) => Zooms.ContainsKey(levelChange);
+
+ /// How much the textures are shrunk from the detail their tiles hold (the preset's resolution setting).
+ public TextureResolution Resolution { get; init; } = TextureResolution.Full;
- /// The level change applied to a texture of .
- public int LevelFor(int fileZoom) => Math.Clamp(LevelChange + (fileZoom == 16 && LevelChange < 1 ? 1 : 0), -4, MaxLevel);
+ /// The largest texture built: , or the explicit limit (tests).
+ public int SizeLimit => Limit ?? TextureSizing.MaxSize;
+
+ /// The zooms finer (positive) or coarser than its own that a texture of is downloaded at.
+ public int LevelFor(int fileZoom)
+ {
+ var (area, airport) = Zooms[LevelChange];
+ return Math.Clamp((TextureResolution.IsAirport(fileZoom) ? airport : area) - fileZoom, -4, MaxLevel);
+ }
/// The zoom its tiles are downloaded at.
public int FetchZoom(int fileZoom) => fileZoom + LevelFor(fileZoom);
- /// Its size in pixels: the downloaded detail, capped by the level's limit, never enlarged.
- public int SizeFor(int fileZoom) => Math.Min(TextureSizing.DownloadedDetail(LevelFor(fileZoom)), SizeLimit);
+ /// Its size in pixels: the downloaded detail shrunk by the resolution, capped by the size limit, never enlarged.
+ public int SizeFor(int fileZoom) => Math.Min(Resolution.SizeOf(TextureSizing.DownloadedDetail(LevelFor(fileZoom)), fileZoom), SizeLimit);
///
/// A texture's name in the cache: the row and column of its top-left tile at the zoom it is downloaded at, and that
/// zoom, such as 87520_143440_BI18 → 43760_71720_PX17 at level -1. The package's code is left out: it never chose
- /// the imagery. ZL17 keeps its package name: it is downloaded at the zoom of ZL16 (one level finer), where a ZL16
- /// texture twice as wide could start at the same tile.
+ /// the imagery. Only ZL16 and ZL18 textures get such a name; the others keep their package name: they are downloaded at
+ /// the zoom of ZL16 or ZL18 (ZL17 at the areas', ZL19 at the airports'), where a texture of a different width could
+ /// start at the same tile.
///
public string CacheStem(TextureName name)
{
- if (name.Zoom == 17) return name.Stem;
+ if (name.Zoom is not (16 or 18)) return name.Stem;
int level = LevelFor(name.Zoom);
return FormattableString.Invariant($"{Shift(name.Row, level)}_{Shift(name.Col, level)}_{TextureName.CacheCode}{FetchZoom(name.Zoom)}");
}
@@ -55,9 +84,9 @@ public string CacheStem(TextureName name)
|| !int.TryParse(m.Groups[2].Value, CultureInfo.InvariantCulture, out int col)
|| !int.TryParse(m.Groups[3].Value, CultureInfo.InvariantCulture, out int fetchZoom))
return null;
- for (int zoom = 4; zoom <= 22; zoom++)
+ foreach (int zoom in PackageZooms)
{
- if (zoom == 17 || FetchZoom(zoom) != fetchZoom) continue;
+ if (FetchZoom(zoom) != fetchZoom) continue;
int level = LevelFor(zoom);
if (TextureName.TryCreate(Shift(row, -level), Shift(col, -level), TextureName.CacheCode, zoom, out TextureName name)
&& CacheStem(name) == stem)
@@ -89,18 +118,16 @@ public string CacheStem(TextureName name)
internal static class TextureSizing
{
- /// The largest texture built.
- public const int MaxSize = 4096;
+ /// The largest texture built: a ZL16 texture from zoom 17, or a ZL18 one from zoom 19, at full detail.
+ public const int MaxSize = 8192;
- ///
- /// Pixels of detail level-change downloads for one texture: 4096 at the file's zoom (16 x 16 tiles of 256 px),
- /// half as much per level below. Above level 0 the detail is finer than 4096, so it is shrunk to 4096.
- ///
- public static int DownloadedDetail(int levelChange) => levelChange >= 0 ? MaxSize : MaxSize >> -levelChange;
+ /// Pixels across a texture at its file's own zoom: 16 x 16 tiles of 256 px.
+ public const int FileZoomDetail = 4096;
///
- /// The largest texture at a level: 4096 px at level 0 and above, half per level below. That is the detail a ZL18
- /// texture downloads, so ZL16 textures, fetched one level finer, are shrunk to the same size.
+ /// Pixels of detail a level change downloads for one texture: 4096 at the file's zoom, twice as much per level
+ /// finer, half per level coarser, up to .
///
- public static int LimitFor(int levelChange) => DownloadedDetail(levelChange);
+ public static int DownloadedDetail(int levelChange) =>
+ levelChange >= 0 ? FileZoomDetail << Math.Min(levelChange, 1) : FileZoomDetail >> -levelChange;
}
diff --git a/src/OrthoStreamXP/Textures/TextureResolution.cs b/src/OrthoStreamXP/Textures/TextureResolution.cs
new file mode 100644
index 0000000..0d6fcd8
--- /dev/null
+++ b/src/OrthoStreamXP/Textures/TextureResolution.cs
@@ -0,0 +1,35 @@
+namespace OrthoStreamXP.Textures;
+
+///
+/// How much a preset's textures are shrunk from the detail their tiles hold: Full keeps it; Medium halves the textures of
+/// the wide ZL16 areas and keeps the airports' ZL18 ones; Low halves them all (a quarter of the graphics memory). The
+/// imagery is downloaded at the same zoom, so a shrunk texture is the same picture with less detail, not coarser imagery.
+/// Only halving: X-Plane refuses a DDS whose size is not a power of two ("is DDS but its size is not power of 2").
+///
+/// The name in the settings file (resolution-<preset> = full, medium or low).
+/// The textures of the wide ZL16 (and coarser) areas are halved.
+/// The ZL18 (airport) textures are halved too, not only the ZL16 areas'.
+internal sealed record TextureResolution(string Value, string Label, bool HalvesAreas, bool HalvesAirports)
+{
+ public static readonly TextureResolution Full = new("full", "Full", HalvesAreas: false, HalvesAirports: false);
+ public static readonly TextureResolution Medium = new("medium", "Medium", HalvesAreas: true, HalvesAirports: false);
+ public static readonly TextureResolution Low = new("low", "Low", HalvesAreas: true, HalvesAirports: true);
+
+ public static IReadOnlyList All { get; } = [Full, Medium, Low];
+
+ public bool IsFull => !HalvesAreas && !HalvesAirports;
+
+ /// The resolution a settings value names (any case), or null for none.
+ public static TextureResolution? Parse(string? value) =>
+ All.FirstOrDefault(r => string.Equals(r.Value, value?.Trim(), StringComparison.OrdinalIgnoreCase));
+
+ ///
+ /// The size of a texture of whose tiles hold pixels across:
+ /// half of it where this resolution halves that zoom (ZL18 and finer are the airports'), never below 4 px.
+ ///
+ public int SizeOf(int fullSize, int fileZoom) =>
+ (IsAirport(fileZoom) ? HalvesAirports : HalvesAreas) ? Math.Max(4, fullSize / 2) : fullSize;
+
+ /// Textures of this zoom are the airports' (ZL18 and finer), not the wide areas' (ZL16).
+ public static bool IsAirport(int fileZoom) => fileZoom >= 18;
+}
diff --git a/src/OrthoStreamXP/Textures/Tiles/SourceTile.cs b/src/OrthoStreamXP/Textures/Tiles/SourceTile.cs
new file mode 100644
index 0000000..c67bbfb
--- /dev/null
+++ b/src/OrthoStreamXP/Textures/Tiles/SourceTile.cs
@@ -0,0 +1,34 @@
+namespace OrthoStreamXP.Textures;
+
+///
+/// A 256x256 source tile as it is kept in RAM: the image bytes as downloaded (a JPEG of some 20-40 KB), decoded only
+/// where its pixels are used. A decoded tile is 192 KB, a large object .NET collects only in full collections: a full-size
+/// texture's 1024 of them made some 190 MB of large-object garbage per build. The synthetic imagery keeps its pixels.
+///
+internal sealed class SourceTile
+{
+ private readonly byte[]? _encoded;
+ private readonly byte[]? _rgb;
+
+ private SourceTile(byte[]? encoded, byte[]? rgb) => (_encoded, _rgb) = (encoded, rgb);
+
+ /// An image file's bytes, already checked to decode ().
+ public static SourceTile FromEncoded(byte[] encoded) => new(encoded, null);
+
+ /// 256x256 RGB pixels.
+ public static SourceTile FromRgb(byte[] rgb) =>
+ rgb.Length == Tiles.TileBytes ? new(null, rgb) : throw new ArgumentException("Not a 256x256 RGB tile", nameof(rgb));
+
+ /// The bytes it takes in RAM.
+ public int Length => (_encoded ?? _rgb)!.Length;
+
+ /// Writes the tile's 256x256 RGB pixels into (a pooled buffer may be longer).
+ public void CopyPixelsTo(Span rgb)
+ {
+ if (_rgb is not null) _rgb.CopyTo(rgb);
+ else Images.DecodeTileInto(_encoded!, rgb);
+ }
+
+ /// The tile's 256x256 RGB pixels in an array of their own (the synthetic tile's own array, not to be changed).
+ public byte[] ToRgb() => _rgb ?? Images.DecodeTile(_encoded!);
+}
diff --git a/src/OrthoStreamXP/Textures/Tiles/TileNotAvailableException.cs b/src/OrthoStreamXP/Textures/Tiles/TileNotAvailableException.cs
new file mode 100644
index 0000000..b80e4ec
--- /dev/null
+++ b/src/OrthoStreamXP/Textures/Tiles/TileNotAvailableException.cs
@@ -0,0 +1,20 @@
+namespace OrthoStreamXP.Textures;
+
+///
+/// No provider has the tile, for good: each answered "not here" (404 or another client error, no imagery, outside its
+/// area), so asking again will not change it. A network failure is a plain instead.
+///
+internal sealed class TileNotAvailableException : IOException
+{
+ public TileNotAvailableException()
+ {
+ }
+
+ public TileNotAvailableException(string message) : base(message)
+ {
+ }
+
+ public TileNotAvailableException(string message, Exception? innerException) : base(message, innerException)
+ {
+ }
+}
diff --git a/src/OrthoStreamXP/Textures/Tiles/TileSource.cs b/src/OrthoStreamXP/Textures/Tiles/TileSource.cs
index 6844247..7bcd7b6 100644
--- a/src/OrthoStreamXP/Textures/Tiles/TileSource.cs
+++ b/src/OrthoStreamXP/Textures/Tiles/TileSource.cs
@@ -8,6 +8,8 @@ namespace OrthoStreamXP.Textures;
internal sealed class TileStats
{
public int Hits, Misses, Calls, Fallbacks;
+ /// Tiles no provider has, made from a coarser tile at hand ().
+ public int FromParents;
/// Bytes of the tiles downloaded for the build (every server answer, as the session's own count).
public long Bytes;
private long _downloadTicks;
@@ -79,7 +81,7 @@ public static IReadOnlyList ParseList(string list, string? cust
}
///
-/// Downloads and decodes 256x256 source tiles. Decoded tiles stay in a bounded RAM cache only while
+/// Downloads 256x256 source tiles. Tiles (as downloaded, see ) stay in a bounded RAM cache only while
/// builds are active, and concurrent requests for the same tile share one download. A tile the first
/// provider cannot supply is asked from the next one in the list. Downloads wait in one queue ordered by
/// ; tiles of the low-zoom base () are kept on disk for good.
@@ -95,7 +97,7 @@ private sealed class Pending(FetchTicket first)
{
private readonly List _tickets = [first];
- public required Task Task { get; init; }
+ public required Task Task { get; init; }
public void Join(FetchTicket ticket)
{
@@ -113,7 +115,7 @@ public int Priority()
private readonly HttpClient _http;
private readonly PriorityGate _gate;
private readonly Lock _cacheLock = new();
- private readonly Dictionary _cache = [];
+ private readonly Dictionary _cache = [];
private readonly Queue _cacheOrder = new();
private readonly Dictionary _inFlight = [];
private long _cacheBytes;
@@ -244,15 +246,22 @@ public Task GetTileAsync(int x, int y, int zoom, bool priority, TileStat
GetTileAsync(x, y, zoom, new FetchTicket(priority ? FetchPriority.Read : FetchPriority.Warm), stats);
/// A decoded 256x256 RGB tile, downloaded at the urgency of if it must be.
- public async Task GetTileAsync(int x, int y, int zoom, FetchTicket ticket, TileStats stats)
+ public async Task GetTileAsync(int x, int y, int zoom, FetchTicket ticket, TileStats stats) =>
+ (await GetSourceTileAsync(x, y, zoom, ticket, stats).ConfigureAwait(false)).ToRgb();
+
+ ///
+ /// The tile as kept (decoded where its pixels are used, ), downloaded at the
+ /// urgency of if it must be.
+ ///
+ public async Task GetSourceTileAsync(int x, int y, int zoom, FetchTicket ticket, TileStats stats)
{
string key = $"{zoom}/{x}/{y}";
Pending? shared;
- var mine = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ var mine = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var pending = new Pending(ticket) { Task = mine.Task };
lock (_cacheLock)
{
- if (_cache.TryGetValue(key, out byte[]? cached))
+ if (_cache.TryGetValue(key, out SourceTile? cached))
{
Interlocked.Increment(ref stats.Hits);
return cached;
@@ -268,10 +277,10 @@ public async Task GetTileAsync(int x, int y, int zoom, FetchTicket ticke
try
{
- byte[]? stored = Stored(x, y, zoom);
+ SourceTile? stored = Stored(x, y, zoom);
if (stored is not null) Interlocked.Increment(ref stats.Hits);
else Interlocked.Increment(ref stats.Misses);
- byte[] tile = stored ?? await DownloadAsync(x, y, zoom, pending, stats).ConfigureAwait(false);
+ SourceTile tile = stored ?? await DownloadAsync(x, y, zoom, pending, stats).ConfigureAwait(false);
lock (_cacheLock)
{
_inFlight.Remove(key);
@@ -296,17 +305,18 @@ public async Task GetTileAsync(int x, int y, int zoom, FetchTicket ticke
public byte[]? TryGetStored(int x, int y, int zoom)
{
lock (_cacheLock)
- if (_cache.TryGetValue($"{zoom}/{x}/{y}", out byte[]? cached)) return cached;
- return Stored(x, y, zoom);
+ if (_cache.TryGetValue($"{zoom}/{x}/{y}", out SourceTile? cached)) return cached.ToRgb();
+ return Stored(x, y, zoom)?.ToRgb();
}
- /// The tile decoded from the low-zoom base, or null (a damaged file is downloaded again).
- private byte[]? Stored(int x, int y, int zoom)
+ /// The tile from the low-zoom base, or null (a damaged file is downloaded again).
+ private SourceTile? Stored(int x, int y, int zoom)
{
if (IsSynthetic || Store?.TryRead(x, y, zoom) is not { } encoded) return null;
try
{
- return Images.DecodeTile(encoded);
+ Images.CheckTile(encoded);
+ return SourceTile.FromEncoded(encoded);
}
catch (InvalidDataException)
{
@@ -314,15 +324,16 @@ public async Task GetTileAsync(int x, int y, int zoom, FetchTicket ticke
}
}
- private async Task DownloadAsync(int x, int y, int zoom, Pending pending, TileStats stats)
+ private async Task DownloadAsync(int x, int y, int zoom, Pending pending, TileStats stats)
{
- if (IsSynthetic) return Images.SyntheticTile(x, y, zoom);
+ if (IsSynthetic) return SourceTile.FromRgb(Images.SyntheticTile(x, y, zoom));
await _gate.WaitAsync(pending.Priority).ConfigureAwait(false);
try
{
Exception? last = null;
- byte[]? placeholder = null; // a "no imagery here" picture, used when no provider has the tile
+ SourceTile? placeholder = null; // a "no imagery here" picture, used when no provider has the tile
var failures = new List();
+ bool forGood = true; // every provider said "not here" (no network trouble): asking again changes nothing
for (int p = 0; p < _providers.Count; p++)
{
ImageryProvider provider = _providers[p];
@@ -347,12 +358,13 @@ private async Task DownloadAsync(int x, int y, int zoom, Pending pending
Interlocked.Add(ref _bytesDownloaded, bytes.Length);
Interlocked.Add(ref stats.Bytes, bytes.Length);
Interlocked.Add(ref _tileTicks, Stopwatch.GetElapsedTime(started).Ticks);
- byte[] decoded = Images.DecodeTile(bytes); // rejects error pages and truncated data
+ Images.CheckTile(bytes); // rejects error pages and truncated data
+ var tile = SourceTile.FromEncoded(bytes);
stats.AddDownload(Stopwatch.GetElapsedTime(started));
// Bing answers a place without imagery with 200 and a placeholder picture, marked only by this header.
if (response.Headers.TryGetValues("X-VE-Tile-Info", out var info) && info.Contains("no-tile", StringComparer.OrdinalIgnoreCase))
{
- placeholder ??= decoded;
+ placeholder ??= tile;
last = new HttpRequestException("no imagery here (X-VE-Tile-Info: no-tile)", null, HttpStatusCode.NotFound);
break;
}
@@ -365,7 +377,7 @@ private async Task DownloadAsync(int x, int y, int zoom, Pending pending
}
if (p > 0) Interlocked.Increment(ref stats.Fallbacks);
if (Store?.Covers(zoom) == true) Store.Save(x, y, zoom, bytes); // never a placeholder
- return decoded;
+ return tile;
}
catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or IOException or InvalidDataException)
{
@@ -376,11 +388,13 @@ private async Task DownloadAsync(int x, int y, int zoom, Pending pending
}
if (attempt < _attempts - 1) await Task.Delay(Math.Min(2000, 250 << attempt)).ConfigureAwait(false);
}
+ if (last is null || !IsDefinitive(last)) forGood = false;
failures.Add(_providers.Count > 1 ? $"{provider.Name}: {last?.Message}" : last?.Message ?? "");
}
if (placeholder is not null) return placeholder;
Interlocked.Increment(ref _failedTiles);
- throw new IOException($"Failed downloading tile {zoom}/{x}/{y}: {string.Join("; ", failures)}", last);
+ string message = $"Failed downloading tile {zoom}/{x}/{y}: {string.Join("; ", failures)}";
+ throw forGood ? new TileNotAvailableException(message, last) : new IOException(message, last);
}
finally
{
@@ -402,13 +416,13 @@ internal static string Url(string template, int x, int y, int zoom, int server)
.Replace("{q}", Tiles.QuadKey(x, y, zoom))
.Replace("{s}", server.ToString(CultureInfo.InvariantCulture));
- private void AddToCache(string key, byte[] tile)
+ private void AddToCache(string key, SourceTile tile)
{
if (!_cache.TryAdd(key, tile)) return;
_cacheOrder.Enqueue(key);
_cacheBytes += tile.Length;
while (_cacheBytes > MaxCacheBytes && _cacheOrder.TryDequeue(out string? old))
- if (_cache.Remove(old, out byte[]? removed)) _cacheBytes -= removed.Length;
+ if (_cache.Remove(old, out SourceTile? removed)) _cacheBytes -= removed.Length;
}
private void ClearCache()
diff --git a/src/OrthoStreamXP/Textures/Tiles/TileStore.cs b/src/OrthoStreamXP/Textures/Tiles/TileStore.cs
index 4a38e0b..bc6d961 100644
--- a/src/OrthoStreamXP/Textures/Tiles/TileStore.cs
+++ b/src/OrthoStreamXP/Textures/Tiles/TileStore.cs
@@ -3,14 +3,19 @@
namespace OrthoStreamXP.Textures;
///
-/// Source tiles kept on disk for good: the low-zoom base (zoom 12 and coarser). One zoom 12 tile covers a whole
+/// Source tiles kept on disk for good: the low-zoom base (zoom 13 and coarser). Four zoom 13 tiles cover a whole
/// ZL16 texture, so far scenery is drawn from here at once, without a download, on every later flight. The base
/// is shared by every setup and package in the cache, and deleting a setup's textures leaves it in place.
-/// Tiles are kept as the provider sent them (JPEG or PNG), about 10-25 KB each.
+/// Tiles are kept as the provider sent them (JPEG or PNG), about 10-30 KB each.
///
+///
+/// Not zoom 12: Bing's zoom 12 and coarser are other imagery, lighter and yellower than its zoom 13 and finer (mean
+/// colour 31 steps off zoom 16 at 20 places, up to 110 in the Alps; zoom 13 is 2 off), so far levels and the colour
+/// matching's target made from it did not match the textures' detailed levels. Esri's zooms agree throughout.
+///
internal sealed class TileStore(string root, int maxZoom = TileStore.DefaultMaxZoom)
{
- public const int DefaultMaxZoom = 12;
+ public const int DefaultMaxZoom = 13;
/// The folder in the cache that holds the base.
public const string FolderName = ".orthostreamxp-base";
diff --git a/src/OrthoStreamXP/Textures/Tiles/Tiles.cs b/src/OrthoStreamXP/Textures/Tiles/Tiles.cs
index 12d18e9..00da8d1 100644
--- a/src/OrthoStreamXP/Textures/Tiles/Tiles.cs
+++ b/src/OrthoStreamXP/Textures/Tiles/Tiles.cs
@@ -9,6 +9,8 @@ namespace OrthoStreamXP.Textures;
internal static class Tiles
{
public const int TilePx = 256;
+ /// Bytes of one tile's RGB pixels.
+ public const int TileBytes = TilePx * TilePx * 3;
/// A texture is 16x16 source tiles (4096 px at its file zoom), as in the .ter files.
public const int TextureSpan = 16;
public const double MaxLat = 85.05112878;
diff --git a/src/OrthoStreamXP/Textures/Vegetation/NdviPalette.cs b/src/OrthoStreamXP/Textures/Vegetation/NdviPalette.cs
new file mode 100644
index 0000000..9ea0699
--- /dev/null
+++ b/src/OrthoStreamXP/Textures/Vegetation/NdviPalette.cs
@@ -0,0 +1,63 @@
+using System.Globalization;
+using System.Xml.Linq;
+
+namespace OrthoStreamXP.Textures;
+
+///
+/// The colours of NASA GIBS's vegetation index pictures and the greenness (NDVI) each stands for, from GIBS's colour
+/// map (ndvi-colormap.xml, MODIS_L3_NDVI, used by its MODIS and VIIRS NDVI layers alike): a picture's colours are
+/// classes 0.005 to 0.01 wide. Water, snow and bare rock (zero or below) count as 0; "no data" as nothing.
+///
+/// A place's greenness is kept as a byte (): 0 for no data, 1 to 251 for 0 to 1 in steps of 0.004.
+///
+///
+internal static class NdviPalette
+{
+ /// The byte of a place without data.
+ public const byte NoData = 0;
+
+ private static readonly Lazy> Colours = new(Load);
+
+ /// The greenness a byte stands for (not for ).
+ public static double ValueOf(byte code) => (code - 1) / 250.0;
+
+ /// The byte of a greenness; below 0 counts as 0.
+ public static byte CodeOf(double ndvi) => (byte)(1 + Math.Round(Math.Clamp(ndvi, 0, 1) * 250));
+
+ /// The greenness of a picture's colour: false for "no data" and for a colour not in the map.
+ public static bool TryValue(byte r, byte g, byte b, out double ndvi)
+ {
+ if (Colours.Value.TryGetValue(Key(r, g, b), out ndvi) && !double.IsNaN(ndvi)) return true;
+ ndvi = 0;
+ return false;
+ }
+
+ private static int Key(int r, int g, int b) => (r << 16) | (g << 8) | b;
+
+ /// Colour to greenness, the middle of each class; NaN for "no data".
+ private static Dictionary Load()
+ {
+ using Stream stream = typeof(NdviPalette).Assembly.GetManifestResourceStream("OrthoStreamXP.ndvi-colormap.xml")
+ ?? throw new InvalidOperationException("The vegetation colour map is missing from the program");
+ var colours = new Dictionary();
+ foreach (XElement entry in XDocument.Load(stream).Descendants("ColorMapEntry"))
+ {
+ int[] rgb = [.. ((string?)entry.Attribute("rgb") ?? "").Split(',').Select(c => int.Parse(c, CultureInfo.InvariantCulture))];
+ if (rgb.Length != 3) continue;
+ double value = (string?)entry.Attribute("nodata") == "true" ? double.NaN : Middle((string?)entry.Attribute("value") ?? "");
+ colours[Key(rgb[0], rgb[1], rgb[2])] = value;
+ }
+ return colours;
+ }
+
+ /// The middle of a class such as "[0.0501,0.0551)", at least 0.
+ private static double Middle(string range)
+ {
+ string[] ends = range.Trim('[', ']', '(', ')').Split(',');
+ return ends.Length == 2
+ && double.TryParse(ends[0], NumberStyles.Float, CultureInfo.InvariantCulture, out double low)
+ && double.TryParse(ends[1], NumberStyles.Float, CultureInfo.InvariantCulture, out double high)
+ ? Math.Max(0, (low + high) / 2)
+ : double.NaN;
+ }
+}
diff --git a/src/OrthoStreamXP/Textures/Vegetation/VegetationSource.cs b/src/OrthoStreamXP/Textures/Vegetation/VegetationSource.cs
new file mode 100644
index 0000000..005aed7
--- /dev/null
+++ b/src/OrthoStreamXP/Textures/Vegetation/VegetationSource.cs
@@ -0,0 +1,189 @@
+using System.Collections.Concurrent;
+using System.Globalization;
+using System.Net;
+
+namespace OrthoStreamXP.Textures;
+
+///
+/// The satellite record of how green each place was over the last year: NASA GIBS's monthly vegetation index
+/// (VIIRS on Suomi NPP, 1 km, free and without an account), one 512 x 512 picture a month for each
+/// tile, about 150 KB each. Each month is kept on disk as its cells
+/// (, 16 KB), so a place is downloaded once for the year.
+///
+/// The year is the latest twelve months NASA has finished: a month's picture appears some weeks after it ends. A
+/// month that is not there is taken from the year before.
+///
+///
+internal sealed class VegetationSource : IDisposable
+{
+ /// The folder in the low-zoom base that holds the record.
+ public const string FolderName = "vegetation";
+
+ /// NASA's layer.
+ public const string Layer = "VIIRS_SNPP_L3_NDVI_Monthly";
+
+ /// How long after a month NASA's picture of it is counted on.
+ private const int DaysToPublish = 40;
+
+ /// The leading bytes of a month's file.
+ private static readonly byte[] Magic = "OSXPNDV1"u8.ToArray();
+
+ private readonly string _folder;
+ private readonly TimeProvider _time;
+ private readonly HttpClient? _http;
+
+ /// Where the months are kept.
+ /// False: only what is already on disk (the Settings page's preview never downloads).
+ /// Replaces the network stack (tests).
+ public VegetationSource(string folder, TimeProvider time, bool download = true, HttpMessageHandler? handler = null)
+ {
+ _folder = Path.GetFullPath(folder);
+ _time = time;
+ if (!download) return;
+ _http = new HttpClient(handler ?? new SocketsHttpHandler { PooledConnectionLifetime = TimeSpan.FromMinutes(10), ConnectTimeout = TimeSpan.FromSeconds(10) })
+ {
+ Timeout = TimeSpan.FromSeconds(30),
+ };
+ _http.DefaultRequestHeaders.UserAgent.ParseAdd("orthostreamxp/1.0");
+ }
+
+ public string Folder => _folder;
+
+ /// Pictures downloaded this session.
+ public int Downloaded => Volatile.Read(ref _downloaded);
+
+ private int _downloaded;
+
+ /// The twelve months of the latest year NASA has finished, oldest first (each the first of its month).
+ public IReadOnlyList Year()
+ {
+ DateOnly published = DateOnly.FromDateTime(_time.GetUtcNow().UtcDateTime.AddDays(-DaysToPublish));
+ var last = new DateOnly(published.Year, published.Month, 1);
+ return [.. Enumerable.Range(0, 12).Select(i => last.AddMonths(i - 11))];
+ }
+
+ ///
+ /// A tile's year, from disk or downloaded; null when fewer than nine of its months could be had (offline, or NASA
+ /// unreachable). Problems are logged, never thrown.
+ ///
+ public async Task LoadAsync(VegetationKey key, CancellationToken cancel)
+ {
+ IReadOnlyList year = Year();
+ byte[]?[] months = new byte[]?[12];
+ var problems = new ConcurrentQueue();
+ Task[] loads = [.. year.Select(month => LoadMonthAsync(key, month, problems, cancel))];
+ await Task.WhenAll(loads).ConfigureAwait(false);
+ for (int i = 0; i < year.Count; i++) months[year[i].Month - 1] = await loads[i].ConfigureAwait(false);
+ if (!problems.IsEmpty)
+ Log.Warning($"Seasons: {problems.Count} month(s) of the satellite record for the tile with its {key} could not be downloaded " +
+ $"({problems.First()}); they are tried again at the next start");
+ var tile = new VegetationTile(key, months);
+ return tile.Months >= 12 - GreennessYear.MaxMissing ? tile : null;
+ }
+
+ /// Removes the months older than the year before the current one: the record moves on a month at a time.
+ public void RemoveOldMonths()
+ {
+ if (!Directory.Exists(_folder)) return;
+ string oldest = Name(Year()[0].AddMonths(-12));
+ foreach (string folder in Directory.EnumerateDirectories(_folder))
+ {
+ string name = Path.GetFileName(folder);
+ if (!DateOnly.TryParseExact(name, "yyyy-MM", CultureInfo.InvariantCulture, DateTimeStyles.None, out _)
+ || string.CompareOrdinal(name, oldest) >= 0) continue;
+ try
+ {
+ Directory.Delete(folder, recursive: true);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ Log.Warning($"Seasons: could not remove the old satellite record {folder}: {ex.Message}");
+ }
+ }
+ }
+
+ ///
+ /// A month's cells: kept on disk, else downloaded. When NASA has no picture of it, or cannot be reached (offline), the
+ /// same month a year before stands in: kept on disk, else downloaded if NASA answered.
+ ///
+ private async Task LoadMonthAsync(VegetationKey key, DateOnly month, ConcurrentQueue problems, CancellationToken cancel)
+ {
+ if (Read(PathOf(key, month)) is { } kept) return kept;
+ bool answered = false;
+ if (_http is not null)
+ {
+ (answered, byte[]? cells) = await DownloadAsync(key, month, problems, cancel).ConfigureAwait(false);
+ if (cells is not null) return cells;
+ }
+ DateOnly yearBefore = month.AddMonths(-12);
+ if (Read(PathOf(key, yearBefore)) is { } older) return older;
+ // Unreachable: not asked again for the year before.
+ return answered ? (await DownloadAsync(key, yearBefore, problems, cancel).ConfigureAwait(false)).Cells : null;
+ }
+
+ ///
+ /// Downloads and keeps a month: (true, cells), (true, null) when NASA has no such picture, (false, null) when it could
+ /// not be had (the reason added to ).
+ ///
+ private async Task<(bool Answered, byte[]? Cells)> DownloadAsync(VegetationKey key, DateOnly month, ConcurrentQueue problems, CancellationToken cancel)
+ {
+ Uri uri = UriOf(key, month);
+ try
+ {
+ using HttpResponseMessage response = await _http!.GetAsync(uri, cancel).ConfigureAwait(false);
+ if (response.StatusCode is HttpStatusCode.NotFound or HttpStatusCode.BadRequest) return (true, null);
+ response.EnsureSuccessStatusCode();
+ byte[] png = await response.Content.ReadAsByteArrayAsync(cancel).ConfigureAwait(false);
+ byte[] cells = VegetationTile.CellsOf(png);
+ Interlocked.Increment(ref _downloaded);
+ Save(PathOf(key, month), cells);
+ return (true, cells);
+ }
+ catch (Exception ex) when (ex is HttpRequestException or InvalidDataException || (ex is TaskCanceledException && !cancel.IsCancellationRequested))
+ {
+ problems.Enqueue(string.Create(CultureInfo.InvariantCulture, $"{month:MMMM yyyy}: {ex.Message}"));
+ return (false, null);
+ }
+ }
+
+ /// NASA's picture of a tile in a month.
+ public static Uri UriOf(VegetationKey key, DateOnly month) => new(string.Create(CultureInfo.InvariantCulture,
+ $"https://gibs.earthdata.nasa.gov/wmts/epsg4326/best/{Layer}/default/{month:yyyy-MM-dd}/1km/6/{key.Row}/{key.Col}.png"));
+
+ private string PathOf(VegetationKey key, DateOnly month) =>
+ Path.Join(_folder, Name(month), string.Create(CultureInfo.InvariantCulture, $"{key.Row}_{key.Col}.ndvi"));
+
+ private static string Name(DateOnly month) => month.ToString("yyyy-MM", CultureInfo.InvariantCulture);
+
+ private static byte[]? Read(string path)
+ {
+ if (!File.Exists(path)) return null;
+ try
+ {
+ byte[] file = File.ReadAllBytes(path);
+ if (file.Length == Magic.Length + VegetationTile.MonthBytes && file.AsSpan(0, Magic.Length).SequenceEqual(Magic))
+ return file[Magic.Length..];
+ Log.Warning($"Seasons: {path} is not a satellite record; it is downloaded again");
+ return null;
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ Log.Warning($"Seasons: could not read {path}: {ex.Message}");
+ return null;
+ }
+ }
+
+ private static void Save(string path, byte[] cells)
+ {
+ try
+ {
+ AtomicFile.Write(path, [.. Magic, .. cells]);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ Log.Warning($"Seasons: could not keep the satellite record in {path}: {ex.Message}");
+ }
+ }
+
+ public void Dispose() => _http?.Dispose();
+}
diff --git a/src/OrthoStreamXP/Textures/Vegetation/VegetationTile.cs b/src/OrthoStreamXP/Textures/Vegetation/VegetationTile.cs
new file mode 100644
index 0000000..7f75edb
--- /dev/null
+++ b/src/OrthoStreamXP/Textures/Vegetation/VegetationTile.cs
@@ -0,0 +1,132 @@
+using System.Globalization;
+using SkiaSharp;
+
+namespace OrthoStreamXP.Textures;
+
+///
+/// One tile of NASA GIBS's 1 km grid at its level 6 (EPSG:4326, 512 x 512 pixels): degrees square,
+/// 40 rows from the North Pole, 80 columns from 180° West.
+///
+internal readonly record struct VegetationKey(int Row, int Col)
+{
+ /// Degrees a tile spans: about 500 km north to south.
+ public const double Span = 4.5;
+
+ public double North => 90 - Row * Span;
+ public double West => -180 + Col * Span;
+
+ /// The tile a place is in.
+ public static VegetationKey At(double lat, double lon) =>
+ new((int)Math.Clamp(Math.Floor((90 - lat) / Span), 0, 180 / Span - 1), (int)Math.Clamp(Math.Floor((lon + 180) / Span), 0, 360 / Span - 1));
+
+ /// "north-west corner 54.0° N, 18.0° E".
+ public override string ToString() => string.Create(CultureInfo.InvariantCulture,
+ $"north-west corner {Math.Abs(North):0.0}° {(North >= 0 ? 'N' : 'S')}, {Math.Abs(West):0.0}° {(West >= 0 ? 'E' : 'W')}");
+}
+
+///
+/// A year of greenness (NDVI) over one tile: a month's picture averaged into
+/// x cells of about 4 km, a byte each (), January first.
+///
+internal sealed class VegetationTile
+{
+ /// Cells a side: 4 x 4 of the picture's pixels each, 3.9 km north to south.
+ public const int Cells = 128;
+
+ /// Pixels a side of NASA's picture.
+ public const int Pixels = 512;
+
+ /// Bytes of one month.
+ public const int MonthBytes = Cells * Cells;
+
+ private readonly byte[]?[] _months;
+
+ /// Twelve months of bytes, January first; null for a month without data.
+ public VegetationTile(VegetationKey key, byte[]?[] months)
+ {
+ if (months.Length != 12) throw new ArgumentException("A year has twelve months", nameof(months));
+ if (months.Any(m => m is not null && m.Length != MonthBytes)) throw new ArgumentException($"A month is {MonthBytes} bytes", nameof(months));
+ Key = key;
+ _months = months;
+ }
+
+ public VegetationKey Key { get; }
+
+ /// The months that have data.
+ public int Months => _months.Count(m => m is not null);
+
+ ///
+ /// The year at a place: its cell and the eight around it (about 12 km), each counted by how green it is at its greenest.
+ /// A town or a lake is never very green, so a place in one takes the season of the country around it.
+ /// Null where no cell has a year (the sea, or too many months missing).
+ ///
+ public GreennessYear? YearAt(double lat, double lon)
+ {
+ int cx = (int)Math.Clamp((lon - Key.West) / VegetationKey.Span * Cells, 0, Cells - 1);
+ int cy = (int)Math.Clamp((Key.North - lat) / VegetationKey.Span * Cells, 0, Cells - 1);
+ Span weights = stackalloc double[12], sums = stackalloc double[12], cell = stackalloc double[12];
+ weights.Clear();
+ sums.Clear();
+ for (int y = Math.Max(0, cy - 1); y <= Math.Min(Cells - 1, cy + 1); y++)
+ for (int x = Math.Max(0, cx - 1); x <= Math.Min(Cells - 1, cx + 1); x++)
+ {
+ int missing = 0;
+ double high = 0;
+ for (int m = 0; m < 12; m++)
+ {
+ byte code = _months[m]?[y * Cells + x] ?? NdviPalette.NoData;
+ cell[m] = code == NdviPalette.NoData ? double.NaN : NdviPalette.ValueOf(code);
+ if (double.IsNaN(cell[m])) missing++;
+ else high = Math.Max(high, cell[m]);
+ }
+ if (missing > GreennessYear.MaxMissing) continue;
+ double weight = high * high + 1e-4;
+ for (int m = 0; m < 12; m++)
+ {
+ if (double.IsNaN(cell[m])) continue;
+ weights[m] += weight;
+ sums[m] += weight * cell[m];
+ }
+ }
+ Span year = stackalloc double[12];
+ for (int m = 0; m < 12; m++) year[m] = weights[m] > 0 ? sums[m] / weights[m] : double.NaN;
+ return GreennessYear.From(year);
+ }
+
+ ///
+ /// A month's cells from NASA's picture (a 512 x 512 PNG in the colours of ): each cell the mean
+ /// of its 16 pixels that have data, or when fewer than 4 have.
+ ///
+ /// Not such a picture.
+ public static byte[] CellsOf(byte[] png)
+ {
+ using var data = SKData.CreateCopy(png);
+ using SKCodec codec = SKCodec.Create(data) ?? throw new InvalidDataException("Not a decodable picture");
+ if (codec.Info.Width != Pixels || codec.Info.Height != Pixels)
+ throw new InvalidDataException($"A vegetation picture is {Pixels} x {Pixels} pixels, not {codec.Info.Width} x {codec.Info.Height}");
+ // Unpremultiplied: the transparent colours (water and snow, "no data") keep their colour, which says which they are.
+ var info = new SKImageInfo(Pixels, Pixels, SKColorType.Rgba8888, SKAlphaType.Unpremul);
+ using var bitmap = new SKBitmap(info);
+ SKCodecResult result = codec.GetPixels(info, bitmap.GetPixels());
+ if (result != SKCodecResult.Success) throw new InvalidDataException($"Vegetation picture decode failed: {result}");
+ ReadOnlySpan rgba = bitmap.GetPixelSpan();
+ byte[] cells = new byte[MonthBytes];
+ const int step = Pixels / Cells;
+ for (int cy = 0; cy < Cells; cy++)
+ for (int cx = 0; cx < Cells; cx++)
+ {
+ double sum = 0;
+ int count = 0;
+ for (int py = cy * step; py < (cy + 1) * step; py++)
+ for (int px = cx * step; px < (cx + 1) * step; px++)
+ {
+ int at = (py * Pixels + px) * 4;
+ if (!NdviPalette.TryValue(rgba[at], rgba[at + 1], rgba[at + 2], out double ndvi)) continue;
+ sum += ndvi;
+ count++;
+ }
+ cells[cy * Cells + cx] = count >= 4 ? NdviPalette.CodeOf(sum / count) : NdviPalette.NoData;
+ }
+ return cells;
+ }
+}
diff --git a/src/OrthoStreamXP/Textures/Vegetation/ndvi-colormap.xml b/src/OrthoStreamXP/Textures/Vegetation/ndvi-colormap.xml
new file mode 100644
index 0000000..90f97de
--- /dev/null
+++ b/src/OrthoStreamXP/Textures/Vegetation/ndvi-colormap.xml
@@ -0,0 +1,300 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/OrthoStreamXP/Tuning/CpuMeter.cs b/src/OrthoStreamXP/Tuning/CpuMeter.cs
index c78eacd..7c8e7a9 100644
--- a/src/OrthoStreamXP/Tuning/CpuMeter.cs
+++ b/src/OrthoStreamXP/Tuning/CpuMeter.cs
@@ -86,12 +86,23 @@ public string Summary()
}
int fullCollections = GC.CollectionCount(2), since = fullCollections - Interlocked.Exchange(ref _fullCollections, fullCollections);
return $"Load over the last {period.TotalMinutes:0.#} min (share of all {Environment.ProcessorCount} logical processors): OrthoStreamXP CPU {process}, " +
- $"all of Windows {windows}; memory: {Memory(GC.GetGCMemoryInfo(), Environment.WorkingSet)}, " +
+ $"all of Windows {windows}; memory: {Memory(LastFullCollection(), Environment.WorkingSet)}, " +
$"{since} full garbage collection{(since == 1 ? "" : "s")}";
}
///
- /// The process's memory in RAM (working set) and the .NET heap as the latest collection left it: how much of it is
+ /// The latest full collection, background or blocking (any collection before the first). Large objects are freed
+ /// only by those: after a quicker one the heap still counts every picture dropped since, as if it were held.
+ ///
+ private static GCMemoryInfo LastFullCollection()
+ {
+ GCMemoryInfo blocking = GC.GetGCMemoryInfo(GCKind.FullBlocking), background = GC.GetGCMemoryInfo(GCKind.Background);
+ GCMemoryInfo latest = blocking.Index >= background.Index ? blocking : background;
+ return latest.Index > 0 ? latest : GC.GetGCMemoryInfo();
+ }
+
+ ///
+ /// The process's memory in RAM (working set) and the .NET heap as the latest full collection left it: how much of it is
/// free gaps between live objects, and the large objects (85 KB and up: tiles, pictures, chains), which are not
/// moved to close their gaps unless the collector decides to compact them.
///
@@ -102,7 +113,7 @@ internal static string Memory(GCMemoryInfo memory, long workingSet)
string large = generations.Length > largeObjects
? $", large objects {Bytes(generations[largeObjects].SizeAfterBytes)} ({Bytes(generations[largeObjects].FragmentationAfterBytes)} free)"
: "";
- return $"working set {Bytes(workingSet)}; .NET heap {Bytes(memory.HeapSizeBytes)} after the last collection, " +
+ return $"working set {Bytes(workingSet)}; .NET heap {Bytes(memory.HeapSizeBytes)} after the last full collection, " +
$"{Bytes(memory.FragmentedBytes)} of it free gaps{large}, {Bytes(memory.TotalCommittedBytes)} committed";
static string Bytes(long n) => CacheInventory.FormatBytes(n);
diff --git a/src/OrthoStreamXP/Tuning/GraphicsMemory.cs b/src/OrthoStreamXP/Tuning/GraphicsMemory.cs
index bb42094..12fe55b 100644
--- a/src/OrthoStreamXP/Tuning/GraphicsMemory.cs
+++ b/src/OrthoStreamXP/Tuning/GraphicsMemory.cs
@@ -1,5 +1,6 @@
using System.Text.Json;
using Microsoft.Win32;
+using OrthoStreamXP.Scenery;
namespace OrthoStreamXP.Tuning;
@@ -8,9 +9,21 @@ namespace OrthoStreamXP.Tuning;
/// X-Plane held. Measured in pixels X-Plane wanted (the same at the same distance, whatever the size), so one flight
/// tells every preset's: a smaller texture just reaches its own size nearer the aircraft. Saved in the log folder as
/// graphics-memory.json; before any flight, the figures of a test flight (Extra, 1 hour, a 3840 px screen).
+///
+/// A resolution may size the airports' (ZL18) textures apart from the wide areas' (Medium halves only the areas'), so a
+/// flight also measures the airports' part of each peak: then adds the two, each from
+/// its own size. Figures without that part (the test flight, earlier versions) count both at the larger size.
+///
///
+/// The size flown: the wide areas' when is known, otherwise the largest.
internal sealed record GraphicsMemory(DateTime MeasuredUtc, int FlownSize, IReadOnlyDictionary PeakBySize)
{
+ /// The airports' (ZL18) part of each peak, measured with it; null when it was not measured.
+ public IReadOnlyDictionary? AirportBySize { get; init; }
+
+ /// The airports' texture size flown, when their part was measured.
+ public int? FlownAirportSize { get; init; }
+
public const string FileName = "graphics-memory.json";
/// X-Plane keeps a texture while its scenery is loaded: what it wanted in the last 20 minutes counts.
@@ -19,7 +32,16 @@ internal sealed record GraphicsMemory(DateTime MeasuredUtc, int FlownSize, IRead
/// What X-Plane itself takes of a graphics card beside the photo textures, about: the warning's margin.
public const long XPlaneOwnBytes = 5L << 30;
- public static readonly int[] Sizes = [1024, 2048, 4096];
+ public static readonly int[] Sizes = [1024, 2048, 4096, 8192];
+
+ ///
+ /// The test flight's peaks, and at 8192 px, which it did not fly, an estimate: the step from 2048 to 4096 again
+ /// (x 1.71), the textures beside the aircraft being the ones that grow.
+ ///
+ private static readonly Dictionary ReferencePeaks = new()
+ {
+ [1024] = 462_000_000, [2048] = 741_000_000, [4096] = 1_267_000_000, [8192] = 2_166_000_000,
+ };
/// Measured on the test flight of 27 October 2026 (Extra over Poland, 57 min, peaks of 20-minute spans).
public static readonly GraphicsMemory TestFlight = new(new DateTime(2026, 10, 27, 12, 0, 0, DateTimeKind.Utc), 4096,
@@ -34,13 +56,40 @@ internal sealed record GraphicsMemory(DateTime MeasuredUtc, int FlownSize, IRead
/// The photo textures' graphics memory at a texture size. Above the size flown, X-Plane's wish for detail next to
/// the aircraft was cut at that size, so the test flight's ratio fills it in.
///
- public long BytesAt(int size)
+ public long BytesAt(int size) => BytesAt(size, size);
+
+ /// The photo textures' graphics memory with the textures of (its areas' and airports' sizes).
+ public long BytesAt(Textures.TexturePlan plan) => BytesAt(plan.SizeFor(16), plan.SizeFor(18));
+
+ ///
+ /// The photo textures' graphics memory with the wide areas' textures at and the airports'
+ /// at : each part as measured up to the size flown, beyond it in the test flight's
+ /// ratio. Without the airports' part measured, both count at the larger size (never less than they may take).
+ ///
+ public long BytesAt(int areaSize, int airportSize)
+ {
+ (areaSize, airportSize) = (Modelled(areaSize), Modelled(airportSize));
+ if (AirportBySize is not { } airports || FlownAirportSize is not { } airportFlown)
+ return Part(PeakBySize, Math.Max(areaSize, airportSize), FlownSize);
+ var areas = PeakBySize.ToDictionary(p => p.Key, p => p.Value - airports.GetValueOrDefault(p.Key));
+ return Part(areas, areaSize, FlownSize) + Part(airports, airportSize, airportFlown);
+ }
+
+ /// A measured part at a size: as measured up to the size flown; above it, the flown size's in the test flight's ratio.
+ private static long Part(IReadOnlyDictionary measured, int size, int flown)
{
- if (size <= FlownSize && PeakBySize.TryGetValue(size, out long measured)) return measured;
- long atFlown = PeakBySize.TryGetValue(FlownSize, out long f) ? f : TestFlight.BytesAt(FlownSize);
- return (long)(atFlown * (double)TestFlight.BytesAt(size) / TestFlight.BytesAt(FlownSize));
+ if (size <= flown && measured.TryGetValue(size, out long bytes)) return bytes;
+ flown = Modelled(flown);
+ long atFlown = measured.TryGetValue(flown, out long f) ? f : Reference(flown);
+ return (long)(atFlown * (double)Reference(size) / Reference(flown));
}
+ /// A size the model has figures for: a smaller texture (a 512 px airport at Low) counts as the smallest, never less.
+ internal static int Modelled(int size) => Math.Clamp(size, Sizes[0], Sizes[^1]);
+
+ private static long Reference(int size) =>
+ ReferencePeaks.TryGetValue(size, out long bytes) ? bytes : throw new ArgumentOutOfRangeException(nameof(size), size, "Not a texture size of the graphics memory model");
+
/// A texture's memory in BC1 with its smaller levels: half a byte a pixel, a third more for the levels.
public static long TextureBytes(int pixels)
{
@@ -123,16 +172,38 @@ public void Save(string history)
}
}
-/// Takes the peak of the photo textures' graphics memory over a session, once a minute.
-internal sealed class GraphicsMemoryMeter(int flownSize)
+///
+/// Takes the peak of the photo textures' graphics memory over a session, once a minute, and the airports' part of it.
+///
+/// The wide areas' (ZL16) texture size flown.
+/// The airports' (ZL18) texture size flown.
+internal sealed class GraphicsMemoryMeter(int areaSize, int airportSize)
{
private readonly Dictionary _peak = GraphicsMemory.Sizes.ToDictionary(s => s, _ => 0L);
+ private readonly Dictionary _airports = GraphicsMemory.Sizes.ToDictionary(s => s, _ => 0L);
- public void Sample(IEnumerable heldDetail)
+ public void Sample(IEnumerable held)
{
- foreach (var (size, bytes) in GraphicsMemory.HeldBytes(heldDetail))
- if (bytes > _peak[size]) _peak[size] = bytes;
+ HeldTexture[] textures = [.. held];
+ foreach (int size in GraphicsMemory.Sizes)
+ {
+ long areas = 0, airports = 0;
+ foreach (HeldTexture t in textures)
+ {
+ long bytes = GraphicsMemory.TextureBytes(Math.Min(size, t.Detail));
+ if (t.Airport) airports += bytes;
+ else areas += bytes;
+ }
+ // The airports' part at the peak itself, so the two parts add up to it.
+ if (areas + airports <= _peak[size]) continue;
+ _peak[size] = areas + airports;
+ _airports[size] = airports;
+ }
}
- public GraphicsMemory Result() => new(DateTime.UtcNow, flownSize, new Dictionary(_peak));
+ public GraphicsMemory Result() => new(DateTime.UtcNow, GraphicsMemory.Modelled(areaSize), new Dictionary(_peak))
+ {
+ AirportBySize = new Dictionary(_airports),
+ FlownAirportSize = GraphicsMemory.Modelled(airportSize),
+ };
}
diff --git a/src/OrthoStreamXP/Tuning/PresetAdvisor.cs b/src/OrthoStreamXP/Tuning/PresetAdvisor.cs
index e5a8f04..1837e42 100644
--- a/src/OrthoStreamXP/Tuning/PresetAdvisor.cs
+++ b/src/OrthoStreamXP/Tuning/PresetAdvisor.cs
@@ -1,19 +1,43 @@
using System.Globalization;
using OrthoStreamXP.Setup;
+using OrthoStreamXP.Textures;
namespace OrthoStreamXP.Tuning;
-/// The preset recommended for this PC, and why in plain words.
-internal sealed record Recommendation(QualityPreset Preset, string Reason);
+/// The preset, at a resolution, recommended for this PC, and why in plain words.
+internal sealed record Recommendation(QualityPreset Preset, TextureResolution Resolution, string Reason)
+{
+ /// "Ultra", or "Ultra at Medium resolution".
+ public string Title => Resolution.IsFull ? Preset.Name : $"{Preset.Name} at {Resolution.Label} resolution";
+}
+
+/// How one preset suits this PC, for its card beside the recommended one.
+/// The finest resolution the graphics card holds it at, when nothing else rules it out; null when it does not suit.
+/// "Also suits your PC", "Also suits your PC at Medium resolution: ...", or why it does not.
+internal sealed record PresetFit(QualityPreset Preset, TextureResolution? Resolution, string Text)
+{
+ public bool Suits => Resolution is not null;
+}
///
-/// Which quality preset suits this PC: the sharpest one every known fact allows. The graphics card must hold the
-/// preset's photo textures beside X-Plane's own needs; the connection must have reached the preset's download speed on
-/// the fastest recent flight that downloaded enough to tell (Sharp about 20 Mbit/s, Ultra 50, Extra 100: a ZL16
-/// texture is 4 times the tiles per step; a flight over cached scenery downloads little and says nothing); and a preset
-/// that was often blurry on the last flight is not recommended again. Without such a flight the connection test says
-/// how fast it is, when it was run; without either there is nothing to say about the connection: Sharp, or Balanced
-/// on a small graphics card.
+/// Which quality preset, at which resolution, suits this PC: the largest textures every known fact allows. The two
+/// facts weigh on different things: the connection on the preset (the resolution downloads the same imagery), the
+/// graphics card on both (it must hold the textures beside X-Plane's own needs).
+///
+/// The connection must have reached the preset's download speed (Sharp about 20 Mbit/s, Ultra 50, Extra 100: a
+/// ZL16 texture is 4 times the tiles per step) on the fastest recent flight that downloaded enough to tell (a flight
+/// over cached scenery downloads little and says nothing) or in the connection test, whichever is faster: each only
+/// shows the connection can do at least that much, a flight downloading what its preset asks. Without either, no more
+/// than Sharp's downloads.
+/// A preset that was often blurry on the last flight is not recommended again (a lower resolution downloads the
+/// same, so it would be as blurry).
+/// Of the pairs left that the card holds, the one with the largest textures in the wide areas, then at the
+/// airports; between equal textures, the preset that downloads less. So when the card cannot hold Ultra, "Ultra at
+/// Medium" (4096 px everywhere) beats Sharp (4096 px, airports 2048), and ties with Extra at Low, which downloads more
+/// for the same textures.
+///
+/// When the card holds none, the smallest textures: Balanced at Low. tells the same of every
+/// preset, for the cards beside the recommended one.
///
internal static class PresetAdvisor
{
@@ -26,45 +50,119 @@ internal static class PresetAdvisor
_ => 100,
};
+ /// Every preset at every resolution (Dynamic is its base's textures, so not among them).
+ private static IEnumerable<(QualityPreset Preset, TextureResolution Resolution)> Pairs =>
+ from preset in QualityPreset.All from resolution in TextureResolution.All select (preset, resolution);
+
+ /// What is known of this PC: the connection's speed and where it was seen, the last flight's blur, the card.
+ /// The connection's speed, Mbit/s; null when nothing has measured it.
+ /// The speed is the flights' (otherwise the connection test's).
+ /// The level of the last flight when it was often blurry; null otherwise.
+ private sealed record Evidence(double? Peak, bool FromFlights, int? BlurryLevel, long? Card, GraphicsMemory Memory)
+ {
+ public string CardText => Card is { } bytes ? $"{CacheInventory.FormatBytes(bytes)} graphics card" : "";
+
+ public string SpeedText => Peak is not { } peak ? ""
+ : FromFlights ? $"downloads reached {peak.ToString("0", CultureInfo.CurrentCulture)} Mbit/s on your recent flights"
+ : $"the connection test measured {peak.ToString("0", CultureInfo.CurrentCulture)} Mbit/s";
+
+ /// The connection keeps up with the preset; true when nothing has measured it (it is not judged then).
+ public bool KeepsUp(QualityPreset preset) => Peak is not { } peak || peak >= NeededMbits(preset);
+
+ /// The preset was often blurry on the last flight, or is sharper than one that was. Balanced never is: nothing is below it.
+ public bool WasBlurry(QualityPreset preset) => BlurryLevel is { } level && preset.Level >= level && preset != QualityPreset.Balanced;
+
+ public bool Fits(QualityPreset preset, TextureResolution resolution) =>
+ Card is not { } card || Memory.BytesAt(preset.PlanAt(resolution)) + GraphicsMemory.XPlaneOwnBytes <= card;
+ }
+
+ private static Evidence Gather(long? card, GraphicsMemory memory, IReadOnlyList flights, ConnectionResult? test)
+ {
+ // Evidence of the connection: the fastest flight that downloaded enough to show its speed, and the connection test.
+ // Each only shows the connection can do at least that much (a flight downloads what its preset asks, not all the
+ // connection can), so the faster one counts.
+ FlightReport? fastest = flights.Where(f => f.Bytes > 200_000_000).MaxBy(f => f.PeakMbits);
+ double? tested = test is { Mbits: > 0 } t ? t.Mbits : null;
+ bool fromFlights = fastest is not null && (tested is null || fastest.PeakMbits >= tested);
+ FlightReport? lastFlight = flights.Count > 0 ? flights[0] : null;
+ int? flownLevel = lastFlight is null ? null : CacheInventory.ParseSetupName(lastFlight.Quality)?.Level;
+ bool blurry = lastFlight is not null && ReportSummary.SharpnessRating(lastFlight) == Rating.Poor;
+ return new Evidence(fromFlights ? fastest!.PeakMbits : tested, fromFlights, blurry ? flownLevel : null, card, memory);
+ }
+
/// The graphics card's memory, when Windows says.
/// The photo textures' graphics memory per texture size, as last measured.
/// The flight reports kept, newest first ().
/// The latest connection test, when there is one.
public static Recommendation Recommend(long? card, GraphicsMemory memory, IReadOnlyList flights, ConnectionResult? test = null)
{
- FlightReport? lastFlight = flights.Count > 0 ? flights[0] : null;
- bool Fits(QualityPreset p) => card is not { } c || memory.BytesAt(p.Size) + GraphicsMemory.XPlaneOwnBytes <= c;
- string cardText = card is { } bytes ? $"{CacheInventory.FormatBytes(bytes)} graphics card" : "";
-
- // Evidence of the connection: the fastest flight that downloaded enough to show its speed, else the connection test.
- FlightReport? fastest = flights.Where(f => f.Bytes > 200_000_000).MaxBy(f => f.PeakMbits);
- double? measured = fastest?.PeakMbits ?? (test is { Mbits: > 0 } t ? t.Mbits : null);
- if (measured is not { } peak)
+ Evidence e = Gather(card, memory, flights, test);
+ if (e.Peak is null)
{
- QualityPreset start = Fits(QualityPreset.Sharp) ? QualityPreset.Sharp : QualityPreset.Balanced;
- return new(start, (start == QualityPreset.Sharp
- ? "A good start on most PCs"
- : $"Your {cardText} is small for sharper textures") + ". Test your connection or fly once, and the recommendation follows your PC and connection.");
+ if (Best(p => p.Preset.Level <= QualityPreset.Sharp.Level && e.Fits(p.Preset, p.Resolution)) is not { } start)
+ return Smallest($"Your {e.CardText} is small for sharper textures. {MeasureFirst}");
+ string opening = start.Preset == QualityPreset.Sharp && start.Resolution.IsFull ? "A good start on most PCs"
+ : start.Resolution.IsFull ? $"Your {e.CardText} is small for sharper textures"
+ : $"{start.Preset.Name} at Full resolution would not fit your {e.CardText}, at {start.Resolution.Label} it does";
+ return new(start.Preset, start.Resolution, $"{opening}. {MeasureFirst}");
}
- int? flownLevel = lastFlight is null ? null : CacheInventory.ParseSetupName(lastFlight.Quality)?.Level;
- bool blurry = lastFlight is not null && ReportSummary.SharpnessRating(lastFlight) == Rating.Poor;
- foreach (QualityPreset preset in QualityPreset.All.Reverse())
- {
- if (preset == QualityPreset.Balanced) break;
- if (!Fits(preset) || peak < NeededMbits(preset)) continue;
- if (blurry && flownLevel is { } level && preset.Level >= level) continue;
- return new(preset, Because(peak, fastest is not null, cardText, blurry && flownLevel is not null));
- }
- return new(QualityPreset.Balanced, Because(peak, fastest is not null, cardText, blurry));
+ if (Best(p => e.KeepsUp(p.Preset) && !e.WasBlurry(p.Preset) && e.Fits(p.Preset, p.Resolution)) is { } best)
+ return new(best.Preset, best.Resolution, Because(e, best));
+ return Smallest(Because(e, null));
}
- private static string Because(double peak, bool flown, string card, bool blurry)
+ ///
+ /// How every preset the window offers suits this PC: the finest resolution the card holds it at when the connection
+ /// keeps up and it was not blurry, otherwise the reason it does not suit. The recommended one is among them.
+ ///
+ /// The presets to tell of: the window's cards () when null.
+ public static IReadOnlyList Assess(long? card, GraphicsMemory memory, IReadOnlyList flights,
+ ConnectionResult? test = null, IEnumerable? presets = null)
+ {
+ Evidence e = Gather(card, memory, flights, test);
+ return [.. (presets ?? QualityPreset.Choices).Select(preset => Assess(e, preset))];
+ }
+
+ private static PresetFit Assess(Evidence e, QualityPreset preset)
+ {
+ if (!e.KeepsUp(preset))
+ return new(preset, null, $"Needs about {NeededMbits(preset):0} Mbit/s of downloads: {e.SpeedText}.");
+ if (e.WasBlurry(preset))
+ return new(preset, null, "Not for now: your last flight was often blurry at this quality or a lower one.");
+ // Full first: the finest resolution the card holds.
+ if (TextureResolution.All.FirstOrDefault(r => e.Fits(preset, r)) is not { } resolution)
+ return new(preset, null, $"Too large for your {e.CardText}, even at Low resolution.");
+ string suits = resolution.IsFull ? "Also suits your PC"
+ : $"Also suits your PC at {resolution.Label} resolution: at Full its textures would not fit your {e.CardText}";
+ // Nothing has measured the connection: only Sharp's downloads and below are judged to keep up.
+ return e.Peak is null && preset.Level > QualityPreset.Sharp.Level
+ ? new(preset, resolution, $"Fits your graphics card{(resolution.IsFull ? "" : $" at {resolution.Label} resolution")}. Test your connection to see whether it keeps up with its downloads.")
+ : new(preset, resolution, $"{suits}.");
+ }
+
+ private const string MeasureFirst = "Test your connection or fly once, and the recommendation follows your PC and connection.";
+
+ /// The pair with the largest textures (areas, then airports); between equal ones, the fewer downloads.
+ private static (QualityPreset Preset, TextureResolution Resolution)? Best(Func<(QualityPreset Preset, TextureResolution Resolution), bool> allowed) =>
+ Pairs.Where(allowed)
+ .OrderByDescending(p => p.Preset.PlanAt(p.Resolution).SizeFor(16))
+ .ThenByDescending(p => p.Preset.PlanAt(p.Resolution).SizeFor(18))
+ .ThenBy(p => p.Preset.Level)
+ .Select(p => ((QualityPreset, TextureResolution)?)p)
+ .FirstOrDefault();
+
+ /// When the card holds nothing: the smallest textures there are.
+ private static Recommendation Smallest(string reason) => new(QualityPreset.Balanced, TextureResolution.Low, reason);
+
+ private static string Because(Evidence e, (QualityPreset Preset, TextureResolution Resolution)? pick)
{
- string speed = peak.ToString("0", CultureInfo.CurrentCulture);
- var facts = new List { flown ? $"downloads reached {speed} Mbit/s on your recent flights" : $"the connection test measured {speed} Mbit/s" };
- if (card.Length > 0) facts.Add($"your {card} holds its textures");
- if (blurry) facts.Add("a sharper quality was often blurry");
+ var facts = new List { e.SpeedText };
+ if (e.CardText.Length > 0)
+ facts.Add(pick is not { } p ? $"your {e.CardText} is small even for the smallest textures"
+ : p.Resolution.IsFull ? $"your {e.CardText} holds its textures"
+ : $"your {e.CardText} would not hold {p.Preset.Name}'s textures at Full resolution, at {p.Resolution.Label} it does, from the same imagery");
+ if (e.BlurryLevel is not null) facts.Add("a sharper quality was often blurry");
return $"For your PC: {string.Join(", ", facts)}.";
}
}
diff --git a/src/OrthoStreamXP/orthostreamxp.example.ini b/src/OrthoStreamXP/orthostreamxp.example.ini
index aa22bf5..44a82ba 100644
--- a/src/OrthoStreamXP/orthostreamxp.example.ini
+++ b/src/OrthoStreamXP/orthostreamxp.example.ini
@@ -35,8 +35,9 @@ log-detail = off
# bing, esri, or several tried in order for each tile: a tile the first lacks comes from the next
texture-provider = bing,esri
texture-url =
-# ZL18 textures use zoom 18 + level, ZL16 textures 16 + (level + 1) up to level 0 (16 + level above): at -2, 16 and 64 tiles; at -1, 64 and 256
-# the level also sets the texture size: 4096 px at level 0 and above, half per level below
+# the quality preset: -2 Balanced, -1 Sharp, 0 Ultra, +1 Extra. Each downloads fixed zooms, areas (ZL16/17) / airports (ZL18 and finer):
+# Balanced 15/16, Sharp 16/17, Ultra 17/18, Extra 17/19
+# the level also sets the texture size, the detail of that imagery, never shrunk: ZL16 2048 px at -2, 4096 at -1, 8192 at 0 and +1; ZL18 half of that up to 0, 8192 at +1
level-change = -2
# --- How fast it builds -----------------------------------------------------------
@@ -57,7 +58,7 @@ filesystem-threads = 64
mip-streaming = on
near-wait = 60
max-wait = 6
-# MB the builds may hold at once, each at its own size (19 MB at 2048 px, 75 MB at 4096 px)
+# MB the builds may hold at once, each at its own size (18 MB at 2048 px, 74 MB at 4096 px, 295 MB at 8192 px)
build-memory = 512
# tiles the builds may download at once: keeps the sharpest textures from filling the connection
build-tiles = 32768
@@ -107,20 +108,14 @@ paging-k = auto
# the flight tuning measures the paging model without them)
read-log = off
-# --- Colours ----------------------------------------------------------------------
-# even out the colours of photos from different captures (on or off): a grey, hazy capture next to a bright, green
-# one is moved towards the colours usual in the area, place by place, against the low-zoom base (brightness and tint
-# only). Needs mip streaming; the cache keeps the photos as downloaded
-match-colours = off
-# 0-100: how much of each correction is made
-match-strength = 100
-
# --- Seasons ----------------------------------------------------------------------
# colour the photos for the season of X-Plane's date and the place (on or off): autumn leaves, bare trees and
# resting fields in winter, fresh green in spring; conifers, roofs, roads and water stay. The cache keeps the photos
# as downloaded, so changing these never downloads them again
seasons = off
-# auto, or early-spring, spring, summer, early-autumn, autumn, late-autumn or winter everywhere
+# auto (by the calendar), satellite (the same, with grass and fields as green as NASA's satellite record of the
+# last year shows them: a green winter on the coast, a dry summer; about 2 MB downloaded once a year for each area
+# of 500 km), or early-spring, spring, summer, early-autumn, autumn, late-autumn or winter everywhere
season = auto
# 0-100: how far the colours move towards the season
season-strength = 80
diff --git a/tests/OrthoStreamXP.Tests/Bc1EncoderTests.cs b/tests/OrthoStreamXP.Tests/Bc1EncoderTests.cs
new file mode 100644
index 0000000..bd38244
--- /dev/null
+++ b/tests/OrthoStreamXP.Tests/Bc1EncoderTests.cs
@@ -0,0 +1,151 @@
+using System.Buffers.Binary;
+using OrthoStreamXP.Textures;
+
+namespace OrthoStreamXP.Tests;
+
+public sealed class Bc1EncoderTests
+{
+ [Fact]
+ public void Ispc_is_loaded_from_the_program_folder()
+ {
+ Assert.True(IspcBc1.IsAvailable, "ispc_texcomp.dll did not load from the output folder");
+ Assert.Equal("ispc", Dds.Encoder);
+ }
+
+ [Fact]
+ public void Ispc_keeps_the_quality_of_the_range_fit()
+ {
+ // On real aerial photos ISPC is 0.1-0.4 dB closer (native\ispc_texcomp\README.md); the synthetic tile's
+ // per-pixel noise is no photo, so here it only has to stay about level with the range fit.
+ const int size = 256;
+ byte[] rgb = Images.SyntheticTile(1234, 5678, 16);
+
+ double ispc = Psnr(Ispc(rgb, size, size, 1), rgb, size, size);
+ double rangeFit = Psnr(RangeFit(rgb, size, size), rgb, size, size);
+
+ Assert.True(ispc >= rangeFit - 0.5, $"ISPC {ispc:F2} dB, range fit {rangeFit:F2} dB");
+ Assert.True(ispc > 30, $"ISPC {ispc:F2} dB");
+ }
+
+ [Fact]
+ public void Every_block_is_in_the_opaque_four_colour_mode()
+ {
+ // Flat areas (a colour 565 holds exactly and one it does not), a gradient and photo-like noise.
+ const int size = 64;
+ byte[] rgb = new byte[size * size * 3];
+ byte[] noise = Images.SyntheticTile(10, 20, 15);
+ for (int y = 0; y < size; y++)
+ for (int x = 0; x < size; x++)
+ {
+ int i = (y * size + x) * 3;
+ (rgb[i], rgb[i + 1], rgb[i + 2]) = (x / 16) switch
+ {
+ 0 => ((byte)255, (byte)0, (byte)255),
+ 1 => ((byte)90, (byte)121, (byte)57),
+ 2 => ((byte)(x * 4), (byte)(y * 4), (byte)128),
+ _ => (noise[i], noise[i + 1], noise[i + 2]),
+ };
+ }
+
+ byte[] blocks = Ispc(rgb, size, size, 1);
+
+ for (int at = 0; at < blocks.Length; at += 8)
+ {
+ ushort c0 = BinaryPrimitives.ReadUInt16LittleEndian(blocks.AsSpan(at)), c1 = BinaryPrimitives.ReadUInt16LittleEndian(blocks.AsSpan(at + 2));
+ Assert.True(c0 > c1, $"block {at / 8}: colours {c0} and {c1}");
+ }
+ }
+
+ [Theory]
+ [InlineData(1, 1)]
+ [InlineData(2, 2)]
+ [InlineData(3, 5)]
+ [InlineData(8, 4)]
+ [InlineData(13, 7)]
+ public void Sizes_off_the_block_grid_repeat_their_edges_like_the_range_fit(int width, int height)
+ {
+ byte[] flat = new byte[width * height * 3];
+ for (int i = 0; i < flat.Length; i += 3) (flat[i], flat[i + 1], flat[i + 2]) = (255, 0, 255);
+ byte[] gradient = new byte[width * height * 3];
+ for (int y = 0; y < height; y++)
+ for (int x = 0; x < width; x++)
+ {
+ int i = (y * width + x) * 3;
+ (gradient[i], gradient[i + 1], gradient[i + 2]) = ((byte)(40 + x * 120 / width), (byte)(60 + y * 100 / height), 128);
+ }
+
+ byte[] flatBlocks = Ispc(flat, width, height, 1);
+ Assert.Equal(RangeFit(flat, width, height).Length, flatBlocks.Length);
+ Assert.Equal(flat, Dds.DecodeLevel(flatBlocks, width, height));
+ double ispc = Psnr(Ispc(gradient, width, height, 1), gradient, width, height);
+ double rangeFit = Psnr(RangeFit(gradient, width, height), gradient, width, height);
+ Assert.True(ispc >= rangeFit - 0.5, $"{width}x{height}: ISPC {ispc:F2} dB, range fit {rangeFit:F2} dB");
+ }
+
+ [Theory]
+ [InlineData(40, 60, 128)]
+ [InlineData(18, 52, 77)] // dark water
+ [InlineData(201, 203, 199)]
+ [InlineData(0, 0, 0)]
+ [InlineData(255, 255, 255)]
+ public void A_one_colour_block_lands_within_a_step_of_its_colour(byte r, byte g, byte b)
+ {
+ byte[] rgb = new byte[8 * 8 * 3];
+ for (int i = 0; i < rgb.Length; i += 3) (rgb[i], rgb[i + 1], rgb[i + 2]) = (r, g, b);
+
+ byte[] blocks = Ispc(rgb, 8, 8, 1);
+ byte[] decoded = Dds.DecodeLevel(blocks, 8, 8);
+ byte[] rangeFit = Dds.DecodeLevel(RangeFit(rgb, 8, 8), 8, 8);
+
+ for (int i = 0; i < rgb.Length; i++)
+ {
+ Assert.True(Math.Abs(decoded[i] - rgb[i]) <= 2, $"channel {i % 3}: {decoded[i]} for {rgb[i]}");
+ Assert.True(Math.Abs(decoded[i] - rgb[i]) <= Math.Abs(rangeFit[i] - rgb[i]), $"channel {i % 3}: {decoded[i]}, range fit {rangeFit[i]}, for {rgb[i]}");
+ }
+ for (int at = 0; at < blocks.Length; at += 8)
+ Assert.True(BinaryPrimitives.ReadUInt16LittleEndian(blocks.AsSpan(at)) > BinaryPrimitives.ReadUInt16LittleEndian(blocks.AsSpan(at + 2)) || (r, g, b) == (0, 0, 0));
+ }
+
+ [Fact]
+ public void The_number_of_workers_changes_nothing()
+ {
+ const int size = 512;
+ byte[] rgb = Images.Resize(Images.SyntheticTile(3, 4, 14), 256, 256, size, size, 1);
+
+ Assert.Equal(Ispc(rgb, size, size, 1), Ispc(rgb, size, size, 8));
+ }
+
+ [Fact]
+ public void A_short_output_is_refused_before_the_native_code_writes()
+ {
+ byte[] rgb = new byte[16 * 16 * 3];
+ Assert.Throws(() => IspcBc1.Encode(rgb, 16, 16, new byte[16 * 8 - 1], 0, 1));
+ Assert.Throws(() => IspcBc1.Encode(rgb, 16, 16, new byte[16 * 8], 8, 1));
+ }
+
+ private static byte[] Ispc(byte[] rgb, int width, int height, int workers)
+ {
+ byte[] output = new byte[Dds.LevelLength(1) * Math.Max(1, (width + 3) / 4) * Math.Max(1, (height + 3) / 4)];
+ IspcBc1.Encode(rgb, width, height, output, 0, workers);
+ return output;
+ }
+
+ private static byte[] RangeFit(byte[] rgb, int width, int height)
+ {
+ byte[] output = new byte[8 * Math.Max(1, (width + 3) / 4) * Math.Max(1, (height + 3) / 4)];
+ Dds.EncodeRangeFit(rgb, width, height, output, 0, 1);
+ return output;
+ }
+
+ private static double Psnr(byte[] blocks, byte[] source, int width, int height)
+ {
+ byte[] decoded = Dds.DecodeLevel(blocks, width, height);
+ double squares = 0;
+ for (int i = 0; i < decoded.Length; i++)
+ {
+ double d = decoded[i] - source[i];
+ squares += d * d;
+ }
+ return squares == 0 ? 99 : 10 * Math.Log10(255.0 * 255.0 * decoded.Length / squares);
+ }
+}
diff --git a/tests/OrthoStreamXP.Tests/Bc1RefinementTests.cs b/tests/OrthoStreamXP.Tests/Bc1RefinementTests.cs
new file mode 100644
index 0000000..5aaf8ac
--- /dev/null
+++ b/tests/OrthoStreamXP.Tests/Bc1RefinementTests.cs
@@ -0,0 +1,165 @@
+using System.Buffers.Binary;
+using OrthoStreamXP.Textures;
+
+namespace OrthoStreamXP.Tests;
+
+public sealed class Bc1RefinementTests
+{
+ [Fact]
+ public void Refining_never_makes_a_block_worse_and_brings_the_whole_closer()
+ {
+ const int size = 128;
+ byte[] rgb = PhotoLike(size);
+ byte[] blocks = RangeFit(rgb, size);
+ byte[] refined = (byte[])blocks.Clone();
+
+ int blocksX = size / 4;
+ for (int b = 0; b < blocksX * blocksX; b++)
+ {
+ byte[] pixels = BlockPixels(rgb, size, b % blocksX, b / blocksX);
+ Span block = refined.AsSpan(b * 8, 8);
+ Bc1Refinement.Refine(block, pixels);
+ Assert.True(BlockError(block, pixels) <= BlockError(blocks.AsSpan(b * 8, 8), pixels), $"block {b} got worse");
+ }
+
+ double before = Psnr(blocks, rgb, size), after = Psnr(refined, rgb, size);
+ Assert.True(after > before + 0.2, $"range fit {before:F2} dB, refined {after:F2} dB");
+ }
+
+ [Fact]
+ public void Refined_blocks_stay_in_the_opaque_four_colour_mode()
+ {
+ const int size = 64;
+ byte[] rgb = PhotoLike(size);
+ byte[] blocks = RangeFit(rgb, size);
+
+ for (int b = 0; b < blocks.Length / 8; b++)
+ {
+ Span block = blocks.AsSpan(b * 8, 8);
+ Bc1Refinement.Refine(block, BlockPixels(rgb, size, b % (size / 4), b / (size / 4)));
+ Assert.True(BinaryPrimitives.ReadUInt16LittleEndian(block) > BinaryPrimitives.ReadUInt16LittleEndian(block[2..]), $"block {b}");
+ }
+ }
+
+ [Fact]
+ public void A_block_of_two_565_colours_finds_them_exactly()
+ {
+ // Half the pixels one colour 565 holds exactly, half another; the block starts with both colours a few steps
+ // off but each pixel already on the right one (index 0 or 1), so one pass solves them exactly.
+ int a = (20 << 11) | (40 << 5) | 10, b = (5 << 11) | (12 << 5) | 25;
+ byte[] pixels = new byte[48];
+ for (int i = 0; i < 16; i++) Put(pixels, i, i < 8 ? a : b);
+ byte[] block = Block((22 << 11) | (37 << 5) | 12, (6 << 11) | (15 << 5) | 23, 0x5555_0000u);
+
+ Bc1Refinement.Refine(block, pixels);
+
+ Assert.Equal(0, BlockError(block, pixels));
+ Assert.Equal(a, BinaryPrimitives.ReadUInt16LittleEndian(block));
+ Assert.Equal(b, BinaryPrimitives.ReadUInt16LittleEndian(block.AsSpan(2)));
+ }
+
+ [Fact]
+ public void A_block_that_is_already_exact_is_left_as_it_is()
+ {
+ byte[] block = Block((25 << 11) | (50 << 5) | 20, (3 << 11) | (9 << 5) | 4, 0xE4E4_1B1Bu);
+ byte[] pixels = Decoded(block);
+ byte[] before = (byte[])block.Clone();
+
+ Bc1Refinement.Refine(block, pixels);
+
+ Assert.Equal(before, block);
+ }
+
+ [Fact]
+ public void A_block_whose_pixels_all_take_one_colour_is_left_as_it_is()
+ {
+ // Every index 2: the normal equations cannot fix two colours from one mix.
+ byte[] pixels = new byte[48];
+ for (int i = 0; i < 16; i++) (pixels[i * 3], pixels[i * 3 + 1], pixels[i * 3 + 2]) = ((byte)(100 + i), 90, 80);
+ byte[] block = Block((15 << 11) | (25 << 5) | 12, (10 << 11) | (20 << 5) | 8, 0xAAAA_AAAAu);
+ byte[] before = (byte[])block.Clone();
+
+ Bc1Refinement.Refine(block, pixels);
+
+ Assert.Equal(before, block);
+ }
+
+ [Fact]
+ public void A_three_colour_block_is_left_as_it_is()
+ {
+ byte[] block = Block(100, 2000, 0x1234_5678u);
+ byte[] before = (byte[])block.Clone();
+
+ Bc1Refinement.Refine(block, new byte[48]);
+
+ Assert.Equal(before, block);
+ }
+
+ [Theory]
+ [InlineData(0u)]
+ [InlineData(0xFFFF_FFFFu)]
+ [InlineData(0x1B1B_E4E4u)]
+ [InlineData(0x8000_0001u)]
+ public void A_blocks_indices_survive_the_vector_lanes(uint indices)
+ {
+ Assert.Equal(indices, Bc1Refinement.Choice.From(indices).Packed());
+ }
+
+ [Fact]
+ public void Fewer_than_16_pixels_are_refused()
+ {
+ byte[] block = Block(2000, 100, 0);
+ Assert.Throws(() => Bc1Refinement.Refine(block, new byte[47]));
+ }
+
+ /// A more photo-like picture than the synthetic tile's per-pixel noise: the tile shrunk, which averages it.
+ private static byte[] PhotoLike(int size) => Images.Resize(Images.SyntheticTile(7, 9, 14), 256, 256, size, size, 1);
+
+ private static byte[] RangeFit(byte[] rgb, int size)
+ {
+ byte[] output = new byte[Dds.LevelLength(size)];
+ Dds.EncodeRangeFit(rgb, size, size, output, 0, 1);
+ return output;
+ }
+
+ private static byte[] BlockPixels(byte[] rgb, int size, int bx, int by)
+ {
+ byte[] pixels = new byte[48];
+ for (int i = 0; i < 16; i++)
+ rgb.AsSpan(((by * 4 + (i >> 2)) * size + bx * 4 + (i & 3)) * 3, 3).CopyTo(pixels.AsSpan(i * 3));
+ return pixels;
+ }
+
+ private static byte[] Block(int c0, int c1, uint indices)
+ {
+ byte[] block = new byte[8];
+ BinaryPrimitives.WriteUInt16LittleEndian(block, (ushort)c0);
+ BinaryPrimitives.WriteUInt16LittleEndian(block.AsSpan(2), (ushort)c1);
+ BinaryPrimitives.WriteUInt32LittleEndian(block.AsSpan(4), indices);
+ return block;
+ }
+
+ private static void Put(byte[] pixels, int i, int c)
+ {
+ var (r, g, b) = ColourTable.Decode565(c);
+ (pixels[i * 3], pixels[i * 3 + 1], pixels[i * 3 + 2]) = ((byte)Math.Round(r), (byte)Math.Round(g), (byte)Math.Round(b));
+ }
+
+ private static byte[] Decoded(ReadOnlySpan block) => Dds.DecodeLevel(block, 4, 4);
+
+ private static int BlockError(ReadOnlySpan block, byte[] pixels)
+ {
+ byte[] decoded = Decoded(block);
+ int total = 0;
+ for (int i = 0; i < 48; i++) total += (decoded[i] - pixels[i]) * (decoded[i] - pixels[i]);
+ return total;
+ }
+
+ private static double Psnr(byte[] blocks, byte[] source, int size)
+ {
+ byte[] decoded = Dds.DecodeLevel(blocks, size, size);
+ double squares = 0;
+ for (int i = 0; i < decoded.Length; i++) squares += (decoded[i] - source[i]) * (double)(decoded[i] - source[i]);
+ return squares == 0 ? 99 : 10 * Math.Log10(255.0 * 255.0 * decoded.Length / squares);
+ }
+}
diff --git a/tests/OrthoStreamXP.Tests/BuildBufferPoolTests.cs b/tests/OrthoStreamXP.Tests/BuildBufferPoolTests.cs
new file mode 100644
index 0000000..eb63cf0
--- /dev/null
+++ b/tests/OrthoStreamXP.Tests/BuildBufferPoolTests.cs
@@ -0,0 +1,89 @@
+using OrthoStreamXP.Textures;
+
+namespace OrthoStreamXP.Tests;
+
+/// The build pictures are reused at their exact size, and the pool never holds more than its capacity.
+public sealed class BuildBufferPoolTests
+{
+ [Fact]
+ public void A_picture_has_its_exact_length_and_is_reused()
+ {
+ var pool = new BuildBufferPool(1000);
+
+ byte[] first = pool.Rent(300);
+ pool.Return(first);
+ byte[] second = pool.Rent(300);
+
+ Assert.Equal(300, first.Length);
+ Assert.Same(first, second);
+ Assert.Equal(300, pool.RentedBytes);
+ Assert.Equal(0, pool.KeptBytes);
+ }
+
+ [Fact]
+ public void A_picture_of_another_length_is_new()
+ {
+ var pool = new BuildBufferPool(1000);
+ byte[] small = pool.Rent(100);
+ pool.Return(small);
+
+ Assert.NotSame(small, pool.Rent(200));
+ Assert.Equal(100, pool.KeptBytes);
+ }
+
+ [Fact]
+ public void Kept_pictures_stay_within_the_capacity_beside_those_in_use()
+ {
+ var pool = new BuildBufferPool(1000);
+ byte[] a = pool.Rent(400), b = pool.Rent(400), c = pool.Rent(400); // more in use than the capacity: allowed
+
+ pool.Return(a);
+ Assert.Equal(0, pool.KeptBytes); // 400 kept + 800 in use would be 1200
+ pool.Return(b);
+ Assert.Equal(400, pool.KeptBytes);
+ pool.Return(c);
+ Assert.Equal(800, pool.KeptBytes);
+ Assert.Equal(0, pool.RentedBytes);
+ }
+
+ [Fact]
+ public void A_new_picture_makes_room_by_letting_the_oldest_kept_ones_go()
+ {
+ var pool = new BuildBufferPool(1000);
+ byte[] a = pool.Rent(400), b = pool.Rent(300);
+ pool.Return(a);
+ pool.Return(b);
+
+ byte[] c = pool.Rent(500);
+
+ Assert.Equal(300, pool.KeptBytes); // the 400 went, the newer 300 fits beside the 500
+ Assert.Same(b, pool.Rent(300));
+ GC.KeepAlive(c);
+ }
+
+ [Fact]
+ public void A_picture_not_asked_for_again_is_let_go()
+ {
+ var time = new ManualTime();
+ var pool = new BuildBufferPool(1000, time);
+ byte[] old = pool.Rent(100);
+ pool.Return(old);
+
+ time.Advance(TimeSpan.FromMilliseconds(BuildBufferPool.IdleMilliseconds + 1));
+
+ Assert.NotSame(old, pool.Rent(100));
+ Assert.Equal(0, pool.KeptBytes);
+ }
+
+ /// Time that moves only when told.
+ private sealed class ManualTime : TimeProvider
+ {
+ private long _ticks;
+
+ public override long TimestampFrequency => TimeSpan.TicksPerSecond;
+
+ public override long GetTimestamp() => _ticks;
+
+ public void Advance(TimeSpan by) => _ticks += by.Ticks;
+ }
+}
diff --git a/tests/OrthoStreamXP.Tests/CacheAreasTests.cs b/tests/OrthoStreamXP.Tests/CacheAreasTests.cs
index c44d7f5..5ad0a7d 100644
--- a/tests/OrthoStreamXP.Tests/CacheAreasTests.cs
+++ b/tests/OrthoStreamXP.Tests/CacheAreasTests.cs
@@ -111,6 +111,21 @@ public void An_area_without_finished_textures_is_pictured_from_the_low_zoom_base
Assert.Equal(0, picture[3]); // the corner's tile is not on this PC: see-through
}
+ [Fact]
+ public void A_base_made_before_zoom_13_still_pictures_the_area_from_its_zoom_12_tiles()
+ {
+ using var tile = new SkiaSharp.SKBitmap(256, 256);
+ tile.Erase(new SkiaSharp.SKColor(30, 150, 70));
+ using SkiaSharp.SKData png = tile.Encode(SkiaSharp.SKEncodedImageFormat.Png, 100);
+ var store = new TileStore(Path.Join(Cache, TileStore.FolderName));
+ var (x, y) = Tiles.LatLonToTile(51.5, 17.5, 12);
+ store.Save(x, y, 12, png.ToArray());
+
+ byte[] picture = CacheAreas.Picture(Cache, new AreaName(51, 17), 48, TestContext.Current.CancellationToken)!;
+
+ Assert.Equal((70, 150, 30, 255), (picture[(24 * 48 + 24) * 4], picture[(24 * 48 + 24) * 4 + 1], picture[(24 * 48 + 24) * 4 + 2], picture[(24 * 48 + 24) * 4 + 3]));
+ }
+
[Fact]
public void A_flight_report_sums_up_the_route_and_keeps_the_earlier_ones()
{
diff --git a/tests/OrthoStreamXP.Tests/ColourMatchTests.cs b/tests/OrthoStreamXP.Tests/ColourMatchTests.cs
deleted file mode 100644
index 896b605..0000000
--- a/tests/OrthoStreamXP.Tests/ColourMatchTests.cs
+++ /dev/null
@@ -1,208 +0,0 @@
-using OrthoStreamXP.Scenery;
-using OrthoStreamXP.Setup;
-using OrthoStreamXP.Textures;
-
-namespace OrthoStreamXP.Tests;
-
-/// Photos from different captures are evened out against the low-zoom base, place by place, brightness and tint only.
-public sealed class ColourMatchTests : IDisposable
-{
- private readonly TempTree _tree = new();
- private static readonly TextureName Wroclaw = new(21840, 35872, "BI", 16);
- private const int Size = 256;
- /// The base everywhere, and a photo with the usual relation to it (ColourMatch.DefaultTarget).
- private static readonly (int R, int G, int B) BaseColour = (90, 110, 60), UsualPhoto = (65, 89, 47), GreyPhoto = (110, 110, 110);
-
- public void Dispose() => _tree.Dispose();
-
- private static byte[] Picture(Func colour, int size = Size)
- {
- byte[] rgb = new byte[size * size * 3];
- for (int y = 0; y < size; y++)
- for (int x = 0; x < size; x++)
- {
- var (r, g, b) = colour(x, y);
- (rgb[(y * size + x) * 3], rgb[(y * size + x) * 3 + 1], rgb[(y * size + x) * 3 + 2]) = ((byte)r, (byte)g, (byte)b);
- }
- return rgb;
- }
-
- private static byte[] Resize(byte[] rgb, int size, int to) => size == to ? rgb : Images.Resize(rgb, size, size, to, to, 1);
-
- private ColourMatcher Matcher(string? file = null) =>
- new(_ => (Picture((_, _) => BaseColour), Size), Resize, file is null ? null : _tree.PathOf(file));
-
- /// A whole DDS of the picture, with the correction applied as X-Plane reads it, and its level 0 decoded again.
- private static byte[] Served(byte[] rgb, TextureColour? colour)
- {
- var layout = DdsLayout.For(Size);
- byte[] file = [.. layout.Header, .. Dds.EncodeChain(rgb, layout, 0, 1)];
- colour?.Apply(file, 0, 8, Size);
- return Dds.DecodeLevel(file.AsSpan(Dds.HeaderSize, layout.LengthOf(0)), Size, Size);
- }
-
- private static (double R, double G, double B) Mean(byte[] rgb, int x0, int x1)
- {
- double r = 0, g = 0, b = 0;
- int n = 0;
- for (int y = 0; y < Size; y++)
- for (int x = x0; x < x1; x++, n++)
- (r, g, b) = (r + rgb[(y * Size + x) * 3], g + rgb[(y * Size + x) * 3 + 1], b + rgb[(y * Size + x) * 3 + 2]);
- return (r / n, g / n, b / n);
- }
-
- [Theory]
- [InlineData(16, 4)]
- [InlineData(18, 1)]
- [InlineData(15, 8)]
- [InlineData(19, 1)]
- public void A_cell_is_a_zoom_14_tile(int zoom, int cells) => Assert.Equal(cells, ColourMatch.CellsAcross(new TextureName(0, 0, "BI", zoom)));
-
- [Fact]
- public void A_grey_capture_moves_towards_the_usual_colours_and_the_usual_one_stays()
- {
- // The left half of the texture is a usual capture, the right half a grey one (cells are a quarter wide).
- byte[] photo = Picture((x, _) => x < Size / 2 ? UsualPhoto : GreyPhoto);
- TextureColour colour = Matcher().ForPhoto(Wroclaw, 1, size => (Resize(photo, Size, size), size))!;
-
- byte[] before = Served(photo, null), after = Served(photo, colour);
- var usual = Mean(after, 0, Size / 4);
- var usualBefore = Mean(before, 0, Size / 4);
- Assert.InRange(usual.R - usualBefore.R, -4, 4);
- Assert.InRange(usual.G - usualBefore.G, -4, 4);
- Assert.InRange(usual.B - usualBefore.B, -4, 4);
-
- // Moved by what is beyond a usual difference, and the change is capped: much nearer its neighbour, not all the way.
- var grey = Mean(after, Size * 3 / 4, Size);
- Assert.InRange(grey.R, UsualPhoto.R, 80);
- Assert.InRange(grey.G, UsualPhoto.G, 97);
- Assert.InRange(grey.B, UsualPhoto.B, 75);
- }
-
- [Fact]
- public void A_usual_capture_is_left_alone_though_its_fields_differ_from_the_base()
- {
- // Cell by cell up to 10 % lighter or darker than the usual relation: crops, not another capture.
- byte[] photo = Picture((x, y) => ((x / 64 + y / 64) % 3) switch
- {
- 0 => UsualPhoto,
- 1 => ((int)(UsualPhoto.R * 1.1), (int)(UsualPhoto.G * 1.1), (int)(UsualPhoto.B * 1.1)),
- _ => ((int)(UsualPhoto.R * 0.9), (int)(UsualPhoto.G * 0.9), (int)(UsualPhoto.B * 0.9)),
- });
- Assert.Null(Matcher().ForPhoto(Wroclaw, 1, size => (Resize(photo, Size, size), size)));
- }
-
- [Fact]
- public void One_odd_cell_is_not_corrected_but_a_capture_covering_several_is()
- {
- ColourGain usual = ColourMatch.DefaultTarget, grey = new(0.2f, 0f, 0.5f);
- ColourGain?[] relation = [.. Enumerable.Repeat(usual, 16)];
- relation[5] = grey; // one cell: a field, a cloud's shadow
- Assert.Null(TextureColour.Matching(relation, 4, usual));
-
- for (int i = 0; i < 16; i += 4) (relation[i + 2], relation[i + 3]) = (grey, grey); // the east half: another capture
- TextureColour colour = TextureColour.Matching(relation, 4, usual)!;
- Assert.Equal(ColourGain.None, colour.Gains[0]);
- Assert.True(colour.Gains[3].B < -0.3f, $"the grey capture loses its blue cast: {colour.Gains[3]}");
- }
-
- [Fact]
- public void A_correction_is_kept_for_its_picture_and_measured_again_for_a_new_one()
- {
- ColourMatcher matcher = Matcher();
- int samples = 0;
- (byte[], int)? Sample(int size)
- {
- samples++;
- return (Picture((_, _) => GreyPhoto, size), size);
- }
-
- TextureColour? first = matcher.ForPhoto(Wroclaw, 1, Sample);
- Assert.Same(first, matcher.ForPhoto(Wroclaw, 1, Sample));
- Assert.Equal(1, samples);
- matcher.ForPhoto(Wroclaw, 2, Sample); // a finer level arrived: perhaps another capture
- Assert.Equal(2, samples);
- }
-
- [Fact]
- public void Without_its_base_tile_a_photo_is_left_as_it_is_until_the_tile_is_here()
- {
- bool here = false;
- var matcher = new ColourMatcher(_ => here ? (Picture((_, _) => BaseColour), Size) : null, Resize, null);
- (byte[], int)? Sample(int size) => (Picture((_, _) => GreyPhoto, size), size);
-
- Assert.Null(matcher.ForPhoto(Wroclaw, 1, Sample));
- here = true;
- Assert.NotNull(matcher.ForPhoto(Wroclaw, 1, Sample));
- }
-
- [Fact]
- public void A_stand_in_from_the_base_gets_the_usual_relation_so_the_photo_does_not_jump_when_it_arrives()
- {
- TextureColour colour = Matcher().ForBase(Wroclaw)!;
- Assert.Equal(ColourMatch.DefaultTarget, Assert.Single(colour.Gains));
- }
-
- [Fact]
- public void An_area_learns_its_usual_colours_from_its_textures_and_keeps_them()
- {
- ColourMatcher matcher = Matcher("logs/colour-match.json");
- AreaName area = AreaName.Of(Wroclaw);
- // Photos here are a little brighter than the default relation says.
- byte[] bright = Picture((_, _) => (80, 100, 55));
- for (int i = 0; i < ColourMatcher.LearntFrom; i++) // northwards, within the same 1° area
- matcher.ForPhoto(Wroclaw with { Row = Wroclaw.Row - 16 * i }, 1, size => (Resize(bright, Size, size), size));
- Assert.Equal(ColourMatch.DefaultTarget, matcher.TargetOf(area)); // fixed for the session at its first use
- matcher.Save();
-
- ColourGain learnt = Matcher("logs/colour-match.json").TargetOf(area);
- Assert.InRange(learnt.R, -0.118, -0.098); // log(88 / 98): each channel + 8, as measured
- Assert.InRange(learnt.G, -0.099, -0.079); // log(108 / 118)
- Assert.InRange(learnt.B, -0.087, -0.067); // log(63 / 68)
- }
-
- [Fact]
- public void Partial_blocks_and_three_colour_blocks_are_left_as_they_are()
- {
- TextureColour colour = TextureColour.Uniform(new ColourGain(-0.4f, -0.4f, -0.4f))!;
- var layout = DdsLayout.For(64);
- byte[] file = [.. layout.Header, .. Dds.EncodeChain(Picture((_, _) => (200, 180, 160), 64), layout, 0, 1)];
- // A three-colour block (first colour not the larger) in the second block.
- (file[Dds.HeaderSize + 8], file[Dds.HeaderSize + 9], file[Dds.HeaderSize + 10], file[Dds.HeaderSize + 11]) = (0x10, 0, 0x20, 0);
- byte[] original = [.. file];
-
- colour.Apply(file.AsSpan(Dds.HeaderSize + 4, 28), Dds.HeaderSize + 4, 8, 64); // cuts the first block
- Assert.Equal(original.AsSpan(Dds.HeaderSize, 16).ToArray(), file.AsSpan(Dds.HeaderSize, 16).ToArray());
- Assert.NotEqual(original.AsSpan(Dds.HeaderSize + 16, 8).ToArray(), file.AsSpan(Dds.HeaderSize + 16, 8).ToArray());
- }
-
- [Fact]
- public void The_strength_makes_part_of_each_correction()
- {
- (byte[], int)? Grey(int size) => (Picture((_, _) => GreyPhoto, size), size);
- ColourGain full = Matcher().ForPhoto(Wroclaw, 1, Grey)!.Gains[0];
- ColourGain half = new ColourMatcher(_ => (Picture((_, _) => BaseColour), Size), Resize, null, strength: 0.5).ForPhoto(Wroclaw, 1, Grey)!.Gains[0];
-
- Assert.Equal(full.R / 2, half.R, 0.001);
- Assert.Equal(full.B / 2, half.B, 0.001);
- Assert.Null(new ColourMatcher(_ => (Picture((_, _) => BaseColour), Size), Resize, null, strength: 0).ForPhoto(Wroclaw, 1, Grey));
- Assert.Null(new ColourMatcher(_ => (Picture((_, _) => BaseColour), Size), Resize, null, strength: 0).ForBase(Wroclaw));
- }
-
- [Fact]
- public void Colour_matching_is_a_setting_off_by_default()
- {
- MountSettings Parse(params string[] extra)
- {
- Directory.CreateDirectory(_tree.PathOf("source"));
- return MountSettings.FromValues(TestSettings.Of(
- [$"source = {_tree.PathOf("source")}", $"cache = {_tree.PathOf("cache")}", $"mountpoint = {_tree.PathOf("mount")}", "texture-provider = bing", .. extra]));
- }
- Assert.False(Parse().MatchColours);
- Assert.True(Parse("match-colours = on").MatchColours);
- Assert.Throws(() => Parse("match-colours = maybe"));
- Assert.Equal(1.0, Parse().MatchStrength);
- Assert.Equal(0.6, Parse("match-strength = 60").MatchStrength, 0.0001);
- Assert.Throws(() => Parse("match-strength = 120"));
- }
-}
diff --git a/tests/OrthoStreamXP.Tests/ContrastTests.cs b/tests/OrthoStreamXP.Tests/ContrastTests.cs
new file mode 100644
index 0000000..c2e44c8
--- /dev/null
+++ b/tests/OrthoStreamXP.Tests/ContrastTests.cs
@@ -0,0 +1,44 @@
+using OrthoStreamXP.Textures;
+
+namespace OrthoStreamXP.Tests;
+
+/// The contrast: an S-curve round mid-grey, black and white kept, nothing clipped.
+public sealed class ContrastTests
+{
+ [Fact]
+ public void Black_white_and_mid_grey_stay_where_they_are()
+ {
+ Assert.Equal(0, Contrast.Apply(0), 9);
+ Assert.Equal(255, Contrast.Apply(255), 9);
+ Assert.Equal(127.5, Contrast.Apply(127.5), 9);
+ }
+
+ [Fact]
+ public void Darker_than_mid_grey_gets_darker_and_lighter_lighter_without_clipping()
+ {
+ for (int v = 1; v < 255; v++)
+ {
+ double after = Contrast.Apply(v);
+ if (v < 127) Assert.True(after < v, $"{v} -> {after:F1}");
+ if (v > 128) Assert.True(after > v, $"{v} -> {after:F1}");
+ Assert.InRange(after, 0.0, 255.0);
+ Assert.True(after > Contrast.Apply(v - 1), $"{v} keeps its order");
+ }
+ }
+
+ [Fact]
+ public void The_mid_tones_are_steeper_and_the_ends_gentler()
+ {
+ double mid = Contrast.Apply(137.5) - Contrast.Apply(117.5), end = Contrast.Apply(20) - Contrast.Apply(0);
+
+ Assert.True(mid > 20 * 1.2, $"mid-tones: 20 steps became {mid:F1}"); // about 1.26 times at 60 %
+ Assert.True(end < 20, $"shadows: 20 steps became {end:F1}");
+ }
+
+ [Fact]
+ public void Values_outside_the_range_are_clamped()
+ {
+ Assert.Equal(Contrast.Apply(0), Contrast.Apply(-10), 9);
+ Assert.Equal(Contrast.Apply(255), Contrast.Apply(300), 9);
+ }
+}
diff --git a/tests/OrthoStreamXP.Tests/DownloadTests.cs b/tests/OrthoStreamXP.Tests/DownloadTests.cs
index cdb039d..af9cd51 100644
--- a/tests/OrthoStreamXP.Tests/DownloadTests.cs
+++ b/tests/OrthoStreamXP.Tests/DownloadTests.cs
@@ -26,7 +26,7 @@ public async Task A_missing_tile_is_not_retried()
{
var server = new FakeTileServer(status: _ => HttpStatusCode.NotFound);
using var tiles = new TileSource("test", FakeTileServer.Template, 4, attempts: 4, handler: server);
- await Assert.ThrowsAsync(() => tiles.GetTileAsync(1, 2, 3, false, new TileStats()));
+ await Assert.ThrowsAsync(() => tiles.GetTileAsync(1, 2, 3, false, new TileStats()));
Assert.Single(server.Requests);
}
@@ -39,6 +39,44 @@ public async Task Server_errors_are_retried_on_the_next_server()
Assert.Equal(["t3.test", "t4.test", "t5.test"], server.Requests.Select(u => u.Host)); // (x + y + attempt) % 8
}
+ [Fact]
+ public async Task A_tile_no_provider_has_is_made_from_its_parent_at_hand()
+ {
+ // A 1024 px ZL16 texture from zoom 14: 4 x 4 tiles. One of them no provider has; its zoom 13 parent is in RAM.
+ var name = new TextureName(21904, 35824, "BI", 16);
+ int missingX = (35824 >> 2) + 1, missingY = (21904 >> 2) + 2;
+ var server = new FakeTileServer(statusOf: uri => uri.AbsolutePath == $"/14/{missingX}/{missingY}" ? HttpStatusCode.NotFound : HttpStatusCode.OK);
+ using var tiles = new TileSource("test", FakeTileServer.Template, 4, handler: server);
+ var builder = new TextureBuilder(tiles, 1);
+ await tiles.GetTileAsync(missingX >> 1, missingY >> 1, 13, false, new TileStats());
+
+ var stats = new TileStats();
+ var (rgb, size) = await builder.FetchRegionAsync(name, 14, 1024, new FetchTicket(FetchPriority.Warm), stats);
+
+ Assert.Equal((1024, 1), (size, stats.FromParents));
+ int at = ((2 * 256 + 128) * 1024 + 256 + 128) * 3; // the middle of the missing tile
+ Assert.Equal([40, 90, 160], rgb[at..(at + 3)]); // the parent's picture
+ }
+
+ [Fact]
+ public async Task A_missing_tile_without_a_parent_at_hand_or_a_network_failure_still_fails_the_build()
+ {
+ var name = new TextureName(21904, 35824, "BI", 16);
+ int x = 35824 >> 2, y = 21904 >> 2;
+ var missing = new FakeTileServer(statusOf: uri => uri.AbsolutePath == $"/14/{x}/{y}" ? HttpStatusCode.NotFound : HttpStatusCode.OK);
+ using (var tiles = new TileSource("test", FakeTileServer.Template, 4, handler: missing))
+ await Assert.ThrowsAsync(() =>
+ new TextureBuilder(tiles, 1).FetchRegionAsync(name, 14, 1024, new FetchTicket(FetchPriority.Warm), new TileStats()));
+
+ // The parent is at hand, but the tile failed for the network: it is not patched, the texture is built again later.
+ var down = new FakeTileServer(statusOf: uri => uri.AbsolutePath == $"/14/{x}/{y}" ? HttpStatusCode.ServiceUnavailable : HttpStatusCode.OK);
+ using var flaky = new TileSource("test", FakeTileServer.Template, 4, attempts: 1, handler: down);
+ await flaky.GetTileAsync(x >> 1, y >> 1, 13, false, new TileStats());
+ IOException error = await Assert.ThrowsAsync(() =>
+ new TextureBuilder(flaky, 1).FetchRegionAsync(name, 14, 1024, new FetchTicket(FetchPriority.Warm), new TileStats()));
+ Assert.IsNotType(error);
+ }
+
[Fact]
public async Task Concurrent_builds_share_one_download_per_tile()
{
diff --git a/tests/OrthoStreamXP.Tests/DynamicQualityTests.cs b/tests/OrthoStreamXP.Tests/DynamicQualityTests.cs
index ebef27c..b1b5108 100644
--- a/tests/OrthoStreamXP.Tests/DynamicQualityTests.cs
+++ b/tests/OrthoStreamXP.Tests/DynamicQualityTests.cs
@@ -139,7 +139,8 @@ public void Dynamic_is_Extra_with_dynamic_quality_on_and_any_other_preset_turns_
Assert.Equal("off", settings.Get("dynamic-quality"));
Assert.Equal(QualityPreset.Extra, QualityPreset.Current(settings.GetInt("level-change"), false));
- Assert.Equal(QualityPreset.Sharp, QualityPreset.Current(-1, true)); // dynamic-quality set by hand at another level
+ Assert.Equal(QualityPreset.DynamicSharp, QualityPreset.Current(-1, true)); // Dynamic from Sharp
+ Assert.Equal(QualityPreset.Balanced, QualityPreset.Current(-2, true)); // dynamic-quality set by hand at a level Dynamic cannot have
Assert.Equal(QualityPreset.Extra, QualityPreset.ForLevel(1)); // the cache, tuning and texture size stay Extra's
Assert.Equal(160, settings.GetInt("download-workers"));
}
@@ -166,4 +167,102 @@ public void Dynamic_shares_what_was_tuned_for_Extra()
Assert.Equal(("7.5", true), (settings.Get("max-wait"), settings.GetBool("dynamic-quality") == true));
}
+
+ // ---------------------------------------------------------------- the base
+
+ [Theory]
+ [InlineData("Extra", 1, new[] { "Sharp", "Balanced" })]
+ [InlineData("Ultra", 0, new[] { "Sharp", "Balanced" })]
+ [InlineData("Sharp", -1, new[] { "Balanced" })] // Sharp's own step is no saving at Sharp
+ public void Dynamic_from_each_base_is_that_presets_level_and_values_with_dynamic_quality_on(string baseName, int level, string[] steps)
+ {
+ QualityPreset near = QualityPreset.All.Single(p => p.Name == baseName);
+ QualityPreset dynamic = QualityPreset.DynamicOn(near)!;
+ var settings = SettingsDocument.FromText("x.ini", "level-change = -2\n");
+
+ dynamic.ApplyTo(settings);
+
+ Assert.Equal((level, true, baseName.ToLowerInvariant()),
+ (settings.GetInt("level-change"), settings.GetBool("dynamic-quality") == true, settings.Get(QualityPreset.DynamicBaseKey)));
+ Assert.Equal(near.Get("dds-build-workers"), settings.Get("dds-build-workers"));
+ Assert.Same(dynamic, QualityPreset.Current(level, true));
+ Assert.Equal(steps, dynamic.DynamicSteps.Select(t => t.Name));
+ Assert.Equal(("Dynamic", $"Dynamic from {baseName}"), (dynamic.Name, dynamic.Title));
+ Assert.Equal(near.PlanAt(TextureResolution.Full), dynamic.PlanAt(TextureResolution.Full)); // its cache and textures
+ Assert.Empty(TunedSettings.Changed(settings, dynamic)); // nothing shown as tuned: its values are its own
+ }
+
+ [Fact]
+ public void Only_Extra_Ultra_and_Sharp_can_be_Dynamics_base()
+ {
+ Assert.Equal([QualityPreset.Extra, QualityPreset.Ultra, QualityPreset.Sharp], QualityPreset.DynamicChoices.Select(p => p.DynamicBase));
+ Assert.Null(QualityPreset.DynamicOn(QualityPreset.Balanced));
+ Assert.Same(QualityPreset.Dynamic, QualityPreset.DynamicOn(QualityPreset.Extra));
+ Assert.All(QualityPreset.All, p => Assert.False(p.IsDynamic));
+ }
+
+ [Fact]
+ public void The_window_keeps_Dynamics_base_while_another_preset_is_chosen()
+ {
+ var settings = SettingsDocument.FromText("x.ini", "");
+ Assert.Same(QualityPreset.Dynamic, QualityPreset.DynamicIn(settings)); // nothing kept: Extra
+
+ QualityPreset.DynamicUltra.ApplyTo(settings);
+ QualityPreset.Balanced.ApplyTo(settings);
+ Assert.Equal(("off", "ultra"), (settings.Get("dynamic-quality"), settings.Get(QualityPreset.DynamicBaseKey)));
+ Assert.Same(QualityPreset.DynamicUltra, QualityPreset.DynamicIn(settings));
+
+ // At Dynamic, the level says which: an edited file's level wins over the base kept.
+ settings.Set("dynamic-quality", "on");
+ settings.Set("level-change", -1);
+ Assert.Same(QualityPreset.DynamicSharp, QualityPreset.DynamicIn(settings));
+
+ settings.Set("dynamic-quality", "off");
+ settings.Set(QualityPreset.DynamicBaseKey, "balanced"); // not a base Dynamic can have
+ Assert.Same(QualityPreset.Dynamic, QualityPreset.DynamicIn(settings));
+ }
+
+ [Fact]
+ public void A_mount_at_Dynamic_from_Ultra_streams_Ultras_textures_at_Dynamics_resolution()
+ {
+ MountSettings s = Parse("level-change = 0", "dynamic-quality = on", "dynamic-base = ultra", "resolution-dynamic = medium", "resolution-ultra = low");
+
+ Assert.Equal((0, TextureResolution.Medium), (s.Textures.LevelChange, s.Textures.Resolution));
+ Assert.Equal(["Sharp", "Balanced"], s.Dynamic!.TiersBelow(s.Textures).Select(t => t.Name));
+ }
+
+ [Fact]
+ public void Dynamic_from_Ultra_shares_what_was_tuned_for_Ultra()
+ {
+ string path = _tree.PathOf("orthostreamxp.ini");
+ TunedStore store = TunedStore.Load(path);
+ store.Set(QualityPreset.Ultra.Level, "max-wait", "6");
+ store.Set(QualityPreset.Extra.Level, "max-wait", "9");
+ store.Save();
+ var settings = SettingsDocument.FromText(path, "");
+
+ TunedSettings.ChoosePreset(settings, QualityPreset.DynamicUltra, TunedStore.Load(path));
+
+ Assert.Equal(("6", 0), (settings.Get("max-wait"), settings.GetInt("level-change")));
+ }
+
+ [Fact]
+ public void Each_Dynamic_needs_its_bases_downloads()
+ {
+ IReadOnlyList fits = PresetAdvisor.Assess(null, GraphicsMemory.TestFlight, [], new ConnectionResult(DateTime.UtcNow, "bing", [new ConnectionRound(64, 1024, 0, 16_900_000, 0.7, 0.14, 60)], 64), QualityPreset.Offered);
+
+ Assert.False(fits.Single(f => f.Preset == QualityPreset.Dynamic).Suits); // Extra's 100 Mbit/s
+ Assert.True(fits.Single(f => f.Preset == QualityPreset.DynamicUltra).Suits); // Ultra's 50
+ Assert.True(fits.Single(f => f.Preset == QualityPreset.DynamicSharp).Suits);
+ }
+
+ [Fact]
+ public void A_new_settings_file_keeps_Dynamics_base_and_reads_as_settings()
+ {
+ SettingsDocument settings = SettingsDocument.CreateNew(_tree.PathOf("orthostreamxp.ini"), @"C:\X-Plane 12", @"C:\Packages", @"D:\cache", QualityPreset.DynamicSharp);
+
+ Assert.Equal(("sharp", -1, true), (settings.Get(QualityPreset.DynamicBaseKey), settings.GetInt("level-change"), settings.GetBool("dynamic-quality") == true));
+ Assert.Same(QualityPreset.DynamicSharp, QualityPreset.DynamicIn(settings));
+ settings.Parse();
+ }
}
diff --git a/tests/OrthoStreamXP.Tests/ExposureTests.cs b/tests/OrthoStreamXP.Tests/ExposureTests.cs
index c0f6e94..91da128 100644
--- a/tests/OrthoStreamXP.Tests/ExposureTests.cs
+++ b/tests/OrthoStreamXP.Tests/ExposureTests.cs
@@ -4,47 +4,37 @@
namespace OrthoStreamXP.Tests;
-/// The exposure: a lookup table that darkens the photos in linear light, its setting, and the preview of the colour settings.
+/// The exposure: darkening the photos in linear light, its setting, and the preview of the colour settings.
public sealed class ExposureTests : IDisposable
{
private readonly TempTree _tree = new();
public void Dispose() => _tree.Dispose();
- private static (double R, double G, double B) Through(ushort[] table, double r, double g, double b) =>
- ColourTable.Decode565(table[ColourTable.Encode565(r, g, b)]);
-
[Fact]
- public void Full_exposure_changes_nothing_and_less_is_clamped_to_one_stop()
+ public void An_exposure_is_a_whole_percent_from_one_stop_darker_to_full()
{
- Assert.Null(Exposure.TableFor(100));
- Assert.Null(Exposure.TableFor(120));
- Assert.Same(Exposure.TableFor(Exposure.Min), Exposure.TableFor(10));
+ Assert.Equal(Exposure.Full, Exposure.Percent(120));
+ Assert.Equal(Exposure.Min, Exposure.Percent(10));
+ Assert.Equal(85, Exposure.Percent(84.6));
}
[Fact]
public void Half_the_light_is_one_stop_darker_in_linear_light_and_black_stays_black()
{
- ushort[] half = Exposure.TableFor(50)!;
-
- var white = Through(half, 255, 255, 255);
- double expected = Exposure.ToSrgb(0.5) * 255; // about 188, not 128: the shadows are not crushed
- Assert.InRange(white.R, expected - 9, expected + 9);
- Assert.InRange(white.G, expected - 5, expected + 5);
- Assert.Equal((0.0, 0.0, 0.0), Through(half, 0, 0, 0));
+ Assert.Equal(Exposure.ToSrgb(0.5) * 255, Exposure.Darken(255, 0.5), 6); // about 188, not 128: the shadows are not crushed
+ Assert.Equal(0, Exposure.Darken(0, 0.5), 6);
+ Assert.Equal(255, Exposure.Darken(255, 1), 6);
}
[Fact]
- public void Less_exposure_is_darker_for_every_colour_and_keeps_its_order()
+ public void Less_exposure_is_darker_for_every_value_and_keeps_its_order()
{
- ushort[] darker = Exposure.TableFor(80)!, darkest = Exposure.TableFor(50)!;
- foreach (var (r, g, b) in new[] { (60.0, 100.0, 50.0), (150.0, 60.0, 50.0), (200.0, 190.0, 170.0), (120.0, 120.0, 118.0) })
+ for (int v = 1; v < 256; v++)
{
- var original = ColourTable.Decode565(ColourTable.Encode565(r, g, b));
- var a = Through(darker, r, g, b);
- var c = Through(darkest, r, g, b);
- Assert.True(a.R <= original.R && a.G <= original.G && a.B <= original.B, $"80 % of {(r, g, b)}: {a}");
- Assert.True(c.R <= a.R && c.G <= a.G && c.B <= a.B, $"50 % of {(r, g, b)}: {c} brighter than 80 %: {a}");
+ Assert.True(Exposure.Darken(v, 0.8) < v, $"80 % of {v}");
+ Assert.True(Exposure.Darken(v, 0.5) < Exposure.Darken(v, 0.8), $"50 % of {v}");
+ Assert.True(Exposure.Darken(v, 0.5) > Exposure.Darken(v - 1, 0.5), $"50 % of {v} keeps its order");
}
}
@@ -79,32 +69,30 @@ private string Cache()
private static double Brightness(byte[] rgb) => rgb.Average(v => (double)v);
[Fact]
- public void The_preview_offers_the_finished_photos_and_shows_them_unchanged_without_settings()
+ public void The_preview_offers_the_finished_photos_and_shows_the_contrast_without_settings()
{
- using var preview = new ColourPreview(Cache(), _tree.PathOf("history"));
+ var preview = new ColourPreview(Cache(), _tree.PathOf("history"));
PreviewPhoto photo = Assert.Single(preview.FindPhotos(TestContext.Current.CancellationToken));
- PreviewPicture picture = preview.Render(photo, new ColourAdjustments(false, 1, SeasonOptions.Off, 100))!;
+ PreviewPicture picture = preview.Render(photo, new ColourAdjustments(SeasonOptions.Off, 100))!;
Assert.Equal(256, picture.Size);
- Assert.Equal(picture.Before, picture.After);
- Assert.Contains("No colour change", Assert.Single(picture.Notes), StringComparison.Ordinal);
+ // The contrast is always on: the summer green (darker than mid-grey) comes out darker.
+ Assert.True(Brightness(picture.After) < Brightness(picture.Before), "the contrast changes nothing");
+ Assert.Contains("Contrast 60 %", Assert.Single(picture.Notes), StringComparison.Ordinal);
}
[Fact]
public void The_preview_shows_the_season_and_the_exposure_as_X_Plane_gets_them()
{
- using var preview = new ColourPreview(Cache(), _tree.PathOf("history"));
+ var preview = new ColourPreview(Cache(), _tree.PathOf("history"));
PreviewPhoto photo = preview.FindPhotos(TestContext.Current.CancellationToken)[0];
- PreviewPicture darker = preview.Render(photo, new ColourAdjustments(false, 1, SeasonOptions.Off, 50))!;
- PreviewPicture winter = preview.Render(photo, new ColourAdjustments(false, 1, new SeasonOptions(true, 1, SeasonChoice.Winter), 100))!;
- PreviewPicture matched = preview.Render(photo, new ColourAdjustments(true, 1, SeasonOptions.Off, 100))!;
+ PreviewPicture darker = preview.Render(photo, new ColourAdjustments(SeasonOptions.Off, 50))!;
+ PreviewPicture winter = preview.Render(photo, new ColourAdjustments(new SeasonOptions(true, 1, SeasonChoice.Winter), 100))!;
Assert.True(Brightness(darker.After) < Brightness(darker.Before) - 20);
Assert.NotEqual(winter.Before, winter.After);
Assert.True(winter.After[0] > winter.After[1], "winter: the green turns brown"); // red above green
- Assert.Equal(matched.Before, matched.After); // no low-zoom base in this cache: nothing to match against
- Assert.Contains(matched.Notes, n => n.Contains("low-zoom base", StringComparison.Ordinal));
}
}
diff --git a/tests/OrthoStreamXP.Tests/FakeTileServer.cs b/tests/OrthoStreamXP.Tests/FakeTileServer.cs
index b078e18..94176ef 100644
--- a/tests/OrthoStreamXP.Tests/FakeTileServer.cs
+++ b/tests/OrthoStreamXP.Tests/FakeTileServer.cs
@@ -17,7 +17,8 @@ internal sealed class FakeTileServer(Func? status = null, F
{
public const string Template = "http://t{s}.test/{z}/{x}/{y}";
- private static readonly byte[] Tile = EncodeTile();
+ /// The tile every request gets: one colour, PNG.
+ public static readonly byte[] Tile = EncodeTile();
public static readonly byte[] TransparentTile = EncodeTile(SKColors.Transparent);
public ConcurrentQueue Requests { get; } = new();
diff --git a/tests/OrthoStreamXP.Tests/ImageryProviderTests.cs b/tests/OrthoStreamXP.Tests/ImageryProviderTests.cs
index 47ebd59..159410f 100644
--- a/tests/OrthoStreamXP.Tests/ImageryProviderTests.cs
+++ b/tests/OrthoStreamXP.Tests/ImageryProviderTests.cs
@@ -129,10 +129,21 @@ public async Task A_tile_no_provider_has_names_each_failure()
var server = new FakeTileServer(status: _ => HttpStatusCode.NotFound);
using var tiles = new TileSource([new("first", FakeTileServer.Template), new("second", Fallback)], 4, handler: server);
- IOException error = await Assert.ThrowsAsync(() => tiles.GetTileAsync(1, 2, 3, false, new TileStats()));
+ IOException error = await Assert.ThrowsAsync(() => tiles.GetTileAsync(1, 2, 3, false, new TileStats()));
Assert.Contains("first:", error.Message, StringComparison.Ordinal);
Assert.Contains("second:", error.Message, StringComparison.Ordinal);
Assert.Equal(2, server.Requests.Count);
}
+
+ [Fact]
+ public async Task A_tile_one_provider_lacks_and_the_other_cannot_reach_is_a_network_failure()
+ {
+ var server = new FakeTileServer(statusOf: uri => uri.Host == "fallback.test" ? HttpStatusCode.ServiceUnavailable : HttpStatusCode.NotFound);
+ using var tiles = new TileSource([new("first", FakeTileServer.Template), new("second", Fallback)], 4, attempts: 1, handler: server);
+
+ IOException error = await Assert.ThrowsAsync(() => tiles.GetTileAsync(1, 2, 3, false, new TileStats()));
+
+ Assert.IsNotType(error); // asked again later, it may come
+ }
}
diff --git a/tests/OrthoStreamXP.Tests/LegacyNamesTests.cs b/tests/OrthoStreamXP.Tests/LegacyNamesTests.cs
index 00fecd0..9ab23af 100644
--- a/tests/OrthoStreamXP.Tests/LegacyNamesTests.cs
+++ b/tests/OrthoStreamXP.Tests/LegacyNamesTests.cs
@@ -50,7 +50,6 @@ public void The_caches_logs_and_history_move_to_the_apps_folders_and_what_descri
_tree.WriteText("cache/.photo-xp-logs/reads-20261027-153542.csv", "reads");
_tree.WriteText("cache/.photo-xp-logs/flight-report.json", "{}");
_tree.WriteText("cache/.photo-xp-logs/flights/flight-20261026-100000.json", "{}");
- _tree.WriteText("cache/.photo-xp-logs/colour-match.json", "{}");
_tree.WriteText("cache/.photo-xp-logs/area-usage.json", "{}");
_tree.WriteText("cache/.photo-xp-logs/map/+51+017-1-v2.png", "png");
_tree.WriteText("cache/.photo-xp-base/12/2241/1367.tile", "tile");
@@ -64,7 +63,6 @@ public void The_caches_logs_and_history_move_to_the_apps_folders_and_what_descri
Assert.True(File.Exists(Path.Join(Logs, "reads-20261027-153542.csv")));
Assert.True(File.Exists(Path.Join(History, "flight-report.json")));
Assert.True(File.Exists(Path.Join(History, "flights", "flight-20261026-100000.json")));
- Assert.True(File.Exists(Path.Join(History, "colour-match.json")));
// The cache's own: renamed folders, and what describes it stays in it.
Assert.True(File.Exists(_tree.PathOf("cache/.orthostreamxp-logs/area-usage.json")));
Assert.True(File.Exists(_tree.PathOf("cache/.orthostreamxp-logs/map/+51+017-1-v2.png")));
diff --git a/tests/OrthoStreamXP.Tests/MapViewportTests.cs b/tests/OrthoStreamXP.Tests/MapViewportTests.cs
new file mode 100644
index 0000000..50e297f
--- /dev/null
+++ b/tests/OrthoStreamXP.Tests/MapViewportTests.cs
@@ -0,0 +1,109 @@
+using System.Windows;
+using OrthoStreamXP.Gui;
+
+namespace OrthoStreamXP.Tests;
+
+/// The cache map's zoom and pan: the whole map fits at first, zooming keeps the place under the pointer, and the map never leaves the view.
+public sealed class MapViewportTests
+{
+ private static MapViewport Fitted(double viewWidth = 800, double viewHeight = 400, double mapWidth = 1000, double mapHeight = 1000)
+ {
+ var viewport = new MapViewport { MaxScale = 4 };
+ viewport.Resize(new Size(viewWidth, viewHeight), new Size(mapWidth, mapHeight));
+ return viewport;
+ }
+
+ [Fact]
+ public void The_whole_map_fits_and_is_centred_on_its_short_side()
+ {
+ MapViewport viewport = Fitted();
+
+ Assert.Equal(0.4, viewport.Scale, 6);
+ Assert.Equal((800 - 400) / 2.0, viewport.OffsetX, 6);
+ Assert.Equal(0, viewport.OffsetY, 6);
+ Assert.True(viewport.IsFitted);
+ Assert.False(viewport.CanZoomOut);
+ Assert.True(viewport.CanZoomIn);
+ }
+
+ [Fact]
+ public void Zooming_keeps_the_place_under_the_pointer()
+ {
+ MapViewport viewport = Fitted();
+ var pointer = new Point(400, 200);
+ Point before = viewport.ToMap(pointer);
+
+ Assert.True(viewport.ZoomAt(pointer, 2));
+
+ Assert.Equal(0.8, viewport.Scale, 6);
+ Point after = viewport.ToMap(pointer);
+ Assert.Equal(before.X, after.X, 6);
+ Assert.Equal(before.Y, after.Y, 6);
+ Assert.False(viewport.IsFitted);
+ }
+
+ [Fact]
+ public void Zoom_stops_at_the_whole_map_and_at_the_largest_scale()
+ {
+ MapViewport viewport = Fitted();
+
+ Assert.False(viewport.ZoomAt(new Point(0, 0), 0.5));
+ Assert.True(viewport.ZoomAt(new Point(0, 0), 100));
+ Assert.Equal(4, viewport.Scale, 6);
+ Assert.False(viewport.ZoomAt(new Point(0, 0), 2));
+
+ Assert.True(viewport.ZoomAt(new Point(0, 0), 0.001));
+ Assert.Equal(0.4, viewport.Scale, 6);
+ Assert.True(viewport.IsFitted);
+ }
+
+ [Fact]
+ public void The_map_cannot_be_dragged_out_of_sight()
+ {
+ MapViewport viewport = Fitted();
+ viewport.ZoomAt(new Point(400, 200), 2); // the map is now 800 x 800 in a 800 x 400 view
+
+ viewport.PanBy(new Vector(5000, 5000));
+ Assert.Equal(0, viewport.OffsetX, 6);
+ Assert.Equal(0, viewport.OffsetY, 6);
+
+ viewport.PanBy(new Vector(-5000, -5000));
+ Assert.Equal(0, viewport.OffsetX, 6);
+ Assert.Equal(400 - 800, viewport.OffsetY, 6);
+ }
+
+ [Fact]
+ public void A_fitted_map_refits_when_the_view_grows_but_a_zoomed_one_keeps_its_zoom()
+ {
+ MapViewport viewport = Fitted();
+ viewport.Resize(new Size(800, 800), new Size(1000, 1000));
+ Assert.Equal(0.8, viewport.Scale, 6);
+
+ viewport.ZoomAt(new Point(0, 0), 2);
+ viewport.Resize(new Size(900, 800), new Size(1000, 1000));
+ Assert.Equal(1.6, viewport.Scale, 6);
+
+ viewport.Fit();
+ Assert.Equal(0.8, viewport.Scale, 6);
+ }
+
+ [Theory]
+ [InlineData(100, 1)]
+ [InlineData(30, 2)]
+ [InlineData(10, 5)]
+ [InlineData(0.5, 30)]
+ public void Grid_lines_are_far_enough_apart(double pixelsPerDegree, int step) =>
+ Assert.Equal(step, Graticule.Step(pixelsPerDegree));
+
+ [Fact]
+ public void The_projection_turns_back_into_degrees()
+ {
+ var map = new MapProjection(10, 55, 100, 0.6);
+
+ Assert.Equal(0, map.X(10), 6);
+ Assert.Equal(60, map.X(11), 6);
+ Assert.Equal(200, map.Y(53), 6);
+ Assert.Equal(12.5, map.Lon(map.X(12.5)), 6);
+ Assert.Equal(51.25, map.Lat(map.Y(51.25)), 6);
+ }
+}
diff --git a/tests/OrthoStreamXP.Tests/MipFilterTests.cs b/tests/OrthoStreamXP.Tests/MipFilterTests.cs
new file mode 100644
index 0000000..234a2a8
--- /dev/null
+++ b/tests/OrthoStreamXP.Tests/MipFilterTests.cs
@@ -0,0 +1,75 @@
+using OrthoStreamXP.Textures;
+
+namespace OrthoStreamXP.Tests;
+
+public sealed class MipFilterTests
+{
+ [Fact]
+ public void Every_flat_colour_stays_exactly_itself()
+ {
+ byte[] values = [.. Enumerable.Range(0, 256).Select(c => (byte)c)];
+ // 256 pixels in a 16 x 16 picture, each 2 x 2 group one value: the half is those values again.
+ byte[] picture = new byte[32 * 32 * 3];
+ for (int y = 0; y < 32; y++)
+ for (int x = 0; x < 32; x++)
+ for (int k = 0; k < 3; k++)
+ picture[(y * 32 + x) * 3 + k] = values[y / 2 * 16 + x / 2];
+
+ byte[] half = MipFilter.Half(picture, 32, 32, 1);
+
+ for (int i = 0; i < 256; i++) Assert.Equal(values[i], half[i * 3]);
+ }
+
+ [Fact]
+ public void Black_and_white_average_to_the_grey_of_half_their_light_not_to_128()
+ {
+ byte[] checker = new byte[2 * 2 * 3];
+ checker.AsSpan(0, 3).Fill(255);
+ checker.AsSpan(9, 3).Fill(255);
+
+ Assert.Equal(188, MipFilter.Half(checker, 2, 2, 1)[0]); // sRGB 188 is half of white's light
+ Assert.Equal(128, Images.BoxHalf(checker, 2, 2, 1)[0]); // the stored values' average, far darker
+ }
+
+ [Fact]
+ public void The_tables_round_like_the_curve_itself()
+ {
+ var random = new Random(5);
+ for (int i = 0; i < 20_000; i++)
+ {
+ // Dark values are where the tables are tightest: sample them as densely as the rest.
+ double light = i % 2 == 0 ? random.NextDouble() : Math.Pow(random.NextDouble(), 6);
+ uint scaled = (uint)Math.Round(light * (1 << 24));
+ double value = StoredValue(scaled / (double)(1 << 24));
+ int exact = (int)Math.Round(value, MidpointRounding.AwayFromZero);
+ bool onBoundary = Math.Abs(value - Math.Floor(value) - 0.5) < 0.01; // closer than the 2^24 scale can tell
+ if (!onBoundary) Assert.Equal(exact, MipFilter.Stored(scaled));
+ else Assert.InRange(MipFilter.Stored(scaled), exact - 1, exact);
+ }
+ }
+
+ [Fact]
+ public void The_whole_chain_keeps_the_pictures_light_where_stored_averages_darken_it()
+ {
+ const int size = 256;
+ byte[] photo = Images.SyntheticTile(400, 700, 15);
+ // Each level is rounded to whole stored values once: across eight levels that drifts a little, never far.
+ Assert.InRange(StoredValue(MeanLight(Chain(photo, size, MipFilter.Half))) - StoredValue(MeanLight(photo)), -1.5, 1.5);
+
+ // A fine pattern of dark and light (shadows between roofs): the light it gives is sRGB 149, not the values' 120.
+ byte[] pattern = new byte[size * size * 3];
+ for (int p = 0; p < size * size; p++) pattern.AsSpan(p * 3, 3).Fill((p + p / size) % 2 == 0 ? (byte)40 : (byte)200);
+ Assert.InRange(Chain(pattern, size, MipFilter.Half)[0], 148, 150);
+ Assert.Equal(120, Chain(pattern, size, Images.BoxHalf)[0]);
+ }
+
+ private static byte[] Chain(byte[] picture, int size, Func half)
+ {
+ for (int s = size; s > 1; s >>= 1) picture = half(picture, s, s, 1);
+ return picture;
+ }
+
+ private static double MeanLight(byte[] rgb) => rgb.Average(v => MipFilter.Linear(v / 255.0));
+
+ private static double StoredValue(double light) => 255 * (light <= 0.0031308 ? light * 12.92 : 1.055 * Math.Pow(light, 1 / 2.4) - 0.055);
+}
diff --git a/tests/OrthoStreamXP.Tests/MountSmokeTests.cs b/tests/OrthoStreamXP.Tests/MountSmokeTests.cs
index 616df5d..e785180 100644
--- a/tests/OrthoStreamXP.Tests/MountSmokeTests.cs
+++ b/tests/OrthoStreamXP.Tests/MountSmokeTests.cs
@@ -24,14 +24,14 @@ public void A_real_mount_serves_a_texture_and_a_terrain_definition_then_unmounts
string mount = _tree.PathOf("mount");
MountSettings settings = MountSettings.FromValues(TestSettings.Of(
$"source = {_tree.PathOf("source")}", $"cache = {_tree.PathOf("cache")}", $"mountpoint = {mount}",
- "texture-provider = synthetic", "level-change = -3"));
+ "texture-provider = synthetic", "level-change = -2"));
// Dispose stops without the flight summaries, so nothing is written to the user's history.
using (MountSession.Start(settings))
{
byte[] dds = File.ReadAllBytes(Path.Join(mount, "textures", Stem + ".dds"));
Assert.Equal("DDS "u8.ToArray(), dds[..4]);
- Assert.Equal(DdsLayout.For(512).Length, dds.Length); // level -3: a ZL16 texture is 512 px
+ Assert.Equal(DdsLayout.For(2048).Length, dds.Length); // Balanced: a ZL16 texture is 2048 px, the detail of zoom 15
string definition = File.ReadAllText(Path.Join(mount, "terrain", Stem + ".ter"));
Assert.Contains($"BASE_TEX_NOWRAP ../textures/{Stem}.dds", definition, StringComparison.Ordinal);
diff --git a/tests/OrthoStreamXP.Tests/NdviPictures.cs b/tests/OrthoStreamXP.Tests/NdviPictures.cs
new file mode 100644
index 0000000..99b684f
--- /dev/null
+++ b/tests/OrthoStreamXP.Tests/NdviPictures.cs
@@ -0,0 +1,109 @@
+using System.Buffers.Binary;
+using System.Globalization;
+using System.IO.Compression;
+using System.Xml.Linq;
+using OrthoStreamXP.Textures;
+
+namespace OrthoStreamXP.Tests;
+
+///
+/// Pictures as NASA GIBS sends its vegetation index: 8-bit palette PNGs in the colours of its colour map, the palette
+/// index being the map's "ref", "no data" and the values below zero transparent.
+///
+internal static class NdviPictures
+{
+ /// The colour map's entries: ref, colour, the middle of its class (NaN for "no data"), and whether it is transparent.
+ public static readonly IReadOnlyList<(int Ref, byte R, byte G, byte B, double Value, bool Transparent)> Entries = Load();
+
+ /// The ref of the class nearest a greenness of 0 to 1.
+ public static int RefOf(double ndvi) =>
+ Entries.Where(e => !double.IsNaN(e.Value) && !e.Transparent).MinBy(e => Math.Abs(e.Value - ndvi)).Ref;
+
+ public const int NoData = 0;
+ public const int Water = 1;
+
+ /// A 512 x 512 picture, every pixel of class (x, y).
+ public static byte[] Picture(Func paint, int size = VegetationTile.Pixels)
+ {
+ byte[] indices = new byte[size * size];
+ for (int y = 0; y < size; y++)
+ for (int x = 0; x < size; x++)
+ indices[y * size + x] = (byte)paint(x, y);
+ return Encode(indices, size, size);
+ }
+
+ /// A picture of one greenness everywhere.
+ public static byte[] Uniform(double ndvi)
+ {
+ int index = RefOf(ndvi);
+ return Picture((_, _) => index);
+ }
+
+ private static byte[] Encode(byte[] indices, int width, int height)
+ {
+ using var png = new MemoryStream();
+ png.Write([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]);
+ byte[] header = new byte[13];
+ BinaryPrimitives.WriteInt32BigEndian(header, width);
+ BinaryPrimitives.WriteInt32BigEndian(header.AsSpan(4), height);
+ header[8] = 8; // bit depth
+ header[9] = 3; // palette
+ Chunk(png, "IHDR", header);
+ int colours = Entries.Max(e => e.Ref) + 1;
+ byte[] palette = new byte[colours * 3], alpha = new byte[colours];
+ foreach (var e in Entries)
+ {
+ (palette[e.Ref * 3], palette[e.Ref * 3 + 1], palette[e.Ref * 3 + 2]) = (e.R, e.G, e.B);
+ alpha[e.Ref] = e.Transparent ? (byte)0 : (byte)255;
+ }
+ Chunk(png, "PLTE", palette);
+ Chunk(png, "tRNS", alpha);
+ using var raw = new MemoryStream();
+ using (var zlib = new ZLibStream(raw, CompressionLevel.Fastest, leaveOpen: true))
+ for (int y = 0; y < height; y++)
+ {
+ zlib.WriteByte(0); // no filter
+ zlib.Write(indices, y * width, width);
+ }
+ Chunk(png, "IDAT", raw.ToArray());
+ Chunk(png, "IEND", []);
+ return png.ToArray();
+ }
+
+ private static void Chunk(Stream png, string type, byte[] data)
+ {
+ byte[] length = new byte[4], crc = new byte[4];
+ BinaryPrimitives.WriteInt32BigEndian(length, data.Length);
+ png.Write(length);
+ byte[] typed = [.. System.Text.Encoding.ASCII.GetBytes(type), .. data];
+ png.Write(typed);
+ BinaryPrimitives.WriteUInt32BigEndian(crc, Crc32(typed));
+ png.Write(crc);
+ }
+
+ private static uint Crc32(byte[] data)
+ {
+ uint crc = 0xFFFFFFFF;
+ foreach (byte b in data)
+ {
+ crc ^= b;
+ for (int k = 0; k < 8; k++) crc = (crc & 1) != 0 ? 0xEDB88320 ^ (crc >> 1) : crc >> 1;
+ }
+ return ~crc;
+ }
+
+ private static List<(int, byte, byte, byte, double, bool)> Load()
+ {
+ using Stream stream = typeof(NdviPalette).Assembly.GetManifestResourceStream("OrthoStreamXP.ndvi-colormap.xml")!;
+ var entries = new List<(int, byte, byte, byte, double, bool)>();
+ foreach (XElement e in XDocument.Load(stream).Descendants("ColorMapEntry"))
+ {
+ byte[] rgb = [.. ((string)e.Attribute("rgb")!).Split(',').Select(c => byte.Parse(c, CultureInfo.InvariantCulture))];
+ string[] ends = ((string)e.Attribute("value")!).Trim('[', ')').Split(',');
+ double value = (string?)e.Attribute("nodata") == "true" ? double.NaN
+ : Math.Max(0, (double.Parse(ends[0], CultureInfo.InvariantCulture) + double.Parse(ends[1], CultureInfo.InvariantCulture)) / 2);
+ entries.Add((int.Parse((string)e.Attribute("ref")!, CultureInfo.InvariantCulture), rgb[0], rgb[1], rgb[2], value, (string?)e.Attribute("transparent") == "true"));
+ }
+ return entries;
+ }
+}
diff --git a/tests/OrthoStreamXP.Tests/PhotoColoursTests.cs b/tests/OrthoStreamXP.Tests/PhotoColoursTests.cs
new file mode 100644
index 0000000..aaffd77
--- /dev/null
+++ b/tests/OrthoStreamXP.Tests/PhotoColoursTests.cs
@@ -0,0 +1,110 @@
+using OrthoStreamXP.Scenery;
+using OrthoStreamXP.Textures;
+
+namespace OrthoStreamXP.Tests;
+
+/// The season, the contrast and the exposure made into one lookup table, rounded to 565 once.
+public sealed class PhotoColoursTests
+{
+ // Whole 1/32 steps of the seasons, so the tables are made for exactly these.
+ private static readonly SeasonState Winter = new(0, 0, 1, 1), Autumn = new(0, 1, 0.125, 0);
+
+ [Fact]
+ public void Without_a_season_or_an_exposure_the_photos_still_get_the_contrast()
+ {
+ ushort[] table = PhotoColours.TableFor(SeasonState.Summer, Exposure.Full);
+
+ for (int c = 0; c < 65536; c += 97)
+ {
+ var (r, g, b) = ColourTable.Decode565(c);
+ Assert.Equal(ColourTable.Encode565(Contrast.Apply(r), Contrast.Apply(g), Contrast.Apply(b)), table[c]);
+ }
+ Assert.NotEqual(ColourTable.Encode565(60, 100, 50), table[ColourTable.Encode565(60, 100, 50)]);
+ // A season too small to show is summer: the same table.
+ Assert.Same(table, PhotoColours.TableFor(new SeasonState(0.015, 0, 0.015, 0), Exposure.Full));
+ }
+
+ [Fact]
+ public void Each_season_and_exposure_is_one_table_kept_for_every_texture()
+ {
+ ushort[] both = PhotoColours.TableFor(Winter, 60);
+
+ Assert.Same(both, PhotoColours.TableFor(Winter, 60.2)); // a whole percent
+ Assert.NotSame(both, PhotoColours.TableFor(Winter, 70));
+ Assert.NotSame(both, PhotoColours.TableFor(Winter, Exposure.Full));
+ Assert.NotSame(both, PhotoColours.TableFor(SeasonState.Summer, 60));
+ }
+
+ [Theory]
+ [InlineData(100)]
+ [InlineData(75)]
+ [InlineData(50)]
+ public void One_rounding_is_never_farther_from_the_exact_colour_than_one_per_adjustment(double exposure)
+ {
+ double factor = exposure / 100, oneRounding = 0, eachRounded = 0;
+ ushort[] season = Table(c => Seasons.Recolor(c.R, c.G, c.B, Autumn));
+ ushort[] contrast = Table(c => (Contrast.Apply(c.R), Contrast.Apply(c.G), Contrast.Apply(c.B)));
+ ushort[] darker = Table(c => (Exposure.Darken(c.R, factor), Exposure.Darken(c.G, factor), Exposure.Darken(c.B, factor)));
+ ushort[] all = PhotoColours.TableFor(Autumn, exposure);
+
+ for (int c = 0; c < 65536; c++)
+ {
+ var (r, g, b) = ColourTable.Decode565(c);
+ var exact = PhotoColours.Adjust(r, g, b, Autumn, factor);
+ var one = Errors(exact, all[c]);
+ var each = Errors(exact, darker[contrast[season[c]]]);
+ Assert.True(one.R <= each.R + 1e-9 && one.G <= each.G + 1e-9 && one.B <= each.B + 1e-9, $"colour {c}: {one} against {each}");
+ oneRounding += one.R + one.G + one.B;
+ eachRounded += each.R + each.G + each.B;
+ }
+
+ Assert.True(oneRounding < eachRounded * 0.95, $"one rounding {oneRounding:F0}, one per adjustment {eachRounded:F0}");
+ }
+
+ [Fact]
+ public void A_season_clock_gives_each_texture_one_table_with_the_contrast_and_the_exposure()
+ {
+ Assert.True(TextureName.TryParseFile("21840_35584_BI16.dds", out TextureName name));
+
+ Assert.Same(PhotoColours.TableFor(Winter, 60),
+ new SeasonClock(new SeasonOptions(true, 1, SeasonChoice.Winter), null, exposure: 60).TableFor(name));
+ Assert.Same(PhotoColours.TableFor(SeasonState.Summer, 60),
+ new SeasonClock(new SeasonOptions(true, 1, SeasonChoice.Summer), null, exposure: 60).TableFor(name));
+ Assert.Same(PhotoColours.TableFor(SeasonState.Summer, Exposure.Full),
+ new SeasonClock(new SeasonOptions(true, 1, SeasonChoice.Summer), null).TableFor(name));
+ }
+
+ [Fact]
+ public void Applying_is_the_tables_recolouring_and_nothing_without_one()
+ {
+ byte[] dds = Dds.Encode(Images.SyntheticTile(3, 4, 14), 256, 256, 1, out _, out _);
+ byte[] expected = (byte[])dds.Clone(), unchanged = (byte[])dds.Clone();
+ ushort[] table = PhotoColours.TableFor(Autumn, 75);
+
+ ColourTable.Apply(expected, 0, 8, table);
+ PhotoColours.Apply(dds, 0, 8, table);
+ PhotoColours.Apply(unchanged, 0, 8, null);
+
+ Assert.Equal(expected, dds);
+ Assert.Equal(Dds.Encode(Images.SyntheticTile(3, 4, 14), 256, 256, 1, out _, out _), unchanged);
+ }
+
+ /// One adjustment alone as a lookup table, rounded to 565.
+ private static ushort[] Table(Func<(double R, double G, double B), (double R, double G, double B)> adjust)
+ {
+ var table = new ushort[65536];
+ for (int c = 0; c < table.Length; c++)
+ {
+ var (r, g, b) = adjust(ColourTable.Decode565(c));
+ table[c] = (ushort)ColourTable.Encode565(r, g, b);
+ }
+ return table;
+ }
+
+ /// How far each channel of a 565 colour lies from the exact colour.
+ private static (double R, double G, double B) Errors((double R, double G, double B) exact, int c)
+ {
+ var (r, g, b) = ColourTable.Decode565(c);
+ return (Math.Abs(r - exact.R), Math.Abs(g - exact.G), Math.Abs(b - exact.B));
+ }
+}
diff --git a/tests/OrthoStreamXP.Tests/PhotoTileServer.cs b/tests/OrthoStreamXP.Tests/PhotoTileServer.cs
new file mode 100644
index 0000000..64e599c
--- /dev/null
+++ b/tests/OrthoStreamXP.Tests/PhotoTileServer.cs
@@ -0,0 +1,49 @@
+using System.Collections.Concurrent;
+using System.Globalization;
+using System.Net;
+using OrthoStreamXP.Textures;
+using SkiaSharp;
+
+namespace OrthoStreamXP.Tests;
+
+///
+/// An XYZ tile server ("http://t{s}.test/{z}/{x}/{y}") answering a JPEG photo that differs per tile (the synthetic
+/// pattern of that tile), so builds go through real JPEG decoding. answers 404 (no provider
+/// has it); answers that tile at 512 x 512, as providers occasionally do.
+///
+internal sealed class PhotoTileServer(Func? missing = null, Func? large = null) : HttpMessageHandler
+{
+ public const string Template = "http://t{s}.test/{z}/{x}/{y}";
+
+ private readonly ConcurrentDictionary<(int, int, int, bool), byte[]> _encoded = new();
+
+ protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
+ {
+ string[] parts = request.RequestUri!.AbsolutePath.Trim('/').Split('/');
+ int zoom = int.Parse(parts[0], CultureInfo.InvariantCulture), x = int.Parse(parts[1], CultureInfo.InvariantCulture),
+ y = int.Parse(parts[2], CultureInfo.InvariantCulture);
+ if (missing?.Invoke(x, y, zoom) == true) return Task.FromResult(new HttpResponseMessage(HttpStatusCode.NotFound) { Content = new ByteArrayContent([]) });
+ bool big = large?.Invoke(x, y, zoom) == true;
+ byte[] body = _encoded.GetOrAdd((x, y, zoom, big), key => Jpeg(key.Item1, key.Item2, key.Item3, key.Item4));
+ return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(body) });
+ }
+
+ /// The tile's synthetic pattern as a JPEG, 256 px or () stretched to 512 px.
+ public static byte[] Jpeg(int x, int y, int zoom, bool big = false)
+ {
+ int size = big ? 512 : Tiles.TilePx;
+ byte[] rgb = Images.SyntheticTile(x, y, zoom);
+ if (big) rgb = Images.ResizeBicubic(rgb, Tiles.TilePx, Tiles.TilePx, size, size, 1);
+ using var bitmap = new SKBitmap(new SKImageInfo(size, size, SKColorType.Rgba8888, SKAlphaType.Opaque));
+ Span pixels = bitmap.GetPixelSpan();
+ for (int i = 0, o = 0; i < rgb.Length; i += 3, o += 4)
+ {
+ pixels[o] = rgb[i];
+ pixels[o + 1] = rgb[i + 1];
+ pixels[o + 2] = rgb[i + 2];
+ pixels[o + 3] = 255;
+ }
+ using SKData jpeg = bitmap.Encode(SKEncodedImageFormat.Jpeg, 85);
+ return jpeg.ToArray();
+ }
+}
diff --git a/tests/OrthoStreamXP.Tests/SatelliteSeasonsTests.cs b/tests/OrthoStreamXP.Tests/SatelliteSeasonsTests.cs
new file mode 100644
index 0000000..f70ca2b
--- /dev/null
+++ b/tests/OrthoStreamXP.Tests/SatelliteSeasonsTests.cs
@@ -0,0 +1,371 @@
+using System.Collections.Concurrent;
+using System.Globalization;
+using System.Net;
+using OrthoStreamXP.Scenery;
+using OrthoStreamXP.Textures;
+
+namespace OrthoStreamXP.Tests;
+
+///
+/// The seasons timed by the satellite record: a place's year of greenness, its season against the calendar, NASA's
+/// pictures read into cells, the record downloaded and kept, and the textures' tables.
+///
+public sealed class SatelliteSeasonsTests : IDisposable
+{
+ private readonly TempTree _tree = new();
+
+ public void Dispose() => _tree.Dispose();
+
+ private static int Day(int month, int day) => new DateTime(2025, month, day).DayOfYear - 1;
+
+ // NASA's VIIRS monthly greenness of real places, October 2025 to September 2026, January first.
+ private static readonly double[] Warsaw = [0.02, 0.04, 0.27, 0.40, 0.53, 0.58, 0.51, 0.52, 0.53, 0.44, 0.32, 0.27];
+ private static readonly double[] Wroclaw = [0.44, 0.43, 0.43, 0.54, 0.68, 0.74, 0.71, 0.69, 0.69, 0.62, 0.55, 0.50]; // farmland with winter crops
+ private static readonly double[] Brest = [0.51, 0.51, 0.55, 0.59, 0.59, 0.60, 0.58, 0.54, 0.54, 0.51, 0.50, 0.50];
+ private static readonly double[] Brittany = [0.46, 0.74, 0.73, 0.74, 0.76, 0.73, 0.63, 0.54, 0.58, 0.78, 0.71, 0.73];
+ private static readonly double[] Kenya = [0.42, 0.34, 0.65, 0.62, 0.68, 0.57, 0.44, 0.31, 0.29, 0.33, 0.40, 0.34];
+
+ private static GreennessYear Year(double[] months) => GreennessYear.From(months)!;
+
+ // ---------------------------------------------------------------- a year of greenness
+
+ [Fact]
+ public void A_missing_month_is_drawn_between_its_neighbours_and_too_many_missing_is_no_year()
+ {
+ double[] months = [.. Warsaw];
+ months[5] = double.NaN;
+ Assert.InRange(Year(months).At(Day(6, 15)), 0.51, 0.53);
+
+ double[] gappy = [.. Warsaw];
+ for (int m = 0; m < 4; m++) gappy[m * 3] = double.NaN;
+ Assert.Null(GreennessYear.From(gappy));
+ }
+
+ [Fact]
+ public void One_odd_month_is_evened_out_but_a_season_of_two_and_the_greenest_month_stay()
+ {
+ double[] cloudy = [.. Enumerable.Repeat(0.7, 12)];
+ cloudy[0] = 0.3; // one cloudy or flooded January
+ Assert.True(Year(cloudy).Range < 0.01);
+
+ double[] winter = [.. Enumerable.Repeat(0.7, 12)];
+ winter[0] = winter[1] = 0.3;
+ Assert.InRange(Year(winter).Range, 0.39, 0.41);
+
+ Assert.Equal(0.58, Year(Warsaw).Peak, 3); // June, greener than May and July
+ }
+
+ [Fact]
+ public void The_greenness_runs_between_the_middles_of_the_months_and_round_the_year()
+ {
+ GreennessYear year = Year([0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0]);
+ Assert.Equal(0, year.ShareOfPeak(Day(3, 15)), 2);
+ Assert.Equal(1, year.ShareOfPeak(Day(8, 15)), 2);
+ Assert.InRange(year.ShareOfPeak(Day(5, 31)), 0.4, 0.6);
+ Assert.Equal(year.At(0), year.At(365), 6);
+ Assert.Equal(1, Year(new double[12]).ShareOfPeak(Day(1, 15))); // never green: nothing to rest from
+ }
+
+ // ---------------------------------------------------------------- the season against the calendar
+
+ [Fact]
+ public void The_trees_keep_the_calendar_where_the_fields_would_mistime_them()
+ {
+ // Wroclaw's winter crops and late crop growth once made its spring five weeks late: bare trees in mid-May.
+ foreach (int day in new[] { Day(4, 20), Day(5, 15), Day(10, 15), Day(11, 6) })
+ {
+ SeasonState calendar = SeasonModel.For(day, 51.15), observed = ObservedSeason.For(Year(Wroclaw), day, 51.15);
+ Assert.Equal((calendar.Spring, calendar.Autumn, calendar.Bare), (observed.Spring, observed.Autumn, observed.Bare));
+ }
+ Assert.True(ObservedSeason.For(Year(Wroclaw), Day(5, 15), 51.15).Spring > 0.9);
+ }
+
+ [Fact]
+ public void A_snowy_winter_rests_fully_and_the_summer_is_the_photos()
+ {
+ SeasonState jan = ObservedSeason.For(Year(Warsaw), Day(1, 15), 52.1);
+
+ Assert.True(jan.Bare > 0.9 && jan.Dormant > 0.95, $"January: {jan}");
+ Assert.True(ObservedSeason.For(Year(Warsaw), Day(7, 15), 52.1).IsSummer);
+ }
+
+ [Fact]
+ public void A_coast_green_all_year_stays_green_in_winter()
+ {
+ SeasonState calendar = SeasonModel.For(Day(1, 15), 48.37), observed = ObservedSeason.For(Year(Brest), Day(1, 15), 48.37);
+
+ Assert.True(calendar.Dormant > 0.9);
+ Assert.True(observed.Dormant < 0.2, $"January's grass and fields green: {observed}");
+ Assert.Equal(calendar.Bare, observed.Bare); // the broadleaf trees are bare all the same
+ }
+
+ [Fact]
+ public void A_dry_summer_dries_the_fields_without_autumn_leaves()
+ {
+ SeasonState august = ObservedSeason.For(Year(Brittany), Day(8, 20), 48.2);
+
+ Assert.True(SeasonModel.For(Day(8, 20), 48.2).IsSummer);
+ Assert.True(august.Dormant > 0.4, $"August's dry grass and harvested fields: {august}");
+ Assert.Equal(0, august.Autumn + august.Bare + august.Spring);
+ }
+
+ [Fact]
+ public void The_tropics_show_their_dry_season_on_the_grass_and_leave_the_trees()
+ {
+ SeasonState dry = ObservedSeason.For(Year(Kenya), Day(8, 20), -1.5), wet = ObservedSeason.For(Year(Kenya), Day(5, 1), -1.5);
+
+ Assert.True(SeasonModel.For(Day(8, 20), -1.5).IsSummer);
+ Assert.True(dry.Dormant > 0.9, $"the dry season: {dry}");
+ Assert.Equal(0, dry.Bare + dry.Autumn + dry.Spring);
+ Assert.True(wet.IsSummer, $"the rains: {wet}");
+ }
+
+ [Fact]
+ public void A_place_never_very_green_keeps_the_calendar()
+ {
+ GreennessYear town = Year([0.10, 0.11, 0.12, 0.16, 0.20, 0.25, 0.25, 0.24, 0.20, 0.16, 0.12, 0.10]);
+
+ foreach (int day in new[] { Day(1, 15), Day(4, 20), Day(7, 15), Day(10, 15) })
+ Assert.Equal(SeasonModel.For(day, 50), ObservedSeason.For(town, day, 50));
+ Assert.StartsWith("too little vegetation", ObservedSeason.Describe(town, Day(1, 15)), StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public void The_preview_says_how_green_the_place_is_against_its_greenest_month()
+ {
+ Assert.Equal("85% as green as in its greenest month: grass and fields resting 8%", ObservedSeason.Describe(Year(Brest), Day(1, 15)));
+ }
+
+ // ---------------------------------------------------------------- NASA's pictures
+
+ [Fact]
+ public void A_picture_is_averaged_into_cells_with_water_as_zero_and_no_data_as_nothing()
+ {
+ int green = NdviPictures.RefOf(0.6), dry = NdviPictures.RefOf(0.2);
+ byte[] png = NdviPictures.Picture((x, y) => x < 128 ? NdviPictures.NoData : x < 256 ? NdviPictures.Water : x < 384 ? green
+ // the last cells: alternate pixels dry and green, and the very last row of cells mostly without data
+ : y >= 508 ? (x % 4 == 0 && y % 4 == 0 ? green : NdviPictures.NoData) : (x + y) % 2 == 0 ? dry : green);
+
+ byte[] cells = VegetationTile.CellsOf(png);
+
+ Assert.Equal(NdviPalette.NoData, cells[10 * VegetationTile.Cells + 5]);
+ Assert.Equal(0, NdviPalette.ValueOf(cells[10 * VegetationTile.Cells + 40]), 3);
+ Assert.Equal(0.6, NdviPalette.ValueOf(cells[10 * VegetationTile.Cells + 80]), 2);
+ Assert.Equal(0.4, NdviPalette.ValueOf(cells[10 * VegetationTile.Cells + 110]), 2);
+ Assert.Equal(NdviPalette.NoData, cells[127 * VegetationTile.Cells + 110]);
+ Assert.Throws(() => VegetationTile.CellsOf(NdviPictures.Picture((_, _) => green, size: 256)));
+ Assert.Throws(() => VegetationTile.CellsOf([1, 2, 3]));
+ }
+
+ [Fact]
+ public void A_town_takes_the_season_of_the_fields_around_it()
+ {
+ var key = VegetationKey.At(52.2, 21.0);
+ byte[]?[] months = new byte[]?[12];
+ for (int m = 0; m < 12; m++)
+ {
+ months[m] = new byte[VegetationTile.MonthBytes];
+ Array.Fill(months[m]!, NdviPalette.CodeOf(Warsaw[m]));
+ }
+ // The town's cell: grey all year.
+ int cx = (int)((21.0 - key.West) / VegetationKey.Span * VegetationTile.Cells), cy = (int)((key.North - 52.2) / VegetationKey.Span * VegetationTile.Cells);
+ foreach (byte[]? month in months) month![cy * VegetationTile.Cells + cx] = NdviPalette.CodeOf(0.15);
+
+ GreennessYear year = new VegetationTile(key, months).YearAt(52.2, 21.0)!;
+
+ Assert.True(year.Range > 0.45, $"range {year.Range}");
+ Assert.Null(new VegetationTile(key, new byte[]?[12]).YearAt(52.2, 21.0));
+ }
+
+ [Fact]
+ public void A_place_is_in_the_tile_NASA_numbers_it_by()
+ {
+ var key = VegetationKey.At(52.2, 21.0);
+ Assert.Equal(new VegetationKey(8, 44), key);
+ Assert.Equal(new VegetationKey(39, 0), VegetationKey.At(-90, -180));
+ Assert.Equal(new VegetationKey(0, 79), VegetationKey.At(90, 180));
+ Assert.Equal("https://gibs.earthdata.nasa.gov/wmts/epsg4326/best/VIIRS_SNPP_L3_NDVI_Monthly/default/2026-07-01/1km/6/8/44.png",
+ VegetationSource.UriOf(key, new DateOnly(2026, 7, 1)).ToString());
+ }
+
+ // ---------------------------------------------------------------- downloaded and kept
+
+ private static readonly FixedTime November = new(new DateTimeOffset(2026, 11, 13, 9, 0, 0, TimeSpan.Zero));
+
+ [Fact]
+ public void The_year_is_the_latest_twelve_months_NASA_has_finished()
+ {
+ using var source = new VegetationSource(_tree.PathOf("vegetation"), November, download: false);
+ IReadOnlyList year = source.Year();
+
+ Assert.Equal(new DateOnly(2025, 11, 1), year[0]);
+ Assert.Equal(new DateOnly(2026, 10, 1), year[^1]);
+ Assert.Equal(12, year.Distinct().Count());
+ }
+
+ [Fact]
+ public async Task A_tiles_year_is_downloaded_once_and_then_read_from_disk()
+ {
+ var server = new FakeGibs(month => Warsaw[month.Month - 1]);
+ var key = VegetationKey.At(52.2, 21.0);
+ using (var source = new VegetationSource(_tree.PathOf("vegetation"), November, handler: server))
+ {
+ VegetationTile tile = (await source.LoadAsync(key, TestContext.Current.CancellationToken))!;
+ Assert.Equal(12, tile.Months);
+ Assert.Equal(12, source.Downloaded);
+ Assert.Equal(0.58, tile.YearAt(52.2, 21.0)!.Peak, 2);
+ }
+ Assert.Equal(12, server.Requests.Count);
+ Assert.All(server.Requests, uri => Assert.Contains("/1km/6/8/44.png", uri.ToString(), StringComparison.Ordinal));
+
+ using var offline = new VegetationSource(_tree.PathOf("vegetation"), November, download: false);
+ VegetationTile again = (await offline.LoadAsync(key, TestContext.Current.CancellationToken))!;
+ Assert.Equal(0.58, again.YearAt(52.2, 21.0)!.Peak, 2);
+ }
+
+ [Fact]
+ public async Task A_month_NASA_does_not_have_is_taken_from_the_year_before()
+ {
+ var server = new FakeGibs(month => Warsaw[month.Month - 1], status: month => month == new DateOnly(2026, 10, 1) ? HttpStatusCode.NotFound : HttpStatusCode.OK);
+ using var source = new VegetationSource(_tree.PathOf("vegetation"), November, handler: server);
+
+ VegetationTile tile = (await source.LoadAsync(VegetationKey.At(52.2, 21.0), TestContext.Current.CancellationToken))!;
+
+ Assert.Equal(12, tile.Months);
+ Assert.Contains(server.Requests, uri => uri.ToString().Contains("/2025-10-01/", StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public async Task Offline_a_new_month_is_stood_in_for_by_the_same_month_a_year_before()
+ {
+ var key = VegetationKey.At(52.2, 21.0);
+ using (var lastYear = new VegetationSource(_tree.PathOf("vegetation"), new FixedTime(November.GetUtcNow().AddYears(-1)), handler: new FakeGibs(month => Warsaw[month.Month - 1])))
+ Assert.NotNull(await lastYear.LoadAsync(key, TestContext.Current.CancellationToken));
+ var offline = new FakeGibs(_ => 0.5, status: _ => HttpStatusCode.ServiceUnavailable);
+ using var source = new VegetationSource(_tree.PathOf("vegetation"), November, handler: offline);
+
+ VegetationTile tile = (await source.LoadAsync(key, TestContext.Current.CancellationToken))!;
+
+ Assert.Equal(12, tile.Months);
+ Assert.Equal(0.58, tile.YearAt(52.2, 21.0)!.Peak, 2);
+ Assert.Equal(12, offline.Requests.Count); // each new month tried once, the year before read from disk
+ }
+
+ [Fact]
+ public async Task Without_NASA_there_is_no_record_and_nothing_is_kept()
+ {
+ var server = new FakeGibs(_ => 0.5, status: _ => HttpStatusCode.ServiceUnavailable);
+ using var source = new VegetationSource(_tree.PathOf("vegetation"), November, handler: server);
+
+ Assert.Null(await source.LoadAsync(VegetationKey.At(52.2, 21.0), TestContext.Current.CancellationToken));
+ Assert.Equal(12, server.Requests.Count); // not asked again for the year before
+ Assert.False(Directory.Exists(_tree.PathOf("vegetation")) && Directory.EnumerateFiles(_tree.PathOf("vegetation"), "*.ndvi", SearchOption.AllDirectories).Any());
+ }
+
+ [Fact]
+ public void Months_older_than_the_year_before_are_removed()
+ {
+ foreach (string month in new[] { "2024-10", "2024-11", "2025-11", "2026-10", "notes" })
+ _tree.WriteText($"vegetation/{month}/8_44.ndvi", "x");
+ using var source = new VegetationSource(_tree.PathOf("vegetation"), November, download: false);
+
+ source.RemoveOldMonths();
+
+ Assert.Equal(["2024-11", "2025-11", "2026-10", "notes"],
+ Directory.EnumerateDirectories(_tree.PathOf("vegetation")).Select(Path.GetFileName).Order(StringComparer.Ordinal));
+ }
+
+ // ---------------------------------------------------------------- the textures
+
+ [Fact]
+ public void A_texture_keeps_its_first_table_while_a_record_arrives_and_the_next_one_gets_the_record()
+ {
+ var release = new TaskCompletionSource();
+ var server = new FakeGibs(month => Brittany[month.Month - 1], hold: release.Task);
+ var source = new VegetationSource(_tree.PathOf("vegetation"), November, handler: server);
+ using var observed = new ObservedSeasons(source, TimeSpan.Zero);
+ var clock = new SeasonClock(new SeasonOptions(true, 1, SeasonChoice.Satellite), null, observed);
+ clock.OfferDate(Day(1, 15), newFlight: true);
+ Assert.True(TextureName.TryParseFile("21840_35584_BI16.dds", out TextureName first));
+ Assert.True(TextureName.TryParseFile("21840_35600_BI16.dds", out TextureName second));
+ ushort[] calendar = PhotoColours.TableFor(SeasonModel.For(Day(1, 15), first.Center.Lat), Exposure.Full);
+
+ Assert.Same(calendar, clock.TableFor(first)); // the record is on its way: the calendar
+ release.SetResult();
+ Assert.True(SpinWait.SpinUntil(() => observed.TilesLoaded == 1, TimeSpan.FromSeconds(10)));
+
+ Assert.Same(calendar, clock.TableFor(first));
+ Assert.NotSame(calendar, clock.TableFor(second));
+ Assert.Contains("1 textures coloured by the satellite record, 1 by the calendar alone", clock.Summary(), StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public void A_date_arriving_after_textures_were_coloured_for_another_asks_for_them_again()
+ {
+ Assert.True(TextureName.TryParseFile("21840_35584_BI16.dds", out TextureName name));
+ string file = _tree.WriteText("sim-date.txt", Day(11, 6).ToString(CultureInfo.InvariantCulture));
+
+ var clock = new SeasonClock(new SeasonOptions(true, 1, SeasonChoice.Auto), file);
+ clock.TableFor(name); // coloured for the last flight's 6 November
+ Assert.True(clock.OfferDate(Day(1, 15), newFlight: false));
+ clock.TableFor(name);
+ Assert.False(clock.OfferDate(Day(1, 15), newFlight: true)); // the same date again
+ Assert.True(clock.OfferDate(Day(7, 1), newFlight: true)); // a new flight on another date, after its first reads
+
+ var unread = new SeasonClock(new SeasonOptions(true, 1, SeasonChoice.Auto), file);
+ Assert.False(unread.OfferDate(Day(3, 1), newFlight: false)); // nothing read yet: nothing to read again
+
+ var byHand = new SeasonClock(new SeasonOptions(true, 1, SeasonChoice.Winter), file);
+ byHand.TableFor(name);
+ Assert.False(byHand.OfferDate(Day(3, 1), newFlight: false)); // the date does not matter
+ }
+
+ [Fact]
+ public void Without_the_satellite_choice_the_record_is_not_used()
+ {
+ var source = new VegetationSource(_tree.PathOf("vegetation"), November, download: false);
+ using var observed = new ObservedSeasons(source, TimeSpan.Zero);
+ var clock = new SeasonClock(new SeasonOptions(true, 1, SeasonChoice.Auto), null, observed);
+
+ Assert.True(TextureName.TryParseFile("21840_35584_BI16.dds", out TextureName name));
+ Assert.Same(PhotoColours.TableFor(clock.StateAt(name.Center.Lat), Exposure.Full), clock.TableFor(name));
+ Assert.Null(clock.Summary());
+ }
+
+ [Fact]
+ public void X_Plane_is_asked_to_reload_its_scenery_as_its_UDP_interface_documents()
+ {
+ Assert.Equal("CMND\0sim/operation/reload_scenery"u8.ToArray(), XPlaneUdp.CommandRequest(XPlaneUdp.ReloadSceneryCommand));
+ }
+
+ [Fact]
+ public void The_settings_choose_the_satellite_record()
+ {
+ SeasonOptions options = MountSettings.ParseSeasons(TestSettings.Of("seasons = on", "season = satellite"));
+
+ Assert.Equal(SeasonChoice.Satellite, options.Choice);
+ Assert.True(options.FollowsDate);
+ Assert.False(new SeasonOptions(true, 1, SeasonChoice.Winter).FollowsDate);
+ }
+
+ private sealed class FixedTime(DateTimeOffset now) : TimeProvider
+ {
+ public override DateTimeOffset GetUtcNow() => now;
+ }
+
+ /// Stands in for NASA GIBS: each month's picture of one greenness everywhere.
+ private sealed class FakeGibs(Func ndvi, Func? status = null, Task? hold = null) : HttpMessageHandler
+ {
+ public ConcurrentQueue Requests { get; } = new();
+
+ protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
+ {
+ Uri uri = request.RequestUri!;
+ Requests.Enqueue(uri);
+ if (hold is not null) await hold.WaitAsync(cancellationToken);
+ DateOnly month = DateOnly.ParseExact(uri.Segments[^5].TrimEnd('/'), "yyyy-MM-dd", CultureInfo.InvariantCulture);
+ HttpStatusCode code = status?.Invoke(month) ?? HttpStatusCode.OK;
+ return new HttpResponseMessage(code) { Content = new ByteArrayContent(code == HttpStatusCode.OK ? NdviPictures.Uniform(ndvi(month)) : []) };
+ }
+ }
+}
diff --git a/tests/OrthoStreamXP.Tests/SceneryPackListTests.cs b/tests/OrthoStreamXP.Tests/SceneryPackListTests.cs
new file mode 100644
index 0000000..b2965ba
--- /dev/null
+++ b/tests/OrthoStreamXP.Tests/SceneryPackListTests.cs
@@ -0,0 +1,100 @@
+using OrthoStreamXP.Scenery;
+
+namespace OrthoStreamXP.Tests;
+
+public sealed class SceneryPackListTests : IDisposable
+{
+ private readonly TempTree _tree = new();
+
+ public void Dispose() => _tree.Dispose();
+
+ private string CustomScenery => _tree.PathOf("X-Plane 12/Custom Scenery");
+
+ private string FileText => File.ReadAllText(Path.Join(CustomScenery, "scenery_packs.ini"));
+
+ private void WriteFile(string text) => _tree.WriteText("X-Plane 12/Custom Scenery/scenery_packs.ini", text);
+
+ [Fact]
+ public void The_entries_are_read_in_order_with_their_state()
+ {
+ WriteFile("I\r\n1000 Version\r\nSCENERY\r\n\r\nSCENERY_PACK Custom Scenery/EDDB Berlin/\r\nSCENERY_PACK *GLOBAL_AIRPORTS*\r\nSCENERY_PACK_DISABLED Custom Scenery\\XPME_Africa\r\n");
+
+ IReadOnlyList entries = new SceneryPackList(CustomScenery).Read();
+
+ Assert.Equal(
+ [
+ new SceneryPackEntry("Custom Scenery/EDDB Berlin/", true),
+ new SceneryPackEntry("*GLOBAL_AIRPORTS*", true),
+ new SceneryPackEntry(@"Custom Scenery\XPME_Africa", false),
+ ], entries);
+ Assert.Equal(["EDDB Berlin", "*GLOBAL_AIRPORTS*", "XPME_Africa"], entries.Select(e => e.Name));
+ }
+
+ [Fact]
+ public void No_file_lists_nothing()
+ {
+ Directory.CreateDirectory(CustomScenery);
+ Assert.Empty(new SceneryPackList(CustomScenery).Read());
+ Assert.False(new SceneryPackList(CustomScenery).SetEnabled("Custom Scenery/KSEA/", false));
+ }
+
+ [Fact]
+ public void An_entry_is_switched_in_place_and_the_rest_of_the_file_stays()
+ {
+ WriteFile("I\r\n1000 Version\r\nSCENERY\r\n\r\nSCENERY_PACK Custom Scenery/KSEA/\r\nSCENERY_PACK Custom Scenery/EDDB Berlin/\r\nSCENERY_PACK *GLOBAL_AIRPORTS*\r\n");
+ var list = new SceneryPackList(CustomScenery);
+
+ Assert.True(list.SetEnabled("Custom Scenery/EDDB Berlin/", false));
+ Assert.Equal("I\r\n1000 Version\r\nSCENERY\r\n\r\nSCENERY_PACK Custom Scenery/KSEA/\r\nSCENERY_PACK_DISABLED Custom Scenery/EDDB Berlin/\r\nSCENERY_PACK *GLOBAL_AIRPORTS*\r\n", FileText);
+ Assert.False(list.SetEnabled("Custom Scenery/EDDB Berlin/", false), "already off: left alone");
+
+ Assert.True(list.SetEnabled("Custom Scenery/EDDB Berlin/", true));
+ Assert.Equal("I\r\n1000 Version\r\nSCENERY\r\n\r\nSCENERY_PACK Custom Scenery/KSEA/\r\nSCENERY_PACK Custom Scenery/EDDB Berlin/\r\nSCENERY_PACK *GLOBAL_AIRPORTS*\r\n", FileText);
+ }
+
+ [Fact]
+ public void An_entry_is_found_whichever_slashes_it_is_written_with_and_LF_endings_stay()
+ {
+ WriteFile("I\n1000 Version\nSCENERY\n\nSCENERY_PACK_DISABLED Custom Scenery\\XPME_Africa\n");
+
+ Assert.True(new SceneryPackList(CustomScenery).SetEnabled("custom scenery/XPME_Africa/", true));
+ Assert.Equal("I\n1000 Version\nSCENERY\n\nSCENERY_PACK Custom Scenery\\XPME_Africa\n", FileText);
+ }
+
+ [Fact]
+ public void A_path_not_listed_changes_nothing()
+ {
+ WriteFile("I\r\n1000 Version\r\nSCENERY\r\n\r\nSCENERY_PACK Custom Scenery/KSEA/\r\n");
+ Assert.False(new SceneryPackList(CustomScenery).SetEnabled("Custom Scenery/KSEAT/", false));
+ Assert.Equal("I\r\n1000 Version\r\nSCENERY\r\n\r\nSCENERY_PACK Custom Scenery/KSEA/\r\n", FileText);
+ }
+
+ [Fact]
+ public void An_entry_moves_to_any_place_the_ones_between_shift_and_the_other_lines_stay()
+ {
+ WriteFile("I\r\n1000 Version\r\nSCENERY\r\n\r\nSCENERY_PACK Custom Scenery/KSEA/\r\n\r\nSCENERY_PACK Custom Scenery/EGLL/\r\nSCENERY_PACK_DISABLED Custom Scenery\\EDDB/\r\nSCENERY_PACK *GLOBAL_AIRPORTS*\r\n");
+ var list = new SceneryPackList(CustomScenery);
+
+ Assert.True(list.MoveTo("Custom Scenery/EDDB", 0));
+ Assert.Equal("I\r\n1000 Version\r\nSCENERY\r\n\r\nSCENERY_PACK_DISABLED Custom Scenery\\EDDB/\r\n\r\nSCENERY_PACK Custom Scenery/KSEA/\r\nSCENERY_PACK Custom Scenery/EGLL/\r\nSCENERY_PACK *GLOBAL_AIRPORTS*\r\n", FileText);
+
+ Assert.True(list.MoveTo("Custom Scenery/EDDB/", 3));
+ Assert.Equal(["Custom Scenery/KSEA/", "Custom Scenery/EGLL/", "*GLOBAL_AIRPORTS*", @"Custom Scenery\EDDB/"], list.Read().Select(e => e.Path));
+
+ Assert.True(list.MoveTo("Custom Scenery/KSEA/", 1));
+ Assert.Equal(["Custom Scenery/EGLL/", "Custom Scenery/KSEA/", "*GLOBAL_AIRPORTS*", @"Custom Scenery\EDDB/"], list.Read().Select(e => e.Path));
+ }
+
+ [Theory]
+ [InlineData("Custom Scenery/KSEA/", 0)]
+ [InlineData("Custom Scenery/KSEA/", 2)]
+ [InlineData("Custom Scenery/KSEA/", -1)]
+ [InlineData("Custom Scenery/Missing/", 0)]
+ public void A_move_to_its_own_place_outside_the_list_or_of_a_missing_entry_changes_nothing(string path, int to)
+ {
+ const string Text = "I\n1000 Version\nSCENERY\n\nSCENERY_PACK Custom Scenery/KSEA/\nSCENERY_PACK *GLOBAL_AIRPORTS*\n";
+ WriteFile(Text);
+ Assert.False(new SceneryPackList(CustomScenery).MoveTo(path, to));
+ Assert.Equal(Text, FileText);
+ }
+}
diff --git a/tests/OrthoStreamXP.Tests/SceneryPacksTests.cs b/tests/OrthoStreamXP.Tests/SceneryPacksTests.cs
index ef3c766..421d682 100644
--- a/tests/OrthoStreamXP.Tests/SceneryPacksTests.cs
+++ b/tests/OrthoStreamXP.Tests/SceneryPacksTests.cs
@@ -48,6 +48,39 @@ SCENERY_PACK Custom Scenery/XPME_Asia/
Assert.False(SceneryPacks.MoveToEnd(CustomScenery, ["XPME_Africa", "XPME_Europe", "XPME_Asia"]), "already in place: left alone");
}
+ [Fact]
+ public void The_packages_added_at_the_start_are_reported_and_removed_again_and_the_listed_ones_stay()
+ {
+ _tree.WriteText("X-Plane 12/Custom Scenery/scenery_packs.ini",
+ "I\r\n1000 Version\r\nSCENERY\r\n\r\nSCENERY_PACK Custom Scenery/KSEA/\r\nSCENERY_PACK_DISABLED Custom Scenery/XPME_Africa/\r\n");
+ string file = Path.Join(CustomScenery, "scenery_packs.ini");
+ string before = File.ReadAllText(file);
+
+ Assert.True(SceneryPacks.MoveToEnd(CustomScenery, ["XPME_Africa", "XPME_Europe"], out IReadOnlyList added));
+ Assert.Equal(["XPME_Europe"], added);
+
+ Assert.True(SceneryPacks.RemoveEntries(CustomScenery, added));
+ Assert.Equal(before, File.ReadAllText(file));
+ Assert.Equal(before, File.ReadAllText(file + ".bak"));
+ Assert.False(SceneryPacks.RemoveEntries(CustomScenery, added), "already gone: left alone");
+ }
+
+ [Fact]
+ public void Nothing_is_added_when_every_package_is_listed()
+ {
+ _tree.WriteText("X-Plane 12/Custom Scenery/scenery_packs.ini", "I\n1000 Version\nSCENERY\nSCENERY_PACK Custom Scenery/XPME_Europe/\n");
+ Assert.False(SceneryPacks.MoveToEnd(CustomScenery, ["XPME_Europe"], out IReadOnlyList added));
+ Assert.Empty(added);
+ }
+
+ [Fact]
+ public void Removing_from_a_missing_file_changes_nothing()
+ {
+ Directory.CreateDirectory(CustomScenery);
+ Assert.False(SceneryPacks.RemoveEntries(CustomScenery, ["XPME_Europe"]));
+ Assert.False(File.Exists(Path.Join(CustomScenery, "scenery_packs.ini")));
+ }
+
[Fact]
public void An_entry_with_the_full_path_is_recognised()
{
@@ -122,6 +155,62 @@ public void Every_package_in_the_base_folder_is_planned_with_its_own_cache_and_m
], plan);
}
+ [Fact]
+ public void A_switched_off_package_is_not_mounted()
+ {
+ Directory.CreateDirectory(CustomScenery);
+ Package("BP/XPME_Europe");
+ Package("BP/XPME_Africa");
+ Package("BP/XPME_Asia");
+ SettingValues args = TestSettings.Of($"base-packages = {_tree.PathOf("BP")}", $"xplane = {_tree.PathOf("X-Plane 12")}", "cache = unused",
+ "skip-packages = xpme_africa, XPME_Asia ,");
+
+ var plan = MountSettings.PlanPackages(args, _tree.PathOf("cache"), out _, out _);
+
+ Assert.Equal(["XPME_Europe"], plan.Select(p => p.Name));
+ }
+
+ [Fact]
+ public void Every_package_switched_off_is_explained()
+ {
+ Directory.CreateDirectory(CustomScenery);
+ Package("BP/XPME_Europe");
+ SettingValues args = TestSettings.Of($"base-packages = {_tree.PathOf("BP")}", $"xplane = {_tree.PathOf("X-Plane 12")}", "cache = unused",
+ "skip-packages = XPME_Europe");
+
+ var error = Assert.Throws(() => MountSettings.PlanPackages(args, _tree.PathOf("cache"), out _, out _));
+ Assert.Contains("is switched off", error.Message, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public void Overlays_alone_are_not_enough_one_region_must_stay_on()
+ {
+ Directory.CreateDirectory(CustomScenery);
+ Package("BP/XPME_Europe");
+ Package("BP/XPME_Overlays");
+ Package("BP/OrthoStream_Overlays");
+ SettingValues OnlyOverlays() => TestSettings.Of($"base-packages = {_tree.PathOf("BP")}", $"xplane = {_tree.PathOf("X-Plane 12")}", "cache = unused",
+ "skip-packages = XPME_Europe");
+ SettingValues RegionAndOverlays() => TestSettings.Of($"base-packages = {_tree.PathOf("BP")}", $"xplane = {_tree.PathOf("X-Plane 12")}", "cache = unused",
+ "skip-packages = OrthoStream_Overlays");
+
+ var error = Assert.Throws(() => MountSettings.PlanPackages(OnlyOverlays(), _tree.PathOf("cache"), out _, out _));
+ Assert.Contains("switch on at least one region", error.Message, StringComparison.Ordinal);
+ Assert.Contains("OrthoStream_Overlays, XPME_Overlays", error.Message, StringComparison.Ordinal);
+
+ Assert.Equal(["XPME_Europe", "XPME_Overlays"], MountSettings.PlanPackages(RegionAndOverlays(), _tree.PathOf("cache"), out _, out _).Select(p => p.Name));
+ }
+
+ [Fact]
+ public void Switching_packages_off_and_on_writes_the_setting_and_removes_it_when_none_is_left_out()
+ {
+ SkippedPackages skipped = SkippedPackages.Parse(null).With("XPME_Europe", skipped: true).With("XPME_Africa", skipped: true);
+ Assert.Equal("XPME_Africa, XPME_Europe", skipped.ToValue());
+ Assert.True(SkippedPackages.Parse(skipped.ToValue()).Contains("xpme_europe"));
+ Assert.Equal("XPME_Africa", skipped.With("xpme_europe", skipped: false).ToValue());
+ Assert.Null(skipped.With("XPME_Europe", skipped: false).With("XPME_Africa", skipped: false).ToValue());
+ }
+
[Fact]
public void One_source_with_the_xplane_folder_mounts_under_its_own_name_and_keeps_the_cache()
{
diff --git a/tests/OrthoStreamXP.Tests/SeasonsTests.cs b/tests/OrthoStreamXP.Tests/SeasonsTests.cs
index bb0987c..5d1929c 100644
--- a/tests/OrthoStreamXP.Tests/SeasonsTests.cs
+++ b/tests/OrthoStreamXP.Tests/SeasonsTests.cs
@@ -54,6 +54,19 @@ public void The_tropics_keep_their_colours_and_the_year_changes_gradually()
private static readonly SeasonState Winter = SeasonModel.For(SeasonChoice.Winter), Autumn = SeasonModel.For(SeasonChoice.Autumn);
+ /// A season's colours alone as a lookup table (the photos' table adds the contrast and the exposure).
+ private static ushort[] SeasonTable(SeasonState season)
+ {
+ var table = new ushort[65536];
+ for (int c = 0; c < table.Length; c++)
+ {
+ var (r, g, b) = ColourTable.Decode565(c);
+ var (r2, g2, b2) = Seasons.Recolor(r, g, b, season);
+ table[c] = (ushort)ColourTable.Encode565(r2, g2, b2);
+ }
+ return table;
+ }
+
private static double Hue((double R, double G, double B) c)
{
double max = Math.Max(c.R, Math.Max(c.G, c.B)), min = Math.Min(c.R, Math.Min(c.G, c.B)), d = max - min;
@@ -117,7 +130,7 @@ public void A_block_is_recoloured_as_its_colour_is_and_stays_an_opaque_block()
byte[] dds = Texture();
byte[] before = Dds.DecodeLevel(dds.AsSpan(Dds.HeaderSize), 16, 16);
- ColourTable.Apply(dds, 0, 8, Seasons.TableFor(Winter)!);
+ ColourTable.Apply(dds, 0, 8, SeasonTable(Winter));
byte[] after = Dds.DecodeLevel(dds.AsSpan(Dds.HeaderSize), 16, 16);
for (int block = Dds.HeaderSize; block < dds.Length; block += 8)
@@ -138,7 +151,7 @@ public void A_block_is_recoloured_as_its_colour_is_and_stays_an_opaque_block()
public void A_block_cut_by_the_end_of_a_read_stays_as_it_is_so_split_reads_always_match()
{
byte[] whole = Texture(), split = (byte[])whole.Clone(), original = (byte[])whole.Clone();
- ushort[] table = Seasons.TableFor(Winter)!;
+ ushort[] table = SeasonTable(Winter);
ColourTable.Apply(whole, 0, 8, table);
// Two reads that cut the second block in half: it stays as made, both halves.
@@ -171,13 +184,15 @@ public void X_Planes_date_is_taken_when_a_flight_starts_and_kept_for_the_next_ru
}
[Fact]
- public void A_texture_takes_the_table_of_its_season_and_none_in_summer()
+ public void A_texture_takes_the_table_of_its_season_and_summers_in_summer()
{
Assert.True(TextureName.TryParseFile("21840_35584_BI16.dds", out TextureName name));
+ ushort[] summer = PhotoColours.TableFor(SeasonState.Summer, Exposure.Full);
- Assert.Same(Seasons.TableFor(Winter), new SeasonClock(new SeasonOptions(true, 1, SeasonChoice.Winter), null).TableFor(name));
- Assert.Null(new SeasonClock(new SeasonOptions(true, 1, SeasonChoice.Summer), null).TableFor(name));
- Assert.Null(new SeasonClock(new SeasonOptions(true, 0, SeasonChoice.Winter), null).TableFor(name));
+ Assert.Same(PhotoColours.TableFor(Winter, Exposure.Full), new SeasonClock(new SeasonOptions(true, 1, SeasonChoice.Winter), null).TableFor(name));
+ Assert.NotSame(summer, new SeasonClock(new SeasonOptions(true, 1, SeasonChoice.Winter), null).TableFor(name));
+ Assert.Same(summer, new SeasonClock(new SeasonOptions(true, 1, SeasonChoice.Summer), null).TableFor(name));
+ Assert.Same(summer, new SeasonClock(new SeasonOptions(true, 0, SeasonChoice.Winter), null).TableFor(name));
}
[Fact]
diff --git a/tests/OrthoStreamXP.Tests/SharpeningTests.cs b/tests/OrthoStreamXP.Tests/SharpeningTests.cs
new file mode 100644
index 0000000..1c209c1
--- /dev/null
+++ b/tests/OrthoStreamXP.Tests/SharpeningTests.cs
@@ -0,0 +1,116 @@
+using OrthoStreamXP.Textures;
+
+namespace OrthoStreamXP.Tests;
+
+/// The sharpening of the photos as a texture is built: an unsharp mask on the brightness, in place.
+public sealed class SharpeningTests
+{
+ [Fact]
+ public void A_flat_picture_stays_as_it_is()
+ {
+ byte[] rgb = Flat(32, 24, 90, 120, 60);
+ byte[] before = (byte[])rgb.Clone();
+
+ Sharpening.Apply(rgb, 32, 24, 1, Sharpening.AirportStrength);
+
+ Assert.Equal(before, rgb);
+ }
+
+ [Fact]
+ public void An_edge_gets_steeper_on_both_sides()
+ {
+ // Dark on the left, light on the right.
+ const int width = 32, height = 8;
+ byte[] rgb = new byte[width * height * 3];
+ for (int y = 0; y < height; y++)
+ for (int x = 0; x < width; x++)
+ rgb.AsSpan((y * width + x) * 3, 3).Fill(x < width / 2 ? (byte)80 : (byte)160);
+
+ Sharpening.Apply(rgb, width, height, 1, Sharpening.AirportStrength);
+
+ int row = 4 * width * 3;
+ Assert.True(rgb[row + (width / 2 - 1) * 3] < 80, $"the dark side of the edge: {rgb[row + (width / 2 - 1) * 3]}");
+ Assert.True(rgb[row + width / 2 * 3] > 160, $"the light side of the edge: {rgb[row + width / 2 * 3]}");
+ Assert.Equal(80, rgb[row]); // far from the edge, as it was
+ Assert.Equal(160, rgb[row + (width - 1) * 3]);
+ }
+
+ [Fact]
+ public void Grey_stays_grey_so_edges_get_no_colour_fringes()
+ {
+ const int size = 48;
+ byte[] rgb = Images.SyntheticTile(5, 6, 14) is var tile ? Images.Resize(tile, 256, 256, size, size, 1) : [];
+ for (int i = 0; i < rgb.Length; i += 3) rgb[i + 1] = rgb[i + 2] = rgb[i];
+
+ Sharpening.Apply(rgb, size, size, 1, Sharpening.AirportStrength);
+
+ for (int i = 0; i < rgb.Length; i += 3)
+ Assert.True(rgb[i] == rgb[i + 1] && rgb[i] == rgb[i + 2], $"pixel {i / 3}: {rgb[i]}, {rgb[i + 1]}, {rgb[i + 2]}");
+ }
+
+ [Fact]
+ public void The_number_of_workers_changes_nothing()
+ {
+ const int size = 300; // several bands, the last one short
+ byte[] one = Images.Resize(Images.SyntheticTile(1, 2, 14), 256, 256, size, size, 1), many = (byte[])one.Clone();
+
+ Sharpening.Apply(one, size, size, 1, Sharpening.AirportStrength);
+ Sharpening.Apply(many, size, size, 8, Sharpening.AirportStrength);
+
+ Assert.Equal(one, many);
+ }
+
+ [Theory]
+ [InlineData(1, 1)]
+ [InlineData(2, 5)]
+ [InlineData(7, 3)]
+ public void Pictures_smaller_than_the_blur_repeat_their_edges(int width, int height)
+ {
+ byte[] rgb = Flat(width, height, 10, 200, 30);
+ rgb[0] = 250;
+ byte[] before = (byte[])rgb.Clone();
+
+ Sharpening.Apply(rgb, width, height, 4, Sharpening.AirportStrength);
+
+ if (width * height == 1) Assert.Equal(before, rgb); // nothing round it to stand out from
+ else Assert.True(rgb[0] > 250 && rgb[1] > 200, $"the brighter pixel only brighter: {rgb[0]}, {rgb[1]}");
+ }
+
+ [Fact]
+ public void A_picture_shorter_than_its_size_is_refused()
+ {
+ Assert.Throws(() => Sharpening.Apply(new byte[10], 4, 4, 1, Sharpening.AirportStrength));
+ }
+
+ [Theory]
+ [InlineData(15, 1.0)]
+ [InlineData(16, 1.0)] // the wide areas: full strength
+ [InlineData(17, 1.0)]
+ [InlineData(18, 0.6)] // the airports: finer imagery, less
+ [InlineData(19, 0.6)]
+ public void Areas_are_sharpened_at_full_strength_airports_at_60_percent(int fileZoom, double strength) =>
+ Assert.Equal(strength, Sharpening.StrengthFor(fileZoom));
+
+ [Fact]
+ public void Full_strength_steepens_an_edge_more_and_zero_leaves_it()
+ {
+ const int width = 32, height = 8, dark = (width / 2 - 1) * 3;
+ byte[] Edge() => [.. Enumerable.Range(0, width * height).SelectMany(i => Enumerable.Repeat(i % width < width / 2 ? (byte)80 : (byte)160, 3))];
+ byte[] airport = Edge(), area = Edge(), none = Edge();
+
+ Sharpening.Apply(airport, width, height, 1, Sharpening.AirportStrength);
+ Sharpening.Apply(area, width, height, 1, Sharpening.AreaStrength);
+ Sharpening.Apply(none, width, height, 1, 0);
+
+ Assert.True(area[dark] < airport[dark] && airport[dark] < 80, $"the dark side: area {area[dark]}, airport {airport[dark]}");
+ Assert.Equal(Edge(), none);
+ Assert.Throws(() => Sharpening.Apply(Edge(), width, height, 1, 1.5));
+ }
+
+ private static byte[] Flat(int width, int height, byte r, byte g, byte b)
+ {
+ byte[] rgb = new byte[width * height * 3];
+ for (int i = 0; i < rgb.Length; i += 3) (rgb[i], rgb[i + 1], rgb[i + 2]) = (r, g, b);
+ return rgb;
+ }
+}
diff --git a/tests/OrthoStreamXP.Tests/StreamingTests.cs b/tests/OrthoStreamXP.Tests/StreamingTests.cs
index 8541e50..68490cc 100644
--- a/tests/OrthoStreamXP.Tests/StreamingTests.cs
+++ b/tests/OrthoStreamXP.Tests/StreamingTests.cs
@@ -28,13 +28,17 @@ private sealed record Setup(FakeTileServer Server, TileSource Tiles, SceneryRoot
ViewTracker View, TextureStreamer Streamer);
/// -3: ZL16 textures are 1024 px from zoom 14, their base level 2 (zoom 12). -2: 2048 px from zoom 15, base level 3.
+ ///
+ /// The engine takes its base zoom from the store; these tests keep a zoom 12 base (not the program's 13), so the small
+ /// 1024 px textures still have a near, a middle and a far band apart. The zoom 13 base has tests of its own below.
+ ///
private Setup Streaming(int level = -3, double maxWait = 0.2, Func? delay = null, Setup? sharing = null, int detailedBuilds = 16,
long buildTiles = TextureStreamer.DefaultBuildTiles, Func? hold = null, Daylight? nightPause = null, ReadLog? readLog = null,
- AltitudeDetail? altitude = null)
+ AltitudeDetail? altitude = null, TextureResolution? resolution = null)
{
FakeTileServer server = sharing?.Server ?? new FakeTileServer(delay: delay, hold: hold);
- TileSource tiles = sharing?.Tiles ?? Track(new TileSource("test", FakeTileServer.Template, 32, handler: server) { Store = new TileStore(_tree.PathOf("base")) });
- var plan = new TexturePlan(level, TextureSizing.MaxSize);
+ TileSource tiles = sharing?.Tiles ?? Track(new TileSource("test", FakeTileServer.Template, 32, handler: server) { Store = new TileStore(_tree.PathOf("base"), maxZoom: 12) });
+ var plan = new TexturePlan(level, TextureSizing.MaxSize) { Resolution = resolution ?? TextureResolution.Full };
var roots = new SceneryRoots(_tree.PathOf("source"), _tree.PathOf("cache"), null, plan);
Directory.CreateDirectory(roots.Source);
var builder = new TextureBuilder(tiles, 2);
@@ -127,7 +131,7 @@ public void The_layout_matches_a_whole_encoded_dds_level_by_level()
Assert.Equal(dds.Length, layout.Length);
Assert.Equal(dds[..Dds.HeaderSize], layout.Header.ToArray());
Assert.Equal(dds[Dds.HeaderSize..], Dds.EncodeChain(rgb, layout, 0, workers: 1));
- Assert.Equal(dds[(int)layout.Offset(3)..], Dds.EncodeChain(Images.BoxHalf(Images.BoxHalf(Images.BoxHalf(rgb, 64, 64, 1), 32, 32, 1), 16, 16, 1), layout, 3, 1));
+ Assert.Equal(dds[(int)layout.Offset(3)..], Dds.EncodeChain(MipFilter.Half(MipFilter.Half(MipFilter.Half(rgb, 64, 64, 1), 32, 32, 1), 16, 16, 1), layout, 3, 1));
Assert.Equal(0, layout.MipAt(Dds.HeaderSize));
Assert.Equal(0, layout.MipAt(layout.Offset(1) - 1));
Assert.Equal(1, layout.MipAt(layout.Offset(1)));
@@ -204,23 +208,41 @@ public void Every_read_gets_the_header_and_its_full_length()
[Fact]
public void Each_level_is_fetched_at_the_zoom_it_needs()
{
- var plan = new TexturePlan(0, TextureSizing.MaxSize); // Ultra: ZL16 textures 4096 px from zoom 17
+ var plan = new TexturePlan(0, TextureSizing.MaxSize); // Ultra: ZL16 textures 8192 px from zoom 17
var zl16 = new StreamedTexture(Texture(), TextureName.TryParseFile(Stem + ".dds", out var name) ? name : default, plan, 12);
- Assert.Equal(4096, zl16.Layout.Size);
- Assert.Equal([17, 15, 14, 13, 12], Enumerable.Range(0, 5).Select(zl16.ZoomFor));
- Assert.Equal(4, zl16.BaseMip); // level 4 of a ZL16 texture is one ZL12 tile
+ Assert.Equal(8192, zl16.Layout.Size);
+ Assert.Equal([17, 16, 15, 14, 13, 12], Enumerable.Range(0, 6).Select(zl16.ZoomFor));
+ Assert.Equal(5, zl16.BaseMip); // level 5 of an 8192 px ZL16 texture is one ZL12 tile
var coarse = new StreamedTexture(Texture(), name, new TexturePlan(-2, TextureSizing.MaxSize), 12);
Assert.Equal((2048, 15, 3), (coarse.Layout.Size, coarse.ZoomFor(0), coarse.BaseMip));
}
+ [Fact]
+ public void The_programs_zoom_13_base_is_one_level_sharper()
+ {
+ TextureName name = TextureName.TryParseFile(Stem + ".dds", out var parsed) ? parsed : default;
+ // Extra and Ultra: 8192 px from zoom 17, the base level 4 (four ZL13 tiles, 512 px) instead of 5.
+ var extra = new StreamedTexture(Texture(), name, new TexturePlan(1), TileStore.DefaultMaxZoom);
+ Assert.Equal((8192, 13, 4), (extra.Layout.Size, extra.ZoomFor(4), extra.BaseMip));
+ // Balanced: 2048 px from zoom 15, the base level 2 (512 px), past the near band: a far read, answered at once.
+ var balanced = new StreamedTexture(Texture(), name, new TexturePlan(-2), TileStore.DefaultMaxZoom);
+ Assert.Equal((2048, 13, 2), (balanced.Layout.Size, balanced.ZoomFor(2), balanced.BaseMip));
+ Assert.Equal(Band.Far, TextureStreamer.BandOf(balanced, balanced.BaseMip));
+ }
+
// ---------------------------------------------------------------- reads
+ /// A position far from while flying: the start is over, and its reads are far.
+ private static void Flying(Setup s, StreamedTexture t) =>
+ s.View.Update(new CameraReport(t.Lat - 3, t.Lon, 300, null, new Motion(60, 0), false, DateTime.UtcNow));
+
[Fact]
- public async Task A_far_read_is_answered_at_once_and_its_one_base_tile_is_fetched_behind_it()
+ public async Task In_flight_a_far_read_is_answered_at_once_and_its_one_base_tile_is_fetched_behind_it()
{
Setup s = Streaming();
StreamedTexture t = s.Streamer.Get(Texture())!;
+ Flying(s, t);
var (first, answer) = ReadLevel(s.Streamer, t, t.BaseMip);
Assert.Equal((Band.Far, Served.Flat), (answer.Band, answer.Served)); // nothing of the place at hand yet
@@ -235,6 +257,39 @@ public async Task A_far_read_is_answered_at_once_and_its_one_base_tile_is_fetche
Assert.True(s.Tiles.Store!.Contains(35824 >> 4, 21904 >> 4, 12));
}
+ [Fact]
+ public void At_a_start_a_far_read_with_nothing_at_hand_waits_for_its_base_tile_instead_of_a_flat_colour()
+ {
+ // The first start with a new cache, 17 Nov: X-Plane loaded the whole area before the base tiles were in,
+ // 1007 far reads got one flat colour, and it read only a third of those textures again.
+ Setup s = Streaming(delay: z => z == 12 ? TimeSpan.FromSeconds(1.5) : TimeSpan.Zero);
+ StreamedTexture t = s.Streamer.Get(Texture())!;
+ Assert.True(s.View.Starting); // no position yet
+
+ var (bytes, answer) = ReadLevel(s.Streamer, t, t.BaseMip);
+
+ Assert.Equal((Band.Far, Served.Real), (answer.Band, answer.Served));
+ Assert.True(answer.WaitMs > 1000, $"waited {answer.WaitMs} ms for the 1.5 s base tile");
+ AssertColor(TileColor, bytes, t.Layout.SizeOf(t.BaseMip));
+ StreamingFacts facts = s.Streamer.Facts();
+ Assert.Equal((0L, 0L), (facts.StartWaits, facts.FlightWaits)); // not the tuning's near and middle waits
+ }
+
+ [Fact]
+ public void At_a_start_a_far_read_with_a_coarser_tile_at_hand_gets_a_stand_in_at_once()
+ {
+ Setup s = Streaming(delay: z => z == 12 ? TimeSpan.FromSeconds(1.5) : TimeSpan.Zero);
+ StreamedTexture t = s.Streamer.Get(Texture())!;
+ s.Tiles.Store!.Save(35824 >> 5, 21904 >> 5, 11, FakeTileServer.Tile); // the zoom 11 tile around it, from an earlier flight
+ Assert.True(s.View.Starting);
+
+ var (bytes, answer) = ReadLevel(s.Streamer, t, t.BaseMip);
+
+ Assert.Equal((Band.Far, Served.StandIn), (answer.Band, answer.Served)); // the right picture, only blurrier
+ Assert.Equal(0, answer.WaitMs);
+ AssertColor(TileColor, bytes, t.Layout.SizeOf(t.BaseMip));
+ }
+
[Fact]
public void A_near_read_waits_for_full_detail_and_the_whole_texture_is_cached()
{
@@ -251,6 +306,24 @@ public void A_near_read_waits_for_full_detail_and_the_whole_texture_is_cached()
Assert.Equal(bytes, File.ReadAllBytes(cached).AsSpan((int)t.Layout.Offset(0), bytes.Length).ToArray());
}
+ [Fact]
+ public void At_medium_resolution_a_halved_texture_streams_from_the_same_tiles()
+ {
+ Setup s = Streaming(resolution: TextureResolution.Medium);
+ StreamedTexture t = s.Streamer.Get(Texture())!;
+ Assert.Equal(512, t.Layout.Size); // 1024 px at full resolution, halved in the ZL16 areas
+ Assert.Equal([14, 12], Enumerable.Range(0, 2).Select(t.ZoomFor)); // level 1 (256 px) is one zoom 12 tile
+
+ var (bytes, answer) = ReadLevel(s.Streamer, t, 0);
+ Assert.Equal((Band.Near, Served.Real), (answer.Band, answer.Served));
+ AssertColor(TileColor, bytes, 512);
+ Assert.All(Zooms(s.Server), z => Assert.Equal(14, z)); // the same 4 x 4 tiles at zoom 14 as Full's
+
+ byte[] cached = File.ReadAllBytes(s.Roots.CachedFile(Texture())!);
+ Assert.Equal(t.Layout.Length, cached.Length);
+ Assert.Equal<(int, int)?>((512, 512), Dds.ReadDimensions(s.Roots.CachedFile(Texture())!));
+ }
+
[Fact]
public void A_read_of_level_1_downloads_only_level_1s_zoom_and_keeps_the_chain()
{
@@ -329,6 +402,7 @@ public async Task A_level_read_in_pieces_stays_one_version_when_better_data_arri
int mip = t.BaseMip, half = t.Layout.LengthOf(mip) / 2;
var cursor = new ReadCursor();
byte[] firstHalf = new byte[half], secondHalf = new byte[half];
+ Flying(s, t); // at a start the first half would wait for the base tile
s.Streamer.Read(t, cursor, t.Layout.Offset(mip), firstHalf); // flat: nothing at hand
await Until(() => s.Streamer.RealFrom(t) <= mip);
@@ -677,8 +751,10 @@ public void When_the_sun_rises_the_next_read_gets_the_photo_again()
// ---------------------------------------------------------------- load-ahead
[Fact]
- public async Task Before_a_position_arrives_load_ahead_fetches_one_base_tile_per_texture()
+ public async Task Before_a_position_arrives_load_ahead_fetches_the_level_XPlane_reads_at_load()
{
+ // These 1024 px textures have their base at zoom 12 (256 px): the 512 px level X-Plane reads when it loads them
+ // is level 1, four zoom 13 tiles, as a ZL18 texture's is in a real package.
Setup s = Streaming();
var catalog = new TextureCatalog();
using var warmer = new MipWarmer(catalog, s.Streamer, s.View, heavy: 2);
@@ -686,12 +762,12 @@ public async Task Before_a_position_arrives_load_ahead_fetches_one_base_tile_per
catalog.AddTerrain(VirtualPath.Of("terrain", "21904_35840_BI16.ter"));
warmer.StartWhatFits();
- await Until(() => catalog.Entries.All(e => s.Streamer.RealFrom(s.Streamer.Get(e.Texture)!) <= 2));
- Assert.Equal([12, 12], Zooms(s.Server));
+ await Until(() => catalog.Entries.All(e => s.Streamer.RealFrom(s.Streamer.Get(e.Texture)!) <= 1));
+ Assert.Equal(Enumerable.Repeat(13, 8), Zooms(s.Server));
}
[Fact]
- public async Task With_the_camera_beside_a_texture_load_ahead_fetches_it_in_full_and_the_far_one_as_a_base_tile()
+ public async Task With_the_camera_beside_a_texture_load_ahead_fetches_it_in_full_and_the_far_one_at_the_level_XPlane_reads_at_load()
{
Setup s = Streaming();
var catalog = new TextureCatalog();
@@ -702,9 +778,60 @@ public async Task With_the_camera_beside_a_texture_load_ahead_fetches_it_in_full
catalog.AddTerrain(VirtualPath.Of("terrain", "21904_36144_BI16.ter"));
warmer.StartWhatFits();
- await Until(() => s.Streamer.RealFrom(near) == 0 && s.Streamer.RealFrom(far) <= far.BaseMip);
+ await Until(() => s.Streamer.RealFrom(near) == 0 && s.Streamer.RealFrom(far) <= MipWarmer.LoadMip(far));
Assert.Equal(16, Zooms(s.Server).Count(z => z == 14));
- Assert.Equal(1, Zooms(s.Server).Count(z => z == 12));
+ Assert.Equal(4, Zooms(s.Server).Count(z => z == 13));
+ Assert.DoesNotContain(12, Zooms(s.Server));
+ }
+
+ [Fact]
+ public void The_level_XPlane_reads_at_load_is_the_512_px_one_at_most_the_base()
+ {
+ // Extra (level +1): 8192 px textures, ZL16 from zoom 17, ZL18 from zoom 19, the low-zoom base at zoom 13.
+ var extra = new TexturePlan(1, TextureSizing.MaxSize);
+ var zl16 = new StreamedTexture(Texture(), new TextureName(21904, 35824, "BI", 16), extra, baseZoom: 13);
+ var zl18 = new StreamedTexture(Texture("89376_140560_BI18"), new TextureName(89376, 140560, "BI", 18), extra, baseZoom: 13);
+
+ // ZL16: the 512 px level is the base (four zoom 13 tiles); ZL18: four zoom 15 tiles, above its base level 6.
+ Assert.Equal((4, 4, 512), (MipWarmer.LoadMip(zl16), zl16.BaseMip, zl16.Layout.SizeOf(4)));
+ Assert.Equal((4, 6, 15), (MipWarmer.LoadMip(zl18), zl18.BaseMip, zl18.ZoomFor(4)));
+ // A texture no larger than 512 px is read whole.
+ Assert.Equal(0, MipWarmer.LoadMip(new StreamedTexture(Texture(), new TextureName(21904, 35824, "BI", 16), new TexturePlan(1, Limit: 512), baseZoom: 13)));
+ }
+
+ [Fact]
+ public async Task A_tile_ahead_has_its_textures_fetched_at_the_level_XPlane_reads_at_load_before_it_loads_them()
+ {
+ Setup s = Streaming();
+ using var warmer = new MipWarmer(new TextureCatalog(), s.Streamer, s.View, heavy: 2);
+ var tile = new SceneryTile(47, 11);
+ string dsf = Path.Join(s.Roots.Source, tile.DsfPath);
+ Directory.CreateDirectory(Path.GetDirectoryName(dsf)!);
+ File.WriteAllBytes(dsf, UpcomingSceneryTests.Dsf("terrain_Water", "terrain/21904_35824_BI16.ter", "terrain/21904_35840_BI16.ter",
+ "terrain/21904_35840_BI16_water_overlay.ter"));
+ using var upcoming = new UpcomingScenery(s.Roots.Source, s.View, new SceneryLoads(s.View), warmer);
+
+ Assert.Equal(2, upcoming.Ready(tile)); // the overlay's texture is one of the two
+ Assert.Equal(0, upcoming.Ready(tile)); // once
+ Assert.Equal(0, upcoming.Ready(new SceneryTile(48, 11))); // not in the package
+
+ warmer.StartWhatFits();
+ StreamedTexture[] textures = [s.Streamer.Get(Texture())!, s.Streamer.Get(Texture("21904_35840_BI16"))!];
+ await Until(() => textures.All(t => s.Streamer.RealFrom(t) <= MipWarmer.LoadMip(t)));
+ Assert.Equal(Enumerable.Repeat(13, 8), Zooms(s.Server)); // their 512 px level: four zoom 13 tiles each
+ }
+
+ [Fact]
+ public void A_far_texture_XPlane_just_opened_is_fetched_at_its_load_level_as_soon_as_a_middle_distance_one()
+ {
+ Setup s = Streaming();
+ using var warmer = new MipWarmer(new TextureCatalog(), s.Streamer, s.View, heavy: 2);
+ StreamedTexture here = s.Streamer.Get(Texture())!;
+ s.View.Update(new CameraReport(here.Lat, here.Lon, 2, null, null, false, DateTime.UtcNow));
+
+ var target = warmer.Target(Texture("21904_36144_BI16"))!.Value; // 20 textures east: the distance asks for the base
+
+ Assert.Equal((1, FetchPriority.Warm + 1), (target.Mip, target.Priority));
}
[Fact]
@@ -730,9 +857,11 @@ public void Flying_towards_a_texture_load_ahead_plans_its_next_level_a_minute_be
using var warmer = new MipWarmer(new TextureCatalog(), s.Streamer, s.View, heavy: 2);
StreamedTexture here = s.Streamer.Get(Texture())!;
VirtualPath ahead = Texture("21824_35824_BI16"); // five textures north, about 31 km to its centre
- // With k = 1830 this 1024 px texture is level 1 out to 25 km (22 km to its near edge): parked, it is level 2.
+ // With k = 1830 this 1024 px texture is level 1 out to 25 km (22 km to its near edge): parked, it is level 2,
+ // raised to level 1 (512 px) as what X-Plane reads when it loads it, but not near scenery's turn.
s.View.Update(new CameraReport(here.Lat, here.Lon, 2, null, null, false, DateTime.UtcNow));
- Assert.Equal(2, warmer.Target(ahead)!.Value.Mip);
+ var parked = warmer.Target(ahead)!.Value;
+ Assert.Equal((1, FetchPriority.Warm + 1), (parked.Mip, parked.Priority));
// At 120 m/s straight towards it, it is within 25 km in a minute: fetch level 1 now, as near scenery.
s.View.Update(new CameraReport(here.Lat, here.Lon, 2, null, new Motion(120, 0), false, DateTime.UtcNow));
@@ -884,6 +1013,18 @@ public async Task The_weighted_gate_keeps_the_budget_and_lets_no_small_work_past
Assert.Equal(70, gate.Used);
}
+ [Fact]
+ public void A_waiting_full_size_build_ahead_of_the_aircraft_does_not_hold_back_a_middle_read()
+ {
+ var gate = new WeightedPriorityGate(budget: 100, maxEntries: 10);
+ _ = gate.WaitAsync(60, () => FetchPriority.NearWarm); // a full-size build ahead runs
+ Task ahead = gate.WaitAsync(60, () => FetchPriority.NearWarm); // the next one waits for memory
+ Task read = gate.WaitAsync(10, () => FetchPriority.ForRead(2)); // X-Plane waits for a middle level
+
+ Assert.True(read.IsCompleted);
+ Assert.False(ahead.IsCompleted);
+ }
+
[Fact]
public async Task The_weighted_gate_says_which_budget_holds_its_most_urgent_waiter_back()
{
@@ -1089,30 +1230,33 @@ Task Waiter(string name, FetchTicket ticket) => gate.WaitAsync(ticket).ContinueW
Waiter("middle read", new FetchTicket(FetchPriority.ForRead(2))),
Waiter("big middle read", new FetchTicket(FetchPriority.ForRead(1))),
Waiter("near read", new FetchTicket(FetchPriority.NearRead)),
+ Waiter("near ahead", new FetchTicket(FetchPriority.NearWarm)),
Waiter("warm", new FetchTicket(FetchPriority.Warm)),
];
- background.Raise(FetchPriority.NearWarm); // X-Plane now waits for what it was fetching
+ background.Raise(FetchPriority.ForRead(0)); // X-Plane now waits for what it was fetching
gate.Release();
await Task.WhenAll(waiters);
- Assert.Equal(["near read", "background", "big middle read", "middle read", "warm"], order);
+ // Every read X-Plane waits for goes before the work ahead of the aircraft, even next to it.
+ Assert.Equal(["near read", "background", "big middle read", "middle read", "near ahead", "warm"], order);
}
[Fact]
- public async Task The_low_zoom_base_keeps_tiles_up_to_zoom_12_for_later_sessions()
+ public async Task The_low_zoom_base_keeps_tiles_up_to_zoom_13_for_later_sessions()
{
var server = new FakeTileServer();
var store = new TileStore(_tree.PathOf("base"));
+ Assert.Equal(13, store.MaxZoom); // Bing's zoom 12 is other, lighter imagery: the base starts at 13
using (var tiles = new TileSource("test", FakeTileServer.Template, 4, handler: server) { Store = store })
{
- await tiles.GetTileAsync(10, 20, 12, false, new TileStats());
await tiles.GetTileAsync(10, 20, 13, false, new TileStats());
+ await tiles.GetTileAsync(10, 20, 14, false, new TileStats());
}
using var later = new TileSource("test", FakeTileServer.Template, 4, handler: server) { Store = store };
- Assert.NotNull(later.TryGetStored(10, 20, 12));
- Assert.Null(later.TryGetStored(10, 20, 13)); // finer zooms are not kept
- byte[] tile = await later.GetTileAsync(10, 20, 12, false, new TileStats());
+ Assert.NotNull(later.TryGetStored(10, 20, 13));
+ Assert.Null(later.TryGetStored(10, 20, 14)); // finer zooms are not kept
+ byte[] tile = await later.GetTileAsync(10, 20, 13, false, new TileStats());
Assert.Equal([40, 90, 160], tile[..3]);
- Assert.Equal(2, server.Requests.Count); // the zoom 12 tile came from disk the second time
+ Assert.Equal(2, server.Requests.Count); // the zoom 13 tile came from disk the second time
}
[Fact]
diff --git a/tests/OrthoStreamXP.Tests/TerrainDefinitionsTests.cs b/tests/OrthoStreamXP.Tests/TerrainDefinitionsTests.cs
index 9f86f46..33af72a 100644
--- a/tests/OrthoStreamXP.Tests/TerrainDefinitionsTests.cs
+++ b/tests/OrthoStreamXP.Tests/TerrainDefinitionsTests.cs
@@ -25,7 +25,7 @@ private string Generate(string name) =>
public void Base_definition_matches_AutoOrtho()
{
Assert.Equal(
- "A\n800\nTERRAIN\n\nLOAD_CENTER 74.50816 18.85254 2613 4096\nBASE_TEX_NOWRAP ../textures/11952_36192_BI16.dds\n" +
+ "A\n800\nTERRAIN\n\nLOAD_CENTER 74.50816 18.85254 2613 8192\nBASE_TEX_NOWRAP ../textures/11952_36192_BI16.dds\n" +
"DECAL_LIB lib/g10/decals/maquify_2_green_key.dcl\nNO_ALPHA\n",
Generate("11952_36192_BI16.ter"));
}
@@ -121,7 +121,7 @@ private static byte[] Pixels(byte[] png)
public void At_0_percent_a_generated_definition_has_no_decal_library()
{
Assert.Equal(
- "A\n800\nTERRAIN\n\nLOAD_CENTER 74.50816 18.85254 2613 4096\nBASE_TEX_NOWRAP ../textures/11952_36192_BI16.dds\nNO_ALPHA\n",
+ "A\n800\nTERRAIN\n\nLOAD_CENTER 74.50816 18.85254 2613 8192\nBASE_TEX_NOWRAP ../textures/11952_36192_BI16.dds\nNO_ALPHA\n",
Resolve(WithDecals(0), "11952_36192_BI16.ter"));
}
@@ -204,7 +204,7 @@ private TerrainDefinitions WithNightLights() =>
public void With_night_lights_a_land_tile_names_its_night_texture_right_after_its_photo()
{
Assert.Equal(
- "A\n800\nTERRAIN\n\nLOAD_CENTER 74.50816 18.85254 2613 4096\nBASE_TEX_NOWRAP ../textures/11952_36192_BI16.dds\n" +
+ "A\n800\nTERRAIN\n\nLOAD_CENTER 74.50816 18.85254 2613 8192\nBASE_TEX_NOWRAP ../textures/11952_36192_BI16.dds\n" +
$"LIT_TEX_NOWRAP ../{NightTextures.Folder}/11952_36192_BI16_LIT.dds\n" +
"DECAL_LIB lib/g10/decals/maquify_2_green_key.dcl\nNO_ALPHA\n",
Resolve(WithNightLights(), "11952_36192_BI16.ter"));
diff --git a/tests/OrthoStreamXP.Tests/TextureQualityTests.cs b/tests/OrthoStreamXP.Tests/TextureQualityTests.cs
index 79f812b..4787ecf 100644
--- a/tests/OrthoStreamXP.Tests/TextureQualityTests.cs
+++ b/tests/OrthoStreamXP.Tests/TextureQualityTests.cs
@@ -3,20 +3,18 @@
namespace OrthoStreamXP.Tests;
///
-/// Texture size = the detail --level-change downloads, capped by the level's own limit (4096 px at level 0 and above,
-/// half per level below: the detail a ZL18 texture downloads), never enlarged.
+/// Texture size = the detail --level-change downloads, never shrunk below it (up to 8192 px), never enlarged.
///
public sealed class TextureQualityTests
{
[Theory]
// level ZL16 ZL18
- [InlineData(-4, 256, 256)]
- [InlineData(-3, 512, 512)]
- [InlineData(-2, 1024, 1024)] // Balanced
- [InlineData(-1, 2048, 2048)] // Sharp
- [InlineData(0, 4096, 4096)] // Ultra
- [InlineData(1, 4096, 4096)] // Extra
- [InlineData(2, 4096, 4096)] // never more than 4096
+ [InlineData(-4, 512, 256)]
+ [InlineData(-3, 1024, 512)]
+ [InlineData(-2, 2048, 1024)] // Balanced
+ [InlineData(-1, 4096, 2048)] // Sharp
+ [InlineData(0, 8192, 4096)] // Ultra
+ [InlineData(1, 8192, 8192)] // Extra
public void The_size_follows_the_level(int level, int zl16, int zl18)
{
var plan = new TexturePlan(level);
@@ -25,11 +23,11 @@ public void The_size_follows_the_level(int level, int zl16, int zl18)
[Theory]
// level ZL16 detail / size ZL18 detail / size
- [InlineData(-2, 2, 1)]
- [InlineData(-1, 2, 1)]
- [InlineData(0, 2, 1)]
- [InlineData(1, 2, 2)] // 4096 px is the largest: Extra's zoom 19 airports are shrunk too
- public void Textures_shrink_the_finer_detail_they_download(int level, int zl16, int zl18)
+ [InlineData(-2, 1, 1)]
+ [InlineData(-1, 1, 1)]
+ [InlineData(0, 1, 1)]
+ [InlineData(1, 1, 1)]
+ public void Textures_keep_the_detail_they_download(int level, int zl16, int zl18)
{
var plan = new TexturePlan(level);
// The pixels a texture's tiles hold: 4096 at its own zoom (16 x 16 tiles of 256 px), twice as many per zoom finer.
@@ -39,45 +37,62 @@ public void Textures_shrink_the_finer_detail_they_download(int level, int zl16,
}
[Fact]
- public void Level_plus_one_downloads_zoom_17_and_19_and_builds_4096()
+ public void Level_plus_one_downloads_zoom_17_and_19_and_builds_8192()
{
var plan = new TexturePlan(1);
- Assert.Equal((17, 4096), (plan.FetchZoom(16), plan.SizeFor(16)));
- Assert.Equal((19, 4096), (plan.FetchZoom(18), plan.SizeFor(18)));
- Assert.Equal("Extra_4096-4096", plan.FolderName);
+ Assert.Equal((17, 8192), (plan.FetchZoom(16), plan.SizeFor(16)));
+ Assert.Equal((19, 8192), (plan.FetchZoom(18), plan.SizeFor(18)));
+ Assert.Equal("Extra_8192-8192", plan.FolderName);
}
[Theory]
- // level ZL18 zoom ZL16 zoom
- [InlineData(-3, 15, 14)]
- [InlineData(-2, 16, 15)]
- [InlineData(-1, 17, 16)]
- [InlineData(0, 18, 17)]
- [InlineData(1, 19, 17)] // above level 0 ZL16 uses 16 + level
- public void ZL18_uses_18_plus_level_and_ZL16_one_level_finer_up_to_level_0(int level, int zl18, int zl16)
+ // level areas airports
+ [InlineData(-3, 14, 15)]
+ [InlineData(-2, 15, 16)] // Balanced
+ [InlineData(-1, 16, 17)] // Sharp
+ [InlineData(0, 17, 18)] // Ultra
+ [InlineData(1, 17, 19)] // Extra
+ public void Each_level_downloads_fixed_zooms_whatever_the_package_zoom(int level, int areas, int airports)
{
var plan = new TexturePlan(level);
- Assert.Equal(zl18, plan.FetchZoom(18)); // 18 + level
- Assert.Equal(zl16, plan.FetchZoom(16)); // 16 + (level + 1), 16 + level above 0
- Assert.Equal(17 + level, plan.FetchZoom(17)); // other zooms: zoom + level
+ Assert.Equal((areas, areas), (plan.FetchZoom(16), plan.FetchZoom(17))); // ZL16/ZL17: the areas'
+ Assert.Equal((airports, airports), (plan.FetchZoom(18), plan.FetchZoom(19))); // ZL18/ZL19: the airports'
+ }
+
+ [Fact]
+ public void A_finer_package_gets_the_same_imagery_in_smaller_textures()
+ {
+ var extra = new TexturePlan(1);
+ Assert.Equal((4096, 4096), (extra.SizeFor(17), extra.SizeFor(19))); // zoom 17 and 19 at the files' own zoom
+ var ultra = new TexturePlan(0);
+ Assert.Equal((4096, 2048), (ultra.SizeFor(17), ultra.SizeFor(19))); // zoom 17 and 18
+ }
+
+ [Theory]
+ [InlineData(2)]
+ [InlineData(-5)]
+ public void A_level_without_its_zooms_is_refused(int level)
+ {
+ Assert.False(TexturePlan.IsKnownLevel(level));
+ Assert.Throws(() => new TexturePlan(level));
}
[Fact]
public void Sizes_by_file_name_and_the_log_line()
{
var plan = new TexturePlan(-2);
- Assert.Equal(1024, plan.SizeFor("21904_35824_BI16.dds"));
+ Assert.Equal(2048, plan.SizeFor("21904_35824_BI16.dds"));
Assert.Null(plan.SizeFor("water_transition.dds"));
- Assert.Equal("ZL16 → zoom 15, 1024 px; ZL18 → zoom 16, 1024 px", plan.Describe());
- Assert.Equal(2048, new TexturePlan(-2, TextureSizing.MaxSize).SizeFor(16)); // an explicit limit (tests) replaces the level's
+ Assert.Equal("ZL16 → zoom 15, 2048 px; ZL18 → zoom 16, 1024 px", plan.Describe());
+ Assert.Equal(4096, new TexturePlan(0, 4096).SizeFor(16)); // an explicit limit (tests) caps the size
}
[Theory]
- [InlineData(-2, "Balanced_1024-1024")]
- [InlineData(-1, "Sharp_2048-2048")]
- [InlineData(0, "Ultra_4096-4096")]
- [InlineData(1, "Extra_4096-4096")]
- [InlineData(-3, "level-3_512-512")]
+ [InlineData(-2, "Balanced_2048-1024")]
+ [InlineData(-1, "Sharp_4096-2048")]
+ [InlineData(0, "Ultra_8192-4096")]
+ [InlineData(1, "Extra_8192-8192")]
+ [InlineData(-3, "level-3_1024-512")]
public void Each_level_has_its_own_cache_folder(int level, string folder) =>
Assert.Equal(folder, new TexturePlan(level).FolderName);
@@ -89,6 +104,8 @@ public void Each_level_has_its_own_cache_folder(int level, string folder) =>
[InlineData(0, "21904_35824_BI16", "43808_71648_PX17")]
[InlineData(-2, "21904_35824_ARC16", "10952_17912_PX15")] // the package's code is left out
[InlineData(0, "43792_71648_BI17", "43792_71648_BI17")] // ZL17 is downloaded where ZL16 is: it keeps its name
+ [InlineData(1, "175040_286880_BI19", "175040_286880_BI19")] // ZL19 where ZL18 is
+ [InlineData(1, "10944_17904_BI15", "10944_17904_BI15")]
public void The_cache_names_a_texture_by_the_tiles_it_downloads(int level, string stem, string cacheStem)
{
Assert.True(TextureName.TryParseStem(stem, out TextureName name));
@@ -98,8 +115,8 @@ public void The_cache_names_a_texture_by_the_tiles_it_downloads(int level, strin
[Fact]
public void A_cache_name_reads_back_as_its_texture_at_every_level()
{
- TextureName[] names = [new(21904, 35824, "BI", 16), new(87520, 143440, "BI", 18), new(10944, 17904, "BI", 15), new(175040, 286880, "BI", 19)];
- for (int level = -4; level <= 2; level++)
+ TextureName[] names = [new(21904, 35824, "BI", 16), new(87520, 143440, "BI", 18)];
+ for (int level = -4; level <= 1; level++)
{
var plan = new TexturePlan(level);
foreach (TextureName name in names)
@@ -119,7 +136,7 @@ public async Task Finer_detail_is_shrunk_to_the_size_when_built()
using var tree = new TempTree();
using var tiles = new TileSource("synthetic", null, 8);
string destination = tree.PathOf("21904_35824_BI16.dds");
- int size = new TexturePlan(-3).SizeFor(16); // 512 px from level -2's 1024 px of detail
+ const int size = 512; // from level -2's 1024 px of detail: a level beyond Extra's still shrinks what it downloads
BuildResult result = await new TextureBuilder(tiles, 2).BuildAsync("21904_35824_BI16.dds", size, destination, levelChange: -2);
diff --git a/tests/OrthoStreamXP.Tests/TextureResolutionTests.cs b/tests/OrthoStreamXP.Tests/TextureResolutionTests.cs
new file mode 100644
index 0000000..8e97afc
--- /dev/null
+++ b/tests/OrthoStreamXP.Tests/TextureResolutionTests.cs
@@ -0,0 +1,151 @@
+using OrthoStreamXP.Scenery;
+using OrthoStreamXP.Setup;
+using OrthoStreamXP.Textures;
+
+namespace OrthoStreamXP.Tests;
+
+///
+/// A preset's resolution shrinks its textures from the same downloads: Full as they are, Medium halves the wide ZL16
+/// areas' and keeps the airports' ZL18 ones, Low halves them all. Each preset keeps its own in the settings.
+///
+public sealed class TextureResolutionTests : IDisposable
+{
+ private readonly TempTree _tree = new();
+
+ public void Dispose() => _tree.Dispose();
+
+ // ---------------------------------------------------------------- sizes
+
+ [Theory]
+ // level resolution ZL16 ZL18
+ [InlineData(-2, "full", 2048, 1024)] // Balanced
+ [InlineData(-2, "medium", 1024, 1024)]
+ [InlineData(-2, "low", 1024, 512)]
+ [InlineData(-1, "medium", 2048, 2048)] // Sharp
+ [InlineData(0, "full", 8192, 4096)] // Ultra
+ [InlineData(0, "medium", 4096, 4096)]
+ [InlineData(0, "low", 4096, 2048)]
+ [InlineData(1, "medium", 4096, 8192)] // Extra
+ [InlineData(1, "low", 4096, 4096)]
+ public void The_resolution_halves_the_size_but_not_the_imagery(int level, string resolution, int zl16, int zl18)
+ {
+ var plan = new TexturePlan(level) { Resolution = TextureResolution.Parse(resolution)! };
+ var full = new TexturePlan(level);
+
+ Assert.Equal((zl16, zl18), (plan.SizeFor(16), plan.SizeFor(18)));
+ Assert.Equal((full.FetchZoom(16), full.FetchZoom(18)), (plan.FetchZoom(16), plan.FetchZoom(18))); // the same downloads
+ }
+
+ [Fact]
+ public void Every_size_is_a_power_of_two_X_Plane_takes()
+ {
+ // X-Plane: "The texture ... is DDS but its size is not power of 2", and the texture is missing.
+ foreach (TextureResolution resolution in TextureResolution.All)
+ foreach (QualityPreset preset in QualityPreset.Choices)
+ foreach (int zoom in new[] { 14, 15, 16, 17, 18, 19 })
+ {
+ int size = preset.PlanAt(resolution).SizeFor(zoom);
+ Assert.True(size >= 4 && (size & (size - 1)) == 0, $"{preset.Name} at {resolution.Label}: ZL{zoom} is {size} px");
+ }
+ }
+
+ [Fact]
+ public void Each_resolution_keeps_its_own_cache_folder_and_it_is_named_after_it()
+ {
+ Assert.Equal("Ultra_8192-4096", new TexturePlan(0).FolderName);
+ Assert.Equal("Ultra_4096-4096", new TexturePlan(0) { Resolution = TextureResolution.Medium }.FolderName);
+ Assert.Equal("Ultra_4096-2048", new TexturePlan(0) { Resolution = TextureResolution.Low }.FolderName);
+
+ Assert.Equal("Ultra", CacheInventory.ParseSetupName("Ultra_8192-4096")!.PresetTitle);
+ Assert.Equal("Ultra, Medium resolution", CacheInventory.ParseSetupName("Ultra_4096-4096")!.PresetTitle);
+ Assert.Equal("Ultra, Low resolution", CacheInventory.ParseSetupName("Ultra_4096-2048")!.PresetTitle);
+ Assert.Equal("Extra, Medium resolution", CacheInventory.ParseSetupName("Extra_4096-8192")!.PresetTitle);
+ }
+
+ [Theory]
+ [InlineData("full", false, false)]
+ [InlineData("Medium", true, false)]
+ [InlineData(" low ", true, true)]
+ public void Resolutions_are_read_by_name(string value, bool areas, bool airports)
+ {
+ TextureResolution resolution = TextureResolution.Parse(value)!;
+ Assert.Equal((areas, airports), (resolution.HalvesAreas, resolution.HalvesAirports));
+ }
+
+ [Fact]
+ public void An_unknown_resolution_is_none() => Assert.Null(TextureResolution.Parse("high"));
+
+ // ---------------------------------------------------------------- the settings
+
+ private MountSettings Parse(params string[] extra)
+ {
+ Directory.CreateDirectory(_tree.PathOf("source"));
+ return MountSettings.FromValues(TestSettings.Of(
+ [$"source = {_tree.PathOf("source")}", $"cache = {_tree.PathOf("cache")}", $"mountpoint = {_tree.PathOf("mount")}", .. extra]));
+ }
+
+ [Fact]
+ public void The_mount_uses_the_resolution_of_the_preset_the_settings_are_at()
+ {
+ Assert.Same(TextureResolution.Full, Parse("level-change = 0").Textures.Resolution); // not set: Full
+
+ MountSettings ultra = Parse("level-change = 0", "resolution-ultra = medium", "resolution-sharp = low");
+ Assert.Same(TextureResolution.Medium, ultra.Textures.Resolution);
+ Assert.Equal((4096, 4096), (ultra.Textures.SizeFor(16), ultra.Textures.SizeFor(18)));
+ Assert.EndsWith("Ultra_4096-4096", ultra.PlanCache, StringComparison.Ordinal);
+
+ Assert.Same(TextureResolution.Low, Parse("level-change = -1", "resolution-ultra = medium", "resolution-sharp = low").Textures.Resolution);
+ }
+
+ [Fact]
+ public void Dynamic_has_its_own_resolution_apart_from_Extras()
+ {
+ Assert.Same(TextureResolution.Low,
+ Parse("level-change = 1", "dynamic-quality = on", "resolution-dynamic = low", "resolution-extra = medium").Textures.Resolution);
+ Assert.Same(TextureResolution.Medium,
+ Parse("level-change = 1", "dynamic-quality = off", "resolution-dynamic = low", "resolution-extra = medium").Textures.Resolution);
+ }
+
+ [Fact]
+ public void A_level_no_preset_has_and_a_wrong_resolution_are_errors()
+ {
+ foreach (string level in new[] { "-4", "-3", "2" })
+ Assert.Contains("level-change", Assert.Throws(() => Parse($"level-change = {level}")).Message, StringComparison.Ordinal);
+ var error = Assert.Throws(() => Parse("level-change = 0", "resolution-ultra = high"));
+ Assert.Contains("resolution-ultra", error.Message, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public void Every_preset_has_its_resolution_setting_and_the_window_reads_it()
+ {
+ foreach (QualityPreset preset in QualityPreset.Choices)
+ TestSettings.Of($"{preset.ResolutionKey} = medium"); // an unknown setting would throw
+
+ SettingsDocument document = SettingsDocument.FromText(_tree.PathOf("settings.ini"), "level-change = 1\ndynamic-quality = on\nresolution-dynamic = low\n");
+ Assert.Same(TextureResolution.Low, QualityPreset.Dynamic.ResolutionIn(document));
+ Assert.Same(TextureResolution.Full, QualityPreset.Extra.ResolutionIn(document));
+ Assert.Equal((4096, 4096), (QualityPreset.PlanIn(document).SizeFor(16), QualityPreset.PlanIn(document).SizeFor(18)));
+ }
+
+ [Fact]
+ public void A_new_settings_file_lists_every_presets_resolution_and_the_setup_sets_them_in_place()
+ {
+ SettingsDocument settings = SettingsDocument.CreateNew(_tree.PathOf("orthostreamxp.ini"), @"C:\X-Plane 12", @"C:\Packages", @"D:\cache", QualityPreset.Ultra);
+ Assert.All(QualityPreset.Choices, p => Assert.Same(TextureResolution.Full, p.ResolutionIn(settings)));
+ int lines = settings.Lines.Count;
+
+ settings.Set(QualityPreset.Ultra.ResolutionKey, TextureResolution.Medium.Value); // what the setup writes for each card
+ Assert.Equal(lines, settings.Lines.Count); // in its place in the file, not added at the end
+ Assert.Same(TextureResolution.Medium, QualityPreset.Ultra.ResolutionIn(settings));
+ Assert.Equal(4096, QualityPreset.PlanIn(settings).SizeFor(16));
+ settings.Parse(); // the file reads as settings
+ }
+
+ [Fact]
+ public void Dynamic_qualitys_steps_shrink_with_the_mounts_resolution()
+ {
+ var mount = new TexturePlan(1) { Resolution = TextureResolution.Low };
+ IReadOnlyList tiers = new DynamicOptions().TiersBelow(mount);
+ Assert.Equal([2048, 1024], tiers.Select(t => t.Plan.SizeFor(16))); // Sharp and Balanced at Low
+ }
+}
diff --git a/tests/OrthoStreamXP.Tests/TileMemoryTests.cs b/tests/OrthoStreamXP.Tests/TileMemoryTests.cs
new file mode 100644
index 0000000..f6c8f78
--- /dev/null
+++ b/tests/OrthoStreamXP.Tests/TileMemoryTests.cs
@@ -0,0 +1,110 @@
+using OrthoStreamXP.Scenery;
+using OrthoStreamXP.Textures;
+
+namespace OrthoStreamXP.Tests;
+
+/// Builds keep downloaded tiles as their image bytes and decode them into reused buffers, with the same pixels.
+public sealed class TileMemoryTests
+{
+ private static readonly TextureName Name = new(21904, 35824, "BI", 16);
+
+ [Theory]
+ [InlineData(4096)] // each tile as it is
+ [InlineData(1024)] // each tile shrunk twice (256 -> 64 px)
+ public async Task The_stitched_region_has_each_tile_decoded_on_its_own(int size)
+ {
+ // One tile comes at 512 px, which is resized to a tile first.
+ bool Large(int x, int y, int z) => x == Name.Col + 7 && y == Name.Row + 2;
+ using var tiles = new TileSource("test", PhotoTileServer.Template, 8, handler: new PhotoTileServer(large: Large));
+
+ var (rgb, regionSize) = await new TextureBuilder(tiles, 2).FetchRegionAsync(Name, 16, size, new FetchTicket(FetchPriority.Warm), new TileStats());
+
+ Assert.Equal(size, regionSize);
+ int tilePx = size / Tiles.TextureSpan;
+ byte[] expected = new byte[size * size * 3];
+ for (int row = 0; row < Tiles.TextureSpan; row++)
+ for (int column = 0; column < Tiles.TextureSpan; column++)
+ {
+ int x = Name.Col + column, y = Name.Row + row;
+ byte[] tile = Images.DecodeTile(PhotoTileServer.Jpeg(x, y, 16, Large(x, y, 16)));
+ for (int px = Tiles.TilePx; px > tilePx; px >>= 1) tile = MipFilter.Half(tile, px, px, 1);
+ for (int line = 0; line < tilePx; line++)
+ Buffer.BlockCopy(tile, line * tilePx * 3, expected, ((row * tilePx + line) * size + column * tilePx) * 3, tilePx * 3);
+ }
+ Assert.True(expected.AsSpan().SequenceEqual(rgb), "The stitched region differs from its tiles decoded one by one");
+ }
+
+ [Fact]
+ public async Task A_tile_that_does_not_decode_is_rejected_when_downloaded()
+ {
+ using var tiles = new TileSource("test", PhotoTileServer.Template, 1, attempts: 1, handler: new BrokenTileServer());
+
+ await Assert.ThrowsAsync(() => tiles.GetSourceTileAsync(1, 2, 3, new FetchTicket(FetchPriority.Warm), new TileStats()));
+ }
+
+ [Fact]
+ public void Header_and_levels_are_written_as_one_file()
+ {
+ using var tree = new TempTree();
+ string path = tree.PathOf("textures/a.dds");
+
+ AtomicFile.Write(path, "DDS "u8, [1, 2, 3]);
+
+ Assert.Equal([.. "DDS "u8, 1, 2, 3], File.ReadAllBytes(path));
+ Assert.Empty(Directory.GetFiles(Path.GetDirectoryName(path)!, "*.partial"));
+ }
+
+ /// Answers every tile with a truncated JPEG.
+ private sealed class BrokenTileServer : HttpMessageHandler
+ {
+ protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) =>
+ Task.FromResult(new HttpResponseMessage(System.Net.HttpStatusCode.OK)
+ {
+ Content = new ByteArrayContent(PhotoTileServer.Jpeg(1, 2, 3)[..200]),
+ });
+ }
+}
+
+[CollectionDefinition(nameof(AllocationCounting), DisableParallelization = true)]
+public sealed class AllocationCounting;
+
+/// Counts the bytes a build allocates, so no other test may run meanwhile.
+[Collection(nameof(AllocationCounting))]
+public sealed class BuildAllocationTests
+{
+ [Fact]
+ public async Task A_build_allocates_little_beyond_the_levels_it_keeps()
+ {
+ var name = new TextureName(21904, 35824, "BI", 16);
+ var layout = DdsLayout.For(4096);
+ using var tiles = new TileSource("test", PhotoTileServer.Template, 8, handler: new PhotoTileServer());
+ var builder = new TextureBuilder(tiles, 2);
+ // The first build fills the buffer pools and the server's own JPEG cache.
+ await builder.BuildChainAsync(name, layout, 0, 16, new FetchTicket(FetchPriority.Warm), new TileStats());
+
+ long before = GC.GetTotalAllocatedBytes(precise: true);
+ byte[] chain = await builder.BuildChainAsync(name, layout, 0, 16, new FetchTicket(FetchPriority.Warm), new TileStats());
+ long extra = GC.GetTotalAllocatedBytes(precise: true) - before - chain.Length;
+
+ // 256 tiles: their JPEGs and the HTTP answers carrying them, some 30 KB each. Decoded into arrays of their own
+ // they were 48 MB more.
+ Assert.True(extra < 24L << 20, $"The build allocated {extra >> 20} MB beyond its {chain.Length >> 20} MB of levels");
+ }
+
+ [Fact]
+ public async Task A_build_holds_no_more_than_its_weight()
+ {
+ const int size = 4096;
+ var name = new TextureName(21904, 35824, "BI", 16);
+ using var tiles = new TileSource("test", PhotoTileServer.Template, 8, handler: new PhotoTileServer());
+ var buffers = new BuildBufferPool(1L << 30);
+
+ byte[] chain = await new TextureBuilder(tiles, 2, buffers).BuildChainAsync(name, DdsLayout.For(size), 0, 16, new FetchTicket(FetchPriority.Warm), new TileStats());
+
+ // The picture and the two its smaller levels took turns in, each at its exact size, all given back.
+ Assert.Equal(0, buffers.RentedBytes);
+ Assert.Equal((long)size * size * 3 + size / 2 * (size / 2) * 3 + size / 4 * (size / 4) * 3, buffers.KeptBytes);
+ Assert.True(buffers.KeptBytes + chain.Length <= TextureStreamer.BuildWeight(size),
+ $"The build held {(buffers.KeptBytes + chain.Length) >> 20} MB, more than its weight of {TextureStreamer.BuildWeight(size) >> 20} MB");
+ }
+}
diff --git a/tests/OrthoStreamXP.Tests/TuningTests.cs b/tests/OrthoStreamXP.Tests/TuningTests.cs
index c2abbe2..82b7d33 100644
--- a/tests/OrthoStreamXP.Tests/TuningTests.cs
+++ b/tests/OrthoStreamXP.Tests/TuningTests.cs
@@ -1,5 +1,6 @@
using OrthoStreamXP.Scenery;
using OrthoStreamXP.Setup;
+using OrthoStreamXP.Textures;
using OrthoStreamXP.Tuning;
namespace OrthoStreamXP.Tests;
@@ -350,9 +351,9 @@ public void A_texture_takes_the_detail_X_Plane_wanted_but_never_more_than_its_si
[Fact]
public void A_flight_measures_the_peak_and_sizes_above_it_follow_the_test_flight()
{
- var meter = new GraphicsMemoryMeter(flownSize: 2048);
- meter.Sample([2048, 2048, 512]);
- meter.Sample([2048]); // later, less: the peak stays
+ var meter = new GraphicsMemoryMeter(areaSize: 2048, airportSize: 2048);
+ meter.Sample([new(2048, false), new(2048, false), new(512, false)]);
+ meter.Sample([new(2048, false)]); // later, less: the peak stays
GraphicsMemory memory = meter.Result();
Assert.Equal(2 * GraphicsMemory.TextureBytes(2048) + GraphicsMemory.TextureBytes(512), memory.BytesAt(2048));
@@ -390,17 +391,131 @@ public void Without_a_flight_it_is_Sharp_or_Balanced_on_a_small_graphics_card()
}
[Theory]
- [InlineData(150, 16, "Extra")] // fast and a big card: the finest
- [InlineData(60, 16, "Ultra")] // not fast enough for Extra's 4 times the downloads
- [InlineData(150, 6, "Sharp")] // 4096 px textures and X-Plane would not fit in 6 GB
- [InlineData(10, 16, "Balanced")]
- public void After_a_flight_it_is_the_sharpest_the_connection_and_the_card_allow(double mbits, int cardGb, string expected)
+ [InlineData(150, 16, "Extra", "Full")] // fast and a big card: the finest
+ [InlineData(60, 16, "Ultra", "Full")] // not fast enough for Extra's 4 times the downloads
+ [InlineData(150, 7, "Ultra", "Medium")] // Ultra's 8192 px would not fit in 7 GB; at Medium 4096 px everywhere, sharper airports than Sharp's
+ [InlineData(150, 6, "Sharp", "Medium")] // nor 4096 px in 6 GB: 2048 px everywhere, from Sharp's finer imagery than Balanced's
+ [InlineData(10, 16, "Balanced", "Full")] // the connection decides the preset; the big card then holds it at Full
+ [InlineData(150, 5, "Balanced", "Low")] // nothing beside X-Plane's own 5 GB: the smallest textures
+ public void After_a_flight_it_is_the_largest_textures_the_connection_and_the_card_allow(double mbits, int cardGb, string preset, string resolution)
{
Recommendation r = PresetAdvisor.Recommend(cardGb * Gb, GraphicsMemory.TestFlight, [Flight("level0_4096-4096", mbits)]);
- Assert.Equal(expected, r.Preset.Name);
+ Assert.Equal((preset, resolution), (r.Preset.Name, r.Resolution.Label));
Assert.Contains("Mbit/s", r.Reason, StringComparison.Ordinal);
}
+ private static ConnectionResult Tested(double mbits) =>
+ new(DateTime.UtcNow, "bing", [new ConnectionRound(64, 256, 0, (long)(mbits * 1e6 / 8), 1, 0.14, mbits)], 64);
+
+ [Fact]
+ public void The_faster_of_the_flights_and_the_connection_test_counts()
+ {
+ // Flights peaked at 47 Mbit/s, at what their preset asked; the test then measured 62: the connection does at least 62.
+ Recommendation tested = PresetAdvisor.Recommend(16 * Gb, GraphicsMemory.TestFlight, [Flight("level-1_4096-2048", 47)], Tested(62));
+ Assert.Equal(QualityPreset.Ultra, tested.Preset);
+ Assert.Contains("the connection test measured 62 Mbit/s", tested.Reason, StringComparison.Ordinal);
+
+ // A flight faster than the test: the flight counts, and the reason says so.
+ Recommendation flown = PresetAdvisor.Recommend(16 * Gb, GraphicsMemory.TestFlight, [Flight("level0_8192-4096", 140)], Tested(62));
+ Assert.Equal(QualityPreset.Extra, flown.Preset);
+ Assert.Contains("downloads reached 140 Mbit/s on your recent flights", flown.Reason, StringComparison.Ordinal);
+ }
+
+ private static Dictionary Assess(long? card, IReadOnlyList flights, ConnectionResult? test = null) =>
+ PresetAdvisor.Assess(card, GraphicsMemory.TestFlight, flights, test).ToDictionary(f => f.Preset.Name);
+
+ [Fact]
+ public void Every_card_says_whether_its_preset_also_suits_and_why_not()
+ {
+ // A 16 GB card, flights at 47 Mbit/s, a connection test at 59: Ultra is recommended.
+ Dictionary fits = Assess(16 * Gb, [Flight("level-1_4096-2048", 47)], Tested(59));
+
+ Assert.All(new[] { "Balanced", "Sharp", "Ultra" }, name => Assert.Equal(("Also suits your PC.", TextureResolution.Full), (fits[name].Text, fits[name].Resolution)));
+ Assert.All(new[] { "Extra", "Dynamic" }, name =>
+ {
+ Assert.False(fits[name].Suits);
+ Assert.Equal("Needs about 100 Mbit/s of downloads: the connection test measured 59 Mbit/s.", fits[name].Text);
+ });
+ }
+
+ [Fact]
+ public void A_card_that_holds_a_preset_only_at_a_lower_resolution_says_which()
+ {
+ // 7 GB and a fast connection: Ultra at Medium is recommended; Extra suits at Low (4096 px everywhere) and Sharp at Full.
+ Dictionary fits = Assess(7 * Gb, [Flight("level0_4096-4096", 150)]);
+ Assert.Equal(TextureResolution.Medium, fits["Ultra"].Resolution);
+ Assert.Equal(TextureResolution.Low, fits["Extra"].Resolution);
+ Assert.Equal("Also suits your PC at Low resolution: at Full its textures would not fit your 7 GB graphics card.", fits["Extra"].Text);
+ Assert.Equal(TextureResolution.Full, fits["Sharp"].Resolution);
+
+ // 5 GB is X-Plane's own: nothing fits.
+ Assert.All(Assess(5 * Gb, [Flight("level0_4096-4096", 150)]).Values, f => Assert.StartsWith("Too large for your 5 GB graphics card", f.Text, StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void Without_a_measured_connection_the_sharper_cards_ask_for_a_test()
+ {
+ Dictionary fits = Assess(16 * Gb, []);
+ Assert.Equal("Also suits your PC.", fits["Sharp"].Text);
+ Assert.Equal("Fits your graphics card. Test your connection to see whether it keeps up with its downloads.", fits["Ultra"].Text);
+ }
+
+ [Fact]
+ public void A_blurry_flight_rules_out_its_quality_and_the_sharper_ones_on_their_cards()
+ {
+ Dictionary fits = Assess(16 * Gb, [Flight("level0_8192-4096", 150, reads: 10_000, standIns: 900)]);
+ Assert.False(fits["Ultra"].Suits);
+ Assert.False(fits["Extra"].Suits);
+ Assert.True(fits["Sharp"].Suits);
+ Assert.StartsWith("Not for now", fits["Ultra"].Text, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public void A_shrunk_resolution_is_recommended_only_when_Full_would_not_fit_and_says_so()
+ {
+ Recommendation r = PresetAdvisor.Recommend(7 * Gb, GraphicsMemory.TestFlight, [Flight("level0_4096-4096", 150)]);
+ Assert.Equal("Ultra at Medium resolution", r.Title);
+ Assert.Contains("would not hold Ultra's textures at Full resolution, at Medium it does", r.Reason, StringComparison.Ordinal);
+
+ // Equal textures: Ultra at Medium and Extra at Low are both 4096 px everywhere; Ultra downloads less for them.
+ Assert.Equal(QualityPreset.Ultra, r.Preset);
+ Assert.Equal(TextureResolution.Full, PresetAdvisor.Recommend(16 * Gb, GraphicsMemory.TestFlight, [Flight("level0_4096-4096", 150)]).Resolution);
+ }
+
+ [Fact]
+ public void Without_a_flight_a_small_card_gets_Sharps_imagery_at_a_lower_resolution()
+ {
+ Recommendation r = PresetAdvisor.Recommend(6 * Gb, GraphicsMemory.TestFlight, []);
+ Assert.Equal((QualityPreset.Sharp, TextureResolution.Medium), (r.Preset, r.Resolution));
+ Assert.Contains("Test your connection or fly once", r.Reason, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public void Measured_airports_let_Extra_at_Medium_count_its_airports_at_8192_and_its_areas_at_4096()
+ {
+ // A flight at Extra at Medium: the areas' textures 4096 px, the airports' 8192.
+ var meter = new GraphicsMemoryMeter(areaSize: 4096, airportSize: 8192);
+ meter.Sample([new(4096, false), new(4096, false), new(1024, false), new(8192, true)]);
+ GraphicsMemory memory = meter.Result();
+
+ long areas = 2 * GraphicsMemory.TextureBytes(4096) + GraphicsMemory.TextureBytes(1024);
+ Assert.Equal(areas + GraphicsMemory.TextureBytes(8192), memory.BytesAt(4096, 8192));
+ Assert.Equal(areas + GraphicsMemory.TextureBytes(4096), memory.BytesAt(4096, 4096)); // Extra at Low: the airports halved
+ Assert.True(memory.BytesAt(8192, 8192) > memory.BytesAt(4096, 8192)); // Extra at Full: the areas beyond the flown 4096, by the test flight's ratio
+
+ // Saved and read back with its airports' part.
+ using var tree = new TempTree();
+ memory.Save(tree.Root);
+ Assert.Equal(memory.BytesAt(4096, 8192), GraphicsMemory.Load(tree.Root).BytesAt(4096, 8192));
+ }
+
+ [Fact]
+ public void Without_the_airports_measured_both_count_at_the_larger_size()
+ {
+ Assert.Equal(GraphicsMemory.TestFlight.BytesAt(8192), GraphicsMemory.TestFlight.BytesAt(4096, 8192));
+ Assert.Equal(GraphicsMemory.TestFlight.BytesAt(1024), GraphicsMemory.TestFlight.BytesAt(1024, 512)); // below the model's sizes: as its smallest
+ }
+
[Fact]
public void A_flight_over_cached_scenery_says_nothing_about_the_connection_but_an_earlier_fast_one_does()
{
diff --git a/tests/OrthoStreamXP.Tests/UpcomingSceneryTests.cs b/tests/OrthoStreamXP.Tests/UpcomingSceneryTests.cs
new file mode 100644
index 0000000..990d891
--- /dev/null
+++ b/tests/OrthoStreamXP.Tests/UpcomingSceneryTests.cs
@@ -0,0 +1,83 @@
+using System.Buffers.Binary;
+using System.Text;
+using OrthoStreamXP.Scenery;
+
+namespace OrthoStreamXP.Tests;
+
+/// The scenery tiles X-Plane will load next, and the textures their DSFs use.
+public sealed class UpcomingSceneryTests
+{
+ [Fact]
+ public void The_terrain_table_lists_the_definitions_of_a_DSF()
+ {
+ using var tree = new TempTree();
+ string path = tree.PathOf("+47+011.dsf");
+ File.WriteAllBytes(path, Dsf("terrain_Water", "terrain/22992_34800_BI16.ter", "terrain/89376_140560_BI18_water_overlay.ter"));
+
+ Assert.Equal(["terrain_Water", "terrain/22992_34800_BI16.ter", "terrain/89376_140560_BI18_water_overlay.ter"], DsfTerrainTable.Read(path));
+ }
+
+ [Fact]
+ public void A_file_that_is_no_DSF_has_no_terrain_table()
+ {
+ using var tree = new TempTree();
+ string path = tree.PathOf("+47+011.dsf");
+ File.WriteAllBytes(path, [(byte)'7', (byte)'z', 0xBC, 0xAF, 0x27, 0x1C, 0, 4, 1, 2, 3, 4, 5, 6]); // a 7-Zip DSF
+
+ Assert.Empty(DsfTerrainTable.Read(path));
+ }
+
+ [Fact]
+ public void XPlane_keeps_three_rows_and_four_columns_of_tiles_around_the_aircraft()
+ {
+ // The test flight of 17 Nov: at 47.72, 13.05 X-Plane loaded +46..+48 and +011..+014.
+ var expected = from lat in new[] { 46, 47, 48 } from lon in new[] { 11, 12, 13, 14 } select new SceneryTile(lat, lon);
+
+ Assert.Equal(expected.ToHashSet(), UpcomingScenery.LoadedAround(47.72, 13.05).ToHashSet());
+ }
+
+ [Fact]
+ public void Flying_north_the_next_row_is_ahead()
+ {
+ // 150 m/s north from 47.95: past 48 within the look-ahead, so the block takes in row +49.
+ var camera = new CameraReport(47.95, 12.6, 900, null, new Motion(150, 0), false, DateTime.UtcNow);
+
+ List ahead = UpcomingScenery.Ahead(camera);
+
+ Assert.Equal(new[] { 11, 12, 13, 14 }.Select(lon => new SceneryTile(49, lon)).ToHashSet(), ahead.ToHashSet());
+ }
+
+ [Fact]
+ public void Parked_or_placed_from_reads_nothing_is_ahead()
+ {
+ Assert.Empty(UpcomingScenery.Ahead(new CameraReport(47.95, 12.6, 2, null, null, false, DateTime.UtcNow)));
+ Assert.Empty(UpcomingScenery.Ahead(new CameraReport(47.95, 12.6, 0, null, new Motion(150, 0), false, DateTime.UtcNow, Inferred: true)));
+ }
+
+ [Fact]
+ public void A_tile_DSF_lies_in_its_ten_degree_folder()
+ {
+ Assert.Equal(Path.Join("Earth nav data", "+40+010", "+47+011.dsf"), new SceneryTile(47, 11).DsfPath);
+ Assert.Equal(Path.Join("Earth nav data", "-10-080", "-03-071.dsf"), new SceneryTile(-3, -71).DsfPath);
+ Assert.Equal(new SceneryTile(-1, -180), SceneryTile.At(-0.5, 180.5));
+ }
+
+ /// A DSF of a header atom, the definitions (the terrain table and an empty object table) and an empty mesh.
+ internal static byte[] Dsf(params string[] terrain)
+ {
+ static byte[] Atom(string id, byte[] payload)
+ {
+ byte[] atom = new byte[8 + payload.Length];
+ Encoding.ASCII.GetBytes(new string([.. id.Reverse()])).CopyTo(atom, 0); // ids are stored as little-endian numbers
+ BinaryPrimitives.WriteUInt32LittleEndian(atom.AsSpan(4), (uint)atom.Length);
+ payload.CopyTo(atom, 8);
+ return atom;
+ }
+
+ byte[] table = Encoding.ASCII.GetBytes(string.Concat(terrain.Select(t => t + "\0")));
+ byte[] definitions = [.. Atom("TERT", table), .. Atom("OBJT", [])];
+ byte[] version = new byte[4];
+ BinaryPrimitives.WriteInt32LittleEndian(version, 1);
+ return [.. "XPLNEDSF"u8, .. version, .. Atom("HEAD", new byte[86]), .. Atom("DEFN", definitions), .. Atom("GEOD", new byte[32]), .. new byte[16]];
+ }
+}
diff --git a/tests/OrthoStreamXP.Tests/WindowSettingsTests.cs b/tests/OrthoStreamXP.Tests/WindowSettingsTests.cs
index f003717..89d5817 100644
--- a/tests/OrthoStreamXP.Tests/WindowSettingsTests.cs
+++ b/tests/OrthoStreamXP.Tests/WindowSettingsTests.cs
@@ -66,7 +66,15 @@ public void An_older_settings_file_with_texture_quality_still_loads()
string path = _tree.WriteText("old.ini", "cache = C:\\c\nlevel-change = 0\ntexture-quality = high\n");
SettingValues args = SettingsDocument.Load(path).Parse(); // no "unknown setting" error
Assert.Equal("high", args.String("texture-quality"));
- Assert.Equal(4096, new OrthoStreamXP.Textures.TexturePlan(args.Int("level-change", 0)).SizeFor(16)); // Ultra's size, whatever it says
+ Assert.Equal(8192, new OrthoStreamXP.Textures.TexturePlan(args.Int("level-change", 0)).SizeFor(16)); // Ultra's size, whatever it says
+ }
+
+ [Fact]
+ public void An_older_settings_file_with_the_removed_colour_matching_still_loads()
+ {
+ string path = _tree.WriteText("old.ini", "cache = C:\\c\nmatch-colours = on\nmatch-strength = 60\n");
+ SettingValues args = SettingsDocument.Load(path).Parse(); // no "unknown setting" error
+ Assert.Equal("on", args.String("match-colours"));
}
[Theory]
@@ -96,6 +104,32 @@ public void Choosing_a_preset_keeps_the_connection_settings()
Assert.Equal(8, settings.GetInt("dds-build-workers"));
}
+ [Fact]
+ public void Choosing_a_preset_rewrites_the_preset_comment_of_a_new_settings_file()
+ {
+ SettingsDocument settings = SettingsDocument.CreateNew(_tree.PathOf("orthostreamxp.ini"), @"C:\X-Plane 12", @"C:\Packages", @"D:\cache", QualityPreset.Sharp);
+ int line = settings.Lines.ToList().FindIndex(l => l.StartsWith("level-change", StringComparison.Ordinal));
+ Assert.Equal("# quality preset: Sharp; the level also sets the texture size (4096 px)", settings.Lines[line - 1]);
+
+ QualityPreset.Ultra.ApplyTo(settings);
+ Assert.Equal("# quality preset: Ultra; the level also sets the texture size (8192 px)", settings.Lines[line - 1]);
+
+ QualityPreset.DynamicSharp.ApplyTo(settings);
+ Assert.Equal("# quality preset: Dynamic from Sharp; the level also sets the texture size (4096 px)", settings.Lines[line - 1]);
+ Assert.Single(settings.Lines, l => l.StartsWith(QualityPreset.LevelCommentPrefix, StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void Choosing_a_preset_keeps_a_comment_of_your_own_above_the_level()
+ {
+ var settings = SettingsDocument.FromText("x.ini", "# my own note\nlevel-change = -2\n");
+
+ QualityPreset.Ultra.ApplyTo(settings);
+
+ Assert.Equal("# my own note", settings.Lines[0]);
+ Assert.Equal(0, settings.GetInt("level-change"));
+ }
+
[Theory]
[InlineData("Ultra_4096-4096", 0, 4096, 4096)]
[InlineData("Balanced_1024-1024", -2, 1024, 1024)]