lexsdl 0.3.0

A wrapper for SDL2 to abstract away annoying parts
// C
pub mod sys;
pub use sys::*;

pub mod types;
pub use types::*;

pub mod particle;
pub use particle::*;


/// Parameters for initializing lexsdl.
#[derive(Clone,PartialEq)]
pub struct LexSdlOptions {
	/// use vsync
	pub vsync: bool,
	/// [`None`] will let sdl decide what to do.
	pub hardware_acceleration: Option<bool>,
	/// fullscreen.
	pub fullscreen: bool,
	/// title of the window/program.
	pub title: String,
	/// size of the window where `x` is width and `y` height
	pub window_size: lexlib::Vec2,
	/// allow the window to be resizable.
	pub window_resizable: bool,
	/// use window decorations.
	pub window_decorations: bool,
}

impl Default for LexSdlOptions {
	fn default() -> Self {
		Self {
			vsync: true,
			hardware_acceleration: None,
			fullscreen: false,
			title: "lexSDL window".to_owned(),
			window_size: lexlib::Vec2::new(800,600),
			window_resizable: true,
			window_decorations: true,
		}
	}
}

/// Initializes lexsdl and internally sdl with the desired options.
pub fn init(options: &LexSdlOptions) -> Result<(),i32> {
	// initialize sdl
	unsafe {
		let err = LEXSDL_Init(0);
		if err != 0 {
			return Err(err);}
	}
	
	// initialize sdl_image
	unsafe {
		let err = LEXSDL_InitIMG(0);
		if err != 0 {
			return Err(err);}
	}
	
	unsafe {
		let mut window_flags = 0;
		if options.fullscreen {
			window_flags |= 0x00000001;}
		if !options.window_decorations {
			window_flags |= 0x00000010;}
			
		#[allow(temporary_cstring_as_ptr)] //this should be safe
		let err = LEXSDL_CreateWindowSized(std::ffi::CString::new(&*options.title).expect("invalid window title, does it contain a 0 byte?").as_ptr(), options.window_size.x,options.window_size.y, window_flags);
		
		if err.is_null() {
			return Err(-1);}
	}
	
	unsafe {
		let mut renderer_flags = 0;
		if options.vsync {
			renderer_flags |= 0x00000004;}
		match options.hardware_acceleration {
			Some(v)	=> if v {
					renderer_flags |= 0x00000002;
				} else {
					renderer_flags |= 0x00000001;
				}
			None => {}
		}
		
		let err = LEXSDL_CreateRenderer(renderer_flags);
		if err.is_null(){
			return Err(-2);}
	}
	
	Ok(())
}

/// quits LEXSDL and internally SDL.
pub fn quit(){
	unsafe{
		LEXSDL_Terminate();
		LEXSDL_Quit();
	}
}

/// run in a loop until [`LEXSDL_EventQuit`] is triggered.
pub fn run<F>(instructions: F) 
where F: Fn() {
	while unsafe {LEXSDL_EventQuit()} == 0 {
		unsafe {
			LEXSDL_HandleEvents();
			LEXSDL_NewFrame();
		}
	
		instructions();
	
		unsafe {
			LEXSDL_ShowFrame();
		}
	}
}