cameraControl.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811
  1. /**
  2. * 相机控制(票 03 / ADR 0008):把三键输入迁移成相机状态,并下发给引擎。
  3. *
  4. * 两层状态(维护者 2026-09-17 要求「移动与旋转更丝滑」):
  5. * · `target` —— 输入意图:拖拽/滚轮直接写它,永远跟手、不丢输入;
  6. * · `shown` —— 实际下发给相机的状态:按 `1 − e^(−dt/τ)` 朝 target 收敛,
  7. * τ 见 `DAMPING_TAU_MS`。这个系数与帧率无关,所以 30fps 与 144fps 手感一致;
  8. * 差到 `SETTLE_EPSILON` 以内就吸附到 target,避免无限逼近。
  9. * 因此「拖右画面右移」这类方向、位移量仍由 target 精确决定(可断言),
  10. * 阻尼只改变**到达过程的形状**(起步渐入、松手后有一点余韵)。
  11. *
  12. * 为什么独立于 `cesiumEngine.js`:本模块**不 import cesium、不读 DOM**,
  13. * 只依赖一个「引擎接口」对象,因此三键语义、中心规则与阻尼都能脱离浏览器直接断言
  14. * (见 verify/t03-camera-contract.mjs);DOM 事件绑定单独放在 `attachCameraInput()`,
  15. * Cesium 适配放在 `cesiumEngine.createCameraEngine()`。三者都在服务层,组件不碰相机。
  16. *
  17. * 引擎接口:
  18. * applyView(pivot, hpr) 把「旋转中心 + 弹簧臂」下发给相机
  19. * readView(pivot) 反读当前相机相对该中心的 { heading, pitch, range }
  20. * pickGroundAtCenter() 屏幕中心的地面拾取点(无地形时按椭球),拾不到返回 null
  21. * projectPivot(pivot) 中心点在画布上的落点(走查断言「中心 = 屏幕中心」用)
  22. * inputTarget() 事件绑定目标(画布)
  23. * viewport() / fovY() 画布尺寸与垂直视场角(平移像素→米的换算)
  24. * now() / requestFrame() 动画帧
  25. */
  26. import {
  27. DAMPING_TAU_MS,
  28. FOCUS_FLIGHT_MS,
  29. INITIAL_PANORAMA,
  30. PITCH_LIMITS,
  31. RANGE_LIMITS,
  32. REANCHOR_LIMIT_RATIO,
  33. RETURN_FLIGHT_MS,
  34. approachHpr,
  35. approachPivot,
  36. clamp,
  37. clampPitch,
  38. dampFactor,
  39. entryFlightProgress,
  40. flightProgress,
  41. isSettled,
  42. lerpHpr,
  43. lerpPivot,
  44. metersPerPixel,
  45. normalizeHeading,
  46. orbit,
  47. pivotDistanceMeters,
  48. pivotOffsetMeters,
  49. returnFlightProgress,
  50. sanitizePivot,
  51. shiftPivot,
  52. zoomByWheel,
  53. } from '../domain/camera.js'
  54. import {
  55. GROUND_MARGIN_M,
  56. SOFT_ZONE_RATIO,
  57. clampPivotToBounds,
  58. clampPivotToSoftArea,
  59. clampRangeForTerrain,
  60. isPivotOutsideBounds,
  61. } from '../domain/areaLimits.js'
  62. /** 首帧状态:真实相机没接上前的占位,`syncFromEngine()` 会用实读值覆盖。 */
  63. const INITIAL_HPR = { ...INITIAL_PANORAMA }
  64. /**
  65. * @param {object} options
  66. * @param {object} options.engine 上面的引擎接口
  67. * @param {object} [options.limits] pitch 上下限(地面视图 / 管线视图)
  68. * @param {object} [options.rangeLimits] range 区间 `{ min, max }`;默认全局 `RANGE_LIMITS`
  69. * @param {number} [options.dampingTauMs] 阻尼时间常数,越大越丝滑
  70. * @param {(state: object) => void} [options.onStateChange] 状态变化回调(写 dataset 用)
  71. */
  72. export function createCameraControl({
  73. engine,
  74. limits = PITCH_LIMITS.ground,
  75. rangeLimits = RANGE_LIMITS,
  76. dampingTauMs = DAMPING_TAU_MS,
  77. onStateChange = null,
  78. }) {
  79. const state = {
  80. target: { pivot: null, hpr: { ...INITIAL_HPR } },
  81. shown: { pivot: null, hpr: { ...INITIAL_HPR } },
  82. focus: null,
  83. drag: null, // null | 'pan' | 'orbit'
  84. lockedPivot: null,
  85. flight: null, // { from, to, startedAt }
  86. /**
  87. * 整段视角飞行(返回全球用):`{from, to, startedAt, durationMs}`。
  88. * 与 `flight`(只换中心)分开:那个保持 heading/range 不变,这个是整段视角一起变。
  89. * 为什么不用阻尼代替:见 `RETURN_FLIGHT_MS` —— 目标 range 跨 2.5e6 倍,
  90. * 阻尼起步最快,头一帧就越过整条雾带。
  91. */
  92. viewFlight: null,
  93. /** 整段视角飞行的时长(毫秒);可现场调(`setReturnFlightMs`)。 */
  94. returnFlightMs: RETURN_FLIGHT_MS,
  95. pendingFocus: null, // 拖拽中来的选中,等松手再飞
  96. last: null, // 上一次指针位置
  97. lastFrameAt: 0,
  98. loopActive: false,
  99. tau: dampingTauMs,
  100. /** 本次拖拽是否**从框外开始**(票 37 的定位豁免;按下时判定,整段拖拽不变)。 */
  101. dragBeganOutside: false,
  102. /**
  103. * range 区间与**区域限位**(票 37)。`area` 为 null = 不限区(区外自由视角 / 未配置)。
  104. * @type {{min: number, max: number, area: {bounds: number[], groundMargin: number, softRatio: number}|null}}
  105. */
  106. range: {
  107. min: Number.isFinite(rangeLimits.min) ? rangeLimits.min : RANGE_LIMITS.min,
  108. max: Number.isFinite(rangeLimits.max) ? rangeLimits.max : RANGE_LIMITS.max,
  109. area: null,
  110. },
  111. }
  112. function snapshotTarget() {
  113. return {
  114. pivot: state.target.pivot ? { ...state.target.pivot } : null,
  115. hpr: { ...state.target.hpr },
  116. }
  117. }
  118. function snapshotShown() {
  119. return {
  120. pivot: state.shown.pivot ? { ...state.shown.pivot } : null,
  121. hpr: { ...state.shown.hpr },
  122. }
  123. }
  124. function settled() {
  125. return isSettled(snapshotShown(), snapshotTarget())
  126. }
  127. function notify() {
  128. if (onStateChange) onStateChange(getState())
  129. }
  130. /** 把 shown 下发给引擎并通知观察者。 */
  131. function render() {
  132. if (!state.shown.pivot) {
  133. notify()
  134. return
  135. }
  136. engine.applyView(state.shown.pivot, state.shown.hpr)
  137. notify()
  138. }
  139. /**
  140. * range 的**唯一**夹取入口:区域区间 × 视图模式区间已由 `setRangeLimits` 合成为
  141. * `state.range.min/max`,这里再叠上防入地(票 37)。
  142. *
  143. * 防入地在**输入时**算一次(与既有 clamp 行为一致,无逐帧主动回拉):
  144. * ADR 0009「限位只在输入时生效」。
  145. */
  146. function clampRange(range, pitch, pivot) {
  147. const limits = { min: state.range.min, max: state.range.max, margin: 0 }
  148. let next = clamp(range, limits.min, limits.max)
  149. const area = state.range.area
  150. if (area && area.groundMargin > 0 && typeof engine.groundHeightBelowCamera === 'function') {
  151. const terrainHeight = engine.groundHeightBelowCamera()
  152. next = clampRangeForTerrain(next, pitch, { terrainHeight, pivotHeight: pivot ? pivot.height : 0 }, {
  153. min: limits.min,
  154. max: limits.max,
  155. margin: area.groundMargin,
  156. })
  157. }
  158. return next
  159. }
  160. /** 拖拽中的中心夹取:锁区时可越界到**软区**边(ADR 0009 的软回弹)。 */
  161. function clampDragPivot(pivot) {
  162. const area = state.range.area
  163. if (!area || !area.bounds) return pivot
  164. // **已经越界在外时不再夹**(票 37 维护者裁定的「定位豁免」):
  165. // 定位可以把中心放在框外十几公里处,若下一次手动拖拽仍按软区夹,一按鼠标就会瞬移回框边。
  166. // 夹取只在**从框内往外拖**时作为"到头了"的限位生效,永远不做瞬移。
  167. if (state.dragBeganOutside) return pivot
  168. return clampPivotToSoftArea(pivot, area.bounds, area.softRatio)
  169. }
  170. /**
  171. * 松手时的**软回弹**:中心若越出硬框,把它夹回框内,交给既有阻尼平滑弹回。
  172. *
  173. * 维护者 2026-09-28 原话:「按紧拖动时向外阻尼移动直到最大限度停止,松开左键自动弹回」。
  174. * 同样遵守定位豁免 —— 拖动**开始时**已在框外(定位得来)就不弹,否则会把刚定位到的点位
  175. * 一把拽回县城框边。
  176. */
  177. function springBackIntoBounds() {
  178. const area = state.range.area
  179. if (!area || !area.bounds || state.dragBeganOutside) return false
  180. const pivot = state.target.pivot
  181. if (!pivot || !isPivotOutsideBounds(pivot, area.bounds)) return false
  182. state.target.pivot = clampPivotToBounds(pivot, area.bounds)
  183. return true
  184. }
  185. function schedule() {
  186. if (state.loopActive) return
  187. state.loopActive = true
  188. // 以「排帧时刻」为基准:帧间隔由真实时间戳决定,而不是写死每帧多少毫秒
  189. // —— 这是阻尼与帧率无关的前提(30fps 与 144fps 走同样的比例)。
  190. state.lastFrameAt = engine.now()
  191. engine.requestFrame(loop)
  192. }
  193. /** 唯一的动画循环:推进换中心飞行 + 推进阻尼 + 下发,未停稳就继续排帧。 */
  194. function loop(frameTime) {
  195. state.loopActive = false
  196. // 真机 rAF 会带时间戳;假引擎(逻辑断言)不带,退回引擎时钟。
  197. const now = typeof frameTime === 'number' ? frameTime : engine.now()
  198. // 下限 1ms:时间戳相同(同毫秒内两次回调)时也要推进,否则会空转排帧。
  199. const dt = Math.max(1, now - state.lastFrameAt)
  200. state.lastFrameAt = now
  201. advanceFlight(now)
  202. // 整段视角飞行(返回全球)优先于阻尼:它自带缓动,不能再叠一层指数逼近。
  203. const flyingView = advanceViewFlight(now)
  204. if (!flyingView) advanceDamping(dt)
  205. render()
  206. if (state.flight || state.viewFlight || !settled()) schedule()
  207. }
  208. /** 换中心:target 的中心从 from 平滑推到 to(保持 heading / pitch / range 不动)。 */
  209. function advanceFlight(now) {
  210. if (!state.flight) return
  211. const { from, to, startedAt } = state.flight
  212. const progress = flightProgress(now - startedAt, FOCUS_FLIGHT_MS)
  213. state.target.pivot = lerpPivot(from, to, progress)
  214. if (progress >= 1) state.flight = null
  215. }
  216. /** 阻尼:shown 朝 target 收敛一步;已停稳就吸附,避免无限逼近。 */
  217. function advanceDamping(dtMs) {
  218. const factor = dampFactor(dtMs, state.tau)
  219. state.shown.hpr = approachHpr(state.shown.hpr, state.target.hpr, factor)
  220. if (state.target.pivot && !state.shown.pivot) {
  221. state.shown.pivot = { ...state.target.pivot }
  222. } else if (state.target.pivot) {
  223. state.shown.pivot = approachPivot(state.shown.pivot, state.target.pivot, factor)
  224. }
  225. if (settled()) {
  226. state.shown.hpr = { ...state.target.hpr }
  227. state.shown.pivot = state.target.pivot ? { ...state.target.pivot } : null
  228. }
  229. }
  230. /** 中心点缺失时现取一次(默认全球视角下屏幕中心多半能拾到椭球交点)。 */
  231. function ensurePivot() {
  232. if (!state.target.pivot) {
  233. const picked = sanitizePivot(engine.pickGroundAtCenter())
  234. state.target.pivot = picked
  235. if (picked && !state.shown.pivot) state.shown.pivot = { ...picked }
  236. }
  237. return state.target.pivot
  238. }
  239. /** 用户开始新操作时打断换中心飞行(阻尼循环由各输入入口自己排帧)。 */
  240. function cancelFlight() {
  241. state.flight = null
  242. // 整段视角飞行同样要能被用户打断:否则拖一下鼠标,镜头还会自己飞回全景。
  243. state.viewFlight = null
  244. }
  245. /**
  246. * 整段视角飞行的逐帧推进(进入主场景 / 返回全球)。到点落位并结束。
  247. * @returns {boolean} 本次是否由它接管了 `shown`
  248. */
  249. function advanceViewFlight(now) {
  250. const flight = state.viewFlight
  251. if (!flight) return false
  252. const { from, to, startedAt, durationMs, entering } = flight
  253. const elapsed = now - startedAt
  254. const t = entering ? entryFlightProgress(elapsed, durationMs) : returnFlightProgress(elapsed, durationMs)
  255. const hpr = lerpHpr(from.hpr, to.hpr, t)
  256. if (entering && t < 1 && from.hpr.range > 0 && to.hpr.range > 0) {
  257. hpr.range = from.hpr.range * (to.hpr.range / from.hpr.range) ** t
  258. }
  259. state.shown = {
  260. // 入场先把视线引向城市,再进入近处;返回全球维持既有轨迹。
  261. pivot: lerpPivot(from.pivot, to.pivot, entering ? 1 - (1 - t) ** 4 : t),
  262. hpr,
  263. }
  264. if (t >= 1) state.viewFlight = null
  265. return true
  266. }
  267. /** 挂载后调用:中心 = 屏幕中心地面拾取点,弹簧臂参数按当前真实相机反读,避免首次交互跳变。 */
  268. function syncFromEngine() {
  269. const pivot = sanitizePivot(engine.pickGroundAtCenter())
  270. if (pivot) {
  271. const read = engine.readView(pivot)
  272. const hpr = {
  273. heading: read.heading,
  274. pitch: clampPitch(read.pitch, limits),
  275. range: read.range,
  276. }
  277. state.target = { pivot: { ...pivot }, hpr: { ...hpr } }
  278. state.shown = { pivot: { ...pivot }, hpr: { ...hpr } }
  279. }
  280. notify()
  281. return getState()
  282. }
  283. function beginDrag({ button, x, y }) {
  284. cancelFlight()
  285. state.pendingFocus = null
  286. state.last = { x, y }
  287. // 票 37:按下瞬间记下「中心是否已在硬框外」——它决定本次拖拽走不走软区夹取与松手回弹。
  288. // 在**按下时**判定(而不是每帧),是为了让整段拖拽行为一致:不会拖到一半突然被夹。
  289. const area = state.range.area
  290. state.dragBeganOutside = !!(
  291. area &&
  292. area.bounds &&
  293. state.target.pivot &&
  294. isPivotOutsideBounds(state.target.pivot, area.bounds)
  295. )
  296. if (button === 2) {
  297. // ADR 0008:右键按下时锁定当时的中心,拖拽中不重新拾取。
  298. ensurePivot()
  299. state.lockedPivot = state.target.pivot ? { ...state.target.pivot } : null
  300. state.drag = state.lockedPivot ? 'orbit' : null
  301. return
  302. }
  303. if (button === 0) {
  304. ensurePivot()
  305. state.drag = state.target.pivot ? 'pan' : null
  306. return
  307. }
  308. state.drag = null
  309. }
  310. function moveDrag({ x, y }) {
  311. if (!state.drag || !state.last) return
  312. const dxPx = x - state.last.x
  313. const dyPx = y - state.last.y
  314. state.last = { x, y }
  315. if (dxPx === 0 && dyPx === 0) return
  316. if (state.drag === 'pan') {
  317. const viewport = engine.viewport()
  318. const metersPerPx = metersPerPixel({
  319. range: state.target.hpr.range,
  320. fovYRad: engine.fovY(),
  321. viewportHeight: viewport.height,
  322. })
  323. const offset = pivotOffsetMeters({ headingDeg: state.target.hpr.heading, dxPx, dyPx, metersPerPx })
  324. // 平移只移动中心:heading / pitch / range 原样带走;方向见 domain/camera.js 的 PAN_FOLLOWS_DRAG。
  325. // 票 37:锁区时拖拽可越界到**软区**边(用户按紧拖到最大限度就停在那里),松手再弹回。
  326. state.target.pivot = clampDragPivot(shiftPivot(state.target.pivot, offset))
  327. schedule()
  328. return
  329. }
  330. if (state.drag === 'orbit') {
  331. state.target.hpr = orbit(state.target.hpr, { dxPx, dyPx }, limits)
  332. // 中心保持按下时锁定的那个点,range 不变。
  333. state.target.pivot = state.lockedPivot
  334. schedule()
  335. }
  336. }
  337. function endDrag() {
  338. if (!state.drag) return
  339. const mode = state.drag
  340. state.drag = null
  341. state.lockedPivot = null
  342. state.last = null
  343. const pending = state.pendingFocus
  344. state.pendingFocus = null
  345. if (mode === 'pan') {
  346. // ADR 0008:只有左键平移才把中心更新为地面拾取点;平移后相机中心不再跟随选中对象。
  347. // 但松手时**不能**把目标直接改写成拾取点 —— 那会一次抹平阻尼攒下的滞后,
  348. // 表现为「松手即停、没有惯性」,与滚轮/右键手感不一致(维护者 2026-09-17 反馈)。
  349. // 改为:偏差小到看不出来时重锚(顺手清掉等距近似的累积误差),偏差大就不动目标。
  350. const picked = sanitizePivot(engine.pickGroundAtCenter())
  351. if (picked) {
  352. const drift = pivotDistanceMeters(state.target.pivot, picked)
  353. const limit = state.target.hpr.range * REANCHOR_LIMIT_RATIO
  354. if (drift <= limit) state.target.pivot = picked
  355. }
  356. // 票 37 软回弹:松开左键时把中心**夹回硬框**,由既有阻尼平滑弹回(维护者 2026-09-28
  357. // 「按紧向外阻尼移动直到最大限度停止,松开左键自动弹回」)。
  358. // 放在重锚**之后**:先按屏幕中心纠正近似误差,再把越界收回来,顺序反了会用拾取点
  359. // 覆盖刚夹好的落点。
  360. springBackIntoBounds()
  361. state.focus = null
  362. schedule()
  363. return
  364. }
  365. // 轨道旋转期间来的选中,等松手后再平滑换中心(拖拽中中心一直是锁定的那个)。
  366. if (pending) startFlight(pending)
  367. schedule()
  368. }
  369. function wheel({ deltaY }) {
  370. cancelFlight()
  371. if (!ensurePivot()) return false
  372. // 票 37:滚轮受「区域上限 × 视图模式 × 防入地」三处夹取(最终生效 = 三者交集)。
  373. const zoomed = zoomByWheel(state.target.hpr, deltaY, state.range)
  374. state.target.hpr = {
  375. ...zoomed,
  376. range: clampRange(zoomed.range, zoomed.pitch, state.target.pivot),
  377. }
  378. schedule()
  379. return true
  380. }
  381. /**
  382. * 选中/取消选中一个对象(监测点、设备详情调用)。
  383. * @param {{lon: number, lat: number, height?: number}|null} point 对象地表点;null = 取消选中
  384. */
  385. function setFocus(point) {
  386. if (!point) {
  387. // ADR 0008:取消选中不立即回退中心。
  388. state.focus = null
  389. state.pendingFocus = null
  390. notify()
  391. return false
  392. }
  393. // 定位服务已采样设备地形高程;换中心时必须保留 Z,不能重置到椭球面。
  394. const target = sanitizePivot(point)
  395. if (!target) return false
  396. state.focus = target
  397. if (state.drag) {
  398. // 拖拽中(尤其右键轨道旋转)中心已锁定:先记下,松手后再换中心,绝不插队。
  399. state.pendingFocus = target
  400. return true
  401. }
  402. return startFlight(target)
  403. }
  404. /** 平滑换中心:保持 heading / pitch / range,只把中心从当前位置推到目标。 */
  405. function startFlight(target) {
  406. if (!state.target.pivot) {
  407. state.target.pivot = target
  408. state.shown.pivot = { ...target }
  409. render()
  410. return true
  411. }
  412. if (state.target.pivot.lon === target.lon && state.target.pivot.lat === target.lat
  413. && state.target.pivot.height === target.height) {
  414. return true
  415. }
  416. state.flight = { from: { ...state.target.pivot }, to: target, startedAt: engine.now() }
  417. schedule()
  418. return true
  419. }
  420. /**
  421. * 换 pitch 上下限(票 21:地面/管线视图切换时放宽到允许平视)。
  422. * 只换限制,不动当前角度 —— clamp 与 orbit 下一次就会用新范围。
  423. */
  424. function setPitchLimits(nextLimits) {
  425. if (!nextLimits || !Number.isFinite(nextLimits.min) || !Number.isFinite(nextLimits.max)) return limits
  426. limits = nextLimits
  427. return limits
  428. }
  429. /**
  430. * 换 range 区间与**区域限位**(票 37,与 `setPitchLimits` 对称)。
  431. *
  432. * 只换限制,不动当前值 —— 但调用方通常紧接着 `setHpr()` 把当前值夹进新区间,
  433. * 否则「进区时 range 已是 12 km 以外」要等用户滚一次才被夹(决策票 03 记的 4.7× 突跳)。
  434. *
  435. * @param {{min?: number, max?: number, area?: {bounds: number[], groundMargin?: number, softRatio?: number}|null}} next
  436. */
  437. function setRangeLimits(next) {
  438. if (!next) return getRangeLimits()
  439. if (Number.isFinite(next.min)) state.range.min = next.min
  440. if (Number.isFinite(next.max)) state.range.max = next.max
  441. if (next.area !== undefined) {
  442. state.range.area =
  443. next.area && Array.isArray(next.area.bounds) && next.area.bounds.length === 4
  444. ? {
  445. bounds: next.area.bounds.slice(),
  446. groundMargin: Number.isFinite(next.area.groundMargin) ? next.area.groundMargin : GROUND_MARGIN_M,
  447. softRatio: Number.isFinite(next.area.softRatio) ? next.area.softRatio : SOFT_ZONE_RATIO,
  448. }
  449. : null
  450. }
  451. // 退化保护:区间反了就按可达的那一侧收口,免得相机被夹死。
  452. if (state.range.min > state.range.max) state.range.min = state.range.max
  453. return getRangeLimits()
  454. }
  455. /** 当前生效的 range 限制(只读副本,走查与排查读它)。 */
  456. function getRangeLimits() {
  457. return {
  458. min: state.range.min,
  459. max: state.range.max,
  460. area: state.range.area ? { ...state.range.area, bounds: state.range.area.bounds.slice() } : null,
  461. }
  462. }
  463. /**
  464. * 把当前 target 夹进生效限位(进区 / 换视图 / 返回全球后调用)。
  465. * **只夹 range 与中心**:pitch 不参与区域收紧(ADR 0009)。
  466. * @param {{clampPivot?: boolean}} [options] `clampPivot` 默认 true;定位路径传 false(维护者 2026-09-28 裁定)
  467. */
  468. function clampToLimits(options = {}) {
  469. const clampPivot = options.clampPivot !== false
  470. let changed = false
  471. const nextRange = clampRange(state.target.hpr.range, state.target.hpr.pitch, state.target.pivot)
  472. if (nextRange !== state.target.hpr.range) {
  473. state.target.hpr = { ...state.target.hpr, range: nextRange }
  474. changed = true
  475. }
  476. const area = state.range.area
  477. if (clampPivot && area && area.bounds && state.target.pivot && isPivotOutsideBounds(state.target.pivot, area.bounds)) {
  478. state.target.pivot = clampPivotToBounds(state.target.pivot, area.bounds)
  479. changed = true
  480. }
  481. if (changed) schedule()
  482. return changed
  483. }
  484. /**
  485. * 直接设目标 hpr(票 21:切换视图时只改 pitch/range,heading 与中心不动)。
  486. * 走同一套阻尼收敛,所以切换过程是平滑的;不动 `state.target.pivot` = 不重置中心。
  487. */
  488. function setHpr(nextHpr) {
  489. if (!nextHpr) return false
  490. state.target.hpr = {
  491. heading: Number.isFinite(nextHpr.heading) ? normalizeHeading(nextHpr.heading) : state.target.hpr.heading,
  492. pitch: clampPitch(Number.isFinite(nextHpr.pitch) ? nextHpr.pitch : state.target.hpr.pitch, limits),
  493. // 票 37:走生效区间(含区域上限),不再直接用全局 RANGE_LIMITS —— 否则视图切换能把
  494. // 相机推回 12 km 以外,绕开进区限位。
  495. range: Number.isFinite(nextHpr.range)
  496. ? clampRange(nextHpr.range, Number.isFinite(nextHpr.pitch) ? nextHpr.pitch : state.target.hpr.pitch, state.target.pivot)
  497. : state.target.hpr.range,
  498. }
  499. schedule()
  500. return true
  501. }
  502. /**
  503. * 套用一个**完整视角预设**(票 30):中心 + heading/pitch/range 一起换。
  504. *
  505. * 与 `setFocus()` 的区别:`setFocus` 模拟「选中对象」,只换中心、保持 heading/range(ADR 0008 的
  506. * 中心规则);而「飞到目标城市」「快速归位」要的是整段视角都到位,所以这里直接写 target 的
  507. * pivot 与 hpr,并复用同一套飞行/阻尼(`syncFromEngine` 的下一次反读会与预设一致)。
  508. *
  509. * @param {{lon: number, lat: number, height?: number}} pivot 中心点
  510. * @param {{heading?: number, pitch?: number, range?: number}} [hpr] 缺省沿用当前值
  511. * @param {object} [options]
  512. * `immediate: true` = 不走飞行,直接落位(进系统首帧用);
  513. * `flightMs: 1800` = 整段视角**按时长 + 慢起缓动**飞过去(返回全球用)。
  514. * 见 `RETURN_FLIGHT_MS`:阻尼在这里会"头一帧就冲上万公里",把低空停留抹掉。
  515. */
  516. function applyViewPreset(pivot, hpr = {}, options = {}) {
  517. const target = sanitizePivot({ lon: pivot.lon, lat: pivot.lat, height: pivot.height || 0 })
  518. if (!target) return false
  519. const pitch = clampPitch(Number.isFinite(hpr.pitch) ? hpr.pitch : state.target.hpr.pitch, limits)
  520. const next = {
  521. pivot: target,
  522. hpr: {
  523. heading: Number.isFinite(hpr.heading) ? normalizeHeading(hpr.heading) : state.target.hpr.heading,
  524. pitch,
  525. // 票 37:预设的 range 也必须落在生效限位内(并行图票 03 Q3=A:定位不设例外、
  526. // 被夹就如实呈现)。**中心不夹** —— 维护者 2026-09-28 裁定定位可到框外点位。
  527. range: Number.isFinite(hpr.range) ? clampRange(hpr.range, pitch, target) : state.target.hpr.range,
  528. },
  529. }
  530. // 用户手动操作过就不该被「飞行中」的旧目标拉扯:清掉拖拽/选中/待飞行状态。
  531. cancelFlight()
  532. state.focus = null
  533. state.pendingFocus = null
  534. state.drag = null
  535. state.lockedPivot = null
  536. state.target = next
  537. if (options.immediate || !state.shown.pivot) {
  538. state.shown = { pivot: { ...next.pivot }, hpr: { ...next.hpr } }
  539. render()
  540. return true
  541. }
  542. // 整段视角飞行:起点取**当前实际态**(不是 target),否则会被上一次飞行的旧目标带偏。
  543. // `flightMs` 显式给 0 或负数 = 不要飞行(走默认阻尼路径)。
  544. const duration = Number.isFinite(options.flightMs) ? Number(options.flightMs) : 0
  545. if (duration > 0) {
  546. state.viewFlight = {
  547. from: snapshotShown(),
  548. to: { pivot: { ...next.pivot }, hpr: { ...next.hpr } },
  549. startedAt: engine.now(),
  550. durationMs: duration,
  551. entering: options.flightCurve === 'entry',
  552. }
  553. schedule()
  554. return true
  555. }
  556. // 复用阻尼收敛到新预设(不额外造动画通道,手感与其它操作一致)。
  557. schedule()
  558. return true
  559. }
  560. /**
  561. * 返回相机状态。`pivot`/`hpr` 保持「输入意图」(target,位移量与方向可精确断言),
  562. * `shown`/`shownPivot`/`shownHpr` 是阻尼后真正下发给相机的状态;
  563. * `settled` = 既没有待推进的换中心飞行、阻尼也已跟上目标。
  564. */
  565. function getState() {
  566. const target = snapshotTarget()
  567. const shown = snapshotShown()
  568. return {
  569. pivot: target.pivot,
  570. hpr: target.hpr,
  571. target,
  572. shown,
  573. shownPivot: shown.pivot,
  574. shownHpr: shown.hpr,
  575. settled: !state.flight && !state.viewFlight && isSettled(shown, target),
  576. focus: state.focus ? { ...state.focus } : null,
  577. dragging: state.drag,
  578. flying: !!state.flight,
  579. /** 是否正在「整段视角飞行」(返回全球);走查据此判"镜头还在飞"。 */
  580. flyingView: !!state.viewFlight,
  581. /** 当前整段视角飞行时长(毫秒)—— 与 `dampingTauMs` 一样做成可现场调的读数。 */
  582. returnFlightMs: state.returnFlightMs,
  583. /** 当前阻尼时间常数(毫秒);0 = 不做阻尼。 */
  584. dampingTauMs: state.tau,
  585. /** 票 37:当前生效的 range 区间与区域限位(只读,走查断言"进区后上限变成 home.range"用)。 */
  586. rangeLimits: getRangeLimits(),
  587. /** 票 37:中心是否在硬框外(定位到区外点位时为 true;人工与走查都读它)。 */
  588. outsideArea: !!(state.range.area && state.range.area.bounds && state.target.pivot
  589. && isPivotOutsideBounds(state.target.pivot, state.range.area.bounds)),
  590. }
  591. }
  592. function projectPivot() {
  593. const pivot = state.shown.pivot || state.target.pivot
  594. return pivot ? engine.projectPivot(pivot) : null
  595. }
  596. /**
  597. * 调阻尼时间常数(毫秒):手感是主观的,所以在 DEV 把手/控制台里能现场拖调
  598. * (`__cockpitMap.setCameraDamping(240)`),不用改代码再看。0 表示不做阻尼(直接跟手)。
  599. */
  600. function setDampingTau(tauMs) {
  601. const next = Number(tauMs)
  602. if (!Number.isFinite(next) || next < 0) return state.tau
  603. state.tau = next
  604. if (next === 0) {
  605. state.shown = snapshotTarget()
  606. render()
  607. } else {
  608. schedule()
  609. }
  610. return state.tau
  611. }
  612. /**
  613. * 调「返回全球」的飞行时长(毫秒)。与 `setDampingTau` 同款理由:
  614. * 退出快慢是主观的,做成能现场拖调,不用改代码再看。
  615. * 大于 0 才生效(0 = 不要飞行,退回阻尼路径);负数/非数字被拒绝并保持原值。
  616. */
  617. function setReturnFlightMs(ms) {
  618. const next = Number(ms)
  619. if (!Number.isFinite(next) || next < 0) return state.returnFlightMs
  620. state.returnFlightMs = next
  621. return state.returnFlightMs
  622. }
  623. function dispose() {
  624. state.flight = null
  625. state.drag = null
  626. state.lockedPivot = null
  627. state.pendingFocus = null
  628. state.last = null
  629. state.dragBeganOutside = false
  630. }
  631. return {
  632. syncFromEngine,
  633. beginDrag,
  634. moveDrag,
  635. endDrag,
  636. wheel,
  637. setFocus,
  638. applyViewPreset,
  639. setPitchLimits,
  640. setRangeLimits,
  641. getRangeLimits,
  642. clampToLimits,
  643. setHpr,
  644. getState,
  645. projectPivot,
  646. setDampingTau,
  647. setReturnFlightMs,
  648. dispose,
  649. }
  650. }
  651. /**
  652. * DOM 事件绑定:左键/右键拖拽 + 滚轮;右键菜单与滚轮默认行为都要吃掉,
  653. * 否则浏览器菜单 / 页面滚动会插进三键契约里。
  654. * @returns {() => void} detach
  655. */
  656. export function attachCameraInput(element, control) {
  657. if (!element || typeof element.addEventListener !== 'function') {
  658. return () => {}
  659. }
  660. const onPointerDown = (event) => {
  661. if (event.button !== 0 && event.button !== 2) return
  662. if (typeof element.setPointerCapture === 'function') {
  663. try {
  664. element.setPointerCapture(event.pointerId)
  665. } catch (error) {
  666. // 某些合成事件没有真实 pointerId,捕获失败不影响后续 move/up。
  667. }
  668. }
  669. control.beginDrag({ button: event.button, x: event.clientX, y: event.clientY })
  670. }
  671. const onPointerMove = (event) => {
  672. control.moveDrag({ x: event.clientX, y: event.clientY })
  673. }
  674. const onPointerUp = (event) => {
  675. if (typeof element.releasePointerCapture === 'function') {
  676. try {
  677. element.releasePointerCapture(event.pointerId)
  678. } catch (error) {
  679. // 同上:捕获不存在时忽略。
  680. }
  681. }
  682. control.endDrag()
  683. }
  684. const onWheel = (event) => {
  685. if (control.wheel({ deltaY: event.deltaY })) {
  686. event.preventDefault()
  687. }
  688. }
  689. const onContextMenu = (event) => {
  690. event.preventDefault()
  691. }
  692. // 右键拖动(旋转)期间,指针可能已经移到 UI 面板上方再松手。此时 `contextmenu` 的
  693. // 目标是那块面板,绑在视口上的处理器收不到,浏览器原生菜单就会弹出来打断操作。
  694. // 所以在**文档捕获阶段**兜住:只有本次右键拖动起于视口时才拦,面板自己的右键不受影响。
  695. const menuGuard = { rightDrag: false, until: 0 }
  696. const now = () => (typeof performance !== 'undefined' && performance.now ? performance.now() : Date.now())
  697. // 松手后原生菜单仍可能晚一拍派发(Windows 在 mouseup 之后),留一个短窗口继续拦。
  698. const MENU_GUARD_MS = 500
  699. const doc = element.ownerDocument || (typeof document !== 'undefined' ? document : null)
  700. const onDocContextMenu = (event) => {
  701. if (!menuGuard.rightDrag && now() >= menuGuard.until) return
  702. event.preventDefault()
  703. event.stopPropagation()
  704. }
  705. const endRightDrag = () => {
  706. if (!menuGuard.rightDrag) return
  707. menuGuard.rightDrag = false
  708. menuGuard.until = now() + MENU_GUARD_MS
  709. }
  710. element.addEventListener('pointerdown', onPointerDown)
  711. element.addEventListener('pointermove', onPointerMove)
  712. element.addEventListener('pointerup', onPointerUp)
  713. element.addEventListener('pointercancel', onPointerUp)
  714. element.addEventListener('wheel', onWheel, { passive: false })
  715. element.addEventListener('contextmenu', onContextMenu)
  716. // 拖动在视口内开始时打标记;结束(含指针捕获失效)一律在这里收口。
  717. const beginMark = (event) => {
  718. if (event.button === 2) menuGuard.rightDrag = true
  719. }
  720. element.addEventListener('pointerdown', beginMark)
  721. element.addEventListener('pointerup', endRightDrag)
  722. element.addEventListener('pointercancel', endRightDrag)
  723. doc?.addEventListener?.('contextmenu', onDocContextMenu, { capture: true })
  724. const win = doc?.defaultView || (typeof window !== 'undefined' ? window : null)
  725. win?.addEventListener?.('pointerup', endRightDrag)
  726. win?.addEventListener?.('pointercancel', endRightDrag)
  727. return () => {
  728. element.removeEventListener('pointerdown', onPointerDown)
  729. element.removeEventListener('pointermove', onPointerMove)
  730. element.removeEventListener('pointerup', onPointerUp)
  731. element.removeEventListener('pointercancel', onPointerUp)
  732. element.removeEventListener('wheel', onWheel)
  733. element.removeEventListener('contextmenu', onContextMenu)
  734. element.removeEventListener('pointerdown', beginMark)
  735. element.removeEventListener('pointerup', endRightDrag)
  736. element.removeEventListener('pointercancel', endRightDrag)
  737. doc?.removeEventListener?.('contextmenu', onDocContextMenu, { capture: true })
  738. win?.removeEventListener?.('pointerup', endRightDrag)
  739. win?.removeEventListener?.('pointercancel', endRightDrag)
  740. }
  741. }