BlueGit

projects-timfalken-com meteors

Files

meteors / src / online.js

online.js

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