BlueGit

projects-timfalken-com meteors

Files

meteors / src / online.js

online.js

online.js 54.8 KiB Download Raw
1'use strict';
2
3/**
4 * Online play: talks to api.php (cookie session), polls lobby and game
5 * state, and draws opponent miniatures plus flying-block tweens.
6 * Real-time sync is not required; a 0.75 s poll is enough.
7 */
8
9var Online = {
10 POLL_MS: 750,
11 DEFAULT_MISS_CHANCE: 0.30,
12 FLIGHT_DURATION: 1.2,
13 configured: false,
14 local: false,
15 csrf: '',
16 me: null,
17 lifetimePoints: 0,
18 onlineAwarded: null,
19 locale: null,
20 localeExplicit: false,
21 authLocale: null,
22 blocks: [],
23 planets: [],
24 lobby: null,
25 incoming: [],
26 shotResults: [],
27 error: '',
28 _timer: null,
29 _pendingShots: [],
30 _pollInFlight: false,
31 _flushPending: false,
32 _lastPollAt: 0,
33 _getPayload: null,
34 _flights: [],
35 _lastStatus: null,
36 onChange: null,
37 onGameStart: null,
38 onIncoming: null,
39 onFinished: null,
40 onLobbyReturn: null
41};
42
43Online._headers = function (json)
44{
45 var h = { 'Accept': 'application/json' };
46 if (json)
47 { h['Content-Type'] = 'application/json'; }
48 if (this.csrf)
49 { h['X-CSRF-Token'] = this.csrf; }
50 return h;
51};
52
53Online._apply = function (data)
54{
55 if (!data)
56 { return; }
57 if (typeof data.configured === 'boolean')
58 { this.configured = data.configured; }
59 if (typeof data.local === 'boolean')
60 { this.local = data.local; }
61 if (data.csrf)
62 { this.csrf = data.csrf; }
63 if (data.me !== undefined)
64 { this.me = data.me; }
65 if (data.lobby !== undefined)
66 { this.lobby = data.lobby; }
67 if (data.incoming)
68 { this.incoming = data.incoming; }
69 if (data.shot_results)
70 { this.shotResults = data.shot_results; }
71 if (data.miss_chance_default != null)
72 { this.DEFAULT_MISS_CHANCE = data.miss_chance_default; }
73 if (data.flight_duration != null)
74 { this.FLIGHT_DURATION = data.flight_duration; }
75 if (data.error)
76 { this.error = data.error; }
77 else if (data.ok)
78 { this.error = ''; }
79 if (data.lifetime_points != null)
80 { this.lifetimePoints = data.lifetime_points; }
81 if (data.online_awarded !== undefined)
82 { this.onlineAwarded = data.online_awarded; }
83 if (data.locale !== undefined)
84 { this.locale = data.locale; }
85 if (data.locale_explicit !== undefined)
86 { this.localeExplicit = !!data.locale_explicit; }
87 if (data.auth_locale !== undefined)
88 { this.authLocale = data.auth_locale; }
89 if (data.last_planet !== undefined)
90 { this.lastPlanet = data.last_planet; }
91 if (data.blocks)
92 { this.blocks = data.blocks; }
93 if (data.planets)
94 {
95 this.planets = data.planets;
96 if (typeof Planet !== 'undefined' && Planet.setCustomPlanets)
97 { Planet.setCustomPlanets(data.planets); }
98 }
99 if (data.lobby && data.lobby.players && typeof Planet !== 'undefined' && Planet.rememberPlanet)
100 {
101 for (var i = 0; i < data.lobby.players.length; i++)
102 {
103 if (data.lobby.players[i].planet)
104 { Planet.rememberPlanet(data.lobby.players[i].planet); }
105 }
106 }
107};
108
109Online.request = function (action, body)
110{
111 var self = this;
112 var isGet = action === 'me' || action === '';
113 var url = 'api.php?action=' + encodeURIComponent(action || 'me');
114 var opts = {
115 method: isGet && !body ? 'GET' : 'POST',
116 credentials: 'same-origin',
117 headers: this._headers(!!body || !isGet)
118 };
119 if (opts.method === 'POST')
120 {
121 var payload = body ? Object.assign({ action: action }, body) : { action: action };
122 opts.body = JSON.stringify(payload);
123 }
124 return fetch(url, opts).then(function (res)
125 {
126 return res.json().then(function (data)
127 {
128 data = data || {};
129 if (!res.ok && !data.error)
130 { data.error = (typeof I18n !== 'undefined' ? I18n.t('error.serverStatus', { status: res.status }) : ('De server gaf ' + res.status)); data.ok = false; }
131 self._apply(data);
132 return data;
133 }, function ()
134 {
135 var fail = { ok: false, error: (typeof I18n !== 'undefined' ? I18n.t('error.badResponse') : 'Geen geldig antwoord van de server.') };
136 self.error = fail.error;
137 return fail;
138 });
139 }).catch(function (err)
140 {
141 var fail = { ok: false, error: (typeof I18n !== 'undefined' ? I18n.t('error.connection') : 'Geen verbinding met de server.') };
142 self.error = fail.error;
143 return fail;
144 });
145};
146
147Online.refresh = function ()
148{
149 return this.request('me');
150};
151
152Online.testLogin = function (who)
153{
154 return this.request('test_login', { user: who });
155};
156
157Online.createLobby = function (planetId)
158{
159 return this.request('lobby_create', {
160 miss_chance: this.DEFAULT_MISS_CHANCE,
161 planet_id: planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra')
162 });
163};
164
165Online.joinLobby = function (code, planetId)
166{
167 return this.request('lobby_join', {
168 code: code,
169 planet_id: planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra')
170 });
171};
172
173Online.setPlanet = function (planetId)
174{
175 return this.request('lobby_set_planet', { planet_id: planetId });
176};
177
178Online.playBegin = function (mode)
179{
180 return this.request('play_begin', { mode: mode || 'solo' });
181};
182
183Online.playFinish = function (token, score)
184{
185 return this.request('play_finish', { token: token, score: score || 0 });
186};
187
188Online.savePlanet = function (planet)
189{
190 return this.request('planet_save', { planet: planet });
191};
192
193Online.deletePlanet = function (id)
194{
195 return this.request('planet_delete', { id: id });
196};
197
198/** Remember the last chosen planet on the profile (t1196). */
199Online.setLastPlanet = function (planetId)
200{
201 this.lastPlanet = planetId;
202 return this.request('set_last_planet', { planet_id: planetId });
203};
204
205Online.setLocale = function (locale)
206{
207 return this.request('set_locale', { locale: locale });
208};
209
210Online.leaveLobby = function ()
211{
212 return this.request('lobby_leave');
213};
214
215Online.setReady = function (ready)
216{
217 return this.request('lobby_ready', { ready: !!ready });
218};
219
220Online.startGame = function ()
221{
222 var self = this;
223 var prev = this.lobby && this.lobby.status;
224 return this.request('lobby_start').then(function (data)
225 {
226 self._handleTransitions(prev, data);
227 return data;
228 });
229};
230
231Online.queueShots = function (shots)
232{
233 for (var i = 0; i < shots.length; i++)
234 {
235 this._pendingShots.push({
236 client_id: String(shots[i].id),
237 color: shots[i].color,
238 col: shots[i].col,
239 y: shots[i].y
240 });
241 }
242};
243
244Online.poll = function (opts)
245{
246 opts = opts || {};
247 var body = {};
248 if (opts.snapshot)
249 { body.snapshot = opts.snapshot; }
250 if (opts.score != null)
251 { body.score = opts.score; }
252 if (opts.eliminated)
253 { body.eliminated = true; }
254 if (this._pendingShots.length)
255 {
256 body.outgoing_shots = this._pendingShots.splice(0, this._pendingShots.length);
257 }
258 var self = this;
259 var prevStatus = this.lobby && this.lobby.status;
260 this._pollInFlight = true;
261 this._lastPollAt = Date.now();
262 return this.request('poll', body).then(function (data)
263 {
264 self._pollInFlight = false;
265 if (self._flushPending)
266 {
267 self._flushPending = false;
268 self.flushShotsSoon();
269 }
270 self._handleTransitions(prevStatus, data);
271 if (self.onChange)
272 { self.onChange(self); }
273 return data;
274 });
275};
276
277Online._handleTransitions = function (prevStatus, data)
278{
279 var lobby = this.lobby;
280 var status = lobby && lobby.status;
281 if (status === 'playing' && prevStatus !== 'playing' && this.onGameStart)
282 { this.onGameStart(lobby); }
283 if (data && data.incoming && data.incoming.length && this.onIncoming)
284 { this.onIncoming(data.incoming); }
285 // Own outgoing results (immediate) and lobby-wide recent flights
286 // (so every client can draw opponent and enemy-to-enemy arcs, t1125).
287 var flights = [];
288 if (data && data.shot_results && data.shot_results.length)
289 { flights = flights.concat(data.shot_results); }
290 if (data && data.shot_flights && data.shot_flights.length)
291 { flights = flights.concat(data.shot_flights); }
292 if (flights.length)
293 { this.spawnFlights(flights, this._flightLocals); }
294 if (status === 'finished' && prevStatus !== 'finished' && this.onFinished)
295 { this.onFinished(lobby); }
296 if (status === 'waiting' && prevStatus === 'finished' && this.onLobbyReturn)
297 { this.onLobbyReturn(lobby); }
298};
299
300Online.startPolling = function (getPayload)
301{
302 this.stopPolling();
303 var self = this;
304 this._getPayload = getPayload || null;
305 var tick = function ()
306 {
307 var payload = getPayload ? getPayload() : {};
308 self.poll(payload);
309 };
310 tick();
311 this._timer = setInterval(tick, this.POLL_MS);
312};
313
314/** Minimum gap between an extra shot flush and the previous poll (ms). */
315Online.FLUSH_MIN_GAP_MS = 120;
316
317/**
318 * Pure decision for flushShotsSoon (t1181): 'now', 'later' (wait for the
319 * in-flight poll or the min gap) or 'none' (nothing to send / not polling).
320 */
321Online.flushDecision = function (state)
322{
323 if (!state || !state.polling || !(state.pending > 0))
324 { return 'none'; }
325 if (state.inFlight)
326 { return 'later'; }
327 if (state.sinceLast < (state.minGap != null ? state.minGap : this.FLUSH_MIN_GAP_MS))
328 { return 'later'; }
329 return 'now';
330};
331
332/**
333 * Send freshly cleared shots on the next possible poll instead of up to
334 * POLL_MS later, so the server's hit/miss result (and the retarget of the
335 * local flight) arrives in about one round trip. Network cadence only;
336 * the server still decides hits, targets and delivery (t1181).
337 */
338Online.flushShotsSoon = function ()
339{
340 var self = this;
341 var d = this.flushDecision({
342 polling: !!this._timer,
343 pending: this._pendingShots.length,
344 inFlight: this._pollInFlight,
345 sinceLast: Date.now() - (this._lastPollAt || 0)
346 });
347 if (d === 'none')
348 { return d; }
349 if (d === 'later')
350 {
351 if (this._pollInFlight)
352 { this._flushPending = true; }
353 else if (!this._flushTimer)
354 {
355 var wait = Math.max(0, this.FLUSH_MIN_GAP_MS - (Date.now() - (this._lastPollAt || 0)));
356 this._flushTimer = setTimeout(function ()
357 {
358 self._flushTimer = null;
359 self.flushShotsSoon();
360 }, wait);
361 }
362 return d;
363 }
364 this.poll(this._getPayload ? this._getPayload() : {});
365 return d;
366};
367
368Online.stopPolling = function ()
369{
370 if (this._flushTimer)
371 {
372 clearTimeout(this._flushTimer);
373 this._flushTimer = null;
374 }
375 this._flushPending = false;
376 if (this._timer)
377 {
378 clearInterval(this._timer);
379 this._timer = null;
380 }
381};
382
383/** Login from the Online screen: come back to online play (t1193). */
384Online.loginUrl = function ()
385{
386 return 'auth.php?return=online';
387};
388
389/** t1247: global or friends leaderboard (GET, no CSRF). */
390Online.leaderboard = function (scope)
391{
392 var self = this;
393 var url = 'api.php?action=leaderboard&scope=' + encodeURIComponent(scope === 'friends' ? 'friends' : 'global');
394 return fetch(url, {
395 method: 'GET',
396 credentials: 'same-origin',
397 headers: this._headers(false)
398 }).then(function (res)
399 {
400 return res.json().then(function (data)
401 {
402 data = data || {};
403 if (!res.ok && !data.error)
404 {
405 data.error = (typeof I18n !== 'undefined'
406 ? I18n.t('error.serverStatus', { status: res.status })
407 : ('De server gaf ' + res.status));
408 data.ok = false;
409 }
410 return data;
411 }, function ()
412 {
413 return { ok: false, error: (typeof I18n !== 'undefined' ? I18n.t('error.badResponse') : 'Geen geldig antwoord van de server.') };
414 });
415 }).catch(function ()
416 {
417 return { ok: false, error: (typeof I18n !== 'undefined' ? I18n.t('error.connection') : 'Geen verbinding met de server.') };
418 });
419};
420
421Online.logoutUrl = function ()
422{
423 return 'logout.php';
424};
425
426Online.opponents = function ()
427{
428 if (!this.lobby || !this.lobby.players)
429 { return []; }
430 return this.lobby.players.filter(function (p) { return !p.is_me; });
431};
432
433Online.aliveOpponents = function ()
434{
435 return this.opponents().filter(function (p) { return !p.eliminated; });
436};
437
438Online.mePlayer = function ()
439{
440 if (!this.lobby || !this.lobby.players)
441 { return null; }
442 for (var i = 0; i < this.lobby.players.length; i++)
443 {
444 if (this.lobby.players[i].is_me)
445 { return this.lobby.players[i]; }
446 }
447 return null;
448};
449
450/* ---------- miniatures --------------------------------------------- */
451
452Online.renderMinis = function (container)
453{
454 if (!container)
455 { return; }
456 var opponents = this.opponents();
457 var existing = {};
458 var kids = container.querySelectorAll('[data-player]');
459 for (var i = 0; i < kids.length; i++)
460 { existing[kids[i].getAttribute('data-player')] = kids[i]; }
461
462 var seen = Object.create(null);
463 for (var i = 0; i < opponents.length; i++)
464 {
465 var p = opponents[i];
466 seen[p.id] = true;
467 var el = existing[p.id];
468 if (!el)
469 {
470 el = document.createElement('div');
471 el.className = 'mini';
472 el.setAttribute('data-player', p.id);
473 el.innerHTML = '<div class="mini-name"></div>'
474 + '<canvas class="mini-canvas" width="80" height="104"></canvas>'
475 + '<div class="mini-meta"></div>';
476 container.appendChild(el);
477 }
478 var mz = (typeof app !== 'undefined' && app.miniLayout && app.miniLayout.mini)
479 ? app.miniLayout.mini
480 : { w: 80, h: 104 };
481 var canvas = el.querySelector('canvas');
482 if (canvas && (canvas.width !== mz.w || canvas.height !== mz.h))
483 {
484 canvas.width = mz.w;
485 canvas.height = mz.h;
486 }
487 if (canvas)
488 {
489 canvas.style.width = mz.w + 'px';
490 canvas.style.height = mz.h + 'px';
491 }
492 el.classList.toggle('eliminated', !!p.eliminated);
493 var hostTag = (typeof I18n !== 'undefined') ? I18n.t('online.host') : 'host';
494 el.querySelector('.mini-name').textContent = p.name + (p.is_host ? ' (' + hostTag + ')' : '');
495 if (p.eliminated)
496 {
497 var out = (typeof I18n !== 'undefined') ? I18n.t('hud.out') : 'Out';
498 if (p.place && typeof I18n !== 'undefined')
499 { out += ' · ' + I18n.place(p.place); }
500 else if (p.place)
501 { out += ' · ' + p.place; }
502 el.querySelector('.mini-meta').textContent = out;
503 }
504 else
505 {
506 el.querySelector('.mini-meta').textContent = (typeof I18n !== 'undefined')
507 ? I18n.t('hud.miniPoints', { n: p.score || 0 })
508 : ('Points ' + (p.score || 0));
509 }
510 this._drawMini(el.querySelector('canvas'), p.snapshot, p.planet, this._predictMini(p));
511 }
512 for (var id in existing)
513 {
514 if (!seen[id])
515 { existing[id].remove(); }
516 }
517 if (typeof applyMinisLayout === 'function')
518 { applyMinisLayout(); }
519};
520
521var MINI_COLORS = ['#d4553a', '#3a9ad4', '#4caf6a', '#e6c04a', '#b86ad4'];
522
523function miniColor (planet, color)
524{
525 if (planet && planet.colors && planet.colors[color] && planet.colors[color].hex)
526 { return planet.colors[color].hex; }
527 return MINI_COLORS[color] || '#888';
528}
529
530
531/**
532 * t1182: smoothed display y for an opponent's falling blocks (see
533 * src/miniPredict.js). Returns id → y, or null without the module.
534 */
535Online._predictMini = function (p, now)
536{
537 var MP = typeof MiniPredict !== 'undefined' ? MiniPredict : null;
538 if (!MP || !p)
539 { return null; }
540 if (!this._miniPredict)
541 { this._miniPredict = Object.create(null); }
542 var st = this._miniPredict[p.id];
543 if (!st)
544 { st = this._miniPredict[p.id] = MP.create(); }
545 now = now != null ? now : (typeof performance !== 'undefined' ? performance.now() : Date.now());
546 MP.update(st, p.snapshot, now);
547 if (p.eliminated)
548 { return null; }
549 return MP.step(st, now, MP.fallSpeedFor(p.planet));
550};
551
552Online._drawMini = function (canvas, snapshot, planet, shownY)
553{
554 if (!canvas)
555 { return; }
556 var ctx = canvas.getContext('2d');
557 var w = 10;
558 var h = 13;
559 var tw = canvas.width / w;
560 var th = canvas.height / h;
561 ctx.fillStyle = '#0c1020';
562 ctx.fillRect(0, 0, canvas.width, canvas.height);
563 ctx.strokeStyle = 'rgba(255,255,255,0.06)';
564 ctx.lineWidth = 1;
565 for (var c = 0; c <= w; c++)
566 {
567 ctx.beginPath();
568 ctx.moveTo(c * tw + 0.5, 0);
569 ctx.lineTo(c * tw + 0.5, canvas.height);
570 ctx.stroke();
571 }
572 for (var r = 0; r <= h; r++)
573 {
574 ctx.beginPath();
575 ctx.moveTo(0, r * th + 0.5);
576 ctx.lineTo(canvas.width, r * th + 0.5);
577 ctx.stroke();
578 }
579 if (!snapshot || !snapshot.blocks)
580 { return; }
581 // t1123: cheap sine pulse behind blocks of nearly-full columns.
582 if (typeof GameCore !== 'undefined' && GameCore.warnColumnsFromSnapshot)
583 {
584 var warns = GameCore.warnColumnsFromSnapshot(snapshot);
585 var pulse = GameCore.columnWarnPulse();
586 for (var wc = 0; wc < warns.length; wc++)
587 {
588 if (!warns[wc])
589 { continue; }
590 ctx.fillStyle = 'rgba(220, 36, 36,' + pulse + ')';
591 ctx.fillRect(wc * tw, 0, tw, canvas.height);
592 }
593 }
594 var blocks = snapshot.blocks;
595 for (var i = 0; i < blocks.length; i++)
596 {
597 var b = blocks[i];
598 var x = b.col * tw;
599 var by = (shownY && shownY[b.id] != null) ? shownY[b.id] : b.y;
600 var y = canvas.height - (by + 1) * th;
601 if (b.state === 'locked')
602 { ctx.fillStyle = '#3a3d4a'; }
603 else if (b.color < 0)
604 { ctx.fillStyle = '#5a5d66'; }
605 else
606 { ctx.fillStyle = miniColor(planet, b.color); }
607 ctx.fillRect(x + 0.5, y + 0.5, tw - 1, th - 1);
608 }
609};
610
611Online.miniElement = function (playerId)
612{
613 return document.querySelector('#minis .mini[data-player="' + CSS.escape(playerId) + '"]');
614};
615
616/* ---------- flight tweens ------------------------------------------ */
617
618function colorSpriteUrl (color, planetId)
619{
620 if (color < 0)
621 { return 'images/block-gray.png'; }
622 var planet = null;
623 if (typeof Planet !== 'undefined')
624 { planet = Planet.planetById(planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra')); }
625 if (planet && planet.colors && planet.colors[color] && planet.colors[color].image)
626 { return planet.colors[color].image; }
627 return 'images/block-gray.png';
628}
629
630/**
631 * Animate shot results. `locals` is a map of client_id → {col, y, color,
632 * startX, startY} in viewport pixels, filled by the view just after
633 * consumeOutgoingShots.
634 */
635Online.playerId = function ()
636{
637 if (typeof app !== 'undefined' && app.offline)
638 { return 'player'; }
639 if (this.lobby && this.lobby.players)
640 {
641 for (var i = 0; i < this.lobby.players.length; i++)
642 {
643 if (this.lobby.players[i].is_me)
644 { return this.lobby.players[i].id; }
645 }
646 }
647 return 'player';
648};
649
650/**
651 * Classify a shot for visual treatment (t1125).
652 * player-to-enemy, enemy-to-player, enemy-to-enemy,
653 * player-miss, enemy-miss.
654 */
655Online.flightKind = function (fromId, targetId, miss)
656{
657 var me = this.playerId();
658 var fromMe = !fromId || fromId === me || fromId === 'player';
659 if (miss)
660 { return fromMe ? 'player-miss' : 'enemy-miss'; }
661 if (fromMe)
662 { return 'player-to-enemy'; }
663 if (targetId === me || targetId === 'player')
664 { return 'enemy-to-player'; }
665 return 'enemy-to-enemy';
666};
667
668/**
669 * Parabolic arc: linear in x, a rise of `height` pixels above the
670 * chord at mid-flight (screen y grows downward, so we subtract).
671 */
672Online.arcPoint = function (start, end, u, height)
673{
674 var t = u < 0 ? 0 : (u > 1 ? 1 : u);
675 var x = start.x + (end.x - start.x) * t;
676 var y = start.y + (end.y - start.y) * t - 4 * height * t * (1 - t);
677 return { x: x, y: y };
678};
679
680Online.arcHeight = function (start, end)
681{
682 var dx = end.x - start.x;
683 var dy = end.y - start.y;
684 var dist = Math.sqrt(dx * dx + dy * dy);
685 return Math.max(48, Math.min(220, dist * 0.28));
686};
687
688Online.easeInOutCubic = function (t)
689{
690 if (t < 0.5)
691 { return 4 * t * t * t; }
692 var u = -2 * t + 2;
693 return 1 - (u * u * u) / 2;
694};
695
696/** Bounding box of the player's field in viewport pixels. */
697Online.playerFieldRect = function ()
698{
699 var appRef = typeof app !== 'undefined' ? app : null;
700 var canvas = appRef && appRef.scene && appRef.scene.canvas;
701 if (canvas && canvas.getBoundingClientRect)
702 { return canvas.getBoundingClientRect(); }
703 if (appRef && appRef.fieldW)
704 {
705 return {
706 left: appRef.fieldX,
707 top: appRef.fieldY,
708 right: appRef.fieldX + appRef.fieldW,
709 bottom: appRef.fieldY + appRef.fieldH,
710 width: appRef.fieldW,
711 height: appRef.fieldH
712 };
713 }
714 return null;
715};
716
717/**
718 * True if (x, y) is inside the field's interior. The top edge (a few
719 * pixels) is not interior: launch and landing may use that band.
720 */
721Online.pointInFieldInterior = function (x, y, field, slop)
722{
723 if (!field)
724 { return false; }
725 slop = slop == null ? 6 : slop;
726 return x > field.left + 0.5 && x < field.right - 0.5
727 && y > field.top + slop && y < field.bottom - 0.5;
728};
729
730/** Cubic Bezier C(t), t ∈ [0, 1]. C¹ (in fact C^∞) on (0, 1) — no corners (t1134). */
731Online.cubicBezier = function (p0, p1, p2, p3, t)
732{
733 if (t < 0)
734 { t = 0; }
735 if (t > 1)
736 { t = 1; }
737 var u = 1 - t;
738 var a = u * u * u;
739 var b = 3 * u * u * t;
740 var c = 3 * u * t * t;
741 var d = t * t * t;
742 return {
743 x: a * p0.x + b * p1.x + c * p2.x + d * p3.x,
744 y: a * p0.y + b * p1.y + c * p2.y + d * p3.y
745 };
746};
747
748/** C'(t) = 3(1−t)²(P1−P0) + 6(1−t)t(P2−P1) + 3t²(P3−P2). */
749Online.cubicBezierDeriv = function (p0, p1, p2, p3, t)
750{
751 if (t < 0)
752 { t = 0; }
753 if (t > 1)
754 { t = 1; }
755 var u = 1 - t;
756 return {
757 x: 3 * u * u * (p1.x - p0.x) + 6 * u * t * (p2.x - p1.x) + 3 * t * t * (p3.x - p2.x),
758 y: 3 * u * u * (p1.y - p0.y) + 6 * u * t * (p2.y - p1.y) + 3 * t * t * (p3.y - p2.y)
759 };
760};
761
762Online.cubicBezierDeriv2 = function (p0, p1, p2, p3, t)
763{
764 if (t < 0)
765 { t = 0; }
766 if (t > 1)
767 { t = 1; }
768 var u = 1 - t;
769 // C''(t) = 6(1−t)(P2−2P1+P0) + 6t(P3−2P2+P1)
770 return {
771 x: 6 * u * (p2.x - 2 * p1.x + p0.x) + 6 * t * (p3.x - 2 * p2.x + p1.x),
772 y: 6 * u * (p2.y - 2 * p1.y + p0.y) + 6 * t * (p3.y - 2 * p2.y + p1.y)
773 };
774};
775
776/** Degree-5 Bézier. One polynomial ⇒ C^∞ on (0, 1) (t1138). */
777Online.quinticBezier = function (pts, t)
778{
779 if (t < 0)
780 { t = 0; }
781 if (t > 1)
782 { t = 1; }
783 var u = 1 - t;
784 var u2 = u * u, u3 = u2 * u, u4 = u3 * u, u5 = u4 * u;
785 var t2 = t * t, t3 = t2 * t, t4 = t3 * t, t5 = t4 * t;
786 var b0 = u5, b1 = 5 * u4 * t, b2 = 10 * u3 * t2;
787 var b3 = 10 * u2 * t3, b4 = 5 * u * t4, b5 = t5;
788 return {
789 x: b0 * pts[0].x + b1 * pts[1].x + b2 * pts[2].x
790 + b3 * pts[3].x + b4 * pts[4].x + b5 * pts[5].x,
791 y: b0 * pts[0].y + b1 * pts[1].y + b2 * pts[2].y
792 + b3 * pts[3].y + b4 * pts[4].y + b5 * pts[5].y
793 };
794};
795
796Online.quinticBezierDeriv = function (pts, t)
797{
798 if (t < 0)
799 { t = 0; }
800 if (t > 1)
801 { t = 1; }
802 var d = [];
803 for (var i = 0; i < 5; i++)
804 { d.push({ x: pts[i + 1].x - pts[i].x, y: pts[i + 1].y - pts[i].y }); }
805 var u = 1 - t;
806 var u2 = u * u, u3 = u2 * u, u4 = u3 * u;
807 var t2 = t * t, t3 = t2 * t, t4 = t3 * t;
808 var b0 = u4, b1 = 4 * u3 * t, b2 = 6 * u2 * t2, b3 = 4 * u * t3, b4 = t4;
809 return {
810 x: 5 * (b0 * d[0].x + b1 * d[1].x + b2 * d[2].x + b3 * d[3].x + b4 * d[4].x),
811 y: 5 * (b0 * d[0].y + b1 * d[1].y + b2 * d[2].y + b3 * d[3].y + b4 * d[4].y)
812 };
813};
814
815Online.quinticBezierDeriv2 = function (pts, t)
816{
817 if (t < 0)
818 { t = 0; }
819 if (t > 1)
820 { t = 1; }
821 var d2 = [];
822 for (var i = 0; i < 4; i++)
823 {
824 d2.push({
825 x: pts[i + 2].x - 2 * pts[i + 1].x + pts[i].x,
826 y: pts[i + 2].y - 2 * pts[i + 1].y + pts[i].y
827 });
828 }
829 var u = 1 - t;
830 var u2 = u * u, u3 = u2 * u;
831 var t2 = t * t, t3 = t2 * t;
832 var b0 = u3, b1 = 3 * u2 * t, b2 = 3 * u * t2, b3 = t3;
833 return {
834 x: 20 * (b0 * d2[0].x + b1 * d2[1].x + b2 * d2[2].x + b3 * d2[3].x),
835 y: 20 * (b0 * d2[0].y + b1 * d2[1].y + b2 * d2[2].y + b3 * d2[3].y)
836 };
837};
838
839/** Signed curvature κ = (x'y'' − y'x'') / |r'|³ (independent of parametrisation). */
840Online.curvature = function (d1, d2)
841{
842 var sp = d1.x * d1.x + d1.y * d1.y;
843 var den = Math.pow(sp, 1.5);
844 if (den < 1e-12)
845 { return 0; }
846 return (d1.x * d2.y - d1.y * d2.x) / den;
847};
848
849/**
850 * de Casteljau evaluation of a Bézier of any degree, plus first
851 * and second derivatives (t1138). A single polynomial is C^∞ on (0, 1).
852 */
853Online.bezierPoint = function (pts, t)
854{
855 if (!pts || !pts.length)
856 { return { x: 0, y: 0 }; }
857 if (t < 0)
858 { t = 0; }
859 if (t > 1)
860 { t = 1; }
861 var tmp = [];
862 var i, k, u = 1 - t;
863 for (i = 0; i < pts.length; i++)
864 { tmp.push({ x: pts[i].x, y: pts[i].y }); }
865 for (k = 1; k < pts.length; k++)
866 {
867 for (i = 0; i < pts.length - k; i++)
868 {
869 tmp[i] = {
870 x: u * tmp[i].x + t * tmp[i + 1].x,
871 y: u * tmp[i].y + t * tmp[i + 1].y
872 };
873 }
874 }
875 return tmp[0];
876};
877
878Online.bezierDeriv = function (pts, t)
879{
880 var n = pts ? pts.length - 1 : 0;
881 if (n < 1)
882 { return { x: 0, y: 0 }; }
883 var d = [];
884 for (var i = 0; i < n; i++)
885 {
886 d.push({
887 x: n * (pts[i + 1].x - pts[i].x),
888 y: n * (pts[i + 1].y - pts[i].y)
889 });
890 }
891 return this.bezierPoint(d, t);
892};
893
894Online.bezierDeriv2 = function (pts, t)
895{
896 var n = pts ? pts.length - 1 : 0;
897 if (n < 2)
898 { return { x: 0, y: 0 }; }
899 var s = n * (n - 1);
900 var d2 = [];
901 for (var i = 0; i < n - 1; i++)
902 {
903 d2.push({
904 x: s * (pts[i + 2].x - 2 * pts[i + 1].x + pts[i].x),
905 y: s * (pts[i + 2].y - 2 * pts[i + 1].y + pts[i].y)
906 });
907 }
908 return this.bezierPoint(d2, t);
909};
910
911/**
912 * Hermite parameter with p(0)=0, p(1)=1, p'(0)=v0, p'(1)=v1.
913 * v0=v1=1 is linear (constant speed in t, no endpoint halt).
914 */
915Online.smoothParam = function (t, v0, v1)
916{
917 if (t < 0)
918 { return 0; }
919 if (t > 1)
920 { return 1; }
921 if (v0 == null)
922 { v0 = 1; }
923 if (v1 == null)
924 { v1 = 1; }
925 var b = 3 - 2 * v0 - v1;
926 var a = v0 + v1 - 2;
927 return ((a * t + b) * t + v0) * t;
928};
929
930/**
931 * One continuous degree-7 Bézier: a single big, round, ballistic
932 * arch (t1138). Vertical at the exit (heading up) and at the
933 * landing (heading down). Horizontal travel sits on the apex,
934 * above the field — a cluster of high control points on each
935 * side keeps the hull out of the interior, with no straight
936 * cruise and no quarter-turn kinks. C^∞ on (0, 1).
937 *
938 * Incoming (low mini → high field): the first mid controls stay
939 * on the outside so the rise clears the top before crossing.
940 * Outgoing (high exit → low mini): mid controls sit above the
941 * target so the dive happens outside. Enemy→enemy (no field)
942 * is a symmetric parabola behind the field.
943 */
944Online.makeAroundCurve = function (start, end, field, opts)
945{
946 opts = opts || {};
947 if (!start)
948 { start = { x: 0, y: 0 }; }
949 if (!end)
950 { end = { x: 0, y: 0 }; }
951 var clearance = opts.clearance || 150;
952 if (typeof MiniLayout !== 'undefined' && MiniLayout.ARC_TOP_PAD)
953 { clearance = Math.max(clearance, MiniLayout.ARC_TOP_PAD); }
954 if (clearance < 150)
955 { clearance = 150; }
956
957 var apexY;
958 var left, right, top;
959 if (field)
960 {
961 top = field.top;
962 left = field.left;
963 right = field.right;
964 apexY = top - clearance;
965 if (apexY < 8)
966 { apexY = Math.max(8, top - Math.max(28, clearance * 0.5)); }
967 }
968 else
969 {
970 apexY = Math.min(start.y, end.y) - Math.max(56, clearance * 0.6);
971 if (apexY < 8)
972 { apexY = Math.min(start.y, end.y) - 40; }
973 left = right = top = null;
974 }
975
976 function outsideX (x)
977 {
978 if (!field)
979 { return x; }
980 var pad = 40;
981 if (x < left + 8)
982 { return Math.min(x, left - pad); }
983 if (x > right - 8)
984 { return Math.max(x, right + pad); }
985 return x;
986 }
987
988 var startLow = field && start.y > top + 8;
989 var endLow = field && end.y > top + 8;
990 var startInside = field && start.x > left + 8 && start.x < right - 8;
991 var endInside = field && end.x > left + 8 && end.x < right - 8;
992 // Incoming: rise on the outside first. Outgoing: cross at
993 // the apex, then dive outside. Otherwise a symmetric arch.
994 var kind;
995 if (startLow && !endLow)
996 { kind = 'in'; }
997 else if (!startLow && endLow)
998 { kind = 'out'; }
999 else if (startLow && endLow)
1000 { kind = startInside ? 'out' : (endInside ? 'in' : 'sym'); }
1001 else
1002 { kind = 'sym'; }
1003
1004 var sx = outsideX(start.x);
1005 var ex = outsideX(end.x);
1006 var rise = Math.max(80, Math.abs(start.y - apexY) * 0.35);
1007 var P0 = { x: start.x, y: start.y };
1008 var P1 = { x: start.x, y: start.y - rise };
1009 var P2, P3, P4, P5;
1010 var P6 = { x: end.x, y: apexY };
1011 var P7 = { x: end.x, y: end.y };
1012 if (kind === 'in')
1013 {
1014 P2 = { x: sx, y: apexY };
1015 P3 = { x: sx, y: apexY };
1016 P4 = { x: sx + (ex - sx) * 0.5, y: apexY };
1017 P5 = { x: sx + (ex - sx) * 0.85, y: apexY };
1018 }
1019 else if (kind === 'out')
1020 {
1021 P2 = { x: start.x, y: apexY };
1022 P3 = { x: sx + (ex - sx) * 0.55, y: apexY };
1023 P4 = { x: ex, y: apexY };
1024 P5 = { x: end.x, y: apexY };
1025 }
1026 else
1027 {
1028 P2 = { x: sx, y: apexY };
1029 P3 = { x: sx + (ex - sx) * 0.35, y: apexY };
1030 P4 = { x: sx + (ex - sx) * 0.65, y: apexY };
1031 P5 = { x: ex, y: apexY };
1032 }
1033 var pts = [P0, P1, P2, P3, P4, P5, P6, P7];
1034
1035 var curve = {
1036 degree: 7,
1037 pts: pts,
1038 p0: P0,
1039 p3: P7,
1040 apexY: apexY,
1041 kind: kind,
1042 arcLength: true
1043 };
1044 this._buildArcLut(curve);
1045 return curve;
1046};
1047
1048Online._evalPoly = function (curve, t)
1049{
1050 if (curve && curve.pts && curve.pts.length >= 2)
1051 { return this.bezierPoint(curve.pts, t); }
1052 if (curve && curve.p1)
1053 { return this.cubicBezier(curve.p0, curve.p1, curve.p2, curve.p3, t); }
1054 if (curve && curve.segments)
1055 {
1056 var n = curve.segments.length;
1057 var at = (t < 0 ? 0 : (t > 1 ? 1 : t)) * n;
1058 var i = Math.floor(at);
1059 if (i >= n)
1060 { i = n - 1; }
1061 var s = curve.segments[i];
1062 return this.cubicBezier(s.p0, s.p1, s.p2, s.p3, at - i);
1063 }
1064 return { x: 0, y: 0 };
1065};
1066
1067Online._evalPolyDeriv = function (curve, t)
1068{
1069 if (curve && curve.pts && curve.pts.length >= 2)
1070 { return this.bezierDeriv(curve.pts, t); }
1071 if (curve && curve.p1)
1072 { return this.cubicBezierDeriv(curve.p0, curve.p1, curve.p2, curve.p3, t); }
1073 return { x: 0, y: 0 };
1074};
1075
1076Online._evalPolyDeriv2 = function (curve, t)
1077{
1078 if (curve && curve.pts && curve.pts.length >= 3)
1079 { return this.bezierDeriv2(curve.pts, t); }
1080 if (curve && curve.p1)
1081 { return this.cubicBezierDeriv2(curve.p0, curve.p1, curve.p2, curve.p3, t); }
1082 return { x: 0, y: 0 };
1083};
1084
1085/** Cumulative-length LUT so u is a fraction of arc length (t1138). */
1086Online._buildArcLut = function (curve, steps)
1087{
1088 steps = steps || 48;
1089 var acc = [0];
1090 var prev = this._evalPoly(curve, 0);
1091 for (var i = 1; i <= steps; i++)
1092 {
1093 var p = this._evalPoly(curve, i / steps);
1094 acc.push(acc[i - 1] + Math.sqrt((p.x - prev.x) * (p.x - prev.x)
1095 + (p.y - prev.y) * (p.y - prev.y)));
1096 prev = p;
1097 }
1098 curve.lutS = acc;
1099 curve.lutN = steps;
1100 curve.totalLen = Math.max(acc[steps], 1);
1101 return curve;
1102};
1103
1104/** Polynomial t whose arc length fraction is u. */
1105Online._arcT = function (curve, u)
1106{
1107 if (u <= 0)
1108 { return 0; }
1109 if (u >= 1)
1110 { return 1; }
1111 if (!curve.lutS)
1112 { this._buildArcLut(curve); }
1113 var s = u * curve.totalLen;
1114 var acc = curve.lutS;
1115 var n = curve.lutN;
1116 var lo = 0;
1117 var hi = n;
1118 while (lo < hi)
1119 {
1120 var mid = (lo + hi) >> 1;
1121 if (acc[mid] < s)
1122 { lo = mid + 1; }
1123 else
1124 { hi = mid; }
1125 }
1126 var i = lo;
1127 if (i <= 0)
1128 { return 0; }
1129 var s0 = acc[i - 1];
1130 var s1 = acc[i];
1131 var f = (s1 > s0) ? (s - s0) / (s1 - s0) : 0;
1132 return ((i - 1) + f) / n;
1133};
1134
1135Online._measureCurve = function (curve)
1136{
1137 if (!curve)
1138 { return curve; }
1139 if (!curve.lutS)
1140 { this._buildArcLut(curve); }
1141 return curve;
1142};
1143
1144Online._segLen = function (seg, steps)
1145{
1146 steps = steps || 10;
1147 if (seg && seg.degree === 5)
1148 {
1149 if (!seg.lutS)
1150 { this._buildArcLut(seg, steps * 4); }
1151 return seg.totalLen;
1152 }
1153 var len = 0;
1154 var prev = this.cubicBezier(seg.p0, seg.p1, seg.p2, seg.p3, 0);
1155 for (var i = 1; i <= steps; i++)
1156 {
1157 var p = this.cubicBezier(seg.p0, seg.p1, seg.p2, seg.p3, i / steps);
1158 len += Math.sqrt((p.x - prev.x) * (p.x - prev.x) + (p.y - prev.y) * (p.y - prev.y));
1159 prev = p;
1160 }
1161 return Math.max(len, 1);
1162};
1163
1164/** Point at arc-length fraction u ∈ [0, 1]. */
1165Online.curvePoint = function (curve, u)
1166{
1167 if (!curve)
1168 { return { x: 0, y: 0 }; }
1169 var t = curve.arcLength !== false ? this._arcT(curve, u) : (u < 0 ? 0 : (u > 1 ? 1 : u));
1170 return this._evalPoly(curve, t);
1171};
1172
1173/**
1174 * dP/du under arc-length parametrisation: unit tangent × total length
1175 * (constant speed in u, direction from the polynomial).
1176 */
1177Online.curveDeriv = function (curve, u)
1178{
1179 if (!curve)
1180 { return { x: 0, y: 0 }; }
1181 var t = curve.arcLength !== false ? this._arcT(curve, u) : (u < 0 ? 0 : (u > 1 ? 1 : u));
1182 var d = this._evalPolyDeriv(curve, t);
1183 if (curve.arcLength !== false)
1184 {
1185 if (!curve.lutS)
1186 { this._buildArcLut(curve); }
1187 var mag = Math.sqrt(d.x * d.x + d.y * d.y);
1188 if (mag < 1e-9)
1189 { return { x: 0, y: 0 }; }
1190 var s = curve.totalLen / mag;
1191 return { x: d.x * s, y: d.y * s };
1192 }
1193 return d;
1194};
1195
1196Online.curveDeriv2 = function (curve, u)
1197{
1198 if (!curve)
1199 { return { x: 0, y: 0 }; }
1200 var t = curve.arcLength !== false ? this._arcT(curve, u) : (u < 0 ? 0 : (u > 1 ? 1 : u));
1201 return this._evalPolyDeriv2(curve, t);
1202};
1203
1204/** Curvature at arc-length fraction u (uses polynomial t, κ is invariant). */
1205Online.curveCurvature = function (curve, u)
1206{
1207 var t = curve && curve.arcLength !== false ? this._arcT(curve, u) : u;
1208 return this.curvature(this._evalPolyDeriv(curve, t), this._evalPolyDeriv2(curve, t));
1209};
1210
1211/**
1212 * Endpoint ease rates so arrival speed ≈ fallSpeed under arc-length
1213 * parametrisation: v = (L / duration) * p'(raw).
1214 */
1215Online.flightEaseRates = function (curve, duration, fallPx)
1216{
1217 if (!curve || !curve.lutS)
1218 { this._measureCurve(curve); }
1219 var L = (curve && curve.totalLen) || 400;
1220 duration = duration || this.FLIGHT_DURATION;
1221 var v1 = fallPx && L ? (fallPx * duration) / L : 0.75;
1222 if (v1 < 0.28)
1223 { v1 = 0.28; }
1224 if (v1 > 1.15)
1225 { v1 = 1.15; }
1226 var v0 = v1 + 0.2;
1227 if (v0 > 1)
1228 { v0 = 1; }
1229 if (v0 < 0.45)
1230 { v0 = 0.45; }
1231 return { v0: v0, v1: v1 };
1232};
1233
1234Online.aroundFieldPoint = function (start, end, u, field, clearance)
1235{
1236 var opts = (clearance && typeof clearance === 'object') ? clearance : { clearance: clearance };
1237 var curve = opts.curve || this.makeAroundCurve(start, end, field, opts);
1238 return this.curvePoint(curve, u);
1239};
1240
1241Online.waypointsAroundField = function (start, end, field, clearance)
1242{
1243 var c = this.makeAroundCurve(start, end, field, { clearance: clearance || 100 });
1244 if (c.pts && c.pts.length)
1245 { return c.pts.slice(); }
1246 return [c.p0, c.p1, c.p2, c.p3];
1247};
1248
1249Online.pointOnPath = function (points, u)
1250{
1251 // Legacy polyline; new flights use cubicBezier.
1252 u = u < 0 ? 0 : (u > 1 ? 1 : u);
1253 if (!points || !points.length)
1254 { return { x: 0, y: 0 }; }
1255 if (points.length === 4 && points[0] && points[3])
1256 { return this.cubicBezier(points[0], points[1], points[2], points[3], u); }
1257 if (points.length === 1)
1258 { return { x: points[0].x, y: points[0].y }; }
1259 var n = points.length - 1;
1260 var at = u * n;
1261 var i = Math.floor(at);
1262 if (i >= n)
1263 { i = n - 1; }
1264 var t = at - i;
1265 var a = points[i];
1266 var b = points[i + 1];
1267 return { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t };
1268};
1269
1270/** Viewport centre of a field cell (y=0 is the bottom row). */
1271Online.cellViewport = function (col, y, rect)
1272{
1273 if (!rect)
1274 {
1275 var field = this.playerFieldRect();
1276 if (!field)
1277 { return { x: 0, y: 0 }; }
1278 rect = field;
1279 }
1280 var w = rect.width != null ? rect.width : (rect.right - rect.left);
1281 var h = rect.height != null ? rect.height : (rect.bottom - rect.top);
1282 return {
1283 x: rect.left + ((col + 0.5) / 10) * w,
1284 y: rect.top + (1 - (y + 0.5) / 13) * h
1285 };
1286};
1287
1288/** Handoff point of an incoming garbage block: y = 13, just into the column (t1135). */
1289Online.fieldEntry = function (col)
1290{
1291 return this.cellViewport(col == null ? 4.5 : col, 13);
1292};
1293
1294Online.miniCellViewport = function (playerId, col, y)
1295{
1296 var el = this.miniElement(playerId);
1297 var canvas = el && (el.querySelector ? el.querySelector('canvas') : null);
1298 var box = canvas || el;
1299 if (!box || !box.getBoundingClientRect)
1300 { return { x: window.innerWidth / 2, y: 48 }; }
1301 return this.cellViewport(col == null ? 4.5 : col, y == null ? 13 : y, box.getBoundingClientRect());
1302};
1303
1304Online._fallSpeedPx = function (field, duration)
1305{
1306 var px = 40;
1307 if (field && field.height)
1308 { px = field.height / 13; }
1309 else if (typeof app !== 'undefined' && app.tile)
1310 { px = app.tile; }
1311 var cells = 13 / 3;
1312 if (typeof app !== 'undefined' && app.planet && app.planet.fallSpeed)
1313 { cells = app.planet.fallSpeed; }
1314 duration = duration || this.FLIGHT_DURATION;
1315 // Distance of P2 from P3 so C'(1)/duration ≈ fall speed (t1135).
1316 return (cells * px * duration) / 3;
1317};
1318
1319Online.rememberLandCol = function (id, col)
1320{
1321 if (id == null || col == null || !isFinite(col))
1322 { return; }
1323 if (!this._pendingLandCol)
1324 { this._pendingLandCol = Object.create(null); }
1325 this._pendingLandCol[String(id)] = col | 0;
1326};
1327
1328/** Resolve the landing column for an incoming shot (t1126). */
1329Online.takeLandCol = function (incoming)
1330{
1331 if (!incoming)
1332 { return null; }
1333 if (incoming.land_col != null && isFinite(incoming.land_col))
1334 { return incoming.land_col | 0; }
1335 if (!this._pendingLandCol)
1336 { return null; }
1337 var keys = [];
1338 if (incoming.id != null)
1339 { keys.push(String(incoming.id)); }
1340 if (incoming.client_id)
1341 { keys.push(String(incoming.client_id)); }
1342 for (var i = 0; i < keys.length; i++)
1343 {
1344 if (this._pendingLandCol[keys[i]] != null)
1345 { return this._pendingLandCol[keys[i]]; }
1346 }
1347 return null;
1348};
1349
1350Online._miniCellSize = function (playerId)
1351{
1352 var el = this.miniElement(playerId);
1353 var canvas = el && el.querySelector('canvas');
1354 if (canvas)
1355 {
1356 var r = canvas.getBoundingClientRect();
1357 return Math.max(6, r.width / 10);
1358 }
1359 return 10;
1360};
1361
1362Online._fullTileSize = function ()
1363{
1364 if (typeof app !== 'undefined' && app.tile)
1365 { return app.tile; }
1366 return 40;
1367};
1368
1369Online._miniAnchor = function (playerId, dir)
1370{
1371 var el = this.miniElement(playerId);
1372 var canvas = el && (el.querySelector ? el.querySelector('canvas') : null);
1373 var box = canvas || el;
1374 if (!box)
1375 { return { x: window.innerWidth / 2, y: 48 }; }
1376 var r = box.getBoundingClientRect();
1377 if (dir === 'out')
1378 { return { x: r.left + r.width / 2, y: r.top + 4 }; }
1379 return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
1380};
1381
1382Online._fieldTop = function (col)
1383{
1384 return this.fieldEntry(col);
1385};
1386
1387/**
1388 * Animate shot results. `locals` is a map of client_id → {col, y, color,
1389 * startX, startY, from_id} in viewport pixels.
1390 *
1391 * Visual-only: a smooth cubic that leaves the real cell, arcs around
1392 * the field, and dives into the landing column at the spawn pose
1393 * (t1134 / t1135). Enemy-to-enemy arcs stay small and are drawn
1394 * behind the player's field. A late-seen flight starts mid-arc via `age`.
1395 */
1396Online.spawnFlights = function (results, locals)
1397{
1398 locals = locals || this._flightLocals || {};
1399 var front = document.getElementById('flights');
1400 var back = document.getElementById('flights-back') || front;
1401 if (!front)
1402 { return; }
1403 if (!this._flightSeen)
1404 { this._flightSeen = Object.create(null); }
1405 if (!this._previewIds)
1406 { this._previewIds = Object.create(null); }
1407 var now = performance.now();
1408 var full = this._fullTileSize();
1409 for (var i = 0; i < results.length; i++)
1410 {
1411 var r = results[i];
1412 var sid = String(r.id != null ? r.id : (r.client_id || ('tmp-' + i)));
1413 // Own shot already flying locally since the clear (t1181):
1414 // pick it up at its current pose and fly on to the real target.
1415 var cid = r.client_id != null ? String(r.client_id) : null;
1416 if (cid && this._previewIds[cid] && this._isOwnShot(r))
1417 {
1418 var own = this._findFlight(cid);
1419 this._flightSeen[sid] = now;
1420 if (own)
1421 { this.retargetFlight(own, r, locals[cid] || {}, now); }
1422 continue;
1423 }
1424 if (this._flightSeen[sid])
1425 {
1426 if (this._previewIds[sid])
1427 {
1428 var existing = this._findFlight(sid);
1429 if (existing)
1430 {
1431 var meta0 = locals[r.client_id] || locals[sid] || {};
1432 this.retargetFlight(existing, r, meta0, now);
1433 }
1434 }
1435 continue;
1436 }
1437 this._flightSeen[sid] = now;
1438
1439 var meta = locals[r.client_id] || locals[sid] || {};
1440 var fromId = r.from_id || r.from_user || meta.from_id || null;
1441 var targetId = r.target_id != null ? r.target_id : r.to_user;
1442 var miss = !!r.miss;
1443 var kind = this.flightKind(fromId, targetId, miss);
1444 var duration = (r.flight_duration || this.FLIGHT_DURATION) * 1000;
1445 if (r.age != null && isFinite(r.age) && r.age * 1000 >= duration)
1446 { continue; }
1447
1448 var landCol = null;
1449 if (r.land_col != null && isFinite(r.land_col))
1450 { landCol = r.land_col | 0; }
1451 else if (meta.land_col != null && isFinite(meta.land_col))
1452 { landCol = meta.land_col | 0; }
1453 else if (kind === 'enemy-to-player'
1454 && typeof app !== 'undefined' && app.core && app.core.pickGarbageColumn)
1455 { landCol = app.core.pickGarbageColumn(); }
1456 if (landCol != null)
1457 {
1458 this.rememberLandCol(sid, landCol);
1459 if (r.client_id)
1460 { this.rememberLandCol(r.client_id, landCol); }
1461 }
1462
1463 var startCol = meta.col != null ? meta.col : r.col;
1464 var startY = meta.y != null ? meta.y : r.y;
1465 var start;
1466 if (meta.startX != null && isFinite(meta.startX))
1467 { start = { x: meta.startX, y: meta.startY }; }
1468 else if (kind === 'player-to-enemy' || kind === 'player-miss')
1469 { start = this._flightStart(startCol, startY); }
1470 else if (startCol != null || startY != null)
1471 { start = this.miniCellViewport(fromId, startCol, startY != null ? startY : 13); }
1472 else
1473 { start = this._miniAnchor(fromId, 'out'); }
1474
1475 var end;
1476 if (miss)
1477 { end = this._missEnd(start, kind === 'enemy-miss'); }
1478 else if (kind === 'enemy-to-player')
1479 { end = this.fieldEntry(landCol != null ? landCol : 4.5); }
1480 else
1481 { end = this._targetEnd(targetId, start, landCol); }
1482
1483 // Hits are ingested as grey garbage; draw them grey (t1130).
1484 // Misses keep the sender's colour — nothing is received.
1485 var flightColor = miss
1486 ? (r.color != null ? r.color : meta.color)
1487 : -1;
1488
1489 var startScale;
1490 var endScale;
1491 var mini = this._miniCellSize(fromId || targetId) / full;
1492 if (mini < 0.12)
1493 { mini = 0.2; }
1494 if (kind === 'player-to-enemy')
1495 {
1496 startScale = 1;
1497 endScale = mini;
1498 }
1499 else if (kind === 'enemy-to-player')
1500 {
1501 startScale = mini;
1502 endScale = 1;
1503 }
1504 else if (kind === 'enemy-to-enemy')
1505 {
1506 startScale = mini;
1507 endScale = mini;
1508 }
1509 else if (kind === 'enemy-miss')
1510 {
1511 startScale = mini;
1512 endScale = 0;
1513 }
1514 else
1515 {
1516 startScale = 1;
1517 endScale = 0;
1518 }
1519
1520 var layer = (kind === 'enemy-to-enemy' && back) ? back : front;
1521 var el = document.createElement('img');
1522 el.src = colorSpriteUrl(flightColor);
1523 el.alt = '';
1524 el.className = 'flight' + (kind === 'enemy-to-enemy' ? ' flight-behind' : '');
1525 el.style.width = full + 'px';
1526 el.style.height = full + 'px';
1527 layer.appendChild(el);
1528
1529 // A flight seen late (poll delay) still starts at the sender's
1530 // field and plays the whole arc, just a bit faster, so it lands
1531 // about when the server delivers it — never a mid-arc pop-in (t1181).
1532 var t0 = now;
1533 duration = this.lateFlightDuration(r.age, duration);
1534 var height = miss
1535 ? Math.max(40, Math.min(160, Math.abs(end.y - start.y) * 0.35))
1536 : this.arcHeight(start, end);
1537 var field = this.playerFieldRect();
1538 var around = !miss && (kind === 'enemy-to-player' || kind === 'player-to-enemy');
1539 var clearance = Math.max(150, height * 0.55);
1540 var endSpeed = this._fallSpeedPx(field, duration / 1000);
1541 var curve = miss ? null : this.makeAroundCurve(start, end, around ? field : null, {
1542 clearance: clearance
1543 });
1544 var easeRates = curve ? this.flightEaseRates(curve, duration / 1000, endSpeed) : null;
1545 this._flights.push({
1546 el: el,
1547 start: start,
1548 end: end,
1549 ctrl: miss ? this._missCtrl(start, end) : null,
1550 height: height,
1551 t0: t0,
1552 duration: duration,
1553 easeRates: easeRates,
1554 spin: miss ? ((Math.random() * 2 - 1) * 720) : ((Math.random() * 2 - 1) * 120),
1555 miss: miss,
1556 kind: kind,
1557 startScale: startScale,
1558 endScale: endScale,
1559 angle: 0,
1560 id: sid,
1561 landCol: landCol,
1562 field: field,
1563 curve: curve,
1564 color: flightColor
1565 });
1566 }
1567 this._flightLocals = {};
1568};
1569
1570/** Shortest share of the normal flight a late-seen flight may get. */
1571Online.LATE_MIN_SHARE = 0.5;
1572
1573/** Duration (ms) for a flight first seen `age` seconds after it was fired. */
1574Online.lateFlightDuration = function (age, duration)
1575{
1576 if (age == null || !isFinite(age) || age <= 0)
1577 { return duration; }
1578 return Math.max(duration * this.LATE_MIN_SHARE, duration - age * 1000);
1579};
1580
1581/** Remaining duration (ms) after a local preview has flown `elapsedMs`. */
1582Online.retargetDuration = function (elapsedMs, duration)
1583{
1584 if (!(elapsedMs > 0))
1585 { return duration; }
1586 return Math.max(duration * this.LATE_MIN_SHARE, duration - elapsedMs);
1587};
1588
1589Online._isOwnShot = function (r)
1590{
1591 var mine = this.me && this.me.id;
1592 var from = r.from_id || r.from_user || null;
1593 return !from || (mine != null && String(from) === String(mine));
1594};
1595
1596/**
1597 * Sender side (t1181): start the flight the moment the block leaves the
1598 * field, before any server round trip. It rises out of the exit cell;
1599 * the poll answer retargets it (hit → opponent mini, miss → off-screen).
1600 */
1601Online.startLocalShot = function (shot, start)
1602{
1603 if (!shot || !start)
1604 { return null; }
1605 return this.previewExit({
1606 id: shot.id,
1607 col: shot.col,
1608 y: shot.y,
1609 vy: shot.vy,
1610 color: shot.color,
1611 start: start,
1612 from_id: null
1613 });
1614};
1615
1616Online.rememberFlightLocal = function (shot, startX, startY)
1617{
1618 if (!this._flightLocals)
1619 { this._flightLocals = {}; }
1620 this._flightLocals[String(shot.id)] = {
1621 col: shot.col,
1622 y: shot.y,
1623 color: shot.color,
1624 startX: startX,
1625 startY: startY,
1626 from_id: shot.from_id,
1627 land_col: shot.land_col,
1628 vy: shot.vy
1629 };
1630};
1631
1632Online._flightStart = function (col, y)
1633{
1634 if (y == null || !isFinite(y))
1635 { y = 13; }
1636 return this.cellViewport(col == null ? 4.5 : col, y);
1637};
1638
1639Online._targetEnd = function (targetId, start, col)
1640{
1641 var el = targetId && this.miniElement(targetId);
1642 if (el)
1643 {
1644 // Slightly inside the mini, in the landing column (t1135).
1645 return this.miniCellViewport(targetId, col, 12);
1646 }
1647 return { x: start.x + (Math.random() - 0.5) * 80, y: 40 };
1648};
1649
1650Online._missEnd = function (start, fromMini)
1651{
1652 var w = window.innerWidth || 800;
1653 var outward;
1654 if (start.x < w * 0.4)
1655 { outward = -(80 + Math.random() * w * 0.25); }
1656 else if (start.x > w * 0.6)
1657 { outward = (80 + Math.random() * w * 0.25); }
1658 else
1659 { outward = (Math.random() * 2 - 1) * w * 0.35; }
1660 var lift = fromMini ? (80 + Math.random() * 160) : (120 + Math.random() * 220);
1661 return { x: start.x + outward, y: start.y - lift };
1662};
1663
1664Online._missCtrl = function (start, end)
1665{
1666 return {
1667 x: (start.x + end.x) / 2 + (Math.random() - 0.5) * 160,
1668 y: Math.min(start.y, end.y) - 40 - Math.random() * 80
1669 };
1670};
1671
1672Online._hitCtrl = function (start, end)
1673{
1674 return {
1675 x: (start.x + end.x) / 2 + (Math.random() - 0.5) * 40,
1676 y: (start.y + end.y) / 2 - 30
1677 };
1678};
1679
1680Online._findFlight = function (sid)
1681{
1682 sid = String(sid);
1683 if (!this._flights)
1684 { return null; }
1685 for (var i = 0; i < this._flights.length; i++)
1686 {
1687 if (String(this._flights[i].id) === sid)
1688 { return this._flights[i]; }
1689 }
1690 return null;
1691};
1692
1693/**
1694 * True once a block has really left the field, matching cullOffTop
1695 * (y ≥ height, default 13). Used so an arc never starts for a
1696 * rocket that only peaked near the top and fell back (t1137).
1697 */
1698Online.EXIT_Y = 13;
1699Online.hasLeftTheField = function (y, height)
1700{
1701 height = height == null ? this.EXIT_Y : height;
1702 return y != null && isFinite(y) && y >= height - 1e-9;
1703};
1704
1705/**
1706 * Start a flight only at the true exit (y ≥ 13). Callers that pass
1707 * a rocket still on the field are ignored, so a fallback never
1708 * shows a phantom arc (t1137). The start pose is the exit cell,
1709 * continuing upward; retargetFlight aims it at the real target
1710 * if a preview was used in the same frame as cull.
1711 */
1712Online.previewExit = function (info)
1713{
1714 if (!info || info.id == null)
1715 { return null; }
1716 if (!this.hasLeftTheField(info.y))
1717 { return null; }
1718 var sid = String(info.id);
1719 if (!this._flights)
1720 { this._flights = []; }
1721 if (!this._flightSeen)
1722 { this._flightSeen = Object.create(null); }
1723 if (!this._previewIds)
1724 { this._previewIds = Object.create(null); }
1725 if (this._previewIds[sid] || this._flightSeen[sid])
1726 { return; }
1727 var front = document.getElementById('flights');
1728 if (!front || !info.start)
1729 { return; }
1730 var start = info.start;
1731 var field = this.playerFieldRect();
1732 var clearance = 80;
1733 if (typeof MiniLayout !== 'undefined' && MiniLayout.ARC_TOP_PAD)
1734 { clearance = Math.max(clearance, MiniLayout.ARC_TOP_PAD * 0.7); }
1735 var apexY = (field ? field.top : start.y) - clearance;
1736 if (apexY < 8)
1737 { apexY = Math.max(8, start.y - 80); }
1738 var end = { x: start.x, y: apexY };
1739 var duration = this.FLIGHT_DURATION * 1000;
1740 var full = this._fullTileSize();
1741 var el = document.createElement('img');
1742 el.src = colorSpriteUrl(info.color);
1743 el.alt = '';
1744 el.className = 'flight';
1745 el.style.width = full + 'px';
1746 el.style.height = full + 'px';
1747 front.appendChild(el);
1748 var endSpeed = this._fallSpeedPx(field, this.FLIGHT_DURATION);
1749 var curve = this.makeAroundCurve(start, end, info.from_id ? null : field, {
1750 clearance: clearance
1751 });
1752 var easeRates = this.flightEaseRates(curve, this.FLIGHT_DURATION, endSpeed);
1753 var now = performance.now();
1754 var mini = info.from_id ? (this._miniCellSize(info.from_id) / full) : 1;
1755 if (mini < 0.12)
1756 { mini = 0.2; }
1757 this._flights.push({
1758 el: el,
1759 start: start,
1760 end: end,
1761 ctrl: null,
1762 height: clearance,
1763 t0: now,
1764 duration: duration,
1765 spin: (Math.random() * 2 - 1) * 90,
1766 miss: false,
1767 kind: info.from_id ? 'enemy-to-enemy' : 'player-to-enemy',
1768 startScale: mini,
1769 endScale: mini,
1770 angle: 0,
1771 id: sid,
1772 landCol: null,
1773 field: field,
1774 curve: curve,
1775 easeRates: easeRates,
1776 preview: true,
1777 color: info.color,
1778 from_id: info.from_id || null
1779 });
1780 this._previewIds[sid] = true;
1781 this._flightSeen[sid] = now;
1782 return true;
1783};
1784
1785/** True while a field sprite should stay hidden — the flight is its visual. */
1786Online.hasExitVisual = function (id)
1787{
1788 if (id == null)
1789 { return false; }
1790 var sid = String(id);
1791 if (this._previewIds && this._previewIds[sid])
1792 { return true; }
1793 var f = this._findFlight(sid);
1794 if (!f || f.miss)
1795 { return false; }
1796 var raw = (performance.now() - f.t0) / f.duration;
1797 return raw < 0.4;
1798};
1799
1800/**
1801 * Once the shot is scored, pick up the preview at its current pose
1802 * and fly the rest of the way to the real end (no jump).
1803 */
1804Online.retargetFlight = function (f, r, meta, now)
1805{
1806 now = now || performance.now();
1807 meta = meta || {};
1808 var raw = (now - f.t0) / f.duration;
1809 if (raw < 0)
1810 { raw = 0; }
1811 if (raw > 0.95)
1812 { raw = 0.95; }
1813 var u = this.smoothParam(raw, 0.9, 0.9);
1814 var pt = f.curve
1815 ? this.curvePoint(f.curve, u)
1816 : { x: f.start.x, y: f.start.y };
1817 var curScale = f.startScale + (f.endScale - f.startScale) * u;
1818
1819 var fromId = r.from_id || r.from_user || meta.from_id || f.from_id || null;
1820 var targetId = r.target_id != null ? r.target_id : r.to_user;
1821 var miss = !!r.miss;
1822 var kind = this.flightKind(fromId, targetId, miss);
1823 var duration = (r.flight_duration || this.FLIGHT_DURATION) * 1000;
1824 if (f.preview)
1825 { duration = this.retargetDuration(now - f.t0, duration); }
1826
1827 var landCol = null;
1828 if (r.land_col != null && isFinite(r.land_col))
1829 { landCol = r.land_col | 0; }
1830 else if (meta.land_col != null && isFinite(meta.land_col))
1831 { landCol = meta.land_col | 0; }
1832 else if (f.landCol != null)
1833 { landCol = f.landCol; }
1834 if (landCol != null)
1835 { this.rememberLandCol(String(f.id), landCol); }
1836
1837 var end;
1838 if (miss)
1839 { end = this._missEnd(pt, kind === 'enemy-miss'); }
1840 else if (kind === 'enemy-to-player')
1841 { end = this.fieldEntry(landCol != null ? landCol : 4.5); }
1842 else
1843 { end = this._targetEnd(targetId, pt, landCol); }
1844
1845 var flightColor = miss
1846 ? (r.color != null ? r.color : meta.color)
1847 : -1;
1848 if (f.el && flightColor !== f.color)
1849 { f.el.src = colorSpriteUrl(flightColor); }
1850
1851 var full = this._fullTileSize();
1852 var mini = this._miniCellSize(fromId || targetId) / full;
1853 if (mini < 0.12)
1854 { mini = 0.2; }
1855 var endScale;
1856 if (kind === 'player-to-enemy')
1857 { endScale = mini; }
1858 else if (kind === 'enemy-to-player')
1859 { endScale = 1; }
1860 else if (kind === 'enemy-to-enemy')
1861 { endScale = mini; }
1862 else
1863 { endScale = 0; }
1864
1865 var field = this.playerFieldRect();
1866 var around = !miss && (kind === 'enemy-to-player' || kind === 'player-to-enemy');
1867 var height = miss
1868 ? Math.max(40, Math.min(160, Math.abs(end.y - pt.y) * 0.35))
1869 : this.arcHeight(pt, end);
1870 var clearance = Math.max(150, height * 0.55);
1871 var endSpeed = this._fallSpeedPx(field, duration / 1000);
1872 var curve = miss ? null : this.makeAroundCurve(pt, end, around ? field : null, {
1873 clearance: clearance
1874 });
1875 var easeRates = curve ? this.flightEaseRates(curve, duration / 1000, endSpeed) : null;
1876
1877 f.start = pt;
1878 f.end = end;
1879 f.t0 = now;
1880 f.duration = duration;
1881 f.curve = curve;
1882 f.easeRates = easeRates;
1883 f.ctrl = miss ? this._missCtrl(pt, end) : null;
1884 f.height = height;
1885 f.miss = miss;
1886 f.kind = kind;
1887 f.startScale = curScale;
1888 f.endScale = endScale;
1889 f.landCol = landCol;
1890 f.field = field;
1891 f.preview = false;
1892 f.color = flightColor;
1893 f.from_id = fromId;
1894 if (this._previewIds)
1895 { delete this._previewIds[String(f.id)]; }
1896
1897 if (kind === 'enemy-to-enemy' && f.el)
1898 {
1899 var back = document.getElementById('flights-back');
1900 if (back && f.el.parentNode !== back)
1901 {
1902 f.el.className = 'flight flight-behind';
1903 back.appendChild(f.el);
1904 }
1905 }
1906};
1907
1908/** Point and (optional) derivative of a flight at parameter u. */
1909Online.flightPointAt = function (f, u)
1910{
1911 if (!f)
1912 { return { x: 0, y: 0 }; }
1913 if (f.curve)
1914 { return this.curvePoint(f.curve, u); }
1915 if (f.miss && f.ctrl)
1916 {
1917 var e = u;
1918 var mt = 1 - e;
1919 return {
1920 x: mt * mt * f.start.x + 2 * mt * e * f.ctrl.x + e * e * f.end.x,
1921 y: mt * mt * f.start.y + 2 * mt * e * f.ctrl.y + e * e * f.end.y
1922 };
1923 }
1924 return this.aroundFieldPoint(f.start, f.end, u, f.field, (f.height || 80) * 0.45);
1925};
1926
1927Online.pointAllowedOnArc = function (p, field, start, end, slop)
1928{
1929 if (!this.pointInFieldInterior(p.x, p.y, field, slop))
1930 { return true; }
1931 if (!field)
1932 { return true; }
1933 var w = (field.right - field.left) / 10;
1934 var corridor = w * 0.7;
1935 if (start && Math.abs(p.x - start.x) <= corridor)
1936 { return true; }
1937 if (end && Math.abs(p.x - end.x) <= corridor)
1938 { return true; }
1939 return false;
1940};
1941
1942/** How long a local preview may wait at its apex for the server (ms). */
1943Online.PREVIEW_HOLD_MS = 2500;
1944
1945Online.tickFlights = function (now)
1946{
1947 now = now || performance.now();
1948 var leftover = [];
1949 for (var i = 0; i < this._flights.length; i++)
1950 {
1951 var f = this._flights[i];
1952 var raw = (now - f.t0) / f.duration;
1953 if (f.preview && raw >= 0.999 && now - f.t0 < f.duration + this.PREVIEW_HOLD_MS)
1954 { raw = 0.999; }
1955 if (raw >= 1)
1956 {
1957 if (f.el && f.el.parentNode)
1958 { f.el.parentNode.removeChild(f.el); }
1959 if (this._previewIds)
1960 { delete this._previewIds[String(f.id)]; }
1961 continue;
1962 }
1963 if (raw < 0)
1964 { raw = 0; }
1965 // Non-zero endpoint speed so the handoff matches fallSpeed (t1135/t1138).
1966 var v0 = (f.easeRates && f.easeRates.v0 != null) ? f.easeRates.v0 : 0.85;
1967 var v1 = (f.easeRates && f.easeRates.v1 != null) ? f.easeRates.v1 : 0.85;
1968 var u = f.miss ? this.easeInOutCubic(raw) : this.smoothParam(raw, v0, v1);
1969 var x, y;
1970 if (f.miss && f.ctrl)
1971 {
1972 var e = raw * raw;
1973 var mt = 1 - e;
1974 x = mt * mt * f.start.x + 2 * mt * e * f.ctrl.x + e * e * f.end.x;
1975 y = mt * mt * f.start.y + 2 * mt * e * f.ctrl.y + e * e * f.end.y;
1976 }
1977 else if (f.curve)
1978 {
1979 var pt = this.curvePoint(f.curve, u);
1980 x = pt.x;
1981 y = pt.y;
1982 }
1983 else
1984 {
1985 var pt = this.aroundFieldPoint(f.start, f.end, u, f.field, (f.height || 80) * 0.45);
1986 x = pt.x;
1987 y = pt.y;
1988 }
1989 var scale = f.startScale + (f.endScale - f.startScale) * u;
1990 if (f.miss)
1991 {
1992 var fadeU = raw * raw;
1993 scale = f.startScale * (1 - fadeU);
1994 }
1995 var angle = f.angle + f.spin * raw;
1996 f.el.style.transform = 'translate(' + x + 'px,' + y + 'px) translate(-50%,-50%) rotate('
1997 + angle + 'deg) scale(' + scale + ')';
1998 f.el.style.opacity = f.miss ? String(Math.max(0, 1 - raw * raw)) : '1';
1999 leftover.push(f);
2000 }
2001 this._flights = leftover;
2002 if (this._flightSeen)
2003 {
2004 var cutoff = now - 8000;
2005 var ids = Object.keys(this._flightSeen);
2006 for (var k = 0; k < ids.length; k++)
2007 {
2008 if (this._flightSeen[ids[k]] < cutoff)
2009 { delete this._flightSeen[ids[k]]; }
2010 }
2011 }
2012};
2013
2014Online.clearFlights = function ()
2015{
2016 for (var i = 0; i < this._flights.length; i++)
2017 {
2018 var el = this._flights[i].el;
2019 if (el && el.parentNode)
2020 { el.parentNode.removeChild(el); }
2021 }
2022 this._flights = [];
2023 this._flightLocals = {};
2024 this._flightSeen = Object.create(null);
2025 this._pendingLandCol = Object.create(null);
2026 this._previewIds = Object.create(null);
2027 this._miniPredict = Object.create(null);
2028};
2029
2030/**
2031 * Totals for the end-of-match reward (t1173 / t1278). Prefers the
2032 * server's online_awarded (same shape as play_finish: after − awarded)
2033 * so a rematch or a stringy payload still starts the tally. Falls back
2034 * to the snapshot taken at match start.
2035 */
2036Online.rewardResult = function (opts)
2037{
2038 opts = opts || {};
2039 var after = Number(opts.lifetimePoints);
2040 if (!isFinite(after))
2041 { return null; }
2042 after = Math.max(0, Math.floor(after));
2043 if (opts.awarded != null && opts.awarded !== '')
2044 {
2045 var awarded = Number(opts.awarded);
2046 if (isFinite(awarded))
2047 {
2048 awarded = Math.max(0, Math.floor(awarded));
2049 return { before: Math.max(0, after - awarded), after: after };
2050 }
2051 }
2052 var before = Number(opts.before);
2053 if (!isFinite(before))
2054 { before = after; }
2055 before = Math.max(0, Math.floor(before));
2056 if (before > after)
2057 { before = after; }
2058 return { before: before, after: after };
2059};
2060
2061if (typeof globalThis !== 'undefined')
2062{ globalThis.Online = Online; }
2063if (typeof module !== 'undefined' && module.exports)
2064{ module.exports = Online; }