mt-polygon-simplification/lib/psimpl-js/index.js
2019-07-25 09:53:20 +02:00

85 lines
2.7 KiB
JavaScript

/*
This file is meant to be processed in the context of an asset bundler.
Specifically the import of 'psimpl.wasm' is meant to be resolved by the
corresponding path to that file. Configure a file loader to resolve .wasm
files (e.g. Webpack: file-loader) accordingly.
Otherwise you have to use the module factory 'psimple.js' manually and
reproduce the steps from below to fit your build context. See example.html.
Other than wrapping the memory handling for convenience this method also makes
sure the module is only loaded once.
*/
import wasmModuleFactory from './psimpl.js'
import wasmUrl from './psimpl.wasm'
import { initEmscriptenModule } from '../../lib/wasm-util/initEmscripten.js'
import {
storeCoords,
unflattenCoords
} from '../../lib/wasm-util/coordinates.js'
export async function simplify_nth_point(coords, n) {
return await callSimplification('nth_point', coords, [n])
}
export async function simplify_radial_distance(coords, tol) {
return await callSimplification('radial_distance', coords, [tol])
}
export async function simplify_perpendicular_distance(coords, tol, repeat) {
const params = [tol, repeat]
return await callSimplification('perpendicular_distance', coords, params)
}
export async function simplify_reumann_witkam(coords, tol) {
return await callSimplification('reumann_witkam', coords, [tol])
}
export async function simplify_opheim(coords, minTol, maxTol) {
return await callSimplification('opheim', coords, [minTol, maxTol])
}
export async function simplify_lang(coords, tol, lookAhead) {
return await callSimplification('lang', coords, [tol, lookAhead])
}
export async function simplify_douglas_peucker(coords, tol) {
return await callSimplification('douglas_peucker', coords, [tol])
}
export async function simplify_douglas_peucker_n(coords, count) {
return await callSimplification('douglas_peucker_n', coords, [count])
}
async function callSimplification(name, coords, params) {
if (!isSimplificationRoutine(name)) throw Error(`Routine ${name} not known`)
const module = await getModule()
const buffer = storeCoords(module, coords)
const result = module[name](buffer, coords.length * 2, ...params)
module._free(buffer)
return unflattenCoords(result)
}
const simplificationRoutines = [
'nth_point',
'radial_distance',
'perpendicular_distance',
'reumann_witkam',
'opheim',
'lang',
'douglas_peucker',
'douglas_peucker_n'
]
function isSimplificationRoutine(name) {
return simplificationRoutines.indexOf(name) !== -1
}
let emscriptenModule
export async function getModule() {
if (!emscriptenModule)
emscriptenModule = initEmscriptenModule(wasmModuleFactory, wasmUrl)
return await emscriptenModule
}