mapEngine.ts 129 KB

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