Interference example | The AssemblyScript Book

Colin Eberhardt's and Ben Smith's WebAssembly interference effect (opens new window), if it was written in AssemblyScript.

# Contents

  • Exporting functions and variables from a WebAssembly module.
  • Calling functions and reading variables exported from WebAssembly.
  • Utilizing 32-bit floating point math to speed up calculations by utilizing Mathf.
  • Keeping an image buffer within the module's memory and copying it to a canvas.
  • Manually growing memory depending on the size of the viewport on the browser side.
  • And finally: Continuously updating and rendering the image buffer.

# Example

EPILEPSY WARNING

A very small percentage of individuals may experience epileptic seizures when exposed to certain light patterns or flashing lights. Exposure to certain patterns or backgrounds on a computer screen may induce an epileptic seizure in these individuals. Certain conditions may induce previously undetected epileptic symptoms even in persons who have no history of prior seizures or epilepsy.

If you experience any of the following symptoms while viewing - dizziness, altered vision, eye or muscle twitches, loss of awareness, disorientation, any involuntary movement, or convulsions - IMMEDIATELY discontinue use and consult your physician.

NOTE

The example makes one important assumption: Since we are not using a sophisticated runtime, we can instead repurpose the entire heap, starting at __heap_base, as our image buffer.

As soon as this condition is no longer met, one would instead either reserve some space by specifying a suitable --memoryBase or export a dynamically instantiated chunk of memory, like an Uint32Array, and utilize it as the image buffer both in WebAssembly and in JavaScript.

# Running locally

Set up a new AssemblyScript project as described in Getting started and copy module.ts to assembly/index.ts and index.html to the project's top-level directory. Edit the build commands in package.json to include

The example can now be compiled with

To view the example, one can modify the instantiation in index.html from

to

because using the loader is not ultimately necessary here (no managed objects are exchanged). If the loader is used instead, it will automatically provide JSMath.

Some browsers may restrict fetching local resources when just opening index.html now, but one can set up a local server as a workaround: