use std::sync::{
atomic::{AtomicBool, AtomicI32, Ordering},
Arc, Mutex,
};
use hao_il2cpp_runtime::{Original, Result};
use crate::{bindings::CAMERA_FIRE_ON_POST_RENDER, Camera};
type Callback = Arc<dyn Fn() + Send + Sync>;
type RenderCallback = Arc<dyn Fn(Camera) + Send + Sync>;
static CALLBACKS: Mutex<Vec<Callback>> = Mutex::new(Vec::new());
static HOOKED: Mutex<bool> = Mutex::new(false);
static LAST_FRAME: AtomicI32 = AtomicI32::new(-1);
static RENDER_CALLBACKS: Mutex<Vec<RenderCallback>> = Mutex::new(Vec::new());
static RENDER_HOOKED: Mutex<bool> = Mutex::new(false);
static SHUTTING_DOWN: AtomicBool = AtomicBool::new(false);
pub fn is_shutting_down() -> bool {
SHUTTING_DOWN.load(Ordering::Relaxed)
}
pub fn shutdown() {
SHUTTING_DOWN.store(true, Ordering::Relaxed);
}
pub fn on_update(callback: impl Fn() + Send + Sync + 'static) -> Result<()> {
CALLBACKS
.lock()
.unwrap_or_else(|e| e.into_inner())
.push(Arc::new(callback));
let mut hooked = HOOKED.lock().unwrap_or_else(|e| e.into_inner());
if !*hooked {
let frame_count = crate::il2cpp()?
.class("UnityEngine.CoreModule", "UnityEngine", "Time")?
.method("get_frameCount", 0)?;
frame_count.hook(|original: Original<_, i32>| {
let frame = original.call(());
if SHUTTING_DOWN.load(Ordering::Relaxed) {
return frame;
}
if LAST_FRAME.swap(frame, Ordering::Relaxed) != frame {
let callbacks = CALLBACKS.lock().unwrap_or_else(|e| e.into_inner()).clone();
for callback in callbacks {
callback();
}
}
frame
})?;
*hooked = true;
tracing::debug!("watching for frame updates");
}
Ok(())
}
pub fn on_render(callback: impl Fn(Camera) + Send + Sync + 'static) -> Result<()> {
RENDER_CALLBACKS
.lock()
.unwrap_or_else(|e| e.into_inner())
.push(Arc::new(callback));
let mut hooked = RENDER_HOOKED.lock().unwrap_or_else(|e| e.into_inner());
if !*hooked {
CAMERA_FIRE_ON_POST_RENDER.method()?.hook(
|camera: Camera, original: Original<_, ()>| {
original.call((camera,));
if SHUTTING_DOWN.load(Ordering::Relaxed) {
return;
}
let callbacks = RENDER_CALLBACKS
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone();
for callback in callbacks {
callback(camera);
}
},
)?;
*hooked = true;
tracing::debug!("watching for camera renders");
}
Ok(())
}