@scm-js/core 0.9.1 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -5552,6 +5552,115 @@ function updateUnits(scn, indices, patch) {
5552
5552
  function moveUnits(scn, units, indices, dx, dy, snap = true) {
5553
5553
  return updateUnits(scn, indices, (u) => snapPlacement(unitGeometry(units, u.unitId), u.x + dx, u.y + dy, scn.width, scn.height, snap));
5554
5554
  }
5555
+ /** The images of `mode` other than the identity; modes that turn the plane need it square and answer nothing otherwise. */
5556
+ function symmetryImages(mode, w, h) {
5557
+ const flipX = (element) => ({
5558
+ element,
5559
+ map: (x, y) => ({
5560
+ x: w - x,
5561
+ y
5562
+ }),
5563
+ linear: (dx, dy) => ({
5564
+ x: -dx,
5565
+ y: dy
5566
+ })
5567
+ });
5568
+ const flipY = (element) => ({
5569
+ element,
5570
+ map: (x, y) => ({
5571
+ x,
5572
+ y: h - y
5573
+ }),
5574
+ linear: (dx, dy) => ({
5575
+ x: dx,
5576
+ y: -dy
5577
+ })
5578
+ });
5579
+ const turn = (element) => ({
5580
+ element,
5581
+ map: (x, y) => ({
5582
+ x: w - x,
5583
+ y: h - y
5584
+ }),
5585
+ linear: (dx, dy) => ({
5586
+ x: -dx,
5587
+ y: -dy
5588
+ })
5589
+ });
5590
+ switch (mode) {
5591
+ case "h": return [flipX(1)];
5592
+ case "v": return [flipY(1)];
5593
+ case "hv": return [
5594
+ flipX(1),
5595
+ flipY(2),
5596
+ turn(3)
5597
+ ];
5598
+ case "rot180": return [turn(1)];
5599
+ case "rot90": return w === h ? [
5600
+ {
5601
+ element: 1,
5602
+ map: (x, y) => ({
5603
+ x: w - y,
5604
+ y: x
5605
+ }),
5606
+ linear: (dx, dy) => ({
5607
+ x: -dy,
5608
+ y: dx
5609
+ })
5610
+ },
5611
+ turn(2),
5612
+ {
5613
+ element: 3,
5614
+ map: (x, y) => ({
5615
+ x: y,
5616
+ y: h - x
5617
+ }),
5618
+ linear: (dx, dy) => ({
5619
+ x: dy,
5620
+ y: -dx
5621
+ })
5622
+ }
5623
+ ] : [];
5624
+ case "diag": return w === h ? [{
5625
+ element: 1,
5626
+ map: (x, y) => ({
5627
+ x: y,
5628
+ y: x
5629
+ }),
5630
+ linear: (dx, dy) => ({
5631
+ x: dy,
5632
+ y: dx
5633
+ })
5634
+ }] : [];
5635
+ case "adiag": return w === h ? [{
5636
+ element: 1,
5637
+ map: (x, y) => ({
5638
+ x: h - y,
5639
+ y: w - x
5640
+ }),
5641
+ linear: (dx, dy) => ({
5642
+ x: -dy,
5643
+ y: -dx
5644
+ })
5645
+ }] : [];
5646
+ default: return [];
5647
+ }
5648
+ }
5649
+ /**
5650
+ * The player an image of something `owner` placed belongs to, when Symmetry hands each
5651
+ * copy its own player. The eight players go in groups of as many as the mode has images —
5652
+ * P1–P2, P3–P4, … for the two-way modes, P1–P4 and P5–P8 for the four-way ones — and the
5653
+ * copy takes the player in the same group the image's element leads to, so whichever
5654
+ * player you place for, each corner keeps its own: under "hv" P1 top-left gives P2
5655
+ * top-right, P3 bottom-left and P4 bottom-right, and placing for P3 bottom-left gives the
5656
+ * same four. Neutral and the rescuable players (9–12) are left alone.
5657
+ */
5658
+ function mirroredOwner(mode, owner, element) {
5659
+ if (element === 0 || owner < 0 || owner > 7) return owner;
5660
+ const size = mode === "hv" || mode === "rot90" ? 4 : 2;
5661
+ const slot = owner % size;
5662
+ return owner - slot + (mode === "rot90" ? (slot + element) % size : slot ^ element);
5663
+ }
5555
5664
  //#endregion
5556
5665
  //#region src/editor/locations.ts
5557
5666
  /**
@@ -7343,6 +7452,21 @@ var TileFlag = {
7343
7452
  BlocksView: 8,
7344
7453
  Ramp: 16
7345
7454
  };
7455
+ /**
7456
+ * A megatile's ground height as the game takes it, from its 16 minitiles (the CV5 height
7457
+ * bits are not read): high when at least 12 are high, else mid when high and mid together
7458
+ * are at least 12, else low.
7459
+ */
7460
+ function megatileHeight(tileset, megatile) {
7461
+ let high = 0, mid = 0;
7462
+ for (let m = 0; m < 16; m++) {
7463
+ const flags = tileset.megatileFlags[megatile * 16 + m] ?? 0;
7464
+ if (flags & TileFlag.HighGround) high++;
7465
+ else if (flags & TileFlag.MidGround) mid++;
7466
+ }
7467
+ if (high >= 12) return 2;
7468
+ return high + mid >= 12 ? 1 : 0;
7469
+ }
7346
7470
  //#endregion
7347
7471
  //#region src/formats/tileset/palette.ts
7348
7472
  /** A flat ground pair: two consecutive groups sharing an index, each with all four edges equal. */
@@ -7784,6 +7908,17 @@ var MAP_SIZES = [
7784
7908
  ];
7785
7909
  //#endregion
7786
7910
  //#region src/editor/sprites.ts
7911
+ /** Insert / remove / replace on an in-place list; removals are listed highest index first. */
7912
+ function applyList(list, changes, direction) {
7913
+ const ordered = direction === "do" ? changes : [...changes].reverse();
7914
+ for (const c of ordered) {
7915
+ const before = direction === "do" ? c.before : c.after;
7916
+ const after = direction === "do" ? c.after : c.before;
7917
+ if (before && after) list[c.index] = after;
7918
+ else if (after) list.splice(c.index, 0, after);
7919
+ else if (before) list.splice(c.index, 1);
7920
+ }
7921
+ }
7787
7922
  function spriteKind(r) {
7788
7923
  return r.flags & SpriteFlag.PureSprite ? "pure" : "unit";
7789
7924
  }
@@ -9650,6 +9785,11 @@ function summarizeTrigger(t, names, briefing = false) {
9650
9785
  actions: t.actions.map((a) => formatAction(a, names, briefing).replace(/;$/, "")).join("; ")
9651
9786
  };
9652
9787
  }
9788
+ /** Text of the trigger's Comment action, if it has one. */
9789
+ function triggerComment(t, names) {
9790
+ const c = t.actions.find((a) => a.type === 47);
9791
+ return c ? names.string(c.text) : null;
9792
+ }
9653
9793
  //#endregion
9654
9794
  //#region src/editor/exchange.ts
9655
9795
  /**
@@ -9910,6 +10050,121 @@ function readSwitchNames(scn) {
9910
10050
  return Array.from({ length: 256 }, (_, i) => (scn.switchNames ? getString(scn.strings, scn.switchNames[i] ?? 0) : null) ?? "");
9911
10051
  }
9912
10052
  //#endregion
10053
+ //#region src/formats/wav.ts
10054
+ /**
10055
+ * RIFF/WAVE, the one sound format every StarCraft build plays. `parseWavHeader` reads the
10056
+ * `fmt ` and `data` chunks so the Sound Editor can say what a file is (and whether the game
10057
+ * or Web Audio will take it); `encodeWav` writes the plain PCM the import conversion
10058
+ * produces, and `decodeWav` reads every WAV encoding the game's own sounds and the usual
10059
+ * tools come in — 8/16/24/32-bit PCM, 32/64-bit float, A-law, µ-law, IMA ADPCM and
10060
+ * Microsoft ADPCM — so a sound lifted out of the game's archives plays and converts here
10061
+ * without the browser's help. Pure, so the round trips are tested under Node; the decoding
10062
+ * of MP3 / Ogg / FLAC and the resampling are the browser's (`services/audioConvert.ts`).
10063
+ */
10064
+ /** `fmt ` format tags this module knows by name. */
10065
+ var WAV_FORMAT = {
10066
+ pcm: 1,
10067
+ msAdpcm: 2,
10068
+ float: 3,
10069
+ alaw: 6,
10070
+ mulaw: 7,
10071
+ imaAdpcm: 17,
10072
+ extensible: 65534
10073
+ };
10074
+ /** Frames in the data chunk, for any encoding this module knows. */
10075
+ function wavFrames(info) {
10076
+ if (info.format === WAV_FORMAT.imaAdpcm || info.format === WAV_FORMAT.msAdpcm) {
10077
+ if (info.blockAlign <= 0) return 0;
10078
+ const blocks = Math.floor(info.dataLength / info.blockAlign);
10079
+ const tail = info.dataLength - blocks * info.blockAlign;
10080
+ const perBlock = adpcmSamplesPerBlock(info);
10081
+ const tailSamples = tail > 0 ? Math.max(0, adpcmSamplesPerBlock({
10082
+ ...info,
10083
+ blockAlign: tail
10084
+ })) : 0;
10085
+ return blocks * perBlock + tailSamples;
10086
+ }
10087
+ const frame = info.channels * Math.ceil(info.bitsPerSample / 8);
10088
+ return frame > 0 ? Math.floor(info.dataLength / frame) : 0;
10089
+ }
10090
+ /** Duration in seconds, from the header — no decoding needed. */
10091
+ function wavDuration(info) {
10092
+ return info.sampleRate > 0 ? wavFrames(info) / info.sampleRate : 0;
10093
+ }
10094
+ /** Samples per block for the two ADPCM layouts: the header's own count when it carries one, else what the block size implies. */
10095
+ function adpcmSamplesPerBlock(info) {
10096
+ const declared = info.extra.length >= 4 ? info.extra[2] | info.extra[3] << 8 : 0;
10097
+ if (info.format === WAV_FORMAT.imaAdpcm) {
10098
+ const implied = Math.floor((info.blockAlign - 4 * info.channels) * 8 / (4 * info.channels)) + 1;
10099
+ return declared > 0 ? Math.min(declared, implied) : implied;
10100
+ }
10101
+ const implied = Math.floor((info.blockAlign - 7 * info.channels) * 2 / info.channels) + 2;
10102
+ return declared > 0 ? Math.min(declared, implied) : implied;
10103
+ }
10104
+ /** A short label: `22050 Hz · 16-bit · mono`, with the codec named when it is not plain PCM. */
10105
+ function wavFormatLabel(info) {
10106
+ const ch = info.channels === 1 ? t("mono") : info.channels === 2 ? t("stereo") : t("{n} ch", { n: info.channels });
10107
+ const codec = wavCodecName(info.format);
10108
+ return `${info.sampleRate} Hz · ${info.bitsPerSample}-bit · ${ch}${codec ? ` · ${codec}` : ""}`;
10109
+ }
10110
+ function wavCodecName(format) {
10111
+ switch (format) {
10112
+ case WAV_FORMAT.pcm: return null;
10113
+ case WAV_FORMAT.msAdpcm: return "MS ADPCM";
10114
+ case WAV_FORMAT.imaAdpcm: return "IMA ADPCM";
10115
+ case WAV_FORMAT.float: return "float";
10116
+ case WAV_FORMAT.alaw: return "A-law";
10117
+ case WAV_FORMAT.mulaw: return "µ-law";
10118
+ default: return `format 0x${format.toString(16)}`;
10119
+ }
10120
+ }
10121
+ /** Reads the header of a RIFF/WAVE file; null when the bytes are not one. */
10122
+ function parseWavHeader(bytes) {
10123
+ if (bytes.length < 12 || tag(bytes, 0) !== "RIFF" || tag(bytes, 8) !== "WAVE") return null;
10124
+ const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
10125
+ let fmt = null;
10126
+ let data = null;
10127
+ let at = 12;
10128
+ while (at + 8 <= bytes.length) {
10129
+ const id = tag(bytes, at);
10130
+ const size = dv.getUint32(at + 4, true);
10131
+ const body = at + 8;
10132
+ if (id === "fmt " && size >= 16 && body + 16 <= bytes.length) {
10133
+ let format = dv.getUint16(body, true);
10134
+ const channels = dv.getUint16(body + 2, true);
10135
+ const sampleRate = dv.getUint32(body + 4, true);
10136
+ const blockAlign = dv.getUint16(body + 12, true);
10137
+ const bitsPerSample = dv.getUint16(body + 14, true);
10138
+ if (format === WAV_FORMAT.extensible && size >= 40 && body + 26 <= bytes.length) format = dv.getUint16(body + 24, true);
10139
+ const extra = bytes.subarray(body + 16, Math.min(body + size, bytes.length));
10140
+ fmt = {
10141
+ format,
10142
+ channels,
10143
+ sampleRate,
10144
+ bitsPerSample,
10145
+ blockAlign,
10146
+ extra
10147
+ };
10148
+ } else if (id === "data") {
10149
+ data = {
10150
+ offset: body,
10151
+ length: Math.min(size, bytes.length - body)
10152
+ };
10153
+ if (fmt) break;
10154
+ }
10155
+ at = body + size + (size & 1);
10156
+ }
10157
+ if (!fmt) return null;
10158
+ return {
10159
+ ...fmt,
10160
+ dataLength: data?.length ?? 0,
10161
+ dataOffset: data?.offset ?? bytes.length
10162
+ };
10163
+ }
10164
+ function tag(bytes, at) {
10165
+ return String.fromCharCode(bytes[at], bytes[at + 1], bytes[at + 2], bytes[at + 3]);
10166
+ }
10167
+ //#endregion
9913
10168
  //#region src/data/isomTables.ts
9914
10169
  function rows(list) {
9915
10170
  return list.map(([index, isomValue = 0, brush = -1, linkId = 0]) => ({
@@ -10970,6 +11225,48 @@ function flatTerrain(width, height, terrain, tileset, random = Math.random, era
10970
11225
  };
10971
11226
  }
10972
11227
  //#endregion
11228
+ //#region src/editor/terrain.ts
11229
+ /**
11230
+ * Terrain edits as invertible change lists.
11231
+ *
11232
+ * Every brush computes the tiles it would change without touching the scenario, the
11233
+ * caller applies them, and the same list undoes the stroke. MTXM and TILE are kept in
11234
+ * step because the game reads one and StarEdit the other (TILE being the ground without
11235
+ * doodads, a change records what TILE held separately — see `TileChange.under`); ISOM
11236
+ * is deliberately left alone — these brushes place tiles the ISOM model has no
11237
+ * vocabulary for, which is exactly what SCMDraft does in its Rectangular/Subtile modes.
11238
+ */
11239
+ /**
11240
+ * Apply a change list, or take it back. Terrain edits (`layer` "terrain") write MTXM and
11241
+ * TILE alike, remembering what TILE held in `under` on first application; doodad edits
11242
+ * ("mtxm") touch only MTXM's contents, leaving TILE as the ground beneath.
11243
+ */
11244
+ function applyChanges(scn, changes, direction = "do", layer = "terrain") {
11245
+ if (changes.length === 0) return;
11246
+ for (const c of changes) if (direction === "do") {
11247
+ if (layer === "terrain") {
11248
+ c.under ??= scn.editorTiles[c.at];
11249
+ scn.editorTiles[c.at] = c.after;
11250
+ }
11251
+ scn.tiles[c.at] = c.after;
11252
+ } else {
11253
+ if (layer === "terrain") scn.editorTiles[c.at] = c.under ?? c.before;
11254
+ scn.tiles[c.at] = c.before;
11255
+ }
11256
+ markDirty(scn, "MTXM", "TILE");
11257
+ }
11258
+ /**
11259
+ * For code that has already written `scn.tiles` itself (the isometric brush): bring
11260
+ * TILE along and record what it held, exactly as `applyChanges` would have.
11261
+ */
11262
+ function mirrorEditorTiles(scn, changes) {
11263
+ for (const c of changes) {
11264
+ c.under ??= scn.editorTiles[c.at];
11265
+ scn.editorTiles[c.at] = c.after;
11266
+ }
11267
+ if (changes.length > 0) markDirty(scn, "TILE");
11268
+ }
11269
+ //#endregion
10973
11270
  //#region src/editor/isom.ts
10974
11271
  /**
10975
11272
  * The isometric terrain brush — StarEdit's, as reverse-engineered for Chkdraft
@@ -11029,6 +11326,7 @@ var QUADRANTS = [
11029
11326
  2,
11030
11327
  3
11031
11328
  ];
11329
+ var opposite = (q) => q + 2 & 3;
11032
11330
  var S_LEFT = 0;
11033
11331
  var S_TOP = 1;
11034
11332
  var S_RIGHT = 2;
@@ -11062,6 +11360,10 @@ var PROJECTED = {
11062
11360
  }
11063
11361
  };
11064
11362
  var FLAG_MASK = 14;
11363
+ /** Editor scratch bits inside an ISOM u16; never written to disk. */
11364
+ var MODIFIED = 1;
11365
+ var VISITED = 32768;
11366
+ var CLEAR_FLAGS = 32766;
11065
11367
  function emptyRow(terrainType = 0) {
11066
11368
  const q = () => ({
11067
11369
  left: 0,
@@ -11629,6 +11931,8 @@ function isomTables(tileset, era) {
11629
11931
  }
11630
11932
  var isomWidth = (scn) => Math.floor(scn.width / 2) + 1;
11631
11933
  var isomHeight = (scn) => scn.height + 1;
11934
+ /** Only lattice points with an even coordinate sum are diamonds. */
11935
+ var isDiamond = (d) => (d.x + d.y) % 2 === 0;
11632
11936
  /** The rect a diamond's quadrant lies in; diamond (x, y) is its own bottom-right rect. */
11633
11937
  function rectOf(d, q) {
11634
11938
  switch (q) {
@@ -11647,6 +11951,462 @@ function rectOf(d, q) {
11647
11951
  };
11648
11952
  }
11649
11953
  }
11954
+ /** Neighbours in quadrant order — upper-left, upper-right, lower-right, lower-left. */
11955
+ function neighbourOf(d, q) {
11956
+ switch (q) {
11957
+ case Q_TL: return {
11958
+ x: d.x - 1,
11959
+ y: d.y - 1
11960
+ };
11961
+ case Q_TR: return {
11962
+ x: d.x + 1,
11963
+ y: d.y - 1
11964
+ };
11965
+ case Q_BR: return {
11966
+ x: d.x + 1,
11967
+ y: d.y + 1
11968
+ };
11969
+ default: return {
11970
+ x: d.x - 1,
11971
+ y: d.y + 1
11972
+ };
11973
+ }
11974
+ }
11975
+ /**
11976
+ * The diamond under a map pixel — StarEdit's own arithmetic. Diamond (x, y) is centred
11977
+ * on pixel (64x, 32y) and spans 128x64. The result can be off the map; check bounds.
11978
+ */
11979
+ function diamondAt(px, py) {
11980
+ const x = Math.max(0, Math.floor(px));
11981
+ const y = Math.max(0, Math.floor(py));
11982
+ let calcX = x - y * 2;
11983
+ let calcY = Math.floor(x / 2) + y;
11984
+ calcX -= calcX - 64 & 127;
11985
+ calcY -= calcY - 32 & 63;
11986
+ const half = Math.trunc(calcX / 2) + 32;
11987
+ return {
11988
+ x: Math.trunc(Math.trunc((calcY + 32 + half) / 32) / 2),
11989
+ y: Math.trunc(Math.trunc((calcY + 32 - half) / 2) / 32)
11990
+ };
11991
+ }
11992
+ /** Brush offsets StarEdit uses: an N-extent brush is N×N diamonds along the lattice axes. */
11993
+ function brushRange(extent) {
11994
+ let min = Math.trunc(extent / -2);
11995
+ let max = min + extent;
11996
+ if (extent % 2 === 0) {
11997
+ min++;
11998
+ max++;
11999
+ }
12000
+ return {
12001
+ min,
12002
+ max
12003
+ };
12004
+ }
12005
+ /**
12006
+ * A pass over one scenario: tracks what it touches so the caller gets change lists,
12007
+ * and keeps the scratch flags StarEdit leaves in the ISOM u16s while it works.
12008
+ */
12009
+ var IsomPass = class {
12010
+ scn;
12011
+ tileset;
12012
+ tables;
12013
+ random;
12014
+ w;
12015
+ h;
12016
+ isom;
12017
+ isomBefore = /* @__PURE__ */ new Map();
12018
+ tileBefore = /* @__PURE__ */ new Map();
12019
+ changed = {
12020
+ left: 0,
12021
+ top: 0,
12022
+ right: -1,
12023
+ bottom: -1
12024
+ };
12025
+ constructor(scn, tileset, tables, random) {
12026
+ this.scn = scn;
12027
+ this.tileset = tileset;
12028
+ this.tables = tables;
12029
+ this.random = random;
12030
+ this.w = isomWidth(scn);
12031
+ this.h = isomHeight(scn);
12032
+ this.isom = scn.isom;
12033
+ this.resetChanged();
12034
+ }
12035
+ resetChanged() {
12036
+ this.changed = {
12037
+ left: this.w,
12038
+ top: this.h,
12039
+ right: 0,
12040
+ bottom: 0
12041
+ };
12042
+ }
12043
+ touch(x, y) {
12044
+ const c = this.changed;
12045
+ c.left = Math.min(c.left, x);
12046
+ c.right = Math.max(c.right, x);
12047
+ c.top = Math.min(c.top, y);
12048
+ c.bottom = Math.max(c.bottom, y);
12049
+ }
12050
+ inBounds(p) {
12051
+ return p.x >= 0 && p.y >= 0 && p.x < this.w && p.y < this.h;
12052
+ }
12053
+ at(p) {
12054
+ return (p.y * this.w + p.x) * 4;
12055
+ }
12056
+ write(index, value) {
12057
+ if (!this.isomBefore.has(index)) this.isomBefore.set(index, this.isom[index]);
12058
+ this.isom[index] = value;
12059
+ }
12060
+ /** The value of the diamond whose bottom-right rect this is. */
12061
+ central(p) {
12062
+ return this.isom[this.at(p) + S_LEFT] >> 4;
12063
+ }
12064
+ centralModified(p) {
12065
+ return (this.isom[this.at(p) + S_LEFT] & MODIFIED) !== 0;
12066
+ }
12067
+ visited(p) {
12068
+ return (this.isom[this.at(p) + S_RIGHT] & VISITED) !== 0;
12069
+ }
12070
+ setVisited(p) {
12071
+ const i = this.at(p) + S_RIGHT;
12072
+ this.write(i, this.isom[i] | VISITED);
12073
+ }
12074
+ setIsomValue(p, q, value) {
12075
+ if (!this.inBounds(p)) return;
12076
+ const { sides, flags } = PROJECTED[q];
12077
+ const base = this.at(p);
12078
+ this.write(base + sides[0], (value << 4 | flags[0] | MODIFIED) & 65535);
12079
+ this.write(base + sides[1], (value << 4 | flags[1] | MODIFIED) & 65535);
12080
+ this.touch(p.x, p.y);
12081
+ }
12082
+ setDiamond(d, value) {
12083
+ for (const q of QUADRANTS) this.setIsomValue(rectOf(d, q), q, value);
12084
+ }
12085
+ needsUpdate(d) {
12086
+ return this.inBounds(d) && !this.centralModified(d) && this.central(d) !== 0;
12087
+ }
12088
+ loadNeighbours(d) {
12089
+ const n = {
12090
+ linkId: [
12091
+ 0,
12092
+ 0,
12093
+ 0,
12094
+ 0
12095
+ ],
12096
+ isomValue: [
12097
+ 0,
12098
+ 0,
12099
+ 0,
12100
+ 0
12101
+ ],
12102
+ modified: [
12103
+ false,
12104
+ false,
12105
+ false,
12106
+ false
12107
+ ],
12108
+ maxModifiedType: 0,
12109
+ best: {
12110
+ isomValue: 0,
12111
+ count: 0
12112
+ }
12113
+ };
12114
+ const { links } = this.tables;
12115
+ for (const q of QUADRANTS) {
12116
+ const nb = neighbourOf(d, q);
12117
+ if (!this.inBounds(nb)) continue;
12118
+ const v = this.central(nb);
12119
+ n.modified[q] = this.centralModified(nb);
12120
+ n.isomValue[q] = v;
12121
+ if (v < links.length) {
12122
+ n.linkId[q] = links[v].quads[opposite(q)].linkId;
12123
+ if (n.modified[q] && links[v].terrainType > n.maxModifiedType) n.maxModifiedType = links[v].terrainType;
12124
+ }
12125
+ }
12126
+ return n;
12127
+ }
12128
+ countMatches(row, n) {
12129
+ const { links } = this.tables;
12130
+ let total = 0;
12131
+ for (const q of QUADRANTS) {
12132
+ const nbRow = links[n.isomValue[q] < links.length ? n.isomValue[q] : 0];
12133
+ const id = row.quads[q].linkId;
12134
+ if (n.linkId[q] === id && (id < SAME_TYPE_ONLY || row.terrainType === nbRow.terrainType)) total++;
12135
+ else if (n.modified[q]) return 0;
12136
+ }
12137
+ return total;
12138
+ }
12139
+ search(startType, n) {
12140
+ const { links, terrainTypes } = this.tables;
12141
+ const untilHigher = startType === Math.floor(terrainTypes.length / 2) + 1;
12142
+ const untilEnd = startType === 0;
12143
+ for (let v = terrainTypes[startType]?.isomValue ?? 0; v < links.length; v++) {
12144
+ const type = links[v].terrainType;
12145
+ if (!untilEnd && type !== startType && (!untilHigher || type > startType)) break;
12146
+ const count = this.countMatches(links[v], n);
12147
+ if (count > n.best.count) n.best = {
12148
+ isomValue: v,
12149
+ count
12150
+ };
12151
+ }
12152
+ }
12153
+ bestMatch(d) {
12154
+ const { links, terrainTypes, terrainTypeMap } = this.tables;
12155
+ const n = this.loadNeighbours(d);
12156
+ const prev = this.central(d);
12157
+ if (prev < links.length) {
12158
+ const prevType = links[prev].terrainType;
12159
+ this.search(terrainTypeMap[n.maxModifiedType * terrainTypes.length + prevType], n);
12160
+ }
12161
+ this.search(n.maxModifiedType, n);
12162
+ this.search(Math.floor(terrainTypes.length / 2) + 1, n);
12163
+ return n.best.isomValue === prev ? null : n.best.isomValue;
12164
+ }
12165
+ propagate(queue) {
12166
+ while (queue.length > 0) {
12167
+ const d = queue.shift();
12168
+ if (!this.needsUpdate(d) || this.visited(d)) continue;
12169
+ this.setVisited(d);
12170
+ this.touch(d.x, d.y);
12171
+ const best = this.bestMatch(d);
12172
+ if (best === null) continue;
12173
+ if (best !== 0) this.setDiamond(d, best);
12174
+ for (const q of QUADRANTS) {
12175
+ const nb = neighbourOf(d, q);
12176
+ if (this.needsUpdate(nb)) queue.push(nb);
12177
+ }
12178
+ }
12179
+ }
12180
+ /** Set the brush diamonds and let the change ripple out. False when the terrain cannot be painted. */
12181
+ place(d, terrainType, extent) {
12182
+ const { links, terrainTypes } = this.tables;
12183
+ const value = terrainTypes[terrainType]?.isomValue ?? 0;
12184
+ if (value === 0 || !isDiamond(d) || value >= links.length || links[value].terrainType === 0) return false;
12185
+ const { min, max } = brushRange(extent);
12186
+ const queue = [];
12187
+ for (let ox = min; ox < max; ox++) for (let oy = min; oy < max; oy++) {
12188
+ const b = {
12189
+ x: d.x + ox - oy,
12190
+ y: d.y + ox + oy
12191
+ };
12192
+ if (!this.inBounds(b)) continue;
12193
+ this.setDiamond(b, value);
12194
+ if (ox === min || ox === max - 1 || oy === min || oy === max - 1) for (const q of QUADRANTS) {
12195
+ const nb = neighbourOf(b, q);
12196
+ if (this.needsUpdate(nb)) queue.push(nb);
12197
+ }
12198
+ }
12199
+ this.propagate(queue);
12200
+ return true;
12201
+ }
12202
+ /**
12203
+ * Set every diamond of `diamonds` to the terrain at once and let the change ripple out
12204
+ * from all of them — the brush with a footprint of any shape. False when the terrain
12205
+ * cannot be painted (nothing is set then).
12206
+ */
12207
+ placeMany(diamonds, terrainType) {
12208
+ const { links, terrainTypes } = this.tables;
12209
+ const value = terrainTypes[terrainType]?.isomValue ?? 0;
12210
+ if (value === 0 || value >= links.length || links[value].terrainType === 0) return false;
12211
+ const set = diamonds.filter((d) => isDiamond(d) && this.inBounds(d));
12212
+ for (const d of set) this.setDiamond(d, value);
12213
+ const queue = [];
12214
+ for (const d of set) for (const q of QUADRANTS) {
12215
+ const nb = neighbourOf(d, q);
12216
+ if (this.needsUpdate(nb)) queue.push(nb);
12217
+ }
12218
+ this.propagate(queue);
12219
+ return true;
12220
+ }
12221
+ tile(x, y) {
12222
+ return this.scn.tiles[y * this.scn.width + x];
12223
+ }
12224
+ setTile(x, y, value) {
12225
+ if (x >= this.scn.width || y >= this.scn.height) return;
12226
+ const at = y * this.scn.width + x;
12227
+ if (!this.tileBefore.has(at)) this.tileBefore.set(at, this.scn.tiles[at]);
12228
+ this.scn.tiles[at] = value;
12229
+ }
12230
+ rectHash(p) {
12231
+ const { links } = this.tables;
12232
+ const base = this.at(p);
12233
+ let hash = 0;
12234
+ let lastType = 0;
12235
+ for (let side = 0; side < 4; side++) {
12236
+ const v = this.isom[base + side] & CLEAR_FLAGS;
12237
+ const row = v >> 4;
12238
+ if (row >= links.length) continue;
12239
+ const link = edgeLink(links[row], v);
12240
+ hash = (hash | link) << 6;
12241
+ if (links[row].terrainType !== 0 && isHard(link)) lastType = links[row].terrainType;
12242
+ }
12243
+ return (hash | lastType) >>> 0;
12244
+ }
12245
+ /** The CV5 groups a rect's links resolve to, in the order StarEdit tries them. */
12246
+ groupsFor(p) {
12247
+ return this.tables.hashToGroups.get(this.rectHash(p));
12248
+ }
12249
+ /** Re-derive the tile pair under rect `p`, and the cliff face stacked above and below it. */
12250
+ updateTile(p) {
12251
+ if (p.x + 1 >= this.w || p.y + 1 >= this.h) return;
12252
+ const { groups } = this.tileset;
12253
+ const total = groups.length;
12254
+ const leftX = 2 * p.x, rightX = leftX + 1;
12255
+ const found = this.groupsFor(p);
12256
+ if (!found) {
12257
+ this.setTile(leftX, p.y, 0);
12258
+ this.setTile(rightX, p.y, 0);
12259
+ return;
12260
+ }
12261
+ let dest = found[0];
12262
+ if (p.y > 0) {
12263
+ const above = this.tile(leftX, p.y - 1) >> 4;
12264
+ if (above < total) {
12265
+ const bottom = groups[above].stack.bottom;
12266
+ for (const g of found) if (groups[g].stack.top === bottom) {
12267
+ dest = g;
12268
+ break;
12269
+ }
12270
+ }
12271
+ }
12272
+ const sub = pickVariation(variationsOf(this.tileset, dest), this.random) & 15;
12273
+ this.setTile(leftX, p.y, 16 * dest + sub);
12274
+ this.setTile(rightX, p.y, 16 * (dest + 1) + sub);
12275
+ let topY = p.y;
12276
+ let curr = this.tile(leftX, topY) >> 4;
12277
+ while (topY > 0 && curr < total && groups[curr].stack.top !== 0) {
12278
+ const above = this.tile(leftX, topY - 1) >> 4;
12279
+ if (above >= total || groups[curr].stack.top !== groups[above].stack.bottom) break;
12280
+ curr = above;
12281
+ topY--;
12282
+ }
12283
+ this.setTile(leftX, topY, 16 * (this.tile(leftX, topY) >> 4) + sub);
12284
+ this.setTile(rightX, topY, 16 * (this.tile(rightX, topY) >> 4) + sub);
12285
+ for (let y = topY + 1; y < this.scn.height; y++) {
12286
+ const upper = this.tile(leftX, y - 1) >> 4;
12287
+ const lower = this.tile(leftX, y) >> 4;
12288
+ if (upper >= total || lower >= total || groups[upper].stack.bottom === 0 || groups[lower].stack.top === 0) break;
12289
+ const bottom = groups[upper].stack.bottom;
12290
+ let leftGroup = lower;
12291
+ let rightGroup = this.tile(rightX, y) >> 4;
12292
+ if (bottom !== groups[lower].stack.top) {
12293
+ const candidates = this.groupsFor({
12294
+ x: p.x,
12295
+ y
12296
+ });
12297
+ if (candidates) {
12298
+ for (const g of candidates) if (groups[g].stack.top === bottom) {
12299
+ leftGroup = g;
12300
+ rightGroup = g + 1;
12301
+ break;
12302
+ }
12303
+ }
12304
+ }
12305
+ this.setTile(leftX, y, 16 * leftGroup + sub);
12306
+ this.setTile(rightX, y, 16 * rightGroup + sub);
12307
+ }
12308
+ }
12309
+ /** Turn every rect the pass touched back into tiles and drop the scratch flags. */
12310
+ updateTiles() {
12311
+ const c = this.changed;
12312
+ for (let y = c.top; y <= c.bottom; y++) for (let x = c.left; x <= c.right; x++) {
12313
+ const base = this.at({
12314
+ x,
12315
+ y
12316
+ });
12317
+ if ((this.isom[base + S_LEFT] | this.isom[base + S_RIGHT]) & MODIFIED) this.updateTile({
12318
+ x,
12319
+ y
12320
+ });
12321
+ for (let s = 0; s < 4; s++) {
12322
+ const v = this.isom[base + s];
12323
+ if (v & -32767) this.write(base + s, v & CLEAR_FLAGS);
12324
+ }
12325
+ }
12326
+ this.resetChanged();
12327
+ }
12328
+ /** What changed, net of anything that ended where it started. */
12329
+ finish() {
12330
+ for (const i of this.isomBefore.keys()) this.isom[i] &= CLEAR_FLAGS;
12331
+ const isom = [];
12332
+ for (const [at, before] of this.isomBefore) {
12333
+ const after = this.isom[at];
12334
+ if (after !== before) isom.push({
12335
+ at,
12336
+ before,
12337
+ after
12338
+ });
12339
+ }
12340
+ const tiles = [];
12341
+ for (const [at, before] of this.tileBefore) {
12342
+ const after = this.scn.tiles[at];
12343
+ if (after !== before) tiles.push({
12344
+ at,
12345
+ before,
12346
+ after
12347
+ });
12348
+ }
12349
+ if (tiles.length > 0) markDirty(this.scn, "MTXM", "TILE");
12350
+ if (isom.length > 0) markDirty(this.scn, "ISOM");
12351
+ return {
12352
+ tiles,
12353
+ isom
12354
+ };
12355
+ }
12356
+ };
12357
+ /** True when the scenario carries an ISOM section the brush can work on. */
12358
+ function hasIsom(scn) {
12359
+ return scn !== null && scn.isom !== null && scn.isom.length >= isomWidth(scn) * isomHeight(scn) * 4;
12360
+ }
12361
+ /**
12362
+ * Paint `terrainType` (a CV5 index) with an `extent`-diamond brush centred on `d`.
12363
+ * Mutates `scn.tiles` and `scn.isom`; returns what changed, or null when the terrain is
12364
+ * not one the tileset paints isometrically or `d` is not a diamond.
12365
+ */
12366
+ function paintIsom(scn, tileset, d, terrainType, extent, random = Math.random) {
12367
+ const pass = new IsomPass(scn, tileset, isomTables(tileset, tilesetIndex(scn)), random);
12368
+ if (!pass.place(d, terrainType, extent)) return null;
12369
+ pass.updateTiles();
12370
+ const edit = pass.finish();
12371
+ mirrorEditorTiles(scn, edit.tiles);
12372
+ return edit;
12373
+ }
12374
+ /**
12375
+ * Paint `terrainType` (a CV5 index) over any set of diamonds in one stroke: each is set to
12376
+ * the terrain, the neighbours they leave are re-picked as `paintIsom` re-picks the edge of
12377
+ * its brush, and the tiles follow. What `scmjs map generate` lays its ground with, a whole
12378
+ * plateau or lake at a time, so the result does not depend on the order of the diamonds.
12379
+ * Diamonds off the lattice or off the map are skipped; null when the terrain is not one
12380
+ * the tileset paints isometrically.
12381
+ */
12382
+ function paintIsomDiamonds(scn, tileset, diamonds, terrainType, random = Math.random) {
12383
+ const pass = new IsomPass(scn, tileset, isomTables(tileset, tilesetIndex(scn)), random);
12384
+ if (!pass.placeMany(diamonds, terrainType)) return null;
12385
+ pass.updateTiles();
12386
+ const edit = pass.finish();
12387
+ mirrorEditorTiles(scn, edit.tiles);
12388
+ return edit;
12389
+ }
12390
+ /** How well the ISOM section describes the tiles that are actually on the map. */
12391
+ function checkIsom(scn, tileset) {
12392
+ const pass = new IsomPass(scn, tileset, isomTables(tileset, tilesetIndex(scn)), Math.random);
12393
+ const { groups } = tileset;
12394
+ let rects = 0, mismatched = 0;
12395
+ for (let y = 0; y < scn.height; y++) for (let x = 0; x < Math.floor(scn.width / 2); x++) {
12396
+ rects++;
12397
+ const actual = groups[scn.tiles[y * scn.width + 2 * x] >> 4]?.index ?? -1;
12398
+ if (actual === 1) continue;
12399
+ const found = pass.groupsFor({
12400
+ x,
12401
+ y
12402
+ });
12403
+ if (actual !== (found ? groups[found[0]].index : -1)) mismatched++;
12404
+ }
12405
+ return {
12406
+ rects,
12407
+ mismatched
12408
+ };
12409
+ }
11650
12410
  /**
11651
12411
  * Reconstruct an ISOM section from the tiles: every tile group's four links say which
11652
12412
  * table rows could have produced it on each side, and each diamond takes the row most
@@ -12076,6 +12836,247 @@ function placeStartLocations(scn, tileset, tables, options) {
12076
12836
  };
12077
12837
  }
12078
12838
  //#endregion
12839
+ //#region src/formats/tileset/doodads.ts
12840
+ /**
12841
+ * The tileset's doodad catalogue: what the Doodads palette lists and what placement
12842
+ * stamps onto the map.
12843
+ *
12844
+ * A doodad is a rectangle of CV5 doodad groups (see `Cv5Doodad`): one group per row,
12845
+ * one megatile slot per column, every group repeating the doodad's `ddData` index,
12846
+ * width and height. Two more files describe it:
12847
+ *
12848
+ * - `tileset\<name>\dddata.bin` — 512 entries of 256 u16, indexed by `ddData`: for
12849
+ * each cell (row-major, stride `width`) the CV5 group that must already be under it
12850
+ * for StarEdit to allow the placement, or 0 for "anything". This is how a ramp only
12851
+ * fits on the cliff edge it was drawn for. Cells can be required yet carry no
12852
+ * megatile (the ramp's approach), or carry a megatile with no requirement.
12853
+ * - `rez\stat_txt.tbl` — the category name each group's `nameIndex` points at.
12854
+ *
12855
+ * DD2 records store the `ddData` index, so it is the doodad's id here too.
12856
+ */
12857
+ function isRampMegatile(tileset, megatile) {
12858
+ const base = megatile * 16;
12859
+ for (let i = 0; i < 16; i++) if (tileset.megatileFlags[base + i] & TileFlag.Ramp) return true;
12860
+ return false;
12861
+ }
12862
+ var UNLISTED = "Unlisted";
12863
+ var SPRITE_OVERLAY = 4096;
12864
+ var UNIT_OVERLAY = 8192;
12865
+ var OVERLAY_FLIPPED = 16384;
12866
+ /**
12867
+ * Read the doodads out of the CV5. `dddata` may be null (no requirements) and `names`
12868
+ * the decoded stat_txt.tbl or null (one anonymous category).
12869
+ */
12870
+ function buildDoodadCatalogue(tileset, dddata, names) {
12871
+ const { groups } = tileset;
12872
+ const data = dddata && dddata.length >= 262144 ? new DataView(dddata.buffer, dddata.byteOffset, dddata.byteLength) : null;
12873
+ const doodads = [];
12874
+ const byId = /* @__PURE__ */ new Map();
12875
+ for (let g = 0; g < groups.length; g++) {
12876
+ const cv5 = groups[g];
12877
+ const d = cv5.doodad;
12878
+ if (!d || cv5.index !== 1) continue;
12879
+ if (byId.has(d.ddData)) continue;
12880
+ if (d.width === 0 || d.height === 0 || d.width > 16) continue;
12881
+ const cells = d.width * d.height;
12882
+ const tiles = new Uint16Array(cells);
12883
+ const required = new Uint16Array(cells);
12884
+ let any = false;
12885
+ for (let row = 0; row < d.height; row++) {
12886
+ const rowGroup = groups[g + row];
12887
+ if (!rowGroup || rowGroup.doodad?.ddData !== d.ddData) continue;
12888
+ for (let col = 0; col < d.width; col++) {
12889
+ const id = g + row << 4 | col;
12890
+ if (megatileForTile(tileset, id) > 0) {
12891
+ tiles[row * d.width + col] = id;
12892
+ any = true;
12893
+ }
12894
+ }
12895
+ }
12896
+ if (!any) continue;
12897
+ if (data && d.ddData < 512) {
12898
+ const base = d.ddData * 256 * 2;
12899
+ for (let i = 0; i < cells && i < 256; i++) required[i] = data.getUint16(base + i * 2, true);
12900
+ }
12901
+ const name = names && d.nameIndex > 0 ? names[d.nameIndex - 1] : void 0;
12902
+ let overlay = null;
12903
+ if (cv5.flags & SPRITE_OVERLAY) overlay = {
12904
+ kind: "sprite",
12905
+ id: d.overlay,
12906
+ flipped: (cv5.flags & OVERLAY_FLIPPED) !== 0
12907
+ };
12908
+ else if (cv5.flags & UNIT_OVERLAY) overlay = {
12909
+ kind: "unit",
12910
+ id: d.overlay,
12911
+ flipped: (cv5.flags & OVERLAY_FLIPPED) !== 0
12912
+ };
12913
+ const def = {
12914
+ id: d.ddData,
12915
+ group: g,
12916
+ width: d.width,
12917
+ height: d.height,
12918
+ category: name?.trim() || UNLISTED,
12919
+ flags: cv5.flags,
12920
+ overlay,
12921
+ tiles,
12922
+ required,
12923
+ ramp: tiles.some((t) => t !== 0 && isRampMegatile(tileset, megatileForTile(tileset, t)))
12924
+ };
12925
+ doodads.push(def);
12926
+ byId.set(def.id, def);
12927
+ }
12928
+ const categories = [];
12929
+ const byName = /* @__PURE__ */ new Map();
12930
+ for (const def of doodads) {
12931
+ let cat = byName.get(def.category);
12932
+ if (!cat) {
12933
+ cat = {
12934
+ name: def.category,
12935
+ doodads: []
12936
+ };
12937
+ byName.set(def.category, cat);
12938
+ categories.push(cat);
12939
+ }
12940
+ cat.doodads.push(def);
12941
+ }
12942
+ const unlisted = categories.findIndex((c) => c.name === UNLISTED);
12943
+ if (unlisted >= 0) categories.push(...categories.splice(unlisted, 1));
12944
+ return {
12945
+ doodads,
12946
+ byId,
12947
+ categories,
12948
+ hasPlacementData: data !== null
12949
+ };
12950
+ }
12951
+ /** The DD2 (and overlay THG2) pixel position of a doodad placed with its top-left tile at (tx, ty). */
12952
+ function doodadCenter(def, tx, ty) {
12953
+ return {
12954
+ x: tx * 32 + def.width * 16,
12955
+ y: ty * 32 + def.height * 16
12956
+ };
12957
+ }
12958
+ //#endregion
12959
+ //#region src/editor/doodads.ts
12960
+ /**
12961
+ * Doodad edits: placing, removing and moving the tile-based doodads StarEdit records in
12962
+ * `DD2 `, as invertible change lists in the spirit of `TileChange` / `UnitChange`.
12963
+ *
12964
+ * A placed doodad is three things in the file, and an edit touches all of them:
12965
+ *
12966
+ * - its megatiles stamped into MTXM (`scenario.tiles`) — but *not* into TILE
12967
+ * (`scenario.editorTiles`), which keeps the ground beneath so removal can restore it;
12968
+ * - a `DD2 ` record with the dddata index and the footprint's pixel centre;
12969
+ * - for doodads with an overlay (tree canopies, Installation doors), a `THG2` sprite at
12970
+ * the same centre carrying the doodad's CV5 flag word, exactly as StarEdit writes it.
12971
+ *
12972
+ * Placement follows StarEdit's rules unless "place anywhere" is on: every cell with a
12973
+ * requirement in dddata.bin must sit on exactly that CV5 group, no cell may land on
12974
+ * another doodad's tile, and the footprint must be inside the map (that last one always
12975
+ * holds — tiles cannot be written off the edge). "Snap to grid" keeps the left column
12976
+ * even, which is where StarEdit puts every doodad (the isometric lattice is two tiles
12977
+ * wide) and what the requirement tables are drawn for.
12978
+ */
12979
+ function applyDoodadChanges(scn, changes, direction = "do") {
12980
+ applyList(scn.doodads, changes, direction);
12981
+ if (changes.length > 0) markDirty(scn, "DD2 ");
12982
+ }
12983
+ var DEFAULT_DOODAD_PLACEMENT = {
12984
+ placeAnywhere: false,
12985
+ snapToGrid: true,
12986
+ asTerrain: false
12987
+ };
12988
+ /**
12989
+ * May `def` go with its top-left tile at (tx, ty)? `tileAt` overrides what a cell
12990
+ * currently holds — a move passes the map as it would be with the moving doodads gone.
12991
+ *
12992
+ * A requirement counts only under a cell the doodad draws. Measured against Blizzard's
12993
+ * own maps (Ice Floes, Spring Thaw, Isolation): every ramp and bridge they placed sits
12994
+ * on ground that matches its drawn cells exactly and its undrawn "approach" cells not
12995
+ * at all — an Ice cliff ramp wants two more rows of cliff above it than any cliff has, a
12996
+ * Desert bridge wants dirt where its channel's water is — so StarEdit never looked at
12997
+ * those.
12998
+ */
12999
+ function checkDoodadPlacement(scn, tileset, def, tx, ty, opts, tileAt = (at) => scn.tiles[at]) {
13000
+ if (tx < 0 || ty < 0 || tx + def.width > scn.width || ty + def.height > scn.height) return {
13001
+ ok: false,
13002
+ outOfBounds: true,
13003
+ bad: []
13004
+ };
13005
+ const bad = [];
13006
+ if (!opts.placeAnywhere) for (let row = 0; row < def.height; row++) for (let col = 0; col < def.width; col++) {
13007
+ const cell = row * def.width + col;
13008
+ const required = def.required[cell];
13009
+ if (def.tiles[cell] === 0) continue;
13010
+ const group = tileAt((ty + row) * scn.width + tx + col) >> 4;
13011
+ if (required !== 0 && group !== required) {
13012
+ bad.push(cell);
13013
+ continue;
13014
+ }
13015
+ if (def.tiles[cell] !== 0 && tileset?.groups[group]?.index === 1) bad.push(cell);
13016
+ }
13017
+ return {
13018
+ ok: bad.length === 0,
13019
+ outOfBounds: false,
13020
+ bad
13021
+ };
13022
+ }
13023
+ function makeDoodad(def, tx, ty, owner) {
13024
+ const c = doodadCenter(def, tx, ty);
13025
+ return {
13026
+ doodadId: def.id,
13027
+ x: c.x,
13028
+ y: c.y,
13029
+ owner,
13030
+ disabled: 0
13031
+ };
13032
+ }
13033
+ /** The THG2 record StarEdit adds for a doodad's overlay, or null when it has none. */
13034
+ function makeOverlaySprite(def, rec) {
13035
+ if (!def.overlay) return null;
13036
+ return {
13037
+ spriteId: def.overlay.id,
13038
+ x: rec.x,
13039
+ y: rec.y,
13040
+ owner: rec.owner,
13041
+ unused: 0,
13042
+ flags: def.flags
13043
+ };
13044
+ }
13045
+ /**
13046
+ * Stamp `def` at (tx, ty): its tiles into MTXM, a DD2 record and, if it has one, the
13047
+ * overlay sprite. `tileAt` is what the cells hold right now (a move passes the state
13048
+ * with the old copy removed). Nothing is applied.
13049
+ */
13050
+ function placeDoodad(scn, def, tx, ty, owner, tileAt = (at) => scn.tiles[at]) {
13051
+ const tiles = [];
13052
+ for (let row = 0; row < def.height; row++) for (let col = 0; col < def.width; col++) {
13053
+ const id = def.tiles[row * def.width + col];
13054
+ if (id === 0) continue;
13055
+ const at = (ty + row) * scn.width + tx + col;
13056
+ const before = tileAt(at);
13057
+ if (before !== id) tiles.push({
13058
+ at,
13059
+ before,
13060
+ after: id
13061
+ });
13062
+ }
13063
+ const rec = makeDoodad(def, tx, ty, owner);
13064
+ const sprite = makeOverlaySprite(def, rec);
13065
+ return {
13066
+ tiles,
13067
+ doodads: [{
13068
+ index: scn.doodads.length,
13069
+ before: null,
13070
+ after: rec
13071
+ }],
13072
+ sprites: sprite ? [{
13073
+ index: scn.sprites.length,
13074
+ before: null,
13075
+ after: sprite
13076
+ }] : []
13077
+ };
13078
+ }
13079
+ //#endregion
12079
13080
  //#region src/plugins/api.ts
12080
13081
  /**
12081
13082
  * The version a host provides; a manifest that asks for a newer one is refused. It stays
@@ -12248,4 +13249,4 @@ function canonicalSpec(source) {
12248
13249
  return source.kind === "builtin" ? `builtin:${source.name}` : source.display;
12249
13250
  }
12250
13251
  //#endregion
12251
- export { ACTION_DEFS, AI_SCRIPT_NAMES, ANYWHERE_NAME, BRIEFING_ACTION_DEFS, BUILD_MANIFEST_MEMBER, BUILD_SOURCE_MEMBER, CHOICES, CONDITION_DEFS, ColorMode, DEFAULT_GAS, DEFAULT_MINERALS, DEFAULT_PLACEMENT, DEFAULT_SAVE_OPTIONS, DEFAULT_START_PLACEMENT, DEFAULT_TEXT_ENCODING, DIRT, FIND_KINDS, FORCE_SLOTS, ForceFlag, MAP_SIZES, MAP_VERSIONS, MEGATILE_PX, MINERAL_FIELD_IDS, MODELLED_SECTIONS, MapLoadError, PLAYER_COLORS, PLAYER_RACES, PLAYER_SLOTS, PLAYER_TYPES, PLUGIN_API_VERSION, PlayerRace, PlayerType, REQUIRED_SECTIONS, SAVE_PRESETS, SCENARIO_PATH, START_LOCATION, STRX_CAPACITY, TECH_NAMES, TEXT_CODES, TEXT_ENCODINGS, TILESETS, TILESET_BY_ID, TRIGGER_OWNERS, TriggerTextError, UNIT_LIMIT, UNIT_NAMES, UNIT_TYPE_COUNT, UPGRADE_NAMES, VESPENE_GEYSER, actionDef, actionDefByName, addLocation, addUnits, aiScriptByName, aiScriptName, applyBriefing, applyForceSettings, applyLocationChanges, applyPlayerSettings, applyStringImport, applyStrings, applyTechSettings, applyTriggers, applyUnitChanges, applyUnitSettings, applyUpgradeSettings, baseTerrain, buildChk, buildMapFile, changeMapVersion, changeTextEncoding, choiceLabel, choiceValue, conditionDef, conditionDefByName, createScenario, decodeTrg, decodeUnitsDat, defaultSaveOptions, deleteUnused, displayColorHex, drawMegatile, editLocation, encodeTrg, escapeStringText, extraKind, findInScenario, fingerprintTrigger, flatTerrain, forceName, formatBytes, formatOf, formatStringTable, formatTrigger, formatTriggers, idealStarts, internString, isExpansion, isPreserved, isRemasteredRevision, isResource, issueCounts, keptExtras, loadMap, loadTileset, locationCapacity, locationName, looksLikeMpq, makeUnit, mapStatistics, mapVersionOf, markDirty, megatileForTile, moveLocations, moveUnits, newAction, newCondition, newTrigger, nextSerial, openMapBytes, packBuiltMap, parseChk, parseScenario, parseStringTable, parseTriggers, placeStartLocations, placedLocations, plainText, planSave, playableCount, playerColorHex, playerRaceLabel, playerTypeLabel, readArchive, readBriefing, readBuildManifest, readExtras, readForceSettings, readMembers, readPlayerSettings, readStrings, readSwitchNames, readTechSettings, readTriggerFile, readTriggers, readUnitSettings, readUpgradeSettings, removeLocations, removeUnits, requiredSections, resizeScenario, resolveIcon, restoreBuiltMap, runsOf, sameTriggers, scenarioDescription, scenarioName, serializeChk, serializeScenario, setExtendedStrings, setMapVersion, setPreserved, setScenarioDescription, setScenarioName, setTextEncoding, soundList, statisticsText, stringCapacity, stringUsages, summarizeTrigger, techName, textCode, tilesetIndex, triggerFormatOf, triggerNames, triggerUsage, triggersFromText, triggersToText, unescapeStringText, unitAt, unitCustomName, unitGeometry, unitName, unitsInBox, unusedStrings, updateUnits, upgradeName, usedLocations, validateManifest, validateScenario, writeArchiveBytes, writeMapBytes };
13252
+ export { ACTION_DEFS, AI_SCRIPT_NAMES, ANYWHERE_NAME, ActionType, BRIEFING_ACTION_DEFS, BUILD_MANIFEST_MEMBER, BUILD_SOURCE_MEMBER, CHOICES, CONDITION_DEFS, ColorMode, Comparison, ConditionType, DEFAULT_DOODAD_PLACEMENT, DEFAULT_GAS, DEFAULT_MINERALS, DEFAULT_PLACEMENT, DEFAULT_SAVE_OPTIONS, DEFAULT_START_PLACEMENT, DEFAULT_TEXT_ENCODING, DIRT, FIND_KINDS, FORCE_SLOTS, ForceFlag, MAP_SIZES, MAP_VERSIONS, MEGATILE_PX, MINERAL_FIELD_IDS, MODELLED_SECTIONS, MapLoadError, PLAYER_COLORS, PLAYER_RACES, PLAYER_SLOTS, PLAYER_TYPES, PLUGIN_API_VERSION, PlayerGroup, PlayerRace, PlayerType, REQUIRED_SECTIONS, ResourceType, SAVE_PRESETS, SCENARIO_PATH, START_LOCATION, STRX_CAPACITY, SetModifier, SwitchAction, SwitchState, TECH_NAMES, TEXT_CODES, TEXT_ENCODINGS, TILESETS, TILESET_BY_ID, TRIGGER_OWNERS, TileFlag, TriggerTextError, UNIT_LIMIT, UNIT_NAMES, UNIT_TYPE_COUNT, UPGRADE_NAMES, UnitClass, VESPENE_GEYSER, actionDef, actionDefByName, addLocation, addUnits, aiScriptByName, aiScriptName, applyBriefing, applyChanges, applyDoodadChanges, applyForceSettings, applyLocationChanges, applyPlayerSettings, applyStringImport, applyStrings, applyTechSettings, applyTriggers, applyUnitChanges, applyUnitSettings, applyUpgradeSettings, baseTerrain, buildChk, buildDoodadCatalogue, buildMapFile, changeMapVersion, changeTextEncoding, checkDoodadPlacement, checkIsom, choiceLabel, choiceValue, conditionDef, conditionDefByName, createScenario, decodeTrg, decodeUnitsDat, defaultSaveOptions, deleteUnused, diamondAt, displayColorHex, drawMegatile, editLocation, encodeTrg, escapeStringText, extraKind, findInScenario, fingerprintTrigger, flatTerrain, forceName, formatBytes, formatOf, formatStringTable, formatTrigger, formatTriggers, groupBuildable, hasIsom, idealStarts, internString, isExpansion, isPreserved, isRemasteredRevision, isResource, isomTables, issueCounts, keptExtras, loadMap, loadTileset, locationCapacity, locationName, looksLikeMpq, makeUnit, mapStatistics, mapVersionOf, markDirty, megatileForTile, megatileHeight, mirroredOwner, moveLocations, moveUnits, newAction, newCondition, newTrigger, nextSerial, openMapBytes, packBuiltMap, paintIsom, paintIsomDiamonds, parseChk, parseScenario, parseStringTable, parseTriggers, parseWavHeader, placeDoodad, placeStartLocations, placedLocations, plainText, planSave, playableCount, playerColorHex, playerRaceLabel, playerTypeLabel, readArchive, readBriefing, readBuildManifest, readExtras, readForceSettings, readMembers, readPlayerSettings, readStrings, readSwitchNames, readTechSettings, readTriggerFile, readTriggers, readUnitSettings, readUpgradeSettings, removeLocations, removeUnits, requiredSections, resizeScenario, resolveIcon, restoreBuiltMap, runsOf, sameTriggers, scenarioDescription, scenarioName, serializeChk, serializeScenario, setExtendedStrings, setMapVersion, setPreserved, setScenarioDescription, setScenarioName, setTextEncoding, soundList, statisticsText, stringCapacity, stringUsages, summarizeTrigger, symmetryImages, techName, techRestrictionSections, techSettingsSections, textCode, tilesetIndex, triggerComment, triggerFormatOf, triggerNames, triggerUsage, triggersFromText, triggersToText, unescapeStringText, unitAt, unitCustomName, unitGeometry, unitName, unitSettingsSections, unitsInBox, unusedStrings, updateUnits, upgradeName, upgradeRestrictionSections, upgradeSettingsSections, usedLocations, validateManifest, validateScenario, wavDuration, wavFormatLabel, writeArchiveBytes, writeMapBytes };