map.ts 97 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251
  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. Page({
  752. data: {
  753. showDebugPanel: false,
  754. showGameInfoPanel: false,
  755. showResultScene: false,
  756. showSystemSettingsPanel: false,
  757. showHeartRateDevicePicker: false,
  758. showCenterScaleRuler: false,
  759. statusBarHeight: 0,
  760. topInsetHeight: 12,
  761. hudPanelIndex: 0,
  762. configSourceText: '顺序赛配置',
  763. centerScaleRulerAnchorMode: DEFAULT_STORED_USER_SETTINGS.centerScaleRulerAnchorMode,
  764. punchHintFxClass: '',
  765. autoRotateEnabled: DEFAULT_STORED_USER_SETTINGS.autoRotateEnabled,
  766. ...DEFAULT_SETTING_LOCKS,
  767. gameInfoTitle: '当前游戏',
  768. gameInfoSubtitle: '未开始',
  769. gameInfoLocalRows: [],
  770. gameInfoGlobalRows: buildEmptyGameInfoSnapshot().globalRows,
  771. resultSceneTitle: '本局结果',
  772. resultSceneSubtitle: '未开始',
  773. resultSceneHeroLabel: '本局用时',
  774. resultSceneHeroValue: '--',
  775. resultSceneRows: buildEmptyResultSceneSnapshot().rows,
  776. resultSceneCountdownText: '',
  777. panelTimerText: '00:00:00',
  778. panelTimerMode: 'elapsed',
  779. panelMileageText: '0m',
  780. panelActionTagText: '目标',
  781. panelDistanceTagText: '点距',
  782. panelTargetSummaryText: '等待选择目标',
  783. panelDistanceValueText: '--',
  784. panelDistanceUnitText: '',
  785. panelProgressText: '0/0',
  786. showPunchHintBanner: true,
  787. sideButtonPlacement: 'left',
  788. gameSessionStatus: 'idle',
  789. gameModeText: '顺序赛',
  790. gpsLockEnabled: false,
  791. gpsLockAvailable: false,
  792. locationSourceMode: 'real',
  793. locationSourceText: '真实定位',
  794. mockBridgeConnected: false,
  795. mockBridgeStatusText: '未连接',
  796. mockBridgeUrlText: 'wss://gs.gotomars.xyz/mock-gps',
  797. mockChannelIdText: 'default',
  798. mockBridgeUrlDraft: 'wss://gs.gotomars.xyz/mock-gps',
  799. mockChannelIdDraft: 'default',
  800. mockCoordText: '--',
  801. mockSpeedText: '--',
  802. heartRateSourceMode: 'real',
  803. heartRateSourceText: '真实心率',
  804. mockHeartRateBridgeConnected: false,
  805. mockHeartRateBridgeStatusText: '未连接',
  806. mockHeartRateBridgeUrlText: 'wss://gs.gotomars.xyz/mock-hr',
  807. mockHeartRateBridgeUrlDraft: 'wss://gs.gotomars.xyz/mock-hr',
  808. mockHeartRateText: '--',
  809. mockDebugLogBridgeConnected: false,
  810. mockDebugLogBridgeStatusText: '已关闭 (wss://gs.gotomars.xyz/debug-log)',
  811. mockDebugLogBridgeUrlText: 'wss://gs.gotomars.xyz/debug-log',
  812. mockDebugLogBridgeUrlDraft: 'wss://gs.gotomars.xyz/debug-log',
  813. heartRateScanText: '未扫描',
  814. heartRateDiscoveredDevices: [],
  815. panelSpeedValueText: '0',
  816. panelTelemetryTone: 'blue',
  817. trackDisplayMode: DEFAULT_STORED_USER_SETTINGS.trackDisplayMode,
  818. trackTailLength: DEFAULT_STORED_USER_SETTINGS.trackTailLength,
  819. trackColorPreset: DEFAULT_STORED_USER_SETTINGS.trackColorPreset,
  820. trackStyleProfile: DEFAULT_STORED_USER_SETTINGS.trackStyleProfile,
  821. gpsMarkerVisible: DEFAULT_STORED_USER_SETTINGS.gpsMarkerVisible,
  822. gpsMarkerStyle: DEFAULT_STORED_USER_SETTINGS.gpsMarkerStyle,
  823. gpsMarkerSize: DEFAULT_STORED_USER_SETTINGS.gpsMarkerSize,
  824. gpsMarkerColorPreset: DEFAULT_STORED_USER_SETTINGS.gpsMarkerColorPreset,
  825. gpsLogoStatusText: '未配置',
  826. gpsLogoSourceText: '--',
  827. panelHeartRateZoneNameText: '--',
  828. panelHeartRateZoneRangeText: '',
  829. heartRateConnected: false,
  830. heartRateStatusText: '心率带未连接',
  831. heartRateDeviceText: '--',
  832. panelHeartRateValueText: '--',
  833. panelHeartRateUnitText: '',
  834. panelCaloriesValueText: '0',
  835. panelCaloriesUnitText: 'kcal',
  836. panelAverageSpeedValueText: '0',
  837. panelAverageSpeedUnitText: 'km/h',
  838. panelAccuracyValueText: '--',
  839. panelAccuracyUnitText: '',
  840. deviceHeadingText: '--',
  841. devicePoseText: '竖持',
  842. headingConfidenceText: '低',
  843. accelerometerText: '--',
  844. gyroscopeText: '--',
  845. deviceMotionText: '--',
  846. compassSourceText: '无数据',
  847. compassTuningProfile: DEFAULT_STORED_USER_SETTINGS.compassTuningProfile,
  848. compassTuningProfileText: '平衡',
  849. punchButtonText: '打点',
  850. punchButtonEnabled: false,
  851. skipButtonEnabled: false,
  852. punchHintText: '等待进入检查点范围',
  853. punchFeedbackVisible: false,
  854. punchFeedbackText: '',
  855. punchFeedbackTone: 'neutral',
  856. contentCardVisible: false,
  857. contentCardTemplate: 'story',
  858. contentCardTitle: '',
  859. contentCardBody: '',
  860. contentCardActions: [],
  861. contentQuizVisible: false,
  862. contentQuizQuestionText: '',
  863. contentQuizCountdownText: '',
  864. contentQuizOptions: [],
  865. contentQuizFeedbackVisible: false,
  866. contentQuizFeedbackText: '',
  867. contentQuizFeedbackTone: 'neutral',
  868. punchButtonFxClass: '',
  869. panelProgressFxClass: '',
  870. panelDistanceFxClass: '',
  871. punchFeedbackFxClass: '',
  872. contentCardFxClass: '',
  873. mapPulseVisible: false,
  874. mapPulseLeftPx: 0,
  875. mapPulseTopPx: 0,
  876. mapPulseFxClass: '',
  877. stageFxVisible: false,
  878. stageFxClass: '',
  879. centerScaleRulerVisible: false,
  880. centerScaleRulerCenterXPx: 0,
  881. centerScaleRulerZeroYPx: 0,
  882. centerScaleRulerHeightPx: 0,
  883. centerScaleRulerAxisBottomPx: 0,
  884. centerScaleRulerZeroVisible: false,
  885. centerScaleRulerZeroLabel: '0 m',
  886. centerScaleRulerMinorTicks: [],
  887. centerScaleRulerMajorMarks: [],
  888. compassTicks: buildCompassTicks(),
  889. compassLabels: buildCompassLabels(),
  890. ...buildSideButtonVisibility('shown'),
  891. ...buildSideButtonState({
  892. sideButtonMode: 'shown',
  893. showGameInfoPanel: false,
  894. showSystemSettingsPanel: false,
  895. showCenterScaleRuler: false,
  896. centerScaleRulerAnchorMode: 'screen-center',
  897. skipButtonEnabled: false,
  898. gameSessionStatus: 'idle',
  899. gpsLockEnabled: false,
  900. gpsLockAvailable: false,
  901. }),
  902. } as unknown as MapPageData,
  903. onLoad(options: MapPageLaunchOptions) {
  904. clearSessionRecoveryPersistTimer()
  905. clearResultExitRedirectTimer()
  906. clearResultExitCountdownTimer()
  907. syncedBackendSessionStartId = ''
  908. syncedBackendSessionFinishId = ''
  909. redirectedToResultPage = false
  910. shouldAutoRestoreRecoverySnapshot = options && options.recoverSession === '1'
  911. currentGameLaunchEnvelope = resolveGameLaunchEnvelope(options)
  912. if (!hasExplicitLaunchOptions(options)) {
  913. const recoverySnapshot = loadSessionRecoverySnapshot()
  914. if (recoverySnapshot) {
  915. currentGameLaunchEnvelope = recoverySnapshot.launchEnvelope
  916. }
  917. }
  918. currentSystemSettingsConfig = undefined
  919. currentRemoteMapConfig = undefined
  920. systemSettingsLockLifetimeActive = false
  921. const storedMockChannelId = loadStoredMockChannelId()
  922. const shouldAutoConnectMockSources = loadMockAutoConnectEnabled()
  923. const systemInfo = wx.getSystemInfoSync()
  924. const statusBarHeight = systemInfo.statusBarHeight || 0
  925. const menuButtonRect = wx.getMenuButtonBoundingClientRect()
  926. const menuButtonBottom = menuButtonRect && typeof menuButtonRect.bottom === 'number' ? menuButtonRect.bottom : statusBarHeight
  927. if (mapEngine) {
  928. mapEngine.destroy()
  929. mapEngine = null
  930. }
  931. mapEngine = new MapEngine(INTERNAL_BUILD_VERSION, {
  932. onData: (patch) => {
  933. const nextPatch = patch as Partial<MapPageData>
  934. const includeDebugFields = this.data.showDebugPanel
  935. const includeRulerFields = this.data.showCenterScaleRuler
  936. let shouldSyncRuntimeSystemSettings = false
  937. let nextLockLifetimeActive = isSystemSettingsLockLifetimeActive()
  938. let heartRateSwitchToastText = ''
  939. const nextData: Partial<MapPageData> = filterDebugOnlyPatch({
  940. ...nextPatch,
  941. }, includeDebugFields, includeRulerFields)
  942. if (
  943. typeof nextPatch.mockBridgeUrlText === 'string'
  944. && this.data.mockBridgeUrlDraft === this.data.mockBridgeUrlText
  945. ) {
  946. nextData.mockBridgeUrlDraft = nextPatch.mockBridgeUrlText
  947. }
  948. if (
  949. typeof nextPatch.mockHeartRateBridgeUrlText === 'string'
  950. && this.data.mockHeartRateBridgeUrlDraft === this.data.mockHeartRateBridgeUrlText
  951. ) {
  952. nextData.mockHeartRateBridgeUrlDraft = nextPatch.mockHeartRateBridgeUrlText
  953. }
  954. if (
  955. typeof nextPatch.mockDebugLogBridgeUrlText === 'string'
  956. && this.data.mockDebugLogBridgeUrlDraft === this.data.mockDebugLogBridgeUrlText
  957. ) {
  958. nextData.mockDebugLogBridgeUrlDraft = nextPatch.mockDebugLogBridgeUrlText
  959. }
  960. if (
  961. typeof nextPatch.mockChannelIdText === 'string'
  962. && this.data.mockChannelIdDraft === this.data.mockChannelIdText
  963. ) {
  964. nextData.mockChannelIdDraft = nextPatch.mockChannelIdText
  965. }
  966. updateCenterScaleRulerInputCache(nextPatch)
  967. const mergedData = {
  968. ...centerScaleRulerInputCache,
  969. ...this.data,
  970. ...nextData,
  971. } as MapPageData
  972. const derivedPatch: Partial<MapPageData> = {}
  973. if (typeof nextPatch.orientationMode === 'string') {
  974. nextData.autoRotateEnabled = nextPatch.orientationMode === 'heading-up'
  975. }
  976. if (
  977. this.data.showCenterScaleRuler
  978. && hasAnyPatchKey(nextPatch as Record<string, unknown>, CENTER_SCALE_RULER_DEP_KEYS)
  979. ) {
  980. clearCenterScaleRulerUpdateTimer()
  981. Object.assign(derivedPatch, buildCenterScaleRulerPatch(mergedData))
  982. }
  983. if (hasAnyPatchKey(nextPatch as Record<string, unknown>, SIDE_BUTTON_DEP_KEYS)) {
  984. Object.assign(derivedPatch, buildSideButtonState(mergedData))
  985. }
  986. if (typeof nextPatch.punchHintText === 'string') {
  987. const nextHintText = nextPatch.punchHintText.trim()
  988. if (nextHintText !== this.data.punchHintText) {
  989. clearPunchHintDismissTimer()
  990. clearPunchHintFxTimer()
  991. nextData.showPunchHintBanner = nextHintText.length > 0
  992. if (nextHintText.length > 0) {
  993. nextData.punchHintFxClass = 'game-punch-hint--fx-enter'
  994. punchHintFxTimer = setTimeout(() => {
  995. punchHintFxTimer = 0
  996. this.setData({
  997. punchHintFxClass: '',
  998. })
  999. }, PUNCH_HINT_FX_DURATION_MS) as unknown as number
  1000. const now = Date.now()
  1001. if (mapEngine && now - lastPunchHintHapticAt >= PUNCH_HINT_HAPTIC_GAP_MS) {
  1002. mapEngine.playPunchHintHaptic()
  1003. lastPunchHintHapticAt = now
  1004. }
  1005. punchHintDismissTimer = setTimeout(() => {
  1006. punchHintDismissTimer = 0
  1007. this.setData({
  1008. showPunchHintBanner: false,
  1009. })
  1010. }, PUNCH_HINT_AUTO_HIDE_MS) as unknown as number
  1011. }
  1012. } else if (!nextHintText) {
  1013. clearPunchHintDismissTimer()
  1014. clearPunchHintFxTimer()
  1015. nextData.showPunchHintBanner = false
  1016. nextData.punchHintFxClass = ''
  1017. }
  1018. }
  1019. const nextAnimationLevel = typeof nextPatch.animationLevel === 'string'
  1020. ? nextPatch.animationLevel
  1021. : this.data.animationLevel
  1022. let shouldSyncBackendSessionStart = false
  1023. let backendSessionFinishStatus: 'finished' | 'failed' | null = null
  1024. let shouldOpenResultExitPrompt = false
  1025. let resultPageSnapshot: MapEngineResultSnapshot | null = null
  1026. if (nextAnimationLevel === 'lite') {
  1027. clearHudFxTimer('timer')
  1028. clearHudFxTimer('mileage')
  1029. clearHudFxTimer('speed')
  1030. clearHudFxTimer('heartRate')
  1031. nextData.panelTimerFxClass = ''
  1032. nextData.panelMileageFxClass = ''
  1033. nextData.panelSpeedFxClass = ''
  1034. nextData.panelHeartRateFxClass = ''
  1035. } else {
  1036. if (typeof nextPatch.panelTimerText === 'string' && nextPatch.panelTimerText !== this.data.panelTimerText && this.data.panelTimerText !== '00:00:00') {
  1037. clearHudFxTimer('timer')
  1038. nextData.panelTimerFxClass = 'race-panel__timer--fx-tick'
  1039. panelTimerFxTimer = setTimeout(() => {
  1040. panelTimerFxTimer = 0
  1041. this.setData({ panelTimerFxClass: '' })
  1042. }, 320) as unknown as number
  1043. }
  1044. if (typeof nextPatch.panelMileageText === 'string' && nextPatch.panelMileageText !== this.data.panelMileageText && this.data.panelMileageText !== '0m') {
  1045. clearHudFxTimer('mileage')
  1046. nextData.panelMileageFxClass = 'race-panel__mileage-wrap--fx-update'
  1047. panelMileageFxTimer = setTimeout(() => {
  1048. panelMileageFxTimer = 0
  1049. this.setData({ panelMileageFxClass: '' })
  1050. }, 360) as unknown as number
  1051. }
  1052. if (typeof nextPatch.panelSpeedValueText === 'string' && nextPatch.panelSpeedValueText !== this.data.panelSpeedValueText && this.data.panelSpeedValueText !== '0') {
  1053. clearHudFxTimer('speed')
  1054. nextData.panelSpeedFxClass = 'race-panel__metric-group--fx-speed-update'
  1055. panelSpeedFxTimer = setTimeout(() => {
  1056. panelSpeedFxTimer = 0
  1057. this.setData({ panelSpeedFxClass: '' })
  1058. }, 360) as unknown as number
  1059. }
  1060. if (typeof nextPatch.panelHeartRateValueText === 'string' && nextPatch.panelHeartRateValueText !== this.data.panelHeartRateValueText && this.data.panelHeartRateValueText !== '--') {
  1061. clearHudFxTimer('heartRate')
  1062. nextData.panelHeartRateFxClass = 'race-panel__metric-group--fx-heart-rate-update'
  1063. panelHeartRateFxTimer = setTimeout(() => {
  1064. panelHeartRateFxTimer = 0
  1065. this.setData({ panelHeartRateFxClass: '' })
  1066. }, 400) as unknown as number
  1067. }
  1068. }
  1069. if (typeof nextPatch.gameSessionStatus === 'string') {
  1070. if (
  1071. nextPatch.gameSessionStatus !== this.data.gameSessionStatus
  1072. && (nextPatch.gameSessionStatus === 'finished' || nextPatch.gameSessionStatus === 'failed')
  1073. ) {
  1074. systemSettingsLockLifetimeActive = false
  1075. nextLockLifetimeActive = false
  1076. shouldSyncRuntimeSystemSettings = true
  1077. clearSessionRecoverySnapshot()
  1078. clearSessionRecoveryPersistTimer()
  1079. clearResultExitRedirectTimer()
  1080. clearResultExitCountdownTimer()
  1081. resultPageSnapshot = mapEngine ? mapEngine.getResultSceneSnapshot() : null
  1082. nextData.showResultScene = true
  1083. nextData.showDebugPanel = false
  1084. nextData.showGameInfoPanel = false
  1085. nextData.showSystemSettingsPanel = false
  1086. clearGameInfoPanelSyncTimer()
  1087. backendSessionFinishStatus = nextPatch.gameSessionStatus === 'finished' ? 'finished' : 'failed'
  1088. shouldOpenResultExitPrompt = true
  1089. if (resultPageSnapshot) {
  1090. nextData.resultSceneTitle = resultPageSnapshot.title
  1091. nextData.resultSceneSubtitle = resultPageSnapshot.subtitle
  1092. nextData.resultSceneHeroLabel = resultPageSnapshot.heroLabel
  1093. nextData.resultSceneHeroValue = resultPageSnapshot.heroValue
  1094. nextData.resultSceneRows = resultPageSnapshot.rows
  1095. }
  1096. nextData.resultSceneCountdownText = '3 秒后自动进入成绩页'
  1097. } else if (
  1098. nextPatch.gameSessionStatus !== this.data.gameSessionStatus
  1099. && nextPatch.gameSessionStatus === 'idle'
  1100. && !isSystemSettingsLockLifetimeActive()
  1101. ) {
  1102. nextLockLifetimeActive = false
  1103. shouldSyncRuntimeSystemSettings = true
  1104. clearSessionRecoverySnapshot()
  1105. clearSessionRecoveryPersistTimer()
  1106. clearResultExitRedirectTimer()
  1107. clearResultExitCountdownTimer()
  1108. } else if (
  1109. nextPatch.gameSessionStatus !== this.data.gameSessionStatus
  1110. && nextPatch.gameSessionStatus === 'running'
  1111. ) {
  1112. shouldSyncBackendSessionStart = true
  1113. } else if (nextPatch.gameSessionStatus === 'running' || nextPatch.gameSessionStatus === 'idle') {
  1114. nextData.showResultScene = false
  1115. }
  1116. }
  1117. if (
  1118. pendingHeartRateSwitchDeviceName
  1119. && nextPatch.heartRateConnected === true
  1120. && typeof nextPatch.heartRateDeviceText === 'string'
  1121. ) {
  1122. const connectedDeviceName = nextPatch.heartRateDeviceText.trim()
  1123. if (connectedDeviceName && connectedDeviceName === pendingHeartRateSwitchDeviceName) {
  1124. heartRateSwitchToastText = `已切换到 ${connectedDeviceName}`
  1125. nextData.statusText = `已切换心率带:${connectedDeviceName}`
  1126. pendingHeartRateSwitchDeviceName = null
  1127. }
  1128. }
  1129. if (Object.keys(nextData).length || Object.keys(derivedPatch).length) {
  1130. this.setData({
  1131. ...nextData,
  1132. ...derivedPatch,
  1133. }, () => {
  1134. if (typeof nextPatch.gameSessionStatus === 'string') {
  1135. this.syncSessionRecoveryLifecycle(nextPatch.gameSessionStatus)
  1136. }
  1137. if (shouldSyncBackendSessionStart) {
  1138. this.syncBackendSessionStart()
  1139. }
  1140. if (backendSessionFinishStatus) {
  1141. this.syncBackendSessionFinish(backendSessionFinishStatus)
  1142. }
  1143. if (shouldOpenResultExitPrompt && resultPageSnapshot) {
  1144. this.stashPendingResultSnapshot(resultPageSnapshot)
  1145. this.presentResultExitPrompt()
  1146. }
  1147. if (heartRateSwitchToastText) {
  1148. wx.showToast({
  1149. title: `${heartRateSwitchToastText},并设为首选设备`,
  1150. icon: 'none',
  1151. duration: 1800,
  1152. })
  1153. }
  1154. if (shouldSyncRuntimeSystemSettings) {
  1155. this.applyRuntimeSystemSettings(nextLockLifetimeActive)
  1156. }
  1157. if (this.data.showGameInfoPanel) {
  1158. this.scheduleGameInfoPanelSnapshotSync()
  1159. }
  1160. })
  1161. } else {
  1162. if (typeof nextPatch.gameSessionStatus === 'string') {
  1163. this.syncSessionRecoveryLifecycle(nextPatch.gameSessionStatus)
  1164. }
  1165. if (shouldSyncBackendSessionStart) {
  1166. this.syncBackendSessionStart()
  1167. }
  1168. if (backendSessionFinishStatus) {
  1169. this.syncBackendSessionFinish(backendSessionFinishStatus)
  1170. }
  1171. if (shouldOpenResultExitPrompt && resultPageSnapshot) {
  1172. this.stashPendingResultSnapshot(resultPageSnapshot)
  1173. this.presentResultExitPrompt()
  1174. }
  1175. if (shouldSyncRuntimeSystemSettings) {
  1176. this.applyRuntimeSystemSettings(nextLockLifetimeActive)
  1177. }
  1178. if (this.data.showGameInfoPanel) {
  1179. this.scheduleGameInfoPanelSnapshotSync()
  1180. }
  1181. }
  1182. },
  1183. onOpenH5Experience: (request) => {
  1184. this.openH5Experience(request)
  1185. },
  1186. })
  1187. mapEngine.applyTelemetryPlayerProfile(getGlobalTelemetryProfile())
  1188. const systemSettingsState = resolveSystemSettingsState(undefined, undefined, false)
  1189. const initialSystemSettings = systemSettingsState.values
  1190. mapEngine.applyCompiledSettingsProfile({
  1191. values: initialSystemSettings,
  1192. locks: systemSettingsState.locks,
  1193. lockLifetimeActive: false,
  1194. })
  1195. mapEngine.setDiagnosticUiEnabled(false)
  1196. centerScaleRulerInputCache = {
  1197. stageWidth: 0,
  1198. stageHeight: 0,
  1199. zoom: 0,
  1200. centerTileY: 0,
  1201. tileSizePx: 0,
  1202. previewScale: 1,
  1203. }
  1204. const initialEngineData = mapEngine.getInitialData()
  1205. this.setData({
  1206. ...initialEngineData,
  1207. ...buildResolvedSystemSettingsPatch(systemSettingsState),
  1208. showDebugPanel: false,
  1209. showGameInfoPanel: false,
  1210. showResultScene: false,
  1211. showSystemSettingsPanel: false,
  1212. statusBarHeight,
  1213. topInsetHeight: Math.max(statusBarHeight + 12, menuButtonBottom + 20),
  1214. hudPanelIndex: 0,
  1215. configSourceText: currentGameLaunchEnvelope.config.configLabel,
  1216. gameInfoTitle: '当前游戏',
  1217. gameInfoSubtitle: '未开始',
  1218. gameInfoLocalRows: [],
  1219. gameInfoGlobalRows: buildEmptyGameInfoSnapshot().globalRows,
  1220. resultSceneTitle: '本局结果',
  1221. resultSceneSubtitle: '未开始',
  1222. resultSceneHeroLabel: '本局用时',
  1223. resultSceneHeroValue: '--',
  1224. resultSceneRows: buildEmptyResultSceneSnapshot().rows,
  1225. resultSceneCountdownText: '',
  1226. panelTimerText: '00:00:00',
  1227. panelTimerMode: 'elapsed',
  1228. panelTimerFxClass: '',
  1229. panelMileageText: '0m',
  1230. panelMileageFxClass: '',
  1231. panelActionTagText: '目标',
  1232. panelDistanceTagText: '点距',
  1233. panelTargetSummaryText: '等待选择目标',
  1234. panelDistanceValueText: '--',
  1235. panelDistanceUnitText: '',
  1236. panelProgressText: '0/0',
  1237. showPunchHintBanner: true,
  1238. gameSessionStatus: 'idle',
  1239. gameModeText: '顺序赛',
  1240. gpsLockEnabled: false,
  1241. gpsLockAvailable: false,
  1242. locationSourceMode: 'real',
  1243. locationSourceText: '真实定位',
  1244. mockBridgeConnected: false,
  1245. mockBridgeStatusText: '未连接',
  1246. mockBridgeUrlText: 'wss://gs.gotomars.xyz/mock-gps',
  1247. mockChannelIdText: storedMockChannelId,
  1248. mockBridgeUrlDraft: 'wss://gs.gotomars.xyz/mock-gps',
  1249. mockChannelIdDraft: storedMockChannelId,
  1250. mockCoordText: '--',
  1251. mockSpeedText: '--',
  1252. heartRateSourceMode: 'real',
  1253. heartRateSourceText: '真实心率',
  1254. mockHeartRateBridgeConnected: false,
  1255. mockHeartRateBridgeStatusText: '未连接',
  1256. mockHeartRateBridgeUrlText: 'wss://gs.gotomars.xyz/mock-hr',
  1257. mockHeartRateBridgeUrlDraft: 'wss://gs.gotomars.xyz/mock-hr',
  1258. mockHeartRateText: '--',
  1259. mockDebugLogBridgeConnected: false,
  1260. mockDebugLogBridgeStatusText: '已关闭 (wss://gs.gotomars.xyz/debug-log)',
  1261. mockDebugLogBridgeUrlText: 'wss://gs.gotomars.xyz/debug-log',
  1262. mockDebugLogBridgeUrlDraft: 'wss://gs.gotomars.xyz/debug-log',
  1263. panelSpeedValueText: '0',
  1264. panelSpeedFxClass: '',
  1265. panelTelemetryTone: 'blue',
  1266. gpsLogoStatusText: '未配置',
  1267. gpsLogoSourceText: '--',
  1268. panelHeartRateZoneNameText: '--',
  1269. panelHeartRateZoneRangeText: '',
  1270. heartRateConnected: false,
  1271. heartRateStatusText: '心率带未连接',
  1272. heartRateDeviceText: '--',
  1273. panelHeartRateValueText: '--',
  1274. panelHeartRateFxClass: '',
  1275. panelHeartRateUnitText: '',
  1276. panelCaloriesValueText: '0',
  1277. panelCaloriesUnitText: 'kcal',
  1278. panelAverageSpeedValueText: '0',
  1279. panelAverageSpeedUnitText: 'km/h',
  1280. panelAccuracyValueText: '--',
  1281. panelAccuracyUnitText: '',
  1282. deviceHeadingText: '--',
  1283. devicePoseText: '竖持',
  1284. headingConfidenceText: '低',
  1285. accelerometerText: '--',
  1286. gyroscopeText: '--',
  1287. deviceMotionText: '--',
  1288. compassSourceText: '无数据',
  1289. compassTuningProfileText: initialEngineData.compassTuningProfileText || '平衡',
  1290. punchButtonText: '打点',
  1291. punchButtonEnabled: false,
  1292. skipButtonEnabled: false,
  1293. punchHintText: '等待进入检查点范围',
  1294. punchHintFxClass: '',
  1295. punchFeedbackVisible: false,
  1296. punchFeedbackText: '',
  1297. punchFeedbackTone: 'neutral',
  1298. contentCardVisible: false,
  1299. contentCardTemplate: 'story',
  1300. contentCardTitle: '',
  1301. contentCardBody: '',
  1302. contentCardActions: [],
  1303. contentQuizVisible: false,
  1304. contentQuizQuestionText: '',
  1305. contentQuizCountdownText: '',
  1306. contentQuizOptions: [],
  1307. contentQuizFeedbackVisible: false,
  1308. contentQuizFeedbackText: '',
  1309. contentQuizFeedbackTone: 'neutral',
  1310. punchButtonFxClass: '',
  1311. panelProgressFxClass: '',
  1312. panelDistanceFxClass: '',
  1313. punchFeedbackFxClass: '',
  1314. contentCardFxClass: '',
  1315. mapPulseVisible: false,
  1316. mapPulseLeftPx: 0,
  1317. mapPulseTopPx: 0,
  1318. mapPulseFxClass: '',
  1319. stageFxVisible: false,
  1320. stageFxClass: '',
  1321. compassTicks: buildCompassTicks(),
  1322. compassLabels: buildCompassLabels(),
  1323. ...buildSideButtonVisibility('shown'),
  1324. ...buildSideButtonState({
  1325. sideButtonMode: 'shown',
  1326. showGameInfoPanel: false,
  1327. showSystemSettingsPanel: false,
  1328. showCenterScaleRuler: initialSystemSettings.showCenterScaleRuler,
  1329. centerScaleRulerAnchorMode: initialSystemSettings.centerScaleRulerAnchorMode,
  1330. skipButtonEnabled: false,
  1331. gameSessionStatus: 'idle',
  1332. gpsLockEnabled: false,
  1333. gpsLockAvailable: false,
  1334. }),
  1335. ...buildCenterScaleRulerPatch({
  1336. ...(mapEngine.getInitialData() as MapPageData),
  1337. showCenterScaleRuler: initialSystemSettings.showCenterScaleRuler,
  1338. centerScaleRulerAnchorMode: initialSystemSettings.centerScaleRulerAnchorMode,
  1339. stageWidth: 0,
  1340. stageHeight: 0,
  1341. topInsetHeight: Math.max(statusBarHeight + 12, menuButtonBottom + 20),
  1342. zoom: 0,
  1343. centerTileY: 0,
  1344. tileSizePx: 0,
  1345. }),
  1346. }, () => {
  1347. if (shouldAutoConnectMockSources) {
  1348. this.handleConnectAllMockSources()
  1349. }
  1350. })
  1351. },
  1352. onReady() {
  1353. stageCanvasAttached = false
  1354. this.measureStageAndCanvas()
  1355. this.loadGameLaunchEnvelope(currentGameLaunchEnvelope)
  1356. const app = getApp<IAppOption>()
  1357. const pendingHeartRateAutoConnect = app.globalData ? app.globalData.pendingHeartRateAutoConnect : null
  1358. if (pendingHeartRateAutoConnect && pendingHeartRateAutoConnect.enabled && mapEngine) {
  1359. const pendingDeviceName = pendingHeartRateAutoConnect.deviceName || '心率带'
  1360. app.globalData.pendingHeartRateAutoConnect = null
  1361. mapEngine.handleConnectHeartRate()
  1362. this.setData({
  1363. statusText: `正在自动连接局前设备:${pendingDeviceName}`,
  1364. heartRateStatusText: `正在自动连接 ${pendingDeviceName}`,
  1365. heartRateDeviceText: pendingDeviceName,
  1366. })
  1367. }
  1368. },
  1369. onShow() {
  1370. if (mapEngine) {
  1371. this.applyCompiledRuntimeProfiles()
  1372. mapEngine.handleAppShow()
  1373. }
  1374. },
  1375. onHide() {
  1376. this.persistSessionRecoverySnapshot()
  1377. clearResultExitRedirectTimer()
  1378. clearResultExitCountdownTimer()
  1379. if (mapEngine) {
  1380. mapEngine.handleAppHide()
  1381. }
  1382. },
  1383. onUnload() {
  1384. this.persistSessionRecoverySnapshot()
  1385. clearSessionRecoveryPersistTimer()
  1386. clearResultExitRedirectTimer()
  1387. clearResultExitCountdownTimer()
  1388. syncedBackendSessionStartId = ''
  1389. syncedBackendSessionFinishId = ''
  1390. clearGameInfoPanelSyncTimer()
  1391. clearCenterScaleRulerSyncTimer()
  1392. clearCenterScaleRulerUpdateTimer()
  1393. clearPunchHintDismissTimer()
  1394. clearPunchHintFxTimer()
  1395. clearHudFxTimer('timer')
  1396. clearHudFxTimer('mileage')
  1397. clearHudFxTimer('speed')
  1398. clearHudFxTimer('heartRate')
  1399. if (mapEngine) {
  1400. mapEngine.destroy()
  1401. mapEngine = null
  1402. }
  1403. currentSystemSettingsConfig = undefined
  1404. currentRemoteMapConfig = undefined
  1405. systemSettingsLockLifetimeActive = false
  1406. currentGameLaunchEnvelope = getDemoGameLaunchEnvelope()
  1407. shouldAutoRestoreRecoverySnapshot = false
  1408. redirectedToResultPage = false
  1409. stageCanvasAttached = false
  1410. },
  1411. loadGameLaunchEnvelope(envelope: GameLaunchEnvelope) {
  1412. this.loadMapConfigFromRemote(
  1413. envelope.config.configUrl,
  1414. envelope.config.configLabel,
  1415. )
  1416. },
  1417. persistSessionRecoverySnapshot() {
  1418. if (!mapEngine || !currentRemoteMapConfig) {
  1419. return false
  1420. }
  1421. const runtimeSnapshot = mapEngine.buildSessionRecoveryRuntimeSnapshot()
  1422. if (!runtimeSnapshot) {
  1423. return false
  1424. }
  1425. const snapshot: SessionRecoverySnapshot = {
  1426. schemaVersion: 1,
  1427. savedAt: Date.now(),
  1428. launchEnvelope: currentGameLaunchEnvelope,
  1429. configAppId: currentRemoteMapConfig.configAppId,
  1430. configVersion: currentRemoteMapConfig.configVersion,
  1431. runtime: runtimeSnapshot,
  1432. }
  1433. saveSessionRecoverySnapshot(snapshot)
  1434. return true
  1435. },
  1436. syncBackendSessionStart() {
  1437. const sessionContext = getCurrentBackendSessionContext()
  1438. if (!sessionContext || syncedBackendSessionStartId === sessionContext.sessionId) {
  1439. return
  1440. }
  1441. startSession({
  1442. baseUrl: getCurrentBackendBaseUrl(),
  1443. sessionId: sessionContext.sessionId,
  1444. sessionToken: sessionContext.sessionToken,
  1445. })
  1446. .then(() => {
  1447. syncedBackendSessionStartId = sessionContext.sessionId
  1448. })
  1449. .catch((error) => {
  1450. const message = error && error.message ? error.message : '未知错误'
  1451. this.setData({
  1452. statusText: `session start 上报失败: ${message}`,
  1453. })
  1454. })
  1455. },
  1456. syncBackendSessionFinish(statusOverride?: 'finished' | 'failed' | 'cancelled') {
  1457. const sessionContext = getCurrentBackendSessionContext()
  1458. if (!sessionContext || syncedBackendSessionFinishId === sessionContext.sessionId || !mapEngine) {
  1459. return
  1460. }
  1461. const finishSummary = mapEngine.getSessionFinishSummary(statusOverride)
  1462. if (!finishSummary) {
  1463. return
  1464. }
  1465. const summaryPayload: BackendSessionFinishSummaryPayload = {}
  1466. if (typeof finishSummary.finalDurationSec === 'number') {
  1467. summaryPayload.finalDurationSec = finishSummary.finalDurationSec
  1468. }
  1469. if (typeof finishSummary.finalScore === 'number') {
  1470. summaryPayload.finalScore = finishSummary.finalScore
  1471. }
  1472. if (typeof finishSummary.completedControls === 'number') {
  1473. summaryPayload.completedControls = finishSummary.completedControls
  1474. }
  1475. if (typeof finishSummary.totalControls === 'number') {
  1476. summaryPayload.totalControls = finishSummary.totalControls
  1477. }
  1478. if (typeof finishSummary.distanceMeters === 'number') {
  1479. summaryPayload.distanceMeters = finishSummary.distanceMeters
  1480. }
  1481. if (typeof finishSummary.averageSpeedKmh === 'number') {
  1482. summaryPayload.averageSpeedKmh = finishSummary.averageSpeedKmh
  1483. }
  1484. finishSession({
  1485. baseUrl: getCurrentBackendBaseUrl(),
  1486. sessionId: sessionContext.sessionId,
  1487. sessionToken: sessionContext.sessionToken,
  1488. status: finishSummary.status,
  1489. summary: summaryPayload,
  1490. })
  1491. .then(() => {
  1492. syncedBackendSessionFinishId = sessionContext.sessionId
  1493. })
  1494. .catch((error) => {
  1495. const message = error && error.message ? error.message : '未知错误'
  1496. this.setData({
  1497. statusText: `session finish 上报失败: ${message}`,
  1498. })
  1499. })
  1500. },
  1501. reportAbandonedRecoverySnapshot(snapshot: SessionRecoverySnapshot) {
  1502. const sessionContext = getBackendSessionContextFromLaunchEnvelope(snapshot.launchEnvelope)
  1503. if (!sessionContext) {
  1504. clearSessionRecoverySnapshot()
  1505. return
  1506. }
  1507. finishSession({
  1508. baseUrl: getCurrentBackendBaseUrl(),
  1509. sessionId: sessionContext.sessionId,
  1510. sessionToken: sessionContext.sessionToken,
  1511. status: 'cancelled',
  1512. summary: {},
  1513. })
  1514. .then(() => {
  1515. syncedBackendSessionFinishId = sessionContext.sessionId
  1516. clearSessionRecoverySnapshot()
  1517. wx.showToast({
  1518. title: '已放弃上次对局',
  1519. icon: 'none',
  1520. duration: 1400,
  1521. })
  1522. })
  1523. .catch((error) => {
  1524. clearSessionRecoverySnapshot()
  1525. const message = error && error.message ? error.message : '未知错误'
  1526. this.setData({
  1527. statusText: `放弃恢复已生效,后端取消上报失败: ${message}`,
  1528. })
  1529. wx.showToast({
  1530. title: '已放弃上次对局',
  1531. icon: 'none',
  1532. duration: 1400,
  1533. })
  1534. })
  1535. },
  1536. stashPendingResultSnapshot(snapshot: MapEngineResultSnapshot) {
  1537. const app = getApp<IAppOption>()
  1538. if (app.globalData) {
  1539. app.globalData.pendingResultSnapshot = snapshot
  1540. }
  1541. },
  1542. redirectToResultPage() {
  1543. if (redirectedToResultPage) {
  1544. return
  1545. }
  1546. clearResultExitRedirectTimer()
  1547. clearResultExitCountdownTimer()
  1548. redirectedToResultPage = true
  1549. const sessionContext = getCurrentBackendSessionContext()
  1550. const resultUrl = sessionContext
  1551. ? `/pages/result/result?sessionId=${encodeURIComponent(sessionContext.sessionId)}`
  1552. : '/pages/result/result'
  1553. wx.redirectTo({
  1554. url: resultUrl,
  1555. })
  1556. },
  1557. presentResultExitPrompt() {
  1558. clearResultExitRedirectTimer()
  1559. clearResultExitCountdownTimer()
  1560. let remainingSeconds = Math.ceil(RESULT_EXIT_REDIRECT_DELAY_MS / 1000)
  1561. this.setData({
  1562. showResultScene: true,
  1563. resultSceneCountdownText: `${remainingSeconds} 秒后自动进入成绩页`,
  1564. })
  1565. resultExitCountdownTimer = setInterval(() => {
  1566. remainingSeconds -= 1
  1567. if (remainingSeconds <= 0) {
  1568. clearResultExitCountdownTimer()
  1569. return
  1570. }
  1571. this.setData({
  1572. resultSceneCountdownText: `${remainingSeconds} 秒后自动进入成绩页`,
  1573. })
  1574. }, 1000) as unknown as number
  1575. resultExitRedirectTimer = setTimeout(() => {
  1576. resultExitRedirectTimer = 0
  1577. this.redirectToResultPage()
  1578. }, RESULT_EXIT_REDIRECT_DELAY_MS) as unknown as number
  1579. },
  1580. restoreRecoverySnapshot(snapshot: SessionRecoverySnapshot) {
  1581. systemSettingsLockLifetimeActive = true
  1582. this.applyRuntimeSystemSettings(true)
  1583. const restored = mapEngine ? mapEngine.restoreSessionRecoveryRuntimeSnapshot(snapshot.runtime) : false
  1584. if (!restored) {
  1585. clearSessionRecoverySnapshot()
  1586. wx.showToast({
  1587. title: '恢复失败,已回到初始状态',
  1588. icon: 'none',
  1589. duration: 1600,
  1590. })
  1591. return false
  1592. }
  1593. this.setData({
  1594. showResultScene: false,
  1595. showDebugPanel: false,
  1596. showGameInfoPanel: false,
  1597. showSystemSettingsPanel: false,
  1598. })
  1599. const sessionContext = getCurrentBackendSessionContext()
  1600. if (sessionContext) {
  1601. syncedBackendSessionStartId = sessionContext.sessionId
  1602. }
  1603. this.syncSessionRecoveryLifecycle('running')
  1604. return true
  1605. },
  1606. syncSessionRecoveryLifecycle(status: MapPageData['gameSessionStatus']) {
  1607. if (status === 'running') {
  1608. this.persistSessionRecoverySnapshot()
  1609. if (!sessionRecoveryPersistTimer) {
  1610. sessionRecoveryPersistTimer = setInterval(() => {
  1611. this.persistSessionRecoverySnapshot()
  1612. }, SESSION_RECOVERY_PERSIST_INTERVAL_MS) as unknown as number
  1613. }
  1614. return
  1615. }
  1616. clearSessionRecoveryPersistTimer()
  1617. },
  1618. maybePromptSessionRecoveryRestore(config: RemoteMapConfig) {
  1619. const snapshot = loadSessionRecoverySnapshot()
  1620. if (!snapshot || !mapEngine) {
  1621. return
  1622. }
  1623. if (
  1624. snapshot.launchEnvelope.config.configUrl !== currentGameLaunchEnvelope.config.configUrl
  1625. || snapshot.configAppId !== config.configAppId
  1626. || snapshot.configVersion !== config.configVersion
  1627. ) {
  1628. clearSessionRecoverySnapshot()
  1629. return
  1630. }
  1631. if (shouldAutoRestoreRecoverySnapshot) {
  1632. shouldAutoRestoreRecoverySnapshot = false
  1633. this.restoreRecoverySnapshot(snapshot)
  1634. return
  1635. }
  1636. wx.showModal({
  1637. title: '恢复对局',
  1638. content: '检测到上次有未正常结束的对局,是否继续恢复?',
  1639. confirmText: '继续恢复',
  1640. cancelText: '放弃',
  1641. success: (result) => {
  1642. if (!result.confirm) {
  1643. this.reportAbandonedRecoverySnapshot(snapshot)
  1644. return
  1645. }
  1646. this.restoreRecoverySnapshot(snapshot)
  1647. },
  1648. })
  1649. },
  1650. compileCurrentRuntimeProfile(lockLifetimeActive = isSystemSettingsLockLifetimeActive()) {
  1651. if (!currentRemoteMapConfig) {
  1652. return null
  1653. }
  1654. return compileRuntimeProfile(currentRemoteMapConfig, {
  1655. playerTelemetryProfile: getGlobalTelemetryProfile(),
  1656. settingsLockLifetimeActive: lockLifetimeActive,
  1657. })
  1658. },
  1659. applyCompiledRuntimeProfiles(
  1660. lockLifetimeActive = isSystemSettingsLockLifetimeActive(),
  1661. options?: {
  1662. includeSettings?: boolean
  1663. includeMap?: boolean
  1664. includeGame?: boolean
  1665. includePresentation?: boolean
  1666. includeTelemetry?: boolean
  1667. includeFeedback?: boolean
  1668. },
  1669. ) {
  1670. const currentEngine = mapEngine
  1671. if (!currentEngine) {
  1672. return null
  1673. }
  1674. const compiledProfile = this.compileCurrentRuntimeProfile(lockLifetimeActive)
  1675. if (!compiledProfile) {
  1676. return null
  1677. }
  1678. if (options && options.includeMap) {
  1679. currentEngine.applyCompiledMapProfile(compiledProfile.map)
  1680. }
  1681. if (options && options.includeSettings) {
  1682. currentEngine.applyCompiledSettingsProfile(compiledProfile.settings)
  1683. }
  1684. if (options && options.includeGame) {
  1685. currentEngine.applyCompiledGameProfile(compiledProfile.game)
  1686. }
  1687. if (options && options.includePresentation) {
  1688. currentEngine.applyCompiledPresentationProfile(compiledProfile.presentation)
  1689. }
  1690. if (!options || options.includeTelemetry !== false) {
  1691. currentEngine.applyCompiledTelemetryProfile(compiledProfile.telemetry)
  1692. }
  1693. if (!options || options.includeFeedback !== false) {
  1694. currentEngine.applyCompiledFeedbackProfile(compiledProfile.feedback)
  1695. }
  1696. return compiledProfile
  1697. },
  1698. applyRuntimeSystemSettings(lockLifetimeActive = isSystemSettingsLockLifetimeActive()) {
  1699. const currentEngine = mapEngine
  1700. if (!currentEngine) {
  1701. return null
  1702. }
  1703. const compiledProfile = this.applyCompiledRuntimeProfiles(lockLifetimeActive, {
  1704. includeSettings: true,
  1705. })
  1706. || {
  1707. settings: resolveSystemSettingsState(
  1708. currentSystemSettingsConfig,
  1709. undefined,
  1710. lockLifetimeActive,
  1711. ),
  1712. }
  1713. const resolvedSettings = compiledProfile.settings
  1714. const engineSnapshot = currentEngine.getInitialData() as Partial<MapPageData>
  1715. updateCenterScaleRulerInputCache(engineSnapshot)
  1716. const resolvedPatch = buildResolvedSystemSettingsPatch(resolvedSettings)
  1717. const mergedData = {
  1718. ...centerScaleRulerInputCache,
  1719. ...this.data,
  1720. ...engineSnapshot,
  1721. ...resolvedPatch,
  1722. } as MapPageData
  1723. this.setData({
  1724. ...filterDebugOnlyPatch(engineSnapshot, this.data.showDebugPanel, resolvedSettings.values.showCenterScaleRuler),
  1725. ...resolvedPatch,
  1726. ...buildCenterScaleRulerPatch(mergedData),
  1727. ...buildSideButtonState(mergedData),
  1728. })
  1729. return resolvedSettings
  1730. },
  1731. persistAndApplySystemSettings(
  1732. patch: Partial<StoredUserSettings>,
  1733. options?: {
  1734. applyCenterScaleRuler?: boolean
  1735. },
  1736. ) {
  1737. updateStoredUserSettings(patch)
  1738. const lockLifetimeActive = isSystemSettingsLockLifetimeActive()
  1739. const resolvedSettings = this.applyRuntimeSystemSettings(lockLifetimeActive)
  1740. if (!resolvedSettings || !(options && options.applyCenterScaleRuler)) {
  1741. return resolvedSettings
  1742. }
  1743. this.applyCenterScaleRulerSettings(
  1744. resolvedSettings.values.showCenterScaleRuler,
  1745. resolvedSettings.values.centerScaleRulerAnchorMode,
  1746. )
  1747. return resolvedSettings
  1748. },
  1749. loadMapConfigFromRemote(configUrl: string, configLabel: string) {
  1750. const currentEngine = mapEngine
  1751. if (!currentEngine) {
  1752. return
  1753. }
  1754. this.setData({
  1755. configSourceText: configLabel,
  1756. configStatusText: `加载中: ${configLabel}`,
  1757. })
  1758. loadRemoteMapConfig(configUrl)
  1759. .then((config) => {
  1760. if (mapEngine !== currentEngine) {
  1761. return
  1762. }
  1763. currentEngine.applyRemoteMapConfig(config)
  1764. this.applyConfiguredSystemSettings(config)
  1765. this.applyCompiledRuntimeProfiles(true, {
  1766. includeMap: true,
  1767. includeGame: true,
  1768. includePresentation: true,
  1769. })
  1770. this.maybePromptSessionRecoveryRestore(config)
  1771. })
  1772. .catch((error) => {
  1773. if (mapEngine !== currentEngine) {
  1774. return
  1775. }
  1776. const rawErrorMessage = error && error.message ? error.message : '未知错误'
  1777. const errorMessage = rawErrorMessage.indexOf('404') >= 0
  1778. ? `release manifest 不存在或未发布 (${configLabel})`
  1779. : rawErrorMessage
  1780. this.setData({
  1781. configStatusText: `载入失败: ${errorMessage}`,
  1782. statusText: `远程地图配置载入失败: ${errorMessage} (${INTERNAL_BUILD_VERSION})`,
  1783. })
  1784. })
  1785. },
  1786. applyConfiguredSystemSettings(config: RemoteMapConfig) {
  1787. currentRemoteMapConfig = config
  1788. currentSystemSettingsConfig = config.systemSettingsConfig
  1789. systemSettingsLockLifetimeActive = true
  1790. this.applyRuntimeSystemSettings(true)
  1791. },
  1792. measureStageAndCanvas(onApplied?: () => void) {
  1793. const page = this
  1794. const applyStage = (rawRect?: Partial<WechatMiniprogram.BoundingClientRectCallbackResult>) => {
  1795. const fallbackRect = getFallbackStageRect()
  1796. const rect: MapEngineStageRect = {
  1797. width: rawRect && typeof rawRect.width === 'number' ? rawRect.width : fallbackRect.width,
  1798. height: rawRect && typeof rawRect.height === 'number' ? rawRect.height : fallbackRect.height,
  1799. left: rawRect && typeof rawRect.left === 'number' ? rawRect.left : fallbackRect.left,
  1800. top: rawRect && typeof rawRect.top === 'number' ? rawRect.top : fallbackRect.top,
  1801. }
  1802. const currentEngine = mapEngine
  1803. if (!currentEngine) {
  1804. return
  1805. }
  1806. currentEngine.setStage(rect)
  1807. if (onApplied) {
  1808. onApplied()
  1809. }
  1810. if (stageCanvasAttached) {
  1811. return
  1812. }
  1813. const canvasQuery = wx.createSelectorQuery().in(page)
  1814. canvasQuery.select('#mapCanvas').fields({ node: true, size: true })
  1815. canvasQuery.select('#routeLabelCanvas').fields({ node: true, size: true })
  1816. canvasQuery.exec((canvasRes) => {
  1817. const canvasRef = canvasRes[0] as any
  1818. const labelCanvasRef = canvasRes[1] as any
  1819. if (!canvasRef || !canvasRef.node) {
  1820. page.setData({
  1821. statusText: `WebGL 引擎初始化失败 (${INTERNAL_BUILD_VERSION})`,
  1822. })
  1823. return
  1824. }
  1825. const dpr = wx.getSystemInfoSync().pixelRatio || 1
  1826. try {
  1827. currentEngine.attachCanvas(
  1828. canvasRef.node,
  1829. rect.width,
  1830. rect.height,
  1831. dpr,
  1832. labelCanvasRef && labelCanvasRef.node ? labelCanvasRef.node : undefined,
  1833. )
  1834. stageCanvasAttached = true
  1835. } catch (error) {
  1836. page.setData({
  1837. statusText: `WebGL 鍒濆鍖栧け璐?(${INTERNAL_BUILD_VERSION})`,
  1838. })
  1839. }
  1840. })
  1841. }
  1842. const query = wx.createSelectorQuery().in(page)
  1843. query.select('.map-stage').boundingClientRect()
  1844. query.exec((res) => {
  1845. const rect = res[0] as WechatMiniprogram.BoundingClientRectCallbackResult | undefined
  1846. applyStage(rect)
  1847. })
  1848. },
  1849. handleTouchStart(event: WechatMiniprogram.TouchEvent) {
  1850. if (mapEngine) {
  1851. mapEngine.handleTouchStart(event)
  1852. }
  1853. },
  1854. handleTouchMove(event: WechatMiniprogram.TouchEvent) {
  1855. if (mapEngine) {
  1856. mapEngine.handleTouchMove(event)
  1857. }
  1858. },
  1859. handleTouchEnd(event: WechatMiniprogram.TouchEvent) {
  1860. if (mapEngine) {
  1861. mapEngine.handleTouchEnd(event)
  1862. }
  1863. },
  1864. handleTouchCancel() {
  1865. if (mapEngine) {
  1866. mapEngine.handleTouchCancel()
  1867. }
  1868. },
  1869. handleRecenter() {
  1870. if (mapEngine) {
  1871. mapEngine.handleRecenter()
  1872. }
  1873. },
  1874. handleRotateStep() {
  1875. if (mapEngine) {
  1876. mapEngine.handleRotateStep()
  1877. }
  1878. },
  1879. handleRotationReset() {
  1880. if (mapEngine) {
  1881. mapEngine.handleRotationReset()
  1882. }
  1883. },
  1884. handleSetManualMode() {
  1885. if (mapEngine) {
  1886. mapEngine.handleSetManualMode()
  1887. }
  1888. },
  1889. handleSetNorthUpMode() {
  1890. if (mapEngine) {
  1891. mapEngine.handleSetNorthUpMode()
  1892. }
  1893. },
  1894. handleSetHeadingUpMode() {
  1895. if (mapEngine) {
  1896. mapEngine.handleSetHeadingUpMode()
  1897. }
  1898. },
  1899. handleCycleNorthReferenceMode() {
  1900. if (mapEngine) {
  1901. mapEngine.handleCycleNorthReferenceMode()
  1902. }
  1903. },
  1904. handleAutoRotateCalibrate() {
  1905. if (mapEngine) {
  1906. mapEngine.handleAutoRotateCalibrate()
  1907. }
  1908. },
  1909. handleToggleGpsTracking() {
  1910. if (mapEngine) {
  1911. mapEngine.handleToggleGpsTracking()
  1912. }
  1913. },
  1914. handleSetRealLocationMode() {
  1915. if (mapEngine) {
  1916. mapEngine.handleSetRealLocationMode()
  1917. }
  1918. },
  1919. handleSetMockLocationMode() {
  1920. if (mapEngine) {
  1921. mapEngine.handleSetMockLocationMode()
  1922. }
  1923. },
  1924. handleConnectMockLocationBridge() {
  1925. if (mapEngine) {
  1926. mapEngine.handleConnectMockLocationBridge()
  1927. }
  1928. },
  1929. handleConnectAllMockSources() {
  1930. if (!mapEngine) {
  1931. return
  1932. }
  1933. const channelId = (this.data.mockChannelIdDraft || '').trim() || 'default'
  1934. this.setData({
  1935. mockChannelIdDraft: channelId,
  1936. })
  1937. persistMockChannelId(channelId)
  1938. persistMockAutoConnectEnabled(true)
  1939. mapEngine.handleSetMockChannelId(channelId)
  1940. mapEngine.handleSetMockLocationBridgeUrl(this.data.mockBridgeUrlDraft)
  1941. mapEngine.handleSetMockHeartRateBridgeUrl(this.data.mockHeartRateBridgeUrlDraft)
  1942. mapEngine.handleSetMockDebugLogBridgeUrl(this.data.mockDebugLogBridgeUrlDraft)
  1943. mapEngine.handleConnectMockLocationBridge()
  1944. mapEngine.handleSetMockLocationMode()
  1945. mapEngine.handleSetMockHeartRateMode()
  1946. mapEngine.handleConnectMockHeartRateBridge()
  1947. mapEngine.handleConnectMockDebugLogBridge()
  1948. },
  1949. handleOpenWebViewTest() {
  1950. wx.navigateTo({
  1951. url: '/pages/webview-test/webview-test',
  1952. })
  1953. },
  1954. handleMockChannelIdInput(event: WechatMiniprogram.Input) {
  1955. this.setData({
  1956. mockChannelIdDraft: event.detail.value,
  1957. })
  1958. },
  1959. handleSaveMockChannelId() {
  1960. const channelId = (this.data.mockChannelIdDraft || '').trim() || 'default'
  1961. this.setData({
  1962. mockChannelIdDraft: channelId,
  1963. })
  1964. persistMockChannelId(channelId)
  1965. if (mapEngine) {
  1966. mapEngine.handleSetMockChannelId(channelId)
  1967. }
  1968. },
  1969. handleMockBridgeUrlInput(event: WechatMiniprogram.Input) {
  1970. this.setData({
  1971. mockBridgeUrlDraft: event.detail.value,
  1972. })
  1973. },
  1974. handleSaveMockBridgeUrl() {
  1975. if (mapEngine) {
  1976. mapEngine.handleSetMockLocationBridgeUrl(this.data.mockBridgeUrlDraft)
  1977. }
  1978. },
  1979. handleDisconnectMockLocationBridge() {
  1980. persistMockAutoConnectEnabled(false)
  1981. if (mapEngine) {
  1982. mapEngine.handleDisconnectMockLocationBridge()
  1983. }
  1984. },
  1985. handleSetRealHeartRateMode() {
  1986. if (mapEngine) {
  1987. mapEngine.handleSetRealHeartRateMode()
  1988. }
  1989. },
  1990. handleSetMockHeartRateMode() {
  1991. if (mapEngine) {
  1992. mapEngine.handleSetMockHeartRateMode()
  1993. }
  1994. },
  1995. handleMockHeartRateBridgeUrlInput(event: WechatMiniprogram.Input) {
  1996. this.setData({
  1997. mockHeartRateBridgeUrlDraft: event.detail.value,
  1998. })
  1999. },
  2000. handleSaveMockHeartRateBridgeUrl() {
  2001. if (mapEngine) {
  2002. mapEngine.handleSetMockHeartRateBridgeUrl(this.data.mockHeartRateBridgeUrlDraft)
  2003. }
  2004. },
  2005. handleMockDebugLogBridgeUrlInput(event: WechatMiniprogram.Input) {
  2006. this.setData({
  2007. mockDebugLogBridgeUrlDraft: event.detail.value,
  2008. })
  2009. },
  2010. handleSaveMockDebugLogBridgeUrl() {
  2011. if (mapEngine) {
  2012. mapEngine.handleSetMockDebugLogBridgeUrl(this.data.mockDebugLogBridgeUrlDraft)
  2013. }
  2014. },
  2015. handleConnectMockDebugLogBridge() {
  2016. if (mapEngine) {
  2017. mapEngine.handleConnectMockDebugLogBridge()
  2018. }
  2019. },
  2020. handleDisconnectMockDebugLogBridge() {
  2021. persistMockAutoConnectEnabled(false)
  2022. if (mapEngine) {
  2023. mapEngine.handleDisconnectMockDebugLogBridge()
  2024. }
  2025. },
  2026. handleConnectMockHeartRateBridge() {
  2027. if (mapEngine) {
  2028. mapEngine.handleConnectMockHeartRateBridge()
  2029. }
  2030. },
  2031. handleDisconnectMockHeartRateBridge() {
  2032. persistMockAutoConnectEnabled(false)
  2033. if (mapEngine) {
  2034. mapEngine.handleDisconnectMockHeartRateBridge()
  2035. }
  2036. },
  2037. handleConnectHeartRate() {
  2038. if (this.data.lockHeartRateDevice || this.data.heartRateSourceMode !== 'real') {
  2039. return
  2040. }
  2041. if (mapEngine) {
  2042. mapEngine.handleConnectHeartRate()
  2043. }
  2044. },
  2045. handleOpenHeartRateDevicePicker() {
  2046. if (this.data.lockHeartRateDevice || this.data.heartRateSourceMode !== 'real') {
  2047. return
  2048. }
  2049. this.setData({
  2050. showHeartRateDevicePicker: true,
  2051. })
  2052. if (mapEngine) {
  2053. mapEngine.handleConnectHeartRate()
  2054. }
  2055. },
  2056. handleCloseHeartRateDevicePicker() {
  2057. this.setData({
  2058. showHeartRateDevicePicker: false,
  2059. })
  2060. },
  2061. handleDisconnectHeartRate() {
  2062. if (this.data.lockHeartRateDevice || this.data.heartRateSourceMode !== 'real') {
  2063. return
  2064. }
  2065. if (mapEngine) {
  2066. mapEngine.handleDisconnectHeartRate()
  2067. }
  2068. },
  2069. handleConnectHeartRateDevice(event: WechatMiniprogram.BaseEvent<{ deviceId?: string }>) {
  2070. if (mapEngine && event.currentTarget && event.currentTarget.dataset && event.currentTarget.dataset.deviceId) {
  2071. const targetDeviceId = event.currentTarget.dataset.deviceId
  2072. const targetDevice = this.data.heartRateDiscoveredDevices.find((item) => item.deviceId === targetDeviceId)
  2073. pendingHeartRateSwitchDeviceName = targetDevice ? targetDevice.name : null
  2074. mapEngine.handleConnectHeartRateDevice(targetDeviceId)
  2075. this.setData({
  2076. showHeartRateDevicePicker: false,
  2077. statusText: targetDevice
  2078. ? `正在切换到 ${targetDevice.name}`
  2079. : '正在切换心率带设备',
  2080. })
  2081. }
  2082. },
  2083. handleClearPreferredHeartRateDevice() {
  2084. if (this.data.lockHeartRateDevice) {
  2085. return
  2086. }
  2087. if (mapEngine) {
  2088. mapEngine.handleClearPreferredHeartRateDevice()
  2089. }
  2090. },
  2091. handleDebugHeartRateBlue() {
  2092. if (mapEngine) {
  2093. mapEngine.handleDebugHeartRateTone('blue')
  2094. }
  2095. },
  2096. handleDebugHeartRatePurple() {
  2097. if (mapEngine) {
  2098. mapEngine.handleDebugHeartRateTone('purple')
  2099. }
  2100. },
  2101. handleDebugHeartRateGreen() {
  2102. if (mapEngine) {
  2103. mapEngine.handleDebugHeartRateTone('green')
  2104. }
  2105. },
  2106. handleDebugHeartRateYellow() {
  2107. if (mapEngine) {
  2108. mapEngine.handleDebugHeartRateTone('yellow')
  2109. }
  2110. },
  2111. handleDebugHeartRateOrange() {
  2112. if (mapEngine) {
  2113. mapEngine.handleDebugHeartRateTone('orange')
  2114. }
  2115. },
  2116. handleDebugHeartRateRed() {
  2117. if (mapEngine) {
  2118. mapEngine.handleDebugHeartRateTone('red')
  2119. }
  2120. },
  2121. handleDebugSetSessionRemainingWarning() {
  2122. if (mapEngine) {
  2123. mapEngine.handleDebugSetSessionRemainingWarning()
  2124. }
  2125. },
  2126. handleDebugSetSessionRemainingOneMinute() {
  2127. if (mapEngine) {
  2128. mapEngine.handleDebugSetSessionRemainingOneMinute()
  2129. }
  2130. },
  2131. handleDebugTimeoutSession() {
  2132. if (mapEngine) {
  2133. mapEngine.handleDebugTimeoutSession()
  2134. }
  2135. },
  2136. handleClearDebugHeartRate() {
  2137. if (mapEngine) {
  2138. mapEngine.handleClearDebugHeartRate()
  2139. }
  2140. },
  2141. handleToggleOsmReference() {
  2142. if (mapEngine) {
  2143. mapEngine.handleToggleOsmReference()
  2144. }
  2145. },
  2146. handleStartGame() {
  2147. if (mapEngine) {
  2148. systemSettingsLockLifetimeActive = true
  2149. this.applyRuntimeSystemSettings(true)
  2150. mapEngine.handleStartGame()
  2151. }
  2152. },
  2153. handleLoadClassicConfig() {
  2154. currentGameLaunchEnvelope = getDemoGameLaunchEnvelope('classic')
  2155. this.loadGameLaunchEnvelope(currentGameLaunchEnvelope)
  2156. },
  2157. handleLoadScoreOConfig() {
  2158. currentGameLaunchEnvelope = getDemoGameLaunchEnvelope('score-o')
  2159. this.loadGameLaunchEnvelope(currentGameLaunchEnvelope)
  2160. },
  2161. handleForceExitGame() {
  2162. if (!mapEngine || this.data.gameSessionStatus !== 'running') {
  2163. return
  2164. }
  2165. wx.showModal({
  2166. title: '确认退出',
  2167. content: '确认强制结束当前对局并返回开始前状态?',
  2168. confirmText: '确认退出',
  2169. cancelText: '取消',
  2170. success: (result) => {
  2171. if (result.confirm && mapEngine) {
  2172. clearResultExitRedirectTimer()
  2173. clearResultExitCountdownTimer()
  2174. this.syncBackendSessionFinish('cancelled')
  2175. clearSessionRecoverySnapshot()
  2176. clearSessionRecoveryPersistTimer()
  2177. systemSettingsLockLifetimeActive = false
  2178. mapEngine.handleForceExitGame()
  2179. wx.showToast({
  2180. title: '已退出当前对局',
  2181. icon: 'none',
  2182. duration: 1000,
  2183. })
  2184. setTimeout(() => {
  2185. navigateAwayFromMapAfterCancel()
  2186. }, 180)
  2187. }
  2188. },
  2189. })
  2190. },
  2191. handleSkipAction() {
  2192. if (!mapEngine || !this.data.skipButtonEnabled) {
  2193. return
  2194. }
  2195. if (!mapEngine.shouldConfirmSkipAction()) {
  2196. mapEngine.handleSkipAction()
  2197. return
  2198. }
  2199. wx.showModal({
  2200. title: '确认跳点',
  2201. content: '确认跳过当前检查点并切换到下一个目标点?',
  2202. confirmText: '确认跳过',
  2203. cancelText: '取消',
  2204. success: (result) => {
  2205. if (result.confirm && mapEngine) {
  2206. mapEngine.handleSkipAction()
  2207. }
  2208. },
  2209. })
  2210. },
  2211. handleClearMapTestArtifacts() {
  2212. if (mapEngine) {
  2213. mapEngine.handleClearMapTestArtifacts()
  2214. }
  2215. },
  2216. syncGameInfoPanelSnapshot() {
  2217. if (!mapEngine) {
  2218. return
  2219. }
  2220. const snapshot = mapEngine.getGameInfoSnapshot()
  2221. const localRows = snapshot.localRows.concat([
  2222. { label: '比例尺开关', value: this.data.showCenterScaleRuler ? '开启' : '关闭' },
  2223. { label: '比例尺锚点', value: this.data.centerScaleRulerAnchorMode === 'compass-center' ? '指北针圆心' : '屏幕中心' },
  2224. { label: '按钮习惯', value: this.data.sideButtonPlacement === 'right' ? '右手' : '左手' },
  2225. { label: '比例尺可见', value: this.data.centerScaleRulerVisible ? 'true' : 'false' },
  2226. { label: '比例尺中心X', value: `${this.data.centerScaleRulerCenterXPx}px` },
  2227. { label: '比例尺零点Y', value: `${this.data.centerScaleRulerZeroYPx}px` },
  2228. { label: '比例尺高度', value: `${this.data.centerScaleRulerHeightPx}px` },
  2229. { label: '比例尺主刻度数', value: String(this.data.centerScaleRulerMajorMarks.length) },
  2230. ])
  2231. this.setData({
  2232. gameInfoTitle: snapshot.title,
  2233. gameInfoSubtitle: snapshot.subtitle,
  2234. gameInfoLocalRows: localRows,
  2235. gameInfoGlobalRows: snapshot.globalRows,
  2236. })
  2237. },
  2238. syncResultSceneSnapshot() {
  2239. if (!mapEngine) {
  2240. return
  2241. }
  2242. const snapshot = mapEngine.getResultSceneSnapshot()
  2243. this.setData({
  2244. resultSceneTitle: snapshot.title,
  2245. resultSceneSubtitle: snapshot.subtitle,
  2246. resultSceneHeroLabel: snapshot.heroLabel,
  2247. resultSceneHeroValue: snapshot.heroValue,
  2248. resultSceneRows: snapshot.rows,
  2249. })
  2250. },
  2251. scheduleGameInfoPanelSnapshotSync() {
  2252. if (!this.data.showGameInfoPanel) {
  2253. clearGameInfoPanelSyncTimer()
  2254. return
  2255. }
  2256. if (gameInfoPanelSyncTimer) {
  2257. return
  2258. }
  2259. gameInfoPanelSyncTimer = setTimeout(() => {
  2260. gameInfoPanelSyncTimer = 0
  2261. if (this.data.showGameInfoPanel) {
  2262. this.syncGameInfoPanelSnapshot()
  2263. }
  2264. }, 400) as unknown as number
  2265. },
  2266. handleOpenGameInfoPanel() {
  2267. clearGameInfoPanelSyncTimer()
  2268. this.syncGameInfoPanelSnapshot()
  2269. this.setData({
  2270. showDebugPanel: false,
  2271. showSystemSettingsPanel: false,
  2272. showGameInfoPanel: true,
  2273. ...buildSideButtonState({
  2274. sideButtonMode: this.data.sideButtonMode,
  2275. showGameInfoPanel: true,
  2276. showSystemSettingsPanel: false,
  2277. showCenterScaleRuler: this.data.showCenterScaleRuler,
  2278. centerScaleRulerAnchorMode: this.data.centerScaleRulerAnchorMode,
  2279. skipButtonEnabled: this.data.skipButtonEnabled,
  2280. gameSessionStatus: this.data.gameSessionStatus,
  2281. gpsLockEnabled: this.data.gpsLockEnabled,
  2282. gpsLockAvailable: this.data.gpsLockAvailable,
  2283. }),
  2284. })
  2285. },
  2286. handleCloseGameInfoPanel() {
  2287. clearGameInfoPanelSyncTimer()
  2288. this.setData({
  2289. showGameInfoPanel: false,
  2290. ...buildSideButtonState({
  2291. sideButtonMode: this.data.sideButtonMode,
  2292. showGameInfoPanel: false,
  2293. showSystemSettingsPanel: this.data.showSystemSettingsPanel,
  2294. showCenterScaleRuler: this.data.showCenterScaleRuler,
  2295. centerScaleRulerAnchorMode: this.data.centerScaleRulerAnchorMode,
  2296. skipButtonEnabled: this.data.skipButtonEnabled,
  2297. gameSessionStatus: this.data.gameSessionStatus,
  2298. gpsLockEnabled: this.data.gpsLockEnabled,
  2299. gpsLockAvailable: this.data.gpsLockAvailable,
  2300. }),
  2301. })
  2302. },
  2303. handleGameInfoPanelTap() {},
  2304. handleResultSceneTap() {},
  2305. handleCloseResultScene() {
  2306. this.redirectToResultPage()
  2307. },
  2308. handleRestartFromResult() {
  2309. this.redirectToResultPage()
  2310. },
  2311. handleOpenSystemSettingsPanel() {
  2312. clearGameInfoPanelSyncTimer()
  2313. this.setData({
  2314. showDebugPanel: false,
  2315. showGameInfoPanel: false,
  2316. showSystemSettingsPanel: true,
  2317. ...buildSideButtonState({
  2318. sideButtonMode: this.data.sideButtonMode,
  2319. showGameInfoPanel: false,
  2320. showSystemSettingsPanel: true,
  2321. showCenterScaleRuler: this.data.showCenterScaleRuler,
  2322. centerScaleRulerAnchorMode: this.data.centerScaleRulerAnchorMode,
  2323. skipButtonEnabled: this.data.skipButtonEnabled,
  2324. gameSessionStatus: this.data.gameSessionStatus,
  2325. gpsLockEnabled: this.data.gpsLockEnabled,
  2326. gpsLockAvailable: this.data.gpsLockAvailable,
  2327. }),
  2328. })
  2329. },
  2330. handleCloseSystemSettingsPanel() {
  2331. this.setData({
  2332. showSystemSettingsPanel: false,
  2333. ...buildSideButtonState({
  2334. sideButtonMode: this.data.sideButtonMode,
  2335. showGameInfoPanel: this.data.showGameInfoPanel,
  2336. showSystemSettingsPanel: false,
  2337. showCenterScaleRuler: this.data.showCenterScaleRuler,
  2338. centerScaleRulerAnchorMode: this.data.centerScaleRulerAnchorMode,
  2339. skipButtonEnabled: this.data.skipButtonEnabled,
  2340. gameSessionStatus: this.data.gameSessionStatus,
  2341. gpsLockEnabled: this.data.gpsLockEnabled,
  2342. gpsLockAvailable: this.data.gpsLockAvailable,
  2343. }),
  2344. })
  2345. },
  2346. handleSystemSettingsPanelTap() {},
  2347. handleSetAnimationLevelStandard() {
  2348. if (this.data.lockAnimationLevel || !mapEngine) {
  2349. return
  2350. }
  2351. this.persistAndApplySystemSettings({
  2352. animationLevel: 'standard',
  2353. })
  2354. },
  2355. handleSetAnimationLevelLite() {
  2356. if (this.data.lockAnimationLevel || !mapEngine) {
  2357. return
  2358. }
  2359. this.persistAndApplySystemSettings({
  2360. animationLevel: 'lite',
  2361. })
  2362. },
  2363. handleSetTrackModeNone() {
  2364. if (this.data.lockTrackMode || !mapEngine) {
  2365. return
  2366. }
  2367. this.persistAndApplySystemSettings({
  2368. trackDisplayMode: 'none',
  2369. })
  2370. },
  2371. handleSetTrackModeTail() {
  2372. if (this.data.lockTrackMode || !mapEngine) {
  2373. return
  2374. }
  2375. this.persistAndApplySystemSettings({
  2376. trackDisplayMode: 'tail',
  2377. })
  2378. },
  2379. handleSetTrackModeFull() {
  2380. if (this.data.lockTrackMode || !mapEngine) {
  2381. return
  2382. }
  2383. this.persistAndApplySystemSettings({
  2384. trackDisplayMode: 'full',
  2385. })
  2386. },
  2387. handleSetTrackTailLengthShort() {
  2388. if (this.data.lockTrackTailLength || !mapEngine) {
  2389. return
  2390. }
  2391. this.persistAndApplySystemSettings({
  2392. trackTailLength: 'short',
  2393. })
  2394. },
  2395. handleSetTrackTailLengthMedium() {
  2396. if (this.data.lockTrackTailLength || !mapEngine) {
  2397. return
  2398. }
  2399. this.persistAndApplySystemSettings({
  2400. trackTailLength: 'medium',
  2401. })
  2402. },
  2403. handleSetTrackTailLengthLong() {
  2404. if (this.data.lockTrackTailLength || !mapEngine) {
  2405. return
  2406. }
  2407. this.persistAndApplySystemSettings({
  2408. trackTailLength: 'long',
  2409. })
  2410. },
  2411. handleSetTrackColorPreset(event: WechatMiniprogram.TouchEvent) {
  2412. if (this.data.lockTrackColor || !mapEngine) {
  2413. return
  2414. }
  2415. const color = event.currentTarget.dataset.color as TrackColorPreset | undefined
  2416. if (!color) {
  2417. return
  2418. }
  2419. this.persistAndApplySystemSettings({
  2420. trackColorPreset: color,
  2421. })
  2422. },
  2423. handleSetTrackStyleClassic() {
  2424. if (this.data.lockTrackStyle || !mapEngine) {
  2425. return
  2426. }
  2427. this.persistAndApplySystemSettings({
  2428. trackStyleProfile: 'classic',
  2429. })
  2430. },
  2431. handleSetTrackStyleNeon() {
  2432. if (this.data.lockTrackStyle || !mapEngine) {
  2433. return
  2434. }
  2435. this.persistAndApplySystemSettings({
  2436. trackStyleProfile: 'neon',
  2437. })
  2438. },
  2439. handleSetGpsMarkerVisibleOn() {
  2440. if (this.data.lockGpsMarkerVisible || !mapEngine) {
  2441. return
  2442. }
  2443. this.persistAndApplySystemSettings({
  2444. gpsMarkerVisible: true,
  2445. })
  2446. },
  2447. handleSetGpsMarkerVisibleOff() {
  2448. if (this.data.lockGpsMarkerVisible || !mapEngine) {
  2449. return
  2450. }
  2451. this.persistAndApplySystemSettings({
  2452. gpsMarkerVisible: false,
  2453. })
  2454. },
  2455. handleSetGpsMarkerStyleDot() {
  2456. if (this.data.lockGpsMarkerStyle || !mapEngine) {
  2457. return
  2458. }
  2459. this.persistAndApplySystemSettings({
  2460. gpsMarkerStyle: 'dot',
  2461. })
  2462. },
  2463. handleSetGpsMarkerStyleBeacon() {
  2464. if (this.data.lockGpsMarkerStyle || !mapEngine) {
  2465. return
  2466. }
  2467. this.persistAndApplySystemSettings({
  2468. gpsMarkerStyle: 'beacon',
  2469. })
  2470. },
  2471. handleSetGpsMarkerStyleDisc() {
  2472. if (this.data.lockGpsMarkerStyle || !mapEngine) {
  2473. return
  2474. }
  2475. this.persistAndApplySystemSettings({
  2476. gpsMarkerStyle: 'disc',
  2477. })
  2478. },
  2479. handleSetGpsMarkerStyleBadge() {
  2480. if (this.data.lockGpsMarkerStyle || !mapEngine) {
  2481. return
  2482. }
  2483. this.persistAndApplySystemSettings({
  2484. gpsMarkerStyle: 'badge',
  2485. })
  2486. },
  2487. handleSetGpsMarkerSizeSmall() {
  2488. if (this.data.lockGpsMarkerSize || !mapEngine) {
  2489. return
  2490. }
  2491. this.persistAndApplySystemSettings({
  2492. gpsMarkerSize: 'small',
  2493. })
  2494. },
  2495. handleSetGpsMarkerSizeMedium() {
  2496. if (this.data.lockGpsMarkerSize || !mapEngine) {
  2497. return
  2498. }
  2499. this.persistAndApplySystemSettings({
  2500. gpsMarkerSize: 'medium',
  2501. })
  2502. },
  2503. handleSetGpsMarkerSizeLarge() {
  2504. if (this.data.lockGpsMarkerSize || !mapEngine) {
  2505. return
  2506. }
  2507. this.persistAndApplySystemSettings({
  2508. gpsMarkerSize: 'large',
  2509. })
  2510. },
  2511. handleSetGpsMarkerColorPreset(event: WechatMiniprogram.TouchEvent) {
  2512. if (this.data.lockGpsMarkerColor || !mapEngine) {
  2513. return
  2514. }
  2515. const color = event.currentTarget.dataset.color as GpsMarkerColorPreset | undefined
  2516. if (!color) {
  2517. return
  2518. }
  2519. this.persistAndApplySystemSettings({
  2520. gpsMarkerColorPreset: color,
  2521. })
  2522. },
  2523. handleSetSideButtonPlacementLeft() {
  2524. if (this.data.lockSideButtonPlacement) {
  2525. return
  2526. }
  2527. this.persistAndApplySystemSettings({
  2528. sideButtonPlacement: 'left',
  2529. })
  2530. },
  2531. handleSetSideButtonPlacementRight() {
  2532. if (this.data.lockSideButtonPlacement) {
  2533. return
  2534. }
  2535. this.persistAndApplySystemSettings({
  2536. sideButtonPlacement: 'right',
  2537. })
  2538. },
  2539. handleSetAutoRotateEnabledOn() {
  2540. if (this.data.lockAutoRotate || !mapEngine) {
  2541. return
  2542. }
  2543. this.persistAndApplySystemSettings({
  2544. autoRotateEnabled: true,
  2545. })
  2546. },
  2547. handleSetAutoRotateEnabledOff() {
  2548. if (this.data.lockAutoRotate || !mapEngine) {
  2549. return
  2550. }
  2551. this.persistAndApplySystemSettings({
  2552. autoRotateEnabled: false,
  2553. })
  2554. },
  2555. handleSetCompassTuningSmooth() {
  2556. if (this.data.lockCompassTuning || !mapEngine) {
  2557. return
  2558. }
  2559. this.persistAndApplySystemSettings({
  2560. compassTuningProfile: 'smooth',
  2561. })
  2562. },
  2563. handleSetCompassTuningBalanced() {
  2564. if (this.data.lockCompassTuning || !mapEngine) {
  2565. return
  2566. }
  2567. this.persistAndApplySystemSettings({
  2568. compassTuningProfile: 'balanced',
  2569. })
  2570. },
  2571. handleSetCompassTuningResponsive() {
  2572. if (this.data.lockCompassTuning || !mapEngine) {
  2573. return
  2574. }
  2575. this.persistAndApplySystemSettings({
  2576. compassTuningProfile: 'responsive',
  2577. })
  2578. },
  2579. handleSetNorthReferenceMagnetic() {
  2580. if (this.data.lockNorthReference || !mapEngine) {
  2581. return
  2582. }
  2583. this.persistAndApplySystemSettings({
  2584. northReferenceMode: 'magnetic',
  2585. })
  2586. },
  2587. handleSetNorthReferenceTrue() {
  2588. if (this.data.lockNorthReference || !mapEngine) {
  2589. return
  2590. }
  2591. this.persistAndApplySystemSettings({
  2592. northReferenceMode: 'true',
  2593. })
  2594. },
  2595. handleOverlayTouch() {},
  2596. handlePunchAction() {
  2597. if (!this.data.punchButtonEnabled) {
  2598. return
  2599. }
  2600. if (mapEngine) {
  2601. mapEngine.handlePunchAction()
  2602. }
  2603. },
  2604. handleOpenPendingContentCard() {
  2605. if (mapEngine) {
  2606. mapEngine.openPendingContentCard()
  2607. }
  2608. },
  2609. handleOpenContentCardAction(event: WechatMiniprogram.BaseEvent) {
  2610. if (!mapEngine) {
  2611. return
  2612. }
  2613. wx.showToast({
  2614. title: '点击CTA',
  2615. icon: 'none',
  2616. duration: 900,
  2617. })
  2618. const actionType = event.currentTarget.dataset.type
  2619. const action = typeof actionType === 'string' ? mapEngine.openCurrentContentCardAction(actionType) : null
  2620. if (action === 'detail') {
  2621. wx.showToast({
  2622. title: '打开详情',
  2623. icon: 'none',
  2624. duration: 900,
  2625. })
  2626. return
  2627. }
  2628. if (action === 'quiz') {
  2629. return
  2630. }
  2631. if (action === 'photo') {
  2632. wx.chooseMedia({
  2633. count: 1,
  2634. mediaType: ['image'],
  2635. sourceType: ['camera'],
  2636. success: () => {
  2637. if (mapEngine) {
  2638. mapEngine.handleContentCardPhotoCaptured()
  2639. }
  2640. },
  2641. })
  2642. return
  2643. }
  2644. if (action === 'audio') {
  2645. if (!contentAudioRecorder) {
  2646. contentAudioRecorder = wx.getRecorderManager()
  2647. contentAudioRecorder.onStop(() => {
  2648. contentAudioRecording = false
  2649. if (mapEngine) {
  2650. mapEngine.handleContentCardAudioRecorded()
  2651. }
  2652. })
  2653. }
  2654. const recorder = contentAudioRecorder
  2655. if (!contentAudioRecording) {
  2656. contentAudioRecording = true
  2657. recorder.start({
  2658. duration: 8000,
  2659. format: 'mp3',
  2660. } as any)
  2661. wx.showToast({
  2662. title: '开始录音',
  2663. icon: 'none',
  2664. duration: 800,
  2665. })
  2666. } else {
  2667. recorder.stop()
  2668. }
  2669. }
  2670. },
  2671. handleContentQuizAnswer(event: WechatMiniprogram.BaseEvent) {
  2672. if (!mapEngine) {
  2673. return
  2674. }
  2675. const optionKey = event.currentTarget.dataset.key
  2676. if (typeof optionKey === 'string') {
  2677. mapEngine.handleContentCardQuizAnswer(optionKey)
  2678. }
  2679. },
  2680. handleDismissTransientContentCard() {
  2681. if (mapEngine) {
  2682. mapEngine.closeContentCard()
  2683. }
  2684. },
  2685. handleContentCardTap() {
  2686. if (!mapEngine) {
  2687. return
  2688. }
  2689. if (!this.data.contentCardActions.length) {
  2690. mapEngine.closeContentCard()
  2691. }
  2692. },
  2693. openH5Experience(request: H5ExperienceRequest) {
  2694. wx.navigateTo({
  2695. url: '/pages/experience-webview/experience-webview',
  2696. success: (result) => {
  2697. const eventChannel = result.eventChannel
  2698. eventChannel.on('fallback', (payload: H5ExperienceFallbackPayload) => {
  2699. if (mapEngine) {
  2700. mapEngine.handleH5ExperienceFallback(payload)
  2701. }
  2702. })
  2703. eventChannel.on('close', () => {
  2704. if (mapEngine) {
  2705. mapEngine.handleH5ExperienceClosed()
  2706. }
  2707. })
  2708. eventChannel.on('submitResult', () => {
  2709. if (mapEngine) {
  2710. mapEngine.handleH5ExperienceClosed()
  2711. }
  2712. })
  2713. eventChannel.emit('init', request)
  2714. },
  2715. fail: () => {
  2716. if (mapEngine) {
  2717. mapEngine.handleH5ExperienceFallback(request.fallback)
  2718. }
  2719. },
  2720. })
  2721. },
  2722. handleCloseContentCard() {
  2723. if (mapEngine) {
  2724. mapEngine.closeContentCard()
  2725. }
  2726. },
  2727. handleClosePunchHint() {
  2728. clearPunchHintDismissTimer()
  2729. this.setData({
  2730. showPunchHintBanner: false,
  2731. })
  2732. },
  2733. handlePunchHintTap() {},
  2734. handleHudPanelChange(event: WechatMiniprogram.CustomEvent<{ current: number }>) {
  2735. this.setData({
  2736. hudPanelIndex: event.detail.current || 0,
  2737. })
  2738. },
  2739. handleCycleSideButtons() {
  2740. const nextMode = getNextSideButtonMode(this.data.sideButtonMode)
  2741. this.setData({
  2742. ...buildSideButtonVisibility(nextMode),
  2743. ...buildSideButtonState({
  2744. sideButtonMode: nextMode,
  2745. showGameInfoPanel: this.data.showGameInfoPanel,
  2746. showSystemSettingsPanel: this.data.showSystemSettingsPanel,
  2747. showCenterScaleRuler: this.data.showCenterScaleRuler,
  2748. centerScaleRulerAnchorMode: this.data.centerScaleRulerAnchorMode,
  2749. skipButtonEnabled: this.data.skipButtonEnabled,
  2750. gameSessionStatus: this.data.gameSessionStatus,
  2751. gpsLockEnabled: this.data.gpsLockEnabled,
  2752. gpsLockAvailable: this.data.gpsLockAvailable,
  2753. }),
  2754. })
  2755. },
  2756. handleToggleGpsLock() {
  2757. if (mapEngine) {
  2758. mapEngine.handleToggleGpsLock()
  2759. }
  2760. },
  2761. handleToggleMapRotateMode() {
  2762. if (!mapEngine || this.data.lockAutoRotate) {
  2763. return
  2764. }
  2765. if (this.data.orientationMode === 'heading-up') {
  2766. this.persistAndApplySystemSettings({
  2767. autoRotateEnabled: false,
  2768. })
  2769. return
  2770. }
  2771. this.persistAndApplySystemSettings({
  2772. autoRotateEnabled: true,
  2773. })
  2774. },
  2775. handleToggleDebugPanel() {
  2776. const nextShowDebugPanel = !this.data.showDebugPanel
  2777. if (!nextShowDebugPanel) {
  2778. clearGameInfoPanelSyncTimer()
  2779. }
  2780. if (mapEngine) {
  2781. mapEngine.setDiagnosticUiEnabled(nextShowDebugPanel)
  2782. }
  2783. this.setData({
  2784. showDebugPanel: nextShowDebugPanel,
  2785. showGameInfoPanel: false,
  2786. showSystemSettingsPanel: false,
  2787. ...buildSideButtonState({
  2788. sideButtonMode: this.data.sideButtonMode,
  2789. showGameInfoPanel: false,
  2790. showSystemSettingsPanel: false,
  2791. showCenterScaleRuler: this.data.showCenterScaleRuler,
  2792. centerScaleRulerAnchorMode: this.data.centerScaleRulerAnchorMode,
  2793. skipButtonEnabled: this.data.skipButtonEnabled,
  2794. gameSessionStatus: this.data.gameSessionStatus,
  2795. gpsLockEnabled: this.data.gpsLockEnabled,
  2796. gpsLockAvailable: this.data.gpsLockAvailable,
  2797. }),
  2798. })
  2799. },
  2800. handleCloseDebugPanel() {
  2801. if (mapEngine) {
  2802. mapEngine.setDiagnosticUiEnabled(false)
  2803. }
  2804. this.setData({
  2805. showDebugPanel: false,
  2806. ...buildSideButtonState({
  2807. sideButtonMode: this.data.sideButtonMode,
  2808. showGameInfoPanel: this.data.showGameInfoPanel,
  2809. showSystemSettingsPanel: this.data.showSystemSettingsPanel,
  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. applyCenterScaleRulerSettings(nextEnabled: boolean, nextAnchorMode: CenterScaleRulerAnchorMode) {
  2820. this.data.showCenterScaleRuler = nextEnabled
  2821. this.data.centerScaleRulerAnchorMode = nextAnchorMode
  2822. clearCenterScaleRulerSyncTimer()
  2823. clearCenterScaleRulerUpdateTimer()
  2824. const syncRulerFromEngine = () => {
  2825. if (!mapEngine) {
  2826. return
  2827. }
  2828. const engineSnapshot = mapEngine.getInitialData() as Partial<MapPageData>
  2829. updateCenterScaleRulerInputCache(engineSnapshot)
  2830. const mergedData = {
  2831. ...centerScaleRulerInputCache,
  2832. ...this.data,
  2833. showCenterScaleRuler: nextEnabled,
  2834. centerScaleRulerAnchorMode: nextAnchorMode,
  2835. } as MapPageData
  2836. this.setData({
  2837. ...filterDebugOnlyPatch(engineSnapshot, this.data.showDebugPanel, nextEnabled),
  2838. showCenterScaleRuler: nextEnabled,
  2839. centerScaleRulerAnchorMode: nextAnchorMode,
  2840. ...buildCenterScaleRulerPatch(mergedData),
  2841. ...buildSideButtonState(mergedData),
  2842. })
  2843. }
  2844. if (!nextEnabled) {
  2845. syncRulerFromEngine()
  2846. return
  2847. }
  2848. this.setData({
  2849. showCenterScaleRuler: true,
  2850. centerScaleRulerAnchorMode: nextAnchorMode,
  2851. ...buildSideButtonState({
  2852. ...this.data,
  2853. showCenterScaleRuler: true,
  2854. centerScaleRulerAnchorMode: nextAnchorMode,
  2855. } as MapPageData),
  2856. })
  2857. this.measureStageAndCanvas(() => {
  2858. syncRulerFromEngine()
  2859. })
  2860. centerScaleRulerSyncTimer = setTimeout(() => {
  2861. centerScaleRulerSyncTimer = 0
  2862. if (!this.data.showCenterScaleRuler) {
  2863. return
  2864. }
  2865. syncRulerFromEngine()
  2866. }, 96) as unknown as number
  2867. },
  2868. handleSetCenterScaleRulerVisibleOn() {
  2869. if (this.data.lockScaleRulerVisible) {
  2870. return
  2871. }
  2872. this.persistAndApplySystemSettings({
  2873. showCenterScaleRuler: true,
  2874. centerScaleRulerAnchorMode: this.data.centerScaleRulerAnchorMode,
  2875. }, {
  2876. applyCenterScaleRuler: true,
  2877. })
  2878. },
  2879. handleSetCenterScaleRulerVisibleOff() {
  2880. if (this.data.lockScaleRulerVisible) {
  2881. return
  2882. }
  2883. this.persistAndApplySystemSettings({
  2884. showCenterScaleRuler: false,
  2885. centerScaleRulerAnchorMode: this.data.centerScaleRulerAnchorMode,
  2886. }, {
  2887. applyCenterScaleRuler: true,
  2888. })
  2889. },
  2890. handleSetCenterScaleRulerAnchorScreenCenter() {
  2891. if (this.data.lockScaleRulerAnchor) {
  2892. return
  2893. }
  2894. this.persistAndApplySystemSettings({
  2895. showCenterScaleRuler: this.data.showCenterScaleRuler,
  2896. centerScaleRulerAnchorMode: 'screen-center',
  2897. }, {
  2898. applyCenterScaleRuler: true,
  2899. })
  2900. },
  2901. handleSetCenterScaleRulerAnchorCompassCenter() {
  2902. if (this.data.lockScaleRulerAnchor) {
  2903. return
  2904. }
  2905. this.persistAndApplySystemSettings({
  2906. showCenterScaleRuler: this.data.showCenterScaleRuler,
  2907. centerScaleRulerAnchorMode: 'compass-center',
  2908. }, {
  2909. applyCenterScaleRuler: true,
  2910. })
  2911. },
  2912. handleToggleCenterScaleRulerAnchor() {
  2913. if (!this.data.showCenterScaleRuler || this.data.lockScaleRulerAnchor) {
  2914. return
  2915. }
  2916. const nextAnchorMode: CenterScaleRulerAnchorMode = this.data.centerScaleRulerAnchorMode === 'screen-center'
  2917. ? 'compass-center'
  2918. : 'screen-center'
  2919. this.persistAndApplySystemSettings({
  2920. centerScaleRulerAnchorMode: nextAnchorMode,
  2921. showCenterScaleRuler: this.data.showCenterScaleRuler,
  2922. }, {
  2923. applyCenterScaleRuler: true,
  2924. })
  2925. },
  2926. handleDebugPanelTap() {},
  2927. })