dxbc_dump.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. #!/usr/bin/env python3
  2. """Disassembles the shaders Wallpaper Engine compiled and cached (shaders/blobsSM40/*.dxs in a workshop item)
  3. or any plain DXBC file, to see what fxc made of a workshop shader's HLSL-only constructs.
  4. A .dxs holds a small header (e.g. "SHDV0069") and then one DXBC per stage. For every DXBC this prints the
  5. constant buffer layout from RDEF (name, byte offset, size, class/rows/cols/elements) and, with --code, a
  6. plain listing of the SHEX/SHDR instructions (opcode names and operands, declarations by name only).
  7. Usage:
  8. dxbc_dump.py <file.dxs|file.dxbc> [--code] [--grep <uniform name>]
  9. --grep only prints blobs whose RDEF mentions that name, handy over a whole blobsSM40 dir:
  10. dxbc_dump.py <item>/shaders/blobsSM40/*.dxs --grep g_AudioSpectrum64Left
  11. """
  12. import re
  13. import struct
  14. import sys
  15. OPCODES = (
  16. "add and break breakc call callc case continue continuec cut default deriv_rtx deriv_rty discard div dp2 dp3 "
  17. "dp4 else emit emitthencut endif endloop endswitch eq exp frc ftoi ftou ge iadd if ieq ige ilt imad imax imin "
  18. "imul ine ineg ishl ishr itof label ld ld_ms log loop lt mad min max customdata mov movc mul ne nop not or "
  19. "resinfo ret retc round_ne round_ni round_pi round_z rsq sample sample_c sample_c_lz sample_l sample_d sample_b "
  20. "sqrt switch sincos udiv ult uge umul umad umax umin ushr utof xor dcl_resource dcl_constantbuffer dcl_sampler "
  21. "dcl_index_range dcl_gs_output_topology dcl_gs_input dcl_max_output_vertex_count dcl_input dcl_input_sgv "
  22. "dcl_input_siv dcl_input_ps dcl_input_ps_sgv dcl_input_ps_siv dcl_output dcl_output_sgv dcl_output_siv "
  23. "dcl_temps dcl_indexable_temp dcl_global_flags"
  24. ).split()
  25. OPERAND_TYPES = {0: 'r', 1: 'v', 2: 'o', 3: 'x', 4: 'l', 5: 'd', 6: 's', 7: 't', 8: 'cb', 9: 'icb', 10: 'label',
  26. 11: 'vPrim', 12: 'oDepth', 13: 'null'}
  27. CUSTOMDATA = 53
  28. def chunks(dxbc):
  29. count = struct.unpack_from('<I', dxbc, 28)[0]
  30. for i in range(count):
  31. offset = struct.unpack_from('<I', dxbc, 32 + 4 * i)[0]
  32. size = struct.unpack_from('<I', dxbc, offset + 4)[0]
  33. yield dxbc[offset:offset + 4], dxbc[offset + 8:offset + 8 + size]
  34. def rdef(data):
  35. def cstr(offset):
  36. return data[offset:data.index(b'\0', offset)].decode()
  37. cb_count, cb_offset, _, _, target = struct.unpack_from('<IIIII', data, 0)
  38. var_stride = 40 if (target & 0xffff) >= 0x500 else 24
  39. lines = []
  40. for c in range(cb_count):
  41. name, var_count, var_offset, size, _, _ = struct.unpack_from('<IIIIII', data, cb_offset + 24 * c)
  42. lines.append(f'cbuffer {cstr(name)} size {size}')
  43. for v in range(var_count):
  44. vname, start, vsize, flags, type_offset, _ = struct.unpack_from('<IIIIII', data, var_offset + var_stride * v)
  45. cls, typ, rows, cols, elements, _ = struct.unpack_from('<HHHHHH', data, type_offset)
  46. # D3D_SVF_USED: the shader reads it, fxc keeps unused variables in the buffer layout
  47. used = 'used' if flags & 2 else 'unused'
  48. lines.append(f' {cstr(vname)} offset {start} size {vsize} class {cls} type {typ} rows {rows} '
  49. f'cols {cols} elements {elements} {used}')
  50. return lines
  51. def disassemble(code):
  52. words = struct.unpack_from(f'<{len(code) // 4}I', code)
  53. pos = 2
  54. def operand():
  55. nonlocal pos
  56. token = words[pos]
  57. pos += 1
  58. components = token & 3
  59. selection = (token >> 2) & 3
  60. component_data = (token >> 4) & 0xff
  61. kind = (token >> 12) & 0xff
  62. dimension = (token >> 20) & 3
  63. extended = token >> 31
  64. while extended:
  65. extended = words[pos] >> 31
  66. pos += 1
  67. if kind == 4:
  68. count = 1 if components == 1 else 4
  69. values = words[pos:pos + count]
  70. pos += count
  71. return 'l(' + ','.join('%g' % struct.unpack('<f', struct.pack('<I', v))[0] for v in values) + ')'
  72. indices = []
  73. for i in range(dimension):
  74. representation = (token >> (22 + 3 * i)) & 7
  75. if representation == 0:
  76. indices.append(str(words[pos]))
  77. pos += 1
  78. elif representation == 2:
  79. indices.append(operand())
  80. elif representation == 3:
  81. immediate = words[pos]
  82. pos += 1
  83. indices.append(f'{operand()}+{immediate}')
  84. else:
  85. indices.append('?')
  86. pos += 1
  87. text = OPERAND_TYPES.get(kind, f't{kind}') + ''.join(f'[{i}]' for i in indices)
  88. if components == 2:
  89. if selection == 0:
  90. text += '.' + ''.join(c for bit, c in enumerate('xyzw') if component_data >> bit & 1)
  91. elif selection == 1:
  92. text += '.' + ''.join('xyzw'[(component_data >> (2 * k)) & 3] for k in range(4))
  93. else:
  94. text += '.' + 'xyzw'[component_data & 3]
  95. return text
  96. lines = []
  97. while pos < len(words):
  98. token = words[pos]
  99. opcode = token & 0x7ff
  100. length = (token >> 24) & 0x7f
  101. start = pos
  102. name = OPCODES[opcode] if opcode < len(OPCODES) else f'op{opcode}'
  103. if opcode == CUSTOMDATA:
  104. length = words[pos + 1]
  105. if name.startswith('dcl') or opcode == CUSTOMDATA:
  106. lines.append(name)
  107. pos = start + length
  108. continue
  109. pos += 1
  110. if token >> 31:
  111. pos += 1
  112. args = []
  113. try:
  114. while pos < start + length:
  115. args.append(operand())
  116. except IndexError:
  117. args.append('<decode error>')
  118. lines.append(name + ('_sat' if (token >> 13) & 1 else '') + ' ' + ', '.join(args))
  119. pos = start + length
  120. return lines
  121. def main(argv):
  122. show_code = '--code' in argv
  123. grep = None
  124. if '--grep' in argv:
  125. grep = argv[argv.index('--grep') + 1]
  126. argv = [a for a in argv if a != grep]
  127. paths = [a for a in argv[1:] if not a.startswith('--')]
  128. for path in paths:
  129. data = open(path, 'rb').read()
  130. for index, match in enumerate(re.finditer(b'DXBC', data)):
  131. dxbc = data[match.start():]
  132. out = []
  133. for tag, body in chunks(dxbc):
  134. if tag == b'RDEF':
  135. out += rdef(body)
  136. elif tag in (b'SHEX', b'SHDR'):
  137. version = struct.unpack_from('<I', body, 0)[0]
  138. stage = {0: 'ps', 1: 'vs', 2: 'gs'}.get(version >> 16, f'stage{version >> 16}')
  139. out.insert(0, f'== {path} #{index} {stage}_{(version >> 4) & 0xf}_{version & 0xf}')
  140. if show_code:
  141. out += disassemble(body)
  142. if grep is None or any(grep in line for line in out):
  143. print('\n'.join(out))
  144. if __name__ == '__main__':
  145. main(sys.argv)