forked from nkast/MonoGame
/
ConcreteGraphicsContext.OpenGL.cs
989 lines (851 loc) · 40.9 KB
/
ConcreteGraphicsContext.OpenGL.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
// Copyright (C)2022 Nick Kastellanos
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using MonoGame.OpenGL;
namespace Microsoft.Xna.Platform.Graphics
{
internal abstract class ConcreteGraphicsContextGL : GraphicsContextStrategy
{
// Keeps track of last applied state to avoid redundant OpenGL calls
internal BlendState _lastBlendState = new BlendState();
internal bool _lastBlendEnable = false;
internal DepthStencilState _lastDepthStencilState = new DepthStencilState();
internal RasterizerState _lastRasterizerState = new RasterizerState();
internal ShaderProgram _shaderProgram = null;
private Vector4 _posFixup;
internal BufferBindingInfo[] _bufferBindingInfos;
private int _activeBufferBindingInfosCount;
internal bool[] _newEnabledVertexAttributes;
internal readonly HashSet<int> _enabledVertexAttributes = new HashSet<int>();
private bool _attribsDirty;
// Keeps track of last applied state to avoid redundant OpenGL calls
private Vector4 _lastClearColor = Vector4.Zero;
private float _lastClearDepth = 1.0f;
private int _lastClearStencil = 0;
private DepthStencilState _clearDepthStencilState = new DepthStencilState { StencilEnable = true };
// FBO cache, we create 1 FBO per RenderTargetBinding combination
internal Dictionary<RenderTargetBinding[], int> _glFramebuffers = new Dictionary<RenderTargetBinding[], int>(new ConcreteGraphicsContextGL.RenderTargetBindingArrayComparer());
// FBO cache used to resolve MSAA rendertargets, we create 1 FBO per RenderTargetBinding combination
internal Dictionary<RenderTargetBinding[], int> _glResolveFramebuffers = new Dictionary<RenderTargetBinding[], int>(new ConcreteGraphicsContextGL.RenderTargetBindingArrayComparer());
internal ShaderProgram ShaderProgram { get { return _shaderProgram; } }
public override Viewport Viewport
{
get { return base.Viewport; }
set
{
base.Viewport = value;
PlatformApplyViewport();
}
}
internal ConcreteGraphicsContextGL(GraphicsDevice device)
: base(device)
{
}
public override void Clear(ClearOptions options, Vector4 color, float depth, int stencil)
{
// TODO: We need to figure out how to detect if we have a
// depth stencil buffer or not, and clear options relating
// to them if not attached.
// Unlike with XNA and DirectX... GL.Clear() obeys several
// different render states:
//
// - The color write flags.
// - The scissor rectangle.
// - The depth/stencil state.
//
// So overwrite these states with what is needed to perform
// the clear correctly and restore it afterwards.
//
Rectangle prevScissorRect = ScissorRectangle;
DepthStencilState prevDepthStencilState = DepthStencilState;
BlendState prevBlendState = BlendState;
ScissorRectangle = _viewport.Bounds;
// DepthStencilState.Default has the Stencil Test disabled;
// make sure stencil test is enabled before we clear since
// some drivers won't clear with stencil test disabled
DepthStencilState = _clearDepthStencilState;
BlendState = BlendState.Opaque;
PlatformApplyState();
ClearBufferMask bufferMask = 0;
if ((options & ClearOptions.Target) == ClearOptions.Target)
{
if (color != _lastClearColor)
{
GL.ClearColor(color.X, color.Y, color.Z, color.W);
GraphicsExtensions.CheckGLError();
_lastClearColor = color;
}
bufferMask = bufferMask | ClearBufferMask.ColorBufferBit;
}
if ((options & ClearOptions.Stencil) == ClearOptions.Stencil)
{
if (stencil != _lastClearStencil)
{
GL.ClearStencil(stencil);
GraphicsExtensions.CheckGLError();
_lastClearStencil = stencil;
}
bufferMask = bufferMask | ClearBufferMask.StencilBufferBit;
}
if ((options & ClearOptions.DepthBuffer) == ClearOptions.DepthBuffer)
{
if (depth != _lastClearDepth)
{
GL.ClearDepth(depth);
GraphicsExtensions.CheckGLError();
_lastClearDepth = depth;
}
bufferMask = bufferMask | ClearBufferMask.DepthBufferBit;
}
#if IOS || TVOS
if (GL.CheckFramebufferStatus(FramebufferTarget.FramebufferExt) == FramebufferErrorCode.FramebufferComplete)
{
#endif
GL.Clear(bufferMask);
GraphicsExtensions.CheckGLError();
#if IOS || TVOS
}
#endif
// Restore the previous render state.
ScissorRectangle = prevScissorRect;
DepthStencilState = prevDepthStencilState;
BlendState = prevBlendState;
}
private void PlatformApplyState()
{
Threading.EnsureUIThread();
{
PlatformApplyBlend();
}
if (_depthStencilStateDirty)
{
_actualDepthStencilState.PlatformApplyState(this);
_depthStencilStateDirty = false;
}
if (_rasterizerStateDirty)
{
_actualRasterizerState.PlatformApplyState(this);
_rasterizerStateDirty = false;
}
if (_scissorRectangleDirty)
{
PlatformApplyScissorRectangle();
_scissorRectangleDirty = false;
}
}
private void PlatformApplyBlend()
{
if (_blendStateDirty)
{
_actualBlendState.PlatformApplyState(this);
_blendStateDirty = false;
}
if (_blendFactorDirty)
{
GL.BlendColor(
this.BlendFactor.R/255.0f,
this.BlendFactor.G/255.0f,
this.BlendFactor.B/255.0f,
this.BlendFactor.A/255.0f);
GraphicsExtensions.CheckGLError();
_blendFactorDirty = false;
}
}
private void PlatformApplyScissorRectangle()
{
Rectangle scissorRect = _scissorRectangle;
if (!IsRenderTargetBound)
scissorRect.Y = this.Device.PresentationParameters.BackBufferHeight - (scissorRect.Y + scissorRect.Height);
GL.Scissor(scissorRect.X, scissorRect.Y, scissorRect.Width, scissorRect.Height);
GraphicsExtensions.CheckGLError();
_scissorRectangleDirty = false;
}
internal void PlatformApplyViewport()
{
if (this.IsRenderTargetBound)
GL.Viewport(_viewport.X, _viewport.Y, _viewport.Width, _viewport.Height);
else
GL.Viewport(_viewport.X, this.Device.PresentationParameters.BackBufferHeight - _viewport.Y - _viewport.Height, _viewport.Width, _viewport.Height);
GraphicsExtensions.LogGLError("GraphicsDevice.Viewport_set() GL.Viewport");
GL.DepthRange(_viewport.MinDepth, _viewport.MaxDepth);
GraphicsExtensions.LogGLError("GraphicsDevice.Viewport_set() GL.DepthRange");
// In OpenGL we have to re-apply the special "_posFixup"
// vertex shader uniform if the viewport changes.
_vertexShaderDirty = true;
}
private void PlatformApplyIndexBuffer()
{
if (_indexBufferDirty)
{
GL.BindBuffer(BufferTarget.ElementArrayBuffer, Indices._ibo);
GraphicsExtensions.CheckGLError();
_indexBufferDirty = false;
}
}
private void PlatformApplyVertexBuffers()
{
}
private void PlatformApplyShaders()
{
if (_vertexShaderDirty || _pixelShaderDirty)
{
ActivateShaderProgram();
if (_vertexShaderDirty)
{
unchecked { this.Device.CurrentContext._graphicsMetrics._vertexShaderCount++; }
}
if (_pixelShaderDirty)
{
unchecked { this.Device.CurrentContext._graphicsMetrics._pixelShaderCount++; }
}
_vertexShaderDirty = false;
_pixelShaderDirty = false;
}
}
private void PlatformApplyShaderBuffers()
{
_vertexConstantBuffers.Apply(this);
_pixelConstantBuffers.Apply(this);
((ConcreteTextureCollection)this.VertexTextures.Strategy).PlatformApply();
((ConcreteSamplerStateCollection)this.VertexSamplerStates.Strategy).PlatformApply();
((ConcreteTextureCollection)this.Textures.Strategy).PlatformApply();
((ConcreteSamplerStateCollection)this.SamplerStates.Strategy).PlatformApply();
}
private int GetCurrentShaderProgramHash2()
{
return VertexShader.HashKey ^ PixelShader.HashKey;
}
/// <summary>
/// Activates the Current Vertex/Pixel shader pair into a program.
/// </summary>
private unsafe void ActivateShaderProgram()
{
// Lookup the shader program.
int programHash = GetCurrentShaderProgramHash2();
ShaderProgram shaderProgram = this.Device._programCache.GetProgram(VertexShader, PixelShader, programHash);
if (shaderProgram.Program == -1)
return;
// Set the new program if it has changed.
if (_shaderProgram != shaderProgram)
{
GL.UseProgram(shaderProgram.Program);
GraphicsExtensions.CheckGLError();
_shaderProgram = shaderProgram;
}
int posFixupLoc = shaderProgram.GetUniformLocation("posFixup");
if (posFixupLoc == -1)
return;
// Apply vertex shader fix:
// The following two lines are appended to the end of vertex shaders
// to account for rendering differences between OpenGL and DirectX:
//
// gl_Position.y = gl_Position.y * posFixup.y;
// gl_Position.xy += posFixup.zw * gl_Position.ww;
//
// (the following paraphrased from wine, wined3d/state.c and wined3d/glsl_shader.c)
//
// - We need to flip along the y-axis in case of offscreen rendering.
// - D3D coordinates refer to pixel centers while GL coordinates refer
// to pixel corners.
// - D3D has a top-left filling convention. We need to maintain this
// even after the y-flip mentioned above.
// In order to handle the last two points, we translate by
// (63.0 / 128.0) / VPw and (63.0 / 128.0) / VPh. This is equivalent to
// translating slightly less than half a pixel. We want the difference to
// be large enough that it doesn't get lost due to rounding inside the
// driver, but small enough to prevent it from interfering with any
// anti-aliasing.
//
// OpenGL coordinates specify the center of the pixel while d3d coords specify
// the corner. The offsets are stored in z and w in posFixup. posFixup.y contains
// 1.0 or -1.0 to turn the rendering upside down for offscreen rendering. PosFixup.x
// contains 1.0 to allow a mad.
_posFixup.X = 1.0f;
_posFixup.Y = 1.0f;
if (!this.Device.UseHalfPixelOffset)
{
_posFixup.Z = 0f;
_posFixup.W = 0f;
}
else
{
_posFixup.Z = (63.0f/64.0f)/Viewport.Width;
_posFixup.W = -(63.0f/64.0f)/Viewport.Height;
}
//If we have a render target bound (rendering offscreen)
if (this.IsRenderTargetBound)
{
//flip vertically
_posFixup.Y = -_posFixup.Y;
_posFixup.W = -_posFixup.W;
}
GL.Uniform4(posFixupLoc, _posFixup);
GraphicsExtensions.CheckGLError();
}
private void SetVertexAttributeArray(bool[] attrs)
{
for (int x = 0; x < attrs.Length; x++)
{
if (attrs[x])
{
if (_enabledVertexAttributes.Add(x))
{
GL.EnableVertexAttribArray(x);
GraphicsExtensions.CheckGLError();
}
}
else
{
if (_enabledVertexAttributes.Remove(x))
{
GL.DisableVertexAttribArray(x);
GraphicsExtensions.CheckGLError();
}
}
}
}
// Get a hashed value based on the currently bound shaders
// throws an exception if no shaders are bound
private int GetCurrentShaderProgramHash()
{
if (VertexShader == null && PixelShader == null)
throw new InvalidOperationException("There is no shader bound!");
if (VertexShader == null)
return PixelShader.HashKey;
if (PixelShader == null)
return VertexShader.HashKey;
return VertexShader.HashKey ^ PixelShader.HashKey;
}
private void PlatformApplyVertexBuffersAttribs(Shader shader, int baseVertex)
{
int programHash = GetCurrentShaderProgramHash();
bool bindingsChanged = false;
for (int slot = 0; slot < _vertexBuffers.Count; slot++)
{
var vertexBufferBinding = _vertexBuffers.Get(slot);
VertexDeclaration vertexDeclaration = vertexBufferBinding.VertexBuffer.VertexDeclaration;
var attrInfo = vertexDeclaration.GetAttributeInfo(shader, programHash);
int vertexStride = vertexDeclaration.VertexStride;
IntPtr offset = (IntPtr)(vertexDeclaration.VertexStride * (baseVertex + vertexBufferBinding.VertexOffset));
if (!_attribsDirty &&
slot < _activeBufferBindingInfosCount &&
_bufferBindingInfos[slot].VertexOffset == offset &&
ReferenceEquals(_bufferBindingInfos[slot].AttributeInfo, attrInfo) &&
_bufferBindingInfos[slot].InstanceFrequency == vertexBufferBinding.InstanceFrequency &&
_bufferBindingInfos[slot].Vbo == vertexBufferBinding.VertexBuffer._vbo)
continue;
bindingsChanged = true;
GL.BindBuffer(BufferTarget.ArrayBuffer, vertexBufferBinding.VertexBuffer._vbo);
GraphicsExtensions.CheckGLError();
for (int e = 0; e < attrInfo.Elements.Count; e++)
{
var element = attrInfo.Elements[e];
GL.VertexAttribPointer(element.AttributeLocation,
element.NumberOfElements,
element.VertexAttribPointerType,
element.Normalized,
vertexStride,
(IntPtr)(offset.ToInt64() + element.Offset));
GraphicsExtensions.CheckGLError();
// only set the divisor if instancing is supported
if (this.Device.Capabilities.SupportsInstancing)
{
GL.VertexAttribDivisor(element.AttributeLocation, vertexBufferBinding.InstanceFrequency);
GraphicsExtensions.CheckGLError();
}
else // If instancing is not supported, but InstanceFrequency of the buffer is not zero, throw an exception
{
if (vertexBufferBinding.InstanceFrequency > 0)
throw new PlatformNotSupportedException("Instanced geometry drawing requires at least OpenGL 3.2 or GLES 3.2. Try upgrading your graphics drivers.");
}
}
_bufferBindingInfos[slot].VertexOffset = offset;
_bufferBindingInfos[slot].AttributeInfo = attrInfo;
_bufferBindingInfos[slot].InstanceFrequency = vertexBufferBinding.InstanceFrequency;
_bufferBindingInfos[slot].Vbo = vertexBufferBinding.VertexBuffer._vbo;
}
_attribsDirty = false;
if (bindingsChanged)
{
for (int eva = 0; eva < _newEnabledVertexAttributes.Length; eva++)
_newEnabledVertexAttributes[eva] = false;
for (int slot = 0; slot < _vertexBuffers.Count; slot++)
{
for (int e = 0; e < _bufferBindingInfos[slot].AttributeInfo.Elements.Count; e++)
{
var element = _bufferBindingInfos[slot].AttributeInfo.Elements[e];
_newEnabledVertexAttributes[element.AttributeLocation] = true;
}
}
_activeBufferBindingInfosCount = _vertexBuffers.Count;
}
SetVertexAttributeArray(_newEnabledVertexAttributes);
}
internal void PlatformApplyUserVertexDataAttribs(VertexDeclaration vertexDeclaration, Shader shader, IntPtr baseVertex)
{
int programHash = GetCurrentShaderProgramHash();
var attrInfo = vertexDeclaration.GetAttributeInfo(shader, programHash);
// Apply the vertex attribute info
for (int i = 0; i < attrInfo.Elements.Count; i++)
{
var element = attrInfo.Elements[i];
GL.VertexAttribPointer(element.AttributeLocation,
element.NumberOfElements,
element.VertexAttribPointerType,
element.Normalized,
vertexDeclaration.VertexStride,
(IntPtr)(baseVertex.ToInt64() + element.Offset));
GraphicsExtensions.CheckGLError();
#if DESKTOPGL
if (this.Device.Capabilities.SupportsInstancing)
{
GL.VertexAttribDivisor(element.AttributeLocation, 0);
GraphicsExtensions.CheckGLError();
}
#endif
}
SetVertexAttributeArray(attrInfo.EnabledAttributes);
_attribsDirty = true;
}
private static GLPrimitiveType PrimitiveTypeGL(PrimitiveType primitiveType)
{
switch (primitiveType)
{
case PrimitiveType.PointList:
return GLPrimitiveType.Points;
case PrimitiveType.LineList:
return GLPrimitiveType.Lines;
case PrimitiveType.LineStrip:
return GLPrimitiveType.LineStrip;
case PrimitiveType.TriangleList:
return GLPrimitiveType.Triangles;
case PrimitiveType.TriangleStrip:
return GLPrimitiveType.TriangleStrip;
default:
throw new ArgumentException();
}
}
public override void DrawPrimitives(PrimitiveType primitiveType, int vertexStart, int vertexCount)
{
PlatformApplyState();
//PlatformApplyIndexBuffer();
PlatformApplyVertexBuffers();
PlatformApplyShaders();
PlatformApplyShaderBuffers();
PlatformApplyVertexBuffersAttribs(VertexShader, 0);
if (vertexStart < 0)
vertexStart = 0;
GL.DrawArrays(ConcreteGraphicsContext.PrimitiveTypeGL(primitiveType),
vertexStart,
vertexCount);
GraphicsExtensions.CheckGLError();
}
public override void DrawIndexedPrimitives(PrimitiveType primitiveType, int baseVertex, int startIndex, int primitiveCount)
{
PlatformApplyState();
PlatformApplyIndexBuffer();
PlatformApplyVertexBuffers();
PlatformApplyShaders();
PlatformApplyShaderBuffers();
bool shortIndices = Indices.IndexElementSize == IndexElementSize.SixteenBits;
var indexElementType = shortIndices ? DrawElementsType.UnsignedShort : DrawElementsType.UnsignedInt;
int indexElementSize = shortIndices ? 2 : 4;
IntPtr indexOffsetInBytes = (IntPtr)(startIndex * indexElementSize);
int indexElementCount = GraphicsContextStrategy.GetElementCountArray(primitiveType, primitiveCount);
var target = ConcreteGraphicsContext.PrimitiveTypeGL(primitiveType);
PlatformApplyVertexBuffersAttribs(VertexShader, baseVertex);
GL.DrawElements(target,
indexElementCount,
indexElementType,
indexOffsetInBytes);
GraphicsExtensions.CheckGLError();
}
public override void DrawInstancedPrimitives(PrimitiveType primitiveType, int baseVertex, int startIndex, int primitiveCount, int baseInstance, int instanceCount)
{
if (!this.Device.Capabilities.SupportsInstancing)
throw new PlatformNotSupportedException("Instanced geometry drawing requires at least OpenGL 3.2 or GLES 3.2. Try upgrading your graphics card drivers.");
PlatformApplyState();
PlatformApplyIndexBuffer();
PlatformApplyVertexBuffers();
PlatformApplyShaders();
PlatformApplyShaderBuffers();
bool shortIndices = Indices.IndexElementSize == IndexElementSize.SixteenBits;
var indexElementType = shortIndices ? DrawElementsType.UnsignedShort : DrawElementsType.UnsignedInt;
int indexElementSize = shortIndices ? 2 : 4;
IntPtr indexOffsetInBytes = (IntPtr)(startIndex * indexElementSize);
int indexElementCount = GraphicsContextStrategy.GetElementCountArray(primitiveType, primitiveCount);
var target = ConcreteGraphicsContext.PrimitiveTypeGL(primitiveType);
PlatformApplyVertexBuffersAttribs(VertexShader, baseVertex);
if (baseInstance > 0)
{
if (!this.Device.Capabilities.SupportsBaseIndexInstancing)
throw new PlatformNotSupportedException("Instanced geometry drawing with base instance requires at least OpenGL 4.2. Try upgrading your graphics card drivers.");
GL.DrawElementsInstancedBaseInstance(target,
indexElementCount,
indexElementType,
indexOffsetInBytes,
instanceCount,
baseInstance);
}
else
GL.DrawElementsInstanced(target,
indexElementCount,
indexElementType,
indexOffsetInBytes,
instanceCount);
GraphicsExtensions.CheckGLError();
}
public override void DrawUserPrimitives<T>(PrimitiveType primitiveType, T[] vertexData, int vertexOffset, VertexDeclaration vertexDeclaration, int vertexCount)
//where T : struct
{
PlatformApplyState();
//PlatformApplyIndexBuffer();
//PlatformApplyVertexBuffers();
PlatformApplyShaders();
PlatformApplyShaderBuffers();
// Unbind current VBOs.
GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
GraphicsExtensions.CheckGLError();
_vertexBuffersDirty = true;
GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0);
GraphicsExtensions.CheckGLError();
_vertexBuffersDirty = true;
// Pin the buffers.
GCHandle vbHandle = GCHandle.Alloc(vertexData, GCHandleType.Pinned);
try
{
// Setup the vertex declaration to point at the VB data.
vertexDeclaration.GraphicsDevice = this.Device;
PlatformApplyUserVertexDataAttribs(vertexDeclaration, VertexShader, vbHandle.AddrOfPinnedObject());
//Draw
GL.DrawArrays(ConcreteGraphicsContext.PrimitiveTypeGL(primitiveType),
vertexOffset,
vertexCount);
GraphicsExtensions.CheckGLError();
}
finally
{
// Release the handles.
vbHandle.Free();
}
}
public override void DrawUserIndexedPrimitives<T>(PrimitiveType primitiveType, T[] vertexData, int vertexOffset, int numVertices, short[] indexData, int indexOffset, int primitiveCount, VertexDeclaration vertexDeclaration)
//where T : struct
{
PlatformApplyState();
//PlatformApplyIndexBuffer();
//PlatformApplyVertexBuffers();
PlatformApplyShaders();
PlatformApplyShaderBuffers();
// Unbind current VBOs.
GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
GraphicsExtensions.CheckGLError();
_vertexBuffersDirty = true;
GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0);
GraphicsExtensions.CheckGLError();
_indexBufferDirty = true;
// Pin the buffers.
GCHandle vbHandle = GCHandle.Alloc(vertexData, GCHandleType.Pinned);
GCHandle ibHandle = GCHandle.Alloc(indexData, GCHandleType.Pinned);
try
{
IntPtr vertexAddr = (IntPtr)(vbHandle.AddrOfPinnedObject().ToInt64() + vertexDeclaration.VertexStride * vertexOffset);
// Setup the vertex declaration to point at the VB data.
vertexDeclaration.GraphicsDevice = this.Device;
PlatformApplyUserVertexDataAttribs(vertexDeclaration, VertexShader, vertexAddr);
//Draw
GL.DrawElements(
ConcreteGraphicsContext.PrimitiveTypeGL(primitiveType),
GraphicsContextStrategy.GetElementCountArray(primitiveType, primitiveCount),
DrawElementsType.UnsignedShort,
(IntPtr)(ibHandle.AddrOfPinnedObject().ToInt64() + (indexOffset * sizeof(short))));
GraphicsExtensions.CheckGLError();
}
finally
{
// Release the handles.
ibHandle.Free();
vbHandle.Free();
}
}
public override void DrawUserIndexedPrimitives<T>(PrimitiveType primitiveType, T[] vertexData, int vertexOffset, int numVertices, int[] indexData, int indexOffset, int primitiveCount, VertexDeclaration vertexDeclaration)
//where T : struct
{
PlatformApplyState();
//PlatformApplyIndexBuffer();
//PlatformApplyVertexBuffers();
PlatformApplyShaders();
PlatformApplyShaderBuffers();
// Unbind current VBOs.
GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
GraphicsExtensions.CheckGLError();
_vertexBuffersDirty = true;
GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0);
GraphicsExtensions.CheckGLError();
_indexBufferDirty = true;
// Pin the buffers.
GCHandle vbHandle = GCHandle.Alloc(vertexData, GCHandleType.Pinned);
GCHandle ibHandle = GCHandle.Alloc(indexData, GCHandleType.Pinned);
try
{
IntPtr vertexAddr = (IntPtr)(vbHandle.AddrOfPinnedObject().ToInt64() + vertexDeclaration.VertexStride * vertexOffset);
// Setup the vertex declaration to point at the VB data.
vertexDeclaration.GraphicsDevice = this.Device;
PlatformApplyUserVertexDataAttribs(vertexDeclaration, VertexShader, vertexAddr);
//Draw
GL.DrawElements(
ConcreteGraphicsContext.PrimitiveTypeGL(primitiveType),
GraphicsContextStrategy.GetElementCountArray(primitiveType, primitiveCount),
DrawElementsType.UnsignedInt,
(IntPtr)(ibHandle.AddrOfPinnedObject().ToInt64() + (indexOffset * sizeof(int))));
GraphicsExtensions.CheckGLError();
}
finally
{
// Release the handles.
ibHandle.Free();
vbHandle.Free();
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
ThrowIfDisposed();
}
base.Dispose(disposing);
}
static readonly FramebufferAttachment[] InvalidateFramebufferAttachements =
{
FramebufferAttachment.ColorAttachment0,
FramebufferAttachment.DepthAttachment,
FramebufferAttachment.StencilAttachment,
};
internal void PlatformResolveRenderTargets()
{
if (!this.IsRenderTargetBound)
return;
var renderTargetBinding = _currentRenderTargetBindings[0];
var renderTarget = renderTargetBinding.RenderTarget as IRenderTarget;
if (renderTarget.MultiSampleCount > 0 && this.Device._supportsBlitFramebuffer)
{
int glResolveFramebuffer = 0;
if (!_glResolveFramebuffers.TryGetValue(_currentRenderTargetBindings, out glResolveFramebuffer))
{
glResolveFramebuffer = GL.GenFramebuffer();
GraphicsExtensions.CheckGLError();
GL.BindFramebuffer(FramebufferTarget.Framebuffer, glResolveFramebuffer);
GraphicsExtensions.CheckGLError();
for (int i = 0; i < _currentRenderTargetCount; i++)
{
var renderTargetGL = (IRenderTargetGL)_currentRenderTargetBindings[i].RenderTarget;
FramebufferAttachment attachement = (FramebufferAttachment.ColorAttachment0 + i);
TextureTarget target = renderTargetGL.GetFramebufferTarget(renderTargetBinding.ArraySlice);
GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, attachement, target, renderTargetGL.GLTexture, 0);
GraphicsExtensions.CheckGLError();
}
_glResolveFramebuffers.Add((RenderTargetBinding[])_currentRenderTargetBindings.Clone(), glResolveFramebuffer);
}
else
{
GL.BindFramebuffer(FramebufferTarget.Framebuffer, glResolveFramebuffer);
GraphicsExtensions.CheckGLError();
}
// The only fragment operations which affect the resolve are the pixel ownership test, the scissor test, and dithering.
if (_lastRasterizerState.ScissorTestEnable)
{
GL.Disable(EnableCap.ScissorTest);
GraphicsExtensions.CheckGLError();
}
int glFramebuffer = _glFramebuffers[_currentRenderTargetBindings];
GL.BindFramebuffer(FramebufferTarget.ReadFramebuffer, glFramebuffer);
GraphicsExtensions.CheckGLError();
for (int i = 0; i < _currentRenderTargetCount; i++)
{
renderTargetBinding = _currentRenderTargetBindings[i];
renderTarget = renderTargetBinding.RenderTarget as IRenderTarget;
GL.ReadBuffer(ReadBufferMode.ColorAttachment0 + i);
GraphicsExtensions.CheckGLError();
GL.DrawBuffer(DrawBufferMode.ColorAttachment0 + i);
GraphicsExtensions.CheckGLError();
GL.BlitFramebuffer(0, 0, renderTarget.Width, renderTarget.Height,
0, 0, renderTarget.Width, renderTarget.Height,
ClearBufferMask.ColorBufferBit, BlitFramebufferFilter.Nearest);
GraphicsExtensions.CheckGLError();
}
if (renderTarget.RenderTargetUsage == RenderTargetUsage.DiscardContents && this.Device._supportsInvalidateFramebuffer)
{
Debug.Assert(this.Device._supportsInvalidateFramebuffer);
GL.InvalidateFramebuffer(FramebufferTarget.Framebuffer, 3, InvalidateFramebufferAttachements);
GraphicsExtensions.CheckGLError();
}
if (_lastRasterizerState.ScissorTestEnable)
{
GL.Enable(EnableCap.ScissorTest);
GraphicsExtensions.CheckGLError();
}
}
for (int i = 0; i < _currentRenderTargetCount; i++)
{
renderTargetBinding = _currentRenderTargetBindings[i];
if (renderTargetBinding.RenderTarget.LevelCount > 1)
{
var renderTargetGL = (IRenderTargetGL)renderTargetBinding.RenderTarget;
GL.BindTexture(renderTargetGL.GLTarget, renderTargetGL.GLTexture);
GraphicsExtensions.CheckGLError();
GL.GenerateMipmap(renderTargetGL.GLTarget);
GraphicsExtensions.CheckGLError();
}
}
}
internal void PlatformApplyDefaultRenderTarget()
{
GL.BindFramebuffer(FramebufferTarget.Framebuffer, this.Device._glDefaultFramebuffer);
GraphicsExtensions.CheckGLError();
// Reset the raster state because we flip vertices
// when rendering offscreen and hence the cull direction.
_rasterizerStateDirty = true;
// Textures will need to be rebound to render correctly in the new render target.
_pixelTextures.Strategy.Dirty();
}
internal IRenderTarget PlatformApplyRenderTargets()
{
int glFramebuffer = 0;
if (!_glFramebuffers.TryGetValue(_currentRenderTargetBindings, out glFramebuffer))
{
glFramebuffer = GL.GenFramebuffer();
GraphicsExtensions.CheckGLError();
GL.BindFramebuffer(FramebufferTarget.Framebuffer, glFramebuffer);
GraphicsExtensions.CheckGLError();
var renderTargetBinding = _currentRenderTargetBindings[0];
var renderTargetGL = (IRenderTargetGL)renderTargetBinding.RenderTarget;
GL.FramebufferRenderbuffer(FramebufferTarget.Framebuffer, FramebufferAttachment.DepthAttachment, RenderbufferTarget.Renderbuffer, renderTargetGL.GLDepthBuffer);
GraphicsExtensions.CheckGLError();
GL.FramebufferRenderbuffer(FramebufferTarget.Framebuffer, FramebufferAttachment.StencilAttachment, RenderbufferTarget.Renderbuffer, renderTargetGL.GLStencilBuffer);
GraphicsExtensions.CheckGLError();
for (int i = 0; i < _currentRenderTargetCount; i++)
{
renderTargetBinding = _currentRenderTargetBindings[i];
var renderTarget = (IRenderTarget)renderTargetBinding.RenderTarget;
renderTargetGL = renderTargetBinding.RenderTarget as IRenderTargetGL;
var attachement = (FramebufferAttachment.ColorAttachment0 + i);
if (renderTargetGL.GLColorBuffer != renderTargetGL.GLTexture)
{
GL.FramebufferRenderbuffer(FramebufferTarget.Framebuffer, attachement, RenderbufferTarget.Renderbuffer, renderTargetGL.GLColorBuffer);
GraphicsExtensions.CheckGLError();
}
else
{
TextureTarget target = renderTargetGL.GetFramebufferTarget(renderTargetBinding.ArraySlice);
GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, attachement, target, renderTargetGL.GLTexture, 0);
GraphicsExtensions.CheckGLError();
}
}
GraphicsExtensions.CheckFramebufferStatus();
_glFramebuffers.Add((RenderTargetBinding[])_currentRenderTargetBindings.Clone(), glFramebuffer);
}
else
{
GL.BindFramebuffer(FramebufferTarget.Framebuffer, glFramebuffer);
GraphicsExtensions.CheckGLError();
}
#if DESKTOPGL
GL.DrawBuffers(_currentRenderTargetCount, ((ConcreteGraphicsContext)this)._drawBuffers);
#endif
// Reset the raster state because we flip vertices
// when rendering offscreen and hence the cull direction.
_rasterizerStateDirty = true;
// Textures will need to be rebound to render correctly in the new render target.
_pixelTextures.Strategy.Dirty();
return _currentRenderTargetBindings[0].RenderTarget as IRenderTarget;
}
internal void PlatformUnbindRenderTarget(IRenderTarget renderTarget)
{
var bindingsToDelete = new List<RenderTargetBinding[]>();
foreach (RenderTargetBinding[] bindings in _glFramebuffers.Keys)
{
foreach (RenderTargetBinding binding in bindings)
{
if (binding.RenderTarget == renderTarget)
{
bindingsToDelete.Add(bindings);
break;
}
}
}
foreach (RenderTargetBinding[] bindings in bindingsToDelete)
{
int fbo = 0;
if (_glFramebuffers.TryGetValue(bindings, out fbo))
{
GL.DeleteFramebuffer(fbo);
GraphicsExtensions.CheckGLError();
_glFramebuffers.Remove(bindings);
}
if (_glResolveFramebuffers.TryGetValue(bindings, out fbo))
{
GL.DeleteFramebuffer(fbo);
GraphicsExtensions.CheckGLError();
_glResolveFramebuffers.Remove(bindings);
}
}
}
// Holds information for caching
internal class BufferBindingInfo
{
public VertexDeclaration.VertexDeclarationAttributeInfo AttributeInfo;
public IntPtr VertexOffset;
public int InstanceFrequency;
public int Vbo;
public BufferBindingInfo(VertexDeclaration.VertexDeclarationAttributeInfo attributeInfo, IntPtr vertexOffset, int instanceFrequency, int vbo)
{
AttributeInfo = attributeInfo;
VertexOffset = vertexOffset;
InstanceFrequency = instanceFrequency;
Vbo = vbo;
}
}
private class RenderTargetBindingArrayComparer : IEqualityComparer<RenderTargetBinding[]>
{
public bool Equals(RenderTargetBinding[] first, RenderTargetBinding[] second)
{
if (object.ReferenceEquals(first, second))
return true;
if (first == null || second == null)
return false;
if (first.Length != second.Length)
return false;
for (int i = 0; i < first.Length; i++)
{
if ((first[i].RenderTarget != second[i].RenderTarget) || (first[i].ArraySlice != second[i].ArraySlice))
{
return false;
}
}
return true;
}
public int GetHashCode(RenderTargetBinding[] array)
{
if (array != null)
{
unchecked
{
int hash = 17;
foreach (var item in array)
{
if (item.RenderTarget != null)
hash = hash * 23 + item.RenderTarget.GetHashCode();
hash = hash * 23 + item.ArraySlice.GetHashCode();
}
return hash;
}
}
return 0;
}
}
}
}