Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 37 additions & 2 deletions docs/bvh.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,8 +123,42 @@ So the "`u16` table at header `0x130`" of section 4 is not a table: it is these
(a root pointer, the element offset and the parent offset, the last usually negative; hence "often monotonic"). With `offsetToPrimRemap` 0 everywhere there is no
primitive remap table either, and the element region allocates 64 bytes per element, `numElements` of them, padded
to 128 bytes (a stride, not a record layout: section 4a describes the packed arrays inside it).
**Open:** where the parent array starts and how big it is. Neither `offsetToParents + 4 * unit` against the header end
or `offsetToElements`, nor a size of `4 *` the node or element count, holds on every stream.
**The parent table (BUILD-1390).** The traversal shader finds the entry for the 64-byte unit `u` at
`offsetToParents + 4 * (u - offsetToElements / 64)` (`XboxBvh4Node_GetParentTableOffset` and
`XboxBvh4Node_LoadParentPointer`, L3254-L3275 of the `.hlsli` above, 32-bit arithmetic). It only looks up the
parent of a box node: the node it climbs from is the last non-triangle node (L6212), asserted to be above `TRI3`
(L6265). The table is laid out for the box nodes only:

* *Start:* `offsetToParents = 0x40 - (((offsetToNodes - offsetToElements) / 16) & ~127)`. The element units'
entries take `(offsetToNodes - offsetToElements) / 16` bytes; their whole 128-byte blocks sit below the header
end, which is why the word is negative from 32 element units up. The first box node's entry is then at
`offsetToParents + (offsetToNodes - offsetToElements) / 16`, in `[0x40, 0xc0)`.
* *Extent:* one entry per box unit (a BOX16 node takes one, a BOX32 node two) from the first box entry, and
`offsetToElements` is the end of the last one rounded up to 128 bytes. The bytes between the header end and the
first box entry, and after the last one, are the only slack.
* *Not shipped:* the bytes from `0x40` to `offsetToElements` are all zero; rehydration writes the entries
(`tools/bvh_rehydrate.py`, which matches the library byte for byte on 8 samples, §4a).
* *The units the header counts:* `totalSizeIn64BNodes + 1` is the end of the last box group in 64-byte units plus
`ceil((4 + 8 * levels) / 64)` units for the level table (§4a). The level table's units have no entry, so the end
`offsetToParents + 4 * (totalSizeIn64BNodes + 1 - offsetToElements / 64)` taken from the header alone, rounded up
to 128, lands on `offsetToElements` on only 259,456 of the 272,858 box-rooted streams.

Measured over every stream of both packs, with a scratch probe over the `tools/bvh_index.py` scan and then with
`tools/bvh_packing_check.py`, which now checks all three (§4a): 272,874 streams (271,627 complete and 10 joined in
`core_bvh4.rpf`, 1,237 in `shared_minigame000_bvh4.rpf`). Counts only.

| rule | holds on |
|---|---|
| `[0x40, offsetToElements)` is zero | 272,874 / 272,874 |
| `offsetToParents` from the start rule | 272,874 / 272,874 |
| `offsetToElements` from the extent rule (box root) | 272,858 / 272,858 |
| `totalSizeIn64BNodes + 1` = box groups' end plus the level table's units (box root) | 272,858 / 272,858 |
| leaf root (`numElements` 1): `offsetToElements` `0x80`, `offsetToNodes` `0x100`, `offsetToParents` `0x40`, `totalSizeIn64BNodes` 3 | 16 / 16 |
| no slack after the last box entry | 8,973 (1 to 31 entries on the rest) |

**Hypothesis:** the console builder sizes the table from the box nodes it wrote and aligns it the same way for
updatable or top-level structures. Every measured stream has `flags` `0x81020006`, a BLAS without the updatable
bit `0x00040000`, so where an updatable structure keeps its leaves' entries is not measured.

The `flags` word has version `6` in its low 16 bits. It also sets `0x80000000` (bottom level), `0x00020000`
(offline) and `0x01000000` (dehydrated). It does not set `0x00010000` (compressed). The sample is therefore a
Expand Down Expand Up @@ -506,6 +540,7 @@ bytes form exactly one tree:
* a box pointer names a node of its own width on a lower level;
* a TRI0 pointer names a leaf slot `offsetToElements + 64 * k` with `k < numElements`;
* nothing points to the root, and every other node and every leaf has exactly one parent;
* the parent table is not shipped and its start and extent follow the element and box regions (§3.1);
* every vertex-order byte is a permutation;
* every stored override lies inside `sceneBounds` in the leaf frame.

Expand Down
56 changes: 46 additions & 10 deletions tests/test_bvh_packing_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
import bvh_rehydrate as R # noqa: E402

FLAGS = 0x80000000 | R.FLAG_DEHYDRATED | 0x00020006
ELEMENTS, NODES = 0x100, 0x200
ELEMENTS, NODES = 0x80, 0x180 # the console layout for four leaves and three BOX16 units (§3.1)
BOUNDS = (0.0, 0.0, 0.0, 4.0, 2.0, 1.0)
GOOD_ORDER = 0x09

Expand Down Expand Up @@ -49,21 +49,23 @@ def group(nodes, wide=False):
return body + struct.pack("<%dH" % len(values), *(R.float_to_half(v) for v in values))


def build(level0=None, level1=None, orders=None, n_leaves=4, flags=FLAGS, root=None, total=0x300, table=None):
def build(level0=None, level1=None, orders=None, n_leaves=4, flags=FLAGS, root=None, total=0x300, table=None,
elements=ELEMENTS, nodes=NODES, parents=0x40):
"""Four leaves; level 0: two BOX16 nodes over leaves (0, 1) and (2, 3); level 1: the BOX16 root over both."""
a, b = ptr(NODES, R.BOX16), ptr(NODES + 64, R.BOX16)
root = ptr(NODES + 128, R.BOX16) if root is None else root
level0 = [([leaf(0), leaf(1)], {}), ([leaf(2), leaf(3)], {})] if level0 is None else level0
a, b = ptr(nodes, R.BOX16), ptr(nodes + 64, R.BOX16)
root = ptr(nodes + 128, R.BOX16) if root is None else root
lf = [ptr(elements + 64 * i, R.TRI0) for i in range(4)]
level0 = [([lf[0], lf[1]], {}), ([lf[2], lf[3]], {})] if level0 is None else level0
level1 = [([a, b], {})] if level1 is None else level1
src = bytearray(total)
src[0:64] = struct.pack("<4I6f6I", flags, total // 64 - 1, 0, n_leaves, *BOUNDS, NODES, 0, root, ELEMENTS,
0x40, R.NO_TRANSFORM)
src[0:64] = struct.pack("<4I6f6I", flags, total // 64 - 1, 0, n_leaves, *BOUNDS, nodes, 0, root, elements,
parents, R.NO_TRANSFORM)
orders = [GOOD_ORDER] * n_leaves if orders is None else orders
chunk = bytes(3 * n_leaves) + bytes([1] * n_leaves) + bytes(3 * n_leaves) + b"\xff" * (3 * n_leaves) + bytes(orders)
src[ELEMENTS:ELEMENTS + len(chunk)] = chunk
src[elements:elements + len(chunk)] = chunk
g0, g1 = group(level0), group(level1)
src[NODES:NODES + len(g0)] = g0
src[NODES + 128:NODES + 128 + len(g1)] = g1
src[nodes:nodes + len(g0)] = g0
src[nodes + 128:nodes + 128 + len(g1)] = g1
table = [(0, 128), (128, 192)] if table is None else table
lv = b"".join(struct.pack("<2I", x, y) for x, y in table) + struct.pack("<I", len(table))
src[total - len(lv):] = lv
Expand Down Expand Up @@ -102,6 +104,28 @@ def test_root_union_equal_to_bounds(self):
self.assertEqual((res.stats["root_components_stored"], res.stats["root_components_equal"]), (1, 1))


class TestParentTable(unittest.TestCase):
def test_negative_offset(self):
# synthetic: 0x4080 bytes of elements -> 0x408 bytes of leaf entries, 0x400 of them below the header end
want, first = C.parent_table(0x1000, 0x5080)
self.assertEqual(want, 0xFFFFFC40)
self.assertEqual(first, 0x48)

def test_small_element_region_keeps_0x40(self):
# fewer than 32 element units: no whole 128-byte block of leaf entries to drop
self.assertEqual(C.parent_table(0x80, 0x100), (0x40, 0x48))
self.assertEqual(C.parent_table(0x80, 0x800), (0x40, 0xB8))
# 32 element units fill one 128-byte block, which goes below the header end
self.assertEqual(C.parent_table(0x80, 0x880), (0xFFFFFFC0, 0x40))
self.assertEqual(C.parent_table(0x80, 0x900), (0xFFFFFFC0, 0x48))

def test_elements_after_parents(self):
self.assertEqual(C.elements_after_parents(0x50, 3), 0x80)
self.assertEqual(C.elements_after_parents(0x40, 16), 0x80)
self.assertEqual(C.elements_after_parents(0x40, 17), 0x100)
self.assertEqual(C.elements_after_parents(0x48, 0), 0x80)


class TestBroken(unittest.TestCase):
def test_not_dehydrated(self):
self.assertEqual(fails(build(flags=FLAGS & ~R.FLAG_DEHYDRATED)), {"not_dehydrated": 1})
Expand Down Expand Up @@ -198,6 +222,18 @@ def test_group_overflow(self):
def test_root_not_a_node(self):
self.assertEqual(fails(build(root=ptr(NODES + 192, R.BOX16))), {"root_not_a_node": 1})

def test_parent_offset(self):
self.assertEqual(fails(build(parents=0x80)), {"parent_offset": 1})

def test_parent_area_nonzero(self):
src = bytearray(build())
src[0x60] = 1
self.assertEqual(fails(bytes(src)), {"parent_area_nonzero": 1})

def test_parent_extent(self):
# a whole unused 128-byte block between the three box units' entries and the elements
self.assertEqual(fails(build(elements=0x100, nodes=0x200)), {"parent_extent": 1})

def test_root_leaf(self):
src = build(n_leaves=1, root=leaf(0), level0=[], level1=[], table=[])
res = C.check_stream(src)
Expand Down
34 changes: 34 additions & 0 deletions tools/bvh_packing_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
stream passes when its bytes form exactly one tree under that reading:

* header: the dehydrated flag is set, and the leaf records and the box groups fit in the declared structure;
* parent table (not shipped): the bytes from the header end to `offsetToElements` are zero; `offsetToParents` is
`0x40 - (((offsetToNodes - offsetToElements) / 16) & ~127)`, and with a box root `offsetToElements` is the end of
one entry per box unit (BOX16 one, BOX32 two) from the first box node's entry, rounded up to 128;
* level table: the last word is the level count; before it, the level ends are in order, a multiple of the node
size apart, and end before the table;
* groups: every group's node words, child pointers and stored values fit in the bytes its nodes occupy;
Expand Down Expand Up @@ -70,6 +73,24 @@ def _valid_order_table():
VALID_ORDER = _valid_order_table()


def parent_table(offset_to_elements, offset_to_nodes):
"""(offsetToParents, first box entry) the console builder writes (docs/bvh.md §3.1).

The entry for unit u is at offsetToParents + 4 * (u - offsetToElements / 64). The element units' entries take
4 bytes each, (offsetToNodes - offsetToElements) / 16 in all; their whole 128-byte blocks fall below the header
end, so the first box node's entry lands in [0x40, 0xc0). The first value is the u32 the header holds, the
second a signed offset from the header.
"""
leaf_bytes = (offset_to_nodes - offset_to_elements) >> 4
start = 0x40 - (leaf_bytes & ~127)
return start & R.M32, start + leaf_bytes


def elements_after_parents(first_box_entry, box_units):
"""offsetToElements: the end of the box nodes' entries (one per 64-byte box unit) rounded up to 128."""
return (first_box_entry + 4 * box_units + 127) & ~127


def mapped_bounds(hdr):
"""sceneBounds mapped through the leaf frame, as tools/bvh_geometry_check.py maps it: (lo xyz, hi xyz)."""
frame = R.LeafFrame(hdr)
Expand Down Expand Up @@ -135,6 +156,16 @@ def check_stream(buf, at=0):
return res
if n and elements + 64 * n > nodes:
res.fail("leaves_overlap_nodes")
# Parent table (docs/bvh.md §3.1): not shipped, so the bytes from the header end to the elements are zero, and
# offsetToParents follows from the element region alone.
first_entry = None
if nodes >= elements:
want, first_entry = parent_table(elements, nodes)
if hdr.offset_to_parents != want:
res.fail("parent_offset")
area = src[64:elements]
if area.count(0) != len(area):
res.fail("parent_area_nonzero")
remaining, chunk = n, 0
while remaining > 0:
c = min(R.LEAVES_PER_CHUNK, remaining)
Expand Down Expand Up @@ -187,6 +218,9 @@ def check_stream(buf, at=0):
runs.append((level, wide, first, count, nid))
nid += count
st["box_nodes"] += nid
box_units = sum(count * (2 if wide else 1) for _, wide, _, count, _ in runs)
if first_entry is not None and elements != elements_after_parents(first_entry, box_units):
res.fail("parent_extent")
if hdr.root not in node_of:
res.fail("root_not_a_node")
return res
Expand Down
Loading