All files / src/workers path-finding-worker.js

0% Statements 0/53
0% Branches 0/1
0% Functions 0/1
0% Lines 0/53

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54                                                                                                           
import { PathFinding } from '../path-finding.js';

let graph;

function routeCharacters(requestQueue) {
  if (!graph) { return; }
  for (let i = 0; i < requestQueue.length; i++) {
    const { actor, destination, exclude, mustHaveCollision } = requestQueue[i];
    const finish = destination;
    const start = {
      x: Math.round(actor.x + actor.width / 2),
      y: Math.round(actor.y + actor.height / 2),
    };
    // const startTime = new Date();
    const waypoints = PathFinding.dijikstras({ graph, start, finish, exclude });
    // const endTime = new Date();
    const newWaypoints = waypoints.slice(1);
    // No way found
    if (waypoints[0] == null) {
      postMessage({
        type: 'remove-character-path-finding-request',
        id: actor.id,
      });
      continue;
    }
    postMessage({
      type: 'set-character-waypoints',
      id: actor.id,
      destination: waypoints[0],
      waypoints: newWaypoints,
      mustHaveCollision,
      exclude,
    });
  }
}

onmessage = (e) => {
  switch (e.data.type) {
    case 'update-grid':
      graph = PathFinding.gridToGraph({
        grid: e.data.grid,
        width: e.data.mapDim.width,
        height: e.data.mapDim.height,
        actorSize: e.data.actorSize,
      });
      break;
    case 'add-requests':
      routeCharacters(e.data.requests);
      break;
    default:
      console.warn(`Unknown event passed to path worker: ${e.data.type}`); // eslint-disable-line no-console
  }
};