diff --git a/src/render/cesium/draw.js b/src/render/cesium/draw.js index 1f9e63ad2..ac73bc4c4 100644 --- a/src/render/cesium/draw.js +++ b/src/render/cesium/draw.js @@ -239,8 +239,26 @@ function radialRimMaterial(fill) { return material; } +/** + * An ellipse radius at a camera `height`: a fixed one as it is, one by + * camera height scaled by its factor and held within its bounds. + * @param {number|{byCameraHeight: {factor: number, min: number, max: number}}} radius + * @param {number} height + */ +export function radiusAt(radius, height) { + if (typeof radius === 'number') return radius; + const { factor, min, max } = radius.byCameraHeight; + return Math.max(min, Math.min(max, height * factor)); +} + +/** Whether a shape is an ellipse with a radius by camera height. */ +const byCameraHeight = (item) => + item.geometry?.kind === 'ellipse' && + (typeof item.geometry.semiMajor !== 'number' || + typeof item.geometry.semiMinor !== 'number'); + /** The line styles the port drapes. */ -const DRAPED_STYLES = new Set(['solid', 'glow', 'dash', 'flow']); +const DRAPED_STYLES = new Set(['solid', 'glow', 'dash', 'flow', 'arrow']); // Whether Cesium's approximate terrain heights have been asked for. let terrainHeightsAsked = false; @@ -2110,7 +2128,7 @@ export function createCesiumDraw({ for (const item of record.items.values()) if (item.mode === 'draped' && !DRAPED_STYLES.has(item.style.kind)) throw new Error( - 'the Cesium renderer drapes solid, glow, dash and flow lines only', + 'the Cesium renderer drapes solid, glow, dash, flow and arrow lines only', ); else if ( item.frame === 'inertial' && @@ -3115,18 +3133,29 @@ export function createCesiumDraw({ outer, holes.map((h) => new Cesium.PolygonHierarchy(h)), ); + const polygon = { + polygonHierarchy: hierarchy, + height: g.perPositionHeight ? undefined : heightOf(g.rings[0][0]), + extrudedHeight, + perPositionHeight: g.perPositionHeight, + }; return { - fill: new Cesium.PolygonGeometry({ - polygonHierarchy: hierarchy, - height: g.perPositionHeight ? undefined : heightOf(g.rings[0][0]), - extrudedHeight, - perPositionHeight: g.perPositionHeight, - }), + fill: new Cesium.PolygonGeometry(polygon), + // Extruded, its outline is the volume's edges (both faces and the + // walls' corners), as the entities' extruded polygons draw it. + outline: + item.outline && extrudedHeight !== undefined + ? new Cesium.PolygonOutlineGeometry(polygon) + : undefined, // Its holes are outlined too, as the entities' polygons outline them. rings: [outer, ...holes], }; } case 'ellipse': { + if (byCameraHeight(item)) + throw new Error( + 'the Cesium renderer takes radii by camera height on clamped ellipses only', + ); const ellipse = { center: toCartesian(g.center), semiMajorAxis: g.semiMajor, @@ -3175,6 +3204,86 @@ export function createCesiumDraw({ } } + /** + * The camera's height for radii by camera height: above the ellipsoid, + * as Cesium places it (1000 m while it has none). + */ + const cameraHeight = () => { + const height = scene.camera?.positionCartographic?.height; + return Number.isFinite(height) ? height : 1000; + }; + + /** A clamped ellipse's radii by camera height at this frame's height, or null. */ + function radiiOf(item) { + if (!byCameraHeight(item)) return null; + const height = cameraHeight(); + return [ + radiusAt(item.geometry.semiMajor, height), + radiusAt(item.geometry.semiMinor, height), + ]; + } + + /** + * Before a frame draws: clamped ellipses with radii by camera height + * whose radii have changed with the camera are drawn at the new ones. A + * colour fill is drawn alone where it is, built in this frame + * (`moveShape`), as Cesium's entities rebuild a ground ellipse whose + * radius follows a callback, while no more than `MOVING_SHAPES` of the + * set would be drawn alone; past that, and for any other fill once its + * radii have changed by more than `REBUILD_RADII`, its set rebuilds (one + * rebuild at a time). Hidden ones wait until they show. + */ + function followCameraHeight() { + for (const record of sets.values()) { + const parts = record.shapeParts; + if (record.kind !== 'shapes' || !parts || record.spec.show === false) + continue; + try { + followIn(record, parts); + } catch (error) { + // The set draws as it did; the next frame tries again. + report(error); + } + } + } + + /** Relative change of radii past which a fill drawn in a batch rebuilds. */ + const REBUILD_RADII = 0.02; + + function followIn(record, parts) { + const changed = (radii, part, by) => + Math.abs(radii[0] - part.radii[0]) > by * part.radii[0] || + Math.abs(radii[1] - part.radii[1]) > by * part.radii[1]; + let alone = 0; + for (const part of parts.values()) if (part.solo) alone += 1; + // Those the host still retiring draws alone count too, until it goes. + if (record.retiring) + for (const part of record.retiringShapeParts?.values() ?? []) + if (part.solo && part.ground && !part.ground.isDestroyed()) alone += 1; + let rebuild = false; + for (const [id, part] of parts) { + if (!part.radii || !part.ground) continue; + const item = record.items.get(id); + if (!item || item.show === false || !byCameraHeight(item)) continue; + const radii = radiiOf(item); + if (!changed(radii, part, 1e-3)) continue; + if (part.ground.isDestroyed() || part.batch?.isDestroyed()) continue; + const movable = + colourFill(item) && + groundSyncs() && + typeof record.host?.add === 'function' && + (part.solo || alone < MOVING_SHAPES); + if (movable) { + if (!part.solo) alone += 1; + moveShape(record, part, item); + } else if (changed(radii, part, REBUILD_RADII)) rebuild = true; + } + if (rebuild && !record.pending) { + record.rebuild(); + requestRender(); + } + } + /** * A clamped shape's fill geometry, on the ellipsoid for draping; an * ellipse with a rim fill is cut finely, so its rim runs round. @@ -3191,14 +3300,19 @@ export function createCesiumDraw({ ), }); } - case 'ellipse': - if (typeof g.semiMajor !== 'number' || typeof g.semiMinor !== 'number') - throw new Error('the Cesium renderer takes fixed ellipse radii only'); + case 'ellipse': { + // Radii by camera height are the ones it has at this frame's height. + const height = cameraHeight(); + const major = radiusAt(g.semiMajor, height); + const minor = radiusAt(g.semiMinor, height); + // Radii that follow the camera apart may cross: the longer is then + // drawn as Cesium's semi-major axis, a quarter turn on. + const crossed = minor > major; return new Cesium.EllipseGeometry({ center: toCartesian(g.center), - semiMajorAxis: g.semiMajor, - semiMinorAxis: g.semiMinor, - rotation: g.rotation ?? 0, + semiMajorAxis: crossed ? minor : major, + semiMinorAxis: crossed ? major : minor, + rotation: (g.rotation ?? 0) + (crossed ? Math.PI / 2 : 0), ...(rimFill ? { granularity: RIM_GRANULARITY, @@ -3208,6 +3322,7 @@ export function createCesiumDraw({ } : {}), }); + } case 'rectangle': return new Cesium.RectangleGeometry({ rectangle: Cesium.Rectangle.fromDegrees( @@ -3279,6 +3394,8 @@ export function createCesiumDraw({ look: lookOf(item), id: pickId(record, item), ground: null, + // Radii by camera height as drawn (`followCameraHeight`). + radii: radiiOf(item), }; parts.set(item.id, part); const show = new Cesium.ShowGeometryInstanceAttribute( @@ -3525,13 +3642,7 @@ export function createCesiumDraw({ if (!was.id || !was.ground || !colourFill(item)) return false; if (!colourFill(was.look)) return false; if (!sameValues(placedLookOf(was.look), placedLookOf(item))) return false; - // Refused geometry (an ellipse radius by camera height) rebuilds, to throw. const g = item.geometry; - if ( - g?.kind === 'ellipse' && - (typeof g.semiMajor !== 'number' || typeof g.semiMinor !== 'number') - ) - return false; if (!['polygon', 'ellipse', 'rectangle'].includes(g?.kind)) return false; return groundSyncs() && typeof record.host?.add === 'function'; } @@ -3545,6 +3656,8 @@ export function createCesiumDraw({ */ function moveShape(record, part, item) { const host = record.host; + // Built first: geometry it cannot build leaves the part as it was. + const geometry = groundGeometry(item); if (part.solo) { if (part.ground && !part.ground.isDestroyed()) host.remove(part.ground); } else { @@ -3558,6 +3671,7 @@ export function createCesiumDraw({ part.solo = true; part.pendingShow = undefined; part.look = lookOf(item); + part.radii = radiiOf(item); part.id.meta = item.meta; const pickable = record.spec.pickable !== false; const Ground = pickable @@ -3566,7 +3680,7 @@ export function createCesiumDraw({ part.ground = new Ground({ geometryInstances: [ new Cesium.GeometryInstance({ - geometry: groundGeometry(item), + geometry, attributes: { color: Cesium.ColorGeometryInstanceAttribute.fromColor( toColor(item.fill), @@ -3652,6 +3766,22 @@ export function createCesiumDraw({ item.extrudeHeight === undefined && (typeof item.fill !== 'object' || Array.isArray(item.fill)); + /** + * Whether an unclamped shape classifies what is inside its volume: one + * with a volume (extruded, or a box) and a fill, on a scene that can + * classify. Where it cannot, it draws as the volume itself. + */ + function classifies(item) { + if (!item.classifyVolume || !item.fill) return false; + if (item.extrudeHeight === undefined && item.geometry.kind !== 'box') + return false; + try { + return Cesium.ClassificationPrimitive.isSupported(scene); + } catch { + return false; + } + } + function buildShapes(record) { const host = new Cesium.PrimitiveCollection(); const outlines = new Cesium.PolylineCollection(); @@ -3694,7 +3824,33 @@ export function createCesiumDraw({ item.extrudeHeight !== undefined || item.geometry.kind === 'box'; // `lit`: shaded by Cesium's light, or flat; by default solids are lit. const lit = item.lit ?? solid; - if (imageFill && !item.outlineOnly) { + if (classifies(item) && !item.outlineOnly) { + if (imageFill) + throw new Error( + 'the Cesium renderer classifies volumes with colours only', + ); + // What lies inside the volume is tinted: the tiles and terrain it + // covers, as `clampTo` names them. + host.add( + new Cesium.ClassificationPrimitive({ + geometryInstances: new Cesium.GeometryInstance({ + geometry: shape.fill, + modelMatrix: shape.modelMatrix, + attributes: { + color: Cesium.ColorGeometryInstanceAttribute.fromColor( + toColor(item.fill), + ), + }, + id, + }), + classificationType: classificationOf( + item.clampTo ?? record.spec.clampTo ?? 'both', + ), + allowPicking: record.spec.pickable !== false, + asynchronous: false, + }), + ); + } else if (imageFill && !item.outlineOnly) { const material = ownMaterial( Cesium.Material.fromType('Image', { image: toImage(imageFill.image), @@ -3921,6 +4077,7 @@ export function createCesiumDraw({ building: () => [...sets.values()].some((record) => record.pending), /** Each frame, before it draws: the horizon cull. */ beforeRender() { + followCameraHeight(); cullHorizon(); runFlows(); for (const record of sets.values()) diff --git a/src/render/cesium/draw.test.mjs b/src/render/cesium/draw.test.mjs index 95d4d7c8e..25c266ecf 100644 --- a/src/render/cesium/draw.test.mjs +++ b/src/render/cesium/draw.test.mjs @@ -503,10 +503,9 @@ test('hidden clamped fills wait for nothing, and the hidden ones it cannot build fill('c', 2, false, { fill: { preset: 'radialRim' } }), fill('d', 3, false, { geometry: { - kind: 'ellipse', + kind: 'box', center: { lon: 3, lat: 0 }, - semiMajor: { byCameraHeight: { factor: 1, min: 1, max: 2 } }, - semiMinor: 1000, + dimensions: { x: 1, y: 1, z: 1 }, }, }), ]), @@ -616,22 +615,204 @@ test('clamped shapes refuse what they cannot draw', () => { ]), /colours only/, ); + set.dispose(); + // Radii by camera height are for clamped ellipses alone. + const unclamped = draw.shapes({ id: 'refuse-unclamped' }); assert.throws( () => - set.set([ + unclamped.set([ { ...disc, + height: 'absolute', geometry: { ...disc.geometry, semiMajor: { byCameraHeight: { factor: 1, min: 1, max: 2 } }, }, }, ]), - /fixed ellipse radii/, + /radii by camera height on clamped ellipses only/, ); - set.dispose(); + unclamped.dispose(); }); +test('a clamped ellipse with radii by camera height draws at the camera height and follows it', () => + withTerrainHeights(() => { + const scene = fakeScene(); + let height = 2000; + Object.defineProperty(scene.camera, 'positionCartographic', { + get: () => ({ height }), + }); + const { draw, frame } = drawOver(scene); + const set = draw.shapes({ id: 'rings' }); + const radius = { byCameraHeight: { factor: 0.03, min: 14, max: 170 } }; + const ring = (show = true) => ({ + id: 'ring', + geometry: { + kind: 'ellipse', + center: { lon: 0, lat: 0 }, + semiMajor: radius, + semiMinor: radius, + }, + fill: [0.5, 0.9, 1, 0.38], + height: 'clampGround', + show, + }); + set.set([ring()]); + const host = scene.added[0]; + const radiusIn = (ground) => + ground.geometryInstances[0].geometry._semiMajorAxis; + const last = () => host.get(host.length - 1); + assert.equal(radiusIn(last()), 60, '3% of 2000 m'); + // The camera has not moved: nothing is built. + const built = last(); + frame(); + assert.equal(last(), built); + // It climbs: the ring is drawn wider in the frame that draws it, alone. + height = 4000; + frame(); + const wider = last(); + assert.notEqual(wider, built); + assert.equal(wider.asynchronous, false); + assert.equal(radiusIn(wider), 120); + assert.equal(wider.geometryInstances[0].id.id, 'ring', 'its own pick id'); + // Held within its bounds. + height = 1e6; + frame(); + assert.equal(radiusIn(last()), 170); + height = 10; + frame(); + assert.equal(radiusIn(last()), 14); + // Hidden, it waits; shown, it catches up. + set.upsert([ring(false)]); + const lastShown = last(); + height = 3000; + frame(); + assert.equal(last(), lastShown, 'hidden: not rebuilt'); + set.upsert([ring(true)]); + frame(); + assert.equal(radiusIn(last()), 90); + assert.equal(scene.added[0], host, 'never a rebuild of the set'); + set.dispose(); + assert.equal(scene.added.length, 0); + })); + +test('radii by camera height that cross draw the longer as the major axis; past the cap of shapes drawn alone, the set rebuilds', () => + withTerrainHeights(() => { + const scene = fakeScene(); + let height = 1000; + Object.defineProperty(scene.camera, 'positionCartographic', { + get: () => ({ height }), + }); + const { draw, frame } = drawOver(scene); + const set = draw.shapes({ id: 'crossing' }); + const ring = (id, lon) => ({ + id, + geometry: { + kind: 'ellipse', + center: { lon, lat: 0 }, + semiMajor: { byCameraHeight: { factor: 0.03, min: 14, max: 170 } }, + semiMinor: { byCameraHeight: { factor: 0.05, min: 20, max: 100 } }, + rotation: 0.25, + }, + fill: [0.5, 0.9, 1, 0.38], + height: 'clampGround', + }); + const rings = Array.from({ length: MOVING_SHAPES + 4 }, (_, i) => + ring(`r${i}`, i * 0.1), + ); + assert.doesNotThrow(() => set.set(rings)); + const first = scene.added[0]; + const ground = (host) => { + for (let i = 0; i < host.length; i++) + if (host.get(i) instanceof Cesium.GroundPrimitive) return host.get(i); + return null; + }; + const geometry = ground(first).geometryInstances[0].geometry; + assert.equal(geometry._semiMajorAxis, 50, 'the longer, 5% of 1000 m'); + assert.equal(geometry._semiMinorAxis, 30); + assert.ok(Math.abs(geometry._rotation - (0.25 + Math.PI / 2)) < 1e-12); + // Its batches built. + for (let i = 0; i < first.length; i++) + if (first.get(i) instanceof Cesium.GroundPrimitive) { + Object.defineProperty(first.get(i), 'ready', { value: true }); + first.get(i).getGeometryInstanceAttributes = () => ({ + show: new Uint8Array([1]), + }); + } + frame(); + // The camera climbs: no more than the cap are drawn alone; the set + // rebuilds for the rest, and nothing throws in the frame. + height = 1500; + assert.doesNotThrow(() => frame()); + let solo = 0; + for (let i = 0; i < first.length; i++) { + const p = first.get(i); + if (p instanceof Cesium.GroundPrimitive && p.asynchronous === false) + solo += 1; + } + assert.equal(solo, MOVING_SHAPES); + assert.notEqual(scene.added.at(-1), first, 'rebuilt for the rest'); + set.dispose(); + })); + +test('rings drawn alone by a host still retiring count toward the cap when the camera moves again', () => + withTerrainHeights(() => { + const scene = fakeScene(); + let height = 1000; + Object.defineProperty(scene.camera, 'positionCartographic', { + get: () => ({ height }), + }); + const { draw, frame } = drawOver(scene); + const set = draw.shapes({ id: 'climbing' }); + const radius = { byCameraHeight: { factor: 0.03, min: 14, max: 170 } }; + const rings = Array.from({ length: MOVING_SHAPES + 4 }, (_, i) => ({ + id: `r${i}`, + geometry: { + kind: 'ellipse', + center: { lon: i * 0.1, lat: 0 }, + semiMajor: radius, + semiMinor: radius, + }, + fill: [0.5, 0.9, 1, 0.38], + height: 'clampGround', + })); + const ready = (host) => { + for (let i = 0; i < host.length; i++) + if (host.get(i) instanceof Cesium.GroundPrimitive) { + Object.defineProperty(host.get(i), 'ready', { value: true }); + host.get(i).getGeometryInstanceAttributes = () => ({ + show: new Uint8Array([1]), + }); + } + }; + const solo = (host) => { + let n = 0; + for (let i = 0; i < host.length; i++) { + const p = host.get(i); + if (p instanceof Cesium.GroundPrimitive && p.asynchronous === false) + n += 1; + } + return n; + }; + set.set(rings); + const first = scene.added[0]; + ready(first); + frame(); + // A climb: the cap drawn alone, and a rebuild for the rest. + height = 1500; + frame(); + assert.equal(solo(first), MOVING_SHAPES); + const second = scene.added.at(-1); + assert.notEqual(second, first, 'rebuilding, the old host retiring'); + ready(second); + // Climbing on while the old host retires: its rings drawn alone still + // count, so none more are drawn alone. + height = 2500; + frame(); + assert.equal(solo(second), 0, 'nothing more drawn alone'); + set.dispose(); + })); + test('the earthquakes layer draws its discs as ground fills on a viewer of its own', async () => { const { createEarthquakesLayer } = await import('../../layers/earthquakes/index.js'); @@ -3543,6 +3724,66 @@ test('an aircraft layer draws its contacts as one GPU icon set moving on the del unbind(); } }); +test('an extruded shape that classifies its volume tints what it covers; its outline is the volume edges', () => { + const scene = fakeScene(); + const { draw } = drawOver(scene); + const set = draw.shapes({ id: 'volumes' }); + const ring = [ + { lon: 0, lat: 0, height: 100 }, + { lon: 0.001, lat: 0, height: 100 }, + { lon: 0.001, lat: 0.001, height: 100 }, + ]; + const volume = { + id: 'volume', + geometry: { kind: 'polygon', rings: [ring] }, + fill: [1, 0.7, 0.3, 0.45], + extrudeHeight: 220, + height: 'absolute', + classifyVolume: true, + }; + const cage = { + id: 'cage', + geometry: { kind: 'polygon', rings: [ring] }, + outline: [1, 0.7, 0.3, 0.32], + outlineOnly: true, + extrudeHeight: 220, + height: 'absolute', + }; + // A scene that cannot classify draws the volume itself. + set.set([volume]); + assert.ok(scene.added[0].get(0) instanceof Cesium.Primitive); + assert.ok(!(scene.added[0].get(0) instanceof Cesium.ClassificationPrimitive)); + scene.context = { stencilBuffer: true }; + set.set([volume, cage]); + const host = scene.added[0]; + const classified = host.get(0); + assert.ok(classified instanceof Cesium.ClassificationPrimitive); + assert.equal(classified.classificationType, Cesium.ClassificationType.BOTH); + const [instance] = [classified.geometryInstances].flat(); + assert.ok(instance.geometry instanceof Cesium.PolygonGeometry); + assert.deepEqual( + [instance.geometry._extrudedHeight, instance.geometry._height].sort( + (a, b) => a - b, + ), + [100, 220], + 'from its base to its extruded face', + ); + assert.equal(instance.id.id, 'volume'); + // The cage: the extruded outline, not a ring at its base. + const edges = host.get(1); + assert.ok(edges instanceof Cesium.Primitive); + assert.ok( + [edges.geometryInstances].flat()[0].geometry instanceof + Cesium.PolygonOutlineGeometry, + ); + // An image cannot classify. + assert.throws( + () => set.set([{ ...volume, fill: { image: 'a.png' } }]), + /classifies volumes with colours only/, + ); + set.dispose(); +}); + test('an unclamped shape filled with an image draws a textured primitive and frees its material with its host', () => withImageClasses(() => { const scene = fakeScene(); @@ -3927,19 +4168,19 @@ test('flow lines run their dashes toward the end, draped or not, on the frame cl asked = 0; frame(); assert.equal(asked, 0, 'an emptied set asks for none'); - // Arrows and patterns are not draped. + // Patterns are not draped. assert.throws( () => set.set([ { - id: 'arrow', + id: 'pattern', positions, widthPx: 1, mode: 'draped', - style: { kind: 'arrow', color: '#fff' }, + style: { kind: 'pattern', image: 'a.png', repeat: 2 }, }, ]), - /drapes solid, glow, dash and flow lines only/, + /drapes solid, glow, dash, flow and arrow lines only/, ); set.dispose(); })); @@ -4472,6 +4713,42 @@ test('draped glow and dash lines drape with their materials, each on a ground pr set.dispose(); })); +test('a draped arrow drapes its arrow material on a ground polyline of its own, recoloured in place', () => + withImageClasses(() => { + const { scene, draw } = drawOver(); + const set = draw.lines({ id: 'arrows' }); + const arrow = (color) => ({ + id: 'to', + positions: [ + { lon: 0, lat: 0 }, + { lon: 0.01, lat: 0.01 }, + ], + widthPx: 16, + mode: 'draped', + style: { kind: 'arrow', color }, + }); + set.set([arrow([0.5, 0.9, 1, 0.95])]); + const host = scene.added[0]; + const ground = host.get(1); + assert.ok(ground instanceof Cesium.GroundPolylinePrimitive); + assert.equal(ground.classificationType, Cesium.ClassificationType.BOTH); + assert.equal(ground.geometryInstances[0].geometry.width, 16); + const material = ground.appearance.material; + assert.equal(material.type, 'PolylineArrow'); + assert.ok( + Cesium.Color.equals( + material.uniforms.color, + new Cesium.Color(0.5, 0.9, 1, 0.95), + ), + ); + // Faded, it takes its new colour on the material it has. + set.upsert([arrow([0.5, 0.9, 1, 0.4])]); + assert.equal(scene.added[0], host, 'not rebuilt'); + assert.equal(ground.appearance.material, material); + assert.equal(material.uniforms.color.alpha, 0.4); + set.dispose(); + })); + test('a draped line drawn by its own material changes colour in place; a batched one rebuilds', () => withImageClasses(() => { const { scene, draw } = drawOver(); diff --git a/src/render/cesium/harness.js b/src/render/cesium/harness.js index 7b7c5e0d4..e725b1ef6 100644 --- a/src/render/cesium/harness.js +++ b/src/render/cesium/harness.js @@ -64,7 +64,9 @@ export const CESIUM_CHECKS = new Set([ 'draw.points.population', 'draw.lodGroup', 'draw.sets', + 'draw.shapes.classifyVolume', 'draw.shapes.drapedRotation', + 'draw.shapes.radiusByCameraHeight', 'effects.crossfade', 'effects.defineStyle', 'effects.screenModulation', diff --git a/src/render/conformance/checks/ports.js b/src/render/conformance/checks/ports.js index 258fc71df..36c6be2e6 100644 --- a/src/render/conformance/checks/ports.js +++ b/src/render/conformance/checks/ports.js @@ -1998,6 +1998,126 @@ export function portChecks() { ok(!mine(at(0)), 'gone with its set'); }, ), + check( + 'draw.shapes.radiusByCameraHeight', + 'a clamped ellipse with radii by camera height draws at the radius the camera height gives, held within its bounds, and follows the camera', + async (h, r) => { + const shapes = r.draw.shapes({ id: 'conf:rings' }); + const radius = { byCameraHeight: { factor: 0.1, min: 50, max: 600 } }; + shapes.set([ + { + id: 'ring', + geometry: { + kind: 'ellipse', + center: { lon: AUSTIN.lon, lat: AUSTIN.lat }, + semiMajor: radius, + semiMinor: radius, + }, + fill: [0.5, 0.9, 1, 0.6], + height: 'clampGround', + }, + ]); + // Metres east of the centre, at its latitude. + const east = (m) => + h.toEcef({ + lon: + AUSTIN.lon + + m / (111320 * Math.cos((AUSTIN.lat * Math.PI) / 180)), + lat: AUSTIN.lat, + }); + const covers = (m) => { + const s = r.query.project(east(m)); + return Boolean( + s && + r.query + .drillPick(s.x, s.y) + .some((hit) => hit.set === 'conf:rings' && hit.id === 'ring'), + ); + }; + const until = async (test) => { + for (let i = 0; i < 300; i++) { + await drawn(h, r, 1); + if (test()) return true; + } + return false; + }; + // 2000 m up: 200 m across its centre. + await overAustin(h, r, 2000); + ok(await until(() => covers(150)), 'at 2000 m it reaches 150 m'); + ok(!covers(260), 'and not 260 m'); + // 4000 m up: 400 m. + await overAustin(h, r, 4000); + ok( + await until(() => covers(300) && !covers(460)), + 'at 4000 m it reaches 300 m, not 460 m', + ); + // 20 km up: held at 600 m. + await overAustin(h, r, 20000); + ok( + await until(() => covers(550) && !covers(700)), + 'held at its largest', + ); + shapes.dispose(); + await drawn(h, r); + ok(!covers(0), 'gone with its set'); + }, + ), + check( + 'draw.shapes.classifyVolume', + 'an extruded shape that classifies its volume picks where it tints what it covers, and hides', + async (h, r) => { + await overAustin(h, r); + const shapes = r.draw.shapes({ id: 'conf:volume' }); + const d = 0.002; + const ring = [ + [-d, -d], + [d, -d], + [d, d], + [-d, d], + ].map(([dLon, dLat]) => ({ + lon: AUSTIN.lon + dLon, + lat: AUSTIN.lat + dLat, + height: -200, + })); + const volume = (extra = {}) => ({ + id: 'volume', + geometry: { kind: 'polygon', rings: [ring] }, + fill: [1, 0.7, 0.3, 0.45], + extrudeHeight: 300, + height: 'absolute', + classifyVolume: true, + ...extra, + }); + const mine = (dLon) => { + const s = r.query.project( + h.toEcef({ lon: AUSTIN.lon + dLon, lat: AUSTIN.lat }), + ); + return Boolean( + s && + r.query + .drillPick(s.x, s.y) + .some((hit) => hit.set === 'conf:volume' && hit.id === 'volume'), + ); + }; + const until = async (test) => { + for (let i = 0; i < 300; i++) { + await drawn(h, r, 1); + if (test()) return true; + } + return false; + }; + shapes.set([volume()]); + ok(await until(() => mine(0)), 'it picks inside'); + ok(!mine(0.008), 'and not outside'); + shapes.upsert([volume({ show: false })]); + ok(await until(() => !mine(0)), 'hidden'); + shapes.upsert([volume()]); + ok(await until(() => mine(0)), 'shown again'); + shapes.dispose(); + await drawn(h, r); + ok(!mine(0), 'gone with its set'); + }, + ), check( 'draw.lines.styles', 'flow lines draw draped and in space, and a line with a depth-fail colour moves every frame, without stopping the frame or picks', @@ -2069,7 +2189,7 @@ export function portChecks() { ), check( 'draw.lines.drape', - 'draped glow and dash lines draw and pick; a revealed line draws only its first part; a draped line and a clamped point that move every frame are drawn where they now are in the next frame', + 'draped glow, dash and arrow lines draw and pick; a revealed line draws only its first part; a draped line and a clamped point that move every frame are drawn where they now are in the next frame', async (h, r) => { await overAustin(h, r); const at = (dLon, dLat = 0) => @@ -2112,12 +2232,20 @@ export function portChecks() { style: { kind: 'solid', color: '#20e7f2' }, revealFraction: 0.5, }, + { + id: 'arrow', + positions: [at(-0.003, -0.004), at(0.003, -0.004)], + widthPx: 16, + mode: 'draped', + style: { kind: 'arrow', color: [0.5, 0.9, 1, 0.95] }, + }, ]); await drawn(h, r); await settled(r); await drawn(h, r); ok(mine(at(0, 0.002), 'glow'), 'a draped glow line picks'); ok(mine(at(0, -0.002), 'dash'), 'a draped dash line picks'); + ok(mine(at(-0.002, -0.004), 'arrow'), 'a draped arrow picks'); ok(mine(at(-0.0015), 'reveal'), 'revealed: its first half draws'); ok(!mine(at(0.0015), 'reveal'), 'revealed: its second half does not'); lines.upsert([ @@ -2191,7 +2319,7 @@ export function portChecks() { `moved, frame ${i}: not where it was`, ); } - equal(lines.size(), 4, 'every line held'); + equal(lines.size(), 5, 'every line held'); points.dispose(); lines.dispose(); }, diff --git a/src/render/stub/index.js b/src/render/stub/index.js index edfa96b1a..1dcf08426 100644 --- a/src/render/stub/index.js +++ b/src/render/stub/index.js @@ -710,6 +710,60 @@ export function createStubRenderer(options = {}) { ); } + /** The eye's height above the ellipsoid, for radii by camera height. */ + const eyeHeight = () => toCartographicRadians(eye().position)?.height ?? 0; + + /** + * Whether `lon`, `lat` (degrees) is in an ellipse geometry, its radii by + * camera height at the eye's height, measured in the plane tangent at its + * centre. + */ + function inEllipse(g, lon, lat) { + const height = eyeHeight(); + const radius = (r) => + typeof r === 'number' + ? r + : Math.max( + r.byCameraHeight.min, + Math.min(r.byCameraHeight.max, height * r.byCameraHeight.factor), + ); + const centre = toCartographicRadians(toEcef(g.center)); + const metresPerRadian = 6378137; + const east = + ((lon * Math.PI) / 180 - centre.lon) * + metresPerRadian * + Math.cos(centre.lat); + const north = ((lat * Math.PI) / 180 - centre.lat) * metresPerRadian; + // The semi-major axis is turned counter-clockwise from north. + const turn = g.rotation ?? 0; + const along = north * Math.cos(turn) - east * Math.sin(turn); + const across = north * Math.sin(turn) + east * Math.cos(turn); + return ( + (along / radius(g.semiMajor)) ** 2 + + (across / radius(g.semiMinor)) ** 2 <= + 1 + ); + } + + /** Whether `lon`, `lat` (degrees) is inside a ring of positions. */ + function inRing(ring, lon, lat) { + const points = ring.map((p) => { + const c = toCartographicRadians(toEcef(p)); + return [toDegrees(c.lon), toDegrees(c.lat)]; + }); + let inside = false; + for (let i = 0, j = points.length - 1; i < points.length; j = i++) { + const [xi, yi] = points[i]; + const [xj, yj] = points[j]; + if ( + yi > lat !== yj > lat && + lon < ((xj - xi) * (lat - yi)) / (yj - yi) + xi + ) + inside = !inside; + } + return inside; + } + /** * The pickable items under a pixel, nearest first. With a `depth`, only * the nearest `depth` things drawn there are looked through, unpickable @@ -745,18 +799,29 @@ export function createStubRenderer(options = {}) { continue; } if (set.kind === 'shapes') { - // Draped rectangles are picked where they cover the ellipsoid, turned - // as the default renderer turns them; other shapes are not picked. + // Draped rectangles and ellipses, and volumes that classify what + // they cover, are picked where they cover the ellipsoid (rectangles + // turned as the default renderer turns them); other shapes are not + // picked. const ground = rayEllipsoid(pickRay(x, y)); const at = ground && toCartographicRadians(ground); if (!at) continue; + const lon = toDegrees(at.lon); + const lat = toDegrees(at.lat); for (const item of set.items.values()) { if (item.show === false) continue; if (!item.fill || item.outlineOnly) continue; - if (item.height !== 'clampGround') continue; - if (item.geometry?.kind !== 'rectangle') continue; - if (!inRectangle(item.geometry, toDegrees(at.lon), toDegrees(at.lat))) - continue; + const g = item.geometry; + const covers = + item.height === 'clampGround' + ? (g?.kind === 'rectangle' && inRectangle(g, lon, lat)) || + (g?.kind === 'ellipse' && inEllipse(g, lon, lat)) + : item.classifyVolume === true && + item.extrudeHeight !== undefined && + g?.kind === 'polygon' && + inRing(g.rings[0], lon, lat) && + !g.rings.slice(1).some((hole) => inRing(hole, lon, lat)); + if (!covers) continue; hits.push({ set: setId, id: item.id, diff --git a/src/render/stub/stub.test.mjs b/src/render/stub/stub.test.mjs index 1b31f60c0..7dc783145 100644 --- a/src/render/stub/stub.test.mjs +++ b/src/render/stub/stub.test.mjs @@ -141,6 +141,40 @@ test('a draped rectangle across the antimeridian picks on both sides of it, turn r.destroy(); }); +test('an extruded volume that classifies picks inside its outer ring and not in its holes', () => { + const r = createStubRenderer(); + r.camera.setView({ + destination: { lon: 0, lat: 0, height: 20_000 }, + orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 }, + }); + const shapes = r.draw.shapes({ id: 'volume' }); + const square = (d) => + [ + [-d, -d], + [d, -d], + [d, d], + [-d, d], + ].map(([lon, lat]) => ({ lon, lat, height: -50 })); + shapes.set([ + { + id: 'v', + geometry: { kind: 'polygon', rings: [square(0.02), square(0.005)] }, + fill: '#f80', + extrudeHeight: 100, + height: 'absolute', + classifyVolume: true, + }, + ]); + const picked = (lon, lat) => { + const s = r.query.project(toEcef({ lon, lat, height: 0 })); + return r.query.drillPick(s.x, s.y).some((hit) => hit.set === 'volume'); + }; + assert.ok(picked(0.012, 0), 'between its rings'); + assert.ok(!picked(0, 0), 'not in its hole'); + assert.ok(!picked(0.03, 0), 'not outside'); + r.destroy(); +}); + test('the stub says where it draws an item, for a camera that is not its own', () => { const r = createStubRenderer(); const t0 = r.frame.time();