/
GraphicsDevice.cs
2405 lines (2003 loc) · 92.1 KB
/
GraphicsDevice.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
990
991
992
993
994
995
996
997
998
999
1000
#region License
/*
Microsoft Public License (Ms-PL)
MonoGame - Copyright © 2009 The MonoGame Team
All rights reserved.
This license governs use of the accompanying software. If you use the software, you accept this license. If you do not
accept the license, do not use the software.
1. Definitions
The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under
U.S. copyright law.
A "contribution" is the original software, or any additions or changes to the software.
A "contributor" is any person that distributes its contribution under this license.
"Licensed patents" are a contributor's patent claims that read directly on its contribution.
2. Grant of Rights
(A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3,
each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.
(B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3,
each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.
3. Conditions and Limitations
(A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks.
(B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software,
your patent license from such contributor to the software ends automatically.
(C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution
notices that are present in the software.
(D) If you distribute any portion of the software in source code form, you may do so only under this license by including
a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object
code form, you may only do so under a license that complies with this license.
(E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees
or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent
permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular
purpose and non-infringement.
*/
#endregion License
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Input.Touch;
using System.Diagnostics;
#if OPENGL
#if MONOMAC
using MonoMac.OpenGL;
#elif WINDOWS || LINUX
using OpenTK.Graphics.OpenGL;
#elif GLES
using OpenTK.Graphics.ES20;
using BeginMode = OpenTK.Graphics.ES20.All;
using EnableCap = OpenTK.Graphics.ES20.All;
using TextureTarget = OpenTK.Graphics.ES20.All;
using BufferTarget = OpenTK.Graphics.ES20.All;
using BufferUsageHint = OpenTK.Graphics.ES20.All;
using DrawElementsType = OpenTK.Graphics.ES20.All;
using GetPName = OpenTK.Graphics.ES20.All;
using FramebufferErrorCode = OpenTK.Graphics.ES20.All;
using FramebufferTarget = OpenTK.Graphics.ES20.All;
using FramebufferAttachment = OpenTK.Graphics.ES20.All;
using RenderbufferTarget = OpenTK.Graphics.ES20.All;
using RenderbufferStorage = OpenTK.Graphics.ES20.All;
#endif
#elif DIRECTX
using SharpDX;
using SharpDX.Direct3D;
#if WINDOWS_PHONE
using SharpDX.Direct3D11;
using Windows.Foundation;
using MonoGame.Framework.WindowsPhone;
#elif WINDOWS_STOREAPP
using Windows.UI.Xaml.Controls;
using Windows.Graphics.Display;
using Windows.UI.Core;
using SharpDX.DXGI;
#elif WINDOWS
using SharpDX.DXGI;
#endif
#elif PSM
using Sce.PlayStation.Core.Graphics;
using PssVertexBuffer = Sce.PlayStation.Core.Graphics.VertexBuffer;
#endif
namespace Microsoft.Xna.Framework.Graphics
{
public class GraphicsDevice : IDisposable
{
private Viewport _viewport;
private bool _isDisposed;
private BlendState _blendState = BlendState.Opaque;
private DepthStencilState _depthStencilState = DepthStencilState.Default;
private RasterizerState _rasterizerState = RasterizerState.CullCounterClockwise;
private bool _blendStateDirty;
private bool _depthStencilStateDirty;
private bool _rasterizerStateDirty;
private Rectangle _scissorRectangle;
private bool _scissorRectangleDirty;
private VertexBuffer _vertexBuffer;
private bool _vertexBufferDirty;
private IndexBuffer _indexBuffer;
private bool _indexBufferDirty;
private RenderTargetBinding[] _currentRenderTargetBindings;
private static readonly RenderTargetBinding[] EmptyRenderTargetBinding = new RenderTargetBinding[0];
public TextureCollection Textures { get; private set; }
public SamplerStateCollection SamplerStates { get; private set; }
private static readonly Color DiscardColor = new Color(68, 34, 136, 255);
/// <summary>
/// The active vertex shader.
/// </summary>
private Shader _vertexShader;
private bool _vertexShaderDirty;
/// <summary>
/// The active pixel shader.
/// </summary>
private Shader _pixelShader;
private bool _pixelShaderDirty;
#if OPENGL
static List<Action> disposeActions = new List<Action>();
static object disposeActionsLock = new object();
#endif
private readonly ConstantBufferCollection _vertexConstantBuffers = new ConstantBufferCollection(ShaderStage.Vertex, 16);
private readonly ConstantBufferCollection _pixelConstantBuffers = new ConstantBufferCollection(ShaderStage.Pixel, 16);
#if DIRECTX
// Core Direct3D Objects
internal SharpDX.Direct3D11.Device _d3dDevice;
internal SharpDX.Direct3D11.DeviceContext _d3dContext;
protected FeatureLevel _featureLevel;
protected SharpDX.Direct3D11.RenderTargetView _renderTargetView;
protected SharpDX.Direct3D11.DepthStencilView _depthStencilView;
#if WINDOWS_STOREAPP
// Declare Direct2D Objects
protected SharpDX.Direct2D1.Factory1 _d2dFactory;
protected SharpDX.Direct2D1.Device _d2dDevice;
protected SharpDX.Direct2D1.DeviceContext _d2dContext;
// Declare DirectWrite & Windows Imaging Component Objects
protected SharpDX.DirectWrite.Factory _dwriteFactory;
protected SharpDX.WIC.ImagingFactory2 _wicFactory;
// The swap chain resources.
protected SharpDX.Direct2D1.Bitmap1 _bitmapTarget;
protected SharpDX.DXGI.SwapChain1 _swapChain;
protected SwapChainBackgroundPanel _swapChainPanel;
protected float _dpi;
#elif !WINDOWS_PHONE
protected SwapChain _swapChain;
#endif
// The active render targets.
protected SharpDX.Direct3D11.RenderTargetView[] _currentRenderTargets = new SharpDX.Direct3D11.RenderTargetView[4];
// The active depth view.
protected SharpDX.Direct3D11.DepthStencilView _currentDepthStencilView;
private readonly Dictionary<ulong, SharpDX.Direct3D11.InputLayout> _inputLayouts = new Dictionary<ulong, SharpDX.Direct3D11.InputLayout>();
private readonly Dictionary<int, DynamicVertexBuffer> _userVertexBuffers = new Dictionary<int, DynamicVertexBuffer>();
private readonly Dictionary<IndexElementSize, DynamicIndexBuffer> _userIndexBuffers = new Dictionary<IndexElementSize, DynamicIndexBuffer>();
#endif // DIRECTX
#if OPENGL
private readonly ShaderProgramCache _programCache = new ShaderProgramCache();
private int _shaderProgram = -1;
static readonly float[] _posFixup = new float[4];
internal static readonly List<int> _enabledVertexAttributes = new List<int>();
#elif PSM
internal GraphicsContext _graphics;
internal List<PssVertexBuffer> _availableVertexBuffers = new List<PssVertexBuffer>();
internal List<PssVertexBuffer> _usedVertexBuffers = new List<PssVertexBuffer>();
#endif
#if GLES
const FramebufferTarget GLFramebuffer = FramebufferTarget.Framebuffer;
const RenderbufferTarget GLRenderbuffer = RenderbufferTarget.Renderbuffer;
const FramebufferAttachment GLDepthAttachment = FramebufferAttachment.DepthAttachment;
const FramebufferAttachment GLStencilAttachment = FramebufferAttachment.StencilAttachment;
const FramebufferAttachment GLColorAttachment0 = FramebufferAttachment.ColorAttachment0;
const GetPName GLFramebufferBinding = GetPName.FramebufferBinding;
const RenderbufferStorage GLDepthComponent16 = RenderbufferStorage.DepthComponent16;
const RenderbufferStorage GLDepthComponent24 = RenderbufferStorage.DepthComponent24Oes;
const RenderbufferStorage GLDepth24Stencil8 = RenderbufferStorage.Depth24Stencil8Oes;
const FramebufferErrorCode GLFramebufferComplete = FramebufferErrorCode.FramebufferComplete;
#elif OPENGL
const FramebufferTarget GLFramebuffer = FramebufferTarget.FramebufferExt;
const RenderbufferTarget GLRenderbuffer = RenderbufferTarget.RenderbufferExt;
const FramebufferAttachment GLDepthAttachment = FramebufferAttachment.DepthAttachmentExt;
const FramebufferAttachment GLStencilAttachment = FramebufferAttachment.StencilAttachment;
const FramebufferAttachment GLColorAttachment0 = FramebufferAttachment.ColorAttachment0;
const GetPName GLFramebufferBinding = GetPName.FramebufferBinding;
const RenderbufferStorage GLDepthComponent16 = RenderbufferStorage.DepthComponent16;
const RenderbufferStorage GLDepthComponent24 = RenderbufferStorage.DepthComponent24;
const RenderbufferStorage GLDepth24Stencil8 = RenderbufferStorage.Depth24Stencil8;
const FramebufferErrorCode GLFramebufferComplete = FramebufferErrorCode.FramebufferComplete;
#endif
// TODO Graphics Device events need implementing
public event EventHandler<EventArgs> DeviceLost;
public event EventHandler<EventArgs> DeviceReset;
public event EventHandler<EventArgs> DeviceResetting;
public event EventHandler<ResourceCreatedEventArgs> ResourceCreated;
public event EventHandler<ResourceDestroyedEventArgs> ResourceDestroyed;
public event EventHandler<EventArgs> Disposing;
readonly List<string> _extensions = new List<string>();
#if OPENGL
internal int glFramebuffer;
internal int MaxVertexAttributes;
#endif
internal int MaxTextureSlots;
#if WINDOWS_STOREAPP
internal float Dpi
{
get { return _dpi; }
set
{
if (_dpi == value)
return;
_dpi = value;
_d2dContext.DotsPerInch = new DrawingSizeF(_dpi, _dpi);
//if (OnDpiChanged != null)
//OnDpiChanged(this);
}
}
#endif
#if OPENGL
internal void SetVertexAttributeArray(bool[] attrs)
{
for(int x = 0; x < attrs.Length; x++)
{
if (attrs[x] && !_enabledVertexAttributes.Contains(x))
{
_enabledVertexAttributes.Add(x);
GL.EnableVertexAttribArray(x);
GraphicsExtensions.CheckGLError();
}
else if (!attrs[x] && _enabledVertexAttributes.Contains(x))
{
_enabledVertexAttributes.Remove(x);
GL.DisableVertexAttribArray(x);
GraphicsExtensions.CheckGLError();
}
}
}
#endif
public bool IsDisposed
{
get
{
return _isDisposed;
}
}
public bool IsContentLost {
get {
// We will just return IsDisposed for now
// as that is the only case I can see for now
return IsDisposed;
}
}
internal bool IsRenderTargetBound
{
get
{
return _currentRenderTargetBindings != null && _currentRenderTargetBindings.Length > 0;
}
}
public GraphicsDevice ()
{
// Initialize the main viewport
_viewport = new Viewport (0, 0,
DisplayMode.Width, DisplayMode.Height);
_viewport.MaxDepth = 1.0f;
MaxTextureSlots = 16;
#if GLES
GL.GetInteger(All.MaxTextureImageUnits, ref MaxTextureSlots);
GraphicsExtensions.CheckGLError();
GL.GetInteger(All.MaxVertexAttribs, ref MaxVertexAttributes);
GraphicsExtensions.CheckGLError();
#elif OPENGL
GL.GetInteger(GetPName.MaxTextureImageUnits, out MaxTextureSlots);
GraphicsExtensions.CheckGLError();
GL.GetInteger(GetPName.MaxVertexAttribs, out MaxVertexAttributes);
GraphicsExtensions.CheckGLError();
#endif
Textures = new TextureCollection (MaxTextureSlots);
SamplerStates = new SamplerStateCollection (MaxTextureSlots);
PresentationParameters = new PresentationParameters ();
PresentationParameters.DepthStencilFormat = DepthFormat.Depth24;
}
~GraphicsDevice()
{
Dispose(false);
}
internal void Initialize()
{
// Setup extensions.
#if OPENGL
#if GLES
var extstring = GL.GetString(RenderbufferStorage.Extensions);
#else
var extstring = GL.GetString(StringName.Extensions);
#endif
GraphicsExtensions.CheckGLError();
if (!string.IsNullOrEmpty(extstring))
{
_extensions.AddRange(extstring.Split(' '));
#if ANDROID
Android.Util.Log.Debug("MonoGame", "Supported extensions:");
#else
System.Diagnostics.Debug.WriteLine("Supported extensions:");
#endif
foreach (string extension in _extensions)
#if ANDROID
Android.Util.Log.Debug("MonoGame", extension);
#else
System.Diagnostics.Debug.WriteLine(extension);
#endif
}
#endif // OPENGL
#if DIRECTX
#if WINDOWS_PHONE
UpdateDevice(DrawingSurfaceState.Device, DrawingSurfaceState.Context);
UpdateTarget(DrawingSurfaceState.RenderTargetView);
DrawingSurfaceState.Device = null;
DrawingSurfaceState.Context = null;
DrawingSurfaceState.RenderTargetView = null;
#elif WINDOWS_STOREAPP
CreateDeviceIndependentResources();
CreateDeviceResources();
Dpi = DisplayProperties.LogicalDpi;
CreateSizeDependentResources();
#elif WINDOWS
CreateDeviceResources();
CreateSizeDependentResources();
#endif
#elif PSM
_graphics = new GraphicsContext();
#elif OPENGL
_viewport = new Viewport(0, 0, PresentationParameters.BackBufferWidth, PresentationParameters.BackBufferHeight);
#endif
// Force set the default render states.
_blendStateDirty = _depthStencilStateDirty = _rasterizerStateDirty = true;
BlendState = BlendState.Opaque;
DepthStencilState = DepthStencilState.Default;
RasterizerState = RasterizerState.CullCounterClockwise;
// Clear the texture and sampler collections forcing
// the state to be reapplied.
Textures.Clear();
SamplerStates.Clear();
// Clear constant buffers
_vertexConstantBuffers.Clear();
_pixelConstantBuffers.Clear();
#if OPENGL
// Ensure the vertex attributes are reset
_enabledVertexAttributes.Clear();
#endif
// Force set the buffers and shaders on next ApplyState() call
_indexBufferDirty = true;
_vertexBufferDirty = true;
_vertexShaderDirty = true;
_pixelShaderDirty = true;
// Set the default scissor rect.
_scissorRectangleDirty = true;
ScissorRectangle = _viewport.Bounds;
// Set the default render target.
ApplyRenderTargets(null);
#if OPENGL
// Free all the cached shader programs.
_programCache.Clear();
_shaderProgram = -1;
#endif
}
#if DIRECTX
#if WINDOWS_PHONE
internal void UpdateDevice(Device device, DeviceContext context)
{
// TODO: Lost device logic!
if (_d3dDevice != null)
{
_d3dDevice.Dispose();
_d3dDevice = null;
}
_d3dDevice = device;
if (_d3dContext != null)
{
_d3dContext.Dispose();
_d3dContext = null;
}
_d3dContext = context;
}
internal void UpdateTarget(RenderTargetView renderTargetView)
{
_renderTargetView = renderTargetView;
_currentRenderTargets[0] = _renderTargetView;
_currentDepthStencilView = _depthStencilView;
var resource = _renderTargetView.Resource;
using (var texture2D = new SharpDX.Direct3D11.Texture2D(resource.NativePointer))
{
var currentWidth = PresentationParameters.BackBufferWidth;
var currentHeight = PresentationParameters.BackBufferHeight;
if (currentWidth != texture2D.Description.Width &&
currentHeight != texture2D.Description.Height)
{
PresentationParameters.BackBufferWidth = texture2D.Description.Width;
PresentationParameters.BackBufferHeight = texture2D.Description.Height;
ComObject.Dispose(ref _depthStencilView);
using (var depthTexture = new SharpDX.Direct3D11.Texture2D(
_d3dDevice,
new Texture2DDescription()
{
Width = PresentationParameters.BackBufferWidth,
Height = PresentationParameters.BackBufferHeight,
ArraySize = 1,
BindFlags = BindFlags.DepthStencil,
CpuAccessFlags = CpuAccessFlags.None,
Format = SharpDX.DXGI.Format.D24_UNorm_S8_UInt,
MipLevels = 1,
OptionFlags = ResourceOptionFlags.None,
SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
Usage = ResourceUsage.Default
}))
_depthStencilView = new DepthStencilView(_d3dDevice, depthTexture);
Viewport = new Viewport(0, 0, PresentationParameters.BackBufferWidth, PresentationParameters.BackBufferHeight);
}
}
}
#elif WINDOWS_STOREAPP
/// <summary>
/// Creates resources not tied the active graphics device.
/// </summary>
protected void CreateDeviceIndependentResources()
{
#if DEBUG
var debugLevel = SharpDX.Direct2D1.DebugLevel.Information;
#else
var debugLevel = SharpDX.Direct2D1.DebugLevel.None;
#endif
// Dispose previous references.
if (_d2dFactory != null)
_d2dFactory.Dispose();
if (_dwriteFactory != null)
_dwriteFactory.Dispose();
if (_wicFactory != null)
_wicFactory.Dispose();
// Allocate new references
_d2dFactory = new SharpDX.Direct2D1.Factory1(SharpDX.Direct2D1.FactoryType.SingleThreaded, debugLevel);
_dwriteFactory = new SharpDX.DirectWrite.Factory(SharpDX.DirectWrite.FactoryType.Shared);
_wicFactory = new SharpDX.WIC.ImagingFactory2();
}
/// <summary>
/// Create graphics device specific resources.
/// </summary>
protected virtual void CreateDeviceResources()
{
// Dispose previous references.
if (_d3dDevice != null)
_d3dDevice.Dispose();
if (_d3dContext != null)
_d3dContext.Dispose();
if (_d2dDevice != null)
_d2dDevice.Dispose();
if (_d2dContext != null)
_d2dContext.Dispose();
// Windows requires BGRA support out of DX.
var creationFlags = SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport;
#if DEBUG
creationFlags |= SharpDX.Direct3D11.DeviceCreationFlags.Debug;
#endif
// Pass the preferred feature levels based on the
// target profile that may have been set by the user.
var featureLevels = new List<FeatureLevel>();
if (GraphicsProfile == GraphicsProfile.HiDef)
{
featureLevels.Add(FeatureLevel.Level_11_1);
featureLevels.Add(FeatureLevel.Level_11_0);
featureLevels.Add(FeatureLevel.Level_10_1);
featureLevels.Add(FeatureLevel.Level_10_0);
}
featureLevels.Add(FeatureLevel.Level_9_3);
featureLevels.Add(FeatureLevel.Level_9_2);
featureLevels.Add(FeatureLevel.Level_9_1);
// Create the Direct3D device.
using (var defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, creationFlags, featureLevels.ToArray()))
_d3dDevice = defaultDevice.QueryInterface<SharpDX.Direct3D11.Device1>();
// Set the correct profile based on the feature level.
_featureLevel = _d3dDevice.FeatureLevel;
GraphicsProfile = _featureLevel <= FeatureLevel.Level_9_3 ? GraphicsProfile.Reach : GraphicsProfile.HiDef;
// Get Direct3D 11.1 context
_d3dContext = _d3dDevice.ImmediateContext.QueryInterface<SharpDX.Direct3D11.DeviceContext1>();
// Create the Direct2D device.
using (var dxgiDevice = _d3dDevice.QueryInterface<SharpDX.DXGI.Device>())
_d2dDevice = new SharpDX.Direct2D1.Device(_d2dFactory, dxgiDevice);
// Create Direct2D context
_d2dContext = new SharpDX.Direct2D1.DeviceContext(_d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None);
}
internal void CreateSizeDependentResources()
{
_d3dContext.OutputMerger.SetTargets((SharpDX.Direct3D11.DepthStencilView)null,
(SharpDX.Direct3D11.RenderTargetView)null);
_d2dContext.Target = null;
if (_renderTargetView != null)
{
_renderTargetView.Dispose();
_renderTargetView = null;
}
if (_depthStencilView != null)
{
_depthStencilView.Dispose();
_depthStencilView = null;
}
if (_bitmapTarget != null)
{
_bitmapTarget.Dispose();
_bitmapTarget = null;
}
// Clear the current render targets.
_currentDepthStencilView = null;
_currentRenderTargets[0] = null;
_currentRenderTargets[1] = null;
_currentRenderTargets[2] = null;
_currentRenderTargets[3] = null;
_currentDepthStencilView = null;
_currentRenderTargetBindings = null;
// Make sure all pending rendering commands are flushed.
_d3dContext.Flush();
// We need presentation parameters to continue here.
if ( PresentationParameters == null ||
(PresentationParameters.DeviceWindowHandle == IntPtr.Zero && PresentationParameters.SwapChainPanel == null))
{
if (_swapChain != null)
{
_swapChain.Dispose();
_swapChain = null;
}
return;
}
// Did we change swap panels?
if (PresentationParameters.SwapChainPanel != _swapChainPanel)
{
_swapChainPanel = null;
if (_swapChain != null)
{
_swapChain.Dispose();
_swapChain = null;
}
}
var multisampleDesc = new SharpDX.DXGI.SampleDescription(1, 0);
if ( PresentationParameters.MultiSampleCount > 1 )
{
multisampleDesc.Count = PresentationParameters.MultiSampleCount;
multisampleDesc.Quality = (int)SharpDX.Direct3D11.StandardMultisampleQualityLevels.StandardMultisamplePattern;
}
// Use BGRA for the swap chain.
var format = PresentationParameters.BackBufferFormat == SurfaceFormat.Color ?
SharpDX.DXGI.Format.B8G8R8A8_UNorm :
SharpDXHelper.ToFormat(PresentationParameters.BackBufferFormat);
// If the swap chain already exists... update it.
if (_swapChain != null)
{
_swapChain.ResizeBuffers( 2,
PresentationParameters.BackBufferWidth,
PresentationParameters.BackBufferHeight,
format,
SwapChainFlags.None);
}
// Otherwise, create a new swap chain.
else
{
// SwapChain description
var desc = new SharpDX.DXGI.SwapChainDescription1()
{
// Automatic sizing
Width = PresentationParameters.BackBufferWidth,
Height = PresentationParameters.BackBufferHeight,
Format = format,
Stereo = false,
SampleDescription = multisampleDesc,
Usage = SharpDX.DXGI.Usage.RenderTargetOutput,
BufferCount = 2,
SwapEffect = SharpDXHelper.ToSwapEffect(PresentationParameters),
// By default we scale the backbuffer to the window
// rectangle to function more like a WP7 game.
Scaling = SharpDX.DXGI.Scaling.Stretch,
};
// Once the desired swap chain description is configured, it must be created on the same adapter as our D3D Device
// First, retrieve the underlying DXGI Device from the D3D Device.
// Creates the swap chain
using (var dxgiDevice2 = _d3dDevice.QueryInterface<SharpDX.DXGI.Device2>())
using (var dxgiAdapter = dxgiDevice2.Adapter)
using (var dxgiFactory2 = dxgiAdapter.GetParent<SharpDX.DXGI.Factory2>())
{
if (PresentationParameters.DeviceWindowHandle != IntPtr.Zero)
{
// Creates a SwapChain from a CoreWindow pointer.
var coreWindow = Marshal.GetObjectForIUnknown(PresentationParameters.DeviceWindowHandle) as CoreWindow;
using (var comWindow = new ComObject(coreWindow))
_swapChain = dxgiFactory2.CreateSwapChainForCoreWindow(_d3dDevice, comWindow, ref desc, null);
}
else
{
_swapChainPanel = PresentationParameters.SwapChainPanel;
using (var nativePanel = ComObject.As<SharpDX.DXGI.ISwapChainBackgroundPanelNative>(PresentationParameters.SwapChainPanel))
{
_swapChain = dxgiFactory2.CreateSwapChainForComposition(_d3dDevice, ref desc, null);
nativePanel.SwapChain = _swapChain;
}
}
// Ensure that DXGI does not queue more than one frame at a time. This both reduces
// latency and ensures that the application will only render after each VSync, minimizing
// power consumption.
dxgiDevice2.MaximumFrameLatency = 1;
}
}
_swapChain.Rotation = SharpDX.DXGI.DisplayModeRotation.Identity;
// Obtain the backbuffer for this window which will be the final 3D rendertarget.
Point targetSize;
using (var backBuffer = SharpDX.Direct3D11.Texture2D.FromSwapChain<SharpDX.Direct3D11.Texture2D>(_swapChain, 0))
{
// Create a view interface on the rendertarget to use on bind.
_renderTargetView = new SharpDX.Direct3D11.RenderTargetView(_d3dDevice, backBuffer);
// Get the rendertarget dimensions for later.
var backBufferDesc = backBuffer.Description;
targetSize = new Point(backBufferDesc.Width, backBufferDesc.Height);
}
// Create the depth buffer if we need it.
if (PresentationParameters.DepthStencilFormat != DepthFormat.None)
{
var depthFormat = SharpDXHelper.ToFormat(PresentationParameters.DepthStencilFormat);
// Allocate a 2-D surface as the depth/stencil buffer.
using (var depthBuffer = new SharpDX.Direct3D11.Texture2D(_d3dDevice, new SharpDX.Direct3D11.Texture2DDescription()
{
Format = depthFormat,
ArraySize = 1,
MipLevels = 1,
Width = targetSize.X,
Height = targetSize.Y,
SampleDescription = multisampleDesc,
Usage = SharpDX.Direct3D11.ResourceUsage.Default,
BindFlags = SharpDX.Direct3D11.BindFlags.DepthStencil,
}))
// Create a DepthStencil view on this surface to use on bind.
_depthStencilView = new SharpDX.Direct3D11.DepthStencilView(_d3dDevice, depthBuffer);
}
// Set the current viewport.
Viewport = new Viewport
{
X = 0,
Y = 0,
Width = targetSize.X,
Height = targetSize.Y,
MinDepth = 0.0f,
MaxDepth = 1.0f
};
// Now we set up the Direct2D render target bitmap linked to the swapchain.
// Whenever we render to this bitmap, it will be directly rendered to the
// swapchain associated with the window.
var bitmapProperties = new SharpDX.Direct2D1.BitmapProperties1(
new SharpDX.Direct2D1.PixelFormat(format, SharpDX.Direct2D1.AlphaMode.Premultiplied),
_dpi, _dpi,
SharpDX.Direct2D1.BitmapOptions.Target | SharpDX.Direct2D1.BitmapOptions.CannotDraw);
// Direct2D needs the dxgi version of the backbuffer surface pointer.
// Get a D2D surface from the DXGI back buffer to use as the D2D render target.
using (var dxgiBackBuffer = _swapChain.GetBackBuffer<SharpDX.DXGI.Surface>(0))
_bitmapTarget = new SharpDX.Direct2D1.Bitmap1(_d2dContext, dxgiBackBuffer, bitmapProperties);
// So now we can set the Direct2D render target.
_d2dContext.Target = _bitmapTarget;
// Set D2D text anti-alias mode to Grayscale to
// ensure proper rendering of text on intermediate surfaces.
_d2dContext.TextAntialiasMode = SharpDX.Direct2D1.TextAntialiasMode.Grayscale;
}
#elif WINDOWS
/// <summary>
/// Create graphics device specific resources.
/// </summary>
protected virtual void CreateDeviceResources()
{
// Dispose previous references.
if (_d3dDevice != null)
_d3dDevice.Dispose();
if (_d3dContext != null)
_d3dContext.Dispose();
// Windows requires BGRA support out of DX.
var creationFlags = SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport;
#if DEBUG
creationFlags |= SharpDX.Direct3D11.DeviceCreationFlags.Debug;
#endif
// Pass the preferred feature levels based on the
// target profile that may have been set by the user.
var featureLevels = new List<FeatureLevel>();
if (GraphicsProfile == GraphicsProfile.HiDef)
{
featureLevels.Add(FeatureLevel.Level_11_0);
featureLevels.Add(FeatureLevel.Level_10_1);
featureLevels.Add(FeatureLevel.Level_10_0);
}
featureLevels.Add(FeatureLevel.Level_9_3);
featureLevels.Add(FeatureLevel.Level_9_2);
featureLevels.Add(FeatureLevel.Level_9_1);
// Create the Direct3D device.
using (var defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, creationFlags, featureLevels.ToArray()))
_d3dDevice = defaultDevice.QueryInterface<SharpDX.Direct3D11.Device>();
// Set the correct profile based on the feature level.
_featureLevel = _d3dDevice.FeatureLevel;
GraphicsProfile = _featureLevel <= FeatureLevel.Level_9_3 ? GraphicsProfile.Reach : GraphicsProfile.HiDef;
// Get Direct3D 11.1 context
_d3dContext = _d3dDevice.ImmediateContext.QueryInterface<SharpDX.Direct3D11.DeviceContext>();
}
internal void CreateSizeDependentResources()
{
_d3dContext.OutputMerger.SetTargets((SharpDX.Direct3D11.DepthStencilView)null,
(SharpDX.Direct3D11.RenderTargetView)null);
if (_renderTargetView != null)
{
_renderTargetView.Dispose();
_renderTargetView = null;
}
if (_depthStencilView != null)
{
_depthStencilView.Dispose();
_depthStencilView = null;
}
// Clear the current render targets.
_currentDepthStencilView = null;
_currentRenderTargets[0] = null;
_currentRenderTargets[1] = null;
_currentRenderTargets[2] = null;
_currentRenderTargets[3] = null;
_currentDepthStencilView = null;
_currentRenderTargetBindings = null;
// Make sure all pending rendering commands are flushed.
_d3dContext.Flush();
// We need presentation parameters to continue here.
if (PresentationParameters == null || PresentationParameters.DeviceWindowHandle == IntPtr.Zero)
{
if (_swapChain != null)
{
_swapChain.Dispose();
_swapChain = null;
}
return;
}
var multisampleDesc = new SharpDX.DXGI.SampleDescription(1, 0);
if (PresentationParameters.MultiSampleCount > 1)
{
multisampleDesc.Count = PresentationParameters.MultiSampleCount;
multisampleDesc.Quality = (int)SharpDX.Direct3D11.StandardMultisampleQualityLevels.StandardMultisamplePattern;
}
// Use BGRA for the swap chain.
var format = PresentationParameters.BackBufferFormat == SurfaceFormat.Color ?
SharpDX.DXGI.Format.B8G8R8A8_UNorm :
SharpDXHelper.ToFormat(PresentationParameters.BackBufferFormat);
// If the swap chain already exists... update it.
if (_swapChain != null)
{
_swapChain.ResizeBuffers(2,
PresentationParameters.BackBufferWidth,
PresentationParameters.BackBufferHeight,
format,
SwapChainFlags.None);
}
// Otherwise, create a new swap chain.
else
{
// SwapChain description
var desc = new SharpDX.DXGI.SwapChainDescription()
{
ModeDescription =
{
Format = format,
Scaling = DisplayModeScaling.Stretched,
Width = PresentationParameters.BackBufferWidth,
Height = PresentationParameters.BackBufferHeight,
},
OutputHandle = PresentationParameters.DeviceWindowHandle,
SampleDescription = multisampleDesc,
Usage = SharpDX.DXGI.Usage.RenderTargetOutput,
BufferCount = 2,
SwapEffect = SharpDXHelper.ToSwapEffect(PresentationParameters),
IsWindowed = true,
};
// Once the desired swap chain description is configured, it must be created on the same adapter as our D3D Device
// First, retrieve the underlying DXGI Device from the D3D Device.
// Creates the swap chain
using (var dxgiDevice = _d3dDevice.QueryInterface<SharpDX.DXGI.Device1>())
using (var dxgiAdapter = dxgiDevice.Adapter)
using (var dxgiFactory = dxgiAdapter.GetParent<SharpDX.DXGI.Factory1>())
{
_swapChain = new SwapChain(dxgiFactory, dxgiDevice, desc);
// Ensure that DXGI does not queue more than one frame at a time. This
// both reduces latency and ensures that the application will only render
// after each VSync, minimizing power consumption.
dxgiDevice.MaximumFrameLatency = 1;
}
}
// Obtain the backbuffer for this window which will be the final 3D rendertarget.
Point targetSize;
using (var backBuffer = SharpDX.Direct3D11.Texture2D.FromSwapChain<SharpDX.Direct3D11.Texture2D>(_swapChain, 0))
{
// Create a view interface on the rendertarget to use on bind.
_renderTargetView = new SharpDX.Direct3D11.RenderTargetView(_d3dDevice, backBuffer);
// Get the rendertarget dimensions for later.
var backBufferDesc = backBuffer.Description;
targetSize = new Point(backBufferDesc.Width, backBufferDesc.Height);
}
// Create the depth buffer if we need it.
if (PresentationParameters.DepthStencilFormat != DepthFormat.None)
{
var depthFormat = SharpDXHelper.ToFormat(PresentationParameters.DepthStencilFormat);
// Allocate a 2-D surface as the depth/stencil buffer.
using (var depthBuffer = new SharpDX.Direct3D11.Texture2D(_d3dDevice, new SharpDX.Direct3D11.Texture2DDescription()
{
Format = depthFormat,
ArraySize = 1,
MipLevels = 1,
Width = targetSize.X,
Height = targetSize.Y,
SampleDescription = multisampleDesc,
Usage = SharpDX.Direct3D11.ResourceUsage.Default,
BindFlags = SharpDX.Direct3D11.BindFlags.DepthStencil,
}))
// Create a DepthStencil view on this surface to use on bind.
_depthStencilView = new SharpDX.Direct3D11.DepthStencilView(_d3dDevice, depthBuffer);
}
// Set the current viewport.
Viewport = new Viewport
{
X = 0,
Y = 0,
Width = targetSize.X,
Height = targetSize.Y,
MinDepth = 0.0f,
MaxDepth = 1.0f
};
}
#endif // WINDOWS
#endif // DIRECTX
public RasterizerState RasterizerState
{
get
{
return _rasterizerState;
}
set
{