diff --git a/CLAUDE.md b/CLAUDE.md index aeb2a6a..bcc870a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -44,7 +44,7 @@ Source layout under `src/OrthoStreamXP/`. Sub-folders are for navigation only: * - `Aircraft/`: `AircraftPositionListener` (X-Plane UDP), `ViewTracker`, `SceneryLoads`. - `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). +- `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`; the tiles AutoOrtho lacks come from `flysimdev/orthostreamxp-scenery`'s latest-release `supplements.json` (`SupplementCatalog`, `RegionSupplement`) and are merged into their region without replacing any file, at install or, for regions installed before, by `Gui/Packages/SupplementUpdater` at each window start), `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 742c04a..62f2569 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ Traditional photo scenery often requires downloading and building large areas be - **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. - **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. +- **Clean photos up close** — X-Plane's procedural grass and dirt speckles are kept faint on the aerial photos by default, or set 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. @@ -61,7 +61,7 @@ The installer also installs the .NET 10 desktop runtime if it is missing. **Important:** OrthoStreamXP streams imagery onto scenery packages; it does not create terrain meshes itself. There are two ways to get them: -1. **Download a region from within OrthoStreamXP:** a whole region's mesh (Europe, North America, ...), during setup or later from the **Packages** page. +1. **Download a region from within OrthoStreamXP:** a whole region's mesh (Europe, North America, ...), during setup or later from the **Packages** page. The few tiles AutoOrtho's collection lacks (around Portland, Oregon, and in Tonga) are added to their region from [OrthoStreamXP's own collection](https://github.com/flysimdev/orthostreamxp-scenery). 2. **Use your own packages:** compatible packages can come from tools such as Ortho4XP, OrthoStudio XP, AutoOrtho, and XPME. You can select an existing package folder during setup. ## Installation diff --git a/docs/OrthoStreamXP-UserGuide.pdf b/docs/OrthoStreamXP-UserGuide.pdf index 261a096..62f81d9 100644 Binary files a/docs/OrthoStreamXP-UserGuide.pdf and b/docs/OrthoStreamXP-UserGuide.pdf differ diff --git a/docs/packages.md b/docs/packages.md index 8102863..fe314bf 100644 --- a/docs/packages.md +++ b/docs/packages.md @@ -19,6 +19,24 @@ The meshes are downloaded from a public collection on [GitHub](https://github.co The page shows the exact sizes of the current release. +## Tiles AutoOrtho lacks + +AutoOrtho's collection is missing a few tiles, for example 9 in Oregon, around Portland and along the coast (North America) and one in Tonga +(Australia and the Pacific). OrthoStreamXP keeps these tiles in [its own collection](https://github.com/flysimdev/orthostreamxp-scenery). +It adds them to the region they belong to, so there is no extra package: + +- **Installing a region** adds its missing tiles as part of the install. +- **A region you installed before** gets them when OrthoStreamXP starts, for example the first start after an update. + Home shows the progress in the notice **Adding the tiles AutoOrtho lacks**, then **Tiles AutoOrtho lacks were added**. + You can stream meanwhile; X-Plane then sees the new tiles from OrthoStreamXP's next start. +- **Until they are added**, the region shows **Update available** with the number of tiles, and **Update** downloads + only those (about 225 MB for North America, about 2 MB for Australia and the Pacific), even while OrthoStreamXP runs. + +The region's details on the **Packages** page list these tiles, for example *+ 9 tiles AutoOrtho lacks, from OrthoStreamXP*. + +These tiles never replace a file of AutoOrtho's. If they cannot be downloaded, the region is installed without them, and +they are added at a later start. + ## Where they go Each region is installed as a package of its own in the **scenery packages folder** chosen in [Settings › Folders](settings.md#folders). If you download one during the setup and have not chosen a folder yet, it goes to `OrthoStreamXP\Base Packages` in your user folder, and that folder becomes your scenery packages folder. @@ -56,10 +74,10 @@ A square of a downloaded mesh no longer shows X-Plane's own roads, forests and b - **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. +- When a newer release comes out, the region says **Update available**. Updating downloads it again in full. (An update that only adds the [tiles AutoOrtho lacks](#tiles-autoortho-lacks) downloads just those.) - **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. +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. Adding the tiles AutoOrtho lacks is the exception: it only adds files, so it works while OrthoStreamXP runs. Next: [X-Plane Custom Scenery](custom-scenery.md) diff --git a/docs/settings.md b/docs/settings.md index edb636f..7245a68 100644 --- a/docs/settings.md +++ b/docs/settings.md @@ -81,11 +81,11 @@ Up close, X-Plane can sprinkle its own procedural grass, shrubs and dirt over th The **Ground detail** slider sets how strong this effect is: -- **Off** (0 %, the default): the photos are shown as they are. -- **10–90 %**: a lighter version of X-Plane's effect, for some extra texture when you are low. +- **30 %** (the lowest, and the default): a faint version of X-Plane's effect; the photos stay clean and sharp. +- **40–90 %**: a stronger version of X-Plane's effect, for more texture when you are low. - **100 %**: X-Plane's full effect, as the packages define it. -Your scenery packages are not changed: OrthoStreamXP adjusts the terrain files as X-Plane reads them. The in-between strengths are made from X-Plane's own decal files, so they need the **X-Plane folder** to be set. Like every setting, a change applies from the next start. +Your scenery packages are not changed: OrthoStreamXP adjusts the terrain files as X-Plane reads them. An older settings file with a lower value (such as the former default, 0) is read as 30 %. The strengths below 100 % are made from X-Plane's own decal files, so they need the **X-Plane folder** to be set. Like every setting, a change applies from the next start. ## Folders diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index df10747..22dc493 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -22,7 +22,7 @@ When something goes wrong, Home shows a notice that says what happened, usually | **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)). | | **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). | +| **Noisy, speckled ground up close** | X-Plane's grass and dirt detail is drawn over the photos. Lower **Ground detail** (30 % is the lowest) in [Settings › Quality](settings.md#ground-detail). | ## The Log page diff --git a/release-notes/v1.5.1.md b/release-notes/v1.5.1.md new file mode 100644 index 0000000..b863f21 --- /dev/null +++ b/release-notes/v1.5.1.md @@ -0,0 +1,12 @@ +## What's new + +- **Photo scenery where AutoOrtho's mesh has gaps.** The regions on the **Packages** page come from AutoOrtho's collection, and it is missing a few tiles: 9 in Oregon, around Portland and along the coast, and one in Tonga. Until now, those places had no photo scenery. OrthoStreamXP now keeps these tiles in its own collection and adds them to **North America** and **Australia and the Pacific**. There is no extra package to install. +- **Ground detail starts at 30 %.** The **Ground detail** slider in **Settings › Quality** now goes from 30 % to 100 %, and 30 % is the default. At 30 %, X-Plane's grass and dirt pattern is faint, and the photos stay clean and sharp. **Off** is no longer a choice. + +## Good to know + +- **Already have North America or Australia and the Pacific?** The missing tiles are added by themselves when you open OrthoStreamXP after the update. A notice on **Home**, **Adding the tiles AutoOrtho lacks**, shows the progress, and **Tiles AutoOrtho lacks were added** tells you when it is done. North America downloads about 225 MB, and Australia and the Pacific about 2 MB (a little less without roads, forests and buildings). +- You can fly meanwhile. If OrthoStreamXP is streaming while the tiles are added, X-Plane sees them from the next start of OrthoStreamXP. +- If the download fails, nothing else changes, and the tiles are added at a later start. Until then, the region on the **Packages** page shows **Update available** with the number of tiles. **Update** downloads only those tiles, and it works even while OrthoStreamXP runs. +- Regions you install from now on get these tiles as part of the install. They never replace a file of AutoOrtho's, and your own scenery packages are not changed. +- **If your Ground detail was Off** (the former default), it is now 30 %. A value of 30 % or more stays as it was. Like every setting, it can be changed only while OrthoStreamXP is stopped, and applies from the next start. diff --git a/src/OrthoStreamXP/Configuration/MountSettings.cs b/src/OrthoStreamXP/Configuration/MountSettings.cs index b8d7e6a..62e7292 100644 --- a/src/OrthoStreamXP/Configuration/MountSettings.cs +++ b/src/OrthoStreamXP/Configuration/MountSettings.cs @@ -142,8 +142,10 @@ public static MountSettings FromValues(SettingValues values, bool console = true throw new SettingsException($"exposure must be between {OrthoStreamXP.Textures.Exposure.Min} and {OrthoStreamXP.Textures.Exposure.Full}"); string readLogValue = values.String("read-log") ?? "off"; bool readLog = ParseOnOff(readLogValue) ?? throw new SettingsException($"read-log must be on or off, not '{readLogValue}'"); - int groundDetail = values.Int("ground-detail", 0); + int groundDetail = values.Int("ground-detail", Scenery.TerrainDecals.Min); if (groundDetail is < 0 or > Scenery.TerrainDecals.Full) throw new SettingsException("ground-detail must be between 0 and 100"); + // Older settings files may hold a value below the minimum (0 used to be the default); it is raised to it. + groundDetail = Math.Max(groundDetail, Scenery.TerrainDecals.Min); string nightValue = values.String("night-lights") ?? "off"; bool nightLights = ParseOnOff(nightValue) ?? throw new SettingsException($"night-lights must be on or off, not '{nightValue}'"); string skipValue = values.String("skip-photos-at-night") ?? "off"; diff --git a/src/OrthoStreamXP/Configuration/SettingsOptions.cs b/src/OrthoStreamXP/Configuration/SettingsOptions.cs index 254f8d0..5504976 100644 --- a/src/OrthoStreamXP/Configuration/SettingsOptions.cs +++ b/src/OrthoStreamXP/Configuration/SettingsOptions.cs @@ -30,7 +30,7 @@ internal static class SettingsOptions .Add("filesystem-threads", $"Threads answering X-Plane's file requests, 2-512. A request waiting for a texture build keeps its thread, so this must comfortably exceed the textures X-Plane waits for at once (default: {MountSettings.DefaultFileSystemThreads})") .Add("texture-quality", "No longer used: the texture size follows level-change (accepted so older settings files still load)") .Add("background-textures", "Build missing DDS files in a bounded background queue when a local DDS fallback exists", arity: 0) - .Add("ground-detail", "How strong X-Plane's detail decals are over the photo scenery, 0-100 percent. The terrain definitions name a decal library (DECAL_LIB) that sprinkles procedural grass, shrubs and dirt over the ground up close; it adds texture to X-Plane's own blurry land-class textures, but over sharp aerial photos it looks like noise. 0 leaves the decals out, 100 keeps them as the packages define, and anything between fades them (read from the X-Plane folder, so it needs xplane). Applied to the photo tiles' terrain definitions as X-Plane reads them; the packages' files are not changed. Takes effect at the next start (default: 0)") + .Add("ground-detail", "How strong X-Plane's detail decals are over the photo scenery, 30-100 percent (a lower value is raised to 30). The terrain definitions name a decal library (DECAL_LIB) that sprinkles procedural grass, shrubs and dirt over the ground up close; it adds texture to X-Plane's own blurry land-class textures, but over sharp aerial photos it looks like noise. 100 keeps them as the packages define, and anything lower fades them (read from the X-Plane folder, so it needs xplane). Applied to the photo tiles' terrain definitions as X-Plane reads them; the packages' files are not changed. Takes effect at the next start (default: 30)") .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)") diff --git a/src/OrthoStreamXP/Gui/Packages/RegionRow.cs b/src/OrthoStreamXP/Gui/Packages/RegionRow.cs index d116041..3c99da1 100644 --- a/src/OrthoStreamXP/Gui/Packages/RegionRow.cs +++ b/src/OrthoStreamXP/Gui/Packages/RegionRow.cs @@ -39,6 +39,7 @@ public RegionRow(PackagesViewModel owner, MeshRegion region) public string Details => $"{CacheInventory.FormatBytes(Region.MeshSize)} mesh" + (Region.OverlaysSize > 0 ? $" + {CacheInventory.FormatBytes(Region.OverlaysSize)} roads, forests and buildings" : "") + + (Region.Supplement is { } supplement ? $" + {supplement.Tiles.Count} tiles AutoOrtho lacks, from OrthoStreamXP" : "") + $" · installed as {Region.PackageName}"; public InstalledRegion? Installed @@ -64,7 +65,10 @@ public long Partial public bool IsInstalled => Installed is not null; - public bool UpToDate => Installed is { } i && i.Release == Region.Release; + public bool UpToDate => Installed is { } i && i.Release == Region.Release && !i.Lacks(Region.Supplement); + + /// Installed at this release, without (all of) the tiles AutoOrtho lacks: an update only adds those. + public bool OnlyTilesLacking => Installed is { } i && i.Release == Region.Release && i.Lacks(Region.Supplement); public bool Busy { @@ -127,7 +131,9 @@ public string Status if (Installed is { } installed) return UpToDate ? $"Installed · release {installed.Release}{(installed.Overlays ? "" : ", without roads, forests and buildings")}" - : $"Update available: release {installed.Release} → {Region.Release}"; + : OnlyTilesLacking + ? $"Update available: {Region.Supplement!.Tiles.Count} tiles AutoOrtho lacks ({CacheInventory.FormatBytes(Region.Supplement.DownloadSize(installed.Overlays))})" + : $"Update available: release {installed.Release} → {Region.Release}"; return Partial > 0 ? $"Stopped with {CacheInventory.FormatBytes(Partial)} downloaded: Resume goes on from there" : "Not installed"; } } @@ -153,6 +159,7 @@ private void RaiseState() { Raise(nameof(IsInstalled)); Raise(nameof(UpToDate)); + Raise(nameof(OnlyTilesLacking)); Raise(nameof(InstallLabel)); Raise(nameof(ShowInstall)); Raise(nameof(Status)); diff --git a/src/OrthoStreamXP/Gui/Packages/SupplementUpdater.cs b/src/OrthoStreamXP/Gui/Packages/SupplementUpdater.cs new file mode 100644 index 0000000..3b7e5ca --- /dev/null +++ b/src/OrthoStreamXP/Gui/Packages/SupplementUpdater.cs @@ -0,0 +1,51 @@ +using OrthoStreamXP.Setup; + +namespace OrthoStreamXP.Gui; + +/// +/// At each start of the window, adds the tiles AutoOrtho lacks to the regions installed without them: installed by an +/// older OrthoStreamXP (the first start after an update), before the tiles were published, or while they could not be +/// downloaded. It takes the install slot like any install; when an install has it, or a download fails, the tiles are +/// added at the next start. +/// +internal sealed class SupplementUpdater(HttpClient http, SupplementCatalog catalog, InstallSlot slot, Func folder) +{ + /// The names of the regions the tiles were added to. + public async Task> RunAsync(IProgress progress, CancellationToken cancel) + { + if (folder() is not { } packages || !Directory.Exists(packages)) return []; + var installer = new RegionInstaller(new AssetDownload(http), packages); + IReadOnlyDictionary installed = installer.Installed(); + if (installed.Count == 0) return []; + IReadOnlyDictionary supplements = await catalog.LoadAsync(refresh: false, cancel).ConfigureAwait(true); + List lacking = [.. installed.Values.Where(r => r.Lacks(supplements.GetValueOrDefault(r.Id)))]; + if (lacking.Count == 0) return []; + if (!slot.TryTake()) + { + Log.Info("The tiles AutoOrtho lacks are added at the next start: another install is running"); + return []; + } + var added = new List(); + try + { + foreach (InstalledRegion region in lacking) + { + try + { + await installer.AddSupplementAsync(region.Id, supplements[region.Id], progress, cancel).ConfigureAwait(true); + added.Add(MeshRegion.NameOf(region.Id)); + } + catch (InstallException ex) + { + Log.Warning($"{ex.Message} They are added at the next start."); + } + } + } + finally + { + slot.Release(); + RelayCommand.Refresh(); + } + return added; + } +} diff --git a/src/OrthoStreamXP/Gui/ViewModels/HomeViewModel.cs b/src/OrthoStreamXP/Gui/ViewModels/HomeViewModel.cs index 1d81414..009a2a4 100644 --- a/src/OrthoStreamXP/Gui/ViewModels/HomeViewModel.cs +++ b/src/OrthoStreamXP/Gui/ViewModels/HomeViewModel.cs @@ -26,6 +26,8 @@ internal sealed class HomeViewModel : ObservableObject, IPage private System.Windows.Media.ImageSource? _reportBackdrop; private string? _reviewPath; private Notice? _tuningNotice; + private Notice? _tilesNotice; + private int _tilesPercent = -1; private readonly AppUpdates _updates = new(); /// Looks for a new version 10 seconds after the window opens, then every 6 hours. private readonly DispatcherTimer _updateTimer = new() { Interval = TimeSpan.FromSeconds(10) }; @@ -145,6 +147,29 @@ private async Task CheckForUpdatesAsync() if (message is not null) UpdateCheckReported?.Invoke(this, message); } + /// The tiles AutoOrtho lacks being added to the installed regions (as the window opens); shown at each whole percent. + public void ShowTilesProgress(InstallProgress progress) + { + int percent = progress.Total > 0 ? (int)(100 * progress.Done / progress.Total) : 0; + if (percent == _tilesPercent) return; + _tilesPercent = percent; + _tilesNotice = new Notice(Severity.Info, "Adding the tiles AutoOrtho lacks", + $"{progress.Stage}: {CacheInventory.FormatBytes(progress.Done)} of {CacheInventory.FormatBytes(progress.Total)}. " + + "You can stream meanwhile; if you do, X-Plane sees the new tiles from the next start of OrthoStreamXP."); + Notices = BuildNotices(); + } + + /// The tiles AutoOrtho lacks were added to (none: the notice goes). + public void ShowTilesAdded(IReadOnlyList regions) + { + _tilesPercent = -1; + _tilesNotice = regions.Count == 0 ? null + : new Notice(Severity.Success, "Tiles AutoOrtho lacks were added", + $"{string.Join(", ", regions)} now {(regions.Count == 1 ? "has" : "have")} the tiles missing from AutoOrtho's scenery. " + + "If OrthoStreamXP was streaming meanwhile, X-Plane sees them from its next start."); + Notices = BuildNotices(); + } + /// Installs the downloaded version and restarts, once confirmed; not while the scenery streams. public void InstallConfirmedUpdate() { @@ -622,6 +647,7 @@ private List BuildNotices() "Update…", InstallUpdate) : new Notice(Severity.Info, $"OrthoStreamXP {version} is ready to install", $"A new version was downloaded (you have {_updates.CurrentVersion}). Stop the streaming when you have finished flying, and install it from here.")); + if (_tilesNotice is not null) notices.Add(_tilesNotice); if (Mount.State == MountState.Stopped && !ShowReview) { if (_tuningNotice is not null) notices.Add(_tuningNotice); diff --git a/src/OrthoStreamXP/Gui/ViewModels/MainViewModel.cs b/src/OrthoStreamXP/Gui/ViewModels/MainViewModel.cs index 92bfece..79170ea 100644 --- a/src/OrthoStreamXP/Gui/ViewModels/MainViewModel.cs +++ b/src/OrthoStreamXP/Gui/ViewModels/MainViewModel.cs @@ -69,8 +69,7 @@ public MainViewModel() Home = new HomeViewModel(this); Settings = new SettingsViewModel(this); Cache = new CacheViewModel(this); - Packages = new PackagesViewModel(Mount, Preferences, MeshHttp, MeshInstalls, - () => SettingsDocument.Load(SettingsDocument.DefaultPath).Get("base-packages")); + Packages = new PackagesViewModel(Mount, Preferences, MeshHttp, MeshInstalls, PackagesFolder); Scenery = new SceneryViewModel(Mount, () => SettingsDocument.Load(SettingsDocument.DefaultPath).Get("xplane")); About = new AboutViewModel(); Navigation = @@ -169,11 +168,43 @@ private set public void Show(IPage page) => SelectedNav = Navigation.First(n => n.Page == page); - /// Called when the window has opened: setup on the first run, otherwise the auto-start. + /// + /// Called when the window has opened: setup on the first run, otherwise the auto-start, with the tiles AutoOrtho lacks + /// added meanwhile to the regions installed without them (they only add files, so the streaming need not wait). + /// public async Task OnOpenedAsync() { - if (NeedsSetup()) RunSetup(); - else if (Preferences.AutoStart) await Mount.StartAsync().ConfigureAwait(true); + if (NeedsSetup()) + { + RunSetup(); + return; + } + _ = AddLackingTilesAsync(); + if (Preferences.AutoStart) await Mount.StartAsync().ConfigureAwait(true); + } + + private static string? PackagesFolder() => SettingsDocument.Load(SettingsDocument.DefaultPath).Get("base-packages"); + + /// The tiles AutoOrtho lacks, added to the installed regions without them; Home shows it while it runs. + private async Task AddLackingTilesAsync() + { + var progress = new Progress(Home.ShowTilesProgress); + IReadOnlyList added = []; + try + { + var updater = new SupplementUpdater(MeshHttp, PackagesViewModel.Supplements(MeshHttp), MeshInstalls, PackagesFolder); + added = await updater.RunAsync(progress, CancellationToken.None).ConfigureAwait(true); + } + catch (Exception ex) + { + // Runs unawaited as the window opens: nothing that goes wrong may vanish, or stop the window. + Log.Error("The tiles AutoOrtho lacks could not be added; they are added at the next start", ex); + } + finally + { + Home.ShowTilesAdded(added); + Packages.FolderChanged(); + } } /// No settings file yet, or one without the folders a mount needs. diff --git a/src/OrthoStreamXP/Gui/ViewModels/PackagesViewModel.cs b/src/OrthoStreamXP/Gui/ViewModels/PackagesViewModel.cs index 2fdac3b..4608751 100644 --- a/src/OrthoStreamXP/Gui/ViewModels/PackagesViewModel.cs +++ b/src/OrthoStreamXP/Gui/ViewModels/PackagesViewModel.cs @@ -115,6 +115,9 @@ public async Task LoadAsync(bool refresh) { var catalog = new MeshCatalog(_http, Path.Join(AppPaths.Root, "mesh-regions.json")); IReadOnlyList regions = await catalog.LoadAsync(refresh, CancellationToken.None).ConfigureAwait(true); + IReadOnlyDictionary supplements = + await Supplements(_http).LoadAsync(refresh, CancellationToken.None).ConfigureAwait(true); + regions = SupplementCatalog.Attach(regions, supplements); if (_install is null) { Rows.Clear(); @@ -133,8 +136,12 @@ public async Task LoadAsync(bool refresh) } } + /// The list of the tiles AutoOrtho lacks, kept beside the settings. + public static SupplementCatalog Supplements(HttpClient http) => new(http, Path.Join(AppPaths.Root, "mesh-supplements.json")); + + /// Adding only the tiles AutoOrtho lacks adds files and replaces none, so it may run while the region is in use. public bool CanInstall(RegionRow row) => - !_slot.Busy && Folder is not null && !row.UpToDate && (!row.IsInstalled || _mount.IsStopped); + !_slot.Busy && Folder is not null && !row.UpToDate && (!row.IsInstalled || _mount.IsStopped || row.OnlyTilesLacking); public bool CanDelete(RegionRow row) => !_slot.Busy && row.IsInstalled && !row.Deleting && _mount.IsStopped; diff --git a/src/OrthoStreamXP/Gui/ViewModels/SettingsViewModel.cs b/src/OrthoStreamXP/Gui/ViewModels/SettingsViewModel.cs index 0c1e0e8..7044222 100644 --- a/src/OrthoStreamXP/Gui/ViewModels/SettingsViewModel.cs +++ b/src/OrthoStreamXP/Gui/ViewModels/SettingsViewModel.cs @@ -266,20 +266,16 @@ public double Exposure /// How strong X-Plane's grass and dirt decals are over the photos, in percent, for the slider. public double GroundDetail { - get => _document.GetDouble("ground-detail") ?? 0; + get => Math.Clamp(_document.GetDouble("ground-detail") ?? Scenery.TerrainDecals.Min, Scenery.TerrainDecals.Min, Scenery.TerrainDecals.Full); set { - Save("ground-detail", Math.Clamp((int)Math.Round(value), 0, Scenery.TerrainDecals.Full).ToString(CultureInfo.InvariantCulture)); + Save("ground-detail", Math.Clamp((int)Math.Round(value), Scenery.TerrainDecals.Min, Scenery.TerrainDecals.Full).ToString(CultureInfo.InvariantCulture)); Raise(); Raise(nameof(GroundDetailText)); } } - public string GroundDetailText => GroundDetail switch - { - <= 0 => "Off", - _ => $"{GroundDetail:0} %", - }; + public string GroundDetailText => $"{GroundDetail:0} %"; /// Street lamps and lit windows on the photo scenery at night. public bool NightLightsOn diff --git a/src/OrthoStreamXP/Gui/Views/SettingsView.xaml b/src/OrthoStreamXP/Gui/Views/SettingsView.xaml index a827de3..61b264d 100644 --- a/src/OrthoStreamXP/Gui/Views/SettingsView.xaml +++ b/src/OrthoStreamXP/Gui/Views/SettingsView.xaml @@ -193,10 +193,10 @@ + Text="Adds a grass and dirt pattern on top of the photos, seen when you are on the ground or flying low. At 30 % (the lowest, and the default) the pattern is faint and the photos stay clean and sharp. Higher values give the ground more texture up close, but make the photos look grainier. Try it if the ground looks too flat to you during taxi or landing." /> - diff --git a/src/OrthoStreamXP/Scenery/FileSystem/TerrainDecals.cs b/src/OrthoStreamXP/Scenery/FileSystem/TerrainDecals.cs index cc4f86e..9ae75c7 100644 --- a/src/OrthoStreamXP/Scenery/FileSystem/TerrainDecals.cs +++ b/src/OrthoStreamXP/Scenery/FileSystem/TerrainDecals.cs @@ -19,6 +19,8 @@ namespace OrthoStreamXP.Scenery; internal sealed class TerrainDecals { public const int Full = 100; + /// The lowest strength the ground-detail setting allows (and its default). + public const int Min = 30; /// The package folder the faded decal textures are served under (it exists only in the mount). public const string Folder = "orthostreamxp_decals"; private const string LibraryPrefix = "lib/g10/decals/"; diff --git a/src/OrthoStreamXP/Setup/Packages/MeshRegion.cs b/src/OrthoStreamXP/Setup/Packages/MeshRegion.cs index 5fe423e..46b4054 100644 --- a/src/OrthoStreamXP/Setup/Packages/MeshRegion.cs +++ b/src/OrthoStreamXP/Setup/Packages/MeshRegion.cs @@ -1,18 +1,37 @@ +using System.Text.Json.Serialization; using OrthoStreamXP.Scenery; namespace OrthoStreamXP.Setup; /// One file of a region's release: its download address, size, and the address of its SHA-256 when one is published. -internal sealed record MeshAsset(string Name, string Url, long Size, string? Sha256Url = null); +internal sealed record MeshAsset(string Name, string Url, long Size, string? Sha256Url = null) +{ + /// + /// A plain file name (never a path that leads elsewhere) and HTTPS addresses only: what a list of files, from GitHub or + /// from a copy kept on the disk, must hold before it is used for paths and downloads. + /// + public bool IsUsable => + Name.Length > 0 && Name == Path.GetFileName(Name) && Name.IndexOfAny(Path.GetInvalidFileNameChars()) < 0 && Name.Trim('.').Length > 0 + && Size >= 0 && IsHttps(Url) && (Sha256Url is null || IsHttps(Sha256Url)); + + private static bool IsHttps(string url) => Uri.TryCreate(url, UriKind.Absolute, out Uri? uri) && uri.Scheme == Uri.UriSchemeHttps; +} /// /// A region of AutoOrtho's scenery mesh (github.com/kubilus1/autoortho-scenery): the zips of its mesh, each holding one /// top folder with Earth nav data, terrain and textures, and the parts of one overlays zip (X-Plane's roads, forests and /// buildings for its squares). Installed as the package , its overlays into -/// . +/// , with the tiles AutoOrtho's release lacks () added to both. /// internal sealed record MeshRegion(string Id, string Release, IReadOnlyList Mesh, IReadOnlyList Overlays) { + /// + /// The region's tiles from OrthoStreamXP's own scenery repository, when it publishes some for this region. Not kept + /// with GitHub's list of AutoOrtho's releases: keeps its own. + /// + [JsonIgnore] + public RegionSupplement? Supplement { get; init; } + /// The package every region's overlays go into. public const string OverlaysPackageName = SceneryPacks.DownloadedPrefix + "Overlays"; @@ -41,6 +60,6 @@ internal sealed record MeshRegion(string Id, string Release, IReadOnlyList Overlays.Sum(a => a.Size); - /// What an install downloads, with or without the overlays. - public long DownloadSize(bool withOverlays) => MeshSize + (withOverlays ? OverlaysSize : 0); + /// What an install downloads, with or without the overlays, the supplement's tiles included. + public long DownloadSize(bool withOverlays) => MeshSize + (withOverlays ? OverlaysSize : 0) + (Supplement?.DownloadSize(withOverlays) ?? 0); } diff --git a/src/OrthoStreamXP/Setup/Packages/OverlayPackage.cs b/src/OrthoStreamXP/Setup/Packages/OverlayPackage.cs index 16141d0..32993e3 100644 --- a/src/OrthoStreamXP/Setup/Packages/OverlayPackage.cs +++ b/src/OrthoStreamXP/Setup/Packages/OverlayPackage.cs @@ -39,6 +39,36 @@ public void Add(string regionId, string staging, IReadOnlyList files) Save(record); } + /// + /// Moves more files of a region (the tiles AutoOrtho lacks) from into the package, beside + /// those it placed already. A file any region placed is kept, unless it is this region's and one of + /// (placed by an earlier version of the same tiles). A file no region placed is taken + /// over: one left by an earlier try that stopped before its record was saved. + /// + /// The files placed (added or replaced). + public IReadOnlyList Append(string regionId, string staging, IReadOnlyList files, IReadOnlySet replaceable) + { + Dictionary> record = Load(); + var owner = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var (region, owned) in record) + foreach (string file in owned) + owner[file] = region; + var placed = new List(); + foreach (string file in files) + { + if (owner.TryGetValue(file, out string? other) && !(other == regionId && replaceable.Contains(file))) continue; + string target = Path.Join(Folder, file); + Directory.CreateDirectory(Path.GetDirectoryName(target)!); + File.Move(Path.Join(staging, file), target, overwrite: true); + placed.Add(file); + } + List added = [.. placed.Where(f => !owner.ContainsKey(f))]; + if (added.Count == 0) return placed; + record[regionId] = [.. record.GetValueOrDefault(regionId) ?? [], .. added]; + Save(record); + return placed; + } + /// Deletes the files a region placed; the package goes with its last region. public void Remove(string regionId) { diff --git a/src/OrthoStreamXP/Setup/Packages/RegionInstaller.cs b/src/OrthoStreamXP/Setup/Packages/RegionInstaller.cs index 565073c..560dacf 100644 --- a/src/OrthoStreamXP/Setup/Packages/RegionInstaller.cs +++ b/src/OrthoStreamXP/Setup/Packages/RegionInstaller.cs @@ -1,11 +1,22 @@ +using System.Globalization; using System.Runtime.ExceptionServices; using System.Text.Json; using OrthoStreamXP.Scenery; namespace OrthoStreamXP.Setup; -/// A region installed in the packages folder: its release, and whether its overlays came with it. -internal sealed record InstalledRegion(string Id, string Release, bool Overlays, DateTime InstalledUtc); +/// +/// A region installed in the packages folder: its release, whether its overlays came with it, and the version of the tiles +/// AutoOrtho lacks added to it (null: none, as before OrthoStreamXP published any). +/// +/// The files the tiles placed in the region's package, relative: a newer version may replace them, never another. +/// The same in the shared overlays package. +internal sealed record InstalledRegion(string Id, string Release, bool Overlays, DateTime InstalledUtc, int? Supplement = null, + IReadOnlyList? SupplementFiles = null, IReadOnlyList? SupplementOverlayFiles = null) +{ + /// The region has not got all of yet (an older version of it, or none). + public bool Lacks(RegionSupplement? supplement) => supplement is not null && (Supplement ?? 0) < supplement.Version; +} /// How far an install is: what it does now, and the bytes downloaded of all it downloads. internal sealed record InstallProgress(string Stage, long Done, long Total); @@ -22,6 +33,11 @@ internal sealed class InstallException(string message, Exception? inner = null) /// where it was. The region takes its place only once all of it is there, with its marker written last, so X-Plane never /// sees half a region. An update is prepared the same way and swapped in at the end. /// +/// +/// The tiles AutoOrtho's release lacks () are added to the prepared region before it takes +/// its place, never over a file of AutoOrtho's; when they cannot be had, the region is installed without them and they are +/// added later (). +/// /// internal sealed class RegionInstaller(AssetDownload download, string packagesFolder) { @@ -30,8 +46,15 @@ internal sealed class RegionInstaller(AssetDownload download, string packagesFol /// Unpacked, a region takes about this much more than its zips (DSFs grow, each small .ter takes a whole disk block). private const double UnpackedRatio = 1.7; private const long SpareBytes = 2L << 30; + /// The work folder of tiles added to an installed region: beside the region's own, which an install clears. + private const string SupplementWorkSuffix = ".supplement"; - private sealed record State(List Unpacked, List? OverlayFiles); + /// The version of the supplement whose mesh is added to the prepared region. + /// The version of the supplement whose overlays are in . + /// The mesh files a supplement placed (or is placing) in the prepared region. + /// Those of a supplement placed (or is placing). + private sealed record State(List Unpacked, List? OverlayFiles, int? SupplementMesh = null, int? SupplementOverlays = null, + List? SupplementMeshFiles = null, List? SupplementOverlayFiles = null); public string PackagesFolder { get; } = packagesFolder; @@ -70,17 +93,32 @@ public long AlreadyDone(MeshRegion region, bool withOverlays) if (withOverlays && state.OverlayFiles is not null) done += region.OverlaysSize; foreach (MeshAsset asset in Pending(region, withOverlays, state)) done += Math.Min(asset.Size, Length(Path.Join(work, "zips", asset.Name))); + if (region.Supplement is { } supplement) + { + done += state.SupplementMesh == supplement.Version ? supplement.Mesh.Size : Math.Min(supplement.Mesh.Size, Length(Path.Join(work, "zips", supplement.Mesh.Name))); + if (withOverlays && supplement.Overlays is { } overlays) + done += state.SupplementOverlays == supplement.Version ? overlays.Size : Math.Min(overlays.Size, Length(Path.Join(work, "zips", overlays.Name))); + } return done; } - /// Installs or updates ; a stop leaves what was downloaded for the next time. + /// + /// Installs or updates ; a stop leaves what was downloaded for the next time. A region installed + /// at this release that only lacks its supplement's tiles gets those alone (). + /// /// Not enough disk space, a download that failed, or a damaged zip. public async Task InstallAsync(MeshRegion region, bool withOverlays, IProgress progress, CancellationToken cancel) { CheckRegion(region); MoveOldNames(); + if (region.Supplement is { } lacking && Installed().GetValueOrDefault(region.Id) is { } installed + && installed.Release == region.Release && installed.Lacks(lacking)) + { + await AddSupplementAsync(region.Id, lacking, progress, cancel).ConfigureAwait(false); + return; + } string work = WorkOf(region); - PrepareWork(region, work); + PrepareWork(work); State state = LoadState(work); long total = region.DownloadSize(withOverlays); long done = AlreadyDone(region, withOverlays); @@ -171,12 +209,179 @@ await Task.Run(() => throw new InstallException($"The {region.Name} mesh could not be installed: {ex.Message}", ex); } + int? supplement = null; + if (region.Supplement is { } tiles) + { + progress.Report(new InstallProgress($"Downloading the tiles AutoOrtho lacks for {region.Name}", done, total)); + (state, supplement) = await AddSupplementToWorkAsync(region, tiles, withOverlays, work, state, Downloaded, cancel).ConfigureAwait(false); + } + cancel.ThrowIfCancellationRequested(); // a Stop just before the end: nothing is put in place progress.Report(new InstallProgress($"Putting the {region.Name} mesh in place", total, total)); - PutInPlace(region, work, withOverlays ? state.OverlayFiles : null); - Log.Info($"The {region.Name} mesh is installed as {region.PackageName}{(withOverlays ? $", its overlays in {MeshRegion.OverlaysPackageName}" : "")}"); + PutInPlace(region, work, withOverlays ? state.OverlayFiles : null, + new InstalledRegion(region.Id, region.Release, withOverlays && state.OverlayFiles is not null, DateTime.UtcNow, supplement, + state.SupplementMeshFiles, withOverlays ? state.SupplementOverlayFiles : null)); + Log.Info($"The {region.Name} mesh is installed as {region.PackageName}{(withOverlays ? $", its overlays in {MeshRegion.OverlaysPackageName}" : "")}" + + (supplement is null ? "" : $", with the {region.Supplement!.Tiles.Count} tiles AutoOrtho lacks")); + } + + /// + /// Adds the tiles AutoOrtho lacks to the region prepared in , never over a file of AutoOrtho's + /// (one a supplement placed is replaced by a newer one). Each half, mesh and overlays, is recorded as done once added, + /// and its files before they move, so a stopped install finishes it next time. When the tiles cannot be had the region + /// is installed without them: that is logged, and they are added later. + /// + /// The state, and the supplement's version once all of it is added (null when it failed). + private async Task<(State State, int? Version)> AddSupplementToWorkAsync(MeshRegion region, RegionSupplement supplement, bool withOverlays, + string work, State state, Action downloaded, CancellationToken cancel) + { + string staging = Path.Join(work, "supplement"); + try + { + if (state.SupplementMesh != supplement.Version) + { + string from = Path.Join(staging, "mesh"), to = Path.Join(work, "mesh"); + IReadOnlyList files = await DownloadAndUnpackAsync(supplement.Mesh, work, from, downloaded, cancel).ConfigureAwait(false); + HashSet ours = Set(state.SupplementMeshFiles); + List placing = Placeable(files, to, ours); + state = state with { SupplementMeshFiles = [.. ours.Union(placing, StringComparer.OrdinalIgnoreCase)] }; + SaveState(work, state); + MoveAll(from, placing, to); + state = state with { SupplementMesh = supplement.Version }; + SaveState(work, state); + } + if (withOverlays && state.OverlayFiles is { } overlayFiles && supplement.Overlays is { } overlays && state.SupplementOverlays != supplement.Version) + { + string from = Path.Join(staging, "overlays"), to = Path.Join(work, "overlays"); + IReadOnlyList files = await DownloadAndUnpackAsync(overlays, work, from, downloaded, cancel).ConfigureAwait(false); + HashSet ours = Set(state.SupplementOverlayFiles); + var autoOrtho = new HashSet(overlayFiles.Where(f => !ours.Contains(f)), StringComparer.OrdinalIgnoreCase); + List placing = [.. files.Where(f => !autoOrtho.Contains(f))]; + List oursNow = [.. ours.Union(placing, StringComparer.OrdinalIgnoreCase)]; + state = state with { OverlayFiles = [.. autoOrtho, .. oursNow], SupplementOverlayFiles = oursNow }; + SaveState(work, state); + MoveAll(from, placing, to); + state = state with { SupplementOverlays = supplement.Version }; + SaveState(work, state); + } + if (Directory.Exists(staging)) Directory.Delete(staging, recursive: true); + bool overlaysDone = !withOverlays || state.OverlayFiles is null || supplement.Overlays is null || state.SupplementOverlays == supplement.Version; + return (state, state.SupplementMesh == supplement.Version && overlaysDone ? supplement.Version : null); + } + catch (Exception ex) when (ex is IOException or InvalidDataException or HttpRequestException or UnauthorizedAccessException) + { + Log.Warning($"The tiles AutoOrtho lacks could not be added to the {region.Name} mesh ({ex.Message}); it is installed without them, and they are added later"); + // The overlays recorded before they moved, some perhaps not there: the region takes only those that are. + string overlaysFolder = Path.Join(work, "overlays"); + bool There(string file) => File.Exists(Path.Join(overlaysFolder, file)); + return (state with + { + OverlayFiles = state.OverlayFiles is { } all ? [.. all.Where(There)] : null, + SupplementOverlayFiles = state.SupplementOverlayFiles is { } ours ? [.. ours.Where(There)] : null, + }, null); + } } + /// + /// Adds the tiles AutoOrtho lacks to an installed region that has not got them (installed before they were published, + /// or by an older OrthoStreamXP), or a newer version of them: the mesh into its package, the overlays into the shared + /// one when the region has its overlays. A file the region has is kept unless an earlier supplement placed it, so + /// AutoOrtho's stay; files are mostly added, so this may run while X-Plane uses the region, which sees the new tiles from + /// its next start. A stop leaves what was downloaded for the next time. + /// + /// The region is not installed, not enough disk space, a download that failed, or a damaged zip. + public async Task AddSupplementAsync(string regionId, RegionSupplement supplement, IProgress progress, CancellationToken cancel) + { + CheckSupplement(regionId, supplement, []); + MoveOldNames(); + string name = MeshRegion.NameOf(regionId); + if (Installed().GetValueOrDefault(regionId) is not { } installed) + throw new InstallException($"The {name} mesh is not installed: the tiles AutoOrtho lacks are added with it."); + string package = Path.Join(PackagesFolder, MeshRegion.PackageOf(regionId)); + string work = Path.Join(WorkRoot, regionId + SupplementWorkSuffix, supplement.Version.ToString(CultureInfo.InvariantCulture)); + PrepareWork(work); + bool withOverlays = installed.Overlays && supplement.Overlays is not null; + long total = supplement.DownloadSize(withOverlays); + long done = supplement.Assets(withOverlays).Sum(a => Math.Min(a.Size, Length(Path.Join(work, "zips", a.Name)))); + CheckSpace(total - done, 0); + Log.Info($"Adding the {supplement.Tiles.Count} tiles AutoOrtho lacks (version {supplement.Version}) to the {name} mesh in {PackagesFolder}"); + void Downloaded(long bytes) + { + done += bytes; + progress.Report(new InstallProgress($"Downloading the tiles AutoOrtho lacks for {name}", done, total)); + } + + string marker = Path.Join(package, MarkerName); + int mesh, overlays = 0; + try + { + string staging = Path.Join(work, "mesh"); + IReadOnlyList files = await DownloadAndUnpackAsync(supplement.Mesh, work, staging, Downloaded, cancel).ConfigureAwait(false); + HashSet ours = Set(installed.SupplementFiles); + List placing = Placeable(files, package, ours); + // Recorded as the supplement's before they move: a stop in the middle replaces them next time, as its own. + installed = installed with { SupplementFiles = [.. ours.Union(placing, StringComparer.OrdinalIgnoreCase)] }; + AtomicFile.Write(marker, JsonSerializer.SerializeToUtf8Bytes(installed)); + MoveAll(staging, placing, package); + mesh = placing.Count; + if (withOverlays) + { + string overlayStaging = Path.Join(work, "overlays"); + files = await DownloadAndUnpackAsync(supplement.Overlays!, work, overlayStaging, Downloaded, cancel).ConfigureAwait(false); + HashSet oursOverlays = Set(installed.SupplementOverlayFiles); + IReadOnlyList placed = Overlays.Append(regionId, overlayStaging, files, oursOverlays); + installed = installed with { SupplementOverlayFiles = [.. oursOverlays.Union(placed, StringComparer.OrdinalIgnoreCase)] }; + overlays = placed.Count; + } + } + catch (Exception ex) when (ex is IOException or InvalidDataException or HttpRequestException or UnauthorizedAccessException) + { + throw new InstallException($"The tiles AutoOrtho lacks could not be added to the {name} mesh: {ex.Message}", ex); + } + + // The version last: a stop before it adds the tiles again next time, over what is there. + AtomicFile.Write(marker, JsonSerializer.SerializeToUtf8Bytes(installed with { Supplement = supplement.Version })); + Directory.Delete(work, recursive: true); + DeleteIfEmpty(Path.GetDirectoryName(work)!); + DeleteIfEmpty(WorkRoot); + Log.Info($"The tiles AutoOrtho lacks are added to the {name} mesh: {mesh} files of mesh, {overlays} of overlays " + + "(AutoOrtho's files were kept)"); + } + + /// Downloads a zip into the work folder, unpacks it into and deletes it; returns its files, relative. + private async Task> DownloadAndUnpackAsync(MeshAsset asset, string work, string destination, Action downloaded, CancellationToken cancel) + { + string zip = Path.Join(work, "zips", asset.Name); + await download.GetAsync(asset, zip, downloaded, cancel).ConfigureAwait(false); + IReadOnlyList files = await Task.Run(() => + { + using FileStream file = File.OpenRead(zip); + return ZipUnpacker.Unpack(file, destination, cancel); + }, cancel).ConfigureAwait(false); + File.Delete(zip); + return files; + } + + /// + /// The supplement's files that may go into : those not there yet, and those a supplement put + /// there before (), which a newer one replaces. Any other file there is AutoOrtho's and stays. + /// + private static List Placeable(IEnumerable files, string folder, HashSet ours) => + [.. files.Where(f => ours.Contains(f) || !File.Exists(Path.Join(folder, f)))]; + + /// Moves (relative) from to the same places under . + private static void MoveAll(string from, IEnumerable files, string to) + { + foreach (string file in files) + { + string target = Path.Join(to, file); + Directory.CreateDirectory(Path.GetDirectoryName(target)!); + File.Move(Path.Join(from, file), target, overwrite: true); + } + } + + private static HashSet Set(IEnumerable? files) => new(files ?? [], StringComparer.OrdinalIgnoreCase); + /// The downloaded parts of the overlays zip, unpacked as the one zip they make; returns the files, relative. private static Task> UnpackPartsAsync(IReadOnlyList parts, string destination, CancellationToken cancel) => Task.Run(() => @@ -213,7 +418,7 @@ public void Delete(string regionId) Log.Info($"The {MeshRegion.NameOf(regionId)} mesh was deleted from {PackagesFolder}"); } - private void PutInPlace(MeshRegion region, string work, IReadOnlyList? overlayFiles) + private void PutInPlace(MeshRegion region, string work, IReadOnlyList? overlayFiles, InstalledRegion marker) { string package = Path.Join(PackagesFolder, region.PackageName); string mesh = Path.Join(work, "mesh"); @@ -228,7 +433,6 @@ private void PutInPlace(MeshRegion region, string work, IReadOnlyList? o if (Directory.Exists(old) && !Directory.Exists(package)) Directory.Move(old, package); throw new InstallException($"The {region.Name} mesh could not be put in place: {ex.Message}", ex); } - var marker = new InstalledRegion(region.Id, region.Release, overlayFiles is not null, DateTime.UtcNow); AtomicFile.Write(Path.Join(package, MarkerName), JsonSerializer.SerializeToUtf8Bytes(marker)); OverlayPackage overlays = Overlays; @@ -257,8 +461,8 @@ private static void DeleteIfEmpty(string folder) if (Directory.Exists(folder) && !Directory.EnumerateFileSystemEntries(folder).Any()) Directory.Delete(folder); } - /// The region's work folder; one left by another release of it is deleted (a new release starts afresh). - private void PrepareWork(MeshRegion region, string work) + /// The work folder; one beside it, left by another release or version, is deleted (a new one starts afresh). + private void PrepareWork(string work) { string regionWork = Path.GetDirectoryName(work)!; if (Directory.Exists(regionWork)) @@ -277,15 +481,23 @@ private static void CheckRegion(MeshRegion region) { if (!MeshRegion.IsKnown(region.Id)) throw new InstallException($"'{region.Id}' is not a region OrthoStreamXP knows."); foreach (MeshAsset asset in region.Mesh.Concat(region.Overlays)) - { - bool plainName = asset.Name.Length > 0 && asset.Name == Path.GetFileName(asset.Name) - && asset.Name.IndexOfAny(Path.GetInvalidFileNameChars()) < 0 && asset.Name.Trim('.').Length > 0; - if (!plainName || !IsHttps(asset.Url) || (asset.Sha256Url is { } sha && !IsHttps(sha))) + if (!asset.IsUsable) throw new InstallException($"The list of the {region.Name} mesh's files has an entry that cannot be used ({asset.Name}). Press Refresh, then try again."); - } + if (region.Supplement is { } supplement) + CheckSupplement(region.Id, supplement, [.. region.Mesh.Concat(region.Overlays).Select(a => a.Name)]); } - private static bool IsHttps(string url) => Uri.TryCreate(url, UriKind.Absolute, out Uri? uri) && uri.Scheme == Uri.UriSchemeHttps; + /// + /// The same for the tiles AutoOrtho lacks, whose files also share the work folder's zips with AutoOrtho's + /// (): a name of theirs is refused. + /// + private static void CheckSupplement(string regionId, RegionSupplement supplement, IReadOnlyCollection otherNames) + { + if (!MeshRegion.IsKnown(regionId)) throw new InstallException($"'{regionId}' is not a region OrthoStreamXP knows."); + foreach (MeshAsset asset in supplement.Assets(withOverlays: true)) + if (!asset.IsUsable || otherNames.Contains(asset.Name, StringComparer.OrdinalIgnoreCase)) + throw new InstallException($"The list of the tiles AutoOrtho lacks for the {MeshRegion.NameOf(regionId)} mesh has an entry that cannot be used ({asset.Name}). Press Refresh, then try again."); + } /// What is left to download. /// A zip that may be on the disk beside the one being unpacked. diff --git a/src/OrthoStreamXP/Setup/Packages/RegionSupplement.cs b/src/OrthoStreamXP/Setup/Packages/RegionSupplement.cs new file mode 100644 index 0000000..efed1a2 --- /dev/null +++ b/src/OrthoStreamXP/Setup/Packages/RegionSupplement.cs @@ -0,0 +1,18 @@ +namespace OrthoStreamXP.Setup; + +/// +/// Tiles of a region that AutoOrtho's release lacks, published by OrthoStreamXP's own scenery repository +/// (): one zip of mesh (Earth nav data and the tiles' sea masks) and one of +/// overlays, added to the region's package and to the shared overlays package. A file already there is never replaced, so +/// AutoOrtho's own files win, and a tile AutoOrtho's release gains later is AutoOrtho's. +/// +/// Goes up whenever the region's files in the repository change; an installed region records the one it has. +/// The tiles, as their DSFs are named (+44-122). +internal sealed record RegionSupplement(int Version, IReadOnlyList Tiles, MeshAsset Mesh, MeshAsset? Overlays) +{ + /// What adding the tiles downloads, with or without their overlays. + public long DownloadSize(bool withOverlays) => Mesh.Size + (withOverlays && Overlays is not null ? Overlays.Size : 0); + + /// The files adding the tiles downloads. + public IEnumerable Assets(bool withOverlays) => withOverlays && Overlays is not null ? [Mesh, Overlays] : [Mesh]; +} diff --git a/src/OrthoStreamXP/Setup/Packages/SupplementCatalog.cs b/src/OrthoStreamXP/Setup/Packages/SupplementCatalog.cs new file mode 100644 index 0000000..cc44e36 --- /dev/null +++ b/src/OrthoStreamXP/Setup/Packages/SupplementCatalog.cs @@ -0,0 +1,124 @@ +using System.Text.Json; + +namespace OrthoStreamXP.Setup; + +/// +/// The tiles AutoOrtho's releases lack, by region: supplements.json of the newest release of OrthoStreamXP's own +/// scenery repository, read from its download address (no GitHub API call, so no hourly limit). The list is kept beside +/// the settings and asked for again at most every hour. It is never needed: when it cannot be read and none was kept, the +/// regions come without supplements and are installed as AutoOrtho publishes them. +/// +internal sealed class SupplementCatalog(HttpClient http, string cacheFile) +{ + public const string Repository = "flysimdev/orthostreamxp-scenery"; + public const string ProjectPage = "https://github.com/" + Repository; + public const string ManifestUrl = ProjectPage + "/releases/latest/download/supplements.json"; + /// The manifest's format this version reads; a newer one is left alone until the program is updated. + public const int Schema = 1; + private static readonly TimeSpan MaxAge = TimeSpan.FromHours(1), RequestTimeout = TimeSpan.FromSeconds(30); + + /// The supplements by region id: from the list kept when it is recent (unless ), else from GitHub. + public async Task> LoadAsync(bool refresh, CancellationToken cancel) + { + bool fresh = !refresh && File.Exists(cacheFile) && DateTime.UtcNow - File.GetLastWriteTimeUtc(cacheFile) < MaxAge; + if (fresh && ReadCache() is { } kept) return kept; + try + { + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancel); + timeout.CancelAfter(RequestTimeout); + using HttpResponseMessage response = await http.GetAsync(new Uri(ManifestUrl), timeout.Token).ConfigureAwait(false); + response.EnsureSuccessStatusCode(); + string json = await response.Content.ReadAsStringAsync(timeout.Token).ConfigureAwait(false); + IReadOnlyDictionary supplements = Parse(json); + WriteCache(json); + return supplements; + } + catch (Exception ex) when (ex is HttpRequestException or JsonException or IOException or OperationCanceledException && !cancel.IsCancellationRequested) + { + IReadOnlyDictionary? older = ReadCache(); + Log.Info($"The list of tiles AutoOrtho lacks could not be read from {Repository} ({ex.Message}); " + + (older is null ? "the regions are installed as AutoOrtho publishes them" : "the list kept from before is used")); + return older ?? new Dictionary(); + } + } + + /// The regions with their supplements attached (a region without one is left as it is). + public static IReadOnlyList Attach(IReadOnlyList regions, IReadOnlyDictionary supplements) => + [.. regions.Select(r => supplements.TryGetValue(r.Id, out RegionSupplement? s) ? r with { Supplement = s } : r)]; + + /// + /// The regions of a manifest. A region the program does not know, or an entry that cannot be used (a file name that is + /// a path, an address that is not HTTPS, a version below 1), is left out and logged; a manifest of another + /// gives none. + /// + /// The text is not JSON. + internal static IReadOnlyDictionary Parse(string json) + { + using JsonDocument doc = JsonDocument.Parse(json); + var found = new Dictionary(); + JsonElement root = doc.RootElement; + if (root.ValueKind != JsonValueKind.Object || !root.TryGetProperty("schema", out JsonElement schema) + || schema.ValueKind != JsonValueKind.Number || schema.GetInt32() != Schema) + { + Log.Info("The list of tiles AutoOrtho lacks is in a format this version does not read; update OrthoStreamXP to use it"); + return found; + } + if (!root.TryGetProperty("regions", out JsonElement regions) || regions.ValueKind != JsonValueKind.Object) return found; + foreach (JsonProperty entry in regions.EnumerateObject()) + { + RegionSupplement? supplement = null; + try + { + supplement = Region(entry.Value); + } + catch (Exception ex) when (ex is InvalidOperationException or FormatException or KeyNotFoundException) + { + // A value of the wrong kind: the entry is left out below. + } + if (MeshRegion.IsKnown(entry.Name) && supplement is not null) found[entry.Name] = supplement; + else Log.Warning($"The tiles AutoOrtho lacks for '{entry.Name}' are left out: the entry cannot be used"); + } + return found; + } + + private static RegionSupplement? Region(JsonElement e) + { + int version = e.GetProperty("version").GetInt32(); + string[] tiles = [.. e.GetProperty("tiles").EnumerateArray().Select(t => t.GetString() ?? "")]; + MeshAsset mesh = Asset(e.GetProperty("mesh")); + MeshAsset? overlays = e.TryGetProperty("overlays", out JsonElement o) && o.ValueKind == JsonValueKind.Object ? Asset(o) : null; + bool usable = version >= 1 && tiles.Length > 0 && mesh.IsUsable && overlays?.IsUsable != false; + return usable ? new RegionSupplement(version, tiles, mesh, overlays) : null; + } + + private static MeshAsset Asset(JsonElement e) => new( + e.GetProperty("name").GetString() ?? "", + e.GetProperty("url").GetString() ?? "", + e.GetProperty("size").GetInt64(), + e.TryGetProperty("sha256Url", out JsonElement sha) && sha.ValueKind == JsonValueKind.String ? sha.GetString() : null); + + private IReadOnlyDictionary? ReadCache() + { + try + { + return File.Exists(cacheFile) ? Parse(File.ReadAllText(cacheFile)) : null; + } + catch (Exception ex) when (ex is IOException or JsonException or UnauthorizedAccessException) + { + return null; + } + } + + private void WriteCache(string json) + { + try + { + Directory.CreateDirectory(Path.GetDirectoryName(cacheFile)!); + AtomicFile.Write(cacheFile, System.Text.Encoding.UTF8.GetBytes(json)); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Log.Warning($"Could not keep the list of tiles AutoOrtho lacks: {ex.Message}"); + } + } +} diff --git a/src/OrthoStreamXP/orthostreamxp.example.ini b/src/OrthoStreamXP/orthostreamxp.example.ini index 44a82ba..d9a9285 100644 --- a/src/OrthoStreamXP/orthostreamxp.example.ini +++ b/src/OrthoStreamXP/orthostreamxp.example.ini @@ -66,11 +66,11 @@ build-tiles = 32768 provisional-lod = 0 provisional-wait = 2 lazy-terrain-listing = true -# 0-100: how strong X-Plane's detail decals are on the photos. The packages' terrain definitions name a decal library +# 30-100: how strong X-Plane's detail decals are on the photos. The packages' terrain definitions name a decal library # that sprinkles procedural grass and dirt over the ground up close. It suits X-Plane's own land-class textures but -# looks like noise on aerial photos: 0 leaves it out, 100 keeps it as the packages define, between fades it. +# looks like noise on aerial photos: 100 keeps it as the packages define, lower fades it (below 30 is raised to 30). # The packages' files are not changed -ground-detail = 0 +ground-detail = 30 # light the towns on the photo tiles at night: street lamps and lit windows along X-Plane's roads, read from the # overlay packages, painted once per tile and kept in the cache (on or off) night-lights = off diff --git a/tests/OrthoStreamXP.Tests/MeshPackagesTests.cs b/tests/OrthoStreamXP.Tests/MeshPackagesTests.cs index a6c2a6a..edc3d08 100644 --- a/tests/OrthoStreamXP.Tests/MeshPackagesTests.cs +++ b/tests/OrthoStreamXP.Tests/MeshPackagesTests.cs @@ -371,8 +371,253 @@ public void The_parts_of_a_split_zip_read_as_one_stream() Assert.Equal('h', (char)stream.ReadByte()); } + // ---------------------------------------------------------------- the tiles AutoOrtho lacks + + [Fact] + public void The_supplements_list_keeps_the_usable_entries_of_known_regions() + { + string json = """ + { "schema": 1, "tag": "v3", "regions": { + "na": { "version": 2, "tiles": ["+44-122", "+45-123"], "contentHash": "ab12", + "mesh": { "name": "z_na_supplement.zip", "url": "https://x.test/z_na_supplement.zip", "size": 100, + "sha256Url": "https://x.test/z_na_supplement.zip.sha256" }, + "overlays": { "name": "y_na_supplement_overlays.zip", "url": "https://x.test/y.zip", "size": 10 } }, + "aus_pac": { "version": 1, "tiles": ["-19-174"], "mesh": { "name": "z.zip", "url": "https://x.test/z.zip", "size": 5 } }, + "mars": { "version": 1, "tiles": ["+00+000"], "mesh": { "name": "z.zip", "url": "https://x.test/z.zip", "size": 5 } }, + "eur": { "version": 1, "tiles": ["+45+005"], "mesh": { "name": "..\\evil.zip", "url": "https://x.test/z.zip", "size": 5 } }, + "afr": { "version": 1, "tiles": ["+30+000"], "mesh": { "name": "z.zip", "url": "http://x.test/z.zip", "size": 5 } }, + "sa": { "version": 0, "tiles": ["-30-060"], "mesh": { "name": "z.zip", "url": "https://x.test/z.zip", "size": 5 } }, + "asi": { "version": "one", "tiles": [], "mesh": {} } + } } + """; + + IReadOnlyDictionary supplements = SupplementCatalog.Parse(json); + + Assert.Equal(["aus_pac", "na"], supplements.Keys.Order(StringComparer.Ordinal)); + RegionSupplement na = supplements["na"]; + Assert.Equal((2, 2, 110L), (na.Version, na.Tiles.Count, na.DownloadSize(withOverlays: true))); + Assert.Equal("https://x.test/z_na_supplement.zip.sha256", na.Mesh.Sha256Url); + Assert.Null(supplements["aus_pac"].Overlays); + } + + [Fact] + public void A_supplements_list_of_another_format_gives_none() + { + Assert.Empty(SupplementCatalog.Parse("""{ "schema": 2, "regions": { "na": {} } }""")); + Assert.ThrowsAny(() => SupplementCatalog.Parse("not json")); + } + + [Fact] + public async Task The_tiles_AutoOrtho_lacks_come_with_a_new_install_and_never_replace_its_files() + { + // Another region's overlays keep the shared package when North America is deleted: what it placed is seen to go. + await Installer().InstallAsync(Region("eur", "1", [Zip(("z_eur_00/Earth nav data/+40+000/+45+005.dsf", "eur"))], + Zip(("y/Earth nav data/+40+000/+45+005.dsf", "eur overlay"))), true, NoProgress, CancellationToken.None); + MeshRegion na = Region("na", "1", + [Zip(("z_na_00/Earth nav data/+40-130/+43-124.dsf", "AO dsf"), ("z_na_00/textures/23040_10192_ZL16.png", "AO mask"))], + Zip(("y/Earth nav data/+40-130/+43-124.dsf", "AO overlay"))) with + { + Supplement = Supplement("na", 1, + Zip(("z_na_supplement/Earth nav data/+40-130/+44-124.dsf", "our dsf"), + ("z_na_supplement/Earth nav data/+40-130/+43-124.dsf", "our copy of AO's tile"), + ("z_na_supplement/textures/23040_10192_ZL16.png", "our mask"), + ("z_na_supplement/textures/23040_10160_ZL16.png", "new mask")), + Zip(("y_na_supplement_overlays/Earth nav data/+40-130/+44-124.dsf", "our overlay"), + ("y_na_supplement_overlays/Earth nav data/+40-130/+43-124.dsf", "our copy of AO's overlay"))), + }; + + await Installer().InstallAsync(na, withOverlays: true, NoProgress, CancellationToken.None); + + string mesh = Path.Join(Packages, "OrthoStream_NA"); + string overlays = Path.Join(Packages, "OrthoStream_Overlays", "Earth nav data", "+40-130"); + Assert.Equal("our dsf", File.ReadAllText(Path.Join(mesh, "Earth nav data", "+40-130", "+44-124.dsf"))); + Assert.Equal("AO dsf", File.ReadAllText(Path.Join(mesh, "Earth nav data", "+40-130", "+43-124.dsf"))); + Assert.Equal("AO mask", File.ReadAllText(Path.Join(mesh, "textures", "23040_10192_ZL16.png"))); + Assert.Equal("new mask", File.ReadAllText(Path.Join(mesh, "textures", "23040_10160_ZL16.png"))); + Assert.Equal("our overlay", File.ReadAllText(Path.Join(overlays, "+44-124.dsf"))); + Assert.Equal("AO overlay", File.ReadAllText(Path.Join(overlays, "+43-124.dsf"))); + Assert.Equal(1, Installer().Installed()["na"].Supplement); + Assert.False(Directory.Exists(Path.Join(Packages, RegionInstaller.WorkFolderName))); + + Installer().Delete("na"); + + Assert.False(Directory.Exists(overlays)); // the supplement's overlays were recorded as North America's + Assert.True(File.Exists(Path.Join(Packages, "OrthoStream_Overlays", "Earth nav data", "+40+000", "+45+005.dsf"))); + } + + [Fact] + public async Task A_region_whose_supplement_cannot_be_had_is_installed_without_it_and_gets_it_later() + { + byte[] aoZip = Zip(("z_na_00/Earth nav data/+40-130/+43-124.dsf", "AO dsf")); + MeshRegion na = Region("na", "1", [aoZip]) with + { + // Not on the server: its download fails. + Supplement = new RegionSupplement(1, ["+44-124"], new MeshAsset("z_na_supplement.zip", Host + "z_na_supplement.zip", 50), null), + }; + + await Installer().InstallAsync(na, withOverlays: true, NoProgress, CancellationToken.None); + + InstalledRegion installed = Installer().Installed()["na"]; + Assert.Null(installed.Supplement); + Assert.True(File.Exists(Path.Join(Packages, "OrthoStream_NA", "Earth nav data", "+40-130", "+43-124.dsf"))); + + na = na with { Supplement = Supplement("na", 1, Zip(("z_na_supplement/Earth nav data/+40-130/+44-124.dsf", "our dsf"))) }; + Assert.True(installed.Lacks(na.Supplement)); + _server.Requests.Clear(); + await Installer().InstallAsync(na, withOverlays: true, NoProgress, CancellationToken.None); + + Assert.DoesNotContain(_server.Requests, r => r.Url.Contains("z_na_00", StringComparison.Ordinal)); // only the tiles were downloaded + Assert.Equal("our dsf", File.ReadAllText(Path.Join(Packages, "OrthoStream_NA", "Earth nav data", "+40-130", "+44-124.dsf"))); + Assert.Equal(("1", 1), (Installer().Installed()["na"].Release, Installer().Installed()["na"].Supplement)); + } + + [Fact] + public async Task Tiles_added_to_an_installed_region_keep_the_overlays_any_region_placed() + { + await Installer().InstallAsync(Region("na", "1", [Zip(("z_na_00/Earth nav data/+40-130/+43-124.dsf", "AO dsf"))], + Zip(("y/Earth nav data/+40-130/+43-124.dsf", "AO overlay"))), true, NoProgress, CancellationToken.None); + // Left by an earlier try that stopped before it was recorded: no region placed it, so it is taken over. + _tree.WriteBytes("Base Packages/OrthoStream_Overlays/Earth nav data/+40-130/+45-124.dsf", Encoding.UTF8.GetBytes("half")); + RegionSupplement supplement = Supplement("na", 1, + Zip(("z_na_supplement/Earth nav data/+40-130/+44-124.dsf", "our dsf")), + Zip(("y/Earth nav data/+40-130/+44-124.dsf", "our overlay"), ("y/Earth nav data/+40-130/+43-124.dsf", "our copy"), + ("y/Earth nav data/+40-130/+45-124.dsf", "whole"))); + + await Installer().AddSupplementAsync("na", supplement, NoProgress, CancellationToken.None); + + string overlays = Path.Join(Packages, "OrthoStream_Overlays", "Earth nav data", "+40-130"); + Assert.Equal("AO overlay", File.ReadAllText(Path.Join(overlays, "+43-124.dsf"))); + Assert.Equal("our overlay", File.ReadAllText(Path.Join(overlays, "+44-124.dsf"))); + Assert.Equal("whole", File.ReadAllText(Path.Join(overlays, "+45-124.dsf"))); + Assert.Equal(1, Installer().Installed()["na"].Supplement); + Assert.False(Directory.Exists(Path.Join(Packages, RegionInstaller.WorkFolderName))); + + Installer().Delete("na"); + + Assert.False(Directory.Exists(Path.Join(Packages, "OrthoStream_Overlays"))); + } + + [Fact] + public async Task A_newer_version_of_the_tiles_replaces_its_own_files_but_still_not_AutoOrthos() + { + MeshRegion na = Region("na", "1", + [Zip(("z_na_00/Earth nav data/+40-130/+43-124.dsf", "AO dsf"), ("z_na_00/textures/1_2_ZL16.png", "AO mask"))], + Zip(("y/Earth nav data/+40-130/+43-124.dsf", "AO overlay"))) with + { + Supplement = Supplement("na", 1, + Zip(("z/Earth nav data/+40-130/+44-124.dsf", "ours 1"), ("z/textures/1_2_ZL16.png", "our mask 1")), + Zip(("y/Earth nav data/+40-130/+44-124.dsf", "our overlay 1"))), + }; + await Installer().InstallAsync(na, withOverlays: true, NoProgress, CancellationToken.None); + RegionSupplement second = Supplement("na", 2, + Zip(("z/Earth nav data/+40-130/+44-124.dsf", "ours 2"), ("z/Earth nav data/+40-130/+43-124.dsf", "ours over AO's"), + ("z/textures/1_2_ZL16.png", "our mask 2"), ("z/Earth nav data/+40-130/+45-124.dsf", "new in 2")), + Zip(("y/Earth nav data/+40-130/+44-124.dsf", "our overlay 2"), ("y/Earth nav data/+40-130/+43-124.dsf", "our copy of AO's"))); + + await Installer().AddSupplementAsync("na", second, NoProgress, CancellationToken.None); + + string mesh = Path.Join(Packages, "OrthoStream_NA", "Earth nav data", "+40-130"); + string overlays = Path.Join(Packages, "OrthoStream_Overlays", "Earth nav data", "+40-130"); + Assert.Equal("ours 2", File.ReadAllText(Path.Join(mesh, "+44-124.dsf"))); + Assert.Equal("new in 2", File.ReadAllText(Path.Join(mesh, "+45-124.dsf"))); + Assert.Equal("AO dsf", File.ReadAllText(Path.Join(mesh, "+43-124.dsf"))); + Assert.Equal("AO mask", File.ReadAllText(Path.Join(Packages, "OrthoStream_NA", "textures", "1_2_ZL16.png"))); // AutoOrtho's from the start + Assert.Equal("our overlay 2", File.ReadAllText(Path.Join(overlays, "+44-124.dsf"))); + Assert.Equal("AO overlay", File.ReadAllText(Path.Join(overlays, "+43-124.dsf"))); + InstalledRegion installed = Installer().Installed()["na"]; + Assert.Equal(2, installed.Supplement); + Assert.Equal(2, installed.SupplementFiles!.Count); + } + + [Fact] + public async Task A_supplement_file_named_like_one_of_AutoOrthos_zips_is_refused() + { + MeshRegion na = Region("na", "1", [Zip(("z_na_00/Earth nav data/+40-130/+43-124.dsf", "AO dsf"))]) with + { + Supplement = new RegionSupplement(1, ["+44-124"], new MeshAsset("z_na_00.zip", Host + "other.zip", 50), null), + }; + + await Assert.ThrowsAsync(() => Installer().InstallAsync(na, true, NoProgress, CancellationToken.None)); + + Assert.Empty(_server.Requests); + } + + [Fact] + public async Task At_the_start_the_tiles_are_added_to_regions_installed_without_them() + { + await Installer().InstallAsync(Region("na", "1", [Zip(("z_na_00/Earth nav data/+40-130/+43-124.dsf", "AO dsf"))]), + true, NoProgress, CancellationToken.None); + Supplement("na", 3, Zip(("z_na_supplement/Earth nav data/+40-130/+44-124.dsf", "our dsf"))); + _server.Files[SupplementCatalog.ManifestUrl] = Encoding.UTF8.GetBytes($$""" + { "schema": 1, "regions": { "na": { "version": 3, "tiles": ["+44-124"], + "mesh": { "name": "z_na_supplement.zip", "url": "{{Host}}z_na_supplement.zip", "size": {{_server.Files[Host + "z_na_supplement.zip"].Length}} } } } } + """); + var slot = new OrthoStreamXP.Gui.InstallSlot(); + var catalog = new SupplementCatalog(_http, _tree.PathOf("mesh-supplements.json")); + var updater = new OrthoStreamXP.Gui.SupplementUpdater(_http, catalog, slot, () => Packages); + + Assert.Equal(["North America"], await updater.RunAsync(NoProgress, CancellationToken.None)); + + Assert.Equal("our dsf", File.ReadAllText(Path.Join(Packages, "OrthoStream_NA", "Earth nav data", "+40-130", "+44-124.dsf"))); + Assert.Equal(3, Installer().Installed()["na"].Supplement); + Assert.False(slot.Busy); + _server.Requests.Clear(); + Assert.Empty(await updater.RunAsync(NoProgress, CancellationToken.None)); // has them now: nothing is downloaded + Assert.DoesNotContain(_server.Requests, r => r.Url.EndsWith(".zip", StringComparison.Ordinal)); + } + + [Fact] + public async Task Without_the_supplements_list_nothing_is_added_at_the_start() + { + await Installer().InstallAsync(Region("na", "1", [Zip(("z_na_00/Earth nav data/+40-130/+43-124.dsf", "AO dsf"))]), + true, NoProgress, CancellationToken.None); + var catalog = new SupplementCatalog(_http, _tree.PathOf("mesh-supplements.json")); + var updater = new OrthoStreamXP.Gui.SupplementUpdater(_http, catalog, new OrthoStreamXP.Gui.InstallSlot(), () => Packages); + + Assert.Empty(await updater.RunAsync(NoProgress, CancellationToken.None)); // the list is not on the server + + Assert.Null(Installer().Installed()["na"].Supplement); + } + + [Fact] + public void A_region_installed_without_its_supplement_offers_an_update_of_the_tiles_alone() + { + var page = new OrthoStreamXP.Gui.PackagesViewModel(new OrthoStreamXP.Gui.MountController(), new OrthoStreamXP.Gui.WindowPreferences(), + _http, new OrthoStreamXP.Gui.InstallSlot(), () => Packages); + MeshRegion na = Region("na", "1", [Zip(("z_na_00/Earth nav data/+40-130/+43-124.dsf", "AO dsf"))]) with + { + Supplement = Supplement("na", 2, Zip(("z_na_supplement/Earth nav data/+40-130/+44-124.dsf", "our dsf"))), + }; + var row = new OrthoStreamXP.Gui.RegionRow(page, na) { Installed = new InstalledRegion("na", "1", true, DateTime.UtcNow, Supplement: 1) }; + + Assert.False(row.UpToDate); + Assert.True(row.OnlyTilesLacking); + Assert.Equal("Update", row.InstallLabel); + Assert.Contains("tiles AutoOrtho lacks", row.Status, StringComparison.Ordinal); + + row.Installed = row.Installed with { Supplement = 2 }; + + Assert.True(row.UpToDate); + Assert.False(row.OnlyTilesLacking); + } + // ---------------------------------------------------------------- helpers + /// The tiles AutoOrtho lacks for a region, served by the fake server (the zips' names as the scenery repository publishes them). + private RegionSupplement Supplement(string id, int version, byte[] meshZip, byte[]? overlaysZip = null) + { + string mesh = $"z_{id}_supplement.zip"; + _server.Files[Host + mesh] = meshZip; + MeshAsset? overlays = null; + if (overlaysZip is not null) + { + string name = $"y_{id}_supplement_overlays.zip"; + _server.Files[Host + name] = overlaysZip; + overlays = new MeshAsset(name, Host + name, overlaysZip.Length); + } + return new RegionSupplement(version, ["+44-124"], new MeshAsset(mesh, Host + mesh, meshZip.Length), overlays); + } + /// A region whose files the fake server serves; its overlays zip cut in parts. private MeshRegion Region(string id, string release, byte[][] meshZips, byte[]? overlaysZip = null, int parts = 1) { diff --git a/tests/OrthoStreamXP.Tests/TerrainDefinitionsTests.cs b/tests/OrthoStreamXP.Tests/TerrainDefinitionsTests.cs index 33af72a..3d30abc 100644 --- a/tests/OrthoStreamXP.Tests/TerrainDefinitionsTests.cs +++ b/tests/OrthoStreamXP.Tests/TerrainDefinitionsTests.cs @@ -187,12 +187,15 @@ public void Fading_to_100_percent_keeps_the_image() } [Fact] - public void The_ground_detail_setting_is_0_unless_raised_and_stays_within_0_to_100() + public void The_ground_detail_setting_is_30_unless_raised_and_stays_within_30_to_100() { MountSettings Parse(params string[] extra) => MountSettings.FromValues(TestSettings.Of( [$"source = {_tree.PathOf("source")}", $"cache = {_tree.PathOf("cache")}", $"mountpoint = {_tree.PathOf("mount")}", .. extra])); - Assert.Equal(0, Parse().GroundDetail); + Assert.Equal(30, Parse().GroundDetail); Assert.Equal(40, Parse("ground-detail = 40").GroundDetail); + Assert.Equal(100, Parse("ground-detail = 100").GroundDetail); + Assert.Equal(30, Parse("ground-detail = 0").GroundDetail); + Assert.Equal(30, Parse("ground-detail = 29").GroundDetail); Assert.Throws(() => Parse("ground-detail = 101")); Assert.Throws(() => Parse("ground-detail = -1")); }