private void BuildRootSignature() { var texTable = new DescriptorRange(DescriptorRangeType.ShaderResourceView, 1, 0); var descriptor1 = new RootDescriptor(0, 0); var descriptor2 = new RootDescriptor(1, 0); var descriptor3 = new RootDescriptor(2, 0); // Root parameter can be a table, root descriptor or root constants. // Perfomance TIP: Order from most frequent to least frequent. var slotRootParameters = new[] { new RootParameter(ShaderVisibility.Pixel, texTable), new RootParameter(ShaderVisibility.Vertex, descriptor1, RootParameterType.ConstantBufferView), new RootParameter(ShaderVisibility.All, descriptor2, RootParameterType.ConstantBufferView), new RootParameter(ShaderVisibility.All, descriptor3, RootParameterType.ConstantBufferView) }; // A root signature is an array of root parameters. var rootSigDesc = new RootSignatureDescription( RootSignatureFlags.AllowInputAssemblerInputLayout, slotRootParameters, GetStaticSamplers()); _rootSignature = Device.CreateRootSignature(rootSigDesc.Serialize()); }
public RootSignatureDescription CreateRayGenRootDesc() { // Create the root-signature RootSignatureDescription desc = new RootSignatureDescription(); var descRange = new DescriptorRange[2]; // gOutput descRange[0].BaseShaderRegister = 0; descRange[0].NumDescriptors = 1; descRange[0].RegisterSpace = 0; descRange[0].RangeType = DescriptorRangeType.UnorderedAccessView; descRange[0].OffsetInDescriptorsFromTableStart = 0; // gRTScene descRange[1].BaseShaderRegister = 0; descRange[1].NumDescriptors = 1; descRange[1].RegisterSpace = 0; descRange[1].RangeType = DescriptorRangeType.ShaderResourceView; descRange[1].OffsetInDescriptorsFromTableStart = 1; desc.Parameters = new RootParameter[1]; desc.Parameters[0] = new RootParameter( new RootDescriptorTable(descRange), ShaderVisibility.All); desc.Flags = RootSignatureFlags.LocalRootSignature; return(desc); }
void GetPipelineState() { DescriptorRange[] ranges = new DescriptorRange[] { new DescriptorRange() { RangeType = DescriptorRangeType.ConstantBufferView, BaseShaderRegister = 0, DescriptorCount = 1 } }; RootParameter parameter = new RootParameter(ShaderVisibility.Vertex, ranges); // Create a root signature. RootSignatureDescription rootSignatureDesc = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout, new RootParameter[] { parameter }); var rootSignature = device.CreateRootSignature(rootSignatureDesc.Serialize()); // Create the pipeline state, which includes compiling and loading shaders. string filePath = @"E:\Code\ROE1\RoeHack-master\Forms\bin\Debug\DirectXHooker\shaders.hlsl"; #if DEBUG var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile(filePath, "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)); #else var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("filePath, "VSMain", "vs_5_0")); #endif #if DEBUG var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile(filePath, "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)); #else var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile(filePath, "PSMain", "ps_5_0")); #endif // Define the vertex input layout. InputElement[] inputElementDescs = new InputElement[] { new InputElement("POSITION",0,Format.R32G32B32_Float,0,0), new InputElement("COLOR",0,Format.R32G32B32A32_Float,12,0) }; // Describe and create the graphics pipeline state object (PSO). GraphicsPipelineStateDescription psoDesc = new GraphicsPipelineStateDescription() { InputLayout = new InputLayoutDescription(inputElementDescs), RootSignature = rootSignature, VertexShader = vertexShader, PixelShader = pixelShader, RasterizerState = RasterizerStateDescription.Default(), BlendState = BlendStateDescription.Default(), DepthStencilFormat = SharpDX.DXGI.Format.D32_Float, DepthStencilState = DepthStencilStateDescription.Default(), SampleMask = int.MaxValue, PrimitiveTopologyType = PrimitiveTopologyType.Triangle, RenderTargetCount = 1, Flags = PipelineStateFlags.None, SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0), StreamOutput = new StreamOutputDescription() }; psoDesc.DepthStencilState.IsDepthEnabled = false; psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm; pipelineState = device.CreateGraphicsPipelineState(psoDesc); }
public DescriptorSteppingMotorEditor(DescriptorRange assignedAccessDescriptor) { InitializeComponent(); _assignedAccessDescriptor = assignedAccessDescriptor; _getValueFormula.Text = _assignedAccessDescriptor.GetReceiveValueFormula(); _minimum.Text = _assignedAccessDescriptor.GetMinimumValueFormula(); _maximum.Text = _assignedAccessDescriptor.GetMaximumValueFormula(); _enableDefaultValue.IsChecked = _assignedAccessDescriptor.EnableDefaultValue; _defaultValue.Text = _assignedAccessDescriptor.EnableDefaultValue ? _assignedAccessDescriptor.GetDefaultValueFormula() : string.Empty; _step.Text = _assignedAccessDescriptor.GetStepFormula(); _defaultValue.IsReadOnly = !_assignedAccessDescriptor.EnableDefaultValue; var cbi = new ComboBoxItem { Tag = CycleType.None }; _cycleType.Items.Add(cbi); _cycleType.Items.Add(new ComboBoxItem { Tag = CycleType.Simple }); _cycleType.Items.Add(new ComboBoxItem { Tag = CycleType.UnreachableMinimum }); _cycleType.Items.Add(new ComboBoxItem { Tag = CycleType.UnreachableMaximum }); var ct = assignedAccessDescriptor.GetCycleType(); foreach (ComboBoxItem cti in _cycleType.Items) { if ((CycleType)cti.Tag != ct) { continue; } _cycleType.SelectedItem = cti; break; } if (_cycleType.SelectedItem == null) { _cycleType.SelectedItem = cbi; } Localize(); }
private static async Task ExecuteOnGpu(GraphicsDevice device, StructuredBuffer <float> sourceBufferView, WriteableStructuredBuffer <float> destinationBufferView) { bool generateWithDelegate = false; DescriptorSet descriptorSet = new DescriptorSet(device, 2); descriptorSet.AddResourceViews(destinationBufferView); descriptorSet.AddResourceViews(sourceBufferView); // Generate computer shader ShaderGenerator shaderGenerator = generateWithDelegate ? CreateShaderGeneratorWithDelegate(sourceBufferView, destinationBufferView) : CreateShaderGeneratorWithClass(); ShaderGeneratorResult result = shaderGenerator.GenerateShader(); // Compile shader byte[] shaderBytecode = ShaderCompiler.Compile(ShaderStage.ComputeShader, result.ShaderSource, result.EntryPoints["compute"]); DescriptorRange[] descriptorRanges = new DescriptorRange[] { new DescriptorRange(DescriptorRangeType.UnorderedAccessView, 1, 0), new DescriptorRange(DescriptorRangeType.ShaderResourceView, 1, 0) }; RootParameter rootParameter = new RootParameter(new RootDescriptorTable(descriptorRanges), ShaderVisibility.All); RootSignatureDescription rootSignatureDescription = new RootSignatureDescription(RootSignatureFlags.None, new[] { rootParameter }); RootSignature rootSignature = new RootSignature(device, rootSignatureDescription); PipelineState pipelineState = new PipelineState(device, rootSignature, shaderBytecode); // Execute computer shader using (CommandList commandList = new CommandList(device, CommandListType.Compute)) { commandList.SetPipelineState(pipelineState); commandList.SetComputeRootDescriptorTable(0, descriptorSet); commandList.Dispatch(1, 1, 1); await commandList.FlushAsync(); } }
private void BuildRootSignature() { var cbvTable0 = new DescriptorRange(DescriptorRangeType.ConstantBufferView, 1, 0); var cbvTable1 = new DescriptorRange(DescriptorRangeType.ConstantBufferView, 1, 1); // Root parameter can be a table, root descriptor or root constants. var slotRootParameters = new[] { new RootParameter(ShaderVisibility.Vertex, cbvTable0), new RootParameter(ShaderVisibility.Vertex, cbvTable1) }; // A root signature is an array of root parameters. var rootSigDesc = new RootSignatureDescription( RootSignatureFlags.AllowInputAssemblerInputLayout, slotRootParameters); // Create a root signature with a single slot which points to a descriptor range consisting of a single constant buffer. _rootSignature = Device.CreateRootSignature(rootSigDesc.Serialize()); }
private void BuildRootSignature() { // Shader programs typically require resources as input (constant buffers, // textures, samplers). The root signature defines the resources the shader // programs expect. If we think of the shader programs as a function, and // the input resources as function parameters, then the root signature can be // thought of as defining the function signature. // Root parameter can be a table, root descriptor or root constants. // Create a single descriptor table of CBVs. var cbvTable = new DescriptorRange(DescriptorRangeType.ConstantBufferView, 1, 0); // A root signature is an array of root parameters. var rootSigDesc = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout, new[] { new RootParameter(ShaderVisibility.Vertex, cbvTable) }); _rootSignature = DXGlobal.device.CreateRootSignature(rootSigDesc.Serialize()); }
private void BuildWavesRootSignature() { var uavTable0 = new DescriptorRange(DescriptorRangeType.UnorderedAccessView, 1, 0); var uavTable1 = new DescriptorRange(DescriptorRangeType.UnorderedAccessView, 1, 1); var uavTable2 = new DescriptorRange(DescriptorRangeType.UnorderedAccessView, 1, 2); // Root parameter can be a table, root descriptor or root constants. // Perfomance TIP: Order from most frequent to least frequent. var slotRootParameters = new[] { new RootParameter(ShaderVisibility.All, new RootConstants(0, 0, 6)), new RootParameter(ShaderVisibility.All, uavTable0), new RootParameter(ShaderVisibility.All, uavTable1), new RootParameter(ShaderVisibility.All, uavTable2), }; // A root signature is an array of root parameters. var rootSigDesc = new RootSignatureDescription( RootSignatureFlags.AllowInputAssemblerInputLayout, slotRootParameters); _wavesRootSignature = Device.CreateRootSignature(rootSigDesc.Serialize()); }
public void PrepareProfile() { Profile.Clear(); // Создание трёх панелей var p1 = new Panel { Name = "Panel1" }; Profile.PanelStorage.StorePanel(p1); var panelId1 = p1.Id; var p2 = new Panel { Name = "Panel2" }; Profile.PanelStorage.StorePanel(p2); var panelId2 = p2.Id; var p3 = new Panel { Name = "Panel3" }; Profile.PanelStorage.StorePanel(p3); var panelId3 = p3.Id; // Создание трёх переменных. Одна в первой панели, вторая и третья во второй var firstTestVariable = new FakeVariable { Size = MemoryVariableSize.Byte, Name = "Var1", PanelId = panelId1, Description = "Тестовая переменная 1\nНовая строка" }; var firstTestVariableId = firstTestVariable.Id; Profile.VariableStorage.StoreVariable(firstTestVariable); var secondTestVariable = new FakeVariable { Size = MemoryVariableSize.EightByteFloat, Name = "Var2", PanelId = panelId2, Description = "Тестовая переменная 2\nНовая строка" }; var secondTestVariableId = secondTestVariable.Id; Profile.VariableStorage.StoreVariable(secondTestVariable); var thirdTestVariable = new FakeVariable { Size = MemoryVariableSize.FourBytesSigned, Name = "Var3", PanelId = panelId2, Description = "Тестовая переменная 3\nНовая строка" }; var thirdTestVariableId = thirdTestVariable.Id; Profile.VariableStorage.StoreVariable(thirdTestVariable); // Создание описателей доступа // Button var valueAccessDescriptor = new DescriptorValue(); var powerFormula = "[" + Profile.PanelStorage.GetPanelById(Profile.VariableStorage.GetVariableById(firstTestVariableId).PanelId).Name + "." + Profile.VariableStorage.GetVariableById(firstTestVariableId).Name + "]"; valueAccessDescriptor.SetPowerFormula(powerFormula); valueAccessDescriptor.AssignDefaultStateId(0); valueAccessDescriptor.AddConnector("Off"); valueAccessDescriptor.AddConnector("On"); // valueAccessDescriptor.AddVariable(firstTestVariableId); valueAccessDescriptor.AddVariable(secondTestVariableId); valueAccessDescriptor.AddVariable(thirdTestVariableId); // valueAccessDescriptor.SetFormula(0, 0, "0"); valueAccessDescriptor.SetFormula(0, secondTestVariableId, "0"); valueAccessDescriptor.SetFormula(0, thirdTestVariableId, "0"); // valueAccessDescriptor.SetFormula(1, 0, "1"); valueAccessDescriptor.SetFormula(1, secondTestVariableId, "2.58"); valueAccessDescriptor.SetFormula(1, thirdTestVariableId, "-3"); valueAccessDescriptor.AssignDefaultStateId(0); valueAccessDescriptor.SetAssignedPanelId(panelId3); valueAccessDescriptor.SetName("AccessDescriptor1"); var valueAccessDescriptorId = Profile.AccessDescriptor.RegisterAccessDescriptor(valueAccessDescriptor); // Encoder var rangeAccessDescriptor = new DescriptorRange(); rangeAccessDescriptor.SetReceiveValueFormula("[" + Profile.PanelStorage.GetPanelById(panelId2).Name + "." + Profile.VariableStorage.GetVariableById(secondTestVariableId).Name + "]"); rangeAccessDescriptor.AddVariable(secondTestVariableId); rangeAccessDescriptor.AddVariable(firstTestVariableId); rangeAccessDescriptor.SetAssignedPanelId(panelId3); rangeAccessDescriptor.SetName("AccessDescriptorRange"); rangeAccessDescriptor.SetFormula(0, secondTestVariableId, "[R]"); rangeAccessDescriptor.SetFormula(1, thirdTestVariableId, "[R]:1"); rangeAccessDescriptor.SetMinimumValueFormula("0"); rangeAccessDescriptor.SetMaximumValueFormula("4"); rangeAccessDescriptor.SetStepFormula("0.5"); // rangeAccessDescriptor.IsLooped = true; var rangeAccessDescriptorId = Profile.AccessDescriptor.RegisterAccessDescriptor(rangeAccessDescriptor); var tempFile = Path.GetTempFileName(); Profile.SaveAs(tempFile); Profile.Clear(); Profile.Load(tempFile, ProfileItemPrivacyType.Public); var valueDescriptor = (DescriptorValue)Profile.AccessDescriptor.GetAccessDesciptorById(valueAccessDescriptorId); Profile.VariableStorage.WriteValue(firstTestVariableId, 0); Profile.VariableStorage.WriteValue(secondTestVariableId, 0); Profile.VariableStorage.WriteValue(thirdTestVariableId, 0); Thread.Sleep(200); valueDescriptor.SetState(1); Thread.Sleep(200); Assert.AreEqual(0, Profile.VariableStorage.ReadValue(firstTestVariableId).Value); Assert.AreEqual(0, Profile.VariableStorage.ReadValue(secondTestVariableId).Value); Assert.AreEqual(0, Profile.VariableStorage.ReadValue(thirdTestVariableId).Value); Profile.VariableStorage.WriteValue(firstTestVariableId, 1); Thread.Sleep(200); valueDescriptor.SetState(1); Thread.Sleep(200); Assert.AreEqual(1, Profile.VariableStorage.ReadValue(firstTestVariableId).Value); Assert.AreEqual(2.58, Profile.VariableStorage.ReadValue(secondTestVariableId).Value); Assert.AreEqual(-3, Profile.VariableStorage.ReadValue(thirdTestVariableId).Value); valueAccessDescriptor.SetDefaultState(); Thread.Sleep(200); Assert.AreEqual(0, Profile.VariableStorage.ReadValue(firstTestVariableId).Value); Assert.AreEqual(0, Profile.VariableStorage.ReadValue(secondTestVariableId).Value); Assert.AreEqual(0, Profile.VariableStorage.ReadValue(thirdTestVariableId).Value); File.Delete(tempFile); }
public void BuildPSO(Device3 device, GraphicsCommandList commandList) { World = Matrix.Translation(-2.5f, -2.5f, -2.5f); buffer.World = World; light = new Lighting { GlobalAmbientX = 1, GlobalAmbientY = 1, GlobalAmbientZ = 1, KaX = .1f, KaY = .1f, KaZ = .1f, KdX = .5f, KdY = .5f, KdZ = .5f, KeX = .25f, KeY = .25f, KeZ = .25f, KsX = .1f, KsY = .1f, KsZ = .1f, LightColorX = 1, LightColorY = 1, LightColorZ = 1, LightPositionX = 10, LightPositionY = 10, LightPositionZ = 10, shininess = 5 }; DescriptorHeapDescription srvHeapDesc = new DescriptorHeapDescription() { DescriptorCount = 1, Flags = DescriptorHeapFlags.ShaderVisible, Type = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView }; _srvDescriptorHeap = device.CreateDescriptorHeap(srvHeapDesc); //setup descriptor ranges DescriptorRange[] ranges = new DescriptorRange[] { new DescriptorRange() { RangeType = DescriptorRangeType.ShaderResourceView, DescriptorCount = 1, OffsetInDescriptorsFromTableStart = int.MinValue, BaseShaderRegister = 0 } }; //Get sampler state setup StaticSamplerDescription sampler = new StaticSamplerDescription() { Filter = Filter.MinimumMinMagMipPoint, AddressU = TextureAddressMode.Border, AddressV = TextureAddressMode.Border, AddressW = TextureAddressMode.Border, MipLODBias = 0, MaxAnisotropy = 0, ComparisonFunc = Comparison.Never, BorderColor = StaticBorderColor.TransparentBlack, MinLOD = 0.0f, MaxLOD = float.MaxValue, ShaderRegister = 0, RegisterSpace = 0, ShaderVisibility = ShaderVisibility.Pixel, }; Projection = Matrix.PerspectiveFovLH((float)Math.PI / 3f, 4f / 3f, 1, 1000); View = Matrix.LookAtLH(new Vector3(10 * (float)Math.Sin(rotation), 5, 10 * (float)Math.Cos(rotation)), Vector3.Zero, Vector3.UnitY); World = Matrix.Translation(-2.5f, -2.5f, -2.5f); DescriptorHeapDescription cbvHeapDesc = new DescriptorHeapDescription() { DescriptorCount = 1, Flags = DescriptorHeapFlags.ShaderVisible, Type = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView }; _objectViewHeap = device.CreateDescriptorHeap(cbvHeapDesc); _lightingViewHeap = device.CreateDescriptorHeap(cbvHeapDesc); RootParameter[] rootParameters = new RootParameter[] { new RootParameter(ShaderVisibility.Pixel, ranges), new RootParameter(ShaderVisibility.All, new RootDescriptor(1, 0), RootParameterType.ConstantBufferView), new RootParameter(ShaderVisibility.All, new RootDescriptor(2, 0), RootParameterType.ConstantBufferView) }; // Create an empty root signature. RootSignatureDescription rootSignatureDesc = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout, rootParameters, new StaticSamplerDescription[] { sampler }); _rootSignature = device.CreateRootSignature(rootSignatureDesc.Serialize()); // Create the pipeline state, which includes compiling and loading shaders. #if DEBUG var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("Shaders/LitVertex.hlsl", "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)); #else var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("Shaders/LitVertex.hlsl", "VSMain", "vs_5_0")); #endif #if DEBUG var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("Shaders/LitVertex.hlsl", "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)); #else var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("Shaders/LitVertex.hlsl", "PSMain", "ps_5_0")); #endif // Define the vertex input layout. InputElement[] inputElementDescs = new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 24, 0) }; // Describe and create the graphics pipeline state object (PSO). GraphicsPipelineStateDescription psoDesc = new GraphicsPipelineStateDescription() { InputLayout = new InputLayoutDescription(inputElementDescs), RootSignature = _rootSignature, VertexShader = vertexShader, PixelShader = pixelShader, RasterizerState = RasterizerStateDescription.Default(), BlendState = BlendStateDescription.Default(), DepthStencilFormat = SharpDX.DXGI.Format.D24_UNorm_S8_UInt, DepthStencilState = DepthStencilStateDescription.Default(), SampleMask = int.MaxValue, PrimitiveTopologyType = PrimitiveTopologyType.Triangle, RenderTargetCount = 1, Flags = PipelineStateFlags.None, SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0), StreamOutput = new StreamOutputDescription() }; psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm; _pipelineState = device.CreateGraphicsPipelineState(psoDesc); // Define the geometry for a triangle. Vertex[] triangleVertices = new Vertex[] { //Front new Vertex() { Position = new Vector3(0, 0, 0), TexCoord = new Vector2(1, 1), Normal = -Vector3.UnitZ }, new Vertex() { Position = new Vector3(0, 5, 0), TexCoord = new Vector2(1, 0), Normal = -Vector3.UnitZ }, new Vertex() { Position = new Vector3(5, 0, 0), TexCoord = new Vector2(0, 1), Normal = -Vector3.UnitZ }, new Vertex() { Position = new Vector3(5, 5, 0), TexCoord = new Vector2(0, 0), Normal = -Vector3.UnitZ }, //Back new Vertex() { Position = new Vector3(0, 0, 5), TexCoord = new Vector2(1, 1), Normal = Vector3.UnitZ }, new Vertex() { Position = new Vector3(0, 5, 5), TexCoord = new Vector2(1, 0), Normal = Vector3.UnitZ }, new Vertex() { Position = new Vector3(5, 0, 5), TexCoord = new Vector2(0, 1), Normal = Vector3.UnitZ }, new Vertex() { Position = new Vector3(5, 5, 5), TexCoord = new Vector2(0, 0), Normal = Vector3.UnitZ }, //Left new Vertex() { Position = new Vector3(0, 0, 0), TexCoord = new Vector2(1, 1), Normal = -Vector3.UnitX }, new Vertex() { Position = new Vector3(0, 5, 0), TexCoord = new Vector2(1, 0), Normal = -Vector3.UnitX }, new Vertex() { Position = new Vector3(0, 0, 5), TexCoord = new Vector2(0, 1), Normal = -Vector3.UnitX }, new Vertex() { Position = new Vector3(0, 5, 5), TexCoord = new Vector2(0, 0), Normal = -Vector3.UnitX }, //Right new Vertex() { Position = new Vector3(5, 0, 0), TexCoord = new Vector2(1, 1), Normal = Vector3.UnitX }, new Vertex() { Position = new Vector3(5, 5, 0), TexCoord = new Vector2(1, 0), Normal = Vector3.UnitX }, new Vertex() { Position = new Vector3(5, 0, 5), TexCoord = new Vector2(0, 1), Normal = Vector3.UnitX }, new Vertex() { Position = new Vector3(5, 5, 5), TexCoord = new Vector2(0, 0), Normal = Vector3.UnitX }, //Top new Vertex() { Position = new Vector3(0, 0, 0), TexCoord = new Vector2(1, 1), Normal = -Vector3.UnitY }, new Vertex() { Position = new Vector3(0, 0, 5), TexCoord = new Vector2(1, 0), Normal = -Vector3.UnitY }, new Vertex() { Position = new Vector3(5, 0, 0), TexCoord = new Vector2(0, 1), Normal = -Vector3.UnitY }, new Vertex() { Position = new Vector3(5, 0, 5), TexCoord = new Vector2(0, 0), Normal = -Vector3.UnitY }, //Bottom new Vertex() { Position = new Vector3(0, 5, 0), TexCoord = new Vector2(1, 1), Normal = Vector3.UnitY }, new Vertex() { Position = new Vector3(0, 5, 5), TexCoord = new Vector2(1, 0), Normal = Vector3.UnitY }, new Vertex() { Position = new Vector3(5, 5, 0), TexCoord = new Vector2(0, 1), Normal = Vector3.UnitY }, new Vertex() { Position = new Vector3(5, 5, 5), TexCoord = new Vector2(0, 0), Normal = Vector3.UnitY } }; int vertexBufferSize = Utilities.SizeOf(triangleVertices); // Note: using upload heaps to transfer static data like vert buffers is not // recommended. Every time the GPU needs it, the upload heap will be marshalled // over. Please read up on Default Heap usage. An upload heap is used here for // code simplicity and because there are very few verts to actually transfer. _vertexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(vertexBufferSize), ResourceStates.GenericRead); // Copy the triangle data to the vertex buffer. IntPtr pVertexDataBegin = _vertexBuffer.Map(0); Utilities.Write(pVertexDataBegin, triangleVertices, 0, triangleVertices.Length); _vertexBuffer.Unmap(0); _indicies = new int[] { 0, 1, 2, 3, 2, 1, 6, 5, 4, 5, 6, 7, 10, 9, 8, 9, 10, 11, 12, 13, 14, 15, 14, 13, 18, 17, 16, 17, 18, 19, 20, 21, 22, 23, 22, 21 }; int indBufferSize = Utilities.SizeOf(_indicies); _indexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(indBufferSize), ResourceStates.GenericRead); IntPtr pIndBegin = _indexBuffer.Map(0); Utilities.Write(pIndBegin, _indicies, 0, _indicies.Length); _indexBuffer.Unmap(0); _indexBufferView = new IndexBufferView() { BufferLocation = _indexBuffer.GPUVirtualAddress, Format = Format.R32_UInt, SizeInBytes = indBufferSize }; // Initialize the vertex buffer view. _vertexBufferView = new VertexBufferView { BufferLocation = _vertexBuffer.GPUVirtualAddress, StrideInBytes = Utilities.SizeOf <Vertex>(), SizeInBytes = vertexBufferSize }; _objectBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(Utilities.SizeOf <ObjectData>()), ResourceStates.GenericRead); //// Describe and create a constant buffer view. ConstantBufferViewDescription cbvDesc = new ConstantBufferViewDescription() { BufferLocation = _objectBuffer.GPUVirtualAddress, SizeInBytes = (Utilities.SizeOf <ObjectData>() + 255) & ~255 }; device.CreateConstantBufferView(cbvDesc, _objectViewHeap.CPUDescriptorHandleForHeapStart); // Initialize and map the constant buffers. We don't unmap this until the // app closes. Keeping things mapped for the lifetime of the resource is okay. _objectPointer = _objectBuffer.Map(0); Utilities.Write(_objectPointer, ref buffer); _lightingBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(Utilities.SizeOf <Lighting>()), ResourceStates.GenericRead); //// Describe and create a constant buffer view. ConstantBufferViewDescription cbvDesc2 = new ConstantBufferViewDescription() { BufferLocation = _objectBuffer.GPUVirtualAddress, SizeInBytes = (Utilities.SizeOf <Lighting>() + 255) & ~255 }; device.CreateConstantBufferView(cbvDesc2, _lightingViewHeap.CPUDescriptorHandleForHeapStart); // Initialize and map the constant buffers. We don't unmap this until the // app closes. Keeping things mapped for the lifetime of the resource is okay. _lightingPointer = _lightingBuffer.Map(0); Utilities.Write(_lightingPointer, ref light); Resource textureUploadHeap; // Create the texture. // Describe and create a Texture2D. ResourceDescription textureDesc = ResourceDescription.Texture2D(Format.R8G8B8A8_UNorm, textureWidth, textureHeight); _texture = device.CreateCommittedResource(new HeapProperties(HeapType.Default), HeapFlags.None, textureDesc, ResourceStates.CopyDestination); long uploadBufferSize = GetRequiredIntermediateSize(device, _texture, 0, 1); // Create the GPU upload buffer. textureUploadHeap = device.CreateCommittedResource(new HeapProperties(CpuPageProperty.WriteBack, MemoryPool.L0), HeapFlags.None, ResourceDescription.Texture2D(Format.R8G8B8A8_UNorm, textureWidth, textureHeight), ResourceStates.GenericRead); // Copy data to the intermediate upload heap and then schedule a copy // from the upload heap to the Texture2D. byte[] textureData = GenerateTextureData(); GCHandle handle = GCHandle.Alloc(textureData, GCHandleType.Pinned); IntPtr ptr = Marshal.UnsafeAddrOfPinnedArrayElement(textureData, 0); textureUploadHeap.WriteToSubresource(0, null, ptr, 4 * textureWidth, textureData.Length); handle.Free(); commandList.CopyTextureRegion(new TextureCopyLocation(_texture, 0), 0, 0, 0, new TextureCopyLocation(textureUploadHeap, 0), null); commandList.ResourceBarrierTransition(_texture, ResourceStates.CopyDestination, ResourceStates.PixelShaderResource); // Describe and create a SRV for the texture. ShaderResourceViewDescription srvDesc = new ShaderResourceViewDescription() { Shader4ComponentMapping = ComponentMapping(0, 1, 2, 3), Format = textureDesc.Format, Dimension = ShaderResourceViewDimension.Texture2D, }; srvDesc.Texture2D.MipLevels = 1; device.CreateShaderResourceView(_texture, srvDesc, _srvDescriptorHeap.CPUDescriptorHandleForHeapStart); _resources = new[] { new GraphicsResource() { Heap = _srvDescriptorHeap, Register = 0, type = ResourceType.DescriptorTable }, new GraphicsResource() { Resource = _objectBuffer, Register = 2, type = ResourceType.ConstantBufferView }, new GraphicsResource() { Resource = _lightingBuffer, Register = 1, type = ResourceType.ConstantBufferView } }; }
private void LoadAssets() { DescriptorRange[] ranges = new DescriptorRange[] { new DescriptorRange() { RangeType = DescriptorRangeType.ShaderResourceView, DescriptorCount = 1, OffsetInDescriptorsFromTableStart = int.MinValue, BaseShaderRegister = 0 } }; StaticSamplerDescription sampler = new StaticSamplerDescription() { Filter = Filter.MinimumMinMagMipPoint, AddressU = TextureAddressMode.Border, AddressV = TextureAddressMode.Border, AddressW = TextureAddressMode.Border, MipLODBias = 0, MaxAnisotropy = 0, ComparisonFunc = Comparison.Never, BorderColor = StaticBorderColor.TransparentBlack, MinLOD = 0.0f, MaxLOD = float.MaxValue, ShaderRegister = 0, RegisterSpace = 0, ShaderVisibility = ShaderVisibility.Pixel, }; RootParameter[] rootParameters = new RootParameter[] { new RootParameter(ShaderVisibility.Pixel, ranges) }; RootSignatureDescription rootSignatureDesc = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout, rootParameters, new StaticSamplerDescription[] { sampler }); rootSignature = device.CreateRootSignature(0, rootSignatureDesc.Serialize()); // Create the pipeline state, which includes compiling and loading shaders. #if DEBUG var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)); #else var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0")); #endif #if DEBUG var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)); #else var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0")); #endif // Define the vertex input layout. InputElement[] inputElementDescs = new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0) }; // Describe and create the graphics pipeline state object (PSO). GraphicsPipelineStateDescription psoDesc = new GraphicsPipelineStateDescription() { InputLayout = new InputLayoutDescription(inputElementDescs), RootSignature = rootSignature, VertexShader = vertexShader, PixelShader = pixelShader, RasterizerState = RasterizerStateDescription.Default(), BlendState = BlendStateDescription.Default(), DepthStencilFormat = SharpDX.DXGI.Format.D32_Float, DepthStencilState = new DepthStencilStateDescription() { IsDepthEnabled = false, IsStencilEnabled = false }, SampleMask = int.MaxValue, PrimitiveTopologyType = PrimitiveTopologyType.Triangle, RenderTargetCount = 1, Flags = PipelineStateFlags.None, SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0), StreamOutput = new StreamOutputDescription() }; psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm; pipelineState = device.CreateGraphicsPipelineState(psoDesc); // Create the command list. commandList = device.CreateCommandList(CommandListType.Direct, commandAllocator, pipelineState); // Create the vertex buffer. float aspectRatio = viewport.Width / viewport.Height; // Define the geometry for a triangle. Vertex[] triangleVertices = new Vertex[] { new Vertex() { position = new Vector3(0.0f, 0.25f * aspectRatio, 0.0f), uv = new Vector2(0.5f, 0.0f) }, new Vertex() { position = new Vector3(0.25f, -0.25f * aspectRatio, 0.0f), uv = new Vector2(1.0f, 1.0f) }, new Vertex() { position = new Vector3(-0.25f, -0.25f * aspectRatio, 0.0f), uv = new Vector2(0.0f, 1.0f) }, }; int vertexBufferSize = Utilities.SizeOf(triangleVertices); // Note: using upload heaps to transfer static data like vert buffers is not // recommended. Every time the GPU needs it, the upload heap will be marshalled // over. Please read up on Default Heap usage. An upload heap is used here for // code simplicity and because there are very few verts to actually transfer. vertexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(vertexBufferSize), ResourceStates.GenericRead); // Copy the triangle data to the vertex buffer. IntPtr pVertexDataBegin = vertexBuffer.Map(0); Utilities.Write(pVertexDataBegin, triangleVertices, 0, triangleVertices.Length); vertexBuffer.Unmap(0); // Initialize the vertex buffer view. vertexBufferView = new VertexBufferView(); vertexBufferView.BufferLocation = vertexBuffer.GPUVirtualAddress; vertexBufferView.StrideInBytes = Utilities.SizeOf <Vertex>(); vertexBufferView.SizeInBytes = vertexBufferSize; Resource textureUploadHeap; // Create the texture. // Describe and create a Texture2D. ResourceDescription textureDesc = ResourceDescription.Texture2D(Format.R8G8B8A8_UNorm, TextureWidth, TextureHeight); texture = device.CreateCommittedResource(new HeapProperties(HeapType.Default), HeapFlags.None, textureDesc, ResourceStates.CopyDestination); long uploadBufferSize = GetRequiredIntermediateSize(this.texture, 0, 1); // Create the GPU upload buffer. textureUploadHeap = device.CreateCommittedResource(new HeapProperties(CpuPageProperty.WriteBack, MemoryPool.L0), HeapFlags.None, ResourceDescription.Texture2D(Format.R8G8B8A8_UNorm, TextureWidth, TextureHeight), ResourceStates.GenericRead); // Copy data to the intermediate upload heap and then schedule a copy // from the upload heap to the Texture2D. byte[] textureData = GenerateTextureData(); GCHandle handle = GCHandle.Alloc(textureData, GCHandleType.Pinned); IntPtr ptr = Marshal.UnsafeAddrOfPinnedArrayElement(textureData, 0); textureUploadHeap.WriteToSubresource(0, null, ptr, TexturePixelSize * TextureWidth, textureData.Length); handle.Free(); commandList.CopyTextureRegion(new TextureCopyLocation(texture, 0), 0, 0, 0, new TextureCopyLocation(textureUploadHeap, 0), null); commandList.ResourceBarrierTransition(this.texture, ResourceStates.CopyDestination, ResourceStates.PixelShaderResource); // Describe and create a SRV for the texture. ShaderResourceViewDescription srvDesc = new ShaderResourceViewDescription() { Shader4ComponentMapping = D3DXUtilities.DefaultComponentMapping(), Format = textureDesc.Format, Dimension = ShaderResourceViewDimension.Texture2D, }; srvDesc.Texture2D.MipLevels = 1; device.CreateShaderResourceView(this.texture, srvDesc, shaderRenderViewHeap.CPUDescriptorHandleForHeapStart); // Command lists are created in the recording state, but there is nothing // to record yet. The main loop expects it to be closed, so close it now. commandList.Close(); commandQueue.ExecuteCommandList(commandList); // Create synchronization objects. fence = device.CreateFence(0, FenceFlags.None); fenceValue = 1; // Create an event handle to use for frame synchronization. fenceEvent = new AutoResetEvent(false); WaitForPreviousFrame(); //release temp texture textureUploadHeap.Dispose(); }
private void LoadAssets() { DescriptorRange[] ranges = new DescriptorRange[] { new DescriptorRange() { RangeType = DescriptorRangeType.ConstantBufferView, BaseShaderRegister = 0, DescriptorCount = 1 } }; RootParameter parameter = new RootParameter(ShaderVisibility.Vertex, ranges); // Create a root signature. RootSignatureDescription rootSignatureDesc = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout, new RootParameter[] { parameter }); rootSignature = device.CreateRootSignature(rootSignatureDesc.Serialize()); // Create the pipeline state, which includes compiling and loading shaders. #if DEBUG var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)); #else var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0")); #endif #if DEBUG var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)); #else var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0")); #endif // Define the vertex input layout. InputElement[] inputElementDescs = new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 12, 0) }; // Describe and create the graphics pipeline state object (PSO). GraphicsPipelineStateDescription psoDesc = new GraphicsPipelineStateDescription() { InputLayout = new InputLayoutDescription(inputElementDescs), RootSignature = rootSignature, VertexShader = vertexShader, PixelShader = pixelShader, RasterizerState = RasterizerStateDescription.Default(), BlendState = BlendStateDescription.Default(), DepthStencilFormat = SharpDX.DXGI.Format.D32_Float, DepthStencilState = DepthStencilStateDescription.Default(), SampleMask = int.MaxValue, PrimitiveTopologyType = PrimitiveTopologyType.Triangle, RenderTargetCount = 1, Flags = PipelineStateFlags.None, SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0), StreamOutput = new StreamOutputDescription() }; psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm; pipelineState = device.CreateGraphicsPipelineState(psoDesc); // Create the command list. commandList = device.CreateCommandList(CommandListType.Direct, commandAllocator, pipelineState); // Command lists are created in the recording state, but there is nothing // to record yet. The main loop expects it to be closed, so close it now. commandList.Close(); // Create the vertex buffer. float aspectRatio = viewport.Width / viewport.Height; // Define the geometry for a cube. Vertex[] vertices = new[] { ////TOP new Vertex(new Vector3(-5, 5, 5), new Vector4(0, 1, 0, 0)), new Vertex(new Vector3(5, 5, 5), new Vector4(0, 1, 0, 0)), new Vertex(new Vector3(5, 5, -5), new Vector4(0, 1, 0, 0)), new Vertex(new Vector3(-5, 5, -5), new Vector4(0, 1, 0, 0)), //BOTTOM new Vertex(new Vector3(-5, -5, 5), new Vector4(1, 0, 1, 1)), new Vertex(new Vector3(5, -5, 5), new Vector4(1, 0, 1, 1)), new Vertex(new Vector3(5, -5, -5), new Vector4(1, 0, 1, 1)), new Vertex(new Vector3(-5, -5, -5), new Vector4(1, 0, 1, 1)), //LEFT new Vertex(new Vector3(-5, -5, 5), new Vector4(1, 0, 0, 1)), new Vertex(new Vector3(-5, 5, 5), new Vector4(1, 0, 0, 1)), new Vertex(new Vector3(-5, 5, -5), new Vector4(1, 0, 0, 1)), new Vertex(new Vector3(-5, -5, -5), new Vector4(1, 0, 0, 1)), //RIGHT new Vertex(new Vector3(5, -5, 5), new Vector4(1, 1, 0, 1)), new Vertex(new Vector3(5, 5, 5), new Vector4(1, 1, 0, 1)), new Vertex(new Vector3(5, 5, -5), new Vector4(1, 1, 0, 1)), new Vertex(new Vector3(5, -5, -5), new Vector4(1, 1, 0, 1)), //FRONT new Vertex(new Vector3(-5, 5, 5), new Vector4(0, 1, 1, 1)), new Vertex(new Vector3(5, 5, 5), new Vector4(0, 1, 1, 1)), new Vertex(new Vector3(5, -5, 5), new Vector4(0, 1, 1, 1)), new Vertex(new Vector3(-5, -5, 5), new Vector4(0, 1, 1, 1)), //BACK new Vertex(new Vector3(-5, 5, -5), new Vector4(0, 0, 1, 1)), new Vertex(new Vector3(5, 5, -5), new Vector4(0, 0, 1, 1)), new Vertex(new Vector3(5, -5, -5), new Vector4(0, 0, 1, 1)), new Vertex(new Vector3(-5, -5, -5), new Vector4(0, 0, 1, 1)) }; int vertexBufferSize = Utilities.SizeOf(vertices); // Note: using upload heaps to transfer static data like vert buffers is not // recommended. Every time the GPU needs it, the upload heap will be marshalled // over. Please read up on Default Heap usage. An upload heap is used here for // code simplicity and because there are very few verts to actually transfer. vertexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(vertexBufferSize), ResourceStates.GenericRead); // Copy the triangle data to the vertex buffer. IntPtr pVertexDataBegin = vertexBuffer.Map(0); Utilities.Write(pVertexDataBegin, vertices, 0, vertices.Length); vertexBuffer.Unmap(0); // Initialize the vertex buffer view. vertexBufferView = new VertexBufferView(); vertexBufferView.BufferLocation = vertexBuffer.GPUVirtualAddress; vertexBufferView.StrideInBytes = Utilities.SizeOf <Vertex>(); vertexBufferView.SizeInBytes = vertexBufferSize; //Create Index Buffer //Indices int[] indices = new int[] { 0, 1, 2, 0, 2, 3, 4, 6, 5, 4, 7, 6, 8, 9, 10, 8, 10, 11, 12, 14, 13, 12, 15, 14, 16, 18, 17, 16, 19, 18, 20, 21, 22, 20, 22, 23 }; int indexBufferSize = Utilities.SizeOf(indices); indexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(indexBufferSize), ResourceStates.GenericRead); // Copy the triangle data to the vertex buffer. IntPtr pIndexDataBegin = indexBuffer.Map(0); Utilities.Write(pIndexDataBegin, indices, 0, indices.Length); indexBuffer.Unmap(0); // Initialize the index buffer view. indexBufferView = new IndexBufferView(); indexBufferView.BufferLocation = indexBuffer.GPUVirtualAddress; indexBufferView.Format = Format.R32_UInt; indexBufferView.SizeInBytes = indexBufferSize; //constant Buffer for each cubes constantBufferViewHeap = device.CreateDescriptorHeap(new DescriptorHeapDescription() { DescriptorCount = NumCubes, Type = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView, Flags = DescriptorHeapFlags.ShaderVisible }); int constantBufferSize = (Utilities.SizeOf <Transform>() + 255) & ~255; constantBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(constantBufferSize * NumCubes), ResourceStates.GenericRead); constantBufferDescriptorSize = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView); //First cube ConstantBufferViewDescription cbvDesc = new ConstantBufferViewDescription() { BufferLocation = constantBuffer.GPUVirtualAddress, SizeInBytes = constantBufferSize }; CpuDescriptorHandle cbHandleHeapStart = constantBufferViewHeap.CPUDescriptorHandleForHeapStart; for (int i = 0; i < NumCubes; i++) { device.CreateConstantBufferView(cbvDesc, cbHandleHeapStart); cbvDesc.BufferLocation += Utilities.SizeOf <Transform>(); cbHandleHeapStart += constantBufferDescriptorSize; } InitBundles(); }
public void BuildPSO(Device3 device, GraphicsCommandList commandList) { buffer = new CBuffer() { Rows = 3, Columns = 5 }; DescriptorHeapDescription cbvHeapDesc = new DescriptorHeapDescription() { DescriptorCount = 1, Flags = DescriptorHeapFlags.ShaderVisible, Type = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView }; _constantBufferViewHeap = device.CreateDescriptorHeap(cbvHeapDesc); DescriptorHeapDescription srvHeapDesc = new DescriptorHeapDescription() { DescriptorCount = 1, Flags = DescriptorHeapFlags.ShaderVisible, Type = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView }; _srvDescriptorHeap = device.CreateDescriptorHeap(srvHeapDesc); DescriptorRange[] ranges = new DescriptorRange[] { new DescriptorRange() { RangeType = DescriptorRangeType.ShaderResourceView, DescriptorCount = 1, OffsetInDescriptorsFromTableStart = int.MinValue, BaseShaderRegister = 0 } }; //Get sampler state setup StaticSamplerDescription sampler = new StaticSamplerDescription() { Filter = Filter.MinimumMinMagMipPoint, AddressU = TextureAddressMode.Border, AddressV = TextureAddressMode.Border, AddressW = TextureAddressMode.Border, MipLODBias = 0, MaxAnisotropy = 0, ComparisonFunc = Comparison.Never, BorderColor = StaticBorderColor.TransparentBlack, MinLOD = 0.0f, MaxLOD = float.MaxValue, ShaderRegister = 0, RegisterSpace = 0, ShaderVisibility = ShaderVisibility.Pixel, }; RootParameter[] rootParameters = new RootParameter[] { new RootParameter(ShaderVisibility.Pixel, ranges), new RootParameter(ShaderVisibility.Pixel, new RootDescriptor(1, 0), RootParameterType.ConstantBufferView) }; // Create an empty root signature. RootSignatureDescription rootSignatureDesc = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout, rootParameters, new StaticSamplerDescription[] { sampler }); _rootSignature = device.CreateRootSignature(rootSignatureDesc.Serialize()); // Create the pipeline state, which includes compiling and loading shaders. #if DEBUG var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("Shaders/AtlasWalk.hlsl", "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)); #else var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("Shaders/AtlasWalk.hlsl", "VSMain", "vs_5_0")); #endif #if DEBUG var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("Shaders/AtlasWalk.hlsl", "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)); #else var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("Shaders/AtlasWalk.hlsl", "PSMain", "ps_5_0")); #endif // Define the vertex input layout. InputElement[] inputElementDescs = new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0) }; // Describe and create the graphics pipeline state object (PSO). GraphicsPipelineStateDescription psoDesc = new GraphicsPipelineStateDescription() { InputLayout = new InputLayoutDescription(inputElementDescs), RootSignature = _rootSignature, VertexShader = vertexShader, PixelShader = pixelShader, RasterizerState = RasterizerStateDescription.Default(), BlendState = BlendStateDescription.Default(), DepthStencilFormat = SharpDX.DXGI.Format.D32_Float, DepthStencilState = new DepthStencilStateDescription() { IsDepthEnabled = false, IsStencilEnabled = false }, SampleMask = int.MaxValue, PrimitiveTopologyType = PrimitiveTopologyType.Triangle, RenderTargetCount = 1, Flags = PipelineStateFlags.None, SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0), StreamOutput = new StreamOutputDescription() }; psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm; _pipelineState = device.CreateGraphicsPipelineState(psoDesc); // Define the geometry for a triangle. Vertex[] triangleVertices = new Vertex[] { new Vertex() { position = new Vector3(-0.5f, -0.5f, 0.5f), texCoord = new Vector2(1.0f, 1.0f) }, new Vertex() { position = new Vector3(-0.5f, 0.5f, 0.5f), texCoord = new Vector2(1.0f, 0.0f) }, new Vertex() { position = new Vector3(0.5f, -0.5f, 0.5f), texCoord = new Vector2(0.0f, 1.0f) }, new Vertex() { position = new Vector3(0.5f, 0.5f, 0.5f), texCoord = new Vector2(0.0f, 0.0f) } }; int vertexBufferSize = Utilities.SizeOf(triangleVertices); // Note: using upload heaps to transfer static data like vert buffers is not // recommended. Every time the GPU needs it, the upload heap will be marshalled // over. Please read up on Default Heap usage. An upload heap is used here for // code simplicity and because there are very few verts to actually transfer. _vertexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(vertexBufferSize), ResourceStates.GenericRead); // Copy the triangle data to the vertex buffer. IntPtr pVertexDataBegin = _vertexBuffer.Map(0); Utilities.Write(pVertexDataBegin, triangleVertices, 0, triangleVertices.Length); _vertexBuffer.Unmap(0); _indicies = new int[] { 0, 1, 2, 3, 2, 1 }; int indBufferSize = Utilities.SizeOf(_indicies); _indexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(indBufferSize), ResourceStates.GenericRead); IntPtr pIndBegin = _indexBuffer.Map(0); Utilities.Write(pIndBegin, _indicies, 0, _indicies.Length); _indexBuffer.Unmap(0); _indexBufferView = new IndexBufferView() { BufferLocation = _indexBuffer.GPUVirtualAddress, Format = Format.R32_UInt, SizeInBytes = indBufferSize }; // Initialize the vertex buffer view. _vertexBufferView = new VertexBufferView { BufferLocation = _vertexBuffer.GPUVirtualAddress, StrideInBytes = Utilities.SizeOf <Vertex>(), SizeInBytes = vertexBufferSize }; Resource textureUploadHeap; // Create the texture. // Describe and create a Texture2D. ResourceDescription textureDesc = ResourceDescription.Texture2D(Format.R8G8B8A8_UNorm, textureWidth, textureHeight); _texture = device.CreateCommittedResource(new HeapProperties(HeapType.Default), HeapFlags.None, textureDesc, ResourceStates.CopyDestination); long uploadBufferSize = GetRequiredIntermediateSize(device, _texture, 0, 1); // Create the GPU upload buffer. textureUploadHeap = device.CreateCommittedResource(new HeapProperties(CpuPageProperty.WriteBack, MemoryPool.L0), HeapFlags.None, ResourceDescription.Texture2D(Format.R8G8B8A8_UNorm, textureWidth, textureHeight), ResourceStates.GenericRead); // Copy data to the intermediate upload heap and then schedule a copy // from the upload heap to the Texture2D. byte[] textureData = GenerateTextureData(); GCHandle handle = GCHandle.Alloc(textureData, GCHandleType.Pinned); IntPtr ptr = Marshal.UnsafeAddrOfPinnedArrayElement(textureData, 0); textureUploadHeap.WriteToSubresource(0, null, ptr, 4 * textureWidth, textureData.Length); handle.Free(); commandList.CopyTextureRegion(new TextureCopyLocation(_texture, 0), 0, 0, 0, new TextureCopyLocation(textureUploadHeap, 0), null); commandList.ResourceBarrierTransition(_texture, ResourceStates.CopyDestination, ResourceStates.PixelShaderResource); // Describe and create a SRV for the texture. ShaderResourceViewDescription srvDesc = new ShaderResourceViewDescription() { Shader4ComponentMapping = ComponentMapping(0, 1, 2, 3), Format = textureDesc.Format, Dimension = ShaderResourceViewDimension.Texture2D, }; srvDesc.Texture2D.MipLevels = 1; device.CreateShaderResourceView(_texture, srvDesc, _srvDescriptorHeap.CPUDescriptorHandleForHeapStart); _constantBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(1024 * 64), ResourceStates.GenericRead); //// Describe and create a constant buffer view. ConstantBufferViewDescription cbvDesc = new ConstantBufferViewDescription() { BufferLocation = _constantBuffer.GPUVirtualAddress, SizeInBytes = (Utilities.SizeOf <CBuffer>() + 255) & ~255 }; device.CreateConstantBufferView(cbvDesc, _constantBufferViewHeap.CPUDescriptorHandleForHeapStart); // Initialize and map the constant buffers. We don't unmap this until the // app closes. Keeping things mapped for the lifetime of the resource is okay. _constantBufferPointer = _constantBuffer.Map(0); Utilities.Write(_constantBufferPointer, ref buffer); _resources = new[] { new GraphicsResource() { Heap = _srvDescriptorHeap, Register = 0, type = ResourceType.DescriptorTable }, new GraphicsResource() { Resource = _constantBuffer, Register = 1, type = ResourceType.ConstantBufferView } }; }
private void CreateRootSignature() { //RootDescriptorTable table = new RootDescriptorTable() //{ //Ranges = new DescriptorRange() // { // } //} //RootParameter rootParameter = new RootParameter(RootDescriptorTable) //{ // DescriptorTable = new RootDescriptorTable //} DescriptorRange Ranges = new DescriptorRange() { BaseShaderRegister = 0, NumDescriptors = 1, OffsetInDescriptorsFromTableStart = 0, RangeType = DescriptorRangeType.ShaderResourceView, RegisterSpace = 0, }; RootParameter[] slotRootParameters = new RootParameter[] { //new RootParameter(new roo //new RootParameter(RootParameterType.ConstantBufferView, new RootDescriptor(0, 0), ShaderVisibility.All), //new RootParameter(RootParameterType.ConstantBufferView, new RootDescriptor(1, 0), ShaderVisibility.All), //new RootParameter(RootParameterType.ShaderResourceView, new RootDescriptor(1, 0), ShaderVisibility.All), //new RootParameter(new RootDescriptorTable(new DescriptorRange[]{ Ranges }), ShaderVisibility.All) }; RootSignatureDescription SignatureDesc = new RootSignatureDescription() { Flags = RootSignatureFlags.AllowInputAssemblerInputLayout, //Parameters = slotRootParameters, //StaticSamplers = new StaticSamplerDescription[] //{ // new StaticSamplerDescription() // { // ShaderRegister = 0, // RegisterSpace = 0, // ShaderVisibility = ShaderVisibility.Pixel, // Filter = Filter.MinMagMipPoint, // AddressU = TextureAddressMode.Border, // AddressV = TextureAddressMode.Border, // AddressW = TextureAddressMode.Border, // MipLODBias = 0, // MaxAnisotropy = 0, // ComparisonFunction = ComparisonFunction.Never, // BorderColor = StaticBorderColor.TransparentBlack, // MinLOD = 0.0f, // MaxLOD = int.MaxValue, // } //}, }; RootSignature = GraphicsDevice.NativeDevice.CreateRootSignature <ID3D12RootSignature>(0, SignatureDesc, RootSignatureVersion.Version10); //RootSignature. }
public static async Task RunAsync(GraphicsDevice device) { bool generateWithDelegate = false; // Create graphics buffer int width = 10; int height = 10; float[] array = new float[width * height]; for (int i = 0; i < array.Length; i++) { array[i] = i; } float[] outputArray = new float[width * height]; using GraphicsBuffer <float> sourceBuffer = GraphicsBuffer.Create <float>(device, array, ResourceFlags.None); using GraphicsBuffer <float> destinationBuffer = GraphicsBuffer.Create <float>(device, array.Length * 2, ResourceFlags.AllowUnorderedAccess); GraphicsBuffer <float> slicedDestinationBuffer = destinationBuffer.Slice(20, 60); slicedDestinationBuffer = slicedDestinationBuffer.Slice(10, 50); DescriptorSet descriptorSet = new DescriptorSet(device, 2); descriptorSet.AddUnorderedAccessViews(slicedDestinationBuffer); descriptorSet.AddShaderResourceViews(sourceBuffer); // Generate computer shader ShaderGenerator shaderGenerator = generateWithDelegate ? CreateShaderGeneratorWithDelegate(sourceBuffer, destinationBuffer) : CreateShaderGeneratorWithClass(); ShaderGeneratorResult result = shaderGenerator.GenerateShader(); // Compile shader byte[] shaderBytecode = ShaderCompiler.Compile(ShaderStage.ComputeShader, result.ShaderSource, result.EntryPoints["compute"]); DescriptorRange[] descriptorRanges = new DescriptorRange[] { new DescriptorRange(DescriptorRangeType.UnorderedAccessView, 1, 0), new DescriptorRange(DescriptorRangeType.ShaderResourceView, 1, 0) }; RootParameter rootParameter = new RootParameter(new RootDescriptorTable(descriptorRanges), ShaderVisibility.All); RootSignatureDescription rootSignatureDescription = new RootSignatureDescription(RootSignatureFlags.None, new[] { rootParameter }); RootSignature rootSignature = new RootSignature(device, rootSignatureDescription); PipelineState pipelineState = new PipelineState(device, rootSignature, shaderBytecode); // Execute computer shader using (CommandList commandList = new CommandList(device, CommandListType.Compute)) { commandList.SetPipelineState(pipelineState); commandList.SetComputeRootDescriptorTable(0, descriptorSet); commandList.Dispatch(1, 1, 1); await commandList.FlushAsync(); } // Print matrix Console.WriteLine("Before:"); PrintMatrix(array, width, height); destinationBuffer.GetData(outputArray.AsSpan()); Console.WriteLine(); Console.WriteLine("After:"); PrintMatrix(outputArray, width, height); }
private void LoadAssets() { DescriptorRange[] ranges = new DescriptorRange[] { new DescriptorRange() { RangeType = DescriptorRangeType.ConstantBufferView, BaseShaderRegister = 0, OffsetInDescriptorsFromTableStart = int.MinValue, DescriptorCount = 1 } }; RootParameter parameter = new RootParameter(ShaderVisibility.Vertex, ranges); // Create an empty root signature. RootSignatureDescription rootSignatureDesc = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout, new RootParameter[] { parameter }); rootSignature = device.CreateRootSignature(rootSignatureDesc.Serialize()); // Create the pipeline state, which includes compiling and loading shaders. #if DEBUG var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)); #else var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0")); #endif #if DEBUG var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)); #else var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0")); #endif // Define the vertex input layout. InputElement[] inputElementDescs = new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 12, 0) }; // Describe and create the graphics pipeline state object (PSO). GraphicsPipelineStateDescription psoDesc = new GraphicsPipelineStateDescription() { InputLayout = new InputLayoutDescription(inputElementDescs), RootSignature = rootSignature, VertexShader = vertexShader, PixelShader = pixelShader, RasterizerState = RasterizerStateDescription.Default(), BlendState = BlendStateDescription.Default(), DepthStencilFormat = SharpDX.DXGI.Format.D32_Float, DepthStencilState = new DepthStencilStateDescription() { IsDepthEnabled = false, IsStencilEnabled = false }, SampleMask = int.MaxValue, PrimitiveTopologyType = PrimitiveTopologyType.Triangle, RenderTargetCount = 1, Flags = PipelineStateFlags.None, SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0), StreamOutput = new StreamOutputDescription() }; psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm; pipelineState = device.CreateGraphicsPipelineState(psoDesc); // Create the command list. commandList = device.CreateCommandList(CommandListType.Direct, commandAllocator, pipelineState); // Create the vertex buffer. float aspectRatio = viewport.Width / viewport.Height; // Define the geometry for a triangle. Vertex[] triangleVertices = new Vertex[] { new Vertex() { position = new Vector3(0.0f, 0.25f * aspectRatio, 0.0f), color = new Vector4(1.0f, 0.0f, 0.0f, 1.0f) }, new Vertex() { position = new Vector3(0.25f, -0.25f * aspectRatio, 0.0f), color = new Vector4(0.0f, 1.0f, 0.0f, 1.0f) }, new Vertex() { position = new Vector3(-0.25f, -0.25f * aspectRatio, 0.0f), color = new Vector4(0.0f, 0.0f, 1.0f, 1.0f) }, }; int vertexBufferSize = Utilities.SizeOf(triangleVertices); // Note: using upload heaps to transfer static data like vert buffers is not // recommended. Every time the GPU needs it, the upload heap will be marshalled // over. Please read up on Default Heap usage. An upload heap is used here for // code simplicity and because there are very few verts to actually transfer. vertexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(vertexBufferSize), ResourceStates.GenericRead); // Copy the triangle data to the vertex buffer. IntPtr pVertexDataBegin = vertexBuffer.Map(0); Utilities.Write(pVertexDataBegin, triangleVertices, 0, triangleVertices.Length); vertexBuffer.Unmap(0); // Initialize the vertex buffer view. vertexBufferView = new VertexBufferView(); vertexBufferView.BufferLocation = vertexBuffer.GPUVirtualAddress; vertexBufferView.StrideInBytes = Utilities.SizeOf <Vertex>(); vertexBufferView.SizeInBytes = vertexBufferSize; // Command lists are created in the recording state, but there is nothing // to record yet. The main loop expects it to be closed, so close it now. commandList.Close(); constantBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(1024 * 64), ResourceStates.GenericRead); //// Describe and create a constant buffer view. ConstantBufferViewDescription cbvDesc = new ConstantBufferViewDescription() { BufferLocation = constantBuffer.GPUVirtualAddress, SizeInBytes = (Utilities.SizeOf <ConstantBuffer>() + 255) & ~255 }; device.CreateConstantBufferView(cbvDesc, constantBufferViewHeap.CPUDescriptorHandleForHeapStart); // Initialize and map the constant buffers. We don't unmap this until the // app closes. Keeping things mapped for the lifetime of the resource is okay. constantBufferPointer = constantBuffer.Map(0); Utilities.Write(constantBufferPointer, ref constantBufferData); // Create synchronization objects. fence = device.CreateFence(0, FenceFlags.None); fenceValue = 1; // Create an event handle to use for frame synchronization. fenceEvent = new AutoResetEvent(false); }