euv-core 0.55.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::*;

/// Returns a monotonic timestamp in microseconds across native and `wasm32` targets.
///
/// # Returns
///
/// - `u64` - Monotonic elapsed microseconds.
#[must_use]
pub(crate) fn stream_now_us() -> u64 {
    #[cfg(not(target_arch = "wasm32"))]
    {
        let epoch: &Instant = STREAM_CLOCK_EPOCH.get_or_init(Instant::now);
        epoch.elapsed().as_micros() as u64
    }
    #[cfg(target_arch = "wasm32")]
    {
        window()
            .and_then(|win: Window| win.performance())
            .map_or(0, |perf: Performance| {
                (perf.now().max(0.0) * 1_000.0) as u64
            })
    }
}

/// Encodes a pre-cooked streamable RGBA8 texture mip payload with the compact `EUVTEX01` header for zero-parse `.euvpak` streaming.
///
/// # Arguments
///
/// - `u32` - Mip width in texels.
/// - `u32` - Mip height in texels.
/// - `u8` - Mip level index (`0` = full resolution).
/// - `u8` - Total allocated mipmap levels.
/// - `bool` - True when texels use sRGB encoding.
/// - `&[u8]` - Packed RGBA8 texel bytes (`width * height * 4`).
///
/// # Returns
///
/// - `Vec<u8>` - Framed `EUVTEX01` binary payload suitable for `EuvPakWriter::add_entry` or `add_mip_tail`.
#[must_use]
pub fn encode_euvtex_mip_payload(
    width: u32,
    height: u32,
    mip_level: u8,
    total_mip_levels: u8,
    is_srgb: bool,
    rgba8: &[u8],
) -> Vec<u8> {
    let mut out: Vec<u8> = Vec::with_capacity(STREAM_TEX_HEADER_BYTES.saturating_add(rgba8.len()));
    out.extend_from_slice(&STREAM_TEX_HEADER_MAGIC);
    out.extend_from_slice(&width.to_le_bytes());
    out.extend_from_slice(&height.to_le_bytes());
    out.push(mip_level);
    out.push(total_mip_levels.max(1));
    out.push(u8::from(is_srgb));
    out.push(0);
    out.extend_from_slice(rgba8);
    out
}

/// Computes total mipmap chain level count for a texture of dimensions `width x height`.
///
/// # Arguments
///
/// - `u32` - Texture width in texels.
/// - `u32` - Texture height in texels.
///
/// # Returns
///
/// - `u8` - Mipmap chain level count (`>= 1`).
#[must_use]
pub(crate) fn compute_mip_levels(width: u32, height: u32) -> u8 {
    let max_dim: u32 = width.max(height).max(1);
    (32u32.saturating_sub(max_dim.leading_zeros())).max(1) as u8
}

/// Decodes uncompressed texture bytes (`EUVTEX01`, PNG, JPEG, or raw RGBA8) into a `DecodedAssetPayload::Texture`.
///
/// # Arguments
///
/// - `&[u8]` - Uncompressed texture bytes.
/// - `StreamJobKind` - Requested job kind (`TextureMipTail` vs `TextureMip`).
/// - `TextureResidencyTier` - Target progressive residency tier.
/// - `bool` - Default sRGB flag when payload lacks an `EUVTEX01` header.
///
/// # Returns
///
/// - `Result<DecodedAssetPayload, String>` - Decoded RGBA8 texture payload with tier VRAM sizing.
pub(crate) fn decode_texture_payload(
    raw_bytes: &[u8],
    kind: StreamJobKind,
    target_tier: TextureResidencyTier,
    default_srgb: bool,
) -> Result<DecodedAssetPayload, String> {
    let (width, height, mip_level, total_mip_levels, is_srgb, rgba8): (
        u32,
        u32,
        u8,
        u8,
        bool,
        Vec<u8>,
    ) = if raw_bytes.len() >= STREAM_TEX_HEADER_BYTES && raw_bytes[0..8] == STREAM_TEX_HEADER_MAGIC
    {
        let width: u32 =
            u32::from_le_bytes([raw_bytes[8], raw_bytes[9], raw_bytes[10], raw_bytes[11]]);
        let height: u32 =
            u32::from_le_bytes([raw_bytes[12], raw_bytes[13], raw_bytes[14], raw_bytes[15]]);
        let mip_level: u8 = raw_bytes[16];
        let total_mips: u8 = raw_bytes[17].max(1);
        let is_srgb: bool = raw_bytes[18] != 0;
        let pixels: &[u8] = &raw_bytes[STREAM_TEX_HEADER_BYTES..];
        let expected: usize = (width as usize)
            .saturating_mul(height as usize)
            .saturating_mul(4);
        if width == 0 || height == 0 || pixels.len() < expected {
            return Err(ERR_STREAM_INVALID_TEXTURE.to_string());
        }
        (
            width,
            height,
            mip_level,
            total_mips,
            is_srgb,
            pixels[..expected].to_vec(),
        )
    } else if (raw_bytes.len() >= 4 && raw_bytes[0..4] == STREAM_PNG_MAGIC)
        || (raw_bytes.len() >= 2 && raw_bytes[0..2] == STREAM_JPEG_MAGIC)
    {
        let decoded: DecodedRgbaImage = decode_raster_image_rgba(raw_bytes)?;
        let width: u32 = decoded.get_width();
        let height: u32 = decoded.get_height();
        let total_mips: u8 = compute_mip_levels(width, height);
        (
            width,
            height,
            0,
            total_mips,
            default_srgb,
            decoded.get_pixels().clone(),
        )
    } else {
        let pixel_count: usize = (raw_bytes.len() / 4).max(1);
        let side: u32 = (pixel_count as f32).sqrt().max(1.0) as u32;
        let expected: usize = (side as usize)
            .saturating_mul(side as usize)
            .saturating_mul(4);
        let mut rgba: Vec<u8> = Vec::with_capacity(expected);
        if raw_bytes.len() >= expected {
            rgba.extend_from_slice(&raw_bytes[..expected]);
        } else {
            rgba.extend_from_slice(raw_bytes);
            rgba.resize(expected, 255);
        }
        let total_mips: u8 = compute_mip_levels(side, side);
        (side, side, 0, total_mips, default_srgb, rgba)
    };
    let effective_tier: TextureResidencyTier = if kind == StreamJobKind::TextureMipTail {
        TextureResidencyTier::MipTail
    } else if target_tier == TextureResidencyTier::Unloaded {
        TextureResidencyTier::FullRes
    } else {
        target_tier
    };
    let full_width: u32 = if kind == StreamJobKind::TextureMipTail {
        width.saturating_mul(1u32 << mip_level.min(6))
    } else {
        width
    };
    let full_height: u32 = if kind == StreamJobKind::TextureMipTail {
        height.saturating_mul(1u32 << mip_level.min(6))
    } else {
        height
    };
    let decoded_len: usize = rgba8.len().max(64);
    let mip_tail_bytes: usize = if kind == StreamJobKind::TextureMipTail {
        decoded_len
    } else {
        decoded_len.min(RESIDENCY_DEFAULT_MIP_TAIL_BYTES)
    };
    let full_res_bytes: usize = ((full_width as usize)
        .saturating_mul(full_height as usize)
        .saturating_mul(4))
    .max(decoded_len);
    let mid_mip_bytes: usize = (full_res_bytes / 4).max(mip_tail_bytes);
    Ok(DecodedAssetPayload::Texture {
        width: full_width.max(1),
        height: full_height.max(1),
        total_mip_levels: total_mip_levels.max(1),
        is_srgb,
        tier: effective_tier,
        mip_tail_bytes,
        mid_mip_bytes,
        full_res_bytes,
        rgba8,
    })
}

/// Decodes uncompressed `.euvpak` entry bytes into a typed `DecodedAssetPayload` without unnecessary copies.
///
/// # Arguments
///
/// - `Vec<u8>` - Verified uncompressed entry payload bytes.
/// - `StreamJobKind` - Semantic decode job category.
/// - `TextureResidencyTier` - Target texture residency tier.
/// - `bool` - Default sRGB flag for texture decoding.
///
/// # Returns
///
/// - `Result<DecodedAssetPayload, String>` - Typed decoded asset payload or diagnostic error.
pub(crate) fn decode_uncompressed_asset(
    raw_bytes: Vec<u8>,
    kind: StreamJobKind,
    target_tier: TextureResidencyTier,
    is_srgb: bool,
) -> Result<DecodedAssetPayload, String> {
    match kind {
        StreamJobKind::TextureMip | StreamJobKind::TextureMipTail => {
            decode_texture_payload(raw_bytes.as_slice(), kind, target_tier, is_srgb)
        }
        StreamJobKind::MeshEuv3d => {
            let vram_bytes: usize = if raw_bytes.len() >= STREAM_EUV3D_MAGIC.len()
                && raw_bytes[0..STREAM_EUV3D_MAGIC.len()] == STREAM_EUV3D_MAGIC
            {
                let bundle: BakedAssetBundle3D =
                    Euv3dPackage::decode_any_bytes(raw_bytes.as_slice())?;
                let mesh_bytes: usize = bundle
                    .get_scene()
                    .get_meshes()
                    .iter()
                    .map(|mesh: &Mesh3D| {
                        mesh.get_vertices()
                            .len()
                            .saturating_mul(size_of::<QuantizedVertex3D>())
                            .saturating_add(
                                mesh.get_indices().len().saturating_mul(size_of::<u32>()),
                            )
                    })
                    .sum();
                mesh_bytes.max(raw_bytes.len().min(65_536))
            } else {
                raw_bytes.len()
            };
            Ok(DecodedAssetPayload::Mesh {
                vram_bytes,
                raw_bytes,
            })
        }
        StreamJobKind::Audio
        | StreamJobKind::Font
        | StreamJobKind::ShaderCache
        | StreamJobKind::RawBytes => Ok(DecodedAssetPayload::Raw {
            kind: stream_job_to_residency_kind(kind),
            bytes: raw_bytes,
        }),
    }
}

/// Executes one complete zero-copy VFS lookup, CRC32 check, LZ4 decompress, and typed decode for `work`.
///
/// # Arguments
///
/// - `&StreamWorkItem` - Active streaming work item.
/// - `&EuvPakArchive` - Mounted zero-copy `.euvpak` archive.
///
/// # Returns
///
/// - `Result<DecodedAssetPayload, String>` - Decoded payload or structured cancellation/I/O error.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn execute_job_from_archive(
    work: &StreamWorkItem,
    archive: &EuvPakArchive,
) -> Result<DecodedAssetPayload, String> {
    if work.get_cancel_token().is_cancelled() {
        return Err(ERR_STREAM_CANCELLED.to_string());
    }
    let decoded_bytes: Vec<u8> = archive.read_entry_decoded(work.get_key_hash())?;
    if work.get_cancel_token().is_cancelled() {
        return Err(ERR_STREAM_CANCELLED.to_string());
    }
    decode_uncompressed_asset(
        decoded_bytes,
        work.get_kind(),
        work.get_target_tier(),
        work.get_is_srgb(),
    )
}

/// Dedicated native background worker thread loop draining the 4-lane priority queue completely off the frame thread.
///
/// # Arguments
///
/// - `Arc<StreamWorkerContext>` - Shared priority queue, VFS handle, completed output queue, and telemetry counters.
/// - `usize` - Zero-based worker thread index used for work-stealing balance.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn stream_io_worker_loop(ctx: Arc<StreamWorkerContext>, worker_index: usize) {
    while let Some(work) = ctx.queue.wait_pop_or_steal(worker_index) {
        if work.get_cancel_token().is_cancelled() {
            continue;
        }
        let _: usize = ctx.in_progress_workers.fetch_add(1, Ordering::AcqRel);
        let started_us: u64 = stream_now_us();
        let archive_opt: Option<Arc<EuvPakArchive>> = ctx
            .vfs
            .lock()
            .ok()
            .and_then(|guard: MutexGuard<'_, Option<Arc<EuvPakArchive>>>| guard.clone());
        let payload_res: Result<DecodedAssetPayload, String> = match archive_opt {
            Some(archive) => execute_job_from_archive(&work, archive.as_ref()),
            None => Err(ERR_STREAM_NO_VFS.to_string()),
        };
        let elapsed_us: u64 = stream_now_us().saturating_sub(started_us);
        let still_live: bool = ctx.queue.mark_completed(
            work.get_key_hash(),
            work.get_generation(),
            ctx.telemetry.as_ref(),
        );
        if still_live && !work.get_cancel_token().is_cancelled() {
            if payload_res.is_ok() {
                ctx.telemetry.record_decode_us(elapsed_us);
            }
            if let Ok(mut completed) = ctx.completed.lock() {
                completed.push_back(CompletedStreamJob {
                    key_hash: work.get_key_hash(),
                    texture_slot: work.get_texture_slot(),
                    payload: payload_res,
                });
                let _: usize = ctx.completed_count.fetch_add(1, Ordering::Release);
            }
        }
        let _: usize = ctx.in_progress_workers.fetch_sub(1, Ordering::AcqRel);
    }
}