DrawManager.cs 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986
  1. using Ryujinx.Graphics.GAL;
  2. using Ryujinx.Graphics.Gpu.Engine.Threed.ComputeDraw;
  3. using Ryujinx.Graphics.Gpu.Engine.Types;
  4. using Ryujinx.Graphics.Gpu.Image;
  5. using Ryujinx.Graphics.Gpu.Memory;
  6. using Ryujinx.Memory.Range;
  7. using System;
  8. namespace Ryujinx.Graphics.Gpu.Engine.Threed
  9. {
  10. /// <summary>
  11. /// Draw manager.
  12. /// </summary>
  13. class DrawManager : IDisposable
  14. {
  15. // Since we don't know the index buffer size for indirect draws,
  16. // we must assume a minimum and maximum size and use that for buffer data update purposes.
  17. private const int MinIndirectIndexCount = 0x10000;
  18. private const int MaxIndirectIndexCount = 0x4000000;
  19. private readonly GpuContext _context;
  20. private readonly GpuChannel _channel;
  21. private readonly DeviceStateWithShadow<ThreedClassState> _state;
  22. private readonly DrawState _drawState;
  23. private readonly SpecializationStateUpdater _currentSpecState;
  24. private readonly VtgAsCompute _vtgAsCompute;
  25. private bool _topologySet;
  26. private bool _instancedDrawPending;
  27. private bool _instancedIndexed;
  28. private bool _instancedIndexedInline;
  29. private int _instancedFirstIndex;
  30. private int _instancedFirstVertex;
  31. private int _instancedFirstInstance;
  32. private int _instancedIndexCount;
  33. private int _instancedDrawStateFirst;
  34. private int _instancedDrawStateCount;
  35. private int _instanceIndex;
  36. private const int VertexBufferFirstMethodOffset = 0x35d;
  37. private const int IndexBufferCountMethodOffset = 0x5f8;
  38. /// <summary>
  39. /// Creates a new instance of the draw manager.
  40. /// </summary>
  41. /// <param name="context">GPU context</param>
  42. /// <param name="channel">GPU channel</param>
  43. /// <param name="state">Channel state</param>
  44. /// <param name="drawState">Draw state</param>
  45. /// <param name="spec">Specialization state updater</param>
  46. public DrawManager(GpuContext context, GpuChannel channel, DeviceStateWithShadow<ThreedClassState> state, DrawState drawState, SpecializationStateUpdater spec)
  47. {
  48. _context = context;
  49. _channel = channel;
  50. _state = state;
  51. _drawState = drawState;
  52. _currentSpecState = spec;
  53. _vtgAsCompute = new(context, channel, state);
  54. }
  55. /// <summary>
  56. /// Marks the entire state as dirty, forcing a full host state update before the next draw.
  57. /// </summary>
  58. public void ForceStateDirty()
  59. {
  60. _topologySet = false;
  61. }
  62. /// <summary>
  63. /// Pushes four 8-bit index buffer elements.
  64. /// </summary>
  65. /// <param name="argument">Method call argument</param>
  66. public void VbElementU8(int argument)
  67. {
  68. _drawState.IbStreamer.VbElementU8(_context.Renderer, argument);
  69. }
  70. /// <summary>
  71. /// Pushes two 16-bit index buffer elements.
  72. /// </summary>
  73. /// <param name="argument">Method call argument</param>
  74. public void VbElementU16(int argument)
  75. {
  76. _drawState.IbStreamer.VbElementU16(_context.Renderer, argument);
  77. }
  78. /// <summary>
  79. /// Pushes one 32-bit index buffer element.
  80. /// </summary>
  81. /// <param name="argument">Method call argument</param>
  82. public void VbElementU32(int argument)
  83. {
  84. _drawState.IbStreamer.VbElementU32(_context.Renderer, argument);
  85. }
  86. /// <summary>
  87. /// Finishes the draw call.
  88. /// This draws geometry on the bound buffers based on the current GPU state.
  89. /// </summary>
  90. /// <param name="engine">3D engine where this method is being called</param>
  91. /// <param name="argument">Method call argument</param>
  92. public void DrawEnd(ThreedClass engine, int argument)
  93. {
  94. _drawState.DrawUsesEngineState = true;
  95. DrawEnd(
  96. engine,
  97. _state.State.IndexBufferState.First,
  98. (int)_state.State.IndexBufferCount,
  99. _state.State.VertexBufferDrawState.First,
  100. _state.State.VertexBufferDrawState.Count);
  101. }
  102. /// <summary>
  103. /// Finishes the draw call.
  104. /// This draws geometry on the bound buffers based on the current GPU state.
  105. /// </summary>
  106. /// <param name="engine">3D engine where this method is being called</param>
  107. /// <param name="firstIndex">Index of the first index buffer element used on the draw</param>
  108. /// <param name="indexCount">Number of index buffer elements used on the draw</param>
  109. /// <param name="drawFirstVertex">Index of the first vertex used on the draw</param>
  110. /// <param name="drawVertexCount">Number of vertices used on the draw</param>
  111. private void DrawEnd(ThreedClass engine, int firstIndex, int indexCount, int drawFirstVertex, int drawVertexCount)
  112. {
  113. ConditionalRenderEnabled renderEnable = ConditionalRendering.GetRenderEnable(
  114. _context,
  115. _channel.MemoryManager,
  116. _state.State.RenderEnableAddress,
  117. _state.State.RenderEnableCondition);
  118. if (renderEnable == ConditionalRenderEnabled.False || _instancedDrawPending)
  119. {
  120. if (renderEnable == ConditionalRenderEnabled.False)
  121. {
  122. PerformDeferredDraws(engine);
  123. }
  124. _drawState.DrawIndexed = false;
  125. if (renderEnable == ConditionalRenderEnabled.Host)
  126. {
  127. _context.Renderer.Pipeline.EndHostConditionalRendering();
  128. }
  129. return;
  130. }
  131. _drawState.FirstIndex = firstIndex;
  132. _drawState.IndexCount = indexCount;
  133. _drawState.DrawFirstVertex = drawFirstVertex;
  134. _drawState.DrawVertexCount = drawVertexCount;
  135. _currentSpecState.SetHasConstantBufferDrawParameters(false);
  136. engine.UpdateState();
  137. bool instanced = _drawState.VsUsesInstanceId || _drawState.IsAnyVbInstanced;
  138. if (instanced)
  139. {
  140. _instancedDrawPending = true;
  141. int ibCount = _drawState.IbStreamer.InlineIndexCount;
  142. _instancedIndexed = _drawState.DrawIndexed;
  143. _instancedIndexedInline = ibCount != 0;
  144. _instancedFirstIndex = firstIndex;
  145. _instancedFirstVertex = (int)_state.State.FirstVertex;
  146. _instancedFirstInstance = (int)_state.State.FirstInstance;
  147. _instancedIndexCount = ibCount != 0 ? ibCount : indexCount;
  148. _instancedDrawStateFirst = drawFirstVertex;
  149. _instancedDrawStateCount = drawVertexCount;
  150. _drawState.DrawIndexed = false;
  151. if (renderEnable == ConditionalRenderEnabled.Host)
  152. {
  153. _context.Renderer.Pipeline.EndHostConditionalRendering();
  154. }
  155. return;
  156. }
  157. int firstInstance = (int)_state.State.FirstInstance;
  158. int inlineIndexCount = _drawState.IbStreamer.GetAndResetInlineIndexCount(_context.Renderer);
  159. if (inlineIndexCount != 0)
  160. {
  161. int firstVertex = (int)_state.State.FirstVertex;
  162. BufferRange br = new(_drawState.IbStreamer.GetInlineIndexBuffer(), 0, inlineIndexCount * 4);
  163. _channel.BufferManager.SetIndexBuffer(br, IndexType.UInt);
  164. DrawImpl(engine, inlineIndexCount, 1, firstIndex, firstVertex, firstInstance, indexed: true);
  165. }
  166. else if (_drawState.DrawIndexed)
  167. {
  168. int firstVertex = (int)_state.State.FirstVertex;
  169. DrawImpl(engine, indexCount, 1, firstIndex, firstVertex, firstInstance, indexed: true);
  170. }
  171. else
  172. {
  173. DrawImpl(engine, drawVertexCount, 1, 0, drawFirstVertex, firstInstance, indexed: false);
  174. }
  175. _drawState.DrawIndexed = false;
  176. if (renderEnable == ConditionalRenderEnabled.Host)
  177. {
  178. _context.Renderer.Pipeline.EndHostConditionalRendering();
  179. }
  180. }
  181. /// <summary>
  182. /// Starts draw.
  183. /// This sets primitive type and instanced draw parameters.
  184. /// </summary>
  185. /// <param name="engine">3D engine where this method is being called</param>
  186. /// <param name="argument">Method call argument</param>
  187. public void DrawBegin(ThreedClass engine, int argument)
  188. {
  189. bool incrementInstance = (argument & (1 << 26)) != 0;
  190. bool resetInstance = (argument & (1 << 27)) == 0;
  191. PrimitiveType type = (PrimitiveType)(argument & 0xffff);
  192. DrawBegin(engine, incrementInstance, resetInstance, type);
  193. }
  194. /// <summary>
  195. /// Starts draw.
  196. /// This sets primitive type and instanced draw parameters.
  197. /// </summary>
  198. /// <param name="engine">3D engine where this method is being called</param>
  199. /// <param name="incrementInstance">Indicates if the current instance should be incremented</param>
  200. /// <param name="resetInstance">Indicates if the current instance should be set to zero</param>
  201. /// <param name="primitiveType">Primitive type</param>
  202. private void DrawBegin(ThreedClass engine, bool incrementInstance, bool resetInstance, PrimitiveType primitiveType)
  203. {
  204. if (incrementInstance)
  205. {
  206. _instanceIndex++;
  207. }
  208. else if (resetInstance)
  209. {
  210. PerformDeferredDraws(engine);
  211. _instanceIndex = 0;
  212. }
  213. PrimitiveTopology topology;
  214. if (_state.State.PrimitiveTypeOverrideEnable)
  215. {
  216. PrimitiveTypeOverride typeOverride = _state.State.PrimitiveTypeOverride;
  217. topology = typeOverride.Convert();
  218. }
  219. else
  220. {
  221. topology = primitiveType.Convert();
  222. }
  223. UpdateTopology(topology);
  224. }
  225. /// <summary>
  226. /// Updates the current primitive topology if needed.
  227. /// </summary>
  228. /// <param name="topology">New primitive topology</param>
  229. private void UpdateTopology(PrimitiveTopology topology)
  230. {
  231. if (_drawState.Topology != topology || !_topologySet)
  232. {
  233. _context.Renderer.Pipeline.SetPrimitiveTopology(topology);
  234. _currentSpecState.SetTopology(topology);
  235. _drawState.Topology = topology;
  236. _topologySet = true;
  237. }
  238. }
  239. /// <summary>
  240. /// Sets the index buffer count.
  241. /// This also sets internal state that indicates that the next draw is an indexed draw.
  242. /// </summary>
  243. /// <param name="argument">Method call argument</param>
  244. public void SetIndexBufferCount(int argument)
  245. {
  246. _drawState.DrawIndexed = true;
  247. }
  248. // TODO: Verify if the index type is implied from the method that is called,
  249. // or if it uses the state index type on hardware.
  250. /// <summary>
  251. /// Performs a indexed draw with 8-bit index buffer elements.
  252. /// </summary>
  253. /// <param name="engine">3D engine where this method is being called</param>
  254. /// <param name="argument">Method call argument</param>
  255. public void DrawIndexBuffer8BeginEndInstanceFirst(ThreedClass engine, int argument)
  256. {
  257. DrawIndexBufferBeginEndInstance(engine, argument, false);
  258. }
  259. /// <summary>
  260. /// Performs a indexed draw with 16-bit index buffer elements.
  261. /// </summary>
  262. /// <param name="engine">3D engine where this method is being called</param>
  263. /// <param name="argument">Method call argument</param>
  264. public void DrawIndexBuffer16BeginEndInstanceFirst(ThreedClass engine, int argument)
  265. {
  266. DrawIndexBufferBeginEndInstance(engine, argument, false);
  267. }
  268. /// <summary>
  269. /// Performs a indexed draw with 32-bit index buffer elements.
  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 DrawIndexBuffer32BeginEndInstanceFirst(ThreedClass engine, int argument)
  274. {
  275. DrawIndexBufferBeginEndInstance(engine, argument, false);
  276. }
  277. /// <summary>
  278. /// Performs a indexed draw with 8-bit index buffer elements,
  279. /// while also pre-incrementing the current instance value.
  280. /// </summary>
  281. /// <param name="engine">3D engine where this method is being called</param>
  282. /// <param name="argument">Method call argument</param>
  283. public void DrawIndexBuffer8BeginEndInstanceSubsequent(ThreedClass engine, int argument)
  284. {
  285. DrawIndexBufferBeginEndInstance(engine, argument, true);
  286. }
  287. /// <summary>
  288. /// Performs a indexed draw with 16-bit index buffer elements,
  289. /// while also pre-incrementing the current instance value.
  290. /// </summary>
  291. /// <param name="engine">3D engine where this method is being called</param>
  292. /// <param name="argument">Method call argument</param>
  293. public void DrawIndexBuffer16BeginEndInstanceSubsequent(ThreedClass engine, int argument)
  294. {
  295. DrawIndexBufferBeginEndInstance(engine, argument, true);
  296. }
  297. /// <summary>
  298. /// Performs a indexed draw with 32-bit index buffer elements,
  299. /// while also pre-incrementing the current instance value.
  300. /// </summary>
  301. /// <param name="engine">3D engine where this method is being called</param>
  302. /// <param name="argument">Method call argument</param>
  303. public void DrawIndexBuffer32BeginEndInstanceSubsequent(ThreedClass engine, int argument)
  304. {
  305. DrawIndexBufferBeginEndInstance(engine, argument, true);
  306. }
  307. /// <summary>
  308. /// Performs a indexed draw with a low number of index buffer elements,
  309. /// while optionally also pre-incrementing the current instance value.
  310. /// </summary>
  311. /// <param name="engine">3D engine where this method is being called</param>
  312. /// <param name="argument">Method call argument</param>
  313. /// <param name="instanced">True to increment the current instance value, false otherwise</param>
  314. private void DrawIndexBufferBeginEndInstance(ThreedClass engine, int argument, bool instanced)
  315. {
  316. DrawBegin(engine, instanced, !instanced, (PrimitiveType)((argument >> 28) & 0xf));
  317. int firstIndex = argument & 0xffff;
  318. int indexCount = (argument >> 16) & 0xfff;
  319. bool oldDrawIndexed = _drawState.DrawIndexed;
  320. _drawState.DrawIndexed = true;
  321. _drawState.DrawUsesEngineState = false;
  322. engine.ForceStateDirty(IndexBufferCountMethodOffset * 4);
  323. DrawEnd(engine, firstIndex, indexCount, 0, 0);
  324. _drawState.DrawIndexed = oldDrawIndexed;
  325. }
  326. /// <summary>
  327. /// Performs a non-indexed draw with the specified topology, index and count.
  328. /// </summary>
  329. /// <param name="engine">3D engine where this method is being called</param>
  330. /// <param name="argument">Method call argument</param>
  331. public void DrawVertexArrayBeginEndInstanceFirst(ThreedClass engine, int argument)
  332. {
  333. DrawVertexArrayBeginEndInstance(engine, argument, false);
  334. }
  335. /// <summary>
  336. /// Performs a non-indexed draw with the specified topology, index and count,
  337. /// while incrementing the current instance.
  338. /// </summary>
  339. /// <param name="engine">3D engine where this method is being called</param>
  340. /// <param name="argument">Method call argument</param>
  341. public void DrawVertexArrayBeginEndInstanceSubsequent(ThreedClass engine, int argument)
  342. {
  343. DrawVertexArrayBeginEndInstance(engine, argument, true);
  344. }
  345. /// <summary>
  346. /// Performs a indexed draw with a low number of index buffer elements,
  347. /// while optionally also pre-incrementing the current instance value.
  348. /// </summary>
  349. /// <param name="engine">3D engine where this method is being called</param>
  350. /// <param name="argument">Method call argument</param>
  351. /// <param name="instanced">True to increment the current instance value, false otherwise</param>
  352. private void DrawVertexArrayBeginEndInstance(ThreedClass engine, int argument, bool instanced)
  353. {
  354. DrawBegin(engine, instanced, !instanced, (PrimitiveType)((argument >> 28) & 0xf));
  355. int firstVertex = argument & 0xffff;
  356. int vertexCount = (argument >> 16) & 0xfff;
  357. bool oldDrawIndexed = _drawState.DrawIndexed;
  358. _drawState.DrawIndexed = false;
  359. _drawState.DrawUsesEngineState = false;
  360. engine.ForceStateDirty(VertexBufferFirstMethodOffset * 4);
  361. DrawEnd(engine, 0, 0, firstVertex, vertexCount);
  362. _drawState.DrawIndexed = oldDrawIndexed;
  363. }
  364. /// <summary>
  365. /// Performs a texture draw with a source texture and sampler ID, along with source
  366. /// and destination coordinates and sizes.
  367. /// </summary>
  368. /// <param name="engine">3D engine where this method is being called</param>
  369. /// <param name="argument">Method call argument</param>
  370. public void DrawTexture(ThreedClass engine, int argument)
  371. {
  372. static float FixedToFloat(int fixedValue)
  373. {
  374. return fixedValue * (1f / 4096);
  375. }
  376. float dstX0 = FixedToFloat(_state.State.DrawTextureDstX);
  377. float dstY0 = FixedToFloat(_state.State.DrawTextureDstY);
  378. float dstWidth = FixedToFloat(_state.State.DrawTextureDstWidth);
  379. float dstHeight = FixedToFloat(_state.State.DrawTextureDstHeight);
  380. // TODO: Confirm behaviour on hardware.
  381. // When this is active, the origin appears to be on the bottom.
  382. if (_state.State.YControl.HasFlag(YControl.NegateY))
  383. {
  384. dstY0 -= dstHeight;
  385. }
  386. float dstX1 = dstX0 + dstWidth;
  387. float dstY1 = dstY0 + dstHeight;
  388. float srcX0 = FixedToFloat(_state.State.DrawTextureSrcX);
  389. float srcY0 = FixedToFloat(_state.State.DrawTextureSrcY);
  390. float srcX1 = ((float)_state.State.DrawTextureDuDx / (1UL << 32)) * dstWidth + srcX0;
  391. float srcY1 = ((float)_state.State.DrawTextureDvDy / (1UL << 32)) * dstHeight + srcY0;
  392. engine.UpdateState(ulong.MaxValue & ~(1UL << StateUpdater.ShaderStateIndex));
  393. _channel.TextureManager.UpdateRenderTargets();
  394. int textureId = _state.State.DrawTextureTextureId;
  395. int samplerId = _state.State.DrawTextureSamplerId;
  396. (Image.Texture texture, Sampler sampler) = _channel.TextureManager.GetGraphicsTextureAndSampler(textureId, samplerId);
  397. srcX0 *= texture.ScaleFactor;
  398. srcY0 *= texture.ScaleFactor;
  399. srcX1 *= texture.ScaleFactor;
  400. srcY1 *= texture.ScaleFactor;
  401. float dstScale = _channel.TextureManager.RenderTargetScale;
  402. dstX0 *= dstScale;
  403. dstY0 *= dstScale;
  404. dstX1 *= dstScale;
  405. dstY1 *= dstScale;
  406. _context.Renderer.Pipeline.DrawTexture(
  407. texture?.HostTexture,
  408. sampler?.GetHostSampler(texture),
  409. new Extents2DF(srcX0, srcY0, srcX1, srcY1),
  410. new Extents2DF(dstX0, dstY0, dstX1, dstY1));
  411. }
  412. /// <summary>
  413. /// Performs a indexed or non-indexed draw.
  414. /// </summary>
  415. /// <param name="engine">3D engine where this method is being called</param>
  416. /// <param name="topology">Primitive topology</param>
  417. /// <param name="count">Index count for indexed draws, vertex count for non-indexed draws</param>
  418. /// <param name="instanceCount">Instance count</param>
  419. /// <param name="firstIndex">First index on the index buffer for indexed draws, ignored for non-indexed draws</param>
  420. /// <param name="firstVertex">First vertex on the vertex buffer</param>
  421. /// <param name="firstInstance">First instance</param>
  422. /// <param name="indexed">True if the draw is indexed, false otherwise</param>
  423. public void Draw(
  424. ThreedClass engine,
  425. PrimitiveTopology topology,
  426. int count,
  427. int instanceCount,
  428. int firstIndex,
  429. int firstVertex,
  430. int firstInstance,
  431. bool indexed)
  432. {
  433. UpdateTopology(topology);
  434. ConditionalRenderEnabled renderEnable = ConditionalRendering.GetRenderEnable(
  435. _context,
  436. _channel.MemoryManager,
  437. _state.State.RenderEnableAddress,
  438. _state.State.RenderEnableCondition);
  439. if (renderEnable == ConditionalRenderEnabled.False)
  440. {
  441. _drawState.DrawIndexed = false;
  442. return;
  443. }
  444. if (indexed)
  445. {
  446. _drawState.FirstIndex = firstIndex;
  447. _drawState.IndexCount = count;
  448. _state.State.FirstVertex = (uint)firstVertex;
  449. engine.ForceStateDirty(IndexBufferCountMethodOffset * 4);
  450. }
  451. else
  452. {
  453. _drawState.DrawFirstVertex = firstVertex;
  454. _drawState.DrawVertexCount = count;
  455. engine.ForceStateDirty(VertexBufferFirstMethodOffset * 4);
  456. }
  457. _state.State.FirstInstance = (uint)firstInstance;
  458. _drawState.DrawIndexed = indexed;
  459. _drawState.DrawUsesEngineState = true;
  460. _currentSpecState.SetHasConstantBufferDrawParameters(true);
  461. engine.UpdateState();
  462. DrawImpl(engine, count, instanceCount, firstIndex, firstVertex, firstInstance, indexed);
  463. if (indexed)
  464. {
  465. _state.State.FirstVertex = 0;
  466. }
  467. _state.State.FirstInstance = 0;
  468. _drawState.DrawIndexed = false;
  469. if (renderEnable == ConditionalRenderEnabled.Host)
  470. {
  471. _context.Renderer.Pipeline.EndHostConditionalRendering();
  472. }
  473. }
  474. /// <summary>
  475. /// Performs a indexed or non-indexed draw.
  476. /// </summary>
  477. /// <param name="engine">3D engine where this method is being called</param>
  478. /// <param name="count">Index count for indexed draws, vertex count for non-indexed draws</param>
  479. /// <param name="instanceCount">Instance count</param>
  480. /// <param name="firstIndex">First index on the index buffer for indexed draws, ignored for non-indexed draws</param>
  481. /// <param name="firstVertex">First vertex on the vertex buffer</param>
  482. /// <param name="firstInstance">First instance</param>
  483. /// <param name="indexed">True if the draw is indexed, false otherwise</param>
  484. private void DrawImpl(
  485. ThreedClass engine,
  486. int count,
  487. int instanceCount,
  488. int firstIndex,
  489. int firstVertex,
  490. int firstInstance,
  491. bool indexed)
  492. {
  493. if (instanceCount > 1)
  494. {
  495. _channel.BufferManager.SetInstancedDrawVertexCount(count);
  496. }
  497. if (_drawState.VertexAsCompute != null)
  498. {
  499. _vtgAsCompute.DrawAsCompute(
  500. engine,
  501. _drawState.VertexAsCompute,
  502. _drawState.GeometryAsCompute,
  503. _drawState.VertexPassthrough,
  504. _drawState.Topology,
  505. count,
  506. instanceCount,
  507. firstIndex,
  508. firstVertex,
  509. firstInstance,
  510. indexed);
  511. if (_drawState.GeometryAsCompute != null)
  512. {
  513. // Geometry draws need to change the topology, so we need to set it here again
  514. // if we are going to do a regular draw.
  515. // Would have been better to do that on the callee, but doing it here
  516. // avoids having to pass the draw manager instance.
  517. ForceStateDirty();
  518. }
  519. }
  520. else
  521. {
  522. if (indexed)
  523. {
  524. _context.Renderer.Pipeline.DrawIndexed(count, instanceCount, firstIndex, firstVertex, firstInstance);
  525. }
  526. else
  527. {
  528. _context.Renderer.Pipeline.Draw(count, instanceCount, firstVertex, firstInstance);
  529. }
  530. }
  531. }
  532. /// <summary>
  533. /// Performs a indirect draw, with parameters from a GPU buffer.
  534. /// </summary>
  535. /// <param name="engine">3D engine where this method is being called</param>
  536. /// <param name="topology">Primitive topology</param>
  537. /// <param name="indirectBufferRange">Memory range of the buffer with the draw parameters, such as count, first index, etc</param>
  538. /// <param name="parameterBufferRange">Memory range of the buffer with the draw count</param>
  539. /// <param name="maxDrawCount">Maximum number of draws that can be made</param>
  540. /// <param name="stride">Distance in bytes between each entry on the data pointed to by <paramref name="indirectBufferAddress"/></param>
  541. /// <param name="indexCount">Maximum number of indices that the draw can consume</param>
  542. /// <param name="drawType">Type of the indirect draw, which can be indexed or non-indexed, with or without a draw count</param>
  543. public void DrawIndirect(
  544. ThreedClass engine,
  545. PrimitiveTopology topology,
  546. MultiRange indirectBufferRange,
  547. MultiRange parameterBufferRange,
  548. int maxDrawCount,
  549. int stride,
  550. int indexCount,
  551. IndirectDrawType drawType)
  552. {
  553. UpdateTopology(topology);
  554. ConditionalRenderEnabled renderEnable = ConditionalRendering.GetRenderEnable(
  555. _context,
  556. _channel.MemoryManager,
  557. _state.State.RenderEnableAddress,
  558. _state.State.RenderEnableCondition);
  559. if (renderEnable == ConditionalRenderEnabled.False)
  560. {
  561. _drawState.DrawIndexed = false;
  562. return;
  563. }
  564. PhysicalMemory memory = _channel.MemoryManager.Physical;
  565. bool hasCount = (drawType & IndirectDrawType.Count) != 0;
  566. bool indexed = (drawType & IndirectDrawType.Indexed) != 0;
  567. if (indexed)
  568. {
  569. indexCount = Math.Clamp(indexCount, MinIndirectIndexCount, MaxIndirectIndexCount);
  570. _drawState.FirstIndex = 0;
  571. _drawState.IndexCount = indexCount;
  572. engine.ForceStateDirty(IndexBufferCountMethodOffset * 4);
  573. }
  574. _drawState.DrawIndexed = indexed;
  575. _drawState.DrawIndirect = true;
  576. _drawState.DrawUsesEngineState = true;
  577. _currentSpecState.SetHasConstantBufferDrawParameters(true);
  578. engine.UpdateState();
  579. if (hasCount)
  580. {
  581. BufferRange indirectBuffer = memory.BufferCache.GetBufferRange(indirectBufferRange, BufferStage.Indirect);
  582. BufferRange parameterBuffer = memory.BufferCache.GetBufferRange(parameterBufferRange, BufferStage.Indirect);
  583. if (indexed)
  584. {
  585. _context.Renderer.Pipeline.DrawIndexedIndirectCount(indirectBuffer, parameterBuffer, maxDrawCount, stride);
  586. }
  587. else
  588. {
  589. _context.Renderer.Pipeline.DrawIndirectCount(indirectBuffer, parameterBuffer, maxDrawCount, stride);
  590. }
  591. }
  592. else
  593. {
  594. BufferRange indirectBuffer = memory.BufferCache.GetBufferRange(indirectBufferRange, BufferStage.Indirect);
  595. if (indexed)
  596. {
  597. _context.Renderer.Pipeline.DrawIndexedIndirect(indirectBuffer);
  598. }
  599. else
  600. {
  601. _context.Renderer.Pipeline.DrawIndirect(indirectBuffer);
  602. }
  603. }
  604. _drawState.DrawIndexed = false;
  605. _drawState.DrawIndirect = false;
  606. if (renderEnable == ConditionalRenderEnabled.Host)
  607. {
  608. _context.Renderer.Pipeline.EndHostConditionalRendering();
  609. }
  610. }
  611. /// <summary>
  612. /// Perform any deferred draws.
  613. /// This is used for instanced draws.
  614. /// Since each instance is a separate draw, we defer the draw and accumulate the instance count.
  615. /// Once we detect the last instanced draw, then we perform the host instanced draw,
  616. /// with the accumulated instance count.
  617. /// </summary>
  618. /// <param name="engine">3D engine where this method is being called</param>
  619. public void PerformDeferredDraws(ThreedClass engine)
  620. {
  621. // Perform any pending instanced draw.
  622. if (_instancedDrawPending)
  623. {
  624. _instancedDrawPending = false;
  625. int instanceCount = _instanceIndex + 1;
  626. int firstInstance = _instancedFirstInstance;
  627. bool indexedInline = _instancedIndexedInline;
  628. if (_instancedIndexed || indexedInline)
  629. {
  630. int indexCount = _instancedIndexCount;
  631. if (indexedInline)
  632. {
  633. int inlineIndexCount = _drawState.IbStreamer.GetAndResetInlineIndexCount(_context.Renderer);
  634. BufferRange br = new(_drawState.IbStreamer.GetInlineIndexBuffer(), 0, inlineIndexCount * 4);
  635. _channel.BufferManager.SetIndexBuffer(br, IndexType.UInt);
  636. indexCount = inlineIndexCount;
  637. }
  638. int firstIndex = _instancedFirstIndex;
  639. int firstVertex = _instancedFirstVertex;
  640. DrawImpl(engine, indexCount, instanceCount, firstIndex, firstVertex, firstInstance, indexed: true);
  641. }
  642. else
  643. {
  644. int vertexCount = _instancedDrawStateCount;
  645. int firstVertex = _instancedDrawStateFirst;
  646. DrawImpl(engine, vertexCount, instanceCount, 0, firstVertex, firstInstance, indexed: false);
  647. }
  648. }
  649. }
  650. /// <summary>
  651. /// Clears the current color and depth-stencil buffers.
  652. /// Which buffers should be cleared can also be specified with the argument.
  653. /// </summary>
  654. /// <param name="engine">3D engine where this method is being called</param>
  655. /// <param name="argument">Method call argument</param>
  656. public void Clear(ThreedClass engine, int argument)
  657. {
  658. Clear(engine, argument, 1);
  659. }
  660. /// <summary>
  661. /// Clears the current color and depth-stencil buffers.
  662. /// Which buffers should be cleared can also specified with the arguments.
  663. /// </summary>
  664. /// <param name="engine">3D engine where this method is being called</param>
  665. /// <param name="argument">Method call argument</param>
  666. /// <param name="layerCount">For array and 3D textures, indicates how many layers should be cleared</param>
  667. public void Clear(ThreedClass engine, int argument, int layerCount)
  668. {
  669. ConditionalRenderEnabled renderEnable = ConditionalRendering.GetRenderEnable(
  670. _context,
  671. _channel.MemoryManager,
  672. _state.State.RenderEnableAddress,
  673. _state.State.RenderEnableCondition);
  674. if (renderEnable == ConditionalRenderEnabled.False)
  675. {
  676. return;
  677. }
  678. bool clearDepth = (argument & 1) != 0;
  679. bool clearStencil = (argument & 2) != 0;
  680. uint componentMask = (uint)((argument >> 2) & 0xf);
  681. int index = (argument >> 6) & 0xf;
  682. int layer = (argument >> 10) & 0x3ff;
  683. RenderTargetUpdateFlags updateFlags = RenderTargetUpdateFlags.SingleColor;
  684. if (layer != 0 || layerCount > 1)
  685. {
  686. updateFlags |= RenderTargetUpdateFlags.Layered;
  687. }
  688. bool clearDS = clearDepth || clearStencil;
  689. if (clearDS)
  690. {
  691. updateFlags |= RenderTargetUpdateFlags.UpdateDepthStencil;
  692. }
  693. // If there is a mismatch on the host clip region and the one explicitly defined by the guest
  694. // on the screen scissor state, then we need to force only one texture to be bound to avoid
  695. // host clipping.
  696. ScreenScissorState screenScissorState = _state.State.ScreenScissorState;
  697. bool clearAffectedByStencilMask = (_state.State.ClearFlags & 1) != 0;
  698. bool clearAffectedByScissor = (_state.State.ClearFlags & 0x100) != 0;
  699. if (clearDS || componentMask == 15)
  700. {
  701. // A full clear if scissor is disabled, or it matches the screen scissor state.
  702. bool fullClear = screenScissorState.X == 0 && screenScissorState.Y == 0;
  703. if (fullClear && clearAffectedByScissor && _state.State.ScissorState[0].Enable)
  704. {
  705. ref ScissorState scissorState = ref _state.State.ScissorState[0];
  706. fullClear = scissorState.X1 == screenScissorState.X &&
  707. scissorState.Y1 == screenScissorState.Y &&
  708. scissorState.X2 >= screenScissorState.X + screenScissorState.Width &&
  709. scissorState.Y2 >= screenScissorState.Y + screenScissorState.Height;
  710. }
  711. if (fullClear && clearDS)
  712. {
  713. // Must clear all aspects of the depth-stencil format.
  714. FormatInfo dsFormat = _state.State.RtDepthStencilState.Format.Convert();
  715. bool hasDepth = dsFormat.Format.HasDepth();
  716. bool hasStencil = dsFormat.Format.HasStencil();
  717. if (hasStencil && (!clearStencil || (clearAffectedByStencilMask && _state.State.StencilTestState.FrontMask != 0xff)))
  718. {
  719. fullClear = false;
  720. }
  721. else if (hasDepth && !clearDepth)
  722. {
  723. fullClear = false;
  724. }
  725. }
  726. if (fullClear)
  727. {
  728. updateFlags |= RenderTargetUpdateFlags.DiscardClip;
  729. }
  730. }
  731. engine.UpdateRenderTargetState(updateFlags, singleUse: componentMask != 0 ? index : -1);
  732. // Must happen after UpdateRenderTargetState to have up-to-date clip region values.
  733. bool clipMismatch = (screenScissorState.X | screenScissorState.Y) != 0 ||
  734. screenScissorState.Width != _channel.TextureManager.ClipRegionWidth ||
  735. screenScissorState.Height != _channel.TextureManager.ClipRegionHeight;
  736. bool needsCustomScissor = !clearAffectedByScissor || clipMismatch;
  737. // Scissor and rasterizer discard also affect clears.
  738. ulong updateMask = 1UL << StateUpdater.RasterizerStateIndex;
  739. if (!needsCustomScissor)
  740. {
  741. updateMask |= 1UL << StateUpdater.ScissorStateIndex;
  742. }
  743. engine.UpdateState(updateMask);
  744. if (needsCustomScissor)
  745. {
  746. int scissorX = screenScissorState.X;
  747. int scissorY = screenScissorState.Y;
  748. int scissorW = screenScissorState.Width;
  749. int scissorH = screenScissorState.Height;
  750. if (clearAffectedByScissor && _state.State.ScissorState[0].Enable)
  751. {
  752. ref ScissorState scissorState = ref _state.State.ScissorState[0];
  753. scissorX = Math.Max(scissorX, scissorState.X1);
  754. scissorY = Math.Max(scissorY, scissorState.Y1);
  755. scissorW = Math.Min(scissorW, scissorState.X2 - scissorState.X1);
  756. scissorH = Math.Min(scissorH, scissorState.Y2 - scissorState.Y1);
  757. }
  758. float scale = _channel.TextureManager.RenderTargetScale;
  759. if (scale != 1f)
  760. {
  761. scissorX = (int)(scissorX * scale);
  762. scissorY = (int)(scissorY * scale);
  763. scissorW = (int)MathF.Ceiling(scissorW * scale);
  764. scissorH = (int)MathF.Ceiling(scissorH * scale);
  765. }
  766. Span<Rectangle<int>> scissors =
  767. [
  768. new(scissorX, scissorY, scissorW, scissorH)
  769. ];
  770. _context.Renderer.Pipeline.SetScissors(scissors);
  771. }
  772. _channel.TextureManager.UpdateRenderTargets();
  773. if (componentMask != 0)
  774. {
  775. ClearColors clearColor = _state.State.ClearColors;
  776. ColorF color = new(clearColor.Red, clearColor.Green, clearColor.Blue, clearColor.Alpha);
  777. _context.Renderer.Pipeline.ClearRenderTargetColor(index, layer, layerCount, componentMask, color);
  778. }
  779. if (clearDepth || clearStencil)
  780. {
  781. float depthValue = _state.State.ClearDepthValue;
  782. int stencilValue = (int)_state.State.ClearStencilValue;
  783. int stencilMask = 0;
  784. if (clearStencil)
  785. {
  786. stencilMask = clearAffectedByStencilMask ? _state.State.StencilTestState.FrontMask : 0xff;
  787. }
  788. if (clipMismatch)
  789. {
  790. _channel.TextureManager.UpdateRenderTargetDepthStencil();
  791. }
  792. _context.Renderer.Pipeline.ClearRenderTargetDepthStencil(
  793. layer,
  794. layerCount,
  795. depthValue,
  796. clearDepth,
  797. stencilValue,
  798. stencilMask);
  799. }
  800. if (needsCustomScissor)
  801. {
  802. engine.UpdateScissorState();
  803. }
  804. engine.UpdateRenderTargetState(RenderTargetUpdateFlags.UpdateAll);
  805. if (renderEnable == ConditionalRenderEnabled.Host)
  806. {
  807. _context.Renderer.Pipeline.EndHostConditionalRendering();
  808. }
  809. }
  810. protected virtual void Dispose(bool disposing)
  811. {
  812. if (disposing)
  813. {
  814. _vtgAsCompute.Dispose();
  815. }
  816. }
  817. public void Dispose()
  818. {
  819. Dispose(true);
  820. GC.SuppressFinalize(this);
  821. }
  822. }
  823. }