protected override void OnRasterStateChanged() { if (IsAttached) { Disposer.RemoveAndDispose(ref rasterState); /// --- set up rasterizer states var rasterStateDesc = new RasterizerStateDescription() { FillMode = FillMode.Solid, CullMode = CullMode.Back, DepthBias = DepthBias, DepthBiasClamp = -1000, SlopeScaledDepthBias = +0, IsDepthClipEnabled = true, IsFrontCounterClockwise = true, //IsMultisampleEnabled = true, //IsAntialiasedLineEnabled = true, //IsScissorEnabled = true, }; try { rasterState = new RasterizerState(Device, rasterStateDesc); } catch (Exception) { } } }
/// <summary> /// SetupRasterizerState /// </summary> void SetupRasterizerState() { var rsd = new RasterizerStateDescription(); if (RasterizerState.CullMode == CullMode.CullNone) { rsd.CullMode = D3DCullMode.None; rsd.IsFrontCounterClockwise = false; } else if (RasterizerState.CullMode == CullMode.CullCW) { rsd.CullMode = D3DCullMode.Front; rsd.IsFrontCounterClockwise = false; } else if (RasterizerState.CullMode == CullMode.CullCCW) { rsd.CullMode = D3DCullMode.Front; rsd.IsFrontCounterClockwise = true; } rsd.FillMode = Converter.Convert(RasterizerState.FillMode); rsd.DepthBias = RasterizerState.DepthBias; rsd.DepthBiasClamp = 0; rsd.IsMultisampleEnabled = RasterizerState.MsaaEnabled; rsd.IsScissorEnabled = RasterizerState.ScissorEnabled; rsd.SlopeScaledDepthBias = RasterizerState.SlopeDepthBias; rasterState = new D3DRasterizerState(device.Device, rsd); }
public FilterPixelShader(Device device, int imageWidth, int imageHeight, int constantBufferSize, string pixelShaderBytecodeFilename) { vertexShader = new VertexShader(device, new ShaderBytecode(File.ReadAllBytes("Content/FullScreenQuadVS.cso"))); pixelShader = new PixelShader(device, new ShaderBytecode(File.ReadAllBytes(pixelShaderBytecodeFilename))); var rasterizerStateDesc = new RasterizerStateDescription() { CullMode = CullMode.None, FillMode = FillMode.Solid, IsDepthClipEnabled = false, IsFrontCounterClockwise = true, IsMultisampleEnabled = false, }; rasterizerState = new RasterizerState(device, rasterizerStateDesc); if (constantBufferSize > 0) { var constantBufferDesc = new BufferDescription() { Usage = ResourceUsage.Dynamic, BindFlags = BindFlags.ConstantBuffer, SizeInBytes = constantBufferSize, CpuAccessFlags = CpuAccessFlags.Write, StructureByteStride = 0, OptionFlags = 0, }; constantBuffer = new Buffer(device, constantBufferDesc); } viewport = new Viewport(0, 0, imageWidth, imageHeight); // TODO: get these dimensions vertexBufferBinding = new VertexBufferBinding(null, 0, 0); }
protected override void FreeResource() { State?.Dispose(); State = null; MultiSamplingState?.Dispose(); MultiSamplingState = null; }
internal void Clear() { m_deviceContext.ClearState(); m_inputLayout = null; m_primitiveTopology = PrimitiveTopology.Undefined; m_indexBufferRef = null; m_indexBufferFormat = 0; m_indexBufferOffset = 0; for (int i = 0; i < m_vertexBuffers.Length; i++) m_vertexBuffers[i] = null; for (int i = 0; i < m_vertexBuffersStrides.Length; i++) m_vertexBuffersStrides[i] = 0; m_blendState = null; m_stencilRef = 0; m_depthStencilState = null; m_rtvsCount = 0; for (int i = 0; i < m_rtvs.Length; i++) m_rtvs[i] = null; m_dsv = null; m_rasterizerState = null; m_scissorLeftTop = new Vector2I(-1, -1); m_scissorRightBottom = new Vector2I(-1, -1); m_viewport = default(RawViewportF); m_targetBuffer = null; m_targetOffsets = 0; m_statistics.ClearStates++; }
public RasterizerState(RasterizerSpec spec, SharpDX.Direct3D11.RasterizerState state, SharpDX.Direct3D11.RasterizerState multiSamplingState) { Spec = spec; State = state; MultiSamplingState = multiSamplingState; }
public ProjectiveTexturingShader(Device device) { var shaderByteCode = new ShaderBytecode(File.ReadAllBytes("Content/DepthAndProjectiveTextureVS.cso")); vertexShader = new VertexShader(device, shaderByteCode); geometryShader = new GeometryShader(device, new ShaderBytecode(File.ReadAllBytes("Content/DepthAndColorGS.cso"))); pixelShader = new PixelShader(device, new ShaderBytecode(File.ReadAllBytes("Content/DepthAndColorPS.cso"))); // depth stencil state var depthStencilStateDesc = new DepthStencilStateDescription() { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.LessEqual, IsStencilEnabled = false, }; depthStencilState = new DepthStencilState(device, depthStencilStateDesc); // rasterizer states var rasterizerStateDesc = new RasterizerStateDescription() { CullMode = CullMode.None, FillMode = FillMode.Solid, IsDepthClipEnabled = true, IsFrontCounterClockwise = true, IsMultisampleEnabled = true, }; rasterizerState = new RasterizerState(device, rasterizerStateDesc); // constant buffer var constantBufferDesc = new BufferDescription() { Usage = ResourceUsage.Dynamic, BindFlags = BindFlags.ConstantBuffer, SizeInBytes = Constants.size, CpuAccessFlags = CpuAccessFlags.Write, StructureByteStride = 0, OptionFlags = 0, }; constantBuffer = new SharpDX.Direct3D11.Buffer(device, constantBufferDesc); // user view sampler state var colorSamplerStateDesc = new SamplerStateDescription() { Filter = Filter.MinMagMipLinear, AddressU = TextureAddressMode.Border, AddressV = TextureAddressMode.Border, AddressW = TextureAddressMode.Border, //BorderColor = new SharpDX.Color4(0.5f, 0.5f, 0.5f, 1.0f), BorderColor = new SharpDX.Color4(0, 0, 0, 1.0f), }; colorSamplerState = new SamplerState(device, colorSamplerStateDesc); vertexInputLayout = new InputLayout(device, shaderByteCode.Data, new[] { new InputElement("SV_POSITION", 0, Format.R32G32B32A32_Float, 0, 0), }); }
public RasterizerState GetCullBackRasterizerState(DXDevice device, CullMode cullMode) { RasterizerState state; if (rasterizerStates.TryGetValue(cullMode, out state)) return state; var newState = new RasterizerState(device, GetRasterizer(cullMode)); rasterizerStates.Add(cullMode, newState); return newState; }
public RasterizerState(SharpDX.Direct3D11.FillMode fillMode, SharpDX.Direct3D11.CullMode cullMode, bool frontCounterClockwise) { RasterizerStateDescription desc = new RasterizerStateDescription(){ FillMode = fillMode, CullMode = cullMode, IsFrontCounterClockwise = frontCounterClockwise }; NativeRasterizerState = new SharpDX.Direct3D11.RasterizerState(GraphicManager.Device, desc); }
/// <summary> /// Initializes a new instance of the StateFactory /// </summary> /// <param name="device"></param> /// <param name="ubershader"></param> public StateFactory( Ubershader ubershader, Type enumType, Primitive primitive, VertexInputElement[] vertexInputElements, BlendState blendState, RasterizerState rasterizerState ) : base(ubershader.GraphicsDevice) { this.ubershader = ubershader; Enumerate( enumType, ubershader, (ps,i) => { ps.Primitive = primitive; ps.VertexInputElements = vertexInputElements; ps.BlendState = blendState; ps.RasterizerState = rasterizerState; } ); }
/// <summary> /// Sets the state of the rasterizer. /// </summary> /// <param name="desc">The desc.</param> /// <exception cref="System.Exception"></exception> public void SetRasterizerState(D3D11.RasterizerStateDescription desc) { if (d3dDevice == null || d3dContext == null) { throw new Exception(MethodBase.GetCurrentMethod().Name + "Device or DeviceContext is null"); } D3D11.RasterizerState rasterState = new D3D11.RasterizerState(d3dDevice, desc); if (d3dContext.Rasterizer.State != null) { d3dContext.Rasterizer.State.Dispose(); } d3dContext.Rasterizer.State = rasterState; }
private void InitDevice(int numSamples) { var width = m_Window.ClientRectangle.Width; var height = m_Window.ClientRectangle.Height; var refreshRate = new Rational(60, 1); var modeDesc = new ModeDescription(width, height, refreshRate, Format.R8G8B8A8_UNorm); var quality = GetBestQuality(numSamples); var swapChainDesc = new SwapChainDescription() { BufferCount = 1, IsWindowed = true, ModeDescription = modeDesc, SampleDescription = new SampleDescription(numSamples, quality), OutputHandle = Game.Inst.Window.Handle, Usage = Usage.RenderTargetOutput }; #if DEBUG const D3D11.DeviceCreationFlags DEBUG_FLAG = D3D11.DeviceCreationFlags.Debug; #else const D3D11.DeviceCreationFlags DEBUG_FLAG = D3D11.DeviceCreationFlags.None; #endif D3D11.Device.CreateWithSwapChain(DriverType.Hardware, D3D11.DeviceCreationFlags.SingleThreaded | DEBUG_FLAG, swapChainDesc, out Device, out m_SwapChain); m_DeviceContext = Device.ImmediateContext; var rsd = new D3D11.RasterizerStateDescription { CullMode = D3D11.CullMode.Back, FillMode = D3D11.FillMode.Solid, IsMultisampleEnabled = true, }; var rs = new D3D11.RasterizerState(Device, rsd); Device.ImmediateContext.Rasterizer.State = rs; var backBuffer = m_SwapChain.GetBackBuffer <D3D11.Texture2D>(0); m_DefaultRenderTarget = new SharpDXRenderTarget(this, backBuffer, width, height, new D3D11.RenderTargetView(Device, backBuffer)); RenderTarget = m_DefaultRenderTarget; m_DeviceContext.Rasterizer.SetViewport(0.0f, 0.0f, width, height); }
public RasterizerState(GraphicsDevice graphicsdevice, RasterizerStateInfo info) : base(graphicsdevice, new StackTrace(1)) { this.Info = info; Handle = new SharpDX.Direct3D11.RasterizerState(graphicsdevice.Device, new RasterizerStateDescription() { FillMode = EnumConverter.Convert(info.FillMode), CullMode = EnumConverter.Convert(info.CullMode), IsFrontCounterClockwise = info.IsFrontCounterClockwise, DepthBias = info.DepthBias, DepthBiasClamp = info.DepthBiasClamp, SlopeScaledDepthBias = info.SlopeScaledDepthBias, IsAntialiasedLineEnabled = info.IsAntialiasedLineEnabled, IsDepthClipEnabled = info.IsDepthClipEnabled, IsScissorEnabled = info.IsScissorEnabled, IsMultisampleEnabled = info.IsMultisampleEnabled }); }
/// <summary> /// Function to retrieve the D3D state object. /// </summary> /// <param name="stateType">The state type information.</param> /// <returns>The D3D state object.</returns> internal override D3D.DeviceChild GetStateObject(ref GorgonRasterizerStates stateType) { var desc = new D3D.RasterizerStateDescription { CullMode = (D3D.CullMode)States.CullingMode, DepthBias = States.DepthBias, DepthBiasClamp = States.DepthBiasClamp, FillMode = (D3D.FillMode)States.FillMode, IsAntialiasedLineEnabled = States.IsAntialiasedLinesEnabled, IsDepthClipEnabled = States.IsDepthClippingEnabled, IsFrontCounterClockwise = States.IsFrontFacingTriangleCounterClockwise, IsMultisampleEnabled = States.IsMultisamplingEnabled, IsScissorEnabled = States.IsScissorTestingEnabled }; var state = new D3D.RasterizerState(Graphics.D3DDevice, desc) { DebugName = "Gorgon Rasterizer State #" + StateCacheCount }; return(state); }
public D3DRasterizerState( Device device, FaceCullingMode cullMode, TriangleFillMode fillMode, bool depthClipEnabled, bool scissorTestEnabled) { _device = device; CullMode = cullMode; FillMode = fillMode; IsDepthClipEnabled = depthClipEnabled; IsScissorTestEnabled = scissorTestEnabled; var desc = new RasterizerStateDescription() { IsDepthClipEnabled = IsDepthClipEnabled, IsScissorEnabled = IsScissorTestEnabled, CullMode = D3DFormats.ConvertCullMode(cullMode), FillMode = D3DFormats.ConvertFillMode(fillMode) }; _deviceState = new SharpDX.Direct3D11.RasterizerState(device, desc); }
public RasterizerStatesStruct(D3D.Device device) { var desc = new D3D.RasterizerStateDescription() { CullMode = D3D.CullMode.Back, DepthBias = 0, DepthBiasClamp = 0, FillMode = D3D.FillMode.Solid, IsAntialiasedLineEnabled = false, IsDepthClipEnabled = true, IsFrontCounterClockwise = false, IsMultisampleEnabled = true, IsScissorEnabled = false, SlopeScaledDepthBias = 0 }; Back = new D3D.RasterizerState(device, desc); desc.CullMode = D3D.CullMode.None; None = new D3D.RasterizerState(device, desc); desc.FillMode = D3D.FillMode.Wireframe; Wire = new D3D.RasterizerState(device, desc); }
private void InitializeDeviceResources(DXGI.SwapChain swapChain) { backbufferTexture = swapChain.GetBackBuffer <D3D11.Texture2D>(0); backbufferRTV = new D3D11.RenderTargetView(device, backbufferTexture); width = backbufferTexture.Description.Width; height = backbufferTexture.Description.Height; D3D11.Texture2DDescription sceneTextureDesc = new D3D11.Texture2DDescription { CpuAccessFlags = D3D11.CpuAccessFlags.None, BindFlags = D3D11.BindFlags.RenderTarget | D3D11.BindFlags.ShaderResource, Format = DXGI.Format.R8G8B8A8_UNorm, Width = width, Height = height, OptionFlags = D3D11.ResourceOptionFlags.None, MipLevels = 1, ArraySize = 1, SampleDescription = { Count = 1, Quality = 0 }, Usage = D3D11.ResourceUsage.Default }; sceneTexture = new D3D11.Texture2D(device, sceneTextureDesc); sceneRTV = new D3D11.RenderTargetView(device, sceneTexture); sceneSRV = new D3D11.ShaderResourceView(device, sceneTexture); var depthBufferDesc = new D3D11.Texture2DDescription() { Width = width, Height = height, MipLevels = 1, ArraySize = 1, Format = DXGI.Format.R32_Typeless, SampleDescription = { Count = 1, Quality = 0 }, Usage = D3D11.ResourceUsage.Default, BindFlags = D3D11.BindFlags.DepthStencil | D3D11.BindFlags.ShaderResource, CpuAccessFlags = D3D11.CpuAccessFlags.None, OptionFlags = D3D11.ResourceOptionFlags.None }; using (var depthStencilBufferTexture = new D3D11.Texture2D(device, depthBufferDesc)) { var depthStencilViewDesc = new D3D11.DepthStencilViewDescription() { Format = DXGI.Format.D32_Float, Dimension = D3D11.DepthStencilViewDimension.Texture2D, Texture2D = { MipSlice = 0 } }; depthDSV = new D3D11.DepthStencilView(device, depthStencilBufferTexture, depthStencilViewDesc); var shaderResourceViewDesc = new D3D11.ShaderResourceViewDescription() { Format = DXGI.Format.R32_Float, Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.Texture2D, Texture2D = { MipLevels = 1, MostDetailedMip = 0 } }; depthSRV = new D3D11.ShaderResourceView(device, depthStencilBufferTexture, shaderResourceViewDesc); } var depthStencilDesc = new D3D11.DepthStencilStateDescription() { IsDepthEnabled = true, DepthWriteMask = D3D11.DepthWriteMask.All, DepthComparison = D3D11.Comparison.Less, IsStencilEnabled = false, StencilReadMask = 0xFF, StencilWriteMask = 0xFF, FrontFace = new D3D11.DepthStencilOperationDescription() { FailOperation = D3D11.StencilOperation.Keep, DepthFailOperation = D3D11.StencilOperation.Keep, PassOperation = D3D11.StencilOperation.Keep, Comparison = D3D11.Comparison.Always }, BackFace = new D3D11.DepthStencilOperationDescription() { FailOperation = D3D11.StencilOperation.Keep, DepthFailOperation = D3D11.StencilOperation.Keep, PassOperation = D3D11.StencilOperation.Keep, Comparison = D3D11.Comparison.Always } }; depthStencilState = new D3D11.DepthStencilState(device, depthStencilDesc); var rasterDesc = new D3D11.RasterizerStateDescription() { IsAntialiasedLineEnabled = false, CullMode = D3D11.CullMode.Back, DepthBias = 0, DepthBiasClamp = 0.0f, IsDepthClipEnabled = true, FillMode = D3D11.FillMode.Solid, IsFrontCounterClockwise = false, IsMultisampleEnabled = false, IsScissorEnabled = false, SlopeScaledDepthBias = 0.0f }; rasterizerState = new D3D11.RasterizerState(device, rasterDesc); }
// Example using async protected override void CreateDeviceDependentResources(Common.DeviceManager deviceManager) { base.CreateDeviceDependentResources(deviceManager); RemoveAndDispose(ref fpsRenderer); RemoveAndDispose(ref cubeRenderer); RemoveAndDispose(ref textRenderer); RemoveAndDispose(ref vertexShader); RemoveAndDispose(ref vertexLayout); RemoveAndDispose(ref pixelShader); var device = deviceManager.Direct3DDevice; #region Compile shaders // Compile Vertex Shader and create vertex InputLayout using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\VS.hlsl", "VSMain", "vs_5_0")) { vertexShader = new VertexShader(device, bytecode); vertexLayout = ToDispose(new InputLayout(device, bytecode.GetPart(ShaderBytecodePart.InputSignatureBlob).Data, new[] { // "SV_Position" = vertex coordinate in object space new InputElement("SV_Position", 0, Format.R32G32B32_Float, 0, 0), // "NORMAL" = the vertex normal new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0), // "COLOR" new InputElement("COLOR", 0, Format.R8G8B8A8_UNorm, 24, 0), // "UV" new InputElement("TEXCOORD", 0, Format.R32G32_Float, 28, 0), // "BLENDINDICES" new InputElement("BLENDINDICES", 0, Format.R32G32B32A32_UInt, 36, 0), // "BLENDWEIGHT" new InputElement("BLENDWEIGHT", 0, Format.R32G32B32A32_Float, 52, 0), })); } // Compile pixel shader using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\SimplePS.hlsl", "PSMain", "ps_5_0")) pixelShader = ToDispose(new PixelShader(device, bytecode)); #endregion #region Create constant buffers // Create constant buffers // Create the constant buffer that will // store our worldViewProjection matrix perObjectBuffer = ToDispose(new SharpDX.Direct3D11.Buffer(device, Utilities.SizeOf<ConstantBuffers.PerObject>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0)); // Create the per frame constant buffer // lighting / camera position perFrameBuffer = ToDispose(new Buffer(device, Utilities.SizeOf<ConstantBuffers.PerFrame>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0)); // Create the per material constant buffer perMaterialBuffer = ToDispose(new Buffer(device, Utilities.SizeOf<ConstantBuffers.PerMaterial>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0)); // Create the per armature/skeletong constant buffer perArmatureBuffer = ToDispose(new Buffer(device, ConstantBuffers.PerArmature.Size(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0)); #endregion #region Create pipeline state variables // Configure the depth buffer to discard pixels that are // further than the current pixel. depthStencilState = ToDispose(new DepthStencilState(device, new DepthStencilStateDescription() { IsDepthEnabled = true, // enable depth? DepthComparison = Comparison.Less, DepthWriteMask = SharpDX.Direct3D11.DepthWriteMask.All, IsStencilEnabled = false,// enable stencil? StencilReadMask = 0xff, // 0xff (no mask) StencilWriteMask = 0xff,// 0xff (no mask) })); rsCullBack = ToDispose(new RasterizerState(device, new RasterizerStateDescription { CullMode = CullMode.Back, IsFrontCounterClockwise = false, FillMode = FillMode.Solid, })); #endregion #region Create Renderers cubeRenderer = new CubeRenderer(); cubeRenderer.Initialize(this); textRenderer = ToDispose(new TextRenderer("Calibri", SharpDX.Color.Black, new Point(20, 100), 48, 800)); textRenderer.Initialize(this); fpsRenderer = ToDispose(new FpsRenderer()); fpsRenderer.Initialize(this); #endregion clock.Start(); }
void DefineRasterizerState() { var desc = RasterizerStateDescription.Default(); desc.IsFrontCounterClockwise = true; default_rasterizer_state = new RasterizerState(device, desc); }
void CreateRasterizerStates() { var desc = RasterizerStateDescription.Default(); _rasterizerStateDefault = new RasterizerState(Device, desc); AutoDispose(_rasterizerStateDefault); }
public DX(int width, int height, float screenDepth, float screenNear, bool vSync, bool fullScreen, IntPtr hwnd) { this.vSync = vSync; var factory = new Factory(); var adapter = factory.GetAdapter(0); var monitor = adapter.Outputs[0]; var modes = monitor.GetDisplayModeList(Format.R8G8B8A8_UNorm, DisplayModeEnumerationFlags.Interlaced); var rational = new Rational(0, 1); if(vSync) { foreach(var mode in modes) { if(mode.Width == width && mode.Height == height) { rational = new Rational(mode.RefreshRate.Numerator, mode.RefreshRate.Denominator); break; } } } monitor.Dispose(); adapter.Dispose(); factory.Dispose(); var swapChainDesc = new SwapChainDescription { BufferCount = 1, ModeDescription = new ModeDescription(width, height, rational, Format.R8G8B8A8_UNorm), Usage = Usage.RenderTargetOutput, OutputHandle = hwnd, SampleDescription = new SampleDescription(1, 0), IsWindowed = !fullScreen, Flags = SwapChainFlags.None, SwapEffect = SwapEffect.Discard }; Device device; Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, new[] {FeatureLevel.Level_10_0}, swapChainDesc, out device, out swapChain); DXDevice = device; DXContext = device.ImmediateContext; var backBuffer = Resource.FromSwapChain<Texture2D>(swapChain, 0); renderTarget = new RenderTargetView(device, backBuffer); backBuffer.Dispose(); var depthBufferDesc = new Texture2DDescription { Width = width, Height = height, MipLevels = 1, ArraySize = 1, Format = Format.D24_UNorm_S8_UInt, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }; depthStenBuffer = new Texture2D(device, depthBufferDesc); var depthStencilDesc = new DepthStencilStateDescription { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less, IsStencilEnabled = true, StencilReadMask = 0xFF, StencilWriteMask = 0xFF, FrontFace = new DepthStencilOperationDescription { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Increment, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always }, BackFace = new DepthStencilOperationDescription { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Decrement, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always } }; depthStenState = new DepthStencilState(DXDevice, depthStencilDesc); DXContext.OutputMerger.SetDepthStencilState(depthStenState, 1); var depthStencilViewDesc = new DepthStencilViewDescription { Format = Format.D24_UNorm_S8_UInt, Dimension = DepthStencilViewDimension.Texture2D, Texture2D = new DepthStencilViewDescription.Texture2DResource { MipSlice = 0 } }; depthStenView = new DepthStencilView(DXDevice, depthStenBuffer, depthStencilViewDesc); DXContext.OutputMerger.SetTargets(depthStenView, renderTarget); var rasterDesc = new RasterizerStateDescription { IsAntialiasedLineEnabled = false, CullMode = CullMode.Back, DepthBias = 0, DepthBiasClamp = .0f, IsDepthClipEnabled = true, FillMode = FillMode.Solid, IsFrontCounterClockwise = false, IsMultisampleEnabled = false, IsScissorEnabled = false, SlopeScaledDepthBias = .0f }; rasterState = new RasterizerState(DXDevice, rasterDesc); DXContext.Rasterizer.State = rasterState; DXContext.Rasterizer.SetViewport(0, 0, width, height); Projection = Matrix.PerspectiveFovLH((float) (Math.PI / 4), ((float) width) / height, screenNear, screenDepth); World = Matrix.Identity; Ortho = Matrix.OrthoLH(width, height, screenNear, screenDepth); OnCleanup += swapChain.Dispose; OnCleanup += rasterState.Dispose; OnCleanup += depthStenBuffer.Dispose; OnCleanup += depthStenState.Dispose; OnCleanup += depthStenView.Dispose; OnCleanup += renderTarget.Dispose; OnCleanup += DXContext.Dispose; OnCleanup += DXDevice.Dispose; }
internal override void Cleanup() { base.Cleanup(); DSV = null; DefaultRasterizer = null; }
/// <summary> /// SetupRasterizerState /// </summary> void SetupRasterizerState () { var rsd = new RasterizerStateDescription(); if ( RasterizerState.CullMode == CullMode.CullNone ) { rsd.CullMode = D3DCullMode.None; rsd.IsFrontCounterClockwise = false; } else if ( RasterizerState.CullMode == CullMode.CullCW ) { rsd.CullMode = D3DCullMode.Front; rsd.IsFrontCounterClockwise = false; } else if ( RasterizerState.CullMode == CullMode.CullCCW ) { rsd.CullMode = D3DCullMode.Front; rsd.IsFrontCounterClockwise = true; } rsd.FillMode = Converter.Convert( RasterizerState.FillMode ); rsd.DepthBias = RasterizerState.DepthBias; rsd.DepthBiasClamp = 0; rsd.IsMultisampleEnabled = RasterizerState.MsaaEnabled; rsd.IsScissorEnabled = RasterizerState.ScissorEnabled; rsd.SlopeScaledDepthBias = RasterizerState.SlopeDepthBias; rsd.IsDepthClipEnabled = RasterizerState.DepthClipEnabled; rasterState = new D3DRasterizerState( device.Device, rsd ); }
private void initializeRasterizerStates() { standardRasterizerStates = new SharpDX.Direct3D11.RasterizerState[4]; RasterizerStateDescription templateDesc = new RasterizerStateDescription { FillMode = SharpDX.Direct3D11.FillMode.Solid, CullMode = SharpDX.Direct3D11.CullMode.Back, IsFrontCounterClockwise = false, DepthBias = 0, DepthBiasClamp = 0.0f, SlopeScaledDepthBias = 0.0f, IsDepthClipEnabled = true, IsScissorEnabled = false, IsMultisampleEnabled = true, IsAntialiasedLineEnabled = true }; templateDesc.CullMode = CullMode.None; standardRasterizerStates[(int)TriangleCullMode.Off] = new RasterizerState(device, templateDesc); templateDesc.CullMode = CullMode.Back; templateDesc.IsFrontCounterClockwise = true; standardRasterizerStates[(int)TriangleCullMode.CullClockwise] = new RasterizerState(device, templateDesc); templateDesc.CullMode = CullMode.Back; templateDesc.IsFrontCounterClockwise = false; standardRasterizerStates[(int)TriangleCullMode.CullCounterClockwise] = new RasterizerState(device, templateDesc); // Special rasterizer state with multisample off. Used for drawing anti-aliased lines without // MSAA, i.e. the lines are drawn with edge anti-aliasing. This produces better results on NVIDIA // GPUs, especially when alpha be templateDesc.CullMode = CullMode.None; templateDesc.IsMultisampleEnabled = false; standardRasterizerStates[3] = new RasterizerState(device, templateDesc); }
public void InitializeBuffers() { //Create back buffer Texture2D backBuffer = Resource.FromSwapChain<Texture2D>(SwapChain, 0); _renderTargetView = new RenderTargetView(Device, backBuffer); backBuffer.Dispose(); //Create the depth/stencil buffer var depthBufferDesc = new Texture2DDescription { Width = ConfigurationManager.Config.Width, Height = ConfigurationManager.Config.Height, MipLevels = 1, ArraySize = 1, Format = Format.D24_UNorm_S8_UInt, SampleDescription = ConfigurationManager.Config.AntiAliasing ? new SampleDescription(4, _maxQualityLevel-1) : new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }; _depthStencilBuffer = new Texture2D(Device, depthBufferDesc); DepthStencilStateDescription depthStencilDesc = new DepthStencilStateDescription { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less, IsStencilEnabled = true, StencilReadMask = 0xFF, StencilWriteMask = 0xFF, // Stencil operation if pixel front-facing. FrontFace = new DepthStencilOperationDescription { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Increment, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always }, // Stencil operation if pixel is back-facing. BackFace = new DepthStencilOperationDescription { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Decrement, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always } }; // Create the depth stencil state. _depthStencilState = new DepthStencilState(Device, depthStencilDesc); DepthStencilStateDescription depthDisabledStencilDesc = new DepthStencilStateDescription { IsDepthEnabled = false, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less, IsStencilEnabled = true, StencilReadMask = 0xFF, StencilWriteMask = 0xFF, // Stencil operation if pixel front-facing. FrontFace = new DepthStencilOperationDescription { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Increment, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always }, // Stencil operation if pixel is back-facing. BackFace = new DepthStencilOperationDescription { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Decrement, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always } }; _depthDisabledStencilState = new DepthStencilState(Device, depthDisabledStencilDesc); // Set the depth stencil state. _isZBufferEnabled = true; DeviceContext.OutputMerger.SetDepthStencilState(_depthStencilState, 1); // Initialize and set up the depth stencil view. DepthStencilViewDescription depthStencilViewDesc; if(ConfigurationManager.Config.AntiAliasing) depthStencilViewDesc = new DepthStencilViewDescription { Format = Format.D24_UNorm_S8_UInt, Dimension = DepthStencilViewDimension.Texture2DMultisampled, Texture2DMS = new DepthStencilViewDescription.Texture2DMultisampledResource() }; else depthStencilViewDesc = new DepthStencilViewDescription { Format = Format.D24_UNorm_S8_UInt, Dimension = DepthStencilViewDimension.Texture2D, Texture2D = new DepthStencilViewDescription.Texture2DResource() { MipSlice = 0 } }; // Create the depth stencil view. DepthStencilView = new DepthStencilView(Device, _depthStencilBuffer, depthStencilViewDesc); RenderToTextureDepthStencilView = new DepthStencilView(Device, new Texture2D(Device, new Texture2DDescription { Width = ConfigurationManager.Config.Width, Height = ConfigurationManager.Config.Height, MipLevels = 1, ArraySize = 1, Format = Format.D24_UNorm_S8_UInt, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }), new DepthStencilViewDescription { Format = Format.D24_UNorm_S8_UInt, Dimension = DepthStencilViewDimension.Texture2D, Texture2D = new DepthStencilViewDescription.Texture2DResource() { MipSlice = 0 } }); // Bind the render target view and depth stencil buffer to the output render pipeline. DeviceContext.OutputMerger.SetTargets(DepthStencilView, _renderTargetView); // Setup the raster description which will determine how and what polygon will be drawn. var rasterDesc = new RasterizerStateDescription { IsAntialiasedLineEnabled = false, CullMode = CullMode.Back, DepthBias = 0, DepthBiasClamp = .0f, IsDepthClipEnabled = true, FillMode = FillMode.Solid, IsFrontCounterClockwise = false, IsMultisampleEnabled = false, IsScissorEnabled = false, SlopeScaledDepthBias = .0f }; // Create the rasterizer state from the description we just filled out. _rasterStateSolid = new RasterizerState(Device, rasterDesc); rasterDesc.FillMode = FillMode.Wireframe; _rasterStateWireFrame = new RasterizerState(Device, rasterDesc); // Now set the rasterizer state. DeviceContext.Rasterizer.State = _rasterStateSolid; // Setup and create the viewport for rendering. DeviceContext.Rasterizer.SetViewport(0, 0, ConfigurationManager.Config.Width, ConfigurationManager.Config.Height, 0, 1); var blendStateDescription = new BlendStateDescription(); blendStateDescription.RenderTarget[0].IsBlendEnabled = true; blendStateDescription.RenderTarget[0].SourceBlend = BlendOption.SourceAlpha; blendStateDescription.RenderTarget[0].DestinationBlend = BlendOption.InverseSourceAlpha; blendStateDescription.RenderTarget[0].BlendOperation = BlendOperation.Add; blendStateDescription.RenderTarget[0].SourceAlphaBlend = BlendOption.One; blendStateDescription.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero; blendStateDescription.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add; blendStateDescription.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; // Create the blend state using the description. _alphaEnabledBlendState = new BlendState(Device, blendStateDescription); blendStateDescription.RenderTarget[0].IsBlendEnabled = false; // Create the blend state using the description. _alphaDisabledBlendState = new BlendState(Device, blendStateDescription); }
protected RasterizerState CullClockwise(DxDevice device) { return cullClockwise ?? (cullClockwise = new RasterizerState(device, GetRasterizer(CullMode.Back))); }
public void Initialize() { Form.SizeChanged += (o, args) => { if (_swapChain == null) return; renderView.Dispose(); depthView.Dispose(); DisposeBuffers(); if (Form.WindowState == FormWindowState.Minimized) return; Width = Form.ClientSize.Width; Height = Form.ClientSize.Height; _swapChain.ResizeBuffers(_swapChain.Description.BufferCount, 0, 0, Format.Unknown, 0); CreateBuffers(); SetSceneConstants(); }; Width = 1024; Height = 768; NearPlane = 1.0f; FarPlane = 200.0f; FieldOfView = (float)Math.PI / 4; try { OnInitializeDevice(); } catch (Exception e) { MessageBox.Show(e.ToString(), "Could not create DirectX 11 device."); return; } // shader.fx const ShaderFlags shaderFlags = ShaderFlags.None; //const ShaderFlags shaderFlags = ShaderFlags.Debug | ShaderFlags.SkipOptimization; string[] sources = new[] { "shader.fx", "grender.fx" }; using (var shaderByteCode = ShaderLoader.FromResource(Assembly.GetExecutingAssembly(), sources, shaderFlags)) { effect = new Effect(_device, shaderByteCode); } EffectTechnique technique = effect.GetTechniqueByName("GBufferCreate"); shadowGenPass = technique.GetPassByName("ShadowMap"); gBufferGenPass = technique.GetPassByName("GBufferGen"); debugDrawPass = technique.GetPassByName("DebugDraw"); BufferDescription sceneConstantsDesc = new BufferDescription() { SizeInBytes = Marshal.SizeOf(typeof(ShaderSceneConstants)), Usage = ResourceUsage.Dynamic, BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None }; sceneConstantsBuffer = new Buffer(_device, sceneConstantsDesc); EffectConstantBuffer effectConstantBuffer = effect.GetConstantBufferByName("scene"); effectConstantBuffer.SetConstantBuffer(sceneConstantsBuffer); RasterizerStateDescription _rasterizerStateDesc = new RasterizerStateDescription() { CullMode = CullMode.None, FillMode = FillMode.Solid, DepthBias = 0, DepthBiasClamp = 0, SlopeScaledDepthBias = 0, IsDepthClipEnabled = true, }; noCullState = new RasterizerState(_device, _rasterizerStateDesc); _rasterizerStateDesc.CullMode = CullMode.Back; backCullState = new RasterizerState(_device, _rasterizerStateDesc); _rasterizerStateDesc.CullMode = CullMode.Front; frontCullState = new RasterizerState(_device, _rasterizerStateDesc); _immediateContext.Rasterizer.State = CullingEnabled ? backCullState : noCullState; DepthStencilStateDescription depthDesc = new DepthStencilStateDescription() { IsDepthEnabled = true, IsStencilEnabled = false, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less }; depthState = new DepthStencilState(_device, depthDesc); depthDesc.DepthWriteMask = DepthWriteMask.Zero; outsideLightVolumeDepthState = new DepthStencilState(_device, depthDesc); depthDesc.DepthComparison = Comparison.Greater; insideLightVolumeDepthState = new DepthStencilState(_device, depthDesc); DepthStencilStateDescription lightDepthStateDesc = new DepthStencilStateDescription() { IsDepthEnabled = true, IsStencilEnabled = false, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less }; lightDepthStencilState = new DepthStencilState(_device, lightDepthStateDesc); // grender.fx technique = effect.GetTechniqueByName("DeferredShader"); gBufferRenderPass = technique.GetPassByName("DeferredShader"); gBufferPostProcessPass = technique.GetPassByName("Blur"); gBufferPostProcessPass2 = technique.GetPassByName("PostProcess"); gBufferOverlayPass = technique.GetPassByName("Overlay"); lightBufferVar = effect.GetVariableByName("lightBuffer").AsShaderResource(); normalBufferVar = effect.GetVariableByName("normalBuffer").AsShaderResource(); diffuseBufferVar = effect.GetVariableByName("diffuseBuffer").AsShaderResource(); depthMapVar = effect.GetVariableByName("depthMap").AsShaderResource(); shadowLightDepthBufferVar = effect.GetVariableByName("lightDepthMap").AsShaderResource(); sunLightDirectionVar = effect.GetVariableByName("SunLightDirection").AsVector(); viewportWidthVar = effect.GetVariableByName("ViewportWidth").AsScalar(); viewportHeightVar = effect.GetVariableByName("ViewportHeight").AsScalar(); viewParametersVar = effect.GetVariableByName("ViewParameters").AsVector(); overlayViewProjectionVar = effect.GetVariableByName("OverlayViewProjection").AsMatrix(); // light.fx using (var shaderByteCode = ShaderLoader.FromResource(Assembly.GetExecutingAssembly(), "light.fx", shaderFlags)) { lightShader = new Effect(_device, shaderByteCode); } technique = lightShader.GetTechniqueByIndex(0); lightAccumulationPass = technique.GetPassByName("Light"); lightWorldVar = lightShader.GetVariableByName("World").AsMatrix(); lightPositionRadiusVar = lightShader.GetVariableByName("PositionRadius").AsVector(); lightColorVar = lightShader.GetVariableByName("Color").AsVector(); lightProjectionVar = lightShader.GetVariableByName("Projection").AsMatrix(); lightViewVar = lightShader.GetVariableByName("View").AsMatrix(); lightViewInverseVar = lightShader.GetVariableByName("ViewInverse").AsMatrix(); lightViewportWidthVar = lightShader.GetVariableByName("ViewportWidth").AsScalar(); lightViewportHeightVar = lightShader.GetVariableByName("ViewportHeight").AsScalar(); lightEyePositionVar = lightShader.GetVariableByName("EyePosition").AsVector(); lightViewParametersVar = lightShader.GetVariableByName("ViewParameters").AsVector(); InputElement[] elements = new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0), }; lightVolumeInputLayout = new InputLayout(Device, lightShader.GetTechniqueByIndex(0).GetPassByName("Light").Description.Signature, elements); pointLightVolumeVertices = Light.CreatePointLightVolume(out pointLightVolumeIndices); BufferDescription vertexBufferDesc = new BufferDescription() { SizeInBytes = Vector3.SizeInBytes * pointLightVolumeVertices.Length, Usage = ResourceUsage.Default, BindFlags = BindFlags.VertexBuffer, }; using (var data = new SharpDX.DataStream(vertexBufferDesc.SizeInBytes, false, true)) { data.WriteRange(pointLightVolumeVertices); data.Position = 0; pointLightVolumeVertexBuffer = new Buffer(Device, data, vertexBufferDesc); } pointLightVolumeVertexBufferBinding = new VertexBufferBinding(pointLightVolumeVertexBuffer, 12, 0); BufferDescription indexBufferDesc = new BufferDescription() { SizeInBytes = sizeof(uint) * pointLightVolumeIndices.Length, Usage = ResourceUsage.Default, BindFlags = BindFlags.IndexBuffer }; using (var data = new SharpDX.DataStream(indexBufferDesc.SizeInBytes, false, true)) { data.WriteRange(pointLightVolumeIndices); data.Position = 0; pointLightVolumeIndexBuffer = new Buffer(Device, data, indexBufferDesc); } lightDepthBufferVar = lightShader.GetVariableByName("depthBuffer").AsShaderResource(); lightNormalBufferVar = lightShader.GetVariableByName("normalBuffer").AsShaderResource(); lights.Add(new Light(pointLightPosition, 60, new Vector4(1, 0.95f, 0.9f, 1))); //lights.Add(new Light(pointLightPosition, 60, new Vector4(0, 0, 1, 1))); //lights.Add(new Light(new Vector3(-10, 10, 10), 30, new Vector4(1, 0, 0, 1))); //lights.Add(new Light(new Vector3(10, 5, -10), 20, new Vector4(0, 1, 0, 1))); //lights.Add(new Light(new Vector3(-10, 5, -10), 20, new Vector4(1, 0, 1, 1))); Info = new InfoText(_device, 256, 256); _meshFactory = new MeshFactory(this); CreateBuffers(); }
private void InitializeInternal(Device device) { Debug.Assert(device != null); var wfDesc = new RasterizerStateDescription { FillMode = FillMode.Wireframe, CullMode = CullMode.Back, IsFrontCounterClockwise = false, IsDepthClipEnabled = true }; _wireframeRs = new RasterizerState(device, wfDesc); var noCullDesc = new RasterizerStateDescription { FillMode = FillMode.Solid, CullMode = CullMode.None, IsFrontCounterClockwise = false, IsDepthClipEnabled = true }; _noCullRs = new RasterizerState(device, noCullDesc); var cullClockwiseDesc = new RasterizerStateDescription { FillMode = FillMode.Solid, CullMode = CullMode.Back, IsFrontCounterClockwise = true, IsDepthClipEnabled = true }; _cullClockwiseRs = new RasterizerState(device, cullClockwiseDesc); var atcDesc = new BlendStateDescription { AlphaToCoverageEnable = true, IndependentBlendEnable = false, }; atcDesc.RenderTarget[0].IsBlendEnabled = false; atcDesc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; _alphaToCoverageBs = new BlendState(device, atcDesc); var transDesc = new BlendStateDescription { AlphaToCoverageEnable = false, IndependentBlendEnable = false }; transDesc.RenderTarget[0].IsBlendEnabled = true; transDesc.RenderTarget[0].SourceBlend = BlendOption.SourceAlpha; transDesc.RenderTarget[0].DestinationBlend = BlendOption.InverseSourceAlpha; transDesc.RenderTarget[0].BlendOperation = BlendOperation.Add; transDesc.RenderTarget[0].SourceAlphaBlend = BlendOption.One; transDesc.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero; transDesc.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add; transDesc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; _transparentBs = new BlendState(device, transDesc); var noRenderTargetWritesDesc = new BlendStateDescription { AlphaToCoverageEnable = false, IndependentBlendEnable = false }; noRenderTargetWritesDesc.RenderTarget[0].IsBlendEnabled = false; noRenderTargetWritesDesc.RenderTarget[0].SourceBlend = BlendOption.One; noRenderTargetWritesDesc.RenderTarget[0].DestinationBlend = BlendOption.Zero; noRenderTargetWritesDesc.RenderTarget[0].BlendOperation = BlendOperation.Add; noRenderTargetWritesDesc.RenderTarget[0].SourceAlphaBlend = BlendOption.One; noRenderTargetWritesDesc.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero; noRenderTargetWritesDesc.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add; noRenderTargetWritesDesc.RenderTarget[0].RenderTargetWriteMask = 0; _noRenderTargetWritesBs = new BlendState(device, noRenderTargetWritesDesc); var mirrorDesc = new DepthStencilStateDescription { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.Zero, DepthComparison = Comparison.Less, IsStencilEnabled = true, StencilReadMask = 0xff, StencilWriteMask = 0xff, FrontFace = new DepthStencilOperationDescription { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Keep, PassOperation = StencilOperation.Replace, Comparison = Comparison.Always }, BackFace = new DepthStencilOperationDescription { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Keep, PassOperation = StencilOperation.Replace, Comparison = Comparison.Always } }; _markMirrorDss = new DepthStencilState(device, mirrorDesc); var drawReflectionDesc = new DepthStencilStateDescription { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less, IsStencilEnabled = true, StencilReadMask = 0xff, StencilWriteMask = 0xff, FrontFace = new DepthStencilOperationDescription { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Keep, PassOperation = StencilOperation.Keep, Comparison = Comparison.Equal }, BackFace = new DepthStencilOperationDescription { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Keep, PassOperation = StencilOperation.Keep, Comparison = Comparison.Equal } }; _drawReflectionDss = new DepthStencilState(device, drawReflectionDesc); var noDoubleBlendDesc = new DepthStencilStateDescription { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less, IsStencilEnabled = true, StencilReadMask = 0xff, StencilWriteMask = 0xff, FrontFace = new DepthStencilOperationDescription { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Keep, PassOperation = StencilOperation.Increment, Comparison = Comparison.Equal }, BackFace = new DepthStencilOperationDescription { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Keep, PassOperation = StencilOperation.Increment, Comparison = Comparison.Equal } }; _noDoubleBlendDss = new DepthStencilState(device, noDoubleBlendDesc); var lessEqualDesc = new DepthStencilStateDescription { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.LessEqual, IsStencilEnabled = false }; _lessEqualDss = new DepthStencilState(device, lessEqualDesc); var equalsDesc = new DepthStencilStateDescription() { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.Zero, DepthComparison = Comparison.LessEqual, }; _equalsDss = new DepthStencilState(device, equalsDesc); var noDepthDesc = new DepthStencilStateDescription() { IsDepthEnabled = false, DepthComparison = Comparison.Always, DepthWriteMask = DepthWriteMask.Zero }; _noDepthDss = new DepthStencilState(device, noDepthDesc); }
protected override void CreateDeviceDependentResources() { RemoveAndDispose(ref vertexShader); RemoveAndDispose(ref lightBuffer); RemoveAndDispose(ref RTV); RemoveAndDispose(ref SRV); RemoveAndDispose(ref rsCullBack); RemoveAndDispose(ref rsCullFront); RemoveAndDispose(ref rsWireframe); RemoveAndDispose(ref blendStateAdd); RemoveAndDispose(ref depthLessThan); RemoveAndDispose(ref depthGreaterThan); RemoveAndDispose(ref depthDisabled); RemoveAndDispose(ref perLightBuffer); RemoveAndDispose(ref psAmbientLight); RemoveAndDispose(ref psDirectionalLight); RemoveAndDispose(ref psPointLight); RemoveAndDispose(ref psSpotLight); RemoveAndDispose(ref psDebugLight); RemoveAndDispose(ref perLightBuffer); // Retrieve our SharpDX.Direct3D11.Device1 instance var device = this.DeviceManager.Direct3DDevice; int width, height; SampleDescription sampleDesc; // Retrieve DSV from GBuffer and extract width/height // then create a new read-only DSV using (var depthTexture = gbuffer.DSV.ResourceAs<Texture2D>()) { width = depthTexture.Description.Width; height = depthTexture.Description.Height; sampleDesc = depthTexture.Description.SampleDescription; // Initialize read-only DSV var dsvDesc = gbuffer.DSV.Description; dsvDesc.Flags = DepthStencilViewFlags.ReadOnlyDepth | DepthStencilViewFlags.ReadOnlyStencil; DSVReadonly = ToDispose(new DepthStencilView(device, depthTexture, dsvDesc)); } // Check if GBuffer is multi-sampled bool isMSAA = sampleDesc.Count > 1; // Initialize the light render target var texDesc = new Texture2DDescription(); texDesc.BindFlags = BindFlags.ShaderResource | BindFlags.RenderTarget; texDesc.ArraySize = 1; texDesc.CpuAccessFlags = CpuAccessFlags.None; texDesc.Usage = ResourceUsage.Default; texDesc.Width = width; texDesc.Height = height; texDesc.MipLevels = 1; // No mip levels texDesc.SampleDescription = sampleDesc; texDesc.Format = Format.R8G8B8A8_UNorm; lightBuffer = ToDispose(new Texture2D(device, texDesc)); // Render Target View description var rtvDesc = new RenderTargetViewDescription(); rtvDesc.Format = Format.R8G8B8A8_UNorm; rtvDesc.Dimension = isMSAA ? RenderTargetViewDimension.Texture2DMultisampled : RenderTargetViewDimension.Texture2D; rtvDesc.Texture2D.MipSlice = 0; RTV = ToDispose(new RenderTargetView(device, lightBuffer, rtvDesc)); // SRV description for render targets var srvDesc = new ShaderResourceViewDescription(); srvDesc.Format = Format.R8G8B8A8_UNorm; srvDesc.Dimension = isMSAA ? SharpDX.Direct3D.ShaderResourceViewDimension.Texture2DMultisampled : SharpDX.Direct3D.ShaderResourceViewDimension.Texture2D; srvDesc.Texture2D.MipLevels = -1; srvDesc.Texture2D.MostDetailedMip = 0; SRV = ToDispose(new ShaderResourceView(device, lightBuffer, srvDesc)); // Initialize additive blend state (assuming single render target) BlendStateDescription bsDesc = new BlendStateDescription(); bsDesc.RenderTarget[0].IsBlendEnabled = true; bsDesc.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add; bsDesc.RenderTarget[0].SourceAlphaBlend = BlendOption.One; bsDesc.RenderTarget[0].DestinationAlphaBlend = BlendOption.One; bsDesc.RenderTarget[0].BlendOperation = BlendOperation.Add; bsDesc.RenderTarget[0].SourceBlend = BlendOption.One; bsDesc.RenderTarget[0].DestinationBlend = BlendOption.One; bsDesc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; blendStateAdd = ToDispose(new BlendState(device, bsDesc)); // Initialize rasterizer states RasterizerStateDescription rsDesc = new RasterizerStateDescription(); rsDesc.FillMode = FillMode.Solid; rsDesc.CullMode = CullMode.Back; rsCullBack = ToDispose(new RasterizerState(device, rsDesc)); rsDesc.CullMode = CullMode.Front; rsCullFront = ToDispose(new RasterizerState(device, rsDesc)); rsDesc.CullMode = CullMode.Front; rsDesc.FillMode = FillMode.Wireframe; rsWireframe = ToDispose(new RasterizerState(device, rsDesc)); // Initialize depth state var dsDesc = new DepthStencilStateDescription(); dsDesc.IsStencilEnabled = false; dsDesc.IsDepthEnabled = true; // Less-than depth comparison dsDesc.DepthComparison = Comparison.Less; depthLessThan = ToDispose(new DepthStencilState(device, dsDesc)); // Greater-than depth comparison dsDesc.DepthComparison = Comparison.Greater; depthGreaterThan = ToDispose(new DepthStencilState(device, dsDesc)); // Depth/stencil testing disabled dsDesc.IsDepthEnabled = false; depthDisabled = ToDispose(new DepthStencilState(device, dsDesc)); // Buffer to light parameters perLightBuffer = ToDispose(new Buffer(device, Utilities.SizeOf<PerLight>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0)); if (isMSAA) { // Compile and create the vertex shader using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\LightsMS.hlsl", "VSLight", "vs_5_0")) vertexShader = ToDispose(new VertexShader(device, bytecode)); // Compile pixel shaders using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\LightsMS.hlsl", "PSAmbientLight", "ps_5_0")) psAmbientLight = ToDispose(new PixelShader(device, bytecode)); using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\LightsMS.hlsl", "PSDirectionalLight", "ps_5_0")) psDirectionalLight = ToDispose(new PixelShader(device, bytecode)); using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\LightsMS.hlsl", "PSPointLight", "ps_5_0")) psPointLight = ToDispose(new PixelShader(device, bytecode)); using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\LightsMS.hlsl", "PSSpotLight", "ps_5_0")) psSpotLight = ToDispose(new PixelShader(device, bytecode)); using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\LightsMS.hlsl", "PSDebugLight", "ps_5_0")) psDebugLight = ToDispose(new PixelShader(device, bytecode)); } else { // Compile and create the vertex shader using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\Lights.hlsl", "VSLight", "vs_5_0")) vertexShader = ToDispose(new VertexShader(device, bytecode)); // Compile pixel shaders using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\Lights.hlsl", "PSAmbientLight", "ps_5_0")) psAmbientLight = ToDispose(new PixelShader(device, bytecode)); using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\Lights.hlsl", "PSDirectionalLight", "ps_5_0")) psDirectionalLight = ToDispose(new PixelShader(device, bytecode)); using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\Lights.hlsl", "PSPointLight", "ps_5_0")) psPointLight = ToDispose(new PixelShader(device, bytecode)); using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\Lights.hlsl", "PSSpotLight", "ps_5_0")) psSpotLight = ToDispose(new PixelShader(device, bytecode)); using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\Lights.hlsl", "PSDebugLight", "ps_5_0")) psDebugLight = ToDispose(new PixelShader(device, bytecode)); } }
/// <summary> /// Initializes the depth buffer, depth stencil /// state, rasterizer state, for rendering. /// </summary> private void InitializeResources(Size resolution) { if (depthStencilState != null) depthStencilState.Dispose(); if ( depthStencilView != null) depthStencilView.Dispose(); if ( rasterizerState != null) rasterizerState.Dispose(); if ( cameraBuffer != null) cameraBuffer.Dispose(); if ( depthBuffer != null) depthBuffer.Dispose(); depthStencilState = new DepthStencilState(Device, new DepthStencilStateDescription { IsDepthEnabled = true, IsStencilEnabled = false, DepthComparison = Comparison.Less, DepthWriteMask = DepthWriteMask.All, }); depthBuffer = new Texture2D(Device, new Texture2DDescription { MipLevels = 1, ArraySize = 1, Width = resolution.Width, Height = resolution.Height, Format = Format.D32_Float, Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, SampleDescription = Settings.MultisamplingOptions, }); depthStencilView = new DepthStencilView(Device, depthBuffer); rasterizerState = new RasterizerState(Device, new RasterizerStateDescription() { FillMode = FillMode.Solid, CullMode = CullMode.None, }); cameraBuffer = new Buffer(Device, new BufferDescription() { SizeInBytes = Camera.Size(), Usage = ResourceUsage.Dynamic, BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, }); }
internal void Clear() { if (m_VBs == null) { m_VBs = new Buffer[8]; m_strides = new int[8]; m_CBs = new Buffer[8]; m_bindings = new SortedDictionary<int, MyBinding>(); m_srvBindings = new SortedSet<Tuple<int, int>>(); m_RTVs = new RenderTargetView[8]; m_SRVs = new ShaderResourceView[8]; m_constantsVersion = new Dictionary<Buffer, int>(); m_constantBindings = new Dictionary<MyStageBinding, Buffer>(); m_srvTableBindings = new Dictionary<MyStageSrvBinding, int>(); m_srvBindings1 = new List<MyStageSrvBinding>(); } m_IB = null; m_inputLayout = null; m_ps = null; m_vs = null; m_gs = null; m_RS = null; m_BS = null; m_DS = null; m_stencilRef = 0; Array.Clear(m_VBs, 0, m_VBs.Length); Array.Clear(m_CBs, 0, m_CBs.Length); m_bindings.Clear(); m_srvBindings.Clear(); m_constantsVersion.Clear(); m_constantBindings.Clear(); m_srvTableBindings.Clear(); m_srvBindings1.Clear(); }
void mediaEngine_PlaybackEvent(MediaEngineEvent mediaEvent, long param1, int param2) { if (mediaEvent == MediaEngineEvent.CanPlay) { if (this.mediaEngine.Error != null) { int a = 0; } if (this.mediaEngine.HasVideo()) { int width = 0; int height = 0; this.mediaEngine.GetNativeVideoSize(out width, out height); this.texture = new SharpDX.Direct3D11.Texture2D(this.context.D3DDevice, new SharpDX.Direct3D11.Texture2DDescription() { ArraySize = 1, Width = width, Height = height, Usage = SharpDX.Direct3D11.ResourceUsage.Default, Format = Format.B8G8R8A8_UNorm, CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.None, BindFlags = SharpDX.Direct3D11.BindFlags.RenderTarget | SharpDX.Direct3D11.BindFlags.ShaderResource, OptionFlags = SharpDX.Direct3D11.ResourceOptionFlags.None, SampleDescription = new SampleDescription(1, 0), MipLevels = 1, }); this.dxgiSurface = this.texture.QueryInterface<SharpDX.DXGI.Surface>(); this.textureView = new ShaderResourceView(this.context.D3DDevice, this.texture); ready = true; this.mediaEngine.Play(); } state = new RasterizerState(this.context.D3DDevice, new RasterizerStateDescription() { CullMode = CullMode.Back, FillMode = FillMode.Solid, DepthBias = 0, DepthBiasClamp = 0, IsDepthClipEnabled = true, IsMultisampleEnabled = true, SlopeScaledDepthBias = 0 }); } }
internal void SetRS(RasterizerState rs) { if (State.m_RS != rs) { State.m_RS = rs; Context.Rasterizer.State = rs; Stats.SetRasterizerState++; } }
internal void SetRasterizerState(RasterizerState rs) { if (rs == m_rasterizerState) return; m_rasterizerState = rs; m_deviceContext.Rasterizer.State = m_rasterizerState; m_statistics.SetRasterizerStates++; }
public Renderer(Game game, SharpDX.Windows.RenderForm renderForm) { this.game = game; int width = renderForm.ClientSize.Width, height = renderForm.ClientSize.Height; ResolutionX = width; ResolutionY = height; #region 3d device & context D3D11.DeviceCreationFlags creationFlags = D3D11.DeviceCreationFlags.BgraSupport; #if DEBUG creationFlags |= D3D11.DeviceCreationFlags.Debug; #endif DXGI.SwapChainDescription swapChainDesc = new DXGI.SwapChainDescription() { ModeDescription = new DXGI.ModeDescription(width, height, new DXGI.Rational(60, 1), DXGI.Format.R8G8B8A8_UNorm), SampleDescription = new DXGI.SampleDescription(SampleCount, SampleQuality), Usage = DXGI.Usage.RenderTargetOutput, BufferCount = 1, OutputHandle = renderForm.Handle, IsWindowed = true, SwapEffect = DXGI.SwapEffect.Discard }; D3D11.Device device; D3D11.Device.CreateWithSwapChain(DriverType.Hardware, creationFlags, swapChainDesc, out device, out swapChain); Device = device; Context = Device.ImmediateContext; #endregion #region 2d device & context DXGI.Device dxgiDevice = Device.QueryInterface <D3D11.Device1>().QueryInterface <DXGI.Device2>(); D2DDevice = new D2D1.Device(dxgiDevice); D2DContext = new D2D1.DeviceContext(D2DDevice, D2D1.DeviceContextOptions.None); D2DFactory = D2DDevice.Factory; #endregion #region 2d brushes/fonts Brushes = new Dictionary <string, D2D1.Brush>(); Brushes.Add("Red", new D2D1.SolidColorBrush(D2DContext, Color.Red)); Brushes.Add("Green", new D2D1.SolidColorBrush(D2DContext, Color.Green)); Brushes.Add("Blue", new D2D1.SolidColorBrush(D2DContext, Color.Blue)); Brushes.Add("White", new D2D1.SolidColorBrush(D2DContext, Color.White)); Brushes.Add("Black", new D2D1.SolidColorBrush(D2DContext, Color.Black)); Brushes.Add("TransparentWhite", new D2D1.SolidColorBrush(D2DContext, new Color(1, 1, 1, .5f))); Brushes.Add("TransparentBlack", new D2D1.SolidColorBrush(D2DContext, new Color(0, 0, 0, .5f))); Brushes.Add("LightGray", new D2D1.SolidColorBrush(D2DContext, Color.LightGray)); Brushes.Add("OrangeRed", new D2D1.SolidColorBrush(D2DContext, Color.OrangeRed)); Brushes.Add("CornflowerBlue", new D2D1.SolidColorBrush(D2DContext, Color.CornflowerBlue)); Brushes.Add("Yellow", new D2D1.SolidColorBrush(D2DContext, Color.Yellow)); Brushes.Add("Magenta", new D2D1.SolidColorBrush(D2DContext, Color.Magenta)); Brushes.Add("RosyBrown", new D2D1.SolidColorBrush(D2DContext, Color.RosyBrown)); DashStyle = new D2D1.StrokeStyle(D2DFactory, new D2D1.StrokeStyleProperties() { StartCap = D2D1.CapStyle.Flat, DashCap = D2D1.CapStyle.Round, EndCap = D2D1.CapStyle.Flat, DashStyle = D2D1.DashStyle.Custom, DashOffset = 0, LineJoin = D2D1.LineJoin.Round, MiterLimit = 1 }, new float[] { 4f, 4f }); FontFactory = new DWrite.Factory(); SegoeUI24 = new DWrite.TextFormat(FontFactory, "Segoe UI", 24f); SegoeUI14 = new DWrite.TextFormat(FontFactory, "Segoe UI", 14f); Consolas14 = new DWrite.TextFormat(FontFactory, "Consolas", 14f); #endregion #region blend states D3D11.BlendStateDescription opaqueDesc = new D3D11.BlendStateDescription(); opaqueDesc.RenderTarget[0].IsBlendEnabled = false; opaqueDesc.RenderTarget[0].RenderTargetWriteMask = D3D11.ColorWriteMaskFlags.All; blendStateOpaque = new D3D11.BlendState(Device, opaqueDesc); D3D11.BlendStateDescription alphaDesc = new D3D11.BlendStateDescription(); alphaDesc.RenderTarget[0].IsBlendEnabled = true; alphaDesc.RenderTarget[0].SourceBlend = D3D11.BlendOption.SourceAlpha; alphaDesc.RenderTarget[0].DestinationBlend = D3D11.BlendOption.InverseSourceAlpha; alphaDesc.RenderTarget[0].BlendOperation = D3D11.BlendOperation.Add; alphaDesc.RenderTarget[0].SourceAlphaBlend = D3D11.BlendOption.One; alphaDesc.RenderTarget[0].DestinationAlphaBlend = D3D11.BlendOption.Zero; alphaDesc.RenderTarget[0].AlphaBlendOperation = D3D11.BlendOperation.Add; alphaDesc.RenderTarget[0].RenderTargetWriteMask = D3D11.ColorWriteMaskFlags.All; blendStateTransparent = new D3D11.BlendState(Device, alphaDesc); #endregion #region rasterizer states rasterizerStateSolidCullBack = new D3D11.RasterizerState(Device, new D3D11.RasterizerStateDescription() { FillMode = D3D11.FillMode.Solid, CullMode = D3D11.CullMode.Back, IsAntialiasedLineEnabled = true, IsDepthClipEnabled = false, IsMultisampleEnabled = true }); rasterizerStateWireframeCullBack = new D3D11.RasterizerState(Device, new D3D11.RasterizerStateDescription() { FillMode = D3D11.FillMode.Wireframe, CullMode = D3D11.CullMode.Back, IsAntialiasedLineEnabled = true, IsDepthClipEnabled = false, IsMultisampleEnabled = true }); rasterizerStateSolidNoCull = new D3D11.RasterizerState(Device, new D3D11.RasterizerStateDescription() { FillMode = D3D11.FillMode.Solid, CullMode = D3D11.CullMode.None, IsAntialiasedLineEnabled = true, IsDepthClipEnabled = false, IsMultisampleEnabled = true }); rasterizerStateWireframeNoCull = new D3D11.RasterizerState(Device, new D3D11.RasterizerStateDescription() { FillMode = D3D11.FillMode.Wireframe, CullMode = D3D11.CullMode.None, IsAntialiasedLineEnabled = true, IsDepthClipEnabled = false, IsMultisampleEnabled = true }); rasterizerStateSolidCullFront = new D3D11.RasterizerState(Device, new D3D11.RasterizerStateDescription() { FillMode = D3D11.FillMode.Solid, CullMode = D3D11.CullMode.Front, IsAntialiasedLineEnabled = true, IsDepthClipEnabled = false, IsMultisampleEnabled = true }); rasterizerStateWireframeCullFront = new D3D11.RasterizerState(Device, new D3D11.RasterizerStateDescription() { FillMode = D3D11.FillMode.Wireframe, CullMode = D3D11.CullMode.Front, IsAntialiasedLineEnabled = true, IsDepthClipEnabled = false, IsMultisampleEnabled = true }); #endregion #region depth stencil states depthStencilStateDefault = new D3D11.DepthStencilState(Device, new D3D11.DepthStencilStateDescription() { IsDepthEnabled = true, IsStencilEnabled = false, DepthComparison = D3D11.Comparison.Less, DepthWriteMask = D3D11.DepthWriteMask.All }); depthStencilStateNoDepth = new D3D11.DepthStencilState(Device, new D3D11.DepthStencilStateDescription() { IsDepthEnabled = false, IsStencilEnabled = false, DepthComparison = D3D11.Comparison.Less, DepthWriteMask = D3D11.DepthWriteMask.All }); Context.OutputMerger.SetDepthStencilState(depthStencilStateDefault); #endregion #region blank textures D3D11.Texture2D wtex = new D3D11.Texture2D(Device, new D3D11.Texture2DDescription() { ArraySize = 1, Width = 1, Height = 1, Format = DXGI.Format.R32G32B32A32_Float, CpuAccessFlags = D3D11.CpuAccessFlags.None, MipLevels = 0, Usage = D3D11.ResourceUsage.Default, SampleDescription = new DXGI.SampleDescription(1, 0), BindFlags = D3D11.BindFlags.ShaderResource, OptionFlags = D3D11.ResourceOptionFlags.None }); Context.UpdateSubresource(new Vector4[] { Vector4.One }, wtex); WhiteTextureView = new D3D11.ShaderResourceView(Device, wtex); D3D11.Texture2D btex = new D3D11.Texture2D(Device, new D3D11.Texture2DDescription() { ArraySize = 1, Width = 1, Height = 1, Format = DXGI.Format.R32G32B32A32_Float, CpuAccessFlags = D3D11.CpuAccessFlags.None, MipLevels = 0, Usage = D3D11.ResourceUsage.Default, SampleDescription = new DXGI.SampleDescription(1, 0), BindFlags = D3D11.BindFlags.ShaderResource, OptionFlags = D3D11.ResourceOptionFlags.None }); Context.UpdateSubresource(new Vector4[] { new Vector4(0, 0, 0, 1) }, btex); BlackTextureView = new D3D11.ShaderResourceView(Device, btex); AnisotropicSampler = new D3D11.SamplerState(Device, new D3D11.SamplerStateDescription() { AddressU = D3D11.TextureAddressMode.Wrap, AddressV = D3D11.TextureAddressMode.Wrap, AddressW = D3D11.TextureAddressMode.Wrap, Filter = D3D11.Filter.Anisotropic, }); #endregion #region screen vertex & constants constants = new CameraConstants(); constantBuffer = D3D11.Buffer.Create(Device, D3D11.BindFlags.ConstantBuffer, ref constants); #endregion //swapChain.GetParent<DXGI.Factory>().MakeWindowAssociation(renderForm.Handle, DXGI.WindowAssociationFlags.); Cameras = new List <Camera>(); MainCamera = Camera.CreatePerspective(MathUtil.DegreesToRadians(70), 16 / 9f); ActiveCamera = MainCamera; Cameras.Add(MainCamera); ShadowCamera = Camera.CreateOrthographic(500, 1); ShadowCamera.zNear = 0; ShadowCamera.zFar = 1000; ShadowCamera.CreateResources(Device, 1, 0, 1024, 1024); //Cameras.Add(ShadowCamera); // TODO: Shadow camera has no depth Resize(ResolutionX, ResolutionY); }
private void Run() { var window = new TesselationParameterForm(); window.Show(); var deviceManager = new DeviceManager(); deviceManager.Initialize(deviceCreationFlags: DeviceCreationFlags.Debug); var settings = new RenderFormSettings(800, 600, false, false, "hello!", WindowAssociationFlags.IgnoreAll); var renderWindow = new PresentationWindow(settings); renderWindow.SwapChain = deviceManager.CreateSwapChainForWindow(renderWindow.Handle, settings); var rtCreationSettings = new RenderTarget.Configuration.CreationSettings( new Size(settings.Width, settings.Height), true, new SampleDescription(1, 0), RenderTarget.Configuration.RenderTargetClearSettings.Default, RenderTarget.Configuration.DepthStencilClearSettings.Default); var renderTarget = deviceManager.RenderTargetManager.CreateRenderTargetFromSwapChain(renderWindow.SwapChain, rtCreationSettings); var context = deviceManager.Context; context.Rasterizer.SetViewports(new Viewport(0, 0, settings.Width, settings.Height, 0.0f, 1.0f)); var vertexData = new[] { new VertexPosition {Position = new Vector3(0.0f, 0.5f, 0.5f)}, new VertexPosition {Position = new Vector3(0.5f, -0.5f, 0.5f)}, new VertexPosition {Position = new Vector3(-0.5f, -0.5f, 0.5f)}, }; var stride = Marshal.SizeOf(typeof (VertexPosition)); var vertexBufferDesc = new BufferDescription( stride*vertexData.Length, ResourceUsage.Immutable, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, stride); var vertexBuffer = Buffer.Create(deviceManager.Device, vertexData, vertexBufferDesc); var binding = new VertexBufferBinding(vertexBuffer, stride, 0); var inputLayout = new InputLayoutCache(deviceManager.Device).GetLayout<VertexPosition>(); var fileName = "../../Shaders/triangle.fx"; var hullShader = new HullShader(deviceManager.Device, deviceManager.ShaderCompiler.LoadByteCodeFromFile(ShaderCompiler.ShaderType.HullShader, fileName, "HS")); var domainerShader = new DomainShader(deviceManager.Device, deviceManager.ShaderCompiler.LoadByteCodeFromFile(ShaderCompiler.ShaderType.DomainShader, fileName, "DS")); var vertexShader = new VertexShader(deviceManager.Device, deviceManager.ShaderCompiler.LoadByteCodeFromFile(ShaderCompiler.ShaderType.VertexShader, fileName, "VS")); var pixelShader = new PixelShader(deviceManager.Device, deviceManager.ShaderCompiler.LoadByteCodeFromFile(ShaderCompiler.ShaderType.PixelShader, fileName, "PS")); Console.Out.WriteLine(""); var rasterizerState = new RasterizerState(deviceManager.Device, new RasterizerStateDescription { CullMode = CullMode.None, FillMode = FillMode.Wireframe, IsDepthClipEnabled = false, IsFrontCounterClockwise = false, IsScissorEnabled = false }); var constantBuffer = new ConstantBuffer<TessellationParameters>(deviceManager.Device); var parameters = new TessellationParameters { TessellationFactor = 5 }; RenderLoop.Run(renderWindow, () => { renderTarget.SetActive(context); renderTarget.Clear(context); context.InputAssembler.SetVertexBuffers(0, binding); context.InputAssembler.PrimitiveTopology = PrimitiveTopology.PatchListWith3ControlPoints; context.InputAssembler.InputLayout = inputLayout; context.VertexShader.Set(vertexShader); context.PixelShader.Set(pixelShader); context.HullShader.Set(hullShader); context.DomainShader.Set(domainerShader); parameters.TessellationFactor = window.TesselationFactor; constantBuffer.UpdateValue(parameters); context.HullShader.SetConstantBuffer(0, constantBuffer.Buffer); //context.OutputMerger.DepthStencilState = null; context.Rasterizer.State = rasterizerState; context.Draw(3, 0); renderWindow.Present(); }); deviceManager.Dispose(); }
public FrustumShader(Device device) { // create single vertex buffer var stream = new DataStream(24 * VertexPosition.SizeInBytes, true, true); stream.Write(new Vector4(-1, -1, 0, 1)); stream.Write(new Vector4( 1, -1, 0, 1)); stream.Write(new Vector4( 1, -1, 0, 1)); stream.Write(new Vector4( 1, 1, 0, 1)); stream.Write(new Vector4( 1, 1, 0, 1)); stream.Write(new Vector4(-1, 1, 0, 1)); stream.Write(new Vector4(-1, 1, 0, 1)); stream.Write(new Vector4(-1, -1, 0, 1)); stream.Write(new Vector4(-1, -1, maxZ, 1)); stream.Write(new Vector4( 1, -1, maxZ, 1)); stream.Write(new Vector4( 1, -1, maxZ, 1)); stream.Write(new Vector4( 1, 1, maxZ, 1)); stream.Write(new Vector4( 1, 1, maxZ, 1)); stream.Write(new Vector4(-1, 1, maxZ, 1)); stream.Write(new Vector4(-1, 1, maxZ, 1)); stream.Write(new Vector4(-1, -1, maxZ, 1)); stream.Write(new Vector4(-1, -1, 0, 1)); stream.Write(new Vector4(-1, -1, maxZ, 1)); stream.Write(new Vector4( 1, -1, 0, 1)); stream.Write(new Vector4( 1, -1, maxZ, 1)); stream.Write(new Vector4( 1, 1, 0, 1)); stream.Write(new Vector4( 1, 1, maxZ, 1)); stream.Write(new Vector4(-1, 1, 0, 1)); stream.Write(new Vector4(-1, 1, maxZ, 1)); stream.Position = 0; var vertexBufferDesc = new BufferDescription() { BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.None, Usage = ResourceUsage.Default, SizeInBytes = 24 * VertexPosition.SizeInBytes, }; vertexBuffer = new SharpDX.Direct3D11.Buffer(device, stream, vertexBufferDesc); stream.Dispose(); vertexBufferBinding = new VertexBufferBinding(vertexBuffer, VertexPosition.SizeInBytes, 0); shaderByteCode = new ShaderBytecode(File.ReadAllBytes("Content/frustumVS.cso")); frustumVS = new VertexShader(device, shaderByteCode); frustumPS = new PixelShader(device, new ShaderBytecode(File.ReadAllBytes("Content/frustumPS.cso"))); // depth stencil state var depthStencilStateDesc = new DepthStencilStateDescription() { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.LessEqual, IsStencilEnabled = false, }; depthStencilState = new DepthStencilState(device, depthStencilStateDesc); // rasterizer state var rasterizerStateDesc = new RasterizerStateDescription() { CullMode = CullMode.None, FillMode = FillMode.Wireframe, IsDepthClipEnabled = true, IsFrontCounterClockwise = true, IsMultisampleEnabled = true, }; rasterizerState = new RasterizerState(device, rasterizerStateDesc); // constant buffer var VSConstantBufferDesc = new BufferDescription() { Usage = ResourceUsage.Dynamic, BindFlags = BindFlags.ConstantBuffer, SizeInBytes = VSConstantBuffer.size, CpuAccessFlags = CpuAccessFlags.Write, StructureByteStride = 0, OptionFlags = 0, }; vertexShaderConstantBuffer = new SharpDX.Direct3D11.Buffer(device, VSConstantBufferDesc); // Pixel shader constant buffer var PSConstantBufferDesc = new BufferDescription() { Usage = ResourceUsage.Dynamic, BindFlags = BindFlags.ConstantBuffer, SizeInBytes = PSConstantBuffer.size, CpuAccessFlags = CpuAccessFlags.Write, StructureByteStride = 0, OptionFlags = 0, }; pixelShaderConstantBuffer = new SharpDX.Direct3D11.Buffer(device, PSConstantBufferDesc); vertexInputLayout = new InputLayout(device, shaderByteCode.Data, new[] { new InputElement("SV_POSITION", 0, Format.R32G32B32A32_Float, 0, 0), }); }
/// <summary> /// Initializes a new instance of the <see cref="RasterizerState" /> class. /// </summary> /// <param name="device">The <see cref="DirectXDevice"/>.</param> /// <param name="description">The description.</param> private RasterizerState(DirectXDevice device, RasterizerStateDescription description) : base(device) { this.description = description; Resource = new SharpDX.Direct3D11.RasterizerState(Device, description); }
private void SetRasterizerState() { rasterizerState = new RasterizerState(device, RasterizerStateDescription.Default()); var desc = rasterizerState.Description; desc.CullMode = CullMode.None; rasterizerState = new RasterizerState(device, desc); deviceContext.Rasterizer.State = rasterizerState; }
public DepthAndColorShader(Device device) { shaderByteCode = new ShaderBytecode(File.ReadAllBytes("Content/DepthAndColorFloatVS.cso")); depthAndColorVS = new VertexShader(device, shaderByteCode); depthAndColorGS = new GeometryShader(device, new ShaderBytecode(File.ReadAllBytes("Content/DepthAndColorGS.cso"))); depthAndColorPS = new PixelShader(device, new ShaderBytecode(File.ReadAllBytes("Content/DepthAndColorPS.cso"))); // depth stencil state var depthStencilStateDesc = new DepthStencilStateDescription() { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.LessEqual, IsStencilEnabled = false, }; depthStencilState = new DepthStencilState(device, depthStencilStateDesc); // rasterizer state var rasterizerStateDesc = new RasterizerStateDescription() { CullMode = CullMode.None, FillMode = FillMode.Solid, IsDepthClipEnabled = true, IsFrontCounterClockwise = true, IsMultisampleEnabled = true, }; rasterizerState = new RasterizerState(device, rasterizerStateDesc); // color sampler state var colorSamplerStateDesc = new SamplerStateDescription() { Filter = Filter.MinMagMipLinear, AddressU = TextureAddressMode.Border, AddressV = TextureAddressMode.Border, AddressW = TextureAddressMode.Border, //BorderColor = new SharpDX.Color4(0.5f, 0.5f, 0.5f, 1.0f), BorderColor = new SharpDX.Color4(0, 0, 0, 1.0f), }; colorSamplerState = new SamplerState(device, colorSamplerStateDesc); //// Kinect depth image //var depthImageTextureDesc = new Texture2DDescription() //{ // Width = depthImageWidth, // Height = depthImageHeight, // MipLevels = 1, // ArraySize = 1, // Format = SharpDX.DXGI.Format.R16_UInt, // R32_Float // SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0), // Usage = ResourceUsage.Dynamic, // BindFlags = BindFlags.ShaderResource, // CpuAccessFlags = CpuAccessFlags.Write, //}; //depthImageTexture = new Texture2D(device, depthImageTextureDesc); //depthImageTextureRV = new ShaderResourceView(device, depthImageTexture); // filtered depth image var filteredDepthImageTextureDesc = new Texture2DDescription() { Width = Kinect2Calibration.depthImageWidth * 3, Height = Kinect2Calibration.depthImageHeight * 3, MipLevels = 1, ArraySize = 1, Format = SharpDX.DXGI.Format.R32G32_Float, SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource, CpuAccessFlags = CpuAccessFlags.None, }; filteredDepthImageTexture = new Texture2D(device, filteredDepthImageTextureDesc); filteredRenderTargetView = new RenderTargetView(device, filteredDepthImageTexture); filteredDepthImageSRV = new ShaderResourceView(device, filteredDepthImageTexture); filteredDepthImageTexture2 = new Texture2D(device, filteredDepthImageTextureDesc); filteredRenderTargetView2 = new RenderTargetView(device, filteredDepthImageTexture2); filteredDepthImageSRV2 = new ShaderResourceView(device, filteredDepthImageTexture2); //// Kinect color image //var colorImageStagingTextureDesc = new Texture2DDescription() //{ // Width = colorImageWidth, // Height = colorImageHeight, // MipLevels = 1, // ArraySize = 1, // Format = SharpDX.DXGI.Format.B8G8R8A8_UNorm, // //Format = SharpDX.DXGI.Format.YUY2 // SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0), // Usage = ResourceUsage.Dynamic, // BindFlags = BindFlags.ShaderResource, // CpuAccessFlags = CpuAccessFlags.Write //}; //colorImageStagingTexture = new Texture2D(device, colorImageStagingTextureDesc); //var colorImageTextureDesc = new Texture2DDescription() //{ // Width = colorImageWidth, // Height = colorImageHeight, // MipLevels = 0, // ArraySize = 1, // Format = SharpDX.DXGI.Format.B8G8R8A8_UNorm, // SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0), // Usage = ResourceUsage.Default, // BindFlags = BindFlags.ShaderResource | BindFlags.RenderTarget, // CpuAccessFlags = CpuAccessFlags.None, // OptionFlags = ResourceOptionFlags.GenerateMipMaps //}; //colorImageTexture = new Texture2D(device, colorImageTextureDesc); //colorImageTextureRV = new ShaderResourceView(device, colorImageTexture); // constant buffer var constantBufferDesc = new BufferDescription() { Usage = ResourceUsage.Dynamic, BindFlags = BindFlags.ConstantBuffer, SizeInBytes = ConstantBuffer.size, CpuAccessFlags = CpuAccessFlags.Write, StructureByteStride = 0, OptionFlags = 0, }; constantBuffer = new SharpDX.Direct3D11.Buffer(device, constantBufferDesc); bilateralFilter = new BilateralFilter(device, Kinect2Calibration.depthImageWidth, Kinect2Calibration.depthImageHeight); vertexInputLayout = new InputLayout(device, shaderByteCode.Data, new[] { new InputElement("SV_POSITION", 0, Format.R32G32B32A32_Float, 0, 0), }); }
public static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // Create main disposer var mainDisposer = new Disposer(); // var random = new Random(1415926535); #region demo setup // show setup dialog and get setup values var title = "Mash Room by Jolt"; var setupView = new StartupView(title); var setupModel = new SetupModel(); var presenter = new SetupPresenter(setupView, setupModel); setupModel.TryLoadSettings(); setupModel.SelectAdapter(0); var dialogResult = setupView.ShowDialog(); if (dialogResult != DialogResult.OK) return; #if DEBUG setupModel.SaveSettings(); // todo: remove save in release mode #endif #endregion // Create Device and SwapChain var demo = new Demo().Init(setupModel, title); var inputHandler = new InputHandler().Bind(demo); #region audio // var audioDeviceType = (setupModel.UseAudio) ? AudioDeviceType.Bass : AudioDeviceType.Silent; var audioDeviceManager = new AudioDeviceManager(); var audioDevice = mainDisposer.Add(audioDeviceManager.CreateDevice(audioDeviceType)); // if (setupModel.UseAudio) { // BassNet.Registration( setupModel.BassRegistrationEmail ?? "", setupModel.BassRegistrationKey ?? ""); // 140 bpm // delay 3.428 (dvs 2 takter i 140 bpm) var bpm = 140; var audioName = "Mashup_v1.00.mp3"; var audioAsset = mainDisposer.Add(demo.AudioManager[audioName]); // init and load audio audioDevice.Init(); audioDevice.Load(audioAsset.Value); audioDevice.PlayPosition = setupModel.StartTime; audioDevice.Bpm = bpm; // use the audio device as timer demo.Timer = audioDevice; } #endregion #region sync demo.SyncManager = new SyncManager().Init(setupModel.SyncRecordMode, demo.Timer.Bpm, 4); demo.SyncManager.TimerDevice = demo.Timer; #endregion #region shaders var planeVertexShader = demo.ShaderManager["plane.vs.cso"].VertexShader; var planePixelShader = demo.ShaderManager["plane.ps.cso"].PixelShader; var postPixelShader = demo.ShaderManager["post.ps.cso"].PixelShader; var postVertexShader = demo.ShaderManager["post.vs.cso"].VertexShader; var vanillaEffect = mainDisposer.Add(new VanillaEffect(demo).Init()); var vanillaLayout = mainDisposer.Add(vanillaEffect.InputLayout.InputLayout); #endregion #region models // load all models demo.ModelManager.LoadAll(); // make all models white (todo: why) foreach (var model in demo.ModelManager) { model.Color = new Color(255, 255, 255, 255); model.ReCreateBuffer(demo.Device); } #endregion #region textures Texture2D backBuffer = null; Texture2D depthBuffer = null; DepthStencilView depthView = null; // 1D texture for scanline distortion var distortionTexture = new Texture1D(demo.Device, new Texture1DDescription { CpuAccessFlags = CpuAccessFlags.None, Format = Format.R8G8B8A8_UNorm, Usage = ResourceUsage.Default, Width = 1080, ArraySize = 1, MipLevels = 1, BindFlags = BindFlags.ShaderResource, OptionFlags = ResourceOptionFlags.None }); var distortionData = new byte[4 * distortionTexture.Description.Width]; var distortionSRV = new ShaderResourceView(demo.Device, distortionTexture); // foreground texture var foregroundTexture = new Texture2D(demo.Device, new Texture2DDescription { CpuAccessFlags = CpuAccessFlags.None, Format = Format.R8_UNorm, Usage = ResourceUsage.Default, Width = 1920, Height = 1080, ArraySize = 1, MipLevels = 1, BindFlags = BindFlags.ShaderResource, OptionFlags = ResourceOptionFlags.None, SampleDescription = new SampleDescription(1, 0), }); var foregroundSRV = new ShaderResourceView(demo.Device, foregroundTexture); var foregroundData = new byte[foregroundTexture.Description.Width * foregroundTexture.Description.Height]; // noise texture var noiseTexture = new Texture2D(demo.Device, new Texture2DDescription { CpuAccessFlags = CpuAccessFlags.None, Format = Format.R8_UNorm, Usage = ResourceUsage.Default, Width = 1920 / 5, Height = 1080 / 5, ArraySize = 1, MipLevels = 1, BindFlags = BindFlags.ShaderResource, OptionFlags = ResourceOptionFlags.None, SampleDescription = new SampleDescription(1, 0), }); var noiseSRV = new ShaderResourceView(demo.Device, noiseTexture); var noiseData = new byte[noiseTexture.Description.Width * noiseTexture.Description.Height]; #endregion #region acts var act0 = mainDisposer.Add(new Act0(demo).Init()); #endregion #region effects //var fractalCityEffect = mainDisposer.Add(new FractalCityEffect(demo).Init()); //var oceanEffect = mainDisposer.Add(new OceanEffect(demo).Init()); //var dustEffect = mainDisposer.Add(new DustEffect(demo).Init()); //var cloudEffect = mainDisposer.Add(new CloudEffect(demo).Init()); //var mandelbulbEffect = mainDisposer.Add(new MandelbulbEffect(demo).Init()); //var redPlanetEffect = mainDisposer.Add(new Effect(demo).Init(new EffectDescription //{ // PixelShaderName = "redPlanet.ps.cso", // TextureNames = "redPlanet0.png,redPlanet1.jpg".Split(',') //})); //var pseudoKleinianEffect = mainDisposer.Add(new Effect(demo).Init(new EffectDescription //{ // PixelShaderName = "pseudoKleinian.ps.cso", //})); //var nonameEffect00 = mainDisposer.Add(new Effect(demo).Init(new EffectDescription { PixelShaderName = "noname00.ps.cso", TextureNames = "tex09.jpg".Split(',') })); //var nonameEffect01 = mainDisposer.Add(new Effect(demo).Init(new EffectDescription { PixelShaderName = "noname01.ps.cso" })); //var nonameEffect02 = mainDisposer.Add(new Effect(demo).Init(new EffectDescription { PixelShaderName = "noname02.ps.cso", TextureNames = "tex09.jpg,tex07.jpg".Split(',') })); //var nonameEffect03 = mainDisposer.Add(new Effect(demo).Init(new EffectDescription { PixelShaderName = "noname03.ps.cso" })); //var nonameEffect04 = mainDisposer.Add(new Effect(demo).Init(new EffectDescription { PixelShaderName = "noname04.ps.cso", TextureNames = "noise256.png".Split(',') })); //var nonameEffect05 = mainDisposer.Add(new Effect(demo).Init(new EffectDescription { PixelShaderName = "noname05.ps.cso" })); //var nonameEffect06 = mainDisposer.Add(new Effect(demo).Init(new EffectDescription { PixelShaderName = "noname06.ps.cso" })); //var nonameEffect07 = mainDisposer.Add(new Effect(demo).Init(new EffectDescription { PixelShaderName = "noname07.ps.cso" })); //var nonameEffect08 = mainDisposer.Add(new Effect(demo).Init(new EffectDescription { PixelShaderName = "noname08.ps.cso" })); //var nonameEffect09 = mainDisposer.Add(new Effect(demo).Init(new EffectDescription { PixelShaderName = "noname09.ps.cso" })); //var nonameEffect10 = mainDisposer.Add(new Effect(demo).Init(new EffectDescription { PixelShaderName = "noname10.ps.cso" })); #endregion var fillStateMsaadesc = RasterizerStateDescription.Default(); fillStateMsaadesc.IsMultisampleEnabled = true; var msaaFillState = new RasterizerState(demo.Device, fillStateMsaadesc); var fillState = new RasterizerState(demo.Device, RasterizerStateDescription.Default()); var vanillaRenderContext = null as RenderContext; var postRenderContext = null as RenderContext; var planeRenderContext = null as RenderContext; // Main loop using (var renderDisposer = new Disposer()) { RenderLoop.Run(demo.Form, () => { if (demo.SyncManager.RowIndex == 0x000006d0) { demo.Form.Close(); return; } // TODO refactor: move the resize code #region resize if (demo.OutputWasResized) { demo.OutputWasResized = false; renderDisposer.DisposeAll(); // dispose old swapchain if (demo.SwapChain != null) { demo.SwapChain.Dispose(); } // create new swapchain demo.SwapChain = renderDisposer.Add(new SwapChain(setupModel.Factory, demo.Device, new SwapChainDescription { BufferCount = 1, ModeDescription = setupModel.Mode, IsWindowed = !setupModel.FullScreen, OutputHandle = demo.Form.Handle, //SampleDescription = new SampleDescription(setupModel.MultiSampleCount, setupModel.MultiSampleQuality), SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput })); if (setupModel.FullScreen) { demo.SwapChain.SetFullscreenState(true, setupModel.Output); } // var postOutputRenderTarget = new RenderTarget(demo.Device, demo.SwapChain); // Get the backbuffer from the swapchain backBuffer = renderDisposer.Add(demo.SwapChain.GetBackBuffer<Texture2D>(0)); // Setup targets and viewport for rendering var postInputRenderTarget = new RenderTarget( device: demo.Device, width: setupModel.Mode.Width / 1, // todo: introduce a scalefactor height: setupModel.Mode.Height / 1, // todo: introduce a scalefactor sampleCount: 1, // todo: use setupModel.MultiSampleCount, sampleQuality: 0, // todo: use setupModel.MultiSampleQuality, format: Format.R8G8B8A8_UNorm // todo: use setupModel.Format ); // Create the depth buffer depthBuffer = renderDisposer.Add(new Texture2D(demo.Device, new Texture2DDescription { Format = Format.D32_Float_S8X24_UInt, ArraySize = 1, MipLevels = 1, Width = postInputRenderTarget.Width, Height = postInputRenderTarget.Height, SampleDescription = postInputRenderTarget.Texture.Description.SampleDescription, Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None })); // Create the depth buffer view depthView = renderDisposer.Add(new DepthStencilView(demo.Device, depthBuffer)); vanillaRenderContext = renderDisposer.Add(new RenderContext { PrimitiveTopology = PrimitiveTopology.TriangleList, InputLayout = vanillaLayout, VertexShader = null, PixelShader = null, RasterizerState = msaaFillState, DepthStencilView = depthView, RenderTarget = postInputRenderTarget, }); postRenderContext = renderDisposer.Add(new RenderContext { PrimitiveTopology = PrimitiveTopology.TriangleList, InputLayout = vanillaLayout, VertexShader = postVertexShader, PixelShader = postPixelShader, RasterizerState = fillState, DepthStencilView = null, RenderTarget = postOutputRenderTarget, }); planeRenderContext = new RenderContext { PrimitiveTopology = PrimitiveTopology.TriangleList, InputLayout = vanillaLayout, VertexShader = planeVertexShader, PixelShader = planePixelShader, RasterizerState = fillState, DepthStencilView = null, RenderTarget = postOutputRenderTarget, }; // todo: remove this hack if (!setupModel.SyncRecordMode) { demo.Timer.StartPlaying(); } if (setupModel.FullScreen) { Cursor.Hide(); } } #endregion // todo: remove demo.SyncManager.Update(demo.Timer.Time); var syncRow = new { demo.SyncManager.Data.Part, demo.SyncManager.Data.Lead, }; // Present! // a crash here is quite common when VertexShader or PixelShader is null demo.SwapChain.Present(setupModel.UseVerticalSync ? 1 : 0, PresentFlags.None); // horizontal distortion and color separation random.NextBytes(distortionData); demo.DeviceContext.UpdateSubresource(distortionData, distortionTexture); // static noise random.NextBytes(noiseData); demo.DeviceContext.UpdateSubresource(noiseData, noiseTexture, 0, noiseTexture.Description.Width); // setup for normal rendering { // use normal rendering demo.DeviceContext.PixelShader.SetShaderResource(0, null); demo.RenderContext = vanillaRenderContext; // clear demo.DeviceContext.ClearDepthStencilView(demo.RenderContext.DepthStencilView, DepthStencilClearFlags.Depth, 1.0f, 0); demo.DeviceContext.ClearRenderTargetView(demo.RenderContext.RenderTarget.RenderTargetView, Color.Black); } // render act act0.Render(); // demo.DeviceContext.ClearRenderTargetView(postRenderContext.RenderTarget.RenderTargetView, Color.Black); // render plane to screen if (true) { // TODO is this really needed ? demo.DeviceContext.OutputMerger.ResetTargets(); demo.DeviceContext.VertexShader.SetConstantBuffer(0, null); // use post rendering demo.RenderContext = postRenderContext; // set textures demo.DeviceContext.PixelShader.SetShaderResource(0, vanillaRenderContext.RenderTarget.ShaderResourceView); demo.DeviceContext.PixelShader.SetShaderResource(1, distortionSRV); demo.DeviceContext.PixelShader.SetShaderResource(2, noiseSRV); // use plane model var model = demo.ModelManager["plane2"]; // todo: make sure we have no z-buffer conflicts (might be hw dependent) var camera = new NoCamera(); demo.Draw(model, camera); } }); } // dispose Disposer.Dispose(ref mainDisposer); }
public bool Initialize(SystemConfiguration configuration, IntPtr windowHandle) { try { #region Environment Configuration // Store the vsync setting. VerticalSyncEnabled = SystemConfiguration.VerticalSyncEnabled; // Create a DirectX graphics interface factory. var factory = new Factory(); // Use the factory to create an adapter for the primary graphics interface (video card). var adapter = factory.GetAdapter(0); // Get the primary adapter output (monitor). var monitor = adapter.GetOutput(0); // Get modes that fit the DXGI_FORMAT_R8G8B8A8_UNORM display format for the adapter output (monitor). var modes = monitor.GetDisplayModeList(Format.R8G8B8A8_UNorm, DisplayModeEnumerationFlags.Interlaced); // Now go through all the display modes and find the one that matches the screen width and height. // When a match is found store the the refresh rate for that monitor, if vertical sync is enabled. // Otherwise we use maximum refresh rate. var rational = new Rational(0, 1); if (VerticalSyncEnabled) { foreach (var mode in modes) { if (mode.Width == configuration.Width && mode.Height == configuration.Height) { rational = new Rational(mode.RefreshRate.Numerator, mode.RefreshRate.Denominator); break; } } } // Get the adapter (video card) description. var adapterDescription = adapter.Description; // Store the dedicated video card memory in megabytes. VideoCardMemory = adapterDescription.DedicatedVideoMemory >> 10 >> 10; // Convert the name of the video card to a character array and store it. VideoCardDescription = adapterDescription.Description; // Release the adapter output. monitor.Dispose(); // Release the adapter. adapter.Dispose(); // Release the factory. factory.Dispose(); #endregion #region Initialize swap chain and d3d device // Initialize the swap chain description. var swapChainDesc = new SwapChainDescription() { // Set to a single back buffer. BufferCount = 1, // Set the width and height of the back buffer. ModeDescription = new ModeDescription(configuration.Width, configuration.Height, rational, Format.R8G8B8A8_UNorm), // Set the usage of the back buffer. Usage = Usage.RenderTargetOutput, // Set the handle for the window to render to. OutputHandle = windowHandle, // Turn multisampling off. SampleDescription = new SampleDescription(1, 0), // Set to full screen or windowed mode. IsWindowed = !SystemConfiguration.FullScreen, // Don't set the advanced flags. Flags = SwapChainFlags.None, // Discard the back buffer content after presenting. SwapEffect = SwapEffect.Discard }; // Create the swap chain, Direct3D device, and Direct3D device context. Device device; SwapChain swapChain; Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, swapChainDesc, out device, out swapChain); Device = device; SwapChain = swapChain; DeviceContext = device.ImmediateContext; #endregion #region Initialize buffers // Get the pointer to the back buffer. var backBuffer = Texture2D.FromSwapChain<Texture2D>(SwapChain, 0); // Create the render target view with the back buffer pointer. RenderTargetView = new RenderTargetView(device, backBuffer); // Release pointer to the back buffer as we no longer need it. backBuffer.Dispose(); // Initialize and set up the description of the depth buffer. var depthBufferDesc = new Texture2DDescription() { Width = configuration.Width, Height = configuration.Height, MipLevels = 1, ArraySize = 1, Format = Format.D24_UNorm_S8_UInt, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }; // Create the texture for the depth buffer using the filled out description. DepthStencilBuffer = new Texture2D(device, depthBufferDesc); #endregion #region Initialize Depth Enabled Stencil // Initialize and set up the description of the stencil state. var depthStencilDesc = new DepthStencilStateDescription() { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less, IsStencilEnabled = true, StencilReadMask = 0xFF, StencilWriteMask = 0xFF, // Stencil operation if pixel front-facing. FrontFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Increment, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always }, // Stencil operation if pixel is back-facing. BackFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Decrement, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always } }; // Create the depth stencil state. DepthStencilState = new DepthStencilState(Device, depthStencilDesc); #endregion #region Initialize Output Merger // Set the depth stencil state. DeviceContext.OutputMerger.SetDepthStencilState(DepthStencilState, 1); // Initialize and set up the depth stencil view. var depthStencilViewDesc = new DepthStencilViewDescription() { Format = Format.D24_UNorm_S8_UInt, Dimension = DepthStencilViewDimension.Texture2D, Texture2D = new DepthStencilViewDescription.Texture2DResource() { MipSlice = 0 } }; // Create the depth stencil view. DepthStencilView = new DepthStencilView(Device, DepthStencilBuffer, depthStencilViewDesc); // Bind the render target view and depth stencil buffer to the output render pipeline. DeviceContext.OutputMerger.SetTargets(DepthStencilView, RenderTargetView); #endregion #region Initialize Raster State // Setup the raster description which will determine how and what polygon will be drawn. var rasterDesc = new RasterizerStateDescription() { IsAntialiasedLineEnabled = false, CullMode = CullMode.Back, DepthBias = 0, DepthBiasClamp = .0f, IsDepthClipEnabled = true, FillMode = FillMode.Solid, IsFrontCounterClockwise = false, IsMultisampleEnabled = false, IsScissorEnabled = false, SlopeScaledDepthBias = .0f }; // Create the rasterizer state from the description we just filled out. RasterState = new RasterizerState(Device, rasterDesc); #endregion #region Initialize Rasterizer // Now set the rasterizer state. DeviceContext.Rasterizer.State = RasterState; // Setup and create the viewport for rendering. DeviceContext.Rasterizer.SetViewport(0, 0, configuration.Width, configuration.Height, 0, 1); #endregion #region Initialize matrices // Setup and create the projection matrix. ProjectionMatrix = Matrix.PerspectiveFovLH((float)(Math.PI / 4f), ((float)configuration.Width / configuration.Height), SystemConfiguration.ScreenNear, SystemConfiguration.ScreenDepth); // Initialize the world matrix to the identity matrix. WorldMatrix = Matrix.Identity; // Create an orthographic projection matrix for 2D rendering. OrthoMatrix = Matrix.OrthoLH(configuration.Width, configuration.Height, SystemConfiguration.ScreenNear, SystemConfiguration.ScreenDepth); #endregion #region Initialize Depth Disabled Stencil // Now create a second depth stencil state which turns off the Z buffer for 2D rendering. // The difference is that DepthEnable is set to false. // All other parameters are the same as the other depth stencil state. var depthDisabledStencilDesc = new DepthStencilStateDescription() { IsDepthEnabled = false, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less, IsStencilEnabled = true, StencilReadMask = 0xFF, StencilWriteMask = 0xFF, // Stencil operation if pixel front-facing. FrontFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Increment, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always }, // Stencil operation if pixel is back-facing. BackFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Decrement, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always } }; // Create the depth stencil state. DepthDisabledStencilState = new DepthStencilState(Device, depthDisabledStencilDesc); #endregion #region Initialize Blend States // Create an alpha enabled blend state description. var blendStateDesc = new BlendStateDescription(); blendStateDesc.RenderTarget[0].IsBlendEnabled = true; blendStateDesc.RenderTarget[0].SourceBlend = BlendOption.One; blendStateDesc.RenderTarget[0].DestinationBlend = BlendOption.InverseSourceAlpha; blendStateDesc.RenderTarget[0].BlendOperation = BlendOperation.Add; blendStateDesc.RenderTarget[0].SourceAlphaBlend = BlendOption.One; blendStateDesc.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero; blendStateDesc.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add; blendStateDesc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; // Create the blend state using the description. AlphaEnableBlendingState = new BlendState(device, blendStateDesc); // Modify the description to create an disabled blend state description. blendStateDesc.RenderTarget[0].IsBlendEnabled = false; // Create the blend state using the description. AlphaDisableBlendingState = new BlendState(device, blendStateDesc); #endregion return true; } catch (Exception) { return false; } }
private void InitializeDeviceResources(DXGI.SwapChain swapChain) { backbufferTexture = swapChain.GetBackBuffer <D3D11.Texture2D>(0); backbufferRTV = new D3D11.RenderTargetView(device, backbufferTexture); width = backbufferTexture.Description.Width; height = backbufferTexture.Description.Height; var depthBufferDesc = new D3D11.Texture2DDescription() { Width = width, Height = height, MipLevels = 1, ArraySize = 1, Format = DXGI.Format.D24_UNorm_S8_UInt, SampleDescription = new DXGI.SampleDescription(1, 0), Usage = D3D11.ResourceUsage.Default, BindFlags = D3D11.BindFlags.DepthStencil, CpuAccessFlags = D3D11.CpuAccessFlags.None, OptionFlags = D3D11.ResourceOptionFlags.None }; using (var depthStencilBufferTexture = new D3D11.Texture2D(device, depthBufferDesc)) { var depthStencilViewDesc = new D3D11.DepthStencilViewDescription() { Format = DXGI.Format.D24_UNorm_S8_UInt, Dimension = D3D11.DepthStencilViewDimension.Texture2D, Texture2D = new D3D11.DepthStencilViewDescription.Texture2DResource() { MipSlice = 0 } }; depthDSV = new D3D11.DepthStencilView(device, depthStencilBufferTexture, depthStencilViewDesc); } var depthStencilDesc = new D3D11.DepthStencilStateDescription() { IsDepthEnabled = true, DepthWriteMask = D3D11.DepthWriteMask.All, DepthComparison = D3D11.Comparison.Less, IsStencilEnabled = false, StencilReadMask = 0xFF, StencilWriteMask = 0xFF, FrontFace = new D3D11.DepthStencilOperationDescription() { FailOperation = D3D11.StencilOperation.Keep, DepthFailOperation = D3D11.StencilOperation.Keep, PassOperation = D3D11.StencilOperation.Keep, Comparison = D3D11.Comparison.Always }, BackFace = new D3D11.DepthStencilOperationDescription() { FailOperation = D3D11.StencilOperation.Keep, DepthFailOperation = D3D11.StencilOperation.Keep, PassOperation = D3D11.StencilOperation.Keep, Comparison = D3D11.Comparison.Always } }; depthStencilState = new D3D11.DepthStencilState(device, depthStencilDesc); var rasterDesc = new D3D11.RasterizerStateDescription() { IsAntialiasedLineEnabled = false, CullMode = D3D11.CullMode.Back, DepthBias = 0, DepthBiasClamp = 0.0f, IsDepthClipEnabled = false, FillMode = D3D11.FillMode.Solid, IsFrontCounterClockwise = false, IsMultisampleEnabled = false, IsScissorEnabled = false, SlopeScaledDepthBias = 0.0f }; /*var blendDesc = new D3D11.BlendStateDescription(); * blendDesc.RenderTarget[0].IsBlendEnabled = true; * blendDesc.RenderTarget[0].SourceBlend = D3D11.BlendOption.SourceAlpha; * blendDesc.RenderTarget[0].DestinationBlend = D3D11.BlendOption.InverseSourceAlpha; * blendDesc.RenderTarget[0].BlendOperation = D3D11.BlendOperation.Add; * blendDesc.RenderTarget[0].SourceAlphaBlend = D3D11.BlendOption.Zero; * blendDesc.RenderTarget[0].DestinationAlphaBlend = D3D11.BlendOption.Zero; * blendDesc.RenderTarget[0].AlphaBlendOperation = D3D11.BlendOperation.Add; * blendDesc.RenderTarget[0].RenderTargetWriteMask = D3D11.ColorWriteMaskFlags.All;*/ #if ALPHABLENDING var blendDesc = new D3D11.BlendStateDescription(); blendDesc.RenderTarget[0].IsBlendEnabled = true; blendDesc.RenderTarget[0].SourceBlend = D3D11.BlendOption.SourceAlpha; blendDesc.RenderTarget[0].DestinationBlend = D3D11.BlendOption.InverseSourceAlpha; blendDesc.RenderTarget[0].BlendOperation = D3D11.BlendOperation.Add; blendDesc.RenderTarget[0].SourceAlphaBlend = D3D11.BlendOption.Zero; blendDesc.RenderTarget[0].DestinationAlphaBlend = D3D11.BlendOption.One; blendDesc.RenderTarget[0].AlphaBlendOperation = D3D11.BlendOperation.Add; blendDesc.RenderTarget[0].RenderTargetWriteMask = D3D11.ColorWriteMaskFlags.All; #endif #if ADDITIVEBLENDING var blendDesc = new D3D11.BlendStateDescription(); blendDesc.RenderTarget[0].IsBlendEnabled = true; blendDesc.RenderTarget[0].SourceBlend = D3D11.BlendOption.SourceAlpha; blendDesc.RenderTarget[0].DestinationBlend = D3D11.BlendOption.DestinationAlpha; blendDesc.RenderTarget[0].BlendOperation = D3D11.BlendOperation.Add; blendDesc.RenderTarget[0].SourceAlphaBlend = D3D11.BlendOption.One; blendDesc.RenderTarget[0].DestinationAlphaBlend = D3D11.BlendOption.One; blendDesc.RenderTarget[0].AlphaBlendOperation = D3D11.BlendOperation.Add; blendDesc.RenderTarget[0].RenderTargetWriteMask = D3D11.ColorWriteMaskFlags.All; #endif // RenderTarget[0].BlendOpSharpDX.Direct3D11.BlendOperation.Add RenderTarget[0].SrcBlendAlphaSharpDX.Direct3D11.BlendOption.One // RenderTarget[0].DestBlendAlphaSharpDX.Direct3D11.BlendOption.Zero RenderTarget[0].BlendOpAlphaSharpDX.Direct3D11.BlendOperation.Add // RenderTarget[0].RenderTargetWriteMaskSharpDX.Direct3D11.ColorWriteMaskFlags.All blendState = new D3D11.BlendState(device, blendDesc); rasterizerState = new D3D11.RasterizerState(device, rasterDesc); }