BlueGit

projects-timfalken-com meteors

Files

meteors / src / online.js

online.js

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