forked from mmp/vice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.go
1553 lines (1335 loc) · 39.8 KB
/
util.go
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// util.go
// Copyright(c) 2022 Matt Pharr, licensed under the GNU Public License, Version 3.
// SPDX: GPL-3.0-only
package main
import (
"encoding/json"
"fmt"
"golang.org/x/exp/constraints"
"image"
"image/color"
"image/draw"
"io"
"math"
"net/http"
"os"
"regexp"
"sort"
"strconv"
"strings"
"time"
"unicode"
"github.com/MichaelTJones/pcg"
"github.com/klauspost/compress/zstd"
)
///////////////////////////////////////////////////////////////////////////
// decompression
var decoder, _ = zstd.NewReader(nil, zstd.WithDecoderConcurrency(0))
// decompressZstd decompresses data that was compressed using zstd.
// There's no error handling to speak of, since this is currently only used
// for data that's baked into the vice binary, so any issues with that
// should be evident upon a first run.
func decompressZstd(s string) string {
b, err := decoder.DecodeAll([]byte(s), nil)
if err != nil {
lg.ErrorfUp1("Error decompressing buffer")
}
return string(b)
}
///////////////////////////////////////////////////////////////////////////
// text
// wrapText wraps the provided text string to the given column limit, returning the
// wrapped string and the number of lines it became. indent gives the amount to
// indent wrapped lines. By default, lines that start with a space are assumed to be
// preformatted and are not wrapped; providing a true value for wrapAll overrides
// that behavior and causes them to be wrapped as well.
func wrapText(s string, columnLimit int, indent int, wrapAll bool) (string, int) {
var accum, result strings.Builder
var wrapLine bool
column := 0
lines := 1
flush := func() {
if wrapLine && column > columnLimit {
result.WriteRune('\n')
lines++
for i := 0; i < indent; i++ {
result.WriteRune(' ')
}
column = indent + accum.Len()
}
result.WriteString(accum.String())
accum.Reset()
}
for _, ch := range s {
// If wrapAll isn't enabled, then if the line starts with a space,
// assume it is preformatted and pass it through unchanged.
if column == 0 {
wrapLine = wrapAll || ch != ' '
}
accum.WriteRune(ch)
column++
if ch == '\n' {
flush()
column = 0
lines++
} else if ch == ' ' {
flush()
}
}
flush()
return result.String(), lines
}
// stopShouting turns text of the form "UNITED AIRLINES" to "United Airlines"
func stopShouting(orig string) string {
var s strings.Builder
wsLast := true
for _, ch := range orig {
if unicode.IsSpace(ch) {
wsLast = true
} else if unicode.IsLetter(ch) {
if wsLast {
// leave it alone
wsLast = false
} else {
ch = unicode.ToLower(ch)
}
}
// otherwise leave it alone
s.WriteRune(ch)
}
return s.String()
}
// atof is a utility for parsing floating point values that sends errors to
// the logging system.
func atof(s string) float64 {
if v, err := strconv.ParseFloat(strings.TrimSpace(s), 64); err != nil {
lg.ErrorfUp1("%s: error converting to float: %s", s, err)
return 0
} else {
return v
}
}
///////////////////////////////////////////////////////////////////////////
// core math
// argmin returns the index of the minimum value of a number of float32s.
func argmin(v ...float32) int {
minval := v[0]
minidx := 0
for i, val := range v {
if val < minval {
minidx = i
minval = val
}
}
return minidx
}
// degrees converts an angle expressed in degrees to radians
func degrees(r float32) float32 {
return r * 180 / math.Pi
}
// radians converts an angle expressed in radians to degrees
func radians(d float32) float32 {
return d / 180 * math.Pi
}
// A number of utility functions for evaluating transcendentals and the like follow;
// since we mostly use float32, it's handy to be able to call these directly rather than
// with all of the casts that are required when using the math package.
func sin(a float32) float32 {
return float32(math.Sin(float64(a)))
}
func cos(a float32) float32 {
return float32(math.Cos(float64(a)))
}
func tan(a float32) float32 {
return float32(math.Tan(float64(a)))
}
func atan2(y, x float32) float32 {
return float32(math.Atan2(float64(y), float64(x)))
}
func sqrt(a float32) float32 {
return float32(math.Sqrt(float64(a)))
}
func mod(a, b float32) float32 {
return float32(math.Mod(float64(a), float64(b)))
}
func sign(v float32) float32 {
if v > 0 {
return 1
} else if v < 0 {
return -1
}
return 0
}
func floor(v float32) float32 {
return float32(math.Floor(float64(v)))
}
func ceil(v float32) float32 {
return float32(math.Ceil(float64(v)))
}
func abs[V constraints.Integer | constraints.Float](x V) V {
if x < 0 {
return -x
}
return x
}
func min[T constraints.Ordered](a, b T) T {
if a < b {
return a
}
return b
}
func max[T constraints.Ordered](a, b T) T {
if a > b {
return a
}
return b
}
func pow(a, b float32) float32 {
return float32(math.Pow(float64(a), float64(b)))
}
func sqr(v float32) float32 { return v * v }
func clamp[T constraints.Ordered](x T, low T, high T) T {
if x < low {
return low
} else if x > high {
return high
}
return x
}
func lerp(x, a, b float32) float32 {
return (1-x)*a + x*b
}
///////////////////////////////////////////////////////////////////////////
// headings and directions
type CardinalOrdinalDirection int
const (
North = iota
NorthEast
East
SouthEast
South
SouthWest
West
NorthWest
)
func (co CardinalOrdinalDirection) Heading() float32 {
return float32(co) * 45
}
func (co CardinalOrdinalDirection) ShortString() string {
switch co {
case North:
return "N"
case NorthEast:
return "NE"
case East:
return "E"
case SouthEast:
return "SE"
case South:
return "S"
case SouthWest:
return "SW"
case West:
return "W"
case NorthWest:
return "NW"
default:
return "ERROR"
}
}
// headingp2ll returns the heading from the point |from| to the point |to|
// in degrees. The provided points should be in latitude-longitude
// coordinates and the provided magnetic correction is applied to the
// result.
func headingp2ll(from Point2LL, to Point2LL, magCorrection float32) float32 {
v := Point2LL{to[0] - from[0], to[1] - from[1]}
return headingv2ll(v, magCorrection)
}
// headingv2ll returns the heading in degrees corresponding to the provided
// vector expressed in latitude-longitude coordinates with the provided
// magnetic correction applied.
func headingv2ll(v Point2LL, magCorrection float32) float32 {
// Note that atan2() normally measures w.r.t. the +x axis and angles
// are positive for counter-clockwise. We want to measure w.r.t. +y and
// to have positive angles be clockwise. Happily, swapping the order of
// values passed to atan2()--passing (x,y), gives what we want.
angle := degrees(atan2(v[0]*scenarioGroup.NmPerLongitude, v[1]*scenarioGroup.NmPerLatitude))
angle += magCorrection
for angle < 0 {
angle += 360
}
return mod(angle, 360)
}
// headingDifference returns the minimum difference between two
// headings. (i.e., the result is always in the range [0,180].)
func headingDifference(a float32, b float32) float32 {
var d float32
if a > b {
d = a - b
} else {
d = b - a
}
if d > 180 {
d = 360 - d
}
return d
}
// compass converts a heading expressed into degrees into a string
// corresponding to the closest compass direction.
func compass(heading float32) string {
h := mod(heading+22.5, 360) // now [0,45] is north, etc...
idx := int(h / 45)
return [...]string{"North", "Northeast", "East", "Southeast",
"South", "Southwest", "West", "Northwest"}[idx]
}
// shortCompass converts a heading expressed in degrees into an abbreviated
// string corresponding to the closest compass direction.
func shortCompass(heading float32) string {
h := mod(heading+22.5, 360) // now [0,45] is north, etc...
idx := int(h / 45)
return [...]string{"N", "NE", "E", "SE", "S", "SW", "W", "NW"}[idx]
}
// headingAsHour converts a heading expressed in degrees into the closest
// "o'clock" value, with an integer result in the range [1,12].
func headingAsHour(heading float32) int {
for heading < 0 {
heading += 360
}
for heading > 360 {
heading -= 360
}
heading -= 15
if heading < 0 {
heading += 360
}
// now [0,30] is 1 o'clock, etc
return 1 + int(heading/30)
}
///////////////////////////////////////////////////////////////////////////
// Extent2D
// Extent2D represents a 2D bounding box with the two vertices at its
// opposite minimum and maximum corners.
type Extent2D struct {
p0, p1 [2]float32
}
// EmptyExtent2D returns an Extent2D representing an empty bounding box.
func EmptyExtent2D() Extent2D {
// Degenerate bounds
return Extent2D{p0: [2]float32{1e30, 1e30}, p1: [2]float32{-1e30, -1e30}}
}
// Extent2DFromPoints returns an Extent2D that bounds all of the provided
// points.
func Extent2DFromPoints(pts [][2]float32) Extent2D {
e := EmptyExtent2D()
for _, p := range pts {
for d := 0; d < 2; d++ {
if p[d] < e.p0[d] {
e.p0[d] = p[d]
}
if p[d] > e.p1[d] {
e.p1[d] = p[d]
}
}
}
return e
}
func (e Extent2D) Width() float32 {
return e.p1[0] - e.p0[0]
}
func (e Extent2D) Height() float32 {
return e.p1[1] - e.p0[1]
}
func (e Extent2D) Center() [2]float32 {
return [2]float32{(e.p0[0] + e.p1[0]) / 2, (e.p0[1] + e.p1[1]) / 2}
}
// Expand expands the extent by the given distance in all directions.
func (e Extent2D) Expand(d float32) Extent2D {
return Extent2D{
p0: [2]float32{e.p0[0] - d, e.p0[1] - d},
p1: [2]float32{e.p1[0] + d, e.p1[1] + d}}
}
func (e Extent2D) Inside(p [2]float32) bool {
return p[0] >= e.p0[0] && p[0] <= e.p1[0] && p[1] >= e.p0[1] && p[1] <= e.p1[1]
}
// Overlaps returns true if the two provided Extent2Ds overlap.
func Overlaps(a Extent2D, b Extent2D) bool {
x := (a.p1[0] >= b.p0[0]) && (a.p0[0] <= b.p1[0])
y := (a.p1[1] >= b.p0[1]) && (a.p0[1] <= b.p1[1])
return x && y
}
func Union(e Extent2D, p [2]float32) Extent2D {
e.p0[0] = min(e.p0[0], p[0])
e.p0[1] = min(e.p0[1], p[1])
e.p1[0] = max(e.p1[0], p[0])
e.p1[1] = max(e.p1[1], p[1])
return e
}
// ClosestPointInBox returns the closest point to p that is inside the
// Extent2D. (If p is already inside it, then it is returned.)
func (e Extent2D) ClosestPointInBox(p [2]float32) [2]float32 {
return [2]float32{clamp(p[0], e.p0[0], e.p1[0]), clamp(p[1], e.p0[1], e.p1[1])}
}
// IntersectRay find the intersections of the ray with given origin and
// direction with the Extent2D. The returned Boolean value indicates
// whether an intersection was found. If true, the two returned
// floating-point values give the parametric distances along the ray where
// the intersections occurred.
func (e Extent2D) IntersectRay(org, dir [2]float32) (bool, float32, float32) {
t0, t1 := float32(0), float32(1e30)
tx0 := (e.p0[0] - org[0]) / dir[0]
tx1 := (e.p1[0] - org[0]) / dir[0]
tx0, tx1 = min(tx0, tx1), max(tx0, tx1)
t0 = max(t0, tx0)
t1 = min(t1, tx1)
ty0 := (e.p0[1] - org[1]) / dir[1]
ty1 := (e.p1[1] - org[1]) / dir[1]
ty0, ty1 = min(ty0, ty1), max(ty0, ty1)
t0 = max(t0, ty0)
t1 = min(t1, ty1)
return t0 < t1, t0, t1
}
func (e Extent2D) Offset(p [2]float32) Extent2D {
return Extent2D{p0: add2f(e.p0, p), p1: add2f(e.p1, p)}
}
func (e Extent2D) Scale(s float32) Extent2D {
return Extent2D{p0: scale2f(e.p0, s), p1: scale2f(e.p1, s)}
}
func (e Extent2D) Lerp(p [2]float32) [2]float32 {
return [2]float32{lerp(p[0], e.p0[0], e.p1[0]), lerp(p[1], e.p0[1], e.p1[1])}
}
///////////////////////////////////////////////////////////////////////////
// Geometry
// LineLineIntersect returns the intersection point of the two lines
// specified by the vertices (p1f, p2f) and (p3f, p4f). An additional
// returned Boolean value indicates whether a valid intersection was found.
// (There's no intersection for parallel lines, and none may be found in
// cases with tricky numerics.)
func LineLineIntersect(p1f, p2f, p3f, p4f [2]float32) ([2]float32, bool) {
// It's important to do this in float64, given differences of
// similar-ish values...
p1 := [2]float64{float64(p1f[0]), float64(p1f[1])}
p2 := [2]float64{float64(p2f[0]), float64(p2f[1])}
p3 := [2]float64{float64(p3f[0]), float64(p3f[1])}
p4 := [2]float64{float64(p4f[0]), float64(p4f[1])}
d12 := [2]float64{p1[0] - p2[0], p1[1] - p2[1]}
d34 := [2]float64{p3[0] - p4[0], p3[1] - p4[1]}
denom := d12[0]*d34[1] - d12[1]*d34[0]
if math.Abs(denom) < 1e-5 { // TODO: threshold?
return [2]float32{}, false
}
numx := (p1[0]*p2[1]-p1[1]*p2[0])*(p3[0]-p4[0]) - (p1[0]-p2[0])*(p3[0]*p4[1]-p3[1]*p4[0])
numy := (p1[0]*p2[1]-p1[1]*p2[0])*(p3[1]-p4[1]) - (p1[1]-p2[1])*(p3[0]*p4[1]-p3[1]*p4[0])
return [2]float32{float32(numx / denom), float32(numy / denom)}, true
}
// RayRayMinimumDistance takes two rays p0+d0*t and p1+d1*t and returns the
// value of t where their distance is minimized.
func RayRayMinimumDistance(p0, d0, p1, d1 [2]float32) float32 {
/*
Mathematica:
f[t_] := {ax, ay} + {bx, by} * t
g[t_] := {cx, cy} + {dx, dy} * t
d2 = Dot[f[t] - g[t], f[t] - g[t]]
Solve[D[d2, t] == 0, t]
CForm[...]
Then substitute ax -> p0[0], etc.
*/
t := (d0[0]*p1[0] + d0[1]*p1[1] - p1[0]*d1[0] + p0[0]*(-d0[0]+d1[0]) - p1[1]*d1[1] + p0[1]*(-d0[1]+d1[1])) /
((d0[0] * d0[0]) + (d0[1] * d0[1]) - 2*d0[0]*d1[0] + (d1[0] * d1[0]) - 2*d0[1]*d1[1] + (d1[1] * d1[1]))
return t
}
// SignedPointLineDistance returns the signed distance from the point p to
// the infinite line defined by (p0, p1) where points to the right of the
// line have negative distances.
func SignedPointLineDistance(p, p0, p1 [2]float32) float32 {
// https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line
dx, dy := p1[0]-p0[0], p1[1]-p0[1]
sq := dx*dx + dy*dy
if sq == 0 {
return float32(math.Inf(1))
}
return (dx*(p0[1]-p[1]) - dy*(p0[0]-p[0])) / sqrt(sq)
}
// PointLineDistance returns the minimum distance from the point p to the infinite line defined by (p0, p1).
func PointLineDistance(p, p0, p1 [2]float32) float32 {
return abs(SignedPointLineDistance(p, p0, p1))
}
// Returns the vertex coordinates of an equilateral triangle centered at
// the origin with specified height.
func EquilateralTriangleVertices(height float32) [3][2]float32 {
const InvSqrt3 = 0.577350269189626
return [3][2]float32{
[2]float32{0, height * 2 / 3},
[2]float32{height * InvSqrt3, -height / 3},
[2]float32{-height * InvSqrt3, -height / 3},
}
}
func PointInPolygon(p Point2LL, pts []Point2LL) bool {
inside := false
for i := 0; i < len(pts)-1; i++ {
p0, p1 := pts[i], pts[i+1]
if (p0[1] <= p[1] && p[1] < p1[1]) || (p1[1] <= p[1] && p[1] < p0[1]) {
x := p0[0] + (p[1]-p0[1])*(p1[0]-p0[0])/(p1[1]-p0[1])
if x > p[0] {
inside = !inside
}
}
}
return inside
}
///////////////////////////////////////////////////////////////////////////
// RGB
type RGB struct {
R, G, B float32
}
type RGBA struct {
R, G, B, A float32
}
func lerpRGB(x float32, a, b RGB) RGB {
return RGB{R: lerp(x, a.R, b.R), G: lerp(x, a.G, b.G), B: lerp(x, a.B, b.B)}
}
func (r RGB) Equals(other RGB) bool {
return r.R == other.R && r.G == other.G && r.B == other.B
}
func (r RGB) Scale(v float32) RGB {
return RGB{R: r.R * v, G: r.G * v, B: r.B * v}
}
// RGBFromHex converts a packed integer color value to an RGB where the low
// 8 bits give blue, the next 8 give green, and then the next 8 give red.
func RGBFromHex(c int) RGB {
r, g, b := (c>>16)&255, (c>>8)&255, c&255
return RGB{R: float32(r) / 255, G: float32(g) / 255, B: float32(b) / 255}
}
///////////////////////////////////////////////////////////////////////////
// Point2LL
const NauticalMilesToFeet = 6076.12
const FeetToNauticalMiles = 1 / NauticalMilesToFeet
// Point2LL represents a 2D point on the Earth in latitude-longitude.
// Important: 0 (x) is longitude, 1 (y) is latitude
type Point2LL [2]float32
func (p Point2LL) Longitude() float32 {
return p[0]
}
func (p Point2LL) Latitude() float32 {
return p[1]
}
// DDString returns the position in decimal degrees, e.g.:
// (39.860901, -75.274864)
func (p Point2LL) DDString() string {
return fmt.Sprintf("(%f, %f)", p[1], p[0]) // latitude, longitude
}
// DMSString returns the position in degrees minutes, seconds, e.g.
// N039.51.39.243, W075.16.29.511
func (p Point2LL) DMSString() string {
format := func(v float32) string {
s := fmt.Sprintf("%03d", int(v))
v -= floor(v)
v *= 60
s += fmt.Sprintf(".%02d", int(v))
v -= floor(v)
v *= 60
s += fmt.Sprintf(".%02d", int(v))
v -= floor(v)
v *= 1000
s += fmt.Sprintf(".%03d", int(v))
return s
}
var s string
if p[1] > 0 {
s = "N"
} else {
s = "S"
}
s += format(abs(p[1]))
if p[0] > 0 {
s += ",E"
} else {
s += ",W"
}
s += format(abs(p[0]))
return s
}
var (
// pair of floats (no exponents)
reWaypointFloat = regexp.MustCompile(`^(\-?[0-9]+\.[0-9]+), *(\-?[0-9]+\.[0-9]+)`)
// https://en.wikipedia.org/wiki/ISO_6709#String_expression_(Annex_H)
// e.g. +403527.580-0734452.955
reISO6709H = regexp.MustCompile(`^([-+][0-9][0-9])([0-9][0-9])([0-9][0-9])\.([0-9][0-9][0-9])([-+][0-9][0-9][0-9])([0-9][0-9])([0-9][0-9])\.([0-9][0-9][0-9])`)
)
// Parse waypoints of the form "N40.37.58.400, W073.46.17.000". Previously
// we would match the following regexp and then peel apart the pieces but
// profiling showed that the majority of the time spent parsing the current
// video maps was spent in this function. Thus, a specialized
// implementation that is about 12x faster and reduces overall time spent
// parsing video maps at startup (including zstd decompression and JSON
// parsing) from ~2.5s to about 0.75s.
//
// For posterity, said regexp:
// reWaypointDotted = regexp.MustCompile(`^([NS][0-9]+\.[0-9]+\.[0-9]+\.[0-9]+), *([EW][0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)`)
func tryParseWaypointDotted(b []byte) (Point2LL, bool) {
if len(b) == 0 || (b[0] != 'N' && b[0] != 'S') {
return Point2LL{}, false
}
negateLatitude := b[0] == 'S'
// Skip over the N/S and parse the four dotted numbers following it
b = b[1:]
latitude, n, ok := tryParseWaypointNumbers(b)
if !ok {
return Point2LL{}, false
}
if negateLatitude {
latitude = -latitude
}
// Skip what's been processed
b = b[n:]
// Skip comma
if len(b) == 0 || b[0] != ',' {
return Point2LL{}, false
}
b = b[1:]
// Skip optional space
if len(b) > 0 && b[0] == ' ' {
b = b[1:]
}
// Onward to E/W
if len(b) == 0 || (b[0] != 'E' && b[0] != 'W') {
return Point2LL{}, false
}
negateLongitude := b[0] == 'W'
// Skip over E/W and parse its four dotted numbers.
b = b[1:]
longitude, _, ok := tryParseWaypointNumbers(b)
if !ok {
return Point2LL{}, false
}
if negateLongitude {
longitude = -longitude
}
return Point2LL{longitude, latitude}, true
}
// Efficient function parse a latlong of the form aaa.bbb.ccc.ddd and
// return the corresponding float32. Returns the latlong, the number of
// bytes of b consumed, and a bool indicating success or failure.
func tryParseWaypointNumbers(b []byte) (float32, int, bool) {
n := 0
var ll float64
// Scan to the end of the current number group; return
// the number of bytes it uses.
scan := func(b []byte) int {
for i, v := range b {
if v == '.' || v == ',' {
return i
}
}
return len(b)
}
for i := 0; i < 4; i++ {
end := scan(b)
if end == 0 {
return 0, 0, false
}
value := 0
for _, ch := range b[:end] {
if ch < '0' || ch > '9' {
return 0, 0, false
}
value *= 10
value += int(ch - '0')
}
if i == 3 {
// Treat the last set of digits as a decimal, so that
// Nxx.yy.zz.1 is handled like Nxx.yy.zz.100.
for j := end; j < 3; j++ {
value *= 10
}
}
scales := [4]float64{1, 60, 3600, 3600000}
ll += float64(value) / scales[i]
n += end
b = b[end:]
if i < 3 {
if len(b) == 0 {
return 0, 0, false
}
b = b[1:]
n++
}
}
return float32(ll), n, true
}
func ParseLatLong(llstr []byte) (Point2LL, error) {
// First try to match e.g. "N040.44.21.753,W075.41.55.347". Try this
// first and by hand rather than with a regexp, since the video map
// files are full of these.
if p, ok := tryParseWaypointDotted(llstr); ok {
return p, nil
} else if strs := reWaypointFloat.FindStringSubmatch(string(llstr)); len(strs) == 3 {
if l, err := strconv.ParseFloat(strs[1], 32); err != nil {
return Point2LL{}, err
} else {
p[1] = float32(l)
}
if l, err := strconv.ParseFloat(strs[2], 32); err != nil {
return Point2LL{}, err
} else {
p[0] = float32(l)
}
return p, nil
} else if strs := reISO6709H.FindStringSubmatch(string(llstr)); len(strs) == 9 {
parse := func(deg, min, sec, frac string) (float32, error) {
d, err := strconv.Atoi(deg)
if err != nil {
return 0, err
}
m, err := strconv.Atoi(min)
if err != nil {
return 0, err
}
s, err := strconv.Atoi(sec)
if err != nil {
return 0, err
}
f, err := strconv.Atoi(frac)
if err != nil {
return 0, err
}
sgn := sign(float32(d))
d = abs(d)
return sgn * (float32(d) + float32(m)/60 + float32(s)/3600 + float32(f)/3600000), nil
}
var err error
p[1], err = parse(strs[1], strs[2], strs[3], strs[4])
if err != nil {
return Point2LL{}, err
}
p[0], err = parse(strs[5], strs[6], strs[7], strs[8])
if err != nil {
return Point2LL{}, err
}
return p, nil
} else {
return Point2LL{}, fmt.Errorf("%s: invalid latlong string", llstr)
}
}
func (p Point2LL) IsZero() bool {
return p[0] == 0 && p[1] == 0
}
func add2ll(a Point2LL, b Point2LL) Point2LL {
return Point2LL(add2f(a, b))
}
func mid2ll(a Point2LL, b Point2LL) Point2LL {
return Point2LL(mid2f(a, b))
}
func sub2ll(a Point2LL, b Point2LL) Point2LL {
return Point2LL(sub2f(a, b))
}
func scale2ll(a Point2LL, s float32) Point2LL {
return Point2LL(scale2f(a, s))
}
func lerp2ll(x float32, a Point2LL, b Point2LL) Point2LL {
return Point2LL(lerp2f(x, a, b))
}
func length2ll(v Point2LL) float32 {
return length2f(v)
}
// nmdistance2ll returns the distance in nautical miles between two
// provided lat-long coordinates.
func nmdistance2ll(a Point2LL, b Point2LL) float32 {
dlat := (a[1] - b[1]) * scenarioGroup.NmPerLatitude
dlong := (a[0] - b[0]) * scenarioGroup.NmPerLongitude
return sqrt(sqr(dlat) + sqr(dlong))
}
// nmlength2ll returns the length of a vector expressed in lat-long
// coordinates.
func nmlength2ll(a Point2LL) float32 {
x := a[0] * scenarioGroup.NmPerLongitude
y := a[1] * scenarioGroup.NmPerLatitude
return sqrt(sqr(x) + sqr(y))
}
// nm2ll converts a point expressed in nautical mile coordinates to
// lat-long.
func nm2ll(p [2]float32) Point2LL {
return Point2LL{p[0] / scenarioGroup.NmPerLongitude, p[1] / scenarioGroup.NmPerLatitude}
}
// ll2nm converts a point expressed in latitude-longitude coordinates to
// nautical mile coordinates; this is useful for example for reasoning
// about distances, since both axes then have the same measure.
func ll2nm(p Point2LL) [2]float32 {
return [2]float32{p[0] * scenarioGroup.NmPerLongitude, p[1] * scenarioGroup.NmPerLatitude}
}
func normalize2ll(a Point2LL) Point2LL {
l := length2ll(a)
if l == 0 {
return Point2LL{0, 0}
}
return scale2ll(a, 1/l)
}
// Store Point2LLs as strings is JSON, for compactness/friendliness...
func (p Point2LL) MarshalJSON() ([]byte, error) {
return []byte("\"" + p.DMSString() + "\""), nil
}
func (p *Point2LL) UnmarshalJSON(b []byte) error {
if b[0] == '[' {
// Backwards compatibility for arrays of two floats...
var pt [2]float32
err := json.Unmarshal(b, &pt)
if err == nil {
*p = pt
}
return err
} else {
n := len(b)
// Remove the quotes before parsing
b = b[1 : n-1]
pt, err := ParseLatLong(b)
if err == nil {
*p = pt
return nil
}
s := string(b)
if n, ok := database.Navaids[s]; ok {
*p = n.Location
return nil
} else if n, ok := database.Airports[s]; ok {
*p = n.Location
return nil
} else if f, ok := database.Fixes[s]; ok {
*p = f.Location
return nil
} else {
return err
}
}
}
///////////////////////////////////////////////////////////////////////////
// point 2f
// Various useful functions for arithmetic with 2D points/vectors.
// Names are brief in order to avoid clutter when they're used.
// a+b
func add2f(a [2]float32, b [2]float32) [2]float32 {
return [2]float32{a[0] + b[0], a[1] + b[1]}
}
// midpoint of a and b
func mid2f(a [2]float32, b [2]float32) [2]float32 {
return scale2f(add2f(a, b), 0.5)
}
// a-b
func sub2f(a [2]float32, b [2]float32) [2]float32 {
return [2]float32{a[0] - b[0], a[1] - b[1]}
}
// a*s
func scale2f(a [2]float32, s float32) [2]float32 {
return [2]float32{s * a[0], s * a[1]}
}
// Linearly interpolate x of the way between a and b. x==0 corresponds to
// a, x==1 corresponds to b, etc.
func lerp2f(x float32, a [2]float32, b [2]float32) [2]float32 {
return [2]float32{(1-x)*a[0] + x*b[0], (1-x)*a[1] + x*b[1]}
}
// Length of v
func length2f(v [2]float32) float32 {
return sqrt(v[0]*v[0] + v[1]*v[1])
}
// Distance between two points
func distance2f(a [2]float32, b [2]float32) float32 {
return length2f(sub2f(a, b))
}
// Normalizes the given vector.
func normalize2f(a [2]float32) [2]float32 {
l := length2f(a)
if l == 0 {
return [2]float32{0, 0}
}
return scale2f(a, 1/l)
}
// rotator2f returns a function that rotates points by the specified angle
// (given in degrees).
func rotator2f(angle float32) func([2]float32) [2]float32 {
s, c := sin(radians(angle)), cos(radians(angle))
return func(p [2]float32) [2]float32 {
return [2]float32{c*p[0] + s*p[1], -s*p[0] + c*p[1]}
}
}
///////////////////////////////////////////////////////////////////////////
// generics
// FlattenMap takes a map and returns separate slices corresponding to the
// keys and values stored in the map. (The slices are ordered so that the
// i'th key corresponds to the i'th value, needless to say.)
func FlattenMap[K comparable, V any](m map[K]V) ([]K, []V) {
keys := make([]K, 0, len(m))
values := make([]V, 0, len(m))
for k, v := range m {