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 X-Plane Custom Scenery page](images/custom-scenery.png) + +## 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 list while OrthoStreamXP runs: its packages are marked OrthoStreamXP and the list cannot be changed](images/custom-scenery-running.png) + +## 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 ![Setup step 5: Quality](images/setup-quality.png) -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 Home page while OrthoStreamXP runs, before X-Plane has started](images/home-running.png) + +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 + +![Scenery packages on the Home page, with OrthoStream_SA switched off](images/home-packages.png) + +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 Packages page, with Australia and the Pacific installed](images/packages.png) +![The Packages page: five regions installed, Asia's download stopped part-way](images/packages.png) 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 -![A region downloading](images/packages-downloading.png) +![Asia downloading, with its progress and speed](images/packages-downloading.png) - **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 ( ![Settings: Other](images/settings-other.png) -- **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](images/log.png) -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 @@ + + + + + + + + + + +