mod host_config;
use std::cell::Cell;
use std::ffi::{CString, c_char, c_void};
use std::sync::Mutex;
use std::sync::atomic::{AtomicPtr, Ordering};
use euv::{
AdaptiveUploadPlan, AndroidPresentTelemetry, App, DamageRegion, DeviceMotionSample,
DirectGpuFrameBatch, GLSL_ES3_BACKDROP_BLUR_FRAGMENT_SHADER,
GLSL_ES3_BACKDROP_BLUR_VERTEX_SHADER, GLSL_ES3_UI_FRAGMENT_SHADER, GLSL_ES3_UI_VERTEX_SHADER,
GPU_PRIMITIVE_INSTANCE_BYTES, GlyphKey, GpuPrimitiveInstance, ImeEvent, KeyCode, KeyEvent,
MAX_REFRESH_RATE_HZ, MIN_REFRESH_RATE_HZ, MemoryPressure, MobileFailoverAction,
MobileFailoverController, MobilePresentPath, MobileSurfaceFault, MobileUploadStrategy,
Modifiers, NativeSystemFont, NetworkStatus, PixelDirtyRect, Point, PointerEvent,
RasterizedGlyph, RenderMode, SafeAreaInsets, SystemEvent, ThemeMode, WindowEvent, WindowId,
compile_display_list_direct_gpu_batch, damage_region_to_pixel_dirty_rects,
gles3_scissor_from_top_down, gles3_ui_instance_attribs, register_external_glyph_rasterizer,
register_native_action_bridge, reset_reactive_runtime, select_adaptive_upload_plan,
};
use euv_example::{ShowcaseState, create_showcase_app_for_platform};
pub type JniEnv = *mut *const JniNativeInterface;
pub type JObject = *mut c_void;
pub type JClass = *mut c_void;
pub type JMethodId = *mut c_void;
pub type JIntArray = *mut c_void;
pub type JByteArray = *mut c_void;
#[repr(C)]
#[derive(Clone, Copy)]
pub union JValue {
pub z: u8,
pub i: i32,
pub f: f32,
pub j: i64,
pub l: JObject,
}
#[repr(C)]
pub struct JniNativeInterface {
_pad0: [*const c_void; 21],
new_global_ref: unsafe extern "C" fn(JniEnv, JObject) -> JObject,
_pad1: *const c_void,
delete_local_ref: unsafe extern "C" fn(JniEnv, JObject),
_pad2: [*const c_void; 89],
get_static_method_id:
unsafe extern "C" fn(JniEnv, JClass, *const c_char, *const c_char) -> JMethodId,
_pad3: [*const c_void; 2],
call_static_object_method_a:
unsafe extern "C" fn(JniEnv, JClass, JMethodId, *const JValue) -> JObject,
_pad3b: [*const c_void; 2],
call_static_boolean_method_a:
unsafe extern "C" fn(JniEnv, JClass, JMethodId, *const JValue) -> u8,
_pad4a: [*const c_void; 47],
new_string_utf: unsafe extern "C" fn(JniEnv, *const c_char) -> JObject,
_pad4b: [*const c_void; 3],
get_array_length: unsafe extern "C" fn(JniEnv, JObject) -> i32,
_pad5: [*const c_void; 28],
get_byte_array_region: unsafe extern "C" fn(JniEnv, JByteArray, i32, i32, *mut i8),
_pad6: [*const c_void; 10],
set_int_array_region: unsafe extern "C" fn(JniEnv, JIntArray, i32, i32, *const i32),
_pad7: [*const c_void; 18],
get_direct_buffer_address: unsafe extern "C" fn(JniEnv, JObject) -> *mut c_void,
get_direct_buffer_capacity: unsafe extern "C" fn(JniEnv, JObject) -> i64,
}
thread_local! {
static ACTIVE_JNI_ENV: Cell<*mut c_void> = const { Cell::new(std::ptr::null_mut()) };
}
static BRIDGE_INIT_LOCK: Mutex<()> = Mutex::new(());
static BRIDGE_CLASS_REF: AtomicPtr<c_void> = AtomicPtr::new(std::ptr::null_mut());
static ACTION_METHOD: AtomicPtr<c_void> = AtomicPtr::new(std::ptr::null_mut());
static GLYPH_METHOD: AtomicPtr<c_void> = AtomicPtr::new(std::ptr::null_mut());
struct JniEnvGuard(*mut c_void);
impl JniEnvGuard {
fn enter(env: JniEnv) -> Self {
let prev: *mut c_void = ACTIVE_JNI_ENV.with(|cell: &Cell<*mut c_void>| cell.replace(env.cast()));
Self(prev)
}
}
impl Drop for JniEnvGuard {
fn drop(&mut self) {
ACTIVE_JNI_ENV.with(|cell: &Cell<*mut c_void>| cell.set(self.0));
}
}
fn android_native_action_bridge(kind: &str, arg1: &str, arg2: &str) -> bool {
let env_ptr: *mut c_void = ACTIVE_JNI_ENV.with(Cell::get);
let cls_ptr: JClass = BRIDGE_CLASS_REF.load(Ordering::Acquire);
let mid_ptr: JMethodId = ACTION_METHOD.load(Ordering::Acquire);
if env_ptr.is_null() || cls_ptr.is_null() || mid_ptr.is_null() {
return false;
}
let Ok(c_kind) = CString::new(kind) else {
return false;
};
let Ok(c_a1) = CString::new(arg1) else {
return false;
};
let Ok(c_a2) = CString::new(arg2) else {
return false;
};
let env: JniEnv = env_ptr.cast();
unsafe {
let table: &JniNativeInterface = &*(*env);
let j_kind: JObject = (table.new_string_utf)(env, c_kind.as_ptr());
let j_a1: JObject = (table.new_string_utf)(env, c_a1.as_ptr());
let j_a2: JObject = (table.new_string_utf)(env, c_a2.as_ptr());
let args: [JValue; 3] = [
JValue { l: j_kind },
JValue { l: j_a1 },
JValue { l: j_a2 },
];
let ok: u8 = (table.call_static_boolean_method_a)(env, cls_ptr, mid_ptr, args.as_ptr());
if !j_kind.is_null() {
(table.delete_local_ref)(env, j_kind);
}
if !j_a1.is_null() {
(table.delete_local_ref)(env, j_a1);
}
if !j_a2.is_null() {
(table.delete_local_ref)(env, j_a2);
}
ok != 0
}
}
fn android_jni_rasterize_glyph(key: GlyphKey) -> Option<RasterizedGlyph> {
let env_ptr: *mut c_void = ACTIVE_JNI_ENV.with(Cell::get);
let cls_ptr: JClass = BRIDGE_CLASS_REF.load(Ordering::Acquire);
let mid_ptr: JMethodId = GLYPH_METHOD.load(Ordering::Acquire);
if env_ptr.is_null() || cls_ptr.is_null() || mid_ptr.is_null() {
return None;
}
let size_px: f32 = ((key.get_size_tenths() as f32) * 0.1).clamp(6.0, 256.0);
let style_flags: i32 = (if key.get_bold() { 1 } else { 0 })
| (if key.get_italic() { 2 } else { 0 })
| (if key.get_monospace() { 4 } else { 0 });
let args: [JValue; 3] = [
JValue { i: key.get_codepoint() as u32 as i32 },
JValue { f: size_px },
JValue { i: style_flags },
];
let env: JniEnv = env_ptr.cast();
unsafe {
let table: &JniNativeInterface = &*(*env);
let arr: JByteArray = (table.call_static_object_method_a)(env, cls_ptr, mid_ptr, args.as_ptr());
if arr.is_null() {
return None;
}
let len_i32: i32 = (table.get_array_length)(env, arr);
if len_i32 < 12 {
(table.delete_local_ref)(env, arr);
return None;
}
let total_len: usize = len_i32 as usize;
let mut raw: Vec<u8> = vec![0u8; total_len];
(table.get_byte_array_region)(env, arr, 0, len_i32, raw.as_mut_ptr().cast::<i8>());
(table.delete_local_ref)(env, arr);
let out_w: u32 = u32::from_le_bytes([raw[0], raw[1], raw[2], raw[3]]);
let out_h: u32 = u32::from_le_bytes([raw[4], raw[5], raw[6], raw[7]]);
let advance: u32 = u32::from_le_bytes([raw[8], raw[9], raw[10], raw[11]]);
let needed: usize = (out_w as usize).saturating_mul(out_h as usize);
if out_w == 0 || out_h == 0 || total_len < 12 + needed {
return None;
}
let coverage: Vec<u8> = raw[12..12 + needed].to_vec();
Some(RasterizedGlyph::new(out_w, out_h, advance.max(1), coverage))
}
}
pub struct EglPresenter {
display: *mut c_void,
context: *mut c_void,
surface: *mut c_void,
program: u32,
texture: u32,
vao: u32,
view_loc: i32,
direct_program: u32,
direct_vao: u32,
quad_vbo: u32,
instance_vbo: u32,
instance_vbo_cap: usize,
direct_viewport_loc: i32,
direct_scroll_loc: i32,
glyph_r8_tex: u32,
glyph_rgba8_tex: u32,
image_tex: u32,
external_tex: u32,
blur_program: u32,
blur_fbo: u32,
blur_tex_a: u32,
blur_tex_b: u32,
blur_w: u32,
blur_h: u32,
blur_texel_loc: i32,
blur_offset_loc: i32,
blur_mode_loc: i32,
tex_w: u32,
tex_h: u32,
surface_w: u32,
surface_h: u32,
context_bound: bool,
last_sync: *mut c_void,
egl_create_sync_khr: Option<unsafe extern "C" fn(*mut c_void, u32, *const i32) -> *mut c_void>,
egl_client_wait_sync_khr: Option<unsafe extern "C" fn(*mut c_void, *mut c_void, i32, u64) -> i32>,
egl_destroy_sync_khr: Option<unsafe extern "C" fn(*mut c_void, *mut c_void) -> u32>,
egl_swap_with_damage_khr: Option<unsafe extern "C" fn(*mut c_void, *mut c_void, *const i32, i32) -> u32>,
egl_presentation_time_android: Option<unsafe extern "C" fn(*mut c_void, *mut c_void, i64) -> u32>,
}
const EGL_NO_DISPLAY: *mut c_void = std::ptr::null_mut();
const EGL_NO_CONTEXT: *mut c_void = std::ptr::null_mut();
const EGL_NO_SURFACE: *mut c_void = std::ptr::null_mut();
const EGL_NO_SYNC_KHR: *mut c_void = std::ptr::null_mut();
const EGL_DEFAULT_DISPLAY: *mut c_void = std::ptr::null_mut();
const EGL_SURFACE_TYPE: i32 = 0x3033;
const EGL_WINDOW_BIT: i32 = 0x0004;
const EGL_RENDERABLE_TYPE: i32 = 0x3040;
const EGL_OPENGL_ES3_BIT: i32 = 0x0040;
const EGL_RED_SIZE: i32 = 0x3024;
const EGL_GREEN_SIZE: i32 = 0x3023;
const EGL_BLUE_SIZE: i32 = 0x3022;
const EGL_ALPHA_SIZE: i32 = 0x3021;
const EGL_NONE: i32 = 0x3038;
const EGL_CONTEXT_CLIENT_VERSION: i32 = 0x3098;
const EGL_CONTEXT_LOST: i32 = 0x300E;
const EGL_SYNC_FENCE_KHR: u32 = 0x30F9;
const EGL_SYNC_FLUSH_COMMANDS_BIT_KHR: i32 = 0x0001;
const EGL_SYNC_WAIT_TIMEOUT_NS: u64 = 16_000_000;
const EGL_MAX_CONTEXT_RECOVERIES: u32 = 2;
const CLOCK_MONOTONIC: i32 = 1;
#[repr(C)]
#[derive(Clone, Copy)]
struct PosixTimespec {
tv_sec: i64,
tv_nsec: i64,
}
unsafe extern "C" {
fn clock_gettime(clk_id: i32, tp: *mut PosixTimespec) -> i32;
}
fn monotonic_time_ns() -> i64 {
let mut ts: PosixTimespec = PosixTimespec { tv_sec: 0, tv_nsec: 0 };
unsafe {
if clock_gettime(CLOCK_MONOTONIC, &mut ts) == 0 {
ts.tv_sec.saturating_mul(1_000_000_000).saturating_add(ts.tv_nsec)
} else {
0
}
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum EglPresentStatus {
Presented,
ContextLost,
Failed,
}
const GL_VERTEX_SHADER: u32 = 0x8B31;
const GL_FRAGMENT_SHADER: u32 = 0x8B30;
const GL_COMPILE_STATUS: u32 = 0x8B81;
const GL_LINK_STATUS: u32 = 0x8B82;
const GL_TEXTURE_2D: u32 = 0x0DE1;
const GL_TEXTURE_MIN_FILTER: u32 = 0x2801;
const GL_TEXTURE_MAG_FILTER: u32 = 0x2800;
const GL_TEXTURE_WRAP_S: u32 = 0x2802;
const GL_TEXTURE_WRAP_T: u32 = 0x2803;
const GL_LINEAR: i32 = 0x2601;
const GL_CLAMP_TO_EDGE: i32 = 0x812F;
const GL_RGBA8: i32 = 0x8058;
const GL_R8: i32 = 0x8229;
const GL_RED: u32 = 0x1903;
const GL_RGBA: u32 = 0x1908;
const GL_UNSIGNED_BYTE: u32 = 0x1401;
const GL_UNSIGNED_INT: u32 = 0x1405;
const GL_FLOAT: u32 = 0x1406;
const GL_UNPACK_ALIGNMENT: u32 = 0x0CF5;
const GL_UNPACK_ROW_LENGTH: u32 = 0x0CF2;
const GL_UNPACK_SKIP_ROWS: u32 = 0x0CF3;
const GL_UNPACK_SKIP_PIXELS: u32 = 0x0CF4;
const GL_TEXTURE0: u32 = 0x84C0;
const GL_TEXTURE1: u32 = 0x84C1;
const GL_TEXTURE2: u32 = 0x84C2;
const GL_TEXTURE3: u32 = 0x84C3;
const GL_TRIANGLES: u32 = 0x0004;
const GL_ARRAY_BUFFER: u32 = 0x8892;
const GL_STATIC_DRAW: u32 = 0x88E4;
const GL_STREAM_DRAW: u32 = 0x88E0;
const GL_BLEND: u32 = 0x0BE2;
const GL_SCISSOR_TEST: u32 = 0x0C11;
const GL_SRC_ALPHA: u32 = 0x0302;
const GL_ONE: u32 = 1;
const GL_ONE_MINUS_SRC_ALPHA: u32 = 0x0303;
const GL_COLOR_BUFFER_BIT: u32 = 0x4000;
const GL_FRAMEBUFFER: u32 = 0x8D40;
const GL_COLOR_ATTACHMENT0: u32 = 0x8CE0;
const GL_FALSE: u8 = 0;
#[link(name = "EGL")]
unsafe extern "C" {
fn eglGetError() -> i32;
fn eglGetProcAddress(procname: *const c_char) -> *const c_void;
fn eglGetDisplay(display_id: *mut c_void) -> *mut c_void;
fn eglInitialize(dpy: *mut c_void, major: *mut i32, minor: *mut i32) -> u32;
fn eglChooseConfig(
dpy: *mut c_void,
attrib_list: *const i32,
configs: *mut *mut c_void,
config_size: i32,
num_config: *mut i32,
) -> u32;
fn eglCreateContext(
dpy: *mut c_void,
config: *mut c_void,
share_context: *mut c_void,
attrib_list: *const i32,
) -> *mut c_void;
fn eglCreateWindowSurface(
dpy: *mut c_void,
config: *mut c_void,
win: *mut ANativeWindow,
attrib_list: *const i32,
) -> *mut c_void;
fn eglMakeCurrent(
dpy: *mut c_void,
draw: *mut c_void,
read: *mut c_void,
ctx: *mut c_void,
) -> u32;
fn eglSwapInterval(dpy: *mut c_void, interval: i32) -> u32;
fn eglSwapBuffers(dpy: *mut c_void, surface: *mut c_void) -> u32;
fn eglDestroySurface(dpy: *mut c_void, surface: *mut c_void) -> u32;
fn eglDestroyContext(dpy: *mut c_void, ctx: *mut c_void) -> u32;
}
#[link(name = "GLESv3")]
unsafe extern "C" {
fn glCreateShader(shader_type: u32) -> u32;
fn glShaderSource(shader: u32, count: i32, string: *const *const c_char, length: *const i32);
fn glCompileShader(shader: u32);
fn glGetShaderiv(shader: u32, pname: u32, params: *mut i32);
fn glDeleteShader(shader: u32);
fn glCreateProgram() -> u32;
fn glAttachShader(program: u32, shader: u32);
fn glLinkProgram(program: u32);
fn glGetProgramiv(program: u32, pname: u32, params: *mut i32);
fn glDeleteProgram(program: u32);
fn glUseProgram(program: u32);
fn glGetUniformLocation(program: u32, name: *const c_char) -> i32;
fn glUniform1i(location: i32, v0: i32);
fn glUniform1f(location: i32, v0: f32);
fn glUniform2f(location: i32, v0: f32, v1: f32);
fn glGenVertexArrays(n: i32, arrays: *mut u32);
fn glBindVertexArray(array: u32);
fn glDeleteVertexArrays(n: i32, arrays: *const u32);
fn glGenBuffers(n: i32, buffers: *mut u32);
fn glBindBuffer(target: u32, buffer: u32);
fn glBufferData(target: u32, size: isize, data: *const c_void, usage: u32);
fn glBufferSubData(target: u32, offset: isize, size: isize, data: *const c_void);
fn glDeleteBuffers(n: i32, buffers: *const u32);
fn glEnableVertexAttribArray(index: u32);
fn glVertexAttribPointer(
index: u32,
size: i32,
ty: u32,
normalized: u8,
stride: i32,
pointer: *const c_void,
);
fn glVertexAttribIPointer(
index: u32,
size: i32,
ty: u32,
stride: i32,
pointer: *const c_void,
);
fn glVertexAttribDivisor(index: u32, divisor: u32);
fn glGenTextures(n: i32, textures: *mut u32);
fn glActiveTexture(texture: u32);
fn glBindTexture(target: u32, texture: u32);
fn glDeleteTextures(n: i32, textures: *const u32);
fn glTexParameteri(target: u32, pname: u32, param: i32);
fn glPixelStorei(pname: u32, param: i32);
fn glTexImage2D(
target: u32,
level: i32,
internalformat: i32,
width: i32,
height: i32,
border: i32,
format: u32,
ty: u32,
pixels: *const c_void,
);
fn glTexSubImage2D(
target: u32,
level: i32,
xoffset: i32,
yoffset: i32,
width: i32,
height: i32,
format: u32,
ty: u32,
pixels: *const c_void,
);
fn glCopyTexSubImage2D(
target: u32,
level: i32,
xoffset: i32,
yoffset: i32,
x: i32,
y: i32,
width: i32,
height: i32,
);
fn glGenFramebuffers(n: i32, framebuffers: *mut u32);
fn glBindFramebuffer(target: u32, framebuffer: u32);
fn glFramebufferTexture2D(
target: u32,
attachment: u32,
textarget: u32,
texture: u32,
level: i32,
);
fn glDeleteFramebuffers(n: i32, framebuffers: *const u32);
fn glEnable(cap: u32);
fn glDisable(cap: u32);
fn glBlendFuncSeparate(src_rgb: u32, dst_rgb: u32, src_alpha: u32, dst_alpha: u32);
fn glScissor(x: i32, y: i32, width: i32, height: i32);
fn glClearColor(r: f32, g: f32, b: f32, a: f32);
fn glClear(mask: u32);
fn glViewport(x: i32, y: i32, width: i32, height: i32);
fn glDrawArrays(mode: u32, first: i32, count: i32);
fn glDrawArraysInstanced(mode: u32, first: i32, count: i32, instancecount: i32);
}
impl EglPresenter {
fn compile_shader(ty: u32, src: &std::ffi::CStr) -> Option<u32> {
unsafe {
let sh: u32 = glCreateShader(ty);
if sh == 0 {
return None;
}
let ptr: *const c_char = src.as_ptr();
glShaderSource(sh, 1, &ptr, std::ptr::null());
glCompileShader(sh);
let mut ok: i32 = 0;
glGetShaderiv(sh, GL_COMPILE_STATUS, &mut ok);
if ok == 0 {
glDeleteShader(sh);
return None;
}
Some(sh)
}
}
fn link_program(vs_src: &std::ffi::CStr, fs_src: &std::ffi::CStr) -> Option<u32> {
unsafe {
let vs: u32 = Self::compile_shader(GL_VERTEX_SHADER, vs_src)?;
let Some(fs) = Self::compile_shader(GL_FRAGMENT_SHADER, fs_src) else {
glDeleteShader(vs);
return None;
};
let program: u32 = glCreateProgram();
glAttachShader(program, vs);
glAttachShader(program, fs);
glLinkProgram(program);
glDeleteShader(vs);
glDeleteShader(fs);
let mut linked: i32 = 0;
glGetProgramiv(program, GL_LINK_STATUS, &mut linked);
if linked == 0 {
glDeleteProgram(program);
return None;
}
Some(program)
}
}
fn init_dummy_texture(internalformat: i32, format: u32) -> u32 {
unsafe {
let mut tex: u32 = 0;
glGenTextures(1, &mut tex);
glBindTexture(GL_TEXTURE_2D, tex);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
let white: [u8; 4] = [255, 255, 255, 255];
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(
GL_TEXTURE_2D,
0,
internalformat,
1,
1,
0,
format,
GL_UNSIGNED_BYTE,
white.as_ptr().cast::<c_void>(),
);
tex
}
}
fn bind_instance_attribs_at(instance_vbo: u32, base_byte_offset: usize) {
unsafe {
glBindBuffer(GL_ARRAY_BUFFER, instance_vbo);
for spec in gles3_ui_instance_attribs().iter() {
let offset_ptr: *const c_void =
base_byte_offset.saturating_add(spec.get_byte_offset()) as *const c_void;
glEnableVertexAttribArray(spec.get_location());
if spec.get_is_integer() {
glVertexAttribIPointer(
spec.get_location(),
spec.get_components(),
GL_UNSIGNED_INT,
spec.get_stride(),
offset_ptr,
);
} else {
glVertexAttribPointer(
spec.get_location(),
spec.get_components(),
GL_FLOAT,
GL_FALSE,
spec.get_stride(),
offset_ptr,
);
}
glVertexAttribDivisor(spec.get_location(), 1);
}
}
}
fn has_direct_pipeline(&self) -> bool {
self.direct_program != 0 && self.direct_vao != 0 && self.instance_vbo != 0
}
fn create(win: *mut ANativeWindow, surface_w: u32, surface_h: u32) -> Option<Self> {
if win.is_null() {
return None;
}
unsafe {
let display: *mut c_void = eglGetDisplay(EGL_DEFAULT_DISPLAY);
if display == EGL_NO_DISPLAY {
return None;
}
let mut maj: i32 = 0;
let mut min: i32 = 0;
if eglInitialize(display, &mut maj, &mut min) == 0 {
return None;
}
let cfg_attribs: [i32; 13] = [
EGL_SURFACE_TYPE,
EGL_WINDOW_BIT,
EGL_RENDERABLE_TYPE,
EGL_OPENGL_ES3_BIT,
EGL_RED_SIZE,
8,
EGL_GREEN_SIZE,
8,
EGL_BLUE_SIZE,
8,
EGL_ALPHA_SIZE,
8,
EGL_NONE,
];
let mut config: *mut c_void = std::ptr::null_mut();
let mut num_cfg: i32 = 0;
if eglChooseConfig(display, cfg_attribs.as_ptr(), &mut config, 1, &mut num_cfg) == 0
|| num_cfg <= 0
|| config.is_null()
{
return None;
}
let ctx_attribs: [i32; 3] = [EGL_CONTEXT_CLIENT_VERSION, 3, EGL_NONE];
let context: *mut c_void =
eglCreateContext(display, config, EGL_NO_CONTEXT, ctx_attribs.as_ptr());
if context == EGL_NO_CONTEXT {
return None;
}
let surface: *mut c_void =
eglCreateWindowSurface(display, config, win, std::ptr::null());
if surface == EGL_NO_SURFACE {
eglDestroyContext(display, context);
return None;
}
if eglMakeCurrent(display, surface, surface, context) == 0 {
eglDestroySurface(display, surface);
eglDestroyContext(display, context);
return None;
}
let _ = eglSwapInterval(display, 0);
let vs_src = c"#version 300 es\nprecision highp float;\nprecision highp int;\nvoid main() {\n vec2 pos = vec2((gl_VertexID == 1) ? 3.0 : -1.0, (gl_VertexID == 2) ? 3.0 : -1.0);\n gl_Position = vec4(pos, 0.0, 1.0);\n}\n";
let fs_src = c"#version 300 es\nprecision highp float;\nprecision highp int;\nprecision highp sampler2D;\nuniform highp sampler2D u_tex;\nuniform highp vec2 u_view;\nout highp vec4 frag_color;\nvoid main() {\n ivec2 tex_size = textureSize(u_tex, 0);\n highp vec2 view = max(u_view, vec2(1.0));\n ivec2 view_size = ivec2(view + vec2(0.5));\n if (tex_size == view_size) {\n ivec2 texel = ivec2(int(gl_FragCoord.x), tex_size.y - 1 - int(gl_FragCoord.y));\n frag_color = texelFetch(u_tex, clamp(texel, ivec2(0), tex_size - ivec2(1)), 0);\n } else {\n highp vec2 uv = vec2(gl_FragCoord.x, view.y - gl_FragCoord.y) / view;\n frag_color = texture(u_tex, uv);\n }\n}\n";
let Some(program) = Self::link_program(vs_src, fs_src) else {
eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
eglDestroySurface(display, surface);
eglDestroyContext(display, context);
return None;
};
let mut vao: u32 = 0;
glGenVertexArrays(1, &mut vao);
let mut texture: u32 = 0;
glGenTextures(1, &mut texture);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glUseProgram(program);
let loc: i32 = glGetUniformLocation(program, c"u_tex".as_ptr());
if loc >= 0 {
glUniform1i(loc, 0);
}
let view_loc: i32 = glGetUniformLocation(program, c"u_view".as_ptr());
let mut direct_program: u32 = 0;
let mut direct_vao: u32 = 0;
let mut quad_vbo: u32 = 0;
let mut instance_vbo: u32 = 0;
let mut direct_viewport_loc: i32 = -1;
let mut direct_scroll_loc: i32 = -1;
let mut glyph_r8_tex: u32 = 0;
let mut glyph_rgba8_tex: u32 = 0;
let mut image_tex: u32 = 0;
let mut external_tex: u32 = 0;
if let (Ok(d_vs), Ok(d_fs)) = (
CString::new(GLSL_ES3_UI_VERTEX_SHADER),
CString::new(GLSL_ES3_UI_FRAGMENT_SHADER),
) && let Some(dp) = Self::link_program(&d_vs, &d_fs)
{
direct_program = dp;
glUseProgram(direct_program);
direct_viewport_loc = glGetUniformLocation(direct_program, c"u_viewport".as_ptr());
direct_scroll_loc = glGetUniformLocation(direct_program, c"u_scroll_offset".as_ptr());
let g_r8_loc: i32 = glGetUniformLocation(direct_program, c"u_glyph_r8".as_ptr());
if g_r8_loc >= 0 {
glUniform1i(g_r8_loc, 0);
}
let g_rgba_loc: i32 = glGetUniformLocation(direct_program, c"u_glyph_rgba8".as_ptr());
if g_rgba_loc >= 0 {
glUniform1i(g_rgba_loc, 1);
}
let img_loc: i32 = glGetUniformLocation(direct_program, c"u_image_tex".as_ptr());
if img_loc >= 0 {
glUniform1i(img_loc, 2);
}
let ext_loc: i32 = glGetUniformLocation(direct_program, c"u_external_tex".as_ptr());
if ext_loc >= 0 {
glUniform1i(ext_loc, 3);
}
glGenVertexArrays(1, &mut direct_vao);
glBindVertexArray(direct_vao);
glGenBuffers(1, &mut quad_vbo);
let corners: [f32; 12] = [0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0];
glBindBuffer(GL_ARRAY_BUFFER, quad_vbo);
glBufferData(
GL_ARRAY_BUFFER,
std::mem::size_of_val(&corners) as isize,
corners.as_ptr().cast::<c_void>(),
GL_STATIC_DRAW,
);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 8, std::ptr::null());
glVertexAttribDivisor(0, 0);
glGenBuffers(1, &mut instance_vbo);
Self::bind_instance_attribs_at(instance_vbo, 0);
glyph_r8_tex = Self::init_dummy_texture(GL_R8, GL_RED);
glyph_rgba8_tex = Self::init_dummy_texture(GL_RGBA8, GL_RGBA);
image_tex = Self::init_dummy_texture(GL_RGBA8, GL_RGBA);
external_tex = Self::init_dummy_texture(GL_RGBA8, GL_RGBA);
}
let mut blur_program: u32 = 0;
let mut blur_fbo: u32 = 0;
let mut blur_tex_a: u32 = 0;
let mut blur_tex_b: u32 = 0;
let mut blur_texel_loc: i32 = -1;
let mut blur_offset_loc: i32 = -1;
let mut blur_mode_loc: i32 = -1;
if let (Ok(b_vs), Ok(b_fs)) = (
CString::new(GLSL_ES3_BACKDROP_BLUR_VERTEX_SHADER),
CString::new(GLSL_ES3_BACKDROP_BLUR_FRAGMENT_SHADER),
) && let Some(bp) = Self::link_program(&b_vs, &b_fs)
{
blur_program = bp;
glUseProgram(blur_program);
let bt_loc: i32 = glGetUniformLocation(blur_program, c"u_blur_tex".as_ptr());
if bt_loc >= 0 {
glUniform1i(bt_loc, 0);
}
blur_texel_loc = glGetUniformLocation(blur_program, c"u_texel_size".as_ptr());
blur_offset_loc = glGetUniformLocation(blur_program, c"u_blur_offset".as_ptr());
blur_mode_loc = glGetUniformLocation(blur_program, c"u_blur_pass_mode".as_ptr());
glGenFramebuffers(1, &mut blur_fbo);
blur_tex_a = Self::init_dummy_texture(GL_RGBA8, GL_RGBA);
blur_tex_b = Self::init_dummy_texture(GL_RGBA8, GL_RGBA);
}
let create_sync_ptr: *const c_void = eglGetProcAddress(c"eglCreateSyncKHR".as_ptr());
let wait_sync_ptr: *const c_void = eglGetProcAddress(c"eglClientWaitSyncKHR".as_ptr());
let destroy_sync_ptr: *const c_void = eglGetProcAddress(c"eglDestroySyncKHR".as_ptr());
let swap_dmg_ptr: *const c_void =
eglGetProcAddress(c"eglSwapBuffersWithDamageKHR".as_ptr());
let pres_time_ptr: *const c_void =
eglGetProcAddress(c"eglPresentationTimeANDROID".as_ptr());
Some(Self {
display,
context,
surface,
program,
texture,
vao,
view_loc,
direct_program,
direct_vao,
quad_vbo,
instance_vbo,
instance_vbo_cap: 0,
direct_viewport_loc,
direct_scroll_loc,
glyph_r8_tex,
glyph_rgba8_tex,
image_tex,
external_tex,
blur_program,
blur_fbo,
blur_tex_a,
blur_tex_b,
blur_w: 0,
blur_h: 0,
blur_texel_loc,
blur_offset_loc,
blur_mode_loc,
tex_w: 0,
tex_h: 0,
surface_w,
surface_h,
context_bound: true,
last_sync: EGL_NO_SYNC_KHR,
egl_create_sync_khr: if create_sync_ptr.is_null() {
None
} else {
Some(std::mem::transmute(create_sync_ptr))
},
egl_client_wait_sync_khr: if wait_sync_ptr.is_null() {
None
} else {
Some(std::mem::transmute(wait_sync_ptr))
},
egl_destroy_sync_khr: if destroy_sync_ptr.is_null() {
None
} else {
Some(std::mem::transmute(destroy_sync_ptr))
},
egl_swap_with_damage_khr: if swap_dmg_ptr.is_null() {
None
} else {
Some(std::mem::transmute(swap_dmg_ptr))
},
egl_presentation_time_android: if pres_time_ptr.is_null() {
None
} else {
Some(std::mem::transmute(pres_time_ptr))
},
})
}
}
fn ensure_current_and_wait_sync(&mut self) -> Result<(), EglPresentStatus> {
unsafe {
if !self.context_bound {
if eglMakeCurrent(self.display, self.surface, self.surface, self.context) == 0 {
return Err(if eglGetError() == EGL_CONTEXT_LOST {
EglPresentStatus::ContextLost
} else {
EglPresentStatus::Failed
});
}
self.context_bound = true;
}
if self.last_sync != EGL_NO_SYNC_KHR {
if let Some(wait_fn) = self.egl_client_wait_sync_khr {
let _: i32 = wait_fn(
self.display,
self.last_sync,
EGL_SYNC_FLUSH_COMMANDS_BIT_KHR,
EGL_SYNC_WAIT_TIMEOUT_NS,
);
}
if let Some(destroy_fn) = self.egl_destroy_sync_khr {
let _: u32 = destroy_fn(self.display, self.last_sync);
}
self.last_sync = EGL_NO_SYNC_KHR;
}
Ok(())
}
}
fn finish_and_swap(
&mut self,
damage_rects: &[[i32; 4]],
) -> (EglPresentStatus, Option<u64>) {
unsafe {
if let Some(create_fn) = self.egl_create_sync_khr {
self.last_sync = create_fn(self.display, EGL_SYNC_FENCE_KHR, std::ptr::null());
}
let ts_ns: i64 = monotonic_time_ns();
let mut reported_ts: Option<u64> = None;
if let Some(pres_fn) = self.egl_presentation_time_android
&& ts_ns > 0
{
if pres_fn(self.display, self.surface, ts_ns) != 0 {
reported_ts = Some(ts_ns as u64);
}
}
let swapped: u32 = if let Some(dmg_fn) = self.egl_swap_with_damage_khr
&& !damage_rects.is_empty()
{
dmg_fn(
self.display,
self.surface,
damage_rects.as_ptr().cast::<i32>(),
damage_rects.len() as i32,
)
} else {
eglSwapBuffers(self.display, self.surface)
};
if swapped != 0 {
if reported_ts.is_none() && ts_ns > 0 {
reported_ts = Some(ts_ns as u64);
}
(EglPresentStatus::Presented, reported_ts)
} else {
self.context_bound = false;
let st: EglPresentStatus = if eglGetError() == EGL_CONTEXT_LOST {
EglPresentStatus::ContextLost
} else {
EglPresentStatus::Failed
};
(st, None)
}
}
}
fn present_direct_gpu(
&mut self,
batch: &DirectGpuFrameBatch,
) -> (EglPresentStatus, Option<u64>) {
if !self.has_direct_pipeline() {
return (EglPresentStatus::Failed, None);
}
if let Err(st) = self.ensure_current_and_wait_sync() {
return (st, None);
}
let vw: u32 = self.surface_w.max(batch.get_viewport_width()).max(1);
let vh: u32 = self.surface_h.max(batch.get_viewport_height()).max(1);
unsafe {
if let Some(glyph_atlas) = batch.glyph_r8_atlas_ref()
&& glyph_atlas.get_width() > 0
&& glyph_atlas.get_height() > 0
{
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, self.glyph_r8_tex);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
glTexImage2D(
GL_TEXTURE_2D,
0,
GL_R8,
glyph_atlas.get_width() as i32,
glyph_atlas.get_height() as i32,
0,
GL_RED,
GL_UNSIGNED_BYTE,
glyph_atlas.get_pixels().as_ptr().cast::<c_void>(),
);
}
if let Some(img_atlas) = batch.image_rgba8_atlas_ref()
&& img_atlas.get_width() > 0
&& img_atlas.get_height() > 0
{
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, self.image_tex);
glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
glTexImage2D(
GL_TEXTURE_2D,
0,
GL_RGBA8,
img_atlas.get_width() as i32,
img_atlas.get_height() as i32,
0,
GL_RGBA,
GL_UNSIGNED_BYTE,
img_atlas.get_pixels().as_ptr().cast::<c_void>(),
);
}
let prims: &[GpuPrimitiveInstance] = batch.get_primitives().as_slice();
let total_prims: usize = prims.len();
let byte_len: usize = total_prims.saturating_mul(GPU_PRIMITIVE_INSTANCE_BYTES);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glViewport(0, 0, vw as i32, vh as i32);
glDisable(GL_SCISSOR_TEST);
let clear: [f32; 4] = batch.get_clear_rgba();
glClearColor(clear[0], clear[1], clear[2], clear[3]);
glClear(GL_COLOR_BUFFER_BIT);
if byte_len > 0 {
glBindBuffer(GL_ARRAY_BUFFER, self.instance_vbo);
if byte_len > self.instance_vbo_cap {
let alloc: usize = byte_len.max(4096).next_power_of_two();
glBufferData(GL_ARRAY_BUFFER, alloc as isize, std::ptr::null(), GL_STREAM_DRAW);
self.instance_vbo_cap = alloc;
}
glBufferSubData(
GL_ARRAY_BUFFER,
0,
byte_len as isize,
prims.as_ptr().cast::<c_void>(),
);
}
let draw_ranges_slice = |egl_self: &EglPresenter, start_idx: usize, end_idx: usize| {
if byte_len == 0 || start_idx >= end_idx {
return;
}
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glViewport(0, 0, vw as i32, vh as i32);
glEnable(GL_BLEND);
glBlendFuncSeparate(
GL_SRC_ALPHA,
GL_ONE_MINUS_SRC_ALPHA,
GL_ONE,
GL_ONE_MINUS_SRC_ALPHA,
);
glEnable(GL_SCISSOR_TEST);
glUseProgram(egl_self.direct_program);
if egl_self.direct_viewport_loc >= 0 {
glUniform2f(egl_self.direct_viewport_loc, vw as f32, vh as f32);
}
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, egl_self.glyph_r8_tex);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, egl_self.glyph_rgba8_tex);
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, egl_self.image_tex);
glActiveTexture(GL_TEXTURE3);
glBindTexture(GL_TEXTURE_2D, egl_self.external_tex);
glBindVertexArray(egl_self.direct_vao);
for range in batch.get_draw_ranges()[start_idx..end_idx].iter() {
let base_inst: usize = range.get_base_instance() as usize;
let count: usize = range.get_instance_count() as usize;
if count == 0 || base_inst >= total_prims {
continue;
}
let draw_count: usize = count.min(total_prims - base_inst);
let sc: [i32; 4] = gles3_scissor_from_top_down(
vh,
range.get_scissor_x(),
range.get_scissor_y(),
range.get_scissor_w(),
range.get_scissor_h(),
);
glScissor(sc[0], sc[1], sc[2], sc[3]);
if egl_self.direct_scroll_loc >= 0 {
glUniform2f(
egl_self.direct_scroll_loc,
range.get_scroll_x(),
range.get_scroll_y(),
);
}
let base_bytes: usize =
base_inst.saturating_mul(GPU_PRIMITIVE_INSTANCE_BYTES);
Self::bind_instance_attribs_at(egl_self.instance_vbo, base_bytes);
glDrawArraysInstanced(GL_TRIANGLES, 0, 6, draw_count as i32);
}
glDisable(GL_SCISSOR_TEST);
};
let total_ranges: usize = batch.get_draw_ranges().len();
let can_blur: bool =
!batch.get_backdrop_blurs().is_empty() && self.blur_program != 0 && self.blur_fbo != 0;
if !can_blur {
draw_ranges_slice(self, 0, total_ranges);
} else {
if self.blur_w != vw || self.blur_h != vh {
for &bt in [self.blur_tex_a, self.blur_tex_b].iter() {
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, bt);
glTexImage2D(
GL_TEXTURE_2D,
0,
GL_RGBA8,
vw as i32,
vh as i32,
0,
GL_RGBA,
GL_UNSIGNED_BYTE,
std::ptr::null(),
);
}
self.blur_w = vw;
self.blur_h = vh;
}
let mut range_cursor: usize = 0;
for pass in batch.get_backdrop_blurs().iter() {
let target_layer: u8 = pass.get_layer_id();
let mut next_cursor: usize = range_cursor;
while next_cursor < total_ranges
&& batch.get_draw_ranges()[next_cursor].get_layer_id() <= target_layer
{
next_cursor += 1;
}
if next_cursor > range_cursor {
draw_ranges_slice(self, range_cursor, next_cursor);
range_cursor = next_cursor;
}
glDisable(GL_BLEND);
glDisable(GL_SCISSOR_TEST);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, self.blur_tex_a);
glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, vw as i32, vh as i32);
glBindFramebuffer(GL_FRAMEBUFFER, self.blur_fbo);
glFramebufferTexture2D(
GL_FRAMEBUFFER,
GL_COLOR_ATTACHMENT0,
GL_TEXTURE_2D,
self.blur_tex_b,
0,
);
glUseProgram(self.blur_program);
glBindVertexArray(self.vao);
if self.blur_texel_loc >= 0 {
glUniform2f(self.blur_texel_loc, 1.0 / (vw as f32), 1.0 / (vh as f32));
}
if self.blur_offset_loc >= 0 {
glUniform1f(self.blur_offset_loc, 1.5);
}
if self.blur_mode_loc >= 0 {
glUniform1i(self.blur_mode_loc, 0);
}
glDrawArrays(GL_TRIANGLES, 0, 3);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glBindTexture(GL_TEXTURE_2D, self.blur_tex_b);
if self.blur_mode_loc >= 0 {
glUniform1i(self.blur_mode_loc, 1);
}
glEnable(GL_SCISSOR_TEST);
let b = pass.get_bounds();
let sc: [i32; 4] = gles3_scissor_from_top_down(
vh,
b.get_x().max(0.0) as u32,
b.get_y().max(0.0) as u32,
b.get_width().max(1.0) as u32,
b.get_height().max(1.0) as u32,
);
glScissor(sc[0], sc[1], sc[2], sc[3]);
glDrawArrays(GL_TRIANGLES, 0, 3);
glDisable(GL_SCISSOR_TEST);
}
if range_cursor < total_ranges {
draw_ranges_slice(self, range_cursor, total_ranges);
}
}
glDisable(GL_BLEND);
}
self.finish_and_swap(&[])
}
fn present_upload_plan(
&mut self,
pixels: &[u8],
fb_w: u32,
fb_h: u32,
plan: &AdaptiveUploadPlan,
) -> (EglPresentStatus, Option<u64>) {
let needed: usize = (fb_w as usize).saturating_mul(fb_h as usize).saturating_mul(4);
if fb_w == 0 || fb_h == 0 || pixels.len() < needed {
return (EglPresentStatus::Failed, None);
}
if plan.get_strategy() == MobileUploadStrategy::None {
return (EglPresentStatus::Presented, None);
}
if let Err(st) = self.ensure_current_and_wait_sync() {
return (st, None);
}
unsafe {
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glDisable(GL_BLEND);
glDisable(GL_SCISSOR_TEST);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, self.texture);
glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
let mut damage_rects: Vec<[i32; 4]> = Vec::with_capacity(plan.get_rects().len());
if self.tex_w != fb_w || self.tex_h != fb_h {
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
glTexImage2D(
GL_TEXTURE_2D,
0,
GL_RGBA8,
fb_w as i32,
fb_h as i32,
0,
GL_RGBA,
GL_UNSIGNED_BYTE,
pixels.as_ptr().cast::<c_void>(),
);
self.tex_w = fb_w;
self.tex_h = fb_h;
} else if plan.get_strategy() == MobileUploadStrategy::FullFrame
|| plan.get_rects().is_empty()
{
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
glTexSubImage2D(
GL_TEXTURE_2D,
0,
0,
0,
fb_w as i32,
fb_h as i32,
GL_RGBA,
GL_UNSIGNED_BYTE,
pixels.as_ptr().cast::<c_void>(),
);
} else {
glPixelStorei(GL_UNPACK_ROW_LENGTH, fb_w as i32);
for rect in plan.get_rects().iter() {
let Some(clamped) = rect.clamp_to(fb_w, fb_h) else {
continue;
};
let rx: u32 = clamped.get_x();
let ry: u32 = clamped.get_y();
let rw: u32 = clamped.get_width();
let rh: u32 = clamped.get_height();
let byte_off: usize = ((ry as usize)
.saturating_mul(fb_w as usize)
.saturating_add(rx as usize))
.saturating_mul(4);
glTexSubImage2D(
GL_TEXTURE_2D,
0,
rx as i32,
ry as i32,
rw as i32,
rh as i32,
GL_RGBA,
GL_UNSIGNED_BYTE,
pixels.as_ptr().add(byte_off).cast::<c_void>(),
);
damage_rects.push(gles3_scissor_from_top_down(self.surface_h, rx, ry, rw, rh));
}
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
}
glViewport(0, 0, self.surface_w as i32, self.surface_h as i32);
glUseProgram(self.program);
if self.view_loc >= 0 {
glUniform2f(self.view_loc, self.surface_w as f32, self.surface_h as f32);
}
glBindVertexArray(self.vao);
glDrawArrays(GL_TRIANGLES, 0, 3);
self.finish_and_swap(&damage_rects)
}
}
fn destroy(&mut self) {
unsafe {
if self.display != EGL_NO_DISPLAY {
if self.last_sync != EGL_NO_SYNC_KHR {
if let Some(destroy_fn) = self.egl_destroy_sync_khr {
let _: u32 = destroy_fn(self.display, self.last_sync);
}
self.last_sync = EGL_NO_SYNC_KHR;
}
let _ = eglMakeCurrent(self.display, self.surface, self.surface, self.context);
self.context_bound = false;
for tex in [
&mut self.texture,
&mut self.glyph_r8_tex,
&mut self.glyph_rgba8_tex,
&mut self.image_tex,
&mut self.external_tex,
&mut self.blur_tex_a,
&mut self.blur_tex_b,
] {
if *tex != 0 {
glDeleteTextures(1, tex);
*tex = 0;
}
}
for buf in [&mut self.quad_vbo, &mut self.instance_vbo] {
if *buf != 0 {
glDeleteBuffers(1, buf);
*buf = 0;
}
}
for v in [&mut self.vao, &mut self.direct_vao] {
if *v != 0 {
glDeleteVertexArrays(1, v);
*v = 0;
}
}
if self.blur_fbo != 0 {
glDeleteFramebuffers(1, &self.blur_fbo);
self.blur_fbo = 0;
}
for prog in [&mut self.program, &mut self.direct_program, &mut self.blur_program] {
if *prog != 0 {
glDeleteProgram(*prog);
*prog = 0;
}
}
let _ = eglMakeCurrent(
self.display,
EGL_NO_SURFACE,
EGL_NO_SURFACE,
EGL_NO_CONTEXT,
);
if self.surface != EGL_NO_SURFACE {
let _ = eglDestroySurface(self.display, self.surface);
self.surface = EGL_NO_SURFACE;
}
if self.context != EGL_NO_CONTEXT {
let _ = eglDestroyContext(self.display, self.context);
self.context = EGL_NO_CONTEXT;
}
self.display = EGL_NO_DISPLAY;
}
}
}
}
pub struct EuvAndroidHandle {
app: App,
_state: ShowcaseState,
wid: WindowId,
native_window: *mut ANativeWindow,
egl: Option<EglPresenter>,
surface_generation: u64,
pending_retry_present: bool,
pending_retry_surface_gen: u64,
egl_recovery_attempts: u32,
egl_fallback_software: bool,
submit_failure_count: u64,
target_refresh_hz: f32,
surface_w: u32,
surface_h: u32,
argb: Vec<i32>,
width: u32,
height: u32,
last_step_us: u64,
last_blit_us: u64,
uploaded_glyph_revision: u64,
present_telemetry: AndroidPresentTelemetry,
failover: MobileFailoverController,
}
#[repr(C)]
pub struct ANativeWindow {
_private: [u8; 0],
}
#[repr(C)]
pub struct ANativeWindowBuffer {
pub width: i32,
pub height: i32,
pub stride: i32,
pub format: i32,
pub bits: *mut c_void,
pub reserved: [u32; 6],
}
#[repr(C)]
pub struct ARect {
pub left: i32,
pub top: i32,
pub right: i32,
pub bottom: i32,
}
const WINDOW_FORMAT_RGBA_8888: i32 = 1;
#[link(name = "android")]
unsafe extern "C" {
fn ANativeWindow_fromSurface(env: JniEnv, surface: JObject) -> *mut ANativeWindow;
fn ANativeWindow_release(window: *mut ANativeWindow);
fn ANativeWindow_setBuffersGeometry(
window: *mut ANativeWindow,
width: i32,
height: i32,
format: i32,
) -> i32;
fn ANativeWindow_lock(
window: *mut ANativeWindow,
out_buffer: *mut ANativeWindowBuffer,
in_out_dirty_bounds: *mut ARect,
) -> i32;
fn ANativeWindow_unlockAndPost(window: *mut ANativeWindow) -> i32;
}
impl Drop for EuvAndroidHandle {
fn drop(&mut self) {
if let Some(mut egl) = self.egl.take() {
egl.destroy();
}
if !self.native_window.is_null() {
unsafe { ANativeWindow_release(self.native_window) };
self.native_window = std::ptr::null_mut();
}
}
}
fn copy_rgba_rect_to_native_window(
src: &[u8],
w: usize,
h: usize,
buf: &ANativeWindowBuffer,
dirty: Option<ARect>,
) {
if buf.bits.is_null() || buf.width <= 0 || buf.height <= 0 || buf.stride <= 0 {
return;
}
let copy_w: usize = w.min(buf.width as usize);
let copy_h: usize = h.min(buf.height as usize);
let src_stride: usize = w * 4;
let dst_stride: usize = (buf.stride as usize) * 4;
if copy_w == 0 || copy_h == 0 || src.len() < copy_h * src_stride {
return;
}
let (x0, y0, x1, y1): (usize, usize, usize, usize) = match dirty {
Some(r) => (
(r.left.max(0) as usize).min(copy_w),
(r.top.max(0) as usize).min(copy_h),
(r.right.max(0) as usize).min(copy_w),
(r.bottom.max(0) as usize).min(copy_h),
),
None => (0, 0, copy_w, copy_h),
};
if x0 >= x1 || y0 >= y1 {
return;
}
let dst_ptr: *mut u8 = buf.bits.cast::<u8>();
let row_bytes: usize = (x1 - x0) * 4;
if x0 == 0 && x1 == copy_w && src_stride == dst_stride && copy_w == w {
let start_off: usize = y0 * src_stride;
let total_bytes: usize = (y1 - y0) * row_bytes;
unsafe {
std::ptr::copy_nonoverlapping(
src.as_ptr().add(start_off),
dst_ptr.add(start_off),
total_bytes,
);
}
return;
}
let x_byte: usize = x0 * 4;
for y in y0..y1 {
unsafe {
std::ptr::copy_nonoverlapping(
src.as_ptr().add(y * src_stride + x_byte),
dst_ptr.add(y * dst_stride + x_byte),
row_bytes,
);
}
}
}
#[unsafe(no_mangle)]
pub extern "C" fn Java_vip_ltpp_euv_showcase_EuvNativeBridge_nativeCreate(
env: JniEnv,
cls: JClass,
phys_width: i32,
phys_height: i32,
scale: f32,
refresh_hz: f32,
safe_top: f32,
safe_right: f32,
safe_bottom: f32,
safe_left: f32,
) -> i64 {
if !env.is_null() && !cls.is_null() {
let _init_guard = BRIDGE_INIT_LOCK.lock().ok();
unsafe {
let table: &JniNativeInterface = &*(*env);
if BRIDGE_CLASS_REF.load(Ordering::Acquire).is_null() {
let global_cls: JClass = (table.new_global_ref)(env, cls);
let act_mid: JMethodId = (table.get_static_method_id)(
env,
global_cls,
c"invokeNativeAction".as_ptr(),
c"(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Z".as_ptr(),
);
let glyph_mid: JMethodId = (table.get_static_method_id)(
env,
global_cls,
c"rasterizeGlyph".as_ptr(),
c"(IFI)[B".as_ptr(),
);
if !global_cls.is_null() {
BRIDGE_CLASS_REF.store(global_cls, Ordering::Release);
if !act_mid.is_null() {
ACTION_METHOD.store(act_mid, Ordering::Release);
register_native_action_bridge(android_native_action_bridge);
}
if !glyph_mid.is_null() {
GLYPH_METHOD.store(glyph_mid, Ordering::Release);
register_external_glyph_rasterizer(android_jni_rasterize_glyph);
}
}
}
}
}
let _jni_guard: JniEnvGuard = JniEnvGuard::enter(env);
reset_reactive_runtime();
let Ok((mut app, state)) = create_showcase_app_for_platform(
host_config::HOST_PLATFORM_KIND,
host_config::HOST_RENDER_MODE,
) else {
return 0;
};
app.get_mut_renderer()
.get_mut_software()
.set_font_provider(NativeSystemFont::system());
let hz: f32 = refresh_hz.clamp(MIN_REFRESH_RATE_HZ, MAX_REFRESH_RATE_HZ);
app.update_display_refresh_rate_hz(hz);
let wid: WindowId = app.get_window_state().get_id();
let pw: u32 = phys_width.max(200) as u32;
let ph: u32 = phys_height.max(200) as u32;
let s: f32 = scale.clamp(1.0, 6.0);
app.set_exact_physical_viewport(pw, ph, s);
app.dispatch_window_event(WindowEvent::SafeAreaChanged(
wid,
SafeAreaInsets::new(
safe_top.max(0.0),
safe_right.max(0.0),
safe_bottom.max(0.0),
safe_left.max(0.0),
),
));
let preferred_path: MobilePresentPath = if host_config::HOST_RENDER_MODE == RenderMode::Software {
MobilePresentPath::Software
} else {
MobilePresentPath::GpuDirect
};
let handle = Box::new(EuvAndroidHandle {
app,
_state: state,
wid,
native_window: std::ptr::null_mut(),
egl: None,
surface_generation: 0,
pending_retry_present: false,
pending_retry_surface_gen: 0,
egl_recovery_attempts: 0,
egl_fallback_software: host_config::HOST_RENDER_MODE == RenderMode::Software,
submit_failure_count: 0,
target_refresh_hz: hz,
surface_w: 0,
surface_h: 0,
argb: Vec::new(),
width: 0,
height: 0,
last_step_us: 0,
last_blit_us: 0,
uploaded_glyph_revision: 0,
present_telemetry: AndroidPresentTelemetry::for_path(preferred_path, hz),
failover: MobileFailoverController::for_preferred(
preferred_path,
preferred_path == MobilePresentPath::GpuDirect,
preferred_path != MobilePresentPath::Software,
),
});
Box::into_raw(handle) as i64
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_vip_ltpp_euv_showcase_EuvNativeBridge_nativeDestroy(
env: JniEnv,
_cls: JObject,
ptr: i64,
) {
if ptr == 0 {
return;
}
let _jni_guard: JniEnvGuard = JniEnvGuard::enter(env);
let handle: Box<EuvAndroidHandle> = unsafe { Box::from_raw(ptr as *mut EuvAndroidHandle) };
drop(handle);
reset_reactive_runtime();
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_vip_ltpp_euv_showcase_EuvNativeBridge_nativeIsRunning(
_env: JniEnv,
_cls: JObject,
ptr: i64,
) -> i32 {
if ptr == 0 {
return 0;
}
let h: &EuvAndroidHandle = unsafe { &*(ptr as *const EuvAndroidHandle) };
if h.app.get_running() { 1 } else { 0 }
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_vip_ltpp_euv_showcase_EuvNativeBridge_nativeUpdateRefreshRate(
env: JniEnv,
_cls: JObject,
ptr: i64,
refresh_hz: f32,
) {
if ptr == 0 {
return;
}
let _jni_guard: JniEnvGuard = JniEnvGuard::enter(env);
let h: &mut EuvAndroidHandle = unsafe { &mut *(ptr as *mut EuvAndroidHandle) };
let hz: f32 = refresh_hz.clamp(MIN_REFRESH_RATE_HZ, MAX_REFRESH_RATE_HZ);
h.target_refresh_hz = hz;
h.app.update_display_refresh_rate_hz(hz);
if !h.native_window.is_null() {
let _: bool = euv::android_set_native_window_frame_rate(h.native_window as usize, hz);
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_vip_ltpp_euv_showcase_EuvNativeBridge_nativeSetSurface(
env: JniEnv,
_cls: JObject,
ptr: i64,
surface: JObject,
phys_width: i32,
phys_height: i32,
scale: f32,
) {
if ptr == 0 {
return;
}
let _jni_guard: JniEnvGuard = JniEnvGuard::enter(env);
let h: &mut EuvAndroidHandle = unsafe { &mut *(ptr as *mut EuvAndroidHandle) };
h.surface_generation = h.surface_generation.wrapping_add(1);
h.pending_retry_present = false;
h.pending_retry_surface_gen = h.surface_generation;
h.egl_recovery_attempts = 0;
if let Some(mut egl) = h.egl.take() {
egl.destroy();
}
if !h.native_window.is_null() {
unsafe { ANativeWindow_release(h.native_window) };
h.native_window = std::ptr::null_mut();
h.surface_w = 0;
h.surface_h = 0;
h.failover.set_surface_valid(false);
}
if !surface.is_null() && phys_width > 0 && phys_height > 0 {
let win: *mut ANativeWindow = unsafe { ANativeWindow_fromSurface(env, surface) };
if !win.is_null() {
let pw: u32 = phys_width.max(200) as u32;
let ph: u32 = phys_height.max(200) as u32;
let s: f32 = scale.clamp(1.0, 4.5);
let _: bool = euv::android_set_native_window_frame_rate(win as usize, h.target_refresh_hz);
let sw_only: bool = host_config::HOST_RENDER_MODE == RenderMode::Software;
h.egl_fallback_software = sw_only;
h.uploaded_glyph_revision = 0;
if !sw_only {
h.egl = EglPresenter::create(win, pw, ph);
}
let direct_ok: bool = h.egl.as_ref().map(EglPresenter::has_direct_pipeline).unwrap_or(false);
let upload_ok: bool = h.egl.is_some();
if let Some(egl) = h.egl.as_ref() {
h.present_telemetry
.set_egl_extension_present_time(egl.egl_presentation_time_android.is_some());
h.present_telemetry
.set_egl_extension_swap_damage(egl.egl_swap_with_damage_khr.is_some());
}
let preferred_path: MobilePresentPath = if sw_only {
MobilePresentPath::Software
} else {
MobilePresentPath::GpuDirect
};
h.failover = MobileFailoverController::for_preferred(preferred_path, direct_ok, upload_ok);
h.failover.set_surface_valid(true);
let use_direct_gpu: bool = h.failover.get_active_path() == MobilePresentPath::GpuDirect;
h.app.get_mut_renderer().set_direct_gpu_present(use_direct_gpu);
if !upload_ok {
unsafe {
let _ = ANativeWindow_setBuffersGeometry(
win,
pw as i32,
ph as i32,
WINDOW_FORMAT_RGBA_8888,
);
}
}
h.native_window = win;
h.surface_w = pw;
h.surface_h = ph;
h.app.set_exact_physical_viewport(pw, ph, s);
}
}
}
fn present_android_software_fallback(
h: &mut EuvAndroidHandle,
pixels: &[u8],
w: u32,
ht: u32,
plan: &AdaptiveUploadPlan,
) -> bool {
if h.native_window.is_null() || w == 0 || ht == 0 {
return false;
}
if h.surface_w != w || h.surface_h != ht {
unsafe {
let _ = ANativeWindow_setBuffersGeometry(
h.native_window,
w as i32,
ht as i32,
WINDOW_FORMAT_RGBA_8888,
);
}
h.surface_w = w;
h.surface_h = ht;
}
let mut buf: ANativeWindowBuffer = ANativeWindowBuffer {
width: 0,
height: 0,
stride: 0,
format: 0,
bits: std::ptr::null_mut(),
reserved: [0; 6],
};
let lock_rc: i32 = unsafe {
ANativeWindow_lock(h.native_window, &mut buf, std::ptr::null_mut())
};
if lock_rc != 0 || buf.bits.is_null() {
return false;
}
if plan.get_strategy() == MobileUploadStrategy::FullFrame || plan.get_rects().is_empty() {
copy_rgba_rect_to_native_window(pixels, w as usize, ht as usize, &buf, None);
} else {
for r in plan.get_rects().iter() {
let dirty: ARect = ARect {
left: r.get_x() as i32,
top: r.get_y() as i32,
right: r.right() as i32,
bottom: r.bottom() as i32,
};
copy_rgba_rect_to_native_window(pixels, w as usize, ht as usize, &buf, Some(dirty));
}
}
let post_rc: i32 = unsafe { ANativeWindow_unlockAndPost(h.native_window) };
post_rc == 0
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_vip_ltpp_euv_showcase_EuvNativeBridge_nativeStepSurfaceWithTimestamp(
env: JniEnv,
_cls: JObject,
ptr: i64,
dt: f32,
force_present: i32,
choreographer_frame_time_ns: i64,
) -> i32 {
if ptr == 0 {
return 0;
}
let _jni_guard: JniEnvGuard = JniEnvGuard::enter(env);
let h: &mut EuvAndroidHandle = unsafe { &mut *(ptr as *mut EuvAndroidHandle) };
if choreographer_frame_time_ns > 0 {
h.present_telemetry
.record_choreographer_frame(choreographer_frame_time_ns as u64, h.target_refresh_hz);
}
let t_step = std::time::Instant::now();
let step_res = h.app.step_game_frame(dt.clamp(1.0 / MAX_REFRESH_RATE_HZ, 0.05));
h.last_step_us = t_step.elapsed().as_micros() as u64;
let Ok(stats) = step_res else {
return 0;
};
let retry_needed: bool =
h.pending_retry_present && h.pending_retry_surface_gen == h.surface_generation;
let changed: bool = stats.get_pixels_shaded() > 0
|| stats.get_draw_commands() > 0
|| h.width == 0
|| force_present != 0
|| retry_needed;
if !changed || h.native_window.is_null() {
h.last_blit_us = 0;
return 0;
}
let t_blit = std::time::Instant::now();
let mut submitted: bool = false;
if h.failover.get_active_path() == MobilePresentPath::GpuDirect && h.egl.is_some() {
let direct_batch: DirectGpuFrameBatch = {
let renderer = h.app.get_mut_renderer();
let dl_clone = renderer.get_display_list().clone();
let font_provider: NativeSystemFont =
renderer.get_font_service().get_font_provider().clone();
let glyph_atlas = renderer.get_mut_font_service().get_mut_glyph_atlas();
compile_display_list_direct_gpu_batch(
&dl_clone,
Some(glyph_atlas),
Some(&font_provider),
h.uploaded_glyph_revision,
)
};
h.width = direct_batch.get_viewport_width();
h.height = direct_batch.get_viewport_height();
let (egl_status, egl_ts) = if let Some(egl) = h.egl.as_mut() {
egl.present_direct_gpu(&direct_batch)
} else {
(EglPresentStatus::Failed, None)
};
if egl_status == EglPresentStatus::Presented {
if let Some(atlas) = direct_batch.glyph_r8_atlas_ref() {
h.uploaded_glyph_revision = atlas.get_revision();
}
let blit_us: u64 = t_blit.elapsed().as_micros() as u64;
h.failover.mark_frame_presented();
h.present_telemetry
.record_direct_gpu_present(&direct_batch, egl_ts, blit_us);
submitted = true;
} else {
let fault: MobileSurfaceFault = if egl_status == EglPresentStatus::ContextLost {
MobileSurfaceFault::ContextLost
} else {
MobileSurfaceFault::SubmitFailed
};
let action: MobileFailoverAction = h
.present_telemetry
.record_fault_with_failover(fault, &mut h.failover);
if fault == MobileSurfaceFault::ContextLost {
if let Some(mut stale) = h.egl.take() {
stale.destroy();
}
h.egl_fallback_software = true;
}
if matches!(action, MobileFailoverAction::KeepLastFrameAndSwitch(_)) {
h.app.get_mut_renderer().set_direct_gpu_present(false);
let _ = h
.app
.get_mut_renderer()
.capture_reference_framebuffer(DamageRegion::full());
}
}
}
if !submitted && h.failover.get_active_path() != MobilePresentPath::GpuDirect {
h.app.get_mut_renderer().set_direct_gpu_present(false);
if h.app.get_renderer().framebuffer().is_none() {
let _ = h
.app
.get_mut_renderer()
.capture_reference_framebuffer(DamageRegion::full());
}
if let Some(fb) = h.app.get_renderer().framebuffer() {
let w: u32 = fb.get_width();
let ht: u32 = fb.get_height();
let pixels: Vec<u8> = fb.get_pixels().to_vec();
h.width = w;
h.height = ht;
if w > 0 && ht > 0 {
let dmg = h.app.last_frame_damage();
let dirty_rects: Vec<PixelDirtyRect> =
damage_region_to_pixel_dirty_rects(dmg, w, ht);
let force_full: bool = force_present != 0 || retry_needed || dmg.get_full_damage();
let plan: AdaptiveUploadPlan =
select_adaptive_upload_plan(w, ht, &dirty_rects, force_full);
if h.failover.get_active_path() == MobilePresentPath::GpuUpload
&& !h.egl_fallback_software
{
let (egl_status, egl_ts) = if let Some(egl) = h.egl.as_mut() {
egl.present_upload_plan(&pixels, w, ht, &plan)
} else {
(EglPresentStatus::Failed, None)
};
if egl_status == EglPresentStatus::Presented {
let blit_us: u64 = t_blit.elapsed().as_micros() as u64;
h.failover.mark_frame_presented();
h.present_telemetry
.record_gpu_upload_present(&plan, egl_ts, blit_us);
submitted = true;
} else {
let fault: MobileSurfaceFault =
if egl_status == EglPresentStatus::ContextLost {
MobileSurfaceFault::ContextLost
} else {
MobileSurfaceFault::SubmitFailed
};
let _: MobileFailoverAction = h
.present_telemetry
.record_fault_with_failover(fault, &mut h.failover);
if fault == MobileSurfaceFault::ContextLost {
if let Some(mut stale) = h.egl.take() {
stale.destroy();
}
h.egl_fallback_software = true;
}
}
}
if !submitted {
if present_android_software_fallback(h, &pixels, w, ht, &plan) {
let copy_us: u64 = t_blit.elapsed().as_micros() as u64;
h.failover.mark_frame_presented();
h.present_telemetry.record_software_present(&plan, copy_us);
submitted = true;
}
}
}
}
}
h.last_blit_us = t_blit.elapsed().as_micros() as u64;
if submitted {
h.pending_retry_present = false;
1
} else {
h.pending_retry_present = true;
h.pending_retry_surface_gen = h.surface_generation;
h.submit_failure_count = h.submit_failure_count.saturating_add(1);
-1
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_vip_ltpp_euv_showcase_EuvNativeBridge_nativeStepSurface(
env: JniEnv,
cls: JObject,
ptr: i64,
dt: f32,
force_present: i32,
) -> i32 {
unsafe {
Java_vip_ltpp_euv_showcase_EuvNativeBridge_nativeStepSurfaceWithTimestamp(
env,
cls,
ptr,
dt,
force_present,
0,
)
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_vip_ltpp_euv_showcase_EuvNativeBridge_nativeRotaryScroll(
env: JniEnv,
_cls: JObject,
ptr: i64,
dx: f32,
dy: f32,
) {
if ptr == 0 {
return;
}
let _jni_guard: JniEnvGuard = JniEnvGuard::enter(env);
let h: &mut EuvAndroidHandle = unsafe { &mut *(ptr as *mut EuvAndroidHandle) };
let clean_x: f32 = if dx.is_finite() { dx } else { 0.0 };
let clean_y: f32 = if dy.is_finite() { dy } else { 0.0 };
h.app
.dispatch_window_event(WindowEvent::Scroll(h.wid, Point::new(clean_x, clean_y)));
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_vip_ltpp_euv_showcase_EuvNativeBridge_nativeAmbientModeChanged(
env: JniEnv,
_cls: JObject,
ptr: i64,
ambient: i32,
) {
if ptr == 0 {
return;
}
let _jni_guard: JniEnvGuard = JniEnvGuard::enter(env);
let h: &mut EuvAndroidHandle = unsafe { &mut *(ptr as *mut EuvAndroidHandle) };
let is_ambient: bool = ambient != 0;
h.app
.dispatch_system_event(SystemEvent::LowPowerModeChanged(is_ambient));
if is_ambient {
h.app.dispatch_system_event(SystemEvent::Inactive);
} else {
h.app.dispatch_system_event(SystemEvent::Foreground);
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_vip_ltpp_euv_showcase_EuvNativeBridge_nativeGetLastStepUs(
_env: JniEnv,
_cls: JObject,
ptr: i64,
) -> i64 {
if ptr == 0 {
return 0;
}
let h: &EuvAndroidHandle = unsafe { &*(ptr as *const EuvAndroidHandle) };
h.last_step_us as i64
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_vip_ltpp_euv_showcase_EuvNativeBridge_nativeGetLastBlitUs(
_env: JniEnv,
_cls: JObject,
ptr: i64,
) -> i64 {
if ptr == 0 {
return 0;
}
let h: &EuvAndroidHandle = unsafe { &*(ptr as *const EuvAndroidHandle) };
h.last_blit_us as i64
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_vip_ltpp_euv_showcase_EuvNativeBridge_nativeGetCpuMirrorActive(
_env: JniEnv,
_cls: JObject,
ptr: i64,
) -> i32 {
if ptr == 0 {
return 1;
}
let h: &EuvAndroidHandle = unsafe { &*(ptr as *const EuvAndroidHandle) };
if h.present_telemetry.get_base().get_cpu_mirror_active() { 1 } else { 0 }
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_vip_ltpp_euv_showcase_EuvNativeBridge_nativeGetActivePresentPath(
_env: JniEnv,
_cls: JObject,
ptr: i64,
) -> i32 {
if ptr == 0 {
return MobilePresentPath::Software as i32;
}
let h: &EuvAndroidHandle = unsafe { &*(ptr as *const EuvAndroidHandle) };
h.present_telemetry.get_base().get_active_path() as i32
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_vip_ltpp_euv_showcase_EuvNativeBridge_nativeGetUploadStrategy(
_env: JniEnv,
_cls: JObject,
ptr: i64,
) -> i32 {
if ptr == 0 {
return MobileUploadStrategy::None as i32;
}
let h: &EuvAndroidHandle = unsafe { &*(ptr as *const EuvAndroidHandle) };
h.present_telemetry.get_base().get_upload_strategy() as i32
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_vip_ltpp_euv_showcase_EuvNativeBridge_nativeGetLastUploadBytes(
_env: JniEnv,
_cls: JObject,
ptr: i64,
) -> i64 {
if ptr == 0 {
return 0;
}
let h: &EuvAndroidHandle = unsafe { &*(ptr as *const EuvAndroidHandle) };
h.present_telemetry.get_base().get_upload_bytes_last_frame() as i64
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_vip_ltpp_euv_showcase_EuvNativeBridge_nativeGetSubmitFailures(
_env: JniEnv,
_cls: JObject,
ptr: i64,
) -> i64 {
if ptr == 0 {
return 0;
}
let h: &EuvAndroidHandle = unsafe { &*(ptr as *const EuvAndroidHandle) };
h.present_telemetry.get_base().get_submit_failures() as i64
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_vip_ltpp_euv_showcase_EuvNativeBridge_nativeGetPresentFailures(
_env: JniEnv,
_cls: JObject,
ptr: i64,
) -> i64 {
if ptr == 0 {
return 0;
}
let h: &EuvAndroidHandle = unsafe { &*(ptr as *const EuvAndroidHandle) };
h.present_telemetry.get_base().get_present_failures() as i64
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_vip_ltpp_euv_showcase_EuvNativeBridge_nativeGetLastPresentTimestampNs(
_env: JniEnv,
_cls: JObject,
ptr: i64,
) -> i64 {
if ptr == 0 {
return -1;
}
let h: &EuvAndroidHandle = unsafe { &*(ptr as *const EuvAndroidHandle) };
match h.present_telemetry.try_get_egl_presentation_time_ns() {
Some(ts) => ts as i64,
None => -1,
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_vip_ltpp_euv_showcase_EuvNativeBridge_nativeResize(
env: JniEnv,
_cls: JObject,
ptr: i64,
phys_width: i32,
phys_height: i32,
scale: f32,
) {
if ptr == 0 {
return;
}
let _jni_guard: JniEnvGuard = JniEnvGuard::enter(env);
let h: &mut EuvAndroidHandle = unsafe { &mut *(ptr as *mut EuvAndroidHandle) };
let pw: u32 = phys_width.max(200) as u32;
let ph: u32 = phys_height.max(200) as u32;
let s: f32 = scale.clamp(1.0, 4.5);
h.app.set_exact_physical_viewport(pw, ph, s);
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_vip_ltpp_euv_showcase_EuvNativeBridge_nativeSetSafeArea(
env: JniEnv,
_cls: JObject,
ptr: i64,
top: f32,
right: f32,
bottom: f32,
left: f32,
) {
if ptr == 0 {
return;
}
let _jni_guard: JniEnvGuard = JniEnvGuard::enter(env);
let h: &mut EuvAndroidHandle = unsafe { &mut *(ptr as *mut EuvAndroidHandle) };
h.app.dispatch_window_event(WindowEvent::SafeAreaChanged(
h.wid,
SafeAreaInsets::new(top.max(0.0), right.max(0.0), bottom.max(0.0), left.max(0.0)),
));
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_vip_ltpp_euv_showcase_EuvNativeBridge_nativeTouchDown(
env: JniEnv,
_cls: JObject,
ptr: i64,
pointer_id: i32,
x: f32,
y: f32,
) {
if ptr == 0 {
return;
}
let _jni_guard: JniEnvGuard = JniEnvGuard::enter(env);
let h: &mut EuvAndroidHandle = unsafe { &mut *(ptr as *mut EuvAndroidHandle) };
h.app.dispatch_window_event(WindowEvent::PointerDown(
h.wid,
PointerEvent::touch((pointer_id as u64).saturating_add(1), x, y),
));
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_vip_ltpp_euv_showcase_EuvNativeBridge_nativeTouchMove(
env: JniEnv,
_cls: JObject,
ptr: i64,
pointer_id: i32,
x: f32,
y: f32,
) {
if ptr == 0 {
return;
}
let _jni_guard: JniEnvGuard = JniEnvGuard::enter(env);
let h: &mut EuvAndroidHandle = unsafe { &mut *(ptr as *mut EuvAndroidHandle) };
h.app.dispatch_window_event(WindowEvent::PointerMove(
h.wid,
PointerEvent::touch((pointer_id as u64).saturating_add(1), x, y),
));
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_vip_ltpp_euv_showcase_EuvNativeBridge_nativeTouchUp(
env: JniEnv,
_cls: JObject,
ptr: i64,
pointer_id: i32,
x: f32,
y: f32,
) {
if ptr == 0 {
return;
}
let _jni_guard: JniEnvGuard = JniEnvGuard::enter(env);
let h: &mut EuvAndroidHandle = unsafe { &mut *(ptr as *mut EuvAndroidHandle) };
h.app.dispatch_window_event(WindowEvent::PointerUp(
h.wid,
PointerEvent::touch((pointer_id as u64).saturating_add(1), x, y),
));
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_vip_ltpp_euv_showcase_EuvNativeBridge_nativeTouchCancel(
env: JniEnv,
_cls: JObject,
ptr: i64,
pointer_id: i32,
) {
if ptr == 0 {
return;
}
let _jni_guard: JniEnvGuard = JniEnvGuard::enter(env);
let h: &mut EuvAndroidHandle = unsafe { &mut *(ptr as *mut EuvAndroidHandle) };
let mapped_id: u64 = if pointer_id < 0 {
0
} else {
(pointer_id as u64).saturating_add(1)
};
h.app
.dispatch_window_event(WindowEvent::PointerCancel(h.wid, mapped_id));
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_vip_ltpp_euv_showcase_EuvNativeBridge_nativeFlushTouchBatch(
env: JniEnv,
_cls: JObject,
ptr: i64,
direct_buf: JObject,
count: i32,
active_mask: i64,
) {
if ptr == 0 || env.is_null() || direct_buf.is_null() {
return;
}
let _jni_guard: JniEnvGuard = JniEnvGuard::enter(env);
let h: &mut EuvAndroidHandle = unsafe { &mut *(ptr as *mut EuvAndroidHandle) };
let rec_count: usize = count.max(0) as usize;
let byte_len: usize = rec_count.saturating_mul(euv::ANDROID_TOUCH_BATCH_RECORD_BYTES);
if byte_len > 0 {
unsafe {
let table: &JniNativeInterface = &*(*env);
let raw_ptr: *mut c_void = (table.get_direct_buffer_address)(env, direct_buf);
let cap: i64 = (table.get_direct_buffer_capacity)(env, direct_buf);
if !raw_ptr.is_null() && cap >= byte_len as i64 {
let bytes: &[u8] = std::slice::from_raw_parts(raw_ptr.cast::<u8>(), byte_len);
let entries: Vec<euv::AndroidTouchBatchEntry> =
euv::android_decode_touch_batch(bytes);
for entry in entries.into_iter() {
let pid: u64 = (entry.get_pointer_id().max(0) as u64).saturating_add(1);
let x: f32 = entry.get_x();
let y: f32 = entry.get_y();
match entry.get_action() {
0 | 5 => {
h.app.dispatch_window_event(WindowEvent::PointerDown(
h.wid,
PointerEvent::touch(pid, x, y),
));
}
2 => {
h.app.dispatch_window_event(WindowEvent::PointerMove(
h.wid,
PointerEvent::touch(pid, x, y),
));
}
1 | 6 => {
h.app.dispatch_window_event(WindowEvent::PointerUp(
h.wid,
PointerEvent::touch(pid, x, y),
));
}
3 => {
let cancel_id: u64 = if entry.get_pointer_id() < 0 { 0 } else { pid };
h.app.dispatch_window_event(WindowEvent::PointerCancel(
h.wid,
cancel_id,
));
}
_ => {}
}
}
}
}
}
let bits: u64 = active_mask as u64;
let mut live_ids: Vec<u64> = Vec::with_capacity(bits.count_ones() as usize);
for bit in 0_u64..63_u64 {
if (bits & (1_u64 << bit)) != 0 {
live_ids.push(bit + 1);
}
}
h.app.reconcile_active_touch_ids(&live_ids);
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_vip_ltpp_euv_showcase_EuvNativeBridge_nativeTouchSyncMask(
env: JniEnv,
_cls: JObject,
ptr: i64,
active_mask: i64,
) {
if ptr == 0 {
return;
}
let _jni_guard: JniEnvGuard = JniEnvGuard::enter(env);
let h: &mut EuvAndroidHandle = unsafe { &mut *(ptr as *mut EuvAndroidHandle) };
let bits: u64 = active_mask as u64;
let mut live_ids: Vec<u64> = Vec::with_capacity(bits.count_ones() as usize);
for bit in 0_u64..63_u64 {
if (bits & (1_u64 << bit)) != 0 {
live_ids.push(bit + 1);
}
}
h.app.reconcile_active_touch_ids(&live_ids);
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_vip_ltpp_euv_showcase_EuvNativeBridge_nativeImeDisabled(
env: JniEnv,
_cls: JObject,
ptr: i64,
) {
if ptr == 0 {
return;
}
let _jni_guard: JniEnvGuard = JniEnvGuard::enter(env);
let h: &mut EuvAndroidHandle = unsafe { &mut *(ptr as *mut EuvAndroidHandle) };
h.app
.dispatch_window_event(WindowEvent::Ime(h.wid, ImeEvent::Disabled));
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_vip_ltpp_euv_showcase_EuvNativeBridge_nativeSystemBack(
env: JniEnv,
_cls: JObject,
ptr: i64,
) {
if ptr == 0 {
return;
}
let _jni_guard: JniEnvGuard = JniEnvGuard::enter(env);
let h: &mut EuvAndroidHandle = unsafe { &mut *(ptr as *mut EuvAndroidHandle) };
h.app.dispatch_window_event(WindowEvent::KeyDown(
h.wid,
KeyEvent::new(KeyCode::Back, Modifiers::default(), false),
));
}
fn read_jni_utf8(env: JniEnv, utf8_bytes: JByteArray) -> Option<String> {
if env.is_null() || utf8_bytes.is_null() {
return None;
}
unsafe {
let table: &JniNativeInterface = &*(*env);
let len: i32 = (table.get_array_length)(env, utf8_bytes);
if len > 0 {
let mut buf: Vec<u8> = vec![0; len as usize];
(table.get_byte_array_region)(env, utf8_bytes, 0, len, buf.as_mut_ptr().cast::<i8>());
String::from_utf8(buf).ok()
} else {
None
}
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_vip_ltpp_euv_showcase_EuvNativeBridge_nativeSystemLifecycle(
env: JniEnv,
_cls: JObject,
ptr: i64,
tag: i32,
) {
if ptr == 0 {
return;
}
let ev: SystemEvent = match tag {
1 => SystemEvent::Appear,
2 => SystemEvent::Disappear,
3 => SystemEvent::Foreground,
4 => SystemEvent::Inactive,
5 => SystemEvent::Background,
6 => SystemEvent::Terminate,
_ => return,
};
let _jni_guard: JniEnvGuard = JniEnvGuard::enter(env);
let h: &mut EuvAndroidHandle = unsafe { &mut *(ptr as *mut EuvAndroidHandle) };
h.app.dispatch_system_event(ev);
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_vip_ltpp_euv_showcase_EuvNativeBridge_nativeFocusChanged(
env: JniEnv,
_cls: JObject,
ptr: i64,
focused: i32,
) {
if ptr == 0 {
return;
}
let _jni_guard: JniEnvGuard = JniEnvGuard::enter(env);
let h: &mut EuvAndroidHandle = unsafe { &mut *(ptr as *mut EuvAndroidHandle) };
h.app
.dispatch_system_event(SystemEvent::FocusChanged(focused != 0));
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_vip_ltpp_euv_showcase_EuvNativeBridge_nativeKeyboardChanged(
env: JniEnv,
_cls: JObject,
ptr: i64,
visible: i32,
height: f32,
) {
if ptr == 0 {
return;
}
let _jni_guard: JniEnvGuard = JniEnvGuard::enter(env);
let h: &mut EuvAndroidHandle = unsafe { &mut *(ptr as *mut EuvAndroidHandle) };
h.app
.dispatch_system_event(SystemEvent::KeyboardVisibilityChanged {
visible: visible != 0,
height: height.max(0.0),
});
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_vip_ltpp_euv_showcase_EuvNativeBridge_nativeThemeChanged(
env: JniEnv,
_cls: JObject,
ptr: i64,
is_dark: i32,
) {
if ptr == 0 {
return;
}
let _jni_guard: JniEnvGuard = JniEnvGuard::enter(env);
let h: &mut EuvAndroidHandle = unsafe { &mut *(ptr as *mut EuvAndroidHandle) };
let mode: ThemeMode = if is_dark != 0 {
ThemeMode::Dark
} else {
ThemeMode::Light
};
h.app.dispatch_system_event(SystemEvent::ThemeChanged(mode));
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_vip_ltpp_euv_showcase_EuvNativeBridge_nativeMemoryWarning(
env: JniEnv,
_cls: JObject,
ptr: i64,
level: i32,
) {
if ptr == 0 {
return;
}
let pressure: MemoryPressure = if level >= 2 {
MemoryPressure::Critical
} else {
MemoryPressure::Warning
};
let _jni_guard: JniEnvGuard = JniEnvGuard::enter(env);
let h: &mut EuvAndroidHandle = unsafe { &mut *(ptr as *mut EuvAndroidHandle) };
h.app
.dispatch_system_event(SystemEvent::MemoryWarning(pressure));
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_vip_ltpp_euv_showcase_EuvNativeBridge_nativeLowPowerChanged(
env: JniEnv,
_cls: JObject,
ptr: i64,
enabled: i32,
) {
if ptr == 0 {
return;
}
let _jni_guard: JniEnvGuard = JniEnvGuard::enter(env);
let h: &mut EuvAndroidHandle = unsafe { &mut *(ptr as *mut EuvAndroidHandle) };
h.app
.dispatch_system_event(SystemEvent::LowPowerModeChanged(enabled != 0));
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_vip_ltpp_euv_showcase_EuvNativeBridge_nativeNetworkChanged(
env: JniEnv,
_cls: JObject,
ptr: i64,
status_tag: i32,
) {
if ptr == 0 {
return;
}
let status: NetworkStatus = match status_tag {
0 => NetworkStatus::Offline,
1 => NetworkStatus::Online,
2 => NetworkStatus::Wifi,
3 => NetworkStatus::Cellular,
_ => NetworkStatus::Unknown,
};
let _jni_guard: JniEnvGuard = JniEnvGuard::enter(env);
let h: &mut EuvAndroidHandle = unsafe { &mut *(ptr as *mut EuvAndroidHandle) };
h.app
.dispatch_system_event(SystemEvent::NetworkStatusChanged(status));
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_vip_ltpp_euv_showcase_EuvNativeBridge_nativeLocaleChanged(
env: JniEnv,
_cls: JObject,
ptr: i64,
utf8_bytes: JByteArray,
) {
if ptr == 0 {
return;
}
let _jni_guard: JniEnvGuard = JniEnvGuard::enter(env);
let h: &mut EuvAndroidHandle = unsafe { &mut *(ptr as *mut EuvAndroidHandle) };
if let Some(locale) = read_jni_utf8(env, utf8_bytes)
&& !locale.is_empty()
{
h.app
.dispatch_system_event(SystemEvent::LocaleChanged(locale));
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_vip_ltpp_euv_showcase_EuvNativeBridge_nativeDeepLink(
env: JniEnv,
_cls: JObject,
ptr: i64,
utf8_bytes: JByteArray,
) {
if ptr == 0 {
return;
}
let _jni_guard: JniEnvGuard = JniEnvGuard::enter(env);
let h: &mut EuvAndroidHandle = unsafe { &mut *(ptr as *mut EuvAndroidHandle) };
if let Some(uri) = read_jni_utf8(env, utf8_bytes)
&& !uri.is_empty()
{
h.app.dispatch_system_event(SystemEvent::DeepLink(uri));
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_vip_ltpp_euv_showcase_EuvNativeBridge_nativeClipboardChanged(
env: JniEnv,
_cls: JObject,
ptr: i64,
) {
if ptr == 0 {
return;
}
let _jni_guard: JniEnvGuard = JniEnvGuard::enter(env);
let h: &mut EuvAndroidHandle = unsafe { &mut *(ptr as *mut EuvAndroidHandle) };
h.app.dispatch_system_event(SystemEvent::ClipboardChanged);
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_vip_ltpp_euv_showcase_EuvNativeBridge_nativeDeviceMotion(
env: JniEnv,
_cls: JObject,
ptr: i64,
gx: f32,
gy: f32,
gz: f32,
lx: f32,
ly: f32,
lz: f32,
wx: f32,
wy: f32,
wz: f32,
pitch: f32,
roll: f32,
yaw: f32,
timestamp_ns: i64,
) {
if ptr == 0 {
return;
}
let _jni_guard: JniEnvGuard = JniEnvGuard::enter(env);
let h: &mut EuvAndroidHandle = unsafe { &mut *(ptr as *mut EuvAndroidHandle) };
let sample: DeviceMotionSample = DeviceMotionSample::from_vectors(
[gx, gy, gz],
[lx, ly, lz],
[wx, wy, wz],
[pitch, roll, yaw],
timestamp_ns.max(0) as u64,
true,
);
h.app
.dispatch_window_event(WindowEvent::System(SystemEvent::DeviceMotion(sample)));
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_vip_ltpp_euv_showcase_EuvNativeBridge_nativeTextInput(
env: JniEnv,
_cls: JObject,
ptr: i64,
utf8_bytes: JByteArray,
) {
if ptr == 0 || env.is_null() || utf8_bytes.is_null() {
return;
}
let _jni_guard: JniEnvGuard = JniEnvGuard::enter(env);
let h: &mut EuvAndroidHandle = unsafe { &mut *(ptr as *mut EuvAndroidHandle) };
let text_opt: Option<String> = unsafe {
let table: &JniNativeInterface = &*(*env);
let len: i32 = (table.get_array_length)(env, utf8_bytes);
if len > 0 {
let mut buf: Vec<u8> = vec![0; len as usize];
(table.get_byte_array_region)(env, utf8_bytes, 0, len, buf.as_mut_ptr().cast::<i8>());
String::from_utf8(buf).ok()
} else {
None
}
};
if let Some(text) = text_opt
&& !text.is_empty()
{
h.app
.dispatch_window_event(WindowEvent::TextInput(h.wid, text));
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_vip_ltpp_euv_showcase_EuvNativeBridge_nativeKeyDown(
env: JniEnv,
_cls: JObject,
ptr: i64,
key_tag: i32,
) {
if ptr == 0 {
return;
}
let code: KeyCode = match key_tag {
1 => KeyCode::Backspace,
2 => KeyCode::Enter,
3 => KeyCode::Tab,
4 => KeyCode::Escape,
_ => return,
};
let _jni_guard: JniEnvGuard = JniEnvGuard::enter(env);
let h: &mut EuvAndroidHandle = unsafe { &mut *(ptr as *mut EuvAndroidHandle) };
h.app.dispatch_window_event(WindowEvent::KeyDown(
h.wid,
KeyEvent::new(code, Modifiers::default(), false),
));
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_vip_ltpp_euv_showcase_EuvNativeBridge_nativeCopyFramebufferDirect(
env: JniEnv,
_cls: JObject,
ptr: i64,
out_rgba: JObject,
max_bytes: i32,
) -> i32 {
if ptr == 0 || env.is_null() || out_rgba.is_null() || max_bytes <= 0 {
return 0;
}
let h: &mut EuvAndroidHandle = unsafe { &mut *(ptr as *mut EuvAndroidHandle) };
if let Some(fb) = h.app.get_renderer().framebuffer() {
let w: u32 = fb.get_width();
let ht: u32 = fb.get_height();
let src: &[u8] = fb.get_pixels().as_slice();
let byte_count: usize = (w as usize) * (ht as usize) * 4;
h.width = w;
h.height = ht;
unsafe {
let table: &JniNativeInterface = &*(*env);
let dst_ptr: *mut c_void = (table.get_direct_buffer_address)(env, out_rgba);
let cap: i64 = (table.get_direct_buffer_capacity)(env, out_rgba);
if !dst_ptr.is_null() && cap >= byte_count as i64 && (max_bytes as usize) >= byte_count && src.len() >= byte_count {
std::ptr::copy_nonoverlapping(src.as_ptr(), dst_ptr.cast::<u8>(), byte_count);
return 1;
}
}
}
0
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_vip_ltpp_euv_showcase_EuvNativeBridge_nativeStepFrameDirect(
env: JniEnv,
_cls: JObject,
ptr: i64,
dt: f32,
out_rgba: JObject,
max_bytes: i32,
) -> i32 {
if ptr == 0 || env.is_null() || out_rgba.is_null() || max_bytes <= 0 {
return 0;
}
let h: &mut EuvAndroidHandle = unsafe { &mut *(ptr as *mut EuvAndroidHandle) };
let step_res = {
let _jni_guard: JniEnvGuard = JniEnvGuard::enter(env);
h.app.step_game_frame(dt.clamp(1.0 / MAX_REFRESH_RATE_HZ, 0.05))
};
let Ok(stats) = step_res else {
return 0;
};
let changed: bool = stats.get_pixels_shaded() > 0 || h.width == 0;
if changed && let Some(fb) = h.app.get_renderer().framebuffer() {
let w: u32 = fb.get_width();
let ht: u32 = fb.get_height();
let src: &[u8] = fb.get_pixels().as_slice();
let byte_count: usize = (w as usize) * (ht as usize) * 4;
h.width = w;
h.height = ht;
unsafe {
let table: &JniNativeInterface = &*(*env);
let dst_ptr: *mut c_void = (table.get_direct_buffer_address)(env, out_rgba);
let cap: i64 = (table.get_direct_buffer_capacity)(env, out_rgba);
if !dst_ptr.is_null() && cap > 0 {
let copy_len: usize = byte_count
.min(src.len())
.min(max_bytes as usize)
.min(cap as usize);
if copy_len > 0 {
std::ptr::copy_nonoverlapping(src.as_ptr(), dst_ptr.cast::<u8>(), copy_len);
}
}
}
}
if changed { 1 } else { 0 }
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_vip_ltpp_euv_showcase_EuvNativeBridge_nativeStepFrame(
env: JniEnv,
_cls: JObject,
ptr: i64,
dt: f32,
out_pixels: JIntArray,
max_len: i32,
) -> i32 {
if ptr == 0 || env.is_null() || out_pixels.is_null() {
return 0;
}
let h: &mut EuvAndroidHandle = unsafe { &mut *(ptr as *mut EuvAndroidHandle) };
let step_res = {
let _jni_guard: JniEnvGuard = JniEnvGuard::enter(env);
h.app.step_game_frame(dt.clamp(1.0 / MAX_REFRESH_RATE_HZ, 0.05))
};
let Ok(stats) = step_res else {
return 0;
};
let changed: bool = stats.get_pixels_shaded() > 0 || h.argb.is_empty();
if changed && let Some(fb) = h.app.get_renderer().framebuffer() {
let w: u32 = fb.get_width();
let ht: u32 = fb.get_height();
let src: &[u8] = fb.get_pixels().as_slice();
let pixel_count: usize = (w as usize) * (ht as usize);
h.width = w;
h.height = ht;
h.argb.resize(pixel_count, 0);
for (idx, chunk) in src.chunks_exact(4).take(pixel_count).enumerate() {
let r: u32 = chunk[0] as u32;
let g: u32 = chunk[1] as u32;
let b: u32 = chunk[2] as u32;
let a: u32 = chunk[3] as u32;
h.argb[idx] = ((a << 24) | (r << 16) | (g << 8) | b) as i32;
}
let copy_len: i32 = (pixel_count as i32).min(max_len);
if copy_len > 0 {
unsafe {
let table: &JniNativeInterface = &*(*env);
(table.set_int_array_region)(env, out_pixels, 0, copy_len, h.argb.as_ptr());
}
}
}
if changed { 1 } else { 0 }
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_vip_ltpp_euv_showcase_EuvNativeBridge_nativeGetWidth(
_env: JniEnv,
_cls: JObject,
ptr: i64,
) -> i32 {
if ptr == 0 {
return 0;
}
let h: &EuvAndroidHandle = unsafe { &*(ptr as *const EuvAndroidHandle) };
h.width as i32
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_vip_ltpp_euv_showcase_EuvNativeBridge_nativeGetHeight(
_env: JniEnv,
_cls: JObject,
ptr: i64,
) -> i32 {
if ptr == 0 {
return 0;
}
let h: &EuvAndroidHandle = unsafe { &*(ptr as *const EuvAndroidHandle) };
h.height as i32
}