-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
339 lines (279 loc) · 11.5 KB
/
Program.cs
File metadata and controls
339 lines (279 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
// Program.cs for GeographicLib.NET (the repo version you pasted)
// Uses GeographicLib.Projections.TransverseMercator where Reverse returns (lat, lon) as a ValueTuple.
//
// Why your previous output was wrong:
// In THIS library, Reverse signature is:
// (double lat, double lon) Reverse(double lon0, double x, double y, out double gamma, out double k)
// and there is an overload:
// (double lat, double lon) Reverse(double lon0, double x, double y)
// So if code assumes out-lat/out-lon, you accidentally read back gamma/k.
//
// Build/run:
// dotnet add package GeographicLib.NET
// dotnet run -- Theater.txt [optional HeightMap.raw]
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using GeographicLib; // GeographicException
using GeographicLib.Projections; // TransverseMercator
internal static class Program
{
private static readonly CultureInfo Invariant = CultureInfo.InvariantCulture;
public static int Main(string[] args)
{
Console.OutputEncoding = System.Text.Encoding.UTF8;
var theaterPath = args.Length >= 1 ? args[0] : "Theater.txt";
if (!File.Exists(theaterPath))
{
Console.Error.WriteLine($"Theater file not found: {theaterPath}");
return 2;
}
var theater = TheaterConfig.Load(theaterPath);
if (theater.MapSizePixels <= 0)
{
Console.Error.WriteLine("Map size in pixels is missing/invalid");
return 3;
}
var proj = ProjString.Parse(theater.ProjectionString);
if (!string.Equals(proj.Proj, "tmerc", StringComparison.OrdinalIgnoreCase))
{
Console.Error.WriteLine($"Unsupported projection: {proj.Proj ?? "(null)"} (expected +proj=tmerc)");
return 4;
}
var grid = TerrainGrid.From(theaterSizeKm: theater.TheaterSizeKm, mapSamples: theater.MapSizePixels);
// This GeographicLib.NET implementation expects flattening f (NOT inverse flattening).
// (See the constructor checks in TransverseMercator.cs: it validates f < 1.)
const double WGS84_A = 6378137.0;
const double WGS84_F = 1.0 / 298.257223563;
var tm = new TransverseMercator(WGS84_A, WGS84_F, proj.K0);
var converter = new CoordinateConverter(grid, proj, tm);
Console.WriteLine("Enter coords as: simX_feet_east simY_feet_north (q to quit)");
while (true)
{
Console.Write("> ");
var line = Console.ReadLine();
if (line is null) return 0;
line = line.Trim();
if (line.Equals("q", StringComparison.OrdinalIgnoreCase) ||
line.Equals("quit", StringComparison.OrdinalIgnoreCase) ||
line.Equals("exit", StringComparison.OrdinalIgnoreCase))
return 0;
if (string.IsNullOrWhiteSpace(line))
continue;
var parts = line.Split(new[] { ' ', '\t', ';', ',' }, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length < 2)
{
Console.WriteLine("Please enter TWO numbers: simX(feet east) simY(feet north).");
continue;
}
if (!TryParseDouble(parts[0], out var simXFeetEast) || !TryParseDouble(parts[1], out var simYFeetNorth))
{
Console.WriteLine("Could not parse numbers.");
continue;
}
var (lat, lon) = converter.SimFeetToLatLon(simXFeetEast, simYFeetNorth);
// Match your expected comma-decimal output (Berlin / de-DE) while still being stable:
var outCulture = CultureInfo.GetCultureInfo("de-DE");
Console.WriteLine($"Lat/Lon: {lat.ToString("F8", outCulture)}, {lon.ToString("F8", outCulture)}");
var (latDm, lonDm) = GeoFormat.ToDegMin(lat, lon, outCulture);
Console.WriteLine($"DegMin: {latDm} {lonDm}");
Console.WriteLine();
}
}
private static bool TryParseDouble(string s, out double value)
{
// Accept both "1234.56" and "1234,56", reject ambiguous mixed separators.
s = s.Trim();
if (s.Contains(',') && s.Contains('.'))
{
value = default;
return false;
}
if (s.Contains(',')) s = s.Replace(',', '.');
return double.TryParse(
s,
NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent,
Invariant,
out value
);
}
}
internal sealed class CoordinateConverter
{
private readonly TerrainGrid _grid;
private readonly ProjString _proj;
private readonly TransverseMercator _tm;
public CoordinateConverter(TerrainGrid grid, ProjString proj, TransverseMercator tm)
{
_grid = grid;
_proj = proj;
_tm = tm;
}
public (double lat, double lon) SimFeetToLatLon(double simXFeetEast, double simYFeetNorth)
{
// Keep your original axis mapping:
// gridX uses simY; gridZ uses simX.
var gridX = -_grid.GridOffset + simYFeetNorth * _grid.FeetToGrid;
var gridZ = -_grid.GridOffset + simXFeetEast * _grid.FeetToGrid;
var half = 0.5 * _grid.HeightmapSize;
var pxX = gridX + half;
var pxZ = -(gridZ - half);
var localX = pxX * _grid.MeterRes;
var localY = pxZ * _grid.MeterRes;
localY = _grid.TheaterSizeMeters - localY;
// This TransverseMercator does NOT include false easting/northing.
var x = localX - _proj.X0;
var y = localY - _proj.Y0;
// IMPORTANT: In this library Reverse RETURNS (lat, lon) and out-params are gamma/k.
// Use the overload without gamma/k if you don't need them:
var (lat, lon) = _tm.Reverse(_proj.Lon0, x, y);
return (lat, lon);
}
}
internal sealed class TerrainGrid
{
private const double MetersToFeet = 3.28084;
public double TheaterSizeMeters { get; }
public int MapSamples { get; }
public double HeightmapSize { get; }
public double GridOffset { get; }
public double MeterRes { get; }
public double GridToFeet { get; }
public double FeetToGrid { get; }
private TerrainGrid(double theaterSizeMeters, int mapSamples)
{
TheaterSizeMeters = theaterSizeMeters;
MapSamples = mapSamples;
HeightmapSize = mapSamples - 1.0;
GridOffset = HeightmapSize / 2.0;
MeterRes = theaterSizeMeters / mapSamples;
GridToFeet = MeterRes * MetersToFeet;
FeetToGrid = 1.0 / GridToFeet;
}
public static TerrainGrid From(double theaterSizeKm, int mapSamples)
=> new TerrainGrid(theaterSizeKm * 1000.0, mapSamples);
}
internal sealed class TheaterConfig
{
public string Name { get; }
public double TheaterSizeKm { get; }
public int MapSizePixels { get; }
public double CenterLat { get; }
public double CenterLon { get; }
public string ProjectionString { get; }
private TheaterConfig(string name, double theaterSizeKm, int mapSizePixels, double centerLat, double centerLon, string projectionString)
{
Name = name;
TheaterSizeKm = theaterSizeKm;
MapSizePixels = mapSizePixels;
CenterLat = centerLat;
CenterLon = centerLon;
ProjectionString = projectionString;
}
public static TheaterConfig Load(string path)
{
var dict = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (var raw in File.ReadAllLines(path))
{
var line = raw.Trim();
if (line.Length == 0) continue;
var idx = line.IndexOf('=');
if (idx < 0) continue;
dict[line.Substring(0, idx).Trim()] = line.Substring(idx + 1).Trim();
}
string name = dict.GetValueOrDefault("Theater name") ?? "Unknown";
double sizeKm = ParseDouble(dict.GetValueOrDefault("Theater size in KM"), 0);
int mapPx = (int)Math.Round(ParseDouble(dict.GetValueOrDefault("Map size in pixels"), 0));
double centerLat = ParseDouble(dict.GetValueOrDefault("Center latitude"), 0);
double centerLon = ParseDouble(dict.GetValueOrDefault("Center longitude"), 0);
string proj = dict.GetValueOrDefault("Projection string") ??
"+proj=tmerc +ellps=WGS84 +units=m +k=1 +lon_0=0 +x_0=0 +y_0=0";
return new TheaterConfig(name, sizeKm, mapPx, centerLat, centerLon, proj);
}
private static double ParseDouble(string? s, double fallback)
{
if (string.IsNullOrWhiteSpace(s)) return fallback;
s = s.Trim();
if (s.Contains(',') && s.Contains('.')) return fallback;
if (s.Contains(',')) s = s.Replace(',', '.');
return double.TryParse(
s,
NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent,
CultureInfo.InvariantCulture,
out var v
) ? v : fallback;
}
}
internal sealed class ProjString
{
public string? Proj { get; }
public double Lon0 { get; }
public double K0 { get; }
public double X0 { get; }
public double Y0 { get; }
private ProjString(string? proj, double lon0, double k0, double x0, double y0)
{
Proj = proj;
Lon0 = lon0;
K0 = k0 == 0 ? 1.0 : k0;
X0 = x0;
Y0 = y0;
}
public static ProjString Parse(string projString)
{
var tokens = projString.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Select(t => t.Trim()).Where(t => t.StartsWith("+", StringComparison.Ordinal)).ToArray();
string? proj = null;
double lon0 = 0, k0 = 1, x0 = 0, y0 = 0;
foreach (var tok in tokens)
{
var kv = tok.Substring(1).Split('=', 2);
var key = kv[0];
var val = kv.Length > 1 ? kv[1] : "";
switch (key)
{
case "proj": proj = val; break;
case "lon_0": lon0 = ParseDouble(val, 0); break;
case "k":
case "k_0": k0 = ParseDouble(val, 1); break;
case "x_0": x0 = ParseDouble(val, 0); break;
case "y_0": y0 = ParseDouble(val, 0); break;
}
}
return new ProjString(proj, lon0, k0, x0, y0);
}
private static double ParseDouble(string s, double fallback)
{
if (string.IsNullOrWhiteSpace(s)) return fallback;
s = s.Trim();
if (s.Contains(',') && s.Contains('.')) return fallback;
if (s.Contains(',')) s = s.Replace(',', '.');
return double.TryParse(
s,
NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent,
CultureInfo.InvariantCulture,
out var v
) ? v : fallback;
}
}
internal static class GeoFormat
{
public static (string latDegMin, string lonDegMin) ToDegMin(double lat, double lon, CultureInfo culture)
=> (ToDegMinSingle(lat, true, culture), ToDegMinSingle(lon, false, culture));
private static string ToDegMinSingle(double deg, bool isLat, CultureInfo culture)
{
int whole = (int)Math.Floor(deg);
double minutes = Math.Abs(deg - whole) * 60.0;
minutes = Math.Round(minutes, 3, MidpointRounding.AwayFromZero);
if (minutes >= 60.0)
{
minutes -= 60.0;
whole += 1;
}
string wholeFmt = isLat ? whole.ToString("00", culture) : whole.ToString("000", culture);
string minFmt = minutes.ToString("00.000", culture);
return $"{wholeFmt},{minFmt}";
}
}