mapEngine.ts 91 KB

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