-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
442 lines (378 loc) · 19.5 KB
/
index.html
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="icon" href="data:;base64,iVBORw0KGgo=">
</head>
<body>
<script type="module">
const getInput = (prompt_) => new Promise((resolve) => {
resolve(window.prompt(prompt_));
});
const charCodeToChar = (charCode) => String.fromCharCode(charCode);
// get args via query string
const args = location.search ? location.search.substring(1).split(',') : [];
const wasmFile = args.shift();
console.log(`wasmFile file: ${wasmFile}`);
console.log('args:', args);
if (wasmFile === 'AddInt.wasm') {
{
const watProm = fetch("AddInt.wasm");
const obj = await WebAssembly.instantiateStreaming(watProm);
const [a, b] = args.map(s => parseInt(s, 10));
const { AddInt } = obj.instance.exports;
if (isNaN(a) || isNaN(b)) {
throw new Error('needs 2 integer numbers passed in as query string arguments!');
}
const c = AddInt(a, b);
console.log('result:', c);
}
} else if (wasmFile === 'HelloWorld.wasm') {
{
const memory = new WebAssembly.Memory ({ initial: 1 });
const importObject = {
env: {
buffer: memory,
startStringIndex: 100,
PrintString: (startStrIdx, strLen) => {
const bytes = new Uint8Array(memory.buffer, startStrIdx, strLen);
const strToLog = new TextDecoder('utf8').decode(bytes);
console.log(strToLog);
}
}
};
const watProm = fetch("HelloWorld.wasm");
const obj = await WebAssembly.instantiateStreaming(watProm, importObject);
const { HelloWorld } = obj.instance.exports;
HelloWorld();
}
} else if (wasmFile === 'ForLoop.wasm') {
{
const importObject = {
env: {
PrintI32: (numI32) => {
console.log(numI32);
}
}
};
const watProm = fetch("ForLoop.wasm");
const obj = await WebAssembly.instantiateStreaming(watProm, importObject);
const { ForLoop } = obj.instance.exports;
const [startNum, endNum] = args.map(s => parseInt(s, 10));
if (isNaN(startNum) || isNaN(endNum)) {
throw new Error('needs 2 integer numbers passed in as query string arguments!');
}
ForLoop(startNum, endNum);
}
} else if (wasmFile === 'Prime.wasm') {
{
const watProm = fetch("Prime.wasm");
const obj = await WebAssembly.instantiateStreaming(watProm);
const { IsPrime } = obj.instance.exports;
const n = parseInt(args[0], 10);
if (isNaN(n)) {
throw new Error('needs 1 integer number passed in as query string argument!');
}
// const isEven = Boolean( EvenCheck(n) ); console.log('is even?', isEven);
// const mc = Boolean( MultipleCheck(n, m) ); console.log(n, m, 'is multiple?', mc);
console.time('Prime.wasm');
const isP = Boolean( IsPrime(n) ); console.log(n, 'is prime?', isP);
console.timeEnd('Prime.wasm');
}
} else if (wasmFile === 'Prime.mjs') {
{
const mod = await import('./Prime.mjs');
const { Prime } = mod;
const n = parseInt(args[0], 10);
console.time('Prime.mjs');
const isP = Prime(n); console.log(n, 'is prime?', isP);
console.timeEnd('Prime.mjs');
}
} else if (wasmFile === 'TableTest.wasm') {
{
let i;
const increment = () => ++i;
const decrement = () => --i;
const importObject = {
js: {
increment,
decrement,
tbl: undefined, // set by TableExport.wasm
wasm_increment: undefined, // set by TableExport.wasm
wasm_decrement: undefined // set by TableExport.wasm
}
};
const watPromExport = fetch("TableExport.wasm");
const objExport = await WebAssembly.instantiateStreaming(watPromExport, importObject);
importObject.js.tbl = objExport.instance.exports.tbl;
importObject.js.wasm_increment = objExport.instance.exports.increment;
importObject.js.wasm_decrement = objExport.instance.exports.decrement;
const watPromTest = fetch("TableTest.wasm");
const objTest = await WebAssembly.instantiateStreaming(watPromTest, importObject);
const { js_table_test, js_import_test,
wasm_table_test, wasm_import_test } = objTest.instance.exports;
i = 0;
console.time('js_table');
js_table_test();
console.timeEnd('js_table');
i = 0;
console.time('js_import');
js_import_test();
console.timeEnd('js_import');
i = 0;
console.time('wasm_table');
wasm_table_test();
console.timeEnd('wasm_table');
i = 0;
console.time('wasm_import');
wasm_import_test();
console.timeEnd('wasm_import');
}
} else if (wasmFile === 'BigIntI64.wasm') {
{
const watProm = fetch("BigIntI64.wasm");
const obj = await WebAssembly.instantiateStreaming(watProm);
const [a, b] = args.map(s => BigInt(s));
const { AddBigInts } = obj.instance.exports;
const c = AddBigInts(a, b);
console.log('result:', c);
}
} else if (wasmFile === 'Strings.wasm') {
{
const memory = new WebAssembly.Memory ({ initial: 1 });
const importObject = {
env: {
buffer: memory,
str_pos_len: (startStrIdx, strLen) => {
const bytes = new Uint8Array(memory.buffer, startStrIdx, strLen);
const strToLog = new TextDecoder('utf8').decode(bytes);
console.log(`[${strToLog}]`);
},
str_pos_len_prefixed: (startStrIdx) => {
const strLen = new Uint8Array(memory.buffer, startStrIdx, 1)[0];
const bytes = new Uint8Array(memory.buffer, startStrIdx+1, strLen);
const strToLog = new TextDecoder('utf8').decode(bytes);
console.log(`[${strToLog}]`);
}
}
};
const watProm = fetch("Strings.wasm");
const obj = await WebAssembly.instantiateStreaming(watProm, importObject);
const { main } = obj.instance.exports;
debugger;
main();
const bytes = new Uint8Array( memory.buffer );
const char = (bytes, idx) => String.fromCharCode(bytes[idx]);
const chars = (bytes, idx, len) => Array.from( bytes.slice(idx, idx + len) )
.map(u8 => u8 ? String.fromCharCode(u8) : '◆') // to make char 0 visible
.join('');
console.log('bytes', bytes);
console.log(char(bytes, 0));
console.log(chars(bytes, 0, 30)); // 1st string
console.log(chars(bytes, 32, 35)); // 2nd string
console.log(chars(bytes, 0, 70)); // we can also see 2 0ed bytes between the strings and after the 2nd one ends
const readNullTerminatedString = (bytes, idx) => {
let s = '';
while (true) {
const u8 = bytes[idx];
if (u8 === 0) return s;
const utf8Char = String.fromCharCode(u8);
s += utf8Char;
++idx;
}
}
console.log(readNullTerminatedString(bytes, 0)); // 1st string
console.log(readNullTerminatedString(bytes, 32)); // 2nd string
}
} else if (wasmFile === 'NumberString.wasm') {
{
const memory = new WebAssembly.Memory ({ initial: 1 });
const importObject = {
env: {
buffer: memory,
PrintString: (startStrIdx, strLen) => {
const bytes = new Uint8Array(memory.buffer, startStrIdx, strLen);
const strToLog = new TextDecoder('utf8').decode(bytes);
console.log(strToLog);
}
}
};
const watProm = fetch("NumberString.wasm");
const obj = await WebAssembly.instantiateStreaming(watProm, importObject);
const { to_string } = obj.instance.exports;
const n = parseInt(args[0], 10);
if (isNaN(n)) {
throw new Error('needs 1 integer number passed in as a cli argument!');
}
to_string(n);
}
} else if (wasmFile === 'TicTacToe.wasm') {
{
const memory = new WebAssembly.Memory ({ initial: 1 });
const importObject = {
env: {
buffer: memory,
PrintChar: (charCode) => {
console.log(String.fromCharCode(charCode));
},
PrintString3x3: (startStrIdx, strLen) => {
const bytes = new Uint8Array(memory.buffer, startStrIdx, strLen);
const strToLog = new TextDecoder('utf8').decode(bytes);
const lines = strToLog.split('').reduce((prev, curr, i) => {
let line;
if (i % 3 === 0) {
line = [];
prev.push(line);
}
else {
line = prev[prev.length - 1];
}
line.push(curr);
return prev;
}, []);
console.log(lines.map(line => line.join('')).join('\n'));
}
}
};
const watProm = fetch("TicTacToe.wasm");
const obj = await WebAssembly.instantiateStreaming(watProm, importObject);
const {
setCharAt, isValidSet, printBoard, hasWon, isBoardFull, nextCharToPlay, getMoveNumber,
} = obj.instance.exports;
while (true) {
const currChar = nextCharToPlay();
const moveNr = getMoveNumber();
console.log(`\nmove #${moveNr}`);
console.log('\nboard:');
printBoard();
console.log(`\nnext to play: ${charCodeToChar(currChar)}`);
let x, y;
while (true) {
x = parseInt(await getInput('x: '), 10);
y = parseInt(await getInput('y: '), 10);
console.log(x, y);
if (isValidSet(x, y, currChar)) break;
console.warn('incorrect move!');
}
setCharAt(x, y, currChar);
if (hasWon(currChar)) {
console.log(`${charCodeToChar(currChar)} has won!`);
break;
}
if (isBoardFull()) {
console.log(`Game was tied!`);
break;
}
}
}
} else if (wasmFile === 'StoreData.wasm') {
{
const mem = new WebAssembly.Memory ({ initial: 1 });
const data_addr = 32; // the address of the first byte of our data
const data_count = 16; // the number of 32-bit integers to set
const importObject = {
env: {
mem,
data_addr,
data_count,
}
};
const mem_i32 = new Uint32Array(mem.buffer);
const data_i32_index = data_addr / 4; // The 32-bit index of the beginning of our data
const watProm = fetch("StoreData.wasm");
await WebAssembly.instantiateStreaming(watProm, importObject);
for (let i = 0; i < data_i32_index + data_count + 4; ++i) {
let data = mem_i32[i];
if (data !== 0) {
console.log(`%cdata[${i}]=${data}`, 'color:red');
} else {
console.log(`data[${i}]=${data}`);
}
}
}
} else if (wasmFile === 'DataStructures.wasm') {
{
const mem = new WebAssembly.Memory ({ initial: 1 });
const mem_i32 = new Uint32Array(mem.buffer);
const obj_base_addr = 0; // the address of the first byte of our data
const obj_count = 16; // the number of structures
const obj_stride = 16; // 16-byte stride
// structure attribute offsets
const x_offset = 0;
const y_offset = 4;
const radius_offset = 8;
const collision_offset = 12;
// 32-bit integer indexes
const obj_i32_base_index = obj_base_addr / 4; // 32-bit data index
const obj_i32_stride = obj_stride / 4; // 32-bit stride
// offsets in the 32-bit integer array
const x_offset_i32 = x_offset / 4;
const y_offset_i32 = y_offset / 4;
const radius_offset_i32 = radius_offset / 4;
const collision_offset_i32 = collision_offset / 4;
const importObject = {
env: {
mem,
obj_base_addr,
obj_count,
obj_stride,
x_offset,
y_offset,
radius_offset,
collision_offset,
}
};
let drawCircle;
{
const SCALE = 5;
const el = document.createElement('canvas');
el.setAttribute('width', SCALE * 100);
el.setAttribute('height', SCALE * 400);
document.body.appendChild(el);
const ctx = el.getContext('2d');
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.lineWidth = 1 / SCALE;
ctx.font = `${14/SCALE}px sans-serif`;
ctx.scale(SCALE, SCALE);
drawCircle = (x, y, r, i, color = 'black') => {
ctx.fillStyle = color;
ctx.strokeStyle = color;
ctx.fillText(`${i}`, x, y);
ctx.beginPath();
ctx.arc(x, y, r, 0, 2 * Math.PI, false);
ctx.stroke();
}
}
// populate structures
for (let i = 0; i < obj_count; ++i) {
const index = obj_i32_stride * i + obj_i32_base_index;
const x = 10 + Math.floor(80 * Math.random());
const y = 10 + Math.floor(80 * Math.random());
const r = 3 + Math.floor(7 * Math.random());
mem_i32[index + x_offset_i32] = x;
mem_i32[index + y_offset_i32] = y;
mem_i32[index + radius_offset_i32] = r;
}
// run collision detection in wasm...
const watProm = fetch("DataStructures.wasm");
await WebAssembly.instantiateStreaming(watProm, importObject);
// print results
for (let i = 0; i < obj_count; ++i) {
const index = obj_i32_stride * i + obj_i32_base_index;
const x = mem_i32[index + x_offset_i32].toString().padStart(2, ' ');
const y = mem_i32[index + y_offset_i32].toString().padStart(2, ' ');
const r = mem_i32[index + radius_offset_i32].toString();
const i_str = i.toString().padStart(2, ' ');
const c = !!mem_i32[index + collision_offset_i32];
if (c) console.log(`%cobj[${i_str}] x:${x} y:${y} r:${r} collision:${c}`, 'color:red');
else console.log(`%cobj[${i_str}] x:${x} y:${y} r:${r} collision:${c}`, 'color:green');
drawCircle(x, y, r, i, c ? 'red' : 'green');
}
}
} else {
alert('expects the wasm file to be provided, followed by the arguments to pass to it');
}
</script>
</body>
</html>