{"size": 1534, "ext": "js", "max_stars_repo_path": "react/performance/web_assembly/game/engine/WASMEngine.js", "max_stars_repo_name": "daunmuyu/project-config", "max_stars_repo_stars_event_min_datetime": "2018-02-04T13:19:38.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-25T09:48:18.000Z", "max_issues_repo_path": "web/react/wasm/game/engine/WASMEngine.js", "max_issues_repo_name": "wxyyxc1992/algods-snippets", "max_issues_repo_issues_event_min_datetime": "2021-05-07T16:29:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-07T16:29:51.000Z", "max_forks_repo_path": "web/react/wasm/game/engine/WASMEngine.js", "max_forks_repo_name": "wxyyxc1992/algods-snippets", "max_forks_repo_forks_event_min_datetime": "2018-03-30T01:08:22.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-15T06:58:20.000Z"}
{"max_stars_count": 52, "max_issues_count": 1, "max_forks_count": 9, "avg_line_length": 25.5666666667, "max_line_length": 80, "alphanum_fraction": 0.5495436767}
// @flow

import EngineWASM from "./wasm/engine.wasm";

export default class WASMEngine {
  constructor(width, height) {
    this.wasm = true;
    this.width = width;
    this.height = height;
    this.module = new EngineWASM({
      env: {
        memoryBase: 0,
        tableBase: 0,
        memory: new window.WebAssembly.Memory({ initial: 1024 }),
        table: new window.WebAssembly.Table({ initial: 0, element: "anyfunc" }),
        _malloc: size => {
          let buffer = new ArrayBuffer(size);
          return new Uint8Array(buffer);
        },
        _memcpy: (source, target, size) => {
          let sourceEnd = source.byteLength;

          let i, j;

          for (
            (i = 0), (j = 0), (k = new Uint8Array(target)), (l = new Uint8Array(
              source
            ));
            i < sourceEnd;
            ++i, ++j
          )
            k[j] = l[i];
        }
      }
    });
  }

  init() {
    // _init returns a pointer to the array of the current game state
    // we'll save it to have a fast access to the state in cellSafe
    this.currentAdress = this.module.exports._init(this.width, this.height);
  }

  cellSafe(i, j) {
    // cellSafe should only be called when we know i and j are within
    // the bounds of the game state array.
    return this.module.HEAP8[
      this.currentAdress + (i + 1) * (this.width + 2) + j + 1
    ];
  }

  computeNextState() {
    this.module.exports._computeNextState();
  }

  set(i, j, value = 1) {
    this.module.exports._set(i, j, value);
  }
}
