use std::marker::PhantomData;
use crate::asset_id::{AppAssetId, IdU16};
use crate::core::CoreAudio;
pub struct AppContext<A: AppAssetId> {
pub audio: Audio<A>,
dims: (f64, f64),
cursor: (f64, f64),
close_requested: bool,
native_px: f64,
is_fullscreen: bool,
desires_fullscreen: bool,
cookie: Vec<u8>,
cookie_updated: bool,
}
impl<A: AppAssetId> AppContext<A> {
pub(crate) fn new(audio: CoreAudio, dims: (f64, f64), native_px: f64) -> AppContext<A> {
AppContext {
audio: Audio { core: audio, phantom: PhantomData },
dims,
cursor: (0., 0.),
close_requested: false,
native_px,
is_fullscreen: false,
desires_fullscreen: false,
cookie: Vec::new(),
cookie_updated: false,
}
}
pub(crate) fn set_cursor(&mut self, cursor: (f64, f64)) {
self.cursor = cursor;
self.bound_cursor();
}
pub(crate) fn set_dims(&mut self, dims: (f64, f64), native_px: f64) {
self.dims = dims;
self.native_px = native_px;
self.bound_cursor();
}
fn bound_cursor(&mut self) {
self.cursor = (
self.cursor.0.max(0.).min(self.dims.0),
self.cursor.1.max(0.).min(self.dims.1),
);
}
pub fn dims(&self) -> (f64, f64) { self.dims }
pub fn cursor(&self) -> (f64, f64) { self.cursor }
pub fn native_px(&self) -> f64 { self.native_px }
pub fn native_px_align(&self, x: f64, y: f64) -> (f64, f64) {
(
(x / self.native_px).round() * self.native_px,
(y / self.native_px).round() * self.native_px,
)
}
pub fn request_fullscreen(&mut self) { self.desires_fullscreen = true; }
pub fn cancel_fullscreen(&mut self) { self.desires_fullscreen = false; }
pub fn is_fullscreen(&self) -> bool { self.is_fullscreen }
pub(crate) fn desires_fullscreen(&self) -> bool { self.desires_fullscreen }
pub(crate) fn set_is_fullscreen(&mut self, is_fullscreen: bool) {
self.is_fullscreen = is_fullscreen;
self.desires_fullscreen = is_fullscreen;
}
pub fn close(&mut self) { self.close_requested = true; }
pub(crate) fn take_close_request(&mut self) -> bool {
let result = self.close_requested;
self.close_requested = false;
result
}
pub fn cookie(&self) -> &[u8] {
&self.cookie
}
pub fn set_cookie(&mut self, cookie: Vec<u8>) {
assert!(cookie.len() < 700);
if cookie != self.cookie {
self.cookie_updated = true;
self.cookie = cookie;
}
}
#[cfg(target_arch = "wasm32")]
pub(crate) fn take_cookie_updated_flag(&mut self) -> bool {
let was_updated = self.cookie_updated;
self.cookie_updated = false;
was_updated
}
#[cfg(target_arch = "wasm32")]
pub(crate) fn cookie_buffer(&mut self) -> &mut Vec<u8> {
&mut self.cookie
}
}
pub struct Audio<A: AppAssetId> { core: CoreAudio, phantom: PhantomData<A> }
impl<A: AppAssetId> Audio<A> {
pub fn play_sound(&mut self, sound: A::Sound) { self.core.play_sound(sound.id_u16()); }
pub fn play_music(&mut self, music: A::Music) { self.core.play_music(music.id_u16(), false); }
pub fn loop_music(&mut self, music: A::Music) { self.core.play_music(music.id_u16(), true); }
pub fn stop_music(&mut self) { self.core.stop_music(); }
}