Example #1
0
        protected override CodeFile CreateCodeFile(string id, string name)
        {
            var result = new CodeFileGlsl(id, name);

            result.ShaderFile = ShaderFile.CreateEmpty();
            return(result);
        }
Example #2
0
        public void CanDoSemanticAnalysisForVariableDeclaration()
        {
            var shaderText = @"in vec3 var1, var2;";

            ShaderFile file = ShaderFile.CreateFromText(shaderText);

            Assert.IsNotNull(file.SemanticContext);
            Assert.AreEqual(2, file.SemanticContext.Model.NodeSymbols.Count);
        }
Example #3
0
        public Program createProgram_Geometry(ShaderFile[] shader_pipeline)
        {
            ShaderFile[] new_shader_pipline = new ShaderFile[shader_pipeline.Length + 1];

            new_shader_pipline[0] = new ShaderFile(OpenTK.Graphics.OpenGL.ShaderType.VertexShader, EngineHelper.path_glsl_common_generic_geometry, null);
            shader_pipeline.CopyTo(new_shader_pipline, 1);

            return(createProgram(_glsl_version, new_shader_pipline));
        }
Example #4
0
        public void CanDoSemanticAnalysisForUnresolvedSymbol()
        {
            var shaderText = @"void main() { float a = unres; }";

            ShaderFile file = ShaderFile.CreateFromText(shaderText);

            Assert.IsNotNull(file.SemanticContext);
            Assert.AreEqual(2, file.SemanticContext.Model.NodeSymbols.Count);
        }
 public ShaderFile GetShader(string MeshName)
 {
     if (Shader.TryGetValue(new AssetType(MeshName, "shader"), out ShaderFile _shader))
     {
         return(_shader);
     }
     else
     {
         ShaderFile shader = LoadShader("Assets/Shaders/", MeshName);
         Shader.Add(new AssetType(MeshName, "shader"), shader);
         return(shader);
     }
 }
Example #6
0
        private int CompileShader(ShaderFile shaderData)
        {
            int vert_shader = GL.CreateShader(ShaderType.VertexShader);
            int frag_shader = GL.CreateShader(ShaderType.FragmentShader);

            GL.ShaderSource(vert_shader, shaderData._vertshader);
            GL.ShaderSource(frag_shader, shaderData._fragshader);

            GL.CompileShader(vert_shader);
            GL.CompileShader(frag_shader);

            int program = GL.CreateProgram();

            GL.AttachShader(program, vert_shader);
            GL.AttachShader(program, frag_shader);
            GL.LinkProgram(program);

            int status;

            GL.GetProgram(program, GetProgramParameterName.LinkStatus, out status);
            if (status == 0)
            {
                Debug.LogError(String.Format("Error linking program: {0}", GL.GetProgramInfoLog(program)));
                GL.DeleteProgram(program);
                return(0);
            }

            GL.DeleteShader(vert_shader);
            GL.DeleteShader(frag_shader);

            GL.GetProgram(program, GetProgramParameterName.ActiveUniforms, out var numberOfUniforms);

            for (var i = 0; i < numberOfUniforms; i++)
            {
                var key      = GL.GetActiveUniform(program, i, out _, out _);
                var location = GL.GetUniformLocation(program, key);
                _uniformLocations.Add(key, location);
            }

            GL.ValidateProgram(program);
            var glerror = GL.GetError();

            if (glerror != ErrorCode.NoError)
            {
                Debug.LogError("SHADER: Failed to create program : " + glerror);
                GL.DeleteProgram(program);
            }
            _shaderProgram = program;
            return(program);
        }
Example #7
0
        static public void Initialize(Device device)
        {
            if (m_Initialized)
            {
                throw new Exception("Already initialized!");
            }

            string[] filters = new[] { "*.hlsl", "*.fx" };

            foreach (string f in filters)
            {
                FileSystemWatcher w = new FileSystemWatcher();
                w.Filter              = f;
                w.Changed            += new FileSystemEventHandler(OnFileChanged);
                w.Renamed            += new RenamedEventHandler(OnFileChanged);
                w.NotifyFilter        = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName;
                w.Path                = Directory.GetCurrentDirectory() + "\\shaders";
                w.EnableRaisingEvents = true;
                m_Watchers.Add(w);
            }

            m_Initialized = true;
            m_Include     = new IncludeFX();

            CultureInfo ci = new CultureInfo("en-US", false);

            string[] filePaths = filters.SelectMany(f => Directory.GetFiles(Directory.GetCurrentDirectory() + "\\shaders", f)).ToArray();

            foreach (string path in filePaths)
            {
                string     fileName = GetFileNameFromPath(path);
                ShaderFile sf       = new ShaderFile();
                sf.m_DirectlyIncludedFiles = new List <String>();
                sf.m_FileName       = fileName;
                sf.m_FilePath       = path;
                sf.m_FlattenedFiles = new HashSet <String>();

                m_AllShaderFiles.Add(fileName, sf);
            }

            foreach (string path in filePaths)
            {
                ParseFile(path);
            }
            FlattenIncludes();
            FinalizeCompilationOnDevice(device);
        }
        public void ParseShaders()
        {
            var path  = Path.Combine(TestContext.CurrentContext.TestDirectory, "Files", "Shaders");
            var files = Directory.GetFiles(path, "*.vcs");

            foreach (var file in files)
            {
                var shader = new ShaderFile();

                using var sw = new StringWriter(CultureInfo.InvariantCulture);
                var originalOutput = Console.Out;
                Console.SetOut(sw);

                shader.Read(file);
                shader.PrintSummary();

                Console.SetOut(originalOutput);
            }
        }
        public static void CloneContent(CodeFileGlsl source, CodeFileGlsl target, IMetadataRecorder metadataRecorder)
        {
            if (source.ShaderFile != null)
            {
                CloningAstVisitor cloner = new CloningAstVisitor();
                if (target.ShaderFile == null)
                {
                    target.ShaderFile = ShaderFile.CreateEmpty(source.ShaderFile.SyntaxTree.Version);
                }

                target.ShaderFile.SyntaxTree.Version = source.ShaderFile.SyntaxTree.Version;
                foreach (var declaration in source.ShaderFile.SyntaxTree.Declarations)
                {
                    var targetNode = cloner.CloneNode(declaration);
                    target.ShaderFile.SyntaxTree.Declarations.Add(targetNode);
                    metadataRecorder.SymbolSourcingFrom(source.NodePathService, declaration, target.NodePathService, targetNode, new Dictionary <string, string>());
                }
            }
        }
Example #10
0
        protected override void Implementation(CodeFileCSharp input, Parameters inputParameters, IMetadataRecorder metadataRecorder, ILogger logger)
        {
            var outFile = this.Outputs[OutStreamName].CreateCodeFile($"{Path.GetFileNameWithoutExtension(input.Name)}.vertex.glsl") as CodeFileGlsl;

            outFile.ShaderFile = ShaderFile.CreateEmpty();
            outFile.ShaderFile.SyntaxTree.Version = ShaderVersion.GlslEs300;

            outFile.ShaderFile.SyntaxTree.Declarations.Add(new FunctionDeclaration()
            {
                Name = new Identifier()
                {
                    Name = "main"
                },
                TypeSpecifier = new TypeNameSpecifier()
                {
                    Identifier = new Identifier()
                    {
                        Name = "void"
                    }
                },
                Statement = new StatementCompound()
            });
        }
Example #11
0
 public Shader(ShaderFile fileShader)
 {
     _uniformLocations = new Dictionary <string, int>();
     CompileShader(fileShader);
 }
Example #12
0
        public static void Initialize(Device device)
        {
            if (m_Initialized)
            {
                throw new Exception("Already initialized!");
            }

            string[] filters = new[] { "*.hlsl", "*.fx" };

            foreach (string f in filters)
            {
                FileSystemWatcher w = new FileSystemWatcher();
                w.Filter = f;
                w.Changed += new FileSystemEventHandler(OnFileChanged);
                w.Renamed += new RenamedEventHandler(OnFileChanged);
                w.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName;
                w.Path = Directory.GetCurrentDirectory() + "\\shaders";
                w.EnableRaisingEvents = true;
                m_Watchers.Add(w);
            }

            m_Initialized = true;
            m_Include = new IncludeFX();

            CultureInfo ci = new CultureInfo("en-US", false);
            string[] filePaths = filters.SelectMany(f => Directory.GetFiles(Directory.GetCurrentDirectory() + "\\shaders", f)).ToArray();

            foreach (string path in filePaths)
            {
                string fileName = GetFileNameFromPath(path);
                ShaderFile sf = new ShaderFile();
                sf.m_DirectlyIncludedFiles = new List<String>();
                sf.m_FileName = fileName;
                sf.m_FilePath = path;
                sf.m_FlattenedFiles = new HashSet<String>();

                m_AllShaderFiles.Add(fileName, sf);
            }

            foreach (string path in filePaths)
            {
                ParseFile(path);
            }
            FlattenIncludes();
            FinalizeCompilationOnDevice(device);
        }
Example #13
0
 public Shader(ShaderFile fileShader, Texture tex0)
 {
     _uniformLocations = new Dictionary <string, int>();
     _Texture          = tex0;
     CompileShader(fileShader);
 }
 /// <summary>
 ///     Creates the shader with an vertex shader and custom fragment.
 /// </summary>
 /// <param name="vertex"></param>
 /// <param name="fragment"></param>
 public PostProcessShader(ShaderFile vertex, string fragment) : this(vertex, new ShaderFile(fragment))
 {
 }
 /// <summary>
 ///     Creates the shader with the default vertex shader and custom fragment shader.
 /// </summary>
 public PostProcessShader(ShaderFile fragment) : this(_normalVertex, fragment)
 {
 }
Example #16
0
        private static void ParseFile(string path)
        {
            List <ShaderWrapper> localShaders = new List <ShaderWrapper>();
            List <Tuple <string, int, int, int> > computeRegisters = new List <Tuple <String, int, int, int> >();
            ShaderFile sf = m_AllShaderFiles[GetFileNameFromPath(path)];

            sf.m_DirectlyIncludedFiles.Clear();
            sf.m_FlattenedFiles.Clear();

            using (StreamReader sr = new StreamReader(path))
            {
                while (!sr.EndOfStream)
                {
                    String line                   = sr.ReadLine();
                    Match  matchShaderRegex       = m_RegexWrapper.shaderRegex.Match(line);
                    Match  matchCbufferRegex      = m_RegexWrapper.cbufferRegex.Match(line);
                    Match  matchSamplerRegex      = m_RegexWrapper.samplerRegex.Match(line);
                    Match  matchNumThreadsRegex   = m_RegexWrapper.numThreadsRegex.Match(line);
                    Match  matchGlobalDefineRegex = m_RegexWrapper.globalDefineRegex.Match(line);
                    Match  matchIncludeRegex      = m_RegexWrapper.includeRegex.Match(line);

                    if (matchIncludeRegex.Success)
                    {
                        string includeName = matchIncludeRegex.Groups[1].Value;
                        sf.m_DirectlyIncludedFiles.Add(includeName);
                    }

                    if (matchGlobalDefineRegex.Success)
                    {
                        string defineName = matchGlobalDefineRegex.Groups[1].Value;
                        float  value      = Single.Parse(matchGlobalDefineRegex.Groups[2].Value, CultureInfo.InvariantCulture);

                        if (m_GlobalDefineValues.ContainsKey(defineName))
                        {
                            m_GlobalDefineValues[defineName] = value;
                        }
                        else
                        {
                            m_GlobalDefineValues.Add(defineName, value);
                        }
                    }

                    if (matchCbufferRegex.Success)
                    {
                        Match globalBufferMatch = m_RegexWrapper.globalBufferRegex.Match(line);
                        Match registerMatch     = m_RegexWrapper.registerRegex.Match(line);
                        if (!registerMatch.Success)
                        {
                            throw new Exception("Unable to find register for constant buffer");
                        }
                        int cbufferRegister = Int32.Parse(registerMatch.Groups[1].Value);

                        // We have a new cbuffer
                        string cbufferName = matchCbufferRegex.Groups[1].Value;

                        string cbufferText = "";
                        while (!sr.EndOfStream)
                        {
                            line = sr.ReadLine();
                            if (line.Contains('{'))
                            {
                                continue;
                            }

                            if (line.Contains('}'))
                            {
                                if (m_ConstantBuffers.ContainsKey(cbufferName))
                                {
                                    m_ConstantBuffers[cbufferName].ParseConstantBuffer(cbufferText, cbufferRegister, globalBufferMatch.Success);
                                }
                                else
                                {
                                    CustomConstantBufferDefinition myNewConstantBuffer =
                                        new CustomConstantBufferDefinition(
                                            cbufferName,
                                            cbufferText,
                                            cbufferRegister,
                                            globalBufferMatch.Success,
                                            path);

                                    m_ConstantBuffers.Add(cbufferName, myNewConstantBuffer);
                                }
                                break;
                            }

                            cbufferText += line.Trim() + "\n";
                        }

                        continue;
                    }

                    if (matchShaderRegex.Success)
                    {
                        // We have a new shader
                        string     shaderType    = matchShaderRegex.Groups[1].Value;
                        string     shaderName    = matchShaderRegex.Groups[2].Value;
                        string     shaderEntry   = matchShaderRegex.Groups[3].Value;
                        string     shaderDefines = matchShaderRegex.Groups[4].Value;
                        ShaderType type          = ShaderType.PixelShader;

                        switch (shaderType.ToLower())
                        {
                        case "pixel": type = ShaderType.PixelShader;
                            break;

                        case "vertex": type = ShaderType.VertexShader;
                            break;

                        case "compute": type = ShaderType.ComputeShader;
                            break;

                        case "geometry": type = ShaderType.GeometryShader;
                            break;
                        }

                        HashSet <string> defines = new HashSet <String>();

                        if (shaderDefines.Length > 0)
                        {
                            var tokens = shaderDefines.Split(new String[] { " ", "\t" }, StringSplitOptions.RemoveEmptyEntries);
                            for (int i = 1; i < tokens.Length; ++i)
                            {
                                defines.Add(tokens[i]);
                            }
                        }

                        ShaderWrapper newShader = new ShaderWrapper()
                        {
                            m_ShaderFile  = sf,
                            m_ShaderName  = shaderName,
                            m_ShaderType  = type,
                            m_ShaderEntry = shaderEntry,
                            m_Defines     = defines
                        };

                        localShaders.Add(newShader);
                    }

                    if (matchNumThreadsRegex.Success)
                    {
                        int threadsX = Int32.Parse(matchNumThreadsRegex.Groups[1].Value);
                        int threadsY = Int32.Parse(matchNumThreadsRegex.Groups[2].Value);
                        int threadsZ = Int32.Parse(matchNumThreadsRegex.Groups[3].Value);

                        string nextLine = sr.ReadLine();
                        var    tokens   = nextLine.Split(new String[] { " ", "(" }, StringSplitOptions.RemoveEmptyEntries);

                        computeRegisters.Add(new Tuple <String, int, int, int>(tokens[1], threadsX, threadsY, threadsZ));
                    }

                    if (matchSamplerRegex.Success)
                    {
                        string samplerType     = matchSamplerRegex.Groups[1].Value;
                        string samplerName     = matchSamplerRegex.Groups[2].Value;
                        string samplerRegister = matchSamplerRegex.Groups[3].Value;

                        m_SamplerStates[Int32.Parse(samplerRegister)] = SamplerStates.GetSamplerStateForName(samplerName);
                    }
                }
            }

            foreach (var shader in localShaders)
            {
                if (m_Shaders.ContainsKey(shader.m_ShaderName))
                {
                    m_Shaders[shader.m_ShaderName] = shader;
                }
                else
                {
                    m_Shaders.Add(shader.m_ShaderName, shader);
                }

                // CompileShader(shader);
                if (shader.m_ShaderCompilationTask != null)
                {
                    throw new Exception("Already compiling");
                }

                shader.m_ShaderCompilationTask = Task.Factory.StartNew(() => CompileShader(shader));
            }

            sf.m_FlattenedFiles.Add(sf.m_FileName);
            sf.m_FlattenedFiles.UnionWith(sf.m_DirectlyIncludedFiles);

            foreach (var registers in computeRegisters)
            {
                var shaderFit = localShaders.Where
                                    (shader => shader.m_ShaderEntry == registers.Item1);

                foreach (var fittingShader in shaderFit)
                {
                    fittingShader.m_ThreadsX = registers.Item2;
                    fittingShader.m_ThreadsY = registers.Item3;
                    fittingShader.m_ThreadsZ = registers.Item4;
                }
            }
        }
 /// <summary>
 ///     Creates the shader with an vertex shader and custom fragment.
 /// </summary>
 /// <param name="vertex"></param>
 /// <param name="fragment"></param>
 public PostProcessShader(ShaderFile vertex, ShaderFile fragment) : base(
         new ShaderFileCollection(vertex, fragment))
 {
     fragment.GLSLExtensions.Add(_fragExtensions);
 }
Example #18
0
 public Shader(ShaderFile fileShader)
 {
     _uniformLocations = new Dictionary <string, int>();
     _Texture          = new Texture(AssetsManager.instance.GetTexture("devTexture", "jpg"));
     CompileShader(fileShader);
 }