Common JavaScript loading code

We will fetch and instantiate a .wasm file in several of the examples, so it makes sense to move the JavaScript loading code to a common file. The actual fetch and instantiation code is only a few lines, but having to repeatedly redefine the importObj object that Emscripten expects is a waste of time. We'll make this code available in a commonly accessible file to expedite the code-writing process. Create a new folder named /common in the /book-examples folder and add a file named load-wasm.js with the following contents:

/**
* Returns a valid importObj.env object with default values to pass
* into the WebAssembly.Instance constructor for Emscripten's
* Wasm module.
*/
const getDefaultEnv = () => ({
memoryBase: 0,
tableBase: 0,
memory: new WebAssembly.Memory({ initial: 256 }),
table: new WebAssembly.Table({ initial: 2, element: 'anyfunc' }),
abort: console.log
});

/**
* Returns a WebAssembly.Instance instance compiled from the specified
* .wasm file.
*/
function loadWasm(fileName, importObj = { env: {} }) {
// Override any default env values with the passed in importObj.env
// values:
const allEnv = Object.assign({}, getDefaultEnv(), importObj.env);

// Ensure the importObj object includes the valid env value:
const allImports = Object.assign({}, importObj, { env: allEnv });

// Return the result of instantiating the module (instance and module):
return fetch(fileName)
.then(response => {
if (response.ok) return response.arrayBuffer();
throw new Error(`Unable to fetch WebAssembly file ${fileName}`);
})
.then(bytes => WebAssembly.instantiate(bytes, allImports));
}

The getDefaultEnv() function provides the required importObj.env contents for Emscripten's Wasm module. We want the ability to pass in any additional imports, which is why the Object.assign() statement is used. With the addition of any other imports the Wasm module expects, Emscripten's Wasm output will always require these five import statements for the "env" object:

(import "env" "memory" (memory $env.memory 256))
(import "env" "table" (table $env.table 8 anyfunc))
(import "env" "memoryBase" (global $env.memoryBase i32))
(import "env" "tableBase" (global $env.tableBase i32))
(import "env" "abort" (func $env.abort (type $t0)))

We need to pass those into the instantiate() function to ensure the Wasm module loads successfully, otherwise the browser will throw an error. Now that we have our loading code ready, let's move on to the HTML and rectangle-rendering code.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset