Skip to content

Commit

Permalink
Implement random seeds under wasm
Browse files Browse the repository at this point in the history
  • Loading branch information
tomassedovic committed Dec 21, 2017
1 parent 6a194bc commit fdbc828
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 4 deletions.
1 change: 1 addition & 0 deletions dose-response.js
Expand Up @@ -118,6 +118,7 @@ fetch('target/wasm32-unknown-unknown/release/dose-response.wasm')

.then(bytes => WebAssembly.instantiate(bytes, {
env: {
random: Math.random,
draw: function(ptr, len) {
if(len % 6 != 0) {
throw new Error("The drawcalls vector must have a multiple of 6 elements!");
Expand Down
1 change: 1 addition & 0 deletions src/main.rs
Expand Up @@ -376,6 +376,7 @@ pub fn initialise() -> *mut State {

extern {
fn draw(nums: *const u8, len: usize);
fn random() -> f32;
}


Expand Down
6 changes: 2 additions & 4 deletions src/state.rs
@@ -1,11 +1,10 @@


use animation::{AreaOfEffect, ScreenFade};
use engine::Mouse;
use keys::Keys;
use monster;
use player::Player;
use point::Point;
use util;
use rand::{self, IsaacRng, SeedableRng};

use stats::Stats;
Expand Down Expand Up @@ -203,8 +202,7 @@ impl State {
) -> State {
let commands = VecDeque::new();
let verifications = VecDeque::new();
//let seed = rand::random::<u32>();
let seed = 1234;
let seed = util::random_seed();
let mut writer: Box<Write> = if let Some(replay_path) = replay_path {
match File::create(&replay_path) {
Ok(f) => {
Expand Down
16 changes: 16 additions & 0 deletions src/util.rs
@@ -1,5 +1,7 @@
use std::time::Duration;

use rand;


/// The number of nanoseconds in a microsecond.
const NANOS_PER_MICRO: u32 = 1000;
Expand All @@ -26,3 +28,17 @@ pub fn num_microseconds(duration: Duration) -> Option<u64> {
}
None
}


#[cfg(not(feature = "web"))]
pub fn random_seed() -> u32 {
rand::random::<u32>()
}

#[cfg(feature = "web")]
pub fn random_seed() -> u32 {
#[allow(unsafe_code)]
// NOTE: this comes from `Math.random` and returns a float in the <0, 1> range:
let random_float = unsafe { ::random() };
(random_float * ::std::u32::MAX as f32) as u32
}

0 comments on commit fdbc828

Please sign in to comment.