hoi4-agent-tools 4.13.0 → 4.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/hoi4_agent_tools/map/operations.js +2 -1
  3. package/dist/hoi4_agent_tools/map/relief/painted-relief.js +2 -2
  4. package/dist/hoi4_agent_tools/map/relief/terrain-synthesis.js +25 -3
  5. package/dist/hoi4_agent_tools/map/tool-operations.js +5 -0
  6. package/dist/hoi4_agent_tools/map/world.js +229 -12
  7. package/dist/hoi4_agent_tools/reference/source-lookup.js +226 -74
  8. package/dist/hoi4_agent_tools/schemas/map.js +13 -0
  9. package/dist/hoi4_agent_tools/schemas/mod-tools.js +33 -0
  10. package/dist/hoi4_agent_tools/version.js +1 -1
  11. package/docs/map.md +2 -0
  12. package/engine/bin/darwin-arm64/hoi4-engine +0 -0
  13. package/engine/bin/linux-arm64/hoi4-engine +0 -0
  14. package/engine/bin/linux-x64/hoi4-engine +0 -0
  15. package/engine/bin/manifest.json +8 -8
  16. package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
  17. package/npm-shrinkwrap.json +2 -2
  18. package/package.json +1 -1
  19. package/schemas/configuration.schema.json +1 -1
  20. package/schemas/continuous-focus-palette.schema.json +1 -1
  21. package/schemas/custom-weighted-pool.schema.json +1 -1
  22. package/schemas/decision-inspect-input.schema.json +1 -1
  23. package/schemas/error-log-input.schema.json +1 -1
  24. package/schemas/event-feature-manifest.schema.json +1 -1
  25. package/schemas/focus-plan.schema.json +1 -1
  26. package/schemas/focus-planning-sidecar.schema.json +1 -1
  27. package/schemas/geography-model.schema.json +1 -1
  28. package/schemas/gui-animation-source.schema.json +1 -1
  29. package/schemas/gui-helper.schema.json +1 -1
  30. package/schemas/gui-scenario.schema.json +1 -1
  31. package/schemas/helper-expansion-request.schema.json +1 -1
  32. package/schemas/helper-expansion-summary.schema.json +1 -1
  33. package/schemas/impact-inspect-input.schema.json +1 -1
  34. package/schemas/map-operation.schema.json +174 -138
  35. package/schemas/mechanic-test-input.schema.json +1 -1
  36. package/schemas/mod-index-input.schema.json +1 -1
  37. package/schemas/operation-result.schema.json +1 -1
  38. package/schemas/package-check-input.schema.json +1 -1
  39. package/schemas/package-manifest.schema.json +1 -1
  40. package/schemas/probability-analysis-result.schema.json +1 -1
  41. package/schemas/probability-compare-input.schema.json +1 -1
  42. package/schemas/probability-evaluate-input.schema.json +1 -1
  43. package/schemas/probability-inspect-input.schema.json +1 -1
  44. package/schemas/probability-render-input.schema.json +1 -1
  45. package/schemas/probability-scenario-set.schema.json +1 -1
  46. package/schemas/probability-sequence-input.schema.json +1 -1
  47. package/schemas/probability-simulate-input.schema.json +1 -1
  48. package/schemas/probability-sweep-input.schema.json +1 -1
  49. package/schemas/reference-context-input.schema.json +1 -1
  50. package/schemas/reference-read-input.schema.json +1 -1
  51. package/schemas/reference-search-input.schema.json +1 -1
  52. package/schemas/reference-sheets.schema.json +1 -1
  53. package/schemas/scenario-suite.schema.json +1 -1
  54. package/schemas/scenario-test-input.schema.json +1 -1
  55. package/schemas/script-validate-input.schema.json +1 -1
  56. package/schemas/shared-scenario.schema.json +1 -1
  57. package/schemas/source-lookup-input.schema.json +1 -1
  58. package/server.json +2 -2
package/CHANGELOG.md CHANGED
@@ -2,6 +2,16 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 4.15.0 - 2026-11-09
6
+
7
+ - Add `create_world.permanentSnow.paintedHeight`. Painted mountains, volcanoes and impassable land put permanent snow above a snow line of their own (232 at the equator to 140 at the poles), which `permanentSnow` did not reach: a ZIN write on 9 November with `iceCapLatitude` 0.97 and `peakHeight` 230 still had 15.37% of its land permanent (804,575 pixels, 20 times the base game's share), of which only about 69,000 were drawn snow. `paintedHeight` (a heightmap value) keeps that line at or above its height, and 256 removes it. `MAP_PERMANENT_SNOW_SHARE` and `MAP_PERMANENT_SNOW_ESTIMATE` gain `bySource`, the permanent pixels above range snow lines, above painted snow lines and on drawn snow, and their warning names the setting of the largest source. Requests without `paintedHeight` write the same files as before.
8
+ - `create_world.synthesisCheck` estimates the permanent-snow share of the write. `MAP_PERMANENT_SNOW_SHARE` came only from the terrain writer, so ZIN could try `permanentSnow` thresholds only through 28-minute writes. The check now applies the writer's rule (snow lines, then drawn snow on ice caps and at `peakHeight` and up) to the half-resolution relief it already builds, and reports `MAP_PERMANENT_SNOW_ESTIMATE` with the same details plus `estimate: true`, also under `synthesisCheck.permanentSnow` per operation. On a 1,024 by 512 test world the estimate was within 1% of the written share. The note is a warning above four times the base game's share, as at the write; a warning does not block the check.
9
+ - Answer `hoi4.source_lookup` from the shared Rust engine when it is asked for no references (`includeReferences: false`), as `hoi4.mod_index` already is (ADR 0082, maintainer decision M-8, first step of issue 107). The engine finds the definitions, their first and last line, the scan revision (the same value the TypeScript scan computes, so `expectedRevision` from any tool still matches) and the near names of a miss; the server reads only the chosen files, only from inside a configured root, and refuses one whose SHA-256 differs from the scan's with `SOURCE_REVISION_STALE`. A missing or failing engine answers `ENGINE_UNAVAILABLE` with no TypeScript fallback for these requests. A lookup that includes references (the default) and a lookup by file and line still answer from the TypeScript scan until the reference extraction moves too, and no input schema changed.
10
+
11
+ ## 4.14.0 - 2026-11-09
12
+
13
+ - `create_world` no longer turns drawn snow into permanent snow. Every reference pixel drawn as snow became the permanent-snow terrain (`terrain.bmp` index 19), and the game drew it as bright blue ice: ZIN's Cold Lands, seen on 9 November, had about a hundred times the base game's share. Drawn snow is now ordinary land (plains, as in play) with seasonal snow, as the base game's northern lands are. Permanent snow stays on ice caps (drawn snow in the tenth of rows nearest each pole, index 19, where the base game keeps it), drawn snow on high ground (height 150 and up, index 16) and above the snow lines of ranges and painted mountains (index 16). A strategic region drawn mostly as snow takes the weather of at least latitude 0.7 (on the map's 0 to 1 scale), so its winters bring snow wherever it lies. The new `create_world.permanentSnow` moves the thresholds (`{ iceCapLatitude, peakHeight }`, defaults 0.8 and 150) or, with `"snowlines"`, keeps permanent snow only above the snow lines: on ZIN's picture the defaults still leave 9.46% of the land permanent, because its inhabited Cold Lands fill the top rows. `MAP_PERMANENT_SNOW_SHARE` reports the permanent-snow share of the land against the base game's 0.76% (33,254 of 4,353,170 land pixels in 1.19.4.2), counting the `rim` and `wall` seam ranges apart, with the thresholds used, and is a warning above four times that share. Snow lines in a reference world now use the base game's snowy mountain entry (16) instead of 19; worlds without a reference picture are unchanged.
14
+
5
15
  ## 4.13.0 - 2026-11-08
6
16
 
7
17
  - `create_world` with `edge.mode` `"wall"` or `"rim"` no longer writes `impassable` adjacency rows across the wrapping seam. The game does not wrap adjacencies and drew each of these rows as a crossing line between the two province centres, through the whole map: 596 red dashed lines on a 5,120-pixel ZIN world written with 4.11.1. Every land province on the first or last column now becomes an impassable state instead, linked and owned like the wall's states, so the seam stays closed without any row; in `rim` mode this makes the rim's seam provinces impassable states. Validation reports any adjacency row between provinces that touch only across the seam as `MAP_ADJACENCY_ACROSS_SEAM` (error), and `MAP_EDGE_RIM_ADJACENCIES` is no longer reported (ADR 0061 amendment).
@@ -7,7 +7,7 @@ import { rgbKey } from './bmp.js';
7
7
  import { MAP_MASK_CELL_LIMIT, MAP_POLYGON_WORK_LIMIT, MAP_SELECTED_OFFSET_BYTES, MAP_SELECTED_PIXEL_LIMIT, } from './limits.js';
8
8
  import { derivedStateCapital, encodeTextDocument, LEVEL_STATE_BUILDINGS, MapWorkspaceIndex, parseMapDate, parseTextDocument, } from './model.js';
9
9
  import { collectContinentReferences, droppedContinentDiagnostics, planReferenceRemap, ReferenceRemapError, } from './references.js';
10
- import { generateWorld } from './world.js';
10
+ import { generateWorld, } from './world.js';
11
11
  import { resolveEdge } from './world-edge.js';
12
12
  import { DEFAULT_AUTO_STRAIT_GAP_PX } from './gameplay/crossings.js';
13
13
  import { planMapPositions, planSupplyRebuild } from './derived.js';
@@ -3422,6 +3422,7 @@ function applyCreateWorld(base, changes, operation, context, signal) {
3422
3422
  ? {}
3423
3423
  : { continentNames: operation.continentNames }),
3424
3424
  ...(operation.inheritedContinents === 'drop' ? { inheritedContinents: 'drop' } : {}),
3425
+ ...(operation.permanentSnow === undefined ? {} : { permanentSnow: operation.permanentSnow }),
3425
3426
  startDate: operation.startDate ?? '1936.1.1',
3426
3427
  rivers: typeof operation.rivers === 'number' ? operation.rivers : reference === undefined ? 8 : 80,
3427
3428
  ...(geography === undefined
@@ -125,8 +125,8 @@ export function applyPaintedRelief(target, input) {
125
125
  if (weight > target.footprint[cell])
126
126
  target.footprint[cell] = weight;
127
127
  if (Math.max(m, v, i) > 0.25) {
128
- const snow = paintedSnowHeight(y, mh);
129
- if (snow < target.snowLine[cell])
128
+ const snow = Math.max(paintedSnowHeight(y, mh), input.snowFloor ?? 0);
129
+ if (snow < 255 && snow < target.snowLine[cell])
130
130
  target.snowLine[cell] = snow;
131
131
  }
132
132
  }
@@ -93,6 +93,10 @@ function barrierField(width, height, kind, heights, riverBitmap, macro, signal)
93
93
  * mouth throws as in `synthesizeTerrain`, with every failing river in its details.
94
94
  */
95
95
  export function checkTerrainRivers(input) {
96
+ return checkTerrainRiversWithRelief(input).notes;
97
+ }
98
+ /** `checkTerrainRivers`, also returning the half-resolution relief for estimates of the write. */
99
+ export function checkTerrainRiversWithRelief(input) {
96
100
  const { geography, width, height, seed, kind } = input;
97
101
  const relief = { ...DEFAULT_RELIEF, ...input.relief };
98
102
  let landPixels = 0;
@@ -108,6 +112,7 @@ export function checkTerrainRivers(input) {
108
112
  relief,
109
113
  signal: input.signal,
110
114
  });
115
+ const rangeSnowLine = macro.snowLine.slice();
111
116
  // The same painted relief as the full synthesis, so the rivers checked are the rivers written.
112
117
  if (input.painted !== undefined)
113
118
  applyPaintedRelief(macro, input.painted);
@@ -140,7 +145,16 @@ export function checkTerrainRivers(input) {
140
145
  for (const note of checkRangesAndFeatures(geography, macro.ranges, { width: macro.width, height: macro.height, kind: macro.kind, heights: quantised }, (peak) => peakHeight(peak, macro.scale), (peak) => peakHeight(peak, macro.scale)))
141
146
  if (note.code === 'MAP_PASS_NOT_LOWER')
142
147
  notes.push(note);
143
- return notes;
148
+ return {
149
+ notes,
150
+ relief: {
151
+ width: macro.width,
152
+ height: macro.height,
153
+ heights: hydrology.heights,
154
+ snowLine: macro.snowLine,
155
+ rangeSnowLine,
156
+ },
157
+ };
144
158
  }
145
159
  /** Build relief, hydrology, normals and fields for a geography model on a map of the given size. */
146
160
  export function synthesizeTerrain(input) {
@@ -163,6 +177,7 @@ export function synthesizeTerrain(input) {
163
177
  relief,
164
178
  signal: input.signal,
165
179
  });
180
+ const rangeSnowLine = macro.snowLine.slice();
166
181
  if (input.painted !== undefined) {
167
182
  const summary = applyPaintedRelief(macro, input.painted);
168
183
  notes.push({
@@ -224,6 +239,7 @@ export function synthesizeTerrain(input) {
224
239
  const heights = new Uint8Array(total);
225
240
  const elevation = new Float32Array(total);
226
241
  const snow = new Uint8Array(total);
242
+ const paintedSnow = new Uint8Array(total);
227
243
  for (let y = 0; y < height; y += 1) {
228
244
  if (y % 64 === 0)
229
245
  input.signal?.throwIfAborted();
@@ -236,9 +252,14 @@ export function synthesizeTerrain(input) {
236
252
  const quantised = Math.round(value);
237
253
  heights[index] = quantised;
238
254
  elevation[index] = Math.min(1, Math.max(0, (quantised - LAND_FLOOR) / 110));
239
- const line = macro.snowLine[(y >> 1) * macro.width + (x >> 1)];
240
- if (line < 255 && quantised >= line)
255
+ const cell = (y >> 1) * macro.width + (x >> 1);
256
+ const line = macro.snowLine[cell];
257
+ if (line < 255 && quantised >= line) {
241
258
  snow[index] = 1;
259
+ const range = rangeSnowLine[cell];
260
+ if (range === 255 || quantised < range)
261
+ paintedSnow[index] = 1;
262
+ }
242
263
  }
243
264
  else {
244
265
  const water = lakeHeight(landDistance[index]);
@@ -360,6 +381,7 @@ export function synthesizeTerrain(input) {
360
381
  riverOrder: raster.order,
361
382
  elevation,
362
383
  snow,
384
+ paintedSnow,
363
385
  fields,
364
386
  rivers: entries,
365
387
  riverPaths: paths,
@@ -574,6 +574,10 @@ async function previewSynthesisCheck(nudger, input, context) {
574
574
  : []);
575
575
  // Drawn rivers are authoritative: crossings of relief they cut through are warnings (ADR 0071).
576
576
  const carved = checked.diagnostics.flatMap(({ code, details }) => code === 'MAP_RIVER_CARVED_CROSSING' && details !== undefined ? [details] : []);
577
+ // The write's permanent-snow share, estimated on the check's relief, per operation.
578
+ const permanentSnow = checked.diagnostics.flatMap(({ code, operationId, details }) => code === 'MAP_PERMANENT_SNOW_ESTIMATE' && details !== undefined
579
+ ? [{ ...(operationId === undefined ? {} : { operationId }), ...details }]
580
+ : []);
577
581
  const compactSemantic = compactMapSemanticDiff(EMPTY_SEMANTIC_DIFF);
578
582
  const result = emptyServiceResult(context.workspaceId, {
579
583
  execution: 'preview',
@@ -590,6 +594,7 @@ async function previewSynthesisCheck(nudger, input, context) {
590
594
  geography: checked.geography.slice(0, 16).map(geographySummary),
591
595
  synthesisCheck: {
592
596
  passed: valid,
597
+ ...(permanentSnow.length === 0 ? {} : { permanentSnow: permanentSnow.slice(0, 16) }),
593
598
  unreachableRivers: rivers.length,
594
599
  rivers: rivers.slice(0, 200),
595
600
  carvedCrossings: carved.length,
@@ -27,7 +27,7 @@ import { landDistanceField, lakeHeight, normalizeLakes, waterColourLevel } from
27
27
  import { DEFAULT_PAINTED_RELIEF } from './relief/painted-relief.js';
28
28
  import { rowStrips, scanAreaStrip } from './geography/index.js';
29
29
  import { overlayGeographyLakes, rasterizeGeographyKind } from './relief/land.js';
30
- import { checkTerrainRivers, synthesizeTerrain, } from './relief/terrain-synthesis.js';
30
+ import { checkTerrainRiversWithRelief, synthesizeTerrain, } from './relief/terrain-synthesis.js';
31
31
  import { assignUnreachedRealmLand, checkRealmPoints, realmPointsError, resolveRealmRules, } from './world-realms.js';
32
32
  // ---------------------------------------------------------------------------------------------
33
33
  // Deterministic randomness and noise
@@ -258,6 +258,157 @@ function geographySurface(spec, geography, reference) {
258
258
  }
259
259
  return { kind, elevation: new Float32Array(total), moisture };
260
260
  }
261
+ /** Reference terrain code of drawn snow (`REFERENCE_TERRAIN.snow`). */
262
+ const REFERENCE_SNOW = 4;
263
+ /** The base game keeps flat permanent snow in the tenth of rows nearest each pole. */
264
+ const ICE_CAP_LATITUDE = 0.8;
265
+ /** Drawn snow at or above this height stays permanent, as the base game's snowy high ground. */
266
+ const PEAK_SNOW_HEIGHT = 150;
267
+ function permanentSnowRule(input) {
268
+ // A latitude above 1 and a height above 255 are never reached.
269
+ if (input === 'snowlines')
270
+ return { iceCapLatitude: 2, peakHeight: 256 };
271
+ return {
272
+ iceCapLatitude: input?.iceCapLatitude ?? ICE_CAP_LATITUDE,
273
+ peakHeight: input?.peakHeight ?? PEAK_SNOW_HEIGHT,
274
+ ...(input?.paintedHeight === undefined ? {} : { paintedHeight: input.paintedHeight }),
275
+ };
276
+ }
277
+ function emptySnowCount() {
278
+ return {
279
+ permanent: 0,
280
+ rangeSnowLines: 0,
281
+ paintedSnowLines: 0,
282
+ drawnSnow: 0,
283
+ painted: 0,
284
+ seasonal: 0,
285
+ land: 0,
286
+ edge: 0,
287
+ };
288
+ }
289
+ /** Strategic regions drawn mostly as snow take the weather of at least this latitude. */
290
+ const SNOW_REGION_LATITUDE = 0.7;
291
+ /**
292
+ * Permanent snow (`perm_snow = yes`, indices 16 and 19) in the base game 1.19.4.2 `terrain.bmp`,
293
+ * over its land pixels: 10,628 mountain and 22,626 plains pixels, the plains almost all in the
294
+ * tenth of rows nearest each pole.
295
+ */
296
+ export const VANILLA_PERMANENT_SNOW = { pixels: 33_254, land: 4_353_170, share: 0.0076 };
297
+ /** A permanent-snow share above this multiple of the base game's is reported as a warning. */
298
+ const PERMANENT_SNOW_WARNING_FACTOR = 4;
299
+ /** Distance of a pixel row from the equator: 0 in the middle row, 1 at the top and bottom. */
300
+ function pixelLatitude(y, height) {
301
+ return Math.abs((y + 0.5) / height - 0.5) * 2;
302
+ }
303
+ function permanentSnowNote(count, input, estimate = false) {
304
+ const rule = permanentSnowRule(input);
305
+ const share = count.permanent / Math.max(1, count.land);
306
+ const ratio = share / VANILLA_PERMANENT_SNOW.share;
307
+ const high = ratio > PERMANENT_SNOW_WARNING_FACTOR;
308
+ const percent = (value) => `${(value * 100).toFixed(2)}%`;
309
+ // The hint names what put most of the snow there, since each source has its own setting.
310
+ const largest = [
311
+ ['paintedSnowLines', count.paintedSnowLines],
312
+ ['rangeSnowLines', count.rangeSnowLines],
313
+ ['drawnSnow', count.drawnSnow],
314
+ ].reduce((best, next) => (next[1] > best[1] ? next : best));
315
+ const hint = largest[0] === 'paintedSnowLines'
316
+ ? `${largest[1]} of them lie above the snow line of painted mountains, volcanoes and impassable land: raise permanentSnow.paintedHeight (256 puts none)`
317
+ : largest[0] === 'rangeSnowLines'
318
+ ? `${largest[1]} of them lie above the snow lines of the model's ranges: raise or remove their snowline`
319
+ : 'raise permanentSnow.iceCapLatitude or peakHeight, or set permanentSnow to "snowlines"';
320
+ return {
321
+ code: estimate ? 'MAP_PERMANENT_SNOW_ESTIMATE' : 'MAP_PERMANENT_SNOW_SHARE',
322
+ severity: high ? 'warning' : 'info',
323
+ message: (estimate
324
+ ? `Estimated from the half-resolution relief of this check, permanent snow would cover ${percent(share)} of the land (${count.permanent} pixels), `
325
+ : `Permanent snow covers ${percent(share)} of the land (${count.permanent} pixels), `) +
326
+ `${ratio.toFixed(1)} times the base game's ${percent(VANILLA_PERMANENT_SNOW.share)}` +
327
+ (count.painted > 0
328
+ ? `; ${count.seasonal} of ${count.painted} drawn snow pixels are ordinary land with seasonal snow`
329
+ : '') +
330
+ (high ? `. The game draws permanent snow as bright ice; ${hint}` : ''),
331
+ details: {
332
+ permanentPixels: count.permanent,
333
+ landPixels: count.land,
334
+ share: Number(share.toFixed(5)),
335
+ vanilla: VANILLA_PERMANENT_SNOW,
336
+ ratio: Number(ratio.toFixed(2)),
337
+ // What put each permanent pixel there, in this order of precedence.
338
+ bySource: {
339
+ rangeSnowLines: count.rangeSnowLines,
340
+ paintedSnowLines: count.paintedSnowLines,
341
+ drawnSnow: count.drawnSnow,
342
+ },
343
+ drawnSnowPixels: count.painted,
344
+ seasonalSnowPixels: count.seasonal,
345
+ // The snow range or wall at a `rim` or `wall` seam, counted apart from the land.
346
+ edgePixels: count.edge,
347
+ permanentSnow: input === 'snowlines'
348
+ ? 'snowlines'
349
+ : {
350
+ iceCapLatitude: rule.iceCapLatitude,
351
+ peakHeight: rule.peakHeight,
352
+ ...(rule.paintedHeight === undefined ? {} : { paintedHeight: rule.paintedHeight }),
353
+ },
354
+ // The write adds full-resolution detail to these heights, so its share differs a little.
355
+ ...(estimate ? { estimate: true, grid: 'half-resolution' } : {}),
356
+ },
357
+ };
358
+ }
359
+ /**
360
+ * The permanent-snow count of the write, estimated on the half-resolution relief of the river
361
+ * check: the same rule as the terrain writer (snow lines, then drawn snow on ice caps and peaks),
362
+ * with each pixel taking the height and snow lines of its half-resolution cell.
363
+ */
364
+ function estimatePermanentSnow(input) {
365
+ const { width, height, kind, relief } = input;
366
+ const rule = permanentSnowRule(input.permanentSnow);
367
+ const count = emptySnowCount();
368
+ for (let y = 0; y < height; y += 1) {
369
+ if (y % 64 === 0)
370
+ input.signal?.throwIfAborted();
371
+ const iceCap = pixelLatitude(y, height) >= rule.iceCapLatitude;
372
+ const row = Math.min(relief.height - 1, y >> 1) * relief.width;
373
+ for (let x = 0; x < width; x += 1) {
374
+ const pixel = y * width + x;
375
+ if (kind[pixel] !== LAND)
376
+ continue;
377
+ if (input.edgePixel(pixel)) {
378
+ count.edge += 1;
379
+ continue;
380
+ }
381
+ count.land += 1;
382
+ const cell = row + Math.min(relief.width - 1, x >> 1);
383
+ const value = Math.round(relief.heights[cell]);
384
+ const line = relief.snowLine[cell];
385
+ const range = relief.rangeSnowLine[cell];
386
+ const drawn = input.drawnSnow(pixel);
387
+ const source = range < 255 && value >= range
388
+ ? 'range'
389
+ : line < 255 && value >= line
390
+ ? 'painted'
391
+ : drawn && (iceCap || value >= rule.peakHeight)
392
+ ? 'drawn'
393
+ : undefined;
394
+ if (source !== undefined) {
395
+ count.permanent += 1;
396
+ if (source === 'range')
397
+ count.rangeSnowLines += 1;
398
+ else if (source === 'painted')
399
+ count.paintedSnowLines += 1;
400
+ else
401
+ count.drawnSnow += 1;
402
+ }
403
+ if (drawn) {
404
+ count.painted += 1;
405
+ if (source === undefined)
406
+ count.seasonal += 1;
407
+ }
408
+ }
409
+ }
410
+ return count;
411
+ }
261
412
  /** Land relief of the base game 1.19.4.1 (`reliefStatistics` over its land provinces). */
262
413
  export const VANILLA_RELIEF = { median: 107, p99: 213, maximum: 239, meanStep: 2.69 };
263
414
  function terrainSummaryNote(terrain, geography) {
@@ -598,6 +749,8 @@ export function generateWorld(spec, context, options = {}) {
598
749
  // impassable regions of the geography model (ZR-28).
599
750
  const impassableMask = impassableLand(reference?.impassable, geography, width, height);
600
751
  // Impassable land is the highest ground even without relief.painted: then only it is raised.
752
+ // permanentSnow.paintedHeight keeps the painted snow line at or above its height.
753
+ const snowFloor = permanentSnowRule(spec.permanentSnow).paintedHeight;
601
754
  const painted = geography === undefined
602
755
  ? undefined
603
756
  : spec.paintedRelief !== undefined && reference !== undefined
@@ -606,6 +759,7 @@ export function generateWorld(spec, context, options = {}) {
606
759
  impassable: impassableMask,
607
760
  settings: spec.paintedRelief,
608
761
  seed: spec.seed,
762
+ snowFloor,
609
763
  }
610
764
  : impassableMask !== undefined
611
765
  ? {
@@ -613,6 +767,7 @@ export function generateWorld(spec, context, options = {}) {
613
767
  impassable: impassableMask,
614
768
  settings: DEFAULT_PAINTED_RELIEF,
615
769
  seed: spec.seed,
770
+ snowFloor,
616
771
  }
617
772
  : undefined;
618
773
  if (edge.mode !== 'none') {
@@ -690,7 +845,7 @@ export function generateWorld(spec, context, options = {}) {
690
845
  .map(({ tag, capital }) => ({ tag, x: capital.x, y: capital.y })),
691
846
  }));
692
847
  try {
693
- const checked = checkTerrainRivers({
848
+ const { notes: checked, relief } = checkTerrainRiversWithRelief({
694
849
  geography,
695
850
  width,
696
851
  height,
@@ -711,6 +866,22 @@ export function generateWorld(spec, context, options = {}) {
711
866
  message: note.message,
712
867
  ...(note.details === undefined ? {} : { details: note.details }),
713
868
  });
869
+ // The share the write's MAP_PERMANENT_SNOW_SHARE will report, so the permanentSnow
870
+ // thresholds can be tuned without a write.
871
+ const snow = estimatePermanentSnow({
872
+ width,
873
+ height,
874
+ kind: surface.kind,
875
+ drawnSnow: (pixel) => reference?.terrain[pixel] === REFERENCE_SNOW,
876
+ edgePixel: (pixel) => wallMask !== undefined
877
+ ? wallMask[pixel] === 1
878
+ : rimStrength(edge, width, pixel % width) > 0.35,
879
+ relief,
880
+ permanentSnow: spec.permanentSnow,
881
+ signal: options.signal,
882
+ });
883
+ if (snow.permanent > 0 || snow.painted > 0)
884
+ notes.push(permanentSnowNote(snow, spec.permanentSnow, true));
714
885
  }
715
886
  catch (error) {
716
887
  if (!(error instanceof ServiceError))
@@ -991,6 +1162,8 @@ export function generateWorld(spec, context, options = {}) {
991
1162
  'marsh',
992
1163
  'jungle',
993
1164
  ];
1165
+ // Provinces drawn as snow: plains in play, with cold weather for their strategic regions.
1166
+ const snowProvinces = new Set();
994
1167
  if (reference !== undefined) {
995
1168
  const votes = new Uint32Array(count * referenceTerrainNames.length);
996
1169
  for (let pixel = 0; pixel < width * height; pixel += 1)
@@ -1003,6 +1176,8 @@ export function generateWorld(spec, context, options = {}) {
1003
1176
  votes[id * referenceTerrainNames.length + selected])
1004
1177
  selected = type;
1005
1178
  terrain.set(id, referenceTerrainNames[selected]);
1179
+ if (selected === REFERENCE_SNOW)
1180
+ snowProvinces.add(id);
1006
1181
  }
1007
1182
  }
1008
1183
  // Impassable land (the `wall` at the seam, painted or regional impassable land) joins no
@@ -1818,12 +1993,28 @@ export function generateWorld(spec, context, options = {}) {
1818
1993
  Math.abs(heights[Math.min(height - 1, y + 1) * width + x] -
1819
1994
  heights[Math.max(0, y - 1) * width + x]) <=
1820
1995
  2;
1821
- const snowAt = (pixel, type) => synthesized !== undefined
1822
- ? (synthesized.snow[pixel] === 1 || reference?.terrain[pixel] === 4) &&
1823
- surface.kind[pixel] === LAND
1824
- : reference === undefined
1825
- ? type === 'mountain' && latitude(provinces.pixel[pixel]) > 0.7
1826
- : reference.terrain[pixel] === 4 && surface.kind[pixel] === LAND;
1996
+ // Drawn snow is ordinary land with seasonal snow, as the base game's northern lands are; only
1997
+ // ice caps near the poles and high ground keep permanent snow. Snow lines are always permanent.
1998
+ const snowRule = permanentSnowRule(spec.permanentSnow);
1999
+ const paintedSnow = (pixel) => reference?.terrain[pixel] === REFERENCE_SNOW && surface.kind[pixel] === LAND;
2000
+ const iceCapOrPeak = (pixel) => pixelLatitude(Math.floor(pixel / width), height) >= snowRule.iceCapLatitude ||
2001
+ heights[pixel] >= snowRule.peakHeight;
2002
+ const snowAt = (pixel, type) => surface.kind[pixel] !== LAND
2003
+ ? false
2004
+ : synthesized?.snow[pixel] === 1 ||
2005
+ (reference !== undefined
2006
+ ? paintedSnow(pixel) && iceCapOrPeak(pixel)
2007
+ : synthesized === undefined &&
2008
+ type === 'mountain' &&
2009
+ latitude(provinces.pixel[pixel]) > 0.7);
2010
+ // The base game draws snowy high ground with its mountain entry (16) and flat ice caps with its
2011
+ // plains entry (19), both `perm_snow = yes`.
2012
+ const snowIndex = (pixel) => reference === undefined ||
2013
+ synthesized?.snow[pixel] === 1 ||
2014
+ heights[pixel] >= snowRule.peakHeight
2015
+ ? 16
2016
+ : 19;
2017
+ const snowCount = emptySnowCount();
1827
2018
  // A wall takes the look of the land it meets, row by row on each side.
1828
2019
  const wallLook = wallMask === undefined
1829
2020
  ? undefined
@@ -1859,9 +2050,7 @@ export function generateWorld(spec, context, options = {}) {
1859
2050
  ? 16
1860
2051
  : (terrainIndex.get(walled) ?? DEFAULT_TERRAIN_INDEX.get(walled) ?? 0)
1861
2052
  : snowy
1862
- ? reference === undefined
1863
- ? 16
1864
- : 19
2053
+ ? snowIndex(pixel)
1865
2054
  : rimmed
1866
2055
  ? 16
1867
2056
  : type === 'lakes'
@@ -1873,6 +2062,27 @@ export function generateWorld(spec, context, options = {}) {
1873
2062
  : snowy || rimmed
1874
2063
  ? 'snow'
1875
2064
  : type);
2065
+ if (surface.kind[pixel] === LAND) {
2066
+ if (walled !== undefined || rimmed)
2067
+ snowCount.edge += 1;
2068
+ else {
2069
+ snowCount.land += 1;
2070
+ if (snowy) {
2071
+ snowCount.permanent += 1;
2072
+ if (synthesized?.snow[pixel] !== 1)
2073
+ snowCount.drawnSnow += 1;
2074
+ else if (synthesized.paintedSnow[pixel] === 1)
2075
+ snowCount.paintedSnowLines += 1;
2076
+ else
2077
+ snowCount.rangeSnowLines += 1;
2078
+ }
2079
+ if (paintedSnow(pixel)) {
2080
+ snowCount.painted += 1;
2081
+ if (!snowy)
2082
+ snowCount.seasonal += 1;
2083
+ }
2084
+ }
2085
+ }
1876
2086
  if (calibrated && walled === undefined && !snowy && !rimmed && surface.kind[pixel] === LAND) {
1877
2087
  // Variant graphical terrains by rule, so one class is not one flat texture.
1878
2088
  const y = (pixel - x) / width;
@@ -1900,6 +2110,8 @@ export function generateWorld(spec, context, options = {}) {
1900
2110
  colourClasses[pixel] = classCode(colour);
1901
2111
  }
1902
2112
  }
2113
+ if (snowCount.permanent > 0 || snowCount.painted > 0)
2114
+ notes.push(permanentSnowNote(snowCount, spec.permanentSnow));
1903
2115
  add(`${map}/terrain.bmp`, createBmp({
1904
2116
  width,
1905
2117
  height,
@@ -2085,6 +2297,11 @@ export function generateWorld(spec, context, options = {}) {
2085
2297
  const meanLatitude = indexes.reduce((sum, id) => sum + 1 - (2 * center(id).y) / height, 0) / indexes.length;
2086
2298
  const desert = indexes.filter((id) => terrain.get(id) === 'desert').length > indexes.length / 2;
2087
2299
  const naval = indexes.every((id) => provinces.kind[id] !== LAND);
2300
+ // A region drawn mostly as snow gets winters cold enough for seasonal snow.
2301
+ const snowy = indexes.filter((id) => snowProvinces.has(id)).length > indexes.length / 2;
2302
+ const weatherLatitude = snowy && Math.abs(meanLatitude) < SNOW_REGION_LATITUDE
2303
+ ? (meanLatitude < 0 ? -1 : 1) * SNOW_REGION_LATITUDE
2304
+ : meanLatitude;
2088
2305
  add(`${map}/strategicregions/${region}-${slug(regionNames.get(region) ?? `World region ${region}`).slice(0, 80)}.txt`, text([
2089
2306
  'strategic_region={',
2090
2307
  `\tid=${region}`,
@@ -2093,7 +2310,7 @@ export function generateWorld(spec, context, options = {}) {
2093
2310
  `\t\t${members.sort((a, b) => a - b).join(' ')} `,
2094
2311
  '\t}',
2095
2312
  ...(naval ? ['\tnaval_terrain=water_deep_ocean'] : []),
2096
- weatherBlock(meanLatitude, desert),
2313
+ weatherBlock(weatherLatitude, desert),
2097
2314
  '}',
2098
2315
  '',
2099
2316
  ].join('\n')));