Pipeline.cs 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308
  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. namespace Ryujinx.Graphics.OpenGL
  9. {
  10. class Pipeline : IPipeline, IDisposable
  11. {
  12. private Program _program;
  13. private bool _rasterizerDiscard;
  14. private VertexArray _vertexArray;
  15. private Framebuffer _framebuffer;
  16. private IntPtr _indexBaseOffset;
  17. private DrawElementsType _elementsType;
  18. private PrimitiveType _primitiveType;
  19. private int _stencilFrontMask;
  20. private bool _depthMask;
  21. private int _boundDrawFramebuffer;
  22. private int _boundReadFramebuffer;
  23. private int[] _fpIsBgra = new int[8];
  24. private float[] _fpRenderScale = new float[65];
  25. private float[] _cpRenderScale = new float[64];
  26. private TextureBase _unit0Texture;
  27. private FrontFaceDirection _frontFace;
  28. private ClipOrigin _clipOrigin;
  29. private ClipDepthMode _clipDepthMode;
  30. private readonly uint[] _componentMasks;
  31. private bool _scissor0Enable = false;
  32. private bool _tfEnabled;
  33. private TransformFeedbackPrimitiveType _tfTopology;
  34. private readonly BufferHandle[] _tfbs;
  35. private readonly BufferRange[] _tfbTargets;
  36. private ColorF _blendConstant;
  37. internal Pipeline()
  38. {
  39. _rasterizerDiscard = false;
  40. _clipOrigin = ClipOrigin.LowerLeft;
  41. _clipDepthMode = ClipDepthMode.NegativeOneToOne;
  42. _componentMasks = new uint[Constants.MaxRenderTargets];
  43. for (int index = 0; index < Constants.MaxRenderTargets; index++)
  44. {
  45. _componentMasks[index] = 0xf;
  46. }
  47. for (int index = 0; index < _fpRenderScale.Length; index++)
  48. {
  49. _fpRenderScale[index] = 1f;
  50. }
  51. for (int index = 0; index < _cpRenderScale.Length; index++)
  52. {
  53. _cpRenderScale[index] = 1f;
  54. }
  55. _tfbs = new BufferHandle[Constants.MaxTransformFeedbackBuffers];
  56. _tfbTargets = new BufferRange[Constants.MaxTransformFeedbackBuffers];
  57. }
  58. public void Barrier()
  59. {
  60. GL.MemoryBarrier(MemoryBarrierFlags.AllBarrierBits);
  61. }
  62. public void BeginTransformFeedback(PrimitiveTopology topology)
  63. {
  64. GL.BeginTransformFeedback(_tfTopology = topology.ConvertToTfType());
  65. _tfEnabled = true;
  66. }
  67. public void ClearRenderTargetColor(int index, uint componentMask, ColorF color)
  68. {
  69. GL.ColorMask(
  70. index,
  71. (componentMask & 1) != 0,
  72. (componentMask & 2) != 0,
  73. (componentMask & 4) != 0,
  74. (componentMask & 8) != 0);
  75. float[] colors = new float[] { color.Red, color.Green, color.Blue, color.Alpha };
  76. GL.ClearBuffer(ClearBuffer.Color, index, colors);
  77. RestoreComponentMask(index);
  78. _framebuffer.SignalModified();
  79. }
  80. public void ClearRenderTargetDepthStencil(float depthValue, bool depthMask, int stencilValue, int stencilMask)
  81. {
  82. bool stencilMaskChanged =
  83. stencilMask != 0 &&
  84. stencilMask != _stencilFrontMask;
  85. bool depthMaskChanged = depthMask && depthMask != _depthMask;
  86. if (stencilMaskChanged)
  87. {
  88. GL.StencilMaskSeparate(StencilFace.Front, stencilMask);
  89. }
  90. if (depthMaskChanged)
  91. {
  92. GL.DepthMask(depthMask);
  93. }
  94. if (depthMask && stencilMask != 0)
  95. {
  96. GL.ClearBuffer(ClearBufferCombined.DepthStencil, 0, depthValue, stencilValue);
  97. }
  98. else if (depthMask)
  99. {
  100. GL.ClearBuffer(ClearBuffer.Depth, 0, ref depthValue);
  101. }
  102. else if (stencilMask != 0)
  103. {
  104. GL.ClearBuffer(ClearBuffer.Stencil, 0, ref stencilValue);
  105. }
  106. if (stencilMaskChanged)
  107. {
  108. GL.StencilMaskSeparate(StencilFace.Front, _stencilFrontMask);
  109. }
  110. if (depthMaskChanged)
  111. {
  112. GL.DepthMask(_depthMask);
  113. }
  114. _framebuffer.SignalModified();
  115. }
  116. public void CopyBuffer(BufferHandle source, BufferHandle destination, int srcOffset, int dstOffset, int size)
  117. {
  118. Buffer.Copy(source, destination, srcOffset, dstOffset, size);
  119. }
  120. public void DispatchCompute(int groupsX, int groupsY, int groupsZ)
  121. {
  122. if (!_program.IsLinked)
  123. {
  124. Logger.Debug?.Print(LogClass.Gpu, "Dispatch error, shader not linked.");
  125. return;
  126. }
  127. PrepareForDispatch();
  128. GL.DispatchCompute(groupsX, groupsY, groupsZ);
  129. }
  130. public void Draw(int vertexCount, int instanceCount, int firstVertex, int firstInstance)
  131. {
  132. if (!_program.IsLinked)
  133. {
  134. Logger.Debug?.Print(LogClass.Gpu, "Draw error, shader not linked.");
  135. return;
  136. }
  137. PreDraw();
  138. if (_primitiveType == PrimitiveType.Quads)
  139. {
  140. DrawQuadsImpl(vertexCount, instanceCount, firstVertex, firstInstance);
  141. }
  142. else if (_primitiveType == PrimitiveType.QuadStrip)
  143. {
  144. DrawQuadStripImpl(vertexCount, instanceCount, firstVertex, firstInstance);
  145. }
  146. else
  147. {
  148. DrawImpl(vertexCount, instanceCount, firstVertex, firstInstance);
  149. }
  150. PostDraw();
  151. }
  152. private void DrawQuadsImpl(
  153. int vertexCount,
  154. int instanceCount,
  155. int firstVertex,
  156. int firstInstance)
  157. {
  158. // TODO: Instanced rendering.
  159. int quadsCount = vertexCount / 4;
  160. int[] firsts = new int[quadsCount];
  161. int[] counts = new int[quadsCount];
  162. for (int quadIndex = 0; quadIndex < quadsCount; quadIndex++)
  163. {
  164. firsts[quadIndex] = firstVertex + quadIndex * 4;
  165. counts[quadIndex] = 4;
  166. }
  167. GL.MultiDrawArrays(
  168. PrimitiveType.TriangleFan,
  169. firsts,
  170. counts,
  171. quadsCount);
  172. }
  173. private void DrawQuadStripImpl(
  174. int vertexCount,
  175. int instanceCount,
  176. int firstVertex,
  177. int firstInstance)
  178. {
  179. int quadsCount = (vertexCount - 2) / 2;
  180. if (firstInstance != 0 || instanceCount != 1)
  181. {
  182. for (int quadIndex = 0; quadIndex < quadsCount; quadIndex++)
  183. {
  184. GL.DrawArraysInstancedBaseInstance(PrimitiveType.TriangleFan, firstVertex + quadIndex * 2, 4, instanceCount, firstInstance);
  185. }
  186. }
  187. else
  188. {
  189. int[] firsts = new int[quadsCount];
  190. int[] counts = new int[quadsCount];
  191. firsts[0] = firstVertex;
  192. counts[0] = 4;
  193. for (int quadIndex = 1; quadIndex < quadsCount; quadIndex++)
  194. {
  195. firsts[quadIndex] = firstVertex + quadIndex * 2;
  196. counts[quadIndex] = 4;
  197. }
  198. GL.MultiDrawArrays(
  199. PrimitiveType.TriangleFan,
  200. firsts,
  201. counts,
  202. quadsCount);
  203. }
  204. }
  205. private void DrawImpl(
  206. int vertexCount,
  207. int instanceCount,
  208. int firstVertex,
  209. int firstInstance)
  210. {
  211. if (firstInstance == 0 && instanceCount == 1)
  212. {
  213. GL.DrawArrays(_primitiveType, firstVertex, vertexCount);
  214. }
  215. else if (firstInstance == 0)
  216. {
  217. GL.DrawArraysInstanced(_primitiveType, firstVertex, vertexCount, instanceCount);
  218. }
  219. else
  220. {
  221. GL.DrawArraysInstancedBaseInstance(
  222. _primitiveType,
  223. firstVertex,
  224. vertexCount,
  225. instanceCount,
  226. firstInstance);
  227. }
  228. }
  229. public void DrawIndexed(
  230. int indexCount,
  231. int instanceCount,
  232. int firstIndex,
  233. int firstVertex,
  234. int firstInstance)
  235. {
  236. if (!_program.IsLinked)
  237. {
  238. Logger.Debug?.Print(LogClass.Gpu, "Draw error, shader not linked.");
  239. return;
  240. }
  241. PreDraw();
  242. int indexElemSize = 1;
  243. switch (_elementsType)
  244. {
  245. case DrawElementsType.UnsignedShort: indexElemSize = 2; break;
  246. case DrawElementsType.UnsignedInt: indexElemSize = 4; break;
  247. }
  248. IntPtr indexBaseOffset = _indexBaseOffset + firstIndex * indexElemSize;
  249. if (_primitiveType == PrimitiveType.Quads)
  250. {
  251. DrawQuadsIndexedImpl(
  252. indexCount,
  253. instanceCount,
  254. indexBaseOffset,
  255. indexElemSize,
  256. firstVertex,
  257. firstInstance);
  258. }
  259. else if (_primitiveType == PrimitiveType.QuadStrip)
  260. {
  261. DrawQuadStripIndexedImpl(
  262. indexCount,
  263. instanceCount,
  264. indexBaseOffset,
  265. indexElemSize,
  266. firstVertex,
  267. firstInstance);
  268. }
  269. else
  270. {
  271. DrawIndexedImpl(
  272. indexCount,
  273. instanceCount,
  274. indexBaseOffset,
  275. firstVertex,
  276. firstInstance);
  277. }
  278. PostDraw();
  279. }
  280. private void DrawQuadsIndexedImpl(
  281. int indexCount,
  282. int instanceCount,
  283. IntPtr indexBaseOffset,
  284. int indexElemSize,
  285. int firstVertex,
  286. int firstInstance)
  287. {
  288. int quadsCount = indexCount / 4;
  289. if (firstInstance != 0 || instanceCount != 1)
  290. {
  291. if (firstVertex != 0 && firstInstance != 0)
  292. {
  293. for (int quadIndex = 0; quadIndex < quadsCount; quadIndex++)
  294. {
  295. GL.DrawElementsInstancedBaseVertexBaseInstance(
  296. PrimitiveType.TriangleFan,
  297. 4,
  298. _elementsType,
  299. indexBaseOffset + quadIndex * 4 * indexElemSize,
  300. instanceCount,
  301. firstVertex,
  302. firstInstance);
  303. }
  304. }
  305. else if (firstInstance != 0)
  306. {
  307. for (int quadIndex = 0; quadIndex < quadsCount; quadIndex++)
  308. {
  309. GL.DrawElementsInstancedBaseInstance(
  310. PrimitiveType.TriangleFan,
  311. 4,
  312. _elementsType,
  313. indexBaseOffset + quadIndex * 4 * indexElemSize,
  314. instanceCount,
  315. firstInstance);
  316. }
  317. }
  318. else
  319. {
  320. for (int quadIndex = 0; quadIndex < quadsCount; quadIndex++)
  321. {
  322. GL.DrawElementsInstanced(
  323. PrimitiveType.TriangleFan,
  324. 4,
  325. _elementsType,
  326. indexBaseOffset + quadIndex * 4 * indexElemSize,
  327. instanceCount);
  328. }
  329. }
  330. }
  331. else
  332. {
  333. IntPtr[] indices = new IntPtr[quadsCount];
  334. int[] counts = new int[quadsCount];
  335. int[] baseVertices = new int[quadsCount];
  336. for (int quadIndex = 0; quadIndex < quadsCount; quadIndex++)
  337. {
  338. indices[quadIndex] = indexBaseOffset + quadIndex * 4 * indexElemSize;
  339. counts[quadIndex] = 4;
  340. baseVertices[quadIndex] = firstVertex;
  341. }
  342. GL.MultiDrawElementsBaseVertex(
  343. PrimitiveType.TriangleFan,
  344. counts,
  345. _elementsType,
  346. indices,
  347. quadsCount,
  348. baseVertices);
  349. }
  350. }
  351. private void DrawQuadStripIndexedImpl(
  352. int indexCount,
  353. int instanceCount,
  354. IntPtr indexBaseOffset,
  355. int indexElemSize,
  356. int firstVertex,
  357. int firstInstance)
  358. {
  359. // TODO: Instanced rendering.
  360. int quadsCount = (indexCount - 2) / 2;
  361. IntPtr[] indices = new IntPtr[quadsCount];
  362. int[] counts = new int[quadsCount];
  363. int[] baseVertices = new int[quadsCount];
  364. indices[0] = indexBaseOffset;
  365. counts[0] = 4;
  366. baseVertices[0] = firstVertex;
  367. for (int quadIndex = 1; quadIndex < quadsCount; quadIndex++)
  368. {
  369. indices[quadIndex] = indexBaseOffset + quadIndex * 2 * indexElemSize;
  370. counts[quadIndex] = 4;
  371. baseVertices[quadIndex] = firstVertex;
  372. }
  373. GL.MultiDrawElementsBaseVertex(
  374. PrimitiveType.TriangleFan,
  375. counts,
  376. _elementsType,
  377. indices,
  378. quadsCount,
  379. baseVertices);
  380. }
  381. private void DrawIndexedImpl(
  382. int indexCount,
  383. int instanceCount,
  384. IntPtr indexBaseOffset,
  385. int firstVertex,
  386. int firstInstance)
  387. {
  388. if (firstInstance == 0 && firstVertex == 0 && instanceCount == 1)
  389. {
  390. GL.DrawElements(_primitiveType, indexCount, _elementsType, indexBaseOffset);
  391. }
  392. else if (firstInstance == 0 && instanceCount == 1)
  393. {
  394. GL.DrawElementsBaseVertex(
  395. _primitiveType,
  396. indexCount,
  397. _elementsType,
  398. indexBaseOffset,
  399. firstVertex);
  400. }
  401. else if (firstInstance == 0 && firstVertex == 0)
  402. {
  403. GL.DrawElementsInstanced(
  404. _primitiveType,
  405. indexCount,
  406. _elementsType,
  407. indexBaseOffset,
  408. instanceCount);
  409. }
  410. else if (firstInstance == 0)
  411. {
  412. GL.DrawElementsInstancedBaseVertex(
  413. _primitiveType,
  414. indexCount,
  415. _elementsType,
  416. indexBaseOffset,
  417. instanceCount,
  418. firstVertex);
  419. }
  420. else if (firstVertex == 0)
  421. {
  422. GL.DrawElementsInstancedBaseInstance(
  423. _primitiveType,
  424. indexCount,
  425. _elementsType,
  426. indexBaseOffset,
  427. instanceCount,
  428. firstInstance);
  429. }
  430. else
  431. {
  432. GL.DrawElementsInstancedBaseVertexBaseInstance(
  433. _primitiveType,
  434. indexCount,
  435. _elementsType,
  436. indexBaseOffset,
  437. instanceCount,
  438. firstVertex,
  439. firstInstance);
  440. }
  441. }
  442. public void EndTransformFeedback()
  443. {
  444. GL.EndTransformFeedback();
  445. _tfEnabled = false;
  446. }
  447. public void SetAlphaTest(bool enable, float reference, CompareOp op)
  448. {
  449. if (!enable)
  450. {
  451. GL.Disable(EnableCap.AlphaTest);
  452. return;
  453. }
  454. GL.AlphaFunc((AlphaFunction)op.Convert(), reference);
  455. GL.Enable(EnableCap.AlphaTest);
  456. }
  457. public void SetBlendState(int index, BlendDescriptor blend)
  458. {
  459. if (!blend.Enable)
  460. {
  461. GL.Disable(IndexedEnableCap.Blend, index);
  462. return;
  463. }
  464. GL.BlendEquationSeparate(
  465. index,
  466. blend.ColorOp.Convert(),
  467. blend.AlphaOp.Convert());
  468. GL.BlendFuncSeparate(
  469. index,
  470. (BlendingFactorSrc)blend.ColorSrcFactor.Convert(),
  471. (BlendingFactorDest)blend.ColorDstFactor.Convert(),
  472. (BlendingFactorSrc)blend.AlphaSrcFactor.Convert(),
  473. (BlendingFactorDest)blend.AlphaDstFactor.Convert());
  474. static bool IsDualSource(BlendFactor factor)
  475. {
  476. switch (factor)
  477. {
  478. case BlendFactor.Src1Color:
  479. case BlendFactor.Src1ColorGl:
  480. case BlendFactor.Src1Alpha:
  481. case BlendFactor.Src1AlphaGl:
  482. case BlendFactor.OneMinusSrc1Color:
  483. case BlendFactor.OneMinusSrc1ColorGl:
  484. case BlendFactor.OneMinusSrc1Alpha:
  485. case BlendFactor.OneMinusSrc1AlphaGl:
  486. return true;
  487. }
  488. return false;
  489. }
  490. EnsureFramebuffer();
  491. _framebuffer.SetDualSourceBlend(
  492. IsDualSource(blend.ColorSrcFactor) ||
  493. IsDualSource(blend.ColorDstFactor) ||
  494. IsDualSource(blend.AlphaSrcFactor) ||
  495. IsDualSource(blend.AlphaDstFactor));
  496. if (_blendConstant != blend.BlendConstant)
  497. {
  498. _blendConstant = blend.BlendConstant;
  499. GL.BlendColor(
  500. blend.BlendConstant.Red,
  501. blend.BlendConstant.Green,
  502. blend.BlendConstant.Blue,
  503. blend.BlendConstant.Alpha);
  504. }
  505. GL.Enable(IndexedEnableCap.Blend, index);
  506. }
  507. public void SetDepthBias(PolygonModeMask enables, float factor, float units, float clamp)
  508. {
  509. if ((enables & PolygonModeMask.Point) != 0)
  510. {
  511. GL.Enable(EnableCap.PolygonOffsetPoint);
  512. }
  513. else
  514. {
  515. GL.Disable(EnableCap.PolygonOffsetPoint);
  516. }
  517. if ((enables & PolygonModeMask.Line) != 0)
  518. {
  519. GL.Enable(EnableCap.PolygonOffsetLine);
  520. }
  521. else
  522. {
  523. GL.Disable(EnableCap.PolygonOffsetLine);
  524. }
  525. if ((enables & PolygonModeMask.Fill) != 0)
  526. {
  527. GL.Enable(EnableCap.PolygonOffsetFill);
  528. }
  529. else
  530. {
  531. GL.Disable(EnableCap.PolygonOffsetFill);
  532. }
  533. if (enables == 0)
  534. {
  535. return;
  536. }
  537. if (HwCapabilities.SupportsPolygonOffsetClamp)
  538. {
  539. GL.PolygonOffsetClamp(factor, units, clamp);
  540. }
  541. else
  542. {
  543. GL.PolygonOffset(factor, units);
  544. }
  545. }
  546. public void SetDepthClamp(bool clamp)
  547. {
  548. if (!clamp)
  549. {
  550. GL.Disable(EnableCap.DepthClamp);
  551. return;
  552. }
  553. GL.Enable(EnableCap.DepthClamp);
  554. }
  555. public void SetDepthMode(DepthMode mode)
  556. {
  557. ClipDepthMode depthMode = mode.Convert();
  558. if (_clipDepthMode != depthMode)
  559. {
  560. _clipDepthMode = depthMode;
  561. GL.ClipControl(_clipOrigin, depthMode);
  562. }
  563. }
  564. public void SetDepthTest(DepthTestDescriptor depthTest)
  565. {
  566. if (depthTest.TestEnable)
  567. {
  568. GL.Enable(EnableCap.DepthTest);
  569. GL.DepthFunc((DepthFunction)depthTest.Func.Convert());
  570. }
  571. else
  572. {
  573. GL.Disable(EnableCap.DepthTest);
  574. }
  575. GL.DepthMask(depthTest.WriteEnable);
  576. _depthMask = depthTest.WriteEnable;
  577. }
  578. public void SetFaceCulling(bool enable, Face face)
  579. {
  580. if (!enable)
  581. {
  582. GL.Disable(EnableCap.CullFace);
  583. return;
  584. }
  585. GL.CullFace(face.Convert());
  586. GL.Enable(EnableCap.CullFace);
  587. }
  588. public void SetFrontFace(FrontFace frontFace)
  589. {
  590. SetFrontFace(_frontFace = frontFace.Convert());
  591. }
  592. public void SetImage(int binding, ITexture texture, Format imageFormat)
  593. {
  594. if (texture == null)
  595. {
  596. return;
  597. }
  598. TextureBase texBase = (TextureBase)texture;
  599. SizedInternalFormat format = FormatTable.GetImageFormat(imageFormat);
  600. if (format != 0)
  601. {
  602. GL.BindImageTexture(binding, texBase.Handle, 0, true, 0, TextureAccess.ReadWrite, format);
  603. }
  604. }
  605. public void SetIndexBuffer(BufferRange buffer, IndexType type)
  606. {
  607. _elementsType = type.Convert();
  608. _indexBaseOffset = (IntPtr)buffer.Offset;
  609. EnsureVertexArray();
  610. _vertexArray.SetIndexBuffer(buffer.Handle);
  611. }
  612. public void SetLogicOpState(bool enable, LogicalOp op)
  613. {
  614. if (enable)
  615. {
  616. GL.Enable(EnableCap.ColorLogicOp);
  617. GL.LogicOp((LogicOp)op.Convert());
  618. }
  619. else
  620. {
  621. GL.Disable(EnableCap.ColorLogicOp);
  622. }
  623. }
  624. public void SetPointParameters(float size, bool isProgramPointSize, bool enablePointSprite, Origin origin)
  625. {
  626. // GL_POINT_SPRITE was deprecated in core profile 3.2+ and causes GL_INVALID_ENUM when set.
  627. // As we don't know if the current context is core or compat, it's safer to keep this code.
  628. if (enablePointSprite)
  629. {
  630. GL.Enable(EnableCap.PointSprite);
  631. }
  632. else
  633. {
  634. GL.Disable(EnableCap.PointSprite);
  635. }
  636. if (isProgramPointSize)
  637. {
  638. GL.Enable(EnableCap.ProgramPointSize);
  639. }
  640. else
  641. {
  642. GL.Disable(EnableCap.ProgramPointSize);
  643. }
  644. GL.PointParameter(origin == Origin.LowerLeft
  645. ? PointSpriteCoordOriginParameter.LowerLeft
  646. : PointSpriteCoordOriginParameter.UpperLeft);
  647. // Games seem to set point size to 0 which generates a GL_INVALID_VALUE
  648. // From the spec, GL_INVALID_VALUE is generated if size is less than or equal to 0.
  649. GL.PointSize(Math.Max(float.Epsilon, size));
  650. }
  651. public void SetPrimitiveRestart(bool enable, int index)
  652. {
  653. if (!enable)
  654. {
  655. GL.Disable(EnableCap.PrimitiveRestart);
  656. return;
  657. }
  658. GL.PrimitiveRestartIndex(index);
  659. GL.Enable(EnableCap.PrimitiveRestart);
  660. }
  661. public void SetPrimitiveTopology(PrimitiveTopology topology)
  662. {
  663. _primitiveType = topology.Convert();
  664. }
  665. public void SetProgram(IProgram program)
  666. {
  667. _program = (Program)program;
  668. if (_tfEnabled)
  669. {
  670. GL.EndTransformFeedback();
  671. _program.Bind();
  672. GL.BeginTransformFeedback(_tfTopology);
  673. }
  674. else
  675. {
  676. _program.Bind();
  677. }
  678. UpdateFpIsBgra();
  679. SetRenderTargetScale(_fpRenderScale[0]);
  680. }
  681. public void SetRasterizerDiscard(bool discard)
  682. {
  683. if (discard)
  684. {
  685. GL.Enable(EnableCap.RasterizerDiscard);
  686. }
  687. else
  688. {
  689. GL.Disable(EnableCap.RasterizerDiscard);
  690. }
  691. _rasterizerDiscard = discard;
  692. }
  693. public void SetRenderTargetScale(float scale)
  694. {
  695. _fpRenderScale[0] = scale;
  696. if (_program != null && _program.FragmentRenderScaleUniform != -1)
  697. {
  698. GL.Uniform1(_program.FragmentRenderScaleUniform, 1, _fpRenderScale); // Just the first element.
  699. }
  700. }
  701. public void SetRenderTargetColorMasks(ReadOnlySpan<uint> componentMasks)
  702. {
  703. for (int index = 0; index < componentMasks.Length; index++)
  704. {
  705. _componentMasks[index] = componentMasks[index];
  706. RestoreComponentMask(index);
  707. }
  708. }
  709. public void SetRenderTargets(ITexture[] colors, ITexture depthStencil)
  710. {
  711. EnsureFramebuffer();
  712. for (int index = 0; index < colors.Length; index++)
  713. {
  714. TextureView color = (TextureView)colors[index];
  715. _framebuffer.AttachColor(index, color);
  716. _fpIsBgra[index] = color != null && color.Format.IsBgra8() ? 1 : 0;
  717. }
  718. UpdateFpIsBgra();
  719. TextureView depthStencilView = (TextureView)depthStencil;
  720. _framebuffer.AttachDepthStencil(depthStencilView);
  721. _framebuffer.SetDrawBuffers(colors.Length);
  722. }
  723. public void SetSampler(int binding, ISampler sampler)
  724. {
  725. if (sampler == null)
  726. {
  727. return;
  728. }
  729. ((Sampler)sampler).Bind(binding);
  730. }
  731. public void SetScissorEnable(int index, bool enable)
  732. {
  733. if (enable)
  734. {
  735. GL.Enable(IndexedEnableCap.ScissorTest, index);
  736. }
  737. else
  738. {
  739. GL.Disable(IndexedEnableCap.ScissorTest, index);
  740. }
  741. if (index == 0)
  742. {
  743. _scissor0Enable = enable;
  744. }
  745. }
  746. public void SetScissor(int index, int x, int y, int width, int height)
  747. {
  748. GL.ScissorIndexed(index, x, y, width, height);
  749. }
  750. public void SetStencilTest(StencilTestDescriptor stencilTest)
  751. {
  752. if (!stencilTest.TestEnable)
  753. {
  754. GL.Disable(EnableCap.StencilTest);
  755. return;
  756. }
  757. GL.StencilOpSeparate(
  758. StencilFace.Front,
  759. stencilTest.FrontSFail.Convert(),
  760. stencilTest.FrontDpFail.Convert(),
  761. stencilTest.FrontDpPass.Convert());
  762. GL.StencilFuncSeparate(
  763. StencilFace.Front,
  764. (StencilFunction)stencilTest.FrontFunc.Convert(),
  765. stencilTest.FrontFuncRef,
  766. stencilTest.FrontFuncMask);
  767. GL.StencilMaskSeparate(StencilFace.Front, stencilTest.FrontMask);
  768. GL.StencilOpSeparate(
  769. StencilFace.Back,
  770. stencilTest.BackSFail.Convert(),
  771. stencilTest.BackDpFail.Convert(),
  772. stencilTest.BackDpPass.Convert());
  773. GL.StencilFuncSeparate(
  774. StencilFace.Back,
  775. (StencilFunction)stencilTest.BackFunc.Convert(),
  776. stencilTest.BackFuncRef,
  777. stencilTest.BackFuncMask);
  778. GL.StencilMaskSeparate(StencilFace.Back, stencilTest.BackMask);
  779. GL.Enable(EnableCap.StencilTest);
  780. _stencilFrontMask = stencilTest.FrontMask;
  781. }
  782. public void SetStorageBuffers(ReadOnlySpan<BufferRange> buffers)
  783. {
  784. SetBuffers(buffers, isStorage: true);
  785. }
  786. public void SetTexture(int binding, ITexture texture)
  787. {
  788. if (texture == null)
  789. {
  790. return;
  791. }
  792. if (binding == 0)
  793. {
  794. _unit0Texture = (TextureBase)texture;
  795. }
  796. else
  797. {
  798. ((TextureBase)texture).Bind(binding);
  799. }
  800. }
  801. public void SetTransformFeedbackBuffers(ReadOnlySpan<BufferRange> buffers)
  802. {
  803. if (_tfEnabled)
  804. {
  805. GL.EndTransformFeedback();
  806. }
  807. int count = Math.Min(buffers.Length, Constants.MaxTransformFeedbackBuffers);
  808. for (int i = 0; i < count; i++)
  809. {
  810. BufferRange buffer = buffers[i];
  811. _tfbTargets[i] = buffer;
  812. if (buffer.Handle == BufferHandle.Null)
  813. {
  814. GL.BindBufferBase(BufferRangeTarget.TransformFeedbackBuffer, i, 0);
  815. continue;
  816. }
  817. if (_tfbs[i] == BufferHandle.Null)
  818. {
  819. _tfbs[i] = Buffer.Create();
  820. }
  821. Buffer.Resize(_tfbs[i], buffer.Size);
  822. Buffer.Copy(buffer.Handle, _tfbs[i], buffer.Offset, 0, buffer.Size);
  823. GL.BindBufferBase(BufferRangeTarget.TransformFeedbackBuffer, i, _tfbs[i].ToInt32());
  824. }
  825. if (_tfEnabled)
  826. {
  827. GL.BeginTransformFeedback(_tfTopology);
  828. }
  829. }
  830. public void SetUniformBuffers(ReadOnlySpan<BufferRange> buffers)
  831. {
  832. SetBuffers(buffers, isStorage: false);
  833. }
  834. public void SetUserClipDistance(int index, bool enableClip)
  835. {
  836. if (!enableClip)
  837. {
  838. GL.Disable(EnableCap.ClipDistance0 + index);
  839. return;
  840. }
  841. GL.Enable(EnableCap.ClipDistance0 + index);
  842. }
  843. public void SetVertexAttribs(ReadOnlySpan<VertexAttribDescriptor> vertexAttribs)
  844. {
  845. EnsureVertexArray();
  846. _vertexArray.SetVertexAttributes(vertexAttribs);
  847. }
  848. public void SetVertexBuffers(ReadOnlySpan<VertexBufferDescriptor> vertexBuffers)
  849. {
  850. EnsureVertexArray();
  851. _vertexArray.SetVertexBuffers(vertexBuffers);
  852. }
  853. public void SetViewports(int first, ReadOnlySpan<Viewport> viewports)
  854. {
  855. float[] viewportArray = new float[viewports.Length * 4];
  856. double[] depthRangeArray = new double[viewports.Length * 2];
  857. for (int index = 0; index < viewports.Length; index++)
  858. {
  859. int viewportElemIndex = index * 4;
  860. Viewport viewport = viewports[index];
  861. viewportArray[viewportElemIndex + 0] = viewport.Region.X;
  862. viewportArray[viewportElemIndex + 1] = viewport.Region.Y + (viewport.Region.Height < 0 ? viewport.Region.Height : 0);
  863. viewportArray[viewportElemIndex + 2] = viewport.Region.Width;
  864. viewportArray[viewportElemIndex + 3] = MathF.Abs(viewport.Region.Height);
  865. if (HwCapabilities.SupportsViewportSwizzle)
  866. {
  867. GL.NV.ViewportSwizzle(
  868. index,
  869. viewport.SwizzleX.Convert(),
  870. viewport.SwizzleY.Convert(),
  871. viewport.SwizzleZ.Convert(),
  872. viewport.SwizzleW.Convert());
  873. }
  874. depthRangeArray[index * 2 + 0] = viewport.DepthNear;
  875. depthRangeArray[index * 2 + 1] = viewport.DepthFar;
  876. }
  877. bool flipY = viewports.Length != 0 && viewports[0].Region.Height < 0;
  878. SetOrigin(flipY ? ClipOrigin.UpperLeft : ClipOrigin.LowerLeft);
  879. GL.ViewportArray(first, viewports.Length, viewportArray);
  880. GL.DepthRangeArray(first, viewports.Length, depthRangeArray);
  881. }
  882. public void TextureBarrier()
  883. {
  884. GL.MemoryBarrier(MemoryBarrierFlags.TextureFetchBarrierBit);
  885. }
  886. public void TextureBarrierTiled()
  887. {
  888. GL.MemoryBarrier(MemoryBarrierFlags.TextureFetchBarrierBit);
  889. }
  890. private void SetBuffers(ReadOnlySpan<BufferRange> buffers, bool isStorage)
  891. {
  892. BufferRangeTarget target = isStorage ? BufferRangeTarget.ShaderStorageBuffer : BufferRangeTarget.UniformBuffer;
  893. for (int index = 0; index < buffers.Length; index++)
  894. {
  895. BufferRange buffer = buffers[index];
  896. if (buffer.Handle == BufferHandle.Null)
  897. {
  898. GL.BindBufferRange(target, index, 0, IntPtr.Zero, 0);
  899. continue;
  900. }
  901. GL.BindBufferRange(target, index, buffer.Handle.ToInt32(), (IntPtr)buffer.Offset, buffer.Size);
  902. }
  903. }
  904. private void SetOrigin(ClipOrigin origin)
  905. {
  906. if (_clipOrigin != origin)
  907. {
  908. _clipOrigin = origin;
  909. GL.ClipControl(origin, _clipDepthMode);
  910. SetFrontFace(_frontFace);
  911. }
  912. }
  913. private void SetFrontFace(FrontFaceDirection frontFace)
  914. {
  915. // Changing clip origin will also change the front face to compensate
  916. // for the flipped viewport, we flip it again here to compensate as
  917. // this effect is undesirable for us.
  918. if (_clipOrigin == ClipOrigin.UpperLeft)
  919. {
  920. frontFace = frontFace == FrontFaceDirection.Ccw ? FrontFaceDirection.Cw : FrontFaceDirection.Ccw;
  921. }
  922. GL.FrontFace(frontFace);
  923. }
  924. private void EnsureVertexArray()
  925. {
  926. if (_vertexArray == null)
  927. {
  928. _vertexArray = new VertexArray();
  929. _vertexArray.Bind();
  930. }
  931. }
  932. private void EnsureFramebuffer()
  933. {
  934. if (_framebuffer == null)
  935. {
  936. _framebuffer = new Framebuffer();
  937. int boundHandle = _framebuffer.Bind();
  938. _boundDrawFramebuffer = _boundReadFramebuffer = boundHandle;
  939. GL.Enable(EnableCap.FramebufferSrgb);
  940. }
  941. }
  942. internal (int drawHandle, int readHandle) GetBoundFramebuffers()
  943. {
  944. if (BackgroundContextWorker.InBackground)
  945. {
  946. return (0, 0);
  947. }
  948. return (_boundDrawFramebuffer, _boundReadFramebuffer);
  949. }
  950. private void UpdateFpIsBgra()
  951. {
  952. if (_program != null)
  953. {
  954. GL.Uniform1(_program.FragmentIsBgraUniform, 8, _fpIsBgra);
  955. }
  956. }
  957. public void UpdateRenderScale(ShaderStage stage, float[] scales, int textureCount, int imageCount)
  958. {
  959. if (_program != null)
  960. {
  961. switch (stage)
  962. {
  963. case ShaderStage.Fragment:
  964. if (_program.FragmentRenderScaleUniform != -1)
  965. {
  966. Array.Copy(scales, 0, _fpRenderScale, 1, textureCount + imageCount);
  967. GL.Uniform1(_program.FragmentRenderScaleUniform, 1 + textureCount + imageCount, _fpRenderScale);
  968. }
  969. break;
  970. case ShaderStage.Compute:
  971. if (_program.ComputeRenderScaleUniform != -1)
  972. {
  973. Array.Copy(scales, 0, _cpRenderScale, 0, textureCount + imageCount);
  974. GL.Uniform1(_program.ComputeRenderScaleUniform, textureCount + imageCount, _cpRenderScale);
  975. }
  976. break;
  977. }
  978. }
  979. }
  980. private void PrepareForDispatch()
  981. {
  982. if (_unit0Texture != null)
  983. {
  984. _unit0Texture.Bind(0);
  985. }
  986. }
  987. private void PreDraw()
  988. {
  989. _vertexArray.Validate();
  990. if (_unit0Texture != null)
  991. {
  992. _unit0Texture.Bind(0);
  993. }
  994. }
  995. private void PostDraw()
  996. {
  997. _framebuffer?.SignalModified();
  998. if (_tfEnabled)
  999. {
  1000. for (int i = 0; i < Constants.MaxTransformFeedbackBuffers; i++)
  1001. {
  1002. if (_tfbTargets[i].Handle != BufferHandle.Null)
  1003. {
  1004. Buffer.Copy(_tfbs[i], _tfbTargets[i].Handle, 0, _tfbTargets[i].Offset, _tfbTargets[i].Size);
  1005. }
  1006. }
  1007. }
  1008. }
  1009. private void RestoreComponentMask(int index)
  1010. {
  1011. GL.ColorMask(
  1012. index,
  1013. (_componentMasks[index] & 1u) != 0,
  1014. (_componentMasks[index] & 2u) != 0,
  1015. (_componentMasks[index] & 4u) != 0,
  1016. (_componentMasks[index] & 8u) != 0);
  1017. }
  1018. public void RestoreScissor0Enable()
  1019. {
  1020. if (_scissor0Enable)
  1021. {
  1022. GL.Enable(IndexedEnableCap.ScissorTest, 0);
  1023. }
  1024. }
  1025. public void RestoreRasterizerDiscard()
  1026. {
  1027. if (_rasterizerDiscard)
  1028. {
  1029. GL.Enable(EnableCap.RasterizerDiscard);
  1030. }
  1031. }
  1032. public bool TryHostConditionalRendering(ICounterEvent value, ulong compare, bool isEqual)
  1033. {
  1034. if (value is CounterQueueEvent)
  1035. {
  1036. // Compare an event and a constant value.
  1037. CounterQueueEvent evt = (CounterQueueEvent)value;
  1038. // Easy host conditional rendering when the check matches what GL can do:
  1039. // - Event is of type samples passed.
  1040. // - Result is not a combination of multiple queries.
  1041. // - Comparing against 0.
  1042. // - Event has not already been flushed.
  1043. if (evt.Disposed)
  1044. {
  1045. // If the event has been flushed, then just use the values on the CPU.
  1046. // The query object may already be repurposed for another draw (eg. begin + end).
  1047. return false;
  1048. }
  1049. if (compare == 0 && evt.Type == QueryTarget.SamplesPassed && evt.ClearCounter)
  1050. {
  1051. GL.BeginConditionalRender(evt.Query, isEqual ? ConditionalRenderType.QueryNoWaitInverted : ConditionalRenderType.QueryNoWait);
  1052. return true;
  1053. }
  1054. }
  1055. // The GPU will flush the queries to CPU and evaluate the condition there instead.
  1056. GL.Flush(); // The thread will be stalled manually flushing the counter, so flush GL commands now.
  1057. return false;
  1058. }
  1059. public bool TryHostConditionalRendering(ICounterEvent value, ICounterEvent compare, bool isEqual)
  1060. {
  1061. GL.Flush(); // The GPU thread will be stalled manually flushing the counter, so flush GL commands now.
  1062. return false; // We don't currently have a way to compare two counters for conditional rendering.
  1063. }
  1064. public void EndHostConditionalRendering()
  1065. {
  1066. GL.EndConditionalRender();
  1067. }
  1068. public void Dispose()
  1069. {
  1070. for (int i = 0; i < Constants.MaxTransformFeedbackBuffers; i++)
  1071. {
  1072. if (_tfbs[i] != BufferHandle.Null)
  1073. {
  1074. Buffer.Delete(_tfbs[i]);
  1075. _tfbs[i] = BufferHandle.Null;
  1076. }
  1077. }
  1078. _framebuffer?.Dispose();
  1079. _vertexArray?.Dispose();
  1080. }
  1081. }
  1082. }