public void EnableRendering(Vector3 origin) { Vector3[] lineColors; int[] lineIndicies; bboxShader = ShaderCompiler.BuildDefaultShader(); bboxShader.Link(); lineColors = null; lineIndicies = null; lines(LineColor, 12, out lineColors, out lineIndicies); _geo = new Box.BoxGeometry(); _pack = new PackedGeometry(); _pack.Coloring = true; _pack._indices = _geo.Indices; _pack._coords = _geo.Vertices; _pack.color = X3DTypeConverters.Vec3ToFloatArray(lineColors); _pack._colorIndicies = lineIndicies; _pack.restartIndex = -1; _pack.Interleave(); _handle = _pack.CreateHandle(); renderingEnabled = _handle.HasGeometry; InitBoundaryPoints(origin); }
internal static void Build(Type type) { if (GetShaderSourceData(type) != null) { return; } Debug.LogFormat("Building material {0}", type.FullName); if (!type.IsSubclassOf(typeof(ScriptableMaterial))) { Debug.LogErrorFormat("Can not build material {0}", type.FullName); return; } ShaderSourceData shaderSourceData = new ShaderSourceData(); foreach (ShaderType shaderType in typeof(ShaderType).GetEnumValues()) { var methodReference = type.GetTypeDefinition().FindMethod(shaderType.ToString()); string source = new ShaderCompiler().Compile(methodReference, out var uniformList); var description = string.Format("// {0} generated from {1}\n", shaderType.ToString(), type.FullName); shaderSourceData.codes[shaderType] = description + source; if (uniformList != null) { foreach (var uniform in uniformList) { shaderSourceData.uniforms.Add(uniform); } } } SetShaderSourceData(type, shaderSourceData); }
public void IncludeTest() { var c = new ShaderCompiler(); var o = new CompileOptions(); o.Language = CompileOptions.InputLanguage.GLSL; o.IncludeCallback = IncludeHandler; string testShader = @"#version 450 #include ""common.glsl"" void main() {}"; var r = c.Preprocess(testShader, ShaderCompiler.Stage.Vertex, o, "testShader"); Assert.True(r.NumberOfErrors == 0, "[Vulkan] GLSL->PREPROCESS: Has error messages"); Assert.True(r.CompileStatus == CompileResult.Status.Success, "[Vulkan] GLSL->PREPROCESS: Compilation failed:" + r.ErrorMessage); var bc = r.GetBytes(); var preprocessed = Encoding.ASCII.GetString(bc); Assert.False(preprocessed.Contains("#include"), "[Vulkan] GLSL->PREPROCESS: Preprocessed shader still " + "contains include directive:" + preprocessed); }
public void PixelShaderEffect_ShaderHasMultipleConstantBuffers_Fails() { const string hlsl1 = @" cbuffer a { float4 x; }; cbuffer b { float4 y; }; float4 main() : SV_Target { return x + y; } "; const string hlsl2 = @" cbuffer a : register(b1) { float4 x; }; float4 main() : SV_Target { return x; } "; byte[] compiledShader1 = ShaderCompiler.CompileShader(hlsl1, "ps_4_0"); byte[] compiledShader2 = ShaderCompiler.CompileShader(hlsl2, "ps_4_0"); Utils.AssertThrowsException <ArgumentException>( () => new PixelShaderEffect(compiledShader1), "Unsupported constant buffer layout. There should be a single constant buffer bound to b0."); Utils.AssertThrowsException <ArgumentException>( () => new PixelShaderEffect(compiledShader2), "Unsupported constant buffer layout. There should be a single constant buffer bound to b0."); }
public void Compile(ShaderCompiler compiler, ShaderCompiler.Operand position, ShaderCompiler.Operand texCoord, ShaderCompiler.Operand[] attributes, ShaderCompiler.Operand borderDistance, ShaderCompiler.Operand[] constants, ShaderCompiler.Operand outputColour) { // The colour is saved in attribute. compiler.Mov(attributes[0], outputColour); }
public override ShaderCompiler.Operand[] Compile(ShaderCompiler compiler, ShaderCompiler.Operand[] operands, FixedShaderParameters parameters, ref DualShareContext shareContext) { return(new ShaderCompiler.Operand[] { compiler.CreateFixed(PinFormat.UInteger, Pin.NotArray, operands[0].ArraySize) }); }
void TryRoundTrip(string sourcePrefix, string compilerSource, byte[] expectedBytes) { var shaderSourceCode = sourcePrefix + compilerSource; var preprocessorDefines = new CompilerMacro[2]; preprocessorDefines[0].Name = "XBOX"; preprocessorDefines[1].Name = "XBOX360"; var includeHandler = new NopIncludeHandler(); var options = CompilerOptions.None; var compiledShader = ShaderCompiler.AssembleFromSource( shaderSourceCode, preprocessorDefines, includeHandler, options, Microsoft.Xna.Framework.TargetPlatform.Xbox360); var compiledBytes = compiledShader.GetShaderCode(); if (compiledBytes == null || compiledBytes.Length != expectedBytes.Length || !MemCmp(compiledBytes, expectedBytes)) { compilerUcodeTextBox.BackColor = System.Drawing.Color.Red; } else { compilerUcodeTextBox.BackColor = System.Drawing.SystemColors.Control; } }
public CodeTabView() { this.InitializeComponent(); this.shaderTextEditor = this.CreateTextEditor(); this.shaderTextEditor.Encoding = System.Text.Encoding.ASCII; //// _shaderTextEditor.TextChanged += new EventHandler(_shaderTextEditor_TextChanged); //// _shaderTextEditor.Document.TextContentChanged += new EventHandler(Document_TextContentChanged); this.shaderTextEditor.Document.DocumentChanged += this.DocumentDocumentChanged; using (var stream = typeof(CodeTabView).Assembly.GetManifestResourceStream("Shazzam.Resources.HLSLSyntax.xshd")) { if (stream != null) { using (var reader = new XmlTextReader(stream)) { var sm = new SyntaxMode("HLSL.xshd", "HLSL", ".fx"); this.hlslHs = HighlightingDefinitionParser.Parse(sm, reader); this.hlslHs.ResolveReferences(); // don't forget this! reader.Close(); } } } this.shaderTextEditor.Document.HighlightingStrategy = this.hlslHs; this.FormsHost.Child = this.shaderTextEditor; this.csTextEditor = this.CreateTextEditor(); this.FormsHostCs.Child = this.csTextEditor; this.compiler = new ShaderCompiler(); this.compiler.Reset(); this.OutputTextBox.DataContext = this.compiler; this.Loaded += this.CodeTabViewLoaded; }
public override ShaderCompiler.Operand[] Compile(ShaderCompiler compiler, ShaderCompiler.Operand[] operands, FixedShaderParameters parameters, ref DualShareContext shareContext) { // We prepare operands. ShaderCompiler.Operand[] ret = new ShaderCompiler.Operand[operands.Length]; for (int i = 0; i < ret.Length; i++) { ret[i] = compiler.CreateTemporary(operands[i].Format, operands[i].ArraySize); compiler.Mov(operands[i], ret[i]); } // We begin while. compiler.BeginWhile(); // We also fill dual share context. ShaderCompiler.Operand[] shared = new ShaderCompiler.Operand[ret.Length]; for (int i = 0; i < ret.Length; i++) { shared[i] = ret[i]; } shareContext = new DualShareContext(shared, parent.outputOperation); // We now go forward. return(ret); }
public CodeTabView() { InitializeComponent(); _shaderTextEditor = CreateTextEditor(); _shaderTextEditor.Encoding = System.Text.Encoding.ASCII; // _shaderTextEditor.TextChanged += new EventHandler(_shaderTextEditor_TextChanged); // _shaderTextEditor.Document.TextContentChanged += new EventHandler(Document_TextContentChanged); _shaderTextEditor.Document.DocumentChanged += new DocumentEventHandler(Document_DocumentChanged); using (var stream = typeof(CodeTabView).Assembly.GetManifestResourceStream("Shazzam.Resources.HLSLSyntax.xshd")) { using (var reader = new XmlTextReader(stream)) { var sm = new SyntaxMode("HLSL.xshd", "HLSL", ".fx"); _hlslHS = HighlightingDefinitionParser.Parse(sm, reader); _hlslHS.ResolveReferences(); // don't forget this! reader.Close(); } } _shaderTextEditor.Document.HighlightingStrategy = _hlslHS; this.formsHost.Child = _shaderTextEditor; _csTextEditor = CreateTextEditor(); this.formsHostCs.Child = _csTextEditor; _vbTextEditor = CreateTextEditor(); this.formsHostVb.Child = _vbTextEditor; _compiler = new ShaderCompiler(); _compiler.Reset(); outputTextBox.DataContext = _compiler; this.Loaded += CodeTabView_Loaded; }
public q3bsp() { //map = this; glshading = new ShaderCompiler(); //showLoadStatus(); // Map elements skybox_env = null; vertexBuffer = -1; indexBuffer = -1; indexCount = 0; lightmap = glshading.createSolidTexture(new Vector4(255, 255, 255, 255)); surfaces = null; shaders = new Dictionary <string, shader_gl>(); highlighted = null; // Sorted draw elements unshadedSurfaces = new List <shader_p>(); defaultSurfaces = new List <shader_p>(); modelSurfaces = new List <shader_p>(); effectSurfaces = new List <shader_p>(); // BSP Elements bspTree = null; // Effect elements startTime = (int)DateTime.Now.Ticks; bgMusic = null; }
public override ShaderCompiler.Operand[] Compile( ShaderCompiler compiler, ShaderCompiler.Operand[] operands, FixedShaderParameters parameters, ref DualShareContext shareContext) { // We resolve interface arrays. object[] interfaces = InterfaceHelper.ResolveInterfaceArray(inputs[1], parameters); Dictionary <ICompositeInterface, ShaderCompiler.Operand[]> constants = new Dictionary <ICompositeInterface, ShaderCompiler.Operand[]>(interfaces.Length); // We extract interface parameters and register them. for (int i = 0; i < interfaces.Length; i++) { ICompositeInterface provider = interfaces[i] as ICompositeInterface; // We now register it. constants.Add(provider, InterfaceHelper.RegisterInterfaceConstants(compiler, string.Format("Composite[{0}]", i), parameters, interfaces[i] as ICompositeInterface)); } // We only need to execute last element. ICompositeInterface pixelProvider = interfaces[interfaces.Length - 1] as ICompositeInterface; // We execute it. return(new ShaderCompiler.Operand[] { pixelProvider.GetPixel(compiler, operands[0], constants) }); }
public override ShaderCompiler.Operand[] Compile(ShaderCompiler compiler, ShaderCompiler.Operand[] operands, FixedShaderParameters parameters, ref DualShareContext shareContext) { return(new ShaderCompiler.Operand[] { compiler.Swizzle(operands[0], mask) }); }
// For matrix types that are accessed as component arrays (int or bool matrix + float matrices other than 3x2 and 4x4). void TestMatrixPropertyType <T>(string hlsl, T[] initialValue, T[] initialArray, T[] newValue, T[] newArray) { var effect = new PixelShaderEffect(ShaderCompiler.CompileShader(hlsl, "ps_4_0")); // Verify initial values. CollectionAssert.AreEqual(initialValue, (T[])effect.Properties["value_row"]); CollectionAssert.AreEqual(initialValue, (T[])effect.Properties["value_col"]); CollectionAssert.AreEqual(initialArray, (T[])effect.Properties["array_row"]); CollectionAssert.AreEqual(initialArray, (T[])effect.Properties["array_col"]); // Set new values. effect.Properties["value_row"] = newValue; effect.Properties["value_col"] = newValue; effect.Properties["array_row"] = newArray; effect.Properties["array_col"] = newArray; // Read back the modified values. CollectionAssert.AreEqual(newValue, (T[])effect.Properties["value_row"]); CollectionAssert.AreEqual(newValue, (T[])effect.Properties["value_col"]); CollectionAssert.AreEqual(newArray, (T[])effect.Properties["array_row"]); CollectionAssert.AreEqual(newArray, (T[])effect.Properties["array_col"]); }
public override ShaderCompiler.Operand[] Compile(ShaderCompiler compiler, ShaderCompiler.Operand[] operands, FixedShaderParameters parameters, ref DualShareContext shareContext) { // We prepare operands. ShaderCompiler.Operand[] ret = new ShaderCompiler.Operand[operands.Length]; for (int i = 1; i < ret.Length; i++) { ret[i] = compiler.CreateTemporary(operands[i].Format, operands[i].ArraySize); compiler.Mov(operands[i], ret[i]); } // At index 0, we have indexer, we initialize to 0. ret[0] = compiler.CreateTemporary(PinFormat.UInteger, Pin.NotArray); compiler.Mov(compiler.CreateFixed(PinFormat.UInteger, Pin.NotArray, (uint)0), ret[0]); // We begin while. compiler.BeginWhile(); // We exit if iteration count is exceeded. compiler.Break(compiler.Compare(CompareFunction.Less, ret[0], operands[0])); compiler.Add(ret[0], compiler.CreateFixed(PinFormat.UInteger, Pin.NotArray, (uint)1), ret[0]); // We also fill dual share context. ShaderCompiler.Operand[] shared = new ShaderCompiler.Operand[ret.Length - 1]; for (int i = 1; i < ret.Length; i++) { shared[i - 1] = ret[i]; } shareContext = new DualShareContext(shared, parent.outputOperation); // We now go forward. return(ret); }
public void PixelShaderEffect_FeatureLevelValidation() { const string hlsl = @" float4 main() : SV_Target { return 0; } "; var effect93 = new PixelShaderEffect(ShaderCompiler.CompileShader(hlsl, "ps_4_0_level_9_3")); var effect40 = new PixelShaderEffect(ShaderCompiler.CompileShader(hlsl, "ps_4_0")); using (var featureLevel93Device = DeviceCreator.CreateDevice(useFeatureLevel93: true)) using (var canvasDevice = CanvasDevice.CreateFromDirect3D11Device(featureLevel93Device)) { Assert.IsTrue(effect93.IsSupported(canvasDevice)); Assert.IsFalse(effect40.IsSupported(canvasDevice)); using (var renderTarget = new CanvasRenderTarget(canvasDevice, 1, 1, 96)) using (var drawingSession = renderTarget.CreateDrawingSession()) { drawingSession.DrawImage(effect93); Utils.AssertThrowsException <COMException>( () => drawingSession.DrawImage(effect40), "This shader requires a higher Direct3D feature level than is supported by the device. Check PixelShaderEffect.IsSupported before using it."); } } }
public ShaderCompiler.Operand[] Compile(ShaderCompiler compiler, ShaderCompiler.Operand[] operands, FixedShaderParameters parameters, ref DualShareContext shareContext) { // We checked if it is fixed on "constant" level (not named). if (!IsReferencable) { return(new ShaderCompiler.Operand[] { compiler.CreateFixed(output.Format, output.Size, value) }); } // We first check if this parameter is fixed. if (parameters.IsParameterFixed(name)) { // If it is fixed, we create a fixed constant. switch (output.Format) { case PinFormat.Texture1D: case PinFormat.Texture1DArray: case PinFormat.Texture2D: case PinFormat.Texture2DArray: case PinFormat.TextureCube: case PinFormat.Texture3D: case PinFormat.Sampler: case PinFormat.BufferTexture: case PinFormat.Interface: // We return "unresolved" parameter, it must be obtained directly. return(new ShaderCompiler.Operand[1] { null }); default: break; } return(new ShaderCompiler.Operand[] { compiler.CreateFixed(output.Format, output.Size, parameters[name]) }); } // We locate it. uint bufferID = 0; uint offset = 0; ConstantBufferLayout[] layouts = parameters.ConstantBuffers; foreach (ConstantBufferLayout layout in layouts) { if (layout.TryGetOffset(name, out offset)) { break; } bufferID++; } // We must emit code. return(new ShaderCompiler.Operand[] { compiler.CreateConstant(output.Format, output.Size, bufferID, offset) }); }
ShaderCompiler.Operand ICompositeInterface.GetPixel(ShaderCompiler compiler, ShaderCompiler.Operand absolutePosition, Dictionary <ICompositeInterface, ShaderCompiler.Operand[]> constants) { return(compiler.Add( source1.Interface.GetPixel(compiler, absolutePosition, constants), source2.Interface.GetPixel(compiler, absolutePosition, constants) )); }
public void PixelShaderEffect_PropertiesDictionary_Methods() { const string hlsl = @" float foo = 23; int i = 42; float4 main() : SV_Target { return foo * i; } "; var effect = new PixelShaderEffect(ShaderCompiler.CompileShader(hlsl, "ps_4_0")); // Test the various dictionary methods that are forwarded from our // Map<> implementation via PixelShaderEffectPropertyMapTraits. // Count. Assert.AreEqual(2, effect.Properties.Count); // HasKey. Assert.IsTrue(effect.Properties.ContainsKey("foo")); Assert.IsTrue(effect.Properties.ContainsKey("i")); Assert.IsFalse(effect.Properties.ContainsKey("bar")); Assert.IsFalse(effect.Properties.ContainsKey("I")); Assert.IsFalse(effect.Properties.ContainsKey(string.Empty)); // Lookup. Assert.AreEqual(23.0f, effect.Properties["foo"]); Assert.AreEqual(42, effect.Properties["i"]); object value; Utils.AssertThrowsException <ArgumentException>( () => value = effect.Properties["bar"], "Shader does not have a property named 'bar'."); Utils.AssertThrowsException <ArgumentException>( () => value = effect.Properties[string.Empty], "Shader does not have a property named ''."); // GetKeyValuePairs. var array = effect.Properties.ToArray(); Assert.AreEqual(2, array.Length); Assert.AreEqual("foo", array[0].Key); Assert.AreEqual(23.0f, array[0].Value); Assert.AreEqual("i", array[1].Key); Assert.AreEqual(42, array[1].Value); // Remove and Clear are not supported. Assert.ThrowsException <NotImplementedException>(() => effect.Properties.Remove("foo")); Assert.ThrowsException <NotImplementedException>(() => effect.Properties.Clear()); }
public void CompileFromFiles(Canvas canvas, string psName, string vsName) { this.psFileName = psName; this.vsFileName = vsName; ShaderProfile psProf = ShaderProfile.PS_1_1; switch (PSTarget) { case 2: psProf = ShaderProfile.PS_2_0; break; case 3: psProf = ShaderProfile.PS_3_0; break; } ShaderProfile vsProf = ShaderProfile.VS_1_1; switch (VSTarget) { case 2: vsProf = ShaderProfile.VS_2_0; break; case 3: vsProf = ShaderProfile.VS_3_0; break; } CompiledShader psShader = ShaderCompiler.CompileFromFile(psFileName, null, null, CompilerOptions.PackMatrixRowMajor, "main", psProf, TargetPlatform.Windows); Log.GetInstance().WriteLine(psShader.ErrorsAndWarnings); CompiledShader vsShader = ShaderCompiler.CompileFromFile(vsFileName, null, null, CompilerOptions.PackMatrixRowMajor, "main", vsProf, TargetPlatform.Windows); Log.GetInstance().WriteLine(vsShader.ErrorsAndWarnings); errorMessage = null; if (vsShader.ErrorsAndWarnings.Length > 1) { errorMessage = "Vertex Shader: " + vsShader.ErrorsAndWarnings; } if (psShader.ErrorsAndWarnings.Length > 1) { if (errorMessage == null) { errorMessage = "Pixel Shader: " + psShader.ErrorsAndWarnings; } else { errorMessage = errorMessage + "\n Pixel Shader: " + psShader.ErrorsAndWarnings; } } if (psShader.Success && vsShader.Success) { ps = new PixelShader(canvas.GetDevice(), psShader.GetShaderCode()); vs = new VertexShader(canvas.GetDevice(), vsShader.GetShaderCode()); compiled = true; } }
public void Compile(ShaderCompiler compiler, ShaderCompiler.Operand position, ShaderCompiler.Operand texCoord, ShaderCompiler.Operand[] attributes, ShaderCompiler.Operand borderDistance, ShaderCompiler.Operand[] constants, ShaderCompiler.Operand outputColour) { ShaderCompiler.Operand texture = constants[0]; ShaderCompiler.Operand sampler = constants[1]; // We perform a sampling. compiler.Sample(sampler, texture, texCoord, outputColour); }
public GlContextManager() { cancelTokenSource = new CancellationTokenSource(); glThread = new Thread(runGlThread); ShaderCompiler = new ShaderCompiler(); activeProgram = NullProgram; renderWidth = 1; renderHeight = 1; }
public void PixelShaderEffect_ShaderReflectionSetsCoordinateMappingDefaults() { const string hlsl = @" texture2D t0; sampler s0; texture2D t1; sampler s1; texture2D t2; sampler s2; texture2D t3; sampler s3; float4 main(float4 texcoord0 : TEXCOORD0, float4 texcoord1 : TEXCOORD1, float4 texcoord2 : TEXCOORD2, float4 texcoord3 : TEXCOORD3) : SV_Target { return t0.Sample(s0, texcoord0) + t1.Sample(s1, texcoord1) + t2.Sample(s2, texcoord2) + t3.Sample(s3, texcoord3); } export float4 ShaderLinkingFunction(float4 input0 : INPUT0, float4 texcoord1 : TEXCOORD1, float4 texcoord2 : TEXCOORD2, float4 input3 : INPUT3) { return input0 + t1.Sample(s1, texcoord1) + t2.Sample(s2, texcoord2) + input3; } "; // If we compile without support for shader linking, all mappings default to Unknown. var effect = new PixelShaderEffect(ShaderCompiler.CompileShader(hlsl, "ps_4_0")); Assert.AreEqual(SamplerCoordinateMapping.Unknown, effect.Source1Mapping); Assert.AreEqual(SamplerCoordinateMapping.Unknown, effect.Source2Mapping); Assert.AreEqual(SamplerCoordinateMapping.Unknown, effect.Source3Mapping); Assert.AreEqual(SamplerCoordinateMapping.Unknown, effect.Source4Mapping); // But if we include a shader linking function, reflection now has enough // info to detect which inputs are simple. These are set to OneToOne mapping. effect = new PixelShaderEffect(ShaderCompiler.CompileShaderAndEmbedLinkingFunction(hlsl)); Assert.AreEqual(SamplerCoordinateMapping.OneToOne, effect.Source1Mapping); Assert.AreEqual(SamplerCoordinateMapping.Unknown, effect.Source2Mapping); Assert.AreEqual(SamplerCoordinateMapping.Unknown, effect.Source3Mapping); Assert.AreEqual(SamplerCoordinateMapping.OneToOne, effect.Source4Mapping); }
ShaderCompiler.Operand ICompositeInterface.GetPixel(ShaderCompiler compiler, ShaderCompiler.Operand absolutePosition, Dictionary <ICompositeInterface, ShaderCompiler.Operand[]> constants) { ShaderCompiler.Operand[] inputs = constants[this]; return(compiler.Add( compiler.Mul(source1.Interface.GetPixel(compiler, absolutePosition, constants), inputs[0]), compiler.Mul(source2.Interface.GetPixel(compiler, absolutePosition, constants), inputs[1]) )); }
ShaderCompiler.Operand ICompositeInterface.GetPixel(ShaderCompiler compiler, ShaderCompiler.Operand absolutePosition, Dictionary <ICompositeInterface, ShaderCompiler.Operand[]> constants) { ShaderCompiler.Operand[] inputs = constants[this]; return(compiler.Sample(inputs[1], inputs[0], compiler.CreateFixed(PinFormat.Floatx2, Pin.NotArray, new Vector2f(0, 0)), compiler.Mul(absolutePosition, inputs[2]) )); }
ShaderCompiler.Operand ICompositeInterface.GetPixel(ShaderCompiler compiler, ShaderCompiler.Operand absolutePosition, Dictionary <ICompositeInterface, ShaderCompiler.Operand[]> constants) { ShaderCompiler.Operand[] inputs = constants[this]; ShaderCompiler.Operand offset = compiler.CreateFixed(PinFormat.Integerx2, Pin.NotArray, new Vector2i(0, 0)); return(compiler.Load(inputs[0], compiler.Expand( compiler.Convert(absolutePosition, PinFormat.Integerx2), PinFormat.Integerx3, ExpandType.AddZeros), offset)); }
private Veldrid.Shader LoadShader(ResourceFactory factory, string set, ShaderStages stage, string entryPoint) { string name = $"{set}-{stage.ToString().ToLower()}.{GetExtension(factory.BackendType)}"; var assetBytes = ReadEmbeddedAssetBytes(name); if (factory.BackendType == GraphicsBackend.Vulkan) { //Create a new compiler and new options var c = new ShaderCompiler(); var o = new CompileOptions(); //Set our compile options o.Language = CompileOptions.InputLanguage.GLSL; o.Optimization = CompileOptions.OptimizationLevel.Performance; //Compile the specified vertex shader and give it a name var r = c.Compile(Encoding.UTF8.GetString(assetBytes), stage == ShaderStages.Vertex ? ShaderCompiler.Stage.Vertex : ShaderCompiler.Stage.Fragment, o, stage == ShaderStages.Vertex ? "VS" : "PS"); //Check if we had any compilation errors if (r.CompileStatus != CompileResult.Status.Success) { //Write the error out System.Console.WriteLine(r.ErrorMessage); throw new Exception("Cannot compile Vulkan shader"); } //Get the produced SPV bytecode assetBytes = r.GetBytes(); } var hash = 0l; using (var sha = SHA256Managed.Create()) { using (var stream = new MemoryStream(assetBytes)) { var rawHash = sha.ComputeHash(stream); hash = BitConverter.ToInt64(rawHash, 0); } } if (stage == ShaderStages.Vertex) { _vertexHash = hash; } else { if (stage == ShaderStages.Fragment) { _fragmentHash = hash; } } return(factory.CreateShader(new ShaderDescription(stage, assetBytes, entryPoint))); }
private static Number4[] RenderScene(Device device) { const int width = 200; const int height = 100; // Create device and swap chain. var swapChainPresenter = new RawSwapChainPresenter(); var swapChain = device.CreateSwapChain( new SwapChainDescription(width, height), swapChainPresenter); var deviceContext = device.ImmediateContext; // Create RenderTargetView from the backbuffer. var backBuffer = Texture2D.FromSwapChain(swapChain, 0); var renderTargetView = device.CreateRenderTargetView(backBuffer); // Compile Vertex and Pixel shaders var vertexShaderByteCode = ShaderCompiler.CompileFromFile("Assets/MiniTri.fx", "VS", "vs_4_0"); var vertexShader = device.CreateVertexShader(vertexShaderByteCode); var pixelShaderByteCode = ShaderCompiler.CompileFromFile("Assets/MiniTri.fx", "PS", "ps_4_0"); var pixelShader = device.CreatePixelShader(pixelShaderByteCode); // Layout from VertexShader input signature var layout = device.CreateInputLayout( new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 0) }, vertexShaderByteCode); // Instantiate Vertex buffer from vertex data var vertices = device.CreateBuffer(new BufferDescription(BindFlags.VertexBuffer), 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) }); // Prepare all the stages deviceContext.InputAssembler.InputLayout = layout; deviceContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; deviceContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, 0, 32)); deviceContext.VertexShader.Shader = vertexShader; deviceContext.Rasterizer.SetViewports(new Viewport(0, 0, width, height, 0.0f, 1.0f)); deviceContext.PixelShader.Shader = pixelShader; deviceContext.OutputMerger.SetTargets(null, renderTargetView); deviceContext.ClearRenderTargetView(renderTargetView, Color4.Black); deviceContext.Draw(3, 0); swapChain.Present(); return(swapChainPresenter.Data); }
private int CreateVertexShader_() { // TODO: Does this spherical UV need to take camera into account? var vertexShaderLines = @"#version 130 uniform float u_sphericalUvEnabled; //struct TextureParams { // vec2 clamped; // vec2 mirrored; // // vec2 maxUv; //}; //uniform TextureParams textureParams0; //uniform TextureParams textureParams1; in vec3 in_position; in vec2 in_uv0; in vec2 in_uv1; in vec3 in_normal; in vec4 in_color; out vec3 v_position; out vec2 v_uv0; out vec2 v_uv1; out vec3 v_normal; out vec3 v_projectedNormal; out vec4 v_shade;" + '\n'; //vertexShaderLines += this.CreateUvMethods(); vertexShaderLines += @"void main() { gl_Position = gl_ModelViewProjectionMatrix * vec4(in_position, 1f); // in_position should already be in world space, since we // project the points w/ software matrices. v_position = in_position; v_uv0 = in_uv0; v_uv1 = in_uv1; //v_uv0 = calculateUv(in_uv0, textureParams0, projectedNormal); //v_uv1 = calculateUv(in_uv1, textureParams1, projectedNormal); v_normal = in_normal; v_projectedNormal = normalize(gl_ModelViewProjectionMatrix * vec4(in_normal, 0f)).xyz; v_shade = in_color; }"; return(ShaderCompiler.Compile(Gl.GL_VERTEX_SHADER, vertexShaderLines)); }
public override ShaderCompiler.Operand[] Compile(ShaderCompiler compiler, ShaderCompiler.Operand[] operands, FixedShaderParameters parameters, ref DualShareContext shareContext) { ShaderCompiler.Operand dst = compiler.CreateTemporary(operands[1].Format, operands[1].ArraySize); compiler.BeginIf(operands[0]); compiler.Mov(operands[1], dst); compiler.Else(); compiler.Mov(operands[2], dst); compiler.EndIf(); return(new ShaderCompiler.Operand[] { dst }); }
public void Load() { Vertex v; List<Vertex> geometry = new List<Vertex>(); v = new Vertex() { Position = new Vector3(0f, 0f, 0) + Position, TexCoord = new Vector2(0f, 1f) }; geometry.Add(v); v = new Vertex() { Position = new Vector3(this.Height, 0f, 0) + Position, TexCoord = new Vector2(1f, 1f) }; geometry.Add(v); v = new Vertex() { Position = new Vector3(this.Height, this.Height, 0) + Position, TexCoord = new Vector2(1f, 0f) }; geometry.Add(v); v = new Vertex() { Position = new Vector3(0f, this.Height, 0) + Position, TexCoord = new Vector2(0f, 0f) }; geometry.Add(v); //Bitmap bmpCross = ImageTexture.CreateBitmap(System.Drawing.Color.Black, 100, 100); //GraphicsUnit gunit = GraphicsUnit.Pixel; //var bounds = bmpCross.GetBounds(ref gunit); //this._image = ImageTexture.CreateTextureFromImage(bmpCross, bounds); //var @default = ShaderCompiler.BuildDefaultShader(); //@default.Link(); //@default.Use(); var @default = ShaderCompiler.ApplyShader(PerlinNoiseShader.vertexShaderSource, PerlinNoiseShader.fragmentShaderSource); @default.Link(); @default.Use(); CurrentShader = @default; Buffering.BufferShaderGeometry(geometry, out vbo, out NumVerticies); }