t1181: start outgoing flights locally, retarget on server result, flush shots early
@@ -1406,8 +1406,14 @@ function tickOnline (dt)
1406
1406
var s = shots[i];
1407
1407
var start = fieldToViewport(s.col, s.y);
1408
1408
Online.rememberFlightLocal(s, start.x, start.y);
1409
// Draw the flight locally right away (t1181); the server
1410
// answer only retargets it.
1411
if (Online.startLocalShot)
1412
{ Online.startLocalShot(s, start); }
1409
1413
}
1410
1414
Online.queueShots(shots);
1415
if (shots.length && Online.flushShotsSoon)
1416
{ Online.flushShotsSoon(); }
1411
1417
}
1412
1418
Online.tickFlights();
1413
1419
Online.renderMinis(document.getElementById('minis'));
@@ -1859,8 +1865,12 @@ function onlinePayload ()
1859
1865
{
1860
1866
if (!app.online || !app.core)
1861
1867
{ return {}; }
1868
var snap = app.core.fieldSnapshot();
1869
// t1182: sender time (ms) so opponents can place the snapshot in
1870
// time and predict falling blocks smoothly. Visual only.
1871
snap.t = Math.round(typeof performance !== 'undefined' ? performance.now() : Date.now());
1862
1872
return {
1863
snapshot: app.core.fieldSnapshot(),
1873
snapshot: snap,
1864
1874
score: app.core.score,
1865
1875
eliminated: app.core.state === 'gameover' || app.spectating || app.eliminatedReported
1866
1876
};
@@ -1406,8 +1406,14 @@ function tickOnline (dt)1406
var s = shots[i];1406
var s = shots[i];1407
var start = fieldToViewport(s.col, s.y);1407
var start = fieldToViewport(s.col, s.y);1408
Online.rememberFlightLocal(s, start.x, start.y);1408
Online.rememberFlightLocal(s, start.x, start.y);1409
// Draw the flight locally right away (t1181); the server1410
// answer only retargets it.1411
if (Online.startLocalShot)1412
{ Online.startLocalShot(s, start); }1409
}1413
}1410
Online.queueShots(shots);1414
Online.queueShots(shots);1415
if (shots.length && Online.flushShotsSoon)1416
{ Online.flushShotsSoon(); }1411
}1417
}1412
Online.tickFlights();1418
Online.tickFlights();1413
Online.renderMinis(document.getElementById('minis'));1419
Online.renderMinis(document.getElementById('minis'));@@ -1859,8 +1865,12 @@ function onlinePayload ()1859
{1865
{1860
if (!app.online || !app.core)1866
if (!app.online || !app.core)1861
{ return {}; }1867
{ return {}; }1868
var snap = app.core.fieldSnapshot();1869
// t1182: sender time (ms) so opponents can place the snapshot in1870
// time and predict falling blocks smoothly. Visual only.1871
snap.t = Math.round(typeof performance !== 'undefined' ? performance.now() : Date.now());1862
return {1872
return {1863
snapshot: app.core.fieldSnapshot(),1873
snapshot: snap,1864
score: app.core.score,1874
score: app.core.score,1865
eliminated: app.core.state === 'gameover' || app.spectating || app.eliminatedReported1875
eliminated: app.core.state === 'gameover' || app.spectating || app.eliminatedReported1866
};1876
};@@ -24,6 +24,10 @@ var Online = {
24
24
error: '',
25
25
_timer: null,
26
26
_pendingShots: [],
27
_pollInFlight: false,
28
_flushPending: false,
29
_lastPollAt: 0,
30
_getPayload: null,
27
31
_flights: [],
28
32
_lastStatus: null,
29
33
onChange: null,
@@ -235,8 +239,16 @@ Online.poll = function (opts)
235
239
}
236
240
var self = this;
237
241
var prevStatus = this.lobby && this.lobby.status;
242
this._pollInFlight = true;
243
this._lastPollAt = Date.now();
238
244
return this.request('poll', body).then(function (data)
239
245
{
246
self._pollInFlight = false;
247
if (self._flushPending)
248
{
249
self._flushPending = false;
250
self.flushShotsSoon();
251
}
240
252
self._handleTransitions(prevStatus, data);
241
253
if (self.onChange)
242
254
{ self.onChange(self); }
@@ -271,6 +283,7 @@ Online.startPolling = function (getPayload)
271
283
{
272
284
this.stopPolling();
273
285
var self = this;
286
this._getPayload = getPayload || null;
274
287
var tick = function ()
275
288
{
276
289
var payload = getPayload ? getPayload() : {};
@@ -280,8 +293,68 @@ Online.startPolling = function (getPayload)
280
293
this._timer = setInterval(tick, this.POLL_MS);
281
294
};
282
295
296
/** Minimum gap between an extra shot flush and the previous poll (ms). */
297
Online.FLUSH_MIN_GAP_MS = 120;
298
299
/**
300
* Pure decision for flushShotsSoon (t1181): 'now', 'later' (wait for the
301
* in-flight poll or the min gap) or 'none' (nothing to send / not polling).
302
*/
303
Online.flushDecision = function (state)
304
{
305
if (!state || !state.polling || !(state.pending > 0))
306
{ return 'none'; }
307
if (state.inFlight)
308
{ return 'later'; }
309
if (state.sinceLast < (state.minGap != null ? state.minGap : this.FLUSH_MIN_GAP_MS))
310
{ return 'later'; }
311
return 'now';
312
};
313
314
/**
315
* Send freshly cleared shots on the next possible poll instead of up to
316
* POLL_MS later, so the server's hit/miss result (and the retarget of the
317
* local flight) arrives in about one round trip. Network cadence only;
318
* the server still decides hits, targets and delivery (t1181).
319
*/
320
Online.flushShotsSoon = function ()
321
{
322
var self = this;
323
var d = this.flushDecision({
324
polling: !!this._timer,
325
pending: this._pendingShots.length,
326
inFlight: this._pollInFlight,
327
sinceLast: Date.now() - (this._lastPollAt || 0)
328
});
329
if (d === 'none')
330
{ return d; }
331
if (d === 'later')
332
{
333
if (this._pollInFlight)
334
{ this._flushPending = true; }
335
else if (!this._flushTimer)
336
{
337
var wait = Math.max(0, this.FLUSH_MIN_GAP_MS - (Date.now() - (this._lastPollAt || 0)));
338
this._flushTimer = setTimeout(function ()
339
{
340
self._flushTimer = null;
341
self.flushShotsSoon();
342
}, wait);
343
}
344
return d;
345
}
346
this.poll(this._getPayload ? this._getPayload() : {});
347
return d;
348
};
349
283
350
Online.stopPolling = function ()
284
351
{
352
if (this._flushTimer)
353
{
354
clearTimeout(this._flushTimer);
355
this._flushTimer = null;
356
}
357
this._flushPending = false;
285
358
if (this._timer)
286
359
{
287
360
clearInterval(this._timer);
@@ -383,7 +456,7 @@ Online.renderMinis = function (container)
383
456
? I18n.t('hud.miniPoints', { n: p.score || 0 })
384
457
: ('Points ' + (p.score || 0));
385
458
}
386
this._drawMini(el.querySelector('canvas'), p.snapshot, p.planet);
459
this._drawMini(el.querySelector('canvas'), p.snapshot, p.planet, this._predictMini(p));
387
460
}
388
461
for (var id in existing)
389
462
{
@@ -404,7 +477,28 @@ function miniColor (planet, color)
404
477
}
405
478
406
479
407
Online._drawMini = function (canvas, snapshot, planet)
480
/**
481
* t1182: smoothed display y for an opponent's falling blocks (see
482
* src/miniPredict.js). Returns id → y, or null without the module.
483
*/
484
Online._predictMini = function (p, now)
485
{
486
var MP = typeof MiniPredict !== 'undefined' ? MiniPredict : null;
487
if (!MP || !p)
488
{ return null; }
489
if (!this._miniPredict)
490
{ this._miniPredict = Object.create(null); }
491
var st = this._miniPredict[p.id];
492
if (!st)
493
{ st = this._miniPredict[p.id] = MP.create(); }
494
now = now != null ? now : (typeof performance !== 'undefined' ? performance.now() : Date.now());
495
MP.update(st, p.snapshot, now);
496
if (p.eliminated)
497
{ return null; }
498
return MP.step(st, now, MP.fallSpeedFor(p.planet));
499
};
500
501
Online._drawMini = function (canvas, snapshot, planet, shownY)
408
502
{
409
503
if (!canvas)
410
504
{ return; }
@@ -451,7 +545,8 @@ Online._drawMini = function (canvas, snapshot, planet)
451
545
{
452
546
var b = blocks[i];
453
547
var x = b.col * tw;
454
var y = canvas.height - (b.y + 1) * th;
548
var by = (shownY && shownY[b.id] != null) ? shownY[b.id] : b.y;
549
var y = canvas.height - (by + 1) * th;
455
550
if (b.state === 'locked')
456
551
{ ctx.fillStyle = '#3a3d4a'; }
457
552
else if (b.color < 0)
@@ -1264,6 +1359,17 @@ Online.spawnFlights = function (results, locals)
1264
1359
{
1265
1360
var r = results[i];
1266
1361
var sid = String(r.id != null ? r.id : (r.client_id || ('tmp-' + i)));
1362
// Own shot already flying locally since the clear (t1181):
1363
// pick it up at its current pose and fly on to the real target.
1364
var cid = r.client_id != null ? String(r.client_id) : null;
1365
if (cid && this._previewIds[cid] && this._isOwnShot(r))
1366
{
1367
var own = this._findFlight(cid);
1368
this._flightSeen[sid] = now;
1369
if (own)
1370
{ this.retargetFlight(own, r, locals[cid] || {}, now); }
1371
continue;
1372
}
1267
1373
if (this._flightSeen[sid])
1268
1374
{
1269
1375
if (this._previewIds[sid])
@@ -1369,12 +1475,11 @@ Online.spawnFlights = function (results, locals)
1369
1475
el.style.height = full + 'px';
1370
1476
layer.appendChild(el);
1371
1477
1478
// A flight seen late (poll delay) still starts at the sender's
1479
// field and plays the whole arc, just a bit faster, so it lands
1480
// about when the server delivers it — never a mid-arc pop-in (t1181).
1372
1481
var t0 = now;
1373
if (r.age != null && isFinite(r.age) && r.age > 0)
1374
{
1375
var u0 = Math.min(0.95, (r.age * 1000) / duration);
1376
t0 = now - u0 * duration;
1377
}
1482
duration = this.lateFlightDuration(r.age, duration);
1378
1483
var height = miss
1379
1484
? Math.max(40, Math.min(160, Math.abs(end.y - start.y) * 0.35))
1380
1485
: this.arcHeight(start, end);
@@ -1411,6 +1516,52 @@ Online.spawnFlights = function (results, locals)
1411
1516
this._flightLocals = {};
1412
1517
};
1413
1518
1519
/** Shortest share of the normal flight a late-seen flight may get. */
1520
Online.LATE_MIN_SHARE = 0.5;
1521
1522
/** Duration (ms) for a flight first seen `age` seconds after it was fired. */
1523
Online.lateFlightDuration = function (age, duration)
1524
{
1525
if (age == null || !isFinite(age) || age <= 0)
1526
{ return duration; }
1527
return Math.max(duration * this.LATE_MIN_SHARE, duration - age * 1000);
1528
};
1529
1530
/** Remaining duration (ms) after a local preview has flown `elapsedMs`. */
1531
Online.retargetDuration = function (elapsedMs, duration)
1532
{
1533
if (!(elapsedMs > 0))
1534
{ return duration; }
1535
return Math.max(duration * this.LATE_MIN_SHARE, duration - elapsedMs);
1536
};
1537
1538
Online._isOwnShot = function (r)
1539
{
1540
var mine = this.me && this.me.id;
1541
var from = r.from_id || r.from_user || null;
1542
return !from || (mine != null && String(from) === String(mine));
1543
};
1544
1545
/**
1546
* Sender side (t1181): start the flight the moment the block leaves the
1547
* field, before any server round trip. It rises out of the exit cell;
1548
* the poll answer retargets it (hit → opponent mini, miss → off-screen).
1549
*/
1550
Online.startLocalShot = function (shot, start)
1551
{
1552
if (!shot || !start)
1553
{ return null; }
1554
return this.previewExit({
1555
id: shot.id,
1556
col: shot.col,
1557
y: shot.y,
1558
vy: shot.vy,
1559
color: shot.color,
1560
start: start,
1561
from_id: null
1562
});
1563
};
1564
1414
1565
Online.rememberFlightLocal = function (shot, startX, startY)
1415
1566
{
1416
1567
if (!this._flightLocals)
@@ -1577,6 +1728,7 @@ Online.previewExit = function (info)
1577
1728
});
1578
1729
this._previewIds[sid] = true;
1579
1730
this._flightSeen[sid] = now;
1731
return true;
1580
1732
};
1581
1733
1582
1734
/** True while a field sprite should stay hidden — the flight is its visual. */
@@ -1618,6 +1770,8 @@ Online.retargetFlight = function (f, r, meta, now)
1618
1770
var miss = !!r.miss;
1619
1771
var kind = this.flightKind(fromId, targetId, miss);
1620
1772
var duration = (r.flight_duration || this.FLIGHT_DURATION) * 1000;
1773
if (f.preview)
1774
{ duration = this.retargetDuration(now - f.t0, duration); }
1621
1775
1622
1776
var landCol = null;
1623
1777
if (r.land_col != null && isFinite(r.land_col))
@@ -1734,6 +1888,9 @@ Online.pointAllowedOnArc = function (p, field, start, end, slop)
1734
1888
return false;
1735
1889
};
1736
1890
1891
/** How long a local preview may wait at its apex for the server (ms). */
1892
Online.PREVIEW_HOLD_MS = 2500;
1893
1737
1894
Online.tickFlights = function (now)
1738
1895
{
1739
1896
now = now || performance.now();
@@ -1742,6 +1899,8 @@ Online.tickFlights = function (now)
1742
1899
{
1743
1900
var f = this._flights[i];
1744
1901
var raw = (now - f.t0) / f.duration;
1902
if (f.preview && raw >= 0.999 && now - f.t0 < f.duration + this.PREVIEW_HOLD_MS)
1903
{ raw = 0.999; }
1745
1904
if (raw >= 1)
1746
1905
{
1747
1906
if (f.el && f.el.parentNode)
@@ -1814,6 +1973,7 @@ Online.clearFlights = function ()
1814
1973
this._flightSeen = Object.create(null);
1815
1974
this._pendingLandCol = Object.create(null);
1816
1975
this._previewIds = Object.create(null);
1976
this._miniPredict = Object.create(null);
1817
1977
};
1818
1978
1819
1979
if (typeof globalThis !== 'undefined')
@@ -24,6 +24,10 @@ var Online = {24
error: '',24
error: '',25
_timer: null,25
_timer: null,26
_pendingShots: [],26
_pendingShots: [],27
_pollInFlight: false,28
_flushPending: false,29
_lastPollAt: 0,30
_getPayload: null,27
_flights: [],31
_flights: [],28
_lastStatus: null,32
_lastStatus: null,29
onChange: null,33
onChange: null,@@ -235,8 +239,16 @@ Online.poll = function (opts)235
}239
}236
var self = this;240
var self = this;237
var prevStatus = this.lobby && this.lobby.status;241
var prevStatus = this.lobby && this.lobby.status;242
this._pollInFlight = true;243
this._lastPollAt = Date.now();238
return this.request('poll', body).then(function (data)244
return this.request('poll', body).then(function (data)239
{245
{246
self._pollInFlight = false;247
if (self._flushPending)248
{249
self._flushPending = false;250
self.flushShotsSoon();251
}240
self._handleTransitions(prevStatus, data);252
self._handleTransitions(prevStatus, data);241
if (self.onChange)253
if (self.onChange)242
{ self.onChange(self); }254
{ self.onChange(self); }@@ -271,6 +283,7 @@ Online.startPolling = function (getPayload)271
{283
{272
this.stopPolling();284
this.stopPolling();273
var self = this;285
var self = this;286
this._getPayload = getPayload || null;274
var tick = function ()287
var tick = function ()275
{288
{276
var payload = getPayload ? getPayload() : {};289
var payload = getPayload ? getPayload() : {};@@ -280,8 +293,68 @@ Online.startPolling = function (getPayload)280
this._timer = setInterval(tick, this.POLL_MS);293
this._timer = setInterval(tick, this.POLL_MS);281
};294
};282
295
296
/** Minimum gap between an extra shot flush and the previous poll (ms). */297
Online.FLUSH_MIN_GAP_MS = 120;298
299
/**300
* Pure decision for flushShotsSoon (t1181): 'now', 'later' (wait for the301
* in-flight poll or the min gap) or 'none' (nothing to send / not polling).302
*/303
Online.flushDecision = function (state)304
{305
if (!state || !state.polling || !(state.pending > 0))306
{ return 'none'; }307
if (state.inFlight)308
{ return 'later'; }309
if (state.sinceLast < (state.minGap != null ? state.minGap : this.FLUSH_MIN_GAP_MS))310
{ return 'later'; }311
return 'now';312
};313
314
/**315
* Send freshly cleared shots on the next possible poll instead of up to316
* POLL_MS later, so the server's hit/miss result (and the retarget of the317
* local flight) arrives in about one round trip. Network cadence only;318
* the server still decides hits, targets and delivery (t1181).319
*/320
Online.flushShotsSoon = function ()321
{322
var self = this;323
var d = this.flushDecision({324
polling: !!this._timer,325
pending: this._pendingShots.length,326
inFlight: this._pollInFlight,327
sinceLast: Date.now() - (this._lastPollAt || 0)328
});329
if (d === 'none')330
{ return d; }331
if (d === 'later')332
{333
if (this._pollInFlight)334
{ this._flushPending = true; }335
else if (!this._flushTimer)336
{337
var wait = Math.max(0, this.FLUSH_MIN_GAP_MS - (Date.now() - (this._lastPollAt || 0)));338
this._flushTimer = setTimeout(function ()339
{340
self._flushTimer = null;341
self.flushShotsSoon();342
}, wait);343
}344
return d;345
}346
this.poll(this._getPayload ? this._getPayload() : {});347
return d;348
};349
283
Online.stopPolling = function ()350
Online.stopPolling = function ()284
{351
{352
if (this._flushTimer)353
{354
clearTimeout(this._flushTimer);355
this._flushTimer = null;356
}357
this._flushPending = false;285
if (this._timer)358
if (this._timer)286
{359
{287
clearInterval(this._timer);360
clearInterval(this._timer);@@ -383,7 +456,7 @@ Online.renderMinis = function (container)383
? I18n.t('hud.miniPoints', { n: p.score || 0 })456
? I18n.t('hud.miniPoints', { n: p.score || 0 })384
: ('Points ' + (p.score || 0));457
: ('Points ' + (p.score || 0));385
}458
}386
this._drawMini(el.querySelector('canvas'), p.snapshot, p.planet);459
this._drawMini(el.querySelector('canvas'), p.snapshot, p.planet, this._predictMini(p));387
}460
}388
for (var id in existing)461
for (var id in existing)389
{462
{@@ -404,7 +477,28 @@ function miniColor (planet, color)404
}477
}405
478
406
479
407
Online._drawMini = function (canvas, snapshot, planet)480
/**481
* t1182: smoothed display y for an opponent's falling blocks (see482
* src/miniPredict.js). Returns id → y, or null without the module.483
*/484
Online._predictMini = function (p, now)485
{486
var MP = typeof MiniPredict !== 'undefined' ? MiniPredict : null;487
if (!MP || !p)488
{ return null; }489
if (!this._miniPredict)490
{ this._miniPredict = Object.create(null); }491
var st = this._miniPredict[p.id];492
if (!st)493
{ st = this._miniPredict[p.id] = MP.create(); }494
now = now != null ? now : (typeof performance !== 'undefined' ? performance.now() : Date.now());495
MP.update(st, p.snapshot, now);496
if (p.eliminated)497
{ return null; }498
return MP.step(st, now, MP.fallSpeedFor(p.planet));499
};500
501
Online._drawMini = function (canvas, snapshot, planet, shownY)408
{502
{409
if (!canvas)503
if (!canvas)410
{ return; }504
{ return; }@@ -451,7 +545,8 @@ Online._drawMini = function (canvas, snapshot, planet)451
{545
{452
var b = blocks[i];546
var b = blocks[i];453
var x = b.col * tw;547
var x = b.col * tw;454
var y = canvas.height - (b.y + 1) * th;548
var by = (shownY && shownY[b.id] != null) ? shownY[b.id] : b.y;549
var y = canvas.height - (by + 1) * th;455
if (b.state === 'locked')550
if (b.state === 'locked')456
{ ctx.fillStyle = '#3a3d4a'; }551
{ ctx.fillStyle = '#3a3d4a'; }457
else if (b.color < 0)552
else if (b.color < 0)@@ -1264,6 +1359,17 @@ Online.spawnFlights = function (results, locals)1264
{1359
{1265
var r = results[i];1360
var r = results[i];1266
var sid = String(r.id != null ? r.id : (r.client_id || ('tmp-' + i)));1361
var sid = String(r.id != null ? r.id : (r.client_id || ('tmp-' + i)));1362
// Own shot already flying locally since the clear (t1181):1363
// pick it up at its current pose and fly on to the real target.1364
var cid = r.client_id != null ? String(r.client_id) : null;1365
if (cid && this._previewIds[cid] && this._isOwnShot(r))1366
{1367
var own = this._findFlight(cid);1368
this._flightSeen[sid] = now;1369
if (own)1370
{ this.retargetFlight(own, r, locals[cid] || {}, now); }1371
continue;1372
}1267
if (this._flightSeen[sid])1373
if (this._flightSeen[sid])1268
{1374
{1269
if (this._previewIds[sid])1375
if (this._previewIds[sid])@@ -1369,12 +1475,11 @@ Online.spawnFlights = function (results, locals)1369
el.style.height = full + 'px';1475
el.style.height = full + 'px';1370
layer.appendChild(el);1476
layer.appendChild(el);1371
1477
1478
// A flight seen late (poll delay) still starts at the sender's1479
// field and plays the whole arc, just a bit faster, so it lands1480
// about when the server delivers it — never a mid-arc pop-in (t1181).1372
var t0 = now;1481
var t0 = now;1373
if (r.age != null && isFinite(r.age) && r.age > 0)1482
duration = this.lateFlightDuration(r.age, duration);1374
{1375
var u0 = Math.min(0.95, (r.age * 1000) / duration);1376
t0 = now - u0 * duration;1377
}1378
var height = miss1483
var height = miss1379
? Math.max(40, Math.min(160, Math.abs(end.y - start.y) * 0.35))1484
? Math.max(40, Math.min(160, Math.abs(end.y - start.y) * 0.35))1380
: this.arcHeight(start, end);1485
: this.arcHeight(start, end);@@ -1411,6 +1516,52 @@ Online.spawnFlights = function (results, locals)1411
this._flightLocals = {};1516
this._flightLocals = {};1412
};1517
};1413
1518
1519
/** Shortest share of the normal flight a late-seen flight may get. */1520
Online.LATE_MIN_SHARE = 0.5;1521
1522
/** Duration (ms) for a flight first seen `age` seconds after it was fired. */1523
Online.lateFlightDuration = function (age, duration)1524
{1525
if (age == null || !isFinite(age) || age <= 0)1526
{ return duration; }1527
return Math.max(duration * this.LATE_MIN_SHARE, duration - age * 1000);1528
};1529
1530
/** Remaining duration (ms) after a local preview has flown `elapsedMs`. */1531
Online.retargetDuration = function (elapsedMs, duration)1532
{1533
if (!(elapsedMs > 0))1534
{ return duration; }1535
return Math.max(duration * this.LATE_MIN_SHARE, duration - elapsedMs);1536
};1537
1538
Online._isOwnShot = function (r)1539
{1540
var mine = this.me && this.me.id;1541
var from = r.from_id || r.from_user || null;1542
return !from || (mine != null && String(from) === String(mine));1543
};1544
1545
/**1546
* Sender side (t1181): start the flight the moment the block leaves the1547
* field, before any server round trip. It rises out of the exit cell;1548
* the poll answer retargets it (hit → opponent mini, miss → off-screen).1549
*/1550
Online.startLocalShot = function (shot, start)1551
{1552
if (!shot || !start)1553
{ return null; }1554
return this.previewExit({1555
id: shot.id,1556
col: shot.col,1557
y: shot.y,1558
vy: shot.vy,1559
color: shot.color,1560
start: start,1561
from_id: null1562
});1563
};1564
1414
Online.rememberFlightLocal = function (shot, startX, startY)1565
Online.rememberFlightLocal = function (shot, startX, startY)1415
{1566
{1416
if (!this._flightLocals)1567
if (!this._flightLocals)@@ -1577,6 +1728,7 @@ Online.previewExit = function (info)1577
});1728
});1578
this._previewIds[sid] = true;1729
this._previewIds[sid] = true;1579
this._flightSeen[sid] = now;1730
this._flightSeen[sid] = now;1731
return true;1580
};1732
};1581
1733
1582
/** True while a field sprite should stay hidden — the flight is its visual. */1734
/** True while a field sprite should stay hidden — the flight is its visual. */@@ -1618,6 +1770,8 @@ Online.retargetFlight = function (f, r, meta, now)1618
var miss = !!r.miss;1770
var miss = !!r.miss;1619
var kind = this.flightKind(fromId, targetId, miss);1771
var kind = this.flightKind(fromId, targetId, miss);1620
var duration = (r.flight_duration || this.FLIGHT_DURATION) * 1000;1772
var duration = (r.flight_duration || this.FLIGHT_DURATION) * 1000;1773
if (f.preview)1774
{ duration = this.retargetDuration(now - f.t0, duration); }1621
1775
1622
var landCol = null;1776
var landCol = null;1623
if (r.land_col != null && isFinite(r.land_col))1777
if (r.land_col != null && isFinite(r.land_col))@@ -1734,6 +1888,9 @@ Online.pointAllowedOnArc = function (p, field, start, end, slop)1734
return false;1888
return false;1735
};1889
};1736
1890
1891
/** How long a local preview may wait at its apex for the server (ms). */1892
Online.PREVIEW_HOLD_MS = 2500;1893
1737
Online.tickFlights = function (now)1894
Online.tickFlights = function (now)1738
{1895
{1739
now = now || performance.now();1896
now = now || performance.now();@@ -1742,6 +1899,8 @@ Online.tickFlights = function (now)1742
{1899
{1743
var f = this._flights[i];1900
var f = this._flights[i];1744
var raw = (now - f.t0) / f.duration;1901
var raw = (now - f.t0) / f.duration;1902
if (f.preview && raw >= 0.999 && now - f.t0 < f.duration + this.PREVIEW_HOLD_MS)1903
{ raw = 0.999; }1745
if (raw >= 1)1904
if (raw >= 1)1746
{1905
{1747
if (f.el && f.el.parentNode)1906
if (f.el && f.el.parentNode)@@ -1814,6 +1973,7 @@ Online.clearFlights = function ()1814
this._flightSeen = Object.create(null);1973
this._flightSeen = Object.create(null);1815
this._pendingLandCol = Object.create(null);1974
this._pendingLandCol = Object.create(null);1816
this._previewIds = Object.create(null);1975
this._previewIds = Object.create(null);1976
this._miniPredict = Object.create(null);1817
};1977
};1818
1978
1819
if (typeof globalThis !== 'undefined')1979
if (typeof globalThis !== 'undefined')@@ -0,0 +1,145 @@
1
'use strict';
2
3
// t1181: flights are drawn locally, decoupled from the poll/server cadence.
4
5
const { describe, it, beforeEach } = require('node:test');
6
const assert = require('node:assert/strict');
7
8
function fakeEl ()
9
{
10
return {
11
style: {},
12
className: '',
13
parentNode: null,
14
children: [],
15
appendChild (c) { c.parentNode = this; this.children.push(c); return c; },
16
removeChild (c) { c.parentNode = null; this.children = this.children.filter((x) => x !== c); },
17
querySelector () { return null; },
18
getBoundingClientRect () { return { left: 0, top: 0, width: 0, height: 0, right: 0, bottom: 0 }; }
19
};
20
}
21
22
const layers = { flights: fakeEl(), 'flights-back': fakeEl() };
23
globalThis.document = {
24
getElementById: (id) => layers[id] || null,
25
querySelector: () => null,
26
createElement: () => fakeEl()
27
};
28
globalThis.window = globalThis.window || { innerWidth: 1280, innerHeight: 800 };
29
globalThis.CSS = globalThis.CSS || { escape: (s) => String(s) };
30
globalThis.app = { fieldX: 400, fieldY: 100, fieldW: 400, fieldH: 520, tile: 40 };
31
32
const Online = require('../src/online.js');
33
34
function reset ()
35
{
36
Online.clearFlights();
37
Online._pendingShots = [];
38
Online.me = { id: 'me' };
39
layers.flights.children = [];
40
layers['flights-back'].children = [];
41
}
42
43
function poseOf (f, now)
44
{
45
Online.tickFlights(now);
46
const m = /translate\(([-\d.]+)px,([-\d.]+)px\)/.exec(f.el.style.transform || '');
47
return m ? { x: Number(m[1]), y: Number(m[2]) } : null;
48
}
49
50
describe('Local flights (t1181)', () =>
51
{
52
beforeEach(reset);
53
54
it('the sender sees its flight at once, before any server answer', () =>
55
{
56
const ok = Online.startLocalShot({ id: 41, col: 3, y: 13, vy: 6, color: 2 }, { x: 470, y: 100 });
57
assert.equal(ok, true);
58
assert.equal(Online._flights.length, 1);
59
assert.equal(layers.flights.children.length, 1, 'img element is on screen immediately');
60
const f = Online._flights[0];
61
assert.equal(f.preview, true);
62
const p = poseOf(f, f.t0 + 16);
63
assert.ok(p && Math.abs(p.x - 470) < 20 && p.y <= 100, 'starts at the exit cell going up: ' + JSON.stringify(p));
64
});
65
66
it('the poll result retargets the same flight without a jump, and only once', () =>
67
{
68
Online.startLocalShot({ id: 7, col: 5, y: 13, vy: 6, color: 1 }, { x: 510, y: 100 });
69
const f = Online._flights[0];
70
f.t0 = performance.now() - 300; // pretend it has been flying for 300 ms
71
const before = poseOf(f, performance.now());
72
// Server answer for the same client id (own shot, a miss so no mini is needed).
73
Online.spawnFlights([{ id: 900, client_id: '7', from_id: 'me', miss: true, color: 1, flight_duration: 1.2, age: 0 }]);
74
assert.equal(Online._flights.length, 1, 'no second flight for the same shot');
75
assert.equal(Online._flights[0], f);
76
assert.equal(f.preview, false);
77
// Retargeting happened at performance.now(); sample the new curve at its start.
78
const after = poseOf(f, f.t0);
79
assert.ok(Math.hypot(after.x - before.x, after.y - before.y) < 2, 'continues from the current pose');
80
// The same shot later in the lobby-wide shot_flights list is ignored.
81
Online.spawnFlights([{ id: 900, client_id: '7', from_id: 'me', miss: true, color: 1, flight_duration: 1.2, age: 0.4 }]);
82
assert.equal(Online._flights.length, 1);
83
});
84
85
it('the retarget keeps the total close to one flight duration', () =>
86
{
87
assert.equal(Online.retargetDuration(0, 1200), 1200);
88
assert.equal(Online.retargetDuration(300, 1200), 900);
89
assert.equal(Online.retargetDuration(1100, 1200), 600, 'never shorter than half a flight');
90
});
91
92
it('a preview waits at its apex for a slow server instead of vanishing', () =>
93
{
94
Online.startLocalShot({ id: 8, col: 5, y: 13, vy: 6, color: 1 }, { x: 510, y: 100 });
95
const f = Online._flights[0];
96
Online.tickFlights(f.t0 + f.duration + 500);
97
assert.equal(Online._flights.length, 1, 'still there while waiting');
98
Online.tickFlights(f.t0 + f.duration + Online.PREVIEW_HOLD_MS + 50);
99
assert.equal(Online._flights.length, 0, 'gives up after the hold');
100
});
101
102
it('a receiver plays a late-seen flight from the start, a bit faster (no mid-arc pop-in)', () =>
103
{
104
assert.equal(Online.lateFlightDuration(0, 1200), 1200);
105
assert.equal(Online.lateFlightDuration(null, 1200), 1200);
106
assert.equal(Online.lateFlightDuration(0.5, 1200), 700);
107
assert.equal(Online.lateFlightDuration(1.0, 1200), 600);
108
const now = performance.now();
109
Online.spawnFlights([{ id: 77, client_id: '3', from_id: 'other', miss: true, color: 0, flight_duration: 1.2, age: 0.5, col: 2, y: 13 }],
110
{ 77: { startX: 200, startY: 90 } });
111
const f = Online._flights.find((x) => x.id === '77');
112
assert.ok(f, 'flight spawned');
113
assert.ok(f.t0 >= now - 1, 't0 is now, not back-dated');
114
assert.ok(Math.abs(f.duration - 700) < 1e-6);
115
const p = poseOf(f, f.t0);
116
assert.ok(Math.hypot(p.x - 200, p.y - 90) < 2, 'starts at the sender field: ' + JSON.stringify(p));
117
});
118
119
it('interpolation depends only on time, not on how often tickFlights runs', () =>
120
{
121
Online.startLocalShot({ id: 9, col: 5, y: 13, vy: 6, color: 1 }, { x: 510, y: 100 });
122
const f = Online._flights[0];
123
const t = f.t0 + 420;
124
poseOf(f, f.t0 + 100);
125
poseOf(f, f.t0 + 250);
126
const a = poseOf(f, t);
127
const b = poseOf(f, t);
128
assert.deepEqual(a, b);
129
});
130
131
it('flushDecision sends new shots right away unless a poll is in flight or just happened', () =>
132
{
133
assert.equal(Online.flushDecision({ polling: true, pending: 2, inFlight: false, sinceLast: 500 }), 'now');
134
assert.equal(Online.flushDecision({ polling: true, pending: 2, inFlight: true, sinceLast: 500 }), 'later');
135
assert.equal(Online.flushDecision({ polling: true, pending: 2, inFlight: false, sinceLast: 30 }), 'later');
136
assert.equal(Online.flushDecision({ polling: true, pending: 0, inFlight: false, sinceLast: 500 }), 'none');
137
assert.equal(Online.flushDecision({ polling: false, pending: 3, inFlight: false, sinceLast: 500 }), 'none');
138
});
139
140
it('the authoritative payload is unchanged: shots are queued exactly as before', () =>
141
{
142
Online.queueShots([{ id: 5, color: 3, col: 1, y: 13 }]);
143
assert.deepEqual(Online._pendingShots, [{ client_id: '5', color: 3, col: 1, y: 13 }]);
144
});
145
});
@@ -0,0 +1,145 @@1
'use strict';2
3
// t1181: flights are drawn locally, decoupled from the poll/server cadence.4
5
const { describe, it, beforeEach } = require('node:test');6
const assert = require('node:assert/strict');7
8
function fakeEl ()9
{10
return {11
style: {},12
className: '',13
parentNode: null,14
children: [],15
appendChild (c) { c.parentNode = this; this.children.push(c); return c; },16
removeChild (c) { c.parentNode = null; this.children = this.children.filter((x) => x !== c); },17
querySelector () { return null; },18
getBoundingClientRect () { return { left: 0, top: 0, width: 0, height: 0, right: 0, bottom: 0 }; }19
};20
}21
22
const layers = { flights: fakeEl(), 'flights-back': fakeEl() };23
globalThis.document = {24
getElementById: (id) => layers[id] || null,25
querySelector: () => null,26
createElement: () => fakeEl()27
};28
globalThis.window = globalThis.window || { innerWidth: 1280, innerHeight: 800 };29
globalThis.CSS = globalThis.CSS || { escape: (s) => String(s) };30
globalThis.app = { fieldX: 400, fieldY: 100, fieldW: 400, fieldH: 520, tile: 40 };31
32
const Online = require('../src/online.js');33
34
function reset ()35
{36
Online.clearFlights();37
Online._pendingShots = [];38
Online.me = { id: 'me' };39
layers.flights.children = [];40
layers['flights-back'].children = [];41
}42
43
function poseOf (f, now)44
{45
Online.tickFlights(now);46
const m = /translate\(([-\d.]+)px,([-\d.]+)px\)/.exec(f.el.style.transform || '');47
return m ? { x: Number(m[1]), y: Number(m[2]) } : null;48
}49
50
describe('Local flights (t1181)', () =>51
{52
beforeEach(reset);53
54
it('the sender sees its flight at once, before any server answer', () =>55
{56
const ok = Online.startLocalShot({ id: 41, col: 3, y: 13, vy: 6, color: 2 }, { x: 470, y: 100 });57
assert.equal(ok, true);58
assert.equal(Online._flights.length, 1);59
assert.equal(layers.flights.children.length, 1, 'img element is on screen immediately');60
const f = Online._flights[0];61
assert.equal(f.preview, true);62
const p = poseOf(f, f.t0 + 16);63
assert.ok(p && Math.abs(p.x - 470) < 20 && p.y <= 100, 'starts at the exit cell going up: ' + JSON.stringify(p));64
});65
66
it('the poll result retargets the same flight without a jump, and only once', () =>67
{68
Online.startLocalShot({ id: 7, col: 5, y: 13, vy: 6, color: 1 }, { x: 510, y: 100 });69
const f = Online._flights[0];70
f.t0 = performance.now() - 300; // pretend it has been flying for 300 ms71
const before = poseOf(f, performance.now());72
// Server answer for the same client id (own shot, a miss so no mini is needed).73
Online.spawnFlights([{ id: 900, client_id: '7', from_id: 'me', miss: true, color: 1, flight_duration: 1.2, age: 0 }]);74
assert.equal(Online._flights.length, 1, 'no second flight for the same shot');75
assert.equal(Online._flights[0], f);76
assert.equal(f.preview, false);77
// Retargeting happened at performance.now(); sample the new curve at its start.78
const after = poseOf(f, f.t0);79
assert.ok(Math.hypot(after.x - before.x, after.y - before.y) < 2, 'continues from the current pose');80
// The same shot later in the lobby-wide shot_flights list is ignored.81
Online.spawnFlights([{ id: 900, client_id: '7', from_id: 'me', miss: true, color: 1, flight_duration: 1.2, age: 0.4 }]);82
assert.equal(Online._flights.length, 1);83
});84
85
it('the retarget keeps the total close to one flight duration', () =>86
{87
assert.equal(Online.retargetDuration(0, 1200), 1200);88
assert.equal(Online.retargetDuration(300, 1200), 900);89
assert.equal(Online.retargetDuration(1100, 1200), 600, 'never shorter than half a flight');90
});91
92
it('a preview waits at its apex for a slow server instead of vanishing', () =>93
{94
Online.startLocalShot({ id: 8, col: 5, y: 13, vy: 6, color: 1 }, { x: 510, y: 100 });95
const f = Online._flights[0];96
Online.tickFlights(f.t0 + f.duration + 500);97
assert.equal(Online._flights.length, 1, 'still there while waiting');98
Online.tickFlights(f.t0 + f.duration + Online.PREVIEW_HOLD_MS + 50);99
assert.equal(Online._flights.length, 0, 'gives up after the hold');100
});101
102
it('a receiver plays a late-seen flight from the start, a bit faster (no mid-arc pop-in)', () =>103
{104
assert.equal(Online.lateFlightDuration(0, 1200), 1200);105
assert.equal(Online.lateFlightDuration(null, 1200), 1200);106
assert.equal(Online.lateFlightDuration(0.5, 1200), 700);107
assert.equal(Online.lateFlightDuration(1.0, 1200), 600);108
const now = performance.now();109
Online.spawnFlights([{ id: 77, client_id: '3', from_id: 'other', miss: true, color: 0, flight_duration: 1.2, age: 0.5, col: 2, y: 13 }],110
{ 77: { startX: 200, startY: 90 } });111
const f = Online._flights.find((x) => x.id === '77');112
assert.ok(f, 'flight spawned');113
assert.ok(f.t0 >= now - 1, 't0 is now, not back-dated');114
assert.ok(Math.abs(f.duration - 700) < 1e-6);115
const p = poseOf(f, f.t0);116
assert.ok(Math.hypot(p.x - 200, p.y - 90) < 2, 'starts at the sender field: ' + JSON.stringify(p));117
});118
119
it('interpolation depends only on time, not on how often tickFlights runs', () =>120
{121
Online.startLocalShot({ id: 9, col: 5, y: 13, vy: 6, color: 1 }, { x: 510, y: 100 });122
const f = Online._flights[0];123
const t = f.t0 + 420;124
poseOf(f, f.t0 + 100);125
poseOf(f, f.t0 + 250);126
const a = poseOf(f, t);127
const b = poseOf(f, t);128
assert.deepEqual(a, b);129
});130
131
it('flushDecision sends new shots right away unless a poll is in flight or just happened', () =>132
{133
assert.equal(Online.flushDecision({ polling: true, pending: 2, inFlight: false, sinceLast: 500 }), 'now');134
assert.equal(Online.flushDecision({ polling: true, pending: 2, inFlight: true, sinceLast: 500 }), 'later');135
assert.equal(Online.flushDecision({ polling: true, pending: 2, inFlight: false, sinceLast: 30 }), 'later');136
assert.equal(Online.flushDecision({ polling: true, pending: 0, inFlight: false, sinceLast: 500 }), 'none');137
assert.equal(Online.flushDecision({ polling: false, pending: 3, inFlight: false, sinceLast: 500 }), 'none');138
});139
140
it('the authoritative payload is unchanged: shots are queued exactly as before', () =>141
{142
Online.queueShots([{ id: 5, color: 3, col: 1, y: 13 }]);143
assert.deepEqual(Online._pendingShots, [{ client_id: '5', color: 3, col: 1, y: 13 }]);144
});145
});