GameRenderer.js 2.35 KB
Newer Older
1
import GameConfig from "../config/GameConfiguration.js";
2
import Time from "../utils/Time.js";
3

4
var canvas,
5
  context,
6 7
  fpsBuffer,
  currentFPS;
8

9
// TODO: Look for values to be copied and stored from GameConfig to reduce access time
10 11
function draw(state) {
  updateFPS(state.delta);
12
  context.clearRect(0, 0, canvas.width, canvas.height);
13
  drawObjects(state.objects);
14
  drawGazePoints(state.gazePoints);
15
  if (GameConfig.getShowDebugInfoOnScreen() === true) {
16 17 18 19
    drawDebugInfo();
  }
}

20
// TODO: Move fps callculation to manager since we need it there to use delta
21 22 23
function updateFPS(delta) {
  let fps = Time.ONE_SECOND_IN_MS / delta;
  fpsBuffer.push(fps);
24
  if (fpsBuffer.length === GameConfig.getFPSBufferLenght()) {
25 26 27 28
    currentFPS = parseInt(fpsBuffer.reduce((a, b) => a + b, 0) /
      fpsBuffer.length);
    fpsBuffer.shift();
  }
29 30
}

31 32 33
function drawObjects(objects) {
  for (let i = 0; i < objects.length; i++) {
    objects[i].draw(context);
34
  }
35 36
}

37
function drawGazePoints(gazePoints) {
38
  context.fillStyle = GameConfig.getGazePointColor();
39 40
  for (let i = 0; i < gazePoints.length; i++) {
    drawSingleGazePoint(gazePoints[i]);
41 42 43
  }
}

44
function drawSingleGazePoint(gazePoint) {
45
  let inversedAge = 1 - gazePoint.relativeAge,
46
    radius = inversedAge * GameConfig.getGazePointRadius();
47
  context.save();
48
  context.globalAlpha = inversedAge;
49 50 51 52 53 54
  context.beginPath();
  context.ellipse(gazePoint.targetX, gazePoint.targetY, radius, radius, Math.PI /
    4, 0, 2 * Math.PI);
  context.closePath();
  context.fill();
  context.restore();
55 56 57 58
}

function drawDebugInfo() {
  context.beginPath();
59 60 61
  context.font = GameConfig.getDebugInfoFont();
  context.fillStyle = GameConfig.getDebugInfoFonColor();
  context.fillText(`${GameConfig.getVersion()} | ${currentFPS}fps`, GameConfig.getDebugInfoPosition().x, GameConfig.getDebugInfoPosition().y);
62 63 64 65 66
  context.closePath();
}

class GameRenderer {

67
  init(gameCanvas) {
68
    fpsBuffer = [];
69 70
    currentFPS = 0;
    canvas = gameCanvas;
71 72 73 74
    canvas.width = GameConfig.getScreenWidth();
    canvas.height = GameConfig.getScreenHeight();
    canvas.style.width = `${GameConfig.getScreenWidth()}px`;
    canvas.style.height = `${GameConfig.getScreenHeight()}px`;
75
    context = canvas.getContext("2d", { alpha: false });
76
    canvas.style.backgroundColor = GameConfig.getWorldBackgroundColor();
77 78
  }

79 80
  render(state) {
    draw(state);
81 82 83 84 85
  }

}

export default new GameRenderer();