DrawManager.cs 30 KB

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