mapEngine.ts 102 KB

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