-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.ts
More file actions
14147 lines (13092 loc) · 472 KB
/
Copy pathmain.ts
File metadata and controls
14147 lines (13092 loc) · 472 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 {
AmbientLight,
Box3,
Box3Helper,
BufferGeometry,
CanvasTexture,
Clock,
Color,
DirectionalLight,
Euler,
Group,
HemisphereLight,
LinearFilter,
LineBasicMaterial,
LineSegments,
Material,
Mesh,
MeshBasicMaterial,
Object3D,
PerspectiveCamera,
PropertyBinding,
Raycaster,
Scene,
SkinnedMesh,
SRGBColorSpace,
Texture,
Vector2,
Vector3,
VideoTexture,
WireframeGeometry,
type AnimationClip
} from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'
import { GLTFLoader, type GLTF } from 'three/examples/jsm/loaders/GLTFLoader.js'
import { compileMsfs2020Behaviors } from './msfs/behavior'
import { normalizeAsoboPrimitiveBaseVertex } from './msfs/gltf/normalizeAsoboPrimitiveBaseVertex'
import { createMsfsGltfLoader } from './msfs/gltf/createMsfsGltfLoader'
import { getMsfsGltfLoadingManagerStats } from './msfs/gltf/createMsfsGltfLoader'
import type { MSFSDDSLoadOptions } from './msfs/gltf/MSFSDDSLoader'
import { normalizeAsoboPrimitiveWinding } from './msfs/gltf/normalizeAsoboPrimitiveWinding'
import { normalizeMsfsMaterials } from './msfs/gltf/normalizeMsfsMaterials'
import { usesBlendGBufferMaterial, usesGeoDecalFrostedMaterial } from './msfs/gltf/normalizeMsfsMaterials'
import { normalizeMsfsNormalsTangents } from './msfs/gltf/normalizeMsfsNormalsTangents'
import { normalizeMsfsSkinning } from './msfs/gltf/normalizeMsfsSkinning'
import { normalizeMsfsTexcoords } from './msfs/gltf/normalizeMsfsTexcoords'
import { normalizeMsfsVertexColors } from './msfs/gltf/normalizeMsfsVertexColors'
import { repairMsfsSkinnedAttributes } from './msfs/gltf/repairMsfsSkinnedAttributes'
import { sanitizeMsfsGltf } from './msfs/gltf/sanitizeMsfsGltf'
import { importBuiltMsfs2020Package } from './msfs/importer'
import {
getCachedMsfsPackageSource,
loadMsfsPackageSource,
type MsfsPackageSource
} from './msfs/packageAssets'
import { normalizeSurfaceLookupName, parseVCockpitSurfaces } from './msfs/panel'
import { loadMsfsLocalization, resolveMsfsLocalizedString, sanitizeMsfsTooltipText, type MsfsLocalization } from './msfs/localization'
import type { VCockpitGaugeEntry, VCockpitSurface } from './msfs/panel'
import { AircraftRuntime, type RuntimeUpdateProfile, SharedMsfsRuntimeHost } from './msfs/runtime'
import { MsfsInteractionAdapter, resolveMsfsAxisPercent, resolveMsfsDragPercent, resolveMsfsLockDragPercent, type MsfsDragTrajectoryPoint, type MsfsInteractionTarget } from './msfs/interactionAdapter'
import { CockpitInteractionDispatcher, type CockpitInteractionChannel } from './input/cockpitInteraction'
import { DEFAULT_COCKPIT_INPUT_STORE, effectiveCockpitInputProfile, loadCockpitInputStore, updateCockpitInputSettings } from './input/cockpitInputProfiles'
import { installViewerBootDevApi, installViewerDevApi } from './devApi'
import type {
CompiledBehaviorSet,
CompiledInteractionBlocker,
CompiledMaterialBinding,
ImportedAircraft,
ImportedCfgSection,
ImportDiagnostic,
ModelLodEntry,
RuntimeState
} from './msfs/types'
import type { CompiledInteractionBinding } from './msfs/types'
import type { ImportedModelDefinition } from './msfs/types'
import { evaluateCompiledExpression } from './msfs/rpn'
import {
createAircraftEnvironment,
createAppRenderer,
createNodeMaterialFactory,
getRendererPixelRatio,
type AppRenderer,
type NodeMaterialFactory,
type RendererInfo
} from './rendering/createAppRenderer'
import { createMsfsRenderPasses } from './rendering/createMsfsRenderPasses'
import { queueTask } from './worker/pool'
import { isAircraftImmutableCacheMode } from './aircraftAssets/cachePolicy'
const DEFAULT_PACKAGE_ROOT = '/tmp/headwindsim-aircraft-a330-900/'
const DEFAULT_STOCK_BEHAVIOR_ROOT = '/vendor/msfs-stock/'
const DEV_DEFAULT_PACKAGE_ROOT = '/aircrafts/headwindsim-aircraft-a330-900/'
const DEV_DEFAULT_AIRCRAFT_ID = 'SimObjects/Airplanes/_Headwind_A330neo-LIVERY#fltsim.0'
const DEFAULT_COCKPIT_RANGE_TEXTURE_SIZE = 1024
const DEFAULT_BACKGROUND_COCKPIT_RANGE_TEXTURE_SIZE = 512
type AssetRoot = MsfsPackageSource
type AircraftSelectorOption = {
readonly packageRoot: string
readonly packageName: string
readonly aircraft: ImportedAircraft
}
async function seedSyncedGaugeSettings(
packageRootUrl: string,
layoutEntries: readonly { readonly path: string }[],
runtimeHost: SharedMsfsRuntimeHost
): Promise<void> {
const packageRoot = new URL(packageRootUrl, window.location.href)
const candidates = layoutEntries
.map(entry => entry.path)
.filter(path => {
const normalizedPath = path.toLowerCase()
return (
normalizedPath.endsWith('.js') &&
(
normalizedPath.includes('/efb/') ||
normalizedPath.includes('/settings/') ||
normalizedPath.endsWith('/settingssync.js')
)
)
})
await Promise.all(
candidates.map(async path => {
try {
const response = await fetch(new URL(path, packageRoot))
if (!response.ok) {
return
}
const source = await response.text()
const storagePrefix =
/NXDataStore\.aircraftProjectPrefix\s*=\s*"([^"]+)"/u.exec(source)?.[1]?.toUpperCase() ??
null
for (const block of source.split('configKey:').slice(1)) {
const setting = block.slice(0, 2500)
const configKey = /^\s*"([^"]+)"/u.exec(setting)?.[1]
const localVarName = /localVarName:\s*"([^"]+)"/u.exec(setting)?.[1]
const defaultValue = /defaultValue:\s*"([^"]*)"/u.exec(setting)?.[1]
if (configKey == null || localVarName == null || defaultValue == null) {
continue
}
const storageKey = storagePrefix == null ? configKey : `${storagePrefix}_${configKey}`
const storedValue = window.localStorage.getItem(storageKey)
if (storedValue == null || storedValue.length === 0) {
continue
}
const rawValue = storedValue.trim().toLowerCase()
const value =
rawValue === 'true' ? 1 : rawValue === 'false' ? 0 : Number.parseInt(rawValue, 10)
if (Number.isFinite(value)) {
runtimeHost.seedVariable(localVarName, value)
}
}
} catch {
// Gauge startup still applies these settings; this only prevents a visible first-frame default.
}
})
)
}
export type LoadedModelComponent = {
readonly kind: 'exterior' | 'interior'
readonly modelDefinition: ImportedModelDefinition
readonly scene: Group
readonly animations: GLTF['animations']
readonly loadedLodIndex: number
readonly loadDiagnostics: ModelLoadDiagnostics
readonly resourceStats: ModelResourceStats | null
readonly vcockpitBinding: VCockpitSurfaceBindingResult | null
}
export type LoadedAircraftModel = {
readonly scene: Group
readonly animations: GLTF['animations']
readonly exterior: LoadedModelComponent
readonly interior: LoadedModelComponent | null
}
type AircraftModelLoadContext = {
readonly aircraft: ImportedAircraft
readonly createLoader: (options?: {
readonly textureLoadOptions?: MSFSDDSLoadOptions
}) => GLTFLoader
readonly createNodeMaterial: NodeMaterialFactory | null
readonly resolvePanelAssetUrl: (source: string) => string | null
}
type ModelLoadPhase = {
readonly label: string
readonly startMs: number
readonly endMs: number
readonly durationMs: number
readonly details: Record<string, unknown> | null
}
type ModelLoadDiagnostics = {
readonly phases: readonly ModelLoadPhase[]
readonly totalDurationMs: number
}
type PreparedMsfsGltfLodWorkerPhase = {
readonly label: string
readonly durationMs: number
readonly details: Record<string, unknown> | null
}
type PreparedMsfsGltfLodWorkerBuffer = {
readonly index: number
readonly buffer: ArrayBuffer
readonly byteLength: number
}
type PreparedMsfsGltfLodWorkerResult = {
readonly gltfJson: Record<string, unknown>
readonly buffers: readonly PreparedMsfsGltfLodWorkerBuffer[]
readonly phases: readonly PreparedMsfsGltfLodWorkerPhase[]
}
type ModelResourceStats = {
readonly geometryCount: number
readonly materialCount: number
readonly textureCount: number
readonly geometryAttributeBytes: number
readonly geometryIndexBytes: number
readonly textureKnownBytes: number
readonly textureEstimatedBytes: number
readonly totalKnownBytes: number
readonly totalEstimatedBytes: number
}
export type CockpitCameraController = {
readonly isAvailable: () => boolean
readonly dispose: () => void
readonly isActive: () => boolean
readonly update: () => void
readonly enter: (source?: CockpitViewToggleSource) => void
readonly exit: (source?: CockpitViewToggleSource) => void
}
type CockpitViewToggleSource = 'keyboard' | 'benchmark'
type VCockpitGaugeMode = 'texture' | 'overlay' | 'video'
type VCockpitGaugeModeRequest = VCockpitGaugeMode | 'htmlTexture'
type VCockpitGaugeOverlayProjection = 'bounds' | 'quad'
type ExteriorInteriorMode = 'deferred' | 'sync' | 'off'
type CockpitTextureMode = 'range-low' | 'full'
export type ViewerConfigProfile = {
readonly packageRoot?: string
readonly aircraftId?: string
readonly lod?: number | null
readonly interiorLod?: number | null
readonly exteriorInteriorMode?: ExteriorInteriorMode
readonly exteriorInteriorLod?: number | null
readonly vcockpitSurfaces?: boolean
readonly vcockpitLiveGauges?: boolean
readonly vcockpitGaugeMode?: VCockpitGaugeMode
readonly vcockpitGaugeOverlayProjection?: VCockpitGaugeOverlayProjection
readonly vcockpitGaugeCaptureFps?: number | null
readonly vcockpitGaugeRasterScale?: number | null
readonly vcockpitGaugeUpdateOutside?: boolean
readonly cockpitTextures?: CockpitTextureMode
readonly cockpitTextureSize?: number | null
readonly cockpitMergeStatic?: boolean
readonly cockpitInstanceStatic?: boolean
readonly cockpitPerf?: boolean
readonly cockpitInteractionHitboxes?: boolean
readonly skipGaugeSettingSeed?: boolean
readonly rendererPixelRatio?: number | null
readonly rawQuery?: string
}
type ViewerConfigStore = {
readonly version: 1
readonly global: ViewerConfigProfile
readonly aircraft: Record<string, ViewerConfigProfile>
}
type ViewerSettingsPanelScope = 'global' | 'aircraft'
type ViewerSettingsApplyEvent = {
readonly scope: ViewerSettingsPanelScope
readonly action: 'apply' | 'reset'
readonly selectedPackageRoot: string
readonly selectedAircraftId: string
}
type ViewerRuntimeSettingsSnapshot = {
readonly exteriorLod: number | null
readonly interiorLod: number | null
readonly exteriorInteriorMode: ExteriorInteriorMode
readonly exteriorInteriorLod: number | null
readonly vcockpitSurfaces: boolean
readonly vcockpitLiveGauges: boolean
readonly vcockpitGaugeMode: VCockpitGaugeModeRequest
readonly vcockpitGaugeOverlayProjection: VCockpitGaugeOverlayProjection
readonly vcockpitGaugeCaptureFps: number
readonly vcockpitGaugeRasterScale: number
readonly vcockpitGaugeUpdateOutside: boolean
readonly cockpitTextures: CockpitTextureMode
readonly cockpitTextureSize: number | null
readonly cockpitMergeStatic: boolean
readonly cockpitInstanceStatic: boolean
readonly cockpitPerf: boolean
readonly cockpitInteractionHitboxes: boolean
readonly skipGaugeSettingSeed: boolean
readonly rendererPixelRatio: number
readonly extraQuery: string
}
export type FpsCounterSnapshot = {
readonly fps: number
readonly averageFrameMs: number
readonly lowFps: number
readonly sampleCount: number
}
type FpsCounter = {
readonly recordFrame: (deltaSeconds: number) => void
readonly getSnapshot: () => FpsCounterSnapshot
}
async function init(): Promise<void> {
setGlobalLoadStage({ stage: 'init:start' })
installViewerBootDevApi()
const backgroundColor = new Color('#405264')
const searchParams = new URLSearchParams(window.location.search)
const configStore = loadViewerConfigStore()
const initialSearchParams = createEffectiveViewerSearchParams(
searchParams,
configStore.global,
null
)
const discoveredPackageRoots = await discoverAircraftPackageRoots()
const additionalPackageRoots = resolveAdditionalPackageRoots(initialSearchParams)
const additionalAssetRoots = await loadConfiguredAssetRoots(additionalPackageRoots)
const requestedAircraftId = initialSearchParams.get('aircraft')
const packageRoot = await resolveRequestedPackageRoot(
initialSearchParams,
discoveredPackageRoots,
requestedAircraftId,
additionalPackageRoots
)
setGlobalLoadStage({ stage: 'import:package', packageRoot })
const packageData = await importBuiltMsfs2020Package(packageRoot, {
additionalPackageRoots,
requestedAircraftId
})
const packageSource = getCachedMsfsPackageSource(packageData.rootUrl)
const cockpitLocalizationPromise: Promise<MsfsLocalization> = packageSource == null
? Promise.resolve(new Map())
: loadMsfsLocalization(packageSource)
const aircraft = selectAircraft(
packageData.aircraft,
requestedAircraftId
)
;(globalThis as Record<string, unknown>).__lastImportedPackage = packageData
;(globalThis as Record<string, unknown>).__lastSelectedAircraft = aircraft
if (aircraft == null || aircraft.model == null) {
if (requestedAircraftId != null) {
const availableAircraft = packageData.aircraft
.map(candidate => candidate.id)
.sort()
throw new Error(
[
`Requested aircraft "${requestedAircraftId}" was not found in package root ${packageRoot}.`,
availableAircraft.length > 0
? `Available aircraft IDs:\n- ${availableAircraft.join('\n- ')}`
: 'The selected package does not contain any importable aircraft models.'
].join('\n\n')
)
}
throw new Error('No importable aircraft model was found in the configured package.')
}
const aircraftConfigProfile =
configStore.aircraft[getViewerAircraftConfigKey(packageRoot, aircraft.id)] ?? null
let effectiveSearchParams = createEffectiveViewerSearchParams(
searchParams,
configStore.global,
aircraftConfigProfile
)
let requestedLodIndex = resolveRequestedLodIndex(effectiveSearchParams)
let requestedInteriorLodIndex = resolveRequestedInteriorLodIndex(effectiveSearchParams)
let requestedExteriorInteriorLodIndex =
resolveRequestedExteriorInteriorLodIndex(effectiveSearchParams)
let exteriorInteriorMode = getExteriorInteriorMode(effectiveSearchParams)
const syncExteriorInterior = exteriorInteriorMode === 'sync'
const scene = new Scene()
const deferInteriorBehaviors = !syncExteriorInterior && aircraft.interiorModel != null
setGlobalLoadStage({ stage: 'compile:behaviors', aircraftId: aircraft.id })
const compiledBehaviorsPromise = compileMsfs2020Behaviors(packageData, aircraft, {
additionalPackageRoots,
includeInteriorModel: !deferInteriorBehaviors
})
setGlobalLoadStage({ stage: 'renderer:create', aircraftId: aircraft.id })
const rendererInfo = await createAppRenderer(effectiveSearchParams)
const { renderer } = rendererInfo
renderer.setClearColor(backgroundColor, 1)
const aircraftEnvironment = createAircraftEnvironment(renderer)
scene.environment = aircraftEnvironment.texture
document.body.appendChild(renderer.domElement)
const camera = new PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
5000
)
camera.position.set(40, 20, 40)
const controls = new OrbitControls(camera, renderer.domElement)
controls.enableDamping = true
controls.target.set(0, 4, 0)
;(globalThis as Record<string, unknown>).__lastRenderer = renderer
;(globalThis as Record<string, unknown>).__lastCamera = camera
;(globalThis as Record<string, unknown>).__lastControls = controls
const ambientLight = new AmbientLight('#ffffff', 0.18)
const fallbackSkyLight = aircraftEnvironment.usedFallback
? new HemisphereLight('#d6e5f5', '#405264', 0.55)
: null
const keyLight = new DirectionalLight('#fff1d5', 2.35)
keyLight.position.set(34, 9, 18)
const fillLight = new DirectionalLight('#b9d5ff', 0.28)
fillLight.position.set(-22, 16, -28)
const rimLight = new DirectionalLight('#d7e6ff', 0.95)
rimLight.position.set(-30, 18, 24)
scene.add(ambientLight, keyLight, fillLight, rimLight)
if (fallbackSkyLight != null) {
scene.add(fallbackSkyLight)
}
const overlay = createOverlay()
document.body.appendChild(overlay)
const selectedPackageSelectorOptions = createPackageAircraftSelectorOptions(
packageData,
packageRoot
)
const selector = createAircraftSelector(selectedPackageSelectorOptions, packageRoot, aircraft)
if (selector != null) {
document.body.appendChild(selector)
}
let handleViewerSettingsApplied:
| ((event: ViewerSettingsApplyEvent) => Promise<string | null>)
| null = null
let settingsPanel = createSettingsPanel({
selectorOptions: selectedPackageSelectorOptions,
packageRoot,
aircraft,
configStore,
effectiveSearchParams,
onApply: event => handleViewerSettingsApplied?.(event) ?? null
})
document.body.appendChild(settingsPanel)
const aircraftModelLoadContext = createAircraftModelLoadContext(
aircraft,
packageData.rootUrl,
packageData.layoutEntries.map(entry => entry.path),
additionalAssetRoots,
rendererInfo
)
setGlobalLoadStage({ stage: 'gltf:load', aircraftId: aircraft.id })
const runtimeHost = new SharedMsfsRuntimeHost([], aircraft)
;(globalThis as Record<string, unknown>).__lastRuntimeHost = runtimeHost
const syncedSettingSeedPromise = shouldSkipGaugeSettingSeed(effectiveSearchParams)
? Promise.resolve()
: seedSyncedGaugeSettings(packageData.rootUrl, packageData.layoutEntries, runtimeHost)
const gltfPromise = loadAircraftGltf(aircraftModelLoadContext, {
preferredLodIndex: requestedLodIndex,
loadExteriorInterior: syncExteriorInterior,
exteriorInteriorPreferredLodIndex: requestedExteriorInteriorLodIndex,
bindVCockpitSurfaces: shouldBindVCockpitSurfaces(effectiveSearchParams),
liveVCockpitGauges: shouldLiveRefreshVCockpitGauges(effectiveSearchParams),
vcockpitGaugeMode: getVCockpitGaugeMode(effectiveSearchParams),
vcockpitGaugeVideoFps: getVCockpitGaugeVideoFps(effectiveSearchParams),
vcockpitGaugeCaptureFps: getVCockpitGaugeCaptureFps(effectiveSearchParams),
vcockpitGaugeRasterScale: getVCockpitGaugeRasterScale(effectiveSearchParams),
debugVCockpitGauges: shouldDebugVCockpitGauges(effectiveSearchParams),
runtimeHost
})
const [initialCompiledBehaviors, gltf, cockpitLocalization] = await Promise.all([
compiledBehaviorsPromise,
gltfPromise,
cockpitLocalizationPromise,
syncedSettingSeedPromise
])
let compiledBehaviors = initialCompiledBehaviors
;(globalThis as Record<string, unknown>).__lastCompiledBehaviors = compiledBehaviors
setGlobalLoadStage({ stage: 'gltf:loaded', aircraftId: aircraft.id })
;(globalThis as Record<string, unknown>).__lastLoadedGltf = gltf
let loadedModel = gltf
const aircraftRoot = new Group()
aircraftRoot.add(loadedModel.scene)
scene.add(aircraftRoot)
;(globalThis as Record<string, unknown>).__lastAircraftRoot = aircraftRoot
;(globalThis as Record<string, unknown>).__lastScene = scene
setGlobalLoadStage({ stage: 'scene:ready', aircraftId: aircraft.id })
centerObjectAtOrigin(aircraftRoot)
fitCameraToObject(camera, controls, aircraftRoot, aircraft)
const renderPasses = createMsfsRenderPasses(renderer, scene, camera, aircraftRoot)
const cameraDepthClipController = createCameraDepthClipController(camera, aircraftRoot)
cameraDepthClipController.update()
;(globalThis as Record<string, unknown>).__lastCameraDepthClipController =
cameraDepthClipController
void loadAircraftSelectorOptions(
discoveredPackageRoots,
packageData,
packageRoot,
additionalPackageRoots
)
.then(selectorOptions => {
const nextSelector = createAircraftSelector(selectorOptions, packageRoot, aircraft)
if (nextSelector == null) {
selector?.remove()
return
}
selector?.replaceWith(nextSelector)
if (selector == null) {
document.body.appendChild(nextSelector)
}
const nextSettingsPanel = createSettingsPanel({
selectorOptions,
packageRoot,
aircraft,
configStore: loadViewerConfigStore(),
effectiveSearchParams,
onApply: event => handleViewerSettingsApplied?.(event) ?? null
})
settingsPanel.replaceWith(nextSettingsPanel)
settingsPanel = nextSettingsPanel
})
.catch(error => {
console.warn('Failed to populate aircraft selector options.', error)
})
let runtime = new AircraftRuntime(
compiledBehaviors,
loadedModel.scene,
runtimeHost,
aircraft,
runtimeHost.simulatorEngine.getAircraft(),
runtimeHost.simulatorEngine
)
let runtimeMaterialState = collectRuntimeMaterialState(loadedModel.scene)
runtime.bindAnimations(loadedModel.animations)
let lastRuntimeModelRevision = runtime.getModelRevision()
;(globalThis as Record<string, unknown>).__lastAircraftRuntime = runtime
const cockpitInteractionStats = {
attemptCount: 0,
hitCount: 0,
executedCount: 0,
lastTarget: null as string | null,
activeHeldTarget: null as string | null,
lastHitObject: null as string | null,
lastHitKind: null as 'interaction-mesh' | 'fallback-hitbox' | 'blocker' | null,
lastMissReason: null as string | null,
interactionTargetCount: runtime.getInteractionBindings().length,
interactionHitVolumeCount: 0,
interactionPickableMeshCount: 0,
interactionMappedBindingCount: 0,
interactionFallbackHitboxCount: 0,
interactionOccluderMeshCount: 0,
lastOccluderObject: null as string | null
}
;(globalThis as Record<string, unknown>).__lastCockpitInteractionStats = cockpitInteractionStats
type CockpitBenchmarkMemorySample = {
readonly usedJSHeapSize: number | null
readonly totalJSHeapSize: number | null
readonly jsHeapSizeLimit: number | null
readonly userAgentSpecificBytes: number | null
readonly userAgentSpecificError: string | null
readonly rendererTextures: number | null
readonly rendererGeometries: number | null
}
type CockpitBenchmarkEvent = {
readonly label: string
readonly nowMs: number
readonly wallTimeMs: number
readonly loadStage: string | null
readonly loadStageTimestampMs: number | null
readonly interiorLodIndex: number | null
readonly cockpitViewActive: boolean
readonly details: Record<string, unknown> | null
readonly memory: CockpitBenchmarkMemorySample | null
}
type CockpitBenchmarkPhaseResult = {
readonly status: 'measured' | 'skipped'
readonly reason: string | null
readonly toggleToLoadStartMs: number | null
readonly toggleToComponentLoadedMs: number | null
readonly toggleToSwapCompleteMs: number | null
readonly toggleToActiveInteriorMs: number | null
readonly toggleToVisualReadyMs: number | null
readonly memoryBefore: CockpitBenchmarkMemorySample | null
readonly memoryAfter: CockpitBenchmarkMemorySample | null
readonly usedJSHeapDelta: number | null
readonly userAgentSpecificBytesDelta: number | null
}
type CockpitBenchmarkRunResult = {
readonly aircraftId: string
readonly createdAt: string
readonly cold: CockpitBenchmarkPhaseResult
readonly cachedExterior: CockpitBenchmarkPhaseResult
readonly warm: CockpitBenchmarkPhaseResult
readonly events: readonly CockpitBenchmarkEvent[]
}
type PerformanceWithMemory = Performance & {
readonly memory?: {
readonly usedJSHeapSize: number
readonly totalJSHeapSize: number
readonly jsHeapSizeLimit: number
}
readonly measureUserAgentSpecificMemory?: () => Promise<{ readonly bytes: number }>
}
let activeCockpitBenchmarkEvents: CockpitBenchmarkEvent[] | null = null
let lastCockpitBenchmarkResult: CockpitBenchmarkRunResult | null = null
const getCockpitBenchmarkLoadStage = (): {
readonly stage: string | null
readonly timestampMs: number | null
} => {
const loadStage = (globalThis as Record<string, unknown>).__msfsLoadStage
if (loadStage == null || typeof loadStage !== 'object') {
return { stage: null, timestampMs: null }
}
const record = loadStage as Record<string, unknown>
return {
stage: typeof record.stage === 'string' ? record.stage : null,
timestampMs: typeof record.timestamp === 'number' ? record.timestamp : null
}
}
const collectCockpitBenchmarkMemory = async (): Promise<CockpitBenchmarkMemorySample> => {
const performanceWithMemory = performance as PerformanceWithMemory
const heap = performanceWithMemory.memory
let userAgentSpecificBytes: number | null = null
let userAgentSpecificError: string | null = null
if (typeof performanceWithMemory.measureUserAgentSpecificMemory === 'function') {
try {
const userAgentSpecificMemory =
await performanceWithMemory.measureUserAgentSpecificMemory()
userAgentSpecificBytes = userAgentSpecificMemory.bytes
} catch (error) {
userAgentSpecificError = error instanceof Error ? error.message : String(error)
}
}
return {
usedJSHeapSize: heap?.usedJSHeapSize ?? null,
totalJSHeapSize: heap?.totalJSHeapSize ?? null,
jsHeapSizeLimit: heap?.jsHeapSizeLimit ?? null,
userAgentSpecificBytes,
userAgentSpecificError,
rendererTextures: renderer.info.memory.textures ?? null,
rendererGeometries: renderer.info.memory.geometries ?? null
}
}
const pushCockpitBenchmarkEvent = (
label: string,
details: Record<string, unknown> | null = null,
memory: CockpitBenchmarkMemorySample | null = null
): CockpitBenchmarkEvent | null => {
if (activeCockpitBenchmarkEvents == null) {
return null
}
const loadStage = getCockpitBenchmarkLoadStage()
const event: CockpitBenchmarkEvent = {
label,
nowMs: performance.now(),
wallTimeMs: Date.now(),
loadStage: loadStage.stage,
loadStageTimestampMs: loadStage.timestampMs,
interiorLodIndex: loadedModel.interior?.loadedLodIndex ?? null,
cockpitViewActive: cockpitCameraController.isActive(),
details,
memory
}
activeCockpitBenchmarkEvents.push(event)
return event
}
const recordCockpitBenchmarkEvent = (
label: string,
details: Record<string, unknown> | null = null
): void => {
pushCockpitBenchmarkEvent(label, details)
}
const captureCockpitBenchmarkSnapshot = async (
label: string,
details: Record<string, unknown> | null = null
): Promise<CockpitBenchmarkEvent | null> => {
return pushCockpitBenchmarkEvent(
label,
details,
await collectCockpitBenchmarkMemory()
)
}
const waitForAnimationFrames = async (frameCount: number): Promise<void> => {
for (let frameIndex = 0; frameIndex < frameCount; frameIndex += 1) {
await new Promise<void>(resolve => {
requestAnimationFrame(() => resolve())
})
}
}
const waitForCockpitBenchmarkCondition = async (
predicate: () => boolean,
timeoutMs: number,
description: string
): Promise<void> => {
const startedAt = performance.now()
while (performance.now() - startedAt < timeoutMs) {
if (predicate()) {
return
}
await new Promise(resolve => window.setTimeout(resolve, 16))
}
throw new Error(`Timed out waiting for ${description}.`)
}
const findCockpitBenchmarkEvent = (
events: readonly CockpitBenchmarkEvent[],
label: string,
minNowMs: number
): CockpitBenchmarkEvent | null => {
return events.find(event => event.label === label && event.nowMs >= minNowMs) ?? null
}
const toCockpitBenchmarkDelta = (
startEvent: CockpitBenchmarkEvent | null,
endEvent: CockpitBenchmarkEvent | null
): number | null => {
return startEvent != null && endEvent != null
? Number((endEvent.nowMs - startEvent.nowMs).toFixed(1))
: null
}
const toCockpitBenchmarkMemoryDelta = (
before: CockpitBenchmarkMemorySample | null,
after: CockpitBenchmarkMemorySample | null,
key: 'usedJSHeapSize' | 'userAgentSpecificBytes'
): number | null => {
const beforeValue = before?.[key]
const afterValue = after?.[key]
return typeof beforeValue === 'number' && typeof afterValue === 'number'
? afterValue - beforeValue
: null
}
const summarizeCockpitBenchmarkPhase = (
events: readonly CockpitBenchmarkEvent[],
options: {
readonly startLabel: string
readonly beforeLabel: string
readonly afterLabel: string
readonly visualReadyLabel?: string
readonly loadStartLabel?: string
readonly componentLoadedLabel?: string
readonly swapCompleteLabel?: string
readonly activeInteriorLabel?: string
readonly skipReason?: string | null
}
): CockpitBenchmarkPhaseResult => {
const beforeEvent = events.find(event => event.label === options.beforeLabel) ?? null
const startEvent =
beforeEvent != null
? findCockpitBenchmarkEvent(events, options.startLabel, beforeEvent.nowMs)
: null
const afterEvent =
startEvent != null
? findCockpitBenchmarkEvent(events, options.afterLabel, startEvent.nowMs)
: null
if (startEvent == null || beforeEvent == null || afterEvent == null) {
return {
status: 'skipped',
reason: options.skipReason ?? 'Required benchmark events were not recorded.',
toggleToLoadStartMs: null,
toggleToComponentLoadedMs: null,
toggleToSwapCompleteMs: null,
toggleToActiveInteriorMs: null,
toggleToVisualReadyMs: null,
memoryBefore: beforeEvent?.memory ?? null,
memoryAfter: afterEvent?.memory ?? null,
usedJSHeapDelta: toCockpitBenchmarkMemoryDelta(
beforeEvent?.memory ?? null,
afterEvent?.memory ?? null,
'usedJSHeapSize'
),
userAgentSpecificBytesDelta: toCockpitBenchmarkMemoryDelta(
beforeEvent?.memory ?? null,
afterEvent?.memory ?? null,
'userAgentSpecificBytes'
)
}
}
return {
status: 'measured',
reason: null,
toggleToLoadStartMs: toCockpitBenchmarkDelta(
startEvent,
options.loadStartLabel != null
? findCockpitBenchmarkEvent(events, options.loadStartLabel, startEvent.nowMs)
: null
),
toggleToComponentLoadedMs: toCockpitBenchmarkDelta(
startEvent,
options.componentLoadedLabel != null
? findCockpitBenchmarkEvent(events, options.componentLoadedLabel, startEvent.nowMs)
: null
),
toggleToSwapCompleteMs: toCockpitBenchmarkDelta(
startEvent,
options.swapCompleteLabel != null
? findCockpitBenchmarkEvent(events, options.swapCompleteLabel, startEvent.nowMs)
: null
),
toggleToActiveInteriorMs: toCockpitBenchmarkDelta(
startEvent,
options.activeInteriorLabel != null
? findCockpitBenchmarkEvent(events, options.activeInteriorLabel, startEvent.nowMs)
: null
),
toggleToVisualReadyMs: toCockpitBenchmarkDelta(
startEvent,
options.visualReadyLabel != null
? findCockpitBenchmarkEvent(events, options.visualReadyLabel, startEvent.nowMs)
: afterEvent
),
memoryBefore: beforeEvent.memory,
memoryAfter: afterEvent.memory,
usedJSHeapDelta: toCockpitBenchmarkMemoryDelta(
beforeEvent.memory,
afterEvent.memory,
'usedJSHeapSize'
),
userAgentSpecificBytesDelta: toCockpitBenchmarkMemoryDelta(
beforeEvent.memory,
afterEvent.memory,
'userAgentSpecificBytes'
)
}
}
const rebuildRuntimeForLoadedModel = (): void => {
cockpitInteractionDispatcher.cancelAll()
cockpitInteractionAdapter.cancelAll()
runtime.dispose()
runtime = new AircraftRuntime(
compiledBehaviors,
loadedModel.scene,
runtimeHost,
aircraft,
runtimeHost.simulatorEngine.getAircraft(),
runtimeHost.simulatorEngine
)
runtime.bindAnimations(loadedModel.animations)
;(globalThis as Record<string, unknown>).__lastAircraftRuntime = runtime
cockpitInteractionStats.interactionTargetCount = runtime.getInteractionBindings().length
cockpitInteractionPickRegistryCache = null
syncCockpitInteractionHitboxHelpers()
runtimeMaterialState = collectRuntimeMaterialState(loadedModel.scene)
runtimeState = runtime.update(0)
lastRuntimeModelRevision = runtime.getModelRevision()
cameraDepthClipController.markModelChanged()
;(globalThis as Record<string, unknown>).__lastRuntimeState = runtimeState
}
let fullCompiledBehaviorsPromise: Promise<CompiledBehaviorSet> | null = null
let hasFullCompiledBehaviors = !deferInteriorBehaviors
const ensureFullCompiledBehaviors = (): Promise<CompiledBehaviorSet> => {
if (hasFullCompiledBehaviors) {
return Promise.resolve(compiledBehaviors)
}
if (fullCompiledBehaviorsPromise != null) {
return fullCompiledBehaviorsPromise
}
setGlobalLoadStage({
stage: 'compile:behaviors:full:start',
aircraftId: aircraft.id
})
fullCompiledBehaviorsPromise = compileMsfs2020Behaviors(packageData, aircraft, {
additionalPackageRoots,
includeInteriorModel: true
})
.then(nextCompiledBehaviors => {
compiledBehaviors = nextCompiledBehaviors
hasFullCompiledBehaviors = true
;(globalThis as Record<string, unknown>).__lastCompiledBehaviors =
compiledBehaviors
rebuildRuntimeForLoadedModel()
setGlobalLoadStage({
stage: 'compile:behaviors:full:ready',
aircraftId: aircraft.id
})
return compiledBehaviors
})
.catch(error => {
setGlobalLoadStage({
stage: 'compile:behaviors:full:error',
aircraftId: aircraft.id,
error: error instanceof Error ? error.message : String(error)
})
throw error
})
.finally(() => {
fullCompiledBehaviorsPromise = null
})
return fullCompiledBehaviorsPromise
}
const setActiveInteriorComponent = (nextInterior: LoadedModelComponent | null): void => {
const currentInterior = loadedModel.interior
if (currentInterior === nextInterior) {
return
}
const swapPhases: ModelLoadPhase[] = []
const recordSwapPhase = (
label: string,
startMs: number,
details: Record<string, unknown> | null = null
): void => {
const endMs = performance.now()
swapPhases.push({
label,
startMs,
endMs,
durationMs: endMs - startMs,
details
})
}
const sceneSwapStartMs = performance.now()
if (currentInterior != null) {
currentInterior.vcockpitBinding?.setActive(false)
loadedModel.scene.remove(currentInterior.scene)
}
if (nextInterior != null && nextInterior.scene.parent !== loadedModel.scene) {
loadedModel.scene.add(nextInterior.scene)
}
if (nextInterior != null) {
nextInterior.vcockpitBinding?.setActive(shouldUpdateVCockpitGaugesForCurrentView())
}
recordSwapPhase('interior-swap:scene-graph', sceneSwapStartMs)
loadedModel = replaceLoadedAircraftInterior(loadedModel, nextInterior)
;(globalThis as Record<string, unknown>).__lastLoadedGltf = loadedModel
cameraDepthClipController.markModelChanged()
const runtimeRebuildStartMs = performance.now()
rebuildRuntimeForLoadedModel()
recordSwapPhase('interior-swap:runtime-rebuild', runtimeRebuildStartMs)
const renderPassRefreshStartMs = performance.now()
renderPasses.refresh()
recordSwapPhase('interior-swap:render-pass-refresh', renderPassRefreshStartMs)
if (cockpitCameraController.isActive()) {
refreshCockpitCameraClipPlanes()
}
clock.getDelta()
recordCockpitBenchmarkEvent('cockpit:interior:swap-complete', {
loadedLodIndex: nextInterior?.loadedLodIndex ?? null,
swapPhases
})
markCockpitPerfFrames('interior-swap', 12)
}
const shouldUpdateVCockpitGaugesForCurrentView = (): boolean =>
cockpitCameraController.isActive() || shouldUpdateVCockpitGaugesOutside(effectiveSearchParams)
let cockpitCameraClipPlanes: CameraClipPlanes = {
near: COCKPIT_CAMERA_CLIP_NEAR,
far: COCKPIT_CAMERA_DEFAULT_CLIP_FAR
}
const refreshCockpitCameraClipPlanes = (): void => {
cockpitCameraClipPlanes = {
near: COCKPIT_CAMERA_CLIP_NEAR,