1082 lines
61 KiB
HTML
1082 lines
61 KiB
HTML
<!doctype html>
|
|
<html lang="en">
|
|
<head>
|
|
<meta charset="utf-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover">
|
|
<meta name="robots" content="noindex, nofollow">
|
|
<title>Vice City Online</title>
|
|
<meta name="description" content="Vice City multiplayer in your browser. Free roam, no install, up to 32 players.">
|
|
<meta name="theme-color" content="#000000">
|
|
<link rel="canonical" href="https://gta.crt.fyi/">
|
|
<meta property="og:type" content="website">
|
|
<meta property="og:url" content="https://gta.crt.fyi/">
|
|
<meta property="og:site_name" content="crt.fyi">
|
|
<meta property="og:locale" content="en_US">
|
|
<meta property="og:title" content="Vice City Online">
|
|
<meta property="og:description" content="Vice City multiplayer in your browser. Free roam, no install, up to 32 players.">
|
|
<meta property="og:image" content="https://gta.crt.fyi/og.jpg">
|
|
<meta property="og:image:type" content="image/jpeg">
|
|
<meta property="og:image:width" content="1200">
|
|
<meta property="og:image:height" content="630">
|
|
<meta property="og:image:alt" content="A Vice City beach and skyline with a player in the foreground">
|
|
<meta name="twitter:card" content="summary_large_image">
|
|
<meta name="twitter:site" content="@CRTkafa">
|
|
<meta name="twitter:title" content="Vice City Online">
|
|
<meta name="twitter:description" content="Vice City multiplayer in your browser. Free roam, no install, up to 32 players.">
|
|
<meta name="twitter:image" content="https://gta.crt.fyi/og.jpg">
|
|
<meta name="twitter:image:alt" content="A Vice City beach and skyline with a player in the foreground">
|
|
<link rel="icon" type="image/png" sizes="64x64" href="/favicon-64.png">
|
|
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32.png">
|
|
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
|
|
<style>
|
|
html, body { margin: 0; height: 100%; background: #000; overflow: hidden; overscroll-behavior: none; -webkit-user-select: none; user-select: none; -webkit-touch-callout: none; }
|
|
canvas { display: block; outline: none; cursor: none; transform-origin: 0 0; }
|
|
/* Loading bar in the style of the game's own: shown until the first frame, then gone. */
|
|
#bar { position: fixed; left: 6.25vw; right: 6.25vw; bottom: 2.9vh; height: 0.9vh; min-height: 4px;
|
|
background: #9b327d; outline: 1px solid #283544; transition: opacity .4s; }
|
|
#status { position: fixed; left: 6.25vw; bottom: 4.6vh; font: 600 13px/1.4 "Trebuchet MS", Arial, sans-serif;
|
|
letter-spacing: .04em; color: #ff96e1; text-shadow: 1px 1px 0 #000; transition: opacity .4s; }
|
|
#bar i { display: block; height: 100%; width: 0; background: #ff96e1; }
|
|
/* A small spinner in the corner while the game waits for data from the network. */
|
|
#spin { position: fixed; right: 2vw; bottom: 2vh; width: 22px; height: 22px; border-radius: 50%;
|
|
border: 3px solid rgba(255,150,225,.25); border-top-color: #ff96e1; opacity: 0; transition: opacity .15s;
|
|
animation: spin .8s linear infinite; pointer-events: none; }
|
|
@keyframes spin { to { transform: rotate(360deg); } }
|
|
/* In-game online UI: plain text in the game's own look (white / pink, black shadow). */
|
|
.ui { position: fixed; font: 700 15px/1.35 "Trebuchet MS", Arial, sans-serif; color: #fff;
|
|
text-shadow: 1px 1px 0 #000, -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000; pointer-events: none; display: none; }
|
|
#net { left: 1.5vw; top: 1.5vh; font-size: 14px; }
|
|
#net b { color: #5dff8a; } #net.slow b { color: #ffe27a; } #net.bad b, #net.off b { color: #ff5d5d; }
|
|
#chat { left: 20vw; bottom: 6.5vh; width: 44vw; }
|
|
#pos { left: 1.5vw; top: 5vh; font-size: 13px; color: #5dff8a; display: none; }
|
|
#chat div { width: fit-content; max-width: 100%; margin-bottom: 2px; padding: 0 6px; background: rgba(0,0,0,.35); transition: opacity 1s; }
|
|
#chat .n { color: #ff96e1; } #chat .sys { color: #ffe27a; }
|
|
#chatbar { position: fixed; left: 20vw; bottom: 1.5vh; width: 44vw; display: none; box-sizing: border-box; padding: 4px 8px; align-items: center; gap: 6px; z-index: 30;
|
|
font: 700 15px "Trebuchet MS", Arial, sans-serif; color: #ff96e1; background: rgba(0,0,0,.65); border: 1px solid #ff96e1; }
|
|
#chatin { flex: 1; min-width: 0; font: inherit; color: #fff; background: none; border: 0; outline: none; padding: 0; }
|
|
#namebox { position: fixed; left: 50%; top: 38%; transform: translateX(-50%); display: none; padding: 16px 22px; background: rgba(0,0,0,.85); border: 2px solid #ff96e1; z-index: 40; text-align: center;
|
|
font: 400 22px "VCMenu", Impact, sans-serif; color: #f0a5d8; text-shadow: 2px 2px 0 #000; user-select: none; }
|
|
#namein { display: block; margin: 10px auto; width: 260px; max-width: 70vw; box-sizing: border-box; padding: 6px 8px; font: 700 16px "Trebuchet MS", Arial, sans-serif; color: #fff; background: #000; border: 1px solid #ff96e1; outline: none; }
|
|
#nameok { font: inherit; color: inherit; background: none; border: 0; cursor: pointer; }
|
|
#board { left: 50%; top: 12vh; transform: translateX(-50%); min-width: 380px; max-height: 70vh; overflow: hidden; padding: 14px 22px 16px; background: rgba(0,0,0,.8);
|
|
border-left: 4px solid #ff5fc4; }
|
|
#board h4 { margin: 0 0 10px; color: #ff5fc4; font: 400 30px "VCMenu", Impact, sans-serif; font-style: italic; text-shadow: 3px 3px 0 #000; }
|
|
#board .row { display: flex; justify-content: space-between; gap: 40px; padding: 3px 0; border-top: 1px solid rgba(255,150,225,.18); }
|
|
#board .me { color: #5dff8a; }
|
|
#help { right: 1.5vw; bottom: 24vh; text-align: right; white-space: pre; font-size: 13px; line-height: 1.5; opacity: .92; }
|
|
#help { opacity: 0; transition: opacity .5s; }
|
|
#help.show { opacity: .92; }
|
|
#help a { color: #ff96e1; pointer-events: auto; }
|
|
/* between the stick and the buttons, where no thumb goes */
|
|
#help.touchlink { left: 50%; right: auto; bottom: 1vh; transform: translateX(-50%); text-align: center; }
|
|
@font-face { font-family: "VCMenu"; src: url("BowlbyOne.ttf"); }
|
|
.menu { position: fixed; inset: 0; display: none; box-sizing: border-box; padding: 5vh 6vw; overflow: auto; background: rgba(0,0,0,.72);
|
|
font: 400 20px "VCMenu", Impact, sans-serif; color: #f0a5d8; text-shadow: 2px 2px 0 #000; user-select: none; cursor: default; }
|
|
.menu h4 { margin: 0 0 2vh; color: #ff5fc4; font: 400 clamp(36px, 7vh, 72px) "VCMenu", Impact, sans-serif; font-style: italic; text-shadow: 4px 4px 0 #000; }
|
|
.menu h5 { margin: 2vh 0 1vh; color: #5fd6e8; font: 400 22px "VCMenu", Impact, sans-serif; }
|
|
.menu .grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(190px, 1fr)); gap: 4px 14px; }
|
|
.menu .featured { grid-template-columns: repeat(auto-fill, minmax(min(280px, 40vw), 1fr)); gap: 8px; }
|
|
.menu button { font: inherit; color: inherit; text-shadow: inherit; background: none; border: 0; border-radius: 0; padding: 4px 10px; text-align: left; cursor: inherit; outline: 0; }
|
|
.menu button img { display: block; width: 100%; aspect-ratio: 16 / 9; object-fit: cover; margin-bottom: 4px; }
|
|
.menu button.sel { background: #1f8a3c; color: #fff; }
|
|
#wheel { position: fixed; inset: 0; display: none; background: rgba(0,0,0,.45); font: 400 15px "VCMenu", Impact, sans-serif; color: #f0a5d8; text-shadow: 2px 2px 0 #000; user-select: none; }
|
|
#wheel .slot { position: absolute; width: 150px; height: 122px; margin: -61px 0 0 -75px; background: rgba(0,0,0,.8); text-align: center; box-sizing: border-box; padding: 6px; }
|
|
#wheel .slot img { display: block; width: 64px; height: 64px; margin: 0 auto 3px; }
|
|
#wheel .slot.sel { background: #1f8a3c; color: #fff; }
|
|
#wheel .mid { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); width: 200px; text-align: center; color: #ff5fc4; font-size: 24px; }
|
|
#touch { position: fixed; inset: 0; display: none; touch-action: none; }
|
|
#touch, #tmenu { font: 400 13px "VCMenu", Impact, sans-serif; color: #fff; text-shadow: 1px 1px 0 #000; }
|
|
#touch .b, #tmenu .b { position: absolute; display: flex; align-items: center; justify-content: center; box-sizing: border-box; border-radius: 50%; background: rgba(0,0,0,.42); border: 2px solid rgba(255,150,225,.75); touch-action: none; }
|
|
#touch .b.bar, #tmenu .b.bar { border-radius: 0; padding: 6px 7px; font-size: 10px; }
|
|
#touch .b.on, #tmenu .b.on { background: rgba(31,138,60,.8); }
|
|
/* the mobile game's own round button pictures */
|
|
#touch .b.ic, #tmenu .b.ic { padding: 0; border: 0; border-radius: 50%; background: center / contain no-repeat; opacity: .85; }
|
|
#touch .b.bar.ic, #tmenu .b.bar.ic { width: 9vmin; height: 9vmin; }
|
|
#touch .b.ic.on, #tmenu .b.ic.on { opacity: 1; filter: brightness(1.7) drop-shadow(0 0 5px #ff96e1); background-color: transparent; }
|
|
#touch .stick.ic { border: 0; background: center / contain no-repeat; }
|
|
#touch .stick.ic i { background: center / contain no-repeat; }
|
|
#touch .stick { position: absolute; display: none; border-radius: 50%; border: 2px solid rgba(255,150,225,.6); background: rgba(0,0,0,.25); pointer-events: none; }
|
|
#touch .stick i { position: absolute; left: 50%; top: 50%; width: 44%; height: 44%; margin: -22% 0 0 -22%; border-radius: 50%; background: rgba(255,150,225,.7); }
|
|
#tmenu { position: fixed; display: none; z-index: 5; }
|
|
#rotate { position: fixed; inset: 0; z-index: 9; display: none; align-items: center; justify-content: center; text-align: center; padding: 8vw; background: #000; color: #ff96e1; font: 400 26px "VCMenu", Impact, sans-serif; }
|
|
.menu { touch-action: pan-y; }
|
|
.menu .grid { grid-template-columns: repeat(auto-fill, minmax(min(190px, 28vw), 1fr)); }
|
|
@media (max-height: 520px) {
|
|
#wheel .slot { width: 92px; height: 74px; margin: -37px 0 0 -46px; padding: 3px; font-size: 10px; }
|
|
#wheel .slot img { width: 38px; height: 38px; margin-bottom: 1px; }
|
|
#wheel .mid { font-size: 18px; width: 140px; }
|
|
#chat, #chatbar { font-size: 12px; left: 30vw; width: 44vw; }
|
|
#board { top: 14vh; min-width: min(340px, 60vw); max-height: 70vh; overflow: hidden; }
|
|
#net { font-size: 12px; }
|
|
.menu { font-size: 15px; padding: 3vh 4vw; }
|
|
.menu h5 { font-size: 16px; }
|
|
}
|
|
/* player tags */
|
|
#tags { position: fixed; inset: 0; overflow: hidden; pointer-events: none; }
|
|
.tag { position: absolute; left: 0; top: 0; display: none; flex-direction: column; align-items: center; will-change: transform; font: 400 16px "VCMenu", Impact, sans-serif; color: #5fd6e8; text-shadow: 2px 2px 0 #000; white-space: nowrap; }
|
|
.tag i { width: 0; height: 0; margin-top: 2px; border-left: 7px solid transparent; border-right: 7px solid transparent; border-top: 10px solid #5fd6e8; filter: drop-shadow(1px 1px 0 #000); }
|
|
/* kills, top right */
|
|
#feed { position: fixed; right: 1.5vw; top: 22vh; display: flex; flex-direction: column; align-items: flex-end; gap: 2px; pointer-events: none; font: 400 15px "VCMenu", Impact, sans-serif; color: #f0a5d8; text-shadow: 2px 2px 0 #000; }
|
|
/* death */
|
|
#death { position: fixed; inset: 0; display: none; flex-direction: column; align-items: center; justify-content: center; pointer-events: none; }
|
|
#death b { font: 400 clamp(40px, 9vh, 84px) "VCMenu", Impact, sans-serif; font-style: italic; color: #ff5fc4; text-shadow: 4px 4px 0 #000; }
|
|
#death span { font: 400 20px "VCMenu", Impact, sans-serif; color: #f0a5d8; text-shadow: 2px 2px 0 #000; }
|
|
/* the world still downloading behind the game */
|
|
#bgload { position: fixed; left: 1.5vw; bottom: 1.5vh; display: none; width: 180px; pointer-events: none; font: 400 12px "VCMenu", Impact, sans-serif; color: #f0a5d8; text-shadow: 1px 1px 0 #000; }
|
|
#bgload div { height: 4px; margin-top: 2px; background: #9b327d; outline: 1px solid #283544; }
|
|
#bgload i { display: block; height: 100%; width: 0; background: #ff96e1; }
|
|
/* over the pause menu: the name belongs to the page, not to the game's own settings */
|
|
#namebtn { position: fixed; right: 3vw; bottom: 4vh; display: none; z-index: 30; cursor: pointer; font: 400 clamp(20px, 4.5vh, 34px) "VCMenu", Impact, sans-serif; color: #f0a5d8; text-shadow: 2px 2px 0 #000; user-select: none; }
|
|
#namebtn:hover { color: #fff; }
|
|
/* radio: the game's station logos in place of its line of text */
|
|
#radio { position: fixed; left: 50%; top: 2vh; transform: translateX(-50%); display: none; align-items: center; gap: 8px; z-index: 20; pointer-events: none; user-select: none; }
|
|
#radio.open, #radio.mini { display: flex; }
|
|
#radio.touch { top: calc(3vh + 11vmin); pointer-events: auto; }
|
|
#radio .r { position: relative; width: min(12vmin, 64px); height: min(12vmin, 64px); opacity: .6; text-align: center; font: 400 min(3vmin, 15px)/min(12vmin, 64px) "VCMenu", Impact, sans-serif; color: #fff; text-shadow: 2px 2px 0 #000; }
|
|
#radio .r img { width: 100%; height: 100%; display: block; }
|
|
#radio .r.sel { width: min(18vmin, 96px); height: min(18vmin, 96px); line-height: min(18vmin, 96px); opacity: 1; }
|
|
#radio.mini .r:not(.sel) { display: none; }
|
|
#radio.mini .r.sel { width: 9vmin; height: 9vmin; line-height: 9vmin; opacity: .85; }
|
|
#radio #rname { position: absolute; left: 50%; top: 100%; transform: translateX(-50%); white-space: nowrap; font: 400 18px "VCMenu", Impact, sans-serif; color: #ff96e1; text-shadow: 2px 2px 0 #000; }
|
|
#radio.mini #rname { display: none; }
|
|
#hint { left: 50%; top: 6vh; transform: translateX(-50%); padding: 6px 14px; font-size: 15px; color: #ffe27a; white-space: nowrap; background: rgba(0,0,0,.65); border-left: 3px solid #ffe27a; }
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<canvas id="canvas" tabindex="-1" oncontextmenu="event.preventDefault()"></canvas>
|
|
<div id="bar"><i></i></div>
|
|
<div id="status"></div>
|
|
<div id="spin"></div>
|
|
<div id="net" class="ui"><b>●</b> <span id="nettext"></span></div>
|
|
<div id="chat" class="ui"></div>
|
|
<div id="pos" class="ui"></div>
|
|
<div id="chatbar"><span>say:</span><input id="chatin" maxlength="120" autocomplete="off" spellcheck="false"></div>
|
|
<div id="namebox"><div id="nametitle"></div><input id="namein" maxlength="20" autocomplete="off" spellcheck="false"><button id="nameok"></button></div>
|
|
<div id="board" class="ui"></div>
|
|
<div id="tags"></div>
|
|
<div id="feed"></div>
|
|
<div id="bgload"><span></span><div><i></i></div></div>
|
|
<div id="death"><b id="deathtitle"></b><span id="deathby"></span></div>
|
|
<div id="help" class="ui"></div>
|
|
<div id="wmenu" class="menu"></div>
|
|
<div id="wheel"></div>
|
|
<div id="radio"></div>
|
|
<div id="namebtn"></div>
|
|
<div id="cmenu" class="menu"></div>
|
|
<div id="touch"></div>
|
|
<div id="tmenu"></div>
|
|
<div id="rotate"></div>
|
|
<div id="hint" class="ui">click to capture the mouse · Esc releases it · Tab: players · T: chat</div>
|
|
<script type="application/json" id="loadareas">["Ocean Beach","Washington Beach","Vice Point","Leaf Links","Starfish Island","Prawn Island","Downtown","Little Havana","Little Haiti","Viceport","Escobar International"]</script>
|
|
<script>
|
|
// The page stays a black canvas until the game draws its own (vanilla) screens.
|
|
const params = new URLSearchParams(location.search);
|
|
// The deploy script puts the data path (an unguessable one, so a CDN may cache it) in place of
|
|
// the marker; a local run uses "data".
|
|
const dataUrl = params.get("data") || (/^__/.test("__DATA_URL__") ? "data" : "__DATA_URL__");
|
|
|
|
// ?mute=1 silences the game at the source (previews and automated checks): audio still
|
|
// plays, into a zero-gain node, and window.vcAudioLevel() reports how loud it would be.
|
|
if (params.get("mute") === "1") {
|
|
const Base = window.AudioContext || window.webkitAudioContext;
|
|
window.AudioContext = window.webkitAudioContext = class extends Base {
|
|
constructor(o) {
|
|
super(o);
|
|
// game -> tap -> (analyser, zero gain -> speakers)
|
|
const tap = this.createGain();
|
|
const silent = this.createGain();
|
|
silent.gain.value = 0;
|
|
tap.connect(silent);
|
|
silent.connect(super.destination);
|
|
const analyser = this.createAnalyser();
|
|
tap.connect(analyser);
|
|
Object.defineProperty(this, "destination", { value: tap });
|
|
window.vcAudioLevel = () => {
|
|
const d = new Float32Array(analyser.fftSize);
|
|
analyser.getFloatTimeDomainData(d);
|
|
return Math.sqrt(d.reduce((s, x) => s + x * x, 0) / d.length);
|
|
};
|
|
}
|
|
};
|
|
}
|
|
|
|
// The game's log, without repeats, for debugging from the console (window.vcLog).
|
|
window.vcLog = [];
|
|
function keepLog(text, out) {
|
|
if (text.includes("GS_PLAYING_GAME")) window.vcPlaying = true;
|
|
if (text.includes("[online] remote player")) (window.vcRemoteLog ||= []).push(text);
|
|
if (vcLog.length && vcLog[vcLog.length - 1].text === text) { vcLog[vcLog.length - 1].n++; return; }
|
|
vcLog.push({ text, n: 1 });
|
|
if (vcLog.length > 3000) vcLog.shift();
|
|
if (!text.startsWith("[DBG]") || new URLSearchParams(location.search).has("debug")) out(text); // the streaming log is constant, and the console is slow
|
|
}
|
|
|
|
async function loadEagerFiles() {
|
|
if (params.has("readlog")) Module.vcReadLog = [];
|
|
const { files, ranged, bundle, start } = await (await fetch(`${dataUrl}/manifest.json`, { cache: "no-cache" })).json();
|
|
Module.vcRanged = ranged;
|
|
Module.vcRangedMap = new Map(ranged.map((f) => [f.path, f.size]));
|
|
const out = [];
|
|
let next = 0, doneBytes = 0;
|
|
const memory = ranged.filter((f) => f.memory);
|
|
const totalBytes = files.reduce((n, f) => n + f.size, 0);
|
|
// Image files flagged "memory" are downloaded whole and kept in the page, so that
|
|
// streaming never waits on the network while playing. The browser keeps them between visits.
|
|
Module.vcImages = {};
|
|
async function loadImage(f) {
|
|
// The pieces live in the browser's normal HTTP cache: measured 8 s for a repeat visit against 20 s
|
|
// with a second copy in cache storage, whose saving also stalled the game. Old copies are freed here.
|
|
try { caches.delete("vc-images").catch(() => {}); } catch (e) {}
|
|
const cache = null, hit = null;
|
|
const buf = new Uint8Array(f.size);
|
|
if (hit) {
|
|
setStatus(T("Loading {0}", loadArea()));
|
|
buf.set(new Uint8Array(await hit.arrayBuffer()));
|
|
doneBytes += f.size;
|
|
} else {
|
|
// Eight-megabyte pieces, six at a time: a CDN serves small files quickly and caches each one.
|
|
// The CDN unpacks zstd and sends it whole, so pieces on another host are always the gzip ones.
|
|
const ua = navigator.userAgent;
|
|
const m = /Chrome\/(\d+)/.exec(ua) || /Firefox\/(\d+)/.exec(ua);
|
|
const ext = !/^https?:/.test(dataUrl) && m && +m[1] >= (/Firefox/.test(ua) ? 126 : 123) ? "zst" : "gz";
|
|
const PIECE = 8 * 1024 * 1024, n = Math.ceil(f.size / PIECE);
|
|
const base = `${dataUrl}/chunks/${f.path.split("/").pop()}`;
|
|
const started = new Uint8Array(n), done = new Uint8Array(n);
|
|
let next = 0, active = 0;
|
|
doneBytes = 0;
|
|
// What the game has just asked for comes first, then the rest in order.
|
|
function takePiece() {
|
|
const want = Module.vcPart.want;
|
|
while (want.length) {
|
|
const k = want.pop();
|
|
if (k < n && !started[k]) { started[k] = 1; return k; }
|
|
}
|
|
while (next < n && started[next]) next++;
|
|
if (next >= n) return -1;
|
|
started[next] = 1;
|
|
return next;
|
|
}
|
|
async function piece() {
|
|
for (;;) {
|
|
// While the game waits on a read only one piece runs, so the download never stops
|
|
// and never crowds the read out on a slow line.
|
|
while (busy > 0 && active > 0) await new Promise((r) => setTimeout(r, 100));
|
|
const k = takePiece();
|
|
if (k < 0) return;
|
|
active++;
|
|
const name = `${base}.${String(k).padStart(3, "0")}.${ext}`;
|
|
let res;
|
|
for (let tries = 0; ; tries++) {
|
|
try { res = await fetch(name); if (res.ok) break; } catch (e) {}
|
|
if (tries >= 3) throw new Error(`${name}: download failed`);
|
|
}
|
|
const data = new Uint8Array(await res.arrayBuffer());
|
|
buf.set(data, k * PIECE);
|
|
done[k] = 1;
|
|
active--;
|
|
doneBytes += data.length;
|
|
bgProgress(doneBytes, f.size);
|
|
}
|
|
}
|
|
let chunked = true;
|
|
try { chunked = (await fetch(`${base}.000.${ext}`, { method: "HEAD" })).ok; } catch (e) { chunked = false; }
|
|
if (chunked) {
|
|
Module.vcPart = { key: f.path, size: PIECE, buf, done, want: [] };
|
|
bgProgress(0, f.size);
|
|
await Promise.all(Array.from({ length: 3 }, piece));
|
|
}
|
|
else {
|
|
// No pieces on this host (a local run): one plain download.
|
|
const res = await fetch(`${dataUrl}/${f.path}`);
|
|
if (!res.ok) throw new Error(`${f.path}: HTTP ${res.status}`);
|
|
buf.set(new Uint8Array(await res.arrayBuffer()));
|
|
}
|
|
}
|
|
Module.vcImages[f.path] = buf;
|
|
Module.vcStart = null;
|
|
Module.vcPart = null;
|
|
el("bgload").style.display = "none";
|
|
// Saved for the next visit once the game is running, so the copy cannot slow the start-up.
|
|
if (cache && !hit) {
|
|
const save = setInterval(() => {
|
|
if (!window.vcPlaying) return;
|
|
clearInterval(save);
|
|
setTimeout(() => cache.put(tag, new Response(buf)).catch(() => {}), 5000);
|
|
}, 1000);
|
|
}
|
|
}
|
|
async function worker() {
|
|
while (next < files.length) {
|
|
const f = files[next++];
|
|
const res = await fetch(`${dataUrl}/${f.path}`);
|
|
if (!res.ok) throw new Error(`${f.path}: HTTP ${res.status}`);
|
|
out.push([f.path, new Uint8Array(await res.arrayBuffer())]);
|
|
doneBytes += f.size;
|
|
setProgress(0.1 * doneBytes / totalBytes);
|
|
}
|
|
}
|
|
if (bundle) {
|
|
// One request for all small files; sizes in manifest order say where each one starts.
|
|
setStatus(T("Loading game files {0} MB", mb(bundle.size)));
|
|
const res = await fetch(`${dataUrl}/${bundle.path}${bundle.hash ? `?v=${bundle.hash}` : ""}`);
|
|
if (!res.ok) throw new Error(`${bundle.path}: HTTP ${res.status}`);
|
|
const all = new Uint8Array(await res.arrayBuffer());
|
|
let at = 0;
|
|
for (const f of files) { out.push([f.path, all.subarray(at, at + f.size)]); at += f.size; }
|
|
setProgress(0.1);
|
|
} else {
|
|
await Promise.all(Array.from({ length: 8 }, worker));
|
|
}
|
|
if (start) {
|
|
setStatus(T("Loading {0}", loadArea()));
|
|
const res = await fetch(`${dataUrl}/${start.path}?v=${start.hash}`);
|
|
if (res.ok) {
|
|
let pos = 0;
|
|
const ranges = start.ranges.map(([at, size]) => { const r = { at, size, pos }; pos += size; return r; });
|
|
Module.vcStart = { key: start.key, ranges, data: new Uint8Array(await res.arrayBuffer()) };
|
|
}
|
|
setProgress(0.2);
|
|
}
|
|
// The world image comes whole behind the running game: until it is here the engine reads what it
|
|
// needs with range requests, afterwards everything is instant.
|
|
// ?imgdelay=<seconds> holds it back, to try the game while the image is not here yet.
|
|
new Promise((r) => setTimeout(r, (+params.get("imgdelay") || 0) * 1000)).then(() => Promise.all(memory.map(loadImage))).catch((e) => { el("bgload").style.display = "none"; console.warn("image download failed, streaming instead", e); });
|
|
return out;
|
|
}
|
|
|
|
// The game draws one canvas pixel per canvas CSS pixel; the glfw layer would multiply the buffer
|
|
// by the display ratio and the game would render into a corner of it. So the ratio is pinned to 1
|
|
// and the canvas is made as many CSS pixels wide as the screen has real pixels (at most 2560),
|
|
// then shrunk back by a transform: the picture is sharp on Full HD and high-DPI screens.
|
|
const screenRatio = window.devicePixelRatio || 1;
|
|
Object.defineProperty(window, "devicePixelRatio", { get: () => 1 });
|
|
function fitCanvas() {
|
|
const c = document.getElementById("canvas");
|
|
// Phones draw fewer pixels: menu.json says how many (window.vcRenderWidth is set once it is read).
|
|
const k = window.vcRenderWidth ? Math.min(screenRatio, window.vcRenderWidth / window.innerWidth) : Math.max(1, Math.min(screenRatio, 2560 / window.innerWidth));
|
|
c.style.width = Math.round(window.innerWidth * k) + "px";
|
|
c.style.height = Math.round(window.innerHeight * k) + "px";
|
|
c.style.transform = `scale(${1 / k})`;
|
|
}
|
|
fitCanvas();
|
|
window.addEventListener("resize", fitCanvas);
|
|
|
|
// Loading bar: real progress while the files download, then a slow creep until the game is up.
|
|
const bar = document.getElementById("bar"), barFill = bar.firstElementChild;
|
|
let progress = 0, creeping = false;
|
|
function setProgress(p) { progress = Math.max(progress, p); barFill.style.width = progress * 100 + "%"; }
|
|
setInterval(() => { if (creeping && progress < 0.97) setProgress(progress + (0.97 - progress) * 0.03); }, 200);
|
|
const statusEl = document.getElementById("status");
|
|
const mb = (n) => (n / 1048576).toFixed(n < 10485760 ? 1 : 0);
|
|
function bgProgress(done, size) {
|
|
const b = el("bgload");
|
|
b.style.display = "block";
|
|
b.firstElementChild.textContent = `${mb(done)} / ${mb(size)} MB`;
|
|
b.querySelector("i").style.width = done / size * 100 + "%";
|
|
}
|
|
function loadArea() {
|
|
const a = JSON.parse(document.getElementById("loadareas").textContent);
|
|
return a[Math.floor(performance.now() / 1400) % a.length];
|
|
}
|
|
function setStatus(text) { statusEl.textContent = text; }
|
|
function gameIsUp() { bar.style.opacity = 0; statusEl.style.opacity = 0; setTimeout(() => { bar.remove(); statusEl.remove(); }, 500); }
|
|
|
|
// Network activity of the game's streaming: a spinner when it has been waiting a moment.
|
|
let busy = 0, spinTimer = 0;
|
|
const spin = document.getElementById("spin");
|
|
function vcBusy(delta) {
|
|
busy = Math.max(0, busy + delta);
|
|
clearTimeout(spinTimer);
|
|
if (busy > 0) spinTimer = setTimeout(() => { spin.style.opacity = 1; }, 250);
|
|
else spin.style.opacity = 0;
|
|
}
|
|
|
|
// ---- online UI: chat, connection state, player list (Tab), mouse hint ----
|
|
const canvasEl = document.getElementById("canvas");
|
|
const net = { id: -1, max: 8, ping: null, players: new Map(), up: false };
|
|
const outbox = [];
|
|
let nick = (() => {
|
|
try { const n = localStorage.getItem("vcName"); if (n) return n; } catch (e) {}
|
|
const n = "Player" + Math.floor(100 + Math.random() * 900);
|
|
try { localStorage.setItem("vcName", n); } catch (e) {}
|
|
return n;
|
|
})();
|
|
const el = (id) => document.getElementById(id);
|
|
// The page speaks the language chosen in the game's menu: English text is the key into lang.json.
|
|
let langs = {}, langNow = "en";
|
|
const LANG_CODES = ["en", "fr", "de", "it", "tr"];
|
|
function currentLang() {
|
|
try { const v = localStorage.getItem("vcLang"); if (v !== null) return LANG_CODES[+v] || "en"; } catch (e) {}
|
|
const c = (navigator.language || "en").slice(0, 2).toLowerCase();
|
|
return LANG_CODES.includes(c) ? c : "en";
|
|
}
|
|
function T(text, ...args) {
|
|
let out = (langs[langNow] && langs[langNow][text]) || text;
|
|
args.forEach((a, i) => { out = out.replace(`{${i}}`, a); });
|
|
return out;
|
|
}
|
|
// What the player set last time goes over the shipped defaults, key by key. The window size belongs to
|
|
// the browser and the language to its own setting, so a saved copy of those never comes back.
|
|
function restoreSettings() {
|
|
let saved = null;
|
|
try { saved = localStorage.getItem("vcSettings"); } catch (e) {}
|
|
if (!saved) return;
|
|
try {
|
|
// The game writes this file itself on its first run: there may be none yet.
|
|
let lines = [];
|
|
try { lines = Module.FS.readFile("/vc/reVC.ini", { encoding: "utf8" }).split(/\r?\n/); } catch (e) {}
|
|
const parse = (text) => { const out = {}; let sec = ""; for (const l of text.split(/\r?\n/)) { const m = /^\[(.+)\]/.exec(l), kv = /^([^=]+?)\s*=\s*(.*)$/.exec(l); if (m) sec = m[1]; else if (kv) out[sec + "/" + kv[1]] = kv[2]; } return out; };
|
|
const mine = parse(saved), merged = [], seen = new Set();
|
|
const skip = (k) => k.startsWith("VideoMode/") || k === "Graphics/VideoMode" || k === "General/Language";
|
|
let sec = "";
|
|
for (const l of lines) {
|
|
const m = /^\[(.+)\]/.exec(l), kv = /^([^=]+?)\s*=/.exec(l);
|
|
if (m) sec = m[1];
|
|
const k = kv && sec + "/" + kv[1];
|
|
if (k) seen.add(k);
|
|
merged.push(k && k in mine && !skip(k) ? `${kv[1]} = ${mine[k]}` : l);
|
|
}
|
|
// Keys the shipped file does not have, such as key bindings the player added.
|
|
for (const k of Object.keys(mine)) {
|
|
if (seen.has(k) || skip(k)) continue;
|
|
const [s, ...name] = k.split("/");
|
|
let at = merged.indexOf(`[${s}]`);
|
|
if (at < 0) { merged.push(`[${s}]`); at = merged.length - 1; }
|
|
merged.splice(at + 1, 0, `${name.join("/")} = ${mine[k]}`);
|
|
}
|
|
Module.FS.writeFile("/vc/reVC.ini", merged.join("\n"));
|
|
} catch (e) { console.warn("settings not restored", e); }
|
|
}
|
|
let menuEnglish = null;
|
|
function applyLang() {
|
|
langNow = currentLang();
|
|
document.documentElement.lang = langNow;
|
|
el("chatbar").firstElementChild.textContent = T("say:");
|
|
el("hint").textContent = T("click to capture the mouse \u00b7 Esc releases it \u00b7 Tab: players \u00b7 T: chat");
|
|
if (!net.up) el("nettext").textContent = T(window.vcPlaying ? "reconnecting" : "connecting");
|
|
if (!menuData || !menuEnglish) return;
|
|
const en = menuEnglish, m = menuData;
|
|
for (const k of ["title", "placeholder", "ok", "locked", "away", "back"]) m.name[k] = T(en.name[k]);
|
|
m.death.title = T(en.death.title); m.death.killedBy = T(en.death.killedBy);
|
|
m.help = en.help.map((l) => T(l));
|
|
m.weapons.forEach((w, i) => { w.name = T(en.weapons[i].name); });
|
|
m.wheel.forEach((w, i) => { w.name = T(en.wheel[i].name); });
|
|
m.carGroups = en.carGroups.map((g) => T(g));
|
|
m.cars.forEach((c, i) => { c.group = T(en.cars[i].group); });
|
|
renderHelp();
|
|
if (m.touch) el("rotate").textContent = T(en.touch.rotate);
|
|
for (const d of document.querySelectorAll("[data-label]")) {
|
|
const label = T(d.dataset.label);
|
|
d.title = label;
|
|
if (!d.style.backgroundImage) d.textContent = label;
|
|
}
|
|
}
|
|
fetch("lang.json", { cache: "no-cache" }).then((r) => r.json()).then((j) => { langs = j; applyLang(); }).catch(() => {});
|
|
setInterval(() => { if (currentLang() !== langNow) applyLang(); }, 500);
|
|
function chatLine(parts, cls) {
|
|
const box = el("chat"), d = document.createElement("div");
|
|
if (cls) d.className = cls;
|
|
for (const [text, c] of parts) { const sp = document.createElement("span"); if (c) sp.className = c; sp.textContent = text; d.appendChild(sp); }
|
|
box.appendChild(d);
|
|
while (box.children.length > 7) box.firstChild.remove();
|
|
setTimeout(() => { d.style.opacity = 0; setTimeout(() => d.remove(), 1000); }, 12000);
|
|
}
|
|
// Frames the game really finished, once a second.
|
|
setInterval(() => { if (!window.Module) return; net.fps = Module.vcFrames || 0; Module.vcFrames = 0; renderNet(); }, 1000);
|
|
function renderNet() {
|
|
el("net").classList.toggle("off", !net.up);
|
|
el("net").classList.toggle("slow", net.up && net.ping >= 150 && net.ping < 300);
|
|
el("net").classList.toggle("bad", net.up && net.ping >= 300);
|
|
el("nettext").textContent = net.up ? `${T("online")} ${net.players.size + 1}/${net.max}` + (net.ping != null ? ` \u00b7 ${net.ping} ms` : "") + ` \u00b7 ${net.fps || 0} fps` : T("reconnecting");
|
|
}
|
|
function renderBoard() {
|
|
const b = el("board");
|
|
b.textContent = "";
|
|
const h = document.createElement("h4"); h.textContent = `${T("Players")} ${net.players.size + 1}/${net.max}`; b.appendChild(h);
|
|
const add = (name, right, me) => {
|
|
const r = document.createElement("div"); r.className = "row" + (me ? " me" : "");
|
|
const a = document.createElement("span"), c = document.createElement("span");
|
|
a.textContent = name; c.textContent = right; r.append(a, c); b.appendChild(r);
|
|
};
|
|
add(nick + " (you)", net.ping != null ? net.ping + " ms" : "", true);
|
|
for (const [, p] of net.players) add(p.name, "", false);
|
|
}
|
|
// Back on the network, or back on this tab: try at once instead of waiting for the next retry.
|
|
window.addEventListener("online", () => { if (window.Module) Module.vcRetryNow = 1; });
|
|
document.addEventListener("visibilitychange", () => { if (!document.hidden && window.Module) Module.vcRetryNow = 1; });
|
|
function onNet(text) {
|
|
let m; try { m = JSON.parse(text); } catch (e) { return; }
|
|
if (m.t === "open") { net.up = true; renderNet(); }
|
|
else if (m.t === "closed") { net.up = false; net.players.clear(); renderNet(); if (!net.lost) chatLine([[T("connection lost, reconnecting"), ""]], "sys"); net.lost = true; }
|
|
else if (m.t === "welcome") { net.lost = false; net.id = m.id; net.max = m.max || 8; renderNet(); chatLine([[T("connected as {0}. T: chat, Tab: players", nick), ""]], "sys"); }
|
|
else if (m.t === "snap") {
|
|
const seen = new Set();
|
|
for (const p of m.p) {
|
|
seen.add(p.id);
|
|
if (!net.players.has(p.id)) { net.players.set(p.id, { name: p.name }); chatLine([[T("{0} joined", p.name), ""]], "sys"); }
|
|
else net.players.get(p.id).name = p.name;
|
|
}
|
|
for (const id of [...net.players.keys()]) if (!seen.has(id)) { chatLine([[T("{0} left", net.players.get(id).name), ""]], "sys"); net.players.delete(id); }
|
|
renderNet();
|
|
if (el("board").style.display === "block") renderBoard();
|
|
}
|
|
else if (m.t === "kill") {
|
|
const f = document.createElement("div");
|
|
f.textContent = m.killer ? `${m.killer} \u203a ${m.victim}` : m.victim;
|
|
el("feed").appendChild(f);
|
|
setTimeout(() => f.remove(), (loadMenuData().death.feedSeconds) * 1000);
|
|
if (m.killer && m.victim === nick) el("deathby").textContent = `${loadMenuData().death.killedBy} ${m.killer}`;
|
|
}
|
|
else if (m.t === "protected") chatLine([[T("spawn protection: {0} s", m.seconds), ""]], "sys");
|
|
else if (m.t === "passive") chatLine([[T(m.wait ? "passive mode: wait a few seconds" : m.on ? "passive mode on" : "passive mode off"), ""]], "sys");
|
|
else if (m.t === "away") { if (m.wait) { chatLine([[menuData.name.locked, ""]], "sys"); } else chatLine([[m.on ? menuData.name.away : menuData.name.back, ""]], "sys"); }
|
|
else if (m.t === "chat") chatLine([[m.name + ": ", "n"], [m.text, ""]]);
|
|
else if (m.t === "pong") { net.ping = Math.round(performance.now() - m.n); renderNet(); }
|
|
}
|
|
setInterval(() => { if (net.up) outbox.push(JSON.stringify({ t: "ping", n: performance.now() })); }, 2000);
|
|
|
|
let typing = false;
|
|
const isTouch = params.get("touch") === "1" || matchMedia("(pointer: coarse)").matches;
|
|
// Names over the other players. The engine says where each one is on every frame.
|
|
const tagEls = new Map();
|
|
let tagsSeen = new Set();
|
|
function bindTags() {
|
|
const near = () => loadMenuData().tags;
|
|
Module.vcTagsBegin = () => { tagsSeen = new Set(); };
|
|
Module.vcTag = (id, x, y, dist) => {
|
|
const p = net.players.get(id);
|
|
if (!p || Module.vcMenuActive) return;
|
|
let t = tagEls.get(id);
|
|
if (!t) {
|
|
t = document.createElement("div"); t.className = "tag";
|
|
t.appendChild(document.createElement("span")); t.appendChild(document.createElement("i"));
|
|
el("tags").appendChild(t); tagEls.set(id, t);
|
|
}
|
|
if (t.firstChild.textContent !== p.name) t.firstChild.textContent = p.name;
|
|
const c = near(), k = Math.max(c.minScale, Math.min(1, c.fullScaleDistance / Math.max(dist, 1)));
|
|
t.style.transform = `translate(${x * innerWidth}px, ${y * innerHeight}px) translate(-50%, -100%) scale(${k})`;
|
|
t.style.display = "flex";
|
|
tagsSeen.add(id);
|
|
};
|
|
Module.vcTagsEnd = () => {
|
|
for (const [id, t] of tagEls) {
|
|
if (tagsSeen.has(id)) continue;
|
|
if (net.players.has(id)) t.style.display = "none";
|
|
else { t.remove(); tagEls.delete(id); }
|
|
}
|
|
};
|
|
Module.vcDeath = (on) => {
|
|
const d = loadMenuData().death;
|
|
el("deathtitle").textContent = d.title;
|
|
if (on) el("deathby").textContent = "";
|
|
el("death").style.display = on ? "flex" : "none";
|
|
};
|
|
}
|
|
const bindTagsTimer = setInterval(() => { if (window.vcPlaying && window.Module) { clearInterval(bindTagsTimer); bindTags(); } }, 250);
|
|
function captureMouse() { if (isTouch) return; try { canvasEl.requestPointerLock(); } catch (e) {} }
|
|
document.addEventListener("pointerlockchange", () => {
|
|
if (document.pointerLockElement) { if (window.Module) Module.vcLookHold = performance.now() + ((menuData && menuData.lookSettleMs) || 0); return; }
|
|
// The browser takes Esc for itself while the mouse is captured: the same press opens the pause menu too.
|
|
if (!window.vcPlaying || Module.vcMenuActive || openMenu || typing || wheelOpen || !document.hasFocus() || fightLocked()) return;
|
|
setTimeout(() => {
|
|
if (Module.vcMenuActive || performance.now() - lastEsc < 300) return;
|
|
outboxCmd("pause");
|
|
}, 120);
|
|
});
|
|
let lastEsc = -1000;
|
|
window.addEventListener("keydown", (e) => { if (e.key === "Escape" && e.isTrusted) lastEsc = performance.now(); }, true);
|
|
let helpUntil = 0;
|
|
let showPos = false, naming = false, awaySent = false;
|
|
function setName(v) {
|
|
nick = v.trim().slice(0, 20) || nick;
|
|
try { localStorage.setItem("vcName", nick); localStorage.setItem("vcNamed", "1"); } catch (e) {}
|
|
outbox.push(JSON.stringify({ t: "hello", name: nick }));
|
|
chatLine([[T("you are now {0}", nick), ""]], "sys");
|
|
}
|
|
const fightLocked = () => Date.now() - (Module.vcLastHit || 0) < loadMenuData().name.fightLockSeconds * 1000;
|
|
function openName() {
|
|
if (naming) return;
|
|
if (fightLocked()) { chatLine([[menuData.name.locked, ""]], "sys"); return; }
|
|
naming = typing = true; try { document.exitPointerLock(); } catch (e) {}
|
|
const n = menuData.name, i = el("namein");
|
|
el("nametitle").textContent = n.title; el("nameok").textContent = n.ok; i.placeholder = n.placeholder; i.value = nick;
|
|
el("namebox").style.display = "block"; i.focus(); i.select();
|
|
}
|
|
function closeName(save) {
|
|
naming = typing = false; el("namebox").style.display = "none"; el("namein").blur();
|
|
if (save) setName(el("namein").value);
|
|
else try { localStorage.setItem("vcNamed", "1"); } catch (e) {}
|
|
if (!Module.vcMenuActive) captureMouse();
|
|
}
|
|
function openChat() { typing = true; try { document.exitPointerLock(); } catch (e) {} const i = el("chatin"); el("chatbar").style.display = "flex"; i.value = ""; i.focus(); }
|
|
function closeChat(send) {
|
|
const i = el("chatin"), text = i.value.trim();
|
|
typing = false; el("chatbar").style.display = "none"; i.blur();
|
|
if (send && text) {
|
|
if (text === "/name") openName();
|
|
else if (text === "/stuck") {
|
|
if (Module.vcInVehicle) chatLine([[T("leave the vehicle first"), ""]], "sys");
|
|
else if (fightLocked()) chatLine([[menuData.name.locked, ""]], "sys");
|
|
else outboxCmd("respawn");
|
|
}
|
|
else if (text === "/pos") { showPos = !showPos; el("pos").style.display = showPos ? "block" : "none"; }
|
|
else if (text === "/mark" && Module.vcPos) {
|
|
const [x, y, z, h] = Module.vcPos, heading = Math.round(h * 180 / Math.PI);
|
|
chatLine([[`marked x ${x.toFixed(1)}, y ${y.toFixed(1)}, z ${z.toFixed(1)}, heading ${heading}`, ""]], "sys");
|
|
outbox.push(JSON.stringify({ t: "marker", x: +x.toFixed(1), y: +y.toFixed(1), z: +z.toFixed(1), heading }));
|
|
} else if (text.startsWith("/name ")) {
|
|
setName(text.slice(6));
|
|
} else outbox.push(JSON.stringify({ t: "chat", text }));
|
|
}
|
|
captureMouse();
|
|
}
|
|
// Menus and the on-screen command list come from online/menu.json (inside the game files).
|
|
let menuData = null;
|
|
function loadMenuData() {
|
|
if (menuData) return menuData;
|
|
try { menuData = JSON.parse(Module.FS.readFile("/vc/online/menu.json", { encoding: "utf8" })); } catch (e) { menuData = { keys: {}, weapons: [], cars: [], help: [] }; }
|
|
menuEnglish = JSON.parse(JSON.stringify(menuData));
|
|
if (isTouch && menuData.touch) setupTouch(menuData.touch);
|
|
applyLang();
|
|
return menuData;
|
|
}
|
|
function renderHelp() {
|
|
const h = el("help");
|
|
h.textContent = "";
|
|
if (isTouch) h.classList.add("touchlink");
|
|
for (const line of isTouch ? menuData.help.filter((l) => /^x\.com\//.test(l)) : menuData.help) {
|
|
const d = document.createElement("div");
|
|
if (/^x\.com\//.test(line)) { const a = document.createElement("a"); a.textContent = line; a.href = "https://" + line; d.appendChild(a); h.style.pointerEvents = "auto"; a.target = "_blank"; a.rel = "noopener"; }
|
|
else d.textContent = line;
|
|
h.appendChild(d);
|
|
}
|
|
}
|
|
let openMenu = null;
|
|
function thumbUrl(model) {
|
|
try { return URL.createObjectURL(new Blob([Module.FS.readFile(`/vc/online/thumbs/${model}.jpg`)], { type: "image/jpeg" })); }
|
|
catch (e) { return null; }
|
|
}
|
|
function select(b) {
|
|
for (const o of el(openMenu).querySelectorAll("button.sel")) o.classList.remove("sel");
|
|
b.classList.add("sel");
|
|
b.scrollIntoView({ block: "nearest" });
|
|
}
|
|
function menuButtons(box, grid, items, cmd, pictures) {
|
|
for (const it of items) {
|
|
const b = document.createElement("button");
|
|
const url = pictures && thumbUrl(it.model);
|
|
if (url) { const i = document.createElement("img"); i.src = url; i.alt = ""; b.appendChild(i); }
|
|
b.appendChild(document.createTextNode(it.name));
|
|
b.addEventListener("click", () => { outboxCmd(cmd(it)); closeMenu(); });
|
|
b.addEventListener("mouseenter", () => select(b));
|
|
grid.appendChild(b);
|
|
}
|
|
}
|
|
// The top of the vehicle list: what this player called last, then the usual picks.
|
|
function recentVehicles() { try { return JSON.parse(localStorage.getItem("vcRecent")) || []; } catch (e) { return []; } }
|
|
function rememberVehicle(model) { try { localStorage.setItem("vcRecent", JSON.stringify([model, ...recentVehicles().filter((m) => m !== model)].slice(0, 6))); } catch (e) {} }
|
|
const vehicleShortlist = () => [...new Set([...recentVehicles(), ...menuData.featured])].slice(0, menuData.featured.length);
|
|
function showMenu(id, title, items, cmd, featured) {
|
|
const box = el(id);
|
|
box.textContent = "";
|
|
const h = document.createElement("h4"); h.textContent = title; box.appendChild(h);
|
|
const add = (cls, list, pics) => { const g = document.createElement("div"); g.className = cls; box.appendChild(g); menuButtons(box, g, list, cmd, pics); };
|
|
if (featured) {
|
|
add("grid featured", featured.map((m) => items.find((c) => c.model === m)).filter(Boolean), true);
|
|
const groups = menuData.carGroups || [];
|
|
if (!groups.length) add("grid", items.filter((c) => !featured.includes(c.model)), true);
|
|
for (const g of groups) {
|
|
const h = document.createElement("h5"); h.textContent = g; box.appendChild(h);
|
|
add("grid", items.filter((c) => c.group === g), true);
|
|
}
|
|
} else add("grid", items, false);
|
|
try { document.exitPointerLock(); } catch (e) {}
|
|
box.style.display = "block";
|
|
openMenu = id;
|
|
select(box.querySelector("button"));
|
|
}
|
|
// Arrow keys walk the buttons by where they are on screen, as in the game's own menus.
|
|
function moveSelection(key) {
|
|
const all = [...el(openMenu).querySelectorAll("button")], cur = el(openMenu).querySelector("button.sel");
|
|
const r = cur.getBoundingClientRect(), dx = key === "ArrowLeft" ? -1 : key === "ArrowRight" ? 1 : 0, dy = key === "ArrowUp" ? -1 : key === "ArrowDown" ? 1 : 0;
|
|
let best = null, bestD = Infinity;
|
|
for (const b of all) {
|
|
if (b === cur) continue;
|
|
const q = b.getBoundingClientRect(), x = q.left - r.left, y = q.top - r.top;
|
|
if ((dx && x * dx <= 1) || (dy && y * dy <= 1)) continue;
|
|
const d = dx ? Math.abs(x) + 4 * Math.abs(y) : Math.abs(y) + 4 * Math.abs(x);
|
|
if (d < bestD) { bestD = d; best = b; }
|
|
}
|
|
if (best) select(best);
|
|
}
|
|
// Weapon wheel: hold the key, push the mouse towards a slot, the wheel cycles inside a slot, release to take it.
|
|
let wheelOpen = false, wheelSel = 0, wheelX = 0, wheelY = 0;
|
|
const wheelPick = {};
|
|
function weaponIcon(type) {
|
|
try { return URL.createObjectURL(new Blob([Module.FS.readFile(`/vc/online/icons/w${type}.png`)], { type: "image/png" })); }
|
|
catch (e) { return null; }
|
|
}
|
|
const weaponName = (t) => (menuData.weapons.find((w) => w.type === t) || {}).name || "";
|
|
const wheelIcons = new Map();
|
|
function wheelIcon(type) {
|
|
if (!wheelIcons.has(type)) wheelIcons.set(type, weaponIcon(type));
|
|
return wheelIcons.get(type);
|
|
}
|
|
function renderWheel() {
|
|
const box = el("wheel"), slots = menuData.wheel;
|
|
if (box.childElementCount !== slots.length + 1) {
|
|
box.textContent = "";
|
|
for (let i = 0; i <= slots.length; i++) {
|
|
const d = document.createElement("div");
|
|
if (i < slots.length) { d.appendChild(document.createElement("img")).alt = ""; d.appendChild(document.createElement("span")); }
|
|
else d.className = "mid";
|
|
box.appendChild(d);
|
|
}
|
|
}
|
|
// The outer edge of the top and bottom slots stays on the screen, whatever its height.
|
|
const side = Math.min(window.innerWidth, window.innerHeight), slotH = box.firstChild.offsetHeight;
|
|
const r = Math.min(side * 0.34, side / 2 - slotH / 2 - 6);
|
|
slots.forEach((s, i) => {
|
|
const a = (i / slots.length) * Math.PI * 2 - Math.PI / 2, type = s.types[(wheelPick[i] || 0) % s.types.length];
|
|
const d = box.children[i], cls = "slot" + (i === wheelSel ? " sel" : "");
|
|
if (d.className !== cls) d.className = cls;
|
|
d.style.left = `calc(50% + ${Math.cos(a) * r}px)`; d.style.top = `calc(50% + ${Math.sin(a) * r}px)`;
|
|
const url = wheelIcon(type), im = d.firstChild;
|
|
if (d.dataset.type !== String(type)) { d.dataset.type = type; if (url) im.src = url; else im.removeAttribute("src"); }
|
|
im.style.display = url ? "" : "none";
|
|
const text = s.types.length > 1 ? `${weaponName(type)} (${(wheelPick[i] || 0) % s.types.length + 1}/${s.types.length})` : weaponName(type);
|
|
if (d.lastChild.textContent !== text) d.lastChild.textContent = text;
|
|
});
|
|
const m = box.lastChild;
|
|
if (m.textContent !== slots[wheelSel].name) m.textContent = slots[wheelSel].name;
|
|
}
|
|
// In the pause menu: change the name without leaving it.
|
|
el("namebtn").addEventListener("click", (e) => { e.stopPropagation(); openName(); });
|
|
setInterval(() => {
|
|
const b = el("namebtn"), on = !!(window.vcPlaying && window.Module && Module.vcMenuActive && !naming);
|
|
if (on) { const t = T("Change name: {0}", nick); if (b.textContent !== t) b.textContent = t; }
|
|
b.style.display = on ? "block" : "none";
|
|
}, 200);
|
|
// Radio strip: follows the station the game reports; on a phone a tap on a logo tunes to it.
|
|
let radioSeq = 0, radioUntil = 0, radioShown = -2, radioMade = false;
|
|
function makeRadio() {
|
|
const box = el("radio");
|
|
radioMade = true;
|
|
if (isTouch) box.classList.add("touch");
|
|
for (const s of menuData.radio) {
|
|
const d = document.createElement("div");
|
|
d.className = "r";
|
|
d.dataset.station = s.station;
|
|
let url = null;
|
|
try { if (s.icon) url = URL.createObjectURL(new Blob([Module.FS.readFile(`/vc/online/icons/r${s.station}.png`)], { type: "image/png" })); } catch (e) {}
|
|
if (url) { const i = document.createElement("img"); i.src = url; i.alt = ""; d.appendChild(i); } else d.textContent = "OFF";
|
|
box.appendChild(d);
|
|
}
|
|
box.addEventListener("pointerdown", (e) => {
|
|
e.preventDefault(); e.stopPropagation();
|
|
const open = box.classList.contains("open"), r = e.target.closest(".r");
|
|
radioUntil = performance.now() + 3000;
|
|
if (open && r) outboxCmd("radio " + r.dataset.station);
|
|
});
|
|
}
|
|
setInterval(() => {
|
|
if (!window.Module || !menuData || !menuData.radio) return;
|
|
const box = el("radio");
|
|
if (!window.vcPlaying || !Module.vcInVehicle || Module.vcMenuActive || Module.vcRadio === undefined) { box.className = isTouch ? "touch" : ""; return; }
|
|
if (!radioMade) makeRadio();
|
|
const now = performance.now();
|
|
if ((Module.vcRadioSeq || 0) !== radioSeq) { radioSeq = Module.vcRadioSeq || 0; radioUntil = now + 3000; }
|
|
box.className = (isTouch ? "touch " : "") + (now < radioUntil ? "open" : isTouch ? "mini" : "");
|
|
if (radioShown === Module.vcRadio) return;
|
|
radioShown = Module.vcRadio;
|
|
let name = el("rname");
|
|
if (!name) { name = document.createElement("div"); name.id = "rname"; }
|
|
for (const d of box.querySelectorAll(".r")) d.classList.toggle("sel", +d.dataset.station === radioShown);
|
|
const st = menuData.radio.find((s) => s.station === radioShown), sel = box.querySelector(".r.sel");
|
|
name.textContent = st ? T(st.name) : "";
|
|
if (sel) sel.appendChild(name);
|
|
}, 100);
|
|
function openWheel() { wheelOpen = true; wheelX = wheelY = 0; el("wheel").style.display = "block"; renderWheel(); }
|
|
// The game's own menu takes over: the wheel goes without choosing anything.
|
|
setInterval(() => { if (wheelOpen && Module.vcMenuActive) { wheelOpen = false; el("wheel").style.display = "none"; } }, 100);
|
|
function closeWheel() {
|
|
if (!wheelOpen) return;
|
|
wheelOpen = false; el("wheel").style.display = "none";
|
|
const s = menuData.wheel[wheelSel]; outboxCmd("weapon " + s.types[(wheelPick[wheelSel] || 0) % s.types.length]);
|
|
}
|
|
window.addEventListener("mousemove", (e) => {
|
|
if (!wheelOpen) return;
|
|
e.stopImmediatePropagation();
|
|
wheelX += e.movementX; wheelY += e.movementY;
|
|
const len = Math.hypot(wheelX, wheelY);
|
|
if (len > 200) { wheelX *= 200 / len; wheelY *= 200 / len; }
|
|
if (len < 30) return;
|
|
const n = menuData.wheel.length, i = (Math.round((Math.atan2(wheelY, wheelX) + Math.PI / 2) / (Math.PI * 2) * n) + n) % n;
|
|
if (i !== wheelSel) { wheelSel = i; renderWheel(); }
|
|
}, true);
|
|
window.addEventListener("wheel", (e) => {
|
|
if (!wheelOpen) return;
|
|
e.stopImmediatePropagation();
|
|
wheelPick[wheelSel] = (wheelPick[wheelSel] || 0) + (e.deltaY > 0 ? 1 : menuData.wheel[wheelSel].types.length - 1);
|
|
renderWheel();
|
|
}, { capture: true, passive: true });
|
|
for (const t of ["mousedown", "mouseup"]) window.addEventListener(t, (e) => { if (wheelOpen) e.stopImmediatePropagation(); }, true);
|
|
// ---- touch controls: stick on the left half, look on the right half, buttons from menu.json ----
|
|
function sendKey(k, down) {
|
|
const e = new KeyboardEvent(down ? "keydown" : "keyup", { key: k.key, code: k.code, keyCode: k.keyCode, which: k.keyCode, bubbles: true, cancelable: true });
|
|
if (e.keyCode !== k.keyCode) { Object.defineProperty(e, "keyCode", { value: k.keyCode }); Object.defineProperty(e, "which", { value: k.keyCode }); }
|
|
document.body.dispatchEvent(e); // the game listens further up than the window's capture phase
|
|
}
|
|
function sendMouse(type, button) {
|
|
canvasEl.dispatchEvent(new MouseEvent(type, { button, buttons: type === "mousedown" ? 1 << button : 0, bubbles: true, clientX: 10, clientY: 10 }));
|
|
}
|
|
function setupTouch(t) {
|
|
window.vcRenderWidth = t.renderWidth;
|
|
Module.vcTouch = 1; // the camera follows the look area only, not the cursor taps move
|
|
fitCanvas();
|
|
const box = el("touch"), bar = el("tmenu");
|
|
const stick = document.createElement("div"); stick.className = "stick";
|
|
const knob = document.createElement("i"); stick.appendChild(knob); box.appendChild(stick);
|
|
stick.style.width = stick.style.height = t.stickRadius * 2 + "px";
|
|
const held = { up: false, down: false, left: false, right: false };
|
|
const setDir = (d, on) => { if (held[d] !== on) { held[d] = on; sendKey(t.stick[d], on); } };
|
|
let stickId = null, sx = 0, sy = 0;
|
|
const looks = new Map();
|
|
box.addEventListener("touchstart", (e) => {
|
|
if (e.target !== box) return;
|
|
e.preventDefault();
|
|
for (const f of e.changedTouches) {
|
|
if (f.clientX < window.innerWidth / 2 && stickId === null) {
|
|
stickId = f.identifier; sx = f.clientX; sy = f.clientY;
|
|
stick.style.left = sx - t.stickRadius + "px"; stick.style.top = sy - t.stickRadius + "px"; stick.style.display = "block"; knob.style.transform = "";
|
|
} else looks.set(f.identifier, [f.clientX, f.clientY]);
|
|
}
|
|
}, { passive: false });
|
|
box.addEventListener("touchmove", (e) => {
|
|
e.preventDefault();
|
|
for (const f of e.changedTouches) {
|
|
if (f.identifier === stickId) {
|
|
let dx = (f.clientX - sx) / t.stickRadius, dy = (f.clientY - sy) / t.stickRadius;
|
|
const len = Math.hypot(dx, dy);
|
|
if (len > 1) { dx /= len; dy /= len; }
|
|
knob.style.transform = `translate(${dx * t.stickRadius}px, ${dy * t.stickRadius}px)`;
|
|
setDir("left", dx < -t.stickDeadZone); setDir("right", dx > t.stickDeadZone); setDir("up", dy < -t.stickDeadZone); setDir("down", dy > t.stickDeadZone);
|
|
} else if (looks.has(f.identifier)) {
|
|
const [x, y] = looks.get(f.identifier);
|
|
Module.vcLookX = (Module.vcLookX || 0) + (f.clientX - x) * t.lookSpeed;
|
|
Module.vcLookY = (Module.vcLookY || 0) + (f.clientY - y) * t.lookSpeed;
|
|
looks.set(f.identifier, [f.clientX, f.clientY]);
|
|
}
|
|
}
|
|
}, { passive: false });
|
|
const end = (e) => {
|
|
for (const f of e.changedTouches) {
|
|
if (f.identifier === stickId) { stickId = null; stick.style.display = "none"; for (const d in held) setDir(d, false); }
|
|
looks.delete(f.identifier);
|
|
}
|
|
};
|
|
box.addEventListener("touchend", end);
|
|
box.addEventListener("touchcancel", end);
|
|
for (const b of t.buttons) {
|
|
const d = document.createElement("div");
|
|
d.className = "b" + (b.bar ? " bar" : "");
|
|
d.textContent = T(b.label);
|
|
d.dataset.label = b.label;
|
|
if (b.icon) { d.dataset.icon = b.icon; d.classList.add("ic"); d.setAttribute("aria-label", b.label); }
|
|
d.style.right = `calc(${b.right}vw + env(safe-area-inset-right))`;
|
|
if (b.top !== undefined) d.style.top = b.top + "vh"; else d.style.bottom = b.bottom + "vh";
|
|
if (b.size) d.style.width = d.style.height = b.size + "vmin";
|
|
d.addEventListener("touchstart", (e) => e.preventDefault(), { passive: false });
|
|
let on = false, lastX = null, lastY = null;
|
|
const press = (down) => {
|
|
if (b.wheel) { if (down && !Module.vcMenuActive) { if (wheelOpen) closeWheel(); else if (!Module.vcInVehicle) openWheel(); } return; }
|
|
if (b.mouse !== undefined) sendMouse(down ? "mousedown" : "mouseup", b.mouse);
|
|
else sendKey(b, down);
|
|
};
|
|
d.addEventListener("pointerdown", (e) => {
|
|
e.preventDefault(); e.stopPropagation();
|
|
lastX = e.clientX; lastY = e.clientY;
|
|
try { d.setPointerCapture(e.pointerId); } catch (x) {}
|
|
if (b.toggle) { on = !on; d.classList.toggle("on", on); press(on); return; }
|
|
d.classList.add("on"); press(true);
|
|
});
|
|
d.addEventListener("pointermove", (e) => {
|
|
if (b.bar || b.wheel || lastX === null) return;
|
|
Module.vcLookX = (Module.vcLookX || 0) + (e.clientX - lastX) * t.lookSpeed;
|
|
Module.vcLookY = (Module.vcLookY || 0) + (e.clientY - lastY) * t.lookSpeed;
|
|
lastX = e.clientX; lastY = e.clientY;
|
|
});
|
|
const up = (e) => { e.stopPropagation(); lastX = null; if (!b.toggle) { d.classList.remove("on"); press(false); } };
|
|
d.addEventListener("pointerup", up);
|
|
d.addEventListener("pointercancel", up);
|
|
(b.always ? bar : box).appendChild(d);
|
|
if (b.always) d.style.position = "fixed";
|
|
}
|
|
// The game's files are mounted only once it runs: the mobile game's button pictures go on then.
|
|
const iconTimer = setInterval(() => {
|
|
if (!window.vcPlaying) return;
|
|
clearInterval(iconTimer);
|
|
const picture = (name) => { try { return URL.createObjectURL(new Blob([Module.FS.readFile(`/vc/online/icons/${name}.png`)], { type: "image/png" })); } catch (e) { return null; } };
|
|
for (const d of document.querySelectorAll("[data-icon]")) {
|
|
const url = picture(d.dataset.icon);
|
|
if (!url) { d.classList.remove("ic"); continue; }
|
|
d.textContent = "";
|
|
d.style.backgroundImage = `url(${url})`;
|
|
}
|
|
const ring = picture("circle"), nub = picture("analognub");
|
|
if (ring && nub) { stick.classList.add("ic"); stick.style.backgroundImage = `url(${ring})`; knob.style.backgroundImage = `url(${nub})`; }
|
|
}, 300);
|
|
// The wheel by touch: a slot takes the first tap, another tap on it walks its weapons, the middle takes it.
|
|
el("wheel").addEventListener("pointerdown", (e) => {
|
|
if (!wheelOpen) return;
|
|
e.preventDefault();
|
|
const slot = e.target.closest(".slot");
|
|
if (e.target.closest(".mid")) { closeWheel(); return; }
|
|
if (!slot) return;
|
|
const i = [...el("wheel").querySelectorAll(".slot")].indexOf(slot);
|
|
if (i === wheelSel) wheelPick[i] = (wheelPick[i] || 0) + 1; else wheelSel = i;
|
|
renderWheel();
|
|
});
|
|
// The game reads the cursor only while it is inside the window.
|
|
canvasEl.dispatchEvent(new MouseEvent("mouseenter", { bubbles: false }));
|
|
canvasEl.dispatchEvent(new MouseEvent("mousemove", { clientX: 10, clientY: 10, bubbles: true }));
|
|
// First tap: full screen and sideways where the browser allows it.
|
|
window.addEventListener("pointerup", async () => {
|
|
try { await document.documentElement.requestFullscreen(); await screen.orientation.lock("landscape"); } catch (x) {}
|
|
}, { once: true });
|
|
}
|
|
function closeMenu() { if (!openMenu) return; el(openMenu).style.display = "none"; openMenu = null; captureMouse(); }
|
|
function outboxCmd(c) { (Module.vcCmds || (Module.vcCmds = [])).push(c); }
|
|
|
|
// Capture phase on the window, registered before the game's own handlers: the keys the UI uses never reach the game.
|
|
window.addEventListener("keydown", (e) => {
|
|
if (!window.vcPlaying || Module.vcMenuActive) return;
|
|
if (openMenu) {
|
|
const k = e.key.toLowerCase(), keys = loadMenuData().keys;
|
|
if (e.key === "Escape" || k === keys.weapons || k === keys.cars) { e.preventDefault(); closeMenu(); }
|
|
else if (e.key.startsWith("Arrow")) { e.preventDefault(); moveSelection(e.key); }
|
|
else if (e.key === "Enter") { e.preventDefault(); el(openMenu).querySelector("button.sel").click(); }
|
|
e.stopImmediatePropagation();
|
|
return;
|
|
}
|
|
// The pause menu counts as passive, so it stays shut right after a fight.
|
|
if (e.key === "Escape" && !typing && window.vcPlaying && !Module.vcMenuActive && fightLocked()) {
|
|
e.preventDefault(); e.stopImmediatePropagation(); chatLine([[menuData.name.locked, ""]], "sys"); return;
|
|
}
|
|
if (typing) {
|
|
if (e.key === "Enter") { e.preventDefault(); naming ? closeName(true) : closeChat(true); }
|
|
else if (e.key === "Escape") { e.preventDefault(); naming ? closeName(false) : closeChat(false); }
|
|
e.stopImmediatePropagation();
|
|
return;
|
|
}
|
|
if (e.key === "Tab") { e.preventDefault(); e.stopImmediatePropagation(); renderBoard(); el("board").style.display = "block"; }
|
|
else if (e.key.toLowerCase() === loadMenuData().keys.weapons) { e.preventDefault(); e.stopImmediatePropagation(); if (!e.repeat && !wheelOpen && !Module.vcInVehicle) openWheel(); }
|
|
else if (e.key.toLowerCase() === menuData.keys.name) { e.preventDefault(); e.stopImmediatePropagation(); if (!e.repeat) openName(); }
|
|
else if (e.key.toLowerCase() === menuData.keys.passive) { e.preventDefault(); e.stopImmediatePropagation(); if (!e.repeat) outbox.push(JSON.stringify({ t: "passive" })); }
|
|
else if (e.key.toLowerCase() === menuData.keys.cars) { e.preventDefault(); e.stopImmediatePropagation(); if (!Module.vcInVehicle) showMenu("cmenu", T("VEHICLES"), menuData.cars, (c) => { rememberVehicle(c.model); return "car " + c.model; }, vehicleShortlist()); }
|
|
else if (e.key === "t" || e.key === "T") { e.preventDefault(); e.stopImmediatePropagation(); openChat(); }
|
|
}, true);
|
|
window.addEventListener("keyup", (e) => {
|
|
if (typing) { e.stopImmediatePropagation(); return; }
|
|
if (wheelOpen && e.key.toLowerCase() === menuData.keys.weapons) { e.stopImmediatePropagation(); closeWheel(); return; }
|
|
if (e.key === "Tab") { e.stopImmediatePropagation(); el("board").style.display = "none"; }
|
|
}, true);
|
|
window.addEventListener("keypress", (e) => { if (typing) e.stopImmediatePropagation(); }, true);
|
|
setInterval(() => {
|
|
const on = !!window.vcPlaying && !Module.vcMenuActive;
|
|
el("net").style.display = on ? "block" : "none";
|
|
el("chat").style.display = on ? "block" : "none";
|
|
if (on) {
|
|
const m = loadMenuData();
|
|
if (!isTouch && m && m.desktopRenderWidth && window.vcRenderWidth !== m.desktopRenderWidth) { window.vcRenderWidth = m.desktopRenderWidth; fitCanvas(); }
|
|
if (!helpUntil && m) helpUntil = Date.now() + m.helpSeconds * 1000;
|
|
}
|
|
// The key list goes away once it has been read; it returns with Tab and when the mouse is released.
|
|
el("help").classList.toggle("show", on && (Date.now() < helpUntil || el("board").style.display === "block" || (!isTouch && !document.pointerLockElement)));
|
|
el("help").style.display = on ? "block" : "none";
|
|
if (isTouch && menuData && menuData.touch) {
|
|
el("touch").style.display = on && !openMenu && !typing && !wheelOpen ? "block" : "none";
|
|
el("tmenu").style.display = window.vcPlaying && !typing ? "block" : "none";
|
|
el("rotate").style.display = window.innerHeight > window.innerWidth ? "flex" : "none";
|
|
}
|
|
canvasEl.style.setProperty("cursor", on && !isTouch && !document.pointerLockElement ? "default" : "none", "important");
|
|
if (window.vcPlaying) {
|
|
const m = loadMenuData();
|
|
if (!window.vcPlayStart) window.vcPlayStart = Date.now();
|
|
let named = true; try { named = !!localStorage.getItem("vcNamed"); } catch (e) {}
|
|
if (on && !named && !naming && !typing && !openMenu && !fightLocked() && Date.now() - window.vcPlayStart > m.name.promptSeconds * 1000) openName();
|
|
const away = !!Module.vcMenuActive || naming;
|
|
if (away !== awaySent) { awaySent = away; outbox.push(JSON.stringify({ t: "away", on: away })); }
|
|
if (showPos && Module.vcPos) { const [x, y, z, h] = Module.vcPos; el("pos").textContent = `x ${x.toFixed(1)} y ${y.toFixed(1)} z ${z.toFixed(1)} heading ${Math.round(h * 180 / Math.PI)}`; }
|
|
}
|
|
el("hint").style.display = on && !isTouch && !openMenu && !typing && !document.pointerLockElement ? "block" : "none";
|
|
}, 300);
|
|
el("nameok").addEventListener("click", () => closeName(true));
|
|
canvasEl.addEventListener("click", () => { if (window.vcPlaying && !document.pointerLockElement && !typing && !openMenu) captureMouse(); });
|
|
|
|
var Module = {
|
|
canvas: document.getElementById("canvas"),
|
|
vcDataUrl: dataUrl,
|
|
vcBusy,
|
|
vcOutbox: outbox,
|
|
get vcPos() { return this.vcP0 === undefined ? null : [this.vcP0, this.vcP1, this.vcP2, this.vcP3]; },
|
|
vcOnNet: onNet,
|
|
vcMarker: (x, y) => {
|
|
x = Math.round(x); y = Math.round(y);
|
|
chatLine([[`map marker at x ${x}, y ${y}`, ""]], "sys");
|
|
outbox.push(JSON.stringify({ t: "marker", x, y }));
|
|
},
|
|
vcHello: () => {
|
|
// A private token kept in this browser: it says which parked cars are yours when you come back.
|
|
let owner = "";
|
|
try {
|
|
owner = localStorage.getItem("vcOwner") || "";
|
|
if (!owner) { owner = [...crypto.getRandomValues(new Uint8Array(16))].map((b) => b.toString(16).padStart(2, "0")).join(""); localStorage.setItem("vcOwner", owner); }
|
|
} catch (e) { owner = [...crypto.getRandomValues(new Uint8Array(16))].map((b) => b.toString(16).padStart(2, "0")).join(""); }
|
|
return JSON.stringify({ t: "hello", name: nick, owner });
|
|
},
|
|
// Game server: ?server=wss://host/ws?key=... for a local test; on the real host the page
|
|
// connects to /ws on its own address and the gate cookie does the authentication.
|
|
vcServer: params.get("server") || (["localhost", "127.0.0.1"].includes(location.hostname) ? "" : (location.protocol === "https:" ? "wss://" : "ws://") + location.host + "/ws"),
|
|
// The engine's two files must come from one build: a browser may keep the script for hours.
|
|
locateFile: (path) => path.endsWith(".wasm") ? path + "?v=__ENGINE_V__" : path,
|
|
print: (t) => keepLog(t, console.log),
|
|
printErr: (t) => keepLog(t, console.warn),
|
|
onRuntimeInitialized: async () => {
|
|
const files = await loadEagerFiles();
|
|
for (const [path, bytes] of files) {
|
|
const dir = "/vc/" + path.split("/").slice(0, -1).join("/");
|
|
Module.FS.mkdirTree(dir);
|
|
Module.FS.writeFile("/vc/" + path, bytes);
|
|
}
|
|
Module.FS.chdir("/vc");
|
|
restoreSettings();
|
|
setProgress(0.9);
|
|
creeping = true;
|
|
setStatus(T("Loading {0}", loadArea()));
|
|
const up = setInterval(() => {
|
|
setStatus(T("Loading {0}", loadArea()));
|
|
if (window.vcPlaying) { clearInterval(up); creeping = false; gameIsUp(); }
|
|
}, 300);
|
|
Module.callMain([]);
|
|
},
|
|
};
|
|
</script>
|
|
<script>
|
|
// Browsers that switch stacks themselves get the lighter engine; the others the instrumented one.
|
|
(function () {
|
|
let saved = null;
|
|
try { saved = localStorage.getItem("vcEngine"); } catch (e) {}
|
|
const force = new URLSearchParams(location.search).get("engine") || saved;
|
|
// The stack switching failed in this browser: from now on it gets the instrumented engine.
|
|
window.addEventListener("error", (e) => {
|
|
if (s.src.includes("jspi") && /SuspendError|suspend JS frames/i.test(String(e.message))) { try { localStorage.setItem("vcEngine", "revc"); location.reload(); } catch (x) {} }
|
|
});
|
|
const jspi = typeof WebAssembly.Suspending === "function" && typeof WebAssembly.promising === "function";
|
|
const s = document.createElement("script");
|
|
s.src = (force || (jspi ? "revc-jspi" : "revc")) + ".js?v=__ENGINE_V__";
|
|
document.body.appendChild(s);
|
|
})();
|
|
</script>
|
|
</body>
|
|
</html>
|