euv-core 0.47.0

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
use super::*;

/// Default `NativeGpuDriver` targets headless recording fallback.
impl Default for NativeGpuDriver {
    /// Creates a headless `NativeGpuDriver`.
    ///
    /// # Returns
    ///
    /// - `Self` - Headless GPU driver.
    fn default() -> Self {
        Self::probe(GraphicsBackend::Headless)
    }
}

/// Construction, surface attachment, texture dirty-rect upload, and pipeline query helpers for `NativeGpuDriver`.
impl NativeGpuDriver {
    /// Probes the active OS GPU hardware, loads or compiles cached native pipelines, and returns a live `NativeGpuDriver`.
    ///
    /// # Arguments
    ///
    /// - `GraphicsBackend` - Requested graphics backend.
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized native GPU driver with automatic headless fallback.
    #[must_use]
    pub fn probe(backend: GraphicsBackend) -> Self {
        let probed: NativeGpuProbeOutput = probe_native_gpu_full(backend);
        let mut fallback: RecordingGpuDriver = RecordingGpuDriver::default();
        fallback.set_backend_kind(backend);
        Self {
            adapter: probed.adapter,
            device_handle: probed.device_handle,
            queue_handle: probed.queue_handle,
            library_handle: probed.library_handle,
            pipeline_handle: probed.pipeline_handle,
            blur_pipeline_handle: probed.blur_pipeline_handle,
            surface_layer_handle: 0,
            glyph_r8_texture_handle: probed.dummy_r8_tex,
            glyph_rgba8_texture_handle: probed.dummy_rgba8_tex,
            image_texture_handle: retain_native_gpu_object(probed.dummy_rgba8_tex),
            external_texture_handle: 0,
            ring_slots: [NativeGpuRingSlot::default(); GPU_DRIVER_RING_SLOTS],
            ring_cursor: 0,
            staging_buffer_handle: 0,
            staging_contents_ptr: 0,
            staging_buffer_capacity: 0,
            submitted_frames: 0,
            uploaded_instances: 0,
            uploaded_bytes: 0,
            last_upload_bytes: 0,
            last_submitted_batches: 0,
            staging_reallocations: 0,
            last_presented_time_ns: 0,
            last_gpu_exec_ns: 0,
            #[cfg(any(target_os = "macos", target_os = "ios"))]
            scratch_primitives: Vec::new(),
            fallback,
        }
    }

    /// Re-initializes the GPU driver for `backend`, releasing any previously retained OS handles.
    ///
    /// # Arguments
    ///
    /// - `GraphicsBackend` - Target graphics backend.
    pub fn switch_backend(&mut self, backend: GraphicsBackend) {
        if self.get_adapter().get_backend() == backend {
            return;
        }
        *self = Self::probe(backend);
    }

    /// Attaches a native `CAMetalLayer*` (or equivalent surface layer) for zero-readback hardware presentation.
    ///
    /// # Arguments
    ///
    /// - `usize` - Native `CAMetalLayer*` pointer (`0` detaches).
    pub fn attach_metal_layer(&mut self, layer_handle: usize) {
        let dev: usize = self.get_device_handle();
        let Self {
            surface_layer_handle,
            ..
        } = self;
        *surface_layer_handle = layer_handle;
        if dev != 0 && layer_handle != 0 {
            configure_native_metal_layer(dev, layer_handle);
        }
    }

    /// Binds an external shared-device GPU texture handle (3D game render target or hardware video surface).
    ///
    /// # Arguments
    ///
    /// - `usize` - Native external texture handle (`0` restores fallback dummy texture).
    pub fn set_external_texture(&mut self, texture_handle: usize) {
        let Self {
            external_texture_handle,
            ..
        } = self;
        *external_texture_handle = texture_handle;
    }

    /// Uploads a dirty R8 or RGBA8 sub-rectangle to the resident glyph atlas or image texture on GPU.
    ///
    /// # Arguments
    ///
    /// - `GpuAtlasPixelFormat` - Target texture pixel format (`R8Unorm` or `Rgba8Unorm`).
    /// - `u8` - Texture slot (`0` = R8 glyph atlas, `1` = RGBA8 color glyph atlas, `2` = UI image texture).
    /// - `(u32, u32)` - Full backing texture dimensions `(width, height)`.
    /// - `(u32, u32, u32, u32)` - Dirty sub-region `(x, y, width, height)`.
    /// - `&[u8]` - Source pixel bytes.
    /// - `usize` - Row stride in bytes.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when the dirty sub-rectangle uploaded cleanly to hardware GPU memory.
    pub fn upload_texture_dirty_rect(
        &mut self,
        format: GpuAtlasPixelFormat,
        texture_slot: u8,
        tex_dims: (u32, u32),
        dirty_rect: (u32, u32, u32, u32),
        bytes: &[u8],
        bytes_per_row: usize,
    ) -> bool {
        let dev: usize = self.get_device_handle();
        let Self {
            glyph_r8_texture_handle,
            glyph_rgba8_texture_handle,
            image_texture_handle,
            ..
        } = self;
        let target: &mut usize = match texture_slot {
            0 => glyph_r8_texture_handle,
            1 => glyph_rgba8_texture_handle,
            _ => image_texture_handle,
        };
        upload_native_texture_dirty_rect(
            dev,
            target,
            format,
            tex_dims,
            dirty_rect,
            bytes,
            bytes_per_row,
        )
    }

    /// Returns `true` when the driver has both a live compiled GPU blur pipeline and an attached presentation surface.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when `BackdropBlur` can execute natively on GPU without CPU fallback.
    #[must_use]
    pub fn supports_backdrop_blur_pass(&self) -> bool {
        self.get_blur_pipeline_handle() != 0 && self.get_surface_layer_handle() != 0
    }
}

/// `GpuDriver` implementation uploading packed 64-byte `GpuPrimitiveInstance` streams to the active physical OS GPU.
impl GpuDriver for NativeGpuDriver {
    /// Returns the resolved `GraphicsBackend`.
    ///
    /// # Returns
    ///
    /// - `GraphicsBackend` - Active backend tag.
    fn backend(&self) -> GraphicsBackend {
        self.get_adapter().get_backend()
    }

    /// Returns the native shader source compiled by this GPU backend.
    ///
    /// # Returns
    ///
    /// - `&'static str` - Native shader program source.
    fn shader_source(&self) -> &'static str {
        self.get_fallback().shader_source()
    }

    /// Uploads instanced 64-byte primitive batches through the 3-slot fenced ring and records draw telemetry.
    ///
    /// # Arguments
    ///
    /// - `u32` - Surface width.
    /// - `u32` - Surface height.
    /// - `Color` - Surface clear color.
    /// - `&[GpuBatch]` - Ordered draw batches.
    ///
    /// # Returns
    ///
    /// - `Result<usize, PlatformError>` - Number of submitted GPU draw calls.
    fn submit_batches(
        &mut self,
        width: u32,
        height: u32,
        clear_color: Color,
        batches: &[GpuBatch],
    ) -> Result<usize, PlatformError> {
        let uploaded: usize =
            submit_native_gpu_ring_frame(self, width, height, clear_color, batches);
        let frame_bytes: usize = uploaded.saturating_mul(GPU_PRIMITIVE_INSTANCE_BYTES);
        let Self {
            submitted_frames,
            uploaded_instances,
            uploaded_bytes,
            last_upload_bytes,
            last_submitted_batches,
            last_presented_time_ns,
            last_gpu_exec_ns,
            fallback,
            ..
        } = self;
        *submitted_frames = submitted_frames.wrapping_add(1);
        *uploaded_instances = uploaded_instances.wrapping_add(uploaded as u64);
        *uploaded_bytes = uploaded_bytes.wrapping_add(frame_bytes as u64);
        *last_upload_bytes = frame_bytes;
        *last_submitted_batches = batches.len();
        *last_presented_time_ns = native_gpu_last_presented_ns();
        *last_gpu_exec_ns = native_gpu_last_exec_ns();
        fallback.submit_batches(width, height, clear_color, batches)
    }
}

/// Automatic native GPU handle cleanup when `NativeGpuDriver` is dropped.
impl Drop for NativeGpuDriver {
    /// Releases retained OS GPU ring buffers, in-flight command buffers, textures, pipelines, and device handles.
    fn drop(&mut self) {
        let Self {
            device_handle,
            queue_handle,
            library_handle,
            pipeline_handle,
            blur_pipeline_handle,
            glyph_r8_texture_handle,
            glyph_rgba8_texture_handle,
            image_texture_handle,
            ring_slots,
            staging_buffer_handle,
            staging_contents_ptr,
            staging_buffer_capacity,
            ..
        } = self;
        for slot in ring_slots.iter_mut() {
            let cmd: usize = slot.get_in_flight_cmd_buffer();
            if cmd != 0 {
                release_native_gpu_object(cmd);
                slot.set_in_flight_cmd_buffer(0);
            }
            let buf: usize = slot.get_buffer_handle();
            if buf != 0 {
                release_native_gpu_object(buf);
                slot.set_buffer_handle(0);
                slot.set_contents_ptr(0);
                slot.set_capacity_bytes(0);
            }
        }
        *staging_buffer_handle = 0;
        *staging_contents_ptr = 0;
        *staging_buffer_capacity = 0;
        release_native_gpu_object(*glyph_r8_texture_handle);
        release_native_gpu_object(*glyph_rgba8_texture_handle);
        release_native_gpu_object(*image_texture_handle);
        release_native_gpu_object(*blur_pipeline_handle);
        release_native_gpu_object(*pipeline_handle);
        release_native_gpu_handles(*device_handle, *queue_handle, *library_handle);
    }
}