hoi4-agent-tools 4.9.0 → 4.10.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 (64) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/dist/hoi4_agent_tools/event/graph.js +16 -2
  3. package/dist/hoi4_agent_tools/event/source-analysis.js +35 -16
  4. package/dist/hoi4_agent_tools/map/gameplay/reachability.js +81 -0
  5. package/dist/hoi4_agent_tools/map/geography/resolve.js +3 -0
  6. package/dist/hoi4_agent_tools/map/operations.js +8 -0
  7. package/dist/hoi4_agent_tools/map/partition-tuning.js +2 -1
  8. package/dist/hoi4_agent_tools/map/reference-world.js +17 -3
  9. package/dist/hoi4_agent_tools/map/relief/painted-relief.js +143 -0
  10. package/dist/hoi4_agent_tools/map/relief/terrain-synthesis.js +13 -0
  11. package/dist/hoi4_agent_tools/map/world.js +108 -23
  12. package/dist/hoi4_agent_tools/probability/model.js +4 -4
  13. package/dist/hoi4_agent_tools/probability/operations.js +6 -0
  14. package/dist/hoi4_agent_tools/probability/service.js +23 -0
  15. package/dist/hoi4_agent_tools/schemas/geography.js +5 -0
  16. package/dist/hoi4_agent_tools/schemas/map.js +29 -0
  17. package/dist/hoi4_agent_tools/version.js +1 -1
  18. package/docs/map.md +12 -9
  19. package/docs/probability.md +1 -1
  20. package/docs/research/probability-adapter-evidence.md +15 -2
  21. package/engine/bin/manifest.json +1 -1
  22. package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
  23. package/npm-shrinkwrap.json +2 -2
  24. package/package.json +1 -1
  25. package/schemas/configuration.schema.json +1 -1
  26. package/schemas/continuous-focus-palette.schema.json +1 -1
  27. package/schemas/custom-weighted-pool.schema.json +1 -1
  28. package/schemas/decision-inspect-input.schema.json +1 -1
  29. package/schemas/error-log-input.schema.json +1 -1
  30. package/schemas/event-feature-manifest.schema.json +1 -1
  31. package/schemas/focus-plan.schema.json +1 -1
  32. package/schemas/focus-planning-sidecar.schema.json +1 -1
  33. package/schemas/geography-model.schema.json +4 -1
  34. package/schemas/gui-animation-source.schema.json +1 -1
  35. package/schemas/gui-helper.schema.json +1 -1
  36. package/schemas/gui-scenario.schema.json +1 -1
  37. package/schemas/helper-expansion-request.schema.json +1 -1
  38. package/schemas/helper-expansion-summary.schema.json +1 -1
  39. package/schemas/impact-inspect-input.schema.json +1 -1
  40. package/schemas/map-operation.schema.json +177 -118
  41. package/schemas/mechanic-test-input.schema.json +1 -1
  42. package/schemas/mod-index-input.schema.json +1 -1
  43. package/schemas/operation-result.schema.json +1 -1
  44. package/schemas/package-check-input.schema.json +1 -1
  45. package/schemas/package-manifest.schema.json +1 -1
  46. package/schemas/probability-analysis-result.schema.json +1 -1
  47. package/schemas/probability-compare-input.schema.json +1 -1
  48. package/schemas/probability-evaluate-input.schema.json +1 -1
  49. package/schemas/probability-inspect-input.schema.json +1 -1
  50. package/schemas/probability-render-input.schema.json +1 -1
  51. package/schemas/probability-scenario-set.schema.json +1 -1
  52. package/schemas/probability-sequence-input.schema.json +1 -1
  53. package/schemas/probability-simulate-input.schema.json +1 -1
  54. package/schemas/probability-sweep-input.schema.json +1 -1
  55. package/schemas/reference-context-input.schema.json +1 -1
  56. package/schemas/reference-read-input.schema.json +1 -1
  57. package/schemas/reference-search-input.schema.json +1 -1
  58. package/schemas/reference-sheets.schema.json +1 -1
  59. package/schemas/scenario-suite.schema.json +1 -1
  60. package/schemas/scenario-test-input.schema.json +1 -1
  61. package/schemas/script-validate-input.schema.json +1 -1
  62. package/schemas/shared-scenario.schema.json +1 -1
  63. package/schemas/source-lookup-input.schema.json +1 -1
  64. package/server.json +2 -2
package/CHANGELOG.md CHANGED
@@ -2,6 +2,17 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 4.10.0 - 2026-11-06
6
+
7
+ - Size lake provinces: `create_world.partitionTuning.lakeArea` (default 6,000 pixels, capped at the largest province the map allows) sets the area of a lake province, so a drawn lake no larger than it stays one province.
8
+ - Raise the relief toward a reference picture's painted mountains, hills and volcanoes (`create_world.relief.painted`, ADR 0079). The classes are blurred over `falloffPx` (default 24) before the rivers are routed, so slopes stay natural and the model's rivers flow around the drawn ranges. Painted mountains get permanent snow by latitude. `MAP_RELIEF_SYNTHESIZED` now reports the base game's relief beside the world's.
9
+ - Make land impassable (ADR 0079): paint it with the palette kind `impassable_mountain` or mark a model region `impassable: true`.
10
+ - Its provinces become impassable `enclave` states linked to the nearest passable state, and it rises to the highest ground.
11
+ - Cities and capitals on it are refused (`MAP_FEATURE_IN_IMPASSABLE`).
12
+ - `MAP_REALM_CUT_OFF` and `MAP_REALM_ENCLOSED` warn when impassable land or borders cut a realm apart or box it in.
13
+ - `EVENT_TARGET_READ_BEFORE_SAVE` no longer reports correct script (#60). A `has_event_target` or `has_global_event_target` check tests whether a target exists. Without a visible producer it is now the design warning `EVENT_GATE_WITHOUT_WRITER`, not a probable defect. A read that such a check guards in the same event, focus or decision is not reported. Names built in a `meta_effect` or with `$parameter$`s are no longer cut at their first bracket. Names far into a long block are read in full instead of being cut at the display limit. The event graph now reads shared and joint focuses and the `completion_reward_joint_originator` and `completion_reward_joint_member` rewards, where vanilla saves `SSB_leader`. On Chaos Redux with vanilla 1.19.4.1 the findings drop from 33 to 2. Both remaining ones are real: vanilla reads `demanded_prov_target` in `events/Generic.txt` and saves it nowhere.
14
+ - Check the hand-kept game data against the installed build (#70). The probability adapters were re-checked on 1.19.4.1: five of the six documentation files they rest on are byte-identical to 1.19.2.0, and the two AI strategy sections they use say the same, so the target moves to `Operation Postern 1.19.4.1 (f584)` and the adapter version to `hoi4-1.19.4.1.v1`. A result on another build now carries the warning `PROBABILITY_GAME_BUILD_UNVERIFIED` instead of only recording `workspace_observed` in its metadata. The nightly game-update watcher lists the adapters or the native-effects list under "Checked against another build" on every run while their pin differs from the installed build, not only on the night the build changes.
15
+
5
16
  ## 4.9.0 - 2026-11-05
6
17
 
7
18
  - Results no longer suggest the wrong conclusion (#65, the parts #82 left open). `error_log` fails a new `error-log-age` check when the mod's script, localisation or interface files changed after the log was written, and names how many, the newest time and an example file, because such a log cannot vouch for the current source. `script_validate` names what made a result partial (`partialReasons`), for example the blocks of a scripted helper file whose scope depends on the caller, by line, so `SCRIPT_CHECK_PARTIAL` with `unresolvedCount: 0` no longer comes without a reason. Every example in a tool description or an argument error is now checked against the tool's own schema in a test. That found and fixed the `gui_rewrite` patch example, which lacked the required `description`, and the `gui_rewrite` and `mechanic_test` examples, which held `...` placeholders. An unknown field in the arguments now lists the fields that object accepts. The tools list budget in the discovery test moves from 80 to 84 KiB for the longer, runnable examples.
@@ -1206,15 +1206,29 @@ function stateLifecycleIssues(graph, stateLinks, budget) {
1206
1206
  clearers.set(key, values);
1207
1207
  }
1208
1208
  }
1209
+ // has_event_target checks per owner: a read in the same owner that ends after the check starts
1210
+ // is guarded. That includes the read recorded for an enclosing `if` or `limit` block.
1211
+ const presenceChecks = new Map();
1212
+ for (const access of graph.stateAccesses) {
1213
+ if (access.metadata.presence !== true)
1214
+ continue;
1215
+ const key = `${access.ownerId}\u0000${stateKey(access)}`;
1216
+ presenceChecks.set(key, [...(presenceChecks.get(key) ?? []), access]);
1217
+ }
1218
+ const guarded = (access) => (presenceChecks.get(`${access.ownerId}\u0000${stateKey(access)}`) ?? []).some((check) => check.location.path === access.location.path &&
1219
+ check.location.start.offset < access.location.end.offset);
1209
1220
  for (const access of graph.stateAccesses) {
1210
1221
  if (access.access !== 'read' && access.access !== 'read_write')
1211
1222
  continue;
1212
1223
  if (compatibleProducerKeys(access).some((producerKey) => (producers.get(producerKey) ?? []).length > 0))
1213
1224
  continue;
1214
1225
  const owner = semanticOwnerId(access.ownerId, nodes, parent);
1215
- if (access.kind === 'event_target' ||
1226
+ if ((access.kind === 'event_target' ||
1216
1227
  access.kind === 'global_event_target' ||
1217
- access.kind === 'saved_scope') {
1228
+ access.kind === 'saved_scope') &&
1229
+ access.metadata.presence !== true) {
1230
+ if (guarded(access))
1231
+ continue;
1218
1232
  addIssue(graph.issues, {
1219
1233
  code: 'EVENT_TARGET_READ_BEFORE_SAVE',
1220
1234
  classification: 'probable_defect',
@@ -152,6 +152,12 @@ function isScopeChain(value) {
152
152
  function isLiteralCountryTag(value) {
153
153
  return /^[A-Z][A-Z0-9]{2}$/u.test(value);
154
154
  }
155
+ const FOCUS_BLOCKS = new Set(['focus', 'shared_focus', 'joint_focus']);
156
+ const FOCUS_REWARD_BLOCKS = [
157
+ 'completion_reward',
158
+ 'completion_reward_joint_originator',
159
+ 'completion_reward_joint_member',
160
+ ];
155
161
  const EFFECT_WRAPPER_BLOCKS = new Set([
156
162
  ...CONTROL_BLOCKS,
157
163
  'effect',
@@ -785,7 +791,9 @@ class FragmentAnalyzer {
785
791
  }
786
792
  analyzeFocuses() {
787
793
  this.visitAssignments(this.document.root, (assignment, ancestors) => {
788
- if (assignment.key.value !== 'focus' || assignment.value.type !== 'block')
794
+ // Shared and joint focuses run their rewards like tree focuses (vanilla's Saadabad branch
795
+ // saves SSB_leader in a joint_focus).
796
+ if (!FOCUS_BLOCKS.has(assignment.key.value) || assignment.value.type !== 'block')
789
797
  return;
790
798
  const id = firstScalar(assignment.value, 'id')?.value;
791
799
  if (id === undefined)
@@ -805,19 +813,22 @@ class FragmentAnalyzer {
805
813
  });
806
814
  });
807
815
  }
808
- const rewardOccurrences = new Map();
809
- childBlocks(assignment.value, 'completion_reward').forEach((block) => this.walk(block, {
810
- ownerId,
811
- sourceScope: 'country',
812
- phase: 'entry',
813
- conditions: [],
814
- helperStack: [],
815
- semanticPath: [
816
- ...ancestors,
817
- id,
818
- semanticOccurrenceSegment('completion_reward', semanticSourceEntry(block), rewardOccurrences),
819
- ],
820
- }));
816
+ // A joint focus rewards its originator and its members in blocks of their own.
817
+ for (const key of FOCUS_REWARD_BLOCKS) {
818
+ const rewardOccurrences = new Map();
819
+ childBlocks(assignment.value, key).forEach((block) => this.walk(block, {
820
+ ownerId,
821
+ sourceScope: 'country',
822
+ phase: 'entry',
823
+ conditions: [],
824
+ helperStack: [],
825
+ semanticPath: [
826
+ ...ancestors,
827
+ id,
828
+ semanticOccurrenceSegment(key, semanticSourceEntry(block), rewardOccurrences),
829
+ ],
830
+ }));
831
+ }
821
832
  });
822
833
  }
823
834
  analyzeDecisions() {
@@ -1397,8 +1408,11 @@ class FragmentAnalyzer {
1397
1408
  }
1398
1409
  const rule = STATE_RULES[assignment.key.value];
1399
1410
  if (rule === undefined) {
1400
- const raw = valueText(this.document, assignment.value);
1401
- for (const match of raw.matchAll(/\b(event_target|global_event_target):([A-Za-z0-9_-]+)/gu)) {
1411
+ // The whole value: valueText is cut for display and would cut a name at its end.
1412
+ const raw = this.document.text.slice(assignment.value.start, assignment.value.end);
1413
+ // A name that runs on into `[...]` or `$...$` is built at run time (meta_effect, scripted
1414
+ // parameters); its literal prefix is not the target's name.
1415
+ for (const match of raw.matchAll(/\b(event_target|global_event_target):([A-Za-z0-9_-]+)(?![A-Za-z0-9_[$-])/gu)) {
1402
1416
  this.addState(context, match[1] === 'global_event_target' ? 'global_event_target' : 'event_target', match[2], 'read', assignment, semanticPath, false);
1403
1417
  }
1404
1418
  return;
@@ -1430,6 +1444,11 @@ class FragmentAnalyzer {
1430
1444
  this.addState(context, kind, name, access, assignment, semanticPath, isDynamic(name), {
1431
1445
  ...(rule.storage === undefined ? {} : { storage: rule.storage }),
1432
1446
  ...(rule.temporary === true ? { temporary: true } : {}),
1447
+ // has_event_target tests whether the target exists; it never reads an unset one.
1448
+ ...(assignment.key.value === 'has_event_target' ||
1449
+ assignment.key.value === 'has_global_event_target'
1450
+ ? { presence: true }
1451
+ : {}),
1433
1452
  });
1434
1453
  }
1435
1454
  addState(context, kind, name, access, node, _semanticPath, dynamic, metadata = {}) {
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Overland reach of each realm through impassable land (ZR-28). Impassable states and impassable
3
+ * adjacency rows make a strategic board, but they can also cut a realm in two or box it in by
4
+ * accident. This compares two graphs of land provinces joined by shared borders and `sea`
5
+ * crossings: one with every province and border, and one without the impassable provinces and
6
+ * the blocked borders. Whatever the first joins and the second separates was cut by impassable
7
+ * land; islands, which neither graph joins, are never reported.
8
+ */
9
+ function components(count, include, edges) {
10
+ const label = new Int32Array(count).fill(-1);
11
+ let next = 0;
12
+ for (let start = 0; start < count; start += 1) {
13
+ if (label[start] !== -1 || !include(start))
14
+ continue;
15
+ const queue = [start];
16
+ label[start] = next;
17
+ // The array iterator also visits provinces queued during the loop.
18
+ for (const id of queue)
19
+ for (const other of edges(id))
20
+ if (label[other] === -1 && include(other)) {
21
+ label[other] = next;
22
+ queue.push(other);
23
+ }
24
+ next += 1;
25
+ }
26
+ return label;
27
+ }
28
+ export function realmReachNotes(input) {
29
+ const count = input.kind.length;
30
+ const key = (a, b) => (a < b ? `${a}:${b}` : `${b}:${a}`);
31
+ const blocked = new Set(input.blocked.map(([a, b]) => key(a, b)));
32
+ const linked = [];
33
+ for (const [a, b] of input.crossings) {
34
+ (linked[a] ??= []).push(b);
35
+ (linked[b] ??= []).push(a);
36
+ }
37
+ const land = (id) => input.kind[id] === 1;
38
+ const everything = components(count, land, (id) => [
39
+ ...input.neighbors[id],
40
+ ...(linked[id] ?? []),
41
+ ]);
42
+ const passable = components(count, (id) => land(id) && !input.impassable.has(id), (id) => [...input.neighbors[id], ...(linked[id] ?? [])].filter((other) => !blocked.has(key(id, other))));
43
+ const notes = [];
44
+ for (const [realm, capital] of input.capitals.entries()) {
45
+ const tag = input.tags[realm] ?? String(realm);
46
+ const home = passable[capital];
47
+ const cut = [];
48
+ for (const [id, owner] of input.owner)
49
+ if (owner === realm &&
50
+ !input.impassable.has(id) &&
51
+ passable[id] !== home &&
52
+ everything[id] === everything[capital])
53
+ cut.push(id);
54
+ if (cut.length > 0)
55
+ notes.push({
56
+ code: 'MAP_REALM_CUT_OFF',
57
+ severity: 'warning',
58
+ message: `${cut.length} land province(s) of ${tag} are cut off from its capital by impassable land or borders; open a pass or give them to a realm on their side`,
59
+ details: { tag, provinces: cut.length, sample: cut.slice(0, 10).map((id) => id + 1) },
60
+ });
61
+ // Boxed in: the land around the capital reaches another realm only through impassable land.
62
+ let foreignBefore = false;
63
+ let foreignAfter = false;
64
+ for (const [id, owner] of input.owner) {
65
+ if (owner === realm)
66
+ continue;
67
+ if (everything[id] === everything[capital])
68
+ foreignBefore = true;
69
+ if (passable[id] === home)
70
+ foreignAfter = true;
71
+ }
72
+ if (foreignBefore && !foreignAfter)
73
+ notes.push({
74
+ code: 'MAP_REALM_ENCLOSED',
75
+ severity: 'warning',
76
+ message: `${tag} reaches no other realm over land: impassable land or borders close every way out of the land around its capital`,
77
+ details: { tag, capitalProvince: capital + 1 },
78
+ });
79
+ }
80
+ return notes;
81
+ }
@@ -540,6 +540,8 @@ export function resolveGeography(model, options) {
540
540
  const shareSum = Object.values(terrain).reduce((sum, share) => sum + share, 0);
541
541
  if (shareSum > 1.05)
542
542
  sink('MAP_GEOGRAPHY_REGION_TERRAIN_SUM', 'warning', `The terrain shares of region ${input.id} add up to ${shareSum.toFixed(2)}, above 1`, { featureId: input.id, sum: shareSum });
543
+ if (input.impassable === true && area === undefined)
544
+ sink('MAP_GEOGRAPHY_IMPASSABLE_WITHOUT_AREA', 'error', `Region ${input.id} is impassable but has no polygons to say where`, { featureId: input.id });
543
545
  const perState = input.density?.provincesPerState;
544
546
  if (perState !== undefined && !(perState[0] <= perState[1] && perState[1] <= perState[2]))
545
547
  sink('MAP_GEOGRAPHY_REGION_DENSITY_ORDER', 'error', `Region ${input.id} lists provincesPerState as [smallest, usual, largest] but they are not in order`, { featureId: input.id });
@@ -551,6 +553,7 @@ export function resolveGeography(model, options) {
551
553
  ...(Object.keys(terrain).length === 0 ? {} : { terrain }),
552
554
  ...(perState === undefined ? {} : { provincesPerState: perState }),
553
555
  ...opt('provinceAreaPx', input.density?.provinceAreaPx),
556
+ ...(input.impassable === true && area !== undefined ? { impassable: true } : {}),
554
557
  });
555
558
  }
556
559
  const lands = [];
@@ -16,6 +16,7 @@ import { planWorldOutputs } from './world-outputs.js';
16
16
  import { resolvePartitionMode } from './partition.js';
17
17
  import { applyAssignTerritory, applyRepartitionStates, } from './territory-operations.js';
18
18
  import { unsupportedGeographyParts } from './relief/index.js';
19
+ import { resolvePaintedRelief } from './relief/painted-relief.js';
19
20
  export function* cancellationCheckpoint(signal, iteration = 0, stride = 1) {
20
21
  if (iteration % stride !== 0)
21
22
  return;
@@ -3336,6 +3337,8 @@ function applyCreateWorld(base, changes, operation, context, signal) {
3336
3337
  throw new ServiceError('MAP_LOOK_CUSTOM_PALETTE_REQUIRED', 'look "custom" needs colormap.palette with at least one class colour');
3337
3338
  if (colormapProfile === 'legacy' && look !== undefined)
3338
3339
  throw new ServiceError('MAP_LOOK_REQUIRES_CALIBRATED_COLORMAP', 'look selects a calibrated palette; remove colormap.profile "legacy" or look');
3340
+ if ((operation.relief?.painted ?? false) !== false && (!hasGeography || reference === undefined))
3341
+ throw new ServiceError('MAP_RELIEF_PAINTED_INPUTS', 'relief.painted raises the relief from the classes of a reference picture onto a geography model; give both reference and geography (or geographyPath)', { reference: reference !== undefined, geography: hasGeography });
3339
3342
  if (!hasGeography && operation.development?.model === 'geography')
3340
3343
  throw new ServiceError('MAP_DEVELOPMENT_REQUIRES_GEOGRAPHY', 'development.model "geography" plans the economy from a geography model; give geography or geographyPath, or use "legacy"');
3341
3344
  if (!hasGeography && operation.autoStraits !== undefined && operation.autoStraits !== false)
@@ -3436,6 +3439,11 @@ function applyCreateWorld(base, changes, operation, context, signal) {
3436
3439
  : { detail: operation.relief.detail }),
3437
3440
  },
3438
3441
  }),
3442
+ ...(operation.relief?.painted === undefined || operation.relief.painted === false
3443
+ ? {}
3444
+ : {
3445
+ paintedRelief: resolvePaintedRelief(operation.relief.painted),
3446
+ }),
3439
3447
  ...(typeof operation.rivers === 'object'
3440
3448
  ? { riverDensity: operation.rivers.density }
3441
3449
  : typeof operation.rivers === 'number'
@@ -49,6 +49,7 @@ export function resolvePartitionTuning(tuning, base) {
49
49
  const sea = tuning?.seaArea;
50
50
  for (const [name, value] of Object.entries(sea ?? {}))
51
51
  checkPixels(`seaArea.${name}`, value, minProvincePixels);
52
+ checkPixels('lakeArea', tuning?.lakeArea, minProvincePixels);
52
53
  const coastal = clamp(sea?.coastal ?? base.seaProvincePixels * PARTITION_DEFAULTS.seaCoastal);
53
54
  const open = clamp(sea?.open ?? base.seaProvincePixels * PARTITION_DEFAULTS.seaOpen);
54
55
  if (coastal > open)
@@ -85,7 +86,7 @@ export function resolvePartitionTuning(tuning, base) {
85
86
  return {
86
87
  landArea: { fertile, plains: clamp(Math.sqrt(fertile * hills)), hills, mountain, waste },
87
88
  seaArea: { coastal, open },
88
- lakeArea: clamp(PARTITION_DEFAULTS.lake),
89
+ lakeArea: clamp(tuning?.lakeArea ?? PARTITION_DEFAULTS.lake),
89
90
  states: group(perState, base.provincesPerState, 0.5, 1.6),
90
91
  regions: group(regionSize, base.landProvincesPerRegion, 0.6, 1.5),
91
92
  seaRegions: group(undefined, base.seaProvincesPerRegion, 0.5, 1.6),
@@ -18,12 +18,15 @@ export const REFERENCE_TERRAIN = {
18
18
  };
19
19
  const TERRAIN_ELEVATION = [0.045, 0.055, 0.035, 0.44, 0.045, 0.35, 0.18, 0.025, 0.06];
20
20
  const TERRAIN_MOISTURE = [0.45, 0.8, 0.06, 0.35, 0.25, 0.05, 0.4, 0.96, 0.92];
21
+ /** Internal class code of `impassable_mountain`, after the terrain codes. */
22
+ const IMPASSABLE_CODE = 3 + Object.keys(REFERENCE_TERRAIN).length;
21
23
  const pointSchema = z.object({ x: z.number().min(0).max(1), y: z.number().min(0).max(1) }).strict();
22
24
  const polygonSchema = z.array(pointSchema).min(3).max(2048);
23
25
  const semanticSchema = z.enum([
24
26
  'sea',
25
27
  'land',
26
28
  'lake',
29
+ 'impassable_mountain',
27
30
  'plains',
28
31
  'forest',
29
32
  'desert',
@@ -135,7 +138,9 @@ function semanticCode(kind) {
135
138
  ? 2
136
139
  : kind === 'land'
137
140
  ? 3
138
- : REFERENCE_TERRAIN[kind] + 3;
141
+ : kind === 'impassable_mountain'
142
+ ? IMPASSABLE_CODE
143
+ : REFERENCE_TERRAIN[kind] + 3;
139
144
  }
140
145
  function pixelColor(data, pixel) {
141
146
  return { r: data[pixel * 3], g: data[pixel * 3 + 1], b: data[pixel * 3 + 2] };
@@ -473,9 +478,17 @@ export async function extractReferenceWorld(imageBytes, input) {
473
478
  }
474
479
  const kind = new Uint8Array(codes.length);
475
480
  const terrain = new Uint8Array(codes.length);
481
+ let impassable;
476
482
  for (let pixel = 0; pixel < codes.length; pixel += 1) {
477
- kind[pixel] = codes[pixel] < 3 ? codes[pixel] : 1;
478
- terrain[pixel] = codes[pixel] < 3 ? 0 : codes[pixel] - 3;
483
+ const code = codes[pixel];
484
+ kind[pixel] = code < 3 ? code : 1;
485
+ if (code === IMPASSABLE_CODE) {
486
+ terrain[pixel] = REFERENCE_TERRAIN.mountain;
487
+ impassable ??= new Uint8Array(codes.length);
488
+ impassable[pixel] = 1;
489
+ }
490
+ else
491
+ terrain[pixel] = code < 3 ? 0 : code - 3;
479
492
  }
480
493
  const riverPoints = (options.riverAnnotations ?? []).reduce((total, path) => total + path.length, 0);
481
494
  if (riverPoints > 131072)
@@ -514,6 +527,7 @@ export async function extractReferenceWorld(imageBytes, input) {
514
527
  rivers,
515
528
  country: new Uint16Array(kind.length),
516
529
  inferredCountries: [],
530
+ ...(impassable === undefined ? {} : { impassable }),
517
531
  diagnostics,
518
532
  };
519
533
  if (!exact)
@@ -0,0 +1,143 @@
1
+ /**
2
+ * Relief from painted classes (ZR-27, ADR 0056 amended). A reference picture classified with a
3
+ * palette says, pixel by pixel, where the mountains, hills and volcanoes are, which the polygons
4
+ * of a geography model only approximate. This stage raises the macro relief toward those classes
5
+ * before the hydrology runs, so the model's rivers route around the painted mountains:
6
+ *
7
+ * - each class is measured as its share of every macro cell and blurred over `falloffPx`, so a
8
+ * single painted pixel lifts nothing and a class edge becomes a slope, never a cliff;
9
+ * - mountains rise toward `mountainPeak` under ridged noise, so ranges keep crests and saddles,
10
+ * hills toward `hillsPeak` under gentle noise, volcanoes toward `volcanoPeak`;
11
+ * - a cell keeps the model's height where that is higher, and every other cell keeps the model's
12
+ * broad elevation untouched;
13
+ * - impassable land (ZR-28) rises toward `impassablePeak`, the highest ground of the map;
14
+ * - painted mountains and volcanoes get permanent snow above a height that falls from the
15
+ * equator toward the poles, and weight the full-resolution detail as model ranges do.
16
+ */
17
+ import { LAND } from './grid.js';
18
+ import { fractal2, ridged2, smoothstep } from './math.js';
19
+ import { HEIGHT_CEILING, PEAK_BASE, PEAK_SPAN } from './macro-relief.js';
20
+ /** Reference terrain codes the stage reads (`REFERENCE_TERRAIN` of the reference interpretation). */
21
+ export const PAINTED_MOUNTAIN = 3;
22
+ export const PAINTED_VOLCANO = 5;
23
+ export const PAINTED_HILLS = 6;
24
+ /** Defaults measured against the base game 1.19.4.1: mountain p99 223, hills p90 140. */
25
+ export const DEFAULT_PAINTED_RELIEF = {
26
+ falloffPx: 24,
27
+ mountainPeak: 0.82,
28
+ hillsPeak: 0.27,
29
+ volcanoPeak: 0.9,
30
+ impassablePeak: 0.95,
31
+ };
32
+ /** Three passes of a separable box blur, about a Gaussian with the given radius in cells. */
33
+ function blur(field, width, height, radius) {
34
+ let source = field;
35
+ const passRadius = Math.max(1, Math.round(radius / Math.sqrt(3)));
36
+ const span = passRadius * 2 + 1;
37
+ for (let pass = 0; pass < 3; pass += 1) {
38
+ const across = new Float32Array(width * height);
39
+ for (let y = 0; y < height; y += 1) {
40
+ const row = y * width;
41
+ let sum = 0;
42
+ for (let x = -passRadius; x <= passRadius; x += 1)
43
+ sum += source[row + Math.min(width - 1, Math.max(0, x))];
44
+ for (let x = 0; x < width; x += 1) {
45
+ across[row + x] = sum / span;
46
+ sum +=
47
+ source[row + Math.min(width - 1, x + passRadius + 1)] -
48
+ source[row + Math.max(0, x - passRadius)];
49
+ }
50
+ }
51
+ const down = new Float32Array(width * height);
52
+ for (let x = 0; x < width; x += 1) {
53
+ let sum = 0;
54
+ for (let y = -passRadius; y <= passRadius; y += 1)
55
+ sum += across[Math.min(height - 1, Math.max(0, y)) * width + x];
56
+ for (let y = 0; y < height; y += 1) {
57
+ down[y * width + x] = sum / span;
58
+ sum +=
59
+ across[Math.min(height - 1, y + passRadius + 1) * width + x] -
60
+ across[Math.max(0, y - passRadius) * width + x];
61
+ }
62
+ }
63
+ source = down;
64
+ }
65
+ return source;
66
+ }
67
+ /** Permanent-snow height in map values at a row: 232 at the equator, 140 at the poles. */
68
+ export function paintedSnowHeight(y, height) {
69
+ const latitude = Math.abs((y + 0.5) / height - 0.5) * 2;
70
+ return Math.round(232 - 92 * latitude ** 1.5);
71
+ }
72
+ export function applyPaintedRelief(target, input) {
73
+ const { width: mw, height: mh, kind } = target;
74
+ const fullWidth = mw * 2;
75
+ const share = (code, source = input.classes) => {
76
+ const field = new Float32Array(mw * mh);
77
+ for (let y = 0; y < mh; y += 1)
78
+ for (let x = 0; x < mw; x += 1) {
79
+ const top = 2 * y * fullWidth + 2 * x;
80
+ let count = 0;
81
+ for (const offset of [0, 1, fullWidth, fullWidth + 1])
82
+ if (source[top + offset] === code)
83
+ count += 1;
84
+ field[y * mw + x] = count / 4;
85
+ }
86
+ return field;
87
+ };
88
+ const radius = Math.max(1, input.settings.falloffPx / 2);
89
+ const mountain = blur(share(PAINTED_MOUNTAIN), mw, mh, radius);
90
+ const hills = blur(share(PAINTED_HILLS), mw, mh, radius);
91
+ // Volcanoes are cones: a narrower falloff keeps them peaked.
92
+ const volcano = blur(share(PAINTED_VOLCANO), mw, mh, Math.max(1, radius / 2));
93
+ const blocked = input.impassable === undefined ? undefined : blur(share(1, input.impassable), mw, mh, radius);
94
+ const lift = (peak) => PEAK_SPAN * peak * target.scale;
95
+ const wavelength = Math.max(6, radius * 3);
96
+ let raisedCells = 0;
97
+ let highest = 0;
98
+ for (let y = 0; y < mh; y += 1)
99
+ for (let x = 0; x < mw; x += 1) {
100
+ const cell = y * mw + x;
101
+ if (kind[cell] !== LAND)
102
+ continue;
103
+ // Coverage saturates inside a painted area, so its interior reaches the peak.
104
+ const m = smoothstep(mountain[cell] * 1.6);
105
+ const h = smoothstep(hills[cell] * 1.6);
106
+ const v = smoothstep(volcano[cell] * 2);
107
+ const i = blocked === undefined ? 0 : smoothstep(blocked[cell] * 1.6);
108
+ if (m <= 0.001 && h <= 0.001 && v <= 0.001 && i <= 0.001)
109
+ continue;
110
+ const ridges = 0.55 + 0.45 * ridged2(input.seed + 4111, x, y, wavelength, 3);
111
+ const swell = 0.7 + 0.3 * fractal2(input.seed + 4127, x, y, wavelength, 3);
112
+ const goal = Math.min(HEIGHT_CEILING, Math.max(PEAK_BASE + lift(input.settings.mountainPeak) * m * ridges, PEAK_BASE + lift(input.settings.hillsPeak) * h * swell, PEAK_BASE + lift(input.settings.volcanoPeak) * v,
113
+ // Impassable land keeps its crests but never sinks below most of its peak.
114
+ PEAK_BASE + lift(input.settings.impassablePeak) * i * (0.8 + 0.2 * ridges)));
115
+ if (goal > target.heights[cell]) {
116
+ target.heights[cell] = goal;
117
+ raisedCells += 1;
118
+ if (goal > highest)
119
+ highest = goal;
120
+ }
121
+ const weight = Math.max(m, 0.6 * h, v, i);
122
+ if (weight > target.footprint[cell])
123
+ target.footprint[cell] = weight;
124
+ if (Math.max(m, v, i) > 0.25) {
125
+ const snow = paintedSnowHeight(y, mh);
126
+ if (snow < target.snowLine[cell])
127
+ target.snowLine[cell] = snow;
128
+ }
129
+ }
130
+ return { raisedCells, highest: Math.round(highest) };
131
+ }
132
+ /** Settings for `relief.painted`: `true` takes the defaults, an object overrides some of them. */
133
+ export function resolvePaintedRelief(input) {
134
+ if (input === true)
135
+ return DEFAULT_PAINTED_RELIEF;
136
+ return {
137
+ falloffPx: input.falloffPx ?? DEFAULT_PAINTED_RELIEF.falloffPx,
138
+ mountainPeak: input.mountainPeak ?? DEFAULT_PAINTED_RELIEF.mountainPeak,
139
+ hillsPeak: input.hillsPeak ?? DEFAULT_PAINTED_RELIEF.hillsPeak,
140
+ volcanoPeak: input.volcanoPeak ?? DEFAULT_PAINTED_RELIEF.volcanoPeak,
141
+ impassablePeak: input.impassablePeak ?? DEFAULT_PAINTED_RELIEF.impassablePeak,
142
+ };
143
+ }
@@ -5,6 +5,7 @@ import { checkRangesAndFeatures, reliefStatistics, straightRiverShare, } from '.
5
5
  import { buildFullResolutionHeights } from './full-resolution.js';
6
6
  import { RIVER_PIXEL_CAP, synthesizeHydrology } from './hydrology.js';
7
7
  import { DEFAULT_RELIEF, LAND_FLOOR, HEIGHT_CEILING, peakHeight, synthesizeMacroRelief, } from './macro-relief.js';
8
+ import { applyPaintedRelief } from './painted-relief.js';
8
9
  import { rasterizeRivers } from './river-raster.js';
9
10
  /** Red channel response of the normal map per height step (base game: about 2.6). */
10
11
  export const NORMAL_RESPONSE = 2.6;
@@ -107,6 +108,9 @@ export function checkTerrainRivers(input) {
107
108
  relief,
108
109
  signal: input.signal,
109
110
  });
111
+ // The same painted relief as the full synthesis, so the rivers checked are the rivers written.
112
+ if (input.painted !== undefined)
113
+ applyPaintedRelief(macro, input.painted);
110
114
  const adjust = input.adjustHeight;
111
115
  if (adjust !== undefined)
112
116
  for (let y = 0; y < macro.height; y += 1)
@@ -158,6 +162,15 @@ export function synthesizeTerrain(input) {
158
162
  relief,
159
163
  signal: input.signal,
160
164
  });
165
+ if (input.painted !== undefined) {
166
+ const summary = applyPaintedRelief(macro, input.painted);
167
+ notes.push({
168
+ code: 'MAP_RELIEF_PAINTED',
169
+ severity: 'info',
170
+ message: `Raised ${summary.raisedCells} half-resolution cells toward the painted mountains, hills and volcanoes (highest ${summary.highest}) before routing the rivers`,
171
+ details: { ...summary, settings: input.painted.settings },
172
+ });
173
+ }
161
174
  const adjust = input.adjustHeight;
162
175
  if (adjust !== undefined)
163
176
  for (let y = 0; y < macro.height; y += 1)