A fallout simulator on the map: nuclear mode, targets, live winds aloft (#1007)

* A fallout model, checked against six Nevada tests

The local fallout of a surface burst lands where layered winds carry particles of every size
from the stabilized cloud.  Cloud and particle sizes come from DNAF-1, WSEG-10 and DELFIC;
the air is the 1976 standard atmosphere.  The six shots' wind profiles, measured contour
areas and plume bearings are in nts-shots.json with their sources, alongside HPAC's
predictions of the same contours.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* A prototype fallout panel on the map

Right-click "Simulate Fallout Here" draws the dose rate at H+1 of one surface burst, in one
wind or in the winds aloft of one of the six Nevada tests.  Nothing is saved.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Fallout lands where it meets the ground

A particle stops falling at the first level where it is at or below the ground under it, not
at a plane at the height of ground zero: early on a ridge in its way, later in a valley.  The
map panel reads the ground from the terrain files the user has downloaded; the Nevada tests
are checked against a small elevation grid of Mapterhorn terrain, as WROLPi publishes it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Fallout falls from the cloud's cap, skirt and stem

The cloud of a surface burst holds 77.5% of its activity in the cap, 15% in a skirt below it
and 7.5% in the stem (Philippe et al.); the stem starts as narrow as the early fireball at the
ground and widens up to the cap (DNAF-1).  More of the fallout lands near ground zero: a 1 Mt
burst now draws a 1000 R/hr contour.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Close-in fallout measured after three Nevada surface bursts

Jangle Sugar, Small Boy and Johnie Boy, from DNAF-1's Table 3: the area, hotline length and
azimuth of each contour from 35 to 1000 R/hr, as observed and as DNAF-1, DELFIC and WSEG-10
predicted them, with each shot's winds.  The deposition grid can look closely at part of the
fallout, and measures hotlines.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Fallout rises with the cloud, and heavy particles drop out low

All of the activity starts in the early fireball and rises with the cloud, whose base and top
climb with the square root of time (SIMFIC).  Each particle rises with the air less its own
settling speed, so a heavy one leaves the cloud low and early and lands near ground zero, and a
light one rides to the top.  A burst above the ground puts down less, by its scaled height.

Against the close-in fallout of Jangle Sugar and Small Boy this is within 2.4x in area and 1.7x
in hotline length (it was 100x short); across the six Nevada tests, 4.2x a priori (it was 8.9x).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The fallout panel offers the weapons in service today

Weapons deployed or stockpiled by each country, each with its yield quoted from the 2025-2026
Nuclear Notebook or SIPRI Yearbook, and the improvised devices FEMA plans for; no retired or
historical weapons, and none whose yield no source gives.  Variable-yield weapons have one entry
for each published setting.  Fission shares are not public; they are assumed as Glasstone and
Dolan plan for, and the user may change them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The fallout panel's dropdowns open above it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* A variable-yield weapon is named once, with each setting's yield beside it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The fallout panel uses the forecast winds aloft

WROLPi fetches, on request, Open-Meteo's hourly forecast of the wind at nineteen pressure levels
(about 100 m to 24 km) and the rain, for the whole degree around the burst: the place is rounded
before it is sent.  The forecast is kept, so the panel can use it offline.  The panel picks the
hour nearest now, gives the forecast's age, and warns of rain, which brings fallout down in places
the map does not show.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* A nuclear mode on the map: targets, and fallout

A radiation button under the print button turns nuclear mode on and off.  In it, targets (likely
detonation sites) are shown alongside the pins, a pin added is saved as a target, and fallout can
be simulated at a target or anywhere on the map.  A pin's kind is kept in map_pins.yaml; a pin
without one is a plain pin, as every pin was.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Targets keep their weapon, and nuclear mode shows the fallout of all of them

A target keeps the weapon chosen for it (or a yield of the user's own) and its fission share in
map_pins.yaml.  Nuclear mode opens on the fallout of every saved target at once, in the forecast
winds aloft fetched most recently; a burst tried out from the map can be saved as a target.

A whole-degree latitude or longitude, which a browser sends as an integer, is a valid pin, and a
pin's label and color may be left out of an update.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* An improvised device is named once, with each yield beside it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Fallout of many targets is calculated in seconds, and shown as it goes

A particle size's settling speed is read from a table by altitude rather than solved again for
every fall of every burst (a burst: 40 ms to 6 ms).  The view yields to the page only every 40 ms,
through a message channel, which a browser does not hold back in a hidden tab as it does timers;
it says how far it has got, and draws the fallout on flat ground while the terrain is read.

A target in the list shows its weapon, and is given a weapon picker when asked; one picker sets
every target's weapon.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The fallout grid covers where fallout shows, not past the poles

The faintest particles of a burst are carried thousands of km in two days; with many targets the
grid stretched past 90 degrees and the map refused the image ("Invalid LngLat latitude").  The grid
now covers the spots which can reach the faintest band drawn, the image's corners stay within
Web Mercator's 85 degrees, and so does the area whose terrain is read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Fallout across a continent is drawn where it lands

The map stretches an image evenly in Web Mercator between its corners, but the fallout grid's rows
are evenly apart in latitude; over tens of degrees (targets across a country) they part ways, and
the southern part of the image was drawn far from its targets.  Each image row now takes the grid
row at its own latitude.  A burst far from the first target keeps its plume as wide, east to west,
as at its own latitude.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Terrain across the antimeridian, and ground with no number, do not break the fallout

Targets in Alaska and Hawaii carry fallout west of 180 degrees, where the terrain's tile arithmetic
read past the tile's pixels; one sample with no number made every target's lowest ground NaN and
every spot fall off the map, and the grid's size Infinity.  Longitudes wrap, a sample with no number
is left out (of the lowest ground, and of the elevation between samples), and a spot not on the map
is left out of the grid rather than breaking it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Every target's weapon is set in one change

Setting it target by target, eight at once, lost most of the changes: each request wrote the whole
pin list, undoing the others (QA: 47 of 156 changed).  PUT /api/map/pins/targets/weapon gives
every target the weapon in one change of the config.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The every-target weapon picker starts empty and always applies

It showed the first target's weapon, so choosing that weapon for all of them did nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Fallout is carried by the winds where it is, region by region

A field of forecasts on a grid over the targets replaces the one forecast for
all of them. Each particle rises and falls through the wind at its place,
height and hour, read between the surrounding grid points, hours and heights.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The winds aloft are fetched as a Job, ninety places a minute

The free forecast service allows 600 calls a minute and a place costs six, so
a field of up to 540 points is fetched in paced batches by a Job, which the
fallout panel follows, instead of inside one request.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* A small burst's hot fallout is kept on a grid over many, and the panel says what it shows

- Each burst's narrow close-in fallout is also put on a fine grid, so the
  lethal zone of a small target is not averaged away in the cells kilometers
  wide of a grid over targets far apart.
- The legend says the dose rate is as at one hour, with all the fallout down,
  and what R/hr is; the error quoted is the unscaled model's.
- The TNA's yield is 150 kt: its source gives only an upper bound below 300.
- Weapons show their fission share beside their yield.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The fallout can be watched landing, hour by hour

A timeline under the legend plays, or steps through, the 48 hours after the
bursts: each hour shows only the fallout which has landed by then, at its
dose rate then (t^-1.2 from H+1), on the same cells as the whole of it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The map can show the total dose of someone outdoors, hour by hour

A "Show" picker switches from the dose rate to the total dose (R) someone
outdoors gets from when the fallout arrives: t^-1.2 added up from each spot's
arrival to the hour on the timeline, or over the first two weeks. Its bands
say what each dose does to a person.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The model is checked against the Army's fallout manuals

- FM 3-3-1's worked decay and dose problems are tests.
- FM 3-11.3's cloud and Zone I nomograms, read from their images, are a
  fixture; the model's cloud top is within 10% of them from 1 kt to 10 Mt,
  and its Zone I within 0.7-1.7 times from 10 kt to 1 Mt, the yields of
  modern weapons, which the test shots do not reach.
- The legend says real fallout may decay faster or slower than usual.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The model is checked against two megaton bursts in the Pacific

Redwing Zuni (3.5 Mt), whose winds were measured above its cloud: the hot
fallout goes where it went and about as far. Castle Bravo (15 Mt), whose
winds were measured only below its cloud: its fallout arrives when it did,
and its hot fallout reaching a third as far is kept in view as a known gap.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Winds are read from the right points at every spacing, and cover the landing

- A field's points were filed by rounding (lat + 90) / spacing but looked up
  by flooring it: at 4 and 8 degrees, which do not divide 90, every point read
  half its neighbor's wind. Both now count whole spacings from the equator.
- The forecast starts at midnight UTC, so two days could end before the
  fallout of a burst this hour was down; three are fetched (the same call
  weight), and the panel says when the last hour's winds are held.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Bravo's known gap is not its unmeasured upper winds

Reanalysis winds above the 1954 sounding turn the plume to within 10 degrees
of the measured one but do not lengthen its hot contours; the fixture's caveat
and the test's explanation said otherwise, and now say what was found.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Rain takes fallout out of the air where it falls

A falling particle in rain loses a share of its activity every step: fast
inside the rain cloud ("rainout"), slower below it, by how hard it rains
("washout"), at Glasstone and Dolan's rates (Tables 9.74a and b), and none
above it. What is taken out comes down where the particle was. The forecast
now asks for relative humidity at 14 levels, and each hour's rain cloud is
taken as HYSPLIT takes it: from the lowest level 80% humid to the first above
it less than 60%.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* With no forecast, the fallout of 30 past days of the month

- wrolpi/scripts/build_fallout_climatology.py builds, from NOAA's reanalysis,
  the winds aloft of 30 days of each month (one from each year 1991-2020) over
  the whole world: a gzip file a month, about 4 MB, for the release download
  location.
- WROLPi fetches the months it lacks once, while there is the Internet, each
  checked against a sha256 pinned in modules/map/climatology.py (none pinned
  until the files are published), and serves them to the panel.
- The panel's "Past days of a month" wind runs the bursts in each day and shows
  on what share of the days each place had the chosen dose rate; it is chosen
  for us when there is no forecast, or it has run out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The climatology's months are published, and their sha256 pinned

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The climatology worker waits for the Internet and the drive on startup

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Counting the past days says flat ground at once, not the forecast's terrain

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Past days' fallout reuses each yield's paths, about 10 times faster

On flat ground in a day's held winds, how each parcel rises with the cloud
and falls does not depend on the wind, so it is worked out once per yield
and kept for every burst and day.  The rising cloud is carried by the winds
over ground zero (it drifts about 10 km); the fall still reads the winds
where the particle is.  A field of one hour is read without its hours, and
the nearest point to a cell past the field is kept.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The rising cloud reads the winds over ground zero from arrays, by level

Each parcel's rise is kept as the levels of the column it passes through
(steps in the same level as one) and their seconds, so a burst reads the
column once and sums.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The fallout panel shows a progress bar while it calculates

At the top of the panel, filled as far as the bursts are done, or moving
without a count until there is one.  A calculation stopped by removing the
last target no longer leaves the panel busy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Past days' fallout runs in Web Workers, with a Cancel button

The days are spread over workers, one for each core but one (left for the
page), at most 6, and at most 2 where the browser says it has 2 GB or less.
A worker is given the next day as it finishes one, and sends back only the
cells reached.  Where workers cannot be made, or fail, the days are
calculated on the page as before.

The days are counted on cells as wide as the coarsest day's grid, so the
count does not depend on which day finishes first.

Cancel, beside the progress bar, stops a calculation (and its workers) at
once; Calculate starts it again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The forecast's bursts are spread over Web Workers too

The workers now take any task: a past day, or a burst.  The page and the
workers build each burst's winds and terrain with the same functions
(work.js), so the fallout is the same either way; the flat pass and the
terrain pass each run on their own workers, and Cancel stops them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The bursts' grid is made in parts by the Web Workers

The grid is a sum over the bursts' spots, sharpened by the most any burst
raises a cell, so it is made in a fixed number of parts (a burst's spots
in one) on one frame, and joined on the page.  The page makes the same
parts when there are no workers, so the grid is the same either way.

The forecast's warnings (bursts outside the winds, rain) are no longer
worked out again on every progress update.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The forecast's hours are labeled once an hour, not on every progress update

Writing each hour's label (toLocaleString) took most of the page's time
while the workers calculated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Faster forecast fallout: the nearest point outside the field, progress, and what workers are sent

- Outside the forecast's field, the nearest point is looked for only
  among the points which can be nearest somewhere in the grid cell (kept
  for each cell); the same point as looking through them all.  Longitudes
  are wrapped however far round the world a particle is carried.
- The progress is shown at most ten times a second.
- The workers are sent the forecast's arrays, not the forecast as fetched.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The fallout panel in steps: the targets, then the fallout hour by hour or in total

Nuclear mode opens on the targets; nothing is calculated until the user goes on.
The winds and terrain wait under Options, with what is used said beside it.
The timeline runs from the first hour to two weeks, saying how much the fallout
has weakened since H+1; the view of all the fallout as if landed at H+1 is gone.
Going back and on again with nothing changed draws what was calculated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The fallout panel's winds: the forecast, past days, or one wind; no test shots' winds

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The fallout panel's wind is a step of its own, between the targets and the fallout

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The fallout panel says it is an estimate; how it compares with the test bursts goes in the help

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Targets are tried out until saved; the saved ones are loaded first, and saved all at once

Nuclear mode starts with no targets.  Targets added are tried out, and the saved
targets join them when the user loads them.  Saving replaces the saved targets
with the list, in one change, and is refused until they were loaded (or there are
none), so none are lost unseen.  A target can be taken out of the list.  The
burst tried out from the map's menu is gone: a target tried out does the same.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Nuclear targets are kept in their own config, map_nuclear.yaml, and listed apart from the pins

The pins are plain pins again.  The targets have their own endpoints, and their
own table on the Pins tab, where one can be deleted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The rest of keeping nuclear targets in map_nuclear.yaml: the config, its endpoints, and the table

The commit before this one was missing these files.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The fallout panel's wind is the forecast when it has the winds until the fallout is down, else one wind

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The weather is a subscription: a forecast around the saved targets, downloaded every day

The Open-Meteo fetch is a recurring Download (daily) instead of a Job the panel
starts.  The Manage tab has a Weather section: turning it on or off, what it
downloads, how its downloads went, and the forecast kept.  Only the newest
forecast is kept, and it covers four days.  The wind step asks the user to turn
the download on, and warns, there and beside the fallout, when the forecast runs
out before the fallout is down.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The forecast service may take three minutes to answer, and a timeout says so

A batch of four days' forecasts took 43 seconds, near the old 60-second limit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The fallout panel's targets step has an Add a target button: the next click on the map places it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
lrnselfreliance 2026-11-25 12:01:13 -07:00 • committed by Roland
parent 72b507116e
commit d4d288f84a
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
50 changed files with 8663 additions and 38 deletions

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,736 @@
import {WEAPON_CHOICES} from './FalloutPanel';
import {serveFallout} from '../map-shared/fallout/work.js';
import {loadTerrainGrid} from './falloutTerrain';
// No terrain files under Jest, until a test gives a grid.
jest.mock('./falloutTerrain', () => ({loadTerrainGrid: jest.fn(async () => null)}));
// No forecast (unless a test gives one), past days or fetches under Jest.
let mockLatestWinds = null;
let mockWeather = {enabled: true, download: {status: 'complete'}, targets: 1, spacing: 1, points: 160, seconds: 61,
field: null};
const mockWeatherSet = [];
jest.mock('../api', () => ({
getFalloutClimatology: async () => null,
getFalloutClimatologyMonth: async () => null,
getWeather: async () => mockWeather,
setWeatherSubscription: (enabled) => {
mockWeatherSet.push(enabled);
return Promise.resolve({...mockWeather, enabled});
},
downloadWeatherNow: async () => mockWeather,
getLatestFalloutWinds: async () => mockLatestWinds,
}));
// Fallout workers serving their tasks (as fallout.worker.js does) here, as a browser's would on
// another thread: messages arrive later, copied. `made` are those made since it was emptied.
const made = [];
const copy = (v) => {
if (v instanceof ArrayBuffer) return v.slice(0);
if (ArrayBuffer.isView(v)) return v.slice();
if (Array.isArray(v)) return v.map(copy);
if (v && typeof v === 'object') return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, copy(x)]));
return v;
};
function worker({fail = false} = {}) {
const scope = {postMessage: (data) => setTimeout(() => !w.terminated && w.onmessage?.({data}), 0)};
serveFallout(scope);
const w = {
terminated: false, onmessage: null, onerror: null, given: [], kind: null,
postMessage(data) {
if (data.type === 'start') {
w.kind = data.kind;
w.start = data;
}
if (data.type === 'task') w.given.push(data.k);
const copied = copy(data);
setTimeout(() => {
if (w.terminated) return;
if (fail && data.type === 'task') w.onerror?.({message: 'No such script'});
else scope.onmessage({data: copied});
}, 0);
},
terminate() {
w.terminated = true;
},
};
made.push(w);
return w;
}
describe('the fallout panel\'s weapons', () => {
test('are grouped by country, then a yield of one\'s own', () => {
const groups = WEAPON_CHOICES.map((g) => g.group);
expect(groups[0]).toBe('United States');
expect(groups).toContain('Russia');
expect(groups).toContain('Improvised nuclear device');
expect(groups[groups.length - 1]).toBe('Other');
expect(WEAPON_CHOICES[groups.length - 1].items.map((i) => i.value)).toEqual(['custom']);
});
test('each read differently, by name and yield', () => {
const labels = WEAPON_CHOICES.flatMap((g) => g.items.map((i) => i.label));
expect(new Set(labels).size).toBe(labels.length);
expect(labels).toContain('B61-12 bomb, 0.3 kt, half fission');
});
test('say their yield', () => {
const w88 = WEAPON_CHOICES[0].items.find((i) => i.value === 'w88');
expect(w88.label).toBe('W88 (Trident II D5), 455 kt, half fission');
});
});
describe('the fallout panel\'s winds', () => {
const {windProfile, hourLabel} = require('./FalloutPanel');
test('fall back to one wind at every height until there is a forecast', () => {
const profile = windProfile({direction: 270, speed: 10});
expect(profile).toHaveLength(1);
expect(profile[0][1]).toBeGreaterThan(0);
});
test('mark the hour nearest now', () => {
expect(hourLabel('2026-11-22T00:00Z', true)).toMatch(/\(now\)$/);
expect(hourLabel('2026-11-22T00:00Z', false)).not.toMatch(/now/);
});
});
describe('the fallout of several bursts', () => {
const {simulateBursts} = require('./FalloutPanel');
const {prepareField} = require('../map-shared/fallout/winds.js');
const winds = {profile: [[0, 10, 0]]};
const bursts = [
{lat: 40, lon: -105, yieldKt: 10, fissionFraction: 0.5},
{lat: 40.5, lon: -104, yieldKt: 100, fissionFraction: 0.5},
];
// A forecast over 39-42 N, 106-103 W, every degree, whose wind turns from the west to the
// south-west over the hours, on ground rising to the east.
const HOURS = ['2026-11-22T00:00Z', '2026-11-22T01:00Z', '2026-11-22T02:00Z'];
function forecast() {
const points = [];
for (const lat of [39, 40, 41, 42]) for (const lon of [-106, -105, -104, -103]) points.push({lat, lon, elevation: 1500 + (lon + 106) * 100});
return {
source: 'Open-Meteo', fetched_at: '2026-11-22T00:30:00+00:00', spacing: 1, points, hours: HOURS,
winds: points.map(() => HOURS.map((_, h) => [[10, 12, 270 - 20 * h], [20000, 30, 260 - 20 * h]])),
rain: points.map(() => HOURS.map(() => 0)),
};
}
const fieldWinds = () => ({prepared: prepareField(forecast()), startMs: Date.parse(HOURS[0])});
test('carries each burst by the winds where it is, from the ground there', async () => {
const ran = await simulateBursts(bursts, {winds: fieldWinds(), useTerrain: false});
expect(ran.grid.values.some((v) => v > 0)).toBe(true);
// Not as one wind would carry them.
const one = await simulateBursts(bursts, {winds, useTerrain: false});
expect(ran.grid.values.length === one.grid.values.length
&& ran.grid.values.every((v, i) => v === one.grid.values[i])).toBe(false);
});
test('is drawn on one grid around the first burst', async () => {
const one = await simulateBursts(bursts.slice(0, 1), {winds, useTerrain: false});
const both = await simulateBursts(bursts, {winds, useTerrain: false});
expect(both.origin).toBe(bursts[0]);
const sum = (g) => g.values.reduce((a, v) => a + v, 0) * g.cell ** 2;
expect(sum(both.grid)).toBeGreaterThan(sum(one.grid) * 5);
expect(both.terrainStatus).toMatch(/terrain is off/);
});
test('stops when it is no longer wanted', async () => {
expect(await simulateBursts(bursts, {winds, useTerrain: false, cancelled: () => true})).toBeNull();
});
const MANY = Array.from({length: 7}, (_, i) => ({lat: 40 + 0.2 * i, lon: -105 + 0.3 * i, yieldKt: 5 * (i + 1), fissionFraction: 0.5}));
// Whether two results have the same grid (said quickly: Jest's diff of such arrays takes minutes).
const same = (a, b) => a.grid.cell === b.grid.cell && a.grid.values.length === b.grid.values.length
&& a.grid.values.every((v, i) => v === b.grid.values[i]);
test('spreads the bursts over workers, as the page calculates them', async () => {
for (const w of [winds, fieldWinds()]) {
made.length = 0;
const here = await simulateBursts(MANY, {winds: w, useTerrain: false});
const heard = [];
const spread = await simulateBursts(MANY, {winds: w, useTerrain: false, workers: 3, makeWorker: () => worker(),
onProgress: (done, total) => heard.push([done, total])});
// The bursts by three workers, then the grid's parts by three more.
const burstWorkers = made.filter((x) => x.kind === 'bursts');
const gridWorkers = made.filter((x) => x.kind === 'grid');
expect(burstWorkers).toHaveLength(3);
expect(gridWorkers).toHaveLength(3);
expect(burstWorkers.flatMap((x) => x.given).sort()).toEqual([0, 1, 2, 3, 4, 5, 6]);
expect(gridWorkers.flatMap((x) => x.given).length).toBeGreaterThan(3);
expect(made.every((x) => x.given.length > 0 && x.terminated)).toBe(true);
expect(heard[heard.length - 1]).toEqual([7, 7]);
expect(same(spread, here)).toBe(true);
expect(JSON.stringify(spread.spots) === JSON.stringify(here.spots)).toBe(true);
// Given the forecast's arrays, not the forecast as fetched.
if (w.prepared) {
const {prepared} = burstWorkers[0].start;
expect(prepared.u).toBeInstanceOf(Float32Array);
expect(prepared.field.winds).toBeUndefined();
expect(prepared.field.points).toHaveLength(16);
}
}
});
test('shows its progress every so often, and when all is done', () => {
const {everySoOften} = require('./FalloutPanel');
jest.useFakeTimers();
try {
const heard = [];
const report = everySoOften((done, total) => heard.push(done));
for (let done = 1; done <= 10; done++) {
report(done, 10);
jest.advanceTimersByTime(30);
}
// The first, one in every four after it (30 ms apart), and the last.
expect(heard).toEqual([1, 5, 9, 10]);
} finally {
jest.useRealTimers();
}
});
test('gives its workers the terrain, when it is read', async () => {
// Ground rising to the north-east of the bursts.
const nx = 81, ny = 81, step = 0.05;
const grid = {west: -107, south: 38, step, nx, ny, values: new Float32Array(nx * ny)};
for (let j = 0; j < ny; j++) for (let i = 0; i < nx; i++) grid.values[j * nx + i] = 1500 + 40 * (i + j);
loadTerrainGrid.mockImplementation(async () => ({grid, zoom: 9, coverage: 1}));
try {
const flat = await simulateBursts(MANY, {winds: fieldWinds(), useTerrain: false});
const here = await simulateBursts(MANY, {winds: fieldWinds(), useTerrain: true});
made.length = 0;
const heard = [];
const spread = await simulateBursts(MANY, {winds: fieldWinds(), useTerrain: true, workers: 2,
makeWorker: () => worker(), onProgress: (done, total) => heard.push([done, total])});
expect(here.terrainStatus).toMatch(/Follows the terrain/);
expect(same(here, flat)).toBe(false);
expect(same(spread, here)).toBe(true);
// A pass on flat ground, then another over the terrain, each by its own workers.
expect(made.map((x) => x.kind)).toEqual(['bursts', 'bursts', 'grid', 'grid', 'bursts', 'bursts', 'grid', 'grid']);
expect(heard[heard.length - 1]).toEqual([14, 14]);
} finally {
loadTerrainGrid.mockImplementation(async () => null);
}
});
test('stops its workers at once when cancelled', async () => {
made.length = 0;
const controller = new AbortController();
const running = simulateBursts(MANY, {winds, useTerrain: false, workers: 3, makeWorker: () => worker(),
signal: controller.signal});
controller.abort();
expect(await running).toBeNull();
expect(made).toHaveLength(3);
expect(made.every((x) => x.terminated)).toBe(true);
});
test('calculates on the page when its workers fail, or there are none', async () => {
made.length = 0;
const error = jest.spyOn(console, 'error').mockImplementation(() => null);
const here = await simulateBursts(MANY, {winds, useTerrain: false});
const ran = await simulateBursts(MANY, {winds, useTerrain: false, workers: 2, makeWorker: () => worker({fail: true})});
expect(error).toHaveBeenCalled();
error.mockRestore();
expect(made.every((x) => x.terminated)).toBe(true);
expect(same(ran, here)).toBe(true);
const none = await simulateBursts(MANY, {winds, useTerrain: false, workers: 2, makeWorker: () => null});
expect(same(none, here)).toBe(true);
});
});
describe('the fallout image', () => {
const {imageRows} = require('./FalloutPanel');
test('takes each row from the grid row at its own latitude', () => {
// A grid from 20 to 80 degrees north, around 40: a tenth of a degree a row.
const grid = {y0: -20 * 111320, cell: 11132, ny: 600, nx: 1};
const rows = imageRows(grid, 40, 600);
// The top row is the grid's northernmost, the bottom its southernmost.
expect(rows[0]).toBe(599);
expect(rows[599]).toBe(0);
// Halfway down the image, in Web Mercator, is well north of halfway in latitude (50 degrees).
expect(rows[300]).toBeGreaterThan(330);
for (let r = 1; r < 600; r++) expect(rows[r]).toBeLessThanOrEqual(rows[r - 1]);
});
test('is the plain grid over a small area', () => {
const grid = {y0: -5000, cell: 100, ny: 100, nx: 1};
const rows = imageRows(grid, 40, 100);
expect(rows[0]).toBe(99);
expect(Math.abs(rows[50] - 49)).toBeLessThanOrEqual(1);
});
});
describe('the fallout timeline', () => {
const {screen, fireEvent} = require('@testing-library/react');
const {renderWithProviders} = require('../test-utils');
const {Timeline, HOURS, afterLabel, weakerThanH1} = require('./FalloutPanel');
test('runs from the first hour to two weeks, in longer steps as it goes', () => {
expect(HOURS[0]).toBe(1);
expect(HOURS[HOURS.length - 1]).toBe(336);
for (let k = 1; k < HOURS.length; k++) expect(HOURS[k]).toBeGreaterThan(HOURS[k - 1]);
expect(HOURS.map(afterLabel)).toEqual(['1 hour', '2 hours', '3 hours', '6 hours', '12 hours', '1 day',
'2 days', '3 days', '5 days', '1 week', '2 weeks']);
});
test('says how much the fallout has weakened since H+1', () => {
// t^-1.2: about 10 times weaker for every 7 times longer.
expect(weakerThanH1(7)).toBe('10');
expect(weakerThanH1(3)).toBe('3.7');
expect(weakerThanH1(48)).toBe('100');
expect(weakerThanH1(336)).toBe('1,100');
});
test('says what it shows, and moves and plays the hours', () => {
const onAfter = jest.fn(), onPlaying = jest.fn();
const {unmount} = renderWithProviders(<Timeline after={1} onAfter={onAfter} playing={false}
onPlaying={onPlaying} startMs={null}/>);
expect(screen.getByText(/^H\+1: the fallout landed by then\.$/)).toBeTruthy();
// Each step of the slider is one of the hours.
fireEvent.change(screen.getByLabelText('Time after the bursts'), {target: {value: String(HOURS.indexOf(48))}});
expect(onAfter).toHaveBeenCalledWith(48);
fireEvent.click(screen.getByLabelText('Play'));
expect(onPlaying).toHaveBeenCalledWith(true);
unmount();
renderWithProviders(<Timeline after={6} onAfter={onAfter} playing={true} onPlaying={onPlaying}
startMs={Date.parse('2026-11-22T00:00Z')}/>);
expect(screen.getByText(/^H\+6, .*: the fallout landed by then, about 8\.6 times weaker than at H\+1\.$/)).toBeTruthy();
expect(screen.getByLabelText('Time after the bursts').getAttribute('aria-valuetext')).toBe('6 hours');
fireEvent.click(screen.getByLabelText('Pause'));
expect(onPlaying).toHaveBeenLastCalledWith(false);
});
});
describe('the total dose view', () => {
const {TOTAL_BANDS, DOSE_BANDS, legendHeading, legendText} = require('./FalloutPanel');
test('has its own bands, each saying what it does to a person', () => {
expect(TOTAL_BANDS.map((b) => b.rate)).toEqual([1000, 450, 100, 25, 5]);
for (const b of TOTAL_BANDS) expect(b.meaning.length).toBeGreaterThan(5);
// The same colors, highest first.
expect(TOTAL_BANDS.map((b) => b.color)).toEqual(DOSE_BANDS.map((b) => b.color));
});
test('says what is shown, by the hour', () => {
expect(legendHeading('total', 6)).toBe('Total dose outdoors in the first two weeks');
expect(legendHeading('rate', 1)).toBe('Dose rate 1 hour after the bursts');
expect(legendHeading('rate', 120)).toBe('Dose rate 5 days after the bursts');
expect(legendText('total')).toMatch(/outdoors the whole time/);
expect(legendText('rate')).toMatch(/landed by then/);
expect(legendText('rate')).toMatch(/weakens/);
});
});
describe('the forecast\'s warning', () => {
const {forecastShortText} = require('./FalloutPanel');
const hourMs = Math.floor(Date.now() / 3600000) * 3600000;
const of = (from, count) => ({hours: Array.from({length: count}, (_, h) => new Date(hourMs + (from + h) * 3600000).toISOString())});
test('says when it has run out, or ends before the fallout is down, and else nothing', () => {
expect(forecastShortText(null, 0)).toBeNull();
expect(forecastShortText(of(-30, 10), 9)).toMatch(/has run out/);
expect(forecastShortText(of(-1, 30), 1)).toMatch(/ends at .*, before all the fallout is down/);
expect(forecastShortText(of(-1, 96), 1)).toBeNull();
});
});
describe('the targets simulated', () => {
const {withSavedTargets, targetsUnsaved, withWeapon} = require('./FalloutPanel');
const saved = [{id: 1, label: 'A', lat: 1, lon: 1, kind: 'target', weapon: 'yars'},
{id: 2, label: 'B', lat: 2, lon: 2, kind: 'target', weapon: 'custom', yield_kt: 20, fission_fraction: 1}];
const tried = {key: 'new-1', label: 'C', lat: 3, lon: 3, weapon: 'w88'};
test('are the saved ones once loaded, then those tried out', () => {
const loaded = withSavedTargets(saved, [tried]);
expect(loaded.map((t) => t.key)).toEqual(['saved-1', 'saved-2', 'new-1']);
// Loading again keeps the tried ones once, and the saved ones as saved.
expect(withSavedTargets(saved, loaded).map((t) => t.key)).toEqual(['saved-1', 'saved-2', 'new-1']);
});
test('are unsaved when they differ from the saved ones', () => {
expect(targetsUnsaved([], saved, false)).toBe(false);
expect(targetsUnsaved([tried], saved, false)).toBe(true);
const loaded = withSavedTargets(saved, []);
expect(targetsUnsaved(loaded, saved, true)).toBe(false);
expect(targetsUnsaved(loaded.slice(1), saved, true)).toBe(true);
expect(targetsUnsaved([withWeapon(loaded[0], {weapon: 'w88'}), loaded[1]], saved, true)).toBe(true);
expect(targetsUnsaved([...loaded, tried], saved, true)).toBe(true);
});
test('take a new weapon in place of the old', () => {
expect(withWeapon(saved[1], {weapon: 'w88', fission_fraction: 0.5})).toEqual(
{id: 2, label: 'B', lat: 2, lon: 2, kind: 'target', weapon: 'w88', fission_fraction: 0.5});
});
});
describe('the fallout panel\'s steps', () => {
const {screen, fireEvent, waitFor, act, cleanup} = require('@testing-library/react');
const {renderWithProviders} = require('../test-utils');
const FalloutPanel = require('./FalloutPanel').default;
// A map which keeps the one image source and layer the panel draws.
function fakeMap() {
const map = {
source: null, layer: false, added: 0,
getSource: () => map.source,
addSource: (id, s) => {
map.added++;
map.source = {...s, updateImage: (i) => Object.assign(map.source, i)};
},
addLayer: () => {
map.layer = true;
},
getLayer: () => map.layer,
removeLayer: () => {
map.layer = false;
},
removeSource: () => {
map.source = null;
},
on: () => null, off: () => null,
getCenter: () => ({lat: 40, lng: -100}),
};
return map;
}
const target = {key: 'saved-1', id: 1, label: 'Somewhere', lat: 40, lon: -100, weapon: 'w88'};
let getContext, toDataURL;
beforeEach(() => {
loadTerrainGrid.mockClear();
// jsdom draws no canvas: an image of the right size is all the map is given.
getContext = jest.spyOn(HTMLCanvasElement.prototype, 'getContext').mockImplementation(() => ({
createImageData: (w, h) => ({data: new Uint8ClampedArray(w * h * 4)}),
putImageData: () => null,
}));
toDataURL = jest.spyOn(HTMLCanvasElement.prototype, 'toDataURL').mockImplementation(() => 'data:');
});
afterEach(() => {
cleanup();
getContext.mockRestore();
toDataURL.mockRestore();
});
test('ask for targets first, and calculate nothing until there are some', async () => {
const map = fakeMap();
renderWithProviders(<FalloutPanel map={map} targets={[]} onClose={() => null}/>);
expect(screen.getByText('Step 2 of 4: Choose the targets')).toBeTruthy();
expect(screen.getByText('No targets yet')).toBeTruthy();
expect(screen.getByText(/Right-clicking the map adds one too/)).toBeTruthy();
expect(screen.getByRole('button', {name: 'Next: the wind'}).disabled).toBe(true);
// The wind is a step of its own.
expect(screen.queryByRole('textbox', {name: 'Wind'})).toBeNull();
await act(async () => new Promise((r) => setTimeout(r, 60)));
expect(map.added).toBe(0);
});
test('show the targets\' fallout only once the user goes on, hour by hour or in total', async () => {
const map = fakeMap();
renderWithProviders(<FalloutPanel map={map} targets={[target]} onClose={() => null}/>);
expect(screen.getByText('1 target')).toBeTruthy();
await act(async () => new Promise((r) => setTimeout(r, 60)));
expect(map.added).toBe(0);
fireEvent.click(screen.getByRole('button', {name: 'Next: the wind'}));
expect(screen.getByText('Step 3 of 4: The wind')).toBeTruthy();
// Its fields are all shown; the winds a user can choose are the forecast or one wind of their
// own, and no test shots' winds.
expect(screen.getByRole('checkbox', {name: 'Follow the terrain'})).toBeTruthy();
expect(screen.getByRole('textbox', {name: 'Speed (mph)'})).toBeTruthy();
Element.prototype.scrollIntoView = Element.prototype.scrollIntoView || (() => null);
fireEvent.click(screen.getByRole('textbox', {name: 'Wind'}));
const winds = (await screen.findAllByRole('option')).map((o) => o.textContent);
expect(winds).toEqual(['Forecast winds aloft', 'One wind at every height']);
await act(async () => new Promise((r) => setTimeout(r, 60)));
expect(map.added).toBe(0);
fireEvent.click(screen.getByRole('button', {name: 'Next: the fallout'}));
expect(screen.getByText('Step 4 of 4: The fallout')).toBeTruthy();
expect(screen.getByRole('button', {name: 'Hour by hour'}).getAttribute('aria-pressed')).toBe('true');
expect(screen.getByText('Dose rate 1 hour after the bursts')).toBeTruthy();
await waitFor(() => expect(loadTerrainGrid).toHaveBeenCalledTimes(1), {timeout: 20000});
await waitFor(() => expect(screen.queryByText(/Calculating/)).toBeNull(), {timeout: 20000});
expect(map.layer).toBe(true);
// A later hour, then the total, which has no timeline.
fireEvent.change(screen.getByLabelText('Time after the bursts'), {target: {value: '5'}});
expect(screen.getByText('Dose rate 1 day after the bursts')).toBeTruthy();
fireEvent.click(screen.getByRole('button', {name: 'Total dose'}));
expect(screen.getByText('Total dose outdoors in the first two weeks')).toBeTruthy();
expect(screen.queryByLabelText('Time after the bursts')).toBeNull();
// Back to the wind clears the map; on again, with nothing changed, it is not calculated again.
fireEvent.click(screen.getByRole('button', {name: 'Back'}));
expect(screen.getByText('Step 3 of 4: The wind')).toBeTruthy();
expect(map.layer).toBe(false);
fireEvent.click(screen.getByRole('button', {name: 'Back'}));
expect(screen.getByText('Step 2 of 4: Choose the targets')).toBeTruthy();
fireEvent.click(screen.getByRole('button', {name: 'Next: the wind'}));
fireEvent.click(screen.getByRole('button', {name: 'Next: the fallout'}));
await waitFor(() => expect(map.layer).toBe(true));
expect(screen.queryByText(/Calculating/)).toBeNull();
expect(loadTerrainGrid).toHaveBeenCalledTimes(1);
}, 60000);
test('default to the forecast when it has the winds until the fallout is down, else one wind', async () => {
Element.prototype.scrollIntoView = Element.prototype.scrollIntoView || (() => null);
const windShown = async () => {
fireEvent.click(screen.getByRole('button', {name: 'Next: the wind'}));
await act(async () => new Promise((r) => setTimeout(r, 20)));
return screen.getByRole('textbox', {name: 'Wind'}).value;
};
// No forecast.
renderWithProviders(<FalloutPanel map={fakeMap()} targets={[target]}/>);
expect(await windShown()).toBe('One wind at every height');
cleanup();
// A forecast from the hour before now, for 3 days: it has the winds.
const hourMs = Math.floor(Date.now() / 3600000) * 3600000;
const hours = (count) => Array.from({length: count}, (_, h) => new Date(hourMs + (h - 1) * 3600000).toISOString());
const forecastOf = (count) => ({source: 'Open-Meteo', fetched_at: new Date(hourMs).toISOString(), spacing: 3,
points: [{lat: 40, lon: -100, elevation: 0}], hours: hours(count),
winds: [hours(count).map(() => [[10, 10, 270], [20000, 20, 270]])], rain: [hours(count).map(() => 0)]});
mockLatestWinds = forecastOf(72);
try {
renderWithProviders(<FalloutPanel map={fakeMap()} targets={[target]}/>);
expect(await windShown()).toBe('Forecast winds aloft');
cleanup();
// One ending a day from now does not: the fallout is still coming down then.
mockLatestWinds = forecastOf(24);
renderWithProviders(<FalloutPanel map={fakeMap()} targets={[target]}/>);
expect(await windShown()).toBe('One wind at every height');
} finally {
mockLatestWinds = null;
}
});
test('ask to download the forecast on the wind step, when it is not', async () => {
const before = mockWeather;
mockWeather = {...before, enabled: false, download: null};
try {
renderWithProviders(<FalloutPanel map={fakeMap()} targets={[target]}/>);
fireEvent.click(screen.getByRole('button', {name: 'Next: the wind'}));
await act(async () => new Promise((r) => setTimeout(r, 20)));
mockWeatherSet.length = 0;
fireEvent.click(screen.getByRole('button', {name: 'Download the forecast every day'}));
await act(async () => new Promise((r) => setTimeout(r, 20)));
expect(mockWeatherSet).toEqual([true]);
expect(screen.queryByRole('button', {name: 'Download the forecast every day'})).toBeNull();
} finally {
mockWeather = before;
}
cleanup();
// Subscribed: nothing asked.
renderWithProviders(<FalloutPanel map={fakeMap()} targets={[target]}/>);
fireEvent.click(screen.getByRole('button', {name: 'Next: the wind'}));
await act(async () => new Promise((r) => setTimeout(r, 20)));
expect(screen.queryByRole('button', {name: 'Download the forecast every day'})).toBeNull();
});
test('warn when the forecast chosen runs out before the fallout is down', async () => {
Element.prototype.scrollIntoView = Element.prototype.scrollIntoView || (() => null);
const hourMs = Math.floor(Date.now() / 3600000) * 3600000;
const hours = Array.from({length: 24}, (_, h) => new Date(hourMs - (100 - h) * 3600000).toISOString());
mockLatestWinds = {source: 'Open-Meteo', fetched_at: new Date(hourMs - 100 * 3600000).toISOString(), spacing: 3,
points: [{lat: 40, lon: -100, elevation: 0}], hours,
winds: [hours.map(() => [[10, 10, 270], [20000, 20, 270]])], rain: [hours.map(() => 0)]};
try {
renderWithProviders(<FalloutPanel map={fakeMap()} targets={[target]}/>);
fireEvent.click(screen.getByRole('button', {name: 'Next: the wind'}));
await act(async () => new Promise((r) => setTimeout(r, 20)));
// Too old: one wind is chosen for the user.
expect(screen.getByRole('textbox', {name: 'Wind'}).value).toBe('One wind at every height');
await act(async () => new Promise((r) => setTimeout(r, 50)));
fireEvent.click(screen.getByRole('textbox', {name: 'Wind'}));
fireEvent.click([...document.querySelectorAll('[role=option]')].find((o) => o.textContent === 'Forecast winds aloft'));
expect(screen.getByText(/This forecast has run out: its last hour's winds are held/)).toBeTruthy();
fireEvent.click(screen.getByRole('button', {name: 'Next: the fallout'}));
expect(screen.getByText(/This forecast has run out/)).toBeTruthy();
} finally {
mockLatestWinds = null;
}
});
test('add a target where the map is clicked next, until stopped', () => {
const onPlaceTarget = jest.fn();
const {rerender} = renderWithProviders(<FalloutPanel map={fakeMap()} targets={[]}
onPlaceTarget={onPlaceTarget}/>);
fireEvent.click(screen.getByRole('button', {name: 'Add a target'}));
expect(onPlaceTarget).toHaveBeenLastCalledWith(true);
rerender(<FalloutPanel map={fakeMap()} targets={[]} placingTarget onPlaceTarget={onPlaceTarget}/>);
expect(screen.getByText('Click the map where the target is.')).toBeTruthy();
expect(screen.queryByRole('button', {name: 'Add a target'})).toBeNull();
fireEvent.click(screen.getByRole('button', {name: 'Stop'}));
expect(onPlaceTarget).toHaveBeenLastCalledWith(false);
// Going on to the wind stops it too.
onPlaceTarget.mockClear();
rerender(<FalloutPanel map={fakeMap()} targets={[target]} placingTarget onPlaceTarget={onPlaceTarget}/>);
fireEvent.click(screen.getByRole('button', {name: 'Next: the wind'}));
expect(onPlaceTarget).toHaveBeenCalledWith(false);
});
test('load the saved targets before saving over them', () => {
const onLoad = jest.fn(), onSave = jest.fn();
const tried = {key: 'new-1', label: 'Tried', lat: 41, lon: -101, weapon: 'w88'};
const {rerender} = renderWithProviders(<FalloutPanel map={fakeMap()} targets={[tried]} savedCount={156}
unsaved onLoad={onLoad} onSave={onSave}/>);
// Only the target being tried out is simulated until the saved ones are loaded.
expect(screen.getByText('1 target')).toBeTruthy();
expect(screen.getByText('(not saved)')).toBeTruthy();
expect(screen.getByText('Not saved.')).toBeTruthy();
const save = screen.getByRole('button', {name: 'Save Targets'});
expect(save.disabled).toBe(true);
expect(screen.getByText(/Saving replaces the saved targets: load them first/)).toBeTruthy();
fireEvent.click(screen.getByRole('button', {name: 'Load Saved Targets (156)'}));
expect(onLoad).toHaveBeenCalledTimes(1);
rerender(<FalloutPanel map={fakeMap()} targets={[target, tried]} savedCount={156} loaded unsaved
onLoad={onLoad} onSave={onSave}/>);
expect(screen.queryByRole('button', {name: /Load Saved Targets/})).toBeNull();
expect(screen.queryByText(/load them first/)).toBeNull();
fireEvent.click(screen.getByRole('button', {name: 'Save Targets'}));
expect(onSave).toHaveBeenCalledTimes(1);
});
test('save targets when none are saved, and take one out of the list', () => {
const onRemoveTarget = jest.fn();
const tried = {key: 'new-1', label: 'Tried', lat: 41, lon: -101, weapon: 'w88'};
const {rerender} = renderWithProviders(<FalloutPanel map={fakeMap()} targets={[]} savedCount={0}/>);
expect(screen.queryByRole('button', {name: /Load Saved Targets/})).toBeNull();
expect(screen.getByRole('button', {name: 'Save Targets'}).disabled).toBe(true);
rerender(<FalloutPanel map={fakeMap()} targets={[tried]} savedCount={0} unsaved
onRemoveTarget={onRemoveTarget}/>);
expect(screen.getByRole('button', {name: 'Save Targets'}).disabled).toBe(false);
fireEvent.click(screen.getByRole('button', {name: 'Remove Tried'}));
expect(onRemoveTarget).toHaveBeenCalledWith(tried);
});
});
describe('the fallout of past days', () => {
const {simulateClimate, CLIMATE_BANDS} = require('./FalloutPanel');
const {parseClimatology} = require('../map-shared/fallout/climatology.js');
// Days on a coarse grid (lat 90..-90 every 30, lon 0..330 every 30), each one wind [east, north].
function climate(days) {
const header = {version: 1, levels_hpa: [1000, 500], lat: [90, -30, 7], lon: [0, 30, 12],
days: days.map((_, k) => `200${k}-05-01`)};
const head = new TextEncoder().encode(JSON.stringify(header));
const size = 2 * 7 * 12;
const bytes = new Uint8Array(10 + head.length + 2 * size + days.length * 2 * size);
bytes.set([87, 70, 67, 76], 0);
const view = new DataView(bytes.buffer);
view.setUint16(4, 1, true);
view.setUint32(6, head.length, true);
bytes.set(head, 10);
let at = 10 + head.length;
for (let c = 0; c < size; c++) view.setInt16(at + 2 * c, c < size / 2 ? 100 : 5500, true);
at += 2 * size;
for (const [e, n] of days) {
for (let c = 0; c < size; c++) view.setInt8(at + c, e);
for (let c = 0; c < size; c++) view.setInt8(at + size + c, n);
at += 2 * size;
}
return parseClimatology(bytes);
}
test('counts the days each place was reached, for all the bursts at once', async () => {
const bursts = [{lat: 30, lon: -120, yieldKt: 10, fissionFraction: 1}, {lat: 31, lon: -118, yieldKt: 10, fissionFraction: 1}];
const heard = [];
const ran = await simulateClimate(bursts, climate([[10, 0], [10, 0], [0, 10]]),
{rate: 1, onProgress: (done, total) => heard.push([done, total])});
expect(ran.origin).toBe(bursts[0]);
expect(ran.grid.days).toBe(3);
const most = ran.grid.values.reduce((a, v) => Math.max(a, v), 0);
expect(most).toBeGreaterThan(0.3);
expect(most).toBeLessThanOrEqual(1);
expect(heard[heard.length - 1]).toEqual([6, 6]);
// The bands go from most days to any.
expect(CLIMATE_BANDS.map((b) => b.rate)).toEqual([...CLIMATE_BANDS.map((b) => b.rate)].sort((a, b) => b - a));
});
test('stops when cancelled', async () => {
const bursts = [{lat: 30, lon: -120, yieldKt: 10, fissionFraction: 1}];
expect(await simulateClimate(bursts, climate([[10, 0], [0, 10]]), {cancelled: () => true})).toBeNull();
});
const BURSTS = [{lat: 30, lon: -120, yieldKt: 10, fissionFraction: 1}, {lat: 31, lon: -118, yieldKt: 10, fissionFraction: 1}];
const DAYS = [[10, 0], [10, 0], [0, 10], [-8, 4], [3, -9]];
test('spreads the days over workers, and counts them as the page does', async () => {
made.length = 0;
const clim = climate(DAYS);
const here = await simulateClimate(BURSTS, clim, {rate: 1});
const heard = [];
const spread = await simulateClimate(BURSTS, clim, {rate: 1, workers: 2, makeWorker: () => worker(),
onProgress: (done, total) => heard.push([done, total])});
expect(made).toHaveLength(2);
// Every day given once, to one worker or the other, and both given some.
expect(made.flatMap((w) => w.given).sort()).toEqual([0, 1, 2, 3, 4]);
expect(made.every((w) => w.given.length > 0)).toBe(true);
expect(made.every((w) => w.terminated)).toBe(true);
expect(heard[heard.length - 1]).toEqual([10, 10]);
expect(spread.grid.days).toBe(5);
expect(spread.grid.cell).toBe(here.grid.cell);
expect(Array.from(spread.grid.values)).toEqual(Array.from(here.grid.values));
});
test('stops its workers at once when cancelled', async () => {
made.length = 0;
const controller = new AbortController();
const running = simulateClimate(BURSTS, climate(DAYS), {rate: 1, workers: 3, makeWorker: () => worker(),
signal: controller.signal});
controller.abort();
expect(await running).toBeNull();
expect(made).toHaveLength(3);
expect(made.every((w) => w.terminated)).toBe(true);
});
test('calculates on the page when its workers fail', async () => {
made.length = 0;
const error = jest.spyOn(console, 'error').mockImplementation(() => null);
const clim = climate(DAYS);
const here = await simulateClimate(BURSTS, clim, {rate: 1});
const ran = await simulateClimate(BURSTS, clim, {rate: 1, workers: 2, makeWorker: () => worker({fail: true})});
expect(error).toHaveBeenCalled();
error.mockRestore();
expect(made.every((w) => w.terminated)).toBe(true);
expect(Array.from(ran.grid.values)).toEqual(Array.from(here.grid.values));
// And where there are none to be had.
const none = await simulateClimate(BURSTS, clim, {rate: 1, workers: 2, makeWorker: () => null});
expect(Array.from(none.grid.values)).toEqual(Array.from(here.grid.values));
});
});
describe('the fallout panel\'s progress', () => {
const {screen} = require('@testing-library/react');
const {renderWithProviders} = require('../test-utils');
const {FalloutProgress} = require('./FalloutPanel');
test('is a bar filled as far as the bursts are calculated', () => {
const {unmount} = renderWithProviders(<FalloutProgress busy={true} progress={{done: 1170, total: 4680}}/>);
const bar = screen.getByRole('progressbar');
expect(bar.getAttribute('aria-valuenow')).toBe('25');
expect(screen.getByText('Calculating 1,170 of 4,680')).toBeTruthy();
unmount();
});
test('has a button which cancels the calculation', () => {
const {fireEvent} = require('@testing-library/react');
const onCancel = jest.fn();
const {unmount} = renderWithProviders(<FalloutProgress busy={true} progress={{done: 1, total: 2}} onCancel={onCancel}/>);
fireEvent.click(screen.getByRole('button', {name: 'Cancel'}));
expect(onCancel).toHaveBeenCalledTimes(1);
unmount();
});
test('moves without a count until there is one, and is gone when done', () => {
const {rerender, unmount} = renderWithProviders(<FalloutProgress busy={true} progress={null}/>);
expect(screen.getByRole('progressbar').getAttribute('aria-valuenow')).toBeNull();
expect(screen.getByText('Calculating…')).toBeTruthy();
rerender(<FalloutProgress busy={false} progress={null}/>);
expect(screen.queryByRole('progressbar')).toBeNull();
unmount();
});
});

View file

@ -11,14 +11,17 @@ import {
} from "./Common";
import {Route, Routes, useNavigate} from "react-router";
import {
deleteMapFile, deleteMapPin, fetchMapSubscriptions, getMapFiles, getMapPins,
deleteMapFile, deleteMapPin, deleteMapTarget, fetchMapSubscriptions, getMapFiles, getMapPins, getMapTargets,
mapSubscribe, mapUnsubscribe, rebuildMapSearchIndex, setMapFileVisible, updateMapPin
} from "../api";
import {targetWeapon} from "../map-shared/fallout/targets.js";
import {formatYieldAndFission} from "../map-shared/fallout/weapons.js";
import {Button, Divider, Group, Header, Icon, Modal, Table, TextInput, Toggle} from "./ui";
import {SortableTable} from "./SortableTable";
import {Media, StatusContext} from "../contexts/contexts";
import {MAP_VIEWER_URI} from "./Vars";
import MapViewer from "./MapViewer";
import {WeatherSection} from "./MapWeather";
import {AddToPlaylistButton} from "./AddToPlaylist";
import {solarCalculatorPath} from "./calculators/solar";
import maplibregl from "maplibre-gl";
@ -501,6 +504,10 @@ function ManageMap() {
</p>
</InfoMessage>
<Divider/>
<WeatherSection/>
<HandPointMessage>
<p>You can also view the map at <a href={MAP_VIEWER_URI}>{MAP_VIEWER_URI}</a></p>
</HandPointMessage>
@ -743,6 +750,103 @@ function MapPins() {
emptyRow={emptyRow}
/>
</Media>
<MapTargets filter={lowerFilter}/>
</>;
}
// The saved nuclear targets (map_nuclear.yaml), apart from the pins: what each is and where, and
// deleting one. `filter` (lower case) matches a name or coordinates.
export function MapTargets({filter = ''}) {
// null = pending, undefined = fetch failed, [] = no targets.
const [targets, setTargets] = useState(null);
const navigate = useNavigate();
const gen = useRef(0);
const fetchTargets = async () => {
const mine = ++gen.current;
const saved = await getMapTargets();
if (mine === gen.current) setTargets(saved);
};
useEffect(() => {
fetchTargets();
}, []);
const handleDelete = async (targetId) => {
await deleteMapTarget(targetId);
await fetchTargets();
};
const weaponOf = (target) => {
const chosen = targetWeapon(target);
return `${chosen.weapon ? chosen.weapon.name : 'A yield of my own'}, `
+ formatYieldAndFission(chosen.yieldKt, chosen.fissionFraction);
};
const place = (target) => {
const to = `/map?lat=${target.lat}&lon=${target.lon}&z=10`;
return <a href={to} onClick={(e) => {
e.preventDefault();
navigate(to);
}}>{target.lat.toFixed(4)}, {target.lon.toFixed(4)}</a>;
};
const deleteButton = (target) => <APIButton
size='xs'
role='danger'
icon='trash'
aria-label={`Delete ${target.label}`}
confirmContent='Delete this target?'
confirmButton='Delete'
onClick={() => handleDelete(target.id)}
/>;
const fullHeaders = [
{key: 'label', text: 'Target', sortBy: i => i.label.toLowerCase()},
{key: 'weapon', text: 'Weapon', sortBy: i => targetWeapon(i).yieldKt},
{key: 'coords', text: 'Coordinates', sortBy: i => i.lat},
{key: 'created', text: 'Created', sortBy: i => i.created},
{key: 'actions', text: '', sortBy: null},
];
const fullRowFunc = (target) => <Table.Row key={target.id}>
<Table.Cell><span aria-hidden>☢ </span>{target.label}</Table.Cell>
<Table.Cell>{weaponOf(target)}</Table.Cell>
<Table.Cell>{place(target)}</Table.Cell>
<Table.Cell>{target.created}</Table.Cell>
<Table.Cell>{deleteButton(target)}</Table.Cell>
</Table.Row>;
const mobileHeaders = [
{key: 'label', text: 'Target', sortBy: i => i.label.toLowerCase()},
{key: 'actions', text: '', sortBy: null},
];
const mobileRowFunc = (target) => <Table.Row key={target.id}>
<Table.Cell>
<span aria-hidden>☢ </span>{target.label}
<div style={{fontSize: '0.6875rem', color: 'var(--muted)'}}>{weaponOf(target)}</div>
<div style={{fontSize: '0.6875rem'}}>{place(target)}</div>
</Table.Cell>
<Table.Cell>{deleteButton(target)}</Table.Cell>
</Table.Row>;
const emptyRow = <Table.Row>
<Table.Cell colSpan={5}>No targets. Turn on nuclear mode (☢) on the map to add and save some.</Table.Cell>
</Table.Row>;
const shown = filter && targets
? targets.filter(t => (t.label || '').toLowerCase().includes(filter) ||
`${t.lat.toFixed(4)}, ${t.lon.toFixed(4)}`.includes(filter))
: targets;
return <>
<Header as='h3'>Nuclear Targets</Header>
{targets === undefined ? <ErrorMessage>Could not fetch the nuclear targets</ErrorMessage> : <>
<Media at='mobile'>
<SortableTable tableHeaders={mobileHeaders} data={shown} rowFunc={mobileRowFunc} rowKey='id'
defaultSortColumn='label' emptyRow={emptyRow}/>
</Media>
<Media greaterThanOrEqual='tablet'>
<SortableTable tableHeaders={fullHeaders} data={shown} rowFunc={fullRowFunc} rowKey='id'
defaultSortColumn='label' emptyRow={emptyRow}/>
</Media>
</>}
</>;
}

View file

@ -102,6 +102,7 @@ const CATALOG = [
jest.mock('../api', () => ({
...jest.requireActual('../api'),
getWeather: async () => ({enabled: false, download: null, targets: 0, field: null}),
getMapFiles: jest.fn(),
fetchMapSubscriptions: jest.fn(),
getMapPins: jest.fn(),

View file

@ -28,6 +28,11 @@ jest.mock('../api', () => ({
getMapFiles: jest.fn(),
fetchMapSubscriptions: jest.fn(),
getMapPins: jest.fn(),
getMapTargets: jest.fn(),
getWeather: jest.fn(),
setWeatherSubscription: jest.fn(),
downloadWeatherNow: jest.fn(),
deleteMapTarget: jest.fn(),
setMapFileVisible: jest.fn(),
rebuildMapSearchIndex: jest.fn(),
}));
@ -38,6 +43,7 @@ const pending = () => new Promise(() => {
});
const NO_PINS = /No pins\. Right-click/;
const NO_RESULTS = /^No results$/;
const WEATHER_OFF = {enabled: false, download: null, targets: 3, spacing: 1, points: 160, seconds: 61, field: null};
// The pins page renders one table per breakpoint through `Media`, so the real media provider is
// needed; the queries below tolerate either variant being in the tree.
@ -59,6 +65,9 @@ beforeEach(() => {
api.getMapFiles.mockResolvedValue({files: []});
api.fetchMapSubscriptions.mockResolvedValue({catalog: [], subscriptions: []});
api.getMapPins.mockResolvedValue({pins: []});
api.getMapTargets.mockResolvedValue([]);
api.deleteMapTarget.mockResolvedValue(true);
api.getWeather.mockResolvedValue(WEATHER_OFF);
});
describe('the Pins tab', () => {
@ -106,6 +115,61 @@ describe('the Pins tab', () => {
});
});
describe('the Pins tab\'s nuclear targets', () => {
const {within} = require('@testing-library/react');
const targets = [
{id: 1, lat: 40.1, lon: -111.2, label: 'Base', created: '2026-11-24', weapon: 'w88', fission_fraction: 0.5},
{id: 2, lat: 41, lon: -112, label: 'Depot', created: '2026-11-24', weapon: 'custom', yield_kt: 20,
fission_fraction: 1},
];
test('are listed in their own table, apart from the pins', async () => {
api.getMapPins.mockResolvedValue({pins: [{id: 1, lat: 40.1, lon: -111.2, label: 'Camp', color: '#f00'}]});
api.getMapTargets.mockResolvedValue(targets);
renderAt('/map/pins');
await act(async () => {
});
const tables = screen.getAllByRole('table');
expect(tables).toHaveLength(2);
const [pinsTable, table] = tables;
expect(within(pinsTable).queryByText('Base')).toBeNull();
expect(within(pinsTable).getByText('Camp')).toBeTruthy();
expect(within(table).queryByText('Camp')).toBeNull();
expect(within(table).getByText('Base')).toBeTruthy();
expect(within(table).getByText(/W88.*455 kt, half fission/)).toBeTruthy();
expect(within(table).getByText(/A yield of my own, 20 kt/)).toBeTruthy();
});
test('says when there are none, and when they could not be fetched', async () => {
const {unmount} = renderAt('/map/pins');
await act(async () => {
});
expect(screen.getAllByText(/No targets\. Turn on nuclear mode/).length).toBeGreaterThan(0);
unmount();
api.getMapTargets.mockResolvedValue(undefined);
renderAt('/map/pins');
await act(async () => {
});
expect(screen.getByText('Could not fetch the nuclear targets')).toBeTruthy();
expect(screen.queryAllByText(/No targets\./)).toHaveLength(0);
});
test('delete one, and are fetched again', async () => {
api.getMapTargets.mockResolvedValueOnce(targets).mockResolvedValueOnce(targets.slice(1));
renderAt('/map/pins');
await act(async () => {
});
fireEvent.click(screen.getAllByRole('button', {name: 'Delete Base'})[0]);
// The delete is confirmed first.
await act(async () => {
fireEvent.click(await screen.findByRole('button', {name: 'Delete'}));
});
expect(api.deleteMapTarget).toHaveBeenCalledWith(1);
expect(api.getMapTargets).toHaveBeenCalledTimes(2);
expect(screen.queryAllByText('Base')).toHaveLength(0);
});
});
describe('the Manage tab subscriptions table', () => {
test('pending: shows a placeholder, not "No results"', async () => {
api.fetchMapSubscriptions.mockReturnValue(pending());
@ -234,3 +298,65 @@ describe('the Manage tab files table', () => {
expect(api.setMapFileVisible).toHaveBeenCalledWith('satellite.pmtiles', true);
});
});
describe('the Manage tab\'s weather', () => {
const hour = 3600000;
const field = (fromHours, toHours) => ({
fetched_at: new Date().toISOString(), spacing: 1, points: 160, size: 5 * 1024 * 1024,
first_hour: new Date(Date.now() + fromHours * hour).toISOString(),
last_hour: new Date(Date.now() + toHours * hour).toISOString(),
});
test('is turned on with its toggle, and says what it downloads', async () => {
api.setWeatherSubscription.mockResolvedValue({...WEATHER_OFF, enabled: true,
download: {status: 'new', next_download: null, last_successful_download: null}});
renderAt('/map/manage');
await act(async () => {
});
expect(screen.getByText('Weather')).toBeInTheDocument();
expect(screen.getByText(/Around 3 targets: 160 places every 1°, which takes about 2 minutes/)).toBeInTheDocument();
expect(screen.getByText('No forecast has been downloaded.')).toBeInTheDocument();
expect(screen.queryByRole('button', {name: 'Download now'})).toBeNull();
await act(async () => {
fireEvent.click(screen.getByRole('switch', {name: /Download the weather forecast from Open-Meteo/}));
});
expect(api.setWeatherSubscription).toHaveBeenCalledWith(true);
expect(screen.getByText('Downloading the forecast…')).toBeInTheDocument();
expect(screen.getByRole('button', {name: 'Download now'})).toBeDisabled();
});
test('shows the forecast kept, and whether it is recent enough for bursts now', async () => {
const done = {status: 'complete', last_successful_download: new Date().toISOString(),
next_download: new Date(Date.now() + 24 * hour).toISOString()};
api.getWeather.mockResolvedValue({...WEATHER_OFF, enabled: true, download: done, field: field(-5, 90)});
api.downloadWeatherNow.mockResolvedValue({...WEATHER_OFF, enabled: true, download: {...done, status: 'new'}});
const {unmount} = renderAt('/map/manage');
await act(async () => {
});
expect(screen.getByText(/Forecast kept: .* 160 places every 1°, 5.0 MB/)).toBeInTheDocument();
expect(screen.getByText(/It has the winds for bursts now/)).toBeInTheDocument();
expect(screen.getByText(/Last downloaded .*\. Next /)).toBeInTheDocument();
await act(async () => {
fireEvent.click(screen.getByRole('button', {name: 'Download now'}));
});
expect(api.downloadWeatherNow).toHaveBeenCalled();
unmount();
// Ending a day from now: too old for bursts now.
api.getWeather.mockResolvedValue({...WEATHER_OFF, enabled: true,
download: {status: 'failed', error: 'The forecast service answered HTTP 500'}, field: field(-60, 24)});
renderAt('/map/manage');
await act(async () => {
});
expect(screen.getByText(/It is too old for bursts now/)).toBeInTheDocument();
expect(screen.getByText(/The last download failed: The forecast service answered HTTP 500/)).toBeInTheDocument();
});
test('says when there are no targets to download around', async () => {
api.getWeather.mockResolvedValue({...WEATHER_OFF, targets: 0, spacing: null, points: null});
renderAt('/map/manage');
await act(async () => {
});
expect(screen.getByText(/No nuclear targets are saved/)).toBeInTheDocument();
});
});

View file

@ -1,4 +1,4 @@
import React, {useCallback, useContext, useEffect, useRef, useState} from "react";
import React, {useCallback, useContext, useEffect, useMemo, useRef, useState} from "react";
import {useNavigate, useSearchParams} from "react-router";
import maplibregl from "maplibre-gl";
import "maplibre-gl/dist/maplibre-gl.css";
@ -12,7 +12,9 @@ import {
getMapQuadName,
getMapFiles,
getMapPins,
getMapTargets,
searchMap,
saveMapTargets,
setMapDefaultLocation,
} from "../api";
import {MAP_VIEWER_URI} from "./Vars";
@ -28,6 +30,7 @@ import {mapFlavor, mapSprite} from "../themes/names";
import {poiPopupHtml} from "./mapPoiPopup";
import {solarCalculatorPath} from "./calculators/solar";
import {
escapeHtml,
addOverlaysToStyle,
labelsOverGround,
buildOverlayLayers,
@ -51,6 +54,8 @@ import {
} from "./mapOverlays";
import {addMissingOverlayIcon, loadOverlayStyles, OVERLAY_ICONS_SPRITE_ID} from "./mapOverlayStyle";
import MapQuadPicker, {QUAD_LAYER_PREFIX} from "./MapQuadPicker";
import FalloutPanel, {targetsUnsaved, WeaponPicker, withSavedTargets, withWeapon} from "./FalloutPanel";
import {DEFAULT_WEAPON} from "../map-shared/fallout/targets.js";
import {contourInterval, contourThresholds, DEFAULT_TERRAIN_MAX_ZOOM, terrainMaxZoom} from "../map-shared/terrain.js";
import {quadAt} from "./mapQuads";
import {
@ -509,9 +514,17 @@ function LayerControl({
const PIN_COLORS = ["red", "blue", "green", "yellow", "orange", "purple"];
function AddPinDialog({lat, lon, onSubmit, onCancel}) {
// A button in a marker's popup (which is HTML), calling `onclick`.
const popupButton = (onclick, text, color) => `<button onclick="${onclick}" `
+ `style="margin-top:4px;margin-right:4px;padding:2px 8px;cursor:pointer;color:${color};`
+ `border:1px solid ${color};background:none;border-radius:3px;">${text}</button>`;
function AddPinDialog({lat, lon, target = false, weapon: initialWeapon = null, onSubmit, onCancel}) {
const [label, setLabel] = useState("");
const [color, setColor] = useState("red");
// A target's weapon, kept with it.
const [weapon, setWeapon] = useState(initialWeapon || {weapon: DEFAULT_WEAPON});
const submit = () => label.trim() && onSubmit(label.trim(), color, target ? weapon : null);
// A floating dialog over the canvas — page chrome, not map data, so it is never
// filtered and keeps flat, bordered surfaces like the rest of the app (no shadow).
@ -520,17 +533,23 @@ function AddPinDialog({lat, lon, onSubmit, onCancel}) {
zIndex: 1002, background: "var(--panel)", border: "1px solid var(--border)", color: "var(--text)",
padding: "1rem", minWidth: "15.625rem",
}}>
<div style={{fontWeight: 600, marginBottom: "0.5rem"}}>Add Pin</div>
<div style={{fontWeight: 600, marginBottom: "0.5rem"}}>{target ? "Add Target" : "Add Pin"}</div>
{target && <div style={{fontSize: '0.75rem', color: "var(--muted)", marginBottom: "0.5rem"}}>
A likely detonation site, tried out until you save the targets.
</div>}
<div style={{fontSize: '0.75rem', color: "var(--muted)", marginBottom: "0.5rem"}}>{lat.toFixed(4)}, {lon.toFixed(4)}</div>
<TextInput
placeholder="Label"
value={label}
onChange={e => setLabel(e.target.value)}
autoFocus
onKeyDown={e => e.key === "Enter" && label.trim() && onSubmit(label.trim(), color)}
onKeyDown={e => e.key === "Enter" && submit()}
style={{marginBottom: "0.5rem"}}
/>
<div style={{display: "flex", gap: "0.375rem", marginBottom: "0.75rem"}}>
{target && <div style={{marginBottom: "0.5rem"}}>
<WeaponPicker label="Weapon" value={weapon} onChange={setWeapon}/>
</div>}
{!target && <div style={{display: "flex", gap: "0.375rem", marginBottom: "0.75rem"}}>
{PIN_COLORS.map(c =>
<div
key={c}
@ -541,13 +560,13 @@ function AddPinDialog({lat, lon, onSubmit, onCancel}) {
}}
/>
)}
</div>
</div>}
<div style={{display: "flex", gap: "0.5rem", justifyContent: "flex-end"}}>
<Button role='cancel' size='sm' onClick={onCancel}>Cancel</Button>
<Button
role='primary'
size='sm'
onClick={() => label.trim() && onSubmit(label.trim(), color)}
onClick={submit}
disabled={!label.trim()}
>
Add
@ -721,8 +740,28 @@ export default function MapViewer() {
const [error, setError] = useState(null);
const [contextMenu, setContextMenu] = useState(null);
const navigate = useNavigate();
const [addingPin, setAddingPin] = useState(null); // {lat, lon} when pin dialog is open
const [addingPin, setAddingPin] = useState(null); // {lat, lon, kind} when pin dialog is open
// Nuclear mode: targets (likely detonation sites) are shown, pins added are targets, and fallout
// can be simulated.
const [nuclear, setNuclear] = useState(false);
const nuclearRef = useRef(false);
const nuclearButtonRef = useRef(null);
// The fallout view (nuclear mode): open or not.
const [falloutOpen, setFalloutOpen] = useState(false);
// The saved nuclear targets (map_nuclear.yaml).
const [savedTargets, setSavedTargets] = useState([]);
const markersRef = useRef([]);
// Nuclear mode's targets, those simulated ({key, id (if saved), lat, lon, label, weapon, ...}):
// tried out, and the saved ones once loaded. `loadedIds` are the ids the saved targets had when
// they were loaded (null until then): saving replaces them, so it is refused until they are.
const [targets, setTargets] = useState([]);
const [loadedIds, setLoadedIds] = useState(null);
const nextTargetKey = useRef(1);
const targetMarkersRef = useRef([]);
// Placing a target: the next click on the map is where it is. The ref tells the map's own click
// handlers to stand by.
const [placingTarget, setPlacingTarget] = useState(false);
const placingTargetRef = useRef(false);
const pinsVisibleRef = useRef(true);
// Choosing a quadrangle to export: null, or {quad} (the quadrangle to start with, if any). While
// choosing, a click on the map chooses, so the ref tells the map's own click handlers to stand by.
@ -859,11 +898,8 @@ export default function MapViewer() {
pinToggle.style.cssText = "font-size:18px;width:29px;height:29px;border:none;cursor:pointer;background:white;border-radius:4px;display:flex;align-items:center;justify-content:center;";
pinToggle.addEventListener("click", () => {
pinsVisibleRef.current = !pinsVisibleRef.current;
const display = pinsVisibleRef.current ? "" : "none";
pinToggle.style.opacity = pinsVisibleRef.current ? "1" : "0.5";
for (const m of markersRef.current) {
m.getElement().style.display = display;
}
showPins();
});
const pinControl = {
onAdd: () => {
@ -898,6 +934,29 @@ export default function MapViewer() {
onRemove: () => {},
}, "top-right");
// Nuclear mode: targets, and fallout.
const nuclearButton = document.createElement("button");
nuclearButton.type = "button";
nuclearButton.title = "Nuclear mode: targets and fallout";
nuclearButton.setAttribute("aria-label", "Nuclear mode");
nuclearButton.setAttribute("aria-pressed", "false");
nuclearButton.textContent = "☢️";
nuclearButton.style.cssText = pinToggle.style.cssText;
nuclearButton.addEventListener("click", () => {
if (destroyed) return;
setNuclear(on => !on);
});
nuclearButtonRef.current = nuclearButton;
map.addControl({
onAdd: () => {
const container = document.createElement("div");
container.className = "maplibregl-ctrl maplibregl-ctrl-group";
container.appendChild(nuclearButton);
return container;
},
onRemove: () => {},
}, "top-right");
// Right-click context menu (desktop).
map.on("contextmenu", (e) => {
if (destroyed) return;
@ -926,7 +985,7 @@ export default function MapViewer() {
const featuresAt = (point, layers) =>
layers.length ? map.queryRenderedFeatures(point, {layers}) : [];
map.on("click", (e) => {
if (destroyed || pickingQuadRef.current) return;
if (destroyed || pickingQuadRef.current || placingTargetRef.current) return;
const html = overlayPopupHtml(featuresAt(e.point, overlayLayerIds()))
|| poiPopupHtml(featuresAt(e.point, poiLayerIds()), e.lngLat);
if (!html) return;
@ -937,7 +996,7 @@ export default function MapViewer() {
});
map.on("mousemove", (e) => {
if (destroyed) return;
if (pickingQuadRef.current) {
if (pickingQuadRef.current || placingTargetRef.current) {
map.getCanvas().style.cursor = "crosshair";
return;
}
@ -1098,6 +1157,26 @@ export default function MapViewer() {
if (map) map.getCanvas().style.cursor = pickingQuad ? "crosshair" : "";
}, [pickingQuad]);
// Placing a target: a click on the map opens the dialog which adds it there; Escape stops.
useEffect(() => {
placingTargetRef.current = placingTarget;
const map = mapRef.current;
if (!map || !placingTarget) return;
map.getCanvas().style.cursor = "crosshair";
const onClick = (e) => {
setPlacingTarget(false);
setAddingPin({lat: e.lngLat.lat, lon: e.lngLat.lng, kind: "target"});
};
const onKey = (e) => e.key === "Escape" && setPlacingTarget(false);
map.on("click", onClick);
document.addEventListener("keydown", onKey);
return () => {
map.off("click", onClick);
document.removeEventListener("keydown", onKey);
map.getCanvas().style.cursor = "";
};
}, [placingTarget]);
const handleExportQuad = useCallback(() => {
if (!contextMenu) return;
// Start with the quadrangle which was clicked; not while another is being exported.
@ -1207,6 +1286,15 @@ export default function MapViewer() {
}, []);
// --- Pins ---
// Show the pins the toggle and the mode allow: pins while pins are shown, and targets only in
// nuclear mode too.
const showPins = useCallback(() => {
for (const m of [...markersRef.current, ...targetMarkersRef.current]) {
const shown = pinsVisibleRef.current && (!m.wrolpiTarget || nuclearRef.current);
m.getElement().style.display = shown ? "" : "none";
}
}, []);
const loadPins = useCallback(async () => {
const map = mapRef.current;
if (!map) return;
@ -1218,8 +1306,9 @@ export default function MapViewer() {
const data = await getMapPins();
if (!data?.pins) return;
data.pins.forEach((pin, index) => {
data.pins.forEach((pin) => {
const el = document.createElement("div");
el.style.cursor = "pointer";
el.style.width = "24px";
el.style.height = "24px";
el.style.borderRadius = "50% 50% 50% 0";
@ -1227,29 +1316,101 @@ export default function MapViewer() {
el.style.border = "2px solid white";
el.style.boxShadow = "0 1px 4px rgba(0,0,0,0.4)";
el.style.transform = "rotate(-45deg)";
el.style.cursor = "pointer";
const popup = new maplibregl.Popup({offset: 15}).setHTML(
`<div style="font-size:13px">` +
`<strong>${pin.label || "Pin"}</strong><br/>` +
`<strong>${escapeHtml(pin.label || "Pin")}</strong><br/>` +
`<small>${pin.lat.toFixed(4)}, ${pin.lon.toFixed(4)}</small><br/>` +
`<button onclick="window.__deleteMapPin(${pin.id})" ` +
`style="margin-top:4px;padding:2px 8px;cursor:pointer;color:red;border:1px solid red;background:none;border-radius:3px;">` +
`Delete</button></div>`
popupButton(`window.__deleteMapPin(${pin.id})`, "Delete", "red") +
`</div>`
);
const marker = new maplibregl.Marker({element: el})
.setLngLat([pin.lon, pin.lat])
.setPopup(popup)
.addTo(map);
if (!pinsVisibleRef.current) {
marker.getElement().style.display = "none";
}
markersRef.current.push(marker);
});
showPins();
}, [showPins]);
// The targets simulated, on the map in nuclear mode.
useEffect(() => {
const map = mapRef.current;
for (const m of targetMarkersRef.current) m.remove();
targetMarkersRef.current = [];
if (!mapReady || !map || !nuclear) return;
for (const t of targets) {
const el = document.createElement("div");
el.textContent = "☢";
el.style.cssText = "cursor:pointer;width:26px;height:26px;border-radius:50%;background:#ffd43b;"
+ "color:#000;border:2px solid #000;box-shadow:0 1px 4px rgba(0,0,0,0.4);display:flex;"
+ "align-items:center;justify-content:center;font-size:18px;line-height:1;"
+ (t.id ? "" : "border-style:dashed;");
const popup = new maplibregl.Popup({offset: 15}).setHTML(
`<div style="font-size:13px">` +
`<strong>${escapeHtml(t.label || "Target")}</strong><br/>` +
`<small>${t.id ? "Target" : "Target, not saved"}</small><br/>` +
`<small>${t.lat.toFixed(4)}, ${t.lon.toFixed(4)}</small><br/>` +
popupButton(`window.__removeTarget('${t.key}')`, "Remove", "red") +
`</div>`
);
const marker = new maplibregl.Marker({element: el}).setLngLat([t.lon, t.lat]).setPopup(popup).addTo(map);
marker.wrolpiTarget = true;
targetMarkersRef.current.push(marker);
}
showPins();
}, [mapReady, nuclear, targets, showPins]);
// Whether the targets simulated differ from the saved ones.
const unsaved = useMemo(() => targetsUnsaved(targets, savedTargets, loadedIds !== null),
[targets, savedTargets, loadedIds]);
// The saved targets join those being tried out.
const handleLoadTargets = useCallback(() => {
setTargets((tried) => withSavedTargets(savedTargets, tried));
setLoadedIds(savedTargets.map((t) => t.id));
}, [savedTargets]);
// The targets simulated, saved in place of the saved ones.
const handleSaveTargets = useCallback(async () => {
const plain = targets.map(({key, ...t}) => t);
const saved = await saveMapTargets(plain, loadedIds || []);
if (!saved) return;
setSavedTargets(saved);
setTargets(withSavedTargets(saved, []));
setLoadedIds(saved.map((t) => t.id));
}, [targets, loadedIds]);
const handleRemoveTarget = useCallback((target) => {
setTargets((list) => list.filter((t) => t.key !== target.key));
}, []);
useEffect(() => {
window.__removeTarget = (key) => setTargets((list) => list.filter((t) => t.key !== key));
return () => { delete window.__removeTarget; };
}, []);
const handleTargetWeapon = useCallback((target, weapon) => {
setTargets((list) => list.map((t) => t.key === target.key ? withWeapon(t, weapon) : t));
}, []);
const handleAllTargetsWeapon = useCallback((weapon) => {
setTargets((list) => list.map((t) => withWeapon(t, weapon)));
}, []);
// Nuclear mode on or off: the button says so, targets are shown or hidden, and leaving it closes
// the fallout simulation.
useEffect(() => {
nuclearRef.current = nuclear;
const button = nuclearButtonRef.current;
if (button) {
button.style.background = nuclear ? "#ffd43b" : "white";
button.setAttribute("aria-pressed", String(nuclear));
}
showPins();
// Nuclear mode opens the fallout panel on its targets step; leaving it closes the panel.
setFalloutOpen(nuclear);
if (!nuclear) setPlacingTarget(false);
}, [nuclear, showPins]);
// Global callback for popup delete buttons.
useEffect(() => {
window.__deleteMapPin = async (pinId) => {
@ -1259,6 +1420,16 @@ export default function MapViewer() {
return () => { delete window.__deleteMapPin; };
}, [loadPins]);
// The saved targets, when nuclear mode is first used.
useEffect(() => {
if (!nuclear) return;
let cancelled = false;
getMapTargets().then((saved) => !cancelled && saved && setSavedTargets(saved));
return () => {
cancelled = true;
};
}, [nuclear]);
// Load pins when map is ready.
useEffect(() => {
if (mapReady) loadPins();
@ -1266,9 +1437,9 @@ export default function MapViewer() {
const handleAddPin = useCallback(() => {
if (!contextMenu) return;
setAddingPin({lat: contextMenu.lat, lon: contextMenu.lon});
setAddingPin({lat: contextMenu.lat, lon: contextMenu.lon, kind: nuclear ? "target" : "pin"});
setContextMenu(null);
}, [contextMenu]);
}, [contextMenu, nuclear]);
const handleSolar = useCallback(() => {
if (!contextMenu) return;
@ -1286,10 +1457,16 @@ export default function MapViewer() {
setContextMenu(null);
}, [fetchSettings]);
const handleSubmitPin = useCallback(async (label, color) => {
const handleSubmitPin = useCallback(async (label, color, weapon) => {
if (!addingPin) return;
const {lat, lon} = addingPin;
const {lat, lon, kind} = addingPin;
setAddingPin(null); // Prevent double-submit.
// A target is tried out until the targets are saved.
if (kind === "target") {
const key = `new-${nextTargetKey.current++}`;
setTargets((list) => [...list, {key, lat, lon, label, ...weapon}]);
return;
}
await addMapPin(lat, lon, label, color);
await loadPins();
}, [addingPin, loadPins]);
@ -1370,7 +1547,7 @@ export default function MapViewer() {
onMouseLeave={e => e.target.style.background = "transparent"}
onClick={handleAddPin}
>
Add Pin Here
{nuclear ? "Add Target Here" : "Add Pin Here"}
</div>
<div
style={{padding: "0.5rem 0.75rem", cursor: "pointer", userSelect: "none"}}
@ -1406,9 +1583,29 @@ export default function MapViewer() {
setPickingQuad(null);
}}
/>}
{mapReady && nuclear && falloutOpen && <FalloutPanel
map={mapRef.current}
targets={targets}
savedCount={savedTargets.length}
loaded={loadedIds !== null}
unsaved={unsaved}
onLoad={handleLoadTargets}
onSave={handleSaveTargets}
onRemoveTarget={handleRemoveTarget}
onTargetWeapon={handleTargetWeapon}
onAllTargetsWeapon={handleAllTargetsWeapon}
placingTarget={placingTarget}
onPlaceTarget={setPlacingTarget}
onClose={() => {
setPlacingTarget(false);
setFalloutOpen(false);
}}
/>}
{addingPin && <AddPinDialog
lat={addingPin.lat}
lon={addingPin.lon}
target={addingPin.kind === "target"}
weapon={addingPin.weapon}
onSubmit={handleSubmitPin}
onCancel={() => setAddingPin(null)}
/>}

View file

@ -0,0 +1,112 @@
import React, {useCallback, useEffect, useState} from "react";
import {downloadWeatherNow, getWeather, setWeatherSubscription} from "../api";
import {ErrorMessage, humanFileSize} from "./Common";
import {Button, Header, Toggle} from "./ui";
import {LANDING_HOURS} from "../map-shared/fallout/winds.js";
// The weather subscription: a forecast of the winds aloft around the saved nuclear targets,
// downloaded every day (a recurring Download), for the fallout simulator.
// How often (ms) the subscription is asked again while it downloads.
const REFRESH_MS = 10000;
// Whether a download of the weather is waiting or running.
export const weatherDownloading = (weather) => ['new', 'pending'].includes(weather?.download?.status);
// The weather subscription, asked again while it downloads: {weather (null while pending, undefined
// when it could not be fetched), downloading, setEnabled(enabled), downloadNow()}.
export function useWeather() {
const [weather, setWeather] = useState(null);
const refresh = useCallback(async () => setWeather(await getWeather()), []);
useEffect(() => {
refresh();
}, [refresh]);
const downloading = weatherDownloading(weather);
useEffect(() => {
if (!downloading) return;
const timer = setInterval(refresh, REFRESH_MS);
return () => clearInterval(timer);
}, [downloading, refresh]);
const setEnabled = async (enabled) => {
const changed = await setWeatherSubscription(enabled);
if (changed) setWeather(changed);
};
const downloadNow = async () => {
const changed = await downloadWeatherNow();
if (changed) setWeather(changed);
};
return {weather, downloading, setEnabled, downloadNow};
}
// Whether the forecast kept (`field`, as the subscription tells it) has the winds for bursts now,
// until all their fallout is down.
export function fieldCoversNow(field, when = new Date()) {
if (!field) return false;
const first = Date.parse(field.first_hour), last = Date.parse(field.last_hour);
return first <= when.getTime() + 3600000 && last >= when.getTime() + LANDING_HOURS * 3600000;
}
// About how long a download takes, as the user reads it.
export const downloadTime = (seconds) => !seconds || seconds < 60 ? "about a minute"
: `about ${Math.round(seconds / 60) + 1} minutes`;
const when = (time) => time ? new Date(time).toLocaleString(undefined, {
weekday: "short", month: "short", day: "numeric", hour: "numeric", minute: "2-digit",
}) : null;
// The Manage tab's section for the weather subscription: turning it on or off, what it downloads,
// how its downloads have gone, and the forecast kept.
export function WeatherSection() {
const {weather, downloading, setEnabled, downloadNow} = useWeather();
const muted = {color: "var(--muted)", fontSize: "0.875rem"};
const warning = {color: "var(--warning)", fontSize: "0.875rem"};
const header = <Header as='h3'>Weather</Header>;
if (weather === undefined) return <>{header}<ErrorMessage>Could not fetch the weather subscription</ErrorMessage></>;
if (!weather) return header;
const {download, field} = weather;
const failed = download && ['failed', 'deferred'].includes(download.status) && download.error;
return <>
{header}
<Toggle label="Download the weather forecast from Open-Meteo every day" checked={weather.enabled}
onChange={(e) => setEnabled(e.currentTarget.checked)}/>
<div style={muted}>
The winds aloft, hour by hour for four days, around the saved nuclear targets: the fallout simulator
carries fallout by them. Open-Meteo is told only places on whole degrees, never a target.
</div>
{weather.targets === 0
? <div style={warning}>
No nuclear targets are saved, so there is nowhere to download the forecast around. Save some in
nuclear mode (☢) on the map.
</div>
: <div style={muted}>
Around {weather.targets === 1 ? "1 target" : `${weather.targets} targets`}: {weather.points} places
every {weather.spacing}°, which takes {downloadTime(weather.seconds)} to download.
</div>}
{weather.enabled && <div style={{marginTop: "0.5rem"}}>
{downloading && <div>Downloading the forecast…</div>}
{download?.last_successful_download && <div style={muted}>
Last downloaded {when(download.last_successful_download)}.
{download.next_download && !downloading && ` Next ${when(download.next_download)}.`}
</div>}
{failed && <div style={warning}>The last download failed: {download.error}</div>}
<Button size='xs' style={{marginTop: "0.25rem"}} disabled={downloading || weather.targets === 0}
onClick={downloadNow}>Download now</Button>
</div>}
<div style={{marginTop: "0.5rem"}}>
{field
? <>
<div>
Forecast kept: {when(field.first_hour)} to {when(field.last_hour)}, {field.points} places
every {field.spacing}°, {humanFileSize(field.size)}.
</div>
{fieldCoversNow(field)
? <div style={muted}>It has the winds for bursts now, until their fallout is down.</div>
: <div style={warning}>
It is too old for bursts now: their fallout comes down over {LANDING_HOURS} hours, past
its end. {weather.enabled ? "Download it again." : "Turn on the download to get a new one."}
</div>}
</>
: <div style={muted}>No forecast has been downloaded.</div>}
</div>
</>;
}

View file

@ -0,0 +1,128 @@
import {PMTiles} from "pmtiles";
import {getMapFiles} from "../api";
import {mediaUrl} from "./mapOverlays";
// The ground under a fallout plume, read from the terrain files the user has downloaded (terrarium
// elevation tiles), as an elevation grid the model reads (map-shared/fallout/terrain.js).
// No more tiles than this are read for one plume; a wider plume is read at a coarser zoom.
const MAX_TILES = 36;
// Deeper than this adds nothing: a spot of fallout is at least a kilometer across.
const DEEPEST_ZOOM = 9;
// How many samples the grid has along its longer side.
const GRID_SAMPLES = 600;
function tileX(lon, z) {
return Math.floor((lon + 180) / 360 * 2 ** z);
}
// The tile column `x` names at zoom `z`, wrapped around the antimeridian.
function wrapTileX(x, z) {
const n = 2 ** z;
return ((x % n) + n) % n;
}
function tileY(lat, z) {
const r = lat * Math.PI / 180;
return Math.floor((1 - Math.log(Math.tan(r) + 1 / Math.cos(r)) / Math.PI) / 2 * 2 ** z);
}
async function decodeTile(data) {
const bitmap = await createImageBitmap(new Blob([data]));
const canvas = document.createElement("canvas");
canvas.width = bitmap.width;
canvas.height = bitmap.height;
const context = canvas.getContext("2d", {willReadFrequently: true});
context.drawImage(bitmap, 0, 0);
return context.getImageData(0, 0, bitmap.width, bitmap.height);
}
let terrainFiles = null;
// The terrain files, finest first: [{tiles (PMTiles), header}].
async function openTerrainFiles() {
if (terrainFiles) return terrainFiles;
const data = await getMapFiles();
const files = (data?.files || []).filter((f) => f.kind === "terrain");
const opened = await Promise.all(files.map(async (f) => {
const tiles = new PMTiles(`${window.location.origin}${mediaUrl(f.path)}`);
return {tiles, header: await tiles.getHeader()};
}));
terrainFiles = opened.sort((a, b) => b.header.maxZoom - a.header.maxZoom);
return terrainFiles;
}
// The terrarium elevation (m) at `lon`, `lat` of the read tiles, or null where none was read.
function sample(tiles, n, lon, lat) {
const r = lat * Math.PI / 180;
// A plume may cross the antimeridian: longitudes wrap.
const fx = ((((lon + 180) % 360) + 360) % 360) / 360 * n;
const fy = (1 - Math.log(Math.tan(r) + 1 / Math.cos(r)) / Math.PI) / 2 * n;
const image = tiles.get(`${Math.floor(fx)}/${Math.floor(fy)}`);
if (!image) return null;
const px = Math.min(Math.floor((fx % 1) * image.width), image.width - 1);
const py = Math.min(Math.floor((fy % 1) * image.height), image.height - 1);
const p = (py * image.width + px) * 4;
const d = image.data;
// Terrarium: meters = R * 256 + G + B / 256 - 32768. Below sea level is the sea floor, mostly:
// fallout lands on the water.
const meters = d[p] * 256 + d[p + 1] + d[p + 2] / 256 - 32768;
return Number.isFinite(meters) ? Math.max(0, meters) : null;
}
// An elevation grid over `bounds` ([west, south, east, north], degrees) around ground zero at `lon`,
// `lat`, or null when no terrain file covers ground zero. Where no file covers the grid, it is as
// high as ground zero (flat ground, as the model takes it without terrain). {grid, zoom, coverage
// (share of samples read from a file)}.
export async function loadTerrainGrid(bounds, lon, lat) {
const files = await openTerrainFiles();
if (!files.length) return null;
// Web Mercator tiles end at 85 degrees.
const [west, east] = [bounds[0], bounds[2]];
const [south, north] = [Math.max(bounds[1], -85), Math.min(bounds[3], 85)];
const covering = files.filter(({header: h}) =>
h.minLon < east && h.maxLon > west && h.minLat < north && h.maxLat > south);
if (!covering.length) return null;
let zoom = Math.min(DEEPEST_ZOOM, Math.max(...covering.map((f) => f.header.maxZoom)));
const count = (z) => (tileX(east, z) - tileX(west, z) + 1) * (tileY(south, z) - tileY(north, z) + 1);
while (zoom > 0 && count(zoom) > MAX_TILES) zoom--;
// Each tile from the finest file which has it.
const tiles = new Map();
const reads = [];
for (let x = tileX(west, zoom); x <= tileX(east, zoom); x++) {
for (let y = tileY(north, zoom); y <= tileY(south, zoom); y++) {
reads.push((async () => {
for (const {tiles: file, header} of covering) {
if (header.maxZoom < zoom) continue;
const tile = await file.getZxy(zoom, wrapTileX(x, zoom), y);
if (tile?.data) {
tiles.set(`${wrapTileX(x, zoom)}/${y}`, await decodeTile(tile.data));
return;
}
}
})());
}
}
await Promise.all(reads);
if (!tiles.size) return null;
const n = 2 ** zoom;
const groundZero = sample(tiles, n, lon, lat);
if (groundZero === null) return null;
const step = Math.max(east - west, north - south) / GRID_SAMPLES;
const nx = Math.ceil((east - west) / step) + 1;
const ny = Math.ceil((north - south) / step) + 1;
const values = new Float32Array(nx * ny);
let read = 0;
for (let j = 0; j < ny; j++) {
for (let i = 0; i < nx; i++) {
const v = sample(tiles, n, west + i * step, south + j * step);
values[j * nx + i] = v === null ? groundZero : v;
if (v !== null) read++;
}
}
return {grid: {west, south, step, nx, ny, values}, zoom, coverage: read / (nx * ny)};
}