euv-core 0.53.1

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 `true` when `node` represents wrapping text that requires CPU line breaking.
///
/// # Arguments
///
/// - `&SceneNode` - Candidate scene node.
///
/// # Returns
///
/// - `bool` - `true` for wrapping `NodeKind::Text` nodes.
#[must_use]
pub fn is_wrapping_text_node(node: &SceneNode) -> bool {
    match node.get_kind() {
        NodeKind::Text(content) => {
            !content.is_empty() && node.get_style().get_text().get_overflow() == TextOverflow::Wrap
        }
        _ => false,
    }
}

/// Returns `true` when `node`'s layout display, flex direction, wrapping, and node kind are supported by the GPU compute kernels.
///
/// # Arguments
///
/// - `&SceneNode` - Candidate scene node.
///
/// # Returns
///
/// - `bool` - `true` when supported by GPU compute layout kernels.
#[must_use]
pub fn is_node_gpu_layout_supported(node: &SceneNode) -> bool {
    match node.get_kind() {
        NodeKind::Input(_) | NodeKind::Canvas(CanvasCaching::DynamicPerFrame) => return false,
        _ => {}
    }
    let layout: LayoutStyle = node.get_style().get_layout();
    match layout.get_display() {
        Display::Flex => {
            if layout.get_flex_wrap() != FlexWrap::NoWrap {
                return false;
            }
            matches!(
                layout.get_flex_direction(),
                FlexDirection::Row | FlexDirection::Column
            )
        }
        Display::Block | Display::Grid | Display::None => true,
    }
}

/// Traverses the subtree rooted at `root` iteratively and computes structural and text complexity metrics.
///
/// # Arguments
///
/// - `&SceneTree` - Retained scene tree containing `root`.
/// - `NodeId` - Root node of the subtree to inspect.
///
/// # Returns
///
/// - `SubtreePartitionMetrics` - Measured node counts, depth, and wrapping text ratio.
#[must_use]
pub fn measure_subtree_metrics(tree: &SceneTree, root: NodeId) -> SubtreePartitionMetrics {
    let mut stack: Vec<(NodeId, usize)> = Vec::with_capacity(64);
    stack.push((root, 0));
    let mut total_nodes: usize = 0;
    let mut dirty_nodes: usize = 0;
    let mut wrapping_text_nodes: usize = 0;
    let mut unsupported_mode_nodes: usize = 0;
    let mut max_depth: usize = 0;
    while let Some((node_id, depth)) = stack.pop() {
        let Some(node) = tree.get_node(node_id) else {
            continue;
        };
        total_nodes = total_nodes.saturating_add(1);
        if depth > max_depth {
            max_depth = depth;
        }
        if node.get_dirty().intersects(SUBTREE_LAYOUT_DIRTY_MASK) {
            dirty_nodes = dirty_nodes.saturating_add(1);
        }
        if is_wrapping_text_node(node) {
            wrapping_text_nodes = wrapping_text_nodes.saturating_add(1);
        }
        if !is_node_gpu_layout_supported(node) {
            unsupported_mode_nodes = unsupported_mode_nodes.saturating_add(1);
        }
        for child_id in tree.children_iter(node_id) {
            stack.push((child_id, depth.saturating_add(1)));
        }
    }
    let wrapping_text_ratio: f32 = if total_nodes == 0 {
        0.0
    } else {
        wrapping_text_nodes as f32 / total_nodes as f32
    };
    SubtreePartitionMetrics {
        total_nodes,
        dirty_nodes,
        wrapping_text_nodes,
        unsupported_mode_nodes,
        max_depth,
        wrapping_text_ratio,
    }
}

/// Evaluates whether a subtree with `metrics` and optional `boundary` is eligible for GPU compute layout.
///
/// # Arguments
///
/// - `SubtreePartitionMetrics` - Measured subtree metrics.
/// - `Option<LayoutBoundary>` - Optional explicit containment boundary hint.
/// - `SubtreePartitionConfig` - Active threshold and device configuration.
///
/// # Returns
///
/// - `Result<SubtreeLane, GpuSubtreeRejectReason>` - `Ok(SubtreeLane::GpuSubtree)` when eligible, or rejection reason.
pub fn evaluate_subtree_gpu_eligibility(
    metrics: SubtreePartitionMetrics,
    boundary: Option<LayoutBoundary>,
    config: SubtreePartitionConfig,
) -> Result<SubtreeLane, GpuSubtreeRejectReason> {
    if let Some(bound) = boundary
        && matches!(
            bound.get_hint(),
            LayoutBoundaryHint::ForceCpu | LayoutBoundaryHint::PreferCpu
        )
    {
        return Err(GpuSubtreeRejectReason::ExplicitCpuBoundary);
    }
    if !config.get_hardware_compute_ready() {
        return Err(GpuSubtreeRejectReason::HardwareUnavailable);
    }
    if config.get_thermal_throttled() {
        return Err(GpuSubtreeRejectReason::ThermalThrottled);
    }
    if metrics.get_unsupported_mode_nodes() > 0 {
        return Err(GpuSubtreeRejectReason::UnsupportedLayoutMode);
    }
    if metrics.get_max_depth() > config.get_max_gpu_depth() {
        return Err(GpuSubtreeRejectReason::ExceedsMaxDepth);
    }
    if metrics.get_wrapping_text_ratio() > config.get_max_text_wrap_ratio() {
        return Err(GpuSubtreeRejectReason::TextWrapRatioExceeded);
    }
    let effective_nodes: usize = metrics.get_dirty_nodes().max(metrics.get_total_nodes());
    let min_required: usize = match boundary.map(|bound: LayoutBoundary| bound.get_hint()) {
        Some(LayoutBoundaryHint::PreferGpu) => config.get_min_gpu_nodes() / 2,
        _ => config.get_min_gpu_nodes(),
    };
    if effective_nodes < min_required {
        return Err(GpuSubtreeRejectReason::BelowNodeThreshold);
    }
    Ok(SubtreeLane::GpuSubtree)
}

/// Resolves a `Length` value into a GPU compute scalar (`-1.0` for `Auto`, pixel value otherwise).
///
/// # Arguments
///
/// - `Length` - Style length specification.
/// - `f32` - Parent reference extent in logical pixels.
/// - `f32` - Viewport reference extent in logical pixels.
///
/// # Returns
///
/// - `f32` - Resolved length in logical pixels or `-1.0` for `Length::Auto`.
#[must_use]
fn resolve_gpu_length(length: Length, parent_extent: f32, viewport_extent: f32) -> f32 {
    match length {
        Length::Auto => -1.0,
        Length::Px(px_val) => px_val.max(0.0),
        Length::Percent(pct_val) => (parent_extent * pct_val * 0.01).max(0.0),
        Length::Fraction(frac_val) => (parent_extent * frac_val).max(0.0),
        Length::ViewportWidth(vw_val) | Length::ViewportHeight(vw_val) => {
            (viewport_extent * vw_val * 0.01).max(0.0)
        }
    }
}

/// Translates a `LayoutStyle` into the corresponding `GpuLayoutMode`.
///
/// # Arguments
///
/// - `LayoutStyle` - Node layout properties.
///
/// # Returns
///
/// - `GpuLayoutMode` - Matching GPU compute kernel layout mode.
#[must_use]
fn map_style_to_gpu_layout_mode(layout: LayoutStyle) -> GpuLayoutMode {
    if layout.get_position() == Position::Absolute || layout.get_position() == Position::Fixed {
        return GpuLayoutMode::Absolute;
    }
    match layout.get_display() {
        Display::Grid => GpuLayoutMode::Grid,
        Display::Block => GpuLayoutMode::Block,
        Display::Flex => match layout.get_flex_direction() {
            FlexDirection::Column | FlexDirection::ColumnReverse => GpuLayoutMode::FlexColumn,
            FlexDirection::Row | FlexDirection::RowReverse => GpuLayoutMode::FlexRow,
        },
        Display::None => GpuLayoutMode::Block,
    }
}

/// Translates a `JustifyContent` value into `GpuJustifyMode`.
///
/// # Arguments
///
/// - `JustifyContent` - Flex/grid justify-content mode.
///
/// # Returns
///
/// - `GpuJustifyMode` - Encoded GPU justify mode.
#[must_use]
fn map_justify_to_gpu(justify: JustifyContent) -> GpuJustifyMode {
    match justify {
        JustifyContent::Start => GpuJustifyMode::Start,
        JustifyContent::Center => GpuJustifyMode::Center,
        JustifyContent::End => GpuJustifyMode::End,
        JustifyContent::SpaceBetween
        | JustifyContent::SpaceAround
        | JustifyContent::SpaceEvenly => GpuJustifyMode::SpaceBetween,
    }
}

/// Translates an `AlignItems` value into `GpuAlignMode`.
///
/// # Arguments
///
/// - `AlignItems` - Flex/grid cross-axis alignment mode.
///
/// # Returns
///
/// - `GpuAlignMode` - Encoded GPU alignment mode.
#[must_use]
fn map_align_to_gpu(align: AlignItems) -> GpuAlignMode {
    match align {
        AlignItems::Stretch => GpuAlignMode::Stretch,
        AlignItems::Start => GpuAlignMode::Start,
        AlignItems::Center => GpuAlignMode::Center,
        AlignItems::End => GpuAlignMode::End,
    }
}

/// Packs an eligible `SceneTree` subtree into a level-ordered `GpuComputeSceneInput` ready for Pass 0 dispatch.
///
/// # Arguments
///
/// - `&SceneTree` - Source scene tree.
/// - `NodeId` - Root node of the GPU-eligible subtree.
/// - `f32` - Viewport width in logical pixels.
/// - `f32` - Viewport height in logical pixels.
/// - `f32` - Horizontal scroll offset in logical pixels.
/// - `f32` - Vertical scroll offset in logical pixels.
///
/// # Returns
///
/// - `GpuComputeSceneInput` - Contiguous BFS level-ordered GPU input buffers.
#[must_use]
pub fn build_gpu_compute_scene_from_subtree(
    tree: &SceneTree,
    root: NodeId,
    viewport_width: f32,
    viewport_height: f32,
    scroll_x: f32,
    scroll_y: f32,
) -> GpuComputeSceneInput {
    let mut bfs_nodes: Vec<(NodeId, u32, usize)> = Vec::new();
    bfs_nodes.push((root, u32::MAX, 0));
    let mut level_offsets: Vec<u32> = vec![0];
    let mut cursor: usize = 0;
    let mut current_depth: usize = 0;
    while cursor < bfs_nodes.len() {
        let (node_id, _, depth): (NodeId, u32, usize) = bfs_nodes[cursor];
        if depth > current_depth {
            while current_depth < depth {
                level_offsets.push(cursor as u32);
                current_depth = current_depth.saturating_add(1);
            }
        }
        let parent_flat: u32 = cursor as u32;
        for child_id in tree.children_iter(node_id) {
            bfs_nodes.push((child_id, parent_flat, depth.saturating_add(1)));
        }
        cursor = cursor.saturating_add(1);
    }
    level_offsets.push(bfs_nodes.len() as u32);
    let node_count: usize = bfs_nodes.len();
    let mut first_child_indices: Vec<u32> = vec![0; node_count];
    let mut child_counts: Vec<u32> = vec![0; node_count];
    for (flat_idx, &(_, parent_idx, _)) in bfs_nodes.iter().enumerate() {
        if parent_idx != u32::MAX {
            let parent_usize: usize = parent_idx as usize;
            if child_counts[parent_usize] == 0 {
                first_child_indices[parent_usize] = flat_idx as u32;
            }
            child_counts[parent_usize] = child_counts[parent_usize].saturating_add(1);
        }
    }
    let mut nodes: Vec<GpuLayoutNodeInput> = Vec::with_capacity(node_count);
    let mut visuals: Vec<GpuVisualStyleInput> = Vec::with_capacity(node_count);
    for (flat_idx, &(node_id, parent_idx, _)) in bfs_nodes.iter().enumerate() {
        let Some(scene_node) = tree.get_node(node_id) else {
            nodes.push(GpuLayoutNodeInput::default());
            visuals.push(GpuVisualStyleInput::default());
            continue;
        };
        let style: Style = scene_node.get_style();
        let layout: LayoutStyle = style.get_layout();
        let paint: PaintStyle = style.get_paint();
        let mode: GpuLayoutMode = map_style_to_gpu_layout_mode(layout);
        let justify: GpuJustifyMode = map_justify_to_gpu(layout.get_justify_content());
        let align: GpuAlignMode = map_align_to_gpu(layout.get_align_items());
        let visible: bool = layout.get_display() != Display::None && paint.get_opacity() > 0.001;
        let fill_color: Color = paint.background_color().unwrap_or(COLOR_TRANSPARENT);
        let border: Border = paint.get_border();
        let emit_visual: bool = visible && (fill_color.get_alpha() > 0 || border.get_width() > 0.0);
        let dirty: bool = scene_node.get_dirty().intersects(SUBTREE_LAYOUT_DIRTY_MASK);
        let flags_kind: u32 =
            pack_gpu_layout_flags(mode, justify, align, visible, emit_visual, dirty);
        let width_px: f32 = resolve_gpu_length(layout.get_width(), viewport_width, viewport_width);
        let height_px: f32 =
            resolve_gpu_length(layout.get_height(), viewport_height, viewport_height);
        let min_w: f32 =
            resolve_gpu_length(layout.get_min_width(), viewport_width, viewport_width).max(0.0);
        let min_h: f32 =
            resolve_gpu_length(layout.get_min_height(), viewport_height, viewport_height).max(0.0);
        let padding: Edges = layout.get_padding();
        let pad_h: f32 = padding.get_left();
        let pad_v: f32 = padding.get_top();
        let gap_main: f32 = if layout.get_row_gap() > 0.0 {
            layout.get_row_gap()
        } else {
            layout.get_column_gap()
        };
        let flex_or_col_gap: f32 = if mode == GpuLayoutMode::Grid {
            layout.get_column_gap()
        } else {
            layout.get_flex_grow()
        };
        let extra0: f32 = if mode == GpuLayoutMode::Grid {
            layout.get_grid_columns().max(1) as f32
        } else if mode == GpuLayoutMode::Absolute {
            layout.left_offset().unwrap_or(0.0)
        } else {
            0.0
        };
        let extra1: f32 = if mode == GpuLayoutMode::Absolute {
            layout.top_offset().unwrap_or(0.0)
        } else {
            layout.aspect_ratio_value().unwrap_or(0.0)
        };
        let input: GpuLayoutNodeInput = GpuLayoutNodeInput {
            parent_bfs: parent_idx,
            first_child: first_child_indices[flat_idx],
            child_count: child_counts[flat_idx],
            flags_kind,
            pref_min_size: [width_px.max(0.0), height_px.max(0.0), min_w, min_h],
            pad_gap_flex: [pad_h, pad_v, gap_main, flex_or_col_gap],
            extra_or_intrinsic: [extra0, extra1, 0.0, 0.0],
        };
        let radius: CornerRadius = paint.get_radius();
        let radii_border: [u16; 4] = [
            GpuPrimitiveInstance::pack_u16_q4(radius.get_top_left()),
            GpuPrimitiveInstance::pack_u16_q4(radius.get_top_right()),
            GpuPrimitiveInstance::pack_u16_q4(radius.get_bottom_right()),
            GpuPrimitiveInstance::pack_u16_q4(radius.get_bottom_left()),
        ];
        let visual: GpuVisualStyleInput = GpuVisualStyleInput {
            color_rgba: GpuPrimitiveInstance::pack_color_rgba8(fill_color),
            aux_color_rgba: GpuPrimitiveInstance::pack_color_rgba8(border.get_color()),
            uv_rect: [0, 0, u16::MAX, u16::MAX],
            radii_border,
            kind_flags: GpuPrimitiveInstance::pack_kind_flags(PrimKind::RoundedRect, 0, 0, 0),
            extra_param: GpuPrimitiveInstance::pack_f16x2(border.get_width(), 0.0),
            clip_ancestor_bfs: u32::MAX,
            scroll_layer_id: 0,
            opacity_q16: u16::MAX as u32,
            z_order_bias: 0,
        };
        nodes.push(input);
        visuals.push(visual);
    }
    GpuComputeSceneInput {
        nodes,
        visuals,
        level_offsets,
        viewport_size: [viewport_width.max(1.0), viewport_height.max(1.0)],
        root_boundary_rect: [
            -scroll_x,
            -scroll_y,
            viewport_width.max(1.0),
            viewport_height.max(1.0),
        ],
        dt_secs: 1.0 / 120.0,
        pick_point: None,
        clear_color: COLOR_TRANSPARENT,
    }
}