diff --git a/docs/experiments/startup-gfx2hlsl-bvh-box32.md b/docs/experiments/startup-gfx2hlsl-bvh-box32.md index f1430af9fe..21acc67961 100644 --- a/docs/experiments/startup-gfx2hlsl-bvh-box32.md +++ b/docs/experiments/startup-gfx2hlsl-bvh-box32.md @@ -1,11 +1,11 @@ -# First `image_bvh_intersect_ray` slice: FP32 box nodes +# First `image_bvh_intersect_ray` slice: FP32 and binary16 box nodes `tools/startup/gfx2hlsl.py` now lowers the 32-bit `image_bvh_intersect_ray` (RDNA 2 MIMG opcode 230) for -one node form: the 128-byte FP32 box node, kind 5. The result is four child pointers, with `0xffffffff` for a -disabled child or a missed box. The helper performs the four slab tests, clips against `ray_extent`, and sorts -hits by entry distance only when bit 31 of descriptor DWORD 1 is set. With sorting disabled each -result remains in its original child slot, including holes. Sorted misses use a positive-infinity -key so that a valid hit at `FLT_MAX` still precedes them. +the two box-node forms: the 128-byte FP32 node (kind 5) and the 64-byte binary16 node (kind 4). The result is +four child pointers, with `0xffffffff` for a disabled child or a missed box. The helper performs the four slab +tests, clips against `ray_extent`, and sorts hits by entry distance only when bit 31 of descriptor DWORD 1 is +set. With sorting disabled each result remains in its original child slot, including holes. Sorted misses use +a positive-infinity key so that a valid hit at `FLT_MAX` still precedes them. The node layout is the one in Mesa 25.1.0 `src/amd/vulkan/bvh/bvh.h` (MIT): `children[4]` at bytes 0..15, `coords[4][2][3]` at 16..111, and four reserved words at 112..127. The slab test follows Mesa @@ -15,15 +15,20 @@ stages that sort the four children. A child word of `0xffffffff` is a miss even The BVH T# fields are RDNA 2 ISA Table 49: base 39:0 (encoded in 256-byte units), reserved 54:40, box growing 62:55, box sorting 63, size 105:64, triangle return mode 120, big page 123 and type 8 at 127:124. +The binary16 node has the same four child words at bytes 0..15 and four boxes of six binary16 values at +16..63. `f16tof32` widens each bound exactly before the same slab test. The inactive-box marker is still a NaN +in `min.x`. + ## Accepted slice - compute stage only; - `image_bvh_intersect_ray v[4], v[11], s[4]` with the packed address form (the disassembler prints `v[16:31]` for the eleven consumed dwords); - a constant inline T# built by four SGPR constants, type 8, nonzero encoded base, box growing zero, - size at least one 64-byte unit and below 4 GiB, and the node inside that size; -- a constant node pointer whose low three bits are 5, 128-byte aligned and inside the 4 GiB relative - address window; the entire node must fit within the 48-bit absolute address space; + size field (a count minus one in 64-byte units) whose decoded extent covers the node (one unit + for binary16, two for FP32; `size=0` is a one-unit span) and below 4 GiB; +- a constant node pointer whose low three bits are 4 (64-byte aligned) or 5 (128-byte aligned) and inside the + same 4 GiB relative address window; the entire node must fit within the 48-bit absolute address space; - either value of the sort bit. The manifest names the node allocation with `srv bvh base 0x size 0x`, using the decoded @@ -35,7 +40,7 @@ of this change. ## Refused by name -Triangle nodes (kind 0), 16-bit box nodes (kind 4), every other node kind, `image_bvh64_intersect_ray`, A16, +Triangle nodes (kinds 0..3), every other node kind, `image_bvh64_intersect_ray`, A16, non-sequential addresses, a pixel or vertex stage, a node pointer that is not a straight-line constant, a T# loaded at run time, a type other than 8, nonzero box growing, an absolute (zero) base, a size that does not cover the node, size bits above 4 GiB, a node address that wraps the 48-bit address space, @@ -51,25 +56,31 @@ python3 -B tests/startup_gfx2hlsl_bvh_check.py The translator check compares synthetic nodes and rays against the independently existing binary32 reference in `tests/gfx1030_bvh_box/bvh_model.py`. It checks the sort-bit negative control (word 0 -changes from `0x1d` to `0x25`), the three-hit sort-disabled result with its second slot still invalid -(`0x25, 0xffffffff, 0x2d, 0x35`), and the finite `FLT_MAX` hit with infinite extent. It separately checks -the translation, full descriptor literals, and manifest for `0x1000`, `0x1008`, and a base using -the high byte of DWORD 1. The top-of-address-space witness checks a valid node ending at the -48-bit boundary and refuses a node whose start wraps to zero in the independent model, before -binding a resource or emitting a helper. The check also covers the named refusals and the actual -emitted helper's mutation sites. It compiles the translated compute shader with DXC when available; -without DXC it prints `dxc compile: skip` and does not count that compilation as a pass. +changes from `0x1d` to `0x25`), the three-hit FP32 sort-disabled result with its second slot still invalid +(`0x25, 0xffffffff, 0x2d, 0x35`), and the finite `FLT_MAX` hit with infinite extent. The binary16 fixtures +are packed as `binary16` bytes and read back through the same independent model, including a bound at 1.1 +that rounds to 1.099609375 so a ray extent between the two values proves `f16tof32` is used. It separately +checks the translation, full descriptor literals, and manifest for `0x1000`, `0x1008`, and a base using +the high byte of DWORD 1, for both node kinds. The top-of-address-space witness checks a valid node ending at +the 48-bit boundary and refuses a node whose start wraps to zero in the independent model, before binding a +resource or emitting a helper. The check also covers the named refusals and the actual emitted helpers' +mutation sites. It compiles the translated compute shader with DXC when available; without DXC it prints +`dxc compile: skip` and does not count that compilation as a pass. ```text python -B tests/startup_gfx2hlsl_bvh_check.py dispatch warp ``` -The dispatch mode compiles the same emitted helper with a `RWByteAddressBuffer` in place of the -bound `ByteAddressBuffer`, writes synthetic nodes and rays, and compares the four result DWORDs -for every case. Its negative controls remove miss filling, compact the unsorted slots, substitute -`FLT_MAX` for the infinite miss key, reintroduce the erroneous low-byte alignment check, and ignore -the high byte of the encoded base in the zero-base check. Each mutant must change its designated -witness result. This is a reproduction procedure, not a new GPU execution result. +The dispatch mode compiles both helpers with a `RWByteAddressBuffer` in place of the bound +`ByteAddressBuffer`, writes four FP32 nodes, four binary16 nodes and twenty-one rays, and compares the +four result DWORDs for every case (1232-byte readback). All eight sorted FP32 cases, three unsorted FP32 +cases, eight sorted binary16 cases (including the rounded bound and both encoded bases) and two unsorted +binary16 cases pass on a Microsoft Basic Render Driver (`1414:008c`, driver `10.0.26100.10068`) and on an +AMD Radeon RX 9060 XT (`1002:7590`, driver `32.0.32029.2010`), in both the dev and release presets. Its +negative controls remove miss filling, compact the unsorted slots, substitute `FLT_MAX` for the infinite +miss key, reintroduce the erroneous low-byte alignment check, and ignore the high byte of the encoded base +in the zero-base check. Each mutant must change its designated witness result; the compact and box16 +miss-fill controls use binary16 witnesses. This is a translator slice. It does not execute the native gfx1030 probe, does not establish the host binding of the node allocation on a D3D12 device, and does not establish any title behavior. diff --git a/tests/startup_gfx2hlsl_bvh_check.py b/tests/startup_gfx2hlsl_bvh_check.py index 531caecccc..9d04c1ef2d 100644 --- a/tests/startup_gfx2hlsl_bvh_check.py +++ b/tests/startup_gfx2hlsl_bvh_check.py @@ -1,11 +1,11 @@ -"""image_bvh_intersect_ray: the FP32 box-node (kind 5) translation slice. +"""image_bvh_intersect_ray: the FP32 and binary16 box-node translation slice. The instruction is RDNA 2 MIMG opcode 230. This check covers the translator path and the box model only: a constant inline BVH T#[12:15], an 11-dword packed address, a constant -node base whose low three bits are 5, and the four child results. Triangle nodes, 16-bit -box nodes, the 64-bit form, A16, NSA and every dynamic descriptor or node base are refused -by name before any HLSL is emitted. The independent CPU box reference is -tests/gfx1030_bvh_box/bvh_model.py; the Windows dispatch exercises the actual emitted helper. +node base whose low three bits are 4 (binary16) or 5 (FP32), and the four child results. +Triangle nodes, the 64-bit form, A16, NSA and every dynamic descriptor or node base are +refused by name before any HLSL is emitted. The independent CPU box reference is +tests/gfx1030_bvh_box/bvh_model.py; the Windows dispatch exercises both emitted helpers. """ import math import os @@ -66,9 +66,39 @@ def box(child, depth, x=-8): "encoded_base_low_bits": (0x1008, 0), "encoded_base_high_byte": (0, 0x81), } -RESULT_OFFSET = max(NODES) + 128 +# The independent model reads the binary16 node in 64-byte units. The FLT_MAX +# fixture has no binary16 encoding, so it has no half copy. +HALF_OFFSETS = {0: 640, 256: 704, 384: 768} +HALF_ROUND_OFFSET = 832 +RESULT_OFFSET = 896 RESULT_WORD = RESULT_OFFSET // 4 -BUFFER_SIZE = RESULT_OFFSET + 16 * (len(RAYS) + len(UNSORTED_RAYS)) + + +def half(value): + return struct.unpack("> 3) | 5, + node_bytes(), B.descriptor(sort=sort_boxes), (offset >> 3) | kind, extent=extent, origin=origin, direction=direction, inverse=tuple(1.0 / c for c in direction))) @@ -123,6 +157,53 @@ def model(nodes, extent, origin, direction, sort_boxes): return tuple(item[0] for item in items) +HALF_RAYS = tuple( + ("box16_" + name, HALF_OFFSETS[offset], extent, origin, direction, + reference(HALF_OFFSETS[offset], extent, origin, direction, True, 4)) + for name, offset, extent, origin, direction, _expected in RAYS + if name not in DESCRIPTOR_BASES and offset in HALF_OFFSETS +) + ( + ("box16_rounded_bound", HALF_ROUND_OFFSET, 1.0998, (0.0, 0.0, 0.0), (1.0, 1e-6, 1e-6), + (0x25, INVALID, INVALID, INVALID)), + ("box16_encoded_base_low_bits", HALF_OFFSETS[0], 19.0, ORIGIN, FORWARD, + reference(HALF_OFFSETS[0], 19.0, ORIGIN, FORWARD, True, 4)), + ("box16_encoded_base_high_byte", HALF_OFFSETS[256], 19.0, ORIGIN, FORWARD, + reference(HALF_OFFSETS[256], 19.0, ORIGIN, FORWARD, True, 4)), +) +HALF_UNSORTED_RAYS = tuple( + ("box16_" + name, HALF_OFFSETS[offset], extent, origin, direction, + reference(HALF_OFFSETS[offset], extent, origin, direction, False, 4)) + for name, offset, extent, origin, direction, _expected in UNSORTED_RAYS + if offset in HALF_OFFSETS +) + + +def dispatch_cases(): + cases = [] + for name, offset, extent, origin, direction, expected in RAYS: + base0, base1 = DESCRIPTOR_BASES.get(name, (0x1000, 0)) + cases.append(dict(name=name, helper="x2w_bvh_intersect_box32", pointer=(offset >> 3) | 5, + word0=base0, word1=base1 | SORT_ENABLE, word2=0x0b, + extent=extent, origin=origin, direction=direction, expected=expected)) + for name, offset, extent, origin, direction, expected in UNSORTED_RAYS: + cases.append(dict(name=name, helper="x2w_bvh_intersect_box32", pointer=(offset >> 3) | 5, + word0=0x1000, word1=0, word2=0x0b, + extent=extent, origin=origin, direction=direction, expected=expected)) + for name, offset, extent, origin, direction, expected in HALF_RAYS: + base0, base1 = HALF_DESCRIPTOR_BASES.get(name, (0x1000, 0)) + cases.append(dict(name=name, helper="x2w_bvh_intersect_box16", pointer=(offset >> 3) | 4, + word0=base0, word1=base1 | SORT_ENABLE, word2=0x40, + extent=extent, origin=origin, direction=direction, expected=expected)) + for name, offset, extent, origin, direction, expected in HALF_UNSORTED_RAYS: + cases.append(dict(name=name, helper="x2w_bvh_intersect_box16", pointer=(offset >> 3) | 4, + word0=0x1000, word1=0, word2=0x40, + extent=extent, origin=origin, direction=direction, expected=expected)) + return cases + + +BUFFER_SIZE = RESULT_OFFSET + 16 * (len(RAYS) + len(UNSORTED_RAYS) + len(HALF_RAYS) + len(HALF_UNSORTED_RAYS)) + + def translate_program(*, node=0x05, sort_boxes=True, word0=0x1000, word1=None, word2=0x0b, word3=RESOURCE_TYPE, loaded_descriptor=False, modifier="", opcode="image_bvh_intersect_ray", constant_node=True, stage_kind="cs"): @@ -200,13 +281,38 @@ def controls(): check("all-miss result is four 0xffffffff words", reference(0, 2.0, ORIGIN, FORWARD, True) == (INVALID,) * 4, "") + bad = None + for name, offset, extent, origin, direction, expected in HALF_RAYS: + actual = model(HALF_NODE_BY_OFFSET[offset], extent, origin, direction, True) + if actual != expected: + bad = (name, actual, expected) + break + check("transcribed box16 model matches the half-packed reference", bad is None, str(bad)) + + bad = None + for name, offset, extent, origin, direction, expected in HALF_UNSORTED_RAYS: + actual = model(HALF_NODE_BY_OFFSET[offset], extent, origin, direction, False) + if actual != expected: + bad = (name, actual, expected) + break + check("transcribed box16 model keeps child order when unsorted", bad is None, str(bad)) + check("binary16 bound rounds below the ray extent", + reference(HALF_ROUND_OFFSET, 1.0998, (0.0, 0.0, 0.0), (1.0, 1e-6, 1e-6), True, 4) + == (0x25, INVALID, INVALID, INVALID), "") + fp32_round = model(((0x25, (1.1, -2.0, -2.0), (2.0, 2.0, 2.0)), + (INVALID, (-2.0, -2.0, -2.0), (2.0, 2.0, 2.0)), + (INVALID, (-2.0, -2.0, -2.0), (2.0, 2.0, 2.0)), + (INVALID, (-2.0, -2.0, -2.0), (2.0, 2.0, 2.0))), + 1.0998, (0.0, 0.0, 0.0), (1.0, 1e-6, 1e-6), True) + check("binary32 bound at 1.1 misses the same extent", fp32_round[0] == INVALID, str(fp32_round)) + pipe, hlsl, refusals = translate_program() check("constant box32 program translates", pipe is not None and not refusals, str(refusals)) if pipe is not None: manifest = pipe.manifest() check("manifest names the node allocation", "srv 0 bvh base 0x100000 size 0xb" in manifest, manifest) check("HLSL declares the node buffer", "ByteAddressBuffer r0 : register(t0);" in hlsl, "") - check("HLSL contains the four-result helper", + check("HLSL contains the box32 helper", "uint4 x2w_bvh_intersect_box32" in hlsl and "x2w_bvh_box32_slot" in hlsl, "") check("the call carries the sort-enabled T# word and four child results", "0x80000000u" in hlsl and all("v%d = bt" % reg in hlsl for reg in range(32, 36)), @@ -217,10 +323,29 @@ def controls(): and "s12" not in call_line and "s13" not in call_line, call_line) pipe, hlsl, refusals = translate_program(sort_boxes=False) - check("sort-disabled program translates", pipe is not None and not refusals, str(refusals)) + check("sort-disabled box32 program translates", pipe is not None and not refusals, str(refusals)) if pipe is not None: call = next((line for line in hlsl.splitlines() if "x2w_bvh_intersect_box32(r0" in line), "") - check("sort-disabled call uses a zero sort word", + check("sort-disabled box32 call uses a zero sort word", + "0x00001000u, 0x00000000u, 0x0000000bu, 0x80000000u" in call, call) + + pipe, hlsl, refusals = translate_program(node=0x04) + check("constant box16 program translates", pipe is not None and not refusals, str(refusals)) + if pipe is not None: + check("HLSL contains the box16 helper", + "uint4 x2w_bvh_intersect_box16" in hlsl and "x2w_bvh_box16_slot" in hlsl + and "f16tof32" in hlsl, "") + call_line = next((line for line in hlsl.splitlines() if "x2w_bvh_intersect_box16(r0" in line), "") + check("box16 call carries the node and four child results", + "0x00000004u" in call_line + and "0x00001000u, 0x80000000u, 0x0000000bu, 0x80000000u" in call_line + and all("v%d = bt" % reg in hlsl for reg in range(32, 36)), call_line) + + pipe, hlsl, refusals = translate_program(node=0x04, sort_boxes=False) + check("sort-disabled box16 program translates", pipe is not None and not refusals, str(refusals)) + if pipe is not None: + call = next((line for line in hlsl.splitlines() if "x2w_bvh_intersect_box16(r0" in line), "") + check("sort-disabled box16 call uses a zero sort word", "0x00001000u, 0x00000000u, 0x0000000bu, 0x80000000u" in call, call) # Independently decode the 40-bit unit field; test the same raw DWORDs in @@ -239,31 +364,67 @@ def controls(): check("manifest uses byte base %#x" % base, "srv 0 bvh base %#x size 0xb" % base in manifest, manifest) check("call preserves all four descriptor DWORDs at %#x" % base, literal_words in call, call) + for units, high, base in ((0x1008, 0, 0x100800), (0, 0x81, 0x810000000000)): + words = (units, high | SORT_ENABLE, 0x0b, RESOURCE_TYPE) + pipe, hlsl, refusals = translate_program(node=0x04, word0=words[0], word1=words[1]) + check("box16 encoded base %#x translates" % base, pipe is not None and not refusals, str(refusals)) + if pipe is not None: + manifest = pipe.manifest() + call = next((line for line in hlsl.splitlines() if "x2w_bvh_intersect_box16(r0" in line), "") + literal_words = ", ".join("0x%08xu" % word for word in words) + check("box16 manifest uses byte base %#x" % base, + "srv 0 bvh base %#x size 0xb" % base in manifest, manifest) + check("box16 call preserves all four descriptor DWORDs at %#x" % base, literal_words in call, call) + # The model wraps the absolute node address at 48 bits. The raw-bound # helper cannot represent that wrap, so the translator must refuse it. words = (0xffffffff, SORT_ENABLE | 0xff, 0x0b, RESOURCE_TYPE) check("public model wraps the node address", B.node_address(words, 0x25) == (5, 0), str(B.node_address(words, 0x25))) pipe, boundary_hlsl, refusals = translate_program(node=0x15, word0=words[0], word1=words[1]) - check("node ending exactly at the 48-bit boundary translates", + check("box32 node ending exactly at the 48-bit boundary translates", pipe is not None and not refusals, str(refusals)) pipe, wrap_hlsl, refusals = translate_program(node=0x25, word0=words[0], word1=words[1]) - check("refuses 48-bit wrap before resource binding", + check("refuses a box32 48-bit wrap before resource binding", refusals == ["image_bvh_intersect_ray node address wraps the 48-bit address space"] and " bvh base " not in pipe.manifest() and "x2w_bvh_intersect_box32" not in wrap_hlsl and "uint4 bt" not in wrap_hlsl, str(refusals)) - - # Portable checks ensure the actual emitted helper and every negative + pipe, boundary_hlsl, refusals = translate_program(node=0x15, word0=words[0], word1=words[1]) + check("box16 node ending exactly at the 48-bit boundary translates", + pipe is not None and not refusals, str(refusals)) + pipe, wrap_hlsl, refusals = translate_program(node=0x54, word0=words[0], word1=words[1]) + check("refuses a box16 48-bit wrap before resource binding", + refusals == ["image_bvh_intersect_ray node address wraps the 48-bit address space"] + and " bvh base " not in pipe.manifest() + and "x2w_bvh_intersect_box16" not in wrap_hlsl and "uint4 bt" not in wrap_hlsl, str(refusals)) + + # Size is a count minus one in 64-byte units. These are exact fits and one unit short. + for node, word2, label in ((0x04, 0, "box16 at offset zero in a one-unit span"), + (0x05, 1, "box32 at offset zero in a two-unit span"), + (0x0c, 1, "box16 in the last unit of a two-unit span")): + pipe, hlsl, refusals = translate_program(node=node, word2=word2) + check("exact-fit %s translates" % label, pipe is not None and not refusals, str(refusals)) + for node, word2, label in ((0x05, 0, "box32 at offset zero in a one-unit span"), + (0x0c, 0, "box16 in the last unit of a one-unit span")): + pipe, hlsl, refusals = translate_program(node=node, word2=word2) + check("too-short %s refuses" % label, + len(refusals) == 1 and "outside descriptor size" in refusals[0], str(refusals)) + pipe, hlsl, refusals = translate_program(node=0x04, word2=0x03ffffff) + check("largest decoded extent translates", pipe is not None and not refusals, str(refusals)) + pipe, hlsl, refusals = translate_program(node=0x04, word2=0x04000000) + check("extent above 4 GiB refuses", len(refusals) == 1 and "above 4 GiB" in refusals[0], str(refusals)) + + # Portable checks ensure the actual emitted helpers and every negative # mutation are present even when a GPU dispatch is unavailable. + pipe, hlsl, refusals = translate_program(node=0x04) helpers = "\n".join(G.BVH_HELPERS) - check("translated shader embeds the dispatch-tested helper", hlsl is not None and helpers in hlsl, "") + check("translated shader embeds both dispatch-tested helpers", pipe is not None and helpers in hlsl, "") for mutation in MUTATIONS: dispatch_hlsl(mutation) # Every refusal must happen before a helper call or a result VGPR is emitted. cases = [ ("triangle node", dict(node=0x00), "triangle node (kind 0)"), - ("16-bit box node", dict(node=0x04), "16-bit box node (kind 4)"), ("unknown node kind", dict(node=0x06), "node kind 6"), ("unaligned node", dict(node=0x0d), "not an aligned 128-byte node"), ("non-constant node", dict(constant_node=False), "non-constant node base"), @@ -274,8 +435,9 @@ def controls(): ("descriptor type", dict(word3=0x60000000), "descriptor type 6 is not 8"), ("box growing", dict(word1=SORT_ENABLE | (2 << 23)), "box growing amount 2"), ("reserved word 1", dict(word1=SORT_ENABLE | 0x100), "reserved word 1"), - ("size zero", dict(word2=0), "does not cover a 128-byte node"), + ("box32 size zero", dict(word2=0), "outside descriptor size"), ("node outside size", dict(node=0x25, word2=3), "outside descriptor size"), + ("box16 node outside size", dict(node=0x54, word2=9), "outside descriptor size"), ("absolute base", dict(word0=0, word1=0), "absolute node base"), ("size high bits", dict(word3=RESOURCE_TYPE | 0x100), "size above 4 GiB"), ] @@ -295,7 +457,8 @@ def controls(): check("refuses %s" % label, ok, str(refusals)) if hlsl is not None: check(" no partial output for %s" % label, - "uint4 bt" not in hlsl and "x2w_bvh_intersect_box32(r" not in hlsl, "") + "uint4 bt" not in hlsl and "x2w_bvh_intersect_box32(r" not in hlsl + and "x2w_bvh_intersect_box16(r" not in hlsl, "") pipe, hlsl, refusals = translate_program(stage_kind="ps") check("refuses a pixel stage", len(refusals) == 1 and "outside a compute stage" in refusals[0], str(refusals)) @@ -322,7 +485,7 @@ def compile_check(hlsl): print("dxc compile: skip (no dxc on this host)") return None with tempfile.TemporaryDirectory(dir=ROOT / "out" if (ROOT / "out").is_dir() else None) as temporary: - source = Path(temporary) / "bvh_box32.hlsl" + source = Path(temporary) / "bvh_box.hlsl" source.write_text(hlsl, encoding="ascii") result = subprocess.run([dxc, "-T", "cs_6_0", "-E", "main", "-Fo", str(source.with_suffix(".cso")), str(source)], capture_output=True, text=True) @@ -333,8 +496,6 @@ def compile_check(hlsl): return True - - def ffloat(value): return "asfloat(0x%08xu)" % struct.unpack("= 1, (mutation, old) helpers = helpers.replace(old, new) lines = [helpers, "RWByteAddressBuffer data : register(u0);", "[numthreads(1, 1, 1)]", "void main() {"] for base_offset, children in NODES.items(): @@ -377,29 +540,102 @@ def dispatch_hlsl(mutation=None): lines.append(" data.Store(%du, %s);" % (base_offset + 16 + 24 * i + 12 + 4 * j, fbits(hi[j]))) for i in range(4): lines.append(" data.Store(%du, 0u);" % (base_offset + 112 + 4 * i)) + for base_offset, children in HALF_NODE_BY_OFFSET.items(): + for i, (child, lo, hi) in enumerate(children): + lines.append(" data.Store(%du, 0x%08xu);" % (base_offset + 4 * i, child)) + packed = struct.unpack("<3I", struct.pack("<6e", *lo, *hi)) + for j, word in enumerate(packed): + lines.append(" data.Store(%du, 0x%08xu);" % (base_offset + 16 + 12 * i + 4 * j, word)) lines.append(" DeviceMemoryBarrierWithGroupSync();") - for case, (_name, offset, extent, origin, direction, _expected) in enumerate(RAYS + UNSORTED_RAYS): - inv = tuple(1.0 / c for c in direction) - base0, base1 = DESCRIPTOR_BASES.get(_name, (0x1000, 0)) - word1 = base1 | (SORT_ENABLE if case < len(RAYS) else 0) + for case, item in enumerate(dispatch_cases()): + inv = tuple(1.0 / c for c in item["direction"]) lines.append( - " uint4 r%d = x2w_bvh_intersect_box32(data, 0x%08xu, 0x%08xu, 0x%08xu, " - "0x0000000bu, 0x80000000u, %s, float3(%s, %s, %s), float3(%s, %s, %s));" % ( - case, (offset >> 3) | 5, base0, word1, ffloat(extent), ffloat(origin[0]), ffloat(origin[1]), - ffloat(origin[2]), ffloat(inv[0]), ffloat(inv[1]), ffloat(inv[2]))) + " uint4 r%d = %s(data, 0x%08xu, 0x%08xu, 0x%08xu, 0x%08xu, 0x80000000u, " + "%s, float3(%s, %s, %s), float3(%s, %s, %s));" % ( + case, item["helper"], item["pointer"], item["word0"], item["word1"], item["word2"], + ffloat(item["extent"]), ffloat(item["origin"][0]), ffloat(item["origin"][1]), + ffloat(item["origin"][2]), ffloat(inv[0]), ffloat(inv[1]), ffloat(inv[2]))) for word in range(4): lines.append(" data.Store(%du, r%d.%s);" % (RESULT_OFFSET + 16 * case + 4 * word, case, "xyzw"[word])) lines.append("}") return "\n".join(lines) + "\n" +BOUNDARY_BOX32_OFFSET = 128 +BOUNDARY_RESULT_OFFSET = 256 +BOUNDARY_BUFFER_SIZE = 320 + + +def boundary_hlsl(): + helpers = "\n".join(G.BVH_HELPERS).replace("ByteAddressBuffer", "RWByteAddressBuffer") + lines = [helpers, "RWByteAddressBuffer data : register(u0);", "[numthreads(1, 1, 1)]", "void main() {"] + for i, (child, lo, hi) in enumerate(HALF_NODES[0]): + lines.append(" data.Store(%du, 0x%08xu);" % (4 * i, child)) + packed = struct.unpack("<3I", struct.pack("<6e", *lo, *hi)) + for j, word in enumerate(packed): + lines.append(" data.Store(%du, 0x%08xu);" % (16 + 12 * i + 4 * j, word)) + for i, (child, lo, hi) in enumerate(NODES[0]): + base = BOUNDARY_BOX32_OFFSET + lines.append(" data.Store(%du, 0x%08xu);" % (base + 4 * i, child)) + for j in range(3): + lines.append(" data.Store(%du, %s);" % (base + 16 + 24 * i + 4 * j, fbits(lo[j]))) + lines.append(" data.Store(%du, %s);" % (base + 16 + 24 * i + 12 + 4 * j, fbits(hi[j]))) + for j in range(4): + lines.append(" data.Store(%du, 0u);" % (base + 112 + 4 * j)) + lines.append(" DeviceMemoryBarrierWithGroupSync();") + box16_ray = HALF_RAYS[0] + box32_ray = RAYS[0] + cases = ( + (0, "x2w_bvh_intersect_box16", 0x04, 0, box16_ray[2:5], box16_ray[-1]), + (1, "x2w_bvh_intersect_box16", 0x0c, 0, box16_ray[2:5], (INVALID,) * 4), + (2, "x2w_bvh_intersect_box32", 0x15, 3, box32_ray[2:5], box32_ray[-1]), + (3, "x2w_bvh_intersect_box32", 0x15, 2, box32_ray[2:5], (INVALID,) * 4), + ) + expected = [] + for case, helper, pointer, word2, ray, result in cases: + extent, origin, direction = ray + inv = tuple(1.0 / c for c in direction) + lines.append( + " uint4 b%d = %s(data, 0x%08xu, 0x1000u, 0x80000000u, 0x%08xu, 0x80000000u, " + "%s, float3(%s, %s, %s), float3(%s, %s, %s));" % ( + case, helper, pointer, word2, ffloat(extent), ffloat(origin[0]), ffloat(origin[1]), + ffloat(origin[2]), ffloat(inv[0]), ffloat(inv[1]), ffloat(inv[2]))) + for word in range(4): + lines.append(" data.Store(%du, b%d.%s);" % (BOUNDARY_RESULT_OFFSET + 16 * case + 4 * word, case, "xyzw"[word])) + expected.append(result) + lines.append("}") + return "\n".join(lines) + "\n", expected + + +def run_boundary_dispatch(dxc, runner, adapter, directory): + source = directory / "bvh_boundary.hlsl" + cso = directory / "bvh_boundary.cso" + output = directory / "bvh_boundary.bin" + hlsl, expected = boundary_hlsl() + source.write_text(hlsl, encoding="ascii") + compiled = subprocess.run([dxc, "-Gis", "-T", "cs_6_0", "-E", "main", "-Fo", str(cso), str(source)], + capture_output=True, text=True) + if compiled.returncode or compiled.stderr: + raise AssertionError(compiled.stderr or "dxc exited with %d" % compiled.returncode) + result = subprocess.run([runner, adapter, "--raw-uav-dump", str(cso), "1", str(BOUNDARY_BUFFER_SIZE), str(output)], + capture_output=True, text=True) + print(result.stdout, end="") + if result.returncode == 77: + return 77, None, expected + if result.returncode or result.stderr: + raise AssertionError(result.stderr or "offscreen_check exited with %d" % result.returncode) + data = output.read_bytes() + assert len(data) == BOUNDARY_BUFFER_SIZE, (len(data), BOUNDARY_BUFFER_SIZE) + return 0, struct.unpack("<%dI" % (len(data) // 4), data), expected + + def run_dispatch(dxc, runner, adapter, directory, mutation=None): name = "bvh_dispatch_" + mutation if mutation else "bvh_dispatch" source = directory / (name + ".hlsl") cso = directory / (name + ".cso") output = directory / (name + ".bin") source.write_text(dispatch_hlsl(mutation), encoding="ascii") - compiled = subprocess.run([dxc, "-T", "cs_6_0", "-E", "main", "-Fo", str(cso), str(source)], + compiled = subprocess.run([dxc, "-Gis", "-T", "cs_6_0", "-E", "main", "-Fo", str(cso), str(source)], capture_output=True, text=True) if compiled.returncode or compiled.stderr: raise AssertionError(compiled.stderr or "dxc exited with %d" % compiled.returncode) @@ -430,28 +666,38 @@ def check_dispatch(dxc, runner, adapter): if status == 77: print("dispatch: skip (adapter unavailable)") return 77 - cases = RAYS + UNSORTED_RAYS - for case, (_name, _offset, _extent, _origin, _direction, expected) in enumerate(cases): + cases = dispatch_cases() + for case, item in enumerate(cases): start = RESULT_WORD + 4 * case got = tuple(words[start:start + 4]) - check("dispatch case %d %s" % (case, _name), got == expected, - "got %s expected %s" % (["%08x" % w for w in got], ["%08x" % w for w in expected])) + check("dispatch case %d %s" % (case, item["name"]), got == item["expected"], + "got %s expected %s" % (["%08x" % w for w in got], ["%08x" % w for w in item["expected"]])) for mutation, (witness, _replacements) in MUTATIONS.items(): status, mutant = run_dispatch(dxc, runner, adapter, directory, mutation=mutation) if status == 77: print("dispatch control: skip (adapter unavailable)") return 77 - case = next(i for i, ray in enumerate(cases) if ray[0] == witness) + case = next(i for i, item in enumerate(cases) if item["name"] == witness) start = RESULT_WORD + 4 * case changed = tuple(mutant[start:start + 4]) - check("dispatch %s control changes %s" % (mutation, witness), changed != cases[case][-1], + check("dispatch %s control changes %s" % (mutation, witness), changed != cases[case]["expected"], "got %s" % ["%08x" % w for w in changed]) + status, boundary_words, boundary_expected = run_boundary_dispatch(dxc, runner, adapter, directory) + if status == 77: + print("dispatch boundary: skip (adapter unavailable)") + return 77 + for case, wanted in enumerate(boundary_expected): + start = BOUNDARY_RESULT_OFFSET // 4 + 4 * case + got = tuple(boundary_words[start:start + 4]) + check("decoded descriptor extent case %d" % case, got == wanted, + "got %s expected %s" % (["%08x" % w for w in got], ["%08x" % w for w in wanted])) if failures: print("FAILED: %s" % ", ".join(failures)) return 1 print("dispatch: all ok on %s" % adapter) return 0 + def main(): if len(sys.argv) == 5 and sys.argv[1] == "dispatch": return check_dispatch(sys.argv[2], sys.argv[3], sys.argv[4]) @@ -461,10 +707,13 @@ def main(): pipe, hlsl, refusals = translate_program() assert not refusals, refusals compile_check(hlsl) + pipe, hlsl, refusals = translate_program(node=0x04) + assert not refusals, refusals + compile_check(hlsl) if failures: print("FAILED: %s" % ", ".join(failures)) return 1 - print("startup gfx2hlsl bvh box32: all ok") + print("startup gfx2hlsl bvh box32/box16: all ok") return 0 diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 3382f7a845..543c28952e 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -8051,18 +8051,18 @@ def bvh_descriptor(self, tok): return (('bvhbase', base, values[2]), None), words, values def op_image_bvh_intersect_ray(self, ops, mods): - """Ray/box intersection for the 128-byte FP32 box node (kind 5). + """Ray/box intersection for the 128-byte FP32 (kind 5) and 64-byte binary16 (kind 4) box nodes. RDNA 2 ISA section 8.2.10 and Table 48: VDATA is four result dwords, VADDR is 11 dwords (node pointer, extent, origin xyz, direction xyz, inverse direction xyz) and SRSRC is the four-word BVH T# of Table 49. This first slice accepts only a straight-line compute program - with a constant node base, a constant inline T# and a node whose kind bits are 5. - The descriptor base binds a ByteAddressBuffer at the 256-byte-aligned allocation; the node - pointer is an offset in 8-byte units from that base. The emitted helper performs the four - slab tests, clips against extent, replaces misses with 0xffffffff in their original slots, - and sorts by entry distance only when the descriptor's box-sorting enable bit is set. - Triangle nodes, 16-bit box nodes, the 64-bit form, A16, non-sequential addresses and every - other node kind are refused by name. + with a constant node base, a constant inline T# and a node whose kind bits are 4 or 5. + The descriptor base encodes address bits 47:8 in 256-byte units and binds a + ByteAddressBuffer at that byte address; the node pointer is an offset in 8-byte units from + that base. The emitted helper performs the four slab tests, clips against extent, replaces + misses with 0xffffffff in their original slots, and sorts by entry distance only when the + descriptor's box-sorting enable bit is set. Triangle nodes, the 64-bit form, A16, + non-sequential addresses and every other node kind are refused by name. """ name = 'image_bvh_intersect_ray' if self.kind != 'cs': @@ -8087,15 +8087,15 @@ def op_image_bvh_intersect_ray(self, ops, mods): if node is None: raise Unsupported('%s non-constant node base %s' % (name, cs[0])) kind = node & 7 - if kind == 4: - raise Unsupported('%s 16-bit box node (kind 4) is not lowered' % name) - if kind == 0: - raise Unsupported('%s triangle node (kind 0) is not lowered' % name) - if kind != 5: + if 0 <= kind <= 3: + raise Unsupported('%s triangle node (kind %d) is not lowered' % (name, kind)) + if kind not in (4, 5): raise Unsupported('%s node kind %d is not lowered' % (name, kind)) + half_box = kind == 4 + node_bytes = 64 if half_box else 128 node_offset = (node & 0xfffffff8) << 3 - if node_offset > 0xffffff80 or node_offset & 0x7f: - raise Unsupported('%s node base %#x is not an aligned 128-byte node' % (name, node_offset)) + if node_offset > (0xffffffc0 if half_box else 0xffffff80) or node_offset & (0x3f if half_box else 0x7f): + raise Unsupported('%s node base %#x is not an aligned %u-byte node' % (name, node_offset, node_bytes)) key, words, vals = self.bvh_descriptor(ops[2]) if vals[1] is not None: if vals[1] & 0x7f800000: @@ -8111,11 +8111,12 @@ def op_image_bvh_intersect_ray(self, ops, mods): if base == 0: raise Unsupported('%s absolute node base is not lowered' % name) if vals[2] is not None: - if vals[2] < 1 or vals[2] >= 0x04000000: - raise Unsupported('%s descriptor size %d does not cover a 128-byte node' % (name, vals[2])) - if (node_offset >> 6) + 1 > vals[2]: + if vals[2] >= 0x04000000: + raise Unsupported('%s descriptor size %d is above 4 GiB' % (name, vals[2])) + # Size is a count minus one in 64-byte units, so size=0 is a one-unit span. + if (node_offset >> 6) + (node_bytes >> 6) - 1 > vals[2]: raise Unsupported('%s node base %#x is outside descriptor size %d' % (name, node_offset, vals[2])) - if base + node_offset + 128 > 1 << 48: + if base + node_offset + node_bytes > 1 << 48: raise Unsupported('%s node address wraps the 48-bit address space' % name) extent = self.f(cs[1]) origin = [self.f(cs[2 + i]) for i in range(3)] @@ -8123,7 +8124,8 @@ def op_image_bvh_intersect_ray(self, ops, mods): inv_dir = [self.f(cs[8 + i]) for i in range(3)] res = self.pipe.resource(key, 'bvh') self.pipe.uses_bvh = True - call = 'x2w_bvh_intersect_box32(%s, 0x%08xu, %s, %s, %s, %s, %s, float3(%s, %s, %s), float3(%s, %s, %s))' % ( + call = '%s(%s, 0x%08xu, %s, %s, %s, %s, %s, float3(%s, %s, %s), float3(%s, %s, %s))' % ( + 'x2w_bvh_intersect_box16' if half_box else 'x2w_bvh_intersect_box32', res, node, words[0], words[1], words[2], words[3], extent, origin[0], origin[1], origin[2], inv_dir[0], inv_dir[1], inv_dir[2]) self.emit('uint4 bt%x = %s;' % (self.pc or 0, call)) @@ -11093,7 +11095,7 @@ def read(fmt, data, offset): # slice does not bind, so it is refused here as a miss rather than read at address zero. 'bool x2w_bvh_descriptor_ok(uint word0, uint word1, uint word2, uint word3) {', ' return (word1 & 0x7fffff00u) == 0u &&', - ' word3 == 0x80000000u && word2 >= 1u && word2 < 0x04000000u &&', + ' word3 == 0x80000000u && word2 < 0x04000000u &&', ' (word0 != 0u || (word1 & 0x000000ffu) != 0u);', '}', # One FP32 box from a radv_bvh_box32_node (Mesa 25.1.0 bvh/bvh.h, MIT): children[4] at @@ -11116,6 +11118,24 @@ def read(fmt, data, offset): ' hit = active && tmax >= max(0.0, tmin) && tmin < extent;', ' return hit ? tmin : asfloat(0x7f800000u);', '}', + # One binary16 box from a radv_bvh_box16_node: children[4] at 0..15, coords[4][2][3] at + # 16..63, six binary16 values per child. The half values widen exactly to binary32. + 'float x2w_bvh_box16_slot(ByteAddressBuffer nodes, uint node_offset, uint index, float extent,', + ' float3 origin, float3 inv_dir, out bool hit) {', + ' uint at = node_offset + 16u + 12u * index;', + ' uint h0 = nodes.Load(at), h1 = nodes.Load(at + 4u), h2 = nodes.Load(at + 8u);', + ' float3 lo = float3(f16tof32(h0), f16tof32(h0 >> 16u), f16tof32(h1));', + ' float3 hi = float3(f16tof32(h1 >> 16u), f16tof32(h2), f16tof32(h2 >> 16u));', + ' float3 bound0 = (lo - origin) * inv_dir;', + ' float3 bound1 = (hi - origin) * inv_dir;', + ' float tmin = max(max(min(bound0.x, bound1.x), min(bound0.y, bound1.y)),', + ' min(bound0.z, bound1.z));', + ' float tmax = min(min(max(bound0.x, bound1.x), max(bound0.y, bound1.y)),', + ' max(bound0.z, bound1.z));', + ' bool active = (asuint(lo.x) & 0x7fffffffu) <= 0x7f800000u;', + ' hit = active && tmax >= max(0.0, tmin) && tmin < extent;', + ' return hit ? tmin : asfloat(0x7f800000u);', + '}', # The five compare-exchange stages of Mesa radv_nir_rt_common.c: a strict comparison # sorts misses (key +inf) to the end without swapping equal keys within each pair. 'void x2w_bvh_sort_pair(inout uint ia, inout uint ib, inout float ka, inout float kb) {', @@ -11163,6 +11183,45 @@ def read(fmt, data, offset): ' x2w_bvh_sort_pair(c1, c2, k1, k2);', ' return uint4(c0, c1, c2, c3);', '}', + 'uint4 x2w_bvh_intersect_box16(ByteAddressBuffer nodes, uint node, uint word0, uint word1,', + ' uint word2, uint word3, float extent, float3 origin,', + ' float3 inv_dir) {', + ' uint4 miss = uint4(X2W_BVH_MISS, X2W_BVH_MISS, X2W_BVH_MISS, X2W_BVH_MISS);', + ' if ((node & 7u) != 4u || !x2w_bvh_descriptor_ok(word0, word1, word2, word3)) return miss;', + ' uint offset = (node & 0xfffffff8u) << 3u;', + ' if ((offset >> 6u) > word2) return miss;', + ' inv_dir = clamp(inv_dir, -3.402823466e+38, 3.402823466e+38);', + ' bool h0, h1, h2, h3;', + ' float d0 = x2w_bvh_box16_slot(nodes, offset, 0u, extent, origin, inv_dir, h0);', + ' float d1 = x2w_bvh_box16_slot(nodes, offset, 1u, extent, origin, inv_dir, h1);', + ' float d2 = x2w_bvh_box16_slot(nodes, offset, 2u, extent, origin, inv_dir, h2);', + ' float d3 = x2w_bvh_box16_slot(nodes, offset, 3u, extent, origin, inv_dir, h3);', + ' bool sort_boxes = (word1 & 0x80000000u) != 0u;', + ' uint c0 = nodes.Load(offset);', + ' uint c1 = nodes.Load(offset + 4u);', + ' uint c2 = nodes.Load(offset + 8u);', + ' uint c3 = nodes.Load(offset + 12u);', + ' h0 = h0 && c0 != X2W_BVH_MISS;', + ' h1 = h1 && c1 != X2W_BVH_MISS;', + ' h2 = h2 && c2 != X2W_BVH_MISS;', + ' h3 = h3 && c3 != X2W_BVH_MISS;', + ' c0 = h0 ? c0 : X2W_BVH_MISS;', + ' c1 = h1 ? c1 : X2W_BVH_MISS;', + ' c2 = h2 ? c2 : X2W_BVH_MISS;', + ' c3 = h3 ? c3 : X2W_BVH_MISS;', + # With sorting disabled, each result remains in its original child slot. + ' if (!sort_boxes) return uint4(c0, c1, c2, c3);', + ' float k0 = h0 ? d0 : asfloat(0x7f800000u);', + ' float k1 = h1 ? d1 : asfloat(0x7f800000u);', + ' float k2 = h2 ? d2 : asfloat(0x7f800000u);', + ' float k3 = h3 ? d3 : asfloat(0x7f800000u);', + ' x2w_bvh_sort_pair(c0, c1, k0, k1);', + ' x2w_bvh_sort_pair(c2, c3, k2, k3);', + ' x2w_bvh_sort_pair(c0, c2, k0, k2);', + ' x2w_bvh_sort_pair(c1, c3, k1, k3);', + ' x2w_bvh_sort_pair(c1, c2, k1, k2);', + ' return uint4(c0, c1, c2, c3);', + '}', )