| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116 |
- import { getTileSizePx, screenToWorld, worldToScreen, type CameraState } from '../camera/camera'
- import { CompassHeadingController } from '../sensor/compassHeadingController'
- import { type HeartRateDiscoveredDevice } from '../sensor/heartRateController'
- import { HeartRateInputController } from '../sensor/heartRateInputController'
- import { LocationController } from '../sensor/locationController'
- import { WebGLMapRenderer } from '../renderer/webglMapRenderer'
- import { type MapRendererStats } from '../renderer/mapRenderer'
- import { lonLatToWorldTile, worldTileToLonLat, type LonLatPoint, type MapCalibration } from '../../utils/projection'
- import { type OrienteeringCourseData } from '../../utils/orienteeringCourse'
- import { isTileWithinBounds, type RemoteMapConfig, type TileZoomBounds } from '../../utils/remoteMapConfig'
- import { GameRuntime } from '../../game/core/gameRuntime'
- import { type GameEffect, type GameResult } from '../../game/core/gameResult'
- import { buildGameDefinitionFromCourse } from '../../game/content/courseToGameDefinition'
- import { FeedbackDirector } from '../../game/feedback/feedbackDirector'
- import { EMPTY_GAME_PRESENTATION_STATE, type GamePresentationState } from '../../game/presentation/presentationState'
- import { TelemetryRuntime } from '../../game/telemetry/telemetryRuntime'
- import { getHeartRateToneSampleBpm, type HeartRateTone } from '../../game/telemetry/telemetryConfig'
- const RENDER_MODE = 'Single WebGL Pipeline'
- const PROJECTION_MODE = 'WGS84 -> WorldTile -> Camera -> Screen'
- const MAP_NORTH_OFFSET_DEG = 0
- let MAGNETIC_DECLINATION_DEG = -6.91
- let MAGNETIC_DECLINATION_TEXT = '6.91掳 W'
- const MIN_ZOOM = 15
- const MAX_ZOOM = 20
- const DEFAULT_ZOOM = 17
- const DESIRED_VISIBLE_COLUMNS = 3
- const OVERDRAW = 1
- const DEFAULT_TOP_LEFT_TILE_X = 108132
- const DEFAULT_TOP_LEFT_TILE_Y = 51199
- const DEFAULT_CENTER_TILE_X = DEFAULT_TOP_LEFT_TILE_X + 1
- const DEFAULT_CENTER_TILE_Y = DEFAULT_TOP_LEFT_TILE_Y + 1
- const TILE_SOURCE = 'https://oss-mbh5.colormaprun.com/wxMap/lcx/{z}/{x}/{y}.png'
- const OSM_TILE_SOURCE = 'https://tiles.mymarsgo.xyz/{z}/{x}/{y}.png'
- const MAP_OVERLAY_OPACITY = 0.72
- const GPS_MAP_CALIBRATION: MapCalibration = {
- offsetEastMeters: 0,
- offsetNorthMeters: 0,
- rotationDeg: 0,
- scale: 1,
- }
- const MIN_PREVIEW_SCALE = 0.55
- const MAX_PREVIEW_SCALE = 1.85
- const INERTIA_FRAME_MS = 16
- const INERTIA_DECAY = 0.92
- const INERTIA_MIN_SPEED = 0.02
- const PREVIEW_RESET_DURATION_MS = 140
- const UI_SYNC_INTERVAL_MS = 80
- const ROTATE_STEP_DEG = 15
- const AUTO_ROTATE_FRAME_MS = 8
- const AUTO_ROTATE_EASE = 0.34
- const AUTO_ROTATE_SNAP_DEG = 0.1
- const AUTO_ROTATE_DEADZONE_DEG = 4
- const AUTO_ROTATE_MAX_STEP_DEG = 0.75
- const AUTO_ROTATE_HEADING_SMOOTHING = 0.32
- const COMPASS_NEEDLE_SMOOTHING = 0.12
- const GPS_TRACK_MAX_POINTS = 200
- const GPS_TRACK_MIN_STEP_METERS = 3
- const MAP_TAP_MOVE_THRESHOLD_PX = 14
- const MAP_TAP_DURATION_MS = 280
- type TouchPoint = WechatMiniprogram.TouchDetail
- type GestureMode = 'idle' | 'pan' | 'pinch'
- type RotationMode = 'manual' | 'auto'
- type OrientationMode = 'manual' | 'north-up' | 'heading-up'
- type AutoRotateSourceMode = 'sensor' | 'course' | 'fusion'
- type NorthReferenceMode = 'magnetic' | 'true'
- const DEFAULT_NORTH_REFERENCE_MODE: NorthReferenceMode = 'magnetic'
- export interface MapEngineStageRect {
- width: number
- height: number
- left: number
- top: number
- }
- export interface MapEngineViewState {
- buildVersion: string
- renderMode: string
- projectionMode: string
- mapReady: boolean
- mapReadyText: string
- mapName: string
- configStatusText: string
- zoom: number
- rotationDeg: number
- rotationText: string
- rotationMode: RotationMode
- rotationModeText: string
- rotationToggleText: string
- orientationMode: OrientationMode
- orientationModeText: string
- sensorHeadingText: string
- compassDeclinationText: string
- northReferenceButtonText: string
- autoRotateSourceText: string
- autoRotateCalibrationText: string
- northReferenceText: string
- compassNeedleDeg: number
- centerTileX: number
- centerTileY: number
- centerText: string
- tileSource: string
- visibleColumnCount: number
- visibleTileCount: number
- readyTileCount: number
- memoryTileCount: number
- diskTileCount: number
- memoryHitCount: number
- diskHitCount: number
- networkFetchCount: number
- cacheHitRateText: string
- tileTranslateX: number
- tileTranslateY: number
- tileSizePx: number
- stageWidth: number
- stageHeight: number
- stageLeft: number
- stageTop: number
- statusText: string
- gpsTracking: boolean
- gpsTrackingText: string
- locationSourceMode: 'real' | 'mock'
- locationSourceText: string
- mockBridgeConnected: boolean
- mockBridgeStatusText: string
- mockBridgeUrlText: string
- mockCoordText: string
- mockSpeedText: string
- gpsCoordText: string
- heartRateSourceMode: 'real' | 'mock'
- heartRateSourceText: string
- heartRateConnected: boolean
- heartRateStatusText: string
- heartRateDeviceText: string
- heartRateScanText: string
- heartRateDiscoveredDevices: Array<{
- deviceId: string
- name: string
- rssiText: string
- preferred: boolean
- connected: boolean
- }>
- mockHeartRateBridgeConnected: boolean
- mockHeartRateBridgeStatusText: string
- mockHeartRateBridgeUrlText: string
- mockHeartRateText: string
- gameSessionStatus: 'idle' | 'running' | 'finished' | 'failed'
- gameModeText: string
- panelTimerText: string
- panelMileageText: string
- panelActionTagText: string
- panelDistanceTagText: string
- panelDistanceValueText: string
- panelDistanceUnitText: string
- panelProgressText: string
- panelSpeedValueText: string
- panelTelemetryTone: 'blue' | 'purple' | 'green' | 'yellow' | 'orange' | 'red'
- panelHeartRateZoneNameText: string
- panelHeartRateZoneRangeText: string
- panelHeartRateValueText: string
- panelHeartRateUnitText: string
- panelCaloriesValueText: string
- panelCaloriesUnitText: string
- panelAverageSpeedValueText: string
- panelAverageSpeedUnitText: string
- panelAccuracyValueText: string
- panelAccuracyUnitText: string
- punchButtonText: string
- punchButtonEnabled: boolean
- skipButtonEnabled: boolean
- punchHintText: string
- punchFeedbackVisible: boolean
- punchFeedbackText: string
- punchFeedbackTone: 'neutral' | 'success' | 'warning'
- contentCardVisible: boolean
- contentCardTitle: string
- contentCardBody: string
- punchButtonFxClass: string
- punchFeedbackFxClass: string
- contentCardFxClass: string
- mapPulseVisible: boolean
- mapPulseLeftPx: number
- mapPulseTopPx: number
- mapPulseFxClass: string
- stageFxVisible: boolean
- stageFxClass: string
- osmReferenceEnabled: boolean
- osmReferenceText: string
- }
- export interface MapEngineCallbacks {
- onData: (patch: Partial<MapEngineViewState>) => void
- }
- export interface MapEngineGameInfoRow {
- label: string
- value: string
- }
- export interface MapEngineGameInfoSnapshot {
- title: string
- subtitle: string
- localRows: MapEngineGameInfoRow[]
- globalRows: MapEngineGameInfoRow[]
- }
- const VIEW_SYNC_KEYS: Array<keyof MapEngineViewState> = [
- 'buildVersion',
- 'renderMode',
- 'projectionMode',
- 'mapReady',
- 'mapReadyText',
- 'mapName',
- 'configStatusText',
- 'zoom',
- 'rotationDeg',
- 'rotationText',
- 'rotationMode',
- 'rotationModeText',
- 'rotationToggleText',
- 'orientationMode',
- 'orientationModeText',
- 'sensorHeadingText',
- 'compassDeclinationText',
- 'northReferenceButtonText',
- 'autoRotateSourceText',
- 'autoRotateCalibrationText',
- 'northReferenceText',
- 'compassNeedleDeg',
- 'centerText',
- 'tileSource',
- 'visibleTileCount',
- 'readyTileCount',
- 'memoryTileCount',
- 'diskTileCount',
- 'memoryHitCount',
- 'diskHitCount',
- 'networkFetchCount',
- 'cacheHitRateText',
- 'tileSizePx',
- 'statusText',
- 'gpsTracking',
- 'gpsTrackingText',
- 'locationSourceMode',
- 'locationSourceText',
- 'mockBridgeConnected',
- 'mockBridgeStatusText',
- 'mockBridgeUrlText',
- 'mockCoordText',
- 'mockSpeedText',
- 'gpsCoordText',
- 'heartRateSourceMode',
- 'heartRateSourceText',
- 'heartRateConnected',
- 'heartRateStatusText',
- 'heartRateDeviceText',
- 'heartRateScanText',
- 'heartRateDiscoveredDevices',
- 'mockHeartRateBridgeConnected',
- 'mockHeartRateBridgeStatusText',
- 'mockHeartRateBridgeUrlText',
- 'mockHeartRateText',
- 'gameSessionStatus',
- 'gameModeText',
- 'panelTimerText',
- 'panelMileageText',
- 'panelActionTagText',
- 'panelDistanceTagText',
- 'panelDistanceValueText',
- 'panelDistanceUnitText',
- 'panelProgressText',
- 'panelSpeedValueText',
- 'panelTelemetryTone',
- 'panelHeartRateZoneNameText',
- 'panelHeartRateZoneRangeText',
- 'panelHeartRateValueText',
- 'panelHeartRateUnitText',
- 'panelCaloriesValueText',
- 'panelCaloriesUnitText',
- 'panelAverageSpeedValueText',
- 'panelAverageSpeedUnitText',
- 'panelAccuracyValueText',
- 'panelAccuracyUnitText',
- 'punchButtonText',
- 'punchButtonEnabled',
- 'skipButtonEnabled',
- 'punchHintText',
- 'punchFeedbackVisible',
- 'punchFeedbackText',
- 'punchFeedbackTone',
- 'contentCardVisible',
- 'contentCardTitle',
- 'contentCardBody',
- 'punchButtonFxClass',
- 'punchFeedbackFxClass',
- 'contentCardFxClass',
- 'mapPulseVisible',
- 'mapPulseLeftPx',
- 'mapPulseTopPx',
- 'mapPulseFxClass',
- 'stageFxVisible',
- 'stageFxClass',
- 'osmReferenceEnabled',
- 'osmReferenceText',
- ]
- function buildCenterText(zoom: number, x: number, y: number): string {
- return `z${zoom} / x${x} / y${y}`
- }
- function clamp(value: number, min: number, max: number): number {
- return Math.max(min, Math.min(max, value))
- }
- function normalizeRotationDeg(rotationDeg: number): number {
- const normalized = rotationDeg % 360
- return normalized < 0 ? normalized + 360 : normalized
- }
- function normalizeAngleDeltaRad(angleDeltaRad: number): number {
- let normalized = angleDeltaRad
- while (normalized > Math.PI) {
- normalized -= Math.PI * 2
- }
- while (normalized < -Math.PI) {
- normalized += Math.PI * 2
- }
- return normalized
- }
- function normalizeAngleDeltaDeg(angleDeltaDeg: number): number {
- let normalized = angleDeltaDeg
- while (normalized > 180) {
- normalized -= 360
- }
- while (normalized < -180) {
- normalized += 360
- }
- return normalized
- }
- function interpolateAngleDeg(currentDeg: number, targetDeg: number, factor: number): number {
- return normalizeRotationDeg(currentDeg + normalizeAngleDeltaDeg(targetDeg - currentDeg) * factor)
- }
- function formatGameSessionStatusText(status: 'idle' | 'running' | 'finished' | 'failed'): string {
- if (status === 'running') {
- return '进行中'
- }
- if (status === 'finished') {
- return '已结束'
- }
- if (status === 'failed') {
- return '已失败'
- }
- return '未开始'
- }
- function formatRotationText(rotationDeg: number): string {
- return `${Math.round(normalizeRotationDeg(rotationDeg))}deg`
- }
- function formatHeadingText(headingDeg: number | null): string {
- if (headingDeg === null) {
- return '--'
- }
- return `${Math.round(normalizeRotationDeg(headingDeg))}掳`
- }
- function formatOrientationModeText(mode: OrientationMode): string {
- if (mode === 'north-up') {
- return 'North Up'
- }
- if (mode === 'heading-up') {
- return 'Heading Up'
- }
- return 'Manual Gesture'
- }
- function formatRotationModeText(mode: OrientationMode): string {
- return formatOrientationModeText(mode)
- }
- function formatRotationToggleText(mode: OrientationMode): string {
- if (mode === 'manual') {
- return '切到北朝上'
- }
- if (mode === 'north-up') {
- return '切到朝向朝上'
- }
- return '切到手动旋转'
- }
- function formatAutoRotateSourceText(mode: AutoRotateSourceMode, hasCourseHeading: boolean): string {
- if (mode === 'sensor') {
- return 'Sensor Only'
- }
- if (mode === 'course') {
- return hasCourseHeading ? 'Course Only' : 'Course Pending'
- }
- return hasCourseHeading ? 'Sensor + Course' : 'Sensor Only'
- }
- function formatAutoRotateCalibrationText(pending: boolean, offsetDeg: number | null): string {
- if (pending) {
- return 'Pending'
- }
- if (offsetDeg === null) {
- return '--'
- }
- return `Offset ${Math.round(normalizeRotationDeg(offsetDeg))}deg`
- }
- function getTrueHeadingDeg(magneticHeadingDeg: number): number {
- return normalizeRotationDeg(magneticHeadingDeg + MAGNETIC_DECLINATION_DEG)
- }
- function getMagneticHeadingDeg(trueHeadingDeg: number): number {
- return normalizeRotationDeg(trueHeadingDeg - MAGNETIC_DECLINATION_DEG)
- }
- function getMapNorthOffsetDeg(_mode: NorthReferenceMode): number {
- return MAP_NORTH_OFFSET_DEG
- }
- function getCompassReferenceHeadingDeg(mode: NorthReferenceMode, magneticHeadingDeg: number): number {
- if (mode === 'true') {
- return getTrueHeadingDeg(magneticHeadingDeg)
- }
- return normalizeRotationDeg(magneticHeadingDeg)
- }
- function getMapReferenceHeadingDegFromSensor(mode: NorthReferenceMode, magneticHeadingDeg: number): number {
- if (mode === 'magnetic') {
- return normalizeRotationDeg(magneticHeadingDeg)
- }
- return getTrueHeadingDeg(magneticHeadingDeg)
- }
- function getMapReferenceHeadingDegFromCourse(mode: NorthReferenceMode, trueHeadingDeg: number): number {
- if (mode === 'magnetic') {
- return getMagneticHeadingDeg(trueHeadingDeg)
- }
- return normalizeRotationDeg(trueHeadingDeg)
- }
- function formatNorthReferenceText(mode: NorthReferenceMode): string {
- if (mode === 'magnetic') {
- return `Compass Magnetic / Heading-Up Magnetic (${MAGNETIC_DECLINATION_TEXT})`
- }
- return `Compass True / Heading-Up True (${MAGNETIC_DECLINATION_TEXT})`
- }
- function formatCompassDeclinationText(mode: NorthReferenceMode): string {
- if (mode === 'true') {
- return MAGNETIC_DECLINATION_TEXT
- }
- return ''
- }
- function formatNorthReferenceButtonText(mode: NorthReferenceMode): string {
- return mode === 'magnetic' ? '北参照:磁北' : '北参照:真北'
- }
- function formatNorthReferenceStatusText(mode: NorthReferenceMode): string {
- if (mode === 'magnetic') {
- return '已切到磁北模式'
- }
- return '已切到真北模式'
- }
- function getNextNorthReferenceMode(mode: NorthReferenceMode): NorthReferenceMode {
- return mode === 'magnetic' ? 'true' : 'magnetic'
- }
- function formatCompassNeedleDegForMode(mode: NorthReferenceMode, magneticHeadingDeg: number | null): number {
- if (magneticHeadingDeg === null) {
- return 0
- }
- const referenceHeadingDeg = mode === 'true'
- ? getTrueHeadingDeg(magneticHeadingDeg)
- : normalizeRotationDeg(magneticHeadingDeg)
- return normalizeRotationDeg(360 - referenceHeadingDeg)
- }
- function formatCacheHitRate(memoryHitCount: number, diskHitCount: number, networkFetchCount: number): string {
- const total = memoryHitCount + diskHitCount + networkFetchCount
- if (!total) {
- return '--'
- }
- const hitRate = ((memoryHitCount + diskHitCount) / total) * 100
- return `${Math.round(hitRate)}%`
- }
- function formatGpsCoordText(point: LonLatPoint | null, accuracyMeters: number | null): string {
- if (!point) {
- return '--'
- }
- const base = `${point.lat.toFixed(6)}, ${point.lon.toFixed(6)}`
- if (accuracyMeters === null || !Number.isFinite(accuracyMeters)) {
- return base
- }
- return `${base} / 卤${Math.round(accuracyMeters)}m`
- }
- function getApproxDistanceMeters(a: LonLatPoint, b: LonLatPoint): number {
- const avgLatRad = ((a.lat + b.lat) / 2) * Math.PI / 180
- const dx = (b.lon - a.lon) * 111320 * Math.cos(avgLatRad)
- const dy = (b.lat - a.lat) * 110540
- return Math.sqrt(dx * dx + dy * dy)
- }
- function getInitialBearingDeg(from: LonLatPoint, to: LonLatPoint): number {
- const fromLatRad = from.lat * Math.PI / 180
- const toLatRad = to.lat * Math.PI / 180
- const deltaLonRad = (to.lon - from.lon) * Math.PI / 180
- const y = Math.sin(deltaLonRad) * Math.cos(toLatRad)
- const x = Math.cos(fromLatRad) * Math.sin(toLatRad) - Math.sin(fromLatRad) * Math.cos(toLatRad) * Math.cos(deltaLonRad)
- const bearingDeg = Math.atan2(y, x) * 180 / Math.PI
- return normalizeRotationDeg(bearingDeg)
- }
- export class MapEngine {
- buildVersion: string
- renderer: WebGLMapRenderer
- compassController: CompassHeadingController
- locationController: LocationController
- heartRateController: HeartRateInputController
- feedbackDirector: FeedbackDirector
- onData: (patch: Partial<MapEngineViewState>) => void
- state: MapEngineViewState
- previewScale: number
- previewOriginX: number
- previewOriginY: number
- panLastX: number
- panLastY: number
- panLastTimestamp: number
- tapStartX: number
- tapStartY: number
- tapStartAt: number
- panVelocityX: number
- panVelocityY: number
- pinchStartDistance: number
- pinchStartScale: number
- pinchStartAngle: number
- pinchStartRotationDeg: number
- pinchAnchorWorldX: number
- pinchAnchorWorldY: number
- gestureMode: GestureMode
- inertiaTimer: number
- previewResetTimer: number
- viewSyncTimer: number
- autoRotateTimer: number
- pendingViewPatch: Partial<MapEngineViewState>
- mounted: boolean
- northReferenceMode: NorthReferenceMode
- sensorHeadingDeg: number | null
- smoothedSensorHeadingDeg: number | null
- compassDisplayHeadingDeg: number | null
- autoRotateHeadingDeg: number | null
- courseHeadingDeg: number | null
- targetAutoRotationDeg: number | null
- autoRotateSourceMode: AutoRotateSourceMode
- autoRotateCalibrationOffsetDeg: number | null
- autoRotateCalibrationPending: boolean
- minZoom: number
- maxZoom: number
- defaultZoom: number
- defaultCenterTileX: number
- defaultCenterTileY: number
- tileBoundsByZoom: Record<number, TileZoomBounds> | null
- currentGpsPoint: LonLatPoint | null
- currentGpsTrack: LonLatPoint[]
- currentGpsAccuracyMeters: number | null
- courseData: OrienteeringCourseData | null
- courseOverlayVisible: boolean
- cpRadiusMeters: number
- configAppId: string
- configSchemaVersion: string
- configVersion: string
- controlScoreOverrides: Record<string, number>
- defaultControlScore: number | null
- gameRuntime: GameRuntime
- telemetryRuntime: TelemetryRuntime
- gamePresentation: GamePresentationState
- gameMode: 'classic-sequential' | 'score-o'
- punchPolicy: 'enter' | 'enter-confirm'
- punchRadiusMeters: number
- requiresFocusSelection: boolean
- skipEnabled: boolean
- skipRadiusMeters: number
- skipRequiresConfirm: boolean
- autoFinishOnLastControl: boolean
- punchFeedbackTimer: number
- contentCardTimer: number
- mapPulseTimer: number
- stageFxTimer: number
- sessionTimerInterval: number
- hasGpsCenteredOnce: boolean
- constructor(buildVersion: string, callbacks: MapEngineCallbacks) {
- this.buildVersion = buildVersion
- this.onData = callbacks.onData
- this.renderer = new WebGLMapRenderer(
- (stats) => {
- this.applyStats(stats)
- },
- (message) => {
- this.setState({
- statusText: `${message} (${this.buildVersion})`,
- })
- },
- )
- this.compassController = new CompassHeadingController({
- onHeading: (headingDeg) => {
- this.handleCompassHeading(headingDeg)
- },
- onError: (message) => {
- this.handleCompassError(message)
- },
- })
- this.locationController = new LocationController({
- onLocation: (update) => {
- this.handleLocationUpdate(update.longitude, update.latitude, typeof update.accuracy === 'number' ? update.accuracy : null)
- },
- onStatus: (message) => {
- this.setState({
- gpsTracking: this.locationController.listening,
- gpsTrackingText: message,
- ...this.getLocationControllerViewPatch(),
- }, true)
- },
- onError: (message) => {
- this.setState({
- gpsTracking: this.locationController.listening,
- gpsTrackingText: message,
- ...this.getLocationControllerViewPatch(),
- statusText: `${message} (${this.buildVersion})`,
- }, true)
- },
- onDebugStateChange: () => {
- this.setState(this.getLocationControllerViewPatch(), true)
- },
- })
- this.heartRateController = new HeartRateInputController({
- onHeartRate: (bpm) => {
- this.telemetryRuntime.dispatch({
- type: 'heart_rate_updated',
- at: Date.now(),
- bpm,
- })
- this.syncSessionTimerText()
- },
- onStatus: (message) => {
- const deviceName = this.heartRateController.currentDeviceName
- || (this.heartRateController.reconnecting ? this.heartRateController.lastDeviceName : null)
- || '--'
- this.setState({
- heartRateStatusText: message,
- heartRateDeviceText: deviceName,
- heartRateScanText: this.getHeartRateScanText(),
- ...this.getHeartRateControllerViewPatch(),
- }, true)
- },
- onError: (message) => {
- this.clearHeartRateSignal()
- const deviceName = this.heartRateController.reconnecting
- ? (this.heartRateController.lastDeviceName || '--')
- : '--'
- this.setState({
- heartRateConnected: false,
- heartRateStatusText: message,
- heartRateDeviceText: deviceName,
- heartRateScanText: this.getHeartRateScanText(),
- ...this.getHeartRateControllerViewPatch(),
- statusText: `${message} (${this.buildVersion})`,
- }, true)
- },
- onConnectionChange: (connected, deviceName) => {
- if (!connected) {
- this.clearHeartRateSignal()
- }
- const resolvedDeviceName = connected
- ? (deviceName || '--')
- : (this.heartRateController.reconnecting
- ? (this.heartRateController.lastDeviceName || '--')
- : '--')
- this.setState({
- heartRateConnected: connected,
- heartRateDeviceText: resolvedDeviceName,
- heartRateStatusText: connected
- ? (this.heartRateController.sourceMode === 'mock' ? '模拟心率源已连接' : '心率带已连接')
- : (this.heartRateController.reconnecting ? '心率带自动重连中' : (this.heartRateController.sourceMode === 'mock' ? '模拟心率源未连接' : '心率带未连接')),
- heartRateScanText: this.getHeartRateScanText(),
- heartRateDiscoveredDevices: this.formatHeartRateDevices(this.heartRateController.discoveredDevices),
- ...this.getHeartRateControllerViewPatch(),
- }, true)
- },
- onDeviceListChange: (devices) => {
- this.setState({
- heartRateDiscoveredDevices: this.formatHeartRateDevices(devices),
- heartRateScanText: this.getHeartRateScanText(),
- ...this.getHeartRateControllerViewPatch(),
- }, true)
- },
- onDebugStateChange: () => {
- this.setState(this.getHeartRateControllerViewPatch(), true)
- },
- })
- this.feedbackDirector = new FeedbackDirector({
- showPunchFeedback: (text, tone, motionClass) => {
- this.showPunchFeedback(text, tone, motionClass)
- },
- showContentCard: (title, body, motionClass) => {
- this.showContentCard(title, body, motionClass)
- },
- setPunchButtonFxClass: (className) => {
- this.setPunchButtonFxClass(className)
- },
- showMapPulse: (controlId, motionClass) => {
- this.showMapPulse(controlId, motionClass)
- },
- showStageFx: (className) => {
- this.showStageFx(className)
- },
- stopLocationTracking: () => {
- if (this.locationController.listening) {
- this.locationController.stop()
- }
- },
- })
- this.minZoom = MIN_ZOOM
- this.maxZoom = MAX_ZOOM
- this.defaultZoom = DEFAULT_ZOOM
- this.defaultCenterTileX = DEFAULT_CENTER_TILE_X
- this.defaultCenterTileY = DEFAULT_CENTER_TILE_Y
- this.tileBoundsByZoom = null
- this.currentGpsPoint = null
- this.currentGpsTrack = []
- this.currentGpsAccuracyMeters = null
- this.courseData = null
- this.courseOverlayVisible = false
- this.cpRadiusMeters = 5
- this.configAppId = ''
- this.configSchemaVersion = '1'
- this.configVersion = ''
- this.controlScoreOverrides = {}
- this.defaultControlScore = null
- this.gameRuntime = new GameRuntime()
- this.telemetryRuntime = new TelemetryRuntime()
- this.telemetryRuntime.configure()
- this.gamePresentation = EMPTY_GAME_PRESENTATION_STATE
- this.gameMode = 'classic-sequential'
- this.punchPolicy = 'enter-confirm'
- this.punchRadiusMeters = 5
- this.requiresFocusSelection = false
- this.skipEnabled = false
- this.skipRadiusMeters = 30
- this.skipRequiresConfirm = true
- this.autoFinishOnLastControl = true
- this.punchFeedbackTimer = 0
- this.contentCardTimer = 0
- this.mapPulseTimer = 0
- this.stageFxTimer = 0
- this.sessionTimerInterval = 0
- this.hasGpsCenteredOnce = false
- this.state = {
- buildVersion: this.buildVersion,
- renderMode: RENDER_MODE,
- projectionMode: PROJECTION_MODE,
- mapReady: false,
- mapReadyText: 'BOOTING',
- mapName: '未命名配置',
- configStatusText: '远程配置待加载',
- zoom: DEFAULT_ZOOM,
- rotationDeg: 0,
- rotationText: formatRotationText(0),
- rotationMode: 'manual',
- rotationModeText: formatRotationModeText('manual'),
- rotationToggleText: formatRotationToggleText('manual'),
- orientationMode: 'manual',
- orientationModeText: formatOrientationModeText('manual'),
- sensorHeadingText: '--',
- compassDeclinationText: formatCompassDeclinationText(DEFAULT_NORTH_REFERENCE_MODE),
- northReferenceButtonText: formatNorthReferenceButtonText(DEFAULT_NORTH_REFERENCE_MODE),
- autoRotateSourceText: formatAutoRotateSourceText('sensor', false),
- autoRotateCalibrationText: formatAutoRotateCalibrationText(false, getMapNorthOffsetDeg(DEFAULT_NORTH_REFERENCE_MODE)),
- northReferenceText: formatNorthReferenceText(DEFAULT_NORTH_REFERENCE_MODE),
- compassNeedleDeg: 0,
- centerTileX: DEFAULT_CENTER_TILE_X,
- centerTileY: DEFAULT_CENTER_TILE_Y,
- centerText: buildCenterText(DEFAULT_ZOOM, DEFAULT_CENTER_TILE_X, DEFAULT_CENTER_TILE_Y),
- tileSource: TILE_SOURCE,
- visibleColumnCount: DESIRED_VISIBLE_COLUMNS,
- visibleTileCount: 0,
- readyTileCount: 0,
- memoryTileCount: 0,
- diskTileCount: 0,
- memoryHitCount: 0,
- diskHitCount: 0,
- networkFetchCount: 0,
- cacheHitRateText: '--',
- tileTranslateX: 0,
- tileTranslateY: 0,
- tileSizePx: 0,
- stageWidth: 0,
- stageHeight: 0,
- stageLeft: 0,
- stageTop: 0,
- statusText: `单 WebGL 管线已就绪,等待传感器接入 (${this.buildVersion})`,
- gpsTracking: false,
- gpsTrackingText: '持续定位待启动',
- locationSourceMode: 'real',
- locationSourceText: '真实定位',
- mockBridgeConnected: false,
- mockBridgeStatusText: '未连接',
- mockBridgeUrlText: 'wss://gs.gotomars.xyz/mock-gps',
- mockCoordText: '--',
- mockSpeedText: '--',
- gpsCoordText: '--',
- heartRateSourceMode: 'real',
- heartRateSourceText: '真实心率',
- heartRateConnected: false,
- heartRateStatusText: '心率带未连接',
- heartRateDeviceText: '--',
- heartRateScanText: '未扫描',
- heartRateDiscoveredDevices: [],
- mockHeartRateBridgeConnected: false,
- mockHeartRateBridgeStatusText: '未连接',
- mockHeartRateBridgeUrlText: 'wss://gs.gotomars.xyz/mock-gps',
- mockHeartRateText: '--',
- panelTimerText: '00:00:00',
- panelMileageText: '0m',
- panelActionTagText: '目标',
- panelDistanceTagText: '点距',
- panelDistanceValueText: '--',
- panelDistanceUnitText: '',
- panelProgressText: '0/0',
- panelSpeedValueText: '0',
- panelTelemetryTone: 'blue',
- panelHeartRateZoneNameText: '激活放松',
- panelHeartRateZoneRangeText: '<=39%',
- panelHeartRateValueText: '--',
- panelHeartRateUnitText: '',
- panelCaloriesValueText: '0',
- panelCaloriesUnitText: 'kcal',
- panelAverageSpeedValueText: '0',
- panelAverageSpeedUnitText: 'km/h',
- panelAccuracyValueText: '--',
- panelAccuracyUnitText: '',
- punchButtonText: '打点',
- gameSessionStatus: 'idle',
- gameModeText: '顺序赛',
- punchButtonEnabled: false,
- skipButtonEnabled: false,
- punchHintText: '等待进入检查点范围',
- punchFeedbackVisible: false,
- punchFeedbackText: '',
- punchFeedbackTone: 'neutral',
- contentCardVisible: false,
- contentCardTitle: '',
- contentCardBody: '',
- punchButtonFxClass: '',
- punchFeedbackFxClass: '',
- contentCardFxClass: '',
- mapPulseVisible: false,
- mapPulseLeftPx: 0,
- mapPulseTopPx: 0,
- mapPulseFxClass: '',
- stageFxVisible: false,
- stageFxClass: '',
- osmReferenceEnabled: false,
- osmReferenceText: 'OSM参考:关',
- }
- this.previewScale = 1
- this.previewOriginX = 0
- this.previewOriginY = 0
- this.panLastX = 0
- this.panLastY = 0
- this.panLastTimestamp = 0
- this.tapStartX = 0
- this.tapStartY = 0
- this.tapStartAt = 0
- this.panVelocityX = 0
- this.panVelocityY = 0
- this.pinchStartDistance = 0
- this.pinchStartScale = 1
- this.pinchStartAngle = 0
- this.pinchStartRotationDeg = 0
- this.pinchAnchorWorldX = 0
- this.pinchAnchorWorldY = 0
- this.gestureMode = 'idle'
- this.inertiaTimer = 0
- this.previewResetTimer = 0
- this.viewSyncTimer = 0
- this.autoRotateTimer = 0
- this.pendingViewPatch = {}
- this.mounted = false
- this.northReferenceMode = DEFAULT_NORTH_REFERENCE_MODE
- this.sensorHeadingDeg = null
- this.smoothedSensorHeadingDeg = null
- this.compassDisplayHeadingDeg = null
- this.autoRotateHeadingDeg = null
- this.courseHeadingDeg = null
- this.targetAutoRotationDeg = null
- this.autoRotateSourceMode = 'sensor'
- this.autoRotateCalibrationOffsetDeg = getMapNorthOffsetDeg(DEFAULT_NORTH_REFERENCE_MODE)
- this.autoRotateCalibrationPending = false
- }
- getInitialData(): MapEngineViewState {
- return { ...this.state }
- }
- getGameInfoSnapshot(): MapEngineGameInfoSnapshot {
- const definition = this.gameRuntime.definition
- const sessionState = this.gameRuntime.state
- const telemetryState = this.telemetryRuntime.state
- const telemetryPresentation = this.telemetryRuntime.getPresentation()
- const currentTarget = definition && sessionState
- ? definition.controls.find((control) => control.id === sessionState.currentTargetControlId) || null
- : null
- const currentTargetText = currentTarget
- ? `${currentTarget.label} / ${currentTarget.kind === 'start'
- ? '开始点'
- : currentTarget.kind === 'finish'
- ? '结束点'
- : '检查点'}`
- : '--'
- const title = this.state.mapName || (definition ? definition.title : '当前游戏')
- const subtitle = `${this.getGameModeText()} / ${formatGameSessionStatusText(this.state.gameSessionStatus)}`
- const localRows: MapEngineGameInfoRow[] = [
- { label: '比赛名称', value: title || '--' },
- { label: '配置版本', value: this.configVersion || '--' },
- { label: 'Schema版本', value: this.configSchemaVersion || '--' },
- { label: '活动ID', value: this.configAppId || '--' },
- { label: '地图', value: this.state.mapName || '--' },
- { label: '模式', value: this.getGameModeText() },
- { label: '状态', value: formatGameSessionStatusText(this.state.gameSessionStatus) },
- { label: '当前目标', value: currentTargetText },
- { label: '进度', value: this.gamePresentation.hud.progressText || '--' },
- { label: '当前积分', value: sessionState ? String(sessionState.score) : '0' },
- { label: '已完成点', value: sessionState ? String(sessionState.completedControlIds.length) : '0' },
- { label: '已跳过点', value: sessionState ? String(sessionState.skippedControlIds.length) : '0' },
- { label: '打点规则', value: `${this.punchPolicy} / ${this.punchRadiusMeters}m` },
- { label: '跳点规则', value: this.skipEnabled ? `${this.skipRadiusMeters}m / ${this.skipRequiresConfirm ? '确认跳过' : '直接跳过'}` : '关闭' },
- { label: '定位源', value: this.state.locationSourceText || '--' },
- { label: '当前位置', value: this.state.gpsCoordText || '--' },
- { label: 'GPS精度', value: telemetryState.lastGpsAccuracyMeters == null ? '--' : `${telemetryState.lastGpsAccuracyMeters.toFixed(1)}m` },
- { label: '目标距离', value: `${telemetryPresentation.distanceToTargetValueText}${telemetryPresentation.distanceToTargetUnitText}` || '--' },
- { label: '当前速度', value: `${telemetryPresentation.speedText} km/h` },
- { label: '心率源', value: this.state.heartRateSourceText || '--' },
- { label: '当前心率', value: this.state.panelHeartRateValueText === '--' ? '--' : `${this.state.panelHeartRateValueText}${this.state.panelHeartRateUnitText}` },
- { label: '心率设备', value: this.state.heartRateDeviceText || '--' },
- { label: '心率分区', value: this.state.panelHeartRateZoneNameText === '--' ? '--' : `${this.state.panelHeartRateZoneNameText} ${this.state.panelHeartRateZoneRangeText}` },
- { label: '本局用时', value: telemetryPresentation.timerText },
- { label: '累计里程', value: telemetryPresentation.mileageText },
- { label: '累计消耗', value: `${telemetryPresentation.caloriesValueText}${telemetryPresentation.caloriesUnitText}` },
- { label: '提示状态', value: this.state.punchHintText || '--' },
- ]
- const globalRows: MapEngineGameInfoRow[] = [
- { label: '全球积分', value: '未接入' },
- { label: '全球排名', value: '未接入' },
- { label: '在线人数', value: '未接入' },
- { label: '队伍状态', value: '未接入' },
- { label: '实时广播', value: '未接入' },
- ]
- return {
- title,
- subtitle,
- localRows,
- globalRows,
- }
- }
- destroy(): void {
- this.clearInertiaTimer()
- this.clearPreviewResetTimer()
- this.clearViewSyncTimer()
- this.clearAutoRotateTimer()
- this.clearPunchFeedbackTimer()
- this.clearContentCardTimer()
- this.clearMapPulseTimer()
- this.clearStageFxTimer()
- this.clearSessionTimerInterval()
- this.compassController.destroy()
- this.locationController.destroy()
- this.heartRateController.destroy()
- this.feedbackDirector.destroy()
- this.renderer.destroy()
- this.mounted = false
- }
- handleAppShow(): void {
- this.feedbackDirector.setAppAudioMode('foreground')
- }
- handleAppHide(): void {
- this.feedbackDirector.setAppAudioMode('foreground')
- }
- clearGameRuntime(): void {
- this.gameRuntime.clear()
- this.telemetryRuntime.reset()
- this.gamePresentation = EMPTY_GAME_PRESENTATION_STATE
- this.courseOverlayVisible = !!this.courseData
- this.clearSessionTimerInterval()
- this.setCourseHeading(null)
- }
- clearHeartRateSignal(): void {
- this.telemetryRuntime.dispatch({
- type: 'heart_rate_updated',
- at: Date.now(),
- bpm: null,
- })
- this.syncSessionTimerText()
- }
- clearFinishedTestOverlay(): void {
- this.currentGpsPoint = null
- this.currentGpsTrack = []
- this.currentGpsAccuracyMeters = null
- this.courseOverlayVisible = false
- this.setCourseHeading(null)
- }
- clearStartSessionResidue(): void {
- this.currentGpsTrack = []
- this.courseOverlayVisible = false
- this.setCourseHeading(null)
- }
- handleClearMapTestArtifacts(): void {
- this.clearFinishedTestOverlay()
- this.setState({
- gpsTracking: false,
- gpsTrackingText: '测试痕迹已清空',
- gpsCoordText: '--',
- statusText: `已清空地图点位与轨迹 (${this.buildVersion})`,
- }, true)
- this.syncRenderer()
- }
- getHudTargetControlId(): string | null {
- return this.gamePresentation.hud.hudTargetControlId
- }
- isSkipAvailable(): boolean {
- const definition = this.gameRuntime.definition
- const state = this.gameRuntime.state
- if (!definition || !state || state.status !== 'running' || !definition.skipEnabled) {
- return false
- }
- const currentTarget = definition.controls.find((control) => control.id === state.currentTargetControlId) || null
- if (!currentTarget || currentTarget.kind !== 'control' || !this.currentGpsPoint) {
- return false
- }
- const avgLatRad = ((currentTarget.point.lat + this.currentGpsPoint.lat) / 2) * Math.PI / 180
- const dx = (this.currentGpsPoint.lon - currentTarget.point.lon) * 111320 * Math.cos(avgLatRad)
- const dy = (this.currentGpsPoint.lat - currentTarget.point.lat) * 110540
- const distanceMeters = Math.sqrt(dx * dx + dy * dy)
- return distanceMeters <= definition.skipRadiusMeters
- }
- shouldConfirmSkipAction(): boolean {
- return !!(this.gameRuntime.definition && this.gameRuntime.definition.skipRequiresConfirm)
- }
- getLocationControllerViewPatch(): Partial<MapEngineViewState> {
- const debugState = this.locationController.getDebugState()
- return {
- gpsTracking: debugState.listening,
- locationSourceMode: debugState.sourceMode,
- locationSourceText: debugState.sourceModeText,
- mockBridgeConnected: debugState.mockBridgeConnected,
- mockBridgeStatusText: debugState.mockBridgeStatusText,
- mockBridgeUrlText: debugState.mockBridgeUrlText,
- mockCoordText: debugState.mockCoordText,
- mockSpeedText: debugState.mockSpeedText,
- }
- }
- getHeartRateControllerViewPatch(): Partial<MapEngineViewState> {
- const debugState = this.heartRateController.getDebugState()
- return {
- heartRateSourceMode: debugState.sourceMode,
- heartRateSourceText: debugState.sourceModeText,
- mockHeartRateBridgeConnected: debugState.mockBridgeConnected,
- mockHeartRateBridgeStatusText: debugState.mockBridgeStatusText,
- mockHeartRateBridgeUrlText: debugState.mockBridgeUrlText,
- mockHeartRateText: debugState.mockHeartRateText,
- }
- }
- getGameModeText(): string {
- return this.gameMode === 'score-o' ? '积分赛' : '顺序赛'
- }
- loadGameDefinitionFromCourse(): GameResult | null {
- if (!this.courseData) {
- this.clearGameRuntime()
- return null
- }
- const definition = buildGameDefinitionFromCourse(
- this.courseData,
- this.cpRadiusMeters,
- this.gameMode,
- this.autoFinishOnLastControl,
- this.punchPolicy,
- this.punchRadiusMeters,
- this.requiresFocusSelection,
- this.skipEnabled,
- this.skipRadiusMeters,
- this.skipRequiresConfirm,
- this.controlScoreOverrides,
- this.defaultControlScore,
- )
- const result = this.gameRuntime.loadDefinition(definition)
- this.telemetryRuntime.loadDefinition(definition)
- this.courseOverlayVisible = true
- this.syncGameResultState(result)
- this.telemetryRuntime.syncGameState(this.gameRuntime.definition, result.nextState, result.presentation.hud.hudTargetControlId)
- this.updateSessionTimerLoop()
- return result
- }
- refreshCourseHeadingFromPresentation(): void {
- if (!this.courseData || !this.gamePresentation.map.activeLegIndices.length) {
- this.setCourseHeading(null)
- return
- }
- const activeLegIndex = this.gamePresentation.map.activeLegIndices[0]
- const activeLeg = this.courseData.layers.legs[activeLegIndex]
- if (!activeLeg) {
- this.setCourseHeading(null)
- return
- }
- this.setCourseHeading(getInitialBearingDeg(activeLeg.fromPoint, activeLeg.toPoint))
- }
- resolveGameStatusText(effects: GameEffect[]): string | null {
- const lastEffect = effects.length ? effects[effects.length - 1] : null
- if (!lastEffect) {
- return null
- }
- if (lastEffect.type === 'control_completed') {
- const sequenceText = typeof lastEffect.sequence === 'number' ? String(lastEffect.sequence) : lastEffect.controlId
- return `宸插畬鎴愭鏌ョ偣 ${sequenceText} (${this.buildVersion})`
- }
- if (lastEffect.type === 'session_finished') {
- return `璺嚎宸插畬鎴?(${this.buildVersion})`
- }
- if (lastEffect.type === 'session_started') {
- return `椤哄簭鎵撶偣宸插紑濮?(${this.buildVersion})`
- }
- return null
- }
- getGameViewPatch(statusText?: string | null): Partial<MapEngineViewState> {
- const telemetryPresentation = this.telemetryRuntime.getPresentation()
- const patch: Partial<MapEngineViewState> = {
- gameSessionStatus: this.gameRuntime.state ? this.gameRuntime.state.status : 'idle',
- gameModeText: this.getGameModeText(),
- panelTimerText: telemetryPresentation.timerText,
- panelMileageText: telemetryPresentation.mileageText,
- panelActionTagText: this.gamePresentation.hud.actionTagText,
- panelDistanceTagText: this.gamePresentation.hud.distanceTagText,
- panelDistanceValueText: telemetryPresentation.distanceToTargetValueText,
- panelDistanceUnitText: telemetryPresentation.distanceToTargetUnitText,
- panelSpeedValueText: telemetryPresentation.speedText,
- panelTelemetryTone: telemetryPresentation.heartRateTone,
- panelHeartRateZoneNameText: telemetryPresentation.heartRateZoneNameText,
- panelHeartRateZoneRangeText: telemetryPresentation.heartRateZoneRangeText,
- panelHeartRateValueText: telemetryPresentation.heartRateValueText,
- panelHeartRateUnitText: telemetryPresentation.heartRateUnitText,
- panelCaloriesValueText: telemetryPresentation.caloriesValueText,
- panelCaloriesUnitText: telemetryPresentation.caloriesUnitText,
- panelAverageSpeedValueText: telemetryPresentation.averageSpeedValueText,
- panelAverageSpeedUnitText: telemetryPresentation.averageSpeedUnitText,
- panelAccuracyValueText: telemetryPresentation.accuracyValueText,
- panelAccuracyUnitText: telemetryPresentation.accuracyUnitText,
- panelProgressText: this.gamePresentation.hud.progressText,
- punchButtonText: this.gamePresentation.hud.punchButtonText,
- punchButtonEnabled: this.gamePresentation.hud.punchButtonEnabled,
- skipButtonEnabled: this.isSkipAvailable(),
- punchHintText: this.gamePresentation.hud.punchHintText,
- }
- if (statusText) {
- patch.statusText = statusText
- }
- return patch
- }
- clearPunchFeedbackTimer(): void {
- if (this.punchFeedbackTimer) {
- clearTimeout(this.punchFeedbackTimer)
- this.punchFeedbackTimer = 0
- }
- }
- clearContentCardTimer(): void {
- if (this.contentCardTimer) {
- clearTimeout(this.contentCardTimer)
- this.contentCardTimer = 0
- }
- }
- clearMapPulseTimer(): void {
- if (this.mapPulseTimer) {
- clearTimeout(this.mapPulseTimer)
- this.mapPulseTimer = 0
- }
- }
- clearStageFxTimer(): void {
- if (this.stageFxTimer) {
- clearTimeout(this.stageFxTimer)
- this.stageFxTimer = 0
- }
- }
- resetTransientGameUiState(): void {
- this.clearPunchFeedbackTimer()
- this.clearContentCardTimer()
- this.clearMapPulseTimer()
- this.clearStageFxTimer()
- this.setState({
- punchFeedbackVisible: false,
- punchFeedbackText: '',
- punchFeedbackTone: 'neutral',
- punchFeedbackFxClass: '',
- contentCardVisible: false,
- contentCardTitle: '',
- contentCardBody: '',
- contentCardFxClass: '',
- mapPulseVisible: false,
- mapPulseFxClass: '',
- stageFxVisible: false,
- stageFxClass: '',
- punchButtonFxClass: '',
- }, true)
- }
- clearSessionTimerInterval(): void {
- if (this.sessionTimerInterval) {
- clearInterval(this.sessionTimerInterval)
- this.sessionTimerInterval = 0
- }
- }
- syncSessionTimerText(): void {
- const telemetryPresentation = this.telemetryRuntime.getPresentation()
- this.setState({
- panelTimerText: telemetryPresentation.timerText,
- panelMileageText: telemetryPresentation.mileageText,
- panelActionTagText: this.gamePresentation.hud.actionTagText,
- panelDistanceTagText: this.gamePresentation.hud.distanceTagText,
- panelDistanceValueText: telemetryPresentation.distanceToTargetValueText,
- panelDistanceUnitText: telemetryPresentation.distanceToTargetUnitText,
- panelSpeedValueText: telemetryPresentation.speedText,
- panelTelemetryTone: telemetryPresentation.heartRateTone,
- panelHeartRateZoneNameText: telemetryPresentation.heartRateZoneNameText,
- panelHeartRateZoneRangeText: telemetryPresentation.heartRateZoneRangeText,
- panelHeartRateValueText: telemetryPresentation.heartRateValueText,
- panelHeartRateUnitText: telemetryPresentation.heartRateUnitText,
- panelCaloriesValueText: telemetryPresentation.caloriesValueText,
- panelCaloriesUnitText: telemetryPresentation.caloriesUnitText,
- panelAverageSpeedValueText: telemetryPresentation.averageSpeedValueText,
- panelAverageSpeedUnitText: telemetryPresentation.averageSpeedUnitText,
- panelAccuracyValueText: telemetryPresentation.accuracyValueText,
- panelAccuracyUnitText: telemetryPresentation.accuracyUnitText,
- }, true)
- }
- updateSessionTimerLoop(): void {
- const gameState = this.gameRuntime.state
- const shouldRun = !!gameState && gameState.status === 'running' && gameState.endedAt === null
- this.syncSessionTimerText()
- if (!shouldRun) {
- this.clearSessionTimerInterval()
- return
- }
- if (this.sessionTimerInterval) {
- return
- }
- this.sessionTimerInterval = setInterval(() => {
- this.syncSessionTimerText()
- }, 1000) as unknown as number
- }
- getControlScreenPoint(controlId: string): { x: number; y: number } | null {
- if (!this.gameRuntime.definition || !this.state.stageWidth || !this.state.stageHeight) {
- return null
- }
- const control = this.gameRuntime.definition.controls.find((item) => item.id === controlId)
- if (!control) {
- return null
- }
- const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
- const screenPoint = worldToScreen({
- centerWorldX: exactCenter.x,
- centerWorldY: exactCenter.y,
- viewportWidth: this.state.stageWidth,
- viewportHeight: this.state.stageHeight,
- visibleColumns: DESIRED_VISIBLE_COLUMNS,
- rotationRad: this.getRotationRad(this.state.rotationDeg),
- }, lonLatToWorldTile(control.point, this.state.zoom), false)
- if (screenPoint.x < -80 || screenPoint.x > this.state.stageWidth + 80 || screenPoint.y < -80 || screenPoint.y > this.state.stageHeight + 80) {
- return null
- }
- return screenPoint
- }
- setPunchButtonFxClass(className: string): void {
- this.setState({
- punchButtonFxClass: className,
- }, true)
- }
- showMapPulse(controlId: string, motionClass = ''): void {
- const screenPoint = this.getControlScreenPoint(controlId)
- if (!screenPoint) {
- return
- }
- this.clearMapPulseTimer()
- this.setState({
- mapPulseVisible: true,
- mapPulseLeftPx: screenPoint.x,
- mapPulseTopPx: screenPoint.y,
- mapPulseFxClass: motionClass,
- }, true)
- this.mapPulseTimer = setTimeout(() => {
- this.mapPulseTimer = 0
- this.setState({
- mapPulseVisible: false,
- mapPulseFxClass: '',
- }, true)
- }, 820) as unknown as number
- }
- showStageFx(className: string): void {
- if (!className) {
- return
- }
- this.clearStageFxTimer()
- this.setState({
- stageFxVisible: true,
- stageFxClass: className,
- }, true)
- this.stageFxTimer = setTimeout(() => {
- this.stageFxTimer = 0
- this.setState({
- stageFxVisible: false,
- stageFxClass: '',
- }, true)
- }, 760) as unknown as number
- }
- showPunchFeedback(text: string, tone: 'neutral' | 'success' | 'warning', motionClass = ''): void {
- this.clearPunchFeedbackTimer()
- this.setState({
- punchFeedbackVisible: true,
- punchFeedbackText: text,
- punchFeedbackTone: tone,
- punchFeedbackFxClass: motionClass,
- }, true)
- this.punchFeedbackTimer = setTimeout(() => {
- this.punchFeedbackTimer = 0
- this.setState({
- punchFeedbackVisible: false,
- punchFeedbackFxClass: '',
- }, true)
- }, 1400) as unknown as number
- }
- showContentCard(title: string, body: string, motionClass = ''): void {
- this.clearContentCardTimer()
- this.setState({
- contentCardVisible: true,
- contentCardTitle: title,
- contentCardBody: body,
- contentCardFxClass: motionClass,
- }, true)
- this.contentCardTimer = setTimeout(() => {
- this.contentCardTimer = 0
- this.setState({
- contentCardVisible: false,
- contentCardFxClass: '',
- }, true)
- }, 2600) as unknown as number
- }
- closeContentCard(): void {
- this.clearContentCardTimer()
- this.setState({
- contentCardVisible: false,
- contentCardFxClass: '',
- }, true)
- }
- applyGameEffects(effects: GameEffect[]): string | null {
- this.feedbackDirector.handleEffects(effects)
- if (effects.some((effect) => effect.type === 'session_finished')) {
- this.setState({
- gpsTracking: false,
- gpsTrackingText: '测试结束,定位已停止',
- }, true)
- }
- this.telemetryRuntime.syncGameState(this.gameRuntime.definition, this.gameRuntime.state, this.getHudTargetControlId())
- this.updateSessionTimerLoop()
- return this.resolveGameStatusText(effects)
- }
- syncGameResultState(result: GameResult): void {
- this.gamePresentation = result.presentation
- this.refreshCourseHeadingFromPresentation()
- }
- resolveAppliedGameStatusText(result: GameResult, fallbackStatusText?: string | null): string | null {
- return this.applyGameEffects(result.effects) || fallbackStatusText || this.resolveGameStatusText(result.effects)
- }
- commitGameResult(
- result: GameResult,
- fallbackStatusText?: string | null,
- extraPatch: Partial<MapEngineViewState> = {},
- syncRenderer = true,
- ): string | null {
- this.syncGameResultState(result)
- const gameStatusText = this.resolveAppliedGameStatusText(result, fallbackStatusText)
- this.setState({
- ...this.getGameViewPatch(gameStatusText),
- ...extraPatch,
- }, true)
- if (syncRenderer) {
- this.syncRenderer()
- }
- return gameStatusText
- }
- handleStartGame(): void {
- if (!this.gameRuntime.definition || !this.gameRuntime.state) {
- this.setState({
- statusText: `当前还没有可开始的路线 (${this.buildVersion})`,
- }, true)
- return
- }
- if (this.gameRuntime.state.status !== 'idle') {
- return
- }
- this.feedbackDirector.reset()
- this.resetTransientGameUiState()
- this.clearStartSessionResidue()
- if (!this.locationController.listening) {
- this.locationController.start()
- }
- const startedAt = Date.now()
- let gameResult = this.gameRuntime.startSession(startedAt)
- if (this.currentGpsPoint) {
- gameResult = this.gameRuntime.dispatch({
- type: 'gps_updated',
- at: Date.now(),
- lon: this.currentGpsPoint.lon,
- lat: this.currentGpsPoint.lat,
- accuracyMeters: this.currentGpsAccuracyMeters,
- })
- }
- this.courseOverlayVisible = true
- const defaultStatusText = this.currentGpsPoint
- ? `顺序打点已开始 (${this.buildVersion})`
- : `顺序打点已开始,GPS定位启动中 (${this.buildVersion})`
- this.commitGameResult(gameResult, defaultStatusText)
- }
- handleForceExitGame(): void {
- this.feedbackDirector.reset()
- if (!this.courseData) {
- this.clearGameRuntime()
- this.resetTransientGameUiState()
- this.setState({
- ...this.getGameViewPatch(`已退出当前对局 (${this.buildVersion})`),
- }, true)
- this.syncRenderer()
- return
- }
- this.loadGameDefinitionFromCourse()
- this.resetTransientGameUiState()
- this.setState({
- ...this.getGameViewPatch(`已退出当前对局 (${this.buildVersion})`),
- }, true)
- this.syncRenderer()
- }
- handlePunchAction(): void {
- const gameResult = this.gameRuntime.dispatch({
- type: 'punch_requested',
- at: Date.now(),
- })
- this.commitGameResult(gameResult)
- }
- handleLocationUpdate(longitude: number, latitude: number, accuracyMeters: number | null): void {
- const nextPoint: LonLatPoint = { lon: longitude, lat: latitude }
- const lastTrackPoint = this.currentGpsTrack.length ? this.currentGpsTrack[this.currentGpsTrack.length - 1] : null
- if (!lastTrackPoint || getApproxDistanceMeters(lastTrackPoint, nextPoint) >= GPS_TRACK_MIN_STEP_METERS) {
- this.currentGpsTrack = [...this.currentGpsTrack, nextPoint].slice(-GPS_TRACK_MAX_POINTS)
- }
- this.currentGpsPoint = nextPoint
- this.currentGpsAccuracyMeters = accuracyMeters
- const gpsWorldPoint = lonLatToWorldTile(nextPoint, this.state.zoom)
- const gpsTileX = Math.floor(gpsWorldPoint.x)
- const gpsTileY = Math.floor(gpsWorldPoint.y)
- const gpsInsideMap = isTileWithinBounds(this.tileBoundsByZoom, this.state.zoom, gpsTileX, gpsTileY)
- let gameStatusText: string | null = null
- if (this.courseData) {
- const eventAt = Date.now()
- const gameResult = this.gameRuntime.dispatch({
- type: 'gps_updated',
- at: eventAt,
- lon: longitude,
- lat: latitude,
- accuracyMeters,
- })
- this.telemetryRuntime.dispatch({
- type: 'gps_updated',
- at: eventAt,
- lon: longitude,
- lat: latitude,
- accuracyMeters,
- })
- this.syncGameResultState(gameResult)
- gameStatusText = this.resolveAppliedGameStatusText(gameResult)
- }
- if (gpsInsideMap && !this.hasGpsCenteredOnce) {
- this.hasGpsCenteredOnce = true
- this.commitViewport({
- centerTileX: gpsWorldPoint.x,
- centerTileY: gpsWorldPoint.y,
- tileTranslateX: 0,
- tileTranslateY: 0,
- gpsTracking: true,
- gpsTrackingText: '持续定位进行中',
- gpsCoordText: formatGpsCoordText(nextPoint, accuracyMeters),
- ...this.getGameViewPatch(),
- }, gameStatusText || `GPS定位成功,已定位到当前位置 (${this.buildVersion})`, true)
- return
- }
- this.setState({
- gpsTracking: true,
- gpsTrackingText: gpsInsideMap ? '持续定位进行中' : 'GPS不在当前地图范围内',
- gpsCoordText: formatGpsCoordText(nextPoint, accuracyMeters),
- ...this.getGameViewPatch(gameStatusText || (gpsInsideMap ? `GPS位置已更新 (${this.buildVersion})` : `GPS位置超出当前地图范围 (${this.buildVersion})`)),
- }, true)
- this.syncRenderer()
- }
- handleToggleOsmReference(): void {
- const nextEnabled = !this.state.osmReferenceEnabled
- this.setState({
- osmReferenceEnabled: nextEnabled,
- osmReferenceText: nextEnabled ? 'OSM参考:开' : 'OSM参考:关',
- statusText: nextEnabled ? `OSM参考底图已开启 (${this.buildVersion})` : `OSM参考底图已关闭 (${this.buildVersion})`,
- }, true)
- this.syncRenderer()
- }
- handleToggleGpsTracking(): void {
- if (this.locationController.listening) {
- this.locationController.stop()
- return
- }
- this.locationController.start()
- }
- handleSetRealLocationMode(): void {
- this.locationController.setSourceMode('real')
- }
- handleSetMockLocationMode(): void {
- this.locationController.setSourceMode('mock')
- }
- handleConnectMockLocationBridge(): void {
- this.locationController.connectMockBridge()
- }
- handleDisconnectMockLocationBridge(): void {
- this.locationController.disconnectMockBridge()
- }
- handleSetMockLocationBridgeUrl(url: string): void {
- this.locationController.setMockBridgeUrl(url)
- }
- handleSetGameMode(nextMode: 'classic-sequential' | 'score-o'): void {
- if (this.gameMode === nextMode) {
- return
- }
- this.gameMode = nextMode
- const result = this.loadGameDefinitionFromCourse()
- const modeText = this.getGameModeText()
- if (!result) {
- return
- }
- this.commitGameResult(result, `已切换到${modeText} (${this.buildVersion})`, {
- gameModeText: modeText,
- })
- }
- handleSkipAction(): void {
- const gameResult = this.gameRuntime.dispatch({
- type: 'skip_requested',
- at: Date.now(),
- lon: this.currentGpsPoint ? this.currentGpsPoint.lon : null,
- lat: this.currentGpsPoint ? this.currentGpsPoint.lat : null,
- })
- this.commitGameResult(gameResult)
- }
- handleConnectHeartRate(): void {
- this.heartRateController.startScanAndConnect()
- }
- handleDisconnectHeartRate(): void {
- this.heartRateController.disconnect()
- }
- handleSetRealHeartRateMode(): void {
- this.heartRateController.setSourceMode('real')
- }
- handleSetMockHeartRateMode(): void {
- this.heartRateController.setSourceMode('mock')
- }
- handleConnectMockHeartRateBridge(): void {
- this.heartRateController.connectMockBridge()
- }
- handleDisconnectMockHeartRateBridge(): void {
- this.heartRateController.disconnectMockBridge()
- }
- handleSetMockHeartRateBridgeUrl(url: string): void {
- this.heartRateController.setMockBridgeUrl(url)
- }
- handleConnectHeartRateDevice(deviceId: string): void {
- this.heartRateController.connectToDiscoveredDevice(deviceId)
- }
- handleClearPreferredHeartRateDevice(): void {
- this.heartRateController.clearPreferredDevice()
- this.setState({
- heartRateDeviceText: this.heartRateController.currentDeviceName || '--',
- heartRateScanText: this.getHeartRateScanText(),
- }, true)
- }
- handleDebugHeartRateTone(tone: HeartRateTone): void {
- const sampleBpm = getHeartRateToneSampleBpm(tone, this.telemetryRuntime.config)
- this.telemetryRuntime.dispatch({
- type: 'heart_rate_updated',
- at: Date.now(),
- bpm: sampleBpm,
- })
- this.setState({
- heartRateStatusText: `调试心率: ${sampleBpm} bpm / ${tone.toUpperCase()}`,
- }, true)
- this.syncSessionTimerText()
- }
- handleClearDebugHeartRate(): void {
- this.telemetryRuntime.dispatch({
- type: 'heart_rate_updated',
- at: Date.now(),
- bpm: null,
- })
- this.setState({
- heartRateStatusText: this.heartRateController.connected
- ? (this.heartRateController.sourceMode === 'mock' ? '模拟心率源已连接' : '心率带已连接')
- : (this.heartRateController.sourceMode === 'mock' ? '模拟心率源未连接' : '心率带未连接'),
- heartRateScanText: this.getHeartRateScanText(),
- ...this.getHeartRateControllerViewPatch(),
- }, true)
- this.syncSessionTimerText()
- }
- formatHeartRateDevices(devices: HeartRateDiscoveredDevice[]): Array<{ deviceId: string; name: string; rssiText: string; preferred: boolean; connected: boolean }> {
- return devices.map((device) => ({
- deviceId: device.deviceId,
- name: device.name,
- rssiText: device.rssi === null ? '--' : `${device.rssi} dBm`,
- preferred: device.isPreferred,
- connected: !!this.heartRateController.currentDeviceId && this.heartRateController.currentDeviceId === device.deviceId && this.heartRateController.connected,
- }))
- }
- getHeartRateScanText(): string {
- if (this.heartRateController.sourceMode === 'mock') {
- if (this.heartRateController.connected) {
- return '模拟源已连接'
- }
- if (this.heartRateController.connecting) {
- return '模拟源连接中'
- }
- return '模拟模式'
- }
- if (this.heartRateController.connected) {
- return '已连接'
- }
- if (this.heartRateController.connecting) {
- return '连接中'
- }
- if (this.heartRateController.disconnecting) {
- return '断开中'
- }
- if (this.heartRateController.scanning) {
- return this.heartRateController.lastDeviceId ? '扫描中(优先首选)' : '扫描中(等待选择)'
- }
- return this.heartRateController.discoveredDevices.length
- ? `已发现 ${this.heartRateController.discoveredDevices.length} 个设备`
- : '未扫描'
- }
- setStage(rect: MapEngineStageRect): void {
- this.previewScale = 1
- this.previewOriginX = rect.width / 2
- this.previewOriginY = rect.height / 2
- this.commitViewport(
- {
- stageWidth: rect.width,
- stageHeight: rect.height,
- stageLeft: rect.left,
- stageTop: rect.top,
- },
- `地图视口已与 WebGL 引擎对齐 (${this.buildVersion})`,
- true,
- )
- }
- attachCanvas(canvasNode: any, width: number, height: number, dpr: number, labelCanvasNode?: any): void {
- this.renderer.attachCanvas(canvasNode, width, height, dpr, labelCanvasNode)
- this.mounted = true
- this.state.mapReady = true
- this.state.mapReadyText = 'READY'
- this.onData({
- mapReady: true,
- mapReadyText: 'READY',
- statusText: `单 WebGL 管线已完成,可切换手动或自动朝向 (${this.buildVersion})`,
- })
- this.syncRenderer()
- this.compassController.start()
- }
- applyRemoteMapConfig(config: RemoteMapConfig): void {
- MAGNETIC_DECLINATION_DEG = config.magneticDeclinationDeg
- MAGNETIC_DECLINATION_TEXT = config.magneticDeclinationText
- this.minZoom = config.minZoom
- this.maxZoom = config.maxZoom
- this.defaultZoom = config.defaultZoom
- this.defaultCenterTileX = config.initialCenterTileX
- this.defaultCenterTileY = config.initialCenterTileY
- this.tileBoundsByZoom = config.tileBoundsByZoom
- this.courseData = config.course
- this.cpRadiusMeters = config.cpRadiusMeters
- this.configAppId = config.configAppId
- this.configSchemaVersion = config.configSchemaVersion
- this.configVersion = config.configVersion
- this.controlScoreOverrides = config.controlScoreOverrides
- this.defaultControlScore = config.defaultControlScore
- this.gameMode = config.gameMode
- this.punchPolicy = config.punchPolicy
- this.punchRadiusMeters = config.punchRadiusMeters
- this.requiresFocusSelection = config.requiresFocusSelection
- this.skipEnabled = config.skipEnabled
- this.skipRadiusMeters = config.skipRadiusMeters
- this.skipRequiresConfirm = config.skipRequiresConfirm
- this.autoFinishOnLastControl = config.autoFinishOnLastControl
- this.telemetryRuntime.configure(config.telemetryConfig)
- this.feedbackDirector.configure({
- audioConfig: config.audioConfig,
- hapticsConfig: config.hapticsConfig,
- uiEffectsConfig: config.uiEffectsConfig,
- })
- const gameResult = this.loadGameDefinitionFromCourse()
- const gameStatusText = gameResult ? this.resolveAppliedGameStatusText(gameResult) : null
- const statePatch: Partial<MapEngineViewState> = {
- mapName: config.configTitle,
- configStatusText: `配置已载入 / ${config.configTitle} / ${config.courseStatusText}`,
- projectionMode: config.projectionModeText,
- tileSource: config.tileSource,
- sensorHeadingText: formatHeadingText(this.smoothedSensorHeadingDeg === null ? null : getCompassReferenceHeadingDeg(this.northReferenceMode, this.smoothedSensorHeadingDeg)),
- compassDeclinationText: formatCompassDeclinationText(this.northReferenceMode),
- northReferenceButtonText: formatNorthReferenceButtonText(this.northReferenceMode),
- northReferenceText: formatNorthReferenceText(this.northReferenceMode),
- compassNeedleDeg: formatCompassNeedleDegForMode(this.northReferenceMode, this.smoothedSensorHeadingDeg),
- ...this.getGameViewPatch(gameStatusText),
- }
- if (!this.state.stageWidth || !this.state.stageHeight) {
- this.setState({
- ...statePatch,
- zoom: this.defaultZoom,
- centerTileX: this.defaultCenterTileX,
- centerTileY: this.defaultCenterTileY,
- centerText: buildCenterText(this.defaultZoom, this.defaultCenterTileX, this.defaultCenterTileY),
- statusText: gameStatusText || `路线已载入,点击开始进入游戏 (${this.buildVersion})`,
- }, true)
- return
- }
- this.commitViewport({
- ...statePatch,
- zoom: this.defaultZoom,
- centerTileX: this.defaultCenterTileX,
- centerTileY: this.defaultCenterTileY,
- tileTranslateX: 0,
- tileTranslateY: 0,
- }, gameStatusText || `路线已载入,点击开始进入游戏 (${this.buildVersion})`, true, () => {
- this.resetPreviewState()
- this.syncRenderer()
- if (this.state.orientationMode === 'heading-up' && this.refreshAutoRotateTarget()) {
- this.scheduleAutoRotate()
- }
- })
- }
- handleTouchStart(event: WechatMiniprogram.TouchEvent): void {
- this.clearInertiaTimer()
- this.clearPreviewResetTimer()
- this.panVelocityX = 0
- this.panVelocityY = 0
- if (event.touches.length >= 2) {
- const origin = this.getStagePoint(event.touches)
- this.gestureMode = 'pinch'
- this.pinchStartDistance = this.getTouchDistance(event.touches)
- this.pinchStartScale = this.previewScale || 1
- this.pinchStartAngle = this.getTouchAngle(event.touches)
- this.pinchStartRotationDeg = this.state.rotationDeg
- const anchorWorld = screenToWorld(this.getCameraState(), origin, true)
- this.pinchAnchorWorldX = anchorWorld.x
- this.pinchAnchorWorldY = anchorWorld.y
- this.setPreviewState(this.pinchStartScale, origin.x, origin.y)
- this.syncRenderer()
- this.compassController.start()
- return
- }
- if (event.touches.length === 1) {
- this.gestureMode = 'pan'
- this.panLastX = event.touches[0].pageX
- this.panLastY = event.touches[0].pageY
- this.panLastTimestamp = event.timeStamp || Date.now()
- this.tapStartX = event.touches[0].pageX
- this.tapStartY = event.touches[0].pageY
- this.tapStartAt = event.timeStamp || Date.now()
- }
- }
- handleTouchMove(event: WechatMiniprogram.TouchEvent): void {
- if (event.touches.length >= 2) {
- const distance = this.getTouchDistance(event.touches)
- const angle = this.getTouchAngle(event.touches)
- const origin = this.getStagePoint(event.touches)
- if (!this.pinchStartDistance) {
- this.pinchStartDistance = distance
- this.pinchStartScale = this.previewScale || 1
- this.pinchStartAngle = angle
- this.pinchStartRotationDeg = this.state.rotationDeg
- const anchorWorld = screenToWorld(this.getCameraState(), origin, true)
- this.pinchAnchorWorldX = anchorWorld.x
- this.pinchAnchorWorldY = anchorWorld.y
- }
- this.gestureMode = 'pinch'
- const nextRotationDeg = this.state.orientationMode === 'heading-up'
- ? this.state.rotationDeg
- : normalizeRotationDeg(this.pinchStartRotationDeg + normalizeAngleDeltaRad(angle - this.pinchStartAngle) * 180 / Math.PI)
- const anchorOffset = this.getWorldOffsetFromScreen(origin.x, origin.y, nextRotationDeg)
- const resolvedViewport = this.resolveViewportForExactCenter(
- this.pinchAnchorWorldX - anchorOffset.x,
- this.pinchAnchorWorldY - anchorOffset.y,
- nextRotationDeg,
- )
- this.setPreviewState(
- clamp(this.pinchStartScale * (distance / this.pinchStartDistance), MIN_PREVIEW_SCALE, MAX_PREVIEW_SCALE),
- origin.x,
- origin.y,
- )
- this.commitViewport(
- {
- ...resolvedViewport,
- rotationDeg: nextRotationDeg,
- rotationText: formatRotationText(nextRotationDeg),
- },
- this.state.orientationMode === 'heading-up'
- ? `双指缩放中,自动朝向保持开启 (${this.buildVersion})`
- : `双指缩放与旋转中 (${this.buildVersion})`,
- )
- return
- }
- if (this.gestureMode !== 'pan' || event.touches.length !== 1) {
- return
- }
- const touch = event.touches[0]
- const deltaX = touch.pageX - this.panLastX
- const deltaY = touch.pageY - this.panLastY
- const nextTimestamp = event.timeStamp || Date.now()
- const elapsed = Math.max(nextTimestamp - this.panLastTimestamp, 16)
- const instantVelocityX = deltaX / elapsed
- const instantVelocityY = deltaY / elapsed
- this.panVelocityX = this.panVelocityX * 0.72 + instantVelocityX * 0.28
- this.panVelocityY = this.panVelocityY * 0.72 + instantVelocityY * 0.28
- this.panLastX = touch.pageX
- this.panLastY = touch.pageY
- this.panLastTimestamp = nextTimestamp
- this.normalizeTranslate(
- this.state.tileTranslateX + deltaX,
- this.state.tileTranslateY + deltaY,
- `宸叉嫋鎷藉崟 WebGL 鍦板浘寮曟搸 (${this.buildVersion})`,
- )
- }
- handleTouchEnd(event: WechatMiniprogram.TouchEvent): void {
- const changedTouch = event.changedTouches && event.changedTouches.length ? event.changedTouches[0] : null
- const endedAsTap = changedTouch
- && this.gestureMode === 'pan'
- && event.touches.length === 0
- && Math.abs(changedTouch.pageX - this.tapStartX) <= MAP_TAP_MOVE_THRESHOLD_PX
- && Math.abs(changedTouch.pageY - this.tapStartY) <= MAP_TAP_MOVE_THRESHOLD_PX
- && ((event.timeStamp || Date.now()) - this.tapStartAt) <= MAP_TAP_DURATION_MS
- if (this.gestureMode === 'pinch' && event.touches.length < 2) {
- const gestureScale = this.previewScale || 1
- const zoomDelta = Math.round(Math.log2(gestureScale))
- const originX = this.previewOriginX || this.state.stageWidth / 2
- const originY = this.previewOriginY || this.state.stageHeight / 2
- if (zoomDelta) {
- const residualScale = gestureScale / Math.pow(2, zoomDelta)
- this.zoomAroundPoint(zoomDelta, originX, originY, residualScale)
- } else {
- this.animatePreviewToRest()
- }
- this.resetPinchState()
- this.panVelocityX = 0
- this.panVelocityY = 0
- if (event.touches.length === 1) {
- this.gestureMode = 'pan'
- this.panLastX = event.touches[0].pageX
- this.panLastY = event.touches[0].pageY
- this.panLastTimestamp = event.timeStamp || Date.now()
- return
- }
- this.gestureMode = 'idle'
- this.renderer.setAnimationPaused(false)
- this.scheduleAutoRotate()
- return
- }
- if (event.touches.length === 1) {
- this.gestureMode = 'pan'
- this.panLastX = event.touches[0].pageX
- this.panLastY = event.touches[0].pageY
- this.panLastTimestamp = event.timeStamp || Date.now()
- return
- }
- if (this.gestureMode === 'pan' && (Math.abs(this.panVelocityX) >= INERTIA_MIN_SPEED || Math.abs(this.panVelocityY) >= INERTIA_MIN_SPEED)) {
- this.startInertia()
- this.gestureMode = 'idle'
- this.resetPinchState()
- return
- }
- if (endedAsTap && changedTouch) {
- this.handleMapTap(changedTouch.pageX - this.state.stageLeft, changedTouch.pageY - this.state.stageTop)
- }
- this.gestureMode = 'idle'
- this.resetPinchState()
- this.renderer.setAnimationPaused(false)
- this.scheduleAutoRotate()
- }
- handleTouchCancel(): void {
- this.gestureMode = 'idle'
- this.resetPinchState()
- this.panVelocityX = 0
- this.panVelocityY = 0
- this.clearInertiaTimer()
- this.animatePreviewToRest()
- this.renderer.setAnimationPaused(false)
- this.scheduleAutoRotate()
- }
- handleMapTap(stageX: number, stageY: number): void {
- if (!this.gameRuntime.definition || !this.gameRuntime.state || this.gameRuntime.definition.mode !== 'score-o') {
- return
- }
- const focusedControlId = this.findFocusableControlAt(stageX, stageY)
- if (focusedControlId === undefined) {
- return
- }
- const gameResult = this.gameRuntime.dispatch({
- type: 'control_focused',
- at: Date.now(),
- controlId: focusedControlId,
- })
- this.commitGameResult(
- gameResult,
- focusedControlId ? `已选择目标点 (${this.buildVersion})` : `已取消目标点选择 (${this.buildVersion})`,
- )
- }
- findFocusableControlAt(stageX: number, stageY: number): string | null | undefined {
- if (!this.gameRuntime.definition || !this.courseData || !this.state.stageWidth || !this.state.stageHeight) {
- return undefined
- }
- const focusableControls = this.gameRuntime.definition.controls.filter((control) => (
- this.gamePresentation.map.focusableControlIds.includes(control.id)
- ))
- let matchedControlId: string | null | undefined
- let matchedDistance = Number.POSITIVE_INFINITY
- const hitRadiusPx = Math.max(28, this.getControlHitRadiusPx())
- for (const control of focusableControls) {
- const screenPoint = this.getControlScreenPoint(control.id)
- if (!screenPoint) {
- continue
- }
- const distancePx = Math.sqrt(
- Math.pow(screenPoint.x - stageX, 2)
- + Math.pow(screenPoint.y - stageY, 2),
- )
- if (distancePx <= hitRadiusPx && distancePx < matchedDistance) {
- matchedDistance = distancePx
- matchedControlId = control.id
- }
- }
- if (matchedControlId === undefined) {
- return undefined
- }
- return matchedControlId === this.gamePresentation.map.focusedControlId ? null : matchedControlId
- }
- getControlHitRadiusPx(): number {
- if (!this.state.tileSizePx) {
- return 28
- }
- const centerLonLat = worldTileToLonLat({ x: this.state.centerTileX + 0.5, y: this.state.centerTileY + 0.5 }, this.state.zoom)
- const metersPerTile = Math.cos(centerLonLat.lat * Math.PI / 180) * 40075016.686 / Math.pow(2, this.state.zoom)
- if (!metersPerTile) {
- return 28
- }
- const pixelsPerMeter = this.state.tileSizePx / metersPerTile
- return Math.max(28, this.cpRadiusMeters * pixelsPerMeter * 1.6)
- }
- handleRecenter(): void {
- this.clearInertiaTimer()
- this.clearPreviewResetTimer()
- this.panVelocityX = 0
- this.panVelocityY = 0
- this.renderer.setAnimationPaused(false)
- this.commitViewport(
- {
- zoom: this.defaultZoom,
- centerTileX: this.defaultCenterTileX,
- centerTileY: this.defaultCenterTileY,
- tileTranslateX: 0,
- tileTranslateY: 0,
- },
- `已回到单 WebGL 引擎默认首屏 (${this.buildVersion})`,
- true,
- () => {
- this.resetPreviewState()
- this.syncRenderer()
- this.compassController.start()
- this.scheduleAutoRotate()
- },
- )
- }
- handleRotateStep(stepDeg = ROTATE_STEP_DEG): void {
- if (this.state.rotationMode === 'auto') {
- this.setState({
- statusText: `当前不是手动旋转模式,请先切回手动 (${this.buildVersion})`,
- }, true)
- return
- }
- const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
- const nextRotationDeg = normalizeRotationDeg(this.state.rotationDeg + stepDeg)
- const resolvedViewport = this.resolveViewportForExactCenter(exactCenter.x, exactCenter.y, nextRotationDeg)
- this.clearInertiaTimer()
- this.clearPreviewResetTimer()
- this.panVelocityX = 0
- this.panVelocityY = 0
- this.renderer.setAnimationPaused(false)
- this.commitViewport(
- {
- ...resolvedViewport,
- rotationDeg: nextRotationDeg,
- rotationText: formatRotationText(nextRotationDeg),
- },
- `旋转角度调整到 ${formatRotationText(nextRotationDeg)} (${this.buildVersion})`,
- true,
- () => {
- this.resetPreviewState()
- this.syncRenderer()
- this.compassController.start()
- },
- )
- }
- handleRotationReset(): void {
- if (this.state.rotationMode === 'auto') {
- this.setState({
- statusText: `当前不是手动旋转模式,请先切回手动 (${this.buildVersion})`,
- }, true)
- return
- }
- const targetRotationDeg = MAP_NORTH_OFFSET_DEG
- if (Math.abs(normalizeAngleDeltaDeg(this.state.rotationDeg - targetRotationDeg)) <= 0.01) {
- return
- }
- const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
- const resolvedViewport = this.resolveViewportForExactCenter(exactCenter.x, exactCenter.y, targetRotationDeg)
- this.clearInertiaTimer()
- this.clearPreviewResetTimer()
- this.panVelocityX = 0
- this.panVelocityY = 0
- this.renderer.setAnimationPaused(false)
- this.commitViewport(
- {
- ...resolvedViewport,
- rotationDeg: targetRotationDeg,
- rotationText: formatRotationText(targetRotationDeg),
- },
- `旋转角度已回到真北参考 (${this.buildVersion})`,
- true,
- () => {
- this.resetPreviewState()
- this.syncRenderer()
- this.compassController.start()
- },
- )
- }
- handleToggleRotationMode(): void {
- if (this.state.orientationMode === 'manual') {
- this.setNorthUpMode()
- return
- }
- if (this.state.orientationMode === 'north-up') {
- this.setHeadingUpMode()
- return
- }
- this.setManualMode()
- }
- handleSetManualMode(): void {
- this.setManualMode()
- }
- handleSetNorthUpMode(): void {
- this.setNorthUpMode()
- }
- handleSetHeadingUpMode(): void {
- this.setHeadingUpMode()
- }
- handleCycleNorthReferenceMode(): void {
- this.cycleNorthReferenceMode()
- }
- handleAutoRotateCalibrate(): void {
- if (this.state.orientationMode !== 'heading-up') {
- this.setState({
- statusText: `请先切到朝向朝上模式再校准 (${this.buildVersion})`,
- }, true)
- return
- }
- if (!this.calibrateAutoRotateToCurrentOrientation()) {
- this.setState({
- statusText: `当前还没有传感器方向数据,暂时无法校准 (${this.buildVersion})`,
- }, true)
- return
- }
- this.setState({
- statusText: `已按当前持机方向完成朝向校准 (${this.buildVersion})`,
- }, true)
- this.scheduleAutoRotate()
- }
- setManualMode(): void {
- this.clearAutoRotateTimer()
- this.targetAutoRotationDeg = null
- this.autoRotateCalibrationPending = false
- this.setState({
- rotationMode: 'manual',
- rotationModeText: formatRotationModeText('manual'),
- rotationToggleText: formatRotationToggleText('manual'),
- orientationMode: 'manual',
- orientationModeText: formatOrientationModeText('manual'),
- autoRotateCalibrationText: formatAutoRotateCalibrationText(false, this.autoRotateCalibrationOffsetDeg),
- statusText: `已切回手动地图旋转 (${this.buildVersion})`,
- }, true)
- }
- setNorthUpMode(): void {
- this.clearAutoRotateTimer()
- this.targetAutoRotationDeg = null
- this.autoRotateCalibrationPending = false
- const mapNorthOffsetDeg = MAP_NORTH_OFFSET_DEG
- this.autoRotateCalibrationOffsetDeg = mapNorthOffsetDeg
- const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
- const resolvedViewport = this.resolveViewportForExactCenter(exactCenter.x, exactCenter.y, mapNorthOffsetDeg)
- this.commitViewport(
- {
- ...resolvedViewport,
- rotationDeg: mapNorthOffsetDeg,
- rotationText: formatRotationText(mapNorthOffsetDeg),
- rotationMode: 'manual',
- rotationModeText: formatRotationModeText('north-up'),
- rotationToggleText: formatRotationToggleText('north-up'),
- orientationMode: 'north-up',
- orientationModeText: formatOrientationModeText('north-up'),
- autoRotateCalibrationText: formatAutoRotateCalibrationText(false, mapNorthOffsetDeg),
- northReferenceText: formatNorthReferenceText(this.northReferenceMode),
- },
- `地图已固定为真北朝上 (${this.buildVersion})`,
- true,
- () => {
- this.resetPreviewState()
- this.syncRenderer()
- },
- )
- }
- setHeadingUpMode(): void {
- this.autoRotateCalibrationPending = false
- this.autoRotateCalibrationOffsetDeg = getMapNorthOffsetDeg(this.northReferenceMode)
- this.targetAutoRotationDeg = null
- this.setState({
- rotationMode: 'auto',
- rotationModeText: formatRotationModeText('heading-up'),
- rotationToggleText: formatRotationToggleText('heading-up'),
- orientationMode: 'heading-up',
- orientationModeText: formatOrientationModeText('heading-up'),
- autoRotateCalibrationText: formatAutoRotateCalibrationText(false, this.autoRotateCalibrationOffsetDeg),
- northReferenceText: formatNorthReferenceText(this.northReferenceMode),
- statusText: `正在启用朝向朝上模式 (${this.buildVersion})`,
- }, true)
- if (this.refreshAutoRotateTarget()) {
- this.scheduleAutoRotate()
- }
- }
- handleCompassHeading(headingDeg: number): void {
- this.sensorHeadingDeg = normalizeRotationDeg(headingDeg)
- this.smoothedSensorHeadingDeg = this.smoothedSensorHeadingDeg === null
- ? this.sensorHeadingDeg
- : interpolateAngleDeg(this.smoothedSensorHeadingDeg, this.sensorHeadingDeg, AUTO_ROTATE_HEADING_SMOOTHING)
- const compassHeadingDeg = getCompassReferenceHeadingDeg(this.northReferenceMode, this.smoothedSensorHeadingDeg)
- this.compassDisplayHeadingDeg = this.compassDisplayHeadingDeg === null
- ? compassHeadingDeg
- : interpolateAngleDeg(this.compassDisplayHeadingDeg, compassHeadingDeg, COMPASS_NEEDLE_SMOOTHING)
- this.autoRotateHeadingDeg = this.resolveAutoRotateInputHeadingDeg()
- this.setState({
- sensorHeadingText: formatHeadingText(compassHeadingDeg),
- compassDeclinationText: formatCompassDeclinationText(this.northReferenceMode),
- northReferenceButtonText: formatNorthReferenceButtonText(this.northReferenceMode),
- autoRotateSourceText: formatAutoRotateSourceText(this.autoRotateSourceMode, this.courseHeadingDeg !== null),
- compassNeedleDeg: formatCompassNeedleDegForMode(this.northReferenceMode, this.smoothedSensorHeadingDeg),
- northReferenceText: formatNorthReferenceText(this.northReferenceMode),
- })
- if (!this.refreshAutoRotateTarget()) {
- return
- }
- if (this.state.orientationMode === 'heading-up') {
- this.scheduleAutoRotate()
- }
- }
- handleCompassError(message: string): void {
- this.clearAutoRotateTimer()
- this.targetAutoRotationDeg = null
- this.autoRotateCalibrationPending = false
- this.setState({
- autoRotateCalibrationText: formatAutoRotateCalibrationText(false, this.autoRotateCalibrationOffsetDeg),
- statusText: `${message} (${this.buildVersion})`,
- }, true)
- }
- cycleNorthReferenceMode(): void {
- const nextMode = getNextNorthReferenceMode(this.northReferenceMode)
- const nextMapNorthOffsetDeg = getMapNorthOffsetDeg(nextMode)
- const compassHeadingDeg = this.smoothedSensorHeadingDeg === null
- ? null
- : getCompassReferenceHeadingDeg(nextMode, this.smoothedSensorHeadingDeg)
- this.northReferenceMode = nextMode
- this.autoRotateCalibrationOffsetDeg = nextMapNorthOffsetDeg
- this.compassDisplayHeadingDeg = compassHeadingDeg
- if (this.state.orientationMode === 'north-up') {
- const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
- const resolvedViewport = this.resolveViewportForExactCenter(exactCenter.x, exactCenter.y, MAP_NORTH_OFFSET_DEG)
- this.commitViewport(
- {
- ...resolvedViewport,
- rotationDeg: MAP_NORTH_OFFSET_DEG,
- rotationText: formatRotationText(MAP_NORTH_OFFSET_DEG),
- northReferenceText: formatNorthReferenceText(nextMode),
- sensorHeadingText: formatHeadingText(compassHeadingDeg),
- compassDeclinationText: formatCompassDeclinationText(nextMode),
- northReferenceButtonText: formatNorthReferenceButtonText(nextMode),
- compassNeedleDeg: formatCompassNeedleDegForMode(nextMode, this.smoothedSensorHeadingDeg),
- autoRotateCalibrationText: formatAutoRotateCalibrationText(false, nextMapNorthOffsetDeg),
- },
- `${formatNorthReferenceStatusText(nextMode)} (${this.buildVersion})`,
- true,
- () => {
- this.resetPreviewState()
- this.syncRenderer()
- },
- )
- return
- }
- this.setState({
- northReferenceText: formatNorthReferenceText(nextMode),
- sensorHeadingText: formatHeadingText(compassHeadingDeg),
- compassDeclinationText: formatCompassDeclinationText(nextMode),
- northReferenceButtonText: formatNorthReferenceButtonText(nextMode),
- compassNeedleDeg: formatCompassNeedleDegForMode(nextMode, this.smoothedSensorHeadingDeg),
- autoRotateCalibrationText: formatAutoRotateCalibrationText(false, nextMapNorthOffsetDeg),
- statusText: `${formatNorthReferenceStatusText(nextMode)} (${this.buildVersion})`,
- }, true)
- if (this.state.orientationMode === 'heading-up' && this.refreshAutoRotateTarget()) {
- this.scheduleAutoRotate()
- }
- }
- setCourseHeading(headingDeg: number | null): void {
- this.courseHeadingDeg = headingDeg === null ? null : normalizeRotationDeg(headingDeg)
- this.setState({
- autoRotateSourceText: formatAutoRotateSourceText(this.autoRotateSourceMode, this.courseHeadingDeg !== null),
- })
- if (this.refreshAutoRotateTarget()) {
- this.scheduleAutoRotate()
- }
- }
- resolveAutoRotateInputHeadingDeg(): number | null {
- const sensorHeadingDeg = this.smoothedSensorHeadingDeg === null
- ? null
- : getMapReferenceHeadingDegFromSensor(this.northReferenceMode, this.smoothedSensorHeadingDeg)
- const courseHeadingDeg = this.courseHeadingDeg === null
- ? null
- : getMapReferenceHeadingDegFromCourse(this.northReferenceMode, this.courseHeadingDeg)
- if (this.autoRotateSourceMode === 'sensor') {
- return sensorHeadingDeg
- }
- if (this.autoRotateSourceMode === 'course') {
- return courseHeadingDeg === null ? sensorHeadingDeg : courseHeadingDeg
- }
- if (sensorHeadingDeg !== null && courseHeadingDeg !== null) {
- return interpolateAngleDeg(sensorHeadingDeg, courseHeadingDeg, 0.35)
- }
- return sensorHeadingDeg === null ? courseHeadingDeg : sensorHeadingDeg
- }
- calibrateAutoRotateToCurrentOrientation(): boolean {
- const inputHeadingDeg = this.resolveAutoRotateInputHeadingDeg()
- if (inputHeadingDeg === null) {
- return false
- }
- this.autoRotateCalibrationOffsetDeg = normalizeRotationDeg(this.state.rotationDeg + inputHeadingDeg)
- this.autoRotateCalibrationPending = false
- this.targetAutoRotationDeg = normalizeRotationDeg(this.autoRotateCalibrationOffsetDeg - inputHeadingDeg)
- this.setState({
- autoRotateCalibrationText: formatAutoRotateCalibrationText(false, this.autoRotateCalibrationOffsetDeg),
- })
- return true
- }
- refreshAutoRotateTarget(): boolean {
- const inputHeadingDeg = this.resolveAutoRotateInputHeadingDeg()
- if (inputHeadingDeg === null) {
- return false
- }
- if (this.autoRotateCalibrationPending || this.autoRotateCalibrationOffsetDeg === null) {
- if (!this.calibrateAutoRotateToCurrentOrientation()) {
- return false
- }
- return true
- }
- this.targetAutoRotationDeg = normalizeRotationDeg(this.autoRotateCalibrationOffsetDeg - inputHeadingDeg)
- this.setState({
- autoRotateCalibrationText: formatAutoRotateCalibrationText(false, this.autoRotateCalibrationOffsetDeg),
- })
- return true
- }
- scheduleAutoRotate(): void {
- if (this.autoRotateTimer || this.state.rotationMode !== 'auto' || this.targetAutoRotationDeg === null) {
- return
- }
- const step = () => {
- this.autoRotateTimer = 0
- if (this.state.rotationMode !== 'auto' || this.targetAutoRotationDeg === null) {
- return
- }
- if (this.gestureMode !== 'idle' || this.inertiaTimer || this.previewResetTimer) {
- this.scheduleAutoRotate()
- return
- }
- const currentRotationDeg = this.state.rotationDeg
- const deltaDeg = normalizeAngleDeltaDeg(this.targetAutoRotationDeg - currentRotationDeg)
- if (Math.abs(deltaDeg) <= AUTO_ROTATE_SNAP_DEG) {
- if (Math.abs(deltaDeg) > 0.01) {
- this.applyAutoRotation(this.targetAutoRotationDeg)
- }
- this.scheduleAutoRotate()
- return
- }
- if (Math.abs(deltaDeg) <= AUTO_ROTATE_DEADZONE_DEG) {
- this.scheduleAutoRotate()
- return
- }
- const easedStepDeg = clamp(deltaDeg * AUTO_ROTATE_EASE, -AUTO_ROTATE_MAX_STEP_DEG, AUTO_ROTATE_MAX_STEP_DEG)
- this.applyAutoRotation(normalizeRotationDeg(currentRotationDeg + easedStepDeg))
- this.scheduleAutoRotate()
- }
- this.autoRotateTimer = setTimeout(step, AUTO_ROTATE_FRAME_MS) as unknown as number
- }
- applyAutoRotation(nextRotationDeg: number): void {
- const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
- const resolvedViewport = this.resolveViewportForExactCenter(exactCenter.x, exactCenter.y, nextRotationDeg)
- this.setState({
- ...resolvedViewport,
- rotationDeg: nextRotationDeg,
- rotationText: formatRotationText(nextRotationDeg),
- centerText: buildCenterText(this.state.zoom, resolvedViewport.centerTileX, resolvedViewport.centerTileY),
- })
- this.syncRenderer()
- }
- applyStats(stats: MapRendererStats): void {
- this.setState({
- visibleTileCount: stats.visibleTileCount,
- readyTileCount: stats.readyTileCount,
- memoryTileCount: stats.memoryTileCount,
- diskTileCount: stats.diskTileCount,
- memoryHitCount: stats.memoryHitCount,
- diskHitCount: stats.diskHitCount,
- networkFetchCount: stats.networkFetchCount,
- cacheHitRateText: formatCacheHitRate(stats.memoryHitCount, stats.diskHitCount, stats.networkFetchCount),
- })
- }
- setState(patch: Partial<MapEngineViewState>, immediateUi = false): void {
- this.state = {
- ...this.state,
- ...patch,
- }
- const viewPatch = this.pickViewPatch(patch)
- if (!Object.keys(viewPatch).length) {
- return
- }
- this.pendingViewPatch = {
- ...this.pendingViewPatch,
- ...viewPatch,
- }
- if (immediateUi) {
- this.flushViewPatch()
- return
- }
- if (this.viewSyncTimer) {
- return
- }
- this.viewSyncTimer = setTimeout(() => {
- this.viewSyncTimer = 0
- this.flushViewPatch()
- }, UI_SYNC_INTERVAL_MS) as unknown as number
- }
- commitViewport(
- patch: Partial<MapEngineViewState>,
- statusText: string,
- immediateUi = false,
- afterUpdate?: () => void,
- ): void {
- const nextZoom = typeof patch.zoom === 'number' ? patch.zoom : this.state.zoom
- const nextCenterTileX = typeof patch.centerTileX === 'number' ? patch.centerTileX : this.state.centerTileX
- const nextCenterTileY = typeof patch.centerTileY === 'number' ? patch.centerTileY : this.state.centerTileY
- const nextStageWidth = typeof patch.stageWidth === 'number' ? patch.stageWidth : this.state.stageWidth
- const nextStageHeight = typeof patch.stageHeight === 'number' ? patch.stageHeight : this.state.stageHeight
- const tileSizePx = getTileSizePx({
- centerWorldX: nextCenterTileX,
- centerWorldY: nextCenterTileY,
- viewportWidth: nextStageWidth,
- viewportHeight: nextStageHeight,
- visibleColumns: DESIRED_VISIBLE_COLUMNS,
- })
- this.setState({
- ...patch,
- tileSizePx,
- centerText: buildCenterText(nextZoom, nextCenterTileX, nextCenterTileY),
- statusText,
- }, immediateUi)
- this.syncRenderer()
- this.compassController.start()
- if (afterUpdate) {
- afterUpdate()
- }
- }
- buildScene() {
- const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
- return {
- tileSource: this.state.tileSource,
- osmTileSource: OSM_TILE_SOURCE,
- zoom: this.state.zoom,
- centerTileX: this.state.centerTileX,
- centerTileY: this.state.centerTileY,
- exactCenterWorldX: exactCenter.x,
- exactCenterWorldY: exactCenter.y,
- tileBoundsByZoom: this.tileBoundsByZoom,
- viewportWidth: this.state.stageWidth,
- viewportHeight: this.state.stageHeight,
- visibleColumns: DESIRED_VISIBLE_COLUMNS,
- overdraw: OVERDRAW,
- translateX: this.state.tileTranslateX,
- translateY: this.state.tileTranslateY,
- rotationRad: this.getRotationRad(this.state.rotationDeg),
- previewScale: this.previewScale || 1,
- previewOriginX: this.previewOriginX || this.state.stageWidth / 2,
- previewOriginY: this.previewOriginY || this.state.stageHeight / 2,
- track: this.currentGpsTrack,
- gpsPoint: this.currentGpsPoint,
- gpsCalibration: GPS_MAP_CALIBRATION,
- gpsCalibrationOrigin: worldTileToLonLat({ x: this.defaultCenterTileX, y: this.defaultCenterTileY }, this.defaultZoom),
- course: this.courseOverlayVisible ? this.courseData : null,
- cpRadiusMeters: this.cpRadiusMeters,
- controlVisualMode: this.gamePresentation.map.controlVisualMode,
- showCourseLegs: this.gamePresentation.map.showCourseLegs,
- guidanceLegAnimationEnabled: this.gamePresentation.map.guidanceLegAnimationEnabled,
- focusableControlIds: this.gamePresentation.map.focusableControlIds,
- focusedControlId: this.gamePresentation.map.focusedControlId,
- focusedControlSequences: this.gamePresentation.map.focusedControlSequences,
- activeControlSequences: this.gamePresentation.map.activeControlSequences,
- activeStart: this.gamePresentation.map.activeStart,
- completedStart: this.gamePresentation.map.completedStart,
- activeFinish: this.gamePresentation.map.activeFinish,
- focusedFinish: this.gamePresentation.map.focusedFinish,
- completedFinish: this.gamePresentation.map.completedFinish,
- revealFullCourse: this.gamePresentation.map.revealFullCourse,
- activeLegIndices: this.gamePresentation.map.activeLegIndices,
- completedLegIndices: this.gamePresentation.map.completedLegIndices,
- completedControlSequences: this.gamePresentation.map.completedControlSequences,
- skippedControlIds: this.gamePresentation.map.skippedControlIds,
- skippedControlSequences: this.gamePresentation.map.skippedControlSequences,
- osmReferenceEnabled: this.state.osmReferenceEnabled,
- overlayOpacity: MAP_OVERLAY_OPACITY,
- }
- }
- syncRenderer(): void {
- if (!this.mounted || !this.state.stageWidth || !this.state.stageHeight) {
- return
- }
- this.renderer.updateScene(this.buildScene())
- }
- getCameraState(rotationDeg = this.state.rotationDeg): CameraState {
- return {
- centerWorldX: this.state.centerTileX + 0.5,
- centerWorldY: this.state.centerTileY + 0.5,
- viewportWidth: this.state.stageWidth,
- viewportHeight: this.state.stageHeight,
- visibleColumns: DESIRED_VISIBLE_COLUMNS,
- translateX: this.state.tileTranslateX,
- translateY: this.state.tileTranslateY,
- rotationRad: this.getRotationRad(rotationDeg),
- }
- }
- getRotationRad(rotationDeg = this.state.rotationDeg): number {
- return normalizeRotationDeg(rotationDeg) * Math.PI / 180
- }
- getBaseCamera(centerTileX = this.state.centerTileX, centerTileY = this.state.centerTileY, rotationDeg = this.state.rotationDeg): CameraState {
- return {
- centerWorldX: centerTileX + 0.5,
- centerWorldY: centerTileY + 0.5,
- viewportWidth: this.state.stageWidth,
- viewportHeight: this.state.stageHeight,
- visibleColumns: DESIRED_VISIBLE_COLUMNS,
- rotationRad: this.getRotationRad(rotationDeg),
- }
- }
- getWorldOffsetFromScreen(stageX: number, stageY: number, rotationDeg = this.state.rotationDeg): { x: number; y: number } {
- const baseCamera = {
- centerWorldX: 0,
- centerWorldY: 0,
- viewportWidth: this.state.stageWidth,
- viewportHeight: this.state.stageHeight,
- visibleColumns: DESIRED_VISIBLE_COLUMNS,
- rotationRad: this.getRotationRad(rotationDeg),
- }
- return screenToWorld(baseCamera, { x: stageX, y: stageY }, false)
- }
- getExactCenterFromTranslate(translateX: number, translateY: number): { x: number; y: number } {
- if (!this.state.stageWidth || !this.state.stageHeight) {
- return {
- x: this.state.centerTileX + 0.5,
- y: this.state.centerTileY + 0.5,
- }
- }
- const screenCenterX = this.state.stageWidth / 2
- const screenCenterY = this.state.stageHeight / 2
- return screenToWorld(this.getBaseCamera(), {
- x: screenCenterX - translateX,
- y: screenCenterY - translateY,
- }, false)
- }
- resolveViewportForExactCenter(centerWorldX: number, centerWorldY: number, rotationDeg = this.state.rotationDeg): {
- centerTileX: number
- centerTileY: number
- tileTranslateX: number
- tileTranslateY: number
- } {
- const nextCenterTileX = Math.floor(centerWorldX)
- const nextCenterTileY = Math.floor(centerWorldY)
- if (!this.state.stageWidth || !this.state.stageHeight) {
- return {
- centerTileX: nextCenterTileX,
- centerTileY: nextCenterTileY,
- tileTranslateX: 0,
- tileTranslateY: 0,
- }
- }
- const roundedCamera = this.getBaseCamera(nextCenterTileX, nextCenterTileY, rotationDeg)
- const projectedCenter = worldToScreen(roundedCamera, { x: centerWorldX, y: centerWorldY }, false)
- return {
- centerTileX: nextCenterTileX,
- centerTileY: nextCenterTileY,
- tileTranslateX: this.state.stageWidth / 2 - projectedCenter.x,
- tileTranslateY: this.state.stageHeight / 2 - projectedCenter.y,
- }
- }
- setPreviewState(scale: number, originX: number, originY: number): void {
- this.previewScale = scale
- this.previewOriginX = originX
- this.previewOriginY = originY
- }
- resetPreviewState(): void {
- this.setPreviewState(1, this.state.stageWidth / 2, this.state.stageHeight / 2)
- }
- resetPinchState(): void {
- this.pinchStartDistance = 0
- this.pinchStartScale = 1
- this.pinchStartAngle = 0
- this.pinchStartRotationDeg = this.state.rotationDeg
- this.pinchAnchorWorldX = 0
- this.pinchAnchorWorldY = 0
- }
- clearPreviewResetTimer(): void {
- if (this.previewResetTimer) {
- clearTimeout(this.previewResetTimer)
- this.previewResetTimer = 0
- }
- }
- clearInertiaTimer(): void {
- if (this.inertiaTimer) {
- clearTimeout(this.inertiaTimer)
- this.inertiaTimer = 0
- }
- }
- clearViewSyncTimer(): void {
- if (this.viewSyncTimer) {
- clearTimeout(this.viewSyncTimer)
- this.viewSyncTimer = 0
- }
- }
- clearAutoRotateTimer(): void {
- if (this.autoRotateTimer) {
- clearTimeout(this.autoRotateTimer)
- this.autoRotateTimer = 0
- }
- }
- pickViewPatch(patch: Partial<MapEngineViewState>): Partial<MapEngineViewState> {
- const viewPatch = {} as Partial<MapEngineViewState>
- for (const key of VIEW_SYNC_KEYS) {
- if (Object.prototype.hasOwnProperty.call(patch, key)) {
- ;(viewPatch as any)[key] = patch[key]
- }
- }
- return viewPatch
- }
- flushViewPatch(): void {
- if (!Object.keys(this.pendingViewPatch).length) {
- return
- }
- const patch = this.pendingViewPatch
- this.pendingViewPatch = {}
- this.onData(patch)
- }
- getTouchDistance(touches: TouchPoint[]): number {
- if (touches.length < 2) {
- return 0
- }
- const first = touches[0]
- const second = touches[1]
- const deltaX = first.pageX - second.pageX
- const deltaY = first.pageY - second.pageY
- return Math.sqrt(deltaX * deltaX + deltaY * deltaY)
- }
- getTouchAngle(touches: TouchPoint[]): number {
- if (touches.length < 2) {
- return 0
- }
- const first = touches[0]
- const second = touches[1]
- return Math.atan2(second.pageY - first.pageY, second.pageX - first.pageX)
- }
- getStagePoint(touches: TouchPoint[]): { x: number; y: number } {
- if (!touches.length) {
- return {
- x: this.state.stageWidth / 2,
- y: this.state.stageHeight / 2,
- }
- }
- let pageX = 0
- let pageY = 0
- for (const touch of touches) {
- pageX += touch.pageX
- pageY += touch.pageY
- }
- return {
- x: pageX / touches.length - this.state.stageLeft,
- y: pageY / touches.length - this.state.stageTop,
- }
- }
- animatePreviewToRest(): void {
- this.clearPreviewResetTimer()
- const startScale = this.previewScale || 1
- const originX = this.previewOriginX || this.state.stageWidth / 2
- const originY = this.previewOriginY || this.state.stageHeight / 2
- if (Math.abs(startScale - 1) < 0.01) {
- this.resetPreviewState()
- this.syncRenderer()
- this.compassController.start()
- this.scheduleAutoRotate()
- return
- }
- const startAt = Date.now()
- const step = () => {
- const progress = Math.min(1, (Date.now() - startAt) / PREVIEW_RESET_DURATION_MS)
- const eased = 1 - Math.pow(1 - progress, 3)
- const nextScale = startScale + (1 - startScale) * eased
- this.setPreviewState(nextScale, originX, originY)
- this.syncRenderer()
- this.compassController.start()
- if (progress >= 1) {
- this.resetPreviewState()
- this.syncRenderer()
- this.compassController.start()
- this.previewResetTimer = 0
- this.scheduleAutoRotate()
- return
- }
- this.previewResetTimer = setTimeout(step, INERTIA_FRAME_MS) as unknown as number
- }
- step()
- }
- normalizeTranslate(translateX: number, translateY: number, statusText: string): void {
- if (!this.state.stageWidth) {
- this.setState({
- tileTranslateX: translateX,
- tileTranslateY: translateY,
- })
- this.syncRenderer()
- this.compassController.start()
- return
- }
- const exactCenter = this.getExactCenterFromTranslate(translateX, translateY)
- const resolvedViewport = this.resolveViewportForExactCenter(exactCenter.x, exactCenter.y)
- const centerChanged = resolvedViewport.centerTileX !== this.state.centerTileX || resolvedViewport.centerTileY !== this.state.centerTileY
- if (centerChanged) {
- this.commitViewport(resolvedViewport, statusText)
- return
- }
- this.setState({
- tileTranslateX: resolvedViewport.tileTranslateX,
- tileTranslateY: resolvedViewport.tileTranslateY,
- })
- this.syncRenderer()
- this.compassController.start()
- }
- zoomAroundPoint(zoomDelta: number, stageX: number, stageY: number, residualScale: number): void {
- const nextZoom = clamp(this.state.zoom + zoomDelta, this.minZoom, this.maxZoom)
- const appliedDelta = nextZoom - this.state.zoom
- if (!appliedDelta) {
- this.animatePreviewToRest()
- return
- }
- if (!this.state.stageWidth || !this.state.stageHeight) {
- this.commitViewport(
- {
- zoom: nextZoom,
- centerTileX: appliedDelta > 0 ? this.state.centerTileX * 2 : Math.floor(this.state.centerTileX / 2),
- centerTileY: appliedDelta > 0 ? this.state.centerTileY * 2 : Math.floor(this.state.centerTileY / 2),
- tileTranslateX: 0,
- tileTranslateY: 0,
- },
- `缩放级别调整到 ${nextZoom}`,
- true,
- () => {
- this.setPreviewState(residualScale, stageX, stageY)
- this.syncRenderer()
- this.compassController.start()
- this.animatePreviewToRest()
- },
- )
- return
- }
- const camera = this.getCameraState()
- const world = screenToWorld(camera, { x: stageX, y: stageY }, true)
- const zoomFactor = Math.pow(2, appliedDelta)
- const nextWorldX = world.x * zoomFactor
- const nextWorldY = world.y * zoomFactor
- const anchorOffset = this.getWorldOffsetFromScreen(stageX, stageY)
- const exactCenterX = nextWorldX - anchorOffset.x
- const exactCenterY = nextWorldY - anchorOffset.y
- const resolvedViewport = this.resolveViewportForExactCenter(exactCenterX, exactCenterY)
- this.commitViewport(
- {
- zoom: nextZoom,
- ...resolvedViewport,
- },
- `缩放级别调整到 ${nextZoom}`,
- true,
- () => {
- this.setPreviewState(residualScale, stageX, stageY)
- this.syncRenderer()
- this.compassController.start()
- this.animatePreviewToRest()
- },
- )
- }
- startInertia(): void {
- this.clearInertiaTimer()
- const step = () => {
- this.panVelocityX *= INERTIA_DECAY
- this.panVelocityY *= INERTIA_DECAY
- if (Math.abs(this.panVelocityX) < INERTIA_MIN_SPEED && Math.abs(this.panVelocityY) < INERTIA_MIN_SPEED) {
- this.setState({
- statusText: `惯性滑动结束 (${this.buildVersion})`,
- })
- this.renderer.setAnimationPaused(false)
- this.inertiaTimer = 0
- this.scheduleAutoRotate()
- return
- }
- this.normalizeTranslate(
- this.state.tileTranslateX + this.panVelocityX * INERTIA_FRAME_MS,
- this.state.tileTranslateY + this.panVelocityY * INERTIA_FRAME_MS,
- `惯性滑动中 (${this.buildVersion})`,
- )
- this.inertiaTimer = setTimeout(step, INERTIA_FRAME_MS) as unknown as number
- }
- this.inertiaTimer = setTimeout(step, INERTIA_FRAME_MS) as unknown as number
- }
- }
|