/** * Cesium 引擎适配层(票 27):本仓库里唯一 `import 'cesium'` 的地方。 * * 只在 `mapService.mountMap()` 完成 `window.CESIUM_BASE_URL` 注入之后被动态 import, * 因此静态 import 提升不会踩到时序(见 services/cesiumAssets.js)。 * * 本模块负责两件事: * 1. 「把引擎接到宿主上」(票 27):唯一 `Viewer`、自带控件与默认相机输入全关、 * 不碰需要账号的能力;底图按 `domain/basemap.js` 的计划挂(票 29), * 没配就不挂(票 27 的「底图未配置不伪造配准」); * 2. 「把相机契约接到引擎上」(票 03):`createCameraEngine()` 把三键契约需要的原语 * (弹簧臂 `lookAtTransform(东北天局部系, HeadingPitchRange)`、屏幕中心地面拾取、 * 中心点投影)包成 services/cameraControl.js 的引擎接口 —— 相机语义本身不在本文件, * 这里只做 Cesium 方言的翻译。 */ import { Cartesian2, Cartesian3, Cartographic, Cesium3DTileset, Cesium3DTileStyle, CesiumTerrainProvider, Color, CustomDataSource, DirectionalLight, Ellipsoid, EllipsoidalOccluder, ImageBasedLighting, HeightReference, HeadingPitchRange, ImageryLayer, LabelStyle, Math as CesiumMath, Matrix4, PostProcessStage, Rectangle, RequestScheduler, SceneTransforms, TileMapServiceImageryProvider, Transforms, UrlTemplateImageryProvider, VerticalOrigin, Viewer, buildModuleUrl, sampleTerrainMostDetailed, } from 'cesium' import 'cesium/Build/Cesium/Widgets/widgets.css' // 强调的**判定**在 domain(纯函数,可脱浏览器断言);本层只把结论写成显示参数。 import { EMPHASIS_STYLE, shouldEmphasize } from '../domain/mapEmphasis.js' // 票 47:动效的**相位与映射**同样在 domain(纯函数,可跨时间采样断言); // 本层只把相位写成 billboard 的 scale/alpha/rotation。 import { DEVICE_EFFECT, RING_LAYERS, blinkStrengthAt, glowScaleAt, glowStrengthAt, hasGlow, pulseStrengthAt, ringEntityCount, ringFrameAt, spinAngleAt } from '../domain/deviceEffects.js' const DEG = Math.PI / 180 const VIEWER_OPTIONS = { // 自带控件全关(导航/时间轴/拾取框等)。 animation: false, timeline: false, geocoder: false, homeButton: false, sceneModePicker: false, baseLayerPicker: false, navigationHelpButton: false, navigationInstructionsInitiallyVisible: false, fullscreenButton: false, infoBox: false, selectionIndicator: false, vrButton: false, // 按需渲染:相机不动且无新瓦片时不再空转 60fps 渲染循环 —— 模型加载(解码+GPU 上传) // 独占主线程,"加载一开始整个场景都卡"的直接缓解。相机一动、瓦片一到货就自动出帧; // maximumRenderTimeChange 兜底:即使无场景变化也至少每 0.5s 渲一帧,保证自建雾 // 等 uniform 更新最迟半秒内可见(自转/雾动画都绑定相机运动,不受影响)。 requestRenderMode: true, maximumRenderTimeChange: 0.5, } /** 按底图计划建 imagery layer;未配置或计划无效时返回 false = 不配底图(票 27:不伪造地理配准)。 */ function createBaseLayer(plan) { if (!plan || !plan.ready) return false if (plan.kind === 'tms') { // Cesium 自带的离线 TMS(随 Assets 目录进产物,不需要账号或外网)。 return ImageryLayer.fromProviderAsync(TileMapServiceImageryProvider.fromUrl(buildModuleUrl(plan.url))) } if (plan.kind === 'xyz') { const options = { url: plan.url } if (plan.subdomains && plan.subdomains.length) options.subdomains = plan.subdomains if (Number.isInteger(plan.minimumLevel)) options.minimumLevel = plan.minimumLevel if (Number.isInteger(plan.maximumLevel)) options.maximumLevel = plan.maximumLevel if (plan.credit) options.credit = plan.credit return new ImageryLayer(new UrlTemplateImageryProvider(options)) } return false } /** * 在宿主要素上创建 Viewer。 * @param {Element} host 宿主要素(`.map-canvas`) * @param {object} [basemapPlan] `domain/basemap.js` 的底图计划(票 29);缺省 = 不配底图 * @returns {Viewer} */ export function createViewer(host, basemapPlan) { const viewer = new Viewer(host, { ...VIEWER_OPTIONS, baseLayer: createBaseLayer(basemapPlan) }) const controller = viewer.scene.screenSpaceCameraController controller.enableRotate = false controller.enableZoom = false controller.enableTilt = false controller.enableLook = false controller.enableTranslate = false // 球体底色用驾驶舱底色:没配底图时看到的就是这个球,配了底图会被影像盖住。 viewer.scene.globe.baseColor = Color.fromCssColorString('#04121f') // 地面视图必须保留地形深度,否则埋在地表以下的 3D Tiles 也会覆盖到地形之上。 // 回归:tools/city-massing/verify-occlusion.mjs 用实际渲染像素检查遮挡。 viewer.scene.globe.depthTestAgainstTerrain = true return viewer } export function resizeViewer(viewer) { viewer.resize() } /** 叠加影像(票 21):本地精细切片画在底图之上,URL 模板里可用 `{reverseY}` 表示 TMS 的 y。 */ function createOverlayProvider(overlay) { const options = { url: overlay.url } if (Number.isInteger(overlay.minimumLevel)) options.minimumLevel = overlay.minimumLevel if (Number.isInteger(overlay.maximumLevel)) options.maximumLevel = overlay.maximumLevel if (overlay.bounds) options.rectangle = Rectangle.fromDegrees(overlay.bounds[0], overlay.bounds[1], overlay.bounds[2], overlay.bounds[3]) if (overlay.credit) options.credit = overlay.credit return new UrlTemplateImageryProvider(options) } /** * 批量采样真实地表高程(票 34 的建模用途):一次请求把整张网格取回来, * 比逐点调 `sampleTerrainHeight()` 快得多(逐点会重复拉同一批瓦片)。 * @param {Array<{lon: number, lat: number}>} points * @returns {Promise>} 与入参等长;无地形或取不到的点为 null */ export async function sampleTerrainHeights(viewer, points) { const list = Array.isArray(points) ? points : [] if (!viewer || !viewer.terrainProvider || !list.length) return list.map(() => null) try { const cartos = list.map((p) => Cartographic.fromDegrees(p.lon, p.lat)) const sampled = await sampleTerrainMostDetailed(viewer.terrainProvider, cartos) return sampled.map((c) => (c && Number.isFinite(c.height) ? c.height : null)) } catch { return list.map(() => null) } } /** * 采样一点的**真实地表高程**(票 30):地形感知的中心点/预设视角靠它把高度从「椭球 0 米」 * 换成实际地形高度,否则相机高度按 0 算,一拉近就落进山体(实测 range 120m 全黑)。 * @returns {Promise} 米;没有地形或采样失败返回 null */ export async function sampleTerrainHeight(viewer, lon, lat) { if (!viewer || !viewer.terrainProvider) return null try { const carto = Cartographic.fromDegrees(lon, lat) const [sampled] = await sampleTerrainMostDetailed(viewer.terrainProvider, [carto]) const height = sampled && sampled.height return Number.isFinite(height) ? height : null } catch { return null } } /** * 挂地形(票 21)。DEM 是**量化网格**:`CesiumTerrainProvider.fromUrl()`, * `layer.json` 里的 `scheme: "tms"` 由 Cesium 自己认,服务端不需要翻 y。 * @returns {Promise} `'ready'`;失败时抛错,由调用方记成失败态(保留椭球兜底) */ export async function applyTerrain(viewer, terrainPlan) { const provider = await CesiumTerrainProvider.fromUrl(terrainPlan.url, { requestVertexNormals: terrainPlan.requestVertexNormals !== false, }) viewer.terrainProvider = provider return 'ready' } /** * 叠加影像句柄(票 39):把「精细层」包成一个只暴露必需动作的对象,供交接状态机驱动。 * * ── 两个必须讲清楚的 Cesium 事实(本票实现依据,都查过源码)── * * 1. **隐藏期间仍要继续预取瓦片**(决策 08 第 1 轮 Q4=A「看不见不等于停止加载」)。 * 瓦片是否被请求由 `GlobeSurfaceTile` 按 **`layer.show`** 决定 * (`Source/Scene/GlobeSurfaceTile.js:691` `if (layer.show) { layer._createTileImagerySkeletons(...) }`), * **不看 `alpha`**。所以"隐藏精细层"的正确做法是 **`alpha = 0` 且保持 `show = true`** —— * 用 `show = false` 会真的停掉预取,等揭示时才开始下载,正好造成"先空白再跳方块"。 * * 2. **alpha 只允许一处写**。本模块提供 `setAlpha()` 作为唯一入口, * 服务层与原型都不得直接摸 `layer.alpha`(原型若同时写会互相打架,见 mapService 的隔离注释)。 */ function createOverlayHandle(layer) { return { layer, /** 该层的原始 alpha(销毁/还原时用)。 */ initialAlpha: Number.isFinite(layer.alpha) ? layer.alpha : 1, /** 当前由交接写入的 alpha(读数与断言用;不代表"画面已遮住")。 */ alpha: Number.isFinite(layer.alpha) ? layer.alpha : 1, /** * 写 alpha(**唯一入口**)。 * * 刻意**不**动 `show`:`alpha = 0` 即不可见,但 `show` 保持 true 让瓦片继续预取 * (见上方事实 1)。UI 不可见 ≠ 停止加载。 */ setAlpha(value) { const next = Math.max(0, Math.min(1, Number.isFinite(value) ? value : 0)) this.alpha = next layer.alpha = next return next }, /** 当前层对象是否还有效(viewer 销毁后不要再碰)。 */ alive() { return !!layer && typeof layer.alpha === 'number' }, } } /** * 把相机**直接放到指定椭球高度**(DEV 诊断用;保持当前经纬度与姿态)。 * * 为什么放在引擎层:`Cartesian3` 只允许出现在本仓唯一 `import 'cesium'` 的地方(ADR 0004), * 服务层不碰 Cesium 类型。 * * 为什么不能直接赋值:`camera.positionWC` / `positionCartographic` 在 * `Source/Scene/Camera.js` 里**只有 getter**(内部由 `_position` 推导), * 赋值不会生效 —— 必须走 `setView()` 这个受支持入口。 * * @returns {number|null} 实际下发的椭球高度(米);失败返回 null */ export function setCameraAltitude(viewer, altitudeM) { if (!viewer || !viewer.camera || !viewer.scene || !viewer.scene.globe) return null if (!Number.isFinite(altitudeM)) return null try { const ellipsoid = viewer.scene.globe.ellipsoid const carto = ellipsoid.cartesianToCartographic(viewer.camera.positionWC) if (!carto) return null const camera = viewer.camera camera.setView({ destination: Cartesian3.fromRadians(carto.longitude, carto.latitude, altitudeM), orientation: { heading: camera.heading, pitch: camera.pitch, roll: camera.roll }, }) return Math.round(altitudeM) } catch (error) { return null } } /** 按配置顺序叠加影像层,返回**句柄数组**(票 39 起需要驱动 alpha,故不再只返回层数)。 */ export function applyOverlays(viewer, overlays) { const handles = [] for (const overlay of overlays || []) { const layer = new ImageryLayer(createOverlayProvider(overlay)) viewer.imageryLayers.add(layer) handles.push(createOverlayHandle(layer)) } return handles } /** * 目标视野的瓦片就绪读数(**如实标注它是代理信号**)。 * * `globe.tilesLoaded` = **地形与影像加载队列为空**(`Source/Scene/Globe.js:422` 的 getter), * 它**不证明**目标视野逐像素就绪 —— 决策票 08 明确警告过这一点。所以这里连同 * "它是代理"这个事实一起返回,免得下游把它当充分证明。 * * 瓦片失败:Cesium 在**没有任何 errorEvent 监听者**时会把错误直接抛到窗口 * (`ImageryLayer.js:1708` `handleError`),所以本层挂一个监听者把失败**收进读数**, * 而不是让它变成页面级报错(走查的「无页面级报错」会因此误伤)。 */ export function createOverlayReadiness(handles = []) { const state = { loaded: false, failed: 0, lastError: '' } const removers = [] for (const handle of handles) { const layer = handle && handle.layer if (!layer || !layer.errorEvent || typeof layer.errorEvent.addEventListener !== 'function') continue // 注意:Cesium 的 `Event.addEventListener` **返回一个"移除函数"**,不是 id // (`Source/Core/Event.js` 末尾 `return function () { event.removeEventListener(...) }`)。 const remove = layer.errorEvent.addEventListener((error) => { state.failed += 1 state.lastError = String((error && error.message) || error || '瓦片加载失败') }) if (typeof remove === 'function') removers.push(remove) } return { state, /** 由服务层在渲染循环里刷新(`globe.tilesLoaded` 是 getter,读它不便宜,故不在这里轮询)。 */ refresh(globe) { state.loaded = !!(globe && globe.tilesLoaded) return state }, detach() { for (const remove of removers) { try { remove() } catch { // 场景已销毁:忽略 } } removers.length = 0 }, } } /** * 3D Tiles 的公共诊断读数:排查「tileset.json 拉到了、内容却没请求」时, * 使用 Cesium 1.145 的公开 `tilesLoaded`、内存和 tile 事件结果;不读取内部 statistics/ready/contentState。 * `visited`/`selected` 保留为 null,因为 Cesium 没有公开的稳定逐帧字段。 */ export function readTilesetDiagnostics(tilesets) { const list = Array.isArray(tilesets) ? tilesets : [] return list.map((tileset) => { const root = tileset.root || {} return { visited: null, selected: null, contentReady: root ? Number(Boolean(root.content)) : 0, tilesLoaded: Boolean(tileset.tilesLoaded), memoryBytes: tileset.totalMemoryUsageInBytes || 0, rootHasContent: Boolean(root && root.content), rootChildren: Array.isArray(root && root.children) ? root.children.length : 0, maximumScreenSpaceError: tileset.maximumScreenSpaceError, } }) } /** * 挂 3D Tiles / 倾斜摄影(票 21):每个条目一个 tileset。 * 单项失败不影响其它项;返回 `{ ready, failed, instances }` 供上层如实报状态 * (页面不白屏、不静默),并把实例交出去给视图条件改透明度。 */ function applyBuildingLighting(scene, tileset) { // Derive a stable local daylight from this dataset's geographic bounds; do not key lighting to the camera. const origin = tileset.boundingSphere?.center if (!origin) return const frame = Transforms.eastNorthUpToFixedFrame(origin) const direction = Matrix4.multiplyByPointAsVector(frame, new Cartesian3(-0.4, -0.6, -1), new Cartesian3()) Cartesian3.normalize(direction, direction) scene.light = new DirectionalLight({ direction, intensity: 2.4 }) tileset.imageBasedLighting = new ImageBasedLighting({ imageBasedLightingFactor: new Cartesian2(1, 1), sphericalHarmonicCoefficients: [new Cartesian3(0.65, 0.65, 0.65), ...Array.from({ length: 8 }, () => new Cartesian3(0, 0, 0))], }) } const DEFAULT_TILESET_MAX_DISTANCE = 18000 const DEFAULT_TILESET_LOAD_DISTANCE = 6000 const MAX_LAZY_TILESET_LOADS = 1 /** 相机静止门槛:位移 ≤8m 且持续 600ms 才允许启动批次加载。 */ const CAMERA_IDLE_METERS = 8 const CAMERA_IDLE_MS = 600 /** 3D Tiles 资产缓存上限(字节):LOD 内容超过即淘汰,防止显存/内存无界增长。 */ const TILESET_CACHE_BYTES = 512 * 1024 * 1024 const TILESET_CACHE_OVERFLOW_BYTES = 256 * 1024 * 1024 function sphereFromTilesetRoot(root) { const box = root && root.boundingVolume && root.boundingVolume.box if (!Array.isArray(box) || box.length < 12) return null const transform = Array.isArray(root.transform) && root.transform.length === 16 ? Matrix4.fromArray(root.transform) : Matrix4.IDENTITY const center = Matrix4.multiplyByPoint(transform, new Cartesian3(box[0], box[1], box[2]), new Cartesian3()) const radii = [ Matrix4.multiplyByPointAsVector(transform, new Cartesian3(box[3], box[4], box[5]), new Cartesian3()), Matrix4.multiplyByPointAsVector(transform, new Cartesian3(box[6], box[7], box[8]), new Cartesian3()), Matrix4.multiplyByPointAsVector(transform, new Cartesian3(box[9], box[10], box[11]), new Cartesian3()), ] const radius = Math.sqrt(radii.reduce((sum, axis) => sum + Cartesian3.magnitudeSquared(axis), 0)) return { center, radius } } async function readTilesetRootSphere(plan) { const response = await fetch(plan.url, { cache: 'no-store' }) if (!response.ok) throw new Error(`tileset metadata ${response.status}: ${plan.url}`) const json = await response.json() const sphere = sphereFromTilesetRoot(json.root) if (!sphere) throw new Error(`tileset root bounding box missing: ${plan.url}`) return sphere } function tilesetOptions(plan) { const options = { skipLevelOfDetail: true, baseScreenSpaceError: 4096, skipScreenSpaceErrorFactor: 32, skipLevels: 2, immediatelyLoadDesiredLevelOfDetail: false, loadSiblings: false, cullRequestsWhileMoving: true, cullRequestsWhileMovingMultiplier: 90, dynamicScreenSpaceError: true, dynamicScreenSpaceErrorDensity: 0.01, dynamicScreenSpaceErrorFactor: 32, foveatedScreenSpaceError: true, foveatedConeSize: 0.1, foveatedMinimumScreenSpaceErrorRelaxation: 0, // SSE 提高到 96:只让视口中央占屏很大的单元才细化到 LOD0,避免进入批次瞬间 // 68 个 LOD1 单元 + LOD0 高模同时上屏(近景卡顿的直接来源)。 maximumScreenSpaceError: Number.isFinite(plan.maximumScreenSpaceError) ? plan.maximumScreenSpaceError : 96, cacheBytes: TILESET_CACHE_BYTES, maximumCacheOverflowBytes: TILESET_CACHE_OVERFLOW_BYTES, } return options } function createTilesetCullingController(scene, entries, instances, failed) { const camera = scene && scene.camera if (!camera || !camera.changed || !Array.isArray(entries) || !entries.length) return null let disposed = false let activeLoads = 0 let lastCameraPosition = null let lastCameraMoveAt = 0 let idleRetryTimer = null async function loadEntry(entry) { if (disposed || entry.loading || entry.instance) return entry.loading = true activeLoads += 1 try { const instance = await Cesium3DTileset.fromUrl(entry.plan.url, tilesetOptions(entry.plan)) if (disposed) { instance.destroy() return } if (entry.plan.lighting === true) applyBuildingLighting(scene, instance) instance.tileFailed.addEventListener((error) => { failed.push({ url: error.url || entry.plan.url, error: error.message || '3D Tiles 内容加载失败' }) }) scene.primitives.add(instance) entry.instance = instance instances.push(instance) } catch (error) { failed.push({ url: entry.plan.url, error: String((error && error.message) || error) }) } finally { entry.loading = false activeLoads = Math.max(0, activeLoads - 1) refresh() } } function refresh() { if (disposed) return const cameraPosition = camera.positionWC // 相机静止判定:与上一次 refresh 的位置差。移动中**只推迟批次加载**(显示/显存 // 切换照常实时更新),加载推迟到相机停下——"模型加载一开始整个场景都卡"的 // 根因就是加载与移动在同一批帧里争主线程。LOD 判定只用这个包围球距离,不用相机高度。 if (lastCameraPosition) { const moved = Cartesian3.distance(lastCameraPosition, cameraPosition) if (moved > CAMERA_IDLE_METERS) lastCameraMoveAt = Date.now() } lastCameraPosition = Cartesian3.clone(cameraPosition) const candidates = [] for (const entry of entries) { if (!entry.sphere) continue const maximumDistance = Number.isFinite(entry.plan.maximumDistance) ? entry.plan.maximumDistance : DEFAULT_TILESET_MAX_DISTANCE const loadDistance = Number.isFinite(entry.plan.loadDistance) ? entry.plan.loadDistance : Math.min(DEFAULT_TILESET_LOAD_DISTANCE, maximumDistance) const distance = Math.max(0, Cartesian3.distance(cameraPosition, entry.sphere.center) - entry.sphere.radius) entry.distance = distance const isFarLayer = entry.plan.role === 'far' if (entry.instance) { const visible = isFarLayer ? true : distance <= loadDistance if (entry.instance.show !== visible) entry.instance.show = visible if (!entry.plan.eager && !isFarLayer && distance > loadDistance * 2) { scene.primitives.remove(entry.instance) entry.instance.destroy() const index = instances.indexOf(entry.instance) if (index >= 0) instances.splice(index, 1) entry.instance = null } } else if (!entry.loading && (entry.plan.eager || isFarLayer || distance <= loadDistance)) { candidates.push({ entry, distance }) } } // 远景粗模层只在**没有任何精细批次实际上屏**时才显示: // 精细批次先预载(loadDistance 提前于显示),上屏后才切走粗模,避免加载间隙出现空白县城。 const fineShowing = entries.some((entry) => entry.plan.role !== 'far' && entry.instance && entry.instance.show) for (const entry of entries) { if (entry.plan.role === 'far' && entry.instance && entry.instance.show !== !fineShowing) { entry.instance.show = !fineShowing } } if (activeLoads < MAX_LAZY_TILESET_LOADS && candidates.length) { if (Date.now() - lastCameraMoveAt >= CAMERA_IDLE_MS) { // 相机已静止:可以安全加载(加载期间 requestRenderMode 让解码不被渲染循环挤占)。 candidates.sort((a, b) => a.distance - b.distance) void loadEntry(candidates[0].entry) } else { // 仍在移动:挂一个短定时器再查一次——停下后没有 camera.changed 事件, // 没有这个重查,加载会被永远推迟。 if (!idleRetryTimer) { idleRetryTimer = setTimeout(() => { idleRetryTimer = null refresh() }, CAMERA_IDLE_MS) } } } } const detach = camera.changed.addEventListener(refresh) return { refresh, async prepare() { await Promise.all(entries.map(async (entry) => { try { entry.sphere = await readTilesetRootSphere(entry.plan) } catch (error) { failed.push({ url: entry.plan.url, error: String((error && error.message) || error) }) } })) await Promise.all(entries.filter((entry) => entry.plan.eager !== false).map((entry) => loadEntry(entry))) refresh() }, detach() { disposed = true if (idleRetryTimer) { clearTimeout(idleRetryTimer) idleRetryTimer = null } detach() }, } } /** * 3D Tiles 懒加载:启动只读根 tileset.json 的包围盒,eager 批次立即加载, * 其余批次只有相机进入 loadDistance 才初始化;离开较远区域后销毁非 eager 批次。 * 已加载 tileset 仍由 Cesium 做 tile 级视锥剔除和内部 LOD。 */ export async function applyTilesets(scene, tilesets) { // 全局请求节流:默认 50 并发会让进入批次瞬间的 GLB 下载+解码挤在同一批帧里(近景卡顿)。 // 限到 10/5:模型、地形、影像三类请求共享同一调度器,加载期间后两者必须还有余量。 try { RequestScheduler.maximumRequests = 10 RequestScheduler.maximumRequestsPerServer = 5 } catch { // 老版本没有这些字段时保持默认。 } const instances = [] const failed = [] const entries = (tilesets || []).map((plan) => ({ plan, sphere: null, instance: null, loading: false, distance: null })) const culling = createTilesetCullingController(scene, entries, instances, failed) if (culling) await culling.prepare() return { ready: instances.length, failed, instances, culling } } /** * 视图条件对图层的影响(票 21):管线视图把地形与 3D Tiles 压成半透明(保留空间参照, * 不完全隐藏),地面视图还原为完全不透明。 * * 地形用 Cesium 的 `globe.translucency`(前台/背面 alpha 一起设,避免只透一半); * 3D Tiles 用 `Cesium3DTileStyle` 的 color alpha。两者都只改显示,不动数据,也不碰相机。 * @param {object} viewer * @param {Array} tilesets 已挂上的 tileset 实例(applyTilesets 的 instances) * @param {object} plan `domain/viewModes.js` 的 planViewMode() */ export function applyViewModeLayers(viewer, tilesets, plan) { if (!viewer || !plan) return const globe = viewer.scene && viewer.scene.globe if (globe) { // 始终参与真实地形深度;管线透视只由显式 translucency 开关控制。 globe.depthTestAgainstTerrain = true const alpha = Number.isFinite(plan.terrainAlpha) ? plan.terrainAlpha : 1 globe.translucency.enabled = alpha < 1 globe.translucency.frontFaceAlpha = alpha globe.translucency.backFaceAlpha = alpha } const alpha = Number.isFinite(plan.tilesetAlpha) ? plan.tilesetAlpha : 1 for (const tileset of tilesets || []) { try { // 地面视图还原 = 清掉样式(而不是设成 white/1,省得留一份无意义样式)。 tileset.style = alpha < 1 ? new Cesium3DTileStyle({ color: `color('white', ${alpha})` }) : undefined } catch { // 单个 tileset 不支持 style 时忽略,不影响其它图层。 } } } export function destroyViewer(viewer) { viewer.destroy() } // ================================================================ 自建视距雾(票 38) /** 自建雾处理级的名字(唯一一个)。 */ export const FOG_STAGE_NAME = 'cockpit-area-fog' /** * 世界射线距离雾的片元着色器(**B 方案:只处理有有效几何深度的地物**)。 * * 契约来源 `cockpit-primary-area-guardrails/spec-fog.md`(决策票 07 固化 B 方案)。三条硬约束: * * 1. **无有效深度 ≠ 天空**,但本级**不重绘它**:`rawDepth >= 1.0` 时整段返回原色 * (不套雾色、不做地平线渐变)。依据决策票 07「采用 B:仅地物距离雾……无有效几何深度背景保持原颜色」, * 以及其只读复核「深度清为 1.0,天空盒与大气不写深度」「无深度值也可能对应没写自身深度的透明内容」。 * 2. **只反解一次对数深度**:`czm_windowToEyeCoordinates(gl_FragCoord.xy, rawDepth)` 这个重载 * **内部自己解 log**(`windowToEyeCoordinates.glsl`),喂给它的是**原始** `texture(depthTexture).r`。 * 先 `czm_reverseLogDepth` 再传进去会解两次 —— 复核里点名的坑。 * 沿视线的距离取重建位置的长度,不取 `-z`;并按 `gl_FragCoord.w` 做齐次除法。 * 3. **两端语义精确**:0 处全清、`endDistance` 处全遮蔽。曲线形状(smoothstep + 保端点光学厚度) * 在 `domain/fog.js` 的 `fogAttenuation` 里算好,这里只做 `mix`,**GLSL 不重写一份数学** * (两处各写一份必然漂移,而端点语义是本票的验收点)。 * * 与原型 `prototypes/fog-prototype-stage.js`(**已归档到 `throwaway/cockpit-prototypes` 分支**, * 票 40 收口)的区别:去掉只有决策票 07 才有的 C 方案分支 * (地平线染色与太阳暖色,已裁定不采用),并改用 CPU 侧算好的强度 uniform。 */ const FOG_FRAGMENT_SHADER = ` uniform sampler2D colorTexture; uniform sampler2D depthTexture; uniform vec3 fogColor; uniform float effectStrength; uniform float startDistance; uniform float endDistance; in vec2 v_textureCoordinates; // 世界射线距离 → 不透明度。与 domain/fog.js 的 fogAttenuation 同一形状, // 但它必须在 GPU 上逐片元算,所以这里保留一份等价实现;**端点断言在 CPU 侧**。 float fogAlpha(float distanceM) { if (distanceM <= startDistance) return 0.0; if (distanceM >= endDistance) return 1.0; float t = (distanceM - startDistance) / (endDistance - startDistance); float smoothT = t * t * (3.0 - 2.0 * t); return (1.0 - exp(-3.0 * smoothT)) / (1.0 - exp(-3.0)); } void main() { vec4 base = texture(colorTexture, v_textureCoordinates); float rawDepth = texture(depthTexture, v_textureCoordinates).r; // 无有效几何深度:**保留原色**(B 方案)。这一支也不做"天空分类"的臆断。 if (rawDepth >= 1.0) { out_FragColor = base; return; } // 原始深度交给这个重载,它内部自己解 log;再补一次齐次除法。 vec4 eye = czm_windowToEyeCoordinates(gl_FragCoord.xy, rawDepth); vec3 eyePos = eye.xyz / eye.w; float distanceM = length(eyePos); float alpha = clamp(fogAlpha(distanceM) * effectStrength, 0.0, 1.0); out_FragColor = vec4(mix(base.rgb, fogColor, alpha), base.a); }` /** * 在场景上建**唯一**一个自建雾处理级(票 38)。幂等:同一 viewer 只会有一个。 * * 三条实现要点,每条都对着决策票 07 的只读复核: * · **能力探测交给引擎**:stage 声明了 `depthTexture` 而设备不支持时, * `PostProcessStage` 自己会整级禁用(`_isSupported`);我们只如实读回 `stage.ready` * 与 `scene.context.depthTexture`,不自己造探测逻辑。 * · **复用对象**:进出与调强度都只改 uniform,不 remove/add(`PostProcessStageCollection.remove` * 会 destroy,对象不可复用)。只有离开地图才 `remove` + 释放。 * · **禁用不等于零开销**:规格明确「禁用后引擎仍可能准备/清理后处理 framebuffer」, * 所以对外措辞只说"禁用",不承诺"完全没有 GPU 开销"。 * * @param {Viewer} viewer * @param {object} params `domain/fog.js` 的 `planFog()` 结果 * @returns {{stage: PostProcessStage, uniforms: object, supported: boolean, destroy: () => void}} */ export function createFogStage(viewer, params) { const scene = viewer.scene /** * 雾的动态 uniform **必须用函数传**(不能用常量)。 * * 依据(Cesium 1.145 `PostProcessStage` 源码,本票实测确认): * · 构造时 `_actualUniforms[name] = uniforms[name]` 会**快照一份**常量值; * · 之后每帧喂给 shader 的是 `_actualUniforms`(`getUniformMapFunction` 读它), * 而 `stage._uniforms` 在构造末尾被**换成另一个对象**。 * 所以「传常量 + 事后改那个常量对象」**永远不会生效** —— 改了原始对象, * 快照仍是初值,shader 拿到的始终是初值。症状极具迷惑性: * 读数、dataset、`stage.enabled` 全都说"已启用、强度 1",而**画面上什么都没有**。 * * 这也正是可丢弃原型 `prototypes/fog-prototype-stage.js`(**已归档到 * `throwaway/cockpit-prototypes` 分支**,票 40 收口)用 `() => params.amount` * 这种写法能跑通的原因 —— 函数形式的 uniform 每帧现取,天然支持动态改值。 */ const state = { fogColor: new Cartesian3(1, 1, 1), effectStrength: 0, startDistance: params.startDistance, endDistance: params.endDistance, } const stage = scene.postProcessStages.add( new PostProcessStage({ name: FOG_STAGE_NAME, fragmentShader: FOG_FRAGMENT_SHADER, uniforms: { fogColor: () => state.fogColor, effectStrength: () => state.effectStrength, startDistance: () => state.startDistance, endDistance: () => state.endDistance, }, }), ) // 先禁用:强度为 0 时不该有任何一次全屏 pass(首次启用由宿主显式打开)。 stage.enabled = false return { stage, state, /** 深度能力:`Context.depthTexture` 是**布尔能力标志**(不是纹理对象,且不在 d.ts 里)。 */ supported: scene.context ? scene.context.depthTexture === true : false, /** * DEV 诊断:对比"我们以为写进去的强度"与"Cesium 真正喂给 shader 的强度"。 * * 读的是 `stage._uniformMap[name]()` —— 那是每帧实际取值的那条路径, * 也是唯一能证伪"值到底有没有送进 shader"的地方。两者不一致就说明 uniform 通道没接对 * (常量快照坑:直接写原始对象绕过了 setter,`_actualUniforms` 永远是初值)。 */ readUniformDiagnostics() { let delivered = null let storedKind = null let storedValue = null try { const uniformMap = stage._uniformMap delivered = uniformMap && typeof uniformMap.effectStrength === 'function' ? uniformMap.effectStrength() : null } catch (error) { delivered = null } try { // `_actualUniforms` 在**构造时**就写好了(不等渲染),所以这一项在隐藏标签页里也可读。 // 它是判定"动态 uniform 有没有接对"的决定性证据: // · 存的是 `function` → 每帧现取,改 state 立刻生效(正确形态); // · 存的是 `number` → 构造时快照,事后改原始对象**永远不生效**(本票的坑)。 const stored = stage._actualUniforms ? stage._actualUniforms.effectStrength : undefined storedKind = typeof stored storedValue = typeof stored === 'number' ? stored : null } catch (error) { storedKind = null } return { intended: state.effectStrength, deliveredToShader: delivered, matches: delivered === state.effectStrength, /** `'function'` = 动态(对);`'number'` = 常量快照(错,改了不生效)。 */ storedKind, storedValue, enabled: stage.enabled, ready: stage.ready === true, } }, destroy() { if (scene.isDestroyed && scene.isDestroyed()) return if (stage.isDestroyed && stage.isDestroyed()) return scene.postProcessStages.remove(stage) }, } } /** 把强度与颜色写进 uniform(**只改 dynamic state,不重建 stage**)。 */ export function applyFogUniforms(handle, { strength, colorRgb, startDistance, endDistance }) { if (!handle || !handle.state) return const state = handle.state if (Number.isFinite(strength)) state.effectStrength = Math.min(1, Math.max(0, strength)) if (colorRgb) state.fogColor = new Cartesian3(colorRgb.r, colorRgb.g, colorRgb.b) if (Number.isFinite(startDistance)) state.startDistance = startDistance if (Number.isFinite(endDistance)) state.endDistance = endDistance // 开关与强度同源:强度为 0 就没有必要跑这一遍全屏 pass。 if (handle.stage) handle.stage.enabled = state.effectStrength > 0 } /** 该处理级是否已可执行(**不等于**画面已被遮住 —— 规格明确区分这两件事)。 */ export function fogStageExecutable(handle) { if (!handle || !handle.stage) return false if (handle.stage.isDestroyed && handle.stage.isDestroyed()) return false return handle.stage.ready === true } /** 当前是否有自建雾处理级挂在场景上(排查与走查读数)。 */ export function hasFogStage(viewer) { if (!viewer || !viewer.scene || !viewer.scene.postProcessStages) return false return viewer.scene.postProcessStages.length > 0 } // ================================================================ 点位标记(票 09) /** * 点位标记的数据源名:**唯一一个**,重新同步时整份替换而不是叠加 * (否则翻一页就多画一批,地图上会出现已经不存在于当前快照的点)。 */ export const POINT_MARKER_SOURCE = 'cockpit-point-markers' /** 管线数据源名(票 22 交付;票 14 的高亮已经按它扫,落地当天即生效,不需要再改高亮)。 */ export const PIPELINE_SOURCE = 'cockpit-pipelines' /** * 关联监测设备图层的**独立**数据源名(票 42)。 * * 与 `POINT_MARKER_SOURCE` 分开是**结构性**的:关联设备只进这个临时图层, * 永远不写回摘要标记计划(规格:摘要分页、摘要图例、`data-map-markers*` 都不含它)。 */ export const DEVICE_MARKER_SOURCE = 'cockpit-associated-device-markers' /** * 建/取点位标记的数据源(幂等)。 * * **必须自己缓存实例,不能只靠 `dataSources.getByName()`**: * Cesium 的 `DataSourceCollection.add()` 是**异步**的(`Promise.resolve(ds).then(...)` 里才 push * 进 `_dataSources`)。同一个 tick 里「先写后读」会走成这样: * 1. `syncPointMarkers()` 建了数据源 A(还没注册进集合)并把 8 个标记加进 A; * 2. 紧接着 `readPointMarkers()` 调 `getByName()` —— 集合里还没有 A,于是**又建了一个空数据源 B**, * 读回来 0 个标记。 * 症状极具迷惑性:模块计数与 dataset 都说 8,组件渲染出来的却是「点位标记 0」, * 而晚一点的 DEV 把手调用(那时 A 已注册)又读回 8 —— 同一个页面两套答案。 * 这是视觉探针截图里「图例有计数、标记写 0」的真正原因(走查没抓到,因为它读的是 dataset 与 DEV 把手)。 * * 用 WeakMap 按 viewer 缓存:viewer 销毁后条目自然消失,不会漏实例,也不会在集合里留空数据源。 */ const markerSources = new WeakMap() function pointMarkerSource(viewer) { const cached = markerSources.get(viewer) if (cached) return cached // 兜一道:热重载等情况下集合里可能已经有同名数据源,优先复用它。 const existing = viewer.dataSources.getByName(POINT_MARKER_SOURCE)[0] if (existing) { markerSources.set(viewer, existing) return existing } const source = new CustomDataSource(POINT_MARKER_SOURCE) viewer.dataSources.add(source) markerSources.set(viewer, source) return source } /** * 把标记计划同步到地图上(票 09 验收第 1 条:标记按后端返回状态渲染)。 * * 形状与颜色**都来自计划**(`domain/pointStatus.js` + 服务层读出的语义色): * 引擎这一层不认识「报警」这种业务词,只认 `shape` 与 `color`,所以状态→视觉的映射 * 只有一份,不会在这里长出第二份。 * * `HeightReference.CLAMP_TO_GROUND` 让标记贴着地形(票 21 有 DEM,票 30 已有地形感知拾取), * 否则点位会浮在山体上方或埋进去。缺坐标/非法坐标的对象**不在计划里**(票 07 已拦下)。 * * @param {Viewer} viewer * @param {Array} markers `domain/pointStatus.js` 的 `planPointMarkers().markers` * @param {(marker: object) => string} colorOf 取该标记的 CSS 颜色(服务层从 token 读,引擎不写色值) * @param {(shape: string, color: string) => string} imageOf 形状+颜色 → 图片 URL(domain/markerSvg) * @returns {{rendered: number, skipped: number}} */ export function syncPointMarkers(viewer, markers, colorOf, imageOf) { const source = pointMarkerSource(viewer) source.entities.removeAll() let rendered = 0 let skipped = 0 for (const marker of markers || []) { // 经纬度缺失或非有限值不上图:计划层已按 `renderable` 过滤, // 这里再挡一道,免得脏数据把整批 entity 建崩(一条坏数据不该让其余点位消失)。 if (!Number.isFinite(marker.longitude) || !Number.isFinite(marker.latitude)) { skipped += 1 continue } const color = colorOf(marker) source.entities.add({ id: `point|${marker.key}`, position: Cartesian3.fromDegrees(marker.longitude, marker.latitude), billboard: { image: imageOf(marker.shape, color), // 像素尺寸同步放大:大屏上 12px 的点位看不清形状(形状是「不只靠颜色」的那一半)。 width: 18, height: 18, scale: 1, // 贴地:有地形时点位落在地表而不是椭球面。 heightReference: HeightReference.CLAMP_TO_GROUND, verticalOrigin: VerticalOrigin.CENTER, disableDepthTestDistance: Number.POSITIVE_INFINITY, }, // 供走查/人工排查读状态:不依赖中文字符串,也不依赖读图。 properties: { pointCode: marker.code, deviceCodes: marker.deviceCodes || [], pointKind: marker.kind, pointStatus: marker.status, visualKey: marker.visualKey, shape: marker.shape, tone: marker.tone, }, }) rendered += 1 } return { rendered, skipped } } /** * 只读回点位标记的**真实图层内容**(走查据此断言「标记真的画在地图上」, * 而不是只信计划算出来的数)。 * * 除了计数与状态分布,还回每个视觉键对应的 billboard 图片 URL:走查用它证明 * 「每个状态的颜色确实不同、形状确实是形状」——这两件事只有从引擎实体上读才算证据。 */ export function readPointMarkers(viewer) { const source = pointMarkerSource(viewer) const byStatus = {} const shapes = new Set() const images = {} for (const entity of source.entities.values) { const properties = entity.properties || {} const get = (key) => (properties[key] ? properties[key].getValue() : '') const visualKey = get('visualKey') || 'UNKNOWN' const shape = get('shape') || '' byStatus[visualKey] = (byStatus[visualKey] || 0) + 1 if (shape) shapes.add(shape) // 同一视觉键只留一份图片,够判「不同状态图片不同」。 if (!images[visualKey]) { const billboard = entity.billboard images[visualKey] = { shape, tone: get('tone'), image: billboard ? billboard.image.getValue() : '', } } } return { count: source.entities.values.length, byStatus, shapes: [...shapes].filter(Boolean).sort(), images } } /** * 只读回点位标记的**窗口坐标**(票 45 走查用:真实鼠标要点的位置)。 * * 与 `readOverlapTargets` 同一条纪律:只回投影后的屏幕坐标与身份,不出 Cesium 实体。 * 用**逻辑可见性** `entity.show`(`isShowing` 是渲染态,headless 下会差一帧)。 */ export function readPointMarkerTargets(viewer) { const source = pointMarkerSource(viewer) const rect = viewer && viewer.canvas ? viewer.canvas.getBoundingClientRect() : null if (!rect || !viewer.scene) return [] const ellipsoid = viewer.scene.globe && viewer.scene.globe.ellipsoid return source.entities.values .map((entity) => { const properties = entity.properties || {} const get = (key) => (properties[key] && properties[key].getValue ? properties[key].getValue() : '') const position = entity.position && entity.position.getValue ? entity.position.getValue(viewer.clock.currentTime) : null if (!position) return null // 点位标记是 `HeightReference.CLAMP_TO_GROUND` **贴地形**渲染的; // 直接投影 `entity.position`(椭球零高度)会与画面上看到的标记差出一段地形高度, // 真实鼠标按那个坐标点会**打不中**(票 45 真实路径走查抓到)。 // 这里与渲染同口径:先取地形高度,再投影。 let world = position if (ellipsoid) { const carto = ellipsoid.cartesianToCartographic(position) if (carto) { let height = 0 const sampled = viewer.scene.globe.getHeight(carto) if (Number.isFinite(sampled)) height = sampled world = Cartesian3.fromRadians(carto.longitude, carto.latitude, height) } } const projected = SceneTransforms.worldToWindowCoordinates(viewer.scene, world) if (!projected || !Number.isFinite(projected.x) || !Number.isFinite(projected.y)) return null return { x: projected.x + rect.left, y: projected.y + rect.top, code: get('pointCode'), status: get('pointStatus'), visible: entity.show !== false, } }) .filter(Boolean) } /** 清空点位标记(快照失效/刷新前用:旧快照的点不得留在图上)。 */ export function clearPointMarkers(viewer) { pointMarkerSource(viewer).entities.removeAll() } // ================================================================ 关联监测设备图层(票 42) const deviceSources = new WeakMap() /** 建/取关联设备图层的数据源(幂等,与点位标记同款:必须自己缓存,理由见上方注释)。 */ function deviceMarkerSource(viewer) { const cached = deviceSources.get(viewer) if (cached) return cached const existing = viewer.dataSources.getByName(DEVICE_MARKER_SOURCE)[0] if (existing) { deviceSources.set(viewer, existing) return existing } const source = new CustomDataSource(DEVICE_MARKER_SOURCE) viewer.dataSources.add(source) deviceSources.set(viewer, source) return source } /** * 把**当前选中点位的关联设备**同步到独立临时图层(票 42)。 * * 三件事是规格硬要求,都体现在签名与实体属性上: * 1. **整份替换**(`removeAll` 后重建):关闭/换点/刷新时旧图层立即撤下,不会与新的混在一起; * 2. **独立身份**:实体 id 与属性都带 `deviceCode` **和** `monitoringPointCode`, * 绝不写 `pointCode` —— 设备不冒充监测点(票 05 的结构性保证); * 3. **尺寸小于监测点**(14 vs 18):层级靠尺寸区分,具体形状/资产接缝归票 44。 * * 调用方只传**已判定可上图**的行(`domain/deviceLayer.js` 的 `placement === 'drawn'`); * 这里再挡一道经纬度,避免一条脏数据把整批 entity 建崩。 * * @param {Viewer} viewer * @param {Array} devices 领域行(含 `code`/`pointCode`/`longitude`/`latitude`/`status`) * @param {(device: object) => string} colorOf 取该设备的 CSS 颜色(色值仍由服务层从 token 读) * @param {(shape: string, color: string) => string} imageOf 形状+颜色 → 图片 URL * @returns {{rendered: number, skipped: number}} */ export function syncAssociatedDevices(viewer, devices, colorOf, imageOf, overlapGroups = []) { const source = deviceMarkerSource(viewer) source.entities.removeAll() // 票 47:实体是**整份重建**的,动效基准与循环必须一起复位 // (否则基准表里留着上一批实体的 id,动效会写到不存在的对象上)。 deviceBaseStyle.clear() stopDeviceEffects() let rendered = 0 let skipped = 0 const groupsByCode = new Map() for (const group of Array.isArray(overlapGroups) ? overlapGroups : []) { if (!group || group.k < 2) continue for (const row of group.rows || []) groupsByCode.set(row.code, group) } for (const device of devices || []) { if (!Number.isFinite(device.longitude) || !Number.isFinite(device.latitude)) { skipped += 1 continue } const color = colorOf(device) // 票 44:尺寸与形状都来自**单一资产接缝**(`domain/deviceAssets.js` 的计划), // 引擎不认识"设备该多大",也不写死尺寸字面量。 const size = Number.isFinite(device.size) ? device.size : 14 const group = groupsByCode.get(device.code) source.entities.add({ id: `device|${device.pointCode}|${device.code}`, position: Cartesian3.fromDegrees(device.longitude, device.latitude), show: !group, billboard: { image: imageOf(device.shape || 'circle', color, size), width: size, height: size, scale: 1, pixelOffset: new Cartesian2(0, 0), heightReference: HeightReference.CLAMP_TO_GROUND, verticalOrigin: VerticalOrigin.CENTER, }, properties: { deviceCode: device.code, monitoringPointCode: device.pointCode, deviceStatus: device.status || '', deviceShape: device.shape || 'circle', assetMode: device.assetMode || '', assetReason: device.assetReason || '', assetReasonText: device.assetReasonText || '', overlapGroup: group ? group.key : '', overlapPointCode: group ? group.pointCode : '', overlapAggregate: false, overlapFanIndex: -1, }, }) rendered += 1 } // 聚合符号没有 deviceCode:拾取它只能返回 overlap action,不能冒充任一台设备。 for (const group of Array.isArray(overlapGroups) ? overlapGroups : []) { if (!group || group.k < 2 || !group.rows.length) continue const representative = group.rows.find((row) => row.status === (group.visual && group.visual.status)) || group.rows[0] const color = colorOf(representative) const size = Number.isFinite(representative.size) ? representative.size : 14 source.entities.add({ id: `overlap|${group.pointCode}|${group.key}`, position: Cartesian3.fromDegrees(representative.longitude, representative.latitude), billboard: { image: imageOf(group.visual.shape, color, size), width: size, height: size, scale: 1, pixelOffset: new Cartesian2(0, 0), heightReference: HeightReference.CLAMP_TO_GROUND, verticalOrigin: VerticalOrigin.CENTER, }, label: { text: String(group.k), font: 'bold 12px sans-serif', fillColor: Color.WHITE, outlineColor: Color.BLACK, outlineWidth: 2, style: LabelStyle.FILL_AND_OUTLINE, pixelOffset: new Cartesian2(14, -12), verticalOrigin: VerticalOrigin.CENTER, }, properties: { overlapAggregate: true, overlapGroup: group.key, overlapPointCode: group.pointCode, overlapCount: group.k, overlapState: group.state, overlapLabel: group.label, deviceStatus: group.visual.status, // 不能含 `deviceCode` / `monitoringPointCode`:聚合符号不冒充设备身份。 }, }) } return { rendered: devices ? devices.length : 0, skipped } } /** * 展开/预览重叠设备:只改 billboard `pixelOffset`(屏幕渲染层);实体 position 与属性经纬度不动。 * `offsets` 是 `{[deviceCode]: {x,y}}`;collapsed 时恢复为 0。 */ export function nudgeOverlap(viewer, groupKey) { const source = deviceMarkerSource(viewer) let touched = 0 for (const entity of source.entities.values) { const properties = entity.properties || {} const group = properties.overlapGroup && properties.overlapGroup.getValue ? properties.overlapGroup.getValue() : '' const aggregate = properties.overlapAggregate && properties.overlapAggregate.getValue ? properties.overlapAggregate.getValue() : false if (group !== groupKey || aggregate !== true) continue if (entity.billboard) { entity.billboard.scale = 1.18 entity.billboard.outlineWidth = 2 entity.billboard.outlineColor = Color.WHITE.withAlpha(0.85) } touched += 1 } return touched } /** 清空重叠聚合面板hover弱提示。 */ export function clearOverlapNudge(viewer) { const source = deviceMarkerSource(viewer) for (const entity of source.entities.values) { const properties = entity.properties || {} const aggregate = properties.overlapAggregate && properties.overlapAggregate.getValue ? properties.overlapAggregate.getValue() : false if (aggregate && entity.billboard) { entity.billboard.scale = 1 entity.billboard.outlineWidth = 0 } } } export function setOverlapPresentation(viewer, { groupKey = '', state = 'collapsed', preview = false, offsets = {} } = {}) { const source = deviceMarkerSource(viewer) let touched = 0 for (const entity of source.entities.values) { const properties = entity.properties || {} const read = (key) => properties[key] && properties[key].getValue ? properties[key].getValue() : '' if (!groupKey || read('overlapGroup') !== groupKey) continue const aggregate = read('overlapAggregate') === true const showFan = state === 'expanded' if (aggregate) { entity.show = showFan ? preview : true } else { const code = read('deviceCode') const offset = offsets[code] entity.show = showFan && Boolean(offset) if (entity.billboard) { entity.billboard.pixelOffset = offset ? new Cartesian2(offset.x, offset.y) : new Cartesian2(0, 0) } } touched += 1 } return touched } /** 只读回关联设备图层的真实内容(走查据此断言「设备真的画在独立图层上」,以及「画成的样子来自接缝」)。 */ export function readAssociatedDevices(viewer) { const source = deviceMarkerSource(viewer) return source.entities.values.map((entity) => { const properties = entity.properties || {} const get = (key) => (properties[key] ? properties[key].getValue() : '') // 票 44:实体上**已经**带着接缝的结论(形状/资产模式/降级原因),原读取器却把它们丢掉了 —— // 于是「地图上真画的那台设备是什么形状、什么资产模式」在引擎侧读不到,走查只能退回去读 // 计划行(那是"打算画什么",不是"画成了什么")。这里如实读回来。 // 尺寸取 **billboard 的真实宽高**,而不是再读一个属性:这样读到的是真画上去的尺寸。 const size = entity.billboard && entity.billboard.width ? entity.billboard.width.getValue() : null return { id: entity.id, deviceCode: get('deviceCode'), monitoringPointCode: get('monitoringPointCode'), deviceStatus: get('deviceStatus'), shape: get('deviceShape'), size, assetMode: get('assetMode'), assetReason: get('assetReason'), assetReasonText: get('assetReasonText'), visible: entity.isShowing === true, overlapAggregate: get('overlapAggregate') === true, overlapGroup: get('overlapGroup'), overlapPointCode: get('overlapPointCode'), overlapCount: get('overlapCount'), pixelOffset: entity.billboard && entity.billboard.pixelOffset ? entity.billboard.pixelOffset.getValue() : null, } }) } /** 清空关联设备图层(关闭 / 换点 / 快照失效 / 离开页面都走它)。 */ /** * 票 45:重叠实体的只读窗口坐标(真实 Cesium 投影 + pixelOffset)。 * 走查用它把真实鼠标送到聚合符号/展开子点;只读渲染坐标,不写设备经纬度。 */ export function readOverlapTargets(viewer) { const source = deviceMarkerSource(viewer) const rect = viewer && viewer.canvas ? viewer.canvas.getBoundingClientRect() : null if (!rect || !viewer.scene) return [] return source.entities.values .filter((entity) => entity.properties && entity.properties.overlapGroup) .map((entity) => { const position = entity.position && entity.position.getValue ? entity.position.getValue(viewer.clock.currentTime) : null const projected = position ? SceneTransforms.worldToWindowCoordinates(viewer.scene, position) : null if (!projected || !Number.isFinite(projected.x) || !Number.isFinite(projected.y)) return null const properties = entity.properties || {} const get = (key) => properties[key] && properties[key].getValue ? properties[key].getValue() : '' const offset = entity.billboard && entity.billboard.pixelOffset && entity.billboard.pixelOffset.getValue ? entity.billboard.pixelOffset.getValue() : { x: 0, y: 0 } return { x: projected.x + rect.left + (offset.x || 0), y: projected.y + rect.top + (offset.y || 0), // 用**逻辑可见性** `entity.show`(Cesium 里 `isShowing` 是渲染态,headless 下 // `show` 改变后可能要等一帧才同步;拾取判据不能依赖渲染帧,否则展开态设备 // 会被误滤掉而聚合却可见 —— 真机走查抓到过这一帧)。 visible: entity.show !== false, aggregate: get('overlapAggregate') === true, deviceCode: get('deviceCode'), overlapGroup: get('overlapGroup'), } }) .filter(Boolean) } export function clearAssociatedDevices(viewer) { // 票 47:图层撤下 ⇒ 特效随图层一起消失(决策票 07:不需要单独的消失逻辑, // 因为特效就挂在图层上)。这里显式停循环,避免空转写帧。 stopDeviceEffects() deviceBaseStyle.clear() deviceMarkerSource(viewer).entities.removeAll() } /** * 屏幕坐标 → **设备标记身份**(票 42 的独立拾取入口;票 43 会在此基础上做双向联动)。 * * 与 `pickPointMarkerAt()` 同一条纪律:只认本图层上带 `deviceCode` 的实体, * 回**身份**不回 Cesium 实体,且**设备优先于监测点**(票 15 的拾取优先级)。 */ function overlapTargetAt(viewer, windowX, windowY) { const targets = readOverlapTargets(viewer) let nearest = null let distance = Infinity for (const target of targets.filter((item) => item.visible)) { const current = Math.hypot(target.x - windowX, target.y - windowY) if (current <= 24 && current < distance) { nearest = target distance = current } } if (!nearest) return null if (nearest.aggregate) return { kind: 'monitoring-device-overlap', code: '', pointCode: '', overlapGroup: nearest.overlapGroup } if (nearest.deviceCode) return { kind: 'monitoring-device', code: nearest.deviceCode, pointCode: '', status: '' } return null } export function pickDeviceMarkerAt(viewer, windowX, windowY) { if (!viewer || !viewer.scene || !viewer.canvas || typeof viewer.scene.pick !== 'function') return null // 票45:展开后的设备拥有屏幕pixelOffset;先按公开投影读数做近邻身份判定, // 避免同屏监测点/地形顶层对象让普通scene.pick吞掉真实设备。仍保持普通拾取语义。 const projectedHit = overlapTargetAt(viewer, windowX, windowY) if (projectedHit) return projectedHit const rect = viewer.canvas.getBoundingClientRect() const picked = viewer.scene.pick(new Cartesian2(windowX - rect.left, windowY - rect.top)) const entity = picked && picked.id const properties = entity && entity.properties if (properties) { const read = (key) => (properties[key] ? properties[key].getValue() : '') if (read('overlapAggregate') === true) { return { kind: 'monitoring-device-overlap', code: '', pointCode: read('overlapPointCode'), overlapGroup: read('overlapGroup'), overlapCount: read('overlapCount'), } } const code = read('deviceCode') if (code) return { kind: 'monitoring-device', code, pointCode: read('monitoringPointCode'), status: read('deviceStatus') } } // 重叠聚合与监测点同屏时,scene.pick 可能只返回顶层点位; // 用聚合实体投影做近邻补偿,仍是普通拾取、不改真实位置。 return overlapTargetAt(viewer, windowX, windowY) } /** 某台设备标记是否存在(暂隐/重新定位类判据用)。 */ export function hasDeviceMarker(viewer, pointCode, code) { if (!viewer || !code) return false const source = deviceSources.get(viewer) || viewer.dataSources.getByName(DEVICE_MARKER_SOURCE)[0] return !!(source && source.show && source.entities.getById(`device|${pointCode}|${code}`)) } // ================================================================ 设备点的对应反应(票 43) /** * 把「每台设备的反应档位」写进显示参数(票 43 的反应语言)。 * * 三条纪律都体现在这里: * 1. **不用颜色**:只改 `scale` 与 `color.alpha`(弱化是压暗,不是换色)—— * 色键语义仍只属于设备状态(票 44/07); * 2. **外环**用 billboard 的 `outlineWidth`/`outlineColor`(Cesium 公开属性), * 不用新建实体、不用着色器 —— 关掉时写回 0; * 3. **每个实体都过一遍**:命中与未命中都要写回值,否则上次的强化会一直留在图上 * (与票 14 的 `highlightEntities` 同一条教训)。 * * @param {Viewer} viewer * @param {Array} reactions `domain/deviceCorrespondence.js` 的 `planDeviceReactions().reactions` * @param {(reaction: string) => object} styleOf 档位 → `{ scale, alpha, ring }` * @returns {number} 本次被写入的实体数(0 = 图层为空 / 引擎没就绪) */ export function applyDeviceReactions(viewer, reactions, styleOf) { const source = deviceSources.get(viewer) || (viewer && viewer.dataSources ? viewer.dataSources.getByName(DEVICE_MARKER_SOURCE)[0] : null) if (!source) return 0 const byId = new Map() for (const item of reactions || []) { if (item && item.code) byId.set(`device|${item.pointCode}|${item.code}`, item.reaction) } let written = 0 for (const entity of source.entities.values) { // 图层里没有对应反应的实体(理论上不该有)也按常态写回,避免残留强化。 const reaction = byId.get(entity.id) || 'normal' const style = styleOf(reaction) || { scale: 1, alpha: 1, ring: false } const billboard = entity.billboard if (!billboard) continue billboard.scale = style.scale // 弱化=压暗(降 alpha),**不动色相**:颜色仍表达设备状态。 billboard.color = Color.WHITE.withAlpha(style.alpha) // 选中外环:Cesium billboard 自带的描边,不用新建实体。 billboard.outlineWidth = style.ring ? 3 : 0 billboard.outlineColor = Color.WHITE // 票 47:记下**基准**(动效在此之上做乘性修饰,不覆盖反应量)。 deviceBaseStyle.set(entity.id, { scale: style.scale, alpha: style.alpha }) written += 1 } return written } /** * 票 47:设备状态**动效**驱动器(决策票 07 的三个动效 + 门控 + 降级)。 * * ── 为什么要和票 43 的"反应量"**合成**而不是各写各的 ── * `applyDeviceReactions()` 已经按选中/hover/弱化写 `scale` 与 `alpha`;动效也要动这两个属性。 * 若动效直接赋值,两者会互相抹掉(表现为"选中态闪一下就没了"或"动画把弱化顶回去")。 * 因此这里记住**反应量写下的基准值**(`deviceBaseStyle`),动效只在基准上做**乘性**修饰。 * * ── 为什么不用 `CallbackProperty` ── * `isConstant=false` 的回调会持续请求新帧(票 02 已核),代价被限制在**异常设备**上是对的, * 但更简单且可控的做法是:一个 rAF 循环只写**参与动效的实体**,其余实体一个字节不动。 * 场景本身未开 `requestRenderMode`,所以这个循环不额外改变渲染节奏。 * * ── 载体是场景内 billboard,**不是后处理级** ── * 决策票 07 已裁定:特效走 billboard ⇒「先特效、后雾」自动成立,不占 `PostProcessStageCollection`、 * 与雾无排序冲突,也不新增穿雾例外。 */ const deviceEffectState = { viewer: null, plan: null, selectedCode: '', raf: 0, tick: 0, } /** 反应量写下的**基准** scale/alpha(动效在其上做乘性修饰)。键=实体 id。 */ const deviceBaseStyle = new Map() /** * 票 47(科技感方向):光环实体池。 * * ── 为什么用**独立 billboard 实体**而不是改设备图标本身 ── * 决策票 07 的参考图要的是「多层同心扩散环 + 中心辉光 + 能量描边」; * 设备图标只有一个 billboard,塞不下多层环。所以另建一层光环实体(`fx|` 前缀): * · **不带 `deviceCode`** ⇒ 按研究笔记第 7 条,它不参与设备拾取判定,不会挡住设备点; * · 位置跟设备同坐标,随图层一起重建/销毁(特效挂在图层上); * · 每台最多 `RING_LAYERS` 个环 + 1 个辉光,同处一个数据源(一次 draw call 量级)。 */ const RING_ENTITY_PREFIX = 'fx|' function ringEntitiesOf(source, code) { return source.entities.values.filter((entity) => typeof entity.id === 'string' && entity.id.startsWith(RING_ENTITY_PREFIX) && entity.id.includes(`|${code}|`)) } /** 建/更新某台设备的光环实体(层数固定:缺则建、数量不符则整组重建)。 */ function ensureRingEntities(source, device, color, fxImageOf) { const size = Number.isFinite(device.size) ? device.size : 14 // 层数与"要不要辉光"都问 domain(引擎不认识业务状态名,只认"几层环")。 const wanted = ringEntityCount(device.status) if (!wanted) return [] const existing = ringEntitiesOf(source, device.code) if (existing.length === wanted) return existing for (const entity of existing) source.entities.remove(entity) const created = [] for (let layer = 0; layer < RING_LAYERS; layer += 1) { created.push(source.entities.add({ id: `${RING_ENTITY_PREFIX}${device.pointCode}|${device.code}|ring${layer}`, position: Cartesian3.fromDegrees(device.longitude, device.latitude), billboard: { // 环用**能量场图片**(径向渐变柔和边缘):比 2px 描边圆更像特效, // 放大时边缘自然扩散,不会一放大就细成一根线(首版真机截图抓到的问题)。 image: fxImageOf('ring', color, size), width: size, height: size, scale: 1, color: Color.WHITE.withAlpha(0), heightReference: HeightReference.CLAMP_TO_GROUND, verticalOrigin: VerticalOrigin.CENTER, }, properties: { effectFx: true, effectFxKind: 'ring', effectFxLayer: layer, effectFxFor: device.code, effectFxStatus: device.status, // 刻意**不写 deviceCode / monitoringPointCode**:光环不冒充设备、不吃拾取。 }, })) } if (hasGlow(device.status)) { created.push(source.entities.add({ id: `${RING_ENTITY_PREFIX}${device.pointCode}|${device.code}|glow`, position: Cartesian3.fromDegrees(device.longitude, device.latitude), billboard: { image: fxImageOf('glow', color, size), width: size, height: size, scale: 1, color: Color.WHITE.withAlpha(0), heightReference: HeightReference.CLAMP_TO_GROUND, verticalOrigin: VerticalOrigin.CENTER, }, properties: { effectFx: true, effectFxKind: 'glow', effectFxLayer: -1, effectFxFor: device.code, effectFxStatus: device.status, }, })) } return created } /** 清掉某台(或全部)光环实体。 */ function clearRingEntities(source, code = '') { for (const entity of source.entities.values.slice()) { if (typeof entity.id !== 'string' || !entity.id.startsWith(RING_ENTITY_PREFIX)) continue if (code && !entity.id.includes(`|${code}|`)) continue source.entities.remove(entity) } } function baseStyleOf(entityId) { return deviceBaseStyle.get(entityId) || { scale: 1, alpha: 1 } } function animatedByCode(plan) { const map = new Map() for (const item of (plan && plan.animated) || []) map.set(item.code, item.effect) return map } function writeEffectFrame() { const viewer = deviceEffectState.viewer const source = viewer && (deviceSources.get(viewer) || (viewer.dataSources ? viewer.dataSources.getByName(DEVICE_MARKER_SOURCE)[0] : null)) if (!viewer || !source) return const plan = deviceEffectState.plan const animated = animatedByCode(plan) const now = Date.now() // 选中那台**额外强化**(决策票 07:选中不等于"只有它有特效",而是它更强)。 const amp = 0.34 const ampSelected = 0.55 for (const entity of source.entities.values) { const billboard = entity.billboard if (!billboard) continue const properties = entity.properties || {} const code = properties.deviceCode && properties.deviceCode.getValue ? properties.deviceCode.getValue() : '' const base = baseStyleOf(entity.id) const effect = code ? animated.get(code) : '' if (!effect) { // 不参与动效(正常/离线/未知,或特效关闭/降级):写回**基准**,不留上一帧的残留。 billboard.scale = base.scale billboard.color = Color.WHITE.withAlpha(base.alpha) billboard.rotation = 0 continue } const isSelected = deviceEffectState.selectedCode && code === deviceEffectState.selectedCode const strength = isSelected ? ampSelected : amp if (effect === DEVICE_EFFECT.SPIN) { // 旋转环:只转角度,不呼吸(与脉冲/闪烁区分开)。 billboard.rotation = spinAngleAt(now) billboard.scale = base.scale billboard.color = Color.WHITE.withAlpha(base.alpha) continue } const factor = effect === DEVICE_EFFECT.BLINK ? blinkStrengthAt(now) : pulseStrengthAt(now) billboard.scale = base.scale * (1 + strength * factor) // 脉冲/闪烁同时走**透明度**:只放大不透明度变化时,远看几乎看不出在动。 billboard.color = Color.WHITE.withAlpha(base.alpha * (0.45 + 0.55 * factor)) billboard.rotation = 0 } // ── 科技感光环层(多层同心扩散环 + 中心辉光)── // 光环实体不带 deviceCode,所以**不参与上面的设备图标循环**,也不吃拾取。 const selectedBoost = 1.25 for (const entity of source.entities.values) { const billboard = entity.billboard const properties = entity.properties || {} const isFx = properties.effectFx && properties.effectFx.getValue && properties.effectFx.getValue() === true if (!billboard || !isFx) continue const forCode = properties.effectFxFor && properties.effectFxFor.getValue ? properties.effectFxFor.getValue() : '' const status = properties.effectFxStatus && properties.effectFxStatus.getValue ? properties.effectFxStatus.getValue() : '' const kind = properties.effectFxKind && properties.effectFxKind.getValue ? properties.effectFxKind.getValue() : '' const layer = properties.effectFxLayer && properties.effectFxLayer.getValue ? properties.effectFxLayer.getValue() : 0 const effect = forCode ? animated.get(forCode) : '' if (!effect) { // 无动效(正常/离线/未知、特效关闭或降级):光环**完全透明**,不留残影。 billboard.scale = 1 billboard.color = Color.WHITE.withAlpha(0) continue } const isSelected = deviceEffectState.selectedCode && forCode === deviceEffectState.selectedCode const boost = isSelected ? selectedBoost : 1 if (kind === 'glow') { const strength = glowStrengthAt(now) billboard.scale = glowScaleAt(now) * boost billboard.color = Color.WHITE.withAlpha(0.32 * strength * boost) continue } // 多层环:每层相位错开、由内向外扩张渐隐。 const frame = ringFrameAt(status, now) const ring = frame.rings[layer] || { scale: 1, alpha: 0 } billboard.scale = ring.scale * boost billboard.color = Color.WHITE.withAlpha(Math.min(1, ring.alpha * boost)) } deviceEffectState.tick += 1 } function ensureEffectLoop() { if (typeof window === 'undefined' || typeof window.requestAnimationFrame !== 'function') return if (deviceEffectState.raf) return const step = () => { if (!deviceEffectState.raf) return writeEffectFrame() deviceEffectState.raf = window.requestAnimationFrame(step) } deviceEffectState.raf = window.requestAnimationFrame(step) } /** * 应用动效计划(由服务层在设备图层同步后调用)。 * @param {Viewer} viewer * @param {object} plan `domain/deviceEffects.js` 的 `planDeviceEffects()` 输出 * @param {object} [options] `{ selectedCode }` 选中设备额外强化 * @returns {boolean} 是否启动了动效 */ export function applyDeviceEffects(viewer, plan, options = {}) { deviceEffectState.viewer = viewer || null deviceEffectState.plan = plan || null deviceEffectState.selectedCode = (options && options.selectedCode) || '' const running = Boolean(viewer && plan && plan.enabled === true && !plan.degraded && plan.animated && plan.animated.length) // 光环实体按计划重建:参与的设备建环,其余(含降级/关闭时全部)清掉 —— 降级后动画全停, // 光环也必须一起消失,否则"停了动画却还留着环"会被读成"还在报警"。 const source = viewer && (deviceSources.get(viewer) || (viewer.dataSources ? viewer.dataSources.getByName(DEVICE_MARKER_SOURCE)[0] : null)) if (source) { if (running && options && options.devices) { const animatedCodes = new Set((plan.animated || []).map((item) => item.code)) for (const device of options.devices) { if (!animatedCodes.has(device.code)) { clearRingEntities(source, device.code); continue } ensureRingEntities( source, device, options.colorOf ? options.colorOf(device) : Color.WHITE, options.fxImageOf || (() => ''), ) } // 已不在本批设备里的光环(换点/换状态)也要清。 const known = new Set(options.devices.map((item) => item.code)) for (const entity of source.entities.values.slice()) { const isFx = entity.properties && entity.properties.effectFx && entity.properties.effectFx.getValue && entity.properties.effectFx.getValue() === true if (!isFx) continue const forCode = entity.properties.effectFxFor && entity.properties.effectFxFor.getValue ? entity.properties.effectFxFor.getValue() : '' if (!known.has(forCode) || !animatedCodes.has(forCode)) source.entities.remove(entity) } } else { clearRingEntities(source) } } if (running) ensureEffectLoop() // 即使不跑动效也要写一帧:把上一轮可能残留的放大/透明度**写回基准**。 writeEffectFrame() return running } /** 停止动效并写回基准(图层撤下 / 详情关闭 / 特效被关掉)。 */ export function stopDeviceEffects() { if (typeof window !== 'undefined' && deviceEffectState.raf && typeof window.cancelAnimationFrame === 'function') { window.cancelAnimationFrame(deviceEffectState.raf) } deviceEffectState.raf = 0 deviceEffectState.plan = null deviceEffectState.selectedCode = '' writeEffectFrame() } /** * 只读读回每台设备的**动效状态与当前帧属性**(走查的"真在跑"证据)。 * * 三层证据的第 2 层(场景图跨帧快照):走查对同一设备**隔帧读两次**, * 断言 `scale`/`alpha`(脉冲/闪烁)或 `rotation`(旋转环)确实变了, * 而正常/离线的设备**完全不变**。这样就不是"拿两份 JS 数据互比"的恒真断言。 */ export function readDeviceEffects(viewer) { const source = viewer && (deviceSources.get(viewer) || (viewer.dataSources ? viewer.dataSources.getByName(DEVICE_MARKER_SOURCE)[0] : null)) if (!source) return { tick: deviceEffectState.tick, devices: [] } const animated = animatedByCode(deviceEffectState.plan) const devices = [] for (const entity of source.entities.values) { const billboard = entity.billboard if (!billboard) continue const properties = entity.properties || {} const get = (key) => (properties[key] && properties[key].getValue ? properties[key].getValue() : '') const code = get('deviceCode') if (!code) continue const color = billboard.color && billboard.color.getValue ? billboard.color.getValue() : null devices.push({ code, status: get('deviceStatus'), effect: animated.get(code) || '', animated: animated.has(code), scale: billboard.scale && billboard.scale.getValue ? billboard.scale.getValue() : billboard.scale, alpha: color ? color.alpha : null, rotation: billboard.rotation && billboard.rotation.getValue ? billboard.rotation.getValue() : (billboard.rotation || 0), }) } // 科技感光环的逐层读数(多层同心环 + 辉光):走查据此断言"环真的在扩张渐隐"。 const fx = [] for (const entity of source.entities.values) { const billboard = entity.billboard if (!billboard) continue const properties = entity.properties || {} const get = (key) => (properties[key] && properties[key].getValue ? properties[key].getValue() : '') if (get('effectFx') !== true) continue const color = billboard.color && billboard.color.getValue ? billboard.color.getValue() : null fx.push({ for: get('effectFxFor'), kind: get('effectFxKind'), layer: get('effectFxLayer'), status: get('effectFxStatus'), scale: billboard.scale && billboard.scale.getValue ? billboard.scale.getValue() : billboard.scale, alpha: color ? color.alpha : null, }) } return { tick: deviceEffectState.tick, running: deviceEffectState.raf !== 0, degraded: Boolean(deviceEffectState.plan && deviceEffectState.plan.degraded), enabled: Boolean(deviceEffectState.plan && deviceEffectState.plan.enabled), ringLayers: RING_LAYERS, devices, fx, } } /** * 选中设备的**归属引线**:从设备点连到监测点标记中心(票 04/12 的面板锚点)。 * * 用一条独立 polyline 实体画在同一个数据源上(`lead|...` 前缀,不参与设备拾取判定)。 * 重合时调用方不该调本函数(`planDeviceLead().draw === false`),所以这里只负责画。 */ export function syncDeviceLead(viewer, { deviceLon, deviceLat, pointLon, pointLat, deviceCode, pointCode } = {}) { const source = deviceMarkerSource(viewer) // 先清掉上一条引线(同一时刻最多一条:只画**当前选中**那台的归属)。 for (const entity of source.entities.values.slice()) { if (typeof entity.id === 'string' && entity.id.startsWith('lead|')) source.entities.remove(entity) } if (![deviceLon, deviceLat, pointLon, pointLat].every(Number.isFinite)) return false source.entities.add({ id: `lead|${pointCode}|${deviceCode}`, polyline: { positions: Cartesian3.fromDegreesArray([deviceLon, deviceLat, pointLon, pointLat]), width: 2, // 引线是**归属指示**,不用色键(那是设备状态语义);用中性白并压半透明。 material: Color.WHITE.withAlpha(0.7), // 贴地线会随地形起伏扭动,引线要的是"直连"语义,所以不贴地。 clampToGround: false, }, }) return true } /** 清空选中引线(取消选中 / 返回点位 / 图层撤下)。 */ export function clearDeviceLead(viewer) { const source = deviceSources.get(viewer) || (viewer && viewer.dataSources ? viewer.dataSources.getByName(DEVICE_MARKER_SOURCE)[0] : null) if (!source) return false for (const entity of source.entities.values.slice()) { if (typeof entity.id === 'string' && entity.id.startsWith('lead|')) source.entities.remove(entity) } return true } /** * 屏幕坐标 → 设备标记身份(**hover 用**,与 `pickDeviceMarkerAt` 同一条判据)。 * * 单独一个函数只是为了让 hover 的调用点读起来是"我在做 hover 拾取", * 实现完全复用点选那一个(**不另写一套判据** —— 两套迟早会分歧)。 */ export function pickDeviceMarkerForHover(viewer, windowX, windowY) { return pickDeviceMarkerAt(viewer, windowX, windowY) } /** * 强调一批编码对应的地图实体(票 14:点事件详情时高亮关联设备与关联管线)。 * * 只调**已存在实体**的显示参数,不新增实体 —— 事件因此永远不会变成独立地图图层 * (票 13 的硬纪律)。两处来源都扫: * 1. 点位标记数据源(票 09):按实体属性 `pointCode` / `deviceCodes` 匹配; * 2. 管线数据源(**票 22 才交付**):按 `pipelineCode` / `deviceCode` 匹配。 * 管线层还没落地时这一处自然扫到 0 个,不需要开关,也不会报错 —— * 票 22 落地的管线只要带这两个属性之一,本函数就自动把它一起高亮。 * * **传空数组 = 还原全部**(详情收起时用):初值存在 `emphasisBase` 里,还原是把 * 上次记下的原值写回去,而不是"猜一个默认宽度" —— 否则收起详情后点位标记会一直胖着、 * 管线的线宽也回不到原样。 * * @param {Viewer} viewer * @param {Array} codes 要高亮的编码(点位码 / 设备码 / 管线码);空数组表示还原 * @returns {number} 本次被强调的实体数(0 = 目标还不在图上,调用方据此说人话) */ export function highlightEntities(viewer, codes) { if (!viewer || !viewer.dataSources) return 0 const wanted = new Set((Array.isArray(codes) ? codes : [codes]).map((item) => String(item || '').trim()).filter(Boolean)) let matched = 0 for (const source of [pointMarkerSource(viewer), pipelineSource(viewer)]) { if (!source) continue for (const entity of source.entities.values) { const properties = (entity && entity.properties) || {} const read = (key) => (properties[key] && properties[key].getValue ? properties[key].getValue() : '') const list = read('deviceCodes') const candidates = [ read('pointCode'), read('pipelineCode'), read('deviceCode'), ...(Array.isArray(list) ? list : []), ] // 每个实体都过判定:命中与**未命中**都要写回值,后者即"还原"。 const hit = shouldEmphasize(candidates, wanted) if (hit) matched += 1 const base = hit ? rememberEmphasisBase(entity) : restoreEmphasisBase(entity) if (entity.billboard) entity.billboard.scale = hit ? EMPHASIS_STYLE.markerScale : base.billboardScale if (entity.polyline) entity.polyline.width = hit ? EMPHASIS_STYLE.pipelineWidth : base.polylineWidth } } return matched } /** 强调前的原值(按实体缓存:还原要有据可依,不能猜默认值)。 */ const emphasisBase = new WeakMap() function rememberEmphasisBase(entity) { if (!emphasisBase.has(entity)) { emphasisBase.set(entity, { billboardScale: entity.billboard ? entity.billboard.scale : 1, polylineWidth: entity.polyline ? entity.polyline.width : undefined, }) } return emphasisBase.get(entity) } function restoreEmphasisBase(entity) { const base = emphasisBase.get(entity) emphasisBase.delete(entity) return base || { billboardScale: 1, polylineWidth: undefined } } /** 管线数据源(票 22 交付时才存在;没有就回 null,不当成错误)。 */ export function pipelineSource(viewer) { if (!viewer || !viewer.dataSources) return null return viewer.dataSources.getByName(PIPELINE_SOURCE)[0] || null } /** Currently loaded terrain height; null means no reliable surface sample yet. */ export function groundHeightAt(viewer, lon, lat) { const globe = viewer && viewer.scene && viewer.scene.globe if (!globe || !Number.isFinite(lon) || !Number.isFinite(lat)) return null const height = globe.getHeight(Cartographic.fromDegrees(lon, lat)) return Number.isFinite(height) ? height : null } export function hasPointMarker(viewer, kind, code) { if (!viewer || !code) return false const source = markerSources.get(viewer) || viewer.dataSources.getByName(POINT_MARKER_SOURCE)[0] return !!(source && source.show && source.entities.getById(`point|${kind}|${code}`)) } /** * 把**渲染中的**贴地标记中心投到窗口坐标(票 41 的锚定锚点)。 * * 锚点必须与**眼睛看到的那个标记**一致,所以高度取值顺序照 Cesium 画 billboard 的实际情况: * 1. 地形已有该处瓦片 → `globe.getHeight()` 给的实测高程(贴地后的真实中心); * 2. 瓦片还没加载/无地形 → **椭球面**(Cesium 的 `CLAMP_TO_GROUND` 在无地形数据时正是画在椭球面上)。 * * 第 2 条是**真机走查抓到的缺陷**:早先写成「配了地形就必须取到高度,取不到回 null」, * 于是相机一飞到尚未加载瓦片的区域,`getHeight` 返回 undefined,锚定被误判成"标记离屏"、 * 整块面板消失 —— 而画面上那个标记明明还看得见。锚点判据不能比"可见性"本身更严。 * * 可见性只用 Cesium **公开**判据:相机前方(`directionWC` 点积)+ 地球遮挡(`EllipsoidalOccluder`), * 再交给 `SceneTransforms` 投影;不做第二套相机矩阵手算。 */ export function projectPointMarker(viewer, kind, code) { if (!viewer || !viewer.scene || !viewer.canvas || !code) return null const source = markerSources.get(viewer) || viewer.dataSources.getByName(POINT_MARKER_SOURCE)[0] if (!source || !source.show) return null const entity = source.entities.getById(`point|${kind}|${code}`) if (!entity || !entity.isShowing || !entity.position || !entity.billboard) return null const original = entity.position.getValue(viewer.clock.currentTime) if (!original) return null const ellipsoid = viewer.scene.globe.ellipsoid const carto = ellipsoid.cartesianToCartographic(original) if (!carto) return null let height = 0 const sampled = viewer.scene.globe.getHeight(carto) if (Number.isFinite(sampled)) height = sampled const world = Cartesian3.fromRadians(carto.longitude, carto.latitude, height) const camera = viewer.camera const toward = Cartesian3.subtract(world, camera.positionWC, new Cartesian3()) const occluder = new EllipsoidalOccluder(ellipsoid, camera.positionWC) if (Cartesian3.dot(toward, camera.directionWC) <= 0 || !occluder.isPointVisible(world)) return null const at = SceneTransforms.worldToWindowCoordinates(viewer.scene, world) if (!at || !Number.isFinite(at.x) || !Number.isFinite(at.y)) return null const rect = viewer.canvas.getBoundingClientRect() return { x: at.x + rect.left, y: at.y + rect.top } } /** * 屏幕坐标 → **点位标记身份**(票 10 的地图点选)。 * * 三件事必须说清: * 1. 只认点位标记数据源上的实体 —— 拾到地形、影像、3D Tiles 或空白一律回 `null` * (不是「拾到什么就打开详情」);判据是实体属性里有 `pointCode`; * 2. 坐标要吃**画布坐标**,而事件给的是窗口坐标:`scene.pick` 用的是画布内部坐标系, * 所以先减去画布原点(票 03 的 `projectPivot()` 踩过同一个坑,那里是加、这里是减); * 3. 回的是**标记身份**而不是 Cesium 实体:引擎对象不出这一层,上层只认 kind/code/status * (与 `syncPointMarkers` 只认 shape/tone 是同一条纪律)。 * * @returns {{kind: string, code: string, status: string}|null} */ export function pickPointMarkerAt(viewer, windowX, windowY) { if (!viewer || !viewer.scene || !viewer.canvas || typeof viewer.scene.pick !== 'function') return null const rect = viewer.canvas.getBoundingClientRect() const picked = viewer.scene.pick(new Cartesian2(windowX - rect.left, windowY - rect.top)) const entity = picked && picked.id const properties = entity && entity.properties if (!properties || !properties.pointCode) return null const read = (key) => (properties[key] ? properties[key].getValue() : '') const code = read('pointCode') if (!code) return null return { kind: read('pointKind'), code, status: read('pointStatus') } } /** * 相机契约的 Cesium 适配(票 03)。返回 services/cameraControl.js 期望的引擎接口; * 相机语义(三键怎么算、中心是谁)在 domain/camera.js 与 cameraControl.js,本函数只翻译方言。 * @param {Viewer} viewer */ export function createCameraEngine(viewer) { const scene = viewer.scene const camera = viewer.camera let frameHandle = null /** * 经纬高 → 该点东北天局部系(弹簧臂原语要求中心是局部地表点)。 * * 极点保护:`eastNorthUpToFixedFrame` 内部用 `east = up × north` 求东向, * 纬度到 ±90 时 up 与 north 共线、叉积退化为零向量,局部系不再是正交基, * `lookAtTransform` 拿它当参照就会出现「整个地球乱转」。 * 域层已把中心纬度夹在 ±POLAR_LAT_LIMIT 内(见 domain/camera.js), * 这里是引擎侧的第二道防线:任何调用方直接喂端点纬度也不会把参照系搞坏。 */ function frameAt(pivot) { const lat = Math.min(89.9, Math.max(-89.9, pivot.lat)) return Transforms.eastNorthUpToFixedFrame(Cartesian3.fromDegrees(pivot.lon, lat, pivot.height || 0)) } return { applyView(pivot, hpr) { camera.lookAtTransform( frameAt(pivot), new HeadingPitchRange(hpr.heading * DEG, hpr.pitch * DEG, hpr.range), ) }, /** 反读当前相机相对该中心的弹簧臂参数,用于挂载时对齐真实相机(避免首次交互跳变)。 */ readView(pivot) { const inverse = Matrix4.inverseTransformation(frameAt(pivot), new Matrix4()) const local = Matrix4.multiplyByPoint(inverse, camera.positionWC, new Cartesian3()) const range = Cartesian3.magnitude(local) if (!(range > 0)) return { heading: 0, pitch: -60, range: 1 } const heading = CesiumMath.toDegrees(Math.atan2(local.x, local.y)) const pitch = -CesiumMath.toDegrees(Math.asin(Math.min(1, Math.max(-1, local.z / range)))) return { heading: (heading + 360) % 360, pitch, range } }, /** * 屏幕中心的地面拾取点(票 21/30 改进):**优先按地形拾取**,拿不到高度再退回椭球。 * * 为什么必须按地形:纯 `pickEllipsoid` 给的是椭球面交点(高程 0),而沅陵县城地面高程 * 两百多米起。用它当中心,弹簧臂 range 一降到几百米,相机就落进山体内部 —— 实测 range 120 m * 时整屏全黑(票 21 走查记录)。地形就绪后用 `globe.getHeight` 把中心抬到真实地表, * 相机高度随之正确,近景才不会钻进山里。 */ pickGroundAtCenter() { const canvas = scene.canvas const at = new Cartesian2(canvas.clientWidth / 2, canvas.clientHeight / 2) const ellipsoid = (scene.globe && scene.globe.ellipsoid) || Ellipsoid.WGS84 const hit = camera.pickEllipsoid(at, ellipsoid) if (!hit) return null const carto = ellipsoid.cartesianToCartographic(hit) const lon = CesiumMath.toDegrees(carto.longitude) const lat = CesiumMath.toDegrees(carto.latitude) // 地形就绪时把中心抬到真实地表;取样不到就保持 0(等价于旧行为,不会更糟)。 let height = 0 const globe = scene.globe if (globe && typeof globe.getHeight === 'function') { const sampled = globe.getHeight(carto) if (Number.isFinite(sampled)) height = sampled } return { lon, lat, height } }, /** * 中心点投影到**窗口坐标**(与 `getBoundingClientRect()` 同一坐标系)。 * * 实测 `SceneTransforms.worldToWindowCoordinates()` 返回的是**相对画布左上角**的值 * (画布在壳里下移了一段,直接用会与 `getBoundingClientRect()` 差出一个画布原点偏移, * 走查里表现为「中心点没落在画布中心」的假失败)。这里显式加上画布原点, * 让消费方拿到的就是窗口坐标,别再靠语义猜。 */ projectPivot(pivot) { const at = SceneTransforms.worldToWindowCoordinates(scene, Cartesian3.fromDegrees(pivot.lon, pivot.lat, pivot.height || 0)) if (!at) return null const rect = viewer.canvas.getBoundingClientRect() return { x: at.x + rect.left, y: at.y + rect.top } }, /** * **相机正下方**的地形高度(米),取不到返回 null(票 37 的防入地输入)。 * * 为什么是「相机正下方」而不是「pivot 下方」:防入地要保证的是**相机自己**别钻进山体。 * 相机在 pivot 沿 heading/pitch 退开 range 的位置上,两者可能隔着几百米、翻过一个山脊, * 用 pivot 的地形判断会在斜坡上误判。 */ groundHeightBelowCamera() { const globe = scene.globe if (!globe || typeof globe.getHeight !== 'function') return null try { const carto = globe.ellipsoid.cartesianToCartographic(camera.positionWC) if (!carto) return null const sampled = globe.getHeight(carto) return Number.isFinite(sampled) ? sampled : null } catch (error) { return null } }, /** 相机当前**绝对**高度(米,椭球高),取不到返回 null。防入地的另一半输入。 */ cameraHeight() { try { const carto = scene.globe.ellipsoid.cartesianToCartographic(camera.positionWC) return carto && Number.isFinite(carto.height) ? carto.height : null } catch (error) { return null } }, inputTarget() { return viewer.canvas }, viewport() { return { width: scene.canvas.clientWidth, height: scene.canvas.clientHeight } }, fovY() { return camera.frustum.fovy || 60 * DEG }, now() { return typeof performance !== 'undefined' ? performance.now() : Date.now() }, requestFrame(callback) { frameHandle = requestAnimationFrame(callback) }, } }