rdc_dump.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. #!/usr/bin/env python3
  2. """RenderDoc capture inspector for this engine's GL puppet-compositing pipeline.
  3. Runs inside qrenderdoc's embedded Python interpreter (not a normal python3 - the
  4. `renderdoc`/`qrenderdoc` modules only exist there). Invoke as:
  5. env -u WAYLAND_DISPLAY QT_QPA_PLATFORM=xcb DISPLAY=:0 \
  6. RDC_CAPFILE=/path/to/capture.rdc RDC_MODE=positions RDC_EVENTID=1775 \
  7. qrenderdoc --python tools/rdc_dump.py
  8. Modes (set via RDC_MODE):
  9. list - print eventId/name/numIndices/outputs for every draw call in the capture.
  10. positions - dump the a_Position vertex buffer for RDC_EVENTID (comma-separated list ok).
  11. texcoords - dump the a_TexCoord vertex buffer for RDC_EVENTID.
  12. uniforms - dump the $Globals uniform block (g_ModelViewProjectionMatrix etc) for RDC_EVENTID.
  13. resources - dump the fragment shader's bound texture resourceIds/names for RDC_EVENTID,
  14. useful for confirming two draws are part of the same object's FBO->composite chain
  15. (an intermediate pass's output resourceId showing up as a later draw's input).
  16. textures - save every fragment shader texture bound at RDC_EVENTID to RDC_OUT_<eid>_<slot>.png
  17. (RDC_OUT is a path prefix here), e.g. to see what a video texture held at its draw.
  18. screenshot - save the final swapchain image of the whole frame (last draw call) to RDC_OUT (PNG).
  19. Several embedded-API quirks aren't documented anywhere obvious - see the per-function comments
  20. below (GetConstantBlock's resourceId lives under .descriptor.resource not .resourceId, resource
  21. names need a manual resourceId->name dict from controller.GetResources() since there's no
  22. GetResourceName(), etc).
  23. """
  24. import os
  25. import sys
  26. import struct
  27. import renderdoc as rd
  28. CAPFILE = os.environ.get("RDC_CAPFILE")
  29. MODE = os.environ.get("RDC_MODE", "list")
  30. EVENTIDS = [int(e) for e in os.environ.get("RDC_EVENTID", "").split(",") if e.strip()]
  31. OUT = os.environ.get("RDC_OUT")
  32. out_lines = []
  33. def log(s):
  34. print(s)
  35. out_lines.append(str(s))
  36. def walk_actions(controller, fn):
  37. def recurse(act):
  38. fn(act)
  39. for c in act.children:
  40. recurse(c)
  41. for a in controller.GetRootActions():
  42. recurse(a)
  43. def dump_vbuffer(controller, eid, attr_name):
  44. controller.SetFrameEvent(eid, True)
  45. state = controller.GetPipelineState()
  46. vp = state.GetViewport(0)
  47. vbs = state.GetVBuffers()
  48. attrs = state.GetVertexInputs()
  49. log(f"eventId={eid} viewport=({vp.x},{vp.y},{vp.width},{vp.height})")
  50. for attr in attrs:
  51. if attr.name != attr_name:
  52. continue
  53. vb = vbs[attr.vertexBuffer]
  54. total_offset = attr.byteOffset + vb.byteOffset
  55. data = controller.GetBufferData(vb.resourceId, total_offset, 0)
  56. comp = attr.format.compCount
  57. n = (len(data) // 4 // comp) * comp
  58. vals = struct.unpack_from(f"<{n}f", data, 0)
  59. log(f" {attr_name} ({comp} floats/vertex, {n // comp} vertices): {vals}")
  60. if comp >= 2:
  61. xs = vals[0::comp]
  62. ys = vals[1::comp]
  63. log(f" {attr_name} X range: {min(xs)} to {max(xs)} (center {(min(xs)+max(xs))/2})")
  64. log(f" {attr_name} Y range: {min(ys)} to {max(ys)} (center {(min(ys)+max(ys))/2})")
  65. def dump_uniforms(controller, eid):
  66. controller.SetFrameEvent(eid, True)
  67. state = controller.GetPipelineState()
  68. refl = state.GetShaderReflection(rd.ShaderStage.Vertex)
  69. vs_id = state.GetShader(rd.ShaderStage.Vertex)
  70. # GetConstantBlock's return type (BoundCBuffer) hides the actual resourceId/byteOffset/byteSize
  71. # under .descriptor, not as direct attributes - not obvious from the method name.
  72. cbuf = state.GetConstantBlock(rd.ShaderStage.Vertex, 0, 0)
  73. d = cbuf.descriptor
  74. variables = controller.GetCBufferVariableContents(
  75. state.GetGraphicsPipelineObject(), vs_id, rd.ShaderStage.Vertex, refl.entryPoint, 0,
  76. d.resource, d.byteOffset, d.byteSize)
  77. log(f"eventId={eid} $Globals:")
  78. for v in variables:
  79. log(f" {v.name}: {v.value.f32v[:16]}")
  80. def dump_resources(controller, eid, resnames):
  81. controller.SetFrameEvent(eid, True)
  82. state = controller.GetPipelineState()
  83. def act_info():
  84. found = [(None, None)]
  85. def fn(act):
  86. if act.eventId == eid:
  87. found[0] = (act.GetName(controller.GetStructuredFile()), list(act.outputs))
  88. walk_actions(controller, fn)
  89. return found[0]
  90. name, outputs = act_info()
  91. log(f"eventId={eid} name={name} outputs={outputs}")
  92. for ro in state.GetReadOnlyResources(rd.ShaderStage.Fragment):
  93. rid = ro.descriptor.resource
  94. log(f" fragment slot={ro.access.index} resourceId={rid} name={resnames.get(rid, '?')}")
  95. def save_textures(controller, eid, resnames):
  96. controller.SetFrameEvent(eid, True)
  97. state = controller.GetPipelineState()
  98. for ro in state.GetReadOnlyResources(rd.ShaderStage.Fragment):
  99. rid = ro.descriptor.resource
  100. if rid == rd.ResourceId.Null():
  101. continue
  102. texsave = rd.TextureSave()
  103. texsave.resourceId = rid
  104. texsave.destType = rd.FileType.PNG
  105. texsave.mip = 0
  106. texsave.slice.sliceIndex = 0
  107. texsave.alpha = rd.AlphaMapping.Preserve
  108. path = f"{OUT or 'texture'}_{eid}_{ro.access.index}.png"
  109. ok = controller.SaveTexture(texsave, path)
  110. log(f"eventId={eid} slot={ro.access.index} resourceId={rid} name={resnames.get(rid, '?')} -> {path} ok={ok}")
  111. def do_list(controller):
  112. def fn(act):
  113. if act.flags & rd.ActionFlags.Drawcall:
  114. log(f"eventId={act.eventId} name={act.GetName(controller.GetStructuredFile())} "
  115. f"numIndices={act.numIndices} outputs={list(act.outputs)}")
  116. walk_actions(controller, fn)
  117. def do_screenshot(controller):
  118. last_draw = [None]
  119. def fn(act):
  120. if act.flags & rd.ActionFlags.Drawcall:
  121. last_draw[0] = act
  122. walk_actions(controller, fn)
  123. if last_draw[0] is None:
  124. log("no draw calls found")
  125. return
  126. controller.SetFrameEvent(last_draw[0].eventId, True)
  127. log(f"last draw eventId={last_draw[0].eventId}")
  128. texsave = rd.TextureSave()
  129. # the output resourceId lives on the *action*, not the controller - there's no
  130. # controller.GetOutputTargets() despite PipeState having one for the currently bound FBO.
  131. texsave.resourceId = last_draw[0].outputs[0]
  132. if texsave.resourceId == rd.ResourceId.Null():
  133. log("no output resource on last draw")
  134. return
  135. texsave.destType = rd.FileType.PNG
  136. texsave.mip = 0
  137. texsave.slice.sliceIndex = 0
  138. ok = controller.SaveTexture(texsave, OUT or "screenshot.png")
  139. log(f"SaveTexture -> {OUT or 'screenshot.png'} ok={ok}")
  140. def sampleCode(controller):
  141. if MODE == "list":
  142. do_list(controller)
  143. elif MODE == "positions":
  144. for eid in EVENTIDS:
  145. dump_vbuffer(controller, eid, "a_Position")
  146. elif MODE == "texcoords":
  147. for eid in EVENTIDS:
  148. dump_vbuffer(controller, eid, "a_TexCoord")
  149. elif MODE == "uniforms":
  150. for eid in EVENTIDS:
  151. dump_uniforms(controller, eid)
  152. elif MODE == "resources":
  153. resnames = {r.resourceId: r.name for r in controller.GetResources()}
  154. for eid in EVENTIDS:
  155. dump_resources(controller, eid, resnames)
  156. elif MODE == "textures":
  157. resnames = {r.resourceId: r.name for r in controller.GetResources()}
  158. for eid in EVENTIDS:
  159. save_textures(controller, eid, resnames)
  160. elif MODE == "screenshot":
  161. do_screenshot(controller)
  162. else:
  163. log(f"unknown RDC_MODE={MODE!r}")
  164. def main():
  165. if not CAPFILE:
  166. log("RDC_CAPFILE env var not set")
  167. return
  168. import time
  169. pyrenderdoc.LoadCapture(CAPFILE, rd.ReplayOptions(), CAPFILE, False, True)
  170. for _ in range(200):
  171. if pyrenderdoc.IsCaptureLoaded():
  172. break
  173. time.sleep(0.1)
  174. log(f"IsCaptureLoaded: {pyrenderdoc.IsCaptureLoaded()}")
  175. pyrenderdoc.Replay().BlockInvoke(sampleCode)
  176. try:
  177. main()
  178. except Exception as e:
  179. import traceback
  180. log(f"EXCEPTION: {e}")
  181. log(traceback.format_exc())
  182. log_path = OUT + ".log" if (OUT and MODE in ("screenshot", "textures")) else OUT
  183. if log_path:
  184. with open(log_path, "w") as f:
  185. f.write("\n".join(out_lines))
  186. os._exit(0)