use std::vec::Vec;
use crate::arena::SmallVec;
use crate::display::Rgba8888;
use crate::engine::VeloxEngine;
use crate::platform::testing::TestingPlatform;
use crate::pod::InputEvent;
use crate::pod::SafeAreaInsets;
use crate::solver::Region;
#[repr(u8)]
#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
pub enum MobileOs {
#[default]
Android = 0,
Ios = 1,
HarmonyOs = 2,
}
impl MobileOs {
#[inline(always)]
pub const fn name(self) -> &'static str {
match self {
Self::Android => "Android",
Self::Ios => "iOS",
Self::HarmonyOs => "HarmonyOS NEXT",
}
}
#[inline(always)]
pub const fn gpu_api_name(self) -> &'static str {
match self {
Self::Android | Self::HarmonyOs => "Vulkan",
Self::Ios => "Metal",
}
}
#[inline(always)]
pub const fn default_safe_area(self, orientation: DeviceOrientation) -> SafeAreaInsets {
let is_portrait = matches!(
orientation,
DeviceOrientation::Portrait | DeviceOrientation::PortraitUpsideDown
);
match (self, is_portrait) {
(Self::Android, true) => SafeAreaInsets::android_portrait(),
(Self::Android, false) => SafeAreaInsets::android_landscape(),
(Self::Ios, true) => SafeAreaInsets::ios_portrait(),
(Self::Ios, false) => SafeAreaInsets::ios_landscape(),
(Self::HarmonyOs, true) => SafeAreaInsets::harmony_portrait(),
(Self::HarmonyOs, false) => SafeAreaInsets::harmony_landscape(),
}
}
}
#[repr(u8)]
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum TouchPhase {
Began = 0,
Moved = 1,
Ended = 2,
Cancelled = 3,
}
impl TouchPhase {
#[inline(always)]
pub const fn from_android_action(action: u8) -> Self {
match action {
0 => Self::Began,
1 => Self::Ended,
2 => Self::Moved,
_ => Self::Cancelled,
}
}
#[inline(always)]
pub const fn from_ios_phase(phase: u8) -> Self {
match phase {
0 => Self::Began,
1 | 2 => Self::Moved,
3 => Self::Ended,
_ => Self::Cancelled,
}
}
#[inline(always)]
pub const fn from_harmony_touch_type(touch_type: u8) -> Self {
match touch_type {
0 => Self::Began,
1 => Self::Ended,
2 => Self::Moved,
_ => Self::Cancelled,
}
}
}
#[repr(u8)]
#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
pub enum DeviceOrientation {
#[default]
Portrait = 0,
LandscapeLeft = 1,
LandscapeRight = 2,
PortraitUpsideDown = 3,
}
#[repr(C)]
#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
pub struct CDirtyRect {
pub x: i16,
pub y: i16,
pub w: i16,
pub h: i16,
}
pub type MobilePlatform<const W: usize = 240, const H: usize = 360> =
TestingPlatform<W, H, Rgba8888>;
pub struct MobileEmbedApp {
pub engine: VeloxEngine,
os: MobileOs,
width: i16,
height: i16,
dpi_scale: i16,
orientation: DeviceOrientation,
backend: super::DesktopRenderBackend,
framebuffer: Vec<Rgba8888>,
dirty_rects: Vec<CDirtyRect>,
active_touch_id: Option<u32>,
#[cfg(feature = "gpu")]
gpu_offscreen: Option<crate::renderers::wgpu::WgpuOffscreenRenderer>,
#[cfg(feature = "gpu")]
gpu_window: Option<crate::renderers::wgpu::WgpuWindowRenderer>,
}
impl MobileEmbedApp {
pub fn new(width: i16, height: i16, safe_area: SafeAreaInsets) -> Self {
Self::new_for_os(MobileOs::Android, width, height, safe_area)
}
pub fn new_for_os(os: MobileOs, width: i16, height: i16, safe_area: SafeAreaInsets) -> Self {
let w = width.max(1);
let h = height.max(1);
let mut engine = VeloxEngine::new(w, h);
engine.set_safe_area(safe_area);
Self {
engine,
os,
width: w,
height: h,
dpi_scale: 1,
orientation: DeviceOrientation::Portrait,
backend: super::DesktopRenderBackend::default_desktop(),
framebuffer: Vec::new(),
dirty_rects: Vec::with_capacity(8),
active_touch_id: None,
#[cfg(feature = "gpu")]
gpu_offscreen: None,
#[cfg(feature = "gpu")]
gpu_window: None,
}
}
#[inline]
pub fn new_android(width: i16, height: i16) -> Self {
Self::new_for_os(
MobileOs::Android,
width,
height,
SafeAreaInsets::android_portrait(),
)
}
#[inline]
pub fn new_ios(width: i16, height: i16) -> Self {
Self::new_for_os(MobileOs::Ios, width, height, SafeAreaInsets::ios_portrait())
}
#[inline]
pub fn new_harmony(width: i16, height: i16) -> Self {
Self::new_for_os(
MobileOs::HarmonyOs,
width,
height,
SafeAreaInsets::harmony_portrait(),
)
}
#[inline]
pub const fn with_os(mut self, os: MobileOs) -> Self {
self.os = os;
self
}
#[inline(always)]
pub const fn os(&self) -> MobileOs {
self.os
}
#[inline]
pub fn with_backend(mut self, backend: super::DesktopRenderBackend) -> Self {
self.backend = backend;
self
}
#[inline]
pub fn set_backend(&mut self, backend: super::DesktopRenderBackend) {
self.backend = backend;
}
#[inline(always)]
pub const fn backend(&self) -> super::DesktopRenderBackend {
self.backend
}
#[inline(always)]
pub const fn orientation(&self) -> DeviceOrientation {
self.orientation
}
pub fn set_orientation(&mut self, orientation: DeviceOrientation) {
self.orientation = orientation;
let insets = self.os.default_safe_area(orientation);
self.engine.set_safe_area(insets);
}
#[cfg(feature = "gpu")]
#[inline]
pub fn gpu_scene(&self) -> Option<&crate::renderers::wgpu::WgpuScene> {
self.gpu_offscreen.as_ref().map(|r| &r.scene)
}
#[cfg(feature = "gpu")]
pub fn attach_gpu_window<T>(&mut self, window_handle: T) -> bool
where
T: Into<crate::renderers::wgpu::wgpu::SurfaceTarget<'static>> + Clone,
{
let pw = self.physical_width().max(1) as u32;
let ph = self.physical_height().max(1) as u32;
self.gpu_window = crate::renderers::wgpu::WgpuWindowRenderer::new(window_handle, pw, ph);
if self.gpu_window.is_some() {
self.framebuffer = Vec::new();
self.gpu_offscreen = None;
true
} else {
false
}
}
#[cfg(feature = "gpu")]
pub fn detach_gpu_window(&mut self) {
self.gpu_window = None;
}
pub fn trim_memory(&mut self) {
self.framebuffer = Vec::new();
self.engine.resize(self.width, self.height);
#[cfg(feature = "gpu")]
{
if let Some(off) = &mut self.gpu_offscreen {
off.trim_cpu_buffers();
off.trim_gpu_memory();
}
if let Some(win) = &mut self.gpu_window {
win.trim_gpu_memory();
}
}
}
#[inline]
pub fn cpu_framebuffer_bytes(&self) -> usize {
self.framebuffer.capacity() * core::mem::size_of::<Rgba8888>()
}
#[inline]
pub fn cpu_memory_bytes(&self) -> usize {
#[allow(unused_mut)]
let mut total = self.cpu_framebuffer_bytes();
#[cfg(feature = "gpu")]
if let Some(off) = &self.gpu_offscreen {
total = total.saturating_add(off.cpu_memory_bytes());
}
total
}
fn ensure_cpu_framebuffer(&mut self) {
let pw = self.physical_width().max(1) as usize;
let ph = self.physical_height().max(1) as usize;
let needed = pw.saturating_mul(ph);
if self.framebuffer.len() != needed {
self.framebuffer.resize(needed, Rgba8888(0));
}
}
#[cfg(feature = "gpu")]
#[inline]
pub fn has_active_gpu_window(&self) -> bool {
self.gpu_window.is_some()
}
#[cfg(not(feature = "gpu"))]
#[inline]
pub const fn has_active_gpu_window(&self) -> bool {
false
}
pub fn set_dpi_scale(&mut self, scale: i16) {
let s = scale.max(1);
if s != self.dpi_scale {
self.dpi_scale = s;
self.engine.set_dpi_scale(s);
let pw = (self.width as usize) * (s as usize);
let ph = (self.height as usize) * (s as usize);
if !self.framebuffer.is_empty() && !self.has_active_gpu_window() {
self.framebuffer.resize(pw * ph, Rgba8888(0));
}
#[cfg(feature = "gpu")]
if let Some(gpu_win) = &mut self.gpu_window {
gpu_win.resize(pw.max(1) as u32, ph.max(1) as u32);
}
self.engine.resize(self.width, self.height);
}
}
#[inline(always)]
pub const fn dpi_scale(&self) -> i16 {
self.dpi_scale
}
#[inline(always)]
pub const fn physical_width(&self) -> i16 {
self.width.saturating_mul(self.dpi_scale)
}
#[inline(always)]
pub const fn physical_height(&self) -> i16 {
self.height.saturating_mul(self.dpi_scale)
}
pub fn resize(&mut self, width: i16, height: i16) {
let w = width.max(1);
let h = height.max(1);
if w != self.width || h != self.height {
self.width = w;
self.height = h;
let pw = (w as usize) * (self.dpi_scale as usize);
let ph = (h as usize) * (self.dpi_scale as usize);
if !self.framebuffer.is_empty() && !self.has_active_gpu_window() {
self.framebuffer.resize(pw * ph, Rgba8888(0));
}
#[cfg(feature = "gpu")]
if let Some(gpu_win) = &mut self.gpu_window {
gpu_win.resize(pw.max(1) as u32, ph.max(1) as u32);
}
self.engine.resize(w, h);
}
}
pub fn push_touch(&mut self, touch_id: u32, phase: TouchPhase, x: i16, y: i16) {
match phase {
TouchPhase::Began => {
if self.active_touch_id.is_none() {
self.active_touch_id = Some(touch_id);
self.engine.dispatch_touch_down(x, y);
}
}
TouchPhase::Moved => {
if self.active_touch_id == Some(touch_id) {
self.engine.dispatch_event(InputEvent::PointerMove { x, y });
}
}
TouchPhase::Ended => {
if self.active_touch_id == Some(touch_id) {
self.active_touch_id = None;
self.engine.dispatch_event(InputEvent::PointerUp { x, y });
}
}
TouchPhase::Cancelled => {
if self.active_touch_id == Some(touch_id) {
self.active_touch_id = None;
self.engine.dispatch_event(InputEvent::PointerCancel);
}
}
}
}
pub fn handle_back(&mut self) -> bool {
self.engine.dispatch_navigate_back()
}
pub fn set_safe_area(&mut self, safe_area: SafeAreaInsets) {
self.engine.set_safe_area(safe_area);
}
pub fn set_keyboard_inset(&mut self, height_px: i16) {
self.engine.set_keyboard_inset(height_px);
}
pub fn set_async_waker(&mut self, waker: impl Fn() + Send + Sync + 'static) {
self.engine.set_async_waker(waker);
}
#[inline]
pub fn poll_async_tasks(&mut self) -> bool {
self.engine.poll_async_tasks()
}
#[inline]
pub fn needs_redraw(&self) -> bool {
self.engine.needs_redraw()
}
pub fn step_frame(&mut self, dt_ms: u16) -> usize {
self.dirty_rects.clear();
let mut regions: SmallVec<Region, 8> = SmallVec::new();
for &r in self.engine.step_frame_dt(dt_ms) {
regions.push(r);
}
if regions.is_empty() {
return 0;
}
let s = self.dpi_scale.max(1);
for ® in regions.as_slice() {
self.dirty_rects.push(CDirtyRect {
x: reg.x.saturating_mul(s),
y: reg.y.saturating_mul(s),
w: reg.w.saturating_mul(s),
h: reg.h.saturating_mul(s),
});
}
#[cfg(feature = "gpu")]
if self.backend == super::DesktopRenderBackend::Wgpu {
if let Some(gpu_win) = &mut self.gpu_window {
let viewport = self.engine.viewport_region();
let ops = self.engine.cached_draw_ops();
if gpu_win.render(ops, viewport, s) {
return self.dirty_rects.len();
}
}
}
let _pw = self.physical_width().max(1) as usize;
let _ph = self.physical_height().max(1) as usize;
self.ensure_cpu_framebuffer();
match self.backend {
super::DesktopRenderBackend::Wgpu => {
#[cfg(feature = "gpu")]
{
use crate::renderers::wgpu::WgpuOffscreenRenderer;
let offscreen = self
.gpu_offscreen
.get_or_insert_with(|| WgpuOffscreenRenderer::new_lazy(_pw, _ph));
let _ = offscreen.render_draw_ops_rgba8888_into(
self.engine.cached_draw_ops(),
self.engine.viewport_region(),
s,
regions.as_slice(),
self.framebuffer.as_mut_slice(),
);
}
#[cfg(not(feature = "gpu"))]
{
for ® in regions.as_slice() {
self.engine
.rasterize_region(reg, self.framebuffer.as_mut_slice());
}
}
}
super::DesktopRenderBackend::Software => {
for ® in regions.as_slice() {
self.engine
.rasterize_region(reg, self.framebuffer.as_mut_slice());
}
}
}
self.dirty_rects.len()
}
#[inline(always)]
pub fn rgba_bytes(&self) -> &[u8] {
unsafe {
core::slice::from_raw_parts(
self.framebuffer.as_ptr() as *const u8,
self.framebuffer.len() * 4,
)
}
}
#[inline(always)]
pub fn dirty_rects(&self) -> &[CDirtyRect] {
self.dirty_rects.as_slice()
}
}
pub mod ffi {
use std::boxed::Box;
use super::{CDirtyRect, MobileEmbedApp, TouchPhase};
use crate::pod::SafeAreaInsets;
#[inline]
pub unsafe fn destroy(app: *mut MobileEmbedApp) {
if !app.is_null() {
unsafe {
drop(Box::from_raw(app));
}
}
}
#[inline]
pub unsafe fn backend_is_gpu(app: *const MobileEmbedApp) -> bool {
if let Some(app_ref) = unsafe { app.as_ref() } {
app_ref.backend().is_gpu()
} else {
false
}
}
#[inline]
pub unsafe fn resize(app: *mut MobileEmbedApp, width: i16, height: i16) {
if let Some(app_ref) = unsafe { app.as_mut() } {
app_ref.resize(width, height);
}
}
#[inline]
pub unsafe fn set_dpi_scale(app: *mut MobileEmbedApp, scale: i16) {
if let Some(app_ref) = unsafe { app.as_mut() } {
app_ref.set_dpi_scale(scale);
}
}
#[inline]
pub unsafe fn set_safe_area(
app: *mut MobileEmbedApp,
top: i16,
right: i16,
bottom: i16,
left: i16,
) {
if let Some(app_ref) = unsafe { app.as_mut() } {
app_ref.set_safe_area(SafeAreaInsets::new(top, right, bottom, left));
}
}
#[inline]
pub unsafe fn set_keyboard_inset(app: *mut MobileEmbedApp, height_px: i16) {
if let Some(app_ref) = unsafe { app.as_mut() } {
app_ref.set_keyboard_inset(height_px);
}
}
#[inline]
pub unsafe fn push_touch(
app: *mut MobileEmbedApp,
touch_id: u32,
phase: TouchPhase,
x: i16,
y: i16,
) {
if let Some(app_ref) = unsafe { app.as_mut() } {
app_ref.push_touch(touch_id, phase, x, y);
}
}
#[inline]
pub unsafe fn push_touch_raw(
app: *mut MobileEmbedApp,
touch_id: u32,
phase: u8,
x: i16,
y: i16,
) {
let p = match phase {
0 => TouchPhase::Began,
1 => TouchPhase::Moved,
2 => TouchPhase::Ended,
_ => TouchPhase::Cancelled,
};
unsafe {
push_touch(app, touch_id, p, x, y);
}
}
#[inline]
pub unsafe fn handle_back(app: *mut MobileEmbedApp) -> bool {
if let Some(app_ref) = unsafe { app.as_mut() } {
app_ref.handle_back()
} else {
false
}
}
#[inline]
pub unsafe fn poll_async_tasks(app: *mut MobileEmbedApp) -> bool {
if let Some(app_ref) = unsafe { app.as_mut() } {
app_ref.poll_async_tasks()
} else {
false
}
}
#[inline]
pub unsafe fn needs_redraw(app: *const MobileEmbedApp) -> bool {
if let Some(app_ref) = unsafe { app.as_ref() } {
app_ref.needs_redraw()
} else {
false
}
}
#[inline]
pub unsafe fn step_frame(app: *mut MobileEmbedApp, dt_ms: u16) -> usize {
if let Some(app_ref) = unsafe { app.as_mut() } {
app_ref.step_frame(dt_ms)
} else {
0
}
}
#[inline]
pub unsafe fn framebuffer_ptr(app: *const MobileEmbedApp) -> *const u8 {
if let Some(app_ref) = unsafe { app.as_ref() } {
app_ref.rgba_bytes().as_ptr()
} else {
core::ptr::null()
}
}
#[inline]
pub unsafe fn dirty_rects_ptr(app: *const MobileEmbedApp) -> *const CDirtyRect {
if let Some(app_ref) = unsafe { app.as_ref() } {
app_ref.dirty_rects().as_ptr()
} else {
core::ptr::null()
}
}
#[inline]
pub unsafe fn dirty_rects_count(app: *const MobileEmbedApp) -> usize {
if let Some(app_ref) = unsafe { app.as_ref() } {
app_ref.dirty_rects().len()
} else {
0
}
}
}