Draw Bhote Koshi and awareness pulses through engine.ground

Render the Bhote Koshi event and locator through one ground and point display.
Keep Cesium's reveal paths, dashed halo, glowing core, polygon classification,
pick identities and independent point outline opacity. Add static pixel dash
masks, synchronous ground reveals after terrain bounds load, and per-point
outline colour so the shared display preserves those behaviours.

Add a ground pulse field with checked state on all three engines. Keep Cesium's
raised material disc, band equations, front widths, wake and rest timing and
reduced-motion behaviour. Navara now follows Cesium's raised pulse surface and
story styling, with ground effects composed after tone mapping. Move the wind
mesh shader into the Navara engine without changing its transparent pass.

Layer renderer lines fall from 210 to 14 for Cesium and from 794 to 314 for
Navara. Viewer lines fall from 953 to 948, extension reads from 6 to 4, and
engine-name lines from 37 to 36. No coupling count grows.

Checked in the browser, keyless: the contract suite, with its new pulse
pixel checks, passes on Navara and on Cesium apart from the camera-events
check that also fails intermittently before; the Nepal locator and Contacts
engine switches pass. The Nepal event and wind engine switches fail the same
way before this change. Side by side at the locator's overview, Cesium draws
the same pixels as before and Navara's river corridor now glows as Cesium's
does, where it was faint.
This commit is contained in:
German Khokhlov committed 2026-11-07 15:06:26 +04:00
1 parent dacfd33f10
commit f385986383
50 files changed
+1438 -520

No files matched your search

+3
View File
@@ -55,6 +55,9 @@ const NO_MESHES = Object.freeze({
list: () => [],
});
const NO_GROUND = Object.freeze({
createPulseField() {
throw new Error('Navara ground needs the view runtime');
},
createSet() {
throw new Error("Navara ground needs the view's three runtime (ground/)");
},
+8 -5
View File
@@ -44,7 +44,7 @@ const E2 =
1 - (ellipsoid.WGS84.minimumRadius / ellipsoid.WGS84.maximumRadius) ** 2;
/** Item looks as the shader reads them: glow, pulse and dash bits. */
export const LOOK = Object.freeze({ glow: 1, pulse: 2, dash: 4 });
export const LOOK = Object.freeze({ glow: 1, pulse: 2, dash: 4, pattern: 8 });
/** RGBA32F texels per corridor item. */
export const ITEM_TEXELS = 5;
@@ -56,9 +56,12 @@ const geodetic = (latcDeg) =>
/** One item's look: five texels (colour, widths, glow/pulse, dash). */
function itemTexels(item, lengthM) {
const { glow, pulse, dash } = item.animation ?? {};
const { glow, pulse, dash, pattern } = item.animation ?? {};
const flags =
(glow ? LOOK.glow : 0) | (pulse ? LOOK.pulse : 0) | (dash ? LOOK.dash : 0);
(glow ? LOOK.glow : 0) |
(pulse ? LOOK.pulse : 0) |
(dash ? LOOK.dash : 0) |
(pattern ? LOOK.pattern : 0);
return [
...item.fill,
item.widthPx ?? 0,
@@ -75,8 +78,8 @@ function itemTexels(item, lengthM) {
dash?.speed ?? 0,
dash?.gapAlpha ?? 0,
dash?.emission ?? 0,
0,
0,
pattern?.lengthPx ?? 0,
pattern?.pattern ?? 0,
];
}
+61
View File
@@ -0,0 +1,61 @@
import { Effect, EffectAttribute } from 'postprocessing';
import { withFrameUpdates, withPassDisposal } from '../frameDescriptor.js';
/**
* A screen-space pass on a Navara view, registered once per view under `key`.
* `insertAfter` and `insertBefore` place it in the view's effect chain.
* `uniforms()` lists the pass's [name, Uniform] entries; `update` and
* `destroy` run as the descriptor's updateFrame and onDestroy, with the
* descriptor as `this` (its `effect`, `owner`, `view`, `ctx` and `find`).
* The owner is the `owner` of the config added with `view.addEffect`.
*/
export function defineGroundEffect({
key,
name,
fragmentShader,
uniforms,
insertAfter,
insertBefore,
update,
destroy,
}) {
const registered = new WeakSet();
const descriptor = (EffectDesc, NavaraEffect) =>
class GroundEffectDesc extends withPassDisposal(
withFrameUpdates(EffectDesc),
) {
static allowDuplication = true;
static key = key;
static insertAfter = insertAfter;
static insertBefore = insertBefore;
constructor(view, context, config) {
super(view, context, config);
this.owner = config[key].owner;
}
createPass() {
this.effect = new Effect(name, fragmentShader, {
// Keep a separate pass: inputColor is the already tone-mapped frame.
attributes: EffectAttribute.CONVOLUTION,
uniforms: uniforms && new Map(uniforms()),
});
return new NavaraEffect(this.view.camera.raw, this.effect);
}
updateFrame() {
update.call(this);
}
onDestroy() {
destroy?.call(this);
this.effect?.dispose();
super.onDestroy();
}
};
return {
key,
/** Register the pass on `view` the first time it is used there. */
register(view, { EffectDesc, NavaraEffect }) {
if (registered.has(view)) return;
view.registerEffect(key, descriptor(EffectDesc, NavaraEffect));
registered.add(view);
},
};
}
+4 -2
View File
@@ -35,6 +35,7 @@ export function createNavaraGround(
view,
{
createPass,
pulseField,
nextFrame = (run) =>
globalThis.requestAnimationFrame
? globalThis.requestAnimationFrame(run)
@@ -89,7 +90,7 @@ export function createNavaraGround(
if (changed || registry.animating()) askNextFrame();
};
view.on('postRender', retry);
const registry = createGroundRegistry((options) => {
const build = (options) => {
const entry = {
options,
shown: true,
@@ -119,7 +120,8 @@ export function createNavaraGround(
compose();
},
};
});
};
const registry = createGroundRegistry(build, { pulseField });
return {
ground: registry.ground,
/** Every live set's state ({ options, items, shown }) for CPU picks. */
+20
View File
@@ -460,3 +460,23 @@ test('each bin of a packed area points at its own segments', () => {
}
assert.equal(pack.segments.length / 4, expected);
});
test('screen-space dash masks keep their CSS length and all sixteen bits in the pass', () => {
const pack = packSet(
'corridor',
items('corridor', [
{
positions: [
[85, 28],
[85.1, 28.1],
],
color: [0.8, 0.5, 0.3, 0.38],
widthPx: 18,
dashPattern: { lengthPx: 18, pattern: 0xa55a },
},
]),
);
assert.equal(pack.items[7], LOOK.pattern);
assert.deepEqual(Array.from(pack.items.slice(18, 20)), [18, 0xa55a]);
assert.equal(pack.items.length, ITEM_TEXELS * 4);
});
+11
View File
@@ -55,6 +55,7 @@ uniform mat4 uInverseProjection;
uniform mat4 uViewToWorld;
uniform float uLogDepthFC;
uniform float uTime;
uniform float uPixelRatio;
// Rows of ${ROW} texels (pack.js texelStorage).
vec4 atSlot(highp sampler2D image, int slot) {
return texelFetch(image, ivec2(slot & ${ROW - 1}, slot >> ${Math.log2(ROW)}), 0);
@@ -95,6 +96,13 @@ vec3 blendCorridor(vec3 color, int item, float nearest, vec2 normal, float along
rgb = max(vec3(glow - 1.0) + rgb, rgb);
alpha *= clamp(glow, 0.0, 1.0);
}
if ((look & ${LOOK.pattern}) != 0) {
// A screen-aligned 16-bit mask, as the ground PolylineDash material.
vec2 tangent = normalize(vec2(-dot(normal, localDy), dot(normal, localDx)));
float across = dot(gl_FragCoord.xy, tangent);
float bit = floor(fract(across / (dash.z * uPixelRatio)) * 16.0);
alpha *= mod(floor(dash.w / exp2(bit)), 2.0);
}
if ((look & ${LOOK.dash}) != 0) {
float flow = fract(s * pulseDash.y - uTime * pulseDash.w);
float on = 1.0 - smoothstep(pulseDash.z - ${float(DASH_EDGE)}, pulseDash.z + ${float(DASH_EDGE)}, flow);
@@ -400,6 +408,7 @@ class GroundEffectDesc extends withPassDisposal(withFrameUpdates(EffectDesc)) {
['uViewToWorld', new Uniform(new Matrix4())],
['uLogDepthFC', new Uniform(1)],
['uTime', new Uniform(0)],
['uPixelRatio', new Uniform(1)],
]),
});
return new NavaraEffect(camera, this.effect);
@@ -439,6 +448,8 @@ class GroundEffectDesc extends withPassDisposal(withFrameUpdates(EffectDesc)) {
u.get('uViewToWorld').value.copy(camera.matrixWorld);
u.get('uLogDepthFC').value = 2 / Math.log2(camera.far + 1);
u.get('uTime').value = groundSeconds();
const cssWidth = this.view.canvas?.clientWidth;
u.get('uPixelRatio').value = cssWidth > 0 ? input.width / cssWidth : 1;
u.get('tFrames').value = owner.textures.frames;
u.get('tStyles').value = owner.textures.styles;
u.get('tSegments').value = owner.textures.segments;
+216
View File
@@ -0,0 +1,216 @@
// Ground pulse fields over the visible globe, after tone mapping.
import { Matrix4, Uniform, Vector3, Vector4 } from 'three';
import { groundSurfaceUniforms, updateGroundSurface } from './surface.js';
import { defineGroundEffect } from './effect.js';
const KEY = 'gevGroundPulses';
const fragmentShader = /* glsl */ `
uniform sampler2D tAllDepth;
uniform sampler2D tSurfaceDepth;
uniform mat4 uInverseProjection;
uniform mat4 uInverseView;
uniform float uLogDepthFC;
uniform vec3 uCenter;
uniform float uRadiusAngle;
uniform vec3 uRadiiM;
uniform vec4 uColor;
uniform vec4 uLineColor;
uniform vec4 uHaloColor;
uniform vec4 uRadii;
uniform vec4 uAlphas;
uniform float uDepth;
uniform float uLineWidth;
uniform float uHaloWidth;
uniform float uPixelRatio;
vec3 toDisplay(vec3 c) {
return mix(12.92*c,1.055*pow(max(c,vec3(0.0)),vec3(1.0/2.4))-0.055,step(vec3(0.0031308),c));
}
vec3 toLinear(vec3 c) {
return mix(c/12.92,pow(max((c+0.055)/1.055,vec3(0.0)),vec3(2.4)),step(vec3(0.04045),c));
}
vec4 over(vec4 top, vec4 under) {
float a = top.a + under.a * (1.0 - top.a);
if (a <= 0.0) return vec4(0.0);
return vec4((top.rgb * top.a + under.rgb * under.a * (1.0 - top.a)) / a, a);
}
void mainImage(const in vec4 inputColor,const in vec2 uv,out vec4 outputColor) {
outputColor=inputColor;
float depth=unpackRGBAToDepth(texture2D(tAllDepth,uv));
float distance=exp2(2.0*depth/uLogDepthFC)-1.0;
vec4 ray=uInverseProjection*vec4(uv*2.0-1.0,-1.0,1.0);
vec3 point=ray.xyz*(distance/-ray.z);
vec3 origin=uInverseView[3].xyz;
vec3 direction=normalize((uInverseView*vec4(ray.xyz,0.0)).xyz);
vec3 o=origin/uRadiiM;
vec3 d=direction/uRadiiM;
float a=dot(d,d);
float b=dot(o,d);
float c=dot(o,o)-1.0;
float discriminant=b*b-a*c;
float hit=(-b-sqrt(max(discriminant,0.0)))/a;
vec3 world=origin+direction*hit;
vec3 up=normalize(world);
float r=length(cross(up,uCenter))/sin(uRadiusAngle);
float cssPx=max(length(vec2(dFdx(r),dFdy(r))),1e-7)*uPixelRatio;
if(discriminant<0.0||hit<=0.0||dot(up,uCenter)<=0.0||r>1.0) return;
// The raised ellipsoid is depth tested, as the material disc is.
if(depth<1.0 && hit>length(point)+1.0) return;
float band=0.0;
for(int i=0;i<4;i++) {
float inside=uRadii[i]-r;
if(inside>=0.0&&inside<=uDepth) {
float t=1.0-inside/uDepth;
band+=uAlphas[i]*t*t;
}
}
vec4 result=vec4(uColor.rgb,clamp(band*uColor.a,0.0,1.0));
float outerHalf=uLineWidth*0.5;
float coreHalf=max(uLineWidth-uHaloWidth,0.0)*0.5;
for(int i=0;i<4;i++) {
float d=abs(uRadii[i]-r)/cssPx;
float cover=clamp(outerHalf+0.5-d,0.0,1.0);
if(cover<=0.0) continue;
float core=clamp(coreHalf+0.5-d,0.0,1.0);
vec4 pulse=mix(uHaloColor,uLineColor,core);
result=over(vec4(pulse.rgb,pulse.a*cover*uAlphas[i]),result);
}
if(result.a<=0.0) return;
vec3 color=mix(toDisplay(inputColor.rgb),result.rgb,result.a);
outputColor=vec4(toLinear(color),inputColor.a);
}
`;
const pulseEffect = defineGroundEffect({
key: KEY,
name: 'GevGroundPulses',
fragmentShader,
insertAfter: [
'gevGround',
'gevObservedWeather',
'gevNepalEvent',
'gevImagery',
'toneMapping',
],
insertBefore: [
'gevPreSharpenOverlay',
'gevSharpen',
'smaa',
'fxaa',
'gevOverlay',
'final',
],
uniforms: () => [
...groundSurfaceUniforms(),
['uInverseView', new Uniform(new Matrix4())],
['uCenter', new Uniform(new Vector3(1, 0, 0))],
['uRadiusAngle', new Uniform(1)],
['uRadiiM', new Uniform(new Vector3())],
['uColor', new Uniform(new Vector4())],
['uLineColor', new Uniform(new Vector4())],
['uHaloColor', new Uniform(new Vector4())],
['uRadii', new Uniform(new Vector4())],
['uAlphas', new Uniform(new Vector4())],
['uDepth', new Uniform(0.35)],
['uLineWidth', new Uniform(3)],
['uHaloWidth', new Uniform(1)],
['uPixelRatio', new Uniform(1)],
],
update() {
const owner = this.owner,
camera = this.view.camera.raw;
if (!this.effect || !camera) return;
updateGroundSurface(this.effect, camera, this.ctx, this.find('mrt'));
const u = this.effect.uniforms;
u.get('uInverseView').value.copy(camera.matrixWorld);
u.get('uCenter').value.copy(owner.center);
u.get('uRadiusAngle').value = owner.radiusAngle;
u.get('uRadiiM').value.set(
6378137 + owner.heightM,
6378137 + owner.heightM,
6356752.314245179 + owner.heightM,
);
u.get('uColor').value.fromArray(owner.color);
u.get('uLineColor').value.fromArray(owner.lineColor);
u.get('uHaloColor').value.fromArray(owner.haloColor);
u.get('uRadii').value.fromArray(owner.radii);
u.get('uAlphas').value.fromArray(owner.alphas);
u.get('uDepth').value = owner.depth;
u.get('uLineWidth').value = owner.lineWidth;
u.get('uHaloWidth').value = owner.haloWidth;
// Buffer pixels per CSS pixel: the pass can run above the canvas's
// CSS size, and the pulse widths are in CSS pixels.
const cssWidth = owner.cssWidth();
u.get('uPixelRatio').value =
cssWidth > 0
? this.ctx.getInputBuffer().width / cssWidth
: globalThis.devicePixelRatio || 1;
},
});
/**
* The pulse disc on one Navara view around `center` (Earth-fixed metres):
* `draw({ radii, alphas, level })` each frame with the fronts as fractions of
* `radiusM` and their opacities, `move(center)`, and `destroy()`. Colors are
* rgba arrays in 0..1: the band, the pulse line and its halo.
*/
export function createNavaraPulseField(
{ view, EffectDesc, NavaraEffect, canvas },
{
center,
radiusM,
heightM,
color,
lineColor,
haloColor,
depth,
lineWidth,
haloWidth,
},
) {
pulseEffect.register(view, { EffectDesc, NavaraEffect });
const owner = {
cssWidth: () => canvas?.clientWidth ?? 0,
center: new Vector3(),
radiusAngle: radiusM / Math.hypot(center.x, center.y, center.z),
heightM,
color,
lineColor,
haloColor,
radii: [0, 0, 0, 0],
alphas: [0, 0, 0, 0],
depth,
lineWidth,
haloWidth,
};
let handle = null,
shown = false,
destroyed = false;
const move = (next) => owner.center.set(next.x, next.y, next.z).normalize();
move(center);
return {
move(next) {
if (!destroyed) move(next);
},
draw({ radii, alphas, level }) {
if (destroyed) return;
for (let i = 0; i < 4; i++) {
owner.radii[i] = radii[i] ?? 0;
owner.alphas[i] = alphas[i] ?? 0;
}
const show = level > 0;
if (show === shown) return;
shown = show;
if (!handle && show)
handle = view.addEffect({ [KEY]: { owner }, visible: true });
else handle?.update({ visible: show });
},
destroy() {
if (destroyed) return;
destroyed = true;
handle?.delete();
handle = null;
view.forceUpdate();
},
};
}
+53
View File
@@ -0,0 +1,53 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as geo from '../../../geo/index.js';
import { createNavaraPulseField } from './pulse.js';
test('the Navara pulse disc draws only while the pulses run', () => {
const effects = [];
const view = {
registerEffect() {},
forceUpdate() {},
addEffect(config) {
const handle = {
config,
visible: config.visible,
deleted: false,
update(next) {
handle.visible = next.visible;
},
delete() {
handle.deleted = true;
},
};
effects.push(handle);
return handle;
},
};
const disc = createNavaraPulseField(
{ view, EffectDesc: class {}, NavaraEffect: class {} },
{
center: geo.cartesian3.fromDegrees(3, 27, 0),
radiusM: 250_000,
heightM: 2500,
color: [0, 0, 1, 0.2],
lineColor: [0, 0, 1, 1],
haloColor: [0, 0, 0, 0.8],
depth: 0.35,
lineWidth: 3,
haloWidth: 1,
},
);
disc.draw({ level: 0, radii: [0.1, 0.4, 0.7], alphas: [0, 0, 0] });
assert.equal(effects.length, 0, 'nothing drawn at rest');
disc.draw({ level: 1, radii: [0.1, 0.4, 0.7], alphas: [0.5, 0.3, 0.2] });
assert.equal(effects.length, 1);
const owner = effects[0].config.gevGroundPulses.owner;
assert.deepEqual(owner.radii, [0.1, 0.4, 0.7, 0]);
assert.deepEqual(owner.alphas, [0.5, 0.3, 0.2, 0]);
assert.ok(Math.abs(owner.center.length() - 1) < 1e-9, 'a unit direction');
disc.draw({ level: 0, radii: [0, 0, 0], alphas: [0, 0, 0] });
assert.equal(effects[0].visible, false);
disc.destroy();
assert.equal(effects[0].deleted, true);
});
+45
View File
@@ -0,0 +1,45 @@
// Public depth inputs shared by actual terrain/tiles classifiers.
import {
DataTexture,
FloatType,
RGBAFormat,
NearestFilter,
Matrix4,
Uniform,
RGBADepthPacking,
} from 'three';
export function createGroundTexture(data, width, height) {
const texture = new DataTexture(data, width, height, RGBAFormat, FloatType);
texture.minFilter = NearestFilter;
texture.magFilter = NearestFilter;
texture.needsUpdate = true;
return texture;
}
export function createGroundStorage(texels) {
const width = Math.min(1024, Math.max(1, texels));
const height = Math.max(1, Math.ceil(texels / width));
const data = new Float32Array(width * height * 4);
return {
data,
width,
height,
texture: createGroundTexture(data, width, height),
};
}
export function groundSurfaceUniforms() {
return [
['tAllDepth', new Uniform(null)],
['tSurfaceDepth', new Uniform(null)],
['uInverseProjection', new Uniform(new Matrix4())],
['uLogDepthFC', new Uniform(1)],
];
}
export function updateGroundSurface(effect, camera, context, mrt) {
if (mrt?.depthBufferPacking !== RGBADepthPacking)
throw new Error('Ground classification requires packed scene depth');
const u = effect.uniforms;
u.get('tAllDepth').value = mrt.depthBuffer;
u.get('tSurfaceDepth').value = context.getRenderTarget().depthTexture;
u.get('uInverseProjection').value.copy(camera.projectionMatrixInverse);
u.get('uLogDepthFC').value = 2 / Math.log2(camera.far + 1);
}
+1 -1
View File
@@ -182,7 +182,7 @@ class ImageryEffectDesc extends withPassDisposal(withFrameUpdates(EffectDesc)) {
'gevNepalEvent',
'gevObservedWeather',
'gevEarthquakeGround',
'gevAwarenessPulses',
'gevGroundPulses',
'gevGround',
'gevPreSharpenOverlay',
'gevSharpen',
+9 -1
View File
@@ -36,6 +36,7 @@ import { createNavaraMovers } from './movers/index.js';
import { createNavaraLines } from './lines/index.js';
import { createNavaraMeshes } from './meshes.js';
import { createNavaraGround } from './ground/index.js';
import { createNavaraPulseField } from './ground/pulse.js';
import { createGroundPass } from './ground/pass.js';
import { createNavaraImagery } from './imagery/index.js';
import { createImageryPass } from './imagery/pass.js';
@@ -176,7 +177,14 @@ export async function createNavaraGlobe({ container, search, hd = false }) {
}),
lines: createNavaraLines(view, { overlay }),
meshes: (parts) => createNavaraMeshes(view, { MeshDesc, ...parts }),
ground: createNavaraGround(view, { createPass: createGroundPass }),
ground: createNavaraGround(view, {
createPass: createGroundPass,
pulseField: (options) =>
createNavaraPulseField(
{ view, EffectDesc, NavaraEffect, canvas },
options,
),
}),
imagery: (parts) =>
createNavaraImagery(view, { ...parts, createPass: createImageryPass }),
});
+13 -6
View File
@@ -35,6 +35,10 @@ import { DETACHED_SONAR, SONAR_VERTEX } from '../sonar.js';
const VERTEX_HEAD = /* glsl */ `
attribute vec4 gevStyle;
attribute vec4 gevColor;
#ifdef GEV_POINT
attribute vec4 gevOutlineColor;
varying vec4 vGevOutlineColor;
#endif
attribute vec4 gevUv;
uniform float uGevSizePx;
uniform float uGevFootprint;
@@ -84,6 +88,7 @@ float gevSizePx = uGevSizePx * gevScale;
vGevOutline = 0.0;
vGevPixelDistance = 0.0;
#ifdef GEV_POINT
vGevOutlineColor = gevOutlineColor;
float gevBorderPx = 2.0 * uGevOutlinePx * gevDistanceScale;
float gevOutlinedSize = gevSizePx + gevBorderPx;
vGevOutline = gevBorderPx / max(gevOutlinedSize, 1e-3);
@@ -118,7 +123,9 @@ vMapUv = mix(gevUv.xy, gevUv.zw, uv);
`;
const FRAGMENT_HEAD = /* glsl */ `
uniform vec4 uGevOutlineColor;
#ifdef GEV_POINT
varying vec4 vGevOutlineColor;
#endif
varying vec4 vGevColor;
varying vec2 vGevLocal;
varying float vGevOutline;
@@ -143,7 +150,7 @@ float gevDistanceToCenter = gevRadius * 0.5;
float gevWholeAlpha = 1.0 - smoothstep(gevMaxDistance, 0.5, gevDistanceToCenter);
float gevInner = 1.0 - vGevOutline;
float gevInnerAlpha = 1.0 - smoothstep(gevMaxDistance * gevInner, 0.5 * gevInner, gevDistanceToCenter);
vec4 gevOutline = vec4(uGevOutlineColor.rgb, uGevOutlineColor.a * vGevSonarFactor);
vec4 gevOutline = vec4(vGevOutlineColor.rgb, vGevOutlineColor.a * vGevSonarFactor);
diffuseColor *= sRGBTransferEOTF(mix(gevOutline, vGevColor, gevInnerAlpha));
diffuseColor.a *= gevWholeAlpha * vGevTranslucency;
if (diffuseColor.a < 0.005) discard;
@@ -183,7 +190,7 @@ export function patchMoverShader(
let fragment = replace(
shader.fragmentShader,
'void main() {',
`${FRAGMENT_HEAD}\nvoid main() {`,
`${point ? '#define GEV_POINT\n' : ''}${FRAGMENT_HEAD}\nvoid main() {`,
);
let colorFragment = fragmentColor(point);
if (alwaysVisible)
@@ -268,6 +275,7 @@ export function createMoverMesh(
const styleAttribute = attribute('gevStyle', 4);
const colorAttribute = attribute('gevColor', 4);
const uvAttribute = attribute('gevUv', 4);
const outlineAttribute = point ? attribute('gevOutlineColor', 4) : null;
const uvRects = point
? null
: atlasUvRects(options.sprite.atlas.cells, options.cellKeys);
@@ -284,9 +292,6 @@ export function createMoverMesh(
value: typeof depthTest === 'object' ? depthTest.disableWithinM : -1,
},
uGevOutlinePx: { value: point ? options.point.outlinePx : 0 },
uGevOutlineColor: {
value: point ? [...options.point.outlineColor] : [0, 0, 0, 1],
},
uGevPixelRatio: { value: 1 },
uGevDepthMode: {
value:
@@ -347,6 +352,7 @@ export function createMoverMesh(
matrices: mesh.instanceMatrix.array,
style: styleAttribute.array,
colors: colorAttribute.array,
outlineColors: outlineAttribute?.array,
uvs: uvAttribute.array,
};
const upload = (from, to) => {
@@ -356,6 +362,7 @@ export function createMoverMesh(
[styleAttribute, 4],
[colorAttribute, 4],
[uvAttribute, 4],
...(outlineAttribute ? [[outlineAttribute, 4]] : []),
]) {
// Ranges add up until three uploads them (and clears them): a
// partial commit after a full rewrite in the same frame (an origin
+29 -1
View File
@@ -156,6 +156,7 @@ test('the shader patch sizes the quad in pixels and colours it per instance', ()
);
assert.doesNotMatch(shader.fragmentShader, /gevRadius > 1\.0\) discard/);
const point = patchMoverShader(basicShader(), {}, { point: true });
assert.match(point.fragmentShader, /#define GEV_POINT/);
assert.match(point.fragmentShader, /if \(gevRadius > 1\.0\) discard;/);
});
@@ -223,12 +224,39 @@ test('points have no atlas and draw a disc', () => {
depthTest: 'always',
point: { sizePx: 6, outlinePx: 1 },
});
const mover = createMoverMesh(options, createMoverStore(options));
const store = createMoverStore(options);
const mover = createMoverMesh(options, store);
assert.equal(mover.mesh.material.map, null);
assert.equal(mover.mesh.material.depthTest, false);
assert.equal(mover.mesh.material.side, FrontSide);
assert.equal(mover.uniforms.uGevDepthMode.value, 0, "'always': no test");
assert.equal(mover.uniforms.uGevOutlinePx.value, 1);
store.set(0, {
position: { x: 6378137, y: 0, z: 0 },
color: [0, 1, 1, 0.5],
outlineColor: [1, 0, 0, 0.25],
});
store.setCount(1);
mover.commit(store.dirty());
assert.deepEqual(
Array.from(mover.mesh.geometry.getAttribute('gevOutlineColor').array),
[1, 0, 0, 0.25],
);
assert.deepEqual(
Array.from(mover.mesh.geometry.getAttribute('gevColor').array),
[0, 1, 1, 0.5],
);
store.clean();
store.set(0, { outlineColor: [0, 0, 1, 0.75] });
mover.commit(store.dirty());
assert.deepEqual(
Array.from(mover.mesh.geometry.getAttribute('gevOutlineColor').array),
[0, 0, 1, 0.75],
);
assert.deepEqual(
Array.from(mover.mesh.geometry.getAttribute('gevColor').array),
[0, 1, 1, 0.5],
);
mover.dispose();
});
+2
View File
@@ -63,6 +63,8 @@ export function packInstances(store, from, to, origin, uvRects, out) {
colorOut[s + 1] = colors[s + 1];
colorOut[s + 2] = colors[s + 2];
colorOut[s + 3] = colors[s + 3];
if (out.outlineColors && store.outlineColors)
out.outlineColors.set(store.outlineColors.subarray(s, s + 4), s);
if (uvs && uvRects) {
const r = cells[index] * 4;
uvs[s] = uvRects[r];
+1 -1
View File
@@ -106,7 +106,7 @@ test('the mover shaders treat contacts by their anchor and keep their position',
if (point)
assert.match(
shader.fragmentShader,
/uGevOutlineColor\.a \* vGevSonarFactor/,
/vGevOutlineColor\.a \* vGevSonarFactor/,
);
}
});
+132
View File
@@ -0,0 +1,132 @@
import {
Mesh,
ShaderMaterial,
InstancedBufferGeometry,
InstancedBufferAttribute,
Float32BufferAttribute,
Vector2,
DoubleSide,
} from 'three';
import { fromDegrees } from '../../geo/cartesian3.js';
const KEY = 'gevWindFlow';
const registered = new WeakSet();
const vertexShader = /* glsl */ `
#include <common>
#include <logdepthbuf_pars_vertex>
attribute vec3 begin, end;
attribute vec3 progress;
uniform vec2 viewport;
varying vec4 flow;
void main() {
vec3 world = mix(begin,end,position.x);
vec4 a = projectionMatrix * viewMatrix * vec4(begin,1.0);
vec4 b = projectionMatrix * viewMatrix * vec4(end,1.0);
vec2 delta = (b.xy/max(1.0,b.w)-a.xy/max(1.0,a.w))*viewport;
vec2 perp = vec2(-delta.y,delta.x)/max(0.000001,length(delta));
gl_Position = mix(a,b,position.x);
gl_Position.xy += perp * position.y * 2.4 * gl_Position.w/viewport;
flow = vec4(mix(progress.x,progress.y,position.x),progress.z,position.y,
dot(normalize(world),normalize(cameraPosition-world)));
#include <logdepthbuf_vertex>
}`;
const fragmentShader = /* glsl */ `
#include <common>
#include <logdepthbuf_pars_fragment>
uniform float seconds,heightFade,ghost;
varying vec4 flow;
void main() {
#include <logdepthbuf_fragment>
float behind=fract(seconds*0.16+flow.y-flow.x);
float tail=1.0-smoothstep(0.0,0.32,behind), tip=1.0-smoothstep(0.0,0.045,behind);
float ends=smoothstep(0.0,0.055,flow.x)*(1.0-smoothstep(0.945,1.0,flow.x));
float edge=1.0-smoothstep(0.52,1.0,abs(flow.z));
float alpha=(ghost+0.64*tail+0.16*tip)*ends*edge*smoothstep(0.0,0.065,flow.w)*heightFade;
if(alpha<0.001) discard;
gl_FragColor=vec4(mix(vec3(0.50,0.79,0.90),vec3(0.91,0.99,1.0),tip),alpha);
}`;
export function createWindFlowMesh({ view, MeshDesc }, paths, heightM) {
if (!registered.has(view)) {
view.registerMesh(
KEY,
class extends MeshDesc {
constructor(host, ctx, config) {
super(host, ctx, config);
this.flow = config[KEY];
}
getPassKey() {
return 'transparent';
}
createMesh() {
return this.flow;
}
onDestroy() {
this.flow.geometry.dispose();
this.flow.material.dispose();
super.onDestroy();
}
},
);
registered.add(view);
}
const segments = paths.reduce((sum, p) => sum + p.coordinates.length - 1, 0);
const begin = new Float32Array(segments * 3),
end = new Float32Array(segments * 3),
progress = new Float32Array(segments * 3);
let i = 0;
for (const path of paths) {
let previous = null;
const n = path.coordinates.length - 1;
for (let j = 0; j <= n; j++) {
const [lon, lat] = path.coordinates[j];
const next = fromDegrees(lon, lat, heightM);
if (previous) {
begin.set([previous.x, previous.y, previous.z], i);
end.set([next.x, next.y, next.z], i);
progress.set([(j - 1) / n, j / n, path.phase], i);
i += 3;
}
previous = next;
}
}
const geometry = new InstancedBufferGeometry();
geometry.setAttribute(
'position',
new Float32BufferAttribute([0, -1, 0, 0, 1, 0, 1, -1, 0, 1, 1, 0], 3),
);
geometry.setIndex([0, 1, 2, 2, 1, 3]);
for (const [key, array] of Object.entries({ begin, end, progress }))
geometry.setAttribute(key, new InstancedBufferAttribute(array, 3));
geometry.instanceCount = segments;
const uniforms = {
seconds: { value: 0 },
heightFade: { value: 0 },
ghost: { value: 0.25 },
viewport: { value: new Vector2(1, 1) },
};
const material = new ShaderMaterial({
uniforms,
vertexShader,
fragmentShader,
transparent: true,
side: DoubleSide,
depthWrite: false,
toneMapped: false,
});
material.forceSinglePass = true;
const mesh = new Mesh(geometry, material);
mesh.frustumCulled = false;
const holder = view.addMesh({ [KEY]: mesh });
return {
update({ time, fade, still, width, height }) {
mesh.visible = fade > 0;
uniforms.seconds.value = time;
uniforms.heightFade.value = fade;
uniforms.ghost.value = still ? 0.34 : 0.25;
uniforms.viewport.value.set(Math.max(1, width), Math.max(1, height));
},
destroy: () => holder.delete(),
segments,
};
}