hoi4-agent-tools 4.16.0 → 4.18.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.
- package/CHANGELOG.md +41 -0
- package/README.md +1 -0
- package/dist/hoi4_agent_tools/core/analysis-checkpoints.js +11 -4
- package/dist/hoi4_agent_tools/core/engine-client.js +30 -1
- package/dist/hoi4_agent_tools/core/engine.js +56 -27
- package/dist/hoi4_agent_tools/core/managed-outputs.js +54 -3
- package/dist/hoi4_agent_tools/core/operation-result.js +37 -6
- package/dist/hoi4_agent_tools/core/scanner.js +148 -7
- package/dist/hoi4_agent_tools/core/server-state.js +50 -2
- package/dist/hoi4_agent_tools/core/source/localisation.js +7 -1
- package/dist/hoi4_agent_tools/event/compare.js +47 -13
- package/dist/hoi4_agent_tools/event/operations.js +111 -20
- package/dist/hoi4_agent_tools/focus/importer.js +2 -5
- package/dist/hoi4_agent_tools/focus/lint.js +2 -5
- package/dist/hoi4_agent_tools/focus/model.js +19 -0
- package/dist/hoi4_agent_tools/focus/tool-operations.js +16 -1
- package/dist/hoi4_agent_tools/focus/tool-support.js +14 -0
- package/dist/hoi4_agent_tools/map/appearance-validation.js +6 -1
- package/dist/hoi4_agent_tools/map/border-quality-input.js +57 -8
- package/dist/hoi4_agent_tools/map/border-quality.js +15 -6
- package/dist/hoi4_agent_tools/map/engine-raster.js +160 -0
- package/dist/hoi4_agent_tools/map/limits.js +13 -0
- package/dist/hoi4_agent_tools/map/model.js +9 -8
- package/dist/hoi4_agent_tools/map/natural-lands.js +902 -0
- package/dist/hoi4_agent_tools/map/operations.js +266 -23
- package/dist/hoi4_agent_tools/map/partition-provinces.js +6 -2
- package/dist/hoi4_agent_tools/map/partition-tuning.js +37 -0
- package/dist/hoi4_agent_tools/map/service.js +25 -12
- package/dist/hoi4_agent_tools/map/territory-operations.js +180 -3
- package/dist/hoi4_agent_tools/map/territory-quality.js +72 -5
- package/dist/hoi4_agent_tools/map/territory.js +63 -2
- package/dist/hoi4_agent_tools/map/tool-operations.js +79 -3
- package/dist/hoi4_agent_tools/map/validation.js +23 -3
- package/dist/hoi4_agent_tools/map/water.js +13 -10
- package/dist/hoi4_agent_tools/map/world-outputs.js +41 -26
- package/dist/hoi4_agent_tools/map/world.js +51 -1
- package/dist/hoi4_agent_tools/mcp/tools/map.js +52 -0
- package/dist/hoi4_agent_tools/mcp/tools/reference.js +3 -3
- package/dist/hoi4_agent_tools/mcp/tools/technology.js +25 -1
- package/dist/hoi4_agent_tools/reference/closure.js +65 -0
- package/dist/hoi4_agent_tools/reference/command-phrases.json +7899 -1127
- package/dist/hoi4_agent_tools/reference/mod-index.js +14 -5
- package/dist/hoi4_agent_tools/reference/operations.js +38 -21
- package/dist/hoi4_agent_tools/reference/ranking.js +77 -2
- package/dist/hoi4_agent_tools/reference/script-validation.js +4 -2
- package/dist/hoi4_agent_tools/reference/service.js +45 -2
- package/dist/hoi4_agent_tools/reference/source-lookup.js +43 -121
- package/dist/hoi4_agent_tools/runtime.js +27 -11
- package/dist/hoi4_agent_tools/schemas/lenient-arguments.js +7 -1
- package/dist/hoi4_agent_tools/schemas/map-requests.js +29 -1
- package/dist/hoi4_agent_tools/schemas/map.js +103 -2
- package/dist/hoi4_agent_tools/schemas/mod-tools.js +49 -0
- package/dist/hoi4_agent_tools/schemas/reference.js +1 -1
- package/dist/hoi4_agent_tools/schemas/script-validation.js +57 -3
- package/dist/hoi4_agent_tools/technology/operations.js +5 -0
- package/dist/hoi4_agent_tools/technology/queries.js +54 -0
- package/dist/hoi4_agent_tools/version.js +1 -1
- package/docs/configuration.md +1 -1
- package/docs/map.md +67 -23
- package/docs/research/reference-benchmark.md +64 -0
- package/docs/tools.md +20 -20
- package/docs/troubleshooting.md +4 -0
- package/engine/bin/darwin-arm64/hoi4-engine +0 -0
- package/engine/bin/linux-arm64/hoi4-engine +0 -0
- package/engine/bin/linux-x64/hoi4-engine +0 -0
- package/engine/bin/manifest.json +8 -8
- package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +5 -3
- package/schemas/configuration.schema.json +1 -1
- package/schemas/continuous-focus-palette.schema.json +1 -1
- package/schemas/custom-weighted-pool.schema.json +1 -1
- package/schemas/decision-inspect-input.schema.json +1 -1
- package/schemas/error-log-input.schema.json +1 -1
- package/schemas/event-feature-manifest.schema.json +1 -1
- package/schemas/focus-plan.schema.json +1 -1
- package/schemas/focus-planning-sidecar.schema.json +1 -1
- package/schemas/geography-model.schema.json +1 -1
- package/schemas/gui-animation-source.schema.json +1 -1
- package/schemas/gui-helper.schema.json +1 -1
- package/schemas/gui-scenario.schema.json +1 -1
- package/schemas/helper-expansion-request.schema.json +1 -1
- package/schemas/helper-expansion-summary.schema.json +1 -1
- package/schemas/impact-inspect-input.schema.json +1 -1
- package/schemas/map-operation.schema.json +1087 -815
- package/schemas/mechanic-test-input.schema.json +1 -1
- package/schemas/mod-index-input.schema.json +1 -1
- package/schemas/operation-result.schema.json +1 -1
- package/schemas/package-check-input.schema.json +1 -1
- package/schemas/package-manifest.schema.json +1 -1
- package/schemas/probability-analysis-result.schema.json +1 -1
- package/schemas/probability-compare-input.schema.json +1 -1
- package/schemas/probability-evaluate-input.schema.json +1 -1
- package/schemas/probability-inspect-input.schema.json +1 -1
- package/schemas/probability-render-input.schema.json +1 -1
- package/schemas/probability-scenario-set.schema.json +1 -1
- package/schemas/probability-sequence-input.schema.json +1 -1
- package/schemas/probability-simulate-input.schema.json +1 -1
- package/schemas/probability-sweep-input.schema.json +1 -1
- package/schemas/reference-context-input.schema.json +1 -1
- package/schemas/reference-read-input.schema.json +1 -1
- package/schemas/reference-search-input.schema.json +2 -2
- package/schemas/reference-sheets.schema.json +1 -1
- package/schemas/scenario-suite.schema.json +1 -1
- package/schemas/scenario-test-input.schema.json +1 -1
- package/schemas/script-validate-input.schema.json +7 -1
- package/schemas/shared-scenario.schema.json +1 -1
- package/schemas/source-lookup-input.schema.json +1 -1
- package/server.json +2 -2
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import { ServiceError } from '../core/result.js';
|
|
2
2
|
import { BORDER_PROVINCE_KIND, buildBorderEdgeTableSteps, scoreBorderAssignment, } from './border-quality.js';
|
|
3
3
|
import { borderQualityInputFromIndex } from './border-quality-input.js';
|
|
4
|
+
import { naturalLandsInputFromIndex, naturalLandsSteps, } from './natural-lands.js';
|
|
4
5
|
import { cloneState, commitState, currentIndex, uniqueStrings, } from './operations.js';
|
|
5
6
|
import { clusterProvinces } from './partition-groups.js';
|
|
7
|
+
import { declaredCountryTags } from './references.js';
|
|
6
8
|
import { restructureStates } from './state-restructure.js';
|
|
7
9
|
import { buildTerritoryAtoms, buildTerritoryProvinceGraph, } from './territory-graph.js';
|
|
8
10
|
import { growTerritory, TERRITORY_MAX_COUNTRIES, } from './territory.js';
|
|
@@ -172,14 +174,50 @@ function buildAtomModel(world, unit, scope) {
|
|
|
172
174
|
excluded,
|
|
173
175
|
};
|
|
174
176
|
}
|
|
177
|
+
/** The land province nearest the centre of a water province, searched within 256 pixels. */
|
|
178
|
+
function nearestLandProvince(world, province) {
|
|
179
|
+
const raster = world.index.raster;
|
|
180
|
+
if (raster === undefined)
|
|
181
|
+
return undefined;
|
|
182
|
+
const { width, height, provinceIds } = raster;
|
|
183
|
+
let sumX = 0;
|
|
184
|
+
let sumY = 0;
|
|
185
|
+
let count = 0;
|
|
186
|
+
for (let pixel = 0; pixel < provinceIds.length; pixel += 1)
|
|
187
|
+
if (provinceIds[pixel] === province) {
|
|
188
|
+
sumX += pixel % width;
|
|
189
|
+
sumY += Math.floor(pixel / width);
|
|
190
|
+
count += 1;
|
|
191
|
+
}
|
|
192
|
+
if (count === 0)
|
|
193
|
+
return undefined;
|
|
194
|
+
const cx = Math.round(sumX / count);
|
|
195
|
+
const cy = Math.round(sumY / count);
|
|
196
|
+
for (let radius = 1; radius <= 256; radius += 1)
|
|
197
|
+
for (let dy = -radius; dy <= radius; dy += 1)
|
|
198
|
+
for (let dx = -radius; dx <= radius; dx += 1) {
|
|
199
|
+
if (Math.max(Math.abs(dx), Math.abs(dy)) !== radius)
|
|
200
|
+
continue;
|
|
201
|
+
const y = cy + dy;
|
|
202
|
+
if (y < 0 || y >= height)
|
|
203
|
+
continue;
|
|
204
|
+
const x = (((cx + dx) % width) + width) % width;
|
|
205
|
+
const id = provinceIds[y * width + x];
|
|
206
|
+
if (isLandProvince(world.table, id))
|
|
207
|
+
return id;
|
|
208
|
+
}
|
|
209
|
+
return undefined;
|
|
210
|
+
}
|
|
175
211
|
function resolveProvince(world, model, province, label) {
|
|
176
212
|
const { index, table } = world;
|
|
177
213
|
if (!index.definitionsById.has(province))
|
|
178
214
|
refuse('MAP_TERRITORY_PROVINCE_UNKNOWN', `${label}: province ${province} does not exist`, {
|
|
179
215
|
province,
|
|
180
216
|
});
|
|
181
|
-
if (!isLandProvince(table, province))
|
|
182
|
-
|
|
217
|
+
if (!isLandProvince(table, province)) {
|
|
218
|
+
const nearest = nearestLandProvince(world, province);
|
|
219
|
+
refuse('MAP_TERRITORY_SEED_IN_WATER', `${label}: province ${province} is not land (sea and lake provinces cannot be owned)${nearest === undefined ? '' : `; the nearest land province is ${nearest}`}`, { province, ...(nearest === undefined ? {} : { nearestLandProvince: nearest }) });
|
|
220
|
+
}
|
|
183
221
|
const atom = model.atoms.atomOfProvince[province];
|
|
184
222
|
if (atom < 0)
|
|
185
223
|
refuse('MAP_TERRITORY_PROVINCE_WITHOUT_STATE', `${label}: province ${province} belongs to no state, so it cannot have an owner`, { province });
|
|
@@ -211,12 +249,59 @@ function resolveRef(world, model, ref, label) {
|
|
|
211
249
|
}
|
|
212
250
|
if ('province' in ref)
|
|
213
251
|
return resolveProvince(world, model, ref.province, label);
|
|
252
|
+
if ('land' in ref) {
|
|
253
|
+
const provinces = landMembers(world, ref.land, label);
|
|
254
|
+
// The province nearest the land's centre, lowest id on a tie.
|
|
255
|
+
const { sumX, sumY, size } = world.graph;
|
|
256
|
+
let totalX = 0;
|
|
257
|
+
let totalY = 0;
|
|
258
|
+
let pixels = 0;
|
|
259
|
+
for (const province of provinces) {
|
|
260
|
+
totalX += sumX[province];
|
|
261
|
+
totalY += sumY[province];
|
|
262
|
+
pixels += size[province];
|
|
263
|
+
}
|
|
264
|
+
const centreX = totalX / Math.max(1, pixels);
|
|
265
|
+
const centreY = totalY / Math.max(1, pixels);
|
|
266
|
+
let best = provinces[0];
|
|
267
|
+
let bestDistance = Infinity;
|
|
268
|
+
for (const province of provinces) {
|
|
269
|
+
const n = Math.max(1, size[province]);
|
|
270
|
+
const distance = (sumX[province] / n - centreX) ** 2 + (sumY[province] / n - centreY) ** 2;
|
|
271
|
+
if (distance < bestDistance) {
|
|
272
|
+
best = province;
|
|
273
|
+
bestDistance = distance;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
return resolveProvince(world, model, best, `${label} in land ${ref.land}`);
|
|
277
|
+
}
|
|
214
278
|
const raster = world.index.raster;
|
|
215
279
|
if (ref.x < 0 || ref.y < 0 || ref.x >= raster.width || ref.y >= raster.height)
|
|
216
280
|
refuse('MAP_TERRITORY_POINT_OUTSIDE_MAP', `${label}: point (${ref.x}, ${ref.y}) is outside the ${raster.width} x ${raster.height} map`, { x: ref.x, y: ref.y });
|
|
217
281
|
const province = raster.provinceIds[ref.y * raster.width + ref.x];
|
|
218
282
|
return resolveProvince(world, model, province, `${label} at (${ref.x}, ${ref.y})`);
|
|
219
283
|
}
|
|
284
|
+
/** The provinces of a natural land the request names. */
|
|
285
|
+
function landMembers(world, land, label) {
|
|
286
|
+
const found = world.lands?.lands.find(({ id }) => id === land);
|
|
287
|
+
if (found === undefined)
|
|
288
|
+
refuse('MAP_NATURAL_LAND_UNKNOWN', `${label}: natural land ${land} does not exist with these landOptions; list the lands with hoi4.map_inspect lands: true and the same options`, { landId: land });
|
|
289
|
+
return found.provinces;
|
|
290
|
+
}
|
|
291
|
+
/** Whether the operation names any natural land, so the lands must be cut. */
|
|
292
|
+
function namesLands(operation) {
|
|
293
|
+
const selections = [
|
|
294
|
+
operation.unowned,
|
|
295
|
+
...operation.countries.flatMap((country) => [
|
|
296
|
+
country.forced,
|
|
297
|
+
country.blocked,
|
|
298
|
+
country.cores,
|
|
299
|
+
country.claims,
|
|
300
|
+
]),
|
|
301
|
+
];
|
|
302
|
+
return (selections.some((selection) => (selection?.landIds?.length ?? 0) > 0) ||
|
|
303
|
+
operation.countries.some((country) => country.seeds.some((seed) => 'land' in seed)));
|
|
304
|
+
}
|
|
220
305
|
function resolveSelection(world, model, selection, label) {
|
|
221
306
|
const atoms = new Set();
|
|
222
307
|
if (selection === undefined)
|
|
@@ -242,6 +327,13 @@ function resolveSelection(world, model, selection, label) {
|
|
|
242
327
|
for (const province of selection.provinceIds ?? []) {
|
|
243
328
|
atoms.add(resolveProvince(world, model, province, label));
|
|
244
329
|
}
|
|
330
|
+
// A land's provinces outside the scope or without a state are left out, as a state's are.
|
|
331
|
+
for (const land of selection.landIds ?? [])
|
|
332
|
+
for (const province of landMembers(world, land, label)) {
|
|
333
|
+
const atom = model.atoms.atomOfProvince[province];
|
|
334
|
+
if (atom >= 0)
|
|
335
|
+
atoms.add(atom);
|
|
336
|
+
}
|
|
245
337
|
if (selection.regionIds !== undefined) {
|
|
246
338
|
const wanted = new Set(selection.regionIds);
|
|
247
339
|
for (const region of wanted)
|
|
@@ -348,6 +440,39 @@ function growInRequestTerms(model, countries, options) {
|
|
|
348
440
|
});
|
|
349
441
|
}
|
|
350
442
|
}
|
|
443
|
+
/**
|
|
444
|
+
* The culture groups of `assign_territory` on the atoms: a province atom takes its province's
|
|
445
|
+
* group, a state atom the group most of its land provinces have (the lowest name on a tie).
|
|
446
|
+
*/
|
|
447
|
+
function atomGroups(world, model, operation) {
|
|
448
|
+
const input = operation.groups;
|
|
449
|
+
if (input === undefined || Object.keys(input).length === 0)
|
|
450
|
+
return {};
|
|
451
|
+
const names = [...new Set(Object.values(input))].sort();
|
|
452
|
+
const code = new Map(names.map((name, position) => [name, position]));
|
|
453
|
+
const votes = new Map();
|
|
454
|
+
for (const [key, name] of Object.entries(input)) {
|
|
455
|
+
const province = Number(key);
|
|
456
|
+
if (!Number.isInteger(province) || !world.index.definitionsById.has(province))
|
|
457
|
+
refuse('MAP_TERRITORY_PROVINCE_UNKNOWN', `groups: province ${key} does not exist`, {
|
|
458
|
+
province: key,
|
|
459
|
+
});
|
|
460
|
+
const atom = model.atoms.atomOfProvince[province] ?? -1;
|
|
461
|
+
if (atom < 0)
|
|
462
|
+
continue;
|
|
463
|
+
const tally = votes.get(atom) ?? new Map();
|
|
464
|
+
tally.set(code.get(name), (tally.get(code.get(name)) ?? 0) + 1);
|
|
465
|
+
votes.set(atom, tally);
|
|
466
|
+
}
|
|
467
|
+
const groups = new Int32Array(model.atoms.count).fill(-1);
|
|
468
|
+
for (const [atom, tally] of votes)
|
|
469
|
+
groups[atom] = [...tally].sort(([a, x], [b, y]) => y - x || a - b)[0][0];
|
|
470
|
+
return {
|
|
471
|
+
groups,
|
|
472
|
+
...(operation.groupPenalty === undefined ? {} : { groupPenalty: operation.groupPenalty }),
|
|
473
|
+
...(operation.groupHard === true ? { groupHard: true } : {}),
|
|
474
|
+
};
|
|
475
|
+
}
|
|
351
476
|
function limited(values, limit = 1_000) {
|
|
352
477
|
return values.slice(0, limit);
|
|
353
478
|
}
|
|
@@ -363,6 +488,11 @@ export function* applyAssignTerritory(base, changes, allocations, operation, sig
|
|
|
363
488
|
refuse('MAP_TERRITORY_STATE_SIZE_INVALID', 'stateSize.max must not be below stateSize.min');
|
|
364
489
|
const index = currentIndex(base, changes);
|
|
365
490
|
const world = yield* buildTerritoryWorld(index, signal);
|
|
491
|
+
if (namesLands(operation))
|
|
492
|
+
world.lands = yield* naturalLandsSteps(naturalLandsInputFromIndex(index).input, {
|
|
493
|
+
...(operation.landOptions ?? {}),
|
|
494
|
+
...(signal === undefined ? {} : { signal }),
|
|
495
|
+
});
|
|
366
496
|
const model = buildAtomModel(world, unit, operation.scope);
|
|
367
497
|
const atoms = model.atoms;
|
|
368
498
|
const policy = ownershipPolicy(operation.ownership);
|
|
@@ -386,6 +516,8 @@ export function* applyAssignTerritory(base, changes, allocations, operation, sig
|
|
|
386
516
|
};
|
|
387
517
|
if (country.overlord !== undefined)
|
|
388
518
|
entry.overlord = country.overlord;
|
|
519
|
+
if (country.fixed === true)
|
|
520
|
+
entry.fixed = true;
|
|
389
521
|
if (country.mergeInto !== undefined)
|
|
390
522
|
entry.mergeInto = country.mergeInto;
|
|
391
523
|
countries.push(entry);
|
|
@@ -412,6 +544,7 @@ export function* applyAssignTerritory(base, changes, allocations, operation, sig
|
|
|
412
544
|
? {}
|
|
413
545
|
: { maxShareChange: operation.smoothing.maxShareChange }),
|
|
414
546
|
},
|
|
547
|
+
...atomGroups(world, model, operation),
|
|
415
548
|
...(signal === undefined ? {} : { signal }),
|
|
416
549
|
};
|
|
417
550
|
const result = growInRequestTerms(model, countries, options);
|
|
@@ -497,9 +630,50 @@ export function* applyAssignTerritory(base, changes, allocations, operation, sig
|
|
|
497
630
|
mode: operation.borderQuality ?? 'report',
|
|
498
631
|
layer: 'country',
|
|
499
632
|
...(operation.borderTargets === undefined ? {} : { targets: operation.borderTargets }),
|
|
633
|
+
...(operation.borderQualityScope === undefined
|
|
634
|
+
? {}
|
|
635
|
+
: { scope: operation.borderQualityScope }),
|
|
500
636
|
},
|
|
501
637
|
};
|
|
502
|
-
|
|
638
|
+
const undefinedTags = undefinedTagDiagnostics(index, operation);
|
|
639
|
+
if (operation.strictTags === true && undefinedTags.length > 0)
|
|
640
|
+
refuse('MAP_TERRITORY_TAG_UNDEFINED', `strictTags: no common/country_tags file declares ${undefinedTags
|
|
641
|
+
.map(({ details }) => String(details?.tag))
|
|
642
|
+
.join(', ')}; declare the countries first or leave strictTags off`, { tags: undefinedTags.map(({ details }) => details?.tag) });
|
|
643
|
+
return {
|
|
644
|
+
diagnostics: [
|
|
645
|
+
...territoryDiagnostics(operation, world, report, result, model),
|
|
646
|
+
...undefinedTags,
|
|
647
|
+
],
|
|
648
|
+
report,
|
|
649
|
+
};
|
|
650
|
+
}
|
|
651
|
+
/**
|
|
652
|
+
* A warning for each country or overlord tag no active `common/country_tags` file declares: the
|
|
653
|
+
* states are written, but the game does not know the owner until the country is defined. Nothing
|
|
654
|
+
* is said when the workspace declares no tags at all, since then nothing can be checked.
|
|
655
|
+
*/
|
|
656
|
+
function undefinedTagDiagnostics(index, operation) {
|
|
657
|
+
const declared = declaredCountryTags(index.sourceFiles);
|
|
658
|
+
if (declared === undefined)
|
|
659
|
+
return [];
|
|
660
|
+
const used = new Map();
|
|
661
|
+
for (const country of operation.countries) {
|
|
662
|
+
used.set(country.tag, 'country');
|
|
663
|
+
if (country.overlord !== undefined && !used.has(country.overlord))
|
|
664
|
+
used.set(country.overlord, 'overlord');
|
|
665
|
+
}
|
|
666
|
+
return [...used]
|
|
667
|
+
.filter(([tag]) => !declared.has(tag))
|
|
668
|
+
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
|
|
669
|
+
.map(([tag, role]) => ({
|
|
670
|
+
code: 'MAP_TERRITORY_TAG_UNDEFINED',
|
|
671
|
+
severity: 'warning',
|
|
672
|
+
category: 'map',
|
|
673
|
+
operationId: operation.id,
|
|
674
|
+
message: `${tag} gets land, but no common/country_tags file declares it; define the country (country_tags, common/countries and history/countries) before the game loads the mod`,
|
|
675
|
+
details: { tag, role },
|
|
676
|
+
}));
|
|
503
677
|
}
|
|
504
678
|
const excludedCache = new WeakMap();
|
|
505
679
|
function excludedSet(model) {
|
|
@@ -910,6 +1084,9 @@ export function* applyRepartitionStates(base, changes, allocations, operation, s
|
|
|
910
1084
|
mode: operation.borderQuality ?? 'report',
|
|
911
1085
|
layer: 'state',
|
|
912
1086
|
...(operation.borderTargets === undefined ? {} : { targets: operation.borderTargets }),
|
|
1087
|
+
...(operation.borderQualityScope === undefined
|
|
1088
|
+
? {}
|
|
1089
|
+
: { scope: operation.borderQualityScope }),
|
|
913
1090
|
},
|
|
914
1091
|
};
|
|
915
1092
|
const diagnostics = [
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { ServiceError } from '../core/result.js';
|
|
2
2
|
import { borderQualityDiagnostics, borderTargetsForLayer, checkBorderTargets, measureBorderNaturalness, } from './border-quality.js';
|
|
3
|
-
import { borderQualityInputFromIndex } from './border-quality-input.js';
|
|
3
|
+
import { borderQualityInputFromIndex, borderQualityScopeIsEmpty, } from './border-quality-input.js';
|
|
4
|
+
import { canonicalJson } from '../core/canonical.js';
|
|
4
5
|
function targetsFor(layer, overrides) {
|
|
5
6
|
const targets = { ...borderTargetsForLayer(layer) };
|
|
6
7
|
if (overrides?.minEnrichment !== undefined)
|
|
@@ -14,7 +15,7 @@ function targetsFor(layer, overrides) {
|
|
|
14
15
|
function requests(plan) {
|
|
15
16
|
const result = [];
|
|
16
17
|
for (const report of plan.territory ?? []) {
|
|
17
|
-
const { mode, layer, targets } = report.borderQuality;
|
|
18
|
+
const { mode, layer, targets, scope } = report.borderQuality;
|
|
18
19
|
if (mode === 'off')
|
|
19
20
|
continue;
|
|
20
21
|
result.push({
|
|
@@ -24,6 +25,7 @@ function requests(plan) {
|
|
|
24
25
|
layers: layer === 'country' ? ['country', 'state'] : ['state'],
|
|
25
26
|
overrides: targets,
|
|
26
27
|
enforced: [layer],
|
|
28
|
+
scope: borderQualityScopeIsEmpty(scope) ? undefined : scope,
|
|
27
29
|
});
|
|
28
30
|
}
|
|
29
31
|
const failed = new Set(plan.blockers.map(({ operationId }) => operationId));
|
|
@@ -40,6 +42,7 @@ function requests(plan) {
|
|
|
40
42
|
layers: ['province', 'state', 'region', 'country'],
|
|
41
43
|
overrides: operation.data.borderTargets,
|
|
42
44
|
enforced: ['province', 'state', 'region', 'country'],
|
|
45
|
+
scope: undefined,
|
|
43
46
|
});
|
|
44
47
|
}
|
|
45
48
|
return result;
|
|
@@ -53,16 +56,40 @@ function describeFailures(check, layer) {
|
|
|
53
56
|
: `natural share ${String(value)} is below ${String(target)}`)
|
|
54
57
|
.join('; ')}`;
|
|
55
58
|
}
|
|
56
|
-
/**
|
|
59
|
+
/**
|
|
60
|
+
* Measure the final index for the operations that asked for border quality: once for the whole
|
|
61
|
+
* map and once more for each distinct `borderQualityScope`.
|
|
62
|
+
*/
|
|
57
63
|
export async function evaluateTerritoryQuality(plan, signal) {
|
|
58
64
|
const asked = requests(plan);
|
|
59
65
|
if (asked.length === 0)
|
|
60
66
|
return undefined;
|
|
67
|
+
const groups = new Map();
|
|
68
|
+
for (const request of asked) {
|
|
69
|
+
const key = request.scope === undefined ? '' : canonicalJson(request.scope);
|
|
70
|
+
groups.set(key, [...(groups.get(key) ?? []), request]);
|
|
71
|
+
}
|
|
72
|
+
const results = [];
|
|
73
|
+
for (const key of [...groups.keys()].sort())
|
|
74
|
+
results.push(await evaluateRequests(plan, groups.get(key), signal));
|
|
75
|
+
const whole = results.find((_, index) => [...groups.keys()].sort()[index] === '');
|
|
76
|
+
const report = (whole ?? results[0])?.report;
|
|
77
|
+
return {
|
|
78
|
+
diagnostics: results.flatMap(({ diagnostics }) => diagnostics),
|
|
79
|
+
blockers: results.flatMap(({ blockers }) => blockers),
|
|
80
|
+
operations: results.flatMap(({ operations }) => operations),
|
|
81
|
+
...(report === undefined ? {} : { report }),
|
|
82
|
+
skippedInputs: results[0]?.skippedInputs ?? [],
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
/** Measure the final index once, for requests that share one scope. */
|
|
86
|
+
async function evaluateRequests(plan, asked, signal) {
|
|
87
|
+
const scope = asked[0].scope;
|
|
61
88
|
const wanted = new Set(asked.flatMap(({ layers }) => layers));
|
|
62
89
|
let measured;
|
|
63
90
|
let skipped;
|
|
64
91
|
try {
|
|
65
|
-
const { input, skipped: missing } = borderQualityInputFromIndex(plan.finalIndex);
|
|
92
|
+
const { input, skipped: missing } = borderQualityInputFromIndex(plan.finalIndex, scope);
|
|
66
93
|
skipped = missing;
|
|
67
94
|
measured = await measureBorderNaturalness({ ...input, layers: input.layers.filter(({ name }) => wanted.has(name)) }, signal === undefined ? {} : { signal });
|
|
68
95
|
}
|
|
@@ -153,7 +180,7 @@ export async function evaluateTerritoryQuality(plan, signal) {
|
|
|
153
180
|
severity: 'info',
|
|
154
181
|
category: 'map',
|
|
155
182
|
operationId: request.operationId,
|
|
156
|
-
message: `Border naturalness of the proposed map: ${verdicts
|
|
183
|
+
message: `Border naturalness of the proposed map${scope === undefined ? '' : ' inside the scope'}: ${verdicts
|
|
157
184
|
.map(({ layer, report, check }) => `${layer} enrichment ${report.barrier.enrichment ?? 'n/a'}, natural share ${report.natural.share ?? 'n/a'}${report.straightness.fraction === null ? '' : `, straight ${report.straightness.fraction}`} (${check.passed ? 'meets' : 'misses'} the targets)`)
|
|
158
185
|
.join('; ')}`,
|
|
159
186
|
details: {
|
|
@@ -168,6 +195,7 @@ export async function evaluateTerritoryQuality(plan, signal) {
|
|
|
168
195
|
passed: check.passed,
|
|
169
196
|
targets,
|
|
170
197
|
})),
|
|
198
|
+
...(scope === undefined ? {} : { scope, scopePixels: measured.report.scopePixels ?? null }),
|
|
171
199
|
},
|
|
172
200
|
});
|
|
173
201
|
}
|
|
@@ -187,3 +215,42 @@ export function territoryArtifactContent(reports, quality) {
|
|
|
187
215
|
skippedInputs: quality?.skippedInputs ?? [],
|
|
188
216
|
};
|
|
189
217
|
}
|
|
218
|
+
/**
|
|
219
|
+
* The compact result of the territory operations as `map-territory-assignment.json`: who owns
|
|
220
|
+
* which provinces and which provinces make each new or changed state, without the whole map.
|
|
221
|
+
*/
|
|
222
|
+
export function territoryAssignmentContent(reports, finalIndex) {
|
|
223
|
+
const touched = new Set();
|
|
224
|
+
const removed = new Set();
|
|
225
|
+
// The report lists are capped, so every state of an assigned country counts as well.
|
|
226
|
+
const tags = new Set();
|
|
227
|
+
for (const report of reports) {
|
|
228
|
+
for (const id of [...report.states.changed, ...report.states.created])
|
|
229
|
+
touched.add(id);
|
|
230
|
+
for (const id of report.states.removed)
|
|
231
|
+
removed.add(id);
|
|
232
|
+
for (const country of report.stats?.countries ?? [])
|
|
233
|
+
tags.add(country.tag);
|
|
234
|
+
}
|
|
235
|
+
for (const state of finalIndex.states)
|
|
236
|
+
if (state.owner !== undefined && tags.has(state.owner))
|
|
237
|
+
touched.add(state.id);
|
|
238
|
+
const owners = {};
|
|
239
|
+
const states = {};
|
|
240
|
+
for (const state of [...finalIndex.states].sort((a, b) => a.id - b.id)) {
|
|
241
|
+
if (!touched.has(state.id))
|
|
242
|
+
continue;
|
|
243
|
+
const provinces = [...state.provinces].sort((a, b) => a - b);
|
|
244
|
+
states[String(state.id)] = provinces;
|
|
245
|
+
const tag = state.owner ?? '';
|
|
246
|
+
owners[tag] = [...(owners[tag] ?? []), ...provinces];
|
|
247
|
+
}
|
|
248
|
+
for (const list of Object.values(owners))
|
|
249
|
+
list.sort((a, b) => a - b);
|
|
250
|
+
return {
|
|
251
|
+
schemaVersion: 1,
|
|
252
|
+
owners,
|
|
253
|
+
states,
|
|
254
|
+
removedStates: [...removed].sort((a, b) => a - b),
|
|
255
|
+
};
|
|
256
|
+
}
|
|
@@ -219,6 +219,9 @@ class TerritoryRun {
|
|
|
219
219
|
rules;
|
|
220
220
|
barriers;
|
|
221
221
|
seaCost;
|
|
222
|
+
groups;
|
|
223
|
+
groupFactor;
|
|
224
|
+
groupHard;
|
|
222
225
|
jitter;
|
|
223
226
|
seed;
|
|
224
227
|
tolerance;
|
|
@@ -244,6 +247,9 @@ class TerritoryRun {
|
|
|
244
247
|
};
|
|
245
248
|
this.barriers = options.barriers ?? 'natural';
|
|
246
249
|
this.seaCost = options.seaCost ?? 3;
|
|
250
|
+
this.groups = options.groups;
|
|
251
|
+
this.groupFactor = 1 + (options.groupPenalty ?? 2);
|
|
252
|
+
this.groupHard = options.groupHard === true;
|
|
247
253
|
this.jitter = options.jitter ?? 0.08;
|
|
248
254
|
this.seed = options.seed ?? 0;
|
|
249
255
|
this.tolerance = options.shareTolerance ?? 0.15;
|
|
@@ -422,6 +428,10 @@ class TerritoryRun {
|
|
|
422
428
|
high[index] += islandTotal;
|
|
423
429
|
}
|
|
424
430
|
const fixedTarget = new Float64Array(entityCount).fill(-1);
|
|
431
|
+
// A fixed country's target is the land it starts with.
|
|
432
|
+
for (const [index, entity] of entities.entries())
|
|
433
|
+
if (entity.fixed)
|
|
434
|
+
fixedTarget[index] = [...new Set([...entity.seeds, ...entity.forced])].reduce((sum, atom) => sum + (open[atom] === 1 ? graph.size[atom] : 0), 0);
|
|
425
435
|
this.lastTargets = targets;
|
|
426
436
|
for (let pass = 0; pass < entityCount + 1; pass += 1) {
|
|
427
437
|
let remaining = openWeight;
|
|
@@ -471,22 +481,45 @@ class TerritoryRun {
|
|
|
471
481
|
for (let index = 0; index < entityCount; index += 1)
|
|
472
482
|
for (const atom of sources(index))
|
|
473
483
|
give(atom, index);
|
|
484
|
+
const groups = this.groups;
|
|
485
|
+
// A step across a culture line costs more, or is never taken when the lines are hard.
|
|
486
|
+
const across = (atom, next) => {
|
|
487
|
+
if (groups === undefined)
|
|
488
|
+
return 1;
|
|
489
|
+
const from = groups[atom];
|
|
490
|
+
const to = groups[next];
|
|
491
|
+
if (from < 0 || to < 0 || from === to)
|
|
492
|
+
return 1;
|
|
493
|
+
return this.groupHard ? 0 : this.groupFactor;
|
|
494
|
+
};
|
|
474
495
|
const relax = (atom, index, distance) => {
|
|
475
496
|
const entity = entities[index];
|
|
497
|
+
if (entity.fixed)
|
|
498
|
+
return;
|
|
476
499
|
// With the nearest policy an unseeded landmass is reached atom by atom over sea edges.
|
|
477
500
|
const byLand = !(this.rules.islandPolicy === 'nearest' && seeded[component[atom]] === 0);
|
|
478
501
|
for (let slot = graph.offsets[atom]; byLand && slot < graph.offsets[atom + 1]; slot += 1) {
|
|
479
502
|
const next = graph.to[slot];
|
|
480
503
|
if (open[next] === 0 || owner[next] >= 0 || entity.blocked.has(next))
|
|
481
504
|
continue;
|
|
482
|
-
|
|
505
|
+
const culture = across(atom, next);
|
|
506
|
+
if (culture === 0)
|
|
507
|
+
continue;
|
|
508
|
+
heap.push(distance +
|
|
509
|
+
(this.baseCost[slot] * regionFactor(index, next) * culture) / multiplier[index], index, next);
|
|
483
510
|
}
|
|
484
511
|
for (let slot = seaOffsets[atom]; slot < seaOffsets[atom + 1]; slot += 1) {
|
|
485
512
|
const next = seaAdjacent[slot];
|
|
486
513
|
if (owner[next] >= 0 || entity.blocked.has(next))
|
|
487
514
|
continue;
|
|
515
|
+
const seaCulture = across(atom, next);
|
|
516
|
+
if (seaCulture === 0)
|
|
517
|
+
continue;
|
|
488
518
|
heap.push(distance +
|
|
489
|
-
(this.centreDistance(atom, next) *
|
|
519
|
+
(this.centreDistance(atom, next) *
|
|
520
|
+
this.seaCost *
|
|
521
|
+
jitterSea(atom, next) *
|
|
522
|
+
seaCulture) /
|
|
490
523
|
multiplier[index], index, next);
|
|
491
524
|
}
|
|
492
525
|
};
|
|
@@ -624,6 +657,8 @@ class TerritoryRun {
|
|
|
624
657
|
#joinCutSeeds(entities, owner, forcedExtra, open, component, sourceOwner) {
|
|
625
658
|
const graph = this.graph;
|
|
626
659
|
for (const [index, entity] of entities.entries()) {
|
|
660
|
+
if (entity.fixed)
|
|
661
|
+
continue;
|
|
627
662
|
const capital = entity.seeds[0] ?? entity.forced[0];
|
|
628
663
|
if (capital === undefined)
|
|
629
664
|
continue;
|
|
@@ -730,6 +765,10 @@ class TerritoryRun {
|
|
|
730
765
|
tried.add(candidate);
|
|
731
766
|
if (entities[candidate].blocked.has(atom))
|
|
732
767
|
continue;
|
|
768
|
+
if (entities[candidate].fixed || entities[from].fixed)
|
|
769
|
+
continue;
|
|
770
|
+
if (this.groupHard && !this.#sameGroupNeighbour(atom, candidate, owner))
|
|
771
|
+
continue;
|
|
733
772
|
// Artificial border length before and after, over the atom's edges.
|
|
734
773
|
let gain = 0;
|
|
735
774
|
for (let s = graph.offsets[atom]; s < graph.offsets[atom + 1]; s += 1) {
|
|
@@ -765,6 +804,19 @@ class TerritoryRun {
|
|
|
765
804
|
break;
|
|
766
805
|
}
|
|
767
806
|
}
|
|
807
|
+
/** With hard culture lines: whether `atom` touches land of `candidate` in its own group. */
|
|
808
|
+
#sameGroupNeighbour(atom, candidate, owner) {
|
|
809
|
+
const groups = this.groups;
|
|
810
|
+
if (groups === undefined || groups[atom] < 0)
|
|
811
|
+
return true;
|
|
812
|
+
const graph = this.graph;
|
|
813
|
+
for (let slot = graph.offsets[atom]; slot < graph.offsets[atom + 1]; slot += 1) {
|
|
814
|
+
const next = graph.to[slot];
|
|
815
|
+
if (owner[next] === candidate && (groups[next] < 0 || groups[next] === groups[atom]))
|
|
816
|
+
return true;
|
|
817
|
+
}
|
|
818
|
+
return false;
|
|
819
|
+
}
|
|
768
820
|
/** Whether the neighbours of `atom` owned by `from` stay joined when `atom` is taken away. */
|
|
769
821
|
#staysConnected(atom, from, owner) {
|
|
770
822
|
const graph = this.graph;
|
|
@@ -843,6 +895,7 @@ function validateCountries(atoms, countries, options) {
|
|
|
843
895
|
forced,
|
|
844
896
|
blocked: new Set(country.blocked ?? []),
|
|
845
897
|
home: new Set(country.homeRegions ?? []),
|
|
898
|
+
fixed: country.fixed === true,
|
|
846
899
|
overlord: -1,
|
|
847
900
|
mergeInto: -1,
|
|
848
901
|
});
|
|
@@ -891,6 +944,7 @@ export function growTerritory(atoms, countries, options = {}) {
|
|
|
891
944
|
['jitter', options.jitter ?? 0.08, 0, 0.5],
|
|
892
945
|
['barrierStrength', options.barrierStrength ?? 6, 0, 60],
|
|
893
946
|
['seaCost', options.seaCost ?? 3, 1, 50],
|
|
947
|
+
['groupPenalty', options.groupPenalty ?? 2, 0, 100],
|
|
894
948
|
['smoothing.maxShareChange', options.smoothing?.maxShareChange ?? 0.15, 0, 1],
|
|
895
949
|
])
|
|
896
950
|
if (!Number.isFinite(value) || value < low || value > high)
|
|
@@ -904,6 +958,11 @@ export function growTerritory(atoms, countries, options = {}) {
|
|
|
904
958
|
option: 'smoothing.passes',
|
|
905
959
|
value: passes,
|
|
906
960
|
});
|
|
961
|
+
if (options.groups !== undefined && options.groups.length !== atoms.count)
|
|
962
|
+
refuse('MAP_TERRITORY_OPTION_INVALID', 'Territory groups must give one group per atom', {
|
|
963
|
+
option: 'groups',
|
|
964
|
+
value: options.groups.length,
|
|
965
|
+
});
|
|
907
966
|
const resolved = validateCountries(atoms, countries, options);
|
|
908
967
|
const run = new TerritoryRun(atoms, options);
|
|
909
968
|
const signal = options.signal;
|
|
@@ -915,6 +974,7 @@ export function growTerritory(atoms, countries, options = {}) {
|
|
|
915
974
|
forced: resolved[index].forced,
|
|
916
975
|
blocked: resolved[index].blocked,
|
|
917
976
|
home: resolved[index].home,
|
|
977
|
+
fixed: resolved[index].fixed,
|
|
918
978
|
});
|
|
919
979
|
// Subjects form a tree under their overlord; a bloc is grown as one entity first.
|
|
920
980
|
const children = new Map();
|
|
@@ -941,6 +1001,7 @@ export function growTerritory(atoms, countries, options = {}) {
|
|
|
941
1001
|
forced: members.flatMap((member) => resolved[member].forced),
|
|
942
1002
|
blocked,
|
|
943
1003
|
home: new Set(members.flatMap((member) => [...resolved[member].home])),
|
|
1004
|
+
fixed: members.every((member) => resolved[member].fixed),
|
|
944
1005
|
};
|
|
945
1006
|
};
|
|
946
1007
|
const origin = new Int32Array(n).fill(-1);
|