Skip to content

Commit

Permalink
run cargo fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
GuillaumeGomez committed Dec 8, 2020
1 parent c418993 commit 7fd7ee4
Show file tree
Hide file tree
Showing 74 changed files with 6,179 additions and 4,713 deletions.
2 changes: 1 addition & 1 deletion build.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
fn main() {
#[cfg(any(target_os="openbsd", target_os="freebsd"))]
#[cfg(any(target_os = "openbsd", target_os = "freebsd"))]
println!(r"cargo:rustc-link-search=/usr/local/lib");
}
73 changes: 54 additions & 19 deletions examples/animation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,28 @@ use std::path::Path;

use sdl2::event::Event;
use sdl2::keyboard::Keycode;
use sdl2::rect::Rect;
use sdl2::rect::Point;
use sdl2::rect::Rect;
use std::time::Duration;

fn main() -> Result<(), String> {
let sdl_context = sdl2::init()?;
let video_subsystem = sdl_context.video()?;

let window = video_subsystem.window("SDL2", 640, 480)
.position_centered().build().map_err(|e| e.to_string())?;
let window = video_subsystem
.window("SDL2", 640, 480)
.position_centered()
.build()
.map_err(|e| e.to_string())?;

let mut canvas = window.into_canvas()
.accelerated().build().map_err(|e| e.to_string())?;
let mut canvas = window
.into_canvas()
.accelerated()
.build()
.map_err(|e| e.to_string())?;
let texture_creator = canvas.texture_creator();

canvas.set_draw_color(sdl2::pixels::Color::RGBA(0,0,0,255));
canvas.set_draw_color(sdl2::pixels::Color::RGBA(0, 0, 0, 255));

let mut timer = sdl_context.timer()?;

Expand All @@ -27,34 +33,39 @@ fn main() -> Result<(), String> {
// animation sheet and extras are available from
// https://opengameart.org/content/a-platformer-in-the-forest
let temp_surface = sdl2::surface::Surface::load_bmp(Path::new("assets/characters.bmp"))?;
let texture = texture_creator.create_texture_from_surface(&temp_surface)
let texture = texture_creator
.create_texture_from_surface(&temp_surface)
.map_err(|e| e.to_string())?;

let frames_per_anim = 4;
let sprite_tile_size = (32,32);
let sprite_tile_size = (32, 32);

// Baby - walk animation
let mut source_rect_0 = Rect::new(0, 0, sprite_tile_size.0, sprite_tile_size.0);
let mut dest_rect_0 = Rect::new(0, 0, sprite_tile_size.0*4, sprite_tile_size.0*4);
dest_rect_0.center_on(Point::new(-64,120));
let mut dest_rect_0 = Rect::new(0, 0, sprite_tile_size.0 * 4, sprite_tile_size.0 * 4);
dest_rect_0.center_on(Point::new(-64, 120));

// King - walk animation
let mut source_rect_1 = Rect::new(0, 32, sprite_tile_size.0, sprite_tile_size.0);
let mut dest_rect_1 = Rect::new(0, 32, sprite_tile_size.0*4, sprite_tile_size.0*4);
dest_rect_1.center_on(Point::new(0,240));
let mut dest_rect_1 = Rect::new(0, 32, sprite_tile_size.0 * 4, sprite_tile_size.0 * 4);
dest_rect_1.center_on(Point::new(0, 240));

// Soldier - walk animation
let mut source_rect_2 = Rect::new(0, 64, sprite_tile_size.0, sprite_tile_size.0);
let mut dest_rect_2 = Rect::new(0, 64, sprite_tile_size.0*4, sprite_tile_size.0*4);
dest_rect_2.center_on(Point::new(440,360));
let mut dest_rect_2 = Rect::new(0, 64, sprite_tile_size.0 * 4, sprite_tile_size.0 * 4);
dest_rect_2.center_on(Point::new(440, 360));

let mut running = true;
while running {
for event in event_pump.poll_iter() {
match event {
Event::Quit {..} | Event::KeyDown {keycode: Some(Keycode::Escape), ..} => {
Event::Quit { .. }
| Event::KeyDown {
keycode: Some(Keycode::Escape),
..
} => {
running = false;
},
}
_ => {}
}
}
Expand All @@ -73,9 +84,33 @@ fn main() -> Result<(), String> {

canvas.clear();
// copy the frame to the canvas
canvas.copy_ex(&texture, Some(source_rect_0), Some(dest_rect_0), 0.0, None, false, false)?;
canvas.copy_ex(&texture, Some(source_rect_1), Some(dest_rect_1), 0.0, None, true, false)?;
canvas.copy_ex(&texture, Some(source_rect_2), Some(dest_rect_2), 0.0, None, false, false)?;
canvas.copy_ex(
&texture,
Some(source_rect_0),
Some(dest_rect_0),
0.0,
None,
false,
false,
)?;
canvas.copy_ex(
&texture,
Some(source_rect_1),
Some(dest_rect_1),
0.0,
None,
true,
false,
)?;
canvas.copy_ex(
&texture,
Some(source_rect_2),
Some(dest_rect_2),
0.0,
None,
false,
false,
)?;
canvas.present();

std::thread::sleep(Duration::from_millis(100));
Expand Down
58 changes: 41 additions & 17 deletions examples/audio-capture-and-replay.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,12 @@ extern crate sdl2;

use sdl2::audio::{AudioCallback, AudioSpecDesired};
use sdl2::AudioSubsystem;
use std::time::Duration;
use std::sync::mpsc;
use std::i16;
use std::sync::mpsc;
use std::time::Duration;

const RECORDING_LENGTH_SECONDS: usize = 3;


struct Recording {
record_buffer: Vec<i16>,
pos: usize,
Expand All @@ -31,30 +30,45 @@ impl AudioCallback for Recording {
self.pos += 1;
if self.pos >= self.record_buffer.len() {
self.done = true;
self.done_sender.send(self.record_buffer.clone())
self.done_sender
.send(self.record_buffer.clone())
.expect("could not send record buffer");
break;
}
}
}
}

fn record(audio_subsystem: &AudioSubsystem, desired_spec: &AudioSpecDesired) -> Result<Vec<i16>, String> {
println!("Capturing {:} seconds... Please rock!", RECORDING_LENGTH_SECONDS);
fn record(
audio_subsystem: &AudioSubsystem,
desired_spec: &AudioSpecDesired,
) -> Result<Vec<i16>, String> {
println!(
"Capturing {:} seconds... Please rock!",
RECORDING_LENGTH_SECONDS
);

let (done_sender, done_receiver) = mpsc::channel();

let capture_device = audio_subsystem.open_capture(None, desired_spec, |spec| {
println!("Capture Spec = {:?}", spec);
Recording {
record_buffer: vec![0; spec.freq as usize * RECORDING_LENGTH_SECONDS * spec.channels as usize],
record_buffer: vec![
0;
spec.freq as usize
* RECORDING_LENGTH_SECONDS
* spec.channels as usize
],
pos: 0,
done_sender,
done: false
done: false,
}
})?;

println!("AudioDriver: {:?}", capture_device.subsystem().current_audio_driver());
println!(
"AudioDriver: {:?}",
capture_device.subsystem().current_audio_driver()
);
capture_device.resume();

// Wait until the recording is done.
Expand All @@ -69,7 +83,6 @@ fn record(audio_subsystem: &AudioSubsystem, desired_spec: &AudioSpecDesired) ->
Ok(recorded_vec)
}


/// Returns a percent value
fn calculate_average_volume(recorded_vec: &[i16]) -> f32 {
let sum: i64 = recorded_vec.iter().map(|&x| (x as i64).abs()).sum();
Expand All @@ -78,12 +91,14 @@ fn calculate_average_volume(recorded_vec: &[i16]) -> f32 {

/// Returns a percent value
fn calculate_max_volume(recorded_vec: &[i16]) -> f32 {
let max: i64 = recorded_vec.iter().map(|&x| (x as i64).abs()).max()
let max: i64 = recorded_vec
.iter()
.map(|&x| (x as i64).abs())
.max()
.expect("expected at least one value in recorded_vec");
(max as f32) / (i16::MAX as f32) * 100.0
}


struct SoundPlayback {
data: Vec<i16>,
pos: usize,
Expand All @@ -100,7 +115,11 @@ impl AudioCallback for SoundPlayback {
}
}

fn replay_recorded_vec(audio_subsystem: &AudioSubsystem, desired_spec: &AudioSpecDesired, recorded_vec: Vec<i16>) -> Result<(), String> {
fn replay_recorded_vec(
audio_subsystem: &AudioSubsystem,
desired_spec: &AudioSpecDesired,
recorded_vec: Vec<i16>,
) -> Result<(), String> {
println!("Playing...");

let playback_device = audio_subsystem.open_playback(None, desired_spec, |spec| {
Expand All @@ -120,21 +139,26 @@ fn replay_recorded_vec(audio_subsystem: &AudioSubsystem, desired_spec: &AudioSpe
Ok(())
}


fn main() -> Result<(), String> {
let sdl_context = sdl2::init()?;
let audio_subsystem = sdl_context.audio()?;

let desired_spec = AudioSpecDesired {
freq: None,
channels: None,
samples: None
samples: None,
};

let recorded_vec = record(&audio_subsystem, &desired_spec)?;

println!("Average Volume of your Recording = {:?}%", calculate_average_volume(&recorded_vec));
println!("Max Volume of your Recording = {:?}%", calculate_max_volume(&recorded_vec));
println!(
"Average Volume of your Recording = {:?}%",
calculate_average_volume(&recorded_vec)
);
println!(
"Max Volume of your Recording = {:?}%",
calculate_max_volume(&recorded_vec)
);

replay_recorded_vec(&audio_subsystem, &desired_spec, recorded_vec)?;

Expand Down
16 changes: 6 additions & 10 deletions examples/audio-queue-squarewave.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,11 @@ fn gen_wave(bytes_to_write: i32) -> Vec<i16> {
let mut result = Vec::new();

for x in 0..sample_count {
result.push(
if (x / period) % 2 == 0 {
tone_volume
}
else {
-tone_volume
}
);
result.push(if (x / period) % 2 == 0 {
tone_volume
} else {
-tone_volume
});
}
result
}
Expand All @@ -32,8 +29,7 @@ fn main() -> Result<(), String> {
freq: Some(48_000),
channels: Some(2),
// mono -
samples: Some(4)
// default sample size
samples: Some(4), // default sample size
};

let device = audio_subsystem.open_queue::<i16, _>(None, &desired_spec)?;
Expand Down
16 changes: 10 additions & 6 deletions examples/audio-squarewave.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use std::time::Duration;
struct SquareWave {
phase_inc: f32,
phase: f32,
volume: f32
volume: f32,
}

impl AudioCallback for SquareWave {
Expand All @@ -15,7 +15,11 @@ impl AudioCallback for SquareWave {
fn callback(&mut self, out: &mut [f32]) {
// Generate a square wave
for x in out.iter_mut() {
*x = if self.phase <= 0.5 { self.volume } else { -self.volume };
*x = if self.phase <= 0.5 {
self.volume
} else {
-self.volume
};
self.phase = (self.phase + self.phase_inc) % 1.0;
}
}
Expand All @@ -27,8 +31,8 @@ fn main() -> Result<(), String> {

let desired_spec = AudioSpecDesired {
freq: Some(44_100),
channels: Some(1), // mono
samples: None // default sample size
channels: Some(1), // mono
samples: None, // default sample size
};

let device = audio_subsystem.open_playback(None, &desired_spec, |spec| {
Expand All @@ -39,7 +43,7 @@ fn main() -> Result<(), String> {
SquareWave {
phase_inc: 440.0 / spec.freq as f32,
phase: 0.0,
volume: 0.25
volume: 0.25,
}
})?;

Expand All @@ -50,6 +54,6 @@ fn main() -> Result<(), String> {
std::thread::sleep(Duration::from_millis(2_000));

// Device is automatically closed when dropped

Ok(())
}
26 changes: 15 additions & 11 deletions examples/audio-wav.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
extern crate sdl2;

use sdl2::audio::{AudioCallback, AudioSpecDesired,AudioSpecWAV,AudioCVT};
use std::time::Duration;
use sdl2::audio::{AudioCVT, AudioCallback, AudioSpecDesired, AudioSpecWAV};
use std::borrow::Cow;
use std::path::{PathBuf, Path};
use std::path::{Path, PathBuf};
use std::time::Duration;

// NOTE: You probably want to investigate the
// mixer feature for real use cases.
Expand Down Expand Up @@ -39,27 +39,31 @@ impl AudioCallback for Sound {
}

fn main() -> Result<(), String> {
let wav_file : Cow<'static, Path> = match std::env::args().nth(1) {
let wav_file: Cow<'static, Path> = match std::env::args().nth(1) {
None => Cow::from(Path::new("./assets/sine.wav")),
Some(s) => Cow::from(PathBuf::from(s))
Some(s) => Cow::from(PathBuf::from(s)),
};
let sdl_context = sdl2::init()?;
let audio_subsystem = sdl_context.audio()?;

let desired_spec = AudioSpecDesired {
freq: Some(44_100),
channels: Some(1), // mono
samples: None // default
samples: None, // default
};

let device = audio_subsystem.open_playback(None, &desired_spec, |spec| {
let wav = AudioSpecWAV::load_wav(wav_file)
.expect("Could not load test WAV file");
let wav = AudioSpecWAV::load_wav(wav_file).expect("Could not load test WAV file");

let cvt = AudioCVT::new(
wav.format, wav.channels, wav.freq,
spec.format, spec.channels, spec.freq)
.expect("Could not convert WAV file");
wav.format,
wav.channels,
wav.freq,
spec.format,
spec.channels,
spec.freq,
)
.expect("Could not convert WAV file");

let data = cvt.convert(wav.buffer().to_vec());

Expand Down
Loading

0 comments on commit 7fd7ee4

Please sign in to comment.