@adatechnology/game-terrain 0.1.2 → 0.2.1

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.d.ts CHANGED
@@ -29,6 +29,24 @@ interface TerrainMaterial {
29
29
  readonly color: readonly [number, number, number];
30
30
  /** Surface pattern a renderer draws while the stratum is intact (`TERRAIN_PATTERNS`). */
31
31
  readonly pattern?: TerrainPattern;
32
+ /** A rigid surface cracks around a hard blow instead of only losing a bowl: lines that run out from the point (concrete, asphalt, tile, stone). */
33
+ readonly crack?: TerrainCrackResponse;
34
+ /** A rigid layer a contact charge breaks right through once it has enough for the whole thickness (the scabbing of a slab): `explosive` only. */
35
+ readonly breach?: TerrainBreachResponse;
36
+ }
37
+ interface TerrainCrackResponse {
38
+ /** Metres the longest line runs for a blow of 1 MJ; it grows with the cube root of the energy. */
39
+ readonly reach: number;
40
+ /** Metres wide the lines open at the point for 1 MJ, also by the cube root, never under a hairline. */
41
+ readonly width: number;
42
+ /** A blow under this many joules leaves no crack (a punch on a slab). */
43
+ readonly thresholdJoules: number;
44
+ }
45
+ interface TerrainBreachResponse {
46
+ /** Joules over the cube of the layer's thickness (J/m³) that break the whole layer through: for reinforced concrete about 1 kg of TNT for 12 cm. */
47
+ readonly joulesPerCubedThickness: number;
48
+ /** Radius of the breach over the thickness at that energy; it grows with the cube root of the excess. */
49
+ readonly radiusOverThickness: number;
32
50
  }
33
51
  interface TerrainFireResponse {
34
52
  /** How black it gets, 0..1: concrete only soots, wood and turf char through. */
@@ -79,6 +97,8 @@ interface TerrainBudget {
79
97
  readonly maxSlideCellsPerFrame: number;
80
98
  /** Cells on fire at once. */
81
99
  readonly maxBurningCells: number;
100
+ /** Stars of cracks kept; past it the oldest goes. */
101
+ readonly maxCracks: number;
82
102
  }
83
103
  interface TerrainOptions {
84
104
  /** World rectangle `[x0, z0, x1, z1]` in metres. */
@@ -128,6 +148,21 @@ interface TerrainDebris {
128
148
  /** Order of creation: the oldest is the one recycled. */
129
149
  readonly born: number;
130
150
  }
151
+ /** A star of cracks on a rigid surface. The lines themselves come from `crackLines`, drawn from the seed, so a snapshot keeps only this. */
152
+ interface TerrainCrack {
153
+ readonly id: number;
154
+ readonly x: number;
155
+ readonly z: number;
156
+ /** Metres the longest line runs. */
157
+ reach: number;
158
+ /** Metres wide the lines are at the point. */
159
+ width: number;
160
+ rays: number;
161
+ readonly seed: number;
162
+ readonly material: string;
163
+ /** Order of creation: the oldest is the one recycled. */
164
+ readonly born: number;
165
+ }
131
166
  /** What a blow did. */
132
167
  interface TerrainBlowResult {
133
168
  readonly point: readonly [number, number, number];
@@ -152,6 +187,10 @@ interface TerrainBlowResult {
152
187
  readonly collapsed: boolean;
153
188
  /** Left a fine mark (`true`) or dug the height field (`false`). */
154
189
  readonly fine: boolean;
190
+ /** The cracks it opened or lengthened around the point, if the surface is rigid. */
191
+ readonly crack?: TerrainCrack;
192
+ /** A contact charge broke the rigid layer right through (`TerrainMaterial.breach`). */
193
+ readonly breached?: boolean;
155
194
  }
156
195
  interface TerrainRegion {
157
196
  readonly x: number;
@@ -246,10 +285,15 @@ interface Terrain {
246
285
  onDeform(listener: (region: TerrainRegion) => void): () => void;
247
286
  /** Moves the pieces, the sliding ground and the fire. */
248
287
  update(dt: number): void;
288
+ /** Chunks waiting to be redrawn; every chunk at once means the floor was just laid anew (a layout, a reset). */
289
+ readonly dirtyChunkCount: number;
249
290
  /** Takes up to the budget's chunks that changed since the last call. */
250
291
  drainDirtyChunks(max?: number): TerrainChunk[];
251
292
  chunk(index: number): TerrainChunk;
252
293
  marks(): readonly TerrainMark[];
294
+ cracks(): readonly TerrainCrack[];
295
+ /** Changes whenever a crack is added or grows, so a renderer redraws only then. */
296
+ readonly cracksVersion: number;
253
297
  debris(): readonly TerrainDebris[];
254
298
  /** Cells on fire now, as world points. */
255
299
  burningPoints(): readonly (readonly [number, number])[];
@@ -268,6 +312,7 @@ interface TerrainSnapshot {
268
312
  readonly scorch: readonly (readonly [number, number])[];
269
313
  readonly barBend?: readonly (readonly [number, number])[];
270
314
  readonly marks: readonly TerrainMark[];
315
+ readonly cracks?: readonly TerrainCrack[];
271
316
  }
272
317
 
273
318
  declare const DEFAULT_TERRAIN_BUDGET: TerrainBudget;
@@ -292,4 +337,21 @@ declare const DEFAULT_BAR_YIELD_JOULES = 2400000;
292
337
  /** The profile of a floor with nothing else said: a plain slab. */
293
338
  declare const DEFAULT_PROFILE = "concrete_slab";
294
339
 
295
- export { DEFAULT_BAR_YIELD_JOULES, DEFAULT_PROFILE, DEFAULT_TERRAIN_BUDGET, TERRAIN_MATERIALS, TERRAIN_PATTERNS, TERRAIN_PROFILES, type Terrain, type TerrainBlow, type TerrainBlowResponse, type TerrainBlowResult, type TerrainBudget, type TerrainChunk, type TerrainColumn, type TerrainDebris, type TerrainDebrisKind, type TerrainFireResponse, type TerrainImplOptions, type TerrainMark, type TerrainMaterial, type TerrainOptions, type TerrainPattern, type TerrainProfile, type TerrainRegion, type TerrainSnapshot, type TerrainStats, type TerrainStratum, createTerrain, createTerrainImpl };
340
+ /** Energy the reach and width of a material's cracks are given for (`TerrainCrackResponse`). */
341
+ declare const CRACK_REFERENCE_JOULES = 1000000;
342
+ /** One piece of a crack line on the ground plane, with the width at each end. */
343
+ interface CrackSegment {
344
+ readonly x0: number;
345
+ readonly z0: number;
346
+ readonly x1: number;
347
+ readonly z1: number;
348
+ readonly w0: number;
349
+ readonly w1: number;
350
+ }
351
+ /**
352
+ * The lines of a star, from its seed: rays that wander a little as they run out and thin towards their tips, with a branch now and then. The same crack always draws the same
353
+ * lines, so only the crack travels in a snapshot or over the network.
354
+ */
355
+ declare function crackLines(crack: TerrainCrack): CrackSegment[];
356
+
357
+ export { CRACK_REFERENCE_JOULES, type CrackSegment, DEFAULT_BAR_YIELD_JOULES, DEFAULT_PROFILE, DEFAULT_TERRAIN_BUDGET, TERRAIN_MATERIALS, TERRAIN_PATTERNS, TERRAIN_PROFILES, type Terrain, type TerrainBlow, type TerrainBlowResponse, type TerrainBlowResult, type TerrainBreachResponse, type TerrainBudget, type TerrainChunk, type TerrainColumn, type TerrainCrack, type TerrainCrackResponse, type TerrainDebris, type TerrainDebrisKind, type TerrainFireResponse, type TerrainImplOptions, type TerrainMark, type TerrainMaterial, type TerrainOptions, type TerrainPattern, type TerrainProfile, type TerrainRegion, type TerrainSnapshot, type TerrainStats, type TerrainStratum, crackLines, createTerrain, createTerrainImpl };
@@ -21,12 +21,14 @@ var GameTerrain = (() => {
21
21
  // src/index.ts
22
22
  var index_exports = {};
23
23
  __export(index_exports, {
24
+ CRACK_REFERENCE_JOULES: () => CRACK_REFERENCE_JOULES,
24
25
  DEFAULT_BAR_YIELD_JOULES: () => DEFAULT_BAR_YIELD_JOULES,
25
26
  DEFAULT_PROFILE: () => DEFAULT_PROFILE,
26
27
  DEFAULT_TERRAIN_BUDGET: () => DEFAULT_TERRAIN_BUDGET,
27
28
  TERRAIN_MATERIALS: () => TERRAIN_MATERIALS,
28
29
  TERRAIN_PATTERNS: () => TERRAIN_PATTERNS,
29
30
  TERRAIN_PROFILES: () => TERRAIN_PROFILES,
31
+ crackLines: () => crackLines,
30
32
  createTerrain: () => createTerrain,
31
33
  createTerrainImpl: () => createTerrainImpl
32
34
  });
@@ -98,6 +100,7 @@ var GameTerrain = (() => {
98
100
  debris: "chips",
99
101
  color: [0.05, 0.05, 0.055],
100
102
  pattern: "asphalt",
103
+ crack: { reach: 0.6, width: 8e-3, thresholdJoules: 800 },
101
104
  hits: {
102
105
  ballistic: { specificEnergy: 3e7, aspect: 0.2, minRadius: 0.03 },
103
106
  blunt: { specificEnergy: 1e8, aspect: 0.1, thresholdJoules: 400 },
@@ -111,6 +114,8 @@ var GameTerrain = (() => {
111
114
  debris: "chips",
112
115
  color: [0.33, 0.33, 0.31],
113
116
  pattern: "concrete",
117
+ crack: { reach: 1, width: 6e-3, thresholdJoules: 300 },
118
+ breach: { joulesPerCubedThickness: 24e8, radiusOverThickness: 1.5 },
114
119
  hits: {
115
120
  ballistic: { specificEnergy: 15e7, aspect: 0.14, minRadius: 0.018 },
116
121
  blunt: { specificEnergy: 3e8, aspect: 0.08, thresholdJoules: 800 },
@@ -137,6 +142,7 @@ var GameTerrain = (() => {
137
142
  debris: "shards",
138
143
  color: [0.72, 0.7, 0.66],
139
144
  pattern: "tile",
145
+ crack: { reach: 0.5, width: 2e-3, thresholdJoules: 40 },
140
146
  hits: {
141
147
  ballistic: { specificEnergy: 8e6, aspect: 0.1, minRadius: 0.05 },
142
148
  blunt: { specificEnergy: 1e7, aspect: 0.08, thresholdJoules: 80, minRadius: 0.06 },
@@ -163,6 +169,7 @@ var GameTerrain = (() => {
163
169
  debris: "chips",
164
170
  color: [0.23, 0.22, 0.2],
165
171
  pattern: "stone",
172
+ crack: { reach: 0.5, width: 4e-3, thresholdJoules: 1e3 },
166
173
  hits: {
167
174
  ballistic: { specificEnergy: 25e7, aspect: 0.12, minRadius: 0.015 },
168
175
  blunt: { specificEnergy: 5e8, aspect: 0.08, thresholdJoules: 1500 },
@@ -186,6 +193,95 @@ var GameTerrain = (() => {
186
193
  var DEFAULT_BAR_YIELD_JOULES = 24e5;
187
194
  var DEFAULT_PROFILE = "concrete_slab";
188
195
 
196
+ // src/random.ts
197
+ function createRandom(seed) {
198
+ let state = seed | 0;
199
+ return () => {
200
+ state = state + 1831565813 | 0;
201
+ let mixed = Math.imul(state ^ state >>> 15, 1 | state);
202
+ mixed = mixed + Math.imul(mixed ^ mixed >>> 7, 61 | mixed) ^ mixed;
203
+ return ((mixed ^ mixed >>> 14) >>> 0) / 4294967296;
204
+ };
205
+ }
206
+
207
+ // src/cracks.ts
208
+ var CRACK_REFERENCE_JOULES = 1e6;
209
+ var MERGE_SHARE = 0.35;
210
+ var HAIRLINE = 15e-4;
211
+ var MIN_RAYS = 4;
212
+ var MAX_RAYS = 11;
213
+ var SEGMENTS = 4;
214
+ var BRANCH_CHANCE = 0.45;
215
+ function createCrackStore() {
216
+ const list = [];
217
+ let version = 0;
218
+ let nextId = 1;
219
+ let born = 0;
220
+ return {
221
+ list,
222
+ get version() {
223
+ return version;
224
+ },
225
+ add(spec, max) {
226
+ version++;
227
+ const near = list.find((crack2) => Math.hypot(crack2.x - spec.x, crack2.z - spec.z) < crack2.reach * MERGE_SHARE);
228
+ if (near) {
229
+ near.reach = Math.max(near.reach, spec.reach) + Math.min(near.reach, spec.reach) * 0.25;
230
+ near.width = Math.max(near.width, spec.width) * 1.1;
231
+ near.rays = Math.min(MAX_RAYS, near.rays + 1);
232
+ return near;
233
+ }
234
+ if (list.length >= max) list.shift();
235
+ const rays = MIN_RAYS + Math.floor(createRandom(spec.seed)() * (MAX_RAYS - MIN_RAYS - 2));
236
+ const crack = { id: nextId++, x: spec.x, z: spec.z, reach: spec.reach, width: Math.max(HAIRLINE, spec.width), rays, seed: spec.seed, material: spec.material, born: born++ };
237
+ list.push(crack);
238
+ return crack;
239
+ },
240
+ clear() {
241
+ list.length = 0;
242
+ version++;
243
+ },
244
+ load(cracks) {
245
+ list.length = 0;
246
+ for (const crack of cracks) {
247
+ list.push({ ...crack });
248
+ nextId = Math.max(nextId, crack.id + 1);
249
+ born = Math.max(born, crack.born + 1);
250
+ }
251
+ version++;
252
+ }
253
+ };
254
+ }
255
+ function crackLines(crack) {
256
+ const random = createRandom(crack.seed);
257
+ const segments = [];
258
+ const widthAt = (distance) => Math.max(HAIRLINE, crack.width * (1 - distance / crack.reach));
259
+ for (let ray = 0; ray < crack.rays; ray++) {
260
+ let angle = ray / crack.rays * Math.PI * 2 + (random() - 0.5) * 0.6;
261
+ const length = crack.reach * (0.45 + 0.55 * random());
262
+ let x = crack.x;
263
+ let z = crack.z;
264
+ let run = 0;
265
+ for (let segment = 0; segment < SEGMENTS; segment++) {
266
+ const step = length / SEGMENTS * (0.75 + 0.5 * random());
267
+ angle += (random() - 0.5) * 0.5;
268
+ const nx = x + Math.cos(angle) * step;
269
+ const nz = z + Math.sin(angle) * step;
270
+ segments.push({ x0: x, z0: z, x1: nx, z1: nz, w0: widthAt(run), w1: widthAt(run + step) });
271
+ if (segment > 0 && random() < BRANCH_CHANCE) {
272
+ const side = angle + (random() < 0.5 ? -1 : 1) * (0.45 + random() * 0.5);
273
+ const branch = step * (0.5 + 0.6 * random());
274
+ const w = widthAt(run + step) * 0.6;
275
+ segments.push({ x0: nx, z0: nz, x1: nx + Math.cos(side) * branch, z1: nz + Math.sin(side) * branch, w0: Math.max(HAIRLINE, w), w1: HAIRLINE });
276
+ }
277
+ run += step;
278
+ x = nx;
279
+ z = nz;
280
+ }
281
+ }
282
+ return segments;
283
+ }
284
+
189
285
  // src/debris.ts
190
286
  var REST_SPEED = 0.6;
191
287
  var RESTITUTION = 0.25;
@@ -367,17 +463,6 @@ var GameTerrain = (() => {
367
463
  };
368
464
  }
369
465
 
370
- // src/random.ts
371
- function createRandom(seed) {
372
- let state = seed | 0;
373
- return () => {
374
- state = state + 1831565813 | 0;
375
- let mixed = Math.imul(state ^ state >>> 15, 1 | state);
376
- mixed = mixed + Math.imul(mixed ^ mixed >>> 7, 61 | mixed) ^ mixed;
377
- return ((mixed ^ mixed >>> 14) >>> 0) / 4294967296;
378
- };
379
- }
380
-
381
466
  // src/terrain.ts
382
467
  var DEFAULT_TERRAIN_BUDGET = {
383
468
  markAreaSize: 2,
@@ -387,7 +472,8 @@ var GameTerrain = (() => {
387
472
  maxDebris: 400,
388
473
  maxDebrisPerBlow: 36,
389
474
  maxSlideCellsPerFrame: 2500,
390
- maxBurningCells: 300
475
+ maxBurningCells: 300,
476
+ maxCracks: 120
391
477
  };
392
478
  var GRAVITY = 9.81;
393
479
  var FINE_CELLS = 1.5;
@@ -430,6 +516,16 @@ var GameTerrain = (() => {
430
516
  const stratum = profile.strata[index];
431
517
  return { index, stratum, top: top - stratum.thickness };
432
518
  }
519
+ function stratumMaterialAtDepth(profile, depth) {
520
+ const strata = profile.strata;
521
+ let top = 0;
522
+ for (let index = 0; index < strata.length; index++) {
523
+ const stratum = strata[index];
524
+ if (depth < top + stratum.thickness - 1e-6) return stratum.material;
525
+ top += stratum.thickness;
526
+ }
527
+ return strata[strata.length - 1].material;
528
+ }
433
529
  var totalThickness = (profile) => profile.strata.reduce((sum, stratum) => sum + stratum.thickness, 0);
434
530
  function createTerrain(options) {
435
531
  const [x0, z0, x1, z1] = options.bounds;
@@ -464,6 +560,7 @@ var GameTerrain = (() => {
464
560
  const mixed = new Uint8Array(chunksX * chunksZ);
465
561
  const dirty = /* @__PURE__ */ new Set();
466
562
  const marks = createMarkStore(budget);
563
+ const cracks = createCrackStore();
467
564
  const debrisStore = createDebrisStore(() => budget.maxDebris);
468
565
  const sliding = /* @__PURE__ */ new Set();
469
566
  const burning = /* @__PURE__ */ new Map();
@@ -544,7 +641,7 @@ var GameTerrain = (() => {
544
641
  };
545
642
  function vertexMaterial(column, row) {
546
643
  const index = row * stride + column;
547
- return materials.get(stratumAtDepth(profileList[profileIndex[index]], dug[index]).stratum.material);
644
+ return materials.get(stratumMaterialAtDepth(profileList[profileIndex[index]], dug[index]));
548
645
  }
549
646
  function columnAt(x, z) {
550
647
  const { index } = vertexOf(x, z);
@@ -640,6 +737,7 @@ var GameTerrain = (() => {
640
737
  let depth = start.depth;
641
738
  let radius = 0;
642
739
  let carved = 0;
740
+ let breached = false;
643
741
  const firstMaterial = materials.get(start.material);
644
742
  if (start.loose <= 0) {
645
743
  for (; ; ) {
@@ -651,6 +749,19 @@ var GameTerrain = (() => {
651
749
  const response = material.hits[blow];
652
750
  if (!response || energy < (response.thresholdJoules ?? 0)) break;
653
751
  const bars = layer.stratum.reinforcement;
752
+ const breach = blow === "explosive" ? material.breach : void 0;
753
+ const breachJoules = breach ? breach.joulesPerCubedThickness * layer.stratum.thickness ** 3 : Infinity;
754
+ if (breach && depth <= layer.top + 1e-6 && energy >= breachJoules) {
755
+ const takenRadius2 = layer.stratum.thickness * breach.radiusOverThickness * Math.cbrt(energy / breachJoules);
756
+ const takenVolume2 = Math.PI * takenRadius2 * takenRadius2 * room / 2;
757
+ energy -= breachJoules;
758
+ depth += room;
759
+ carved += room;
760
+ breached = true;
761
+ radius = Math.max(radius, takenRadius2);
762
+ removed.push({ material: material.id, volume: takenVolume2 });
763
+ continue;
764
+ }
654
765
  const pastCover = bars !== void 0 && depth - layer.top >= bars.cover - 1e-6;
655
766
  const specificEnergy = response.specificEnergy * (pastCover ? bars.resistance : 1);
656
767
  const limit = bars && !pastCover ? Math.min(room, layer.top + bars.cover - depth) : room;
@@ -678,8 +789,10 @@ var GameTerrain = (() => {
678
789
  removed.push({ material: firstMaterial.id, volume });
679
790
  }
680
791
  }
681
- const collapsed = loadBars(blow, spec.energy, x, z, profile);
682
- if (radius <= 0) return { point, radius: 0, depth: 0, totalDepth: columnAt(x, z).depth, removed: [], exposed: start.material, atLimit: start.remaining <= 1e-6, rebarExposed: rebarShowing(profile, start.depth), collapsed, fine: true };
792
+ let collapsed = loadBars(blow, spec.energy, x, z, profile);
793
+ const crack = crackAround(blow, spec.energy, x, z, start.loose > 0 ? void 0 : firstMaterial);
794
+ const extra = { ...crack ? { crack } : {}, ...breached ? { breached } : {} };
795
+ if (radius <= 0) return { point, radius: 0, depth: 0, totalDepth: columnAt(x, z).depth, removed: [], exposed: start.material, atLimit: start.remaining <= 1e-6, rebarExposed: rebarShowing(profile, start.depth), collapsed, fine: true, ...extra };
683
796
  if (firstMaterial.reposeDegrees === void 0 && start.loose <= 0) radius *= 1 + RIGID_WIDENING * (start.depth / maxDepthOfProfile(profile));
684
797
  const volumeTotal = removed.reduce((sum, entry) => sum + entry.volume, 0);
685
798
  const fine = radius < cellSize * FINE_CELLS;
@@ -697,8 +810,16 @@ var GameTerrain = (() => {
697
810
  throwPieces({ x, y: point[1], z, volume: thrown, material, energy: spec.energy * (entry.volume / volumeTotal), direction: spec.direction, quota: share, bowlRadius: radius, blow });
698
811
  quota -= share;
699
812
  }
813
+ if (breached) collapsed = loadBars(blow, spec.energy, x, z, profile) || collapsed;
700
814
  const after = columnAt(x, z);
701
- return { point, radius, depth: carved, totalDepth: after.depth, removed, exposed: after.material, atLimit: after.remaining <= 1e-4, rebarExposed: rebarShowing(profile, after.depth), collapsed, fine };
815
+ return { point, radius, depth: carved, totalDepth: after.depth, removed, exposed: after.material, atLimit: after.remaining <= 1e-4, rebarExposed: rebarShowing(profile, after.depth), collapsed, fine, ...extra };
816
+ }
817
+ function crackAround(blow, energy, x, z, material) {
818
+ const response = material?.crack;
819
+ if (!material || !response || energy < response.thresholdJoules) return void 0;
820
+ if (blow === "slash") return void 0;
821
+ const scale = Math.cbrt(energy / CRACK_REFERENCE_JOULES);
822
+ return cracks.add({ x, z, reach: response.reach * scale, width: response.width * scale, material: material.id, seed: Math.floor(random() * 2 ** 31) }, budget.maxCracks);
702
823
  }
703
824
  function loadBars(blow, energy, x, z, profile) {
704
825
  const bars = profile.strata.find((stratum) => stratum.reinforcement);
@@ -939,6 +1060,7 @@ var GameTerrain = (() => {
939
1060
  barBend.fill(0);
940
1061
  touched.fill(0);
941
1062
  marks.clear();
1063
+ cracks.clear();
942
1064
  debrisStore.clear();
943
1065
  sliding.clear();
944
1066
  burning.clear();
@@ -990,6 +1112,9 @@ var GameTerrain = (() => {
990
1112
  updateSlides();
991
1113
  updateFire(dt);
992
1114
  },
1115
+ get dirtyChunkCount() {
1116
+ return dirty.size;
1117
+ },
993
1118
  drainDirtyChunks(max = budget.maxDirtyChunksPerFrame) {
994
1119
  const taken = [];
995
1120
  for (const index of dirty) {
@@ -1001,6 +1126,10 @@ var GameTerrain = (() => {
1001
1126
  },
1002
1127
  chunk,
1003
1128
  marks: () => marks.list,
1129
+ cracks: () => cracks.list,
1130
+ get cracksVersion() {
1131
+ return cracks.version;
1132
+ },
1004
1133
  debris: () => debrisStore.list,
1005
1134
  burningPoints: () => [...burning.keys()].map((key) => {
1006
1135
  const cellRow = Math.floor(key / 65536);
@@ -1013,7 +1142,7 @@ var GameTerrain = (() => {
1013
1142
  stats: () => ({ marks: marks.list.length, debris: debrisStore.list.length, debrisMoving: debrisStore.list.filter((piece) => !piece.atRest).length, dirtyChunks: dirty.size, burning: burning.size }),
1014
1143
  reset,
1015
1144
  serialize() {
1016
- return { layout: currentLayout, dug: sparse(dug), loose: sparse(loose), scorch: sparse(scorch), barBend: sparse(barBend), marks: marks.list.map((mark) => ({ ...mark })) };
1145
+ return { layout: currentLayout, dug: sparse(dug), loose: sparse(loose), scorch: sparse(scorch), barBend: sparse(barBend), marks: marks.list.map((mark) => ({ ...mark })), cracks: cracks.list.map((crack) => ({ ...crack })) };
1017
1146
  },
1018
1147
  load(snapshot) {
1019
1148
  currentLayout = snapshot.layout;
@@ -1023,6 +1152,7 @@ var GameTerrain = (() => {
1023
1152
  fillSparse(scorch, snapshot.scorch);
1024
1153
  fillSparse(barBend, snapshot.barBend ?? []);
1025
1154
  marks.load(snapshot.marks);
1155
+ cracks.load(snapshot.cracks ?? []);
1026
1156
  for (let chunkIndex = 0; chunkIndex < touched.length; chunkIndex++) markChunk(chunkIndex);
1027
1157
  }
1028
1158
  };
@@ -1032,24 +1162,49 @@ var GameTerrain = (() => {
1032
1162
  var PART_ID = "ground";
1033
1163
  var PART_DEPTH = 3;
1034
1164
  var RAY_BACKOFF = 1;
1165
+ var GROUND_HP = 1e12;
1035
1166
  function createTerrainImpl(terrain, options) {
1036
1167
  const { id } = options;
1037
1168
  const [x0, z0, x1, z1] = terrain.bounds;
1038
- const spec = () => ({
1169
+ const centerColumn = Math.max(0, Math.min(terrain.columns, Math.round((x1 - x0) / 2 / terrain.cellSize)));
1170
+ const centerRow = Math.max(0, Math.min(terrain.rows, Math.round((z1 - z0) / 2 / terrain.cellSize)));
1171
+ const centerMaterial = () => terrain.vertexMaterial(centerColumn, centerRow).id;
1172
+ const buildSpec = (material) => ({
1039
1173
  name: options.name ?? "Ground",
1040
1174
  parts: [
1041
1175
  {
1042
1176
  id: PART_ID,
1043
- material: terrain.columnAt((x0 + x1) / 2, (z0 + z1) / 2).material,
1177
+ material,
1044
1178
  shape: { kind: "box", size: [x1 - x0, PART_DEPTH, z1 - z0] },
1045
1179
  position: [(x0 + x1) / 2, -PART_DEPTH / 2, (z0 + z1) / 2],
1046
- hp: 1e12,
1180
+ hp: GROUND_HP,
1047
1181
  anchored: true,
1048
1182
  tags: ["terrain"]
1049
1183
  }
1050
1184
  ],
1051
1185
  joints: []
1052
1186
  });
1187
+ let cachedSpec;
1188
+ const spec = () => {
1189
+ const material = centerMaterial();
1190
+ if (cachedSpec?.parts[0]?.material !== material) cachedSpec = buildSpec(material);
1191
+ return cachedSpec;
1192
+ };
1193
+ const buildState = (material) => ({
1194
+ id,
1195
+ position: [0, 0, 0],
1196
+ rotation: [0, 0, 0, 1],
1197
+ parts: [{ id: PART_ID, material, status: "intact", hp: GROUND_HP, maxHp: GROUND_HP, mass: 0, temperature: 0, burning: false, fuel: 0, char: 0, melt: 0, dents: [], holes: [], cracks: [], group: 0 }],
1198
+ joints: [],
1199
+ groups: [[PART_ID]],
1200
+ destroyed: false
1201
+ });
1202
+ let cachedState;
1203
+ const state = () => {
1204
+ const material = centerMaterial();
1205
+ if (cachedState?.parts[0]?.material !== material) cachedState = buildState(material);
1206
+ return cachedState;
1207
+ };
1053
1208
  const resolve = (hit) => {
1054
1209
  if (hit.type !== "ballistic" && hit.type !== "blunt" && hit.type !== "slash") return hit;
1055
1210
  if (!hit.direction) return { ...hit, point: [hit.point[0], terrain.heightAt(hit.point[0], hit.point[2]), hit.point[2]] };
@@ -1067,26 +1222,20 @@ var GameTerrain = (() => {
1067
1222
  const result = terrain.applyHit(landed);
1068
1223
  if (!result || result.radius <= 0) return [];
1069
1224
  options.onBlow?.(result, landed);
1070
- return [{ type: "damage", object: id, time: 0, part: PART_ID, amount: 0, hp: 1e12, damageType: hit.type, ...hit.source ? { source: hit.source } : {} }];
1225
+ return [{ type: "damage", object: id, time: 0, part: PART_ID, amount: 0, hp: GROUND_HP, damageType: hit.type, ...hit.source ? { source: hit.source } : {} }];
1071
1226
  },
1072
1227
  update(dt) {
1073
1228
  terrain.update(dt);
1074
1229
  return [];
1075
1230
  },
1076
- state() {
1077
- return {
1078
- id,
1079
- position: [0, 0, 0],
1080
- rotation: [0, 0, 0, 1],
1081
- parts: [],
1082
- joints: [],
1083
- groups: [[PART_ID]],
1084
- destroyed: false
1085
- };
1231
+ state,
1232
+ reset() {
1233
+ terrain.reset();
1086
1234
  },
1087
- reset: () => terrain.reset(),
1088
1235
  serialize: () => terrain.serialize(),
1089
- load: (data) => terrain.load(data)
1236
+ load(data) {
1237
+ terrain.load(data);
1238
+ }
1090
1239
  };
1091
1240
  }
1092
1241