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
use std::{future::IntoFuture, sync::Arc};

use faithe::{internal::alloc_console, pattern::Pattern};
use once_cell::sync::OnceCell;
use thiserror::Error;
use tokio::{runtime::Runtime, task::JoinHandle};

use self::{
    hooks::Hooks, overlay::Overlay, scripting::ScriptHost, tracing::Profiler,
    vfs::VirtualFileSystem,
};

pub mod hooks;
pub mod overlay;
pub mod scripting;
pub mod tracing;
pub mod vfs;

#[derive(Debug, Error)]
pub enum FrameworkError {
    #[error("failed to assemble code")]
    CodeAssemblyFailed(#[from] dynasmrt::DynasmError),

    #[error("failed to patch code")]
    CodePatchingFailed(#[from] detour::Error),

    #[error("internal I/O error")]
    IoError(#[from] std::io::Error),

    #[error("no matches found for '{}' with pattern '{:?}'", identifier, pattern)]
    NoMatchesFound {
        identifier: &'static str,
        pattern: Pattern,
    },

    #[error("unable to resolve symbol '{}'", 0)]
    NoSymbolFound(&'static str),

    #[error("failed to execute pattern scan")]
    PatternScanningFailed(#[from] faithe::FaitheError),

    #[error("a lua error occurred")]
    ScriptingError(#[from] mlua::Error),
}

pub struct FrameworkBuilder {
    debug_console: bool,
}

impl Default for FrameworkBuilder {
    fn default() -> Self {
        Self {
            debug_console: true,
        }
    }
}

impl FrameworkBuilder {
    pub fn debug_console(self, new_value: bool) -> Self {
        Self {
            debug_console: new_value,
        }
    }

    pub fn build(self) -> Result<Me3, FrameworkError> {
        Ok(Arc::new(Framework::setup_framework(self)?))
    }
}

pub type Me3 = std::sync::Arc<Framework>;

pub struct Framework {
    hooks: &'static Hooks,
    overlay: &'static Overlay,
    profiler: &'static Profiler,
    script_host: &'static ScriptHost,
    scheduler: Runtime,
    vfs: &'static VirtualFileSystem,
}

pub trait FrameworkGlobal: Sync + Send + Sized {
    fn cell() -> &'static OnceCell<Self>;
    fn create() -> Result<Self, FrameworkError>;

    fn get_or_create() -> Result<&'static Self, FrameworkError> {
        Self::cell().get_or_try_init(|| Self::create())
    }

    /// # Safety
    ///
    /// It is only safe to retrieve a [FrameworkGlobal] after it has been initialized
    /// via [FrameworkGlobal::get_or_create].
    unsafe fn get_unchecked() -> &'static Self {
        Self::cell().get_unchecked()
    }
}

impl Framework {
    pub fn setup_framework(builder: FrameworkBuilder) -> Result<Self, FrameworkError> {
        if builder.debug_console {
            let _ = alloc_console();
        }

        fern::Dispatch::new()
            .format(move |out, message, record| {
                out.finish(format_args!(
                    "{}[{}] {}",
                    chrono::Local::now().format("[%H:%M:%S]"),
                    record.level(),
                    message
                ))
            })
            .level(log::LevelFilter::Debug)
            .chain(std::io::stdout())
            .chain(fern::log_file("me3.log")?)
            .apply()
            .unwrap_or_else(|_| println!("unable to setup logging system"));

        let hooks = Hooks::get_or_create()?;
        let overlay = Overlay::get_or_create()?;
        let profiler = Profiler::get_or_create()?;
        let script_host = ScriptHost::get_or_create()?;
        let scheduler = Runtime::new()?;
        let vfs = VirtualFileSystem::get_or_create()?;

        Ok(Self {
            hooks,
            overlay,
            profiler,
            script_host,
            scheduler,
            vfs,
        })
    }

    pub fn get_hooks(&self) -> &'static hooks::Hooks {
        self.hooks
    }

    pub fn get_overlay(&self) -> &'static overlay::Overlay {
        self.overlay
    }

    pub fn get_profiler(&self) -> &'static tracing::Profiler {
        self.profiler
    }

    pub fn get_script_host(&self) -> &'static scripting::ScriptHost {
        self.script_host
    }

    pub fn get_vfs(&self) -> &'static vfs::VirtualFileSystem {
        self.vfs
    }

    pub fn spawn<F>(&self, future: F) -> JoinHandle<<F as IntoFuture>::Output>
    where
        F: IntoFuture,
        F::IntoFuture: Send + Sync + 'static,
        F::Output: Send + Sync + 'static,
    {
        self.scheduler.spawn(future.into_future())
    }

    pub fn run_until_shutdown(&self) {
        self.scheduler.block_on(async move {
            loop {
                tokio::task::yield_now().await;
            }
        });
    }
}

#[cfg(test)]
mod test {
    use super::*;

    fn assert_send<T: Send>() {}
    fn assert_sync<T: Sync>() {}

    #[test]
    fn framework_is_thread_safe() {
        assert_send::<Framework>();
        assert_sync::<Framework>();
    }
}