From 1339905253d6eb0c0cb1af246d6243c86466bb06 Mon Sep 17 00:00:00 2001 From: Reece Humphreys Date: Tue, 23 Jan 2024 15:26:10 -0500 Subject: [PATCH] Clean up satellite web assembly api --- src/lib.rs | 16 ++++++++++++---- src/satellite.rs | 23 ++++++++++++++++++++++- 2 files changed, 34 insertions(+), 5 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 0484ba6..8beb9d4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -10,21 +10,29 @@ use ndarray::{s, Array, Array1, Array2, Array3}; use rand::distributions::{Distribution, Uniform}; use rand_distr::{Normal, UnitSphere}; +#[cfg(target_arch = "wasm32")] +use wasm_bindgen::{prelude::*, JsValue}; + // Non-WebAssembly bindings #[cfg(not(target_arch = "wasm32"))] pub fn run(event: &impl FragmentationEvent) -> Array3 { run_core(event) } -// WebAssembly bindings #[cfg(target_arch = "wasm32")] -use wasm_bindgen::{prelude::*, JsValue}; +#[wasm_bindgen] +pub fn run_explosion(event: &ExplosionEvent) -> JsValue { + let result = run_core(event); + // Convert the result to JsValue + serde_wasm_bindgen::to_value(&result).unwrap() +} #[cfg(target_arch = "wasm32")] -pub fn run(event: &impl FragmentationEvent) -> Option { +#[wasm_bindgen] +pub fn run_collision(event: &CollisionEvent) -> JsValue { let result = run_core(event); // Convert the result to JsValue - serde_wasm_bindgen::to_value(&result).ok() + serde_wasm_bindgen::to_value(&result).unwrap() } fn run_core(event: &impl FragmentationEvent) -> Array3 { diff --git a/src/satellite.rs b/src/satellite.rs index 178cfad..5c450ed 100644 --- a/src/satellite.rs +++ b/src/satellite.rs @@ -1,6 +1,9 @@ use ndarray::prelude::*; use wasm_bindgen::prelude::*; +#[cfg(target_arch = "wasm32")] +use js_sys::Float32Array; + #[wasm_bindgen] #[derive(Debug, Clone)] pub struct Satellite { @@ -13,7 +16,7 @@ pub struct Satellite { #[wasm_bindgen] impl Satellite { - #[wasm_bindgen(constructor)] + #[cfg(not(target_arch = "wasm32"))] pub fn new(position: Vec, velocity: Vec, mass: f32, sat_kind: SatKind) -> Self { Self { position: Array1::from_vec(position), @@ -24,6 +27,24 @@ impl Satellite { } } + #[cfg(target_arch = "wasm32")] + #[wasm_bindgen(constructor)] + pub fn new(position: JsValue, velocity: JsValue, mass: f32, sat_kind: SatKind) -> Self { + let position_array: Float32Array = position.into(); + let velocity_array: Float32Array = velocity.into(); + + assert_eq!(position_array.length(), 3, "Position array must have 3 elements."); + assert_eq!(velocity_array.length(), 3, "Velocity array must have 3 elements."); + + Self { + position: Array1::from_vec(position_array.to_vec()), + velocity: Array1::from_vec(velocity_array.to_vec()), + mass, + characteristic_length: calculate_characteristic_length_from_mass(mass), + sat_kind, + } + } + pub fn set_position(&mut self, position: &[f32]) { self.position = Array1::from_vec(position.to_vec()); }