facett-graphview 0.1.12

facett — a vello-backed, domain-agnostic scalable 2D graph render engine. Runtime-selects vello (GPU/wgpu) when a usable GPU exists, vello_cpu (multithreaded SIMD) as the no-GPU fallback. The eventual home for every graph surface (dep/arch/release dashboards, korp, graph-DB browsing).
Documentation
//! **facett-graphview** — a domain-agnostic, scalable 2D **graph render engine**,
//! vello-backed, that **runtime-selects its backend by hardware**: `vello`
//! (GPU/wgpu compute) when a usable GPU exists, `vello_cpu` (multithreaded SIMD)
//! as the no-GPU fallback. The eventual single home for every graph surface —
//! nornir's arch/dep/release dashboards, korp, graph-DB browsing — aiming to
//! beat Graphviz on interactivity + scale.
//!
//! # The shared API (a future drop-in for nornir's `draw_graph`)
//! The model — [`GraphModel`] (nodes id/label/pos/fill/stroke + edges
//! from/to/color/dashed/label) and the caller-supplied [`Decorations`] overlay
//! (per-node ring/badge + emphasis edges) — mirrors nornir's
//! `src/viz/graph_render.rs` SHARED API exactly, so that egui routine can swap
//! its painter for this engine without changing its callers. Decorations stay
//! caller-supplied and domain-agnostic: facett never learns what a "release
//! gate" is.
//!
//! # Backends (vello is NOT GPU-only)
//! [`Backend`] {`GpuVello`, `CpuVello`}; [`decide`] turns a [`GpuProbe`] into a
//! pick (probe → choose, mirroring nornir's embedder runtime-select). The CPU
//! path ([`cpu::render`]) is the proven reference — `vello_cpu` already ships
//! transitively inside epaint 0.34, so it always builds here. The GPU path is a
//! real, version-aligned seam (`vello` 0.9 ↔ wgpu 29 ↔ egui-wgpu 0.34), wired
//! behind the `gpu` cargo feature; see [`gpu`].
//!
//! # Render entry point
//! [`render_to_rgba`] dispatches on the chosen [`Backend`] and returns straight
//! RGBA8 pixels (PNG / egui-texture ready). Today both backends route through
//! the CPU rasterizer (the GPU readback path is the #17 follow-up); the dispatch
//! seam is in place.
//!
//! # What is STUBBED (documented, not built — see `.nornir/design.md`)
//! LOD / viewport-culling, clustering / aggregation, edge-bundling, streaming
//! layout, and the data-source **adapters** (nornir dep graph / FalkorDB /
//! pipeline). Clear TODOs live at each seam.

/// The pure-algorithm **graph analysis** toolbox (centrality / community /
/// pathfinding / cycles / components / k-core / similarity) — the compute core of the
/// graph-DB IDE. Index-based `(n, edges)`; no egui, no GPU.
pub mod analysis;
pub mod backend;
pub mod clip;
pub mod community;
pub mod cpu;
pub mod decorated_view;
pub mod depgraph_layout;
pub mod fdeb;
pub mod gpu_layout;
pub mod l0;
pub mod metro;
pub mod model;

#[cfg(feature = "gpu")]
pub mod gpu;

pub use backend::{Backend, GpuProbe, decide, probe_from_env};
pub use clip::{GraphClipReport, WidgetRect, pick, render_graph_clipped};
pub use cpu::{Rendered, render as render_cpu};
pub use decorated_view::{DecoratedGraphView, downstream_of};
pub use depgraph_layout::{DepEdge, DepGraphLayout, EdgeClass, LaidEdge, LaidNode};
// The elite GPU-compute layout engine (#1): CSR streamed from Arrow → force-directed
// positions that iterate in VRAM (feature `gpu`), with the deterministic CPU fallback
// always built. See [`gpu_layout`] + `.nornir/elite-graph-engine.md`.
pub use gpu_layout::{relax_cpu, step_cpu, GraphCsr, LayoutParams, LayoutState};
// Force-directed edge bundling (#2): the hairball cure — compatible edges attract
// into shared "information highways". See [`fdeb`].
pub use fdeb::{bundle, occupancy, BundleParams, BundledEdge};
// Topological semantic zoom (#3): Louvain communities collapse into meta-nodes when
// zoomed out and fracture open (injected-clock easing) when zoomed in. See [`community`].
pub use community::{
    fracture_t, fractured_positions, louvain, meta_graph, visible_count, Communities, MetaGraph, MetaNode,
};
// CONS-CORE Phase C: the opt-in L0 kernel adoption (routes nodes/edges through the
// shared `facett_core::render` Canvas). The default render path
// ([`render_to_rgba`]) is UNCHANGED — this is the alternative L0 lane.
pub use l0::{render_to_rgba_l0, lower as lower_to_l0};
pub use metro::{MetroBranch, MetroLine, MetroMap, MetroStation, MetroView, StationKind};
pub use model::{
    BOX_H, BOX_W, Camera, Color, Decorations, GraphEdge, GraphModel, GraphNode, NodeDecoration, Pos,
};

/// Render `model` (decorated, under `camera`) to a `w × h` straight-RGBA8 frame,
/// dispatching on the runtime-chosen `backend`. The one call a host makes after
/// [`decide`].
///
/// Both [`Backend`] arms currently rasterize through [`cpu::render`]: the
/// `GpuVello` arm builds its vello GPU scene (when the `gpu` feature is on) for
/// the seam, then falls through to the CPU rasterizer for the readback — the GPU
/// texture readback is the #17 follow-up. The point of this spike is the
/// architecture + the proven CPU path + the version-aligned GPU seam, not a live
/// GPU framebuffer on a headless box.
pub fn render_to_rgba(
    backend: Backend,
    model: &GraphModel,
    decorations: &Decorations,
    camera: &Camera,
    width: u32,
    height: u32,
    background: Color,
) -> Rendered {
    // ── render-lane dispatch emit: record WHICH backend arm this call took ─────
    // The recurring smear hid in an uninstrumented branch; emit the chosen arm so
    // the matrix proves both the GpuVello and CpuVello dispatch arms get exercised.
    #[cfg(feature = "testmatrix")]
    facett_core::testmatrix::emit(
        "facett-graphview::render_to_rgba",
        "render_dispatch",
        true,
        &format!("backend={backend:?} nodes={} edges={}", model.nodes.len(), model.edges.len()),
    );
    match backend {
        Backend::GpuVello => {
            #[cfg(feature = "gpu")]
            {
                // Build the GPU scene (proves the vello-0.9 seam compiles); the
                // texture render+readback is the #17 follow-up, so we hand back
                // the CPU raster for now to keep one pixel contract.
                let _scene = gpu::build_scene(model, decorations, camera);
            }
            cpu::render(model, decorations, camera, width, height, background)
        }
        Backend::CpuVello => cpu::render(model, decorations, camera, width, height, background),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn sample_graph() -> GraphModel {
        let nodes = vec![
            GraphNode {
                id: "a".into(),
                label: "alpha".into(),
                fill: Color::rgb(60, 90, 160),
                stroke: Color::WHITE,
                pos: Pos::new(0.0, 0.0),
            },
            GraphNode {
                id: "b".into(),
                label: "beta".into(),
                fill: Color::rgb(60, 140, 90),
                stroke: Color::WHITE,
                pos: Pos::new(300.0, -80.0),
            },
            GraphNode {
                id: "c".into(),
                label: "gamma".into(),
                fill: Color::rgb(160, 90, 60),
                stroke: Color::WHITE,
                pos: Pos::new(300.0, 80.0),
            },
        ];
        let edges = vec![
            GraphEdge { from: "a".into(), to: "b".into(), color: Color::rgb(200, 200, 220), dashed: false, label: None },
            GraphEdge { from: "a".into(), to: "c".into(), color: Color::rgb(200, 200, 220), dashed: true, label: None },
        ];
        GraphModel { nodes, edges }
    }

    #[test]
    fn cpu_render_produces_nonblank_frame() {
        let model = sample_graph();
        let cam = Camera::fit(&model, 640.0, 480.0, 40.0);
        let backend = decide(GpuProbe::cpu_only());
        assert_eq!(backend, Backend::CpuVello);
        let frame = render_to_rgba(
            backend,
            &model,
            &Decorations::default(),
            &cam,
            640,
            480,
            Color::rgb(18, 20, 28),
        );
        assert_eq!(frame.rgba.len(), 640 * 480 * 4);
        // Non-blank: more than one distinct colour drew (chips + edges over bg).
        let mut seen = std::collections::HashSet::new();
        for px in frame.rgba.chunks_exact(4) {
            seen.insert([px[0], px[1], px[2]]);
            if seen.len() > 3 {
                break;
            }
        }
        assert!(seen.len() > 3, "vello_cpu drew a real graph, not a flat pane");
    }

    #[test]
    fn camera_fit_centers_world() {
        let model = sample_graph();
        let cam = Camera::fit(&model, 640.0, 480.0, 40.0);
        // The world-bounds centre should land near the viewport centre.
        let (min_x, min_y, max_x, max_y) = model.world_bounds().unwrap();
        let (wcx, wcy) = ((min_x + max_x) * 0.5, (min_y + max_y) * 0.5);
        let (sx, sy) = cam.project(Pos::new(wcx, wcy));
        assert!((sx - 320.0).abs() < 1.0, "x centered, got {sx}");
        assert!((sy - 240.0).abs() < 1.0, "y centered, got {sy}");
    }
}