Skip to content

Commit

Permalink
Clean up satellite web assembly api
Browse files Browse the repository at this point in the history
  • Loading branch information
ReeceHumphreys committed Jan 23, 2024
1 parent 879eed6 commit 1339905
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 5 deletions.
16 changes: 12 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<f32> {
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<JsValue> {
#[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<f32> {
Expand Down
23 changes: 22 additions & 1 deletion src/satellite.rs
Original file line number Diff line number Diff line change
@@ -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 {
Expand All @@ -13,7 +16,7 @@ pub struct Satellite {

#[wasm_bindgen]
impl Satellite {
#[wasm_bindgen(constructor)]
#[cfg(not(target_arch = "wasm32"))]
pub fn new(position: Vec<f32>, velocity: Vec<f32>, mass: f32, sat_kind: SatKind) -> Self {
Self {
position: Array1::from_vec(position),
Expand All @@ -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());
}
Expand Down

0 comments on commit 1339905

Please sign in to comment.