Skip to content

Instantly share code, notes, and snippets.

@eXponenta
Created July 23, 2020 18:28
Show Gist options
  • Save eXponenta/1d56181079d50f8229198e0c855f3882 to your computer and use it in GitHub Desktop.
Save eXponenta/1d56181079d50f8229198e0c855f3882 to your computer and use it in GitHub Desktop.
import {exports} from "./loader.js";
let FF_WASM = (...args) => {};
const N_DX = [0, 1, 0, -1]; // relative neighbor x coordinates
const N_DY = [-1, 0, 1, 0]; // relative neighbor y coordinates
const stack = new Array(100);
function FF_JS(x, y, color, width, height, data)
{
const index = (x + y * width);
const oldc32 = data[index];
let stackIndex = 0;
let count = 0;
stack[stackIndex ++] = x;
stack[stackIndex ++] = y;
while(stackIndex > 0) {
const cy = stack[--stackIndex];
const cx = stack[--stackIndex];
if(stackIndex < 0) {
break;
}
const i = (cx + cy * width);
data[i] = color;
for(let j = 0; j < 4; j ++) {
let nx = cx + N_DX[j];
let ny = cy + N_DY[j];
if(nx >= 0 && ny >= 0 && nx < width && ny < height) {
const ni = (nx + ny * width);
if(data[ni] === oldc32) {
stack[stackIndex ++] = nx;
stack[stackIndex ++] = ny;
}
}
}
}
return data;
}
fetch("./build/untouched.wasm")
.then((response) => response.arrayBuffer())
.then((buff) => exports.instantiate(buff))
.then(({exports})=>{
const {floodFill, Uint32Array_ID, __allocArray, __getArray, __retain, __release} = exports;
let res = [];
FF_WASM = (x, y, c, w, h, buff) =>{
const arr = __retain(__allocArray(Uint32Array_ID, buff));
floodFill(x,y,c,w,h,arr);
const ret = __getArray(arr);
__release(arr);
return ret;
}
function test(func) {
const buff = new Array(100 * 100).fill(0);
const start = performance.now();
const out = func(0,0, 0xff00ffff, 100, 100, buff);
const end = performance.now() - start;
console.log(end, func.name);
res.push(out);
}
for(let i = 0; i < 100; i ++) {
test(FF_WASM);
test(FF_JS);
}
})
const N_DX: u32[] = [0, 1, 0, -1]; // relative neighbor x coordinates
const N_DY: u32[] = [-1, 0, 1, 0]; // relative neighbor y coordinates
export const Uint32Array_ID = idof<Uint32Array>();
const stack: Array<u32> = new Array<u32>(100);
export function floodFill(x: u32, y: u32, color: u32, width: u32, height: u32, data: Uint32Array): u32
{
const index: u32 = (x + y * width);
const oldc32 = data[index];
let stackIndex: u32 = 0;
let count: u32 = 0;
stack[stackIndex ++] = x;
stack[stackIndex ++] = y;
while(stackIndex > 0) {
const cy: u32 = stack[--stackIndex];
const cx: u32 = stack[--stackIndex];
if(stackIndex < 0) {
break;
}
const i:u32 = (cx + cy * width);
data[i] = color;
count ++;
for(let j = 0; j < 4; j ++) {
let nx: u32 = cx + N_DX[j];
let ny: u32 = cy + N_DY[j];
if(nx >= 0 && ny >= 0 && nx < width && ny < height) {
const ni = (nx + ny * width);
if(data[ni] === oldc32) {
stack[stackIndex ++] = nx;
stack[stackIndex ++] = ny;
}
}
}
}
return count;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment