1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
#![cfg_attr(all(target_arch = "arm", target_os = "none"), no_std)]

extern crate alloc;
extern crate playdate_rs_sys as sys;

#[macro_use]
#[doc(hidden)]
pub mod print;

pub mod display;
pub mod error;
pub mod fs;
pub mod graphics;
pub mod lua;
pub mod math;
mod memory;
pub mod scoreboards;
pub mod sound;
pub mod sprite;
pub mod system;
pub mod util;
pub mod video;

use alloc::{boxed::Box, format};
pub use no_std_io::io;
pub use playdate_rs_macros::app;

pub struct Playdate {
    raw_api: *mut sys::PlaydateAPI,
    /// System interaction
    pub system: system::PlaydateSystem,
    /// Filesystem operations
    pub file: fs::PlaydateFileSystem,
    /// Graphics operations and drawing functions
    pub graphics: graphics::PlaydateGraphics,
    /// Sprite and global sprite display list operations
    pub sprite: sprite::PlaydateSprite,
    /// Display operations and management
    pub display: display::PlaydateDisplay,
    /// Sound controls
    pub sound: sound::PlaydateSound,
    /// Scoreboard operations (unimplemented)
    pub scoreboards: scoreboards::PlaydateScoreboards,
    /// Lua VM interactions (unimplemented)
    pub lua: lua::Lua,
    // The playdate JSON lib is not supported. Please use serde instead:
    // pub json: *const playdate_json,
}

unsafe impl Sync for Playdate {}
unsafe impl Send for Playdate {}

impl Playdate {
    fn new(playdate: *mut sys::PlaydateAPI) -> Self {
        let playdate_ref = unsafe { &*playdate };
        Self {
            raw_api: playdate,
            system: system::PlaydateSystem::new(playdate_ref.system),
            file: fs::PlaydateFileSystem::new(playdate_ref.file),
            graphics: graphics::PlaydateGraphics::new(playdate_ref.graphics),
            sprite: sprite::PlaydateSprite::new(playdate_ref.sprite),
            display: display::PlaydateDisplay::new(playdate_ref.display),
            sound: sound::PlaydateSound::new(playdate_ref.sound),
            scoreboards: scoreboards::PlaydateScoreboards::new(playdate_ref.scoreboards),
            lua: lua::Lua::new(playdate_ref.lua),
        }
    }

    /// Returns a raw pointer to the raw playdate-rs-sys API.
    pub fn get_raw_api(&self) -> *mut sys::PlaydateAPI {
        self.raw_api
    }
}

static INIT: spin::Once = spin::Once::new();

static mut PLAYDATE_PTR: *mut sys::PlaydateAPI = core::ptr::null_mut();

pub static PLAYDATE: spin::Lazy<Playdate> =
    spin::Lazy::new(|| Playdate::new(unsafe { PLAYDATE_PTR }));

pub trait App: Sized + 'static {
    /// Constructor for the app. This is called once when the app is loaded.
    fn new() -> Self;

    /// Returns a reference to the app singleton.
    fn get() -> &'static mut Self {
        unsafe { &mut *(APP.unwrap() as *mut Self) }
    }

    /// Called once when the app is loaded.
    fn init(&mut self) {}

    /// Called once per frame.
    ///
    /// `delta` is the time in seconds since the last frame.
    fn update(&mut self, _delta: f32) {}

    /// Called when a system event occurs.
    fn handle_event(&mut self, _event: system::SystemEvent, _arg: u32) {}
}

static mut APP: Option<*mut ()> = None;

unsafe extern "C" fn update<T: App>(_: *mut core::ffi::c_void) -> i32 {
    let app = T::get();
    // calculate delta time since last frame
    let delta_time = {
        static mut LAST_FRAME_TIME: Option<usize> = None;
        let current_time = PLAYDATE.system.get_current_time_milliseconds();
        let delta = if let Some(last_frame_time) = LAST_FRAME_TIME {
            (current_time - last_frame_time) as f32 / 1000.0
        } else {
            0.0
        };
        LAST_FRAME_TIME = Some(current_time);
        delta
    };
    // update frame
    app.update(delta_time);
    1
}

fn start_playdate_app<T: App>(pd: *mut sys::PlaydateAPI) {
    // Initialize playdate singleton
    INIT.call_once(|| unsafe {
        PLAYDATE_PTR = pd;
        spin::Lazy::force(&PLAYDATE);
    });
    // Create app instance
    let app = Box::leak(Box::new(T::new()));
    unsafe {
        APP = Some(app as *mut T as *mut ());
    }
    // Initialize app
    app.init();
    PLAYDATE.system.set_update_callback(Some(update::<T>));
}

#[doc(hidden)]
pub fn __playdate_handle_event<T: App>(
    pd: *mut ::core::ffi::c_void,
    event: system::SystemEvent,
    arg: u32,
) {
    let pd = pd as *mut sys::PlaydateAPI;
    if event == system::SystemEvent::kEventInit {
        start_playdate_app::<T>(pd);
    }
    T::get().handle_event(event, arg);
}

#[doc(hidden)]
pub fn __playdate_handle_panic(info: &core::panic::PanicInfo) -> ! {
    PLAYDATE.system.error(format!("{}", info));
    loop {
        unreachable!()
    }
}

#[macro_export]
macro_rules! register_playdate_app {
    ($app: ident) => {
        mod __playdate_api {
            #[no_mangle]
            unsafe extern "C" fn eventHandler(
                pd: *mut ::core::ffi::c_void,
                event: $crate::system::SystemEvent,
                arg: u32,
            ) {
                $crate::__playdate_handle_event::<super::$app>(pd, event, arg);
            }
        }
        #[cfg(all(target_arch = "arm", target_os = "none"))]
        #[panic_handler]
        #[doc(hidden)]
        fn __panic_handler(info: &core::panic::PanicInfo) -> ! {
            $crate::__playdate_handle_panic(info);
        }

        #[cfg(all(target_arch = "arm", target_os = "none"))]
        #[no_mangle]
        extern "C" fn _exit() {}

        #[cfg(all(target_arch = "arm", target_os = "none"))]
        #[no_mangle]
        extern "C" fn _kill() {}

        #[cfg(all(target_arch = "arm", target_os = "none"))]
        #[no_mangle]
        extern "C" fn _getpid() {}

        #[cfg(all(target_arch = "arm", target_os = "none"))]
        #[no_mangle]
        extern "C" fn __exidx_start() {
            unimplemented!();
        }

        #[cfg(all(target_arch = "arm", target_os = "none"))]
        #[no_mangle]
        extern "C" fn __exidx_end() {
            unimplemented!();
        }
    };
}