mapEngine.ts 130 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008
  1. import { getTileSizePx, screenToWorld, worldToScreen, type CameraState } from '../camera/camera'
  2. import { AccelerometerController } from '../sensor/accelerometerController'
  3. import { CompassHeadingController, type CompassTuningProfile } from '../sensor/compassHeadingController'
  4. import { DeviceMotionController } from '../sensor/deviceMotionController'
  5. import { GyroscopeController } from '../sensor/gyroscopeController'
  6. import { type HeartRateDiscoveredDevice } from '../sensor/heartRateController'
  7. import { HeartRateInputController } from '../sensor/heartRateInputController'
  8. import { LocationController } from '../sensor/locationController'
  9. import { WebGLMapRenderer } from '../renderer/webglMapRenderer'
  10. import { type MapRendererStats } from '../renderer/mapRenderer'
  11. import { lonLatToWorldTile, worldTileToLonLat, type LonLatPoint, type MapCalibration } from '../../utils/projection'
  12. import { type OrienteeringCourseData } from '../../utils/orienteeringCourse'
  13. import { isTileWithinBounds, type RemoteMapConfig, type TileZoomBounds } from '../../utils/remoteMapConfig'
  14. import { formatAnimationLevelText, resolveAnimationLevel, type AnimationLevel } from '../../utils/animationLevel'
  15. import { GameRuntime } from '../../game/core/gameRuntime'
  16. import { type GameEffect, type GameResult } from '../../game/core/gameResult'
  17. import { buildGameDefinitionFromCourse } from '../../game/content/courseToGameDefinition'
  18. import { FeedbackDirector } from '../../game/feedback/feedbackDirector'
  19. import { EMPTY_GAME_PRESENTATION_STATE, type GamePresentationState } from '../../game/presentation/presentationState'
  20. import { TelemetryRuntime } from '../../game/telemetry/telemetryRuntime'
  21. import { getHeartRateToneSampleBpm, type HeartRateTone } from '../../game/telemetry/telemetryConfig'
  22. const RENDER_MODE = 'Single WebGL Pipeline'
  23. const PROJECTION_MODE = 'WGS84 -> WorldTile -> Camera -> Screen'
  24. const MAP_NORTH_OFFSET_DEG = 0
  25. let MAGNETIC_DECLINATION_DEG = -6.91
  26. let MAGNETIC_DECLINATION_TEXT = '6.91˚ W'
  27. const MIN_ZOOM = 15
  28. const MAX_ZOOM = 20
  29. const DEFAULT_ZOOM = 17
  30. const DESIRED_VISIBLE_COLUMNS = 3
  31. const OVERDRAW = 1
  32. const DEFAULT_TOP_LEFT_TILE_X = 108132
  33. const DEFAULT_TOP_LEFT_TILE_Y = 51199
  34. const DEFAULT_CENTER_TILE_X = DEFAULT_TOP_LEFT_TILE_X + 1
  35. const DEFAULT_CENTER_TILE_Y = DEFAULT_TOP_LEFT_TILE_Y + 1
  36. const TILE_SOURCE = 'https://oss-mbh5.colormaprun.com/wxMap/lcx/{z}/{x}/{y}.png'
  37. const OSM_TILE_SOURCE = 'https://tiles.mymarsgo.xyz/{z}/{x}/{y}.png'
  38. const MAP_OVERLAY_OPACITY = 0.72
  39. const GPS_MAP_CALIBRATION: MapCalibration = {
  40. offsetEastMeters: 0,
  41. offsetNorthMeters: 0,
  42. rotationDeg: 0,
  43. scale: 1,
  44. }
  45. const MIN_PREVIEW_SCALE = 0.55
  46. const MAX_PREVIEW_SCALE = 1.85
  47. const INERTIA_FRAME_MS = 16
  48. const INERTIA_DECAY = 0.92
  49. const INERTIA_MIN_SPEED = 0.02
  50. const PREVIEW_RESET_DURATION_MS = 140
  51. const UI_SYNC_INTERVAL_MS = 80
  52. const ROTATE_STEP_DEG = 15
  53. const AUTO_ROTATE_FRAME_MS = 8
  54. const AUTO_ROTATE_EASE = 0.34
  55. const AUTO_ROTATE_SNAP_DEG = 0.1
  56. const AUTO_ROTATE_DEADZONE_DEG = 4
  57. const AUTO_ROTATE_MAX_STEP_DEG = 0.75
  58. const AUTO_ROTATE_HEADING_SMOOTHING = 0.46
  59. const COMPASS_NEEDLE_FRAME_MS = 16
  60. const COMPASS_NEEDLE_SNAP_DEG = 0.08
  61. const COMPASS_BOOTSTRAP_RETRY_DELAY_MS = 700
  62. const COMPASS_TUNING_PRESETS: Record<CompassTuningProfile, {
  63. needleMinSmoothing: number
  64. needleMaxSmoothing: number
  65. displayDeadzoneDeg: number
  66. }> = {
  67. smooth: {
  68. needleMinSmoothing: 0.16,
  69. needleMaxSmoothing: 0.4,
  70. displayDeadzoneDeg: 0.75,
  71. },
  72. balanced: {
  73. needleMinSmoothing: 0.22,
  74. needleMaxSmoothing: 0.52,
  75. displayDeadzoneDeg: 0.45,
  76. },
  77. responsive: {
  78. needleMinSmoothing: 0.3,
  79. needleMaxSmoothing: 0.68,
  80. displayDeadzoneDeg: 0.2,
  81. },
  82. }
  83. const SMART_HEADING_BLEND_START_SPEED_KMH = 1.2
  84. const SMART_HEADING_MOVEMENT_SPEED_KMH = 3.0
  85. const SMART_HEADING_MIN_DISTANCE_METERS = 12
  86. const SMART_HEADING_MAX_ACCURACY_METERS = 25
  87. const SMART_HEADING_MOVEMENT_MIN_SMOOTHING = 0.12
  88. const SMART_HEADING_MOVEMENT_MAX_SMOOTHING = 0.24
  89. const GPS_TRACK_MAX_POINTS = 200
  90. const GPS_TRACK_MIN_STEP_METERS = 3
  91. const MAP_TAP_MOVE_THRESHOLD_PX = 14
  92. const MAP_TAP_DURATION_MS = 280
  93. type TouchPoint = WechatMiniprogram.TouchDetail
  94. type GestureMode = 'idle' | 'pan' | 'pinch'
  95. type RotationMode = 'manual' | 'auto'
  96. type OrientationMode = 'manual' | 'north-up' | 'heading-up'
  97. type AutoRotateSourceMode = 'sensor' | 'course' | 'fusion' | 'smart'
  98. type SmartHeadingSource = 'sensor' | 'blended' | 'movement'
  99. type NorthReferenceMode = 'magnetic' | 'true'
  100. const DEFAULT_NORTH_REFERENCE_MODE: NorthReferenceMode = 'magnetic'
  101. export interface MapEngineStageRect {
  102. width: number
  103. height: number
  104. left: number
  105. top: number
  106. }
  107. export interface MapEngineViewState {
  108. animationLevel: AnimationLevel
  109. buildVersion: string
  110. renderMode: string
  111. projectionMode: string
  112. mapReady: boolean
  113. mapReadyText: string
  114. mapName: string
  115. configStatusText: string
  116. zoom: number
  117. rotationDeg: number
  118. rotationText: string
  119. rotationMode: RotationMode
  120. rotationModeText: string
  121. rotationToggleText: string
  122. orientationMode: OrientationMode
  123. orientationModeText: string
  124. sensorHeadingText: string
  125. deviceHeadingText: string
  126. devicePoseText: string
  127. headingConfidenceText: string
  128. accelerometerText: string
  129. gyroscopeText: string
  130. deviceMotionText: string
  131. compassSourceText: string
  132. compassTuningProfile: CompassTuningProfile
  133. compassTuningProfileText: string
  134. compassDeclinationText: string
  135. northReferenceMode: NorthReferenceMode
  136. northReferenceButtonText: string
  137. autoRotateSourceText: string
  138. autoRotateCalibrationText: string
  139. northReferenceText: string
  140. compassNeedleDeg: number
  141. centerTileX: number
  142. centerTileY: number
  143. centerText: string
  144. tileSource: string
  145. visibleColumnCount: number
  146. visibleTileCount: number
  147. readyTileCount: number
  148. memoryTileCount: number
  149. diskTileCount: number
  150. memoryHitCount: number
  151. diskHitCount: number
  152. networkFetchCount: number
  153. cacheHitRateText: string
  154. tileTranslateX: number
  155. tileTranslateY: number
  156. tileSizePx: number
  157. previewScale: number
  158. stageWidth: number
  159. stageHeight: number
  160. stageLeft: number
  161. stageTop: number
  162. statusText: string
  163. gpsTracking: boolean
  164. gpsTrackingText: string
  165. gpsLockEnabled: boolean
  166. gpsLockAvailable: boolean
  167. locationSourceMode: 'real' | 'mock'
  168. locationSourceText: string
  169. mockBridgeConnected: boolean
  170. mockBridgeStatusText: string
  171. mockBridgeUrlText: string
  172. mockCoordText: string
  173. mockSpeedText: string
  174. gpsCoordText: string
  175. heartRateSourceMode: 'real' | 'mock'
  176. heartRateSourceText: string
  177. heartRateConnected: boolean
  178. heartRateStatusText: string
  179. heartRateDeviceText: string
  180. heartRateScanText: string
  181. heartRateDiscoveredDevices: Array<{
  182. deviceId: string
  183. name: string
  184. rssiText: string
  185. preferred: boolean
  186. connected: boolean
  187. }>
  188. mockHeartRateBridgeConnected: boolean
  189. mockHeartRateBridgeStatusText: string
  190. mockHeartRateBridgeUrlText: string
  191. mockHeartRateText: string
  192. gameSessionStatus: 'idle' | 'running' | 'finished' | 'failed'
  193. gameModeText: string
  194. panelTimerText: string
  195. panelMileageText: string
  196. panelActionTagText: string
  197. panelDistanceTagText: string
  198. panelDistanceValueText: string
  199. panelDistanceUnitText: string
  200. panelProgressText: string
  201. panelSpeedValueText: string
  202. panelTelemetryTone: 'blue' | 'purple' | 'green' | 'yellow' | 'orange' | 'red'
  203. panelHeartRateZoneNameText: string
  204. panelHeartRateZoneRangeText: string
  205. panelHeartRateValueText: string
  206. panelHeartRateUnitText: string
  207. panelCaloriesValueText: string
  208. panelCaloriesUnitText: string
  209. panelAverageSpeedValueText: string
  210. panelAverageSpeedUnitText: string
  211. panelAccuracyValueText: string
  212. panelAccuracyUnitText: string
  213. punchButtonText: string
  214. punchButtonEnabled: boolean
  215. skipButtonEnabled: boolean
  216. punchHintText: string
  217. punchFeedbackVisible: boolean
  218. punchFeedbackText: string
  219. punchFeedbackTone: 'neutral' | 'success' | 'warning'
  220. contentCardVisible: boolean
  221. contentCardTitle: string
  222. contentCardBody: string
  223. punchButtonFxClass: string
  224. panelProgressFxClass: string
  225. panelDistanceFxClass: string
  226. punchFeedbackFxClass: string
  227. contentCardFxClass: string
  228. mapPulseVisible: boolean
  229. mapPulseLeftPx: number
  230. mapPulseTopPx: number
  231. mapPulseFxClass: string
  232. stageFxVisible: boolean
  233. stageFxClass: string
  234. osmReferenceEnabled: boolean
  235. osmReferenceText: string
  236. }
  237. export interface MapEngineCallbacks {
  238. onData: (patch: Partial<MapEngineViewState>) => void
  239. }
  240. export interface MapEngineGameInfoRow {
  241. label: string
  242. value: string
  243. }
  244. export interface MapEngineGameInfoSnapshot {
  245. title: string
  246. subtitle: string
  247. localRows: MapEngineGameInfoRow[]
  248. globalRows: MapEngineGameInfoRow[]
  249. }
  250. const VIEW_SYNC_KEYS: Array<keyof MapEngineViewState> = [
  251. 'animationLevel',
  252. 'buildVersion',
  253. 'renderMode',
  254. 'projectionMode',
  255. 'mapReady',
  256. 'mapReadyText',
  257. 'mapName',
  258. 'configStatusText',
  259. 'zoom',
  260. 'centerTileX',
  261. 'centerTileY',
  262. 'rotationDeg',
  263. 'rotationText',
  264. 'rotationMode',
  265. 'rotationModeText',
  266. 'rotationToggleText',
  267. 'orientationMode',
  268. 'orientationModeText',
  269. 'sensorHeadingText',
  270. 'deviceHeadingText',
  271. 'devicePoseText',
  272. 'headingConfidenceText',
  273. 'accelerometerText',
  274. 'gyroscopeText',
  275. 'deviceMotionText',
  276. 'compassSourceText',
  277. 'compassTuningProfile',
  278. 'compassTuningProfileText',
  279. 'compassDeclinationText',
  280. 'northReferenceMode',
  281. 'northReferenceButtonText',
  282. 'autoRotateSourceText',
  283. 'autoRotateCalibrationText',
  284. 'northReferenceText',
  285. 'compassNeedleDeg',
  286. 'centerText',
  287. 'tileSource',
  288. 'visibleTileCount',
  289. 'readyTileCount',
  290. 'memoryTileCount',
  291. 'diskTileCount',
  292. 'memoryHitCount',
  293. 'diskHitCount',
  294. 'networkFetchCount',
  295. 'cacheHitRateText',
  296. 'tileSizePx',
  297. 'previewScale',
  298. 'stageWidth',
  299. 'stageHeight',
  300. 'stageLeft',
  301. 'stageTop',
  302. 'statusText',
  303. 'gpsTracking',
  304. 'gpsTrackingText',
  305. 'gpsLockEnabled',
  306. 'gpsLockAvailable',
  307. 'locationSourceMode',
  308. 'locationSourceText',
  309. 'mockBridgeConnected',
  310. 'mockBridgeStatusText',
  311. 'mockBridgeUrlText',
  312. 'mockCoordText',
  313. 'mockSpeedText',
  314. 'gpsCoordText',
  315. 'heartRateSourceMode',
  316. 'heartRateSourceText',
  317. 'heartRateConnected',
  318. 'heartRateStatusText',
  319. 'heartRateDeviceText',
  320. 'heartRateScanText',
  321. 'heartRateDiscoveredDevices',
  322. 'mockHeartRateBridgeConnected',
  323. 'mockHeartRateBridgeStatusText',
  324. 'mockHeartRateBridgeUrlText',
  325. 'mockHeartRateText',
  326. 'gameSessionStatus',
  327. 'gameModeText',
  328. 'panelTimerText',
  329. 'panelMileageText',
  330. 'panelActionTagText',
  331. 'panelDistanceTagText',
  332. 'panelDistanceValueText',
  333. 'panelDistanceUnitText',
  334. 'panelProgressText',
  335. 'panelSpeedValueText',
  336. 'panelTelemetryTone',
  337. 'panelHeartRateZoneNameText',
  338. 'panelHeartRateZoneRangeText',
  339. 'panelHeartRateValueText',
  340. 'panelHeartRateUnitText',
  341. 'panelCaloriesValueText',
  342. 'panelCaloriesUnitText',
  343. 'panelAverageSpeedValueText',
  344. 'panelAverageSpeedUnitText',
  345. 'panelAccuracyValueText',
  346. 'panelAccuracyUnitText',
  347. 'punchButtonText',
  348. 'punchButtonEnabled',
  349. 'skipButtonEnabled',
  350. 'punchHintText',
  351. 'punchFeedbackVisible',
  352. 'punchFeedbackText',
  353. 'punchFeedbackTone',
  354. 'contentCardVisible',
  355. 'contentCardTitle',
  356. 'contentCardBody',
  357. 'punchButtonFxClass',
  358. 'panelProgressFxClass',
  359. 'panelDistanceFxClass',
  360. 'punchFeedbackFxClass',
  361. 'contentCardFxClass',
  362. 'mapPulseVisible',
  363. 'mapPulseLeftPx',
  364. 'mapPulseTopPx',
  365. 'mapPulseFxClass',
  366. 'stageFxVisible',
  367. 'stageFxClass',
  368. 'osmReferenceEnabled',
  369. 'osmReferenceText',
  370. ]
  371. const INTERACTION_DEFERRED_VIEW_KEYS = new Set<keyof MapEngineViewState>([
  372. 'rotationText',
  373. 'sensorHeadingText',
  374. 'deviceHeadingText',
  375. 'devicePoseText',
  376. 'headingConfidenceText',
  377. 'accelerometerText',
  378. 'gyroscopeText',
  379. 'deviceMotionText',
  380. 'compassSourceText',
  381. 'compassTuningProfile',
  382. 'compassTuningProfileText',
  383. 'compassDeclinationText',
  384. 'autoRotateSourceText',
  385. 'autoRotateCalibrationText',
  386. 'northReferenceText',
  387. 'centerText',
  388. 'gpsCoordText',
  389. 'visibleTileCount',
  390. 'readyTileCount',
  391. 'memoryTileCount',
  392. 'diskTileCount',
  393. 'memoryHitCount',
  394. 'diskHitCount',
  395. 'networkFetchCount',
  396. 'cacheHitRateText',
  397. 'heartRateDiscoveredDevices',
  398. 'mockCoordText',
  399. 'mockSpeedText',
  400. 'mockHeartRateText',
  401. ])
  402. function buildCenterText(zoom: number, x: number, y: number): string {
  403. return `z${zoom} / x${x} / y${y}`
  404. }
  405. function clamp(value: number, min: number, max: number): number {
  406. return Math.max(min, Math.min(max, value))
  407. }
  408. function normalizeRotationDeg(rotationDeg: number): number {
  409. const normalized = rotationDeg % 360
  410. return normalized < 0 ? normalized + 360 : normalized
  411. }
  412. function normalizeAngleDeltaRad(angleDeltaRad: number): number {
  413. let normalized = angleDeltaRad
  414. while (normalized > Math.PI) {
  415. normalized -= Math.PI * 2
  416. }
  417. while (normalized < -Math.PI) {
  418. normalized += Math.PI * 2
  419. }
  420. return normalized
  421. }
  422. function normalizeAngleDeltaDeg(angleDeltaDeg: number): number {
  423. let normalized = angleDeltaDeg
  424. while (normalized > 180) {
  425. normalized -= 360
  426. }
  427. while (normalized < -180) {
  428. normalized += 360
  429. }
  430. return normalized
  431. }
  432. function interpolateAngleDeg(currentDeg: number, targetDeg: number, factor: number): number {
  433. return normalizeRotationDeg(currentDeg + normalizeAngleDeltaDeg(targetDeg - currentDeg) * factor)
  434. }
  435. function getCompassNeedleSmoothingFactor(
  436. currentDeg: number,
  437. targetDeg: number,
  438. profile: CompassTuningProfile,
  439. ): number {
  440. const preset = COMPASS_TUNING_PRESETS[profile]
  441. const deltaDeg = Math.abs(normalizeAngleDeltaDeg(targetDeg - currentDeg))
  442. if (deltaDeg <= 4) {
  443. return preset.needleMinSmoothing
  444. }
  445. if (deltaDeg >= 36) {
  446. return preset.needleMaxSmoothing
  447. }
  448. const progress = (deltaDeg - 4) / (36 - 4)
  449. return preset.needleMinSmoothing
  450. + (preset.needleMaxSmoothing - preset.needleMinSmoothing) * progress
  451. }
  452. function getMovementHeadingSmoothingFactor(speedKmh: number | null): number {
  453. if (speedKmh === null || !Number.isFinite(speedKmh) || speedKmh <= SMART_HEADING_BLEND_START_SPEED_KMH) {
  454. return SMART_HEADING_MOVEMENT_MIN_SMOOTHING
  455. }
  456. if (speedKmh >= SMART_HEADING_MOVEMENT_SPEED_KMH) {
  457. return SMART_HEADING_MOVEMENT_MAX_SMOOTHING
  458. }
  459. const progress = (speedKmh - SMART_HEADING_BLEND_START_SPEED_KMH)
  460. / (SMART_HEADING_MOVEMENT_SPEED_KMH - SMART_HEADING_BLEND_START_SPEED_KMH)
  461. return SMART_HEADING_MOVEMENT_MIN_SMOOTHING
  462. + (SMART_HEADING_MOVEMENT_MAX_SMOOTHING - SMART_HEADING_MOVEMENT_MIN_SMOOTHING) * progress
  463. }
  464. function formatGameSessionStatusText(status: 'idle' | 'running' | 'finished' | 'failed'): string {
  465. if (status === 'running') {
  466. return '进行中'
  467. }
  468. if (status === 'finished') {
  469. return '已结束'
  470. }
  471. if (status === 'failed') {
  472. return '已失败'
  473. }
  474. return '未开始'
  475. }
  476. function formatRotationText(rotationDeg: number): string {
  477. return `${Math.round(normalizeRotationDeg(rotationDeg))}deg`
  478. }
  479. function normalizeDegreeDisplayText(text: string): string {
  480. return text.replace(/[掳•˚]/g, '°')
  481. }
  482. function formatHeadingText(headingDeg: number | null): string {
  483. if (headingDeg === null) {
  484. return '--'
  485. }
  486. return `${Math.round(normalizeRotationDeg(headingDeg))}°`
  487. }
  488. function formatDevicePoseText(pose: 'upright' | 'tilted' | 'flat'): string {
  489. if (pose === 'flat') {
  490. return '平放'
  491. }
  492. if (pose === 'tilted') {
  493. return '倾斜'
  494. }
  495. return '竖持'
  496. }
  497. function formatHeadingConfidenceText(confidence: 'low' | 'medium' | 'high'): string {
  498. if (confidence === 'high') {
  499. return '高'
  500. }
  501. if (confidence === 'medium') {
  502. return '中'
  503. }
  504. return '低'
  505. }
  506. function formatClockTime(timestamp: number | null): string {
  507. if (!timestamp || !Number.isFinite(timestamp)) {
  508. return '--:--:--'
  509. }
  510. const date = new Date(timestamp)
  511. const hh = String(date.getHours()).padStart(2, '0')
  512. const mm = String(date.getMinutes()).padStart(2, '0')
  513. const ss = String(date.getSeconds()).padStart(2, '0')
  514. return `${hh}:${mm}:${ss}`
  515. }
  516. function formatGyroscopeText(gyroscope: { x: number; y: number; z: number } | null): string {
  517. if (!gyroscope) {
  518. return '--'
  519. }
  520. return `x:${gyroscope.x.toFixed(2)} y:${gyroscope.y.toFixed(2)} z:${gyroscope.z.toFixed(2)}`
  521. }
  522. function formatDeviceMotionText(motion: { alpha: number | null; beta: number | null; gamma: number | null } | null): string {
  523. if (!motion) {
  524. return '--'
  525. }
  526. const alphaDeg = motion.alpha === null ? '--' : Math.round(normalizeRotationDeg(360 - motion.alpha))
  527. const betaDeg = motion.beta === null ? '--' : Math.round(motion.beta)
  528. const gammaDeg = motion.gamma === null ? '--' : Math.round(motion.gamma)
  529. return `a:${alphaDeg} b:${betaDeg} g:${gammaDeg}`
  530. }
  531. function formatOrientationModeText(mode: OrientationMode): string {
  532. if (mode === 'north-up') {
  533. return 'North Up'
  534. }
  535. if (mode === 'heading-up') {
  536. return 'Heading Up'
  537. }
  538. return 'Manual Gesture'
  539. }
  540. function formatRotationModeText(mode: OrientationMode): string {
  541. return formatOrientationModeText(mode)
  542. }
  543. function formatRotationToggleText(mode: OrientationMode): string {
  544. if (mode === 'manual') {
  545. return '切到北朝上'
  546. }
  547. if (mode === 'north-up') {
  548. return '切到朝向朝上'
  549. }
  550. return '切到手动旋转'
  551. }
  552. function formatAutoRotateSourceText(mode: AutoRotateSourceMode, hasCourseHeading: boolean): string {
  553. if (mode === 'smart') {
  554. return 'Smart / 手机朝向'
  555. }
  556. if (mode === 'sensor') {
  557. return 'Sensor Only'
  558. }
  559. if (mode === 'course') {
  560. return hasCourseHeading ? 'Course Only' : 'Course Pending'
  561. }
  562. return hasCourseHeading ? 'Sensor + Course' : 'Sensor Only'
  563. }
  564. function formatSmartHeadingSourceText(source: SmartHeadingSource): string {
  565. if (source === 'movement') {
  566. return 'Smart / 前进方向'
  567. }
  568. if (source === 'blended') {
  569. return 'Smart / 融合'
  570. }
  571. return 'Smart / 手机朝向'
  572. }
  573. function formatAutoRotateCalibrationText(pending: boolean, offsetDeg: number | null): string {
  574. if (pending) {
  575. return 'Pending'
  576. }
  577. if (offsetDeg === null) {
  578. return '--'
  579. }
  580. return `Offset ${Math.round(normalizeRotationDeg(offsetDeg))}deg`
  581. }
  582. function getTrueHeadingDeg(magneticHeadingDeg: number): number {
  583. return normalizeRotationDeg(magneticHeadingDeg + MAGNETIC_DECLINATION_DEG)
  584. }
  585. function getMagneticHeadingDeg(trueHeadingDeg: number): number {
  586. return normalizeRotationDeg(trueHeadingDeg - MAGNETIC_DECLINATION_DEG)
  587. }
  588. function getMapNorthOffsetDeg(_mode: NorthReferenceMode): number {
  589. return MAP_NORTH_OFFSET_DEG
  590. }
  591. function getCompassReferenceHeadingDeg(mode: NorthReferenceMode, magneticHeadingDeg: number): number {
  592. if (mode === 'true') {
  593. return getTrueHeadingDeg(magneticHeadingDeg)
  594. }
  595. return normalizeRotationDeg(magneticHeadingDeg)
  596. }
  597. function getMapReferenceHeadingDegFromSensor(mode: NorthReferenceMode, magneticHeadingDeg: number): number {
  598. if (mode === 'magnetic') {
  599. return normalizeRotationDeg(magneticHeadingDeg)
  600. }
  601. return getTrueHeadingDeg(magneticHeadingDeg)
  602. }
  603. function getMapReferenceHeadingDegFromCourse(mode: NorthReferenceMode, trueHeadingDeg: number): number {
  604. if (mode === 'magnetic') {
  605. return getMagneticHeadingDeg(trueHeadingDeg)
  606. }
  607. return normalizeRotationDeg(trueHeadingDeg)
  608. }
  609. function formatNorthReferenceText(mode: NorthReferenceMode): string {
  610. if (mode === 'magnetic') {
  611. return `Compass Magnetic / Heading-Up Magnetic (${MAGNETIC_DECLINATION_TEXT})`
  612. }
  613. return `Compass True / Heading-Up True (${MAGNETIC_DECLINATION_TEXT})`
  614. }
  615. function formatCompassDeclinationText(mode: NorthReferenceMode): string {
  616. if (mode === 'true') {
  617. return MAGNETIC_DECLINATION_TEXT
  618. }
  619. return ''
  620. }
  621. function formatCompassSourceText(source: 'compass' | 'motion' | null): string {
  622. if (source === 'compass') {
  623. return '罗盘'
  624. }
  625. if (source === 'motion') {
  626. return '设备方向兜底'
  627. }
  628. return '无数据'
  629. }
  630. function formatCompassTuningProfileText(profile: CompassTuningProfile): string {
  631. if (profile === 'smooth') {
  632. return '顺滑'
  633. }
  634. if (profile === 'responsive') {
  635. return '跟手'
  636. }
  637. return '平衡'
  638. }
  639. function formatNorthReferenceButtonText(mode: NorthReferenceMode): string {
  640. return mode === 'magnetic' ? '北参照:磁北' : '北参照:真北'
  641. }
  642. function formatNorthReferenceStatusText(mode: NorthReferenceMode): string {
  643. if (mode === 'magnetic') {
  644. return '已切到磁北模式'
  645. }
  646. return '已切到真北模式'
  647. }
  648. function getNextNorthReferenceMode(mode: NorthReferenceMode): NorthReferenceMode {
  649. return mode === 'magnetic' ? 'true' : 'magnetic'
  650. }
  651. function formatCompassNeedleDegForMode(mode: NorthReferenceMode, magneticHeadingDeg: number | null): number {
  652. if (magneticHeadingDeg === null) {
  653. return 0
  654. }
  655. const referenceHeadingDeg = mode === 'true'
  656. ? getTrueHeadingDeg(magneticHeadingDeg)
  657. : normalizeRotationDeg(magneticHeadingDeg)
  658. return normalizeRotationDeg(360 - referenceHeadingDeg)
  659. }
  660. function formatCacheHitRate(memoryHitCount: number, diskHitCount: number, networkFetchCount: number): string {
  661. const total = memoryHitCount + diskHitCount + networkFetchCount
  662. if (!total) {
  663. return '--'
  664. }
  665. const hitRate = ((memoryHitCount + diskHitCount) / total) * 100
  666. return `${Math.round(hitRate)}%`
  667. }
  668. function formatGpsCoordText(point: LonLatPoint | null, accuracyMeters: number | null): string {
  669. if (!point) {
  670. return '--'
  671. }
  672. const base = `${point.lat.toFixed(6)}, ${point.lon.toFixed(6)}`
  673. if (accuracyMeters === null || !Number.isFinite(accuracyMeters)) {
  674. return base
  675. }
  676. return `${base} / 卤${Math.round(accuracyMeters)}m`
  677. }
  678. function getApproxDistanceMeters(a: LonLatPoint, b: LonLatPoint): number {
  679. const avgLatRad = ((a.lat + b.lat) / 2) * Math.PI / 180
  680. const dx = (b.lon - a.lon) * 111320 * Math.cos(avgLatRad)
  681. const dy = (b.lat - a.lat) * 110540
  682. return Math.sqrt(dx * dx + dy * dy)
  683. }
  684. function resolveSmartHeadingSource(speedKmh: number | null, movementReliable: boolean): SmartHeadingSource {
  685. if (!movementReliable || speedKmh === null || !Number.isFinite(speedKmh) || speedKmh <= SMART_HEADING_BLEND_START_SPEED_KMH) {
  686. return 'sensor'
  687. }
  688. if (speedKmh >= SMART_HEADING_MOVEMENT_SPEED_KMH) {
  689. return 'movement'
  690. }
  691. return 'blended'
  692. }
  693. function getInitialBearingDeg(from: LonLatPoint, to: LonLatPoint): number {
  694. const fromLatRad = from.lat * Math.PI / 180
  695. const toLatRad = to.lat * Math.PI / 180
  696. const deltaLonRad = (to.lon - from.lon) * Math.PI / 180
  697. const y = Math.sin(deltaLonRad) * Math.cos(toLatRad)
  698. const x = Math.cos(fromLatRad) * Math.sin(toLatRad) - Math.sin(fromLatRad) * Math.cos(toLatRad) * Math.cos(deltaLonRad)
  699. const bearingDeg = Math.atan2(y, x) * 180 / Math.PI
  700. return normalizeRotationDeg(bearingDeg)
  701. }
  702. export class MapEngine {
  703. buildVersion: string
  704. animationLevel: AnimationLevel
  705. renderer: WebGLMapRenderer
  706. accelerometerController: AccelerometerController
  707. compassController: CompassHeadingController
  708. gyroscopeController: GyroscopeController
  709. deviceMotionController: DeviceMotionController
  710. locationController: LocationController
  711. heartRateController: HeartRateInputController
  712. feedbackDirector: FeedbackDirector
  713. onData: (patch: Partial<MapEngineViewState>) => void
  714. state: MapEngineViewState
  715. accelerometerErrorText: string | null
  716. previewScale: number
  717. previewOriginX: number
  718. previewOriginY: number
  719. panLastX: number
  720. panLastY: number
  721. panLastTimestamp: number
  722. tapStartX: number
  723. tapStartY: number
  724. tapStartAt: number
  725. panVelocityX: number
  726. panVelocityY: number
  727. pinchStartDistance: number
  728. pinchStartScale: number
  729. pinchStartAngle: number
  730. pinchStartRotationDeg: number
  731. pinchAnchorWorldX: number
  732. pinchAnchorWorldY: number
  733. gestureMode: GestureMode
  734. inertiaTimer: number
  735. previewResetTimer: number
  736. viewSyncTimer: number
  737. autoRotateTimer: number
  738. compassNeedleTimer: number
  739. compassBootstrapRetryTimer: number
  740. pendingViewPatch: Partial<MapEngineViewState>
  741. mounted: boolean
  742. diagnosticUiEnabled: boolean
  743. northReferenceMode: NorthReferenceMode
  744. sensorHeadingDeg: number | null
  745. smoothedSensorHeadingDeg: number | null
  746. compassDisplayHeadingDeg: number | null
  747. targetCompassDisplayHeadingDeg: number | null
  748. lastCompassSampleAt: number
  749. compassSource: 'compass' | 'motion' | null
  750. compassTuningProfile: CompassTuningProfile
  751. smoothedMovementHeadingDeg: number | null
  752. autoRotateHeadingDeg: number | null
  753. courseHeadingDeg: number | null
  754. targetAutoRotationDeg: number | null
  755. autoRotateSourceMode: AutoRotateSourceMode
  756. autoRotateCalibrationOffsetDeg: number | null
  757. autoRotateCalibrationPending: boolean
  758. lastStatsUiSyncAt: number
  759. minZoom: number
  760. maxZoom: number
  761. defaultZoom: number
  762. defaultCenterTileX: number
  763. defaultCenterTileY: number
  764. tileBoundsByZoom: Record<number, TileZoomBounds> | null
  765. currentGpsPoint: LonLatPoint | null
  766. currentGpsTrack: LonLatPoint[]
  767. currentGpsAccuracyMeters: number | null
  768. currentGpsInsideMap: boolean
  769. courseData: OrienteeringCourseData | null
  770. courseOverlayVisible: boolean
  771. cpRadiusMeters: number
  772. configAppId: string
  773. configSchemaVersion: string
  774. configVersion: string
  775. controlScoreOverrides: Record<string, number>
  776. defaultControlScore: number | null
  777. gameRuntime: GameRuntime
  778. telemetryRuntime: TelemetryRuntime
  779. gamePresentation: GamePresentationState
  780. gameMode: 'classic-sequential' | 'score-o'
  781. punchPolicy: 'enter' | 'enter-confirm'
  782. punchRadiusMeters: number
  783. requiresFocusSelection: boolean
  784. skipEnabled: boolean
  785. skipRadiusMeters: number
  786. skipRequiresConfirm: boolean
  787. autoFinishOnLastControl: boolean
  788. punchFeedbackTimer: number
  789. contentCardTimer: number
  790. mapPulseTimer: number
  791. stageFxTimer: number
  792. sessionTimerInterval: number
  793. hasGpsCenteredOnce: boolean
  794. gpsLockEnabled: boolean
  795. constructor(buildVersion: string, callbacks: MapEngineCallbacks) {
  796. this.buildVersion = buildVersion
  797. this.animationLevel = resolveAnimationLevel(wx.getSystemInfoSync())
  798. this.compassTuningProfile = 'balanced'
  799. this.onData = callbacks.onData
  800. this.accelerometerErrorText = null
  801. this.renderer = new WebGLMapRenderer(
  802. (stats) => {
  803. this.applyStats(stats)
  804. },
  805. (message) => {
  806. this.setState({
  807. statusText: `${message} (${this.buildVersion})`,
  808. })
  809. },
  810. )
  811. this.accelerometerController = new AccelerometerController({
  812. onSample: (x, y, z) => {
  813. this.accelerometerErrorText = null
  814. this.telemetryRuntime.dispatch({
  815. type: 'accelerometer_updated',
  816. at: Date.now(),
  817. x,
  818. y,
  819. z,
  820. })
  821. if (this.diagnosticUiEnabled) {
  822. this.setState(this.getTelemetrySensorViewPatch())
  823. }
  824. },
  825. onError: (message) => {
  826. this.accelerometerErrorText = `不可用: ${message}`
  827. if (this.diagnosticUiEnabled) {
  828. this.setState({
  829. ...this.getTelemetrySensorViewPatch(),
  830. statusText: `加速度计启动失败 (${this.buildVersion})`,
  831. })
  832. }
  833. },
  834. })
  835. this.compassController = new CompassHeadingController({
  836. onHeading: (headingDeg) => {
  837. this.handleCompassHeading(headingDeg)
  838. },
  839. onError: (message) => {
  840. this.handleCompassError(message)
  841. },
  842. })
  843. this.compassController.setTuningProfile(this.compassTuningProfile)
  844. this.gyroscopeController = new GyroscopeController({
  845. onSample: (x, y, z) => {
  846. this.telemetryRuntime.dispatch({
  847. type: 'gyroscope_updated',
  848. at: Date.now(),
  849. x,
  850. y,
  851. z,
  852. })
  853. if (this.diagnosticUiEnabled) {
  854. this.setState(this.getTelemetrySensorViewPatch())
  855. }
  856. },
  857. onError: () => {
  858. if (this.diagnosticUiEnabled) {
  859. this.setState(this.getTelemetrySensorViewPatch())
  860. }
  861. },
  862. })
  863. this.deviceMotionController = new DeviceMotionController({
  864. onSample: (alpha, beta, gamma) => {
  865. this.telemetryRuntime.dispatch({
  866. type: 'device_motion_updated',
  867. at: Date.now(),
  868. alpha,
  869. beta,
  870. gamma,
  871. })
  872. if (this.diagnosticUiEnabled) {
  873. this.setState({
  874. ...this.getTelemetrySensorViewPatch(),
  875. autoRotateSourceText: this.getAutoRotateSourceText(),
  876. })
  877. }
  878. },
  879. onError: () => {
  880. if (this.diagnosticUiEnabled) {
  881. this.setState(this.getTelemetrySensorViewPatch())
  882. }
  883. },
  884. })
  885. this.locationController = new LocationController({
  886. onLocation: (update) => {
  887. this.handleLocationUpdate(update.longitude, update.latitude, typeof update.accuracy === 'number' ? update.accuracy : null)
  888. },
  889. onStatus: (message) => {
  890. this.setState({
  891. gpsTracking: this.locationController.listening,
  892. gpsTrackingText: message,
  893. ...this.getLocationControllerViewPatch(),
  894. })
  895. },
  896. onError: (message) => {
  897. this.setState({
  898. gpsTracking: this.locationController.listening,
  899. gpsTrackingText: message,
  900. ...this.getLocationControllerViewPatch(),
  901. statusText: `${message} (${this.buildVersion})`,
  902. })
  903. },
  904. onDebugStateChange: () => {
  905. if (this.diagnosticUiEnabled) {
  906. this.setState(this.getLocationControllerViewPatch())
  907. }
  908. },
  909. })
  910. this.heartRateController = new HeartRateInputController({
  911. onHeartRate: (bpm) => {
  912. this.telemetryRuntime.dispatch({
  913. type: 'heart_rate_updated',
  914. at: Date.now(),
  915. bpm,
  916. })
  917. this.syncSessionTimerText()
  918. },
  919. onStatus: (message) => {
  920. const deviceName = this.heartRateController.currentDeviceName
  921. || (this.heartRateController.reconnecting ? this.heartRateController.lastDeviceName : null)
  922. || '--'
  923. this.setState({
  924. heartRateStatusText: message,
  925. heartRateDeviceText: deviceName,
  926. heartRateScanText: this.getHeartRateScanText(),
  927. ...this.getHeartRateControllerViewPatch(),
  928. })
  929. },
  930. onError: (message) => {
  931. this.clearHeartRateSignal()
  932. const deviceName = this.heartRateController.reconnecting
  933. ? (this.heartRateController.lastDeviceName || '--')
  934. : '--'
  935. this.setState({
  936. heartRateConnected: false,
  937. heartRateStatusText: message,
  938. heartRateDeviceText: deviceName,
  939. heartRateScanText: this.getHeartRateScanText(),
  940. ...this.getHeartRateControllerViewPatch(),
  941. statusText: `${message} (${this.buildVersion})`,
  942. })
  943. },
  944. onConnectionChange: (connected, deviceName) => {
  945. if (!connected) {
  946. this.clearHeartRateSignal()
  947. }
  948. const resolvedDeviceName = connected
  949. ? (deviceName || '--')
  950. : (this.heartRateController.reconnecting
  951. ? (this.heartRateController.lastDeviceName || '--')
  952. : '--')
  953. this.setState({
  954. heartRateConnected: connected,
  955. heartRateDeviceText: resolvedDeviceName,
  956. heartRateStatusText: connected
  957. ? (this.heartRateController.sourceMode === 'mock' ? '模拟心率源已连接' : '心率带已连接')
  958. : (this.heartRateController.reconnecting ? '心率带自动重连中' : (this.heartRateController.sourceMode === 'mock' ? '模拟心率源未连接' : '心率带未连接')),
  959. heartRateScanText: this.getHeartRateScanText(),
  960. heartRateDiscoveredDevices: this.formatHeartRateDevices(this.heartRateController.discoveredDevices),
  961. ...this.getHeartRateControllerViewPatch(),
  962. })
  963. },
  964. onDeviceListChange: (devices) => {
  965. if (this.diagnosticUiEnabled) {
  966. this.setState({
  967. heartRateDiscoveredDevices: this.formatHeartRateDevices(devices),
  968. heartRateScanText: this.getHeartRateScanText(),
  969. ...this.getHeartRateControllerViewPatch(),
  970. })
  971. }
  972. },
  973. onDebugStateChange: () => {
  974. if (this.diagnosticUiEnabled) {
  975. this.setState(this.getHeartRateControllerViewPatch())
  976. }
  977. },
  978. })
  979. this.feedbackDirector = new FeedbackDirector({
  980. showPunchFeedback: (text, tone, motionClass) => {
  981. this.showPunchFeedback(text, tone, motionClass)
  982. },
  983. showContentCard: (title, body, motionClass) => {
  984. this.showContentCard(title, body, motionClass)
  985. },
  986. setPunchButtonFxClass: (className) => {
  987. this.setPunchButtonFxClass(className)
  988. },
  989. setHudProgressFxClass: (className) => {
  990. this.setHudProgressFxClass(className)
  991. },
  992. setHudDistanceFxClass: (className) => {
  993. this.setHudDistanceFxClass(className)
  994. },
  995. showMapPulse: (controlId, motionClass) => {
  996. this.showMapPulse(controlId, motionClass)
  997. },
  998. showStageFx: (className) => {
  999. this.showStageFx(className)
  1000. },
  1001. stopLocationTracking: () => {
  1002. if (this.locationController.listening) {
  1003. this.locationController.stop()
  1004. }
  1005. },
  1006. })
  1007. this.feedbackDirector.setAnimationLevel(this.animationLevel)
  1008. this.minZoom = MIN_ZOOM
  1009. this.maxZoom = MAX_ZOOM
  1010. this.defaultZoom = DEFAULT_ZOOM
  1011. this.defaultCenterTileX = DEFAULT_CENTER_TILE_X
  1012. this.defaultCenterTileY = DEFAULT_CENTER_TILE_Y
  1013. this.tileBoundsByZoom = null
  1014. this.currentGpsPoint = null
  1015. this.currentGpsTrack = []
  1016. this.currentGpsAccuracyMeters = null
  1017. this.currentGpsInsideMap = false
  1018. this.courseData = null
  1019. this.courseOverlayVisible = false
  1020. this.cpRadiusMeters = 5
  1021. this.configAppId = ''
  1022. this.configSchemaVersion = '1'
  1023. this.configVersion = ''
  1024. this.controlScoreOverrides = {}
  1025. this.defaultControlScore = null
  1026. this.gameRuntime = new GameRuntime()
  1027. this.telemetryRuntime = new TelemetryRuntime()
  1028. this.telemetryRuntime.configure()
  1029. this.gamePresentation = EMPTY_GAME_PRESENTATION_STATE
  1030. this.gameMode = 'classic-sequential'
  1031. this.punchPolicy = 'enter-confirm'
  1032. this.punchRadiusMeters = 5
  1033. this.requiresFocusSelection = false
  1034. this.skipEnabled = false
  1035. this.skipRadiusMeters = 30
  1036. this.skipRequiresConfirm = true
  1037. this.autoFinishOnLastControl = true
  1038. this.gpsLockEnabled = false
  1039. this.punchFeedbackTimer = 0
  1040. this.contentCardTimer = 0
  1041. this.mapPulseTimer = 0
  1042. this.stageFxTimer = 0
  1043. this.sessionTimerInterval = 0
  1044. this.hasGpsCenteredOnce = false
  1045. this.state = {
  1046. animationLevel: this.animationLevel,
  1047. buildVersion: this.buildVersion,
  1048. renderMode: RENDER_MODE,
  1049. projectionMode: PROJECTION_MODE,
  1050. mapReady: false,
  1051. mapReadyText: 'BOOTING',
  1052. mapName: '未命名配置',
  1053. configStatusText: '远程配置待加载',
  1054. zoom: DEFAULT_ZOOM,
  1055. rotationDeg: 0,
  1056. rotationText: formatRotationText(0),
  1057. rotationMode: 'manual',
  1058. rotationModeText: formatRotationModeText('manual'),
  1059. rotationToggleText: formatRotationToggleText('manual'),
  1060. orientationMode: 'manual',
  1061. orientationModeText: formatOrientationModeText('manual'),
  1062. sensorHeadingText: '--',
  1063. deviceHeadingText: '--',
  1064. devicePoseText: '竖持',
  1065. headingConfidenceText: '低',
  1066. accelerometerText: '未启用',
  1067. gyroscopeText: '--',
  1068. deviceMotionText: '--',
  1069. compassSourceText: '无数据',
  1070. compassTuningProfile: this.compassTuningProfile,
  1071. compassTuningProfileText: formatCompassTuningProfileText(this.compassTuningProfile),
  1072. compassDeclinationText: formatCompassDeclinationText(DEFAULT_NORTH_REFERENCE_MODE),
  1073. northReferenceMode: DEFAULT_NORTH_REFERENCE_MODE,
  1074. northReferenceButtonText: formatNorthReferenceButtonText(DEFAULT_NORTH_REFERENCE_MODE),
  1075. autoRotateSourceText: formatAutoRotateSourceText('smart', false),
  1076. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, getMapNorthOffsetDeg(DEFAULT_NORTH_REFERENCE_MODE)),
  1077. northReferenceText: formatNorthReferenceText(DEFAULT_NORTH_REFERENCE_MODE),
  1078. compassNeedleDeg: 0,
  1079. centerTileX: DEFAULT_CENTER_TILE_X,
  1080. centerTileY: DEFAULT_CENTER_TILE_Y,
  1081. centerText: buildCenterText(DEFAULT_ZOOM, DEFAULT_CENTER_TILE_X, DEFAULT_CENTER_TILE_Y),
  1082. tileSource: TILE_SOURCE,
  1083. visibleColumnCount: DESIRED_VISIBLE_COLUMNS,
  1084. visibleTileCount: 0,
  1085. readyTileCount: 0,
  1086. memoryTileCount: 0,
  1087. diskTileCount: 0,
  1088. memoryHitCount: 0,
  1089. diskHitCount: 0,
  1090. networkFetchCount: 0,
  1091. cacheHitRateText: '--',
  1092. tileTranslateX: 0,
  1093. tileTranslateY: 0,
  1094. tileSizePx: 0,
  1095. previewScale: 1,
  1096. stageWidth: 0,
  1097. stageHeight: 0,
  1098. stageLeft: 0,
  1099. stageTop: 0,
  1100. statusText: `单 WebGL 管线已就绪,等待传感器接入 (${this.buildVersion})`,
  1101. gpsTracking: false,
  1102. gpsTrackingText: '持续定位待启动',
  1103. gpsLockEnabled: false,
  1104. gpsLockAvailable: false,
  1105. locationSourceMode: 'real',
  1106. locationSourceText: '真实定位',
  1107. mockBridgeConnected: false,
  1108. mockBridgeStatusText: '未连接',
  1109. mockBridgeUrlText: 'wss://gs.gotomars.xyz/mock-gps',
  1110. mockCoordText: '--',
  1111. mockSpeedText: '--',
  1112. gpsCoordText: '--',
  1113. heartRateSourceMode: 'real',
  1114. heartRateSourceText: '真实心率',
  1115. heartRateConnected: false,
  1116. heartRateStatusText: '心率带未连接',
  1117. heartRateDeviceText: '--',
  1118. heartRateScanText: '未扫描',
  1119. heartRateDiscoveredDevices: [],
  1120. mockHeartRateBridgeConnected: false,
  1121. mockHeartRateBridgeStatusText: '未连接',
  1122. mockHeartRateBridgeUrlText: 'wss://gs.gotomars.xyz/mock-gps',
  1123. mockHeartRateText: '--',
  1124. panelTimerText: '00:00:00',
  1125. panelMileageText: '0m',
  1126. panelActionTagText: '目标',
  1127. panelDistanceTagText: '点距',
  1128. panelDistanceValueText: '--',
  1129. panelDistanceUnitText: '',
  1130. panelProgressText: '0/0',
  1131. panelSpeedValueText: '0',
  1132. panelTelemetryTone: 'blue',
  1133. panelHeartRateZoneNameText: '激活放松',
  1134. panelHeartRateZoneRangeText: '<=39%',
  1135. panelHeartRateValueText: '--',
  1136. panelHeartRateUnitText: '',
  1137. panelCaloriesValueText: '0',
  1138. panelCaloriesUnitText: 'kcal',
  1139. panelAverageSpeedValueText: '0',
  1140. panelAverageSpeedUnitText: 'km/h',
  1141. panelAccuracyValueText: '--',
  1142. panelAccuracyUnitText: '',
  1143. punchButtonText: '打点',
  1144. gameSessionStatus: 'idle',
  1145. gameModeText: '顺序赛',
  1146. punchButtonEnabled: false,
  1147. skipButtonEnabled: false,
  1148. punchHintText: '等待进入检查点范围',
  1149. punchFeedbackVisible: false,
  1150. punchFeedbackText: '',
  1151. punchFeedbackTone: 'neutral',
  1152. contentCardVisible: false,
  1153. contentCardTitle: '',
  1154. contentCardBody: '',
  1155. punchButtonFxClass: '',
  1156. panelProgressFxClass: '',
  1157. panelDistanceFxClass: '',
  1158. punchFeedbackFxClass: '',
  1159. contentCardFxClass: '',
  1160. mapPulseVisible: false,
  1161. mapPulseLeftPx: 0,
  1162. mapPulseTopPx: 0,
  1163. mapPulseFxClass: '',
  1164. stageFxVisible: false,
  1165. stageFxClass: '',
  1166. osmReferenceEnabled: false,
  1167. osmReferenceText: 'OSM参考:关',
  1168. }
  1169. this.previewScale = 1
  1170. this.previewOriginX = 0
  1171. this.previewOriginY = 0
  1172. this.panLastX = 0
  1173. this.panLastY = 0
  1174. this.panLastTimestamp = 0
  1175. this.tapStartX = 0
  1176. this.tapStartY = 0
  1177. this.tapStartAt = 0
  1178. this.panVelocityX = 0
  1179. this.panVelocityY = 0
  1180. this.pinchStartDistance = 0
  1181. this.pinchStartScale = 1
  1182. this.pinchStartAngle = 0
  1183. this.pinchStartRotationDeg = 0
  1184. this.pinchAnchorWorldX = 0
  1185. this.pinchAnchorWorldY = 0
  1186. this.gestureMode = 'idle'
  1187. this.inertiaTimer = 0
  1188. this.previewResetTimer = 0
  1189. this.viewSyncTimer = 0
  1190. this.autoRotateTimer = 0
  1191. this.compassNeedleTimer = 0
  1192. this.compassBootstrapRetryTimer = 0
  1193. this.pendingViewPatch = {}
  1194. this.mounted = false
  1195. this.diagnosticUiEnabled = false
  1196. this.northReferenceMode = DEFAULT_NORTH_REFERENCE_MODE
  1197. this.sensorHeadingDeg = null
  1198. this.smoothedSensorHeadingDeg = null
  1199. this.compassDisplayHeadingDeg = null
  1200. this.targetCompassDisplayHeadingDeg = null
  1201. this.lastCompassSampleAt = 0
  1202. this.compassSource = null
  1203. this.compassTuningProfile = 'balanced'
  1204. this.smoothedMovementHeadingDeg = null
  1205. this.autoRotateHeadingDeg = null
  1206. this.courseHeadingDeg = null
  1207. this.targetAutoRotationDeg = null
  1208. this.autoRotateSourceMode = 'smart'
  1209. this.autoRotateCalibrationOffsetDeg = getMapNorthOffsetDeg(DEFAULT_NORTH_REFERENCE_MODE)
  1210. this.autoRotateCalibrationPending = false
  1211. this.lastStatsUiSyncAt = 0
  1212. }
  1213. getInitialData(): MapEngineViewState {
  1214. return { ...this.state }
  1215. }
  1216. setDiagnosticUiEnabled(enabled: boolean): void {
  1217. if (this.diagnosticUiEnabled === enabled) {
  1218. return
  1219. }
  1220. this.diagnosticUiEnabled = enabled
  1221. if (!enabled) {
  1222. return
  1223. }
  1224. this.setState({
  1225. ...this.getTelemetrySensorViewPatch(),
  1226. ...this.getLocationControllerViewPatch(),
  1227. ...this.getHeartRateControllerViewPatch(),
  1228. heartRateDiscoveredDevices: this.formatHeartRateDevices(this.heartRateController.discoveredDevices),
  1229. autoRotateSourceText: this.getAutoRotateSourceText(),
  1230. visibleTileCount: this.state.visibleTileCount,
  1231. readyTileCount: this.state.readyTileCount,
  1232. memoryTileCount: this.state.memoryTileCount,
  1233. diskTileCount: this.state.diskTileCount,
  1234. memoryHitCount: this.state.memoryHitCount,
  1235. diskHitCount: this.state.diskHitCount,
  1236. networkFetchCount: this.state.networkFetchCount,
  1237. cacheHitRateText: this.state.cacheHitRateText,
  1238. }, true)
  1239. }
  1240. getGameInfoSnapshot(): MapEngineGameInfoSnapshot {
  1241. const definition = this.gameRuntime.definition
  1242. const sessionState = this.gameRuntime.state
  1243. const telemetryState = this.telemetryRuntime.state
  1244. const telemetryPresentation = this.telemetryRuntime.getPresentation()
  1245. const currentTarget = definition && sessionState
  1246. ? definition.controls.find((control) => control.id === sessionState.currentTargetControlId) || null
  1247. : null
  1248. const currentTargetText = currentTarget
  1249. ? `${currentTarget.label} / ${currentTarget.kind === 'start'
  1250. ? '开始点'
  1251. : currentTarget.kind === 'finish'
  1252. ? '结束点'
  1253. : '检查点'}`
  1254. : '--'
  1255. const title = this.state.mapName || (definition ? definition.title : '当前游戏')
  1256. const subtitle = `${this.getGameModeText()} / ${formatGameSessionStatusText(this.state.gameSessionStatus)}`
  1257. const localRows: MapEngineGameInfoRow[] = [
  1258. { label: '比赛名称', value: title || '--' },
  1259. { label: '配置版本', value: this.configVersion || '--' },
  1260. { label: 'Schema版本', value: this.configSchemaVersion || '--' },
  1261. { label: '活动ID', value: this.configAppId || '--' },
  1262. { label: '动画等级', value: formatAnimationLevelText(this.state.animationLevel) },
  1263. { label: '地图', value: this.state.mapName || '--' },
  1264. { label: '模式', value: this.getGameModeText() },
  1265. { label: '状态', value: formatGameSessionStatusText(this.state.gameSessionStatus) },
  1266. { label: '当前目标', value: currentTargetText },
  1267. { label: '进度', value: this.gamePresentation.hud.progressText || '--' },
  1268. { label: '当前积分', value: sessionState ? String(sessionState.score) : '0' },
  1269. { label: '已完成点', value: sessionState ? String(sessionState.completedControlIds.length) : '0' },
  1270. { label: '已跳过点', value: sessionState ? String(sessionState.skippedControlIds.length) : '0' },
  1271. { label: '打点规则', value: `${this.punchPolicy} / ${this.punchRadiusMeters}m` },
  1272. { label: '跳点规则', value: this.skipEnabled ? `${this.skipRadiusMeters}m / ${this.skipRequiresConfirm ? '确认跳过' : '直接跳过'}` : '关闭' },
  1273. { label: '定位源', value: this.state.locationSourceText || '--' },
  1274. { label: '当前位置', value: this.state.gpsCoordText || '--' },
  1275. { label: 'GPS精度', value: telemetryState.lastGpsAccuracyMeters == null ? '--' : `${telemetryState.lastGpsAccuracyMeters.toFixed(1)}m` },
  1276. { label: '设备朝向', value: this.state.deviceHeadingText || '--' },
  1277. { label: '设备姿态', value: this.state.devicePoseText || '--' },
  1278. { label: '朝向可信度', value: this.state.headingConfidenceText || '--' },
  1279. { label: '目标距离', value: `${telemetryPresentation.distanceToTargetValueText}${telemetryPresentation.distanceToTargetUnitText}` || '--' },
  1280. { label: '当前速度', value: `${telemetryPresentation.speedText} km/h` },
  1281. { label: '心率源', value: this.state.heartRateSourceText || '--' },
  1282. { label: '当前心率', value: this.state.panelHeartRateValueText === '--' ? '--' : `${this.state.panelHeartRateValueText}${this.state.panelHeartRateUnitText}` },
  1283. { label: '心率设备', value: this.state.heartRateDeviceText || '--' },
  1284. { label: '心率分区', value: this.state.panelHeartRateZoneNameText === '--' ? '--' : `${this.state.panelHeartRateZoneNameText} ${this.state.panelHeartRateZoneRangeText}` },
  1285. { label: '本局用时', value: telemetryPresentation.timerText },
  1286. { label: '累计里程', value: telemetryPresentation.mileageText },
  1287. { label: '累计消耗', value: `${telemetryPresentation.caloriesValueText}${telemetryPresentation.caloriesUnitText}` },
  1288. { label: '提示状态', value: this.state.punchHintText || '--' },
  1289. ]
  1290. const globalRows: MapEngineGameInfoRow[] = [
  1291. { label: '全球积分', value: '未接入' },
  1292. { label: '全球排名', value: '未接入' },
  1293. { label: '在线人数', value: '未接入' },
  1294. { label: '队伍状态', value: '未接入' },
  1295. { label: '实时广播', value: '未接入' },
  1296. ]
  1297. return {
  1298. title,
  1299. subtitle,
  1300. localRows,
  1301. globalRows,
  1302. }
  1303. }
  1304. destroy(): void {
  1305. this.clearInertiaTimer()
  1306. this.clearPreviewResetTimer()
  1307. this.clearViewSyncTimer()
  1308. this.clearAutoRotateTimer()
  1309. this.clearCompassNeedleTimer()
  1310. this.clearCompassBootstrapRetryTimer()
  1311. this.clearPunchFeedbackTimer()
  1312. this.clearContentCardTimer()
  1313. this.clearMapPulseTimer()
  1314. this.clearStageFxTimer()
  1315. this.clearSessionTimerInterval()
  1316. this.accelerometerController.destroy()
  1317. this.compassController.destroy()
  1318. this.gyroscopeController.destroy()
  1319. this.deviceMotionController.destroy()
  1320. this.locationController.destroy()
  1321. this.heartRateController.destroy()
  1322. this.feedbackDirector.destroy()
  1323. this.renderer.destroy()
  1324. this.mounted = false
  1325. }
  1326. handleAppShow(): void {
  1327. this.feedbackDirector.setAppAudioMode('foreground')
  1328. if (this.mounted) {
  1329. this.lastCompassSampleAt = 0
  1330. this.compassController.start()
  1331. this.scheduleCompassBootstrapRetry()
  1332. }
  1333. }
  1334. handleAppHide(): void {
  1335. this.feedbackDirector.setAppAudioMode('foreground')
  1336. }
  1337. clearGameRuntime(): void {
  1338. this.gameRuntime.clear()
  1339. this.telemetryRuntime.reset()
  1340. this.gamePresentation = EMPTY_GAME_PRESENTATION_STATE
  1341. this.courseOverlayVisible = !!this.courseData
  1342. this.clearSessionTimerInterval()
  1343. this.setCourseHeading(null)
  1344. }
  1345. clearHeartRateSignal(): void {
  1346. this.telemetryRuntime.dispatch({
  1347. type: 'heart_rate_updated',
  1348. at: Date.now(),
  1349. bpm: null,
  1350. })
  1351. this.syncSessionTimerText()
  1352. }
  1353. clearFinishedTestOverlay(): void {
  1354. this.currentGpsPoint = null
  1355. this.currentGpsTrack = []
  1356. this.currentGpsAccuracyMeters = null
  1357. this.currentGpsInsideMap = false
  1358. this.smoothedMovementHeadingDeg = null
  1359. this.courseOverlayVisible = false
  1360. this.setCourseHeading(null)
  1361. }
  1362. clearStartSessionResidue(): void {
  1363. this.currentGpsTrack = []
  1364. this.smoothedMovementHeadingDeg = null
  1365. this.courseOverlayVisible = false
  1366. this.setCourseHeading(null)
  1367. }
  1368. handleClearMapTestArtifacts(): void {
  1369. this.clearFinishedTestOverlay()
  1370. this.setState({
  1371. gpsTracking: false,
  1372. gpsTrackingText: '测试痕迹已清空',
  1373. gpsCoordText: '--',
  1374. statusText: `已清空地图点位与轨迹 (${this.buildVersion})`,
  1375. }, true)
  1376. this.syncRenderer()
  1377. }
  1378. getHudTargetControlId(): string | null {
  1379. return this.gamePresentation.hud.hudTargetControlId
  1380. }
  1381. isSkipAvailable(): boolean {
  1382. const definition = this.gameRuntime.definition
  1383. const state = this.gameRuntime.state
  1384. if (!definition || !state || state.status !== 'running' || !definition.skipEnabled) {
  1385. return false
  1386. }
  1387. const currentTarget = definition.controls.find((control) => control.id === state.currentTargetControlId) || null
  1388. if (!currentTarget || currentTarget.kind !== 'control' || !this.currentGpsPoint) {
  1389. return false
  1390. }
  1391. const avgLatRad = ((currentTarget.point.lat + this.currentGpsPoint.lat) / 2) * Math.PI / 180
  1392. const dx = (this.currentGpsPoint.lon - currentTarget.point.lon) * 111320 * Math.cos(avgLatRad)
  1393. const dy = (this.currentGpsPoint.lat - currentTarget.point.lat) * 110540
  1394. const distanceMeters = Math.sqrt(dx * dx + dy * dy)
  1395. return distanceMeters <= definition.skipRadiusMeters
  1396. }
  1397. shouldConfirmSkipAction(): boolean {
  1398. return !!(this.gameRuntime.definition && this.gameRuntime.definition.skipRequiresConfirm)
  1399. }
  1400. getLocationControllerViewPatch(): Partial<MapEngineViewState> {
  1401. const debugState = this.locationController.getDebugState()
  1402. return {
  1403. gpsTracking: debugState.listening,
  1404. gpsLockEnabled: this.gpsLockEnabled,
  1405. gpsLockAvailable: !!this.currentGpsPoint && this.currentGpsInsideMap,
  1406. locationSourceMode: debugState.sourceMode,
  1407. locationSourceText: debugState.sourceModeText,
  1408. mockBridgeConnected: debugState.mockBridgeConnected,
  1409. mockBridgeStatusText: debugState.mockBridgeStatusText,
  1410. mockBridgeUrlText: debugState.mockBridgeUrlText,
  1411. mockCoordText: debugState.mockCoordText,
  1412. mockSpeedText: debugState.mockSpeedText,
  1413. }
  1414. }
  1415. getHeartRateControllerViewPatch(): Partial<MapEngineViewState> {
  1416. const debugState = this.heartRateController.getDebugState()
  1417. return {
  1418. heartRateSourceMode: debugState.sourceMode,
  1419. heartRateSourceText: debugState.sourceModeText,
  1420. mockHeartRateBridgeConnected: debugState.mockBridgeConnected,
  1421. mockHeartRateBridgeStatusText: debugState.mockBridgeStatusText,
  1422. mockHeartRateBridgeUrlText: debugState.mockBridgeUrlText,
  1423. mockHeartRateText: debugState.mockHeartRateText,
  1424. }
  1425. }
  1426. getTelemetrySensorViewPatch(): Partial<MapEngineViewState> {
  1427. const telemetryState = this.telemetryRuntime.state
  1428. return {
  1429. deviceHeadingText: formatHeadingText(
  1430. telemetryState.deviceHeadingDeg === null
  1431. ? null
  1432. : getCompassReferenceHeadingDeg(this.northReferenceMode, telemetryState.deviceHeadingDeg),
  1433. ),
  1434. devicePoseText: formatDevicePoseText(telemetryState.devicePose),
  1435. headingConfidenceText: formatHeadingConfidenceText(telemetryState.headingConfidence),
  1436. accelerometerText: telemetryState.accelerometer
  1437. ? `#${telemetryState.accelerometerSampleCount} ${formatClockTime(telemetryState.accelerometerUpdatedAt)} x:${telemetryState.accelerometer.x.toFixed(3)} y:${telemetryState.accelerometer.y.toFixed(3)} z:${telemetryState.accelerometer.z.toFixed(3)}`
  1438. : '未启用',
  1439. gyroscopeText: formatGyroscopeText(telemetryState.gyroscope),
  1440. deviceMotionText: formatDeviceMotionText(telemetryState.deviceMotion),
  1441. compassSourceText: formatCompassSourceText(this.compassSource),
  1442. compassTuningProfile: this.compassTuningProfile,
  1443. compassTuningProfileText: formatCompassTuningProfileText(this.compassTuningProfile),
  1444. }
  1445. }
  1446. getGameModeText(): string {
  1447. return this.gameMode === 'score-o' ? '积分赛' : '顺序赛'
  1448. }
  1449. loadGameDefinitionFromCourse(): GameResult | null {
  1450. if (!this.courseData) {
  1451. this.clearGameRuntime()
  1452. return null
  1453. }
  1454. const definition = buildGameDefinitionFromCourse(
  1455. this.courseData,
  1456. this.cpRadiusMeters,
  1457. this.gameMode,
  1458. this.autoFinishOnLastControl,
  1459. this.punchPolicy,
  1460. this.punchRadiusMeters,
  1461. this.requiresFocusSelection,
  1462. this.skipEnabled,
  1463. this.skipRadiusMeters,
  1464. this.skipRequiresConfirm,
  1465. this.controlScoreOverrides,
  1466. this.defaultControlScore,
  1467. )
  1468. const result = this.gameRuntime.loadDefinition(definition)
  1469. this.telemetryRuntime.loadDefinition(definition)
  1470. this.courseOverlayVisible = true
  1471. this.syncGameResultState(result)
  1472. this.telemetryRuntime.syncGameState(this.gameRuntime.definition, result.nextState, result.presentation.hud.hudTargetControlId)
  1473. this.updateSessionTimerLoop()
  1474. return result
  1475. }
  1476. refreshCourseHeadingFromPresentation(): void {
  1477. if (!this.courseData || !this.gamePresentation.map.activeLegIndices.length) {
  1478. this.setCourseHeading(null)
  1479. return
  1480. }
  1481. const activeLegIndex = this.gamePresentation.map.activeLegIndices[0]
  1482. const activeLeg = this.courseData.layers.legs[activeLegIndex]
  1483. if (!activeLeg) {
  1484. this.setCourseHeading(null)
  1485. return
  1486. }
  1487. this.setCourseHeading(getInitialBearingDeg(activeLeg.fromPoint, activeLeg.toPoint))
  1488. }
  1489. resolveGameStatusText(effects: GameEffect[]): string | null {
  1490. const lastEffect = effects.length ? effects[effects.length - 1] : null
  1491. if (!lastEffect) {
  1492. return null
  1493. }
  1494. if (lastEffect.type === 'control_completed') {
  1495. const sequenceText = typeof lastEffect.sequence === 'number' ? String(lastEffect.sequence) : lastEffect.controlId
  1496. return `宸插畬鎴愭鏌ョ偣 ${sequenceText} (${this.buildVersion})`
  1497. }
  1498. if (lastEffect.type === 'session_finished') {
  1499. return `璺嚎宸插畬鎴?(${this.buildVersion})`
  1500. }
  1501. if (lastEffect.type === 'session_started') {
  1502. return `椤哄簭鎵撶偣宸插紑濮?(${this.buildVersion})`
  1503. }
  1504. return null
  1505. }
  1506. getGameViewPatch(statusText?: string | null): Partial<MapEngineViewState> {
  1507. const telemetryPresentation = this.telemetryRuntime.getPresentation()
  1508. const patch: Partial<MapEngineViewState> = {
  1509. gameSessionStatus: this.gameRuntime.state ? this.gameRuntime.state.status : 'idle',
  1510. gameModeText: this.getGameModeText(),
  1511. panelTimerText: telemetryPresentation.timerText,
  1512. panelMileageText: telemetryPresentation.mileageText,
  1513. panelActionTagText: this.gamePresentation.hud.actionTagText,
  1514. panelDistanceTagText: this.gamePresentation.hud.distanceTagText,
  1515. panelDistanceValueText: telemetryPresentation.distanceToTargetValueText,
  1516. panelDistanceUnitText: telemetryPresentation.distanceToTargetUnitText,
  1517. panelSpeedValueText: telemetryPresentation.speedText,
  1518. panelTelemetryTone: telemetryPresentation.heartRateTone,
  1519. panelHeartRateZoneNameText: telemetryPresentation.heartRateZoneNameText,
  1520. panelHeartRateZoneRangeText: telemetryPresentation.heartRateZoneRangeText,
  1521. panelHeartRateValueText: telemetryPresentation.heartRateValueText,
  1522. panelHeartRateUnitText: telemetryPresentation.heartRateUnitText,
  1523. panelCaloriesValueText: telemetryPresentation.caloriesValueText,
  1524. panelCaloriesUnitText: telemetryPresentation.caloriesUnitText,
  1525. panelAverageSpeedValueText: telemetryPresentation.averageSpeedValueText,
  1526. panelAverageSpeedUnitText: telemetryPresentation.averageSpeedUnitText,
  1527. panelAccuracyValueText: telemetryPresentation.accuracyValueText,
  1528. panelAccuracyUnitText: telemetryPresentation.accuracyUnitText,
  1529. panelProgressText: this.gamePresentation.hud.progressText,
  1530. punchButtonText: this.gamePresentation.hud.punchButtonText,
  1531. punchButtonEnabled: this.gamePresentation.hud.punchButtonEnabled,
  1532. skipButtonEnabled: this.isSkipAvailable(),
  1533. punchHintText: this.gamePresentation.hud.punchHintText,
  1534. gpsLockEnabled: this.gpsLockEnabled,
  1535. gpsLockAvailable: !!this.currentGpsPoint && this.currentGpsInsideMap,
  1536. }
  1537. if (statusText) {
  1538. patch.statusText = statusText
  1539. }
  1540. return patch
  1541. }
  1542. clearPunchFeedbackTimer(): void {
  1543. if (this.punchFeedbackTimer) {
  1544. clearTimeout(this.punchFeedbackTimer)
  1545. this.punchFeedbackTimer = 0
  1546. }
  1547. }
  1548. clearContentCardTimer(): void {
  1549. if (this.contentCardTimer) {
  1550. clearTimeout(this.contentCardTimer)
  1551. this.contentCardTimer = 0
  1552. }
  1553. }
  1554. clearMapPulseTimer(): void {
  1555. if (this.mapPulseTimer) {
  1556. clearTimeout(this.mapPulseTimer)
  1557. this.mapPulseTimer = 0
  1558. }
  1559. }
  1560. clearStageFxTimer(): void {
  1561. if (this.stageFxTimer) {
  1562. clearTimeout(this.stageFxTimer)
  1563. this.stageFxTimer = 0
  1564. }
  1565. }
  1566. resetTransientGameUiState(): void {
  1567. this.clearPunchFeedbackTimer()
  1568. this.clearContentCardTimer()
  1569. this.clearMapPulseTimer()
  1570. this.clearStageFxTimer()
  1571. this.setState({
  1572. punchFeedbackVisible: false,
  1573. punchFeedbackText: '',
  1574. punchFeedbackTone: 'neutral',
  1575. punchFeedbackFxClass: '',
  1576. contentCardVisible: false,
  1577. contentCardTitle: '',
  1578. contentCardBody: '',
  1579. contentCardFxClass: '',
  1580. mapPulseVisible: false,
  1581. mapPulseFxClass: '',
  1582. stageFxVisible: false,
  1583. stageFxClass: '',
  1584. punchButtonFxClass: '',
  1585. panelProgressFxClass: '',
  1586. panelDistanceFxClass: '',
  1587. }, true)
  1588. }
  1589. clearSessionTimerInterval(): void {
  1590. if (this.sessionTimerInterval) {
  1591. clearInterval(this.sessionTimerInterval)
  1592. this.sessionTimerInterval = 0
  1593. }
  1594. }
  1595. syncSessionTimerText(): void {
  1596. const telemetryPresentation = this.telemetryRuntime.getPresentation()
  1597. this.setState({
  1598. panelTimerText: telemetryPresentation.timerText,
  1599. panelMileageText: telemetryPresentation.mileageText,
  1600. panelActionTagText: this.gamePresentation.hud.actionTagText,
  1601. panelDistanceTagText: this.gamePresentation.hud.distanceTagText,
  1602. panelDistanceValueText: telemetryPresentation.distanceToTargetValueText,
  1603. panelDistanceUnitText: telemetryPresentation.distanceToTargetUnitText,
  1604. panelSpeedValueText: telemetryPresentation.speedText,
  1605. panelTelemetryTone: telemetryPresentation.heartRateTone,
  1606. panelHeartRateZoneNameText: telemetryPresentation.heartRateZoneNameText,
  1607. panelHeartRateZoneRangeText: telemetryPresentation.heartRateZoneRangeText,
  1608. panelHeartRateValueText: telemetryPresentation.heartRateValueText,
  1609. panelHeartRateUnitText: telemetryPresentation.heartRateUnitText,
  1610. panelCaloriesValueText: telemetryPresentation.caloriesValueText,
  1611. panelCaloriesUnitText: telemetryPresentation.caloriesUnitText,
  1612. panelAverageSpeedValueText: telemetryPresentation.averageSpeedValueText,
  1613. panelAverageSpeedUnitText: telemetryPresentation.averageSpeedUnitText,
  1614. panelAccuracyValueText: telemetryPresentation.accuracyValueText,
  1615. panelAccuracyUnitText: telemetryPresentation.accuracyUnitText,
  1616. })
  1617. }
  1618. updateSessionTimerLoop(): void {
  1619. const gameState = this.gameRuntime.state
  1620. const shouldRun = !!gameState && gameState.status === 'running' && gameState.endedAt === null
  1621. this.syncSessionTimerText()
  1622. if (!shouldRun) {
  1623. this.clearSessionTimerInterval()
  1624. return
  1625. }
  1626. if (this.sessionTimerInterval) {
  1627. return
  1628. }
  1629. this.sessionTimerInterval = setInterval(() => {
  1630. this.syncSessionTimerText()
  1631. }, 1000) as unknown as number
  1632. }
  1633. getControlScreenPoint(controlId: string): { x: number; y: number } | null {
  1634. if (!this.gameRuntime.definition || !this.state.stageWidth || !this.state.stageHeight) {
  1635. return null
  1636. }
  1637. const control = this.gameRuntime.definition.controls.find((item) => item.id === controlId)
  1638. if (!control) {
  1639. return null
  1640. }
  1641. const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
  1642. const screenPoint = worldToScreen({
  1643. centerWorldX: exactCenter.x,
  1644. centerWorldY: exactCenter.y,
  1645. viewportWidth: this.state.stageWidth,
  1646. viewportHeight: this.state.stageHeight,
  1647. visibleColumns: DESIRED_VISIBLE_COLUMNS,
  1648. rotationRad: this.getRotationRad(this.state.rotationDeg),
  1649. }, lonLatToWorldTile(control.point, this.state.zoom), false)
  1650. if (screenPoint.x < -80 || screenPoint.x > this.state.stageWidth + 80 || screenPoint.y < -80 || screenPoint.y > this.state.stageHeight + 80) {
  1651. return null
  1652. }
  1653. return screenPoint
  1654. }
  1655. setPunchButtonFxClass(className: string): void {
  1656. this.setState({
  1657. punchButtonFxClass: className,
  1658. }, true)
  1659. }
  1660. setHudProgressFxClass(className: string): void {
  1661. this.setState({
  1662. panelProgressFxClass: className,
  1663. }, true)
  1664. }
  1665. setHudDistanceFxClass(className: string): void {
  1666. this.setState({
  1667. panelDistanceFxClass: className,
  1668. }, true)
  1669. }
  1670. showMapPulse(controlId: string, motionClass = ''): void {
  1671. const screenPoint = this.getControlScreenPoint(controlId)
  1672. if (!screenPoint) {
  1673. return
  1674. }
  1675. this.clearMapPulseTimer()
  1676. this.setState({
  1677. mapPulseVisible: true,
  1678. mapPulseLeftPx: screenPoint.x,
  1679. mapPulseTopPx: screenPoint.y,
  1680. mapPulseFxClass: motionClass,
  1681. }, true)
  1682. this.mapPulseTimer = setTimeout(() => {
  1683. this.mapPulseTimer = 0
  1684. this.setState({
  1685. mapPulseVisible: false,
  1686. mapPulseFxClass: '',
  1687. }, true)
  1688. }, 820) as unknown as number
  1689. }
  1690. showStageFx(className: string): void {
  1691. if (!className) {
  1692. return
  1693. }
  1694. this.clearStageFxTimer()
  1695. this.setState({
  1696. stageFxVisible: true,
  1697. stageFxClass: className,
  1698. }, true)
  1699. this.stageFxTimer = setTimeout(() => {
  1700. this.stageFxTimer = 0
  1701. this.setState({
  1702. stageFxVisible: false,
  1703. stageFxClass: '',
  1704. }, true)
  1705. }, 760) as unknown as number
  1706. }
  1707. showPunchFeedback(text: string, tone: 'neutral' | 'success' | 'warning', motionClass = ''): void {
  1708. this.clearPunchFeedbackTimer()
  1709. this.setState({
  1710. punchFeedbackVisible: true,
  1711. punchFeedbackText: text,
  1712. punchFeedbackTone: tone,
  1713. punchFeedbackFxClass: motionClass,
  1714. }, true)
  1715. this.punchFeedbackTimer = setTimeout(() => {
  1716. this.punchFeedbackTimer = 0
  1717. this.setState({
  1718. punchFeedbackVisible: false,
  1719. punchFeedbackFxClass: '',
  1720. }, true)
  1721. }, 1400) as unknown as number
  1722. }
  1723. showContentCard(title: string, body: string, motionClass = ''): void {
  1724. this.clearContentCardTimer()
  1725. this.setState({
  1726. contentCardVisible: true,
  1727. contentCardTitle: title,
  1728. contentCardBody: body,
  1729. contentCardFxClass: motionClass,
  1730. }, true)
  1731. this.contentCardTimer = setTimeout(() => {
  1732. this.contentCardTimer = 0
  1733. this.setState({
  1734. contentCardVisible: false,
  1735. contentCardFxClass: '',
  1736. }, true)
  1737. }, 2600) as unknown as number
  1738. }
  1739. closeContentCard(): void {
  1740. this.clearContentCardTimer()
  1741. this.setState({
  1742. contentCardVisible: false,
  1743. contentCardFxClass: '',
  1744. }, true)
  1745. }
  1746. applyGameEffects(effects: GameEffect[]): string | null {
  1747. this.feedbackDirector.handleEffects(effects)
  1748. if (effects.some((effect) => effect.type === 'session_finished')) {
  1749. if (this.locationController.listening) {
  1750. this.locationController.stop()
  1751. }
  1752. this.setState({
  1753. gpsTracking: false,
  1754. gpsTrackingText: '测试结束,定位已停止',
  1755. }, true)
  1756. }
  1757. this.telemetryRuntime.syncGameState(this.gameRuntime.definition, this.gameRuntime.state, this.getHudTargetControlId())
  1758. this.updateSessionTimerLoop()
  1759. return this.resolveGameStatusText(effects)
  1760. }
  1761. syncGameResultState(result: GameResult): void {
  1762. this.gamePresentation = result.presentation
  1763. this.refreshCourseHeadingFromPresentation()
  1764. }
  1765. resolveAppliedGameStatusText(result: GameResult, fallbackStatusText?: string | null): string | null {
  1766. return this.applyGameEffects(result.effects) || fallbackStatusText || this.resolveGameStatusText(result.effects)
  1767. }
  1768. commitGameResult(
  1769. result: GameResult,
  1770. fallbackStatusText?: string | null,
  1771. extraPatch: Partial<MapEngineViewState> = {},
  1772. syncRenderer = true,
  1773. ): string | null {
  1774. this.syncGameResultState(result)
  1775. const gameStatusText = this.resolveAppliedGameStatusText(result, fallbackStatusText)
  1776. this.setState({
  1777. ...this.getGameViewPatch(gameStatusText),
  1778. ...extraPatch,
  1779. }, true)
  1780. if (syncRenderer) {
  1781. this.syncRenderer()
  1782. }
  1783. return gameStatusText
  1784. }
  1785. handleStartGame(): void {
  1786. if (!this.gameRuntime.definition || !this.gameRuntime.state) {
  1787. this.setState({
  1788. statusText: `当前还没有可开始的路线 (${this.buildVersion})`,
  1789. }, true)
  1790. return
  1791. }
  1792. if (this.gameRuntime.state.status !== 'idle') {
  1793. return
  1794. }
  1795. this.feedbackDirector.reset()
  1796. this.resetTransientGameUiState()
  1797. this.clearStartSessionResidue()
  1798. if (!this.locationController.listening) {
  1799. this.locationController.start()
  1800. }
  1801. const startedAt = Date.now()
  1802. const startResult = this.gameRuntime.startSession(startedAt)
  1803. let gameResult = startResult
  1804. if (this.currentGpsPoint) {
  1805. const gpsResult = this.gameRuntime.dispatch({
  1806. type: 'gps_updated',
  1807. at: Date.now(),
  1808. lon: this.currentGpsPoint.lon,
  1809. lat: this.currentGpsPoint.lat,
  1810. accuracyMeters: this.currentGpsAccuracyMeters,
  1811. })
  1812. gameResult = {
  1813. nextState: gpsResult.nextState,
  1814. presentation: gpsResult.presentation,
  1815. effects: [...startResult.effects, ...gpsResult.effects],
  1816. }
  1817. }
  1818. this.courseOverlayVisible = true
  1819. const defaultStatusText = this.currentGpsPoint
  1820. ? `顺序打点已开始 (${this.buildVersion})`
  1821. : `顺序打点已开始,GPS定位启动中 (${this.buildVersion})`
  1822. this.commitGameResult(gameResult, defaultStatusText)
  1823. }
  1824. handleForceExitGame(): void {
  1825. this.feedbackDirector.reset()
  1826. if (this.locationController.listening) {
  1827. this.locationController.stop()
  1828. }
  1829. if (!this.courseData) {
  1830. this.clearGameRuntime()
  1831. this.resetTransientGameUiState()
  1832. this.feedbackDirector.handleEffects([{ type: 'session_cancelled' }])
  1833. this.setState({
  1834. gpsTracking: false,
  1835. gpsTrackingText: '已退出对局,定位已停止',
  1836. ...this.getGameViewPatch(`已退出当前对局 (${this.buildVersion})`),
  1837. }, true)
  1838. this.syncRenderer()
  1839. return
  1840. }
  1841. this.loadGameDefinitionFromCourse()
  1842. this.resetTransientGameUiState()
  1843. this.feedbackDirector.handleEffects([{ type: 'session_cancelled' }])
  1844. this.setState({
  1845. gpsTracking: false,
  1846. gpsTrackingText: '已退出对局,定位已停止',
  1847. ...this.getGameViewPatch(`已退出当前对局 (${this.buildVersion})`),
  1848. }, true)
  1849. this.syncRenderer()
  1850. }
  1851. handlePunchAction(): void {
  1852. const gameResult = this.gameRuntime.dispatch({
  1853. type: 'punch_requested',
  1854. at: Date.now(),
  1855. })
  1856. this.commitGameResult(gameResult)
  1857. }
  1858. handleLocationUpdate(longitude: number, latitude: number, accuracyMeters: number | null): void {
  1859. const nextPoint: LonLatPoint = { lon: longitude, lat: latitude }
  1860. const lastTrackPoint = this.currentGpsTrack.length ? this.currentGpsTrack[this.currentGpsTrack.length - 1] : null
  1861. if (!lastTrackPoint || getApproxDistanceMeters(lastTrackPoint, nextPoint) >= GPS_TRACK_MIN_STEP_METERS) {
  1862. this.currentGpsTrack = [...this.currentGpsTrack, nextPoint].slice(-GPS_TRACK_MAX_POINTS)
  1863. }
  1864. this.currentGpsPoint = nextPoint
  1865. this.currentGpsAccuracyMeters = accuracyMeters
  1866. this.updateMovementHeadingDeg()
  1867. const gpsWorldPoint = lonLatToWorldTile(nextPoint, this.state.zoom)
  1868. const gpsTileX = Math.floor(gpsWorldPoint.x)
  1869. const gpsTileY = Math.floor(gpsWorldPoint.y)
  1870. const gpsInsideMap = isTileWithinBounds(this.tileBoundsByZoom, this.state.zoom, gpsTileX, gpsTileY)
  1871. this.currentGpsInsideMap = gpsInsideMap
  1872. let gameStatusText: string | null = null
  1873. if (!gpsInsideMap && this.gpsLockEnabled) {
  1874. this.gpsLockEnabled = false
  1875. gameStatusText = `GPS已超出地图范围,锁定已关闭 (${this.buildVersion})`
  1876. }
  1877. if (this.courseData) {
  1878. const eventAt = Date.now()
  1879. const gameResult = this.gameRuntime.dispatch({
  1880. type: 'gps_updated',
  1881. at: eventAt,
  1882. lon: longitude,
  1883. lat: latitude,
  1884. accuracyMeters,
  1885. })
  1886. this.telemetryRuntime.dispatch({
  1887. type: 'gps_updated',
  1888. at: eventAt,
  1889. lon: longitude,
  1890. lat: latitude,
  1891. accuracyMeters,
  1892. })
  1893. this.syncGameResultState(gameResult)
  1894. gameStatusText = this.resolveAppliedGameStatusText(gameResult)
  1895. }
  1896. if (this.state.orientationMode === 'heading-up' && this.refreshAutoRotateTarget()) {
  1897. this.scheduleAutoRotate()
  1898. }
  1899. if (gpsInsideMap && (this.gpsLockEnabled || !this.hasGpsCenteredOnce)) {
  1900. this.hasGpsCenteredOnce = true
  1901. const lockedViewport = this.resolveViewportForExactCenter(gpsWorldPoint.x, gpsWorldPoint.y)
  1902. this.commitViewport({
  1903. ...lockedViewport,
  1904. gpsTracking: true,
  1905. gpsTrackingText: '持续定位进行中',
  1906. gpsCoordText: formatGpsCoordText(nextPoint, accuracyMeters),
  1907. autoRotateSourceText: this.getAutoRotateSourceText(),
  1908. gpsLockEnabled: this.gpsLockEnabled,
  1909. gpsLockAvailable: true,
  1910. ...this.getGameViewPatch(),
  1911. }, gameStatusText || (this.gpsLockEnabled ? `GPS锁定跟随中 (${this.buildVersion})` : `GPS定位成功,已定位到当前位置 (${this.buildVersion})`), true)
  1912. return
  1913. }
  1914. this.setState({
  1915. gpsTracking: true,
  1916. gpsTrackingText: gpsInsideMap ? '持续定位进行中' : 'GPS不在当前地图范围内',
  1917. gpsCoordText: formatGpsCoordText(nextPoint, accuracyMeters),
  1918. autoRotateSourceText: this.getAutoRotateSourceText(),
  1919. gpsLockEnabled: this.gpsLockEnabled,
  1920. gpsLockAvailable: gpsInsideMap,
  1921. ...this.getGameViewPatch(gameStatusText || (gpsInsideMap ? `GPS位置已更新 (${this.buildVersion})` : `GPS位置超出当前地图范围 (${this.buildVersion})`)),
  1922. })
  1923. this.syncRenderer()
  1924. }
  1925. handleToggleGpsLock(): void {
  1926. if (!this.currentGpsPoint || !this.currentGpsInsideMap) {
  1927. this.setState({
  1928. gpsLockEnabled: false,
  1929. gpsLockAvailable: false,
  1930. statusText: this.currentGpsPoint
  1931. ? `当前位置不在地图范围内,无法锁定 (${this.buildVersion})`
  1932. : `当前还没有可锁定的GPS位置 (${this.buildVersion})`,
  1933. }, true)
  1934. return
  1935. }
  1936. const nextEnabled = !this.gpsLockEnabled
  1937. this.gpsLockEnabled = nextEnabled
  1938. if (nextEnabled) {
  1939. const gpsWorldPoint = lonLatToWorldTile(this.currentGpsPoint, this.state.zoom)
  1940. const gpsTileX = Math.floor(gpsWorldPoint.x)
  1941. const gpsTileY = Math.floor(gpsWorldPoint.y)
  1942. const gpsInsideMap = isTileWithinBounds(this.tileBoundsByZoom, this.state.zoom, gpsTileX, gpsTileY)
  1943. if (gpsInsideMap) {
  1944. this.hasGpsCenteredOnce = true
  1945. const lockedViewport = this.resolveViewportForExactCenter(gpsWorldPoint.x, gpsWorldPoint.y)
  1946. this.commitViewport({
  1947. ...lockedViewport,
  1948. gpsLockEnabled: true,
  1949. gpsLockAvailable: true,
  1950. }, `GPS已锁定在屏幕中央 (${this.buildVersion})`, true)
  1951. return
  1952. }
  1953. this.setState({
  1954. gpsLockEnabled: true,
  1955. gpsLockAvailable: true,
  1956. statusText: `GPS锁定已开启,等待进入地图范围 (${this.buildVersion})`,
  1957. }, true)
  1958. this.syncRenderer()
  1959. return
  1960. }
  1961. this.setState({
  1962. gpsLockEnabled: false,
  1963. gpsLockAvailable: true,
  1964. statusText: `GPS锁定已关闭 (${this.buildVersion})`,
  1965. }, true)
  1966. this.syncRenderer()
  1967. }
  1968. handleToggleOsmReference(): void {
  1969. const nextEnabled = !this.state.osmReferenceEnabled
  1970. this.setState({
  1971. osmReferenceEnabled: nextEnabled,
  1972. osmReferenceText: nextEnabled ? 'OSM参考:开' : 'OSM参考:关',
  1973. statusText: nextEnabled ? `OSM参考底图已开启 (${this.buildVersion})` : `OSM参考底图已关闭 (${this.buildVersion})`,
  1974. }, true)
  1975. this.syncRenderer()
  1976. }
  1977. handleToggleGpsTracking(): void {
  1978. if (this.locationController.listening) {
  1979. this.locationController.stop()
  1980. return
  1981. }
  1982. this.locationController.start()
  1983. }
  1984. handleSetRealLocationMode(): void {
  1985. this.locationController.setSourceMode('real')
  1986. }
  1987. handleSetMockLocationMode(): void {
  1988. this.locationController.setSourceMode('mock')
  1989. }
  1990. handleConnectMockLocationBridge(): void {
  1991. this.locationController.connectMockBridge()
  1992. }
  1993. handleDisconnectMockLocationBridge(): void {
  1994. this.locationController.disconnectMockBridge()
  1995. }
  1996. handleSetMockLocationBridgeUrl(url: string): void {
  1997. this.locationController.setMockBridgeUrl(url)
  1998. }
  1999. handleSetGameMode(nextMode: 'classic-sequential' | 'score-o'): void {
  2000. if (this.gameMode === nextMode) {
  2001. return
  2002. }
  2003. this.gameMode = nextMode
  2004. const result = this.loadGameDefinitionFromCourse()
  2005. const modeText = this.getGameModeText()
  2006. if (!result) {
  2007. return
  2008. }
  2009. this.commitGameResult(result, `已切换到${modeText} (${this.buildVersion})`, {
  2010. gameModeText: modeText,
  2011. })
  2012. }
  2013. handleSkipAction(): void {
  2014. const gameResult = this.gameRuntime.dispatch({
  2015. type: 'skip_requested',
  2016. at: Date.now(),
  2017. lon: this.currentGpsPoint ? this.currentGpsPoint.lon : null,
  2018. lat: this.currentGpsPoint ? this.currentGpsPoint.lat : null,
  2019. })
  2020. this.commitGameResult(gameResult)
  2021. }
  2022. handleConnectHeartRate(): void {
  2023. this.heartRateController.startScanAndConnect()
  2024. }
  2025. handleDisconnectHeartRate(): void {
  2026. this.heartRateController.disconnect()
  2027. }
  2028. handleSetRealHeartRateMode(): void {
  2029. this.heartRateController.setSourceMode('real')
  2030. }
  2031. handleSetMockHeartRateMode(): void {
  2032. this.heartRateController.setSourceMode('mock')
  2033. }
  2034. handleConnectMockHeartRateBridge(): void {
  2035. this.heartRateController.connectMockBridge()
  2036. }
  2037. handleDisconnectMockHeartRateBridge(): void {
  2038. this.heartRateController.disconnectMockBridge()
  2039. }
  2040. handleSetMockHeartRateBridgeUrl(url: string): void {
  2041. this.heartRateController.setMockBridgeUrl(url)
  2042. }
  2043. handleConnectHeartRateDevice(deviceId: string): void {
  2044. this.heartRateController.connectToDiscoveredDevice(deviceId)
  2045. }
  2046. handleClearPreferredHeartRateDevice(): void {
  2047. this.heartRateController.clearPreferredDevice()
  2048. this.setState({
  2049. heartRateDeviceText: this.heartRateController.currentDeviceName || '--',
  2050. heartRateScanText: this.getHeartRateScanText(),
  2051. })
  2052. }
  2053. handleDebugHeartRateTone(tone: HeartRateTone): void {
  2054. const sampleBpm = getHeartRateToneSampleBpm(tone, this.telemetryRuntime.config)
  2055. this.telemetryRuntime.dispatch({
  2056. type: 'heart_rate_updated',
  2057. at: Date.now(),
  2058. bpm: sampleBpm,
  2059. })
  2060. this.setState({
  2061. heartRateStatusText: `调试心率: ${sampleBpm} bpm / ${tone.toUpperCase()}`,
  2062. })
  2063. this.syncSessionTimerText()
  2064. }
  2065. handleClearDebugHeartRate(): void {
  2066. this.telemetryRuntime.dispatch({
  2067. type: 'heart_rate_updated',
  2068. at: Date.now(),
  2069. bpm: null,
  2070. })
  2071. this.setState({
  2072. heartRateStatusText: this.heartRateController.connected
  2073. ? (this.heartRateController.sourceMode === 'mock' ? '模拟心率源已连接' : '心率带已连接')
  2074. : (this.heartRateController.sourceMode === 'mock' ? '模拟心率源未连接' : '心率带未连接'),
  2075. heartRateScanText: this.getHeartRateScanText(),
  2076. ...this.getHeartRateControllerViewPatch(),
  2077. })
  2078. this.syncSessionTimerText()
  2079. }
  2080. formatHeartRateDevices(devices: HeartRateDiscoveredDevice[]): Array<{ deviceId: string; name: string; rssiText: string; preferred: boolean; connected: boolean }> {
  2081. return devices.map((device) => ({
  2082. deviceId: device.deviceId,
  2083. name: device.name,
  2084. rssiText: device.rssi === null ? '--' : `${device.rssi} dBm`,
  2085. preferred: device.isPreferred,
  2086. connected: !!this.heartRateController.currentDeviceId && this.heartRateController.currentDeviceId === device.deviceId && this.heartRateController.connected,
  2087. }))
  2088. }
  2089. getHeartRateScanText(): string {
  2090. if (this.heartRateController.sourceMode === 'mock') {
  2091. if (this.heartRateController.connected) {
  2092. return '模拟源已连接'
  2093. }
  2094. if (this.heartRateController.connecting) {
  2095. return '模拟源连接中'
  2096. }
  2097. return '模拟模式'
  2098. }
  2099. if (this.heartRateController.connected) {
  2100. return '已连接'
  2101. }
  2102. if (this.heartRateController.connecting) {
  2103. return '连接中'
  2104. }
  2105. if (this.heartRateController.disconnecting) {
  2106. return '断开中'
  2107. }
  2108. if (this.heartRateController.scanning) {
  2109. return this.heartRateController.lastDeviceId ? '扫描中(优先首选)' : '扫描中(等待选择)'
  2110. }
  2111. return this.heartRateController.discoveredDevices.length
  2112. ? `已发现 ${this.heartRateController.discoveredDevices.length} 个设备`
  2113. : '未扫描'
  2114. }
  2115. setStage(rect: MapEngineStageRect): void {
  2116. this.previewScale = 1
  2117. this.previewOriginX = rect.width / 2
  2118. this.previewOriginY = rect.height / 2
  2119. this.commitViewport(
  2120. {
  2121. stageWidth: rect.width,
  2122. stageHeight: rect.height,
  2123. stageLeft: rect.left,
  2124. stageTop: rect.top,
  2125. },
  2126. `地图视口已与 WebGL 引擎对齐 (${this.buildVersion})`,
  2127. true,
  2128. )
  2129. }
  2130. attachCanvas(canvasNode: any, width: number, height: number, dpr: number, labelCanvasNode?: any): void {
  2131. if (this.mounted) {
  2132. return
  2133. }
  2134. this.renderer.attachCanvas(canvasNode, width, height, dpr, labelCanvasNode)
  2135. this.mounted = true
  2136. this.state.mapReady = true
  2137. this.state.mapReadyText = 'READY'
  2138. this.onData({
  2139. mapReady: true,
  2140. mapReadyText: 'READY',
  2141. statusText: `单 WebGL 管线已完成,可切换手动或自动朝向 (${this.buildVersion})`,
  2142. })
  2143. this.syncRenderer()
  2144. this.accelerometerErrorText = null
  2145. this.lastCompassSampleAt = 0
  2146. this.compassController.start()
  2147. this.scheduleCompassBootstrapRetry()
  2148. this.gyroscopeController.start()
  2149. this.deviceMotionController.start()
  2150. }
  2151. applyRemoteMapConfig(config: RemoteMapConfig): void {
  2152. MAGNETIC_DECLINATION_DEG = config.magneticDeclinationDeg
  2153. MAGNETIC_DECLINATION_TEXT = normalizeDegreeDisplayText(config.magneticDeclinationText)
  2154. this.minZoom = config.minZoom
  2155. this.maxZoom = config.maxZoom
  2156. this.defaultZoom = config.defaultZoom
  2157. this.defaultCenterTileX = config.initialCenterTileX
  2158. this.defaultCenterTileY = config.initialCenterTileY
  2159. this.tileBoundsByZoom = config.tileBoundsByZoom
  2160. this.courseData = config.course
  2161. this.cpRadiusMeters = config.cpRadiusMeters
  2162. this.configAppId = config.configAppId
  2163. this.configSchemaVersion = config.configSchemaVersion
  2164. this.configVersion = config.configVersion
  2165. this.controlScoreOverrides = config.controlScoreOverrides
  2166. this.defaultControlScore = config.defaultControlScore
  2167. this.gameMode = config.gameMode
  2168. this.punchPolicy = config.punchPolicy
  2169. this.punchRadiusMeters = config.punchRadiusMeters
  2170. this.requiresFocusSelection = config.requiresFocusSelection
  2171. this.skipEnabled = config.skipEnabled
  2172. this.skipRadiusMeters = config.skipRadiusMeters
  2173. this.skipRequiresConfirm = config.skipRequiresConfirm
  2174. this.autoFinishOnLastControl = config.autoFinishOnLastControl
  2175. this.telemetryRuntime.configure(config.telemetryConfig)
  2176. this.feedbackDirector.configure({
  2177. audioConfig: config.audioConfig,
  2178. hapticsConfig: config.hapticsConfig,
  2179. uiEffectsConfig: config.uiEffectsConfig,
  2180. })
  2181. const gameResult = this.loadGameDefinitionFromCourse()
  2182. const gameStatusText = gameResult ? this.resolveAppliedGameStatusText(gameResult) : null
  2183. const statePatch: Partial<MapEngineViewState> = {
  2184. mapName: config.configTitle,
  2185. configStatusText: `配置已载入 / ${config.configTitle} / ${config.courseStatusText}`,
  2186. projectionMode: config.projectionModeText,
  2187. tileSource: config.tileSource,
  2188. sensorHeadingText: formatHeadingText(this.compassDisplayHeadingDeg),
  2189. compassDeclinationText: formatCompassDeclinationText(this.northReferenceMode),
  2190. northReferenceButtonText: formatNorthReferenceButtonText(this.northReferenceMode),
  2191. northReferenceText: formatNorthReferenceText(this.northReferenceMode),
  2192. compassNeedleDeg: formatCompassNeedleDegForMode(this.northReferenceMode, this.compassDisplayHeadingDeg),
  2193. ...this.getGameViewPatch(gameStatusText),
  2194. }
  2195. if (!this.state.stageWidth || !this.state.stageHeight) {
  2196. this.setState({
  2197. ...statePatch,
  2198. zoom: this.defaultZoom,
  2199. centerTileX: this.defaultCenterTileX,
  2200. centerTileY: this.defaultCenterTileY,
  2201. centerText: buildCenterText(this.defaultZoom, this.defaultCenterTileX, this.defaultCenterTileY),
  2202. statusText: gameStatusText || `路线已载入,点击开始进入游戏 (${this.buildVersion})`,
  2203. }, true)
  2204. return
  2205. }
  2206. this.commitViewport({
  2207. ...statePatch,
  2208. zoom: this.defaultZoom,
  2209. centerTileX: this.defaultCenterTileX,
  2210. centerTileY: this.defaultCenterTileY,
  2211. tileTranslateX: 0,
  2212. tileTranslateY: 0,
  2213. }, gameStatusText || `路线已载入,点击开始进入游戏 (${this.buildVersion})`, true, () => {
  2214. this.resetPreviewState()
  2215. this.syncRenderer()
  2216. if (this.state.orientationMode === 'heading-up' && this.refreshAutoRotateTarget()) {
  2217. this.scheduleAutoRotate()
  2218. }
  2219. })
  2220. }
  2221. handleTouchStart(event: WechatMiniprogram.TouchEvent): void {
  2222. this.clearInertiaTimer()
  2223. this.clearPreviewResetTimer()
  2224. this.panVelocityX = 0
  2225. this.panVelocityY = 0
  2226. if (event.touches.length >= 2) {
  2227. const origin = this.gpsLockEnabled
  2228. ? { x: this.state.stageWidth / 2, y: this.state.stageHeight / 2 }
  2229. : this.getStagePoint(event.touches)
  2230. this.gestureMode = 'pinch'
  2231. this.pinchStartDistance = this.getTouchDistance(event.touches)
  2232. this.pinchStartScale = this.previewScale || 1
  2233. this.pinchStartAngle = this.getTouchAngle(event.touches)
  2234. this.pinchStartRotationDeg = this.state.rotationDeg
  2235. const anchorWorld = this.gpsLockEnabled && this.currentGpsPoint
  2236. ? lonLatToWorldTile(this.currentGpsPoint, this.state.zoom)
  2237. : screenToWorld(this.getCameraState(), origin, true)
  2238. this.pinchAnchorWorldX = anchorWorld.x
  2239. this.pinchAnchorWorldY = anchorWorld.y
  2240. this.setPreviewState(this.pinchStartScale, origin.x, origin.y)
  2241. this.syncRenderer()
  2242. this.compassController.start()
  2243. return
  2244. }
  2245. if (event.touches.length === 1) {
  2246. this.gestureMode = 'pan'
  2247. this.panLastX = event.touches[0].pageX
  2248. this.panLastY = event.touches[0].pageY
  2249. this.panLastTimestamp = event.timeStamp || Date.now()
  2250. this.tapStartX = event.touches[0].pageX
  2251. this.tapStartY = event.touches[0].pageY
  2252. this.tapStartAt = event.timeStamp || Date.now()
  2253. }
  2254. }
  2255. handleTouchMove(event: WechatMiniprogram.TouchEvent): void {
  2256. if (event.touches.length >= 2) {
  2257. const distance = this.getTouchDistance(event.touches)
  2258. const angle = this.getTouchAngle(event.touches)
  2259. const origin = this.gpsLockEnabled
  2260. ? { x: this.state.stageWidth / 2, y: this.state.stageHeight / 2 }
  2261. : this.getStagePoint(event.touches)
  2262. if (!this.pinchStartDistance) {
  2263. this.pinchStartDistance = distance
  2264. this.pinchStartScale = this.previewScale || 1
  2265. this.pinchStartAngle = angle
  2266. this.pinchStartRotationDeg = this.state.rotationDeg
  2267. const anchorWorld = this.gpsLockEnabled && this.currentGpsPoint
  2268. ? lonLatToWorldTile(this.currentGpsPoint, this.state.zoom)
  2269. : screenToWorld(this.getCameraState(), origin, true)
  2270. this.pinchAnchorWorldX = anchorWorld.x
  2271. this.pinchAnchorWorldY = anchorWorld.y
  2272. }
  2273. this.gestureMode = 'pinch'
  2274. const nextRotationDeg = this.state.orientationMode === 'heading-up'
  2275. ? this.state.rotationDeg
  2276. : normalizeRotationDeg(this.pinchStartRotationDeg + normalizeAngleDeltaRad(angle - this.pinchStartAngle) * 180 / Math.PI)
  2277. const anchorOffset = this.getWorldOffsetFromScreen(origin.x, origin.y, nextRotationDeg)
  2278. const resolvedViewport = this.resolveViewportForExactCenter(
  2279. this.pinchAnchorWorldX - anchorOffset.x,
  2280. this.pinchAnchorWorldY - anchorOffset.y,
  2281. nextRotationDeg,
  2282. )
  2283. this.setPreviewState(
  2284. clamp(this.pinchStartScale * (distance / this.pinchStartDistance), MIN_PREVIEW_SCALE, MAX_PREVIEW_SCALE),
  2285. origin.x,
  2286. origin.y,
  2287. )
  2288. this.commitViewport(
  2289. {
  2290. ...resolvedViewport,
  2291. rotationDeg: nextRotationDeg,
  2292. rotationText: formatRotationText(nextRotationDeg),
  2293. },
  2294. this.state.orientationMode === 'heading-up'
  2295. ? `双指缩放中,自动朝向保持开启 (${this.buildVersion})`
  2296. : `双指缩放与旋转中 (${this.buildVersion})`,
  2297. )
  2298. return
  2299. }
  2300. if (this.gestureMode !== 'pan' || event.touches.length !== 1) {
  2301. return
  2302. }
  2303. const touch = event.touches[0]
  2304. const deltaX = touch.pageX - this.panLastX
  2305. const deltaY = touch.pageY - this.panLastY
  2306. const nextTimestamp = event.timeStamp || Date.now()
  2307. const elapsed = Math.max(nextTimestamp - this.panLastTimestamp, 16)
  2308. const instantVelocityX = deltaX / elapsed
  2309. const instantVelocityY = deltaY / elapsed
  2310. this.panVelocityX = this.panVelocityX * 0.72 + instantVelocityX * 0.28
  2311. this.panVelocityY = this.panVelocityY * 0.72 + instantVelocityY * 0.28
  2312. this.panLastX = touch.pageX
  2313. this.panLastY = touch.pageY
  2314. this.panLastTimestamp = nextTimestamp
  2315. if (this.gpsLockEnabled) {
  2316. this.panVelocityX = 0
  2317. this.panVelocityY = 0
  2318. return
  2319. }
  2320. this.normalizeTranslate(
  2321. this.state.tileTranslateX + deltaX,
  2322. this.state.tileTranslateY + deltaY,
  2323. `宸叉嫋鎷藉崟 WebGL 鍦板浘寮曟搸 (${this.buildVersion})`,
  2324. )
  2325. }
  2326. handleTouchEnd(event: WechatMiniprogram.TouchEvent): void {
  2327. const changedTouch = event.changedTouches && event.changedTouches.length ? event.changedTouches[0] : null
  2328. const endedAsTap = changedTouch
  2329. && this.gestureMode === 'pan'
  2330. && event.touches.length === 0
  2331. && Math.abs(changedTouch.pageX - this.tapStartX) <= MAP_TAP_MOVE_THRESHOLD_PX
  2332. && Math.abs(changedTouch.pageY - this.tapStartY) <= MAP_TAP_MOVE_THRESHOLD_PX
  2333. && ((event.timeStamp || Date.now()) - this.tapStartAt) <= MAP_TAP_DURATION_MS
  2334. if (this.gestureMode === 'pinch' && event.touches.length < 2) {
  2335. const gestureScale = this.previewScale || 1
  2336. const zoomDelta = Math.round(Math.log2(gestureScale))
  2337. const originX = this.gpsLockEnabled ? this.state.stageWidth / 2 : (this.previewOriginX || this.state.stageWidth / 2)
  2338. const originY = this.gpsLockEnabled ? this.state.stageHeight / 2 : (this.previewOriginY || this.state.stageHeight / 2)
  2339. if (zoomDelta) {
  2340. const residualScale = gestureScale / Math.pow(2, zoomDelta)
  2341. this.zoomAroundPoint(zoomDelta, originX, originY, residualScale)
  2342. } else {
  2343. this.animatePreviewToRest()
  2344. }
  2345. this.resetPinchState()
  2346. this.panVelocityX = 0
  2347. this.panVelocityY = 0
  2348. if (event.touches.length === 1) {
  2349. this.gestureMode = 'pan'
  2350. this.panLastX = event.touches[0].pageX
  2351. this.panLastY = event.touches[0].pageY
  2352. this.panLastTimestamp = event.timeStamp || Date.now()
  2353. return
  2354. }
  2355. this.gestureMode = 'idle'
  2356. this.renderer.setAnimationPaused(false)
  2357. this.scheduleAutoRotate()
  2358. return
  2359. }
  2360. if (event.touches.length === 1) {
  2361. this.gestureMode = 'pan'
  2362. this.panLastX = event.touches[0].pageX
  2363. this.panLastY = event.touches[0].pageY
  2364. this.panLastTimestamp = event.timeStamp || Date.now()
  2365. return
  2366. }
  2367. if (this.gestureMode === 'pan' && (Math.abs(this.panVelocityX) >= INERTIA_MIN_SPEED || Math.abs(this.panVelocityY) >= INERTIA_MIN_SPEED)) {
  2368. this.startInertia()
  2369. this.gestureMode = 'idle'
  2370. this.resetPinchState()
  2371. return
  2372. }
  2373. if (endedAsTap && changedTouch) {
  2374. this.handleMapTap(changedTouch.pageX - this.state.stageLeft, changedTouch.pageY - this.state.stageTop)
  2375. }
  2376. this.gestureMode = 'idle'
  2377. this.resetPinchState()
  2378. this.renderer.setAnimationPaused(false)
  2379. this.scheduleAutoRotate()
  2380. }
  2381. handleTouchCancel(): void {
  2382. this.gestureMode = 'idle'
  2383. this.resetPinchState()
  2384. this.panVelocityX = 0
  2385. this.panVelocityY = 0
  2386. this.clearInertiaTimer()
  2387. this.animatePreviewToRest()
  2388. this.renderer.setAnimationPaused(false)
  2389. this.scheduleAutoRotate()
  2390. }
  2391. handleMapTap(stageX: number, stageY: number): void {
  2392. if (!this.gameRuntime.definition || !this.gameRuntime.state || this.gameRuntime.definition.mode !== 'score-o') {
  2393. return
  2394. }
  2395. const focusedControlId = this.findFocusableControlAt(stageX, stageY)
  2396. if (focusedControlId === undefined) {
  2397. return
  2398. }
  2399. const gameResult = this.gameRuntime.dispatch({
  2400. type: 'control_focused',
  2401. at: Date.now(),
  2402. controlId: focusedControlId,
  2403. })
  2404. this.commitGameResult(
  2405. gameResult,
  2406. focusedControlId ? `已选择目标点 (${this.buildVersion})` : `已取消目标点选择 (${this.buildVersion})`,
  2407. )
  2408. }
  2409. findFocusableControlAt(stageX: number, stageY: number): string | null | undefined {
  2410. if (!this.gameRuntime.definition || !this.courseData || !this.state.stageWidth || !this.state.stageHeight) {
  2411. return undefined
  2412. }
  2413. const focusableControls = this.gameRuntime.definition.controls.filter((control) => (
  2414. this.gamePresentation.map.focusableControlIds.includes(control.id)
  2415. ))
  2416. let matchedControlId: string | null | undefined
  2417. let matchedDistance = Number.POSITIVE_INFINITY
  2418. const hitRadiusPx = Math.max(28, this.getControlHitRadiusPx())
  2419. for (const control of focusableControls) {
  2420. const screenPoint = this.getControlScreenPoint(control.id)
  2421. if (!screenPoint) {
  2422. continue
  2423. }
  2424. const distancePx = Math.sqrt(
  2425. Math.pow(screenPoint.x - stageX, 2)
  2426. + Math.pow(screenPoint.y - stageY, 2),
  2427. )
  2428. if (distancePx <= hitRadiusPx && distancePx < matchedDistance) {
  2429. matchedDistance = distancePx
  2430. matchedControlId = control.id
  2431. }
  2432. }
  2433. if (matchedControlId === undefined) {
  2434. return undefined
  2435. }
  2436. return matchedControlId === this.gamePresentation.map.focusedControlId ? null : matchedControlId
  2437. }
  2438. getControlHitRadiusPx(): number {
  2439. if (!this.state.tileSizePx) {
  2440. return 28
  2441. }
  2442. const centerLonLat = worldTileToLonLat({ x: this.state.centerTileX + 0.5, y: this.state.centerTileY + 0.5 }, this.state.zoom)
  2443. const metersPerTile = Math.cos(centerLonLat.lat * Math.PI / 180) * 40075016.686 / Math.pow(2, this.state.zoom)
  2444. if (!metersPerTile) {
  2445. return 28
  2446. }
  2447. const pixelsPerMeter = this.state.tileSizePx / metersPerTile
  2448. return Math.max(28, this.cpRadiusMeters * pixelsPerMeter * 1.6)
  2449. }
  2450. handleRecenter(): void {
  2451. this.clearInertiaTimer()
  2452. this.clearPreviewResetTimer()
  2453. this.panVelocityX = 0
  2454. this.panVelocityY = 0
  2455. this.renderer.setAnimationPaused(false)
  2456. this.commitViewport(
  2457. {
  2458. zoom: this.defaultZoom,
  2459. centerTileX: this.defaultCenterTileX,
  2460. centerTileY: this.defaultCenterTileY,
  2461. tileTranslateX: 0,
  2462. tileTranslateY: 0,
  2463. },
  2464. `已回到单 WebGL 引擎默认首屏 (${this.buildVersion})`,
  2465. true,
  2466. () => {
  2467. this.resetPreviewState()
  2468. this.syncRenderer()
  2469. this.compassController.start()
  2470. this.scheduleAutoRotate()
  2471. },
  2472. )
  2473. }
  2474. handleRotateStep(stepDeg = ROTATE_STEP_DEG): void {
  2475. if (this.state.rotationMode === 'auto') {
  2476. this.setState({
  2477. statusText: `当前不是手动旋转模式,请先切回手动 (${this.buildVersion})`,
  2478. }, true)
  2479. return
  2480. }
  2481. const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
  2482. const nextRotationDeg = normalizeRotationDeg(this.state.rotationDeg + stepDeg)
  2483. const resolvedViewport = this.resolveViewportForExactCenter(exactCenter.x, exactCenter.y, nextRotationDeg)
  2484. this.clearInertiaTimer()
  2485. this.clearPreviewResetTimer()
  2486. this.panVelocityX = 0
  2487. this.panVelocityY = 0
  2488. this.renderer.setAnimationPaused(false)
  2489. this.commitViewport(
  2490. {
  2491. ...resolvedViewport,
  2492. rotationDeg: nextRotationDeg,
  2493. rotationText: formatRotationText(nextRotationDeg),
  2494. },
  2495. `旋转角度调整到 ${formatRotationText(nextRotationDeg)} (${this.buildVersion})`,
  2496. true,
  2497. () => {
  2498. this.resetPreviewState()
  2499. this.syncRenderer()
  2500. this.compassController.start()
  2501. },
  2502. )
  2503. }
  2504. handleRotationReset(): void {
  2505. if (this.state.rotationMode === 'auto') {
  2506. this.setState({
  2507. statusText: `当前不是手动旋转模式,请先切回手动 (${this.buildVersion})`,
  2508. }, true)
  2509. return
  2510. }
  2511. const targetRotationDeg = MAP_NORTH_OFFSET_DEG
  2512. if (Math.abs(normalizeAngleDeltaDeg(this.state.rotationDeg - targetRotationDeg)) <= 0.01) {
  2513. return
  2514. }
  2515. const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
  2516. const resolvedViewport = this.resolveViewportForExactCenter(exactCenter.x, exactCenter.y, targetRotationDeg)
  2517. this.clearInertiaTimer()
  2518. this.clearPreviewResetTimer()
  2519. this.panVelocityX = 0
  2520. this.panVelocityY = 0
  2521. this.renderer.setAnimationPaused(false)
  2522. this.commitViewport(
  2523. {
  2524. ...resolvedViewport,
  2525. rotationDeg: targetRotationDeg,
  2526. rotationText: formatRotationText(targetRotationDeg),
  2527. },
  2528. `旋转角度已回到真北参考 (${this.buildVersion})`,
  2529. true,
  2530. () => {
  2531. this.resetPreviewState()
  2532. this.syncRenderer()
  2533. this.compassController.start()
  2534. },
  2535. )
  2536. }
  2537. handleToggleRotationMode(): void {
  2538. if (this.state.orientationMode === 'manual') {
  2539. this.setNorthUpMode()
  2540. return
  2541. }
  2542. if (this.state.orientationMode === 'north-up') {
  2543. this.setHeadingUpMode()
  2544. return
  2545. }
  2546. this.setManualMode()
  2547. }
  2548. handleSetManualMode(): void {
  2549. this.setManualMode()
  2550. }
  2551. handleSetNorthUpMode(): void {
  2552. this.setNorthUpMode()
  2553. }
  2554. handleSetHeadingUpMode(): void {
  2555. this.setHeadingUpMode()
  2556. }
  2557. handleCycleNorthReferenceMode(): void {
  2558. this.cycleNorthReferenceMode()
  2559. }
  2560. handleSetNorthReferenceMode(mode: NorthReferenceMode): void {
  2561. this.setNorthReferenceMode(mode)
  2562. }
  2563. handleSetAnimationLevel(level: AnimationLevel): void {
  2564. if (this.animationLevel === level) {
  2565. return
  2566. }
  2567. this.animationLevel = level
  2568. this.feedbackDirector.setAnimationLevel(level)
  2569. this.setState({
  2570. animationLevel: level,
  2571. statusText: `动画性能已切换为${formatAnimationLevelText(level)} (${this.buildVersion})`,
  2572. })
  2573. this.syncRenderer()
  2574. }
  2575. handleSetCompassTuningProfile(profile: CompassTuningProfile): void {
  2576. if (this.compassTuningProfile === profile) {
  2577. return
  2578. }
  2579. this.compassTuningProfile = profile
  2580. this.compassController.setTuningProfile(profile)
  2581. this.setState({
  2582. compassTuningProfile: profile,
  2583. compassTuningProfileText: formatCompassTuningProfileText(profile),
  2584. statusText: `指北针响应已切换为${formatCompassTuningProfileText(profile)} (${this.buildVersion})`,
  2585. }, true)
  2586. }
  2587. handleAutoRotateCalibrate(): void {
  2588. if (this.state.orientationMode !== 'heading-up') {
  2589. this.setState({
  2590. statusText: `请先切到朝向朝上模式再校准 (${this.buildVersion})`,
  2591. }, true)
  2592. return
  2593. }
  2594. if (!this.calibrateAutoRotateToCurrentOrientation()) {
  2595. this.setState({
  2596. statusText: `当前还没有传感器方向数据,暂时无法校准 (${this.buildVersion})`,
  2597. }, true)
  2598. return
  2599. }
  2600. this.setState({
  2601. statusText: `已按当前持机方向完成朝向校准 (${this.buildVersion})`,
  2602. }, true)
  2603. this.scheduleAutoRotate()
  2604. }
  2605. setManualMode(): void {
  2606. this.clearAutoRotateTimer()
  2607. this.targetAutoRotationDeg = null
  2608. this.autoRotateCalibrationPending = false
  2609. this.setState({
  2610. rotationMode: 'manual',
  2611. rotationModeText: formatRotationModeText('manual'),
  2612. rotationToggleText: formatRotationToggleText('manual'),
  2613. orientationMode: 'manual',
  2614. orientationModeText: formatOrientationModeText('manual'),
  2615. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, this.autoRotateCalibrationOffsetDeg),
  2616. statusText: `已切回手动地图旋转 (${this.buildVersion})`,
  2617. }, true)
  2618. }
  2619. setNorthUpMode(): void {
  2620. this.clearAutoRotateTimer()
  2621. this.targetAutoRotationDeg = null
  2622. this.autoRotateCalibrationPending = false
  2623. const mapNorthOffsetDeg = MAP_NORTH_OFFSET_DEG
  2624. this.autoRotateCalibrationOffsetDeg = mapNorthOffsetDeg
  2625. const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
  2626. const resolvedViewport = this.resolveViewportForExactCenter(exactCenter.x, exactCenter.y, mapNorthOffsetDeg)
  2627. this.commitViewport(
  2628. {
  2629. ...resolvedViewport,
  2630. rotationDeg: mapNorthOffsetDeg,
  2631. rotationText: formatRotationText(mapNorthOffsetDeg),
  2632. rotationMode: 'manual',
  2633. rotationModeText: formatRotationModeText('north-up'),
  2634. rotationToggleText: formatRotationToggleText('north-up'),
  2635. orientationMode: 'north-up',
  2636. orientationModeText: formatOrientationModeText('north-up'),
  2637. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, mapNorthOffsetDeg),
  2638. northReferenceText: formatNorthReferenceText(this.northReferenceMode),
  2639. },
  2640. `地图已固定为真北朝上 (${this.buildVersion})`,
  2641. true,
  2642. () => {
  2643. this.resetPreviewState()
  2644. this.syncRenderer()
  2645. },
  2646. )
  2647. }
  2648. setHeadingUpMode(): void {
  2649. this.autoRotateCalibrationPending = false
  2650. this.autoRotateCalibrationOffsetDeg = getMapNorthOffsetDeg(this.northReferenceMode)
  2651. this.targetAutoRotationDeg = null
  2652. this.setState({
  2653. rotationMode: 'auto',
  2654. rotationModeText: formatRotationModeText('heading-up'),
  2655. rotationToggleText: formatRotationToggleText('heading-up'),
  2656. orientationMode: 'heading-up',
  2657. orientationModeText: formatOrientationModeText('heading-up'),
  2658. autoRotateSourceText: this.getAutoRotateSourceText(),
  2659. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, this.autoRotateCalibrationOffsetDeg),
  2660. northReferenceText: formatNorthReferenceText(this.northReferenceMode),
  2661. statusText: `正在启用朝向朝上模式 (${this.buildVersion})`,
  2662. }, true)
  2663. if (this.refreshAutoRotateTarget()) {
  2664. this.scheduleAutoRotate()
  2665. }
  2666. }
  2667. applyHeadingSample(headingDeg: number, source: 'compass' | 'motion'): void {
  2668. this.compassSource = source
  2669. this.sensorHeadingDeg = normalizeRotationDeg(headingDeg)
  2670. this.smoothedSensorHeadingDeg = this.smoothedSensorHeadingDeg === null
  2671. ? this.sensorHeadingDeg
  2672. : interpolateAngleDeg(this.smoothedSensorHeadingDeg, this.sensorHeadingDeg, AUTO_ROTATE_HEADING_SMOOTHING)
  2673. const compassHeadingDeg = getCompassReferenceHeadingDeg(this.northReferenceMode, this.smoothedSensorHeadingDeg)
  2674. if (this.compassDisplayHeadingDeg === null) {
  2675. this.compassDisplayHeadingDeg = compassHeadingDeg
  2676. this.targetCompassDisplayHeadingDeg = compassHeadingDeg
  2677. this.syncCompassDisplayState()
  2678. } else {
  2679. this.targetCompassDisplayHeadingDeg = compassHeadingDeg
  2680. const displayDeltaDeg = Math.abs(normalizeAngleDeltaDeg(compassHeadingDeg - this.compassDisplayHeadingDeg))
  2681. if (displayDeltaDeg >= COMPASS_TUNING_PRESETS[this.compassTuningProfile].displayDeadzoneDeg) {
  2682. this.scheduleCompassNeedleFollow()
  2683. }
  2684. }
  2685. this.autoRotateHeadingDeg = this.resolveAutoRotateInputHeadingDeg()
  2686. this.setState({
  2687. compassSourceText: formatCompassSourceText(this.compassSource),
  2688. ...(this.diagnosticUiEnabled
  2689. ? {
  2690. ...this.getTelemetrySensorViewPatch(),
  2691. northReferenceButtonText: formatNorthReferenceButtonText(this.northReferenceMode),
  2692. autoRotateSourceText: this.getAutoRotateSourceText(),
  2693. northReferenceText: formatNorthReferenceText(this.northReferenceMode),
  2694. }
  2695. : {}),
  2696. })
  2697. if (!this.refreshAutoRotateTarget()) {
  2698. return
  2699. }
  2700. if (this.state.orientationMode === 'heading-up') {
  2701. this.scheduleAutoRotate()
  2702. }
  2703. }
  2704. handleCompassHeading(headingDeg: number): void {
  2705. this.lastCompassSampleAt = Date.now()
  2706. this.clearCompassBootstrapRetryTimer()
  2707. this.applyHeadingSample(headingDeg, 'compass')
  2708. }
  2709. handleCompassError(message: string): void {
  2710. this.clearAutoRotateTimer()
  2711. this.clearCompassNeedleTimer()
  2712. this.targetAutoRotationDeg = null
  2713. this.autoRotateCalibrationPending = false
  2714. this.compassSource = null
  2715. this.targetCompassDisplayHeadingDeg = null
  2716. this.setState({
  2717. compassSourceText: formatCompassSourceText(null),
  2718. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, this.autoRotateCalibrationOffsetDeg),
  2719. statusText: `${message} (${this.buildVersion})`,
  2720. }, true)
  2721. }
  2722. cycleNorthReferenceMode(): void {
  2723. this.setNorthReferenceMode(getNextNorthReferenceMode(this.northReferenceMode))
  2724. }
  2725. setNorthReferenceMode(nextMode: NorthReferenceMode): void {
  2726. if (nextMode === this.northReferenceMode) {
  2727. return
  2728. }
  2729. const nextMapNorthOffsetDeg = getMapNorthOffsetDeg(nextMode)
  2730. const compassHeadingDeg = this.smoothedSensorHeadingDeg === null
  2731. ? null
  2732. : getCompassReferenceHeadingDeg(nextMode, this.smoothedSensorHeadingDeg)
  2733. this.northReferenceMode = nextMode
  2734. this.autoRotateCalibrationOffsetDeg = nextMapNorthOffsetDeg
  2735. this.compassDisplayHeadingDeg = compassHeadingDeg
  2736. this.targetCompassDisplayHeadingDeg = compassHeadingDeg
  2737. if (this.state.orientationMode === 'north-up') {
  2738. const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
  2739. const resolvedViewport = this.resolveViewportForExactCenter(exactCenter.x, exactCenter.y, MAP_NORTH_OFFSET_DEG)
  2740. this.commitViewport(
  2741. {
  2742. ...resolvedViewport,
  2743. rotationDeg: MAP_NORTH_OFFSET_DEG,
  2744. rotationText: formatRotationText(MAP_NORTH_OFFSET_DEG),
  2745. northReferenceText: formatNorthReferenceText(nextMode),
  2746. sensorHeadingText: formatHeadingText(this.compassDisplayHeadingDeg),
  2747. ...this.getTelemetrySensorViewPatch(),
  2748. compassDeclinationText: formatCompassDeclinationText(nextMode),
  2749. northReferenceMode: nextMode,
  2750. northReferenceButtonText: formatNorthReferenceButtonText(nextMode),
  2751. compassNeedleDeg: formatCompassNeedleDegForMode(nextMode, this.compassDisplayHeadingDeg),
  2752. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, nextMapNorthOffsetDeg),
  2753. },
  2754. `${formatNorthReferenceStatusText(nextMode)} (${this.buildVersion})`,
  2755. true,
  2756. () => {
  2757. this.resetPreviewState()
  2758. this.syncRenderer()
  2759. },
  2760. )
  2761. return
  2762. }
  2763. this.setState({
  2764. northReferenceText: formatNorthReferenceText(nextMode),
  2765. sensorHeadingText: formatHeadingText(this.compassDisplayHeadingDeg),
  2766. ...this.getTelemetrySensorViewPatch(),
  2767. compassDeclinationText: formatCompassDeclinationText(nextMode),
  2768. northReferenceMode: nextMode,
  2769. northReferenceButtonText: formatNorthReferenceButtonText(nextMode),
  2770. compassNeedleDeg: formatCompassNeedleDegForMode(nextMode, this.compassDisplayHeadingDeg),
  2771. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, nextMapNorthOffsetDeg),
  2772. statusText: `${formatNorthReferenceStatusText(nextMode)} (${this.buildVersion})`,
  2773. }, true)
  2774. if (this.state.orientationMode === 'heading-up' && this.refreshAutoRotateTarget()) {
  2775. this.scheduleAutoRotate()
  2776. }
  2777. if (this.compassDisplayHeadingDeg !== null) {
  2778. this.syncCompassDisplayState()
  2779. }
  2780. }
  2781. setCourseHeading(headingDeg: number | null): void {
  2782. this.courseHeadingDeg = headingDeg === null ? null : normalizeRotationDeg(headingDeg)
  2783. this.setState({
  2784. autoRotateSourceText: this.getAutoRotateSourceText(),
  2785. })
  2786. if (this.refreshAutoRotateTarget()) {
  2787. this.scheduleAutoRotate()
  2788. }
  2789. }
  2790. getRawMovementHeadingDeg(): number | null {
  2791. if (!this.currentGpsInsideMap) {
  2792. return null
  2793. }
  2794. if (this.currentGpsAccuracyMeters !== null && this.currentGpsAccuracyMeters > SMART_HEADING_MAX_ACCURACY_METERS) {
  2795. return null
  2796. }
  2797. if (this.currentGpsTrack.length < 2) {
  2798. return null
  2799. }
  2800. const lastPoint = this.currentGpsTrack[this.currentGpsTrack.length - 1]
  2801. let accumulatedDistanceMeters = 0
  2802. for (let index = this.currentGpsTrack.length - 2; index >= 0; index -= 1) {
  2803. const nextPoint = this.currentGpsTrack[index + 1]
  2804. const point = this.currentGpsTrack[index]
  2805. accumulatedDistanceMeters += getApproxDistanceMeters(point, nextPoint)
  2806. if (accumulatedDistanceMeters >= SMART_HEADING_MIN_DISTANCE_METERS) {
  2807. return getInitialBearingDeg(point, lastPoint)
  2808. }
  2809. }
  2810. return null
  2811. }
  2812. updateMovementHeadingDeg(): void {
  2813. const rawMovementHeadingDeg = this.getRawMovementHeadingDeg()
  2814. if (rawMovementHeadingDeg === null) {
  2815. this.smoothedMovementHeadingDeg = null
  2816. return
  2817. }
  2818. const smoothingFactor = getMovementHeadingSmoothingFactor(this.telemetryRuntime.state.currentSpeedKmh)
  2819. this.smoothedMovementHeadingDeg = this.smoothedMovementHeadingDeg === null
  2820. ? rawMovementHeadingDeg
  2821. : interpolateAngleDeg(this.smoothedMovementHeadingDeg, rawMovementHeadingDeg, smoothingFactor)
  2822. }
  2823. getMovementHeadingDeg(): number | null {
  2824. return this.smoothedMovementHeadingDeg
  2825. }
  2826. getPreferredSensorHeadingDeg(): number | null {
  2827. return this.smoothedSensorHeadingDeg === null
  2828. ? null
  2829. : getMapReferenceHeadingDegFromSensor(this.northReferenceMode, this.smoothedSensorHeadingDeg)
  2830. }
  2831. getSmartAutoRotateHeadingDeg(): number | null {
  2832. const sensorHeadingDeg = this.getPreferredSensorHeadingDeg()
  2833. const movementHeadingDeg = this.getMovementHeadingDeg()
  2834. const speedKmh = this.telemetryRuntime.state.currentSpeedKmh
  2835. const smartSource = resolveSmartHeadingSource(speedKmh, movementHeadingDeg !== null)
  2836. if (smartSource === 'movement') {
  2837. return movementHeadingDeg === null ? sensorHeadingDeg : movementHeadingDeg
  2838. }
  2839. if (smartSource === 'blended' && sensorHeadingDeg !== null && movementHeadingDeg !== null && speedKmh !== null) {
  2840. const blend = Math.max(0, Math.min(1, (speedKmh - SMART_HEADING_BLEND_START_SPEED_KMH) / (SMART_HEADING_MOVEMENT_SPEED_KMH - SMART_HEADING_BLEND_START_SPEED_KMH)))
  2841. return interpolateAngleDeg(sensorHeadingDeg, movementHeadingDeg, blend)
  2842. }
  2843. return sensorHeadingDeg === null ? movementHeadingDeg : sensorHeadingDeg
  2844. }
  2845. getAutoRotateSourceText(): string {
  2846. if (this.autoRotateSourceMode !== 'smart') {
  2847. return formatAutoRotateSourceText(this.autoRotateSourceMode, this.courseHeadingDeg !== null)
  2848. }
  2849. const smartSource = resolveSmartHeadingSource(
  2850. this.telemetryRuntime.state.currentSpeedKmh,
  2851. this.getMovementHeadingDeg() !== null,
  2852. )
  2853. return formatSmartHeadingSourceText(smartSource)
  2854. }
  2855. resolveAutoRotateInputHeadingDeg(): number | null {
  2856. if (this.autoRotateSourceMode === 'smart') {
  2857. return this.getSmartAutoRotateHeadingDeg()
  2858. }
  2859. const sensorHeadingDeg = this.getPreferredSensorHeadingDeg()
  2860. const courseHeadingDeg = this.courseHeadingDeg === null
  2861. ? null
  2862. : getMapReferenceHeadingDegFromCourse(this.northReferenceMode, this.courseHeadingDeg)
  2863. if (this.autoRotateSourceMode === 'sensor') {
  2864. return sensorHeadingDeg
  2865. }
  2866. if (this.autoRotateSourceMode === 'course') {
  2867. return courseHeadingDeg === null ? sensorHeadingDeg : courseHeadingDeg
  2868. }
  2869. if (sensorHeadingDeg !== null && courseHeadingDeg !== null) {
  2870. return interpolateAngleDeg(sensorHeadingDeg, courseHeadingDeg, 0.35)
  2871. }
  2872. return sensorHeadingDeg === null ? courseHeadingDeg : sensorHeadingDeg
  2873. }
  2874. calibrateAutoRotateToCurrentOrientation(): boolean {
  2875. const inputHeadingDeg = this.resolveAutoRotateInputHeadingDeg()
  2876. if (inputHeadingDeg === null) {
  2877. return false
  2878. }
  2879. this.autoRotateCalibrationOffsetDeg = normalizeRotationDeg(this.state.rotationDeg + inputHeadingDeg)
  2880. this.autoRotateCalibrationPending = false
  2881. this.targetAutoRotationDeg = normalizeRotationDeg(this.autoRotateCalibrationOffsetDeg - inputHeadingDeg)
  2882. this.setState({
  2883. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, this.autoRotateCalibrationOffsetDeg),
  2884. })
  2885. return true
  2886. }
  2887. refreshAutoRotateTarget(): boolean {
  2888. const inputHeadingDeg = this.resolveAutoRotateInputHeadingDeg()
  2889. if (inputHeadingDeg === null) {
  2890. return false
  2891. }
  2892. if (this.autoRotateCalibrationPending || this.autoRotateCalibrationOffsetDeg === null) {
  2893. if (!this.calibrateAutoRotateToCurrentOrientation()) {
  2894. return false
  2895. }
  2896. return true
  2897. }
  2898. this.targetAutoRotationDeg = normalizeRotationDeg(this.autoRotateCalibrationOffsetDeg - inputHeadingDeg)
  2899. this.setState({
  2900. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, this.autoRotateCalibrationOffsetDeg),
  2901. })
  2902. return true
  2903. }
  2904. scheduleAutoRotate(): void {
  2905. if (this.autoRotateTimer || this.state.rotationMode !== 'auto' || this.targetAutoRotationDeg === null) {
  2906. return
  2907. }
  2908. const step = () => {
  2909. this.autoRotateTimer = 0
  2910. if (this.state.rotationMode !== 'auto' || this.targetAutoRotationDeg === null) {
  2911. return
  2912. }
  2913. if (this.gestureMode !== 'idle' || this.inertiaTimer || this.previewResetTimer) {
  2914. this.scheduleAutoRotate()
  2915. return
  2916. }
  2917. const currentRotationDeg = this.state.rotationDeg
  2918. const deltaDeg = normalizeAngleDeltaDeg(this.targetAutoRotationDeg - currentRotationDeg)
  2919. if (Math.abs(deltaDeg) <= AUTO_ROTATE_SNAP_DEG) {
  2920. if (Math.abs(deltaDeg) > 0.01) {
  2921. this.applyAutoRotation(this.targetAutoRotationDeg)
  2922. }
  2923. this.scheduleAutoRotate()
  2924. return
  2925. }
  2926. if (Math.abs(deltaDeg) <= AUTO_ROTATE_DEADZONE_DEG) {
  2927. this.scheduleAutoRotate()
  2928. return
  2929. }
  2930. const easedStepDeg = clamp(deltaDeg * AUTO_ROTATE_EASE, -AUTO_ROTATE_MAX_STEP_DEG, AUTO_ROTATE_MAX_STEP_DEG)
  2931. this.applyAutoRotation(normalizeRotationDeg(currentRotationDeg + easedStepDeg))
  2932. this.scheduleAutoRotate()
  2933. }
  2934. this.autoRotateTimer = setTimeout(step, AUTO_ROTATE_FRAME_MS) as unknown as number
  2935. }
  2936. applyAutoRotation(nextRotationDeg: number): void {
  2937. const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
  2938. const resolvedViewport = this.resolveViewportForExactCenter(exactCenter.x, exactCenter.y, nextRotationDeg)
  2939. this.setState({
  2940. ...resolvedViewport,
  2941. rotationDeg: nextRotationDeg,
  2942. rotationText: formatRotationText(nextRotationDeg),
  2943. centerText: buildCenterText(this.state.zoom, resolvedViewport.centerTileX, resolvedViewport.centerTileY),
  2944. })
  2945. this.syncRenderer()
  2946. }
  2947. applyStats(stats: MapRendererStats): void {
  2948. const statsPatch = {
  2949. visibleTileCount: stats.visibleTileCount,
  2950. readyTileCount: stats.readyTileCount,
  2951. memoryTileCount: stats.memoryTileCount,
  2952. diskTileCount: stats.diskTileCount,
  2953. memoryHitCount: stats.memoryHitCount,
  2954. diskHitCount: stats.diskHitCount,
  2955. networkFetchCount: stats.networkFetchCount,
  2956. cacheHitRateText: formatCacheHitRate(stats.memoryHitCount, stats.diskHitCount, stats.networkFetchCount),
  2957. }
  2958. if (!this.diagnosticUiEnabled) {
  2959. this.state = {
  2960. ...this.state,
  2961. ...statsPatch,
  2962. }
  2963. return
  2964. }
  2965. const now = Date.now()
  2966. if (now - this.lastStatsUiSyncAt < 500) {
  2967. this.state = {
  2968. ...this.state,
  2969. ...statsPatch,
  2970. }
  2971. return
  2972. }
  2973. this.lastStatsUiSyncAt = now
  2974. this.setState(statsPatch)
  2975. }
  2976. setState(patch: Partial<MapEngineViewState>, immediateUi = false): void {
  2977. this.state = {
  2978. ...this.state,
  2979. ...patch,
  2980. }
  2981. const viewPatch = this.pickViewPatch(patch)
  2982. if (!Object.keys(viewPatch).length) {
  2983. return
  2984. }
  2985. this.pendingViewPatch = {
  2986. ...this.pendingViewPatch,
  2987. ...viewPatch,
  2988. }
  2989. if (immediateUi) {
  2990. this.flushViewPatch()
  2991. return
  2992. }
  2993. if (this.viewSyncTimer) {
  2994. return
  2995. }
  2996. this.viewSyncTimer = setTimeout(() => {
  2997. this.viewSyncTimer = 0
  2998. this.flushViewPatch()
  2999. }, UI_SYNC_INTERVAL_MS) as unknown as number
  3000. }
  3001. commitViewport(
  3002. patch: Partial<MapEngineViewState>,
  3003. statusText: string,
  3004. immediateUi = false,
  3005. afterUpdate?: () => void,
  3006. ): void {
  3007. const nextZoom = typeof patch.zoom === 'number' ? patch.zoom : this.state.zoom
  3008. const nextCenterTileX = typeof patch.centerTileX === 'number' ? patch.centerTileX : this.state.centerTileX
  3009. const nextCenterTileY = typeof patch.centerTileY === 'number' ? patch.centerTileY : this.state.centerTileY
  3010. const nextStageWidth = typeof patch.stageWidth === 'number' ? patch.stageWidth : this.state.stageWidth
  3011. const nextStageHeight = typeof patch.stageHeight === 'number' ? patch.stageHeight : this.state.stageHeight
  3012. const tileSizePx = getTileSizePx({
  3013. centerWorldX: nextCenterTileX,
  3014. centerWorldY: nextCenterTileY,
  3015. viewportWidth: nextStageWidth,
  3016. viewportHeight: nextStageHeight,
  3017. visibleColumns: DESIRED_VISIBLE_COLUMNS,
  3018. })
  3019. this.setState({
  3020. ...patch,
  3021. tileSizePx,
  3022. centerText: buildCenterText(nextZoom, nextCenterTileX, nextCenterTileY),
  3023. statusText,
  3024. }, immediateUi)
  3025. this.syncRenderer()
  3026. this.compassController.start()
  3027. if (afterUpdate) {
  3028. afterUpdate()
  3029. }
  3030. }
  3031. buildScene() {
  3032. const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
  3033. const readyControlSequences = this.resolveReadyControlSequences()
  3034. return {
  3035. tileSource: this.state.tileSource,
  3036. osmTileSource: OSM_TILE_SOURCE,
  3037. zoom: this.state.zoom,
  3038. centerTileX: this.state.centerTileX,
  3039. centerTileY: this.state.centerTileY,
  3040. exactCenterWorldX: exactCenter.x,
  3041. exactCenterWorldY: exactCenter.y,
  3042. tileBoundsByZoom: this.tileBoundsByZoom,
  3043. viewportWidth: this.state.stageWidth,
  3044. viewportHeight: this.state.stageHeight,
  3045. visibleColumns: DESIRED_VISIBLE_COLUMNS,
  3046. overdraw: OVERDRAW,
  3047. translateX: this.state.tileTranslateX,
  3048. translateY: this.state.tileTranslateY,
  3049. rotationRad: this.getRotationRad(this.state.rotationDeg),
  3050. animationLevel: this.state.animationLevel,
  3051. previewScale: this.previewScale || 1,
  3052. previewOriginX: this.previewOriginX || this.state.stageWidth / 2,
  3053. previewOriginY: this.previewOriginY || this.state.stageHeight / 2,
  3054. track: this.currentGpsTrack,
  3055. gpsPoint: this.currentGpsPoint,
  3056. gpsCalibration: GPS_MAP_CALIBRATION,
  3057. gpsCalibrationOrigin: worldTileToLonLat({ x: this.defaultCenterTileX, y: this.defaultCenterTileY }, this.defaultZoom),
  3058. course: this.courseOverlayVisible ? this.courseData : null,
  3059. cpRadiusMeters: this.cpRadiusMeters,
  3060. controlVisualMode: this.gamePresentation.map.controlVisualMode,
  3061. showCourseLegs: this.gamePresentation.map.showCourseLegs,
  3062. guidanceLegAnimationEnabled: this.gamePresentation.map.guidanceLegAnimationEnabled,
  3063. focusableControlIds: this.gamePresentation.map.focusableControlIds,
  3064. focusedControlId: this.gamePresentation.map.focusedControlId,
  3065. focusedControlSequences: this.gamePresentation.map.focusedControlSequences,
  3066. activeControlSequences: this.gamePresentation.map.activeControlSequences,
  3067. readyControlSequences,
  3068. activeStart: this.gamePresentation.map.activeStart,
  3069. completedStart: this.gamePresentation.map.completedStart,
  3070. activeFinish: this.gamePresentation.map.activeFinish,
  3071. focusedFinish: this.gamePresentation.map.focusedFinish,
  3072. completedFinish: this.gamePresentation.map.completedFinish,
  3073. revealFullCourse: this.gamePresentation.map.revealFullCourse,
  3074. activeLegIndices: this.gamePresentation.map.activeLegIndices,
  3075. completedLegIndices: this.gamePresentation.map.completedLegIndices,
  3076. completedControlSequences: this.gamePresentation.map.completedControlSequences,
  3077. skippedControlIds: this.gamePresentation.map.skippedControlIds,
  3078. skippedControlSequences: this.gamePresentation.map.skippedControlSequences,
  3079. osmReferenceEnabled: this.state.osmReferenceEnabled,
  3080. overlayOpacity: MAP_OVERLAY_OPACITY,
  3081. }
  3082. }
  3083. resolveReadyControlSequences(): number[] {
  3084. const punchableControlId = this.gamePresentation.hud.punchableControlId
  3085. const definition = this.gameRuntime.definition
  3086. if (!punchableControlId || !definition) {
  3087. return []
  3088. }
  3089. const control = definition.controls.find((item) => item.id === punchableControlId)
  3090. if (!control || control.sequence === null) {
  3091. return []
  3092. }
  3093. return [control.sequence]
  3094. }
  3095. syncRenderer(): void {
  3096. if (!this.mounted || !this.state.stageWidth || !this.state.stageHeight) {
  3097. return
  3098. }
  3099. this.renderer.updateScene(this.buildScene())
  3100. }
  3101. getCameraState(rotationDeg = this.state.rotationDeg): CameraState {
  3102. return {
  3103. centerWorldX: this.state.centerTileX + 0.5,
  3104. centerWorldY: this.state.centerTileY + 0.5,
  3105. viewportWidth: this.state.stageWidth,
  3106. viewportHeight: this.state.stageHeight,
  3107. visibleColumns: DESIRED_VISIBLE_COLUMNS,
  3108. translateX: this.state.tileTranslateX,
  3109. translateY: this.state.tileTranslateY,
  3110. rotationRad: this.getRotationRad(rotationDeg),
  3111. }
  3112. }
  3113. getRotationRad(rotationDeg = this.state.rotationDeg): number {
  3114. return normalizeRotationDeg(rotationDeg) * Math.PI / 180
  3115. }
  3116. getBaseCamera(centerTileX = this.state.centerTileX, centerTileY = this.state.centerTileY, rotationDeg = this.state.rotationDeg): CameraState {
  3117. return {
  3118. centerWorldX: centerTileX + 0.5,
  3119. centerWorldY: centerTileY + 0.5,
  3120. viewportWidth: this.state.stageWidth,
  3121. viewportHeight: this.state.stageHeight,
  3122. visibleColumns: DESIRED_VISIBLE_COLUMNS,
  3123. rotationRad: this.getRotationRad(rotationDeg),
  3124. }
  3125. }
  3126. getWorldOffsetFromScreen(stageX: number, stageY: number, rotationDeg = this.state.rotationDeg): { x: number; y: number } {
  3127. const baseCamera = {
  3128. centerWorldX: 0,
  3129. centerWorldY: 0,
  3130. viewportWidth: this.state.stageWidth,
  3131. viewportHeight: this.state.stageHeight,
  3132. visibleColumns: DESIRED_VISIBLE_COLUMNS,
  3133. rotationRad: this.getRotationRad(rotationDeg),
  3134. }
  3135. return screenToWorld(baseCamera, { x: stageX, y: stageY }, false)
  3136. }
  3137. getExactCenterFromTranslate(translateX: number, translateY: number): { x: number; y: number } {
  3138. if (!this.state.stageWidth || !this.state.stageHeight) {
  3139. return {
  3140. x: this.state.centerTileX + 0.5,
  3141. y: this.state.centerTileY + 0.5,
  3142. }
  3143. }
  3144. const screenCenterX = this.state.stageWidth / 2
  3145. const screenCenterY = this.state.stageHeight / 2
  3146. return screenToWorld(this.getBaseCamera(), {
  3147. x: screenCenterX - translateX,
  3148. y: screenCenterY - translateY,
  3149. }, false)
  3150. }
  3151. resolveViewportForExactCenter(centerWorldX: number, centerWorldY: number, rotationDeg = this.state.rotationDeg): {
  3152. centerTileX: number
  3153. centerTileY: number
  3154. tileTranslateX: number
  3155. tileTranslateY: number
  3156. } {
  3157. const nextCenterTileX = Math.floor(centerWorldX)
  3158. const nextCenterTileY = Math.floor(centerWorldY)
  3159. if (!this.state.stageWidth || !this.state.stageHeight) {
  3160. return {
  3161. centerTileX: nextCenterTileX,
  3162. centerTileY: nextCenterTileY,
  3163. tileTranslateX: 0,
  3164. tileTranslateY: 0,
  3165. }
  3166. }
  3167. const roundedCamera = this.getBaseCamera(nextCenterTileX, nextCenterTileY, rotationDeg)
  3168. const projectedCenter = worldToScreen(roundedCamera, { x: centerWorldX, y: centerWorldY }, false)
  3169. return {
  3170. centerTileX: nextCenterTileX,
  3171. centerTileY: nextCenterTileY,
  3172. tileTranslateX: this.state.stageWidth / 2 - projectedCenter.x,
  3173. tileTranslateY: this.state.stageHeight / 2 - projectedCenter.y,
  3174. }
  3175. }
  3176. setPreviewState(scale: number, originX: number, originY: number): void {
  3177. this.previewScale = scale
  3178. this.previewOriginX = originX
  3179. this.previewOriginY = originY
  3180. this.setState({
  3181. previewScale: scale,
  3182. }, true)
  3183. }
  3184. resetPreviewState(): void {
  3185. this.setPreviewState(1, this.state.stageWidth / 2, this.state.stageHeight / 2)
  3186. }
  3187. resetPinchState(): void {
  3188. this.pinchStartDistance = 0
  3189. this.pinchStartScale = 1
  3190. this.pinchStartAngle = 0
  3191. this.pinchStartRotationDeg = this.state.rotationDeg
  3192. this.pinchAnchorWorldX = 0
  3193. this.pinchAnchorWorldY = 0
  3194. }
  3195. clearPreviewResetTimer(): void {
  3196. if (this.previewResetTimer) {
  3197. clearTimeout(this.previewResetTimer)
  3198. this.previewResetTimer = 0
  3199. }
  3200. }
  3201. clearInertiaTimer(): void {
  3202. if (this.inertiaTimer) {
  3203. clearTimeout(this.inertiaTimer)
  3204. this.inertiaTimer = 0
  3205. }
  3206. }
  3207. clearViewSyncTimer(): void {
  3208. if (this.viewSyncTimer) {
  3209. clearTimeout(this.viewSyncTimer)
  3210. this.viewSyncTimer = 0
  3211. }
  3212. }
  3213. clearAutoRotateTimer(): void {
  3214. if (this.autoRotateTimer) {
  3215. clearTimeout(this.autoRotateTimer)
  3216. this.autoRotateTimer = 0
  3217. }
  3218. }
  3219. clearCompassNeedleTimer(): void {
  3220. if (this.compassNeedleTimer) {
  3221. clearTimeout(this.compassNeedleTimer)
  3222. this.compassNeedleTimer = 0
  3223. }
  3224. }
  3225. clearCompassBootstrapRetryTimer(): void {
  3226. if (this.compassBootstrapRetryTimer) {
  3227. clearTimeout(this.compassBootstrapRetryTimer)
  3228. this.compassBootstrapRetryTimer = 0
  3229. }
  3230. }
  3231. scheduleCompassBootstrapRetry(): void {
  3232. this.clearCompassBootstrapRetryTimer()
  3233. if (!this.mounted) {
  3234. return
  3235. }
  3236. this.compassBootstrapRetryTimer = setTimeout(() => {
  3237. this.compassBootstrapRetryTimer = 0
  3238. if (!this.mounted || this.lastCompassSampleAt > 0) {
  3239. return
  3240. }
  3241. this.compassController.stop()
  3242. this.compassController.start()
  3243. }, COMPASS_BOOTSTRAP_RETRY_DELAY_MS) as unknown as number
  3244. }
  3245. syncCompassDisplayState(): void {
  3246. this.setState({
  3247. compassNeedleDeg: formatCompassNeedleDegForMode(this.northReferenceMode, this.compassDisplayHeadingDeg),
  3248. sensorHeadingText: formatHeadingText(this.compassDisplayHeadingDeg),
  3249. compassDeclinationText: formatCompassDeclinationText(this.northReferenceMode),
  3250. ...(this.diagnosticUiEnabled
  3251. ? {
  3252. ...this.getTelemetrySensorViewPatch(),
  3253. northReferenceButtonText: formatNorthReferenceButtonText(this.northReferenceMode),
  3254. autoRotateSourceText: this.getAutoRotateSourceText(),
  3255. northReferenceText: formatNorthReferenceText(this.northReferenceMode),
  3256. }
  3257. : {}),
  3258. })
  3259. }
  3260. scheduleCompassNeedleFollow(): void {
  3261. if (
  3262. this.compassNeedleTimer
  3263. || this.targetCompassDisplayHeadingDeg === null
  3264. || this.compassDisplayHeadingDeg === null
  3265. ) {
  3266. return
  3267. }
  3268. const step = () => {
  3269. this.compassNeedleTimer = 0
  3270. if (
  3271. this.targetCompassDisplayHeadingDeg === null
  3272. || this.compassDisplayHeadingDeg === null
  3273. ) {
  3274. return
  3275. }
  3276. const deltaDeg = normalizeAngleDeltaDeg(
  3277. this.targetCompassDisplayHeadingDeg - this.compassDisplayHeadingDeg,
  3278. )
  3279. const absDeltaDeg = Math.abs(deltaDeg)
  3280. if (absDeltaDeg <= COMPASS_NEEDLE_SNAP_DEG) {
  3281. if (absDeltaDeg > 0.001) {
  3282. this.compassDisplayHeadingDeg = this.targetCompassDisplayHeadingDeg
  3283. this.syncCompassDisplayState()
  3284. }
  3285. return
  3286. }
  3287. this.compassDisplayHeadingDeg = interpolateAngleDeg(
  3288. this.compassDisplayHeadingDeg,
  3289. this.targetCompassDisplayHeadingDeg,
  3290. getCompassNeedleSmoothingFactor(
  3291. this.compassDisplayHeadingDeg,
  3292. this.targetCompassDisplayHeadingDeg,
  3293. this.compassTuningProfile,
  3294. ),
  3295. )
  3296. this.syncCompassDisplayState()
  3297. this.scheduleCompassNeedleFollow()
  3298. }
  3299. this.compassNeedleTimer = setTimeout(step, COMPASS_NEEDLE_FRAME_MS) as unknown as number
  3300. }
  3301. pickViewPatch(patch: Partial<MapEngineViewState>): Partial<MapEngineViewState> {
  3302. const viewPatch = {} as Partial<MapEngineViewState>
  3303. for (const key of VIEW_SYNC_KEYS) {
  3304. if (Object.prototype.hasOwnProperty.call(patch, key)) {
  3305. ;(viewPatch as any)[key] = patch[key]
  3306. }
  3307. }
  3308. return viewPatch
  3309. }
  3310. flushViewPatch(): void {
  3311. if (!Object.keys(this.pendingViewPatch).length) {
  3312. return
  3313. }
  3314. const patch = this.pendingViewPatch
  3315. const shouldDeferForInteraction = this.gestureMode !== 'idle' || !!this.inertiaTimer || !!this.previewResetTimer
  3316. const nextPendingPatch = {} as Partial<MapEngineViewState>
  3317. const outputPatch = {} as Partial<MapEngineViewState>
  3318. for (const [key, value] of Object.entries(patch) as Array<[keyof MapEngineViewState, MapEngineViewState[keyof MapEngineViewState]]>) {
  3319. if (shouldDeferForInteraction && INTERACTION_DEFERRED_VIEW_KEYS.has(key)) {
  3320. ;(nextPendingPatch as Record<string, unknown>)[key] = value
  3321. continue
  3322. }
  3323. ;(outputPatch as Record<string, unknown>)[key] = value
  3324. }
  3325. this.pendingViewPatch = nextPendingPatch
  3326. if (Object.keys(this.pendingViewPatch).length && !this.viewSyncTimer) {
  3327. this.viewSyncTimer = setTimeout(() => {
  3328. this.viewSyncTimer = 0
  3329. this.flushViewPatch()
  3330. }, UI_SYNC_INTERVAL_MS) as unknown as number
  3331. }
  3332. if (!Object.keys(outputPatch).length) {
  3333. return
  3334. }
  3335. this.onData(outputPatch)
  3336. }
  3337. getTouchDistance(touches: TouchPoint[]): number {
  3338. if (touches.length < 2) {
  3339. return 0
  3340. }
  3341. const first = touches[0]
  3342. const second = touches[1]
  3343. const deltaX = first.pageX - second.pageX
  3344. const deltaY = first.pageY - second.pageY
  3345. return Math.sqrt(deltaX * deltaX + deltaY * deltaY)
  3346. }
  3347. getTouchAngle(touches: TouchPoint[]): number {
  3348. if (touches.length < 2) {
  3349. return 0
  3350. }
  3351. const first = touches[0]
  3352. const second = touches[1]
  3353. return Math.atan2(second.pageY - first.pageY, second.pageX - first.pageX)
  3354. }
  3355. getStagePoint(touches: TouchPoint[]): { x: number; y: number } {
  3356. if (!touches.length) {
  3357. return {
  3358. x: this.state.stageWidth / 2,
  3359. y: this.state.stageHeight / 2,
  3360. }
  3361. }
  3362. let pageX = 0
  3363. let pageY = 0
  3364. for (const touch of touches) {
  3365. pageX += touch.pageX
  3366. pageY += touch.pageY
  3367. }
  3368. return {
  3369. x: pageX / touches.length - this.state.stageLeft,
  3370. y: pageY / touches.length - this.state.stageTop,
  3371. }
  3372. }
  3373. animatePreviewToRest(): void {
  3374. this.clearPreviewResetTimer()
  3375. const startScale = this.previewScale || 1
  3376. const originX = this.previewOriginX || this.state.stageWidth / 2
  3377. const originY = this.previewOriginY || this.state.stageHeight / 2
  3378. if (Math.abs(startScale - 1) < 0.01) {
  3379. this.resetPreviewState()
  3380. this.syncRenderer()
  3381. this.compassController.start()
  3382. this.scheduleAutoRotate()
  3383. return
  3384. }
  3385. const startAt = Date.now()
  3386. const step = () => {
  3387. const progress = Math.min(1, (Date.now() - startAt) / PREVIEW_RESET_DURATION_MS)
  3388. const eased = 1 - Math.pow(1 - progress, 3)
  3389. const nextScale = startScale + (1 - startScale) * eased
  3390. this.setPreviewState(nextScale, originX, originY)
  3391. this.syncRenderer()
  3392. this.compassController.start()
  3393. if (progress >= 1) {
  3394. this.resetPreviewState()
  3395. this.syncRenderer()
  3396. this.compassController.start()
  3397. this.previewResetTimer = 0
  3398. this.scheduleAutoRotate()
  3399. return
  3400. }
  3401. this.previewResetTimer = setTimeout(step, INERTIA_FRAME_MS) as unknown as number
  3402. }
  3403. step()
  3404. }
  3405. normalizeTranslate(translateX: number, translateY: number, statusText: string): void {
  3406. if (!this.state.stageWidth) {
  3407. this.setState({
  3408. tileTranslateX: translateX,
  3409. tileTranslateY: translateY,
  3410. })
  3411. this.syncRenderer()
  3412. this.compassController.start()
  3413. return
  3414. }
  3415. const exactCenter = this.getExactCenterFromTranslate(translateX, translateY)
  3416. const resolvedViewport = this.resolveViewportForExactCenter(exactCenter.x, exactCenter.y)
  3417. const centerChanged = resolvedViewport.centerTileX !== this.state.centerTileX || resolvedViewport.centerTileY !== this.state.centerTileY
  3418. if (centerChanged) {
  3419. this.commitViewport(resolvedViewport, statusText)
  3420. return
  3421. }
  3422. this.setState({
  3423. tileTranslateX: resolvedViewport.tileTranslateX,
  3424. tileTranslateY: resolvedViewport.tileTranslateY,
  3425. })
  3426. this.syncRenderer()
  3427. this.compassController.start()
  3428. }
  3429. zoomAroundPoint(zoomDelta: number, stageX: number, stageY: number, residualScale: number): void {
  3430. const nextZoom = clamp(this.state.zoom + zoomDelta, this.minZoom, this.maxZoom)
  3431. const appliedDelta = nextZoom - this.state.zoom
  3432. if (!appliedDelta) {
  3433. this.animatePreviewToRest()
  3434. return
  3435. }
  3436. if (this.gpsLockEnabled && this.currentGpsPoint) {
  3437. const nextGpsWorldPoint = lonLatToWorldTile(this.currentGpsPoint, nextZoom)
  3438. const resolvedViewport = this.resolveViewportForExactCenter(nextGpsWorldPoint.x, nextGpsWorldPoint.y)
  3439. this.commitViewport(
  3440. {
  3441. zoom: nextZoom,
  3442. ...resolvedViewport,
  3443. },
  3444. `缩放级别调整到 ${nextZoom}`,
  3445. true,
  3446. () => {
  3447. this.setPreviewState(residualScale, this.state.stageWidth / 2, this.state.stageHeight / 2)
  3448. this.syncRenderer()
  3449. this.compassController.start()
  3450. this.animatePreviewToRest()
  3451. },
  3452. )
  3453. return
  3454. }
  3455. if (!this.state.stageWidth || !this.state.stageHeight) {
  3456. this.commitViewport(
  3457. {
  3458. zoom: nextZoom,
  3459. centerTileX: appliedDelta > 0 ? this.state.centerTileX * 2 : Math.floor(this.state.centerTileX / 2),
  3460. centerTileY: appliedDelta > 0 ? this.state.centerTileY * 2 : Math.floor(this.state.centerTileY / 2),
  3461. tileTranslateX: 0,
  3462. tileTranslateY: 0,
  3463. },
  3464. `缩放级别调整到 ${nextZoom}`,
  3465. true,
  3466. () => {
  3467. this.setPreviewState(residualScale, stageX, stageY)
  3468. this.syncRenderer()
  3469. this.compassController.start()
  3470. this.animatePreviewToRest()
  3471. },
  3472. )
  3473. return
  3474. }
  3475. const camera = this.getCameraState()
  3476. const world = screenToWorld(camera, { x: stageX, y: stageY }, true)
  3477. const zoomFactor = Math.pow(2, appliedDelta)
  3478. const nextWorldX = world.x * zoomFactor
  3479. const nextWorldY = world.y * zoomFactor
  3480. const anchorOffset = this.getWorldOffsetFromScreen(stageX, stageY)
  3481. const exactCenterX = nextWorldX - anchorOffset.x
  3482. const exactCenterY = nextWorldY - anchorOffset.y
  3483. const resolvedViewport = this.resolveViewportForExactCenter(exactCenterX, exactCenterY)
  3484. this.commitViewport(
  3485. {
  3486. zoom: nextZoom,
  3487. ...resolvedViewport,
  3488. },
  3489. `缩放级别调整到 ${nextZoom}`,
  3490. true,
  3491. () => {
  3492. this.setPreviewState(residualScale, stageX, stageY)
  3493. this.syncRenderer()
  3494. this.compassController.start()
  3495. this.animatePreviewToRest()
  3496. },
  3497. )
  3498. }
  3499. startInertia(): void {
  3500. this.clearInertiaTimer()
  3501. const step = () => {
  3502. this.panVelocityX *= INERTIA_DECAY
  3503. this.panVelocityY *= INERTIA_DECAY
  3504. if (Math.abs(this.panVelocityX) < INERTIA_MIN_SPEED && Math.abs(this.panVelocityY) < INERTIA_MIN_SPEED) {
  3505. this.setState({
  3506. statusText: `惯性滑动结束 (${this.buildVersion})`,
  3507. })
  3508. this.renderer.setAnimationPaused(false)
  3509. this.inertiaTimer = 0
  3510. this.scheduleAutoRotate()
  3511. return
  3512. }
  3513. this.normalizeTranslate(
  3514. this.state.tileTranslateX + this.panVelocityX * INERTIA_FRAME_MS,
  3515. this.state.tileTranslateY + this.panVelocityY * INERTIA_FRAME_MS,
  3516. `惯性滑动中 (${this.buildVersion})`,
  3517. )
  3518. this.inertiaTimer = setTimeout(step, INERTIA_FRAME_MS) as unknown as number
  3519. }
  3520. this.inertiaTimer = setTimeout(step, INERTIA_FRAME_MS) as unknown as number
  3521. }
  3522. }