// ==UserScript== // @name GeoFS F-16 Addon // @namespace https://github.com/ArjanKw/GeoFS-BlueAngels/ // @version 3.0.0 // @description Improves the cockpit with custom MFDs, adjustable seat height and more. // @author Natrium // @match https://geo-fs.com/geofs.php* // @match https://*.geo-fs.com/geofs.php* // @icon https://www.google.com/s2/favicons?sz=64&domain=geo-fs.com // @grant none // ==/UserScript== !function(){"use strict";class HelperModule{static parseSemver(version){const[major,minor,patch]=version.split(".").map(Number);return{major:major,minor:minor,patch:patch}}static isSemverAtLeast(version,minimumVersion){const a=HelperModule.parseSemver(version),b=HelperModule.parseSemver(minimumVersion);return a.major!==b.major?a.major>b.major:a.minor!==b.minor?a.minor>b.minor:a.patch>=b.patch}}window.GeoFSAddonCore||(window.GeoFSAddonCore={version:"1.0.0",HelperModule:HelperModule,registry:new class AddonRegistryModule{constructor(){this.plugins=Object.create(null)}register(plugin){return this.plugins[plugin.id]=plugin,plugin}get(id){return this.plugins[id]??null}list(){return Object.values(this.plugins)}}},window.addonRuntime||(window.addonRuntime={checklistModule:null,mapModule:null,navModule:null,communicationModule:null,mfdUiStates:Object.create(null),mfdPagesCatalog:null,mfdRuntimeRefs:Object.create(null),navRdrRuntime:{bootStartMs:0},mainPlugin:null}))}();var addonRuntime=window.addonRuntime;class HelperModule{static parseSemver(version){const[major,minor,patch]=version.split(".").map(Number);return{major:major,minor:minor,patch:patch}}static isSemverAtLeast(version,minimumVersion){const a=HelperModule.parseSemver(version),b=HelperModule.parseSemver(minimumVersion);return a.major!==b.major?a.major>b.major:a.minor!==b.minor?a.minor>b.minor:a.patch>=b.patch}static deepCloneJson(value){return JSON.parse(JSON.stringify(value))}static angleDiffDeg(a,b){let d=a-b;for(;d>180;)d-=360;for(;d<-180;)d+=360;return d}static clampValue(value,min,max){return Math.max(min,Math.min(max,value))}static isAircraftParkedAndCold(){return 0===window.controls?.gear?.position&&!window.geofs?.animation?.values?.enginesOn&&window.geofs?.aircraft?.instance?.groundContact}constructor(){this.padControls=new Map}static getClickScreenCoords(){const mouse=window.controls?.mouse;if(!mouse)return null;const rawX=mouse.lastX??mouse.originalX,rawY=mouse.lastY??mouse.originalY,oX=mouse.oX??0,oY=mouse.oY??0;return Number.isFinite(rawX)&&Number.isFinite(rawY)?{x:rawX-oX,y:rawY-oY}:null}getClickScreenCoords(){return HelperModule.getClickScreenCoords()}getPadsContainer(){return document.querySelector(".geofs-pads-container")}createPadButton(options){const cfg=options??{},label=String(cfg.label??"BTN"),id=String(cfg.id??""),onClick="function"==typeof cfg.onClick?cfg.onClick:()=>{},outer=document.createElement("div");id&&(outer.id=id),outer.className="geofs-inline-overlay geofs-textOverlay control-pad geofs-visible geofs-manipulator",outer.style.backgroundSize="50px 25px",outer.style.marginLeft="0px",outer.style.marginBottom="0px",outer.style.zIndex="60",outer.style.backgroundPosition="0px 0px",outer.style.width="50px",outer.style.height="25px",outer.style.transformOrigin="0px 25px",outer.style.opacity="1",outer.style.transform="rotate(0deg)",outer.style.position="relative",outer.style.cursor="pointer";const inner=document.createElement("div");return inner.className="geofs-overlay geofs-textOverlay control-pad-dyn-label geofs-visible",inner.style.backgroundSize="50px 25px",inner.style.marginLeft="0px",inner.style.marginBottom="0px",inner.style.left="0px",inner.style.bottom="0px",inner.style.zIndex="61",inner.style.backgroundPosition="0px 0px",inner.style.width="50px",inner.style.height="25px",inner.style.transformOrigin="0px 25px",inner.style.opacity="1",inner.style.transform="rotate(0deg)",inner.textContent=label,cfg?.outerStyle&&"object"==typeof cfg.outerStyle&&Object.assign(outer.style,cfg.outerStyle),cfg?.innerStyle&&"object"==typeof cfg.innerStyle&&Object.assign(inner.style,cfg.innerStyle),outer.appendChild(inner),outer.addEventListener("click",onClick),outer}installPadControl(options){const cfg=options??{},id=String(cfg.id??"").trim(),element=cfg.element,prepend=!1!==cfg.prepend;if(!id||!element)return!1;const padsContainer=this.getPadsContainer();return!!padsContainer&&(this.removePadControl(id),prepend?padsContainer.prepend(element):padsContainer.appendChild(element),this.padControls.set(id,element),!0)}removePadControl(id){const key=String(id??"").trim();if(!key)return;const element=this.padControls.get(key)??document.getElementById(key);element&&element.remove(),this.padControls.delete(key)}}class OptionModule{static STORAGE_KEY="F18Options";static storageKeysByAircraft=Object.create(null);static optionKeyCache=Object.create(null);static optionStoreCache=null;static initializeStorageKey(aircraftId,storageKey){return OptionModule.storageKeysByAircraft[aircraftId]=storageKey,!0}static useStorageKeyForAircraft(aircraftId){const nextStorageKey=OptionModule.storageKeysByAircraft[aircraftId];return!(!nextStorageKey||nextStorageKey===OptionModule.STORAGE_KEY)&&(OptionModule.STORAGE_KEY=nextStorageKey,OptionModule.optionStoreCache=null,!0)}static normalizeOptionToken(value){return String(value??"").trim().toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_+|_+$/g,"")}static getCachedOptionKey(pageTitle,buttonKey){const pageToken=OptionModule.normalizeOptionToken(pageTitle),buttonToken=OptionModule.normalizeOptionToken(buttonKey),cacheId=`${pageToken}\0${buttonToken}`;let optionKey=OptionModule.optionKeyCache[cacheId];return optionKey||(optionKey=`${pageToken}.${buttonToken}`,OptionModule.optionKeyCache[cacheId]=optionKey,optionKey)}static buildOptionKey(pageTitle,buttonKey){return OptionModule.getCachedOptionKey(pageTitle,buttonKey)}static readOptions(){if(OptionModule.optionStoreCache)return OptionModule.optionStoreCache;const raw=window.localStorage.getItem(OptionModule.STORAGE_KEY);return raw?(OptionModule.optionStoreCache=JSON.parse(raw),OptionModule.optionStoreCache):(OptionModule.optionStoreCache={},OptionModule.optionStoreCache)}static getOption(pageTitle,buttonKey,fallback=null){return OptionModule.readOptions()[OptionModule.buildOptionKey(pageTitle,buttonKey)]??fallback}static writeOptions(options){const payload=options??{};return OptionModule.optionStoreCache=payload,window.localStorage.setItem(OptionModule.STORAGE_KEY,JSON.stringify(payload)),!0}static setOption(pageTitle,buttonKey,value){const options=OptionModule.readOptions();options[OptionModule.getCachedOptionKey(pageTitle,buttonKey)]=value,OptionModule.writeOptions(options)}static getOptionValue(pageTitle,buttonKey,fallback=null){const selectedState=OptionModule.getOption(pageTitle,buttonKey,null),pages=window.BasePlugin.getActiveMfdPages();if(!pages.length)return selectedState??fallback;const page=pages.find(p=>p?.title===pageTitle);if(!page)return selectedState??fallback;const button=[...Array.isArray(page.leftButtons)?page.leftButtons:[],...Array.isArray(page.rightButtons)?page.rightButtons:[]].find(b=>b?.key===buttonKey||b?.label===buttonKey);if(!button||!Array.isArray(button.values)||!button.values.length)return selectedState??fallback;let stateIndex=-1;return null!=selectedState&&Array.isArray(button.states)&&(stateIndex=button.states.findIndex(s=>s===selectedState)),stateIndex<0&&Number.isInteger(button.stateIndex)&&(stateIndex=button.stateIndex),stateIndex>=0&&stateIndex{const mode=OptionModule.getOption("WPN","MODE","NAV"),modeLoadout=this.getModeLoadout(mode);this.selectNextWeapon(mode,modeLoadout,0)},show:()=>1===window.controls?.gear?.position&&window.geofs?.animation?.values?.haglFeet>50},{key:"CONFIG",label:"CFG",states:["A/A","L/R A/A","A/G","L/R A/G","L/R","MIN","CLEAN"],stateIndex:0,show:()=>HelperModule.isAircraftParkedAndCold()}],rightButtons:[{key:"MODE",label:"MODE",states:["NAV","A/A","A/G","JETTISON"],stateIndex:0},{key:"FIRE",label:"FIRE",states:["N/A"],stateIndex:0,onClick:({page:page})=>{const mode=OptionModule.getOption("WPN","MODE","NAV"),modeLoadout=this.getModeLoadout(mode);this.fireSelectedWeapon(mode,modeLoadout)},show:()=>1===window.controls?.gear?.position&&window.geofs?.animation?.values?.haglFeet>50&&"OFF"!==OptionModule.getOption("WPN","MASTER","OFF")&&"JETTISON"!==OptionModule.getOption("WPN","MODE","NAV")},{key:"JETTISON",label:"JETT",states:["N/A"],stateIndex:0,onClick:({page:page})=>{const mode=OptionModule.getOption("WPN","MODE","NAV"),modeLoadout=this.getModeLoadout(mode);this.jettisonSelectedWeapon(mode,modeLoadout)},show:()=>1===window.controls?.gear?.position&&window.geofs?.animation?.values?.haglFeet>50&&"JETTISON"===OptionModule.getOption("WPN","MODE","NAV")},{key:"REARM",label:"ARM",states:["START"],stateIndex:0,onClick:({page:page})=>{const config=OptionModule.getOption("WPN","CONFIG","A/A");this.startRearm(config)},show:()=>HelperModule.isAircraftParkedAndCold()&&"OFF"===OptionModule.getOption("WPN","MASTER","OFF")}],lines:[],render:(renderer,renderContext)=>{const ctx=renderContext?.ctx??renderer?.canvasAPI?.context,w=renderContext?.w??renderer?.canvasAPI?.canvas?.width??512,h=renderContext?.h??renderer?.canvasAPI?.canvas?.height??512;if(!ctx)return;this.updateRearmState();const selectedMode=OptionModule.getOption("WPN","MODE","NAV"),modeLoadout=this.getModeLoadout(selectedMode);if(!modeLoadout)return;const selectedWeapon=this.ensureSelectedWeapon(selectedMode,modeLoadout),fireButton=renderContext?.page?.rightButtons?.find(b=>"FIRE"===b?.key);fireButton&&(fireButton.states=[this.getSelectedLoadDisplay(selectedMode,modeLoadout)],fireButton.stateIndex=0);const jettisonButton=renderContext?.page?.rightButtons?.find(b=>"JETTISON"===b?.key);jettisonButton&&(jettisonButton.states=[this.getSelectedLoadDisplay(selectedMode,modeLoadout)],jettisonButton.stateIndex=0);const color=renderContext?.color??"#00ff66",left=modeLoadout?.left??{},right=modeLoadout?.right??{},gunRounds=Number.isFinite(modeLoadout?.gun)?modeLoadout.gun:"--",drawStation=(x,y,station,options={})=>{const quantity=Number.isFinite(station?.quantity)?String(station.quantity):"--",display=station?.display??"--",showDiamond=!1!==options.showDiamond,boxedQuantity=!0===options.boxedQuantity;if(showDiamond&&((x,y,size)=>{ctx.beginPath(),ctx.moveTo(x,y-size),ctx.lineTo(x+size,y),ctx.lineTo(x,y+size),ctx.lineTo(x-size,y),ctx.closePath(),ctx.stroke()})(x,y-.036*h,.012*w),ctx.textAlign="center",ctx.textBaseline="middle",ctx.font=`bold ${Math.round(.042*h)}px monospace`,boxedQuantity){const boxW=.078*w,boxH=.044*h,by=y-.5*boxH+.003*h;ctx.strokeRect(x-.5*boxW,by+1,boxW,boxH)}ctx.fillText(quantity,x,y+4),ctx.fillText(display,x,y+.045*h+4)};ctx.save(),ctx.setTransform(1,0,0,1,0,0),ctx.strokeStyle=color,ctx.fillStyle=color,ctx.lineWidth=Math.max(1.4,.003*w);const yOffset=.11*h,cx=.5*w,leftRootX=.44*w,rightRootX=.56*w,topY=.2*h+yOffset,midY=.31*h+yOffset,breakY=.4*h+yOffset,tipY=.54*h+yOffset,leftBreakX=.31*w,rightBreakX=.69*w,leftTipX=.09*w,rightTipX=.91*w;if(ctx.textAlign="center",ctx.textBaseline="middle",ctx.font=`bold ${Math.round(.048*h)}px monospace`,"gun"===selectedWeapon?.station){const boxW=.12*w,boxH=.06*h;ctx.strokeRect(cx-.5*boxW,topY-.5*boxH,boxW,boxH)}ctx.fillText(String(gunRounds),cx,topY),ctx.beginPath(),ctx.moveTo(leftRootX,topY),ctx.lineTo(leftRootX,midY),ctx.lineTo(leftBreakX,breakY),ctx.lineTo(leftTipX,tipY),ctx.moveTo(rightRootX,topY),ctx.lineTo(rightRootX,midY),ctx.lineTo(rightBreakX,breakY),ctx.lineTo(rightTipX,tipY),ctx.stroke(),ctx.font=`bold ${Math.round(.055*h)}px monospace`,ctx.fillText("FUEL",cx,.35*h+yOffset),"OFF"!==OptionModule.getOption("WPN","MASTER","OFF")&&ctx.fillText("ARM",cx,.47*h+yOffset),ctx.font=`bold ${Math.round(.046*h)}px monospace`,drawStation(.06*w,.5*h+yOffset,left?.wingtip,{showDiamond:!1,boxedQuantity:"left"===selectedWeapon?.side&&"wingtip"===selectedWeapon?.station}),drawStation(.18*w,.54*h+yOffset,left?.hardpoint1,{boxedQuantity:"left"===selectedWeapon?.side&&"hardpoint1"===selectedWeapon?.station}),drawStation(.29*w,.47*h+yOffset,left?.hardpoint2,{boxedQuantity:"left"===selectedWeapon?.side&&"hardpoint2"===selectedWeapon?.station}),drawStation(.71*w,.47*h+yOffset,right?.hardpoint2,{boxedQuantity:"right"===selectedWeapon?.side&&"hardpoint2"===selectedWeapon?.station}),drawStation(.82*w,.54*h+yOffset,right?.hardpoint1,{boxedQuantity:"right"===selectedWeapon?.side&&"hardpoint1"===selectedWeapon?.station}),drawStation(.94*w,.5*h+yOffset,right?.wingtip,{showDiamond:!1,boxedQuantity:"right"===selectedWeapon?.side&&"wingtip"===selectedWeapon?.station}),this.isFireFlashVisible()&&(ctx.textBaseline="middle",ctx.font=`bold ${Math.round(.12*h)}px monospace`,ctx.fillStyle="#ff0000",ctx.fillText(this.getActionFlashLabel(),cx,.72*h),ctx.fillStyle=color);const rearmTextY=.84*h;ctx.textBaseline="middle";const wpnRearmState=this.rearmState;if(wpnRearmState.active){const progress=Math.max(0,Math.min(1,wpnRearmState.progress??0)),pct=Math.round(100*progress),barW=.5*w,barH=.03*h,barX=cx-.5*barW,barY=.875*h;ctx.font=`bold ${Math.round(.034*h)}px monospace`,ctx.fillText(`REARMING ${wpnRearmState.config} ${pct}%`,cx,rearmTextY),ctx.strokeRect(barX,barY,barW,barH),ctx.fillRect(barX,barY,barW*progress,barH)}else ctx.font=`bold ${Math.round(.03*h)}px monospace`,ctx.fillText("Rearm with Engine OFF, Master OFF on ground.",cx,rearmTextY);ctx.restore()}}),!0}isModeCompatibleStation(mode,stationName,stationData){if("JETTISON"===mode)return"gun"!==stationName;if("gun"===stationName)return"NAV"!==mode;if("NAV"===mode)return!1;const stationType=stationData.type;return!stationType||stationType===mode}saveStateToStorage(){const payload={config:OptionModule.getOption("WPN","CONFIG","A/A"),loadout:this.currentLoadout,selected:this.selectedWeaponByMode};window.localStorage.setItem(this.STORAGE_KEY,JSON.stringify(payload))}loadStateFromStorage(){const raw=window.localStorage.getItem(this.STORAGE_KEY);if(!raw)return;const parsed=JSON.parse(raw),storedLoadout=parsed.loadout,baseTemplate=HelperModule.deepCloneJson(this.loadoutTemplates["A/A"]);baseTemplate.gun=storedLoadout.gun;for(const sideKey of["left","right"])for(const stationKey of Object.keys(baseTemplate[sideKey])){const stationTemplate=baseTemplate[sideKey][stationKey],stationStored=storedLoadout[sideKey][stationKey];stationTemplate.quantity=stationStored.quantity,stationTemplate.load=stationStored.load,stationTemplate.display=stationStored.display,stationTemplate.type=stationStored.type}this.currentLoadout=baseTemplate;for(const key of Object.keys(this.selectedWeaponByMode))delete this.selectedWeaponByMode[key];const storedSelected=parsed.selected;for(const modeKey of Object.keys(storedSelected)){const selected=storedSelected[modeKey];this.selectedWeaponByMode[modeKey]={side:selected.side,station:selected.station}}this.rearmState.config=parsed.config}resolveTemplateConfig(config){return this.loadoutTemplates[config]?config:this.loadoutTemplates["A/A"]?"A/A":Object.keys(this.loadoutTemplates)[0]}getRearmTemplateByMode(config){const resolvedConfig=this.resolveTemplateConfig(config),sourceTemplate=this.loadoutTemplates[resolvedConfig];return sourceTemplate?HelperModule.deepCloneJson(sourceTemplate):null}zeroCurrentLoadout(){if(this.currentLoadout){this.currentLoadout.gun=0;for(const sideKey of["left","right"]){const sideStations=this.currentLoadout[sideKey];for(const stationKey of Object.keys(sideStations))Number.isFinite(sideStations[stationKey].quantity)&&(sideStations[stationKey].quantity=0)}}}applyRearmProgress(targetByMode,progress){const p=Math.max(0,Math.min(1,progress));if(this.currentLoadout&&targetByMode){this.currentLoadout.gun=Math.floor(targetByMode.gun*p);for(const sideKey of["left","right"]){this.currentLoadout[sideKey]=this.currentLoadout[sideKey]??{};const targetSide=targetByMode[sideKey]??{};for(const stationKey of Object.keys(targetSide)){const targetStation=targetSide[stationKey]??{};this.currentLoadout[sideKey][stationKey]=this.currentLoadout[sideKey][stationKey]??{},this.currentLoadout[sideKey][stationKey].load=targetStation.load,this.currentLoadout[sideKey][stationKey].display=targetStation.display,this.currentLoadout[sideKey][stationKey].type=targetStation.type;const targetQuantity=Number.isFinite(targetStation.quantity)?targetStation.quantity:0;this.currentLoadout[sideKey][stationKey].quantity=Math.floor(targetQuantity*p)}}}}startRearm(config){if(this.rearmState.active)return!1;if(!HelperModule.isAircraftParkedAndCold()||"OFF"!==OptionModule.getOption("WPN","MASTER","OFF"))return!1;const resolvedConfig=this.resolveTemplateConfig(config),targetByMode=this.getRearmTemplateByMode(resolvedConfig);if(!resolvedConfig||!targetByMode)return!1;this.zeroCurrentLoadout();for(const modeKey of Object.keys(this.selectedWeaponByMode))delete this.selectedWeaponByMode[modeKey];return this.rearmState.active=!0,this.rearmState.startTime=Date.now(),this.rearmState.progress=0,this.rearmState.config=resolvedConfig,this.rearmState.status="REARMING",this.rearmState.lastSavedPercent=-1,this.rearmState.targetByMode=targetByMode,this.saveStateToStorage(),!0}updateRearmState(){if(!this.rearmState.active)return;if(window.geofs?.animation?.values?.enginesOn)return this.rearmState.active=!1,this.rearmState.status="ABORTED",this.rearmState.targetByMode=null,void this.saveStateToStorage();const elapsed=Date.now()-this.rearmState.startTime,duration=Math.max(1,Number.isFinite(this.rearmState.durationMs)?this.rearmState.durationMs:this.REARM_DURATION_MS),progress=Math.max(0,Math.min(1,elapsed/duration));this.rearmState.progress=progress,this.applyRearmProgress(this.rearmState.targetByMode,progress);const percent=Math.round(100*progress);percent!==this.rearmState.lastSavedPercent&&(this.rearmState.lastSavedPercent=percent,this.saveStateToStorage()),progress>=1&&(this.rearmState.active=!1,this.rearmState.status="READY",this.rearmState.targetByMode=null,this.saveStateToStorage())}stopGunFireTimer(){const wasFiring=this.gunFireState.firing;this.gunFireState.firing=!1,this.gunFireState.timerId&&(clearTimeout(this.gunFireState.timerId),this.gunFireState.timerId=null),this.gunFireState.mode=null,this.gunFireState.roundsRemainingInBurst=0,this.gunFireState.triggerHeld=!1,this.gunFireState.accumulator=0,wasFiring&&this.emit("gunstate",{firing:!1})}processGunFireTick(){const state=this.gunFireState,now=performance.now(),elapsedSeconds=Math.min(.2,Math.max(0,(now-state.lastTickAt)/1e3));state.lastTickAt=now,state.accumulator+=elapsedSeconds*this.GUN_FIRE_RATE_RPS;let roundsDue=Math.floor(state.accumulator);state.accumulator-=roundsDue;const mode=state.mode,modeLoadout=this.getModeLoadout(mode);for(;roundsDue>0&&(state.triggerHeld||state.roundsRemainingInBurst>0)&&modeLoadout.gun>0;)modeLoadout.gun-=1,state.triggerHeld||(state.roundsRemainingInBurst-=1),roundsDue-=1,this.emitFireEvent(mode,{side:"center",station:"gun"},{load:"GUN"});return modeLoadout.gun>0?!state.triggerHeld&&state.roundsRemainingInBurst<=0?(this.stopGunFireTimer(),void this.saveStateToStorage()):void(state.timerId=setTimeout(()=>this.processGunFireTick(),this.GUN_FIRE_TICK_MS)):(this.stopGunFireTimer(),this.selectNextWeapon(mode,modeLoadout,0),void this.saveStateToStorage())}beginGunFireTimer(mode){const state=this.gunFireState;state.mode=mode,state.firing||(state.lastTickAt=performance.now(),state.accumulator=1,this.emit("gunstate",{firing:!0}),this.triggerFireFlash(),state.firing=!0,this.processGunFireTick())}startGunFire(mode,modeLoadout){return!modeLoadout||!Number.isFinite(modeLoadout.gun)||modeLoadout.gun<=0?(this.emit("dryfire",{weapon:"GUN"}),!1):(this.gunFireState.roundsRemainingInBurst+=this.GUN_ROUNDS_PER_BURST,this.beginGunFireTimer(mode),!0)}startGunTrigger(mode,modeLoadout){return!modeLoadout||!Number.isFinite(modeLoadout.gun)||modeLoadout.gun<=0?(this.emit("dryfire",{weapon:"GUN"}),!1):(this.gunFireState.triggerHeld=!0,this.beginGunFireTimer(mode),!0)}pressTrigger(){const mode=OptionModule.getOption("WPN","MODE","NAV");if("NAV"===mode||"JETTISON"===mode)return this.emit("blocked",{reason:"mode",mode:mode}),!1;if("OFF"===OptionModule.getOption("WPN","MASTER","OFF"))return this.emit("blocked",{reason:"master"}),!1;const modeLoadout=this.getModeLoadout(mode);let selected=this.ensureSelectedWeapon(mode,modeLoadout);return!selected&&this.selectNextWeapon(mode,modeLoadout,0)&&(selected=this.ensureSelectedWeapon(mode,modeLoadout)),"gun"===selected?.station?this.startGunTrigger(mode,modeLoadout):this.fireSelectedWeapon(mode,modeLoadout)}releaseTrigger(){this.gunFireState.triggerHeld&&(this.gunFireState.triggerHeld=!1,this.gunFireState.roundsRemainingInBurst<=0&&(this.stopGunFireTimer(),this.saveStateToStorage()))}triggerActionFlash(label="FIRE"){this.fireFlash.startTime=Date.now(),this.fireFlash.label=label}triggerFireFlash(){this.triggerActionFlash("FIRE")}getActionFlashLabel(){return this.fireFlash.label||"FIRE"}isFireFlashVisible(){if(!this.fireFlash.startTime)return!1;const elapsed=Date.now()-this.fireFlash.startTime;return elapsed>=this.FIRE_BLINK_INTERVAL_MS*this.FIRE_BLINK_PHASES?(this.fireFlash.startTime=0,this.fireFlash.label="FIRE",!1):Math.floor(elapsed/this.FIRE_BLINK_INTERVAL_MS)%2==0}getModeLoadout(){return this.currentLoadout??null}getStationQuantity(modeLoadout,side,station){if("gun"===station){const gun=modeLoadout?.gun;return Number.isFinite(gun)?gun:0}const q=modeLoadout?.[side]?.[station]?.quantity;return Number.isFinite(q)?q:0}canUseStationForMode(mode,modeLoadout,side,station,minimumQuantity=0){if(!modeLoadout||!station)return!1;if("gun"===station)return!!this.isModeCompatibleStation(mode,station,null)&&this.getStationQuantity(modeLoadout,side,station)>minimumQuantity;const stationData=modeLoadout?.[side]?.[station];return!!stationData&&(!!this.isModeCompatibleStation(mode,station,stationData)&&this.getStationQuantity(modeLoadout,side,station)>minimumQuantity)}ensureSelectedWeapon(mode,modeLoadout){if(!modeLoadout)return null;const current=this.selectedWeaponByMode[mode];if("gun"===current?.station&&Number.isFinite(modeLoadout?.gun))return this.isModeCompatibleStation(mode,"gun",null)?current:null;if(current?.side&¤t?.station&&modeLoadout?.[current.side]?.[current.station]){const stationData=modeLoadout[current.side][current.station];return this.isModeCompatibleStation(mode,current.station,stationData)?current:null}return null}getSelectedLoadDisplay(mode,modeLoadout){const selected=this.ensureSelectedWeapon(mode,modeLoadout);if(!selected)return"N/A";if("gun"===selected.station)return"GUN";const station=modeLoadout?.[selected.side]?.[selected.station];return station?.load??"N/A"}getSelectedQuantityLine(mode,modeLoadout){const selected=this.ensureSelectedWeapon(mode,modeLoadout);if(!selected)return"N/A";if("gun"===selected.station){return`${Number.isFinite(modeLoadout?.gun)?modeLoadout.gun:0}x GUN`}const station=modeLoadout?.[selected.side]?.[selected.station];if(!station)return"N/A";return`${Number.isFinite(station.quantity)?station.quantity:0}x ${station.load??station.display??"N/A"}`}getSelectedWeaponEffectiveness(mode,modeLoadout){const selected=this.ensureSelectedWeapon(mode,modeLoadout);if(!selected||"gun"===selected.station)return null;const station=modeLoadout[selected.side][selected.station],profile=WeaponModule.effectivenessByType.find(item=>item.name===station.load);return profile||null}getEffectivenessMarkerFractions(profile){const minEngagement=profile.engagement_window.min,maxEngagement=profile.engagement_window.max,span=maxEngagement-minEngagement;return{engagementMax:0,effectiveMax:(maxEngagement-profile.effective_range.max)/span,effectiveMin:(maxEngagement-profile.effective_range.min)/span,engagementMin:1}}getEffectivenessDistanceFraction(profile,distanceNm){const minEngagement=profile.engagement_window.min,maxEngagement=profile.engagement_window.max,fraction=(maxEngagement-distanceNm)/(maxEngagement-minEngagement);return HelperModule.clampValue(fraction,0,1)}hasRadarHardLock(){const addon=window.BasePlugin?.getActiveAddon?.();return addon?.combat?.targets?addon.combat.targets.hasLock():!!addon?.radar?.hardLockedUid}selectNextWeapon(mode,modeLoadout,minimumQuantity=0){if(!modeLoadout)return!1;const current=this.ensureSelectedWeapon(mode,modeLoadout),currentIndex=current?Math.max(0,this.STATION_RENDER_ORDER.findIndex(s=>s.side===current.side&&s.station===current.station)):-1;for(let step=1;step<=this.STATION_RENDER_ORDER.length;step++){const index=(currentIndex+step)%this.STATION_RENDER_ORDER.length,candidate=this.STATION_RENDER_ORDER[index];if(this.canUseStationForMode(mode,modeLoadout,candidate.side,candidate.station,minimumQuantity))return this.selectedWeaponByMode[mode]={side:candidate.side,station:candidate.station},this.saveStateToStorage(),!0}return!1}selectPreviousWeapon(mode,modeLoadout,minimumQuantity=0){if(!modeLoadout)return!1;const current=this.ensureSelectedWeapon(mode,modeLoadout),currentIndex=current?this.STATION_RENDER_ORDER.findIndex(s=>s.side===current.side&&s.station===current.station):0;for(let step=1;step<=this.STATION_RENDER_ORDER.length;step+=1){const index=(currentIndex-step+this.STATION_RENDER_ORDER.length)%this.STATION_RENDER_ORDER.length,candidate=this.STATION_RENDER_ORDER[index];if(this.canUseStationForMode(mode,modeLoadout,candidate.side,candidate.station,minimumQuantity))return this.selectedWeaponByMode[mode]={side:candidate.side,station:candidate.station},this.saveStateToStorage(),!0}return!1}selectSameWeaponHardpoint(mode,modeLoadout,selected){if(!modeLoadout||!selected)return!1;if("gun"===selected.station)return!1;if(!String(selected.station).startsWith("hardpoint"))return!1;const currentStation=modeLoadout?.[selected.side]?.[selected.station],currentLoadType=currentStation?.load;if(!currentLoadType)return!1;if(!this.isModeCompatibleStation(mode,selected.station,currentStation))return!1;const selectedIndex=this.STATION_RENDER_ORDER.findIndex(s=>s.side===selected.side&&s.station===selected.station);if(selectedIndex<0)return!1;for(let step=1;step<=this.STATION_RENDER_ORDER.length;step++){const index=(selectedIndex+step)%this.STATION_RENDER_ORDER.length,candidate=this.STATION_RENDER_ORDER[index];if(!candidate?.station||!String(candidate.station).startsWith("hardpoint"))continue;const candidateStation=modeLoadout?.[candidate.side]?.[candidate.station];if(candidateStation&&(candidateStation.load===currentLoadType&&this.isModeCompatibleStation(mode,candidate.station,candidateStation)&&Number.isFinite(candidateStation.quantity)&&!(candidateStation.quantity<=0)))return this.selectedWeaponByMode[mode]={side:candidate.side,station:candidate.station},this.saveStateToStorage(),!0}return!1}on(eventName,listener){return"function"!=typeof listener?()=>{}:(this.listeners.has(eventName)||this.listeners.set(eventName,new Set),this.listeners.get(eventName).add(listener),()=>this.off(eventName,listener))}off(eventName,listener){this.listeners.get(eventName)?.delete(listener)}emit(eventName,payload){for(const listener of this.listeners.get(eventName)??[])try{listener(payload)}catch(error){console.error(`[WeaponModule] ${eventName} listener failed`,error)}}emitFireEvent(mode,selected,station){const load=station?.load??("gun"===selected?.station?"GUN":null),profile=load?WeaponModule.effectivenessByType.find(item=>item.name===load):null,projectile="GUN"===load?{...WeaponModule.gunMetadata}:{...WeaponModule.defaultMissileMetadata,...WeaponModule.projectileMetadataByType[load]??{}};this.emit("fire",{mode:mode,selected:selected?{...selected}:null,weapon:load,metadata:{engagement_window:profile?{...profile.engagement_window}:null,effective_range:profile?{...profile.effective_range}:null,projectile:projectile}})}fireSelectedWeapon(mode,modeLoadout){if(!modeLoadout)return!1;if("NAV"===mode||"JETTISON"===mode)return!1;if("OFF"===OptionModule.getOption("WPN","MASTER","OFF"))return!1;let selected=this.ensureSelectedWeapon(mode,modeLoadout);if(!selected){if(!this.selectNextWeapon(mode,modeLoadout,0))return!1;if(selected=this.ensureSelectedWeapon(mode,modeLoadout),!selected)return!1}if("gun"===selected.station)return this.startGunFire(mode,modeLoadout);if(!this.hasRadarHardLock())return this.emit("blocked",{reason:"lock"}),!1;const station=modeLoadout?.[selected.side]?.[selected.station];return!(!station||!Number.isFinite(station.quantity))&&(station.quantity<=0?(this.emit("dryfire",{weapon:station.load}),this.selectSameWeaponHardpoint(mode,modeLoadout,selected)||this.selectNextWeapon(mode,modeLoadout,0),!1):(station.quantity-=1,this.triggerFireFlash(),this.emitFireEvent(mode,selected,station),this.saveStateToStorage(),station.quantity<=0&&(this.selectSameWeaponHardpoint(mode,modeLoadout,selected)||this.selectNextWeapon(mode,modeLoadout,0)),!0))}jettisonSelectedWeapon(mode,modeLoadout){if(!modeLoadout)return!1;if("JETTISON"!==mode)return!1;let selected=this.ensureSelectedWeapon(mode,modeLoadout);if(!selected){if(!this.selectNextWeapon(mode,modeLoadout,0))return!1;if(selected=this.ensureSelectedWeapon(mode,modeLoadout),!selected)return!1}if("gun"===selected.station)return!1;const station=modeLoadout?.[selected.side]?.[selected.station];return!(!station||!Number.isFinite(station.quantity))&&(station.quantity<=0?(this.emit("dryfire",{weapon:station.load}),this.selectSameWeaponHardpoint(mode,modeLoadout,selected)||this.selectNextWeapon(mode,modeLoadout,0),!1):(station.quantity=0,this.triggerActionFlash("JETT"),this.saveStateToStorage(),this.selectSameWeaponHardpoint(mode,modeLoadout,selected)||this.selectNextWeapon(mode,modeLoadout,0),!0))}}!function(){"use strict";class CombatMath{static DEG=Math.PI/180;static R_EARTH=6378137;static NM=1852;static dot(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]}static cross(a,b){return[a[1]*b[2]-a[2]*b[1],a[2]*b[0]-a[0]*b[2],a[0]*b[1]-a[1]*b[0]]}static add(a,b){return[a[0]+b[0],a[1]+b[1],a[2]+b[2]]}static mul(a,s){return[a[0]*s,a[1]*s,a[2]*s]}static normalizeHeading(heading){return(heading%360+360)%360}static angleDifference(from,to){return(to-from+540)%360-180}static moveGeoPoint(lat,lon,northMeters,eastMeters){const latitudeRad=lat*CombatMath.DEG,nextLat=lat+northMeters/CombatMath.R_EARTH/CombatMath.DEG,longitudeScale=Math.max(.01,Math.cos(latitudeRad));return{lat:nextLat,lon:lon+eastMeters/(CombatMath.R_EARTH*longitudeScale)/CombatMath.DEG}}static bearingAndDistance(own,lat,lon,alt){const deg=CombatMath.DEG,dLat=(lat-own[0])*deg,dLon=(lon-own[1])*deg,lat1=own[0]*deg,lat2=lat*deg,a=Math.sin(dLat/2)**2+Math.cos(lat1)*Math.cos(lat2)*Math.sin(dLon/2)**2,groundDistance=2*CombatMath.R_EARTH*Math.atan2(Math.sqrt(a),Math.sqrt(1-a)),distance=Math.hypot(groundDistance,alt-own[2]),y=Math.sin(dLon)*Math.cos(lat2),x=Math.cos(lat1)*Math.sin(lat2)-Math.sin(lat1)*Math.cos(lat2)*Math.cos(dLon);return{bearing:CombatMath.normalizeHeading(Math.atan2(y,x)/deg),distance:distance}}static worldPosition(enuMat,p){return Cesium.Matrix4.multiplyByPoint(enuMat,new Cesium.Cartesian3(p[0],p[1],p[2]),new Cesium.Cartesian3)}static projectWorld(scene,world){return(Cesium.SceneTransforms.worldToWindowCoordinates||Cesium.SceneTransforms.wgs84ToWindowCoordinates).call(Cesium.SceneTransforms,scene,world)}static turnVelocity(velocity,desired,maxAngle){const{dot:dot,cross:cross,add:add,mul:mul}=CombatMath,speed=Math.hypot(velocity[0],velocity[1],velocity[2]),desiredSpeed=Math.hypot(desired[0],desired[1],desired[2]);if(speed<1e-6||desiredSpeed<1e-6)return velocity;const current=mul(velocity,1/speed),target=mul(desired,1/desiredSpeed),cosine=Math.max(-1,Math.min(1,dot(current,target))),angle=Math.acos(cosine);if(angle<1e-6)return mul(target,speed);const axisVector=cross(current,target),axisLength=Math.hypot(axisVector[0],axisVector[1],axisVector[2]);let axis;if(axisLength<1e-6){axis=cross(current,Math.abs(current[0])<.9?[1,0,0]:[0,1,0]);axis=mul(axis,1/Math.hypot(axis[0],axis[1],axis[2]))}else axis=mul(axisVector,1/axisLength);const turn=Math.min(angle,maxAngle),c=Math.cos(turn),s=Math.sin(turn),rotated=add(add(mul(current,c),mul(cross(axis,current),s)),mul(axis,dot(axis,current)*(1-c)));return mul(rotated,speed)}static ensureGeneralFieldset(className,legendText,instructionsText){const preferences=document.querySelector(".geofs-preferences"),general=preferences?.querySelector(":scope > li:first-of-type > .geofs-collapsible");if(!general)return null;let fieldset=general.querySelector(`.${className}`),created=!1;if(!fieldset){created=!0,fieldset=document.createElement("fieldset"),fieldset.className=className;const legend=document.createElement("legend");if(legend.textContent=legendText,fieldset.appendChild(legend),instructionsText){const instructions=document.createElement("p");instructions.textContent=instructionsText,instructions.style.margin="8px 0",fieldset.appendChild(instructions)}const controls=document.createElement("div");controls.className=`${className}-controls`,fieldset.appendChild(controls),general.appendChild(fieldset)}return{fieldset:fieldset,controls:fieldset.querySelector(`.${className}-controls`),created:created}}static makeButton(text,ariaLabel,onClick,disabled=!1){const button=document.createElement("button");return button.type="button",button.className="mdl-button mdl-js-button mdl-button--raised mdl-button--colored",button.textContent=text,button.setAttribute("aria-label",ariaLabel),button.disabled=disabled,button.addEventListener("click",event=>event.stopPropagation()),button.addEventListener("click",onClick),button}static makeSelect(labelText,value,values,onChange,ariaLabel,formatOption=String){const label=document.createElement("label");label.style.display="flex",label.style.alignItems="center",label.style.gap="6px",label.textContent=labelText;const select=document.createElement("select");select.setAttribute("aria-label",ariaLabel);for(const optionValue of values){const option=document.createElement("option");option.value=String(optionValue),option.textContent=formatOption(optionValue),select.appendChild(option)}return select.value=String(value),select.addEventListener("change",event=>{event.stopPropagation(),onChange(Number(select.value))}),select.addEventListener("click",event=>event.stopPropagation()),label.appendChild(select),label}static readStorage(key,fallback=null){try{const raw=window.localStorage.getItem(key);return null===raw?fallback:JSON.parse(raw)}catch(error){return fallback}}static writeStorage(key,value){try{return window.localStorage.setItem(key,JSON.stringify(value)),!0}catch(error){return!1}}}window.CombatMath=CombatMath,window.CombatContext=class CombatContext{constructor(){this.weapons=null,this.overlay=null,this.targets=null,this.audio=null,this.projectile=null,this.aaCombat=null,this.multiplayer=null,this.notifyListeners=new Set}onNotify(listener){return this.notifyListeners.add(listener),()=>this.notifyListeners.delete(listener)}notify(text,durationMs=2e3){for(const listener of this.notifyListeners)try{listener(text,durationMs)}catch(error){console.error("[Combat] notify listener failed",error)}}}}(),function(){"use strict";const{dot:dot,cross:cross,add:add,mul:mul,DEG:DEG,R_EARTH:R_EARTH}=CombatMath;class WeaponOverlayModule{constructor(combat,config={}){this.combat=combat,combat.overlay=this,this.cfg={color:"#94ffaf",maskBottom:.62,lineDeg:.12,hudOffset:{x:0,y:0},cockpitOnly:!0,orientationSource:"aircraft",zIndex:9,enabled:!0,...config},this.enabled=this.cfg.enabled,this.canvas=null,this.ctx=null,this.dpr=1,this.rafId=null,this.layers=[],this.aircraftChangeListeners=new Set,this.lastFrameTime=0,this.lastInstance=null,this.frameContext=null,this.vel=[0,0,0],this.omega=[0,0,0],this.lastPos=null,this.lastT=0,this.prevAxes=null,this.combos=[];for(const hs of[1,-1])for(const ps of[1,-1])for(const rs of[1,-1])this.combos.push([hs,ps,rs]);this.scores=this.combos.map(()=>0),this.best=0,this.impacts=[],this.onResize=()=>this.resize(),this.frame=()=>this.renderFrame()}start(){this.canvas||(this.canvas=document.createElement("canvas"),Object.assign(this.canvas.style,{position:"fixed",left:"0",top:"0",width:"100vw",height:"100vh",pointerEvents:"none",zIndex:String(this.cfg.zIndex)}),document.body.appendChild(this.canvas),this.ctx=this.canvas.getContext("2d"),this.resize(),window.addEventListener("resize",this.onResize),this.rafId=requestAnimationFrame(this.frame))}stop(){this.rafId&&cancelAnimationFrame(this.rafId),this.rafId=null,window.removeEventListener("resize",this.onResize),this.canvas?.remove(),this.canvas=null,this.ctx=null,this.frameContext=null}resize(){this.canvas&&(this.dpr=window.devicePixelRatio||1,this.canvas.width=Math.round(innerWidth*this.dpr),this.canvas.height=Math.round(innerHeight*this.dpr))}registerLayer(name,priority,fn){const layer={name:name,priority:priority,fn:fn};return this.layers.push(layer),this.layers.sort((a,b)=>a.priority-b.priority),()=>{this.layers=this.layers.filter(item=>item!==layer)}}onAircraftChange(listener){return this.aircraftChangeListeners.add(listener),()=>this.aircraftChangeListeners.delete(listener)}getFrame(){return this.frameContext}addImpact(position,nowMs=performance.now()){this.impacts.push({pos:position,t0:nowMs})}toggleEnabled(){return this.enabled=!this.enabled,this.combat.notify("EEGS display: "+(this.enabled?"ON":"OFF"),2e3),this.enabled}static isReady(){return!!(window.geofs&&geofs.aircraft&&geofs.aircraft.instance&&geofs.api&&geofs.api.viewer&&window.Cesium&&geofs.animation&&geofs.animation.values)}inCockpit(){if(!this.cfg.cockpitOnly)return!0;const camera=window.geofs?.camera;if(!camera)return!0;const name=String(camera.currentModeName||"").toLowerCase();return name?name.includes("cockpit"):0===camera.currentMode}cameraAxes(){const cam=geofs.api.viewer.scene.camera,inv=Cesium.Matrix4.inverseTransformation(Cesium.Transforms.eastNorthUpToFixedFrame(cam.positionWC),new Cesium.Matrix4),enu=c=>{const o=Cesium.Matrix4.multiplyByPointAsVector(inv,c,new Cesium.Cartesian3);return[o.x,o.y,o.z]};return[enu(cam.directionWC),enu(cam.rightWC),mul(enu(cam.upWC),-1)]}aircraftAxes(hs,ps,rs){const v=geofs.animation.values,h=(v.heading360||0)*DEG*hs,p=(v.atilt||0)*DEG*ps,r=(v.aroll||0)*DEG*rs,fwd=[Math.sin(h)*Math.cos(p),Math.cos(h)*Math.cos(p),Math.sin(p)],right0=[Math.cos(h),-Math.sin(h),0],up0=cross(right0,fwd),c=Math.cos(r),s=Math.sin(r),right=add(mul(right0,c),mul(up0,-s)),up=add(mul(right0,s),mul(up0,c));return[fwd,right,mul(up,-1)]}bodyAxes(){const cam=this.cameraAxes();if("camera"===this.cfg.orientationSource)return cam;const all=this.combos.map(c=>this.aircraftAxes(c[0],c[1],c[2]));if(this.inCockpit()){for(let i=0;ithis.scores[this.best]+3&&(this.best=i)}return all[this.best]}updateMotion(axes){const lla=geofs.aircraft.instance.llaLocation,now=performance.now(),dt=(now-this.lastT)/1e3;if(lla&&this.lastPos&&dt>.001&&dt<.5){const a=Math.min(1,8*dt),n=(lla[0]-this.lastPos[0])*DEG*R_EARTH/dt,e=(lla[1]-this.lastPos[1])*DEG*R_EARTH*Math.cos(lla[0]*DEG)/dt,u=(lla[2]-this.lastPos[2])/dt;if(Math.hypot(e,n,u)<1500&&(this.vel[0]+=(e-this.vel[0])*a,this.vel[1]+=(n-this.vel[1])*a,this.vel[2]+=(u-this.vel[2])*a),this.prevAxes){const prev=this.prevAxes,d=(i,j)=>dot(prev[i],axes[j]),w=[(d(2,1)-d(1,2))/(2*dt),(d(0,2)-d(2,0))/(2*dt),(d(1,0)-d(0,1))/(2*dt)];if(Math.hypot(w[0],w[1],w[2])<4){const b=Math.min(1,6*dt);for(let i=0;i<3;i++)this.omega[i]+=(w[i]-this.omega[i])*b}}}this.lastPos=lla?lla.slice():null,this.lastT=now,this.prevAxes=axes}inRotatedFrame(v,t){const omega=this.omega,m=Math.hypot(omega[0],omega[1],omega[2]),th=m*t;if(th<1e-6)return v;const k=[omega[0]/m,omega[1]/m,omega[2]/m],c=Math.cos(th),s=Math.sin(th),kxv=cross(k,v),kdv=dot(k,v);return[v[0]*c-kxv[0]*s+k[0]*kdv*(1-c),v[1]*c-kxv[1]*s+k[1]*kdv*(1-c),v[2]*c-kxv[2]*s+k[2]*kdv*(1-c)]}toScreen(enuMat,scene,p,raw){const world=CombatMath.worldPosition(enuMat,p);return this.worldToScreen(scene,world,raw)}worldToScreen(scene,world,raw){const s=CombatMath.projectWorld(scene,world);if(!s)return null;const rect=scene.canvas.getBoundingClientRect(),k=rect.width/scene.canvas.clientWidth||1,ox=raw?0:this.cfg.hudOffset.x,oy=raw?0:this.cfg.hudOffset.y;return{x:rect.left+s.x*k+ox,y:rect.top+s.y*k+oy}}renderFrame(){this.rafId=requestAnimationFrame(this.frame);const ctx=this.ctx;if(!ctx)return;if(ctx.setTransform(this.dpr,0,0,this.dpr,0,0),ctx.clearRect(0,0,innerWidth,innerHeight),!WeaponOverlayModule.isReady())return;const scene=geofs.api.viewer.scene,axes=this.bodyAxes();this.updateMotion(axes);const nowMs=performance.now(),dt=Math.min(.1,Math.max(0,(nowMs-this.lastFrameTime)/1e3));if(this.lastFrameTime=nowMs,geofs.aircraft.instance!==this.lastInstance){this.lastInstance=geofs.aircraft.instance;for(const listener of this.aircraftChangeListeners)try{listener()}catch(error){console.error("[Overlay] aircraft change listener failed",error)}}const camPos=scene.camera.positionWC,fovy=scene.camera.frustum&&scene.camera.frustum.fovy||1,pxPerRad=scene.canvas.clientHeight/2/Math.tan(fovy/2),ang=d=>pxPerRad*Math.tan(d*DEG),frame={ctx:ctx,scene:scene,nowMs:nowMs,dt:dt,axes:axes,vel:this.vel,omega:this.omega,enuMat:Cesium.Transforms.eastNorthUpToFixedFrame(camPos),pxPerRad:pxPerRad,ang:ang,lw:Math.max(1,ang(this.cfg.lineDeg)),maskY:innerHeight*this.cfg.maskBottom,active:this.enabled&&this.inCockpit(),dpr:this.dpr,overlay:this};this.frameContext=frame;for(const layer of this.layers){ctx.save();try{layer.fn(ctx,frame)}catch(error){console.error(`[Overlay] layer "${layer.name}" failed`,error)}ctx.restore()}}}window.WeaponOverlayModule=WeaponOverlayModule}(),function(){"use strict";const{DEG:DEG,NM:NM,normalizeHeading:normalizeHeading,angleDifference:angleDifference,bearingAndDistance:bearingAndDistance}=CombatMath;window.TargetModule=class TargetModule{constructor(combat,addon=null){this.combat=combat,this.addon=addon,combat.targets=this,this.targetMode=!1,this.selectedTargetId=null,this.lockedTargetId=null,this.currentTargets=[],this.providers=new Set,this.lastRefreshAt=0,this.unregisterLayer=null}start(){const overlay=this.combat.overlay;overlay&&(this.unregisterLayer=overlay.registerLayer("targets",4,(ctx,frame)=>this.update(frame)),overlay.onAircraftChange(()=>this.reset()))}stop(){this.unregisterLayer?.(),this.unregisterLayer=null,this.reset()}reset(){this.targetMode=!1,this.selectedTargetId=null,this.lockedTargetId=null,this.currentTargets=[]}registerProvider(provider){return this.providers.add(provider),()=>this.providers.delete(provider)}isTrackingNeeded(){return this.targetMode||!!this.combat.aaCombat?.active||!!this.combat.projectile?.hasTrackedMissiles?.()}update(frame){this.isTrackingNeeded()?this.refresh(!0):this.currentTargets=[],this.selectedTargetId&&!this.currentTargets.some(t=>t.id===this.selectedTargetId)&&(this.selectedTargetId=null),this.lockedTargetId&&!this.currentTargets.some(t=>t.id===this.lockedTargetId)&&(this.lockedTargetId=null,this.combat.notify("RADAR: TARGET LOST",1500)),this.targetMode&&!this.selectedTargetId&&this.currentTargets.length&&(this.selectedTargetId=this.currentTargets[0].id)}refresh(force=!1){const now=performance.now();return!force&&now-this.lastRefreshAt<100||(this.lastRefreshAt=now,this.currentTargets=this.computeTargets()),this.currentTargets}computeTargets(){if(!window.geofs?.aircraft?.instance)return[];const own=geofs.aircraft.instance.llaLocation;if(!own)return[];const ownHeading=Number(geofs.animation?.values?.heading360||geofs.animation?.values?.heading)||0,rangeLimit=70*NM,targets=[],consider=contact=>{const{bearing:bearing,distance:distance}=bearingAndDistance(own,contact.lat,contact.lon,contact.alt);!Number.isFinite(distance)||distance<50||distance>rangeLimit||targets.push({...contact,bearing:bearing,rangeNm:distance/NM,relativeBearing:angleDifference(ownHeading,bearing)})};for(const user of Object.values(window.multiplayer?.visibleUsers??{})){const co=user&&user.lastUpdate&&user.lastUpdate.co;if(!Array.isArray(co)||co.length<3)continue;const lat=Number(co[0]),lon=Number(co[1]),alt=Number(co[2]);if(!Number.isFinite(lat)||!Number.isFinite(lon)||!Number.isFinite(alt))continue;const id=String(user.id??user.uid??user.callsign??user.cs??"");id&&consider({id:id,callsign:String(user.callsign??user.cs??user.aircraftName??"CONTACT"),lat:lat,lon:lon,alt:alt})}for(const provider of this.providers){let contacts=[];try{contacts=provider()||[]}catch(error){console.error("[Targets] provider failed",error)}for(const contact of contacts)consider(contact)}return targets.sort((a,b)=>a.rangeNm-b.rangeNm),targets}toggleTargetMode(){this.targetMode=!this.targetMode,this.targetMode?(this.refresh(!0),!this.selectedTargetId&&this.currentTargets.length&&(this.selectedTargetId=this.currentTargets[0].id)):(this.selectedTargetId=null,this.lockedTargetId=null),this.combat.notify("TARGET MODE: "+(this.targetMode?"ON":"OFF"),1500)}selectTarget(step){this.refresh(!0);const targets=this.currentTargets;if(!targets.length)return this.selectedTargetId=null,this.lockedTargetId=null,void this.combat.notify("RADAR: NO CONTACTS",1500);const index=targets.findIndex(t=>t.id===this.selectedTargetId),next=index<0?step>0?0:targets.length-1:(index+step+targets.length)%targets.length;this.selectedTargetId=targets[next].id,this.lockedTargetId=null,this.combat.notify(`TARGET: ${targets[next].callsign}`,1500)}toggleLock(){this.refresh(!0);const target=this.currentTargets.find(t=>t.id===this.selectedTargetId);if(!target)return this.lockedTargetId=null,void this.combat.notify("RADAR: SELECT A TARGET FIRST",1500);this.lockedTargetId===target.id?(this.lockedTargetId=null,this.combat.notify("RADAR: LOCK RELEASED",1500)):(this.lockedTargetId=target.id,this.combat.notify(`RADAR: LOCKED ${target.callsign}`,1500))}getSelectedTarget(){return this.currentTargets.find(t=>t.id===this.selectedTargetId)??null}getLockedTarget(){if(this.refresh(!0),this.lockedTargetId){const locked=this.currentTargets.find(t=>t.id===this.lockedTargetId);if(locked)return locked}const radarUid=this.addon?.radar?.hardLockedUid??window.BasePlugin?.getActiveAddon?.()?.radar?.hardLockedUid;return radarUid?this.currentTargets.find(t=>t.id===String(radarUid))??null:null}hasLock(){return!!this.getLockedTarget()}findTarget(id){return this.currentTargets.find(t=>t.id===id)??null}}}(),function(){"use strict";window.WeaponAudioModule=class WeaponAudioModule{constructor(combat,weaponModule,config={}){this.combat=combat,this.weapons=weaponModule,combat.audio=this,this.cfg={sound:!0,gunVolume:.7,...config},this.actx=null,this.gunBuf=null,this.gunFilter=null,this.gunGain=null,this.gunSrc=null,this.soundOn=!1,this.unsubscribers=[]}start(){this.weapons?.on&&this.unsubscribers.push(this.weapons.on("fire",event=>{event.weapon&&"GUN"!==event.weapon&&this.missileSound()}),this.weapons.on("dryfire",()=>this.dryClick()),this.weapons.on("gunstate",({firing:firing})=>this.gunSound(!!firing)))}stop(){this.gunSound(!1);for(const unsubscribe of this.unsubscribers)unsubscribe();this.unsubscribers=[]}initAudio(){if(this.actx||!this.cfg.sound)return;const AudioCtor=window.AudioContext||window.webkitAudioContext;if(!AudioCtor)return;const actx=new AudioCtor;this.actx=actx;const sr=actx.sampleRate,rate=this.weapons?.GUN_FIRE_RATE_RPS??100,period=Math.round(sr/rate),len=60*period;this.gunBuf=actx.createBuffer(1,len,sr);const d=this.gunBuf.getChannelData(0);for(let r=0;r<60;r++){const amp=.8+.2*Math.random(),start=r*period;for(let n=0;n<2*period;n++){const t=n/sr,crack=(2*Math.random()-1)*Math.exp(-t/.0012),thump=Math.sin(2*Math.PI*70*t)*Math.exp(-t/.0055);d[(start+n)%len]+=amp*(.55*crack+.9*thump)}}let peak=0;for(let i=0;ithis.handleKeyDown(event),this.onKeyUp=event=>this.handleKeyUp(event),this.onBlur=()=>this.weaponModule?.releaseTrigger?.()}start(){this.running||(window.addEventListener("keydown",this.onKeyDown,!0),window.addEventListener("keyup",this.onKeyUp,!0),window.addEventListener("blur",this.onBlur),this.running=!0,this.installOptionsControls(),this.optionsTimer=setInterval(()=>this.installOptionsControls(),1e3))}stop(){this.running&&(window.removeEventListener("keydown",this.onKeyDown,!0),window.removeEventListener("keyup",this.onKeyUp,!0),window.removeEventListener("blur",this.onBlur),this.weaponModule?.releaseTrigger?.(),this.running=!1,clearInterval(this.optionsTimer),this.optionsTimer=null,document.querySelector(".geofs-addon-keybinds")?.remove())}installOptionsControls(){const mounted=CombatMath.ensureGeneralFieldset("geofs-addon-keybinds","Weapon Keybinds");if(mounted&&!mounted.controls.dataset.built){mounted.controls.dataset.built="1";for(const[action,label]of Object.entries(LABELS)){const input=document.createElement("input");input.type="text",input.value=this.bindings[action],input.title="Keyboard event.code, optionally prefixed with Shift+",input.addEventListener("change",()=>{this.bindings[action]=input.value.trim()||DEFAULT_BINDINGS[action],input.value=this.bindings[action],OptionModule.setOption("KEY",OPTION_KEYS[action],this.bindings[action])});const row=document.createElement("label");row.style.display="block",row.textContent=`${label}: `,row.appendChild(input),mounted.controls.appendChild(row)}}}static isTyping(event){const target=event.target;return!(!target||!target.isContentEditable&&!/^(INPUT|TEXTAREA|SELECT)$/.test(target.tagName||""))}findAction(event){let fallback=null;for(const[action,binding]of Object.entries(this.bindings)){const requiresShift=/^shift\+/i.test(binding);if(binding.replace(/^shift\+/i,"")===event.code){if(requiresShift===event.shiftKey)return action;requiresShift||(fallback=fallback??action)}}return fallback}handleKeyDown(event){if(KeybindModule.isTyping(event)||event.ctrlKey||event.altKey||event.metaKey)return;const action=this.findAction(event);if(!action)return;const targets=this.combat.targets;("selectNext"===action||"selectPrevious"===action||"lock"===action)&&!targets?.targetMode||("fire"!==action?(event.preventDefault(),event.repeat||this.invoke(action)):event.repeat||this.weaponModule?.pressTrigger?.())}handleKeyUp(event){const binding=this.bindings.fire.replace(/^shift\+/i,"");event.code===binding&&this.weaponModule?.releaseTrigger?.()}invoke(action){const combat=this.combat,weapons=this.weaponModule,mode=OptionModule.getOption("WPN","MODE","A/A");switch(action){case"selectWeaponNext":return weapons?.selectNextWeapon?.(mode,weapons.getModeLoadout(mode),0);case"selectWeaponPrevious":return weapons?.selectPreviousWeapon?.(mode,weapons.getModeLoadout(mode),0);case"targetMode":return combat.targets?.toggleTargetMode();case"selectNext":return combat.targets?.selectTarget(1);case"selectPrevious":return combat.targets?.selectTarget(-1);case"lock":return combat.targets?.toggleLock();case"countermeasures":return combat.projectile?.releaseCountermeasures();case"display":return combat.overlay?.toggleEnabled();case"reload":return"OFF"!==OptionModule.getOption("WPN","MASTER","OFF")?void combat.notify("SET MASTER OFF TO REARM",2e3):weapons?.startRearm?.(OptionModule.getOption("WPN","CONFIG","A/A"));default:return}}}window.KeybindModule=KeybindModule}(),function(){"use strict";const{dot:dot,add:add,mul:mul,DEG:DEG}=CombatMath;window.WeaponHudModule=class WeaponHudModule{constructor(combat,weaponModule,config={}){this.combat=combat,this.weapons=weaponModule,combat.weaponHud=this,this.cfg={hudFov:{w:18,h:20},crossDeg:.7,step:.03,maxTime:4,minRange:150,maxRange:2400,wingspan:10.7,tickRanges:[500,1e3,1500,2e3],tickTextDeg:.8,counterTextDeg:1.1,lockedColor:"#ff5959",showAmmoCounter:!1,showHudFrame:!1,...config},this.unregisterLayer=null}start(){this.unregisterLayer=this.combat.overlay?.registerLayer("weapon-hud",60,(ctx,frame)=>this.draw(ctx,frame))??null}stop(){this.unregisterLayer?.(),this.unregisterLayer=null}polyline(ctx,pts){if(!(pts.length<2)){ctx.beginPath(),ctx.moveTo(pts[0].x,pts[0].y);for(let i=1;i0?color:"#ff0000",ctx.fillText(ammo>0?`${label} ${String(ammo).padStart(3,"0")}`:`${label} NO AMMO`,boresight.x-halfW+ang(.5),bottom-ang(.6)))}}drawFunnel(ctx,f,boresight){const{scene:scene,axes:axes,vel:vel,enuMat:enuMat,pxPerRad:pxPerRad,ang:ang,overlay:overlay}=f,cfg=this.cfg,gun=WeaponModule.gunMetadata,v0=add(vel,mul(axes[0],gun.muzzleVelocity)),pts=[];for(let t=cfg.step;t<=cfg.maxTime;t+=cfg.step){const k=(1-Math.exp(-gun.drag*t))/gun.drag,bullet=add(mul(v0,k),[0,0,-.5*gun.gravity*t*t]),rel=[bullet[0]-vel[0]*t,bullet[1]-vel[1]*t,bullet[2]-vel[2]*t],b0=[dot(axes[0],rel),dot(axes[1],rel),dot(axes[2],rel)],b=overlay.inRotatedFrame(b0,t),range=Math.hypot(b[0],b[1],b[2]);if(rangecfg.maxRange)break;const dir=add(add(mul(axes[0],b[0]/range),mul(axes[1],b[1]/range)),mul(axes[2],b[2]/range)),screen=overlay.toScreen(enuMat,scene,mul(dir,1e3));screen&&pts.push({x:screen.x,y:screen.y,r:range})}if(pts.length<3)return;const left=[],right=[];for(let i=0;ip.r>=range);i<0||(ctx.beginPath(),ctx.moveTo(left[i].x,left[i].y),ctx.lineTo(right[i].x,right[i].y),ctx.stroke(),ctx.fillText((range/1e3).toFixed(1),right[i].x+ang(.4),right[i].y+ang(.3)))}}drawTarget(ctx,f,target,bounds){if(!target)return;const world=Cesium.Cartesian3.fromDegrees(target.lon,target.lat,target.alt),point=f.overlay.worldToScreen(f.scene,world);if(!point)return;const{x:x,y:y}=point;if(xbounds.right||ybounds.bottom)return;const color=this.combat.targets.getLockedTarget()?.id===target.id?this.cfg.lockedColor:f.overlay.cfg.color;ctx.save(),ctx.strokeStyle=color,ctx.fillStyle=color,ctx.lineWidth=2,ctx.shadowColor=color,ctx.shadowBlur=5,ctx.strokeRect(x-11,y-11,22,22),ctx.font="11px monospace",ctx.textAlign="left",ctx.textBaseline="bottom",ctx.fillText(target.callsign.slice(0,14),x+11+4,y-2),ctx.textBaseline="top",ctx.fillText(`${target.rangeNm.toFixed(1)} NM`,x+11+4,y+2),ctx.restore()}}}(),function(){"use strict";const{add:add,mul:mul,NM:NM,turnVelocity:turnVelocity,worldPosition:worldPosition}=CombatMath;window.ProjectileModule=class ProjectileModule{constructor(combat,weaponModule,config={}){this.combat=combat,this.weapons=weaponModule,combat.projectile=this,this.cfg={tracers:!0,...config},this.missiles=[],this.tracers=[],this.countermeasures=[],this.tracerAcc=0,this.countermeasureSequence=0,this.networkMissileSequence=0,this.unsubscribers=[]}start(){this.unsubscribers.push(this.weapons.on("fire",event=>this.onFire(event)));const overlay=this.combat.overlay;overlay&&this.unsubscribers.push(overlay.registerLayer("countermeasures",10,(ctx,frame)=>this.drawCountermeasures(ctx,frame)),overlay.registerLayer("projectiles",50,(ctx,frame)=>this.updateAndDraw(ctx,frame)),overlay.onAircraftChange(()=>this.reset()))}stop(){for(const unsubscribe of this.unsubscribers)unsubscribe();this.unsubscribers=[],this.reset()}reset(){this.missiles=[],this.tracers=[],this.countermeasures=[],this.tracerAcc=0}hasTrackedMissiles(){return this.missiles.some(missile=>missile.targetId)}getCountermeasures(){return this.countermeasures}onFire(event){const frame=this.combat.overlay?.getFrame();frame&&window.geofs?.aircraft?.instance&&("GUN"===event.weapon?this.fireGunRound(frame,event.metadata?.projectile??WeaponModule.gunMetadata):event.weapon&&this.launchMissile(frame,event))}aircraftOrigin(){const lla=geofs.aircraft.instance.llaLocation;return lla?Cesium.Transforms.eastNorthUpToFixedFrame(Cesium.Cartesian3.fromDegrees(lla[1],lla[0],lla[2])):null}fireGunRound(frame,gun){if(this.tracerAcc+=1,this.cfg.tracers)for(;this.tracerAcc>=gun.tracerEvery;){this.tracerAcc-=gun.tracerEvery;const origin=this.aircraftOrigin();if(!origin)return;this.tracers.push({enuMat:origin,t0:performance.now(),v0:add(frame.vel,mul(frame.axes[0],gun.muzzleVelocity)),gun:gun})}}computeHitChance(metadata,distanceNm){const engagement=metadata?.engagement_window,effective=metadata?.effective_range;if(!engagement||!effective)return 1;if(distanceNmengagement.max)return.1;if(distanceNm>=effective.min&&distanceNm<=effective.max)return.95;const edge=distanceNm{sent&&this.combat.notify("MISSILE EVENT SENT IN PUBLIC CHAT",2500)})):status="MP GROUP MISSING":status="MP SYNC OFF"}this.combat.notify(`${event.weapon} LAUNCHED: ${target.callsign}${status?" | "+status:""}`,1500)}sendTerminal(missile,kind){missile.networkId&&(("H"===kind?missile.networkHitSent:missile.networkTerminalSent)||("H"===kind&&(missile.networkHitSent=!0),missile.networkTerminalSent=!0,this.combat.multiplayer?.sendEvent([1,kind,missile.networkId,missile.targetId,Date.now()])))}releaseCountermeasures(){if(!WeaponOverlayModule.isReady())return;const lla=geofs.aircraft.instance.llaLocation;if(!lla)return;const now=performance.now(),axes=this.combat.overlay?.getFrame()?.axes??this.combat.overlay.bodyAxes(),origin=Cesium.Transforms.eastNorthUpToFixedFrame(Cesium.Cartesian3.fromDegrees(lla[1],lla[0],lla[2])),invOrigin=Cesium.Matrix4.inverseTransformation(origin,new Cesium.Matrix4),sequence=++this.countermeasureSequence;for(let i=0;i<18;i++){const lateral=8*(Math.random()-.5);this.countermeasures.push({type:"chaff",t0:now,life:2.2,sequence:sequence,origin:origin,invOrigin:invOrigin,offset:add(mul(axes[0],-7),mul(axes[1],lateral)),velocity:add(mul(axes[0],-12-8*Math.random()),mul(axes[1],12*(Math.random()-.5))),size:1+1.5*Math.random()})}for(let i=0;i<3;i++)this.countermeasures.push({type:"flare",t0:now,life:1.8,sequence:sequence,origin:origin,invOrigin:invOrigin,offset:add(mul(axes[0],-7),mul(axes[1],5*(Math.random()-.5))),velocity:add(mul(axes[0],-18-8*Math.random()),[0,0,-3-4*Math.random()]),size:3+2*Math.random()});this.combat.audio?.countermeasureSound();const evade=this.combat.multiplayer?.evadeIncomingMissiles();evade&&evade.count?(this.combat.notify("FLARES RELEASED - REPORTING MISSILE EVADE",2e3),evade.promise.then(sentCount=>{this.combat.notify(sentCount===evade.count?"FLARES RELEASED - MISSILE EVADE SENT":"FLARES RELEASED - EVADE MESSAGE NOT SENT",2e3)})):this.combat.notify("CHAFF / FLARE RELEASED",1500)}decoyWorldPosition(p,nowMs){const age=Math.max(0,(nowMs-p.t0)/1e3),local=add(p.offset,add(mul(p.velocity,age),[0,0,-4.905*age*age]));return Cesium.Matrix4.multiplyByPoint(p.origin,new Cesium.Cartesian3(local[0],local[1],local[2]),new Cesium.Cartesian3)}countermeasureWorld(p,nowMs,aircraftWorld){const age=(nowMs-p.t0)/1e3,aircraftPosition=Cesium.Matrix4.multiplyByPoint(p.invOrigin,aircraftWorld,new Cesium.Cartesian3),offset=add(aircraftPosition,add(p.offset,add(mul(p.velocity,age),[0,0,-4.905*age*age])));return Cesium.Matrix4.multiplyByPoint(p.origin,new Cesium.Cartesian3(offset[0],offset[1],offset[2]),new Cesium.Cartesian3)}drawCountermeasures(ctx,frame){const now=frame.nowMs;if(this.countermeasures=this.countermeasures.filter(p=>now-p.t0<1e3*p.life),!this.countermeasures.length)return;const lla=geofs.aircraft.instance.llaLocation;if(!lla)return;const aircraftWorld=Cesium.Cartesian3.fromDegrees(lla[1],lla[0],lla[2]);for(const p of this.countermeasures){const age=(now-p.t0)/1e3,screen=frame.overlay.worldToScreen(frame.scene,this.countermeasureWorld(p,now,aircraftWorld),!0);screen&&(ctx.globalAlpha=1-age/p.life,"flare"===p.type?(ctx.fillStyle="#ffd26a",ctx.shadowColor="#ff5a18",ctx.shadowBlur=22,ctx.beginPath(),ctx.arc(screen.x,screen.y,p.size*(1-age/p.life*.35)+3,0,2*Math.PI),ctx.fill()):(ctx.fillStyle="#e7edf2",ctx.shadowColor="#d8e4ef",ctx.shadowBlur=8,ctx.fillRect(screen.x,screen.y,p.size+2,p.size+1)))}}isBelowTerrain(scene,world){if(!scene.globe||!scene.globe.getHeight)return!1;const cartographic=Cesium.Cartographic.fromCartesian(world);if(!cartographic)return!1;const height=scene.globe.getHeight(cartographic);return void 0!==height&&cartographic.height<=height}updateAndDraw(ctx,f){const aaCombat=this.combat.aaCombat,targets=this.combat.targets,impacts=f.overlay.impacts;f.active||(this.tracers=[]),ctx.save(),ctx.beginPath(),ctx.rect(0,0,innerWidth,f.maskY),ctx.clip(),this.updateMissiles(ctx,f,aaCombat,targets,impacts),this.updateTracers(ctx,f,aaCombat,impacts),this.drawImpacts(ctx,f,impacts),ctx.restore()}updateMissiles(ctx,f,aaCombat,targets,impacts){const{scene:scene,nowMs:nowMs}=f,ballistic=(missile,t)=>{const k=(1-Math.exp(-.03*t))/.03;return add(missile.start,add(mul(missile.v0,k),[0,0,-.75*t*t]))},live=[];for(const missile of this.missiles){const t=(nowMs-missile.t0)/1e3;if(t>missile.maxFlightTime){this.sendTerminal(missile,"X");continue}const target=missile.targetId&&targets?.findTarget(missile.targetId);let position;if(target){if(target.isNpc&&missile.npcDecoy&&nowMs-missile.npcDecoy.t0>=missile.npcDecoy.life){impacts.push({pos:aaCombat.flareWorldPosition(missile.npcDecoy,nowMs),t0:nowMs}),this.combat.notify("PLAYER MISSILE SPOOFED BY BANDIT FLARE",2e3);continue}if(target.isNpc&&!missile.npcDecoy&&aaCombat){const newFlares=aaCombat.getNpcFlares().filter(flare=>flare.ownerId===target.id&&flare.sequence>(missile.npcCountermeasureSequence??0)&&nowMs-flare.t0flare.sequence)),Math.random()0){missile.velocity=turnVelocity(missile.velocity,delta,missile.turnRate*dt);const velocityLength=Math.hypot(...missile.velocity)||1;missile.velocity=mul(missile.velocity,missile.speed/velocityLength),missile.position=add(missile.position,mul(missile.velocity,dt)),missile.updatedAt=nowMs}position=missile.position}else position=ballistic(missile,t);const world=worldPosition(missile.enuMat,position);if(this.isBelowTerrain(scene,world)){this.sendTerminal(missile,"X"),impacts.push({pos:world,t0:nowMs});continue}live.push(missile);const lastPoint=missile.trail[missile.trail.length-1];(!lastPoint||Math.hypot(position[0]-lastPoint.position[0],position[1]-lastPoint.position[1],position[2]-lastPoint.position[2])>=5||nowMs-lastPoint.t0>=75)&&missile.trail.push({position:position.slice(),t0:nowMs}),missile.trail=missile.trail.filter(point=>nowMs-point.t0<1400),f.active&&this.drawMissile(ctx,f,missile,position)}this.missiles=live}drawMissile(ctx,f,missile,position){const{scene:scene,nowMs:nowMs,overlay:overlay}=f;ctx.save(),ctx.strokeStyle="#ffffff",ctx.shadowColor="#ffffff";for(let i=1;i1?overlay.toScreen(missile.enuMat,scene,missile.trail[missile.trail.length-2].position,!0):null;if(current){if(previous){const angle=Math.atan2(current.y-previous.y,current.x-previous.x);ctx.globalAlpha=.85,ctx.strokeStyle="#ffb06a",ctx.shadowColor="#ff7a24",ctx.shadowBlur=9,ctx.lineWidth=2,ctx.beginPath(),ctx.moveTo(current.x-2*Math.cos(angle),current.y-2*Math.sin(angle)),ctx.lineTo(current.x-10*Math.cos(angle),current.y-10*Math.sin(angle)),ctx.stroke()}ctx.globalAlpha=.9,ctx.fillStyle="#ffffff",ctx.shadowColor="#ffffff",ctx.shadowBlur=5,ctx.beginPath(),ctx.arc(current.x,current.y,1.7,0,2*Math.PI),ctx.fill()}ctx.restore()}updateTracers(ctx,f,aaCombat,impacts){if(!this.cfg.tracers)return void(this.tracers=[]);const{scene:scene,nowMs:nowMs,overlay:overlay}=f,alive=[];ctx.save();for(const tracer of this.tracers){const gun=tracer.gun,offs=t=>{const k=(1-Math.exp(-gun.drag*t))/gun.drag;return[tracer.v0[0]*k,tracer.v0[1]*k,tracer.v0[2]*k-.5*gun.gravity*t*t]},t=(nowMs-tracer.t0)/1e3;if(t>3)continue;const pa=offs(t),world=worldPosition(tracer.enuMat,pa);if(this.isBelowTerrain(scene,world)){impacts.push({pos:world,t0:nowMs});continue}if(aaCombat?.damageNpcAtWorldPosition(world,1,"GUN"))continue;if(alive.push(tracer),!f.active||Math.hypot(pa[0],pa[1],pa[2])=0;i--)nowMs-impacts[i].t0>=500&&impacts.splice(i,1);if(f.active){ctx.save(),ctx.shadowBlur=0,ctx.fillStyle=WeaponModule.gunMetadata.impactColor;for(const impact of impacts){const s=overlay.worldToScreen(scene,impact.pos,!0);if(!s)continue;const k=1-(nowMs-impact.t0)/500;ctx.globalAlpha=k,ctx.beginPath(),ctx.arc(s.x,s.y,2+6*k,0,2*Math.PI),ctx.fill()}ctx.restore()}}}}(),function(){"use strict";const{add:add,mul:mul,DEG:DEG,R_EARTH:R_EARTH,NM:NM,normalizeHeading:normalizeHeading,angleDifference:angleDifference,moveGeoPoint:moveGeoPoint,turnVelocity:turnVelocity,worldPosition:worldPosition}=CombatMath,DIFFICULTY_NAMES=["Easy","Basic","Standard","Advanced","Expert","Hard"],DIFFICULTY_SETTINGS=[{speed:160,turnRate:12,attackRangeNm:8,attackDelay:14e3,missileSpeed:700,missileTurnRate:1.1,flareChance:.25},{speed:185,turnRate:16,attackRangeNm:10,attackDelay:13e3,missileSpeed:750,missileTurnRate:1.25,flareChance:.35},{speed:210,turnRate:20,attackRangeNm:12,attackDelay:12e3,missileSpeed:800,missileTurnRate:1.4,flareChance:.45},{speed:235,turnRate:24,attackRangeNm:14,attackDelay:11e3,missileSpeed:850,missileTurnRate:1.55,flareChance:.58},{speed:265,turnRate:30,attackRangeNm:16,attackDelay:1e4,missileSpeed:950,missileTurnRate:1.75,flareChance:.72},{speed:300,turnRate:36,attackRangeNm:20,attackDelay:9e3,missileSpeed:1050,missileTurnRate:2,flareChance:.84}];window.AACombatModule=class AACombatModule{constructor(combat,config={}){this.combat=combat,combat.aaCombat=this,this.cfg={...config},this.active=!1,this.npcs=[],this.kills=0,this.hits=0,this.hitsTaken=0,this.npcMissiles=[],this.npcFlares=[],this.flareSequence=0,this.npcSequence=0,this.selectedDifficulty=3,this.selectedBanditCount=1,this.showBanditHudPoi=!1!==CombatMath.readStorage("geofs-addon-combat-aa-poi",!0),this.lastUiUpdate=0,this.statusElement=null,this.startButton=null,this.stopButton=null,this.unsubscribers=[]}start(){const overlay=this.combat.overlay;overlay&&(this.unsubscribers.push(this.combat.targets?.registerProvider(()=>this.getNpcContacts())??(()=>{}),overlay.registerLayer("aa-sim",3,(ctx,f)=>this.updateSimulation(f)),overlay.registerLayer("aa-npc-flares",20,(ctx,f)=>this.drawNpcFlares(ctx,f)),overlay.registerLayer("aa-npc-missiles",30,(ctx,f)=>this.updateAndDrawNpcMissiles(ctx,f)),overlay.registerLayer("aa-hud-poi",70,(ctx,f)=>this.drawHudTargets(ctx,f)),overlay.registerLayer("aa-mini-radar",80,(ctx,f)=>this.drawMiniRadar(ctx,f)),overlay.onAircraftChange(()=>{this.active&&this.stopSimulation("A/A SIM STOPPED")})),this.mountOptions())}stop(){this.active&&this.stopSimulation();for(const unsubscribe of this.unsubscribers)unsubscribe();this.unsubscribers=[]}getDifficulty(level){const index=Math.max(1,Math.min(DIFFICULTY_SETTINGS.length,Number(level)||1))-1;return DIFFICULTY_SETTINGS[index]}getNpcFlares(){return this.npcFlares}getNpcContacts(){return this.active?this.npcs.map(npc=>({id:npc.id,callsign:npc.callsign,lat:npc.lat,lon:npc.lon,alt:npc.alt,isNpc:!0,health:npc.health,difficulty:npc.difficulty})):[]}startSimulation(){if(!WeaponOverlayModule.isReady())return void this.combat.notify("A/A SIM REQUIRES THE AIRCRAFT TO BE READY",2500);const own=geofs.aircraft.instance.llaLocation;if(!(Array.isArray(own)&&Number.isFinite(own[0])&&Number.isFinite(own[1])&&Number.isFinite(own[2])))return void this.combat.notify("A/A SIM: AIRCRAFT POSITION UNAVAILABLE",2500);const now=performance.now();this.removePlayerMissilesAtNpcs(new Set(this.npcs.map(npc=>npc.id))),this.npcMissiles=[],this.combat.projectile&&(this.combat.projectile.tracers=[]);const difficulty=this.selectedDifficulty,settings=this.getDifficulty(difficulty);this.active=!0,this.npcs=Array.from({length:this.selectedBanditCount},(_,index)=>{const side=index%2==0?1:-1,distanceNm=Math.sqrt(25+875*Math.random()),bearing=Math.random()*Math.PI*2,distanceMeters=distanceNm*NM,position=moveGeoPoint(own[0],own[1],Math.cos(bearing)*distanceMeters,Math.sin(bearing)*distanceMeters);return{id:"addon-bandit-"+ ++this.npcSequence,callsign:`BANDIT ${index+1}`,lat:position.lat,lon:position.lon,alt:Math.max(0,Number(own[2])+150+index%3*80),heading:360*Math.random(),lastUpdate:now,elapsed:0,health:3,side:side,difficulty:difficulty,nextAttackAt:now+.5*settings.attackDelay+1700*index,nextFlareAt:now+3e3+900*index}}),this.npcFlares=[];const targets=this.combat.targets;targets&&(targets.targetMode=!0,targets.selectedTargetId=this.npcs[0]?.id??null,targets.lockedTargetId=null,targets.refresh(!0)),this.combat.notify(`A/A SIM STARTED - ${this.selectedBanditCount} BANDIT(S), DIFFICULTY ${difficulty}/6`,2500),this.updateOptions()}stopSimulation(message="A/A SIM STOPPED"){const npcIds=new Set(this.npcs.map(npc=>npc.id));this.active=!1,this.npcs=[],this.removePlayerMissilesAtNpcs(npcIds),this.npcMissiles=[],this.npcFlares=[],this.combat.projectile&&(this.combat.projectile.tracers=[]);const targets=this.combat.targets;targets&&(npcIds.has(targets.selectedTargetId)&&(targets.selectedTargetId=null),npcIds.has(targets.lockedTargetId)&&(targets.lockedTargetId=null),targets.refresh(!0)),this.combat.notify(message,2e3),this.updateOptions()}removePlayerMissilesAtNpcs(npcIds){const projectile=this.combat.projectile;projectile&&(projectile.missiles=projectile.missiles.filter(m=>!npcIds.has(m.targetId)))}updateSimulation(f){if(f.nowMs-this.lastUiUpdate>1e3&&(this.lastUiUpdate=f.nowMs,this.mountOptions(),this.updateOptions()),!this.active||!this.npcs.length)return;const own=geofs.aircraft.instance.llaLocation;if(Array.isArray(own)&&Number.isFinite(own[0])&&Number.isFinite(own[1]))for(const npc of this.npcs)this.updateNpc(npc,own,f.nowMs,f.dt)}updateNpc(npc,own,now,dt){const settings=this.getDifficulty(npc.difficulty),dLon=(own[1]-npc.lon)*DEG,lat1=npc.lat*DEG,lat2=own[0]*DEG,y=Math.sin(dLon)*Math.cos(lat2),x=Math.cos(lat1)*Math.sin(lat2)-Math.sin(lat1)*Math.cos(lat2)*Math.cos(dLon),bearingToPlayer=normalizeHeading(Math.atan2(y,x)/DEG);npc.elapsed+=dt;const maneuver=Math.sin(.32*npc.elapsed)*(12+2*npc.difficulty),desiredHeading=normalizeHeading(bearingToPlayer+npc.side*(8+maneuver)),maxTurn=settings.turnRate*dt;npc.heading=normalizeHeading(npc.heading+Math.max(-maxTurn,Math.min(maxTurn,angleDifference(npc.heading,desiredHeading))));const headingRad=npc.heading*DEG,travel=settings.speed*dt,position=moveGeoPoint(npc.lat,npc.lon,Math.cos(headingRad)*travel,Math.sin(headingRad)*travel);npc.lat=position.lat,npc.lon=position.lon,npc.alt=Math.max(30,npc.alt+8*Math.sin(.7*npc.elapsed)*dt),npc.lastUpdate=now;const ownWorld=Cesium.Cartesian3.fromDegrees(own[1],own[0],own[2]),npcWorld=Cesium.Cartesian3.fromDegrees(npc.lon,npc.lat,npc.alt),range=Cesium.Cartesian3.distance(ownWorld,npcWorld);(this.combat.projectile?.missiles??[]).some(missile=>{if(missile.targetId!==npc.id)return!1;const missileWorld=worldPosition(missile.enuMat,missile.position);return Cesium.Cartesian3.distance(missileWorld,npcWorld)<=1800})&&now>=npc.nextFlareAt&&(this.releaseNpcFlares(npc,now),npc.nextFlareAt=now+Math.max(3500,11e3-1e3*npc.difficulty)+2500*Math.random(),this.combat.notify(`${npc.callsign} FLARES - MISSILE SEEKER MAY BE DECOYED`,2200));const alreadyLaunched=this.npcMissiles.some(missile=>missile.sourceId===npc.id);if(now>=npc.nextAttackAt&&range<=settings.attackRangeNm*NM&&!alreadyLaunched){const direction=Cesium.Cartesian3.subtract(ownWorld,npcWorld,new Cesium.Cartesian3);Cesium.Cartesian3.normalize(direction,direction);const velocity=Cesium.Cartesian3.multiplyByScalar(direction,settings.missileSpeed,new Cesium.Cartesian3);this.npcMissiles.push({sourceId:npc.id,callsign:npc.callsign,position:npcWorld,lastTargetWorld:Cesium.Cartesian3.clone(ownWorld),velocity:velocity,t0:now,updatedAt:now,maxFlightTime:60,speed:settings.missileSpeed,turnRate:settings.missileTurnRate,trail:[],countermeasureSequence:this.combat.projectile?.countermeasureSequence??0}),npc.nextAttackAt=now+settings.attackDelay+Math.random()*settings.attackDelay*.35,this.combat.notify(`${npc.callsign} MISSILE LAUNCH - BREAK / BACKSPACE`,2500)}}releaseNpcFlares(npc,now){const origin=Cesium.Transforms.eastNorthUpToFixedFrame(Cesium.Cartesian3.fromDegrees(npc.lon,npc.lat,npc.alt)),heading=npc.heading*DEG,forward=[Math.sin(heading),Math.cos(heading),0],right=[Math.cos(heading),-Math.sin(heading),0],sequence=++this.flareSequence;for(let i=0;i<4;i++)this.npcFlares.push({type:"flare",ownerId:npc.id,sequence:sequence,t0:now,life:1800,origin:origin,offset:add(mul(forward,-8),mul(right,7*(Math.random()-.5))),velocity:add(mul(forward,-18-8*Math.random()),add(mul(right,9*(Math.random()-.5)),[0,0,3+3*Math.random()]))})}flareWorldPosition(flare,now){const age=Math.max(0,(now-flare.t0)/1e3),local=add(flare.offset,add(mul(flare.velocity,age),[0,0,-4.905*age*age]));return Cesium.Matrix4.multiplyByPoint(flare.origin,new Cesium.Cartesian3(local[0],local[1],local[2]),new Cesium.Cartesian3)}drawNpcFlares(ctx,f){if(this.npcFlares.length){this.npcFlares=this.npcFlares.filter(flare=>f.nowMs-flare.t0missile.maxFlightTime){this.combat.notify("BANDIT MISSILE EXPIRED",1500);continue}missile.decoy&&now-missile.decoy.t0>=1e3*missile.decoy.life&&(missile.decoy=null,missile.lastTargetWorld=Cesium.Cartesian3.clone(ownWorld));const newCountermeasures=(projectile?.getCountermeasures()??[]).filter(item=>item.sequence>missile.countermeasureSequence&&now-item.t0<1e3*item.life);if(newCountermeasures.length){missile.countermeasureSequence=Math.max(...newCountermeasures.map(item=>item.sequence));const flares=newCountermeasures.filter(item=>"flare"===item.type),chaff=newCountermeasures.filter(item=>"chaff"===item.type),decoy=flares[0]||chaff[0],decoyChance=flares.length?.78:.3;decoy&&Math.random()0&&dt>0){missile.velocity=turnVelocity([missile.velocity.x,missile.velocity.y,missile.velocity.z],[delta.x,delta.y,delta.z],missile.turnRate*dt);const speed=Math.hypot(...missile.velocity)||1;missile.velocity=mul(missile.velocity,missile.speed/speed),nextPosition=Cesium.Cartesian3.add(previousPosition,Cesium.Cartesian3.multiplyByScalar(new Cesium.Cartesian3(...missile.velocity),dt,new Cesium.Cartesian3),new Cesium.Cartesian3)}const previousTarget=missile.lastTargetWorld||target,relativeStart=Cesium.Cartesian3.subtract(previousPosition,previousTarget,new Cesium.Cartesian3),relativeEnd=Cesium.Cartesian3.subtract(nextPosition,target,new Cesium.Cartesian3),relativeTravel=Cesium.Cartesian3.subtract(relativeEnd,relativeStart,new Cesium.Cartesian3),travelSquared=Cesium.Cartesian3.dot(relativeTravel,relativeTravel),closestFraction=travelSquared>0?Math.max(0,Math.min(1,-Cesium.Cartesian3.dot(relativeStart,relativeTravel)/travelSquared)):0,closestPoint=Cesium.Cartesian3.add(relativeStart,Cesium.Cartesian3.multiplyByScalar(relativeTravel,closestFraction,new Cesium.Cartesian3),new Cesium.Cartesian3),hitRadius=missile.decoy?10:55;if(Cesium.Cartesian3.magnitude(closestPoint)<=hitRadius){missile.decoy?this.combat.notify(`BANDIT MISSILE DEFEATED BY ${missile.decoy.type.toUpperCase()}`,2e3):(this.hitsTaken++,this.combat.notify("SIMULATED MISSILE HIT - EVADE WITH BACKSPACE",2500),this.updateOptions());continue}missile.position=nextPosition,missile.lastTargetWorld=Cesium.Cartesian3.clone(target),missile.updatedAt=now,missile.trail.push(Cesium.Cartesian3.clone(missile.position)),missile.trail.length>12&&missile.trail.shift(),live.push(missile),ctx.save(),ctx.strokeStyle="#ff5555",ctx.fillStyle="#ff5555",ctx.shadowColor="#ff3333",ctx.shadowBlur=8,ctx.lineWidth=2;for(let i=1;inpc.id!==npcId),this.removePlayerMissilesAtNpcs(new Set([npcId])),this.npcMissiles=this.npcMissiles.filter(missile=>missile.sourceId!==npcId),this.npcFlares=this.npcFlares.filter(flare=>flare.ownerId!==npcId);const targets=this.combat.targets;targets&&(targets.selectedTargetId===npcId&&(targets.selectedTargetId=this.npcs[0]?.id??null),targets.lockedTargetId===npcId&&(targets.lockedTargetId=null)),this.npcs.length?(this.combat.notify(`${hitNpc.callsign} DESTROYED - ${this.npcs.length} LEFT`,2e3),this.updateOptions()):this.stopSimulation(`ALL BANDITS DESTROYED - KILL ${this.kills}`)}else this.combat.notify(`${hitNpc.callsign} HIT (${source}) - ${hitNpc.health} HIT(S) LEFT`,1800),this.updateOptions();return!0}drawHudTargets(ctx,f){if(!f.active||!this.active||!this.showBanditHudPoi)return;const targets=(this.combat.targets?.currentTargets??[]).filter(t=>t.isNpc);if(!targets.length)return;const{scene:scene,overlay:overlay}=f,camera=scene.camera,centerX=innerWidth/2,centerY=innerHeight/2,selectedId=this.combat.targets.selectedTargetId;ctx.font="bold 12px monospace",ctx.textBaseline="middle";for(const target of targets){const world=Cesium.Cartesian3.fromDegrees(target.lon,target.lat,target.alt),point=overlay.worldToScreen(scene,world),toTarget=Cesium.Cartesian3.subtract(world,camera.positionWC,new Cesium.Cartesian3),inFront=Cesium.Cartesian3.dot(toTarget,camera.directionWC)>0;let x,y,onScreen=!1;if(point&&inFront&&(x=point.x,y=point.y,onScreen=x>=28&&x<=innerWidth-28&&y>=28&&y<=innerHeight-28),!onScreen){let directionX,directionY;if(point&&inFront)directionX=x-centerX,directionY=y-centerY;else{const bearing=target.relativeBearing*DEG;directionX=Math.sin(bearing),directionY=-Math.cos(bearing)}const length=Math.hypot(directionX,directionY)||1;directionX/=length,directionY/=length;const edgeScale=Math.min((innerWidth/2-28)/Math.max(Math.abs(directionX),.001),(innerHeight/2-28)/Math.max(Math.abs(directionY),.001));x=centerX+directionX*edgeScale,y=centerY+directionY*edgeScale}const selected=target.id===selectedId,color=selected?"#ffffff":"#ffab55";if(ctx.save(),ctx.strokeStyle=color,ctx.fillStyle=color,ctx.shadowColor=color,ctx.shadowBlur=7,ctx.lineWidth=selected?2.5:1.5,onScreen){const size=selected?24:18;ctx.strokeRect(x-size/2,y-size/2,size,size)}else ctx.translate(x,y),ctx.rotate(Math.atan2(y-centerY,x-centerX)+Math.PI/2),ctx.beginPath(),ctx.moveTo(0,-9),ctx.lineTo(7,7),ctx.lineTo(-7,7),ctx.closePath(),ctx.fill(),ctx.setTransform(f.dpr,0,0,f.dpr,0,0);const labelX=Math.min(x+14,innerWidth-140),labelY=Math.max(33,Math.min(y,innerHeight-28-5));ctx.textAlign=labelX>innerWidth-150?"right":"left",ctx.fillText(`${target.callsign} ${target.rangeNm.toFixed(1)}NM`,"right"===ctx.textAlign?Math.max(33,x-14):labelX,labelY),ctx.restore()}}drawMiniRadar(ctx,f){if(!f.active||!this.active)return;const centerX=innerWidth-66-24,centerY=innerHeight-66-42,ownHeading=Number(geofs.animation.values.heading360||geofs.animation.values.heading)||0,own=geofs.aircraft.instance.llaLocation;ctx.fillStyle="rgba(0, 18, 12, 0.78)",ctx.strokeStyle="#94ffaf",ctx.lineWidth=1,ctx.beginPath(),ctx.arc(centerX,centerY,66,0,2*Math.PI),ctx.fill(),ctx.stroke(),ctx.globalAlpha=.5;for(const ring of[10,20,30])ctx.beginPath(),ctx.arc(centerX,centerY,2.2*ring,0,2*Math.PI),ctx.stroke();ctx.beginPath(),ctx.moveTo(centerX-66,centerY),ctx.lineTo(centerX+66,centerY),ctx.moveTo(centerX,centerY-66),ctx.lineTo(centerX,centerY+66),ctx.stroke(),ctx.globalAlpha=1,ctx.fillStyle="#94ffaf",ctx.beginPath(),ctx.arc(centerX,centerY,3,0,2*Math.PI),ctx.fill();for(const target of this.combat.targets?.currentTargets??[]){if(target.rangeNm>30)continue;const angle=angleDifference(ownHeading,target.bearing)*DEG;ctx.fillStyle=target.isNpc?"#ffab55":"#61d9ff",ctx.beginPath(),ctx.arc(centerX+Math.sin(angle)*target.rangeNm*2.2,centerY-Math.cos(angle)*target.rangeNm*2.2,target.isNpc?4:3,0,2*Math.PI),ctx.fill()}for(const missile of this.npcMissiles){const position=Cesium.Cartographic.fromCartesian(missile.position);if(!position||!own)continue;const north=(position.latitude/DEG-own[0])*DEG*R_EARTH,east=(position.longitude/DEG-own[1])*DEG*R_EARTH*Math.cos(own[0]*DEG),bearing=normalizeHeading(Math.atan2(east,north)/DEG),range=Math.hypot(north,east)/NM;if(range>30)continue;const angle=angleDifference(ownHeading,bearing)*DEG;ctx.fillStyle="#ff4040",ctx.fillRect(centerX+Math.sin(angle)*range*2.2-2,centerY-Math.cos(angle)*range*2.2-2,4,4)}ctx.font="bold 11px monospace",ctx.textAlign="center",ctx.fillStyle="#94ffaf",ctx.fillText("A/A RADAR 30 NM",centerX,centerY-66-8),ctx.font="9px monospace",ctx.fillText("N",centerX,centerY-66+11),ctx.fillStyle="#ffab55",ctx.fillText("BANDIT",centerX-25,centerY+66+18),ctx.fillStyle="#ff4040",ctx.fillText("MISSILE",centerX+27,centerY+66+18)}mountOptions(){const mounted=CombatMath.ensureGeneralFieldset("addon-combat-aa","A/A Combat Simulation","Choose difficulty (1 easy to 6 hardest) and 1-10 bandits. Each bandit spawns at a random spot 5-30 NM away, facing a random heading. Settings apply when you start/restart. Bandits fire training missiles and use flares; evade incoming missiles with Backspace. The 30 NM mini-radar appears during the simulation.");mounted&&(mounted.controls.dataset.built&&this.statusElement?.isConnected||(mounted.controls.dataset.built="1",this.buildOptions(mounted.controls)))}buildOptions(container){container.replaceChildren(),this.statusElement=document.createElement("p"),container.appendChild(this.statusElement);const settings=document.createElement("div");Object.assign(settings.style,{display:"flex",flexWrap:"wrap",alignItems:"center",gap:"12px",margin:"8px 0"}),settings.append(CombatMath.makeSelect("Difficulty (1 easy - 6 hard)",this.selectedDifficulty,[1,2,3,4,5,6],value=>{this.selectedDifficulty=value},"A/A simulation difficulty",value=>`${value} - ${DIFFICULTY_NAMES[value-1]}`),CombatMath.makeSelect("Bandits",this.selectedBanditCount,Array.from({length:10},(_,i)=>i+1),value=>{this.selectedBanditCount=value},"Number of A/A simulation bandits"));const poiLabel=document.createElement("label");Object.assign(poiLabel.style,{display:"flex",alignItems:"center",gap:"6px"});const poiCheckbox=document.createElement("input");poiCheckbox.type="checkbox",poiCheckbox.checked=this.showBanditHudPoi,poiCheckbox.setAttribute("aria-label","Show bandit HUD points of interest"),poiCheckbox.addEventListener("change",event=>{event.stopPropagation(),this.showBanditHudPoi=poiCheckbox.checked,CombatMath.writeStorage("geofs-addon-combat-aa-poi",this.showBanditHudPoi)}),poiCheckbox.addEventListener("click",event=>event.stopPropagation()),poiLabel.append(poiCheckbox,document.createTextNode("Show bandit HUD POI")),settings.appendChild(poiLabel),container.appendChild(settings);const actions=document.createElement("div");Object.assign(actions.style,{display:"flex",flexWrap:"wrap",gap:"8px"}),this.startButton=CombatMath.makeButton("Start / Restart A/A","Start or restart A/A training with the selected difficulty and bandit count",()=>this.startSimulation()),this.stopButton=CombatMath.makeButton("Stop Simulation","Stop A/A training",()=>this.stopSimulation()),actions.append(this.startButton,this.stopButton),container.appendChild(actions),this.updateOptions()}updateOptions(){if(!this.statusElement?.isConnected)return;let text=this.active?`${this.npcs.length} BANDIT(S) ACTIVE | DIFFICULTY ${this.npcs[0]?.difficulty??this.selectedDifficulty}/6 | ${this.kills} KILL(S)`:`INACTIVE | ${this.kills} KILL(S) | ${this.hits} HIT(S)`;this.active&&(text+=` | INCOMING: ${this.npcMissiles.length} | HITS TAKEN: ${this.hitsTaken}`);const mp=this.combat.multiplayer;mp?.enabled&&mp.group&&(text+=` | MP SYNC ${mp.sharedHits} HIT(S)`),this.statusElement.textContent=text,this.startButton&&(this.startButton.disabled=!WeaponOverlayModule.isReady()),this.stopButton&&(this.stopButton.disabled=!this.active)}}}(),function(){"use strict";const{turnVelocity:turnVelocity,mul:mul}=CombatMath;class GeoFsChatTransport{constructor(onChatMessage){this.onChatMessage=onChatMessage,this.originalUpdate=null,this.wrappedUpdate=null}isAvailable(){return"function"==typeof window.multiplayer?.setChatMessage}send(message){if(!this.isAvailable())throw new Error("GEOFS CHAT SYNC API UNAVAILABLE");if(message.length>70)throw new Error("SYNC EVENT EXCEEDS GEOFS CHAT LIMIT");return window.multiplayer.setChatMessage(message),!0}getSelfId(payload){return String(window.multiplayer?.myId??window.multiplayer?.lastResponse?.myId??payload?.myId??"")}ensureHook(){const multiplayer=window.multiplayer;if(!multiplayer||"function"!=typeof multiplayer.updateCallback)return!1;if(this.hookedMultiplayer===multiplayer)return!0;const transport=this,original=multiplayer.updateCallback;return this.hookedMultiplayer=multiplayer,this.originalUpdate=original,this.active=!0,this.wrappedUpdate=function(payload){if(transport.active)try{const messages=Array.isArray(payload?.chatMessages)?payload.chatMessages:[];for(const message of messages)transport.onChatMessage(message,payload)}catch(error){console.error("[MultiplayerModule] chat processing failed",error)}return original.apply(this,arguments)},multiplayer.updateCallback=this.wrappedUpdate,!0}stop(){this.active=!1;const multiplayer=this.hookedMultiplayer;multiplayer&&multiplayer.updateCallback===this.wrappedUpdate&&this.originalUpdate&&(multiplayer.updateCallback=this.originalUpdate),this.hookedMultiplayer=null}}window.GeoFsChatTransport=GeoFsChatTransport,window.MultiplayerModule=class MultiplayerModule{constructor(combat,config={}){this.combat=combat,combat.multiplayer=this,this.cfg={...config};const saved=CombatMath.readStorage("geofs-addon-combat-mp",{})||{};this.enabled=!!saved.enabled,this.group="string"==typeof saved.group?saved.group.replace(/[^a-zA-Z0-9_-]/g,"").slice(0,16):"",this.sharedHits=0,this.networkMissiles=[],this.receivedNetworkEvents=new Set,this.seenChatMessages=new Set,this.transport=new GeoFsChatTransport((message,payload)=>this.processChat(message,payload)),this.lastHookCheck=0,this.unsubscribers=[]}start(){this.transport.ensureHook();const overlay=this.combat.overlay;overlay&&this.unsubscribers.push(overlay.registerLayer("multiplayer",40,(ctx,f)=>this.updateAndDrawNetworkMissiles(ctx,f)),overlay.onAircraftChange(()=>{this.networkMissiles=[]}))}stop(){this.transport.stop();for(const unsubscribe of this.unsubscribers)unsubscribe();this.unsubscribers=[],this.networkMissiles=[]}saveSettings(){CombatMath.writeStorage("geofs-addon-combat-mp",{enabled:this.enabled,group:this.group})}rememberEvent(key){this.receivedNetworkEvents.add(key),this.receivedNetworkEvents.size>500&&this.receivedNetworkEvents.delete(this.receivedNetworkEvents.values().next().value)}groupFingerprint(){let hash=2166136261;for(let i=0;i>>0).toString(36)}encodeEvent(eventData){if(!Array.isArray(eventData))return"";const prefix=`F7|${this.groupFingerprint()}|`;if("T"===eventData[1])return`${prefix}T|${Date.now().toString(36)}`;if("L"===eventData[1]&&3===eventData[0]){const[,,missileId,targetId,sentAt]=eventData;if("string"!=typeof missileId||"string"!=typeof targetId)return"";const sentAtToken="string"==typeof sentAt?sentAt:Number(sentAt).toString(36);return/^[0-9a-z]+$/i.test(sentAtToken)?prefix+["L",encodeURIComponent(missileId),encodeURIComponent(targetId),sentAtToken].join("|"):""}if(("H"===eventData[1]||"X"===eventData[1]||"D"===eventData[1])&&5===eventData.length){const[,type,missileId,targetId,sentAt]=eventData;return"string"==typeof missileId&&"string"==typeof targetId&&Number.isFinite(sentAt)?prefix+[type,encodeURIComponent(missileId),encodeURIComponent(targetId),sentAt.toString(36)].join("|"):""}return""}parseEvent(value){const fields=value.split("|"),type=fields[0];if("T"===type&&2===fields.length){const sentAt=Number.parseInt(fields[1],36);return Number.isFinite(sentAt)?[1,"T",sentAt]:null}if("L"===type&&4===fields.length){const sentAt=Number.parseInt(fields[3],36);return Number.isFinite(sentAt)?[3,"L",decodeURIComponent(fields[1]),decodeURIComponent(fields[2]),sentAt]:null}if(("H"===type||"X"===type||"D"===type)&&4===fields.length){const sentAt=Number.parseInt(fields[3],36);return Number.isFinite(sentAt)?[1,type,decodeURIComponent(fields[1]),decodeURIComponent(fields[2]),sentAt]:null}return null}normalizeChatText(value){let text=String(value??"");for(let attempt=0;attempt<2;attempt++)try{const decoded=decodeURIComponent(text.replace(/\+/g,"%20"));if(decoded===text)break;text=decoded}catch(error){break}return text}async sendEvent(eventData){if(!this.enabled||this.group.length<16)return!1;try{const message=this.encodeEvent(eventData);return!!message&&this.transport.send(message)}catch(error){return this.combat.notify(error.message||"MULTIPLAYER EVENT COULD NOT BE SENT",3e3),!1}}getUser(userId){const users=window.multiplayer?.visibleUsers;if(!users||"object"!=typeof users)return null;const id=String(userId);for(const[key,user]of Object.entries(users))if([key,user?.id,user?.uid].some(value=>null!=value&&String(value)===id))return user;return null}getUserLabel(userId){const user=this.getUser(userId),label=user?.callsign??user?.cs??user?.aircraftName??user?.username;return label?String(label).slice(0,20):`PLAYER ${String(userId).slice(0,12)}`}processChat(message,payload){if(!this.enabled||this.group.length<16)return;const senderId=String(message?.uid??""),selfId=this.transport.getSelfId(payload);if(!senderId||selfId&&senderId===selfId)return;const chatText=this.normalizeChatText(message?.msg);if(!chatText.startsWith("F7|"))return;const groupSeparator=chatText.indexOf("|",3);if(groupSeparator<0)return;if(chatText.slice(3,groupSeparator)!==this.groupFingerprint())return;const messageKey=`${senderId}:${chatText}`;if(!this.seenChatMessages.has(messageKey)){this.seenChatMessages.add(messageKey),this.seenChatMessages.size>500&&this.seenChatMessages.delete(this.seenChatMessages.values().next().value);try{const data=this.parseEvent(chatText.slice(groupSeparator+1));if(!data)throw new Error("Malformed sync event");this.processEvent(data,senderId,selfId)}catch(error){this.combat.notify(`INVALID SYNC CHAT MESSAGE (${chatText.length} CHARS)`,3e3)}}}isFresh(sentAt){return Number.isFinite(sentAt)&&Math.abs(Date.now()-sentAt)<=15e3}processEvent(data,senderId,selfId){if(!this.enabled||!Array.isArray(data))return;const type=data[1];if("T"===type)return void this.combat.notify("MULTIPLAYER SYNC TEST RECEIVED",3e3);const[,,missileId,targetId,sentAt]=data;if("string"!=typeof missileId||!this.isFresh(sentAt))return;const key=`${senderId}:${missileId}`;if("L"===type){if(3!==data[0]||!selfId||String(targetId)!==selfId)return;if(this.receivedNetworkEvents.has(`L:${key}`))return;const coordinates=this.getUser(senderId)?.lastUpdate?.co,own=geofs.aircraft.instance?.llaLocation;if(!Array.isArray(coordinates)||coordinates.length<3||!Array.isArray(own)||own.length<3)return;const[lat,lon,altitude]=coordinates.map(Number);if(![lat,lon,altitude].every(Number.isFinite))return;const position=Cesium.Cartesian3.fromDegrees(lon,lat,altitude),targetPosition=Cesium.Cartesian3.fromDegrees(own[1],own[0],own[2]),direction=Cesium.Cartesian3.subtract(targetPosition,position,new Cesium.Cartesian3),distance=Cesium.Cartesian3.magnitude(direction);if(!Number.isFinite(distance)||distance<=0)return;return Cesium.Cartesian3.normalize(direction,direction),Cesium.Cartesian3.multiplyByScalar(direction,900,direction),this.rememberEvent(`L:${key}`),this.networkMissiles.push({key:key,senderId:senderId,missileId:missileId,position:position,velocity:[direction.x,direction.y,direction.z],speed:900,turnRate:1.2,maxFlightTime:Math.min(240,Math.max(8,distance/700+10)),t0:performance.now(),updatedAt:performance.now(),trail:[]}),this.networkMissiles.length>32&&this.networkMissiles.shift(),void this.combat.notify(`MISSILE LAUNCHED BY ${this.getUserLabel(senderId)}`,2500)}if("H"===type){if(String(targetId)!==selfId)return;if(this.receivedNetworkEvents.has(`D:${key}`)||this.receivedNetworkEvents.has(`H:${key}`))return;this.rememberEvent(`H:${key}`),this.networkMissiles=this.networkMissiles.filter(missile=>missile.key!==key),this.sharedHits++;const own=geofs.aircraft.instance?.llaLocation;return Array.isArray(own)&&own.length>=3&&this.combat.overlay?.addImpact(Cesium.Cartesian3.fromDegrees(own[1],own[0],own[2])),void this.combat.notify(`MISSILE HIT FROM ${this.getUserLabel(senderId)}`,3500)}if("D"===type){if(String(targetId)!==senderId)return;const evadeKey=`D:${key}`;if(this.receivedNetworkEvents.has(evadeKey))return;const projectile=this.combat.projectile,missile=projectile?.missiles.find(item=>item.networkId===missileId&&String(item.targetId)===senderId);if(!missile)return;return this.rememberEvent(evadeKey),projectile.missiles=projectile.missiles.filter(item=>item!==missile),this.combat.overlay?.addImpact(CombatMath.worldPosition(missile.enuMat,missile.position)),void this.combat.notify(`${this.getUserLabel(senderId)} EVADED MISSILE WITH FLARES`,3e3)}if("X"===type){if(String(targetId)!==selfId)return;this.networkMissiles=this.networkMissiles.filter(missile=>missile.key!==key)}}evadeIncomingMissiles(){const now=performance.now(),incoming=this.networkMissiles.filter(missile=>now-missile.t0<1e3*missile.maxFlightTime);if(!incoming.length)return null;const selfId=this.transport.getSelfId(),sends=incoming.map(missile=>(this.rememberEvent(`D:${missile.key}`),this.enabled&&selfId?this.sendEvent([1,"D",missile.missileId,selfId,Date.now()]):Promise.resolve(!1)));return this.networkMissiles=this.networkMissiles.filter(missile=>!incoming.includes(missile)),{count:incoming.length,promise:Promise.all(sends).then(results=>results.filter(Boolean).length)}}updateAndDrawNetworkMissiles(ctx,f){if(f.nowMs-this.lastHookCheck>1e3&&(this.lastHookCheck=f.nowMs,this.transport.ensureHook(),this.mountOptions()),!this.enabled||!this.networkMissiles.length)return;const own=geofs.aircraft.instance.llaLocation;if(!Array.isArray(own)||own.length<3)return;const now=f.nowMs,ownWorld=Cesium.Cartesian3.fromDegrees(own[1],own[0],own[2]),live=[];for(const missile of this.networkMissiles){const age=(now-missile.t0)/1e3;if(age>missile.maxFlightTime+5)continue;const dt=Math.min(.25,Math.max(0,(now-missile.updatedAt)/1e3)),previousPosition=missile.position,delta=Cesium.Cartesian3.subtract(ownWorld,previousPosition,new Cesium.Cartesian3);let nextPosition=previousPosition;if(Cesium.Cartesian3.magnitude(delta)>0&&dt>0){missile.velocity=turnVelocity(missile.velocity,[delta.x,delta.y,delta.z],missile.turnRate*dt);const speed=Math.hypot(...missile.velocity)||1;missile.velocity=mul(missile.velocity,missile.speed/speed),nextPosition=Cesium.Cartesian3.add(previousPosition,Cesium.Cartesian3.multiplyByScalar(new Cesium.Cartesian3(...missile.velocity),dt,new Cesium.Cartesian3),new Cesium.Cartesian3)}if(age>.15&&dt>0){const segment=Cesium.Cartesian3.subtract(nextPosition,previousPosition,new Cesium.Cartesian3),segmentSquared=Cesium.Cartesian3.dot(segment,segment),toTarget=Cesium.Cartesian3.subtract(ownWorld,previousPosition,new Cesium.Cartesian3),closestFraction=segmentSquared>0?Math.max(0,Math.min(1,Cesium.Cartesian3.dot(toTarget,segment)/segmentSquared)):0,closestPoint=Cesium.Cartesian3.add(previousPosition,Cesium.Cartesian3.multiplyByScalar(segment,closestFraction,new Cesium.Cartesian3),new Cesium.Cartesian3);if(Cesium.Cartesian3.distance(closestPoint,ownWorld)<=35){const hitKey=`H:${missile.key}`;this.receivedNetworkEvents.has(hitKey)||(this.rememberEvent(hitKey),this.sharedHits++,f.overlay.addImpact(Cesium.Cartesian3.clone(ownWorld),now),this.combat.notify(`MISSILE HIT FROM ${this.getUserLabel(missile.senderId)}`,3500));continue}}missile.position=nextPosition,missile.updatedAt=now,missile.trail.push(Cesium.Cartesian3.clone(nextPosition)),missile.trail.length>18&&missile.trail.shift(),live.push(missile),ctx.save(),ctx.strokeStyle="#ff4545",ctx.fillStyle="#ff4545",ctx.shadowColor="#ff2020",ctx.shadowBlur=9,ctx.lineWidth=2.5;for(let i=1;i{this.enabled=enabledInput.checked,this.saveSettings(),this.enabled||(this.networkMissiles=[]),this.combat.notify("MULTIPLAYER MISSILE SYNC "+(this.enabled?"ON":"OFF"),2e3)}),label.append(enabledInput,document.createTextNode("Enable multiplayer missile sync"));const groupLabel=document.createElement("label");Object.assign(groupLabel.style,{display:"flex",alignItems:"center",gap:"8px"}),groupLabel.appendChild(document.createTextNode("Sync group code"));const groupInput=document.createElement("input");groupInput.type="text",groupInput.value=this.group,groupInput.maxLength=16,groupInput.autocomplete="off",groupInput.spellcheck=!1,groupInput.placeholder="share the same 16-character code",groupInput.setAttribute("aria-label","Multiplayer missile sync group code"),groupInput.addEventListener("change",()=>{const value=groupInput.value.replace(/[^a-zA-Z0-9_-]/g,"").slice(0,16);groupInput.value!==value&&(groupInput.value=value),this.group=value,this.saveSettings()}),groupLabel.appendChild(groupInput);const generateButton=CombatMath.makeButton("Generate Group Code","Generate a random sync group code",()=>{this.group=crypto.randomUUID().replace(/-/g,"").slice(0,16),groupInput.value=this.group,this.saveSettings()}),testButton=CombatMath.makeButton("Send Sync Test","Send a multiplayer sync test message",async()=>{this.enabled?this.group.length<16?this.combat.notify("SET A 16-CHARACTER SYNC GROUP CODE",2500):await this.sendEvent([1,"T",Date.now()])&&this.combat.notify("SYNC TEST SENT IN PUBLIC GEOFS CHAT",3e3):this.combat.notify("ENABLE MULTIPLAYER SYNC FIRST",2500)}),buttons=document.createElement("div");Object.assign(buttons.style,{display:"flex",flexWrap:"wrap",gap:"8px",margin:"8px 0"}),buttons.append(generateButton,testButton);const note=document.createElement("p");note.style.margin="6px 0",note.textContent="Both players need the same 16-character group code and updated addon. Lock a radar contact with Enter before launching a missile; Backspace releases flares and reports an evade for synced incoming missiles. Sync messages are plain text in public GeoFS chat; anyone can read them. The group fingerprint only filters messages.",container.append(label,groupLabel,buttons,note)}}}();class ChecklistModule{static loadDefaults(presetName="fighter"){const defaultsApi=window.ChecklistModuleDefaults,createFromDefaults=defaultsApi?.createModule;if("function"!=typeof createFromDefaults)return null;const module=createFromDefaults(presetName);return module instanceof ChecklistModule?module:null}constructor(dependencies={}){this.dependencies=dependencies??{},this.types=["PROC","EMER","OPS","FLP"],this.checklistsByType=Object.create(null),this.currentIndexByType=Object.create(null);for(const type of this.types)this.checklistsByType[type]=[],this.currentIndexByType[type]=0}registerMfdPages(mfdModule){return mfdModule.registerPage({title:"CHK",leftButtons:[{key:"PREV",label:"PREV",states:[""],stateIndex:0,managedExternally:!0,onClick:()=>{const type=OptionModule.getOption("CHK","TYPE","PROC");this.prevChecklist(type)}},{key:"N/A1",label:"",states:[""],stateIndex:0},{key:"ALL",label:"SHOW",states:["ONE","ALL"],stateIndex:0},{key:"N/A2",label:"",states:[""],stateIndex:0},{key:"TYPE",label:"TYPE",states:["PROC","EMER","OPS","FLP"],stateIndex:0,onClick:({nextState:nextState})=>{OptionModule.setOption("CHK","ALL","ALL"),this.setCurrentIndex(nextState,0)}}],rightButtons:[{key:"NEXT",label:"NEXT",states:[""],stateIndex:0,managedExternally:!0,onClick:()=>{const type=OptionModule.getOption("CHK","TYPE","PROC");this.nextChecklist(type)}},{key:"N/A3",label:"",states:[""],stateIndex:0},{key:"N/A31",label:"",states:[""],show:()=>"ONE"!==OptionModule.getOption("CHK","ALL","ONE"),stateIndex:0},{key:"CHECK_ITEM",label:"CHK",states:[""],stateIndex:0,managedExternally:!0,show:()=>"ONE"===OptionModule.getOption("CHK","ALL","ONE"),onClick:()=>{const type=OptionModule.getOption("CHK","TYPE","PROC");this.markNextCurrentItem(type)}},{key:"RESET",label:"RST",states:[""],stateIndex:0,managedExternally:!0,onClick:()=>{const isAllMode="ALL"===OptionModule.getOption("CHK","ALL","ONE"),type=OptionModule.getOption("CHK","TYPE","PROC");isAllMode?this.resetType(type):this.resetCurrent(type)}},{key:"COMPLETE",label:"DONE",states:[""],stateIndex:0,managedExternally:!0,onClick:()=>{const isAllMode="ALL"===OptionModule.getOption("CHK","ALL","ONE"),type=OptionModule.getOption("CHK","TYPE","PROC");if(isAllMode)return this.toggleCurrentCompleted(type),void this.nextChecklistNoWrap(type);this.setCurrentCompleted(type,!0),this.nextChecklistNoWrap(type)}}],lines:[],render:(renderer,renderContext)=>{const ctx=renderContext?.ctx??renderer?.canvasAPI?.context,w=renderContext?.w??renderer?.canvasAPI?.canvas?.width??512,h=renderContext?.h??renderer?.canvasAPI?.canvas?.height??512,color=renderContext?.color??"#00ff66";if(!ctx)return;const selectedType=OptionModule.getOption("CHK","TYPE","PROC"),showAll="ALL"===OptionModule.getOption("CHK","ALL","ONE"),checklists=this.getChecklists(selectedType);ctx.save(),ctx.setTransform(1,0,0,1,0,0),ctx.fillStyle=color,ctx.strokeStyle=color,ctx.textBaseline="middle";const contentX=.22*w,textPx=Math.round(.045*h);if(ctx.textAlign="left",ctx.font=`bold ${textPx}px monospace`,ctx.fillText(`TYPE ${selectedType} MODE ${showAll?"ALL":"ONE"}`,contentX,.16*h),!checklists.length)return ctx.font=`bold ${textPx}px monospace`,ctx.fillText("NO CHECKLISTS",contentX,.24*h),void ctx.restore();if(showAll){const startX=contentX,startY=.22*h,rowStep=.062*h,boxSize=.032*h;ctx.textAlign="left",ctx.font=`bold ${textPx}px monospace`;for(let i=0;i.88*h)break;const checklist=checklists[i];ctx.strokeRect(startX,rowY-.5*boxSize,boxSize,boxSize),checklist?.completed&&ctx.fillRect(startX+2,rowY-.5*boxSize+2,Math.max(0,boxSize-4),Math.max(0,boxSize-4));const currentMark=i===this.getCurrentIndex(selectedType)?">":" ";ctx.fillText(`${currentMark} ${checklist?.title??`Checklist ${i+1}`}`,startX+boxSize+.02*w,rowY)}}else{const current=this.getCurrentChecklist(selectedType),completedTag=current?.completed?"[X]":"[ ]";ctx.textAlign="left",ctx.font=`bold ${textPx}px monospace`,ctx.fillText(`${completedTag} ${current?.title??"Checklist"}`,contentX,.24*h),ctx.textAlign="left",ctx.font=`bold ${textPx}px monospace`;const items=Array.isArray(current?.items)?current.items:[],itemCompleted=this.getCurrentItemCompleted(selectedType);let y=.295*h;for(let i=0;i.88*h);i++){const marker=itemCompleted[i]?"v":"-";ctx.fillText(`${marker} ${items[i]}`,contentX,y),y+=.055*h}}ctx.restore()}}),!0}getTypeList(type){const list=this.checklistsByType[type];if(!Array.isArray(list))throw new Error(`Unsupported checklist type: ${type}`);return list}ensureItemStates(checklist){const states=checklist.itemCompleted;if(!Array.isArray(states)||states.length!==checklist.items.length)throw new Error("Checklist itemCompleted must be an array matching items length");return states}addChecklist(definition){const type=definition.type,list=this.getTypeList(type),title=String(definition?.title??"").trim();if(!title)return!1;const items=Array.isArray(definition?.items)?definition.items.map(item=>String(item??"").trim()).filter(Boolean):[],checklist={id:String(definition?.id??`${type}-${list.length+1}`),type:type,title:title,items:items,itemCompleted:Array.isArray(definition?.itemCompleted)?definition.itemCompleted.slice(0,items.length):new Array(items.length).fill(!1),completed:Boolean(definition?.completed)};this.ensureItemStates(checklist),checklist.completed&&checklist.itemCompleted.length&&(checklist.itemCompleted=checklist.itemCompleted.map(()=>!0)),list.push(checklist);const idx=this.currentIndexByType[type]??0;return this.currentIndexByType[type]=Math.max(0,Math.min(idx,list.length-1)),!0}getChecklists(type){return this.getTypeList(type)}getCurrentIndex(type){const list=this.getChecklists(type);if(!list.length)return 0;const idx=Number(this.currentIndexByType[type]);return Number.isFinite(idx)?Math.max(0,Math.min(list.length-1,Math.floor(idx))):0}setCurrentIndex(type,index){const list=this.getChecklists(type);if(!list.length)return this.currentIndexByType[type]=0,0;const idx=Number(index),clamped=Number.isFinite(idx)?Math.max(0,Math.min(list.length-1,Math.floor(idx))):0;return this.currentIndexByType[type]=clamped,clamped}nextChecklist(type){const list=this.getChecklists(type);if(!list.length)return null;const next=(this.getCurrentIndex(type)+1)%list.length;return this.currentIndexByType[type]=next,list[next]}prevChecklist(type){const list=this.getChecklists(type);if(!list.length)return null;const next=(this.getCurrentIndex(type)-1+list.length)%list.length;return this.currentIndexByType[type]=next,list[next]}getCurrentChecklist(type){const list=this.getChecklists(type);return list.length?list[this.getCurrentIndex(type)]??null:null}hasNextChecklist(type){const list=this.getChecklists(type);return!!list.length&&this.getCurrentIndex(type)=list.length-1)return list[current]??null;const next=current+1;return this.currentIndexByType[type]=next,list[next]??null}setCurrentCompleted(type,completed){const checklist=this.getCurrentChecklist(type);if(!checklist)return!1;const nextCompleted=Boolean(completed);checklist.completed=nextCompleted;const states=this.ensureItemStates(checklist);for(let i=0;i!value);return nextItemIndex<0?(states.length&&(checklist.completed=!0),!1):(states[nextItemIndex]=!0,checklist.completed=states.length>0&&states.every(Boolean),!0)}resetCurrent(type){return this.setCurrentCompleted(type,!1)}resetType(type){const list=this.getChecklists(type);for(const checklist of list)checklist.completed=!1,this.ensureItemStates(checklist).fill(!1);return this.currentIndexByType[type]=0,!0}}class DataCartridgeModule{static FOO_AREA_STYLE={color:"#f44336",fillColor:"#f44336",fillOpacity:.16};static AREA_STYLE_BY_TYPE={SAM:{color:"#ff5252",fillColor:"#ff5252",fillOpacity:.18},NOFLY:{color:"#ff9800",fillColor:"#ff9800",fillOpacity:.16},UNRESTRICTED:{color:"#4caf50",fillColor:"#4caf50",fillOpacity:.12},DANGER:{color:"#9c27b0",fillColor:"#9c27b0",fillOpacity:.16},AREA:{color:"#03a9f4",fillColor:"#03a9f4",fillOpacity:.14}};static MARKPOINT_COLOR_BY_TYPE={TARGET:"#f44336",FRIENDLY:"#2196f3",RESQUE:"#ff9800",CIVILIAN:"#4caf50"};static NAVAID_COLOR_BY_MISSION_TYPE={CIVILIAN:"#4caf50",FOO:"#f44336",FRIEND:"#2196f3",ALTERNATE:"#ff9800"};constructor(){this.data=this._newData()}_newData(){return{version:1,source:"empty",missionName:"Untitled",group:"",flight:"",wingman:"",flightData:{startTimeZ:"",startTaxiZ:"",startToZ:"",timeOverTargetZ:"",endTimeZ:""},positions:[],cruise:{altitude:"",speed:""},notes:"",landing:{airportIcao:"",runway:"",nav1:"",pattern:"",formation:"",altEntryAgl:"",speedEntryKn:"",pitchIntervalS:"",speedDownwindKn:""},loadedAt:null,flightPlan:[],navaids:[],markpoints:[],areas:[],checklists:[],iffCodes:[]}}_clone(value){return JSON.parse(JSON.stringify(value))}_nextMarkpointId(){return Array.isArray(this.data?.markpoints)&&this.data.markpoints.length?this.data.markpoints.reduce((maxId,item)=>Math.max(maxId,Number(item?.id)||0),0)+1:1}_emitUpdate(){window.dispatchEvent(new CustomEvent("GeoFSDataCartridge:updated",{detail:this.getMissionData()}))}clear(){return this.data=this._newData(),this._emitUpdate(),!0}loadMissionData(missionData,options={}){const src=missionData,loadedAt=(new Date).toISOString(),normalized=this._newData();return normalized.source=options.source??"mission-planner",normalized.missionName=src.name??src.missionName??"Untitled",normalized.group=src.group??"",normalized.flight=src.flight??"",normalized.wingman=src.wingman??"",normalized.flightData=this._clone(src.flightData??normalized.flightData),normalized.positions=this._clone(src.positions??[]),normalized.cruise=this._clone(src.cruise??normalized.cruise),normalized.notes=src.notes??src.cruise?.notes??"",normalized.landing=this._clone(src.landing??normalized.landing),normalized.loadedAt=loadedAt,normalized.flightPlan=this._clone(src.flightPlan??[]),normalized.checklists=this._clone(src.checklists??[]),normalized.iffCodes=this._clone(src.iffCodes??[]),normalized.navaids=this._clone(src.navaids??[]),normalized.markpoints=this._clone(src.markpoints??[]),normalized.areas=this._clone(src.areas??[]).sort((a,b)=>a.order-b.order),this.data=normalized,this._emitUpdate(),!0}addTgpMarkpoint(point,options={}){const nextId=this._nextMarkpointId(),markpoint={id:nextId,name:options.name??`TGP Markpoint ${nextId}`,abbreviation:options.abbreviation??`TGP${nextId}`,type:options.type??"TARGET",lat:point.lat,lon:point.lon,altM:point.altM??null,source:"TGP"};return this.data.markpoints.push(markpoint),this._emitUpdate(),this._clone(markpoint)}setMarkpointType(index,type){const markpoint=this.data.markpoints[index];return!!markpoint&&(markpoint.type=type,this._emitUpdate(),!0)}setActiveMarkpoint(index){if(!this.data.markpoints[index])return!1;for(let i=0;imarkpoint?.active);return active?this._clone(active):null}deleteMarkpoint(index){return!!this.data.markpoints[index]&&(this.data.markpoints.splice(index,1),this._emitUpdate(),!0)}getMissionData(){return this._clone(this.data)}getMissionName(){return this.data.missionName}getGroup(){return this.data.group}getFlight(){return this.data.flight}getWingman(){return this.data.wingman}getFlightData(){return this._clone(this.data.flightData)}getPositions(){return this._clone(this.data.positions)}getCruise(){return this._clone(this.data.cruise)}getNotes(){return this.data.notes??""}getLanding(){return this._clone(this.data.landing)}getFlightPlan(){return this._clone(this.data.flightPlan)}getNavaids(){return this._clone(this.data.navaids)}getMarkpoints(){return this._clone(this.data.markpoints)}getAreas(){return this._clone(this.data.areas)}getChecklists(){return this._clone(this.data.checklists)}getIffCodes(){return this._clone(this.data.iffCodes)}getRenderableData(){const data=this.getMissionData();return{missionName:data.missionName,loadedAt:data.loadedAt,navaids:data.navaids,markpoints:data.markpoints,areas:data.areas}}getAreaStyle(type,group=""){return"FOO"===group?this._clone(DataCartridgeModule.FOO_AREA_STYLE):this._clone(DataCartridgeModule.AREA_STYLE_BY_TYPE[type]??DataCartridgeModule.AREA_STYLE_BY_TYPE.AREA)}getMarkpointColor(type){return DataCartridgeModule.MARKPOINT_COLOR_BY_TYPE[type]??"#00bcd4"}getNavaidColor(missionType){return DataCartridgeModule.NAVAID_COLOR_BY_MISSION_TYPE[missionType??"FRIEND"]??"#2196f3"}}window.DataCartridgeModule=DataCartridgeModule;class NavModule{constructor(mapModule=null,dataCartridgeModule=null){this.mapModule=mapModule,this.dataCartridgeModule=dataCartridgeModule}setMapModule(mapModule){return this.mapModule=mapModule,this}setDataCartridgeModule(dataCartridgeModule){return this.dataCartridgeModule=dataCartridgeModule,this}registerMfdPages(mfdModule){return mfdModule.registerPage({title:"NAV",leftButtons:[{key:"DISPLAY",label:"DISP",states:["HSI","MAP"],stateIndex:0},{key:"DECLUTTER",label:"DCL",states:["OFF","L1","L2"],stateIndex:0},{key:"MARK",label:"MRK",states:["","FRND","CIV","UNKN","FOO"],values:["","FRIEND","CIVILIAN","UNKNOWN","FOO"],stateIndex:0,managedExternally:!0,show:()=>"MAP"===OptionModule.getOption("NAV","DISPLAY","HSI"),onClick:()=>{this.mapModule.cycleSelectedTrafficMark()}},{key:"SHOW",label:"SHOW",states:["","FRND","CIV","UNKN","FOO"],values:["","FRIEND","CIVILIAN","UNKNOWN","FOO"],stateIndex:0,managedExternally:!0,show:()=>"MAP"===OptionModule.getOption("NAV","DISPLAY","HSI"),onClick:()=>{this.mapModule.cycleShowFilter()}},{key:"VIEW",label:"VW",states:["A/C F/W","A/C CNT","A/C N","TGT","TGT N"],stateIndex:0,managedExternally:!0,show:()=>"MAP"===OptionModule.getOption("NAV","DISPLAY","HSI"),onClick:()=>{this.mapModule.cycleViewMode()}},{key:"N/A",label:"",states:[""],stateIndex:0},{key:"WPSEL",label:"↑",states:[""],stateIndex:0,minimal:!0,managedExternally:!0,combinedGroupLabel:"WP",show:()=>"HSI"===OptionModule.getOption("NAV","DISPLAY","HSI"),onClick:()=>{this.stepSelectedFlightPlanWaypoint(1)}},{key:"WPSEL",label:"↓",states:[""],stateIndex:0,minimal:!0,managedExternally:!0,combinedGroupLabel:"WP",show:()=>"HSI"===OptionModule.getOption("NAV","DISPLAY","HSI"),onClick:()=>{this.stepSelectedFlightPlanWaypoint(-1)}}],rightButtons:[{key:"RANGE",label:"↑",states:["1","2.5","5","10","20","40","80","160"],values:[1,2.5,5,10,20,40,80,160],stateIndex:5,managedExternally:!0,minimal:!0,combinedGroupLabel:"RNG",onClick:()=>{this.mapModule.stepRange(1)}},{key:"RANGE",label:"↓",states:["1","2.5","5","10","20","40","80","160"],values:[1,2.5,5,10,20,40,80,160],stateIndex:5,managedExternally:!0,minimal:!0,combinedGroupLabel:"RNG",onClick:()=>{this.mapModule.stepRange(-1)}},{key:"ACSEL",label:"→",states:["A/C"],values:["A/C"],stateIndex:0,managedExternally:!0,minimal:!0,combinedGroupLabel:"AC",onClick:()=>{this.mapModule.stepSelectedTraffic(1)}},{key:"ACSEL",label:"←",states:["A/C"],values:["A/C"],stateIndex:0,managedExternally:!0,minimal:!0,combinedGroupLabel:"AC",onClick:()=>{this.mapModule.stepSelectedTraffic(-1)}},{key:"CLEAR",label:"CLR",states:[""],stateIndex:0,managedExternally:!0,onClick:()=>{this.mapModule.clearSelectedTraffic()}}],lines:[],render:(renderer,renderContext)=>{const ctx=renderContext?.ctx??renderer?.canvasAPI?.context,w=renderContext?.w??renderer?.canvasAPI?.canvas?.width??512,h=renderContext?.h??renderer?.canvasAPI?.canvas?.height??512,color=renderContext?.color??"#00ff66";if(!ctx)return;window.addonRuntime.navRdrRuntime=window.addonRuntime.navRdrRuntime||{bootStartMs:0};const engOn=Boolean(window.geofs?.animation?.values?.enginesOn);engOn?window.addonRuntime.navRdrRuntime.bootStartMs||(window.addonRuntime.navRdrRuntime.bootStartMs=Date.now()):window.addonRuntime.navRdrRuntime.bootStartMs=0;const elapsedMs=engOn?Date.now()-window.addonRuntime.navRdrRuntime.bootStartMs:0,bootReady=engOn&&elapsedMs>=4e3,contentX=.19*w,contentY=.13*h,contentW=.62*w,contentH=.74*h,mode=OptionModule.getOptionValue("NAV","DISPLAY","HSI"),declutterLevel=OptionModule.getOptionValue("NAV","DECLUTTER","OFF"),radarEnabled="ON"===OptionModule.getOptionValue("RDR","RADAR","OFF"),radarConeHalfAngleDeg="3B"===OptionModule.getOptionValue("RDR","SCAN","6B")?15:30;if(ctx.save(),ctx.setTransform(1,0,0,1,0,0),"MAP"!==mode&&(ctx.fillStyle="#000000",ctx.fillRect(contentX,contentY,contentW,contentH)),!engOn)return ctx.fillStyle=color,ctx.textAlign="center",ctx.textBaseline="middle",ctx.font=`bold ${Math.round(.046*h)}px monospace`,ctx.fillText("NAV OFF",contentX+.5*contentW,contentY+.5*contentH),void ctx.restore();if(!bootReady)return ctx.fillStyle=color,ctx.textAlign="center",ctx.textBaseline="middle",ctx.font=`bold ${Math.round(.046*h)}px monospace`,ctx.fillText("ALIGNING NAV...",contentX+.5*contentW,contentY+.5*contentH),void ctx.restore();const scene=this.mapModule.getSceneData(),rangeNm=Math.max(1,Number(scene?.rangeNm)||40),shouldShowTraffic=radarEnabled&&"L2"!==declutterLevel;shouldShowTraffic||this.mapModule.clearSelectedTraffic();const visibleTraffic=shouldShowTraffic?this.mapModule.getFilteredTraffic(scene?.traffic??[]):[],selectedTrafficUid=shouldShowTraffic?this.mapModule.getSelectedTrafficUid(visibleTraffic):null,selectedTraffic=visibleTraffic.find(c=>String(c?.uid??"")===String(selectedTrafficUid??""))??null,dataCartridgeScene=this.getDataCartridgeScene(),navObjectTextPx=Math.round(.032*h),drawOwnshipSymbol=(x,y,size=1,headingRelDeg=0)=>{ctx.strokeStyle="#ffffff",ctx.lineWidth=2;const fuselageHalf=.032*h*size,wingY=.01*-h*size,wingHalf=.028*h*size,tailY=.024*h*size,tailHalf=.014*h*size,angleRad=(Number(headingRelDeg)||0)*Math.PI/180;ctx.save(),ctx.translate(x,y),ctx.rotate(angleRad),ctx.beginPath(),ctx.moveTo(0,-fuselageHalf),ctx.lineTo(0,fuselageHalf),ctx.moveTo(-wingHalf,wingY),ctx.lineTo(wingHalf,wingY),ctx.moveTo(-tailHalf,tailY),ctx.lineTo(tailHalf,tailY),ctx.stroke(),ctx.restore()},drawRadarConeGuides=(x,y,headingRelDeg=0,topLimitY=0,maxLen=1/0)=>{if(radarEnabled){ctx.strokeStyle=color,ctx.lineWidth=1.8,ctx.beginPath();for(const side of[-1,1]){const guideRad=(headingRelDeg+side*radarConeHalfAngleDeg)*Math.PI/180,gx=Math.sin(guideRad),gy=-Math.cos(guideRad),guideLen=Math.min(maxLen,(y-topLimitY)/Math.max(1e-4,-gy));ctx.moveTo(x,y),ctx.lineTo(x+gx*guideLen,y+gy*guideLen)}ctx.stroke()}},drawWaypointDiamond=(x,y,selected=!1)=>{const size=selected?Math.max(5,.012*h):Math.max(4,.01*h);selected&&(ctx.fillStyle="#3da2ff",ctx.beginPath(),ctx.moveTo(x,y-size),ctx.lineTo(x+size,y),ctx.lineTo(x,y+size),ctx.lineTo(x-size,y),ctx.closePath(),ctx.fill()),ctx.strokeStyle="#3da2ff",ctx.lineWidth=2,ctx.beginPath(),ctx.moveTo(x,y-size),ctx.lineTo(x+size,y),ctx.lineTo(x,y+size),ctx.lineTo(x-size,y),ctx.closePath(),ctx.stroke()},drawCartridgePoint=(x,y,pointColor,label="",isMarkpoint=!1)=>{const radius=Math.max(3.5,.008*h);ctx.strokeStyle="#ffffff",ctx.lineWidth=1,ctx.fillStyle=pointColor,isMarkpoint?(ctx.beginPath(),ctx.moveTo(x,y-radius-1),ctx.lineTo(x+radius,y+radius),ctx.lineTo(x-radius,y+radius),ctx.closePath(),ctx.fill(),ctx.stroke()):(ctx.beginPath(),ctx.arc(x,y,radius,0,2*Math.PI),ctx.fill(),ctx.stroke()),"L2"!==declutterLevel&&label&&(ctx.fillStyle=pointColor,ctx.font=`bold ${Math.round(.026*h)}px monospace`,ctx.textAlign="left",ctx.textBaseline="middle",ctx.fillText(label.slice(0,10),x+.01*w,y-.012*h))},drawCartridgeAreaPath=(points,style)=>{if(Array.isArray(points)&&!(points.length<3)){ctx.strokeStyle=style.color,ctx.lineWidth=1.4,ctx.fillStyle=style.fillColor,ctx.globalAlpha=Number.isFinite(style.fillOpacity)?style.fillOpacity:.12,ctx.beginPath();for(let i=0;i{const isSelected=String(contact?.uid??"")===String(selectedTrafficUid??""),trafficColor=this.mapModule.getTrafficColor(contact);if("L1"===declutterLevel){ctx.fillStyle=trafficColor;const boxSize=Math.max(8,Math.round(.018*h));if(ctx.fillRect(x-.5*boxSize,y-.5*boxSize,boxSize,boxSize),isSelected){const pad=2,left=x-.5*boxSize-pad,right=x+.5*boxSize+pad,top=y-.5*boxSize-pad,bottom=y+.5*boxSize+pad,arm=Math.max(5,.012*h);ctx.strokeStyle="#ff3333",ctx.lineWidth=2,ctx.beginPath(),ctx.moveTo(left,top+arm),ctx.lineTo(left,top),ctx.lineTo(left+arm,top),ctx.moveTo(right-arm,top),ctx.lineTo(right,top),ctx.lineTo(right,top+arm),ctx.moveTo(left,bottom-arm),ctx.lineTo(left,bottom),ctx.lineTo(left+arm,bottom),ctx.moveTo(right-arm,bottom),ctx.lineTo(right,bottom),ctx.lineTo(right,bottom-arm),ctx.stroke()}return}const number=this.mapModule.getContactNumber(contact),glyph=String(number);ctx.fillStyle=trafficColor,ctx.font=`bold ${navObjectTextPx}px monospace`,ctx.textAlign="center",ctx.textBaseline="middle",ctx.fillText(glyph,x,y);const numberHalfH=Math.max(.016*h,8),roofHalfW=Math.max(.022*w,10),roofY=y-numberHalfH-.007*h,legLen=Math.max(.022*h,10);ctx.strokeStyle=trafficColor,ctx.lineWidth=2,ctx.beginPath(),ctx.moveTo(x-roofHalfW,roofY),ctx.lineTo(x+roofHalfW,roofY),ctx.moveTo(x-roofHalfW,roofY),ctx.lineTo(x-roofHalfW,roofY+legLen),ctx.moveTo(x+roofHalfW,roofY),ctx.lineTo(x+roofHalfW,roofY+legLen),ctx.stroke();const track=Number(contact?.trackDeg),relTrackRad=Number.isFinite(track)?(track-upHeadingDeg)*Math.PI/180:0,dirX=Math.sin(relTrackRad),dirY=-Math.cos(relTrackRad),lineStart=Math.max(.021*h,11)+2,lineLen=Math.max(.034*h,16);if(ctx.beginPath(),ctx.moveTo(x+dirX*lineStart,y+dirY*lineStart),ctx.lineTo(x+dirX*(lineStart+lineLen),y+dirY*(lineStart+lineLen)),ctx.stroke(),isSelected){const pad=2,left=x-roofHalfW-pad,right=x+roofHalfW+pad,top=roofY-pad,bottom=y+numberHalfH+pad,arm=Math.max(5,.012*h);ctx.strokeStyle="#ff3333",ctx.lineWidth=2,ctx.beginPath(),ctx.moveTo(left,top+arm),ctx.lineTo(left,top),ctx.lineTo(left+arm,top),ctx.moveTo(right-arm,top),ctx.lineTo(right,top),ctx.lineTo(right,top+arm),ctx.moveTo(left,bottom-arm),ctx.lineTo(left,bottom),ctx.lineTo(left+arm,bottom),ctx.moveTo(right-arm,bottom),ctx.lineTo(right,bottom),ctx.lineTo(right,bottom-arm),ctx.stroke()}},drawSelectedTrafficInfo=(anchorX,anchorY)=>{if(!selectedTraffic)return;const lineStep=.04*h;let y=anchorY;const name=String(selectedTraffic?.aircraftName??"").trim()||"UNKNOWN",callsign=String(selectedTraffic?.callsign??"").trim()||"N/A",speed=Number.isFinite(selectedTraffic?.speedKts)?selectedTraffic.speedKts:"--",altitude=Number.isFinite(selectedTraffic?.altFeet)?selectedTraffic.altFeet:"--",headingSel=Number.isFinite(selectedTraffic?.headingDeg)?selectedTraffic.headingDeg:"--",selectedNumber=this.mapModule.getContactNumber(selectedTraffic);ctx.fillStyle="#ff3333",ctx.font=`bold ${Math.round(.04*h)}px monospace`,ctx.textAlign="center",ctx.textBaseline="middle",ctx.fillText(`TGT ${selectedNumber}`,anchorX,y),y+=lineStep,ctx.fillText(`${name} / ${callsign}`.slice(0,34),anchorX,y),y+=lineStep,ctx.fillText(`SPD ${speed}`,anchorX,y),y+=lineStep,ctx.fillText(`ALT ${altitude}`,anchorX,y),y+=lineStep,ctx.fillText(`HDG ${headingSel}`,anchorX,y)},drawRadarOffInfo=(anchorX,anchorY)=>{radarEnabled||"OFF"!==String(declutterLevel).toUpperCase()||(ctx.fillStyle="#ffff33",ctx.font=`bold ${Math.round(.04*h)}px monospace`,ctx.textAlign="center",ctx.textBaseline="middle",ctx.fillText("Radar OFF",anchorX,anchorY))};if("HSI"===mode){const heading=Number(scene?.ownship?.heading)||Number(window.geofs?.animation?.values?.heading)||0,cx=contentX+.5*contentW,compassShiftPx=.016*h,cy=contentY+.525*contentH+compassShiftPx,radius=Math.min(.44*contentW,.305*h)+compassShiftPx,navTextPx=Math.round(.04*h),headingTextPx=Math.round(.046*h),headingBoxW=.13*w,headingBoxH=.06*h,headingBoxY=Math.max(contentY+.002*h,cy-radius-.129*h),navReadouts=this.getReadouts(),hasNavCourse=Number.isFinite(navReadouts.course),courseDisplay=hasNavCourse?(navReadouts.course%360+360)%360:null,hasAutopilotHeading=Number.isFinite(navReadouts.autopilotHeading),autopilotHeadingDisplay=hasAutopilotHeading?(navReadouts.autopilotHeading%360+360)%360:null,projectHsi=point=>{const right=Number(point?.rightNm),forward=Number(point?.forwardNm);return Number.isFinite(right)&&Number.isFinite(forward)?{x:cx+right/rangeNm*radius,y:cy-forward/rangeNm*radius}:null};for(let deg=0;deg<360;deg+=10){const relRad=(deg-heading)*Math.PI/180,dotX=cx+Math.sin(relRad)*radius,dotY=cy-Math.cos(relRad)*radius,dotR=deg%30==0?Math.max(1.8,.0038*h):Math.max(1.2,.0026*h),hasLabel=deg%30==0&&!("L2"===declutterLevel&&!(deg%90==0));if(hasLabel||(ctx.fillStyle=color,ctx.beginPath(),ctx.arc(dotX,dotY,dotR,0,2*Math.PI),ctx.fill()),hasLabel){const label=0===deg?"N":90===deg?"E":180===deg?"S":270===deg?"W":String(Math.round(deg/10));ctx.fillStyle=color,ctx.font=`bold ${navTextPx}px monospace`,ctx.textAlign="center",ctx.textBaseline="middle",ctx.fillText(label,dotX,dotY)}}if("OFF"===declutterLevel){ctx.fillStyle=color,ctx.font=`bold ${navTextPx}px monospace`,ctx.textAlign="left",ctx.textBaseline="top";const kias=Number(window.geofs?.animation?.values?.kias)||0,topReadoutY=headingBoxY,rowStepY=.052*h,leftReadoutX=contentX+.025*contentW,rightReadoutX=contentX+.725*contentW;ctx.fillText(`GND ${Math.round(1.05*kias)}`,leftReadoutX,topReadoutY),ctx.fillText(`TAS ${Math.round(1.15*kias)}`,leftReadoutX,topReadoutY+rowStepY);const dmeText=Number.isFinite(navReadouts.dme)?String(navReadouts.dme):"--",navaidText=navReadouts.navaidLabel||"";ctx.fillText(`DME ${dmeText}`,rightReadoutX,topReadoutY),navaidText&&ctx.fillText(navaidText,rightReadoutX,topReadoutY+rowStepY),ctx.textBaseline="middle"}const headingDisplay=(value=>{const deg=Number(value);return Number.isFinite(deg)?(Math.round(deg)%360+360)%360:0})(window.geofs?.animation?.values?.heading360??0);if(hasNavCourse){const getValue=window.geofs?.animation?.getValue?.bind(window.geofs?.animation),navCourseDeviation=getValue?getValue("NAVCourseDeviation")??0:window.geofs?.animation?.values?.NAVCourseDeviation??0,courseOffsetPx=HelperModule.clampValue(5*navCourseDeviation,-100,100)*(w/512),courseRelRad=(courseDisplay-heading)*Math.PI/180,dirX=Math.sin(courseRelRad),dirY=-Math.cos(courseRelRad),leftX=dirY,leftY=-dirX,signedOffset=-courseOffsetPx,lineCenterX=cx+leftX*signedOffset,lineCenterY=cy+leftY*signedOffset,offsetAbs=Math.abs(signedOffset),lineInset=Math.max(.016*h,6),lineRadius=Math.max(8,radius-lineInset),clampedOffsetAbs=Math.min(offsetAbs,Math.max(0,lineRadius-2)),halfLen=Math.sqrt(Math.max(0,lineRadius*lineRadius-clampedOffsetAbs*clampedOffsetAbs));ctx.strokeStyle=color,ctx.lineWidth=2,ctx.beginPath(),ctx.moveTo(lineCenterX-dirX*halfLen,lineCenterY-dirY*halfLen),ctx.lineTo(lineCenterX+dirX*halfLen,lineCenterY+dirY*halfLen),ctx.stroke();const arrowTipX=lineCenterX+dirX*halfLen,arrowTipY=lineCenterY+dirY*halfLen,arrowLen=Math.max(.028*h,10),arrowHalfW=Math.max(.013*h,5),arrowBaseX=arrowTipX-dirX*arrowLen,arrowBaseY=arrowTipY-dirY*arrowLen;ctx.beginPath(),ctx.moveTo(arrowTipX,arrowTipY),ctx.lineTo(arrowBaseX+leftX*arrowHalfW,arrowBaseY+leftY*arrowHalfW),ctx.lineTo(arrowBaseX-leftX*arrowHalfW,arrowBaseY-leftY*arrowHalfW),ctx.closePath(),ctx.fillStyle=color,ctx.fill()}ctx.save(),ctx.beginPath(),ctx.arc(cx,cy,radius,0,2*Math.PI),ctx.clip();const waypointPoints=[];for(const wp of scene?.waypoints??[]){const p=projectHsi(wp);p&&waypointPoints.push({...p,wp:wp})}const projectGeoToHsi=(lat,lon)=>{const ownship=scene?.ownship;if(!ownship||!Number.isFinite(Number(lat))||!Number.isFinite(Number(lon)))return null;const relNm=this.mapModule.toRelativeNm(ownship,Number(lat),Number(lon)),framePoint=this.mapModule.toHeadingFrame(relNm,ownship.heading);return projectHsi(framePoint)},sortedAreas=[...dataCartridgeScene?.areas??[]].sort((a,b)=>Number(a?.order??0)-Number(b?.order??0));for(const area of sortedAreas){const style=this.getAreaStyle(area);if("CIRCLE"===String(area?.variant).toUpperCase()){const center=Array.isArray(area?.center)?area.center:null,centerPt=center?projectGeoToHsi(center[0],center[1]):null,radiusMeters=Number(area?.radius);if(!centerPt||!Number.isFinite(radiusMeters)||radiusMeters<=0)continue;const radiusPx=radiusMeters/1852/rangeNm*radius;ctx.fillStyle=style.fillColor,ctx.globalAlpha=Number.isFinite(style.fillOpacity)?style.fillOpacity:.12,ctx.beginPath(),ctx.arc(centerPt.x,centerPt.y,radiusPx,0,2*Math.PI),ctx.fill(),ctx.globalAlpha=1,ctx.strokeStyle=style.color,ctx.lineWidth=1.4,ctx.stroke();continue}drawCartridgeAreaPath((Array.isArray(area?.points)?area.points:[]).map(pt=>projectGeoToHsi(pt?.[0],pt?.[1])).filter(Boolean),style)}if(waypointPoints.length>=2){ctx.strokeStyle="#3da2ff",ctx.lineWidth=1.4,ctx.beginPath();for(let i=0;i(tab?.y??0)+(tab?.h??0))):.11*h,bottomStripTop=bottomTabs.length?Math.min(...bottomTabs.map(tab=>tab?.y??h)):.89*h,mapLeft=0,mapRight=w,mapTop=topStripBottom+.004*h,mapW=mapRight-mapLeft,mapH=bottomStripTop-.004*h-mapTop,mapViewFrame=this.mapModule.getMapViewFrame(scene,selectedTraffic),anchorX=mapLeft+.5*mapW,anchorY=mapTop+mapH*("center"===mapViewFrame?.anchor?.5:2/3),pxPerNm=Math.max(1e-4,(anchorY-mapTop)/rangeNm),mapUpHeadingDeg=Number(mapViewFrame?.upHeadingDeg)||0,drawNorthArrow=()=>{const arrowMargin=.185*w,pivotX=mapRight-arrowMargin,pivotY=arrowMargin,shaftHalfLen=Math.max(.08*h,32),headLen=Math.max(.028*h,12),headHalfW=Math.max(.02*w,8),northRelRad=(0-mapUpHeadingDeg)*Math.PI/180,dirX=Math.sin(northRelRad),dirY=-Math.cos(northRelRad),leftX=-dirY,leftY=dirX,textBgR=Math.max(.018*h,9),shaftGap=textBgR+2,tipX=pivotX+dirX*shaftHalfLen,tipY=pivotY+dirY*shaftHalfLen,tailX=pivotX-dirX*shaftHalfLen,tailY=pivotY-dirY*shaftHalfLen,baseX=tipX-dirX*headLen,baseY=tipY-dirY*headLen,nearTipGapX=pivotX+dirX*shaftGap,nearTipGapY=pivotY+dirY*shaftGap,nearTailGapX=pivotX-dirX*shaftGap,nearTailGapY=pivotY-dirY*shaftGap;ctx.strokeStyle=color,ctx.lineWidth=2,ctx.beginPath(),ctx.moveTo(nearTipGapX,nearTipGapY),ctx.lineTo(tipX,tipY),ctx.moveTo(tailX,tailY),ctx.lineTo(nearTailGapX,nearTailGapY),ctx.stroke(),ctx.beginPath(),ctx.moveTo(tipX,tipY),ctx.lineTo(baseX+leftX*headHalfW,baseY+leftY*headHalfW),ctx.lineTo(baseX-leftX*headHalfW,baseY-leftY*headHalfW),ctx.closePath(),ctx.fillStyle=color,ctx.fill();const textX=pivotX,textY=pivotY;ctx.fillStyle="#000000",ctx.beginPath(),ctx.arc(textX,textY,textBgR,0,2*Math.PI),ctx.fill(),ctx.strokeStyle=color,ctx.lineWidth=1.5,ctx.beginPath(),ctx.arc(textX,textY,textBgR,0,2*Math.PI),ctx.stroke(),ctx.fillStyle=color,ctx.font=`bold ${Math.round(.032*h)}px monospace`,ctx.textAlign="center",ctx.textBaseline="middle",ctx.fillText("N",textX,textY)},projectMap=(point,latKey="lat",lonKey="lon")=>{const projected=this.mapModule.projectToMapViewFrame(mapViewFrame,point?.[latKey],point?.[lonKey]),right=Number(projected?.rightNm),forward=Number(projected?.forwardNm);return Number.isFinite(right)&&Number.isFinite(forward)?{x:anchorX+right*pxPerNm,y:anchorY-forward*pxPerNm}:null};ctx.save(),ctx.beginPath(),ctx.rect(mapLeft,mapTop,mapW,mapH),ctx.clip();const waypointPoints=[];for(const wp of scene?.waypoints??[]){const p=projectMap(wp,"lat","lon");p&&waypointPoints.push({...p,wp:wp})}const sortedAreas=[...dataCartridgeScene?.areas??[]].sort((a,b)=>Number(a?.order??0)-Number(b?.order??0));for(const area of sortedAreas){const style=this.getAreaStyle(area);if("CIRCLE"===String(area?.variant).toUpperCase()){const center=Array.isArray(area?.center)?area.center:null,centerPt=center?projectMap({lat:center[0],lon:center[1]},"lat","lon"):null,radiusMeters=Number(area?.radius);if(!centerPt||!Number.isFinite(radiusMeters)||radiusMeters<=0)continue;const radiusPx=radiusMeters/1852*pxPerNm;ctx.fillStyle=style.fillColor,ctx.globalAlpha=Number.isFinite(style.fillOpacity)?style.fillOpacity:.12,ctx.beginPath(),ctx.arc(centerPt.x,centerPt.y,radiusPx,0,2*Math.PI),ctx.fill(),ctx.globalAlpha=1,ctx.strokeStyle=style.color,ctx.lineWidth=1.4,ctx.stroke();continue}drawCartridgeAreaPath((Array.isArray(area?.points)?area.points:[]).map(pt=>projectMap({lat:pt?.[0],lon:pt?.[1]},"lat","lon")).filter(Boolean),style)}if(waypointPoints.length>=2){ctx.strokeStyle="#3da2ff",ctx.lineWidth=1.5,ctx.beginPath();for(let i=0;ithis.isTrafficContactVisible(user?.callsign??user?.cs))}getNavaidTypeLabel(navUnit=this.getCurrentNavUnit()){if("ILS"===navUnit?.navaid?.type){return`ILS ${navUnit?.navaid?.icao??""}`.trim()}if("VORTAC"===navUnit?.navaid?.type){return`VOR ${navUnit?.navaid?.ident??navUnit?.navaid?.icao??""}`.trim()}const type=String(navUnit?.navaid?.type??"").trim();let ident=navUnit?.navaid?.ident;ident||(ident=navUnit?.navaid?.icao??"");return`${type} ${String(ident??"").trim()}`.trim()}getReadouts(navUnit=this.getCurrentNavUnit()){return{navUnit:navUnit,dme:this.getDmeValue(navUnit),bearing:this.getBearingDeg(navUnit),course:this.getCourseDeg(navUnit),timeToSignal:this.getTimeToSignal(navUnit),navaidLabel:this.getNavaidTypeLabel(navUnit),autopilotHeading:this.getAutopilotHeadingDeg()}}stepSelectedFlightPlanWaypoint(step=1){const direction=Number(step)>=0?1:-1,flightPlan=window.geofs?.flightPlan,waypointArray=flightPlan?.waypointArray;if(!Array.isArray(waypointArray)||0===waypointArray.length)return!1;if("function"!=typeof flightPlan?.selectWaypoint)return!1;const currentIndex=waypointArray.findIndex(waypoint=>!0===waypoint?.selected),nextIndex=((currentIndex>=0?currentIndex:direction>0?-1:0)+direction+waypointArray.length)%waypointArray.length;return flightPlan.selectWaypoint(nextIndex),!0}}class MapModule{static RANGE_OPTIONS_NM=[1,2.5,5,10,20,40,80,160];static MARK_STATES=["","FRIEND","CIVILIAN","UNKNOWN","FOO"];static SHOW_STATES=["ALL","UNM","FRIEND","CIVILIAN","UNKNOWN","FOO"];static VIEW_MODES=["A/C F/W","A/C CNT","A/C N","TGT","TGT N"];static TRAFFIC_STALE_TIMEOUT_MS=1e4;constructor(navModule=null){this.navModule=navModule,this.selectedTrafficUid=null,this.trafficSelectionCleared=!1,this.trafficMarksByUid=Object.create(null),this.showFilter="ALL",this.trafficContactsByUid=Object.create(null)}setNavModule(navModule){return this.navModule=navModule,this}getRangeNm(){const raw=Number(OptionModule.getOptionValue("NAV","RANGE",40));return this.normalizeRangeNm(raw)}normalizeRangeNm(rawRange){return Number(rawRange)}setRangeNm(range){return OptionModule.setOption("NAV","RANGE",String(range)),range}stepRange(step=0){const direction=Number(step)>=0?1:-1,current=this.getRangeNm(),options=MapModule.RANGE_OPTIONS_NM,idx=Math.max(0,options.indexOf(current)),nextIndex=HelperModule.clampValue(idx+direction,0,options.length-1);return this.setRangeNm(options[nextIndex])}isRadarEnabled(){return"ON"===OptionModule.getOptionValue("RDR","RADAR","OFF")}getViewMode(){return OptionModule.getOptionValue("NAV","VIEW","A/C F/W")}setViewMode(mode){return OptionModule.setOption("NAV","VIEW",mode),mode}cycleViewMode(){const modes=MapModule.VIEW_MODES,current=this.getViewMode(),idx=Math.max(0,modes.indexOf(current)),next=modes[(idx+1)%modes.length];return this.setViewMode(next)}getMapViewFrame(scene,selectedTraffic=null){const mode=this.getViewMode(),ownship=scene?.ownship,ownHeading=Number(ownship?.heading)||0,selectedLat=Number(selectedTraffic?.lat),selectedLon=Number(selectedTraffic?.lon),hasSelectedPosition=Number.isFinite(selectedLat)&&Number.isFinite(selectedLon);let centerLat=Number(ownship?.lat),centerLon=Number(ownship?.lon),anchor="forward",upHeadingDeg=ownHeading;return"A/C CNT"===mode?anchor="center":"A/C N"===mode?(anchor="center",upHeadingDeg=0):"TGT"===mode?(anchor="center",hasSelectedPosition&&(centerLat=selectedLat,centerLon=selectedLon)):"TGT N"===mode&&(anchor="center",upHeadingDeg=0,hasSelectedPosition&&(centerLat=selectedLat,centerLon=selectedLon)),Number.isFinite(centerLat)&&Number.isFinite(centerLon)?{mode:mode,anchor:anchor,centerLat:centerLat,centerLon:centerLon,upHeadingDeg:upHeadingDeg}:null}projectToMapViewFrame(frame,lat,lon){if(!frame)return null;const targetLat=Number(lat),targetLon=Number(lon);if(!Number.isFinite(targetLat)||!Number.isFinite(targetLon))return null;const relativeNm=this.toRelativeNm({lat:frame.centerLat,lon:frame.centerLon},targetLat,targetLon);return relativeNm?this.toHeadingFrame(relativeNm,frame.upHeadingDeg):null}getOwnshipState(){const lla=window.geofs?.aircraft?.instance?.llaLocation;if(!Array.isArray(lla)||!Number.isFinite(lla[0])||!Number.isFinite(lla[1]))return null;const heading=Number(window.geofs?.animation?.values?.heading);return{lat:Number(lla[0])||0,lon:Number(lla[1])||0,alt:Number(lla[2])||0,heading:Number.isFinite(heading)?heading:0}}normalizeHeadingDeg(value){const deg=Number(value);return Number.isFinite(deg)?(Math.round(deg)%360+360)%360:null}toRelativeNm(ownship,targetLat,targetLon){if(!ownship||!Number.isFinite(targetLat)||!Number.isFinite(targetLon))return null;const latAvgRad=.5*(ownship.lat+targetLat)*(Math.PI/180);return{northNm:110540*(targetLat-ownship.lat)/1852,eastNm:111320*(targetLon-ownship.lon)*Math.cos(latAvgRad)/1852}}toHeadingFrame(relativeNm,headingDeg){if(!relativeNm)return null;const hdgRad=(Number(headingDeg)||0)*(Math.PI/180),sinH=Math.sin(hdgRad),cosH=Math.cos(hdgRad);return{forwardNm:relativeNm.northNm*cosH+relativeNm.eastNm*sinH,rightNm:-relativeNm.northNm*sinH+relativeNm.eastNm*cosH}}getCombatContacts(){try{const addon="undefined"!=typeof BasePlugin?BasePlugin.getActiveAddon():null;return addon?.combat?.aaCombat?.getNpcContacts?.()??[]}catch(error){return[]}}getTrafficContacts(ownship){if(!ownship)return[];const users=Object.values(window.multiplayer?.visibleUsers??{}),nowMs=Date.now();for(const user of users){if(this.navModule&&!this.navModule.isTrafficContactVisible(user?.callsign??user?.cs))continue;const co=user?.lastUpdate?.co;if(!Array.isArray(co)||!Number.isFinite(co[0])||!Number.isFinite(co[1]))continue;const uid=String(user?.id??user?.uid??"").trim();uid&&(this.trafficContactsByUid[uid]={uid:uid,aircraftName:String(user?.aircraftName??"").trim(),callsign:String(user?.callsign??user?.cs??"").trim(),lat:Number(co[0])||0,lon:Number(co[1])||0,alt:Number(co[2])||0,speedKts:Number.isFinite(Number(user?.lastUpdate?.st?.as))?Math.round(Number(user.lastUpdate.st.as)):null,headingDeg:this.normalizeHeadingDeg(co[3]),trackDeg:this.normalizeHeadingDeg(co[3]),lastSeenMs:nowMs})}const npcContacts=this.getCombatContacts(),npcUids=new Set;for(const npc of npcContacts){const uid=String(npc.id);npcUids.add(uid),this.navModule&&!this.navModule.isTrafficContactVisible(npc.callsign)||(this.trafficContactsByUid[uid]={uid:uid,isNpc:!0,aircraftName:"BANDIT",callsign:String(npc.callsign??"BANDIT"),lat:npc.lat,lon:npc.lon,alt:npc.alt,speedKts:Number.isFinite(npc.speedKts)?npc.speedKts:null,headingDeg:this.normalizeHeadingDeg(npc.headingDeg),trackDeg:this.normalizeHeadingDeg(npc.headingDeg),lastSeenMs:nowMs})}for(const uid of Object.keys(this.trafficContactsByUid))this.trafficContactsByUid[uid]?.isNpc&&!npcUids.has(uid)&&delete this.trafficContactsByUid[uid];const result=[];for(const uid of Object.keys(this.trafficContactsByUid)){const cached=this.trafficContactsByUid[uid];if(!cached)continue;const ageMs=nowMs-Number(cached.lastSeenMs||0);if(!Number.isFinite(ageMs)||ageMs>MapModule.TRAFFIC_STALE_TIMEOUT_MS){delete this.trafficContactsByUid[uid],String(this.selectedTrafficUid??"")===String(uid)&&(this.selectedTrafficUid=null,this.trafficSelectionCleared=!0);continue}const relNm=this.toRelativeNm(ownship,Number(cached.lat),Number(cached.lon)),frameNm=this.toHeadingFrame(relNm,ownship.heading);frameNm&&result.push({uid:cached.uid,aircraftName:cached.aircraftName,callsign:cached.callsign,lat:cached.lat,lon:cached.lon,alt:cached.alt,altFeet:Number.isFinite(Number(cached.alt))?Math.round(3.28084*Number(cached.alt)):null,speedKts:cached.speedKts,isNpc:!!cached.isNpc,headingDeg:cached.headingDeg,trackDeg:cached.trackDeg,...frameNm})}return result.sort((a,b)=>{const ta=this.getTrafficSortToken(a),tb=this.getTrafficSortToken(b);return ta.localeCompare(tb)}),result}getTrafficKey(contact){return String(contact?.uid||contact?.callsign||`${contact?.lat??""}:${contact?.lon??""}`)}getContactNumber(contact){const aircraftId=String(contact?.id??contact?.uid??"").trim();if(!aircraftId)return 0;const numericPart=aircraftId.replace(/\D/g,"");if(!numericPart)return 0;const lastTwo=numericPart.slice(-2);return Number(lastTwo)||0}getTrafficSortToken(contact){const number=this.getContactNumber(contact);return`${String(number).padStart(3,"0")}:${this.getTrafficKey(contact)}`}getSelectedTrafficUid(contacts=[]){const list=Array.isArray(contacts)?contacts:[];if(!list.length)return this.selectedTrafficUid=null,null;return this.selectedTrafficUid&&list.some(c=>String(c?.uid)===String(this.selectedTrafficUid))?this.selectedTrafficUid:this.trafficSelectionCleared?null:(this.selectedTrafficUid=list[0]?.uid?String(list[0].uid):null,this.selectedTrafficUid)}getTrafficMark(uid){const key=String(uid??"");return key&&this.trafficMarksByUid[key]||""}setTrafficMark(uid,markState){const key=String(uid??"");if(!key)return"";const normalized=markState||"";return normalized?(this.trafficMarksByUid[key]=normalized,normalized):(delete this.trafficMarksByUid[key],"")}cycleSelectedTrafficMark(){const scene=this.getSceneData(),contacts=this.getTrafficInRange(this.getFilteredTraffic(scene?.traffic??[]),scene?.rangeNm),uid=this.getSelectedTrafficUid(contacts);if(!uid)return"";const current=this.getTrafficMark(uid),states=MapModule.MARK_STATES,idx=Math.max(0,states.indexOf(current)),next=states[(idx+1)%states.length]??"";return this.setTrafficMark(uid,next)}getSelectedTrafficMark(){const scene=this.getSceneData(),contacts=this.getTrafficInRange(this.getFilteredTraffic(scene?.traffic??[]),scene?.rangeNm),uid=this.getSelectedTrafficUid(contacts);return uid?this.getTrafficMark(uid):""}getTrafficColor(contact){const mark=this.getTrafficMark(contact?.uid);return"FRIEND"===mark?"#3da2ff":"CIVILIAN"===mark?"#33ff66":"UNKNOWN"===mark?"#ffff33":"FOO"===mark?"#ff3333":"#ffffff"}getShowFilter(){return this.showFilter||"ALL"}setShowFilter(value){return this.showFilter=value||"ALL",this.showFilter}cycleShowFilter(){const states=MapModule.SHOW_STATES,current=this.getShowFilter(),idx=Math.max(0,states.indexOf(current)),next=states[(idx+1)%states.length]??"ALL";return this.setShowFilter(next)}matchesShowFilter(contact,includeSelected=!0){const uid=String(contact?.uid??"");if(includeSelected&&uid&&uid===String(this.selectedTrafficUid??""))return!0;const filter=this.getShowFilter();return"ALL"===filter||("UNM"===filter?""===this.getTrafficMark(uid):this.getTrafficMark(uid)===filter)}getFilteredTraffic(contacts=[],includeSelected=!0){return(Array.isArray(contacts)?contacts:[]).filter(contact=>this.matchesShowFilter(contact,includeSelected))}getTrafficInRange(contacts=[],rangeNm=this.getRangeNm()){const list=Array.isArray(contacts)?contacts:[],maxRange=Math.max(.1,Number(rangeNm)||0);return list.filter(contact=>{const forward=Number(contact?.forwardNm),right=Number(contact?.rightNm);return!(!Number.isFinite(forward)||!Number.isFinite(right))&&Math.hypot(forward,right)<=maxRange})}stepSelectedTraffic(step=1){const direction=Number(step)>=0?1:-1,scene=this.getSceneData(),contacts=this.getTrafficInRange(this.getFilteredTraffic(scene?.traffic??[]),scene?.rangeNm);if(!contacts.length)return this.selectedTrafficUid=null,this.trafficSelectionCleared=!1,null;this.trafficSelectionCleared=!1;const currentUid=this.getSelectedTrafficUid(contacts),nextIndex=(Math.max(0,contacts.findIndex(c=>String(c?.uid)===String(currentUid)))+direction+contacts.length)%contacts.length;return this.selectedTrafficUid=String(contacts[nextIndex]?.uid??""),this.selectedTrafficUid||null}clearSelectedTraffic(){return this.selectedTrafficUid=null,this.trafficSelectionCleared=!0,null}getFlightPlanWaypoints(ownship){if(!ownship)return[];const waypoints=window.geofs?.flightPlan?.waypointArray;if(!Array.isArray(waypoints))return[];const result=[];for(let i=0;iString(a?.uid??"").trim()).filter(Boolean))];if(!uids.length)return;if(!currentUid||!uids.includes(currentUid))return void(mapModule.selectedTrafficUid=uids[0]);const newIndex=(uids.indexOf(currentUid)+direction+uids.length)%uids.length;mapModule.selectedTrafficUid=uids[newIndex]}registerMfdPages(mfdModule){const radarModule=this;return mfdModule.registerPage({title:"RDR",leftButtons:[{key:"RADAR",label:"RDR",states:["OFF","ON"],stateIndex:0,onClick:({nextState:nextState})=>{"ON"===String(nextState??"").toUpperCase()&&(window.addonRuntime=window.addonRuntime||{},window.addonRuntime.navRdrRuntime=window.addonRuntime.navRdrRuntime||{bootStartMs:0},window.addonRuntime.navRdrRuntime.bootStartMs=Date.now())}},{key:"FOO",label:"FOO",states:["SH","HD"],stateIndex:0,managedExternally:!0,onClick:()=>{const current=OptionModule.getOptionValue("RDR","FOO","SH");OptionModule.setOption("RDR","FOO","SH"===current?"HD":"SH")}},{key:"LOCK",label:"LOCK",states:[""],stateIndex:0,onClick:()=>{const mapModule=radarModule.navModule?.mapModule;if(!mapModule)return;const selectedUid=String(mapModule.selectedTrafficUid??"").trim();selectedUid&&(String(radarModule.hardLockedUid??"")!==selectedUid?radarModule.hardLockedUid=selectedUid:radarModule.hardLockedUid=null)}},{key:"SCAN",label:"SCN",states:["6B","3B"],stateIndex:0,managedExternally:!0,onClick:()=>{const current=OptionModule.getOptionValue("RDR","SCAN","6B");OptionModule.setOption("RDR","SCAN","6B"===current?"3B":"6B")}},{key:"FIRE",label:"FIRE",states:[""],stateIndex:0,onClick:()=>{const mode=OptionModule.getOption("WPN","MODE","NAV"),modeLoadout=radarModule.weaponModule?.getModeLoadout(mode);radarModule.weaponModule&&modeLoadout&&radarModule.weaponModule.fireSelectedWeapon(mode,modeLoadout)},show:()=>1===window.controls?.gear?.position&&window.geofs?.animation?.values?.haglFeet>50&&"OFF"!==OptionModule.getOption("WPN","MASTER","OFF")&&"A/A"===OptionModule.getOption("WPN","MODE","NAV")}],rightButtons:[{key:"RANGE",label:"↑",states:["5","10","20","40","80","160"],values:[5,10,20,40,80,160],stateIndex:2,managedExternally:!0,minimal:!0,combinedGroupLabel:"RNG",onClick:()=>{const currentValues=[5,10,20,40,80,160],currentVal=Number(OptionModule.getOptionValue("RDR","RANGE",20)),currentIndex=currentValues.indexOf(currentVal),newIndex=Math.min(currentValues.length-1,currentIndex+1);OptionModule.setOption("RDR","RANGE",String(currentValues[newIndex]))}},{key:"RANGE",label:"↓",states:["5","10","20","40","80","160"],values:[5,10,20,40,80,160],stateIndex:2,managedExternally:!0,minimal:!0,combinedGroupLabel:"RNG",onClick:()=>{const currentValues=[5,10,20,40,80,160],currentVal=Number(OptionModule.getOptionValue("RDR","RANGE",20)),currentIndex=currentValues.indexOf(currentVal),newIndex=Math.max(0,currentIndex-1);OptionModule.setOption("RDR","RANGE",String(currentValues[newIndex]))}},{key:"ACSEL",label:"→",states:["A/C"],values:["A/C"],stateIndex:0,managedExternally:!0,minimal:!0,combinedGroupLabel:"AC",onClick:()=>{radarModule.stepSelectedTrafficInCone(1)}},{key:"ACSEL",label:"←",states:["A/C"],values:["A/C"],stateIndex:0,managedExternally:!0,minimal:!0,combinedGroupLabel:"AC",onClick:()=>{radarModule.stepSelectedTrafficInCone(-1)}},{key:"CLEAR",label:"CLR",states:[""],stateIndex:0,managedExternally:!0,onClick:()=>{radarModule.navModule?.mapModule?.clearSelectedTraffic(),radarModule.hardLockedUid=null}}],lines:[],render:(renderer,renderContext)=>{const ctx=renderContext?.ctx??renderer?.canvasAPI?.context,w=renderContext?.w??renderer?.canvasAPI?.canvas?.width??512,h=renderContext?.h??renderer?.canvasAPI?.canvas?.height??512,color=renderContext?.color??"#00ff66";if(!ctx)return;window.addonRuntime=window.addonRuntime||{},window.addonRuntime.navRdrRuntime=window.addonRuntime.navRdrRuntime||{bootStartMs:0};const engOn=Boolean(window.geofs?.animation?.values?.enginesOn);engOn?window.addonRuntime.navRdrRuntime.bootStartMs||(window.addonRuntime.navRdrRuntime.bootStartMs=Date.now()):window.addonRuntime.navRdrRuntime.bootStartMs=0;const elapsedMs=engOn?Date.now()-window.addonRuntime.navRdrRuntime.bootStartMs:0,bootReady=engOn&&elapsedMs>=5e3,contentX=.14*w,contentY=.1*h,contentW=.74*w,contentH=.8*h,rangeNmRaw=Number(OptionModule.getOptionValue("RDR","RANGE",20)),rangeNm=Number.isFinite(rangeNmRaw)&&rangeNmRaw>0?rangeNmRaw:20,radarEnabled="ON"===OptionModule.getOptionValue("RDR","RADAR","OFF"),fooMode=OptionModule.getOptionValue("RDR","FOO","SH"),scanMode=OptionModule.getOptionValue("RDR","SCAN","6B"),weaponMasterState=String(OptionModule.getOptionValue("WPN","MASTER","OFF")).toUpperCase(),weaponMode=String(OptionModule.getOptionValue("WPN","MODE","NAV")).toUpperCase(),modeLoadout=radarModule.weaponModule?.getModeLoadout(weaponMode),selectedWeaponLabel=modeLoadout?radarModule.weaponModule.getSelectedLoadDisplay(weaponMode,modeLoadout):"N/A",selectedWeaponEffectiveness=modeLoadout?radarModule.weaponModule.getSelectedWeaponEffectiveness(weaponMode,modeLoadout):null;if(ctx.save(),ctx.setTransform(1,0,0,1,0,0),ctx.fillStyle="#000000",ctx.fillRect(contentX,contentY,contentW,contentH),!engOn)return ctx.fillStyle=color,ctx.textAlign="center",ctx.textBaseline="middle",ctx.font=`bold ${Math.round(.046*h)}px monospace`,ctx.fillText("RDR OFF",contentX+.5*contentW,contentY+.5*contentH),void ctx.restore();if(!bootReady)return ctx.fillStyle=color,ctx.textAlign="center",ctx.textBaseline="middle",ctx.font=`bold ${Math.round(.046*h)}px monospace`,ctx.fillText("RADAR BIT TEST...",contentX+.5*contentW,contentY+.5*contentH),void ctx.restore();if(!radarEnabled)return ctx.fillStyle="#ffff33",ctx.textAlign="center",ctx.textBaseline="middle",ctx.font=`bold ${Math.round(.075*h)}px monospace`,ctx.fillText("Radar OFF",contentX+.5*contentW,contentY+.5*contentH),void ctx.restore();const navModule=radarModule.navModule,mapModule=navModule?.mapModule,scene=mapModule?.getSceneData?.(),ownship=scene?.ownship??null,trafficContactsAll=Array.isArray(scene?.traffic)?scene.traffic:[],trafficContacts="HD"===fooMode?trafficContactsAll.filter(contact=>"Foo"!==contact.callsign):trafficContactsAll,myHeading=Number(ownship?.heading??window.geofs?.animation?.values?.heading)||0,myPitch=-Number(window.geofs?.animation?.values?.atilt),myAltMeters=Number(ownship?.alt??window.geofs?.aircraft?.instance?.llaLocation?.[2])||0,margin=.02*contentW,displayLeft=contentX+margin,displayRight=contentX+contentW-margin,displayTop=contentY+.06*contentH,displayBottom=contentY+.95*contentH,displayWidth=displayRight-displayLeft,displayHeight=displayBottom-displayTop,sweepMs="3B"===scanMode?500:1e3,sweepNow=Date.now();radarModule.lastSweepUpdateTime||(radarModule.lastSweepUpdateTime=sweepNow);const deltaMs=sweepNow-radarModule.lastSweepUpdateTime;radarModule.lastSweepUpdateTime=sweepNow,radarModule.sweepAngle+=radarModule.sweepDirection*(deltaMs*(100/sweepMs)),radarModule.sweepAngle>=100?(radarModule.sweepAngle=100,radarModule.sweepDirection=-1):radarModule.sweepAngle<=0&&(radarModule.sweepAngle=0,radarModule.sweepDirection=1);const sweepX=displayLeft+radarModule.sweepAngle/100*displayWidth,verticalNow=Date.now();radarModule.lastVerticalScanUpdateTime||(radarModule.lastVerticalScanUpdateTime=verticalNow);const verticalDeltaMs=verticalNow-radarModule.lastVerticalScanUpdateTime;radarModule.lastVerticalScanUpdateTime=verticalNow,radarModule.verticalScanPos+=radarModule.verticalScanDirection*(verticalDeltaMs*(100/sweepMs)),radarModule.verticalScanPos>=100?(radarModule.verticalScanPos=100,radarModule.verticalScanDirection=-1):radarModule.verticalScanPos<=0&&(radarModule.verticalScanPos=0,radarModule.verticalScanDirection=1);const selectedTrafficUid=mapModule?.selectedTrafficUid??null,CONE_HALF_ANGLE_H="3B"===scanMode?15:30,CONE_HALF_ANGLE_V="3B"===scanMode?15:30,currentTime=Date.now(),contactUpdateMs="3B"===scanMode?500:1e3,shouldUpdate=currentTime-radarModule.lastContactUpdateTime>=contactUpdateMs;let aircraftInCone=radarModule.cachedAircraftInCone;if(shouldUpdate&&ownship){radarModule.lastContactUpdateTime=currentTime,aircraftInCone=[];for(const contact of trafficContacts){const uid=contact?.uid;if(!uid)continue;if("function"==typeof mapModule?.isContactAllowedByShowFilter&&!mapModule.isContactAllowedByShowFilter(contact))continue;const forwardNm=Number(contact?.forwardNm),rightNm=Number(contact?.rightNm);if(!Number.isFinite(forwardNm)||!Number.isFinite(rightNm))continue;const distanceNm=Math.sqrt(forwardNm*forwardNm+rightNm*rightNm);if(!Number.isFinite(distanceNm)||distanceNm<=0||distanceNm>=rangeNm)continue;const relativeBearing=180*Math.atan2(rightNm,forwardNm)/Math.PI;if(Math.abs(relativeBearing)>CONE_HALF_ANGLE_H)continue;const horizontalDistM=Math.max(1,1852*distanceNm),targetAltMeters=Number(contact?.alt),altDiff=(Number.isFinite(targetAltMeters)?targetAltMeters:myAltMeters)-myAltMeters,relativeElevation=180*Math.atan2(altDiff,horizontalDistM)/Math.PI-myPitch;if(Math.abs(relativeElevation)>CONE_HALF_ANGLE_V)continue;const x=displayLeft+(relativeBearing+CONE_HALF_ANGLE_H)/(2*CONE_HALF_ANGLE_H)*displayWidth,y=displayBottom-distanceNm/rangeNm*displayHeight,track=Number(contact?.trackDeg??contact?.headingDeg??0);aircraftInCone.push({x:x,y:y,uid:uid,distanceNm:distanceNm,relativeBearing:relativeBearing,relativeElevation:relativeElevation,track:track,altKft:Number.isFinite(Number(contact?.altFeet))?Math.round(Number(contact.altFeet)/1e3):Math.round(3.28084*(Number(contact?.alt)||0)/1e3),contact:contact})}radarModule.cachedAircraftInCone=aircraftInCone}if(radarModule.visibleAircraftInCone=aircraftInCone,radarModule.hardLockedUid){aircraftInCone.some(aircraft=>String(aircraft?.uid??"")===String(radarModule.hardLockedUid))||(radarModule.hardLockedUid=null)}const lockedAircraft=radarModule.hardLockedUid?aircraftInCone.find(aircraft=>String(aircraft.uid)===String(radarModule.hardLockedUid)):null;ctx.strokeStyle=color,ctx.lineWidth=2,ctx.strokeRect(displayLeft,displayTop,displayWidth,displayHeight);const statusY=displayTop-.03*h;if(ctx.fillStyle=color,ctx.font=`bold ${Math.round(.032*h)}px monospace`,ctx.textBaseline="middle",ctx.textAlign="left",ctx.fillText(`WPN ${weaponMode}`,displayLeft,statusY),ctx.textAlign="center",ctx.fillText(selectedWeaponLabel,displayLeft+.5*displayWidth,statusY),ctx.textAlign="right",ctx.fillText(`MASTER ${weaponMasterState}`,displayRight,statusY),selectedWeaponEffectiveness){const markerFractions=radarModule.weaponModule.getEffectivenessMarkerFractions(selectedWeaponEffectiveness),bracketHeight=displayHeight*(2/3),bracketTop=displayTop+.5*(displayHeight-bracketHeight),bracketBottom=bracketTop+bracketHeight,bracketX=displayRight-.02*w,tickLen=.018*w;ctx.strokeStyle=color,ctx.lineWidth=2,ctx.beginPath(),ctx.moveTo(bracketX,bracketTop),ctx.lineTo(bracketX,bracketBottom),ctx.stroke();const markerYs=[bracketTop+markerFractions.engagementMax*bracketHeight,bracketTop+markerFractions.effectiveMax*bracketHeight,bracketTop+markerFractions.effectiveMin*bracketHeight,bracketTop+markerFractions.engagementMin*bracketHeight];for(const y of markerYs)ctx.beginPath(),ctx.moveTo(bracketX,y),ctx.lineTo(bracketX-tickLen,y),ctx.stroke();if(lockedAircraft){const lockedY=bracketTop+radarModule.weaponModule.getEffectivenessDistanceFraction(selectedWeaponEffectiveness,lockedAircraft.distanceNm)*bracketHeight;ctx.fillStyle=color,ctx.font=`bold ${Math.round(.046*h)}px monospace`,ctx.textAlign="right",ctx.textBaseline="middle",ctx.fillText(">",bracketX,lockedY),ctx.fillStyle=color}}"OFF"===weaponMasterState?(ctx.fillStyle="#ffff33",ctx.textAlign="center",ctx.textBaseline="middle",ctx.font=`bold ${Math.round(.032*h)}px monospace`,ctx.fillText("MASTER OFF",displayLeft+.5*displayWidth,displayTop+.5*displayHeight),ctx.fillStyle=color):"A/A"!==weaponMode&&(ctx.fillStyle="#ffff33",ctx.textAlign="center",ctx.textBaseline="middle",ctx.font=`bold ${Math.round(.032*h)}px monospace`,ctx.fillText("SELECT A/A MODE",displayLeft+.5*displayWidth,displayTop+.5*displayHeight),ctx.fillStyle=color),ctx.strokeStyle="#004422",ctx.lineWidth=1;for(let i=1;i<=3;i++){const y=displayBottom-displayHeight*(i/4);ctx.beginPath(),ctx.moveTo(displayLeft,y),ctx.lineTo(displayRight,y),ctx.stroke()}for(let i=1;i<=3;i++){const y=displayTop+displayHeight*i/4;ctx.beginPath(),ctx.moveTo(displayLeft,y),ctx.lineTo(displayLeft+20,y),ctx.stroke(),ctx.beginPath(),ctx.moveTo(displayRight,y),ctx.lineTo(displayRight-20,y),ctx.stroke()}const topBottomTickCount="3B"===scanMode?2:5;for(let i=1;i<=topBottomTickCount;i++){const x=displayLeft+displayWidth*i/(topBottomTickCount+1);ctx.beginPath(),ctx.moveTo(x,displayTop),ctx.lineTo(x,displayTop+20),ctx.stroke(),ctx.beginPath(),ctx.moveTo(x,displayBottom),ctx.lineTo(x,displayBottom-20),ctx.stroke()}ctx.strokeStyle=color,ctx.lineWidth=2,ctx.beginPath(),ctx.moveTo(sweepX,displayTop),ctx.lineTo(sweepX,displayBottom),ctx.stroke();const firstBarY=displayBottom-displayHeight*(1/4),thirdBarY=displayBottom-displayHeight*(3/4),scanTopY=Math.min(firstBarY,thirdBarY),fullScanSpan=Math.max(firstBarY,thirdBarY)-scanTopY,verticalScanSpan="3B"===scanMode?.5*fullScanSpan:fullScanSpan,verticalScanY=scanTopY+.5*(fullScanSpan-verticalScanSpan)+radarModule.verticalScanPos/100*verticalScanSpan;ctx.fillStyle=color,ctx.font=`bold ${Math.round(.035*h)}px monospace`,ctx.textAlign="center",ctx.textBaseline="middle",ctx.fillText("<",displayLeft+10,verticalScanY),radarModule.weaponModule?.isFireFlashVisible()&&(ctx.textAlign="center",ctx.textBaseline="middle",ctx.font=`bold ${Math.round(.12*h)}px monospace`,ctx.fillStyle="#ff0000",ctx.fillText(radarModule.weaponModule.getActionFlashLabel(),contentX+.5*contentW,.72*h),ctx.fillStyle=color);const drawTrafficContact=(x,y,aircraft)=>{const isSelected=String(aircraft.uid)===String(selectedTrafficUid),isHardLocked=String(aircraft.uid)===String(radarModule.hardLockedUid),baseColor=isHardLocked?"#ff0000":mapModule?.getTrafficColor(aircraft.contact)??"#ffffff",number=mapModule?.getContactNumber(aircraft.contact)??"?",glyph=String(number);ctx.fillStyle=baseColor,ctx.font=`bold ${Math.round(.032*h)}px monospace`,ctx.textAlign="center",ctx.textBaseline="middle",ctx.fillText(glyph,x,y);const numberHalfH=Math.max(.016*h,8),roofHalfW=Math.max(.022*w,10),roofY=y-numberHalfH-.007*h,legLen=Math.max(.022*h,10);ctx.strokeStyle=baseColor,ctx.lineWidth=2,ctx.beginPath(),ctx.moveTo(x-roofHalfW,roofY),ctx.lineTo(x+roofHalfW,roofY),ctx.moveTo(x-roofHalfW,roofY),ctx.lineTo(x-roofHalfW,roofY+legLen),ctx.moveTo(x+roofHalfW,roofY),ctx.lineTo(x+roofHalfW,roofY+legLen),ctx.stroke();const relTrackRad=(Number(aircraft.track??0)-myHeading)*Math.PI/180,dirX=Math.sin(relTrackRad),dirY=-Math.cos(relTrackRad),lineStart=Math.max(.021*h,11)+2,lineLen=Math.max(.034*h,16);if(ctx.beginPath(),ctx.moveTo(x+dirX*lineStart,y+dirY*lineStart),ctx.lineTo(x+dirX*(lineStart+lineLen),y+dirY*(lineStart+lineLen)),ctx.stroke(),isSelected&&!isHardLocked){const pad=2,left=x-roofHalfW-pad,right=x+roofHalfW+pad,top=roofY-pad,bottom=y+numberHalfH+pad,arm=Math.max(5,.012*h);ctx.strokeStyle="#ff3333",ctx.lineWidth=2,ctx.beginPath(),ctx.moveTo(left,top+arm),ctx.lineTo(left,top),ctx.lineTo(left+arm,top),ctx.moveTo(right-arm,top),ctx.lineTo(right,top),ctx.lineTo(right,top+arm),ctx.moveTo(left,bottom-arm),ctx.lineTo(left,bottom),ctx.lineTo(left+arm,bottom),ctx.moveTo(right-arm,bottom),ctx.lineTo(right,bottom),ctx.lineTo(right,bottom-arm),ctx.stroke()}if(isHardLocked){const halfW=.5*(x+roofHalfW+6-(x-roofHalfW-6)),halfH=.5*(y+numberHalfH+6-(roofY-6)),diamondSize=Math.max(halfW,halfH)+3,diamondCenterY=y-2;ctx.strokeStyle="#ff0000",ctx.lineWidth=2.5,ctx.beginPath(),ctx.moveTo(x,diamondCenterY-diamondSize),ctx.lineTo(x+diamondSize,diamondCenterY),ctx.lineTo(x,diamondCenterY+diamondSize),ctx.lineTo(x-diamondSize,diamondCenterY),ctx.closePath(),ctx.stroke()}};for(const aircraft of aircraftInCone)drawTrafficContact(aircraft.x,aircraft.y,aircraft);if(ctx.fillStyle=color,ctx.font=`bold ${Math.round(.032*h)}px monospace`,ctx.textAlign="right",ctx.textBaseline="top",ctx.fillText(`${rangeNm} NM`,displayRight-.01*w,displayTop+.01*h),radarModule.hardLockedUid){const lockedType=String(lockedAircraft?.contact?.aircraftName??"").trim()||"UNKNOWN",lockedCallsign=String(lockedAircraft?.contact?.callsign??"").trim()||"N/A";ctx.fillStyle="#ff0000",ctx.font=`bold ${Math.round(.034*h)}px monospace`,ctx.textAlign="center",ctx.textBaseline="top";const lockLineStep=.036*h,lockTextX=displayLeft+.5*displayWidth,lockTextY=displayTop+20+.01*h;ctx.fillText(`LOCK ${lockedCallsign}`.slice(0,42),lockTextX,lockTextY),ctx.fillText(lockedType.slice(0,42),lockTextX,lockTextY+lockLineStep)}ctx.restore()}}),!0}}class CommunicationModule{static HISTORY_LIMIT=120;static HUD_MESSAGE_VISIBLE_MS=1e4;static VOICE_RATE_OPTIONS=[.75,1,1.25,1.5,2,2.5,3];constructor(dependencies={}){this.dependencies=dependencies??{},this.installed=!1,this.multiplayerRef=null,this.originalUpdateCallback=null,this.wrappedUpdateCallback=null,this.messages=[],this.hudMessage=null,this.lastVoiceMode="NONE",this.voiceEnabledAtServerTime=null,this.voiceEnabledAtLocalMs=0}ensureLoaded(){return!!this.installed||this.installMultiplayerHook()}registerMfdPages(mfdModule){const communicationModule=this;return mfdModule.registerPage({title:"COMM",leftButtons:[{key:"SHOW",label:"SHOW",states:["MSG","CFG"],stateIndex:0},{key:"N/A1",label:"",states:[""],stateIndex:0},{key:"DISPLAY",label:"DISP",states:["NO","ALL","GRP","FLT","W/M"],values:["NONE","ALL","GROUP","FLIGHT","WINGMAN"],stateIndex:0,show:()=>"MSG"===OptionModule.getOption("COMM","SHOW","MSG")},{key:"N/A2",label:"",states:[""],stateIndex:0},{key:"HUD",label:"HUD",states:["NO","ALL","GRP","FLT","W/M"],values:["NONE","ALL","GROUP","FLIGHT","WINGMAN"],stateIndex:0,show:()=>"MSG"===OptionModule.getOption("COMM","SHOW","MSG")}],rightButtons:[{key:"VOICE",label:"VOICE",states:["NONE","ALL","GROUP","FLIGHT","WINGMAN"],stateIndex:0,show:()=>"CFG"===OptionModule.getOption("COMM","SHOW","MSG")},{key:"N/A3",label:"",states:[""],stateIndex:0},{key:"RATE",label:"RATE",states:["0.75","1","1.25","1.5","2","2.5","3"],values:[.75,1,1.25,1.5,2,2.5,3],stateIndex:3,show:()=>"CFG"===OptionModule.getOption("COMM","SHOW","MSG")}],lines:[],render:(renderer,renderContext)=>{const ctx=renderContext?.ctx??renderer?.canvasAPI?.context,w=renderContext?.w??renderer?.canvasAPI?.canvas?.width??512,h=renderContext?.h??renderer?.canvasAPI?.canvas?.height??512,color=renderContext?.color??"#00ff66";if(!ctx)return;const profile=communicationModule.getProfile(),voiceLanguage=communicationModule.getVoiceLanguage(),voiceRate=communicationModule.getVoiceRate(),voiceMode=OptionModule.getOptionValue("COMM","VOICE","NONE"),displayMode=OptionModule.getOptionValue("COMM","DISPLAY","NONE"),hudMode=OptionModule.getOptionValue("COMM","HUD","NONE"),showMode=OptionModule.getOption("COMM","SHOW","MSG"),mfdMessageMode="ALL"===displayMode?"ANY":displayMode,recentMessages=communicationModule.getMessagesByMode(mfdMessageMode,5),fmt=(value,withBrackets=!1)=>{const token=String(value??"").trim();return token?withBrackets?`[${token}]`:token:"-"},trimMessageLine=(text,maxChars=64)=>communicationModule.trimLine(text,maxChars),wrapFixed=(text,lineLen=32,maxLines=2)=>{const cleaned=String(text??"").replace(/\s+/g," ").trim();if(!cleaned)return[""];const lines=[];let cursor=0;for(;cursorMath.floor(.6*lineLen)&&(cut=lastSpace),lines.push(remaining.slice(0,cut).trim()),cursor+=cut;" "===cleaned[cursor];)cursor+=1}if(cursorthis.voiceEnabledAtServerTime:!!(Number.isFinite(this.voiceEnabledAtLocalMs)&&this.voiceEnabledAtLocalMs>0)&&Number(entry?.timestampMs)>this.voiceEnabledAtLocalMs}processIncomingMessage(message,payload){const callsign=message?.cs||"UNKNOWN",text=this.decodeChatText(message?.msg??"").trim();if(!text)return;const matches=this.resolveMatches(callsign),entry={uid:String(message?.uid??""),acid:Number(message?.acid),callsign:callsign,message:text,serverTime:Number(payload?.serverTime)||null,timestampMs:Date.now(),category:this.getCategoryTag(matches),...matches};this.messages.push(entry),this.messages.length>CommunicationModule.HISTORY_LIMIT&&this.messages.splice(0,this.messages.length-CommunicationModule.HISTORY_LIMIT);const voiceMode=OptionModule.getOptionValue("COMM","VOICE","NONE");this.refreshVoiceActivationWindow(voiceMode,payload?.serverTime),this.matchesMode(voiceMode,entry)&&this.isMessageNewForVoice(entry)&&this.speakMessage(entry);const hudMode=OptionModule.getOptionValue("COMM","HUD","NONE");if(this.matchesMode(hudMode,entry)){const formatted=[`[${entry.category}]`,this.trimLine(entry.callsign,44),this.trimLine(entry.message,88)].join("\n");this.hudMessage={text:formatted,expiresAtMs:Date.now()+CommunicationModule.HUD_MESSAGE_VISIBLE_MS}}}speakMessage(entry){const synth=window.speechSynthesis;if(!synth||"function"!=typeof window.SpeechSynthesisUtterance)return!1;const spokenCallsign=this.getSpokenCallsign(entry.callsign),utterance=new window.SpeechSynthesisUtterance(`${spokenCallsign}. ${entry.message}`);return utterance.lang=this.getVoiceLanguage(),utterance.rate=this.getVoiceRate(),synth.speak(utterance),!0}getMessagesByMode(mode="ALL",limit=5){const modeToken=String(mode??"ALL").toUpperCase(),max=Math.max(1,Math.min(50,Number(limit)||5)),filtered="ANY"===modeToken?this.messages.slice():this.messages.filter(entry=>this.matchesMode(modeToken,entry));return filtered.slice(Math.max(0,filtered.length-max))}getHudOverlayText(){return this.hudMessage?.text?!Number.isFinite(this.hudMessage.expiresAtMs)||Date.now()>this.hudMessage.expiresAtMs?(this.hudMessage=null,null):this.hudMessage.text:null}}class RecorderModule{FLIGHT_RECORDER_MIN_VERSION="1.2.0";constructor(dependencies={}){this.dependencies=dependencies??{}}registerMfdPages(mfdModule){return mfdModule.registerPage({title:"REC",leftButtons:[{key:"STATE",label:"REC",states:["OFF"],stateIndex:0,managedExternally:!0,onClick:()=>{this.toggleRecordingFromMfd()}}],rightButtons:[{key:"PLAYBACK",label:"START",states:["START"],stateIndex:0,managedExternally:!0,combinedAction:!0,combinedGroupLabel:"PLAYBACK",onClick:()=>{this.controlPlaybackFromMfd("START")}},{key:"PLAYBACK",label:"PAUSE",states:["PAUSE"],stateIndex:0,managedExternally:!0,combinedAction:!0,combinedGroupLabel:"PLAYBACK",onClick:()=>{this.controlPlaybackFromMfd("PAUSE")}},{key:"PLAYBACK",label:"STOP",states:["STOP"],stateIndex:0,managedExternally:!0,combinedAction:!0,combinedGroupLabel:"PLAYBACK",onClick:()=>{this.controlPlaybackFromMfd("STOP")}}],lines:[],render:(renderer,renderContext)=>{const ctx=renderContext?.ctx??renderer?.canvasAPI?.context,w=renderContext?.w??renderer?.canvasAPI?.canvas?.width??512,h=renderContext?.h??renderer?.canvasAPI?.canvas?.height??512,color=renderContext?.color??"#00ff66";if(!ctx)return;const status=window.BasePlugin?.getActiveAddon?.()?.recorder?.getFlightRecorderMfdStatus?.()??{installed:!1,compatible:!1,recordingState:"OFF",playbackState:"STOPPED"},cx=.5*w;if(ctx.save(),ctx.setTransform(1,0,0,1,0,0),ctx.fillStyle=color,ctx.textAlign="center",ctx.textBaseline="middle",!status.compatible)return ctx.font=`bold ${Math.round(.042*h)}px monospace`,ctx.fillText("Install Flight Recorder",cx,.58*h),ctx.fillText("v1.2.0 or higher",cx,.66*h),void ctx.restore();ctx.font=`bold ${Math.round(.042*h)}px monospace`,ctx.fillText(`FR v${status.version??"unknown"}`,cx,.56*h),ctx.fillText(`REC ${status.recordingState}`,cx,.64*h),ctx.fillText(`PLAY ${status.playbackState}`,cx,.72*h),ctx.restore()}}),!0}isFlightRecorderCompatible(){return HelperModule.isSemverAtLeast(window.FlightRecorder?.api.getVersion()??"0.0.0",this.FLIGHT_RECORDER_MIN_VERSION)}getFlightRecorderMfdStatus(){const installed=Boolean(window.FlightRecorder?.api),version=window.FlightRecorder?.api.getVersion(),compatible=this.isFlightRecorderCompatible();return installed&&compatible?{installed:installed,compatible:!0,version:version,recordingState:window.FlightRecorder?.api.recording.getState().state,playbackState:window.FlightRecorder?.api.playback.getState().state,message:""}:{installed:installed,compatible:!1,version:version,recordingState:"OFF",playbackState:"STOPPED",message:"Install Flight Recorder v1.2.0 or higher"}}toggleRecordingFromMfd(){if(!this.isFlightRecorderCompatible())return!1;const currentState=window.FlightRecorder?.api.recording.getState().state;return"RECORDING"===currentState?window.FlightRecorder?.api.recording.stop():window.FlightRecorder?.api.recording.start(),!0}controlPlaybackFromMfd(action){return!!this.isFlightRecorderCompatible()&&("START"===action?(window.FlightRecorder?.api.playback.start(),!0):"PAUSE"===action?(window.FlightRecorder?.api.playback.pause(),!0):"STOP"===action&&(window.FlightRecorder?.api.playback.stop(),!0))}}class F18MfdUiState{constructor(dependencies={},pageRegistry=[]){this.mapModule=dependencies.mapModule,this.weaponsModule=dependencies.weaponsModule,this.recorderModule=dependencies.recorderModule,this.pageIndex=0,this.pendingMfdExport=null,this.pages=pageRegistry,this.ensureDefaultsInStorage()}queueMfdExport(pageTitle="MFD"){this.pendingMfdExport=pageTitle}exportMfdCanvasToPng(canvas,pageTitle="MFD"){const pad2=value=>`${value}`.padStart(2,"0"),now=new Date,stamp=`${now.getFullYear()}${pad2(now.getMonth()+1)}${pad2(now.getDate())}-${pad2(now.getHours())}${pad2(now.getMinutes())}${pad2(now.getSeconds())}`,filename=`${pageTitle.replace(/[^a-z0-9_-]+/gi,"_").replace(/^_+|_+$/g,"")||"MFD"}-MFD-${stamp}.png`,link=document.createElement("a");link.href=canvas.toDataURL("image/png"),link.download=filename,link.click()}getCurrentPage(){return this.pages[this.pageIndex]??this.pages[0]}nextPage(){this.pageIndex=(this.pageIndex+1)%this.pages.length}prevPage(){this.pageIndex=(this.pageIndex-1+this.pages.length)%this.pages.length}setPage(index){index>=0&&indexs===storedState);if(exactIndex>=0)return exactIndex}return Number.isInteger(button.stateIndex)&&button.stateIndex>=0&&button.stateIndex=2&&groups.push({key:key,startSlot:start,endSlot:i-1,entries:visibleEntries.slice(start,i)})}return groups}getCombinedGroupForSlot(side,slotIndex,page=this.getCurrentPage()){return this.getCombinedButtonGroups(side,page).find(group=>slotIndex>=group.startSlot&&slotIndex<=group.endSlot)??null}toggleButtonBySlot(side,slotIndex){const page=this.getCurrentPage(),visibleEntries=this.getVisibleButtonEntries(side,page),entry=visibleEntries?.[slotIndex];entry&&this.toggleButton(side,entry.actualIndex)}getStateLabel(button,page,actualIndex,side){if("REC"===page?.title){const status=this.recorderModule?.getFlightRecorderMfdStatus?.()??{installed:!1,compatible:!1,recordingState:"OFF",playbackState:"STOPPED"};if(!status.compatible)return"UNAVAIL";if("STATE"===button?.key)return status.recordingState;if("PLAYBACK"===button?.key)return button?.combinedAction?button?.states?.[0]??button?.label??"N/A":status.playbackState}if("WPN"===page?.title&&("FIRE"===button?.key||"JETTISON"===button?.key)){const mode=OptionModule.getOption("WPN","MODE","NAV"),modeLoadout=this.weaponsModule?.getModeLoadout?.(mode);return this.weaponsModule?.getSelectedLoadDisplay?.(mode,modeLoadout)??"N/A"}if("NAV"===page?.title){const abbreviateNavTrafficState=value=>{const token=String(value??"").trim().toUpperCase();return"FRIEND"===token?"FRND":"CIVILIAN"===token?"CIV":"UNKNOWN"===token?"UNKN":token};if("MARK"===button?.key)return abbreviateNavTrafficState(this.mapModule?.getSelectedTrafficMark?.()||"");if("SHOW"===button?.key)return abbreviateNavTrafficState(this.mapModule?.getShowFilter?.());if("VIEW"===button?.key)return this.mapModule?.getViewMode?.()??""}const sideToken="right"===side?"R":"L",resolvedIndex=this.getStoredStateIndex(page,button,actualIndex,sideToken);return button?.states?.[resolvedIndex]??""}getLayout(w,h){const frame={left:0,top:0,width:w,height:h},tabY=frame.top+.022*h,bottomTabY=frame.top+.92*h,tabW=.14*w,tabH=.06*h,tabGap=.03*w,topPages=this.pages.slice(0,5),bottomPages=this.pages.slice(5,10),topTabCount=topPages.length,bottomTabCount=bottomPages.length,tabsTotalW=topTabCount*tabW+Math.max(0,topTabCount-1)*tabGap,tabStartX=frame.left+.5*(frame.width-tabsTotalW),bottomTabsTotalW=bottomTabCount*tabW+Math.max(0,bottomTabCount-1)*tabGap,bottomTabStartX=frame.left+.5*(frame.width-bottomTabsTotalW),topTabs=topPages.map((p,i)=>({index:i,title:p.title,x:tabStartX+i*(tabW+tabGap)-.012*w,y:tabY-.01*h,w:tabW+.024*w,h:tabH+.02*h})),bottomTabs=bottomPages.map((p,i)=>({index:i+5,title:p.title,x:bottomTabStartX+i*(tabW+tabGap)-.012*w,y:bottomTabY-.01*h,w:tabW+.024*w,h:tabH+.02*h})),leftButtons=[],rightButtons=[],rowStartY=frame.top+.14*h,rowStep=.155*h+3,rowH=.08*h;for(let i=0;i<5;i++){const y=rowStartY+i*rowStep;leftButtons.push({index:i,x:frame.left+.028*w,y:y,w:.4*w,h:rowH}),rightButtons.push({index:i,x:frame.left+frame.width-.428*w,y:y,w:.4*w,h:rowH})}return{frame:frame,topTabs:topTabs,bottomTabs:bottomTabs,leftButtons:leftButtons,rightButtons:rightButtons}}handleLocalClick(nx,ny){if(!Number.isFinite(nx)||!Number.isFinite(ny))return!1;if(nx<0||nx>1||ny<0||ny>1)return!1;const x=512*nx,y=512*ny,page=this.getCurrentPage(),layout=this.getLayout(512,512);for(const tab of layout.topTabs)if(x>=tab.x&&x<=tab.x+tab.w&&y>=tab.y&&y<=tab.y+tab.h)return this.setPage(tab.index),!0;for(const tab of layout.bottomTabs)if(x>=tab.x&&x<=tab.x+tab.w&&y>=tab.y&&y<=tab.y+tab.h)return this.setPage(tab.index),!0;for(const slot of layout.leftButtons)if(slot.index=slot.x&&x<=slot.x+slot.w&&y>=slot.y&&y<=slot.y+slot.h)return this.toggleButtonBySlot("left",slot.index),!0;for(const slot of layout.rightButtons)if(slot.index=slot.x&&x<=slot.x+slot.w&&y>=slot.y&&y<=slot.y+slot.h)return this.toggleButtonBySlot("right",slot.index),!0;return!1}render(renderer){const ctx=renderer.canvasAPI.context,w=renderer.canvasAPI.canvas.width,h=renderer.canvasAPI.canvas.height,page=this.getCurrentPage(),layout=this.getLayout(w,h),baseColor=OptionModule.getOptionValue("HUD","COLOR","#00ff66"),color=MfdModule.applyBrightnessToHexColor(baseColor,MfdModule.getMfdBrightnessFactor());renderer.canvasAPI.clear(),ctx.strokeStyle=color,ctx.lineWidth=2,ctx.strokeRect(layout.frame.left,layout.frame.top,layout.frame.width,layout.frame.height),ctx.save(),ctx.setTransform(1,0,0,1,0,0),ctx.globalCompositeOperation="source-over",ctx.globalAlpha=1,ctx.fillStyle="#000000",ctx.fillRect(0,0,w,h),ctx.restore(),ctx.fillStyle=color,ctx.textAlign="center",ctx.textBaseline="middle",ctx.font=`bold ${Math.round(.045*h)}px monospace`,"function"==typeof page.render&&(ctx.save(),page.render(renderer,{ctx:ctx,w:w,h:h,page:page,layout:layout,uiState:this,color:color}),ctx.restore()),ctx.setTransform(1,0,0,1,0,0),ctx.globalCompositeOperation="source-over",ctx.globalAlpha=1,ctx.fillStyle=color,ctx.strokeStyle=color,ctx.textAlign="center",ctx.textBaseline="middle",ctx.font=`bold ${Math.round(.045*h)}px monospace`;for(const tab of layout.topTabs)ctx.fillText(tab.title,tab.x+tab.w/2,tab.y+tab.h/2),tab.index===this.pageIndex&&ctx.strokeRect(tab.x-4,tab.y-2,tab.w+8,tab.h+4);for(const tab of layout.bottomTabs)ctx.fillText(tab.title,tab.x+tab.w/2,tab.y+tab.h/2),tab.index===this.pageIndex&&ctx.strokeRect(tab.x-4,tab.y-2,tab.w+8,tab.h+4);ctx.textAlign="left",ctx.font=`bold ${Math.round(.045*h)}px monospace`;const visibleLeftButtons=this.getVisibleButtonEntries("left",page),visibleRightButtons=this.getVisibleButtonEntries("right",page),drawStackedLabel=(text,centerX,centerY,stepPx)=>{const chars=String(text??"").split(""),startY=centerY-.5*Math.max(0,(chars.length-1)*stepPx);for(let c=0;c{const groups=this.getCombinedButtonGroups(side,page),slots="left"===side?layout.leftButtons:layout.rightButtons;if(groups?.length&&slots?.length){ctx.save(),ctx.strokeStyle=color,ctx.fillStyle=color,ctx.lineWidth=Math.max(1.5,.0028*w),ctx.textAlign="left",ctx.textBaseline="middle",ctx.font=`bold ${Math.round(.038*h)}px monospace`;for(const group of groups){const startSlot=slots[group.startSlot],endSlot=slots[group.endSlot];if(!startSlot||!endSlot)continue;if(Boolean(group.entries?.[0]?.button?.minimal)){const button=group.entries[0].button,rawDisplayValue=Array.isArray(button?.values)&&button.values.length?OptionModule.getOptionValue(page?.title??"PAGE",button?.key||button?.label||"",""):this.getStateLabel(button,page,group.entries[0]?.actualIndex??0,side),displayValue=String(rawDisplayValue??"").trim().length>0?rawDisplayValue:button?.combinedGroupLabel??button?.key??"",yMid=.5*(startSlot.y+.22*startSlot.h+(endSlot.y+.78*endSlot.h)),valueX="left"===side?startSlot.x+.016*w:startSlot.x+startSlot.w-.016*w;ctx.save(),ctx.textAlign="left"===side?"left":"right",ctx.textBaseline="middle",ctx.fillText(String(displayValue??""),valueX,yMid),ctx.restore();continue}const groupLabel=group.entries?.[0]?.button?.combinedGroupLabel??group.entries?.[0]?.button?.key??"",yTop=startSlot.y+.22*startSlot.h,yBottom=endSlot.y+.78*endSlot.h,yMid=.5*(yTop+yBottom),bracketX="left"===side?startSlot.x+.38*startSlot.w:startSlot.x+.56*startSlot.w,bracketArm=.012*w,labelOffset=.048*w;ctx.beginPath(),"left"===side?(ctx.moveTo(bracketX-bracketArm,yTop),ctx.lineTo(bracketX,yTop),ctx.lineTo(bracketX,yBottom),ctx.lineTo(bracketX-bracketArm,yBottom)):(ctx.moveTo(bracketX+bracketArm,yTop),ctx.lineTo(bracketX,yTop),ctx.lineTo(bracketX,yBottom),ctx.lineTo(bracketX+bracketArm,yBottom)),ctx.stroke();const labelX="left"===side?bracketX+labelOffset:bracketX-labelOffset,labelChars=String(groupLabel??"").split(""),lineStep=.038*h,startY=yMid-.5*Math.max(0,(labelChars.length-1)*lineStep);ctx.save(),ctx.textAlign="center",ctx.textBaseline="middle";for(let c=0;c{ctx.fillText(line,.5*w,h*(.72+.07*i))})),null!==this.pendingMfdExport){const request=this.pendingMfdExport;this.pendingMfdExport=null,this.exportMfdCanvasToPng(renderer.canvasAPI.canvas,request||page.title)}}}class SystemModule{registerMfdPages(mfdModule){return mfdModule.registerPage({title:"SYS",leftButtons:[{key:"FLAPS",label:"FLAP",states:["MAN","AUTO"],stateIndex:0},{key:"NA",label:"",states:[""],stateIndex:0},{key:"SPEEDBRAKE",label:"SPLR",states:["MAX","25%","50%","75%"],stateIndex:0}],rightButtons:[{key:"REFUELING",label:"FUEL",states:["CLOSED","OPEN"],stateIndex:0},{key:"NA2",label:"",states:[""],stateIndex:0},{key:"CANOPY",label:"CANOPY",states:["CLOSED","OPEN"],stateIndex:0}],lines:[],render:(renderer,renderContext)=>{const ctx=renderContext?.ctx??renderer?.canvasAPI?.context,w=renderContext?.w??renderer?.canvasAPI?.canvas?.width??512,h=renderContext?.h??renderer?.canvasAPI?.canvas?.height??512,color=renderContext?.color??"#00ff66";ctx&&(F18HudModule.drawGearAndFlapIndicators(ctx,w,h,color,{target:"mfd"}),ctx.save(),ctx.fillStyle=color,ctx.textAlign="center",ctx.textBaseline="alphabetic",ctx.font=`${Math.max(8,Math.round(.028*h))}px monospace`,ctx.fillText("Created by NatriumFS",w/2,h-Math.round(.32*h)),ctx.fillText("Credits to yicha.25 (壹茶) for targeting pod, combat module,",w/2,h-Math.round(.24*h),.96*w),ctx.fillText("missiles and ADI view. Thank you for your contribution.",w/2,h-Math.round(.2*h),.96*w),ctx.restore())}}),!0}}class FlightModule{static DISPLAY_MODES=["ADI","FLP","MRK","MSS","IFF"];static MARKPOINT_TYPES=["TARGET","FRIENDLY","RESQUE","CIVILIAN"];static MISSION_PAGE_STATES=["P1","P2","P3","P4","P5","P6"];constructor(getAddon=()=>null){this.getAddon=getAddon,this.selectedFlpIndex=0,this.selectedMarkpointIndex=0,this.missionPageIndex=0}getDisplayMode(){return OptionModule.getOption("FLT","DISPLAY",OptionModule.getOption("ADI","DISPLAY","ADI"))}getDataCartridge(){return this.getAddon()?.dataCartridge??null}getFlightPlanItems(){return window.geofs?.flightPlan?.waypointArray??[]}getMarkpointItems(){const cartridge=this.getDataCartridge();return cartridge?.getMarkpoints?.()??[]}getSelectedFlpIndex(items){return items.length?(this.selectedFlpIndex=Math.max(0,Math.min(this.selectedFlpIndex,items.length-1)),this.selectedFlpIndex):(this.selectedFlpIndex=0,0)}getSelectedMarkpointIndex(items){return items.length?(this.selectedMarkpointIndex=Math.max(0,Math.min(this.selectedMarkpointIndex,items.length-1)),this.selectedMarkpointIndex):(this.selectedMarkpointIndex=0,0)}stepSelectedFlightPlan(step){const items=this.getFlightPlanItems();if(!items.length)return!1;const next=(this.getSelectedFlpIndex(items)+step+items.length)%items.length;return this.selectedFlpIndex=next,!0}stepSelectedMarkpoint(step){const items=this.getMarkpointItems();if(!items.length)return!1;const next=(this.getSelectedMarkpointIndex(items)+step+items.length)%items.length;return this.selectedMarkpointIndex=next,!0}activateSelectedFlightPlan(){const items=this.getFlightPlanItems();if(!items.length)return!1;const index=this.getSelectedFlpIndex(items);return window.geofs.flightPlan.selectWaypoint(index),!0}activateSelectedMarkpoint(){const items=this.getMarkpointItems();if(!items.length)return!1;const index=this.getSelectedMarkpointIndex(items),markpoint=items[index],cartridge=this.getDataCartridge();cartridge?.setActiveMarkpoint?.(index);const targetingPod=this.getAddon()?.targetingPod;return targetingPod?.trackMarkpoint&&targetingPod.trackMarkpoint(markpoint),!0}deleteSelectedFlightPlan(){const items=this.getFlightPlanItems();if(!items.length)return!1;const index=this.getSelectedFlpIndex(items);window.geofs.flightPlan.deleteWaypoint(index);const nextItems=this.getFlightPlanItems();return this.selectedFlpIndex=Math.max(0,Math.min(index,Math.max(0,nextItems.length-1))),!0}deleteSelectedMarkpoint(){const items=this.getMarkpointItems();if(!items.length)return!1;const index=this.getSelectedMarkpointIndex(items);this.getDataCartridge().deleteMarkpoint(index);const nextItems=this.getMarkpointItems();return this.selectedMarkpointIndex=Math.max(0,Math.min(index,Math.max(0,nextItems.length-1))),!0}setSelectedMarkpointType(type){const items=this.getMarkpointItems();if(!items.length)return!1;const index=this.getSelectedMarkpointIndex(items);return this.getDataCartridge().setMarkpointType(index,type)}cycleSelectedMarkpointType(){const items=this.getMarkpointItems();if(!items.length)return!1;const index=this.getSelectedMarkpointIndex(items),current=items[index]?.type,states=FlightModule.MARKPOINT_TYPES,nextIndex=(states.findIndex(type=>type===current)+1+states.length)%states.length;return this.setSelectedMarkpointType(states[nextIndex])}getMissionSections(){const data=this.getDataCartridge()?.getMissionData?.()??{},noteLines=String(data.notes??data.cruise?.notes??"").replace(/\r?\n/g," ").match(/.{1,38}/g)??[""],positions=Array.isArray(data.positions)?data.positions:[],positionRows=positions.length?positions.map((position,index)=>[`#${index+1}`,position?.callsign??position?.name??position?.pilot??""]):[["#1",""]];return{mission:{title:"MISSION",rows:[["Name",data.missionName??data.name??"Untitled"],["Group",data.group??""],["Flight",data.flight??""],["Wingman",data.wingman??""]]},times:{title:"TIMES",rows:[["Start",data.flightData?.startTimeZ??""],["Taxi",data.flightData?.startTaxiZ??""],["T/O",data.flightData?.startToZ??""],["TOT",data.flightData?.timeOverTargetZ??""],["End",data.flightData?.endTimeZ??""]]},cruise:{title:"CRUISE",rows:[["Altitude",data.cruise?.altitude??""],["Speed",data.cruise?.speed??""]]},notes:{title:"NOTES",rows:noteLines.map(line=>["",line])},positions:{title:"POSITIONS",rows:positionRows},landing:{title:"LANDING",rows:[["Airport",data.landing?.airportIcao??""],["Runway",data.landing?.runway??""],["NAV1",data.landing?.nav1??""],["Pattern",data.landing?.pattern??""],["Form",data.landing?.formation??""]]},landingPerf:{title:"LANDING PERF",rows:[["Entry AGL",data.landing?.altEntryAgl??""],["Entry SPD",data.landing?.speedEntryKn??""],["Pitch Int",data.landing?.pitchIntervalS??""],["Downwind",data.landing?.speedDownwindKn??""]]}}}getMissionPages(){const sections=this.getMissionSections();return[{rowHeights:[.38,.16,.46],blocks:[{section:sections.mission,col:0,row:0,colSpan:1},{section:sections.times,col:1,row:0,colSpan:1},{section:sections.cruise,col:0,row:1,colSpan:2},{section:sections.notes,col:0,row:2,colSpan:2}]},{rowHeights:[.333,.333,.334],blocks:[{section:sections.landing,col:0,row:0,colSpan:2},{section:sections.landingPerf,col:0,row:1,colSpan:2},{section:sections.positions,col:0,row:2,colSpan:2}]}]}getMissionPageCount(){return this.getMissionPages().length}renderAdi(ctx,w,h,color,layout){const pitch=Number(window.geofs?.animation?.values?.atilt)||0,roll=Number(window.geofs?.animation?.values?.aroll)||0,kias=Math.round(Number(window.geofs?.animation?.values?.kias)||0),alt=Math.round(Number(window.geofs?.animation?.values?.altitude)||0),vsi=Math.round(Number(window.geofs?.animation?.values?.climbrate)||0),frame=layout?.frame??{left:0,top:0,width:w,height:h};ctx.save(),ctx.setTransform(1,0,0,1,0,0);const cx=frame.left+.5*frame.width,cy=frame.top+.54*frame.height,radius=.31*frame.width;ctx.save(),ctx.beginPath(),ctx.arc(cx,cy,radius,0,2*Math.PI),ctx.clip(),ctx.translate(cx,cy),ctx.rotate(roll*Math.PI/180),ctx.translate(0,8*-pitch),ctx.strokeStyle=color,ctx.lineWidth=1,ctx.beginPath();for(let i=4;i<4*radius;i+=8)ctx.moveTo(3*-radius,i),ctx.lineTo(3*radius,i);ctx.stroke(),ctx.lineWidth=3,ctx.beginPath(),ctx.moveTo(3*-radius,0),ctx.lineTo(3*radius,0),ctx.stroke(),ctx.lineWidth=2,ctx.beginPath(),ctx.moveTo(0,5*-radius),ctx.lineTo(0,5*radius),ctx.stroke(),ctx.font="bold 20px monospace",ctx.textAlign="center",ctx.textBaseline="middle";for(let p=-90;p<=90;p+=10){if(0===p)continue;const py=8*-p,lineW=p%20==0?50:25;ctx.beginPath(),ctx.moveTo(-lineW,py),ctx.lineTo(lineW,py),ctx.stroke(),ctx.fillStyle="#000000",ctx.fillRect(-18,py-9,36,18),ctx.fillStyle=color,ctx.fillText(Math.abs(p),0,py+1)}ctx.restore(),ctx.strokeStyle=color,ctx.fillStyle=color,ctx.lineWidth=3,ctx.beginPath(),ctx.arc(cx,cy,radius,0,2*Math.PI),ctx.stroke();const wx=cx,wy=cy,ww=.027*w,wh=.016*h,stub=.01*w;ctx.lineWidth=2,ctx.beginPath(),ctx.moveTo(wx-ww,wy),ctx.lineTo(wx-.55*ww,wy+wh),ctx.lineTo(wx,wy-.15*wh),ctx.lineTo(wx+.55*ww,wy+wh),ctx.lineTo(wx+ww,wy),ctx.moveTo(wx-ww-stub,wy),ctx.lineTo(wx-ww,wy),ctx.moveTo(wx+ww,wy),ctx.lineTo(wx+ww+stub,wy),ctx.stroke(),ctx.textAlign="center",ctx.textBaseline="middle";const boxY=cy-radius-.012*h,spdX=.25*w,altX=.82*w;ctx.lineWidth=2,ctx.strokeRect(spdX-42,boxY-20,84,40),ctx.font="bold 26px monospace",ctx.fillText(kias,spdX,boxY+2),ctx.strokeRect(altX-52,boxY-22,104,44);const altRounded=Math.max(0,Math.round(alt)),thousands=Math.floor(altRounded/1e3),hundredsText=String(altRounded%1e3).padStart(3,"0"),rightX=altX+52-.014*w,altCenterY=boxY+1;ctx.textAlign="right",ctx.font="bold 22px monospace";const hundredsWidth=ctx.measureText(hundredsText).width;ctx.fillText(hundredsText,rightX,altCenterY),ctx.font="bold 30px monospace",ctx.fillText(String(thousands),rightX-hundredsWidth-.006*w,altCenterY);const vsiText=`${vsi>=0?" ":""}${vsi}`;ctx.font="bold 24px monospace",ctx.textAlign="left",ctx.fillText(vsiText,altX-.07*w,boxY-.08*h),ctx.restore()}renderSelectableList(ctx,w,h,items,selectedIndex,title,rowBuilder,color,options={}){if(ctx.save(),ctx.setTransform(1,0,0,1,0,0),ctx.fillStyle=color,ctx.textAlign="left",ctx.textBaseline="middle",ctx.font=`bold ${Math.round(.045*h)}px monospace`,ctx.fillText(title,.22*w,.16*h),!items.length)return ctx.fillText("NO ITEMS",.22*w,.26*h),void ctx.restore();const keyX=w*(options.keyXRatio??.24),valueX=w*(options.valueXRatio??.62),prefixOffset=w*(options.prefixOffsetRatio??.018);let y=.25*h;for(let i=0;i.88*h);i++){const item=items[i],prefix=i===selectedIndex?">":" ",row=rowBuilder(item,i)??{},rowColor=options.rowColorBuilder?options.rowColorBuilder(item,i):color;ctx.fillStyle=rowColor,ctx.fillText(prefix,keyX-prefixOffset,y),ctx.fillText(String(row.key??""),keyX,y),ctx.fillText(String(row.value??""),valueX,y),y+=.055*h}ctx.restore()}renderMissionGroup(ctx,group,x,y,width,height,color){const rows=group?.rows??[];if(ctx.strokeStyle=color,ctx.lineWidth=2,ctx.strokeRect(x,y,width,height),ctx.fillStyle=color,ctx.textAlign="left",ctx.textBaseline="middle",ctx.font="bold 18px monospace",ctx.fillText(String(group?.title??""),x+10,y+16),"NOTES"===group?.title){let lineY=y+40;ctx.font="bold 16px monospace";for(const[,value]of rows){if(lineY>y+height-12)break;ctx.fillText(String(value??""),x+10,lineY),lineY+=20}return}if("CRUISE"===group?.title){const left=rows[0]??["Altitude",""],right=rows[1]??["Speed",""],colWidth=.5*width,leftX=x+10,rightX=x+colWidth+10,leftValueX=leftX+.52*colWidth,rightValueX=rightX+.52*colWidth,rowY=y+44;return ctx.font="bold 16px monospace",ctx.fillText(String(left[0]??""),leftX,rowY),ctx.fillText(String(left[1]??""),leftValueX,rowY),ctx.fillText(String(right[0]??""),rightX,rowY),void ctx.fillText(String(right[1]??""),rightValueX,rowY)}if("POSITIONS"===group?.title){const shown=rows.slice(0,8),twoColumns=shown.length>4,colWidth=twoColumns?.5*width:width,leftPad=10,valueOffset=twoColumns?.52*colWidth:.52*width;ctx.font="bold 16px monospace";for(let i=0;iy+height-12)break;const colX=x+column*colWidth,keyX=colX+leftPad,valueX=colX+leftPad+valueOffset;ctx.fillText(String(shown[i][0]??""),keyX,rowY),ctx.fillText(String(shown[i][1]??""),valueX,rowY)}return}const keyX=x+10,valueX=x+.52*width;let rowY=y+40;ctx.font="bold 16px monospace";for(const[key,value]of rows){if(rowY>y+height-12)break;ctx.fillText(String(key??""),keyX,rowY),ctx.fillText(String(value??""),valueX,rowY),rowY+=20}}renderMissionData(ctx,w,h,color,renderContext){const pages=this.getMissionPages(),pageCount=Math.max(1,pages.length),pageButton=renderContext?.page?.leftButtons?.find(button=>"PAGE"===button?.key);this.missionPageIndex=Math.max(0,Math.min(this.missionPageIndex,pageCount-1)),pageButton&&(pageButton.stateIndex=this.missionPageIndex);const activePage=pages[this.missionPageIndex]??{rowHeights:[.333,.333,.334],blocks:[]},pageBlocks=activePage.blocks??[];ctx.save(),ctx.setTransform(1,0,0,1,0,0),ctx.fillStyle=color,ctx.textAlign="left",ctx.textBaseline="middle",ctx.font=`bold ${Math.round(.043*h)}px monospace`,ctx.fillText(`MISSION DATA ${this.missionPageIndex+1}/${pageCount}`,.22*w,.12*h);const gridLeft=.22*w,gridTop=.17*h,gapX=.02*w,gapY=.03*h,boxW=(.7*w-gapX)/2,availableH=.74*h-2*gapY,rowHeights=activePage.rowHeights??[.333,.333,.334],rowSizes=[availableH*(rowHeights[0]??.333),availableH*(rowHeights[1]??.333),availableH*(rowHeights[2]??.334)],rowOffsets=[0,rowSizes[0]+gapY,rowSizes[0]+gapY+rowSizes[1]+gapY];for(const block of pageBlocks){const column=block.col??0,row=block.row??0,colSpan=block.colSpan??1,x=gridLeft+column*(boxW+gapX),y=gridTop+(rowOffsets[row]??rowOffsets[0]),width=2===colSpan?2*boxW+gapX:boxW,height=rowSizes[row]??rowSizes[0];this.renderMissionGroup(ctx,block.section,x,y,width,height,color)}ctx.restore()}renderIff(ctx,w,h,color){const codes=this.getDataCartridge()?.getIffCodes?.()??[];if(ctx.save(),ctx.setTransform(1,0,0,1,0,0),ctx.fillStyle=color,ctx.textAlign="left",ctx.textBaseline="middle",ctx.font=`bold ${Math.round(.045*h)}px monospace`,ctx.fillText("IFF CODEBOOK",.22*w,.16*h),ctx.font=`bold ${Math.round(.024*h)}px monospace`,ctx.fillText('Interrogate: Say "IFF [CS] - Code [NO.]"',.22*w,.2*h),ctx.fillText('Response: "IFF [Code]"',.22*w,.235*h),!codes.length)return ctx.fillText("NO IFF CODES",.22*w,.26*h),void ctx.restore();const shown=codes.slice(0,14),baseX=.22*w,columnGap=.31*w,responseOffset=.12*w,lineHeight=.053*h;ctx.font=`bold ${Math.round(.043*h)}px monospace`;for(let i=0;i=7?1:0,y=.29*h+i%7*lineHeight;if(y>.88*h)break;const code=shown[i],keyX=baseX+column*columnGap,valueX=keyX+responseOffset;ctx.fillText(String(code.key??""),keyX,y),ctx.fillText(String(code.response??""),valueX,y)}ctx.restore()}registerMfdPages(mfdModule){return mfdModule.registerPage({title:"FLT",leftButtons:[{key:"DISPLAY",label:"DISP",states:FlightModule.DISPLAY_MODES,stateIndex:0},{key:"N/A20",label:"",states:[""],stateIndex:0,show:()=>"MSS"===this.getDisplayMode()&&this.getMissionPageCount()>1},{key:"PAGE",label:"PAGE",states:FlightModule.MISSION_PAGE_STATES,stateIndex:0,managedExternally:!0,show:()=>"MSS"===this.getDisplayMode()&&this.getMissionPageCount()>1,onClick:({button:button})=>{const pageCount=this.getMissionPageCount();if(pageCount<=1)return this.missionPageIndex=0,void(button&&(button.stateIndex=0));this.missionPageIndex=(this.missionPageIndex+1)%pageCount,button&&(button.stateIndex=this.missionPageIndex)}},{key:"PREV",label:"↑",states:[""],stateIndex:0,managedExternally:!0,show:()=>{const mode=this.getDisplayMode();return"FLP"===mode||"MRK"===mode},onClick:()=>{"FLP"!==this.getDisplayMode()?this.stepSelectedMarkpoint(-1):this.stepSelectedFlightPlan(-1)}},{key:"NEXT",label:"↓",states:[""],stateIndex:0,managedExternally:!0,show:()=>{const mode=this.getDisplayMode();return"FLP"===mode||"MRK"===mode},onClick:()=>{"FLP"!==this.getDisplayMode()?this.stepSelectedMarkpoint(1):this.stepSelectedFlightPlan(1)}},{key:"TYPE",label:"TYPE",states:[""],stateIndex:0,managedExternally:!0,show:()=>"MRK"===this.getDisplayMode(),onClick:()=>{this.cycleSelectedMarkpointType()}}],rightButtons:[{key:"N/A30",label:"",states:[""],stateIndex:0,show:()=>{const mode=this.getDisplayMode();return"FLP"===mode||"MRK"===mode}},{key:"ACTIVATE",label:"ACTIVATE",states:[""],stateIndex:0,managedExternally:!0,show:()=>{const mode=this.getDisplayMode();return"FLP"===mode||"MRK"===mode},onClick:()=>{"FLP"!==this.getDisplayMode()?this.activateSelectedMarkpoint():this.activateSelectedFlightPlan()}},{key:"N/A31",label:"",states:[""],stateIndex:0,show:()=>{const mode=this.getDisplayMode();return"FLP"===mode||"MRK"===mode}},{key:"N/A32",label:"",states:[""],stateIndex:0,show:()=>{const mode=this.getDisplayMode();return"FLP"===mode||"MRK"===mode}},{key:"DELETE",label:"DEL",states:[""],stateIndex:0,managedExternally:!0,show:()=>{const mode=this.getDisplayMode();return"FLP"===mode||"MRK"===mode},onClick:()=>{"FLP"!==this.getDisplayMode()?this.deleteSelectedMarkpoint():this.deleteSelectedFlightPlan()}}],lines:[],render:(renderer,renderContext)=>{const ctx=renderContext?.ctx??renderer?.canvasAPI?.context,w=renderContext?.w??renderer?.canvasAPI?.canvas?.width??512,h=renderContext?.h??renderer?.canvasAPI?.canvas?.height??512,color=renderContext?.color??"#00ff66",layout=renderContext?.layout;if(!ctx)return;const displayMode=this.getDisplayMode();if("ADI"!==displayMode){if("FLP"===displayMode){const items=this.getFlightPlanItems(),selectedIndex=this.getSelectedFlpIndex(items);return void this.renderSelectableList(ctx,w,h,items,selectedIndex,"FLIGHTPLAN",(item,index)=>({key:`WP${index+1} ${item.ident??""}`.trim(),value:`${item.type??""}${item?.selected?" (ACTIVE)":""}`}),color,{keyXRatio:.23,valueXRatio:.6,prefixOffsetRatio:.028})}if("MRK"===displayMode){const items=this.getMarkpointItems(),selectedIndex=this.getSelectedMarkpointIndex(items);return void this.renderSelectableList(ctx,w,h,items,selectedIndex,"MARKPOINTS",(item,index)=>({key:`MRK${index+1} ${item.abbreviation??item.name??""}`.trim(),value:`${item.type??""}${item?.active?" (ACTIVE)":""}`}),color,{keyXRatio:.23,valueXRatio:.56,prefixOffsetRatio:.028,rowColorBuilder:item=>this.getDataCartridge()?.getMarkpointColor(item?.type)??color})}"MSS"!==displayMode?this.renderIff(ctx,w,h,color):this.renderMissionData(ctx,w,h,color,renderContext)}else this.renderAdi(ctx,w,h,color,layout)}}),!0}}window.FlightModule=FlightModule;class TargetingPodModule{constructor(getAddon=()=>null){this.getAddon=getAddon,this.activePage=null,this.pendingMarkpoint=null}_resolveMarkpointTarget(markpoint){const lat=Number(markpoint?.lat),lon=Number(markpoint?.lon);if(!Number.isFinite(lat)||!Number.isFinite(lon))return null;let altM=Number(markpoint?.altM);if(!Number.isFinite(altM)&&"undefined"!=typeof Cesium){const viewer=window.geofs?.api?.viewer,globe=viewer?.scene?.globe,cartographic=Cesium.Cartographic.fromDegrees(lon,lat);altM=Number(globe?.getHeight(cartographic))}return Number.isFinite(altM)||(altM=0),{lat:lat,lon:lon,altM:altM,createdAt:Date.now()}}trackMarkpoint(markpoint){const page=this.activePage,target=this._resolveMarkpointTarget(markpoint);return!!target&&(page?._applyLockedPoint&&page?._setLockState?(page._markPoint=target,page._applyLockedPoint(target,"MRK","MRK"),page._setLockState("MRK"),!0):(this.pendingMarkpoint=target,!0))}registerMfdPages(mfdModule){const owner=this,getMapModule=()=>this.getAddon()?.map??null,getOption=(page,key,fallback)=>OptionModule.getOption(page,key,fallback),getMode=()=>OptionModule.getOption("TGP","MODE","CAPTURE"),isMarkMode=()=>"MARK"===getMode(),isCaptureOrMarkMode=()=>{const mode=getMode();return"CAPTURE"===mode||"MARK"===mode},isSettingsMode=()=>"SETTINGS"===getMode();return mfdModule.registerPage({title:"TGP",leftButtons:[{key:"MODE",label:"MODE",states:["CAPTURE","MARK","SETTINGS"],stateIndex:0,onClick:({page:page,nextState:nextState})=>{if(page)if("MARK"===nextState)page._setLockState("FREE"),page._resetLockData(),page._lockedCallsign="N/A",page._relYaw=0,page._relPitch=0;else if("CAPTURE"===nextState){const lockState=OptionModule.getOption("TGP","LOCK","FREE");"FIX"!==lockState&&"MARK"!==lockState&&"MRK"!==lockState||page._setLockState("FREE")}}},{key:"RANGE",label:"↑",states:["0.1","0.5","1","2","5","10","15","20","30","45","60","90","120"],stateIndex:4,minimal:!0,managedExternally:!0,combinedGroupLabel:"RNG",show:()=>isCaptureOrMarkMode(),onClick:({page:page})=>page&&page._stepRange(1)},{key:"RANGE",label:"↓",states:["0.1","0.5","1","2","5","10","15","20","30","45","60","90","120"],stateIndex:4,minimal:!0,managedExternally:!0,combinedGroupLabel:"RNG",show:()=>isCaptureOrMarkMode(),onClick:({page:page})=>page&&page._stepRange(-1)},{key:"LOCK",label:"LOCK",states:["FREE","TRK","WPT","MRK","FIX","MARK"],stateIndex:0,managedExternally:!0,show:()=>isCaptureOrMarkMode(),onClick:({page:page})=>{if(!page)return;if(isMarkMode()){const lockState=OptionModule.getOption("TGP","LOCK","FREE");if("FIX"===lockState||"MARK"===lockState||"MRK"===lockState)return page._setLockState("FREE"),page._resetLockData(),page._lockedCallsign="N/A",page._relYaw=0,void(page._relPitch=0);const lookPoint=page._resolveCurrentAimGroundPoint();if(!lookPoint)return;return void page._applyLockedPoint(lookPoint,"FIX","FIX")}const cycle=["FREE","TRK","WPT","MRK"],current=OptionModule.getOption("TGP","LOCK","FREE"),currentIndex=Math.max(0,cycle.findIndex(state=>state===current)),next=cycle[(currentIndex+1)%cycle.length];"MRK"!==next?(page._setLockState(next),"FREE"===next&&(page._resetLockData(),page._lockedCallsign="N/A")):page._lockActiveMarkpointFromCartridge()||(page._setLockState("FREE"),page._resetLockData(),page._lockedCallsign="N/A")}},{key:"CAPTURE",label:"CPT",states:[""],show:()=>"CAPTURE"===getMode(),onClick:({page:page,uiState:uiState})=>{uiState.queueMfdExport(page.title)},stateIndex:0},{key:"MARKPOINT",label:"MRK",states:[""],show:()=>isMarkMode(),onClick:({page:page})=>{if(!page)return;owner.activePage=page;const lookPoint=page._resolveCurrentAimGroundPoint();if(!lookPoint)return;page._markPoint={lat:lookPoint.lat,lon:lookPoint.lon,altM:lookPoint.altM,createdAt:Date.now()},page._applyLockedPoint(page._markPoint,"MARK","MRK");const addon=this.getAddon?.(),dataCartridge=addon?.dataCartridge;dataCartridge?.addTgpMarkpoint&&dataCartridge.addTgpMarkpoint(page._markPoint)},stateIndex:0},{key:"NA10",label:"",states:[""],stateIndex:0,show:()=>isSettingsMode()},{key:"FREQUENCY",label:"FREQ",states:["2","3","5","10","15","30","45","60"],stateIndex:3,show:()=>isSettingsMode()},{key:"NA12",label:"",states:[""],stateIndex:0,show:()=>isSettingsMode()},{key:"POWER",label:"PWR",states:["ON","OFF"],stateIndex:1,show:()=>isSettingsMode()}],rightButtons:[{key:"SLEW_UP",label:"↑",states:[""],stateIndex:0,show:()=>isCaptureOrMarkMode(),onClick:({page:page})=>page&&page._updateSlew(0,1)},{key:"SLEW_DOWN",label:"↓",states:[""],stateIndex:0,show:()=>isCaptureOrMarkMode(),onClick:({page:page})=>page&&page._updateSlew(0,-1)},{key:"SLEW_LEFT",label:"←",states:[""],stateIndex:0,show:()=>isCaptureOrMarkMode(),onClick:({page:page})=>page&&page._updateSlew(-1,0)},{key:"SLEW_RIGHT",label:"→",states:[""],stateIndex:0,show:()=>isCaptureOrMarkMode(),onClick:({page:page})=>page&&page._updateSlew(1,0)},{key:"SLEW_STEP",label:"STEP",states:["0.01","0.05","0.1","0.25","0.5","1","2.5","5","10"],stateIndex:2,show:()=>isCaptureOrMarkMode()},{key:"STYLE",label:"STL",states:["DAY","NIGHT","WHITE"],stateIndex:0,show:()=>isSettingsMode()},{key:"NA3",label:"",states:[""],stateIndex:0,show:()=>isSettingsMode()},{key:"TRACK",label:"TRK",states:["SIMPLE","ADVANCED"],stateIndex:0,show:()=>isSettingsMode()},{key:"NA4",label:"",states:[""],stateIndex:0,show:()=>isSettingsMode()},{key:"SLEW_RESET",label:"SLEW",states:["RESET"],stateIndex:0,onClick:({page:page})=>page&&page._resetSlew(),show:()=>isSettingsMode()}],_snap:null,_snapCtx:null,_snapCoverCrop:null,_styleCanvas:null,_styleCtx:null,_captureQueued:!1,_captureFovRad:0,_captureIsLocked:!1,_tick:0,_camYaw:0,_camPitch:-15,_relYaw:0,_relPitch:0,_lockMode:"FREE",_activeMode:"A/G",_targetWorldH:0,_targetWorldP:0,_targetLat:null,_targetLon:null,_targetAltM:null,_targetNorthM:0,_targetEastM:0,_targetUpM:0,_lockTargetKey:null,_lockedCallsign:"N/A",_lockedDist:null,_targetAltFt:0,_targetHdg:0,_closureKts:0,_trackUpdateByUid:{},_markPoint:null,_WGS84_A:6378137,_WGS84_E2:.00669437999014,_llaToEcef:function(latDeg,lonDeg,altM){const lat=latDeg*Math.PI/180,lon=lonDeg*Math.PI/180,sinLat=Math.sin(lat),cosLat=Math.cos(lat),sinLon=Math.sin(lon),cosLon=Math.cos(lon),N=this._WGS84_A/Math.sqrt(1-this._WGS84_E2*sinLat*sinLat);return[(N+altM)*cosLat*cosLon,(N+altM)*cosLat*sinLon,(N*(1-this._WGS84_E2)+altM)*sinLat]},_ecefDeltaToNeu:function(refLatDeg,refLonDeg,dX,dY,dZ){const lat=refLatDeg*Math.PI/180,lon=refLonDeg*Math.PI/180,sinLat=Math.sin(lat),cosLat=Math.cos(lat),sinLon=Math.sin(lon),cosLon=Math.cos(lon);return[-sinLat*cosLon*dX-sinLat*sinLon*dY+cosLat*dZ,-sinLon*dX+cosLon*dY,cosLat*cosLon*dX+cosLat*sinLon*dY+sinLat*dZ]},_computeClosureRateKts:function(dN,dE,dU,targetHeadingDeg,targetSpeedKts){const losLen=Math.hypot(dN,dE,dU);if(!losLen)return 0;const losN=dN/losLen,losE=dE/losLen,losU=dU/losLen,ownHeadingDeg=Number(window.geofs?.animation?.values?.heading??0),ownSpeedMps=Number(window.geofs?.animation?.values?.airspeedms??0),ownHeadingRad=ownHeadingDeg*Math.PI/180,ownVelN=ownSpeedMps*Math.cos(ownHeadingRad),ownVelE=ownSpeedMps*Math.sin(ownHeadingRad),tgtHeadingRad=targetHeadingDeg*Math.PI/180,tgtSpeedMps=targetSpeedKts/1.94384,closureMps=-((tgtSpeedMps*Math.cos(tgtHeadingRad)-ownVelN)*losN+(tgtSpeedMps*Math.sin(tgtHeadingRad)-ownVelE)*losE+0*losU);return Math.round(1.94384*closureMps)},_computeRelativePositionMeters:function(ownLat,ownLon,ownAltM,targetLat,targetLon,targetAltM){const latAvgRad=(ownLat+targetLat)/2*Math.PI/180,dE=111320*(targetLon-ownLon)*Math.cos(latAvgRad),dN=110540*(targetLat-ownLat),dU=targetAltM-ownAltM,distM=Math.hypot(dN,dE,dU);return{dN:dN,dE:dE,dU:dU,distM:distM,distNm:539957e-9*distM}},_getTrackDistanceNmFromMultiplayer:function(trackUid){if(!trackUid)return null;const users=Object.values(window.multiplayer?.visibleUsers??{});for(const user of users){if(String(user?.id??user?.uid??"")!==String(trackUid))continue;const distanceFeet=Number(user?.distance);return Number.isFinite(distanceFeet)?distanceFeet/6076.11549:null}return null},_getTrackUpdateAgeMs:function(trackUid,lat,lon,altM){const uid=String(trackUid??"");if(!uid)return 0;const now=Date.now(),cache=this._trackUpdateByUid[uid];return cache?cache.lat!==lat||cache.lon!==lon||cache.altM!==altM?(cache.lat=lat,cache.lon=lon,cache.altM=altM,cache.changedMs=now,0):now-cache.changedMs:(this._trackUpdateByUid[uid]={lat:lat,lon:lon,altM:altM,changedMs:now},0)},_predictTrackedPosition:function(lat,lon,altM,headingDeg,speedKts,lastSeenMs){const dtSec=Math.max(0,(Date.now()-lastSeenMs)/1e3);if(!dtSec)return{lat:lat,lon:lon,altM:altM};const travelM=speedKts/1.94384*dtSec,hdgRad=headingDeg*Math.PI/180;return{lat:lat+travelM*Math.cos(hdgRad)/110540,lon:lon+travelM*Math.sin(hdgRad)/(111320*Math.cos(lat*Math.PI/180)),altM:altM}},_setLockState:function(nextState){const state=String(nextState??"FREE").toUpperCase();OptionModule.setOption("TGP","LOCK",state),this._lockMode=state;const lockButtons=this.leftButtons?.filter(button=>"LOCK"===button?.key)??[];for(const button of lockButtons){const index=button.states.findIndex(entry=>entry===state);button.stateIndex=index>=0?index:0}},_getCaptureOrientation:function(isLocked){const animVals=window.geofs?.animation?.values??{},acHeading=Number(animVals.heading360??animVals.heading??0),acPitch=-Number(animVals.atilt??0),acRoll=Number(animVals.aroll??0),normDeg=a=>(a%360+540)%360-180;let finalH,finalP,finalR;if(isLocked&&this._lockTargetKey){const viewer=window.geofs?.api?.viewer;let refLat=Number(window.geofs?.camera?.lla?.[0]),refLon=Number(window.geofs?.camera?.lla?.[1]),refAlt=Number(window.geofs?.camera?.lla?.[2]);const sceneCamera=viewer?.scene?.camera;if("undefined"!=typeof Cesium&&sceneCamera?.positionWC){const carto=Cesium.Cartographic.fromCartesian(sceneCamera.positionWC);refLat=Cesium.Math.toDegrees(carto.latitude),refLon=Cesium.Math.toDegrees(carto.longitude),refAlt=Number(carto.height)}const tgtLat=Number(this._targetLat),tgtLon=Number(this._targetLon),tgtAlt=Number(this._targetAltM);if(Number.isFinite(refLat)&&Number.isFinite(refLon)&&Number.isFinite(refAlt)&&Number.isFinite(tgtLat)&&Number.isFinite(tgtLon)&&Number.isFinite(tgtAlt)){const refEcef=this._llaToEcef(refLat,refLon,refAlt),tgtEcef=this._llaToEcef(tgtLat,tgtLon,tgtAlt),dX=tgtEcef[0]-refEcef[0],dY=tgtEcef[1]-refEcef[1],dZ=tgtEcef[2]-refEcef[2],[dN,dE,dU]=this._ecefDeltaToNeu(refLat,refLon,dX,dY,dZ),hdgRad=acHeading*Math.PI/180,pitchRad=acPitch*Math.PI/180,rollRad=-acRoll*Math.PI/180,xH=dN*Math.cos(hdgRad)+dE*Math.sin(hdgRad),yH=-dN*Math.sin(hdgRad)+dE*Math.cos(hdgRad),zH=dU,xP=xH*Math.cos(pitchRad)+zH*Math.sin(pitchRad),yP=yH,zP=-xH*Math.sin(pitchRad)+zH*Math.cos(pitchRad),xB=xP,yB=yP*Math.cos(rollRad)-zP*Math.sin(rollRad),zB=yP*Math.sin(rollRad)+zP*Math.cos(rollRad);finalH=normDeg(180*Math.atan2(yB,xB)/Math.PI+this._relYaw),finalP=Math.max(-85,Math.min(85,180*Math.atan2(zB,Math.hypot(xB,yB))/Math.PI+this._relPitch)),finalR=0}else finalH=normDeg(this._targetWorldH-acHeading+this._relYaw),finalP=Math.max(-85,Math.min(85,this._targetWorldP-acPitch+this._relPitch)),finalR=0}else finalH=this._camYaw,finalP=this._camPitch,finalR=0;return{finalH:finalH,finalP:finalP,finalR:finalR}},_resolveCurrentAimGroundPoint:function(){const viewer=window.geofs?.api?.viewer,mode1=window.geofs?.camera?.modes?.[1];if(!viewer?.scene||!mode1||"undefined"==typeof Cesium)return null;const fovRad=Number(getOption("TGP","RANGE",30))*Math.PI/180,isLocked="FREE"!==OptionModule.getOption("TGP","LOCK","FREE"),{finalH:finalH,finalP:finalP,finalR:finalR}=this._getCaptureOrientation(isLocked),oPos=[...mode1.position],oOri=[...mode1.orientation],oFov=mode1.FOV,oCurr=mode1.orientations?[...mode1.orientations.current]:[...oOri],oLast=mode1.orientations?[...mode1.orientations.last]:[...oOri],frustum=viewer.scene.camera.frustum,origFrustumFov=frustum.fov;try{mode1.position=[oPos[0],oPos[1],-1.2],mode1.orientation=[finalH,finalP,finalR],mode1.FOV=fovRad,mode1.orientations&&(mode1.orientations.current=[finalH,finalP,finalR],mode1.orientations.last=[finalH,finalP,finalR]),frustum.fov=fovRad,viewer.scene.render(viewer.clock.currentTime);const vc=viewer.canvas,ray=viewer.scene.camera.getPickRay(new Cesium.Cartesian2(vc.width/2,vc.height/2)),hit=ray?viewer.scene.globe.pick(ray,viewer.scene):null;if(!hit)return null;const carto=Cesium.Cartographic.fromCartesian(hit);return carto?{lat:Cesium.Math.toDegrees(carto.latitude),lon:Cesium.Math.toDegrees(carto.longitude),altM:Number(carto.height)||0}:null}finally{mode1.position=oPos,mode1.orientation=oOri,mode1.FOV=oFov,frustum.fov=origFrustumFov,mode1.orientations&&(mode1.orientations.current=oCurr,mode1.orientations.last=oLast)}},_applyLockedPoint:function(point,lockState="FIX",callsign="FIX"){if(!point)return!1;const lat=Number(point.lat),lon=Number(point.lon),altM=Number(point.altM)||0;return!(!Number.isFinite(lat)||!Number.isFinite(lon))&&(this._targetLat=lat,this._targetLon=lon,this._targetAltM=altM,this._targetAltFt=Math.round(3.28084*altM),this._lockTargetKey=`${lockState}:${Date.now()}`,this._lockedCallsign=callsign,this._relYaw=0,this._relPitch=0,this._setLockState(lockState),!0)},_lockActiveMarkpointFromCartridge:function(){const cartridge=owner.getAddon?.()?.dataCartridge;let markpoint=cartridge?.getActiveMarkpoint?.();if(!markpoint){const markpoints=cartridge?.getMarkpoints?.()??[];markpoints.length&&(markpoint=markpoints[0],cartridge?.setActiveMarkpoint?.(0))}if(!markpoint)return!1;const target=owner._resolveMarkpointTarget(markpoint);return!!target&&this._applyLockedPoint(target,"MRK","MRK")},_updateSlew:function(x,y){const stepBtn=this.rightButtons.find(b=>"SLEW_STEP"===b.key),step=Number(stepBtn.states[stepBtn.stateIndex]);"FREE"===this._lockMode?(this._camYaw=(this._camYaw+x*step+360)%360,this._camYaw>180&&(this._camYaw-=360),this._camPitch=Math.max(-85,Math.min(30,this._camPitch+y*step))):(this._relYaw=(this._relYaw+x*step+360)%360,this._relYaw>180&&(this._relYaw-=360),this._relPitch=Math.max(-85,Math.min(85,this._relPitch+y*step)))},_resetSlew:function(){this._camYaw=0,this._camPitch=0,this._relYaw=0,this._relPitch=0},_stepRange:function(direction){const rangeButtons=this.leftButtons.filter(b=>"RANGE"===b.key);if(!rangeButtons.length)return;const states=rangeButtons[0].states,selected=OptionModule.getOption("TGP","RANGE",states[rangeButtons[0].stateIndex]),currentIndex=Math.max(0,states.findIndex(s=>s===selected)),nextIndex=Math.max(0,Math.min(states.length-1,currentIndex+direction)),nextState=states[nextIndex];OptionModule.setOption("TGP","RANGE",nextState);for(const button of rangeButtons)button.stateIndex=nextIndex},_updateLock:function(){if("FREE"===this._lockMode)return void this._resetLockData();let tLat=null,tLon=null,tAltM=0,cs="UNKNOWN",targetKey=null,trackUid=null,targetHeadingDeg=0,targetSpeedKts=0;if("TRK"===this._lockMode){const map=getMapModule(),nav=map?.getSceneData?.()??null,traffic=map?.getFilteredTraffic?.(nav?.traffic??[],!0)??[],uid=map?.getSelectedTrafficUid?.(traffic)??null,target=traffic.find(c=>String(c?.uid??"")===String(uid??""))??null;if(target){tLat=Number(target.lat),tLon=Number(target.lon),tAltM=Number(target.alt)||0,cs=target.callsign??target.cs??"TRACK",trackUid=String(target.uid??uid??""),targetKey=`TRK:${String(target.uid??uid??cs)}`,this._targetAltFt=Math.round(3.28084*tAltM),targetHeadingDeg=Number(target.headingDeg??target.trackDeg??target.heading??target.hdg??0),targetSpeedKts=Number(target.speedKts??0),this._targetHdg=targetHeadingDeg;if("ADVANCED"===getOption("TGP","TRACK","SIMPLE")){const ageMs=this._getTrackUpdateAgeMs(trackUid,tLat,tLon,tAltM),predicted=this._predictTrackedPosition(tLat,tLon,tAltM,targetHeadingDeg,targetSpeedKts,Date.now()-ageMs);tLat=predicted.lat,tLon=predicted.lon,tAltM=predicted.altM}}}else if("WPT"===this._lockMode){const waypointArray=window.geofs?.flightPlan?.waypointArray,wp=Array.isArray(waypointArray)?waypointArray.find(w=>w?.selected):null;wp&&(tLat=Number(wp.lat),tLon=Number(wp.lon),tAltM=.3048*(Number(wp.alt)||0),cs=String(wp.ident??wp.name??wp.id??"WPT"),targetKey=`WPT:${cs}`,this._targetAltFt=Math.round(3.28084*tAltM))}else"FIX"!==this._lockMode&&"MARK"!==this._lockMode&&"MRK"!==this._lockMode||(tLat=Number(this._targetLat),tLon=Number(this._targetLon),tAltM=Number(this._targetAltM)||0,cs="FIX"===this._lockMode?"FIX":"MRK",targetKey=String(this._lockTargetKey??`${this._lockMode}:POINT`),this._targetAltFt=Math.round(3.28084*tAltM));const own=window.geofs?.aircraft?.instance?.llaLocation;if(null===tLat||null===tLon||!Number.isFinite(tLat)||!Number.isFinite(tLon)||!own)return void this._resetLockData();targetKey&&targetKey!==this._lockTargetKey&&(this._lockTargetKey=targetKey,this._relYaw=0,this._relPitch=0,this._closureKts=0);const ownEcef=this._llaToEcef(own[0],own[1],own[2]),tgtEcef=this._llaToEcef(tLat,tLon,tAltM),dX=tgtEcef[0]-ownEcef[0],dY=tgtEcef[1]-ownEcef[1],dZ=tgtEcef[2]-ownEcef[2],[dN,dE,dU]=this._ecefDeltaToNeu(own[0],own[1],dX,dY,dZ),rel=this._computeRelativePositionMeters(own[0],own[1],own[2],tLat,tLon,tAltM),distH=Math.hypot(dN,dE),trkDistNm="TRK"===this._lockMode?this._getTrackDistanceNmFromMultiplayer(trackUid):null,distNm="TRK"===this._lockMode?null!==trkDistNm?Math.round(10*trkDistNm)/10:null:Math.round(10*rel.distNm)/10;this._closureKts=this._computeClosureRateKts(rel.dN,rel.dE,rel.dU,targetHeadingDeg,targetSpeedKts),this._targetWorldH=(180*Math.atan2(dE,dN)/Math.PI+360)%360,this._targetWorldP=180*Math.atan2(dU,distH)/Math.PI,this._targetLat=tLat,this._targetLon=tLon,this._targetAltM=tAltM,this._targetNorthM=dN,this._targetEastM=dE,this._targetUpM=dU,this._lockedCallsign=cs,this._lockedDist=distNm},_resetLockData:function(){this._lockTargetKey=null,this._targetLat=null,this._targetLon=null,this._targetAltM=null,this._targetNorthM=0,this._targetEastM=0,this._targetUpM=0,this._lockedDist=null,this._closureKts=0},_captureFrame:function(fovRad,isLocked){const viewer=window.geofs?.api?.viewer,mode1=window.geofs?.camera?.modes?.[1];if(!viewer?.scene||!mode1)return;const oPos=[...mode1.position],oOri=[...mode1.orientation],oFov=mode1.FOV,oCurr=mode1.orientations?[...mode1.orientations.current]:[...oOri],oLast=mode1.orientations?[...mode1.orientations.last]:[...oOri],{finalH:finalH,finalP:finalP,finalR:finalR}=this._getCaptureOrientation(isLocked);mode1.position=[oPos[0],oPos[1],-1.2],mode1.orientation=[finalH,finalP,finalR],mode1.FOV=fovRad,mode1.orientations&&(mode1.orientations.current=[finalH,finalP,finalR],mode1.orientations.last=[finalH,finalP,finalR]);const frustum=viewer.scene.camera.frustum,origFrustumFov=frustum.fov;frustum.fov=fovRad,viewer.scene.render(viewer.clock.currentTime),frustum.fov=origFrustumFov;const vc=viewer.canvas;this._snap.width===vc.width&&this._snap.height===vc.height||(this._snap.width=vc.width,this._snap.height=vc.height,this._snapCoverCrop=null,this._snapCtx=null),this._snapCtx||(this._snapCtx=this._snap.getContext("2d",{alpha:!1})),this._snapCtx.drawImage(vc,0,0),mode1.position=oPos,mode1.orientation=oOri,mode1.FOV=oFov,mode1.orientations&&(mode1.orientations.current=oCurr,mode1.orientations.last=oLast)},_queueCaptureFrame:function(fovRad,isLocked){this._captureFovRad=fovRad,this._captureIsLocked=isLocked,this._captureQueued||(this._captureQueued=!0,requestAnimationFrame(()=>{this._captureQueued=!1,this._captureFrame(this._captureFovRad,this._captureIsLocked)}))},_drawSnapshot:function(ctx,w,h){const srcW=this._snap.width,srcH=this._snap.height,dstW=w,dstH=h;let crop=this._snapCoverCrop;if(!crop||crop.srcW!==srcW||crop.srcH!==srcH||crop.dstW!==dstW||crop.dstH!==dstH){const scale=Math.max(dstW/srcW,dstH/srcH),sw=dstW/scale,sh=dstH/scale;crop={srcW:srcW,srcH:srcH,dstW:dstW,dstH:dstH,sx:(srcW-sw)/2,sy:(srcH-sh)/2,sw:sw,sh:sh},this._snapCoverCrop=crop}ctx.drawImage(this._snap,crop.sx,crop.sy,crop.sw,crop.sh,0,0,dstW,dstH)},_applyImageMode:function(ctx,imgMode){if("DAY"===imgMode)return;const w=ctx.canvas.width,h=ctx.canvas.height,id=ctx.getImageData(0,0,w,h),d=id.data;for(let i=0;i0&&ctx.fillRect(barX-4,barY+44*(1-frac),4,44*frac);for(let i=0;i<=4;i+=1){const ty=barY+11*i,len=2===i?8:4;ctx.beginPath(),ctx.moveTo(barX,ty),ctx.lineTo(barX+len,ty),ctx.stroke()}if(ctx.font="bold 18px monospace",ctx.textAlign="left",ctx.fillText("A/A",70,60),ctx.textAlign="right",ctx.fillText(`FOV ${fovDeg}°`,w-50,60),ctx.textAlign="center",isLocked&&this._lockTargetKey?ctx.fillText(`TRK ◆ ${this._lockedCallsign}`,cx,60):ctx.fillText("ACQ",cx,60),isLocked&&this._lockTargetKey){ctx.font="bold 17px monospace",ctx.textAlign="left",ctx.fillText(`ALT ${this._targetAltFt} ft`,70,h-151),null!==this._lockedDist&&ctx.fillText(`RNG ${this._lockedDist} NM`,70,h-124),Math.abs(this._closureKts)>200&&(ctx.fillStyle="#ffcc00");const vcSign=this._closureKts>=0?"+":"";ctx.fillText(`CLR ${vcSign}${this._closureKts} kts`,70,h-97),ctx.fillStyle=hud,ctx.fillText(`BRG ${Math.round(this._targetWorldH)}°`,70,h-70)}else ctx.textAlign="center",ctx.font="bold 16px monospace",ctx.fillText("NO TARGET SELECTED",cx,h-70)},render:function(renderer,renderContext){const ctx=renderContext?.ctx??renderer?.canvasAPI?.context,w=renderContext?.w??512,h=renderContext?.h??512,color=renderContext?.color??"#00ff66";if(!ctx)return;this._snap||(this._snap=document.createElement("canvas"));const page=renderContext?.page;if(!page)return;owner.activePage=this,owner.pendingMarkpoint&&(this._markPoint=owner.pendingMarkpoint,this._applyLockedPoint(owner.pendingMarkpoint,"MRK","MRK"),this._setLockState("MRK"),owner.pendingMarkpoint=null);const imgMode=getOption("TGP","STYLE","DAY"),fovDeg=Number(getOption("TGP","RANGE",30)),fovRad=fovDeg*Math.PI/180,frequency=Number(getOption("TGP","FREQUENCY",4)),isPoweredOn="ON"===String(getOption("TGP","POWER","OFF")).toUpperCase();if(this._activeMode=getOption("WPN","MODE","A/G"),this._lockMode=getOption("TGP","LOCK","FREE"),!isPoweredOn)return ctx.save(),ctx.setTransform(1,0,0,1,0,0),ctx.fillStyle="#000000",ctx.fillRect(0,0,w,h),ctx.fillStyle=color,ctx.textAlign="center",ctx.textBaseline="middle",ctx.font=`bold ${Math.round(.075*h)}px monospace`,ctx.fillText("TGP OFF",.5*w,.5*h),void ctx.restore();const mode=getMode();"MARK"!==mode||["FREE","FIX","MARK"].includes(this._lockMode)||(this._setLockState("FREE"),this._lockMode="FREE",this._resetLockData()),"MARK"!==mode&&["FIX","MARK"].includes(this._lockMode)&&(this._setLockState("FREE"),this._lockMode="FREE",this._resetLockData());const isLocked="FREE"!==this._lockMode,isAA="A/A"===this._activeMode;this._updateLock(),this._tick+=1,this._tick%frequency===0&&this._queueCaptureFrame(fovRad,isLocked),ctx.save(),ctx.setTransform(1,0,0,1,0,0),this._snap?.width>0&&this._drawStyledSnapshot(ctx,w,h,imgMode);const hud=isLocked?"#ff0000":color;ctx.strokeStyle=hud,ctx.fillStyle=hud,ctx.lineWidth=2,isAA?this._drawAaHud(ctx,w,h,fovDeg,isLocked,hud):this._drawAgHud(ctx,w,h,fovDeg,isLocked),ctx.restore()}}),!0}}window.TargetingPodModule=TargetingPodModule;class F18HudModule{static HUD_PHYSICAL_HEIGHT_M=.3;static HUD_PARALLAX_GAIN=1.65;static CAMERA_TO_HUD_DISTANCE_M=.92;static DEFAULT_COLOR="#00ff00";static RAD_TO_DEG=180/Math.PI;static DEG_TO_RAD=Math.PI/180;static LADDER_TICK_RANGE_DEG=85;static REFERENCE_MOVEMENT_MIN_METERS=.01;static FLIGHT_PATH_REFERENCE_REPLACEMENT_DEG=3;constructor(dependencies={}){this.dependencies={optionModule:dependencies.optionModule??OptionModule,helperModule:dependencies.helperModule??HelperModule,cameraModule:dependencies.cameraModule??CameraModule,mfdModule:dependencies.mfdModule??MfdModule,hudCombinerConfig:dependencies.hudCombinerConfig??null,getAddon:dependencies.getAddon??(()=>window.BasePlugin?.getActiveAddon?.()??null)},this.originalRenderer=null,this.installed=!1,this.isPitchLadderCaged=!1,this.isHudProjectionDebug=!1,this.lastHudProjectionDebugAt=0,this.hasReportedProjectionFailure=!1,this.fpvState={lastLat:null,lastLon:null,lastAlt:null,relAzDeg:0,relElDeg:0,valid:!1},this.referenceFlightPathState={previousAircraftPosition:null},this.maxG=1}getAddon(){return this.dependencies.getAddon?.()??null}getOption(pageTitle,buttonKey,fallback=null){return this.dependencies.optionModule?.getOption?.(pageTitle,buttonKey,fallback)}setOption(pageTitle,buttonKey,value){return this.dependencies.optionModule?.setOption?.(pageTitle,buttonKey,value)}getOptionValue(pageTitle,buttonKey,fallback=null){return this.dependencies.optionModule?.getOptionValue?.(pageTitle,buttonKey,fallback)}getMfdBrightnessFactor(){return this.getAddon()?.mfd?.getMfdBrightnessFactor?.()??.6}applyBrightnessToHexColor(color,factor){return this.getAddon()?.mfd?.applyBrightnessToHexColor?.(color,factor)??color}getWpnModeFromOptions(){return this.getOption("WPN","MODE","NAV")}getWpnModeLoadout(mode){return this.getAddon()?.weapons?.getModeLoadout?.(mode)??null}getSelectedWpnQuantityLine(mode,modeLoadout){return this.getAddon()?.weapons?.getSelectedQuantityLine?.(mode,modeLoadout)??"N/A"}updateWpnRearmState(){return this.getAddon()?.weapons?.updateRearmState?.()}isWpnFireFlashVisible(){return this.getAddon()?.weapons?.isFireFlashVisible?.()??!1}getWpnActionFlashLabel(){return this.getAddon()?.weapons?.getActionFlashLabel?.()??"FIRE"}getNavModule(){return this.getAddon()?.nav??null}getCommunicationModule(){return this.getAddon()?.communication??null}registerMfdPages(mfdModule=this.dependencies.mfdModule){return mfdModule.registerPage({title:"HUD",leftButtons:[{key:"HUD",label:"HUD",states:["F-18","DEFAULT"],stateIndex:0,onClick:({nextState:nextState})=>{this.setMode(nextState)}},{key:"BRIGHT",label:"BRT",states:["NORM","DAY","NIGHT"],stateIndex:0},{key:"LEVEL",label:"LVL",states:["FULL","DECLUTTERED","MIN"],stateIndex:0},{key:"MAX_G",label:"MAXG",states:["RESET"],stateIndex:0,onClick:()=>{const currentLoadFactor=window.geofs?.animation?.values?.loadFactor;this.maxG=Number.isFinite(currentLoadFactor)?currentLoadFactor:1}}],rightButtons:[{key:"COLOR",label:"COLOR",states:["GREEN","WHITE","BLUE","RED"],values:["#00FF00","#FFFFFF","#00fffb","#FF0000"],stateIndex:0}],lines:[]}),!0}static isAircraftActive(){return Boolean(window.BasePlugin?.getActivePlugin?.()?.isAircraftActive?.())}install(){if(this.installed)return!0;const renderers=window.instruments?.renderers;if(!renderers?.genericHUD)return!1;window.__GeoFsOriginalGenericHudRenderer||(window.__GeoFsOriginalGenericHudRenderer=renderers.genericHUD),this.originalRenderer=window.__GeoFsOriginalGenericHudRenderer;const self=this;return renderers.genericHUD=function(renderer){if(!F18HudModule.isAircraftActive()||"DEFAULT"===self.getOption("HUD","HUD","F-18"))return window.__GeoFsOriginalGenericHudRenderer.call(this,renderer);self.renderF18Hud(renderer)},this.installed=!0,!0}getMode(){return this.getOption("HUD","HUD","F-18")}setMode(mode){return this.setOption("HUD","HUD",mode),this.ensureLoaded(),mode}ensureLoaded(){return"DEFAULT"===this.getOption("HUD","HUD","F-18")?(this.restore(),!0):!!this.install()}restore(){window.__GeoFsOriginalGenericHudRenderer&&window.instruments?.renderers&&(window.instruments.renderers.genericHUD=window.__GeoFsOriginalGenericHudRenderer),this.originalRenderer=null,this.installed=!1}static isFiniteVector(vector,length=3){return Array.isArray(vector)&&vector.length===length&&vector.every(value=>Number.isFinite(value))}static addVectors(left,right){return[left[0]+right[0],left[1]+right[1],left[2]+right[2]]}static subtractVectors(left,right){return[left[0]-right[0],left[1]-right[1],left[2]-right[2]]}static scaleVector(vector,scalar){return[vector[0]*scalar,vector[1]*scalar,vector[2]*scalar]}static dotProduct(left,right){return left[0]*right[0]+left[1]*right[1]+left[2]*right[2]}static crossProduct(left,right){return[left[1]*right[2]-left[2]*right[1],left[2]*right[0]-left[0]*right[2],left[0]*right[1]-left[1]*right[0]]}static normalizeVector(vector){if(!this.isFiniteVector(vector))return null;const length=Math.hypot(vector[0],vector[1],vector[2]);return!Number.isFinite(length)||length<1e-8?null:this.scaleVector(vector,1/length)}static angleBetweenDegrees(left,right){if(!left||!right)return null;const cosine=Math.max(-1,Math.min(1,this.dotProduct(left,right)));return Math.acos(cosine)*this.RAD_TO_DEG}static rotateVector(vector,axis,angleRad){const normalizedAxis=this.normalizeVector(axis);if(!normalizedAxis)return null;const cosine=Math.cos(angleRad),sine=Math.sin(angleRad);return this.addVectors(this.addVectors(this.scaleVector(vector,cosine),this.scaleVector(this.crossProduct(normalizedAxis,vector),sine)),this.scaleVector(normalizedAxis,this.dotProduct(normalizedAxis,vector)*(1-cosine)))}static isValidCombinerConfig(config){if(!config||!this.isFiniteVector(config.origin)||!this.isFiniteVector(config.normal)||!this.isFiniteVector(config.right)||!this.isFiniteVector(config.up)||!Array.isArray(config.outline)||config.outline.length<3)return!1;const normal=this.normalizeVector(config.normal),right=this.normalizeVector(config.right),up=this.normalizeVector(config.up);return Boolean(normal&&right&&up&&Math.abs(this.dotProduct(normal,right))<1e-4&&Math.abs(this.dotProduct(normal,up))<1e-4&&Math.abs(this.dotProduct(right,up))<1e-4&&config.outline.every(point=>Array.isArray(point)&&2===point.length&&point.every(value=>Number.isFinite(value))))}reportProjectionFailure(reason){this.hasReportedProjectionFailure||(this.hasReportedProjectionFailure=!0,console.warn(`[F18HudModule] Attitude HUD projection unavailable: ${reason}`))}getCameraCombinerDistance(frame){return Math.hypot(frame.cameraPosition[0]-frame.combiner.origin[0],frame.cameraPosition[1]-frame.combiner.origin[1],frame.cameraPosition[2]-frame.combiner.origin[2])}projectCombinerPoint(frame,point){const relative=F18HudModule.subtractVectors(point,frame.combiner.origin),right=F18HudModule.dotProduct(relative,frame.combiner.right),up=F18HudModule.dotProduct(relative,frame.combiner.up),{minRight:minRight,maxRight:maxRight,minUp:minUp,maxUp:maxUp}=frame.combiner.bounds,width=maxRight-minRight,height=maxUp-minUp;return width<=0||height<=0?null:{x:(right-minRight)/width*frame.viewport.width,y:(maxUp-up)/height*frame.viewport.height,worldPoint:point}}projectWorldDirection(frame,direction){const normalizedDirection=F18HudModule.normalizeVector(direction);if(!normalizedDirection)return null;const denominator=F18HudModule.dotProduct(normalizedDirection,frame.combiner.normal);if(Math.abs(denominator)<1e-8)return null;const distance=F18HudModule.dotProduct(F18HudModule.subtractVectors(frame.combiner.origin,frame.cameraPosition),frame.combiner.normal)/denominator;if(!Number.isFinite(distance)||distance<=0)return null;const point=F18HudModule.addVectors(frame.cameraPosition,F18HudModule.scaleVector(normalizedDirection,distance));return this.projectCombinerPoint(frame,point)}collectHudProjectionInputs(renderer,ac){const config=this.dependencies.hudCombinerConfig,viewer=window.geofs?.api?.viewer,sceneCamera=viewer?.scene?.camera??viewer?.camera,CesiumApi=window.Cesium,canvas=renderer?.canvasAPI?.canvas??renderer?.canvasAPI?.context?.canvas,lla=ac?.llaLocation;if(!F18HudModule.isValidCombinerConfig(config))return this.reportProjectionFailure("HUD combiner configuration is invalid"),null;if(!(canvas&&viewer?.canvas&&sceneCamera?.positionWC&&CesiumApi&&Array.isArray(lla)&&F18HudModule.isFiniteVector(lla)&&ac?.object3d?.setVectorWorldPosition))return this.reportProjectionFailure("required GeoFS camera, aircraft, or Cesium data is missing"),null;const ellipsoid=viewer.scene?.globe?.ellipsoid??CesiumApi.Ellipsoid.WGS84,aircraftPosition=CesiumApi.Cartesian3.fromDegrees(lla[1],lla[0],lla[2]),currentAircraftPosition=[aircraftPosition.x,aircraftPosition.y,aircraftPosition.z],enuToWorld=CesiumApi.Transforms.eastNorthUpToFixedFrame(aircraftPosition,ellipsoid),transformSamples=new Map,isTrackedTransformPoint=localPoint=>this.isHudProjectionDebug&&(localPoint.every((value,index)=>value===config.origin[index])||localPoint.every(value=>0===value)),localPointToWorld=localPoint=>{const localEnu=ac.object3d.setVectorWorldPosition([...localPoint]);if(!F18HudModule.isFiniteVector(localEnu))return null;const world=CesiumApi.Matrix4.multiplyByPoint(enuToWorld,new CesiumApi.Cartesian3(localEnu[0],localEnu[1],localEnu[2]),new CesiumApi.Cartesian3),worldPoint=[world.x,world.y,world.z];return isTrackedTransformPoint(localPoint)&&transformSamples.set(localPoint.join(","),{localPoint:[...localPoint],setVectorWorldPositionResult:[...localEnu],versionAWorld:worldPoint}),worldPoint},combinerOrigin=localPointToWorld(config.origin),normalPoint=localPointToWorld(F18HudModule.addVectors(config.origin,config.normal)),rightPoint=localPointToWorld(F18HudModule.addVectors(config.origin,config.right)),upPoint=localPointToWorld(F18HudModule.addVectors(config.origin,config.up));if(!(combinerOrigin&&normalPoint&&rightPoint&&upPoint))return this.reportProjectionFailure("aircraft-local combiner transform failed"),null;const combiner={origin:combinerOrigin,normal:F18HudModule.normalizeVector(F18HudModule.subtractVectors(normalPoint,combinerOrigin)),right:F18HudModule.normalizeVector(F18HudModule.subtractVectors(rightPoint,combinerOrigin)),up:F18HudModule.normalizeVector(F18HudModule.subtractVectors(upPoint,combinerOrigin))};if(!combiner.normal||!combiner.right||!combiner.up)return this.reportProjectionFailure("combiner axes are degenerate after transformation"),null;if(combiner.outline=config.outline.map(([rightOffset,upOffset])=>localPointToWorld(F18HudModule.addVectors(config.origin,F18HudModule.addVectors(F18HudModule.scaleVector(config.right,rightOffset),F18HudModule.scaleVector(config.up,upOffset))))),combiner.outline.some(point=>!point))return this.reportProjectionFailure("aircraft-local combiner outline transform failed"),null;combiner.bounds={minRight:Math.min(...combiner.outline.map(point=>F18HudModule.dotProduct(F18HudModule.subtractVectors(point,combiner.origin),combiner.right))),maxRight:Math.max(...combiner.outline.map(point=>F18HudModule.dotProduct(F18HudModule.subtractVectors(point,combiner.origin),combiner.right))),minUp:Math.min(...combiner.outline.map(point=>F18HudModule.dotProduct(F18HudModule.subtractVectors(point,combiner.origin),combiner.up))),maxUp:Math.max(...combiner.outline.map(point=>F18HudModule.dotProduct(F18HudModule.subtractVectors(point,combiner.origin),combiner.up)))};const cameraPosition=sceneCamera.positionWC,cameraWorld=[cameraPosition.x,cameraPosition.y,cameraPosition.z],inverseEnuToWorld=CesiumApi.Matrix4.inverseTransformation(enuToWorld,new CesiumApi.Matrix4),cameraEnuCartesian=CesiumApi.Matrix4.multiplyByPoint(inverseEnuToWorld,cameraPosition,new CesiumApi.Cartesian3),cameraEnu=[cameraEnuCartesian.x,cameraEnuCartesian.y,cameraEnuCartesian.z],earthUpCartesian=ellipsoid.geodeticSurfaceNormal(aircraftPosition,new CesiumApi.Cartesian3),earthUp=F18HudModule.normalizeVector([earthUpCartesian.x,earthUpCartesian.y,earthUpCartesian.z]),aircraftOrigin=localPointToWorld([0,0,0]),aircraftForwardPoint=localPointToWorld([0,1,0]),boresightDirection=aircraftOrigin&&aircraftForwardPoint?F18HudModule.normalizeVector(F18HudModule.subtractVectors(aircraftForwardPoint,aircraftOrigin)):null,airVelocity=F18HudModule.isFiniteVector(ac.airVelocity)?[...ac.airVelocity]:null,velocity=F18HudModule.isFiniteVector(ac.velocity)?[...ac.velocity]:null,localVelocity=airVelocity??velocity,velocitySource=airVelocity?"airVelocity":velocity?"velocity":null;let flightPathDirection=null,velocityWorld=null;if(localVelocity){const transformedVelocity=CesiumApi.Matrix4.multiplyByPointAsVector(enuToWorld,new CesiumApi.Cartesian3(localVelocity[0],localVelocity[1],localVelocity[2]),new CesiumApi.Cartesian3);velocityWorld=[transformedVelocity.x,transformedVelocity.y,transformedVelocity.z],flightPathDirection=F18HudModule.normalizeVector([transformedVelocity.x,transformedVelocity.y,transformedVelocity.z])}const previousAircraftPosition=this.referenceFlightPathState.previousAircraftPosition,movementVector=previousAircraftPosition?F18HudModule.subtractVectors(currentAircraftPosition,previousAircraftPosition):null,movementDistance=movementVector?Math.hypot(...movementVector):0,referenceFlightPathDirection=movementDistance>F18HudModule.REFERENCE_MOVEMENT_MIN_METERS?F18HudModule.normalizeVector(movementVector):null;this.referenceFlightPathState.previousAircraftPosition=currentAircraftPosition;const flightPathReferenceDifferenceDeg=F18HudModule.angleBetweenDegrees(flightPathDirection,referenceFlightPathDirection),shouldUseReferenceFlightPath=referenceFlightPathDirection&&(!flightPathDirection||null!=flightPathReferenceDifferenceDeg&&flightPathReferenceDifferenceDeg>F18HudModule.FLIGHT_PATH_REFERENCE_REPLACEMENT_DEG),fpvFlightPathDirection=shouldUseReferenceFlightPath?referenceFlightPathDirection:flightPathDirection,fpvFlightPathSource=shouldUseReferenceFlightPath?"referenceMovement":velocitySource,frame={Cesium:CesiumApi,ellipsoid:ellipsoid,viewport:{width:canvas.width,height:canvas.height},cameraPosition:cameraWorld,earthUp:earthUp,combiner:combiner,boresightDirection:boresightDirection,flightPathDirection:flightPathDirection,referenceFlightPathDirection:referenceFlightPathDirection,flightPathReferenceDifferenceDeg:flightPathReferenceDifferenceDeg,fpvFlightPathDirection:fpvFlightPathDirection,fpvFlightPathSource:fpvFlightPathSource,movementDistance:movementDistance,airVelocity:airVelocity,velocity:velocity,velocityWorld:velocityWorld,velocitySource:velocitySource,combinerConfigOrigin:[...config.origin]},originTransform=transformSamples.get(config.origin.join(",")),rootTransform=transformSamples.get("0,0,0");if(originTransform){const distanceBetween=(left,right)=>Math.hypot(left[0]-right[0],left[1]-right[1],left[2]-right[2]);frame.transformDiagnostics={origin:originTransform,root:rootTransform??null,cameraEnu:cameraEnu,distanceA:distanceBetween(cameraWorld,originTransform.versionAWorld),distanceBWithEcefCamera:distanceBetween(cameraWorld,originTransform.setVectorWorldPositionResult),distanceBInEnu:distanceBetween(cameraEnu,originTransform.setVectorWorldPositionResult)}}return frame.outline=combiner.outline.map(point=>this.projectCombinerPoint(frame,point)),earthUp&&boresightDirection&&!frame.outline.some(point=>!point)?frame:(this.reportProjectionFailure("Earth frame, boresight, or combiner outline could not be projected"),null)}collectHudGeometryDebugData(frame,attitudeGeometry,flightPathSymbol,anim,ac){const pointDistance=(left,right)=>left&&right?Math.hypot(right.x-left.x,right.y-left.y):null;return{aircraftPitchDeg:-Number(anim.atilt??ac.htr?.[1]??0),aircraftRollDeg:Number(anim.aroll??ac.htr?.[2]??0),aircraftHeadingDeg:Number(anim.heading360??anim.heading??ac.htr?.[0]??0),verticalSpeed:Number(anim.climbrate??0),boresightDirection:frame.boresightDirection,flightPathDirection:frame.flightPathDirection,referenceFlightPathDirection:frame.referenceFlightPathDirection,angleBetweenFlightPathDirectionsDeg:frame.flightPathReferenceDifferenceDeg,fpvFlightPathSource:frame.fpvFlightPathSource,movementDistance:frame.movementDistance,velocitySource:frame.velocitySource,airVelocity:frame.airVelocity,velocity:frame.velocity,velocityWorld:frame.velocityWorld,angleBetweenBoresightAndFlightPathDeg:F18HudModule.angleBetweenDegrees(frame.boresightDirection,frame.fpvFlightPathDirection),camera:frame.cameraPosition,configOrigin:frame.combinerConfigOrigin,combiner:frame.combiner.origin,cameraToCombinerDistance:this.getCameraCombinerDistance(frame),transformDiagnostics:frame.transformDiagnostics??null,boresightPosition:frame.projectDirection(frame.boresightDirection),horizonCenter:attitudeGeometry.horizonCenter,ladderZeroCenter:attitudeGeometry.pitch0,fpvPosition:flightPathSymbol?.position??null,flightPathAngleDeg:flightPathSymbol?.flightPathAngleDeg??null,trackOffsetDeg:flightPathSymbol?.trackOffsetDeg??null,attitudePixelsPerDeg:attitudeGeometry.pixelsPerDeg,pitch0:attitudeGeometry.pitch0,pitch5:attitudeGeometry.pitch5,pitch10:attitudeGeometry.pitch10,pitchMinus5:attitudeGeometry.pitchMinus5,pitchMinus10:attitudeGeometry.pitchMinus10,delta0to5:pointDistance(attitudeGeometry.pitch0,attitudeGeometry.pitch5),delta5to10:pointDistance(attitudeGeometry.pitch5,attitudeGeometry.pitch10),horizonToLadderZeroPx:pointDistance(attitudeGeometry.horizonCenter,attitudeGeometry.pitch0),horizonToFpvPx:pointDistance(attitudeGeometry.horizonCenter,flightPathSymbol?.position??null),ladderZeroToFpvPx:pointDistance(attitudeGeometry.pitch0,flightPathSymbol?.position??null)}}reportHudGeometryDiagnostics(debugData){if(!this.isHudProjectionDebug)return;const now=Date.now();now-this.lastHudProjectionDebugAt<1e3||(this.lastHudProjectionDebugAt=now,console.log("[F18HudModule] HUD geometry",debugData),(debugData.cameraToCombinerDistance>2||debugData.cameraToCombinerDistance<.2)&&console.warn("[F18HudModule] Implausible camera-to-combiner distance",{distance:debugData.cameraToCombinerDistance,transformDiagnostics:debugData.transformDiagnostics}))}static getLegacyPixelsPerDegree(height){return height/(2*Math.atan(F18HudModule.HUD_PHYSICAL_HEIGHT_M/2/F18HudModule.CAMERA_TO_HUD_DISTANCE_M)*F18HudModule.RAD_TO_DEG)}getLegacyHudGeometry(w,h){const pixelsPerDeg=F18HudModule.getLegacyPixelsPerDegree(h),hudPhysicalWidthM=F18HudModule.HUD_PHYSICAL_HEIGHT_M*(w/h),pixelsPerDegX=w/(2*Math.atan(hudPhysicalWidthM/2/F18HudModule.CAMERA_TO_HUD_DISTANCE_M)*F18HudModule.RAD_TO_DEG),mode=window.geofs?.camera?.modes?.[1],baseZ=mode?.position?.[2]??this.dependencies.cameraModule?.DEFAULT_HUD_CAMERA_Z,offsetZ=mode?.offsets?.current?.[2]??0;return{pixelsPerDeg:pixelsPerDeg,pixelsPerDegX:pixelsPerDegX,cameraOffsetPx:Math.atan2(baseZ+offsetZ-this.dependencies.cameraModule?.DEFAULT_HUD_CAMERA_Z,F18HudModule.CAMERA_TO_HUD_DISTANCE_M)*F18HudModule.RAD_TO_DEG*pixelsPerDeg*F18HudModule.HUD_PARALLAX_GAIN}}updateLegacyFpvState(lla,ac){if(!Array.isArray(lla)||!F18HudModule.isFiniteVector(lla))return;const fpvState=this.fpvState,[lat,lon,alt]=lla;if(null!=fpvState.lastLat&&null!=fpvState.lastLon&&null!=fpvState.lastAlt){const latRad=lat*Math.PI/180,dNorth=111320*(lat-fpvState.lastLat),dEast=(lon-fpvState.lastLon)*(111320*Math.cos(latRad)),dUp=alt-fpvState.lastAlt,horizontal=Math.hypot(dNorth,dEast);if(horizontal>.01||Math.abs(dUp)>.01){let trackDeg=Math.atan2(dEast,dNorth)*F18HudModule.RAD_TO_DEG;trackDeg<0&&(trackDeg+=360);const fpaDeg=Math.atan2(dUp,Math.max(horizontal,1e-6))*F18HudModule.RAD_TO_DEG,heading=window.geofs?.animation?.values?.heading360??window.geofs?.animation?.values?.heading??ac.htr?.[0]??0;fpvState.relAzDeg=this.dependencies.helperModule?.angleDiffDeg?.(heading,trackDeg)??0,fpvState.relElDeg=fpaDeg- -(ac.htr?.[1]||0),fpvState.valid=!0}}fpvState.lastLat=lat,fpvState.lastLon=lon,fpvState.lastAlt=alt}computeLegacyFpvScreenPosition(camera,cx,symbolCy,pixelsPerDeg,pixelsPerDegX){if(!this.fpvState.valid)return null;const dxBody=-this.fpvState.relAzDeg*pixelsPerDegX,dyBody=-this.fpvState.relElDeg*pixelsPerDeg,cosine=Math.cos(-camera.roll),sine=Math.sin(-camera.roll);return{x:cx+(dxBody*cosine-dyBody*sine),y:symbolCy+(dxBody*sine+dyBody*cosine)}}renderLegacyAttitude(ctx,camera,ac,hudLevel,helperModule,w,h,aoa){const cx=w/2,clipCy=h/2,{pixelsPerDeg:pixelsPerDeg,pixelsPerDegX:pixelsPerDegX,cameraOffsetPx:cameraOffsetPx}=this.getLegacyHudGeometry(w,h),symbolCy=clipCy-cameraOffsetPx;this.updateLegacyFpvState(ac.llaLocation,ac),"FULL"===hudLevel&&F18HudModule.drawLegacyBoresight(ctx,cx,symbolCy,pixelsPerDeg,w,h),F18HudModule.drawLegacyPitchLadder(ctx,camera,ac,cx,clipCy,symbolCy,pixelsPerDeg,w,h);const fpvPos=this.computeLegacyFpvScreenPosition(camera,cx,symbolCy,pixelsPerDeg,pixelsPerDegX);ctx.save(),ctx.beginPath(),ctx.ellipse(cx,clipCy,.28*w,.38*h,0,0,2*Math.PI),ctx.clip();const fpvDrawn=F18HudModule.drawFpv(ctx,fpvPos,w,h);"MIN"!==hudLevel&&F18HudModule.drawIlsDeviationCues(ctx,fpvDrawn,helperModule,w,h),ctx.restore();const isGearDown=window.controls?.gear?.position<.5;F18HudModule.drawLegacyAoaBracket(ctx,fpvDrawn,cx,clipCy,pixelsPerDeg,w,h,aoa,isGearDown)}static drawAoaText(ctx,w,h,aoa){const previousAlign=ctx.textAlign,previousBaseline=ctx.textBaseline;ctx.fillStyle=this.DEFAULT_COLOR,ctx.textAlign="left",ctx.textBaseline="middle",ctx.fillText(`α ${aoa.toFixed(1)}`,.716*w,.93*h),ctx.textAlign=previousAlign,ctx.textBaseline=previousBaseline}static drawBoresight(ctx,boresightPoint,w,h){if(!boresightPoint)return;ctx.save(),ctx.strokeStyle=this.DEFAULT_COLOR,ctx.lineWidth=1.1,ctx.setLineDash([]);const wx=boresightPoint.x,wy=boresightPoint.y,ww=.027*w,wh=.016*h,stub=.01*w;ctx.beginPath(),ctx.moveTo(wx-ww,wy),ctx.lineTo(wx-.55*ww,wy+wh),ctx.lineTo(wx,wy-.15*wh),ctx.lineTo(wx+.55*ww,wy+wh),ctx.lineTo(wx+ww,wy),ctx.stroke(),ctx.beginPath(),ctx.moveTo(wx-ww-stub,wy),ctx.lineTo(wx-ww,wy),ctx.moveTo(wx+ww,wy),ctx.lineTo(wx+ww+stub,wy),ctx.stroke(),ctx.restore()}static getFpvAttitudeGeometry(anim,ac,width,height){const aircraftPitchDeg=-Number(anim.atilt??ac.htr?.[1]??0),aircraftRollDeg=Number(anim.aroll??ac.htr?.[2]??0),pixelsPerDeg=this.getLegacyPixelsPerDegree(height),hudPhysicalWidthM=this.HUD_PHYSICAL_HEIGHT_M*(width/height),pixelsPerDegX=width/(2*Math.atan(hudPhysicalWidthM/2/this.CAMERA_TO_HUD_DISTANCE_M)*this.RAD_TO_DEG),centerX=width/2,centerY=height/2,rollRad=aircraftRollDeg*this.DEG_TO_RAD,horizonOffsetY=aircraftPitchDeg*pixelsPerDeg,projectAngularOffset=(trackOffsetDeg,flightPathAngleDeg)=>{const localX=trackOffsetDeg*pixelsPerDegX,localY=horizonOffsetY-flightPathAngleDeg*pixelsPerDeg;return{x:centerX+Math.cos(rollRad)*localX-Math.sin(rollRad)*localY,y:centerY+Math.sin(rollRad)*localX+Math.cos(rollRad)*localY}};return{centerX:centerX,centerY:centerY,rollRad:rollRad,horizonOffsetY:horizonOffsetY,pixelsPerDeg:pixelsPerDeg,pixelsPerDegX:pixelsPerDegX,projectAngularOffset:projectAngularOffset,horizonCenter:projectAngularOffset(0,0),pitch0:projectAngularOffset(0,0),pitch5:projectAngularOffset(0,5),pitch10:projectAngularOffset(0,10),pitchMinus5:projectAngularOffset(0,-5),pitchMinus10:projectAngularOffset(0,-10)}}static createWorldAttitudeBasis(frame){const horizontalForward=this.normalizeVector(this.subtractVectors(frame.boresightDirection,this.scaleVector(frame.earthUp,this.dotProduct(frame.boresightDirection,frame.earthUp)))),lateral=horizontalForward?this.normalizeVector(this.crossProduct(horizontalForward,frame.earthUp)):null;return horizontalForward&&lateral?{forward:horizontalForward,lateral:lateral}:null}static getFlightPathAttitudePosition(frame,attitudeGeometry){if(!frame.fpvFlightPathDirection||!frame.boresightDirection||!frame.earthUp)return null;const attitudeBasis=this.createWorldAttitudeBasis(frame);if(!attitudeBasis)return null;const upComponent=Math.max(-1,Math.min(1,this.dotProduct(frame.fpvFlightPathDirection,frame.earthUp))),flightPathAngleDeg=Math.asin(upComponent)*this.RAD_TO_DEG,trackOffsetDeg=Math.atan2(this.dotProduct(frame.fpvFlightPathDirection,attitudeBasis.lateral),this.dotProduct(frame.fpvFlightPathDirection,attitudeBasis.forward))*this.RAD_TO_DEG;return{flightPathAngleDeg:flightPathAngleDeg,trackOffsetDeg:trackOffsetDeg,position:attitudeGeometry.projectAngularOffset(trackOffsetDeg,flightPathAngleDeg)}}static applyCombinerClip(ctx,frame){const[first,...rest]=frame.outline;if(!first)return!1;ctx.beginPath(),ctx.moveTo(first.x,first.y);for(const point of rest)ctx.lineTo(point.x,point.y);return ctx.closePath(),ctx.clip(),!0}static drawDebugMarker(ctx,point,color,label){point&&(ctx.save(),ctx.strokeStyle=color,ctx.fillStyle=color,ctx.lineWidth=1.5,ctx.beginPath(),ctx.arc(point.x,point.y,4,0,2*Math.PI),ctx.stroke(),ctx.beginPath(),ctx.moveTo(point.x-6,point.y),ctx.lineTo(point.x+6,point.y),ctx.moveTo(point.x,point.y-6),ctx.lineTo(point.x,point.y+6),ctx.stroke(),ctx.font="10px monospace",ctx.textAlign="left",ctx.textBaseline="bottom",ctx.fillText(label,point.x+7,point.y-7),ctx.restore())}static drawHudDebugMarkers(ctx,debugData){this.drawDebugMarker(ctx,debugData.boresightPosition,"#ff3333","B"),this.drawDebugMarker(ctx,debugData.fpvPosition,"#00ff00","F"),this.drawDebugMarker(ctx,debugData.horizonCenter,"#3399ff","H"),this.drawDebugMarker(ctx,debugData.ladderZeroCenter,"#ffff00","0")}static drawAttitudePitchLadder(ctx,geometry,w,h){ctx.save(),ctx.strokeStyle=this.DEFAULT_COLOR,ctx.fillStyle=this.DEFAULT_COLOR,ctx.font=`${Math.round(.038*h)}px monospace`,ctx.textAlign="center",ctx.textBaseline="middle",ctx.lineWidth=1,ctx.translate(geometry.centerX,geometry.centerY),ctx.rotate(geometry.rollRad),ctx.translate(0,geometry.horizonOffsetY),ctx.beginPath(),ctx.moveTo(.56*-w,0),ctx.lineTo(.56*w,0),ctx.stroke();for(let degree=5;degree<=this.LADDER_TICK_RANGE_DEG;degree+=5)for(const tickY of[-degree*geometry.pixelsPerDeg,degree*geometry.pixelsPerDeg]){const isBelowHorizon=tickY>0,tickDirection=isBelowHorizon?-1:1;ctx.setLineDash(isBelowHorizon?[6,4]:[]),ctx.beginPath(),ctx.moveTo(.14*-w,tickY),ctx.lineTo(.025*-w,tickY),ctx.moveTo(.025*w,tickY),ctx.lineTo(.14*w,tickY),ctx.stroke(),ctx.setLineDash([]),ctx.beginPath(),ctx.moveTo(.14*-w,tickY),ctx.lineTo(.14*-w,tickY+tickDirection*h*.03),ctx.moveTo(.14*w,tickY),ctx.lineTo(.14*w,tickY+tickDirection*h*.03),ctx.stroke(),ctx.fillText(String(degree),.165*-w-3,isBelowHorizon?tickY-7:tickY+7),ctx.fillText(String(degree),.165*w+3,isBelowHorizon?tickY-7:tickY+7)}ctx.restore()}static drawFpv(ctx,fpvPos,w,h){if(!fpvPos)return null;const fpvX=fpvPos.x,fpvY=fpvPos.y;ctx.save(),ctx.strokeStyle=this.DEFAULT_COLOR,ctx.lineWidth=1.4,ctx.setLineDash([]);const r=.012*w,wing=.024*w,tail=.024*h;return ctx.beginPath(),ctx.arc(fpvX,fpvY,r,0,2*Math.PI),ctx.stroke(),ctx.beginPath(),ctx.moveTo(fpvX-r-wing,fpvY),ctx.lineTo(fpvX-r,fpvY),ctx.moveTo(fpvX+r,fpvY),ctx.lineTo(fpvX+r+wing,fpvY),ctx.moveTo(fpvX,fpvY-r),ctx.lineTo(fpvX,fpvY-r-tail),ctx.stroke(),ctx.restore(),{x:fpvX,y:fpvY,r:r,wing:wing}}static drawAoaBracket(ctx,fpvDrawn,w,h,aoa,isGearDown){if(!isGearDown||!fpvDrawn||!Number.isFinite(aoa))return;const tickSpacing=.03*h,index=(aoa-6.9)/1.2,topY=fpvDrawn.y-index*tickSpacing,midY=topY+tickSpacing,bottomY=topY+2*tickSpacing,bracketX=fpvDrawn.x-fpvDrawn.r-fpvDrawn.wing-.022*w,tickLen=.018*w;ctx.save(),ctx.strokeStyle=this.DEFAULT_COLOR,ctx.lineWidth=1.3,ctx.setLineDash([]),ctx.beginPath(),ctx.moveTo(bracketX,topY),ctx.lineTo(bracketX,bottomY),ctx.moveTo(bracketX,topY),ctx.lineTo(bracketX+tickLen,topY),ctx.moveTo(bracketX,midY),ctx.lineTo(bracketX+tickLen,midY),ctx.moveTo(bracketX,bottomY),ctx.lineTo(bracketX+tickLen,bottomY),ctx.stroke(),ctx.restore()}static drawLegacyBoresight(ctx,cx,symbolCy,pixelsPerDeg,w,h){const point={x:cx,y:symbolCy-1.5*pixelsPerDeg};this.drawBoresight(ctx,point,w,h)}static drawLegacyPitchLadder(ctx,camera,ac,cx,clipCy,symbolCy,pixelsPerDeg,w,h){const pitchDeg=-ac.htr[1]||0,geometry={centerX:cx,centerY:clipCy,rollRad:-camera.roll,horizonOffsetY:pitchDeg*pixelsPerDeg+(symbolCy-clipCy),pixelsPerDeg:pixelsPerDeg};ctx.save(),ctx.beginPath(),ctx.moveTo(.34*w,.06*h),ctx.lineTo(.66*w,.06*h),ctx.lineTo(.92*w,.27*h),ctx.lineTo(.82*w,.92*h),ctx.lineTo(.18*w,.92*h),ctx.lineTo(.08*w,.27*h),ctx.closePath(),ctx.clip(),this.drawAttitudePitchLadder(ctx,geometry,w,h),ctx.restore()}static drawLegacyAoaBracket(ctx,fpvDrawn,cx,clipCy,pixelsPerDeg,w,h,aoa,isGearDown){if(!isGearDown||!fpvDrawn||!Number.isFinite(aoa))return;const tickSpacing=1.2*pixelsPerDeg,topY=fpvDrawn.y-(aoa-6.9)/1.2*tickSpacing,midY=topY+tickSpacing,bottomY=topY+2*tickSpacing,bracketX=fpvDrawn.x-fpvDrawn.r-fpvDrawn.wing-.022*w,tickLength=.018*w;ctx.save(),ctx.beginPath(),ctx.ellipse(cx,clipCy,.28*w,.38*h,0,0,2*Math.PI),ctx.clip(),ctx.strokeStyle=this.DEFAULT_COLOR,ctx.lineWidth=1.3,ctx.beginPath(),ctx.moveTo(bracketX,topY),ctx.lineTo(bracketX,bottomY),ctx.moveTo(bracketX,topY),ctx.lineTo(bracketX+tickLength,topY),ctx.moveTo(bracketX,midY),ctx.lineTo(bracketX+tickLength,midY),ctx.moveTo(bracketX,bottomY),ctx.lineTo(bracketX+tickLength,bottomY),ctx.stroke(),ctx.restore()}static drawSpeedBox(ctx,kias,w,h){const boxX=.145*w,boxY=.295*h,boxW=.118*w,boxH=.064*h;ctx.save(),ctx.setTransform(1,0,0,1,0,0),ctx.strokeStyle=this.DEFAULT_COLOR,ctx.lineWidth=Math.max(1.2,.0028*w),ctx.strokeRect(boxX,boxY,boxW,boxH),ctx.fillStyle=this.DEFAULT_COLOR,ctx.font=`bold ${Math.round(.042*h)}px monospace`,ctx.textAlign="center",ctx.textBaseline="middle",ctx.fillText(`${Math.round(kias)}`,boxX+boxW/2,boxY+boxH/2+1),ctx.restore()}static drawAltitudeBox(ctx,alt,w,h){const boxX=.73*w,boxY=.295*h,boxW=.138*w,boxH=.064*h,altRounded=Math.max(0,Math.round(alt)),thousands=Math.floor(altRounded/1e3),hundreds=altRounded%1e3;ctx.save(),ctx.setTransform(1,0,0,1,0,0),ctx.strokeStyle=this.DEFAULT_COLOR,ctx.lineWidth=Math.max(1.2,.0028*w),ctx.strokeRect(boxX,boxY,boxW,boxH);const rightX=boxX+boxW-.012*w,centerY=boxY+boxH/2+1,smallText=String(hundreds).padStart(3,"0");ctx.fillStyle=this.DEFAULT_COLOR,ctx.textAlign="right",ctx.textBaseline="middle",ctx.font=`bold ${Math.round(.034*h)}px monospace`;const smallWidth=ctx.measureText(smallText).width;ctx.fillText(smallText,rightX,centerY),ctx.font=`bold ${Math.round(.046*h)}px monospace`,ctx.fillText(String(thousands),rightX-smallWidth-.006*w,centerY),ctx.restore()}static drawLeftReadouts(ctx,mach,gValue,aoa,maxGValue,autopilot,w,h){const x=.145*w,y1=.405*h,y2=.457*h,y3=.509*h,y4=.561*h;ctx.save(),ctx.setTransform(1,0,0,1,0,0),ctx.fillStyle=this.DEFAULT_COLOR,ctx.font=`${Math.round(.036*h)}px monospace`,ctx.textAlign="left",ctx.textBaseline="middle";const gPrefixWidth=ctx.measureText("G ").width;if(ctx.fillText(`M ${mach.toFixed(2)}`,x,y1),ctx.fillText(`α ${aoa.toFixed(1)}`,x,y2),ctx.fillText("G ",x,y3),ctx.fillText(gValue.toFixed(1),x+gPrefixWidth,y3),ctx.fillText(maxGValue.toFixed(1),x+gPrefixWidth,y4),autopilot?.on){const sepY=.596*h;ctx.beginPath(),ctx.moveTo(x,sepY),ctx.lineTo(.265*w,sepY),ctx.strokeStyle=this.DEFAULT_COLOR,ctx.lineWidth=1.2,ctx.stroke();const rowStep=.046*h;let rowY=sepY+.038*h;if(ctx.font=`${Math.round(.032*h)}px monospace`,null!=autopilot?.values?.speed&&(ctx.fillText(`SPD ${Math.round(autopilot.values.speed)}`,x,rowY),rowY+=rowStep),null!=autopilot?.values?.altitude){const altitudeText=String(autopilot.values.altitude).split(".")[0];ctx.fillText(`ALT ${altitudeText}`,x,rowY),rowY+=rowStep}autopilot?.mode&&ctx.fillText(String(autopilot.mode),x,rowY)}ctx.restore()}static drawRightReadouts(ctx,vsi,radioAlt,trimDisplay,navUnit,navModule,w,h,wpnHudStatus){const x=.73*w,yTop=.26*h,yBottom=.405*h,yTrim=.457*h,yWpn1=.509*h,yWpn2=.561*h;if(ctx.save(),ctx.setTransform(1,0,0,1,0,0),ctx.fillStyle=this.DEFAULT_COLOR,ctx.font=`${Math.round(.036*h)}px monospace`,ctx.textAlign="left",ctx.textBaseline="middle",ctx.fillText(` ${vsi>=0?" ":""}${vsi}`,x,yTop),radioAlt<=1e4&&ctx.fillText(`R ${Math.round(radioAlt)}`,x,yBottom),ctx.fillText(trimDisplay,x,yTrim),wpnHudStatus&&(ctx.fillText(wpnHudStatus.line1,x,yWpn1),ctx.fillText(wpnHudStatus.line2,x,yWpn2)),null!=navUnit){const navReadouts=navModule?.getReadouts?.(navUnit)??{},sepY=.596*h;ctx.beginPath(),ctx.moveTo(x,sepY),ctx.lineTo(.85*w,sepY),ctx.strokeStyle=this.DEFAULT_COLOR,ctx.lineWidth=1.2,ctx.stroke();const rowStep=.046*h;let rowY=sepY+.038*h;ctx.font=`${Math.round(.032*h)}px monospace`;const dme=Number.isFinite(navReadouts.dme)?navReadouts.dme:"",bearing=Number.isFinite(navReadouts.bearing)?navReadouts.bearing:"",course=Number.isFinite(navReadouts.course)?navReadouts.course:"",timeToSignal=Number.isFinite(navReadouts.timeToSignal)?navReadouts.timeToSignal:"";ctx.fillText(`DME ${dme}`,x,rowY),rowY+=rowStep,ctx.fillText(`B ${bearing}`,x,rowY),rowY+=rowStep,ctx.fillText(`C ${course}`,x,rowY),rowY+=rowStep,ctx.fillText(`T ${timeToSignal} MIN`,x,rowY),rowY+=rowStep,ctx.fillText(navReadouts.navaidLabel||"",x,rowY)}ctx.restore()}static drawWeaponEffectivenessBracket(ctx,weaponModule,profile,lockedDistanceNm,w,h){const markerFractions=weaponModule.getEffectivenessMarkerFractions(profile),bracketTop=.26*h,bracketHeight=.32*h,bracketBottom=bracketTop+bracketHeight,bracketX=.715*w,tickLen=.018*w;ctx.save(),ctx.setTransform(1,0,0,1,0,0),ctx.strokeStyle=this.DEFAULT_COLOR,ctx.fillStyle=this.DEFAULT_COLOR,ctx.lineWidth=2,ctx.beginPath(),ctx.moveTo(bracketX,bracketTop),ctx.lineTo(bracketX,bracketBottom),ctx.stroke();const markerYs=[bracketTop+markerFractions.engagementMax*bracketHeight,bracketTop+markerFractions.effectiveMax*bracketHeight,bracketTop+markerFractions.effectiveMin*bracketHeight,bracketTop+markerFractions.engagementMin*bracketHeight];for(const y of markerYs)ctx.beginPath(),ctx.moveTo(bracketX,y),ctx.lineTo(bracketX-tickLen,y),ctx.stroke();if(Number.isFinite(lockedDistanceNm)){const lockedFraction=weaponModule.getEffectivenessDistanceFraction(profile,lockedDistanceNm);ctx.font=`bold ${Math.round(.046*h)}px monospace`,ctx.textAlign="right",ctx.textBaseline="middle",ctx.fillText(">",bracketX,bracketTop+lockedFraction*bracketHeight)}ctx.restore()}static drawTopHeadingScale(ctx,renderer,hdg,navUnit,helperModule,w,h){const bandX=.275*w,bandY=.078*h,bandW=.45*w,bandH=.108*h;ctx.save(),ctx.beginPath(),ctx.rect(bandX,bandY,bandW,bandH),ctx.clip(),ctx.textAlign="center";const prevFont=ctx.font;ctx.font=`${Math.round(.03*h)}px monospace`,renderer.drawGrads(renderer.canvasAPI,{position:[bandX,bandY+.03*h],zero:[bandW/2,0],size:[bandW,bandH],orientation:"x",direction:1,value:hdg,interval:5,pixelRatio:.0105*w,pattern:[[{length:.016*h,legend:!0,legendOffset:{x:0,y:.004*-h},process:v=>{const deg=(10*Math.round(v/10)%360+360)%360;return String(deg)}}],[{length:.009*h}]]}),ctx.font=prevFont,ctx.restore();const cx=w/2,topY=bandY+bandH-.043*h,halfW=.012*w,height=.016*h;if(ctx.save(),ctx.setTransform(1,0,0,1,0,0),ctx.strokeStyle=this.DEFAULT_COLOR,ctx.lineWidth=Math.max(1.2,.0026*w),ctx.beginPath(),ctx.moveTo(cx-halfW,topY),ctx.lineTo(cx,topY-height),ctx.lineTo(cx+halfW,topY),ctx.stroke(),null!=navUnit&&Number.isFinite(navUnit?.bearing)){const diamondX=cx+(helperModule?.angleDiffDeg?.(navUnit.bearing,hdg)??0)*(.0105*w/5);if(diamondX>=bandX&&diamondX<=bandX+bandW){const diamondTopY=topY-height,diamondHalfW=.007*w,diamondHalfH=.01*h;ctx.fillStyle=this.DEFAULT_COLOR,ctx.beginPath(),ctx.moveTo(diamondX,diamondTopY),ctx.lineTo(diamondX+diamondHalfW,diamondTopY+diamondHalfH),ctx.lineTo(diamondX,diamondTopY+2*diamondHalfH),ctx.lineTo(diamondX-diamondHalfW,diamondTopY+diamondHalfH),ctx.closePath(),ctx.fill()}}ctx.restore()}static drawIlsDeviationCues(ctx,fpvDrawn,helperModule,w,h){const navUnit=window.geofs?.nav?.currentNAVUnit;if(!navUnit||!fpvDrawn)return;const navDirection=window.geofs?.animation?.getValue?.("NAVDirection")??window.geofs?.animation?.values?.NAVDirection??navUnit?.NAVDirection,outOfRange=!1===navUnit?.inRange;if(outOfRange||("from"===navUnit||"from"===navDirection))return ctx.save(),ctx.setTransform(1,0,0,1,0,0),ctx.fillStyle=this.DEFAULT_COLOR,ctx.textAlign="center",ctx.textBaseline="top",ctx.font=`${Math.round(.033*h)}px monospace`,ctx.fillText(outOfRange?"OUT OF RANGE":"FROM",fpvDrawn.x,fpvDrawn.y+.032*h),void ctx.restore();const getValue=window.geofs?.animation?.getValue?.bind(window.geofs?.animation),navCourseDeviation=getValue?getValue("NAVCourseDeviation")??0:window.geofs?.animation?.values?.NAVCourseDeviation??0,navGlideDeviation=getValue?getValue("NAVGlideAngleDeviation")??0:window.geofs?.animation?.values?.NAVGlideAngleDeviation??0,courseOffsetPx=(helperModule?.clampValue?.(10*navCourseDeviation,-75,75)??0)*(w/512),glideOffsetPx=(helperModule?.clampValue?.(-10*navGlideDeviation,-75,75)??0)*(h/512),fpvX=fpvDrawn.x,fpvY=fpvDrawn.y,hLen=.055*w,vLen=.055*h;if(ctx.save(),ctx.setTransform(1,0,0,1,0,0),ctx.strokeStyle=this.DEFAULT_COLOR,ctx.lineWidth=1.4,ctx.setLineDash([]),navUnit?.VNAVCapable){const glideY=fpvY+glideOffsetPx;ctx.beginPath(),ctx.moveTo(fpvX-hLen,glideY),ctx.lineTo(fpvX+hLen,glideY),ctx.stroke()}if(navUnit?.LNAVCapable){const courseX=fpvX+courseOffsetPx;ctx.beginPath(),ctx.moveTo(courseX,fpvY-vLen),ctx.lineTo(courseX,fpvY+vLen),ctx.stroke()}ctx.restore()}static drawGearAndFlapIndicators(ctx,w,h,lineColor,options={}){const isMfd="mfd"===String(options?.target??"hud").toLowerCase(),gearRaw=Number(window.controls?.gear?.position),gearPos=Number.isFinite(gearRaw)?gearRaw:1,flapsPosRaw=Number(window.controls?.flaps?.position),flapsPos=Number.isFinite(flapsPosRaw)?flapsPosRaw:0,flapsMaxRaw=Number(window.controls?.flaps?.maxPosition),flapsMax=Number.isFinite(flapsMaxRaw)&&flapsMaxRaw>0?flapsMaxRaw:1,flapsNorm=Math.max(0,Math.min(1,flapsPos/flapsMax)),hookRaw=Number(window.controls?.accessories?.position),hookPos=Number.isFinite(hookRaw)?Math.max(0,Math.min(1,hookRaw)):0,top=isMfd?.27*h:.02*h,clusterW=isMfd?.58*w:.5*w,gapGearToFlap=clusterW*(isMfd?.07:.06),gapFlapToHook=clusterW*(isMfd?.045:.035),blockW=(clusterW-gapGearToFlap-gapFlapToHook)/3,left=.5*w-.5*clusterW,indicatorTopY=top,indicatorBottomY=top+(isMfd?.12*h:.14*h),textY=top+(isMfd?.17*h:.19*h);ctx.save(),ctx.setTransform(1,0,0,1,0,0),ctx.strokeStyle=lineColor,ctx.fillStyle=lineColor,ctx.lineWidth=Math.max(1.5,.0025*w),ctx.setLineDash([]);const flapsLineWidth=isMfd?5:3,hookLineWidth=isMfd?5:3,dotRadius=isMfd?2.5:Math.max(1.5,.0028*w),gearX=left,boxW=blockW*(isMfd?.13:.11),boxH=h*(isMfd?.042:.1),leftBoxX=gearX+.2*blockW,leftBoxY=indicatorBottomY-boxH,rightBoxX=gearX+.7*blockW,rightBoxY=indicatorBottomY-boxH,isGearDown=gearPos<=0,isGearTrans=!isGearDown&&!(gearPos>=1),gearFill=isGearDown?"#00ff00":isGearTrans?"#ff8a24":null,drawGearBox=(x,y)=>{ctx.strokeRect(x,y,boxW,boxH),gearFill&&(ctx.fillStyle=gearFill,ctx.fillRect(x+1,y+1,Math.max(0,boxW-2),Math.max(0,boxH-2)),ctx.fillStyle=lineColor)};drawGearBox(gearX+.445*blockW,indicatorTopY-(isMfd?.8*boxH:0)),drawGearBox(leftBoxX,leftBoxY),drawGearBox(rightBoxX,rightBoxY);let gearStatus="GEAR UP";isGearDown?gearStatus="GEAR DOWN":isGearTrans&&(gearStatus="GEAR TRANS");const flapX=gearX+blockW+gapGearToFlap,flapWingY=top+(isMfd?.03*h:.045*h),wingStartX=flapX+.08*blockW,wingEndX=flapX+.62*blockW,flapHingeX=wingEndX,slatHingeX=wingStartX,segmentLen=blockW*(isMfd?.4:.22),flapRad=45*flapsNorm*Math.PI/180,slatNorm=Math.max(0,Math.min(1,flapsPos)),previousLineWidth=ctx.lineWidth;ctx.lineWidth=flapsLineWidth,ctx.beginPath(),ctx.moveTo(wingStartX,flapWingY),ctx.lineTo(wingEndX,flapWingY),ctx.stroke();const slatRad=30*slatNorm*Math.PI/180,slatEndX=slatHingeX-Math.cos(slatRad)*(.55*segmentLen),slatEndY=flapWingY+Math.sin(slatRad)*(.55*segmentLen);ctx.beginPath(),ctx.moveTo(slatHingeX,flapWingY),ctx.lineTo(slatEndX,slatEndY),ctx.stroke();const flapEndX=flapHingeX+Math.cos(flapRad)*segmentLen,flapEndY=flapWingY+Math.sin(flapRad)*segmentLen;ctx.beginPath(),ctx.moveTo(flapHingeX,flapWingY),ctx.lineTo(flapEndX,flapEndY),ctx.stroke(),ctx.lineWidth=previousLineWidth;const detentCount=Math.max(1,Math.round(flapsMax));for(let i=0;i<=detentCount;i++){const a=45*(i/detentCount)*Math.PI/180,dotX=flapHingeX+Math.cos(a)*segmentLen,dotY=flapWingY+Math.sin(a)*segmentLen;ctx.beginPath(),ctx.arc(dotX,dotY,dotRadius,0,2*Math.PI),ctx.fill()}let flapStatus="FLAPS UP";if(flapsPos>=flapsMax)flapStatus="FLAPS DOWN";else if(flapsPos>0){flapStatus=`FLAPS ${Math.max(1,Math.min(detentCount-1,Math.round(flapsPos)))} / ${detentCount}`}const hookX=flapX+blockW+gapFlapToHook,hookWingY=flapWingY,hookHingeX=hookX+.38*blockW,hookLen=blockW*(isMfd?.36:.24),hookRad=45*hookPos*Math.PI/180,hookUpX=hookHingeX+hookLen,hookUpY=hookWingY,hookDownX=hookHingeX+Math.cos(Math.PI/4)*hookLen,hookDownY=hookWingY+Math.sin(Math.PI/4)*hookLen;ctx.lineWidth=hookLineWidth;const hookEndX=hookHingeX+Math.cos(hookRad)*hookLen,hookEndY=hookWingY+Math.sin(hookRad)*hookLen;ctx.beginPath(),ctx.moveTo(hookHingeX,hookWingY),ctx.lineTo(hookEndX,hookEndY),ctx.stroke(),ctx.lineWidth=previousLineWidth,ctx.beginPath(),ctx.arc(hookUpX,hookUpY,dotRadius,0,2*Math.PI),ctx.fill(),ctx.beginPath(),ctx.arc(hookDownX,hookDownY,dotRadius,0,2*Math.PI),ctx.fill();let hookStatus="HOOK UP";hookPos>=1?hookStatus="HOOK DOWN":hookPos>0&&(hookStatus="HOOK MOV"),ctx.textAlign="center",ctx.textBaseline="middle",ctx.font=`bold ${Math.round(h*(isMfd?.036:.048))}px monospace`;const gearCenterX=gearX+.5*blockW,flapCenterX=flapX+.5*blockW,hookCenterX=hookX+.5*blockW;ctx.fillStyle=isGearTrans?"#ff8a24":lineColor,ctx.fillText(gearStatus,gearCenterX,textY),ctx.fillStyle=lineColor,ctx.fillText(flapStatus,flapCenterX,textY),ctx.fillText(hookStatus,hookCenterX,textY),ctx.restore()}renderF18Hud(renderer){const o=renderer.canvasAPI.context,canvas=renderer.canvasAPI.canvas??o.canvas,w=canvas?.width||512,h=canvas?.height||512,ac=window.geofs?.aircraft?.instance,camera=window.geofs?.api?.viewer?.camera,anim=window.geofs?.animation?.values??{},kias=window.exponentialSmoothing?window.exponentialSmoothing("smoothKias",anim.kias??0,.1):anim.kias??0,alt=anim.altitude??0,hdg=anim.heading360??anim.heading??0,aoa=anim.aoa??0,mach=Math.round(100*(window.geofs?.animation?.values?.mach??0))/100,vsi=10*Math.round((window.geofs?.animation?.values?.climbrate??0)/10),radioAlt=window.geofs?.animation?.values?.haglFeet??0,trimScaled=Math.round(100*(window.geofs?.animation?.values?.trim??0)),trimDisplay=0===trimScaled?"T T/O":`T ${trimScaled}`,currentG=Number.isFinite(anim.loadFactor)?anim.loadFactor:1,navUnit=window.geofs?.nav?.currentNAVUnit??null,autopilot=window.geofs?.autopilot??null,wpnMaster=this.getOption("WPN","MASTER","OFF"),wpnMode=this.getWpnModeFromOptions(),wpnModeLoadout=this.getWpnModeLoadout(wpnMode),wpnHudStatus="OFF"!==wpnMaster?{line1:`${"SIM"===wpnMaster?"SIM":"ARM"} ${wpnMode}`,line2:this.getSelectedWpnQuantityLine(wpnMode,wpnModeLoadout)}:null,hudBaseColor=this.getOptionValue("HUD","COLOR",F18HudModule.DEFAULT_COLOR),hudColor=this.applyBrightnessToHexColor(hudBaseColor,this.getMfdBrightnessFactor()),hudLevel=this.getOption("HUD","LEVEL","FULL");F18HudModule.DEFAULT_COLOR=hudColor,this.updateWpnRearmState(),currentG>this.maxG&&(this.maxG=currentG);const helperModule=this.dependencies.helperModule,navModule=this.getNavModule();if(o.save(),o.setTransform(1,0,0,1,0,0),o.clearRect(0,0,w,h),o.restore(),o.fillStyle=hudColor,o.strokeStyle=hudColor,o.lineWidth=2,o.font="20px sans-serif","FULL"==hudLevel&&F18HudModule.drawTopHeadingScale(o,renderer,hdg,navUnit,helperModule,w,h),F18HudModule.drawSpeedBox(o,kias,w,h),F18HudModule.drawAltitudeBox(o,alt,w,h),"MIN"!==hudLevel){F18HudModule.drawLeftReadouts(o,mach,currentG,aoa,this.maxG,autopilot,w,h),F18HudModule.drawRightReadouts(o,vsi,radioAlt,trimDisplay,navUnit,navModule,w,h,wpnHudStatus);const weapons=this.getAddon()?.weapons,effectiveness=wpnModeLoadout?weapons?.getSelectedWeaponEffectiveness?.(wpnMode,wpnModeLoadout):null;if("A/A"===wpnMode&&effectiveness){const locked=this.getAddon()?.combat?.targets?.getLockedTarget?.();F18HudModule.drawWeaponEffectivenessBracket(o,weapons,effectiveness,locked?.rangeNm,w,h)}}if(ac&&this.dependencies.hudCombinerConfig){const hudFrame=this.collectHudProjectionInputs(renderer,ac);if(hudFrame){hudFrame.projectDirection=direction=>this.projectWorldDirection(hudFrame,direction);const boresightPoint=hudFrame.projectDirection(hudFrame.boresightDirection),attitudeGeometry=F18HudModule.getFpvAttitudeGeometry(anim,ac,w,h),flightPathSymbol=F18HudModule.getFlightPathAttitudePosition(hudFrame,attitudeGeometry),fpvPoint=flightPathSymbol?.position??null,debugData=this.isHudProjectionDebug?this.collectHudGeometryDebugData(hudFrame,attitudeGeometry,flightPathSymbol,anim,ac):null;if(debugData&&this.reportHudGeometryDiagnostics(debugData),o.save(),o.setTransform(1,0,0,1,0,0),F18HudModule.applyCombinerClip(o,hudFrame)){"FULL"===hudLevel&&F18HudModule.drawBoresight(o,boresightPoint,w,h),F18HudModule.drawAttitudePitchLadder(o,attitudeGeometry,w,h);const fpvDrawn=F18HudModule.drawFpv(o,fpvPoint,w,h);"MIN"!==hudLevel&&F18HudModule.drawIlsDeviationCues(o,fpvDrawn,helperModule,w,h);const isGearDown=window.controls?.gear?.position<.5;F18HudModule.drawAoaBracket(o,fpvDrawn,w,h,aoa,isGearDown),debugData&&F18HudModule.drawHudDebugMarkers(o,debugData)}o.restore()}}else camera&&ac?.htr&&this.renderLegacyAttitude(o,camera,ac,hudLevel,helperModule,w,h,aoa);this.isWpnFireFlashVisible()&&(o.save(),o.setTransform(1,0,0,1,0,0),o.fillStyle=F18HudModule.DEFAULT_COLOR,o.textAlign="center",o.textBaseline="middle",o.font=`${Math.round(.15*h)}px monospace`,o.fillText(this.getWpnActionFlashLabel(),.5*w,.52*h),o.restore());const communicationModule=this.getCommunicationModule(),commHudText=communicationModule?.getHudOverlayText?.();if(commHudText){o.save(),o.setTransform(1,0,0,1,0,0),o.fillStyle=F18HudModule.DEFAULT_COLOR,o.textAlign="center",o.textBaseline="bottom",o.font=`bold ${Math.round(.038*h)}px monospace`;const lines=String(commHudText??"").split("\n").map(line=>line.trim()).filter(Boolean),lineHeight=.045*h,startY=.96*h-(lines.length-1)*lineHeight;for(let i=0;i{self.adjustHudCameraZ(CameraModule.CAMERA_STEP_Z)}),seatLabelButton=this.helperModule?.createPadButton({label:"SEAT",id:"f18-seat-label",onClick:()=>{},outerStyle:{marginTop:"-9px",borderRadius:"0",borderTop:"0",cursor:"default",pointerEvents:"none"},innerStyle:{fontWeight:"700"}}),downButton=this.createCameraPadButton("DOWN",CameraModule.CAMERA_DOWN_BUTTON_ID,()=>{self.adjustHudCameraZ(-CameraModule.CAMERA_STEP_Z)});return!!(upButton&&seatLabelButton&&downButton)&&(wrapper.appendChild(upButton),wrapper.appendChild(seatLabelButton),wrapper.appendChild(downButton),this.helperModule.installPadControl({id:wrapper.id,element:wrapper,prepend:!0}))}installCockpitViewControls(){if(document.getElementById(this.cockpitViewControlsWrapperId))return!0;if(!this.helperModule)return!1;const wrapper=document.createElement("div");wrapper.id=this.cockpitViewControlsWrapperId,wrapper.style.display="flex",wrapper.style.flexDirection="column",wrapper.style.gap="0px",wrapper.style.alignItems="flex-start";const viewButton=this.helperModule?.createPadButton({label:"VIEW",id:CameraModule.CAMERA_VIEW_BUTTON_ID,onClick:()=>{this.nextCockpitView()},outerStyle:{borderRadius:"15px"},innerStyle:{fontWeight:"700"}});return!!viewButton&&(wrapper.appendChild(viewButton),this.helperModule.installPadControl({id:wrapper.id,element:wrapper,prepend:!0}))}removeCameraControls(){this.helperModule?.removePadControl("f18-hud-camera-controls")}removeCockpitViewControls(){this.helperModule?.removePadControl(this.cockpitViewControlsWrapperId)}applyCockpitViewByIndex(index=0){const mode=window.geofs?.camera?.modes?.[1];if(!mode)return!1;const views=this.getCockpitViewPresets();if(!views.length)return!1;const safeIndex=HelperModule.clampValue(Math.floor(Number(index)||0),0,views.length-1),preset=views[safeIndex];return!!preset&&(mode.position=Array.isArray(preset.position)?[...preset.position]:[0,5.5,CameraModule.DEFAULT_HUD_CAMERA_Z],mode.offsets=mode.offsets&&"object"==typeof mode.offsets?mode.offsets:{},mode.offsets.current=[0,0,0],mode.orientations=mode.orientations&&"object"==typeof mode.orientations?mode.orientations:{},mode.orientations.current=Array.isArray(preset.orientation)?[...preset.orientation]:[0,-15,0],mode.orientation=Array.isArray(preset.orientation)?[...preset.orientation]:[0,-15,0],mode.FOV=Number.isFinite(Number(preset.FOV))?Number(preset.FOV):1.7,this.cockpitViewIndex=safeIndex,!0)}nextCockpitView(){const views=this.getCockpitViewPresets();if(!views.length)return!1;const next=(this.cockpitViewIndex+1)%views.length,ok=this.applyCockpitViewByIndex(next);return ok&&(this.cockpitViewApplied=!0),ok}isAircraftCameraReady(){const aircraft=window.geofs?.aircraft?.instance,parts=aircraft?.parts,mode1=window.geofs?.camera?.modes?.[1];return Boolean(parts&&Object.keys(parts).length>0&&mode1?.position)}hasCustomModes(modes){if(!modes)return!1;const definitions=this.getCameraModeDefinitions();return Object.entries(definitions).every(([indexKey,definition])=>{const index=Number(indexKey),current=modes[index];return Boolean(current&¤t.name===definition.name&¤t.view===definition.view)})}ensureLoaded(){if(!window.BasePlugin?.getActivePlugin?.()?.isAircraftActive?.())return this.removeCameraControls(),this.removeCockpitViewControls(),!1;const modes=window.geofs?.camera?.modes;if(!modes)return!1;if(!this.isAircraftCameraReady())return!1;const cockpitViewPresets=this.getCockpitViewPresets(),cameraModeDefinitions=this.getCameraModeDefinitions(),isCockpitView="cockpit"===window.geofs?.camera?.currentModeName;if(cockpitViewPresets.length>0){if(!this.installCockpitViewControls())return!1}else this.removeCockpitViewControls();if(isCockpitView){if(!this.installCameraControls())return!1}else this.removeCameraControls(),this.removeCockpitViewControls(),this.cockpitViewApplied=!1;const modesRefChanged=this.boundModesRef&&this.boundModesRef!==modes,customModesPresent=this.hasCustomModes(modes);if(this.installed&&!modesRefChanged&&customModesPresent)return!0;this.installed&&!modesRefChanged||this.originalModesByIndex.clear();for(const[indexKey,definition]of Object.entries(cameraModeDefinitions)){const index=Number(indexKey);if(Number.isInteger(index)){if(!this.originalModesByIndex.has(index)){const hasOriginalMode=Object.prototype.hasOwnProperty.call(modes,index);this.originalModesByIndex.set(index,{exists:hasOriginalMode,value:hasOriginalMode?HelperModule.deepCloneJson(modes[index]):null})}modes[index]=HelperModule.deepCloneJson(definition)}}return this.installed=!0,this.boundModesRef=modes,isCockpitView&&cockpitViewPresets.length>0&&(!this.cockpitViewApplied||modesRefChanged||!customModesPresent)&&(this.applyCockpitViewByIndex(this.cockpitViewIndex),this.cockpitViewApplied=!0),!0}restore(){if(this.removeCameraControls(),this.removeCockpitViewControls(),!this.installed&&0===this.originalModesByIndex.size)return;const modes=window.geofs?.camera?.modes;if(modes&&(!this.boundModesRef||modes===this.boundModesRef))for(const[index,originalState]of this.originalModesByIndex.entries())originalState?.exists?modes[index]=HelperModule.deepCloneJson(originalState.value):delete modes[index];this.originalModesByIndex.clear(),this.installed=!1,this.boundModesRef=null,this.cockpitViewApplied=!1}}class FMCModule{constructor(){this.installed=!1,this.timer=null,this.lastFlapsMode=null,this.lastAutoTarget=null,this.originalSetPartAnimationDelta=null,this.airbrakeDeltaHookInstalled=!1}ensureLoaded(){return this.installed||(this.installed=!0,this.startLoop()),!0}startLoop(){this.timer||(this.timer=setInterval(()=>this.tick(),120))}stopLoop(){this.timer&&(clearInterval(this.timer),this.timer=null)}getSpeedbrakeCapNormalized(){const raw=String(OptionModule.getOption("SYS","SPEEDBRAKE","MAX")??"MAX").trim().toUpperCase();if("MAX"===raw)return 1;const percentMatch=raw.match(/^(\d+(?:\.\d+)?)%$/);if(percentMatch){const pct=Number(percentMatch[1]);if(Number.isFinite(pct))return HelperModule.clampValue(pct/100,0,1)}return 1}installAirbrakeDeltaHook(controlsApi){if(!controlsApi||"function"!=typeof controlsApi.setPartAnimationDelta)return!1;if(this.airbrakeDeltaHookInstalled)return!0;this.originalSetPartAnimationDelta=controlsApi.setPartAnimationDelta;const self=this;return controlsApi.setPartAnimationDelta=function(part){const airbrakes=controlsApi.airbrakes;if(part&&airbrakes&&part===airbrakes){const cap=self.getSpeedbrakeCapNormalized(),target=Number(airbrakes.target);Number.isFinite(target)&&target>cap&&(airbrakes.target=cap);const positionTarget=Number(airbrakes.positionTarget);Number.isFinite(positionTarget)&&positionTarget>cap&&(airbrakes.positionTarget=cap)}return self.originalSetPartAnimationDelta.call(this,part)},this.airbrakeDeltaHookInstalled=!0,!0}enforceAirbrakeTargetCap(controlsApi){const airbrakes=controlsApi?.airbrakes;if(!airbrakes)return;const cap=this.getSpeedbrakeCapNormalized();let changed=!1;const target=Number(airbrakes.target);Number.isFinite(target)&&target>cap&&(airbrakes.target=cap,changed=!0);const positionTarget=Number(airbrakes.positionTarget);Number.isFinite(positionTarget)&&positionTarget>cap&&(airbrakes.positionTarget=cap,changed=!0),changed&&"function"==typeof controlsApi.setPartAnimationDelta&&controlsApi.setPartAnimationDelta(airbrakes)}uninstallAirbrakeDeltaHook(){const controlsApi=window.controls;this.airbrakeDeltaHookInstalled&&controlsApi&&this.originalSetPartAnimationDelta&&(controlsApi.setPartAnimationDelta=this.originalSetPartAnimationDelta),this.originalSetPartAnimationDelta=null,this.airbrakeDeltaHookInstalled=!1}computeAutoFlapsTarget(){const controlsApi=window.controls,maxPositionRaw=Number(controlsApi?.flaps?.maxPosition),maxPosition=Number.isFinite(maxPositionRaw)&&maxPositionRaw>0?maxPositionRaw:1,anim=window.geofs?.animation?.values??{},kias=Number(anim.kias),aoa=Number(anim.aoa),gLoad=Number(anim.loadFactor),mach=Number(anim.mach);if(Number.isFinite(kias)&&kias>=250)return 0;if(Number.isFinite(kias)&&kias<=130)return maxPosition;const speedFactor=Number.isFinite(kias)?Math.pow(HelperModule.clampValue((250-kias)/120,0,1),2.6):0,aoaFactor=Number.isFinite(aoa)?HelperModule.clampValue((aoa-6)/10,0,1):0,gFactor=Number.isFinite(gLoad)?HelperModule.clampValue((gLoad-1.15)/3,0,1):0,machFactor=Number.isFinite(mach)?Math.pow(HelperModule.clampValue((.28-mach)/.12,0,1),2):0;return Math.max(speedFactor,aoaFactor,gFactor,machFactor)*maxPosition}applyFlapsTarget(target){const controlsApi=window.controls,flaps=controlsApi?.flaps;if(!flaps||"function"!=typeof controlsApi?.setPartAnimationDelta)return;const maxPositionRaw=Number(flaps?.maxPosition),maxPosition=Number.isFinite(maxPositionRaw)&&maxPositionRaw>0?maxPositionRaw:1,clampedTarget=HelperModule.clampValue(Number(target)||0,0,maxPosition);null!=this.lastAutoTarget&&Math.abs(this.lastAutoTarget-clampedTarget)<.015||(flaps.positionTarget=clampedTarget,controlsApi.setPartAnimationDelta(flaps),this.lastAutoTarget=clampedTarget)}tick(){if(!window.BasePlugin?.getActivePlugin?.()?.isAircraftActive?.())return this.lastFlapsMode=null,void(this.lastAutoTarget=null);const controlsApi=window.controls;if(controlsApi){if(this.installAirbrakeDeltaHook(controlsApi),controlsApi.flaps){const flapsMode=OptionModule.getOption("SYS","FLAPS","MAN");if("AUTO"===flapsMode){const target=this.computeAutoFlapsTarget();this.applyFlapsTarget(target)}else"AUTO"===this.lastFlapsMode&&(this.lastAutoTarget=null,this.applyFlapsTarget(0));this.lastFlapsMode=flapsMode}else this.lastFlapsMode=null;this.enforceAirbrakeTargetCap(controlsApi)}}restore(){this.stopLoop(),this.uninstallAirbrakeDeltaHook(),window.BasePlugin?.getActivePlugin?.()?.isAircraftActive?.()&&(this.lastAutoTarget=null,this.applyFlapsTarget(0)),this.lastFlapsMode=null,this.installed=!1}}class ControlModule{static UPDATE_INTERVAL_MS=50;constructor(helperModule=null){this.helperModule=helperModule,this.installed=!1,this.timer=null,this.controls=new Map,this.lastAircraftId=null}registerControl(definition){const key=String(definition?.key||"");if(!key)return!1;const control={key:key,padLabel:String(definition?.padLabel||""),defaultState:String(definition?.defaultState||"CLOSED"),durationMs:Math.max(0,Number(definition?.durationMs)||0),parts:Array.isArray(definition?.parts)?definition.parts:[],runtime:{initialized:!1,currentState:null,targetState:null,transitionStartMs:0,timingByValueKey:Object.create(null),fromValues:Object.create(null),toValues:Object.create(null),currentValues:Object.create(null)}};return this.controls.set(key,control),this.timer&&this.installPadControlFor(control),!0}ensureLoaded(){return this.installed||(this.installed=!0),!0}start(){return this.installed||this.ensureLoaded(),this.installPadControls(),this.startLoop(),!0}stop(){this.stopLoop(),this.removePadControls(),this.lastAircraftId=null;for(const control of this.controls.values())control.runtime.initialized=!1;return!0}setControlState(control,state){const tokens=this.parseConfigKey(control.key);return!(!tokens.page||!tokens.key)&&(OptionModule.setOption(tokens.page,tokens.key,state),!0)}createPadButton(label,id,onClick,outerStyle={},innerStyle={}){return this.helperModule?.createPadButton({label:label,id:id,onClick:onClick,outerStyle:outerStyle,innerStyle:innerStyle})??null}getPadControlWrapperId(control){return`control-pad-${control.key}`}installPadControlFor(control){if(!this.helperModule)return!1;if(!control.padLabel)return!1;const wrapperId=this.getPadControlWrapperId(control);if(document.getElementById(wrapperId))return!0;const wrapper=document.createElement("div");wrapper.id=wrapperId,wrapper.style.display="flex",wrapper.style.flexDirection="column",wrapper.style.gap="0px",wrapper.style.alignItems="flex-start";const openButton=this.createPadButton("OPEN",`${wrapperId}-open`,()=>{this.setControlState(control,"OPEN")},{borderBottom:"1px solid #333",borderRadius:"15px 15px 0 0"}),centerLabel=this.createPadButton(control.padLabel,`${wrapperId}-label`,()=>{},{marginTop:"-9px",borderRadius:"0",borderTop:"0",cursor:"default",pointerEvents:"none"},{fontWeight:"700"}),closeButton=this.createPadButton("CLOSE",`${wrapperId}-close`,()=>{this.setControlState(control,"CLOSED")},{marginTop:"-9px",borderRadius:"0 0 15px 15px",borderTop:"0"});return!!(openButton&¢erLabel&&closeButton)&&(wrapper.appendChild(openButton),wrapper.appendChild(centerLabel),wrapper.appendChild(closeButton),this.helperModule.installPadControl({id:wrapper.id,element:wrapper,prepend:!0}))}installPadControls(){for(const control of this.controls.values())this.installPadControlFor(control);return!0}removePadControls(){for(const control of this.controls.values())this.helperModule?.removePadControl(this.getPadControlWrapperId(control))}startLoop(){this.timer||(this.timer=setInterval(()=>this.tick(),ControlModule.UPDATE_INTERVAL_MS))}stopLoop(){this.timer&&(clearInterval(this.timer),this.timer=null)}parseConfigKey(configKey){const raw=String(configKey||""),[page,key]=raw.split(".");return{page:String(page||""),key:String(key||"")}}getRequestedState(control){const tokens=this.parseConfigKey(control?.key);if(!tokens.page||!tokens.key)return control.defaultState;const runtime=control?.runtime||{},raw=OptionModule.getOption(tokens.page,tokens.key,null);return String(null==raw||""===raw?runtime.targetState||runtime.currentState||control.defaultState:raw)}getAnimationValue(valueKey,fallback=0){const raw=Number(window.geofs?.animation?.values?.[valueKey]);return Number.isFinite(raw)?raw:Number(fallback)||0}getControlByKey(key){return key&&this.controls.get(key)||null}getControlSnapshot(controlKey){const control=this.getControlByKey(controlKey);return control?{key:control.key,defaultState:control.defaultState,durationMs:control.durationMs,parts:JSON.parse(JSON.stringify(control.parts||[])),runtime:{initialized:!!control.runtime?.initialized,currentState:control.runtime?.currentState??null,targetState:control.runtime?.targetState??null,currentValues:{...control.runtime?.currentValues||{}}}}:null}setControlDuration(controlKey,durationMs){const control=this.getControlByKey(controlKey);if(!control)return!1;const next=Math.max(0,Number(durationMs)||0);return control.durationMs=next,!0}setChannelValue(controlKey,partName,valueKey,state,value){const control=this.getControlByKey(controlKey);if(!control)return!1;const numericValue=Number(value);if(!(partName&&valueKey&&state&&Number.isFinite(numericValue)))return!1;const partDef=control.parts.find(p=>p.partName===partName);return!!partDef&&(partDef.channels=partDef.channels||{},partDef.channels[valueKey]=partDef.channels[valueKey]||{},partDef.channels[valueKey][state]=numericValue,!0)}setChannelValueByValueKey(controlKey,valueKey,state,value){const control=this.getControlByKey(controlKey);if(!control)return!1;const valueKeyNorm=String(valueKey||"").trim(),stateNorm=String(state||"").trim(),numericValue=Number(value);if(!valueKeyNorm||!stateNorm||!Number.isFinite(numericValue))return!1;const matches=control.parts.filter(p=>Object.prototype.hasOwnProperty.call(p?.channels||{},valueKeyNorm));if(1!==matches.length)return!1;const partDef=matches[0];return partDef.channels=partDef.channels||{},partDef.channels[valueKeyNorm]=partDef.channels[valueKeyNorm]||{},partDef.channels[valueKeyNorm][stateNorm]=numericValue,!0}setPartTiming(controlKey,partName,state,delayMs,durationMs){const control=this.getControlByKey(controlKey);if(!control)return!1;const partNameNorm=String(partName||"").trim(),stateNorm=String(state||"").trim(),delay=Number(delayMs),duration=Number(durationMs);if(!partNameNorm||!stateNorm)return!1;const partDef=control.parts.find(p=>String(p?.partName||"").trim()===partNameNorm);return!!partDef&&(partDef.motion=partDef.motion||{},partDef.motion[stateNorm]={delayMs:Number.isFinite(delay)?Math.max(0,delay):0,durationMs:Number.isFinite(duration)?Math.max(1,duration):Math.max(1,Number(control.durationMs)||1)},!0)}reanimateControlToOption(controlKey){const control=this.getControlByKey(controlKey);return!!control&&(control.runtime.initialized=!1,!0)}reanimateAllControlsToOption(){for(const control of this.controls.values())control.runtime.initialized=!1;return!0}findNodeNameLoose(model,wanted){const target=String(wanted||"").trim();if(!target||!model)return null;const nodesByName=model._nodesByName||model._runtime?.nodesByName;if(nodesByName){const exact=nodesByName[target]||nodesByName[target.toLowerCase()]||nodesByName[target.toUpperCase()];if(exact)return String(exact.name||exact._name||exact.id||target)}const wantedLow=target.toLowerCase(),arr=Array.isArray(model._runtime?.nodes)?model._runtime.nodes:Array.isArray(model._nodes)?model._nodes:[];for(const node of arr){const nodeName=String(node?.name||node?._name||node?.id||"").trim();if(nodeName&&nodeName.toLowerCase()===wantedLow)return nodeName}return null}ensurePartExists(partName){const aircraft=window.geofs?.aircraft?.instance,model=aircraft?.object3d?.model?._model;if(!aircraft||!model)return null;let part=aircraft.parts?.[partName]||null;if(part?.object3d)return part;const nodeName=this.findNodeNameLoose(model,partName);if(!nodeName)return null;const partDef={name:partName,node:nodeName,parent:"root",animations:[]};return aircraft.definition.parts=Array.isArray(aircraft.definition?.parts)?aircraft.definition.parts:[],aircraft.definition.parts.some(p=>String(p?.name||"")===partName)||aircraft.definition.parts.push(partDef),aircraft.addParts([partDef],aircraft.aircraftRecord?.fullPath,aircraft.definition?.scale||1,aircraft.definition?.orientation),part=aircraft.parts?.[partName]||null,part?.object3d?part:null}inferAxisFromValueKey(valueKey){const m=String(valueKey||"").match(/Rot([XYZ])Deg$/i);return m?m[1].toUpperCase():null}ensurePartAnimations(partName,channels){const part=this.ensurePartExists(partName);if(!part?.object3d)return null;part.animations=Array.isArray(part.animations)?part.animations:[];for(const valueKey of Object.keys(channels||{})){const axis=this.inferAxisFromValueKey(valueKey);if(!axis)continue;if(part.animations.some(a=>String(a?.value||"")===valueKey))continue;const rotationMethod=part.object3d[`rotate${axis}`];"function"==typeof rotationMethod&&part.animations.push({name:valueKey,type:"rotate",axis:axis,value:valueKey,rotationMethod:rotationMethod})}return part}ensureControlBindings(control){let allBound=!0;for(const partDef of control.parts||[]){const channels=partDef?.channels||{},part=this.ensurePartAnimations(partDef?.partName,channels);if(part?.object3d)for(const valueKey of Object.keys(channels)){(part.animations||[]).some(a=>String(a?.value||"")===String(valueKey))||(allBound=!1)}else allBound=!1}return allBound}buildTargetValues(control,state){const targetState=String(state||control.defaultState).toUpperCase(),values=Object.create(null);for(const partDef of control.parts){this.ensurePartAnimations(partDef?.partName,partDef?.channels);const channels=partDef?.channels||{};for(const[valueKey,byState]of Object.entries(channels)){const fallback=Number(byState?.[control.defaultState]),raw=byState?.[targetState],target=Number(raw);values[valueKey]=Number.isFinite(target)?target:Number.isFinite(fallback)?fallback:0}}return values}resolvePartMotion(partDef,targetState,control){const state=String(targetState||control?.defaultState||"CLOSED").toUpperCase(),cfg=partDef?.motion?.[state]||{},delayRaw=Number(cfg?.delayMs),durationRaw=Number(cfg?.durationMs),fallbackDuration=Math.max(1,Number(control?.durationMs)||1);return{delayMs:Number.isFinite(delayRaw)?Math.max(0,delayRaw):0,durationMs:Number.isFinite(durationRaw)?Math.max(1,durationRaw):fallbackDuration}}buildTimingByValueKey(control,targetState){const map=Object.create(null);for(const partDef of control.parts||[]){const channels=partDef?.channels||{},timing=this.resolvePartMotion(partDef,targetState,control);for(const valueKey of Object.keys(channels))map[valueKey]={delayMs:timing.delayMs,durationMs:timing.durationMs}}return map}applyCurrentValues(runtime){for(const[valueKey,value]of Object.entries(runtime.currentValues||{}))window.geofs?.animation?.setValue?.(valueKey,Number(value)||0)}updateControl(control,nowMs){const runtime=control.runtime;if(!this.ensureControlBindings(control))return void(runtime.initialized=!1);const requestedState=this.getRequestedState(control);if(!runtime.initialized){const initialTargetValues=this.buildTargetValues(control,requestedState),initialFromValues=Object.create(null);for(const key of Object.keys(initialTargetValues||{}))initialFromValues[key]=this.getAnimationValue(key,initialTargetValues[key]);return runtime.initialized=!0,runtime.currentState=null,runtime.targetState=requestedState,runtime.timingByValueKey=this.buildTimingByValueKey(control,requestedState),runtime.fromValues={...initialFromValues},runtime.toValues={...initialTargetValues},runtime.currentValues={...initialFromValues},runtime.transitionStartMs=nowMs,void(0===Math.max(0,Number(control.durationMs)||0)&&(runtime.currentState=requestedState,runtime.currentValues={...runtime.toValues},this.applyCurrentValues(runtime)))}if(requestedState!==runtime.targetState&&(runtime.fromValues={...runtime.currentValues},runtime.toValues=this.buildTargetValues(control,requestedState),runtime.timingByValueKey=this.buildTimingByValueKey(control,requestedState),runtime.transitionStartMs=nowMs,runtime.targetState=requestedState),runtime.targetState!==runtime.currentState){const elapsedMs=Math.max(0,nowMs-runtime.transitionStartMs),keys=new Set([...Object.keys(runtime.fromValues||{}),...Object.keys(runtime.toValues||{})]);let allDone=!0;for(const key of keys){const from=Number(runtime.fromValues?.[key]),to=Number(runtime.toValues?.[key]),a=Number.isFinite(from)?from:0,b=Number.isFinite(to)?to:0,timing=runtime.timingByValueKey?.[key]||{delayMs:0,durationMs:Math.max(1,Number(control.durationMs)||1)},delayMs=Math.max(0,Number(timing?.delayMs)||0),durationMs=Math.max(1,Number(timing?.durationMs)||1),localT=Math.max(0,Math.min(1,(elapsedMs-delayMs)/durationMs));runtime.currentValues[key]=a+(b-a)*localT,localT<1&&(allDone=!1)}allDone&&(runtime.currentState=runtime.targetState,runtime.currentValues={...runtime.toValues})}this.applyCurrentValues(runtime)}tick(){const aircraftId=String(window.geofs?.aircraft?.instance?.id??"");if(aircraftId!==this.lastAircraftId){this.lastAircraftId=aircraftId;for(const control of this.controls.values())control.runtime.initialized=!1}const nowMs=Date.now();for(const control of this.controls.values())this.updateControl(control,nowMs)}restore(){this.stop(),this.installed=!1}}class MfdDisplay{static DEFAULTS={MFD_BASE_SCALE:[.29,.29,.285],MFD_BUTTON_BASE_SCALE:[.047,.047,.047],MFD_BUTTON_COUNT:5,MFD_BUTTON_START_X:-.048,MFD_BUTTON_STEP_X:.023,MFD_BUTTON_Y:-.01,MFD_BUTTON_Z_OFFSET:.083,MFD_LEFT_BUTTON_X:-.085,MFD_RIGHT_BUTTON_X:.0835,MFD_SIDE_BUTTON_Y:-.01,MFD_SIDE_BUTTON_START_Z:.05,MFD_SIDE_BUTTON_STEP_Z:.023,MFD_TOP_BUTTON_VISUAL_SCALE:2/3,MFD_CLICK_HALF_WIDTH:.36,MFD_CLICK_HALF_HEIGHT:.36,MFD_PART_MODEL_URL:"https://raw.githubusercontent.com/ArjanKw/GeoFS-BlueAngels/refs/heads/main/Scripts/addon/models/glassPanel.gltf"};constructor(mfdModule,config={}){this.mfdModule=mfdModule,this.cfg={...MfdDisplay.DEFAULTS,name:"RIGHT",position:[.2167,6.158,.584],rotation:[8,0,0],scale:[.29,.29,.285],parentPartName:null,defaultPageTitle:null,...config},this.slotName=this.cfg.name,this.slotNameLower=this.slotName.toLowerCase(),this.names={MFD_RENDERER_NAME:`mfdRenderer${this.slotName}`,MFD_INCLUDE_KEY:`mfd-include-${this.slotNameLower}`,MFD_PART_NAME:`mfdPart${this.slotName}`,MFD_TOP_BUTTON_RENDERER_NAME:`mfdTopButtonRenderer${this.slotName}`,MFD_TOP_BUTTON_INCLUDE_KEY_BASE:`mfd-top-button-include-${this.slotNameLower}`,MFD_TOP_BUTTON_PART_NAME_BASE:`mfdTopButtonPart${this.slotName}_`,MFD_BOTTOM_BUTTON_PART_NAME_BASE:`mfdBottomButtonPart${this.slotName}_`,MFD_LEFT_BUTTON_PART_NAME_BASE:`mfdLeftButtonPart${this.slotName}_`,MFD_RIGHT_BUTTON_PART_NAME_BASE:`mfdRightButtonPart${this.slotName}_`},this.uiState=new F18MfdUiState({mapModule:this.mfdModule.mapModule,weaponsModule:this.mfdModule.weaponsModule,recorderModule:this.mfdModule.recorderModule},this.mfdModule.pageRegistry),this.nodeClickHandlerInstalled=!1,this.onNodeClickBound=this.onNodeClick.bind(this),this.defaultPageApplied=!1,this.installed=!1}get partName(){return this.names.MFD_PART_NAME}getTopButtonPartName(index){return`${this.names.MFD_TOP_BUTTON_PART_NAME_BASE}${index}`}getLeftButtonPartName(index){return`${this.names.MFD_LEFT_BUTTON_PART_NAME_BASE}${index}`}getBottomButtonPartName(index){return`${this.names.MFD_BOTTOM_BUTTON_PART_NAME_BASE}${index}`}getRightButtonPartName(index){return`${this.names.MFD_RIGHT_BUTTON_PART_NAME_BASE}${index}`}getButtonPartName(side,index){return"top"===side?this.getTopButtonPartName(index):"bottom"===side?this.getBottomButtonPartName(index):"left"===side?this.getLeftButtonPartName(index):this.getRightButtonPartName(index)}getButtonBasePosition(side,index){return"top"===side?[this.cfg.MFD_BUTTON_START_X+index*this.cfg.MFD_BUTTON_STEP_X,this.cfg.MFD_BUTTON_Y,Math.abs(this.cfg.MFD_BUTTON_Z_OFFSET)]:"bottom"===side?[this.cfg.MFD_BUTTON_START_X+index*this.cfg.MFD_BUTTON_STEP_X,this.cfg.MFD_BUTTON_Y,-Math.abs(this.cfg.MFD_BUTTON_Z_OFFSET)]:"left"===side?[this.cfg.MFD_LEFT_BUTTON_X,this.cfg.MFD_SIDE_BUTTON_Y,this.cfg.MFD_SIDE_BUTTON_START_Z-index*this.cfg.MFD_SIDE_BUTTON_STEP_Z]:[this.cfg.MFD_RIGHT_BUTTON_X,this.cfg.MFD_SIDE_BUTTON_Y,this.cfg.MFD_SIDE_BUTTON_START_Z-index*this.cfg.MFD_SIDE_BUTTON_STEP_Z]}getMfdScaleRatios(){const scale=this.cfg.scale,base=this.cfg.MFD_BASE_SCALE;return[scale[0]/base[0],scale[1]/base[1],scale[2]/base[2]]}scaleButtonLocalPosition(basePosition){const[sx,sy,sz]=this.getMfdScaleRatios();return[basePosition[0]*sx,basePosition[1]*sy,basePosition[2]*sz]}getScaledButtonPartScale(){const[sx,sy,sz]=this.getMfdScaleRatios(),base=this.cfg.MFD_BUTTON_BASE_SCALE;return[base[0]*sx,base[1]*sy,base[2]*sz]}applyDefaultPage(){if(this.defaultPageApplied)return;const desiredTitle=this.cfg.defaultPageTitle;if(!desiredTitle)return;const idx=this.uiState.pages.findIndex(p=>p.title===desiredTitle);idx>=0&&this.uiState.setPage(idx),this.defaultPageApplied=!0}renderMfdButton(renderer){const ctx=renderer.canvasAPI.context,w=renderer.canvasAPI.canvas.width,h=renderer.canvasAPI.canvas.height,cx=w/2,cy=h/2,outerSize=Math.min(w,h)*this.cfg.MFD_TOP_BUTTON_VISUAL_SCALE,outerRadius=.2*outerSize,innerInset=.24*outerSize,innerSize=outerSize-2*innerInset,innerRadius=.36*innerSize;renderer.canvasAPI.clear("#000000"),ctx.save(),ctx.setTransform(1,0,0,1,0,0),ctx.globalCompositeOperation="source-over",ctx.globalAlpha=1;const outerX=cx-outerSize/2,outerY=cy-outerSize/2;ctx.beginPath(),ctx.roundRect(outerX,outerY,outerSize,outerSize,outerRadius),ctx.fillStyle="#222120",ctx.fill(),ctx.lineWidth=Math.max(2,.045*outerSize),ctx.strokeStyle="#0f0f0e",ctx.stroke(),ctx.beginPath(),ctx.roundRect(outerX+innerInset,outerY+innerInset,innerSize,innerSize,innerRadius),ctx.fillStyle="#3a3835",ctx.fill(),ctx.lineWidth=Math.max(1.2,.018*outerSize),ctx.strokeStyle="#2f2d2a",ctx.stroke(),ctx.restore()}ensureMainRendererFunction(){const self=this;return window.instruments.renderers[this.names.MFD_RENDERER_NAME]=renderer=>{if(self.uiState.render)return void self.uiState.render(renderer);const ctx=renderer.canvasAPI.context,w=renderer.canvasAPI.canvas.width,h=renderer.canvasAPI.canvas.height;renderer.canvasAPI.clear("#000000");const fallbackBaseColor=OptionModule.getOptionValue("HUD","COLOR","#00ff00");ctx.fillStyle=MfdModule.applyBrightnessToHexColor(fallbackBaseColor,MfdModule.getMfdBrightnessFactor()),ctx.font=`bold ${Math.round(.18*h)}px monospace`,ctx.textAlign="center",ctx.textBaseline="middle",ctx.fillText("MFD INIT",w/2,h/2)},!0}ensureButtonRendererFunction(){const self=this;return window.instruments.renderers[this.names.MFD_TOP_BUTTON_RENDERER_NAME]=renderer=>{self.renderMfdButton(renderer)},!0}ensureIncludeDefinition(includeKey,rendererName,modelUrl){return window.geofs.includes=window.geofs.includes||{},window.geofs.includes[includeKey]||(window.geofs.includes[includeKey]=[{model:{url:modelUrl,shader:{name:"generic",textures:{diffuse:""}},translucent:!1,opaque:!0},safeTransparency:!1,renderer:{name:rendererName,width:512,height:512,enableTransparency:!1,images:{}},animations:[{type:"render",value:"geofsTime"}],shadows:"SHADOWS_NONE"}]),!0}ensureMainIncludeDefinition(){return this.ensureIncludeDefinition(this.names.MFD_INCLUDE_KEY,this.names.MFD_RENDERER_NAME,`${this.cfg.MFD_PART_MODEL_URL}?v=${encodeURIComponent(this.names.MFD_RENDERER_NAME)}`)}getButtonIncludeKey(partName){return`${this.names.MFD_TOP_BUTTON_INCLUDE_KEY_BASE}-${partName}`}ensureButtonIncludeDefinition(partName){return this.ensureIncludeDefinition(this.getButtonIncludeKey(partName),this.names.MFD_TOP_BUTTON_RENDERER_NAME,`${this.cfg.MFD_PART_MODEL_URL}?v=mfd-button-${encodeURIComponent(partName)}`)}registerButtonPickNode(partName,nodeName){const part=window.geofs.aircraft.instance.parts[partName];if(!part)return!1;const nodesByName=part.object3d?.model?._model?._nodesByName;if(!nodesByName)return!1;let targetNode=nodesByName.glassPanel;if(!targetNode){const keys=Object.keys(nodesByName);keys.length>0&&(targetNode=nodesByName[keys[0]])}return!!targetNode&&(targetNode.name=nodeName,nodesByName[nodeName]=targetNode,!0)}installButtonGroup(side){const aircraft=window.geofs.aircraft.instance;if(!aircraft.parts[this.names.MFD_PART_NAME])return!1;const count=this.cfg.MFD_BUTTON_COUNT,partsToAdd=[];for(let i=0;i{this.registerButtonPickNode(partName,partName)})}return!0}ensureMfdParts(){const aircraft=window.geofs.aircraft.instance,parentPartName=this.cfg.parentPartName||this.mfdModule.getDefaultParentPartName();if(this.installed){const existingPart=aircraft.parts[this.names.MFD_PART_NAME];if(existingPart){if(this.cfg.parentPartName||"root"!==existingPart.parent||"root"===parentPartName)return!0;this.removeParts(),this.installed=!1}this.installed=!1}if(!this.ensureMainRendererFunction())return!1;if(!this.ensureMainIncludeDefinition())return!1;if(!this.ensureButtonRendererFunction())return!1;aircraft.parts[this.names.MFD_PART_NAME]||aircraft.addParts([{name:this.names.MFD_PART_NAME,include:this.names.MFD_INCLUDE_KEY,parent:parentPartName,position:this.cfg.position,rotation:this.cfg.rotation,scale:this.cfg.scale,points:{topLeft:[-this.cfg.MFD_CLICK_HALF_WIDTH,0,this.cfg.MFD_CLICK_HALF_HEIGHT],topRight:[this.cfg.MFD_CLICK_HALF_WIDTH,0,this.cfg.MFD_CLICK_HALF_HEIGHT],bottomLeft:[-this.cfg.MFD_CLICK_HALF_WIDTH,0,-this.cfg.MFD_CLICK_HALF_HEIGHT],bottomRight:[this.cfg.MFD_CLICK_HALF_WIDTH,0,-this.cfg.MFD_CLICK_HALF_HEIGHT]}}]);const mfdPart=aircraft.parts[this.names.MFD_PART_NAME];if(!mfdPart)return!1;const registerMainPickNode=()=>{const nodesByName=mfdPart.object3d?.model?._model?._nodesByName;if(!nodesByName)return!1;let glassNode=nodesByName.glassPanel;if(!glassNode){const keys=Object.keys(nodesByName);keys.length>0&&(glassNode=nodesByName[keys[0]])}return!!glassNode&&(glassNode.name=this.names.MFD_PART_NAME,nodesByName[this.names.MFD_PART_NAME]=glassNode,!0)};return registerMainPickNode()||mfdPart["3dmodel"].readyPromise.then(()=>registerMainPickNode()),!!this.installButtonGroup("top")&&(!!this.installButtonGroup("bottom")&&(!!this.installButtonGroup("left")&&(!!this.installButtonGroup("right")&&(this.installed=!0,!0))))}removePartByName(partName){const ac=window.geofs.aircraft.instance,part=ac.parts[partName];if(!part)return;const parent=part.object3d.getParent();if(parent._children){const idx=parent._children.indexOf(part.object3d);idx>=0&&parent._children.splice(idx,1)}part.object3d.destroy(),part.rendererInstance?.destroy(),part["3dmodel"]?.destroy(),delete ac.parts[partName]}removeParts(){for(let i=0;ithis.projectMfdCorner(c,partObj,aircraftLla));if(projected.some(p=>!p))return null;const[topLeft,topRight,bottomLeft,bottomRight]=projected,xs=projected.map(p=>p.x),ys=projected.map(p=>p.y);return{left:Math.min(...xs),top:Math.min(...ys),width:Math.max(...xs)-Math.min(...xs),height:Math.max(...ys)-Math.min(...ys),corners:{topLeft:topLeft,topRight:topRight,bottomLeft:bottomLeft,bottomRight:bottomRight}}}pointInTriangle(p,a,b,c){const area=(u,v,w)=>(u.x-w.x)*(v.y-w.y)-(v.x-w.x)*(u.y-w.y),s1=area(p,a,b),s2=area(p,b,c),s3=area(p,c,a);return!((s1<0||s2<0||s3<0)&&(s1>0||s2>0||s3>0))}pointInProjectedQuad(x,y,corners){const p={x:x,y:y},{topLeft:topLeft,topRight:topRight,bottomLeft:bottomLeft,bottomRight:bottomRight}=corners;return this.pointInTriangle(p,topLeft,topRight,bottomRight)||this.pointInTriangle(p,topLeft,bottomRight,bottomLeft)}getPickScore(x,y){const bounds=this.getProjectedMfdBounds();if(!bounds||!this.pointInProjectedQuad(x,y,bounds.corners))return 1/0;const{topLeft:topLeft,topRight:topRight,bottomLeft:bottomLeft,bottomRight:bottomRight}=bounds.corners,dx=x-(topLeft.x+topRight.x+bottomLeft.x+bottomRight.x)/4,dy=y-(topLeft.y+topRight.y+bottomLeft.y+bottomRight.y)/4;return dx*dx+dy*dy}getButtonIndexFromScreenCoords(side,x,y){const aircraft=window.geofs.aircraft.instance,aircraftLla=aircraft.llaLocation,halfW=this.cfg.MFD_CLICK_HALF_WIDTH*this.cfg.MFD_TOP_BUTTON_VISUAL_SCALE,halfH=this.cfg.MFD_CLICK_HALF_HEIGHT*this.cfg.MFD_TOP_BUTTON_VISUAL_SCALE,localCorners=[[-halfW,0,halfH],[halfW,0,halfH],[-halfW,0,-halfH],[halfW,0,-halfH]],count=this.cfg.MFD_BUTTON_COUNT;for(let i=0;ithis.projectMfdCorner(corner,partObj,aircraftLla));if(projected.some(p=>!p))continue;const[topLeft,topRight,bottomLeft,bottomRight]=projected;if(this.pointInProjectedQuad(x,y,{topLeft:topLeft,topRight:topRight,bottomLeft:bottomLeft,bottomRight:bottomRight}))return i}return-1}isOwnedNode(nodeName){if(nodeName===this.names.MFD_PART_NAME)return!0;for(let i=0;i{for(let i=0;i=0)return this.uiState.setPage(topButtonIndex),!0;const bottomButtonIndex=(()=>{for(let i=0;i=0)return this.uiState.setPage(this.cfg.MFD_BUTTON_COUNT+bottomButtonIndex),!0;const leftButtonIndex=(()=>{for(let i=0;i=0)return this.uiState.toggleButtonBySlot("left",leftButtonIndex),!0;const rightButtonIndex=(()=>{for(let i=0;i=0?(this.uiState.toggleButtonBySlot("right",rightButtonIndex),!0):nodeName===this.names.MFD_PART_NAME&&this.handlePickClick()}handlePickClick(clickOverride=null){const click=clickOverride??HelperModule.getClickScreenCoords();if(!click)return!1;const bounds=this.getProjectedMfdBounds();if(!bounds||!this.pointInProjectedQuad(click.x,click.y,bounds.corners))return!1;const pickedTopButtonIndex=this.getButtonIndexFromScreenCoords("top",click.x,click.y);if(pickedTopButtonIndex>=0)return this.uiState.setPage(pickedTopButtonIndex),!0;const pickedBottomButtonIndex=this.getButtonIndexFromScreenCoords("bottom",click.x,click.y);if(pickedBottomButtonIndex>=0)return this.uiState.setPage(this.cfg.MFD_BUTTON_COUNT+pickedBottomButtonIndex),!0;const pickedLeftButtonIndex=this.getButtonIndexFromScreenCoords("left",click.x,click.y);if(pickedLeftButtonIndex>=0)return this.uiState.toggleButtonBySlot("left",pickedLeftButtonIndex),!0;const pickedRightButtonIndex=this.getButtonIndexFromScreenCoords("right",click.x,click.y);return pickedRightButtonIndex>=0?(this.uiState.toggleButtonBySlot("right",pickedRightButtonIndex),!0):(this.uiState.nextPage(),!0)}restore(){this.removeNodeClickHandler(),this.removeParts(),this.defaultPageApplied=!1}}class MfdModule{constructor(helperModule,mapModule,cameraModule,weaponsModule,recorderModule){this.helperModule=helperModule,this.mapModule=mapModule,this.cameraModule=cameraModule,this.weaponsModule=weaponsModule,this.recorderModule=recorderModule,this.mfds=[],this.pageRegistry=[],this.mfdPickNodeHandlerInstalled=!1,this.onMfdPickNodeClickBound=this.onMfdPickNodeClick.bind(this),this.runNodeBridgeInstalled=!1,this.cameraWatchTimer=null,this.cameraWatchTicks=0,this.lastMfdRecoveryTick=-999}static getMfdBrightnessFactor(){const brightMode=OptionModule.getOption("HUD","BRIGHT","NORM");return"DAY"===brightMode?1:"NIGHT"===brightMode?.3:.6}static applyBrightnessToHexColor(color,factor){const hex=color.startsWith("#")?color.slice(1):color,clampChannel=channel=>Math.max(0,Math.min(255,Math.round(channel*factor))),r=clampChannel(parseInt(hex.slice(0,2),16)),g=clampChannel(parseInt(hex.slice(2,4),16)),b=clampChannel(parseInt(hex.slice(4,6),16)),toHex=n=>n.toString(16).padStart(2,"0");return`#${toHex(r)}${toHex(g)}${toHex(b)}`}getDefaultParentPartName(){const parts=window.geofs?.aircraft?.instance?.parts;if(parts?.cockpit)return"cockpit";const hudPart=Object.values(parts||{}).find(part=>"genericHUD"===part.renderer?.name||"genericHUD"===part.rendererInstance?.definition?.name);return hudPart?.parent||"root"}registerPage(pageDefinition){if(!pageDefinition.title)return!1;const existingIndex=this.pageRegistry.findIndex(p=>p.title===pageDefinition.title);return existingIndex>=0?this.pageRegistry[existingIndex]=pageDefinition:this.pageRegistry.push(pageDefinition),!0}addMfd(config={}){const display=new MfdDisplay(this,config);return this.mfds.push(display),display}getMfdAtScreenPoint(x,y){let targetDisplay=null,bestScore=1/0;for(const display of this.mfds){const score=display.getPickScore(x,y);score{if(bridgedHandler.__mfdBridgeOriginal(nodeName),!window.controls.nodeClickHandlers[nodeName])for(const callback of bridgedHandler.__mfdBridgeCallbacks)callback(nodeName)};bridgedHandler.__mfdBridge=!0,bridgedHandler.__mfdBridgeOriginal=original,bridgedHandler.__mfdBridgeCallbacks=[],window.controls.runNodeClickHandlers=bridgedHandler,handler=bridgedHandler}return handler.__mfdBridgeCallbacks.includes(this.onMfdPickNodeClickBound)||handler.__mfdBridgeCallbacks.push(this.onMfdPickNodeClickBound),this.runNodeBridgeInstalled=!0,!0}removeGlobalMfdPickNodeHandler(){this.mfdPickNodeHandlerInstalled&&(delete window.controls.nodeClickHandlers.glassPanel,this.mfdPickNodeHandlerInstalled=!1)}removeRunNodeClickBridge(){if(!this.runNodeBridgeInstalled)return;const handler=window.controls.runNodeClickHandlers;handler.__mfdBridge&&(handler.__mfdBridgeCallbacks=handler.__mfdBridgeCallbacks.filter(callback=>callback!==this.onMfdPickNodeClickBound),handler.__mfdBridgeCallbacks.length||(window.controls.runNodeClickHandlers=handler.__mfdBridgeOriginal)),this.runNodeBridgeInstalled=!1}startCameraWatch(){this.cameraWatchTimer||(this.cameraWatchTimer=setInterval(()=>{this.cameraWatchTicks+=1;const mode=window.geofs.camera.currentModeName,aircraft=window.geofs.aircraft.instance;if(aircraft&&aircraft.parts&&"cockpit"===mode&&this.cameraWatchTicks%4==0)for(const display of this.mfds)display.ensureLoaded()},250))}stopCameraWatch(){this.cameraWatchTimer&&(clearInterval(this.cameraWatchTimer),this.cameraWatchTimer=null)}initializeDefaultMfds(defaultLayout){const existingSlots=new Set(this.mfds.map(display=>display.slotName));for(const config of defaultLayout)existingSlots.has(config.name)||(this.addMfd(config),existingSlots.add(config.name))}getSlots(){return this.mfds.map(display=>display.slotName)}getDisplay(slotName="RIGHT"){return this.mfds.find(display=>display.slotName===slotName)||null}getDisplayTransform(slotName="RIGHT"){const display=this.getDisplay(slotName);return display?{slotName:display.slotName,position:[...display.cfg.position],rotation:[...display.cfg.rotation],scale:[...display.cfg.scale]}:null}static vec3Equals(a,b){return Array.isArray(a)&&Array.isArray(b)&&a.length>=3&&b.length>=3&&a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]}updateDisplayTransform(slotName="RIGHT",transform={},options={}){const display=this.getDisplay(slotName);if(!display)return!1;const applyScale=!0===options.applyScale,changes={position:!1,rotation:!1,scale:!1};if(transform.position){const nextPosition=[...transform.position];changes.position=!MfdModule.vec3Equals(display.cfg.position,nextPosition),changes.position&&(display.cfg.position=nextPosition)}if(transform.rotation){const nextRotation=[...transform.rotation];changes.rotation=!MfdModule.vec3Equals(display.cfg.rotation,nextRotation),changes.rotation&&(display.cfg.rotation=nextRotation)}if(transform.scale&&applyScale){const nextScale=[...transform.scale];changes.scale=!MfdModule.vec3Equals(display.cfg.scale,nextScale),changes.scale&&(display.cfg.scale=nextScale)}return!(changes.position||changes.rotation||changes.scale)||(display.applyTransformToLiveParts(changes)||(display.restore(),display.ensureLoaded()),!0)}ensureLoaded(){const pickNodeReady=this.ensureGlobalMfdPickNodeHandler(),nodeBridgeReady=this.ensureRunNodeClickBridge();return this.mfds.forEach(display=>{display.ensureLoaded()}),pickNodeReady&&nodeBridgeReady}restore(){this.stopCameraWatch(),this.removeGlobalMfdPickNodeHandler(),this.removeRunNodeClickBridge(),this.mfds.forEach(display=>display.restore())}}!function(){"use strict";window.WeaponModuleDefaults={fighter:{defaultConfig:"A/A",loadouts:{"A/A":{gun:412,left:{wingtip:{load:"AIM-9X",display:"9M",quantity:2,type:"A/A"},hardpoint1:{load:"AIM-120D",display:"12M",quantity:2,type:"A/A"},hardpoint2:{load:"AIM-120D",display:"12M",quantity:2,type:"A/A"}},right:{wingtip:{load:"AIM-9X",display:"9M",quantity:2,type:"A/A"},hardpoint1:{load:"AIM-120D",display:"12M",quantity:2,type:"A/A"},hardpoint2:{load:"AIM-120D",display:"12M",quantity:2,type:"A/A"}}},"L/R A/A":{gun:412,left:{wingtip:{load:"AIM-9X",display:"9M",quantity:2,type:"A/A"},hardpoint1:{load:"AIM-120D",display:"12M",quantity:2,type:"A/A"},hardpoint2:{load:"Fuel",display:"FUEL",quantity:1,type:"FUEL"}},right:{wingtip:{load:"AIM-9X ",display:"9M",quantity:2,type:"A/A"},hardpoint1:{load:"AIM-120D",display:"12M",quantity:2,type:"A/A"},hardpoint2:{load:"Fuel",display:"FUEL",quantity:1,type:"FUEL"}}},"A/G":{gun:412,left:{wingtip:{load:"AIM-9X",display:"9M",quantity:2,type:"A/A"},hardpoint1:{load:"AGM-88",display:"HARM",quantity:1,type:"A/G"},hardpoint2:{load:"AGM-84K",display:"SLAM-ER",quantity:1,type:"A/G"}},right:{wingtip:{load:"AIM-9X",display:"9M",quantity:2,type:"A/A"},hardpoint1:{load:"AGM-88",display:"HARM",quantity:1,type:"A/G"},hardpoint2:{load:"JDAM",display:"JDAM",quantity:1,type:"A/G"}}},"L/R A/G":{gun:412,left:{wingtip:{load:"AIM-9X",display:"9M",quantity:2,type:"A/A"},hardpoint1:{load:"AGM-88",display:"HARM",quantity:1,type:"A/G"},hardpoint2:{load:"Fuel",display:"FUEL",quantity:1,type:"FUEL"}},right:{wingtip:{load:"AIM-9X",display:"9M",quantity:2,type:"A/A"},hardpoint1:{load:"AGM-88",display:"HARM",quantity:1,type:"A/G"},hardpoint2:{load:"Fuel",display:"FUEL",quantity:1,type:"FUEL"}}},"L/R":{gun:412,left:{wingtip:{load:"AIM-9X",display:"9M",quantity:1,type:"A/A"},hardpoint1:{load:"Fuel",display:"FUEL",quantity:1,type:"FUEL"},hardpoint2:{load:"Fuel",display:"FUEL",quantity:1,type:"FUEL"}},right:{wingtip:{load:"AIM-9X",display:"9M",quantity:1,type:"A/A"},hardpoint1:{load:"Fuel",display:"FUEL",quantity:1,type:"FUEL"},hardpoint2:{load:"Fuel",display:"FUEL",quantity:1,type:"FUEL"}}},MIN:{gun:300,left:{wingtip:{load:"AIM-9X",display:"9M",quantity:1,type:"A/A"},hardpoint1:{load:"N/A",display:"N/A",quantity:0,type:"N/A"},hardpoint2:{load:"N/A",display:"N/A",quantity:0,type:"N/A"}},right:{wingtip:{load:"AIM-9X",display:"9M",quantity:1,type:"A/A"},hardpoint1:{load:"N/A",display:"N/A",quantity:0,type:"N/A"},hardpoint2:{load:"N/A",display:"N/A",quantity:0,type:"N/A"}}},CLEAN:{gun:0,left:{wingtip:{load:"N/A",display:"N/A",quantity:0,type:"N/A"},hardpoint1:{load:"N/A",display:"N/A",quantity:0,type:"N/A"},hardpoint2:{load:"N/A",display:"N/A",quantity:0,type:"N/A"}},right:{wingtip:{load:"N/A",display:"N/A",quantity:0,type:"N/A"},hardpoint1:{load:"N/A",display:"N/A",quantity:0,type:"N/A"},hardpoint2:{load:"N/A",display:"N/A",quantity:0,type:"N/A"}}}}}}}(),function(){"use strict";const presets={fighter:[{type:"PROC",title:"Engine Start",items:["Parking Brake ON","Data Cartridge LOADED","Briefing/Mission CHECKED","Master Arm OFF","Radar OFF","Weapon Config SELECTED","Rearming FINISHED","Area CLEAR","Engine ON","Instruments CHECK"],completed:!1},{type:"PROC",title:"Before Taxi",items:["Ladder UP","Tailhook UP","Fuel Probe CLOSED","TGP Power OFF","Wings LOCKED","Flaps MAN","Canopy AS DESIRED","Recording AS DESIRED","Taxi REQUESTED"],completed:!1},{type:"PROC",title:"Taxi / Before Takeoff",items:["Taxi Clearance GRANTED","Parking Brake OFF","Flaps ONE","HUD Bright/LVL AS DESIRED","Trim SET T/O","Canopy CLOSED","Spoiler UP","Brakes CHECK","Flight Controls CHECK","Instruments CHECK","Takeoff Clearance REQUESTED"],completed:!1},{type:"PROC",title:"Takeoff",items:["Takeoff Clearance GRANTED","Runway CLEAR","Runway ALIGNED","Flaps ONE CHECK","Brakes ON","Engine 30%","Brakes RELEASED","Engine 100%","Speed 175 KN","Climb POSITIVE","Gear UP"],completed:!1},{type:"PROC",title:"Climb",items:["Flaps AUTO","Attitude SET","Trim SET","Radar AS DESIRED"],completed:!1},{type:"PROC",title:"Cruise",items:["Altitude AS BRIEFED","Speed AS BRIEFED","Trim SET","HUD Brightness AS DESIRED","HUD Level AS DESIRED"],completed:!1},{type:"PROC",title:"Descent",items:["Trim SET","Approach BRIEFED","ATIS CHECKED","Approach Clearance REQUESTED"],completed:!1},{type:"PROC",title:"Before landing",items:["Master Arm OFF","Radar OFF","Targeting Pod OFF","Landing Gear 3 GREEN","Flaps FULL"],completed:!1},{type:"PROC",title:"After Landing",items:["Taxi CLEAR OF RUNWAY","Taxi Clearance REQUESTED","Flaps UP"],completed:!1},{type:"PROC",title:"Taxi",items:["Taxi TO PARKING","Canopy AS DESIRED"],completed:!1},{type:"PROC",title:"Shutdown",items:["Parking Brake ON","Engine OFF"],completed:!1},{type:"EMER",title:"Engine Fire",items:["Throttle IDLE","Engine OFF","Divert NEAREST","Descent GLIDE","Airspeed SET OPTIMAL","Radio MAYDAY","Land ASAP"],completed:!1},{type:"OPS",title:"Targeting Pod - A/G",items:["Flightplan OPEN","Target MARK AS WAYPOINT","Entry INGRESS FROM SOUTH","Heading 0°","Flightplan SELECT TARGET WP","MFD SWITCH TO TGP","MODE/FREQ AS DESIRED","FOV WIDE","View ADJUST","FOV NARROW"],completed:!1},{type:"OPS",title:"Targeting Pod - A/A",items:["MFD SWITCH TO RDR","Radar ON","Foo AS DESIRED","MFD SWITCH TO NAV","A/C SELECT","MFD SWITCH TO TGP","Entry INGRESS FROM SOUTH","Heading 0°","Lock SET TO TRK","MODE / FOV AS DESIRED"],completed:!1},{type:"OPS",title:"Formation (Re)join",items:["Target LOCK","Closure > 1 nm - +60knots","Closure 6000 ft - 60 knots","Closure 2000 ft - 40 knots","Closure 500 ft - 20 knots","Visual Contact","Take position"],completed:!1},{type:"OPS",title:"Overhead Break (Landing)",items:["Runway DETERMINED","RW + break to L/R ANNOUNCED","Runway ALIGN","Alt/Speed AS BRIEFED","#1 Break ANNOUNCE","#1 BREAK","#2 and up REPEAT","Downwind Speed AS BRIEFED","Land"],completed:!1}]};window.ChecklistModuleDefaults={presets:presets,createModule:function createModule(presetName="fighter"){if("function"!=typeof ChecklistModule)return null;const preset=presets[presetName]??[],module=new ChecklistModule;for(const definition of preset)module.addChecklist(HelperModule.deepCloneJson(definition));return module}}}(),function(){"use strict";class BasePlugin{static LIFECYCLE_INTERVAL_MS=500;static getRuntime(){return window.GeoFsAddonPluginRuntime||(window.GeoFsAddonPluginRuntime={activePlugin:null,plugins:[],lifecycleTimer:null}),window.GeoFsAddonPluginRuntime}constructor(config={}){this.id=config.id,this.version=config.version,this.api=null,this.running=!1,this.managedModules=[],this.installAttempts=0,this.installComplete=!1,this.installMaxAttempts=50,this.once=Object.create(null)}static registerPlugin(plugin){const runtime=BasePlugin.getRuntime();return runtime.plugins.includes(plugin)||runtime.plugins.push(plugin),BasePlugin.ensureLifecycleLoop(),BasePlugin.syncPlugins(),plugin}static ensureLifecycleLoop(){const runtime=BasePlugin.getRuntime();runtime.lifecycleTimer||(runtime.lifecycleTimer=setInterval(()=>{BasePlugin.syncPlugins()},BasePlugin.LIFECYCLE_INTERVAL_MS))}static syncPlugins(){const runtime=BasePlugin.getRuntime();for(const plugin of runtime.plugins){const shouldRun=plugin.isAircraftActive(),isRunning=plugin.isRunning();shouldRun&&!isRunning?plugin.start():!shouldRun&&isRunning&&plugin.stop(),shouldRun&&plugin.isRunning()&&plugin.tickActive()}}static setActivePlugin(plugin){const runtime=BasePlugin.getRuntime();return runtime.activePlugin=plugin,runtime.activePlugin}static getActivePlugin(){return BasePlugin.getRuntime().activePlugin}static getActiveAddon(){return BasePlugin.getActivePlugin()?.addon??null}static isAircraftActive(){const activePlugin=BasePlugin.getActivePlugin();return!!activePlugin&&activePlugin.isAircraftActive()}static getActiveMfdPages(){const activePlugin=BasePlugin.getActivePlugin();return activePlugin?activePlugin.getMfdPages():[]}setManagedModules(modules){return this.managedModules=modules,this}initializeOptionalModules(addon,options={}){const weapons=addon?.weapons,cfg=value=>!0===value?{}:value,wantsCombat=!!(options.weaponHud||options.projectile||options.aaCombat||options.multiplayer);if(!weapons||!window.CombatContext||!wantsCombat&&!options.keybind)return addon.optionalModules=[],[];const combat=new window.CombatContext;combat.weapons=weapons;const modules=[],add=(name,Module,...args)=>{if(!Module)return null;const instance=new Module(...args);return modules.push(instance),addon[name]=instance,instance};return add("weaponOverlay",window.WeaponOverlayModule,combat,cfg(options.overlay)??{}),add("combatTargets",window.TargetModule,combat,addon),add("weaponAudio",window.WeaponAudioModule,combat,weapons,cfg(options.audio)??{}),options.keybind&&add("keybinds",window.KeybindModule,combat,weapons,cfg(options.keybind)),options.weaponHud&&add("weaponHud",window.WeaponHudModule,combat,weapons,cfg(options.weaponHud)),options.projectile&&add("projectile",window.ProjectileModule,combat,weapons,cfg(options.projectile)),options.aaCombat&&add("aaCombat",window.AACombatModule,combat,cfg(options.aaCombat)),options.multiplayer&&add("multiplayer",window.MultiplayerModule,combat,cfg(options.multiplayer)),addon.combat=combat,addon.optionalModules=modules,modules}startManagedModules(){for(const module of this.managedModules)"function"==typeof module.start&&module.start()}stopManagedModules(){for(let index=this.managedModules.length-1;index>=0;index-=1){const module=this.managedModules[index];"function"==typeof module.stop&&module.stop()}}resetInstallState(){this.installAttempts=0,this.installComplete=!1}startLifecycle(){return!this.running&&(!!this.isAircraftActive()&&(OptionModule.useStorageKeyForAircraft(this.id),BasePlugin.setActivePlugin(this),addonRuntime.mainPlugin=this,this.running=!0,this.resetInstallState(),this.startManagedModules(),!0))}stopLifecycle(){return!!this.running&&(this.running=!1,this.stopManagedModules(),BasePlugin.getActivePlugin()===this&&BasePlugin.setActivePlugin(null),addonRuntime.mainPlugin===this&&(addonRuntime.mainPlugin=null),!0)}runInstallTick(label,installer){return!this.running||this.installComplete||(this.installAttempts+=1,this.installComplete=installer(),!this.installComplete&&this.installAttempts>this.installMaxAttempts&&(this.installComplete=!0,console.warn(`[${label}] Install timeout after ${this.installMaxAttempts} attempts, continuing anyway`))),this.installComplete}runOnce(key,action){return!this.once[key]&&(action(),this.once[key]=!0,!0)}static createAddonApi({version:version,helper:helper={},options:options={},sections:sections={}}={}){return{version:version,helper:helper,options:options,...sections}}start(){throw new Error("start() must be implemented by subclass")}stop(){throw new Error("stop() must be implemented by subclass")}restart(){return this.stop(),this.start()}tickActive(){}getMfdPages(){return[]}isRunning(){return!1}isAircraftActive(){throw new Error("isAircraftActive() must be implemented by subclass")}}window.BasePlugin=BasePlugin}(),function(){"use strict";class F16MainPlugin extends window.BasePlugin{static AIRCRAFT_ID="7";static DEFAULT_MFD_LAYOUT=[{name:"LEFT",position:[.18,5.277,.714],rotation:[5.5,0,0],scale:[.27,.22,.26],defaultPageTitle:"NAV"},{name:"RIGHT",position:[-.189,5.277,.711],rotation:[5.5,0,0],scale:[.25,.22,.27],defaultPageTitle:"NAV"}];static CAMERA_CONFIG={cockpitViewPresets:[],cameraModeDefinitions:{}};constructor(config={}){super({id:"f16",version:config.version??"3.0.0"}),OptionModule.initializeStorageKey(this.id,"F16AddonOptions"),window.F16Addon={version:this.version,options:{buildKey:OptionModule.buildOptionKey,read:OptionModule.readOptions,write:OptionModule.writeOptions,get:OptionModule.getOption,set:OptionModule.setOption,getValue:OptionModule.getOptionValue},weapons:new WeaponModule({...window.WeaponModuleDefaults?.fighter,storageKey:"F16AddonWpnState"}),checklists:ChecklistModule.loadDefaults("fighter")??new ChecklistModule,helper:new HelperModule,map:null,nav:null,communication:new CommunicationModule,system:new SystemModule,hud:new F18HudModule,camera:null,fmc:new FMCModule,controls:null,dataCartridge:null,radar:null,targetingPod:null,flight:null,recorder:new RecorderModule,mfd:MfdModule,lifecycle:{start:()=>this.start(),stop:()=>this.stop(),restart:()=>this.restart(),isRunning:()=>this.isRunning()}},window.F16Addon.camera=new CameraModule(window.F16Addon.helper,F16MainPlugin.CAMERA_CONFIG),window.F16Addon.controls=new ControlModule(window.F16Addon.helper),window.F16Addon.nav=new NavModule,window.F16Addon.map=new MapModule,window.F16Addon.nav.setMapModule(window.F16Addon.map),window.F16Addon.map.setNavModule(window.F16Addon.nav),window.F16Addon.dataCartridge=new DataCartridgeModule,window.F16Addon.radar=new RadarModule({navModule:window.F16Addon.nav,weaponModule:window.F16Addon.weapons}),window.F16Addon.targetingPod=new TargetingPodModule(()=>window.F16Addon),window.F16Addon.flight=new FlightModule(()=>window.F16Addon),window.F16Addon.nav.setDataCartridgeModule(window.F16Addon.dataCartridge),window.F16Addon.mfd=new MfdModule(window.F16Addon.helper,window.F16Addon.map,window.F16Addon.camera,window.F16Addon.weapons,window.F16Addon.recorder),window.F16Addon.checklists.registerMfdPages(window.F16Addon.mfd),window.F16Addon.nav.registerMfdPages(window.F16Addon.mfd),window.F16Addon.weapons.registerMfdPages(window.F16Addon.mfd),window.F16Addon.hud.registerMfdPages(window.F16Addon.mfd),window.F16Addon.recorder.registerMfdPages(window.F16Addon.mfd),window.F16Addon.communication.registerMfdPages(window.F16Addon.mfd),window.F16Addon.system.registerMfdPages(window.F16Addon.mfd),window.F16Addon.radar.registerMfdPages(window.F16Addon.mfd),window.F16Addon.flight.registerMfdPages(window.F16Addon.mfd),window.F16Addon.targetingPod.registerMfdPages(window.F16Addon.mfd),this.setManagedModules([window.F16Addon.controls,...this.initializeOptionalModules(window.F16Addon,config.optionalModules??{keybind:!0,weaponHud:{enabled:!0},projectile:!0,aaCombat:{enabled:!0},multiplayer:{enabled:!0}})])}isAircraftActive(){return window.geofs?.aircraft?.instance?.id===F16MainPlugin.AIRCRAFT_ID}getMfdPages(){return window.F16Addon.mfd.pageRegistry}tryInstall(){return window.F16Addon.mfd.ensureLoaded()}start(){this.startLifecycle()&&(window.F16Addon.mfd.initializeDefaultMfds(F16MainPlugin.DEFAULT_MFD_LAYOUT),window.F16Addon.mfd.startCameraWatch(),this.tickActive())}tickActive(){this.runInstallTick("F16MainPlugin",()=>this.tryInstall())}stop(){this.stopLifecycle()&&window.F16Addon.mfd.restore()}restart(){this.stop(),this.start()}isRunning(){return this.running}}window.F16MainPlugin=F16MainPlugin}(),function(){"use strict";const PluginCtor=window.F16MainPlugin;if("function"!=typeof PluginCtor)return void console.error("[GeoFS F-16 Addon] F16MainPlugin is not available on window.");const plugin=new PluginCtor({version:"3.0.0"});window.F16Plugin=plugin,window.BasePlugin.registerPlugin(plugin)}();