Files
cruiseSimulator/Assets/Soundings/Runtime/PassageWeather.cs

190 lines
8.1 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UIElements;
namespace Soundings
{
public sealed partial class SoundingsApp
{
private sealed class PassageWeatherSelection
{
public WeatherCondition Condition;
public bool Loading;
public int Request;
public string Status;
}
[Serializable]
private sealed class WeatherReply
{
public CurrentWeather current;
}
[Serializable]
private sealed class CurrentWeather
{
public string time;
public float wind_speed_10m;
public float precipitation;
public int weather_code;
}
private readonly Dictionary<(int, int), PassageWeatherSelection> passageWeather = new();
private static (int, int) WeatherRoute(int origin, int destination)
=> origin < destination ? (origin, destination) : (destination, origin);
private void ResetWeatherSelection() => passageWeather.Clear();
private WeatherCondition PassageWeatherFor(int origin, int destination)
=> passageWeather.TryGetValue(WeatherRoute(origin, destination), out var selection)
? selection.Condition
: WeatherCondition.Calm;
private void DrawWeatherPicker(VisualElement parent, Voyage quote)
{
var route = WeatherRoute(quote.Origin, quote.Destination);
if (!passageWeather.TryGetValue(route, out var selection))
{
selection = new PassageWeatherSelection();
passageWeather.Add(route, selection);
}
quote.Weather = selection.Condition;
var picker = Add(parent, "chart-money-row");
picker.style.flexWrap = Wrap.Wrap;
var label = AddText(picker, "Sea state", "chart-money-label");
label.style.marginRight = 5;
foreach (WeatherCondition condition in Enum.GetValues(typeof(WeatherCondition)))
{
var preset = condition;
string name = preset.ToString();
bool selected = selection.Condition == preset;
Button choice = Action(name, () =>
{
selection.Request++;
selection.Loading = false;
selection.Condition = preset;
selection.Status = null;
Render();
}, "chart-step", "weather-" + name.ToLowerInvariant());
choice.style.width = StyleKeyword.Auto;
choice.style.paddingLeft = 5;
choice.style.paddingRight = 5;
choice.style.marginRight = 2;
choice.style.minHeight = 25;
if (selected)
{
choice.style.backgroundColor = (Color)new Color32(39, 69, 70, 255);
choice.style.color = (Color)new Color32(248, 234, 200, 255);
}
picker.Add(choice);
}
var tools = Add(parent, "chart-forecast-tools");
Button live = Action(selection.Loading ? "Checking…" : "Fetch live", () =>
{
selection.Loading = true;
selection.Status = null;
StartCoroutine(FetchPassageWeather(route, selection, ++selection.Request));
Render();
}, "chart-step", "weather-live");
live.tooltip = "Fetch current model weather at the midpoint of this route from Open-Meteo.";
live.SetEnabled(!selection.Loading);
live.style.width = StyleKeyword.Auto;
live.style.paddingLeft = 5;
live.style.paddingRight = 5;
live.style.minHeight = 25;
tools.Add(live);
DrawShorePlanningLink(tools, quote, false);
if (!string.IsNullOrEmpty(selection.Status))
AddText(parent, selection.Status, "chart-paper-note");
}
private IEnumerator FetchPassageWeather((int Origin, int Destination) route,
PassageWeatherSelection selection, int request)
{
(double latitude, double longitude) = WeatherMidpoint(Market.Ports[route.Origin], Market.Ports[route.Destination]);
string address = FormattableString.Invariant(
$"https://api.open-meteo.com/v1/forecast?latitude={latitude:F3}&longitude={longitude:F3}&current=wind_speed_10m,precipitation,weather_code&wind_speed_unit=kn&timezone=GMT");
using var download = UnityWebRequest.Get(address);
download.timeout = 6;
yield return download.SendWebRequest();
if (selection.Request != request || !passageWeather.TryGetValue(route, out var active) || active != selection)
yield break;
selection.Loading = false;
CurrentWeather reading = download.result == UnityWebRequest.Result.Success
? ParseCurrentWeather(download.downloadHandler.text)
: null;
if (reading == null)
{
selection.Status = "Live weather unavailable. Preset kept.";
}
else
{
selection.Condition = ClassifyWeather(reading);
DateTime.TryParseExact(reading.time, "yyyy-MM-dd'T'HH:mm", CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out var utc);
string stamp = utc == default ? reading.time : utc.ToString("MMM d HH:mm", CultureInfo.InvariantCulture);
selection.Status = $"Open-Meteo · {stamp} UTC · {reading.wind_speed_10m:0.#} kt";
}
if (!title && underway == null && page == 3 && Ship != null && WeatherRoute(Ship.Port, inspectedPort) == route)
Render();
}
private static CurrentWeather ParseCurrentWeather(string text)
{
if (string.IsNullOrWhiteSpace(text))
return null;
try
{
CurrentWeather weather = JsonUtility.FromJson<WeatherReply>(text)?.current;
if (weather == null || string.IsNullOrWhiteSpace(weather.time)
|| float.IsNaN(weather.wind_speed_10m) || float.IsInfinity(weather.wind_speed_10m)
|| float.IsNaN(weather.precipitation) || float.IsInfinity(weather.precipitation)
|| weather.wind_speed_10m < 0 || weather.precipitation < 0)
return null;
return weather;
}
catch (ArgumentException)
{
return null;
}
}
private static WeatherCondition ClassifyWeather(CurrentWeather reading)
{
if (reading.weather_code >= 95 || reading.wind_speed_10m >= 32 || reading.precipitation >= 5)
return WeatherCondition.Storm;
if (reading.wind_speed_10m >= 16 || reading.precipitation >= 1 || reading.weather_code == 82)
return WeatherCondition.Swell;
return WeatherCondition.Calm;
}
private static (double Latitude, double Longitude) WeatherMidpoint(PortSpec a, PortSpec b)
{
const double radians = Math.PI / 180;
double latA = a.Latitude * radians, latB = b.Latitude * radians;
double lonA = a.Longitude * radians, lonB = b.Longitude * radians;
double x = Math.Cos(latA) * Math.Cos(lonA) + Math.Cos(latB) * Math.Cos(lonB);
double y = Math.Cos(latA) * Math.Sin(lonA) + Math.Cos(latB) * Math.Sin(lonB);
double z = Math.Sin(latA) + Math.Sin(latB);
double horizontal = Math.Sqrt(x * x + y * y);
if (horizontal < 1e-8 && Math.Abs(z) < 1e-8)
{
float longitude = a.Longitude + Mathf.DeltaAngle(a.Longitude, b.Longitude) / 2;
return ((a.Latitude + b.Latitude) / 2, Mathf.Repeat(longitude + 180, 360) - 180);
}
return (Math.Atan2(z, horizontal) / radians, Math.Atan2(y, x) / radians);
}
}
}