// Guttman R-tree (quadratic split), M = 16, m = 6.
//
// Nodes live in one contiguous pool addressed by u32 index. Each node stores
// its 16 entry rectangles as four coordinate arrays (structure of arrays) so
// that intersection / containment / distance / enlargement tests over all
// entries of a node are done with 16-lane portable vectors. Unused slots hold
// an "empty" rectangle (x0 = y0 = 2^20, x1 = y1 = -1) that never intersects
// or contains anything, so search needs no count mask.

const std = @import("std");
const Allocator = std.mem.Allocator;

const M: u32 = 16;
const MIN_FILL: u32 = 6;
const MAXH: usize = 40;

const V = @Vector(16, i32);
const VL = @Vector(16, i64);
const VU = @Vector(16, u32);
const BV = @Vector(16, bool);

const EMPTY_LO: i32 = 1 << 20;
const EMPTY_HI: i32 = -1;
const NONE: u32 = 0xFFFF_FFFF;
const I64MAX: i64 = std.math.maxInt(i64);
const I64MIN: i64 = std.math.minInt(i64);

const LANE: VU = blk: {
    var a: [16]u32 = undefined;
    for (&a, 0..) |*v, i| v.* = @intCast(i);
    break :blk a;
};

inline fn band(a: BV, b: BV) BV {
    return @select(bool, a, b, @as(BV, @splat(false)));
}

inline fn bits16(m: BV) u32 {
    return @as(u16, @bitCast(m));
}

inline fn widen(v: V) VL {
    return @intCast(v);
}

const Rect = struct {
    x0: i32,
    y0: i32,
    x1: i32,
    y1: i32,
};

const Node = struct {
    x0: [M]i32 align(128),
    y0: [M]i32,
    x1: [M]i32,
    y1: [M]i32,
    ref: [M]u32, // entry id (leaf) or child node index (internal)
    count: u32,
    level: u32, // 0 = leaf

    inline fn clearFrom(n: *Node, from: u32) void {
        var i = from;
        while (i < M) : (i += 1) {
            n.x0[i] = EMPTY_LO;
            n.y0[i] = EMPTY_LO;
            n.x1[i] = EMPTY_HI;
            n.y1[i] = EMPTY_HI;
        }
    }

    inline fn bbox(n: *const Node) Rect {
        const x0: V = n.x0;
        const y0: V = n.y0;
        const x1: V = n.x1;
        const y1: V = n.y1;
        return .{
            .x0 = @reduce(.Min, x0),
            .y0 = @reduce(.Min, y0),
            .x1 = @reduce(.Max, x1),
            .y1 = @reduce(.Max, y1),
        };
    }

    inline fn setRect(n: *Node, i: u32, r: Rect) void {
        n.x0[i] = r.x0;
        n.y0[i] = r.y0;
        n.x1[i] = r.x1;
        n.y1[i] = r.y1;
    }

    inline fn getRect(n: *const Node, i: u32) Rect {
        return .{ .x0 = n.x0[i], .y0 = n.y0[i], .x1 = n.x1[i], .y1 = n.y1[i] };
    }

    inline fn append(n: *Node, r: Rect, ref: u32) void {
        const c = n.count;
        n.setRect(c, r);
        n.ref[c] = ref;
        n.count = c + 1;
    }

    // Remove entry i by moving the last entry into its slot.
    inline fn removeAt(n: *Node, i: u32) void {
        const last = n.count - 1;
        if (i != last) {
            n.x0[i] = n.x0[last];
            n.y0[i] = n.y0[last];
            n.x1[i] = n.x1[last];
            n.y1[i] = n.y1[last];
            n.ref[i] = n.ref[last];
        }
        n.x0[last] = EMPTY_LO;
        n.y0[last] = EMPTY_LO;
        n.x1[last] = EMPTY_HI;
        n.y1[last] = EMPTY_HI;
        n.count = last;
    }

    // Index of the child needing least enlargement to include r; ties by
    // smallest area, then lowest index.
    inline fn chooseSubtree(n: *const Node, r: Rect) u32 {
        const x0: V = n.x0;
        const y0: V = n.y0;
        const x1: V = n.x1;
        const y1: V = n.y1;
        const area = widen(x1 - x0) * widen(y1 - y0);
        const ux0 = @min(x0, @as(V, @splat(r.x0)));
        const uy0 = @min(y0, @as(V, @splat(r.y0)));
        const ux1 = @max(x1, @as(V, @splat(r.x1)));
        const uy1 = @max(y1, @as(V, @splat(r.y1)));
        const uarea = widen(ux1 - ux0) * widen(uy1 - uy0);
        const maxv: VL = @splat(I64MAX);
        const valid = LANE < @as(VU, @splat(n.count));
        const enl = @select(i64, valid, uarea - area, maxv);
        const me = @reduce(.Min, enl);
        const a2 = @select(i64, enl == @as(VL, @splat(me)), area, maxv);
        const ma = @reduce(.Min, a2);
        return @ctz(bits16(a2 == @as(VL, @splat(ma))));
    }
};

comptime {
    std.debug.assert(@sizeOf(Node) == 384);
}

const HeapItem = struct {
    d: i64,
    n: u32,
};

const Orphan = struct {
    r: Rect,
    ref: u32,
    level: u32,
};

pub const RTree = struct {
    allocator: Allocator,
    nodes: []Node,
    used: u32, // pool slots ever handed out
    free_head: u32, // intrusive free list (next index stored in .count)
    free_count: u32,
    root: u32,
    size: usize,

    // nearest() scratch
    heap: []HeapItem,
    res_d: []i64,
    res_id: []i32,

    pub fn init(allocator: Allocator) RTree {
        return .{
            .allocator = allocator,
            .nodes = &.{},
            .used = 0,
            .free_head = NONE,
            .free_count = 0,
            .root = NONE,
            .size = 0,
            .heap = &.{},
            .res_d = &.{},
            .res_id = &.{},
        };
    }

    pub fn deinit(self: *RTree) void {
        self.allocator.free(self.nodes);
        self.allocator.free(self.heap);
        self.allocator.free(self.res_d);
        self.allocator.free(self.res_id);
        self.* = undefined;
    }

    // ------------------------------------------------------------ pool

    // Make sure `k` nodes can be allocated without growing the pool.
    fn reserve(self: *RTree, k: u32) Allocator.Error!void {
        const avail = self.free_count + (@as(u32, @intCast(self.nodes.len)) - self.used);
        if (avail >= k) return;
        var new_cap: usize = @max(self.nodes.len * 2, 64);
        if (new_cap < self.used + k) new_cap = self.used + k;
        self.nodes = try self.allocator.realloc(self.nodes, new_cap);
    }

    inline fn allocNode(self: *RTree, level: u32) u32 {
        var idx: u32 = undefined;
        if (self.free_head != NONE) {
            idx = self.free_head;
            self.free_head = self.nodes[idx].count;
            self.free_count -= 1;
        } else {
            idx = self.used;
            self.used += 1;
        }
        const n = &self.nodes[idx];
        n.count = 0;
        n.level = level;
        n.clearFrom(0);
        return idx;
    }

    inline fn freeNode(self: *RTree, idx: u32) void {
        self.nodes[idx].count = self.free_head;
        self.free_head = idx;
        self.free_count += 1;
    }

    // ------------------------------------------------------------ insert

    pub fn insert(self: *RTree, x0: i32, y0: i32, x1: i32, y1: i32, id: i32) Allocator.Error!void {
        if (self.root == NONE) {
            try self.reserve(1);
            self.root = self.allocNode(0);
        }
        try self.insertAt(.{ .x0 = x0, .y0 = y0, .x1 = x1, .y1 = y1 }, @bitCast(id), 0);
        self.size += 1;
    }

    // Insert entry (r, ref) into a node at `level` (0 = leaf).
    fn insertAt(self: *RTree, r: Rect, ref: u32, level: u32) Allocator.Error!void {
        try self.reserve(self.nodes[self.root].level + 2);
        const nodes = self.nodes.ptr;

        var path_n: [MAXH]u32 = undefined;
        var path_i: [MAXH]u32 = undefined;
        var depth: usize = 0;
        var cur = self.root;
        while (true) {
            const n = &nodes[cur];
            if (n.level == level) break;
            const i = n.chooseSubtree(r);
            // The child's exact bounding rectangle after the insertion is the
            // union (a split below does not change the union of the halves).
            n.x0[i] = @min(n.x0[i], r.x0);
            n.y0[i] = @min(n.y0[i], r.y0);
            n.x1[i] = @max(n.x1[i], r.x1);
            n.y1[i] = @max(n.y1[i], r.y1);
            path_n[depth] = cur;
            path_i[depth] = i;
            depth += 1;
            const next = n.ref[i];
            @prefetch(@as([*]const u8, @ptrCast(&nodes[next])), .{});
            @prefetch(@as([*]const u8, @ptrCast(&nodes[next])) + 128, .{});
            @prefetch(@as([*]const u8, @ptrCast(&nodes[next])) + 256, .{});
            cur = next;
        }

        if (nodes[cur].count < M) {
            nodes[cur].append(r, ref);
            return;
        }
        var sib = self.split(cur, r, ref);
        while (depth > 0) {
            depth -= 1;
            const pidx = path_n[depth];
            const p = &nodes[pidx];
            p.setRect(path_i[depth], nodes[cur].bbox());
            const sb = nodes[sib].bbox();
            if (p.count < M) {
                p.append(sb, sib);
                return;
            }
            cur = pidx;
            sib = self.split(cur, sb, sib);
        }
        // The root was split: grow the tree.
        const old = cur;
        const nr = self.allocNode(nodes[old].level + 1);
        nodes[nr].append(nodes[old].bbox(), old);
        nodes[nr].append(nodes[sib].bbox(), sib);
        self.root = nr;
    }

    // Quadratic split of node `idx`'s 16 entries plus (r, ref). Group 1 stays
    // in `idx`, group 2 goes to a new node whose index is returned.
    fn split(self: *RTree, idx: u32, r: Rect, ref: u32) u32 {
        const N = M + 1;
        const n = &self.nodes[idx];
        var ex0: [N]i32 = undefined;
        var ey0: [N]i32 = undefined;
        var ex1: [N]i32 = undefined;
        var ey1: [N]i32 = undefined;
        var eref: [N]u32 = undefined;
        var area: [N]i64 = undefined;

        const X0: V = n.x0;
        const Y0: V = n.y0;
        const X1: V = n.x1;
        const Y1: V = n.y1;
        const A = widen(X1 - X0) * widen(Y1 - Y0);
        ex0[0..M].* = n.x0;
        ey0[0..M].* = n.y0;
        ex1[0..M].* = n.x1;
        ey1[0..M].* = n.y1;
        eref[0..M].* = n.ref;
        area[0..M].* = A;
        ex0[M] = r.x0;
        ey0[M] = r.y0;
        ex1[M] = r.x1;
        ey1[M] = r.y1;
        eref[M] = ref;
        area[M] = @as(i64, r.x1 - r.x0) * @as(i64, r.y1 - r.y0);

        // PickSeeds: maximise area(J) - area(E1) - area(E2).
        var best: i64 = I64MIN;
        var s1: usize = 0;
        var s2: usize = 1;
        const minv: VL = @splat(I64MIN);
        var i: usize = 0;
        while (i < N) : (i += 1) {
            const jx0 = @min(X0, @as(V, @splat(ex0[i])));
            const jy0 = @min(Y0, @as(V, @splat(ey0[i])));
            const jx1 = @max(X1, @as(V, @splat(ex1[i])));
            const jy1 = @max(Y1, @as(V, @splat(ey1[i])));
            var d = widen(jx1 - jx0) * widen(jy1 - jy0) - A - @as(VL, @splat(area[i]));
            // pairs (j, i) with j < i among the node's entries (and all of them
            // for the new entry i = 16)
            d = @select(i64, LANE < @as(VU, @splat(@as(u32, @intCast(i)))), d, minv);
            const m = @reduce(.Max, d);
            if (m > best) {
                best = m;
                s1 = i;
                s2 = @ctz(bits16(d == @as(VL, @splat(m))));
            }
        }

        var grp: [N]u8 = undefined;
        grp[s1] = 0;
        grp[s2] = 1;
        var g1 = Rect{ .x0 = ex0[s1], .y0 = ey0[s1], .x1 = ex1[s1], .y1 = ey1[s1] };
        var g2 = Rect{ .x0 = ex0[s2], .y0 = ey0[s2], .x1 = ex1[s2], .y1 = ey1[s2] };
        var a1: i64 = area[s1];
        var a2: i64 = area[s2];
        var c1: u32 = 1;
        var c2: u32 = 1;
        var rem: [N]u8 = undefined;
        var nrem: u32 = 0;
        i = 0;
        while (i < N) : (i += 1) {
            if (i != s1 and i != s2) {
                rem[nrem] = @intCast(i);
                nrem += 1;
            }
        }

        while (nrem > 0) {
            if (c1 + nrem <= MIN_FILL) {
                for (rem[0..nrem]) |e| grp[e] = 0;
                break;
            }
            if (c2 + nrem <= MIN_FILL) {
                for (rem[0..nrem]) |e| grp[e] = 1;
                break;
            }
            // PickNext
            var best_diff: i64 = -1;
            var bk: u32 = 0;
            var bd1: i64 = 0;
            var bd2: i64 = 0;
            var k: u32 = 0;
            while (k < nrem) : (k += 1) {
                const e = rem[k];
                const d1 = @as(i64, @max(g1.x1, ex1[e]) - @min(g1.x0, ex0[e])) *
                    @as(i64, @max(g1.y1, ey1[e]) - @min(g1.y0, ey0[e])) - a1;
                const d2 = @as(i64, @max(g2.x1, ex1[e]) - @min(g2.x0, ex0[e])) *
                    @as(i64, @max(g2.y1, ey1[e]) - @min(g2.y0, ey0[e])) - a2;
                const diff = if (d1 > d2) d1 - d2 else d2 - d1;
                if (diff > best_diff) {
                    best_diff = diff;
                    bk = k;
                    bd1 = d1;
                    bd2 = d2;
                }
            }
            const e = rem[bk];
            nrem -= 1;
            rem[bk] = rem[nrem];
            const to_first = if (bd1 != bd2)
                bd1 < bd2
            else if (a1 != a2)
                a1 < a2
            else
                c1 <= c2;
            if (to_first) {
                grp[e] = 0;
                g1 = .{ .x0 = @min(g1.x0, ex0[e]), .y0 = @min(g1.y0, ey0[e]), .x1 = @max(g1.x1, ex1[e]), .y1 = @max(g1.y1, ey1[e]) };
                a1 += bd1;
                c1 += 1;
            } else {
                grp[e] = 1;
                g2 = .{ .x0 = @min(g2.x0, ex0[e]), .y0 = @min(g2.y0, ey0[e]), .x1 = @max(g2.x1, ex1[e]), .y1 = @max(g2.y1, ey1[e]) };
                a2 += bd2;
                c2 += 1;
            }
        }

        const sidx = self.allocNode(n.level);
        const s = &self.nodes[sidx];
        var na: u32 = 0;
        var nb: u32 = 0;
        i = 0;
        while (i < N) : (i += 1) {
            if (grp[i] == 0) {
                n.x0[na] = ex0[i];
                n.y0[na] = ey0[i];
                n.x1[na] = ex1[i];
                n.y1[na] = ey1[i];
                n.ref[na] = eref[i];
                na += 1;
            } else {
                s.x0[nb] = ex0[i];
                s.y0[nb] = ey0[i];
                s.x1[nb] = ex1[i];
                s.y1[nb] = ey1[i];
                s.ref[nb] = eref[i];
                nb += 1;
            }
        }
        n.count = na;
        n.clearFrom(na);
        s.count = nb;
        return sidx;
    }

    // ------------------------------------------------------------ remove

    pub fn remove(self: *RTree, x0: i32, y0: i32, x1: i32, y1: i32, id: i32) Allocator.Error!bool {
        if (self.size == 0) return false;
        const nodes = self.nodes.ptr;
        const qx0: V = @splat(x0);
        const qy0: V = @splat(y0);
        const qx1: V = @splat(x1);
        const qy1: V = @splat(y1);
        const qid: VU = @splat(@as(u32, @bitCast(id)));

        var path_n: [MAXH]u32 = undefined;
        var path_i: [MAXH]u32 = undefined;
        var masks: [MAXH]u32 = undefined;
        var depth: usize = 0;
        var cur = self.root;
        var leaf_i: u32 = undefined;

        // Depth-first search of the subtrees whose rectangles contain the
        // query rectangle.
        outer: while (true) {
            const n = &nodes[cur];
            const X0: V = n.x0;
            const Y0: V = n.y0;
            const X1: V = n.x1;
            const Y1: V = n.y1;
            if (n.level == 0) {
                const R: VU = n.ref;
                const m = bits16(band(band(X0 == qx0, Y0 == qy0), band(band(X1 == qx1, Y1 == qy1), R == qid)));
                if (m != 0) {
                    leaf_i = @ctz(m);
                    break :outer;
                }
            } else {
                path_n[depth] = cur;
                masks[depth] = bits16(band(band(X0 <= qx0, Y0 <= qy0), band(X1 >= qx1, Y1 >= qy1)));
                depth += 1;
            }
            while (true) {
                if (depth == 0) return false;
                const d = depth - 1;
                const mk = masks[d];
                if (mk != 0) {
                    const i: u32 = @ctz(mk);
                    masks[d] = mk & (mk - 1);
                    path_i[d] = i;
                    cur = nodes[path_n[d]].ref[i];
                    break;
                }
                depth -= 1;
            }
        }

        nodes[cur].removeAt(leaf_i);
        self.size -= 1;

        // Condense the tree.
        var orphans: [MAXH * M]Orphan = undefined;
        var no: usize = 0;
        var child = cur;
        var d = depth;
        while (d > 0) {
            d -= 1;
            const p = &nodes[path_n[d]];
            const pi = path_i[d];
            const c = &nodes[child];
            if (c.count < MIN_FILL) {
                var k: u32 = 0;
                while (k < c.count) : (k += 1) {
                    orphans[no] = .{ .r = c.getRect(k), .ref = c.ref[k], .level = c.level };
                    no += 1;
                }
                p.removeAt(pi);
                self.freeNode(child);
            } else {
                const b = c.bbox();
                if (b.x0 == p.x0[pi] and b.y0 == p.y0[pi] and b.x1 == p.x1[pi] and b.y1 == p.y1[pi]) break;
                p.setRect(pi, b);
            }
            child = path_n[d];
        }

        // Reinsert set-aside entries at their levels (highest first).
        var k = no;
        while (k > 0) {
            k -= 1;
            const o = orphans[k];
            try self.insertAt(o.r, o.ref, o.level);
        }

        // Shorten the tree while the root is internal with one child.
        while (true) {
            const rn = &self.nodes[self.root];
            if (rn.level == 0 or rn.count != 1) break;
            const old = self.root;
            self.root = rn.ref[0];
            self.freeNode(old);
        }
        return true;
    }

    // ------------------------------------------------------------ search

    pub fn search(self: *const RTree, x0: i32, y0: i32, x1: i32, y1: i32, out_ids: []i32) usize {
        if (self.size == 0) return 0;
        const nodes = self.nodes.ptr;
        const qx0: V = @splat(x0);
        const qy0: V = @splat(y0);
        const qx1: V = @splat(x1);
        const qy1: V = @splat(y1);
        const cap = out_ids.len;
        const out = out_ids.ptr;
        var total: usize = 0;

        var stack: [16 * MAXH]u32 = undefined;
        stack[0] = self.root;
        var sp: usize = 1;
        while (sp > 0) {
            sp -= 1;
            const n = &nodes[stack[sp]];
            const X0: V = n.x0;
            const Y0: V = n.y0;
            const X1: V = n.x1;
            const Y1: V = n.y1;
            var m = bits16(band(band(X0 <= qx1, qx0 <= X1), band(Y0 <= qy1, qy0 <= Y1)));
            if (n.level == 0) {
                if (total + 16 <= cap) {
                    while (m != 0) {
                        const i = @ctz(m);
                        m &= m - 1;
                        out[total] = @bitCast(n.ref[i]);
                        total += 1;
                    }
                } else {
                    while (m != 0) {
                        const i = @ctz(m);
                        m &= m - 1;
                        if (total < cap) out[total] = @bitCast(n.ref[i]);
                        total += 1;
                    }
                }
            } else {
                while (m != 0) {
                    const i = @ctz(m);
                    m &= m - 1;
                    const c = n.ref[i];
                    const p: [*]const u8 = @ptrCast(&nodes[c]);
                    @prefetch(p, .{});
                    @prefetch(p + 128, .{});
                    @prefetch(p + 256, .{});
                    stack[sp] = c;
                    sp += 1;
                }
            }
        }
        return total;
    }

    // ------------------------------------------------------------ nearest

    fn heapPush(self: *RTree, hn: *usize, item: HeapItem) Allocator.Error!void {
        if (hn.* == self.heap.len) {
            self.heap = try self.allocator.realloc(self.heap, @max(self.heap.len * 2, 256));
        }
        const h = self.heap.ptr;
        var i = hn.*;
        hn.* += 1;
        while (i > 0) {
            const parent = (i - 1) >> 1;
            if (h[parent].d <= item.d) break;
            h[i] = h[parent];
            i = parent;
        }
        h[i] = item;
    }

    inline fn heapPop(self: *RTree, hn: *usize) void {
        const h = self.heap.ptr;
        const n = hn.* - 1;
        hn.* = n;
        if (n == 0) return;
        const item = h[n];
        var i: usize = 0;
        while (true) {
            var c = 2 * i + 1;
            if (c >= n) break;
            if (c + 1 < n and h[c + 1].d < h[c].d) c += 1;
            if (item.d <= h[c].d) break;
            h[i] = h[c];
            i = c;
        }
        h[i] = item;
    }

    pub fn nearest(self: *RTree, x: i32, y: i32, k: usize, out_ids: []i32) Allocator.Error!usize {
        if (k == 0 or self.size == 0) return 0;
        const kk = @min(k, self.size);
        if (self.res_d.len < kk) {
            const cap = @max(kk, 32);
            self.res_d = try self.allocator.realloc(self.res_d, cap);
            self.res_id = try self.allocator.realloc(self.res_id, cap);
        }
        const rd = self.res_d.ptr;
        const rid = self.res_id.ptr;
        var rc: usize = 0;
        var worst: i64 = I64MAX;

        const px: V = @splat(x);
        const py: V = @splat(y);
        const zero: V = @splat(0);
        var hn: usize = 0;
        var cur = self.root;
        while (true) {
            const n = &self.nodes[cur];
            const X0: V = n.x0;
            const Y0: V = n.y0;
            const X1: V = n.x1;
            const Y1: V = n.y1;
            const dx = widen(@max(@max(X0 - px, px - X1), zero));
            const dy = widen(@max(@max(Y0 - py, py - Y1), zero));
            const dv = dx * dx + dy * dy;
            const valid = LANE < @as(VU, @splat(n.count));
            var m = bits16(band(valid, dv <= @as(VL, @splat(worst))));
            const da: [16]i64 = dv;
            if (n.level == 0) {
                while (m != 0) {
                    const i = @ctz(m);
                    m &= m - 1;
                    const dd = da[i];
                    const id: i32 = @bitCast(n.ref[i]);
                    var j: usize = undefined;
                    if (rc < kk) {
                        j = rc;
                        rc += 1;
                    } else {
                        if (dd > worst or (dd == worst and id > rid[kk - 1])) continue;
                        j = kk - 1;
                    }
                    while (j > 0 and (rd[j - 1] > dd or (rd[j - 1] == dd and rid[j - 1] > id))) : (j -= 1) {
                        rd[j] = rd[j - 1];
                        rid[j] = rid[j - 1];
                    }
                    rd[j] = dd;
                    rid[j] = id;
                    if (rc == kk) worst = rd[kk - 1];
                }
            } else {
                while (m != 0) {
                    const i = @ctz(m);
                    m &= m - 1;
                    try self.heapPush(&hn, .{ .d = da[i], .n = n.ref[i] });
                }
            }
            if (hn == 0) break;
            const top = self.heap[0];
            if (top.d > worst) break;
            self.heapPop(&hn);
            cur = top.n;
            const p: [*]const u8 = @ptrCast(&self.nodes[cur]);
            @prefetch(p + 128, .{});
            @prefetch(p + 256, .{});
        }
        @memcpy(out_ids[0..rc], rid[0..rc]);
        return rc;
    }

    // ------------------------------------------------------------ info

    pub fn len(self: *const RTree) usize {
        return self.size;
    }

    pub fn height(self: *const RTree) usize {
        if (self.size == 0) return 0;
        return self.nodes[self.root].level + 1;
    }

    pub fn nodeCount(self: *const RTree) usize {
        if (self.size == 0) return 0;
        var stack: [16 * MAXH]u32 = undefined;
        stack[0] = self.root;
        var sp: usize = 1;
        var count: usize = 0;
        while (sp > 0) {
            sp -= 1;
            const n = &self.nodes[stack[sp]];
            count += 1;
            if (n.level > 0) {
                for (n.ref[0..n.count]) |c| {
                    stack[sp] = c;
                    sp += 1;
                }
            }
        }
        return count;
    }
};
