Pipeline.cs 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326
  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.Threading;
  9. namespace Ryujinx.Graphics.OpenGL
  10. {
  11. class Pipeline : IPipeline, IDisposable
  12. {
  13. private Program _program;
  14. private bool _rasterizerDiscard;
  15. private VertexArray _vertexArray;
  16. private Framebuffer _framebuffer;
  17. private IntPtr _indexBaseOffset;
  18. private DrawElementsType _elementsType;
  19. private PrimitiveType _primitiveType;
  20. private int _stencilFrontMask;
  21. private bool _depthMask;
  22. private bool _depthTest;
  23. private bool _hasDepthBuffer;
  24. private int _boundDrawFramebuffer;
  25. private int _boundReadFramebuffer;
  26. private int[] _fpIsBgra = new int[8];
  27. private float[] _fpRenderScale = new float[33];
  28. private float[] _cpRenderScale = new float[32];
  29. private TextureBase _unit0Texture;
  30. private TextureBase _rtColor0Texture;
  31. private TextureBase _rtDepthTexture;
  32. private FrontFaceDirection _frontFace;
  33. private ClipOrigin _clipOrigin;
  34. private ClipDepthMode _clipDepthMode;
  35. private readonly uint[] _componentMasks;
  36. private bool _scissor0Enable = false;
  37. private bool _tfEnabled;
  38. private ColorF _blendConstant;
  39. internal Pipeline()
  40. {
  41. _rasterizerDiscard = false;
  42. _clipOrigin = ClipOrigin.LowerLeft;
  43. _clipDepthMode = ClipDepthMode.NegativeOneToOne;
  44. _componentMasks = new uint[Constants.MaxRenderTargets];
  45. for (int index = 0; index < Constants.MaxRenderTargets; index++)
  46. {
  47. _componentMasks[index] = 0xf;
  48. }
  49. for (int index = 0; index < _fpRenderScale.Length; index++)
  50. {
  51. _fpRenderScale[index] = 1f;
  52. }
  53. for (int index = 0; index < _cpRenderScale.Length; index++)
  54. {
  55. _cpRenderScale[index] = 1f;
  56. }
  57. }
  58. public void Barrier()
  59. {
  60. GL.MemoryBarrier(MemoryBarrierFlags.AllBarrierBits);
  61. }
  62. public void BeginTransformFeedback(PrimitiveTopology topology)
  63. {
  64. GL.BeginTransformFeedback(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. PrepareForDraw();
  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. _framebuffer.SignalModified();
  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. PrepareForDraw();
  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. _framebuffer.SignalModified();
  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. GL.DepthFunc((DepthFunction)depthTest.Func.Convert());
  567. _depthMask = depthTest.WriteEnable;
  568. _depthTest = depthTest.TestEnable;
  569. UpdateDepthTest();
  570. }
  571. public void SetFaceCulling(bool enable, Face face)
  572. {
  573. if (!enable)
  574. {
  575. GL.Disable(EnableCap.CullFace);
  576. return;
  577. }
  578. GL.CullFace(face.Convert());
  579. GL.Enable(EnableCap.CullFace);
  580. }
  581. public void SetFrontFace(FrontFace frontFace)
  582. {
  583. SetFrontFace(_frontFace = frontFace.Convert());
  584. }
  585. public void SetImage(int index, ShaderStage stage, ITexture texture, Format imageFormat)
  586. {
  587. int unit = _program.GetImageUnit(stage, index);
  588. if (unit != -1 && texture != null)
  589. {
  590. TextureBase texBase = (TextureBase)texture;
  591. SizedInternalFormat format = FormatTable.GetImageFormat(imageFormat);
  592. if (format != 0)
  593. {
  594. GL.BindImageTexture(unit, texBase.Handle, 0, true, 0, TextureAccess.ReadWrite, format);
  595. }
  596. }
  597. }
  598. public void SetIndexBuffer(BufferRange buffer, IndexType type)
  599. {
  600. _elementsType = type.Convert();
  601. _indexBaseOffset = (IntPtr)buffer.Offset;
  602. EnsureVertexArray();
  603. _vertexArray.SetIndexBuffer(buffer.Handle);
  604. }
  605. public void SetLogicOpState(bool enable, LogicalOp op)
  606. {
  607. if (enable)
  608. {
  609. GL.Enable(EnableCap.ColorLogicOp);
  610. GL.LogicOp((LogicOp)op.Convert());
  611. }
  612. else
  613. {
  614. GL.Disable(EnableCap.ColorLogicOp);
  615. }
  616. }
  617. public void SetPointParameters(float size, bool isProgramPointSize, bool enablePointSprite, Origin origin)
  618. {
  619. // GL_POINT_SPRITE was deprecated in core profile 3.2+ and causes GL_INVALID_ENUM when set.
  620. // As we don't know if the current context is core or compat, it's safer to keep this code.
  621. if (enablePointSprite)
  622. {
  623. GL.Enable(EnableCap.PointSprite);
  624. }
  625. else
  626. {
  627. GL.Disable(EnableCap.PointSprite);
  628. }
  629. if (isProgramPointSize)
  630. {
  631. GL.Enable(EnableCap.ProgramPointSize);
  632. }
  633. else
  634. {
  635. GL.Disable(EnableCap.ProgramPointSize);
  636. }
  637. GL.PointParameter(origin == Origin.LowerLeft
  638. ? PointSpriteCoordOriginParameter.LowerLeft
  639. : PointSpriteCoordOriginParameter.UpperLeft);
  640. // Games seem to set point size to 0 which generates a GL_INVALID_VALUE
  641. // From the spec, GL_INVALID_VALUE is generated if size is less than or equal to 0.
  642. GL.PointSize(Math.Max(float.Epsilon, size));
  643. }
  644. public void SetPrimitiveRestart(bool enable, int index)
  645. {
  646. if (!enable)
  647. {
  648. GL.Disable(EnableCap.PrimitiveRestart);
  649. return;
  650. }
  651. GL.PrimitiveRestartIndex(index);
  652. GL.Enable(EnableCap.PrimitiveRestart);
  653. }
  654. public void SetPrimitiveTopology(PrimitiveTopology topology)
  655. {
  656. _primitiveType = topology.Convert();
  657. }
  658. public void SetProgram(IProgram program)
  659. {
  660. _program = (Program)program;
  661. if (_tfEnabled)
  662. {
  663. GL.PauseTransformFeedback();
  664. _program.Bind();
  665. GL.ResumeTransformFeedback();
  666. }
  667. else
  668. {
  669. _program.Bind();
  670. }
  671. UpdateFpIsBgra();
  672. SetRenderTargetScale(_fpRenderScale[0]);
  673. }
  674. public void SetRasterizerDiscard(bool discard)
  675. {
  676. if (discard)
  677. {
  678. GL.Enable(EnableCap.RasterizerDiscard);
  679. }
  680. else
  681. {
  682. GL.Disable(EnableCap.RasterizerDiscard);
  683. }
  684. _rasterizerDiscard = discard;
  685. }
  686. public void SetRenderTargetScale(float scale)
  687. {
  688. _fpRenderScale[0] = scale;
  689. if (_program != null && _program.FragmentRenderScaleUniform != -1)
  690. {
  691. GL.Uniform1(_program.FragmentRenderScaleUniform, 1, _fpRenderScale); // Just the first element.
  692. }
  693. }
  694. public void SetRenderTargetColorMasks(ReadOnlySpan<uint> componentMasks)
  695. {
  696. for (int index = 0; index < componentMasks.Length; index++)
  697. {
  698. _componentMasks[index] = componentMasks[index];
  699. RestoreComponentMask(index);
  700. }
  701. }
  702. public void SetRenderTargets(ITexture[] colors, ITexture depthStencil)
  703. {
  704. EnsureFramebuffer();
  705. _rtColor0Texture = (TextureBase)colors[0];
  706. _rtDepthTexture = (TextureBase)depthStencil;
  707. for (int index = 0; index < colors.Length; index++)
  708. {
  709. TextureView color = (TextureView)colors[index];
  710. _framebuffer.AttachColor(index, color);
  711. _fpIsBgra[index] = color != null && color.Format.IsBgra8() ? 1 : 0;
  712. }
  713. UpdateFpIsBgra();
  714. TextureView depthStencilView = (TextureView)depthStencil;
  715. _framebuffer.AttachDepthStencil(depthStencilView);
  716. _framebuffer.SetDrawBuffers(colors.Length);
  717. _hasDepthBuffer = depthStencil != null && depthStencilView.Format != Format.S8Uint;
  718. UpdateDepthTest();
  719. }
  720. public void SetSampler(int index, ShaderStage stage, ISampler sampler)
  721. {
  722. int unit = _program.GetTextureUnit(stage, index);
  723. if (unit != -1 && sampler != null)
  724. {
  725. ((Sampler)sampler).Bind(unit);
  726. }
  727. }
  728. public void SetScissorEnable(int index, bool enable)
  729. {
  730. if (enable)
  731. {
  732. GL.Enable(IndexedEnableCap.ScissorTest, index);
  733. }
  734. else
  735. {
  736. GL.Disable(IndexedEnableCap.ScissorTest, index);
  737. }
  738. if (index == 0)
  739. {
  740. _scissor0Enable = enable;
  741. }
  742. }
  743. public void SetScissor(int index, int x, int y, int width, int height)
  744. {
  745. GL.ScissorIndexed(index, x, y, width, height);
  746. }
  747. public void SetStencilTest(StencilTestDescriptor stencilTest)
  748. {
  749. if (!stencilTest.TestEnable)
  750. {
  751. GL.Disable(EnableCap.StencilTest);
  752. return;
  753. }
  754. GL.StencilOpSeparate(
  755. StencilFace.Front,
  756. stencilTest.FrontSFail.Convert(),
  757. stencilTest.FrontDpFail.Convert(),
  758. stencilTest.FrontDpPass.Convert());
  759. GL.StencilFuncSeparate(
  760. StencilFace.Front,
  761. (StencilFunction)stencilTest.FrontFunc.Convert(),
  762. stencilTest.FrontFuncRef,
  763. stencilTest.FrontFuncMask);
  764. GL.StencilMaskSeparate(StencilFace.Front, stencilTest.FrontMask);
  765. GL.StencilOpSeparate(
  766. StencilFace.Back,
  767. stencilTest.BackSFail.Convert(),
  768. stencilTest.BackDpFail.Convert(),
  769. stencilTest.BackDpPass.Convert());
  770. GL.StencilFuncSeparate(
  771. StencilFace.Back,
  772. (StencilFunction)stencilTest.BackFunc.Convert(),
  773. stencilTest.BackFuncRef,
  774. stencilTest.BackFuncMask);
  775. GL.StencilMaskSeparate(StencilFace.Back, stencilTest.BackMask);
  776. GL.Enable(EnableCap.StencilTest);
  777. _stencilFrontMask = stencilTest.FrontMask;
  778. }
  779. public void SetStorageBuffer(int index, ShaderStage stage, BufferRange buffer)
  780. {
  781. SetBuffer(index, stage, buffer, isStorage: true);
  782. }
  783. public void SetTexture(int index, ShaderStage stage, ITexture texture)
  784. {
  785. int unit = _program.GetTextureUnit(stage, index);
  786. if (unit != -1 && texture != null)
  787. {
  788. if (unit == 0)
  789. {
  790. _unit0Texture = (TextureBase)texture;
  791. }
  792. else
  793. {
  794. ((TextureBase)texture).Bind(unit);
  795. }
  796. // Update scale factor for bound textures.
  797. switch (stage)
  798. {
  799. case ShaderStage.Fragment:
  800. if (_program.FragmentRenderScaleUniform != -1)
  801. {
  802. // Only update and send sampled texture scales if the shader uses them.
  803. bool interpolate = false;
  804. float scale = texture.ScaleFactor;
  805. if (scale != 1)
  806. {
  807. TextureBase activeTarget = _rtColor0Texture ?? _rtDepthTexture;
  808. if (activeTarget != null && activeTarget.Width / (float)texture.Width == activeTarget.Height / (float)texture.Height)
  809. {
  810. // If the texture's size is a multiple of the sampler size,
  811. // enable interpolation using gl_FragCoord.
  812. // (helps "invent" new integer values between scaled pixels)
  813. interpolate = true;
  814. }
  815. }
  816. _fpRenderScale[index + 1] = interpolate ? -scale : scale;
  817. }
  818. break;
  819. case ShaderStage.Compute:
  820. _cpRenderScale[index] = texture.ScaleFactor;
  821. break;
  822. }
  823. }
  824. }
  825. public void SetTransformFeedbackBuffer(int index, BufferRange buffer)
  826. {
  827. const BufferRangeTarget target = BufferRangeTarget.TransformFeedbackBuffer;
  828. if (_tfEnabled)
  829. {
  830. GL.PauseTransformFeedback();
  831. GL.BindBufferRange(target, index, buffer.Handle.ToInt32(), (IntPtr)buffer.Offset, buffer.Size);
  832. GL.ResumeTransformFeedback();
  833. }
  834. else
  835. {
  836. GL.BindBufferRange(target, index, buffer.Handle.ToInt32(), (IntPtr)buffer.Offset, buffer.Size);
  837. }
  838. }
  839. public void SetUniformBuffer(int index, ShaderStage stage, BufferRange buffer)
  840. {
  841. SetBuffer(index, stage, buffer, isStorage: false);
  842. }
  843. public void SetUserClipDistance(int index, bool enableClip)
  844. {
  845. if (!enableClip)
  846. {
  847. GL.Disable(EnableCap.ClipDistance0 + index);
  848. return;
  849. }
  850. GL.Enable(EnableCap.ClipDistance0 + index);
  851. }
  852. public void SetVertexAttribs(ReadOnlySpan<VertexAttribDescriptor> vertexAttribs)
  853. {
  854. EnsureVertexArray();
  855. _vertexArray.SetVertexAttributes(vertexAttribs);
  856. }
  857. public void SetVertexBuffers(ReadOnlySpan<VertexBufferDescriptor> vertexBuffers)
  858. {
  859. EnsureVertexArray();
  860. _vertexArray.SetVertexBuffers(vertexBuffers);
  861. }
  862. public void SetViewports(int first, ReadOnlySpan<Viewport> viewports)
  863. {
  864. float[] viewportArray = new float[viewports.Length * 4];
  865. double[] depthRangeArray = new double[viewports.Length * 2];
  866. for (int index = 0; index < viewports.Length; index++)
  867. {
  868. int viewportElemIndex = index * 4;
  869. Viewport viewport = viewports[index];
  870. viewportArray[viewportElemIndex + 0] = viewport.Region.X;
  871. viewportArray[viewportElemIndex + 1] = viewport.Region.Y + (viewport.Region.Height < 0 ? viewport.Region.Height : 0);
  872. viewportArray[viewportElemIndex + 2] = viewport.Region.Width;
  873. viewportArray[viewportElemIndex + 3] = MathF.Abs(viewport.Region.Height);
  874. if (HwCapabilities.SupportsViewportSwizzle)
  875. {
  876. GL.NV.ViewportSwizzle(
  877. index,
  878. viewport.SwizzleX.Convert(),
  879. viewport.SwizzleY.Convert(),
  880. viewport.SwizzleZ.Convert(),
  881. viewport.SwizzleW.Convert());
  882. }
  883. depthRangeArray[index * 2 + 0] = viewport.DepthNear;
  884. depthRangeArray[index * 2 + 1] = viewport.DepthFar;
  885. }
  886. bool flipY = viewports.Length != 0 && viewports[0].Region.Height < 0;
  887. SetOrigin(flipY ? ClipOrigin.UpperLeft : ClipOrigin.LowerLeft);
  888. GL.ViewportArray(first, viewports.Length, viewportArray);
  889. GL.DepthRangeArray(first, viewports.Length, depthRangeArray);
  890. }
  891. public void TextureBarrier()
  892. {
  893. GL.MemoryBarrier(MemoryBarrierFlags.TextureFetchBarrierBit);
  894. }
  895. public void TextureBarrierTiled()
  896. {
  897. GL.MemoryBarrier(MemoryBarrierFlags.TextureFetchBarrierBit);
  898. }
  899. private void SetBuffer(int index, ShaderStage stage, BufferRange buffer, bool isStorage)
  900. {
  901. int bindingPoint = isStorage
  902. ? _program.GetStorageBufferBindingPoint(stage, index)
  903. : _program.GetUniformBufferBindingPoint(stage, index);
  904. if (bindingPoint == -1)
  905. {
  906. return;
  907. }
  908. BufferRangeTarget target = isStorage
  909. ? BufferRangeTarget.ShaderStorageBuffer
  910. : BufferRangeTarget.UniformBuffer;
  911. if (buffer.Handle == null)
  912. {
  913. GL.BindBufferRange(target, bindingPoint, 0, IntPtr.Zero, 0);
  914. return;
  915. }
  916. IntPtr bufferOffset = (IntPtr)buffer.Offset;
  917. GL.BindBufferRange(target, bindingPoint, buffer.Handle.ToInt32(), bufferOffset, buffer.Size);
  918. }
  919. private void SetOrigin(ClipOrigin origin)
  920. {
  921. if (_clipOrigin != origin)
  922. {
  923. _clipOrigin = origin;
  924. GL.ClipControl(origin, _clipDepthMode);
  925. SetFrontFace(_frontFace);
  926. }
  927. }
  928. private void SetFrontFace(FrontFaceDirection frontFace)
  929. {
  930. // Changing clip origin will also change the front face to compensate
  931. // for the flipped viewport, we flip it again here to compensate as
  932. // this effect is undesirable for us.
  933. if (_clipOrigin == ClipOrigin.UpperLeft)
  934. {
  935. frontFace = frontFace == FrontFaceDirection.Ccw ? FrontFaceDirection.Cw : FrontFaceDirection.Ccw;
  936. }
  937. GL.FrontFace(frontFace);
  938. }
  939. private void EnsureVertexArray()
  940. {
  941. if (_vertexArray == null)
  942. {
  943. _vertexArray = new VertexArray();
  944. _vertexArray.Bind();
  945. }
  946. }
  947. private void EnsureFramebuffer()
  948. {
  949. if (_framebuffer == null)
  950. {
  951. _framebuffer = new Framebuffer();
  952. int boundHandle = _framebuffer.Bind();
  953. _boundDrawFramebuffer = _boundReadFramebuffer = boundHandle;
  954. GL.Enable(EnableCap.FramebufferSrgb);
  955. }
  956. }
  957. internal (int drawHandle, int readHandle) GetBoundFramebuffers()
  958. {
  959. if (BackgroundContextWorker.InBackground)
  960. {
  961. return (0, 0);
  962. }
  963. return (_boundDrawFramebuffer, _boundReadFramebuffer);
  964. }
  965. private void UpdateFpIsBgra()
  966. {
  967. if (_program != null)
  968. {
  969. GL.Uniform1(_program.FragmentIsBgraUniform, 8, _fpIsBgra);
  970. }
  971. }
  972. private void UpdateDepthTest()
  973. {
  974. // Enabling depth operations is only valid when we have
  975. // a depth buffer, otherwise it's not allowed.
  976. if (_hasDepthBuffer)
  977. {
  978. if (_depthTest)
  979. {
  980. GL.Enable(EnableCap.DepthTest);
  981. }
  982. else
  983. {
  984. GL.Disable(EnableCap.DepthTest);
  985. }
  986. GL.DepthMask(_depthMask);
  987. }
  988. else
  989. {
  990. GL.Disable(EnableCap.DepthTest);
  991. GL.DepthMask(false);
  992. }
  993. }
  994. public void UpdateRenderScale(ShaderStage stage, int textureCount)
  995. {
  996. if (_program != null)
  997. {
  998. switch (stage)
  999. {
  1000. case ShaderStage.Fragment:
  1001. if (_program.FragmentRenderScaleUniform != -1)
  1002. {
  1003. GL.Uniform1(_program.FragmentRenderScaleUniform, textureCount + 1, _fpRenderScale);
  1004. }
  1005. break;
  1006. case ShaderStage.Compute:
  1007. if (_program.ComputeRenderScaleUniform != -1)
  1008. {
  1009. GL.Uniform1(_program.ComputeRenderScaleUniform, textureCount, _cpRenderScale);
  1010. }
  1011. break;
  1012. }
  1013. }
  1014. }
  1015. private void PrepareForDispatch()
  1016. {
  1017. if (_unit0Texture != null)
  1018. {
  1019. _unit0Texture.Bind(0);
  1020. }
  1021. }
  1022. private void PrepareForDraw()
  1023. {
  1024. _vertexArray.Validate();
  1025. if (_unit0Texture != null)
  1026. {
  1027. _unit0Texture.Bind(0);
  1028. }
  1029. }
  1030. private void RestoreComponentMask(int index)
  1031. {
  1032. GL.ColorMask(
  1033. index,
  1034. (_componentMasks[index] & 1u) != 0,
  1035. (_componentMasks[index] & 2u) != 0,
  1036. (_componentMasks[index] & 4u) != 0,
  1037. (_componentMasks[index] & 8u) != 0);
  1038. }
  1039. public void RestoreScissor0Enable()
  1040. {
  1041. if (_scissor0Enable)
  1042. {
  1043. GL.Enable(IndexedEnableCap.ScissorTest, 0);
  1044. }
  1045. }
  1046. public void RestoreRasterizerDiscard()
  1047. {
  1048. if (_rasterizerDiscard)
  1049. {
  1050. GL.Enable(EnableCap.RasterizerDiscard);
  1051. }
  1052. }
  1053. public bool TryHostConditionalRendering(ICounterEvent value, ulong compare, bool isEqual)
  1054. {
  1055. if (value is CounterQueueEvent)
  1056. {
  1057. // Compare an event and a constant value.
  1058. CounterQueueEvent evt = (CounterQueueEvent)value;
  1059. // Easy host conditional rendering when the check matches what GL can do:
  1060. // - Event is of type samples passed.
  1061. // - Result is not a combination of multiple queries.
  1062. // - Comparing against 0.
  1063. // - Event has not already been flushed.
  1064. if (evt.Disposed)
  1065. {
  1066. // If the event has been flushed, then just use the values on the CPU.
  1067. // The query object may already be repurposed for another draw (eg. begin + end).
  1068. return false;
  1069. }
  1070. if (compare == 0 && evt.Type == QueryTarget.SamplesPassed && evt.ClearCounter)
  1071. {
  1072. GL.BeginConditionalRender(evt.Query, isEqual ? ConditionalRenderType.QueryNoWaitInverted : ConditionalRenderType.QueryNoWait);
  1073. return true;
  1074. }
  1075. }
  1076. // The GPU will flush the queries to CPU and evaluate the condition there instead.
  1077. GL.Flush(); // The thread will be stalled manually flushing the counter, so flush GL commands now.
  1078. return false;
  1079. }
  1080. public bool TryHostConditionalRendering(ICounterEvent value, ICounterEvent compare, bool isEqual)
  1081. {
  1082. GL.Flush(); // The GPU thread will be stalled manually flushing the counter, so flush GL commands now.
  1083. return false; // We don't currently have a way to compare two counters for conditional rendering.
  1084. }
  1085. public void EndHostConditionalRendering()
  1086. {
  1087. GL.EndConditionalRender();
  1088. }
  1089. public void Dispose()
  1090. {
  1091. _framebuffer?.Dispose();
  1092. _vertexArray?.Dispose();
  1093. }
  1094. }
  1095. }