@korial29/tiny-fps 0.18.0 → 0.19.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
@@ -25,8 +25,19 @@ var GRAB_REACH = .2;
25
25
  var GRAB_GAP = .03;
26
26
  var CLIMB_INSET = .2;
27
27
  var CLIMB_FWD_SPEED = 5.5;
28
- var RULES = { maxPlayers: 16 };
28
+ var TEAM_COLOR = ["#ff3d4f", "#2f80ff"];
29
+ var RULES = {
30
+ maxPlayers: 16,
31
+ scoreLimit: 3,
32
+ timeLimit: 480
33
+ };
29
34
  // src/shared/types.ts
35
+ /** Where a team's flag is: at its base, on a carrier's back, or on the ground where it was dropped. */
36
+ var FLAG = {
37
+ HOME: 0,
38
+ CARRIED: 1,
39
+ DROPPED: 2
40
+ };
30
41
  /** Bits of Input.keys. Keys are read by KeyboardEvent.code, so WASD is ZQSD on AZERTY. */
31
42
  var KEY = {
32
43
  FORWARD: 1,
@@ -83,7 +94,9 @@ var EV = {
83
94
  WALLRUN_START: 64,
84
95
  WALLRUN_END: 128,
85
96
  SLIDE_START: 256,
86
- SLIDE_END: 512
97
+ SLIDE_END: 512,
98
+ /** Fell under the kill floor and was put back at a spawn: the host drops a carried flag. */
99
+ RESPAWN: 1024
87
100
  };
88
101
  /** Procedural textures, generated by the client. A brush names one for its top and one for its sides. */
89
102
  var TEX = {
@@ -100,6 +113,315 @@ var TEX = {
100
113
  /** Metal floor grating over darkness. */
101
114
  GRATE: 7
102
115
  };
116
+ // src/shared/world.ts
117
+ /** Metres per grid cell: about the size of the player's reach, so a query touches 1 to 4 cells. */
118
+ var CELL = 4;
119
+ /** Cell coordinates run from -OFF to OFF - 1: a 8 km square at 4 m, far more than any map. */
120
+ var OFF = 1024;
121
+ /** The key of the cell with integer coordinates (cx, cz). */
122
+ var key = (cx, cz) => (cx + OFF) * (2 * OFF) + cz + OFF;
123
+ /** Integer cell coordinate of a metre value, clamped to the keyed range. */
124
+ var at = (v, cell) => Math.min(Math.max(Math.floor(v / cell), -1024), 1023);
125
+ /** Builds the grid: each brush is listed in every cell its footprint covers. */
126
+ var build = (def, cell = CELL) => {
127
+ const grid = /* @__PURE__ */ new Map();
128
+ def.brushes.forEach(({ min, max }, i) => {
129
+ for (let cx = at(min[0], cell); cx <= at(max[0], cell); cx++) for (let cz = at(min[2], cell); cz <= at(max[2], cell); cz++) {
130
+ const k = key(cx, cz);
131
+ const list = grid.get(k);
132
+ if (list) list.push(i);
133
+ else grid.set(k, [i]);
134
+ }
135
+ });
136
+ return {
137
+ def,
138
+ cell,
139
+ grid
140
+ };
141
+ };
142
+ /**
143
+ * Indices of the brushes whose footprint may overlap the square of half side r around (x, z): every
144
+ * brush listed in a cell the square touches, once each. A candidate list, not an exact overlap.
145
+ */
146
+ var near = (w, x, z, r) => {
147
+ const out = [];
148
+ for (let cx = at(x - r, w.cell); cx <= at(x + r, w.cell); cx++) for (let cz = at(z - r, w.cell); cz <= at(z + r, w.cell); cz++) for (const i of w.grid.get(key(cx, cz)) ?? []) if (!out.includes(i)) out.push(i);
149
+ return out;
150
+ };
151
+ /**
152
+ * Distance along the ray from o in the unit direction d to the first brush face, at most max. A ray
153
+ * that starts inside a brush hits at 0; one that starts on a face and moves away from it does not hit it.
154
+ *
155
+ * Walks the grid cells the ray crosses (Amanatides and Woo), testing the brushes of each against
156
+ * the exact slab test, and stops once the next cell starts beyond the best hit or max. A brush
157
+ * spanning several cells is tested in each: the hit is the same, and lists are short.
158
+ */
159
+ var ray = (w, o, d, max) => {
160
+ const { cell, def } = w;
161
+ let best = max;
162
+ let cx = at(o[0], cell);
163
+ let cz = at(o[2], cell);
164
+ const sx = Math.sign(d[0]);
165
+ const sz = Math.sign(d[2]);
166
+ const nx = sx ? ((cx + (sx > 0 ? 1 : 0)) * cell - o[0]) / d[0] : Infinity;
167
+ const nz = sz ? ((cz + (sz > 0 ? 1 : 0)) * cell - o[2]) / d[2] : Infinity;
168
+ let tx = nx;
169
+ let tz = nz;
170
+ const dx = sx ? cell / Math.abs(d[0]) : Infinity;
171
+ const dz = sz ? cell / Math.abs(d[2]) : Infinity;
172
+ for (;;) {
173
+ for (const i of w.grid.get(key(cx, cz)) ?? []) {
174
+ const b = def.brushes[i];
175
+ let [lo, hi] = [0, best];
176
+ for (let a = 0; a < 3 && lo <= hi; a++) {
177
+ if (!d[a]) {
178
+ if (o[a] < b.min[a] || o[a] > b.max[a]) hi = -1;
179
+ continue;
180
+ }
181
+ const t0 = (b.min[a] - o[a]) / d[a];
182
+ const t1 = (b.max[a] - o[a]) / d[a];
183
+ lo = Math.max(lo, Math.min(t0, t1));
184
+ hi = Math.min(hi, Math.max(t0, t1));
185
+ }
186
+ if (lo <= hi && hi > 0 && lo < best) best = lo;
187
+ }
188
+ if (Math.min(tx, tz) >= best || Math.abs(cx) > OFF || Math.abs(cz) > OFF) return best;
189
+ if (tx < tz) {
190
+ cx += sx;
191
+ tx += dx;
192
+ } else {
193
+ cz += sz;
194
+ tz += dz;
195
+ }
196
+ }
197
+ };
198
+ // src/shared/ctf.ts
199
+ var home = () => ({
200
+ state: FLAG.HOME,
201
+ by: 0,
202
+ x: 0,
203
+ y: 0,
204
+ z: 0,
205
+ left: 0
206
+ });
207
+ /** How far under a carrier a flag that he drops in the air is looked for a floor, metres. */
208
+ var FALL = 60;
209
+ var Ctf = class {
210
+ /** Captures per team, red then blue. */
211
+ score = [0, 0];
212
+ /** The match is over and the end screen shows. */
213
+ over = false;
214
+ /** The flag of each team, red then blue. */
215
+ flags = [home(), home()];
216
+ world;
217
+ rules;
218
+ mates = /* @__PURE__ */ new Map();
219
+ /** Ticks to the end of the match, or to the next one while it is over. */
220
+ clock;
221
+ /** Ticks before each dropped flag goes home. */
222
+ back = [0, 0];
223
+ /** Who may not take each flag, and for how many more ticks: the carrier that was made to drop it. */
224
+ lock = [{
225
+ id: -1,
226
+ left: 0
227
+ }, {
228
+ id: -1,
229
+ left: 0
230
+ }];
231
+ constructor(world, rules) {
232
+ this.world = world;
233
+ this.rules = rules;
234
+ this.clock = rules.timeLimit * 60;
235
+ }
236
+ /** A player joined, standing at `at`. */
237
+ join(id, team, at) {
238
+ this.mates.set(id, {
239
+ team,
240
+ caps: 0,
241
+ returns: 0,
242
+ ground: [
243
+ at.x,
244
+ at.y,
245
+ at.z
246
+ ]
247
+ });
248
+ }
249
+ /** A player left: a flag he carried is dropped where he last stood. */
250
+ leave(id) {
251
+ const k = this.carrying(id);
252
+ const m = this.mates.get(id);
253
+ if (k >= 0 && m) this.dropAt(k, m.ground);
254
+ this.mates.delete(id);
255
+ }
256
+ /** A player was put at `at` (a new match): his last ground is there. */
257
+ place(id, at) {
258
+ const m = this.mates.get(id);
259
+ if (m) m.ground = [
260
+ at.x,
261
+ at.y,
262
+ at.z
263
+ ];
264
+ }
265
+ /**
266
+ * The player's state after one move. Under the kill floor and put back at a spawn (EV.RESPAWN),
267
+ * a carrier drops the flag where he last stood; then a floor under him is his last ground.
268
+ */
269
+ moved(p) {
270
+ const m = this.mates.get(p.id);
271
+ if (!m) return;
272
+ const k = this.carrying(p.id);
273
+ if (p.ev & EV.RESPAWN && k >= 0) this.dropAt(k, m.ground);
274
+ if (p.ground) m.ground = [
275
+ p.x,
276
+ p.y,
277
+ p.z
278
+ ];
279
+ }
280
+ /**
281
+ * Makes the player drop the flag he carries (the tackle of step 7). It lies under him: where he
282
+ * stands, or on the first floor below him, or at his last ground when there is none (over the
283
+ * void). False when he carried nothing.
284
+ */
285
+ drop(p) {
286
+ const k = this.carrying(p.id);
287
+ const m = this.mates.get(p.id);
288
+ if (k < 0 || !m || this.over) return false;
289
+ let at = m.ground;
290
+ if (p.ground) at = [
291
+ p.x,
292
+ p.y,
293
+ p.z
294
+ ];
295
+ else {
296
+ const d = ray(this.world, [
297
+ p.x,
298
+ p.y + .05,
299
+ p.z
300
+ ], [
301
+ 0,
302
+ -1,
303
+ 0
304
+ ], FALL);
305
+ if (d < FALL) at = [
306
+ p.x,
307
+ p.y + .05 - d,
308
+ p.z
309
+ ];
310
+ }
311
+ this.dropAt(k, at);
312
+ this.lock[k] = {
313
+ id: p.id,
314
+ left: 120
315
+ };
316
+ return true;
317
+ }
318
+ /** The team whose flag the player carries, or -1. */
319
+ carrying(id) {
320
+ return this.flags.findIndex((f) => f.state === FLAG.CARRIED && f.by === id);
321
+ }
322
+ /** The winning team of a match that is over, or -1 for a draw. */
323
+ winner() {
324
+ const [r, b] = this.score;
325
+ return r > b ? 0 : b > r ? 1 : -1;
326
+ }
327
+ /** What every player has done this match. */
328
+ tally() {
329
+ return [...this.mates].map(([id, m]) => ({
330
+ id,
331
+ caps: m.caps,
332
+ returns: m.returns
333
+ }));
334
+ }
335
+ /** The room is empty: the next match starts from scratch. */
336
+ reset() {
337
+ this.over = false;
338
+ this.score = [0, 0];
339
+ this.flags = [home(), home()];
340
+ this.back = [0, 0];
341
+ this.lock.forEach((l) => l.left = 0);
342
+ this.clock = this.rules.timeLimit * 60;
343
+ for (const m of this.mates.values()) m.caps = m.returns = 0;
344
+ }
345
+ /** The part of a snapshot that is the match's. */
346
+ wire() {
347
+ return {
348
+ score: [...this.score],
349
+ clock: Math.ceil(this.clock / 60),
350
+ over: this.over,
351
+ flags: this.flags.map((f) => ({ ...f }))
352
+ };
353
+ }
354
+ /**
355
+ * One host tick over the players: the dropped flags run down, flags are taken, returned and
356
+ * captured, the clock runs. 'end' when the match has just ended, 'start' when the end screen is
357
+ * done and a new match begins (the room puts everyone back at a spawn).
358
+ */
359
+ tick(players) {
360
+ if (this.over) {
361
+ if (--this.clock <= 0) {
362
+ this.reset();
363
+ return "start";
364
+ }
365
+ return;
366
+ }
367
+ for (const k of [0, 1]) {
368
+ const f = this.flags[k];
369
+ this.lock[k].left--;
370
+ if (f.state === FLAG.DROPPED) {
371
+ f.left = Math.ceil(--this.back[k] / 60);
372
+ if (this.back[k] <= 0) this.flags[k] = home();
373
+ }
374
+ }
375
+ for (const k of [0, 1]) {
376
+ const f = this.flags[k];
377
+ if (f.state === FLAG.CARRIED) continue;
378
+ const at = f.state === FLAG.HOME ? this.world.def.teams[k].base : [
379
+ f.x,
380
+ f.y,
381
+ f.z
382
+ ];
383
+ const near = players.filter((q) => touches(q.state, at));
384
+ const mate = f.state === FLAG.DROPPED ? near.find((q) => q.team === k) : void 0;
385
+ const foe = near.find((q) => q.team !== k && (q.id !== this.lock[k].id || this.lock[k].left <= 0));
386
+ if (mate) {
387
+ const m = this.mates.get(mate.id);
388
+ if (m) m.returns++;
389
+ this.flags[k] = home();
390
+ } else if (foe) this.flags[k] = {
391
+ ...home(),
392
+ state: FLAG.CARRIED,
393
+ by: foe.id
394
+ };
395
+ }
396
+ for (const p of players) {
397
+ const k = this.carrying(p.id);
398
+ if (k >= 0 && this.flags[p.team].state === FLAG.HOME && touches(p.state, this.world.def.teams[p.team].base)) {
399
+ this.score[p.team]++;
400
+ const m = this.mates.get(p.id);
401
+ if (m) m.caps++;
402
+ this.flags[k] = home();
403
+ }
404
+ }
405
+ if (this.score.some((s) => s >= this.rules.scoreLimit) || --this.clock <= 0) {
406
+ this.over = true;
407
+ this.clock = 600;
408
+ return "end";
409
+ }
410
+ }
411
+ dropAt(k, [x, y, z]) {
412
+ this.flags[k] = {
413
+ state: FLAG.DROPPED,
414
+ by: 0,
415
+ x,
416
+ y,
417
+ z,
418
+ left: 10
419
+ };
420
+ this.back[k] = 600;
421
+ }
422
+ };
423
+ /** Whether the player's body reaches the flag foot at `at`: close enough, and overlapping its height. */
424
+ var touches = (p, at) => Math.hypot(p.x - at[0], p.z - at[2]) < 1.5 && p.y < at[1] + 2.2 && p.y + 1.8 > at[1];
103
425
  // src/shared/map.ts
104
426
  /** The bottom of every building: far below the kill floor, so nothing shows beneath a roof. */
105
427
  var BASE = -30;
@@ -157,7 +479,7 @@ var stair = (z, y) => [
157
479
  * sprint jump 6.3 m, and reaches a box 1.7 m high; the hands catch a top 1.2 to 2.4 m above the
158
480
  * feet, and a fall that reaches a face within about 3.5 m is caught by them.
159
481
  *
160
- * - A: the start roof (10 m), with the spawns. B: a roof at 10 m, across a 4.2 m gap from A (a
482
+ * - A: the start roof (10 m), red's base, with its spawns. B: a roof at 10 m, across a 4.2 m gap from A (a
161
483
  * run and a jump: walking off the edge falls).
162
484
  * - On B, a platform floating at 12.2 to 12.6 m (an overhang to walk under, a bump for a jump) and
163
485
  * a stair of six 0.4 m steps up to it. 3 m north of it, C (12.4 m): the south face of C above B
@@ -167,6 +489,8 @@ var stair = (z, y) => [
167
489
  * - G (8 m) is across a 10 m drop from E, reached by a 0.5 m wide beam; it has a 1.6 m ledge.
168
490
  * - F (12.4 m) is 13 m north of C: a sprint and a jump fall short of it, and so does a walk with
169
491
  * the dash or the double jump; it takes the sprint and the jump and the dash or the double jump.
492
+ * F is blue's base, with its spawns: the flags are 90 m and the chasm apart, and the way back is
493
+ * the same line in reverse, then a drop to B and the A gap jumped south.
170
494
  */
171
495
  var ROOFTOPS = {
172
496
  name: "Rooftops",
@@ -277,56 +601,119 @@ var ROOFTOPS = {
277
601
  68
278
602
  ], TEX.STONE, TEX.BRICK)
279
603
  ],
280
- spawns: [
281
- [
282
- 6,
283
- 10,
284
- 72,
285
- 0
286
- ],
287
- [
288
- 10,
289
- 10,
290
- 72,
291
- 0
292
- ],
293
- [
604
+ teams: [{
605
+ base: [
294
606
  14,
295
607
  10,
296
- 72,
297
- 0
298
- ],
299
- [
300
- 18,
301
- 10,
302
- 72,
303
- 0
304
- ],
305
- [
306
- 22,
307
- 10,
308
- 72,
309
- 0
310
- ],
311
- [
312
- 8,
313
- 10,
314
- 66,
315
- 0
608
+ 62.5
316
609
  ],
317
- [
610
+ spawns: [
611
+ [
612
+ 6,
613
+ 10,
614
+ 72,
615
+ 0
616
+ ],
617
+ [
618
+ 10,
619
+ 10,
620
+ 72,
621
+ 0
622
+ ],
623
+ [
624
+ 14,
625
+ 10,
626
+ 72,
627
+ 0
628
+ ],
629
+ [
630
+ 18,
631
+ 10,
632
+ 72,
633
+ 0
634
+ ],
635
+ [
636
+ 22,
637
+ 10,
638
+ 72,
639
+ 0
640
+ ],
641
+ [
642
+ 8,
643
+ 10,
644
+ 66,
645
+ 0
646
+ ],
647
+ [
648
+ 14,
649
+ 10,
650
+ 66,
651
+ 0
652
+ ],
653
+ [
654
+ 20,
655
+ 10,
656
+ 66,
657
+ 0
658
+ ]
659
+ ]
660
+ }, {
661
+ base: [
318
662
  14,
319
- 10,
320
- 66,
321
- 0
663
+ 12.4,
664
+ 2.2
322
665
  ],
323
- [
324
- 20,
325
- 10,
326
- 66,
327
- 0
666
+ spawns: [
667
+ [
668
+ 6,
669
+ 12.4,
670
+ -3,
671
+ Math.PI
672
+ ],
673
+ [
674
+ 10,
675
+ 12.4,
676
+ -3,
677
+ Math.PI
678
+ ],
679
+ [
680
+ 14,
681
+ 12.4,
682
+ -3,
683
+ Math.PI
684
+ ],
685
+ [
686
+ 18,
687
+ 12.4,
688
+ -3,
689
+ Math.PI
690
+ ],
691
+ [
692
+ 22,
693
+ 12.4,
694
+ -3,
695
+ Math.PI
696
+ ],
697
+ [
698
+ 8,
699
+ 12.4,
700
+ .5,
701
+ Math.PI
702
+ ],
703
+ [
704
+ 14,
705
+ 12.4,
706
+ .5,
707
+ Math.PI
708
+ ],
709
+ [
710
+ 20,
711
+ 12.4,
712
+ .5,
713
+ Math.PI
714
+ ]
328
715
  ]
329
- ],
716
+ }],
330
717
  floor: -25,
331
718
  sun: {
332
719
  dir: [
@@ -356,41 +743,6 @@ var ROOFTOPS = {
356
743
  .008
357
744
  ]
358
745
  };
359
- // src/shared/world.ts
360
- /** Metres per grid cell: about the size of the player's reach, so a query touches 1 to 4 cells. */
361
- var CELL = 4;
362
- /** Cell coordinates run from -OFF to OFF - 1: a 8 km square at 4 m, far more than any map. */
363
- var OFF = 1024;
364
- /** The key of the cell with integer coordinates (cx, cz). */
365
- var key = (cx, cz) => (cx + OFF) * (2 * OFF) + cz + OFF;
366
- /** Integer cell coordinate of a metre value, clamped to the keyed range. */
367
- var at = (v, cell) => Math.min(Math.max(Math.floor(v / cell), -1024), 1023);
368
- /** Builds the grid: each brush is listed in every cell its footprint covers. */
369
- var build = (def, cell = CELL) => {
370
- const grid = /* @__PURE__ */ new Map();
371
- def.brushes.forEach(({ min, max }, i) => {
372
- for (let cx = at(min[0], cell); cx <= at(max[0], cell); cx++) for (let cz = at(min[2], cell); cz <= at(max[2], cell); cz++) {
373
- const k = key(cx, cz);
374
- const list = grid.get(k);
375
- if (list) list.push(i);
376
- else grid.set(k, [i]);
377
- }
378
- });
379
- return {
380
- def,
381
- cell,
382
- grid
383
- };
384
- };
385
- /**
386
- * Indices of the brushes whose footprint may overlap the square of half side r around (x, z): every
387
- * brush listed in a cell the square touches, once each. A candidate list, not an exact overlap.
388
- */
389
- var near = (w, x, z, r) => {
390
- const out = [];
391
- for (let cx = at(x - r, w.cell); cx <= at(x + r, w.cell); cx++) for (let cz = at(z - r, w.cell); cz <= at(z + r, w.cell); cz++) for (const i of w.grid.get(key(cx, cz)) ?? []) if (!out.includes(i)) out.push(i);
392
- return out;
393
- };
394
746
  // src/shared/physics.ts
395
747
  var DT = 1 / 60;
396
748
  var TAU = Math.PI * 2;
@@ -441,9 +793,9 @@ var STILL = {
441
793
  ev: 0,
442
794
  fall: 0
443
795
  };
444
- /** A player standing on spawn point n of the world (modulo the count). */
445
- var spawn = (id, w, n) => {
446
- const { spawns } = w.def;
796
+ /** A player standing on spawn point n of a team (modulo the count): the red team's by default. */
797
+ var spawn = (id, w, n, team = 0) => {
798
+ const { spawns } = w.def.teams[team];
447
799
  const [x, y, z, yaw] = spawns[(n % spawns.length + spawns.length) % spawns.length];
448
800
  return {
449
801
  id,
@@ -993,9 +1345,9 @@ var air = (p, w, c, burst) => {
993
1345
  /**
994
1346
  * Applies one input for 1 / TICK_HZ s, in place: yaw and pitch from the input (pitch clamped to
995
1347
  * MAX_PITCH), then the step of the current mode (see the top of the file). Feet under the world's
996
- * kill floor put the player back at a spawn.
1348
+ * kill floor put the player back at a spawn of his `team` (EV.RESPAWN).
997
1349
  */
998
- var move = (p, i, w) => {
1350
+ var move = (p, i, w, team = 0) => {
999
1351
  p.yaw = norm(i.yaw);
1000
1352
  p.pitch = Math.max(-MAX_PITCH, Math.min(MAX_PITCH, i.pitch));
1001
1353
  const f = (i.keys & KEY.FORWARD ? 1 : 0) - (i.keys & KEY.BACK ? 1 : 0);
@@ -1026,9 +1378,10 @@ var move = (p, i, w) => {
1026
1378
  else if (p.mode !== MODE.HANG) free(p, w, c);
1027
1379
  if (p.y < w.def.floor) {
1028
1380
  const { yaw, pitch, id } = p;
1029
- Object.assign(p, spawn(id, w, id), {
1381
+ Object.assign(p, spawn(id, w, id, team), {
1030
1382
  yaw,
1031
- pitch
1383
+ pitch,
1384
+ ev: p.ev | EV.RESPAWN
1032
1385
  });
1033
1386
  }
1034
1387
  p.t = p.mode === before ? Math.min(255, p.t + 1) : p.t;
@@ -1044,6 +1397,8 @@ var move = (p, i, w) => {
1044
1397
  p.vz = f32(p.vz);
1045
1398
  p.edge = f32(p.edge);
1046
1399
  };
1400
+ /** A flag's resting place on the wire: 1/16 m in an i16, so ±2 km. */
1401
+ var POS = 16;
1047
1402
  var TURN = 65536 / (2 * Math.PI);
1048
1403
  /** Radians to 65536ths of a turn; the mask also folds negative and ≥ 2π angles into one turn. */
1049
1404
  var toTurn = (yaw) => Math.round(yaw * TURN) & 65535;
@@ -1065,8 +1420,11 @@ var decodeInput = (buf) => {
1065
1420
  view: (v.getUint16(8) * 256 + v.getUint8(10)) / 256
1066
1421
  };
1067
1422
  };
1423
+ /** Bytes of a flag on the wire, by its state. */
1424
+ var flagBytes = (state) => state === FLAG.CARRIED ? 2 : state === FLAG.DROPPED ? 8 : 1;
1068
1425
  var encodeSnapshot = (s) => {
1069
- const v = /* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(4 + 39 * s.players.length));
1426
+ const end = 4 + 39 * s.players.length;
1427
+ const v = new DataView(new ArrayBuffer(end + 4 + s.flags.reduce((n, f) => n + flagBytes(f.state), 0)));
1070
1428
  v.setUint8(0, 2);
1071
1429
  v.setUint16(1, s.tick & 65535);
1072
1430
  v.setUint8(3, s.players.length);
@@ -1088,6 +1446,21 @@ var encodeSnapshot = (s) => {
1088
1446
  v.setUint8(o + 37, p.dash);
1089
1447
  v.setUint8(o + 38, p.coyote & 7 | (p.buffer & 7) << 3 | (p.held & KEY.JUMP ? 64 : 0) | (p.held & KEY.DASH ? 128 : 0));
1090
1448
  });
1449
+ v.setUint8(end, s.score[0]);
1450
+ v.setUint8(end + 1, s.score[1]);
1451
+ v.setUint16(end + 2, s.clock & 32767 | (s.over ? 32768 : 0));
1452
+ let o = end + 4;
1453
+ for (const f of s.flags) {
1454
+ v.setUint8(o, f.state);
1455
+ if (f.state === FLAG.CARRIED) v.setUint8(o + 1, f.by);
1456
+ else if (f.state === FLAG.DROPPED) {
1457
+ v.setInt16(o + 1, clamp16(f.x * POS));
1458
+ v.setInt16(o + 3, clamp16(f.y * POS));
1459
+ v.setInt16(o + 5, clamp16(f.z * POS));
1460
+ v.setUint8(o + 7, Math.min(255, f.left));
1461
+ }
1462
+ o += flagBytes(f.state);
1463
+ }
1091
1464
  return v.buffer;
1092
1465
  };
1093
1466
  /** Returns null on anything that is not a known text message. */
@@ -1104,24 +1477,6 @@ var parseText = (raw) => {
1104
1477
  var MAX_CATCH_UP = 20;
1105
1478
  /** A new player does not spawn within this many metres of another one. */
1106
1479
  var SPAWN_CLEAR = 2;
1107
- var COLORS = [
1108
- "#e6194b",
1109
- "#3cb44b",
1110
- "#ffe119",
1111
- "#4363d8",
1112
- "#f58231",
1113
- "#911eb4",
1114
- "#42d4f4",
1115
- "#f032e6",
1116
- "#bfef45",
1117
- "#fabed4",
1118
- "#469990",
1119
- "#dcbeff",
1120
- "#9a6324",
1121
- "#800000",
1122
- "#aaffc3",
1123
- "#808000"
1124
- ];
1125
1480
  /** First n characters (code points) of s, trimmed. */
1126
1481
  var cut = (s, n) => Array.from(s).slice(0, n).join("").trim();
1127
1482
  var cleanName = (raw) => cut((typeof raw === "string" ? raw : "").replace(/\s+/g, " ").replace(/\p{Cc}/gu, "").trim(), 16);
@@ -1139,13 +1494,18 @@ var setEvery = (cb, ms) => {
1139
1494
  * One game, transport-agnostic. The Node server and the local host tab both drive a Room: they
1140
1495
  * feed it connections and frames, the room answers through Conn.send.
1141
1496
  *
1142
- * - A peer joins with { t: 'join', name }: unique name (`Bob 2`), unique colour, a spawn point not
1143
- * taken by another player; 'full' beyond rules.maxPlayers. Everyone gets a fresh 'roster' on
1144
- * every join and leave.
1497
+ * - A peer joins with { t: 'join', name }: unique name (`Bob 2`), the smaller team (red on a tie)
1498
+ * and its colour, a spawn point of the team not taken by another player; 'full' beyond
1499
+ * rules.maxPlayers. Everyone gets a fresh 'roster' on every join and leave. Teams are not
1500
+ * rebalanced when someone leaves: the next join fills the smaller one.
1145
1501
  * - Each input frame moves its player at once with move(); the INPUT_BURST bank drops the excess.
1146
1502
  * rewind() answers where the others were drawn at the view tick of an input (lag compensation,
1147
1503
  * at most MAX_REWIND ticks back).
1148
- * - Every SNAP_EVERY ticks of TICK_HZ, one snapshot with every player goes to every peer.
1504
+ * - Every SNAP_EVERY ticks of TICK_HZ, one snapshot with every player, the score, the clock and
1505
+ * the two flags goes to every peer. The flag rules and the match are ctf.ts's: a match ends at
1506
+ * rules.scoreLimit or rules.timeLimit ('end' text to everyone), the end screen runs END_SCREEN
1507
+ * seconds, then everyone is put back at a spawn of his team and the score starts again.
1508
+ * drop(id) makes a carrier drop the flag: the hook of the tackle (step 7).
1149
1509
  */
1150
1510
  var Room = class {
1151
1511
  /** Every connected peer; null until it joins. */
@@ -1154,10 +1514,11 @@ var Room = class {
1154
1514
  /** The players as each snapshot of the last MAX_REWIND ticks sent them. */
1155
1515
  history = [];
1156
1516
  world;
1517
+ ctf;
1157
1518
  halt;
1158
1519
  rules;
1159
- /** Round-robin cursor over the spawn points, used once they are all taken. */
1160
- rr = 0;
1520
+ /** Round-robin cursor over the spawn points of each team, used once they are all taken. */
1521
+ rr = [0, 0];
1161
1522
  /** Missing rules fall back to RULES. */
1162
1523
  constructor(rules = {}, map = ROOFTOPS) {
1163
1524
  this.rules = {
@@ -1165,6 +1526,7 @@ var Room = class {
1165
1526
  ...rules
1166
1527
  };
1167
1528
  this.world = build(map);
1529
+ this.ctf = new Ctf(this.world, this.rules);
1168
1530
  }
1169
1531
  /** Number of joined players. */
1170
1532
  get size() {
@@ -1185,7 +1547,8 @@ var Room = class {
1185
1547
  const input = p && decodeInput(data);
1186
1548
  if (input && p.bank > 0) {
1187
1549
  p.bank--;
1188
- move(p.state, input, this.world);
1550
+ move(p.state, input, this.world, p.info.team);
1551
+ this.ctf.moved(p.state);
1189
1552
  p.ack = input.seq;
1190
1553
  }
1191
1554
  }
@@ -1193,7 +1556,19 @@ var Room = class {
1193
1556
  disconnect(conn) {
1194
1557
  const p = this.peers.get(conn);
1195
1558
  this.peers.delete(conn);
1196
- if (p) this.roster();
1559
+ if (p) {
1560
+ this.ctf.leave(p.info.id);
1561
+ if (!this.size) this.ctf.reset();
1562
+ this.roster();
1563
+ }
1564
+ }
1565
+ /**
1566
+ * Makes the player `id` drop the flag he carries, where he stands (the tackle of step 7).
1567
+ * False when he carries none or is not there.
1568
+ */
1569
+ drop(id) {
1570
+ const p = this.players().find((q) => q.info.id === id);
1571
+ return !!p && this.ctf.drop(p.state);
1197
1572
  }
1198
1573
  /** One host tick. Public so tests can drive the room without a timer. */
1199
1574
  tick() {
@@ -1201,6 +1576,13 @@ var Room = class {
1201
1576
  if (!players.length) return;
1202
1577
  const now = ++this.ticks;
1203
1578
  for (const p of players) p.bank = Math.min(10, p.bank + 1);
1579
+ const turn = this.ctf.tick(players.map((p) => ({
1580
+ id: p.info.id,
1581
+ team: p.info.team,
1582
+ state: p.state
1583
+ })));
1584
+ if (turn === "end") this.end(players);
1585
+ else if (turn === "start") this.restart(players);
1204
1586
  if (now % 2 === 0) {
1205
1587
  this.history.push({
1206
1588
  tick: now,
@@ -1212,7 +1594,8 @@ var Room = class {
1212
1594
  players: players.map((p) => ({
1213
1595
  ...p.state,
1214
1596
  ack: p.ack
1215
- }))
1597
+ })),
1598
+ ...this.ctf.wire()
1216
1599
  });
1217
1600
  players.forEach((p) => p.conn.send(snap));
1218
1601
  }
@@ -1272,13 +1655,40 @@ var Room = class {
1272
1655
  } : pb ?? pa ?? p;
1273
1656
  });
1274
1657
  }
1275
- /** The first spawn point with none of `others` within SPAWN_CLEAR, else the next one round-robin. */
1276
- place(id, others) {
1277
- const n = this.world.def.spawns.findIndex((_, k) => {
1278
- const { x, z } = spawn(id, this.world, k);
1658
+ /** The first spawn point of the team with none of `others` within SPAWN_CLEAR, else the next one round-robin. */
1659
+ place(id, team, others) {
1660
+ const n = this.world.def.teams[team].spawns.findIndex((_, k) => {
1661
+ const { x, z } = spawn(id, this.world, k, team);
1279
1662
  return !others.some((o) => Math.hypot(o.x - x, o.z - z) < SPAWN_CLEAR);
1280
1663
  });
1281
- return spawn(id, this.world, n < 0 ? this.rr++ : n);
1664
+ return spawn(id, this.world, n < 0 ? this.rr[team]++ : n, team);
1665
+ }
1666
+ /** The match is over: everyone gets the result and what each player did. */
1667
+ end(players) {
1668
+ const tally = this.ctf.tally().flatMap((t) => {
1669
+ const info = players.find((p) => p.info.id === t.id)?.info;
1670
+ return info ? [{
1671
+ ...t,
1672
+ name: info.name,
1673
+ team: info.team
1674
+ }] : [];
1675
+ });
1676
+ const msg = JSON.stringify({
1677
+ t: "end",
1678
+ score: this.ctf.score,
1679
+ players: tally
1680
+ });
1681
+ players.forEach((p) => p.conn.send(msg));
1682
+ }
1683
+ /** A new match: everyone back at a spawn of his team. */
1684
+ restart(players) {
1685
+ const put = [];
1686
+ this.rr = [0, 0];
1687
+ for (const p of players) {
1688
+ p.state = this.place(p.info.id, p.info.team, put);
1689
+ put.push(p.state);
1690
+ this.ctf.place(p.info.id, p.state);
1691
+ }
1282
1692
  }
1283
1693
  players() {
1284
1694
  return [...this.peers.values()].filter((p) => p !== null);
@@ -1291,19 +1701,22 @@ var Room = class {
1291
1701
  }
1292
1702
  let id = 0;
1293
1703
  while (players.some((p) => p.info.id === id)) id++;
1294
- const color = COLORS.find((c) => !players.some((p) => p.info.color === c)) ?? COLORS[id % COLORS.length];
1704
+ const reds = players.filter((p) => p.info.team === 0).length;
1705
+ const team = reds > players.length - reds ? 1 : 0;
1295
1706
  const player = {
1296
1707
  conn,
1297
1708
  info: {
1298
1709
  id,
1299
1710
  name: unique(cleanName(name) || `Player ${id}`, players.map((p) => p.info.name)),
1300
- color
1711
+ team,
1712
+ color: TEAM_COLOR[team]
1301
1713
  },
1302
- state: this.place(id, players.map((p) => p.state)),
1714
+ state: this.place(id, team, players.map((p) => p.state)),
1303
1715
  bank: 10,
1304
1716
  ack: 65535
1305
1717
  };
1306
1718
  this.peers.set(conn, player);
1719
+ this.ctf.join(id, team, player.state);
1307
1720
  this.roster();
1308
1721
  }
1309
1722
  /** Each joined peer gets the full roster with its own id. */