s3m-three 0.3.11 → 0.3.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -49,6 +49,19 @@ function styledMaterialOf(mesh) {
49
49
  function isPointCloudObject(o) {
50
50
  return o.isPoints === true;
51
51
  }
52
+ /**
53
+ * 全局透明度钳到 [0, 1],**允许到 0**。
54
+ *
55
+ * 以前这里有个 0.05 下限,本意是「别让整层彻底看不见、又还在挡东西」。但那个问题
56
+ * 真正的来源不是透明度,而是「透明物体仍然写深度」:全透明还写深度就会在底图上挖洞。
57
+ * 现在到 0 时 `renderFrame()` 直接跳过绘制(不写颜色也不写深度),语义就干净了。
58
+ */
59
+ function clampOpacity(v) {
60
+ const n = v ?? 1;
61
+ return n < 0 ? 0 : n > 1 ? 1 : n;
62
+ }
63
+ /** 低于这个透明度就当作完全不可见:跳过绘制,避免全透明物体写深度 */
64
+ const OPACITY_EPS = 1e-3;
52
65
  /* ------------------------------------------------------------------ 可动画的样式键 */
53
66
  /**
54
67
  * 能逐帧插值的标量样式键。
@@ -147,10 +160,18 @@ export class S3MViewer {
147
160
  _tileFadeSeq = 0;
148
161
  /** setMode 编排的代次,用来作废被新调用顶掉的旧编排 */
149
162
  _modeGen = 0;
163
+ /** `shading` 另一种变体是否已预热(每个 viewer 只做一次) */
164
+ _shadingPrewarmed = false;
165
+ /** 是否允许自动预热(选项 `prewarmShading`,默认开) */
166
+ _prewarmShadingEnabled = true;
167
+ /** 预热进行中:期间跳过渲染,避免把「翻转后的变体」画到屏幕上 */
168
+ _prewarming = false;
150
169
  /** 路径运动的规格表:通道 key → 路径 + 偏移 */
151
170
  _pathSpecs = new Map();
152
171
  /** 路径采样临时对象,避免每帧 new */
153
172
  _pathScratch = new Float32Array(3);
173
+ /** 求切线用的第二个采样点(包围盒换算 GPU 路径朝向时用) */
174
+ _pathScratch2 = new Float32Array(3);
154
175
  /** 预制棱线缓存(Crease Cache):从外部 source-creases 载入的全局统一 LineSegments,性能最高、视觉最干净 */
155
176
  _creaseLines = null;
156
177
  /** 数据自带的棱线对象(LineSegments),改棱线颜色时只刷这些,不再全场景 traverse */
@@ -220,6 +241,7 @@ export class S3MViewer {
220
241
  this.onReady = options.onReady ?? (() => { });
221
242
  this.onPick = options.onPick ?? (() => { });
222
243
  this.onError = options.onError ?? ((e) => console.warn('[s3m]', e));
244
+ this._prewarmShadingEnabled = options.prewarmShading !== false;
223
245
  this.groundManager = new GroundManager(options.ground);
224
246
  if (!this.scene) {
225
247
  this.scene = new THREE.Scene();
@@ -331,7 +353,7 @@ export class S3MViewer {
331
353
  }
332
354
  try {
333
355
  // 旧上下文已失效,dispose 可能抛错,忽略即可
334
- this.renderer?.dispose();
356
+ this.renderer?.dispose?.();
335
357
  }
336
358
  catch {
337
359
  /* noop */
@@ -371,7 +393,7 @@ export class S3MViewer {
371
393
  this._pathSpecs.clear();
372
394
  this._heightMin = Infinity;
373
395
  this._heightMax = -Infinity;
374
- this.renderer?.dispose();
396
+ this.renderer?.dispose?.();
375
397
  this.renderer = null;
376
398
  this.canvas = null;
377
399
  }
@@ -776,6 +798,54 @@ export class S3MViewer {
776
798
  this.animator.unregister(key);
777
799
  this._pathSpecs.delete(key);
778
800
  }
801
+ /**
802
+ * 换算 GPU 路径单体在**当前时间**的位置与朝向。
803
+ *
804
+ * 位移发生在顶点着色器里,JS 侧要拿到「屏幕上现在在哪」只能按同一套公式在 CPU 复算:
805
+ * `t = phase + uPathTime * speed`,再按 loop 模式夹到 0~1,最后查弧长表。
806
+ * 与 StyleMaterial 的 row5 分支逐行对应,改那边时这里必须同步。
807
+ */
808
+ _gpuPathPoseAt(smid) {
809
+ const gp = this._featureStyleManager.getFeatureStyle(smid)?.gpuPath;
810
+ if (!gp)
811
+ return null;
812
+ const path = this.gpuPathManager.getPath(gp.pathId);
813
+ if (!path || path.length <= 0)
814
+ return null;
815
+ const time = this.uniforms.uPathTime?.value ?? 0;
816
+ let t = (gp.phase ?? 0) + time * (gp.speed ?? 0);
817
+ const loop = gp.loop;
818
+ if (loop === 'clamp' || loop === false) {
819
+ t = Math.min(1, Math.max(0, t));
820
+ }
821
+ else if (loop === 'pingpong') {
822
+ t = t % 2;
823
+ if (t < 0)
824
+ t += 2;
825
+ t = t > 1 ? 2 - t : t;
826
+ }
827
+ else {
828
+ t = t - Math.floor(t);
829
+ }
830
+ path.sampleAt(t, this._pathScratch);
831
+ const pos = [this._pathScratch[0], this._pathScratch[1], this._pathScratch[2]];
832
+ let yaw = 0;
833
+ if (gp.autoHeading !== false) {
834
+ const d = 1e-3;
835
+ path.sampleAt(Math.min(1, t + d), this._pathScratch2);
836
+ let dx = this._pathScratch2[0] - pos[0];
837
+ let dy = this._pathScratch2[1] - pos[1];
838
+ if (dx * dx + dy * dy < 1e-8) {
839
+ // 已经在终点:退回用「后一点减前一点」求切线
840
+ path.sampleAt(Math.max(0, t - d), this._pathScratch2);
841
+ dx = pos[0] - this._pathScratch2[0];
842
+ dy = pos[1] - this._pathScratch2[1];
843
+ }
844
+ if (dx * dx + dy * dy >= 1e-8)
845
+ yaw = Math.atan2(dy, dx);
846
+ }
847
+ return { pos, yaw };
848
+ }
779
849
  /**
780
850
  * 注册 GPU 路径到路径库
781
851
  * @param points 折线点数组或 Path 实例
@@ -1264,7 +1334,7 @@ export class S3MViewer {
1264
1334
  else {
1265
1335
  const mat = styledMaterialOf(mesh);
1266
1336
  if (mat) {
1267
- const o = Math.min(1, Math.max(0.05, this.style.opacity ?? 1));
1337
+ const o = clampOpacity(this.style.opacity);
1268
1338
  // 不写 mat.opacity:全局透明度走共享 uOpacity,材质自身 opacity 保留模型自带 alpha
1269
1339
  mat.transparent = o < 0.999;
1270
1340
  const keepDepth = this.style.depthWrite !== false;
@@ -1692,7 +1762,7 @@ export class S3MViewer {
1692
1762
  u.uAmbientGain.value = s.ambientGain;
1693
1763
  }
1694
1764
  if (u.uOpacity && s.opacity != null) {
1695
- u.uOpacity.value = Math.min(1, Math.max(0.05, s.opacity));
1765
+ u.uOpacity.value = clampOpacity(s.opacity);
1696
1766
  }
1697
1767
  if (this.outlineMaterial) {
1698
1768
  if (this.outlineMaterial.uniforms.uElevation && s.selectElevation != null) {
@@ -1718,7 +1788,7 @@ export class S3MViewer {
1718
1788
  * 现在逐帧只写一个 float(`uOpacity`),混合开关只在**真正跨过阈值**时切一次。
1719
1789
  */
1720
1790
  _applyOpacity() {
1721
- const o = Math.min(1, Math.max(0.05, this.style.opacity ?? 1));
1791
+ const o = clampOpacity(this.style.opacity);
1722
1792
  if (this.uniforms.uOpacity)
1723
1793
  this.uniforms.uOpacity.value = o;
1724
1794
  const transparent = o < 0.999;
@@ -1769,6 +1839,62 @@ export class S3MViewer {
1769
1839
  }
1770
1840
  this._requestRepaint();
1771
1841
  }
1842
+ /**
1843
+ * 预热另一种 `shading` 变体,让首次切换不再同步编译着色器。
1844
+ *
1845
+ * 做法是「把材质翻到另一种变体 → 编译 → 翻回来」:three 的 program 缓存按
1846
+ * cacheKey(含 flatShading / defines)分桶,编译一次就留在缓存里,之后
1847
+ * `_applyShading()` 切过去只是取缓存。
1848
+ *
1849
+ * 翻转期间材质是「错误变体」,所以用 `_prewarming` 让 renderFrame 跳过渲染——
1850
+ * 少画一两帧看不出来,把平滑的楼画成平面的就很明显。
1851
+ * 优先用 `compileAsync`(KHR_parallel_shader_compile),没有就退回同步 `compile`。
1852
+ */
1853
+ async prewarmShading() {
1854
+ if (this._shadingPrewarmed || this._prewarming)
1855
+ return;
1856
+ const r = this.renderer;
1857
+ const scene = this.scene;
1858
+ const camera = this.camera;
1859
+ if (!r || !scene || !camera)
1860
+ return;
1861
+ const mats = [];
1862
+ const seen = new Set();
1863
+ for (const p of this._pickables.values()) {
1864
+ const m = styledMaterialOf(p.mesh);
1865
+ if (!m || seen.has(m))
1866
+ continue;
1867
+ seen.add(m);
1868
+ mats.push(m);
1869
+ }
1870
+ if (mats.length === 0)
1871
+ return;
1872
+ this._shadingPrewarmed = true;
1873
+ this._prewarming = true;
1874
+ // 当前是 smooth(flatShading = false)就预热 flat,反之预热 smooth
1875
+ const target = this.style.shading === 'smooth';
1876
+ const saved = mats.map((m) => m.flatShading);
1877
+ for (const m of mats)
1878
+ m.flatShading = target;
1879
+ try {
1880
+ const anyR = r;
1881
+ if (typeof anyR.compileAsync === 'function')
1882
+ await anyR.compileAsync(scene, camera);
1883
+ else
1884
+ r.compile(scene, camera);
1885
+ }
1886
+ catch {
1887
+ // 预热失败不影响主流程:最坏情况退回「首次切换时编译一次」
1888
+ }
1889
+ finally {
1890
+ for (let i = 0; i < mats.length; i++) {
1891
+ mats[i].flatShading = saved[i];
1892
+ mats[i].needsUpdate = true;
1893
+ }
1894
+ this._prewarming = false;
1895
+ this._requestRepaint();
1896
+ }
1897
+ }
1772
1898
  /**
1773
1899
  * 高度范围增量维护。
1774
1900
  *
@@ -1976,7 +2102,7 @@ export class S3MViewer {
1976
2102
  const mat = new THREE.LineBasicMaterial({
1977
2103
  color: new THREE.Color(s.edgeColor),
1978
2104
  transparent: true,
1979
- opacity: Math.min(1, Math.max(0, s.edgeOpacity ?? 0.6)) * Math.min(1, Math.max(0.05, s.opacity ?? 1)),
2105
+ opacity: Math.min(1, Math.max(0, s.edgeOpacity ?? 0.6)) * clampOpacity(s.opacity),
1980
2106
  depthWrite: false,
1981
2107
  });
1982
2108
  const lines = new THREE.LineSegments(geo, mat);
@@ -2008,7 +2134,7 @@ export class S3MViewer {
2008
2134
  const s = this.style;
2009
2135
  const fade = this.uniforms.uEdgeFade?.value ?? 1;
2010
2136
  const opacity = Math.min(1, Math.max(0, s.edgeOpacity ?? 0.6)) *
2011
- Math.min(1, Math.max(0.05, s.opacity ?? 1)) *
2137
+ clampOpacity(s.opacity) *
2012
2138
  fade;
2013
2139
  const u = this.edgeMaterial.uniforms;
2014
2140
  u.uColor.value.set(s.edgeColor);
@@ -2030,7 +2156,7 @@ export class S3MViewer {
2030
2156
  const baseOpacity = this.style.edgeOpacity ?? 0.6;
2031
2157
  mat.opacity =
2032
2158
  baseOpacity *
2033
- Math.min(1, Math.max(0.05, this.style.opacity ?? 1)) *
2159
+ clampOpacity(this.style.opacity) *
2034
2160
  (this.uniforms.uEdgeFade?.value ?? 1);
2035
2161
  mat.transparent = true;
2036
2162
  mat.polygonOffset = true;
@@ -2565,13 +2691,30 @@ export class S3MViewer {
2565
2691
  rotM3 = new THREE.Matrix3().set(rotMat[0], rotMat[1], rotMat[2], rotMat[3], rotMat[4], rotMat[5], rotMat[6], rotMat[7], rotMat[8]);
2566
2692
  rotPiv = off.pivot ? new THREE.Vector3(off.pivot[0], off.pivot[1], off.pivot[2]) : new THREE.Vector3(0, 0, 0);
2567
2693
  }
2694
+ // GPU 路径:位移发生在顶点着色器里,包围盒要按同一套公式在 CPU 复算,
2695
+ // 否则「运动中的车」的包围盒会停在路径原点(相机 fitBounds / 属性过滤都会错)。
2696
+ const gpuPose = smid != null ? this._gpuPathPoseAt(smid) : null;
2697
+ let headM3 = null;
2698
+ if (gpuPose && gpuPose.yaw !== 0) {
2699
+ const c = Math.cos(gpuPose.yaw);
2700
+ const s = Math.sin(gpuPose.yaw);
2701
+ // 与着色器的 mat3( c, s, 0, -s, c, 0, 0, 0, 1 ) 等价:GLSL 是列优先,
2702
+ // three 的 Matrix3.set 是行优先,所以这里写成 (c, -s; s, c) 才是同一个矩阵。
2703
+ headM3 = new THREE.Matrix3().set(c, -s, 0, s, c, 0, 0, 0, 1);
2704
+ }
2568
2705
  for (const c of corners) {
2569
2706
  if (rotM3 && rotPiv)
2570
2707
  c.sub(rotPiv).applyMatrix3(rotM3).add(rotPiv);
2708
+ if (headM3) {
2709
+ const piv = rotPiv ?? new THREE.Vector3(0, 0, 0);
2710
+ c.sub(piv).applyMatrix3(headM3).add(piv);
2711
+ }
2571
2712
  if (trans)
2572
2713
  c.add(new THREE.Vector3(trans[0], trans[1], trans[2]));
2573
2714
  else if (elev)
2574
2715
  c.z += elev;
2716
+ if (gpuPose)
2717
+ c.add(new THREE.Vector3(gpuPose.pos[0], gpuPose.pos[1], gpuPose.pos[2]));
2575
2718
  c.applyMatrix4(mesh.matrixWorld);
2576
2719
  const s = this.sceneAnchor.meterInMercator;
2577
2720
  const [lng, lat] = this._lngLatFromWorld(c.x * s + this.sceneAnchor.x, -c.y * s + this.sceneAnchor.y);
@@ -2809,7 +2952,7 @@ export class S3MViewer {
2809
2952
  const u = this.selectionEdgeMaterial.uniforms;
2810
2953
  u.uColor.value.set(s.outlineColor ?? s.selectColor);
2811
2954
  u.uWidth.value = Math.max(0.1, s.outlineWidthPx ?? 3);
2812
- u.uOpacity.value = Math.min(1, Math.max(0.05, s.opacity ?? 1));
2955
+ u.uOpacity.value = clampOpacity(s.opacity);
2813
2956
  // 只加全局 selectElevation:单体自己的拔高已经写在状态纹理第 2 行 z 里,
2814
2957
  // 顶点着色器采样时带出来了,这里再加一次就会双重拔高
2815
2958
  if (u.uElevation)
@@ -2899,6 +3042,10 @@ export class S3MViewer {
2899
3042
  const gl = this.renderer.getContext();
2900
3043
  if (gl && typeof gl.isContextLost === 'function' && gl.isContextLost())
2901
3044
  return false;
3045
+ // shading 预热期间材质是「另一种变体」,这一帧先不画:少画一两帧看不出来,
3046
+ // 把平滑的楼画成平面的一眼就能看出来。
3047
+ if (this._prewarming)
3048
+ return true;
2902
3049
  // 先推进动画,再刷脏标记,最后渲染 —— 保证本帧画出来的是最新值
2903
3050
  const animating = this.animator.tick();
2904
3051
  // 脏标记正常由微任务刷掉;这里再兜一次底,保证「本帧画出来的」一定是最新样式
@@ -2949,7 +3096,11 @@ export class S3MViewer {
2949
3096
  this._updateLineResolution(canvas);
2950
3097
  this.renderer.setViewport(0, 0, canvas.width, canvas.height);
2951
3098
  this.renderer.resetState();
2952
- this.renderer.render(this.scene, this.camera);
3099
+ // 完全透明时什么都不画:透明物体照样写深度,画了会在底图上挖出一个洞。
3100
+ // 这里跳过的是「本层的绘制」,宿主自己的清屏 / 底图照旧。
3101
+ if ((this.uniforms.uOpacity?.value ?? 1) > OPACITY_EPS) {
3102
+ this.renderer.render(this.scene, this.camera);
3103
+ }
2953
3104
  this._frame++;
2954
3105
  const now = performance.now();
2955
3106
  if (now - this._fps.last > 500) {
@@ -2959,11 +3110,16 @@ export class S3MViewer {
2959
3110
  }
2960
3111
  // 动态着色 / 动画进行中 / 瓦片加载中 / 瓦片层级或可见性改变,都需要宿主继续驱动下一帧。
2961
3112
  // 动画结束那一帧必须精确回到 false,否则 MapLibre 会永远重绘(耗电、发热)。
2962
- return (animating ||
3113
+ const needsNextFrame = animating ||
2963
3114
  this.style.mode === STYLE.DYNAMIC ||
2964
3115
  gpuPathActive ||
2965
3116
  this.stats.loading > 0 ||
2966
- tilesetChanged);
3117
+ tilesetChanged;
3118
+ // 首帧画完、场上有材质了,再把另一种 shading 变体编出来(异步,不挡当前帧)
3119
+ if (this._prewarmShadingEnabled && !this._shadingPrewarmed && this._pickables.size > 0) {
3120
+ void this.prewarmShading();
3121
+ }
3122
+ return needsNextFrame;
2967
3123
  }
2968
3124
  /* ---------------------------------------------------------------- 只读属性 */
2969
3125
  get fps() {