BlueGit

projects-timfalken-com meteors

Files

meteors / src / online.js

online.js

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