public Fragment LoadFragment(string fileName, InputElement[] inputElements) { Fragment result = new Fragment(); ShaderBytecode vertexShaderByteCode = null; ShaderBytecode pixelShaderByteCode = null; Assembly assembly = Assembly.GetExecutingAssembly(); using (Stream streamPS = assembly.GetManifestResourceStream("Profiler.DirectX.Shaders." + fileName + "_ps.fxo")) { pixelShaderByteCode = ShaderBytecode.FromStream(streamPS); } using (Stream streamVS = assembly.GetManifestResourceStream("Profiler.DirectX.Shaders." + fileName + "_vs.fxo")) { vertexShaderByteCode = ShaderBytecode.FromStream(streamVS); } result.VS = new VertexShader(RenderDevice, vertexShaderByteCode.Data); result.PS = new PixelShader(RenderDevice, pixelShaderByteCode.Data); result.Layout = new InputLayout(RenderDevice, vertexShaderByteCode, inputElements); vertexShaderByteCode.Dispose(); pixelShaderByteCode.Dispose(); return(result); }
public void RecompileShaders(string relPath) { string file = $"{ShaderDirectory}/{relPath}"; // Arrange. var relDir = Path.GetDirectoryName(relPath); Directory.CreateDirectory($"{OutputDir}/{relDir}"); var sourceName = GetSourceNameFromObject($"{ShaderDirectory}/{relPath}.o"); if (ShaderDirectory != OutputDir) { File.Copy($"{ShaderDirectory}/{relDir}/{sourceName}", $"{OutputDir}/{relDir}/{sourceName}", true); } if (ShaderDirectory != OutputDir) { File.Copy($"{ShaderDirectory}/{relPath}.asm", $"{OutputDir}/{relPath}.asm", true); } var asmFileText = string.Join(Environment.NewLine, File.ReadAllLines(file + ".asm").Select(x => x.Trim())); // Act. var binaryFileBytes = File.ReadAllBytes(file + ".o"); var shaderModel = ShaderReader.ReadShader(binaryFileBytes); var hlslWriter = new HlslWriter(shaderModel); string decompiledHLSL = ""; using (var stream = new MemoryStream()) { hlslWriter.Write(stream); stream.Position = 0; using (var reader = new StreamReader(stream, Encoding.UTF8)) { decompiledHLSL = reader.ReadToEnd(); } } File.WriteAllText($"{OutputDir}/{relPath}.d.hlsl", decompiledHLSL); using (var shaderBytecode = ShaderBytecode.FromStream(new MemoryStream(binaryFileBytes))) { var profile = shaderModel.Type == DX9Shader.ShaderType.Pixel ? $"ps_{shaderModel.MajorVersion}_{shaderModel.MinorVersion}" : $"vs_{shaderModel.MajorVersion}_{shaderModel.MinorVersion}"; var compiledShader = ShaderBytecode.Compile(decompiledHLSL, "main", profile); var disassembly = shaderBytecode.Disassemble(); var redisassembly = compiledShader.Bytecode.Disassemble(); File.WriteAllText($"{OutputDir}/{relPath}.d1.asm", disassembly); File.WriteAllText($"{OutputDir}/{relPath}.d2.asm", redisassembly); // Assert. Warn.If(disassembly, Is.EqualTo(redisassembly)); } // Assert. Assert.Pass(); }
public void SetPixelShader(byte[] code) { using (var result = ShaderBytecode.FromStream(new MemoryStream(code))) { if (mPixelShader != null) { mPixelShader.Dispose(); } mPixelShader = new PixelShader(mContext.Device, result); } }
public static byte[] LoadBytesFromResource <T>(string resourceName) { Type type = typeof(T); Assembly assembly = type.Assembly; using (Stream stream = assembly.GetManifestResourceStream(resourceName)) { if (stream == null) { throw new ArgumentException("missing resource: " + resourceName); } using (var bytecode = ShaderBytecode.FromStream(stream)) { return(bytecode.Data); } } }
public void SetPixelShader(byte[] code) { if (!mPixelShaderCache.ContainsKey(code)) { using (var result = ShaderBytecode.FromStream(new MemoryStream(code))) { if (mPixelShader != null) { mPixelShader.Dispose(); } mPixelShaderCache[code] = new PixelShader(mContext.Device, result.Data); } } mPixelShader = (PixelShader)mPixelShaderCache[code]; }
public void SetVertexShader(byte[] code) { var result = ShaderBytecode.FromStream(new MemoryStream(code)); if (mVertexShader != null) { mVertexShader.Dispose(); } if (VertexShaderCode != null) { VertexShaderCode.Dispose(); } VertexShaderCode = result; mVertexShader = new VertexShader(mContext.Device, VertexShaderCode.Data); }
public void RecompileTest(string relPath) { // Arrange. var file = $"{ShaderDirectory}/{relPath}"; var relDir = Path.GetDirectoryName(relPath); Directory.CreateDirectory($"{OutputDir}/{relDir}"); var sourceName = GetSourceNameFromObject($"{ShaderDirectory}/{relPath}.o"); if (ShaderDirectory != OutputDir) { File.Copy($"{ShaderDirectory}/{relDir}/{sourceName}", $"{OutputDir}/{relDir}/{sourceName}", true); } if (ShaderDirectory != OutputDir) { File.Copy($"{ShaderDirectory}/{relPath}.asm", $"{OutputDir}/{relPath}.asm", true); } var asmFileText = string.Join(Environment.NewLine, File.ReadAllLines(file + ".asm").Select(x => x.Trim())); // Act. var binaryFileBytes = File.ReadAllBytes(file + ".o"); using (var shaderBytecode = ShaderBytecode.FromStream(new MemoryStream(binaryFileBytes))) { var shaderVersion = shaderBytecode.GetVersion(); var shaderCode = DXDecompiler.Decompile(File.ReadAllBytes(file + ".o")); File.WriteAllText($"{OutputDir}/{relPath}.d.hlsl", shaderCode); var entryPoint = TestUtils.GetShaderEntryPoint(shaderVersion); var profile = TestUtils.GetShaderProfile(shaderVersion); var compiledShader = ShaderBytecode.Compile(shaderCode, entryPoint, profile); var disassembly = shaderBytecode.Disassemble(); var redisassembly = compiledShader.Bytecode.Disassemble(); File.WriteAllText($"{OutputDir}/{relPath}.d1.asm", disassembly); File.WriteAllText($"{OutputDir}/{relPath}.d2.asm", redisassembly); // Assert. Warn.If(disassembly, Is.EqualTo(redisassembly)); //Assert.Warn("Dissassembly does not match"); } }
public D3D10GammaCorrector(Device device, string gammaCorrectorResourcePath) { _cachedDevice = device ?? throw new ArgumentNullException(nameof(device)); using (var stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(gammaCorrectorResourcePath)) { if (null == stream) { throw new InvalidOperationException(string.Format("Compiled shader resource not found: {0}", gammaCorrectorResourcePath)); } using (var shaderBytes = ShaderBytecode.FromStream(stream)) { _effect = new Effect(device, shaderBytes); } } using (EffectTechnique technique = _effect.GetTechniqueByIndex(0)) { using (EffectPass pass = technique.GetPassByIndex(0)) { _vertexLayout = new InputLayout(device, pass.Description.Signature, new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 16, 0) }); _vertices = Buffer.Create(device, BindFlags.VertexBuffer, new[] { // 3D coordinates UV Texture coordinates -1.0f, 1.0f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, -1.0f, 0.5f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 0.5f, 1.0f, 0.0f, 1.0f, -1.0f, 1.0f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.5f, 1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 0.5f, 1.0f, 1.0f, 1.0f, }); } } }
public void ShaderReflectionMatchesDirect3DReflection(string relPath) { // Arrange. var file = $"{ShaderDirectory}/{relPath}"; var binaryFileBytes = File.ReadAllBytes(file + ".o"); // Act. if (binaryFileBytes[0] == 0x01 && binaryFileBytes[1] == 0x20 && binaryFileBytes[2] == 0xFF && binaryFileBytes[3] == 0xFE) { Effects11.CompareEffect(null, binaryFileBytes, Path.GetFileNameWithoutExtension(relPath)); return; } var container = BytecodeContainer.Parse(binaryFileBytes); if (container.Chunks.OfType <LibHeaderChunk>().Any()) { CompareLibrary(container, binaryFileBytes); return; } if (container.Chunks.OfType <EffectChunk>().Any()) { Effects10.CompareEffect(container, binaryFileBytes, Path.GetFileNameWithoutExtension(relPath)); return; } using (var shaderBytecode = ShaderBytecode.FromStream(new MemoryStream(binaryFileBytes))) using (var shaderReflection = new ShaderReflection(shaderBytecode)) { var desc = shaderReflection.Description; // Assert. Assert.AreEqual(shaderReflection.BitwiseInstructionCount, 0); // TODO Assert.AreEqual(shaderReflection.ConditionalMoveInstructionCount, container.Statistics.MovCInstructionCount); Assert.AreEqual(shaderReflection.ConversionInstructionCount, container.Statistics.ConversionInstructionCount); Assert.AreEqual((int)shaderReflection.GeometryShaderSInputPrimitive, (int)container.Statistics.InputPrimitive); Assert.AreEqual(shaderReflection.InterfaceSlotCount, container.ResourceDefinition.InterfaceSlotCount); Assert.AreEqual((bool)shaderReflection.IsSampleFrequencyShader, container.Statistics.IsSampleFrequencyShader); Assert.AreEqual(shaderReflection.MoveInstructionCount, container.Statistics.MovInstructionCount); var flags = ShaderRequiresFlags.None; if (container.Version.MajorVersion >= 5) { if (container.Sfi0 != null) { flags = (ShaderRequiresFlags)container.Sfi0.Flags; } else { var dcl = container.Shader.DeclarationTokens .OfType <GlobalFlagsDeclarationToken>() .FirstOrDefault(); var globals = dcl?.Flags ?? 0; flags = (ShaderRequiresFlags)Chunks.Sfi0.Sfi0Chunk.GlobalFlagsToRequireFlags(globals); } } Assert.AreEqual(shaderReflection.RequiresFlags, flags); int expectedSizeX, expectedSizeY, expectedSizeZ; uint actualSizeX, actualSizeY, actualSizeZ; shaderReflection.GetThreadGroupSize(out expectedSizeX, out expectedSizeY, out expectedSizeZ); container.Shader.GetThreadGroupSize(out actualSizeX, out actualSizeY, out actualSizeZ); Assert.AreEqual(expectedSizeX, actualSizeX); Assert.AreEqual(expectedSizeY, actualSizeY); Assert.AreEqual(expectedSizeZ, actualSizeZ); SharpDX.Direct3D.FeatureLevel featureLevel = 0; if (container.Chunks.OfType <Chunks.Aon9.Level9ShaderChunk>().Any()) { var level9Chunk = container.Chunks .OfType <Chunks.Aon9.Level9ShaderChunk>() .First(); featureLevel = level9Chunk.ShaderModel.MinorVersion == 1 ? SharpDX.Direct3D.FeatureLevel.Level_9_3 : SharpDX.Direct3D.FeatureLevel.Level_9_1; } else if (container.Version.MajorVersion == 4 && container.Version.MinorVersion == 0) { featureLevel = SharpDX.Direct3D.FeatureLevel.Level_10_0; } else if (container.Version.MajorVersion == 4 && container.Version.MinorVersion == 1) { featureLevel = SharpDX.Direct3D.FeatureLevel.Level_10_1; } else if (container.Version.MajorVersion == 5) { featureLevel = SharpDX.Direct3D.FeatureLevel.Level_11_0; if (flags.HasFlag(ShaderRequiresFlags.ShaderRequires64UnorderedAccessViews)) { featureLevel = SharpDX.Direct3D.FeatureLevel.Level_11_1; } } Assert.AreEqual(shaderReflection.MinFeatureLevel, featureLevel); // TODO Assert.AreEqual(desc.ArrayInstructionCount, container.Statistics.ArrayInstructionCount); Assert.AreEqual(desc.BarrierInstructions, container.Statistics.BarrierInstructions); Assert.AreEqual(desc.BoundResources, container.ResourceDefinition.ResourceBindings.Count); Assert.AreEqual(desc.ConstantBuffers, container.ResourceDefinition.ConstantBuffers.Count); Assert.AreEqual(desc.ControlPoints, container.Statistics.ControlPoints); Assert.AreEqual(desc.Creator, container.ResourceDefinition.Creator); Assert.AreEqual(desc.CutInstructionCount, container.Statistics.CutInstructionCount); Assert.AreEqual(desc.DeclarationCount, container.Statistics.DeclarationCount); Assert.AreEqual(desc.DefineCount, container.Statistics.DefineCount); Assert.AreEqual(desc.DynamicFlowControlCount, container.Statistics.DynamicFlowControlCount); Assert.AreEqual(desc.EmitInstructionCount, container.Statistics.EmitInstructionCount); Assert.AreEqual((int)desc.Flags, (int)container.ResourceDefinition.Flags); Assert.AreEqual(desc.FloatInstructionCount, container.Statistics.FloatInstructionCount); Assert.AreEqual(desc.GeometryShaderInstanceCount, container.Statistics.GeometryShaderInstanceCount); Assert.AreEqual(desc.GeometryShaderMaxOutputVertexCount, container.Statistics.GeometryShaderMaxOutputVertexCount); Assert.AreEqual((int)desc.GeometryShaderOutputTopology, (int)container.Statistics.GeometryShaderOutputTopology); Assert.AreEqual((int)desc.HullShaderOutputPrimitive, (int)container.Statistics.HullShaderOutputPrimitive); Assert.AreEqual((int)desc.HullShaderPartitioning, (int)container.Statistics.HullShaderPartitioning); Assert.AreEqual(desc.InputParameters, container.InputSignature.Parameters.Count); Assert.AreEqual((int)desc.InputPrimitive, (int)container.Statistics.InputPrimitive); Assert.AreEqual(desc.InstructionCount, container.Statistics.InstructionCount); Assert.AreEqual(desc.InterlockedInstructions, container.Statistics.InterlockedInstructions); Assert.AreEqual(desc.IntInstructionCount, container.Statistics.IntInstructionCount); Assert.AreEqual(desc.MacroInstructionCount, container.Statistics.MacroInstructionCount); Assert.AreEqual(desc.OutputParameters, container.OutputSignature.Parameters.Count); Assert.AreEqual(desc.PatchConstantParameters, (container.PatchConstantSignature != null) ? container.PatchConstantSignature.Parameters.Count : 0); Assert.AreEqual(desc.StaticFlowControlCount, container.Statistics.StaticFlowControlCount); Assert.AreEqual(desc.TempArrayCount, container.Statistics.TempArrayCount); Assert.AreEqual(desc.TempRegisterCount, container.Statistics.TempRegisterCount); Assert.AreEqual((int)desc.TessellatorDomain, (int)container.Statistics.TessellatorDomain); Assert.AreEqual(desc.TextureBiasInstructions, container.Statistics.TextureBiasInstructions); Assert.AreEqual(desc.TextureCompInstructions, container.Statistics.TextureCompInstructions); Assert.AreEqual(desc.TextureGradientInstructions, container.Statistics.TextureGradientInstructions); Assert.AreEqual(desc.TextureLoadInstructions, container.Statistics.TextureLoadInstructions); Assert.AreEqual(desc.TextureNormalInstructions, container.Statistics.TextureNormalInstructions); Assert.AreEqual(desc.TextureStoreInstructions, container.Statistics.TextureStoreInstructions); Assert.AreEqual(desc.UintInstructionCount, container.Statistics.UIntInstructionCount); var version = Chunks.Common.ShaderVersion.FromShexToken((uint)desc.Version); Assert.AreEqual(version.ToString(), container.ResourceDefinition.Target.ToString()); for (int i = 0; i < shaderReflection.Description.ConstantBuffers; i++) { CompareConstantBuffer(shaderReflection.GetConstantBuffer(i), container.ResourceDefinition.ConstantBuffers[i]); } for (int i = 0; i < shaderReflection.Description.BoundResources; i++) { CompareResourceBinding(shaderReflection.GetResourceBindingDescription(i), container.ResourceDefinition.ResourceBindings[i]); } for (int i = 0; i < shaderReflection.Description.InputParameters; i++) { CompareParameter(shaderReflection.GetInputParameterDescription(i), container.InputSignature.Parameters[i]); } for (int i = 0; i < shaderReflection.Description.OutputParameters; i++) { CompareParameter(shaderReflection.GetOutputParameterDescription(i), container.OutputSignature.Parameters[i]); } for (int i = 0; i < shaderReflection.Description.PatchConstantParameters; i++) { CompareParameter(shaderReflection.GetPatchConstantParameterDescription(i), container.PatchConstantSignature.Parameters[i]); } } }
/// <summary> /// Attaches the scene to the device specified in <paramref name="device"/>, and allocate resources specific to that device. /// </summary> /// <param name="device">The device to attach to.</param> /// <param name="hostSize">The size of the device.</param> public void Attach(Device device, PointD2D hostSize) { if (null != _cachedDevice) { throw new InvalidOperationException("Try to attach to device without deattach former device!"); } _cachedDevice = device ?? throw new ArgumentNullException(nameof(device)); _hostSize = hostSize; using (var stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("Altaxo.CompiledShaders.Effects.Lighting.cso")) { if (null == stream) { throw new InvalidOperationException(string.Format("Compiled shader resource not found: {0}", "Altaxo.CompiledShaders.Effects.Lighting.cso")); } using (var shaderBytes = ShaderBytecode.FromStream(stream)) { _lightingEffect = new Effect(device, shaderBytes); } } for (int i = 0; i < _layoutNames.Length; ++i) { string techniqueName = "Shade_" + _layoutNames[i]; var technique = _lightingEffect.GetTechniqueByName(techniqueName); if (null == technique || !technique.IsValid) { throw new InvalidProgramException(string.Format("Technique {0} was not found or is invalid", techniqueName)); } var pass = technique.GetPassByIndex(0); if (null == pass || !pass.IsValid) { throw new InvalidProgramException(string.Format("Pass[0] of technique {0} was not found or is invalid", techniqueName)); } InputLayout inputLayout; switch (i) { case 0: inputLayout = new InputLayout(device, pass.Description.Signature, new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0) }); break; case 1: inputLayout = new InputLayout(device, pass.Description.Signature, new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0) }); break; case 2: inputLayout = new InputLayout(device, pass.Description.Signature, new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 16, 0) }); break; case 3: inputLayout = new InputLayout(device, pass.Description.Signature, new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("NORMAL", 0, Format.R32G32B32A32_Float, 16, 0) }); break; case 4: inputLayout = new InputLayout(device, pass.Description.Signature, new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("NORMAL", 0, Format.R32G32B32A32_Float, 16, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 32, 0) }); break; case 5: inputLayout = new InputLayout(device, pass.Description.Signature, new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("NORMAL", 0, Format.R32G32B32A32_Float, 16, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 32, 0) }); break; case 6: inputLayout = new InputLayout(device, pass.Description.Signature, new[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 24, 0) }); break; default: throw new NotImplementedException(); } _renderLayouts[i] = new RenderLayout(technique, pass, inputLayout); } // Create Constant Buffers //_constantBuffer = new Buffer(device, Utilities.SizeOf<Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None); //_constantBufferForColor = new Buffer(device, Utilities.SizeOf<Vector4>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None); //_constantBufferForSixPlanes = new Buffer(device, Utilities.SizeOf<Vector4>() * 6, ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None); // View transformation variables _cbViewTransformation = _lightingEffect.GetConstantBufferByName("cbViewTransformation"); _evWorldViewProj = _cbViewTransformation.GetMemberByName("WorldViewProj").AsMatrix(); _evEyePosition = _cbViewTransformation.GetMemberByName("EyePosition").AsVector(); _cbMaterial = _lightingEffect.GetConstantBufferByName("cbMaterial"); _evMaterialDiffuseColor = _cbMaterial.GetMemberByName("MaterialDiffuseColor").AsVector(); _evMaterialSpecularExponent = _cbMaterial.GetMemberByName("MaterialSpecularExponent").AsScalar(); _evMaterialSpecularExponent.Set(4.0f); _evMaterialSpecularIntensity = _cbMaterial.GetMemberByName("MaterialSpecularIntensity").AsScalar(); _evMaterialSpecularIntensity.Set(1.0f); _evMaterialDiffuseIntensity = _cbMaterial.GetMemberByName("MaterialDiffuseIntensity").AsScalar(); _evMaterialMetalnessValue = _cbMaterial.GetMemberByName("MaterialMetalnessValue").AsScalar(); _evMaterialMetalnessValue.Set(0.75f); // Color providers BindTextureFor1DColorProviders(); // Clip plane variables _cbClipPlanes = _lightingEffect.GetConstantBufferByName("cbClipPlanes"); for (int i = 0; i < 6; ++i) { _evClipPlanes[i] = _cbClipPlanes.GetMemberByName("ClipPlane" + i.ToString(System.Globalization.CultureInfo.InvariantCulture)).AsVector(); } // Lighting variables _lighting = new Lighting(_lightingEffect); _lighting.SetDefaultLighting(); // -------------------- now draw the scene again with the new attached device -------------- if (null != _altaxoCamera && null != _altaxoLightSettings) { if (_altaxoDrawingGeometry != null) { BringDrawingIntoBuffers(_altaxoDrawingGeometry); } if (null != _altaxoMarkerGeometry) { BringMarkerGeometryIntoDeviceBuffers(_altaxoMarkerGeometry); } if (null != _altaxoOverlayGeometry) { BringOverlayGeometryIntoDeviceBuffers(_altaxoOverlayGeometry); } } }
public void ShaderReflectionMatchesDirect3DReflection(string file) { // Arrange. var binaryFileBytes = File.ReadAllBytes(file + ".o"); using (var shaderBytecode = ShaderBytecode.FromStream(new MemoryStream(binaryFileBytes))) using (var shaderReflection = new ShaderReflection(shaderBytecode)) { var desc = shaderReflection.Description; // Act. var container = BytecodeContainer.Parse(binaryFileBytes); // Assert. Assert.AreEqual(shaderReflection.BitwiseInstructionCount, 0); // TODO Assert.AreEqual(shaderReflection.ConditionalMoveInstructionCount, container.Statistics.MovCInstructionCount); Assert.AreEqual(shaderReflection.ConversionInstructionCount, container.Statistics.ConversionInstructionCount); Assert.AreEqual((int)shaderReflection.GeometryShaderSInputPrimitive, (int)container.Statistics.InputPrimitive); Assert.AreEqual(shaderReflection.InterfaceSlotCount, container.ResourceDefinition.InterfaceSlotCount); Assert.AreEqual((bool)shaderReflection.IsSampleFrequencyShader, container.Statistics.IsSampleFrequencyShader); Assert.AreEqual(shaderReflection.MoveInstructionCount, container.Statistics.MovInstructionCount); //Assert.AreEqual(shaderReflection.RequiresFlags, 0); // TODO int expectedSizeX, expectedSizeY, expectedSizeZ; uint actualSizeX, actualSizeY, actualSizeZ; shaderReflection.GetThreadGroupSize(out expectedSizeX, out expectedSizeY, out expectedSizeZ); container.Shader.GetThreadGroupSize(out actualSizeX, out actualSizeY, out actualSizeZ); Assert.AreEqual(expectedSizeX, actualSizeX); Assert.AreEqual(expectedSizeY, actualSizeY); Assert.AreEqual(expectedSizeZ, actualSizeZ); //Assert.AreEqual((int) shaderReflection.MinFeatureLevel, 0); // TODO Assert.AreEqual(desc.ArrayInstructionCount, container.Statistics.ArrayInstructionCount); Assert.AreEqual(desc.BarrierInstructions, container.Statistics.BarrierInstructions); Assert.AreEqual(desc.BoundResources, container.ResourceDefinition.ResourceBindings.Count); Assert.AreEqual(desc.ConstantBuffers, container.ResourceDefinition.ConstantBuffers.Count); Assert.AreEqual(desc.ControlPoints, container.Statistics.ControlPoints); Assert.AreEqual(desc.Creator, container.ResourceDefinition.Creator); Assert.AreEqual(desc.CutInstructionCount, container.Statistics.CutInstructionCount); Assert.AreEqual(desc.DeclarationCount, container.Statistics.DeclarationCount); Assert.AreEqual(desc.DefineCount, container.Statistics.DefineCount); Assert.AreEqual(desc.DynamicFlowControlCount, container.Statistics.DynamicFlowControlCount); Assert.AreEqual(desc.EmitInstructionCount, container.Statistics.EmitInstructionCount); Assert.AreEqual((int)desc.Flags, (int)container.ResourceDefinition.Flags); Assert.AreEqual(desc.FloatInstructionCount, container.Statistics.FloatInstructionCount); Assert.AreEqual(desc.GeometryShaderInstanceCount, container.Statistics.GeometryShaderInstanceCount); Assert.AreEqual(desc.GeometryShaderMaxOutputVertexCount, container.Statistics.GeometryShaderMaxOutputVertexCount); Assert.AreEqual((int)desc.GeometryShaderOutputTopology, (int)container.Statistics.GeometryShaderOutputTopology); Assert.AreEqual((int)desc.HullShaderOutputPrimitive, (int)container.Statistics.HullShaderOutputPrimitive); Assert.AreEqual((int)desc.HullShaderPartitioning, (int)container.Statistics.HullShaderPartitioning); Assert.AreEqual(desc.InputParameters, container.InputSignature.Parameters.Count); Assert.AreEqual((int)desc.InputPrimitive, (int)container.Statistics.InputPrimitive); Assert.AreEqual(desc.InstructionCount, container.Statistics.InstructionCount); Assert.AreEqual(desc.InterlockedInstructions, container.Statistics.InterlockedInstructions); Assert.AreEqual(desc.IntInstructionCount, container.Statistics.IntInstructionCount); Assert.AreEqual(desc.MacroInstructionCount, container.Statistics.MacroInstructionCount); Assert.AreEqual(desc.OutputParameters, container.OutputSignature.Parameters.Count); Assert.AreEqual(desc.PatchConstantParameters, (container.PatchConstantSignature != null) ? container.PatchConstantSignature.Parameters.Count : 0); Assert.AreEqual(desc.StaticFlowControlCount, container.Statistics.StaticFlowControlCount); Assert.AreEqual(desc.TempArrayCount, container.Statistics.TempArrayCount); Assert.AreEqual(desc.TempRegisterCount, container.Statistics.TempRegisterCount); Assert.AreEqual((int)desc.TessellatorDomain, (int)container.Statistics.TessellatorDomain); Assert.AreEqual(desc.TextureBiasInstructions, container.Statistics.TextureBiasInstructions); Assert.AreEqual(desc.TextureCompInstructions, container.Statistics.TextureCompInstructions); Assert.AreEqual(desc.TextureGradientInstructions, container.Statistics.TextureGradientInstructions); Assert.AreEqual(desc.TextureLoadInstructions, container.Statistics.TextureLoadInstructions); Assert.AreEqual(desc.TextureNormalInstructions, container.Statistics.TextureNormalInstructions); Assert.AreEqual(desc.TextureStoreInstructions, container.Statistics.TextureStoreInstructions); Assert.AreEqual(desc.UintInstructionCount, container.Statistics.UIntInstructionCount); //Assert.AreEqual(desc.Version, container.ResourceDefinition.Target); // TODO for (int i = 0; i < shaderReflection.Description.ConstantBuffers; i++) { CompareConstantBuffer(shaderReflection.GetConstantBuffer(i), container.ResourceDefinition.ConstantBuffers[i]); } for (int i = 0; i < shaderReflection.Description.BoundResources; i++) { CompareResourceBinding(shaderReflection.GetResourceBindingDescription(i), container.ResourceDefinition.ResourceBindings[i]); } for (int i = 0; i < shaderReflection.Description.InputParameters; i++) { CompareParameter(shaderReflection.GetInputParameterDescription(i), container.InputSignature.Parameters[i]); } for (int i = 0; i < shaderReflection.Description.OutputParameters; i++) { CompareParameter(shaderReflection.GetOutputParameterDescription(i), container.OutputSignature.Parameters[i]); } for (int i = 0; i < shaderReflection.Description.PatchConstantParameters; i++) { CompareParameter(shaderReflection.GetPatchConstantParameterDescription(i), container.PatchConstantSignature.Parameters[i]); } } }
public Renderer(IWin32Window form, RenderHost renderHost, ColorTextures colorTextures, TextureCache textureCache) { this.renderHost = renderHost; this.textureCache = textureCache; this.colorTextures = colorTextures; sceneElements = new List <SceneElement>(); // SwapChain description var desc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(100, 100, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = form.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; #if DEBUG var flag = DeviceCreationFlags.Debug; #else var flag = DeviceCreationFlags.None; #endif // Create Device and SwapChain Device.CreateWithSwapChain(DriverType.Hardware, flag | DeviceCreationFlags.BgraSupport, desc, out device, out swapChain); immediateContext = device.ImmediateContext; // Initialize helper classes colorTextures.Initialize(device); textureCache.Initialize(device); // Load the Vertex and Pixel shaders ShaderBytecode vertexShaderByteCode; using (var stream = new MemoryStream(Resources.vs)) { vertexShaderByteCode = ShaderBytecode.FromStream(stream); vertexShader = new VertexShader(device, vertexShaderByteCode); } immediateContext.VertexShader.Set(vertexShader); ShaderBytecode pixelShaderByteCode; using (var stream = new MemoryStream(Resources.ps)) { pixelShaderByteCode = ShaderBytecode.FromStream(stream); pixelShader = new PixelShader(device, pixelShaderByteCode); } immediateContext.PixelShader.Set(pixelShader); // Create the input layout for the COMPLEX vertex inputLayout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 16, 0) }); immediateContext.InputAssembler.InputLayout = inputLayout; immediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; // Release the bytecode vertexShaderByteCode.Dispose(); pixelShaderByteCode.Dispose(); // Create Constant Buffer vertexShaderPerFrameConstantBuffer = new Buffer(device, Utilities.SizeOf <Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); immediateContext.VertexShader.SetConstantBuffer(0, vertexShaderPerFrameConstantBuffer); // Create the default texture sampler textureSamplerWrap = new SamplerState(device, new SamplerStateDescription { Filter = Filter.MinMagMipPoint, AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, BorderColor = new Color4(0.0f, 0.0f, 0.0f, 0.0f), ComparisonFunction = Comparison.Always, MaximumAnisotropy = 16, MipLodBias = 0, MinimumLod = 0, MaximumLod = 3.402823466e+38f//D3D11_FLOAT32_MAX }); textureSamplerBorder = new SamplerState(device, new SamplerStateDescription { Filter = Filter.MinMagMipPoint, AddressU = TextureAddressMode.Border, AddressV = TextureAddressMode.Border, AddressW = TextureAddressMode.Border, BorderColor = new Color4(0.0f, 0.0f, 0.0f, 0.0f), ComparisonFunction = Comparison.Always, MaximumAnisotropy = 16, MipLodBias = 0, MinimumLod = 0, MaximumLod = 3.402823466e+38f//D3D11_FLOAT32_MAX }); // Prepare the camera Camera = new Camera(); // Create the depth stencil state depthStencilState = new DepthStencilState(device, new DepthStencilStateDescription { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.GreaterEqual, IsStencilEnabled = false, StencilReadMask = 0xff, //D3D11_DEFAULT_STENCIL_READ_MASK StencilWriteMask = 0xff, //D3D11_DEFAULT_STENCIL_WRITE_MASK FrontFace = new DepthStencilOperationDescription { DepthFailOperation = StencilOperation.Keep, FailOperation = StencilOperation.Keep, PassOperation = StencilOperation.Replace, Comparison = Comparison.Always }, BackFace = new DepthStencilOperationDescription { DepthFailOperation = StencilOperation.Keep, FailOperation = StencilOperation.Keep, PassOperation = StencilOperation.Replace, Comparison = Comparison.Always } }); // Create the raster state defaultRastState = new RasterizerState(device, new RasterizerStateDescription { IsAntialiasedLineEnabled = false, CullMode = CullMode.Back, DepthBias = 0, DepthBiasClamp = 0.0f, IsDepthClipEnabled = true, FillMode = FillMode.Solid, IsFrontCounterClockwise = false, IsMultisampleEnabled = true, IsScissorEnabled = false, SlopeScaledDepthBias = 0 }); wireframeOverlayRastState = new RasterizerState(device, new RasterizerStateDescription { IsAntialiasedLineEnabled = false, CullMode = CullMode.Back, DepthBias = (int)(Math.Pow(2.0, 23.0) / 1000), DepthBiasClamp = 0.001f, IsDepthClipEnabled = true, FillMode = FillMode.Wireframe, IsFrontCounterClockwise = false, IsMultisampleEnabled = true, IsScissorEnabled = false, SlopeScaledDepthBias = 0 }); // Create the blend state var blendDesc = new BlendStateDescription { AlphaToCoverageEnable = false, IndependentBlendEnable = false }; for (var i = 0; i < 8; ++i) { blendDesc.RenderTarget[i].IsBlendEnabled = true; blendDesc.RenderTarget[i].BlendOperation = BlendOperation.Add; blendDesc.RenderTarget[i].AlphaBlendOperation = BlendOperation.Add; blendDesc.RenderTarget[i].DestinationBlend = BlendOption.InverseSourceAlpha; blendDesc.RenderTarget[i].DestinationAlphaBlend = BlendOption.One; blendDesc.RenderTarget[i].RenderTargetWriteMask = ColorWriteMaskFlags.All; blendDesc.RenderTarget[i].SourceBlend = BlendOption.SourceAlpha; blendDesc.RenderTarget[i].SourceAlphaBlend = BlendOption.One; } blendState = new BlendState(device, blendDesc); // Prepare the stages that don't change per frame immediateContext.OutputMerger.SetDepthStencilState(depthStencilState); immediateContext.OutputMerger.SetBlendState(blendState); immediateContext.PixelShader.SetSampler(0, textureSamplerWrap); }
ShaderBytecode GetBytecode(string path) { using (Stream stream = ResourceLoader.FileSystem.OpenFile(FileSystemPath.Parse(path), FileAccess.Read)) return(ShaderBytecode.FromStream(stream)); }