Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions src/lib/arrow-legend.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/**
* Colours and stroke weights for drawing the arrow and barb shapes in a
* legend, taken from the styles the map draws them with so the legend cannot
* drift away from the map.
*/
import {
ARROW_LATTICE,
type ArrowStyle,
BARB_LATTICE,
TILE_PX
} from '@openmeteo/weather-map-layer';

import { SHAPE_UNITS } from '$lib/arrow-shapes';
import { BARB_OPACITY_RANGE, arrowLevelFor, defaultArrowStyle } from '$lib/chart-styles';
import { alphaOfCssColor, rescaleInto } from '$lib/color';
import { BARB_LINE_WIDTH } from '$lib/om-layer-defs';

/**
* On-screen size of one lattice cell at an integer zoom, which is the size a
* shape is drawn to fill in the tile.
*/
const cellPx = (style: ArrowStyle): number =>
TILE_PX / (style === 'barb' ? BARB_LATTICE : ARROW_LATTICE);

/**
* Stroke width in shape units, i.e. what a legend drawing the shape at
* `SHAPE_UNITS` needs to match the line the map draws at `sizePx`.
*/
const strokeUnits = (lineWidth: number, sizePx: number): number =>
(lineWidth * SHAPE_UNITS) / sizePx;

const levels = () => [...defaultArrowStyle.levels].sort((a, b) => a.minSpeed - b.minSpeed);

const levelFor = (speed: number) => arrowLevelFor(defaultArrowStyle, speed);

const arrowColor = (speed: number, dark: boolean): string => {
const level = levelFor(speed);
return dark ? level.darkColor : level.lightColor;
};

const barbColor = (speed: number, dark: boolean): string => {
const alphas = levels().map((level) =>
alphaOfCssColor(dark ? level.darkColor : level.lightColor)
);
const level = levelFor(speed);
const alpha = alphaOfCssColor(dark ? level.darkColor : level.lightColor);
const rgb = dark ? '255,255,255' : '0,0,0';
return `rgba(${rgb},${rescaleInto(alpha, alphas, BARB_OPACITY_RANGE).toFixed(3)})`;
};

/** Colour the map draws a shape in, for legends: the opacity ramps included. */
export const shapeColor = (style: ArrowStyle, speed: number, dark: boolean): string =>
style === 'barb' ? barbColor(speed, dark) : arrowColor(speed, dark);

/** Stroke a legend should use for a shape, matching the map's own weight. */
export const shapeStrokeUnits = (style: ArrowStyle, speed: number): number =>
style === 'barb'
? strokeUnits(BARB_LINE_WIDTH, cellPx('barb'))
: strokeUnits(levelFor(speed).width, cellPx('arrow'));
134 changes: 134 additions & 0 deletions src/lib/arrow-shapes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
/**
* The arrow and wind-barb shapes, as polylines in a 100-unit box, mirroring
* the geometry `generateArrows` and `generateWindBarbs` write into vector
* tiles. Kept here so the sprites drawn for the icon renderer, and the
* previews in the settings pane, come from one description of the shape.
*
* Both shapes point up (north) at rest and are rotated by the renderer.
*/

/** Viewbox units per shape, i.e. `size` in the tile generators. */
export const SHAPE_UNITS = 100;

export const MS_TO_KNOTS = 1.9438445;

// ── Arrow, from `generateArrows` ────────────────────────────────────────

/** Head half-width and depth, as fractions of `size` in the generator. */
const HEAD_HALF = 13;
const HEAD_DEPTH = 22;

/** Total arrow length per speed (m/s), the generator's own steps. */
export const arrowLength = (speed: number): number => {
if (speed < 1) return 0.5;
if (speed < 2) return 0.55;
if (speed < 3) return 0.6;
if (speed < 5) return 0.7;
if (speed < 10) return 0.75;
if (speed < 20) return 0.8;
return 0.85;
};

/** Arrow pointing where the flow goes, as polylines in the box. */
export const arrowShape = (speed: number): number[][][] => {
const centre = SHAPE_UNITS / 2;
const half = (arrowLength(speed) * SHAPE_UNITS) / 2;
const barb = HEAD_DEPTH - half;
return [
[
[centre, centre + half],
[centre, centre - half]
],
[
[centre - HEAD_HALF, centre + barb],
[centre, centre - half],
[centre + HEAD_HALF, centre + barb]
]
];
};

// ── Wind barb, from `generateWindBarbs` ─────────────────────────────────

const CIRCLE_KNOTS = 0.5;
const STAFF_HALF = 0.42;
const SLOT_STEP = 0.16;
const BARB_SPAN = 0.64;
const BARB_LENGTH = 0.26;
const BARB_LEAN = 0.13;
const CALM_RADIUS = 0.21;
const CALM_INNER_RADIUS = 0.14;
const CELL_BUDGET = 0.47;
const FIT = Math.min(1, CELL_BUDGET / Math.hypot(STAFF_HALF + BARB_LEAN, BARB_LENGTH));

/** Pennants, full barbs and half barbs for a speed, rounded to 5 kt. */
export const barbCounts = (knots: number): { pennants: number; full: number; half: number } => {
let remaining = Math.round(knots / 5) * 5;
const pennants = Math.floor(remaining / 50);
remaining -= pennants * 50;
const full = Math.floor(remaining / 10);
remaining -= full * 10;
return { pennants, full, half: remaining >= 5 ? 1 : 0 };
};

export interface BarbShape {
/** Staff, barbs and calm rings. */
lines: number[][][];
/** Pennant triangles, drawn solid. */
pennants: number[][][];
}

/** Wind barb with its staff pointing into the wind, as polylines in the box. */
export const barbShape = (knots: number): BarbShape => {
const centre = SHAPE_UNITS / 2;
const at = (across: number, along: number): number[] => [
centre + across * FIT * SHAPE_UNITS,
centre + along * FIT * SHAPE_UNITS
];

const lines: number[][][] = [];
const pennants: number[][][] = [];

if (knots < CIRCLE_KNOTS) {
const corners = 12;
for (const radius of [CALM_RADIUS, CALM_INNER_RADIUS]) {
const ring: number[][] = [];
for (let i = 0; i <= corners; i++) {
const angle = (i / corners) * 2 * Math.PI;
ring.push(at(radius * Math.sin(angle), radius * Math.cos(angle)));
}
lines.push(ring);
}
return { lines, pennants };
}

lines.push([at(0, STAFF_HALF), at(0, -STAFF_HALF)]);

const counts = barbCounts(knots);
const lonely = counts.half === 1 && counts.pennants === 0 && counts.full === 0;
const slots = counts.pennants * 2 + counts.full + counts.half + (lonely ? 1 : 0);
const step = Math.min(SLOT_STEP, BARB_SPAN / Math.max(1, slots));

let along = -STAFF_HALF + (lonely ? step : 0);
for (let i = 0; i < counts.pennants; i++) {
pennants.push([at(0, along), at(BARB_LENGTH, along - BARB_LEAN), at(0, along + 2 * step)]);
along += 2 * step;
}
for (let i = 0; i < counts.full; i++) {
lines.push([at(0, along), at(BARB_LENGTH, along - BARB_LEAN)]);
along += step;
}
if (counts.half) {
lines.push([at(0, along), at(BARB_LENGTH / 2, along - BARB_LEAN / 2)]);
}

return { lines, pennants };
};

/** An SVG path for a shape's polylines, for previews outside the map. */
export const shapePath = (polylines: number[][][]): string =>
polylines
.map(
(line) =>
'M' + line.map(([x, y]) => `${Number(x.toFixed(1))} ${Number(y.toFixed(1))}`).join('L')
)
.join('');
9 changes: 5 additions & 4 deletions src/lib/chart-presets.ts
Comment thread
vincentvdwal marked this conversation as resolved.
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export const chartPresets: ChartPreset[] = [
contours: true,
contourInterval: 12.5
},
{ variable: 'pressure_msl', contours: true, contourInterval: 5 }
{ variable: 'pressure_msl', contours: true, contourInterval: 2 }
]
},
{
Expand Down Expand Up @@ -191,7 +191,7 @@ export const chartPresets: ChartPreset[] = [
group: 'Precipitation',
sources: [
{ variable: 'precipitation', raster: true },
{ variable: 'pressure_msl', contours: true, contourInterval: 5 }
{ variable: 'pressure_msl', contours: true, contourInterval: 2 }
]
},
{
Expand All @@ -201,7 +201,7 @@ export const chartPresets: ChartPreset[] = [
group: 'Precipitation',
sources: [
{ variable: 'snowfall', raster: true },
{ variable: 'pressure_msl', contours: true, contourInterval: 5 }
{ variable: 'pressure_msl', contours: true, contourInterval: 2 }
]
},
{
Expand All @@ -211,7 +211,7 @@ export const chartPresets: ChartPreset[] = [
group: 'Precipitation',
sources: [
{ variable: 'freezing_level_height', raster: true },
{ variable: 'pressure_msl', contours: true, contourInterval: 5 }
{ variable: 'pressure_msl', contours: true, contourInterval: 2 }
]
},
{
Expand Down Expand Up @@ -286,6 +286,7 @@ export const popularVariables: PopularVariable[] = [
{ id: 'nitrogen_dioxide' },
{ id: 'dust' },
{ id: 'uv_index' },

// Marine domains (ecmwf_wam*, dwd_*wam, ncep_gfswave*, meteofrance_wave)
{ id: 'wave_height' },
{ id: 'wave_period' },
Expand Down
46 changes: 46 additions & 0 deletions src/lib/chart-styles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
* properties (line color, width). The defaults match the original
* hardcoded MapLibre expressions.
*/
import { alphaOfCssColor, rescaleInto } from '$lib/color';

import type * as maplibregl from 'maplibre-gl';

// ── Contour styles ──────────────────────────────────────────────────────
Expand Down Expand Up @@ -204,6 +206,50 @@ export function buildArrowColorExpr(
return expr;
}

/**
* The level a speed falls in, matching how the expressions below cascade:
* the highest level whose threshold the speed is past.
*/
export function arrowLevelFor(style: ArrowStyle, speed: number): ArrowLevel {
const sorted = [...style.levels].sort((a, b) => a.minSpeed - b.minSpeed);
let level = sorted[0];
for (const candidate of sorted) if (speed > candidate.minSpeed) level = candidate;
return level;
}

/**
* Opacity range wind barbs are drawn over. They follow the arrow ramp's
* progression, but a barb already spells its speed out in pennants and barbs,
* so fading a slow one to the arrows' 0.2 only makes it unreadable.
*/
export const BARB_OPACITY_RANGE: [min: number, max: number] = [0.45, 0.85];

/**
* Build a barb line-color expression: the arrow ramp's speed thresholds, in
* plain black or white at the shallower barb opacities.
*/
export function buildBarbColorExpr(
style: ArrowStyle,
dark: boolean
): maplibregl.ExpressionSpecification {
const sorted = [...style.levels].sort((a, b) => a.minSpeed - b.minSpeed);
const alphas = sorted.map((level) => alphaOfCssColor(dark ? level.darkColor : level.lightColor));
const rgb = dark ? '255,255,255' : '0,0,0';
const color = (i: number): string =>
`rgba(${rgb},${rescaleInto(alphas[i], alphas, BARB_OPACITY_RANGE).toFixed(3)})`;

let expr: maplibregl.ExpressionSpecification = ['literal', color(0)];
for (let i = 1; i < sorted.length; i++) {
expr = [
'case',
['boolean', ['>', ['to-number', ['get', 'value']], sorted[i].minSpeed], false],
color(i),
expr
];
}
return expr;
}

/** Build an arrow line-width expression from an ArrowStyle. */
export function buildArrowWidthExpr(style: ArrowStyle): maplibregl.ExpressionSpecification {
const sorted = [...style.levels].sort((a, b) => a.minSpeed - b.minSpeed);
Expand Down
17 changes: 17 additions & 0 deletions src/lib/color.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,23 @@ export function getAlpha(rgba: number[]): number {
return rgba[3] ?? 1;
}

/** Alpha of an `rgb()`/`rgba()` string; 1 when it carries none. */
export function alphaOfCssColor(color: string): number {
const parts = color.slice(color.indexOf('(') + 1, color.lastIndexOf(')')).split(',');
return parts.length > 3 ? Number(parts[3]) : 1;
}

/**
* Rescale `value` from the span of `values` into `range`, keeping its relative
* position. Used to reuse a colour ramp's progression at another intensity.
*/
export function rescaleInto(value: number, values: number[], [min, max]: [number, number]): number {
const weakest = Math.min(...values);
const strongest = Math.max(...values);
const t = strongest === weakest ? 1 : (value - weakest) / (strongest - weakest);
return min + t * (max - min);
}

export function alphaToPercent(alpha: number): number {
return Math.round(alpha * 100);
}
Expand Down
4 changes: 3 additions & 1 deletion src/lib/components/help/help-dialog.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -431,7 +431,9 @@
</div>
<b>Grid</b> - Show individual model grid points as orange dots on map
<div>
<b>Arrows</b> - Show directional arrows on maps with speed and direction (wind / wave)
<b>Arrows</b> - Show directional arrows on maps with speed and direction (wind / wave). Switch
the style to wind barbs to read the speed off the staff: half barb 5 knots, full barb 10,
pennant 50.
</div>
<div><b>Contours</b> - Show contour lines between certain thresholds</div>
<div>
Expand Down
2 changes: 1 addition & 1 deletion src/lib/components/scale/color-picker.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@

<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="color-picker-content absolute left-full bottom-0 ml-2 bg-glass backdrop-blur-sm border border-border rounded-lg shadow-xl p-3 w-60"
class="color-picker-content absolute left-full bottom-0 z-50 ml-2 bg-glass backdrop-blur-sm border border-border rounded-lg shadow-xl p-3 w-60"
onclick={(e) => e.stopPropagation()}
onkeydown={(e) => e.key === 'Escape' && onclose()}
>
Expand Down
29 changes: 19 additions & 10 deletions src/lib/components/scale/scale-legend.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,12 @@
const totalHeight = $derived(colorBlockHeight * labeledColors.length);
</script>

<div class="relative flex items-end gap-0.5 select-none" style="max-height: {totalHeight + 100}px;">
<!-- Lifted while editing: legends are siblings at z-auto, so the picker of one
legend would otherwise paint under the legends after it -->
<div
class="relative flex items-end gap-0.5 select-none {editingIndex !== null ? 'z-50' : ''}"
style="max-height: {totalHeight + 100}px;"
>
<div class="flex flex-col-reverse rounded shadow-md">
<div class="flex flex-col-reverse bg-glass/30 backdrop-blur-sm rounded-b">
{#each labeledColors as lc, i (lc.index)}
Expand All @@ -148,15 +153,6 @@
.color[2]}); opacity: {(alphaValue * $opacity) / 100};"
></div>
</button>
<!-- Color Picker Popover -->
{#if editingIndex === i}
<ColorPicker
color={rgbaToHex(lc.color)}
alpha={alphaValue}
onchange={handleColorChange}
onclose={closePicker}
/>
{/if}
{/each}
</div>

Expand Down Expand Up @@ -233,4 +229,17 @@
{/each}
</div>
{/if}

<!-- Color picker popover. A child of the legend root, not of the colour
column: that column's backdrop blur traps its descendants in a stacking
context, under the value labels and the legends beside it. -->
{#if editingIndex !== null && labeledColors[editingIndex]}
{@const editing = labeledColors[editingIndex]}
<ColorPicker
color={rgbaToHex(editing.color)}
alpha={getAlpha(editing.color)}
onchange={handleColorChange}
onclose={closePicker}
/>
{/if}
</div>
Loading
Loading