mapEngine.ts 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802
  1. import { getTileSizePx, screenToWorld, worldToScreen, type CameraState } from '../camera/camera'
  2. import { CompassHeadingController } from '../sensor/compassHeadingController'
  3. import { LocationController } from '../sensor/locationController'
  4. import { WebGLMapRenderer } from '../renderer/webglMapRenderer'
  5. import { type MapRendererStats } from '../renderer/mapRenderer'
  6. import { lonLatToWorldTile, worldTileToLonLat, type LonLatPoint, type MapCalibration } from '../../utils/projection'
  7. import { isTileWithinBounds, type RemoteMapConfig, type TileZoomBounds } from '../../utils/remoteMapConfig'
  8. const RENDER_MODE = 'Single WebGL Pipeline'
  9. const PROJECTION_MODE = 'WGS84 -> WorldTile -> Camera -> Screen'
  10. const MAP_NORTH_OFFSET_DEG = 0
  11. let MAGNETIC_DECLINATION_DEG = -6.91
  12. let MAGNETIC_DECLINATION_TEXT = '6.91° W'
  13. const MIN_ZOOM = 15
  14. const MAX_ZOOM = 20
  15. const DEFAULT_ZOOM = 17
  16. const DESIRED_VISIBLE_COLUMNS = 3
  17. const OVERDRAW = 1
  18. const DEFAULT_TOP_LEFT_TILE_X = 108132
  19. const DEFAULT_TOP_LEFT_TILE_Y = 51199
  20. const DEFAULT_CENTER_TILE_X = DEFAULT_TOP_LEFT_TILE_X + 1
  21. const DEFAULT_CENTER_TILE_Y = DEFAULT_TOP_LEFT_TILE_Y + 1
  22. const TILE_SOURCE = 'https://oss-mbh5.colormaprun.com/wxMap/lcx/{z}/{x}/{y}.png'
  23. const OSM_TILE_SOURCE = 'https://tiles.mymarsgo.xyz/{z}/{x}/{y}.png'
  24. const MAP_OVERLAY_OPACITY = 0.72
  25. const GPS_MAP_CALIBRATION: MapCalibration = {
  26. offsetEastMeters: 0,
  27. offsetNorthMeters: 0,
  28. rotationDeg: 0,
  29. scale: 1,
  30. }
  31. const MIN_PREVIEW_SCALE = 0.55
  32. const MAX_PREVIEW_SCALE = 1.85
  33. const INERTIA_FRAME_MS = 16
  34. const INERTIA_DECAY = 0.92
  35. const INERTIA_MIN_SPEED = 0.02
  36. const PREVIEW_RESET_DURATION_MS = 140
  37. const UI_SYNC_INTERVAL_MS = 80
  38. const ROTATE_STEP_DEG = 15
  39. const AUTO_ROTATE_FRAME_MS = 8
  40. const AUTO_ROTATE_EASE = 0.34
  41. const AUTO_ROTATE_SNAP_DEG = 0.1
  42. const AUTO_ROTATE_DEADZONE_DEG = 4
  43. const AUTO_ROTATE_MAX_STEP_DEG = 0.75
  44. const AUTO_ROTATE_HEADING_SMOOTHING = 0.32
  45. const COMPASS_NEEDLE_SMOOTHING = 0.12
  46. const GPS_TRACK_MAX_POINTS = 200
  47. const GPS_TRACK_MIN_STEP_METERS = 3
  48. type TouchPoint = WechatMiniprogram.TouchDetail
  49. type GestureMode = 'idle' | 'pan' | 'pinch'
  50. type RotationMode = 'manual' | 'auto'
  51. type OrientationMode = 'manual' | 'north-up' | 'heading-up'
  52. type AutoRotateSourceMode = 'sensor' | 'course' | 'fusion'
  53. type NorthReferenceMode = 'magnetic' | 'true'
  54. const DEFAULT_NORTH_REFERENCE_MODE: NorthReferenceMode = 'magnetic'
  55. export interface MapEngineStageRect {
  56. width: number
  57. height: number
  58. left: number
  59. top: number
  60. }
  61. export interface MapEngineViewState {
  62. buildVersion: string
  63. renderMode: string
  64. projectionMode: string
  65. mapReady: boolean
  66. mapReadyText: string
  67. mapName: string
  68. configStatusText: string
  69. zoom: number
  70. rotationDeg: number
  71. rotationText: string
  72. rotationMode: RotationMode
  73. rotationModeText: string
  74. rotationToggleText: string
  75. orientationMode: OrientationMode
  76. orientationModeText: string
  77. sensorHeadingText: string
  78. compassDeclinationText: string
  79. northReferenceButtonText: string
  80. autoRotateSourceText: string
  81. autoRotateCalibrationText: string
  82. northReferenceText: string
  83. compassNeedleDeg: number
  84. centerTileX: number
  85. centerTileY: number
  86. centerText: string
  87. tileSource: string
  88. visibleColumnCount: number
  89. visibleTileCount: number
  90. readyTileCount: number
  91. memoryTileCount: number
  92. diskTileCount: number
  93. memoryHitCount: number
  94. diskHitCount: number
  95. networkFetchCount: number
  96. cacheHitRateText: string
  97. tileTranslateX: number
  98. tileTranslateY: number
  99. tileSizePx: number
  100. stageWidth: number
  101. stageHeight: number
  102. stageLeft: number
  103. stageTop: number
  104. statusText: string
  105. gpsTracking: boolean
  106. gpsTrackingText: string
  107. gpsCoordText: string
  108. osmReferenceEnabled: boolean
  109. osmReferenceText: string
  110. }
  111. export interface MapEngineCallbacks {
  112. onData: (patch: Partial<MapEngineViewState>) => void
  113. }
  114. const VIEW_SYNC_KEYS: Array<keyof MapEngineViewState> = [
  115. 'buildVersion',
  116. 'renderMode',
  117. 'projectionMode',
  118. 'mapReady',
  119. 'mapReadyText',
  120. 'mapName',
  121. 'configStatusText',
  122. 'zoom',
  123. 'rotationDeg',
  124. 'rotationText',
  125. 'rotationMode',
  126. 'rotationModeText',
  127. 'rotationToggleText',
  128. 'orientationMode',
  129. 'orientationModeText',
  130. 'sensorHeadingText',
  131. 'compassDeclinationText',
  132. 'northReferenceButtonText',
  133. 'autoRotateSourceText',
  134. 'autoRotateCalibrationText',
  135. 'northReferenceText',
  136. 'compassNeedleDeg',
  137. 'centerText',
  138. 'tileSource',
  139. 'visibleTileCount',
  140. 'readyTileCount',
  141. 'memoryTileCount',
  142. 'diskTileCount',
  143. 'memoryHitCount',
  144. 'diskHitCount',
  145. 'networkFetchCount',
  146. 'cacheHitRateText',
  147. 'tileSizePx',
  148. 'statusText',
  149. 'gpsTracking',
  150. 'gpsTrackingText',
  151. 'gpsCoordText',
  152. 'osmReferenceEnabled',
  153. 'osmReferenceText',
  154. ]
  155. function buildCenterText(zoom: number, x: number, y: number): string {
  156. return `z${zoom} / x${x} / y${y}`
  157. }
  158. function clamp(value: number, min: number, max: number): number {
  159. return Math.max(min, Math.min(max, value))
  160. }
  161. function normalizeRotationDeg(rotationDeg: number): number {
  162. const normalized = rotationDeg % 360
  163. return normalized < 0 ? normalized + 360 : normalized
  164. }
  165. function normalizeAngleDeltaRad(angleDeltaRad: number): number {
  166. let normalized = angleDeltaRad
  167. while (normalized > Math.PI) {
  168. normalized -= Math.PI * 2
  169. }
  170. while (normalized < -Math.PI) {
  171. normalized += Math.PI * 2
  172. }
  173. return normalized
  174. }
  175. function normalizeAngleDeltaDeg(angleDeltaDeg: number): number {
  176. let normalized = angleDeltaDeg
  177. while (normalized > 180) {
  178. normalized -= 360
  179. }
  180. while (normalized < -180) {
  181. normalized += 360
  182. }
  183. return normalized
  184. }
  185. function interpolateAngleDeg(currentDeg: number, targetDeg: number, factor: number): number {
  186. return normalizeRotationDeg(currentDeg + normalizeAngleDeltaDeg(targetDeg - currentDeg) * factor)
  187. }
  188. function formatRotationText(rotationDeg: number): string {
  189. return `${Math.round(normalizeRotationDeg(rotationDeg))}deg`
  190. }
  191. function formatHeadingText(headingDeg: number | null): string {
  192. if (headingDeg === null) {
  193. return '--'
  194. }
  195. return `${Math.round(normalizeRotationDeg(headingDeg))}deg`
  196. }
  197. function formatOrientationModeText(mode: OrientationMode): string {
  198. if (mode === 'north-up') {
  199. return 'North Up'
  200. }
  201. if (mode === 'heading-up') {
  202. return 'Heading Up'
  203. }
  204. return 'Manual Gesture'
  205. }
  206. function formatRotationModeText(mode: OrientationMode): string {
  207. return formatOrientationModeText(mode)
  208. }
  209. function formatRotationToggleText(mode: OrientationMode): string {
  210. if (mode === 'manual') {
  211. return '切到北朝上'
  212. }
  213. if (mode === 'north-up') {
  214. return '切到朝向朝上'
  215. }
  216. return '切到手动旋转'
  217. }
  218. function formatAutoRotateSourceText(mode: AutoRotateSourceMode, hasCourseHeading: boolean): string {
  219. if (mode === 'sensor') {
  220. return 'Sensor Only'
  221. }
  222. if (mode === 'course') {
  223. return hasCourseHeading ? 'Course Only' : 'Course Pending'
  224. }
  225. return hasCourseHeading ? 'Sensor + Course' : 'Sensor Only'
  226. }
  227. function formatAutoRotateCalibrationText(pending: boolean, offsetDeg: number | null): string {
  228. if (pending) {
  229. return 'Pending'
  230. }
  231. if (offsetDeg === null) {
  232. return '--'
  233. }
  234. return `Offset ${Math.round(normalizeRotationDeg(offsetDeg))}deg`
  235. }
  236. function getTrueHeadingDeg(magneticHeadingDeg: number): number {
  237. return normalizeRotationDeg(magneticHeadingDeg + MAGNETIC_DECLINATION_DEG)
  238. }
  239. function getMagneticHeadingDeg(trueHeadingDeg: number): number {
  240. return normalizeRotationDeg(trueHeadingDeg - MAGNETIC_DECLINATION_DEG)
  241. }
  242. function getMapNorthOffsetDeg(_mode: NorthReferenceMode): number {
  243. return MAP_NORTH_OFFSET_DEG
  244. }
  245. function getCompassReferenceHeadingDeg(mode: NorthReferenceMode, magneticHeadingDeg: number): number {
  246. if (mode === 'true') {
  247. return getTrueHeadingDeg(magneticHeadingDeg)
  248. }
  249. return normalizeRotationDeg(magneticHeadingDeg)
  250. }
  251. function getMapReferenceHeadingDegFromSensor(mode: NorthReferenceMode, magneticHeadingDeg: number): number {
  252. if (mode === 'magnetic') {
  253. return normalizeRotationDeg(magneticHeadingDeg)
  254. }
  255. return getTrueHeadingDeg(magneticHeadingDeg)
  256. }
  257. function getMapReferenceHeadingDegFromCourse(mode: NorthReferenceMode, trueHeadingDeg: number): number {
  258. if (mode === 'magnetic') {
  259. return getMagneticHeadingDeg(trueHeadingDeg)
  260. }
  261. return normalizeRotationDeg(trueHeadingDeg)
  262. }
  263. function formatNorthReferenceText(mode: NorthReferenceMode): string {
  264. if (mode === 'magnetic') {
  265. return `Compass Magnetic / Heading-Up Magnetic (${MAGNETIC_DECLINATION_TEXT})`
  266. }
  267. return `Compass True / Heading-Up True (${MAGNETIC_DECLINATION_TEXT})`
  268. }
  269. function formatCompassDeclinationText(mode: NorthReferenceMode): string {
  270. if (mode === 'true') {
  271. return MAGNETIC_DECLINATION_TEXT
  272. }
  273. return ''
  274. }
  275. function formatNorthReferenceButtonText(mode: NorthReferenceMode): string {
  276. return mode === 'magnetic' ? '北参考:磁北' : '北参考:真北'
  277. }
  278. function formatNorthReferenceStatusText(mode: NorthReferenceMode): string {
  279. if (mode === 'magnetic') {
  280. return '已切到磁北模式'
  281. }
  282. return '已切到真北模式'
  283. }
  284. function getNextNorthReferenceMode(mode: NorthReferenceMode): NorthReferenceMode {
  285. return mode === 'magnetic' ? 'true' : 'magnetic'
  286. }
  287. function formatCompassNeedleDegForMode(mode: NorthReferenceMode, magneticHeadingDeg: number | null): number {
  288. if (magneticHeadingDeg === null) {
  289. return 0
  290. }
  291. const referenceHeadingDeg = mode === 'true'
  292. ? getTrueHeadingDeg(magneticHeadingDeg)
  293. : normalizeRotationDeg(magneticHeadingDeg)
  294. return normalizeRotationDeg(360 - referenceHeadingDeg)
  295. }
  296. function formatCacheHitRate(memoryHitCount: number, diskHitCount: number, networkFetchCount: number): string {
  297. const total = memoryHitCount + diskHitCount + networkFetchCount
  298. if (!total) {
  299. return '--'
  300. }
  301. const hitRate = ((memoryHitCount + diskHitCount) / total) * 100
  302. return `${Math.round(hitRate)}%`
  303. }
  304. function formatGpsCoordText(point: LonLatPoint | null, accuracyMeters: number | null): string {
  305. if (!point) {
  306. return '--'
  307. }
  308. const base = `${point.lat.toFixed(6)}, ${point.lon.toFixed(6)}`
  309. if (accuracyMeters === null || !Number.isFinite(accuracyMeters)) {
  310. return base
  311. }
  312. return `${base} / ±${Math.round(accuracyMeters)}m`
  313. }
  314. function getApproxDistanceMeters(a: LonLatPoint, b: LonLatPoint): number {
  315. const avgLatRad = ((a.lat + b.lat) / 2) * Math.PI / 180
  316. const dx = (b.lon - a.lon) * 111320 * Math.cos(avgLatRad)
  317. const dy = (b.lat - a.lat) * 110540
  318. return Math.sqrt(dx * dx + dy * dy)
  319. }
  320. export class MapEngine {
  321. buildVersion: string
  322. renderer: WebGLMapRenderer
  323. compassController: CompassHeadingController
  324. locationController: LocationController
  325. onData: (patch: Partial<MapEngineViewState>) => void
  326. state: MapEngineViewState
  327. previewScale: number
  328. previewOriginX: number
  329. previewOriginY: number
  330. panLastX: number
  331. panLastY: number
  332. panLastTimestamp: number
  333. panVelocityX: number
  334. panVelocityY: number
  335. pinchStartDistance: number
  336. pinchStartScale: number
  337. pinchStartAngle: number
  338. pinchStartRotationDeg: number
  339. pinchAnchorWorldX: number
  340. pinchAnchorWorldY: number
  341. gestureMode: GestureMode
  342. inertiaTimer: number
  343. previewResetTimer: number
  344. viewSyncTimer: number
  345. autoRotateTimer: number
  346. pendingViewPatch: Partial<MapEngineViewState>
  347. mounted: boolean
  348. northReferenceMode: NorthReferenceMode
  349. sensorHeadingDeg: number | null
  350. smoothedSensorHeadingDeg: number | null
  351. compassDisplayHeadingDeg: number | null
  352. autoRotateHeadingDeg: number | null
  353. courseHeadingDeg: number | null
  354. targetAutoRotationDeg: number | null
  355. autoRotateSourceMode: AutoRotateSourceMode
  356. autoRotateCalibrationOffsetDeg: number | null
  357. autoRotateCalibrationPending: boolean
  358. minZoom: number
  359. maxZoom: number
  360. defaultZoom: number
  361. defaultCenterTileX: number
  362. defaultCenterTileY: number
  363. tileBoundsByZoom: Record<number, TileZoomBounds> | null
  364. currentGpsPoint: LonLatPoint | null
  365. currentGpsTrack: LonLatPoint[]
  366. currentGpsAccuracyMeters: number | null
  367. hasGpsCenteredOnce: boolean
  368. constructor(buildVersion: string, callbacks: MapEngineCallbacks) {
  369. this.buildVersion = buildVersion
  370. this.onData = callbacks.onData
  371. this.renderer = new WebGLMapRenderer(
  372. (stats) => {
  373. this.applyStats(stats)
  374. },
  375. (message) => {
  376. this.setState({
  377. statusText: `${message} (${this.buildVersion})`,
  378. })
  379. },
  380. )
  381. this.compassController = new CompassHeadingController({
  382. onHeading: (headingDeg) => {
  383. this.handleCompassHeading(headingDeg)
  384. },
  385. onError: (message) => {
  386. this.handleCompassError(message)
  387. },
  388. })
  389. this.locationController = new LocationController({
  390. onLocation: (update) => {
  391. this.handleLocationUpdate(update.longitude, update.latitude, typeof update.accuracy === 'number' ? update.accuracy : null)
  392. },
  393. onStatus: (message) => {
  394. this.setState({
  395. gpsTracking: this.locationController.listening,
  396. gpsTrackingText: message,
  397. }, true)
  398. },
  399. onError: (message) => {
  400. this.setState({
  401. gpsTracking: false,
  402. gpsTrackingText: message,
  403. statusText: `${message} (${this.buildVersion})`,
  404. }, true)
  405. },
  406. })
  407. this.minZoom = MIN_ZOOM
  408. this.maxZoom = MAX_ZOOM
  409. this.defaultZoom = DEFAULT_ZOOM
  410. this.defaultCenterTileX = DEFAULT_CENTER_TILE_X
  411. this.defaultCenterTileY = DEFAULT_CENTER_TILE_Y
  412. this.tileBoundsByZoom = null
  413. this.currentGpsPoint = null
  414. this.currentGpsTrack = []
  415. this.currentGpsAccuracyMeters = null
  416. this.hasGpsCenteredOnce = false
  417. this.state = {
  418. buildVersion: this.buildVersion,
  419. renderMode: RENDER_MODE,
  420. projectionMode: PROJECTION_MODE,
  421. mapReady: false,
  422. mapReadyText: 'BOOTING',
  423. mapName: 'LCX 测试地图',
  424. configStatusText: '远程配置待加载',
  425. zoom: DEFAULT_ZOOM,
  426. rotationDeg: 0,
  427. rotationText: formatRotationText(0),
  428. rotationMode: 'manual',
  429. rotationModeText: formatRotationModeText('manual'),
  430. rotationToggleText: formatRotationToggleText('manual'),
  431. orientationMode: 'manual',
  432. orientationModeText: formatOrientationModeText('manual'),
  433. sensorHeadingText: '--',
  434. compassDeclinationText: formatCompassDeclinationText(DEFAULT_NORTH_REFERENCE_MODE),
  435. northReferenceButtonText: formatNorthReferenceButtonText(DEFAULT_NORTH_REFERENCE_MODE),
  436. autoRotateSourceText: formatAutoRotateSourceText('fusion', false),
  437. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, getMapNorthOffsetDeg(DEFAULT_NORTH_REFERENCE_MODE)),
  438. northReferenceText: formatNorthReferenceText(DEFAULT_NORTH_REFERENCE_MODE),
  439. compassNeedleDeg: 0,
  440. centerTileX: DEFAULT_CENTER_TILE_X,
  441. centerTileY: DEFAULT_CENTER_TILE_Y,
  442. centerText: buildCenterText(DEFAULT_ZOOM, DEFAULT_CENTER_TILE_X, DEFAULT_CENTER_TILE_Y),
  443. tileSource: TILE_SOURCE,
  444. visibleColumnCount: DESIRED_VISIBLE_COLUMNS,
  445. visibleTileCount: 0,
  446. readyTileCount: 0,
  447. memoryTileCount: 0,
  448. diskTileCount: 0,
  449. memoryHitCount: 0,
  450. diskHitCount: 0,
  451. networkFetchCount: 0,
  452. cacheHitRateText: '--',
  453. tileTranslateX: 0,
  454. tileTranslateY: 0,
  455. tileSizePx: 0,
  456. stageWidth: 0,
  457. stageHeight: 0,
  458. stageLeft: 0,
  459. stageTop: 0,
  460. statusText: `单 WebGL 管线已准备接入方向传感器 (${this.buildVersion})`,
  461. gpsTracking: false,
  462. gpsTrackingText: '持续定位待启动',
  463. gpsCoordText: '--',
  464. osmReferenceEnabled: false,
  465. osmReferenceText: 'OSM参考:关',
  466. }
  467. this.previewScale = 1
  468. this.previewOriginX = 0
  469. this.previewOriginY = 0
  470. this.panLastX = 0
  471. this.panLastY = 0
  472. this.panLastTimestamp = 0
  473. this.panVelocityX = 0
  474. this.panVelocityY = 0
  475. this.pinchStartDistance = 0
  476. this.pinchStartScale = 1
  477. this.pinchStartAngle = 0
  478. this.pinchStartRotationDeg = 0
  479. this.pinchAnchorWorldX = 0
  480. this.pinchAnchorWorldY = 0
  481. this.gestureMode = 'idle'
  482. this.inertiaTimer = 0
  483. this.previewResetTimer = 0
  484. this.viewSyncTimer = 0
  485. this.autoRotateTimer = 0
  486. this.pendingViewPatch = {}
  487. this.mounted = false
  488. this.northReferenceMode = DEFAULT_NORTH_REFERENCE_MODE
  489. this.sensorHeadingDeg = null
  490. this.smoothedSensorHeadingDeg = null
  491. this.compassDisplayHeadingDeg = null
  492. this.autoRotateHeadingDeg = null
  493. this.courseHeadingDeg = null
  494. this.targetAutoRotationDeg = null
  495. this.autoRotateSourceMode = 'fusion'
  496. this.autoRotateCalibrationOffsetDeg = getMapNorthOffsetDeg(DEFAULT_NORTH_REFERENCE_MODE)
  497. this.autoRotateCalibrationPending = false
  498. }
  499. getInitialData(): MapEngineViewState {
  500. return { ...this.state }
  501. }
  502. destroy(): void {
  503. this.clearInertiaTimer()
  504. this.clearPreviewResetTimer()
  505. this.clearViewSyncTimer()
  506. this.clearAutoRotateTimer()
  507. this.compassController.destroy()
  508. this.locationController.destroy()
  509. this.renderer.destroy()
  510. this.mounted = false
  511. }
  512. handleLocationUpdate(longitude: number, latitude: number, accuracyMeters: number | null): void {
  513. const nextPoint: LonLatPoint = { lon: longitude, lat: latitude }
  514. const lastTrackPoint = this.currentGpsTrack.length ? this.currentGpsTrack[this.currentGpsTrack.length - 1] : null
  515. if (!lastTrackPoint || getApproxDistanceMeters(lastTrackPoint, nextPoint) >= GPS_TRACK_MIN_STEP_METERS) {
  516. this.currentGpsTrack = [...this.currentGpsTrack, nextPoint].slice(-GPS_TRACK_MAX_POINTS)
  517. }
  518. this.currentGpsPoint = nextPoint
  519. this.currentGpsAccuracyMeters = accuracyMeters
  520. const gpsWorldPoint = lonLatToWorldTile(nextPoint, this.state.zoom)
  521. const gpsTileX = Math.floor(gpsWorldPoint.x)
  522. const gpsTileY = Math.floor(gpsWorldPoint.y)
  523. const gpsInsideMap = isTileWithinBounds(this.tileBoundsByZoom, this.state.zoom, gpsTileX, gpsTileY)
  524. if (gpsInsideMap && !this.hasGpsCenteredOnce) {
  525. this.hasGpsCenteredOnce = true
  526. this.commitViewport({
  527. centerTileX: gpsWorldPoint.x,
  528. centerTileY: gpsWorldPoint.y,
  529. tileTranslateX: 0,
  530. tileTranslateY: 0,
  531. gpsTracking: true,
  532. gpsTrackingText: '持续定位进行中',
  533. gpsCoordText: formatGpsCoordText(nextPoint, accuracyMeters),
  534. }, `GPS定位成功,已定位到当前位置 (${this.buildVersion})`, true)
  535. return
  536. }
  537. this.setState({
  538. gpsTracking: true,
  539. gpsTrackingText: gpsInsideMap ? '持续定位进行中' : 'GPS不在当前地图范围内',
  540. gpsCoordText: formatGpsCoordText(nextPoint, accuracyMeters),
  541. statusText: gpsInsideMap ? `GPS位置已更新 (${this.buildVersion})` : `GPS位置超出当前地图范围 (${this.buildVersion})`,
  542. }, true)
  543. this.syncRenderer()
  544. }
  545. handleToggleOsmReference(): void {
  546. const nextEnabled = !this.state.osmReferenceEnabled
  547. this.setState({
  548. osmReferenceEnabled: nextEnabled,
  549. osmReferenceText: nextEnabled ? 'OSM参考:开' : 'OSM参考:关',
  550. statusText: nextEnabled ? `OSM参考底图已开启 (${this.buildVersion})` : `OSM参考底图已关闭 (${this.buildVersion})`,
  551. }, true)
  552. this.syncRenderer()
  553. }
  554. handleToggleGpsTracking(): void {
  555. if (this.locationController.listening) {
  556. this.locationController.stop()
  557. return
  558. }
  559. this.locationController.start()
  560. }
  561. setStage(rect: MapEngineStageRect): void {
  562. this.previewScale = 1
  563. this.previewOriginX = rect.width / 2
  564. this.previewOriginY = rect.height / 2
  565. this.commitViewport(
  566. {
  567. stageWidth: rect.width,
  568. stageHeight: rect.height,
  569. stageLeft: rect.left,
  570. stageTop: rect.top,
  571. },
  572. `地图视口与 WebGL 引擎已对齐 (${this.buildVersion})`,
  573. true,
  574. )
  575. }
  576. attachCanvas(canvasNode: any, width: number, height: number, dpr: number): void {
  577. this.renderer.attachCanvas(canvasNode, width, height, dpr)
  578. this.mounted = true
  579. this.state.mapReady = true
  580. this.state.mapReadyText = 'READY'
  581. this.onData({
  582. mapReady: true,
  583. mapReadyText: 'READY',
  584. statusText: `单 WebGL 管线已就绪,可切换手动或自动朝向 (${this.buildVersion})`,
  585. })
  586. this.syncRenderer()
  587. this.compassController.start()
  588. }
  589. applyRemoteMapConfig(config: RemoteMapConfig): void {
  590. MAGNETIC_DECLINATION_DEG = config.magneticDeclinationDeg
  591. MAGNETIC_DECLINATION_TEXT = config.magneticDeclinationText
  592. this.minZoom = config.minZoom
  593. this.maxZoom = config.maxZoom
  594. this.defaultZoom = config.defaultZoom
  595. this.defaultCenterTileX = config.initialCenterTileX
  596. this.defaultCenterTileY = config.initialCenterTileY
  597. this.tileBoundsByZoom = config.tileBoundsByZoom
  598. const statePatch: Partial<MapEngineViewState> = {
  599. configStatusText: '远程配置已载入',
  600. projectionMode: config.projectionModeText,
  601. tileSource: config.tileSource,
  602. sensorHeadingText: formatHeadingText(this.smoothedSensorHeadingDeg === null ? null : getCompassReferenceHeadingDeg(this.northReferenceMode, this.smoothedSensorHeadingDeg)),
  603. compassDeclinationText: formatCompassDeclinationText(this.northReferenceMode),
  604. northReferenceButtonText: formatNorthReferenceButtonText(this.northReferenceMode),
  605. northReferenceText: formatNorthReferenceText(this.northReferenceMode),
  606. compassNeedleDeg: formatCompassNeedleDegForMode(this.northReferenceMode, this.smoothedSensorHeadingDeg),
  607. }
  608. if (!this.state.stageWidth || !this.state.stageHeight) {
  609. this.setState({
  610. ...statePatch,
  611. zoom: this.defaultZoom,
  612. centerTileX: this.defaultCenterTileX,
  613. centerTileY: this.defaultCenterTileY,
  614. centerText: buildCenterText(this.defaultZoom, this.defaultCenterTileX, this.defaultCenterTileY),
  615. statusText: `远程地图配置已载入 (${this.buildVersion})`,
  616. }, true)
  617. return
  618. }
  619. this.commitViewport({
  620. ...statePatch,
  621. zoom: this.defaultZoom,
  622. centerTileX: this.defaultCenterTileX,
  623. centerTileY: this.defaultCenterTileY,
  624. tileTranslateX: 0,
  625. tileTranslateY: 0,
  626. }, `远程地图配置已载入 (${this.buildVersion})`, true, () => {
  627. this.resetPreviewState()
  628. this.syncRenderer()
  629. if (this.state.orientationMode === 'heading-up' && this.refreshAutoRotateTarget()) {
  630. this.scheduleAutoRotate()
  631. }
  632. })
  633. }
  634. handleTouchStart(event: WechatMiniprogram.TouchEvent): void {
  635. this.clearInertiaTimer()
  636. this.clearPreviewResetTimer()
  637. this.renderer.setAnimationPaused(true)
  638. this.panVelocityX = 0
  639. this.panVelocityY = 0
  640. if (event.touches.length >= 2) {
  641. const origin = this.getStagePoint(event.touches)
  642. this.gestureMode = 'pinch'
  643. this.pinchStartDistance = this.getTouchDistance(event.touches)
  644. this.pinchStartScale = this.previewScale || 1
  645. this.pinchStartAngle = this.getTouchAngle(event.touches)
  646. this.pinchStartRotationDeg = this.state.rotationDeg
  647. const anchorWorld = screenToWorld(this.getCameraState(), origin, true)
  648. this.pinchAnchorWorldX = anchorWorld.x
  649. this.pinchAnchorWorldY = anchorWorld.y
  650. this.setPreviewState(this.pinchStartScale, origin.x, origin.y)
  651. this.syncRenderer()
  652. this.compassController.start()
  653. return
  654. }
  655. if (event.touches.length === 1) {
  656. this.gestureMode = 'pan'
  657. this.panLastX = event.touches[0].pageX
  658. this.panLastY = event.touches[0].pageY
  659. this.panLastTimestamp = event.timeStamp || Date.now()
  660. }
  661. }
  662. handleTouchMove(event: WechatMiniprogram.TouchEvent): void {
  663. if (event.touches.length >= 2) {
  664. const distance = this.getTouchDistance(event.touches)
  665. const angle = this.getTouchAngle(event.touches)
  666. const origin = this.getStagePoint(event.touches)
  667. if (!this.pinchStartDistance) {
  668. this.pinchStartDistance = distance
  669. this.pinchStartScale = this.previewScale || 1
  670. this.pinchStartAngle = angle
  671. this.pinchStartRotationDeg = this.state.rotationDeg
  672. const anchorWorld = screenToWorld(this.getCameraState(), origin, true)
  673. this.pinchAnchorWorldX = anchorWorld.x
  674. this.pinchAnchorWorldY = anchorWorld.y
  675. }
  676. this.gestureMode = 'pinch'
  677. const nextRotationDeg = this.state.orientationMode === 'heading-up'
  678. ? this.state.rotationDeg
  679. : normalizeRotationDeg(this.pinchStartRotationDeg + normalizeAngleDeltaRad(angle - this.pinchStartAngle) * 180 / Math.PI)
  680. const anchorOffset = this.getWorldOffsetFromScreen(origin.x, origin.y, nextRotationDeg)
  681. const resolvedViewport = this.resolveViewportForExactCenter(
  682. this.pinchAnchorWorldX - anchorOffset.x,
  683. this.pinchAnchorWorldY - anchorOffset.y,
  684. nextRotationDeg,
  685. )
  686. this.setPreviewState(
  687. clamp(this.pinchStartScale * (distance / this.pinchStartDistance), MIN_PREVIEW_SCALE, MAX_PREVIEW_SCALE),
  688. origin.x,
  689. origin.y,
  690. )
  691. this.commitViewport(
  692. {
  693. ...resolvedViewport,
  694. rotationDeg: nextRotationDeg,
  695. rotationText: formatRotationText(nextRotationDeg),
  696. },
  697. this.state.orientationMode === 'heading-up'
  698. ? `双指缩放中,自动朝向保持开启 (${this.buildVersion})`
  699. : `双指缩放与旋转中 (${this.buildVersion})`,
  700. )
  701. return
  702. }
  703. if (this.gestureMode !== 'pan' || event.touches.length !== 1) {
  704. return
  705. }
  706. const touch = event.touches[0]
  707. const deltaX = touch.pageX - this.panLastX
  708. const deltaY = touch.pageY - this.panLastY
  709. const nextTimestamp = event.timeStamp || Date.now()
  710. const elapsed = Math.max(nextTimestamp - this.panLastTimestamp, 16)
  711. const instantVelocityX = deltaX / elapsed
  712. const instantVelocityY = deltaY / elapsed
  713. this.panVelocityX = this.panVelocityX * 0.72 + instantVelocityX * 0.28
  714. this.panVelocityY = this.panVelocityY * 0.72 + instantVelocityY * 0.28
  715. this.panLastX = touch.pageX
  716. this.panLastY = touch.pageY
  717. this.panLastTimestamp = nextTimestamp
  718. this.normalizeTranslate(
  719. this.state.tileTranslateX + deltaX,
  720. this.state.tileTranslateY + deltaY,
  721. `已拖拽单 WebGL 地图引擎 (${this.buildVersion})`,
  722. )
  723. }
  724. handleTouchEnd(event: WechatMiniprogram.TouchEvent): void {
  725. if (this.gestureMode === 'pinch' && event.touches.length < 2) {
  726. const gestureScale = this.previewScale || 1
  727. const zoomDelta = Math.round(Math.log2(gestureScale))
  728. const originX = this.previewOriginX || this.state.stageWidth / 2
  729. const originY = this.previewOriginY || this.state.stageHeight / 2
  730. if (zoomDelta) {
  731. const residualScale = gestureScale / Math.pow(2, zoomDelta)
  732. this.zoomAroundPoint(zoomDelta, originX, originY, residualScale)
  733. } else {
  734. this.animatePreviewToRest()
  735. }
  736. this.resetPinchState()
  737. this.panVelocityX = 0
  738. this.panVelocityY = 0
  739. if (event.touches.length === 1) {
  740. this.gestureMode = 'pan'
  741. this.panLastX = event.touches[0].pageX
  742. this.panLastY = event.touches[0].pageY
  743. this.panLastTimestamp = event.timeStamp || Date.now()
  744. return
  745. }
  746. this.gestureMode = 'idle'
  747. this.renderer.setAnimationPaused(false)
  748. this.scheduleAutoRotate()
  749. return
  750. }
  751. if (event.touches.length === 1) {
  752. this.gestureMode = 'pan'
  753. this.panLastX = event.touches[0].pageX
  754. this.panLastY = event.touches[0].pageY
  755. this.panLastTimestamp = event.timeStamp || Date.now()
  756. return
  757. }
  758. if (this.gestureMode === 'pan' && (Math.abs(this.panVelocityX) >= INERTIA_MIN_SPEED || Math.abs(this.panVelocityY) >= INERTIA_MIN_SPEED)) {
  759. this.startInertia()
  760. this.gestureMode = 'idle'
  761. this.resetPinchState()
  762. return
  763. }
  764. this.gestureMode = 'idle'
  765. this.resetPinchState()
  766. this.renderer.setAnimationPaused(false)
  767. this.scheduleAutoRotate()
  768. }
  769. handleTouchCancel(): void {
  770. this.gestureMode = 'idle'
  771. this.resetPinchState()
  772. this.panVelocityX = 0
  773. this.panVelocityY = 0
  774. this.clearInertiaTimer()
  775. this.animatePreviewToRest()
  776. this.renderer.setAnimationPaused(false)
  777. this.scheduleAutoRotate()
  778. }
  779. handleRecenter(): void {
  780. this.clearInertiaTimer()
  781. this.clearPreviewResetTimer()
  782. this.panVelocityX = 0
  783. this.panVelocityY = 0
  784. this.renderer.setAnimationPaused(false)
  785. this.commitViewport(
  786. {
  787. zoom: this.defaultZoom,
  788. centerTileX: this.defaultCenterTileX,
  789. centerTileY: this.defaultCenterTileY,
  790. tileTranslateX: 0,
  791. tileTranslateY: 0,
  792. },
  793. `已回到单 WebGL 引擎默认首屏 (${this.buildVersion})`,
  794. true,
  795. () => {
  796. this.resetPreviewState()
  797. this.syncRenderer()
  798. this.compassController.start()
  799. this.scheduleAutoRotate()
  800. },
  801. )
  802. }
  803. handleRotateStep(stepDeg = ROTATE_STEP_DEG): void {
  804. if (this.state.rotationMode === 'auto') {
  805. this.setState({
  806. statusText: `当前不是手动旋转模式,请先切回手动 (${this.buildVersion})`,
  807. }, true)
  808. return
  809. }
  810. const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
  811. const nextRotationDeg = normalizeRotationDeg(this.state.rotationDeg + stepDeg)
  812. const resolvedViewport = this.resolveViewportForExactCenter(exactCenter.x, exactCenter.y, nextRotationDeg)
  813. this.clearInertiaTimer()
  814. this.clearPreviewResetTimer()
  815. this.panVelocityX = 0
  816. this.panVelocityY = 0
  817. this.renderer.setAnimationPaused(false)
  818. this.commitViewport(
  819. {
  820. ...resolvedViewport,
  821. rotationDeg: nextRotationDeg,
  822. rotationText: formatRotationText(nextRotationDeg),
  823. },
  824. `旋转角度调整到 ${formatRotationText(nextRotationDeg)} (${this.buildVersion})`,
  825. true,
  826. () => {
  827. this.resetPreviewState()
  828. this.syncRenderer()
  829. this.compassController.start()
  830. },
  831. )
  832. }
  833. handleRotationReset(): void {
  834. if (this.state.rotationMode === 'auto') {
  835. this.setState({
  836. statusText: `当前不是手动旋转模式,请先切回手动 (${this.buildVersion})`,
  837. }, true)
  838. return
  839. }
  840. const targetRotationDeg = MAP_NORTH_OFFSET_DEG
  841. if (Math.abs(normalizeAngleDeltaDeg(this.state.rotationDeg - targetRotationDeg)) <= 0.01) {
  842. return
  843. }
  844. const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
  845. const resolvedViewport = this.resolveViewportForExactCenter(exactCenter.x, exactCenter.y, targetRotationDeg)
  846. this.clearInertiaTimer()
  847. this.clearPreviewResetTimer()
  848. this.panVelocityX = 0
  849. this.panVelocityY = 0
  850. this.renderer.setAnimationPaused(false)
  851. this.commitViewport(
  852. {
  853. ...resolvedViewport,
  854. rotationDeg: targetRotationDeg,
  855. rotationText: formatRotationText(targetRotationDeg),
  856. },
  857. `旋转角度已回到真北参考 (${this.buildVersion})`,
  858. true,
  859. () => {
  860. this.resetPreviewState()
  861. this.syncRenderer()
  862. this.compassController.start()
  863. },
  864. )
  865. }
  866. handleToggleRotationMode(): void {
  867. if (this.state.orientationMode === 'manual') {
  868. this.setNorthUpMode()
  869. return
  870. }
  871. if (this.state.orientationMode === 'north-up') {
  872. this.setHeadingUpMode()
  873. return
  874. }
  875. this.setManualMode()
  876. }
  877. handleSetManualMode(): void {
  878. this.setManualMode()
  879. }
  880. handleSetNorthUpMode(): void {
  881. this.setNorthUpMode()
  882. }
  883. handleSetHeadingUpMode(): void {
  884. this.setHeadingUpMode()
  885. }
  886. handleCycleNorthReferenceMode(): void {
  887. this.cycleNorthReferenceMode()
  888. }
  889. handleAutoRotateCalibrate(): void {
  890. if (this.state.orientationMode !== 'heading-up') {
  891. this.setState({
  892. statusText: `请先切到朝向朝上模式再校准 (${this.buildVersion})`,
  893. }, true)
  894. return
  895. }
  896. if (!this.calibrateAutoRotateToCurrentOrientation()) {
  897. this.setState({
  898. statusText: `当前还没有传感器方向数据,暂时无法校准 (${this.buildVersion})`,
  899. }, true)
  900. return
  901. }
  902. this.setState({
  903. statusText: `已按当前持机方向完成朝向校准 (${this.buildVersion})`,
  904. }, true)
  905. this.scheduleAutoRotate()
  906. }
  907. setManualMode(): void {
  908. this.clearAutoRotateTimer()
  909. this.targetAutoRotationDeg = null
  910. this.autoRotateCalibrationPending = false
  911. this.setState({
  912. rotationMode: 'manual',
  913. rotationModeText: formatRotationModeText('manual'),
  914. rotationToggleText: formatRotationToggleText('manual'),
  915. orientationMode: 'manual',
  916. orientationModeText: formatOrientationModeText('manual'),
  917. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, this.autoRotateCalibrationOffsetDeg),
  918. statusText: `已切回手动地图旋转 (${this.buildVersion})`,
  919. }, true)
  920. }
  921. setNorthUpMode(): void {
  922. this.clearAutoRotateTimer()
  923. this.targetAutoRotationDeg = null
  924. this.autoRotateCalibrationPending = false
  925. const mapNorthOffsetDeg = MAP_NORTH_OFFSET_DEG
  926. this.autoRotateCalibrationOffsetDeg = mapNorthOffsetDeg
  927. const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
  928. const resolvedViewport = this.resolveViewportForExactCenter(exactCenter.x, exactCenter.y, mapNorthOffsetDeg)
  929. this.commitViewport(
  930. {
  931. ...resolvedViewport,
  932. rotationDeg: mapNorthOffsetDeg,
  933. rotationText: formatRotationText(mapNorthOffsetDeg),
  934. rotationMode: 'manual',
  935. rotationModeText: formatRotationModeText('north-up'),
  936. rotationToggleText: formatRotationToggleText('north-up'),
  937. orientationMode: 'north-up',
  938. orientationModeText: formatOrientationModeText('north-up'),
  939. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, mapNorthOffsetDeg),
  940. northReferenceText: formatNorthReferenceText(this.northReferenceMode),
  941. },
  942. `地图已固定为真北朝上 (${this.buildVersion})`,
  943. true,
  944. () => {
  945. this.resetPreviewState()
  946. this.syncRenderer()
  947. },
  948. )
  949. }
  950. setHeadingUpMode(): void {
  951. this.autoRotateCalibrationPending = false
  952. this.autoRotateCalibrationOffsetDeg = getMapNorthOffsetDeg(this.northReferenceMode)
  953. this.targetAutoRotationDeg = null
  954. this.setState({
  955. rotationMode: 'auto',
  956. rotationModeText: formatRotationModeText('heading-up'),
  957. rotationToggleText: formatRotationToggleText('heading-up'),
  958. orientationMode: 'heading-up',
  959. orientationModeText: formatOrientationModeText('heading-up'),
  960. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, this.autoRotateCalibrationOffsetDeg),
  961. northReferenceText: formatNorthReferenceText(this.northReferenceMode),
  962. statusText: `正在启用朝向朝上模式 (${this.buildVersion})`,
  963. }, true)
  964. if (this.refreshAutoRotateTarget()) {
  965. this.scheduleAutoRotate()
  966. }
  967. }
  968. handleCompassHeading(headingDeg: number): void {
  969. this.sensorHeadingDeg = normalizeRotationDeg(headingDeg)
  970. this.smoothedSensorHeadingDeg = this.smoothedSensorHeadingDeg === null
  971. ? this.sensorHeadingDeg
  972. : interpolateAngleDeg(this.smoothedSensorHeadingDeg, this.sensorHeadingDeg, AUTO_ROTATE_HEADING_SMOOTHING)
  973. const compassHeadingDeg = getCompassReferenceHeadingDeg(this.northReferenceMode, this.smoothedSensorHeadingDeg)
  974. this.compassDisplayHeadingDeg = this.compassDisplayHeadingDeg === null
  975. ? compassHeadingDeg
  976. : interpolateAngleDeg(this.compassDisplayHeadingDeg, compassHeadingDeg, COMPASS_NEEDLE_SMOOTHING)
  977. this.autoRotateHeadingDeg = this.resolveAutoRotateInputHeadingDeg()
  978. this.setState({
  979. sensorHeadingText: formatHeadingText(compassHeadingDeg),
  980. compassDeclinationText: formatCompassDeclinationText(this.northReferenceMode),
  981. northReferenceButtonText: formatNorthReferenceButtonText(this.northReferenceMode),
  982. autoRotateSourceText: formatAutoRotateSourceText(this.autoRotateSourceMode, this.courseHeadingDeg !== null),
  983. compassNeedleDeg: formatCompassNeedleDegForMode(this.northReferenceMode, this.smoothedSensorHeadingDeg),
  984. northReferenceText: formatNorthReferenceText(this.northReferenceMode),
  985. })
  986. if (!this.refreshAutoRotateTarget()) {
  987. return
  988. }
  989. if (this.state.orientationMode === 'heading-up') {
  990. this.scheduleAutoRotate()
  991. }
  992. }
  993. handleCompassError(message: string): void {
  994. this.clearAutoRotateTimer()
  995. this.targetAutoRotationDeg = null
  996. this.autoRotateCalibrationPending = false
  997. this.setState({
  998. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, this.autoRotateCalibrationOffsetDeg),
  999. statusText: `${message} (${this.buildVersion})`,
  1000. }, true)
  1001. }
  1002. cycleNorthReferenceMode(): void {
  1003. const nextMode = getNextNorthReferenceMode(this.northReferenceMode)
  1004. const nextMapNorthOffsetDeg = getMapNorthOffsetDeg(nextMode)
  1005. const compassHeadingDeg = this.smoothedSensorHeadingDeg === null
  1006. ? null
  1007. : getCompassReferenceHeadingDeg(nextMode, this.smoothedSensorHeadingDeg)
  1008. this.northReferenceMode = nextMode
  1009. this.autoRotateCalibrationOffsetDeg = nextMapNorthOffsetDeg
  1010. this.compassDisplayHeadingDeg = compassHeadingDeg
  1011. if (this.state.orientationMode === 'north-up') {
  1012. const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
  1013. const resolvedViewport = this.resolveViewportForExactCenter(exactCenter.x, exactCenter.y, MAP_NORTH_OFFSET_DEG)
  1014. this.commitViewport(
  1015. {
  1016. ...resolvedViewport,
  1017. rotationDeg: MAP_NORTH_OFFSET_DEG,
  1018. rotationText: formatRotationText(MAP_NORTH_OFFSET_DEG),
  1019. northReferenceText: formatNorthReferenceText(nextMode),
  1020. sensorHeadingText: formatHeadingText(compassHeadingDeg),
  1021. compassDeclinationText: formatCompassDeclinationText(nextMode),
  1022. northReferenceButtonText: formatNorthReferenceButtonText(nextMode),
  1023. compassNeedleDeg: formatCompassNeedleDegForMode(nextMode, this.smoothedSensorHeadingDeg),
  1024. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, nextMapNorthOffsetDeg),
  1025. },
  1026. `${formatNorthReferenceStatusText(nextMode)} (${this.buildVersion})`,
  1027. true,
  1028. () => {
  1029. this.resetPreviewState()
  1030. this.syncRenderer()
  1031. },
  1032. )
  1033. return
  1034. }
  1035. this.setState({
  1036. northReferenceText: formatNorthReferenceText(nextMode),
  1037. sensorHeadingText: formatHeadingText(compassHeadingDeg),
  1038. compassDeclinationText: formatCompassDeclinationText(nextMode),
  1039. northReferenceButtonText: formatNorthReferenceButtonText(nextMode),
  1040. compassNeedleDeg: formatCompassNeedleDegForMode(nextMode, this.smoothedSensorHeadingDeg),
  1041. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, nextMapNorthOffsetDeg),
  1042. statusText: `${formatNorthReferenceStatusText(nextMode)} (${this.buildVersion})`,
  1043. }, true)
  1044. if (this.state.orientationMode === 'heading-up' && this.refreshAutoRotateTarget()) {
  1045. this.scheduleAutoRotate()
  1046. }
  1047. }
  1048. setCourseHeading(headingDeg: number | null): void {
  1049. this.courseHeadingDeg = headingDeg === null ? null : normalizeRotationDeg(headingDeg)
  1050. this.setState({
  1051. autoRotateSourceText: formatAutoRotateSourceText(this.autoRotateSourceMode, this.courseHeadingDeg !== null),
  1052. })
  1053. if (this.refreshAutoRotateTarget()) {
  1054. this.scheduleAutoRotate()
  1055. }
  1056. }
  1057. resolveAutoRotateInputHeadingDeg(): number | null {
  1058. const sensorHeadingDeg = this.smoothedSensorHeadingDeg === null
  1059. ? null
  1060. : getMapReferenceHeadingDegFromSensor(this.northReferenceMode, this.smoothedSensorHeadingDeg)
  1061. const courseHeadingDeg = this.courseHeadingDeg === null
  1062. ? null
  1063. : getMapReferenceHeadingDegFromCourse(this.northReferenceMode, this.courseHeadingDeg)
  1064. if (this.autoRotateSourceMode === 'sensor') {
  1065. return sensorHeadingDeg
  1066. }
  1067. if (this.autoRotateSourceMode === 'course') {
  1068. return courseHeadingDeg === null ? sensorHeadingDeg : courseHeadingDeg
  1069. }
  1070. if (sensorHeadingDeg !== null && courseHeadingDeg !== null) {
  1071. return interpolateAngleDeg(sensorHeadingDeg, courseHeadingDeg, 0.35)
  1072. }
  1073. return sensorHeadingDeg === null ? courseHeadingDeg : sensorHeadingDeg
  1074. }
  1075. calibrateAutoRotateToCurrentOrientation(): boolean {
  1076. const inputHeadingDeg = this.resolveAutoRotateInputHeadingDeg()
  1077. if (inputHeadingDeg === null) {
  1078. return false
  1079. }
  1080. this.autoRotateCalibrationOffsetDeg = normalizeRotationDeg(this.state.rotationDeg + inputHeadingDeg)
  1081. this.autoRotateCalibrationPending = false
  1082. this.targetAutoRotationDeg = normalizeRotationDeg(this.autoRotateCalibrationOffsetDeg - inputHeadingDeg)
  1083. this.setState({
  1084. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, this.autoRotateCalibrationOffsetDeg),
  1085. })
  1086. return true
  1087. }
  1088. refreshAutoRotateTarget(): boolean {
  1089. const inputHeadingDeg = this.resolveAutoRotateInputHeadingDeg()
  1090. if (inputHeadingDeg === null) {
  1091. return false
  1092. }
  1093. if (this.autoRotateCalibrationPending || this.autoRotateCalibrationOffsetDeg === null) {
  1094. if (!this.calibrateAutoRotateToCurrentOrientation()) {
  1095. return false
  1096. }
  1097. return true
  1098. }
  1099. this.targetAutoRotationDeg = normalizeRotationDeg(this.autoRotateCalibrationOffsetDeg - inputHeadingDeg)
  1100. this.setState({
  1101. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, this.autoRotateCalibrationOffsetDeg),
  1102. })
  1103. return true
  1104. }
  1105. scheduleAutoRotate(): void {
  1106. if (this.autoRotateTimer || this.state.rotationMode !== 'auto' || this.targetAutoRotationDeg === null) {
  1107. return
  1108. }
  1109. const step = () => {
  1110. this.autoRotateTimer = 0
  1111. if (this.state.rotationMode !== 'auto' || this.targetAutoRotationDeg === null) {
  1112. return
  1113. }
  1114. if (this.gestureMode !== 'idle' || this.inertiaTimer || this.previewResetTimer) {
  1115. this.scheduleAutoRotate()
  1116. return
  1117. }
  1118. const currentRotationDeg = this.state.rotationDeg
  1119. const deltaDeg = normalizeAngleDeltaDeg(this.targetAutoRotationDeg - currentRotationDeg)
  1120. if (Math.abs(deltaDeg) <= AUTO_ROTATE_SNAP_DEG) {
  1121. if (Math.abs(deltaDeg) > 0.01) {
  1122. this.applyAutoRotation(this.targetAutoRotationDeg)
  1123. }
  1124. this.scheduleAutoRotate()
  1125. return
  1126. }
  1127. if (Math.abs(deltaDeg) <= AUTO_ROTATE_DEADZONE_DEG) {
  1128. this.scheduleAutoRotate()
  1129. return
  1130. }
  1131. const easedStepDeg = clamp(deltaDeg * AUTO_ROTATE_EASE, -AUTO_ROTATE_MAX_STEP_DEG, AUTO_ROTATE_MAX_STEP_DEG)
  1132. this.applyAutoRotation(normalizeRotationDeg(currentRotationDeg + easedStepDeg))
  1133. this.scheduleAutoRotate()
  1134. }
  1135. this.autoRotateTimer = setTimeout(step, AUTO_ROTATE_FRAME_MS) as unknown as number
  1136. }
  1137. applyAutoRotation(nextRotationDeg: number): void {
  1138. const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
  1139. const resolvedViewport = this.resolveViewportForExactCenter(exactCenter.x, exactCenter.y, nextRotationDeg)
  1140. this.setState({
  1141. ...resolvedViewport,
  1142. rotationDeg: nextRotationDeg,
  1143. rotationText: formatRotationText(nextRotationDeg),
  1144. centerText: buildCenterText(this.state.zoom, resolvedViewport.centerTileX, resolvedViewport.centerTileY),
  1145. })
  1146. this.syncRenderer()
  1147. }
  1148. applyStats(stats: MapRendererStats): void {
  1149. this.setState({
  1150. visibleTileCount: stats.visibleTileCount,
  1151. readyTileCount: stats.readyTileCount,
  1152. memoryTileCount: stats.memoryTileCount,
  1153. diskTileCount: stats.diskTileCount,
  1154. memoryHitCount: stats.memoryHitCount,
  1155. diskHitCount: stats.diskHitCount,
  1156. networkFetchCount: stats.networkFetchCount,
  1157. cacheHitRateText: formatCacheHitRate(stats.memoryHitCount, stats.diskHitCount, stats.networkFetchCount),
  1158. })
  1159. }
  1160. setState(patch: Partial<MapEngineViewState>, immediateUi = false): void {
  1161. this.state = {
  1162. ...this.state,
  1163. ...patch,
  1164. }
  1165. const viewPatch = this.pickViewPatch(patch)
  1166. if (!Object.keys(viewPatch).length) {
  1167. return
  1168. }
  1169. this.pendingViewPatch = {
  1170. ...this.pendingViewPatch,
  1171. ...viewPatch,
  1172. }
  1173. if (immediateUi) {
  1174. this.flushViewPatch()
  1175. return
  1176. }
  1177. if (this.viewSyncTimer) {
  1178. return
  1179. }
  1180. this.viewSyncTimer = setTimeout(() => {
  1181. this.viewSyncTimer = 0
  1182. this.flushViewPatch()
  1183. }, UI_SYNC_INTERVAL_MS) as unknown as number
  1184. }
  1185. commitViewport(
  1186. patch: Partial<MapEngineViewState>,
  1187. statusText: string,
  1188. immediateUi = false,
  1189. afterUpdate?: () => void,
  1190. ): void {
  1191. const nextZoom = typeof patch.zoom === 'number' ? patch.zoom : this.state.zoom
  1192. const nextCenterTileX = typeof patch.centerTileX === 'number' ? patch.centerTileX : this.state.centerTileX
  1193. const nextCenterTileY = typeof patch.centerTileY === 'number' ? patch.centerTileY : this.state.centerTileY
  1194. const nextStageWidth = typeof patch.stageWidth === 'number' ? patch.stageWidth : this.state.stageWidth
  1195. const nextStageHeight = typeof patch.stageHeight === 'number' ? patch.stageHeight : this.state.stageHeight
  1196. const tileSizePx = getTileSizePx({
  1197. centerWorldX: nextCenterTileX,
  1198. centerWorldY: nextCenterTileY,
  1199. viewportWidth: nextStageWidth,
  1200. viewportHeight: nextStageHeight,
  1201. visibleColumns: DESIRED_VISIBLE_COLUMNS,
  1202. })
  1203. this.setState({
  1204. ...patch,
  1205. tileSizePx,
  1206. centerText: buildCenterText(nextZoom, nextCenterTileX, nextCenterTileY),
  1207. statusText,
  1208. }, immediateUi)
  1209. this.syncRenderer()
  1210. this.compassController.start()
  1211. if (afterUpdate) {
  1212. afterUpdate()
  1213. }
  1214. }
  1215. buildScene() {
  1216. const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
  1217. return {
  1218. tileSource: this.state.tileSource,
  1219. osmTileSource: OSM_TILE_SOURCE,
  1220. zoom: this.state.zoom,
  1221. centerTileX: this.state.centerTileX,
  1222. centerTileY: this.state.centerTileY,
  1223. exactCenterWorldX: exactCenter.x,
  1224. exactCenterWorldY: exactCenter.y,
  1225. tileBoundsByZoom: this.tileBoundsByZoom,
  1226. viewportWidth: this.state.stageWidth,
  1227. viewportHeight: this.state.stageHeight,
  1228. visibleColumns: DESIRED_VISIBLE_COLUMNS,
  1229. overdraw: OVERDRAW,
  1230. translateX: this.state.tileTranslateX,
  1231. translateY: this.state.tileTranslateY,
  1232. rotationRad: this.getRotationRad(this.state.rotationDeg),
  1233. previewScale: this.previewScale || 1,
  1234. previewOriginX: this.previewOriginX || this.state.stageWidth / 2,
  1235. previewOriginY: this.previewOriginY || this.state.stageHeight / 2,
  1236. track: this.currentGpsTrack,
  1237. gpsPoint: this.currentGpsPoint,
  1238. gpsCalibration: GPS_MAP_CALIBRATION,
  1239. gpsCalibrationOrigin: worldTileToLonLat({ x: this.defaultCenterTileX, y: this.defaultCenterTileY }, this.defaultZoom),
  1240. osmReferenceEnabled: this.state.osmReferenceEnabled,
  1241. overlayOpacity: MAP_OVERLAY_OPACITY,
  1242. }
  1243. }
  1244. syncRenderer(): void {
  1245. if (!this.mounted || !this.state.stageWidth || !this.state.stageHeight) {
  1246. return
  1247. }
  1248. this.renderer.updateScene(this.buildScene())
  1249. }
  1250. getCameraState(rotationDeg = this.state.rotationDeg): CameraState {
  1251. return {
  1252. centerWorldX: this.state.centerTileX + 0.5,
  1253. centerWorldY: this.state.centerTileY + 0.5,
  1254. viewportWidth: this.state.stageWidth,
  1255. viewportHeight: this.state.stageHeight,
  1256. visibleColumns: DESIRED_VISIBLE_COLUMNS,
  1257. translateX: this.state.tileTranslateX,
  1258. translateY: this.state.tileTranslateY,
  1259. rotationRad: this.getRotationRad(rotationDeg),
  1260. }
  1261. }
  1262. getRotationRad(rotationDeg = this.state.rotationDeg): number {
  1263. return normalizeRotationDeg(rotationDeg) * Math.PI / 180
  1264. }
  1265. getBaseCamera(centerTileX = this.state.centerTileX, centerTileY = this.state.centerTileY, rotationDeg = this.state.rotationDeg): CameraState {
  1266. return {
  1267. centerWorldX: centerTileX + 0.5,
  1268. centerWorldY: centerTileY + 0.5,
  1269. viewportWidth: this.state.stageWidth,
  1270. viewportHeight: this.state.stageHeight,
  1271. visibleColumns: DESIRED_VISIBLE_COLUMNS,
  1272. rotationRad: this.getRotationRad(rotationDeg),
  1273. }
  1274. }
  1275. getWorldOffsetFromScreen(stageX: number, stageY: number, rotationDeg = this.state.rotationDeg): { x: number; y: number } {
  1276. const baseCamera = {
  1277. centerWorldX: 0,
  1278. centerWorldY: 0,
  1279. viewportWidth: this.state.stageWidth,
  1280. viewportHeight: this.state.stageHeight,
  1281. visibleColumns: DESIRED_VISIBLE_COLUMNS,
  1282. rotationRad: this.getRotationRad(rotationDeg),
  1283. }
  1284. return screenToWorld(baseCamera, { x: stageX, y: stageY }, false)
  1285. }
  1286. getExactCenterFromTranslate(translateX: number, translateY: number): { x: number; y: number } {
  1287. if (!this.state.stageWidth || !this.state.stageHeight) {
  1288. return {
  1289. x: this.state.centerTileX + 0.5,
  1290. y: this.state.centerTileY + 0.5,
  1291. }
  1292. }
  1293. const screenCenterX = this.state.stageWidth / 2
  1294. const screenCenterY = this.state.stageHeight / 2
  1295. return screenToWorld(this.getBaseCamera(), {
  1296. x: screenCenterX - translateX,
  1297. y: screenCenterY - translateY,
  1298. }, false)
  1299. }
  1300. resolveViewportForExactCenter(centerWorldX: number, centerWorldY: number, rotationDeg = this.state.rotationDeg): {
  1301. centerTileX: number
  1302. centerTileY: number
  1303. tileTranslateX: number
  1304. tileTranslateY: number
  1305. } {
  1306. const nextCenterTileX = Math.floor(centerWorldX)
  1307. const nextCenterTileY = Math.floor(centerWorldY)
  1308. if (!this.state.stageWidth || !this.state.stageHeight) {
  1309. return {
  1310. centerTileX: nextCenterTileX,
  1311. centerTileY: nextCenterTileY,
  1312. tileTranslateX: 0,
  1313. tileTranslateY: 0,
  1314. }
  1315. }
  1316. const roundedCamera = this.getBaseCamera(nextCenterTileX, nextCenterTileY, rotationDeg)
  1317. const projectedCenter = worldToScreen(roundedCamera, { x: centerWorldX, y: centerWorldY }, false)
  1318. return {
  1319. centerTileX: nextCenterTileX,
  1320. centerTileY: nextCenterTileY,
  1321. tileTranslateX: this.state.stageWidth / 2 - projectedCenter.x,
  1322. tileTranslateY: this.state.stageHeight / 2 - projectedCenter.y,
  1323. }
  1324. }
  1325. setPreviewState(scale: number, originX: number, originY: number): void {
  1326. this.previewScale = scale
  1327. this.previewOriginX = originX
  1328. this.previewOriginY = originY
  1329. }
  1330. resetPreviewState(): void {
  1331. this.setPreviewState(1, this.state.stageWidth / 2, this.state.stageHeight / 2)
  1332. }
  1333. resetPinchState(): void {
  1334. this.pinchStartDistance = 0
  1335. this.pinchStartScale = 1
  1336. this.pinchStartAngle = 0
  1337. this.pinchStartRotationDeg = this.state.rotationDeg
  1338. this.pinchAnchorWorldX = 0
  1339. this.pinchAnchorWorldY = 0
  1340. }
  1341. clearPreviewResetTimer(): void {
  1342. if (this.previewResetTimer) {
  1343. clearTimeout(this.previewResetTimer)
  1344. this.previewResetTimer = 0
  1345. }
  1346. }
  1347. clearInertiaTimer(): void {
  1348. if (this.inertiaTimer) {
  1349. clearTimeout(this.inertiaTimer)
  1350. this.inertiaTimer = 0
  1351. }
  1352. }
  1353. clearViewSyncTimer(): void {
  1354. if (this.viewSyncTimer) {
  1355. clearTimeout(this.viewSyncTimer)
  1356. this.viewSyncTimer = 0
  1357. }
  1358. }
  1359. clearAutoRotateTimer(): void {
  1360. if (this.autoRotateTimer) {
  1361. clearTimeout(this.autoRotateTimer)
  1362. this.autoRotateTimer = 0
  1363. }
  1364. }
  1365. pickViewPatch(patch: Partial<MapEngineViewState>): Partial<MapEngineViewState> {
  1366. const viewPatch = {} as Partial<MapEngineViewState>
  1367. for (const key of VIEW_SYNC_KEYS) {
  1368. if (Object.prototype.hasOwnProperty.call(patch, key)) {
  1369. ;(viewPatch as any)[key] = patch[key]
  1370. }
  1371. }
  1372. return viewPatch
  1373. }
  1374. flushViewPatch(): void {
  1375. if (!Object.keys(this.pendingViewPatch).length) {
  1376. return
  1377. }
  1378. const patch = this.pendingViewPatch
  1379. this.pendingViewPatch = {}
  1380. this.onData(patch)
  1381. }
  1382. getTouchDistance(touches: TouchPoint[]): number {
  1383. if (touches.length < 2) {
  1384. return 0
  1385. }
  1386. const first = touches[0]
  1387. const second = touches[1]
  1388. const deltaX = first.pageX - second.pageX
  1389. const deltaY = first.pageY - second.pageY
  1390. return Math.sqrt(deltaX * deltaX + deltaY * deltaY)
  1391. }
  1392. getTouchAngle(touches: TouchPoint[]): number {
  1393. if (touches.length < 2) {
  1394. return 0
  1395. }
  1396. const first = touches[0]
  1397. const second = touches[1]
  1398. return Math.atan2(second.pageY - first.pageY, second.pageX - first.pageX)
  1399. }
  1400. getStagePoint(touches: TouchPoint[]): { x: number; y: number } {
  1401. if (!touches.length) {
  1402. return {
  1403. x: this.state.stageWidth / 2,
  1404. y: this.state.stageHeight / 2,
  1405. }
  1406. }
  1407. let pageX = 0
  1408. let pageY = 0
  1409. for (const touch of touches) {
  1410. pageX += touch.pageX
  1411. pageY += touch.pageY
  1412. }
  1413. return {
  1414. x: pageX / touches.length - this.state.stageLeft,
  1415. y: pageY / touches.length - this.state.stageTop,
  1416. }
  1417. }
  1418. animatePreviewToRest(): void {
  1419. this.clearPreviewResetTimer()
  1420. const startScale = this.previewScale || 1
  1421. const originX = this.previewOriginX || this.state.stageWidth / 2
  1422. const originY = this.previewOriginY || this.state.stageHeight / 2
  1423. if (Math.abs(startScale - 1) < 0.01) {
  1424. this.resetPreviewState()
  1425. this.syncRenderer()
  1426. this.compassController.start()
  1427. this.scheduleAutoRotate()
  1428. return
  1429. }
  1430. const startAt = Date.now()
  1431. const step = () => {
  1432. const progress = Math.min(1, (Date.now() - startAt) / PREVIEW_RESET_DURATION_MS)
  1433. const eased = 1 - Math.pow(1 - progress, 3)
  1434. const nextScale = startScale + (1 - startScale) * eased
  1435. this.setPreviewState(nextScale, originX, originY)
  1436. this.syncRenderer()
  1437. this.compassController.start()
  1438. if (progress >= 1) {
  1439. this.resetPreviewState()
  1440. this.syncRenderer()
  1441. this.compassController.start()
  1442. this.previewResetTimer = 0
  1443. this.scheduleAutoRotate()
  1444. return
  1445. }
  1446. this.previewResetTimer = setTimeout(step, INERTIA_FRAME_MS) as unknown as number
  1447. }
  1448. step()
  1449. }
  1450. normalizeTranslate(translateX: number, translateY: number, statusText: string): void {
  1451. if (!this.state.stageWidth) {
  1452. this.setState({
  1453. tileTranslateX: translateX,
  1454. tileTranslateY: translateY,
  1455. })
  1456. this.syncRenderer()
  1457. this.compassController.start()
  1458. return
  1459. }
  1460. const exactCenter = this.getExactCenterFromTranslate(translateX, translateY)
  1461. const resolvedViewport = this.resolveViewportForExactCenter(exactCenter.x, exactCenter.y)
  1462. const centerChanged = resolvedViewport.centerTileX !== this.state.centerTileX || resolvedViewport.centerTileY !== this.state.centerTileY
  1463. if (centerChanged) {
  1464. this.commitViewport(resolvedViewport, statusText)
  1465. return
  1466. }
  1467. this.setState({
  1468. tileTranslateX: resolvedViewport.tileTranslateX,
  1469. tileTranslateY: resolvedViewport.tileTranslateY,
  1470. })
  1471. this.syncRenderer()
  1472. this.compassController.start()
  1473. }
  1474. zoomAroundPoint(zoomDelta: number, stageX: number, stageY: number, residualScale: number): void {
  1475. const nextZoom = clamp(this.state.zoom + zoomDelta, this.minZoom, this.maxZoom)
  1476. const appliedDelta = nextZoom - this.state.zoom
  1477. if (!appliedDelta) {
  1478. this.animatePreviewToRest()
  1479. return
  1480. }
  1481. if (!this.state.stageWidth || !this.state.stageHeight) {
  1482. this.commitViewport(
  1483. {
  1484. zoom: nextZoom,
  1485. centerTileX: appliedDelta > 0 ? this.state.centerTileX * 2 : Math.floor(this.state.centerTileX / 2),
  1486. centerTileY: appliedDelta > 0 ? this.state.centerTileY * 2 : Math.floor(this.state.centerTileY / 2),
  1487. tileTranslateX: 0,
  1488. tileTranslateY: 0,
  1489. },
  1490. `缩放级别调整到 ${nextZoom}`,
  1491. true,
  1492. () => {
  1493. this.setPreviewState(residualScale, stageX, stageY)
  1494. this.syncRenderer()
  1495. this.compassController.start()
  1496. this.animatePreviewToRest()
  1497. },
  1498. )
  1499. return
  1500. }
  1501. const camera = this.getCameraState()
  1502. const world = screenToWorld(camera, { x: stageX, y: stageY }, true)
  1503. const zoomFactor = Math.pow(2, appliedDelta)
  1504. const nextWorldX = world.x * zoomFactor
  1505. const nextWorldY = world.y * zoomFactor
  1506. const anchorOffset = this.getWorldOffsetFromScreen(stageX, stageY)
  1507. const exactCenterX = nextWorldX - anchorOffset.x
  1508. const exactCenterY = nextWorldY - anchorOffset.y
  1509. const resolvedViewport = this.resolveViewportForExactCenter(exactCenterX, exactCenterY)
  1510. this.commitViewport(
  1511. {
  1512. zoom: nextZoom,
  1513. ...resolvedViewport,
  1514. },
  1515. `缩放级别调整到 ${nextZoom}`,
  1516. true,
  1517. () => {
  1518. this.setPreviewState(residualScale, stageX, stageY)
  1519. this.syncRenderer()
  1520. this.compassController.start()
  1521. this.animatePreviewToRest()
  1522. },
  1523. )
  1524. }
  1525. startInertia(): void {
  1526. this.clearInertiaTimer()
  1527. const step = () => {
  1528. this.panVelocityX *= INERTIA_DECAY
  1529. this.panVelocityY *= INERTIA_DECAY
  1530. if (Math.abs(this.panVelocityX) < INERTIA_MIN_SPEED && Math.abs(this.panVelocityY) < INERTIA_MIN_SPEED) {
  1531. this.setState({
  1532. statusText: `惯性滑动结束 (${this.buildVersion})`,
  1533. })
  1534. this.renderer.setAnimationPaused(false)
  1535. this.inertiaTimer = 0
  1536. this.scheduleAutoRotate()
  1537. return
  1538. }
  1539. this.normalizeTranslate(
  1540. this.state.tileTranslateX + this.panVelocityX * INERTIA_FRAME_MS,
  1541. this.state.tileTranslateY + this.panVelocityY * INERTIA_FRAME_MS,
  1542. `惯性滑动中 (${this.buildVersion})`,
  1543. )
  1544. this.inertiaTimer = setTimeout(step, INERTIA_FRAME_MS) as unknown as number
  1545. }
  1546. this.inertiaTimer = setTimeout(step, INERTIA_FRAME_MS) as unknown as number
  1547. }
  1548. }