Trial a Rust engine powering a Civet interface

Write a basic web app with a Rust engine, compiled to WebAssembly,
powering a Civet interface. Do linear algebra in the engine using
the `nalgebra` crate.
This commit is contained in:
Aaron Fenyes 2024-07-28 21:10:04 -07:00
parent d7dbee4c05
commit 12abef4076
8 changed files with 287 additions and 0 deletions

View file

@ -0,0 +1,55 @@
mod utils;
extern crate js_sys;
use nalgebra::*;
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub struct Circle {
pub center_x: f64,
pub center_y: f64,
pub radius: f64,
}
// construct the circle through
//
// (x1, y1), (x2, y2), (x3, y3)
//
// from the array
//
// [x1, y1, x2, y2, x3, y3]
//
#[wasm_bindgen]
pub fn circThru(data_raw: js_sys::Float64Array) -> Result<Circle, JsValue> {
// represent the given points as the columns of a matrix
let data = Matrix2x3::from_vec(data_raw.to_vec());
// build the matrix that maps the circle's coefficient vector to the
// negative of the linear part of the circle's equation, evaluated at the
// given points
let neg_lin_part = stack![2.0*data.transpose(), Vector3::repeat(1.0)];
// find the quadrdatic part of the circle's equation, evaluated at the given
// points
let quad_part = Vector3::from_iterator(
data.column_iter().map(|v| v.dot(&v))
);
// find the circle's coefficient vector, and from there its center and
// radius
match neg_lin_part.lu().solve(&quad_part) {
None => Err(JsValue::from("Couldn't solve system")),
Some(coeffs) => {
let center_x = coeffs[0];
let center_y = coeffs[1];
Ok(Circle {
center_x: center_x,
center_y: center_y,
radius: (
coeffs[2] + center_x*center_x + center_y*center_y
).sqrt(),
})
}
}
}

View file

@ -0,0 +1,10 @@
pub fn set_panic_hook() {
// When the `console_error_panic_hook` feature is enabled, we can call the
// `set_panic_hook` function at least once during initialization, and then
// we will get better error messages if our code ever panics.
//
// For more details see
// https://github.com/rustwasm/console_error_panic_hook#readme
#[cfg(feature = "console_error_panic_hook")]
console_error_panic_hook::set_once();
}