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,
blur_up_pipeline_handle: 0,
engine3d_pipeline_handle: 0,
ocean_pipeline_handle: 0,
scene_ocean_pipeline_handle: 0,
scene_boat_pipeline_handle: 0,
scene_3d_sky_pipeline_handle: 0,
scene_3d_mesh_pipeline_handle: 0,
scene_depth_stencil_handle: 0,
dummy_r8_tex: 0,
dummy_rgba8_tex: 0,
};
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
{
if backend == GraphicsBackend::Metal {
probe_apple_metal_full(backend)
} else {
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,
blur_up_pipeline_handle: 0,
engine3d_pipeline_handle: 0,
ocean_pipeline_handle: 0,
scene_ocean_pipeline_handle: 0,
scene_boat_pipeline_handle: 0,
scene_3d_sky_pipeline_handle: 0,
scene_3d_mesh_pipeline_handle: 0,
scene_depth_stencil_handle: 0,
dummy_r8_tex: 0,
dummy_rgba8_tex: 0,
}
}
}
#[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,
blur_up_pipeline_handle: 0,
engine3d_pipeline_handle: 0,
ocean_pipeline_handle: 0,
scene_ocean_pipeline_handle: 0,
scene_boat_pipeline_handle: 0,
scene_3d_sky_pipeline_handle: 0,
scene_3d_mesh_pipeline_handle: 0,
scene_depth_stencil_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,
blur_up_pipeline_handle: 0,
engine3d_pipeline_handle: 0,
ocean_pipeline_handle: 0,
scene_ocean_pipeline_handle: 0,
scene_boat_pipeline_handle: 0,
scene_3d_sky_pipeline_handle: 0,
scene_3d_mesh_pipeline_handle: 0,
scene_depth_stencil_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,
blur_up_pipeline_handle: 0,
engine3d_pipeline_handle: 0,
ocean_pipeline_handle: 0,
scene_ocean_pipeline_handle: 0,
scene_boat_pipeline_handle: 0,
scene_3d_sky_pipeline_handle: 0,
scene_3d_mesh_pipeline_handle: 0,
scene_depth_stencil_handle: 0,
dummy_r8_tex: 0,
dummy_rgba8_tex: 0,
}
}
#[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "windows")))]
#[cfg(not(any(target_os = "linux", target_os = "android", target_arch = "wasm32")))]
{
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,
blur_up_pipeline_handle: 0,
engine3d_pipeline_handle: 0,
ocean_pipeline_handle: 0,
scene_ocean_pipeline_handle: 0,
scene_boat_pipeline_handle: 0,
scene_3d_sky_pipeline_handle: 0,
scene_3d_mesh_pipeline_handle: 0,
scene_depth_stencil_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(|blue_val: &GpuBatch| {
blue_val
.get_primitives()
.len()
.max(blue_val.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(|blue_val: &GpuBatch| {
blue_val
.get_primitives()
.len()
.max(blue_val.get_instances().len())
})
.sum()
}
}
pub(crate) fn execute_native_dual_kawase_blur_passes(
driver: &mut NativeGpuDriver,
width: u32,
height: u32,
blur_passes: &[GpuBackdropBlurPass],
) -> usize {
if blur_passes.is_empty() || !driver.supports_backdrop_blur_pass() {
return 0;
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
{
metal_execute_dual_kawase_blur_passes(driver, width, height, blur_passes)
}
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
{
let _: (&mut NativeGpuDriver, u32, u32) = (driver, width, height);
0
}
}
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;
pub(crate) fn objc_autoreleasePoolPush() -> *mut c_void;
pub(crate) fn objc_autoreleasePoolPop(pool: *mut c_void);
pub(crate) fn objc_msgSend();
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
unsafe extern "C" {
pub(crate) static _NSConcreteGlobalBlock: c_void;
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
pub(crate) 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"))]
pub(crate) 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"))]
pub(crate) 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"))]
pub(crate) 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"))]
pub(crate) 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"))]
pub(crate) 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"))]
pub(crate) 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"))]
pub(crate) 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"))]
pub(crate) 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"))]
pub(crate) 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"))]
pub(crate) 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"))]
pub(crate) 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"))]
pub(crate) 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);
LAST_GPU_RENDER_NS.store(exec_ns, Ordering::Relaxed);
}
let _: u64 = COMPLETED_GPU_FENCE.fetch_add(1, Ordering::Release);
}
#[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(),
MSL_ENGINE3D_PBR_SHADER.as_bytes(),
MSL_FLUID_OCEAN_SHADER.as_bytes(),
MSL_GPU_SCENE_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) {
metal_build_render_pipeline_with_depth(
device,
library,
vs_name,
fs_name,
archive,
enable_blend,
0,
)
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn metal_build_render_pipeline_with_depth(
device: *mut c_void,
library: *mut c_void,
vs_name: &str,
fs_name: &str,
archive: *mut c_void,
enable_blend: bool,
depth_pixel_format: usize,
) -> (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 depth_pixel_format != 0 {
mtl_send_void_usize(
desc,
mtl_sel_cstr(MTL_SEL_SET_DEPTH_ATTACHMENT_PIXEL_FORMAT),
depth_pixel_format,
);
}
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_build_render_pipeline_3d(
device: *mut c_void,
library: *mut c_void,
archive: *mut c_void,
) -> (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(MTL_FN_3D_VERTEX),
);
let fs_fn: *mut c_void = mtl_send_ptr1(
library,
mtl_sel_cstr(MTL_SEL_NEW_FUNCTION),
mtl_ns_string(MTL_FN_3D_FRAGMENT),
);
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 vdesc_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_VERTEX_DESC);
let vdesc_alloc: *mut c_void = mtl_send_ptr0(vdesc_cls, mtl_sel_cstr(MTL_SEL_ALLOC));
let vdesc: *mut c_void = mtl_send_ptr0(vdesc_alloc, mtl_sel_cstr(MTL_SEL_INIT));
if !vdesc.is_null() {
let send_idx: unsafe extern "C" fn(*mut c_void, *mut c_void, usize) -> *mut c_void =
unsafe { transmute(objc_msgSend as *const c_void) };
let sel_idx: *mut c_void = mtl_sel_cstr(MTL_SEL_OBJECT_AT_INDEX);
let attrs: *mut c_void = mtl_send_ptr0(vdesc, mtl_sel_cstr(MTL_SEL_ATTRIBUTES));
let attr0: *mut c_void = unsafe { send_idx(attrs, sel_idx, 0) };
let attr1: *mut c_void = unsafe { send_idx(attrs, sel_idx, 1) };
if !attr0.is_null() {
mtl_send_void_usize(
attr0,
mtl_sel_cstr(MTL_SEL_SET_FORMAT),
MTL_VERTEX_FORMAT_FLOAT3,
);
mtl_send_void_usize(attr0, mtl_sel_cstr(MTL_SEL_SET_OFFSET), 0);
mtl_send_void_usize(attr0, mtl_sel_cstr(MTL_SEL_SET_BUFFER_INDEX), 2);
}
if !attr1.is_null() {
mtl_send_void_usize(
attr1,
mtl_sel_cstr(MTL_SEL_SET_FORMAT),
MTL_VERTEX_FORMAT_FLOAT3,
);
mtl_send_void_usize(attr1, mtl_sel_cstr(MTL_SEL_SET_OFFSET), 12);
mtl_send_void_usize(attr1, mtl_sel_cstr(MTL_SEL_SET_BUFFER_INDEX), 2);
}
let layouts: *mut c_void = mtl_send_ptr0(vdesc, mtl_sel_cstr(MTL_SEL_LAYOUTS));
let layout2: *mut c_void = unsafe { send_idx(layouts, sel_idx, 2) };
if !layout2.is_null() {
mtl_send_void_usize(layout2, mtl_sel_cstr(MTL_SEL_SET_STRIDE), 24);
mtl_send_void_usize(
layout2,
mtl_sel_cstr(MTL_SEL_SET_STEP_FUNCTION),
MTL_VERTEX_STEP_PER_VERTEX,
);
mtl_send_void_usize(layout2, mtl_sel_cstr(MTL_SEL_SET_STEP_RATE), 1);
}
mtl_send_void_ptr1(desc, mtl_sel_cstr(MTL_SEL_SET_VERTEX_DESC), vdesc);
mtl_send_void0(vdesc, sel_rel);
}
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 !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_create_depth_stencil_state(device: *mut c_void) -> usize {
if device.is_null() {
return 0;
}
let cls: *mut c_void = mtl_cls_cstr(MTL_CLS_DEPTH_STENCIL_DESC);
if cls.is_null() {
return 0;
}
let alloc: *mut c_void = mtl_send_ptr0(cls, mtl_sel_cstr(MTL_SEL_ALLOC));
let desc: *mut c_void = mtl_send_ptr0(alloc, mtl_sel_cstr(MTL_SEL_INIT));
if desc.is_null() {
return 0;
}
mtl_send_void_usize(
desc,
mtl_sel_cstr(MTL_SEL_SET_DEPTH_COMPARE_FN),
MTL_COMPARE_FUNC_LESS,
);
mtl_send_void_bool(desc, mtl_sel_cstr(MTL_SEL_SET_DEPTH_WRITE_ENABLED), true);
let state: *mut c_void =
mtl_send_ptr1(device, mtl_sel_cstr(MTL_SEL_NEW_DEPTH_STENCIL_STATE), desc);
mtl_send_void0(desc, mtl_sel_cstr(MTL_SEL_RELEASE));
state as usize
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn metal_create_depth_texture(device: *mut c_void, width: u32, height: u32) -> usize {
if device.is_null() {
return 0;
}
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,
bool,
) -> *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),
MTL_PIXEL_FORMAT_DEPTH32_FLOAT,
width.max(1) as usize,
height.max(1) as usize,
false,
);
if desc.is_null() {
return 0;
}
mtl_send_void_usize(
desc,
mtl_sel_cstr(MTL_SEL_SET_USAGE),
MTL_TEX_USAGE_RENDER_TARGET_GPU,
);
mtl_send_void_usize(
desc,
mtl_sel_cstr(MTL_SEL_SET_STORAGE_MODE_GPU),
MTL_STORAGE_MODE_PRIVATE_GPU,
);
mtl_send_ptr1(device, mtl_sel_cstr(MTL_SEL_NEW_TEXTURE), desc) as usize
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn metal_ensure_and_upload_shared_buffer(
device: *mut c_void,
buf_handle: &mut usize,
buf_capacity: &mut usize,
bytes: &[u8],
) -> *mut c_void {
if device.is_null() || bytes.is_empty() {
return *buf_handle as *mut c_void;
}
let sel: &MetalSelectors = cached_metal_selectors();
if *buf_handle == 0 || *buf_capacity < bytes.len() {
if *buf_handle != 0 {
mtl_send_void0(*buf_handle as *mut c_void, sel.release as *mut c_void);
*buf_handle = 0;
*buf_capacity = 0;
}
let alloc_bytes: usize = bytes.len().max(1024).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() {
*buf_handle = new_buf as usize;
*buf_capacity = alloc_bytes;
}
}
}
if *buf_handle == 0 {
return null_mut();
}
let ptr: *mut c_void = mtl_send_ptr0(*buf_handle as *mut c_void, sel.contents as *mut c_void);
if !ptr.is_null() {
unsafe {
ptr.cast::<u8>()
.copy_from_nonoverlapping(bytes.as_ptr(), bytes.len());
}
}
*buf_handle as *mut c_void
}
#[must_use]
pub fn metal_binary_archive_allowed(device_name: &str, is_simulator: bool) -> bool {
if is_simulator {
return false;
}
let lower: String = device_name.to_ascii_lowercase();
!lower.contains(MTL_SIMULATOR_TOKEN) && !lower.contains(MTL_VIRTUAL_TOKEN)
}
#[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) {
if !metal_binary_archive_allowed(device_name, cfg!(target_abi = "sim"))
|| !mtl_responds_to_sel(device, mtl_sel_cstr(MTL_SEL_NEW_BINARY_ARCHIVE))
{
return (null_mut(), null_mut(), false);
}
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"))]
pub(crate) fn init_apple_metal_shared_cache(
backend: GraphicsBackend,
) -> &'static MetalSharedPipelineCache {
METAL_SHARED_PIPELINE.get_or_init(|| {
let pool: *mut c_void = unsafe { objc_autoreleasePoolPush() };
let total_start: Instant = Instant::now();
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,
blur_up_pipeline: 0,
engine3d_pipeline: 0,
ocean_pipeline: 0,
scene_ocean_pipeline: 0,
scene_boat_pipeline: 0,
scene_3d_sky_pipeline: 0,
scene_3d_mesh_pipeline: 0,
scene_depth_stencil: 0,
binary_archive_enabled: false,
binary_archive_hit: false,
ui_compile_us: 0,
blur_compile_us: 0,
engine3d_compile_us: 0,
ocean_compile_us: 0,
total_compile_us: 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 archive_enabled: bool = !archive.is_null();
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 ui_start: Instant = Instant::now();
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 ui_compile_us: u64 = ui_start.elapsed().as_micros() as u64;
let blur_start: Instant = Instant::now();
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_lib.is_null() {
mtl_send_void0(blur_lib, mtl_sel_cstr(MTL_SEL_RELEASE));
}
let blur_compile_us: u64 = blur_start.elapsed().as_micros() as u64;
let pbr_start: Instant = Instant::now();
let mut pbr_err: *mut c_void = null_mut();
let pbr_lib: *mut c_void = send_lib(
device,
mtl_sel_cstr(MTL_SEL_NEW_LIBRARY),
mtl_ns_string(MSL_ENGINE3D_PBR_SHADER),
null_mut(),
&mut pbr_err,
);
let (engine3d_pipeline, _): (usize, bool) =
metal_build_render_pipeline_3d(device, pbr_lib, archive);
if !pbr_lib.is_null() {
mtl_send_void0(pbr_lib, mtl_sel_cstr(MTL_SEL_RELEASE));
}
let engine3d_compile_us: u64 = pbr_start.elapsed().as_micros() as u64;
let ocean_start: Instant = Instant::now();
let mut ocean_err: *mut c_void = null_mut();
let ocean_lib: *mut c_void = send_lib(
device,
mtl_sel_cstr(MTL_SEL_NEW_LIBRARY),
mtl_ns_string(MSL_FLUID_OCEAN_SHADER),
null_mut(),
&mut ocean_err,
);
let (ocean_pipeline, _): (usize, bool) = metal_build_render_pipeline(
device,
ocean_lib,
MTL_FN_OCEAN_VERTEX,
MTL_FN_OCEAN_FRAGMENT,
archive,
false,
);
if !ocean_lib.is_null() {
mtl_send_void0(ocean_lib, mtl_sel_cstr(MTL_SEL_RELEASE));
}
let ocean_compile_us: u64 = ocean_start.elapsed().as_micros() as u64;
let mut scene_err: *mut c_void = null_mut();
let scene_lib: *mut c_void = send_lib(
device,
mtl_sel_cstr(MTL_SEL_NEW_LIBRARY),
mtl_ns_string(MSL_GPU_SCENE_SHADER),
null_mut(),
&mut scene_err,
);
let (scene_ocean_pipeline, _): (usize, bool) =
metal_build_render_pipeline_with_depth(
device,
scene_lib,
MTL_FN_SCENE_OCEAN_VERT,
MTL_FN_SCENE_OCEAN_FRAG,
archive,
false,
0,
);
let (scene_boat_pipeline, _): (usize, bool) =
metal_build_render_pipeline_with_depth(
device,
scene_lib,
MTL_FN_SCENE_BOAT_VERT,
MTL_FN_SCENE_BOAT_FRAG,
archive,
true,
0,
);
let (scene_3d_sky_pipeline, _): (usize, bool) =
metal_build_render_pipeline_with_depth(
device,
scene_lib,
MTL_FN_SCENE_3D_SKY_VERT,
MTL_FN_SCENE_3D_SKY_FRAG,
archive,
false,
MTL_PIXEL_FORMAT_DEPTH32_FLOAT,
);
let (scene_3d_mesh_pipeline, _): (usize, bool) =
metal_build_render_pipeline_with_depth(
device,
scene_lib,
MTL_FN_SCENE_3D_MESH_VERT,
MTL_FN_SCENE_3D_MESH_FRAG,
archive,
false,
MTL_PIXEL_FORMAT_DEPTH32_FLOAT,
);
if !scene_lib.is_null() {
mtl_send_void0(scene_lib, mtl_sel_cstr(MTL_SEL_RELEASE));
}
let scene_depth_stencil: usize = metal_create_depth_stencil_state(device);
if !archive.is_null() {
if !archive_existed
&& !archive_url.is_null()
&& pipeline != 0
&& metal_binary_archive_allowed(&device_name, cfg!(target_abi = "sim"))
&& mtl_responds_to_sel(archive, mtl_sel_cstr(MTL_SEL_SERIALIZE_TO_URL))
{
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;
let total_compile_us: u64 = total_start.elapsed().as_micros() as u64;
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,
blur_up_pipeline,
engine3d_pipeline,
ocean_pipeline,
scene_ocean_pipeline,
scene_boat_pipeline,
scene_3d_sky_pipeline,
scene_3d_mesh_pipeline,
scene_depth_stencil,
binary_archive_enabled: archive_enabled,
binary_archive_hit: archive_enabled && archive_existed,
ui_compile_us,
blur_compile_us,
engine3d_compile_us,
ocean_compile_us,
total_compile_us,
dummy_r8_tex,
dummy_rgba8_tex,
}
}
};
unsafe { objc_autoreleasePoolPop(pool) };
result
})
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn probe_apple_metal_full(backend: GraphicsBackend) -> NativeGpuProbeOutput {
let cached: &MetalSharedPipelineCache = init_apple_metal_shared_cache(backend);
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),
blur_up_pipeline_handle: mtl_retain_handle(cached.blur_up_pipeline),
engine3d_pipeline_handle: mtl_retain_handle(cached.engine3d_pipeline),
ocean_pipeline_handle: mtl_retain_handle(cached.ocean_pipeline),
scene_ocean_pipeline_handle: mtl_retain_handle(cached.scene_ocean_pipeline),
scene_boat_pipeline_handle: mtl_retain_handle(cached.scene_boat_pipeline),
scene_3d_sky_pipeline_handle: mtl_retain_handle(cached.scene_3d_sky_pipeline),
scene_3d_mesh_pipeline_handle: mtl_retain_handle(cached.scene_3d_mesh_pipeline),
scene_depth_stencil_handle: mtl_retain_handle(cached.scene_depth_stencil),
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"))]
pub(crate) 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_fragment_bytes: mtl_sel_cstr(MTL_SEL_SET_FRAGMENT_BYTES) as usize,
set_scissor_rect: mtl_sel_cstr(MTL_SEL_SET_SCISSOR_RECT) as usize,
set_viewport: mtl_sel_cstr(MTL_SEL_SET_VIEWPORT) 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,
depth_attachment: mtl_sel_cstr(MTL_SEL_DEPTH_ATTACHMENT) as usize,
set_clear_depth: mtl_sel_cstr(MTL_SEL_SET_CLEAR_DEPTH) as usize,
set_depth_stencil_state: mtl_sel_cstr(MTL_SEL_SET_DEPTH_STENCIL_STATE) 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(|blue_val: &GpuBatch| {
blue_val
.get_primitives()
.len()
.max(blue_val.get_instances().len())
})
.sum();
let device_handle: usize = driver.get_device_handle();
let queue_handle: usize = driver.get_queue_handle();
let layer_handle: usize = driver.get_surface_layer_handle();
if device_handle == 0 || queue_handle == 0 || layer_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 blur_down_pso: *mut c_void = driver.get_blur_pipeline_handle() as *mut c_void;
let blur_up_pso: *mut c_void = driver.get_blur_up_pipeline_handle() as *mut c_void;
let scene_pipelines: [*mut c_void; 5] = [
driver.get_scene_ocean_pipeline_handle() as *mut c_void,
driver.get_scene_boat_pipeline_handle() as *mut c_void,
driver.get_scene_3d_sky_pipeline_handle() as *mut c_void,
driver.get_scene_3d_mesh_pipeline_handle() as *mut c_void,
driver.get_scene_depth_stencil_handle() as *mut c_void,
];
let layer_ptr: *mut c_void = 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 mut tex_ext: *mut c_void = if raw_ext != 0 {
raw_ext as *mut c_void
} else {
tex_rgba8
};
let has_blur_batches: bool = !blur_down_pso.is_null()
&& !blur_up_pso.is_null()
&& batches.iter().any(|batch_item: &GpuBatch| {
batch_item
.get_primitives()
.iter()
.any(|prim_item: &GpuPrimitiveInstance| {
prim_item.prim_kind() == PrimKind::BackdropBlur
})
});
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,
blur_scene_texture_handle,
blur_half_texture_handle,
blur_full_texture_handle,
blur_texture_dims,
scene_color_texture_handle,
scene_depth_texture_handle,
scene_wake_texture_handle,
scene_texture_dims,
scene_3d_vertex_buffer_handle,
scene_3d_vertex_revision,
scene_3d_vertex_capacity,
scene_3d_instance_buffer_handle,
scene_3d_instance_capacity,
scene_boat_buffer_handle,
scene_boat_capacity,
pending_gpu_scene_pass,
..
} = driver;
let frame_scene_pass: Option<DirectGpuScenePass> = pending_gpu_scene_pass.take();
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);
if !drawable_tex.is_null() && !pass_cls.is_null() {
let tex_w: usize = mtl_send_usize0(drawable_tex, sel.width as *mut c_void);
let tex_h: usize = mtl_send_usize0(drawable_tex, sel.height as *mut c_void);
let draw_w: usize = if tex_w > 0 {
tex_w
} else {
width.max(1) as usize
};
let draw_h: usize = if tex_h > 0 {
tex_h
} else {
height.max(1) as usize
};
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,
};
let mut use_blur_offscreen: bool = false;
let mut scene_tex_ptr: *mut c_void = null_mut();
let mut half_tex_ptr: *mut c_void = null_mut();
let mut full_tex_ptr: *mut c_void = null_mut();
let half_w_u32: u32 = ((draw_w as u32) / 2).max(1);
let half_h_u32: u32 = ((draw_h as u32) / 2).max(1);
if has_blur_batches {
let target_dims: (u32, u32) = (draw_w as u32, draw_h as u32);
if *blur_scene_texture_handle == 0
|| *blur_half_texture_handle == 0
|| *blur_full_texture_handle == 0
|| *blur_texture_dims != target_dims
{
release_native_gpu_object(*blur_scene_texture_handle);
release_native_gpu_object(*blur_half_texture_handle);
release_native_gpu_object(*blur_full_texture_handle);
let unified_mem: bool = cfg!(target_arch = "aarch64");
*blur_scene_texture_handle = metal_create_offscreen_render_texture(
device_handle,
target_dims.0,
target_dims.1,
unified_mem,
);
*blur_half_texture_handle = metal_create_offscreen_render_texture(
device_handle,
half_w_u32,
half_h_u32,
unified_mem,
);
*blur_full_texture_handle = metal_create_offscreen_render_texture(
device_handle,
target_dims.0,
target_dims.1,
unified_mem,
);
*blur_texture_dims = target_dims;
}
scene_tex_ptr = *blur_scene_texture_handle as *mut c_void;
half_tex_ptr = *blur_half_texture_handle as *mut c_void;
full_tex_ptr = *blur_full_texture_handle as *mut c_void;
use_blur_offscreen = !scene_tex_ptr.is_null()
&& !half_tex_ptr.is_null()
&& !full_tex_ptr.is_null();
}
let primary_target: *mut c_void = if use_blur_offscreen {
scene_tex_ptr
} else {
drawable_tex
};
if let Some(scene_pass) = frame_scene_pass.as_ref() {
let mut scene_buf_handles: [usize; 6] = [
*scene_3d_vertex_buffer_handle,
*scene_3d_vertex_capacity,
*scene_3d_instance_buffer_handle,
*scene_3d_instance_capacity,
*scene_boat_buffer_handle,
*scene_boat_capacity,
];
let maybe_scene_tex: Option<*mut c_void> = metal_encode_gpu_scene_pass(
cmd_buf,
pass_cls,
device,
scene_pipelines,
(
scene_color_texture_handle,
scene_depth_texture_handle,
scene_wake_texture_handle,
scene_texture_dims,
),
(&mut scene_buf_handles, scene_3d_vertex_revision),
scene_pass,
);
*scene_3d_vertex_buffer_handle = scene_buf_handles[0];
*scene_3d_vertex_capacity = scene_buf_handles[1];
*scene_3d_instance_buffer_handle = scene_buf_handles[2];
*scene_3d_instance_capacity = scene_buf_handles[3];
*scene_boat_buffer_handle = scene_buf_handles[4];
*scene_boat_capacity = scene_buf_handles[5];
if let Some(rendered_scene_tex) = maybe_scene_tex {
tex_ext = rendered_scene_tex;
}
}
let mut active_encoder: *mut c_void = metal_begin_ui_render_encoder(
cmd_buf,
pass_cls,
primary_target,
(MTL_LOAD_ACTION_CLEAR, mtl_clear),
(draw_w, draw_h),
(pipeline, buf_handle as *mut c_void),
[tex_r8, tex_rgba8, tex_img, tex_ext],
);
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 is_blur_batch: bool = use_blur_offscreen
&& batch.get_primitives().iter().any(
|prim_item: &GpuPrimitiveInstance| {
prim_item.prim_kind() == PrimKind::BackdropBlur
},
);
if is_blur_batch {
if !active_encoder.is_null() {
mtl_send_void0(active_encoder, sel.end_encoding as *mut c_void);
}
let blur_offset: f32 = 2.5;
let down_uniform: [f32; 4] = [
1.0 / (draw_w.max(1) as f32),
1.0 / (draw_h.max(1) as f32),
blur_offset,
0.0,
];
let up_uniform: [f32; 4] = [
1.0 / (half_w_u32 as f32),
1.0 / (half_h_u32 as f32),
blur_offset,
1.0,
];
let _: bool = metal_encode_fullscreen_blur_pass(
cmd_buf,
pass_cls,
half_tex_ptr,
blur_down_pso,
scene_tex_ptr,
&down_uniform,
);
let _: bool = metal_encode_fullscreen_blur_pass(
cmd_buf,
pass_cls,
full_tex_ptr,
blur_up_pso,
half_tex_ptr,
&up_uniform,
);
active_encoder = metal_begin_ui_render_encoder(
cmd_buf,
pass_cls,
scene_tex_ptr,
(MTL_LOAD_ACTION_LOAD, mtl_clear),
(draw_w, draw_h),
(pipeline, buf_handle as *mut c_void),
[tex_r8, tex_rgba8, tex_img, full_tex_ptr],
);
}
if !active_encoder.is_null() {
metal_encode_ui_batch_draw(
active_encoder,
(draw_w, draw_h),
batch,
count,
base_instance,
);
if is_blur_batch && !tex_ext.is_null() {
unsafe {
let send_ftex: unsafe extern "C" fn(
*mut c_void,
*mut c_void,
*mut c_void,
usize,
) = transmute(objc_msgSend as *const c_void);
send_ftex(
active_encoder,
sel.set_fragment_texture as *mut c_void,
tex_ext,
3,
);
}
}
}
base_instance = base_instance.saturating_add(count);
}
if !active_encoder.is_null() {
mtl_send_void0(active_encoder, sel.end_encoding as *mut c_void);
}
if use_blur_offscreen {
let copy_prim: GpuPrimitiveInstance = GpuPrimitiveInstance {
rect: [0.0, 0.0, draw_w as f32, draw_h as f32],
clip_rect: [0.0, 0.0, draw_w as f32, draw_h as f32],
color_rgba: GpuPrimitiveInstance::pack_color_rgba8(COLOR_WHITE),
aux_color_rgba: 0,
uv_rect: [0, 0, u16::MAX, u16::MAX],
radii_border: [0; 4],
kind_flags: GpuPrimitiveInstance::pack_kind_flags(
PrimKind::ExternalGpuSurface,
0,
0,
0,
),
extra_param: 0,
};
let copy_enc: *mut c_void = metal_begin_ui_render_encoder(
cmd_buf,
pass_cls,
drawable_tex,
(MTL_LOAD_ACTION_CLEAR, mtl_clear),
(draw_w, draw_h),
(pipeline, null_mut()),
[tex_r8, tex_rgba8, tex_img, scene_tex_ptr],
);
if !copy_enc.is_null() {
let uniform: GpuLayerUniform =
GpuLayerUniform::new(draw_w as f32, draw_h as f32, [0.0, 0.0]);
unsafe {
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_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);
send_vbytes(
copy_enc,
sel.set_vertex_bytes as *mut c_void,
(©_prim as *const GpuPrimitiveInstance).cast::<c_void>(),
size_of::<GpuPrimitiveInstance>(),
0,
);
send_vbytes(
copy_enc,
sel.set_vertex_bytes as *mut c_void,
(&uniform as *const GpuLayerUniform).cast::<c_void>(),
size_of::<GpuLayerUniform>(),
1,
);
send_scissor(
copy_enc,
sel.set_scissor_rect as *mut c_void,
MtlScissorRect {
x: 0,
y: 0,
width: draw_w,
height: draw_h,
},
);
send_draw(
copy_enc,
sel.draw_primitives_instanced as *mut c_void,
MTL_PRIMITIVE_TYPE_TRIANGLE,
0,
6,
1,
0,
);
}
mtl_send_void0(copy_enc, 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);
let _: u64 = SUBMITTED_GPU_FENCE.fetch_add(1, Ordering::AcqRel);
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_execute_dual_kawase_blur_passes(
driver: &mut NativeGpuDriver,
width: u32,
height: u32,
blur_passes: &[GpuBackdropBlurPass],
) -> usize {
let device_handle: usize = driver.get_device_handle();
let queue_handle: usize = driver.get_queue_handle();
let blur_down_pso: usize = driver.get_blur_pipeline_handle();
let blur_up_pso: usize = driver.get_blur_up_pipeline_handle();
if device_handle == 0
|| queue_handle == 0
|| blur_down_pso == 0
|| blur_up_pso == 0
|| blur_passes.is_empty()
{
return 0;
}
let full_w: u32 = width.max(2);
let full_h: u32 = height.max(2);
let half_w: u32 = (full_w / 2).max(1);
let half_h: u32 = (full_h / 2).max(1);
let src_tex_handle: usize = if driver.get_external_texture_handle() != 0 {
driver.get_external_texture_handle()
} else if driver.get_image_texture_handle() != 0 {
driver.get_image_texture_handle()
} else {
driver.get_glyph_rgba8_texture_handle()
};
if src_tex_handle == 0 {
return 0;
}
let NativeGpuDriver {
blur_half_texture_handle,
blur_full_texture_handle,
blur_texture_dims,
..
} = driver;
if *blur_half_texture_handle == 0
|| *blur_full_texture_handle == 0
|| *blur_texture_dims != (full_w, full_h)
{
release_native_gpu_object(*blur_half_texture_handle);
release_native_gpu_object(*blur_full_texture_handle);
let unified_mem: bool = cfg!(target_arch = "aarch64");
*blur_half_texture_handle =
metal_create_offscreen_render_texture(device_handle, half_w, half_h, unified_mem);
*blur_full_texture_handle =
metal_create_offscreen_render_texture(device_handle, full_w, full_h, unified_mem);
*blur_texture_dims = (full_w, full_h);
}
let half_tex: *mut c_void = *blur_half_texture_handle as *mut c_void;
let full_tex: *mut c_void = *blur_full_texture_handle as *mut c_void;
if half_tex.is_null() || full_tex.is_null() {
return 0;
}
let pool: *mut c_void = unsafe { objc_autoreleasePoolPush() };
let sel: &MetalSelectors = cached_metal_selectors();
let queue: *mut c_void = queue_handle as *mut c_void;
let cmd_buf: *mut c_void = mtl_send_ptr0(queue, sel.command_buffer as *mut c_void);
if cmd_buf.is_null() {
unsafe { objc_autoreleasePoolPop(pool) };
return 0;
}
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());
}
let pass_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_PASS_DESC);
let mut executed: usize = 0;
let max_regions: usize = blur_passes.len().min(RENDER_GRAPH_MAX_BLUR_PASSES);
for pass in blur_passes.iter().take(max_regions) {
let blur_offset: f32 = (pass.get_blur_radius() * 0.25).clamp(0.5, 8.0);
let down_uniform: [f32; 4] = [
1.0 / (full_w as f32),
1.0 / (full_h as f32),
blur_offset,
0.0,
];
let up_uniform: [f32; 4] = [
1.0 / (half_w as f32),
1.0 / (half_h as f32),
blur_offset,
1.0,
];
let down_ok: bool = metal_encode_fullscreen_blur_pass(
cmd_buf,
pass_cls,
half_tex,
blur_down_pso as *mut c_void,
src_tex_handle as *mut c_void,
&down_uniform,
);
let up_ok: bool = if down_ok {
metal_encode_fullscreen_blur_pass(
cmd_buf,
pass_cls,
full_tex,
blur_up_pso as *mut c_void,
half_tex,
&up_uniform,
)
} else {
false
};
if down_ok && up_ok {
executed = executed.saturating_add(1);
}
}
let _: u64 = SUBMITTED_GPU_FENCE.fetch_add(1, Ordering::AcqRel);
mtl_send_void0(cmd_buf, sel.commit as *mut c_void);
mtl_send_void0(cmd_buf, sel.wait_until_completed as *mut c_void);
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);
LAST_GPU_RENDER_NS.store(exec_ns, Ordering::Relaxed);
}
unsafe { objc_autoreleasePoolPop(pool) };
executed
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn metal_encode_fullscreen_blur_pass(
cmd_buf: *mut c_void,
pass_cls: *mut c_void,
dst_tex: *mut c_void,
pso: *mut c_void,
src_tex: *mut c_void,
uniform: &[f32; 4],
) -> bool {
let sel: &MetalSelectors = cached_metal_selectors();
let pass_desc: *mut c_void = mtl_send_ptr0(pass_cls, sel.render_pass_desc as *mut c_void);
if pass_desc.is_null() {
return false;
}
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() {
return false;
}
mtl_send_void_ptr1(att0, sel.set_texture as *mut c_void, dst_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 encoder: *mut c_void = mtl_send_ptr1(cmd_buf, sel.render_encoder as *mut c_void, pass_desc);
if encoder.is_null() {
return false;
}
mtl_send_void_ptr1(encoder, sel.set_pipeline_state as *mut c_void, pso);
unsafe {
let send_fbytes: 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_draw: unsafe extern "C" fn(
*mut c_void,
*mut c_void,
usize,
usize,
usize,
usize,
usize,
) = transmute(objc_msgSend as *const c_void);
send_fbytes(
encoder,
sel.set_fragment_bytes as *mut c_void,
uniform.as_ptr().cast::<c_void>(),
size_of::<[f32; 4]>(),
0,
);
send_ftex(encoder, sel.set_fragment_texture as *mut c_void, src_tex, 0);
send_draw(
encoder,
sel.draw_primitives_instanced as *mut c_void,
MTL_PRIMITIVE_TYPE_TRIANGLE,
0,
3,
1,
0,
);
}
mtl_send_void0(encoder, sel.end_encoding as *mut c_void);
true
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn metal_encode_gpu_scene_pass(
cmd_buf: *mut c_void,
pass_cls: *mut c_void,
device: *mut c_void,
pipelines: [*mut c_void; 5],
textures: (&mut usize, &mut usize, &mut usize, &mut (u32, u32)),
buffers: (&mut [usize; 6], &mut u64),
scene_pass: &DirectGpuScenePass,
) -> Option<*mut c_void> {
let (color_tex_h, depth_tex_h, wake_tex_h, tex_dims): (
&mut usize,
&mut usize,
&mut usize,
&mut (u32, u32),
) = textures;
let (buf_arr, v3d_rev): (&mut [usize; 6], &mut u64) = buffers;
let [v3d_buf_h, v3d_cap, i3d_buf_h, i3d_cap, boat_buf_h, boat_cap]: &mut [usize; 6] = buf_arr;
let sel: &MetalSelectors = cached_metal_selectors();
let (req_w, req_h, needs_depth): (u32, u32, bool) = match scene_pass {
DirectGpuScenePass::OceanFluid(ocean) => (
ocean.get_target_width().clamp(64, 16384),
ocean.get_target_height().clamp(64, 16384),
false,
),
DirectGpuScenePass::World3d(world) => (
world.get_target_width().clamp(64, 16384),
world.get_target_height().clamp(64, 16384),
true,
),
};
if *color_tex_h == 0 || *tex_dims != (req_w, req_h) || (needs_depth && *depth_tex_h == 0) {
release_native_gpu_object(*color_tex_h);
release_native_gpu_object(*depth_tex_h);
let unified_mem: bool = cfg!(target_arch = "aarch64");
*color_tex_h =
metal_create_offscreen_render_texture(device as usize, req_w, req_h, unified_mem);
*depth_tex_h = if needs_depth {
metal_create_depth_texture(device, req_w, req_h)
} else {
0
};
*tex_dims = (req_w, req_h);
}
let color_tex: *mut c_void = *color_tex_h as *mut c_void;
if color_tex.is_null() {
return None;
}
let pass_desc: *mut c_void = mtl_send_ptr0(pass_cls, sel.render_pass_desc as *mut c_void);
if pass_desc.is_null() {
return None;
}
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() {
return None;
}
mtl_send_void_ptr1(att0, sel.set_texture as *mut c_void, color_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,
);
if needs_depth {
let depth_tex: *mut c_void = *depth_tex_h as *mut c_void;
if depth_tex.is_null() {
return None;
}
let depth_att: *mut c_void = mtl_send_ptr0(pass_desc, sel.depth_attachment as *mut c_void);
if depth_att.is_null() {
return None;
}
mtl_send_void_ptr1(depth_att, sel.set_texture as *mut c_void, depth_tex);
mtl_send_void_usize(
depth_att,
sel.set_load_action as *mut c_void,
MTL_LOAD_ACTION_CLEAR,
);
mtl_send_void_usize(
depth_att,
sel.set_store_action as *mut c_void,
MTL_STORE_ACTION_DONT_CARE,
);
unsafe {
let send_clear_d: unsafe extern "C" fn(*mut c_void, *mut c_void, f64) =
transmute(objc_msgSend as *const c_void);
send_clear_d(depth_att, sel.set_clear_depth as *mut c_void, 1.0);
}
}
let encoder: *mut c_void = mtl_send_ptr1(cmd_buf, sel.render_encoder as *mut c_void, pass_desc);
if encoder.is_null() {
return None;
}
let viewport: MtlViewport = MtlViewport {
origin_x: 0.0,
origin_y: 0.0,
width: f64::from(req_w),
height: f64::from(req_h),
znear: 0.0,
zfar: 1.0,
};
unsafe {
let send_vp: unsafe extern "C" fn(*mut c_void, *mut c_void, MtlViewport) =
transmute(objc_msgSend as *const c_void);
send_vp(encoder, sel.set_viewport as *mut c_void, viewport);
}
match scene_pass {
DirectGpuScenePass::OceanFluid(ocean) => {
let ocean_pso: *mut c_void = pipelines[0];
let boat_pso: *mut c_void = pipelines[1];
if !ocean_pso.is_null() {
let wake_w: u32 = ocean.get_wake_width().max(1);
let wake_h: u32 = ocean.get_wake_height().max(1);
if (*wake_tex_h == 0 || ocean.get_has_active_wake())
&& ocean.get_wake_rgba8().len() >= (wake_w as usize) * (wake_h as usize) * 4
{
let _: bool = metal_upload_texture_dirty_rect(
device as usize,
wake_tex_h,
GpuAtlasPixelFormat::Rgba8Unorm,
(wake_w, wake_h),
(0, 0, wake_w, wake_h),
ocean.get_wake_rgba8().as_slice(),
(wake_w as usize) * 4,
);
}
let sun: [f32; 3] = ocean.get_sun_dir();
let boat_uv: [f32; 2] = ocean.get_boat_uv();
let wf: f32 = req_w as f32;
let hf: f32 = req_h as f32;
let ocean_uniform: [f32; 16] = [
ocean.get_sim_time(),
ocean.get_agitation(),
ocean.get_horizon_v(),
ocean.get_aspect(),
ocean.get_roll_cos(),
ocean.get_roll_sin(),
boat_uv[0],
boat_uv[1],
sun[0],
sun[1],
sun[2],
if ocean.get_has_active_wake() && *wake_tex_h != 0 {
1.0
} else {
0.0
},
wf,
hf,
1.0 / wf.max(1.0),
1.0 / hf.max(1.0),
];
mtl_send_void_ptr1(encoder, sel.set_pipeline_state as *mut c_void, ocean_pso);
unsafe {
let send_fbytes: 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_draw: unsafe extern "C" fn(
*mut c_void,
*mut c_void,
usize,
usize,
usize,
usize,
usize,
) = transmute(objc_msgSend as *const c_void);
send_fbytes(
encoder,
sel.set_fragment_bytes as *mut c_void,
ocean_uniform.as_ptr().cast::<c_void>(),
size_of::<[f32; 16]>(),
0,
);
if *wake_tex_h != 0 {
send_ftex(
encoder,
sel.set_fragment_texture as *mut c_void,
*wake_tex_h as *mut c_void,
0,
);
}
send_draw(
encoder,
sel.draw_primitives_instanced as *mut c_void,
MTL_PRIMITIVE_TYPE_TRIANGLE,
0,
3,
1,
0,
);
}
}
let boat_verts: &[GpuOceanBoatVertex] = ocean.get_boat_vertices().as_slice();
if !boat_pso.is_null() && !boat_verts.is_empty() {
let boat_bytes: &[u8] = unsafe {
from_raw_parts(boat_verts.as_ptr().cast::<u8>(), size_of_val(boat_verts))
};
let boat_buf: *mut c_void =
metal_ensure_and_upload_shared_buffer(device, boat_buf_h, boat_cap, boat_bytes);
if !boat_buf.is_null() {
mtl_send_void_ptr1(encoder, sel.set_pipeline_state as *mut c_void, boat_pso);
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_draw: unsafe extern "C" fn(
*mut c_void,
*mut c_void,
usize,
usize,
usize,
usize,
usize,
) = transmute(objc_msgSend as *const c_void);
send_vbuf(
encoder,
sel.set_vertex_buffer as *mut c_void,
boat_buf,
0,
0,
);
send_draw(
encoder,
sel.draw_primitives_instanced as *mut c_void,
MTL_PRIMITIVE_TYPE_TRIANGLE,
0,
boat_verts.len(),
1,
0,
);
}
}
}
}
DirectGpuScenePass::World3d(world) => {
let sky_pso: *mut c_void = pipelines[2];
let mesh_pso: *mut c_void = pipelines[3];
let depth_state: *mut c_void = pipelines[4];
let mut uniform: [f32; 36] = [0.0; 36];
uniform[0..16].copy_from_slice(&world.get_view_proj());
uniform[16..20].copy_from_slice(&world.get_camera_pos());
uniform[20..24].copy_from_slice(&world.get_sun_dir_fog());
uniform[24..28].copy_from_slice(&world.get_sun_color_ambient());
uniform[28..32].copy_from_slice(&world.get_sky_horizon_tod());
uniform[32..36].copy_from_slice(&world.get_sky_zenith_aspect());
if !sky_pso.is_null() {
mtl_send_void_ptr1(encoder, sel.set_pipeline_state as *mut c_void, sky_pso);
unsafe {
let send_fbytes: unsafe extern "C" fn(
*mut c_void,
*mut c_void,
*const c_void,
usize,
usize,
) = 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);
send_fbytes(
encoder,
sel.set_fragment_bytes as *mut c_void,
uniform.as_ptr().cast::<c_void>(),
size_of::<[f32; 36]>(),
0,
);
send_draw(
encoder,
sel.draw_primitives_instanced as *mut c_void,
MTL_PRIMITIVE_TYPE_TRIANGLE,
0,
3,
1,
0,
);
}
}
let mesh_verts: &[GpuWorld3dVertex] = world.get_mesh_buffer().get_vertices().as_slice();
let mesh_insts: &[GpuWorld3dInstance] = world.get_instances().as_slice();
if !mesh_pso.is_null() && !mesh_verts.is_empty() && !mesh_insts.is_empty() {
let mesh_rev: u64 = world.get_mesh_buffer().get_revision();
let vbuf: *mut c_void = if *v3d_buf_h == 0 || *v3d_rev != mesh_rev {
let vert_bytes: &[u8] = unsafe {
from_raw_parts(mesh_verts.as_ptr().cast::<u8>(), size_of_val(mesh_verts))
};
let uploaded: *mut c_void = metal_ensure_and_upload_shared_buffer(
device, v3d_buf_h, v3d_cap, vert_bytes,
);
if !uploaded.is_null() {
*v3d_rev = mesh_rev;
}
uploaded
} else {
*v3d_buf_h as *mut c_void
};
let inst_bytes: &[u8] = unsafe {
from_raw_parts(mesh_insts.as_ptr().cast::<u8>(), size_of_val(mesh_insts))
};
let ibuf: *mut c_void =
metal_ensure_and_upload_shared_buffer(device, i3d_buf_h, i3d_cap, inst_bytes);
if !vbuf.is_null() && !ibuf.is_null() {
mtl_send_void_ptr1(encoder, sel.set_pipeline_state as *mut c_void, mesh_pso);
if !depth_state.is_null() {
mtl_send_void_ptr1(
encoder,
sel.set_depth_stencil_state as *mut c_void,
depth_state,
);
}
unsafe {
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_fbytes: unsafe extern "C" fn(
*mut c_void,
*mut c_void,
*const c_void,
usize,
usize,
) = transmute(objc_msgSend as *const c_void);
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_draw: unsafe extern "C" fn(
*mut c_void,
*mut c_void,
usize,
usize,
usize,
usize,
usize,
) = transmute(objc_msgSend as *const c_void);
send_vbytes(
encoder,
sel.set_vertex_bytes as *mut c_void,
uniform.as_ptr().cast::<c_void>(),
size_of::<[f32; 36]>(),
0,
);
send_fbytes(
encoder,
sel.set_fragment_bytes as *mut c_void,
uniform.as_ptr().cast::<c_void>(),
size_of::<[f32; 36]>(),
0,
);
send_vbuf(encoder, sel.set_vertex_buffer as *mut c_void, vbuf, 0, 1);
send_vbuf(encoder, sel.set_vertex_buffer as *mut c_void, ibuf, 0, 2);
for batch in world.get_draw_batches().iter() {
if batch.get_vertex_count() == 0 || batch.get_instance_count() == 0 {
continue;
}
send_draw(
encoder,
sel.draw_primitives_instanced as *mut c_void,
MTL_PRIMITIVE_TYPE_TRIANGLE,
batch.get_vertex_start() as usize,
batch.get_vertex_count() as usize,
batch.get_instance_count() as usize,
batch.get_instance_start() as usize,
);
}
}
}
}
}
}
mtl_send_void0(encoder, sel.end_encoding as *mut c_void);
Some(color_tex)
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn metal_begin_ui_render_encoder(
cmd_buf: *mut c_void,
pass_cls: *mut c_void,
target_tex: *mut c_void,
load_spec: (usize, MtlClearColor),
draw_dims: (usize, usize),
pipe_buf: (*mut c_void, *mut c_void),
textures: [*mut c_void; 4],
) -> *mut c_void {
let sel: &MetalSelectors = cached_metal_selectors();
let pass_desc: *mut c_void = mtl_send_ptr0(pass_cls, sel.render_pass_desc as *mut c_void);
if pass_desc.is_null() {
return null_mut();
}
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() {
return null_mut();
}
mtl_send_void_ptr1(att0, sel.set_texture as *mut c_void, target_tex);
mtl_send_void_usize(att0, sel.set_load_action as *mut c_void, load_spec.0);
mtl_send_void_usize(
att0,
sel.set_store_action as *mut c_void,
MTL_STORE_ACTION_STORE,
);
if load_spec.0 == MTL_LOAD_ACTION_CLEAR {
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, load_spec.1);
}
}
let encoder: *mut c_void = mtl_send_ptr1(cmd_buf, sel.render_encoder as *mut c_void, pass_desc);
if encoder.is_null() {
return null_mut();
}
mtl_send_void_ptr1(encoder, sel.set_pipeline_state as *mut c_void, pipe_buf.0);
unsafe {
let send_viewport: unsafe extern "C" fn(*mut c_void, *mut c_void, MtlViewport) =
transmute(objc_msgSend as *const c_void);
send_viewport(
encoder,
sel.set_viewport as *mut c_void,
MtlViewport {
origin_x: 0.0,
origin_y: 0.0,
width: draw_dims.0 as f64,
height: draw_dims.1 as f64,
znear: 0.0,
zfar: 1.0,
},
);
if !pipe_buf.1.is_null() {
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);
send_vbuf(
encoder,
sel.set_vertex_buffer as *mut c_void,
pipe_buf.1,
0,
0,
);
}
let send_ftex: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void, usize) =
transmute(objc_msgSend as *const c_void);
for (slot_idx, tex_ptr) in textures.iter().enumerate() {
if !tex_ptr.is_null() {
send_ftex(
encoder,
sel.set_fragment_texture as *mut c_void,
*tex_ptr,
slot_idx,
);
}
}
}
encoder
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn metal_encode_ui_batch_draw(
encoder: *mut c_void,
draw_dims: (usize, usize),
batch: &GpuBatch,
count: usize,
base_instance: usize,
) {
let sel: &MetalSelectors = cached_metal_selectors();
let (draw_w, draw_h): (usize, usize) = draw_dims;
let uniform: GpuLayerUniform =
GpuLayerUniform::new(draw_w as f32, draw_h as f32, batch.get_scroll_offset());
let rect_bounds: Rect = batch.get_scissor();
let sx: usize = (rect_bounds.get_x().max(0.0).floor() as usize).min(draw_w.saturating_sub(1));
let sy: usize = (rect_bounds.get_y().max(0.0).floor() as usize).min(draw_h.saturating_sub(1));
let sw: usize = (rect_bounds.get_width().max(1.0).ceil() as usize)
.min(draw_w.saturating_sub(sx))
.max(1);
let sh: usize = (rect_bounds.get_height().max(1.0).ceil() as usize)
.min(draw_h.saturating_sub(sy))
.max(1);
unsafe {
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_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);
send_vbytes(
encoder,
sel.set_vertex_bytes as *mut c_void,
(&uniform as *const GpuLayerUniform).cast::<c_void>(),
size_of::<GpuLayerUniform>(),
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,
);
}
}
#[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(|blue_val: &GpuBatch| {
blue_val
.get_primitives()
.len()
.max(blue_val.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 has_runtime: bool = cached.has_d3d12 && cached.has_compiler;
let label: &str = if cached.has_d3d12 {
GPU_DEVICE_D3D12
} else {
GPU_DEVICE_FALLBACK
};
(
GpuAdapterInfo::new(backend, label.to_string(), has_runtime, false),
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, false),
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,
stroke_width: 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, stroke_width 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 red_val in coalesced.iter() {
merged_bbox = merged_bbox.union_with(*red_val);
multi_bytes = multi_bytes.saturating_add(red_val.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(red_val) = damage.resolve(fb_w, fb_h) else {
return Vec::new();
};
let rx0: u32 = (red_val.get_x().floor().max(0.0) as u32).min(fb_w);
let ry0: u32 = (red_val.get_y().floor().max(0.0) as u32).min(fb_h);
let rx1: u32 = (red_val.right().ceil().max(0.0) as u32).clamp(rx0, fb_w);
let ry1: u32 = (red_val.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(|blue_val: &GpuBatch| {
blue_val
.get_primitives()
.len()
.max(blue_val.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 rect_bounds: Rect = batch.get_scissor();
let sx: u32 = (rect_bounds.get_x().max(0.0).floor() as u32).min(vw.saturating_sub(1));
let sy: u32 = (rect_bounds.get_y().max(0.0).floor() as u32).min(vh.saturating_sub(1));
let stroke_width: u32 = (rect_bounds.get_width().max(1.0).ceil() as u32)
.min(vw.saturating_sub(sx))
.max(1);
let sh: u32 = (rect_bounds.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: stroke_width,
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,
) {
if clip.get_width() <= 0.0 || clip.get_height() <= 0.0 {
return;
}
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 stroke_width: 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() == stroke_width
&& 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: stroke_width,
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,
pos_x: u32,
pos_y: u32,
width_val: u32,
height_val: 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 = (((pos_x as f32) * inv_w).clamp(0.0, 1.0) * 65535.0).round() as u16;
let v0: u16 = (((pos_y as f32) * inv_h).clamp(0.0, 1.0) * 65535.0).round() as u16;
let u1: u16 = ((((pos_x + width_val) as f32) * inv_w).clamp(0.0, 1.0) * 65535.0).round() as u16;
let v1: u16 =
((((pos_y + height_val) 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(16384);
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, Rect, u16)> = Vec::with_capacity(16);
clip_stack.push((full_clip, full_clip, 0));
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, safe_inner_clip, active_rounded_bits): (Rect, Rect, u16) = clip_stack
.last()
.copied()
.unwrap_or((full_clip, full_clip, 0));
let clip_arr: [f32; 4] = [
active_clip.get_x(),
active_clip.get_y(),
active_clip.right(),
active_clip.bottom(),
];
let cmd_prim_start: usize = primitives.len();
match cmd {
DrawCommand::Clear(char_item) => {
clear_rgba = char_item.to_f32_array();
}
DrawCommand::PushClip(rect) => {
let phys: Rect = snap_physical_rect(*rect, scale);
let next_scissor: Rect = active_clip.intersect(phys).unwrap_or_default();
let next_safe: Rect = safe_inner_clip.intersect(phys).unwrap_or_default();
let next_bits: u16 = GpuPrimitiveInstance::encode_rounded_clip_bits(
active_clip,
active_rounded_bits,
next_scissor,
phys,
None,
);
clip_stack.push((next_scissor, next_safe, next_bits));
}
DrawCommand::PushRoundedClip { rect, radius } => {
let phys: Rect = snap_physical_rect(*rect, scale);
let next_scissor: Rect = active_clip.intersect(phys).unwrap_or_default();
let phys_radius: CornerRadius = CornerRadius::new(
radius.get_top_left() * scale,
radius.get_top_right() * scale,
radius.get_bottom_right() * scale,
radius.get_bottom_left() * scale,
);
let max_r: f32 = phys_radius.max_radius().ceil();
let inset_w: f32 = (phys.get_width() - max_r * 2.0).max(0.0);
let inset_h: f32 = (phys.get_height() - max_r * 2.0).max(0.0);
let rounded_safe: Rect =
Rect::new(phys.get_x() + max_r, phys.get_y() + max_r, inset_w, inset_h);
let next_safe: Rect = safe_inner_clip.intersect(rounded_safe).unwrap_or_default();
let next_bits: u16 = GpuPrimitiveInstance::encode_rounded_clip_bits(
active_clip,
active_rounded_bits,
next_scissor,
phys,
Some(phys_radius),
);
clip_stack.push((next_scissor, next_safe, next_bits));
}
DrawCommand::PopClip => {
if clip_stack.len() > 1 {
let _: Option<(Rect, Rect, u16)> = 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 border_width: f32 = if border.get_width() > 0.0 {
(border.get_width() * scale).max(1.0)
} else {
0.0
};
let query_val: 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: border_width,
angle_rad: 0.0,
kind: GpuPrimitiveKind::RoundedRect as u32,
reserved: 0,
};
push_direct_gpu_primitive(
&mut primitives,
&mut draw_ranges,
GpuPrimitiveInstance::from_quad_instance(&query_val, 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 quat_val: 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(&quat_val, 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 corner_vec: 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(&corner_vec, 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 green_val: &RasterizedGlyph = match font_provider {
Some(fp) => atlas.get_or_rasterize_with(key, fp),
None => atlas.get_or_rasterize(key),
};
(
green_val.get_width(),
green_val.get_height(),
(green_val.get_advance() as f32).max(1.0) + letter_sp,
)
};
line_glyphs.push((Some(key), gw, gh, adv));
line_w_px += adv;
}
let fit_scale: f32 = if rect_w_px > 1.0 && line_w_px > rect_w_px + 1.0 {
(rect_w_px / line_w_px).clamp(0.72, 1.0)
} else {
1.0
};
let fitted_line_w: f32 = line_w_px * fit_scale;
let align_offset: f32 = match style.get_align() {
TextAlign::Center => ((rect_w_px - fitted_line_w) * 0.5).max(0.0),
TextAlign::Right => (rect_w_px - fitted_line_w).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 * fit_scale;
}
}
} else {
let queue_entry: 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(&queue_entry, 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_phys: f32 = if let Some(atlas) = glyph_atlas.as_deref_mut() {
let phys_font_px: f32 = (style.get_font_size() * scale).max(6.0);
let letter_sp: f32 = style.get_letter_spacing() * scale;
if let Some(line) = meas.get_lines().last() {
let mut acc: f32 = 0.0;
for ch in line.get_text().chars() {
if ch == ' ' || ch == '\t' {
acc += measure_char_advance(ch, *style) * scale + letter_sp;
} else {
let key: GlyphKey =
GlyphKey::from_text_style(ch, phys_font_px, *style);
let geometry_val: &RasterizedGlyph = match font_provider {
Some(fp) => atlas.get_or_rasterize_with(key, fp),
None => atlas.get_or_rasterize(key),
};
acc += (geometry_val.get_advance() as f32).max(1.0) + letter_sp;
}
}
acc
} else {
0.0
}
} else {
meas.get_lines()
.last()
.map(TextLine::get_width)
.unwrap_or(0.0)
* scale
};
let line_idx: usize = meas.get_lines().len().saturating_sub(1);
let trailing_gap_phys: f32 = if last_w_phys > 0.0 { 1.0 * scale } else { 0.0 };
let caret_x_phys: f32 =
(text_rect.get_x() * scale + last_w_phys + trailing_gap_phys).clamp(
content_rect.get_x() * scale,
((content_rect.right() - 2.0) * scale).max(content_rect.get_x() * scale),
);
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 query_val_primary: GpuQuadInstance = GpuQuadInstance {
rect: [
caret_x_phys.round(),
(caret_y * scale).round(),
(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(
&query_val_primary,
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 query_val_secondary: 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(
&query_val_secondary,
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 query_val_next: 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(&query_val_next, 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 stroke_width: 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 stroke_width == 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, stroke_width, sh),
});
let query_val_alt: 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(&query_val_alt, 0, active_layer_id),
active_clip,
phys_w,
phys_h,
);
image_fixups.push((prim_idx, img_idx));
}
DrawCommand::ExternalSurface { rect, radius } => {
let snapped: Rect = snap_physical_rect(*rect, scale);
if snapped.get_width() <= 0.0 || snapped.get_height() <= 0.0 {
continue;
}
let ext_quad: 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::ExternalSurface as u32,
reserved: 0,
};
push_direct_gpu_primitive(
&mut primitives,
&mut draw_ranges,
GpuPrimitiveInstance::from_quad_instance(&ext_quad, 3, active_layer_id),
active_clip,
phys_w,
phys_h,
);
}
DrawCommand::Circle {
center,
radius,
color,
} => {
let red_val: f32 = radius * scale;
let pad: f32 = 1.5;
let extent: f32 = red_val + pad;
let query_val_inner: 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: [red_val; 4],
stroke_or_blur: red_val,
angle_rad: 0.0,
kind: GpuPrimitiveKind::Circle as u32,
reserved: 0,
};
push_direct_gpu_primitive(
&mut primitives,
&mut draw_ranges,
GpuPrimitiveInstance::from_quad_instance(&query_val_inner, 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 query_val_local: 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(&query_val_local, 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 query_val_cur: 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(&query_val_cur, 0, active_layer_id),
active_clip,
phys_w,
phys_h,
);
}
}
if active_rounded_bits != 0 && primitives.len() > cmd_prim_start {
for prim_item in primitives[cmd_prim_start..].iter_mut() {
let quad_rect: [f32; 4] = prim_item.get_rect();
let safe_non_empty: bool =
safe_inner_clip.get_width() > 0.0 && safe_inner_clip.get_height() > 0.0;
let inside_safe: bool = safe_non_empty
&& quad_rect[0] >= safe_inner_clip.get_x()
&& quad_rect[1] >= safe_inner_clip.get_y()
&& (quad_rect[0] + quad_rect[2]) <= safe_inner_clip.right()
&& (quad_rect[1] + quad_rect[3]) <= safe_inner_clip.bottom();
if !inside_safe {
*prim_item = prim_item.with_rounded_clip_bits(active_rounded_bits);
}
}
}
}
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(|alpha_val: &DirectGpuAtlasUpload| alpha_val.get_pixels().len())
.unwrap_or(0);
let image_bytes: usize = image_rgba8_atlas
.as_ref()
.map(|first_val: &DirectGpuAtlasUpload| first_val.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,
}
}
#[must_use]
pub const fn default_native_gpu_backend() -> GraphicsBackend {
#[cfg(any(target_os = "macos", target_os = "ios"))]
{
GraphicsBackend::Metal
}
#[cfg(target_os = "windows")]
{
GraphicsBackend::Direct3D12
}
#[cfg(any(target_os = "linux", target_os = "android"))]
{
GraphicsBackend::Vulkan
}
#[cfg(target_arch = "wasm32")]
{
GraphicsBackend::WebGl2
}
#[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "windows")))]
#[cfg(not(any(target_os = "linux", target_os = "android", target_arch = "wasm32")))]
{
GraphicsBackend::Headless
}
}
#[must_use]
pub fn shader_program_cache_hash(device_name: &str, primary_src: &str, secondary_src: &str) -> u64 {
let mut hash: u64 = FNV1A_OFFSET_BASIS;
for chunk in [
device_name.as_bytes(),
primary_src.as_bytes(),
secondary_src.as_bytes(),
]
.iter()
{
for &byte in chunk.iter() {
hash ^= byte as u64;
hash = hash.wrapping_mul(FNV1A_PRIME);
}
}
hash
}
fn run_shader_precompile_uncached(backend: GraphicsBackend) -> ShaderPrecompileReport {
#[cfg(not(target_arch = "wasm32"))]
let total_start: Instant = Instant::now();
let _: Vec<u8> = build_aces_srgb_lut();
let lang_label: &str = ShaderProgramId::language_for_backend(backend);
#[cfg(any(target_os = "macos", target_os = "ios"))]
if backend == GraphicsBackend::Metal {
let cached: &MetalSharedPipelineCache = init_apple_metal_shared_cache(backend);
let device_name: String = cached.adapter.get_device_name().clone();
let hardware_gpu: bool = cached.adapter.get_hardware_verified();
let archive_enabled: bool = cached.binary_archive_enabled;
let archive_hit: bool = cached.binary_archive_hit;
let handles_and_us: [(ShaderProgramId, usize, u64); 4] = [
(
ShaderProgramId::UiUber,
cached.pipeline,
cached.ui_compile_us,
),
(
ShaderProgramId::BackdropBlur,
if cached.blur_pipeline != 0 && cached.blur_up_pipeline != 0 {
cached.blur_pipeline
} else {
0
},
cached.blur_compile_us,
),
(
ShaderProgramId::Engine3dPbr,
cached.engine3d_pipeline,
cached.engine3d_compile_us,
),
(
ShaderProgramId::FluidOceanOptical,
cached.ocean_pipeline,
cached.ocean_compile_us,
),
];
let mut entries: Vec<ShaderProgramCacheEntry> = Vec::with_capacity(handles_and_us.len());
let mut ready_count: usize = 0;
let mut hw_compiled: usize = 0;
for (program, pso_handle, compile_us) in handles_and_us {
let (src_a, src_b): (&str, &str) = program.source_pair(backend);
let src_bytes: usize = src_a.len().saturating_add(src_b.len());
let src_hash: u64 = shader_program_cache_hash(&device_name, src_a, src_b);
let state: ShaderCompileState = if pso_handle != 0 {
hw_compiled += 1;
ready_count += 1;
if archive_hit {
ShaderCompileState::LoadedFromBinaryArchive
} else {
ShaderCompileState::CompiledHardware
}
} else if !src_a.is_empty() {
ready_count += 1;
ShaderCompileState::ValidatedFallback
} else {
ShaderCompileState::Failed
};
entries.push(ShaderProgramCacheEntry {
program,
name: program.label().to_string(),
language: lang_label.to_string(),
state,
source_hash: src_hash,
source_bytes: src_bytes,
compile_time_us: compile_us,
pipeline_ready: state.is_ready(),
});
}
let elapsed_us: u64 = total_start.elapsed().as_micros() as u64;
let cold_us: u64 = cached.total_compile_us.max(elapsed_us);
return ShaderPrecompileReport {
backend,
device_name,
hardware_gpu,
binary_archive_enabled: archive_enabled,
binary_archive_hit: archive_hit,
cache_hit: false,
total_programs: entries.len(),
ready_programs: ready_count,
hardware_compiled_programs: hw_compiled,
cold_compile_us: cold_us,
last_call_us: elapsed_us,
entries,
};
}
let probed: NativeGpuProbeOutput = probe_native_gpu_full(backend);
let device_name: String = probed.adapter.get_device_name().clone();
let hardware_gpu: bool = probed.adapter.get_hardware_verified();
let hw_shader_ok: bool = probed.adapter.get_shader_compiled();
let has_compiled_pso: bool = probed.device_handle != 0 && probed.pipeline_handle != 0;
release_native_gpu_object(probed.dummy_r8_tex);
release_native_gpu_object(probed.dummy_rgba8_tex);
release_native_gpu_object(probed.ocean_pipeline_handle);
release_native_gpu_object(probed.engine3d_pipeline_handle);
release_native_gpu_object(probed.blur_up_pipeline_handle);
release_native_gpu_object(probed.blur_pipeline_handle);
release_native_gpu_object(probed.pipeline_handle);
release_native_gpu_handles(
probed.device_handle,
probed.queue_handle,
probed.library_handle,
);
let programs: [ShaderProgramId; 4] = ShaderProgramId::all();
let mut entries: Vec<ShaderProgramCacheEntry> = Vec::with_capacity(programs.len());
let mut ready_count: usize = 0;
let mut hw_compiled: usize = 0;
for program in programs {
#[cfg(not(target_arch = "wasm32"))]
let item_start: Instant = Instant::now();
let (src_a, src_b): (&str, &str) = program.source_pair(backend);
let src_bytes: usize = src_a.len().saturating_add(src_b.len());
let src_hash: u64 = shader_program_cache_hash(&device_name, src_a, src_b);
let is_valid: bool = !src_a.is_empty();
let state: ShaderCompileState =
if has_compiled_pso && hardware_gpu && hw_shader_ok && is_valid {
hw_compiled += 1;
ready_count += 1;
ShaderCompileState::CompiledHardware
} else if is_valid {
ready_count += 1;
ShaderCompileState::ValidatedFallback
} else {
ShaderCompileState::Failed
};
#[cfg(not(target_arch = "wasm32"))]
let item_us: u64 = item_start.elapsed().as_micros() as u64;
#[cfg(target_arch = "wasm32")]
let item_us: u64 = 0;
entries.push(ShaderProgramCacheEntry {
program,
name: program.label().to_string(),
language: lang_label.to_string(),
state,
source_hash: src_hash,
source_bytes: src_bytes,
compile_time_us: item_us,
pipeline_ready: state.is_ready(),
});
}
#[cfg(not(target_arch = "wasm32"))]
let elapsed_us: u64 = total_start.elapsed().as_micros() as u64;
#[cfg(target_arch = "wasm32")]
let elapsed_us: u64 = 0;
ShaderPrecompileReport {
backend,
device_name,
hardware_gpu,
binary_archive_enabled: false,
binary_archive_hit: false,
cache_hit: false,
total_programs: entries.len(),
ready_programs: ready_count,
hardware_compiled_programs: hw_compiled,
cold_compile_us: elapsed_us,
last_call_us: elapsed_us,
entries,
}
}
#[must_use]
pub fn precompile_shaders(backend: GraphicsBackend) -> ShaderPrecompileReport {
#[cfg(any(all(unix, not(target_os = "watchos")), windows))]
{
let call_start: Instant = Instant::now();
let cache_mutex: &Mutex<HashMap<GraphicsBackend, ShaderPrecompileReport>> =
SHADER_PRECOMPILE_CACHE.get_or_init(|| Mutex::new(HashMap::new()));
if let Ok(guard) = cache_mutex.lock()
&& let Some(existing) = guard.get(&backend)
{
let mut hit_report: ShaderPrecompileReport = existing.clone();
hit_report.set_cache_hit(true);
hit_report.set_last_call_us(call_start.elapsed().as_micros() as u64);
return hit_report;
}
let fresh: ShaderPrecompileReport = run_shader_precompile_uncached(backend);
if let Ok(mut guard) = cache_mutex.lock() {
let _: Option<ShaderPrecompileReport> = guard.insert(backend, fresh.clone());
}
fresh
}
#[cfg(not(any(all(unix, not(target_os = "watchos")), windows)))]
{
run_shader_precompile_uncached(backend)
}
}
pub fn precompile_shaders_async(backend: GraphicsBackend) {
#[cfg(any(all(unix, not(target_os = "watchos")), windows))]
{
let cache_mutex: &Mutex<HashMap<GraphicsBackend, ShaderPrecompileReport>> =
SHADER_PRECOMPILE_CACHE.get_or_init(|| Mutex::new(HashMap::new()));
if let Ok(guard) = cache_mutex.lock()
&& guard.contains_key(&backend)
{
return;
}
if SHADER_PRECOMPILE_IN_FLIGHT
.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
.is_err()
{
return;
}
let spawn_result: io::Result<JoinHandle<()>> = Builder::new()
.name("euv-shader-precompile".to_string())
.spawn(move || {
let _: ShaderPrecompileReport = precompile_shaders(backend);
SHADER_PRECOMPILE_IN_FLIGHT.store(false, Ordering::Release);
});
if spawn_result.is_err() {
SHADER_PRECOMPILE_IN_FLIGHT.store(false, Ordering::Release);
let _: ShaderPrecompileReport = precompile_shaders(backend);
}
}
#[cfg(not(any(all(unix, not(target_os = "watchos")), windows)))]
{
let _: ShaderPrecompileReport = run_shader_precompile_uncached(backend);
}
}
#[must_use]
pub fn shader_precompile_status() -> Option<ShaderPrecompileReport> {
#[cfg(any(all(unix, not(target_os = "watchos")), windows))]
{
let cache_mutex: &Mutex<HashMap<GraphicsBackend, ShaderPrecompileReport>> =
SHADER_PRECOMPILE_CACHE.get()?;
let guard: MutexGuard<'_, HashMap<GraphicsBackend, ShaderPrecompileReport>> =
cache_mutex.lock().ok()?;
let native_backend: GraphicsBackend = default_native_gpu_backend();
if let Some(native_report) = guard.get(&native_backend) {
return Some(native_report.clone());
}
guard.values().next().cloned()
}
#[cfg(not(any(all(unix, not(target_os = "watchos")), windows)))]
{
None
}
}
#[must_use]
pub fn is_shader_precompile_in_flight() -> bool {
#[cfg(any(all(unix, not(target_os = "watchos")), windows))]
{
SHADER_PRECOMPILE_IN_FLIGHT.load(Ordering::Acquire)
}
#[cfg(not(any(all(unix, not(target_os = "watchos")), windows)))]
{
false
}
}