@team-antioch/sc2-adjutant-height-tuner 0.0.0-stage → 0.2.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 TeamAntioch
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,120 @@
1
- # Temporary Holding Version
1
+ # height-tuner, an sc2-adjutant Utility
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Tune a terrain texture's height map in the game. On a tileset that height-blends, how a texture shows
4
+ over the one under it depends on the red channel of its normal map: whether it covers the ground in
5
+ solid clumps, breaks up into stones with grass in the gaps, or reads as sunken. The tuner builds a
6
+ small **test map** per texture. The base texture is held at full weight, and there is one **strip** per candidate
7
+ normal map (a **variant**). Each strip's paint rises from 0 to 100% left to right. Capture the strips and
8
+ judge them on a Still Review page.
9
+
10
+ It is a Utility ([ADR-0023](../../docs/adr/0023-utility-plugin-role.md)). The normal maps it makes
11
+ come from your own install and go only into the test map under a Mission's git-ignored `output/`
12
+ ([ADR-0027](../../docs/adr/0027-stock-files-made-on-each-machine.md)).
13
+
14
+ ## Using it
15
+
16
+ A Workspace made by `/sc2-adjutant:init` has it already. In another, install the package beside
17
+ sc2-adjutant and list it in the Workspace config:
18
+
19
+ ```sh
20
+ npm install @team-antioch/sc2-adjutant-height-tuner
21
+ ```
22
+
23
+ ```json
24
+ { "utilities": ["bundled:height-tuner"] }
25
+ ```
26
+
27
+ At the next session start, its `height-tuner` skill is copied into the Workspace's `.claude/skills/`.
28
+
29
+ It reads the game's files with a **CASC extractor**, named in `SC2_CASC_TOOL`: install one as
30
+ [tools/README.md](../../tools/README.md#a-casc-extractor) says. Without one, the command stops with
31
+ those install steps. The install is the machine config's
32
+ `sc2Path`.
33
+
34
+ ```sh
35
+ node node_modules/@team-antioch/sc2-adjutant-height-tuner/dist/tune.js missions/<id>/blueprint.json ShakurasCity2 [--base BelShirGrassLightEx2] [--variants <list>] [--pitch <degrees>] [--install <StarCraft II folder>]
36
+ ```
37
+
38
+ It writes `missions/<id>/output/height-tuner/<texture>/`:
39
+
40
+ | File | What it is |
41
+ |---|---|
42
+ | `HeightTune<texture>.SC2Map` | The test map, on the Mission's tileset and lighting |
43
+ | `shots.json` | Two Shots a strip, for `capture_shots`: every strip's low half (`<n>. <variant>, 0-50%`), then every strip's high half (`, 50-100%`) |
44
+ | `tune.json` | What each strip is: its variant, CTerrainTex id, normal map, scale and offset, mean height and share at 0; what the stock red channel holds; warnings |
45
+ | `blueprint.json` | The generated Blueprint the map is compiled from |
46
+ | `extract/` | The stock catalogs and normal map, from the install |
47
+
48
+ Capture the map with `capture_shots` (`mapPath` the map, `shots` from `shots.json`), then build a
49
+ Still Review round with `build_still_review`, one version whose capture holds every strip. The skill
50
+ runs all of it, with one subagent per texture when there are several.
51
+
52
+ ## Variants
53
+
54
+ A variant is a word: `<kind>[:<% at 0>][*<HeightMapScale>][+<HeightMapOffset>]`. The default list is
55
+ `stock,crush:15,crush:25,crush:40,inverted-crush:15,inverted-crush:25,inverted-crush:40`. A map holds 7
56
+ strips: its texture set's 8 textures, less the base. `stock` is always the first strip.
57
+
58
+ | Kind | Its red channel |
59
+ |---|---|
60
+ | `stock` | The texture's own normal map. With a scale or offset, a copy with only those changed |
61
+ | `crush:<n>` | The source height with the tile's broad bands flattened, then the lowest *n*% of the tile at 0 and the rest stretched up to the stock top. The base texture grows in the gaps between the stones |
62
+ | `inverted-crush:<n>` | The same, upside down: the highest *n*% (the stone tops) at 0. The base sits on the tops and the stone reads as sunken, with deep crevices |
63
+ | `flat` | The source height with the broad bands flattened, at the stock top |
64
+ | `relevel` | The source height stretched to 0..1 |
65
+
66
+ **The source height** is the stock normal map's red channel when that is a height. When it is flat,
67
+ or a copy of the normal's Y (86 Liberty textures), the source is integrated from the normal's slopes
68
+ instead (Frankot-Chellappa, periodic edges), and the command warns. For a texture whose red channel is a
69
+ height, the command checks the sign of the integrated height against it: on ShakurasCity2 they agree at 0.93. It
70
+ warns below 0.5.
71
+
72
+ **The share at 0** is found from each texture's own height, so `crush:25` puts a quarter of the tile
73
+ at 0 on any texture. On ShakurasCity2, `crush:25` reproduces the research's `scrush` (ImageMagick
74
+ `-level 28%,100%`; correlation 0.997) and `crush:43` its `scrush2` (`-level 34%`).
75
+
76
+ Each non-stock variant is a map-local `CTerrainTex` named `<texture>_Ht<Variant>`, for example
77
+ `ShakurasCity2_HtCrush25`. It is a copy of the stock entry's Texture, EditorIcon, PhysicsMaterial,
78
+ TilingFreq, POMScale and HeightMapScale/Offset (but not its DoodadEntry), with its own normal map at
79
+ `Assets\Textures\HeightTune_<texture>_<Variant>.dds`. That normal map is the stock file with only its red channel
80
+ rewritten at every mip level. Its alpha (the normal's X) is kept byte for byte, and its green (Y)
81
+ is re-encoded with the red, in the same DXT colour block (core's `recolourDdsAt`).
82
+
83
+ ## How the map is made
84
+
85
+ The command compiles a generated Mission Blueprint with core: the Mission's tileset and `lighting`,
86
+ one flat Zone painted with the base, and the textures `[base, texture]`. Then it dresses the package:
87
+
88
+ - texture slots 2-7 get the variants' ids in `t3Terrain.xml`, `t3SyncTextureInfo` and the
89
+ tileset's map-local `CTerrain` override in `TerrainData.xml`, which also gets
90
+ `HeightMapEnabled 1`;
91
+ - `t3TextureMasks` gets the strips: layer 0 (the base) at 15 everywhere, and strip *i* on layer
92
+ *i* + 1, from 0 to 15 in 16 steps of 4 cells along its 64 cells;
93
+ - `Base.SC2Data/GameData/TerrainTexData.xml` and `Assets/Textures/` get the variants.
94
+
95
+ Each strip is 16 cells wide, with 12 cells of base between strips and a 24-cell margin, so the
96
+ map is 112×232 cells for 7 strips. The Shots come in two passes: each strip's low half (paint
97
+ 0-50%, 8 of its 16 steps), then each strip's high half (50-100%), so the page shows the variants
98
+ side by side at the same weights. Each Shot frames 34×18 cells, a little farther back than the
99
+ player's own camera, and its 16:9 frame shows no other strip. That is where the ground is sharpest:
100
+ small strips framed from nearer were blurrier, since a closer camera only stretches the terrain
101
+ textures past their resolution (2026-11-28).
102
+
103
+ ## What it's built on
104
+
105
+ These facts are in [terrain-height-maps.md](../../docs/reference/terrain-height-maps.md):
106
+
107
+ - A layer's height is the red channel of its `Normalmap`. The `Heightmap` field does nothing on this build.
108
+ - A map-local `CTerrainTex` entry, with a normal map shipped in the package, works in the game.
109
+ - Only layers painted at a texel compete there, so the base must be painted under the test texture.
110
+
111
+ ## Files
112
+
113
+ | Path | What it is |
114
+ |---|---|
115
+ | `tune.ts` | The command |
116
+ | `build.ts` | The test map: the Blueprint, the compile, the slots, masks and data |
117
+ | `heights.ts` | The heights: reading the red channel, integrating a normal, flattening, crushing |
118
+ | `variants.ts` | The variant words and what each makes |
119
+ | `stock.ts` | The extractor, and reading the stock catalogs |
120
+ | `skills/height-tuner/` | The skill |
package/dist/.built ADDED
@@ -0,0 +1 @@
1
+ eff69340932ea134a1441580ea3da4c3213cb33d2c47d592e184e2edab9b4e67
package/dist/build.js ADDED
@@ -0,0 +1,328 @@
1
+ // One texture's test map: a small flat map of the base texture with a strip per variant, where the
2
+ // test texture's paint rises from 0 to 15/15 along the strip over the base held at 15/15.
3
+ //
4
+ // The map is a generated Mission Blueprint compiled by core into the Mission's git-ignored output,
5
+ // on the Mission's tileset (its lighting) with a set of two textures, the base and the test
6
+ // texture. The build then dresses the package: slots 2-7 get the variants' CTerrainTex copies (in
7
+ // t3Terrain.xml, t3SyncTextureInfo and the tileset override in TerrainData.xml, which also turns
8
+ // height blending on), t3TextureMasks gets the strips, and the variants' entries and normal maps
9
+ // go in as map-local data (Base.SC2Data/GameData/TerrainTexData.xml, Assets/Textures/).
10
+ import { existsSync } from "node:fs";
11
+ import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
12
+ import path from "node:path";
13
+ import { compileMission, decodeDds, ddsLayout, recolourDdsAt, TEXELS_PER_CELL, workspaceFor, writeT3SyncTextureInfo, writeT3TextureMasks, } from "@team-antioch/sc2-adjutant/plugin-sdk";
14
+ import { correlation, downsampled, flattenBands, integrateNormal, meanOf, readRed, redHeight, zeroShare } from "./heights.js";
15
+ import { CATALOG_PATTERNS, extract, filesByLowerPath, findExtracted, gameFile, readCatalogs, stockHeightMapEnabled, stockTexture } from "./stock.js";
16
+ import { needsNormalMap, variantHeight, variantLabel, variantName, variantRecipe, variantSuffix } from "./variants.js";
17
+ /** The texture the strips are painted over unless told otherwise: the Bel'Shir grass the first texture was tuned on. */
18
+ export const DEFAULT_BASE = "BelShirGrassLightEx2";
19
+ // The layout, in cells. A strip is 64 cells long (16 steps of 4 cells) and 16 wide, with 12 cells of
20
+ // plain base between strips, so half a strip fills a frame at the player's camera distance (about 32
21
+ // cells across) and shows none of the next. A closer camera only magnifies the terrain textures past
22
+ // their resolution (2026-11-28). The margin keeps every Shot clear of the camera's bounds at the
23
+ // map's edge.
24
+ export const STRIP_LENGTH = 64;
25
+ export const STRIP_WIDTH = 16;
26
+ export const STRIP_GAP = 12;
27
+ export const MARGIN = 24;
28
+ /** Weight steps along a strip: 0 to 15 of 15. */
29
+ export const STEPS = 16;
30
+ /** A Shot frames half a strip (8 of its 16 steps) with a cell to spare each side. */
31
+ const SHOT_MARGIN = 1;
32
+ /** The two passes: each strip's low half, then its high half. */
33
+ export const PASSES = [
34
+ { from: 0, label: "0-50%" },
35
+ { from: 0.5, label: "50-100%" },
36
+ ];
37
+ /** The CTerrainTex fields a variant copies from the stock entry: what makes it look and blend as the stock one does. */
38
+ const COPIED_FIELDS = ["Texture", "EditorIcon", "Normalmap", "PhysicsMaterial", "TilingFreq", "POMScale", "HeightMapScale", "HeightMapOffset"];
39
+ /** The tuner's folder for one texture in a Mission's output. */
40
+ export const tuneFolder = (blueprintPath, texture) => path.join(path.dirname(blueprintPath), "output", "height-tuner", texture);
41
+ /** Where a texture's stock files are extracted to: its own folder, so tuners run side by side don't share one. */
42
+ const extractFolder = (folder) => path.join(folder, "extract");
43
+ /** The Still Review set a texture's strips are judged in. */
44
+ export const reviewSet = (texture) => `height-${texture.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`;
45
+ /** Cells: a strip's rectangle, by its index from the bottom. */
46
+ export function stripRect(index) {
47
+ const bottom = MARGIN + index * (STRIP_WIDTH + STRIP_GAP);
48
+ return [MARGIN, bottom, MARGIN + STRIP_LENGTH, bottom + STRIP_WIDTH];
49
+ }
50
+ /** The map's size for `strips` strips, each side a multiple of 8 (the texture blocks). */
51
+ export function mapSize(strips) {
52
+ const up = (value) => Math.ceil(value / 8) * 8;
53
+ return { width: up(2 * MARGIN + STRIP_LENGTH), height: up(2 * MARGIN + strips * STRIP_WIDTH + (strips - 1) * STRIP_GAP) };
54
+ }
55
+ /**
56
+ * Each texel's 8 layer weights (0..15), [texel * 8 + layer], rows from the bottom: the base on
57
+ * layer 0 at 15 everywhere, strip i on layer i + 1 rising from 0 to 15 across it in STEPS steps.
58
+ */
59
+ export function stripWeights(strips) {
60
+ const { width, height } = mapSize(strips);
61
+ const [maskWidth, maskHeight] = [width * TEXELS_PER_CELL, height * TEXELS_PER_CELL];
62
+ const weights = new Uint8Array(maskWidth * maskHeight * 8);
63
+ for (let texel = 0; texel < maskWidth * maskHeight; texel++)
64
+ weights[texel * 8] = 15;
65
+ const stepTexels = (STRIP_LENGTH * TEXELS_PER_CELL) / STEPS;
66
+ for (let strip = 0; strip < strips; strip++) {
67
+ const [left, bottom, right, top] = stripRect(strip).map((cells) => cells * TEXELS_PER_CELL);
68
+ for (let y = bottom; y < top; y++)
69
+ for (let x = left; x < right; x++)
70
+ weights[(y * maskWidth + x) * 8 + strip + 1] = Math.min(15, Math.floor((x - left) / stepTexels));
71
+ }
72
+ return weights;
73
+ }
74
+ /**
75
+ * The Shots of a test map, in two passes: every strip's low half (paint 0-50%, its left), then
76
+ * every strip's high half (50-100%, its right), so the page shows the variants side by side at the
77
+ * same weights. Each frames 34×18 cells, at about the player's camera distance.
78
+ */
79
+ export function stripShots(variants, pitch) {
80
+ return PASSES.flatMap((pass) => variants.map((variant, index) => {
81
+ const [left, bottom, right, top] = stripRect(index);
82
+ const start = left + pass.from * (right - left);
83
+ return {
84
+ rect: [start - SHOT_MARGIN, bottom - SHOT_MARGIN, start + (right - left) / 2 + SHOT_MARGIN, top + SHOT_MARGIN],
85
+ label: `${index + 1}. ${variantLabel(variant)}, ${pass.label}`,
86
+ ...(pitch !== undefined ? { pitch } : {}),
87
+ };
88
+ }));
89
+ }
90
+ /** The CTerrainTex id of a variant's copy: `ShakurasCity2_HtCrush28`. */
91
+ export const variantTextureId = (texture, variant) => `${texture}_Ht${variantSuffix(variant)}`;
92
+ /** The map path of a variant's normal map. */
93
+ export const variantNormalPath = (texture, variant) => `Assets\\Textures\\HeightTune_${texture}_${variantSuffix(variant)}.dds`;
94
+ const xmlAttribute = (value) => value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
95
+ /** The map-local TerrainTexData.xml: a full copy of the stock entry per variant, with its own normal map, scale and offset. */
96
+ export function variantCatalog(stock, variants) {
97
+ const entries = variants
98
+ .filter((variant) => needsNormalMap(variant) || variant.scale !== undefined || variant.offset !== undefined)
99
+ .map((variant) => {
100
+ const fields = {};
101
+ for (const name of COPIED_FIELDS)
102
+ if (stock.fields[name] !== undefined)
103
+ fields[name] = stock.fields[name];
104
+ if (needsNormalMap(variant))
105
+ fields.Normalmap = variantNormalPath(stock.id, variant);
106
+ if (variant.scale !== undefined)
107
+ fields.HeightMapScale = String(variant.scale);
108
+ if (variant.offset !== undefined)
109
+ fields.HeightMapOffset = String(variant.offset);
110
+ const lines = Object.entries(fields).map(([name, value]) => ` <${name} value="${xmlAttribute(value)}"/>`);
111
+ return [` <CTerrainTex id="${variantTextureId(stock.id, variant)}">`, ...lines, " </CTerrainTex>"].join("\n");
112
+ });
113
+ return ['<?xml version="1.0" encoding="utf-8"?>', "<Catalog>", ...entries, "</Catalog>", ""].join("\n");
114
+ }
115
+ /** `xml`'s tileset override (the compile's map-local CTerrain) with the 8 slots `names` and height blending on. */
116
+ export function withSlots(terrainData, tileset, names) {
117
+ const opening = new RegExp(`<CTerrain id="${tileset}">`);
118
+ const at = terrainData.search(opening);
119
+ if (at < 0)
120
+ throw new Error(`The compiled map's TerrainData.xml has no <CTerrain id="${tileset}"> override to put the variants in`);
121
+ const end = terrainData.indexOf("</CTerrain>", at);
122
+ const body = terrainData
123
+ .slice(at, end)
124
+ .split("\n")
125
+ .filter((line) => !/<(BlendTextures|HeightMapEnabled)\b/.test(line))
126
+ .join("\n")
127
+ .replace(/\s*$/, "");
128
+ const added = [...names.map((name, index) => ` <BlendTextures index="${index}" value="${name}"/>`), ' <HeightMapEnabled value="1"/>'];
129
+ return `${terrainData.slice(0, at)}${body}\n${added.join("\n")}\n ${terrainData.slice(end)}`;
130
+ }
131
+ /** `xml` (t3Terrain.xml) with texture slots 0-7 named `names`. */
132
+ export function withSlotNames(terrainXml, names) {
133
+ let out = terrainXml;
134
+ names.forEach((name, slot) => {
135
+ const line = new RegExp(`(<texture i="${slot}" name=")[^"]*(")`);
136
+ if (!line.test(out))
137
+ throw new Error(`The compiled map's t3Terrain.xml has no texture slot ${slot}`);
138
+ out = out.replace(line, `$1${name}$2`);
139
+ });
140
+ return out;
141
+ }
142
+ /** The tileset a test map is on: the Mission's, for its lighting, else BelShirEx2 (the default base's). */
143
+ export const testTileset = (mission) => mission.tilesetId ?? "BelShirEx2";
144
+ /** The generated Blueprint the test map is compiled from. */
145
+ export function testBlueprint(mission, texture, base, strips) {
146
+ const { width, height } = mapSize(strips);
147
+ const tilesetId = testTileset(mission);
148
+ return {
149
+ id: `height-tune-${texture.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`,
150
+ campaignId: mission.campaignId,
151
+ title: `Height Tune ${texture}`,
152
+ summary: `Height-map test strips of ${texture} over ${base}, written by the height-tuner Utility.`,
153
+ setting: "A flat test field.",
154
+ mapSize: { width, height },
155
+ tilesetId,
156
+ ...(mission.lighting !== undefined ? { lighting: mission.lighting } : {}),
157
+ textures: [base, texture],
158
+ zones: [
159
+ {
160
+ id: "ground",
161
+ name: "Ground",
162
+ elevation: 1,
163
+ landform: "flat",
164
+ role: "base",
165
+ texture: base,
166
+ polygon: [
167
+ { x: 0, y: 0 },
168
+ { x: width, y: 0 },
169
+ { x: width, y: height },
170
+ { x: 0, y: height },
171
+ ],
172
+ connections: [],
173
+ },
174
+ ],
175
+ anchors: [],
176
+ beats: [{ id: "look", title: "Look", summary: "Judge the strips.", zoneIds: ["ground"], anchorIds: [] }],
177
+ screenplay: { title: `Height Tune ${texture}`, scenes: [] },
178
+ };
179
+ }
180
+ /** The level the highest stones keep in a variant: the stock red's top for a real height, else a little under 1, as the stock tops are. */
181
+ const topLevel = (red) => (red.kind === "height" ? red.max / 255 : 0.96);
182
+ /** Builds one texture's test map and its Shots; returns what it wrote. */
183
+ export async function buildTestMap(options) {
184
+ const log = options.log ?? (() => undefined);
185
+ const base = options.base ?? DEFAULT_BASE;
186
+ const { texture, variants, blueprintPath } = options;
187
+ if (texture === base)
188
+ throw new Error(`The texture to tune and the base are both ${texture}: the strips need a base texture of another kind under them`);
189
+ const warnings = [];
190
+ const mission = JSON.parse(await readFile(blueprintPath, "utf8"));
191
+ const tileset = testTileset(mission);
192
+ const folder = tuneFolder(blueprintPath, texture);
193
+ await mkdir(folder, { recursive: true });
194
+ // The stock catalogs, then the texture's normal map, from this machine's install.
195
+ const extracted = extractFolder(folder);
196
+ let files = await filesByLowerPath(extracted);
197
+ if (!files.has("mods/core.sc2mod/base.sc2data/gamedata/terraintexdata.xml")) {
198
+ log(`Extracting the stock terrain catalogs from ${options.install}`);
199
+ await extract(options.install, CATALOG_PATTERNS, extracted, options.tool);
200
+ files = await filesByLowerPath(extracted);
201
+ }
202
+ const catalogs = await readCatalogs(files);
203
+ if (catalogs.textures.length === 0)
204
+ throw new Error(`No stock TerrainTexData.xml came out of ${options.install}: is it a StarCraft II install?`);
205
+ const stock = stockTexture(catalogs.textures, texture);
206
+ if (!stock)
207
+ throw new Error(`No stock CTerrainTex is called ${texture}`);
208
+ if (!stockTexture(catalogs.textures, base))
209
+ throw new Error(`No stock CTerrainTex is called ${base} (the base)`);
210
+ const normalGamePath = stock.fields.Normalmap;
211
+ if (!normalGamePath)
212
+ throw new Error(`${texture} names no Normalmap, so it has no height to tune`);
213
+ const normal = gameFile(normalGamePath);
214
+ let normalFile = findExtracted(files, normal.tail);
215
+ if (!normalFile) {
216
+ log(`Extracting ${normalGamePath}`);
217
+ await extract(options.install, [normal.pattern], extracted, options.tool);
218
+ files = await filesByLowerPath(extracted);
219
+ normalFile = findExtracted(files, normal.tail);
220
+ if (!normalFile)
221
+ throw new Error(`${texture}'s normal map ${normalGamePath} isn't in ${options.install}'s storage (13 stock textures name files that aren't)`);
222
+ }
223
+ // The heights.
224
+ const normalData = new Uint8Array(await readFile(normalFile));
225
+ const layout = ddsLayout(normalData);
226
+ if (layout.width !== layout.height)
227
+ throw new Error(`${normalGamePath} is ${layout.width}×${layout.height}; the tuner reads square normal maps`);
228
+ const top = decodeDds(normalData)[0];
229
+ const red = readRed(top.rgba);
230
+ const integrate = () => integrateNormal(top.rgba, top.width);
231
+ const source = red.kind === "height" ? redHeight(top.rgba, top.width) : integrate();
232
+ const heightSource = red.kind === "height" ? "red channel" : "integrated from the normal";
233
+ let integratedAgreement;
234
+ if (red.kind === "height") {
235
+ // The sign check the research asked for: the integrated height should agree with Blizzard's.
236
+ integratedAgreement = correlation(integrate(), source);
237
+ if (integratedAgreement < 0.5)
238
+ warnings.push(`${texture}'s height integrated from its normal agrees with its red channel at only ${integratedAgreement.toFixed(2)}: its red channel may not be the height its normal shows`);
239
+ }
240
+ else {
241
+ warnings.push(`${texture}'s red channel is ${red.kind === "flat" ? `flat (${Math.round(red.mean)} everywhere)` : "a copy of its normal's Y, not a height"}: the variants' heights are integrated from its normal instead`);
242
+ }
243
+ const flattened = flattenBands(source);
244
+ // The test map.
245
+ const blueprintFile = path.join(folder, "blueprint.json");
246
+ await writeFile(blueprintFile, `${JSON.stringify(testBlueprint(mission, texture, base, variants.length), null, 2)}\n`);
247
+ const mapPath = path.join(folder, `HeightTune${texture}.SC2Map`);
248
+ await rm(mapPath, { recursive: true, force: true });
249
+ log(`Compiling the test map into ${mapPath}`);
250
+ const compiled = await compileMission(await workspaceFor(blueprintFile), blueprintFile, mapPath);
251
+ warnings.push(...compiled.warnings);
252
+ const strips = [];
253
+ const slotNames = [base];
254
+ const assets = path.join(mapPath, "Assets", "Textures");
255
+ for (const [index, variant] of variants.entries()) {
256
+ const own = needsNormalMap(variant) || variant.scale !== undefined || variant.offset !== undefined;
257
+ const textureId = own ? variantTextureId(texture, variant) : texture;
258
+ slotNames.push(textureId);
259
+ const height = variantHeight(variant, source, flattened, topLevel(red));
260
+ let normalMap = normalGamePath;
261
+ if (height) {
262
+ normalMap = variantNormalPath(texture, variant);
263
+ const levels = new Map();
264
+ const atSize = (size) => levels.get(size) ?? (levels.set(size, downsampled(height, size)), levels.get(size));
265
+ const written = recolourDdsAt(normalData, ([, g, b], x, y, width) => [atSize(width).values[y * width + x] * 255, g, b]);
266
+ await mkdir(assets, { recursive: true });
267
+ await writeFile(path.join(assets, path.basename(normalMap.split("\\").join("/"))), written);
268
+ }
269
+ const shown = height ?? source;
270
+ strips.push({
271
+ variant: variantName(variant),
272
+ label: variantLabel(variant),
273
+ recipe: variantRecipe(variant),
274
+ textureId,
275
+ normalMap,
276
+ ...(variant.scale !== undefined || stock.fields.HeightMapScale !== undefined ? { heightMapScale: String(variant.scale ?? stock.fields.HeightMapScale) } : {}),
277
+ ...(variant.offset !== undefined || stock.fields.HeightMapOffset !== undefined ? { heightMapOffset: String(variant.offset ?? stock.fields.HeightMapOffset) } : {}),
278
+ heightMean: round(meanOf(shown)),
279
+ zeroShare: round(zeroShare(shown)),
280
+ rect: stripRect(index),
281
+ });
282
+ }
283
+ while (slotNames.length < 8)
284
+ slotNames.push("");
285
+ // Dress the package: the slots, the strips' paint and the variants' data.
286
+ const terrainXmlFile = path.join(mapPath, "t3Terrain.xml");
287
+ await writeFile(terrainXmlFile, withSlotNames(await readFile(terrainXmlFile, "utf8"), slotNames));
288
+ const terrainDataFile = path.join(mapPath, "Base.SC2Data", "GameData", "TerrainData.xml");
289
+ await writeFile(terrainDataFile, withSlots(await readFile(terrainDataFile, "utf8"), tileset, slotNames));
290
+ const { width, height } = mapSize(variants.length);
291
+ const weights = stripWeights(variants.length);
292
+ await writeFile(path.join(mapPath, "t3TextureMasks"), writeT3TextureMasks({ width, height, textureWeights: new Uint8Array(width * height * 8), texelWeights: weights }));
293
+ const dominant = new Uint32Array(width * height);
294
+ const [maskWidth, half] = [width * TEXELS_PER_CELL, TEXELS_PER_CELL / 2];
295
+ for (let cy = 0; cy < height; cy++) {
296
+ for (let cx = 0; cx < width; cx++) {
297
+ const centre = ((cy * TEXELS_PER_CELL + half) * maskWidth + cx * TEXELS_PER_CELL + half) * 8;
298
+ for (let layer = 1; layer < 8; layer++)
299
+ if (weights[centre + layer] > 7)
300
+ dominant[cy * width + cx] = layer;
301
+ }
302
+ }
303
+ await writeFile(path.join(mapPath, "t3SyncTextureInfo"), writeT3SyncTextureInfo({ width, height, textureSetCount: 1, textureNames: slotNames, dominantTextureIndices: dominant, textureSetIndices: new Uint32Array(width * height) }));
304
+ const textureDataFile = path.join(mapPath, "Base.SC2Data", "GameData", "TerrainTexData.xml");
305
+ if (existsSync(textureDataFile))
306
+ throw new Error(`The compiled map already has a TerrainTexData.xml, which the tuner would overwrite: ${textureDataFile}`);
307
+ await writeFile(textureDataFile, variantCatalog(stock, variants));
308
+ const shotsPath = path.join(folder, "shots.json");
309
+ await writeFile(shotsPath, `${JSON.stringify({ shots: stripShots(variants, options.pitch) }, null, 2)}\n`);
310
+ const report = {
311
+ texture,
312
+ base,
313
+ tileset,
314
+ mapPath,
315
+ shotsPath,
316
+ red,
317
+ heightSource,
318
+ ...(integratedAgreement !== undefined ? { integratedAgreement: round(integratedAgreement) } : {}),
319
+ stockHeightBlending: stockHeightMapEnabled(catalogs.terrains, tileset),
320
+ strips,
321
+ warnings,
322
+ };
323
+ if (report.stockHeightBlending !== true)
324
+ warnings.push(`${tileset} doesn't height-blend in stock data; the test map turns it on, so a Mission on ${tileset} needs it turned on too for its ground to look like this`);
325
+ await writeFile(path.join(folder, "tune.json"), `${JSON.stringify(report, null, 2)}\n`);
326
+ return report;
327
+ }
328
+ const round = (value) => Math.round(value * 1000) / 1000;
@@ -0,0 +1,251 @@
1
+ // The heights the tuner writes into a normal map's red channel (docs/reference/height-blending.md).
2
+ // A layer's height is the red channel of its CTerrainTex Normalmap, 0..1, so a variant is a new red
3
+ // channel for the test texture's own normal map: its green (Y) and alpha (X) stay the normal.
4
+ //
5
+ // Every height here is a square image of values 0..1, row-major from the top left, and treated as
6
+ // tiling: blurs wrap round its edges, as the texture does on the ground.
7
+ /** The thresholds the research's classification of every stock texture used. */
8
+ const FLAT_SD = 3;
9
+ const NORMAL_COPY_CORR = 0.85;
10
+ /** The red channel of an RGBA image, classified. */
11
+ export function readRed(rgba) {
12
+ const n = rgba.length / 4;
13
+ let [sumR, sumG, min, max] = [0, 0, 255, 0];
14
+ for (let i = 0; i < n; i++) {
15
+ const r = rgba[4 * i];
16
+ sumR += r;
17
+ sumG += rgba[4 * i + 1];
18
+ if (r < min)
19
+ min = r;
20
+ if (r > max)
21
+ max = r;
22
+ }
23
+ const [meanR, meanG] = [sumR / n, sumG / n];
24
+ let [varR, varG, cov] = [0, 0, 0];
25
+ for (let i = 0; i < n; i++) {
26
+ const [r, g] = [rgba[4 * i] - meanR, rgba[4 * i + 1] - meanG];
27
+ varR += r * r;
28
+ varG += g * g;
29
+ cov += r * g;
30
+ }
31
+ const sd = Math.sqrt(varR / n);
32
+ const corrRG = varR > 0 && varG > 0 ? cov / Math.sqrt(varR * varG) : 0;
33
+ const kind = sd <= FLAT_SD ? "flat" : Math.abs(corrRG) > NORMAL_COPY_CORR ? "normal-copy" : "height";
34
+ return { kind, mean: meanR, sd, min, max, corrRG };
35
+ }
36
+ /** The red channel of a square RGBA image as a height. */
37
+ export function redHeight(rgba, size) {
38
+ const values = new Float32Array(size * size);
39
+ for (let i = 0; i < values.length; i++)
40
+ values[i] = rgba[4 * i] / 255;
41
+ return { size, values };
42
+ }
43
+ /**
44
+ * A height recovered from a tangent-space normal map's slopes (X in alpha, Y in green, as SC2's
45
+ * DXT5 terrain normals keep them), integrated in the frequency domain (Frankot-Chellappa) with
46
+ * periodic edges, since the texture tiles. Levelled to 0..1. For a texture whose red channel holds
47
+ * no height. On ShakurasCity2, whose red channel is a real height, this agrees with it at 0.93,
48
+ * without flipping Y. The size must be a power of two.
49
+ */
50
+ export function integrateNormal(rgba, size) {
51
+ if (size < 2 || (size & (size - 1)) !== 0)
52
+ throw new Error(`integrating a normal map needs a power-of-two size, and this one is ${size}`);
53
+ const n = size * size;
54
+ const [pr, pi, qr, qi] = [new Float64Array(n), new Float64Array(n), new Float64Array(n), new Float64Array(n)];
55
+ for (let i = 0; i < n; i++) {
56
+ const nx = rgba[4 * i + 3] / 127.5 - 1;
57
+ const ny = rgba[4 * i + 1] / 127.5 - 1;
58
+ const nz = Math.sqrt(Math.max(0.05, 1 - nx * nx - ny * ny));
59
+ pr[i] = -nx / nz;
60
+ qr[i] = -ny / nz;
61
+ }
62
+ fft2(pr, pi, size, false);
63
+ fft2(qr, qi, size, false);
64
+ const [hr, hi] = [new Float64Array(n), new Float64Array(n)];
65
+ for (let v = 0; v < size; v++) {
66
+ for (let u = 0; u < size; u++) {
67
+ const i = v * size + u;
68
+ if (i === 0)
69
+ continue;
70
+ const wu = (2 * Math.PI * (u <= size / 2 ? u : u - size)) / size;
71
+ const wv = (2 * Math.PI * (v <= size / 2 ? v : v - size)) / size;
72
+ const d = wu * wu + wv * wv;
73
+ // H = -i (wu P + wv Q) / d
74
+ const sr = wu * pr[i] + wv * qr[i];
75
+ const si = wu * pi[i] + wv * qi[i];
76
+ hr[i] = si / d;
77
+ hi[i] = -sr / d;
78
+ }
79
+ }
80
+ fft2(hr, hi, size, true);
81
+ return levelled({ size, values: Float32Array.from(hr) });
82
+ }
83
+ /** In-place radix-2 FFT of a complex row (re, im). */
84
+ function fft(re, im, inverse) {
85
+ const n = re.length;
86
+ for (let i = 1, j = 0; i < n; i++) {
87
+ let bit = n >> 1;
88
+ for (; j & bit; bit >>= 1)
89
+ j ^= bit;
90
+ j ^= bit;
91
+ if (i < j) {
92
+ [re[i], re[j]] = [re[j], re[i]];
93
+ [im[i], im[j]] = [im[j], im[i]];
94
+ }
95
+ }
96
+ for (let len = 2; len <= n; len <<= 1) {
97
+ const angle = ((2 * Math.PI) / len) * (inverse ? 1 : -1);
98
+ const [wr, wi] = [Math.cos(angle), Math.sin(angle)];
99
+ for (let i = 0; i < n; i += len) {
100
+ let [cr, ci] = [1, 0];
101
+ for (let k = 0; k < len / 2; k++) {
102
+ const [a, b] = [i + k, i + k + len / 2];
103
+ const ar = re[b] * cr - im[b] * ci;
104
+ const ai = re[b] * ci + im[b] * cr;
105
+ re[b] = re[a] - ar;
106
+ im[b] = im[a] - ai;
107
+ re[a] = re[a] + ar;
108
+ im[a] = im[a] + ai;
109
+ [cr, ci] = [cr * wr - ci * wi, cr * wi + ci * wr];
110
+ }
111
+ }
112
+ }
113
+ if (inverse)
114
+ for (let i = 0; i < n; i++)
115
+ (re[i] = re[i] / n), (im[i] = im[i] / n);
116
+ }
117
+ function fft2(re, im, size, inverse) {
118
+ const [r, m] = [new Float64Array(size), new Float64Array(size)];
119
+ for (let y = 0; y < size; y++) {
120
+ for (let x = 0; x < size; x++)
121
+ (r[x] = re[y * size + x]), (m[x] = im[y * size + x]);
122
+ fft(r, m, inverse);
123
+ for (let x = 0; x < size; x++)
124
+ (re[y * size + x] = r[x]), (im[y * size + x] = m[x]);
125
+ }
126
+ for (let x = 0; x < size; x++) {
127
+ for (let y = 0; y < size; y++)
128
+ (r[y] = re[y * size + x]), (m[y] = im[y * size + x]);
129
+ fft(r, m, inverse);
130
+ for (let y = 0; y < size; y++)
131
+ (re[y * size + x] = r[y]), (im[y * size + x] = m[y]);
132
+ }
133
+ }
134
+ /** `height` stretched so its lowest value is 0 and its highest 1 (ImageMagick's -auto-level). */
135
+ export function levelled({ size, values }) {
136
+ let [low, high] = [Infinity, -Infinity];
137
+ for (const value of values)
138
+ (low = Math.min(low, value)), (high = Math.max(high, value));
139
+ const span = high - low;
140
+ return { size, values: values.map((value) => (span > 0 ? (value - low) / span : 0.5)) };
141
+ }
142
+ /**
143
+ * A Gaussian blur of `sigma` texels, wrapping round the edges: three box blurs each way, which
144
+ * approach a Gaussian closely enough for flattening broad bands.
145
+ */
146
+ export function wrapBlur({ size, values }, sigma) {
147
+ // Three boxes of width w have a variance of 3(w² - 1)/12.
148
+ const radius = Math.max(1, Math.round((Math.sqrt(4 * sigma * sigma + 1) - 1) / 2));
149
+ let current = Float32Array.from(values);
150
+ const next = new Float32Array(values.length);
151
+ const width = 2 * radius + 1;
152
+ for (let pass = 0; pass < 3; pass++) {
153
+ for (const across of [true, false]) {
154
+ for (let line = 0; line < size; line++) {
155
+ const at = (k) => {
156
+ const wrapped = ((k % size) + size) % size;
157
+ return across ? line * size + wrapped : wrapped * size + line;
158
+ };
159
+ let sum = 0;
160
+ for (let k = -radius; k <= radius; k++)
161
+ sum += current[at(k)];
162
+ for (let k = 0; k < size; k++) {
163
+ next[at(k)] = sum / width;
164
+ sum += current[at(k + radius + 1)] - current[at(k - radius)];
165
+ }
166
+ }
167
+ current.set(next);
168
+ }
169
+ }
170
+ return { size, values: current };
171
+ }
172
+ /** How wide the flattening blur is on a 1024-texel tile: the tile's broad bands are about 500 texels wide, its stones 40-160. */
173
+ export const BAND_SIGMA_AT_1024 = 120;
174
+ /**
175
+ * `height` with the tile's broad light and dark bands taken out and its stones kept: the height
176
+ * minus a wide wrapped blur of it, levelled to 0..1. On ShakurasCity2 this correlates 0.99 with
177
+ * the stock height.
178
+ */
179
+ export function flattenBands(height, sigma = (BAND_SIGMA_AT_1024 * height.size) / 1024) {
180
+ const blurred = wrapBlur(height, sigma);
181
+ return levelled({ size: height.size, values: height.values.map((value, i) => value - blurred.values[i] + 0.5) });
182
+ }
183
+ /**
184
+ * `height` crushed: everything at or below `black` goes to 0, the rest is stretched to 0..`top`,
185
+ * its highest texel at `top` (on a levelled height, ImageMagick's -level black,100% then × top).
186
+ * Under a texture painted over a base texture, the zeroed part is where the base shows through.
187
+ */
188
+ export function crush({ size, values }, black, top) {
189
+ let high = -Infinity;
190
+ for (const value of values)
191
+ high = Math.max(high, value);
192
+ const span = high - black;
193
+ return { size, values: values.map((value) => (value <= black || span <= 0 ? 0 : (top * (value - black)) / span)) };
194
+ }
195
+ /**
196
+ * The level below which `share` (0..1) of the height's texels lie: the black point that crushes
197
+ * that share of the tile to 0, whatever the height's spread.
198
+ */
199
+ export function levelAtShare({ values }, share) {
200
+ const sorted = Float32Array.from(values).sort();
201
+ return sorted[Math.min(sorted.length - 1, Math.max(0, Math.floor(share * sorted.length)))];
202
+ }
203
+ /** `height` with `share` of its texels (the lowest) crushed to 0, the rest stretched to 0..`top`. */
204
+ export const crushShare = (height, share, top) => crush(height, levelAtShare(height, share), top);
205
+ /** `height` upside down: its highs low and its lows high. */
206
+ export const inverted = ({ size, values }) => ({ size, values: values.map((value) => 1 - value) });
207
+ /** `height` scaled by `top`: its highest point at `top`. */
208
+ export const scaled = ({ size, values }, top) => ({ size, values: values.map((value) => value * top) });
209
+ /** The share of a height's texels at 0: how much of the tile the base texture can take. */
210
+ export function zeroShare({ values }) {
211
+ let zero = 0;
212
+ for (const value of values)
213
+ if (value <= 1 / 510)
214
+ zero++;
215
+ return zero / values.length;
216
+ }
217
+ export const meanOf = ({ values }) => values.reduce((sum, value) => sum + value, 0) / values.length;
218
+ /** Pearson's correlation of two heights of one size: how to check a derived height's sign against another source. */
219
+ export function correlation(a, b) {
220
+ const [ma, mb] = [meanOf(a), meanOf(b)];
221
+ let [va, vb, cov] = [0, 0, 0];
222
+ for (let i = 0; i < a.values.length; i++) {
223
+ const [x, y] = [a.values[i] - ma, b.values[i] - mb];
224
+ va += x * x;
225
+ vb += y * y;
226
+ cov += x * y;
227
+ }
228
+ return va > 0 && vb > 0 ? cov / Math.sqrt(va * vb) : 0;
229
+ }
230
+ /**
231
+ * `height` at a mip level's size: each texel the mean of the block of texels it covers, as a mip
232
+ * chain is built. The size must divide the height's.
233
+ */
234
+ export function downsampled(height, size) {
235
+ if (size === height.size)
236
+ return height;
237
+ const step = height.size / size;
238
+ if (!Number.isInteger(step))
239
+ throw new Error(`a ${height.size}-texel height can't be taken down to ${size} texels`);
240
+ const values = new Float32Array(size * size);
241
+ for (let y = 0; y < size; y++) {
242
+ for (let x = 0; x < size; x++) {
243
+ let sum = 0;
244
+ for (let dy = 0; dy < step; dy++)
245
+ for (let dx = 0; dx < step; dx++)
246
+ sum += height.values[(y * step + dy) * height.size + x * step + dx];
247
+ values[y * size + x] = sum / (step * step);
248
+ }
249
+ }
250
+ return { size, values };
251
+ }
package/dist/stock.js ADDED
@@ -0,0 +1,151 @@
1
+ // The game's own files the tuner reads, made on this machine from its install and never committed
2
+ // (ADR-0027): the stock terrain catalogs, for a texture's entry, and the texture's normal map. They
3
+ // come out of the install's CASC storage through the extractor SC2_CASC_TOOL names, called as
4
+ // stormex is (tools/README.md in the sc2-adjutant repo):
5
+ //
6
+ // $SC2_CASC_TOOL -S <install folder> -I <case-insensitive regex> -x -o <folder>
7
+ import { execFile } from "node:child_process";
8
+ import { existsSync } from "node:fs";
9
+ import { mkdir, readdir, readFile } from "node:fs/promises";
10
+ import path from "node:path";
11
+ import { promisify } from "node:util";
12
+ export const CASC_TOOL_VARIABLE = "SC2_CASC_TOOL";
13
+ /** Where installing an extractor is explained. */
14
+ const INSTALL_HELP = "https://github.com/TeamAntioch/sc2-adjutant/blob/main/tools/README.md#a-casc-extractor";
15
+ /** The mods whose GameData holds the stock terrain catalogs, in load order: a later one's fields win. */
16
+ export const STOCK_MODS = ["core", "liberty", "swarm", "void"];
17
+ /** The extractor SC2_CASC_TOOL names. Throws, saying how to install one, when it's unset or missing. */
18
+ export function cascTool(env = process.env) {
19
+ const tool = env[CASC_TOOL_VARIABLE];
20
+ if (!tool)
21
+ throw new Error(`${CASC_TOOL_VARIABLE} isn't set. The tuner reads the texture's normal map from your StarCraft II install with a CASC extractor: install stormex and set ${CASC_TOOL_VARIABLE} to it (${INSTALL_HELP})`);
22
+ if (!existsSync(tool))
23
+ throw new Error(`${CASC_TOOL_VARIABLE} is ${tool}, which doesn't exist (${INSTALL_HELP})`);
24
+ return tool;
25
+ }
26
+ /** A regex source matching a storage path ending in `parts`, any separator between them, any case. */
27
+ export const storagePattern = (...parts) => `(^|[\\\\/])${parts.map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("[\\\\/]")}$`;
28
+ /** Extracts every storage path matching one of `patterns` into `folder`. */
29
+ export async function extract(install, patterns, folder, tool = cascTool()) {
30
+ await mkdir(folder, { recursive: true });
31
+ const regex = patterns.length === 1 ? patterns[0] : `(?:${patterns.join("|")})`;
32
+ const args = ["-S", install, "-I", regex, "-x", "-o", folder];
33
+ try {
34
+ // A JavaScript tool runs through node: Windows starts only programs, never a script by its shebang.
35
+ if (/\.[cm]?js$/i.test(tool))
36
+ await promisify(execFile)(process.execPath, [tool, ...args], { maxBuffer: 64 * 1024 * 1024 });
37
+ else
38
+ await promisify(execFile)(tool, args, { maxBuffer: 64 * 1024 * 1024 });
39
+ }
40
+ catch (error) {
41
+ const reason = error.stderr || error.message;
42
+ throw new Error(`${CASC_TOOL_VARIABLE} (${tool}) couldn't extract ${regex} from ${install}: ${String(reason).trim()}`);
43
+ }
44
+ }
45
+ /** Every file under `folder`, by its path below it lower-cased with / separators: extractors write paths in any case. */
46
+ export async function filesByLowerPath(folder) {
47
+ const found = new Map();
48
+ if (!existsSync(folder))
49
+ return found;
50
+ for (const entry of await readdir(folder, { recursive: true, withFileTypes: true })) {
51
+ if (!entry.isFile())
52
+ continue;
53
+ const full = path.join(entry.parentPath, entry.name);
54
+ found.set(path.relative(folder, full).split(path.sep).join("/").toLowerCase(), full);
55
+ }
56
+ return found;
57
+ }
58
+ /** The storage path of a mod's terrain catalog, lower-cased. */
59
+ export const catalogPath = (mod, file) => `mods/${mod}.sc2mod/base.sc2data/gamedata/${file}`;
60
+ /** The patterns of the stock terrain catalogs. */
61
+ export const CATALOG_PATTERNS = STOCK_MODS.flatMap((mod) => ["terraintexdata.xml", "terraindata.xml"].map((file) => storagePattern("mods", `${mod}.sc2mod`, "base.sc2data", "gamedata", file)));
62
+ /** The entries of one catalog's `kind` (CTerrainTex, CTerrain), each with its `<Field value="…"/>` children. Fields with an index, and nested ones, are left out. */
63
+ export function catalogEntries(xml, kind) {
64
+ const entries = [];
65
+ const opening = new RegExp(`<${kind}\\b([^>]*?)(/?)>`, "g");
66
+ for (let match = opening.exec(xml); match; match = opening.exec(xml)) {
67
+ const attributes = match[1];
68
+ const id = /\bid="([^"]*)"/.exec(attributes)?.[1];
69
+ const parent = /\bparent="([^"]*)"/.exec(attributes)?.[1];
70
+ const isDefault = /\bdefault="1"/.test(attributes);
71
+ const fields = {};
72
+ if (match[2] !== "/") {
73
+ const end = xml.indexOf(`</${kind}>`, opening.lastIndex);
74
+ const body = xml.slice(opening.lastIndex, end < 0 ? xml.length : end);
75
+ // Only the entry's own top-level single fields: <Name value="…"/> with no index, not inside another element.
76
+ let depth = 0;
77
+ for (const tag of body.matchAll(/<(\/?)(\w+)([^>]*?)(\/?)>/g)) {
78
+ const [, closing, name, attributes, selfClosing] = tag;
79
+ if (closing)
80
+ depth--;
81
+ else if (!selfClosing)
82
+ depth++;
83
+ else if (depth === 0 && !/\bindex=/.test(attributes)) {
84
+ const value = /\bvalue="([^"]*)"/.exec(attributes)?.[1];
85
+ if (value !== undefined)
86
+ fields[name] = value;
87
+ }
88
+ }
89
+ opening.lastIndex = end < 0 ? xml.length : end;
90
+ }
91
+ if (id === undefined && !isDefault)
92
+ continue;
93
+ entries.push({ id: id ?? "", ...(parent !== undefined ? { parent } : {}), isDefault, fields });
94
+ }
95
+ return entries;
96
+ }
97
+ /**
98
+ * The CTerrainTex `id` as the stock catalogs give it: the kind's default entry, its parent's
99
+ * fields, then its own, each mod's over the one before. Undefined when no stock catalog has it.
100
+ */
101
+ export function stockTexture(catalogs, id) {
102
+ const all = catalogs.flatMap((xml) => catalogEntries(xml, "CTerrainTex"));
103
+ if (!all.some((entry) => entry.id === id && !entry.isDefault))
104
+ return undefined;
105
+ const resolve = (entryId, seen) => {
106
+ if (seen.has(entryId))
107
+ return {};
108
+ seen.add(entryId);
109
+ const own = all.filter((entry) => entry.id === entryId && !entry.isDefault);
110
+ const parent = own.findLast((entry) => entry.parent !== undefined)?.parent;
111
+ return Object.assign({}, parent !== undefined ? resolve(parent, seen) : {}, ...own.map((entry) => entry.fields));
112
+ };
113
+ const defaults = Object.assign({}, ...all.filter((entry) => entry.isDefault).map((entry) => entry.fields));
114
+ return { id, fields: { ...defaults, ...resolve(id, new Set()) } };
115
+ }
116
+ /** Whether the stock CTerrain `tileset` height-blends (HeightMapEnabled 1), the last catalog that sets it winning; undefined when none does. */
117
+ export function stockHeightMapEnabled(catalogs, tileset) {
118
+ let enabled;
119
+ for (const xml of catalogs)
120
+ for (const entry of catalogEntries(xml, "CTerrain"))
121
+ if (entry.id === tileset && entry.fields.HeightMapEnabled !== undefined)
122
+ enabled = entry.fields.HeightMapEnabled === "1";
123
+ return enabled;
124
+ }
125
+ /** A game path (`Assets\Textures\X.dds`) as a storage path pattern and as the lower-case tail an extracted file's path ends in. */
126
+ export function gameFile(gamePath) {
127
+ const parts = gamePath.split(/[\\/]+/).filter(Boolean);
128
+ return { pattern: storagePattern(...parts), tail: parts.join("/").toLowerCase() };
129
+ }
130
+ /** The extracted file whose lower-case path ends in `tail`, from the last mod that has it. */
131
+ export function findExtracted(files, tail) {
132
+ const matches = [...files.keys()].filter((key) => key === tail || key.endsWith(`/${tail}`));
133
+ const rank = (key) => STOCK_MODS.findIndex((mod) => key.includes(`mods/${mod}.sc2mod/`));
134
+ matches.sort((a, b) => rank(a) - rank(b));
135
+ const last = matches.at(-1);
136
+ return last === undefined ? undefined : files.get(last);
137
+ }
138
+ /** The stock terrain catalogs from an extraction folder, in load order (each mod's CTerrainTex file, then its CTerrain one). */
139
+ export async function readCatalogs(files) {
140
+ const read = async (key) => {
141
+ const file = files.get(key);
142
+ return file === undefined ? [] : [await readFile(file, "utf8")];
143
+ };
144
+ const textures = [];
145
+ const terrains = [];
146
+ for (const mod of STOCK_MODS) {
147
+ textures.push(...(await read(catalogPath(mod, "terraintexdata.xml"))));
148
+ terrains.push(...(await read(catalogPath(mod, "terraindata.xml"))));
149
+ }
150
+ return { textures, terrains };
151
+ }
package/dist/tune.js ADDED
@@ -0,0 +1,56 @@
1
+ // The tuner's command: one texture's height-map test map, its Shots and its report.
2
+ //
3
+ // node <plugin>/dist/tune.js <Mission blueprint.json> <texture> [--base <texture>] [--variants <list>] [--pitch <degrees>] [--install <StarCraft II folder>]
4
+ //
5
+ // It writes missions/<id>/output/height-tuner/<texture>/: HeightTune<texture>.SC2Map, shots.json
6
+ // (two Shots a strip, its low half then its high half, for capture_shots), tune.json (what each strip is) and blueprint.json (the
7
+ // generated Blueprint the map is compiled from). Stock files come from the install through the
8
+ // CASC extractor SC2_CASC_TOOL names; the install is the machine config's sc2Path unless --install.
9
+ import path from "node:path";
10
+ import { parseArgs } from "node:util";
11
+ import { hostContext, loadMachineConfig } from "@team-antioch/sc2-adjutant/plugin-sdk";
12
+ import { buildTestMap, DEFAULT_BASE, reviewSet } from "./build.js";
13
+ import { DEFAULT_VARIANTS, parseVariants } from "./variants.js";
14
+ const USAGE = `Usage: node dist/tune.js <Mission blueprint.json> <texture> [--base <texture>] [--variants <list>] [--pitch <degrees>] [--install <StarCraft II folder>]
15
+ --base the texture under the strips (default ${DEFAULT_BASE})
16
+ --variants comma-separated, each <kind>[:<% at 0>][*<scale>][+<offset>], kinds stock, crush, inverted-crush, flat, relevel
17
+ (default ${DEFAULT_VARIANTS}); stock is always the first strip, and a map holds 7`;
18
+ async function main() {
19
+ const { values, positionals } = parseArgs({
20
+ allowPositionals: true,
21
+ options: { base: { type: "string" }, variants: { type: "string" }, pitch: { type: "string" }, install: { type: "string" }, help: { type: "boolean", short: "h" } },
22
+ });
23
+ if (values.help || positionals.length !== 2) {
24
+ console.log(USAGE);
25
+ if (!values.help)
26
+ process.exitCode = 2;
27
+ return;
28
+ }
29
+ const cwd = process.env.INIT_CWD ?? process.cwd();
30
+ const [blueprint, texture] = positionals;
31
+ const variants = parseVariants(values.variants ?? DEFAULT_VARIANTS);
32
+ const install = values.install ? path.resolve(cwd, values.install) : hostContext(await loadMachineConfig()).requirePath("sc2Path");
33
+ const pitch = values.pitch !== undefined ? Number(values.pitch) : undefined;
34
+ if (pitch !== undefined && !(pitch > 0 && pitch <= 90))
35
+ throw new Error(`--pitch is degrees down from level, up to 90, not ${values.pitch}`);
36
+ const report = await buildTestMap({
37
+ blueprintPath: path.resolve(cwd, blueprint),
38
+ texture,
39
+ ...(values.base ? { base: values.base } : {}),
40
+ variants,
41
+ install,
42
+ ...(pitch !== undefined ? { pitch } : {}),
43
+ log: (line) => console.log(line),
44
+ });
45
+ console.log(`\n${report.texture} over ${report.base}, on ${report.tileset}. Its red channel: ${report.red.kind} (mean ${Math.round(report.red.mean)}, sd ${Math.round(report.red.sd)}); heights from its ${report.heightSource}${report.integratedAgreement !== undefined ? ` (the integrated height agrees at ${report.integratedAgreement})` : ""}.`);
46
+ for (const [index, strip] of report.strips.entries()) {
47
+ console.log(` ${index + 1}. ${strip.label}: ${strip.textureId}, mean height ${strip.heightMean}, ${Math.round(strip.zeroShare * 100)}% at 0${strip.heightMapScale ? `, scale ${strip.heightMapScale}` : ""}`);
48
+ }
49
+ console.log(`\nMap: ${report.mapPath}\nShots: ${report.shotsPath} (Still Review set ${reviewSet(report.texture)})`);
50
+ for (const warning of report.warnings)
51
+ console.warn(`Warning: ${warning}`);
52
+ }
53
+ main().catch((error) => {
54
+ console.error(error instanceof Error ? error.message : error);
55
+ process.exit(1);
56
+ });
@@ -0,0 +1,126 @@
1
+ // The candidate heights a test map compares, one strip each. A variant is written as a word:
2
+ //
3
+ // <kind>[:<% at 0>][*<HeightMapScale>][+<HeightMapOffset>]
4
+ //
5
+ // stock the texture as the game has it (always the first strip)
6
+ // stock*2 its own height at HeightMapScale 2
7
+ // crush:25 the stones kept, the lowest 25% of the tile at 0: the base texture grows in the gaps
8
+ // inverted-crush:25 the same upside down: the highest 25% (the stone tops) at 0, so the base texture sits on
9
+ // them and the stone reads as sunken
10
+ //
11
+ // A crush's number is the share of the tile that goes to 0, where the base shows through, found
12
+ // for each texture from its own height (a quantile), so it means the same on any texture. On
13
+ // ShakurasCity2, crush:25 is the research's level 28% (scrush, the author's pick) and crush:43 its
14
+ // level 34% (scrush2).
15
+ // flat only the tile's broad bands taken out
16
+ // relevel the stock height stretched to 0..1
17
+ //
18
+ // Each variant but a stock one with no scale or offset is a CTerrainTex copy of its own.
19
+ import { crushShare, inverted, levelled, scaled } from "./heights.js";
20
+ export const VARIANT_KINDS = ["stock", "crush", "inverted-crush", "flat", "relevel"];
21
+ /** The variants a test map shows unless told otherwise: the author's pick for ShakurasCity2 (a quarter of the tile crushed) between a lighter and a heavier one, and the inverted crush at the same three. */
22
+ export const DEFAULT_VARIANTS = "stock,crush:15,crush:25,crush:40,inverted-crush:15,inverted-crush:25,inverted-crush:40";
23
+ /** A test map's set holds 8 textures: the base, then a strip each. */
24
+ export const MAX_VARIANTS = 7;
25
+ const WORD = /^(stock|crush|inverted-crush|flat|relevel)(?::(\d+(?:\.\d+)?))?(?:\*(\d+(?:\.\d+)?))?(?:\+(-?\d+(?:\.\d+)?))?$/;
26
+ /** The variants of a comma-separated list, stock first whether it's named or not. Throws on a word it can't read. */
27
+ export function parseVariants(list) {
28
+ const variants = list
29
+ .split(",")
30
+ .map((word) => word.trim())
31
+ .filter(Boolean)
32
+ .map(parseVariant);
33
+ if (!variants.some((variant) => variant.kind === "stock" && variant.scale === undefined && variant.offset === undefined))
34
+ variants.unshift({ kind: "stock" });
35
+ else
36
+ variants.sort((a, b) => Number(isPlainStock(b)) - Number(isPlainStock(a)));
37
+ const names = variants.map(variantName);
38
+ const twice = names.find((name, i) => names.indexOf(name) !== i);
39
+ if (twice)
40
+ throw new Error(`The variant ${twice} is listed twice`);
41
+ if (variants.length > MAX_VARIANTS)
42
+ throw new Error(`A test map holds ${MAX_VARIANTS} strips (its texture set's 8 textures, less the base), and this list makes ${variants.length}, stock included: split it over two runs`);
43
+ return variants;
44
+ }
45
+ function parseVariant(word) {
46
+ const match = WORD.exec(word);
47
+ if (!match)
48
+ throw new Error(`${JSON.stringify(word)} isn't a variant: write <kind>[:<% at 0>][*<scale>][+<offset>], with a kind of ${VARIANT_KINDS.join(", ")}`);
49
+ const [, kind, share, scale, offset] = match;
50
+ const crushing = kind === "crush" || kind === "inverted-crush";
51
+ if (crushing && share === undefined)
52
+ throw new Error(`${word}: a ${kind} needs the % of the tile that goes to 0 (as crush:25)`);
53
+ if (!crushing && share !== undefined)
54
+ throw new Error(`${word}: only crush and inverted-crush take a %`);
55
+ if (share !== undefined && !(Number(share) > 0 && Number(share) < 100))
56
+ throw new Error(`${word}: the share at 0 is a % between 0 and 100`);
57
+ return {
58
+ kind,
59
+ ...(share !== undefined ? { share: Number(share) / 100 } : {}),
60
+ ...(scale !== undefined ? { scale: Number(scale) } : {}),
61
+ ...(offset !== undefined ? { offset: Number(offset) } : {}),
62
+ };
63
+ }
64
+ const isPlainStock = (variant) => variant.kind === "stock" && variant.scale === undefined && variant.offset === undefined;
65
+ /** Whether a variant needs a normal map of its own: every kind but stock. */
66
+ export const needsNormalMap = (variant) => variant.kind !== "stock";
67
+ /** The variant as its word: `crush:28*2`. */
68
+ export function variantName(variant) {
69
+ const share = variant.share !== undefined ? `:${round(variant.share * 100)}` : "";
70
+ const scale = variant.scale !== undefined ? `*${variant.scale}` : "";
71
+ const offset = variant.offset !== undefined ? `+${variant.offset}` : "";
72
+ return `${variant.kind}${share}${scale}${offset}`;
73
+ }
74
+ /** The variant for a person: `crush 28%, scale 2`. */
75
+ export function variantLabel(variant) {
76
+ const parts = [`${variant.kind.replace("-", " ")}${variant.share !== undefined ? ` ${round(variant.share * 100)}%` : ""}`];
77
+ if (variant.scale !== undefined)
78
+ parts.push(`scale ${variant.scale}`);
79
+ if (variant.offset !== undefined)
80
+ parts.push(`offset ${variant.offset}`);
81
+ return parts.join(", ");
82
+ }
83
+ /** The variant in a CTerrainTex id or file name: `Crush28S2`. */
84
+ export function variantSuffix(variant) {
85
+ const kind = variant.kind.split("-").map((part) => part[0].toUpperCase() + part.slice(1)).join("");
86
+ const share = variant.share !== undefined ? String(round(variant.share * 100)).replace(".", "p") : "";
87
+ const scale = variant.scale !== undefined ? `S${String(variant.scale).replace(".", "p")}` : "";
88
+ const offset = variant.offset !== undefined ? `O${String(variant.offset).replace(".", "p").replace("-", "m")}` : "";
89
+ return `${kind}${share}${scale}${offset}`;
90
+ }
91
+ /** What a variant does, in a line, for the report and the Shot's label. */
92
+ export function variantRecipe(variant) {
93
+ switch (variant.kind) {
94
+ case "stock":
95
+ return "the texture's own height";
96
+ case "crush":
97
+ return `the stones kept; the lowest ${round(variant.share * 100)}% of the tile at 0, where the base texture grows in the gaps`;
98
+ case "inverted-crush":
99
+ return `the height upside down; the highest ${round(variant.share * 100)}% of the tile (the stone tops) at 0, so the base sits on them and the stone reads as sunken`;
100
+ case "flat":
101
+ return "the tile's broad light and dark bands taken out, the stones kept";
102
+ case "relevel":
103
+ return "the height stretched to the full 0..1";
104
+ }
105
+ }
106
+ /**
107
+ * The red channel a variant gives the texture, from its source height (0..1: the stock red
108
+ * channel, or a height integrated from the normal), that height with its broad bands flattened
109
+ * (flattenBands, made once for every variant), and `top`, the level the highest stones keep.
110
+ * Undefined for stock, which keeps the texture's own normal map.
111
+ */
112
+ export function variantHeight(variant, source, flattened, top) {
113
+ switch (variant.kind) {
114
+ case "stock":
115
+ return undefined;
116
+ case "relevel":
117
+ return levelled(source);
118
+ case "flat":
119
+ return scaled(flattened, top);
120
+ case "crush":
121
+ return crushShare(flattened, variant.share, top);
122
+ case "inverted-crush":
123
+ return crushShare(inverted(flattened), variant.share, top);
124
+ }
125
+ }
126
+ const round = (value) => Math.round(value * 100) / 100;
package/package.json CHANGED
@@ -1,6 +1,34 @@
1
1
  {
2
2
  "name": "@team-antioch/sc2-adjutant-height-tuner",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "An sc2-adjutant Utility that builds a terrain texture height-map test map: strips of candidate normal maps, each painted from 0 to 100% over a base texture, for judging in game.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/TeamAntioch/sc2-adjutant.git",
9
+ "directory": "packages/plugin-height-tuner"
10
+ },
11
+ "type": "module",
12
+ "exports": {
13
+ "./sc2-adjutant-plugin.json": "./sc2-adjutant-plugin.json",
14
+ "./package.json": "./package.json"
15
+ },
16
+ "files": [
17
+ "dist",
18
+ "!dist/.tsbuildinfo",
19
+ "sc2-adjutant-plugin.json",
20
+ "skills"
21
+ ],
22
+ "scripts": {
23
+ "build": "tsc -p tsconfig.json && node ../core/scripts/write-built-stamp.mjs",
24
+ "prepack": "pnpm run build",
25
+ "lint": "tsc -p tsconfig.json --noEmit",
26
+ "test": "vitest run"
27
+ },
28
+ "engines": {
29
+ "node": ">=22.18"
30
+ },
31
+ "peerDependencies": {
32
+ "@team-antioch/sc2-adjutant": "^0.2.0"
33
+ }
34
+ }
@@ -0,0 +1,7 @@
1
+ {
2
+ "name": "height-tuner",
3
+ "version": "0.1.0",
4
+ "pluginApi": 2,
5
+ "roles": ["utility"],
6
+ "contributions": { "skills": ["skills/height-tuner"] }
7
+ }
@@ -0,0 +1,41 @@
1
+ ---
2
+ name: height-tuner
3
+ description: Tunes a terrain texture's height map in game. Builds a small test map per texture with a strip per candidate normal map, each painted 0 to 100% over a base texture, captures the strips and publishes them as a Still Review. Use when a height-blended texture covers too much or too little, shows as solid clumps, or should let the ground under it grow through its gaps; when the author asks to tune, crush or invert a texture's height; or to compare normal-map variants of one or more textures.
4
+ ---
5
+
6
+ A layer's height is the **red channel of its CTerrainTex Normalmap**. The `Heightmap` field does nothing on this build, and `HeightMapScale`/`HeightMapOffset` scale it. Only layers painted at a texel compete there. So a texture's look over another depends on its normal map's red channel. The command and its files: [README.md]({{PLUGIN_FOLDER}}/README.md). The engine facts and how each variant is made: [terrain-height-maps.md](https://github.com/TeamAntioch/sc2-adjutant/blob/main/docs/reference/terrain-height-maps.md).
7
+
8
+ The Utility's command builds one texture's **test map**:
9
+
10
+ ```sh
11
+ node {{PLUGIN_FOLDER}}/dist/tune.js <Mission blueprint.json> <texture> [--base <texture>] [--variants <list>]
12
+ ```
13
+
14
+ It writes `missions/<id>/output/height-tuner/<texture>/`: the map, `shots.json` (two Shots a strip) and `tune.json` (what each strip is). The map uses the Mission's tileset and lighting. The base texture is held at 15/15 everywhere, and each strip raises the test texture from 0 at its left to 15/15 at its right.
15
+
16
+ ## Leading words
17
+
18
+ - **Variant**: one candidate height, written `<kind>[:<% at 0>][*<HeightMapScale>][+<HeightMapOffset>]`. Each is a map-local CTerrainTex copy with its own normal map, made on this machine from the install and never committed.
19
+ - `stock`: the texture as the game has it. It is always strip 1, the reference.
20
+ - `crush:25`: the stones kept, with the lowest 25% of the tile at 0, so the base texture grows in the gaps. The author's pick for ShakurasCity2 over this grass was crush:25: "exactly what I'm looking for".
21
+ - `inverted-crush:25`: the highest 25% (the stone tops) at 0, so the base sits on the tops and the stone reads as sunken, with deep crevices. The author: "a ton of depth to a texture". It is a look of its own, not a fix.
22
+ - `flat` takes out the tile's broad bands only, `relevel` stretches the height to 0..1, and `*2` sets HeightMapScale 2.
23
+ - The default list is `stock,crush:15,crush:25,crush:40,inverted-crush:15,inverted-crush:25,inverted-crush:40`. A map holds 7 strips.
24
+ - **Strip**: one variant on the test map. It is 64 cells long and 16 wide, framed in two passes at about the player's camera distance: every strip's low half (`<n>. <variant>, 0-50%`), then every strip's high half (`, 50-100%`). The page then shows the variants side by side at the same weights. At 0-50% the strip's first steps show almost nothing: weights 0 and 1 of 15.
25
+
26
+ ## Steps
27
+
28
+ 1. **Settle the run.** You need the textures to tune (CTerrainTex ids), the base (default `BelShirGrassLightEx2`, the Bel'Shir grass), the Mission whose output and lighting the maps use, and the variants. Use the default list unless the author names a look: gaps of base → crush, depth → inverted crush. Done when each texture has its base and its variant list.
29
+ 2. **Check the extractor.** The command reads the stock catalogs and the normal map from the install through the CASC extractor named in `SC2_CASC_TOOL`. When it stops on that, give the author the install steps in [tools/README.md, "A CASC extractor"](https://github.com/TeamAntioch/sc2-adjutant/blob/main/tools/README.md#a-casc-extractor) and wait. Done when `echo $SC2_CASC_TOOL` names a file that exists.
30
+ 3. **Get the go-ahead to capture.** Each texture's capture takes about 3 minutes, and the Editor comes to the front and runs the map. The screen must be left alone until every capture is done, since a click or a key press lands in the game. Done when the author has said go.
31
+ 4. **Build and capture each texture.** With one texture, do it here. With several, start one subagent per texture, all in one message, each with its texture, base, Mission, variants and this step's brief. Each one:
32
+ 1. runs the command, and reads its report and warnings;
33
+ 2. calls `capture_shots` with `mapPath` the map, `shots` from its `shots.json`, `name` `<set>-r1` (the set is `height-<texture in lower case>`, which the command prints), and `lighting` the Mission's Light if its Blueprint sets one;
34
+ 3. opens every frame: the stock strip's right end shows the test texture solid, and the variants differ from it and from each other;
35
+ 4. calls `build_still_review` with `mission`, `set`, `round` `r1` and one version, `{ label: "strips", note: "<texture> over <base>, one strip per variant", captures: [<the capture folder>] }`;
36
+ 5. returns the round's folder, its problems, and one line per strip: its variant, its share at 0, and what the frame shows.
37
+ The captures queue one at a time through the Editor Broker, so subagents running side by side wait their turn. Done when every texture has a round folder with every frame on its page, or its problems are reported.
38
+ 5. **Publish and read back.** Follow the still-review skill's steps 5 and 6 for each round. Tell the author the page's "best version" pick has one version here, so the pick goes in each strip's tags and note and in the overall note. Done when the feedback is recorded and the author has confirmed your summary of it.
39
+ 6. **Refine or settle.** A next round narrows around the pick: shares either side of it (`crush:20,crush:25,crush:30`), or the pick at another scale (`crush:25*0.5`, `crush:25*2`). Run it as a new set, `height-<texture>-2`, since its strips are new variants at the old strips' places. Once the author settles on a variant, tell them its word, its CTerrainTex entry and its normal map (both in `tune.json`). Done when the author has a pick for each texture, or has stopped.
40
+
41
+ A Mission Blueprint can't declare a texture's tuned height yet. Carrying a pick into a Mission means a hand-made map-local entry. When the author does that, offer the report-missing-feature skill once.