public void CreateWindowSizeDependentResources() { uint width = this.deviceResources.BackBufferWidth; uint height = this.deviceResources.BackBufferHeight; // Create fragment count buffer this.fragmentCountBuffer = this.deviceResources.D3DDevice.CreateTexture2D( new D3D11Texture2DDesc( DxgiFormat.R32UInt, width, height, 1, 1, D3D11BindOptions.UnorderedAccess | D3D11BindOptions.ShaderResource)); // Create prefix sum buffer this.prefixSum = this.deviceResources.D3DDevice.CreateBuffer(new D3D11BufferDesc( width * height * 4, D3D11BindOptions.UnorderedAccess | D3D11BindOptions.ShaderResource, D3D11Usage.Default, D3D11CpuAccessOptions.None, D3D11ResourceMiscOptions.None, 4)); // Create the deep frame buffer. // This simple allocation scheme for the deep frame buffer allocates space for 8 times the size of the // frame buffer, which means that it can hold an average of 8 fragments per pixel. This will usually waste some // space, and in some cases of high overdraw the buffer could run into problems with overflow. It // may be useful to make the buffer size more intelligent to avoid these problems. this.deepBuffer = this.deviceResources.D3DDevice.CreateBuffer(new D3D11BufferDesc( width * height * 8 * 4, D3D11BindOptions.UnorderedAccess | D3D11BindOptions.ShaderResource, D3D11Usage.Default, D3D11CpuAccessOptions.None, D3D11ResourceMiscOptions.None, 4)); // Create deep frame buffer for color this.deepBufferColor = this.deviceResources.D3DDevice.CreateBuffer(new D3D11BufferDesc( width * height * 8 * 4 * 1, D3D11BindOptions.UnorderedAccess | D3D11BindOptions.ShaderResource, D3D11Usage.Default, D3D11CpuAccessOptions.None, D3D11ResourceMiscOptions.None, 4 * 1)); this.fragmentCountRV = this.deviceResources.D3DDevice.CreateShaderResourceView( this.fragmentCountBuffer, new D3D11ShaderResourceViewDesc( D3D11SrvDimension.Texture2D, DxgiFormat.R32UInt, 0, 1)); this.fragmentCountUAV = this.deviceResources.D3DDevice.CreateUnorderedAccessView( this.fragmentCountBuffer, new D3D11UnorderedAccessViewDesc( D3D11UavDimension.Texture2D, DxgiFormat.R32UInt, 0)); this.prefixSumUAV = this.deviceResources.D3DDevice.CreateUnorderedAccessView( this.prefixSum, new D3D11UnorderedAccessViewDesc( D3D11UavDimension.Buffer, DxgiFormat.R32UInt, 0, width * height)); this.deepBufferUAV = this.deviceResources.D3DDevice.CreateUnorderedAccessView( this.deepBuffer, new D3D11UnorderedAccessViewDesc( D3D11UavDimension.Buffer, DxgiFormat.R32Float, 0, width * height * 8)); this.deepBufferColorUAV = this.deviceResources.D3DDevice.CreateUnorderedAccessView( this.deepBufferColor, new D3D11UnorderedAccessViewDesc( D3D11UavDimension.Buffer, DxgiFormat.B8G8R8A8UNorm, 0, width * height * 8)); this.screenTexture = this.deviceResources.D3DDevice.CreateTexture2D( new D3D11Texture2DDesc( DxgiFormat.B8G8R8A8UNorm, width, height, 1, 1, D3D11BindOptions.RenderTarget | D3D11BindOptions.UnorderedAccess)); this.screenTextureRTV = this.deviceResources.D3DDevice.CreateRenderTargetView(this.screenTexture, null); this.screenTextureUAV = this.deviceResources.D3DDevice.CreateUnorderedAccessView(this.screenTexture, new D3D11UnorderedAccessViewDesc(D3D11UavDimension.Texture2D, DxgiFormat.B8G8R8A8UNorm, 0)); }
public void PerEdgeTessellation( XMMatrix matWVP, ref D3D11Buffer ppTessedVerticesBuf, ref D3D11Buffer ppTessedIndicesBuf, out uint num_tessed_vertices, out uint num_tessed_indices) { var d3dDevice = this.deviceResources.D3DDevice; var d3dContext = this.deviceResources.D3DContext; // Update per-edge tessellation factors { EdgeFactorConstantBuffer cbCS = default; cbCS.MatWVP = matWVP; cbCS.TessEdgeLengthScale = this.m_tess_edge_len_scale; cbCS.NumTriangles = this.m_nVertices / 3; d3dContext.UpdateSubresource( this.s_pEdgeFactorCSCB, D3D11Utils.CalcSubresource(0, 0, 1), null, cbCS, EdgeFactorConstantBuffer.Size, EdgeFactorConstantBuffer.Size); this.RunComputeShader( this.s_pEdgeFactorCS, new[] { this.m_pBaseVBSRV }, null, this.s_pEdgeFactorCSCB, this.m_pEdgeFactorBufUAV, (uint)Math.Ceiling(this.m_nVertices / 3 / 128.0f), 1U, 1U); } // How many vertices/indices are needed for the tessellated mesh? { uint[] cbCS = new uint[] { this.m_nVertices / 3, 0, 0, 0 }; d3dContext.UpdateSubresource( this.s_pCSCB, D3D11Utils.CalcSubresource(0, 0, 1), null, cbCS, 4 * 4, 4 * 4); this.RunComputeShader( this.s_pNumVerticesIndicesCSs[(int)this.PartitioningMode], new[] { this.m_pEdgeFactorBufSRV }, this.s_pLookupTableCSCB, this.s_pCSCB, this.m_pScanBuf0UAV, (uint)Math.Ceiling(this.m_nVertices / 3 / 128.0f), 1U, 1U); this.s_ScanCS.Scan(d3dContext, this.m_nVertices / 3, this.m_pScanBuf0SRV, this.m_pScanBuf0UAV, this.m_pScanBuf1SRV, this.m_pScanBuf1UAV); // read back the number of vertices/indices for tessellation output D3D11Box box = default; box.Left = 4 * 2 * this.m_nVertices / 3 - 4 * 2; box.Right = 4 * 2 * this.m_nVertices / 3; box.Top = 0; box.Bottom = 1; box.Front = 0; box.Back = 1; d3dContext.CopySubresourceRegion(this.s_pCSReadBackBuf, 0, 0, 0, 0, this.m_pScanBuf0, 0, box); D3D11MappedSubResource mappedResource = d3dContext.Map(this.s_pCSReadBackBuf, 0, D3D11MapCpuPermission.Read, D3D11MapOptions.None); try { num_tessed_vertices = (uint)Marshal.ReadInt32(mappedResource.Data + 4 * 0); num_tessed_indices = (uint)Marshal.ReadInt32(mappedResource.Data + 4 * 1); } finally { d3dContext.Unmap(this.s_pCSReadBackBuf, 0); } } if (num_tessed_vertices == 0 || num_tessed_indices == 0) { return; } // Turn on this and set a breakpoint on the line beginning with "p = " and see what has been written to m_pScanBuf0 if (DebugEnabled) { #pragma warning disable IDE0059 // Assignation inutile d'une valeur var p = this.CreateAndCopyToDebugBuf <(uint v, uint t)>(this.m_pScanBuf0); #pragma warning restore IDE0059 // Assignation inutile d'une valeur } // Generate buffers for scattering TriID and IndexID for both vertex data and index data, // also generate buffers for output tessellated vertex data and index data { if (this.m_pScatterVertexBuf == null || this.m_nCachedTessedVertices < num_tessed_vertices || this.m_nCachedTessedVertices > num_tessed_vertices * 2) { D3D11Utils.DisposeAndNull(ref this.m_pScatterVertexBuf); D3D11Utils.DisposeAndNull(ref this.m_pScatterVertexBufSRV); D3D11Utils.DisposeAndNull(ref this.m_pScatterVertexBufUAV); D3D11Utils.DisposeAndNull(ref ppTessedVerticesBuf); D3D11Utils.DisposeAndNull(ref this.m_pTessedVerticesBufUAV); D3D11Utils.DisposeAndNull(ref this.m_pTessedVerticesBufSRV); this.m_pScatterVertexBuf = d3dDevice.CreateBuffer(new D3D11BufferDesc { BindOptions = D3D11BindOptions.ShaderResource | D3D11BindOptions.UnorderedAccess, ByteWidth = 4 * 2 * num_tessed_vertices, StructureByteStride = 4 * 2, MiscOptions = D3D11ResourceMiscOptions.BufferStructured, Usage = D3D11Usage.Default }); this.m_pScatterVertexBufSRV = d3dDevice.CreateShaderResourceView(this.m_pScatterVertexBuf, new D3D11ShaderResourceViewDesc { ViewDimension = D3D11SrvDimension.Buffer, Format = DxgiFormat.Unknown, Buffer = new D3D11BufferSrv { FirstElement = 0, NumElements = num_tessed_vertices } }); this.m_pScatterVertexBufUAV = d3dDevice.CreateUnorderedAccessView(this.m_pScatterVertexBuf, new D3D11UnorderedAccessViewDesc { ViewDimension = D3D11UavDimension.Buffer, Format = DxgiFormat.Unknown, Buffer = new D3D11BufferUav { FirstElement = 0, NumElements = num_tessed_vertices } }); // generate the output tessellated vertices buffer ppTessedVerticesBuf = d3dDevice.CreateBuffer(new D3D11BufferDesc { BindOptions = D3D11BindOptions.ShaderResource | D3D11BindOptions.UnorderedAccess, ByteWidth = 4 * 3 * num_tessed_vertices, StructureByteStride = 4 * 3, MiscOptions = D3D11ResourceMiscOptions.BufferStructured, Usage = D3D11Usage.Default }); this.m_pTessedVerticesBufUAV = d3dDevice.CreateUnorderedAccessView(ppTessedVerticesBuf, new D3D11UnorderedAccessViewDesc { ViewDimension = D3D11UavDimension.Buffer, Format = DxgiFormat.Unknown, Buffer = new D3D11BufferUav { FirstElement = 0, NumElements = num_tessed_vertices } }); this.m_pTessedVerticesBufSRV = d3dDevice.CreateShaderResourceView(ppTessedVerticesBuf, new D3D11ShaderResourceViewDesc { ViewDimension = D3D11SrvDimension.Buffer, Format = DxgiFormat.Unknown, Buffer = new D3D11BufferSrv { FirstElement = 0, NumElements = num_tessed_vertices } }); this.m_nCachedTessedVertices = num_tessed_vertices; } if (this.m_pScatterIndexBuf == null || this.m_nCachedTessedIndices < num_tessed_indices) { D3D11Utils.DisposeAndNull(ref this.m_pScatterIndexBuf); D3D11Utils.DisposeAndNull(ref this.m_pScatterIndexBufSRV); D3D11Utils.DisposeAndNull(ref this.m_pScatterIndexBufUAV); D3D11Utils.DisposeAndNull(ref ppTessedIndicesBuf); D3D11Utils.DisposeAndNull(ref this.m_pTessedIndicesBufUAV); this.m_pScatterIndexBuf = d3dDevice.CreateBuffer(new D3D11BufferDesc { BindOptions = D3D11BindOptions.ShaderResource | D3D11BindOptions.UnorderedAccess, ByteWidth = 4 * 2 * num_tessed_indices, StructureByteStride = 4 * 2, MiscOptions = D3D11ResourceMiscOptions.BufferStructured, Usage = D3D11Usage.Default }); this.m_pScatterIndexBufSRV = d3dDevice.CreateShaderResourceView(this.m_pScatterIndexBuf, new D3D11ShaderResourceViewDesc { ViewDimension = D3D11SrvDimension.Buffer, Format = DxgiFormat.Unknown, Buffer = new D3D11BufferSrv { FirstElement = 0, NumElements = num_tessed_indices } }); this.m_pScatterIndexBufUAV = d3dDevice.CreateUnorderedAccessView(this.m_pScatterIndexBuf, new D3D11UnorderedAccessViewDesc { ViewDimension = D3D11UavDimension.Buffer, Format = DxgiFormat.Unknown, Buffer = new D3D11BufferUav { FirstElement = 0, NumElements = num_tessed_indices } }); // generate the output tessellated indices buffer ppTessedIndicesBuf = d3dDevice.CreateBuffer(new D3D11BufferDesc { BindOptions = D3D11BindOptions.ShaderResource | D3D11BindOptions.UnorderedAccess | D3D11BindOptions.IndexBuffer, ByteWidth = 4 * num_tessed_indices, MiscOptions = D3D11ResourceMiscOptions.BufferAllowRawViews, Usage = D3D11Usage.Default }); this.m_pTessedIndicesBufUAV = d3dDevice.CreateUnorderedAccessView(ppTessedIndicesBuf, new D3D11UnorderedAccessViewDesc { ViewDimension = D3D11UavDimension.Buffer, Format = DxgiFormat.R32Typeless, Buffer = new D3D11BufferUav { FirstElement = 0, NumElements = num_tessed_indices, Options = D3D11BufferUavOptions.Raw } }); this.m_nCachedTessedIndices = num_tessed_indices; } } // Scatter TriID, IndexID { uint[] cbCS = new uint[] { this.m_nVertices / 3, 0, 0, 0 }; D3D11ShaderResourceView[] aRViews = new[] { this.m_pScanBuf0SRV }; d3dContext.UpdateSubresource( this.s_pCSCB, D3D11Utils.CalcSubresource(0, 0, 1), null, cbCS, 4 * 4, 4 * 4); // Scatter vertex TriID, IndexID this.RunComputeShader( this.s_pScatterVertexTriIDIndexIDCS, aRViews, null, this.s_pCSCB, this.m_pScatterVertexBufUAV, (uint)Math.Ceiling(this.m_nVertices / 3 / 128.0f), 1U, 1U); // Scatter index TriID, IndexID this.RunComputeShader( this.s_pScatterIndexTriIDIndexIDCS, aRViews, null, this.s_pCSCB, this.m_pScatterIndexBufUAV, (uint)Math.Ceiling(this.m_nVertices / 3 / 128.0f), 1U, 1U); } // Turn on this and set a breakpoint on the line beginning with "p = " and see what has been written to m_pScatterVertexBuf if (DebugEnabled) { #pragma warning disable IDE0059 // Assignation inutile d'une valeur var p = this.CreateAndCopyToDebugBuf <(uint v, uint t)>(this.m_pScatterVertexBuf); #pragma warning restore IDE0059 // Assignation inutile d'une valeur } // Tessellate vertex { uint[] cbCS = new uint[] { num_tessed_vertices, 0, 0, 0 }; d3dContext.UpdateSubresource( this.s_pCSCB, D3D11Utils.CalcSubresource(0, 0, 1), null, cbCS, 4 * 4, 4 * 4); this.RunComputeShader( this.s_pTessVerticesCSs[(int)this.PartitioningMode], new[] { this.m_pScatterVertexBufSRV, this.m_pEdgeFactorBufSRV }, this.s_pLookupTableCSCB, this.s_pCSCB, this.m_pTessedVerticesBufUAV, (uint)Math.Ceiling(num_tessed_vertices / 128.0f), 1U, 1U); } // Turn on this and set a breakpoint on the line beginning with "p = " and see what has been written to *ppTessedVerticesBuf if (DebugEnabled) { #pragma warning disable IDE0059 // Assignation inutile d'une valeur var p = this.CreateAndCopyToDebugBuf <(uint id, float u, float v)>(ppTessedVerticesBuf); #pragma warning restore IDE0059 // Assignation inutile d'une valeur } // Tessellate indices { uint[] cbCS = new uint[] { num_tessed_indices, 0, 0, 0 }; d3dContext.UpdateSubresource( this.s_pCSCB, D3D11Utils.CalcSubresource(0, 0, 1), null, cbCS, 4 * 4, 4 * 4); this.RunComputeShader( this.s_pTessIndicesCSs[(int)this.PartitioningMode], new[] { this.m_pScatterIndexBufSRV, this.m_pEdgeFactorBufSRV, this.m_pScanBuf0SRV }, this.s_pLookupTableCSCB, this.s_pCSCB, this.m_pTessedIndicesBufUAV, (uint)Math.Ceiling(num_tessed_indices / 128.0f), 1U, 1U); } // Turn on this and set a breakpoint on the line beginning with "p = " and see what has been written to *ppTessedIndicesBuf if (DebugEnabled) { #pragma warning disable IDE0059 // Assignation inutile d'une valeur var p = this.CreateAndCopyToDebugBuf <int>(ppTessedIndicesBuf); #pragma warning restore IDE0059 // Assignation inutile d'une valeur } }
static void CreateResources() { var d3dDevice = deviceResources.D3DDevice; // Create the Bitonic Sort Compute Shader g_pComputeShaderBitonic = d3dDevice.CreateComputeShader(File.ReadAllBytes("CSSortBitonic.cso"), null); // Create the Matrix Transpose Compute Shader g_pComputeShaderTranspose = d3dDevice.CreateComputeShader(File.ReadAllBytes("CSSortTranspose.cso"), null); // Create the Const Buffer var constantBufferDesc = new D3D11BufferDesc(ConstantBufferData.Size, D3D11BindOptions.ConstantBuffer); g_pCB = d3dDevice.CreateBuffer(constantBufferDesc); // Create the Buffer of Elements // Create 2 buffers for switching between when performing the transpose var bufferDesc = new D3D11BufferDesc( NUM_ELEMENTS * sizeof(uint), D3D11BindOptions.UnorderedAccess | D3D11BindOptions.ShaderResource, D3D11Usage.Default, D3D11CpuAccessOptions.None, D3D11ResourceMiscOptions.BufferStructured, sizeof(uint)); g_pBuffer1 = d3dDevice.CreateBuffer(bufferDesc); g_pBuffer2 = d3dDevice.CreateBuffer(bufferDesc); // Create the Shader Resource View for the Buffers // This is used for reading the buffer during the transpose var srvbufferDesc = new D3D11ShaderResourceViewDesc(D3D11SrvDimension.Buffer, DxgiFormat.Unknown) { Buffer = new D3D11BufferSrv { ElementWidth = NUM_ELEMENTS } }; g_pBuffer1SRV = d3dDevice.CreateShaderResourceView(g_pBuffer1, srvbufferDesc); g_pBuffer2SRV = d3dDevice.CreateShaderResourceView(g_pBuffer2, srvbufferDesc); // Create the Unordered Access View for the Buffers // This is used for writing the buffer during the sort and transpose var uavbufferDesc = new D3D11UnorderedAccessViewDesc(D3D11UavDimension.Buffer, DxgiFormat.Unknown) { Buffer = new D3D11BufferUav { NumElements = NUM_ELEMENTS } }; g_pBuffer1UAV = d3dDevice.CreateUnorderedAccessView(g_pBuffer1, uavbufferDesc); g_pBuffer2UAV = d3dDevice.CreateUnorderedAccessView(g_pBuffer2, uavbufferDesc); // Create the Readback Buffer // This is used to read the results back to the CPU var readbackBufferDesc = new D3D11BufferDesc( NUM_ELEMENTS * sizeof(uint), D3D11BindOptions.None, D3D11Usage.Staging, D3D11CpuAccessOptions.Read, D3D11ResourceMiscOptions.None, sizeof(uint)); g_pReadBackBuffer = d3dDevice.CreateBuffer(readbackBufferDesc); }
protected override void CreateDeviceDependentResources() { base.CreateDeviceDependentResources(); byte[] vertexShaderBytecode = File.ReadAllBytes(Lesson4Game.ShadersDirectory + "Textures.VertexShader.cso"); this.vertexShader = this.DeviceResources.D3DDevice.CreateVertexShader(vertexShaderBytecode, null); D3D11InputElementDesc[] basicVertexLayoutDesc = new D3D11InputElementDesc[] { new D3D11InputElementDesc { SemanticName = "POSITION", SemanticIndex = 0, Format = DxgiFormat.R32G32B32Float, InputSlot = 0, AlignedByteOffset = 0, InputSlotClass = D3D11InputClassification.PerVertexData, InstanceDataStepRate = 0 }, new D3D11InputElementDesc { SemanticName = "NORMAL", SemanticIndex = 0, Format = DxgiFormat.R32G32B32Float, InputSlot = 0, AlignedByteOffset = 12, InputSlotClass = D3D11InputClassification.PerVertexData, InstanceDataStepRate = 0 }, new D3D11InputElementDesc { SemanticName = "TEXCOORD", SemanticIndex = 0, Format = DxgiFormat.R32G32Float, InputSlot = 0, AlignedByteOffset = 24, InputSlotClass = D3D11InputClassification.PerVertexData, InstanceDataStepRate = 0 } }; this.inputLayout = this.DeviceResources.D3DDevice.CreateInputLayout(basicVertexLayoutDesc, vertexShaderBytecode); byte[] pixelShaderBytecode = File.ReadAllBytes(Lesson4Game.ShadersDirectory + "Textures.PixelShader.cso"); this.pixelShader = this.DeviceResources.D3DDevice.CreatePixelShader(pixelShaderBytecode, null); var vertexBufferDesc = D3D11BufferDesc.From(cubeVertices, D3D11BindOptions.VertexBuffer); this.vertexBuffer = this.DeviceResources.D3DDevice.CreateBuffer(vertexBufferDesc, cubeVertices, 0, 0); var indexBufferDesc = D3D11BufferDesc.From(cubeIndices, D3D11BindOptions.IndexBuffer); this.indexBuffer = this.DeviceResources.D3DDevice.CreateBuffer(indexBufferDesc, cubeIndices, 0, 0); var constantBufferDesc = new D3D11BufferDesc(ConstantBufferData.Size, D3D11BindOptions.ConstantBuffer); this.constantBuffer = this.DeviceResources.D3DDevice.CreateBuffer(constantBufferDesc); this.constantBufferData.View = new Float4X4( -1.00000000f, 0.00000000f, 0.00000000f, 0.00000000f, 0.00000000f, 0.89442718f, 0.44721359f, 0.00000000f, 0.00000000f, 0.44721359f, -0.89442718f, -2.23606800f, 0.00000000f, 0.00000000f, 0.00000000f, 1.00000000f ); byte[] textureData = File.ReadAllBytes("../../texturedata.bin"); D3D11Texture2DDesc textureDesc = new D3D11Texture2DDesc(DxgiFormat.R8G8B8A8UNorm, 256, 256, 1, 1); D3D11SubResourceData[] textureSubResData = new[] { new D3D11SubResourceData(textureData, 1024) }; using (var texture = this.DeviceResources.D3DDevice.CreateTexture2D(textureDesc, textureSubResData)) { D3D11ShaderResourceViewDesc textureViewDesc = new D3D11ShaderResourceViewDesc { Format = textureDesc.Format, ViewDimension = D3D11SrvDimension.Texture2D, Texture2D = new D3D11Texture2DSrv { MipLevels = textureDesc.MipLevels, MostDetailedMip = 0 } }; this.textureView = this.DeviceResources.D3DDevice.CreateShaderResourceView(texture, textureViewDesc); } D3D11SamplerDesc samplerDesc = new D3D11SamplerDesc( D3D11Filter.Anisotropic, D3D11TextureAddressMode.Wrap, D3D11TextureAddressMode.Wrap, D3D11TextureAddressMode.Wrap, 0.0f, this.DeviceResources.D3DFeatureLevel > D3D11FeatureLevel.FeatureLevel91 ? D3D11Constants.DefaultMaxAnisotropy : D3D11Constants.FeatureLevel91DefaultMaxAnisotropy, D3D11ComparisonFunction.Never, new float[] { 0.0f, 0.0f, 0.0f, 0.0f }, 0.0f, float.MaxValue); this.sampler = this.DeviceResources.D3DDevice.CreateSamplerState(samplerDesc); }
public void SetBaseMesh(uint nVertices, D3D11Buffer pBaseVB) { var d3dDevice = this.deviceResources.D3DDevice; this.m_nVertices = nVertices; // shader resource view of base mesh vertex data this.m_pBaseVBSRV = d3dDevice.CreateShaderResourceView(pBaseVB, new D3D11ShaderResourceViewDesc { ViewDimension = D3D11SrvDimension.Buffer, Format = DxgiFormat.R32G32B32A32Float, Buffer = new D3D11BufferSrv { FirstElement = 0, NumElements = this.m_nVertices } }); // Buffer for edge tessellation factor this.m_pEdgeFactorBuf = d3dDevice.CreateBuffer(new D3D11BufferDesc { BindOptions = D3D11BindOptions.ShaderResource | D3D11BindOptions.UnorderedAccess, ByteWidth = 4 * 4 * this.m_nVertices / 3, StructureByteStride = 4 * 4, MiscOptions = D3D11ResourceMiscOptions.BufferStructured, Usage = D3D11Usage.Default }); // shader resource view of the buffer above this.m_pEdgeFactorBufSRV = d3dDevice.CreateShaderResourceView(this.m_pEdgeFactorBuf, new D3D11ShaderResourceViewDesc { ViewDimension = D3D11SrvDimension.Buffer, Format = DxgiFormat.Unknown, Buffer = new D3D11BufferSrv { FirstElement = 0, NumElements = this.m_nVertices / 3 } }); // UAV of the buffer above this.m_pEdgeFactorBufUAV = d3dDevice.CreateUnorderedAccessView(this.m_pEdgeFactorBuf, new D3D11UnorderedAccessViewDesc { ViewDimension = D3D11UavDimension.Buffer, Format = DxgiFormat.Unknown, Buffer = new D3D11BufferUav { FirstElement = 0, NumElements = this.m_nVertices / 3 } }); // Buffers for scan this.m_pScanBuf0 = d3dDevice.CreateBuffer(new D3D11BufferDesc { BindOptions = D3D11BindOptions.ShaderResource | D3D11BindOptions.UnorderedAccess, ByteWidth = 4 * 2 * this.m_nVertices / 3, StructureByteStride = 4 * 2, MiscOptions = D3D11ResourceMiscOptions.BufferStructured, Usage = D3D11Usage.Default }); this.m_pScanBuf1 = d3dDevice.CreateBuffer(new D3D11BufferDesc { BindOptions = D3D11BindOptions.ShaderResource | D3D11BindOptions.UnorderedAccess, ByteWidth = 4 * 2 * this.m_nVertices / 3, StructureByteStride = 4 * 2, MiscOptions = D3D11ResourceMiscOptions.BufferStructured, Usage = D3D11Usage.Default }); // shader resource views of the scan buffers this.m_pScanBuf0SRV = d3dDevice.CreateShaderResourceView(this.m_pScanBuf0, new D3D11ShaderResourceViewDesc { ViewDimension = D3D11SrvDimension.Buffer, Format = DxgiFormat.Unknown, Buffer = new D3D11BufferSrv { FirstElement = 0, NumElements = this.m_nVertices / 3 } }); this.m_pScanBuf1SRV = d3dDevice.CreateShaderResourceView(this.m_pScanBuf1, new D3D11ShaderResourceViewDesc { ViewDimension = D3D11SrvDimension.Buffer, Format = DxgiFormat.Unknown, Buffer = new D3D11BufferSrv { FirstElement = 0, NumElements = this.m_nVertices / 3 } }); // UAV of the scan buffers this.m_pScanBuf0UAV = d3dDevice.CreateUnorderedAccessView(this.m_pScanBuf0, new D3D11UnorderedAccessViewDesc { ViewDimension = D3D11UavDimension.Buffer, Format = DxgiFormat.Unknown, Buffer = new D3D11BufferUav { FirstElement = 0, NumElements = this.m_nVertices / 3 } }); this.m_pScanBuf1UAV = d3dDevice.CreateUnorderedAccessView(this.m_pScanBuf1, new D3D11UnorderedAccessViewDesc { ViewDimension = D3D11UavDimension.Buffer, Format = DxgiFormat.Unknown, Buffer = new D3D11BufferUav { FirstElement = 0, NumElements = this.m_nVertices / 3 } }); }
private void CreateParticlePosVeloBuffers() { var d3dDevice = this.deviceResources.D3DDevice; // Initialize the data in the buffers Particle[] pData1 = new Particle[MaxParticles]; Random rand = this.Random ?? new Random(0); if (this.DiskGalaxyFormationType == 0) { // Disk Galaxy Formation float fCenterSpread = Spread * 0.50f; LoadParticles( rand, pData1, 0, new XMFloat3(fCenterSpread, 0, 0), new XMFloat4(0, 0, -20, 1 / 10000.0f / 10000.0f), Spread, pData1.Length / 2); LoadParticles( rand, pData1, pData1.Length / 2, new XMFloat3(-fCenterSpread, 0, 0), new XMFloat4(0, 0, 20, 1 / 10000.0f / 10000.0f), Spread, pData1.Length - pData1.Length / 2); } else { // Disk Galaxy Formation with impacting third cluster LoadParticles( rand, pData1, 0, new XMFloat3(Spread, 0, 0), new XMFloat4(0, 0, -8, 1 / 10000.0f / 10000.0f), Spread, pData1.Length / 3); LoadParticles( rand, pData1, pData1.Length / 3, new XMFloat3(-Spread, 0, 0), new XMFloat4(0, 0, 8, 1 / 10000.0f / 10000.0f), Spread, pData1.Length / 3); LoadParticles( rand, pData1, 2 * pData1.Length / 3, new XMFloat3(0, 0, Spread * 15.0f), new XMFloat4(0, 0, -60, 1 / 10000.0f / 10000.0f), Spread, pData1.Length - 2 * pData1.Length / 3); } D3D11BufferDesc desc = D3D11BufferDesc.From(pData1, D3D11BindOptions.UnorderedAccess | D3D11BindOptions.ShaderResource); desc.MiscOptions = D3D11ResourceMiscOptions.BufferStructured; desc.StructureByteStride = Particle.Size; this.g_pParticlePosVelo0 = d3dDevice.CreateBuffer(desc, pData1, 0, 0); this.g_pParticlePosVelo1 = d3dDevice.CreateBuffer(desc, pData1, 0, 0); D3D11ShaderResourceViewDesc DescRV = new D3D11ShaderResourceViewDesc( this.g_pParticlePosVelo0, DxgiFormat.Unknown, 0, desc.ByteWidth / desc.StructureByteStride); this.g_pParticlePosVeloRV0 = d3dDevice.CreateShaderResourceView(this.g_pParticlePosVelo0, DescRV); this.g_pParticlePosVeloRV1 = d3dDevice.CreateShaderResourceView(this.g_pParticlePosVelo1, DescRV); D3D11UnorderedAccessViewDesc DescUAV = new D3D11UnorderedAccessViewDesc( this.g_pParticlePosVelo0, DxgiFormat.Unknown, 0, desc.ByteWidth / desc.StructureByteStride); this.g_pParticlePosVeloUAV0 = d3dDevice.CreateUnorderedAccessView(this.g_pParticlePosVelo0, DescUAV); this.g_pParticlePosVeloUAV1 = d3dDevice.CreateUnorderedAccessView(this.g_pParticlePosVelo1, DescUAV); }
// Use this for initialization void Start() { NewTextureForRender(); if (Application.isPlaying) { if (MicroLightManager.Instance) { switch (MicroLightManager.Instance.mRenderType) { case RendererType.MicroLightRender: { //Create Shared Texture2D LeftRT2D = MicroLightPlugin.D3D11Helper.CreateSharedView(MicroLightManager.Instance.m_UnityDevice, DXGI_FORMAT.DXGI_FORMAT_B8G8R8A8_UNORM, (int)TextureSize.x, (int)TextureSize.y); if (LeftRT2D == IntPtr.Zero) { Debug.Log(this + " LeftRT2D is null"); } HANDLE LeftRTHandleSend = MicroLightPlugin.D3D11Helper.GetSharedHandle(MicroLightManager.Instance.m_UnityDevice, LeftRT2D); if (LeftRTHandleSend == IntPtr.Zero) { Debug.Log(this + " LeftRTHandleSend is null"); } D3D11Resource LeftRTHandleReceive = MicroLightPlugin.D3D11Helper.OpenSharedResource(MicroLightManager.Instance.m_Device, LeftRTHandleSend); if (LeftRTHandleReceive == IntPtr.Zero) { Debug.Log(this + " LeftRTHandleReceive is null"); } RightRT2D = MicroLightPlugin.D3D11Helper.CreateSharedView(MicroLightManager.Instance.m_UnityDevice, DXGI_FORMAT.DXGI_FORMAT_B8G8R8A8_UNORM, (int)TextureSize.x, (int)TextureSize.y); if (RightRT2D == IntPtr.Zero) { Debug.Log(this + " RightRT2D is null"); } HANDLE RightRTHandleSend = MicroLightPlugin.D3D11Helper.GetSharedHandle(MicroLightManager.Instance.m_UnityDevice, RightRT2D); if (RightRTHandleSend == IntPtr.Zero) { Debug.Log(this + " RightRTHandleSend is null"); } D3D11Resource RightRTHandleReceive = MicroLightPlugin.D3D11Helper.OpenSharedResource(MicroLightManager.Instance.m_Device, RightRTHandleSend); if (RightRTHandleSend == IntPtr.Zero) { Debug.Log(this + " RightRTHandleReceive is null"); } leftView = MicroLightPlugin.D3D11Helper.CreateShaderResourceView(MicroLightManager.Instance.m_Device, LeftRTHandleReceive); rightView = MicroLightPlugin.D3D11Helper.CreateShaderResourceView(MicroLightManager.Instance.m_Device, RightRTHandleReceive); if (leftView == IntPtr.Zero) { UnityEngine.Debug.Log("leftView is null"); } if (rightView == IntPtr.Zero) { UnityEngine.Debug.Log("rightView is null"); } switch (MicroLightManager.Instance.mRenderMode) { case RenderMode.LR3D: { MicroLightPlugin.Render.AddView(MicroLightManager.Instance.m_RenderAPI, ((int)id * 10 + (int)LeftEye.mEyeTye), leftView, rightView, 0.5f, 1.0f, -0.25f, 0); MicroLightPlugin.Render.AddView(MicroLightManager.Instance.m_RenderAPI, ((int)id * 10 + (int)RightEye.mEyeTye), rightView, leftView, 0.5f, 1.0f, 0.25f, 0); } break; case RenderMode.Stereo: { switch (id) { case TrackingSpaceId.Surface: MicroLightPlugin.Render.AddView(MicroLightManager.Instance.m_RenderAPI, (int)id, leftView, rightView, 1, 1, 0, 0); break; case TrackingSpaceId.LTypeRoomFront: MicroLightPlugin.Render.AddView(MicroLightManager.Instance.m_RenderAPI, (int)id, leftView, rightView, 0.5f, 1.0f, -0.25f, 0); break; case TrackingSpaceId.LTypeRoomFloor: MicroLightPlugin.Render.AddView(MicroLightManager.Instance.m_RenderAPI, (int)id, leftView, rightView, 0.5f, 1.0f, 0.25f, 0); break; case TrackingSpaceId.TrapezoidRoomLeft: MicroLightPlugin.Render.AddView(MicroLightManager.Instance.m_RenderAPI, (int)id, leftView, rightView, 0.25f, 1.0f, -0.375f, 0); break; case TrackingSpaceId.TrapezoidRoomFront: MicroLightPlugin.Render.AddView(MicroLightManager.Instance.m_RenderAPI, (int)id, leftView, rightView, 0.25f, 1.0f, -0.125f, 0); break; case TrackingSpaceId.TrapezoidRoomRight: MicroLightPlugin.Render.AddView(MicroLightManager.Instance.m_RenderAPI, (int)id, leftView, rightView, 0.25f, 1.0f, 0.125f, 0); break; #if MicroLightGridView case TrackingSpaceId.TrapezoidRoomFloor: MicroLightPlugin.Render.AddView(MicroLightManager.Instance.m_RenderAPI, (int)id + 1, leftView, rightView, 0.25f, 1.0f, 0.375f, 0); break; #else case TrackingSpaceId.TrapezoidRoomFloor: MicroLightPlugin.Render.AddView(MicroLightManager.Instance.m_RenderAPI, (int)id, leftView, rightView, 0.25f, 1.0f, 0.375f, 0); break; #endif } } break; } } break; case RendererType.UnityRender: { leftView = MicroLightPlugin.D3D11Helper.CreateShaderResourceViewFromRenderTexture(MicroLightManager.Instance.m_UnityDevice, LeftRT.GetNativeTexturePtr(), DXGI_FORMAT.DXGI_FORMAT_B8G8R8A8_UNORM); rightView = MicroLightPlugin.D3D11Helper.CreateShaderResourceViewFromRenderTexture(MicroLightManager.Instance.m_UnityDevice, RightRT.GetNativeTexturePtr(), DXGI_FORMAT.DXGI_FORMAT_B8G8R8A8_UNORM); if (leftView == IntPtr.Zero) { UnityEngine.Debug.Log("leftView is null"); } if (rightView == IntPtr.Zero) { UnityEngine.Debug.Log("rightView is null"); } switch (MicroLightManager.Instance.mRenderMode) { case RenderMode.LR3D: MicroLightPlugin.Render.AddView(MicroLightManager.Instance.m_UnityRenderAPI, ((int)id * 10 + (int)LeftEye.mEyeTye), leftView, rightView, 0.5f, 1.0f, -0.25f, 0); MicroLightPlugin.Render.AddView(MicroLightManager.Instance.m_UnityRenderAPI, ((int)id * 10 + (int)RightEye.mEyeTye), rightView, leftView, 0.5f, 1.0f, 0.25f, 0); break; case RenderMode.Stereo: switch (id) { case TrackingSpaceId.Surface: UnityNativePlugin.Render.AddView(MicroLightManager.Instance.m_UnityRenderAPI, (int)id, leftView, rightView, 1, 1, 0, 0); break; case TrackingSpaceId.LTypeRoomFront: UnityNativePlugin.Render.AddView(MicroLightManager.Instance.m_UnityRenderAPI, (int)id, leftView, rightView, 0.5f, 1.0f, -0.25f, 0); break; case TrackingSpaceId.LTypeRoomFloor: UnityNativePlugin.Render.AddView(MicroLightManager.Instance.m_UnityRenderAPI, (int)id, leftView, rightView, 0.5f, 1.0f, 0.25f, 0); break; case TrackingSpaceId.TrapezoidRoomLeft: UnityNativePlugin.Render.AddView(MicroLightManager.Instance.m_UnityRenderAPI, (int)id, leftView, rightView, 0.25f, 1.0f, -0.375f, 0); break; case TrackingSpaceId.TrapezoidRoomFront: UnityNativePlugin.Render.AddView(MicroLightManager.Instance.m_UnityRenderAPI, (int)id, leftView, rightView, 0.25f, 1.0f, -0.125f, 0); break; case TrackingSpaceId.TrapezoidRoomRight: UnityNativePlugin.Render.AddView(MicroLightManager.Instance.m_UnityRenderAPI, (int)id, leftView, rightView, 0.25f, 1.0f, 0.125f, 0); break; #if MicroLightGridView case TrackingSpaceId.TrapezoidRoomFloor: UnityNativePlugin.Render.AddView(MicroLightManager.Instance.m_UnityRenderAPI, (int)id + 1, leftView, rightView, 0.25f, 1.0f, 0.375f, 0); break; #else case TrackingSpaceId.TrapezoidRoomFloor: UnityNativePlugin.Render.AddView(MicroLightManager.Instance.m_UnityRenderAPI, (int)id, leftView, rightView, 0.25f, 1.0f, 0.375f, 0); break; #endif } break; } } break; case RendererType.UnityCoverRender: { leftView = MicroLightPlugin.D3D11Helper.CreateShaderResourceViewFromRenderTexture(MicroLightManager.Instance.m_UnityDevice, LeftRT.GetNativeTexturePtr(), DXGI_FORMAT.DXGI_FORMAT_B8G8R8A8_UNORM); rightView = MicroLightPlugin.D3D11Helper.CreateShaderResourceViewFromRenderTexture(MicroLightManager.Instance.m_UnityDevice, RightRT.GetNativeTexturePtr(), DXGI_FORMAT.DXGI_FORMAT_B8G8R8A8_UNORM); if (leftView == IntPtr.Zero) { UnityEngine.Debug.Log("leftView is null"); } if (rightView == IntPtr.Zero) { UnityEngine.Debug.Log("rightView is null"); } switch (MicroLightManager.Instance.mRenderMode) { case RenderMode.LR3D: UnityNativePlugin.CoverRender.AddView(MicroLightManager.Instance.m_CoverRenderAPI, ((int)id * 10 + (int)LeftEye.mEyeTye), leftView, rightView, 0.5f, 1.0f, -0.25f, 0); UnityNativePlugin.CoverRender.AddView(MicroLightManager.Instance.m_CoverRenderAPI, ((int)id * 10 + (int)RightEye.mEyeTye), rightView, leftView, 0.5f, 1.0f, 0.25f, 0); break; case RenderMode.Stereo: switch (id) { case TrackingSpaceId.Surface: UnityNativePlugin.CoverRender.AddView(MicroLightManager.Instance.m_UnityRenderAPI, (int)id, leftView, rightView, 1, 1, 0, 0); break; case TrackingSpaceId.LTypeRoomFront: UnityNativePlugin.CoverRender.AddView(MicroLightManager.Instance.m_UnityRenderAPI, (int)id, leftView, rightView, 0.5f, 1.0f, -0.25f, 0); break; case TrackingSpaceId.LTypeRoomFloor: UnityNativePlugin.CoverRender.AddView(MicroLightManager.Instance.m_UnityRenderAPI, (int)id, leftView, rightView, 0.5f, 1.0f, 0.25f, 0); break; case TrackingSpaceId.TrapezoidRoomLeft: UnityNativePlugin.CoverRender.AddView(MicroLightManager.Instance.m_UnityRenderAPI, (int)id, leftView, rightView, 0.25f, 1.0f, -0.375f, 0); break; case TrackingSpaceId.TrapezoidRoomFront: UnityNativePlugin.CoverRender.AddView(MicroLightManager.Instance.m_UnityRenderAPI, (int)id, leftView, rightView, 0.25f, 1.0f, -0.125f, 0); break; case TrackingSpaceId.TrapezoidRoomRight: UnityNativePlugin.CoverRender.AddView(MicroLightManager.Instance.m_UnityRenderAPI, (int)id, leftView, rightView, 0.25f, 1.0f, 0.125f, 0); break; #if MicroLightGridView case TrackingSpaceId.TrapezoidRoomFloor: UnityNativePlugin.CoverRender.AddView(MicroLightManager.Instance.m_UnityRenderAPI, (int)id + 1, leftView, rightView, 0.25f, 1.0f, 0.375f, 0); break; #else case TrackingSpaceId.TrapezoidRoomFloor: UnityNativePlugin.CoverRender.AddView(MicroLightManager.Instance.m_UnityRenderAPI, (int)id, leftView, rightView, 0.25f, 1.0f, 0.375f, 0); break; #endif } break; } } break; } } } }
private void CreateTexture(byte[] data, uint width, uint height, out D3D11Texture2D texture, out D3D11ShaderResourceView textureView) { D3D11Texture2DDesc textureDesc = new D3D11Texture2DDesc(DxgiFormat.R8G8B8A8UNorm, width, height, 1, 1); D3D11SubResourceData[] textureSubResData = new[] { new D3D11SubResourceData(data, width * 4) }; D3D11Texture2D texture2D = this.d3dDevice.CreateTexture2D(textureDesc, textureSubResData); D3D11ShaderResourceView shaderResourceView; try { D3D11ShaderResourceViewDesc textureViewDesc = new D3D11ShaderResourceViewDesc { Format = textureDesc.Format, ViewDimension = D3D11SrvDimension.Texture2D, Texture2D = new D3D11Texture2DSrv { MipLevels = textureDesc.MipLevels, MostDetailedMip = 0 } }; shaderResourceView = this.d3dDevice.CreateShaderResourceView(texture2D, textureViewDesc); } catch { D3D11Utils.DisposeAndNull(ref texture2D); throw; } texture = texture2D; textureView = shaderResourceView; }
public static extern bool SubmitSharedView(D3D11Device device, RednerTextureIntPtr source, D3D11ShaderResourceView resource);
public void LoadTexture(string filename, uint width, uint height, out D3D11Texture2D texture, out D3D11ShaderResourceView textureView) { byte[] textureData = File.ReadAllBytes(filename); this.CreateTexture(textureData, width, height, out texture, out textureView); }
static void Main(string[] args) { try { Console.Write("Creating device..."); CreateComputeDevice(); Console.WriteLine("done"); Console.Write("Creating Compute Shader..."); CreateComputeShader(); Console.WriteLine("done"); Console.Write("Creating buffers and filling them with initial data..."); for (int i = 0; i < NUM_ELEMENTS; ++i) { g_vBuf0[i].i = i; g_vBuf0[i].f = (float)i; #if TEST_DOUBLE g_vBuf0[i].d = (double)i; #endif g_vBuf1[i].i = i; g_vBuf1[i].f = (float)i; #if TEST_DOUBLE g_vBuf1[i].d = (double)i; #endif } #if USE_STRUCTURED_BUFFERS g_pBuf0 = CreateStructuredBuffer(deviceResources.D3DDevice, g_vBuf0); g_pBuf1 = CreateStructuredBuffer(deviceResources.D3DDevice, g_vBuf1); g_pBufResult = CreateStructuredBuffer(deviceResources.D3DDevice, new BufType[NUM_ELEMENTS]); #else g_pBuf0 = CreateRawBuffer(deviceResources.D3DDevice, g_vBuf0); g_pBuf1 = CreateRawBuffer(deviceResources.D3DDevice, g_vBuf1); g_pBufResult = CreateRawBuffer(deviceResources.D3DDevice, new BufType[NUM_ELEMENTS]); #endif #if DEBUG g_pBuf0?.SetDebugName("Buffer0"); g_pBuf1?.SetDebugName("Buffer1"); g_pBufResult?.SetDebugName("Result"); #endif Console.WriteLine("done"); Console.Write("Creating buffer views..."); g_pBuf0SRV = CreateBufferSRV(deviceResources.D3DDevice, g_pBuf0); g_pBuf1SRV = CreateBufferSRV(deviceResources.D3DDevice, g_pBuf1); g_pBufResultUAV = CreateBufferUAV(deviceResources.D3DDevice, g_pBufResult); #if DEBUG g_pBuf0SRV?.SetDebugName("Buffer0 SRV"); g_pBuf1SRV?.SetDebugName("Buffer1 SRV"); g_pBufResultUAV?.SetDebugName("Result UAV"); #endif Console.WriteLine("done"); Console.Write("Running Compute Shader..."); RunComputeShader(deviceResources.D3DContext, g_pCS, new[] { g_pBuf0SRV, g_pBuf1SRV }, g_pBufResultUAV, NUM_ELEMENTS, 1, 1); Console.WriteLine("done"); // Read back the result from GPU, verify its correctness against result computed by CPU D3D11Buffer debugbuf = CreateAndCopyToDebugBuf(deviceResources.D3DDevice, deviceResources.D3DContext, g_pBufResult); try { D3D11MappedSubResource mappedResource = deviceResources.D3DContext.Map(debugbuf, 0, D3D11MapCpuPermission.Read, D3D11MapOptions.None); try { // Set a break point here and put down the expression "p, 1024" in your watch window to see what has been written out by our CS // This is also a common trick to debug CS programs. // Verify that if Compute Shader has done right Console.Write("Verifying against CPU result..."); bool bSuccess = true; for (int i = 0; i < NUM_ELEMENTS; ++i) { BufType p = Marshal.PtrToStructure <BufType>(mappedResource.Data + i * (int)BufType.Size); if ((p.i != g_vBuf0[i].i + g_vBuf1[i].i) || (p.f != g_vBuf0[i].f + g_vBuf1[i].f) #if TEST_DOUBLE || (p.d != g_vBuf0[i].d + g_vBuf1[i].d) #endif ) { Console.WriteLine("failure"); bSuccess = false; break; } } if (bSuccess) { Console.WriteLine("succeeded"); } } finally { deviceResources.D3DContext.Unmap(debugbuf, 0); } } finally { D3D11Utils.ReleaseAndNull(ref debugbuf); } } catch (Exception ex) { Console.WriteLine(ex); } finally { Console.Write("Cleaning up..."); CleanupResources(); Console.WriteLine("done"); } Console.ReadKey(false); }
private static void CreateTexture(D3D11Device device, D3D11DeviceContext deviceContext, string fileName, out D3D11ShaderResourceView textureView) { if (!File.Exists(fileName)) { textureView = null; return; } string ext = Path.GetExtension(fileName); if (string.Equals(ext, ".dds", StringComparison.OrdinalIgnoreCase)) { DdsDirectX.CreateTexture(fileName, device, deviceContext, out textureView); } else if (string.Equals(ext, ".jpg", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".bmp", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".png", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".gif", StringComparison.OrdinalIgnoreCase)) { CreateBitmapTexture(device, fileName, out textureView); } else { throw new NotSupportedException(); } }
public void CreateDeviceDependentResources(DeviceResources resources) { this.deviceResources = resources; byte[] renderSceneVertexShaderBytecode = File.ReadAllBytes("RenderSceneVertexShader.cso"); this.g_pSceneVS = this.deviceResources.D3DDevice.CreateVertexShader(renderSceneVertexShaderBytecode, null); D3D11InputElementDesc[] layoutDesc = new D3D11InputElementDesc[] { new D3D11InputElementDesc { SemanticName = "POSITION", SemanticIndex = 0, Format = DxgiFormat.R32G32B32Float, InputSlot = 0, AlignedByteOffset = 0, InputSlotClass = D3D11InputClassification.PerVertexData, InstanceDataStepRate = 0 }, new D3D11InputElementDesc { SemanticName = "NORMAL", SemanticIndex = 0, Format = DxgiFormat.R32G32B32Float, InputSlot = 0, AlignedByteOffset = 12, InputSlotClass = D3D11InputClassification.PerVertexData, InstanceDataStepRate = 0 }, new D3D11InputElementDesc { SemanticName = "TEXTURE", SemanticIndex = 0, Format = DxgiFormat.R32G32Float, InputSlot = 0, AlignedByteOffset = 24, InputSlotClass = D3D11InputClassification.PerVertexData, InstanceDataStepRate = 0 } }; this.g_pSceneVertexLayout = this.deviceResources.D3DDevice.CreateInputLayout(layoutDesc, renderSceneVertexShaderBytecode); byte[] renderScenePixelShaderBytecode = File.ReadAllBytes("RenderScenePixelShader.cso"); this.g_pScenePS = this.deviceResources.D3DDevice.CreatePixelShader(renderScenePixelShaderBytecode, null); byte[] renderSceneShadowMapVertexShaderBytecode = File.ReadAllBytes("RenderSceneShadowMapVertexShader.cso"); this.g_pShadowMapVS = this.deviceResources.D3DDevice.CreateVertexShader(renderSceneShadowMapVertexShaderBytecode, null); this.g_SceneMesh = SdkMeshFile.FromFile(this.deviceResources.D3DDevice, this.deviceResources.D3DContext, @"ColumnScene\scene.sdkmesh"); this.g_Poles = SdkMeshFile.FromFile(this.deviceResources.D3DDevice, this.deviceResources.D3DContext, @"ColumnScene\poles.sdkmesh"); this.g_pcbConstants = this.deviceResources.D3DDevice.CreateBuffer( new D3D11BufferDesc(ConstantBufferConstants.Size, D3D11BindOptions.ConstantBuffer)); D3D11SamplerDesc samplerDesc = new D3D11SamplerDesc( D3D11Filter.ComparisonMinMagMipPoint, D3D11TextureAddressMode.Border, D3D11TextureAddressMode.Border, D3D11TextureAddressMode.Border, 0.0f, 1, D3D11ComparisonFunction.LessEqual, new float[] { 1.0f, 1.0f, 1.0f, 1.0f }, 0.0f, float.MaxValue); // PointCmp this.g_pSamplePointCmp = this.deviceResources.D3DDevice.CreateSamplerState(samplerDesc); // Point samplerDesc.Filter = D3D11Filter.MinMagMipPoint; samplerDesc.ComparisonFunction = D3D11ComparisonFunction.Always; this.g_pSamplePoint = this.deviceResources.D3DDevice.CreateSamplerState(samplerDesc); // Linear samplerDesc.Filter = D3D11Filter.MinMagMipLinear; samplerDesc.AddressU = D3D11TextureAddressMode.Wrap; samplerDesc.AddressV = D3D11TextureAddressMode.Wrap; samplerDesc.AddressW = D3D11TextureAddressMode.Wrap; this.g_pSampleLinear = this.deviceResources.D3DDevice.CreateSamplerState(samplerDesc); // Create a blend state to disable alpha blending D3D11BlendDesc blendDesc = D3D11BlendDesc.Default; blendDesc.IsIndependentBlendEnabled = false; D3D11RenderTargetBlendDesc[] blendDescRenderTargets = blendDesc.GetRenderTargets(); blendDescRenderTargets[0].IsBlendEnabled = false; blendDescRenderTargets[0].RenderTargetWriteMask = D3D11ColorWriteEnables.All; blendDesc.SetRenderTargets(blendDescRenderTargets); this.g_pBlendStateNoBlend = this.deviceResources.D3DDevice.CreateBlendState(blendDesc); blendDescRenderTargets[0].RenderTargetWriteMask = D3D11ColorWriteEnables.None; blendDesc.SetRenderTargets(blendDescRenderTargets); this.g_pBlendStateColorWritesOff = this.deviceResources.D3DDevice.CreateBlendState(blendDesc); // textures / rts D3D11Texture2DDesc TDesc = new D3D11Texture2DDesc( DxgiFormat.R16Typeless, (uint)g_fShadowMapWidth, (uint)g_fShadowMapHeight, 1, 1, D3D11BindOptions.DepthStencil | D3D11BindOptions.ShaderResource); this.g_pShadowMapDepthStencilTexture = this.deviceResources.D3DDevice.CreateTexture2D(TDesc); D3D11ShaderResourceViewDesc SRVDesc = new D3D11ShaderResourceViewDesc { Format = DxgiFormat.R16UNorm, ViewDimension = D3D11SrvDimension.Texture2D, Texture2D = new D3D11Texture2DSrv { MipLevels = 1, MostDetailedMip = 0 } }; this.g_pDepthTextureSRV = this.deviceResources.D3DDevice.CreateShaderResourceView(this.g_pShadowMapDepthStencilTexture, SRVDesc); D3D11DepthStencilViewDesc DSVDesc = new D3D11DepthStencilViewDesc { Format = DxgiFormat.D16UNorm, ViewDimension = D3D11DsvDimension.Texture2D, Options = D3D11DepthStencilViewOptions.None, Texture2D = new D3D11Texture2DDsv { MipSlice = 0 } }; this.g_pDepthStencilTextureDSV = this.deviceResources.D3DDevice.CreateDepthStencilView(this.g_pShadowMapDepthStencilTexture, DSVDesc); XMFloat3 vecEye = new XMFloat3(0.95f, 5.83f, -14.48f); XMFloat3 vecAt = new XMFloat3(0.90f, 5.44f, -13.56f); XMFloat3 vecUp = new XMFloat3(0.0f, 1.0f, 0.0f); this.ViewMatrix = XMMatrix.LookAtLH(vecEye, vecAt, vecUp); this.WorldMatrix = XMMatrix.Identity; XMFloat3 vecEyeL = new XMFloat3(0, 0, 0); XMFloat3 vecAtL = new XMFloat3(0, -0.5f, 1); XMFloat3 vecUUpL = new XMFloat3(0.0f, 1.0f, 0.0f); this.LightViewMatrix = XMMatrix.LookAtLH(vecEyeL, vecAtL, vecUUpL); this.LightWorldMatrix = XMMatrix.Identity; }
public void Render() { var context = this.deviceResources.D3DContext; D3D11RenderTargetView[] pRTV = new D3D11RenderTargetView[2]; D3D11ShaderResourceView[] pSRV = new D3D11ShaderResourceView[8]; // Array of our samplers D3D11SamplerState[] ppSamplerStates = new D3D11SamplerState[3] { this.g_pSamplePoint, this.g_pSampleLinear, this.g_pSamplePointCmp }; context.PixelShaderSetSamplers(0, ppSamplerStates); // Store off original render target, this is the back buffer of the swap chain D3D11RenderTargetView pOrigRTV = this.deviceResources.D3DRenderTargetView; D3D11DepthStencilView pOrigDSV = this.deviceResources.D3DDepthStencilView; // Clear the render target float[] ClearColor = { 0.0f, 0.25f, 0.25f, 1.0f }; context.ClearRenderTargetView(this.deviceResources.D3DRenderTargetView, ClearColor); context.ClearDepthStencilView(this.deviceResources.D3DDepthStencilView, D3D11ClearOptions.Depth | D3D11ClearOptions.Stencil, 1.0f, 0); // disable color writes context.OutputMergerSetBlendState(this.g_pBlendStateColorWritesOff, null, 0xffffffff); this.RenderShadowMap(out XMFloat4X4 mViewProjLight, out XMFloat3 vLightDir); // enable color writes context.OutputMergerSetBlendState(this.g_pBlendStateNoBlend, null, 0xffffffff); // Get the projection & view matrix from the camera class XMMatrix mView = this.ViewMatrix; XMMatrix mProj = this.ProjectionMatrix; XMMatrix mWorldViewProjection = mView * mProj; // Setup the constant buffer for the scene vertex shader ConstantBufferConstants pConstants = new ConstantBufferConstants { WorldViewProjection = mWorldViewProjection.Transpose(), WorldViewProjLight = mViewProjLight.ToMatrix().Transpose(), ShadowMapDimensions = new XMFloat4( g_fShadowMapWidth, g_fShadowMapHeight, 1.0f / g_fShadowMapWidth, 1.0f / g_fShadowMapHeight), LightDir = new XMFloat4(vLightDir.X, vLightDir.Y, vLightDir.Z, 0.0f), SunWidth = this.SunWidth }; context.UpdateSubresource(this.g_pcbConstants, 0, null, pConstants, 0, 0); context.VertexShaderSetConstantBuffers(g_iConstantsConstantBufferBind, new[] { this.g_pcbConstants }); context.PixelShaderSetConstantBuffers(g_iConstantsConstantBufferBind, new[] { this.g_pcbConstants }); // Set the shaders context.VertexShaderSetShader(this.g_pSceneVS, null); context.PixelShaderSetShader(this.g_pScenePS, null); // Set the vertex buffer format context.InputAssemblerSetInputLayout(this.g_pSceneVertexLayout); // Rebind to original back buffer and depth buffer pRTV[0] = pOrigRTV; context.OutputMergerSetRenderTargets(pRTV, pOrigDSV); // set the shadow map context.PixelShaderSetShaderResources(1, new[] { this.g_pDepthTextureSRV }); // Render the scene this.g_SceneMesh.Render(0, -1, -1); this.g_Poles.Render(0, -1, -1); // restore resources context.PixelShaderSetShaderResources(0, pSRV); }