added support for usernames through ip or fingerprint, and also control based on it and restarting sessions

This commit is contained in:
2026-06-06 00:37:03 +01:00
parent 0f98ae862f
commit 4e4bd6a145
3 changed files with 450 additions and 132 deletions
+254 -72
View File
@@ -44,9 +44,49 @@
max-width: 100vw;
max-height: 100vh;
object-fit: contain;
cursor: none;
display: block;
}
#gameCanvas.watching { cursor: default; }
#gameCanvas.controlling { cursor: none; }
#queue-panel {
position: fixed;
top: 10px;
right: 10px;
background: rgba(0,0,0,0.75);
padding: 10px 14px;
border-radius: 4px;
font-size: 12px;
z-index: 10;
min-width: 180px;
}
#queue-panel h3 { font-size: 12px; color: #ffcc00; margin-bottom: 6px; }
#queue-panel .controller-row { color: #4fc; margin-bottom: 4px; }
#queue-panel .queue-row { color: #aaa; margin-bottom: 2px; }
#queue-panel .you { color: #fff; font-weight: bold; }
#loading-overlay {
display: none;
position: fixed;
inset: 0;
background: rgba(0,0,0,0.85);
flex-direction: column;
align-items: center;
justify-content: center;
z-index: 100;
}
#loading-overlay.visible { display: flex; }
#loading-overlay p { color: #fff; font-size: 14px; margin-bottom: 16px; }
.spinner {
width: 48px;
height: 48px;
border: 4px solid #333;
border-top-color: #4fc;
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
@keyframes spin { to { transform: rotate(360deg); } }
#faq {
position: fixed;
bottom: 40px;
@@ -65,11 +105,24 @@
</head>
<body>
<div id="status">Connecting...</div>
<video id="gameCanvas" autoplay muted playsinline></video>
<div id="hint">Click to capture mouse | ESC to release</div>
<div id="queue-panel">
<h3>Controller</h3>
<div id="queue-list"></div>
</div>
<div id="loading-overlay">
<p>Switching player — please wait...</p>
<div class="spinner"></div>
</div>
<video id="gameCanvas" class="watching" autoplay muted playsinline></video>
<div id="hint">Click to take control</div>
<div id="faq">
<h2>FAQ</h2>
<div class="faq-item">
<div class="faq-item">
<h3>What is this?</h3>
<p>This is the unloze webclient. You can play Zombie escape, Minigame and Zombie Riot with it. Visit our website at: https://unloze.com</p>
</div>
@@ -80,11 +133,11 @@
</div>
<div class="faq-item">
<h3>How can i join the server?</h3>
<p>The IP is 51.195.188.106:27015. </p>
<p>The IP is 51.195.188.106:27015.</p>
</div>
<div class="faq-item">
<h3>Want to chat with us?</h3>
<p>We have our own self hosted stoat instance: https://unloze.com/stoat/ </p>
<p>We have our own self hosted stoat instance: https://unloze.com/stoat/</p>
</div>
<div class="faq-item">
<h3>⚠️ Opening the in-game menu</h3>
@@ -98,15 +151,110 @@
</div>
<script type="module">
const fpPromise = import('https://openfpcdn.io/fingerprintjs/v5')
.then(FingerprintJS => FingerprintJS.load());
function hashString(str) {
let hash = 5381;
for (let i = 0; i < str.length; i++) {
hash = ((hash << 5) + hash) + str.charCodeAt(i);
hash = hash & 0x7fffffff; // keep positive 31-bit
}
return hash;
}
function visitorIdToName(input) {
const adjectives = [
'Fast', 'Slow', 'Red', 'Blue', 'Green', 'Dark', 'Bright', 'Wild',
'Cool', 'Hot', 'Big', 'Small', 'Sharp', 'Brave', 'Swift', 'Bold'
];
const nouns = [
'Wolf', 'Eagle', 'Tiger', 'Bear', 'Fox', 'Lion', 'Hawk', 'Shark',
'Snake', 'Raven', 'Storm', 'Rock', 'Fire', 'Ice', 'Wind', 'Steel'
];
const h1 = hashString(input);
const h2 = hashString(input + '1');
const h3 = hashString(input + '2');
const adjIndex = h1 % adjectives.length;
const nounIndex = h2 % nouns.length;
const number = h3 % 9999;
return `${adjectives[adjIndex]} ${nouns[nounIndex]} ${number}`;
}
let visitorName = null;
async function initVisitorName() {
try {
const fp = await fpPromise;
const result = await fp.get();
if (result.visitorId) {
visitorName = visitorIdToName(result.visitorId);
return;
}
} catch (e) {
}
// Fallback: request IP from server
// Wait until WebSocket is open
const waitForIp = new Promise(resolve => {
const handler = e => {
if (e.data instanceof Blob) return;
const msg = JSON.parse(e.data);
if (msg.type === 'your_ip') {
visitorName = visitorIdToName(msg.ip);
sigWs.removeEventListener('message', handler);
resolve();
}
};
sigWs.addEventListener('message', handler);
sigWs.send(JSON.stringify({ type: 'get_ip' }));
});
await waitForIp;
}
const SIG_URL = `${location.protocol === 'https:' ? 'wss' : 'ws'}://${location.host}`;
const statusEl = document.getElementById('status');
const canvas = document.getElementById('gameCanvas');
const statusEl = document.getElementById('status');
const canvas = document.getElementById('gameCanvas');
const hintEl = document.getElementById('hint');
const queueList = document.getElementById('queue-list');
const loadingEl = document.getElementById('loading-overlay');
let sigWs = null;
let pc = null;
let sessionId = null;
let pointerLocked = false;
let sigWs = null;
let pc = null;
let sessionId = null;
let pointerLocked = false;
let isControlling = false;
let isInQueue = false;
let isWaitingForRestart = false;
function setStatus(msg) {
statusEl.textContent = msg;
}
function setLoading(visible) {
loadingEl.classList.toggle('visible', visible);
}
function updateQueuePanel(controller, queue, restarting) {
let html = '';
if (restarting) {
html = '<div class="controller-row">⟳ Restarting...</div>';
} else if (controller) {
const isMe = visitorName && controller === visitorName;
html += `<div class="controller-row${isMe ? ' you' : ''}">🎮 ${controller}${isMe ? ' (you)' : ''}</div>`;
} else {
html += '<div class="controller-row">— nobody —</div>';
}
if (queue.length > 0) {
html += '<div style="margin-top:6px;color:#ffcc00;font-size:11px">Queue:</div>';
queue.forEach((name, i) => {
const isMe = visitorName && name === visitorName;
html += `<div class="queue-row${isMe ? ' you' : ''}">${i + 1}. ${name}${isMe ? ' (you)' : ''}</div>`;
});
}
queueList.innerHTML = html;
}
// ── Microphone / PTT ──────────────────────────────────────────────────
let micStream = null;
@@ -118,17 +266,11 @@
if (micStream) return true;
try {
micStream = await navigator.mediaDevices.getUserMedia({
audio: {
sampleRate: 48000,
channelCount: 1,
echoCancellation: true,
noiseSuppression: true,
},
audio: { sampleRate: 48000, channelCount: 1, echoCancellation: true, noiseSuppression: true },
video: false,
});
return true;
} catch (e) {
console.error('[mic] getUserMedia failed:', e);
return false;
}
}
@@ -137,10 +279,8 @@
if (micActive) return;
const ok = await initMic();
if (!ok) return;
audioContext = new AudioContext({ sampleRate: 48000 });
const source = audioContext.createMediaStreamSource(micStream);
micProcessor = audioContext.createScriptProcessor(4096, 1, 1);
micProcessor.onaudioprocess = e => {
if (!micActive) return;
@@ -149,11 +289,8 @@
for (let i = 0; i < float32.length; i++) {
int16[i] = Math.max(-32768, Math.min(32767, float32[i] * 32768));
}
if (sigWs && sigWs.readyState === WebSocket.OPEN) {
sigWs.send(int16.buffer);
}
if (sigWs && sigWs.readyState === WebSocket.OPEN) sigWs.send(int16.buffer);
};
source.connect(micProcessor);
micProcessor.connect(audioContext.destination);
micActive = true;
@@ -169,12 +306,38 @@
}
}
// ── WebRTC ────────────────────────────────────────────────────────────
function setStatus(msg) {
statusEl.textContent = msg;
console.log('[client]', msg);
// ── Control ───────────────────────────────────────────────────────────
function requestControl() {
if (!visitorName || !sigWs || sigWs.readyState !== WebSocket.OPEN) return;
if (isControlling || isInQueue || isWaitingForRestart) return;
sigWs.send(JSON.stringify({ type: 'request_control', visitorName }));
isInQueue = true;
hintEl.textContent = 'Waiting in queue...';
}
function enterControl() {
isControlling = true;
isInQueue = false;
isWaitingForRestart = false;
canvas.classList.replace('watching', 'controlling');
canvas.muted = false;
canvas.requestPointerLock();
hintEl.textContent = 'Mouse captured — ESC to release';
}
function exitControl() {
isControlling = false;
isInQueue = false;
isWaitingForRestart = false;
canvas.classList.replace('controlling', 'watching');
hintEl.textContent = 'Click to take control';
stopMic();
if (document.pointerLockElement === canvas) {
document.exitPointerLock();
}
}
// ── WebRTC ────────────────────────────────────────────────────────────
async function setupPeerConnection() {
pc = new RTCPeerConnection({
iceServers: [{ urls: 'stun:stun.cloudflare.com:3478' }],
@@ -186,10 +349,7 @@
pc.ontrack = event => {
remoteStream.addTrack(event.track);
if (event.track.kind === 'video') {
setStatus('Streaming — click to play');
}
console.log(`[client] got ${event.track.kind} track`);
if (event.track.kind === 'video') setStatus('Streaming');
};
await pc.setLocalDescription(await pc.createOffer({
@@ -197,11 +357,7 @@
offerToReceiveAudio: true,
}));
sigWs.send(JSON.stringify({
type: 'browser_connect',
sdp: pc.localDescription.sdp,
}));
sigWs.send(JSON.stringify({ type: 'browser_connect', sdp: pc.localDescription.sdp }));
setStatus('Waiting for session...');
}
@@ -210,10 +366,12 @@
setStatus('Connecting...');
sigWs = new WebSocket(SIG_URL);
sigWs.onopen = () => {
setStatus('Connected — setting up stream...');
setupPeerConnection();
};
sigWs.onopen = () => {
setStatus('Connected — setting up stream...');
initVisitorName().then(() => {
});
setupPeerConnection();
};
sigWs.onmessage = async e => {
if (e.data instanceof Blob) return;
@@ -231,27 +389,34 @@
if (result.requiresImmediateRenegotiation) {
await pc.setRemoteDescription(new RTCSessionDescription(result.sessionDescription));
await pc.setLocalDescription(await pc.createAnswer());
sigWs.send(JSON.stringify({
type: 'renegotiate',
sessionId: sessionId,
sdp: pc.localDescription.sdp,
}));
sigWs.send(JSON.stringify({ type: 'renegotiate', sessionId, sdp: pc.localDescription.sdp }));
}
}
else if (msg.type === 'queue_state') {
updateQueuePanel(msg.controller, msg.queue, msg.restarting);
isWaitingForRestart = msg.restarting;
setLoading(msg.restarting && (isControlling || isInQueue));
}
else if (msg.type === 'control_granted') {
setLoading(false);
enterControl();
}
else if (msg.type === 'control_released') {
exitControl();
hintEl.textContent = msg.reason === 'idle'
? 'Control released (idle) — click to take control'
: 'Click to take control';
}
else if (msg.type === 'waiting') {
setStatus('Waiting for game instance...');
}
else if (msg.type === 'error') {
setStatus('Error: ' + msg.message);
console.error('[client] server error:', msg.message);
}
};
sigWs.onerror = () => setStatus('Connection error');
sigWs.onclose = () => {
stopMic();
setStatus('Disconnected');
};
sigWs.onclose = () => { stopMic(); exitControl(); setStatus('Disconnected'); };
}
function waitForIce() {
@@ -278,15 +443,25 @@
}
canvas.addEventListener('click', () => {
canvas.muted = false;
canvas.requestPointerLock();
if (isControlling) {
// Already controller, just recapture pointer lock
canvas.muted = false;
canvas.requestPointerLock();
} else {
requestControl();
}
});
document.addEventListener('pointerlockchange', () => {
pointerLocked = document.pointerLockElement === canvas;
document.getElementById('hint').textContent = pointerLocked
? 'Mouse captured — ESC to release'
: 'Click to capture mouse | ESC to release';
if (!pointerLocked && isControlling) {
hintEl.textContent = 'Mouse released — click to recapture or wait to release control';
} else if (pointerLocked) {
hintEl.textContent = 'Mouse captured — ESC to release';
if (sigWs && sigWs.readyState === WebSocket.OPEN) {
sigWs.send(JSON.stringify({ type: 'controller_active' }));
}
}
});
const heldKeys = new Set();
@@ -297,28 +472,37 @@
stopMic();
});
setInterval(() => {
if (pointerLocked && isControlling && sigWs && sigWs.readyState === WebSocket.OPEN) {
sigWs.send(JSON.stringify({ type: 'controller_active' }));
}
}, 3000);
let lastMouseMove = 0;
document.addEventListener('mousemove', e => {
if (!pointerLocked) return;
if (!pointerLocked || !isControlling) return;
const now = performance.now();
if (now - lastMouseMove < 16) return;
lastMouseMove = now;
sendInput({ type: 'mouse_move', dx: e.movementX, dy: e.movementY });
if (sigWs && sigWs.readyState === WebSocket.OPEN) {
sigWs.send(JSON.stringify({ type: 'controller_active' }));
}
});
canvas.addEventListener('mousedown', e => {
if (!pointerLocked) return;
if (!pointerLocked || !isControlling) return;
sendInput({ type: 'mouse_down', button: e.button + 1 });
});
canvas.addEventListener('mouseup', e => {
if (!pointerLocked) return;
if (!pointerLocked || !isControlling) return;
sendInput({ type: 'mouse_up', button: e.button + 1 });
});
let lastMouseWheel = 0;
canvas.addEventListener('wheel', e => {
if (!pointerLocked) return;
if (!pointerLocked || !isControlling) return;
e.preventDefault();
const now = performance.now();
if (now - lastMouseWheel < 16) return;
@@ -356,31 +540,29 @@
if (e.key === 'q' && e.ctrlKey) { e.preventDefault(); return; }
if (e.key === 'F11') { e.preventDefault(); return; }
if (e.key === 'Escape') {
sendInput({ type: 'key_down', key: 'Escape' });
sendInput({ type: 'key_up', key: 'Escape' });
if (isControlling) {
sendInput({ type: 'key_down', key: 'Escape' });
sendInput({ type: 'key_up', key: 'Escape' });
}
return;
}
if (!pointerLocked) return;
if (!pointerLocked || !isControlling) return;
e.preventDefault();
const key = KEY_MAP[e.code] || e.code.toLowerCase();
if (e.code === 'KeyK' && !e.repeat) {
startMic();
}
if (e.code === 'KeyK' && !e.repeat) startMic();
heldKeys.add(key);
sendInput({ type: 'key_down', key });
});
document.addEventListener('keyup', e => {
if (e.key === 'Escape') {
sendInput({ type: 'key_up', key: 'Escape' });
if (isControlling) sendInput({ type: 'key_up', key: 'Escape' });
return;
}
if (!pointerLocked) return;
if (!pointerLocked || !isControlling) return;
e.preventDefault();
const key = KEY_MAP[e.code] || e.code.toLowerCase();
if (e.code === 'KeyK') {
stopMic();
}
if (e.code === 'KeyK') stopMic();
heldKeys.delete(key);
sendInput({ type: 'key_up', key });
});