-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.js
80 lines (64 loc) · 2.3 KB
/
game.js
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// Render Mandelbrot Set with a Zig Function in WebAssembly. Based on...
// https://dev.to/sleibrock/webassembly-with-zig-pt-ii-ei7
// https://github.com/daneelsan/zig-wasm-logger/blob/master/script.js
// References to Exported Zig Functions
let Game;
// Export JavaScript Functions to Zig
const importObject = {
// JavaScript Functions exported to Zig
env: {
// JavaScript Print Function exported to Zig
print: function(x) { console.log(x); }
}
};
// Get the HTML Canvas Context
const canvas = window.document.getElementById("game_canvas");
const context = canvas.getContext("2d");
// Main Function
function main() {
console.log("main: start");
// Render Loop
const loop = function() {
console.log("loop: start");
// Clear the HTML Canvas
context.fillStyle = "white";
context.fillRect(0, 0, canvas.width, canvas.height);
// For every Pixel in HTML Canvas...
for (let x = 0; x < canvas.width; x++) {
for (let y = 0; y < canvas.height; y++) {
// Get the Pixel Color from Zig
const color = Game.instance.exports
.get_pixel_color(x, y);
// Render the Pixel in HTML Canvas
if (color < 10) {
context.fillStyle = "red";
} else if (color < 128) {
context.fillStyle = "grey";
} else {
context.fillStyle = "white";
}
context.fillRect(x, y, x + 1, y + 1);
}
}
// Loop to next frame. Disabled for now because it slows down the browser.
// TODO: window.requestAnimationFrame(loop);
console.log("loop: end");
};
loop();
console.log("main: end");
};
// Load the WebAssembly Module and start the Main Function
async function bootstrap() {
// Load the WebAssembly Module
// https://developer.mozilla.org/en-US/docs/WebAssembly/JavaScript_interface/instantiateStreaming
const result = await WebAssembly.instantiateStreaming(
fetch("mandelbrot.wasm"),
importObject
);
// Store references to WebAssembly Functions and Memory exported by Zig
Game = result;
// Start the Main Function
main();
}
// Start the loading of WebAssembly Module
bootstrap();