DrawManager.cs 23 KB

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