Pipeline.cs 41 KB

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