-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.ts
375 lines (293 loc) · 10.1 KB
/
index.ts
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
import {dsvFormat} from 'd3-dsv';
namespace CUPParser {
const csv = dsvFormat(',');
const RE_LAT = /(\d{2})(\d{2}\.\d{3})([NS])/;
const RE_LON = /(\d{3})(\d{2}\.\d{3})([EW])/;
const RE_VDIS = /^\s*(\d+(?:\.\d+)?)(m|ft)\s*$/i;
const RE_HDIS = /^\s*(\d+(?:\.\d+)?)(km|ml|nm|m|ft)\s*$/i;
const RE_DURATION = /(?:(?:(\d+):)?(\d+):)?(\d{2})/;
export interface CUPFile {
waypoints: Waypoint[];
tasks: Task[];
}
export interface Waypoint {
name: string;
code: string;
country: string;
latitude: number;
longitude: number;
elevation: VDistance | null;
style: WaypointStyle;
runwayDirection: number | null;
runwayLength: HDistance | null;
frequency: string | null;
description: string;
}
export interface HDistance {
value: number;
unit: 'm' | 'km' | 'nm' | 'ml' | 'ft';
}
export interface VDistance {
value: number;
unit: 'm' | 'ft';
}
export enum WaypointStyle {
Unknown = 0,
Normal = 1,
AirfieldGrass = 2,
Outlanding = 3,
GliderSite = 4,
AirfieldSolid = 5,
MtPass = 6,
MtTop = 7,
Sender = 8,
Vor = 9,
Ndb = 10,
CoolTower = 11,
Dam = 12,
Tunnel = 13,
Bridge = 14,
PowerPlant = 15,
Castle = 16,
Intersection = 17,
}
export interface Task {
description: string;
points: Taskpoint[];
options: TaskOptions;
}
export interface Taskpoint {
name: string;
options?: TaskpointOptions;
}
export interface TaskpointOptions {
style?: TaskpointStyle;
r1?: HDistance;
a1?: number;
r2?: HDistance;
a2?: number;
a12?: number;
line: boolean;
}
export enum TaskpointStyle {
FixedValue = 0,
Symmetrical = 1,
ToNextPoint = 2,
ToPreviousPoint = 3,
ToStartPoint = 4,
}
export interface TaskOptions {
/** Opening of start line */
noStart?: string;
/** Designated Time for the task (seconds) */
taskTime?: number;
/** Task distance calculation. False = use fixes, True = use waypoints */
wpDis?: boolean;
/** Distance tolerance */
nearDis?: HDistance;
/** Altitude tolerance */
nearAlt?: VDistance;
/** Uncompleted leg. False = calculate maximum distance from last observation zone. */
minDis?: boolean;
/** if true, then Random order of waypoints is checked */
randomOrder?: boolean;
/** Maximum number of points */
maxPts?: number;
/**
* Number of mandatory waypoints at the beginning.
* 1 means start line only, two means start line plus first point in task sequence (Task line).
*/
beforePts?: number;
/**
* Number of mandatory waypoints at the end.
* 1 means finish line only, two means finish line and one point before finish in task sequence (Task line).
*/
afterPts?: number;
/** Bonus for crossing the finish line */
bonus?: number;
}
export function parse(str: string): CUPFile {
let [waypointPart, taskPart] = str.split('-----Related Tasks-----');
let waypoints = parseWaypoints(waypointPart);
let tasks = parseTasks(taskPart);
return { waypoints, tasks };
}
export function parseHDistance(str: string | undefined, description: string = 'distance'): HDistance {
if (!str) throw new Error(`Invalid ${description}: ${str}`);
let match = str.match(RE_HDIS);
if (!match) throw new Error(`Invalid ${description}: ${str}`);
let value = Number(match[1]);
let unit = match[2].toLowerCase() as ('m' | 'km' | 'nm' | 'ml');
return { value, unit };
}
export function parseVDistance(str: string | undefined, description: string = 'vertical distance'): VDistance {
if (!str) throw new Error(`Invalid ${description}: ${str}`);
let match = str.match(RE_VDIS);
if (!match) throw new Error(`Invalid ${description}: ${str}`);
let value = Number(match[1]);
let unit = match[2].toLowerCase() as ('m' | 'ft');
return { value, unit };
}
export function parseDuration(str: string | undefined, description: string = 'duration'): number {
if (!str) throw new Error(`Invalid ${description}: ${str}`);
let match = str.match(RE_DURATION);
if (!match) throw new Error(`Invalid ${description}: ${str}`);
let h = match[1] ? Number(match[1]) : 0;
let m = match[2] ? Number(match[2]) : 0;
let s = Number(match[3]);
return (h * 60 + m) * 60 + s;
}
export function parseBoolean(str: string | undefined, description: string = 'boolean'): boolean {
if (!str) throw new Error(`Invalid ${description}: ${str}`);
let value = str.toLowerCase().trim();
if (value === 'true') {
return true;
} else if (value === 'false') {
return false;
} else {
throw new Error(`Invalid ${description}: ${str}`);
}
}
export function parseLatitude(str: string): number {
let match = str.match(RE_LAT);
if (!match) throw new Error(`Invalid latitude: ${str}`);
let value = Number(match[1]) + Number(match[2]) / 60;
if (value > 90) throw new Error(`Invalid latitude: ${str}`);
return (match[3] === 'S') ? -value : value;
}
export function parseLongitude(str: string): number {
let match = str.match(RE_LON);
if (!match) throw new Error(`Invalid longitude: ${str}`);
let value = Number(match[1]) + Number(match[2]) / 60;
if (value > 180) throw new Error(`Invalid longitude: ${str}`);
return (match[3] === 'W') ? -value : value;
}
export function parseWaypoints(str: string): Waypoint[] {
return csv.parseRows(str, row => {
if (row.length < 5) throw new Error(`Invalid waypoint: ${str}`);
// ignore CSV header line
if (row[2].toLowerCase() === 'country') return {};
let name = row[0];
let code = row[1] || '';
let country = row[2] || '';
let latitude = parseLatitude(row[3]);
let longitude = parseLongitude(row[4]);
let elevation = row[5] ? parseVDistance(row[5], 'elevation') : null;
let style = parseWaypointStyle(row[6]);
let runwayDirection = row[7] ? Number(row[7]) : null;
let runwayLength = row[8] ? parseHDistance(row[8], 'runway length') : null;
let frequency = row[9] || null;
let description = row[10] || '';
return {
name,
code,
country,
latitude,
longitude,
elevation,
style,
runwayDirection,
runwayLength,
frequency,
description,
};
}).filter(row => 'name' in row) as Waypoint[];
}
export function parseWaypointStyle(str: string | undefined): WaypointStyle {
if (!str) return WaypointStyle.Unknown;
let value = Number(str);
return value < 1 || value > 17 ? WaypointStyle.Unknown : value;
}
export function parseTasks(str: string): Task[] {
if (!str) return [];
let rows = csv.parseRows(str);
let tasks: Task[] = [];
for (let row of rows) {
if (row[0] === 'Options') {
let lastTask = tasks[tasks.length - 1];
if (!lastTask) throw new Error(`Missing task for "Options" line`);
lastTask.options = parseTaskOptions(row);
} else if (row[0].indexOf('ObsZone=') === 0) {
let lastTask = tasks[tasks.length - 1];
if (!lastTask) throw new Error(`Missing task for "ObsZone" line`);
let pointIndex = Number(row[0].slice(8));
let point = lastTask.points[pointIndex];
if (!point) throw new Error(`Missing point for "ObsZone" line`);
point.options = parseTaskpointOptions(row);
} else {
let description = row[0] || '';
let names = row.slice(1).filter(Boolean);
if (names.length === 0) continue;
let points = names.map(name => ({ name } as Taskpoint));
tasks.push({ description, points, options: {} });
}
}
return tasks;
}
export function parseTaskOptions(columns: string[]): TaskOptions {
let options: TaskOptions = {};
for (let column of columns) {
let [name, value] = column.split('=');
if (name === 'NoStart') {
options.noStart = value;
} else if (name === 'TaskTime') {
options.taskTime = parseDuration(value);
} else if (name === 'WpDis') {
options.wpDis = parseBoolean(value);
} else if (name === 'NearDis') {
options.nearDis = parseHDistance(value, name);
} else if (name === 'NearAlt') {
options.nearAlt = parseVDistance(value, name);
} else if (name === 'MinDis') {
options.minDis = parseBoolean(value);
} else if (name === 'RandomOrder') {
options.randomOrder = parseBoolean(value);
} else if (name === 'MaxPts') {
options.maxPts = Number(value);
} else if (name === 'BeforePts') {
options.beforePts = Number(value);
} else if (name === 'AfterPts') {
options.afterPts = Number(value);
} else if (name === 'Bonus') {
options.bonus = Number(value);
}
}
return options;
}
export function parseTaskpointOptions(columns: string[]): TaskpointOptions {
let options: TaskpointOptions = { line: false };
for (let column of columns) {
let [name, value] = column.split('=');
if (name === 'Style' && value) {
let style = Number(value);
if (style >= 0 && style <= 4) {
options.style = style;
}
} else if (name === 'R1') {
let r1 = parseHDistance(value, 'R1');
if (!r1) throw new Error(`Invalid ${name}: ${value}`);
options.r1 = r1;
} else if (name === 'A1') {
let num = Number(value);
if (isNaN(num)) throw new Error(`Invalid ${name}: ${value}`);
options.a12 = num;
} else if (name === 'R2') {
let r2 = parseHDistance(value, 'R2');
if (!r2) throw new Error(`Invalid ${name}: ${value}`);
options.r2 = r2;
} else if (name === 'A2') {
let num = Number(value);
if (isNaN(num)) throw new Error(`Invalid ${name}: ${value}`);
options.a12 = num;
} else if (name === 'A12') {
let num = Number(value);
if (isNaN(num)) throw new Error(`Invalid ${name}: ${value}`);
options.a12 = num;
} else if (name === 'Line' && value === '1') {
options.line = true;
}
}
return options;
}
}
export = CUPParser;