cesiumPipeModels.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. /** Cesium-only adapter: terrain - virtual depth, ENU tiles, glTF GPU instance streams. */
  2. import { Cartesian3, Cartographic, DistanceDisplayCondition, Matrix4, Model, Quaternion, Transforms, sampleTerrainMostDetailed } from 'cesium'
  3. import { planPipeModels, PIPE_MODEL_NOTE } from '../domain/pipeModels.js'
  4. import { createPipeModelBatches } from './pipeModelBatches.js'
  5. import { enuToGltf, instanceGltf } from './pipeInstanceGltf.js'
  6. import { PIPE_DISPLAY } from '../domain/pipeVisual.js'
  7. import { createPipeModelShader } from './pipeModelShader.js'
  8. const templates = new Map()
  9. const DEG = Math.PI / 180
  10. const TILE_DEG = 0.01
  11. const FAR_GUIDE = new DistanceDisplayCondition(PIPE_DISPLAY.guideFromM, Number.MAX_VALUE)
  12. const ALL_DISTANCES = new DistanceDisplayCondition(0, Number.MAX_VALUE)
  13. const gltfCoordinates = (point) => enuToGltf([point.x, point.y, point.z])
  14. async function templateOf(kind, base) {
  15. const url = `${base}cockpit/models/pipes/${kind}.gltf`
  16. if (!templates.has(url)) {
  17. const promise = fetch(url).then(async (response) => {
  18. if (!response.ok) throw new Error(`管件素材 ${response.status}`)
  19. const gltf = await response.json()
  20. if (gltf.asset?.version !== '2.0' || gltf.nodes?.length !== 1 || !gltf.meshes?.length) throw new Error('Invalid pipe template')
  21. for (const buffer of gltf.buffers || []) {
  22. const resource = new URL(buffer.uri, new URL(url, window.location.href))
  23. if (resource.origin !== window.location.origin) throw new Error('Pipe buffer must be same-origin')
  24. buffer.uri = resource.href
  25. }
  26. return gltf
  27. }).catch((error) => { templates.delete(url); throw error })
  28. templates.set(url, promise)
  29. }
  30. return templates.get(url)
  31. }
  32. function rotationFromZ(direction) {
  33. const length = Cartesian3.magnitude(direction)
  34. const unit = Cartesian3.divideByScalar(direction, length, new Cartesian3())
  35. const dot = Math.max(-1, Math.min(1, unit.z))
  36. if (dot > 0.99999999) return [0,0,0,1]
  37. const axis = dot < -0.99999999 ? Cartesian3.UNIT_X : Cartesian3.normalize(Cartesian3.cross(Cartesian3.UNIT_Z, unit, new Cartesian3()), new Cartesian3())
  38. const q = Quaternion.fromAxisAngle(axis, Math.acos(dot), new Quaternion())
  39. return [q.x,q.y,q.z,q.w]
  40. }
  41. /** Geographic subspans lie ON the original path; not smoothing and not connection inference. */
  42. function terrainSpans(instance) {
  43. if (instance.kind !== 'spline') return [instance]
  44. const a=instance.start,b=instance.end
  45. const approximateM=Math.hypot((b[0]-a[0])*Math.cos(a[1]*DEG),(b[1]-a[1]))*111320
  46. const count=Math.max(1,Math.ceil(approximateM/20))
  47. const point=(t)=>[a[0]+(b[0]-a[0])*t,a[1]+(b[1]-a[1])*t]
  48. return Array.from({length:count},(_,i)=>({...instance,start:point(i/count),end:point((i+1)/count)}))
  49. }
  50. async function groupsFor(viewer, plan, heights, alive) {
  51. const rows=plan.instances.flatMap(terrainSpans)
  52. const needed=new Map()
  53. const keyOf=(p)=>`${p[0]},${p[1]}`
  54. for(const row of rows) for(const point of row.kind==='spline'?[row.start,row.end]:[row.position]) {
  55. const key=keyOf(point)
  56. if(!heights.has(key)) needed.set(key,point)
  57. }
  58. const entries=[...needed]
  59. const chunks=[]
  60. for(let i=0;i<entries.length;i+=512) chunks.push(entries.slice(i,i+512))
  61. // 有限并发(最多 3 批在飞)。批大小仍是 512 点 —— 单批请求规模不变,只是把批与批之间
  62. // 从"串行等待"改成"最多 3 批并行",所以峰值由 Cesium 的 RequestScheduler 兜底、不会翻倍。
  63. //
  64. // 为什么需要:票 60 之后地面视图不再预先采样地形(那本是被否掉的浪费),于是这一轮采样
  65. // 落在**切到管线视图的关键路径**上 —— 串行等待表现为"切过去要等很久才出现模型"。
  66. // 落地顺序与结果都没变(heights 只是缓存,谁先写谁后写不影响取值),只是等待时间变短。
  67. const TERRAIN_CHUNK_CONCURRENCY=3
  68. let cursor=0
  69. const sampleChunk=async()=>{
  70. while(alive()) {
  71. const index=cursor
  72. cursor+=1
  73. if(index>=chunks.length) return
  74. const chunk=chunks[index]
  75. try {
  76. const values=await sampleTerrainMostDetailed(viewer.terrainProvider,chunk.map(([,p])=>Cartographic.fromDegrees(p[0],p[1])))
  77. if(!alive()) return
  78. for(let j=0;j<chunk.length;j+=1) if(Number.isFinite(values[j]?.height)) heights.set(chunk[j][0],values[j].height)
  79. } catch { /* No invented ground elevation: retain fallback. */ }
  80. }
  81. }
  82. await Promise.all(Array.from({length:Math.min(TERRAIN_CHUNK_CONCURRENCY,chunks.length)},sampleChunk))
  83. if(!alive()) return []
  84. const world=(p,depthM=2)=>{
  85. const height=heights.get(keyOf(p))
  86. return Number.isFinite(height)?Cartesian3.fromDegrees(p[0],p[1],height-depthM):null
  87. }
  88. const groups=new Map(), missing=new Set()
  89. for(const row of rows) {
  90. const p=row.start||row.position
  91. const tileX=Math.floor(p[0]/TILE_DEG),tileY=Math.floor(p[1]/TILE_DEG)
  92. const key=`${tileX}:${tileY}:${row.kind}:${row.colorKey||'UNKNOWN'}:${row.surface?.kind || 'unknown'}`
  93. const origin=[(tileX+.5)*TILE_DEG,(tileY+.5)*TILE_DEG]
  94. const matrix=Transforms.eastNorthUpToFixedFrame(Cartesian3.fromDegrees(...origin))
  95. const inverse=Matrix4.inverseTransformation(matrix,new Matrix4())
  96. const a=world(p,row.virtualDepthM),b=row.end?world(row.end,row.virtualDepthM):null
  97. if(!a||(row.end&&!b)){missing.add(row.id);continue}
  98. const local=Matrix4.multiplyByPoint(inverse,a,new Cartesian3())
  99. let translation=gltfCoordinates(local),rotation=[0,0,0,1],scale=[row.sizeM,row.sizeM,row.sizeM]
  100. if(row.kind==='spline') {
  101. const end=Matrix4.multiplyByPoint(inverse,b,new Cartesian3()),delta=Cartesian3.subtract(end,local,new Cartesian3())
  102. const length=Cartesian3.magnitude(delta)
  103. if(length<0.001){missing.add(row.id);continue}
  104. rotation=rotationFromZ(new Cartesian3(...gltfCoordinates(delta)))
  105. scale=[row.displayDiameterM,row.displayDiameterM,length]
  106. }
  107. if(!groups.has(key)) groups.set(key,{key,kind:row.kind,industry:row.industry,colorKey:row.colorKey||'UNKNOWN',surface:row.surface,origin,instances:[]})
  108. groups.get(key).instances.push({id:row.id,translation,rotation,scale})
  109. }
  110. // One missing span keeps its entire business pipe's fallback visible.
  111. return { groups:[...groups.values()], missing }
  112. }
  113. export function createCesiumPipeModels(viewer, { source, onChange=()=>{}, base=import.meta.env?.BASE_URL||'/', viewMode='ground', componentOverlayActive=()=>false }={}) {
  114. const heights=new Map()
  115. const guideStates=new WeakMap()
  116. let active=true,generation=0,fingerprint='',missing=new Set(),allIds=[],task=null,planning=false
  117. let lastGroups=[], signatures=new Map(), terrainFailed=false, lastTerrainAttempt=0
  118. let diameterSummary={reported:0,interpolated:0,missing:0}, visualDefaultCount=0
  119. let pipelineView=viewMode==='pipeline'
  120. // 最近一次拿到的管网数据。地面视图虽然不建模型,但必须**记住数据**:
  121. // 计划同步(`syncPipeLayerForPlan`)只由计划数组变化触发,切视图模式不会叫它,
  122. // 所以切回管线时只有这里能立刻重建(详见 setViewMode 的说明)。
  123. let lastNetwork=null
  124. const publish=(state)=>{
  125. if(!active) return
  126. const covered=new Set(state.covered.filter((id)=>!missing.has(id)))
  127. for(const entity of source.entities.values) {
  128. const modeled=covered.has(entity.id)
  129. if(entity.polyline) {
  130. if(entity.show!==true) entity.show=true
  131. const distantOnly=pipelineView&&modeled
  132. if(guideStates.get(entity.polyline)!==distantOnly) {
  133. entity.polyline.distanceDisplayCondition=distantOnly?FAR_GUIDE:ALL_DISTANCES
  134. guideStates.set(entity.polyline,distantOnly)
  135. }
  136. } else {
  137. // 票 101:地面视图的构件点位交给 DOM overlay 标记(icon+标签,与设备/设施同一套视觉),
  138. // Cesium 兜底点隐藏,避免同一构件出现两套视觉;管线视图保留原语义——
  139. // 未建模(无 3D 模型)的构件仍用 Cesium 点兜底,不让构件在地下视图里消失。
  140. const show = pipelineView ? !modeled : !componentOverlayActive()
  141. if(entity.show!==show) entity.show=show
  142. }
  143. }
  144. onChange({...state,covered:[...covered],fallback:allIds.length-covered.size,planning,terrainFailed,diameterSummary,visualDefaultCount,viewMode:pipelineView?'pipeline':'ground',note:PIPE_MODEL_NOTE})
  145. viewer.scene.requestRender()
  146. }
  147. const batches=createPipeModelBatches({
  148. load:async(group,events)=>{
  149. const template=await templateOf(group.kind,base)
  150. if (!active || !events.alive() || viewer.isDestroyed()) throw new Error('Cancelled pipe batch')
  151. const gltf=instanceGltf(template,group.instances)
  152. // Use a public URL/Resource entry, not Cesium's private options.gltf JSON hook.
  153. const url=URL.createObjectURL(new Blob([JSON.stringify(gltf)],{type:'model/gltf+json'}))
  154. const shader=createPipeModelShader(group.colorKey, group.surface)
  155. let model
  156. try {
  157. model=await Model.fromGltfAsync({url,modelMatrix:Transforms.eastNorthUpToFixedFrame(Cartesian3.fromDegrees(...group.origin)),
  158. id:{kind:'pipe-model-batch',key:group.key,instances:group.instances.map((row)=>row.id)},incrementallyLoadTextures:false,
  159. customShader:shader})
  160. const release=()=>{ URL.revokeObjectURL(url) }
  161. model.readyEvent.addEventListener(()=>{release();events.ready()})
  162. model.errorEvent.addEventListener(()=>{release();events.error()})
  163. if(!active || !events.alive() || viewer.isDestroyed()){model.destroy();throw new Error('Disposed pipe batch')}
  164. viewer.scene.primitives.add(model)
  165. viewer.scene.requestRender()
  166. return {model,url,shader}
  167. } catch(error){URL.revokeObjectURL(url);shader.destroy();throw error}
  168. },
  169. remove:({model,url,shader})=>{
  170. URL.revokeObjectURL(url)
  171. if(!viewer.isDestroyed()&&!model.isDestroyed()) viewer.scene.primitives.remove(model)
  172. else if(!model.isDestroyed()) model.destroy()
  173. if(!shader.isDestroyed()) shader.destroy()
  174. },
  175. onChange:publish,
  176. })
  177. function sync(network) {
  178. if (!active || viewer.isDestroyed()) return Promise.resolve()
  179. lastNetwork = network
  180. // 维护者要求(第 352 轮):**地面视图不建任何管线 3D 模型**,只保留地图上的走向线。
  181. // 原实现即使 `ground` 也照样采样地形、拼 GLTF、上传 GPU 模型 —— 那是纯浪费:
  182. // 地面视图下这些模型本来就被 `show=false` 隐藏,等于白花 CPU/GPU/内存。
  183. // 这里显式清空批次并释放 GPU 资源,等切到管线视图再重建。
  184. if (!pipelineView) {
  185. lastGroups = []
  186. signatures = new Map()
  187. fingerprint = ''
  188. planning = false
  189. const cleared = batches.clear()
  190. // 票 101:地面视图也要 publish 一次 —— 构件点的 Cesium 兜底点必须在这里被隐藏
  191. //(DOM overlay 标记接管),否则首次同步后地面视图会出现「DOM 标记 + Cesium 点」双视觉。
  192. publish(batches.state())
  193. return cleared
  194. }
  195. const plan=planPipeModels(network)
  196. diameterSummary=plan.diameterSummary
  197. visualDefaultCount=plan.visualDefaultCount
  198. const next=JSON.stringify(plan)
  199. if(next===fingerprint && !(terrainFailed && Date.now()-lastTerrainAttempt>=30000)) {
  200. if (planning) return task
  201. task=batches.sync(lastGroups)
  202. publish(batches.state())
  203. return task
  204. }
  205. fingerprint=next
  206. const token=++generation
  207. const previousSignatures=signatures
  208. const byId=new Map()
  209. for(const row of plan.instances) {
  210. if(!byId.has(row.id)) byId.set(row.id,[])
  211. byId.get(row.id).push(row)
  212. }
  213. signatures=new Map([...byId].map(([id,rows])=>[id,JSON.stringify(rows)]))
  214. allIds=[...(network.pipes||[]).map((p)=>`pipe:${p.code}`),...(network.components||[]).map((c)=>`component:${c.code}`)]
  215. planning=true
  216. // Remove only changed/removed batches before awaits. Keep stable geometry visible.
  217. batches.retain((group)=>group.instances.every((row)=>signatures.has(row.id)&&signatures.get(row.id)===previousSignatures.get(row.id)))
  218. task=(async()=>{
  219. const alive=()=>active&&token===generation&&!viewer.isDestroyed()
  220. lastTerrainAttempt=Date.now()
  221. const result=await groupsFor(viewer,plan,heights,alive)
  222. if(!alive()) return
  223. missing=result.missing
  224. terrainFailed=missing.size>0
  225. for(const row of plan.fallbacks) missing.add(row.id)
  226. lastGroups=result.groups
  227. planning=false
  228. await batches.sync(lastGroups)
  229. if(alive()) publish(batches.state())
  230. })().catch(()=>{if(active&&token===generation){terrainFailed=true;planning=false;publish(batches.state())}})
  231. return task
  232. }
  233. function destroy() {
  234. active=false;generation+=1
  235. batches.clear()
  236. heights.clear()
  237. }
  238. function setViewMode(mode) {
  239. const next = mode==='pipeline'
  240. if (next === pipelineView) return
  241. pipelineView = next
  242. if (!pipelineView) {
  243. // 切回地面视图:立刻释放 GPU 模型(下一帧还会被 sync 的短路再确认一次)。
  244. lastGroups = []
  245. signatures = new Map()
  246. fingerprint = ''
  247. planning = false
  248. batches.clear()
  249. }
  250. publish(batches.state())
  251. // 切回管线视图必须**自己重建**,不能等下一次计划同步。
  252. // 缺陷复盘(维护者 2026-10-27 现场反馈):地面期已把批次清空,而计划同步只由
  253. // MapCanvas 的 watch(依赖 markers/byStatus/pipelines/facilities,**不看 viewMode**)
  254. // 触发 —— 切视图模式根本叫不动它。旧实现里地面视图"顺手"把模型建好了,
  255. // 所以切过去立刻能看见;票 60 把地面建模去掉后这条顺带路径消失,现象变成:
  256. // 切到管线视图仍只显示地面视图的 2D 走向线,3D 模型要等下一次翻页/30s tick
  257. // 才可能出现,甚至一直不出现。
  258. if (pipelineView && lastNetwork) void sync(lastNetwork)
  259. }
  260. return {sync,setViewMode,destroy,state:batches.state}
  261. }