DrawManager.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  1. using Ryujinx.Graphics.GAL;
  2. using Ryujinx.Graphics.Gpu.Engine.Types;
  3. using System;
  4. using System.Text;
  5. namespace Ryujinx.Graphics.Gpu.Engine.Threed
  6. {
  7. /// <summary>
  8. /// Draw manager.
  9. /// </summary>
  10. class DrawManager
  11. {
  12. private readonly GpuContext _context;
  13. private readonly GpuChannel _channel;
  14. private readonly DeviceStateWithShadow<ThreedClassState> _state;
  15. private readonly DrawState _drawState;
  16. private bool _topologySet;
  17. private bool _instancedDrawPending;
  18. private bool _instancedIndexed;
  19. private bool _instancedIndexedInline;
  20. private int _instancedFirstIndex;
  21. private int _instancedFirstVertex;
  22. private int _instancedFirstInstance;
  23. private int _instancedIndexCount;
  24. private int _instancedDrawStateFirst;
  25. private int _instancedDrawStateCount;
  26. private int _instanceIndex;
  27. private const int IndexBufferCountMethodOffset = 0x5f8;
  28. /// <summary>
  29. /// Creates a new instance of the draw manager.
  30. /// </summary>
  31. /// <param name="context">GPU context</param>
  32. /// <param name="channel">GPU channel</param>
  33. /// <param name="state">Channel state</param>
  34. /// <param name="drawState">Draw state</param>
  35. public DrawManager(GpuContext context, GpuChannel channel, DeviceStateWithShadow<ThreedClassState> state, DrawState drawState)
  36. {
  37. _context = context;
  38. _channel = channel;
  39. _state = state;
  40. _drawState = drawState;
  41. }
  42. /// <summary>
  43. /// Marks the entire state as dirty, forcing a full host state update before the next draw.
  44. /// </summary>
  45. public void ForceStateDirty()
  46. {
  47. _topologySet = false;
  48. }
  49. /// <summary>
  50. /// Pushes four 8-bit index buffer elements.
  51. /// </summary>
  52. /// <param name="argument">Method call argument</param>
  53. public void VbElementU8(int argument)
  54. {
  55. _drawState.IbStreamer.VbElementU8(_context.Renderer, argument);
  56. }
  57. /// <summary>
  58. /// Pushes two 16-bit index buffer elements.
  59. /// </summary>
  60. /// <param name="argument">Method call argument</param>
  61. public void VbElementU16(int argument)
  62. {
  63. _drawState.IbStreamer.VbElementU16(_context.Renderer, argument);
  64. }
  65. /// <summary>
  66. /// Pushes one 32-bit index buffer element.
  67. /// </summary>
  68. /// <param name="argument">Method call argument</param>
  69. public void VbElementU32(int argument)
  70. {
  71. _drawState.IbStreamer.VbElementU32(_context.Renderer, argument);
  72. }
  73. /// <summary>
  74. /// Finishes the draw call.
  75. /// This draws geometry on the bound buffers based on the current GPU state.
  76. /// </summary>
  77. /// <param name="engine">3D engine where this method is being called</param>
  78. /// <param name="argument">Method call argument</param>
  79. public void DrawEnd(ThreedClass engine, int argument)
  80. {
  81. DrawEnd(engine, _state.State.IndexBufferState.First, (int)_state.State.IndexBufferCount);
  82. }
  83. /// <summary>
  84. /// Finishes the draw call.
  85. /// This draws geometry on the bound buffers based on the current GPU state.
  86. /// </summary>
  87. /// <param name="engine">3D engine where this method is being called</param>
  88. /// <param name="firstIndex">Index of the first index buffer element used on the draw</param>
  89. /// <param name="indexCount">Number of index buffer elements used on the draw</param>
  90. private void DrawEnd(ThreedClass engine, int firstIndex, int indexCount)
  91. {
  92. ConditionalRenderEnabled renderEnable = ConditionalRendering.GetRenderEnable(
  93. _context,
  94. _channel.MemoryManager,
  95. _state.State.RenderEnableAddress,
  96. _state.State.RenderEnableCondition);
  97. if (renderEnable == ConditionalRenderEnabled.False || _instancedDrawPending)
  98. {
  99. if (renderEnable == ConditionalRenderEnabled.False)
  100. {
  101. PerformDeferredDraws();
  102. }
  103. _drawState.DrawIndexed = false;
  104. if (renderEnable == ConditionalRenderEnabled.Host)
  105. {
  106. _context.Renderer.Pipeline.EndHostConditionalRendering();
  107. }
  108. return;
  109. }
  110. _drawState.FirstIndex = firstIndex;
  111. _drawState.IndexCount = indexCount;
  112. engine.UpdateState();
  113. bool instanced = _drawState.VsUsesInstanceId || _drawState.IsAnyVbInstanced;
  114. if (instanced)
  115. {
  116. _instancedDrawPending = true;
  117. int ibCount = _drawState.IbStreamer.InlineIndexCount;
  118. _instancedIndexed = _drawState.DrawIndexed;
  119. _instancedIndexedInline = ibCount != 0;
  120. _instancedFirstIndex = firstIndex;
  121. _instancedFirstVertex = (int)_state.State.FirstVertex;
  122. _instancedFirstInstance = (int)_state.State.FirstInstance;
  123. _instancedIndexCount = ibCount != 0 ? ibCount : indexCount;
  124. var drawState = _state.State.VertexBufferDrawState;
  125. _instancedDrawStateFirst = drawState.First;
  126. _instancedDrawStateCount = drawState.Count;
  127. _drawState.DrawIndexed = false;
  128. if (renderEnable == ConditionalRenderEnabled.Host)
  129. {
  130. _context.Renderer.Pipeline.EndHostConditionalRendering();
  131. }
  132. return;
  133. }
  134. int firstInstance = (int)_state.State.FirstInstance;
  135. int inlineIndexCount = _drawState.IbStreamer.GetAndResetInlineIndexCount();
  136. if (inlineIndexCount != 0)
  137. {
  138. int firstVertex = (int)_state.State.FirstVertex;
  139. BufferRange br = new BufferRange(_drawState.IbStreamer.GetInlineIndexBuffer(), 0, inlineIndexCount * 4);
  140. _channel.BufferManager.SetIndexBuffer(br, IndexType.UInt);
  141. _context.Renderer.Pipeline.DrawIndexed(inlineIndexCount, 1, firstIndex, firstVertex, firstInstance);
  142. }
  143. else if (_drawState.DrawIndexed)
  144. {
  145. int firstVertex = (int)_state.State.FirstVertex;
  146. _context.Renderer.Pipeline.DrawIndexed(indexCount, 1, firstIndex, firstVertex, firstInstance);
  147. }
  148. else
  149. {
  150. var drawState = _state.State.VertexBufferDrawState;
  151. _context.Renderer.Pipeline.Draw(drawState.Count, 1, drawState.First, firstInstance);
  152. }
  153. _drawState.DrawIndexed = false;
  154. if (renderEnable == ConditionalRenderEnabled.Host)
  155. {
  156. _context.Renderer.Pipeline.EndHostConditionalRendering();
  157. }
  158. }
  159. /// <summary>
  160. /// Starts draw.
  161. /// This sets primitive type and instanced draw parameters.
  162. /// </summary>
  163. /// <param name="argument">Method call argument</param>
  164. public void DrawBegin(int argument)
  165. {
  166. bool incrementInstance = (argument & (1 << 26)) != 0;
  167. bool resetInstance = (argument & (1 << 27)) == 0;
  168. if (_state.State.PrimitiveTypeOverrideEnable)
  169. {
  170. PrimitiveTypeOverride typeOverride = _state.State.PrimitiveTypeOverride;
  171. DrawBegin(incrementInstance, resetInstance, typeOverride.Convert());
  172. }
  173. else
  174. {
  175. PrimitiveType type = (PrimitiveType)(argument & 0xffff);
  176. DrawBegin(incrementInstance, resetInstance, type.Convert());
  177. }
  178. }
  179. /// <summary>
  180. /// Starts draw.
  181. /// This sets primitive type and instanced draw parameters.
  182. /// </summary>
  183. /// <param name="incrementInstance">Indicates if the current instance should be incremented</param>
  184. /// <param name="resetInstance">Indicates if the current instance should be set to zero</param>
  185. /// <param name="topology">Primitive topology</param>
  186. private void DrawBegin(bool incrementInstance, bool resetInstance, PrimitiveTopology topology)
  187. {
  188. if (incrementInstance)
  189. {
  190. _instanceIndex++;
  191. }
  192. else if (resetInstance)
  193. {
  194. PerformDeferredDraws();
  195. _instanceIndex = 0;
  196. }
  197. if (_drawState.Topology != topology || !_topologySet)
  198. {
  199. _context.Renderer.Pipeline.SetPrimitiveTopology(topology);
  200. _drawState.Topology = topology;
  201. _topologySet = true;
  202. }
  203. }
  204. /// <summary>
  205. /// Sets the index buffer count.
  206. /// This also sets internal state that indicates that the next draw is an indexed draw.
  207. /// </summary>
  208. /// <param name="argument">Method call argument</param>
  209. public void SetIndexBufferCount(int argument)
  210. {
  211. _drawState.DrawIndexed = true;
  212. }
  213. /// <summary>
  214. /// Performs a indexed draw with a low number of index buffer elements.
  215. /// </summary>
  216. /// <param name="engine">3D engine where this method is being called</param>
  217. /// <param name="argument">Method call argument</param>
  218. public void DrawIndexedSmall(ThreedClass engine, int argument)
  219. {
  220. DrawIndexedSmall(engine, argument, false);
  221. }
  222. /// <summary>
  223. /// Performs a indexed draw with a low number of index buffer elements.
  224. /// </summary>
  225. /// <param name="engine">3D engine where this method is being called</param>
  226. /// <param name="argument">Method call argument</param>
  227. public void DrawIndexedSmall2(ThreedClass engine, int argument)
  228. {
  229. DrawIndexedSmall(engine, argument);
  230. }
  231. /// <summary>
  232. /// Performs a indexed draw with a low number of index buffer elements,
  233. /// while also pre-incrementing the current instance value.
  234. /// </summary>
  235. /// <param name="engine">3D engine where this method is being called</param>
  236. /// <param name="argument">Method call argument</param>
  237. public void DrawIndexedSmallIncInstance(ThreedClass engine, int argument)
  238. {
  239. DrawIndexedSmall(engine, argument, true);
  240. }
  241. /// <summary>
  242. /// Performs a indexed draw with a low number of index buffer elements,
  243. /// while also pre-incrementing the current instance value.
  244. /// </summary>
  245. /// <param name="engine">3D engine where this method is being called</param>
  246. /// <param name="argument">Method call argument</param>
  247. public void DrawIndexedSmallIncInstance2(ThreedClass engine, int argument)
  248. {
  249. DrawIndexedSmallIncInstance(engine, argument);
  250. }
  251. /// <summary>
  252. /// Performs a indexed draw with a low number of index buffer elements,
  253. /// while optionally also pre-incrementing the current instance value.
  254. /// </summary>
  255. /// <param name="engine">3D engine where this method is being called</param>
  256. /// <param name="argument">Method call argument</param>
  257. /// <param name="instanced">True to increment the current instance value, false otherwise</param>
  258. private void DrawIndexedSmall(ThreedClass engine, int argument, bool instanced)
  259. {
  260. PrimitiveTypeOverride typeOverride = _state.State.PrimitiveTypeOverride;
  261. DrawBegin(instanced, !instanced, typeOverride.Convert());
  262. int firstIndex = argument & 0xffff;
  263. int indexCount = (argument >> 16) & 0xfff;
  264. bool oldDrawIndexed = _drawState.DrawIndexed;
  265. _drawState.DrawIndexed = true;
  266. engine.ForceStateDirty(IndexBufferCountMethodOffset * 4);
  267. DrawEnd(engine, firstIndex, indexCount);
  268. _drawState.DrawIndexed = oldDrawIndexed;
  269. }
  270. /// <summary>
  271. /// Performs a texture draw with a source texture and sampler ID, along with source
  272. /// and destination coordinates and sizes.
  273. /// </summary>
  274. /// <param name="engine">3D engine where this method is being called</param>
  275. /// <param name="argument">Method call argument</param>
  276. public void DrawTexture(ThreedClass engine, int argument)
  277. {
  278. static float FixedToFloat(int fixedValue)
  279. {
  280. return fixedValue * (1f / 4096);
  281. }
  282. float dstX0 = FixedToFloat(_state.State.DrawTextureDstX);
  283. float dstY0 = FixedToFloat(_state.State.DrawTextureDstY);
  284. float dstWidth = FixedToFloat(_state.State.DrawTextureDstWidth);
  285. float dstHeight = FixedToFloat(_state.State.DrawTextureDstHeight);
  286. // TODO: Confirm behaviour on hardware.
  287. // When this is active, the origin appears to be on the bottom.
  288. if (_state.State.YControl.HasFlag(YControl.NegateY))
  289. {
  290. dstY0 -= dstHeight;
  291. }
  292. float dstX1 = dstX0 + dstWidth;
  293. float dstY1 = dstY0 + dstHeight;
  294. float srcX0 = FixedToFloat(_state.State.DrawTextureSrcX);
  295. float srcY0 = FixedToFloat(_state.State.DrawTextureSrcY);
  296. float srcX1 = ((float)_state.State.DrawTextureDuDx / (1UL << 32)) * dstWidth + srcX0;
  297. float srcY1 = ((float)_state.State.DrawTextureDvDy / (1UL << 32)) * dstHeight + srcY0;
  298. engine.UpdateState();
  299. int textureId = _state.State.DrawTextureTextureId;
  300. int samplerId = _state.State.DrawTextureSamplerId;
  301. (var texture, var sampler) = _channel.TextureManager.GetGraphicsTextureAndSampler(textureId, samplerId);
  302. srcX0 *= texture.ScaleFactor;
  303. srcY0 *= texture.ScaleFactor;
  304. srcX1 *= texture.ScaleFactor;
  305. srcY1 *= texture.ScaleFactor;
  306. float dstScale = _channel.TextureManager.RenderTargetScale;
  307. dstX0 *= dstScale;
  308. dstY0 *= dstScale;
  309. dstX1 *= dstScale;
  310. dstY1 *= dstScale;
  311. _context.Renderer.Pipeline.DrawTexture(
  312. texture?.HostTexture,
  313. sampler?.GetHostSampler(texture),
  314. new Extents2DF(srcX0, srcY0, srcX1, srcY1),
  315. new Extents2DF(dstX0, dstY0, dstX1, dstY1));
  316. }
  317. /// <summary>
  318. /// Performs a indirect multi-draw, with parameters from a GPU buffer.
  319. /// </summary>
  320. /// <param name="engine">3D engine where this method is being called</param>
  321. /// <param name="topology">Primitive topology</param>
  322. /// <param name="indirectBuffer">GPU buffer with the draw parameters, such as count, first index, etc</param>
  323. /// <param name="parameterBuffer">GPU buffer with the draw count</param>
  324. /// <param name="maxDrawCount">Maximum number of draws that can be made</param>
  325. /// <param name="stride">Distance in bytes between each element on the <paramref name="indirectBuffer"/> array</param>
  326. public void MultiDrawIndirectCount(
  327. ThreedClass engine,
  328. int indexCount,
  329. PrimitiveTopology topology,
  330. BufferRange indirectBuffer,
  331. BufferRange parameterBuffer,
  332. int maxDrawCount,
  333. int stride)
  334. {
  335. engine.Write(IndexBufferCountMethodOffset * 4, indexCount);
  336. _context.Renderer.Pipeline.SetPrimitiveTopology(topology);
  337. _drawState.Topology = topology;
  338. _topologySet = true;
  339. ConditionalRenderEnabled renderEnable = ConditionalRendering.GetRenderEnable(
  340. _context,
  341. _channel.MemoryManager,
  342. _state.State.RenderEnableAddress,
  343. _state.State.RenderEnableCondition);
  344. if (renderEnable == ConditionalRenderEnabled.False)
  345. {
  346. _drawState.DrawIndexed = false;
  347. return;
  348. }
  349. _drawState.FirstIndex = _state.State.IndexBufferState.First;
  350. _drawState.IndexCount = indexCount;
  351. engine.UpdateState();
  352. if (_drawState.DrawIndexed)
  353. {
  354. _context.Renderer.Pipeline.MultiDrawIndexedIndirectCount(indirectBuffer, parameterBuffer, maxDrawCount, stride);
  355. }
  356. else
  357. {
  358. _context.Renderer.Pipeline.MultiDrawIndirectCount(indirectBuffer, parameterBuffer, maxDrawCount, stride);
  359. }
  360. _drawState.DrawIndexed = false;
  361. if (renderEnable == ConditionalRenderEnabled.Host)
  362. {
  363. _context.Renderer.Pipeline.EndHostConditionalRendering();
  364. }
  365. }
  366. /// <summary>
  367. /// Perform any deferred draws.
  368. /// This is used for instanced draws.
  369. /// Since each instance is a separate draw, we defer the draw and accumulate the instance count.
  370. /// Once we detect the last instanced draw, then we perform the host instanced draw,
  371. /// with the accumulated instance count.
  372. /// </summary>
  373. public void PerformDeferredDraws()
  374. {
  375. // Perform any pending instanced draw.
  376. if (_instancedDrawPending)
  377. {
  378. _instancedDrawPending = false;
  379. bool indexedInline = _instancedIndexedInline;
  380. if (_instancedIndexed || indexedInline)
  381. {
  382. if (indexedInline)
  383. {
  384. int inlineIndexCount = _drawState.IbStreamer.GetAndResetInlineIndexCount();
  385. BufferRange br = new BufferRange(_drawState.IbStreamer.GetInlineIndexBuffer(), 0, inlineIndexCount * 4);
  386. _channel.BufferManager.SetIndexBuffer(br, IndexType.UInt);
  387. }
  388. _context.Renderer.Pipeline.DrawIndexed(
  389. _instancedIndexCount,
  390. _instanceIndex + 1,
  391. _instancedFirstIndex,
  392. _instancedFirstVertex,
  393. _instancedFirstInstance);
  394. }
  395. else
  396. {
  397. _context.Renderer.Pipeline.Draw(
  398. _instancedDrawStateCount,
  399. _instanceIndex + 1,
  400. _instancedDrawStateFirst,
  401. _instancedFirstInstance);
  402. }
  403. }
  404. }
  405. /// <summary>
  406. /// Clears the current color and depth-stencil buffers.
  407. /// Which buffers should be cleared is also specified on the argument.
  408. /// </summary>
  409. /// <param name="engine">3D engine where this method is being called</param>
  410. /// <param name="argument">Method call argument</param>
  411. public void Clear(ThreedClass engine, int argument)
  412. {
  413. ConditionalRenderEnabled renderEnable = ConditionalRendering.GetRenderEnable(
  414. _context,
  415. _channel.MemoryManager,
  416. _state.State.RenderEnableAddress,
  417. _state.State.RenderEnableCondition);
  418. if (renderEnable == ConditionalRenderEnabled.False)
  419. {
  420. return;
  421. }
  422. int index = (argument >> 6) & 0xf;
  423. engine.UpdateRenderTargetState(useControl: false, singleUse: index);
  424. // If there is a mismatch on the host clip region and the one explicitly defined by the guest
  425. // on the screen scissor state, then we need to force only one texture to be bound to avoid
  426. // host clipping.
  427. var screenScissorState = _state.State.ScreenScissorState;
  428. // Must happen after UpdateRenderTargetState to have up-to-date clip region values.
  429. bool clipMismatch = (screenScissorState.X | screenScissorState.Y) != 0 ||
  430. screenScissorState.Width != _channel.TextureManager.ClipRegionWidth ||
  431. screenScissorState.Height != _channel.TextureManager.ClipRegionHeight;
  432. bool clearAffectedByStencilMask = (_state.State.ClearFlags & 1) != 0;
  433. bool clearAffectedByScissor = (_state.State.ClearFlags & 0x100) != 0;
  434. bool needsCustomScissor = !clearAffectedByScissor || clipMismatch;
  435. // Scissor and rasterizer discard also affect clears.
  436. ulong updateMask = 1UL << StateUpdater.RasterizerStateIndex;
  437. if (!needsCustomScissor)
  438. {
  439. updateMask |= 1UL << StateUpdater.ScissorStateIndex;
  440. }
  441. engine.UpdateState(updateMask);
  442. if (needsCustomScissor)
  443. {
  444. int scissorX = screenScissorState.X;
  445. int scissorY = screenScissorState.Y;
  446. int scissorW = screenScissorState.Width;
  447. int scissorH = screenScissorState.Height;
  448. if (clearAffectedByScissor && _state.State.ScissorState[0].Enable)
  449. {
  450. ref var scissorState = ref _state.State.ScissorState[0];
  451. scissorX = Math.Max(scissorX, scissorState.X1);
  452. scissorY = Math.Max(scissorY, scissorState.Y1);
  453. scissorW = Math.Min(scissorW, scissorState.X2 - scissorState.X1);
  454. scissorH = Math.Min(scissorH, scissorState.Y2 - scissorState.Y1);
  455. }
  456. float scale = _channel.TextureManager.RenderTargetScale;
  457. if (scale != 1f)
  458. {
  459. scissorX = (int)(scissorX * scale);
  460. scissorY = (int)(scissorY * scale);
  461. scissorW = (int)MathF.Ceiling(scissorW * scale);
  462. scissorH = (int)MathF.Ceiling(scissorH * scale);
  463. }
  464. _context.Renderer.Pipeline.SetScissor(0, true, scissorX, scissorY, scissorW, scissorH);
  465. }
  466. if (clipMismatch)
  467. {
  468. _channel.TextureManager.UpdateRenderTarget(index);
  469. }
  470. else
  471. {
  472. _channel.TextureManager.UpdateRenderTargets();
  473. }
  474. bool clearDepth = (argument & 1) != 0;
  475. bool clearStencil = (argument & 2) != 0;
  476. uint componentMask = (uint)((argument >> 2) & 0xf);
  477. if (componentMask != 0)
  478. {
  479. var clearColor = _state.State.ClearColors;
  480. ColorF color = new ColorF(clearColor.Red, clearColor.Green, clearColor.Blue, clearColor.Alpha);
  481. _context.Renderer.Pipeline.ClearRenderTargetColor(index, componentMask, color);
  482. }
  483. if (clearDepth || clearStencil)
  484. {
  485. float depthValue = _state.State.ClearDepthValue;
  486. int stencilValue = (int)_state.State.ClearStencilValue;
  487. int stencilMask = 0;
  488. if (clearStencil)
  489. {
  490. stencilMask = clearAffectedByStencilMask ? _state.State.StencilTestState.FrontMask : 0xff;
  491. }
  492. if (clipMismatch)
  493. {
  494. _channel.TextureManager.UpdateRenderTargetDepthStencil();
  495. }
  496. _context.Renderer.Pipeline.ClearRenderTargetDepthStencil(
  497. depthValue,
  498. clearDepth,
  499. stencilValue,
  500. stencilMask);
  501. }
  502. if (needsCustomScissor)
  503. {
  504. engine.UpdateScissorState();
  505. }
  506. engine.UpdateRenderTargetState(useControl: true);
  507. if (renderEnable == ConditionalRenderEnabled.Host)
  508. {
  509. _context.Renderer.Pipeline.EndHostConditionalRendering();
  510. }
  511. }
  512. }
  513. }