BlueGit

projects-timfalken-com meteors

Files

meteors / src / online.js

online.js

online.js 25.6 KiB Download Raw
1'use strict';
2
3/**
4 * Online play: talks to api.php (cookie session), polls lobby and game
5 * state, and draws opponent miniatures plus flying-block tweens.
6 * Real-time sync is not required; a 0.75 s poll is enough.
7 */
8
9var Online = {
10 POLL_MS: 750,
11 DEFAULT_MISS_CHANCE: 0.30,
12 FLIGHT_DURATION: 1.2,
13 configured: false,
14 local: false,
15 csrf: '',
16 me: null,
17 lobby: null,
18 incoming: [],
19 shotResults: [],
20 error: '',
21 _timer: null,
22 _pendingShots: [],
23 _flights: [],
24 _lastStatus: null,
25 onChange: null,
26 onGameStart: null,
27 onIncoming: null,
28 onFinished: null,
29 onLobbyReturn: null
30};
31
32Online._headers = function (json)
33{
34 var h = { 'Accept': 'application/json' };
35 if (json)
36 { h['Content-Type'] = 'application/json'; }
37 if (this.csrf)
38 { h['X-CSRF-Token'] = this.csrf; }
39 return h;
40};
41
42Online._apply = function (data)
43{
44 if (!data)
45 { return; }
46 if (typeof data.configured === 'boolean')
47 { this.configured = data.configured; }
48 if (typeof data.local === 'boolean')
49 { this.local = data.local; }
50 if (data.csrf)
51 { this.csrf = data.csrf; }
52 if (data.me !== undefined)
53 { this.me = data.me; }
54 if (data.lobby !== undefined)
55 { this.lobby = data.lobby; }
56 if (data.incoming)
57 { this.incoming = data.incoming; }
58 if (data.shot_results)
59 { this.shotResults = data.shot_results; }
60 if (data.miss_chance_default != null)
61 { this.DEFAULT_MISS_CHANCE = data.miss_chance_default; }
62 if (data.flight_duration != null)
63 { this.FLIGHT_DURATION = data.flight_duration; }
64 if (data.error)
65 { this.error = data.error; }
66 else if (data.ok)
67 { this.error = ''; }
68};
69
70Online.request = function (action, body)
71{
72 var self = this;
73 var isGet = action === 'me' || action === '';
74 var url = 'api.php?action=' + encodeURIComponent(action || 'me');
75 var opts = {
76 method: isGet && !body ? 'GET' : 'POST',
77 credentials: 'same-origin',
78 headers: this._headers(!!body || !isGet)
79 };
80 if (opts.method === 'POST')
81 {
82 var payload = body ? Object.assign({ action: action }, body) : { action: action };
83 opts.body = JSON.stringify(payload);
84 }
85 return fetch(url, opts).then(function (res)
86 {
87 return res.json().then(function (data)
88 {
89 data = data || {};
90 if (!res.ok && !data.error)
91 { data.error = 'De server gaf ' + res.status; data.ok = false; }
92 self._apply(data);
93 return data;
94 }, function ()
95 {
96 var fail = { ok: false, error: 'Geen geldig antwoord van de server.' };
97 self.error = fail.error;
98 return fail;
99 });
100 }).catch(function (err)
101 {
102 var fail = { ok: false, error: 'Geen verbinding met de server.' };
103 self.error = fail.error;
104 return fail;
105 });
106};
107
108Online.refresh = function ()
109{
110 return this.request('me');
111};
112
113Online.testLogin = function (who)
114{
115 return this.request('test_login', { user: who });
116};
117
118Online.createLobby = function (planetId)
119{
120 return this.request('lobby_create', {
121 miss_chance: this.DEFAULT_MISS_CHANCE,
122 planet_id: planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra')
123 });
124};
125
126Online.joinLobby = function (code, planetId)
127{
128 return this.request('lobby_join', {
129 code: code,
130 planet_id: planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra')
131 });
132};
133
134Online.setPlanet = function (planetId)
135{
136 return this.request('lobby_set_planet', { planet_id: planetId });
137};
138
139Online.leaveLobby = function ()
140{
141 return this.request('lobby_leave');
142};
143
144Online.setReady = function (ready)
145{
146 return this.request('lobby_ready', { ready: !!ready });
147};
148
149Online.startGame = function ()
150{
151 var self = this;
152 var prev = this.lobby && this.lobby.status;
153 return this.request('lobby_start').then(function (data)
154 {
155 self._handleTransitions(prev, data);
156 return data;
157 });
158};
159
160Online.queueShots = function (shots)
161{
162 for (var i = 0; i < shots.length; i++)
163 {
164 this._pendingShots.push({
165 client_id: String(shots[i].id),
166 color: shots[i].color,
167 col: shots[i].col,
168 y: shots[i].y
169 });
170 }
171};
172
173Online.poll = function (opts)
174{
175 opts = opts || {};
176 var body = {};
177 if (opts.snapshot)
178 { body.snapshot = opts.snapshot; }
179 if (opts.score != null)
180 { body.score = opts.score; }
181 if (opts.eliminated)
182 { body.eliminated = true; }
183 if (this._pendingShots.length)
184 {
185 body.outgoing_shots = this._pendingShots.splice(0, this._pendingShots.length);
186 }
187 var self = this;
188 var prevStatus = this.lobby && this.lobby.status;
189 return this.request('poll', body).then(function (data)
190 {
191 self._handleTransitions(prevStatus, data);
192 if (self.onChange)
193 { self.onChange(self); }
194 return data;
195 });
196};
197
198Online._handleTransitions = function (prevStatus, data)
199{
200 var lobby = this.lobby;
201 var status = lobby && lobby.status;
202 if (status === 'playing' && prevStatus !== 'playing' && this.onGameStart)
203 { this.onGameStart(lobby); }
204 if (data && data.incoming && data.incoming.length && this.onIncoming)
205 { this.onIncoming(data.incoming); }
206 // Own outgoing results (immediate) and lobby-wide recent flights
207 // (so every client can draw opponent and enemy-to-enemy arcs, t1125).
208 var flights = [];
209 if (data && data.shot_results && data.shot_results.length)
210 { flights = flights.concat(data.shot_results); }
211 if (data && data.shot_flights && data.shot_flights.length)
212 { flights = flights.concat(data.shot_flights); }
213 if (flights.length)
214 { this.spawnFlights(flights, this._flightLocals); }
215 if (status === 'finished' && prevStatus !== 'finished' && this.onFinished)
216 { this.onFinished(lobby); }
217 if (status === 'waiting' && prevStatus === 'finished' && this.onLobbyReturn)
218 { this.onLobbyReturn(lobby); }
219};
220
221Online.startPolling = function (getPayload)
222{
223 this.stopPolling();
224 var self = this;
225 var tick = function ()
226 {
227 var payload = getPayload ? getPayload() : {};
228 self.poll(payload);
229 };
230 tick();
231 this._timer = setInterval(tick, this.POLL_MS);
232};
233
234Online.stopPolling = function ()
235{
236 if (this._timer)
237 {
238 clearInterval(this._timer);
239 this._timer = null;
240 }
241};
242
243Online.loginUrl = function ()
244{
245 return 'auth.php';
246};
247
248Online.logoutUrl = function ()
249{
250 return 'logout.php';
251};
252
253Online.opponents = function ()
254{
255 if (!this.lobby || !this.lobby.players)
256 { return []; }
257 return this.lobby.players.filter(function (p) { return !p.is_me; });
258};
259
260Online.aliveOpponents = function ()
261{
262 return this.opponents().filter(function (p) { return !p.eliminated; });
263};
264
265Online.mePlayer = function ()
266{
267 if (!this.lobby || !this.lobby.players)
268 { return null; }
269 for (var i = 0; i < this.lobby.players.length; i++)
270 {
271 if (this.lobby.players[i].is_me)
272 { return this.lobby.players[i]; }
273 }
274 return null;
275};
276
277/* ---------- miniatures --------------------------------------------- */
278
279Online.renderMinis = function (container)
280{
281 if (!container)
282 { return; }
283 var opponents = this.opponents();
284 var existing = {};
285 var kids = container.querySelectorAll('[data-player]');
286 for (var i = 0; i < kids.length; i++)
287 { existing[kids[i].getAttribute('data-player')] = kids[i]; }
288
289 var seen = Object.create(null);
290 for (var i = 0; i < opponents.length; i++)
291 {
292 var p = opponents[i];
293 seen[p.id] = true;
294 var el = existing[p.id];
295 if (!el)
296 {
297 el = document.createElement('div');
298 el.className = 'mini';
299 el.setAttribute('data-player', p.id);
300 el.innerHTML = '<div class="mini-name"></div>'
301 + '<canvas class="mini-canvas" width="80" height="104"></canvas>'
302 + '<div class="mini-meta"></div>';
303 container.appendChild(el);
304 }
305 var mz = (typeof app !== 'undefined' && app.miniLayout && app.miniLayout.mini)
306 ? app.miniLayout.mini
307 : { w: 80, h: 104 };
308 var canvas = el.querySelector('canvas');
309 if (canvas && (canvas.width !== mz.w || canvas.height !== mz.h))
310 {
311 canvas.width = mz.w;
312 canvas.height = mz.h;
313 }
314 if (canvas)
315 {
316 canvas.style.width = mz.w + 'px';
317 canvas.style.height = mz.h + 'px';
318 }
319 el.classList.toggle('eliminated', !!p.eliminated);
320 el.querySelector('.mini-name').textContent = p.name + (p.is_host ? ' (host)' : '');
321 el.querySelector('.mini-meta').textContent = p.eliminated
322 ? ('Uit' + (p.place ? ' · ' + p.place + 'e' : ''))
323 : ('Punten ' + (p.score || 0));
324 this._drawMini(el.querySelector('canvas'), p.snapshot, p.planet);
325 }
326 for (var id in existing)
327 {
328 if (!seen[id])
329 { existing[id].remove(); }
330 }
331 if (typeof applyMinisLayout === 'function')
332 { applyMinisLayout(); }
333};
334
335var MINI_COLORS = ['#d4553a', '#3a9ad4', '#4caf6a', '#e6c04a', '#b86ad4'];
336
337function miniColor (planet, color)
338{
339 if (planet && planet.colors && planet.colors[color] && planet.colors[color].hex)
340 { return planet.colors[color].hex; }
341 return MINI_COLORS[color] || '#888';
342}
343
344
345Online._drawMini = function (canvas, snapshot, planet)
346{
347 if (!canvas)
348 { return; }
349 var ctx = canvas.getContext('2d');
350 var w = 10;
351 var h = 13;
352 var tw = canvas.width / w;
353 var th = canvas.height / h;
354 ctx.fillStyle = '#0c1020';
355 ctx.fillRect(0, 0, canvas.width, canvas.height);
356 ctx.strokeStyle = 'rgba(255,255,255,0.06)';
357 ctx.lineWidth = 1;
358 for (var c = 0; c <= w; c++)
359 {
360 ctx.beginPath();
361 ctx.moveTo(c * tw + 0.5, 0);
362 ctx.lineTo(c * tw + 0.5, canvas.height);
363 ctx.stroke();
364 }
365 for (var r = 0; r <= h; r++)
366 {
367 ctx.beginPath();
368 ctx.moveTo(0, r * th + 0.5);
369 ctx.lineTo(canvas.width, r * th + 0.5);
370 ctx.stroke();
371 }
372 if (!snapshot || !snapshot.blocks)
373 { return; }
374 // t1123: cheap sine pulse behind blocks of nearly-full columns.
375 if (typeof GameCore !== 'undefined' && GameCore.warnColumnsFromSnapshot)
376 {
377 var warns = GameCore.warnColumnsFromSnapshot(snapshot);
378 var pulse = GameCore.columnWarnPulse();
379 for (var wc = 0; wc < warns.length; wc++)
380 {
381 if (!warns[wc])
382 { continue; }
383 ctx.fillStyle = 'rgba(220, 36, 36,' + pulse + ')';
384 ctx.fillRect(wc * tw, 0, tw, canvas.height);
385 }
386 }
387 var blocks = snapshot.blocks;
388 for (var i = 0; i < blocks.length; i++)
389 {
390 var b = blocks[i];
391 var x = b.col * tw;
392 var y = canvas.height - (b.y + 1) * th;
393 if (b.state === 'locked')
394 { ctx.fillStyle = '#3a3d4a'; }
395 else if (b.color < 0)
396 { ctx.fillStyle = '#5a5d66'; }
397 else
398 { ctx.fillStyle = miniColor(planet, b.color); }
399 ctx.fillRect(x + 0.5, y + 0.5, tw - 1, th - 1);
400 }
401};
402
403Online.miniElement = function (playerId)
404{
405 return document.querySelector('#minis .mini[data-player="' + CSS.escape(playerId) + '"]');
406};
407
408/* ---------- flight tweens ------------------------------------------ */
409
410function colorSpriteUrl (color, planetId)
411{
412 if (color < 0)
413 { return 'images/block-gray.png'; }
414 var planet = null;
415 if (typeof Planet !== 'undefined')
416 { planet = Planet.planetById(planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra')); }
417 if (planet && planet.colors && planet.colors[color] && planet.colors[color].image)
418 { return planet.colors[color].image; }
419 return 'images/block-gray.png';
420}
421
422/**
423 * Animate shot results. `locals` is a map of client_id → {col, y, color,
424 * startX, startY} in viewport pixels, filled by the view just after
425 * consumeOutgoingShots.
426 */
427Online.playerId = function ()
428{
429 if (typeof app !== 'undefined' && app.offline)
430 { return 'player'; }
431 if (this.lobby && this.lobby.players)
432 {
433 for (var i = 0; i < this.lobby.players.length; i++)
434 {
435 if (this.lobby.players[i].is_me)
436 { return this.lobby.players[i].id; }
437 }
438 }
439 return 'player';
440};
441
442/**
443 * Classify a shot for visual treatment (t1125).
444 * player-to-enemy, enemy-to-player, enemy-to-enemy,
445 * player-miss, enemy-miss.
446 */
447Online.flightKind = function (fromId, targetId, miss)
448{
449 var me = this.playerId();
450 var fromMe = !fromId || fromId === me || fromId === 'player';
451 if (miss)
452 { return fromMe ? 'player-miss' : 'enemy-miss'; }
453 if (fromMe)
454 { return 'player-to-enemy'; }
455 if (targetId === me || targetId === 'player')
456 { return 'enemy-to-player'; }
457 return 'enemy-to-enemy';
458};
459
460/**
461 * Parabolic arc: linear in x, a rise of `height` pixels above the
462 * chord at mid-flight (screen y grows downward, so we subtract).
463 */
464Online.arcPoint = function (start, end, u, height)
465{
466 var t = u < 0 ? 0 : (u > 1 ? 1 : u);
467 var x = start.x + (end.x - start.x) * t;
468 var y = start.y + (end.y - start.y) * t - 4 * height * t * (1 - t);
469 return { x: x, y: y };
470};
471
472Online.arcHeight = function (start, end)
473{
474 var dx = end.x - start.x;
475 var dy = end.y - start.y;
476 var dist = Math.sqrt(dx * dx + dy * dy);
477 return Math.max(48, Math.min(220, dist * 0.28));
478};
479
480Online.easeInOutCubic = function (t)
481{
482 if (t < 0.5)
483 { return 4 * t * t * t; }
484 var u = -2 * t + 2;
485 return 1 - (u * u * u) / 2;
486};
487
488/** Bounding box of the player's field in viewport pixels. */
489Online.playerFieldRect = function ()
490{
491 var appRef = typeof app !== 'undefined' ? app : null;
492 var canvas = appRef && appRef.scene && appRef.scene.canvas;
493 if (canvas && canvas.getBoundingClientRect)
494 { return canvas.getBoundingClientRect(); }
495 if (appRef && appRef.fieldW)
496 {
497 return {
498 left: appRef.fieldX,
499 top: appRef.fieldY,
500 right: appRef.fieldX + appRef.fieldW,
501 bottom: appRef.fieldY + appRef.fieldH,
502 width: appRef.fieldW,
503 height: appRef.fieldH
504 };
505 }
506 return null;
507};
508
509/**
510 * True if (x, y) is inside the field's interior. The top edge (a few
511 * pixels) is not interior: that is where arcs may land (t1128).
512 */
513Online.pointInFieldInterior = function (x, y, field, slop)
514{
515 if (!field)
516 { return false; }
517 slop = slop == null ? 6 : slop;
518 return x > field.left + 0.5 && x < field.right - 0.5
519 && y > field.top + slop && y < field.bottom - 0.5;
520};
521
522/**
523 * Waypoints that route a player↔enemy arc around the field, never
524 * through its interior: up the outside, across above the top edge,
525 * then into the target (t1128). If both ends already sit at or above
526 * the top, a simple two-point path is enough.
527 */
528Online.waypointsAroundField = function (start, end, field, clearance)
529{
530 if (!start || !end)
531 { return [start || { x: 0, y: 0 }, end || { x: 0, y: 0 }]; }
532 if (!field)
533 { return [start, end]; }
534 clearance = clearance || 64;
535 var top = field.top;
536 var left = field.left;
537 var right = field.right;
538 var pad = 10;
539 var apexY = Math.min(start.y, end.y, top) - clearance;
540 if (apexY < 8)
541 { apexY = Math.max(8, top - Math.max(24, clearance * 0.5)); }
542
543 if (start.y <= top + 6 && end.y <= top + 6)
544 { return [start, end]; }
545
546 var w1x = start.x;
547 var w2x = end.x;
548 if (start.x < left)
549 { w1x = Math.min(start.x, left - pad); }
550 else if (start.x > right)
551 { w1x = Math.max(start.x, right + pad); }
552 if (end.x < left)
553 { w2x = Math.min(end.x, left - pad); }
554 else if (end.x > right)
555 { w2x = Math.max(end.x, right + pad); }
556
557 return [
558 start,
559 { x: w1x, y: apexY },
560 { x: w2x, y: apexY },
561 end
562 ];
563};
564
565/**
566 * Point at parameter u ∈ [0, 1] along a polyline, with a small upward
567 * bulge on each segment so the path reads as a "boogje".
568 */
569Online.pointOnPath = function (points, u)
570{
571 u = u < 0 ? 0 : (u > 1 ? 1 : u);
572 if (!points || !points.length)
573 { return { x: 0, y: 0 }; }
574 if (points.length === 1)
575 { return { x: points[0].x, y: points[0].y }; }
576 var lens = [];
577 var total = 0;
578 for (var i = 1; i < points.length; i++)
579 {
580 var dx = points[i].x - points[i - 1].x;
581 var dy = points[i].y - points[i - 1].y;
582 var L = Math.sqrt(dx * dx + dy * dy);
583 if (L < 1)
584 { L = 1; }
585 lens.push(L);
586 total += L;
587 }
588 var dist = u * total;
589 var acc = 0;
590 for (var i = 0; i < lens.length; i++)
591 {
592 if (acc + lens[i] >= dist || i === lens.length - 1)
593 {
594 var t = (dist - acc) / lens[i];
595 if (t < 0)
596 { t = 0; }
597 if (t > 1)
598 { t = 1; }
599 var a = points[i];
600 var b = points[i + 1];
601 var bump = 4 * 16 * t * (1 - t);
602 return {
603 x: a.x + (b.x - a.x) * t,
604 y: a.y + (b.y - a.y) * t - bump
605 };
606 }
607 acc += lens[i];
608 }
609 var last = points[points.length - 1];
610 return { x: last.x, y: last.y };
611};
612
613/** Sample a player↔enemy path; used by tests and the ticker. */
614Online.aroundFieldPoint = function (start, end, u, field, clearance)
615{
616 var pts = this.waypointsAroundField(start, end, field, clearance);
617 if (pts.length === 2)
618 {
619 var h = this.arcHeight(start, end);
620 return this.arcPoint(start, end, u, h);
621 }
622 return this.pointOnPath(pts, u);
623};
624
625Online.rememberLandCol = function (id, col)
626{
627 if (id == null || col == null || !isFinite(col))
628 { return; }
629 if (!this._pendingLandCol)
630 { this._pendingLandCol = Object.create(null); }
631 this._pendingLandCol[String(id)] = col | 0;
632};
633
634/** Resolve the landing column for an incoming shot (t1126). */
635Online.takeLandCol = function (incoming)
636{
637 if (!incoming)
638 { return null; }
639 if (incoming.land_col != null && isFinite(incoming.land_col))
640 { return incoming.land_col | 0; }
641 if (!this._pendingLandCol)
642 { return null; }
643 var keys = [];
644 if (incoming.id != null)
645 { keys.push(String(incoming.id)); }
646 if (incoming.client_id)
647 { keys.push(String(incoming.client_id)); }
648 for (var i = 0; i < keys.length; i++)
649 {
650 if (this._pendingLandCol[keys[i]] != null)
651 { return this._pendingLandCol[keys[i]]; }
652 }
653 return null;
654};
655
656Online._miniCellSize = function (playerId)
657{
658 var el = this.miniElement(playerId);
659 var canvas = el && el.querySelector('canvas');
660 if (canvas)
661 {
662 var r = canvas.getBoundingClientRect();
663 return Math.max(6, r.width / 10);
664 }
665 return 10;
666};
667
668Online._fullTileSize = function ()
669{
670 if (typeof app !== 'undefined' && app.tile)
671 { return app.tile; }
672 return 40;
673};
674
675Online._miniAnchor = function (playerId, dir)
676{
677 var el = this.miniElement(playerId);
678 var canvas = el && (el.querySelector ? el.querySelector('canvas') : null);
679 var box = canvas || el;
680 if (!box)
681 { return { x: window.innerWidth / 2, y: 48 }; }
682 var r = box.getBoundingClientRect();
683 if (dir === 'out')
684 { return { x: r.left + r.width / 2, y: r.top + 4 }; }
685 return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
686};
687
688Online._fieldTop = function (col)
689{
690 return this._flightStart(col);
691};
692
693/**
694 * Animate shot results. `locals` is a map of client_id → {col, y, color,
695 * startX, startY, from_id} in viewport pixels.
696 *
697 * Visual-only (t1125): a parabolic arc whose scale goes from mini-cell
698 * to full tile (or the reverse). Enemy-to-enemy arcs stay small and
699 * are drawn behind the player's field. Delivery timing is unchanged;
700 * a late-seen flight starts mid-arc via `age`.
701 */
702Online.spawnFlights = function (results, locals)
703{
704 locals = locals || this._flightLocals || {};
705 var front = document.getElementById('flights');
706 var back = document.getElementById('flights-back') || front;
707 if (!front)
708 { return; }
709 if (!this._flightSeen)
710 { this._flightSeen = Object.create(null); }
711 var now = performance.now();
712 var full = this._fullTileSize();
713 for (var i = 0; i < results.length; i++)
714 {
715 var r = results[i];
716 var sid = String(r.id != null ? r.id : (r.client_id || ('tmp-' + i)));
717 if (this._flightSeen[sid])
718 { continue; }
719 this._flightSeen[sid] = now;
720
721 var meta = locals[r.client_id] || locals[sid] || {};
722 var fromId = r.from_id || r.from_user || meta.from_id || null;
723 var targetId = r.target_id != null ? r.target_id : r.to_user;
724 var miss = !!r.miss;
725 var kind = this.flightKind(fromId, targetId, miss);
726 var duration = (r.flight_duration || this.FLIGHT_DURATION) * 1000;
727 if (r.age != null && isFinite(r.age) && r.age * 1000 >= duration)
728 { continue; }
729
730 var landCol = null;
731 if (r.land_col != null && isFinite(r.land_col))
732 { landCol = r.land_col | 0; }
733 else if (meta.land_col != null && isFinite(meta.land_col))
734 { landCol = meta.land_col | 0; }
735 else if (kind === 'enemy-to-player'
736 && typeof app !== 'undefined' && app.core && app.core.pickGarbageColumn)
737 { landCol = app.core.pickGarbageColumn(); }
738 if (landCol != null)
739 {
740 this.rememberLandCol(sid, landCol);
741 if (r.client_id)
742 { this.rememberLandCol(r.client_id, landCol); }
743 }
744
745 var start;
746 if (meta.startX != null && isFinite(meta.startX))
747 { start = { x: meta.startX, y: meta.startY }; }
748 else if (kind === 'player-to-enemy' || kind === 'player-miss')
749 { start = this._flightStart(meta.col != null ? meta.col : r.col); }
750 else
751 { start = this._miniAnchor(fromId, 'out'); }
752
753 var end;
754 if (miss)
755 { end = this._missEnd(start, kind === 'enemy-miss'); }
756 else if (kind === 'enemy-to-player')
757 { end = this._fieldTop(landCol != null ? landCol : 4.5); }
758 else
759 { end = this._targetEnd(targetId, start, landCol); }
760
761 // Hits are ingested as grey garbage; draw them grey (t1130).
762 // Misses keep the sender's colour — nothing is received.
763 var flightColor = miss
764 ? (r.color != null ? r.color : meta.color)
765 : -1;
766
767 var startScale;
768 var endScale;
769 var mini = this._miniCellSize(fromId || targetId) / full;
770 if (mini < 0.12)
771 { mini = 0.2; }
772 if (kind === 'player-to-enemy')
773 {
774 startScale = 1;
775 endScale = mini;
776 }
777 else if (kind === 'enemy-to-player')
778 {
779 startScale = mini;
780 endScale = 1;
781 }
782 else if (kind === 'enemy-to-enemy')
783 {
784 startScale = mini;
785 endScale = mini;
786 }
787 else if (kind === 'enemy-miss')
788 {
789 startScale = mini;
790 endScale = 0;
791 }
792 else
793 {
794 startScale = 1;
795 endScale = 0;
796 }
797
798 var layer = (kind === 'enemy-to-enemy' && back) ? back : front;
799 var el = document.createElement('img');
800 el.src = colorSpriteUrl(flightColor);
801 el.alt = '';
802 el.className = 'flight' + (kind === 'enemy-to-enemy' ? ' flight-behind' : '');
803 el.style.width = full + 'px';
804 el.style.height = full + 'px';
805 layer.appendChild(el);
806
807 var t0 = now;
808 if (r.age != null && isFinite(r.age) && r.age > 0)
809 {
810 var u0 = Math.min(0.95, (r.age * 1000) / duration);
811 t0 = now - u0 * duration;
812 }
813 var height = miss
814 ? Math.max(40, Math.min(160, Math.abs(end.y - start.y) * 0.35))
815 : this.arcHeight(start, end);
816 var field = this.playerFieldRect();
817 var around = !miss && (kind === 'enemy-to-player' || kind === 'player-to-enemy');
818 var waypoints = around ? this.waypointsAroundField(start, end, field, height * 0.45) : null;
819 this._flights.push({
820 el: el,
821 start: start,
822 end: end,
823 ctrl: miss ? this._missCtrl(start, end) : null,
824 height: height,
825 t0: t0,
826 duration: duration,
827 spin: (Math.random() * 2 - 1) * 720,
828 miss: miss,
829 kind: kind,
830 startScale: startScale,
831 endScale: endScale,
832 angle: Math.random() * 360,
833 id: sid,
834 landCol: landCol,
835 field: field,
836 waypoints: waypoints,
837 color: flightColor
838 });
839 }
840 this._flightLocals = {};
841};
842
843Online.rememberFlightLocal = function (shot, startX, startY)
844{
845 if (!this._flightLocals)
846 { this._flightLocals = {}; }
847 this._flightLocals[String(shot.id)] = {
848 col: shot.col,
849 y: shot.y,
850 color: shot.color,
851 startX: startX,
852 startY: startY,
853 from_id: shot.from_id
854 };
855};
856
857Online._flightStart = function (col)
858{
859 var appRef = typeof app !== 'undefined' ? app : null;
860 if (appRef && appRef.scene && appRef.scene.canvas)
861 {
862 var canvas = appRef.scene.canvas;
863 var rect = canvas.getBoundingClientRect();
864 var c = col == null ? 4.5 : col;
865 return {
866 x: rect.left + (c + 0.5) * (rect.width / 10),
867 y: rect.top + 4
868 };
869 }
870 var field = document.querySelector('canvas');
871 if (field)
872 {
873 var rect = field.getBoundingClientRect();
874 return { x: rect.left + rect.width / 2, y: rect.top };
875 }
876 return { x: window.innerWidth / 2, y: window.innerHeight * 0.3 };
877};
878
879Online._targetEnd = function (targetId, start, col)
880{
881 var el = targetId && this.miniElement(targetId);
882 if (el)
883 {
884 var canvas = el.querySelector('canvas') || el;
885 var r = canvas.getBoundingClientRect();
886 var x = r.left + r.width / 2;
887 if (col != null && isFinite(col))
888 { x = r.left + ((col + 0.5) / 10) * r.width; }
889 return { x: x, y: r.top + 4 };
890 }
891 return { x: start.x + (Math.random() - 0.5) * 80, y: 40 };
892};
893
894Online._missEnd = function (start, fromMini)
895{
896 var w = window.innerWidth || 800;
897 var outward;
898 if (start.x < w * 0.4)
899 { outward = -(80 + Math.random() * w * 0.25); }
900 else if (start.x > w * 0.6)
901 { outward = (80 + Math.random() * w * 0.25); }
902 else
903 { outward = (Math.random() * 2 - 1) * w * 0.35; }
904 var lift = fromMini ? (80 + Math.random() * 160) : (120 + Math.random() * 220);
905 return { x: start.x + outward, y: start.y - lift };
906};
907
908Online._missCtrl = function (start, end)
909{
910 return {
911 x: (start.x + end.x) / 2 + (Math.random() - 0.5) * 160,
912 y: Math.min(start.y, end.y) - 40 - Math.random() * 80
913 };
914};
915
916Online._hitCtrl = function (start, end)
917{
918 return {
919 x: (start.x + end.x) / 2 + (Math.random() - 0.5) * 40,
920 y: (start.y + end.y) / 2 - 30
921 };
922};
923
924Online.tickFlights = function (now)
925{
926 now = now || performance.now();
927 var leftover = [];
928 for (var i = 0; i < this._flights.length; i++)
929 {
930 var f = this._flights[i];
931 var raw = (now - f.t0) / f.duration;
932 if (raw >= 1)
933 {
934 if (f.el && f.el.parentNode)
935 { f.el.parentNode.removeChild(f.el); }
936 continue;
937 }
938 if (raw < 0)
939 { raw = 0; }
940 var u = this.easeInOutCubic(raw);
941 var x, y;
942 if (f.miss && f.ctrl)
943 {
944 var e = raw * raw;
945 var mt = 1 - e;
946 x = mt * mt * f.start.x + 2 * mt * e * f.ctrl.x + e * e * f.end.x;
947 y = mt * mt * f.start.y + 2 * mt * e * f.ctrl.y + e * e * f.end.y;
948 }
949 else if (f.waypoints && f.waypoints.length > 2)
950 {
951 var pt = this.pointOnPath(f.waypoints, u);
952 x = pt.x;
953 y = pt.y;
954 }
955 else if (f.waypoints && f.field)
956 {
957 var pt = this.aroundFieldPoint(f.start, f.end, u, f.field, (f.height || 80) * 0.45);
958 x = pt.x;
959 y = pt.y;
960 }
961 else
962 {
963 var pt = this.arcPoint(f.start, f.end, u, f.height || 80);
964 x = pt.x;
965 y = pt.y;
966 }
967 var scale = f.startScale + (f.endScale - f.startScale) * u;
968 if (f.miss)
969 {
970 var fadeU = raw * raw;
971 scale = f.startScale * (1 - fadeU);
972 }
973 var angle = f.angle + f.spin * raw;
974 f.el.style.transform = 'translate(' + x + 'px,' + y + 'px) translate(-50%,-50%) rotate('
975 + angle + 'deg) scale(' + scale + ')';
976 f.el.style.opacity = f.miss ? String(Math.max(0, 1 - raw * raw)) : '1';
977 leftover.push(f);
978 }
979 this._flights = leftover;
980 if (this._flightSeen)
981 {
982 var cutoff = now - 8000;
983 var ids = Object.keys(this._flightSeen);
984 for (var k = 0; k < ids.length; k++)
985 {
986 if (this._flightSeen[ids[k]] < cutoff)
987 { delete this._flightSeen[ids[k]]; }
988 }
989 }
990};
991
992Online.clearFlights = function ()
993{
994 for (var i = 0; i < this._flights.length; i++)
995 {
996 var el = this._flights[i].el;
997 if (el && el.parentNode)
998 { el.parentNode.removeChild(el); }
999 }
1000 this._flights = [];
1001 this._flightLocals = {};
1002 this._flightSeen = Object.create(null);
1003 this._pendingLandCol = Object.create(null);
1004};
1005
1006if (typeof globalThis !== 'undefined')
1007{ globalThis.Online = Online; }
1008if (typeof module !== 'undefined' && module.exports)
1009{ module.exports = Online; }