mirror of
https://github.com/isledecomp/isle-portable.git
synced 2026-05-01 18:13:57 +00:00
* Add multiplayer extension * Fix animation system to work when host is outside ISLE world - Move TickHostSessions outside m_inIsleWorld gate so the host can coordinate animations from any world - Load animation catalog early in HandleCreate so the host can coordinate before entering the ISLE world - Use network-reported positions for remote player location detection instead of requiring spawned ROIs - Always erase sessions at launch — the host's job ends when the animation starts; clients play and complete independently - Replace BroadcastAnimComplete with locally-driven completion callbacks: host generates eventId at launch, clients cache completion JSON at start time, fire it when ScenePlayer finishes - Make StopAnimation only do local cleanup (stop playback, cancel own interest, reset coordinator) without destroying the session host, so other players' sessions survive world transitions - Broadcast state=0 in ResetAnimationState for full teardown paths (shutdown, reconnect, host migration) so clients aren't left with stale session state * Fix use-after-free crash in ScenePlayer when remote player disconnects mid-animation When a remote player's ROI is destroyed (disconnect, timeout, or respawn), notify all active ScenePlayer instances to null out dangling references before the ROI is freed. The animation engine already handles null ROI map entries gracefully, so playback continues for remaining participants. * Fix crash when performer's child ROIs are left dangling in ScenePlayer NotifyROIDestroyed now walks the parent chain to also invalidate child ROIs of the destroyed performer (head, limbs, etc.) that were placed into the roiMap by BuildROIMap. The ancestor walk happens once; all other fields are cleaned with simple pointer equality. * Allow spectator to play click animation during scene playback * Make PTATCAM track spectator ROI instead of camera in ScenePlayer * Only regenerate emscripten version files when git state changes Replace add_custom_target(ALL) with add_custom_command(OUTPUT) so the version script only runs when .git/HEAD or the current branch ref file changes, instead of on every build. * Fix ROI name collision causing dangling pointers in NPC locomotion roiMaps When ScenePlayer created cloned NPC ROIs for cooperative animations, it renamed them to match the original character name and added them to the ViewManager. This created a name collision: two ROIs with the same name. The original game's AppendROIToScene searches by name and stops at the first match, so if a locomotion BuildROIMap ran while the clone existed, it could capture pointers to the clone's child ROIs. When the clone was later destroyed (CleanupProps), those roiMap entries became dangling pointers, crashing in AnimateWithTransform at roi.h:151 (SetVisibility). Fix: use the alias mechanism (already supported by AnimUtils::BuildROIMap) instead of renaming clones. Also unify all ROI name generation behind a shared counter to prevent character manager key collisions.
265 lines
6.3 KiB
TypeScript
265 lines
6.3 KiB
TypeScript
import {
|
|
HEADER_SIZE,
|
|
TARGET_BROADCAST,
|
|
TARGET_HOST,
|
|
TARGET_BROADCAST_ALL,
|
|
createAssignIdMsg,
|
|
createHostAssignMsg,
|
|
createLeaveMsg,
|
|
readTarget,
|
|
stampSender,
|
|
} from "./protocol";
|
|
import type { Env } from "./relay";
|
|
import { CORS_HEADERS } from "./cors";
|
|
|
|
export class GameRoom implements DurableObject {
|
|
private connections = new Map<number, WebSocket>();
|
|
private nextPeerId = 1;
|
|
private hostPeerId = 0;
|
|
private maxPlayers = 5;
|
|
private isPublic = true;
|
|
private roomId: string | null = null;
|
|
|
|
constructor(
|
|
private state: DurableObjectState,
|
|
private env: Env
|
|
) {
|
|
state.blockConcurrencyWhile(async () => {
|
|
this.isPublic =
|
|
(await state.storage.get<boolean>("isPublic")) ?? true;
|
|
this.roomId =
|
|
(await state.storage.get<string>("roomId")) ?? null;
|
|
this.maxPlayers =
|
|
(await state.storage.get<number>("maxPlayers")) ?? 5;
|
|
});
|
|
}
|
|
|
|
async fetch(request: Request): Promise<Response> {
|
|
// Extract roomId from URL path if not yet known
|
|
if (!this.roomId) {
|
|
const url = new URL(request.url);
|
|
const parts = url.pathname.split("/").filter(Boolean);
|
|
if (parts.length === 2 && parts[0] === "room") {
|
|
this.roomId = parts[1];
|
|
await this.state.storage.put("roomId", this.roomId);
|
|
}
|
|
}
|
|
|
|
// Handle non-WebSocket requests (HTTP API)
|
|
if (request.headers.get("Upgrade") !== "websocket") {
|
|
return this.handleHttpRequest(request);
|
|
}
|
|
|
|
// Capacity check
|
|
if (this.connections.size >= this.maxPlayers) {
|
|
return new Response("Room is full", {
|
|
status: 503,
|
|
headers: CORS_HEADERS,
|
|
});
|
|
}
|
|
|
|
const pair = new WebSocketPair();
|
|
const [client, server] = [pair[0], pair[1]];
|
|
|
|
const peerId = this.nextPeerId++;
|
|
|
|
server.accept();
|
|
this.connections.set(peerId, server);
|
|
this.notifyRegistry().catch(() => {});
|
|
|
|
server.send(createAssignIdMsg(peerId));
|
|
this.assignHostIfNeeded(peerId, server);
|
|
|
|
server.addEventListener("message", (event) =>
|
|
this.handleMessage(event, peerId)
|
|
);
|
|
|
|
const handleDisconnect = () => this.handleDisconnect(peerId);
|
|
server.addEventListener("close", handleDisconnect);
|
|
server.addEventListener("error", handleDisconnect);
|
|
|
|
return new Response(null, { status: 101, webSocket: client });
|
|
}
|
|
|
|
private async handleHttpRequest(request: Request): Promise<Response> {
|
|
const method = request.method.toUpperCase();
|
|
|
|
if (method === "POST") {
|
|
try {
|
|
const body = (await request.json()) as {
|
|
maxPlayers?: number;
|
|
isPublic?: boolean;
|
|
};
|
|
const ceiling = this.env.MAX_PLAYERS_CEILING
|
|
? Number(this.env.MAX_PLAYERS_CEILING)
|
|
: 64;
|
|
if (body.maxPlayers !== undefined) {
|
|
this.maxPlayers = Math.max(
|
|
2,
|
|
Math.min(body.maxPlayers, ceiling)
|
|
);
|
|
await this.state.storage.put(
|
|
"maxPlayers",
|
|
this.maxPlayers
|
|
);
|
|
}
|
|
if (body.isPublic !== undefined) {
|
|
this.isPublic = body.isPublic;
|
|
await this.state.storage.put(
|
|
"isPublic",
|
|
this.isPublic
|
|
);
|
|
}
|
|
} catch {
|
|
// Ignore parse errors, keep defaults
|
|
}
|
|
this.notifyRegistry().catch(() => {});
|
|
return new Response(
|
|
JSON.stringify({ maxPlayers: this.maxPlayers }),
|
|
{
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
...CORS_HEADERS,
|
|
},
|
|
}
|
|
);
|
|
}
|
|
|
|
if (method === "GET") {
|
|
return new Response(
|
|
JSON.stringify({
|
|
players: this.connections.size,
|
|
maxPlayers: this.maxPlayers,
|
|
isPublic: this.isPublic,
|
|
}),
|
|
{
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
...CORS_HEADERS,
|
|
},
|
|
}
|
|
);
|
|
}
|
|
|
|
return new Response("Method Not Allowed", {
|
|
status: 405,
|
|
headers: CORS_HEADERS,
|
|
});
|
|
}
|
|
|
|
private assignHostIfNeeded(peerId: number, ws: WebSocket): void {
|
|
if (this.hostPeerId === 0 || !this.connections.has(this.hostPeerId)) {
|
|
this.hostPeerId = peerId;
|
|
this.broadcast(createHostAssignMsg(this.hostPeerId));
|
|
} else {
|
|
this.trySend(ws, createHostAssignMsg(this.hostPeerId));
|
|
}
|
|
}
|
|
|
|
private handleDisconnect(peerId: number): void {
|
|
this.connections.delete(peerId);
|
|
this.broadcast(createLeaveMsg(peerId));
|
|
this.notifyRegistry().catch(() => {});
|
|
|
|
if (peerId === this.hostPeerId) {
|
|
this.electNewHost();
|
|
}
|
|
}
|
|
|
|
private handleMessage(event: MessageEvent, peerId: number): void {
|
|
if (!(event.data instanceof ArrayBuffer)) {
|
|
return;
|
|
}
|
|
|
|
const data = new Uint8Array(event.data);
|
|
if (data.length < HEADER_SIZE) {
|
|
return;
|
|
}
|
|
|
|
const stamped = stampSender(data, peerId);
|
|
const target = readTarget(stamped);
|
|
|
|
if (target === TARGET_BROADCAST) {
|
|
this.broadcastExcept(stamped.buffer, peerId);
|
|
} else if (target === TARGET_HOST) {
|
|
this.sendToHost(stamped);
|
|
} else if (target === TARGET_BROADCAST_ALL) {
|
|
this.broadcast(stamped.buffer);
|
|
} else {
|
|
this.sendToTarget(stamped, target);
|
|
}
|
|
}
|
|
|
|
private sendToHost(data: Uint8Array): void {
|
|
const hostWs = this.connections.get(this.hostPeerId);
|
|
if (hostWs) {
|
|
this.trySend(hostWs, data.buffer);
|
|
}
|
|
}
|
|
|
|
private sendToTarget(data: Uint8Array, targetId: number): void {
|
|
const targetWs = this.connections.get(targetId);
|
|
if (targetWs) {
|
|
if (!this.trySend(targetWs, data.buffer)) {
|
|
this.connections.delete(targetId);
|
|
}
|
|
}
|
|
}
|
|
|
|
private broadcast(msg: ArrayBuffer): void {
|
|
for (const ws of this.connections.values()) {
|
|
this.trySend(ws, msg);
|
|
}
|
|
}
|
|
|
|
private broadcastExcept(msg: ArrayBuffer, excludePeerId: number): void {
|
|
for (const [id, ws] of this.connections) {
|
|
if (id !== excludePeerId) {
|
|
if (!this.trySend(ws, msg)) {
|
|
this.connections.delete(id);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
private trySend(ws: WebSocket, data: ArrayBuffer): boolean {
|
|
try {
|
|
ws.send(data);
|
|
return true;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
private electNewHost(): void {
|
|
this.hostPeerId = 0;
|
|
|
|
for (const id of this.connections.keys()) {
|
|
if (this.hostPeerId === 0 || id < this.hostPeerId) {
|
|
this.hostPeerId = id;
|
|
}
|
|
}
|
|
|
|
if (this.hostPeerId > 0) {
|
|
this.broadcast(createHostAssignMsg(this.hostPeerId));
|
|
}
|
|
}
|
|
|
|
private async notifyRegistry(): Promise<void> {
|
|
if (!this.isPublic || !this.roomId) return;
|
|
const id = this.env.ROOM_REGISTRY.idFromName("global");
|
|
const registry = this.env.ROOM_REGISTRY.get(id);
|
|
await registry.fetch(
|
|
new Request("https://registry/", {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({
|
|
roomId: this.roomId,
|
|
players: this.connections.size,
|
|
maxPlayers: this.maxPlayers,
|
|
}),
|
|
})
|
|
);
|
|
}
|
|
}
|