mapEngine.ts 93 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895
  1. import { getTileSizePx, screenToWorld, worldToScreen, type CameraState } from '../camera/camera'
  2. import { CompassHeadingController } from '../sensor/compassHeadingController'
  3. import { type HeartRateDiscoveredDevice } from '../sensor/heartRateController'
  4. import { HeartRateInputController } from '../sensor/heartRateInputController'
  5. import { LocationController } from '../sensor/locationController'
  6. import { WebGLMapRenderer } from '../renderer/webglMapRenderer'
  7. import { type MapRendererStats } from '../renderer/mapRenderer'
  8. import { lonLatToWorldTile, worldTileToLonLat, type LonLatPoint, type MapCalibration } from '../../utils/projection'
  9. import { type OrienteeringCourseData } from '../../utils/orienteeringCourse'
  10. import { isTileWithinBounds, type RemoteMapConfig, type TileZoomBounds } from '../../utils/remoteMapConfig'
  11. import { GameRuntime } from '../../game/core/gameRuntime'
  12. import { type GameEffect } from '../../game/core/gameResult'
  13. import { buildGameDefinitionFromCourse } from '../../game/content/courseToGameDefinition'
  14. import { FeedbackDirector } from '../../game/feedback/feedbackDirector'
  15. import { EMPTY_GAME_PRESENTATION_STATE, type GamePresentationState } from '../../game/presentation/presentationState'
  16. import { TelemetryRuntime } from '../../game/telemetry/telemetryRuntime'
  17. import { getHeartRateToneSampleBpm, type HeartRateTone } from '../../game/telemetry/telemetryConfig'
  18. const RENDER_MODE = 'Single WebGL Pipeline'
  19. const PROJECTION_MODE = 'WGS84 -> WorldTile -> Camera -> Screen'
  20. const MAP_NORTH_OFFSET_DEG = 0
  21. let MAGNETIC_DECLINATION_DEG = -6.91
  22. let MAGNETIC_DECLINATION_TEXT = '6.91掳 W'
  23. const MIN_ZOOM = 15
  24. const MAX_ZOOM = 20
  25. const DEFAULT_ZOOM = 17
  26. const DESIRED_VISIBLE_COLUMNS = 3
  27. const OVERDRAW = 1
  28. const DEFAULT_TOP_LEFT_TILE_X = 108132
  29. const DEFAULT_TOP_LEFT_TILE_Y = 51199
  30. const DEFAULT_CENTER_TILE_X = DEFAULT_TOP_LEFT_TILE_X + 1
  31. const DEFAULT_CENTER_TILE_Y = DEFAULT_TOP_LEFT_TILE_Y + 1
  32. const TILE_SOURCE = 'https://oss-mbh5.colormaprun.com/wxMap/lcx/{z}/{x}/{y}.png'
  33. const OSM_TILE_SOURCE = 'https://tiles.mymarsgo.xyz/{z}/{x}/{y}.png'
  34. const MAP_OVERLAY_OPACITY = 0.72
  35. const GPS_MAP_CALIBRATION: MapCalibration = {
  36. offsetEastMeters: 0,
  37. offsetNorthMeters: 0,
  38. rotationDeg: 0,
  39. scale: 1,
  40. }
  41. const MIN_PREVIEW_SCALE = 0.55
  42. const MAX_PREVIEW_SCALE = 1.85
  43. const INERTIA_FRAME_MS = 16
  44. const INERTIA_DECAY = 0.92
  45. const INERTIA_MIN_SPEED = 0.02
  46. const PREVIEW_RESET_DURATION_MS = 140
  47. const UI_SYNC_INTERVAL_MS = 80
  48. const ROTATE_STEP_DEG = 15
  49. const AUTO_ROTATE_FRAME_MS = 8
  50. const AUTO_ROTATE_EASE = 0.34
  51. const AUTO_ROTATE_SNAP_DEG = 0.1
  52. const AUTO_ROTATE_DEADZONE_DEG = 4
  53. const AUTO_ROTATE_MAX_STEP_DEG = 0.75
  54. const AUTO_ROTATE_HEADING_SMOOTHING = 0.32
  55. const COMPASS_NEEDLE_SMOOTHING = 0.12
  56. const GPS_TRACK_MAX_POINTS = 200
  57. const GPS_TRACK_MIN_STEP_METERS = 3
  58. const MAP_TAP_MOVE_THRESHOLD_PX = 14
  59. const MAP_TAP_DURATION_MS = 280
  60. type TouchPoint = WechatMiniprogram.TouchDetail
  61. type GestureMode = 'idle' | 'pan' | 'pinch'
  62. type RotationMode = 'manual' | 'auto'
  63. type OrientationMode = 'manual' | 'north-up' | 'heading-up'
  64. type AutoRotateSourceMode = 'sensor' | 'course' | 'fusion'
  65. type NorthReferenceMode = 'magnetic' | 'true'
  66. const DEFAULT_NORTH_REFERENCE_MODE: NorthReferenceMode = 'magnetic'
  67. export interface MapEngineStageRect {
  68. width: number
  69. height: number
  70. left: number
  71. top: number
  72. }
  73. export interface MapEngineViewState {
  74. buildVersion: string
  75. renderMode: string
  76. projectionMode: string
  77. mapReady: boolean
  78. mapReadyText: string
  79. mapName: string
  80. configStatusText: string
  81. zoom: number
  82. rotationDeg: number
  83. rotationText: string
  84. rotationMode: RotationMode
  85. rotationModeText: string
  86. rotationToggleText: string
  87. orientationMode: OrientationMode
  88. orientationModeText: string
  89. sensorHeadingText: string
  90. compassDeclinationText: string
  91. northReferenceButtonText: string
  92. autoRotateSourceText: string
  93. autoRotateCalibrationText: string
  94. northReferenceText: string
  95. compassNeedleDeg: number
  96. centerTileX: number
  97. centerTileY: number
  98. centerText: string
  99. tileSource: string
  100. visibleColumnCount: number
  101. visibleTileCount: number
  102. readyTileCount: number
  103. memoryTileCount: number
  104. diskTileCount: number
  105. memoryHitCount: number
  106. diskHitCount: number
  107. networkFetchCount: number
  108. cacheHitRateText: string
  109. tileTranslateX: number
  110. tileTranslateY: number
  111. tileSizePx: number
  112. stageWidth: number
  113. stageHeight: number
  114. stageLeft: number
  115. stageTop: number
  116. statusText: string
  117. gpsTracking: boolean
  118. gpsTrackingText: string
  119. locationSourceMode: 'real' | 'mock'
  120. locationSourceText: string
  121. mockBridgeConnected: boolean
  122. mockBridgeStatusText: string
  123. mockBridgeUrlText: string
  124. mockCoordText: string
  125. mockSpeedText: string
  126. gpsCoordText: string
  127. heartRateSourceMode: 'real' | 'mock'
  128. heartRateSourceText: string
  129. heartRateConnected: boolean
  130. heartRateStatusText: string
  131. heartRateDeviceText: string
  132. heartRateScanText: string
  133. heartRateDiscoveredDevices: Array<{
  134. deviceId: string
  135. name: string
  136. rssiText: string
  137. preferred: boolean
  138. connected: boolean
  139. }>
  140. mockHeartRateBridgeConnected: boolean
  141. mockHeartRateBridgeStatusText: string
  142. mockHeartRateBridgeUrlText: string
  143. mockHeartRateText: string
  144. gameSessionStatus: 'idle' | 'running' | 'finished' | 'failed'
  145. gameModeText: string
  146. panelTimerText: string
  147. panelMileageText: string
  148. panelActionTagText: string
  149. panelDistanceTagText: string
  150. panelDistanceValueText: string
  151. panelDistanceUnitText: string
  152. panelProgressText: string
  153. panelSpeedValueText: string
  154. panelTelemetryTone: 'blue' | 'purple' | 'green' | 'yellow' | 'orange' | 'red'
  155. panelHeartRateZoneNameText: string
  156. panelHeartRateZoneRangeText: string
  157. panelHeartRateValueText: string
  158. panelHeartRateUnitText: string
  159. panelCaloriesValueText: string
  160. panelCaloriesUnitText: string
  161. panelAverageSpeedValueText: string
  162. panelAverageSpeedUnitText: string
  163. panelAccuracyValueText: string
  164. panelAccuracyUnitText: string
  165. punchButtonText: string
  166. punchButtonEnabled: boolean
  167. punchHintText: string
  168. punchFeedbackVisible: boolean
  169. punchFeedbackText: string
  170. punchFeedbackTone: 'neutral' | 'success' | 'warning'
  171. contentCardVisible: boolean
  172. contentCardTitle: string
  173. contentCardBody: string
  174. punchButtonFxClass: string
  175. punchFeedbackFxClass: string
  176. contentCardFxClass: string
  177. mapPulseVisible: boolean
  178. mapPulseLeftPx: number
  179. mapPulseTopPx: number
  180. mapPulseFxClass: string
  181. stageFxVisible: boolean
  182. stageFxClass: string
  183. osmReferenceEnabled: boolean
  184. osmReferenceText: string
  185. }
  186. export interface MapEngineCallbacks {
  187. onData: (patch: Partial<MapEngineViewState>) => void
  188. }
  189. const VIEW_SYNC_KEYS: Array<keyof MapEngineViewState> = [
  190. 'buildVersion',
  191. 'renderMode',
  192. 'projectionMode',
  193. 'mapReady',
  194. 'mapReadyText',
  195. 'mapName',
  196. 'configStatusText',
  197. 'zoom',
  198. 'rotationDeg',
  199. 'rotationText',
  200. 'rotationMode',
  201. 'rotationModeText',
  202. 'rotationToggleText',
  203. 'orientationMode',
  204. 'orientationModeText',
  205. 'sensorHeadingText',
  206. 'compassDeclinationText',
  207. 'northReferenceButtonText',
  208. 'autoRotateSourceText',
  209. 'autoRotateCalibrationText',
  210. 'northReferenceText',
  211. 'compassNeedleDeg',
  212. 'centerText',
  213. 'tileSource',
  214. 'visibleTileCount',
  215. 'readyTileCount',
  216. 'memoryTileCount',
  217. 'diskTileCount',
  218. 'memoryHitCount',
  219. 'diskHitCount',
  220. 'networkFetchCount',
  221. 'cacheHitRateText',
  222. 'tileSizePx',
  223. 'statusText',
  224. 'gpsTracking',
  225. 'gpsTrackingText',
  226. 'locationSourceMode',
  227. 'locationSourceText',
  228. 'mockBridgeConnected',
  229. 'mockBridgeStatusText',
  230. 'mockBridgeUrlText',
  231. 'mockCoordText',
  232. 'mockSpeedText',
  233. 'gpsCoordText',
  234. 'heartRateSourceMode',
  235. 'heartRateSourceText',
  236. 'heartRateConnected',
  237. 'heartRateStatusText',
  238. 'heartRateDeviceText',
  239. 'heartRateScanText',
  240. 'heartRateDiscoveredDevices',
  241. 'mockHeartRateBridgeConnected',
  242. 'mockHeartRateBridgeStatusText',
  243. 'mockHeartRateBridgeUrlText',
  244. 'mockHeartRateText',
  245. 'gameSessionStatus',
  246. 'gameModeText',
  247. 'panelTimerText',
  248. 'panelMileageText',
  249. 'panelActionTagText',
  250. 'panelDistanceTagText',
  251. 'panelDistanceValueText',
  252. 'panelDistanceUnitText',
  253. 'panelProgressText',
  254. 'panelSpeedValueText',
  255. 'panelTelemetryTone',
  256. 'panelHeartRateZoneNameText',
  257. 'panelHeartRateZoneRangeText',
  258. 'panelHeartRateValueText',
  259. 'panelHeartRateUnitText',
  260. 'panelCaloriesValueText',
  261. 'panelCaloriesUnitText',
  262. 'panelAverageSpeedValueText',
  263. 'panelAverageSpeedUnitText',
  264. 'panelAccuracyValueText',
  265. 'panelAccuracyUnitText',
  266. 'punchButtonText',
  267. 'punchButtonEnabled',
  268. 'punchHintText',
  269. 'punchFeedbackVisible',
  270. 'punchFeedbackText',
  271. 'punchFeedbackTone',
  272. 'contentCardVisible',
  273. 'contentCardTitle',
  274. 'contentCardBody',
  275. 'punchButtonFxClass',
  276. 'punchFeedbackFxClass',
  277. 'contentCardFxClass',
  278. 'mapPulseVisible',
  279. 'mapPulseLeftPx',
  280. 'mapPulseTopPx',
  281. 'mapPulseFxClass',
  282. 'stageFxVisible',
  283. 'stageFxClass',
  284. 'osmReferenceEnabled',
  285. 'osmReferenceText',
  286. ]
  287. function buildCenterText(zoom: number, x: number, y: number): string {
  288. return `z${zoom} / x${x} / y${y}`
  289. }
  290. function clamp(value: number, min: number, max: number): number {
  291. return Math.max(min, Math.min(max, value))
  292. }
  293. function normalizeRotationDeg(rotationDeg: number): number {
  294. const normalized = rotationDeg % 360
  295. return normalized < 0 ? normalized + 360 : normalized
  296. }
  297. function normalizeAngleDeltaRad(angleDeltaRad: number): number {
  298. let normalized = angleDeltaRad
  299. while (normalized > Math.PI) {
  300. normalized -= Math.PI * 2
  301. }
  302. while (normalized < -Math.PI) {
  303. normalized += Math.PI * 2
  304. }
  305. return normalized
  306. }
  307. function normalizeAngleDeltaDeg(angleDeltaDeg: number): number {
  308. let normalized = angleDeltaDeg
  309. while (normalized > 180) {
  310. normalized -= 360
  311. }
  312. while (normalized < -180) {
  313. normalized += 360
  314. }
  315. return normalized
  316. }
  317. function interpolateAngleDeg(currentDeg: number, targetDeg: number, factor: number): number {
  318. return normalizeRotationDeg(currentDeg + normalizeAngleDeltaDeg(targetDeg - currentDeg) * factor)
  319. }
  320. function formatRotationText(rotationDeg: number): string {
  321. return `${Math.round(normalizeRotationDeg(rotationDeg))}deg`
  322. }
  323. function formatHeadingText(headingDeg: number | null): string {
  324. if (headingDeg === null) {
  325. return '--'
  326. }
  327. return `${Math.round(normalizeRotationDeg(headingDeg))}掳`
  328. }
  329. function formatOrientationModeText(mode: OrientationMode): string {
  330. if (mode === 'north-up') {
  331. return 'North Up'
  332. }
  333. if (mode === 'heading-up') {
  334. return 'Heading Up'
  335. }
  336. return 'Manual Gesture'
  337. }
  338. function formatRotationModeText(mode: OrientationMode): string {
  339. return formatOrientationModeText(mode)
  340. }
  341. function formatRotationToggleText(mode: OrientationMode): string {
  342. if (mode === 'manual') {
  343. return '切到北朝上'
  344. }
  345. if (mode === 'north-up') {
  346. return '切到朝向朝上'
  347. }
  348. return '切到手动旋转'
  349. }
  350. function formatAutoRotateSourceText(mode: AutoRotateSourceMode, hasCourseHeading: boolean): string {
  351. if (mode === 'sensor') {
  352. return 'Sensor Only'
  353. }
  354. if (mode === 'course') {
  355. return hasCourseHeading ? 'Course Only' : 'Course Pending'
  356. }
  357. return hasCourseHeading ? 'Sensor + Course' : 'Sensor Only'
  358. }
  359. function formatAutoRotateCalibrationText(pending: boolean, offsetDeg: number | null): string {
  360. if (pending) {
  361. return 'Pending'
  362. }
  363. if (offsetDeg === null) {
  364. return '--'
  365. }
  366. return `Offset ${Math.round(normalizeRotationDeg(offsetDeg))}deg`
  367. }
  368. function getTrueHeadingDeg(magneticHeadingDeg: number): number {
  369. return normalizeRotationDeg(magneticHeadingDeg + MAGNETIC_DECLINATION_DEG)
  370. }
  371. function getMagneticHeadingDeg(trueHeadingDeg: number): number {
  372. return normalizeRotationDeg(trueHeadingDeg - MAGNETIC_DECLINATION_DEG)
  373. }
  374. function getMapNorthOffsetDeg(_mode: NorthReferenceMode): number {
  375. return MAP_NORTH_OFFSET_DEG
  376. }
  377. function getCompassReferenceHeadingDeg(mode: NorthReferenceMode, magneticHeadingDeg: number): number {
  378. if (mode === 'true') {
  379. return getTrueHeadingDeg(magneticHeadingDeg)
  380. }
  381. return normalizeRotationDeg(magneticHeadingDeg)
  382. }
  383. function getMapReferenceHeadingDegFromSensor(mode: NorthReferenceMode, magneticHeadingDeg: number): number {
  384. if (mode === 'magnetic') {
  385. return normalizeRotationDeg(magneticHeadingDeg)
  386. }
  387. return getTrueHeadingDeg(magneticHeadingDeg)
  388. }
  389. function getMapReferenceHeadingDegFromCourse(mode: NorthReferenceMode, trueHeadingDeg: number): number {
  390. if (mode === 'magnetic') {
  391. return getMagneticHeadingDeg(trueHeadingDeg)
  392. }
  393. return normalizeRotationDeg(trueHeadingDeg)
  394. }
  395. function formatNorthReferenceText(mode: NorthReferenceMode): string {
  396. if (mode === 'magnetic') {
  397. return `Compass Magnetic / Heading-Up Magnetic (${MAGNETIC_DECLINATION_TEXT})`
  398. }
  399. return `Compass True / Heading-Up True (${MAGNETIC_DECLINATION_TEXT})`
  400. }
  401. function formatCompassDeclinationText(mode: NorthReferenceMode): string {
  402. if (mode === 'true') {
  403. return MAGNETIC_DECLINATION_TEXT
  404. }
  405. return ''
  406. }
  407. function formatNorthReferenceButtonText(mode: NorthReferenceMode): string {
  408. return mode === 'magnetic' ? '北参照:磁北' : '北参照:真北'
  409. }
  410. function formatNorthReferenceStatusText(mode: NorthReferenceMode): string {
  411. if (mode === 'magnetic') {
  412. return '已切到磁北模式'
  413. }
  414. return '已切到真北模式'
  415. }
  416. function getNextNorthReferenceMode(mode: NorthReferenceMode): NorthReferenceMode {
  417. return mode === 'magnetic' ? 'true' : 'magnetic'
  418. }
  419. function formatCompassNeedleDegForMode(mode: NorthReferenceMode, magneticHeadingDeg: number | null): number {
  420. if (magneticHeadingDeg === null) {
  421. return 0
  422. }
  423. const referenceHeadingDeg = mode === 'true'
  424. ? getTrueHeadingDeg(magneticHeadingDeg)
  425. : normalizeRotationDeg(magneticHeadingDeg)
  426. return normalizeRotationDeg(360 - referenceHeadingDeg)
  427. }
  428. function formatCacheHitRate(memoryHitCount: number, diskHitCount: number, networkFetchCount: number): string {
  429. const total = memoryHitCount + diskHitCount + networkFetchCount
  430. if (!total) {
  431. return '--'
  432. }
  433. const hitRate = ((memoryHitCount + diskHitCount) / total) * 100
  434. return `${Math.round(hitRate)}%`
  435. }
  436. function formatGpsCoordText(point: LonLatPoint | null, accuracyMeters: number | null): string {
  437. if (!point) {
  438. return '--'
  439. }
  440. const base = `${point.lat.toFixed(6)}, ${point.lon.toFixed(6)}`
  441. if (accuracyMeters === null || !Number.isFinite(accuracyMeters)) {
  442. return base
  443. }
  444. return `${base} / 卤${Math.round(accuracyMeters)}m`
  445. }
  446. function getApproxDistanceMeters(a: LonLatPoint, b: LonLatPoint): number {
  447. const avgLatRad = ((a.lat + b.lat) / 2) * Math.PI / 180
  448. const dx = (b.lon - a.lon) * 111320 * Math.cos(avgLatRad)
  449. const dy = (b.lat - a.lat) * 110540
  450. return Math.sqrt(dx * dx + dy * dy)
  451. }
  452. function getInitialBearingDeg(from: LonLatPoint, to: LonLatPoint): number {
  453. const fromLatRad = from.lat * Math.PI / 180
  454. const toLatRad = to.lat * Math.PI / 180
  455. const deltaLonRad = (to.lon - from.lon) * Math.PI / 180
  456. const y = Math.sin(deltaLonRad) * Math.cos(toLatRad)
  457. const x = Math.cos(fromLatRad) * Math.sin(toLatRad) - Math.sin(fromLatRad) * Math.cos(toLatRad) * Math.cos(deltaLonRad)
  458. const bearingDeg = Math.atan2(y, x) * 180 / Math.PI
  459. return normalizeRotationDeg(bearingDeg)
  460. }
  461. export class MapEngine {
  462. buildVersion: string
  463. renderer: WebGLMapRenderer
  464. compassController: CompassHeadingController
  465. locationController: LocationController
  466. heartRateController: HeartRateInputController
  467. feedbackDirector: FeedbackDirector
  468. onData: (patch: Partial<MapEngineViewState>) => void
  469. state: MapEngineViewState
  470. previewScale: number
  471. previewOriginX: number
  472. previewOriginY: number
  473. panLastX: number
  474. panLastY: number
  475. panLastTimestamp: number
  476. tapStartX: number
  477. tapStartY: number
  478. tapStartAt: number
  479. panVelocityX: number
  480. panVelocityY: number
  481. pinchStartDistance: number
  482. pinchStartScale: number
  483. pinchStartAngle: number
  484. pinchStartRotationDeg: number
  485. pinchAnchorWorldX: number
  486. pinchAnchorWorldY: number
  487. gestureMode: GestureMode
  488. inertiaTimer: number
  489. previewResetTimer: number
  490. viewSyncTimer: number
  491. autoRotateTimer: number
  492. pendingViewPatch: Partial<MapEngineViewState>
  493. mounted: boolean
  494. northReferenceMode: NorthReferenceMode
  495. sensorHeadingDeg: number | null
  496. smoothedSensorHeadingDeg: number | null
  497. compassDisplayHeadingDeg: number | null
  498. autoRotateHeadingDeg: number | null
  499. courseHeadingDeg: number | null
  500. targetAutoRotationDeg: number | null
  501. autoRotateSourceMode: AutoRotateSourceMode
  502. autoRotateCalibrationOffsetDeg: number | null
  503. autoRotateCalibrationPending: boolean
  504. minZoom: number
  505. maxZoom: number
  506. defaultZoom: number
  507. defaultCenterTileX: number
  508. defaultCenterTileY: number
  509. tileBoundsByZoom: Record<number, TileZoomBounds> | null
  510. currentGpsPoint: LonLatPoint | null
  511. currentGpsTrack: LonLatPoint[]
  512. currentGpsAccuracyMeters: number | null
  513. courseData: OrienteeringCourseData | null
  514. courseOverlayVisible: boolean
  515. cpRadiusMeters: number
  516. gameRuntime: GameRuntime
  517. telemetryRuntime: TelemetryRuntime
  518. gamePresentation: GamePresentationState
  519. gameMode: 'classic-sequential' | 'score-o'
  520. punchPolicy: 'enter' | 'enter-confirm'
  521. punchRadiusMeters: number
  522. autoFinishOnLastControl: boolean
  523. punchFeedbackTimer: number
  524. contentCardTimer: number
  525. mapPulseTimer: number
  526. stageFxTimer: number
  527. sessionTimerInterval: number
  528. hasGpsCenteredOnce: boolean
  529. constructor(buildVersion: string, callbacks: MapEngineCallbacks) {
  530. this.buildVersion = buildVersion
  531. this.onData = callbacks.onData
  532. this.renderer = new WebGLMapRenderer(
  533. (stats) => {
  534. this.applyStats(stats)
  535. },
  536. (message) => {
  537. this.setState({
  538. statusText: `${message} (${this.buildVersion})`,
  539. })
  540. },
  541. )
  542. this.compassController = new CompassHeadingController({
  543. onHeading: (headingDeg) => {
  544. this.handleCompassHeading(headingDeg)
  545. },
  546. onError: (message) => {
  547. this.handleCompassError(message)
  548. },
  549. })
  550. this.locationController = new LocationController({
  551. onLocation: (update) => {
  552. this.handleLocationUpdate(update.longitude, update.latitude, typeof update.accuracy === 'number' ? update.accuracy : null)
  553. },
  554. onStatus: (message) => {
  555. this.setState({
  556. gpsTracking: this.locationController.listening,
  557. gpsTrackingText: message,
  558. ...this.getLocationControllerViewPatch(),
  559. }, true)
  560. },
  561. onError: (message) => {
  562. this.setState({
  563. gpsTracking: this.locationController.listening,
  564. gpsTrackingText: message,
  565. ...this.getLocationControllerViewPatch(),
  566. statusText: `${message} (${this.buildVersion})`,
  567. }, true)
  568. },
  569. onDebugStateChange: () => {
  570. this.setState(this.getLocationControllerViewPatch(), true)
  571. },
  572. })
  573. this.heartRateController = new HeartRateInputController({
  574. onHeartRate: (bpm) => {
  575. this.telemetryRuntime.dispatch({
  576. type: 'heart_rate_updated',
  577. at: Date.now(),
  578. bpm,
  579. })
  580. this.syncSessionTimerText()
  581. },
  582. onStatus: (message) => {
  583. const deviceName = this.heartRateController.currentDeviceName
  584. || (this.heartRateController.reconnecting ? this.heartRateController.lastDeviceName : null)
  585. || '--'
  586. this.setState({
  587. heartRateStatusText: message,
  588. heartRateDeviceText: deviceName,
  589. heartRateScanText: this.getHeartRateScanText(),
  590. ...this.getHeartRateControllerViewPatch(),
  591. }, true)
  592. },
  593. onError: (message) => {
  594. this.clearHeartRateSignal()
  595. const deviceName = this.heartRateController.reconnecting
  596. ? (this.heartRateController.lastDeviceName || '--')
  597. : '--'
  598. this.setState({
  599. heartRateConnected: false,
  600. heartRateStatusText: message,
  601. heartRateDeviceText: deviceName,
  602. heartRateScanText: this.getHeartRateScanText(),
  603. ...this.getHeartRateControllerViewPatch(),
  604. statusText: `${message} (${this.buildVersion})`,
  605. }, true)
  606. },
  607. onConnectionChange: (connected, deviceName) => {
  608. if (!connected) {
  609. this.clearHeartRateSignal()
  610. }
  611. const resolvedDeviceName = connected
  612. ? (deviceName || '--')
  613. : (this.heartRateController.reconnecting
  614. ? (this.heartRateController.lastDeviceName || '--')
  615. : '--')
  616. this.setState({
  617. heartRateConnected: connected,
  618. heartRateDeviceText: resolvedDeviceName,
  619. heartRateStatusText: connected
  620. ? (this.heartRateController.sourceMode === 'mock' ? '模拟心率源已连接' : '心率带已连接')
  621. : (this.heartRateController.reconnecting ? '心率带自动重连中' : (this.heartRateController.sourceMode === 'mock' ? '模拟心率源未连接' : '心率带未连接')),
  622. heartRateScanText: this.getHeartRateScanText(),
  623. heartRateDiscoveredDevices: this.formatHeartRateDevices(this.heartRateController.discoveredDevices),
  624. ...this.getHeartRateControllerViewPatch(),
  625. }, true)
  626. },
  627. onDeviceListChange: (devices) => {
  628. this.setState({
  629. heartRateDiscoveredDevices: this.formatHeartRateDevices(devices),
  630. heartRateScanText: this.getHeartRateScanText(),
  631. ...this.getHeartRateControllerViewPatch(),
  632. }, true)
  633. },
  634. onDebugStateChange: () => {
  635. this.setState(this.getHeartRateControllerViewPatch(), true)
  636. },
  637. })
  638. this.feedbackDirector = new FeedbackDirector({
  639. showPunchFeedback: (text, tone, motionClass) => {
  640. this.showPunchFeedback(text, tone, motionClass)
  641. },
  642. showContentCard: (title, body, motionClass) => {
  643. this.showContentCard(title, body, motionClass)
  644. },
  645. setPunchButtonFxClass: (className) => {
  646. this.setPunchButtonFxClass(className)
  647. },
  648. showMapPulse: (controlId, motionClass) => {
  649. this.showMapPulse(controlId, motionClass)
  650. },
  651. showStageFx: (className) => {
  652. this.showStageFx(className)
  653. },
  654. stopLocationTracking: () => {
  655. if (this.locationController.listening) {
  656. this.locationController.stop()
  657. }
  658. },
  659. })
  660. this.minZoom = MIN_ZOOM
  661. this.maxZoom = MAX_ZOOM
  662. this.defaultZoom = DEFAULT_ZOOM
  663. this.defaultCenterTileX = DEFAULT_CENTER_TILE_X
  664. this.defaultCenterTileY = DEFAULT_CENTER_TILE_Y
  665. this.tileBoundsByZoom = null
  666. this.currentGpsPoint = null
  667. this.currentGpsTrack = []
  668. this.currentGpsAccuracyMeters = null
  669. this.courseData = null
  670. this.courseOverlayVisible = false
  671. this.cpRadiusMeters = 5
  672. this.gameRuntime = new GameRuntime()
  673. this.telemetryRuntime = new TelemetryRuntime()
  674. this.telemetryRuntime.configure()
  675. this.gamePresentation = EMPTY_GAME_PRESENTATION_STATE
  676. this.gameMode = 'classic-sequential'
  677. this.punchPolicy = 'enter-confirm'
  678. this.punchRadiusMeters = 5
  679. this.autoFinishOnLastControl = true
  680. this.punchFeedbackTimer = 0
  681. this.contentCardTimer = 0
  682. this.mapPulseTimer = 0
  683. this.stageFxTimer = 0
  684. this.sessionTimerInterval = 0
  685. this.hasGpsCenteredOnce = false
  686. this.state = {
  687. buildVersion: this.buildVersion,
  688. renderMode: RENDER_MODE,
  689. projectionMode: PROJECTION_MODE,
  690. mapReady: false,
  691. mapReadyText: 'BOOTING',
  692. mapName: 'LCX 测试地图',
  693. configStatusText: '远程配置待加载',
  694. zoom: DEFAULT_ZOOM,
  695. rotationDeg: 0,
  696. rotationText: formatRotationText(0),
  697. rotationMode: 'manual',
  698. rotationModeText: formatRotationModeText('manual'),
  699. rotationToggleText: formatRotationToggleText('manual'),
  700. orientationMode: 'manual',
  701. orientationModeText: formatOrientationModeText('manual'),
  702. sensorHeadingText: '--',
  703. compassDeclinationText: formatCompassDeclinationText(DEFAULT_NORTH_REFERENCE_MODE),
  704. northReferenceButtonText: formatNorthReferenceButtonText(DEFAULT_NORTH_REFERENCE_MODE),
  705. autoRotateSourceText: formatAutoRotateSourceText('sensor', false),
  706. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, getMapNorthOffsetDeg(DEFAULT_NORTH_REFERENCE_MODE)),
  707. northReferenceText: formatNorthReferenceText(DEFAULT_NORTH_REFERENCE_MODE),
  708. compassNeedleDeg: 0,
  709. centerTileX: DEFAULT_CENTER_TILE_X,
  710. centerTileY: DEFAULT_CENTER_TILE_Y,
  711. centerText: buildCenterText(DEFAULT_ZOOM, DEFAULT_CENTER_TILE_X, DEFAULT_CENTER_TILE_Y),
  712. tileSource: TILE_SOURCE,
  713. visibleColumnCount: DESIRED_VISIBLE_COLUMNS,
  714. visibleTileCount: 0,
  715. readyTileCount: 0,
  716. memoryTileCount: 0,
  717. diskTileCount: 0,
  718. memoryHitCount: 0,
  719. diskHitCount: 0,
  720. networkFetchCount: 0,
  721. cacheHitRateText: '--',
  722. tileTranslateX: 0,
  723. tileTranslateY: 0,
  724. tileSizePx: 0,
  725. stageWidth: 0,
  726. stageHeight: 0,
  727. stageLeft: 0,
  728. stageTop: 0,
  729. statusText: `单 WebGL 管线已就绪,等待传感器接入 (${this.buildVersion})`,
  730. gpsTracking: false,
  731. gpsTrackingText: '持续定位待启动',
  732. locationSourceMode: 'real',
  733. locationSourceText: '真实定位',
  734. mockBridgeConnected: false,
  735. mockBridgeStatusText: '未连接',
  736. mockBridgeUrlText: 'wss://gs.gotomars.xyz/mock-gps',
  737. mockCoordText: '--',
  738. mockSpeedText: '--',
  739. gpsCoordText: '--',
  740. heartRateSourceMode: 'real',
  741. heartRateSourceText: '真实心率',
  742. heartRateConnected: false,
  743. heartRateStatusText: '心率带未连接',
  744. heartRateDeviceText: '--',
  745. heartRateScanText: '未扫描',
  746. heartRateDiscoveredDevices: [],
  747. mockHeartRateBridgeConnected: false,
  748. mockHeartRateBridgeStatusText: '未连接',
  749. mockHeartRateBridgeUrlText: 'wss://gs.gotomars.xyz/mock-gps',
  750. mockHeartRateText: '--',
  751. panelTimerText: '00:00:00',
  752. panelMileageText: '0m',
  753. panelActionTagText: '目标',
  754. panelDistanceTagText: '点距',
  755. panelDistanceValueText: '--',
  756. panelDistanceUnitText: '',
  757. panelProgressText: '0/0',
  758. panelSpeedValueText: '0',
  759. panelTelemetryTone: 'blue',
  760. panelHeartRateZoneNameText: '激活放松',
  761. panelHeartRateZoneRangeText: '<=39%',
  762. panelHeartRateValueText: '--',
  763. panelHeartRateUnitText: '',
  764. panelCaloriesValueText: '0',
  765. panelCaloriesUnitText: 'kcal',
  766. panelAverageSpeedValueText: '0',
  767. panelAverageSpeedUnitText: 'km/h',
  768. panelAccuracyValueText: '--',
  769. panelAccuracyUnitText: '',
  770. punchButtonText: '打点',
  771. gameSessionStatus: 'idle',
  772. gameModeText: '顺序赛',
  773. punchButtonEnabled: false,
  774. punchHintText: '等待进入检查点范围',
  775. punchFeedbackVisible: false,
  776. punchFeedbackText: '',
  777. punchFeedbackTone: 'neutral',
  778. contentCardVisible: false,
  779. contentCardTitle: '',
  780. contentCardBody: '',
  781. punchButtonFxClass: '',
  782. punchFeedbackFxClass: '',
  783. contentCardFxClass: '',
  784. mapPulseVisible: false,
  785. mapPulseLeftPx: 0,
  786. mapPulseTopPx: 0,
  787. mapPulseFxClass: '',
  788. stageFxVisible: false,
  789. stageFxClass: '',
  790. osmReferenceEnabled: false,
  791. osmReferenceText: 'OSM参考:关',
  792. }
  793. this.previewScale = 1
  794. this.previewOriginX = 0
  795. this.previewOriginY = 0
  796. this.panLastX = 0
  797. this.panLastY = 0
  798. this.panLastTimestamp = 0
  799. this.tapStartX = 0
  800. this.tapStartY = 0
  801. this.tapStartAt = 0
  802. this.panVelocityX = 0
  803. this.panVelocityY = 0
  804. this.pinchStartDistance = 0
  805. this.pinchStartScale = 1
  806. this.pinchStartAngle = 0
  807. this.pinchStartRotationDeg = 0
  808. this.pinchAnchorWorldX = 0
  809. this.pinchAnchorWorldY = 0
  810. this.gestureMode = 'idle'
  811. this.inertiaTimer = 0
  812. this.previewResetTimer = 0
  813. this.viewSyncTimer = 0
  814. this.autoRotateTimer = 0
  815. this.pendingViewPatch = {}
  816. this.mounted = false
  817. this.northReferenceMode = DEFAULT_NORTH_REFERENCE_MODE
  818. this.sensorHeadingDeg = null
  819. this.smoothedSensorHeadingDeg = null
  820. this.compassDisplayHeadingDeg = null
  821. this.autoRotateHeadingDeg = null
  822. this.courseHeadingDeg = null
  823. this.targetAutoRotationDeg = null
  824. this.autoRotateSourceMode = 'sensor'
  825. this.autoRotateCalibrationOffsetDeg = getMapNorthOffsetDeg(DEFAULT_NORTH_REFERENCE_MODE)
  826. this.autoRotateCalibrationPending = false
  827. }
  828. getInitialData(): MapEngineViewState {
  829. return { ...this.state }
  830. }
  831. destroy(): void {
  832. this.clearInertiaTimer()
  833. this.clearPreviewResetTimer()
  834. this.clearViewSyncTimer()
  835. this.clearAutoRotateTimer()
  836. this.clearPunchFeedbackTimer()
  837. this.clearContentCardTimer()
  838. this.clearMapPulseTimer()
  839. this.clearStageFxTimer()
  840. this.clearSessionTimerInterval()
  841. this.compassController.destroy()
  842. this.locationController.destroy()
  843. this.heartRateController.destroy()
  844. this.feedbackDirector.destroy()
  845. this.renderer.destroy()
  846. this.mounted = false
  847. }
  848. handleAppShow(): void {
  849. this.feedbackDirector.setAppAudioMode('foreground')
  850. }
  851. handleAppHide(): void {
  852. this.feedbackDirector.setAppAudioMode('foreground')
  853. }
  854. clearGameRuntime(): void {
  855. this.gameRuntime.clear()
  856. this.telemetryRuntime.reset()
  857. this.gamePresentation = EMPTY_GAME_PRESENTATION_STATE
  858. this.courseOverlayVisible = !!this.courseData
  859. this.clearSessionTimerInterval()
  860. this.setCourseHeading(null)
  861. }
  862. clearHeartRateSignal(): void {
  863. this.telemetryRuntime.dispatch({
  864. type: 'heart_rate_updated',
  865. at: Date.now(),
  866. bpm: null,
  867. })
  868. this.syncSessionTimerText()
  869. }
  870. clearFinishedTestOverlay(): void {
  871. this.currentGpsPoint = null
  872. this.currentGpsTrack = []
  873. this.currentGpsAccuracyMeters = null
  874. this.courseOverlayVisible = false
  875. this.setCourseHeading(null)
  876. }
  877. handleClearMapTestArtifacts(): void {
  878. this.clearFinishedTestOverlay()
  879. this.setState({
  880. gpsTracking: false,
  881. gpsTrackingText: '测试痕迹已清空',
  882. gpsCoordText: '--',
  883. statusText: `已清空地图点位与轨迹 (${this.buildVersion})`,
  884. }, true)
  885. this.syncRenderer()
  886. }
  887. getHudTargetControlId(): string | null {
  888. return this.gamePresentation.hud.hudTargetControlId
  889. }
  890. getLocationControllerViewPatch(): Partial<MapEngineViewState> {
  891. const debugState = this.locationController.getDebugState()
  892. return {
  893. gpsTracking: debugState.listening,
  894. locationSourceMode: debugState.sourceMode,
  895. locationSourceText: debugState.sourceModeText,
  896. mockBridgeConnected: debugState.mockBridgeConnected,
  897. mockBridgeStatusText: debugState.mockBridgeStatusText,
  898. mockBridgeUrlText: debugState.mockBridgeUrlText,
  899. mockCoordText: debugState.mockCoordText,
  900. mockSpeedText: debugState.mockSpeedText,
  901. }
  902. }
  903. getHeartRateControllerViewPatch(): Partial<MapEngineViewState> {
  904. const debugState = this.heartRateController.getDebugState()
  905. return {
  906. heartRateSourceMode: debugState.sourceMode,
  907. heartRateSourceText: debugState.sourceModeText,
  908. mockHeartRateBridgeConnected: debugState.mockBridgeConnected,
  909. mockHeartRateBridgeStatusText: debugState.mockBridgeStatusText,
  910. mockHeartRateBridgeUrlText: debugState.mockBridgeUrlText,
  911. mockHeartRateText: debugState.mockHeartRateText,
  912. }
  913. }
  914. getGameModeText(): string {
  915. return this.gameMode === 'score-o' ? '积分赛' : '顺序赛'
  916. }
  917. loadGameDefinitionFromCourse(): GameEffect[] {
  918. if (!this.courseData) {
  919. this.clearGameRuntime()
  920. return []
  921. }
  922. const definition = buildGameDefinitionFromCourse(
  923. this.courseData,
  924. this.cpRadiusMeters,
  925. this.gameMode,
  926. this.autoFinishOnLastControl,
  927. this.punchPolicy,
  928. this.punchRadiusMeters,
  929. )
  930. const result = this.gameRuntime.loadDefinition(definition)
  931. this.telemetryRuntime.loadDefinition(definition)
  932. this.gamePresentation = result.presentation
  933. this.courseOverlayVisible = true
  934. this.telemetryRuntime.syncGameState(this.gameRuntime.definition, result.nextState, this.getHudTargetControlId())
  935. this.refreshCourseHeadingFromPresentation()
  936. this.updateSessionTimerLoop()
  937. this.setState({
  938. gameModeText: this.getGameModeText(),
  939. })
  940. return result.effects
  941. }
  942. refreshCourseHeadingFromPresentation(): void {
  943. if (!this.courseData || !this.gamePresentation.map.activeLegIndices.length) {
  944. this.setCourseHeading(null)
  945. return
  946. }
  947. const activeLegIndex = this.gamePresentation.map.activeLegIndices[0]
  948. const activeLeg = this.courseData.layers.legs[activeLegIndex]
  949. if (!activeLeg) {
  950. this.setCourseHeading(null)
  951. return
  952. }
  953. this.setCourseHeading(getInitialBearingDeg(activeLeg.fromPoint, activeLeg.toPoint))
  954. }
  955. resolveGameStatusText(effects: GameEffect[]): string | null {
  956. const lastEffect = effects.length ? effects[effects.length - 1] : null
  957. if (!lastEffect) {
  958. return null
  959. }
  960. if (lastEffect.type === 'control_completed') {
  961. const sequenceText = typeof lastEffect.sequence === 'number' ? String(lastEffect.sequence) : lastEffect.controlId
  962. return `宸插畬鎴愭鏌ョ偣 ${sequenceText} (${this.buildVersion})`
  963. }
  964. if (lastEffect.type === 'session_finished') {
  965. return `璺嚎宸插畬鎴?(${this.buildVersion})`
  966. }
  967. if (lastEffect.type === 'session_started') {
  968. return `椤哄簭鎵撶偣宸插紑濮?(${this.buildVersion})`
  969. }
  970. return null
  971. }
  972. getGameViewPatch(statusText?: string | null): Partial<MapEngineViewState> {
  973. const telemetryPresentation = this.telemetryRuntime.getPresentation()
  974. const patch: Partial<MapEngineViewState> = {
  975. gameSessionStatus: this.gameRuntime.state ? this.gameRuntime.state.status : 'idle',
  976. gameModeText: this.getGameModeText(),
  977. panelTimerText: telemetryPresentation.timerText,
  978. panelMileageText: telemetryPresentation.mileageText,
  979. panelActionTagText: this.gamePresentation.hud.actionTagText,
  980. panelDistanceTagText: this.gamePresentation.hud.distanceTagText,
  981. panelDistanceValueText: telemetryPresentation.distanceToTargetValueText,
  982. panelDistanceUnitText: telemetryPresentation.distanceToTargetUnitText,
  983. panelSpeedValueText: telemetryPresentation.speedText,
  984. panelTelemetryTone: telemetryPresentation.heartRateTone,
  985. panelHeartRateZoneNameText: telemetryPresentation.heartRateZoneNameText,
  986. panelHeartRateZoneRangeText: telemetryPresentation.heartRateZoneRangeText,
  987. panelHeartRateValueText: telemetryPresentation.heartRateValueText,
  988. panelHeartRateUnitText: telemetryPresentation.heartRateUnitText,
  989. panelCaloriesValueText: telemetryPresentation.caloriesValueText,
  990. panelCaloriesUnitText: telemetryPresentation.caloriesUnitText,
  991. panelAverageSpeedValueText: telemetryPresentation.averageSpeedValueText,
  992. panelAverageSpeedUnitText: telemetryPresentation.averageSpeedUnitText,
  993. panelAccuracyValueText: telemetryPresentation.accuracyValueText,
  994. panelAccuracyUnitText: telemetryPresentation.accuracyUnitText,
  995. panelProgressText: this.gamePresentation.hud.progressText,
  996. punchButtonText: this.gamePresentation.hud.punchButtonText,
  997. punchButtonEnabled: this.gamePresentation.hud.punchButtonEnabled,
  998. punchHintText: this.gamePresentation.hud.punchHintText,
  999. }
  1000. if (statusText) {
  1001. patch.statusText = statusText
  1002. }
  1003. return patch
  1004. }
  1005. clearPunchFeedbackTimer(): void {
  1006. if (this.punchFeedbackTimer) {
  1007. clearTimeout(this.punchFeedbackTimer)
  1008. this.punchFeedbackTimer = 0
  1009. }
  1010. }
  1011. clearContentCardTimer(): void {
  1012. if (this.contentCardTimer) {
  1013. clearTimeout(this.contentCardTimer)
  1014. this.contentCardTimer = 0
  1015. }
  1016. }
  1017. clearMapPulseTimer(): void {
  1018. if (this.mapPulseTimer) {
  1019. clearTimeout(this.mapPulseTimer)
  1020. this.mapPulseTimer = 0
  1021. }
  1022. }
  1023. clearStageFxTimer(): void {
  1024. if (this.stageFxTimer) {
  1025. clearTimeout(this.stageFxTimer)
  1026. this.stageFxTimer = 0
  1027. }
  1028. }
  1029. clearSessionTimerInterval(): void {
  1030. if (this.sessionTimerInterval) {
  1031. clearInterval(this.sessionTimerInterval)
  1032. this.sessionTimerInterval = 0
  1033. }
  1034. }
  1035. syncSessionTimerText(): void {
  1036. const telemetryPresentation = this.telemetryRuntime.getPresentation()
  1037. this.setState({
  1038. panelTimerText: telemetryPresentation.timerText,
  1039. panelMileageText: telemetryPresentation.mileageText,
  1040. panelActionTagText: this.gamePresentation.hud.actionTagText,
  1041. panelDistanceTagText: this.gamePresentation.hud.distanceTagText,
  1042. panelDistanceValueText: telemetryPresentation.distanceToTargetValueText,
  1043. panelDistanceUnitText: telemetryPresentation.distanceToTargetUnitText,
  1044. panelSpeedValueText: telemetryPresentation.speedText,
  1045. panelTelemetryTone: telemetryPresentation.heartRateTone,
  1046. panelHeartRateZoneNameText: telemetryPresentation.heartRateZoneNameText,
  1047. panelHeartRateZoneRangeText: telemetryPresentation.heartRateZoneRangeText,
  1048. panelHeartRateValueText: telemetryPresentation.heartRateValueText,
  1049. panelHeartRateUnitText: telemetryPresentation.heartRateUnitText,
  1050. panelCaloriesValueText: telemetryPresentation.caloriesValueText,
  1051. panelCaloriesUnitText: telemetryPresentation.caloriesUnitText,
  1052. panelAverageSpeedValueText: telemetryPresentation.averageSpeedValueText,
  1053. panelAverageSpeedUnitText: telemetryPresentation.averageSpeedUnitText,
  1054. panelAccuracyValueText: telemetryPresentation.accuracyValueText,
  1055. panelAccuracyUnitText: telemetryPresentation.accuracyUnitText,
  1056. }, true)
  1057. }
  1058. updateSessionTimerLoop(): void {
  1059. const gameState = this.gameRuntime.state
  1060. const shouldRun = !!gameState && gameState.status === 'running' && gameState.endedAt === null
  1061. this.syncSessionTimerText()
  1062. if (!shouldRun) {
  1063. this.clearSessionTimerInterval()
  1064. return
  1065. }
  1066. if (this.sessionTimerInterval) {
  1067. return
  1068. }
  1069. this.sessionTimerInterval = setInterval(() => {
  1070. this.syncSessionTimerText()
  1071. }, 1000) as unknown as number
  1072. }
  1073. getControlScreenPoint(controlId: string): { x: number; y: number } | null {
  1074. if (!this.gameRuntime.definition || !this.state.stageWidth || !this.state.stageHeight) {
  1075. return null
  1076. }
  1077. const control = this.gameRuntime.definition.controls.find((item) => item.id === controlId)
  1078. if (!control) {
  1079. return null
  1080. }
  1081. const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
  1082. const screenPoint = worldToScreen({
  1083. centerWorldX: exactCenter.x,
  1084. centerWorldY: exactCenter.y,
  1085. viewportWidth: this.state.stageWidth,
  1086. viewportHeight: this.state.stageHeight,
  1087. visibleColumns: DESIRED_VISIBLE_COLUMNS,
  1088. rotationRad: this.getRotationRad(this.state.rotationDeg),
  1089. }, lonLatToWorldTile(control.point, this.state.zoom), false)
  1090. if (screenPoint.x < -80 || screenPoint.x > this.state.stageWidth + 80 || screenPoint.y < -80 || screenPoint.y > this.state.stageHeight + 80) {
  1091. return null
  1092. }
  1093. return screenPoint
  1094. }
  1095. setPunchButtonFxClass(className: string): void {
  1096. this.setState({
  1097. punchButtonFxClass: className,
  1098. }, true)
  1099. }
  1100. showMapPulse(controlId: string, motionClass = ''): void {
  1101. const screenPoint = this.getControlScreenPoint(controlId)
  1102. if (!screenPoint) {
  1103. return
  1104. }
  1105. this.clearMapPulseTimer()
  1106. this.setState({
  1107. mapPulseVisible: true,
  1108. mapPulseLeftPx: screenPoint.x,
  1109. mapPulseTopPx: screenPoint.y,
  1110. mapPulseFxClass: motionClass,
  1111. }, true)
  1112. this.mapPulseTimer = setTimeout(() => {
  1113. this.mapPulseTimer = 0
  1114. this.setState({
  1115. mapPulseVisible: false,
  1116. mapPulseFxClass: '',
  1117. }, true)
  1118. }, 820) as unknown as number
  1119. }
  1120. showStageFx(className: string): void {
  1121. if (!className) {
  1122. return
  1123. }
  1124. this.clearStageFxTimer()
  1125. this.setState({
  1126. stageFxVisible: true,
  1127. stageFxClass: className,
  1128. }, true)
  1129. this.stageFxTimer = setTimeout(() => {
  1130. this.stageFxTimer = 0
  1131. this.setState({
  1132. stageFxVisible: false,
  1133. stageFxClass: '',
  1134. }, true)
  1135. }, 760) as unknown as number
  1136. }
  1137. showPunchFeedback(text: string, tone: 'neutral' | 'success' | 'warning', motionClass = ''): void {
  1138. this.clearPunchFeedbackTimer()
  1139. this.setState({
  1140. punchFeedbackVisible: true,
  1141. punchFeedbackText: text,
  1142. punchFeedbackTone: tone,
  1143. punchFeedbackFxClass: motionClass,
  1144. }, true)
  1145. this.punchFeedbackTimer = setTimeout(() => {
  1146. this.punchFeedbackTimer = 0
  1147. this.setState({
  1148. punchFeedbackVisible: false,
  1149. punchFeedbackFxClass: '',
  1150. }, true)
  1151. }, 1400) as unknown as number
  1152. }
  1153. showContentCard(title: string, body: string, motionClass = ''): void {
  1154. this.clearContentCardTimer()
  1155. this.setState({
  1156. contentCardVisible: true,
  1157. contentCardTitle: title,
  1158. contentCardBody: body,
  1159. contentCardFxClass: motionClass,
  1160. }, true)
  1161. this.contentCardTimer = setTimeout(() => {
  1162. this.contentCardTimer = 0
  1163. this.setState({
  1164. contentCardVisible: false,
  1165. contentCardFxClass: '',
  1166. }, true)
  1167. }, 2600) as unknown as number
  1168. }
  1169. closeContentCard(): void {
  1170. this.clearContentCardTimer()
  1171. this.setState({
  1172. contentCardVisible: false,
  1173. contentCardFxClass: '',
  1174. }, true)
  1175. }
  1176. applyGameEffects(effects: GameEffect[]): string | null {
  1177. this.feedbackDirector.handleEffects(effects)
  1178. if (effects.some((effect) => effect.type === 'session_finished')) {
  1179. this.setState({
  1180. gpsTracking: false,
  1181. gpsTrackingText: '测试结束,定位已停止',
  1182. }, true)
  1183. }
  1184. this.telemetryRuntime.syncGameState(this.gameRuntime.definition, this.gameRuntime.state, this.getHudTargetControlId())
  1185. this.updateSessionTimerLoop()
  1186. return this.resolveGameStatusText(effects)
  1187. }
  1188. handleStartGame(): void {
  1189. if (!this.gameRuntime.definition || !this.gameRuntime.state) {
  1190. this.setState({
  1191. statusText: `当前还没有可开始的路线 (${this.buildVersion})`,
  1192. }, true)
  1193. return
  1194. }
  1195. if (this.gameRuntime.state.status !== 'idle') {
  1196. return
  1197. }
  1198. if (!this.locationController.listening) {
  1199. this.locationController.start()
  1200. }
  1201. const startedAt = Date.now()
  1202. let gameResult = this.gameRuntime.startSession(startedAt)
  1203. if (this.currentGpsPoint) {
  1204. gameResult = this.gameRuntime.dispatch({
  1205. type: 'gps_updated',
  1206. at: Date.now(),
  1207. lon: this.currentGpsPoint.lon,
  1208. lat: this.currentGpsPoint.lat,
  1209. accuracyMeters: this.currentGpsAccuracyMeters,
  1210. })
  1211. }
  1212. this.gamePresentation = this.gameRuntime.getPresentation()
  1213. this.courseOverlayVisible = true
  1214. this.refreshCourseHeadingFromPresentation()
  1215. const defaultStatusText = this.currentGpsPoint
  1216. ? `顺序打点已开始 (${this.buildVersion})`
  1217. : `顺序打点已开始,GPS定位启动中 (${this.buildVersion})`
  1218. const gameStatusText = this.applyGameEffects(gameResult.effects) || defaultStatusText
  1219. this.setState({
  1220. ...this.getGameViewPatch(gameStatusText),
  1221. }, true)
  1222. this.syncRenderer()
  1223. }
  1224. handlePunchAction(): void {
  1225. const gameResult = this.gameRuntime.dispatch({
  1226. type: 'punch_requested',
  1227. at: Date.now(),
  1228. })
  1229. this.gamePresentation = gameResult.presentation
  1230. this.refreshCourseHeadingFromPresentation()
  1231. const gameStatusText = this.applyGameEffects(gameResult.effects)
  1232. this.setState({
  1233. ...this.getGameViewPatch(gameStatusText),
  1234. }, true)
  1235. this.syncRenderer()
  1236. }
  1237. handleLocationUpdate(longitude: number, latitude: number, accuracyMeters: number | null): void {
  1238. const nextPoint: LonLatPoint = { lon: longitude, lat: latitude }
  1239. const lastTrackPoint = this.currentGpsTrack.length ? this.currentGpsTrack[this.currentGpsTrack.length - 1] : null
  1240. if (!lastTrackPoint || getApproxDistanceMeters(lastTrackPoint, nextPoint) >= GPS_TRACK_MIN_STEP_METERS) {
  1241. this.currentGpsTrack = [...this.currentGpsTrack, nextPoint].slice(-GPS_TRACK_MAX_POINTS)
  1242. }
  1243. this.currentGpsPoint = nextPoint
  1244. this.currentGpsAccuracyMeters = accuracyMeters
  1245. const gpsWorldPoint = lonLatToWorldTile(nextPoint, this.state.zoom)
  1246. const gpsTileX = Math.floor(gpsWorldPoint.x)
  1247. const gpsTileY = Math.floor(gpsWorldPoint.y)
  1248. const gpsInsideMap = isTileWithinBounds(this.tileBoundsByZoom, this.state.zoom, gpsTileX, gpsTileY)
  1249. let gameStatusText: string | null = null
  1250. if (this.courseData) {
  1251. const eventAt = Date.now()
  1252. const gameResult = this.gameRuntime.dispatch({
  1253. type: 'gps_updated',
  1254. at: eventAt,
  1255. lon: longitude,
  1256. lat: latitude,
  1257. accuracyMeters,
  1258. })
  1259. this.telemetryRuntime.dispatch({
  1260. type: 'gps_updated',
  1261. at: eventAt,
  1262. lon: longitude,
  1263. lat: latitude,
  1264. accuracyMeters,
  1265. })
  1266. this.gamePresentation = gameResult.presentation
  1267. this.refreshCourseHeadingFromPresentation()
  1268. gameStatusText = this.applyGameEffects(gameResult.effects)
  1269. }
  1270. if (gpsInsideMap && !this.hasGpsCenteredOnce) {
  1271. this.hasGpsCenteredOnce = true
  1272. this.commitViewport({
  1273. centerTileX: gpsWorldPoint.x,
  1274. centerTileY: gpsWorldPoint.y,
  1275. tileTranslateX: 0,
  1276. tileTranslateY: 0,
  1277. gpsTracking: true,
  1278. gpsTrackingText: '持续定位进行中',
  1279. gpsCoordText: formatGpsCoordText(nextPoint, accuracyMeters),
  1280. ...this.getGameViewPatch(),
  1281. }, gameStatusText || `GPS定位成功,已定位到当前位置 (${this.buildVersion})`, true)
  1282. return
  1283. }
  1284. this.setState({
  1285. gpsTracking: true,
  1286. gpsTrackingText: gpsInsideMap ? '持续定位进行中' : 'GPS不在当前地图范围内',
  1287. gpsCoordText: formatGpsCoordText(nextPoint, accuracyMeters),
  1288. ...this.getGameViewPatch(gameStatusText || (gpsInsideMap ? `GPS位置已更新 (${this.buildVersion})` : `GPS位置超出当前地图范围 (${this.buildVersion})`)),
  1289. }, true)
  1290. this.syncRenderer()
  1291. }
  1292. handleToggleOsmReference(): void {
  1293. const nextEnabled = !this.state.osmReferenceEnabled
  1294. this.setState({
  1295. osmReferenceEnabled: nextEnabled,
  1296. osmReferenceText: nextEnabled ? 'OSM参考:开' : 'OSM参考:关',
  1297. statusText: nextEnabled ? `OSM参考底图已开启 (${this.buildVersion})` : `OSM参考底图已关闭 (${this.buildVersion})`,
  1298. }, true)
  1299. this.syncRenderer()
  1300. }
  1301. handleToggleGpsTracking(): void {
  1302. if (this.locationController.listening) {
  1303. this.locationController.stop()
  1304. return
  1305. }
  1306. this.locationController.start()
  1307. }
  1308. handleSetRealLocationMode(): void {
  1309. this.locationController.setSourceMode('real')
  1310. }
  1311. handleSetMockLocationMode(): void {
  1312. this.locationController.setSourceMode('mock')
  1313. }
  1314. handleConnectMockLocationBridge(): void {
  1315. this.locationController.connectMockBridge()
  1316. }
  1317. handleDisconnectMockLocationBridge(): void {
  1318. this.locationController.disconnectMockBridge()
  1319. }
  1320. handleSetMockLocationBridgeUrl(url: string): void {
  1321. this.locationController.setMockBridgeUrl(url)
  1322. }
  1323. handleSetGameMode(nextMode: 'classic-sequential' | 'score-o'): void {
  1324. if (this.gameMode === nextMode) {
  1325. return
  1326. }
  1327. this.gameMode = nextMode
  1328. const effects = this.loadGameDefinitionFromCourse()
  1329. const modeText = this.getGameModeText()
  1330. const statusText = this.applyGameEffects(effects) || `已切换到${modeText} (${this.buildVersion})`
  1331. this.setState({
  1332. ...this.getGameViewPatch(statusText),
  1333. gameModeText: modeText,
  1334. }, true)
  1335. this.syncRenderer()
  1336. }
  1337. handleConnectHeartRate(): void {
  1338. this.heartRateController.startScanAndConnect()
  1339. }
  1340. handleDisconnectHeartRate(): void {
  1341. this.heartRateController.disconnect()
  1342. }
  1343. handleSetRealHeartRateMode(): void {
  1344. this.heartRateController.setSourceMode('real')
  1345. }
  1346. handleSetMockHeartRateMode(): void {
  1347. this.heartRateController.setSourceMode('mock')
  1348. }
  1349. handleConnectMockHeartRateBridge(): void {
  1350. this.heartRateController.connectMockBridge()
  1351. }
  1352. handleDisconnectMockHeartRateBridge(): void {
  1353. this.heartRateController.disconnectMockBridge()
  1354. }
  1355. handleSetMockHeartRateBridgeUrl(url: string): void {
  1356. this.heartRateController.setMockBridgeUrl(url)
  1357. }
  1358. handleConnectHeartRateDevice(deviceId: string): void {
  1359. this.heartRateController.connectToDiscoveredDevice(deviceId)
  1360. }
  1361. handleClearPreferredHeartRateDevice(): void {
  1362. this.heartRateController.clearPreferredDevice()
  1363. this.setState({
  1364. heartRateDeviceText: this.heartRateController.currentDeviceName || '--',
  1365. heartRateScanText: this.getHeartRateScanText(),
  1366. }, true)
  1367. }
  1368. handleDebugHeartRateTone(tone: HeartRateTone): void {
  1369. const sampleBpm = getHeartRateToneSampleBpm(tone, this.telemetryRuntime.config)
  1370. this.telemetryRuntime.dispatch({
  1371. type: 'heart_rate_updated',
  1372. at: Date.now(),
  1373. bpm: sampleBpm,
  1374. })
  1375. this.setState({
  1376. heartRateStatusText: `调试心率: ${sampleBpm} bpm / ${tone.toUpperCase()}`,
  1377. }, true)
  1378. this.syncSessionTimerText()
  1379. }
  1380. handleClearDebugHeartRate(): void {
  1381. this.telemetryRuntime.dispatch({
  1382. type: 'heart_rate_updated',
  1383. at: Date.now(),
  1384. bpm: null,
  1385. })
  1386. this.setState({
  1387. heartRateStatusText: this.heartRateController.connected
  1388. ? (this.heartRateController.sourceMode === 'mock' ? '模拟心率源已连接' : '心率带已连接')
  1389. : (this.heartRateController.sourceMode === 'mock' ? '模拟心率源未连接' : '心率带未连接'),
  1390. heartRateScanText: this.getHeartRateScanText(),
  1391. ...this.getHeartRateControllerViewPatch(),
  1392. }, true)
  1393. this.syncSessionTimerText()
  1394. }
  1395. formatHeartRateDevices(devices: HeartRateDiscoveredDevice[]): Array<{ deviceId: string; name: string; rssiText: string; preferred: boolean; connected: boolean }> {
  1396. return devices.map((device) => ({
  1397. deviceId: device.deviceId,
  1398. name: device.name,
  1399. rssiText: device.rssi === null ? '--' : `${device.rssi} dBm`,
  1400. preferred: device.isPreferred,
  1401. connected: !!this.heartRateController.currentDeviceId && this.heartRateController.currentDeviceId === device.deviceId && this.heartRateController.connected,
  1402. }))
  1403. }
  1404. getHeartRateScanText(): string {
  1405. if (this.heartRateController.sourceMode === 'mock') {
  1406. if (this.heartRateController.connected) {
  1407. return '模拟源已连接'
  1408. }
  1409. if (this.heartRateController.connecting) {
  1410. return '模拟源连接中'
  1411. }
  1412. return '模拟模式'
  1413. }
  1414. if (this.heartRateController.connected) {
  1415. return '已连接'
  1416. }
  1417. if (this.heartRateController.connecting) {
  1418. return '连接中'
  1419. }
  1420. if (this.heartRateController.disconnecting) {
  1421. return '断开中'
  1422. }
  1423. if (this.heartRateController.scanning) {
  1424. return this.heartRateController.lastDeviceId ? '扫描中(优先首选)' : '扫描中(等待选择)'
  1425. }
  1426. return this.heartRateController.discoveredDevices.length
  1427. ? `已发现 ${this.heartRateController.discoveredDevices.length} 个设备`
  1428. : '未扫描'
  1429. }
  1430. setStage(rect: MapEngineStageRect): void {
  1431. this.previewScale = 1
  1432. this.previewOriginX = rect.width / 2
  1433. this.previewOriginY = rect.height / 2
  1434. this.commitViewport(
  1435. {
  1436. stageWidth: rect.width,
  1437. stageHeight: rect.height,
  1438. stageLeft: rect.left,
  1439. stageTop: rect.top,
  1440. },
  1441. `地图视口已与 WebGL 引擎对齐 (${this.buildVersion})`,
  1442. true,
  1443. )
  1444. }
  1445. attachCanvas(canvasNode: any, width: number, height: number, dpr: number, labelCanvasNode?: any): void {
  1446. this.renderer.attachCanvas(canvasNode, width, height, dpr, labelCanvasNode)
  1447. this.mounted = true
  1448. this.state.mapReady = true
  1449. this.state.mapReadyText = 'READY'
  1450. this.onData({
  1451. mapReady: true,
  1452. mapReadyText: 'READY',
  1453. statusText: `单 WebGL 管线已完成,可切换手动或自动朝向 (${this.buildVersion})`,
  1454. })
  1455. this.syncRenderer()
  1456. this.compassController.start()
  1457. }
  1458. applyRemoteMapConfig(config: RemoteMapConfig): void {
  1459. MAGNETIC_DECLINATION_DEG = config.magneticDeclinationDeg
  1460. MAGNETIC_DECLINATION_TEXT = config.magneticDeclinationText
  1461. this.minZoom = config.minZoom
  1462. this.maxZoom = config.maxZoom
  1463. this.defaultZoom = config.defaultZoom
  1464. this.defaultCenterTileX = config.initialCenterTileX
  1465. this.defaultCenterTileY = config.initialCenterTileY
  1466. this.tileBoundsByZoom = config.tileBoundsByZoom
  1467. this.courseData = config.course
  1468. this.cpRadiusMeters = config.cpRadiusMeters
  1469. this.gameMode = config.gameMode
  1470. this.punchPolicy = config.punchPolicy
  1471. this.punchRadiusMeters = config.punchRadiusMeters
  1472. this.autoFinishOnLastControl = config.autoFinishOnLastControl
  1473. this.telemetryRuntime.configure(config.telemetryConfig)
  1474. this.feedbackDirector.configure({
  1475. audioConfig: config.audioConfig,
  1476. hapticsConfig: config.hapticsConfig,
  1477. uiEffectsConfig: config.uiEffectsConfig,
  1478. })
  1479. const gameEffects = this.loadGameDefinitionFromCourse()
  1480. const gameStatusText = this.applyGameEffects(gameEffects)
  1481. const statePatch: Partial<MapEngineViewState> = {
  1482. configStatusText: `远程配置已载入 / ${config.courseStatusText}`,
  1483. projectionMode: config.projectionModeText,
  1484. tileSource: config.tileSource,
  1485. sensorHeadingText: formatHeadingText(this.smoothedSensorHeadingDeg === null ? null : getCompassReferenceHeadingDeg(this.northReferenceMode, this.smoothedSensorHeadingDeg)),
  1486. compassDeclinationText: formatCompassDeclinationText(this.northReferenceMode),
  1487. northReferenceButtonText: formatNorthReferenceButtonText(this.northReferenceMode),
  1488. northReferenceText: formatNorthReferenceText(this.northReferenceMode),
  1489. compassNeedleDeg: formatCompassNeedleDegForMode(this.northReferenceMode, this.smoothedSensorHeadingDeg),
  1490. ...this.getGameViewPatch(),
  1491. }
  1492. if (!this.state.stageWidth || !this.state.stageHeight) {
  1493. this.setState({
  1494. ...statePatch,
  1495. zoom: this.defaultZoom,
  1496. centerTileX: this.defaultCenterTileX,
  1497. centerTileY: this.defaultCenterTileY,
  1498. centerText: buildCenterText(this.defaultZoom, this.defaultCenterTileX, this.defaultCenterTileY),
  1499. statusText: gameStatusText || `路线已载入,点击开始进入游戏 (${this.buildVersion})`,
  1500. }, true)
  1501. return
  1502. }
  1503. this.commitViewport({
  1504. ...statePatch,
  1505. zoom: this.defaultZoom,
  1506. centerTileX: this.defaultCenterTileX,
  1507. centerTileY: this.defaultCenterTileY,
  1508. tileTranslateX: 0,
  1509. tileTranslateY: 0,
  1510. }, gameStatusText || `路线已载入,点击开始进入游戏 (${this.buildVersion})`, true, () => {
  1511. this.resetPreviewState()
  1512. this.syncRenderer()
  1513. if (this.state.orientationMode === 'heading-up' && this.refreshAutoRotateTarget()) {
  1514. this.scheduleAutoRotate()
  1515. }
  1516. })
  1517. }
  1518. handleTouchStart(event: WechatMiniprogram.TouchEvent): void {
  1519. this.clearInertiaTimer()
  1520. this.clearPreviewResetTimer()
  1521. this.panVelocityX = 0
  1522. this.panVelocityY = 0
  1523. if (event.touches.length >= 2) {
  1524. const origin = this.getStagePoint(event.touches)
  1525. this.gestureMode = 'pinch'
  1526. this.pinchStartDistance = this.getTouchDistance(event.touches)
  1527. this.pinchStartScale = this.previewScale || 1
  1528. this.pinchStartAngle = this.getTouchAngle(event.touches)
  1529. this.pinchStartRotationDeg = this.state.rotationDeg
  1530. const anchorWorld = screenToWorld(this.getCameraState(), origin, true)
  1531. this.pinchAnchorWorldX = anchorWorld.x
  1532. this.pinchAnchorWorldY = anchorWorld.y
  1533. this.setPreviewState(this.pinchStartScale, origin.x, origin.y)
  1534. this.syncRenderer()
  1535. this.compassController.start()
  1536. return
  1537. }
  1538. if (event.touches.length === 1) {
  1539. this.gestureMode = 'pan'
  1540. this.panLastX = event.touches[0].pageX
  1541. this.panLastY = event.touches[0].pageY
  1542. this.panLastTimestamp = event.timeStamp || Date.now()
  1543. this.tapStartX = event.touches[0].pageX
  1544. this.tapStartY = event.touches[0].pageY
  1545. this.tapStartAt = event.timeStamp || Date.now()
  1546. }
  1547. }
  1548. handleTouchMove(event: WechatMiniprogram.TouchEvent): void {
  1549. if (event.touches.length >= 2) {
  1550. const distance = this.getTouchDistance(event.touches)
  1551. const angle = this.getTouchAngle(event.touches)
  1552. const origin = this.getStagePoint(event.touches)
  1553. if (!this.pinchStartDistance) {
  1554. this.pinchStartDistance = distance
  1555. this.pinchStartScale = this.previewScale || 1
  1556. this.pinchStartAngle = angle
  1557. this.pinchStartRotationDeg = this.state.rotationDeg
  1558. const anchorWorld = screenToWorld(this.getCameraState(), origin, true)
  1559. this.pinchAnchorWorldX = anchorWorld.x
  1560. this.pinchAnchorWorldY = anchorWorld.y
  1561. }
  1562. this.gestureMode = 'pinch'
  1563. const nextRotationDeg = this.state.orientationMode === 'heading-up'
  1564. ? this.state.rotationDeg
  1565. : normalizeRotationDeg(this.pinchStartRotationDeg + normalizeAngleDeltaRad(angle - this.pinchStartAngle) * 180 / Math.PI)
  1566. const anchorOffset = this.getWorldOffsetFromScreen(origin.x, origin.y, nextRotationDeg)
  1567. const resolvedViewport = this.resolveViewportForExactCenter(
  1568. this.pinchAnchorWorldX - anchorOffset.x,
  1569. this.pinchAnchorWorldY - anchorOffset.y,
  1570. nextRotationDeg,
  1571. )
  1572. this.setPreviewState(
  1573. clamp(this.pinchStartScale * (distance / this.pinchStartDistance), MIN_PREVIEW_SCALE, MAX_PREVIEW_SCALE),
  1574. origin.x,
  1575. origin.y,
  1576. )
  1577. this.commitViewport(
  1578. {
  1579. ...resolvedViewport,
  1580. rotationDeg: nextRotationDeg,
  1581. rotationText: formatRotationText(nextRotationDeg),
  1582. },
  1583. this.state.orientationMode === 'heading-up'
  1584. ? `双指缩放中,自动朝向保持开启 (${this.buildVersion})`
  1585. : `双指缩放与旋转中 (${this.buildVersion})`,
  1586. )
  1587. return
  1588. }
  1589. if (this.gestureMode !== 'pan' || event.touches.length !== 1) {
  1590. return
  1591. }
  1592. const touch = event.touches[0]
  1593. const deltaX = touch.pageX - this.panLastX
  1594. const deltaY = touch.pageY - this.panLastY
  1595. const nextTimestamp = event.timeStamp || Date.now()
  1596. const elapsed = Math.max(nextTimestamp - this.panLastTimestamp, 16)
  1597. const instantVelocityX = deltaX / elapsed
  1598. const instantVelocityY = deltaY / elapsed
  1599. this.panVelocityX = this.panVelocityX * 0.72 + instantVelocityX * 0.28
  1600. this.panVelocityY = this.panVelocityY * 0.72 + instantVelocityY * 0.28
  1601. this.panLastX = touch.pageX
  1602. this.panLastY = touch.pageY
  1603. this.panLastTimestamp = nextTimestamp
  1604. this.normalizeTranslate(
  1605. this.state.tileTranslateX + deltaX,
  1606. this.state.tileTranslateY + deltaY,
  1607. `宸叉嫋鎷藉崟 WebGL 鍦板浘寮曟搸 (${this.buildVersion})`,
  1608. )
  1609. }
  1610. handleTouchEnd(event: WechatMiniprogram.TouchEvent): void {
  1611. const changedTouch = event.changedTouches && event.changedTouches.length ? event.changedTouches[0] : null
  1612. const endedAsTap = changedTouch
  1613. && this.gestureMode === 'pan'
  1614. && event.touches.length === 0
  1615. && Math.abs(changedTouch.pageX - this.tapStartX) <= MAP_TAP_MOVE_THRESHOLD_PX
  1616. && Math.abs(changedTouch.pageY - this.tapStartY) <= MAP_TAP_MOVE_THRESHOLD_PX
  1617. && ((event.timeStamp || Date.now()) - this.tapStartAt) <= MAP_TAP_DURATION_MS
  1618. if (this.gestureMode === 'pinch' && event.touches.length < 2) {
  1619. const gestureScale = this.previewScale || 1
  1620. const zoomDelta = Math.round(Math.log2(gestureScale))
  1621. const originX = this.previewOriginX || this.state.stageWidth / 2
  1622. const originY = this.previewOriginY || this.state.stageHeight / 2
  1623. if (zoomDelta) {
  1624. const residualScale = gestureScale / Math.pow(2, zoomDelta)
  1625. this.zoomAroundPoint(zoomDelta, originX, originY, residualScale)
  1626. } else {
  1627. this.animatePreviewToRest()
  1628. }
  1629. this.resetPinchState()
  1630. this.panVelocityX = 0
  1631. this.panVelocityY = 0
  1632. if (event.touches.length === 1) {
  1633. this.gestureMode = 'pan'
  1634. this.panLastX = event.touches[0].pageX
  1635. this.panLastY = event.touches[0].pageY
  1636. this.panLastTimestamp = event.timeStamp || Date.now()
  1637. return
  1638. }
  1639. this.gestureMode = 'idle'
  1640. this.renderer.setAnimationPaused(false)
  1641. this.scheduleAutoRotate()
  1642. return
  1643. }
  1644. if (event.touches.length === 1) {
  1645. this.gestureMode = 'pan'
  1646. this.panLastX = event.touches[0].pageX
  1647. this.panLastY = event.touches[0].pageY
  1648. this.panLastTimestamp = event.timeStamp || Date.now()
  1649. return
  1650. }
  1651. if (this.gestureMode === 'pan' && (Math.abs(this.panVelocityX) >= INERTIA_MIN_SPEED || Math.abs(this.panVelocityY) >= INERTIA_MIN_SPEED)) {
  1652. this.startInertia()
  1653. this.gestureMode = 'idle'
  1654. this.resetPinchState()
  1655. return
  1656. }
  1657. if (endedAsTap && changedTouch) {
  1658. this.handleMapTap(changedTouch.pageX - this.state.stageLeft, changedTouch.pageY - this.state.stageTop)
  1659. }
  1660. this.gestureMode = 'idle'
  1661. this.resetPinchState()
  1662. this.renderer.setAnimationPaused(false)
  1663. this.scheduleAutoRotate()
  1664. }
  1665. handleTouchCancel(): void {
  1666. this.gestureMode = 'idle'
  1667. this.resetPinchState()
  1668. this.panVelocityX = 0
  1669. this.panVelocityY = 0
  1670. this.clearInertiaTimer()
  1671. this.animatePreviewToRest()
  1672. this.renderer.setAnimationPaused(false)
  1673. this.scheduleAutoRotate()
  1674. }
  1675. handleMapTap(stageX: number, stageY: number): void {
  1676. if (!this.gameRuntime.definition || !this.gameRuntime.state || this.gameRuntime.definition.mode !== 'score-o') {
  1677. return
  1678. }
  1679. const focusedControlId = this.findFocusableControlAt(stageX, stageY)
  1680. if (focusedControlId === undefined) {
  1681. return
  1682. }
  1683. const gameResult = this.gameRuntime.dispatch({
  1684. type: 'control_focused',
  1685. at: Date.now(),
  1686. controlId: focusedControlId,
  1687. })
  1688. this.gamePresentation = gameResult.presentation
  1689. this.telemetryRuntime.syncGameState(this.gameRuntime.definition, this.gameRuntime.state, this.getHudTargetControlId())
  1690. this.setState({
  1691. ...this.getGameViewPatch(focusedControlId ? `已选择目标点 (${this.buildVersion})` : `已取消目标点选择 (${this.buildVersion})`),
  1692. }, true)
  1693. this.syncRenderer()
  1694. }
  1695. findFocusableControlAt(stageX: number, stageY: number): string | null | undefined {
  1696. if (!this.gameRuntime.definition || !this.courseData || !this.state.stageWidth || !this.state.stageHeight) {
  1697. return undefined
  1698. }
  1699. const focusableControls = this.gameRuntime.definition.controls.filter((control) => (
  1700. this.gamePresentation.map.focusableControlIds.includes(control.id)
  1701. ))
  1702. let matchedControlId: string | null | undefined
  1703. let matchedDistance = Number.POSITIVE_INFINITY
  1704. const hitRadiusPx = Math.max(28, this.getControlHitRadiusPx())
  1705. for (const control of focusableControls) {
  1706. const screenPoint = this.getControlScreenPoint(control.id)
  1707. if (!screenPoint) {
  1708. continue
  1709. }
  1710. const distancePx = Math.sqrt(
  1711. Math.pow(screenPoint.x - stageX, 2)
  1712. + Math.pow(screenPoint.y - stageY, 2),
  1713. )
  1714. if (distancePx <= hitRadiusPx && distancePx < matchedDistance) {
  1715. matchedDistance = distancePx
  1716. matchedControlId = control.id
  1717. }
  1718. }
  1719. if (matchedControlId === undefined) {
  1720. return undefined
  1721. }
  1722. return matchedControlId === this.gamePresentation.map.focusedControlId ? null : matchedControlId
  1723. }
  1724. getControlHitRadiusPx(): number {
  1725. if (!this.state.tileSizePx) {
  1726. return 28
  1727. }
  1728. const centerLonLat = worldTileToLonLat({ x: this.state.centerTileX + 0.5, y: this.state.centerTileY + 0.5 }, this.state.zoom)
  1729. const metersPerTile = Math.cos(centerLonLat.lat * Math.PI / 180) * 40075016.686 / Math.pow(2, this.state.zoom)
  1730. if (!metersPerTile) {
  1731. return 28
  1732. }
  1733. const pixelsPerMeter = this.state.tileSizePx / metersPerTile
  1734. return Math.max(28, this.cpRadiusMeters * pixelsPerMeter * 1.6)
  1735. }
  1736. handleRecenter(): void {
  1737. this.clearInertiaTimer()
  1738. this.clearPreviewResetTimer()
  1739. this.panVelocityX = 0
  1740. this.panVelocityY = 0
  1741. this.renderer.setAnimationPaused(false)
  1742. this.commitViewport(
  1743. {
  1744. zoom: this.defaultZoom,
  1745. centerTileX: this.defaultCenterTileX,
  1746. centerTileY: this.defaultCenterTileY,
  1747. tileTranslateX: 0,
  1748. tileTranslateY: 0,
  1749. },
  1750. `已回到单 WebGL 引擎默认首屏 (${this.buildVersion})`,
  1751. true,
  1752. () => {
  1753. this.resetPreviewState()
  1754. this.syncRenderer()
  1755. this.compassController.start()
  1756. this.scheduleAutoRotate()
  1757. },
  1758. )
  1759. }
  1760. handleRotateStep(stepDeg = ROTATE_STEP_DEG): void {
  1761. if (this.state.rotationMode === 'auto') {
  1762. this.setState({
  1763. statusText: `当前不是手动旋转模式,请先切回手动 (${this.buildVersion})`,
  1764. }, true)
  1765. return
  1766. }
  1767. const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
  1768. const nextRotationDeg = normalizeRotationDeg(this.state.rotationDeg + stepDeg)
  1769. const resolvedViewport = this.resolveViewportForExactCenter(exactCenter.x, exactCenter.y, nextRotationDeg)
  1770. this.clearInertiaTimer()
  1771. this.clearPreviewResetTimer()
  1772. this.panVelocityX = 0
  1773. this.panVelocityY = 0
  1774. this.renderer.setAnimationPaused(false)
  1775. this.commitViewport(
  1776. {
  1777. ...resolvedViewport,
  1778. rotationDeg: nextRotationDeg,
  1779. rotationText: formatRotationText(nextRotationDeg),
  1780. },
  1781. `旋转角度调整到 ${formatRotationText(nextRotationDeg)} (${this.buildVersion})`,
  1782. true,
  1783. () => {
  1784. this.resetPreviewState()
  1785. this.syncRenderer()
  1786. this.compassController.start()
  1787. },
  1788. )
  1789. }
  1790. handleRotationReset(): void {
  1791. if (this.state.rotationMode === 'auto') {
  1792. this.setState({
  1793. statusText: `当前不是手动旋转模式,请先切回手动 (${this.buildVersion})`,
  1794. }, true)
  1795. return
  1796. }
  1797. const targetRotationDeg = MAP_NORTH_OFFSET_DEG
  1798. if (Math.abs(normalizeAngleDeltaDeg(this.state.rotationDeg - targetRotationDeg)) <= 0.01) {
  1799. return
  1800. }
  1801. const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
  1802. const resolvedViewport = this.resolveViewportForExactCenter(exactCenter.x, exactCenter.y, targetRotationDeg)
  1803. this.clearInertiaTimer()
  1804. this.clearPreviewResetTimer()
  1805. this.panVelocityX = 0
  1806. this.panVelocityY = 0
  1807. this.renderer.setAnimationPaused(false)
  1808. this.commitViewport(
  1809. {
  1810. ...resolvedViewport,
  1811. rotationDeg: targetRotationDeg,
  1812. rotationText: formatRotationText(targetRotationDeg),
  1813. },
  1814. `旋转角度已回到真北参考 (${this.buildVersion})`,
  1815. true,
  1816. () => {
  1817. this.resetPreviewState()
  1818. this.syncRenderer()
  1819. this.compassController.start()
  1820. },
  1821. )
  1822. }
  1823. handleToggleRotationMode(): void {
  1824. if (this.state.orientationMode === 'manual') {
  1825. this.setNorthUpMode()
  1826. return
  1827. }
  1828. if (this.state.orientationMode === 'north-up') {
  1829. this.setHeadingUpMode()
  1830. return
  1831. }
  1832. this.setManualMode()
  1833. }
  1834. handleSetManualMode(): void {
  1835. this.setManualMode()
  1836. }
  1837. handleSetNorthUpMode(): void {
  1838. this.setNorthUpMode()
  1839. }
  1840. handleSetHeadingUpMode(): void {
  1841. this.setHeadingUpMode()
  1842. }
  1843. handleCycleNorthReferenceMode(): void {
  1844. this.cycleNorthReferenceMode()
  1845. }
  1846. handleAutoRotateCalibrate(): void {
  1847. if (this.state.orientationMode !== 'heading-up') {
  1848. this.setState({
  1849. statusText: `请先切到朝向朝上模式再校准 (${this.buildVersion})`,
  1850. }, true)
  1851. return
  1852. }
  1853. if (!this.calibrateAutoRotateToCurrentOrientation()) {
  1854. this.setState({
  1855. statusText: `当前还没有传感器方向数据,暂时无法校准 (${this.buildVersion})`,
  1856. }, true)
  1857. return
  1858. }
  1859. this.setState({
  1860. statusText: `已按当前持机方向完成朝向校准 (${this.buildVersion})`,
  1861. }, true)
  1862. this.scheduleAutoRotate()
  1863. }
  1864. setManualMode(): void {
  1865. this.clearAutoRotateTimer()
  1866. this.targetAutoRotationDeg = null
  1867. this.autoRotateCalibrationPending = false
  1868. this.setState({
  1869. rotationMode: 'manual',
  1870. rotationModeText: formatRotationModeText('manual'),
  1871. rotationToggleText: formatRotationToggleText('manual'),
  1872. orientationMode: 'manual',
  1873. orientationModeText: formatOrientationModeText('manual'),
  1874. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, this.autoRotateCalibrationOffsetDeg),
  1875. statusText: `已切回手动地图旋转 (${this.buildVersion})`,
  1876. }, true)
  1877. }
  1878. setNorthUpMode(): void {
  1879. this.clearAutoRotateTimer()
  1880. this.targetAutoRotationDeg = null
  1881. this.autoRotateCalibrationPending = false
  1882. const mapNorthOffsetDeg = MAP_NORTH_OFFSET_DEG
  1883. this.autoRotateCalibrationOffsetDeg = mapNorthOffsetDeg
  1884. const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
  1885. const resolvedViewport = this.resolveViewportForExactCenter(exactCenter.x, exactCenter.y, mapNorthOffsetDeg)
  1886. this.commitViewport(
  1887. {
  1888. ...resolvedViewport,
  1889. rotationDeg: mapNorthOffsetDeg,
  1890. rotationText: formatRotationText(mapNorthOffsetDeg),
  1891. rotationMode: 'manual',
  1892. rotationModeText: formatRotationModeText('north-up'),
  1893. rotationToggleText: formatRotationToggleText('north-up'),
  1894. orientationMode: 'north-up',
  1895. orientationModeText: formatOrientationModeText('north-up'),
  1896. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, mapNorthOffsetDeg),
  1897. northReferenceText: formatNorthReferenceText(this.northReferenceMode),
  1898. },
  1899. `地图已固定为真北朝上 (${this.buildVersion})`,
  1900. true,
  1901. () => {
  1902. this.resetPreviewState()
  1903. this.syncRenderer()
  1904. },
  1905. )
  1906. }
  1907. setHeadingUpMode(): void {
  1908. this.autoRotateCalibrationPending = false
  1909. this.autoRotateCalibrationOffsetDeg = getMapNorthOffsetDeg(this.northReferenceMode)
  1910. this.targetAutoRotationDeg = null
  1911. this.setState({
  1912. rotationMode: 'auto',
  1913. rotationModeText: formatRotationModeText('heading-up'),
  1914. rotationToggleText: formatRotationToggleText('heading-up'),
  1915. orientationMode: 'heading-up',
  1916. orientationModeText: formatOrientationModeText('heading-up'),
  1917. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, this.autoRotateCalibrationOffsetDeg),
  1918. northReferenceText: formatNorthReferenceText(this.northReferenceMode),
  1919. statusText: `正在启用朝向朝上模式 (${this.buildVersion})`,
  1920. }, true)
  1921. if (this.refreshAutoRotateTarget()) {
  1922. this.scheduleAutoRotate()
  1923. }
  1924. }
  1925. handleCompassHeading(headingDeg: number): void {
  1926. this.sensorHeadingDeg = normalizeRotationDeg(headingDeg)
  1927. this.smoothedSensorHeadingDeg = this.smoothedSensorHeadingDeg === null
  1928. ? this.sensorHeadingDeg
  1929. : interpolateAngleDeg(this.smoothedSensorHeadingDeg, this.sensorHeadingDeg, AUTO_ROTATE_HEADING_SMOOTHING)
  1930. const compassHeadingDeg = getCompassReferenceHeadingDeg(this.northReferenceMode, this.smoothedSensorHeadingDeg)
  1931. this.compassDisplayHeadingDeg = this.compassDisplayHeadingDeg === null
  1932. ? compassHeadingDeg
  1933. : interpolateAngleDeg(this.compassDisplayHeadingDeg, compassHeadingDeg, COMPASS_NEEDLE_SMOOTHING)
  1934. this.autoRotateHeadingDeg = this.resolveAutoRotateInputHeadingDeg()
  1935. this.setState({
  1936. sensorHeadingText: formatHeadingText(compassHeadingDeg),
  1937. compassDeclinationText: formatCompassDeclinationText(this.northReferenceMode),
  1938. northReferenceButtonText: formatNorthReferenceButtonText(this.northReferenceMode),
  1939. autoRotateSourceText: formatAutoRotateSourceText(this.autoRotateSourceMode, this.courseHeadingDeg !== null),
  1940. compassNeedleDeg: formatCompassNeedleDegForMode(this.northReferenceMode, this.smoothedSensorHeadingDeg),
  1941. northReferenceText: formatNorthReferenceText(this.northReferenceMode),
  1942. })
  1943. if (!this.refreshAutoRotateTarget()) {
  1944. return
  1945. }
  1946. if (this.state.orientationMode === 'heading-up') {
  1947. this.scheduleAutoRotate()
  1948. }
  1949. }
  1950. handleCompassError(message: string): void {
  1951. this.clearAutoRotateTimer()
  1952. this.targetAutoRotationDeg = null
  1953. this.autoRotateCalibrationPending = false
  1954. this.setState({
  1955. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, this.autoRotateCalibrationOffsetDeg),
  1956. statusText: `${message} (${this.buildVersion})`,
  1957. }, true)
  1958. }
  1959. cycleNorthReferenceMode(): void {
  1960. const nextMode = getNextNorthReferenceMode(this.northReferenceMode)
  1961. const nextMapNorthOffsetDeg = getMapNorthOffsetDeg(nextMode)
  1962. const compassHeadingDeg = this.smoothedSensorHeadingDeg === null
  1963. ? null
  1964. : getCompassReferenceHeadingDeg(nextMode, this.smoothedSensorHeadingDeg)
  1965. this.northReferenceMode = nextMode
  1966. this.autoRotateCalibrationOffsetDeg = nextMapNorthOffsetDeg
  1967. this.compassDisplayHeadingDeg = compassHeadingDeg
  1968. if (this.state.orientationMode === 'north-up') {
  1969. const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
  1970. const resolvedViewport = this.resolveViewportForExactCenter(exactCenter.x, exactCenter.y, MAP_NORTH_OFFSET_DEG)
  1971. this.commitViewport(
  1972. {
  1973. ...resolvedViewport,
  1974. rotationDeg: MAP_NORTH_OFFSET_DEG,
  1975. rotationText: formatRotationText(MAP_NORTH_OFFSET_DEG),
  1976. northReferenceText: formatNorthReferenceText(nextMode),
  1977. sensorHeadingText: formatHeadingText(compassHeadingDeg),
  1978. compassDeclinationText: formatCompassDeclinationText(nextMode),
  1979. northReferenceButtonText: formatNorthReferenceButtonText(nextMode),
  1980. compassNeedleDeg: formatCompassNeedleDegForMode(nextMode, this.smoothedSensorHeadingDeg),
  1981. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, nextMapNorthOffsetDeg),
  1982. },
  1983. `${formatNorthReferenceStatusText(nextMode)} (${this.buildVersion})`,
  1984. true,
  1985. () => {
  1986. this.resetPreviewState()
  1987. this.syncRenderer()
  1988. },
  1989. )
  1990. return
  1991. }
  1992. this.setState({
  1993. northReferenceText: formatNorthReferenceText(nextMode),
  1994. sensorHeadingText: formatHeadingText(compassHeadingDeg),
  1995. compassDeclinationText: formatCompassDeclinationText(nextMode),
  1996. northReferenceButtonText: formatNorthReferenceButtonText(nextMode),
  1997. compassNeedleDeg: formatCompassNeedleDegForMode(nextMode, this.smoothedSensorHeadingDeg),
  1998. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, nextMapNorthOffsetDeg),
  1999. statusText: `${formatNorthReferenceStatusText(nextMode)} (${this.buildVersion})`,
  2000. }, true)
  2001. if (this.state.orientationMode === 'heading-up' && this.refreshAutoRotateTarget()) {
  2002. this.scheduleAutoRotate()
  2003. }
  2004. }
  2005. setCourseHeading(headingDeg: number | null): void {
  2006. this.courseHeadingDeg = headingDeg === null ? null : normalizeRotationDeg(headingDeg)
  2007. this.setState({
  2008. autoRotateSourceText: formatAutoRotateSourceText(this.autoRotateSourceMode, this.courseHeadingDeg !== null),
  2009. })
  2010. if (this.refreshAutoRotateTarget()) {
  2011. this.scheduleAutoRotate()
  2012. }
  2013. }
  2014. resolveAutoRotateInputHeadingDeg(): number | null {
  2015. const sensorHeadingDeg = this.smoothedSensorHeadingDeg === null
  2016. ? null
  2017. : getMapReferenceHeadingDegFromSensor(this.northReferenceMode, this.smoothedSensorHeadingDeg)
  2018. const courseHeadingDeg = this.courseHeadingDeg === null
  2019. ? null
  2020. : getMapReferenceHeadingDegFromCourse(this.northReferenceMode, this.courseHeadingDeg)
  2021. if (this.autoRotateSourceMode === 'sensor') {
  2022. return sensorHeadingDeg
  2023. }
  2024. if (this.autoRotateSourceMode === 'course') {
  2025. return courseHeadingDeg === null ? sensorHeadingDeg : courseHeadingDeg
  2026. }
  2027. if (sensorHeadingDeg !== null && courseHeadingDeg !== null) {
  2028. return interpolateAngleDeg(sensorHeadingDeg, courseHeadingDeg, 0.35)
  2029. }
  2030. return sensorHeadingDeg === null ? courseHeadingDeg : sensorHeadingDeg
  2031. }
  2032. calibrateAutoRotateToCurrentOrientation(): boolean {
  2033. const inputHeadingDeg = this.resolveAutoRotateInputHeadingDeg()
  2034. if (inputHeadingDeg === null) {
  2035. return false
  2036. }
  2037. this.autoRotateCalibrationOffsetDeg = normalizeRotationDeg(this.state.rotationDeg + inputHeadingDeg)
  2038. this.autoRotateCalibrationPending = false
  2039. this.targetAutoRotationDeg = normalizeRotationDeg(this.autoRotateCalibrationOffsetDeg - inputHeadingDeg)
  2040. this.setState({
  2041. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, this.autoRotateCalibrationOffsetDeg),
  2042. })
  2043. return true
  2044. }
  2045. refreshAutoRotateTarget(): boolean {
  2046. const inputHeadingDeg = this.resolveAutoRotateInputHeadingDeg()
  2047. if (inputHeadingDeg === null) {
  2048. return false
  2049. }
  2050. if (this.autoRotateCalibrationPending || this.autoRotateCalibrationOffsetDeg === null) {
  2051. if (!this.calibrateAutoRotateToCurrentOrientation()) {
  2052. return false
  2053. }
  2054. return true
  2055. }
  2056. this.targetAutoRotationDeg = normalizeRotationDeg(this.autoRotateCalibrationOffsetDeg - inputHeadingDeg)
  2057. this.setState({
  2058. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, this.autoRotateCalibrationOffsetDeg),
  2059. })
  2060. return true
  2061. }
  2062. scheduleAutoRotate(): void {
  2063. if (this.autoRotateTimer || this.state.rotationMode !== 'auto' || this.targetAutoRotationDeg === null) {
  2064. return
  2065. }
  2066. const step = () => {
  2067. this.autoRotateTimer = 0
  2068. if (this.state.rotationMode !== 'auto' || this.targetAutoRotationDeg === null) {
  2069. return
  2070. }
  2071. if (this.gestureMode !== 'idle' || this.inertiaTimer || this.previewResetTimer) {
  2072. this.scheduleAutoRotate()
  2073. return
  2074. }
  2075. const currentRotationDeg = this.state.rotationDeg
  2076. const deltaDeg = normalizeAngleDeltaDeg(this.targetAutoRotationDeg - currentRotationDeg)
  2077. if (Math.abs(deltaDeg) <= AUTO_ROTATE_SNAP_DEG) {
  2078. if (Math.abs(deltaDeg) > 0.01) {
  2079. this.applyAutoRotation(this.targetAutoRotationDeg)
  2080. }
  2081. this.scheduleAutoRotate()
  2082. return
  2083. }
  2084. if (Math.abs(deltaDeg) <= AUTO_ROTATE_DEADZONE_DEG) {
  2085. this.scheduleAutoRotate()
  2086. return
  2087. }
  2088. const easedStepDeg = clamp(deltaDeg * AUTO_ROTATE_EASE, -AUTO_ROTATE_MAX_STEP_DEG, AUTO_ROTATE_MAX_STEP_DEG)
  2089. this.applyAutoRotation(normalizeRotationDeg(currentRotationDeg + easedStepDeg))
  2090. this.scheduleAutoRotate()
  2091. }
  2092. this.autoRotateTimer = setTimeout(step, AUTO_ROTATE_FRAME_MS) as unknown as number
  2093. }
  2094. applyAutoRotation(nextRotationDeg: number): void {
  2095. const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
  2096. const resolvedViewport = this.resolveViewportForExactCenter(exactCenter.x, exactCenter.y, nextRotationDeg)
  2097. this.setState({
  2098. ...resolvedViewport,
  2099. rotationDeg: nextRotationDeg,
  2100. rotationText: formatRotationText(nextRotationDeg),
  2101. centerText: buildCenterText(this.state.zoom, resolvedViewport.centerTileX, resolvedViewport.centerTileY),
  2102. })
  2103. this.syncRenderer()
  2104. }
  2105. applyStats(stats: MapRendererStats): void {
  2106. this.setState({
  2107. visibleTileCount: stats.visibleTileCount,
  2108. readyTileCount: stats.readyTileCount,
  2109. memoryTileCount: stats.memoryTileCount,
  2110. diskTileCount: stats.diskTileCount,
  2111. memoryHitCount: stats.memoryHitCount,
  2112. diskHitCount: stats.diskHitCount,
  2113. networkFetchCount: stats.networkFetchCount,
  2114. cacheHitRateText: formatCacheHitRate(stats.memoryHitCount, stats.diskHitCount, stats.networkFetchCount),
  2115. })
  2116. }
  2117. setState(patch: Partial<MapEngineViewState>, immediateUi = false): void {
  2118. this.state = {
  2119. ...this.state,
  2120. ...patch,
  2121. }
  2122. const viewPatch = this.pickViewPatch(patch)
  2123. if (!Object.keys(viewPatch).length) {
  2124. return
  2125. }
  2126. this.pendingViewPatch = {
  2127. ...this.pendingViewPatch,
  2128. ...viewPatch,
  2129. }
  2130. if (immediateUi) {
  2131. this.flushViewPatch()
  2132. return
  2133. }
  2134. if (this.viewSyncTimer) {
  2135. return
  2136. }
  2137. this.viewSyncTimer = setTimeout(() => {
  2138. this.viewSyncTimer = 0
  2139. this.flushViewPatch()
  2140. }, UI_SYNC_INTERVAL_MS) as unknown as number
  2141. }
  2142. commitViewport(
  2143. patch: Partial<MapEngineViewState>,
  2144. statusText: string,
  2145. immediateUi = false,
  2146. afterUpdate?: () => void,
  2147. ): void {
  2148. const nextZoom = typeof patch.zoom === 'number' ? patch.zoom : this.state.zoom
  2149. const nextCenterTileX = typeof patch.centerTileX === 'number' ? patch.centerTileX : this.state.centerTileX
  2150. const nextCenterTileY = typeof patch.centerTileY === 'number' ? patch.centerTileY : this.state.centerTileY
  2151. const nextStageWidth = typeof patch.stageWidth === 'number' ? patch.stageWidth : this.state.stageWidth
  2152. const nextStageHeight = typeof patch.stageHeight === 'number' ? patch.stageHeight : this.state.stageHeight
  2153. const tileSizePx = getTileSizePx({
  2154. centerWorldX: nextCenterTileX,
  2155. centerWorldY: nextCenterTileY,
  2156. viewportWidth: nextStageWidth,
  2157. viewportHeight: nextStageHeight,
  2158. visibleColumns: DESIRED_VISIBLE_COLUMNS,
  2159. })
  2160. this.setState({
  2161. ...patch,
  2162. tileSizePx,
  2163. centerText: buildCenterText(nextZoom, nextCenterTileX, nextCenterTileY),
  2164. statusText,
  2165. }, immediateUi)
  2166. this.syncRenderer()
  2167. this.compassController.start()
  2168. if (afterUpdate) {
  2169. afterUpdate()
  2170. }
  2171. }
  2172. buildScene() {
  2173. const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
  2174. return {
  2175. tileSource: this.state.tileSource,
  2176. osmTileSource: OSM_TILE_SOURCE,
  2177. zoom: this.state.zoom,
  2178. centerTileX: this.state.centerTileX,
  2179. centerTileY: this.state.centerTileY,
  2180. exactCenterWorldX: exactCenter.x,
  2181. exactCenterWorldY: exactCenter.y,
  2182. tileBoundsByZoom: this.tileBoundsByZoom,
  2183. viewportWidth: this.state.stageWidth,
  2184. viewportHeight: this.state.stageHeight,
  2185. visibleColumns: DESIRED_VISIBLE_COLUMNS,
  2186. overdraw: OVERDRAW,
  2187. translateX: this.state.tileTranslateX,
  2188. translateY: this.state.tileTranslateY,
  2189. rotationRad: this.getRotationRad(this.state.rotationDeg),
  2190. previewScale: this.previewScale || 1,
  2191. previewOriginX: this.previewOriginX || this.state.stageWidth / 2,
  2192. previewOriginY: this.previewOriginY || this.state.stageHeight / 2,
  2193. track: this.currentGpsTrack,
  2194. gpsPoint: this.currentGpsPoint,
  2195. gpsCalibration: GPS_MAP_CALIBRATION,
  2196. gpsCalibrationOrigin: worldTileToLonLat({ x: this.defaultCenterTileX, y: this.defaultCenterTileY }, this.defaultZoom),
  2197. course: this.courseOverlayVisible ? this.courseData : null,
  2198. cpRadiusMeters: this.cpRadiusMeters,
  2199. controlVisualMode: this.gamePresentation.map.controlVisualMode,
  2200. showCourseLegs: this.gamePresentation.map.showCourseLegs,
  2201. guidanceLegAnimationEnabled: this.gamePresentation.map.guidanceLegAnimationEnabled,
  2202. focusableControlIds: this.gamePresentation.map.focusableControlIds,
  2203. focusedControlId: this.gamePresentation.map.focusedControlId,
  2204. focusedControlSequences: this.gamePresentation.map.focusedControlSequences,
  2205. activeControlSequences: this.gamePresentation.map.activeControlSequences,
  2206. activeStart: this.gamePresentation.map.activeStart,
  2207. completedStart: this.gamePresentation.map.completedStart,
  2208. activeFinish: this.gamePresentation.map.activeFinish,
  2209. focusedFinish: this.gamePresentation.map.focusedFinish,
  2210. completedFinish: this.gamePresentation.map.completedFinish,
  2211. revealFullCourse: this.gamePresentation.map.revealFullCourse,
  2212. activeLegIndices: this.gamePresentation.map.activeLegIndices,
  2213. completedLegIndices: this.gamePresentation.map.completedLegIndices,
  2214. completedControlSequences: this.gamePresentation.map.completedControlSequences,
  2215. osmReferenceEnabled: this.state.osmReferenceEnabled,
  2216. overlayOpacity: MAP_OVERLAY_OPACITY,
  2217. }
  2218. }
  2219. syncRenderer(): void {
  2220. if (!this.mounted || !this.state.stageWidth || !this.state.stageHeight) {
  2221. return
  2222. }
  2223. this.renderer.updateScene(this.buildScene())
  2224. }
  2225. getCameraState(rotationDeg = this.state.rotationDeg): CameraState {
  2226. return {
  2227. centerWorldX: this.state.centerTileX + 0.5,
  2228. centerWorldY: this.state.centerTileY + 0.5,
  2229. viewportWidth: this.state.stageWidth,
  2230. viewportHeight: this.state.stageHeight,
  2231. visibleColumns: DESIRED_VISIBLE_COLUMNS,
  2232. translateX: this.state.tileTranslateX,
  2233. translateY: this.state.tileTranslateY,
  2234. rotationRad: this.getRotationRad(rotationDeg),
  2235. }
  2236. }
  2237. getRotationRad(rotationDeg = this.state.rotationDeg): number {
  2238. return normalizeRotationDeg(rotationDeg) * Math.PI / 180
  2239. }
  2240. getBaseCamera(centerTileX = this.state.centerTileX, centerTileY = this.state.centerTileY, rotationDeg = this.state.rotationDeg): CameraState {
  2241. return {
  2242. centerWorldX: centerTileX + 0.5,
  2243. centerWorldY: centerTileY + 0.5,
  2244. viewportWidth: this.state.stageWidth,
  2245. viewportHeight: this.state.stageHeight,
  2246. visibleColumns: DESIRED_VISIBLE_COLUMNS,
  2247. rotationRad: this.getRotationRad(rotationDeg),
  2248. }
  2249. }
  2250. getWorldOffsetFromScreen(stageX: number, stageY: number, rotationDeg = this.state.rotationDeg): { x: number; y: number } {
  2251. const baseCamera = {
  2252. centerWorldX: 0,
  2253. centerWorldY: 0,
  2254. viewportWidth: this.state.stageWidth,
  2255. viewportHeight: this.state.stageHeight,
  2256. visibleColumns: DESIRED_VISIBLE_COLUMNS,
  2257. rotationRad: this.getRotationRad(rotationDeg),
  2258. }
  2259. return screenToWorld(baseCamera, { x: stageX, y: stageY }, false)
  2260. }
  2261. getExactCenterFromTranslate(translateX: number, translateY: number): { x: number; y: number } {
  2262. if (!this.state.stageWidth || !this.state.stageHeight) {
  2263. return {
  2264. x: this.state.centerTileX + 0.5,
  2265. y: this.state.centerTileY + 0.5,
  2266. }
  2267. }
  2268. const screenCenterX = this.state.stageWidth / 2
  2269. const screenCenterY = this.state.stageHeight / 2
  2270. return screenToWorld(this.getBaseCamera(), {
  2271. x: screenCenterX - translateX,
  2272. y: screenCenterY - translateY,
  2273. }, false)
  2274. }
  2275. resolveViewportForExactCenter(centerWorldX: number, centerWorldY: number, rotationDeg = this.state.rotationDeg): {
  2276. centerTileX: number
  2277. centerTileY: number
  2278. tileTranslateX: number
  2279. tileTranslateY: number
  2280. } {
  2281. const nextCenterTileX = Math.floor(centerWorldX)
  2282. const nextCenterTileY = Math.floor(centerWorldY)
  2283. if (!this.state.stageWidth || !this.state.stageHeight) {
  2284. return {
  2285. centerTileX: nextCenterTileX,
  2286. centerTileY: nextCenterTileY,
  2287. tileTranslateX: 0,
  2288. tileTranslateY: 0,
  2289. }
  2290. }
  2291. const roundedCamera = this.getBaseCamera(nextCenterTileX, nextCenterTileY, rotationDeg)
  2292. const projectedCenter = worldToScreen(roundedCamera, { x: centerWorldX, y: centerWorldY }, false)
  2293. return {
  2294. centerTileX: nextCenterTileX,
  2295. centerTileY: nextCenterTileY,
  2296. tileTranslateX: this.state.stageWidth / 2 - projectedCenter.x,
  2297. tileTranslateY: this.state.stageHeight / 2 - projectedCenter.y,
  2298. }
  2299. }
  2300. setPreviewState(scale: number, originX: number, originY: number): void {
  2301. this.previewScale = scale
  2302. this.previewOriginX = originX
  2303. this.previewOriginY = originY
  2304. }
  2305. resetPreviewState(): void {
  2306. this.setPreviewState(1, this.state.stageWidth / 2, this.state.stageHeight / 2)
  2307. }
  2308. resetPinchState(): void {
  2309. this.pinchStartDistance = 0
  2310. this.pinchStartScale = 1
  2311. this.pinchStartAngle = 0
  2312. this.pinchStartRotationDeg = this.state.rotationDeg
  2313. this.pinchAnchorWorldX = 0
  2314. this.pinchAnchorWorldY = 0
  2315. }
  2316. clearPreviewResetTimer(): void {
  2317. if (this.previewResetTimer) {
  2318. clearTimeout(this.previewResetTimer)
  2319. this.previewResetTimer = 0
  2320. }
  2321. }
  2322. clearInertiaTimer(): void {
  2323. if (this.inertiaTimer) {
  2324. clearTimeout(this.inertiaTimer)
  2325. this.inertiaTimer = 0
  2326. }
  2327. }
  2328. clearViewSyncTimer(): void {
  2329. if (this.viewSyncTimer) {
  2330. clearTimeout(this.viewSyncTimer)
  2331. this.viewSyncTimer = 0
  2332. }
  2333. }
  2334. clearAutoRotateTimer(): void {
  2335. if (this.autoRotateTimer) {
  2336. clearTimeout(this.autoRotateTimer)
  2337. this.autoRotateTimer = 0
  2338. }
  2339. }
  2340. pickViewPatch(patch: Partial<MapEngineViewState>): Partial<MapEngineViewState> {
  2341. const viewPatch = {} as Partial<MapEngineViewState>
  2342. for (const key of VIEW_SYNC_KEYS) {
  2343. if (Object.prototype.hasOwnProperty.call(patch, key)) {
  2344. ;(viewPatch as any)[key] = patch[key]
  2345. }
  2346. }
  2347. return viewPatch
  2348. }
  2349. flushViewPatch(): void {
  2350. if (!Object.keys(this.pendingViewPatch).length) {
  2351. return
  2352. }
  2353. const patch = this.pendingViewPatch
  2354. this.pendingViewPatch = {}
  2355. this.onData(patch)
  2356. }
  2357. getTouchDistance(touches: TouchPoint[]): number {
  2358. if (touches.length < 2) {
  2359. return 0
  2360. }
  2361. const first = touches[0]
  2362. const second = touches[1]
  2363. const deltaX = first.pageX - second.pageX
  2364. const deltaY = first.pageY - second.pageY
  2365. return Math.sqrt(deltaX * deltaX + deltaY * deltaY)
  2366. }
  2367. getTouchAngle(touches: TouchPoint[]): number {
  2368. if (touches.length < 2) {
  2369. return 0
  2370. }
  2371. const first = touches[0]
  2372. const second = touches[1]
  2373. return Math.atan2(second.pageY - first.pageY, second.pageX - first.pageX)
  2374. }
  2375. getStagePoint(touches: TouchPoint[]): { x: number; y: number } {
  2376. if (!touches.length) {
  2377. return {
  2378. x: this.state.stageWidth / 2,
  2379. y: this.state.stageHeight / 2,
  2380. }
  2381. }
  2382. let pageX = 0
  2383. let pageY = 0
  2384. for (const touch of touches) {
  2385. pageX += touch.pageX
  2386. pageY += touch.pageY
  2387. }
  2388. return {
  2389. x: pageX / touches.length - this.state.stageLeft,
  2390. y: pageY / touches.length - this.state.stageTop,
  2391. }
  2392. }
  2393. animatePreviewToRest(): void {
  2394. this.clearPreviewResetTimer()
  2395. const startScale = this.previewScale || 1
  2396. const originX = this.previewOriginX || this.state.stageWidth / 2
  2397. const originY = this.previewOriginY || this.state.stageHeight / 2
  2398. if (Math.abs(startScale - 1) < 0.01) {
  2399. this.resetPreviewState()
  2400. this.syncRenderer()
  2401. this.compassController.start()
  2402. this.scheduleAutoRotate()
  2403. return
  2404. }
  2405. const startAt = Date.now()
  2406. const step = () => {
  2407. const progress = Math.min(1, (Date.now() - startAt) / PREVIEW_RESET_DURATION_MS)
  2408. const eased = 1 - Math.pow(1 - progress, 3)
  2409. const nextScale = startScale + (1 - startScale) * eased
  2410. this.setPreviewState(nextScale, originX, originY)
  2411. this.syncRenderer()
  2412. this.compassController.start()
  2413. if (progress >= 1) {
  2414. this.resetPreviewState()
  2415. this.syncRenderer()
  2416. this.compassController.start()
  2417. this.previewResetTimer = 0
  2418. this.scheduleAutoRotate()
  2419. return
  2420. }
  2421. this.previewResetTimer = setTimeout(step, INERTIA_FRAME_MS) as unknown as number
  2422. }
  2423. step()
  2424. }
  2425. normalizeTranslate(translateX: number, translateY: number, statusText: string): void {
  2426. if (!this.state.stageWidth) {
  2427. this.setState({
  2428. tileTranslateX: translateX,
  2429. tileTranslateY: translateY,
  2430. })
  2431. this.syncRenderer()
  2432. this.compassController.start()
  2433. return
  2434. }
  2435. const exactCenter = this.getExactCenterFromTranslate(translateX, translateY)
  2436. const resolvedViewport = this.resolveViewportForExactCenter(exactCenter.x, exactCenter.y)
  2437. const centerChanged = resolvedViewport.centerTileX !== this.state.centerTileX || resolvedViewport.centerTileY !== this.state.centerTileY
  2438. if (centerChanged) {
  2439. this.commitViewport(resolvedViewport, statusText)
  2440. return
  2441. }
  2442. this.setState({
  2443. tileTranslateX: resolvedViewport.tileTranslateX,
  2444. tileTranslateY: resolvedViewport.tileTranslateY,
  2445. })
  2446. this.syncRenderer()
  2447. this.compassController.start()
  2448. }
  2449. zoomAroundPoint(zoomDelta: number, stageX: number, stageY: number, residualScale: number): void {
  2450. const nextZoom = clamp(this.state.zoom + zoomDelta, this.minZoom, this.maxZoom)
  2451. const appliedDelta = nextZoom - this.state.zoom
  2452. if (!appliedDelta) {
  2453. this.animatePreviewToRest()
  2454. return
  2455. }
  2456. if (!this.state.stageWidth || !this.state.stageHeight) {
  2457. this.commitViewport(
  2458. {
  2459. zoom: nextZoom,
  2460. centerTileX: appliedDelta > 0 ? this.state.centerTileX * 2 : Math.floor(this.state.centerTileX / 2),
  2461. centerTileY: appliedDelta > 0 ? this.state.centerTileY * 2 : Math.floor(this.state.centerTileY / 2),
  2462. tileTranslateX: 0,
  2463. tileTranslateY: 0,
  2464. },
  2465. `缩放级别调整到 ${nextZoom}`,
  2466. true,
  2467. () => {
  2468. this.setPreviewState(residualScale, stageX, stageY)
  2469. this.syncRenderer()
  2470. this.compassController.start()
  2471. this.animatePreviewToRest()
  2472. },
  2473. )
  2474. return
  2475. }
  2476. const camera = this.getCameraState()
  2477. const world = screenToWorld(camera, { x: stageX, y: stageY }, true)
  2478. const zoomFactor = Math.pow(2, appliedDelta)
  2479. const nextWorldX = world.x * zoomFactor
  2480. const nextWorldY = world.y * zoomFactor
  2481. const anchorOffset = this.getWorldOffsetFromScreen(stageX, stageY)
  2482. const exactCenterX = nextWorldX - anchorOffset.x
  2483. const exactCenterY = nextWorldY - anchorOffset.y
  2484. const resolvedViewport = this.resolveViewportForExactCenter(exactCenterX, exactCenterY)
  2485. this.commitViewport(
  2486. {
  2487. zoom: nextZoom,
  2488. ...resolvedViewport,
  2489. },
  2490. `缩放级别调整到 ${nextZoom}`,
  2491. true,
  2492. () => {
  2493. this.setPreviewState(residualScale, stageX, stageY)
  2494. this.syncRenderer()
  2495. this.compassController.start()
  2496. this.animatePreviewToRest()
  2497. },
  2498. )
  2499. }
  2500. startInertia(): void {
  2501. this.clearInertiaTimer()
  2502. const step = () => {
  2503. this.panVelocityX *= INERTIA_DECAY
  2504. this.panVelocityY *= INERTIA_DECAY
  2505. if (Math.abs(this.panVelocityX) < INERTIA_MIN_SPEED && Math.abs(this.panVelocityY) < INERTIA_MIN_SPEED) {
  2506. this.setState({
  2507. statusText: `惯性滑动结束 (${this.buildVersion})`,
  2508. })
  2509. this.renderer.setAnimationPaused(false)
  2510. this.inertiaTimer = 0
  2511. this.scheduleAutoRotate()
  2512. return
  2513. }
  2514. this.normalizeTranslate(
  2515. this.state.tileTranslateX + this.panVelocityX * INERTIA_FRAME_MS,
  2516. this.state.tileTranslateY + this.panVelocityY * INERTIA_FRAME_MS,
  2517. `惯性滑动中 (${this.buildVersion})`,
  2518. )
  2519. this.inertiaTimer = setTimeout(step, INERTIA_FRAME_MS) as unknown as number
  2520. }
  2521. this.inertiaTimer = setTimeout(step, INERTIA_FRAME_MS) as unknown as number
  2522. }
  2523. }