Pipeline.cs 40 KB

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