#[cfg(not(target_arch = "wasm32"))]
use std::path::Path;
use std::{
env,
thread::sleep,
time::{Duration, Instant},
};
#[cfg(target_os = "macos")]
use std::{
ffi::c_void,
ptr::{null, null_mut},
sync::atomic::{AtomicBool, Ordering},
};
#[cfg(target_os = "macos")]
use euv::PlatformKind;
#[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
use euv_automation::{AiAppHooks, AiSchemaProtocol, DEV_AI_INSPECTOR_ADDR, DevAutomationBridge};
#[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
use euv_example::{
ENV_AI_INSPECTOR_ADDR, FLAG_AI_QUERY, FLAG_AI_SCHEMA, FLAG_AI_URI, dispatch_automation_uri,
};
#[cfg(not(target_arch = "wasm32"))]
use euv_example::{FLAG_CAPTURE_DIR, capture_showcase_screenshots};
#[cfg(target_os = "macos")]
use euv_example::{MACOS_CF_STRING_ENCODING_UTF8, MACOS_EVENT_TRACKING_RUN_LOOP_MODE};
use {
euv::{
AdaptiveFrameMetrics, AdaptiveRouterSnapshot, App, FrameStats, MIN_REFRESH_RATE_HZ,
PlatformError, Rect, RenderMode, is_frame_needed,
},
euv_example::{
FLAG_HARDWARE, FLAG_HEADLESS, FLAG_HYBRID, FLAG_INTERACTIVE, FLAG_SOFTWARE,
ShowcaseAdaptiveSyncKey, ShowcaseState, create_showcase_app, run_headless_smoke,
showcase_has_active_game_viewport, sync_showcase_adaptive_if_changed,
},
};
const MAIN_MAX_REFRESH_RATE_HZ: f32 = 1000.0;
#[cfg(target_os = "macos")]
#[repr(C)]
struct MainCfRunLoopTimerContext {
version: isize,
info: *mut c_void,
retain: *const c_void,
release: *const c_void,
copy_description: *const c_void,
}
#[cfg(target_os = "macos")]
struct MainMacosLiveResizeState {
app_ptr: *mut App,
in_step: AtomicBool,
}
#[cfg(target_os = "macos")]
#[link(name = "CoreFoundation", kind = "framework")]
unsafe extern "C" {
fn CFAbsoluteTimeGetCurrent() -> f64;
fn CFRunLoopGetCurrent() -> *mut c_void;
fn CFStringCreateWithBytes(
alloc: *const c_void,
bytes: *const u8,
num_bytes: isize,
encoding: u32,
is_external_representation: u8,
) -> *const c_void;
fn CFRunLoopTimerCreate(
allocator: *const c_void,
fire_date: f64,
interval: f64,
flags: u64,
order: isize,
callout: unsafe extern "C" fn(*mut c_void, *mut c_void),
context: *mut MainCfRunLoopTimerContext,
) -> *mut c_void;
fn CFRunLoopAddTimer(rl: *mut c_void, timer: *mut c_void, mode: *const c_void);
fn CFRunLoopTimerInvalidate(timer: *mut c_void);
fn CFRelease(cf: *const c_void);
}
#[cfg(target_os = "macos")]
unsafe extern "C" fn macos_live_resize_callout(_timer: *mut c_void, info: *mut c_void) {
if info.is_null() {
return;
}
let resize_state: &MainMacosLiveResizeState =
unsafe { &*info.cast::<MainMacosLiveResizeState>() };
if resize_state
.in_step
.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
.is_err()
{
return;
}
if !resize_state.app_ptr.is_null() {
let app: &mut App = unsafe { &mut *resize_state.app_ptr };
if app.should_pump_frames() {
let _: Result<FrameStats, PlatformError> = app.step_frame();
}
}
resize_state.in_step.store(false, Ordering::Release);
}
#[cfg(target_os = "macos")]
fn macos_install_tracking_resize_timer(
refresh_hz: f32,
state_ptr: *mut MainMacosLiveResizeState,
) -> *mut c_void {
let interval: f64 =
1.0 / f64::from(refresh_hz.clamp(MIN_REFRESH_RATE_HZ, MAIN_MAX_REFRESH_RATE_HZ));
let mut ctx: MainCfRunLoopTimerContext = MainCfRunLoopTimerContext {
version: 0,
info: state_ptr.cast::<c_void>(),
retain: null(),
release: null(),
copy_description: null(),
};
let mode_bytes: &[u8] = MACOS_EVENT_TRACKING_RUN_LOOP_MODE.as_bytes();
unsafe {
let fire_date: f64 = CFAbsoluteTimeGetCurrent() + interval;
let timer: *mut c_void = CFRunLoopTimerCreate(
null(),
fire_date,
interval,
0,
0,
macos_live_resize_callout,
&mut ctx,
);
if timer.is_null() {
return null_mut();
}
let rl: *mut c_void = CFRunLoopGetCurrent();
let mode_cf: *const c_void = CFStringCreateWithBytes(
null(),
mode_bytes.as_ptr(),
mode_bytes.len() as isize,
MACOS_CF_STRING_ENCODING_UTF8,
0,
);
if !rl.is_null() && !mode_cf.is_null() {
CFRunLoopAddTimer(rl, timer, mode_cf);
}
if !mode_cf.is_null() {
CFRelease(mode_cf);
}
timer
}
}
#[cfg(target_os = "macos")]
fn macos_remove_tracking_resize_timer(timer: *mut c_void) {
if timer.is_null() {
return;
}
unsafe {
CFRunLoopTimerInvalidate(timer);
CFRelease(timer.cast_const());
}
}
fn run_interactive_showcase(app: &mut App, state: &ShowcaseState) -> FrameStats {
#[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
let explicit_bridge_env: bool = env::var(ENV_AI_INSPECTOR_ADDR)
.ok()
.is_some_and(|text_value: String| !text_value.trim().is_empty());
#[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
let mut dev_bridge: DevAutomationBridge = {
let bind_addr: String = env::var(ENV_AI_INSPECTOR_ADDR)
.ok()
.filter(|text_value: &String| !text_value.trim().is_empty())
.unwrap_or_else(|| DEV_AI_INSPECTOR_ADDR.to_string());
DevAutomationBridge::start(&bind_addr).with_hooks(state.build_ai_hooks())
};
#[cfg(target_os = "macos")]
let mut live_resize_state: MainMacosLiveResizeState = MainMacosLiveResizeState {
app_ptr: app as *mut App,
in_step: AtomicBool::new(false),
};
#[cfg(target_os = "macos")]
let live_resize_timer: *mut c_void = if app.platform_kind() == PlatformKind::MacOs {
macos_install_tracking_resize_timer(app.display_refresh_rate_hz(), &mut live_resize_state)
} else {
null_mut()
};
let mut last_stats: FrameStats = FrameStats::default();
let mut last_sync_key: Option<ShowcaseAdaptiveSyncKey> = None;
let mut active_game_bounds: Vec<Rect> = Vec::new();
let mut prev_tick: Instant = Instant::now();
let mut next_deadline: Instant = prev_tick;
let mut rendered_initial_frame: bool = false;
while app.get_running() {
let async_loaded: bool = state.poll_async_loads();
let has_game: bool = showcase_has_active_game_viewport(app, state, &mut active_game_bounds);
#[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
let bridge_requires_poll: bool = explicit_bridge_env;
#[cfg(not(all(debug_assertions, not(target_arch = "wasm32"))))]
let bridge_requires_poll: bool = false;
let idle_sleep: bool = !app.should_pump_frames()
|| (rendered_initial_frame
&& app.is_idle()
&& !app.has_active_animations()
&& !is_frame_needed()
&& !async_loaded
&& !has_game
&& !bridge_requires_poll);
if idle_sleep {
let wait_result: Result<FrameStats, PlatformError> = app.wait_background_events();
match wait_result {
Ok(stats) => {
let _: bool = sync_showcase_adaptive_if_changed(state, app, &mut last_sync_key);
last_stats = stats;
}
Err(err) => {
eprintln!("{err}");
break;
}
}
let resume_now: Instant = Instant::now();
prev_tick = resume_now;
next_deadline = resume_now;
continue;
}
let frame_start: Instant = Instant::now();
let dt: f32 = frame_start
.duration_since(prev_tick)
.as_secs_f32()
.clamp(1.0 / MAIN_MAX_REFRESH_RATE_HZ, 0.05);
prev_tick = frame_start;
#[cfg(target_os = "macos")]
live_resize_state.in_step.store(true, Ordering::Release);
let step_result: Result<FrameStats, PlatformError> = app.step_game_frame(dt);
#[cfg(target_os = "macos")]
live_resize_state.in_step.store(false, Ordering::Release);
match step_result {
Ok(stats) => {
rendered_initial_frame = true;
let _: bool = sync_showcase_adaptive_if_changed(state, app, &mut last_sync_key);
last_stats = stats;
}
Err(err) => {
eprintln!("{err}");
break;
}
}
#[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
{
let _: usize = dev_bridge.poll(app);
}
let native_hz: f64 = f64::from(
app.display_refresh_rate_hz()
.clamp(MIN_REFRESH_RATE_HZ, MAIN_MAX_REFRESH_RATE_HZ),
);
let target_hz: f64 = app
.fps_limit()
.map(|fps: u32| f64::from(fps.max(1)))
.unwrap_or(native_hz);
let target: Duration = Duration::from_secs_f64(1.0 / target_hz);
next_deadline = next_deadline.checked_add(target).unwrap_or(frame_start);
let now: Instant = Instant::now();
if now >= next_deadline {
if now.duration_since(next_deadline) > target {
next_deadline = now;
}
} else {
let remaining: Duration = next_deadline.duration_since(now);
sleep(remaining);
}
}
#[cfg(target_os = "macos")]
macos_remove_tracking_resize_timer(live_resize_timer);
last_stats
}
fn main() {
let args: Vec<String> = env::args().collect();
#[cfg(not(target_arch = "wasm32"))]
if let Some(pos) = args.iter().position(|arg: &String| arg == FLAG_CAPTURE_DIR)
&& let Some(dir) = args.get(pos + 1)
{
match capture_showcase_screenshots(Path::new(dir)) {
Ok(item_count) => println!("captured={item_count} dir={dir}"),
Err(err) => eprintln!("{err}"),
}
return;
}
#[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
if args.iter().any(|arg: &String| arg == FLAG_AI_SCHEMA) {
if let Ok((mut app, state)) = create_showcase_app(true, RenderMode::Software) {
drop(app.step_frame());
let hooks: AiAppHooks = state.build_ai_hooks();
println!(
"{}",
AiSchemaProtocol::snapshot_pretty_json_with_hooks(&app, Some(&hooks))
);
}
return;
}
#[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
if let Some(pos) = args.iter().position(|arg: &String| arg == FLAG_AI_QUERY)
&& let Some(query_json) = args.get(pos + 1)
{
if let Ok((mut app, state)) = create_showcase_app(true, RenderMode::Software) {
drop(app.step_frame());
let hooks: AiAppHooks = state.build_ai_hooks();
println!(
"{}",
AiSchemaProtocol::handle_json_with_hooks(&mut app, query_json, Some(&hooks))
);
}
return;
}
#[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
if let Some(pos) = args.iter().position(|arg: &String| arg == FLAG_AI_URI)
&& let Some(uri) = args.get(pos + 1)
{
if let Ok((mut app, state)) = create_showcase_app(true, RenderMode::Software) {
drop(app.step_frame());
if let Some(out) = dispatch_automation_uri(&mut app, &state, uri) {
println!("{out}");
}
}
return;
}
let headless: bool = args.iter().any(|arg: &String| arg == FLAG_HEADLESS);
let interactive: bool = args.iter().any(|arg: &String| arg == FLAG_INTERACTIVE);
let mode: RenderMode = if args.iter().any(|arg: &String| arg == FLAG_SOFTWARE) {
RenderMode::Software
} else if args.iter().any(|arg: &String| arg == FLAG_HARDWARE) {
RenderMode::Hardware
} else if args.iter().any(|arg: &String| arg == FLAG_HYBRID) {
RenderMode::Hybrid
} else {
RenderMode::Auto
};
if headless {
match run_headless_smoke(mode) {
Ok(stats) => {
print_stats(&stats);
}
Err(err) => {
eprintln!("{err}");
}
}
} else {
match create_showcase_app(false, mode) {
Ok((mut app, state)) => {
if interactive {
let last_stats: FrameStats = run_interactive_showcase(&mut app, &state);
print_stats(&last_stats);
} else if let Ok(stats) = app.run_frames(Some(1)) {
state.sync_adaptive_from_app(&mut app);
let snap: AdaptiveRouterSnapshot = app.adaptive_router_snapshot();
let metrics: AdaptiveFrameMetrics = app.adaptive_frame_metrics();
println!(
"backend={:?} adaptive_candidate={:?} cpu_mirror={} upload={:?} draw_commands={} draw_batches={} layout_nodes={} frame_hash={:#018x}",
stats.get_active_backend(),
snap.get_active_candidate(),
metrics.get_cpu_mirror_active(),
metrics.get_upload_strategy(),
stats.get_draw_commands(),
stats.get_draw_batches(),
stats.get_layout_nodes(),
stats.get_frame_hash()
);
}
}
Err(err) => {
eprintln!("{err}");
}
}
}
}
fn print_stats(stats: &FrameStats) {
println!(
"backend={:?} draw_commands={} draw_batches={} layout_nodes={} frame_hash={:#018x}",
stats.get_active_backend(),
stats.get_draw_commands(),
stats.get_draw_batches(),
stats.get_layout_nodes(),
stats.get_frame_hash()
);
}