/* Utility functions to store and load coordinates to and from module memory Coordinates are assumed to be an array of coordinate pairs ([[x1,y1], [x2,y2], [x3,y3]]) */ /** * Allocate memory for coordinates and stores them in a flat representation. * Returns a pointer to the buffer. The length of the buffer is coords.length * 2 * @param {*} module * @param {Array} coords - An array of coordinate pairs */ export function storeCoords(module, coords) { const flatSize = coords.length * 2 const offset = module._malloc(flatSize * Float64Array.BYTES_PER_ELEMENT) const heapView = new Float64Array(module.HEAPF64.buffer, offset, flatSize) for (let i = 0; i < coords.length; i++) { heapView[2 * i] = coords[i][0] heapView[2 * i + 1] = coords[i][1] } return offset } /** * Loads coordinates from the memory by the result pointer. * Frees the resultpointer and the result before returning * @param {*} module * @param {*} result - pointer to Uint32 array of length 2. Stores the resultPointer and resultLength */ export function loadResultAndFreeMemory(module, resultInfo) { const [resultPointer, resultLength] = new Uint32Array( module.HEAPU32.buffer, resultInfo, 2 ) const simplified = new Float64Array( module.HEAPF64.buffer, resultPointer, resultLength ) const coords = unflattenCoords(simplified) module._free(resultInfo) module._free(resultPointer) return coords } /** * Loads coordinates from the memory by the result pointer without freeing memory. * For benchmarking purposes * @param {*} module * @param {*} result - pointer to Uint32 array of length 2. Stores the resultPointer and resultLength */ export function loadResult(module, result) { const [resultPointer, resultLength] = new Uint32Array( module.HEAPU32.buffer, result, 2 ) const simplified = new Float64Array( module.HEAPF64.buffer, resultPointer, resultLength ) return unflattenCoords(simplified) } /** * Transforms a flat array to an array coordinate pairs * @param {Array} flattened - length must be even */ export function unflattenCoords(flattened) { const coords = [] let x, y for (let i = 0; i < flattened.length; i += 2) { x = flattened[i] y = flattened[i + 1] coords.push([x, y]) } return coords }