use super::*;
#[must_use]
pub fn probe_native_gpu(backend: GraphicsBackend) -> (GpuAdapterInfo, usize, usize, usize) {
let probed: NativeGpuProbeOutput = probe_native_gpu_full(backend);
(
probed.adapter,
probed.device_handle,
probed.queue_handle,
probed.library_handle,
)
}
#[must_use]
pub(crate) fn probe_native_gpu_full(backend: GraphicsBackend) -> NativeGpuProbeOutput {
if backend == GraphicsBackend::Headless || backend == GraphicsBackend::SoftwareCpu {
return NativeGpuProbeOutput {
adapter: GpuAdapterInfo::new(backend, GPU_DEVICE_FALLBACK.to_string(), false, false),
device_handle: 0,
queue_handle: 0,
library_handle: 0,
pipeline_handle: 0,
blur_pipeline_handle: 0,
dummy_r8_tex: 0,
dummy_rgba8_tex: 0,
};
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
{
probe_apple_metal_full(backend)
}
#[cfg(target_os = "windows")]
{
let (adapter, device_handle, queue_handle, library_handle): (
GpuAdapterInfo,
usize,
usize,
usize,
) = probe_windows_d3d12(backend);
NativeGpuProbeOutput {
adapter,
device_handle,
queue_handle,
library_handle,
pipeline_handle: 0,
blur_pipeline_handle: 0,
dummy_r8_tex: 0,
dummy_rgba8_tex: 0,
}
}
#[cfg(any(target_os = "linux", target_os = "android"))]
{
let (adapter, device_handle, queue_handle, library_handle): (
GpuAdapterInfo,
usize,
usize,
usize,
) = probe_vulkan_runtime(backend);
NativeGpuProbeOutput {
adapter,
device_handle,
queue_handle,
library_handle,
pipeline_handle: 0,
blur_pipeline_handle: 0,
dummy_r8_tex: 0,
dummy_rgba8_tex: 0,
}
}
#[cfg(target_arch = "wasm32")]
{
NativeGpuProbeOutput {
adapter: GpuAdapterInfo::new(backend, GPU_DEVICE_WEB.to_string(), true, false),
device_handle: 0,
queue_handle: 0,
library_handle: 0,
pipeline_handle: 0,
blur_pipeline_handle: 0,
dummy_r8_tex: 0,
dummy_rgba8_tex: 0,
}
}
#[cfg(not(any(target_arch = "wasm32", unix, windows)))]
{
NativeGpuProbeOutput {
adapter: GpuAdapterInfo::new(backend, GPU_DEVICE_FALLBACK.to_string(), false, false),
device_handle: 0,
queue_handle: 0,
library_handle: 0,
pipeline_handle: 0,
blur_pipeline_handle: 0,
dummy_r8_tex: 0,
dummy_rgba8_tex: 0,
}
}
}
pub fn submit_native_gpu_batches(
device_handle: usize,
queue_handle: usize,
batches: &[GpuBatch],
) -> usize {
#[cfg(any(target_os = "macos", target_os = "ios"))]
{
metal_submit_batches(device_handle, queue_handle, batches)
}
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
{
let _: (usize, usize) = (device_handle, queue_handle);
batches
.iter()
.map(|b: &GpuBatch| b.get_primitives().len().max(b.get_instances().len()))
.sum()
}
}
pub(crate) fn submit_native_gpu_ring_frame(
driver: &mut NativeGpuDriver,
width: u32,
height: u32,
clear_color: Color,
batches: &[GpuBatch],
) -> usize {
#[cfg(any(target_os = "macos", target_os = "ios"))]
{
metal_submit_ring_frame(driver, width, height, clear_color, batches)
}
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
{
let _: (&mut NativeGpuDriver, u32, u32, Color) = (driver, width, height, clear_color);
batches
.iter()
.map(|b: &GpuBatch| b.get_primitives().len().max(b.get_instances().len()))
.sum()
}
}
pub(crate) fn configure_native_metal_layer(device_handle: usize, layer_handle: usize) {
#[cfg(any(target_os = "macos", target_os = "ios"))]
{
metal_configure_layer(device_handle, layer_handle);
}
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
{
let _: (usize, usize) = (device_handle, layer_handle);
}
}
pub(crate) fn upload_native_texture_dirty_rect(
device_handle: usize,
texture_handle: &mut usize,
format: GpuAtlasPixelFormat,
tex_dims: (u32, u32),
dirty_rect: (u32, u32, u32, u32),
bytes: &[u8],
bytes_per_row: usize,
) -> bool {
#[cfg(any(target_os = "macos", target_os = "ios"))]
{
metal_upload_texture_dirty_rect(
device_handle,
texture_handle,
format,
tex_dims,
dirty_rect,
bytes,
bytes_per_row,
)
}
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
{
let _: usize = device_handle;
let _: &mut usize = texture_handle;
let _: GpuAtlasPixelFormat = format;
let _: (u32, u32) = tex_dims;
let _: (u32, u32, u32, u32) = dirty_rect;
let _: &[u8] = bytes;
let _: usize = bytes_per_row;
false
}
}
pub(crate) fn retain_native_gpu_object(handle: usize) -> usize {
#[cfg(any(target_os = "macos", target_os = "ios"))]
{
mtl_retain_handle(handle)
}
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
{
handle
}
}
pub(crate) fn release_native_gpu_object(handle: usize) {
#[cfg(any(target_os = "macos", target_os = "ios"))]
{
if handle != 0 {
let sel: &MetalSelectors = cached_metal_selectors();
mtl_send_void0(handle as *mut c_void, sel.release as *mut c_void);
}
}
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
{
let _: usize = handle;
}
}
pub fn release_native_gpu_handles(
device_handle: usize,
queue_handle: usize,
library_handle: usize,
) {
#[cfg(any(target_os = "macos", target_os = "ios"))]
{
metal_release_handles(device_handle, queue_handle, library_handle);
}
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
{
let _: (usize, usize, usize) = (device_handle, queue_handle, library_handle);
}
}
#[must_use]
pub fn native_gpu_last_presented_ns() -> u64 {
#[cfg(any(target_os = "macos", target_os = "ios"))]
{
METAL_LAST_PRESENTED_NS.load(Ordering::Relaxed)
}
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
{
0
}
}
#[must_use]
pub fn native_gpu_last_exec_ns() -> u64 {
#[cfg(any(target_os = "macos", target_os = "ios"))]
{
METAL_LAST_GPU_EXEC_NS.load(Ordering::Relaxed)
}
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
{
0
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
#[link(name = "Metal", kind = "framework")]
unsafe extern "C" {
fn MTLCreateSystemDefaultDevice() -> *mut c_void;
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
#[link(name = "objc")]
unsafe extern "C" {
fn objc_getClass(name: *const c_char) -> *mut c_void;
fn sel_registerName(name: *const c_char) -> *mut c_void;
fn objc_autoreleasePoolPush() -> *mut c_void;
fn objc_autoreleasePoolPop(pool: *mut c_void);
fn objc_msgSend();
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
unsafe extern "C" {
static _NSConcreteGlobalBlock: c_void;
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn mtl_sel_cstr(name: &'static str) -> *mut c_void {
unsafe { sel_registerName(name.as_ptr().cast::<c_char>()) }
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn mtl_cls_cstr(name: &'static str) -> *mut c_void {
unsafe { objc_getClass(name.as_ptr().cast::<c_char>()) }
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn mtl_ns_string(text: &str) -> *mut c_void {
let Ok(c_text) = CString::new(text) else {
return null_mut();
};
unsafe {
let cls: *mut c_void = mtl_cls_cstr(MTL_CLS_NS_STRING);
if cls.is_null() {
return null_mut();
}
let send: unsafe extern "C" fn(*mut c_void, *mut c_void, *const c_char) -> *mut c_void =
transmute(objc_msgSend as *const c_void);
send(cls, mtl_sel_cstr(MTL_SEL_STRING_UTF8), c_text.as_ptr())
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn mtl_send_ptr0(obj: *mut c_void, sel: *mut c_void) -> *mut c_void {
if obj.is_null() || sel.is_null() {
return null_mut();
}
unsafe {
let send: unsafe extern "C" fn(*mut c_void, *mut c_void) -> *mut c_void =
transmute(objc_msgSend as *const c_void);
send(obj, sel)
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn mtl_send_ptr1(obj: *mut c_void, sel: *mut c_void, arg0: *mut c_void) -> *mut c_void {
if obj.is_null() || sel.is_null() {
return null_mut();
}
unsafe {
let send: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) -> *mut c_void =
transmute(objc_msgSend as *const c_void);
send(obj, sel, arg0)
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn mtl_send_void0(obj: *mut c_void, sel: *mut c_void) {
if obj.is_null() || sel.is_null() {
return;
}
unsafe {
let send: unsafe extern "C" fn(*mut c_void, *mut c_void) =
transmute(objc_msgSend as *const c_void);
send(obj, sel);
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn mtl_send_void_ptr1(obj: *mut c_void, sel: *mut c_void, arg0: *mut c_void) {
if obj.is_null() || sel.is_null() {
return;
}
unsafe {
let send: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) =
transmute(objc_msgSend as *const c_void);
send(obj, sel, arg0);
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn mtl_send_void_usize(obj: *mut c_void, sel: *mut c_void, val: usize) {
if obj.is_null() || sel.is_null() {
return;
}
unsafe {
let send: unsafe extern "C" fn(*mut c_void, *mut c_void, usize) =
transmute(objc_msgSend as *const c_void);
send(obj, sel, val);
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn mtl_send_void_bool(obj: *mut c_void, sel: *mut c_void, val: bool) {
if obj.is_null() || sel.is_null() {
return;
}
unsafe {
let send: unsafe extern "C" fn(*mut c_void, *mut c_void, i8) =
transmute(objc_msgSend as *const c_void);
send(obj, sel, if val { 1 } else { 0 });
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn mtl_send_usize0(obj: *mut c_void, sel: *mut c_void) -> usize {
if obj.is_null() || sel.is_null() {
return 0;
}
unsafe {
let send: unsafe extern "C" fn(*mut c_void, *mut c_void) -> usize =
transmute(objc_msgSend as *const c_void);
send(obj, sel)
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn mtl_send_f64_0(obj: *mut c_void, sel: *mut c_void) -> f64 {
if obj.is_null() || sel.is_null() {
return 0.0;
}
unsafe {
let send: unsafe extern "C" fn(*mut c_void, *mut c_void) -> f64 =
transmute(objc_msgSend as *const c_void);
send(obj, sel)
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn mtl_responds_to_sel(obj: *mut c_void, sel: *mut c_void) -> bool {
if obj.is_null() || sel.is_null() {
return false;
}
let responds_sel: *mut c_void = cached_metal_selectors().responds_to_sel as *mut c_void;
unsafe {
let send: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) -> i8 =
transmute(objc_msgSend as *const c_void);
send(obj, responds_sel, sel) != 0
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn mtl_retain_handle(handle: usize) -> usize {
if handle == 0 {
return 0;
}
let sel_retain: *mut c_void = cached_metal_selectors().retain as *mut c_void;
mtl_send_ptr0(handle as *mut c_void, sel_retain) as usize
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
unsafe extern "C" fn metal_presented_handler_invoke(_block: *mut c_void, drawable: *mut c_void) {
if drawable.is_null() {
return;
}
let sel: &MetalSelectors = cached_metal_selectors();
let presented_secs: f64 = mtl_send_f64_0(drawable, sel.presented_time as *mut c_void);
if presented_secs.is_finite() && presented_secs > 0.0 {
let ns: u64 = (presented_secs * 1_000_000_000.0).round() as u64;
METAL_LAST_PRESENTED_NS.store(ns, Ordering::Relaxed);
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
unsafe extern "C" fn metal_completed_handler_invoke(_block: *mut c_void, cmd_buf: *mut c_void) {
if cmd_buf.is_null() {
return;
}
let sel: &MetalSelectors = cached_metal_selectors();
let start_s: f64 = mtl_send_f64_0(cmd_buf, sel.gpu_start_time as *mut c_void);
let end_s: f64 = mtl_send_f64_0(cmd_buf, sel.gpu_end_time as *mut c_void);
if start_s.is_finite() && end_s.is_finite() && end_s >= start_s {
let exec_ns: u64 = ((end_s - start_s) * 1_000_000_000.0).round() as u64;
METAL_LAST_GPU_EXEC_NS.store(exec_ns, Ordering::Relaxed);
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn metal_presented_block_ptr() -> *mut c_void {
let addr: usize = *METAL_PRESENTED_BLOCK_ADDR.get_or_init(|| {
let block: Box<ObjcGlobalBlock> = Box::new(ObjcGlobalBlock {
isa: unsafe { &_NSConcreteGlobalBlock as *const c_void },
flags: OBJC_BLOCK_IS_GLOBAL,
reserved: 0,
invoke: metal_presented_handler_invoke,
descriptor: &METAL_BLOCK_DESCRIPTOR,
});
Box::into_raw(block) as usize
});
addr as *mut c_void
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn metal_completed_block_ptr() -> *mut c_void {
let addr: usize = *METAL_COMPLETED_BLOCK_ADDR.get_or_init(|| {
let block: Box<ObjcGlobalBlock> = Box::new(ObjcGlobalBlock {
isa: unsafe { &_NSConcreteGlobalBlock as *const c_void },
flags: OBJC_BLOCK_IS_GLOBAL,
reserved: 0,
invoke: metal_completed_handler_invoke,
descriptor: &METAL_BLOCK_DESCRIPTOR,
});
Box::into_raw(block) as usize
});
addr as *mut c_void
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn metal_pipeline_cache_hash(device_name: &str) -> u64 {
let mut hash: u64 = FNV1A_OFFSET_BASIS;
for chunk in [
device_name.as_bytes(),
MSL_UI_SHADER.as_bytes(),
MSL_BACKDROP_BLUR_SHADER.as_bytes(),
]
.iter()
{
for &byte in chunk.iter() {
hash ^= byte as u64;
hash = hash.wrapping_mul(FNV1A_PRIME);
}
}
hash
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn metal_create_texture(
device: *mut c_void,
format: GpuAtlasPixelFormat,
width: u32,
height: u32,
) -> usize {
if device.is_null() {
return 0;
}
let px_fmt: usize = match format {
GpuAtlasPixelFormat::R8Unorm => MTL_PIXEL_FORMAT_R8_UNORM,
GpuAtlasPixelFormat::Rgba8Unorm => MTL_PIXEL_FORMAT_RGBA8_UNORM,
};
let cls_desc: *mut c_void = mtl_cls_cstr(MTL_CLS_TEX_DESC);
if cls_desc.is_null() {
return 0;
}
unsafe {
let send_desc: unsafe extern "C" fn(
*mut c_void,
*mut c_void,
usize,
usize,
usize,
i8,
) -> *mut c_void = transmute(objc_msgSend as *const c_void);
let desc: *mut c_void = send_desc(
cls_desc,
mtl_sel_cstr(MTL_SEL_TEX_2D_DESC),
px_fmt,
width.max(1) as usize,
height.max(1) as usize,
0,
);
if desc.is_null() {
return 0;
}
mtl_send_void_usize(desc, mtl_sel_cstr(MTL_SEL_SET_USAGE), 1);
let tex: *mut c_void = mtl_send_ptr1(device, mtl_sel_cstr(MTL_SEL_NEW_TEXTURE), desc);
tex as usize
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn metal_build_render_pipeline(
device: *mut c_void,
library: *mut c_void,
vs_name: &str,
fs_name: &str,
archive: *mut c_void,
enable_blend: bool,
) -> (usize, bool) {
if device.is_null() || library.is_null() {
return (0, false);
}
let sel_rel: *mut c_void = mtl_sel_cstr(MTL_SEL_RELEASE);
let vs_fn: *mut c_void = mtl_send_ptr1(
library,
mtl_sel_cstr(MTL_SEL_NEW_FUNCTION),
mtl_ns_string(vs_name),
);
let fs_fn: *mut c_void = mtl_send_ptr1(
library,
mtl_sel_cstr(MTL_SEL_NEW_FUNCTION),
mtl_ns_string(fs_name),
);
let functions_ok: bool = !vs_fn.is_null() && !fs_fn.is_null();
if !functions_ok {
if !vs_fn.is_null() {
mtl_send_void0(vs_fn, sel_rel);
}
if !fs_fn.is_null() {
mtl_send_void0(fs_fn, sel_rel);
}
return (0, false);
}
let desc_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_PIPELINE_DESC);
let desc_alloc: *mut c_void = mtl_send_ptr0(desc_cls, mtl_sel_cstr(MTL_SEL_ALLOC));
let desc: *mut c_void = mtl_send_ptr0(desc_alloc, mtl_sel_cstr(MTL_SEL_INIT));
if desc.is_null() {
mtl_send_void0(vs_fn, sel_rel);
mtl_send_void0(fs_fn, sel_rel);
return (0, functions_ok);
}
mtl_send_void_ptr1(desc, mtl_sel_cstr(MTL_SEL_SET_VERTEX_FUNCTION), vs_fn);
mtl_send_void_ptr1(desc, mtl_sel_cstr(MTL_SEL_SET_FRAGMENT_FUNCTION), fs_fn);
let color_atts: *mut c_void = mtl_send_ptr0(desc, mtl_sel_cstr(MTL_SEL_COLOR_ATTACHMENTS));
let att0: *mut c_void = unsafe {
let send_idx: unsafe extern "C" fn(*mut c_void, *mut c_void, usize) -> *mut c_void =
transmute(objc_msgSend as *const c_void);
send_idx(color_atts, mtl_sel_cstr(MTL_SEL_OBJECT_AT_INDEX), 0)
};
if !att0.is_null() {
mtl_send_void_usize(
att0,
mtl_sel_cstr(MTL_SEL_SET_PIXEL_FORMAT),
MTL_PIXEL_FORMAT_BGRA8_UNORM,
);
if enable_blend {
mtl_send_void_bool(att0, mtl_sel_cstr(MTL_SEL_SET_BLENDING_ENABLED), true);
mtl_send_void_usize(att0, mtl_sel_cstr(MTL_SEL_SET_RGB_BLEND_OP), 0);
mtl_send_void_usize(att0, mtl_sel_cstr(MTL_SEL_SET_ALPHA_BLEND_OP), 0);
mtl_send_void_usize(
att0,
mtl_sel_cstr(MTL_SEL_SET_SRC_RGB_BLEND),
MTL_BLEND_FACTOR_SRC_ALPHA,
);
mtl_send_void_usize(
att0,
mtl_sel_cstr(MTL_SEL_SET_DST_RGB_BLEND),
MTL_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA,
);
mtl_send_void_usize(
att0,
mtl_sel_cstr(MTL_SEL_SET_SRC_ALPHA_BLEND),
MTL_BLEND_FACTOR_ONE,
);
mtl_send_void_usize(
att0,
mtl_sel_cstr(MTL_SEL_SET_DST_ALPHA_BLEND),
MTL_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA,
);
}
}
if !archive.is_null() && mtl_responds_to_sel(desc, mtl_sel_cstr(MTL_SEL_SET_BINARY_ARCHIVES)) {
let arr_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_NS_ARRAY);
let arr: *mut c_void =
mtl_send_ptr1(arr_cls, mtl_sel_cstr(MTL_SEL_ARRAY_WITH_OBJECT), archive);
if !arr.is_null() {
mtl_send_void_ptr1(desc, mtl_sel_cstr(MTL_SEL_SET_BINARY_ARCHIVES), arr);
}
}
let mut err_ptr: *mut c_void = null_mut();
let pipeline: *mut c_void = unsafe {
let send_pso: unsafe extern "C" fn(
*mut c_void,
*mut c_void,
*mut c_void,
*mut *mut c_void,
) -> *mut c_void = transmute(objc_msgSend as *const c_void);
send_pso(
device,
mtl_sel_cstr(MTL_SEL_NEW_PIPELINE_STATE),
desc,
&mut err_ptr,
)
};
if !archive.is_null() && !pipeline.is_null() {
let mut add_err: *mut c_void = null_mut();
unsafe {
let send_add: unsafe extern "C" fn(
*mut c_void,
*mut c_void,
*mut c_void,
*mut *mut c_void,
) -> i8 = transmute(objc_msgSend as *const c_void);
let _: i8 = send_add(
archive,
mtl_sel_cstr(MTL_SEL_ADD_PIPELINE_TO_ARCHIVE),
desc,
&mut add_err,
);
}
}
mtl_send_void0(desc, sel_rel);
mtl_send_void0(vs_fn, sel_rel);
mtl_send_void0(fs_fn, sel_rel);
(pipeline as usize, functions_ok)
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn metal_open_binary_archive(
device: *mut c_void,
device_name: &str,
) -> (*mut c_void, *mut c_void, bool) {
let arch_desc_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_BINARY_ARCHIVE_DESC);
if arch_desc_cls.is_null() {
return (null_mut(), null_mut(), false);
}
let cache_hash: u64 = metal_pipeline_cache_hash(device_name);
let archive_path: String = env::temp_dir()
.join(format!(
"{MTL_ARCHIVE_FILE_PREFIX}{cache_hash:016x}{MTL_ARCHIVE_FILE_SUFFIX}"
))
.to_string_lossy()
.into_owned();
let existed: bool = fs::metadata(&archive_path).is_ok();
let ns_path: *mut c_void = mtl_ns_string(&archive_path);
let url_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_NS_URL);
let ns_url: *mut c_void =
mtl_send_ptr1(url_cls, mtl_sel_cstr(MTL_SEL_FILE_URL_WITH_PATH), ns_path);
let arch_desc_alloc: *mut c_void = mtl_send_ptr0(arch_desc_cls, mtl_sel_cstr(MTL_SEL_ALLOC));
let arch_desc: *mut c_void = mtl_send_ptr0(arch_desc_alloc, mtl_sel_cstr(MTL_SEL_INIT));
if arch_desc.is_null() {
return (null_mut(), ns_url, existed);
}
if existed && !ns_url.is_null() {
mtl_send_void_ptr1(arch_desc, mtl_sel_cstr(MTL_SEL_SET_URL), ns_url);
}
let mut err_ptr: *mut c_void = null_mut();
let archive: *mut c_void = unsafe {
let send_new: unsafe extern "C" fn(
*mut c_void,
*mut c_void,
*mut c_void,
*mut *mut c_void,
) -> *mut c_void = transmute(objc_msgSend as *const c_void);
send_new(
device,
mtl_sel_cstr(MTL_SEL_NEW_BINARY_ARCHIVE),
arch_desc,
&mut err_ptr,
)
};
mtl_send_void0(arch_desc, mtl_sel_cstr(MTL_SEL_RELEASE));
(archive, ns_url, existed)
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn probe_apple_metal_full(backend: GraphicsBackend) -> NativeGpuProbeOutput {
let cached: &MetalSharedPipelineCache = METAL_SHARED_PIPELINE.get_or_init(|| {
let pool: *mut c_void = unsafe { objc_autoreleasePoolPush() };
let result: MetalSharedPipelineCache = unsafe {
let device: *mut c_void = MTLCreateSystemDefaultDevice();
if device.is_null() {
MetalSharedPipelineCache {
adapter: GpuAdapterInfo::new(
backend,
GPU_DEVICE_FALLBACK.to_string(),
false,
false,
),
device: 0,
queue: 0,
library: 0,
pipeline: 0,
blur_pipeline: 0,
dummy_r8_tex: 0,
dummy_rgba8_tex: 0,
}
} else {
let ns_name: *mut c_void = mtl_send_ptr0(device, mtl_sel_cstr(MTL_SEL_NAME));
let utf8_ptr: *const c_char =
mtl_send_ptr0(ns_name, mtl_sel_cstr(MTL_SEL_UTF8_STRING)).cast::<c_char>();
let device_name: String = if utf8_ptr.is_null() {
GPU_DEVICE_APPLE_METAL.to_string()
} else {
CStr::from_ptr(utf8_ptr).to_string_lossy().into_owned()
};
let queue: *mut c_void = mtl_send_ptr0(device, mtl_sel_cstr(MTL_SEL_NEW_CMD_QUEUE));
let (archive, archive_url, archive_existed): (*mut c_void, *mut c_void, bool) =
metal_open_binary_archive(device, &device_name);
let send_lib: unsafe extern "C" fn(
*mut c_void,
*mut c_void,
*mut c_void,
*mut c_void,
*mut *mut c_void,
) -> *mut c_void = transmute(objc_msgSend as *const c_void);
let mut err_ptr: *mut c_void = null_mut();
let library: *mut c_void = send_lib(
device,
mtl_sel_cstr(MTL_SEL_NEW_LIBRARY),
mtl_ns_string(MSL_UI_SHADER),
null_mut(),
&mut err_ptr,
);
let (pipeline, ui_fns_ok): (usize, bool) = metal_build_render_pipeline(
device,
library,
MTL_FN_VERTEX,
MTL_FN_FRAGMENT,
archive,
true,
);
let mut blur_err: *mut c_void = null_mut();
let blur_lib: *mut c_void = send_lib(
device,
mtl_sel_cstr(MTL_SEL_NEW_LIBRARY),
mtl_ns_string(MSL_BACKDROP_BLUR_SHADER),
null_mut(),
&mut blur_err,
);
let (blur_pipeline, _): (usize, bool) = metal_build_render_pipeline(
device,
blur_lib,
MTL_FN_BLUR_VERTEX,
MTL_FN_BLUR_DOWN,
archive,
false,
);
let (blur_up_pipeline, _): (usize, bool) = metal_build_render_pipeline(
device,
blur_lib,
MTL_FN_BLUR_VERTEX,
MTL_FN_BLUR_UP,
archive,
false,
);
if blur_up_pipeline != 0 {
mtl_send_void0(
blur_up_pipeline as *mut c_void,
mtl_sel_cstr(MTL_SEL_RELEASE),
);
}
if !blur_lib.is_null() {
mtl_send_void0(blur_lib, mtl_sel_cstr(MTL_SEL_RELEASE));
}
if !archive.is_null() {
if !archive_existed && !archive_url.is_null() && pipeline != 0 {
let mut ser_err: *mut c_void = null_mut();
let send_ser: unsafe extern "C" fn(
*mut c_void,
*mut c_void,
*mut c_void,
*mut *mut c_void,
) -> i8 = transmute(objc_msgSend as *const c_void);
let _: i8 = send_ser(
archive,
mtl_sel_cstr(MTL_SEL_SERIALIZE_TO_URL),
archive_url,
&mut ser_err,
);
}
mtl_send_void0(archive, mtl_sel_cstr(MTL_SEL_RELEASE));
}
let dummy_r8_tex: usize =
metal_create_texture(device, GpuAtlasPixelFormat::R8Unorm, 1, 1);
let dummy_rgba8_tex: usize =
metal_create_texture(device, GpuAtlasPixelFormat::Rgba8Unorm, 1, 1);
let shader_compiled: bool = ui_fns_ok && pipeline != 0;
MetalSharedPipelineCache {
adapter: GpuAdapterInfo::new(
GraphicsBackend::Metal,
device_name,
!queue.is_null(),
shader_compiled,
),
device: device as usize,
queue: queue as usize,
library: library as usize,
pipeline,
blur_pipeline,
dummy_r8_tex,
dummy_rgba8_tex,
}
}
};
unsafe { objc_autoreleasePoolPop(pool) };
result
});
NativeGpuProbeOutput {
adapter: cached.adapter.clone(),
device_handle: mtl_retain_handle(cached.device),
queue_handle: mtl_retain_handle(cached.queue),
library_handle: mtl_retain_handle(cached.library),
pipeline_handle: mtl_retain_handle(cached.pipeline),
blur_pipeline_handle: mtl_retain_handle(cached.blur_pipeline),
dummy_r8_tex: mtl_retain_handle(cached.dummy_r8_tex),
dummy_rgba8_tex: mtl_retain_handle(cached.dummy_rgba8_tex),
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn cached_metal_selectors() -> &'static MetalSelectors {
METAL_SELECTORS.get_or_init(|| MetalSelectors {
retain: mtl_sel_cstr(MTL_SEL_RETAIN) as usize,
new_buffer_with_bytes: mtl_sel_cstr(MTL_SEL_NEW_BUFFER) as usize,
new_buffer_with_length: mtl_sel_cstr(MTL_SEL_NEW_BUFFER_LENGTH) as usize,
contents: mtl_sel_cstr(MTL_SEL_CONTENTS) as usize,
command_buffer: mtl_sel_cstr(MTL_SEL_CMD_BUFFER) as usize,
render_encoder: mtl_sel_cstr(MTL_SEL_RENDER_ENCODER) as usize,
set_pipeline_state: mtl_sel_cstr(MTL_SEL_SET_PIPELINE_STATE) as usize,
set_vertex_buffer: mtl_sel_cstr(MTL_SEL_SET_VERTEX_BUFFER) as usize,
set_vertex_bytes: mtl_sel_cstr(MTL_SEL_SET_VERTEX_BYTES) as usize,
set_fragment_texture: mtl_sel_cstr(MTL_SEL_SET_FRAGMENT_TEXTURE) as usize,
set_scissor_rect: mtl_sel_cstr(MTL_SEL_SET_SCISSOR_RECT) as usize,
draw_primitives_instanced: mtl_sel_cstr(MTL_SEL_DRAW_PRIMITIVES_INSTANCED) as usize,
end_encoding: mtl_sel_cstr(MTL_SEL_END_ENCODING) as usize,
present_drawable: mtl_sel_cstr(MTL_SEL_PRESENT_DRAWABLE) as usize,
add_presented_handler: mtl_sel_cstr(MTL_SEL_ADD_PRESENTED_HANDLER) as usize,
add_completed_handler: mtl_sel_cstr(MTL_SEL_ADD_COMPLETED_HANDLER) as usize,
presented_time: mtl_sel_cstr(MTL_SEL_PRESENTED_TIME) as usize,
responds_to_sel: mtl_sel_cstr(MTL_SEL_RESPONDS_TO_SEL) as usize,
status: mtl_sel_cstr(MTL_SEL_STATUS) as usize,
wait_until_completed: mtl_sel_cstr(MTL_SEL_WAIT_UNTIL_COMPLETED) as usize,
gpu_start_time: mtl_sel_cstr(MTL_SEL_GPU_START_TIME) as usize,
gpu_end_time: mtl_sel_cstr(MTL_SEL_GPU_END_TIME) as usize,
next_drawable: mtl_sel_cstr(MTL_SEL_NEXT_DRAWABLE) as usize,
drawable_size: mtl_sel_cstr(MTL_SEL_DRAWABLE_SIZE) as usize,
set_drawable_size: mtl_sel_cstr(MTL_SEL_SET_DRAWABLE_SIZE) as usize,
texture: mtl_sel_cstr(MTL_SEL_TEXTURE) as usize,
width: mtl_sel_cstr(MTL_SEL_WIDTH) as usize,
height: mtl_sel_cstr(MTL_SEL_HEIGHT) as usize,
render_pass_desc: mtl_sel_cstr(MTL_SEL_RENDER_PASS_DESC) as usize,
color_attachments: mtl_sel_cstr(MTL_SEL_COLOR_ATTACHMENTS) as usize,
object_at_index: mtl_sel_cstr(MTL_SEL_OBJECT_AT_INDEX) as usize,
set_texture: mtl_sel_cstr(MTL_SEL_SET_TEXTURE) as usize,
set_load_action: mtl_sel_cstr(MTL_SEL_SET_LOAD_ACTION) as usize,
set_store_action: mtl_sel_cstr(MTL_SEL_SET_STORE_ACTION) as usize,
set_clear_color: mtl_sel_cstr(MTL_SEL_SET_CLEAR_COLOR) as usize,
replace_region: mtl_sel_cstr(MTL_SEL_REPLACE_REGION) as usize,
commit: mtl_sel_cstr(MTL_SEL_COMMIT) as usize,
release: mtl_sel_cstr(MTL_SEL_RELEASE) as usize,
})
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn metal_configure_layer(device_handle: usize, layer_handle: usize) {
if device_handle == 0 || layer_handle == 0 {
return;
}
let layer: *mut c_void = layer_handle as *mut c_void;
mtl_send_void_ptr1(
layer,
mtl_sel_cstr(MTL_SEL_SET_DEVICE),
device_handle as *mut c_void,
);
mtl_send_void_usize(
layer,
mtl_sel_cstr(MTL_SEL_SET_PIXEL_FORMAT),
MTL_PIXEL_FORMAT_BGRA8_UNORM,
);
mtl_send_void_bool(layer, mtl_sel_cstr(MTL_SEL_SET_FRAMEBUFFER_ONLY), true);
let sel_max: *mut c_void = mtl_sel_cstr(MTL_SEL_SET_MAX_DRAWABLE_COUNT);
if mtl_responds_to_sel(layer, sel_max) {
mtl_send_void_usize(layer, sel_max, GPU_DRIVER_RING_SLOTS);
}
let sel_sync: *mut c_void = mtl_sel_cstr(MTL_SEL_SET_DISPLAY_SYNC);
if mtl_responds_to_sel(layer, sel_sync) {
mtl_send_void_bool(layer, sel_sync, true);
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn metal_upload_texture_dirty_rect(
device_handle: usize,
texture_handle: &mut usize,
format: GpuAtlasPixelFormat,
tex_dims: (u32, u32),
dirty_rect: (u32, u32, u32, u32),
bytes: &[u8],
bytes_per_row: usize,
) -> bool {
if device_handle == 0 || dirty_rect.2 == 0 || dirty_rect.3 == 0 || bytes.is_empty() {
return false;
}
let pool: *mut c_void = unsafe { objc_autoreleasePoolPush() };
let (tex_w, tex_h): (u32, u32) = (tex_dims.0.max(1), tex_dims.1.max(1));
let sel: &MetalSelectors = cached_metal_selectors();
let cur_w: usize = if *texture_handle != 0 {
mtl_send_usize0(*texture_handle as *mut c_void, sel.width as *mut c_void)
} else {
0
};
let cur_h: usize = if *texture_handle != 0 {
mtl_send_usize0(*texture_handle as *mut c_void, sel.height as *mut c_void)
} else {
0
};
if *texture_handle == 0 || cur_w != tex_w as usize || cur_h != tex_h as usize {
if *texture_handle != 0 {
mtl_send_void0(*texture_handle as *mut c_void, sel.release as *mut c_void);
}
*texture_handle = metal_create_texture(device_handle as *mut c_void, format, tex_w, tex_h);
}
if *texture_handle == 0 {
unsafe { objc_autoreleasePoolPop(pool) };
return false;
}
let region: MtlRegion = MtlRegion {
origin: MtlOrigin {
x: dirty_rect.0 as usize,
y: dirty_rect.1 as usize,
z: 0,
},
size: MtlSize {
width: dirty_rect.2 as usize,
height: dirty_rect.3 as usize,
depth: 1,
},
};
unsafe {
let send_replace: unsafe extern "C" fn(
*mut c_void,
*mut c_void,
MtlRegion,
usize,
*const c_void,
usize,
) = transmute(objc_msgSend as *const c_void);
send_replace(
*texture_handle as *mut c_void,
sel.replace_region as *mut c_void,
region,
0,
bytes.as_ptr().cast::<c_void>(),
bytes_per_row,
);
objc_autoreleasePoolPop(pool);
}
true
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn metal_submit_ring_frame(
driver: &mut NativeGpuDriver,
width: u32,
height: u32,
clear_color: Color,
batches: &[GpuBatch],
) -> usize {
let total_instances: usize = batches
.iter()
.map(|b: &GpuBatch| b.get_primitives().len().max(b.get_instances().len()))
.sum();
let device_handle: usize = driver.get_device_handle();
let queue_handle: usize = driver.get_queue_handle();
if device_handle == 0 || queue_handle == 0 {
return total_instances;
}
let pool: *mut c_void = unsafe { objc_autoreleasePoolPush() };
let sel: &MetalSelectors = cached_metal_selectors();
let sel_rel: *mut c_void = sel.release as *mut c_void;
let slot_idx: usize = driver.get_ring_cursor() % GPU_DRIVER_RING_SLOTS;
let device: *mut c_void = device_handle as *mut c_void;
let queue: *mut c_void = queue_handle as *mut c_void;
let pipeline: *mut c_void = driver.get_pipeline_handle() as *mut c_void;
let layer_ptr: *mut c_void = driver.get_surface_layer_handle() as *mut c_void;
let tex_r8: *mut c_void = driver.get_glyph_r8_texture_handle() as *mut c_void;
let tex_rgba8: *mut c_void = driver.get_glyph_rgba8_texture_handle() as *mut c_void;
let tex_img: *mut c_void = driver.get_image_texture_handle() as *mut c_void;
let raw_ext: usize = driver.get_external_texture_handle();
let tex_ext: *mut c_void = if raw_ext != 0 {
raw_ext as *mut c_void
} else {
tex_rgba8
};
let total_bytes: usize = total_instances.saturating_mul(size_of::<GpuPrimitiveInstance>());
let NativeGpuDriver {
ring_slots,
ring_cursor,
staging_buffer_handle,
staging_contents_ptr,
staging_buffer_capacity,
staging_reallocations,
scratch_primitives,
..
} = driver;
let slot: &mut NativeGpuRingSlot = &mut ring_slots[slot_idx];
let prev_cmd: usize = slot.get_in_flight_cmd_buffer();
if prev_cmd != 0 {
let status: usize = mtl_send_usize0(prev_cmd as *mut c_void, sel.status as *mut c_void);
if status < MTL_CMD_BUFFER_STATUS_COMPLETED {
mtl_send_void0(
prev_cmd as *mut c_void,
sel.wait_until_completed as *mut c_void,
);
}
mtl_send_void0(prev_cmd as *mut c_void, sel_rel);
slot.set_in_flight_cmd_buffer(0);
}
if total_bytes > 0
&& (slot.get_buffer_handle() == 0
|| slot.get_contents_ptr() == 0
|| total_bytes > slot.get_capacity_bytes())
{
if slot.get_buffer_handle() != 0 {
mtl_send_void0(slot.get_buffer_handle() as *mut c_void, sel_rel);
slot.set_buffer_handle(0);
slot.set_contents_ptr(0);
slot.set_capacity_bytes(0);
}
let alloc_bytes: usize = total_bytes.max(4096).next_power_of_two();
unsafe {
let send_new_len: unsafe extern "C" fn(
*mut c_void,
*mut c_void,
usize,
usize,
) -> *mut c_void = transmute(objc_msgSend as *const c_void);
let new_buf: *mut c_void = send_new_len(
device,
sel.new_buffer_with_length as *mut c_void,
alloc_bytes,
0,
);
if !new_buf.is_null() {
let ptr: *mut c_void = mtl_send_ptr0(new_buf, sel.contents as *mut c_void);
if !ptr.is_null() {
slot.set_buffer_handle(new_buf as usize);
slot.set_contents_ptr(ptr as usize);
slot.set_capacity_bytes(alloc_bytes);
*staging_reallocations = staging_reallocations.wrapping_add(1);
} else {
mtl_send_void0(new_buf, sel_rel);
}
}
}
}
let buf_handle: usize = slot.get_buffer_handle();
let contents_ptr: usize = slot.get_contents_ptr();
let capacity_bytes: usize = slot.get_capacity_bytes();
*staging_buffer_handle = buf_handle;
*staging_contents_ptr = contents_ptr;
*staging_buffer_capacity = capacity_bytes;
if contents_ptr != 0 && total_bytes > 0 && total_bytes <= capacity_bytes {
unsafe {
let mut dst: *mut u8 = (contents_ptr as *mut c_void).cast::<u8>();
for batch in batches.iter() {
let prims: &[GpuPrimitiveInstance] = batch.get_primitives();
if !prims.is_empty() {
let byte_len: usize = size_of_val(prims);
dst.copy_from_nonoverlapping(prims.as_ptr().cast::<u8>(), byte_len);
dst = dst.add(byte_len);
} else if !batch.get_instances().is_empty() {
scratch_primitives.clear();
for quad in batch.get_instances().iter() {
scratch_primitives.push(GpuPrimitiveInstance::from_quad_instance(
quad,
batch.get_texture_slot(),
batch.get_layer_id(),
));
}
let byte_len: usize = size_of_val(scratch_primitives.as_slice());
dst.copy_from_nonoverlapping(
scratch_primitives.as_ptr().cast::<u8>(),
byte_len,
);
dst = dst.add(byte_len);
}
}
}
}
let cmd_buf: *mut c_void = mtl_send_ptr0(queue, sel.command_buffer as *mut c_void);
if !cmd_buf.is_null() {
let sel_completed: *mut c_void = sel.add_completed_handler as *mut c_void;
if mtl_responds_to_sel(cmd_buf, sel_completed) {
mtl_send_void_ptr1(cmd_buf, sel_completed, metal_completed_block_ptr());
}
if !layer_ptr.is_null() && !pipeline.is_null() {
if width > 0
&& height > 0
&& mtl_responds_to_sel(layer_ptr, sel.set_drawable_size as *mut c_void)
{
let target_w: f64 = f64::from(width);
let target_h: f64 = f64::from(height);
let needs_resize: bool =
if mtl_responds_to_sel(layer_ptr, sel.drawable_size as *mut c_void) {
let cur: MtlCgSize = unsafe {
let get_size: unsafe extern "C" fn(
*mut c_void,
*mut c_void,
)
-> MtlCgSize = transmute(objc_msgSend as *const c_void);
get_size(layer_ptr, sel.drawable_size as *mut c_void)
};
(cur.width - target_w).abs() > 0.5 || (cur.height - target_h).abs() > 0.5
} else {
true
};
if needs_resize {
unsafe {
let set_size: unsafe extern "C" fn(*mut c_void, *mut c_void, MtlCgSize) =
transmute(objc_msgSend as *const c_void);
set_size(
layer_ptr,
sel.set_drawable_size as *mut c_void,
MtlCgSize {
width: target_w,
height: target_h,
},
);
}
}
}
let drawable: *mut c_void = mtl_send_ptr0(layer_ptr, sel.next_drawable as *mut c_void);
if !drawable.is_null() {
let drawable_tex: *mut c_void = mtl_send_ptr0(drawable, sel.texture as *mut c_void);
let pass_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_PASS_DESC);
let pass_desc: *mut c_void =
mtl_send_ptr0(pass_cls, sel.render_pass_desc as *mut c_void);
if !drawable_tex.is_null() && !pass_desc.is_null() {
let draw_w: usize = mtl_send_usize0(drawable_tex, sel.width as *mut c_void)
.max(width.max(1) as usize);
let draw_h: usize = mtl_send_usize0(drawable_tex, sel.height as *mut c_void)
.max(height.max(1) as usize);
let color_atts: *mut c_void =
mtl_send_ptr0(pass_desc, sel.color_attachments as *mut c_void);
let att0: *mut c_void = unsafe {
let send_idx: unsafe extern "C" fn(
*mut c_void,
*mut c_void,
usize,
) -> *mut c_void = transmute(objc_msgSend as *const c_void);
send_idx(color_atts, sel.object_at_index as *mut c_void, 0)
};
if !att0.is_null() {
mtl_send_void_ptr1(att0, sel.set_texture as *mut c_void, drawable_tex);
mtl_send_void_usize(
att0,
sel.set_load_action as *mut c_void,
MTL_LOAD_ACTION_CLEAR,
);
mtl_send_void_usize(
att0,
sel.set_store_action as *mut c_void,
MTL_STORE_ACTION_STORE,
);
let clear_rgba: [f32; 4] = clear_color.to_f32_array();
let mtl_clear: MtlClearColor = MtlClearColor {
red: clear_rgba[0] as f64,
green: clear_rgba[1] as f64,
blue: clear_rgba[2] as f64,
alpha: clear_rgba[3] as f64,
};
unsafe {
let send_clear: unsafe extern "C" fn(
*mut c_void,
*mut c_void,
MtlClearColor,
) = transmute(objc_msgSend as *const c_void);
send_clear(att0, sel.set_clear_color as *mut c_void, mtl_clear);
}
}
let encoder: *mut c_void =
mtl_send_ptr1(cmd_buf, sel.render_encoder as *mut c_void, pass_desc);
if !encoder.is_null() {
mtl_send_void_ptr1(
encoder,
sel.set_pipeline_state as *mut c_void,
pipeline,
);
unsafe {
let send_vbuf: unsafe extern "C" fn(
*mut c_void,
*mut c_void,
*mut c_void,
usize,
usize,
) = transmute(objc_msgSend as *const c_void);
let send_vbytes: unsafe extern "C" fn(
*mut c_void,
*mut c_void,
*const c_void,
usize,
usize,
) = transmute(objc_msgSend as *const c_void);
let send_ftex: unsafe extern "C" fn(
*mut c_void,
*mut c_void,
*mut c_void,
usize,
) = transmute(objc_msgSend as *const c_void);
let send_scissor: unsafe extern "C" fn(
*mut c_void,
*mut c_void,
MtlScissorRect,
) = transmute(objc_msgSend as *const c_void);
let send_draw: unsafe extern "C" fn(
*mut c_void,
*mut c_void,
usize,
usize,
usize,
usize,
usize,
) = transmute(objc_msgSend as *const c_void);
if buf_handle != 0 {
send_vbuf(
encoder,
sel.set_vertex_buffer as *mut c_void,
buf_handle as *mut c_void,
0,
0,
);
}
if !tex_r8.is_null() {
send_ftex(
encoder,
sel.set_fragment_texture as *mut c_void,
tex_r8,
0,
);
}
if !tex_rgba8.is_null() {
send_ftex(
encoder,
sel.set_fragment_texture as *mut c_void,
tex_rgba8,
1,
);
}
if !tex_img.is_null() {
send_ftex(
encoder,
sel.set_fragment_texture as *mut c_void,
tex_img,
2,
);
}
if !tex_ext.is_null() {
send_ftex(
encoder,
sel.set_fragment_texture as *mut c_void,
tex_ext,
3,
);
}
let mut base_instance: usize = 0;
for batch in batches.iter() {
let count: usize = batch
.get_primitives()
.len()
.max(batch.get_instances().len());
if count == 0 || buf_handle == 0 {
continue;
}
let uniform: GpuLayerUniform = GpuLayerUniform::new(
draw_w as f32,
draw_h as f32,
batch.get_scroll_offset(),
);
send_vbytes(
encoder,
sel.set_vertex_bytes as *mut c_void,
(&uniform as *const GpuLayerUniform).cast::<c_void>(),
size_of::<GpuLayerUniform>(),
1,
);
let sc: Rect = batch.get_scissor();
let sx: usize = (sc.get_x().max(0.0).floor() as usize)
.min(draw_w.saturating_sub(1));
let sy: usize = (sc.get_y().max(0.0).floor() as usize)
.min(draw_h.saturating_sub(1));
let sw: usize = (sc.get_width().max(1.0).ceil() as usize)
.min(draw_w.saturating_sub(sx))
.max(1);
let sh: usize = (sc.get_height().max(1.0).ceil() as usize)
.min(draw_h.saturating_sub(sy))
.max(1);
send_scissor(
encoder,
sel.set_scissor_rect as *mut c_void,
MtlScissorRect {
x: sx,
y: sy,
width: sw,
height: sh,
},
);
send_draw(
encoder,
sel.draw_primitives_instanced as *mut c_void,
MTL_PRIMITIVE_TYPE_TRIANGLE,
0,
6,
count,
base_instance,
);
base_instance = base_instance.saturating_add(count);
}
}
mtl_send_void0(encoder, sel.end_encoding as *mut c_void);
}
let sel_pres: *mut c_void = sel.add_presented_handler as *mut c_void;
if mtl_responds_to_sel(drawable, sel_pres) {
mtl_send_void_ptr1(drawable, sel_pres, metal_presented_block_ptr());
}
mtl_send_void_ptr1(cmd_buf, sel.present_drawable as *mut c_void, drawable);
}
}
}
let retained_cmd: usize = mtl_retain_handle(cmd_buf as usize);
slot.set_in_flight_cmd_buffer(retained_cmd);
mtl_send_void0(cmd_buf, sel.commit as *mut c_void);
}
*ring_cursor = (slot_idx + 1) % GPU_DRIVER_RING_SLOTS;
unsafe { objc_autoreleasePoolPop(pool) };
total_instances
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn metal_submit_batches(device_handle: usize, queue_handle: usize, batches: &[GpuBatch]) -> usize {
let total_instances: usize = batches
.iter()
.map(|b: &GpuBatch| b.get_primitives().len().max(b.get_instances().len()))
.sum();
if device_handle == 0 || queue_handle == 0 || total_instances == 0 {
return total_instances;
}
let pool: *mut c_void = unsafe { objc_autoreleasePoolPush() };
let device: *mut c_void = device_handle as *mut c_void;
let queue: *mut c_void = queue_handle as *mut c_void;
let sel: &MetalSelectors = cached_metal_selectors();
let sel_buf: *mut c_void = sel.new_buffer_with_bytes as *mut c_void;
let sel_rel: *mut c_void = sel.release as *mut c_void;
unsafe {
let send_buf: unsafe extern "C" fn(
*mut c_void,
*mut c_void,
*const c_void,
usize,
usize,
) -> *mut c_void = transmute(objc_msgSend as *const c_void);
for batch in batches.iter() {
let prims: &[GpuPrimitiveInstance] = batch.get_primitives();
if !prims.is_empty() {
let byte_len: usize = size_of_val(prims);
let mtl_buf: *mut c_void = send_buf(
device,
sel_buf,
prims.as_ptr().cast::<c_void>(),
byte_len,
0,
);
if !mtl_buf.is_null() {
mtl_send_void0(mtl_buf, sel_rel);
}
} else {
let instances: &[GpuQuadInstance] = batch.get_instances();
if instances.is_empty() {
continue;
}
let byte_len: usize = size_of_val(instances);
let mtl_buf: *mut c_void = send_buf(
device,
sel_buf,
instances.as_ptr().cast::<c_void>(),
byte_len,
0,
);
if !mtl_buf.is_null() {
mtl_send_void0(mtl_buf, sel_rel);
}
}
}
let cmd_buf: *mut c_void = mtl_send_ptr0(queue, sel.command_buffer as *mut c_void);
if !cmd_buf.is_null() {
mtl_send_void0(cmd_buf, sel.commit as *mut c_void);
}
objc_autoreleasePoolPop(pool);
}
total_instances
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn metal_release_handles(device_handle: usize, queue_handle: usize, library_handle: usize) {
let sel_rel: *mut c_void = cached_metal_selectors().release as *mut c_void;
if library_handle != 0 {
mtl_send_void0(library_handle as *mut c_void, sel_rel);
}
if queue_handle != 0 {
mtl_send_void0(queue_handle as *mut c_void, sel_rel);
}
if device_handle != 0 {
mtl_send_void0(device_handle as *mut c_void, sel_rel);
}
}
#[cfg(target_os = "windows")]
#[link(name = "kernel32")]
unsafe extern "system" {
fn LoadLibraryA(lp_lib_file_name: *const u8) -> *mut c_void;
fn GetProcAddress(h_module: *mut c_void, lp_proc_name: *const u8) -> *mut c_void;
}
#[cfg(target_os = "windows")]
fn probe_windows_d3d12(backend: GraphicsBackend) -> (GpuAdapterInfo, usize, usize, usize) {
let cached: &WindowsD3d12ProbeCache = WINDOWS_D3D12_CACHE.get_or_init(|| unsafe {
let d3d12_mod: *mut c_void = LoadLibraryA(DLL_D3D12.as_ptr());
let has_d3d12: bool = if !d3d12_mod.is_null() {
!GetProcAddress(d3d12_mod, SYM_D3D12_CREATE_DEVICE.as_ptr()).is_null()
} else {
false
};
let compiler_mod: *mut c_void = LoadLibraryA(DLL_D3DCOMPILER.as_ptr());
let has_compiler: bool = if !compiler_mod.is_null() {
!GetProcAddress(compiler_mod, SYM_D3D_COMPILE.as_ptr()).is_null()
} else {
false
};
WindowsD3d12ProbeCache {
has_d3d12,
has_compiler,
}
});
let label: &str = if cached.has_d3d12 {
GPU_DEVICE_D3D12
} else {
GPU_DEVICE_FALLBACK
};
(
GpuAdapterInfo::new(
backend,
label.to_string(),
cached.has_d3d12,
cached.has_compiler,
),
0,
0,
0,
)
}
#[cfg(any(target_os = "linux", target_os = "android"))]
unsafe extern "C" {
fn dlopen(filename: *const c_char, flags: i32) -> *mut c_void;
fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
}
#[cfg(any(target_os = "linux", target_os = "android"))]
fn probe_vulkan_runtime(backend: GraphicsBackend) -> (GpuAdapterInfo, usize, usize, usize) {
let cached: &VulkanProbeCache = VULKAN_PROBE_CACHE.get_or_init(|| {
let Ok(lib_name) = CString::new(LIB_VULKAN_SONAME) else {
return VulkanProbeCache {
available: false,
lib_handle: 0,
};
};
let Ok(sym_create) = CString::new(SYM_VK_CREATE_INSTANCE) else {
return VulkanProbeCache {
available: false,
lib_handle: 0,
};
};
let Ok(sym_enum) = CString::new(SYM_VK_ENUM_DEVICES) else {
return VulkanProbeCache {
available: false,
lib_handle: 0,
};
};
unsafe {
let handle: *mut c_void = dlopen(lib_name.as_ptr(), RTLD_LAZY_GPU);
if handle.is_null() {
VulkanProbeCache {
available: false,
lib_handle: 0,
}
} else {
let p1: *mut c_void = dlsym(handle, sym_create.as_ptr());
let p2: *mut c_void = dlsym(handle, sym_enum.as_ptr());
VulkanProbeCache {
available: !p1.is_null() && !p2.is_null(),
lib_handle: handle as usize,
}
}
}
});
let name: &str = if cached.available {
GPU_DEVICE_VULKAN
} else {
GPU_DEVICE_FALLBACK
};
(
GpuAdapterInfo::new(
backend,
name.to_string(),
cached.available,
cached.available,
),
cached.lib_handle,
0,
0,
)
}
#[cfg(target_arch = "wasm32")]
pub fn webgl2_compile_ui_program(gl: &WebGl2RenderingContext) -> Option<WebGlProgram> {
let vs: WebGlShader = gl.create_shader(WebGl2RenderingContext::VERTEX_SHADER)?;
gl.shader_source(&vs, GLSL_ES3_UI_VERTEX_SHADER);
gl.compile_shader(&vs);
let fs: WebGlShader = gl.create_shader(WebGl2RenderingContext::FRAGMENT_SHADER)?;
gl.shader_source(&fs, GLSL_ES3_UI_FRAGMENT_SHADER);
gl.compile_shader(&fs);
let program: WebGlProgram = gl.create_program()?;
gl.attach_shader(&program, &vs);
gl.attach_shader(&program, &fs);
gl.link_program(&program);
Some(program)
}
#[must_use]
pub const fn gles3_ui_instance_attribs() -> [Gles3InstanceAttribSpec; 5] {
let stride: i32 = GPU_PRIMITIVE_INSTANCE_BYTES as i32;
[
Gles3InstanceAttribSpec {
location: 1,
components: 4,
is_integer: false,
byte_offset: 0,
stride,
},
Gles3InstanceAttribSpec {
location: 2,
components: 4,
is_integer: false,
byte_offset: 16,
stride,
},
Gles3InstanceAttribSpec {
location: 3,
components: 2,
is_integer: true,
byte_offset: 32,
stride,
},
Gles3InstanceAttribSpec {
location: 4,
components: 4,
is_integer: true,
byte_offset: 40,
stride,
},
Gles3InstanceAttribSpec {
location: 5,
components: 2,
is_integer: true,
byte_offset: 56,
stride,
},
]
}
#[must_use]
pub fn gles3_scissor_from_top_down(surface_h: u32, sx: u32, sy: u32, sw: u32, sh: u32) -> [i32; 4] {
let y1: u32 = sy.saturating_add(sh).min(surface_h);
let y_bottom: u32 = surface_h.saturating_sub(y1);
[sx as i32, y_bottom as i32, sw as i32, sh as i32]
}
#[must_use]
pub fn select_adaptive_upload_plan(
fb_w: u32,
fb_h: u32,
dirty_rects: &[PixelDirtyRect],
force_full: bool,
) -> AdaptiveUploadPlan {
if fb_w == 0 || fb_h == 0 {
return AdaptiveUploadPlan {
strategy: MobileUploadStrategy::None,
rects: Vec::new(),
total_upload_bytes: 0,
merged_bbox_bytes: 0,
full_frame_bytes: 0,
estimated_cost_score: 0.0,
};
}
let full_rect: PixelDirtyRect = PixelDirtyRect::new(0, 0, fb_w, fb_h);
let full_bytes: usize = full_rect.byte_size_rgba8();
if force_full {
return AdaptiveUploadPlan {
strategy: MobileUploadStrategy::FullFrame,
rects: vec![full_rect],
total_upload_bytes: full_bytes,
merged_bbox_bytes: full_bytes,
full_frame_bytes: full_bytes,
estimated_cost_score: (full_bytes + MOBILE_UPLOAD_PER_RECT_OVERHEAD_BYTES) as f32,
};
}
let mut coalesced: Vec<PixelDirtyRect> = Vec::with_capacity(dirty_rects.len().min(16));
for rect in dirty_rects.iter() {
let Some(mut clamped) = rect.clamp_to(fb_w, fb_h) else {
continue;
};
let mut merged_any: bool = true;
while merged_any {
merged_any = false;
let mut idx: usize = 0;
while idx < coalesced.len() {
if coalesced[idx].intersects_or_adjacent(clamped, MOBILE_UPLOAD_COALESCE_PAD_PX) {
let existing: PixelDirtyRect = coalesced.swap_remove(idx);
clamped = clamped.union_with(existing);
merged_any = true;
} else {
idx += 1;
}
}
}
coalesced.push(clamped);
}
if coalesced.is_empty() {
return AdaptiveUploadPlan {
strategy: MobileUploadStrategy::None,
rects: Vec::new(),
total_upload_bytes: 0,
merged_bbox_bytes: 0,
full_frame_bytes: full_bytes,
estimated_cost_score: 0.0,
};
}
let mut merged_bbox: PixelDirtyRect = coalesced[0];
let mut multi_bytes: usize = 0;
for r in coalesced.iter() {
merged_bbox = merged_bbox.union_with(*r);
multi_bytes = multi_bytes.saturating_add(r.byte_size_rgba8());
}
let merged_bytes: usize = merged_bbox.byte_size_rgba8();
let multi_cost: usize = multi_bytes.saturating_add(
coalesced
.len()
.saturating_mul(MOBILE_UPLOAD_PER_RECT_OVERHEAD_BYTES),
);
let merged_cost: usize = merged_bytes.saturating_add(MOBILE_UPLOAD_PER_RECT_OVERHEAD_BYTES);
let full_threshold_bytes: usize =
((full_bytes as f32) * MOBILE_UPLOAD_FULL_FRAME_COVERAGE_THRESHOLD).round() as usize;
let full_cost: usize = full_bytes.saturating_add(MOBILE_UPLOAD_PER_RECT_OVERHEAD_BYTES);
let multi_eligible: bool = coalesced.len() >= 2
&& coalesced.len() <= MOBILE_MAX_MULTI_UPLOAD_RECTS
&& multi_bytes <= full_threshold_bytes
&& multi_cost < merged_cost
&& multi_cost < full_cost;
if multi_eligible {
return AdaptiveUploadPlan {
strategy: MobileUploadStrategy::MultiRect,
rects: coalesced,
total_upload_bytes: multi_bytes,
merged_bbox_bytes: merged_bytes,
full_frame_bytes: full_bytes,
estimated_cost_score: multi_cost as f32,
};
}
if merged_bytes <= full_threshold_bytes && merged_cost < full_cost {
return AdaptiveUploadPlan {
strategy: MobileUploadStrategy::MergedBbox,
rects: vec![merged_bbox],
total_upload_bytes: merged_bytes,
merged_bbox_bytes: merged_bytes,
full_frame_bytes: full_bytes,
estimated_cost_score: merged_cost as f32,
};
}
AdaptiveUploadPlan {
strategy: MobileUploadStrategy::FullFrame,
rects: vec![full_rect],
total_upload_bytes: full_bytes,
merged_bbox_bytes: merged_bytes,
full_frame_bytes: full_bytes,
estimated_cost_score: full_cost as f32,
}
}
#[must_use]
pub fn damage_region_to_pixel_dirty_rects(
damage: DamageRegion,
fb_w: u32,
fb_h: u32,
) -> Vec<PixelDirtyRect> {
if fb_w == 0 || fb_h == 0 {
return Vec::new();
}
if damage.get_full_damage() {
return vec![PixelDirtyRect::new(0, 0, fb_w, fb_h)];
}
let Some(r) = damage.resolve(fb_w, fb_h) else {
return Vec::new();
};
let rx0: u32 = (r.get_x().floor().max(0.0) as u32).min(fb_w);
let ry0: u32 = (r.get_y().floor().max(0.0) as u32).min(fb_h);
let rx1: u32 = (r.right().ceil().max(0.0) as u32).clamp(rx0, fb_w);
let ry1: u32 = (r.bottom().ceil().max(0.0) as u32).clamp(ry0, fb_h);
if rx1 > rx0 && ry1 > ry0 {
vec![PixelDirtyRect::new(rx0, ry0, rx1 - rx0, ry1 - ry0)]
} else {
Vec::new()
}
}
#[must_use]
pub fn build_direct_gpu_frame_batch_from_batches(
viewport_width: u32,
viewport_height: u32,
clear_color: Color,
batches: &[GpuBatch],
blur_passes: &[GpuBackdropBlurPass],
) -> DirectGpuFrameBatch {
let total_prims: usize = batches
.iter()
.map(|b: &GpuBatch| b.get_primitives().len().max(b.get_instances().len()))
.sum();
let mut primitives: Vec<GpuPrimitiveInstance> = Vec::with_capacity(total_prims);
let mut draw_ranges: Vec<DirectGpuBatchRange> = Vec::with_capacity(batches.len());
let vw: u32 = viewport_width.max(1);
let vh: u32 = viewport_height.max(1);
for batch in batches.iter() {
let base_instance: u32 = primitives.len() as u32;
if !batch.get_primitives().is_empty() {
primitives.extend_from_slice(batch.get_primitives());
} else {
for quad in batch.get_instances().iter() {
primitives.push(GpuPrimitiveInstance::from_quad_instance(
quad,
batch.get_texture_slot(),
batch.get_layer_id(),
));
}
}
let instance_count: u32 = (primitives.len() as u32).saturating_sub(base_instance);
if instance_count == 0 {
continue;
}
let sc: Rect = batch.get_scissor();
let sx: u32 = (sc.get_x().max(0.0).floor() as u32).min(vw.saturating_sub(1));
let sy: u32 = (sc.get_y().max(0.0).floor() as u32).min(vh.saturating_sub(1));
let sw: u32 = (sc.get_width().max(1.0).ceil() as u32)
.min(vw.saturating_sub(sx))
.max(1);
let sh: u32 = (sc.get_height().max(1.0).ceil() as u32)
.min(vh.saturating_sub(sy))
.max(1);
let scroll: [f32; 2] = batch.get_scroll_offset();
draw_ranges.push(DirectGpuBatchRange {
base_instance,
instance_count,
scissor_x: sx,
scissor_y: sy,
scissor_w: sw,
scissor_h: sh,
scroll_x: scroll[0],
scroll_y: scroll[1],
texture_slot: batch.get_texture_slot(),
layer_id: batch.get_layer_id(),
pad: [0, 0],
});
}
let instance_upload_bytes: usize = primitives
.len()
.saturating_mul(GPU_PRIMITIVE_INSTANCE_BYTES);
DirectGpuFrameBatch {
viewport_width: vw,
viewport_height: vh,
clear_rgba: clear_color.to_f32_array(),
primitives,
draw_ranges,
backdrop_blurs: blur_passes.to_vec(),
glyph_r8_atlas: None,
image_rgba8_atlas: None,
instance_upload_bytes,
cpu_mirror_active: false,
upload_strategy: MobileUploadStrategy::DirectGpu,
}
}
fn push_direct_gpu_primitive(
primitives: &mut Vec<GpuPrimitiveInstance>,
draw_ranges: &mut Vec<DirectGpuBatchRange>,
prim: GpuPrimitiveInstance,
clip: Rect,
vw: u32,
vh: u32,
) {
let sx: u32 = (clip.get_x().max(0.0).floor() as u32).min(vw.saturating_sub(1));
let sy: u32 = (clip.get_y().max(0.0).floor() as u32).min(vh.saturating_sub(1));
let sw: u32 = (clip.get_width().max(1.0).ceil() as u32)
.min(vw.saturating_sub(sx))
.max(1);
let sh: u32 = (clip.get_height().max(1.0).ceil() as u32)
.min(vh.saturating_sub(sy))
.max(1);
let layer_id: u8 = prim.layer_id();
let base: u32 = primitives.len() as u32;
primitives.push(prim);
if let Some(last) = draw_ranges.last_mut()
&& last.get_scissor_x() == sx
&& last.get_scissor_y() == sy
&& last.get_scissor_w() == sw
&& last.get_scissor_h() == sh
&& last.get_layer_id() == layer_id
&& last.get_instance_count() < MAX_QUADS_PER_BATCH as u32
{
last.set_instance_count(last.get_instance_count().saturating_add(1));
return;
}
draw_ranges.push(DirectGpuBatchRange {
base_instance: base,
instance_count: 1,
scissor_x: sx,
scissor_y: sy,
scissor_w: sw,
scissor_h: sh,
scroll_x: 0.0,
scroll_y: 0.0,
texture_slot: 0,
layer_id,
pad: [0, 0],
});
}
fn encode_atlas_uv_rect(atlas_w: u32, atlas_h: u32, x: u32, y: u32, w: u32, h: u32) -> [u16; 4] {
let inv_w: f32 = 1.0 / (atlas_w.max(1) as f32);
let inv_h: f32 = 1.0 / (atlas_h.max(1) as f32);
let u0: u16 = (((x as f32) * inv_w).clamp(0.0, 1.0) * 65535.0).round() as u16;
let v0: u16 = (((y as f32) * inv_h).clamp(0.0, 1.0) * 65535.0).round() as u16;
let u1: u16 = ((((x + w) as f32) * inv_w).clamp(0.0, 1.0) * 65535.0).round() as u16;
let v1: u16 = ((((y + h) as f32) * inv_h).clamp(0.0, 1.0) * 65535.0).round() as u16;
[u0, v0, u1, v1]
}
fn pack_frame_image_atlas(
images: &[DirectGpuImageSlice<'_>],
revision: u64,
) -> (Option<DirectGpuAtlasUpload>, Vec<[u16; 4]>) {
if images.is_empty() {
return (None, Vec::new());
}
let mut max_w: u32 = 1;
let mut sum_w: u32 = 1;
for entry in images.iter() {
let cw: u32 = entry.crop.get_width();
max_w = max_w.max(cw.saturating_add(2));
sum_w = sum_w.saturating_add(cw.saturating_add(1));
}
let atlas_w: u32 = sum_w
.clamp(64, 2048)
.max(max_w)
.next_power_of_two()
.min(4096);
let mut placements: Vec<(u32, u32, u32, u32)> = Vec::with_capacity(images.len());
let mut cx: u32 = 1;
let mut cy: u32 = 1;
let mut shelf_h: u32 = 0;
for entry in images.iter() {
let clamped_w: u32 = entry.crop.get_width().min(atlas_w.saturating_sub(2)).max(1);
let clamped_h: u32 = entry.crop.get_height().max(1);
if cx + clamped_w + 1 > atlas_w {
cx = 1;
cy = cy.saturating_add(shelf_h).saturating_add(1);
shelf_h = 0;
}
placements.push((cx, cy, clamped_w, clamped_h));
cx = cx.saturating_add(clamped_w).saturating_add(1);
shelf_h = shelf_h.max(clamped_h);
}
let atlas_h: u32 = cy.saturating_add(shelf_h).saturating_add(1).max(64);
let mut pixels: Vec<u8> = vec![0; (atlas_w as usize) * (atlas_h as usize) * 4];
let mut uvs: Vec<[u16; 4]> = Vec::with_capacity(images.len());
for (idx, entry) in images.iter().enumerate() {
let (dx, dy, copy_w, copy_h): (u32, u32, u32, u32) = placements[idx];
let sx: u32 = entry.crop.get_x();
let sy: u32 = entry.crop.get_y();
let valid_w: u32 = copy_w.min(entry.src_w.saturating_sub(sx));
let valid_h: u32 = copy_h.min(entry.src_h.saturating_sub(sy));
for row in 0..valid_h {
let src_off: usize =
(((sy + row) as usize) * (entry.src_w as usize) + (sx as usize)) * 4;
let dst_off: usize = (((dy + row) as usize) * (atlas_w as usize) + (dx as usize)) * 4;
let row_bytes: usize = (valid_w as usize) * 4;
if src_off + row_bytes <= entry.pixels.len() && dst_off + row_bytes <= pixels.len() {
pixels[dst_off..dst_off + row_bytes]
.copy_from_slice(&entry.pixels[src_off..src_off + row_bytes]);
}
}
uvs.push(encode_atlas_uv_rect(
atlas_w, atlas_h, dx, dy, valid_w, valid_h,
));
}
(
Some(DirectGpuAtlasUpload {
width: atlas_w,
height: atlas_h,
revision,
pixels,
}),
uvs,
)
}
#[must_use]
pub fn compile_display_list_direct_gpu_batch(
display_list: &DisplayList,
mut glyph_atlas: Option<&mut GlyphAtlas>,
font_provider: Option<&NativeSystemFont>,
last_glyph_revision: u64,
) -> DirectGpuFrameBatch {
let scale: f32 = display_list.get_scale_factor().max(0.5);
let phys_w: u32 = ((display_list.get_viewport().get_width() * scale).round() as u32).max(1);
let phys_h: u32 = ((display_list.get_viewport().get_height() * scale).round() as u32).max(1);
let full_clip: Rect = Rect::new(0.0, 0.0, phys_w as f32, phys_h as f32);
let mut clip_stack: Vec<Rect> = Vec::with_capacity(16);
clip_stack.push(full_clip);
let mut primitives: Vec<GpuPrimitiveInstance> =
Vec::with_capacity(display_list.get_commands().len().saturating_mul(2));
let mut draw_ranges: Vec<DirectGpuBatchRange> = Vec::with_capacity(16);
let mut backdrop_blurs: Vec<GpuBackdropBlurPass> = Vec::new();
let mut glyph_fixups: Vec<(usize, GlyphKey)> = Vec::new();
let mut image_entries: Vec<DirectGpuImageSlice<'_>> = Vec::new();
let mut image_fixups: Vec<(usize, usize)> = Vec::new();
let mut clear_rgba: [f32; 4] = COLOR_WHITE.to_f32_array();
let mut active_layer_id: u8 = 0;
for cmd in display_list.get_commands().iter() {
let active_clip: Rect = clip_stack.last().copied().unwrap_or(full_clip);
let clip_arr: [f32; 4] = [
active_clip.get_x(),
active_clip.get_y(),
active_clip.right(),
active_clip.bottom(),
];
match cmd {
DrawCommand::Clear(c) => {
clear_rgba = c.to_f32_array();
}
DrawCommand::PushClip(rect) => {
let phys: Rect = snap_physical_rect(*rect, scale);
clip_stack.push(active_clip.intersect(phys).unwrap_or_default());
}
DrawCommand::PushRoundedClip { rect, .. } => {
let phys: Rect = snap_physical_rect(*rect, scale);
clip_stack.push(active_clip.intersect(phys).unwrap_or_default());
}
DrawCommand::PopClip => {
if clip_stack.len() > 1 {
let _: Option<Rect> = clip_stack.pop();
}
}
DrawCommand::FillRoundedRect {
rect,
color,
radius,
border,
} => {
let snapped: Rect = snap_physical_rect(*rect, scale);
let quad: [f32; 4] = [
snapped.get_x(),
snapped.get_y(),
snapped.get_width(),
snapped.get_height(),
];
if quad[2] <= 0.0 || quad[3] <= 0.0 || active_clip.get_width() <= 0.0 {
continue;
}
let bw: f32 = if border.get_width() > 0.0 {
(border.get_width() * scale).max(1.0)
} else {
0.0
};
let q: GpuQuadInstance = GpuQuadInstance {
rect: quad,
clip: clip_arr,
color: color.to_f32_array(),
secondary_color: border.get_color().to_f32_array(),
radii: [
radius.get_top_left() * scale,
radius.get_top_right() * scale,
radius.get_bottom_right() * scale,
radius.get_bottom_left() * scale,
],
stroke_or_blur: bw,
angle_rad: 0.0,
kind: GpuPrimitiveKind::RoundedRect as u32,
reserved: 0,
};
push_direct_gpu_primitive(
&mut primitives,
&mut draw_ranges,
GpuPrimitiveInstance::from_quad_instance(&q, 0, active_layer_id),
active_clip,
phys_w,
phys_h,
);
}
DrawCommand::LinearGradientRect {
rect,
gradient,
radius,
} => {
let snapped: Rect = snap_physical_rect(*rect, scale);
let quad: [f32; 4] = [
snapped.get_x(),
snapped.get_y(),
snapped.get_width(),
snapped.get_height(),
];
if quad[2] <= 0.0 || quad[3] <= 0.0 || active_clip.get_width() <= 0.0 {
continue;
}
let q: GpuQuadInstance = GpuQuadInstance {
rect: quad,
clip: clip_arr,
color: gradient.get_start_color().to_f32_array(),
secondary_color: gradient.get_end_color().to_f32_array(),
radii: [
radius.get_top_left() * scale,
radius.get_top_right() * scale,
radius.get_bottom_right() * scale,
radius.get_bottom_left() * scale,
],
stroke_or_blur: 0.0,
angle_rad: gradient.get_angle_deg().to_radians(),
kind: GpuPrimitiveKind::Gradient as u32,
reserved: 0,
};
push_direct_gpu_primitive(
&mut primitives,
&mut draw_ranges,
GpuPrimitiveInstance::from_quad_instance(&q, 0, active_layer_id),
active_clip,
phys_w,
phys_h,
);
}
DrawCommand::BoxShadow {
rect,
radius,
shadow,
} => {
let spread: f32 = shadow.get_spread_radius() * scale;
let blur: f32 = (shadow.get_blur_radius().max(0.5) * scale).min(96.0);
let sigma: f32 = (blur * 0.5).max(0.75);
let pad: f32 = (sigma * 3.0).ceil();
let base_rect: Rect = snap_physical_rect(*rect, scale);
let cx: f32 = base_rect.get_x() + (shadow.get_offset_x() * scale).round() - spread;
let cy: f32 = base_rect.get_y() + (shadow.get_offset_y() * scale).round() - spread;
let cw: f32 = (base_rect.get_width() + spread * 2.0).max(1.0);
let ch: f32 = (base_rect.get_height() + spread * 2.0).max(1.0);
let q: GpuQuadInstance = GpuQuadInstance {
rect: [cx - pad, cy - pad, cw + pad * 2.0, ch + pad * 2.0],
clip: clip_arr,
color: shadow.get_color().to_f32_array(),
secondary_color: [0.0; 4],
radii: [
(radius.get_top_left() * scale + spread).max(0.0),
(radius.get_top_right() * scale + spread).max(0.0),
(radius.get_bottom_right() * scale + spread).max(0.0),
(radius.get_bottom_left() * scale + spread).max(0.0),
],
stroke_or_blur: sigma,
angle_rad: pad,
kind: GpuPrimitiveKind::Shadow as u32,
reserved: 0,
};
push_direct_gpu_primitive(
&mut primitives,
&mut draw_ranges,
GpuPrimitiveInstance::from_quad_instance(&q, 0, active_layer_id),
active_clip,
phys_w,
phys_h,
);
}
DrawCommand::BackdropBlur {
rect,
radius,
blur_radius,
} => {
let snapped: Rect = snap_physical_rect(*rect, scale);
let phys_blur: f32 = (*blur_radius * scale).clamp(0.5, 96.0);
let radii_px: [f32; 4] = [
radius.get_top_left() * scale,
radius.get_top_right() * scale,
radius.get_bottom_right() * scale,
radius.get_bottom_left() * scale,
];
let halo: Rect = Rect::new(
(snapped.get_x() - phys_blur).max(0.0),
(snapped.get_y() - phys_blur).max(0.0),
(snapped.get_width() + phys_blur * 2.0).min(phys_w as f32),
(snapped.get_height() + phys_blur * 2.0).min(phys_h as f32),
);
backdrop_blurs.push(GpuBackdropBlurPass {
bounds: snapped,
input_bounds: halo,
clip_rect: active_clip,
radii: radii_px,
blur_radius: phys_blur,
layer_id: active_layer_id,
});
active_layer_id = active_layer_id.saturating_add(1);
}
DrawCommand::TextRun { rect, text, style } => {
if text.is_empty()
|| active_clip.get_width() <= 0.0
|| active_clip.get_height() <= 0.0
{
continue;
}
if let Some(atlas) = glyph_atlas.as_deref_mut() {
let phys_font_px: f32 = (style.get_font_size() * scale).max(6.0);
let meas: TextLayoutResult = DeterministicTextMeasurer.measure(
text,
*style,
Some(rect.get_width().max(1.0)),
);
let line_h: f32 = meas.get_line_height_px() * scale;
let letter_sp: f32 = style.get_letter_spacing() * scale;
let rect_w_px: f32 = rect.get_width() * scale;
let color_rgba: u32 = GpuPrimitiveInstance::pack_color_rgba8(style.get_color());
let kind_flags: u32 = GpuPrimitiveInstance::pack_kind_flags(
PrimKind::GlyphAlpha8,
0,
0,
active_layer_id,
);
let mut line_glyphs: Vec<(Option<GlyphKey>, u32, u32, f32)> = Vec::new();
for (line_idx, line) in meas.get_lines().iter().enumerate() {
line_glyphs.clear();
let mut line_w_px: f32 = 0.0;
for ch in line.get_text().chars() {
if ch == ' ' || ch == '\t' {
let sp_adv: f32 = measure_char_advance(ch, *style) * scale;
line_glyphs.push((None, 0, 0, sp_adv));
line_w_px += sp_adv;
continue;
}
let key: GlyphKey = GlyphKey::from_text_style(ch, phys_font_px, *style);
let (gw, gh, adv): (u32, u32, f32) = {
let g: &RasterizedGlyph = match font_provider {
Some(fp) => atlas.get_or_rasterize_with(key, fp),
None => atlas.get_or_rasterize(key),
};
(
g.get_width(),
g.get_height(),
(g.get_advance() as f32).max(1.0) + letter_sp,
)
};
line_glyphs.push((Some(key), gw, gh, adv));
line_w_px += adv;
}
let align_offset: f32 = match style.get_align() {
TextAlign::Center => ((rect_w_px - line_w_px) * 0.5).max(0.0),
TextAlign::Right => (rect_w_px - line_w_px).max(0.0),
TextAlign::Left => 0.0,
};
let base_y: f32 = rect.get_y() * scale + (line_idx as f32) * line_h;
let mut pen_x: f32 = rect.get_x() * scale + align_offset;
for &(key_opt, gw, gh, adv) in line_glyphs.iter() {
if let Some(key) = key_opt
&& gw > 0
&& gh > 0
{
let y_off: f32 = ((line_h - (gh as f32)) * 0.5).round();
let prim_idx: usize = primitives.len();
let prim: GpuPrimitiveInstance = GpuPrimitiveInstance {
rect: [
pen_x.round(),
(base_y + y_off).round(),
gw as f32,
gh as f32,
],
clip_rect: clip_arr,
color_rgba,
aux_color_rgba: 0,
uv_rect: [0, 0, 0, 0],
radii_border: [0; 4],
kind_flags,
extra_param: 0,
};
push_direct_gpu_primitive(
&mut primitives,
&mut draw_ranges,
prim,
active_clip,
phys_w,
phys_h,
);
glyph_fixups.push((prim_idx, key));
}
pen_x += adv;
}
}
} else {
let q: GpuQuadInstance = GpuQuadInstance {
rect: [
rect.get_x() * scale,
rect.get_y() * scale,
rect.get_width() * scale,
rect.get_height() * scale,
],
clip: clip_arr,
color: style.get_color().to_f32_array(),
secondary_color: [0.0; 4],
radii: [0.0; 4],
stroke_or_blur: style.get_font_size() * scale,
angle_rad: 0.0,
kind: GpuPrimitiveKind::Glyph as u32,
reserved: text.chars().count() as u32,
};
push_direct_gpu_primitive(
&mut primitives,
&mut draw_ranges,
GpuPrimitiveInstance::from_quad_instance(&q, 0, active_layer_id),
active_clip,
phys_w,
phys_h,
);
}
}
DrawCommand::TextCaret {
text_rect,
content_rect,
text,
style,
caret_height,
color,
multiline,
} => {
if active_clip.get_width() <= 0.0 || active_clip.get_height() <= 0.0 {
continue;
}
let meas: TextLayoutResult = DeterministicTextMeasurer.measure(
text,
*style,
if *multiline {
Some(content_rect.get_width().max(1.0))
} else {
None
},
);
let last_w: f32 = meas
.get_lines()
.last()
.map(TextLine::get_width)
.unwrap_or(0.0);
let line_idx: usize = meas.get_lines().len().saturating_sub(1);
let caret_x: f32 =
(text_rect.get_x() + last_w + if last_w > 0.0 { 1.5 } else { 0.0 }).clamp(
content_rect.get_x(),
(content_rect.right() - 2.0).max(content_rect.get_x()),
);
let caret_y: f32 = if *multiline {
(content_rect.get_y()
+ (line_idx as f32) * meas.get_line_height_px()
+ ((meas.get_line_height_px() - caret_height) * 0.5).max(0.0))
.clamp(
content_rect.get_y(),
(content_rect.bottom() - caret_height).max(content_rect.get_y()),
)
} else {
content_rect.get_y()
+ ((content_rect.get_height() - caret_height) * 0.5).max(0.0)
};
let q: GpuQuadInstance = GpuQuadInstance {
rect: [
caret_x * scale,
caret_y * scale,
(1.5 * scale).max(1.0),
(caret_height * scale).max(2.0),
],
clip: clip_arr,
color: color.to_f32_array(),
secondary_color: [0.0; 4],
radii: [0.5 * scale; 4],
stroke_or_blur: 0.0,
angle_rad: 0.0,
kind: GpuPrimitiveKind::RoundedRect as u32,
reserved: 0,
};
push_direct_gpu_primitive(
&mut primitives,
&mut draw_ranges,
GpuPrimitiveInstance::from_quad_instance(&q, 0, active_layer_id),
active_clip,
phys_w,
phys_h,
);
}
DrawCommand::Image {
rect,
buffer,
radius,
} => {
let snapped: Rect = snap_physical_rect(*rect, scale);
let img_w: u32 = buffer.get_width();
let img_h: u32 = buffer.get_height();
if img_w == 0
|| img_h == 0
|| snapped.get_width() <= 0.0
|| snapped.get_height() <= 0.0
{
continue;
}
let img_idx: usize = image_entries.len();
image_entries.push(DirectGpuImageSlice {
src_w: img_w,
src_h: img_h,
pixels: buffer.get_pixels(),
crop: PixelDirtyRect::new(0, 0, img_w, img_h),
});
let q: GpuQuadInstance = GpuQuadInstance {
rect: [
snapped.get_x(),
snapped.get_y(),
snapped.get_width(),
snapped.get_height(),
],
clip: clip_arr,
color: [1.0, 1.0, 1.0, 1.0],
secondary_color: [0.0; 4],
radii: [
radius.get_top_left() * scale,
radius.get_top_right() * scale,
radius.get_bottom_right() * scale,
radius.get_bottom_left() * scale,
],
stroke_or_blur: 0.0,
angle_rad: 0.0,
kind: GpuPrimitiveKind::TexturedQuad as u32,
reserved: 0,
};
let prim_idx: usize = primitives.len();
push_direct_gpu_primitive(
&mut primitives,
&mut draw_ranges,
GpuPrimitiveInstance::from_quad_instance(&q, 0, active_layer_id),
active_clip,
phys_w,
phys_h,
);
image_fixups.push((prim_idx, img_idx));
}
DrawCommand::SharedImage {
rect,
width,
height,
pixels,
radius,
} => {
let snapped: Rect = snap_physical_rect(*rect, scale);
if *width == 0
|| *height == 0
|| snapped.get_width() <= 0.0
|| snapped.get_height() <= 0.0
{
continue;
}
let img_idx: usize = image_entries.len();
image_entries.push(DirectGpuImageSlice {
src_w: *width,
src_h: *height,
pixels: pixels.as_slice(),
crop: PixelDirtyRect::new(0, 0, *width, *height),
});
let q: GpuQuadInstance = GpuQuadInstance {
rect: [
snapped.get_x(),
snapped.get_y(),
snapped.get_width(),
snapped.get_height(),
],
clip: clip_arr,
color: [1.0, 1.0, 1.0, 1.0],
secondary_color: [0.0; 4],
radii: [
radius.get_top_left() * scale,
radius.get_top_right() * scale,
radius.get_bottom_right() * scale,
radius.get_bottom_left() * scale,
],
stroke_or_blur: 0.0,
angle_rad: 0.0,
kind: GpuPrimitiveKind::TexturedQuad as u32,
reserved: 0,
};
let prim_idx: usize = primitives.len();
push_direct_gpu_primitive(
&mut primitives,
&mut draw_ranges,
GpuPrimitiveInstance::from_quad_instance(&q, 0, active_layer_id),
active_clip,
phys_w,
phys_h,
);
image_fixups.push((prim_idx, img_idx));
}
DrawCommand::SpriteRegion {
rect,
buffer,
src_rect,
tint,
} => {
let snapped: Rect = snap_physical_rect(*rect, scale);
let img_w: u32 = buffer.get_width();
let img_h: u32 = buffer.get_height();
let sx: u32 = (src_rect.get_x().max(0.0).floor() as u32).min(img_w);
let sy: u32 = (src_rect.get_y().max(0.0).floor() as u32).min(img_h);
let sw: u32 =
(src_rect.get_width().max(1.0).ceil() as u32).min(img_w.saturating_sub(sx));
let sh: u32 =
(src_rect.get_height().max(1.0).ceil() as u32).min(img_h.saturating_sub(sy));
if sw == 0 || sh == 0 || snapped.get_width() <= 0.0 || snapped.get_height() <= 0.0 {
continue;
}
let img_idx: usize = image_entries.len();
image_entries.push(DirectGpuImageSlice {
src_w: img_w,
src_h: img_h,
pixels: buffer.get_pixels(),
crop: PixelDirtyRect::new(sx, sy, sw, sh),
});
let q: GpuQuadInstance = GpuQuadInstance {
rect: [
snapped.get_x(),
snapped.get_y(),
snapped.get_width(),
snapped.get_height(),
],
clip: clip_arr,
color: tint.to_f32_array(),
secondary_color: [0.0; 4],
radii: [0.0; 4],
stroke_or_blur: 0.0,
angle_rad: 0.0,
kind: GpuPrimitiveKind::TexturedQuad as u32,
reserved: 1,
};
let prim_idx: usize = primitives.len();
push_direct_gpu_primitive(
&mut primitives,
&mut draw_ranges,
GpuPrimitiveInstance::from_quad_instance(&q, 0, active_layer_id),
active_clip,
phys_w,
phys_h,
);
image_fixups.push((prim_idx, img_idx));
}
DrawCommand::Circle {
center,
radius,
color,
} => {
let r: f32 = radius * scale;
let pad: f32 = 1.5;
let extent: f32 = r + pad;
let q: GpuQuadInstance = GpuQuadInstance {
rect: [
center.get_x() * scale - extent,
center.get_y() * scale - extent,
extent * 2.0,
extent * 2.0,
],
clip: clip_arr,
color: color.to_f32_array(),
secondary_color: [0.0; 4],
radii: [r; 4],
stroke_or_blur: r,
angle_rad: 0.0,
kind: GpuPrimitiveKind::Circle as u32,
reserved: 0,
};
push_direct_gpu_primitive(
&mut primitives,
&mut draw_ranges,
GpuPrimitiveInstance::from_quad_instance(&q, 0, active_layer_id),
active_clip,
phys_w,
phys_h,
);
}
DrawCommand::Line {
from,
to,
color,
width,
} => {
let fx0: f32 = from.get_x() * scale;
let fy0: f32 = from.get_y() * scale;
let fx1: f32 = to.get_x() * scale;
let fy1: f32 = to.get_y() * scale;
let dx: f32 = fx1 - fx0;
let dy: f32 = fy1 - fy0;
let stroke_px: f32 = (width * scale).max(1.0);
let pad: f32 = stroke_px * 0.5 + 1.5;
let min_x: f32 = fx0.min(fx1) - pad;
let min_y: f32 = fy0.min(fy1) - pad;
let max_x: f32 = fx0.max(fx1) + pad;
let max_y: f32 = fy0.max(fy1) + pad;
let q: GpuQuadInstance = GpuQuadInstance {
rect: [
min_x,
min_y,
(max_x - min_x).max(2.0),
(max_y - min_y).max(2.0),
],
clip: clip_arr,
color: color.to_f32_array(),
secondary_color: [0.0; 4],
radii: [fx0, fy0, fx1, fy1],
stroke_or_blur: stroke_px,
angle_rad: dy.atan2(dx),
kind: GpuPrimitiveKind::Line as u32,
reserved: 0,
};
push_direct_gpu_primitive(
&mut primitives,
&mut draw_ranges,
GpuPrimitiveInstance::from_quad_instance(&q, 0, active_layer_id),
active_clip,
phys_w,
phys_h,
);
}
DrawCommand::Triangle { p0, p1, p2, color } => {
let min_x: f32 = p0.get_x().min(p1.get_x()).min(p2.get_x()) * scale - 1.5;
let min_y: f32 = p0.get_y().min(p1.get_y()).min(p2.get_y()) * scale - 1.5;
let max_x: f32 = p0.get_x().max(p1.get_x()).max(p2.get_x()) * scale + 1.5;
let max_y: f32 = p0.get_y().max(p1.get_y()).max(p2.get_y()) * scale + 1.5;
let q: GpuQuadInstance = GpuQuadInstance {
rect: [
min_x,
min_y,
(max_x - min_x).max(2.0),
(max_y - min_y).max(2.0),
],
clip: clip_arr,
color: color.to_f32_array(),
secondary_color: [p0.get_x() * scale, p0.get_y() * scale, 0.0, 0.0],
radii: [
p1.get_x() * scale,
p1.get_y() * scale,
p2.get_x() * scale,
p2.get_y() * scale,
],
stroke_or_blur: 0.0,
angle_rad: 0.0,
kind: GpuPrimitiveKind::Triangle as u32,
reserved: 3,
};
push_direct_gpu_primitive(
&mut primitives,
&mut draw_ranges,
GpuPrimitiveInstance::from_quad_instance(&q, 0, active_layer_id),
active_clip,
phys_w,
phys_h,
);
}
}
}
let mut glyph_r8_atlas: Option<DirectGpuAtlasUpload> = None;
if let Some(atlas) = glyph_atlas.as_deref()
&& (!glyph_fixups.is_empty() || atlas.get_revision() != last_glyph_revision)
&& !atlas.is_empty()
{
let packed: PackedGlyphAtlas = atlas.pack_rgba_atlas();
let aw: u32 = packed.get_width();
let ah: u32 = packed.get_height();
for &(prim_idx, key) in glyph_fixups.iter() {
if let Some(&(gx, gy, gw, gh)) = packed.get_regions().get(&key) {
primitives[prim_idx].set_uv_rect(encode_atlas_uv_rect(aw, ah, gx, gy, gw, gh));
}
}
if packed.get_revision() != last_glyph_revision {
let rgba: &[u8] = packed.get_pixels().as_slice();
let mut r8: Vec<u8> = Vec::with_capacity((aw as usize).saturating_mul(ah as usize));
for px in rgba.as_chunks::<4>().0 {
r8.push(px[3]);
}
glyph_r8_atlas = Some(DirectGpuAtlasUpload {
width: aw,
height: ah,
revision: packed.get_revision(),
pixels: r8,
});
}
}
let (image_rgba8_atlas, img_uvs): (Option<DirectGpuAtlasUpload>, Vec<[u16; 4]>) =
pack_frame_image_atlas(&image_entries, display_list.fast_hash());
for &(prim_idx, img_idx) in image_fixups.iter() {
if let Some(&uv) = img_uvs.get(img_idx) {
primitives[prim_idx].set_uv_rect(uv);
}
}
let glyph_bytes: usize = glyph_r8_atlas
.as_ref()
.map(|a: &DirectGpuAtlasUpload| a.get_pixels().len())
.unwrap_or(0);
let image_bytes: usize = image_rgba8_atlas
.as_ref()
.map(|a: &DirectGpuAtlasUpload| a.get_pixels().len())
.unwrap_or(0);
let instance_upload_bytes: usize = primitives
.len()
.saturating_mul(GPU_PRIMITIVE_INSTANCE_BYTES)
.saturating_add(glyph_bytes)
.saturating_add(image_bytes);
DirectGpuFrameBatch {
viewport_width: phys_w,
viewport_height: phys_h,
clear_rgba,
primitives,
draw_ranges,
backdrop_blurs,
glyph_r8_atlas,
image_rgba8_atlas,
instance_upload_bytes,
cpu_mirror_active: false,
upload_strategy: MobileUploadStrategy::DirectGpu,
}
}