-
Notifications
You must be signed in to change notification settings - Fork 77
Expand file tree
/
Copy pathsimulationEngine.ts
More file actions
1398 lines (1243 loc) · 50.9 KB
/
Copy pathsimulationEngine.ts
File metadata and controls
1398 lines (1243 loc) · 50.9 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
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
import nearestPointOnLine from '@turf/nearest-point-on-line'
import type { Feature, LineString } from 'geojson'
import type { TransitData, VehiclePosition, Trip, LRTLine, BusRoute, BusStop, Flight, Ferry, ScheduleType } from '../types'
import { FERRY_BERTHS_BY_TERMINAL, FERRY_COLOR_BY_OPERATOR } from './ferryBerths'
import { FERRY_ROUTES, interpolatePath, pathLengthMeters } from './ferryRoutes'
import { macauWeekday, macauMinutesOfDay } from '../macauTime'
function getScheduleType(date: Date): ScheduleType {
const day = macauWeekday(date)
if (day === 5) return 'friday'
if (day === 0 || day === 6) return 'sat_sun'
return 'mon_thu'
}
export { getScheduleType }
export interface BusServiceWindow {
start: number
end: number
}
export type BusServiceBucket = 'weekday' | 'sat' | 'sun'
export function getBusServiceBucket(date: Date): BusServiceBucket {
const day = macauWeekday(date)
if (day === 0) return 'sun'
if (day === 6) return 'sat'
return 'weekday'
}
function normalizeBusServiceBucket(bucket: BusServiceBucket | boolean = 'weekday'): BusServiceBucket {
if (bucket === true) return 'sun'
if (bucket === false) return 'weekday'
return bucket
}
export function getBusServiceWindow(
route: BusRoute,
bucket: BusServiceBucket | boolean = 'weekday',
): BusServiceWindow | null {
const serviceBucket = normalizeBusServiceBucket(bucket)
if (
serviceBucket === 'sat'
&& route.serviceHoursStartSat !== undefined
&& route.serviceHoursEndSat !== undefined
) {
if (route.serviceHoursStartSat === null || route.serviceHoursEndSat === null) return null
return { start: route.serviceHoursStartSat, end: route.serviceHoursEndSat }
}
if (
serviceBucket === 'sun'
&& route.serviceHoursStartSun !== undefined
&& route.serviceHoursEndSun !== undefined
) {
if (route.serviceHoursStartSun === null || route.serviceHoursEndSun === null) return null
return { start: route.serviceHoursStartSun, end: route.serviceHoursEndSun }
}
const start = route.serviceHoursStart
const end = route.serviceHoursEnd
if (start === null || end === null) return null
return { start, end }
}
function timeToMinutes(date: Date): number {
return macauMinutesOfDay(date)
}
// Per-polyline precomputation for fast progress → (position, bearing) lookup.
//
// Hot path: interpolateOnLine runs once per vehicle per sim tick (~20 Hz ×
// 300–400 vehicles). The naive implementation — turf's along() — walks the
// coordinate array from index 0 and sums haversine distances until it hits
// the target km. That's O(n) haversines per call, and the engine originally
// invoked it twice per vehicle (position + lookahead for bearing), giving
// ~12k full-route scans per second. For 100–150 point bus routes this was
// the single biggest CPU sink on the main thread.
//
// Key insight: the geometry is immutable, so the per-segment work (length
// and heading) only needs to happen once. We cache:
// - cumKm[i] cumulative km from coords[0] to coords[i]
// - segBearing[i] heading of the segment coords[i] → coords[i+1]
//
// Per-call cost then drops to:
// - one binary search on cumKm to locate the segment (O(log n) compares)
// - one linear interpolation between two lat/lng pairs (plain arithmetic)
// - one table lookup for bearing (no second along())
//
// No trig in the hot loop, no walking the array, no WeakMap miss after the
// first touch. We intentionally do NOT cache a per-line lastIdx hint:
// multiple vehicles share a line at wildly different progress values, so a
// shared hint would thrash. log₂(150) ≈ 8 comparisons is already cheap
// enough that per-vehicle hints aren't worth the state.
type LineCache = {
coords: [number, number][]
cumKm: Float64Array
segBearing: Float64Array
totalKm: number
}
const lineCache = new WeakMap<Feature<LineString>, LineCache>()
const EARTH_KM = 6371
function haversineKm(a: [number, number], b: [number, number]): number {
const dLat = ((b[1] - a[1]) * Math.PI) / 180
const dLng = ((b[0] - a[0]) * Math.PI) / 180
const lat1 = (a[1] * Math.PI) / 180
const lat2 = (b[1] * Math.PI) / 180
const h =
Math.sin(dLat / 2) ** 2 +
Math.sin(dLng / 2) ** 2 * Math.cos(lat1) * Math.cos(lat2)
return 2 * EARTH_KM * Math.asin(Math.sqrt(h))
}
function getLineCache(line: Feature<LineString>): LineCache {
let c = lineCache.get(line)
if (c) return c
const coords = line.geometry.coordinates as [number, number][]
const n = coords.length
const cumKm = new Float64Array(n)
const segBearing = new Float64Array(Math.max(0, n - 1))
for (let i = 1; i < n; i++) {
cumKm[i] = cumKm[i - 1] + haversineKm(coords[i - 1], coords[i])
const dx = coords[i][0] - coords[i - 1][0]
const dy = coords[i][1] - coords[i - 1][1]
segBearing[i - 1] = (Math.atan2(dx, dy) * 180) / Math.PI
}
c = { coords, cumKm, segBearing, totalKm: n > 0 ? cumKm[n - 1] : 0 }
lineCache.set(line, c)
return c
}
function getLineLength(line: Feature<LineString>): number {
return getLineCache(line).totalKm
}
export function interpolateOnLine(
line: Feature<LineString>,
progress: number
): { coordinates: [number, number]; bearing: number } {
const c = getLineCache(line)
const coords = c.coords
const n = coords.length
if (n < 2) return { coordinates: coords[0] ?? [0, 0], bearing: 0 }
const totalKm = c.totalKm
const targetKm = Math.max(0, Math.min(totalKm, progress * totalKm))
// Binary search: find largest i such that cumKm[i] <= targetKm (0..n-2)
const cum = c.cumKm
let lo = 0
let hi = n - 1
while (lo < hi) {
const mid = (lo + hi + 1) >>> 1
if (cum[mid] <= targetKm) lo = mid
else hi = mid - 1
}
const i = Math.min(lo, n - 2)
const segKm = cum[i + 1] - cum[i]
const t = segKm > 0 ? (targetKm - cum[i]) / segKm : 0
const [x0, y0] = coords[i]
const [x1, y1] = coords[i + 1]
return {
coordinates: [x0 + (x1 - x0) * t, y0 + (y1 - y0) * t],
bearing: c.segBearing[i],
}
}
// Position + tangent bearing sampled as the chord from (progress − δ) to
// (progress + δ) along the line. The per-segment `segBearing` lookup in
// `interpolateOnLine` is piecewise-constant, so a long rigid body (e.g. the
// 57 m two-car LRT) snaps visibly each time its pivot crosses a segment
// boundary on a curved viaduct. Averaging a short arc window smooths those
// step transitions into a continuous heading. windowKm controls the arc
// length (±), default 15 m — small enough to still track real curves, large
// enough to hide segment steps in the source polyline.
function pointAtKm(coords: [number, number][], cum: Float64Array, km: number): [number, number] {
const n = coords.length
let lo = 0
let hi = n - 1
while (lo < hi) {
const mid = (lo + hi + 1) >>> 1
if (cum[mid] <= km) lo = mid
else hi = mid - 1
}
const i = Math.min(lo, n - 2)
const segKm = cum[i + 1] - cum[i]
const t = segKm > 0 ? (km - cum[i]) / segKm : 0
const [x0, y0] = coords[i]
const [x1, y1] = coords[i + 1]
return [x0 + (x1 - x0) * t, y0 + (y1 - y0) * t]
}
export function interpolateOnLineSmooth(
line: Feature<LineString>,
progress: number,
windowKm = 0.015,
): { coordinates: [number, number]; bearing: number } {
const c = getLineCache(line)
const coords = c.coords
const n = coords.length
if (n < 2) return { coordinates: coords[0] ?? [0, 0], bearing: 0 }
const totalKm = c.totalKm
const targetKm = Math.max(0, Math.min(totalKm, progress * totalKm))
const cum = c.cumKm
const here = pointAtKm(coords, cum, targetKm)
const aKm = Math.max(0, targetKm - windowKm)
const bKm = Math.min(totalKm, targetKm + windowKm)
// Fall back to the segment bearing if the window collapses (at endpoints
// the tangent would degenerate).
if (bKm - aKm < 1e-6) {
return { coordinates: here, bearing: c.segBearing[Math.min(n - 2, Math.max(0, n - 2))] }
}
const pa = pointAtKm(coords, cum, aKm)
const pb = pointAtKm(coords, cum, bKm)
const dx = pb[0] - pa[0]
const dy = pb[1] - pa[1]
const bearing = (Math.atan2(dx, dy) * 180) / Math.PI
return { coordinates: here, bearing }
}
function computeLRTVehicles(
trips: Trip[],
lines: LRTLine[],
stationProgressMap: Map<string, { progress: number }>,
nowMinutes: number
): VehiclePosition[] {
const vehicles: VehiclePosition[] = []
const lineMap = new Map(lines.map(l => [l.id, l]))
for (const trip of trips) {
const line = lineMap.get(trip.lineId)
if (!line) continue
const entries = trip.entries
if (entries.length < 2) continue
const firstArr = entries[0].arrivalMinutes
const lastDep = entries[entries.length - 1].departureMinutes ?? entries[entries.length - 1].arrivalMinutes
let effective = nowMinutes
if (nowMinutes < firstArr && nowMinutes + 1440 >= firstArr && nowMinutes + 1440 <= lastDep) {
effective = nowMinutes + 1440
}
if (effective < firstArr || effective > lastDep) continue
let overallProgress: number | null = null
for (let i = 0; i < entries.length; i++) {
const e = entries[i]
const dep = e.departureMinutes ?? e.arrivalMinutes
if (effective >= e.arrivalMinutes && effective <= dep) {
const key = `${trip.lineId}:${e.stationId}`
overallProgress = stationProgressMap.get(key)?.progress ?? (i / (entries.length - 1))
break
}
if (i < entries.length - 1) {
const next = entries[i + 1]
if (effective > dep && effective < next.arrivalMinutes) {
const travelDuration = next.arrivalMinutes - dep
const segProgress = travelDuration > 0
? (effective - dep) / travelDuration
: 0
const fromKey = `${trip.lineId}:${e.stationId}`
const toKey = `${trip.lineId}:${next.stationId}`
const fromP = stationProgressMap.get(fromKey)?.progress ?? (i / (entries.length - 1))
const toP = stationProgressMap.get(toKey)?.progress ?? ((i + 1) / (entries.length - 1))
overallProgress = fromP + (toP - fromP) * segProgress
break
}
}
}
if (overallProgress === null) continue
overallProgress = Math.max(0, Math.min(1, overallProgress))
const pos = interpolateOnLineSmooth(line.geometry, overallProgress)
vehicles.push({
id: trip.id,
lineId: trip.lineId,
type: 'lrt',
coordinates: pos.coordinates,
bearing: pos.bearing,
progress: overallProgress,
color: line.color,
})
}
return vehicles
}
export const DWELL_SEC = 8
export interface BusStopScheduleEntry {
stopId: string
progress: number
arriveSec: number
departSec: number
}
export interface BusSchedule {
tripDurationSec: number
cycleSec: number
isCircular: boolean
totalLenKm: number
forwardStops: BusStopScheduleEntry[]
backwardStops: BusStopScheduleEntry[]
}
function projectPointOnSegment(
a: [number, number],
b: [number, number],
p: [number, number],
): { alongKm: number; distKm: number; segLenKm: number } {
const midLatRad = ((a[1] + b[1]) / 2) * Math.PI / 180
const kmPerDegLat = 110.574
const kmPerDegLon = 111.32 * Math.cos(midLatRad)
const ax = a[0] * kmPerDegLon, ay = a[1] * kmPerDegLat
const bx = b[0] * kmPerDegLon, by = b[1] * kmPerDegLat
const px = p[0] * kmPerDegLon, py = p[1] * kmPerDegLat
const dx = bx - ax, dy = by - ay
const segLenKm = Math.sqrt(dx * dx + dy * dy)
let t = 0
if (segLenKm > 0) {
t = ((px - ax) * dx + (py - ay) * dy) / (segLenKm * segLenKm)
t = Math.max(0, Math.min(1, t))
}
const cx = ax + t * dx, cy = ay + t * dy
const distKm = Math.sqrt((px - cx) ** 2 + (py - cy) ** 2)
return { alongKm: t * segLenKm, distKm, segLenKm }
}
function projectStopsOrdered(
coords: [number, number][],
cumKm: number[],
totalLenKm: number,
stopIds: string[],
busStopMap: Map<string, BusStop>,
): number[] {
const out: number[] = new Array(stopIds.length).fill(0)
if (totalLenKm <= 0 || coords.length < 2) return out
const N = stopIds.length
const firstEqualsLast = N > 1 && stopIds[0] === stopIds[N - 1]
// Window: a self-crossing polyline can pass near a stop in multiple
// places. Constrain each ordered pickup to "a few segment-spacings
// ahead" so one globally-nearest late-loop projection doesn't push
// the cursor past all remaining stops.
const avgStepKm = totalLenKm / Math.max(1, N - 1)
const windowKm = Math.max(avgStepKm * 3, 1.0)
let cursorKm = 0
for (let idx = 0; idx < N; idx++) {
const stop = busStopMap.get(stopIds[idx])
if (!stop) { out[idx] = cursorKm / totalLenKm; continue }
if (idx === 0 && firstEqualsLast) { out[0] = 0; cursorKm = 0; continue }
if (idx === N - 1 && firstEqualsLast) { out[idx] = 1; cursorKm = totalLenKm; continue }
const hiKm = cursorKm + windowKm
let bestDist = Infinity
let bestKm = cursorKm
for (let i = 1; i < coords.length; i++) {
if (cumKm[i] < cursorKm) continue
if (cumKm[i - 1] > hiKm) break
const { alongKm, distKm } = projectPointOnSegment(coords[i - 1], coords[i], stop.coordinates)
let candidateKm = cumKm[i - 1] + alongKm
if (candidateKm < cursorKm) candidateKm = cursorKm
if (candidateKm > hiKm) candidateKm = hiKm
if (distKm < bestDist) { bestDist = distKm; bestKm = candidateKm }
}
// Fallback: no segment within the window got close (> 300m). Scan
// all remaining and take the globally nearest — better than stuck.
if (bestDist > 0.3) {
for (let i = 1; i < coords.length; i++) {
if (cumKm[i] < cursorKm) continue
const { alongKm, distKm } = projectPointOnSegment(coords[i - 1], coords[i], stop.coordinates)
let candidateKm = cumKm[i - 1] + alongKm
if (candidateKm < cursorKm) candidateKm = cursorKm
if (distKm < bestDist) { bestDist = distKm; bestKm = candidateKm }
}
}
out[idx] = bestKm / totalLenKm
cursorKm = bestKm
}
return out
}
function projectStopsUnordered(
routeGeom: Feature<LineString>,
totalLenKm: number,
stopIds: string[],
busStopMap: Map<string, BusStop>,
): number[] {
const out: number[] = new Array(stopIds.length).fill(0)
if (totalLenKm <= 0) return out
for (let idx = 0; idx < stopIds.length; idx++) {
const stop = busStopMap.get(stopIds[idx])
if (!stop) continue
const projected = nearestPointOnLine(routeGeom, stop.coordinates, { units: 'kilometers' })
const dist = (projected.properties.location ?? 0) as number
out[idx] = Math.max(0, Math.min(1, dist / totalLenKm))
}
return out
}
function buildDirectionSchedule(
stopIds: string[],
stopProgs: number[],
tripDurationSec: number,
sign: 1 | -1,
startProgress: number,
): BusStopScheduleEntry[] {
const EPS = 0.0001
const cleaned: { stopId: string; progress: number }[] = []
let prev = startProgress - sign * EPS
for (let i = 0; i < stopIds.length; i++) {
let p = Math.max(0, Math.min(1, stopProgs[i]))
if ((p - prev) * sign <= EPS) p = prev + sign * EPS
p = Math.max(0, Math.min(1, p))
cleaned.push({ stopId: stopIds[i], progress: p })
prev = p
}
const N = cleaned.length
if (N === 0) return []
const dwellTotal = N * DWELL_SEC
const moveTimeSec = Math.max(1, tripDurationSec - dwellTotal)
const endProgress = sign === 1 ? 1 : 0
const gaps: number[] = []
let cur = startProgress
for (const s of cleaned) { gaps.push(Math.abs(s.progress - cur)); cur = s.progress }
gaps.push(Math.abs(endProgress - cur))
const totalGap = gaps.reduce((a, b) => a + b, 0) || 1
const scale = moveTimeSec / totalGap
const result: BusStopScheduleEntry[] = []
let cursorTime = 0
for (let i = 0; i < N; i++) {
cursorTime += gaps[i] * scale
const arriveSec = cursorTime
const departSec = arriveSec + DWELL_SEC
cursorTime = departSec
result.push({ stopId: cleaned[i].stopId, progress: cleaned[i].progress, arriveSec, departSec })
}
return result
}
const busScheduleCache = new WeakMap<BusRoute, BusSchedule>()
export function getBusSchedule(route: BusRoute, busStopMap: Map<string, BusStop>): BusSchedule | null {
const cached = busScheduleCache.get(route)
if (cached) return cached
const coords = (route.geometry.geometry?.coordinates ?? []) as [number, number][]
if (coords.length < 2) return null
const totalLenKm = getLineLength(route.geometry)
if (totalLenKm < 0.01) return null
const cumKm: number[] = [0]
for (let i = 1; i < coords.length; i++) {
const { segLenKm } = projectPointOnSegment(coords[i - 1], coords[i], coords[i])
cumKm.push(cumKm[i - 1] + segLenKm)
}
const isCircular = route.routeType === 'circular'
const tripDurationSec = (totalLenKm < 5 ? 30 : 60) * 60
const cycleSec = isCircular ? tripDurationSec : tripDurationSec * 2
const stopProgFwd = isCircular
? projectStopsOrdered(coords, cumKm, totalLenKm, route.stopsForward, busStopMap)
: projectStopsUnordered(route.geometry, totalLenKm, route.stopsForward, busStopMap)
const stopProgBwd = !isCircular
? projectStopsUnordered(route.geometry, totalLenKm, route.stopsBackward, busStopMap)
: []
const forwardStops = buildDirectionSchedule(route.stopsForward, stopProgFwd, tripDurationSec, 1, 0)
const backwardStops = !isCircular
? buildDirectionSchedule(route.stopsBackward, stopProgBwd, tripDurationSec, -1, 1)
: []
const schedule: BusSchedule = {
tripDurationSec, cycleSec, isCircular, totalLenKm, forwardStops, backwardStops,
}
busScheduleCache.set(route, schedule)
return schedule
}
function progressAtDirection(
stops: BusStopScheduleEntry[],
startProgress: number,
endProgress: number,
tripDurationSec: number,
dirSec: number,
): number {
const t = Math.max(0, Math.min(tripDurationSec, dirSec))
if (stops.length === 0) {
if (tripDurationSec <= 0) return startProgress
return startProgress + (endProgress - startProgress) * (t / tripDurationSec)
}
for (let i = 0; i < stops.length; i++) {
const s = stops[i]
if (t <= s.departSec) {
if (t <= s.arriveSec) {
const prevDepart = i > 0 ? stops[i - 1].departSec : 0
const prevProg = i > 0 ? stops[i - 1].progress : startProgress
const seg = s.arriveSec - prevDepart
if (seg <= 0) return s.progress
const f = (t - prevDepart) / seg
return prevProg + (s.progress - prevProg) * f
}
return s.progress
}
}
const last = stops[stops.length - 1]
const seg = tripDurationSec - last.departSec
if (seg <= 0) return endProgress
const f = (t - last.departSec) / seg
return last.progress + (endProgress - last.progress) * f
}
export function progressAtCycle(schedule: BusSchedule, cycleSec: number): number {
const wrapped = ((cycleSec % schedule.cycleSec) + schedule.cycleSec) % schedule.cycleSec
if (schedule.isCircular) {
return progressAtDirection(schedule.forwardStops, 0, 1, schedule.tripDurationSec, wrapped)
}
if (wrapped <= schedule.tripDurationSec) {
return progressAtDirection(schedule.forwardStops, 0, 1, schedule.tripDurationSec, wrapped)
}
return progressAtDirection(
schedule.backwardStops, 1, 0, schedule.tripDurationSec, wrapped - schedule.tripDurationSec
)
}
export function computeBusCycleSec(
vehicleId: string,
schedule: BusSchedule,
route: BusRoute,
nowMinutes: number,
serviceBucket: BusServiceBucket | boolean = 'weekday',
): number {
const vIndex = parseInt(vehicleId.split('-').pop() ?? '0', 10) || 0
const window = getBusServiceWindow(route, serviceBucket)
if (!window) return 0
const startMin = window.start * 60
let endMin = window.end * 60
if (endMin <= startMin) endMin += 1440
const cycleMin = schedule.cycleSec / 60
let effectiveNow = nowMinutes
if (effectiveNow < startMin && effectiveNow + 1440 <= endMin + cycleMin) {
effectiveNow += 1440
}
const elapsed = effectiveNow - startMin - vIndex * route.frequency
if (elapsed < 0) return 0
const elapsedSec = elapsed * 60
return ((elapsedSec % schedule.cycleSec) + schedule.cycleSec) % schedule.cycleSec
}
export function computeBusDirSec(
cycleSec: number,
schedule: BusSchedule,
): { dirSec: number; returning: boolean } {
if (schedule.isCircular) return { dirSec: cycleSec, returning: false }
if (cycleSec <= schedule.tripDurationSec) return { dirSec: cycleSec, returning: false }
return { dirSec: cycleSec - schedule.tripDurationSec, returning: true }
}
const QUEUE_OFFSET_KM = 0.028 // ~28m per queue slot (22m bus + ~6m gap)
function computeBusVehicles(
busRoutes: BusRoute[],
busStopMap: Map<string, BusStop>,
nowMinutes: number,
serviceBucket: BusServiceBucket,
): VehiclePosition[] {
type Raw = {
route: BusRoute
schedule: BusSchedule
id: string
progress: number
returning: boolean
dwellStopId: string | null
dwellTimeIntoSec: number
}
const raws: Raw[] = []
for (const route of busRoutes) {
const schedule = getBusSchedule(route, busStopMap)
if (!schedule) continue
const tripDurationMin = schedule.tripDurationSec / 60
const cycleMin = schedule.cycleSec / 60
const window = getBusServiceWindow(route, serviceBucket)
if (!window) continue
const startMin = window.start * 60
let endMin = window.end * 60
// Route crosses midnight (serviceHoursEnd may be >24 or <start)
if (endMin <= startMin) endMin += 1440
// Pick the effective "now" that falls inside the window; wrap-around
// takes `nowMinutes + 1440` when the service started yesterday.
let effectiveNow = nowMinutes
if (effectiveNow < startMin && effectiveNow + 1440 <= endMin + cycleMin) {
effectiveNow += 1440
}
if (effectiveNow < startMin || effectiveNow > endMin + cycleMin) continue
const minutesSinceStart = effectiveNow - startMin
const numVehicles = Math.max(1, Math.floor(tripDurationMin / route.frequency))
for (let v = 0; v < numVehicles; v++) {
const offset = v * route.frequency
const elapsed = minutesSinceStart - offset
if (elapsed < 0) continue
if (effectiveNow > endMin) {
const cycleStart = startMin + offset + Math.floor(elapsed / cycleMin) * cycleMin
if (cycleStart > endMin) continue
}
const elapsedSec = elapsed * 60
const wrapped = ((elapsedSec % schedule.cycleSec) + schedule.cycleSec) % schedule.cycleSec
const { dirSec, returning } = computeBusDirSec(wrapped, schedule)
const progress = Math.max(0, Math.min(1, progressAtCycle(schedule, elapsedSec)))
const stops = returning ? schedule.backwardStops : schedule.forwardStops
let dwellStopId: string | null = null
let dwellTimeIntoSec = 0
for (const s of stops) {
if (dirSec >= s.arriveSec && dirSec <= s.departSec) {
dwellStopId = s.stopId
dwellTimeIntoSec = dirSec - s.arriveSec
break
}
}
raws.push({
route, schedule, id: `${route.id}-${v}`, progress, returning,
dwellStopId, dwellTimeIntoSec,
})
}
}
// Queue dwellers sharing a stop so their sprites don't overlap.
// Front of queue (largest dwellTimeIntoSec = arrived earliest) stays put;
// later arrivals shift backward along their own route direction.
const byStop = new Map<string, Raw[]>()
for (const r of raws) {
if (!r.dwellStopId) continue
const arr = byStop.get(r.dwellStopId)
if (arr) arr.push(r)
else byStop.set(r.dwellStopId, [r])
}
const queueIdx = new Map<string, number>()
for (const group of byStop.values()) {
if (group.length < 2) continue
group.sort((a, b) => b.dwellTimeIntoSec - a.dwellTimeIntoSec)
for (let i = 0; i < group.length; i++) queueIdx.set(group[i].id, i)
}
const QUEUE_PERP_M = 7 // right-of-travel nudge when longitudinal shift is clamped at an endpoint
const vehicles: VehiclePosition[] = []
for (const r of raws) {
let finalProgress = r.progress
let clampedSlot = 0
const qi = queueIdx.get(r.id) ?? 0
if (qi > 0) {
const delta = (QUEUE_OFFSET_KM * qi) / r.schedule.totalLenKm
if (r.returning) {
const shifted = r.progress + delta
if (shifted > 1) { finalProgress = 1; clampedSlot = qi }
else finalProgress = shifted
} else {
const shifted = r.progress - delta
if (shifted < 0) { finalProgress = 0; clampedSlot = qi }
else finalProgress = shifted
}
}
const pos = interpolateOnLine(r.route.geometry, finalProgress)
let [lng, lat] = pos.coordinates
if (clampedSlot > 0) {
const bearingRad = (pos.bearing * Math.PI) / 180
const eastM = Math.cos(bearingRad) * QUEUE_PERP_M * clampedSlot
const northM = -Math.sin(bearingRad) * QUEUE_PERP_M * clampedSlot
const latRad = lat * Math.PI / 180
lng += eastM / (111320 * Math.cos(latRad))
lat += northM / 110574
}
vehicles.push({
id: r.id,
lineId: r.route.id,
type: 'bus',
coordinates: [lng, lat],
bearing: pos.bearing,
progress: finalProgress,
color: r.route.color,
})
}
return vehicles
}
const FLIGHT_VISIBLE_MINUTES = 15
const DEPARTURE_CLIMB_MINUTES = 8
const FLIGHT_MAX_DISTANCE_KM = 30
const FLIGHT_MAX_ALTITUDE_M = 3000
const FLIGHT_COLOR = '#38bdf8'
const DEG_PER_KM_LAT = 1 / 111.32
type TaxiWaypoint = { pos: [number, number]; noseTarget: [number, number] }
// Landing approach routes with waypoints: { pos: [lng, lat], noseTarget: [lng, lat] }
// Route 1: From north — descend southward along the runway, turn, taxi to apron
const LANDING_ROUTE_SOUTH: TaxiWaypoint[] = [
{ pos: [113.58617746739547, 22.163612095293683], noseTarget: [113.59661639803325, 22.135252811158846] },
{ pos: [113.59661639803325, 22.135252811158846], noseTarget: [113.59573637190391, 22.13488739162877] },
{ pos: [113.59573637190391, 22.13488739162877], noseTarget: [113.59461357994577, 22.13570255697138] },
{ pos: [113.59461357994577, 22.13570255697138], noseTarget: [113.59024379502763, 22.14733923049094] },
{ pos: [113.59024379502763, 22.14733923049094], noseTarget: [113.57667925434424, 22.155714791453473] },
{ pos: [113.57667925434424, 22.155714791453473], noseTarget: [113.57667925434424, 22.155714791453473] },
]
// Route 2: From south — land heading north along the runway, turn to apron
const LANDING_ROUTE_NORTH: TaxiWaypoint[] = [
{ pos: [113.59652536084747, 22.135309029463954], noseTarget: [113.58678438196743, 22.161953979300034] },
{ pos: [113.58678438196743, 22.161953979300034], noseTarget: [113.58302151162125, 22.16268467689253] },
{ pos: [113.58302151162125, 22.16268467689253], noseTarget: [113.57856068951732, 22.161223277911876] },
{ pos: [113.57856068951732, 22.161223277911876], noseTarget: [113.57856068951732, 22.161223277911876] },
]
// Two non-overlapping traffic circuits over water east of the runway. Each
// circle's west side sits on the runway extended centerline (same longitude as
// the corresponding firstWp), so orbit exit → short straight inbound leg →
// final approach all share the same heading.
// South-landing (from south/east): CCW circle north of runway north threshold.
// Entry east → north (base) → exit west heading south → inbound → LANDING_ROUTE_SOUTH.
// North-landing (from north/west): CW circle south of runway south threshold.
// Entry east → south (base) → exit west heading north → inbound → LANDING_ROUTE_NORTH.
const HOLDING_CENTER_S: [number, number] = [113.60778, 22.175]
const HOLDING_CENTER_N: [number, number] = [113.61812, 22.125]
const HOLDING_RADIUS_DEG = 0.020
const HOLDING_ALTITUDE_M = 600
const HOLDING_CIRCLE_MINUTES = 2
const HOLD_EXIT_FRACTION = 0.5
const HOLD_INBOUND_MINUTES = 0.5
const RUNWAY_BUSY_BUFFER_MINUTES = 0.8
const APRON_STANDS: [number, number][] = [
[113.57296247130137, 22.155734815822715],
[113.5735298224446, 22.156080223561954],
[113.57405681042064, 22.15623040046111],
[113.57465381777813, 22.15658536340373],
[113.57511447160334, 22.15702223964229],
[113.57545351284965, 22.157534202263445],
[113.57578149837322, 22.158131489627372],
[113.57611685435795, 22.158680991762665],
[113.57615714826129, 22.159292084371216],
[113.57634435144236, 22.159958431996046],
[113.57662402849351, 22.160693708475325],
[113.57685408539844, 22.161487468535842],
]
const APRON_TARGET: [number, number] = [113.56229310185826, 22.167971582336254]
const APRON_LOOKAHEAD_MINUTES = 240
const TAXI_MINUTES = 3
const TAXI_ROUTE_SOUTH: TaxiWaypoint[] = [
{ pos: [113.57846893201933, 22.161205178260285], noseTarget: [113.5861293203778, 22.163669348178995] },
{ pos: [113.5861293203778, 22.163669348178995], noseTarget: [113.59651483316301, 22.135547426147557] },
]
const TAKEOFF_SOUTH: [number, number] = [113.59651483316301, 22.135547426147557]
const TAXI_ROUTE_NORTH: TaxiWaypoint[] = [
{ pos: [113.57665948112424, 22.15577473693072], noseTarget: [113.59027110500244, 22.14725668004919] },
{ pos: [113.59027110500244, 22.14725668004919], noseTarget: [113.59458354434732, 22.135724664946018] },
{ pos: [113.59458354434732, 22.135724664946018], noseTarget: [113.59584660181989, 22.134955830373045] },
{ pos: [113.59584660181989, 22.134955830373045], noseTarget: [113.59659541446433, 22.135281749889227] },
{ pos: [113.59659541446433, 22.135281749889227], noseTarget: [113.5857744315255, 22.164838365489818] },
]
const TAKEOFF_NORTH: [number, number] = [113.5857744315255, 22.164838365489818]
function bearingTo(fromLon: number, fromLat: number, toLon: number, toLat: number): number {
const dLon = (toLon - fromLon) * Math.PI / 180
const lat1 = fromLat * Math.PI / 180
const lat2 = toLat * Math.PI / 180
const y = Math.sin(dLon) * Math.cos(lat2)
const x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLon)
return ((Math.atan2(y, x) * 180 / Math.PI) + 360) % 360
}
function isSouthbound(bearing: number): boolean {
return bearing >= 90 && bearing < 270
}
function distDeg(a: [number, number], b: [number, number]): number {
const dLon = a[0] - b[0], dLat = a[1] - b[1]
return Math.sqrt(dLon * dLon + dLat * dLat)
}
function buildTaxiPath(apronPos: [number, number], route: TaxiWaypoint[], takeoffPt: [number, number]): [number, number][] {
return [apronPos, ...route.map(w => w.pos), takeoffPt]
}
function taxiPathTotalDist(path: [number, number][]): number {
let d = 0
for (let i = 1; i < path.length; i++) d += distDeg(path[i - 1], path[i])
return d
}
function interpolateTaxiPath(
path: [number, number][],
_route: TaxiWaypoint[],
t: number,
): { pos: [number, number]; bearing: number } {
const totalDist = taxiPathTotalDist(path)
let targetDist = t * totalDist
for (let i = 1; i < path.length; i++) {
const segDist = distDeg(path[i - 1], path[i])
if (targetDist <= segDist || i === path.length - 1) {
const segT = segDist > 0 ? Math.min(1, targetDist / segDist) : 0
const lon = path[i - 1][0] + (path[i][0] - path[i - 1][0]) * segT
const lat = path[i - 1][1] + (path[i][1] - path[i - 1][1]) * segT
// Use segment direction (path[i-1] → path[i]) as the bearing — this is
// constant along the segment, so it's numerically stable. The earlier
// "bearingTo(plane_pos, noseTarget)" approach was unstable: as the
// plane approached noseTarget the displacement vector shrank toward
// zero and sub-metre position noise caused multi-degree bearing swings
// per frame, which the eye reads as 前後抖動 even though position
// itself is continuous.
const curBearing = bearingTo(path[i - 1][0], path[i - 1][1], path[i][0], path[i][1])
return { pos: [lon, lat], bearing: curBearing }
}
targetDist -= segDist
}
const last = path[path.length - 1]
return { pos: last, bearing: bearingTo(path[path.length - 2][0], path[path.length - 2][1], last[0], last[1]) }
}
function interpolateLandingRoute(
route: TaxiWaypoint[],
t: number,
): { pos: [number, number]; bearing: number } {
const path = route.map(w => w.pos)
const totalDist = taxiPathTotalDist(path)
let targetDist = t * totalDist
for (let i = 1; i < path.length; i++) {
const segDist = distDeg(path[i - 1], path[i])
if (targetDist <= segDist || i === path.length - 1) {
const segT = segDist > 0 ? Math.min(1, targetDist / segDist) : 0
const lon = path[i - 1][0] + (path[i][0] - path[i - 1][0]) * segT
const lat = path[i - 1][1] + (path[i][1] - path[i - 1][1]) * segT
const curBearing = bearingTo(path[i - 1][0], path[i - 1][1], path[i][0], path[i][1])
return { pos: [lon, lat], bearing: curBearing }
}
targetDist -= segDist
}
const last = route[route.length - 1]
return {
pos: last.pos,
bearing: bearingTo(last.pos[0], last.pos[1], last.noseTarget[0], last.noseTarget[1]),
}
}
function isRunwayBusy(flights: Flight[], nowMinutes: number): boolean {
for (const f of flights) {
if (f.type !== 'departure') continue
const until = f.scheduledTime - nowMinutes
const elapsed = nowMinutes - f.scheduledTime
if (until > 0 && until <= TAXI_MINUTES) return true
if (elapsed >= 0 && elapsed <= RUNWAY_BUSY_BUFFER_MINUTES) return true
}
return false
}
function holdingPosition(
fraction: number,
center: [number, number],
clockwise: boolean,
): { lon: number; lat: number; bearing: number } {
const theta = (clockwise ? -1 : 1) * fraction * Math.PI * 2
const degPerKmLon = DEG_PER_KM_LAT / Math.cos((center[1] * Math.PI) / 180)
const lonScale = degPerKmLon / DEG_PER_KM_LAT
const lon = center[0] + Math.cos(theta) * HOLDING_RADIUS_DEG * lonScale
const lat = center[1] + Math.sin(theta) * HOLDING_RADIUS_DEG
const sign = clockwise ? -1 : 1
const vEast = -Math.sin(theta) * lonScale * sign
const vNorth = Math.cos(theta) * sign
const bearing = ((Math.atan2(vEast, vNorth) * 180) / Math.PI + 360) % 360
return { lon, lat, bearing }
}
// Arrival phases after APPROACH_END_MIN:
// Hold (if runway busy): circle repeatedly
// Transition: fly from circle exit point to first waypoint of landing route
// Landing: follow waypoint route (descend + taxi)
const APPROACH_END_MIN = 7
const LANDING_ROUTE_MINUTES = 3
function computeFlightVehicles(
flights: Flight[],
nowMinutes: number,
): VehiclePosition[] {
const vehicles: VehiclePosition[] = []
const departures = flights
.filter(f => f.type === 'departure')
.sort((a, b) => a.scheduledTime - b.scheduledTime)
const taxiStart = TAXI_MINUTES
const apronEnd = APRON_LOOKAHEAD_MINUTES
const pendingDepartures = departures.filter(f => {
const until = f.scheduledTime - nowMinutes
return until > taxiStart && until <= apronEnd
})
for (let i = 0; i < pendingDepartures.length && i < APRON_STANDS.length; i++) {
const flight = pendingDepartures[i]
const [lon, lat] = APRON_STANDS[i]
const heading = bearingTo(lon, lat, APRON_TARGET[0], APRON_TARGET[1])
vehicles.push({
id: flight.id,
lineId: flight.flightNumber,
type: 'flight',
coordinates: [lon, lat],
bearing: heading,
progress: 0,
color: FLIGHT_COLOR,
altitude: 0,
scale: 0.25,
flightPhase: 'apron',
flightData: flight,
})
}
for (const flight of flights) {
if (flight.type === 'departure') {
const until = flight.scheduledTime - nowMinutes
const elapsed = nowMinutes - flight.scheduledTime
if (until > 0 && until <= taxiStart) {
const destBearing = flight.destination?.bearing ?? 0
const southbound = isSouthbound(destBearing)
const route = southbound ? TAXI_ROUTE_SOUTH : TAXI_ROUTE_NORTH
const takeoffPt = southbound ? TAKEOFF_SOUTH : TAKEOFF_NORTH
const apronPos = APRON_STANDS[0]
const path = buildTaxiPath(apronPos, route, takeoffPt)
const t = 1 - until / taxiStart
const { pos, bearing } = interpolateTaxiPath(path, route, t)
vehicles.push({
id: flight.id,
lineId: flight.flightNumber,
type: 'flight',
coordinates: pos,
bearing,
progress: 0,
color: FLIGHT_COLOR,
altitude: 0,
scale: 0.25,
flightPhase: 'taxi',
flightData: flight,
})
continue
}
if (elapsed < 0 || elapsed > DEPARTURE_CLIMB_MINUTES) continue
const progress = Math.max(0, Math.min(1, elapsed / DEPARTURE_CLIMB_MINUTES))
const destBearing = flight.destination?.bearing ?? 0
const southbound = isSouthbound(destBearing)
const takeoffPt = southbound ? TAKEOFF_SOUTH : TAKEOFF_NORTH
const flyBearing = destBearing
const bearingRad = (flyBearing * Math.PI) / 180
const dist = progress * FLIGHT_MAX_DISTANCE_KM
const degPerKmLon = DEG_PER_KM_LAT / Math.cos((takeoffPt[1] * Math.PI) / 180)
const lat = takeoffPt[1] + Math.cos(bearingRad) * dist * DEG_PER_KM_LAT
const lon = takeoffPt[0] + Math.sin(bearingRad) * dist * degPerKmLon
const altitude = progress * FLIGHT_MAX_ALTITUDE_M