@korial29/tiny-fps 0.2.0 → 0.3.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/server.js CHANGED
@@ -7,10 +7,22 @@ var PLAYER_H = 1.8;
7
7
  var EYE = 1.6;
8
8
  /** Pitch is clamped to ±MAX_PITCH radians, just short of straight up or down. */
9
9
  var MAX_PITCH = 1.55;
10
+ /** A floor at most this much higher is walked onto; a higher one needs a jump. */
11
+ var STEP_H = .5;
10
12
  /** Speed factor while the trigger is held. */
11
13
  var FIRE_SLOW = .5;
12
14
  /** Largest angle, in radians, between a shot and the view direction. */
13
15
  var SPREAD = .02;
16
+ var WALKER_R = .4;
17
+ var WALKER_H = 1.8;
18
+ var WALKER_SPEED = 2.5;
19
+ var FLYER_R = .45;
20
+ var FLYER_H = .9;
21
+ /** A flyer's underside floats this high above the floor below it, ceilings allowing. */
22
+ var FLYER_HOVER = 1.2;
23
+ var FLYER_SPEED = 3.5;
24
+ var SIGHT_COS = Math.cos(Math.PI / 6);
25
+ var BULLET_R = .15;
14
26
  var RULES = { maxPlayers: 16 };
15
27
  // src/shared/level.ts
16
28
  /** Joins every edge a→b with the sector that has b→a, if any: that edge is a portal. */
@@ -40,6 +52,26 @@ var inside = ({ pts }, x, z) => pts.every(([ax, az], i) => {
40
52
  });
41
53
  /** Index of the first sector holding (x, z), -1 outside the map. */
42
54
  var sectorAt = ({ map }, x, z) => map.sectors.findIndex((s) => inside(s, x, z));
55
+ /**
56
+ * Whether a wall, a step or a ceiling hides b from a (both inside the map). Between two edge
57
+ * crossings the segment stays in one sector, and each crossing is checked against the opening of
58
+ * its portal, so floors and ceilings need no test of their own.
59
+ */
60
+ var blocked = ({ map, edges }, [ax, ay, az], [bx, by, bz]) => {
61
+ const [dx, dz] = [bx - ax, bz - az];
62
+ return edges.some((e) => {
63
+ const [ex, ez] = [e.bx - e.ax, e.bz - e.az];
64
+ const den = dx * ez - dz * ex;
65
+ if (!den) return false;
66
+ const t = ((e.ax - ax) * ez - (e.az - az) * ex) / den;
67
+ const u = ((e.ax - ax) * dz - (e.az - az) * dx) / den;
68
+ if (t <= 0 || t >= 1 || u < 0 || u > 1) return false;
69
+ if (e.back < 0) return true;
70
+ const [f, k] = [map.sectors[e.front], map.sectors[e.back]];
71
+ const y = ay + t * (by - ay);
72
+ return y < Math.max(f.floor, k.floor) || y > Math.min(f.ceil, k.ceil);
73
+ });
74
+ };
43
75
  // src/shared/types.ts
44
76
  /** Bits of Input.keys. Keys are read by KeyboardEvent.code, so WASD is ZQSD on AZERTY. */
45
77
  var KEY = {
@@ -51,6 +83,24 @@ var KEY = {
51
83
  /** Left mouse button: the chaingun fires every FIRE_EVERY steps while held. */
52
84
  FIRE: 32
53
85
  };
86
+ /** Monster kinds. */
87
+ var MONSTER = {
88
+ /** Walks the floors like a player, shoots bullets from afar and hits up close. */
89
+ WALKER: 0,
90
+ /** Hovers above the floor, flies over steps and pits, hits up close. */
91
+ FLYER: 1
92
+ };
93
+ /** What a GameEvent reports. */
94
+ var EVENT = {
95
+ /** Monster `id` died, (x, y, z) the middle of its body: gibs and an explosion. */
96
+ DIE: 0,
97
+ /** Player `id` was hit by a bullet or a blow at (x, y, z). Harmless until health (step 4). */
98
+ HURT: 1,
99
+ /** A bullet burst on the level at (x, y, z); `id` is the bullet. */
100
+ BOOM: 2,
101
+ /** Monster `id` swung at its target from (x, y, z), hit or miss. */
102
+ SWING: 3
103
+ };
54
104
  /** Procedural textures, generated by the client. A sector names one per surface. */
55
105
  var TEX = {
56
106
  BRICK: 0,
@@ -192,10 +242,60 @@ var HALL = {
192
242
  14,
193
243
  Math.PI * 1.5
194
244
  ]
245
+ ],
246
+ monsters: [
247
+ [
248
+ 24,
249
+ 2,
250
+ Math.PI * 1.2,
251
+ MONSTER.WALKER
252
+ ],
253
+ [
254
+ 33,
255
+ 3,
256
+ Math.PI * .75,
257
+ MONSTER.WALKER
258
+ ],
259
+ [
260
+ 33,
261
+ 8,
262
+ Math.PI * .5,
263
+ MONSTER.WALKER
264
+ ],
265
+ [
266
+ 24,
267
+ 14,
268
+ Math.PI * 1.8,
269
+ MONSTER.WALKER
270
+ ],
271
+ [
272
+ 30,
273
+ 23,
274
+ 0,
275
+ MONSTER.WALKER
276
+ ],
277
+ [
278
+ 28,
279
+ 8,
280
+ 0,
281
+ MONSTER.FLYER
282
+ ],
283
+ [
284
+ 34,
285
+ 13,
286
+ Math.PI * .3,
287
+ MONSTER.FLYER
288
+ ],
289
+ [
290
+ 34,
291
+ 22,
292
+ Math.PI * .5,
293
+ MONSTER.FLYER
294
+ ]
195
295
  ]
196
296
  };
197
297
  // src/shared/physics.ts
198
- var DT = 1 / 60;
298
+ var DT$1 = 1 / 60;
199
299
  var TAU = Math.PI * 2;
200
300
  /** Overlaps smaller than this are rounding noise, not contact. */
201
301
  var EPS = 1e-6;
@@ -212,17 +312,17 @@ var forward = (yaw) => [-Math.sin(yaw), -Math.cos(yaw)];
212
312
  var f32 = Math.fround;
213
313
  var clamp = (v, lo, hi) => Math.min(Math.max(v, lo), hi);
214
314
  /**
215
- * Whether the edge stops a player whose feet are at y: a solid wall, a floor on the far side more
216
- * than STEP_H above the feet, or an opening (the lower ceiling minus the higher floor) too short
217
- * for the body or under the head. SKIN keeps rounding from flipping the answer
315
+ * Whether the edge stops a body of height h whose feet are at y: a solid wall, a floor on the far
316
+ * side more than `step` above the feet, or an opening (the lower ceiling minus the higher floor)
317
+ * too short for the body or under the head. SKIN keeps rounding from flipping the answer
218
318
  * for a player resting on a step or against a ceiling.
219
319
  */
220
- var shut = ({ map }, e, y) => {
320
+ var shut = ({ map }, e, y, h, step) => {
221
321
  if (e.back < 0) return true;
222
322
  const f = map.sectors[e.front];
223
323
  const k = map.sectors[e.back];
224
324
  const top = Math.min(f.ceil, k.ceil);
225
- return k.floor > y + .5 + SKIN || top - Math.max(f.floor, k.floor) < 1.8 - SKIN || top < y + 1.8 - SKIN;
325
+ return k.floor > y + step + SKIN || top - Math.max(f.floor, k.floor) < h - SKIN || top < y + h - SKIN;
226
326
  };
227
327
  /**
228
328
  * Pushes the player out of every shut edge it overlaps, deepest first (up to 4 passes: two walls
@@ -236,8 +336,8 @@ var shut = ({ map }, e, y) => {
236
336
  * Tunnelling is impossible: a step is RUN_SPEED / TICK_HZ = 0.1 m and the axis ends each step at
237
337
  * least PLAYER_R = 0.4 m from every shut edge it started beside, so it cannot cross one in 0.1 m.
238
338
  */
239
- var push = (p, lvl) => {
240
- const reach = (PLAYER_R - EPS) ** 2;
339
+ var push = (p, lvl, r, h, step) => {
340
+ const reach = (r - EPS) ** 2;
241
341
  for (let pass = 0; pass < 4; pass++) {
242
342
  let best = 0;
243
343
  let px = 0;
@@ -254,8 +354,8 @@ var push = (p, lvl) => {
254
354
  const d2 = dx * dx + dz * dz;
255
355
  if (d2 >= reach) continue;
256
356
  const d = Math.sqrt(d2);
257
- if (.4 - d <= best || !shut(lvl, e, p.y)) continue;
258
- best = PLAYER_R - d;
357
+ if (r - d <= best || !shut(lvl, e, p.y, h, step)) continue;
358
+ best = r - d;
259
359
  const n = d || Math.hypot(ex, ez);
260
360
  px = (d ? dx : -ez) / n * best;
261
361
  pz = (d ? dz : ex) / n * best;
@@ -270,11 +370,11 @@ var push = (p, lvl) => {
270
370
  * sector holding the axis and of every sector across a portal the circle overlaps and could walk
271
371
  * through (a shut edge is a wall: the circle never counts what lies behind it).
272
372
  */
273
- var span = (lvl, x, z, y) => {
373
+ var span = (lvl, x, z, y, r, h, step) => {
274
374
  const { map, edges } = lvl;
275
375
  const s = Math.max(sectorAt(lvl, x, z), 0);
276
376
  let { floor, ceil } = map.sectors[s];
277
- const reach = (PLAYER_R - EPS) ** 2;
377
+ const reach = (r - EPS) ** 2;
278
378
  for (const e of edges) {
279
379
  if (e.front !== s || e.back < 0) continue;
280
380
  const ex = e.bx - e.ax;
@@ -282,7 +382,7 @@ var span = (lvl, x, z, y) => {
282
382
  const rx = x - e.ax;
283
383
  const rz = z - e.az;
284
384
  const t = clamp((rx * ex + rz * ez) / (ex * ex + ez * ez), 0, 1);
285
- if ((rx - t * ex) ** 2 + (rz - t * ez) ** 2 < reach && !shut(lvl, e, y)) {
385
+ if ((rx - t * ex) ** 2 + (rz - t * ez) ** 2 < reach && !shut(lvl, e, y, h, step)) {
286
386
  const k = map.sectors[e.back];
287
387
  floor = Math.max(floor, k.floor);
288
388
  ceil = Math.min(ceil, k.ceil);
@@ -291,32 +391,20 @@ var span = (lvl, x, z, y) => {
291
391
  return [floor, ceil];
292
392
  };
293
393
  /**
294
- * Applies one input for 1 / TICK_HZ s, in place: yaw and pitch from the input (pitch clamped to
295
- * MAX_PITCH), RUN_SPEED along the held keys (diagonals not faster), a jump from the ground,
296
- * GRAVITY, then collisions of the cylinder (PLAYER_R, PLAYER_H) with the sectors of the level:
297
- * it slides along shut edges (see shut and push), stands on the highest floor under the circle
298
- * (a step up to STEP_H is climbed at once, a higher one needs a jump, a ledge is a fall), and
299
- * bumps its head on the lowest ceiling.
300
- * The chaingun: `cool` counts down one per step, RUN_SPEED is scaled by FIRE_SLOW while KEY.FIRE
301
- * is held, and the step that finds it held with `cool` at 0 re-arms it to FIRE_EVERY and returns
302
- * true: the caller resolves a shot (one every FIRE_EVERY steps, the first at once).
394
+ * Moves the feet by (dx, dz) for 1 / TICK_HZ s, then a jump from the ground, GRAVITY and the
395
+ * collisions of the cylinder (PLAYER_R, PLAYER_H) with the sectors of the level: it slides along
396
+ * shut edges (see shut and push), stands on the highest floor under the circle (a step up to
397
+ * STEP_H is climbed at once, a higher one needs a jump, a ledge is a fall), and bumps its head on
398
+ * the lowest ceiling. Players and walkers share it, in place.
303
399
  */
304
- var move = (p, i, lvl) => {
305
- const fire = (i.keys & KEY.FIRE) !== 0;
306
- p.cool = Math.max(0, p.cool - 1);
307
- p.yaw = norm(i.yaw);
308
- p.pitch = Math.max(-MAX_PITCH, Math.min(MAX_PITCH, i.pitch));
309
- const f = (i.keys & KEY.FORWARD ? 1 : 0) - (i.keys & KEY.BACK ? 1 : 0);
310
- const s = (i.keys & KEY.RIGHT ? 1 : 0) - (i.keys & KEY.LEFT ? 1 : 0);
311
- const d = 6 * DT * (fire ? FIRE_SLOW : 1) / (Math.hypot(f, s) || 1);
312
- const [fx, fz] = forward(p.yaw);
313
- p.x += (fx * f - fz * s) * d;
314
- p.z += (fz * f + fx * s) * d;
315
- push(p, lvl);
316
- const [floor, ceil] = span(lvl, p.x, p.z, p.y);
317
- if (p.ground && i.keys & KEY.JUMP) p.vy = 7;
318
- const vy = p.vy - 20 * DT;
319
- p.y += (p.vy + vy) / 2 * DT;
400
+ var walk = (p, dx, dz, jump, lvl) => {
401
+ p.x += dx;
402
+ p.z += dz;
403
+ push(p, lvl, PLAYER_R, PLAYER_H, STEP_H);
404
+ const [floor, ceil] = span(lvl, p.x, p.z, p.y, PLAYER_R, PLAYER_H, STEP_H);
405
+ if (p.ground && jump) p.vy = 7;
406
+ const vy = p.vy - 20 * DT$1;
407
+ p.y += (p.vy + vy) / 2 * DT$1;
320
408
  p.vy = vy;
321
409
  p.ground = false;
322
410
  if (p.y + 1.8 > ceil) {
@@ -334,6 +422,44 @@ var move = (p, i, lvl) => {
334
422
  p.y = f32(p.y);
335
423
  p.z = f32(p.z);
336
424
  p.vy = f32(p.vy);
425
+ };
426
+ /**
427
+ * Moves a flyer (underside at p.y, radius FLYER_R, height FLYER_H) by (dx, dy, dz): sideways it is
428
+ * stopped by solid walls and by openings too small for it, and it never steps (it flies over
429
+ * steps and pits); then y is held between FLYER_HOVER above the highest floor under it and the
430
+ * lowest ceiling minus FLYER_H, the ceiling winning in a low room. Below the hover height it
431
+ * rises at FLYER_SPEED, so crossing from a pit to a ledge is not a jump; the floor itself is
432
+ * never entered.
433
+ */
434
+ var fly = (p, dx, dy, dz, lvl) => {
435
+ p.x += dx;
436
+ p.z += dz;
437
+ push(p, lvl, FLYER_R, FLYER_H, 0);
438
+ const [floor, ceil] = span(lvl, p.x, p.z, p.y, FLYER_R, FLYER_H, 0);
439
+ const hover = Math.min(floor + FLYER_HOVER, ceil - FLYER_H);
440
+ const low = Math.max(floor, Math.min(hover, p.y + FLYER_SPEED * DT$1));
441
+ p.y = Math.min(Math.max(p.y + dy, low), ceil - FLYER_H);
442
+ p.x = f32(p.x);
443
+ p.y = f32(p.y);
444
+ p.z = f32(p.z);
445
+ };
446
+ /**
447
+ * Applies one input for 1 / TICK_HZ s, in place: yaw and pitch from the input (pitch clamped to
448
+ * MAX_PITCH), RUN_SPEED along the held keys (diagonals not faster), then walk().
449
+ * The chaingun: `cool` counts down one per step, RUN_SPEED is scaled by FIRE_SLOW while KEY.FIRE
450
+ * is held, and the step that finds it held with `cool` at 0 re-arms it to FIRE_EVERY and returns
451
+ * true: the caller resolves a shot (one every FIRE_EVERY steps, the first at once).
452
+ */
453
+ var move = (p, i, lvl) => {
454
+ const fire = (i.keys & KEY.FIRE) !== 0;
455
+ p.cool = Math.max(0, p.cool - 1);
456
+ p.yaw = norm(i.yaw);
457
+ p.pitch = Math.max(-MAX_PITCH, Math.min(MAX_PITCH, i.pitch));
458
+ const f = (i.keys & KEY.FORWARD ? 1 : 0) - (i.keys & KEY.BACK ? 1 : 0);
459
+ const s = (i.keys & KEY.RIGHT ? 1 : 0) - (i.keys & KEY.LEFT ? 1 : 0);
460
+ const d = 6 * DT$1 * (fire ? FIRE_SLOW : 1) / (Math.hypot(f, s) || 1);
461
+ const [fx, fz] = forward(p.yaw);
462
+ walk(p, (fx * f - fz * s) * d, (fz * f + fx * s) * d, (i.keys & KEY.JUMP) !== 0, lvl);
337
463
  if (fire && !p.cool) {
338
464
  p.cool = 5;
339
465
  return true;
@@ -357,65 +483,6 @@ var spawn = (id, lvl, n) => {
357
483
  cool: 0
358
484
  };
359
485
  };
360
- var TURN = 65536 / (2 * Math.PI);
361
- /** Radians to 65536ths of a turn; the mask also folds negative and ≥ 2π angles into one turn. */
362
- var toTurn = (yaw) => Math.round(yaw * TURN) & 65535;
363
- var clamp16 = (v) => Math.max(-32768, Math.min(32767, Math.round(v)));
364
- /** Pitch in 1/10000 rad, and back. */
365
- var toPitch = (pitch) => clamp16(pitch * 1e4);
366
- var fromPitch = (w) => w / 1e4;
367
- var fromTurn = (w) => w / TURN;
368
- /** Null on anything that is not a well-formed input frame. */
369
- var decodeInput = (buf) => {
370
- if (buf.byteLength !== 11) return null;
371
- const v = new DataView(buf);
372
- if (v.getUint8(0) !== 1) return null;
373
- return {
374
- seq: v.getUint16(1),
375
- keys: v.getUint8(3),
376
- yaw: fromTurn(v.getUint16(4)),
377
- pitch: fromPitch(v.getInt16(6)),
378
- view: (v.getUint16(8) * 256 + v.getUint8(10)) / 256
379
- };
380
- };
381
- var encodeSnapshot = (s) => {
382
- const shots = 4 + 24 * s.players.length;
383
- const v = new DataView(new ArrayBuffer(shots + 1 + 14 * s.shots.length));
384
- v.setUint8(0, 2);
385
- v.setUint16(1, s.tick & 65535);
386
- v.setUint8(3, s.players.length);
387
- s.players.forEach((p, i) => {
388
- const o = 4 + i * 24;
389
- v.setUint8(o, p.id);
390
- v.setFloat32(o + 1, p.x);
391
- v.setFloat32(o + 5, p.y);
392
- v.setFloat32(o + 9, p.z);
393
- v.setFloat32(o + 13, p.vy);
394
- v.setUint16(o + 17, toTurn(p.yaw));
395
- v.setInt16(o + 19, toPitch(p.pitch));
396
- v.setUint16(o + 21, p.ack & 65535);
397
- v.setUint8(o + 23, +p.ground | p.cool << 1);
398
- });
399
- v.setUint8(shots, s.shots.length);
400
- s.shots.forEach((h, i) => {
401
- const o = shots + 1 + i * 14;
402
- v.setUint8(o, h.id);
403
- v.setFloat32(o + 1, h.x);
404
- v.setFloat32(o + 5, h.y);
405
- v.setFloat32(o + 9, h.z);
406
- v.setUint8(o + 13, h.hit & 255);
407
- });
408
- return v.buffer;
409
- };
410
- /** Returns null on anything that is not a known text message. */
411
- var parseText = (raw) => {
412
- try {
413
- const msg = JSON.parse(raw);
414
- return msg && typeof msg.t === "string" ? msg : null;
415
- } catch {
416
- return null;
417
- }
418
- };
419
486
  // src/shared/shoot.ts
420
487
  /** 32-bit integer hash (a xorshift-multiply round, twice). */
421
488
  var hash = (n) => {
@@ -493,14 +560,14 @@ var hit = (o, d, t) => {
493
560
  const [px, pz] = [o[0] - t.x, o[2] - t.z];
494
561
  const a = d[0] * d[0] + d[2] * d[2];
495
562
  const b = px * d[0] + pz * d[2];
496
- const c = px * px + pz * pz - PLAYER_R * PLAYER_R;
563
+ const c = px * px + pz * pz - t.r * t.r;
497
564
  let [lo, hi] = [0, Infinity];
498
565
  if (a > 1e-12) {
499
566
  const q = b * b - a * c;
500
567
  if (q < 0) return Infinity;
501
568
  [lo, hi] = [Math.max(0, (-b - Math.sqrt(q)) / a), (-b + Math.sqrt(q)) / a];
502
569
  } else if (c > 0) return Infinity;
503
- const [y0, y1] = [t.y - o[1], t.y + PLAYER_H - o[1]];
570
+ const [y0, y1] = [t.y - o[1], t.y + t.h - o[1]];
504
571
  if (d[1]) {
505
572
  const [u, v] = [y0 / d[1], y1 / d[1]];
506
573
  lo = Math.max(lo, Math.min(u, v));
@@ -508,10 +575,31 @@ var hit = (o, d, t) => {
508
575
  } else if (y0 > 0 || y1 < 0) return Infinity;
509
576
  return lo <= hi ? lo : Infinity;
510
577
  };
578
+ /** The body a shot sees of a player. */
579
+ var body = ({ id, x, y, z }) => ({
580
+ id,
581
+ x,
582
+ y,
583
+ z,
584
+ r: PLAYER_R,
585
+ h: PLAYER_H
586
+ });
587
+ /** The body a shot sees of a monster. */
588
+ var monsterBody = ({ id, kind, x, y, z }) => {
589
+ const walker = kind === MONSTER.WALKER;
590
+ return {
591
+ id,
592
+ x,
593
+ y,
594
+ z,
595
+ r: walker ? WALKER_R : FLYER_R,
596
+ h: walker ? WALKER_H : FLYER_H
597
+ };
598
+ };
511
599
  /**
512
600
  * Resolves one shot of `shooter` (state after the step that fired) from its eye (feet + EYE)
513
601
  * along aim(yaw, pitch, seq): the nearest of the level (trace) and the upright cylinders
514
- * (PLAYER_R, PLAYER_H, from the feet) of `targets` other than the shooter, within RANGE.
602
+ * of `targets` (bodies: players, monsters) other than the shooter, within RANGE.
515
603
  */
516
604
  var fire = (lvl, shooter, seq, targets) => {
517
605
  const o = [
@@ -534,6 +622,371 @@ var fire = (lvl, shooter, seq, targets) => {
534
622
  hit: id
535
623
  };
536
624
  };
625
+ // src/shared/monsters.ts
626
+ var DT = 1 / 60;
627
+ /** Radians a monster turns per tick toward its target. */
628
+ var TURN$1 = .05;
629
+ /** A patrolling monster moves at this share of its speed. */
630
+ var PATROL = .4;
631
+ /** A chasing monster stops this close (metres): inside MELEE_R, short of standing in the player. */
632
+ var STOP = 1;
633
+ /** Ticks between the start of a swing and its blow. */
634
+ var SWING_DELAY = 15;
635
+ /** Height of a player's chest above the feet: where monsters aim. */
636
+ var CHEST = 1.2;
637
+ /** The snapshot counts bullets with a u8. */
638
+ var MAX_BULLETS = 255;
639
+ /** Mulberry32: a small seeded generator, uniform in [0, 1). */
640
+ var mulberry32 = (seed) => {
641
+ let a = seed | 0;
642
+ return () => {
643
+ a = a + 1831565813 | 0;
644
+ let t = Math.imul(a ^ a >>> 15, 1 | a);
645
+ t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
646
+ return ((t ^ t >>> 14) >>> 0) / 4294967296;
647
+ };
648
+ };
649
+ /** The monsters of the level's map, from the first spawn. */
650
+ var createHorde = (lvl, rand) => {
651
+ const def = (lvl.map.monsters ?? []).slice(0, 64);
652
+ let mobs = [];
653
+ let shells = [];
654
+ const events = [];
655
+ let tick = 0;
656
+ let nextBullet = 0;
657
+ let wait = 0;
658
+ const spawnAll = () => {
659
+ mobs = def.map(([x, z, yaw, kind], i) => {
660
+ const { floor, ceil } = lvl.map.sectors[Math.max(sectorAt(lvl, x, z), 0)];
661
+ const flyer = kind === MONSTER.FLYER;
662
+ return {
663
+ id: 16 + i,
664
+ kind,
665
+ x: Math.fround(x),
666
+ y: Math.fround(flyer ? Math.min(floor + FLYER_HOVER, ceil - FLYER_H) : floor),
667
+ z: Math.fround(z),
668
+ yaw: norm(yaw),
669
+ chase: false,
670
+ vy: 0,
671
+ ground: true,
672
+ target: -1,
673
+ turn: Math.floor(rand() * 240),
674
+ melee: 0,
675
+ swing: 0,
676
+ shoot: Math.floor(rand() * 90)
677
+ };
678
+ });
679
+ };
680
+ spawnAll();
681
+ const mid = (m) => m.y + monsterBody(m).h / 2;
682
+ const eye = (m) => [
683
+ m.x,
684
+ m.kind === MONSTER.WALKER ? m.y + EYE : mid(m),
685
+ m.z
686
+ ];
687
+ const eyeOf = (p) => [
688
+ p.x,
689
+ p.y + EYE,
690
+ p.z
691
+ ];
692
+ const hunt = (m, id) => {
693
+ m.target = id;
694
+ m.chase = id >= 0;
695
+ };
696
+ /** The monsters within ALERT_R of `src` that it can see, and that are not hunting, hunt `who`. */
697
+ const alert = (src, who) => {
698
+ for (const m of mobs) if (m !== src && !m.chase && Math.hypot(m.x - src.x, m.z - src.z) < 12 && !blocked(lvl, eye(src), eye(m))) hunt(m, who);
699
+ };
700
+ /** The nearest player in range, inside the sight cone and not hidden becomes the target. */
701
+ const look = (m, players) => {
702
+ const [fx, fz] = forward(m.yaw);
703
+ let seen;
704
+ let near = Infinity;
705
+ for (const p of players) {
706
+ const [dx, dz] = [p.x - m.x, p.z - m.z];
707
+ const d = Math.hypot(dx, dz);
708
+ if (d <= 30 && d < near && dx * fx + dz * fz >= SIGHT_COS * d && !blocked(lvl, eye(m), eyeOf(p))) [seen, near] = [p, d];
709
+ }
710
+ if (seen) {
711
+ const spotted = !m.chase;
712
+ hunt(m, seen.id);
713
+ if (spotted) alert(m, seen.id);
714
+ }
715
+ };
716
+ const turnTo = (m, yaw) => {
717
+ const arc = ((yaw - m.yaw + Math.PI) % TAU + TAU) % TAU - Math.PI;
718
+ m.yaw = norm(m.yaw + Math.max(-.05, Math.min(TURN$1, arc)));
719
+ };
720
+ /** Whether the floor under the axis is more than a step below `y`. */
721
+ const ledge = (m, y) => lvl.map.sectors[Math.max(sectorAt(lvl, m.x, m.z), 0)].floor < y - STEP_H;
722
+ const patrol = (m) => {
723
+ const s = (m.kind === MONSTER.WALKER ? WALKER_SPEED : FLYER_SPEED) * PATROL * DT;
724
+ const [fx, fz] = forward(m.yaw);
725
+ const before = {
726
+ x: m.x,
727
+ y: m.y,
728
+ z: m.z,
729
+ vy: m.vy,
730
+ ground: m.ground
731
+ };
732
+ if (m.kind === MONSTER.WALKER) walk(m, fx * s, fz * s, false, lvl);
733
+ else fly(m, fx * s, -s, fz * s, lvl);
734
+ const drop = m.kind === MONSTER.WALKER && ledge(m, before.y);
735
+ if (drop || Math.hypot(m.x - before.x, m.z - before.z) < s / 2) {
736
+ if (drop) Object.assign(m, before);
737
+ m.yaw = norm(m.yaw + rand() * TAU);
738
+ } else if (--m.turn <= 0) {
739
+ m.turn = 120 + Math.floor(rand() * 240);
740
+ m.yaw = norm(m.yaw + (rand() - .5) * Math.PI);
741
+ }
742
+ };
743
+ /** A walker that sees the player fires a bullet from its eye at the chest, and waits. */
744
+ const shootAt = (m, p) => {
745
+ const [ox, oy, oz] = eye(m);
746
+ if (shells.length >= MAX_BULLETS || blocked(lvl, [
747
+ ox,
748
+ oy,
749
+ oz
750
+ ], eyeOf(p))) {
751
+ m.shoot = 0;
752
+ return;
753
+ }
754
+ const v = [
755
+ p.x - ox,
756
+ p.y + CHEST - oy,
757
+ p.z - oz
758
+ ];
759
+ const k = 12 * DT / Math.hypot(...v);
760
+ shells.push({
761
+ id: nextBullet++ & 255,
762
+ x: ox,
763
+ y: oy,
764
+ z: oz,
765
+ vx: v[0] * k,
766
+ vy: v[1] * k,
767
+ vz: v[2] * k,
768
+ life: 300
769
+ });
770
+ m.shoot = 90 + Math.floor((rand() - .5) * 20);
771
+ };
772
+ const chase = (m, p) => {
773
+ const [dx, dz] = [p.x - m.x, p.z - m.z];
774
+ const d = Math.hypot(dx, dz);
775
+ if (d > 1e-6) turnTo(m, Math.atan2(-dx, -dz));
776
+ if (m.kind === MONSTER.WALKER) {
777
+ const [fx, fz] = forward(m.yaw);
778
+ const s = d > STOP ? WALKER_SPEED * DT : 0;
779
+ walk(m, fx * s, fz * s, false, lvl);
780
+ } else {
781
+ const dy = p.y + CHEST - FLYER_H / 2 - m.y;
782
+ const k = Math.min(1, FLYER_SPEED * DT / (Math.hypot(d, dy) || 1));
783
+ fly(m, d > STOP ? dx * k : 0, dy * k, d > STOP ? dz * k : 0, lvl);
784
+ }
785
+ const near = Math.hypot(p.x - m.x, p.z - m.z) <= 1.4 && m.y < p.y + 1.8 && p.y < m.y + monsterBody(m).h;
786
+ m.melee = Math.max(0, m.melee - 1);
787
+ if (m.swing && !--m.swing && near) {
788
+ const [fx, fz] = forward(m.yaw);
789
+ if ((p.x - m.x) * fx + (p.z - m.z) * fz > 0) events.push({
790
+ type: EVENT.HURT,
791
+ id: p.id,
792
+ x: p.x,
793
+ y: p.y + CHEST,
794
+ z: p.z
795
+ });
796
+ }
797
+ if (near && !m.melee) {
798
+ events.push({
799
+ type: EVENT.SWING,
800
+ id: m.id,
801
+ x: m.x,
802
+ y: mid(m),
803
+ z: m.z
804
+ });
805
+ [m.melee, m.swing] = [45, SWING_DELAY];
806
+ }
807
+ if (m.kind === MONSTER.WALKER && m.shoot-- <= 0 && d <= 30) shootAt(m, p);
808
+ };
809
+ /** Moves a bullet one tick; false when it is spent: it hit a player or the level, or timed out. */
810
+ const advance = (b, players) => {
811
+ const len = Math.hypot(b.vx, b.vy, b.vz);
812
+ const o = [
813
+ b.x,
814
+ b.y,
815
+ b.z
816
+ ];
817
+ const dir = [
818
+ b.vx / len,
819
+ b.vy / len,
820
+ b.vz / len
821
+ ];
822
+ let t = trace(lvl, o, dir, len);
823
+ let who = -1;
824
+ for (const p of players) {
825
+ const u = hit(o, dir, {
826
+ id: p.id,
827
+ x: p.x,
828
+ y: p.y - BULLET_R,
829
+ z: p.z,
830
+ r: PLAYER_R + BULLET_R,
831
+ h: PLAYER_H + 2 * BULLET_R
832
+ });
833
+ if (u < t) [t, who] = [u, p.id];
834
+ }
835
+ [b.x, b.y, b.z] = [
836
+ o[0] + dir[0] * t,
837
+ o[1] + dir[1] * t,
838
+ o[2] + dir[2] * t
839
+ ];
840
+ if (who >= 0) events.push({
841
+ type: EVENT.HURT,
842
+ id: who,
843
+ x: b.x,
844
+ y: b.y,
845
+ z: b.z
846
+ });
847
+ else if (t < len) events.push({
848
+ type: EVENT.BOOM,
849
+ id: b.id,
850
+ x: b.x,
851
+ y: b.y,
852
+ z: b.z
853
+ });
854
+ return who < 0 && t >= len && --b.life > 0;
855
+ };
856
+ return {
857
+ monsters: () => mobs.map(({ id, kind, x, y, z, yaw, chase }) => ({
858
+ id,
859
+ kind,
860
+ x,
861
+ y,
862
+ z,
863
+ yaw,
864
+ chase
865
+ })),
866
+ bullets: () => shells.map(({ id, x, y, z }) => ({
867
+ id,
868
+ x,
869
+ y,
870
+ z
871
+ })),
872
+ events,
873
+ step: (players) => {
874
+ tick++;
875
+ for (const m of mobs) {
876
+ if ((tick + m.id) % 60 === 0) look(m, players);
877
+ const target = players.find((p) => p.id === m.target);
878
+ if (m.chase && !target) hunt(m, -1);
879
+ if (target) chase(m, target);
880
+ else patrol(m);
881
+ }
882
+ shells = shells.filter((b) => advance(b, players));
883
+ if (!mobs.length && def.length && --wait <= 0) spawnAll();
884
+ },
885
+ kill: (id, by) => {
886
+ const i = mobs.findIndex((m) => m.id === id);
887
+ if (i < 0) return;
888
+ const [m] = mobs.splice(i, 1);
889
+ events.push({
890
+ type: EVENT.DIE,
891
+ id,
892
+ x: m.x,
893
+ y: mid(m),
894
+ z: m.z
895
+ });
896
+ alert(m, by);
897
+ wait = 300;
898
+ }
899
+ };
900
+ };
901
+ var TURN = 65536 / (2 * Math.PI);
902
+ /** Radians to 65536ths of a turn; the mask also folds negative and ≥ 2π angles into one turn. */
903
+ var toTurn = (yaw) => Math.round(yaw * TURN) & 65535;
904
+ var clamp16 = (v) => Math.max(-32768, Math.min(32767, Math.round(v)));
905
+ /** Pitch in 1/10000 rad, and back. */
906
+ var toPitch = (pitch) => clamp16(pitch * 1e4);
907
+ var fromPitch = (w) => w / 1e4;
908
+ var fromTurn = (w) => w / TURN;
909
+ /** Null on anything that is not a well-formed input frame. */
910
+ var decodeInput = (buf) => {
911
+ if (buf.byteLength !== 11) return null;
912
+ const v = new DataView(buf);
913
+ if (v.getUint8(0) !== 1) return null;
914
+ return {
915
+ seq: v.getUint16(1),
916
+ keys: v.getUint8(3),
917
+ yaw: fromTurn(v.getUint16(4)),
918
+ pitch: fromPitch(v.getInt16(6)),
919
+ view: (v.getUint16(8) * 256 + v.getUint8(10)) / 256
920
+ };
921
+ };
922
+ var encodeSnapshot = (s) => {
923
+ const shots = 4 + 24 * s.players.length;
924
+ const monsters = shots + 1 + 14 * s.shots.length;
925
+ const bullets = monsters + 1 + 16 * s.monsters.length;
926
+ const events = bullets + 1 + 13 * s.bullets.length;
927
+ const v = new DataView(new ArrayBuffer(events + 1 + 14 * s.events.length));
928
+ v.setUint8(0, 2);
929
+ v.setUint16(1, s.tick & 65535);
930
+ v.setUint8(3, s.players.length);
931
+ s.players.forEach((p, i) => {
932
+ const o = 4 + i * 24;
933
+ v.setUint8(o, p.id);
934
+ v.setFloat32(o + 1, p.x);
935
+ v.setFloat32(o + 5, p.y);
936
+ v.setFloat32(o + 9, p.z);
937
+ v.setFloat32(o + 13, p.vy);
938
+ v.setUint16(o + 17, toTurn(p.yaw));
939
+ v.setInt16(o + 19, toPitch(p.pitch));
940
+ v.setUint16(o + 21, p.ack & 65535);
941
+ v.setUint8(o + 23, +p.ground | p.cool << 1);
942
+ });
943
+ v.setUint8(shots, s.shots.length);
944
+ s.shots.forEach((h, i) => {
945
+ const o = shots + 1 + i * 14;
946
+ v.setUint8(o, h.id);
947
+ v.setFloat32(o + 1, h.x);
948
+ v.setFloat32(o + 5, h.y);
949
+ v.setFloat32(o + 9, h.z);
950
+ v.setUint8(o + 13, h.hit & 255);
951
+ });
952
+ v.setUint8(monsters, s.monsters.length);
953
+ s.monsters.forEach((m, i) => {
954
+ const o = monsters + 1 + i * 16;
955
+ v.setUint8(o, m.id);
956
+ v.setUint8(o + 1, m.kind & 1 | +m.chase << 1);
957
+ v.setFloat32(o + 2, m.x);
958
+ v.setFloat32(o + 6, m.y);
959
+ v.setFloat32(o + 10, m.z);
960
+ v.setUint16(o + 14, toTurn(m.yaw));
961
+ });
962
+ v.setUint8(bullets, s.bullets.length);
963
+ s.bullets.forEach((b, i) => {
964
+ const o = bullets + 1 + i * 13;
965
+ v.setUint8(o, b.id);
966
+ v.setFloat32(o + 1, b.x);
967
+ v.setFloat32(o + 5, b.y);
968
+ v.setFloat32(o + 9, b.z);
969
+ });
970
+ v.setUint8(events, s.events.length);
971
+ s.events.forEach((e, i) => {
972
+ const o = events + 1 + i * 14;
973
+ v.setUint8(o, e.type);
974
+ v.setUint8(o + 1, e.id);
975
+ v.setFloat32(o + 2, e.x);
976
+ v.setFloat32(o + 6, e.y);
977
+ v.setFloat32(o + 10, e.z);
978
+ });
979
+ return v.buffer;
980
+ };
981
+ /** Returns null on anything that is not a known text message. */
982
+ var parseText = (raw) => {
983
+ try {
984
+ const msg = JSON.parse(raw);
985
+ return msg && typeof msg.t === "string" ? msg : null;
986
+ } catch {
987
+ return null;
988
+ }
989
+ };
537
990
  // src/shared/room.ts
538
991
  /** Ticks run at most this many times per timer callback, so a stalled host does not spiral. */
539
992
  var MAX_CATCH_UP = 20;
@@ -582,27 +1035,31 @@ var setEvery = (cb, ms) => {
582
1035
  * - Each input frame moves its player at once with move(); the INPUT_BURST bank drops the excess.
583
1036
  * A step that fires resolves its shot at once with fire(), the other players rewound to the
584
1037
  * view tick of the input (lag compensation, at most MAX_REWIND ticks back).
585
- * - Every SNAP_EVERY ticks of TICK_HZ, one snapshot with every player and the shots resolved
586
- * since the last one goes to every peer.
1038
+ * - The room owns the horde (monsters.ts), stepped every tick while a player is present. A shot
1039
+ * rewinds the monsters with the players, and one that hits a monster kills it.
1040
+ * - Every SNAP_EVERY ticks of TICK_HZ, one snapshot with every player, the shots resolved since
1041
+ * the last one, the monsters, the bullets and the events since the last one goes to every peer.
587
1042
  */
588
1043
  var Room = class {
589
1044
  /** Every connected peer; null until it joins. */
590
1045
  peers = /* @__PURE__ */ new Map();
591
1046
  ticks = 0;
592
- /** The players as each snapshot of the last MAX_REWIND ticks sent them. */
1047
+ /** The players and monsters as each snapshot of the last MAX_REWIND ticks sent them. */
593
1048
  history = [];
1049
+ horde;
594
1050
  /** Shots resolved since the last snapshot. */
595
1051
  shots = [];
596
1052
  halt;
597
1053
  rules;
598
1054
  /** Round-robin cursor over the spawn points, used once they are all taken. */
599
1055
  rr = 0;
600
- /** Missing rules fall back to RULES. */
601
- constructor(rules = {}) {
1056
+ /** Missing rules fall back to RULES. The seed drives the monsters. */
1057
+ constructor(rules = {}, seed = Date.now()) {
602
1058
  this.rules = {
603
1059
  ...RULES,
604
1060
  ...rules
605
1061
  };
1062
+ this.horde = createHorde(LEVEL, mulberry32(seed));
606
1063
  }
607
1064
  /** Number of joined players. */
608
1065
  get size() {
@@ -623,7 +1080,11 @@ var Room = class {
623
1080
  const input = p && decodeInput(data);
624
1081
  if (input && p.bank > 0) {
625
1082
  p.bank--;
626
- if (move(p.state, input, LEVEL)) this.shots.push(fire(LEVEL, p.state, input.seq, this.rewind(p, input.view)));
1083
+ if (move(p.state, input, LEVEL)) {
1084
+ const shot = fire(LEVEL, p.state, input.seq, this.rewind(p, input.view));
1085
+ this.shots.push(shot);
1086
+ if (shot.hit >= 16) this.horde.kill(shot.hit, p.state.id);
1087
+ }
627
1088
  p.ack = input.seq;
628
1089
  }
629
1090
  }
@@ -638,10 +1099,13 @@ var Room = class {
638
1099
  const players = this.players();
639
1100
  if (!players.length) return;
640
1101
  players.forEach((p) => p.bank = Math.min(10, p.bank + 1));
1102
+ this.horde.step(players.map((p) => p.state));
641
1103
  if (++this.ticks % 2 === 0) {
1104
+ const monsters = this.horde.monsters();
642
1105
  this.history.push({
643
1106
  tick: this.ticks,
644
- players: players.map((p) => ({ ...p.state }))
1107
+ players: players.map((p) => ({ ...p.state })),
1108
+ monsters
645
1109
  });
646
1110
  while (this.history[0].tick < this.ticks - 30) this.history.shift();
647
1111
  const snap = encodeSnapshot({
@@ -650,7 +1114,10 @@ var Room = class {
650
1114
  ...p.state,
651
1115
  ack: p.ack
652
1116
  })),
653
- shots: this.shots
1117
+ shots: this.shots,
1118
+ monsters,
1119
+ bullets: this.horde.bullets(),
1120
+ events: this.horde.events.splice(0, 255)
654
1121
  });
655
1122
  this.shots = [];
656
1123
  players.forEach((p) => p.conn.send(snap));
@@ -684,25 +1151,26 @@ var Room = class {
684
1151
  this.halt = void 0;
685
1152
  }
686
1153
  /**
687
- * The players other than `shooter` as the shooter drew them at `view` (a u16 tick, fractional,
688
- * read against the current tick and clamped to the kept history): x, y, z interpolated between
689
- * the two snapshots around it like the client does. A player the history does not hold stands
690
- * where it is.
1154
+ * The bodies a shot of `shooter` can hit as the shooter drew them at `view` (a u16 tick,
1155
+ * fractional, read against the current tick and clamped to the kept history): the other players
1156
+ * and the monsters, x, y, z interpolated between the two snapshots around it like the client
1157
+ * does. One the history does not hold stands where it is.
691
1158
  */
692
1159
  rewind(shooter, view = 0) {
693
1160
  const now = this.players().filter((p) => p !== shooter).map((p) => p.state);
1161
+ const mobs = this.horde.monsters();
694
1162
  const [first, last] = [this.history[0], this.history.at(-1)];
695
- if (!first || !last) return now;
1163
+ if (!first || !last) return [...now.map(body), ...mobs.map(monsterBody)];
696
1164
  const back = ((this.ticks - view + 32768) % 65536 + 65536) % 65536 - 32768;
697
1165
  const t = Math.min(Math.max(this.ticks - back, first.tick), last.tick);
698
1166
  let k = 0;
699
1167
  while (k + 1 < this.history.length && this.history[k + 1].tick <= t) k++;
700
1168
  const [a, b] = [this.history[k], this.history[k + 1] ?? this.history[k]];
701
1169
  const u = b.tick > a.tick ? (t - a.tick) / (b.tick - a.tick) : 0;
702
- return now.map((p) => {
703
- const pa = a.players.find((q) => q.id === p.id);
704
- const pb = b.players.find((q) => q.id === p.id);
705
- const l = (m, n) => m + (n - m) * u;
1170
+ const l = (m, n) => m + (n - m) * u;
1171
+ const at = (cur, list) => cur.map((p) => {
1172
+ const pa = list(a).find((q) => q.id === p.id);
1173
+ const pb = list(b).find((q) => q.id === p.id);
706
1174
  return pa && pb ? {
707
1175
  ...pb,
708
1176
  x: l(pa.x, pb.x),
@@ -710,6 +1178,7 @@ var Room = class {
710
1178
  z: l(pa.z, pb.z)
711
1179
  } : pb ?? pa ?? p;
712
1180
  });
1181
+ return [...at(now, (h) => h.players).map(body), ...at(mobs, (h) => h.monsters).map(monsterBody)];
713
1182
  }
714
1183
  players() {
715
1184
  return [...this.peers.values()].filter((p) => p !== null);