game runs in seperate thread

This commit is contained in:
Evan
2025-02-01 12:05:11 -08:00
parent f988d555bb
commit 8616e9bfcb
17 changed files with 135 additions and 263 deletions
+17 -96
View File
@@ -1,106 +1,27 @@
// pathfinding.ts
import { Cell, GameMap, TerrainMap, TerrainTile, TerrainType } from "../game/Game";
import { loadTerrainMap } from "../game/TerrainMapLoader";
import { PriorityQueue } from "@datastructures-js/priority-queue";
import { AStar, PathFindResultType, SearchNode } from "../pathfinding/AStar";
import { MiniAStar } from "../pathfinding/MiniAStar";
import { consolex } from "../Consolex";
import { createGameRunner, GameRunner } from "../GameRunner";
import { GameUpdateViewData } from "../GameView";
let terrainMapPromise: Promise<{
map: TerrainMap,
miniMap: TerrainMap
}> | null = null;
let searches = new PriorityQueue<Search>((a: Search, b: Search) => (a.deadline - b.deadline))
let processingInterval: number | null = null;
let isProcessingSearch = false
let gameRunner: Promise<GameRunner> = null
interface Search {
aStar: AStar,
deadline: number
requestId: string,
end: Cell
}
interface SearchRequest {
requestId: string
currentTick: number
// duration in ticks
duration: number
start: Cell
end: Cell
function gameUpdate(gu: GameUpdateViewData) {
self.postMessage({
type: "game_update",
gameUpdate: gu
})
}
self.onmessage = (e) => {
switch (e.data.type) {
case 'init':
initializeMap(e.data);
break;
case 'findPath':
terrainMapPromise.then(tm => findPath(tm.map, tm.miniMap, e.data))
gameRunner = createGameRunner(e.data.gameID, e.data.gameConfig, gameUpdate).then(gr => {
self.postMessage({
type: 'initialized'
});
return gr;
});
break;
case 'turn':
gameRunner.then(gr => gr.addTurn(e.data.turn))
}
};
function initializeMap(data: { gameMap: GameMap }) {
terrainMapPromise = loadTerrainMap(data.gameMap)
self.postMessage({ type: 'initialized' });
processingInterval = setInterval(computeSearches, .1) as unknown as number;
}
function findPath(terrainMap: TerrainMap, miniTerrainMap: TerrainMap, req: SearchRequest) {
const aStar = new MiniAStar(
terrainMap,
miniTerrainMap,
terrainMap.terrain(req.start),
terrainMap.terrain(req.end),
(sn: SearchNode) => (sn as TerrainTile).type() == TerrainType.Ocean,
10_000,
req.duration,
);
searches.enqueue({
aStar: aStar,
deadline: req.currentTick + req.duration,
requestId: req.requestId,
end: req.end
})
}
function computeSearches() {
if (isProcessingSearch || searches.isEmpty()) {
return
}
isProcessingSearch = true
try {
for (let i = 0; i < 10; i++) {
if (searches.isEmpty()) {
return
}
const search = searches.dequeue()
switch (search.aStar.compute()) {
case PathFindResultType.Completed:
self.postMessage({
type: 'pathFound',
requestId: search.requestId,
path: search.aStar.reconstructPath()
});
break;
case PathFindResultType.Pending:
searches.push(search)
break
case PathFindResultType.PathNotFound:
consolex.warn(`worker: path not found to port`);
self.postMessage({
type: 'pathNotFound',
requestId: search.requestId,
});
break
}
}
} finally {
isProcessingSearch = false
}
}
};
+17 -114
View File
@@ -1,7 +1,9 @@
import { consolex } from "../Consolex";
import { Cell, Game, GameMap, TerrainTile, TerrainType, Tile } from "../game/Game";
import { GameUpdateViewData } from "../GameView";
import { AStar, PathFindResultType } from "../pathfinding/AStar";
import { MiniAStar } from "../pathfinding/MiniAStar";
import { GameConfig, GameID, Turn } from "../Schemas";
import { generateID } from "../Util";
@@ -9,39 +11,43 @@ export class WorkerClient {
private worker: Worker;
private isInitialized = false;
constructor(private game: Game, private gameMap: GameMap) {
constructor(private gameID: GameID, private gameConfig: GameConfig) {
// Create a new worker using webpack worker-loader
// The import.meta.url ensures webpack can properly bundle the worker
this.worker = new Worker(new URL('./Worker.worker.ts', import.meta.url));
}
initialize(): Promise<void> {
initialize(gameUpdate: (gu: GameUpdateViewData) => void): Promise<void> {
return new Promise((resolve, reject) => {
this.worker.postMessage({
type: 'init',
gameMap: this.gameMap
gameID: this.gameID,
gameConfig: this.gameConfig
});
const handler = (e: MessageEvent) => {
if (e.data.type === 'initialized') {
this.worker.removeEventListener('message', handler);
this.isInitialized = true;
resolve();
} else {
this.worker.removeEventListener('message', handler);
return
}
if (!this.isInitialized) {
reject('Failed to initialize pathfinder');
}
if (e.data.type == "game_update") {
gameUpdate(e.data.gameUpdate)
}
};
this.worker.addEventListener('message', handler);
});
}
createParallelAStar(src: Tile, dst: Tile, numTicks: number, types: TerrainType[]): ParallelAStar {
if (!this.isInitialized) {
throw new Error('PathFinder not initialized');
}
return new ParallelAStar(this.game, this.worker, src, dst, numTicks, types);
sendTurn(turn: Turn) {
this.worker.postMessage({
type: "turn",
turn: turn
})
}
cleanup() {
@@ -49,106 +55,3 @@ export class WorkerClient {
}
}
export class ParallelAStar implements AStar {
private path: Cell[] | 'NOT_FOUND' | null = null;
private promise: Promise<void>;
constructor(
private game: Game,
private worker: Worker,
private src: Tile,
private dst: Tile,
private numTicks: number,
private terrainTypes: TerrainType[]
) { }
findPath(): Promise<void> {
const requestId = generateID()
this.promise = new Promise((resolve, reject) => {
const handler = (e: MessageEvent) => {
if (e.data.requestId != requestId) {
return;
}
this.worker.removeEventListener('message', handler);
if (e.data.type === 'pathFound') {
this.path = e.data.path
resolve();
} else if (e.data.type === 'pathNotFound') {
this.path = 'NOT_FOUND';
} else {
reject(e.data.reason || "Path not found");
}
};
this.worker.addEventListener('message', handler);
this.worker.postMessage({
type: 'findPath',
requestId: requestId,
terrainTypes: this.terrainTypes,
currentTick: this.game.ticks(),
duration: this.numTicks,
start: { x: this.src.cell().x, y: this.src.cell().y },
end: { x: this.dst.cell().x, y: this.dst.cell().y }
});
});
return this.promise;
}
// TODO: rename to poll?
compute(): PathFindResultType {
if (this.promise == null) {
this.findPath();
}
this.numTicks--;
if (this.numTicks <= 0) {
if (this.path == 'NOT_FOUND') {
return PathFindResultType.PathNotFound;
}
if (this.path != null) {
return PathFindResultType.Completed;
}
// Path was not found in worker thread in time, so now we need
// to recompute it in main thread. This will lock up game.
consolex.warn(`path not completed in worker thread, recomputing`)
const local = new MiniAStar(
this.game.terrainMap(),
this.game.terrainMiniMap(),
this.src, this.dst,
(t: TerrainTile) => t.type() == TerrainType.Ocean,
100_000_000,
20
)
const result = local.compute()
switch (result) {
case PathFindResultType.Completed:
consolex.log('recomputed path in worker client')
this.path = local.reconstructPath()
break
case PathFindResultType.PathNotFound:
this.path = "NOT_FOUND"
break
case PathFindResultType.Pending:
// TODO: make sure same number of tries as worker thread.
consolex.warn("path not found after many tries")
this.path = "NOT_FOUND"
break
}
if (result == PathFindResultType.Completed) {
this.path = local.reconstructPath()
}
return result
}
return PathFindResultType.Pending;
}
reconstructPath(): Cell[] {
if (this.path == "NOT_FOUND" || this.path == null) {
throw Error(`cannot reconstruct path: ${this.path}`);
}
return this.path
}
}