map.ts 98 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272
  1. import {
  2. MapEngine,
  3. type MapEngineGameInfoRow,
  4. type MapEngineGameInfoSnapshot,
  5. type MapEngineResultSnapshot,
  6. type MapEngineStageRect,
  7. type MapEngineViewState,
  8. } from '../../engine/map/mapEngine'
  9. import {
  10. getBackendSessionContextFromLaunchEnvelope,
  11. getDemoGameLaunchEnvelope,
  12. resolveGameLaunchEnvelope,
  13. type GameLaunchEnvelope,
  14. type MapPageLaunchOptions,
  15. } from '../../utils/gameLaunch'
  16. import { finishSession, startSession, type BackendSessionFinishSummaryPayload } from '../../utils/backendApi'
  17. import { loadBackendBaseUrl } from '../../utils/backendAuth'
  18. import { loadRemoteMapConfig, type RemoteMapConfig } from '../../utils/remoteMapConfig'
  19. import { type H5ExperienceFallbackPayload, type H5ExperienceRequest } from '../../game/experience/h5Experience'
  20. import { type TrackColorPreset } from '../../game/presentation/trackStyleConfig'
  21. import { type GpsMarkerColorPreset } from '../../game/presentation/gpsMarkerStyleConfig'
  22. import { type PlayerTelemetryProfile } from '../../game/telemetry/playerTelemetryProfile'
  23. import {
  24. DEFAULT_SETTING_LOCKS,
  25. DEFAULT_STORED_USER_SETTINGS,
  26. loadStoredUserSettings,
  27. mergeStoredUserSettings,
  28. persistStoredUserSettings,
  29. resolveSystemSettingsState,
  30. type SystemSettingsConfig,
  31. type CenterScaleRulerAnchorMode,
  32. type ResolvedSystemSettingsState,
  33. type SideButtonPlacement,
  34. type StoredUserSettings,
  35. } from '../../game/core/systemSettingsState'
  36. import {
  37. compileRuntimeProfile,
  38. } from '../../game/core/runtimeProfileCompiler'
  39. import {
  40. clearSessionRecoverySnapshot,
  41. loadSessionRecoverySnapshot,
  42. saveSessionRecoverySnapshot,
  43. type SessionRecoverySnapshot,
  44. } from '../../game/core/sessionRecovery'
  45. type CompassTickData = {
  46. angle: number
  47. long: boolean
  48. major: boolean
  49. }
  50. type CompassLabelData = {
  51. text: string
  52. angle: number
  53. rotateBack: number
  54. radius: number
  55. className: string
  56. }
  57. type ScaleRulerMinorTickData = {
  58. key: string
  59. topPx: number
  60. long: boolean
  61. }
  62. type ScaleRulerMajorMarkData = {
  63. key: string
  64. topPx: number
  65. label: string
  66. }
  67. type SideButtonMode = 'shown' | 'hidden'
  68. type SideActionButtonState = 'muted' | 'default' | 'active'
  69. type MapPageData = MapEngineViewState & {
  70. showDebugPanel: boolean
  71. showGameInfoPanel: boolean
  72. showResultScene: boolean
  73. showSystemSettingsPanel: boolean
  74. showHeartRateDevicePicker: boolean
  75. showCenterScaleRuler: boolean
  76. showPunchHintBanner: boolean
  77. punchHintFxClass: string
  78. centerScaleRulerAnchorMode: CenterScaleRulerAnchorMode
  79. statusBarHeight: number
  80. topInsetHeight: number
  81. hudPanelIndex: number
  82. configSourceText: string
  83. mockBridgeUrlDraft: string
  84. mockHeartRateBridgeUrlDraft: string
  85. mockDebugLogBridgeUrlDraft: string
  86. mockChannelIdDraft: string
  87. gameInfoTitle: string
  88. gameInfoSubtitle: string
  89. gameInfoLocalRows: MapEngineGameInfoRow[]
  90. gameInfoGlobalRows: MapEngineGameInfoRow[]
  91. resultSceneTitle: string
  92. resultSceneSubtitle: string
  93. resultSceneHeroLabel: string
  94. resultSceneHeroValue: string
  95. resultSceneRows: MapEngineGameInfoRow[]
  96. resultSceneCountdownText: string
  97. panelTimerText: string
  98. panelTimerMode: 'elapsed' | 'countdown'
  99. panelMileageText: string
  100. panelTargetSummaryText: string
  101. panelDistanceValueText: string
  102. panelProgressText: string
  103. panelSpeedValueText: string
  104. panelTimerFxClass: string
  105. panelMileageFxClass: string
  106. panelSpeedFxClass: string
  107. panelHeartRateFxClass: string
  108. compassTicks: CompassTickData[]
  109. compassLabels: CompassLabelData[]
  110. sideButtonMode: SideButtonMode
  111. sideButtonPlacement: SideButtonPlacement
  112. autoRotateEnabled: boolean
  113. lockAnimationLevel: boolean
  114. lockTrackMode: boolean
  115. lockTrackTailLength: boolean
  116. lockTrackColor: boolean
  117. lockTrackStyle: boolean
  118. lockGpsMarkerVisible: boolean
  119. lockGpsMarkerStyle: boolean
  120. lockGpsMarkerSize: boolean
  121. lockGpsMarkerColor: boolean
  122. lockSideButtonPlacement: boolean
  123. lockAutoRotate: boolean
  124. lockCompassTuning: boolean
  125. lockScaleRulerVisible: boolean
  126. lockScaleRulerAnchor: boolean
  127. lockNorthReference: boolean
  128. lockHeartRateDevice: boolean
  129. sideToggleIconSrc: string
  130. sideButton2Class: string
  131. sideButton4Class: string
  132. sideButton11Class: string
  133. sideButton12Class: string
  134. sideButton13Class: string
  135. sideButton14Class: string
  136. sideButton16Class: string
  137. centerScaleRulerVisible: boolean
  138. centerScaleRulerCenterXPx: number
  139. centerScaleRulerZeroYPx: number
  140. centerScaleRulerHeightPx: number
  141. centerScaleRulerAxisBottomPx: number
  142. centerScaleRulerZeroVisible: boolean
  143. centerScaleRulerZeroLabel: string
  144. centerScaleRulerMinorTicks: ScaleRulerMinorTickData[]
  145. centerScaleRulerMajorMarks: ScaleRulerMajorMarkData[]
  146. showLeftButtonGroup: boolean
  147. showRightButtonGroups: boolean
  148. showBottomDebugButton: boolean
  149. }
  150. function getGlobalTelemetryProfile(): PlayerTelemetryProfile | null {
  151. const app = getApp<IAppOption>()
  152. const profile = app.globalData && app.globalData.telemetryPlayerProfile
  153. return profile ? { ...profile } : null
  154. }
  155. const INTERNAL_BUILD_VERSION = 'map-build-293'
  156. const PUNCH_HINT_AUTO_HIDE_MS = 30000
  157. const PUNCH_HINT_FX_DURATION_MS = 420
  158. const PUNCH_HINT_HAPTIC_GAP_MS = 2400
  159. const SESSION_RECOVERY_PERSIST_INTERVAL_MS = 5000
  160. const RESULT_EXIT_REDIRECT_DELAY_MS = 3000
  161. let currentGameLaunchEnvelope: GameLaunchEnvelope = getDemoGameLaunchEnvelope()
  162. let mapEngine: MapEngine | null = null
  163. let stageCanvasAttached = false
  164. let gameInfoPanelSyncTimer = 0
  165. let centerScaleRulerSyncTimer = 0
  166. let contentAudioRecorder: WechatMiniprogram.RecorderManager | null = null
  167. let contentAudioRecording = false
  168. let centerScaleRulerUpdateTimer = 0
  169. let punchHintDismissTimer = 0
  170. let punchHintFxTimer = 0
  171. let panelTimerFxTimer = 0
  172. let panelMileageFxTimer = 0
  173. let panelSpeedFxTimer = 0
  174. let panelHeartRateFxTimer = 0
  175. let sessionRecoveryPersistTimer = 0
  176. let resultExitRedirectTimer = 0
  177. let resultExitCountdownTimer = 0
  178. let lastPunchHintHapticAt = 0
  179. let currentSystemSettingsConfig: SystemSettingsConfig | undefined
  180. let currentRemoteMapConfig: RemoteMapConfig | undefined
  181. let systemSettingsLockLifetimeActive = false
  182. let syncedBackendSessionStartId = ''
  183. let syncedBackendSessionFinishId = ''
  184. let shouldAutoRestoreRecoverySnapshot = false
  185. let redirectedToResultPage = false
  186. let pendingHeartRateSwitchDeviceName: string | null = null
  187. const DEBUG_MOCK_CHANNEL_ID_STORAGE_KEY = 'cmr.debug.mockChannelId.v1'
  188. const DEBUG_MOCK_AUTO_CONNECT_STORAGE_KEY = 'cmr.debug.autoConnectMockSources.v1'
  189. let lastCenterScaleRulerStablePatch: Pick<
  190. MapPageData,
  191. | 'centerScaleRulerVisible'
  192. | 'centerScaleRulerCenterXPx'
  193. | 'centerScaleRulerZeroYPx'
  194. | 'centerScaleRulerHeightPx'
  195. | 'centerScaleRulerAxisBottomPx'
  196. | 'centerScaleRulerZeroVisible'
  197. | 'centerScaleRulerZeroLabel'
  198. | 'centerScaleRulerMinorTicks'
  199. | 'centerScaleRulerMajorMarks'
  200. > = {
  201. centerScaleRulerVisible: false,
  202. centerScaleRulerCenterXPx: 0,
  203. centerScaleRulerZeroYPx: 0,
  204. centerScaleRulerHeightPx: 0,
  205. centerScaleRulerAxisBottomPx: 0,
  206. centerScaleRulerZeroVisible: false,
  207. centerScaleRulerZeroLabel: '0 m',
  208. centerScaleRulerMinorTicks: [],
  209. centerScaleRulerMajorMarks: [],
  210. }
  211. let centerScaleRulerInputCache: Partial<Pick<
  212. MapPageData,
  213. 'stageWidth'
  214. | 'stageHeight'
  215. | 'zoom'
  216. | 'centerTileY'
  217. | 'tileSizePx'
  218. | 'previewScale'
  219. >> = {}
  220. const DEBUG_ONLY_VIEW_KEYS = new Set<string>([
  221. 'buildVersion',
  222. 'renderMode',
  223. 'projectionMode',
  224. 'mapReady',
  225. 'mapReadyText',
  226. 'mapName',
  227. 'configStatusText',
  228. 'deviceHeadingText',
  229. 'devicePoseText',
  230. 'headingConfidenceText',
  231. 'accelerometerText',
  232. 'gyroscopeText',
  233. 'deviceMotionText',
  234. 'compassSourceText',
  235. 'compassTuningProfile',
  236. 'compassTuningProfileText',
  237. 'northReferenceButtonText',
  238. 'autoRotateSourceText',
  239. 'autoRotateCalibrationText',
  240. 'northReferenceText',
  241. 'centerText',
  242. 'tileSource',
  243. 'visibleTileCount',
  244. 'readyTileCount',
  245. 'memoryTileCount',
  246. 'diskTileCount',
  247. 'memoryHitCount',
  248. 'diskHitCount',
  249. 'networkFetchCount',
  250. 'cacheHitRateText',
  251. 'locationSourceMode',
  252. 'locationSourceText',
  253. 'mockBridgeConnected',
  254. 'mockBridgeStatusText',
  255. 'mockBridgeUrlText',
  256. 'mockCoordText',
  257. 'mockSpeedText',
  258. 'gpsCoordText',
  259. 'heartRateSourceMode',
  260. 'heartRateSourceText',
  261. 'heartRateConnected',
  262. 'heartRateStatusText',
  263. 'heartRateDeviceText',
  264. 'heartRateScanText',
  265. 'heartRateDiscoveredDevices',
  266. 'mockHeartRateBridgeConnected',
  267. 'mockHeartRateBridgeStatusText',
  268. 'mockHeartRateBridgeUrlText',
  269. 'mockHeartRateText',
  270. ])
  271. const CENTER_SCALE_RULER_DEP_KEYS = new Set<string>([
  272. 'showCenterScaleRuler',
  273. 'centerScaleRulerAnchorMode',
  274. 'stageWidth',
  275. 'stageHeight',
  276. 'topInsetHeight',
  277. 'zoom',
  278. 'centerTileY',
  279. 'tileSizePx',
  280. 'previewScale',
  281. ])
  282. const CENTER_SCALE_RULER_CACHE_KEYS: Array<keyof typeof centerScaleRulerInputCache> = [
  283. 'stageWidth',
  284. 'stageHeight',
  285. 'zoom',
  286. 'centerTileY',
  287. 'tileSizePx',
  288. 'previewScale',
  289. ]
  290. const RULER_ONLY_VIEW_KEYS = new Set<string>([
  291. 'zoom',
  292. 'centerTileX',
  293. 'centerTileY',
  294. 'tileSizePx',
  295. 'previewScale',
  296. 'stageWidth',
  297. 'stageHeight',
  298. 'stageLeft',
  299. 'stageTop',
  300. ])
  301. const SIDE_BUTTON_DEP_KEYS = new Set<string>([
  302. 'sideButtonMode',
  303. 'showGameInfoPanel',
  304. 'showCenterScaleRuler',
  305. 'centerScaleRulerAnchorMode',
  306. 'skipButtonEnabled',
  307. 'gameSessionStatus',
  308. 'gpsLockEnabled',
  309. 'gpsLockAvailable',
  310. ])
  311. function hasAnyPatchKey(patch: Record<string, unknown>, keys: Set<string>): boolean {
  312. return Object.keys(patch).some((key) => keys.has(key))
  313. }
  314. function filterDebugOnlyPatch(
  315. patch: Partial<MapPageData>,
  316. includeDebugFields: boolean,
  317. includeRulerFields: boolean,
  318. ): Partial<MapPageData> {
  319. if (includeDebugFields && includeRulerFields) {
  320. return patch
  321. }
  322. const filteredPatch: Partial<MapPageData> = {}
  323. for (const [key, value] of Object.entries(patch)) {
  324. if (!includeDebugFields && DEBUG_ONLY_VIEW_KEYS.has(key)) {
  325. continue
  326. }
  327. if (!includeRulerFields && RULER_ONLY_VIEW_KEYS.has(key)) {
  328. continue
  329. }
  330. {
  331. ;(filteredPatch as Record<string, unknown>)[key] = value
  332. }
  333. }
  334. return filteredPatch
  335. }
  336. function clearGameInfoPanelSyncTimer() {
  337. if (gameInfoPanelSyncTimer) {
  338. clearTimeout(gameInfoPanelSyncTimer)
  339. gameInfoPanelSyncTimer = 0
  340. }
  341. }
  342. function clearCenterScaleRulerSyncTimer() {
  343. if (centerScaleRulerSyncTimer) {
  344. clearTimeout(centerScaleRulerSyncTimer)
  345. centerScaleRulerSyncTimer = 0
  346. }
  347. }
  348. function clearCenterScaleRulerUpdateTimer() {
  349. if (centerScaleRulerUpdateTimer) {
  350. clearTimeout(centerScaleRulerUpdateTimer)
  351. centerScaleRulerUpdateTimer = 0
  352. }
  353. }
  354. function clearPunchHintDismissTimer() {
  355. if (punchHintDismissTimer) {
  356. clearTimeout(punchHintDismissTimer)
  357. punchHintDismissTimer = 0
  358. }
  359. }
  360. function clearPunchHintFxTimer() {
  361. if (punchHintFxTimer) {
  362. clearTimeout(punchHintFxTimer)
  363. punchHintFxTimer = 0
  364. }
  365. }
  366. function clearHudFxTimer(key: 'timer' | 'mileage' | 'speed' | 'heartRate') {
  367. const timerMap = {
  368. timer: panelTimerFxTimer,
  369. mileage: panelMileageFxTimer,
  370. speed: panelSpeedFxTimer,
  371. heartRate: panelHeartRateFxTimer,
  372. }
  373. const timer = timerMap[key]
  374. if (timer) {
  375. clearTimeout(timer)
  376. }
  377. if (key === 'timer') {
  378. panelTimerFxTimer = 0
  379. } else if (key === 'mileage') {
  380. panelMileageFxTimer = 0
  381. } else if (key === 'speed') {
  382. panelSpeedFxTimer = 0
  383. } else {
  384. panelHeartRateFxTimer = 0
  385. }
  386. }
  387. function updateCenterScaleRulerInputCache(patch: Partial<MapPageData>) {
  388. for (const key of CENTER_SCALE_RULER_CACHE_KEYS) {
  389. if (Object.prototype.hasOwnProperty.call(patch, key)) {
  390. ;(centerScaleRulerInputCache as Record<string, unknown>)[key] =
  391. (patch as Record<string, unknown>)[key]
  392. }
  393. }
  394. }
  395. function updateStoredUserSettings(patch: Partial<StoredUserSettings>) {
  396. persistStoredUserSettings(
  397. mergeStoredUserSettings(loadStoredUserSettings(), patch),
  398. )
  399. }
  400. function loadStoredMockChannelId(): string {
  401. try {
  402. const value = wx.getStorageSync(DEBUG_MOCK_CHANNEL_ID_STORAGE_KEY)
  403. if (typeof value === 'string' && value.trim().length > 0) {
  404. return value.trim()
  405. }
  406. } catch (_error) {
  407. // Ignore storage read failures and fall back to default.
  408. }
  409. return 'default'
  410. }
  411. function persistMockChannelId(channelId: string) {
  412. try {
  413. wx.setStorageSync(DEBUG_MOCK_CHANNEL_ID_STORAGE_KEY, channelId)
  414. } catch (_error) {
  415. // Ignore storage write failures in debug preference persistence.
  416. }
  417. }
  418. function loadMockAutoConnectEnabled(): boolean {
  419. try {
  420. return wx.getStorageSync(DEBUG_MOCK_AUTO_CONNECT_STORAGE_KEY) === true
  421. } catch (_error) {
  422. return false
  423. }
  424. }
  425. function persistMockAutoConnectEnabled(enabled: boolean) {
  426. try {
  427. wx.setStorageSync(DEBUG_MOCK_AUTO_CONNECT_STORAGE_KEY, enabled)
  428. } catch (_error) {
  429. // Ignore storage write failures in debug preference persistence.
  430. }
  431. }
  432. function buildResolvedSystemSettingsPatch(
  433. resolvedSettings: ResolvedSystemSettingsState,
  434. ): Partial<MapPageData> {
  435. return {
  436. ...resolvedSettings.values,
  437. ...resolvedSettings.locks,
  438. autoRotateEnabled: resolvedSettings.values.autoRotateEnabled,
  439. sideButtonPlacement: resolvedSettings.values.sideButtonPlacement,
  440. showCenterScaleRuler: resolvedSettings.values.showCenterScaleRuler,
  441. centerScaleRulerAnchorMode: resolvedSettings.values.centerScaleRulerAnchorMode,
  442. }
  443. }
  444. function isSystemSettingsLockLifetimeActive(): boolean {
  445. return systemSettingsLockLifetimeActive
  446. }
  447. function clearSessionRecoveryPersistTimer() {
  448. if (sessionRecoveryPersistTimer) {
  449. clearInterval(sessionRecoveryPersistTimer)
  450. sessionRecoveryPersistTimer = 0
  451. }
  452. }
  453. function clearResultExitRedirectTimer() {
  454. if (resultExitRedirectTimer) {
  455. clearTimeout(resultExitRedirectTimer)
  456. resultExitRedirectTimer = 0
  457. }
  458. }
  459. function clearResultExitCountdownTimer() {
  460. if (resultExitCountdownTimer) {
  461. clearInterval(resultExitCountdownTimer)
  462. resultExitCountdownTimer = 0
  463. }
  464. }
  465. function navigateAwayFromMapAfterCancel() {
  466. const pages = getCurrentPages()
  467. if (pages.length > 1) {
  468. wx.navigateBack({
  469. delta: 1,
  470. })
  471. return
  472. }
  473. wx.redirectTo({
  474. url: '/pages/home/home',
  475. })
  476. }
  477. function hasExplicitLaunchOptions(options?: MapPageLaunchOptions | null): boolean {
  478. if (!options) {
  479. return false
  480. }
  481. return !!(
  482. options.launchId
  483. || options.preset
  484. || options.configUrl
  485. || options.competitionId
  486. || options.eventId
  487. || options.sessionId
  488. || options.launchRequestId
  489. )
  490. }
  491. function getCurrentBackendSessionContext(): { sessionId: string; sessionToken: string } | null {
  492. return getBackendSessionContextFromLaunchEnvelope(currentGameLaunchEnvelope)
  493. }
  494. function getCurrentBackendBaseUrl(): string {
  495. const app = getApp<IAppOption>()
  496. if (app.globalData && app.globalData.backendBaseUrl) {
  497. return app.globalData.backendBaseUrl
  498. }
  499. return loadBackendBaseUrl()
  500. }
  501. function buildSideButtonVisibility(mode: SideButtonMode) {
  502. return {
  503. sideButtonMode: mode,
  504. showLeftButtonGroup: mode === 'shown',
  505. showRightButtonGroups: false,
  506. showBottomDebugButton: true,
  507. }
  508. }
  509. function getNextSideButtonMode(currentMode: SideButtonMode): SideButtonMode {
  510. return currentMode === 'shown' ? 'hidden' : 'shown'
  511. }
  512. function buildCompassTicks(): CompassTickData[] {
  513. const ticks: CompassTickData[] = []
  514. for (let angle = 0; angle < 360; angle += 5) {
  515. ticks.push({
  516. angle,
  517. long: angle % 15 === 0,
  518. major: angle % 45 === 0,
  519. })
  520. }
  521. return ticks
  522. }
  523. function buildCompassLabels(): CompassLabelData[] {
  524. return [
  525. { text: '\u5317', angle: 0, rotateBack: 0, radius: 68, className: 'compass-widget__mark--cardinal compass-widget__mark--north' },
  526. { text: '\u4e1c\u5317', angle: 45, rotateBack: 0, radius: 58, className: 'compass-widget__mark--intermediate compass-widget__mark--northeast' },
  527. { text: '\u4e1c', angle: 90, rotateBack: 0, radius: 68, className: 'compass-widget__mark--cardinal' },
  528. { text: '\u4e1c\u5357', angle: 135, rotateBack: 0, radius: 58, className: 'compass-widget__mark--intermediate' },
  529. { text: '\u5357', angle: 180, rotateBack: 0, radius: 68, className: 'compass-widget__mark--cardinal' },
  530. { text: '\u897f\u5357', angle: 225, rotateBack: 0, radius: 58, className: 'compass-widget__mark--intermediate' },
  531. { text: '\u897f', angle: 270, rotateBack: 0, radius: 68, className: 'compass-widget__mark--cardinal' },
  532. { text: '\u897f\u5317', angle: 315, rotateBack: 0, radius: 58, className: 'compass-widget__mark--intermediate compass-widget__mark--northwest' },
  533. ]
  534. }
  535. function getFallbackStageRect(): MapEngineStageRect {
  536. const systemInfo = wx.getSystemInfoSync()
  537. const width = Math.max(320, systemInfo.windowWidth)
  538. const height = Math.max(280, systemInfo.windowHeight)
  539. return {
  540. width,
  541. height,
  542. left: 0,
  543. top: 0,
  544. }
  545. }
  546. function getSideToggleIconSrc(mode: SideButtonMode): string {
  547. if (mode === 'hidden') {
  548. return '../../assets/btn_more1.png'
  549. }
  550. return '../../assets/btn_more3.png'
  551. }
  552. function getSideActionButtonClass(state: SideActionButtonState): string {
  553. if (state === 'muted') {
  554. return 'map-side-button map-side-button--muted'
  555. }
  556. if (state === 'active') {
  557. return 'map-side-button map-side-button--active'
  558. }
  559. return 'map-side-button map-side-button--default'
  560. }
  561. function buildSideButtonState(data: Pick<MapPageData, 'sideButtonMode' | 'showGameInfoPanel' | 'showSystemSettingsPanel' | 'showCenterScaleRuler' | 'centerScaleRulerAnchorMode' | 'skipButtonEnabled' | 'gameSessionStatus' | 'gpsLockEnabled' | 'gpsLockAvailable'>) {
  562. const sideButton2State: SideActionButtonState = !data.gpsLockAvailable
  563. ? 'muted'
  564. : data.gpsLockEnabled
  565. ? 'active'
  566. : 'default'
  567. const sideButton4State: SideActionButtonState = data.gameSessionStatus === 'running' ? 'active' : 'muted'
  568. const sideButton11State: SideActionButtonState = data.showGameInfoPanel ? 'active' : 'default'
  569. const sideButton12State: SideActionButtonState = data.showSystemSettingsPanel ? 'active' : 'default'
  570. const sideButton13State: SideActionButtonState = data.showCenterScaleRuler ? 'active' : 'default'
  571. const sideButton14State: SideActionButtonState = !data.showCenterScaleRuler
  572. ? 'muted'
  573. : data.centerScaleRulerAnchorMode === 'compass-center'
  574. ? 'active'
  575. : 'default'
  576. const sideButton16State: SideActionButtonState = data.skipButtonEnabled ? 'default' : 'muted'
  577. return {
  578. sideToggleIconSrc: getSideToggleIconSrc(data.sideButtonMode),
  579. sideButton2Class: getSideActionButtonClass(sideButton2State),
  580. sideButton4Class: getSideActionButtonClass(sideButton4State),
  581. sideButton11Class: getSideActionButtonClass(sideButton11State),
  582. sideButton12Class: getSideActionButtonClass(sideButton12State),
  583. sideButton13Class: getSideActionButtonClass(sideButton13State),
  584. sideButton14Class: getSideActionButtonClass(sideButton14State),
  585. sideButton16Class: getSideActionButtonClass(sideButton16State),
  586. }
  587. }
  588. function getRpxUnitInPx(): number {
  589. const systemInfo = wx.getSystemInfoSync()
  590. return systemInfo.windowWidth / 750
  591. }
  592. function worldTileYToLat(worldTileY: number, zoom: number): number {
  593. const scale = Math.pow(2, zoom)
  594. const n = Math.PI - (2 * Math.PI * worldTileY) / scale
  595. return (180 / Math.PI) * Math.atan(Math.sinh(n))
  596. }
  597. function getNiceDistanceMeters(rawDistanceMeters: number): number {
  598. if (!Number.isFinite(rawDistanceMeters) || rawDistanceMeters <= 0) {
  599. return 50
  600. }
  601. const exponent = Math.floor(Math.log10(rawDistanceMeters))
  602. const base = Math.pow(10, exponent)
  603. const normalized = rawDistanceMeters / base
  604. if (normalized <= 1) {
  605. return base
  606. }
  607. if (normalized <= 2) {
  608. return 2 * base
  609. }
  610. if (normalized <= 5) {
  611. return 5 * base
  612. }
  613. return 10 * base
  614. }
  615. function formatScaleDistanceLabel(distanceMeters: number): string {
  616. if (distanceMeters >= 1000) {
  617. const distanceKm = distanceMeters / 1000
  618. const formatted = distanceKm >= 10 ? distanceKm.toFixed(0) : distanceKm.toFixed(1)
  619. return `${formatted.replace(/\.0$/, '')} km`
  620. }
  621. return `${Math.round(distanceMeters)} m`
  622. }
  623. function buildCenterScaleRulerPatch(data: Pick<MapPageData, 'showCenterScaleRuler' | 'centerScaleRulerAnchorMode' | 'stageWidth' | 'stageHeight' | 'topInsetHeight' | 'zoom' | 'centerTileY' | 'tileSizePx' | 'previewScale'>) {
  624. if (!data.showCenterScaleRuler) {
  625. lastCenterScaleRulerStablePatch = {
  626. centerScaleRulerVisible: false,
  627. centerScaleRulerCenterXPx: 0,
  628. centerScaleRulerZeroYPx: 0,
  629. centerScaleRulerHeightPx: 0,
  630. centerScaleRulerAxisBottomPx: 0,
  631. centerScaleRulerZeroVisible: false,
  632. centerScaleRulerZeroLabel: '0 m',
  633. centerScaleRulerMinorTicks: [] as ScaleRulerMinorTickData[],
  634. centerScaleRulerMajorMarks: [] as ScaleRulerMajorMarkData[],
  635. }
  636. return { ...lastCenterScaleRulerStablePatch }
  637. }
  638. if (!data.stageWidth || !data.stageHeight) {
  639. return { ...lastCenterScaleRulerStablePatch }
  640. }
  641. const topPadding = 12
  642. const rpxUnitPx = getRpxUnitInPx()
  643. const compassBottomPaddingPx = 248 * rpxUnitPx
  644. const compassDialRadiusPx = (196 * rpxUnitPx) / 2
  645. const compassHeadingOverlayHeightPx = 40 * rpxUnitPx
  646. const compassOcclusionPaddingPx = 10 * rpxUnitPx
  647. const zeroYPx = data.centerScaleRulerAnchorMode === 'compass-center'
  648. ? Math.round(data.stageHeight - compassBottomPaddingPx - compassDialRadiusPx)
  649. : Math.round(data.stageHeight / 2)
  650. const fallbackHeight = Math.max(zeroYPx - topPadding, 160)
  651. const coveredBottomPx = data.centerScaleRulerAnchorMode === 'compass-center'
  652. ? Math.round(compassDialRadiusPx + compassHeadingOverlayHeightPx + compassOcclusionPaddingPx)
  653. : 0
  654. if (
  655. !data.tileSizePx
  656. || !Number.isFinite(data.zoom)
  657. || !Number.isFinite(data.centerTileY)
  658. ) {
  659. return {
  660. ...lastCenterScaleRulerStablePatch,
  661. centerScaleRulerVisible: true,
  662. centerScaleRulerCenterXPx: Math.round(data.stageWidth / 2),
  663. centerScaleRulerZeroYPx: zeroYPx,
  664. centerScaleRulerHeightPx: lastCenterScaleRulerStablePatch.centerScaleRulerHeightPx || fallbackHeight,
  665. centerScaleRulerAxisBottomPx: coveredBottomPx,
  666. centerScaleRulerZeroVisible: data.centerScaleRulerAnchorMode !== 'compass-center',
  667. }
  668. }
  669. const centerLat = worldTileYToLat(data.centerTileY + 0.5, data.zoom)
  670. const metersPerTile = Math.cos(centerLat * Math.PI / 180) * 40075016.686 / Math.pow(2, data.zoom)
  671. const metersPerPixel = metersPerTile / data.tileSizePx
  672. const effectivePreviewScale = Number.isFinite(data.previewScale) && data.previewScale > 0 ? data.previewScale : 1
  673. const effectiveMetersPerPixel = metersPerPixel / effectivePreviewScale
  674. const rulerHeight = Math.floor(zeroYPx - topPadding)
  675. if (!Number.isFinite(effectiveMetersPerPixel) || effectiveMetersPerPixel <= 0 || rulerHeight < 120) {
  676. return {
  677. ...lastCenterScaleRulerStablePatch,
  678. centerScaleRulerVisible: true,
  679. centerScaleRulerCenterXPx: Math.round(data.stageWidth / 2),
  680. centerScaleRulerZeroYPx: zeroYPx,
  681. centerScaleRulerHeightPx: lastCenterScaleRulerStablePatch.centerScaleRulerHeightPx || fallbackHeight,
  682. centerScaleRulerAxisBottomPx: coveredBottomPx,
  683. centerScaleRulerZeroVisible: data.centerScaleRulerAnchorMode !== 'compass-center',
  684. }
  685. }
  686. const labelDistanceMeters = getNiceDistanceMeters(effectiveMetersPerPixel * 80)
  687. const minorDistanceMeters = labelDistanceMeters / 8
  688. const minorStepPx = minorDistanceMeters / effectiveMetersPerPixel
  689. const visibleTopLimitPx = rulerHeight - coveredBottomPx
  690. const minorTicks: ScaleRulerMinorTickData[] = []
  691. const majorMarks: ScaleRulerMajorMarkData[] = []
  692. for (let index = 1; index <= 200; index += 1) {
  693. const topPx = Math.round(rulerHeight - index * minorStepPx)
  694. if (topPx < 0) {
  695. break
  696. }
  697. if (topPx >= visibleTopLimitPx) {
  698. continue
  699. }
  700. const isHalfMajor = index % 4 === 0
  701. const isLabelMajor = index % 8 === 0
  702. minorTicks.push({
  703. key: `minor-${index}`,
  704. topPx,
  705. long: isHalfMajor,
  706. })
  707. if (isLabelMajor) {
  708. majorMarks.push({
  709. key: `major-${index}`,
  710. topPx,
  711. label: formatScaleDistanceLabel((index / 8) * labelDistanceMeters),
  712. })
  713. }
  714. }
  715. lastCenterScaleRulerStablePatch = {
  716. centerScaleRulerVisible: true,
  717. centerScaleRulerCenterXPx: Math.round(data.stageWidth / 2),
  718. centerScaleRulerZeroYPx: zeroYPx,
  719. centerScaleRulerHeightPx: rulerHeight,
  720. centerScaleRulerAxisBottomPx: coveredBottomPx,
  721. centerScaleRulerZeroVisible: data.centerScaleRulerAnchorMode !== 'compass-center',
  722. centerScaleRulerZeroLabel: '0 m',
  723. centerScaleRulerMinorTicks: minorTicks,
  724. centerScaleRulerMajorMarks: majorMarks,
  725. }
  726. return { ...lastCenterScaleRulerStablePatch }
  727. }
  728. function buildEmptyGameInfoSnapshot(): MapEngineGameInfoSnapshot {
  729. return {
  730. title: '当前游戏',
  731. subtitle: '未开始',
  732. localRows: [],
  733. globalRows: [
  734. { label: '全球积分', value: '未接入' },
  735. { label: '全球排名', value: '未接入' },
  736. { label: '在线人数', value: '未接入' },
  737. { label: '队伍状态', value: '未接入' },
  738. { label: '实时广播', value: '未接入' },
  739. ],
  740. }
  741. }
  742. function buildEmptyResultSceneSnapshot(): MapEngineResultSnapshot {
  743. return {
  744. title: '本局结果',
  745. subtitle: '未开始',
  746. heroLabel: '本局用时',
  747. heroValue: '--',
  748. rows: [],
  749. }
  750. }
  751. function buildRuntimeSummaryRows(envelope: GameLaunchEnvelope): MapEngineGameInfoRow[] {
  752. const runtime = envelope.runtime
  753. const variantName = envelope.variant ? (envelope.variant.variantName || envelope.variant.variantId || null) : null
  754. const variantRouteCode = envelope.variant ? (envelope.variant.routeCode || null) : null
  755. if (!runtime) {
  756. return []
  757. }
  758. const rows: MapEngineGameInfoRow[] = []
  759. rows.push({ label: '运行绑定', value: runtime.runtimeBindingId || '--' })
  760. rows.push({ label: '地点', value: runtime.placeName || runtime.placeId || '--' })
  761. rows.push({ label: '地图', value: runtime.mapName || runtime.mapId || '--' })
  762. rows.push({ label: '赛道集', value: runtime.courseSetId || '--' })
  763. rows.push({ label: '赛道版本', value: runtime.courseVariantId || variantName || '--' })
  764. rows.push({ label: 'RouteCode', value: runtime.routeCode || variantRouteCode || '--' })
  765. rows.push({ label: '瓦片版本', value: runtime.tileReleaseId || '--' })
  766. return rows
  767. }
  768. Page({
  769. data: {
  770. showDebugPanel: false,
  771. showGameInfoPanel: false,
  772. showResultScene: false,
  773. showSystemSettingsPanel: false,
  774. showHeartRateDevicePicker: false,
  775. showCenterScaleRuler: false,
  776. statusBarHeight: 0,
  777. topInsetHeight: 12,
  778. hudPanelIndex: 0,
  779. configSourceText: '顺序赛配置',
  780. centerScaleRulerAnchorMode: DEFAULT_STORED_USER_SETTINGS.centerScaleRulerAnchorMode,
  781. punchHintFxClass: '',
  782. autoRotateEnabled: DEFAULT_STORED_USER_SETTINGS.autoRotateEnabled,
  783. ...DEFAULT_SETTING_LOCKS,
  784. gameInfoTitle: '当前游戏',
  785. gameInfoSubtitle: '未开始',
  786. gameInfoLocalRows: [],
  787. gameInfoGlobalRows: buildEmptyGameInfoSnapshot().globalRows,
  788. resultSceneTitle: '本局结果',
  789. resultSceneSubtitle: '未开始',
  790. resultSceneHeroLabel: '本局用时',
  791. resultSceneHeroValue: '--',
  792. resultSceneRows: buildEmptyResultSceneSnapshot().rows,
  793. resultSceneCountdownText: '',
  794. panelTimerText: '00:00:00',
  795. panelTimerMode: 'elapsed',
  796. panelMileageText: '0m',
  797. panelActionTagText: '目标',
  798. panelDistanceTagText: '点距',
  799. panelTargetSummaryText: '等待选择目标',
  800. panelDistanceValueText: '--',
  801. panelDistanceUnitText: '',
  802. panelProgressText: '0/0',
  803. showPunchHintBanner: true,
  804. sideButtonPlacement: 'left',
  805. gameSessionStatus: 'idle',
  806. gameModeText: '顺序赛',
  807. gpsLockEnabled: false,
  808. gpsLockAvailable: false,
  809. locationSourceMode: 'real',
  810. locationSourceText: '真实定位',
  811. mockBridgeConnected: false,
  812. mockBridgeStatusText: '未连接',
  813. mockBridgeUrlText: 'wss://gs.gotomars.xyz/mock-gps',
  814. mockChannelIdText: 'default',
  815. mockBridgeUrlDraft: 'wss://gs.gotomars.xyz/mock-gps',
  816. mockChannelIdDraft: 'default',
  817. mockCoordText: '--',
  818. mockSpeedText: '--',
  819. heartRateSourceMode: 'real',
  820. heartRateSourceText: '真实心率',
  821. mockHeartRateBridgeConnected: false,
  822. mockHeartRateBridgeStatusText: '未连接',
  823. mockHeartRateBridgeUrlText: 'wss://gs.gotomars.xyz/mock-hr',
  824. mockHeartRateBridgeUrlDraft: 'wss://gs.gotomars.xyz/mock-hr',
  825. mockHeartRateText: '--',
  826. mockDebugLogBridgeConnected: false,
  827. mockDebugLogBridgeStatusText: '已关闭 (wss://gs.gotomars.xyz/debug-log)',
  828. mockDebugLogBridgeUrlText: 'wss://gs.gotomars.xyz/debug-log',
  829. mockDebugLogBridgeUrlDraft: 'wss://gs.gotomars.xyz/debug-log',
  830. heartRateScanText: '未扫描',
  831. heartRateDiscoveredDevices: [],
  832. panelSpeedValueText: '0',
  833. panelTelemetryTone: 'blue',
  834. trackDisplayMode: DEFAULT_STORED_USER_SETTINGS.trackDisplayMode,
  835. trackTailLength: DEFAULT_STORED_USER_SETTINGS.trackTailLength,
  836. trackColorPreset: DEFAULT_STORED_USER_SETTINGS.trackColorPreset,
  837. trackStyleProfile: DEFAULT_STORED_USER_SETTINGS.trackStyleProfile,
  838. gpsMarkerVisible: DEFAULT_STORED_USER_SETTINGS.gpsMarkerVisible,
  839. gpsMarkerStyle: DEFAULT_STORED_USER_SETTINGS.gpsMarkerStyle,
  840. gpsMarkerSize: DEFAULT_STORED_USER_SETTINGS.gpsMarkerSize,
  841. gpsMarkerColorPreset: DEFAULT_STORED_USER_SETTINGS.gpsMarkerColorPreset,
  842. gpsLogoStatusText: '未配置',
  843. gpsLogoSourceText: '--',
  844. panelHeartRateZoneNameText: '--',
  845. panelHeartRateZoneRangeText: '',
  846. heartRateConnected: false,
  847. heartRateStatusText: '心率带未连接',
  848. heartRateDeviceText: '--',
  849. panelHeartRateValueText: '--',
  850. panelHeartRateUnitText: '',
  851. panelCaloriesValueText: '0',
  852. panelCaloriesUnitText: 'kcal',
  853. panelAverageSpeedValueText: '0',
  854. panelAverageSpeedUnitText: 'km/h',
  855. panelAccuracyValueText: '--',
  856. panelAccuracyUnitText: '',
  857. deviceHeadingText: '--',
  858. devicePoseText: '竖持',
  859. headingConfidenceText: '低',
  860. accelerometerText: '--',
  861. gyroscopeText: '--',
  862. deviceMotionText: '--',
  863. compassSourceText: '无数据',
  864. compassTuningProfile: DEFAULT_STORED_USER_SETTINGS.compassTuningProfile,
  865. compassTuningProfileText: '平衡',
  866. punchButtonText: '打点',
  867. punchButtonEnabled: false,
  868. skipButtonEnabled: false,
  869. punchHintText: '等待进入检查点范围',
  870. punchFeedbackVisible: false,
  871. punchFeedbackText: '',
  872. punchFeedbackTone: 'neutral',
  873. contentCardVisible: false,
  874. contentCardTemplate: 'story',
  875. contentCardTitle: '',
  876. contentCardBody: '',
  877. contentCardActions: [],
  878. contentQuizVisible: false,
  879. contentQuizQuestionText: '',
  880. contentQuizCountdownText: '',
  881. contentQuizOptions: [],
  882. contentQuizFeedbackVisible: false,
  883. contentQuizFeedbackText: '',
  884. contentQuizFeedbackTone: 'neutral',
  885. punchButtonFxClass: '',
  886. panelProgressFxClass: '',
  887. panelDistanceFxClass: '',
  888. punchFeedbackFxClass: '',
  889. contentCardFxClass: '',
  890. mapPulseVisible: false,
  891. mapPulseLeftPx: 0,
  892. mapPulseTopPx: 0,
  893. mapPulseFxClass: '',
  894. stageFxVisible: false,
  895. stageFxClass: '',
  896. centerScaleRulerVisible: false,
  897. centerScaleRulerCenterXPx: 0,
  898. centerScaleRulerZeroYPx: 0,
  899. centerScaleRulerHeightPx: 0,
  900. centerScaleRulerAxisBottomPx: 0,
  901. centerScaleRulerZeroVisible: false,
  902. centerScaleRulerZeroLabel: '0 m',
  903. centerScaleRulerMinorTicks: [],
  904. centerScaleRulerMajorMarks: [],
  905. compassTicks: buildCompassTicks(),
  906. compassLabels: buildCompassLabels(),
  907. ...buildSideButtonVisibility('shown'),
  908. ...buildSideButtonState({
  909. sideButtonMode: 'shown',
  910. showGameInfoPanel: false,
  911. showSystemSettingsPanel: false,
  912. showCenterScaleRuler: false,
  913. centerScaleRulerAnchorMode: 'screen-center',
  914. skipButtonEnabled: false,
  915. gameSessionStatus: 'idle',
  916. gpsLockEnabled: false,
  917. gpsLockAvailable: false,
  918. }),
  919. } as unknown as MapPageData,
  920. onLoad(options: MapPageLaunchOptions) {
  921. clearSessionRecoveryPersistTimer()
  922. clearResultExitRedirectTimer()
  923. clearResultExitCountdownTimer()
  924. syncedBackendSessionStartId = ''
  925. syncedBackendSessionFinishId = ''
  926. redirectedToResultPage = false
  927. shouldAutoRestoreRecoverySnapshot = options && options.recoverSession === '1'
  928. currentGameLaunchEnvelope = resolveGameLaunchEnvelope(options)
  929. if (!hasExplicitLaunchOptions(options)) {
  930. const recoverySnapshot = loadSessionRecoverySnapshot()
  931. if (recoverySnapshot) {
  932. currentGameLaunchEnvelope = recoverySnapshot.launchEnvelope
  933. }
  934. }
  935. currentSystemSettingsConfig = undefined
  936. currentRemoteMapConfig = undefined
  937. systemSettingsLockLifetimeActive = false
  938. const storedMockChannelId = loadStoredMockChannelId()
  939. const shouldAutoConnectMockSources = loadMockAutoConnectEnabled()
  940. const systemInfo = wx.getSystemInfoSync()
  941. const statusBarHeight = systemInfo.statusBarHeight || 0
  942. const menuButtonRect = wx.getMenuButtonBoundingClientRect()
  943. const menuButtonBottom = menuButtonRect && typeof menuButtonRect.bottom === 'number' ? menuButtonRect.bottom : statusBarHeight
  944. if (mapEngine) {
  945. mapEngine.destroy()
  946. mapEngine = null
  947. }
  948. mapEngine = new MapEngine(INTERNAL_BUILD_VERSION, {
  949. onData: (patch) => {
  950. const nextPatch = patch as Partial<MapPageData>
  951. const includeDebugFields = this.data.showDebugPanel
  952. const includeRulerFields = this.data.showCenterScaleRuler
  953. let shouldSyncRuntimeSystemSettings = false
  954. let nextLockLifetimeActive = isSystemSettingsLockLifetimeActive()
  955. let heartRateSwitchToastText = ''
  956. const nextData: Partial<MapPageData> = filterDebugOnlyPatch({
  957. ...nextPatch,
  958. }, includeDebugFields, includeRulerFields)
  959. if (
  960. typeof nextPatch.mockBridgeUrlText === 'string'
  961. && this.data.mockBridgeUrlDraft === this.data.mockBridgeUrlText
  962. ) {
  963. nextData.mockBridgeUrlDraft = nextPatch.mockBridgeUrlText
  964. }
  965. if (
  966. typeof nextPatch.mockHeartRateBridgeUrlText === 'string'
  967. && this.data.mockHeartRateBridgeUrlDraft === this.data.mockHeartRateBridgeUrlText
  968. ) {
  969. nextData.mockHeartRateBridgeUrlDraft = nextPatch.mockHeartRateBridgeUrlText
  970. }
  971. if (
  972. typeof nextPatch.mockDebugLogBridgeUrlText === 'string'
  973. && this.data.mockDebugLogBridgeUrlDraft === this.data.mockDebugLogBridgeUrlText
  974. ) {
  975. nextData.mockDebugLogBridgeUrlDraft = nextPatch.mockDebugLogBridgeUrlText
  976. }
  977. if (
  978. typeof nextPatch.mockChannelIdText === 'string'
  979. && this.data.mockChannelIdDraft === this.data.mockChannelIdText
  980. ) {
  981. nextData.mockChannelIdDraft = nextPatch.mockChannelIdText
  982. }
  983. updateCenterScaleRulerInputCache(nextPatch)
  984. const mergedData = {
  985. ...centerScaleRulerInputCache,
  986. ...this.data,
  987. ...nextData,
  988. } as MapPageData
  989. const derivedPatch: Partial<MapPageData> = {}
  990. if (typeof nextPatch.orientationMode === 'string') {
  991. nextData.autoRotateEnabled = nextPatch.orientationMode === 'heading-up'
  992. }
  993. if (
  994. this.data.showCenterScaleRuler
  995. && hasAnyPatchKey(nextPatch as Record<string, unknown>, CENTER_SCALE_RULER_DEP_KEYS)
  996. ) {
  997. clearCenterScaleRulerUpdateTimer()
  998. Object.assign(derivedPatch, buildCenterScaleRulerPatch(mergedData))
  999. }
  1000. if (hasAnyPatchKey(nextPatch as Record<string, unknown>, SIDE_BUTTON_DEP_KEYS)) {
  1001. Object.assign(derivedPatch, buildSideButtonState(mergedData))
  1002. }
  1003. if (typeof nextPatch.punchHintText === 'string') {
  1004. const nextHintText = nextPatch.punchHintText.trim()
  1005. if (nextHintText !== this.data.punchHintText) {
  1006. clearPunchHintDismissTimer()
  1007. clearPunchHintFxTimer()
  1008. nextData.showPunchHintBanner = nextHintText.length > 0
  1009. if (nextHintText.length > 0) {
  1010. nextData.punchHintFxClass = 'game-punch-hint--fx-enter'
  1011. punchHintFxTimer = setTimeout(() => {
  1012. punchHintFxTimer = 0
  1013. this.setData({
  1014. punchHintFxClass: '',
  1015. })
  1016. }, PUNCH_HINT_FX_DURATION_MS) as unknown as number
  1017. const now = Date.now()
  1018. if (mapEngine && now - lastPunchHintHapticAt >= PUNCH_HINT_HAPTIC_GAP_MS) {
  1019. mapEngine.playPunchHintHaptic()
  1020. lastPunchHintHapticAt = now
  1021. }
  1022. punchHintDismissTimer = setTimeout(() => {
  1023. punchHintDismissTimer = 0
  1024. this.setData({
  1025. showPunchHintBanner: false,
  1026. })
  1027. }, PUNCH_HINT_AUTO_HIDE_MS) as unknown as number
  1028. }
  1029. } else if (!nextHintText) {
  1030. clearPunchHintDismissTimer()
  1031. clearPunchHintFxTimer()
  1032. nextData.showPunchHintBanner = false
  1033. nextData.punchHintFxClass = ''
  1034. }
  1035. }
  1036. const nextAnimationLevel = typeof nextPatch.animationLevel === 'string'
  1037. ? nextPatch.animationLevel
  1038. : this.data.animationLevel
  1039. let shouldSyncBackendSessionStart = false
  1040. let backendSessionFinishStatus: 'finished' | 'failed' | null = null
  1041. let shouldOpenResultExitPrompt = false
  1042. let resultPageSnapshot: MapEngineResultSnapshot | null = null
  1043. if (nextAnimationLevel === 'lite') {
  1044. clearHudFxTimer('timer')
  1045. clearHudFxTimer('mileage')
  1046. clearHudFxTimer('speed')
  1047. clearHudFxTimer('heartRate')
  1048. nextData.panelTimerFxClass = ''
  1049. nextData.panelMileageFxClass = ''
  1050. nextData.panelSpeedFxClass = ''
  1051. nextData.panelHeartRateFxClass = ''
  1052. } else {
  1053. if (typeof nextPatch.panelTimerText === 'string' && nextPatch.panelTimerText !== this.data.panelTimerText && this.data.panelTimerText !== '00:00:00') {
  1054. clearHudFxTimer('timer')
  1055. nextData.panelTimerFxClass = 'race-panel__timer--fx-tick'
  1056. panelTimerFxTimer = setTimeout(() => {
  1057. panelTimerFxTimer = 0
  1058. this.setData({ panelTimerFxClass: '' })
  1059. }, 320) as unknown as number
  1060. }
  1061. if (typeof nextPatch.panelMileageText === 'string' && nextPatch.panelMileageText !== this.data.panelMileageText && this.data.panelMileageText !== '0m') {
  1062. clearHudFxTimer('mileage')
  1063. nextData.panelMileageFxClass = 'race-panel__mileage-wrap--fx-update'
  1064. panelMileageFxTimer = setTimeout(() => {
  1065. panelMileageFxTimer = 0
  1066. this.setData({ panelMileageFxClass: '' })
  1067. }, 360) as unknown as number
  1068. }
  1069. if (typeof nextPatch.panelSpeedValueText === 'string' && nextPatch.panelSpeedValueText !== this.data.panelSpeedValueText && this.data.panelSpeedValueText !== '0') {
  1070. clearHudFxTimer('speed')
  1071. nextData.panelSpeedFxClass = 'race-panel__metric-group--fx-speed-update'
  1072. panelSpeedFxTimer = setTimeout(() => {
  1073. panelSpeedFxTimer = 0
  1074. this.setData({ panelSpeedFxClass: '' })
  1075. }, 360) as unknown as number
  1076. }
  1077. if (typeof nextPatch.panelHeartRateValueText === 'string' && nextPatch.panelHeartRateValueText !== this.data.panelHeartRateValueText && this.data.panelHeartRateValueText !== '--') {
  1078. clearHudFxTimer('heartRate')
  1079. nextData.panelHeartRateFxClass = 'race-panel__metric-group--fx-heart-rate-update'
  1080. panelHeartRateFxTimer = setTimeout(() => {
  1081. panelHeartRateFxTimer = 0
  1082. this.setData({ panelHeartRateFxClass: '' })
  1083. }, 400) as unknown as number
  1084. }
  1085. }
  1086. if (typeof nextPatch.gameSessionStatus === 'string') {
  1087. if (
  1088. nextPatch.gameSessionStatus !== this.data.gameSessionStatus
  1089. && (nextPatch.gameSessionStatus === 'finished' || nextPatch.gameSessionStatus === 'failed')
  1090. ) {
  1091. systemSettingsLockLifetimeActive = false
  1092. nextLockLifetimeActive = false
  1093. shouldSyncRuntimeSystemSettings = true
  1094. clearSessionRecoverySnapshot()
  1095. clearSessionRecoveryPersistTimer()
  1096. clearResultExitRedirectTimer()
  1097. clearResultExitCountdownTimer()
  1098. resultPageSnapshot = mapEngine ? mapEngine.getResultSceneSnapshot() : null
  1099. nextData.showResultScene = true
  1100. nextData.showDebugPanel = false
  1101. nextData.showGameInfoPanel = false
  1102. nextData.showSystemSettingsPanel = false
  1103. clearGameInfoPanelSyncTimer()
  1104. backendSessionFinishStatus = nextPatch.gameSessionStatus === 'finished' ? 'finished' : 'failed'
  1105. shouldOpenResultExitPrompt = true
  1106. if (resultPageSnapshot) {
  1107. nextData.resultSceneTitle = resultPageSnapshot.title
  1108. nextData.resultSceneSubtitle = resultPageSnapshot.subtitle
  1109. nextData.resultSceneHeroLabel = resultPageSnapshot.heroLabel
  1110. nextData.resultSceneHeroValue = resultPageSnapshot.heroValue
  1111. nextData.resultSceneRows = resultPageSnapshot.rows
  1112. }
  1113. nextData.resultSceneCountdownText = '3 秒后自动进入成绩页'
  1114. } else if (
  1115. nextPatch.gameSessionStatus !== this.data.gameSessionStatus
  1116. && nextPatch.gameSessionStatus === 'idle'
  1117. && !isSystemSettingsLockLifetimeActive()
  1118. ) {
  1119. nextLockLifetimeActive = false
  1120. shouldSyncRuntimeSystemSettings = true
  1121. clearSessionRecoverySnapshot()
  1122. clearSessionRecoveryPersistTimer()
  1123. clearResultExitRedirectTimer()
  1124. clearResultExitCountdownTimer()
  1125. } else if (
  1126. nextPatch.gameSessionStatus !== this.data.gameSessionStatus
  1127. && nextPatch.gameSessionStatus === 'running'
  1128. ) {
  1129. shouldSyncBackendSessionStart = true
  1130. } else if (nextPatch.gameSessionStatus === 'running' || nextPatch.gameSessionStatus === 'idle') {
  1131. nextData.showResultScene = false
  1132. }
  1133. }
  1134. if (
  1135. pendingHeartRateSwitchDeviceName
  1136. && nextPatch.heartRateConnected === true
  1137. && typeof nextPatch.heartRateDeviceText === 'string'
  1138. ) {
  1139. const connectedDeviceName = nextPatch.heartRateDeviceText.trim()
  1140. if (connectedDeviceName && connectedDeviceName === pendingHeartRateSwitchDeviceName) {
  1141. heartRateSwitchToastText = `已切换到 ${connectedDeviceName}`
  1142. nextData.statusText = `已切换心率带:${connectedDeviceName}`
  1143. pendingHeartRateSwitchDeviceName = null
  1144. }
  1145. }
  1146. if (Object.keys(nextData).length || Object.keys(derivedPatch).length) {
  1147. this.setData({
  1148. ...nextData,
  1149. ...derivedPatch,
  1150. }, () => {
  1151. if (typeof nextPatch.gameSessionStatus === 'string') {
  1152. this.syncSessionRecoveryLifecycle(nextPatch.gameSessionStatus)
  1153. }
  1154. if (shouldSyncBackendSessionStart) {
  1155. this.syncBackendSessionStart()
  1156. }
  1157. if (backendSessionFinishStatus) {
  1158. this.syncBackendSessionFinish(backendSessionFinishStatus)
  1159. }
  1160. if (shouldOpenResultExitPrompt && resultPageSnapshot) {
  1161. this.stashPendingResultSnapshot(resultPageSnapshot)
  1162. this.presentResultExitPrompt()
  1163. }
  1164. if (heartRateSwitchToastText) {
  1165. wx.showToast({
  1166. title: `${heartRateSwitchToastText},并设为首选设备`,
  1167. icon: 'none',
  1168. duration: 1800,
  1169. })
  1170. }
  1171. if (shouldSyncRuntimeSystemSettings) {
  1172. this.applyRuntimeSystemSettings(nextLockLifetimeActive)
  1173. }
  1174. if (this.data.showGameInfoPanel) {
  1175. this.scheduleGameInfoPanelSnapshotSync()
  1176. }
  1177. })
  1178. } else {
  1179. if (typeof nextPatch.gameSessionStatus === 'string') {
  1180. this.syncSessionRecoveryLifecycle(nextPatch.gameSessionStatus)
  1181. }
  1182. if (shouldSyncBackendSessionStart) {
  1183. this.syncBackendSessionStart()
  1184. }
  1185. if (backendSessionFinishStatus) {
  1186. this.syncBackendSessionFinish(backendSessionFinishStatus)
  1187. }
  1188. if (shouldOpenResultExitPrompt && resultPageSnapshot) {
  1189. this.stashPendingResultSnapshot(resultPageSnapshot)
  1190. this.presentResultExitPrompt()
  1191. }
  1192. if (shouldSyncRuntimeSystemSettings) {
  1193. this.applyRuntimeSystemSettings(nextLockLifetimeActive)
  1194. }
  1195. if (this.data.showGameInfoPanel) {
  1196. this.scheduleGameInfoPanelSnapshotSync()
  1197. }
  1198. }
  1199. },
  1200. onOpenH5Experience: (request) => {
  1201. this.openH5Experience(request)
  1202. },
  1203. })
  1204. mapEngine.applyTelemetryPlayerProfile(getGlobalTelemetryProfile())
  1205. const systemSettingsState = resolveSystemSettingsState(undefined, undefined, false)
  1206. const initialSystemSettings = systemSettingsState.values
  1207. mapEngine.applyCompiledSettingsProfile({
  1208. values: initialSystemSettings,
  1209. locks: systemSettingsState.locks,
  1210. lockLifetimeActive: false,
  1211. })
  1212. mapEngine.setDiagnosticUiEnabled(false)
  1213. centerScaleRulerInputCache = {
  1214. stageWidth: 0,
  1215. stageHeight: 0,
  1216. zoom: 0,
  1217. centerTileY: 0,
  1218. tileSizePx: 0,
  1219. previewScale: 1,
  1220. }
  1221. const initialEngineData = mapEngine.getInitialData()
  1222. this.setData({
  1223. ...initialEngineData,
  1224. ...buildResolvedSystemSettingsPatch(systemSettingsState),
  1225. showDebugPanel: false,
  1226. showGameInfoPanel: false,
  1227. showResultScene: false,
  1228. showSystemSettingsPanel: false,
  1229. statusBarHeight,
  1230. topInsetHeight: Math.max(statusBarHeight + 12, menuButtonBottom + 20),
  1231. hudPanelIndex: 0,
  1232. configSourceText: currentGameLaunchEnvelope.config.configLabel,
  1233. gameInfoTitle: '当前游戏',
  1234. gameInfoSubtitle: '未开始',
  1235. gameInfoLocalRows: [],
  1236. gameInfoGlobalRows: buildEmptyGameInfoSnapshot().globalRows,
  1237. resultSceneTitle: '本局结果',
  1238. resultSceneSubtitle: '未开始',
  1239. resultSceneHeroLabel: '本局用时',
  1240. resultSceneHeroValue: '--',
  1241. resultSceneRows: buildEmptyResultSceneSnapshot().rows,
  1242. resultSceneCountdownText: '',
  1243. panelTimerText: '00:00:00',
  1244. panelTimerMode: 'elapsed',
  1245. panelTimerFxClass: '',
  1246. panelMileageText: '0m',
  1247. panelMileageFxClass: '',
  1248. panelActionTagText: '目标',
  1249. panelDistanceTagText: '点距',
  1250. panelTargetSummaryText: '等待选择目标',
  1251. panelDistanceValueText: '--',
  1252. panelDistanceUnitText: '',
  1253. panelProgressText: '0/0',
  1254. showPunchHintBanner: true,
  1255. gameSessionStatus: 'idle',
  1256. gameModeText: '顺序赛',
  1257. gpsLockEnabled: false,
  1258. gpsLockAvailable: false,
  1259. locationSourceMode: 'real',
  1260. locationSourceText: '真实定位',
  1261. mockBridgeConnected: false,
  1262. mockBridgeStatusText: '未连接',
  1263. mockBridgeUrlText: 'wss://gs.gotomars.xyz/mock-gps',
  1264. mockChannelIdText: storedMockChannelId,
  1265. mockBridgeUrlDraft: 'wss://gs.gotomars.xyz/mock-gps',
  1266. mockChannelIdDraft: storedMockChannelId,
  1267. mockCoordText: '--',
  1268. mockSpeedText: '--',
  1269. heartRateSourceMode: 'real',
  1270. heartRateSourceText: '真实心率',
  1271. mockHeartRateBridgeConnected: false,
  1272. mockHeartRateBridgeStatusText: '未连接',
  1273. mockHeartRateBridgeUrlText: 'wss://gs.gotomars.xyz/mock-hr',
  1274. mockHeartRateBridgeUrlDraft: 'wss://gs.gotomars.xyz/mock-hr',
  1275. mockHeartRateText: '--',
  1276. mockDebugLogBridgeConnected: false,
  1277. mockDebugLogBridgeStatusText: '已关闭 (wss://gs.gotomars.xyz/debug-log)',
  1278. mockDebugLogBridgeUrlText: 'wss://gs.gotomars.xyz/debug-log',
  1279. mockDebugLogBridgeUrlDraft: 'wss://gs.gotomars.xyz/debug-log',
  1280. panelSpeedValueText: '0',
  1281. panelSpeedFxClass: '',
  1282. panelTelemetryTone: 'blue',
  1283. gpsLogoStatusText: '未配置',
  1284. gpsLogoSourceText: '--',
  1285. panelHeartRateZoneNameText: '--',
  1286. panelHeartRateZoneRangeText: '',
  1287. heartRateConnected: false,
  1288. heartRateStatusText: '心率带未连接',
  1289. heartRateDeviceText: '--',
  1290. panelHeartRateValueText: '--',
  1291. panelHeartRateFxClass: '',
  1292. panelHeartRateUnitText: '',
  1293. panelCaloriesValueText: '0',
  1294. panelCaloriesUnitText: 'kcal',
  1295. panelAverageSpeedValueText: '0',
  1296. panelAverageSpeedUnitText: 'km/h',
  1297. panelAccuracyValueText: '--',
  1298. panelAccuracyUnitText: '',
  1299. deviceHeadingText: '--',
  1300. devicePoseText: '竖持',
  1301. headingConfidenceText: '低',
  1302. accelerometerText: '--',
  1303. gyroscopeText: '--',
  1304. deviceMotionText: '--',
  1305. compassSourceText: '无数据',
  1306. compassTuningProfileText: initialEngineData.compassTuningProfileText || '平衡',
  1307. punchButtonText: '打点',
  1308. punchButtonEnabled: false,
  1309. skipButtonEnabled: false,
  1310. punchHintText: '等待进入检查点范围',
  1311. punchHintFxClass: '',
  1312. punchFeedbackVisible: false,
  1313. punchFeedbackText: '',
  1314. punchFeedbackTone: 'neutral',
  1315. contentCardVisible: false,
  1316. contentCardTemplate: 'story',
  1317. contentCardTitle: '',
  1318. contentCardBody: '',
  1319. contentCardActions: [],
  1320. contentQuizVisible: false,
  1321. contentQuizQuestionText: '',
  1322. contentQuizCountdownText: '',
  1323. contentQuizOptions: [],
  1324. contentQuizFeedbackVisible: false,
  1325. contentQuizFeedbackText: '',
  1326. contentQuizFeedbackTone: 'neutral',
  1327. punchButtonFxClass: '',
  1328. panelProgressFxClass: '',
  1329. panelDistanceFxClass: '',
  1330. punchFeedbackFxClass: '',
  1331. contentCardFxClass: '',
  1332. mapPulseVisible: false,
  1333. mapPulseLeftPx: 0,
  1334. mapPulseTopPx: 0,
  1335. mapPulseFxClass: '',
  1336. stageFxVisible: false,
  1337. stageFxClass: '',
  1338. compassTicks: buildCompassTicks(),
  1339. compassLabels: buildCompassLabels(),
  1340. ...buildSideButtonVisibility('shown'),
  1341. ...buildSideButtonState({
  1342. sideButtonMode: 'shown',
  1343. showGameInfoPanel: false,
  1344. showSystemSettingsPanel: false,
  1345. showCenterScaleRuler: initialSystemSettings.showCenterScaleRuler,
  1346. centerScaleRulerAnchorMode: initialSystemSettings.centerScaleRulerAnchorMode,
  1347. skipButtonEnabled: false,
  1348. gameSessionStatus: 'idle',
  1349. gpsLockEnabled: false,
  1350. gpsLockAvailable: false,
  1351. }),
  1352. ...buildCenterScaleRulerPatch({
  1353. ...(mapEngine.getInitialData() as MapPageData),
  1354. showCenterScaleRuler: initialSystemSettings.showCenterScaleRuler,
  1355. centerScaleRulerAnchorMode: initialSystemSettings.centerScaleRulerAnchorMode,
  1356. stageWidth: 0,
  1357. stageHeight: 0,
  1358. topInsetHeight: Math.max(statusBarHeight + 12, menuButtonBottom + 20),
  1359. zoom: 0,
  1360. centerTileY: 0,
  1361. tileSizePx: 0,
  1362. }),
  1363. }, () => {
  1364. if (shouldAutoConnectMockSources) {
  1365. this.handleConnectAllMockSources()
  1366. }
  1367. })
  1368. },
  1369. onReady() {
  1370. stageCanvasAttached = false
  1371. this.measureStageAndCanvas()
  1372. this.loadGameLaunchEnvelope(currentGameLaunchEnvelope)
  1373. const app = getApp<IAppOption>()
  1374. const pendingHeartRateAutoConnect = app.globalData ? app.globalData.pendingHeartRateAutoConnect : null
  1375. if (pendingHeartRateAutoConnect && pendingHeartRateAutoConnect.enabled && mapEngine) {
  1376. const pendingDeviceName = pendingHeartRateAutoConnect.deviceName || '心率带'
  1377. app.globalData.pendingHeartRateAutoConnect = null
  1378. mapEngine.handleConnectHeartRate()
  1379. this.setData({
  1380. statusText: `正在自动连接局前设备:${pendingDeviceName}`,
  1381. heartRateStatusText: `正在自动连接 ${pendingDeviceName}`,
  1382. heartRateDeviceText: pendingDeviceName,
  1383. })
  1384. }
  1385. },
  1386. onShow() {
  1387. if (mapEngine) {
  1388. this.applyCompiledRuntimeProfiles()
  1389. mapEngine.handleAppShow()
  1390. }
  1391. },
  1392. onHide() {
  1393. this.persistSessionRecoverySnapshot()
  1394. clearResultExitRedirectTimer()
  1395. clearResultExitCountdownTimer()
  1396. if (mapEngine) {
  1397. mapEngine.handleAppHide()
  1398. }
  1399. },
  1400. onUnload() {
  1401. this.persistSessionRecoverySnapshot()
  1402. clearSessionRecoveryPersistTimer()
  1403. clearResultExitRedirectTimer()
  1404. clearResultExitCountdownTimer()
  1405. syncedBackendSessionStartId = ''
  1406. syncedBackendSessionFinishId = ''
  1407. clearGameInfoPanelSyncTimer()
  1408. clearCenterScaleRulerSyncTimer()
  1409. clearCenterScaleRulerUpdateTimer()
  1410. clearPunchHintDismissTimer()
  1411. clearPunchHintFxTimer()
  1412. clearHudFxTimer('timer')
  1413. clearHudFxTimer('mileage')
  1414. clearHudFxTimer('speed')
  1415. clearHudFxTimer('heartRate')
  1416. if (mapEngine) {
  1417. mapEngine.destroy()
  1418. mapEngine = null
  1419. }
  1420. currentSystemSettingsConfig = undefined
  1421. currentRemoteMapConfig = undefined
  1422. systemSettingsLockLifetimeActive = false
  1423. currentGameLaunchEnvelope = getDemoGameLaunchEnvelope()
  1424. shouldAutoRestoreRecoverySnapshot = false
  1425. redirectedToResultPage = false
  1426. stageCanvasAttached = false
  1427. },
  1428. loadGameLaunchEnvelope(envelope: GameLaunchEnvelope) {
  1429. this.loadMapConfigFromRemote(
  1430. envelope.config.configUrl,
  1431. envelope.config.configLabel,
  1432. )
  1433. },
  1434. persistSessionRecoverySnapshot() {
  1435. if (!mapEngine || !currentRemoteMapConfig) {
  1436. return false
  1437. }
  1438. const runtimeSnapshot = mapEngine.buildSessionRecoveryRuntimeSnapshot()
  1439. if (!runtimeSnapshot) {
  1440. return false
  1441. }
  1442. const snapshot: SessionRecoverySnapshot = {
  1443. schemaVersion: 1,
  1444. savedAt: Date.now(),
  1445. launchEnvelope: currentGameLaunchEnvelope,
  1446. configAppId: currentRemoteMapConfig.configAppId,
  1447. configVersion: currentRemoteMapConfig.configVersion,
  1448. runtime: runtimeSnapshot,
  1449. }
  1450. saveSessionRecoverySnapshot(snapshot)
  1451. return true
  1452. },
  1453. syncBackendSessionStart() {
  1454. const sessionContext = getCurrentBackendSessionContext()
  1455. if (!sessionContext || syncedBackendSessionStartId === sessionContext.sessionId) {
  1456. return
  1457. }
  1458. startSession({
  1459. baseUrl: getCurrentBackendBaseUrl(),
  1460. sessionId: sessionContext.sessionId,
  1461. sessionToken: sessionContext.sessionToken,
  1462. })
  1463. .then(() => {
  1464. syncedBackendSessionStartId = sessionContext.sessionId
  1465. })
  1466. .catch((error) => {
  1467. const message = error && error.message ? error.message : '未知错误'
  1468. this.setData({
  1469. statusText: `session start 上报失败: ${message}`,
  1470. })
  1471. })
  1472. },
  1473. syncBackendSessionFinish(statusOverride?: 'finished' | 'failed' | 'cancelled') {
  1474. const sessionContext = getCurrentBackendSessionContext()
  1475. if (!sessionContext || syncedBackendSessionFinishId === sessionContext.sessionId || !mapEngine) {
  1476. return
  1477. }
  1478. const finishSummary = mapEngine.getSessionFinishSummary(statusOverride)
  1479. if (!finishSummary) {
  1480. return
  1481. }
  1482. const summaryPayload: BackendSessionFinishSummaryPayload = {}
  1483. if (typeof finishSummary.finalDurationSec === 'number') {
  1484. summaryPayload.finalDurationSec = finishSummary.finalDurationSec
  1485. }
  1486. if (typeof finishSummary.finalScore === 'number') {
  1487. summaryPayload.finalScore = finishSummary.finalScore
  1488. }
  1489. if (typeof finishSummary.completedControls === 'number') {
  1490. summaryPayload.completedControls = finishSummary.completedControls
  1491. }
  1492. if (typeof finishSummary.totalControls === 'number') {
  1493. summaryPayload.totalControls = finishSummary.totalControls
  1494. }
  1495. if (typeof finishSummary.distanceMeters === 'number') {
  1496. summaryPayload.distanceMeters = finishSummary.distanceMeters
  1497. }
  1498. if (typeof finishSummary.averageSpeedKmh === 'number') {
  1499. summaryPayload.averageSpeedKmh = finishSummary.averageSpeedKmh
  1500. }
  1501. finishSession({
  1502. baseUrl: getCurrentBackendBaseUrl(),
  1503. sessionId: sessionContext.sessionId,
  1504. sessionToken: sessionContext.sessionToken,
  1505. status: finishSummary.status,
  1506. summary: summaryPayload,
  1507. })
  1508. .then(() => {
  1509. syncedBackendSessionFinishId = sessionContext.sessionId
  1510. })
  1511. .catch((error) => {
  1512. const message = error && error.message ? error.message : '未知错误'
  1513. this.setData({
  1514. statusText: `session finish 上报失败: ${message}`,
  1515. })
  1516. })
  1517. },
  1518. reportAbandonedRecoverySnapshot(snapshot: SessionRecoverySnapshot) {
  1519. const sessionContext = getBackendSessionContextFromLaunchEnvelope(snapshot.launchEnvelope)
  1520. if (!sessionContext) {
  1521. clearSessionRecoverySnapshot()
  1522. return
  1523. }
  1524. finishSession({
  1525. baseUrl: getCurrentBackendBaseUrl(),
  1526. sessionId: sessionContext.sessionId,
  1527. sessionToken: sessionContext.sessionToken,
  1528. status: 'cancelled',
  1529. summary: {},
  1530. })
  1531. .then(() => {
  1532. syncedBackendSessionFinishId = sessionContext.sessionId
  1533. clearSessionRecoverySnapshot()
  1534. wx.showToast({
  1535. title: '已放弃上次对局',
  1536. icon: 'none',
  1537. duration: 1400,
  1538. })
  1539. })
  1540. .catch((error) => {
  1541. clearSessionRecoverySnapshot()
  1542. const message = error && error.message ? error.message : '未知错误'
  1543. this.setData({
  1544. statusText: `放弃恢复已生效,后端取消上报失败: ${message}`,
  1545. })
  1546. wx.showToast({
  1547. title: '已放弃上次对局',
  1548. icon: 'none',
  1549. duration: 1400,
  1550. })
  1551. })
  1552. },
  1553. stashPendingResultSnapshot(snapshot: MapEngineResultSnapshot) {
  1554. const app = getApp<IAppOption>()
  1555. if (app.globalData) {
  1556. app.globalData.pendingResultSnapshot = snapshot
  1557. app.globalData.pendingResultLaunchEnvelope = currentGameLaunchEnvelope
  1558. }
  1559. },
  1560. redirectToResultPage() {
  1561. if (redirectedToResultPage) {
  1562. return
  1563. }
  1564. clearResultExitRedirectTimer()
  1565. clearResultExitCountdownTimer()
  1566. redirectedToResultPage = true
  1567. const sessionContext = getCurrentBackendSessionContext()
  1568. const resultUrl = sessionContext
  1569. ? `/pages/result/result?sessionId=${encodeURIComponent(sessionContext.sessionId)}`
  1570. : '/pages/result/result'
  1571. wx.redirectTo({
  1572. url: resultUrl,
  1573. })
  1574. },
  1575. presentResultExitPrompt() {
  1576. clearResultExitRedirectTimer()
  1577. clearResultExitCountdownTimer()
  1578. let remainingSeconds = Math.ceil(RESULT_EXIT_REDIRECT_DELAY_MS / 1000)
  1579. this.setData({
  1580. showResultScene: true,
  1581. resultSceneCountdownText: `${remainingSeconds} 秒后自动进入成绩页`,
  1582. })
  1583. resultExitCountdownTimer = setInterval(() => {
  1584. remainingSeconds -= 1
  1585. if (remainingSeconds <= 0) {
  1586. clearResultExitCountdownTimer()
  1587. return
  1588. }
  1589. this.setData({
  1590. resultSceneCountdownText: `${remainingSeconds} 秒后自动进入成绩页`,
  1591. })
  1592. }, 1000) as unknown as number
  1593. resultExitRedirectTimer = setTimeout(() => {
  1594. resultExitRedirectTimer = 0
  1595. this.redirectToResultPage()
  1596. }, RESULT_EXIT_REDIRECT_DELAY_MS) as unknown as number
  1597. },
  1598. restoreRecoverySnapshot(snapshot: SessionRecoverySnapshot) {
  1599. systemSettingsLockLifetimeActive = true
  1600. this.applyRuntimeSystemSettings(true)
  1601. const restored = mapEngine ? mapEngine.restoreSessionRecoveryRuntimeSnapshot(snapshot.runtime) : false
  1602. if (!restored) {
  1603. clearSessionRecoverySnapshot()
  1604. wx.showToast({
  1605. title: '恢复失败,已回到初始状态',
  1606. icon: 'none',
  1607. duration: 1600,
  1608. })
  1609. return false
  1610. }
  1611. this.setData({
  1612. showResultScene: false,
  1613. showDebugPanel: false,
  1614. showGameInfoPanel: false,
  1615. showSystemSettingsPanel: false,
  1616. })
  1617. const sessionContext = getCurrentBackendSessionContext()
  1618. if (sessionContext) {
  1619. syncedBackendSessionStartId = sessionContext.sessionId
  1620. }
  1621. this.syncSessionRecoveryLifecycle('running')
  1622. return true
  1623. },
  1624. syncSessionRecoveryLifecycle(status: MapPageData['gameSessionStatus']) {
  1625. if (status === 'running') {
  1626. this.persistSessionRecoverySnapshot()
  1627. if (!sessionRecoveryPersistTimer) {
  1628. sessionRecoveryPersistTimer = setInterval(() => {
  1629. this.persistSessionRecoverySnapshot()
  1630. }, SESSION_RECOVERY_PERSIST_INTERVAL_MS) as unknown as number
  1631. }
  1632. return
  1633. }
  1634. clearSessionRecoveryPersistTimer()
  1635. },
  1636. maybePromptSessionRecoveryRestore(config: RemoteMapConfig) {
  1637. const snapshot = loadSessionRecoverySnapshot()
  1638. if (!snapshot || !mapEngine) {
  1639. return
  1640. }
  1641. if (
  1642. snapshot.launchEnvelope.config.configUrl !== currentGameLaunchEnvelope.config.configUrl
  1643. || snapshot.configAppId !== config.configAppId
  1644. || snapshot.configVersion !== config.configVersion
  1645. ) {
  1646. clearSessionRecoverySnapshot()
  1647. return
  1648. }
  1649. if (shouldAutoRestoreRecoverySnapshot) {
  1650. shouldAutoRestoreRecoverySnapshot = false
  1651. this.restoreRecoverySnapshot(snapshot)
  1652. return
  1653. }
  1654. wx.showModal({
  1655. title: '恢复对局',
  1656. content: '检测到上次有未正常结束的对局,是否继续恢复?',
  1657. confirmText: '继续恢复',
  1658. cancelText: '放弃',
  1659. success: (result) => {
  1660. if (!result.confirm) {
  1661. this.reportAbandonedRecoverySnapshot(snapshot)
  1662. return
  1663. }
  1664. this.restoreRecoverySnapshot(snapshot)
  1665. },
  1666. })
  1667. },
  1668. compileCurrentRuntimeProfile(lockLifetimeActive = isSystemSettingsLockLifetimeActive()) {
  1669. if (!currentRemoteMapConfig) {
  1670. return null
  1671. }
  1672. return compileRuntimeProfile(currentRemoteMapConfig, {
  1673. playerTelemetryProfile: getGlobalTelemetryProfile(),
  1674. settingsLockLifetimeActive: lockLifetimeActive,
  1675. })
  1676. },
  1677. applyCompiledRuntimeProfiles(
  1678. lockLifetimeActive = isSystemSettingsLockLifetimeActive(),
  1679. options?: {
  1680. includeSettings?: boolean
  1681. includeMap?: boolean
  1682. includeGame?: boolean
  1683. includePresentation?: boolean
  1684. includeTelemetry?: boolean
  1685. includeFeedback?: boolean
  1686. },
  1687. ) {
  1688. const currentEngine = mapEngine
  1689. if (!currentEngine) {
  1690. return null
  1691. }
  1692. const compiledProfile = this.compileCurrentRuntimeProfile(lockLifetimeActive)
  1693. if (!compiledProfile) {
  1694. return null
  1695. }
  1696. if (options && options.includeMap) {
  1697. currentEngine.applyCompiledMapProfile(compiledProfile.map)
  1698. }
  1699. if (options && options.includeSettings) {
  1700. currentEngine.applyCompiledSettingsProfile(compiledProfile.settings)
  1701. }
  1702. if (options && options.includeGame) {
  1703. currentEngine.applyCompiledGameProfile(compiledProfile.game)
  1704. }
  1705. if (options && options.includePresentation) {
  1706. currentEngine.applyCompiledPresentationProfile(compiledProfile.presentation)
  1707. }
  1708. if (!options || options.includeTelemetry !== false) {
  1709. currentEngine.applyCompiledTelemetryProfile(compiledProfile.telemetry)
  1710. }
  1711. if (!options || options.includeFeedback !== false) {
  1712. currentEngine.applyCompiledFeedbackProfile(compiledProfile.feedback)
  1713. }
  1714. return compiledProfile
  1715. },
  1716. applyRuntimeSystemSettings(lockLifetimeActive = isSystemSettingsLockLifetimeActive()) {
  1717. const currentEngine = mapEngine
  1718. if (!currentEngine) {
  1719. return null
  1720. }
  1721. const compiledProfile = this.applyCompiledRuntimeProfiles(lockLifetimeActive, {
  1722. includeSettings: true,
  1723. })
  1724. || {
  1725. settings: resolveSystemSettingsState(
  1726. currentSystemSettingsConfig,
  1727. undefined,
  1728. lockLifetimeActive,
  1729. ),
  1730. }
  1731. const resolvedSettings = compiledProfile.settings
  1732. const engineSnapshot = currentEngine.getInitialData() as Partial<MapPageData>
  1733. updateCenterScaleRulerInputCache(engineSnapshot)
  1734. const resolvedPatch = buildResolvedSystemSettingsPatch(resolvedSettings)
  1735. const mergedData = {
  1736. ...centerScaleRulerInputCache,
  1737. ...this.data,
  1738. ...engineSnapshot,
  1739. ...resolvedPatch,
  1740. } as MapPageData
  1741. this.setData({
  1742. ...filterDebugOnlyPatch(engineSnapshot, this.data.showDebugPanel, resolvedSettings.values.showCenterScaleRuler),
  1743. ...resolvedPatch,
  1744. ...buildCenterScaleRulerPatch(mergedData),
  1745. ...buildSideButtonState(mergedData),
  1746. })
  1747. return resolvedSettings
  1748. },
  1749. persistAndApplySystemSettings(
  1750. patch: Partial<StoredUserSettings>,
  1751. options?: {
  1752. applyCenterScaleRuler?: boolean
  1753. },
  1754. ) {
  1755. updateStoredUserSettings(patch)
  1756. const lockLifetimeActive = isSystemSettingsLockLifetimeActive()
  1757. const resolvedSettings = this.applyRuntimeSystemSettings(lockLifetimeActive)
  1758. if (!resolvedSettings || !(options && options.applyCenterScaleRuler)) {
  1759. return resolvedSettings
  1760. }
  1761. this.applyCenterScaleRulerSettings(
  1762. resolvedSettings.values.showCenterScaleRuler,
  1763. resolvedSettings.values.centerScaleRulerAnchorMode,
  1764. )
  1765. return resolvedSettings
  1766. },
  1767. loadMapConfigFromRemote(configUrl: string, configLabel: string) {
  1768. const currentEngine = mapEngine
  1769. if (!currentEngine) {
  1770. return
  1771. }
  1772. this.setData({
  1773. configSourceText: configLabel,
  1774. configStatusText: `加载中: ${configLabel}`,
  1775. })
  1776. loadRemoteMapConfig(configUrl)
  1777. .then((config) => {
  1778. if (mapEngine !== currentEngine) {
  1779. return
  1780. }
  1781. currentEngine.applyRemoteMapConfig(config)
  1782. this.applyConfiguredSystemSettings(config)
  1783. this.applyCompiledRuntimeProfiles(true, {
  1784. includeMap: true,
  1785. includeGame: true,
  1786. includePresentation: true,
  1787. })
  1788. this.maybePromptSessionRecoveryRestore(config)
  1789. })
  1790. .catch((error) => {
  1791. if (mapEngine !== currentEngine) {
  1792. return
  1793. }
  1794. const rawErrorMessage = error && error.message ? error.message : '未知错误'
  1795. const errorMessage = rawErrorMessage.indexOf('404') >= 0
  1796. ? `release manifest 不存在或未发布 (${configLabel})`
  1797. : rawErrorMessage
  1798. this.setData({
  1799. configStatusText: `载入失败: ${errorMessage}`,
  1800. statusText: `远程地图配置载入失败: ${errorMessage} (${INTERNAL_BUILD_VERSION})`,
  1801. })
  1802. })
  1803. },
  1804. applyConfiguredSystemSettings(config: RemoteMapConfig) {
  1805. currentRemoteMapConfig = config
  1806. currentSystemSettingsConfig = config.systemSettingsConfig
  1807. systemSettingsLockLifetimeActive = true
  1808. this.applyRuntimeSystemSettings(true)
  1809. },
  1810. measureStageAndCanvas(onApplied?: () => void) {
  1811. const page = this
  1812. const applyStage = (rawRect?: Partial<WechatMiniprogram.BoundingClientRectCallbackResult>) => {
  1813. const fallbackRect = getFallbackStageRect()
  1814. const rect: MapEngineStageRect = {
  1815. width: rawRect && typeof rawRect.width === 'number' ? rawRect.width : fallbackRect.width,
  1816. height: rawRect && typeof rawRect.height === 'number' ? rawRect.height : fallbackRect.height,
  1817. left: rawRect && typeof rawRect.left === 'number' ? rawRect.left : fallbackRect.left,
  1818. top: rawRect && typeof rawRect.top === 'number' ? rawRect.top : fallbackRect.top,
  1819. }
  1820. const currentEngine = mapEngine
  1821. if (!currentEngine) {
  1822. return
  1823. }
  1824. currentEngine.setStage(rect)
  1825. if (onApplied) {
  1826. onApplied()
  1827. }
  1828. if (stageCanvasAttached) {
  1829. return
  1830. }
  1831. const canvasQuery = wx.createSelectorQuery().in(page)
  1832. canvasQuery.select('#mapCanvas').fields({ node: true, size: true })
  1833. canvasQuery.select('#routeLabelCanvas').fields({ node: true, size: true })
  1834. canvasQuery.exec((canvasRes) => {
  1835. const canvasRef = canvasRes[0] as any
  1836. const labelCanvasRef = canvasRes[1] as any
  1837. if (!canvasRef || !canvasRef.node) {
  1838. page.setData({
  1839. statusText: `WebGL 引擎初始化失败 (${INTERNAL_BUILD_VERSION})`,
  1840. })
  1841. return
  1842. }
  1843. const dpr = wx.getSystemInfoSync().pixelRatio || 1
  1844. try {
  1845. currentEngine.attachCanvas(
  1846. canvasRef.node,
  1847. rect.width,
  1848. rect.height,
  1849. dpr,
  1850. labelCanvasRef && labelCanvasRef.node ? labelCanvasRef.node : undefined,
  1851. )
  1852. stageCanvasAttached = true
  1853. } catch (error) {
  1854. page.setData({
  1855. statusText: `WebGL 鍒濆鍖栧け璐?(${INTERNAL_BUILD_VERSION})`,
  1856. })
  1857. }
  1858. })
  1859. }
  1860. const query = wx.createSelectorQuery().in(page)
  1861. query.select('.map-stage').boundingClientRect()
  1862. query.exec((res) => {
  1863. const rect = res[0] as WechatMiniprogram.BoundingClientRectCallbackResult | undefined
  1864. applyStage(rect)
  1865. })
  1866. },
  1867. handleTouchStart(event: WechatMiniprogram.TouchEvent) {
  1868. if (mapEngine) {
  1869. mapEngine.handleTouchStart(event)
  1870. }
  1871. },
  1872. handleTouchMove(event: WechatMiniprogram.TouchEvent) {
  1873. if (mapEngine) {
  1874. mapEngine.handleTouchMove(event)
  1875. }
  1876. },
  1877. handleTouchEnd(event: WechatMiniprogram.TouchEvent) {
  1878. if (mapEngine) {
  1879. mapEngine.handleTouchEnd(event)
  1880. }
  1881. },
  1882. handleTouchCancel() {
  1883. if (mapEngine) {
  1884. mapEngine.handleTouchCancel()
  1885. }
  1886. },
  1887. handleRecenter() {
  1888. if (mapEngine) {
  1889. mapEngine.handleRecenter()
  1890. }
  1891. },
  1892. handleRotateStep() {
  1893. if (mapEngine) {
  1894. mapEngine.handleRotateStep()
  1895. }
  1896. },
  1897. handleRotationReset() {
  1898. if (mapEngine) {
  1899. mapEngine.handleRotationReset()
  1900. }
  1901. },
  1902. handleSetManualMode() {
  1903. if (mapEngine) {
  1904. mapEngine.handleSetManualMode()
  1905. }
  1906. },
  1907. handleSetNorthUpMode() {
  1908. if (mapEngine) {
  1909. mapEngine.handleSetNorthUpMode()
  1910. }
  1911. },
  1912. handleSetHeadingUpMode() {
  1913. if (mapEngine) {
  1914. mapEngine.handleSetHeadingUpMode()
  1915. }
  1916. },
  1917. handleCycleNorthReferenceMode() {
  1918. if (mapEngine) {
  1919. mapEngine.handleCycleNorthReferenceMode()
  1920. }
  1921. },
  1922. handleAutoRotateCalibrate() {
  1923. if (mapEngine) {
  1924. mapEngine.handleAutoRotateCalibrate()
  1925. }
  1926. },
  1927. handleToggleGpsTracking() {
  1928. if (mapEngine) {
  1929. mapEngine.handleToggleGpsTracking()
  1930. }
  1931. },
  1932. handleSetRealLocationMode() {
  1933. if (mapEngine) {
  1934. mapEngine.handleSetRealLocationMode()
  1935. }
  1936. },
  1937. handleSetMockLocationMode() {
  1938. if (mapEngine) {
  1939. mapEngine.handleSetMockLocationMode()
  1940. }
  1941. },
  1942. handleConnectMockLocationBridge() {
  1943. if (mapEngine) {
  1944. mapEngine.handleConnectMockLocationBridge()
  1945. }
  1946. },
  1947. handleConnectAllMockSources() {
  1948. if (!mapEngine) {
  1949. return
  1950. }
  1951. const channelId = (this.data.mockChannelIdDraft || '').trim() || 'default'
  1952. this.setData({
  1953. mockChannelIdDraft: channelId,
  1954. })
  1955. persistMockChannelId(channelId)
  1956. persistMockAutoConnectEnabled(true)
  1957. mapEngine.handleSetMockChannelId(channelId)
  1958. mapEngine.handleSetMockLocationBridgeUrl(this.data.mockBridgeUrlDraft)
  1959. mapEngine.handleSetMockHeartRateBridgeUrl(this.data.mockHeartRateBridgeUrlDraft)
  1960. mapEngine.handleSetMockDebugLogBridgeUrl(this.data.mockDebugLogBridgeUrlDraft)
  1961. mapEngine.handleConnectMockLocationBridge()
  1962. mapEngine.handleSetMockLocationMode()
  1963. mapEngine.handleSetMockHeartRateMode()
  1964. mapEngine.handleConnectMockHeartRateBridge()
  1965. mapEngine.handleConnectMockDebugLogBridge()
  1966. },
  1967. handleOpenWebViewTest() {
  1968. wx.navigateTo({
  1969. url: '/pages/webview-test/webview-test',
  1970. })
  1971. },
  1972. handleMockChannelIdInput(event: WechatMiniprogram.Input) {
  1973. this.setData({
  1974. mockChannelIdDraft: event.detail.value,
  1975. })
  1976. },
  1977. handleSaveMockChannelId() {
  1978. const channelId = (this.data.mockChannelIdDraft || '').trim() || 'default'
  1979. this.setData({
  1980. mockChannelIdDraft: channelId,
  1981. })
  1982. persistMockChannelId(channelId)
  1983. if (mapEngine) {
  1984. mapEngine.handleSetMockChannelId(channelId)
  1985. }
  1986. },
  1987. handleMockBridgeUrlInput(event: WechatMiniprogram.Input) {
  1988. this.setData({
  1989. mockBridgeUrlDraft: event.detail.value,
  1990. })
  1991. },
  1992. handleSaveMockBridgeUrl() {
  1993. if (mapEngine) {
  1994. mapEngine.handleSetMockLocationBridgeUrl(this.data.mockBridgeUrlDraft)
  1995. }
  1996. },
  1997. handleDisconnectMockLocationBridge() {
  1998. persistMockAutoConnectEnabled(false)
  1999. if (mapEngine) {
  2000. mapEngine.handleDisconnectMockLocationBridge()
  2001. }
  2002. },
  2003. handleSetRealHeartRateMode() {
  2004. if (mapEngine) {
  2005. mapEngine.handleSetRealHeartRateMode()
  2006. }
  2007. },
  2008. handleSetMockHeartRateMode() {
  2009. if (mapEngine) {
  2010. mapEngine.handleSetMockHeartRateMode()
  2011. }
  2012. },
  2013. handleMockHeartRateBridgeUrlInput(event: WechatMiniprogram.Input) {
  2014. this.setData({
  2015. mockHeartRateBridgeUrlDraft: event.detail.value,
  2016. })
  2017. },
  2018. handleSaveMockHeartRateBridgeUrl() {
  2019. if (mapEngine) {
  2020. mapEngine.handleSetMockHeartRateBridgeUrl(this.data.mockHeartRateBridgeUrlDraft)
  2021. }
  2022. },
  2023. handleMockDebugLogBridgeUrlInput(event: WechatMiniprogram.Input) {
  2024. this.setData({
  2025. mockDebugLogBridgeUrlDraft: event.detail.value,
  2026. })
  2027. },
  2028. handleSaveMockDebugLogBridgeUrl() {
  2029. if (mapEngine) {
  2030. mapEngine.handleSetMockDebugLogBridgeUrl(this.data.mockDebugLogBridgeUrlDraft)
  2031. }
  2032. },
  2033. handleConnectMockDebugLogBridge() {
  2034. if (mapEngine) {
  2035. mapEngine.handleConnectMockDebugLogBridge()
  2036. }
  2037. },
  2038. handleDisconnectMockDebugLogBridge() {
  2039. persistMockAutoConnectEnabled(false)
  2040. if (mapEngine) {
  2041. mapEngine.handleDisconnectMockDebugLogBridge()
  2042. }
  2043. },
  2044. handleConnectMockHeartRateBridge() {
  2045. if (mapEngine) {
  2046. mapEngine.handleConnectMockHeartRateBridge()
  2047. }
  2048. },
  2049. handleDisconnectMockHeartRateBridge() {
  2050. persistMockAutoConnectEnabled(false)
  2051. if (mapEngine) {
  2052. mapEngine.handleDisconnectMockHeartRateBridge()
  2053. }
  2054. },
  2055. handleConnectHeartRate() {
  2056. if (this.data.lockHeartRateDevice || this.data.heartRateSourceMode !== 'real') {
  2057. return
  2058. }
  2059. if (mapEngine) {
  2060. mapEngine.handleConnectHeartRate()
  2061. }
  2062. },
  2063. handleOpenHeartRateDevicePicker() {
  2064. if (this.data.lockHeartRateDevice || this.data.heartRateSourceMode !== 'real') {
  2065. return
  2066. }
  2067. this.setData({
  2068. showHeartRateDevicePicker: true,
  2069. })
  2070. if (mapEngine) {
  2071. mapEngine.handleConnectHeartRate()
  2072. }
  2073. },
  2074. handleCloseHeartRateDevicePicker() {
  2075. this.setData({
  2076. showHeartRateDevicePicker: false,
  2077. })
  2078. },
  2079. handleDisconnectHeartRate() {
  2080. if (this.data.lockHeartRateDevice || this.data.heartRateSourceMode !== 'real') {
  2081. return
  2082. }
  2083. if (mapEngine) {
  2084. mapEngine.handleDisconnectHeartRate()
  2085. }
  2086. },
  2087. handleConnectHeartRateDevice(event: WechatMiniprogram.BaseEvent<{ deviceId?: string }>) {
  2088. if (mapEngine && event.currentTarget && event.currentTarget.dataset && event.currentTarget.dataset.deviceId) {
  2089. const targetDeviceId = event.currentTarget.dataset.deviceId
  2090. const targetDevice = this.data.heartRateDiscoveredDevices.find((item) => item.deviceId === targetDeviceId)
  2091. pendingHeartRateSwitchDeviceName = targetDevice ? targetDevice.name : null
  2092. mapEngine.handleConnectHeartRateDevice(targetDeviceId)
  2093. this.setData({
  2094. showHeartRateDevicePicker: false,
  2095. statusText: targetDevice
  2096. ? `正在切换到 ${targetDevice.name}`
  2097. : '正在切换心率带设备',
  2098. })
  2099. }
  2100. },
  2101. handleClearPreferredHeartRateDevice() {
  2102. if (this.data.lockHeartRateDevice) {
  2103. return
  2104. }
  2105. if (mapEngine) {
  2106. mapEngine.handleClearPreferredHeartRateDevice()
  2107. }
  2108. },
  2109. handleDebugHeartRateBlue() {
  2110. if (mapEngine) {
  2111. mapEngine.handleDebugHeartRateTone('blue')
  2112. }
  2113. },
  2114. handleDebugHeartRatePurple() {
  2115. if (mapEngine) {
  2116. mapEngine.handleDebugHeartRateTone('purple')
  2117. }
  2118. },
  2119. handleDebugHeartRateGreen() {
  2120. if (mapEngine) {
  2121. mapEngine.handleDebugHeartRateTone('green')
  2122. }
  2123. },
  2124. handleDebugHeartRateYellow() {
  2125. if (mapEngine) {
  2126. mapEngine.handleDebugHeartRateTone('yellow')
  2127. }
  2128. },
  2129. handleDebugHeartRateOrange() {
  2130. if (mapEngine) {
  2131. mapEngine.handleDebugHeartRateTone('orange')
  2132. }
  2133. },
  2134. handleDebugHeartRateRed() {
  2135. if (mapEngine) {
  2136. mapEngine.handleDebugHeartRateTone('red')
  2137. }
  2138. },
  2139. handleDebugSetSessionRemainingWarning() {
  2140. if (mapEngine) {
  2141. mapEngine.handleDebugSetSessionRemainingWarning()
  2142. }
  2143. },
  2144. handleDebugSetSessionRemainingOneMinute() {
  2145. if (mapEngine) {
  2146. mapEngine.handleDebugSetSessionRemainingOneMinute()
  2147. }
  2148. },
  2149. handleDebugTimeoutSession() {
  2150. if (mapEngine) {
  2151. mapEngine.handleDebugTimeoutSession()
  2152. }
  2153. },
  2154. handleClearDebugHeartRate() {
  2155. if (mapEngine) {
  2156. mapEngine.handleClearDebugHeartRate()
  2157. }
  2158. },
  2159. handleToggleOsmReference() {
  2160. if (mapEngine) {
  2161. mapEngine.handleToggleOsmReference()
  2162. }
  2163. },
  2164. handleStartGame() {
  2165. if (mapEngine) {
  2166. systemSettingsLockLifetimeActive = true
  2167. this.applyRuntimeSystemSettings(true)
  2168. mapEngine.handleStartGame()
  2169. }
  2170. },
  2171. handleLoadClassicConfig() {
  2172. currentGameLaunchEnvelope = getDemoGameLaunchEnvelope('classic')
  2173. this.loadGameLaunchEnvelope(currentGameLaunchEnvelope)
  2174. },
  2175. handleLoadScoreOConfig() {
  2176. currentGameLaunchEnvelope = getDemoGameLaunchEnvelope('score-o')
  2177. this.loadGameLaunchEnvelope(currentGameLaunchEnvelope)
  2178. },
  2179. handleForceExitGame() {
  2180. if (!mapEngine || this.data.gameSessionStatus !== 'running') {
  2181. return
  2182. }
  2183. wx.showModal({
  2184. title: '确认退出',
  2185. content: '确认强制结束当前对局并返回开始前状态?',
  2186. confirmText: '确认退出',
  2187. cancelText: '取消',
  2188. success: (result) => {
  2189. if (result.confirm && mapEngine) {
  2190. clearResultExitRedirectTimer()
  2191. clearResultExitCountdownTimer()
  2192. this.syncBackendSessionFinish('cancelled')
  2193. clearSessionRecoverySnapshot()
  2194. clearSessionRecoveryPersistTimer()
  2195. systemSettingsLockLifetimeActive = false
  2196. mapEngine.handleForceExitGame()
  2197. wx.showToast({
  2198. title: '已退出当前对局',
  2199. icon: 'none',
  2200. duration: 1000,
  2201. })
  2202. setTimeout(() => {
  2203. navigateAwayFromMapAfterCancel()
  2204. }, 180)
  2205. }
  2206. },
  2207. })
  2208. },
  2209. handleSkipAction() {
  2210. if (!mapEngine || !this.data.skipButtonEnabled) {
  2211. return
  2212. }
  2213. if (!mapEngine.shouldConfirmSkipAction()) {
  2214. mapEngine.handleSkipAction()
  2215. return
  2216. }
  2217. wx.showModal({
  2218. title: '确认跳点',
  2219. content: '确认跳过当前检查点并切换到下一个目标点?',
  2220. confirmText: '确认跳过',
  2221. cancelText: '取消',
  2222. success: (result) => {
  2223. if (result.confirm && mapEngine) {
  2224. mapEngine.handleSkipAction()
  2225. }
  2226. },
  2227. })
  2228. },
  2229. handleClearMapTestArtifacts() {
  2230. if (mapEngine) {
  2231. mapEngine.handleClearMapTestArtifacts()
  2232. }
  2233. },
  2234. syncGameInfoPanelSnapshot() {
  2235. if (!mapEngine) {
  2236. return
  2237. }
  2238. const snapshot = mapEngine.getGameInfoSnapshot()
  2239. const localRows = snapshot.localRows.concat([
  2240. ...buildRuntimeSummaryRows(currentGameLaunchEnvelope),
  2241. { label: '比例尺开关', value: this.data.showCenterScaleRuler ? '开启' : '关闭' },
  2242. { label: '比例尺锚点', value: this.data.centerScaleRulerAnchorMode === 'compass-center' ? '指北针圆心' : '屏幕中心' },
  2243. { label: '按钮习惯', value: this.data.sideButtonPlacement === 'right' ? '右手' : '左手' },
  2244. { label: '比例尺可见', value: this.data.centerScaleRulerVisible ? 'true' : 'false' },
  2245. { label: '比例尺中心X', value: `${this.data.centerScaleRulerCenterXPx}px` },
  2246. { label: '比例尺零点Y', value: `${this.data.centerScaleRulerZeroYPx}px` },
  2247. { label: '比例尺高度', value: `${this.data.centerScaleRulerHeightPx}px` },
  2248. { label: '比例尺主刻度数', value: String(this.data.centerScaleRulerMajorMarks.length) },
  2249. ])
  2250. this.setData({
  2251. gameInfoTitle: snapshot.title,
  2252. gameInfoSubtitle: snapshot.subtitle,
  2253. gameInfoLocalRows: localRows,
  2254. gameInfoGlobalRows: snapshot.globalRows,
  2255. })
  2256. },
  2257. syncResultSceneSnapshot() {
  2258. if (!mapEngine) {
  2259. return
  2260. }
  2261. const snapshot = mapEngine.getResultSceneSnapshot()
  2262. this.setData({
  2263. resultSceneTitle: snapshot.title,
  2264. resultSceneSubtitle: snapshot.subtitle,
  2265. resultSceneHeroLabel: snapshot.heroLabel,
  2266. resultSceneHeroValue: snapshot.heroValue,
  2267. resultSceneRows: snapshot.rows.concat(buildRuntimeSummaryRows(currentGameLaunchEnvelope)),
  2268. })
  2269. },
  2270. scheduleGameInfoPanelSnapshotSync() {
  2271. if (!this.data.showGameInfoPanel) {
  2272. clearGameInfoPanelSyncTimer()
  2273. return
  2274. }
  2275. if (gameInfoPanelSyncTimer) {
  2276. return
  2277. }
  2278. gameInfoPanelSyncTimer = setTimeout(() => {
  2279. gameInfoPanelSyncTimer = 0
  2280. if (this.data.showGameInfoPanel) {
  2281. this.syncGameInfoPanelSnapshot()
  2282. }
  2283. }, 400) as unknown as number
  2284. },
  2285. handleOpenGameInfoPanel() {
  2286. clearGameInfoPanelSyncTimer()
  2287. this.syncGameInfoPanelSnapshot()
  2288. this.setData({
  2289. showDebugPanel: false,
  2290. showSystemSettingsPanel: false,
  2291. showGameInfoPanel: true,
  2292. ...buildSideButtonState({
  2293. sideButtonMode: this.data.sideButtonMode,
  2294. showGameInfoPanel: true,
  2295. showSystemSettingsPanel: false,
  2296. showCenterScaleRuler: this.data.showCenterScaleRuler,
  2297. centerScaleRulerAnchorMode: this.data.centerScaleRulerAnchorMode,
  2298. skipButtonEnabled: this.data.skipButtonEnabled,
  2299. gameSessionStatus: this.data.gameSessionStatus,
  2300. gpsLockEnabled: this.data.gpsLockEnabled,
  2301. gpsLockAvailable: this.data.gpsLockAvailable,
  2302. }),
  2303. })
  2304. },
  2305. handleCloseGameInfoPanel() {
  2306. clearGameInfoPanelSyncTimer()
  2307. this.setData({
  2308. showGameInfoPanel: false,
  2309. ...buildSideButtonState({
  2310. sideButtonMode: this.data.sideButtonMode,
  2311. showGameInfoPanel: false,
  2312. showSystemSettingsPanel: this.data.showSystemSettingsPanel,
  2313. showCenterScaleRuler: this.data.showCenterScaleRuler,
  2314. centerScaleRulerAnchorMode: this.data.centerScaleRulerAnchorMode,
  2315. skipButtonEnabled: this.data.skipButtonEnabled,
  2316. gameSessionStatus: this.data.gameSessionStatus,
  2317. gpsLockEnabled: this.data.gpsLockEnabled,
  2318. gpsLockAvailable: this.data.gpsLockAvailable,
  2319. }),
  2320. })
  2321. },
  2322. handleGameInfoPanelTap() {},
  2323. handleResultSceneTap() {},
  2324. handleCloseResultScene() {
  2325. this.redirectToResultPage()
  2326. },
  2327. handleRestartFromResult() {
  2328. this.redirectToResultPage()
  2329. },
  2330. handleOpenSystemSettingsPanel() {
  2331. clearGameInfoPanelSyncTimer()
  2332. this.setData({
  2333. showDebugPanel: false,
  2334. showGameInfoPanel: false,
  2335. showSystemSettingsPanel: true,
  2336. ...buildSideButtonState({
  2337. sideButtonMode: this.data.sideButtonMode,
  2338. showGameInfoPanel: false,
  2339. showSystemSettingsPanel: true,
  2340. showCenterScaleRuler: this.data.showCenterScaleRuler,
  2341. centerScaleRulerAnchorMode: this.data.centerScaleRulerAnchorMode,
  2342. skipButtonEnabled: this.data.skipButtonEnabled,
  2343. gameSessionStatus: this.data.gameSessionStatus,
  2344. gpsLockEnabled: this.data.gpsLockEnabled,
  2345. gpsLockAvailable: this.data.gpsLockAvailable,
  2346. }),
  2347. })
  2348. },
  2349. handleCloseSystemSettingsPanel() {
  2350. this.setData({
  2351. showSystemSettingsPanel: false,
  2352. ...buildSideButtonState({
  2353. sideButtonMode: this.data.sideButtonMode,
  2354. showGameInfoPanel: this.data.showGameInfoPanel,
  2355. showSystemSettingsPanel: false,
  2356. showCenterScaleRuler: this.data.showCenterScaleRuler,
  2357. centerScaleRulerAnchorMode: this.data.centerScaleRulerAnchorMode,
  2358. skipButtonEnabled: this.data.skipButtonEnabled,
  2359. gameSessionStatus: this.data.gameSessionStatus,
  2360. gpsLockEnabled: this.data.gpsLockEnabled,
  2361. gpsLockAvailable: this.data.gpsLockAvailable,
  2362. }),
  2363. })
  2364. },
  2365. handleSystemSettingsPanelTap() {},
  2366. handleSetAnimationLevelStandard() {
  2367. if (this.data.lockAnimationLevel || !mapEngine) {
  2368. return
  2369. }
  2370. this.persistAndApplySystemSettings({
  2371. animationLevel: 'standard',
  2372. })
  2373. },
  2374. handleSetAnimationLevelLite() {
  2375. if (this.data.lockAnimationLevel || !mapEngine) {
  2376. return
  2377. }
  2378. this.persistAndApplySystemSettings({
  2379. animationLevel: 'lite',
  2380. })
  2381. },
  2382. handleSetTrackModeNone() {
  2383. if (this.data.lockTrackMode || !mapEngine) {
  2384. return
  2385. }
  2386. this.persistAndApplySystemSettings({
  2387. trackDisplayMode: 'none',
  2388. })
  2389. },
  2390. handleSetTrackModeTail() {
  2391. if (this.data.lockTrackMode || !mapEngine) {
  2392. return
  2393. }
  2394. this.persistAndApplySystemSettings({
  2395. trackDisplayMode: 'tail',
  2396. })
  2397. },
  2398. handleSetTrackModeFull() {
  2399. if (this.data.lockTrackMode || !mapEngine) {
  2400. return
  2401. }
  2402. this.persistAndApplySystemSettings({
  2403. trackDisplayMode: 'full',
  2404. })
  2405. },
  2406. handleSetTrackTailLengthShort() {
  2407. if (this.data.lockTrackTailLength || !mapEngine) {
  2408. return
  2409. }
  2410. this.persistAndApplySystemSettings({
  2411. trackTailLength: 'short',
  2412. })
  2413. },
  2414. handleSetTrackTailLengthMedium() {
  2415. if (this.data.lockTrackTailLength || !mapEngine) {
  2416. return
  2417. }
  2418. this.persistAndApplySystemSettings({
  2419. trackTailLength: 'medium',
  2420. })
  2421. },
  2422. handleSetTrackTailLengthLong() {
  2423. if (this.data.lockTrackTailLength || !mapEngine) {
  2424. return
  2425. }
  2426. this.persistAndApplySystemSettings({
  2427. trackTailLength: 'long',
  2428. })
  2429. },
  2430. handleSetTrackColorPreset(event: WechatMiniprogram.TouchEvent) {
  2431. if (this.data.lockTrackColor || !mapEngine) {
  2432. return
  2433. }
  2434. const color = event.currentTarget.dataset.color as TrackColorPreset | undefined
  2435. if (!color) {
  2436. return
  2437. }
  2438. this.persistAndApplySystemSettings({
  2439. trackColorPreset: color,
  2440. })
  2441. },
  2442. handleSetTrackStyleClassic() {
  2443. if (this.data.lockTrackStyle || !mapEngine) {
  2444. return
  2445. }
  2446. this.persistAndApplySystemSettings({
  2447. trackStyleProfile: 'classic',
  2448. })
  2449. },
  2450. handleSetTrackStyleNeon() {
  2451. if (this.data.lockTrackStyle || !mapEngine) {
  2452. return
  2453. }
  2454. this.persistAndApplySystemSettings({
  2455. trackStyleProfile: 'neon',
  2456. })
  2457. },
  2458. handleSetGpsMarkerVisibleOn() {
  2459. if (this.data.lockGpsMarkerVisible || !mapEngine) {
  2460. return
  2461. }
  2462. this.persistAndApplySystemSettings({
  2463. gpsMarkerVisible: true,
  2464. })
  2465. },
  2466. handleSetGpsMarkerVisibleOff() {
  2467. if (this.data.lockGpsMarkerVisible || !mapEngine) {
  2468. return
  2469. }
  2470. this.persistAndApplySystemSettings({
  2471. gpsMarkerVisible: false,
  2472. })
  2473. },
  2474. handleSetGpsMarkerStyleDot() {
  2475. if (this.data.lockGpsMarkerStyle || !mapEngine) {
  2476. return
  2477. }
  2478. this.persistAndApplySystemSettings({
  2479. gpsMarkerStyle: 'dot',
  2480. })
  2481. },
  2482. handleSetGpsMarkerStyleBeacon() {
  2483. if (this.data.lockGpsMarkerStyle || !mapEngine) {
  2484. return
  2485. }
  2486. this.persistAndApplySystemSettings({
  2487. gpsMarkerStyle: 'beacon',
  2488. })
  2489. },
  2490. handleSetGpsMarkerStyleDisc() {
  2491. if (this.data.lockGpsMarkerStyle || !mapEngine) {
  2492. return
  2493. }
  2494. this.persistAndApplySystemSettings({
  2495. gpsMarkerStyle: 'disc',
  2496. })
  2497. },
  2498. handleSetGpsMarkerStyleBadge() {
  2499. if (this.data.lockGpsMarkerStyle || !mapEngine) {
  2500. return
  2501. }
  2502. this.persistAndApplySystemSettings({
  2503. gpsMarkerStyle: 'badge',
  2504. })
  2505. },
  2506. handleSetGpsMarkerSizeSmall() {
  2507. if (this.data.lockGpsMarkerSize || !mapEngine) {
  2508. return
  2509. }
  2510. this.persistAndApplySystemSettings({
  2511. gpsMarkerSize: 'small',
  2512. })
  2513. },
  2514. handleSetGpsMarkerSizeMedium() {
  2515. if (this.data.lockGpsMarkerSize || !mapEngine) {
  2516. return
  2517. }
  2518. this.persistAndApplySystemSettings({
  2519. gpsMarkerSize: 'medium',
  2520. })
  2521. },
  2522. handleSetGpsMarkerSizeLarge() {
  2523. if (this.data.lockGpsMarkerSize || !mapEngine) {
  2524. return
  2525. }
  2526. this.persistAndApplySystemSettings({
  2527. gpsMarkerSize: 'large',
  2528. })
  2529. },
  2530. handleSetGpsMarkerColorPreset(event: WechatMiniprogram.TouchEvent) {
  2531. if (this.data.lockGpsMarkerColor || !mapEngine) {
  2532. return
  2533. }
  2534. const color = event.currentTarget.dataset.color as GpsMarkerColorPreset | undefined
  2535. if (!color) {
  2536. return
  2537. }
  2538. this.persistAndApplySystemSettings({
  2539. gpsMarkerColorPreset: color,
  2540. })
  2541. },
  2542. handleSetSideButtonPlacementLeft() {
  2543. if (this.data.lockSideButtonPlacement) {
  2544. return
  2545. }
  2546. this.persistAndApplySystemSettings({
  2547. sideButtonPlacement: 'left',
  2548. })
  2549. },
  2550. handleSetSideButtonPlacementRight() {
  2551. if (this.data.lockSideButtonPlacement) {
  2552. return
  2553. }
  2554. this.persistAndApplySystemSettings({
  2555. sideButtonPlacement: 'right',
  2556. })
  2557. },
  2558. handleSetAutoRotateEnabledOn() {
  2559. if (this.data.lockAutoRotate || !mapEngine) {
  2560. return
  2561. }
  2562. this.persistAndApplySystemSettings({
  2563. autoRotateEnabled: true,
  2564. })
  2565. },
  2566. handleSetAutoRotateEnabledOff() {
  2567. if (this.data.lockAutoRotate || !mapEngine) {
  2568. return
  2569. }
  2570. this.persistAndApplySystemSettings({
  2571. autoRotateEnabled: false,
  2572. })
  2573. },
  2574. handleSetCompassTuningSmooth() {
  2575. if (this.data.lockCompassTuning || !mapEngine) {
  2576. return
  2577. }
  2578. this.persistAndApplySystemSettings({
  2579. compassTuningProfile: 'smooth',
  2580. })
  2581. },
  2582. handleSetCompassTuningBalanced() {
  2583. if (this.data.lockCompassTuning || !mapEngine) {
  2584. return
  2585. }
  2586. this.persistAndApplySystemSettings({
  2587. compassTuningProfile: 'balanced',
  2588. })
  2589. },
  2590. handleSetCompassTuningResponsive() {
  2591. if (this.data.lockCompassTuning || !mapEngine) {
  2592. return
  2593. }
  2594. this.persistAndApplySystemSettings({
  2595. compassTuningProfile: 'responsive',
  2596. })
  2597. },
  2598. handleSetNorthReferenceMagnetic() {
  2599. if (this.data.lockNorthReference || !mapEngine) {
  2600. return
  2601. }
  2602. this.persistAndApplySystemSettings({
  2603. northReferenceMode: 'magnetic',
  2604. })
  2605. },
  2606. handleSetNorthReferenceTrue() {
  2607. if (this.data.lockNorthReference || !mapEngine) {
  2608. return
  2609. }
  2610. this.persistAndApplySystemSettings({
  2611. northReferenceMode: 'true',
  2612. })
  2613. },
  2614. handleOverlayTouch() {},
  2615. handlePunchAction() {
  2616. if (!this.data.punchButtonEnabled) {
  2617. return
  2618. }
  2619. if (mapEngine) {
  2620. mapEngine.handlePunchAction()
  2621. }
  2622. },
  2623. handleOpenPendingContentCard() {
  2624. if (mapEngine) {
  2625. mapEngine.openPendingContentCard()
  2626. }
  2627. },
  2628. handleOpenContentCardAction(event: WechatMiniprogram.BaseEvent) {
  2629. if (!mapEngine) {
  2630. return
  2631. }
  2632. wx.showToast({
  2633. title: '点击CTA',
  2634. icon: 'none',
  2635. duration: 900,
  2636. })
  2637. const actionType = event.currentTarget.dataset.type
  2638. const action = typeof actionType === 'string' ? mapEngine.openCurrentContentCardAction(actionType) : null
  2639. if (action === 'detail') {
  2640. wx.showToast({
  2641. title: '打开详情',
  2642. icon: 'none',
  2643. duration: 900,
  2644. })
  2645. return
  2646. }
  2647. if (action === 'quiz') {
  2648. return
  2649. }
  2650. if (action === 'photo') {
  2651. wx.chooseMedia({
  2652. count: 1,
  2653. mediaType: ['image'],
  2654. sourceType: ['camera'],
  2655. success: () => {
  2656. if (mapEngine) {
  2657. mapEngine.handleContentCardPhotoCaptured()
  2658. }
  2659. },
  2660. })
  2661. return
  2662. }
  2663. if (action === 'audio') {
  2664. if (!contentAudioRecorder) {
  2665. contentAudioRecorder = wx.getRecorderManager()
  2666. contentAudioRecorder.onStop(() => {
  2667. contentAudioRecording = false
  2668. if (mapEngine) {
  2669. mapEngine.handleContentCardAudioRecorded()
  2670. }
  2671. })
  2672. }
  2673. const recorder = contentAudioRecorder
  2674. if (!contentAudioRecording) {
  2675. contentAudioRecording = true
  2676. recorder.start({
  2677. duration: 8000,
  2678. format: 'mp3',
  2679. } as any)
  2680. wx.showToast({
  2681. title: '开始录音',
  2682. icon: 'none',
  2683. duration: 800,
  2684. })
  2685. } else {
  2686. recorder.stop()
  2687. }
  2688. }
  2689. },
  2690. handleContentQuizAnswer(event: WechatMiniprogram.BaseEvent) {
  2691. if (!mapEngine) {
  2692. return
  2693. }
  2694. const optionKey = event.currentTarget.dataset.key
  2695. if (typeof optionKey === 'string') {
  2696. mapEngine.handleContentCardQuizAnswer(optionKey)
  2697. }
  2698. },
  2699. handleDismissTransientContentCard() {
  2700. if (mapEngine) {
  2701. mapEngine.closeContentCard()
  2702. }
  2703. },
  2704. handleContentCardTap() {
  2705. if (!mapEngine) {
  2706. return
  2707. }
  2708. if (!this.data.contentCardActions.length) {
  2709. mapEngine.closeContentCard()
  2710. }
  2711. },
  2712. openH5Experience(request: H5ExperienceRequest) {
  2713. wx.navigateTo({
  2714. url: '/pages/experience-webview/experience-webview',
  2715. success: (result) => {
  2716. const eventChannel = result.eventChannel
  2717. eventChannel.on('fallback', (payload: H5ExperienceFallbackPayload) => {
  2718. if (mapEngine) {
  2719. mapEngine.handleH5ExperienceFallback(payload)
  2720. }
  2721. })
  2722. eventChannel.on('close', () => {
  2723. if (mapEngine) {
  2724. mapEngine.handleH5ExperienceClosed()
  2725. }
  2726. })
  2727. eventChannel.on('submitResult', () => {
  2728. if (mapEngine) {
  2729. mapEngine.handleH5ExperienceClosed()
  2730. }
  2731. })
  2732. eventChannel.emit('init', request)
  2733. },
  2734. fail: () => {
  2735. if (mapEngine) {
  2736. mapEngine.handleH5ExperienceFallback(request.fallback)
  2737. }
  2738. },
  2739. })
  2740. },
  2741. handleCloseContentCard() {
  2742. if (mapEngine) {
  2743. mapEngine.closeContentCard()
  2744. }
  2745. },
  2746. handleClosePunchHint() {
  2747. clearPunchHintDismissTimer()
  2748. this.setData({
  2749. showPunchHintBanner: false,
  2750. })
  2751. },
  2752. handlePunchHintTap() {},
  2753. handleHudPanelChange(event: WechatMiniprogram.CustomEvent<{ current: number }>) {
  2754. this.setData({
  2755. hudPanelIndex: event.detail.current || 0,
  2756. })
  2757. },
  2758. handleCycleSideButtons() {
  2759. const nextMode = getNextSideButtonMode(this.data.sideButtonMode)
  2760. this.setData({
  2761. ...buildSideButtonVisibility(nextMode),
  2762. ...buildSideButtonState({
  2763. sideButtonMode: nextMode,
  2764. showGameInfoPanel: this.data.showGameInfoPanel,
  2765. showSystemSettingsPanel: this.data.showSystemSettingsPanel,
  2766. showCenterScaleRuler: this.data.showCenterScaleRuler,
  2767. centerScaleRulerAnchorMode: this.data.centerScaleRulerAnchorMode,
  2768. skipButtonEnabled: this.data.skipButtonEnabled,
  2769. gameSessionStatus: this.data.gameSessionStatus,
  2770. gpsLockEnabled: this.data.gpsLockEnabled,
  2771. gpsLockAvailable: this.data.gpsLockAvailable,
  2772. }),
  2773. })
  2774. },
  2775. handleToggleGpsLock() {
  2776. if (mapEngine) {
  2777. mapEngine.handleToggleGpsLock()
  2778. }
  2779. },
  2780. handleToggleMapRotateMode() {
  2781. if (!mapEngine || this.data.lockAutoRotate) {
  2782. return
  2783. }
  2784. if (this.data.orientationMode === 'heading-up') {
  2785. this.persistAndApplySystemSettings({
  2786. autoRotateEnabled: false,
  2787. })
  2788. return
  2789. }
  2790. this.persistAndApplySystemSettings({
  2791. autoRotateEnabled: true,
  2792. })
  2793. },
  2794. handleToggleDebugPanel() {
  2795. const nextShowDebugPanel = !this.data.showDebugPanel
  2796. if (!nextShowDebugPanel) {
  2797. clearGameInfoPanelSyncTimer()
  2798. }
  2799. if (mapEngine) {
  2800. mapEngine.setDiagnosticUiEnabled(nextShowDebugPanel)
  2801. }
  2802. this.setData({
  2803. showDebugPanel: nextShowDebugPanel,
  2804. showGameInfoPanel: false,
  2805. showSystemSettingsPanel: false,
  2806. ...buildSideButtonState({
  2807. sideButtonMode: this.data.sideButtonMode,
  2808. showGameInfoPanel: false,
  2809. showSystemSettingsPanel: false,
  2810. showCenterScaleRuler: this.data.showCenterScaleRuler,
  2811. centerScaleRulerAnchorMode: this.data.centerScaleRulerAnchorMode,
  2812. skipButtonEnabled: this.data.skipButtonEnabled,
  2813. gameSessionStatus: this.data.gameSessionStatus,
  2814. gpsLockEnabled: this.data.gpsLockEnabled,
  2815. gpsLockAvailable: this.data.gpsLockAvailable,
  2816. }),
  2817. })
  2818. },
  2819. handleCloseDebugPanel() {
  2820. if (mapEngine) {
  2821. mapEngine.setDiagnosticUiEnabled(false)
  2822. }
  2823. this.setData({
  2824. showDebugPanel: false,
  2825. ...buildSideButtonState({
  2826. sideButtonMode: this.data.sideButtonMode,
  2827. showGameInfoPanel: this.data.showGameInfoPanel,
  2828. showSystemSettingsPanel: this.data.showSystemSettingsPanel,
  2829. showCenterScaleRuler: this.data.showCenterScaleRuler,
  2830. centerScaleRulerAnchorMode: this.data.centerScaleRulerAnchorMode,
  2831. skipButtonEnabled: this.data.skipButtonEnabled,
  2832. gameSessionStatus: this.data.gameSessionStatus,
  2833. gpsLockEnabled: this.data.gpsLockEnabled,
  2834. gpsLockAvailable: this.data.gpsLockAvailable,
  2835. }),
  2836. })
  2837. },
  2838. applyCenterScaleRulerSettings(nextEnabled: boolean, nextAnchorMode: CenterScaleRulerAnchorMode) {
  2839. this.data.showCenterScaleRuler = nextEnabled
  2840. this.data.centerScaleRulerAnchorMode = nextAnchorMode
  2841. clearCenterScaleRulerSyncTimer()
  2842. clearCenterScaleRulerUpdateTimer()
  2843. const syncRulerFromEngine = () => {
  2844. if (!mapEngine) {
  2845. return
  2846. }
  2847. const engineSnapshot = mapEngine.getInitialData() as Partial<MapPageData>
  2848. updateCenterScaleRulerInputCache(engineSnapshot)
  2849. const mergedData = {
  2850. ...centerScaleRulerInputCache,
  2851. ...this.data,
  2852. showCenterScaleRuler: nextEnabled,
  2853. centerScaleRulerAnchorMode: nextAnchorMode,
  2854. } as MapPageData
  2855. this.setData({
  2856. ...filterDebugOnlyPatch(engineSnapshot, this.data.showDebugPanel, nextEnabled),
  2857. showCenterScaleRuler: nextEnabled,
  2858. centerScaleRulerAnchorMode: nextAnchorMode,
  2859. ...buildCenterScaleRulerPatch(mergedData),
  2860. ...buildSideButtonState(mergedData),
  2861. })
  2862. }
  2863. if (!nextEnabled) {
  2864. syncRulerFromEngine()
  2865. return
  2866. }
  2867. this.setData({
  2868. showCenterScaleRuler: true,
  2869. centerScaleRulerAnchorMode: nextAnchorMode,
  2870. ...buildSideButtonState({
  2871. ...this.data,
  2872. showCenterScaleRuler: true,
  2873. centerScaleRulerAnchorMode: nextAnchorMode,
  2874. } as MapPageData),
  2875. })
  2876. this.measureStageAndCanvas(() => {
  2877. syncRulerFromEngine()
  2878. })
  2879. centerScaleRulerSyncTimer = setTimeout(() => {
  2880. centerScaleRulerSyncTimer = 0
  2881. if (!this.data.showCenterScaleRuler) {
  2882. return
  2883. }
  2884. syncRulerFromEngine()
  2885. }, 96) as unknown as number
  2886. },
  2887. handleSetCenterScaleRulerVisibleOn() {
  2888. if (this.data.lockScaleRulerVisible) {
  2889. return
  2890. }
  2891. this.persistAndApplySystemSettings({
  2892. showCenterScaleRuler: true,
  2893. centerScaleRulerAnchorMode: this.data.centerScaleRulerAnchorMode,
  2894. }, {
  2895. applyCenterScaleRuler: true,
  2896. })
  2897. },
  2898. handleSetCenterScaleRulerVisibleOff() {
  2899. if (this.data.lockScaleRulerVisible) {
  2900. return
  2901. }
  2902. this.persistAndApplySystemSettings({
  2903. showCenterScaleRuler: false,
  2904. centerScaleRulerAnchorMode: this.data.centerScaleRulerAnchorMode,
  2905. }, {
  2906. applyCenterScaleRuler: true,
  2907. })
  2908. },
  2909. handleSetCenterScaleRulerAnchorScreenCenter() {
  2910. if (this.data.lockScaleRulerAnchor) {
  2911. return
  2912. }
  2913. this.persistAndApplySystemSettings({
  2914. showCenterScaleRuler: this.data.showCenterScaleRuler,
  2915. centerScaleRulerAnchorMode: 'screen-center',
  2916. }, {
  2917. applyCenterScaleRuler: true,
  2918. })
  2919. },
  2920. handleSetCenterScaleRulerAnchorCompassCenter() {
  2921. if (this.data.lockScaleRulerAnchor) {
  2922. return
  2923. }
  2924. this.persistAndApplySystemSettings({
  2925. showCenterScaleRuler: this.data.showCenterScaleRuler,
  2926. centerScaleRulerAnchorMode: 'compass-center',
  2927. }, {
  2928. applyCenterScaleRuler: true,
  2929. })
  2930. },
  2931. handleToggleCenterScaleRulerAnchor() {
  2932. if (!this.data.showCenterScaleRuler || this.data.lockScaleRulerAnchor) {
  2933. return
  2934. }
  2935. const nextAnchorMode: CenterScaleRulerAnchorMode = this.data.centerScaleRulerAnchorMode === 'screen-center'
  2936. ? 'compass-center'
  2937. : 'screen-center'
  2938. this.persistAndApplySystemSettings({
  2939. centerScaleRulerAnchorMode: nextAnchorMode,
  2940. showCenterScaleRuler: this.data.showCenterScaleRuler,
  2941. }, {
  2942. applyCenterScaleRuler: true,
  2943. })
  2944. },
  2945. handleDebugPanelTap() {},
  2946. })