Pipeline.cs 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788
  1. using OpenTK.Graphics.OpenGL;
  2. using Ryujinx.Common.Logging;
  3. using Ryujinx.Graphics.GAL;
  4. using Ryujinx.Graphics.OpenGL.Image;
  5. using Ryujinx.Graphics.OpenGL.Queries;
  6. using Ryujinx.Graphics.Shader;
  7. using System;
  8. using System.Runtime.CompilerServices;
  9. namespace Ryujinx.Graphics.OpenGL
  10. {
  11. class Pipeline : IPipeline, IDisposable
  12. {
  13. private const int SavedImages = 2;
  14. private readonly DrawTextureEmulation _drawTexture;
  15. internal ulong DrawCount { get; private set; }
  16. private Program _program;
  17. private bool _rasterizerDiscard;
  18. private VertexArray _vertexArray;
  19. private Framebuffer _framebuffer;
  20. private IntPtr _indexBaseOffset;
  21. private DrawElementsType _elementsType;
  22. private PrimitiveType _primitiveType;
  23. private int _stencilFrontMask;
  24. private bool _depthMask;
  25. private bool _depthTestEnable;
  26. private bool _stencilTestEnable;
  27. private bool _cullEnable;
  28. private float[] _viewportArray = Array.Empty<float>();
  29. private double[] _depthRangeArray = Array.Empty<double>();
  30. private int _boundDrawFramebuffer;
  31. private int _boundReadFramebuffer;
  32. private CounterQueueEvent _activeConditionalRender;
  33. private Vector4<int>[] _fpIsBgra = new Vector4<int>[SupportBuffer.FragmentIsBgraCount];
  34. private Vector4<float>[] _renderScale = new Vector4<float>[73];
  35. private int _fragmentScaleCount;
  36. private (TextureBase, Format)[] _images;
  37. private TextureBase _unit0Texture;
  38. private Sampler _unit0Sampler;
  39. private FrontFaceDirection _frontFace;
  40. private ClipOrigin _clipOrigin;
  41. private ClipDepthMode _clipDepthMode;
  42. private uint _fragmentOutputMap;
  43. private uint _componentMasks;
  44. private uint _currentComponentMasks;
  45. private bool _advancedBlendEnable;
  46. private uint _scissorEnables;
  47. private bool _tfEnabled;
  48. private TransformFeedbackPrimitiveType _tfTopology;
  49. private SupportBufferUpdater _supportBuffer;
  50. private readonly BufferHandle[] _tfbs;
  51. private readonly BufferRange[] _tfbTargets;
  52. private ColorF _blendConstant;
  53. internal Pipeline()
  54. {
  55. _drawTexture = new DrawTextureEmulation();
  56. _rasterizerDiscard = false;
  57. _clipOrigin = ClipOrigin.LowerLeft;
  58. _clipDepthMode = ClipDepthMode.NegativeOneToOne;
  59. _fragmentOutputMap = uint.MaxValue;
  60. _componentMasks = uint.MaxValue;
  61. _images = new (TextureBase, Format)[SavedImages];
  62. var defaultScale = new Vector4<float> { X = 1f, Y = 0f, Z = 0f, W = 0f };
  63. new Span<Vector4<float>>(_renderScale).Fill(defaultScale);
  64. _tfbs = new BufferHandle[Constants.MaxTransformFeedbackBuffers];
  65. _tfbTargets = new BufferRange[Constants.MaxTransformFeedbackBuffers];
  66. }
  67. public void Initialize(OpenGLRenderer renderer)
  68. {
  69. _supportBuffer = new SupportBufferUpdater(renderer);
  70. GL.BindBufferBase(BufferRangeTarget.UniformBuffer, 0, Unsafe.As<BufferHandle, int>(ref _supportBuffer.Handle));
  71. _supportBuffer.UpdateFragmentIsBgra(_fpIsBgra, 0, SupportBuffer.FragmentIsBgraCount);
  72. _supportBuffer.UpdateRenderScale(_renderScale, 0, SupportBuffer.RenderScaleMaxCount);
  73. }
  74. public void Barrier()
  75. {
  76. GL.MemoryBarrier(MemoryBarrierFlags.AllBarrierBits);
  77. }
  78. public void BeginTransformFeedback(PrimitiveTopology topology)
  79. {
  80. GL.BeginTransformFeedback(_tfTopology = topology.ConvertToTfType());
  81. _tfEnabled = true;
  82. }
  83. public void ClearBuffer(BufferHandle destination, int offset, int size, uint value)
  84. {
  85. Buffer.Clear(destination, offset, size, value);
  86. }
  87. public void ClearRenderTargetColor(int index, int layer, int layerCount, uint componentMask, ColorF color)
  88. {
  89. EnsureFramebuffer();
  90. GL.ColorMask(
  91. index,
  92. (componentMask & 1) != 0,
  93. (componentMask & 2) != 0,
  94. (componentMask & 4) != 0,
  95. (componentMask & 8) != 0);
  96. float[] colors = new float[] { color.Red, color.Green, color.Blue, color.Alpha };
  97. if (layer != 0 || layerCount != _framebuffer.GetColorLayerCount(index))
  98. {
  99. for (int l = layer; l < layer + layerCount; l++)
  100. {
  101. _framebuffer.AttachColorLayerForClear(index, l);
  102. GL.ClearBuffer(OpenTK.Graphics.OpenGL.ClearBuffer.Color, index, colors);
  103. }
  104. _framebuffer.DetachColorLayerForClear(index);
  105. }
  106. else
  107. {
  108. GL.ClearBuffer(OpenTK.Graphics.OpenGL.ClearBuffer.Color, index, colors);
  109. }
  110. RestoreComponentMask(index);
  111. }
  112. public void ClearRenderTargetDepthStencil(int layer, int layerCount, float depthValue, bool depthMask, int stencilValue, int stencilMask)
  113. {
  114. EnsureFramebuffer();
  115. bool stencilMaskChanged =
  116. stencilMask != 0 &&
  117. stencilMask != _stencilFrontMask;
  118. bool depthMaskChanged = depthMask && depthMask != _depthMask;
  119. if (stencilMaskChanged)
  120. {
  121. GL.StencilMaskSeparate(StencilFace.Front, stencilMask);
  122. }
  123. if (depthMaskChanged)
  124. {
  125. GL.DepthMask(depthMask);
  126. }
  127. if (layer != 0 || layerCount != _framebuffer.GetDepthStencilLayerCount())
  128. {
  129. for (int l = layer; l < layer + layerCount; l++)
  130. {
  131. _framebuffer.AttachDepthStencilLayerForClear(l);
  132. ClearDepthStencil(depthValue, depthMask, stencilValue, stencilMask);
  133. }
  134. _framebuffer.DetachDepthStencilLayerForClear();
  135. }
  136. else
  137. {
  138. ClearDepthStencil(depthValue, depthMask, stencilValue, stencilMask);
  139. }
  140. if (stencilMaskChanged)
  141. {
  142. GL.StencilMaskSeparate(StencilFace.Front, _stencilFrontMask);
  143. }
  144. if (depthMaskChanged)
  145. {
  146. GL.DepthMask(_depthMask);
  147. }
  148. }
  149. private static void ClearDepthStencil(float depthValue, bool depthMask, int stencilValue, int stencilMask)
  150. {
  151. if (depthMask && stencilMask != 0)
  152. {
  153. GL.ClearBuffer(ClearBufferCombined.DepthStencil, 0, depthValue, stencilValue);
  154. }
  155. else if (depthMask)
  156. {
  157. GL.ClearBuffer(OpenTK.Graphics.OpenGL.ClearBuffer.Depth, 0, ref depthValue);
  158. }
  159. else if (stencilMask != 0)
  160. {
  161. GL.ClearBuffer(OpenTK.Graphics.OpenGL.ClearBuffer.Stencil, 0, ref stencilValue);
  162. }
  163. }
  164. public void CommandBufferBarrier()
  165. {
  166. GL.MemoryBarrier(MemoryBarrierFlags.CommandBarrierBit);
  167. }
  168. public void CopyBuffer(BufferHandle source, BufferHandle destination, int srcOffset, int dstOffset, int size)
  169. {
  170. Buffer.Copy(source, destination, srcOffset, dstOffset, size);
  171. }
  172. public void DispatchCompute(int groupsX, int groupsY, int groupsZ)
  173. {
  174. if (!_program.IsLinked)
  175. {
  176. Logger.Debug?.Print(LogClass.Gpu, "Dispatch error, shader not linked.");
  177. return;
  178. }
  179. PrepareForDispatch();
  180. GL.DispatchCompute(groupsX, groupsY, groupsZ);
  181. }
  182. public void Draw(int vertexCount, int instanceCount, int firstVertex, int firstInstance)
  183. {
  184. if (!_program.IsLinked)
  185. {
  186. Logger.Debug?.Print(LogClass.Gpu, "Draw error, shader not linked.");
  187. return;
  188. }
  189. PreDraw(vertexCount);
  190. if (_primitiveType == PrimitiveType.Quads && !HwCapabilities.SupportsQuads)
  191. {
  192. DrawQuadsImpl(vertexCount, instanceCount, firstVertex, firstInstance);
  193. }
  194. else if (_primitiveType == PrimitiveType.QuadStrip && !HwCapabilities.SupportsQuads)
  195. {
  196. DrawQuadStripImpl(vertexCount, instanceCount, firstVertex, firstInstance);
  197. }
  198. else
  199. {
  200. DrawImpl(vertexCount, instanceCount, firstVertex, firstInstance);
  201. }
  202. PostDraw();
  203. }
  204. private void DrawQuadsImpl(
  205. int vertexCount,
  206. int instanceCount,
  207. int firstVertex,
  208. int firstInstance)
  209. {
  210. // TODO: Instanced rendering.
  211. int quadsCount = vertexCount / 4;
  212. int[] firsts = new int[quadsCount];
  213. int[] counts = new int[quadsCount];
  214. for (int quadIndex = 0; quadIndex < quadsCount; quadIndex++)
  215. {
  216. firsts[quadIndex] = firstVertex + quadIndex * 4;
  217. counts[quadIndex] = 4;
  218. }
  219. GL.MultiDrawArrays(
  220. PrimitiveType.TriangleFan,
  221. firsts,
  222. counts,
  223. quadsCount);
  224. }
  225. private void DrawQuadStripImpl(
  226. int vertexCount,
  227. int instanceCount,
  228. int firstVertex,
  229. int firstInstance)
  230. {
  231. int quadsCount = (vertexCount - 2) / 2;
  232. if (firstInstance != 0 || instanceCount != 1)
  233. {
  234. for (int quadIndex = 0; quadIndex < quadsCount; quadIndex++)
  235. {
  236. GL.DrawArraysInstancedBaseInstance(PrimitiveType.TriangleFan, firstVertex + quadIndex * 2, 4, instanceCount, firstInstance);
  237. }
  238. }
  239. else
  240. {
  241. int[] firsts = new int[quadsCount];
  242. int[] counts = new int[quadsCount];
  243. firsts[0] = firstVertex;
  244. counts[0] = 4;
  245. for (int quadIndex = 1; quadIndex < quadsCount; quadIndex++)
  246. {
  247. firsts[quadIndex] = firstVertex + quadIndex * 2;
  248. counts[quadIndex] = 4;
  249. }
  250. GL.MultiDrawArrays(
  251. PrimitiveType.TriangleFan,
  252. firsts,
  253. counts,
  254. quadsCount);
  255. }
  256. }
  257. private void DrawImpl(
  258. int vertexCount,
  259. int instanceCount,
  260. int firstVertex,
  261. int firstInstance)
  262. {
  263. if (firstInstance == 0 && instanceCount == 1)
  264. {
  265. GL.DrawArrays(_primitiveType, firstVertex, vertexCount);
  266. }
  267. else if (firstInstance == 0)
  268. {
  269. GL.DrawArraysInstanced(_primitiveType, firstVertex, vertexCount, instanceCount);
  270. }
  271. else
  272. {
  273. GL.DrawArraysInstancedBaseInstance(
  274. _primitiveType,
  275. firstVertex,
  276. vertexCount,
  277. instanceCount,
  278. firstInstance);
  279. }
  280. }
  281. public void DrawIndexed(
  282. int indexCount,
  283. int instanceCount,
  284. int firstIndex,
  285. int firstVertex,
  286. int firstInstance)
  287. {
  288. if (!_program.IsLinked)
  289. {
  290. Logger.Debug?.Print(LogClass.Gpu, "Draw error, shader not linked.");
  291. return;
  292. }
  293. PreDrawVbUnbounded();
  294. int indexElemSize = 1;
  295. switch (_elementsType)
  296. {
  297. case DrawElementsType.UnsignedShort: indexElemSize = 2; break;
  298. case DrawElementsType.UnsignedInt: indexElemSize = 4; break;
  299. }
  300. IntPtr indexBaseOffset = _indexBaseOffset + firstIndex * indexElemSize;
  301. if (_primitiveType == PrimitiveType.Quads && !HwCapabilities.SupportsQuads)
  302. {
  303. DrawQuadsIndexedImpl(
  304. indexCount,
  305. instanceCount,
  306. indexBaseOffset,
  307. indexElemSize,
  308. firstVertex,
  309. firstInstance);
  310. }
  311. else if (_primitiveType == PrimitiveType.QuadStrip && !HwCapabilities.SupportsQuads)
  312. {
  313. DrawQuadStripIndexedImpl(
  314. indexCount,
  315. instanceCount,
  316. indexBaseOffset,
  317. indexElemSize,
  318. firstVertex,
  319. firstInstance);
  320. }
  321. else
  322. {
  323. DrawIndexedImpl(
  324. indexCount,
  325. instanceCount,
  326. indexBaseOffset,
  327. firstVertex,
  328. firstInstance);
  329. }
  330. PostDraw();
  331. }
  332. private void DrawQuadsIndexedImpl(
  333. int indexCount,
  334. int instanceCount,
  335. IntPtr indexBaseOffset,
  336. int indexElemSize,
  337. int firstVertex,
  338. int firstInstance)
  339. {
  340. int quadsCount = indexCount / 4;
  341. if (firstInstance != 0 || instanceCount != 1)
  342. {
  343. if (firstVertex != 0 && firstInstance != 0)
  344. {
  345. for (int quadIndex = 0; quadIndex < quadsCount; quadIndex++)
  346. {
  347. GL.DrawElementsInstancedBaseVertexBaseInstance(
  348. PrimitiveType.TriangleFan,
  349. 4,
  350. _elementsType,
  351. indexBaseOffset + quadIndex * 4 * indexElemSize,
  352. instanceCount,
  353. firstVertex,
  354. firstInstance);
  355. }
  356. }
  357. else if (firstInstance != 0)
  358. {
  359. for (int quadIndex = 0; quadIndex < quadsCount; quadIndex++)
  360. {
  361. GL.DrawElementsInstancedBaseInstance(
  362. PrimitiveType.TriangleFan,
  363. 4,
  364. _elementsType,
  365. indexBaseOffset + quadIndex * 4 * indexElemSize,
  366. instanceCount,
  367. firstInstance);
  368. }
  369. }
  370. else
  371. {
  372. for (int quadIndex = 0; quadIndex < quadsCount; quadIndex++)
  373. {
  374. GL.DrawElementsInstanced(
  375. PrimitiveType.TriangleFan,
  376. 4,
  377. _elementsType,
  378. indexBaseOffset + quadIndex * 4 * indexElemSize,
  379. instanceCount);
  380. }
  381. }
  382. }
  383. else
  384. {
  385. IntPtr[] indices = new IntPtr[quadsCount];
  386. int[] counts = new int[quadsCount];
  387. int[] baseVertices = new int[quadsCount];
  388. for (int quadIndex = 0; quadIndex < quadsCount; quadIndex++)
  389. {
  390. indices[quadIndex] = indexBaseOffset + quadIndex * 4 * indexElemSize;
  391. counts[quadIndex] = 4;
  392. baseVertices[quadIndex] = firstVertex;
  393. }
  394. GL.MultiDrawElementsBaseVertex(
  395. PrimitiveType.TriangleFan,
  396. counts,
  397. _elementsType,
  398. indices,
  399. quadsCount,
  400. baseVertices);
  401. }
  402. }
  403. private void DrawQuadStripIndexedImpl(
  404. int indexCount,
  405. int instanceCount,
  406. IntPtr indexBaseOffset,
  407. int indexElemSize,
  408. int firstVertex,
  409. int firstInstance)
  410. {
  411. // TODO: Instanced rendering.
  412. int quadsCount = (indexCount - 2) / 2;
  413. IntPtr[] indices = new IntPtr[quadsCount];
  414. int[] counts = new int[quadsCount];
  415. int[] baseVertices = new int[quadsCount];
  416. indices[0] = indexBaseOffset;
  417. counts[0] = 4;
  418. baseVertices[0] = firstVertex;
  419. for (int quadIndex = 1; quadIndex < quadsCount; quadIndex++)
  420. {
  421. indices[quadIndex] = indexBaseOffset + quadIndex * 2 * indexElemSize;
  422. counts[quadIndex] = 4;
  423. baseVertices[quadIndex] = firstVertex;
  424. }
  425. GL.MultiDrawElementsBaseVertex(
  426. PrimitiveType.TriangleFan,
  427. counts,
  428. _elementsType,
  429. indices,
  430. quadsCount,
  431. baseVertices);
  432. }
  433. private void DrawIndexedImpl(
  434. int indexCount,
  435. int instanceCount,
  436. IntPtr indexBaseOffset,
  437. int firstVertex,
  438. int firstInstance)
  439. {
  440. if (firstInstance == 0 && firstVertex == 0 && instanceCount == 1)
  441. {
  442. GL.DrawElements(_primitiveType, indexCount, _elementsType, indexBaseOffset);
  443. }
  444. else if (firstInstance == 0 && instanceCount == 1)
  445. {
  446. GL.DrawElementsBaseVertex(
  447. _primitiveType,
  448. indexCount,
  449. _elementsType,
  450. indexBaseOffset,
  451. firstVertex);
  452. }
  453. else if (firstInstance == 0 && firstVertex == 0)
  454. {
  455. GL.DrawElementsInstanced(
  456. _primitiveType,
  457. indexCount,
  458. _elementsType,
  459. indexBaseOffset,
  460. instanceCount);
  461. }
  462. else if (firstInstance == 0)
  463. {
  464. GL.DrawElementsInstancedBaseVertex(
  465. _primitiveType,
  466. indexCount,
  467. _elementsType,
  468. indexBaseOffset,
  469. instanceCount,
  470. firstVertex);
  471. }
  472. else if (firstVertex == 0)
  473. {
  474. GL.DrawElementsInstancedBaseInstance(
  475. _primitiveType,
  476. indexCount,
  477. _elementsType,
  478. indexBaseOffset,
  479. instanceCount,
  480. firstInstance);
  481. }
  482. else
  483. {
  484. GL.DrawElementsInstancedBaseVertexBaseInstance(
  485. _primitiveType,
  486. indexCount,
  487. _elementsType,
  488. indexBaseOffset,
  489. instanceCount,
  490. firstVertex,
  491. firstInstance);
  492. }
  493. }
  494. public void DrawIndexedIndirect(BufferRange indirectBuffer)
  495. {
  496. if (!_program.IsLinked)
  497. {
  498. Logger.Debug?.Print(LogClass.Gpu, "Draw error, shader not linked.");
  499. return;
  500. }
  501. PreDrawVbUnbounded();
  502. _vertexArray.SetRangeOfIndexBuffer();
  503. GL.BindBuffer((BufferTarget)All.DrawIndirectBuffer, indirectBuffer.Handle.ToInt32());
  504. GL.DrawElementsIndirect(_primitiveType, _elementsType, (IntPtr)indirectBuffer.Offset);
  505. _vertexArray.RestoreIndexBuffer();
  506. PostDraw();
  507. }
  508. public void DrawIndexedIndirectCount(BufferRange indirectBuffer, BufferRange parameterBuffer, int maxDrawCount, int stride)
  509. {
  510. if (!_program.IsLinked)
  511. {
  512. Logger.Debug?.Print(LogClass.Gpu, "Draw error, shader not linked.");
  513. return;
  514. }
  515. PreDrawVbUnbounded();
  516. _vertexArray.SetRangeOfIndexBuffer();
  517. GL.BindBuffer((BufferTarget)All.DrawIndirectBuffer, indirectBuffer.Handle.ToInt32());
  518. GL.BindBuffer((BufferTarget)All.ParameterBuffer, parameterBuffer.Handle.ToInt32());
  519. GL.MultiDrawElementsIndirectCount(
  520. _primitiveType,
  521. (All)_elementsType,
  522. (IntPtr)indirectBuffer.Offset,
  523. (IntPtr)parameterBuffer.Offset,
  524. maxDrawCount,
  525. stride);
  526. _vertexArray.RestoreIndexBuffer();
  527. PostDraw();
  528. }
  529. public void DrawIndirect(BufferRange indirectBuffer)
  530. {
  531. if (!_program.IsLinked)
  532. {
  533. Logger.Debug?.Print(LogClass.Gpu, "Draw error, shader not linked.");
  534. return;
  535. }
  536. PreDrawVbUnbounded();
  537. GL.BindBuffer((BufferTarget)All.DrawIndirectBuffer, indirectBuffer.Handle.ToInt32());
  538. GL.DrawArraysIndirect(_primitiveType, (IntPtr)indirectBuffer.Offset);
  539. PostDraw();
  540. }
  541. public void DrawIndirectCount(BufferRange indirectBuffer, BufferRange parameterBuffer, int maxDrawCount, int stride)
  542. {
  543. if (!_program.IsLinked)
  544. {
  545. Logger.Debug?.Print(LogClass.Gpu, "Draw error, shader not linked.");
  546. return;
  547. }
  548. PreDrawVbUnbounded();
  549. GL.BindBuffer((BufferTarget)All.DrawIndirectBuffer, indirectBuffer.Handle.ToInt32());
  550. GL.BindBuffer((BufferTarget)All.ParameterBuffer, parameterBuffer.Handle.ToInt32());
  551. GL.MultiDrawArraysIndirectCount(
  552. _primitiveType,
  553. (IntPtr)indirectBuffer.Offset,
  554. (IntPtr)parameterBuffer.Offset,
  555. maxDrawCount,
  556. stride);
  557. PostDraw();
  558. }
  559. public void DrawTexture(ITexture texture, ISampler sampler, Extents2DF srcRegion, Extents2DF dstRegion)
  560. {
  561. if (texture is TextureView view && sampler is Sampler samp)
  562. {
  563. _supportBuffer.Commit();
  564. if (HwCapabilities.SupportsDrawTexture)
  565. {
  566. GL.NV.DrawTexture(
  567. view.Handle,
  568. samp.Handle,
  569. dstRegion.X1,
  570. dstRegion.Y1,
  571. dstRegion.X2,
  572. dstRegion.Y2,
  573. 0,
  574. srcRegion.X1 / view.Width,
  575. srcRegion.Y1 / view.Height,
  576. srcRegion.X2 / view.Width,
  577. srcRegion.Y2 / view.Height);
  578. }
  579. else
  580. {
  581. static void Disable(EnableCap cap, bool enabled)
  582. {
  583. if (enabled)
  584. {
  585. GL.Disable(cap);
  586. }
  587. }
  588. static void Enable(EnableCap cap, bool enabled)
  589. {
  590. if (enabled)
  591. {
  592. GL.Enable(cap);
  593. }
  594. }
  595. Disable(EnableCap.CullFace, _cullEnable);
  596. Disable(EnableCap.StencilTest, _stencilTestEnable);
  597. Disable(EnableCap.DepthTest, _depthTestEnable);
  598. if (_depthMask)
  599. {
  600. GL.DepthMask(false);
  601. }
  602. if (_tfEnabled)
  603. {
  604. GL.EndTransformFeedback();
  605. }
  606. GL.ClipControl(ClipOrigin.UpperLeft, ClipDepthMode.NegativeOneToOne);
  607. _drawTexture.Draw(
  608. view,
  609. samp,
  610. dstRegion.X1,
  611. dstRegion.Y1,
  612. dstRegion.X2,
  613. dstRegion.Y2,
  614. srcRegion.X1 / view.Width,
  615. srcRegion.Y1 / view.Height,
  616. srcRegion.X2 / view.Width,
  617. srcRegion.Y2 / view.Height);
  618. _program?.Bind();
  619. _unit0Sampler?.Bind(0);
  620. RestoreViewport0();
  621. Enable(EnableCap.CullFace, _cullEnable);
  622. Enable(EnableCap.StencilTest, _stencilTestEnable);
  623. Enable(EnableCap.DepthTest, _depthTestEnable);
  624. if (_depthMask)
  625. {
  626. GL.DepthMask(true);
  627. }
  628. if (_tfEnabled)
  629. {
  630. GL.BeginTransformFeedback(_tfTopology);
  631. }
  632. RestoreClipControl();
  633. }
  634. }
  635. }
  636. public void EndTransformFeedback()
  637. {
  638. GL.EndTransformFeedback();
  639. _tfEnabled = false;
  640. }
  641. public double GetCounterDivisor(CounterType type)
  642. {
  643. if (type == CounterType.SamplesPassed)
  644. {
  645. return _renderScale[0].X * _renderScale[0].X;
  646. }
  647. return 1;
  648. }
  649. public void SetAlphaTest(bool enable, float reference, CompareOp op)
  650. {
  651. if (!enable)
  652. {
  653. GL.Disable(EnableCap.AlphaTest);
  654. return;
  655. }
  656. GL.AlphaFunc((AlphaFunction)op.Convert(), reference);
  657. GL.Enable(EnableCap.AlphaTest);
  658. }
  659. public void SetBlendState(AdvancedBlendDescriptor blend)
  660. {
  661. if (HwCapabilities.SupportsBlendEquationAdvanced)
  662. {
  663. GL.BlendEquation((BlendEquationMode)blend.Op.Convert());
  664. GL.NV.BlendParameter(NvBlendEquationAdvanced.BlendOverlapNv, (int)blend.Overlap.Convert());
  665. GL.NV.BlendParameter(NvBlendEquationAdvanced.BlendPremultipliedSrcNv, blend.SrcPreMultiplied ? 1 : 0);
  666. GL.Enable(EnableCap.Blend);
  667. _advancedBlendEnable = true;
  668. }
  669. }
  670. public void SetBlendState(int index, BlendDescriptor blend)
  671. {
  672. if (_advancedBlendEnable)
  673. {
  674. GL.Disable(EnableCap.Blend);
  675. _advancedBlendEnable = false;
  676. }
  677. if (!blend.Enable)
  678. {
  679. GL.Disable(IndexedEnableCap.Blend, index);
  680. return;
  681. }
  682. GL.BlendEquationSeparate(
  683. index,
  684. blend.ColorOp.Convert(),
  685. blend.AlphaOp.Convert());
  686. GL.BlendFuncSeparate(
  687. index,
  688. (BlendingFactorSrc)blend.ColorSrcFactor.Convert(),
  689. (BlendingFactorDest)blend.ColorDstFactor.Convert(),
  690. (BlendingFactorSrc)blend.AlphaSrcFactor.Convert(),
  691. (BlendingFactorDest)blend.AlphaDstFactor.Convert());
  692. static bool IsDualSource(BlendFactor factor)
  693. {
  694. switch (factor)
  695. {
  696. case BlendFactor.Src1Color:
  697. case BlendFactor.Src1ColorGl:
  698. case BlendFactor.Src1Alpha:
  699. case BlendFactor.Src1AlphaGl:
  700. case BlendFactor.OneMinusSrc1Color:
  701. case BlendFactor.OneMinusSrc1ColorGl:
  702. case BlendFactor.OneMinusSrc1Alpha:
  703. case BlendFactor.OneMinusSrc1AlphaGl:
  704. return true;
  705. }
  706. return false;
  707. }
  708. EnsureFramebuffer();
  709. _framebuffer.SetDualSourceBlend(
  710. IsDualSource(blend.ColorSrcFactor) ||
  711. IsDualSource(blend.ColorDstFactor) ||
  712. IsDualSource(blend.AlphaSrcFactor) ||
  713. IsDualSource(blend.AlphaDstFactor));
  714. if (_blendConstant != blend.BlendConstant)
  715. {
  716. _blendConstant = blend.BlendConstant;
  717. GL.BlendColor(
  718. blend.BlendConstant.Red,
  719. blend.BlendConstant.Green,
  720. blend.BlendConstant.Blue,
  721. blend.BlendConstant.Alpha);
  722. }
  723. GL.Enable(IndexedEnableCap.Blend, index);
  724. }
  725. public void SetDepthBias(PolygonModeMask enables, float factor, float units, float clamp)
  726. {
  727. if ((enables & PolygonModeMask.Point) != 0)
  728. {
  729. GL.Enable(EnableCap.PolygonOffsetPoint);
  730. }
  731. else
  732. {
  733. GL.Disable(EnableCap.PolygonOffsetPoint);
  734. }
  735. if ((enables & PolygonModeMask.Line) != 0)
  736. {
  737. GL.Enable(EnableCap.PolygonOffsetLine);
  738. }
  739. else
  740. {
  741. GL.Disable(EnableCap.PolygonOffsetLine);
  742. }
  743. if ((enables & PolygonModeMask.Fill) != 0)
  744. {
  745. GL.Enable(EnableCap.PolygonOffsetFill);
  746. }
  747. else
  748. {
  749. GL.Disable(EnableCap.PolygonOffsetFill);
  750. }
  751. if (enables == 0)
  752. {
  753. return;
  754. }
  755. if (HwCapabilities.SupportsPolygonOffsetClamp)
  756. {
  757. GL.PolygonOffsetClamp(factor, units, clamp);
  758. }
  759. else
  760. {
  761. GL.PolygonOffset(factor, units);
  762. }
  763. }
  764. public void SetDepthClamp(bool clamp)
  765. {
  766. if (!clamp)
  767. {
  768. GL.Disable(EnableCap.DepthClamp);
  769. return;
  770. }
  771. GL.Enable(EnableCap.DepthClamp);
  772. }
  773. public void SetDepthMode(DepthMode mode)
  774. {
  775. ClipDepthMode depthMode = mode.Convert();
  776. if (_clipDepthMode != depthMode)
  777. {
  778. _clipDepthMode = depthMode;
  779. GL.ClipControl(_clipOrigin, depthMode);
  780. }
  781. }
  782. public void SetDepthTest(DepthTestDescriptor depthTest)
  783. {
  784. if (depthTest.TestEnable)
  785. {
  786. GL.Enable(EnableCap.DepthTest);
  787. GL.DepthFunc((DepthFunction)depthTest.Func.Convert());
  788. }
  789. else
  790. {
  791. GL.Disable(EnableCap.DepthTest);
  792. }
  793. GL.DepthMask(depthTest.WriteEnable);
  794. _depthMask = depthTest.WriteEnable;
  795. _depthTestEnable = depthTest.TestEnable;
  796. }
  797. public void SetFaceCulling(bool enable, Face face)
  798. {
  799. _cullEnable = enable;
  800. if (!enable)
  801. {
  802. GL.Disable(EnableCap.CullFace);
  803. return;
  804. }
  805. GL.CullFace(face.Convert());
  806. GL.Enable(EnableCap.CullFace);
  807. }
  808. public void SetFrontFace(FrontFace frontFace)
  809. {
  810. SetFrontFace(_frontFace = frontFace.Convert());
  811. }
  812. public void SetImage(int binding, ITexture texture, Format imageFormat)
  813. {
  814. if ((uint)binding < SavedImages)
  815. {
  816. _images[binding] = (texture as TextureBase, imageFormat);
  817. }
  818. if (texture == null)
  819. {
  820. GL.BindImageTexture(binding, 0, 0, true, 0, TextureAccess.ReadWrite, SizedInternalFormat.Rgba8);
  821. return;
  822. }
  823. TextureBase texBase = (TextureBase)texture;
  824. SizedInternalFormat format = FormatTable.GetImageFormat(imageFormat);
  825. if (format != 0)
  826. {
  827. GL.BindImageTexture(binding, texBase.Handle, 0, true, 0, TextureAccess.ReadWrite, format);
  828. }
  829. }
  830. public void SetIndexBuffer(BufferRange buffer, IndexType type)
  831. {
  832. _elementsType = type.Convert();
  833. _indexBaseOffset = (IntPtr)buffer.Offset;
  834. EnsureVertexArray();
  835. _vertexArray.SetIndexBuffer(buffer);
  836. }
  837. public void SetLogicOpState(bool enable, LogicalOp op)
  838. {
  839. if (enable)
  840. {
  841. GL.Enable(EnableCap.ColorLogicOp);
  842. GL.LogicOp((LogicOp)op.Convert());
  843. }
  844. else
  845. {
  846. GL.Disable(EnableCap.ColorLogicOp);
  847. }
  848. }
  849. public void SetMultisampleState(MultisampleDescriptor multisample)
  850. {
  851. if (multisample.AlphaToCoverageEnable)
  852. {
  853. GL.Enable(EnableCap.SampleAlphaToCoverage);
  854. if (multisample.AlphaToOneEnable)
  855. {
  856. GL.Enable(EnableCap.SampleAlphaToOne);
  857. }
  858. else
  859. {
  860. GL.Disable(EnableCap.SampleAlphaToOne);
  861. }
  862. if (HwCapabilities.SupportsAlphaToCoverageDitherControl)
  863. {
  864. GL.NV.AlphaToCoverageDitherControl(multisample.AlphaToCoverageDitherEnable
  865. ? NvAlphaToCoverageDitherControl.AlphaToCoverageDitherEnableNv
  866. : NvAlphaToCoverageDitherControl.AlphaToCoverageDitherDisableNv);
  867. }
  868. }
  869. else
  870. {
  871. GL.Disable(EnableCap.SampleAlphaToCoverage);
  872. }
  873. }
  874. public void SetLineParameters(float width, bool smooth)
  875. {
  876. if (smooth)
  877. {
  878. GL.Enable(EnableCap.LineSmooth);
  879. }
  880. else
  881. {
  882. GL.Disable(EnableCap.LineSmooth);
  883. }
  884. GL.LineWidth(width);
  885. }
  886. public unsafe void SetPatchParameters(int vertices, ReadOnlySpan<float> defaultOuterLevel, ReadOnlySpan<float> defaultInnerLevel)
  887. {
  888. GL.PatchParameter(PatchParameterInt.PatchVertices, vertices);
  889. fixed (float* pOuterLevel = defaultOuterLevel)
  890. {
  891. GL.PatchParameter(PatchParameterFloat.PatchDefaultOuterLevel, pOuterLevel);
  892. }
  893. fixed (float* pInnerLevel = defaultInnerLevel)
  894. {
  895. GL.PatchParameter(PatchParameterFloat.PatchDefaultInnerLevel, pInnerLevel);
  896. }
  897. }
  898. public void SetPointParameters(float size, bool isProgramPointSize, bool enablePointSprite, Origin origin)
  899. {
  900. // GL_POINT_SPRITE was deprecated in core profile 3.2+ and causes GL_INVALID_ENUM when set.
  901. // As we don't know if the current context is core or compat, it's safer to keep this code.
  902. if (enablePointSprite)
  903. {
  904. GL.Enable(EnableCap.PointSprite);
  905. }
  906. else
  907. {
  908. GL.Disable(EnableCap.PointSprite);
  909. }
  910. if (isProgramPointSize)
  911. {
  912. GL.Enable(EnableCap.ProgramPointSize);
  913. }
  914. else
  915. {
  916. GL.Disable(EnableCap.ProgramPointSize);
  917. }
  918. GL.PointParameter(origin == Origin.LowerLeft
  919. ? PointSpriteCoordOriginParameter.LowerLeft
  920. : PointSpriteCoordOriginParameter.UpperLeft);
  921. // Games seem to set point size to 0 which generates a GL_INVALID_VALUE
  922. // From the spec, GL_INVALID_VALUE is generated if size is less than or equal to 0.
  923. GL.PointSize(Math.Max(float.Epsilon, size));
  924. }
  925. public void SetPolygonMode(GAL.PolygonMode frontMode, GAL.PolygonMode backMode)
  926. {
  927. if (frontMode == backMode)
  928. {
  929. GL.PolygonMode(MaterialFace.FrontAndBack, frontMode.Convert());
  930. }
  931. else
  932. {
  933. GL.PolygonMode(MaterialFace.Front, frontMode.Convert());
  934. GL.PolygonMode(MaterialFace.Back, backMode.Convert());
  935. }
  936. }
  937. public void SetPrimitiveRestart(bool enable, int index)
  938. {
  939. if (!enable)
  940. {
  941. GL.Disable(EnableCap.PrimitiveRestart);
  942. return;
  943. }
  944. GL.PrimitiveRestartIndex(index);
  945. GL.Enable(EnableCap.PrimitiveRestart);
  946. }
  947. public void SetPrimitiveTopology(PrimitiveTopology topology)
  948. {
  949. _primitiveType = topology.Convert();
  950. }
  951. public void SetProgram(IProgram program)
  952. {
  953. Program prg = (Program)program;
  954. if (_tfEnabled)
  955. {
  956. GL.EndTransformFeedback();
  957. prg.Bind();
  958. GL.BeginTransformFeedback(_tfTopology);
  959. }
  960. else
  961. {
  962. prg.Bind();
  963. }
  964. if (prg.HasFragmentShader && _fragmentOutputMap != (uint)prg.FragmentOutputMap)
  965. {
  966. _fragmentOutputMap = (uint)prg.FragmentOutputMap;
  967. for (int index = 0; index < Constants.MaxRenderTargets; index++)
  968. {
  969. RestoreComponentMask(index, force: false);
  970. }
  971. }
  972. _program = prg;
  973. }
  974. public void SetRasterizerDiscard(bool discard)
  975. {
  976. if (discard)
  977. {
  978. GL.Enable(EnableCap.RasterizerDiscard);
  979. }
  980. else
  981. {
  982. GL.Disable(EnableCap.RasterizerDiscard);
  983. }
  984. _rasterizerDiscard = discard;
  985. }
  986. public void SetRenderTargetScale(float scale)
  987. {
  988. _renderScale[0].X = scale;
  989. _supportBuffer.UpdateRenderScale(_renderScale, 0, 1); // Just the first element.
  990. }
  991. public void SetRenderTargetColorMasks(ReadOnlySpan<uint> componentMasks)
  992. {
  993. _componentMasks = 0;
  994. for (int index = 0; index < componentMasks.Length; index++)
  995. {
  996. _componentMasks |= componentMasks[index] << (index * 4);
  997. RestoreComponentMask(index, force: false);
  998. }
  999. }
  1000. public void SetRenderTargets(ITexture[] colors, ITexture depthStencil)
  1001. {
  1002. EnsureFramebuffer();
  1003. bool isBgraChanged = false;
  1004. for (int index = 0; index < colors.Length; index++)
  1005. {
  1006. TextureView color = (TextureView)colors[index];
  1007. _framebuffer.AttachColor(index, color);
  1008. if (color != null)
  1009. {
  1010. int isBgra = color.Format.IsBgr() ? 1 : 0;
  1011. if (_fpIsBgra[index].X != isBgra)
  1012. {
  1013. _fpIsBgra[index].X = isBgra;
  1014. isBgraChanged = true;
  1015. RestoreComponentMask(index);
  1016. }
  1017. }
  1018. }
  1019. if (isBgraChanged)
  1020. {
  1021. _supportBuffer.UpdateFragmentIsBgra(_fpIsBgra, 0, SupportBuffer.FragmentIsBgraCount);
  1022. }
  1023. TextureView depthStencilView = (TextureView)depthStencil;
  1024. _framebuffer.AttachDepthStencil(depthStencilView);
  1025. _framebuffer.SetDrawBuffers(colors.Length);
  1026. }
  1027. public void SetScissors(ReadOnlySpan<Rectangle<int>> regions)
  1028. {
  1029. int count = Math.Min(regions.Length, Constants.MaxViewports);
  1030. Span<int> v = stackalloc int[count * 4];
  1031. for (int index = 0; index < count; index++)
  1032. {
  1033. int vIndex = index * 4;
  1034. var region = regions[index];
  1035. bool enabled = (region.X | region.Y) != 0 || region.Width != 0xffff || region.Height != 0xffff;
  1036. uint mask = 1u << index;
  1037. if (enabled)
  1038. {
  1039. v[vIndex] = region.X;
  1040. v[vIndex + 1] = region.Y;
  1041. v[vIndex + 2] = region.Width;
  1042. v[vIndex + 3] = region.Height;
  1043. if ((_scissorEnables & mask) == 0)
  1044. {
  1045. _scissorEnables |= mask;
  1046. GL.Enable(IndexedEnableCap.ScissorTest, index);
  1047. }
  1048. }
  1049. else
  1050. {
  1051. if ((_scissorEnables & mask) != 0)
  1052. {
  1053. _scissorEnables &= ~mask;
  1054. GL.Disable(IndexedEnableCap.ScissorTest, index);
  1055. }
  1056. }
  1057. }
  1058. GL.ScissorArray(0, count, ref v[0]);
  1059. }
  1060. public void SetStencilTest(StencilTestDescriptor stencilTest)
  1061. {
  1062. _stencilTestEnable = stencilTest.TestEnable;
  1063. if (!stencilTest.TestEnable)
  1064. {
  1065. GL.Disable(EnableCap.StencilTest);
  1066. return;
  1067. }
  1068. GL.StencilOpSeparate(
  1069. StencilFace.Front,
  1070. stencilTest.FrontSFail.Convert(),
  1071. stencilTest.FrontDpFail.Convert(),
  1072. stencilTest.FrontDpPass.Convert());
  1073. GL.StencilFuncSeparate(
  1074. StencilFace.Front,
  1075. (StencilFunction)stencilTest.FrontFunc.Convert(),
  1076. stencilTest.FrontFuncRef,
  1077. stencilTest.FrontFuncMask);
  1078. GL.StencilMaskSeparate(StencilFace.Front, stencilTest.FrontMask);
  1079. GL.StencilOpSeparate(
  1080. StencilFace.Back,
  1081. stencilTest.BackSFail.Convert(),
  1082. stencilTest.BackDpFail.Convert(),
  1083. stencilTest.BackDpPass.Convert());
  1084. GL.StencilFuncSeparate(
  1085. StencilFace.Back,
  1086. (StencilFunction)stencilTest.BackFunc.Convert(),
  1087. stencilTest.BackFuncRef,
  1088. stencilTest.BackFuncMask);
  1089. GL.StencilMaskSeparate(StencilFace.Back, stencilTest.BackMask);
  1090. GL.Enable(EnableCap.StencilTest);
  1091. _stencilFrontMask = stencilTest.FrontMask;
  1092. }
  1093. public void SetStorageBuffers(ReadOnlySpan<BufferAssignment> buffers)
  1094. {
  1095. SetBuffers(buffers, isStorage: true);
  1096. }
  1097. public void SetTextureAndSampler(ShaderStage stage, int binding, ITexture texture, ISampler sampler)
  1098. {
  1099. if (texture != null)
  1100. {
  1101. if (binding == 0)
  1102. {
  1103. _unit0Texture = (TextureBase)texture;
  1104. }
  1105. else
  1106. {
  1107. ((TextureBase)texture).Bind(binding);
  1108. }
  1109. }
  1110. else
  1111. {
  1112. TextureBase.ClearBinding(binding);
  1113. }
  1114. Sampler glSampler = (Sampler)sampler;
  1115. glSampler?.Bind(binding);
  1116. if (binding == 0)
  1117. {
  1118. _unit0Sampler = glSampler;
  1119. }
  1120. }
  1121. public void SetTransformFeedbackBuffers(ReadOnlySpan<BufferRange> buffers)
  1122. {
  1123. if (_tfEnabled)
  1124. {
  1125. GL.EndTransformFeedback();
  1126. }
  1127. int count = Math.Min(buffers.Length, Constants.MaxTransformFeedbackBuffers);
  1128. for (int i = 0; i < count; i++)
  1129. {
  1130. BufferRange buffer = buffers[i];
  1131. _tfbTargets[i] = buffer;
  1132. if (buffer.Handle == BufferHandle.Null)
  1133. {
  1134. GL.BindBufferBase(BufferRangeTarget.TransformFeedbackBuffer, i, 0);
  1135. continue;
  1136. }
  1137. if (_tfbs[i] == BufferHandle.Null)
  1138. {
  1139. _tfbs[i] = Buffer.Create();
  1140. }
  1141. Buffer.Resize(_tfbs[i], buffer.Size);
  1142. Buffer.Copy(buffer.Handle, _tfbs[i], buffer.Offset, 0, buffer.Size);
  1143. GL.BindBufferBase(BufferRangeTarget.TransformFeedbackBuffer, i, _tfbs[i].ToInt32());
  1144. }
  1145. if (_tfEnabled)
  1146. {
  1147. GL.BeginTransformFeedback(_tfTopology);
  1148. }
  1149. }
  1150. public void SetUniformBuffers(ReadOnlySpan<BufferAssignment> buffers)
  1151. {
  1152. SetBuffers(buffers, isStorage: false);
  1153. }
  1154. public void SetUserClipDistance(int index, bool enableClip)
  1155. {
  1156. if (!enableClip)
  1157. {
  1158. GL.Disable(EnableCap.ClipDistance0 + index);
  1159. return;
  1160. }
  1161. GL.Enable(EnableCap.ClipDistance0 + index);
  1162. }
  1163. public void SetVertexAttribs(ReadOnlySpan<VertexAttribDescriptor> vertexAttribs)
  1164. {
  1165. EnsureVertexArray();
  1166. _vertexArray.SetVertexAttributes(vertexAttribs);
  1167. }
  1168. public void SetVertexBuffers(ReadOnlySpan<VertexBufferDescriptor> vertexBuffers)
  1169. {
  1170. EnsureVertexArray();
  1171. _vertexArray.SetVertexBuffers(vertexBuffers);
  1172. }
  1173. public void SetViewports(ReadOnlySpan<Viewport> viewports, bool disableTransform)
  1174. {
  1175. Array.Resize(ref _viewportArray, viewports.Length * 4);
  1176. Array.Resize(ref _depthRangeArray, viewports.Length * 2);
  1177. float[] viewportArray = _viewportArray;
  1178. double[] depthRangeArray = _depthRangeArray;
  1179. for (int index = 0; index < viewports.Length; index++)
  1180. {
  1181. int viewportElemIndex = index * 4;
  1182. Viewport viewport = viewports[index];
  1183. viewportArray[viewportElemIndex + 0] = viewport.Region.X;
  1184. viewportArray[viewportElemIndex + 1] = viewport.Region.Y + (viewport.Region.Height < 0 ? viewport.Region.Height : 0);
  1185. viewportArray[viewportElemIndex + 2] = viewport.Region.Width;
  1186. viewportArray[viewportElemIndex + 3] = MathF.Abs(viewport.Region.Height);
  1187. if (HwCapabilities.SupportsViewportSwizzle)
  1188. {
  1189. GL.NV.ViewportSwizzle(
  1190. index,
  1191. viewport.SwizzleX.Convert(),
  1192. viewport.SwizzleY.Convert(),
  1193. viewport.SwizzleZ.Convert(),
  1194. viewport.SwizzleW.Convert());
  1195. }
  1196. depthRangeArray[index * 2 + 0] = viewport.DepthNear;
  1197. depthRangeArray[index * 2 + 1] = viewport.DepthFar;
  1198. }
  1199. bool flipY = viewports.Length != 0 && viewports[0].Region.Height < 0;
  1200. SetOrigin(flipY ? ClipOrigin.UpperLeft : ClipOrigin.LowerLeft);
  1201. GL.ViewportArray(0, viewports.Length, viewportArray);
  1202. GL.DepthRangeArray(0, viewports.Length, depthRangeArray);
  1203. float disableTransformF = disableTransform ? 1.0f : 0.0f;
  1204. if (_supportBuffer.Data.ViewportInverse.W != disableTransformF || disableTransform)
  1205. {
  1206. float scale = _renderScale[0].X;
  1207. _supportBuffer.UpdateViewportInverse(new Vector4<float>
  1208. {
  1209. X = scale * 2f / viewports[0].Region.Width,
  1210. Y = scale * 2f / viewports[0].Region.Height,
  1211. Z = 1,
  1212. W = disableTransformF
  1213. });
  1214. }
  1215. }
  1216. public void TextureBarrier()
  1217. {
  1218. GL.MemoryBarrier(MemoryBarrierFlags.TextureFetchBarrierBit);
  1219. }
  1220. public void TextureBarrierTiled()
  1221. {
  1222. GL.MemoryBarrier(MemoryBarrierFlags.TextureFetchBarrierBit);
  1223. }
  1224. private void SetBuffers(ReadOnlySpan<BufferAssignment> buffers, bool isStorage)
  1225. {
  1226. BufferRangeTarget target = isStorage ? BufferRangeTarget.ShaderStorageBuffer : BufferRangeTarget.UniformBuffer;
  1227. for (int index = 0; index < buffers.Length; index++)
  1228. {
  1229. BufferAssignment assignment = buffers[index];
  1230. BufferRange buffer = assignment.Range;
  1231. if (buffer.Handle == BufferHandle.Null)
  1232. {
  1233. GL.BindBufferRange(target, assignment.Binding, 0, IntPtr.Zero, 0);
  1234. continue;
  1235. }
  1236. GL.BindBufferRange(target, assignment.Binding, buffer.Handle.ToInt32(), (IntPtr)buffer.Offset, buffer.Size);
  1237. }
  1238. }
  1239. private void SetOrigin(ClipOrigin origin)
  1240. {
  1241. if (_clipOrigin != origin)
  1242. {
  1243. _clipOrigin = origin;
  1244. GL.ClipControl(origin, _clipDepthMode);
  1245. SetFrontFace(_frontFace);
  1246. }
  1247. }
  1248. private void SetFrontFace(FrontFaceDirection frontFace)
  1249. {
  1250. // Changing clip origin will also change the front face to compensate
  1251. // for the flipped viewport, we flip it again here to compensate as
  1252. // this effect is undesirable for us.
  1253. if (_clipOrigin == ClipOrigin.UpperLeft)
  1254. {
  1255. frontFace = frontFace == FrontFaceDirection.Ccw ? FrontFaceDirection.Cw : FrontFaceDirection.Ccw;
  1256. }
  1257. GL.FrontFace(frontFace);
  1258. }
  1259. private void EnsureVertexArray()
  1260. {
  1261. if (_vertexArray == null)
  1262. {
  1263. _vertexArray = new VertexArray();
  1264. _vertexArray.Bind();
  1265. }
  1266. }
  1267. private void EnsureFramebuffer()
  1268. {
  1269. if (_framebuffer == null)
  1270. {
  1271. _framebuffer = new Framebuffer();
  1272. int boundHandle = _framebuffer.Bind();
  1273. _boundDrawFramebuffer = _boundReadFramebuffer = boundHandle;
  1274. GL.Enable(EnableCap.FramebufferSrgb);
  1275. }
  1276. }
  1277. internal (int drawHandle, int readHandle) GetBoundFramebuffers()
  1278. {
  1279. if (BackgroundContextWorker.InBackground)
  1280. {
  1281. return (0, 0);
  1282. }
  1283. return (_boundDrawFramebuffer, _boundReadFramebuffer);
  1284. }
  1285. public void UpdateRenderScale(ReadOnlySpan<float> scales, int totalCount, int fragmentCount)
  1286. {
  1287. bool changed = false;
  1288. for (int index = 0; index < totalCount; index++)
  1289. {
  1290. if (_renderScale[1 + index].X != scales[index])
  1291. {
  1292. _renderScale[1 + index].X = scales[index];
  1293. changed = true;
  1294. }
  1295. }
  1296. // Only update fragment count if there are scales after it for the vertex stage.
  1297. if (fragmentCount != totalCount && fragmentCount != _fragmentScaleCount)
  1298. {
  1299. _fragmentScaleCount = fragmentCount;
  1300. _supportBuffer.UpdateFragmentRenderScaleCount(_fragmentScaleCount);
  1301. }
  1302. if (changed)
  1303. {
  1304. _supportBuffer.UpdateRenderScale(_renderScale, 0, 1 + totalCount);
  1305. }
  1306. }
  1307. private void PrepareForDispatch()
  1308. {
  1309. _unit0Texture?.Bind(0);
  1310. _supportBuffer.Commit();
  1311. }
  1312. private void PreDraw(int vertexCount)
  1313. {
  1314. _vertexArray.PreDraw(vertexCount);
  1315. PreDraw();
  1316. }
  1317. private void PreDrawVbUnbounded()
  1318. {
  1319. _vertexArray.PreDrawVbUnbounded();
  1320. PreDraw();
  1321. }
  1322. private void PreDraw()
  1323. {
  1324. DrawCount++;
  1325. _unit0Texture?.Bind(0);
  1326. _supportBuffer.Commit();
  1327. }
  1328. private void PostDraw()
  1329. {
  1330. if (_tfEnabled)
  1331. {
  1332. for (int i = 0; i < Constants.MaxTransformFeedbackBuffers; i++)
  1333. {
  1334. if (_tfbTargets[i].Handle != BufferHandle.Null)
  1335. {
  1336. Buffer.Copy(_tfbs[i], _tfbTargets[i].Handle, 0, _tfbTargets[i].Offset, _tfbTargets[i].Size);
  1337. }
  1338. }
  1339. }
  1340. }
  1341. public void RestoreComponentMask(int index, bool force = true)
  1342. {
  1343. // If the bound render target is bgra, swap the red and blue masks.
  1344. uint redMask = _fpIsBgra[index].X == 0 ? 1u : 4u;
  1345. uint blueMask = _fpIsBgra[index].X == 0 ? 4u : 1u;
  1346. int shift = index * 4;
  1347. uint componentMask = _componentMasks & _fragmentOutputMap;
  1348. uint checkMask = 0xfu << shift;
  1349. uint componentMaskAtIndex = componentMask & checkMask;
  1350. if (!force && componentMaskAtIndex == (_currentComponentMasks & checkMask))
  1351. {
  1352. return;
  1353. }
  1354. componentMask >>= shift;
  1355. componentMask &= 0xfu;
  1356. GL.ColorMask(
  1357. index,
  1358. (componentMask & redMask) != 0,
  1359. (componentMask & 2u) != 0,
  1360. (componentMask & blueMask) != 0,
  1361. (componentMask & 8u) != 0);
  1362. _currentComponentMasks &= ~checkMask;
  1363. _currentComponentMasks |= componentMaskAtIndex;
  1364. }
  1365. public void RestoreClipControl()
  1366. {
  1367. GL.ClipControl(_clipOrigin, _clipDepthMode);
  1368. }
  1369. public void RestoreScissor0Enable()
  1370. {
  1371. if ((_scissorEnables & 1u) != 0)
  1372. {
  1373. GL.Enable(IndexedEnableCap.ScissorTest, 0);
  1374. }
  1375. }
  1376. public void RestoreRasterizerDiscard()
  1377. {
  1378. if (_rasterizerDiscard)
  1379. {
  1380. GL.Enable(EnableCap.RasterizerDiscard);
  1381. }
  1382. }
  1383. public void RestoreViewport0()
  1384. {
  1385. if (_viewportArray.Length > 0)
  1386. {
  1387. GL.ViewportArray(0, 1, _viewportArray);
  1388. }
  1389. }
  1390. public void RestoreProgram()
  1391. {
  1392. _program?.Bind();
  1393. }
  1394. public void RestoreImages1And2()
  1395. {
  1396. for (int i = 0; i < SavedImages; i++)
  1397. {
  1398. (TextureBase texBase, Format imageFormat) = _images[i];
  1399. if (texBase != null)
  1400. {
  1401. SizedInternalFormat format = FormatTable.GetImageFormat(imageFormat);
  1402. if (format != 0)
  1403. {
  1404. GL.BindImageTexture(i, texBase.Handle, 0, true, 0, TextureAccess.ReadWrite, format);
  1405. continue;
  1406. }
  1407. }
  1408. GL.BindImageTexture(i, 0, 0, true, 0, TextureAccess.ReadWrite, SizedInternalFormat.Rgba8);
  1409. }
  1410. }
  1411. public bool TryHostConditionalRendering(ICounterEvent value, ulong compare, bool isEqual)
  1412. {
  1413. if (value is CounterQueueEvent)
  1414. {
  1415. // Compare an event and a constant value.
  1416. CounterQueueEvent evt = (CounterQueueEvent)value;
  1417. // Easy host conditional rendering when the check matches what GL can do:
  1418. // - Event is of type samples passed.
  1419. // - Result is not a combination of multiple queries.
  1420. // - Comparing against 0.
  1421. // - Event has not already been flushed.
  1422. if (compare == 0 && evt.Type == QueryTarget.SamplesPassed && evt.ClearCounter)
  1423. {
  1424. if (!value.ReserveForHostAccess())
  1425. {
  1426. // If the event has been flushed, then just use the values on the CPU.
  1427. // The query object may already be repurposed for another draw (eg. begin + end).
  1428. return false;
  1429. }
  1430. GL.BeginConditionalRender(evt.Query, isEqual ? ConditionalRenderType.QueryNoWaitInverted : ConditionalRenderType.QueryNoWait);
  1431. _activeConditionalRender = evt;
  1432. return true;
  1433. }
  1434. }
  1435. // The GPU will flush the queries to CPU and evaluate the condition there instead.
  1436. GL.Flush(); // The thread will be stalled manually flushing the counter, so flush GL commands now.
  1437. return false;
  1438. }
  1439. public bool TryHostConditionalRendering(ICounterEvent value, ICounterEvent compare, bool isEqual)
  1440. {
  1441. GL.Flush(); // The GPU thread will be stalled manually flushing the counter, so flush GL commands now.
  1442. return false; // We don't currently have a way to compare two counters for conditional rendering.
  1443. }
  1444. public void EndHostConditionalRendering()
  1445. {
  1446. GL.EndConditionalRender();
  1447. _activeConditionalRender?.ReleaseHostAccess();
  1448. _activeConditionalRender = null;
  1449. }
  1450. public void Dispose()
  1451. {
  1452. _supportBuffer?.Dispose();
  1453. for (int i = 0; i < Constants.MaxTransformFeedbackBuffers; i++)
  1454. {
  1455. if (_tfbs[i] != BufferHandle.Null)
  1456. {
  1457. Buffer.Delete(_tfbs[i]);
  1458. _tfbs[i] = BufferHandle.Null;
  1459. }
  1460. }
  1461. _activeConditionalRender?.ReleaseHostAccess();
  1462. _framebuffer?.Dispose();
  1463. _vertexArray?.Dispose();
  1464. _drawTexture.Dispose();
  1465. }
  1466. }
  1467. }