Pipeline.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080
  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 bool _depthTest;
  22. private bool _hasDepthBuffer;
  23. private TextureBase _unit0Texture;
  24. private ClipOrigin _clipOrigin;
  25. private ClipDepthMode _clipDepthMode;
  26. private readonly uint[] _componentMasks;
  27. private bool _scissor0Enable = false;
  28. ColorF _blendConstant = new ColorF(0, 0, 0, 0);
  29. internal Pipeline()
  30. {
  31. _rasterizerDiscard = false;
  32. _clipOrigin = ClipOrigin.LowerLeft;
  33. _clipDepthMode = ClipDepthMode.NegativeOneToOne;
  34. _componentMasks = new uint[Constants.MaxRenderTargets];
  35. for (int index = 0; index < Constants.MaxRenderTargets; index++)
  36. {
  37. _componentMasks[index] = 0xf;
  38. }
  39. }
  40. public void Barrier()
  41. {
  42. GL.MemoryBarrier(MemoryBarrierFlags.AllBarrierBits);
  43. }
  44. public void ClearRenderTargetColor(int index, uint componentMask, ColorF color)
  45. {
  46. GL.ColorMask(
  47. index,
  48. (componentMask & 1) != 0,
  49. (componentMask & 2) != 0,
  50. (componentMask & 4) != 0,
  51. (componentMask & 8) != 0);
  52. float[] colors = new float[] { color.Red, color.Green, color.Blue, color.Alpha };
  53. GL.ClearBuffer(ClearBuffer.Color, index, colors);
  54. RestoreComponentMask(index);
  55. _framebuffer.SignalModified();
  56. }
  57. public void ClearRenderTargetDepthStencil(float depthValue, bool depthMask, int stencilValue, int stencilMask)
  58. {
  59. bool stencilMaskChanged =
  60. stencilMask != 0 &&
  61. stencilMask != _stencilFrontMask;
  62. bool depthMaskChanged = depthMask && depthMask != _depthMask;
  63. if (stencilMaskChanged)
  64. {
  65. GL.StencilMaskSeparate(StencilFace.Front, stencilMask);
  66. }
  67. if (depthMaskChanged)
  68. {
  69. GL.DepthMask(depthMask);
  70. }
  71. if (depthMask && stencilMask != 0)
  72. {
  73. GL.ClearBuffer(ClearBufferCombined.DepthStencil, 0, depthValue, stencilValue);
  74. }
  75. else if (depthMask)
  76. {
  77. GL.ClearBuffer(ClearBuffer.Depth, 0, ref depthValue);
  78. }
  79. else if (stencilMask != 0)
  80. {
  81. GL.ClearBuffer(ClearBuffer.Stencil, 0, ref stencilValue);
  82. }
  83. if (stencilMaskChanged)
  84. {
  85. GL.StencilMaskSeparate(StencilFace.Front, _stencilFrontMask);
  86. }
  87. if (depthMaskChanged)
  88. {
  89. GL.DepthMask(_depthMask);
  90. }
  91. _framebuffer.SignalModified();
  92. }
  93. public void CopyBuffer(BufferHandle source, BufferHandle destination, int srcOffset, int dstOffset, int size)
  94. {
  95. Buffer.Copy(source, destination, srcOffset, dstOffset, size);
  96. }
  97. public void DispatchCompute(int groupsX, int groupsY, int groupsZ)
  98. {
  99. if (!_program.IsLinked)
  100. {
  101. Logger.PrintDebug(LogClass.Gpu, "Dispatch error, shader not linked.");
  102. return;
  103. }
  104. PrepareForDispatch();
  105. GL.DispatchCompute(groupsX, groupsY, groupsZ);
  106. }
  107. public void Draw(int vertexCount, int instanceCount, int firstVertex, int firstInstance)
  108. {
  109. if (!_program.IsLinked)
  110. {
  111. Logger.PrintDebug(LogClass.Gpu, "Draw error, shader not linked.");
  112. return;
  113. }
  114. PrepareForDraw();
  115. if (_primitiveType == PrimitiveType.Quads)
  116. {
  117. DrawQuadsImpl(vertexCount, instanceCount, firstVertex, firstInstance);
  118. }
  119. else if (_primitiveType == PrimitiveType.QuadStrip)
  120. {
  121. DrawQuadStripImpl(vertexCount, instanceCount, firstVertex, firstInstance);
  122. }
  123. else
  124. {
  125. DrawImpl(vertexCount, instanceCount, firstVertex, firstInstance);
  126. }
  127. _framebuffer.SignalModified();
  128. }
  129. private void DrawQuadsImpl(
  130. int vertexCount,
  131. int instanceCount,
  132. int firstVertex,
  133. int firstInstance)
  134. {
  135. // TODO: Instanced rendering.
  136. int quadsCount = vertexCount / 4;
  137. int[] firsts = new int[quadsCount];
  138. int[] counts = new int[quadsCount];
  139. for (int quadIndex = 0; quadIndex < quadsCount; quadIndex++)
  140. {
  141. firsts[quadIndex] = firstVertex + quadIndex * 4;
  142. counts[quadIndex] = 4;
  143. }
  144. GL.MultiDrawArrays(
  145. PrimitiveType.TriangleFan,
  146. firsts,
  147. counts,
  148. quadsCount);
  149. }
  150. private void DrawQuadStripImpl(
  151. int vertexCount,
  152. int instanceCount,
  153. int firstVertex,
  154. int firstInstance)
  155. {
  156. int quadsCount = (vertexCount - 2) / 2;
  157. if (firstInstance != 0 || instanceCount != 1)
  158. {
  159. for (int quadIndex = 0; quadIndex < quadsCount; quadIndex++)
  160. {
  161. GL.DrawArraysInstancedBaseInstance(PrimitiveType.TriangleFan, firstVertex + quadIndex * 2, 4, instanceCount, firstInstance);
  162. }
  163. }
  164. else
  165. {
  166. int[] firsts = new int[quadsCount];
  167. int[] counts = new int[quadsCount];
  168. firsts[0] = firstVertex;
  169. counts[0] = 4;
  170. for (int quadIndex = 1; quadIndex < quadsCount; quadIndex++)
  171. {
  172. firsts[quadIndex] = firstVertex + quadIndex * 2;
  173. counts[quadIndex] = 4;
  174. }
  175. GL.MultiDrawArrays(
  176. PrimitiveType.TriangleFan,
  177. firsts,
  178. counts,
  179. quadsCount);
  180. }
  181. }
  182. private void DrawImpl(
  183. int vertexCount,
  184. int instanceCount,
  185. int firstVertex,
  186. int firstInstance)
  187. {
  188. if (firstInstance == 0 && instanceCount == 1)
  189. {
  190. GL.DrawArrays(_primitiveType, firstVertex, vertexCount);
  191. }
  192. else if (firstInstance == 0)
  193. {
  194. GL.DrawArraysInstanced(_primitiveType, firstVertex, vertexCount, instanceCount);
  195. }
  196. else
  197. {
  198. GL.DrawArraysInstancedBaseInstance(
  199. _primitiveType,
  200. firstVertex,
  201. vertexCount,
  202. instanceCount,
  203. firstInstance);
  204. }
  205. }
  206. public void DrawIndexed(
  207. int indexCount,
  208. int instanceCount,
  209. int firstIndex,
  210. int firstVertex,
  211. int firstInstance)
  212. {
  213. if (!_program.IsLinked)
  214. {
  215. Logger.PrintDebug(LogClass.Gpu, "Draw error, shader not linked.");
  216. return;
  217. }
  218. PrepareForDraw();
  219. int indexElemSize = 1;
  220. switch (_elementsType)
  221. {
  222. case DrawElementsType.UnsignedShort: indexElemSize = 2; break;
  223. case DrawElementsType.UnsignedInt: indexElemSize = 4; break;
  224. }
  225. IntPtr indexBaseOffset = _indexBaseOffset + firstIndex * indexElemSize;
  226. if (_primitiveType == PrimitiveType.Quads)
  227. {
  228. DrawQuadsIndexedImpl(
  229. indexCount,
  230. instanceCount,
  231. indexBaseOffset,
  232. indexElemSize,
  233. firstVertex,
  234. firstInstance);
  235. }
  236. else if (_primitiveType == PrimitiveType.QuadStrip)
  237. {
  238. DrawQuadStripIndexedImpl(
  239. indexCount,
  240. instanceCount,
  241. indexBaseOffset,
  242. indexElemSize,
  243. firstVertex,
  244. firstInstance);
  245. }
  246. else
  247. {
  248. DrawIndexedImpl(
  249. indexCount,
  250. instanceCount,
  251. indexBaseOffset,
  252. firstVertex,
  253. firstInstance);
  254. }
  255. _framebuffer.SignalModified();
  256. }
  257. private void DrawQuadsIndexedImpl(
  258. int indexCount,
  259. int instanceCount,
  260. IntPtr indexBaseOffset,
  261. int indexElemSize,
  262. int firstVertex,
  263. int firstInstance)
  264. {
  265. int quadsCount = indexCount / 4;
  266. if (firstInstance != 0 || instanceCount != 1)
  267. {
  268. if (firstVertex != 0 && firstInstance != 0)
  269. {
  270. for (int quadIndex = 0; quadIndex < quadsCount; quadIndex++)
  271. {
  272. GL.DrawElementsInstancedBaseVertexBaseInstance(
  273. PrimitiveType.TriangleFan,
  274. 4,
  275. _elementsType,
  276. indexBaseOffset + quadIndex * 4 * indexElemSize,
  277. instanceCount,
  278. firstVertex,
  279. firstInstance);
  280. }
  281. }
  282. else if (firstInstance != 0)
  283. {
  284. for (int quadIndex = 0; quadIndex < quadsCount; quadIndex++)
  285. {
  286. GL.DrawElementsInstancedBaseInstance(
  287. PrimitiveType.TriangleFan,
  288. 4,
  289. _elementsType,
  290. indexBaseOffset + quadIndex * 4 * indexElemSize,
  291. instanceCount,
  292. firstInstance);
  293. }
  294. }
  295. else
  296. {
  297. for (int quadIndex = 0; quadIndex < quadsCount; quadIndex++)
  298. {
  299. GL.DrawElementsInstanced(
  300. PrimitiveType.TriangleFan,
  301. 4,
  302. _elementsType,
  303. indexBaseOffset + quadIndex * 4 * indexElemSize,
  304. instanceCount);
  305. }
  306. }
  307. }
  308. else
  309. {
  310. IntPtr[] indices = new IntPtr[quadsCount];
  311. int[] counts = new int[quadsCount];
  312. int[] baseVertices = new int[quadsCount];
  313. for (int quadIndex = 0; quadIndex < quadsCount; quadIndex++)
  314. {
  315. indices[quadIndex] = indexBaseOffset + quadIndex * 4 * indexElemSize;
  316. counts[quadIndex] = 4;
  317. baseVertices[quadIndex] = firstVertex;
  318. }
  319. GL.MultiDrawElementsBaseVertex(
  320. PrimitiveType.TriangleFan,
  321. counts,
  322. _elementsType,
  323. indices,
  324. quadsCount,
  325. baseVertices);
  326. }
  327. }
  328. private void DrawQuadStripIndexedImpl(
  329. int indexCount,
  330. int instanceCount,
  331. IntPtr indexBaseOffset,
  332. int indexElemSize,
  333. int firstVertex,
  334. int firstInstance)
  335. {
  336. // TODO: Instanced rendering.
  337. int quadsCount = (indexCount - 2) / 2;
  338. IntPtr[] indices = new IntPtr[quadsCount];
  339. int[] counts = new int[quadsCount];
  340. int[] baseVertices = new int[quadsCount];
  341. indices[0] = indexBaseOffset;
  342. counts[0] = 4;
  343. baseVertices[0] = firstVertex;
  344. for (int quadIndex = 1; quadIndex < quadsCount; quadIndex++)
  345. {
  346. indices[quadIndex] = indexBaseOffset + quadIndex * 2 * indexElemSize;
  347. counts[quadIndex] = 4;
  348. baseVertices[quadIndex] = firstVertex;
  349. }
  350. GL.MultiDrawElementsBaseVertex(
  351. PrimitiveType.TriangleFan,
  352. counts,
  353. _elementsType,
  354. indices,
  355. quadsCount,
  356. baseVertices);
  357. }
  358. private void DrawIndexedImpl(
  359. int indexCount,
  360. int instanceCount,
  361. IntPtr indexBaseOffset,
  362. int firstVertex,
  363. int firstInstance)
  364. {
  365. if (firstInstance == 0 && firstVertex == 0 && instanceCount == 1)
  366. {
  367. GL.DrawElements(_primitiveType, indexCount, _elementsType, indexBaseOffset);
  368. }
  369. else if (firstInstance == 0 && instanceCount == 1)
  370. {
  371. GL.DrawElementsBaseVertex(
  372. _primitiveType,
  373. indexCount,
  374. _elementsType,
  375. indexBaseOffset,
  376. firstVertex);
  377. }
  378. else if (firstInstance == 0 && firstVertex == 0)
  379. {
  380. GL.DrawElementsInstanced(
  381. _primitiveType,
  382. indexCount,
  383. _elementsType,
  384. indexBaseOffset,
  385. instanceCount);
  386. }
  387. else if (firstInstance == 0)
  388. {
  389. GL.DrawElementsInstancedBaseVertex(
  390. _primitiveType,
  391. indexCount,
  392. _elementsType,
  393. indexBaseOffset,
  394. instanceCount,
  395. firstVertex);
  396. }
  397. else if (firstVertex == 0)
  398. {
  399. GL.DrawElementsInstancedBaseInstance(
  400. _primitiveType,
  401. indexCount,
  402. _elementsType,
  403. indexBaseOffset,
  404. instanceCount,
  405. firstInstance);
  406. }
  407. else
  408. {
  409. GL.DrawElementsInstancedBaseVertexBaseInstance(
  410. _primitiveType,
  411. indexCount,
  412. _elementsType,
  413. indexBaseOffset,
  414. instanceCount,
  415. firstVertex,
  416. firstInstance);
  417. }
  418. }
  419. public void SetBlendState(int index, BlendDescriptor blend)
  420. {
  421. if (!blend.Enable)
  422. {
  423. GL.Disable(IndexedEnableCap.Blend, index);
  424. return;
  425. }
  426. GL.BlendEquationSeparate(
  427. index,
  428. blend.ColorOp.Convert(),
  429. blend.AlphaOp.Convert());
  430. GL.BlendFuncSeparate(
  431. index,
  432. (BlendingFactorSrc)blend.ColorSrcFactor.Convert(),
  433. (BlendingFactorDest)blend.ColorDstFactor.Convert(),
  434. (BlendingFactorSrc)blend.AlphaSrcFactor.Convert(),
  435. (BlendingFactorDest)blend.AlphaDstFactor.Convert());
  436. if (_blendConstant != blend.BlendConstant)
  437. {
  438. _blendConstant = blend.BlendConstant;
  439. GL.BlendColor(
  440. blend.BlendConstant.Red,
  441. blend.BlendConstant.Green,
  442. blend.BlendConstant.Blue,
  443. blend.BlendConstant.Alpha);
  444. }
  445. GL.Enable(IndexedEnableCap.Blend, index);
  446. }
  447. public void SetDepthBias(PolygonModeMask enables, float factor, float units, float clamp)
  448. {
  449. if ((enables & PolygonModeMask.Point) != 0)
  450. {
  451. GL.Enable(EnableCap.PolygonOffsetPoint);
  452. }
  453. else
  454. {
  455. GL.Disable(EnableCap.PolygonOffsetPoint);
  456. }
  457. if ((enables & PolygonModeMask.Line) != 0)
  458. {
  459. GL.Enable(EnableCap.PolygonOffsetLine);
  460. }
  461. else
  462. {
  463. GL.Disable(EnableCap.PolygonOffsetLine);
  464. }
  465. if ((enables & PolygonModeMask.Fill) != 0)
  466. {
  467. GL.Enable(EnableCap.PolygonOffsetFill);
  468. }
  469. else
  470. {
  471. GL.Disable(EnableCap.PolygonOffsetFill);
  472. }
  473. if (enables == 0)
  474. {
  475. return;
  476. }
  477. GL.PolygonOffset(factor, units / 2f);
  478. // TODO: Enable when GL_EXT_polygon_offset_clamp is supported.
  479. // GL.PolygonOffsetClamp(factor, units, clamp);
  480. }
  481. public void SetDepthClamp(bool clamp)
  482. {
  483. if (!clamp)
  484. {
  485. GL.Disable(EnableCap.DepthClamp);
  486. return;
  487. }
  488. GL.Enable(EnableCap.DepthClamp);
  489. }
  490. public void SetDepthMode(DepthMode mode)
  491. {
  492. ClipDepthMode depthMode = mode.Convert();
  493. if (_clipDepthMode != depthMode)
  494. {
  495. _clipDepthMode = depthMode;
  496. GL.ClipControl(_clipOrigin, depthMode);
  497. }
  498. }
  499. public void SetDepthTest(DepthTestDescriptor depthTest)
  500. {
  501. GL.DepthFunc((DepthFunction)depthTest.Func.Convert());
  502. _depthMask = depthTest.WriteEnable;
  503. _depthTest = depthTest.TestEnable;
  504. UpdateDepthTest();
  505. }
  506. public void SetFaceCulling(bool enable, Face face)
  507. {
  508. if (!enable)
  509. {
  510. GL.Disable(EnableCap.CullFace);
  511. return;
  512. }
  513. GL.CullFace(face.Convert());
  514. GL.Enable(EnableCap.CullFace);
  515. }
  516. public void SetFrontFace(FrontFace frontFace)
  517. {
  518. GL.FrontFace(frontFace.Convert());
  519. }
  520. public void SetImage(int index, ShaderStage stage, ITexture texture)
  521. {
  522. int unit = _program.GetImageUnit(stage, index);
  523. if (unit != -1 && texture != null)
  524. {
  525. TextureBase texBase = (TextureBase)texture;
  526. FormatInfo formatInfo = FormatTable.GetFormatInfo(texBase.Format);
  527. SizedInternalFormat format = (SizedInternalFormat)formatInfo.PixelInternalFormat;
  528. GL.BindImageTexture(unit, texBase.Handle, 0, true, 0, TextureAccess.ReadWrite, format);
  529. }
  530. }
  531. public void SetIndexBuffer(BufferRange buffer, IndexType type)
  532. {
  533. _elementsType = type.Convert();
  534. _indexBaseOffset = (IntPtr)buffer.Offset;
  535. EnsureVertexArray();
  536. _vertexArray.SetIndexBuffer(buffer.Handle);
  537. }
  538. public void SetPointSize(float size)
  539. {
  540. GL.PointSize(size);
  541. }
  542. public void SetPrimitiveRestart(bool enable, int index)
  543. {
  544. if (!enable)
  545. {
  546. GL.Disable(EnableCap.PrimitiveRestart);
  547. return;
  548. }
  549. GL.PrimitiveRestartIndex(index);
  550. GL.Enable(EnableCap.PrimitiveRestart);
  551. }
  552. public void SetPrimitiveTopology(PrimitiveTopology topology)
  553. {
  554. _primitiveType = topology.Convert();
  555. }
  556. public void SetProgram(IProgram program)
  557. {
  558. _program = (Program)program;
  559. _program.Bind();
  560. }
  561. public void SetRasterizerDiscard(bool discard)
  562. {
  563. if (discard)
  564. {
  565. GL.Enable(EnableCap.RasterizerDiscard);
  566. }
  567. else
  568. {
  569. GL.Disable(EnableCap.RasterizerDiscard);
  570. }
  571. _rasterizerDiscard = discard;
  572. }
  573. public void SetRenderTargetColorMasks(ReadOnlySpan<uint> componentMasks)
  574. {
  575. for (int index = 0; index < componentMasks.Length; index++)
  576. {
  577. _componentMasks[index] = componentMasks[index];
  578. RestoreComponentMask(index);
  579. }
  580. }
  581. public void SetRenderTargets(ITexture[] colors, ITexture depthStencil)
  582. {
  583. EnsureFramebuffer();
  584. for (int index = 0; index < colors.Length; index++)
  585. {
  586. TextureView color = (TextureView)colors[index];
  587. _framebuffer.AttachColor(index, color);
  588. }
  589. TextureView depthStencilView = (TextureView)depthStencil;
  590. _framebuffer.AttachDepthStencil(depthStencilView);
  591. _framebuffer.SetDrawBuffers(colors.Length);
  592. _hasDepthBuffer = depthStencil != null && depthStencilView.Format != Format.S8Uint;
  593. UpdateDepthTest();
  594. }
  595. public void SetSampler(int index, ShaderStage stage, ISampler sampler)
  596. {
  597. int unit = _program.GetTextureUnit(stage, index);
  598. if (unit != -1 && sampler != null)
  599. {
  600. ((Sampler)sampler).Bind(unit);
  601. }
  602. }
  603. public void SetScissorEnable(int index, bool enable)
  604. {
  605. if (enable)
  606. {
  607. GL.Enable(IndexedEnableCap.ScissorTest, index);
  608. }
  609. else
  610. {
  611. GL.Disable(IndexedEnableCap.ScissorTest, index);
  612. }
  613. if (index == 0)
  614. {
  615. _scissor0Enable = enable;
  616. }
  617. }
  618. public void SetScissor(int index, int x, int y, int width, int height)
  619. {
  620. GL.ScissorIndexed(index, x, y, width, height);
  621. }
  622. public void SetStencilTest(StencilTestDescriptor stencilTest)
  623. {
  624. if (!stencilTest.TestEnable)
  625. {
  626. GL.Disable(EnableCap.StencilTest);
  627. return;
  628. }
  629. GL.StencilOpSeparate(
  630. StencilFace.Front,
  631. stencilTest.FrontSFail.Convert(),
  632. stencilTest.FrontDpFail.Convert(),
  633. stencilTest.FrontDpPass.Convert());
  634. GL.StencilFuncSeparate(
  635. StencilFace.Front,
  636. (StencilFunction)stencilTest.FrontFunc.Convert(),
  637. stencilTest.FrontFuncRef,
  638. stencilTest.FrontFuncMask);
  639. GL.StencilMaskSeparate(StencilFace.Front, stencilTest.FrontMask);
  640. GL.StencilOpSeparate(
  641. StencilFace.Back,
  642. stencilTest.BackSFail.Convert(),
  643. stencilTest.BackDpFail.Convert(),
  644. stencilTest.BackDpPass.Convert());
  645. GL.StencilFuncSeparate(
  646. StencilFace.Back,
  647. (StencilFunction)stencilTest.BackFunc.Convert(),
  648. stencilTest.BackFuncRef,
  649. stencilTest.BackFuncMask);
  650. GL.StencilMaskSeparate(StencilFace.Back, stencilTest.BackMask);
  651. GL.Enable(EnableCap.StencilTest);
  652. _stencilFrontMask = stencilTest.FrontMask;
  653. }
  654. public void SetStorageBuffer(int index, ShaderStage stage, BufferRange buffer)
  655. {
  656. SetBuffer(index, stage, buffer, isStorage: true);
  657. }
  658. public void SetTexture(int index, ShaderStage stage, ITexture texture)
  659. {
  660. int unit = _program.GetTextureUnit(stage, index);
  661. if (unit != -1 && texture != null)
  662. {
  663. if (unit == 0)
  664. {
  665. _unit0Texture = (TextureBase)texture;
  666. }
  667. else
  668. {
  669. ((TextureBase)texture).Bind(unit);
  670. }
  671. }
  672. }
  673. public void SetUniformBuffer(int index, ShaderStage stage, BufferRange buffer)
  674. {
  675. SetBuffer(index, stage, buffer, isStorage: false);
  676. }
  677. public void SetUserClipDistance(int index, bool enableClip)
  678. {
  679. if (!enableClip)
  680. {
  681. GL.Disable(EnableCap.ClipDistance0 + index);
  682. return;
  683. }
  684. GL.Enable(EnableCap.ClipDistance0 + index);
  685. }
  686. public void SetVertexAttribs(ReadOnlySpan<VertexAttribDescriptor> vertexAttribs)
  687. {
  688. EnsureVertexArray();
  689. _vertexArray.SetVertexAttributes(vertexAttribs);
  690. }
  691. public void SetVertexBuffers(ReadOnlySpan<VertexBufferDescriptor> vertexBuffers)
  692. {
  693. EnsureVertexArray();
  694. _vertexArray.SetVertexBuffers(vertexBuffers);
  695. }
  696. public void SetViewports(int first, ReadOnlySpan<Viewport> viewports)
  697. {
  698. bool flipY = false;
  699. float[] viewportArray = new float[viewports.Length * 4];
  700. double[] depthRangeArray = new double[viewports.Length * 2];
  701. for (int index = 0; index < viewports.Length; index++)
  702. {
  703. int viewportElemIndex = index * 4;
  704. Viewport viewport = viewports[index];
  705. viewportArray[viewportElemIndex + 0] = viewport.Region.X;
  706. viewportArray[viewportElemIndex + 1] = viewport.Region.Y;
  707. // OpenGL does not support per-viewport flipping, so
  708. // instead we decide that based on the viewport 0 value.
  709. // It will apply to all viewports.
  710. if (index == 0)
  711. {
  712. flipY = viewport.Region.Height < 0;
  713. }
  714. if (viewport.SwizzleY == ViewportSwizzle.NegativeY)
  715. {
  716. flipY = !flipY;
  717. }
  718. viewportArray[viewportElemIndex + 2] = MathF.Abs(viewport.Region.Width);
  719. viewportArray[viewportElemIndex + 3] = MathF.Abs(viewport.Region.Height);
  720. depthRangeArray[index * 2 + 0] = viewport.DepthNear;
  721. depthRangeArray[index * 2 + 1] = viewport.DepthFar;
  722. }
  723. GL.ViewportArray(first, viewports.Length, viewportArray);
  724. GL.DepthRangeArray(first, viewports.Length, depthRangeArray);
  725. SetOrigin(flipY ? ClipOrigin.UpperLeft : ClipOrigin.LowerLeft);
  726. }
  727. public void TextureBarrier()
  728. {
  729. GL.MemoryBarrier(MemoryBarrierFlags.TextureFetchBarrierBit);
  730. }
  731. public void TextureBarrierTiled()
  732. {
  733. GL.MemoryBarrier(MemoryBarrierFlags.TextureFetchBarrierBit);
  734. }
  735. private void SetBuffer(int index, ShaderStage stage, BufferRange buffer, bool isStorage)
  736. {
  737. int bindingPoint = isStorage
  738. ? _program.GetStorageBufferBindingPoint(stage, index)
  739. : _program.GetUniformBufferBindingPoint(stage, index);
  740. if (bindingPoint == -1)
  741. {
  742. return;
  743. }
  744. BufferRangeTarget target = isStorage
  745. ? BufferRangeTarget.ShaderStorageBuffer
  746. : BufferRangeTarget.UniformBuffer;
  747. if (buffer.Handle == null)
  748. {
  749. GL.BindBufferRange(target, bindingPoint, 0, IntPtr.Zero, 0);
  750. return;
  751. }
  752. IntPtr bufferOffset = (IntPtr)buffer.Offset;
  753. GL.BindBufferRange(target, bindingPoint, buffer.Handle.ToInt32(), bufferOffset, buffer.Size);
  754. }
  755. private void SetOrigin(ClipOrigin origin)
  756. {
  757. if (_clipOrigin != origin)
  758. {
  759. _clipOrigin = origin;
  760. GL.ClipControl(origin, _clipDepthMode);
  761. }
  762. }
  763. private void EnsureVertexArray()
  764. {
  765. if (_vertexArray == null)
  766. {
  767. _vertexArray = new VertexArray();
  768. _vertexArray.Bind();
  769. }
  770. }
  771. private void EnsureFramebuffer()
  772. {
  773. if (_framebuffer == null)
  774. {
  775. _framebuffer = new Framebuffer();
  776. _framebuffer.Bind();
  777. GL.Enable(EnableCap.FramebufferSrgb);
  778. }
  779. }
  780. private void UpdateDepthTest()
  781. {
  782. // Enabling depth operations is only valid when we have
  783. // a depth buffer, otherwise it's not allowed.
  784. if (_hasDepthBuffer)
  785. {
  786. if (_depthTest)
  787. {
  788. GL.Enable(EnableCap.DepthTest);
  789. }
  790. else
  791. {
  792. GL.Disable(EnableCap.DepthTest);
  793. }
  794. GL.DepthMask(_depthMask);
  795. }
  796. else
  797. {
  798. GL.Disable(EnableCap.DepthTest);
  799. GL.DepthMask(false);
  800. }
  801. }
  802. private void PrepareForDispatch()
  803. {
  804. if (_unit0Texture != null)
  805. {
  806. _unit0Texture.Bind(0);
  807. }
  808. }
  809. private void PrepareForDraw()
  810. {
  811. _vertexArray.Validate();
  812. if (_unit0Texture != null)
  813. {
  814. _unit0Texture.Bind(0);
  815. }
  816. }
  817. private void RestoreComponentMask(int index)
  818. {
  819. GL.ColorMask(
  820. index,
  821. (_componentMasks[index] & 1u) != 0,
  822. (_componentMasks[index] & 2u) != 0,
  823. (_componentMasks[index] & 4u) != 0,
  824. (_componentMasks[index] & 8u) != 0);
  825. }
  826. public void RestoreScissor0Enable()
  827. {
  828. if (_scissor0Enable)
  829. {
  830. GL.Enable(IndexedEnableCap.ScissorTest, 0);
  831. }
  832. }
  833. public void RestoreRasterizerDiscard()
  834. {
  835. if (_rasterizerDiscard)
  836. {
  837. GL.Enable(EnableCap.RasterizerDiscard);
  838. }
  839. }
  840. public bool TryHostConditionalRendering(ICounterEvent value, ulong compare, bool isEqual)
  841. {
  842. if (value is CounterQueueEvent)
  843. {
  844. // Compare an event and a constant value.
  845. CounterQueueEvent evt = (CounterQueueEvent)value;
  846. // Easy host conditional rendering when the check matches what GL can do:
  847. // - Event is of type samples passed.
  848. // - Result is not a combination of multiple queries.
  849. // - Comparing against 0.
  850. // - Event has not already been flushed.
  851. if (evt.Disposed)
  852. {
  853. // If the event has been flushed, then just use the values on the CPU.
  854. // The query object may already be repurposed for another draw (eg. begin + end).
  855. return false;
  856. }
  857. if (compare == 0 && evt.Type == QueryTarget.SamplesPassed && evt.ClearCounter)
  858. {
  859. GL.BeginConditionalRender(evt.Query, isEqual ? ConditionalRenderType.QueryNoWaitInverted : ConditionalRenderType.QueryNoWait);
  860. return true;
  861. }
  862. }
  863. return false; // The GPU will flush the queries to CPU and evaluate the condition there instead.
  864. }
  865. public bool TryHostConditionalRendering(ICounterEvent value, ICounterEvent compare, bool isEqual)
  866. {
  867. return false; // We don't currently have a way to compare two counters for conditional rendering.
  868. }
  869. public void EndHostConditionalRendering()
  870. {
  871. GL.EndConditionalRender();
  872. }
  873. public void Dispose()
  874. {
  875. _framebuffer?.Dispose();
  876. _vertexArray?.Dispose();
  877. }
  878. }
  879. }