/// <summary> /// Builds an input layout based on what this shader requires, and the shader signature passed to it /// </summary> /// <param name="device">The D3D Device to create the layout with</param> /// <param name="inputSignature">The shader input signature to verify the input layout against</param> /// <returns> /// An input layout for this shader /// </returns> public InputLayout MakeInputLayout(Device device, ShaderSignature inputSignature) { return new InputLayout(device, inputSignature, new[] { new InputElement("POSITION", 0, SlimDX.DXGI.Format.R32G32B32_Float, 0), new InputElement("COLOR",0,SlimDX.DXGI.Format.R32G32B32_Float,0) }); }
public void Initialize(Device device) { _b = EffectUtils.Load("DeferredGObject"); E = new Effect(device, _b); TechStandardDeferred = E.GetTechniqueByName("StandardDeferred"); TechStandardForward = E.GetTechniqueByName("StandardForward"); TechAmbientShadowDeferred = E.GetTechniqueByName("AmbientShadowDeferred"); TechTransparentDeferred = E.GetTechniqueByName("TransparentDeferred"); TechTransparentForward = E.GetTechniqueByName("TransparentForward"); TechTransparentMask = E.GetTechniqueByName("TransparentMask"); for (var i = 0; i < TechStandardDeferred.Description.PassCount && InputSignaturePNTG == null; i++) { InputSignaturePNTG = TechStandardDeferred.GetPassByIndex(i).Description.Signature; } if (InputSignaturePNTG == null) throw new System.Exception("input signature (DeferredGObject, PNTG, StandardDeferred) == null"); LayoutPNTG = new InputLayout(device, InputSignaturePNTG, InputLayouts.VerticePNTG.InputElementsValue); for (var i = 0; i < TechAmbientShadowDeferred.Description.PassCount && InputSignaturePT == null; i++) { InputSignaturePT = TechAmbientShadowDeferred.GetPassByIndex(i).Description.Signature; } if (InputSignaturePT == null) throw new System.Exception("input signature (DeferredGObject, PT, AmbientShadowDeferred) == null"); LayoutPT = new InputLayout(device, InputSignaturePT, InputLayouts.VerticePT.InputElementsValue); FxWorld = E.GetVariableByName("gWorld").AsMatrix(); FxWorldInvTranspose = E.GetVariableByName("gWorldInvTranspose").AsMatrix(); FxWorldViewProj = E.GetVariableByName("gWorldViewProj").AsMatrix(); FxDiffuseMap = E.GetVariableByName("gDiffuseMap").AsResource(); FxNormalMap = E.GetVariableByName("gNormalMap").AsResource(); FxMapsMap = E.GetVariableByName("gMapsMap").AsResource(); FxDetailsMap = E.GetVariableByName("gDetailsMap").AsResource(); FxDetailsNormalMap = E.GetVariableByName("gDetailsNormalMap").AsResource(); FxReflectionCubemap = E.GetVariableByName("gReflectionCubemap").AsResource(); FxEyePosW = E.GetVariableByName("gEyePosW").AsVector(); FxAmbientDown = E.GetVariableByName("gAmbientDown").AsVector(); FxAmbientRange = E.GetVariableByName("gAmbientRange").AsVector(); FxLightColor = E.GetVariableByName("gLightColor").AsVector(); FxDirectionalLightDirection = E.GetVariableByName("gDirectionalLightDirection").AsVector(); FxMaterial = E.GetVariableByName("gMaterial"); }
private void GetSignatureAndReflection(ShaderBytecode sbc, ref ShaderSignature shaderSignature, ref ShaderReflection reflection) { shaderSignature = ShaderSignature.GetInputSignature(sbc); reflection = new ShaderReflection(sbc); }
public void Initialize(Device device) { _b = EffectUtils.Load("TestingPnt"); E = new Effect(device, _b); TechCube = E.GetTechniqueByName("Cube"); for (var i = 0; i < TechCube.Description.PassCount && InputSignaturePNT == null; i++) { InputSignaturePNT = TechCube.GetPassByIndex(i).Description.Signature; } if (InputSignaturePNT == null) throw new System.Exception("input signature (TestingPnt, PNT, Cube) == null"); LayoutPNT = new InputLayout(device, InputSignaturePNT, InputLayouts.VerticePNT.InputElementsValue); FxWorldViewProj = E.GetVariableByName("gWorldViewProj").AsMatrix(); }
private bool InitializeShader(Device device, IntPtr windowHandler, string vsFileName, string psFileName) { try { // Setup full pathes vsFileName = SystemConfiguration.ShadersFilePath + vsFileName; psFileName = SystemConfiguration.ShadersFilePath + psFileName; // Compile the vertex shader code. var vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFileName, "BumpMapVertexShader", SystemConfiguration.VertexShaderProfile, ShaderFlags.None, EffectFlags.None); // Compile the pixel shader code. var pixelShaderByteCode = ShaderBytecode.CompileFromFile(psFileName, "BumpMapPixelShader", SystemConfiguration.PixelShaderProfile, ShaderFlags.None, EffectFlags.None); // Create the vertex shader from the buffer. VertexShader = new VertexShader(device, vertexShaderByteCode); // Create the pixel shader from the buffer. PixelShader = new PixelShader(device, pixelShaderByteCode); // Now setup the layout of the data that goes into the shader. // This setup needs to match the VertexType structure in the Model and in the shader. var inputElements = new InputElement[] { new InputElement() { SemanticName = "POSITION", SemanticIndex = 0, Format = Format.R32G32B32_Float, Slot = 0, AlignedByteOffset = InputElement.AppendAligned, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 }, new InputElement() { SemanticName = "TEXCOORD", SemanticIndex = 0, Format = Format.R32G32_Float, Slot = 0, AlignedByteOffset = InputElement.AppendAligned, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 }, new InputElement() { SemanticName = "NORMAL", SemanticIndex = 0, Format = Format.R32G32B32_Float, Slot = 0, AlignedByteOffset = InputElement.AppendAligned, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 }, new InputElement() { SemanticName = "TANGENT", SemanticIndex = 0, Format = Format.R32G32B32_Float, Slot = 0, AlignedByteOffset = InputElement.AppendAligned, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 }, new InputElement() { SemanticName = "BINORMAL", SemanticIndex = 0, Format = Format.R32G32B32_Float, Slot = 0, AlignedByteOffset = InputElement.AppendAligned, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 } }; // Create the vertex input the layout. Layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements); // Release the vertex and pixel shader buffers, since they are no longer needed. vertexShaderByteCode.Dispose(); pixelShaderByteCode.Dispose(); // Setup the description of the dynamic matrix constant buffer that is in the vertex shader. var matrixBufferDesc = new BufferDescription() { Usage = ResourceUsage.Dynamic, SizeInBytes = Utilities.SizeOf <MatrixBuffer>(), BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class. ConstantMatrixBuffer = new Buffer(device, matrixBufferDesc); // Create a texture sampler state description. var samplerDesc = new SamplerStateDescription() { Filter = Filter.MinMagMipLinear, AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, MipLodBias = 0, MaximumAnisotropy = 1, ComparisonFunction = Comparison.Always, BorderColor = new Color4(0, 0, 0, 0), MinimumLod = 0, MaximumLod = 0 }; // Create the texture sampler state. SampleState = new SamplerState(device, samplerDesc); // Setup the description of the light dynamic constant bufffer that is in the pixel shader. var lightBufferDesc = new BufferDescription() { Usage = ResourceUsage.Dynamic, SizeInBytes = Utilities.SizeOf <LightBuffer>(), BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class. ConstantLightBuffer = new Buffer(device, lightBufferDesc); return(true); } catch (Exception ex) { MessageBox.Show("Error initializing shader. Error is " + ex.Message); return(false); }; }
public InputLayout CreateInputLayout(Renderer renderer, InputElement[] inputElementDescriptions) { ShaderSignature signature = ShaderSignature.GetInputSignature(_shaderByteCode); return(new InputLayout(renderer.Device, signature, inputElementDescriptions)); }
public void Initialise() { sw = new Stopwatch(); sw.Start(); // Set the minimum and maximum values for the bounding box. minV = new Vector3(1000.0f, 1000.0f, 1000.0f); maxV = new Vector3(-1000.0f, -1000.0f, -1000.0f); // Get the terrain size. int te_width = te.getTerrainSize(); int te_length = te.getTerrainSize(); // Initialise the vertex array. vl = new List <Vertex>(); vt = new Vertex[te_width * te_length]; for (int i = 0; i < te_width; i++) { for (int j = 0; j < te_length; j++) { vt[te_width * i + j] = new Vertex() { Position = new Vector4(te.heightmap[i, j].position.X, te.heightmap[i, j].position.Y, te.heightmap[i, j].position.Z, 1.0f), Normal = new Vector4(te.heightmap[i, j].normal.X, te.heightmap[i, j].normal.Y, te.heightmap[i, j].normal.Z, 1.0f), TexUV = new Vector2(0.5f, 0.5f), Color = new Vector4(0.13f, 0.5f, 0.2f, 1.0f) }; // Perform a check for the min and max values. // Update the bounds accordingly. minV.X = getMin(vt[te_width * i + j].Position.X, minV.X); minV.Y = getMin(vt[te_width * i + j].Position.Y, minV.Y); minV.Z = getMin(vt[te_width * i + j].Position.Z, minV.Z); maxV.X = getMax(vt[te_width * i + j].Position.X, maxV.X); maxV.Y = getMax(vt[te_width * i + j].Position.Y, maxV.Y); maxV.Z = getMax(vt[te_width * i + j].Position.Z, maxV.Z); } } for (int i = 0; i < te_width - 1; i++) { for (int j = 0; j < te_length - 1; j++) { // Triangle 1 int index = i * te_width + j; vl.Add(new Vertex() { Position = new Vector4(vt[index].Position.X, vt[index].Position.Y, vt[index].Position.Z, vt[index].Position.W), Normal = new Vector4(vt[index].Normal.X, vt[index].Normal.Y, vt[index].Normal.Z, vt[index].Normal.W), TexUV = new Vector2(0.0f, 0.0f), Color = new Vector4(0.3f, 0.7f, 0.5f, 1.0f) }); index = (i) * te_width + (j + 1); vl.Add(new Vertex() { Position = new Vector4(vt[index].Position.X, vt[index].Position.Y, vt[index].Position.Z, vt[index].Position.W), Normal = new Vector4(vt[index].Normal.X, vt[index].Normal.Y, vt[index].Normal.Z, vt[index].Normal.W), TexUV = new Vector2(0.0f, 1.0f), Color = new Vector4(0.3f, 0.7f, 0.5f, 1.0f) }); index = (i + 1) * te_width + (j + 1); vl.Add(new Vertex() { Position = new Vector4(vt[index].Position.X, vt[index].Position.Y, vt[index].Position.Z, vt[index].Position.W), Normal = new Vector4(vt[index].Normal.X, vt[index].Normal.Y, vt[index].Normal.Z, vt[index].Normal.W), TexUV = new Vector2(1.0f, 1.0f), Color = new Vector4(0.3f, 0.7f, 0.5f, 1.0f) }); // Triangle 2 index = (i + 1) * te_width + (j + 1); vl.Add(new Vertex() { Position = new Vector4(vt[index].Position.X, vt[index].Position.Y, vt[index].Position.Z, vt[index].Position.W), Normal = new Vector4(vt[index].Normal.X, vt[index].Normal.Y, vt[index].Normal.Z, vt[index].Normal.W), TexUV = new Vector2(1.0f, 1.0f), Color = new Vector4(0.3f, 0.7f, 0.5f, 1.0f) }); index = (i + 1) * te_width + (j); vl.Add(new Vertex() { Position = new Vector4(vt[index].Position.X, vt[index].Position.Y, vt[index].Position.Z, vt[index].Position.W), Normal = new Vector4(vt[index].Normal.X, vt[index].Normal.Y, vt[index].Normal.Z, vt[index].Normal.W), TexUV = new Vector2(1.0f, 0.0f), Color = new Vector4(0.3f, 0.7f, 0.5f, 1.0f) }); index = i * te_width + (j); vl.Add(new Vertex() { Position = new Vector4(vt[index].Position.X, vt[index].Position.Y, vt[index].Position.Z, vt[index].Position.W), Normal = new Vector4(vt[index].Normal.X, vt[index].Normal.Y, vt[index].Normal.Z, vt[index].Normal.W), TexUV = new Vector2(0.0f, 0.0f), Color = new Vector4(0.3f, 0.7f, 0.5f, 1.0f) }); } } var vt2 = vl.ToArray(); vertices = Buffer.Create(dev, BindFlags.VertexBuffer, vt2); //vertices = new Buffer(dev, Utilities.SizeOf<Vertex>() * vl.Count, // ResourceUsage.Dynamic, BindFlags.VertexBuffer, // CpuAccessFlags.Write, ResourceOptionFlags.None, 0); //dev.ImmediateContext.UpdateSubresource(vt2, vertices); bbc = new BBCorners(minV, maxV); var bb8corners = bbc.getBB8Corners(); bb = bbc.getBoundingBox(); bBox = Buffer.Create(dev, BindFlags.VertexBuffer, bb8corners); // Vertex and Pixel shaders. vsByteCode = ShaderBytecode.CompileFromFile("TerrainShader.hlsl", "VSMain", "vs_5_0", ShaderFlags.None, EffectFlags.None); vShader = new VertexShader(dev, vsByteCode); psByteCode = ShaderBytecode.CompileFromFile("TerrainShader.hlsl", "PSMain", "ps_5_0", ShaderFlags.None, EffectFlags.None); pShader = new PixelShader(dev, psByteCode); vsByteCode2 = ShaderBytecode.CompileFromFile("BBoxShader.hlsl", "VSMain", "vs_5_0", ShaderFlags.None, EffectFlags.None); vShader2 = new VertexShader(dev, vsByteCode2); psByteCode2 = ShaderBytecode.CompileFromFile("BBoxShader.hlsl", "PSMain", "ps_5_0", ShaderFlags.None, EffectFlags.None); pShader2 = new PixelShader(dev, psByteCode2); signature = ShaderSignature.GetInputSignature(vsByteCode); signature2 = ShaderSignature.GetInputSignature(vsByteCode2); // Input layout. layout = new InputLayout(dev, signature, new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("NORMAL", 0, Format.R32G32B32A32_Float, InputElement.AppendAligned, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, InputElement.AppendAligned, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, InputElement.AppendAligned, 0) }); layout2 = new InputLayout(dev, signature2, new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0) }); // Constant buffer cBuffer = new Buffer(dev, Utilities.SizeOf <cBufferStruct>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); // Texture ImageLoader imgLoader = new ImageLoader(); var texture = imgLoader.loadImage("grasstex.png", ref dev); textureView = new ShaderResourceView(dev, texture); colorSampler = new SamplerState(dev, new SamplerStateDescription() { Filter = Filter.MinMagMipLinear, AddressU = TextureAddressMode.Clamp, AddressV = TextureAddressMode.Clamp, AddressW = TextureAddressMode.Clamp, BorderColor = Color.Black, ComparisonFunction = Comparison.Never, MaximumAnisotropy = 16, MipLodBias = 0, MinimumLod = -float.MaxValue, MaximumLod = float.MaxValue }); // Set up matrices Vector3 eye = new Vector3(-20, 5, -20); Vector3 at = new Vector3(0, 0, 0); Vector3 up = Vector3.UnitY; view = Matrix.LookAtLH(eye, at, up); proj = Matrix.Identity; // Set up projection matrix with correct aspect ratio. proj = Matrix.PerspectiveFovLH((float)MathUtil.Pi / 4.0f, ((float)formWidth / (float)formHeight), 0.1f, 1000.0f); }
public static SharpDXInfo Initialize(IntPtr handle, System.Drawing.Size size, IEnumerable <VertexPositionColorTexture> rawVertices, IEnumerable <int> rawIndices, Matrix viewWorldProj, string texturePath) { var desc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(size.Width, size.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; // Create Device and SwapChain Device device; SwapChain swapChain; Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.Debug, desc, out device, out swapChain); var context = device.ImmediateContext; // Ignore all windows events var factory = swapChain.GetParent <Factory>(); factory.MakeWindowAssociation(handle, WindowAssociationFlags.IgnoreAll); // New RenderTargetView from the backbuffer var backBuffer = Texture2D.FromSwapChain <Texture2D>(swapChain, 0); var renderView = new RenderTargetView(device, backBuffer); // Compile Vertex and Pixel shaders using (var vertexShaderByteCode = ShaderBytecode.CompileFromFile(DefaultShaderPath, "VS", "vs_4_0")) using (var pixelShaderByteCode = ShaderBytecode.CompileFromFile(DefaultShaderPath, "PS", "ps_4_0")) { var vertexShader = new VertexShader(device, vertexShaderByteCode); var pixelShader = new PixelShader(device, pixelShaderByteCode); // Layout from VertexShader input signature var layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 32, 0), }); // Instantiate buffers var vertexBuffer = CreateBuffer <VertexPositionColorTexture>(device, BindFlags.VertexBuffer, rawVertices.Count()); var indexBuffer = CreateBuffer <int>(device, BindFlags.IndexBuffer, rawIndices.Count()); var cameraBuffer = CreateConstantBuffer <Matrix>(device); var depthBuffer = new Texture2D(device, new Texture2DDescription() { Format = Format.D32_Float_S8X24_UInt, ArraySize = 1, MipLevels = 1, Width = size.Width, Height = size.Height, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }); var depthView = new DepthStencilView(device, depthBuffer); // Load texture and create sampler var texture = Texture2D.FromFile <Texture2D>(device, texturePath); var textureView = new ShaderResourceView(device, texture); var sampler = new SamplerState(device, new SamplerStateDescription() { Filter = Filter.MinMagMipLinear, AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, BorderColor = Color.Black, ComparisonFunction = Comparison.Never, MaximumAnisotropy = 16, MipLodBias = 0, MinimumLod = 0, MaximumLod = 16, }); // initialize sharpdxlib context var info = new SharpDXInfo( device, swapChain, handle, size, depthView, renderView, vertexBuffer, indexBuffer, cameraBuffer, depthBuffer, rawVertices, rawIndices, texture, textureView, vertexShader, pixelShader, layout, backBuffer, factory); // Prepare All the stages context.InputAssembler.InputLayout = layout; context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, Utilities.SizeOf <VertexPositionColorTexture>(), 0)); context.InputAssembler.SetIndexBuffer(indexBuffer, Format.R32_UInt, 0); context.VertexShader.SetConstantBuffer(0, cameraBuffer); context.VertexShader.Set(vertexShader); RasterizerStateDescription rasdesc = new RasterizerStateDescription() { CullMode = CullMode.None, FillMode = FillMode.Solid, IsFrontCounterClockwise = true, DepthBias = 0, DepthBiasClamp = 0, SlopeScaledDepthBias = 0, IsDepthClipEnabled = true, IsMultisampleEnabled = true, }; context.Rasterizer.State = new RasterizerState(device, rasdesc); context.Rasterizer.SetViewport(new Viewport(0, 0, size.Width, size.Height, 0.0f, 1)); context.PixelShader.Set(pixelShader); context.PixelShader.SetSampler(0, sampler); context.PixelShader.SetShaderResource(0, textureView); context.OutputMerger.SetTargets(depthView, renderView); UpdateVertexBuffer(info, rawVertices); UpdateIndexBuffer(info, rawIndices); UpdateCameraBuffer(info, viewWorldProj); return(info); } }
public void Initialize(Device device) { _b = EffectUtils.Load("KunosShader"); E = new Effect(device, _b); TechPerPixel = E.GetTechniqueByName("PerPixel"); for (var i = 0; i < TechPerPixel.Description.PassCount && InputSignaturePNT == null; i++) { InputSignaturePNT = TechPerPixel.GetPassByIndex(i).Description.Signature; } if (InputSignaturePNT == null) throw new System.Exception("input signature (KunosShader, PNT, PerPixel) == null"); LayoutPNT = new InputLayout(device, InputSignaturePNT, InputLayouts.VerticePNT.InputElementsValue); FxWorld = E.GetVariableByName("gWorld").AsMatrix(); FxWorldInvTranspose = E.GetVariableByName("gWorldInvTranspose").AsMatrix(); FxWorldViewProj = E.GetVariableByName("gWorldViewProj").AsMatrix(); FxDiffuseMap = E.GetVariableByName("gDiffuseMap").AsResource(); FxEyePosW = E.GetVariableByName("gEyePosW").AsVector(); FxMaterial = E.GetVariableByName("gMaterial"); }
public void Initialize(Device device) { _b = EffectUtils.Load("DeferredTransparent"); E = new Effect(device, _b); TechDebug = E.GetTechniqueByName("Debug"); TechDebugPost = E.GetTechniqueByName("DebugPost"); TechDebugLighting = E.GetTechniqueByName("DebugLighting"); TechDebugLocalReflections = E.GetTechniqueByName("DebugLocalReflections"); TechCombine0 = E.GetTechniqueByName("Combine0"); for (var i = 0; i < TechDebug.Description.PassCount && InputSignaturePT == null; i++) { InputSignaturePT = TechDebug.GetPassByIndex(i).Description.Signature; } if (InputSignaturePT == null) throw new System.Exception("input signature (DeferredTransparent, PT, Debug) == null"); LayoutPT = new InputLayout(device, InputSignaturePT, InputLayouts.VerticePT.InputElementsValue); FxWorldViewProjInv = E.GetVariableByName("gWorldViewProjInv").AsMatrix(); FxBaseMap = E.GetVariableByName("gBaseMap").AsResource(); FxNormalMap = E.GetVariableByName("gNormalMap").AsResource(); FxMapsMap = E.GetVariableByName("gMapsMap").AsResource(); FxDepthMap = E.GetVariableByName("gDepthMap").AsResource(); FxLightMap = E.GetVariableByName("gLightMap").AsResource(); FxLocalReflectionMap = E.GetVariableByName("gLocalReflectionMap").AsResource(); FxReflectionCubemap = E.GetVariableByName("gReflectionCubemap").AsResource(); FxAmbientDown = E.GetVariableByName("gAmbientDown").AsVector(); FxAmbientRange = E.GetVariableByName("gAmbientRange").AsVector(); FxEyePosW = E.GetVariableByName("gEyePosW").AsVector(); }
public void Initialize(Device device) { _b = EffectUtils.Load("DeferredPpSslr"); E = new Effect(device, _b); TechHabrahabrVersion = E.GetTechniqueByName("HabrahabrVersion"); for (var i = 0; i < TechHabrahabrVersion.Description.PassCount && InputSignaturePT == null; i++) { InputSignaturePT = TechHabrahabrVersion.GetPassByIndex(i).Description.Signature; } if (InputSignaturePT == null) throw new System.Exception("input signature (DeferredPpSslr, PT, HabrahabrVersion) == null"); LayoutPT = new InputLayout(device, InputSignaturePT, InputLayouts.VerticePT.InputElementsValue); FxWorldViewProjInv = E.GetVariableByName("gWorldViewProjInv").AsMatrix(); FxWorldViewProj = E.GetVariableByName("gWorldViewProj").AsMatrix(); FxBaseMap = E.GetVariableByName("gBaseMap").AsResource(); FxLightMap = E.GetVariableByName("gLightMap").AsResource(); FxNormalMap = E.GetVariableByName("gNormalMap").AsResource(); FxMapsMap = E.GetVariableByName("gMapsMap").AsResource(); FxDepthMap = E.GetVariableByName("gDepthMap").AsResource(); FxEyePosW = E.GetVariableByName("gEyePosW").AsVector(); }
public void Initialize(Device device) { _b = EffectUtils.Load("DeferredLight"); E = new Effect(device, _b); TechPointLight = E.GetTechniqueByName("PointLight"); TechPointLight_NoSpec = E.GetTechniqueByName("PointLight_NoSpec"); TechPointLight_Debug = E.GetTechniqueByName("PointLight_Debug"); TechDirectionalLight = E.GetTechniqueByName("DirectionalLight"); TechDirectionalLight_Shadows = E.GetTechniqueByName("DirectionalLight_Shadows"); TechDirectionalLight_Shadows_NoFilter = E.GetTechniqueByName("DirectionalLight_Shadows_NoFilter"); TechDirectionalLight_Split = E.GetTechniqueByName("DirectionalLight_Split"); for (var i = 0; i < TechDirectionalLight.Description.PassCount && InputSignaturePT == null; i++) { InputSignaturePT = TechDirectionalLight.GetPassByIndex(i).Description.Signature; } if (InputSignaturePT == null) throw new System.Exception("input signature (DeferredLight, PT, DirectionalLight) == null"); LayoutPT = new InputLayout(device, InputSignaturePT, InputLayouts.VerticePT.InputElementsValue); FxWorld = E.GetVariableByName("gWorld").AsMatrix(); FxWorldInvTranspose = E.GetVariableByName("gWorldInvTranspose").AsMatrix(); FxWorldViewProj = E.GetVariableByName("gWorldViewProj").AsMatrix(); FxWorldViewProjInv = E.GetVariableByName("gWorldViewProjInv").AsMatrix(); FxShadowViewProj = E.GetVariableByName("gShadowViewProj").AsMatrix(); FxBaseMap = E.GetVariableByName("gBaseMap").AsResource(); FxNormalMap = E.GetVariableByName("gNormalMap").AsResource(); FxMapsMap = E.GetVariableByName("gMapsMap").AsResource(); FxDepthMap = E.GetVariableByName("gDepthMap").AsResource(); FxShadowMaps = E.GetVariableByName("gShadowMaps").AsResource(); FxPointLightRadius = E.GetVariableByName("gPointLightRadius").AsScalar(); FxScreenSize = E.GetVariableByName("gScreenSize").AsVector(); FxLightColor = E.GetVariableByName("gLightColor").AsVector(); FxDirectionalLightDirection = E.GetVariableByName("gDirectionalLightDirection").AsVector(); FxPointLightPosition = E.GetVariableByName("gPointLightPosition").AsVector(); FxShadowDepths = E.GetVariableByName("gShadowDepths").AsVector(); FxEyePosW = E.GetVariableByName("gEyePosW").AsVector(); }
public void Initialize(Device device) { _b = EffectUtils.Load("DeferredGSky"); E = new Effect(device, _b); TechSkyDeferred = E.GetTechniqueByName("SkyDeferred"); TechSkyForward = E.GetTechniqueByName("SkyForward"); for (var i = 0; i < TechSkyDeferred.Description.PassCount && InputSignatureP == null; i++) { InputSignatureP = TechSkyDeferred.GetPassByIndex(i).Description.Signature; } if (InputSignatureP == null) throw new System.Exception("input signature (DeferredGSky, P, SkyDeferred) == null"); LayoutP = new InputLayout(device, InputSignatureP, InputLayouts.VerticeP.InputElementsValue); FxWorld = E.GetVariableByName("gWorld").AsMatrix(); FxWorldInvTranspose = E.GetVariableByName("gWorldInvTranspose").AsMatrix(); FxWorldViewProj = E.GetVariableByName("gWorldViewProj").AsMatrix(); FxSkyDown = E.GetVariableByName("gSkyDown").AsVector(); FxSkyRange = E.GetVariableByName("gSkyRange").AsVector(); }
public void Initialize(Device device) { _b = EffectUtils.Load("DeferredGObjectSpecial"); E = new Effect(device, _b); TechSpecialGlDeferred = E.GetTechniqueByName("SpecialGlDeferred"); TechSpecialGlForward = E.GetTechniqueByName("SpecialGlForward"); TechSpecialGlMask = E.GetTechniqueByName("SpecialGlMask"); for (var i = 0; i < TechSpecialGlDeferred.Description.PassCount && InputSignaturePNTG == null; i++) { InputSignaturePNTG = TechSpecialGlDeferred.GetPassByIndex(i).Description.Signature; } if (InputSignaturePNTG == null) throw new System.Exception("input signature (DeferredGObjectSpecial, PNTG, SpecialGlDeferred) == null"); LayoutPNTG = new InputLayout(device, InputSignaturePNTG, InputLayouts.VerticePNTG.InputElementsValue); FxWorld = E.GetVariableByName("gWorld").AsMatrix(); FxWorldInvTranspose = E.GetVariableByName("gWorldInvTranspose").AsMatrix(); FxWorldViewProj = E.GetVariableByName("gWorldViewProj").AsMatrix(); }
private void CreateMesh() { var device = Direct2D1Platform.Direct3D11Device; // Compile Vertex and Pixel shaders var vertexShaderByteCode = ShaderBytecode.CompileFromFile("MiniCube.fx", "VS", "vs_4_0"); var vertexShader = new VertexShader(device, vertexShaderByteCode); var pixelShaderByteCode = ShaderBytecode.CompileFromFile("MiniCube.fx", "PS", "ps_4_0"); var pixelShader = new PixelShader(device, pixelShaderByteCode); var signature = ShaderSignature.GetInputSignature(vertexShaderByteCode); var inputElements = new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0) }; // Layout from VertexShader input signature var layout = new InputLayout( device, signature, inputElements); // Instantiate Vertex buffer from vertex data var vertices = Buffer.Create( device, BindFlags.VertexBuffer, new[] { new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), // Front new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), // BACK new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), // Top new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), // Bottom new Vector4(1.0f, -1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), new Vector4(1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), new Vector4(1.0f, -1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), // Left new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), new Vector4(1.0f, -1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), // Right new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, -1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), }); // Create Constant Buffer _contantBuffer = new Buffer(device, Utilities.SizeOf <Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); var context = Direct2D1Platform.Direct3D11Device.ImmediateContext; // Prepare All the stages context.InputAssembler.InputLayout = layout; context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, Utilities.SizeOf <Vector4>() * 2, 0)); context.VertexShader.SetConstantBuffer(0, _contantBuffer); context.VertexShader.Set(vertexShader); context.PixelShader.Set(pixelShader); }
private unsafe void CreateDeviceObjects() { IO io = ImGui.GetIO(); // Build texture atlas FontTextureData texData = io.FontAtlas.GetTexDataAsRGBA32(); // Create DirectX Texture fontTexture = new Texture2D(Device, new Texture2DDescription() { Width = texData.Width, Height = texData.Height, MipLevels = 1, ArraySize = 1, Format = SharpDX.DXGI.Format.R8G8B8A8_UNorm, SampleDescription = new SharpDX.DXGI.SampleDescription(1, 1), Usage = ResourceUsage.Default, BindFlags = BindFlags.ShaderResource, CpuAccessFlags = 0 }, new SharpDX.DataRectangle(new IntPtr(texData.Pixels), texData.Width)); fontTextureView = new ShaderResourceView(Device, fontTexture, new ShaderResourceViewDescription() { Format = SharpDX.DXGI.Format.R8G8B8A8_UNorm, Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.Texture2D, Texture2D = new ShaderResourceViewDescription.Texture2DResource() { MipLevels = 1, MostDetailedMip = 0, } }); io.FontAtlas.SetTexID(FontTextureId); // Create texture sampler fontSampler = new SamplerState(Device, new SamplerStateDescription() { Filter = Filter.MinMagMipLinear, AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, MipLodBias = 0.0f, ComparisonFunction = Comparison.Always, MinimumLod = 0.0f, MaximumLod = 0.0f }); // Compile Shader var vertexShaderByteCode = ShaderBytecode.Compile(vertexShaderCode, "vs_4_0", ShaderFlags.None, EffectFlags.None); var vertexShader = new VertexShader(Device, vertexShaderByteCode); var pixelShaderByteCode = ShaderBytecode.Compile(pixelShaderCode, "ps_4_0", ShaderFlags.None, EffectFlags.None); var pixelShader = new PixelShader(Device, pixelShaderByteCode); inputLayout = new InputLayout(Device, ShaderSignature.GetInputSignature(vertexShaderByteCode), new[] { new InputElement("POSITION", 0, Format.R32G32_Float, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 1), new InputElement("COLOR", 0, Format.R8G8B8A8_UNorm, 2) }); vertexConstantBuffer = new Buffer(Device, SharpDX.Utilities.SizeOf <SharpDX.Matrix>(), ResourceUsage.Dynamic, BindFlags.ConstantBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, 0); // Create the blending setup var blendStateDesc = new BlendStateDescription(); blendStateDesc.AlphaToCoverageEnable = true; blendStateDesc.RenderTarget[0].IsBlendEnabled = true; blendStateDesc.RenderTarget[0].SourceAlphaBlend = BlendOption.SourceAlpha; blendStateDesc.RenderTarget[0].DestinationBlend = BlendOption.InverseSourceAlpha; blendStateDesc.RenderTarget[0].BlendOperation = BlendOperation.Add; blendStateDesc.RenderTarget[0].SourceBlend = BlendOption.InverseSourceAlpha; blendStateDesc.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero; blendStateDesc.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add; blendStateDesc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; blendState = new BlendState(Device, blendStateDesc); // Create the rasterizer state rasterizerState = new RasterizerState(Device, new RasterizerStateDescription() { FillMode = FillMode.Solid, CullMode = CullMode.None, IsScissorEnabled = true, IsDepthClipEnabled = true, }); // Create depth-stencil State depthStencilState = new DepthStencilState(Device, new DepthStencilStateDescription() { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Always, IsStencilEnabled = false, FrontFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Keep, PassOperation = StencilOperation.Keep }, BackFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Keep, PassOperation = StencilOperation.Keep } }); }
public void Initialize(Device device) { _b = EffectUtils.Load("PpBasic"); E = new Effect(device, _b); TechCopy = E.GetTechniqueByName("Copy"); TechCopyNoAlpha = E.GetTechniqueByName("CopyNoAlpha"); TechOverlay = E.GetTechniqueByName("Overlay"); TechShadow = E.GetTechniqueByName("Shadow"); TechDepth = E.GetTechniqueByName("Depth"); TechFxaa = E.GetTechniqueByName("Fxaa"); for (var i = 0; i < TechCopy.Description.PassCount && InputSignaturePT == null; i++) { InputSignaturePT = TechCopy.GetPassByIndex(i).Description.Signature; } if (InputSignaturePT == null) throw new System.Exception("input signature (PpBasic, PT, Copy) == null"); LayoutPT = new InputLayout(device, InputSignaturePT, InputLayouts.VerticePT.InputElementsValue); FxInputMap = E.GetVariableByName("gInputMap").AsResource(); FxOverlayMap = E.GetVariableByName("gOverlayMap").AsResource(); FxDepthMap = E.GetVariableByName("gDepthMap").AsResource(); FxSizeMultipler = E.GetVariableByName("gSizeMultipler").AsScalar(); FxScreenSize = E.GetVariableByName("gScreenSize").AsVector(); }
public override void Initialize() { try { using (ShaderBytecode geometryShaderByteCode = ShaderBytecode.CompileFromFile( "Shaders/Sprite.fx", "mainGS", "gs_4_0", ShaderFlags.None, EffectFlags.None, null, new IncludeFX("Shaders"))) { geometryShader = new GeometryShader(DeviceManager.Instance.device, geometryShaderByteCode); } using (ShaderBytecode vertexShaderByteCode = ShaderBytecode.CompileFromFile( "Shaders/Sprite.fx", "mainVS", "vs_4_0", ShaderFlags.None, EffectFlags.None, null, new IncludeFX("Shaders"))) { vertexShader = new VertexShader(DeviceManager.Instance.device, vertexShaderByteCode); inputSignature = ShaderSignature.GetInputSignature(vertexShaderByteCode); } using (ShaderBytecode pixelShaderByteCode = ShaderBytecode.CompileFromFile( "Shaders/Sprite.fx", "mainPS", "ps_4_0", ShaderFlags.None, EffectFlags.None, null, new IncludeFX("Shaders"))) { pixelShader = new PixelShader(DeviceManager.Instance.device, pixelShaderByteCode); } layout = new InputLayout(DeviceManager.Instance.device, inputSignature, elements); #region Blend States RenderTargetBlendDescription rtBlendDefault = new RenderTargetBlendDescription() { BlendEnable = true, BlendOperation = BlendOperation.Add, RenderTargetWriteMask = ColorWriteMaskFlags.All, SourceBlend = BlendOption.SourceAlpha, DestinationBlend = BlendOption.InverseSourceAlpha, BlendOperationAlpha = BlendOperation.Add, SourceBlendAlpha = BlendOption.SourceAlpha, DestinationBlendAlpha = BlendOption.InverseSourceAlpha, }; BlendStateDescription bBlendStateDefault = new BlendStateDescription(); bBlendStateDefault.AlphaToCoverageEnable = false; bBlendStateDefault.IndependentBlendEnable = false; bBlendStateDefault.RenderTargets[0] = rtBlendDefault; blendStateDepth = BlendState.FromDescription(DeviceManager.Instance.device, bBlendStateDefault); #endregion #region Depth Stencils DepthStencilStateDescription dsStateNoDepth = new DepthStencilStateDescription() { IsDepthEnabled = false, DepthWriteMask = DepthWriteMask.Zero }; depthStencilStateNoDepth = DepthStencilState.FromDescription(DeviceManager.Instance.device, dsStateNoDepth); #endregion } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }
public void Initialize(Device device) { _b = EffectUtils.Load("PpBlur"); E = new Effect(device, _b); TechGaussianBlur = E.GetTechniqueByName("GaussianBlur"); TechReflectionGaussianBlur = E.GetTechniqueByName("ReflectionGaussianBlur"); for (var i = 0; i < TechGaussianBlur.Description.PassCount && InputSignaturePT == null; i++) { InputSignaturePT = TechGaussianBlur.GetPassByIndex(i).Description.Signature; } if (InputSignaturePT == null) throw new System.Exception("input signature (PpBlur, PT, GaussianBlur) == null"); LayoutPT = new InputLayout(device, InputSignaturePT, InputLayouts.VerticePT.InputElementsValue); FxInputMap = E.GetVariableByName("gInputMap").AsResource(); FxMapsMap = E.GetVariableByName("gMapsMap").AsResource(); FxSampleWeights = E.GetVariableByName("gSampleWeights").AsScalar(); FxPower = E.GetVariableByName("gPower").AsScalar(); FxSampleOffsets = E.GetVariableByName("gSampleOffsets").AsVector(); }
void RenderingQuard(GraphicsDevice graphics, TProperties props) { var device = graphics.D3DDevice; var context = graphics.ImmediateContext; context.ResolveSubresource(colorTargetTex2D.Get(), 0, colorTargetNoMSAA.Get().Resource, 0, colorDesc.Format); context.ResolveSubresource(alphaTargetTex2D.Get(), 0, alphaTargetNoMSAA.Get().Resource, 0, alphaDesc.Format); context.VertexShader.Set(vertexShaderQuard.Get()); context.PixelShader.Set(pixelShaderQuard.Get()); context.PixelShader.SetShaderResources(10, new[] { colorTargetNoMSAA.Get(), alphaTargetNoMSAA.Get() }); context.PixelShader.SetSampler(0, targetSampler.Get()); var inputSignature = ShaderSignature.GetInputSignature(quardPass.VertexShader.ReadCompiledBytes()); context.InputAssembler.InputLayout = new InputLayout(device, inputSignature, new[] { new InputElement("SV_VERTEXID", 0, Format.R32_UInt, 0) }); context.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleStrip; var BSAlphaBlend = new BlendStateDescription(); BSAlphaBlend.RenderTarget[0] = new RenderTargetBlendDescription() { AlphaBlendOperation = BlendOperation.Add, BlendOperation = BlendOperation.Add, SourceBlend = BlendOption.SourceAlpha, DestinationBlend = BlendOption.InverseSourceAlpha, SourceAlphaBlend = BlendOption.SourceAlpha, DestinationAlphaBlend = BlendOption.DestinationAlpha, IsBlendEnabled = true, RenderTargetWriteMask = ColorWriteMaskFlags.All }; var DSSNoDepthNoStencil = new DepthStencilStateDescription() { IsDepthEnabled = false, IsStencilEnabled = false, DepthWriteMask = DepthWriteMask.Zero, DepthComparison = Comparison.Always, FrontFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Keep, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always }, BackFace = new DepthStencilOperationDescription() { Comparison = Comparison.Always, FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Keep, PassOperation = StencilOperation.Keep }, StencilReadMask = 0, StencilWriteMask = 0 }; context.OutputMerger.SetDepthStencilState(new DepthStencilState(device, DSSNoDepthNoStencil), 0); context.OutputMerger.SetBlendState(new BlendState(device, BSAlphaBlend), new SharpDX.Mathematics.Interop.RawColor4(0, 0, 0, 0), -1); //context.OutputMerger.SetTargets(quardTargetView.Get()); var rester = new RasterizerStateDescription2 { CullMode = CullMode.None, FillMode = FillMode.Solid, DepthBias = 0, DepthBiasClamp = 0, SlopeScaledDepthBias = 0, IsFrontCounterClockwise = false, IsMultisampleEnabled = false, IsAntialiasedLineEnabled = false, IsDepthClipEnabled = false, IsScissorEnabled = true }; using (var rasterizerState = graphics.CreateRasterizerState(rester)) { context.Rasterizer.State = rasterizerState; graphics.ImmediateContext.Draw(4, 0); } }
public void Initialize(Device device) { _b = EffectUtils.Load("PpHdr"); E = new Effect(device, _b); TechDownsampling = E.GetTechniqueByName("Downsampling"); TechAdaptation = E.GetTechniqueByName("Adaptation"); TechTonemap = E.GetTechniqueByName("Tonemap"); TechCopy = E.GetTechniqueByName("Copy"); TechCombine = E.GetTechniqueByName("Combine"); TechBloom = E.GetTechniqueByName("Bloom"); for (var i = 0; i < TechDownsampling.Description.PassCount && InputSignaturePT == null; i++) { InputSignaturePT = TechDownsampling.GetPassByIndex(i).Description.Signature; } if (InputSignaturePT == null) throw new System.Exception("input signature (PpHdr, PT, Downsampling) == null"); LayoutPT = new InputLayout(device, InputSignaturePT, InputLayouts.VerticePT.InputElementsValue); FxInputMap = E.GetVariableByName("gInputMap").AsResource(); FxBrightnessMap = E.GetVariableByName("gBrightnessMap").AsResource(); FxBloomMap = E.GetVariableByName("gBloomMap").AsResource(); FxPixel = E.GetVariableByName("gPixel").AsVector(); FxCropImage = E.GetVariableByName("gCropImage").AsVector(); }
public ImGuiRender(DX11 dx11, RenderForm form, CoreSettings coreSettings) { _form = form; Dx11 = dx11; CoreSettings = coreSettings; FormBounds = form.Bounds; using (new PerformanceTimer("Init ImGui")) { Initialize(); } sizeOfImDrawVert = Utilities.SizeOf <ImDrawVert>(); sizeOfImDrawIdx = Utilities.SizeOf <ushort>(); VertexBufferSize = 10000; IndexBufferSize = 30000; // Compile the vertex shader code. var vertexShaderByteCode = ShaderBytecode.CompileFromFile("Shaders\\ImGuiVertexShader.hlsl", "VS", "vs_4_0"); // Compile the pixel shader code. var pixelShaderByteCode = ShaderBytecode.CompileFromFile("Shaders\\ImGuiPixelShader.hlsl", "PS", "ps_4_0"); VertexShader = new VertexShader(Dx11.D11Device, vertexShaderByteCode); PixelShader = new PixelShader(Dx11.D11Device, pixelShaderByteCode); VertexBuffer = new Buffer(Dx11.D11Device, new BufferDescription { Usage = ResourceUsage.Dynamic, BindFlags = BindFlags.VertexBuffer, OptionFlags = ResourceOptionFlags.None, CpuAccessFlags = CpuAccessFlags.Write, SizeInBytes = VertexBufferSizeBytes }); IndexBuffer = new Buffer(Dx11.D11Device, new BufferDescription { Usage = ResourceUsage.Dynamic, BindFlags = BindFlags.IndexBuffer, OptionFlags = ResourceOptionFlags.None, CpuAccessFlags = CpuAccessFlags.Write, SizeInBytes = IndexBufferSizeBytes }); ConstantBuffer = new Buffer(Dx11.D11Device, new BufferDescription { BindFlags = BindFlags.ConstantBuffer, Usage = ResourceUsage.Dynamic, OptionFlags = ResourceOptionFlags.None, CpuAccessFlags = CpuAccessFlags.Write, SizeInBytes = Utilities.SizeOf <Matrix4x4>() }); var inputElements = new[] { new InputElement { SemanticName = "POSITION", SemanticIndex = 0, Format = Format.R32G32_Float, Slot = 0, AlignedByteOffset = 0, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 }, new InputElement { SemanticName = "TEXCOORD", SemanticIndex = 0, Format = Format.R32G32_Float, Slot = 0, AlignedByteOffset = InputElement.AppendAligned, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 }, new InputElement { SemanticName = "COLOR", SemanticIndex = 0, Format = Format.R8G8B8A8_UNorm, Slot = 0, AlignedByteOffset = InputElement.AppendAligned, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 } }; Layout = new InputLayout(Dx11.D11Device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements); CreateStates(); UpdateConstantBuffer(); vertexShaderByteCode.Dispose(); pixelShaderByteCode.Dispose(); }
public void Initialize(Device device) { _b = EffectUtils.Load("PpOutline"); E = new Effect(device, _b); TechOutline = E.GetTechniqueByName("Outline"); for (var i = 0; i < TechOutline.Description.PassCount && InputSignaturePT == null; i++) { InputSignaturePT = TechOutline.GetPassByIndex(i).Description.Signature; } if (InputSignaturePT == null) throw new System.Exception("input signature (PpOutline, PT, Outline) == null"); LayoutPT = new InputLayout(device, InputSignaturePT, InputLayouts.VerticePT.InputElementsValue); FxInputMap = E.GetVariableByName("gInputMap").AsResource(); FxDepthMap = E.GetVariableByName("gDepthMap").AsResource(); FxScreenSize = E.GetVariableByName("gScreenSize").AsVector(); }
public void init() { form = new RenderForm("My HelloWorld SlimDX app"); var description = new SwapChainDescription() { BufferCount = 1, Usage = Usage.RenderTargetOutput, OutputHandle = form.Handle, IsWindowed = true, ModeDescription = new ModeDescription(0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm), SampleDescription = new SampleDescription(1, 0), Flags = SwapChainFlags.AllowModeSwitch, SwapEffect = SwapEffect.Discard }; Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, description, out device, out swapChain); // create a view of our render target, which is the backbuffer of the swap chain we just created using (var resource = Resource.FromSwapChain<Texture2D>(swapChain, 0)) renderTarget = new RenderTargetView(device, resource); // setting a viewport is required if you want to actually see anything context = device.ImmediateContext; var viewport = new Viewport(0.0f, 0.0f, form.ClientSize.Width, form.ClientSize.Height); context.OutputMerger.SetTargets(renderTarget); context.Rasterizer.SetViewports(viewport); // load and compile the vertex shader using (var bytecode = ShaderBytecode.CompileFromFile("triangle.fx", "VShader", "vs_4_0", ShaderFlags.None, EffectFlags.None)) { inputSignature = ShaderSignature.GetInputSignature(bytecode); vertexShader = new VertexShader(device, bytecode); } // load and compile the pixel shader using (var bytecode = ShaderBytecode.CompileFromFile("triangle.fx", "PShader", "ps_4_0", ShaderFlags.None, EffectFlags.None)) pixelShader = new PixelShader(device, bytecode); elements = new[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0) }; layout = new InputLayout(device, inputSignature, elements); // prevent DXGI handling of alt+enter, which doesn't work properly with Winforms using (var factory = swapChain.GetParent<Factory>()) factory.SetWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAltEnter); // handle alt+enter ourselves form.KeyDown += (o, e) => { if (e.Alt && e.KeyCode == System.Windows.Forms.Keys.Enter) swapChain.IsFullScreen = !swapChain.IsFullScreen; }; // handle form size changes form.UserResized += (o, e) => { renderTarget.Dispose(); swapChain.ResizeBuffers(2, 0, 0, Format.R8G8B8A8_UNorm, SwapChainFlags.AllowModeSwitch); using (var resource = Resource.FromSwapChain<Texture2D>(swapChain, 0)) renderTarget = new RenderTargetView(device, resource); context.OutputMerger.SetTargets(renderTarget); }; }
public void Initialize(Device device) { _b = EffectUtils.Load("PpSmaa"); E = new Effect(device, _b); TechSmaa = E.GetTechniqueByName("Smaa"); TechSmaaB = E.GetTechniqueByName("SmaaB"); TechSmaaN = E.GetTechniqueByName("SmaaN"); for (var i = 0; i < TechSmaa.Description.PassCount && InputSignaturePT == null; i++) { InputSignaturePT = TechSmaa.GetPassByIndex(i).Description.Signature; } if (InputSignaturePT == null) throw new System.Exception("input signature (PpSmaa, PT, Smaa) == null"); LayoutPT = new InputLayout(device, InputSignaturePT, InputLayouts.VerticePT.InputElementsValue); FxInputMap = E.GetVariableByName("gInputMap").AsResource(); FxEdgesMap = E.GetVariableByName("gEdgesMap").AsResource(); FxBlendMap = E.GetVariableByName("gBlendMap").AsResource(); FxAreaTexMap = E.GetVariableByName("gAreaTexMap").AsResource(); FxSearchTexMap = E.GetVariableByName("gSearchTexMap").AsResource(); FxSizeMultipler = E.GetVariableByName("gSizeMultipler").AsScalar(); FxScreenSizeSpec = E.GetVariableByName("gScreenSizeSpec").AsVector(); }
public void InitializeDevice() { isInitialized = false; try { // Declare and create the Device and SwapChain. var desc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(mParent.ClientSize.Width, mParent.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = mParent.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; Factory fact = new Factory(); Device.CreateWithSwapChain(fact.GetAdapter(0), DriverType.Hardware, DeviceCreationFlags.None, desc, out device, out swapChain); Device context = device; shaderEffect = ShaderHelper.GetEffect(device); shaderHelper.Initialize(device, shaderEffect); shaderSignature = shaderEffect.GetTechniqueByIndex(0).GetPassByIndex(0).Description.Signature; // Scale the buffers appropriately to the size of the parent control. isInitialized = true; ResizeBuffers(); EnableAlphaBlending(); UpdateTextures(); UpdateAllShapes(); } catch (Direct3D10Exception ex) { MessageBox.Show("" + ex.Message + "\n\n" + ex.ResultCode.Code.ToString("X") + "\n\n" + ex.StackTrace); return; } }
public void Initialize(Device device) { _b = EffectUtils.Load("SimpleMaterial"); E = new Effect(device, _b); TechStandard = E.GetTechniqueByName("Standard"); TechAlpha = E.GetTechniqueByName("Alpha"); TechReflective = E.GetTechniqueByName("Reflective"); TechNm = E.GetTechniqueByName("Nm"); TechNmUvMult = E.GetTechniqueByName("NmUvMult"); TechAtNm = E.GetTechniqueByName("AtNm"); TechMaps = E.GetTechniqueByName("Maps"); TechDiffMaps = E.GetTechniqueByName("DiffMaps"); TechGl = E.GetTechniqueByName("Gl"); TechAmbientShadow = E.GetTechniqueByName("AmbientShadow"); TechMirror = E.GetTechniqueByName("Mirror"); for (var i = 0; i < TechAmbientShadow.Description.PassCount && InputSignaturePT == null; i++) { InputSignaturePT = TechAmbientShadow.GetPassByIndex(i).Description.Signature; } if (InputSignaturePT == null) throw new System.Exception("input signature (SimpleMaterial, PT, AmbientShadow) == null"); LayoutPT = new InputLayout(device, InputSignaturePT, InputLayouts.VerticePT.InputElementsValue); for (var i = 0; i < TechStandard.Description.PassCount && InputSignaturePNTG == null; i++) { InputSignaturePNTG = TechStandard.GetPassByIndex(i).Description.Signature; } if (InputSignaturePNTG == null) throw new System.Exception("input signature (SimpleMaterial, PNTG, Standard) == null"); LayoutPNTG = new InputLayout(device, InputSignaturePNTG, InputLayouts.VerticePNTG.InputElementsValue); FxWorld = E.GetVariableByName("gWorld").AsMatrix(); FxWorldInvTranspose = E.GetVariableByName("gWorldInvTranspose").AsMatrix(); FxWorldViewProj = E.GetVariableByName("gWorldViewProj").AsMatrix(); FxDiffuseMap = E.GetVariableByName("gDiffuseMap").AsResource(); FxNormalMap = E.GetVariableByName("gNormalMap").AsResource(); FxMapsMap = E.GetVariableByName("gMapsMap").AsResource(); FxDetailsMap = E.GetVariableByName("gDetailsMap").AsResource(); FxDetailsNormalMap = E.GetVariableByName("gDetailsNormalMap").AsResource(); FxEyePosW = E.GetVariableByName("gEyePosW").AsVector(); FxMaterial = E.GetVariableByName("gMaterial"); FxReflectiveMaterial = E.GetVariableByName("gReflectiveMaterial"); FxMapsMaterial = E.GetVariableByName("gMapsMaterial"); FxAlphaMaterial = E.GetVariableByName("gAlphaMaterial"); FxNmUvMultMaterial = E.GetVariableByName("gNmUvMultMaterial"); }
// [STAThread] private static void Main() { var form = new RenderForm("SharpDX - MiniCube Direct3D11 Sample"); // SwapChain description var desc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = form.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; // Used for debugging dispose object references // Configuration.EnableObjectTracking = true; // Disable throws on shader compilation errors //Configuration.ThrowOnShaderCompileError = false; // Create Device and SwapChain Device device; SwapChain swapChain; Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, desc, out device, out swapChain); var context = device.ImmediateContext; // Ignore all windows events var factory = swapChain.GetParent <Factory>(); factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll); // Compile Vertex and Pixel shaders var vertexShaderByteCode = ShaderBytecode.CompileFromFile("MiniCube.fx", "VS", "vs_4_0"); var vertexShader = new VertexShader(device, vertexShaderByteCode); var pixelShaderByteCode = ShaderBytecode.CompileFromFile("MiniCube.fx", "PS", "ps_4_0"); var pixelShader = new PixelShader(device, pixelShaderByteCode); var signature = ShaderSignature.GetInputSignature(vertexShaderByteCode); // Layout from VertexShader input signature var layout = new InputLayout(device, signature, new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0) }); // Instantiate Vertex buiffer from vertex data var vertices = Buffer.Create(device, BindFlags.VertexBuffer, new[] { new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), // Front new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), // BACK new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), // Top new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), // Bottom new Vector4(1.0f, -1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), new Vector4(1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), new Vector4(1.0f, -1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), // Left new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), new Vector4(1.0f, -1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), // Right new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, -1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), }); // Create Constant Buffer var contantBuffer = new Buffer(device, Utilities.SizeOf <Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); // Prepare All the stages context.InputAssembler.InputLayout = layout; context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, Utilities.SizeOf <Vector4>() * 2, 0)); context.VertexShader.SetConstantBuffer(0, contantBuffer); context.VertexShader.Set(vertexShader); context.PixelShader.Set(pixelShader); // Prepare matrices var view = Matrix.LookAtLH(new Vector3(0, 0, -5), new Vector3(0, 0, 0), Vector3.UnitY); Matrix proj = Matrix.Identity; // Use clock var clock = new Stopwatch(); clock.Start(); // Declare texture for rendering bool userResized = true; Texture2D backBuffer = null; RenderTargetView renderView = null; Texture2D depthBuffer = null; DepthStencilView depthView = null; // Setup handler on resize form form.UserResized += (sender, args) => userResized = true; // Setup full screen mode change F5 (Full) F4 (Window) form.KeyUp += (sender, args) => { if (args.KeyCode == Keys.F5) { swapChain.SetFullscreenState(true, null); } else if (args.KeyCode == Keys.F4) { swapChain.SetFullscreenState(false, null); } else if (args.KeyCode == Keys.Escape) { form.Close(); } }; // Main loop RenderLoop.Run(form, () => { // If Form resized if (userResized) { // Dispose all previous allocated resources Utilities.Dispose(ref backBuffer); Utilities.Dispose(ref renderView); Utilities.Dispose(ref depthBuffer); Utilities.Dispose(ref depthView); // Resize the backbuffer swapChain.ResizeBuffers(desc.BufferCount, form.ClientSize.Width, form.ClientSize.Height, Format.Unknown, SwapChainFlags.None); // Get the backbuffer from the swapchain backBuffer = Texture2D.FromSwapChain <Texture2D>(swapChain, 0); // Renderview on the backbuffer renderView = new RenderTargetView(device, backBuffer); // Create the depth buffer depthBuffer = new Texture2D(device, new Texture2DDescription() { Format = Format.D32_Float_S8X24_UInt, ArraySize = 1, MipLevels = 1, Width = form.ClientSize.Width, Height = form.ClientSize.Height, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }); // Create the depth buffer view depthView = new DepthStencilView(device, depthBuffer); // Setup targets and viewport for rendering context.Rasterizer.SetViewport(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f)); context.OutputMerger.SetTargets(depthView, renderView); // Setup new projection matrix with correct aspect ratio proj = Matrix.PerspectiveFovLH((float)Math.PI / 4.0f, form.ClientSize.Width / (float)form.ClientSize.Height, 0.1f, 100.0f); // We are done resizing userResized = false; } var time = clock.ElapsedMilliseconds / 1000.0f; var viewProj = Matrix.Multiply(view, proj); // Clear views context.ClearDepthStencilView(depthView, DepthStencilClearFlags.Depth, 1.0f, 0); context.ClearRenderTargetView(renderView, Color.Black); // Update WorldViewProj Matrix var worldViewProj = Matrix.RotationX(time) * Matrix.RotationY(time * 2) * Matrix.RotationZ(time * .7f) * viewProj; worldViewProj.Transpose(); context.UpdateSubresource(ref worldViewProj, contantBuffer); // Draw the cube context.Draw(36, 0); // Present! swapChain.Present(0, PresentFlags.None); }); // Release all resources signature.Dispose(); vertexShaderByteCode.Dispose(); vertexShader.Dispose(); pixelShaderByteCode.Dispose(); pixelShader.Dispose(); vertices.Dispose(); layout.Dispose(); contantBuffer.Dispose(); depthBuffer.Dispose(); depthView.Dispose(); renderView.Dispose(); backBuffer.Dispose(); context.ClearState(); context.Flush(); device.Dispose(); context.Dispose(); swapChain.Dispose(); factory.Dispose(); }
public void Initialize(Device device) { _b = EffectUtils.Load("SpecialShadow"); E = new Effect(device, _b); TechHorizontalShadowBlur = E.GetTechniqueByName("HorizontalShadowBlur"); TechVerticalShadowBlur = E.GetTechniqueByName("VerticalShadowBlur"); TechAmbientShadow = E.GetTechniqueByName("AmbientShadow"); TechResult = E.GetTechniqueByName("Result"); for (var i = 0; i < TechHorizontalShadowBlur.Description.PassCount && InputSignaturePT == null; i++) { InputSignaturePT = TechHorizontalShadowBlur.GetPassByIndex(i).Description.Signature; } if (InputSignaturePT == null) throw new System.Exception("input signature (SpecialShadow, PT, HorizontalShadowBlur) == null"); LayoutPT = new InputLayout(device, InputSignaturePT, InputLayouts.VerticePT.InputElementsValue); FxShadowViewProj = E.GetVariableByName("gShadowViewProj").AsMatrix(); FxInputMap = E.GetVariableByName("gInputMap").AsResource(); FxDepthMap = E.GetVariableByName("gDepthMap").AsResource(); FxMultipler = E.GetVariableByName("gMultipler").AsScalar(); FxCount = E.GetVariableByName("gCount").AsScalar(); FxPadding = E.GetVariableByName("gPadding").AsScalar(); FxSize = E.GetVariableByName("gSize").AsVector(); FxShadowSize = E.GetVariableByName("gShadowSize").AsVector(); }
public TextureShader(Device device) { var vertexShaderByteCode = ShaderBytecode.CompileFromFile(VertexShaderFileName, "TextureVertexShader", "vs_4_0", ShaderFlags.None, EffectFlags.None); var pixelShaderByteCode = ShaderBytecode.CompileFromFile(PixelShaderFileName, "TexturePixelShader", "ps_4_0", ShaderFlags.None, EffectFlags.None); VertexShader = new VertexShader(device, vertexShaderByteCode); PixelShader = new PixelShader(device, pixelShaderByteCode); var inputElements = new InputElement[] { new InputElement { SemanticName = "POSITION", SemanticIndex = 0, Format = Format.R32G32B32_Float, Slot = 0, AlignedByteOffset = 0, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 }, new InputElement { SemanticName = "TEXCOORD", SemanticIndex = 0, Format = Format.R32G32_Float, Slot = 0, AlignedByteOffset = TextureShader.Vertex.AppendAlignedElement, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 } }; Layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements); vertexShaderByteCode.Dispose(); pixelShaderByteCode.Dispose(); // Setup the description of the dynamic matrix constant buffer that is in the vertex shader. var matrixBufferDesc = new BufferDescription { Usage = ResourceUsage.Dynamic, // Updated each frame SizeInBytes = Utilities.SizeOf <TextureShader.MatrixBuffer>(), // Contains three matrices BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; ConstantMatrixBuffer = new SharpDX.Direct3D11.Buffer(device, matrixBufferDesc); // Create a texture sampler state description. var samplerDesc = new SamplerStateDescription { Filter = Filter.MinMagMipLinear, AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, MipLodBias = 0, MaximumAnisotropy = 1, ComparisonFunction = Comparison.Always, BorderColor = new Color4(0, 0, 0, 0), MinimumLod = 0, MaximumLod = 0 }; // Create the texture sampler state. SamplerState = new SamplerState(device, samplerDesc); }
public void Initialize(Device device) { _b = EffectUtils.Load("SpecialTrackMap"); E = new Effect(device, _b); TechMain = E.GetTechniqueByName("Main"); TechPp = E.GetTechniqueByName("Pp"); TechFinal = E.GetTechniqueByName("Final"); TechFinalCheckers = E.GetTechniqueByName("FinalCheckers"); TechPpHorizontalBlur = E.GetTechniqueByName("PpHorizontalBlur"); TechPpVerticalBlur = E.GetTechniqueByName("PpVerticalBlur"); for (var i = 0; i < TechMain.Description.PassCount && InputSignaturePNTG == null; i++) { InputSignaturePNTG = TechMain.GetPassByIndex(i).Description.Signature; } if (InputSignaturePNTG == null) throw new System.Exception("input signature (SpecialTrackMap, PNTG, Main) == null"); LayoutPNTG = new InputLayout(device, InputSignaturePNTG, InputLayouts.VerticePNTG.InputElementsValue); for (var i = 0; i < TechPp.Description.PassCount && InputSignaturePT == null; i++) { InputSignaturePT = TechPp.GetPassByIndex(i).Description.Signature; } if (InputSignaturePT == null) throw new System.Exception("input signature (SpecialTrackMap, PT, Pp) == null"); LayoutPT = new InputLayout(device, InputSignaturePT, InputLayouts.VerticePT.InputElementsValue); FxWorldViewProj = E.GetVariableByName("gWorldViewProj").AsMatrix(); FxWorldInvTranspose = E.GetVariableByName("gWorldInvTranspose").AsMatrix(); FxInputMap = E.GetVariableByName("gInputMap").AsResource(); FxScreenSize = E.GetVariableByName("gScreenSize").AsVector(); }
protected override void Rendering(GraphicsDevice graphics, TProperties props) { var device = graphics.D3DDevice; var context = graphics.ImmediateContext; if (!pass.IsCompiled) { pass.Compile(graphics.Compilator); var vertexShaderByteCode = pass.VertexShader.ReadCompiledBytes(); var inputSignature = ShaderSignature.GetInputSignature(vertexShaderByteCode); inputLayout.Set(new InputLayout(device, inputSignature, layconst.ConstuctElements())); vertexShader.Set(new VertexShader(device, vertexShaderByteCode)); pixelShader.Set(new PixelShader(device, pass.PixelShader.ReadCompiledBytes())); } DepthStencilState depthStencilState = null; BlendState blendingState = null; try { depthStencilState = new DepthStencilState(graphics.D3DDevice, D3DDepthStencilDefinition.DepthDisabled.Description); blendingState = new BlendState(graphics.D3DDevice, D3DBlendStateDescriptions.BlendStateEnabled); foreach (var en in entities) { if (!en.Contains <BlackAndWhiteRenderComponent>()) { continue; } var geo = en.GetComponent <GeometryComponent>(); var renderable = en.GetComponent <RenderableComponent>(); var transform = en.GetComponent <TransformComponent>(); graphics.ClearAllShader(); graphics.SetVertexShader(vertexShader); graphics.SetPixelShader(pixelShader); SharpDX.Direct3D11.Buffer vertexBuffer = null; SharpDX.Direct3D11.Buffer indexBuffer = null; SharpDX.Direct3D11.Buffer transformWorldBuffer = null; try { var vertex = new Vertex[geo.Positions.Length]; for (var index = 0; index < vertex.Length; index++) { vertex[index] = new Vertex(geo.Positions[index]); } vertexBuffer = graphics.CreateBuffer(BindFlags.VertexBuffer, vertex); indexBuffer = graphics.CreateBuffer(BindFlags.IndexBuffer, geo.Indices.ToArray()); transformWorldBuffer = CreateTransformWorldBuffer(graphics, ref transform); context.VertexShader.SetConstantBuffer(GameStructBuffer.RegisterResourceSlot, props.Game); context.VertexShader.SetConstantBuffer(TransforStructBuffer.RegisterResourceSlot, transformWorldBuffer); context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, layconst.VertexSize, 0)); context.InputAssembler.SetIndexBuffer(indexBuffer, SharpDX.DXGI.Format.R32_UInt, 0); context.InputAssembler.InputLayout = inputLayout.Get(); context.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList; context.OutputMerger.SetDepthStencilState(depthStencilState); context.OutputMerger.SetBlendState(blendingState, new SharpDX.Mathematics.Interop.RawColor4(0, 0, 0, 0), -1); using (var rasterizerState = graphics.CreateRasterizerState(rasterizerStateDescription)) { context.Rasterizer.State = rasterizerState; context.DrawIndexed(geo.Indices.Length, 0, 0); } } finally { vertexBuffer?.Dispose(); indexBuffer?.Dispose(); transformWorldBuffer?.Dispose(); } } } finally { depthStencilState?.Dispose(); blendingState?.Dispose(); blendingState = null; depthStencilState = null; } }
public void Initialize(Device device) { _b = EffectUtils.Load("SpecialUv"); E = new Effect(device, _b); TechMain = E.GetTechniqueByName("Main"); for (var i = 0; i < TechMain.Description.PassCount && InputSignaturePNTG == null; i++) { InputSignaturePNTG = TechMain.GetPassByIndex(i).Description.Signature; } if (InputSignaturePNTG == null) throw new System.Exception("input signature (SpecialUv, PNTG, Main) == null"); LayoutPNTG = new InputLayout(device, InputSignaturePNTG, InputLayouts.VerticePNTG.InputElementsValue); FxOffset = E.GetVariableByName("gOffset").AsVector(); }
public void Init(Form form) { ViewportSize = new Size2F(form.Width, form.Height); hViewportSize = new Size2F(form.Width / 2f, form.Height / 2f); ModeDescription backBufferDesc = new ModeDescription(form.Width, form.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm); SwapChainDescription swapChainDesc = new SwapChainDescription() { ModeDescription = backBufferDesc, SampleDescription = new SampleDescription(1, 0), Usage = Usage.RenderTargetOutput, BufferCount = 1, OutputHandle = form.Handle, IsWindowed = true, }; D3D11.Device.CreateWithSwapChain(DriverType.Hardware, D3D11.DeviceCreationFlags.None, swapChainDesc, out d3dDevice, out swapChain); d3dDeviceContext = d3dDevice.ImmediateContext; d3dDeviceContext.Rasterizer.SetViewport(0, 0, form.Width, form.Height); using (D3D11.Texture2D backBuffer = swapChain.GetBackBuffer <D3D11.Texture2D>(0)) { renderTargetView = new D3D11.RenderTargetView(d3dDevice, backBuffer); } D3D11.BlendStateDescription blendStateDesc = D3D11.BlendStateDescription.Default(); blendStateDesc.AlphaToCoverageEnable = false; blendStateDesc.RenderTarget[0].IsBlendEnabled = true; blendStateDesc.RenderTarget[0].SourceBlend = D3D11.BlendOption.SourceAlpha; blendStateDesc.RenderTarget[0].DestinationBlend = D3D11.BlendOption.One; // blendStateDesc.RenderTarget[0].BlendOperation = D3D11.BlendOperation.Maximum; blendStateDesc.RenderTarget[0].SourceAlphaBlend = D3D11.BlendOption.SourceAlpha; //Zero blendStateDesc.RenderTarget[0].DestinationAlphaBlend = D3D11.BlendOption.DestinationAlpha; blendStateDesc.RenderTarget[0].AlphaBlendOperation = D3D11.BlendOperation.Maximum; blendStateDesc.RenderTarget[0].RenderTargetWriteMask = D3D11.ColorWriteMaskFlags.All; blendState = new D3D11.BlendState(d3dDevice, blendStateDesc); GeometryBuffer = new GeometryBuffer(this); Fonts = new FontCache(this); var layout = new D3D11.InputElement[] { new D3D11.InputElement("POSITION", 0, Format.R32G32_Float, 0, 0), new D3D11.InputElement("COLOR", 0, Format.R32G32B32A32_Float, 8, 0), new D3D11.InputElement("TEXCOORDS", 0, Format.R32G32_Float, 24, 0), }; var vertexShaderOutput = ShaderBytecode.Compile(vertexShaderCode, "main", "vs_4_0", ShaderFlags.Debug); var pixelShaderOutput = ShaderBytecode.Compile(pixelShaderCode, "main", "ps_4_0", ShaderFlags.Debug); vertexShader = new D3D11.VertexShader(Device, vertexShaderOutput); pixelShader = new D3D11.PixelShader(Device, pixelShaderOutput); var shaderSignature = ShaderSignature.GetInputSignature(vertexShaderOutput); inputLayout = new D3D11.InputLayout(Device, shaderSignature, layout); IntPtr data = System.Runtime.InteropServices.Marshal.AllocHGlobal(4 * 4 * 4); var white = BitConverter.GetBytes(1f); for (int i = 0; i < 4 * 4; i++) { for (int j = 0; j < white.Length; j++) { System.Runtime.InteropServices.Marshal.WriteByte(data, i * sizeof(float) + j, white[j]); } } White = new D3D11.Texture2D(Device, new D3D11.Texture2DDescription { Width = 4, Height = 4, ArraySize = 1, BindFlags = D3D11.BindFlags.ShaderResource, Usage = D3D11.ResourceUsage.Dynamic, CpuAccessFlags = D3D11.CpuAccessFlags.Write, Format = Format.R32G32B32A32_Float, MipLevels = 1, OptionFlags = D3D11.ResourceOptionFlags.None, SampleDescription = new DXGI.SampleDescription(1, 0), }, new DataBox[] { new DataBox(data, 4 * 2, 4) }); System.Runtime.InteropServices.Marshal.FreeHGlobal(data); WhiteView = new D3D11.ShaderResourceView(Device, White); samplerState = new D3D11.SamplerState(Device, new D3D11.SamplerStateDescription() { Filter = D3D11.Filter.MinMagMipLinear, AddressU = D3D11.TextureAddressMode.Clamp, AddressV = D3D11.TextureAddressMode.Clamp, AddressW = D3D11.TextureAddressMode.Clamp, BorderColor = new RawColor4(1f, 0f, 1f, 1f), ComparisonFunction = D3D11.Comparison.Never, MaximumAnisotropy = 16, MipLodBias = 0, MinimumLod = 0, MaximumLod = 16 }); transfBuffer = new SharpDX.Direct3D11.Buffer(Device, new SharpDX.Direct3D11.BufferDescription(sizeof(float) * 4, SharpDX.Direct3D11.ResourceUsage.Dynamic, SharpDX.Direct3D11.BindFlags.ConstantBuffer, SharpDX.Direct3D11.CpuAccessFlags.Write, SharpDX.Direct3D11.ResourceOptionFlags.None, sizeof(float))); DataStream stream; DeviceContext.MapSubresource(transfBuffer, D3D11.MapMode.WriteDiscard, D3D11.MapFlags.None, out stream); stream.Write(hViewportSize.Width); stream.Write(hViewportSize.Height); DeviceContext.UnmapSubresource(transfBuffer, 0); DeviceContext.VertexShader.SetShader(vertexShader, null, 0); DeviceContext.VertexShader.SetConstantBuffer(0, transfBuffer); DeviceContext.PixelShader.SetShader(pixelShader, null, 0); DeviceContext.PixelShader.SetSampler(0, samplerState); DeviceContext.InputAssembler.InputLayout = inputLayout; DeviceContext.OutputMerger.BlendState = blendState; }
public EarthFromOBJ(DeviceContext dx11Context) { _dx11Context = dx11Context; World = Matrix.Translation(0, 100, -5000); _light.Color = Color4.White; const string obj = "3DModelsFiles\\Earth\\earth.obj"; const string mtl = "3DModelsFiles\\Earth\\earth.mtl"; const string jpg = "3DModelsFiles\\Earth\\earthmap.jpg"; const string shadersFile = "Shaders\\EarthT.hlsl"; Tuple <List <Face>, List <uint> > tuple = GetFaces(obj); _facesCount = tuple.Item2.Count; _vertexBuffer = Buffer.Create(dx11Context.Device, BindFlags.VertexBuffer, tuple.Item1.ToArray()); _indexBuffer = Buffer.Create(dx11Context.Device, BindFlags.IndexBuffer, tuple.Item2.ToArray()); _vertexBinding = new VertexBufferBinding(_vertexBuffer, Utilities.SizeOf <Face>(), 0); MtlMaterial material = GetMaterial(mtl); _materialsBuffer = Buffer.Create(_dx11Context.Device, BindFlags.ConstantBuffer, ref material); _constantBuffer = new Buffer(_dx11Context.Device, Utilities.SizeOf <Matrices>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); _lightBuffer = new Buffer(_dx11Context.Device, Utilities.SizeOf <Light>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); _textureResourse = _dx11Context.LoadTextureFromFile(jpg); _textureResourse1 = _dx11Context.LoadTextureFromFile("3DModelsFiles\\Earth\\map.jpg"); _textureResourse2 = _dx11Context.LoadTextureFromFile("3DModelsFiles\\Earth\\map1.jpg"); SamplerStateDescription description = SamplerStateDescription.Default(); description.Filter = Filter.MinMagMipLinear; description.AddressU = TextureAddressMode.Wrap; description.AddressV = TextureAddressMode.Wrap; description.AddressW = TextureAddressMode.Wrap; _samplerState = new SamplerState(_dx11Context.Device, description); //Загружаем шейдеры из файлов InputElement[] inputElements = new InputElement[] { new InputElement("SV_Position", 0, Format.R32G32B32_Float, 0, 0), new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0), new InputElement("TEXCOORD", 0, Format.R32G32B32_Float, 24, 0) }; ShaderFlags shaderFlags = ShaderFlags.None; #if DEBUG shaderFlags = ShaderFlags.Debug; #endif using (var vertexShaderByteCode = ShaderBytecode.CompileFromFile(shadersFile, "VS", "vs_5_0", shaderFlags)) { //Синатура храянящая сведения о том какие входные переменные есть у шейдера _inputSignature = ShaderSignature.GetInputSignature(vertexShaderByteCode); _vertexShader = new VertexShader(_dx11Context.Device, vertexShaderByteCode); } using (var pixelShaderByteCode = ShaderBytecode.CompileFromFile(shadersFile, "PS", "ps_5_0", shaderFlags)) { _pixelShader = new PixelShader(_dx11Context.Device, pixelShaderByteCode); } using (var pixelShaderByteCode = ShaderBytecode.CompileFromFile(shadersFile, "HS", "hs_5_0", shaderFlags)) { _hShader = new HullShader(_dx11Context.Device, pixelShaderByteCode); } using (var pixelShaderByteCode = ShaderBytecode.CompileFromFile(shadersFile, "DS", "ds_5_0", shaderFlags)) { _dShader = new DomainShader(_dx11Context.Device, pixelShaderByteCode); } _inputLayout = new InputLayout(_dx11Context.Device, _inputSignature, inputElements); RasterizerStateDescription rasterizerStateDescription = RasterizerStateDescription.Default(); rasterizerStateDescription.CullMode = CullMode.None; rasterizerStateDescription.FillMode = FillMode.Solid; DepthStencilStateDescription DStateDescripshion = DepthStencilStateDescription.Default(); DStateDescripshion.IsDepthEnabled = true; _DState = new DepthStencilState(_dx11Context.Device, DStateDescripshion); _rasterizerState = new RasterizerState(_dx11Context.Device, rasterizerStateDescription); _light.Direction = new Vector3(1f, -1f, 1f); }
private bool InitializeShader(Device device, IntPtr windowsHandler, string vsFileName, string psFileName) { try { // Setup full pathes vsFileName = DSystemConfiguration.ShaderFilePath + vsFileName; psFileName = DSystemConfiguration.ShaderFilePath + psFileName; // Compile the Vertex Shader & Pixel Shader code. ShaderBytecode vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFileName, "LightVertexShader", "vs_4_0", ShaderFlags.None, EffectFlags.None); ShaderBytecode pixelShaderByteCode = ShaderBytecode.CompileFromFile(psFileName, "LightPixelShader", "ps_4_0", ShaderFlags.None, EffectFlags.None); // Create the Vertex & Pixel Shaders from the buffer. VertexShader = new VertexShader(device, vertexShaderByteCode); PixelShader = new PixelShader(device, pixelShaderByteCode); // Now setup the layout of the data that goes into the shader. // This setup needs to match the VertexType structure in the Model and in the shader. InputElement[] inputElements = new InputElement[] { new InputElement() { SemanticName = "POSITION", SemanticIndex = 0, Format = SharpDX.DXGI.Format.R32G32B32_Float, Slot = 0, AlignedByteOffset = 0, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 }, new InputElement() { SemanticName = "TEXCOORD", SemanticIndex = 0, Format = SharpDX.DXGI.Format.R32G32_Float, Slot = 0, AlignedByteOffset = InputElement.AppendAligned, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 }, new InputElement() { SemanticName = "NORMAL", SemanticIndex = 0, Format = SharpDX.DXGI.Format.R32G32B32_Float, Slot = 0, AlignedByteOffset = InputElement.AppendAligned, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 } }; // Create the vertex input the layout. Kin dof like a Vertex Declaration. Layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements); // Release the vertex and pixel shader buffers, since they are no longer needed. vertexShaderByteCode.Dispose(); pixelShaderByteCode.Dispose(); // Create a texture sampler state description. SamplerStateDescription samplerDesc = new SamplerStateDescription() { Filter = Filter.MinMagMipLinear, AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, MipLodBias = 0, MaximumAnisotropy = 1, ComparisonFunction = Comparison.Always, BorderColor = new Color4(0, 0, 0, 0), // Black Border. MinimumLod = 0, MaximumLod = float.MaxValue }; // Create the texture sampler state. SamplerState = new SamplerState(device, samplerDesc); // Setup the description of the dynamic matrix constant Matrix buffer that is in the vertex shader. BufferDescription matrixBufferDescription = new BufferDescription() { Usage = ResourceUsage.Dynamic, // ResourceUsage.Default SizeInBytes = Utilities.SizeOf <DMatrixBuffer>(), BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, // CpuAccessFlags.None OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class. ConstantMatrixBuffer = new SharpDX.Direct3D11.Buffer(device, matrixBufferDescription); // Setup the description of the light dynamic constant bufffer that is in the pixel shader. // Note that ByteWidth alwalys needs to be a multiple of the 16 if using D3D11_BIND_CONSTANT_BUFFER or CreateBuffer will fail. BufferDescription lightBufferDesc = new BufferDescription() { Usage = ResourceUsage.Dynamic, SizeInBytes = Utilities.SizeOf <DLightBuffer>(), // Must be divisable by 16 bytes, so this is equated to 32. BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class. ConstantLightBuffer = new SharpDX.Direct3D11.Buffer(device, lightBufferDesc); return(true); } catch (Exception ex) { MessageBox.Show("Error initializing shader. Error is " + ex.Message); return(false); } }
static void RunDirectX(MainForm mainWnd, ref D3DDevice device, SwapChain swapChain, ref World blockWorld) { // Setup graphics pipeline // 0. Prepare buffers // Create vertex buffer var vertexData = blockWorld.Blocks; var vertexDataSize = Utilities.SizeOf(vertexData); var vertexBufferDesc = new BufferDescription() { /* Usage */ Usage = ResourceUsage.Default, /* ByteWidth */ SizeInBytes = vertexDataSize, /* BindFlags */ BindFlags = BindFlags.VertexBuffer, /* CPUAccessFlags */ CpuAccessFlags = CpuAccessFlags.None, /* MiscFlags */ OptionFlags = ResourceOptionFlags.None, /* StructureByteStride */ StructureByteStride = 0, }; var vertexBuffer = D3DBuffer.Create(device, vertexData, vertexBufferDesc); // Create constant buffer var constantData = new[] { Matrix.Identity }; var constantDataSize = constantData.Length * Utilities.SizeOf <Matrix>(); var constantBufferDesc = new BufferDescription() { /* Usage */ Usage = ResourceUsage.Default, /* ByteWidth */ SizeInBytes = constantDataSize, /* BindFlags */ BindFlags = BindFlags.ConstantBuffer, /* CPUAccessFlags */ CpuAccessFlags = CpuAccessFlags.None, /* MiscFlags */ OptionFlags = ResourceOptionFlags.None, /* StructureByteStride */ StructureByteStride = 0, }; var constantBuffer = D3DBuffer.Create(device, constantData, constantBufferDesc); var context = device.ImmediateContext; // 1. IA, VS, PS stage: Prepare shaders, bind buffers var vertexSize = Utilities.SizeOf <Vector4>() * 2; var vertexBuffers = new[] { vertexBuffer }; var vertexBufferStrides = new[] { vertexSize }; var vertexBufferOffsets = new[] { 0 }; var vertexShaderByteCode = ShaderBytecode.CompileFromFile("Shader.fx", "VS", "vs_4_0"); var vertexShader = new VertexShader(device, vertexShaderByteCode); var pixelShaderByteCode = ShaderBytecode.CompileFromFile("Shader.fx", "PS", "ps_4_0"); var pixelShader = new PixelShader(device, pixelShaderByteCode); var signature = ShaderSignature.GetInputSignature(vertexShaderByteCode); var inputLayout = new InputLayout(device, signature, new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0) }); context.InputAssembler.InputLayout = inputLayout; context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; context.InputAssembler.SetVertexBuffers(0, vertexBuffers, vertexBufferStrides, vertexBufferOffsets); context.VertexShader.SetConstantBuffer(0, constantBuffer); context.VertexShader.Set(vertexShader); context.PixelShader.Set(pixelShader); // 2. Rasterizer, OM stage: viewport, render targets & depth-stencil test. var viewport = new Viewport(0, 0, mainWnd.ClientSize.Width, mainWnd.ClientSize.Height, 0.0f, 1.0f); var backBuffer = Texture2D.FromSwapChain <Texture2D>(swapChain, 0); var depthBuffer = new Texture2D(device, new Texture2DDescription() { Format = Format.D32_Float_S8X24_UInt, ArraySize = 1, MipLevels = 1, Width = mainWnd.ClientSize.Width, Height = mainWnd.ClientSize.Height, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }); var renderView = new RenderTargetView(device, backBuffer); var depthView = new DepthStencilView(device, depthBuffer); context.Rasterizer.SetViewport(viewport); context.OutputMerger.SetTargets(depthView, renderView); // Setup transformations & control. var eye = new Vector3(0, 0, -10); var rotateWorld = 0.0f; var keyMap = new Dictionary <char, bool>(); keyMap['w'] = false; keyMap['s'] = false; keyMap['a'] = false; keyMap['d'] = false; keyMap['q'] = false; keyMap['e'] = false; var mouseBaseX = 0; var mouseBaseY = 0; var mousePosX = 0.0f; var mousePosY = 0.0f; var jump = 0.0f; var jumpVec = 0.0f; mainWnd.MouseMove += (sender, e) => { mousePosX = ((e.X + mainWnd.ClientSize.Width - mouseBaseX) % mainWnd.ClientSize.Width) * 1.0f / mainWnd.ClientSize.Width; mousePosY = ((e.Y + mainWnd.ClientSize.Height - mouseBaseY) % mainWnd.ClientSize.Height) * 1.0f / mainWnd.ClientSize.Height; mainWnd.debugText.Text = "X: " + e.X + "\tY: " + e.Y + "\r\nPX: " + mousePosX + "\tPY: " + mousePosY + "\r\nJump: " + jump + "\tVec: " + jumpVec; }; mainWnd.KeyDown += (sender, args) => { if (args.KeyCode == Keys.W) { keyMap['w'] = true; } else if (args.KeyCode == Keys.S) { keyMap['s'] = true; } else if (args.KeyCode == Keys.A) { keyMap['a'] = true; } else if (args.KeyCode == Keys.D) { keyMap['d'] = true; } else if (args.KeyCode == Keys.Q) { keyMap['q'] = true; } else if (args.KeyCode == Keys.E) { keyMap['e'] = true; } else if (args.KeyCode == Keys.Space) { jumpVec = 10.0f; } }; mainWnd.KeyUp += (sender, args) => { if (args.KeyCode == Keys.W) { keyMap['w'] = false; } else if (args.KeyCode == Keys.S) { keyMap['s'] = false; } else if (args.KeyCode == Keys.A) { keyMap['a'] = false; } else if (args.KeyCode == Keys.D) { keyMap['d'] = false; } else if (args.KeyCode == Keys.Q) { keyMap['q'] = false; } else if (args.KeyCode == Keys.E) { keyMap['e'] = false; } else if (args.KeyCode == Keys.Escape) { mainWnd.Close(); } }; // Render. var vertexCount = vertexBuffer.Description.SizeInBytes / vertexSize; RenderLoop.Run(mainWnd, () => { if (keyMap['w']) { eye.X += 1.5f / 60.0f; } if (keyMap['s']) { eye.X -= 1.5f / 60.0f; } if (keyMap['a']) { eye.Y += 1.5f / 60.0f; } if (keyMap['d']) { eye.Y -= 1.5f / 60.0f; } if (keyMap['q']) { rotateWorld += 0.1f / 60.0f; } if (keyMap['e']) { rotateWorld -= 0.1f / 60.0f; } // Clear views. context.ClearDepthStencilView(depthView, DepthStencilClearFlags.Depth, 1.0f, 0); context.ClearRenderTargetView(renderView, Color.Black); // Update world data. if (jump > 0.0f || (jump == 0.0f && jumpVec != 0.0f)) { jump += jumpVec / 60.0f / 3.0f; jumpVec += -9.8f / 60.0f / 3.0f; } else { jump = jumpVec = 0.0f; } var ray = new Vector3(eye.X, eye.Y + 1.0f, eye.Z - jump) - new Vector3(eye.X, eye.Y, eye.Z - jump); var proj = Matrix.PerspectiveFovLH((float)Math.PI / 4.0f, mainWnd.ClientSize.Width / (float)mainWnd.ClientSize.Height, 0.1f, 100.0f); var view = Matrix.LookAtLH(new Vector3(eye.X, eye.Y, eye.Z - jump), new Vector3(eye.X, eye.Y + 1.0f, eye.Z - jump), new Vector3(0, 0, 1)); var world = Matrix.RotationZ(rotateWorld); var matrix = world * (view * Matrix.RotationY(mousePosX * 2.0f * (float)Math.PI) * Matrix.RotationX(-mousePosY * 2.0f * (float)Math.PI)) * proj; matrix.Transpose(); context.UpdateSubresource(ref matrix, constantBuffer); // Draw. context.Draw(vertexCount, 0); swapChain.Present(0, PresentFlags.None); }); }
public static void DrawMesh(Direct3DControl control) { var desc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(control.ClientSize.Width, control.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = control.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; Device device; SwapChain swapChain; Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, desc, out device, out swapChain); var context = device.ImmediateContext; var vertices = Buffer.Create(device, BindFlags.VertexBuffer, new[] { new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), // Front new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), // BACK new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), // Top new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), // Bottom new Vector4(1.0f, -1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), new Vector4(1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), new Vector4(1.0f, -1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), // Left new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), new Vector4(1.0f, -1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), // Right new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, -1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), }); var vertexShaderByteCode = ShaderBytecode.CompileFromFile("MiniCube.fx", "VS", "vs_4_0"); var vertexShader = new VertexShader(device, vertexShaderByteCode); var pixelShaderByteCode = ShaderBytecode.CompileFromFile("MiniCube.fx", "PS", "ps_4_0"); var pixelShader = new PixelShader(device, pixelShaderByteCode); var signature = ShaderSignature.GetInputSignature(vertexShaderByteCode); // Layout from VertexShader input signature var layout = new InputLayout(device, signature, new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0) }); var contantBuffer = new Buffer(device, Utilities.SizeOf <Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); context.InputAssembler.InputLayout = layout; context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleStrip; context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, Utilities.SizeOf <Vector4>() * 2, 0)); context.VertexShader.SetConstantBuffer(0, contantBuffer); context.VertexShader.Set(vertexShader); context.PixelShader.Set(pixelShader); //var view = Matrix.LookAtLH(new Vector3(0, 0, -5), new Vector3(0, 0, 0), Vector3.UnitY); //Matrix proj = Matrix.Identity; swapChain.ResizeBuffers(1, control.ClientSize.Width, control.ClientSize.Height, Format.Unknown, SwapChainFlags.None); // Get the backbuffer from the swapchain var backBuffer = Texture2D.FromSwapChain <Texture2D>(swapChain, 0); // Renderview on the backbuffer var renderView = new RenderTargetView(device, backBuffer); // Create the depth buffer var depthBuffer = new Texture2D(device, new Texture2DDescription() { Format = Format.D32_Float_S8X24_UInt, ArraySize = 1, MipLevels = 1, Width = control.ClientSize.Width, Height = control.ClientSize.Height, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }); // Create the depth buffer view var depthView = new DepthStencilView(device, depthBuffer); context.Rasterizer.SetViewport(new Viewport(0, 0, control.ClientSize.Width, control.ClientSize.Height, 0.0f, 1.0f)); context.OutputMerger.SetTargets(depthView, renderView); //proj = Matrix.PerspectiveFovLH((float)Math.PI / 4.0f, 1, 0.1f, 100.0f); context.OutputMerger.SetTargets(depthView, renderView); //var viewProj = Matrix.Multiply(view, proj); context.ClearDepthStencilView(depthView, DepthStencilClearFlags.Depth, 1.0f, 0); context.ClearRenderTargetView(renderView, Color.White); //var worldViewProj = Matrix.RotationX(10) * Matrix.RotationY(10 * 2) * Matrix.RotationZ(10 * .7f) * viewProj; //worldViewProj.Transpose(); //context.UpdateSubresource(ref worldViewProj, contantBuffer); context.Draw(36, 0); // Present! swapChain.Present(0, PresentFlags.None); }
public SoComponent(Device device, VertexPositionNormalTexture[] vertices, string geometryShaderName, string pixelShaderName) { this.vertices = vertices; bufferForSo = Buffer.Create(device, BindFlags.VertexBuffer, this.vertices); var location = Assembly.GetExecutingAssembly().Location; var path = Path.GetDirectoryName(location) + "\\Shaders\\" + pixelShaderName; using (var vertexShaderByteCode = ShaderBytecode.CompileFromFile(path, "VS", "vs_5_0", ShaderFlags.PackMatrixRowMajor)) { colorInputSignature = ShaderSignature.GetInputSignature(vertexShaderByteCode); colorVertexShader = new VertexShader(device, vertexShaderByteCode); } using (var pixelShaderByteCode = ShaderBytecode.CompileFromFile(path, "PS", "ps_5_0", ShaderFlags.PackMatrixRowMajor)) { colorPixelShader = new PixelShader(device, pixelShaderByteCode); } path = Path.GetDirectoryName(location) + "\\Shaders\\" + geometryShaderName; using (var geometryShaderByteCode = ShaderBytecode.CompileFromFile(path, "GS", "gs_5_0", ShaderFlags.PackMatrixRowMajor)) { StreamOutputElement[] streamOutput = { new StreamOutputElement { SemanticName = "POSITION", SemanticIndex = 0, StartComponent = 0, ComponentCount = 4, OutputSlot = 0 }, new StreamOutputElement { SemanticName = "COLOR", SemanticIndex = 0, StartComponent = 0, ComponentCount = 4, OutputSlot = 0 } }; int[] bufferStride = { Utilities.SizeOf <Vector4>() + Utilities.SizeOf <Color4>() }; geometryShader = new GeometryShader(device, geometryShaderByteCode, streamOutput, bufferStride, -1); } using (var vertexShaderByteCode = ShaderBytecode.CompileFromFile(path, "VS", "vs_5_0", ShaderFlags.PackMatrixRowMajor)) { soInputSignature = ShaderSignature.GetInputSignature(vertexShaderByteCode); vertexShaderSo = new VertexShader(device, vertexShaderByteCode); } colorInputLayout = new InputLayout(device, colorInputSignature, colorInputElements); soInputLayout = new InputLayout(device, soInputSignature, soInputElement); constantBufferColor = new Buffer(device, Utilities.SizeOf <Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); soBuffer = new Buffer(device, new BufferDescription { BindFlags = BindFlags.VertexBuffer | BindFlags.StreamOutput, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, Usage = ResourceUsage.Default, StructureByteStride = Utilities.SizeOf <VertexPositionColor>(), SizeInBytes = Utilities.SizeOf <VertexPositionColor>() * Utilities.SizeOf(vertices) }); }
protected override void Rendering(GraphicsDevice graphics, TProperties props) { var device = graphics.D3DDevice; var context = graphics.ImmediateContext; if (!pass.IsCompiled) { pass.Compile(graphics.Compilator); var vertexShaderByteCode = pass.VertexShader.ReadCompiledBytes(); var inputSignature = ShaderSignature.GetInputSignature(vertexShaderByteCode); inputLayout.Set(new InputLayout(device, inputSignature, layconst.ConstuctElements())); vertexShader.Set(new VertexShader(device, vertexShaderByteCode)); pixelShader.Set(new PixelShader(device, pass.PixelShader.ReadCompiledBytes())); } if (!quardPass.IsCompiled) { quardPass.Compile(graphics.Compilator); //var inputSignature = ShaderSignature.GetInputSignature(quardPass.VertexShader.ReadCompiledBytes()); //inputLayoutQuard = new InputLayout(device, inputSignature, null); vertexShaderQuard.Set(new VertexShader(device, quardPass.VertexShader.ReadCompiledBytes())); pixelShaderQuard.Set(new PixelShader(device, quardPass.PixelShader.ReadCompiledBytes())); } //clear shaders off prev. technique graphics.ClearAllShader(); if (!colorTargetTex2D.HasValue) { colorDesc.BindFlags = alphaDesc.BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource; colorDesc.SampleDescription = alphaDesc.SampleDescription = new SampleDescription(1, 0); colorDesc.Width = alphaDesc.Width = (int)graphics.Size.Width; colorDesc.Height = alphaDesc.Height = (int)graphics.Size.Height; colorTargetTex2D.Set(new Texture2D(device, colorDesc)); alphaTargetTex2D.Set(new Texture2D(device, alphaDesc)); { colorTargetNoMSAATexture2D.Set(new Texture2D(device, colorDesc)); alphaTargetNoMSAATexture2D.Set(new Texture2D(device, alphaDesc)); colorTargetNoMSAA.Set(new ShaderResourceView(device, colorTargetNoMSAATexture2D.Get())); alphaTargetNoMSAA.Set(new ShaderResourceView(device, alphaTargetNoMSAATexture2D.Get())); } targetSampler.Set(new SamplerState(device, LinearSamplerWrapAni1)); colorTargetView.Set(new RenderTargetView(device, colorTargetTex2D.Get())); alphaTargetView.Set(new RenderTargetView(device, alphaTargetTex2D.Get())); var d = colorDesc; d.BindFlags = BindFlags.RenderTarget; quardTargetView.Set(new RenderTargetView(device, new Texture2D(device, d))); } //RenderingAlfa(entities, graphics, props); RenderingQuard(graphics, props); }
private static void Main() { RenderForm form = new RenderForm("OculusWrap SharpDX demo"); IntPtr sessionPtr; InputLayout inputLayout = null; Buffer contantBuffer = null; Buffer vertexBuffer = null; ShaderSignature shaderSignature = null; PixelShader pixelShader = null; ShaderBytecode pixelShaderByteCode = null; VertexShader vertexShader = null; ShaderBytecode vertexShaderByteCode = null; Texture2D mirrorTextureD3D = null; EyeTexture[] eyeTextures = null; DeviceContext immediateContext = null; DepthStencilState depthStencilState = null; DepthStencilView depthStencilView = null; Texture2D depthBuffer = null; RenderTargetView backBufferRenderTargetView = null; Texture2D backBuffer = null; SharpDX.DXGI.SwapChain swapChain = null; Factory factory = null; MirrorTexture mirrorTexture = null; Guid textureInterfaceId = new Guid("6f15aaf2-d208-4e89-9ab4-489535d34f9c"); // Interface ID of the Direct3D Texture2D interface. Result result; OvrWrap OVR = OvrWrap.Create(); // Define initialization parameters with debug flag. InitParams initializationParameters = new InitParams(); initializationParameters.Flags = InitFlags.Debug | InitFlags.RequestVersion; initializationParameters.RequestedMinorVersion = 17; // Initialize the Oculus runtime. string errorReason = null; try { result = OVR.Initialize(initializationParameters); if (result < Result.Success) { errorReason = result.ToString(); } } catch (Exception ex) { errorReason = ex.Message; } if (errorReason != null) { MessageBox.Show("Failed to initialize the Oculus runtime library:\r\n" + errorReason, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } // Use the head mounted display. sessionPtr = IntPtr.Zero; var graphicsLuid = new GraphicsLuid(); result = OVR.Create(ref sessionPtr, ref graphicsLuid); if (result < Result.Success) { MessageBox.Show("The HMD is not enabled: " + result.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } var hmdDesc = OVR.GetHmdDesc(sessionPtr); try { // Create a set of layers to submit. eyeTextures = new EyeTexture[2]; // Create DirectX drawing device. SharpDX.Direct3D11.Device device = new Device(SharpDX.Direct3D.DriverType.Hardware, DeviceCreationFlags.Debug); // Create DirectX Graphics Interface factory, used to create the swap chain. factory = new SharpDX.DXGI.Factory4(); immediateContext = device.ImmediateContext; // Define the properties of the swap chain. SwapChainDescription swapChainDescription = new SwapChainDescription(); swapChainDescription.BufferCount = 1; swapChainDescription.IsWindowed = true; swapChainDescription.OutputHandle = form.Handle; swapChainDescription.SampleDescription = new SampleDescription(1, 0); swapChainDescription.Usage = Usage.RenderTargetOutput | Usage.ShaderInput; swapChainDescription.SwapEffect = SwapEffect.Sequential; swapChainDescription.Flags = SwapChainFlags.AllowModeSwitch; swapChainDescription.ModeDescription.Width = form.Width; swapChainDescription.ModeDescription.Height = form.Height; swapChainDescription.ModeDescription.Format = Format.R8G8B8A8_UNorm; swapChainDescription.ModeDescription.RefreshRate.Numerator = 0; swapChainDescription.ModeDescription.RefreshRate.Denominator = 1; // Create the swap chain. swapChain = new SwapChain(factory, device, swapChainDescription); // Retrieve the back buffer of the swap chain. backBuffer = swapChain.GetBackBuffer <Texture2D>(0); backBufferRenderTargetView = new RenderTargetView(device, backBuffer); // Create a depth buffer, using the same width and height as the back buffer. Texture2DDescription depthBufferDescription = new Texture2DDescription(); depthBufferDescription.Format = Format.D32_Float; depthBufferDescription.ArraySize = 1; depthBufferDescription.MipLevels = 1; depthBufferDescription.Width = form.Width; depthBufferDescription.Height = form.Height; depthBufferDescription.SampleDescription = new SampleDescription(1, 0); depthBufferDescription.Usage = ResourceUsage.Default; depthBufferDescription.BindFlags = BindFlags.DepthStencil; depthBufferDescription.CpuAccessFlags = CpuAccessFlags.None; depthBufferDescription.OptionFlags = ResourceOptionFlags.None; // Define how the depth buffer will be used to filter out objects, based on their distance from the viewer. DepthStencilStateDescription depthStencilStateDescription = new DepthStencilStateDescription(); depthStencilStateDescription.IsDepthEnabled = true; depthStencilStateDescription.DepthComparison = Comparison.Less; depthStencilStateDescription.DepthWriteMask = DepthWriteMask.Zero; // Create the depth buffer. depthBuffer = new Texture2D(device, depthBufferDescription); depthStencilView = new DepthStencilView(device, depthBuffer); depthStencilState = new DepthStencilState(device, depthStencilStateDescription); var viewport = new Viewport(0, 0, hmdDesc.Resolution.Width, hmdDesc.Resolution.Height, 0.0f, 1.0f); immediateContext.OutputMerger.SetDepthStencilState(depthStencilState); immediateContext.OutputMerger.SetRenderTargets(depthStencilView, backBufferRenderTargetView); immediateContext.Rasterizer.SetViewport(viewport); // Retrieve the DXGI device, in order to set the maximum frame latency. using (SharpDX.DXGI.Device1 dxgiDevice = device.QueryInterface <SharpDX.DXGI.Device1>()) { dxgiDevice.MaximumFrameLatency = 1; } var layerEyeFov = new LayerEyeFov(); layerEyeFov.Header.Type = LayerType.EyeFov; layerEyeFov.Header.Flags = LayerFlags.None; for (int eyeIndex = 0; eyeIndex < 2; eyeIndex++) { EyeType eye = (EyeType)eyeIndex; var eyeTexture = new EyeTexture(); eyeTextures[eyeIndex] = eyeTexture; // Retrieve size and position of the texture for the current eye. eyeTexture.FieldOfView = hmdDesc.DefaultEyeFov[eyeIndex]; eyeTexture.TextureSize = OVR.GetFovTextureSize(sessionPtr, eye, hmdDesc.DefaultEyeFov[eyeIndex], 1.0f); eyeTexture.RenderDescription = OVR.GetRenderDesc(sessionPtr, eye, hmdDesc.DefaultEyeFov[eyeIndex]); eyeTexture.HmdToEyeViewOffset = eyeTexture.RenderDescription.HmdToEyePose.Position; eyeTexture.ViewportSize.Position = new Vector2i(0, 0); eyeTexture.ViewportSize.Size = eyeTexture.TextureSize; eyeTexture.Viewport = new Viewport(0, 0, eyeTexture.TextureSize.Width, eyeTexture.TextureSize.Height, 0.0f, 1.0f); // Define a texture at the size recommended for the eye texture. eyeTexture.Texture2DDescription = new Texture2DDescription(); eyeTexture.Texture2DDescription.Width = eyeTexture.TextureSize.Width; eyeTexture.Texture2DDescription.Height = eyeTexture.TextureSize.Height; eyeTexture.Texture2DDescription.ArraySize = 1; eyeTexture.Texture2DDescription.MipLevels = 1; eyeTexture.Texture2DDescription.Format = Format.R8G8B8A8_UNorm; eyeTexture.Texture2DDescription.SampleDescription = new SampleDescription(1, 0); eyeTexture.Texture2DDescription.Usage = ResourceUsage.Default; eyeTexture.Texture2DDescription.CpuAccessFlags = CpuAccessFlags.None; eyeTexture.Texture2DDescription.BindFlags = BindFlags.ShaderResource | BindFlags.RenderTarget; // Convert the SharpDX texture description to the Oculus texture swap chain description. TextureSwapChainDesc textureSwapChainDesc = SharpDXHelpers.CreateTextureSwapChainDescription(eyeTexture.Texture2DDescription); // Create a texture swap chain, which will contain the textures to render to, for the current eye. IntPtr textureSwapChainPtr; result = OVR.CreateTextureSwapChainDX(sessionPtr, device.NativePointer, ref textureSwapChainDesc, out textureSwapChainPtr); WriteErrorDetails(OVR, result, "Failed to create swap chain."); eyeTexture.SwapTextureSet = new TextureSwapChain(OVR, sessionPtr, textureSwapChainPtr); // Retrieve the number of buffers of the created swap chain. int textureSwapChainBufferCount; result = eyeTexture.SwapTextureSet.GetLength(out textureSwapChainBufferCount); WriteErrorDetails(OVR, result, "Failed to retrieve the number of buffers of the created swap chain."); // Create room for each DirectX texture in the SwapTextureSet. eyeTexture.Textures = new Texture2D[textureSwapChainBufferCount]; eyeTexture.RenderTargetViews = new RenderTargetView[textureSwapChainBufferCount]; // Create a texture 2D and a render target view, for each unmanaged texture contained in the SwapTextureSet. for (int textureIndex = 0; textureIndex < textureSwapChainBufferCount; textureIndex++) { // Retrieve the Direct3D texture contained in the Oculus TextureSwapChainBuffer. IntPtr swapChainTextureComPtr = IntPtr.Zero; result = eyeTexture.SwapTextureSet.GetBufferDX(textureIndex, textureInterfaceId, out swapChainTextureComPtr); WriteErrorDetails(OVR, result, "Failed to retrieve a texture from the created swap chain."); // Create a managed Texture2D, based on the unmanaged texture pointer. eyeTexture.Textures[textureIndex] = new Texture2D(swapChainTextureComPtr); // Create a render target view for the current Texture2D. eyeTexture.RenderTargetViews[textureIndex] = new RenderTargetView(device, eyeTexture.Textures[textureIndex]); } // Define the depth buffer, at the size recommended for the eye texture. eyeTexture.DepthBufferDescription = new Texture2DDescription(); eyeTexture.DepthBufferDescription.Format = Format.D32_Float; eyeTexture.DepthBufferDescription.Width = eyeTexture.TextureSize.Width; eyeTexture.DepthBufferDescription.Height = eyeTexture.TextureSize.Height; eyeTexture.DepthBufferDescription.ArraySize = 1; eyeTexture.DepthBufferDescription.MipLevels = 1; eyeTexture.DepthBufferDescription.SampleDescription = new SampleDescription(1, 0); eyeTexture.DepthBufferDescription.Usage = ResourceUsage.Default; eyeTexture.DepthBufferDescription.BindFlags = BindFlags.DepthStencil; eyeTexture.DepthBufferDescription.CpuAccessFlags = CpuAccessFlags.None; eyeTexture.DepthBufferDescription.OptionFlags = ResourceOptionFlags.None; // Create the depth buffer. eyeTexture.DepthBuffer = new Texture2D(device, eyeTexture.DepthBufferDescription); eyeTexture.DepthStencilView = new DepthStencilView(device, eyeTexture.DepthBuffer); // Specify the texture to show on the HMD. if (eyeIndex == 0) { layerEyeFov.ColorTextureLeft = eyeTexture.SwapTextureSet.TextureSwapChainPtr; layerEyeFov.ViewportLeft.Position = new Vector2i(0, 0); layerEyeFov.ViewportLeft.Size = eyeTexture.TextureSize; layerEyeFov.FovLeft = eyeTexture.FieldOfView; } else { layerEyeFov.ColorTextureRight = eyeTexture.SwapTextureSet.TextureSwapChainPtr; layerEyeFov.ViewportRight.Position = new Vector2i(0, 0); layerEyeFov.ViewportRight.Size = eyeTexture.TextureSize; layerEyeFov.FovRight = eyeTexture.FieldOfView; } } MirrorTextureDesc mirrorTextureDescription = new MirrorTextureDesc(); mirrorTextureDescription.Format = TextureFormat.R8G8B8A8_UNorm_SRgb; mirrorTextureDescription.Width = form.Width; mirrorTextureDescription.Height = form.Height; mirrorTextureDescription.MiscFlags = TextureMiscFlags.None; // Create the texture used to display the rendered result on the computer monitor. IntPtr mirrorTexturePtr; result = OVR.CreateMirrorTextureDX(sessionPtr, device.NativePointer, ref mirrorTextureDescription, out mirrorTexturePtr); WriteErrorDetails(OVR, result, "Failed to create mirror texture."); mirrorTexture = new MirrorTexture(OVR, sessionPtr, mirrorTexturePtr); // Retrieve the Direct3D texture contained in the Oculus MirrorTexture. IntPtr mirrorTextureComPtr = IntPtr.Zero; result = mirrorTexture.GetBufferDX(textureInterfaceId, out mirrorTextureComPtr); WriteErrorDetails(OVR, result, "Failed to retrieve the texture from the created mirror texture buffer."); // Create a managed Texture2D, based on the unmanaged texture pointer. mirrorTextureD3D = new Texture2D(mirrorTextureComPtr); #region Vertex and pixel shader // Create vertex shader. vertexShaderByteCode = ShaderBytecode.CompileFromFile("Shaders.fx", "VertexShaderPositionColor", "vs_4_0"); vertexShader = new VertexShader(device, vertexShaderByteCode); // Create pixel shader. pixelShaderByteCode = ShaderBytecode.CompileFromFile("Shaders.fx", "PixelShaderPositionColor", "ps_4_0"); pixelShader = new PixelShader(device, pixelShaderByteCode); shaderSignature = ShaderSignature.GetInputSignature(vertexShaderByteCode); // Specify that each vertex consists of a single vertex position and color. InputElement[] inputElements = new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0) }; // Define an input layout to be passed to the vertex shader. inputLayout = new InputLayout(device, shaderSignature, inputElements); // Create a vertex buffer, containing our 3D model. vertexBuffer = Buffer.Create(device, BindFlags.VertexBuffer, m_vertices); // Create a constant buffer, to contain our WorldViewProjection matrix, that will be passed to the vertex shader. contantBuffer = new Buffer(device, Utilities.SizeOf <Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); // Setup the immediate context to use the shaders and model we defined. immediateContext.InputAssembler.InputLayout = inputLayout; immediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; immediateContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, sizeof(float) * 4 * 2, 0)); immediateContext.VertexShader.SetConstantBuffer(0, contantBuffer); immediateContext.VertexShader.Set(vertexShader); immediateContext.PixelShader.Set(pixelShader); #endregion DateTime startTime = DateTime.Now; Vector3 position = new Vector3(0, 0, -1); #region Render loop RenderLoop.Run(form, () => { Vector3f[] hmdToEyeViewOffsets = { eyeTextures[0].HmdToEyeViewOffset, eyeTextures[1].HmdToEyeViewOffset }; double displayMidpoint = OVR.GetPredictedDisplayTime(sessionPtr, 0); TrackingState trackingState = OVR.GetTrackingState(sessionPtr, displayMidpoint, true); Posef[] eyePoses = new Posef[2]; // Calculate the position and orientation of each eye. OVR.CalcEyePoses(trackingState.HeadPose.ThePose, hmdToEyeViewOffsets, ref eyePoses); float timeSinceStart = (float)(DateTime.Now - startTime).TotalSeconds; for (int eyeIndex = 0; eyeIndex < 2; eyeIndex++) { EyeType eye = (EyeType)eyeIndex; EyeTexture eyeTexture = eyeTextures[eyeIndex]; if (eyeIndex == 0) { layerEyeFov.RenderPoseLeft = eyePoses[0]; } else { layerEyeFov.RenderPoseRight = eyePoses[1]; } // Update the render description at each frame, as the HmdToEyeOffset can change at runtime. eyeTexture.RenderDescription = OVR.GetRenderDesc(sessionPtr, eye, hmdDesc.DefaultEyeFov[eyeIndex]); // Retrieve the index of the active texture int textureIndex; result = eyeTexture.SwapTextureSet.GetCurrentIndex(out textureIndex); WriteErrorDetails(OVR, result, "Failed to retrieve texture swap chain current index."); immediateContext.OutputMerger.SetRenderTargets(eyeTexture.DepthStencilView, eyeTexture.RenderTargetViews[textureIndex]); immediateContext.ClearRenderTargetView(eyeTexture.RenderTargetViews[textureIndex], Color.Black); immediateContext.ClearDepthStencilView(eyeTexture.DepthStencilView, DepthStencilClearFlags.Depth | DepthStencilClearFlags.Stencil, 1.0f, 0); immediateContext.Rasterizer.SetViewport(eyeTexture.Viewport); // Retrieve the eye rotation quaternion and use it to calculate the LookAt direction and the LookUp direction. Quaternion rotationQuaternion = SharpDXHelpers.ToQuaternion(eyePoses[eyeIndex].Orientation); Matrix rotationMatrix = Matrix.RotationQuaternion(rotationQuaternion); Vector3 lookUp = Vector3.Transform(new Vector3(0, -1, 0), rotationMatrix).ToVector3(); Vector3 lookAt = Vector3.Transform(new Vector3(0, 0, 1), rotationMatrix).ToVector3(); Vector3 viewPosition = position - eyePoses[eyeIndex].Position.ToVector3(); Matrix world = Matrix.Scaling(0.1f) * Matrix.RotationX(timeSinceStart / 10f) * Matrix.RotationY(timeSinceStart * 2 / 10f) * Matrix.RotationZ(timeSinceStart * 3 / 10f); Matrix viewMatrix = Matrix.LookAtLH(viewPosition, viewPosition + lookAt, lookUp); Matrix projectionMatrix = OVR.Matrix4f_Projection(eyeTexture.FieldOfView, 0.1f, 100.0f, ProjectionModifier.LeftHanded).ToMatrix(); projectionMatrix.Transpose(); Matrix worldViewProjection = world * viewMatrix * projectionMatrix; worldViewProjection.Transpose(); // Update the transformation matrix. immediateContext.UpdateSubresource(ref worldViewProjection, contantBuffer); // Draw the cube immediateContext.Draw(m_vertices.Length / 2, 0); // Commits any pending changes to the TextureSwapChain, and advances its current index result = eyeTexture.SwapTextureSet.Commit(); WriteErrorDetails(OVR, result, "Failed to commit the swap chain texture."); } result = OVR.SubmitFrame(sessionPtr, 0L, IntPtr.Zero, ref layerEyeFov); WriteErrorDetails(OVR, result, "Failed to submit the frame of the current layers."); immediateContext.CopyResource(mirrorTextureD3D, backBuffer); swapChain.Present(0, PresentFlags.None); }); #endregion } finally { if (immediateContext != null) { immediateContext.ClearState(); immediateContext.Flush(); } // Release all resources Dispose(inputLayout); Dispose(contantBuffer); Dispose(vertexBuffer); Dispose(shaderSignature); Dispose(pixelShader); Dispose(pixelShaderByteCode); Dispose(vertexShader); Dispose(vertexShaderByteCode); Dispose(mirrorTextureD3D); Dispose(mirrorTexture); Dispose(eyeTextures[0]); Dispose(eyeTextures[1]); Dispose(immediateContext); Dispose(depthStencilState); Dispose(depthStencilView); Dispose(depthBuffer); Dispose(backBufferRenderTargetView); Dispose(backBuffer); Dispose(swapChain); Dispose(factory); // Disposing the device, before the hmd, will cause the hmd to fail when disposing. // Disposing the device, after the hmd, will cause the dispose of the device to fail. // It looks as if the hmd steals ownership of the device and destroys it, when it's shutting down. // device.Dispose(); OVR.Destroy(sessionPtr); } }
private bool InitializeShader(Device device, IntPtr windowsHandle, string vsFileName, string psFileName) { try { vsFileName = DSystemConfiguration.ShaderFilePath + vsFileName; psFileName = DSystemConfiguration.ShaderFilePath + psFileName; ShaderBytecode vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFileName, "ColorVertexShader", "vs_4_0", ShaderFlags.None, EffectFlags.None); ShaderBytecode pixelShaderByteCode = ShaderBytecode.CompileFromFile(psFileName, "ColorPixelShader", "ps_4_0", ShaderFlags.None, EffectFlags.None); VertexShader = new VertexShader(device, vertexShaderByteCode); PixelShader = new PixelShader(device, pixelShaderByteCode); InputElement[] inputElements = new InputElement[] { new InputElement() { SemanticName = "POSITION", SemanticIndex = 0, Format = SharpDX.DXGI.Format.R32G32B32_Float, Slot = 0, AlignedByteOffset = 0, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 }, new InputElement() { SemanticName = "COLOR", SemanticIndex = 0, Format = SharpDX.DXGI.Format.R32G32B32A32_Float, Slot = 0, AlignedByteOffset = InputElement.AppendAligned, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 } }; Layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements); vertexShaderByteCode.Dispose(); pixelShaderByteCode.Dispose(); BufferDescription matrixBufDesc = new BufferDescription() { Usage = ResourceUsage.Dynamic, SizeInBytes = Utilities.SizeOf <DMatrixBuffer>(), BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; ConstantMatrixBuffer = new SharpDX.Direct3D11.Buffer(device, matrixBufDesc); return(true); } catch (Exception) { throw new ShaderNotInitializedException(); } }
private bool InitializeShader(SharpDX.Direct3D11.Device device, IntPtr windowsHandle) //, string vsFileName, string psFileName //, Matrix worldMatrix { try { /*var vsFileNameByteArray = "../../../sc_instance_shader/" + "red.vs"; * var psFileNameByteArray = "../../../sc_instance_shader/" + "red.ps"; * var gsFileNameByteArray = "../../../sc_instance_shader/" + "HLSL.gs"; * * vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFileNameByteArray, "ColorVertexShader", "vs_4_0", ShaderFlags.None, SharpDX.D3DCompiler.EffectFlags.None); * pixelShaderByteCode = ShaderBytecode.CompileFromFile(psFileNameByteArray, "ColorPixelShader", "ps_4_0", ShaderFlags.None, SharpDX.D3DCompiler.EffectFlags.None); * geometryShaderByteCode = ShaderBytecode.CompileFromFile(gsFileNameByteArray, "GS", "gs_5_0", ShaderFlags.None, EffectFlags.None); */ /* * if (MainWindow.is_wpf == 1) * { * var vsFileNameByteArray = SCCoreSystems.Properties.Resources.red1; * var psFileNameByteArray = SCCoreSystems.Properties.Resources.red; * var gsFileNameByteArray = SCCoreSystems.Properties.Resources.HLSL; * vertexShaderByteCode = ShaderBytecode.Compile(vsFileNameByteArray, "ColorVertexShader", "vs_5_0", ShaderFlags.None, EffectFlags.None); * pixelShaderByteCode = ShaderBytecode.Compile(psFileNameByteArray, "ColorPixelShader", "ps_5_0", ShaderFlags.None, EffectFlags.None); * geometryShaderByteCode = ShaderBytecode.Compile(gsFileNameByteArray, "GS", "gs_5_0", ShaderFlags.None, EffectFlags.None); * * * } * else * { * * }*/ var vsFileNameByteArray = SCCoreSystems.Properties.Resources.red1; var psFileNameByteArray = SCCoreSystems.Properties.Resources.red; var gsFileNameByteArray = SCCoreSystems.Properties.Resources.HLSL; vertexShaderByteCode = ShaderBytecode.Compile(vsFileNameByteArray, "ColorVertexShader", "vs_5_0", ShaderFlags.None, EffectFlags.None); pixelShaderByteCode = ShaderBytecode.Compile(psFileNameByteArray, "ColorPixelShader", "ps_5_0", ShaderFlags.None, EffectFlags.None); geometryShaderByteCode = ShaderBytecode.Compile(gsFileNameByteArray, "GS", "gs_5_0", ShaderFlags.None, EffectFlags.None); //ShaderBytecode vertexShaderByteCode = ShaderBytecode.Compile(gsFileNameByteArray, "VS", "vs_5_0", ShaderFlags.None, EffectFlags.None); //ShaderBytecode pixelShaderByteCode = ShaderBytecode.Compile(gsFileNameByteArray, "PS", "ps_5_0", ShaderFlags.None, EffectFlags.None); // Create the vertex shader from the buffer. VertexShader = new VertexShader(device, vertexShaderByteCode); // Create the pixel shader from the buffer. PixelShader = new PixelShader(device, pixelShaderByteCode); GeometryShader = new GeometryShader(device, geometryShaderByteCode); // Now setup the layout of the data that goes into the shader. // This setup needs to match the VertexType structure in the Model and in the shader. InputElement[] inputElements = new InputElement[] { //new InputElement("POSITION", 0, SharpDX.DXGI.Format.R32G32B32_Float, 0, 0) new InputElement() { SemanticName = "POSITION", SemanticIndex = 0, Format = SharpDX.DXGI.Format.R32G32B32_Float, Slot = 0, AlignedByteOffset = 0, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 }, new InputElement() { SemanticName = "COLOR", SemanticIndex = 0, Format = SharpDX.DXGI.Format.R32G32B32A32_Float, Slot = 0, AlignedByteOffset = InputElement.AppendAligned, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 }, new InputElement() { SemanticName = "TEXCOORD", SemanticIndex = 1, Format = SharpDX.DXGI.Format.R32G32B32A32_Float, Slot = 1, AlignedByteOffset = 0, Classification = InputClassification.PerInstanceData, InstanceDataStepRate = 1 }, }; // Create the vertex input the layout. Kin dof like a Vertex Declaration. Layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements); // Release the vertex and pixel shader buffers, since they are no longer needed. vertexShaderByteCode.Dispose(); pixelShaderByteCode.Dispose(); // Setup the description of the dynamic matrix constant Matrix buffer that is in the vertex shader. BufferDescription matrixBufferDescription = new BufferDescription() { Usage = ResourceUsage.Dynamic, SizeInBytes = Utilities.SizeOf <DMatrixBuffer>(),// * Utilities.SizeOf<DInstanceType>() * instances.Length, //Utilities.SizeOf<DMatrixBuffer>() * BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; /*BufferDescription matrixBufferDescription = new BufferDescription() * { * Usage = ResourceUsage.Default, * SizeInBytes = Utilities.SizeOf<DMatrixBuffer>(), * BindFlags = BindFlags.ConstantBuffer, * CpuAccessFlags = CpuAccessFlags.None, * OptionFlags = ResourceOptionFlags.None, * StructureByteStride = 0 * };*/ // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class. ConstantMatrixBuffer = new SharpDX.Direct3D11.Buffer(device, matrixBufferDescription); //ConstantMatrixBuffer = SharpDX.Direct3D11.Buffer.Create(device, BindFlags.VertexBuffer, instances); //int bufferSlotNumberer = 0; //device.ImmediateContext.VertexShader.SetConstantBuffer(bufferSlotNumberer, ConstantMatrixBuffer); //ConstantMatrixBuffer = SharpDX.Direct3D11.Buffer.Create(device, BindFlags.ConstantBuffer, instances, Utilities.SizeOf<DMatrixBuffer>()* Utilities.SizeOf<DInstanceType>() * instances.Length, ResourceUsage.Dynamic, CpuAccessFlags.Write, ResourceOptionFlags.None, 0); // Create a texture sampler state description. /*SamplerStateDescription samplerDesc = new SamplerStateDescription() * { * Filter = Filter.MinMagMipLinear, * AddressU = TextureAddressMode.Wrap, * AddressV = TextureAddressMode.Wrap, * AddressW = TextureAddressMode.Wrap, * MipLodBias = 0, * MaximumAnisotropy = 1, * ComparisonFunction = Comparison.Always, * BorderColor = new Color4(0, 0, 0, 0), // Black Border. * MinimumLod = 0, * MaximumLod = float.MaxValue * }; * * // Create the texture sampler state. * SamplerState = new SamplerState(device, samplerDesc); */ //int bufferSlotNumber = 0; //device.ImmediateContext.VertexShader.SetConstantBuffer(bufferSlotNumber, ConstantMatrixBuffer); return(true); } catch (Exception ex) { Console.WriteLine(" SC_VR_TOUCH_SHADER ERROR ### " + ex.ToString()); return(false); } }
private bool InitializeShader(Device device, IntPtr windowsHandle, string vsFileName, string psFileName) { try { vsFileName = DSystemConfiguration.ShaderFilePath + vsFileName; psFileName = DSystemConfiguration.ShaderFilePath + psFileName; // Compile the vertex shader code. ShaderBytecode vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFileName, "ColorVertexShader", "vs_4_0", ShaderFlags.None, EffectFlags.None); // Compile the pixel shader code. ShaderBytecode pixelShaderByteCode = ShaderBytecode.CompileFromFile(psFileName, "ColorPixelShader", "ps_4_0", ShaderFlags.None, EffectFlags.None); // Create the vertex shader from the buffer. VertexShader = new VertexShader(device, vertexShaderByteCode); // Create the pixel shader from the buffer. PixelShader = new PixelShader(device, pixelShaderByteCode); // Now setup the layout of the data that goes into the shader. // This setup needs to match the VertexType structure in the Model and in the shader. InputElement[] inputElements = new InputElement[] { new InputElement() { SemanticName = "POSITION", SemanticIndex = 0, Format = SharpDX.DXGI.Format.R32G32B32_Float, Slot = 0, AlignedByteOffset = 0, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 }, new InputElement() { SemanticName = "COLOR", SemanticIndex = 0, Format = SharpDX.DXGI.Format.R32G32B32A32_Float, Slot = 0, AlignedByteOffset = InputElement.AppendAligned, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 } }; // Create the vertex input the layout. Layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements); // Release the vertex and pixel shader buffers, since they are no longer needed. vertexShaderByteCode.Dispose(); pixelShaderByteCode.Dispose(); // Setup the description of the dynamic matrix constant buffer that is in the vertex shader. BufferDescription matrixBufDesc = new BufferDescription() { Usage = ResourceUsage.Dynamic, SizeInBytes = Utilities.SizeOf <DMatrixBuffer>(), // was Matrix BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class. ConstantMatrixBuffer = new SharpDX.Direct3D11.Buffer(device, matrixBufDesc); return(true); } catch (Exception ex) { MessageBox.Show("Error initializing shader. Error is " + ex.Message); return(false); } }
private void FormMain_Shown(object sender, EventArgs e) { var desc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(this.Width, this.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = this.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; // Create Device and SwapChain Device11 device11; SwapChain swMain; Device11.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, desc, out device11, out swMain); // Ignore all windows events var factory = swMain.GetParent <Factory>(); factory.MakeWindowAssociation(this.Handle, WindowAssociationFlags.IgnoreAll); // New RenderTargetView from the backbuffer var backBuffer = Texture2D.FromSwapChain <Texture2D>(swMain, 0); var renderView = new RenderTargetView(device11, backBuffer); device11.ImmediateContext.Rasterizer.State = new RasterizerState(device11, new RasterizerStateDescription() { CullMode = CullMode.None, FillMode = FillMode.Solid }); device11.ImmediateContext.Rasterizer.SetViewport(new Viewport(0, 0, this.Width, this.Height, 0.0f, 1.0f)); device11.ImmediateContext.OutputMerger.SetTargets(renderView); // Compile Vertex and Pixel shaders var vertexShaderByteCode = ShaderBytecode.CompileFromFile("Color.hlsl", "VS", "vs_5_0", ShaderFlags.None, EffectFlags.None); var vertexShader = new VertexShader(device11, vertexShaderByteCode); var pixelShaderByteCode = ShaderBytecode.CompileFromFile("Color.hlsl", "PS", "ps_4_0", ShaderFlags.None, EffectFlags.None); var pixelShader = new PixelShader(device11, pixelShaderByteCode); // Layout from VertexShader input signature var layout = new InputLayout( device11, ShaderSignature.GetInputSignature(vertexShaderByteCode), new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0) }); // Instantiate Vertex buiffer from vertex data var vertices1 = Buffer11.Create(device11, BindFlags.VertexBuffer, new[] { new Vector4(-0.5f, 0.5f, 0f, 1.0f), new Vector4(0.0f, 0.0f, 0.0f, 1.0f), new Vector4(-0.1f, 0.5f, 0f, 1.0f), new Vector4(0.0f, 0.0f, 0.0f, 1.0f), new Vector4(-0.5f, 0.1f, 0f, 1.0f), new Vector4(0.0f, 0.0f, 0.0f, 1.0f), new Vector4(-0.5f, 0.1f, 0f, 1.0f), new Vector4(0.0f, 0.0f, 0.0f, 1.0f), new Vector4(-0.1f, 0.5f, 0f, 1.0f), new Vector4(0.0f, 0.0f, 0.0f, 1.0f), new Vector4(-0.1f, 0.1f, 0f, 1.0f), new Vector4(0.0f, 0.0f, 0.0f, 1.0f), new Vector4(0.1f, 0.5f, 0f, 1.0f), new Vector4(0.0f, 0.0f, 0.0f, 1.0f), new Vector4(0.5f, 0.5f, 0f, 1.0f), new Vector4(0.0f, 0.0f, 0.0f, 1.0f), new Vector4(0.1f, 0.1f, 0f, 1.0f), new Vector4(0.0f, 0.0f, 0.0f, 1.0f), new Vector4(0.1f, 0.1f, 0f, 1.0f), new Vector4(0.0f, 0.0f, 0.0f, 1.0f), new Vector4(0.5f, 0.5f, 0f, 1.0f), new Vector4(0.0f, 0.0f, 0.0f, 1.0f), new Vector4(0.5f, 0.1f, 0f, 1.0f), new Vector4(0.0f, 0.0f, 0.0f, 1.0f), }); var vertices2 = Buffer11.Create(device11, BindFlags.VertexBuffer, new[] { new Vector4(-0.5f, -0.1f, 0f, 1.0f), new Vector4(0.0f, 0.0f, 0.0f, 1.0f), new Vector4(-0.1f, -0.1f, 0f, 1.0f), new Vector4(0.0f, 0.0f, 0.0f, 1.0f), new Vector4(-0.5f, -0.5f, 0f, 1.0f), new Vector4(0.0f, 0.0f, 0.0f, 1.0f), new Vector4(-0.5f, -0.5f, 0f, 1.0f), new Vector4(0.0f, 0.0f, 0.0f, 1.0f), new Vector4(-0.1f, -0.1f, 0f, 1.0f), new Vector4(0.0f, 0.0f, 0.0f, 1.0f), new Vector4(-0.1f, -0.5f, 0f, 1.0f), new Vector4(0.0f, 0.0f, 0.0f, 1.0f), new Vector4(0.1f, -0.1f, 0f, 1.0f), new Vector4(0.0f, 0.0f, 0.0f, 1.0f), new Vector4(0.5f, -0.1f, 0f, 1.0f), new Vector4(0.0f, 0.0f, 0.0f, 1.0f), new Vector4(0.1f, -0.5f, 0f, 1.0f), new Vector4(0.0f, 0.0f, 0.0f, 1.0f), new Vector4(0.1f, -0.5f, 0f, 1.0f), new Vector4(0.0f, 0.0f, 0.0f, 1.0f), new Vector4(0.5f, -0.1f, 0f, 1.0f), new Vector4(0.0f, 0.0f, 0.0f, 1.0f), new Vector4(0.5f, -0.5f, 0f, 1.0f), new Vector4(0.0f, 0.0f, 0.0f, 1.0f), }); // Prepare All the stages device11.ImmediateContext.InputAssembler.InputLayout = layout; device11.ImmediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; device11.ImmediateContext.VertexShader.Set(vertexShader); device11.ImmediateContext.PixelShader.Set(pixelShader); Buffer11 wvpBuffer = new Buffer11(device11, Utilities.SizeOf <Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); // Main loop RenderLoop.Run(this, () => { device11.ImmediateContext.ClearRenderTargetView(renderView, Color.Aquamarine); device11.ImmediateContext.VertexShader.SetConstantBuffer(0, wvpBuffer); Matrix projection = Matrix.OrthoLH(1f, 1f, 0, 2f); Matrix view = Matrix.LookAtLH(new Vector3(0, 0, -1f), Vector3.Zero, Vector3.Up); Matrix world = Matrix.RotationZ(2); Matrix WVP = world * view * projection; device11.ImmediateContext.UpdateSubresource <Matrix>(ref WVP, wvpBuffer); device11.ImmediateContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices1, 32, 0)); device11.ImmediateContext.Draw(12, 0); device11.ImmediateContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices2, 32, 0)); device11.ImmediateContext.Draw(12, 0); swMain.Present(0, PresentFlags.None); }); // Release all resources vertexShaderByteCode.Dispose(); vertexShader.Dispose(); pixelShaderByteCode.Dispose(); pixelShader.Dispose(); vertices1.Dispose(); vertices2.Dispose(); layout.Dispose(); renderView.Dispose(); backBuffer.Dispose(); device11.ImmediateContext.ClearState(); device11.ImmediateContext.Flush(); device11.Dispose(); device11.ImmediateContext.Dispose(); swMain.Dispose(); factory.Dispose(); }
private static void Main() { var form = new RenderForm("SharpDX - MiniTri Direct3D 11 Sample"); // SwapChain description var desc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = form.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; // Create Device and SwapChain Device device; SwapChain swapChain; Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.Debug, desc, out device, out swapChain); var context = device.ImmediateContext; // Ignore all windows events Factory factory = swapChain.GetParent <Factory>(); factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.None); // New RenderTargetView from the backbuffer Texture2D backBuffer = Texture2D.FromSwapChain <Texture2D>(swapChain, 0); var renderView = new RenderTargetView(device, backBuffer); // Compile Vertex and Pixel shaders var vertexShaderByteCode = ShaderBytecode.CompileFromFile("MiniTri.fx", "VS", "vs_4_0", ShaderFlags.None, EffectFlags.None); var vertexShader = new VertexShader(device, vertexShaderByteCode); var pixelShaderByteCode = ShaderBytecode.CompileFromFile("MiniTri.fx", "PS", "ps_4_0", ShaderFlags.None, EffectFlags.None); var pixelShader = new PixelShader(device, pixelShaderByteCode); // Layout from VertexShader input signature var layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0) }); // Write vertex data to a datastream var stream = new DataStream(32 * 3, true, true); stream.WriteRange(new[] { new Vector4(0.0f, 0.5f, 0.5f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(-0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f) }); stream.Position = 0; // Instantiate Vertex buiffer from vertex data var vertices = new Buffer(device, stream, new BufferDescription() { BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, SizeInBytes = 32 * 3, Usage = ResourceUsage.Default, StructureByteStride = 0 }); stream.Release(); // Prepare All the stages context.InputAssembler.SetInputLayout(layout); context.InputAssembler.SetPrimitiveTopology(PrimitiveTopology.TriangleList); context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, 32, 0)); context.VertexShader.Set(vertexShader); context.Rasterizer.SetViewports(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f)); context.PixelShader.Set(pixelShader); context.OutputMerger.SetTargets(renderView); // Main loop RenderLoop.Run(form, () => { context.ClearRenderTargetView(renderView, new Color4(1.0f, 0.0f, 0.0f, 0.0f)); context.Draw(3, 0); swapChain.Present(0, PresentFlags.None); }); // Release all resources vertexShaderByteCode.Release(); vertexShader.Release(); pixelShaderByteCode.Release(); pixelShader.Release(); vertices.Release(); layout.Release(); renderView.Release(); backBuffer.Release(); context.ClearState(); context.Flush(); device.Release(); context.Release(); swapChain.Release(); factory.Release(); }
private void SetupD3D() { SharpDX.Configuration.EnableObjectTracking = true; if (D3DDevice != null) { return; } var desc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(Convert.ToInt32(host.ActualWidth), Convert.ToInt32(host.ActualHeight), new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = new WindowInteropHelper(HostWindow).Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; SharpDX.Direct3D11.Device.CreateWithSwapChain(SharpDX.Direct3D.DriverType.Hardware, SharpDX.Direct3D11.DeviceCreationFlags.None, desc, out D3DDevice, out SwapChain); D3DContext = D3DDevice.ImmediateContext; //Load Shader from the Internal Resource string shader = ""; var assembly = this.GetType().Assembly; using (var stream = assembly.GetManifestResourceStream(assembly.GetName().Name + "." + "ffmege.fx")) { shader = new StreamReader(stream).ReadToEnd(); } // Compile Vertex and Pixel shaders var vertexShaderByteCode = ShaderBytecode.Compile(shader, "VS", "vs_4_0", ShaderFlags.None, EffectFlags.None); var vertexShader = new VertexShader(D3DDevice, vertexShaderByteCode); var pixelShaderByteCode = ShaderBytecode.Compile(shader, "PS", "ps_4_0", ShaderFlags.None, EffectFlags.None); var pixelShader = new PixelShader(D3DDevice, pixelShaderByteCode); var layout = new InputLayout(D3DDevice, ShaderSignature.GetInputSignature(vertexShaderByteCode), new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 16, 0) }); // Instantiate Vertex buiffer from vertex data var vertices = SharpDX.Direct3D11.Buffer.Create(D3DDevice, SharpDX.Direct3D11.BindFlags.VertexBuffer, new[] { // Position Colour U V -1.0f, 1.0f, 0.5f, 1.0f, 0.0f, 0.0f, //top left 1.0f, -1.0f, 0.5f, 1.0f, 1.0f, 1.0f, //bottom right -1.0f, -1.0f, 0.5f, 1.0f, 0.0f, 1.0f, //bottom left -1.0f, 1.0f, 0.5f, 1.0f, 0.0f, 0.0f, //top left 1.0f, 1.0f, 0.5f, 1.0f, 1.0f, 0.0f, //top right 1.0f, -1.0f, 0.5f, 1.0f, 1.0f, 1.0f, //bottom right }); var vertexBufferBinding = new VertexBufferBinding(vertices, sizeof(float) * 6, 0); var sampler = new SamplerState(D3DDevice, new SamplerStateDescription() { Filter = Filter.MinMagMipLinear, AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, BorderColor = SharpDX.Color.Black, ComparisonFunction = Comparison.Never, MaximumAnisotropy = 1, MipLodBias = 0, MinimumLod = -float.MaxValue, MaximumLod = float.MaxValue }); // Prepare All the stages D3DContext.InputAssembler.SetVertexBuffers(0, vertexBufferBinding); D3DContext.InputAssembler.InputLayout = layout; D3DContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; D3DContext.VertexShader.Set(vertexShader); D3DContext.PixelShader.SetSampler(0, sampler); D3DContext.PixelShader.Set(pixelShader); //Clean up temporary resources vertexShader.Dispose(); pixelShader.Dispose(); layout.Dispose(); vertexBufferBinding.Buffer.Dispose(); vertices.Dispose(); sampler.Dispose(); }
/// <summary> /// Compile shader code and add it with Textures. /// </summary> public void BuildShaderInputLayout() { // load and compile the vertex shader using (var bytecode = ShaderBytecode.CompileFromFile("C:\\transparent.fx", "VShader", "vs_4_0", ShaderFlags.None, EffectFlags.None)) { inputSignature = ShaderSignature.GetInputSignature(bytecode); vertexShader = new VertexShader(device, bytecode); } // load and compile the pixel shader using (var bytecode = ShaderBytecode.CompileFromFile("C:\\transparent.fx", "PShader", "ps_4_0", ShaderFlags.None, EffectFlags.None)) pixelShader = new PixelShader(device, bytecode); //Create vertex layout. var elements = new[] { new InputElement("POSITION",0, SlimDX.DXGI.Format.R32G32B32_Float, 0,0,InputClassification.PerVertexData,0), new InputElement("NORMAL", 0 ,SlimDX.DXGI.Format.R32G32B32_Float,12,0,InputClassification.PerVertexData,0), new InputElement("TEXCOORD", 0 ,SlimDX.DXGI.Format.R32G32B32_Float,24,0,InputClassification.PerVertexData,0), }; //config what things will be extracated from the shaders layout = new InputLayout(device, inputSignature, elements); }
private bool InitializeShader(Device device, IntPtr hwnd, string vsFileName, string psFileName) { try { // Setup full pathes vsFileName = DSystemConfiguration.ShaderFilePath + vsFileName; psFileName = DSystemConfiguration.ShaderFilePath + psFileName; // Compile the Vertex & Pixel Shader code. ShaderBytecode vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFileName, "SkyDomeVertexShader", DSystemConfiguration.VertexShaderProfile, ShaderFlags.None, EffectFlags.None); ShaderBytecode pixelShaderByteCode = ShaderBytecode.CompileFromFile(psFileName, "SkyDomePixelShader", DSystemConfiguration.PixelShaderProfile, ShaderFlags.None, EffectFlags.None); // Create the Vertex & Pixel Shader from the buffer. VertexShader = new VertexShader(device, vertexShaderByteCode); PixelShader = new PixelShader(device, pixelShaderByteCode); // Create the vertex input layout description. InputElement[] inputElements = new InputElement[] { new InputElement() { SemanticName = "POSITION", SemanticIndex = 0, Format = SharpDX.DXGI.Format.R32G32B32_Float, Slot = 0, AlignedByteOffset = 0, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 } }; // Create the vertex input the layout. Layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements); // Release the vertex and pixel shader buffers, since they are no longer needed. vertexShaderByteCode.Dispose(); pixelShaderByteCode.Dispose(); // Setup the description of the dynamic matrix constant buffer that is in the vertex shader. BufferDescription matrixBufferDesc = new BufferDescription() { Usage = ResourceUsage.Dynamic, SizeInBytes = Utilities.SizeOf <DMatrixBuffer>(), BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class. ConstantMatrixBuffer = new SharpDX.Direct3D11.Buffer(device, matrixBufferDesc); // Setup the description of the gradient constant buffer that is in the pixel shader. BufferDescription gradientBufferDesc = new BufferDescription() { Usage = ResourceUsage.Dynamic, SizeInBytes = Utilities.SizeOf <DGradientBuffer>(), BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; // Create the constant buffer pointer so we can access the pixel shader constant buffer from within this class. ConstantGradientBuffer = new SharpDX.Direct3D11.Buffer(device, gradientBufferDesc); return(true); } catch { return(false); } }
public void CreateShaders(string code) { UpdateRenderer = true; // load and compile the vertex shader using (var bytecode = ShaderBytecode.Compile(code, "VShader", "vs_5_0", ShaderFlags.None, EffectFlags.None)) { inputSignature = ShaderSignature.GetInputSignature(bytecode); vertexShader = new VertexShader(device, bytecode); } // load and compile the pixel shader using (var bytecode = ShaderBytecode.Compile(code, "PShader", "ps_5_0", ShaderFlags.None, EffectFlags.None)) pixelShader = new PixelShader(device, bytecode); string compilationError = ""; //ShaderBytecode compiledShader = ShaderBytecode.CompileFromFile("vteffect.fx", "fx_4_0", ShaderFlags.None, EffectFlags.None, null, null, out compilationError); //fx = new Effect(device, compiledShader); // create test vertex data, making sure to rewind the stream afterward vertices = new DataStream(20 * 4, true, true); vertices.Write(new Vector3(-1f, -1f, 0.5f)); vertices.Write(new Vector2(0f, 1f)); vertices.Write(new Vector3(-1f, 1f, 0.5f)); vertices.Write(new Vector2(0f, 0f)); vertices.Write(new Vector3(1f, -1f, 0.5f)); vertices.Write(new Vector2(1f, 1f)); vertices.Write(new Vector3(1f, 1f, 0.5f)); vertices.Write(new Vector2(1f, 0f)); vertices.Position = 0; // create the vertex layout and buffer var elements = new[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0) }; layout = new InputLayout(device, inputSignature, elements); vertexBuffer = new SlimDX.Direct3D11.Buffer(device, vertices, 20 * 4, ResourceUsage.Dynamic, BindFlags.VertexBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, 0); List<int> indices = new List<int>(); indices.Add(0); indices.Add(1); indices.Add(2); indices.Add(2); indices.Add(1); indices.Add(3); var ibd = new BufferDescription(sizeof(int) * indices.Count, ResourceUsage.Immutable, BindFlags.IndexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); indexBuffer = new SlimDX.Direct3D11.Buffer(device, new DataStream(indices.ToArray(), false, false), ibd); // configure the Input Assembler portion of the pipeline with the vertex data context.InputAssembler.InputLayout = layout; context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, 20, 0)); context.InputAssembler.SetIndexBuffer(indexBuffer, Format.R32_UInt, 0); // set the shaders context.VertexShader.Set(vertexShader); context.PixelShader.Set(pixelShader); SamplerDescription sampleDesc = new SamplerDescription(); sampleDesc.Filter = Filter.MinMagMipPoint; sampleDesc.AddressU = TextureAddressMode.Clamp; sampleDesc.AddressV = TextureAddressMode.Clamp; sampleDesc.AddressW = TextureAddressMode.Clamp; sampleDesc.MipLodBias = 0.0f; sampleDesc.ComparisonFunction = Comparison.Always; sampleDesc.BorderColor = new Color4(0, 0, 0, 0); sampleDesc.MinimumLod = 0; sampleDesc.MaximumLod = 1; sampleState = SamplerState.FromDescription(device, sampleDesc); SamplerDescription indSampleDesc = new SamplerDescription(); sampleDesc.Filter = Filter.MinMagMipPoint; sampleDesc.AddressU = TextureAddressMode.Wrap; sampleDesc.AddressV = TextureAddressMode.Wrap; sampleDesc.AddressW = TextureAddressMode.Wrap; sampleDesc.MipLodBias = 0.0f; sampleDesc.ComparisonFunction = Comparison.Always; sampleDesc.BorderColor = new Color4(0, 0, 0, 0); sampleDesc.MinimumLod = 0; sampleDesc.MaximumLod = 1; indSampleState = SamplerState.FromDescription(device, sampleDesc); ImageLoadInformation loadInfo = new ImageLoadInformation() { Width = 2, Height = 2 }; loadInfo.BindFlags = BindFlags.ShaderResource; loadInfo.CpuAccessFlags = CpuAccessFlags.None; loadInfo.Depth = 4; loadInfo.FilterFlags = FilterFlags.Point; loadInfo.FirstMipLevel = 0; loadInfo.Format = Format.R8G8B8A8_SInt; loadInfo.MipLevels = 0; loadInfo.Usage = ResourceUsage.Default; texture = new Texture2D(device, new Texture2DDescription { BindFlags = BindFlags.ShaderResource, ArraySize = 1024, Width = 128, Height = 128, Usage = ResourceUsage.Default, CpuAccessFlags = CpuAccessFlags.None, Format = Format.R8G8B8A8_UNorm, SampleDescription = new SampleDescription(1, 0), MipLevels = 1, OptionFlags = ResourceOptionFlags.None });//Texture2D.FromFile(device,"Tourism_Industrial_d.png"); resourceView = new ShaderResourceView(device, texture); device.ImmediateContext.PixelShader.SetShaderResource(resourceView, 0); context.PixelShader.SetShaderResource(resourceView, 0); context.PixelShader.SetSampler(sampleState, 0); context.PixelShader.SetSampler(indSampleState, 1); if (currentEntry != null) SetTexture(currentEntry); }
static void Main() { var form = new RenderForm("Triange") { ClientSize = new System.Drawing.Size(800, 800) }; Device device; SwapChain swapChain; var swapDesc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = form.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; Device.CreateWithSwapChain( DriverType.Hardware, DeviceCreationFlags.None, swapDesc, out device, out swapChain); var backBuffer = swapChain.GetBackBuffer <Texture2D>(0); var renderView = new RenderTargetView(device, backBuffer); var vertexShaderByteCode = ShaderBytecode.CompileFromFile(@".\MiniTri.fx", "VSMain", "vs_5_0"); var vertexShader = new VertexShader(device, vertexShaderByteCode); var pixelShaderByteCode = ShaderBytecode.CompileFromFile(@".\MiniTri.fx", "PSMain", "ps_5_0"); var pixelShader = new PixelShader(device, pixelShaderByteCode); var layout = new InputLayout( device, ShaderSignature.GetInputSignature(vertexShaderByteCode), new [] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0) }); var points = new[] { new Vector4(0.0f, 0.5f, 0.5f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(-0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector4(0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f) }; var bufDesc = new BufferDescription { BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, Usage = ResourceUsage.Default }; var vb = Buffer.Create(device, points, bufDesc); DeviceContext context = device.ImmediateContext; context.InputAssembler.InputLayout = layout; context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vb, 32, 0)); context.VertexShader.Set(vertexShader); context.PixelShader.Set(pixelShader); context.Rasterizer.State = new RasterizerState(device, new RasterizerStateDescription { CullMode = CullMode.None, FillMode = FillMode.Solid }); context.Rasterizer.SetViewport(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f)); context.OutputMerger.SetTargets(renderView); RenderLoop.Run(form, () => { context.ClearRenderTargetView(renderView, Color.Black); context.Draw(3, 0); swapChain.Present(0, PresentFlags.None); }); vertexShaderByteCode.Dispose(); vertexShader.Dispose(); pixelShaderByteCode.Dispose(); pixelShader.Dispose(); vb.Dispose(); layout.Dispose(); renderView.Dispose(); backBuffer.Dispose(); context.ClearState(); context.Flush(); device.Dispose(); context.Dispose(); swapChain.Dispose(); }
public virtual void Update(Device device, ShaderSignature effectSignature) { if (device != null && !device.Disposed) { mDevice = device; mSignature = effectSignature; // If there is less than 1 vertex then we can't make a point, let alone a shape! if (Vertices != null && Vertices.Count > 0) { CalculatePreTransformBoundingBox(); // Add Vertices to a datastream. using (DataStream dataStream = new DataStream(Vertices.NumBytes, true, true)) { dataStream.WriteRange(this.Vertices.ToArray()); dataStream.Position = 0; // Create a new data buffer description and buffer BufferDescription desc = new BufferDescription() { BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, SizeInBytes = Vertices.NumBytes, Usage = ResourceUsage.Default }; if (vertexBuffer != null) vertexBuffer.Dispose(); vertexBuffer = new SlimDX.Direct3D10.Buffer(device, dataStream, desc); //dataStream.Close(); } if (Vertices != null && Vertices.Count > 0) { // Set the input layout. InputElement[] inputElements = Vertices[0].GetInputElements(); if (vertexLayout != null) vertexLayout.Dispose(); vertexLayout = new InputLayout(device, effectSignature, inputElements); // Draw Indexed if (Vertices.Indices != null && Vertices.Indices.Count > 0) { using (DataStream iStream = new DataStream(sizeof(int) * Vertices.Indices.Count, true, true)) { iStream.WriteRange(Vertices.Indices.ToArray()); iStream.Position = 0; BufferDescription desc = new BufferDescription() { Usage = ResourceUsage.Default, SizeInBytes = sizeof(int) * Vertices.Indices.Count, BindFlags = BindFlags.IndexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }; if (indexBuffer != null) indexBuffer.Dispose(); indexBuffer = new Buffer(device, iStream, desc); //iStream.Close(); } } else { if (indexBuffer != null) indexBuffer.Dispose(); indexBuffer = null; } } else { if (vertexBuffer != null) vertexBuffer.Dispose(); vertexBuffer = null; } } } FireShapeChangeEvent(new ShapeChangeEventArgs(this, ShapeChangeEventArgs.ChangeAction.None)); }
private bool InitialiseShader(Device device, IntPtr windowHandle, string vertexShaderFileName, string pixelShaderFileName) { try { vertexShaderFileName = SystemConfiguration.ShaderFilePath + vertexShaderFileName; pixelShaderFileName = SystemConfiguration.ShaderFilePath + pixelShaderFileName; var vertexShaderByteCode = ShaderBytecode.CompileFromFile(vertexShaderFileName, "FoliageVertexShader", SystemConfiguration.VertexShaderProfile, ShaderFlags.None, EffectFlags.None); var pixelShaderByteCode = ShaderBytecode.CompileFromFile(pixelShaderFileName, "FoliagePixelShader", SystemConfiguration.PixelShaderProfile, ShaderFlags.None, EffectFlags.None); VertexShader = new VertexShader(device, vertexShaderByteCode); PixelShader = new PixelShader(device, pixelShaderByteCode); var inputElements = new InputElement[] { new InputElement() { SemanticName = "POSITION", SemanticIndex = 0, Format = SharpDX.DXGI.Format.R32G32B32_Float, Slot = 0, AlignedByteOffset = 0, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 }, new InputElement() { SemanticName = "TEXCOORD", SemanticIndex = 0, Format = SharpDX.DXGI.Format.R32G32_Float, Slot = 0, AlignedByteOffset = InputElement.AppendAligned, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 }, new InputElement() { SemanticName = "WORLD", SemanticIndex = 0, Format = SharpDX.DXGI.Format.R32G32B32A32_Float, Slot = 1, AlignedByteOffset = 0, Classification = InputClassification.PerInstanceData, InstanceDataStepRate = 1 }, new InputElement() { SemanticName = "WORLD", SemanticIndex = 1, Format = SharpDX.DXGI.Format.R32G32B32A32_Float, Slot = 1, AlignedByteOffset = InputElement.AppendAligned, Classification = InputClassification.PerInstanceData, InstanceDataStepRate = 1 }, new InputElement() { SemanticName = "WORLD", SemanticIndex = 2, Format = SharpDX.DXGI.Format.R32G32B32A32_Float, Slot = 1, AlignedByteOffset = InputElement.AppendAligned, Classification = InputClassification.PerInstanceData, InstanceDataStepRate = 1 }, new InputElement() { SemanticName = "WORLD", SemanticIndex = 3, Format = SharpDX.DXGI.Format.R32G32B32A32_Float, Slot = 1, AlignedByteOffset = InputElement.AppendAligned, Classification = InputClassification.PerInstanceData, InstanceDataStepRate = 1 }, new InputElement() { SemanticName = "TEXCOORD", SemanticIndex = 1, Format = SharpDX.DXGI.Format.R32G32B32_Float, Slot = 1, AlignedByteOffset = InputElement.AppendAligned, Classification = InputClassification.PerInstanceData, InstanceDataStepRate = 1 } }; Layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements); vertexShaderByteCode.Dispose(); pixelShaderByteCode.Dispose(); var samplerDesc = new SamplerStateDescription() { Filter = Filter.MinMagMipLinear, AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, MipLodBias = 0.0f, MaximumAnisotropy = 1, ComparisonFunction = Comparison.Always, BorderColor = new Color4(0, 0, 0, 0), MinimumLod = 0, MaximumLod = float.MaxValue }; SampleState = new SamplerState(device, samplerDesc); BufferDescription matrixBufferDesc = new BufferDescription() { Usage = ResourceUsage.Dynamic, SizeInBytes = SharpDX.Utilities.SizeOf <ViewProjectionMatrixBuffer>(), BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; ConstantMatrixBuffer = new Buffer(device, matrixBufferDesc); return(true); } catch (Exception ex) { return(false); } }
public RenderObject(Device device) { cb.vp = Matrix.Identity; cb.world = Matrix.Identity; // load and compile the vertex shader using (var bytecode = ShaderBytecode.CompileFromFile("simple.fx", "VShader", "vs_4_0", ShaderFlags.None, EffectFlags.None)) { vsInputSignature = ShaderSignature.GetInputSignature(bytecode); vertexShader = new VertexShader(device, bytecode); } // load and compile the pixel shader using (var bytecode = ShaderBytecode.CompileFromFile("simple.fx", "PShader", "ps_4_0", ShaderFlags.None, EffectFlags.None)) pixelShader = new PixelShader(device, bytecode); // Old school style. /* vertexSize = 24; vertexCount = 3; var vertexStream = new DataStream(vertexSize * vertexCount, true, true); vertexStream.Write(new Vector3(0.0f, 5.0f, 0.5f)); vertexStream.Write(new Vector3(1, 0, 0)); // color vertexStream.Write(new Vector3(5.0f, -5.0f, 0.5f)); vertexStream.Write(new Vector3(0, 1, 0)); // color vertexStream.Write(new Vector3(-5.0f, -5.0f, 0.5f)); vertexStream.Write(new Vector3(0, 0, 1)); // color vertexStream.Position = 0; */ // Use struct Vertex[] vertices = new Vertex[] { new Vertex() { pos = new Vector3(0.0f, 50.0f, 0.5f), col = new Vector3(1, 0, 0), uv = new Vector2(0, 0) }, new Vertex() { pos = new Vector3(50.0f, -50.0f, 0.5f), col = new Vector3(1, 1, 0), uv = new Vector2(1, 0) }, new Vertex() { pos = new Vector3(-50.0f, -50.0f, 0.5f), col = new Vector3(0, 1, 1), uv = new Vector2(1, 1) }, }; vertexSize = Marshal.SizeOf(typeof(Vertex)); vertexCount = vertices.Length; var vertexStream = new DataStream(vertexSize * vertexCount, true, true); foreach (var vertex in vertices) { vertexStream.Write(vertex); } vertexStream.Position = 0; // create the vertex layout and buffer var elements = new[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0), new InputElement("COLOR", 0, Format.R32G32B32_Float, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 0) }; vertexBufferLayout = new InputLayout(device, vsInputSignature, elements); vertexBuffer = new Buffer(device, vertexStream, vertexSize * vertexCount, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); vertexStream.Close(); // Setup Constant Buffers constantBuffer = new Buffer(device, Marshal.SizeOf(typeof(ConstantBuffer)), ResourceUsage.Dynamic, BindFlags.ConstantBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, 0); // http://asc-chalmers-project.googlecode.com/svn-history/r26/trunk/Source/AdvGraphicsProject/Program.cs // Try load a texture SamplerDescription samplerDescription = new SamplerDescription(); samplerDescription.AddressU = TextureAddressMode.Wrap; samplerDescription.AddressV = TextureAddressMode.Wrap; samplerDescription.AddressW = TextureAddressMode.Wrap; samplerDescription.Filter = Filter.MinPointMagMipLinear; samplerLinear = SamplerState.FromDescription(device, samplerDescription); texture = Texture2D.FromFile(device, "Data/cco.png"); textureView = new ShaderResourceView(device, texture); var desc = new BlendStateDescription() { AlphaToCoverageEnable = true, IndependentBlendEnable = true }; desc.RenderTargets[0].BlendEnable = false; desc.RenderTargets[0].BlendOperation = BlendOperation.Add; desc.RenderTargets[0].BlendOperationAlpha = BlendOperation.Add; desc.RenderTargets[0].RenderTargetWriteMask = ColorWriteMaskFlags.Alpha; desc.RenderTargets[0].SourceBlend = BlendOption.SourceAlpha; desc.RenderTargets[0].DestinationBlend = BlendOption.InverseSourceAlpha; desc.RenderTargets[0].DestinationBlendAlpha = BlendOption.InverseSourceAlpha; desc.RenderTargets[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; blendState = BlendState.FromDescription(device, desc); }
public HoverForm(Maze maze) : base("HoverRenderer") { this.ClientSize = new System.Drawing.Size(640, 480); var description = new SwapChainDescription() { BufferCount = 2, Usage = Usage.RenderTargetOutput, OutputHandle = this.Handle, IsWindowed = true, ModeDescription = new ModeDescription(0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm), SampleDescription = new SampleDescription(1, 0), Flags = SwapChainFlags.AllowModeSwitch, SwapEffect = SwapEffect.Discard }; Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.Debug, description, out device, out swapChain); // create a view of our render target, which is the backbuffer of the swap chain we just created using (var resource = Resource.FromSwapChain<Texture2D>(swapChain, 0)) { renderTarget = new RenderTargetView(device, resource); } // Create the depth buffer var depthBufferDescription = new Texture2DDescription { ArraySize = 1, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, Format = Format.D32_Float, Height = this.ClientSize.Height, Width = this.ClientSize.Width, MipLevels = 1, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default }; using (var depthBuffer = new Texture2D(device, depthBufferDescription)) { depthStencilView = new DepthStencilView(device, depthBuffer); depthStencilState = DepthStencilState.FromDescription(device, new DepthStencilStateDescription { IsDepthEnabled = true, IsStencilEnabled = false, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.LessEqual }); } // Setup wireframe mode rasteriserState = RasterizerState.FromDescription(device, new RasterizerStateDescription { CullMode = SlimDX.Direct3D11.CullMode.None, FillMode = SlimDX.Direct3D11.FillMode.Wireframe }); // setting a viewport is required if you want to actually see anything context = device.ImmediateContext; var viewport = new Viewport(0.0f, 0.0f, this.ClientSize.Width, this.ClientSize.Height); context.OutputMerger.SetTargets(depthStencilView, renderTarget); context.OutputMerger.DepthStencilState = depthStencilState; context.Rasterizer.State = rasteriserState; context.Rasterizer.SetViewports(viewport); // load and compile the vertex shader using (var bytecode = ShaderBytecode.CompileFromFile("shader.fx", "VShader", "vs_4_0", ShaderFlags.Debug, EffectFlags.None)) { inputSignature = ShaderSignature.GetInputSignature(bytecode); vertexShader = new VertexShader(device, bytecode); } // load and compile the pixel shader using (var bytecode = ShaderBytecode.CompileFromFile("shader.fx", "PShader", "ps_4_0", ShaderFlags.Debug, EffectFlags.None)) pixelShader = new PixelShader(device, bytecode); // create test vertex data, making sure to rewind the stream afterward vertices = CreateTriangleListFromMaze(maze); camera.Position = FindHumanStartPosition(maze); // create the vertex layout and buffer var elements = new[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0), new InputElement("COLOR", 0, Format.R32G32B32_Float, 0) }; layout = new InputLayout(device, inputSignature, elements); vertexBuffer = new Buffer(device, vertices, (int)vertices.Length, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); // configure the Input Assembler portion of the pipeline with the vertex data context.InputAssembler.InputLayout = layout; context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, 24, 0)); // set the shaders context.VertexShader.Set(vertexShader); context.PixelShader.Set(pixelShader); // crate the constant buffer constantBuffer = new Buffer(device, new BufferDescription { Usage = ResourceUsage.Default, SizeInBytes = Marshal.SizeOf(typeof(ConstantBuffer)), BindFlags = BindFlags.ConstantBuffer }); // prevent DXGI handling of alt+enter, which doesn't work properly with Winforms using (var factory = swapChain.GetParent<Factory>()) factory.SetWindowAssociation(this.Handle, WindowAssociationFlags.IgnoreAltEnter); // handle alt+enter ourselves this.KeyDown += (o, e) => { if (e.Alt && e.KeyCode == Keys.Enter) swapChain.IsFullScreen = !swapChain.IsFullScreen; }; // handle form size changes this.UserResized += (o, e) => { renderTarget.Dispose(); swapChain.ResizeBuffers(2, 0, 0, Format.R8G8B8A8_UNorm, SwapChainFlags.AllowModeSwitch); using (var resource = Resource.FromSwapChain<Texture2D>(swapChain, 0)) renderTarget = new RenderTargetView(device, resource); context.OutputMerger.SetTargets(renderTarget); }; this.KeyDown += new KeyEventHandler(HoverForm_KeyDown); }