protected override void ConstructFragmentShader(ShaderBuilder frag)
        {
            base.ConstructFragmentShader(frag);

            frag.AddUniform(ShaderVarType.Vec4, "body");
            frag.Logic = GetRenderFuncSource() + @"
                void main(void)
                {
                    float r = body.w;
                    vec3 cam = camera - body.xyz;
                    float len2 = dot(var_position, var_position);

                    if (len2 > 1) discard;

                    vec3 l = normalize(cam / r - var_position);

                    float b = dot(l, var_position);
                    float d = -b + sqrt(b * b - len2 + 1);

                    vec3 pos = (var_position + l * d) * r;
                    vec4 fin = proj * view * vec4(pos + body.xyz, 1);

                    gl_FragDepth = (fin.z / fin.w + 1) / 2;

                    out_colour = render(pos, cam);
                }
            ";
        }
Example #2
0
        public DynamicTexture(Context context, Format format, Vector4i size)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (format == null)
            {
                throw new ArgumentNullException("format");
            }
            this.format      = format;
            this.frameBuffer = new FrameBuffer();
            this.mainProgram = new Program();
            this.dimensions  = size;

            var builder = ShaderBuilder.CreateFromAssemblyResource("Glare.Graphics.Shaders.DynamicTexture.glsl");

            mainProgram.Shaders.AddRange(
                builder.VertexShader("Common", "Vertex"),
                builder.FragmentShader("Common", "Fragment"));
            mainProgram.MustLink();
            mainProgramAction = mainProgram.FragmentStage.Uniforms["Act"];
            mainProgram.Attributes["Position"].BindArray(new Vector2f[] {
                new Vector2f(-1, 1), new Vector2f(-1, -1),
                new Vector2f(1, 1), new Vector2f(1, -1)
            });
        }
        protected override void ConstructVertexShader(ShaderBuilder vert)
        {
            base.ConstructVertexShader(vert);

            vert.AddUniform(ShaderVarType.Vec4, "body");
            vert.AddAttribute(ShaderVarType.Vec2, "in_vertex");
            vert.AddVarying(ShaderVarType.Vec3, "var_position");
            vert.Logic = @"
                void main(void)
                {
                    float r = body.w;
                    vec3 cam = camera - body.xyz;
                    float dist = length(cam);
                    float hyp = sqrt(dist * dist - r * r);
                    float ang = atan(r / hyp);
                    float opp = hyp * sin(ang);
                    float dif = sqrt(r * r - opp * opp);

                    vec3 center = normalize(cam) * dif;
                    vec3 up = normalize(cross(cam, (view * vec4(0, 0, 1, 0)).xyz)) * opp;
                    vec3 right = normalize(cross(cam, up)) * opp;

                    var_position = vec3(center + in_vertex.x * right + in_vertex.y * up) / r;

                    gl_Position = proj * view * vec4(body.xyz + center + in_vertex.x * right + in_vertex.y * up, 1);
                }
            ";
        }
Example #4
0
        protected override void ConstructFragmentShader(ShaderBuilder frag)
        {
            base.ConstructFragmentShader(frag);

            frag.AddUniform(ShaderVarType.Sampler2DArray, "tiles");
            frag.AddUniform(ShaderVarType.Sampler2D, "bloodmap");
            frag.Logic = @"
                void main(void)
                {
                    vec4 clr = texture2DArray(tiles, var_tex);
                    if (clr.a < 1.0)
                        discard;

                    vec2 blood_tex = vec2(
                        floor(var_blood_tex.x) / world_size.x,
                        floor(var_blood_tex.y) / world_size.y
                    ) / 8.0;

                    float blood = floor(var_blood * 8.0) / 8.0;

                    if (blood > 0.0) {
                        blood = floor(blood * texture2D(bloodmap, blood_tex).a * 5.0) / 4.0;
                        clr = clr * (2.0 - blood) * 0.5 + vec4(0.2, 0.0, 0.0, 0.0) * blood;
                    }
   
                    out_colour = vec4(clr.rgb * var_shade, 1.0);
                }
            ";
        }
Example #5
0
        public PlanarTerrain(int blockSize)
            : base()
        {
            //if (terrainEffect == null) throw new ArgumentNullException("terrainEffect");

            BlockSize = blockSize;

            NarrowHeightTexture = new Texture2D(Formats.Vector2f, blockSize / 16, blockSize);
            SmallHeightTexture  = new Texture2D(Formats.Vector2f, blockSize / 16, blockSize / 16);
            SmallHeightData     = new float[(blockSize / 16) * (blockSize / 16) * 2];

            BlockBuffer = CreateBlockBuffer();

            Texture2D randomTexture = Texture.CreateRandom4nb(256, 256);

            var builder = ShaderBuilder.CreateFromAssemblyResource("Glare.Graphics.Shaders.Terrain.glsl");

            Program = new Program(
                builder.VertexShader("Common", "Vertex"),
                builder.FragmentShader("Common", "Fragment"));
            Program.Uniforms["terrainSize"].Set(blockSize);
            Program.Uniforms["randomTexture"].Set(randomTexture);

            UnitBuffer = GraphicsBuffer.Create(UnitVertices);
        }
Example #6
0
        protected override void ConstructVertexShader(ShaderBuilder vert)
        {
            base.ConstructVertexShader(vert);

            vert.AddUniform(ShaderVarType.Mat4, "mdl_matrix");
            vert.AddAttribute(ShaderVarType.Vec3, "in_position");
            vert.AddAttribute(ShaderVarType.Vec3, "in_texture");
            vert.AddAttribute(ShaderVarType.Vec3, "in_normal");
            vert.AddVarying(ShaderVarType.Float, "var_shade");
            vert.AddVarying(ShaderVarType.Vec3, "var_texture");
            vert.Logic = @"
                void main(void)
                {
                    var_texture = in_texture;

                    const vec3 sun_dir = normalize(vec3(1.0, -2.0, 0.0));

                    var_shade = 0.75 + abs(dot(sun_dir, (mdl_matrix * vec4(in_normal, 0.0)).xyz)) * 0.25;

                    vec3 world_pos = (mdl_matrix * vec4(in_position, 1.0)).xyz;

                    gl_Position = proj * view * vec4(
                        world_pos.x + world_offset.x,
                        world_pos.y,
                        world_pos.z + world_offset.y,
                        1.0
                    );
                }
            ";
        }
Example #7
0
        /// <summary>
        /// Initialise the editor.
        /// </summary>
        /// <param name="terrainEditorProgram">The terrain editor effect to clone. In the default content, this is stored as "Terracotta/TerrainEditorEffect".</param>
        /// <param name="terrain">The terrain to edit.</param>
        public TerrainEditor(PlanarTerrainBlock block)
        {
            this.terrainBlock = block;

            var builder = ShaderBuilder.CreateFromAssemblyResource("Glare.Graphics.Shaders.TerrainEditor.glsl");

            Program = new Program(
                builder.VertexShader("Common", "Vertex"),
                builder.FragmentShader("Common", "Fragment"));

            Program.Uniforms["TerrainSize"].Set(Terrain.BlockSize);
            Program.Uniforms["InverseTerrainSize"].Set(1.0 / Terrain.BlockSize);
            Rng = new Random();

            byte[] permutations = new byte[PerlinSize];
            for (int i = 0; i < permutations.Length; i++)
            {
                permutations[i] = (byte)i;
            }
            for (int i = 0; i < permutations.Length; i++)
            {
                Extensions.Swap(ref permutations[i], ref permutations[Rng.Next(permutations.Length)]);
            }

            CreatePerlinPermutationTexture(permutations);
            CreatePerlinGradientTexture(permutations);
            CreateTemporaryTexture();
            //LoadRandomPerlinTransform();
            PerlinTransform = Matrix4d.Identity;
        }
    public static void CreateShader()
    {
        ShaderBuilder window = GetWindow <ShaderBuilder>();

        window.CenterOnMainWin();
        window.Show();
    }
Example #9
0
        protected override void ConstructVertexShader(ShaderBuilder vert)
        {
            base.ConstructVertexShader(vert);

            vert.AddUniform(ShaderVarType.Mat4, "proj");
            vert.AddUniform(ShaderVarType.Mat4, "view");
            vert.AddUniform(ShaderVarType.Vec3, "camera");
        }
Example #10
0
        protected override void ConstructFragmentShader(ShaderBuilder frag)
        {
            base.ConstructVertexShader(frag);

            frag.AddUniform(ShaderVarType.Mat4, "proj");
            frag.AddUniform(ShaderVarType.Mat4, "view");
            frag.AddUniform(ShaderVarType.Vec3, "camera");
        }
Example #11
0
        static void ShowOutput(string shader, ShaderVersion version)
        {
            var workingDirectory = TestContext.CurrentContext.TestDirectory;

            var source = File.ReadAllText(Path.Combine(workingDirectory, shader));

            var output = ShaderBuilder.ShowOutput(source, version);

            File.WriteAllText(Path.Combine(workingDirectory, shader + "." + version + ".output"), output);
        }
Example #12
0
        protected override void ConstructFragmentShader(ShaderBuilder frag)
        {
            base.ConstructFragmentShader(frag);

            frag.AddUniform(ShaderVarType.Vec3, "sun");
            frag.AddUniform(ShaderVarType.Float, "time");
            frag.AddUniform(ShaderVarType.Vec4, "light_model");
            frag.AddUniform(ShaderVarType.Vec3, "colour");
            frag.AddUniform(ShaderVarType.SamplerCube, "skybox");
        }
Example #13
0
        protected override void ConstructFragmentShader(ShaderBuilder frag)
        {
            base.ConstructFragmentShader(frag);

            frag.AddUniform(ShaderVarType.Sampler2D, "frame");
            frag.Logic = @"
                void main(void)
                {
                    gl_FragColor = texture2D(frame, var_texcoord);
                }
            ";
        }
Example #14
0
        protected override void ConstructFragmentShader(ShaderBuilder frag)
        {
            base.ConstructFragmentShader(frag);

            frag.AddUniform(ShaderVarType.Vec4, "colour");
            frag.Logic = @"
                void main(void)
                {
                    out_colour = colour;
                }
            ";
        }
Example #15
0
        static void Compile(string shader, ShaderVersion version, bool optimize)
        {
            var workingDirectory = TestContext.CurrentContext.TestDirectory;

            var source = File.ReadAllText(Path.Combine(workingDirectory, shader));

            string output   = null;
            var    compiled = ShaderBuilder.BuildAndShowOutput(source, version, optimize, out output);

            File.WriteAllText(Path.Combine(workingDirectory, shader + "." + version + ".output"), output);
            File.WriteAllBytes(Path.Combine(workingDirectory, shader + "." + version + ".compiled"), compiled);
        }
Example #16
0
        protected override void ConstructFragmentShader(ShaderBuilder frag)
        {
            base.ConstructFragmentShader(frag);

            frag.AddUniform(ShaderVarType.Sampler2DArray, "ents");
            frag.Logic = @"
                void main(void)
                {
                    out_colour = texture2DArray(ents, var_texture);
                    if(out_colour.a < 0.5) discard;
                }
            ";
        }
Example #17
0
        protected override void ConstructVertexShader(ShaderBuilder vert)
        {
            base.ConstructVertexShader(vert);

            vert.AddAttribute(ShaderVarType.Vec2, "in_vertex");
            vert.AddVarying(ShaderVarType.Vec2, "var_texcoord");
            vert.Logic = @"
                void main(void)
                {
                    var_texcoord = vec2(in_vertex.x, 1 - in_vertex.y);
                    gl_Position = in_vertex * screen_resolution;
                }
            ";
        }
Example #18
0
        protected override void ConstructFragmentShader(ShaderBuilder frag)
        {
            base.ConstructFragmentShader(frag);

            frag.AddUniform(ShaderVarType.SamplerCube, "skybox");
            frag.AddUniform(ShaderVarType.Vec3, "sun");
            frag.AddUniform(ShaderVarType.Float, "time");
            frag.Logic = SunFragSource + @"
                void main(void)
                {
                    vec3 sky = textureCube(skybox, var_texcoord).rgb;
                    out_colour = vec4(sky + (vec3(1, 1, 1) - sky) * getSun(var_texcoord), 1);
                }
            ";
        }
Example #19
0
        protected override void ConstructVertexShader(ShaderBuilder vert)
        {
            base.ConstructVertexShader(vert);

            vert.AddAttribute(ShaderVarType.Vec3, "in_vertex");
            vert.AddVarying(ShaderVarType.Vec3, "var_texcoord");
            vert.Logic = @"
                void main(void)
                {
                    vec4 pos = proj * view * vec4(in_vertex, 0);

                    gl_Position = pos.xyww;
                    var_texcoord = in_vertex;
                }
            ";
        }
Example #20
0
        public static Shader CreateDefaultShader()
        {
            var sb = new ShaderBuilder(VertexDeclaration);

            var combinedMatrix = sb.AddUniform(CombinedMatrixUniformName, "mat4");
            var color          = sb.AddVarying("vec4");

            sb.VertexShader = new Sequence(
                new Assign(color, sb.VertexDeclaration.GetAttribute(AttributeUsage.Color)),
                new Assign(sb.GlPosition, () => $"{combinedMatrix.Ref} * vec4({sb.VertexDeclaration.GetAttribute(AttributeUsage.Position).Name}, 1)")
                );
            sb.FragmentShader = new Sequence(
                new Assign(sb.GlFragColor, () => $"{color.Ref}")
                );

            return(sb.Build());
        }
Example #21
0
        protected override void ConstructFragmentShader(ShaderBuilder frag)
        {
            base.ConstructFragmentShader(frag);

            frag.AddUniform(ShaderVarType.Sampler2D, "sprite");
            frag.Logic = @"
                void main(void)
                {
                    vec4 clr = texture2D(sprite, var_texture) * var_colour;

                    if (clr.a != 0.0) {
                        out_colour = clr.rgba;
                    } else {
                        discard;
                    }
                }
            ";
        }
Example #22
0
        protected override void ConstructFragmentShader(ShaderBuilder frag)
        {
            base.ConstructFragmentShader(frag);

            frag.AddUniform(ShaderVarType.Sampler2D, "sprite");
            frag.Logic = @"
                void main(void)
                {
                    vec4 clr = texture2D(sprite, var_texture) * var_colour;

                    if (clr.a != 0.0) {
                        out_colour = clr.rgba;
                    } else {
                        discard;
                    }
                }
            ";
        }
Example #23
0
        protected override void ConstructVertexShader(ShaderBuilder vert)
        {
            base.ConstructVertexShader(vert);

            vert.AddAttribute(ShaderVarType.Vec2, "in_position");
            vert.AddAttribute(ShaderVarType.Vec2, "in_texture");
            vert.AddAttribute(ShaderVarType.Vec4, "in_colour");
            vert.AddVarying(ShaderVarType.Vec2, "var_texture");
            vert.AddVarying(ShaderVarType.Vec4, "var_colour");
            vert.Logic = @"
                void main(void)
                {
                    var_texture = in_texture;
                    var_colour = in_colour;

                    gl_Position = in_position;
                }
            ";
        }
Example #24
0
        protected override void ConstructVertexShader(ShaderBuilder vert)
        {
            base.ConstructVertexShader(vert);

            vert.AddAttribute(ShaderVarType.Vec3, "in_vertex");
            vert.Logic = @"
                void main(void)
                {
                    const float yscale = 2.0 / sqrt(3.0);

                    gl_Position = proj * view * vec4(
                        in_vertex.x + world_offset.x,
                        in_vertex.y * yscale,
                        in_vertex.z + world_offset.y,
                        1.0
                    );
                }
            ";
        }
Example #25
0
        protected override void ConstructVertexShader(ShaderBuilder vert)
        {
            base.ConstructVertexShader(vert);

            vert.AddAttribute(ShaderVarType.Vec2, "in_position");
            vert.AddAttribute(ShaderVarType.Vec2, "in_texture");
            vert.AddAttribute(ShaderVarType.Vec4, "in_colour");
            vert.AddVarying(ShaderVarType.Vec2, "var_texture");
            vert.AddVarying(ShaderVarType.Vec4, "var_colour");
            vert.Logic = @"
                void main(void)
                {
                    var_texture = in_texture;
                    var_colour = in_colour;

                    gl_Position = in_position;
                }
            ";
        }
Example #26
0
        public UrielForm(UrielConfiguration configuration)
        {
            this.configuration = configuration;
            if (configuration.WorkflowMode != UrielWorkflowMode.MovieMode)
            {
                this.watcher = new ShaderFileWatcher(configuration.WatchDirectory);
                watcher.Run();
            }

            this.renderLoop   = new RenderLoop();
            this.builder      = new ShaderBuilder(ShaderZoo.BadShaderArguments());
            this.FrameTracker = new FrameTracker();
            this.ShaderBlobs  = new BindingList <ShaderBlob>();

            this.listener = new KeyPressListener();
            this.tks      = new TotalKeyState();
            this.ki       = new KeyInterpreter();

            InitializeComponent();
        }
Example #27
0
        public override void save(ProgressNotifier pn)
        {
            string       code       = editor.Text;
            FileStream   fileStream = File.Create(desc.FilePath);
            StreamWriter writer     = new StreamWriter(fileStream);

            writer.WriteLine(code);
            writer.Flush();
            writer.Close();
            fileStream.Close();

            lastText = editor.Text;


            ShaderBuilder sb = new ShaderBuilder();

            sb.buildShader(desc.FilePath, desc.FilePath.Replace(".hlsl", ".mgfx"));
            desc.ShouldBeLoadedAgain = true;

            base.save(pn);
        }
        public static Shader CreateDefaultShader()
        {
            var sb = new ShaderBuilder(VertexDeclaration);

            var combinedMatrix = sb.AddUniform(CombinedMatrixUniformName, "mat4");
            var texture        = sb.AddUniform(TextureUniformName, "sampler2D");

            var color        = sb.AddVarying("vec4");
            var textureCoord = sb.AddVarying("vec2");

            sb.VertexShader = new Sequence(
                new Assign(color, sb.VertexDeclaration.GetAttribute(AttributeUsage.Color)),
                new Assign(textureCoord, sb.VertexDeclaration.GetAttribute(AttributeUsage.DiffuseMapCoord)),
                new Assign(sb.GlPosition, () => $"{combinedMatrix.Ref} * vec4({sb.VertexDeclaration.GetAttribute(AttributeUsage.Position).Name}, 0, 1)")
                );
            sb.FragmentShader = new Sequence(
                new Assign(sb.GlFragColor, () => $"{color.Ref} * texture2D({texture.Ref}, {textureCoord.Ref})")
                );

            return(sb.Build());
        }
Example #29
0
        protected override void ConstructVertexShader(ShaderBuilder vert)
        {
            base.ConstructVertexShader(vert);

            vert.AddUniform(ShaderVarType.Vec2, "scale");
            vert.AddUniform(ShaderVarType.Vec3, "position");
            vert.AddUniform(ShaderVarType.Vec2, "size");
            vert.AddUniform(ShaderVarType.Float, "texture");
            vert.AddAttribute(ShaderVarType.Vec3, "in_vertex");
            vert.AddVarying(ShaderVarType.Vec3, "var_texture");
            vert.Logic = @"
                void main(void)
                {
                    switch(int(in_vertex.z))
                    {
                        case 0:
                            var_texture = vec3(0.0, 0.0, texture); break;
                        case 1:
                            var_texture = vec3(size.x, 0.0, texture); break;
                        case 2:
                            var_texture = vec3(0.0, size.y, texture); break;
                        case 3:
                            var_texture = vec3(size.x, size.y, texture); break;
                    }

                    const float yscale = 2.0 / sqrt(3.0);

                    gl_Position = proj * view * vec4(
                        position.x + world_offset.x,
                        (position.y + in_vertex.y * size.y) * yscale,
                        position.z + world_offset.y,
                        1.0
                    ) + vec4(in_vertex.x * scale.x * size.x, 0.0, 0.0, 0.0);
                }
            ";
        }
Example #30
0
        protected override void ConstructFragmentShader(ShaderBuilder frag)
        {
            base.ConstructFragmentShader(frag);

            frag.Logic = @"
                void main(void)
                {
                    const float FXAA_SPAN_MAX = 8.0;
                    const float FXAA_REDUCE_MUL = 1.0 / 8.0;
                    const float FXAA_REDUCE_MIN = 1.0 / 128.0;

                    vec2 rcpRes = vec2(1 / screen_resolution.x, 1 / screen_resolution.y);

                    vec3 rgbNW = texture2D(frame, var_texcoord + (vec2(-1.0, -1.0) * rcpRes)).xyz;
                    vec3 rgbNE = texture2D(frame, var_texcoord + (vec2( 1.0, -1.0) * rcpRes)).xyz;
                    vec3 rgbSW = texture2D(frame, var_texcoord + (vec2(-1.0,  1.0) * rcpRes)).xyz;
                    vec3 rgbSE = texture2D(frame, var_texcoord + (vec2( 1.0,  1.0) * rcpRes)).xyz;
                    vec3 rgbM = texture2D(frame, var_texcoord).xyz;

                    vec3 luma = vec3(0.299, 0.587, 0.114);

                    float lumaNW = dot(rgbNW, luma);
                    float lumaNE = dot(rgbNE, luma);
                    float lumaSW = dot(rgbSW, luma);
                    float lumaSE = dot(rgbSE, luma);
                    float lumaM  = dot(rgbM,  luma);
        
                    float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));
                    float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));
        
                    vec2 dir;
                    dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));
                    dir.y =  ((lumaNW + lumaSW) - (lumaNE + lumaSE));
        
                    float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) *
                        (0.25 * FXAA_REDUCE_MUL), FXAA_REDUCE_MIN);
          
                    float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);
        
                    dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),
                        max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),
                        dir * rcpDirMin)) * rcpRes;
                
                    vec3 rgbA = 0.5 * (
                        texture2D(frame, var_texcoord.xy + dir * (1.0 / 3.0 - 0.5)).xyz +
                        texture2D(frame, var_texcoord.xy + dir * (2.0 / 3.0 - 0.5)).xyz);

                    vec3 rgbB = rgbA * 0.5 + 0.25 * (
                        texture2D(frame, var_texcoord.xy + dir * -0.5).xyz +
                        texture2D(frame, var_texcoord.xy + dir *  0.5).xyz);

                    float lumaB = dot(rgbB, luma);

                    if ((lumaB < lumaMin) || (lumaB > lumaMax)) {
                        gl_FragColor = vec4(rgbA, 1);
                    } else {
                        gl_FragColor = vec4(rgbB, 1);
                    }
                }
            ";
        }
Example #31
0
        protected override void ConstructVertexShader(ShaderBuilder vert)
        {
            base.ConstructVertexShader(vert);

            vert.AddAttribute(ShaderVarType.Vec3, "in_vertex");
            vert.AddVarying(ShaderVarType.Vec3, "var_tex");
            vert.AddVarying(ShaderVarType.Float, "var_shade");
            vert.AddVarying(ShaderVarType.Vec2, "var_blood_tex");
            vert.AddVarying(ShaderVarType.Float, "var_blood");
            vert.Logic = @"
                void main(void)
                {
                    int dat = int(in_vertex.z);

                    int ix = int(in_vertex.x);
                    int iz = int(in_vertex.y);

                    float x = (ix & 0xfff) / 8.0;
                    float z = (iz & 0xfff) / 8.0;

                    var_tex = vec3(
                        float(dat & 0x1),
                        float((dat >> 1) & 0x3) / 2.0,
                        float((dat >> 8) & 0xffff)
                    );

                    const float yscale = 1.0 / sqrt(3.0);
                    vec2 normals[] = vec2[4]
                    (
                        vec2( 0.5,  0.0),
                        vec2( 0.0,  0.5),
                        vec2(-0.5,  0.0),
                        vec2( 0.0, -0.5)
                    );

                    float y = float((dat >> 4) & 0xf);
                    vec2 bloodadd;

                    if (y > 0.0f) {
                        int normalno = ((ix >> 12) & 0x1) | ((iz >> 11) & 0x2);
                        bloodadd = normals[normalno];
                    } else {
                        bloodadd = vec2(0.0, 0.0);
                    }

                    var_shade = 1.0 - 0.125 * float((dat >> 3) & 0x1);
                    var_blood = max(1.0 - y / 2.0, 0.0);

                    var_blood_tex = vec2(
                        x + bloodadd.x,
                        z + bloodadd.y
                    ) * 8.0;

                    gl_Position = proj * view * vec4(
                        x + world_offset.x,
                        y * yscale,
                        z + world_offset.y,
                        1.0
                    );
                }
            ";
        }
Example #32
0
        //private static void BuildAppConfigFile(string root_path, AppProject project)
        //{
        //    GameProperties props = new GameProperties()
        //    {
        //        Title = project.Title,
        //        FrameRate = project.FrameRate,
        //        CanvasWidth = project.CanvasWidth,
        //        CanvasHeight = project.CanvasHeight,
        //        Fullscreen = project.StartFullscreen,
        //        PreloadResourcePaks = project.PreloadPaks
        //    };

        //    File.WriteAllBytes(Path.Combine(root_path, "Config.json"),
        //        JsonSerializer.PrettyPrintByteArray(JsonSerializer.Serialize(props)));

        //}

        private static List <ResourcePak> BuildProjectResources(GameAssetsManifest manifest)
        {
            var resource_groups = manifest.Resources;

            var results = new List <ResourcePak>();

            foreach (var(groupKey, group) in resource_groups)
            {
                var pak = new ResourcePak(groupKey);

                Console.WriteLine($"Creating resource Pak: {pak.Name}");

                if (group.Images != null)
                {
                    foreach (var image_info in group.Images)
                    {
                        var pixmap_data = ImageBuilder.Build(image_info.Id, image_info.Path);

                        pak.Images.Add(image_info.Id, pixmap_data);

                        pak.TotalResourcesCount++;

                        Console.WriteLine($"Added Image: {pixmap_data.Id}");
                    }
                }

                if (group.Shaders != null)
                {
                    foreach (var shader_info in group.Shaders)
                    {
                        var shader_data = ShaderBuilder.Build(shader_info.Id, shader_info.VsPath, shader_info.FsPath);

                        pak.Shaders.Add(shader_info.Id, shader_data);

                        pak.TotalResourcesCount++;

                        Console.WriteLine($"Added Shader: {shader_data.Id}");
                    }
                }

                if (group.Fonts != null)
                {
                    foreach (var font_info in group.Fonts)
                    {
                        var build_params = new FontBuildParams()
                        {
                            Id          = font_info.Id,
                            LineSpacing = font_info.LineSpacing,
                            Spacing     = font_info.Spacing,
                            DefaultChar = font_info.DefaultChar,
                            Faces       = font_info.Faces.Select(f => new FontFace()
                            {
                                CharRanges = f.CharRanges.Select(CharRange.GetFromKey).ToList(),
                                Path       = f.Path,
                                Size       = f.Size,
                            }).ToList()
                        };

                        var font_data = FontBuilder.Build(build_params);

                        pak.Fonts.Add(font_info.Id, font_data);

                        pak.TotalResourcesCount++;

                        Console.WriteLine($"Added Font: {font_data.Id}");
                    }
                }

                if (group.Atlases != null)
                {
                    foreach (var atlas_info in group.Atlases)
                    {
                        var atlas_data = AtlasBuilder.Build(atlas_info.Id, atlas_info.Path, atlas_info.Regions);

                        pak.Atlases.Add(atlas_data.Id, atlas_data);

                        pak.TotalResourcesCount++;

                        Console.WriteLine($"Added Atlas: {atlas_data.Id}");
                    }
                }

                if (group.TextFiles != null)
                {
                    foreach (var text_file_info in group.TextFiles)
                    {
                        var text_file_data = TextBuilder.Build(text_file_info.Id, text_file_info.Path);
                        pak.TextFiles.Add(text_file_info.Id, text_file_data);

                        pak.TotalResourcesCount++;

                        Console.WriteLine($"Added TextFile: {text_file_data.Id}");
                    }
                }

                results.Add(pak);
                Console.WriteLine($"Built PAK with {pak.TotalResourcesCount} resources.");
            }

            return(results);
        }
Example #33
0
 protected virtual void ConstructFragmentShader(ShaderBuilder frag)
 {
     return;
 }
Example #34
0
        public static void GenerateShadersAndMaterials()
        {
            int                     blendModeCount = System.Enum.GetNames(typeof(ShapesBlendMode)).Length;
            const string            CORE_SUFFIX    = " Core";
            IEnumerable <TextAsset> shaderCores    = ShapesIO.LoadAllAssets <TextAsset>(ShapesIO.CoreShaderFolder);
            IEnumerable <string>    shaderNames    = shaderCores.Select(x => x.name.Substring(0, x.name.Length - CORE_SUFFIX.Length));

            // generate all shaders
            foreach (string name in shaderNames)
            {
                for (int i = 0; i < blendModeCount; i++)
                {
                    ShapesBlendMode blendMode      = (ShapesBlendMode)i;
                    string          path           = $"{ShapesIO.GeneratedShadersFolder}/{name} {blendMode}.shader";
                    string          shaderContents = new ShaderBuilder(name, blendMode).shader;
                    File.WriteAllText(path, shaderContents);
                }
            }

            // reimport all assets to load newly generated shaders
            AssetDatabase.Refresh(ImportAssetOptions.Default);

            // generate all materials
            foreach (string name in shaderNames)
            {
                for (int i = 0; i < blendModeCount; i++)
                {
                    ShapesBlendMode blendMode         = (ShapesBlendMode)i;
                    string          nameWithBlendMode = ShapesMaterials.GetMaterialName(name, blendMode.ToString());
                    Shader          shader            = Shader.Find($"Shapes/{nameWithBlendMode}");
                    if (shader == null)
                    {
                        Debug.LogError("missing shader " + $"Shapes/{nameWithBlendMode}");
                        continue;
                    }


                    if (ShaderBuilder.shaderKeywords.ContainsKey(name))
                    {
                        // create all permutations
                        MultiCompile[] multis = ShaderBuilder.shaderKeywords[name];
                        List <string>  keywordPermutations = new List <string>();
                        foreach (IEnumerable <string> perm in GetPermutations(multis.Select(m => m.Enumerate())))
                        {
                            IEnumerable <string> validKeywords = perm.Where(p => string.IsNullOrEmpty(p) == false);
                            string kws = $" [{string.Join( "][", validKeywords )}]";
                            if (kws.Contains("[]"))                                // this means it has no permutations
                            {
                                kws = "";
                            }
                            TryCreateMaterial(nameWithBlendMode + kws, validKeywords);
                        }
                    }
                    else
                    {
                        TryCreateMaterial(nameWithBlendMode);
                    }

                    Material TryCreateMaterial(string fullMaterialName, IEnumerable <string> keywords = null)
                    {
                        string   savePath = $"{ShapesIO.GeneratedMaterialsFolder}/{fullMaterialName}.mat";
                        Material mat      = AssetDatabase.LoadAssetAtPath <Material>(savePath);

                        void TrySetKeywords()
                        {
                            if (keywords != null)
                            {
                                foreach (string keyword in keywords)
                                {
                                    mat.EnableKeyword(keyword);
                                }
                            }
                        }

                        if (mat != null)
                        {
                            EditorUtility.SetDirty(mat);
                            mat.hideFlags = HideFlags.HideInInspector;
                            TrySetKeywords();
                        }
                        else
                        {
                            Debug.Log("creating material " + savePath);
                            mat = new Material(shader)
                            {
                                enableInstancing = true, hideFlags = HideFlags.HideInInspector
                            };
                            TrySetKeywords();
                            AssetDatabase.CreateAsset(mat, savePath);
                        }

                        return(mat);
                    }
                }
            }

            AssetDatabase.Refresh(ImportAssetOptions.Default);
        }
Example #35
0
        //private static void BuildAppConfigFile(string root_path, AppProject project)
        //{
        //    GameProperties props = new GameProperties()
        //    {
        //        Title = project.Title,
        //        FrameRate = project.FrameRate,
        //        CanvasWidth = project.CanvasWidth,
        //        CanvasHeight = project.CanvasHeight,
        //        Fullscreen = project.StartFullscreen,
        //        PreloadResourcePaks = project.PreloadPaks
        //    };

        //    File.WriteAllBytes(Path.Combine(root_path, "Config.json"),
        //        JsonSerializer.PrettyPrintByteArray(JsonSerializer.Serialize(props)));

        //}

        private static List <ResourcePak> BuildProjectResources(GameAssetsManifest manifest)
        {
            var resource_groups = manifest.Resources;

            var results = new List <ResourcePak>();

            foreach (var resource_group in resource_groups)
            {
                var pak = new ResourcePak(resource_group.Key);

                Console.WriteLine($"Creating resource Pak: {pak.Name}");

                if (resource_group.Value.Images != null)
                {
                    foreach (var image_info in resource_group.Value.Images)
                    {
                        var pixmap_data = ImageBuilder.Build(image_info.Id, image_info.Path);

                        pak.Images.Add(image_info.Id, pixmap_data);

                        pak.TotalResourcesCount++;

                        Console.WriteLine($"Added Image: {pixmap_data.Id}");
                    }
                }

                if (resource_group.Value.Shaders != null)
                {
                    foreach (var shader_info in resource_group.Value.Shaders)
                    {
                        var shader_data = ShaderBuilder.Build(shader_info.Id, shader_info.VsPath, shader_info.FsPath);

                        pak.Shaders.Add(shader_info.Id, shader_data);

                        pak.TotalResourcesCount++;

                        Console.WriteLine($"Added Shader: {shader_data.Id}");
                    }
                }

                if (resource_group.Value.Fonts != null)
                {
                    foreach (var font_info in resource_group.Value.Fonts)
                    {
                        var build_params = new FontBuildParams()
                        {
                            Id             = font_info.Id,
                            Path           = font_info.Path,
                            Size           = font_info.Size,
                            CharRangeLevel = font_info.CharRangeLevel,
                            PaddingLeft    = font_info.Padding != null ? font_info.Padding[0] : 0,
                            PaddingRight   = font_info.Padding != null ? font_info.Padding[1] : 0,
                            PaddingUp      = font_info.Padding != null ? font_info.Padding[2] : 0,
                            PaddingDown    = font_info.Padding != null ? font_info.Padding[3] : 0,
                            DropShadow     = font_info.DropShadow,
                            ShadowOffsetX  = font_info.ShadowOffsetX,
                            ShadowOffsetY  = font_info.ShadowOffsetY,
                            ShadowColor    = font_info.ShadowColor != null?Color.FromHex(font_info.ShadowColor) : Color.Black
                        };

                        var font_data = FontBuilder.Build(build_params);

                        pak.Fonts.Add(font_info.Id, font_data);

                        pak.TotalResourcesCount++;

                        Console.WriteLine($"Added Font: {font_data.Id}");
                    }
                }

                if (resource_group.Value.Atlases != null)
                {
                    foreach (var atlas_info in resource_group.Value.Atlases)
                    {
                        var atlas_data = AtlasBuilder.Build(atlas_info.Id, atlas_info.Path, atlas_info.Regions);

                        pak.Atlases.Add(atlas_data.Id, atlas_data);

                        pak.TotalResourcesCount++;

                        Console.WriteLine($"Added Atlas: {atlas_data.Id}");
                    }
                }

                if (resource_group.Value.TextFiles != null)
                {
                    foreach (var text_file_info in resource_group.Value.TextFiles)
                    {
                        var text_file_data = TextBuilder.Build(text_file_info.Id, text_file_info.Path);
                        pak.TextFiles.Add(text_file_info.Id, text_file_data);

                        pak.TotalResourcesCount++;

                        Console.WriteLine($"Added TextFile: {text_file_data.Id}");
                    }
                }

                results.Add(pak);
                Console.WriteLine($"Built PAK with {pak.TotalResourcesCount} resources.");
            }

            return(results);
        }
Example #36
0
        private void Create()
        {
            Program = GL.CreateProgram();

            int vert = GL.CreateShader(ShaderType.VertexShader);
            int frag = GL.CreateShader(ShaderType.FragmentShader);

            var vertBuilder = new ShaderBuilder(ShaderType.VertexShader, Flat);

            ConstructVertexShader(vertBuilder);

            var fragBuilder = new ShaderBuilder(ShaderType.FragmentShader, Flat, vertBuilder);

            ConstructFragmentShader(fragBuilder);

            GL.ShaderSource(vert, vertBuilder.Generate());
            GL.ShaderSource(frag, fragBuilder.Generate());

            GL.CompileShader(vert);
            GL.CompileShader(frag);

            String log;

            Trace.WriteLine(GetType().FullName);
            if ((log = GL.GetShaderInfoLog(vert).Trim()).Length > 0)
            {
                Trace.WriteLine(log);
            }
            if ((log = GL.GetShaderInfoLog(frag).Trim()).Length > 0)
            {
                Trace.WriteLine(log);
            }

            GL.AttachShader(Program, vert);
            GL.AttachShader(Program, frag);

            GL.LinkProgram(Program);

            if ((log = GL.GetProgramInfoLog(Program).Trim()).Length > 0)
            {
                Trace.WriteLine(log);
            }
            Trace.WriteLine("----------------");
            Use();

            if (Tools.GL3)
            {
                GL.BindFragDataLocation(Program, 0, "out_colour");
            }

            foreach (var uniform in vertBuilder.Uniforms.Union(fragBuilder.Uniforms))
            {
                switch (uniform.Value)
                {
                case ShaderVarType.Sampler2D:
                case ShaderVarType.Sampler2DArray:
                case ShaderVarType.SamplerCube:
                    AddTexture(uniform.Key);
                    break;

                default:
                    AddUniform(uniform.Key);
                    break;
                }
            }

            OnCreate();

            Tools.ErrorCheck("create");
        }
Example #37
0
 public OrbitCamera(ShaderBuilder shaderFactory, float startScale = 0.5f)
 {
     this._shaderFactory = shaderFactory;
     this.Scale          = startScale;
 }
Example #38
0
        public static vertex_shader_src_t buildVertexShader(shader_t stageShader, stage_t stage)
        {
            ShaderBuilder shader;
            Dictionary <string, string> attribs, varyings, uniforms;
            List <string> statements;

            shader     = new ShaderBuilder();
            attribs    = new Dictionary <string, string>();
            varyings   = new Dictionary <string, string>();
            uniforms   = new Dictionary <string, string>();
            statements = new List <string>();

            shader.addAttribs("position", "vec3");
            shader.addAttribs("normal", "vec3");
            shader.addAttribs("color", "vec4");

            shader.addVaryings("vTexCoord", "vec2");
            shader.addVaryings("vColor", "vec4");

            shader.addUniforms("modelViewMat", "mat4");
            shader.addUniforms("projectionMat", "mat4");
            shader.addUniforms("time", "float");

            if (stage.isLightmap == true)
            {
                shader.addAttribs("lightCoord", "vec2");
            }
            else
            {
                shader.addAttribs("texCoord", "vec2");
            }

            shader.addLines("vec3 defPosition = position;");

            //shader.addAttribs(attribs);
            //shader.addVaryings(varyings);
            //shader.addUniforms(uniforms);
            //shader.addLines(statements);

            for (int i = 0; i < stageShader.vertexDeforms.Count; ++i)
            {
                deform_t deform = stageShader.vertexDeforms[i];

                switch (deform.type)
                {
                case "wave":
                    String name    = "deform" + i.ToString();
                    String offName = "deformOff" + i.ToString();

                    shader.addLine("float " + offName + " = (position.x + position.y + position.z) * " + ShaderBuilder.toStringAsFixed(deform.spread, 4) + ";");

                    var phase = deform.waveform.phase;
                    deform.waveform.phase = ShaderBuilder.toStringAsFixed((double)phase, 4) + " + " + offName;
                    shader.addWaveform(name, deform.waveform, null);
                    deform.waveform.phase = phase;

                    shader.addLine("defPosition += normal * " + name + ";");
                    break;

                default: break;
                }
            }

            shader.addLine("vec4 worldPosition = modelViewMat * vec4(defPosition, 1.0);");
            shader.addLine("vColor = color;");

            if (stage.tcGen == "environment")
            {
                shader.addLines(
                    "vec3 viewer = normalize(-worldPosition.xyz);",
                    "float d = dot(normal, viewer);",
                    "vec3 reflected = normal*2.0*d - viewer;",
                    "vTexCoord = vec2(0.5, 0.5) + reflected.xy * 0.5;"
                    );
            }
            else
            {
                // Standard texturing
                if (stage.isLightmap == true)
                {
                    shader.addLines("vTexCoord = lightCoord;");
                }
                else
                {
                    shader.addLines("vTexCoord = texCoord;");
                }
            }

            // tcMods
            for (int i = 0; i < stage.tcMods.Count; ++i)
            {
                tcMod_t tcMod = stage.tcMods[i];

                switch (tcMod.type)
                {
                case "rotate":
                    shader.addLines(
                        string.Format("float r = {0} * time;", ShaderBuilder.toStringAsFixed(tcMod.angle, 4)),
                        "vTexCoord -= vec2(0.5, 0.5);",
                        "vTexCoord = vec2(vTexCoord.s * cos(r) - vTexCoord.t * sin(r), vTexCoord.t * cos(r) + vTexCoord.s * sin(r));",
                        "vTexCoord += vec2(0.5, 0.5);"
                        );
                    break;

                case "scroll":
                    double sSpeed = tcMod.sSpeed;     // was tcMod['sSpeed'].toFixed(4)
                    double tSpeed = tcMod.tSpeed;

                    shader.addLines(string.Format("vTexCoord += vec2({0} * time, {1} * time); ", ShaderBuilder.toStringAsFixed(sSpeed, 4), ShaderBuilder.toStringAsFixed(tSpeed, 4)));
                    break;

                case "scale":
                    double scaleX = tcMod.scaleX;
                    double scaleY = tcMod.scaleY;

                    shader.addLines("vTexCoord *= vec2(" + ShaderBuilder.toStringAsFixed(scaleX, 4) + ", " + ShaderBuilder.toStringAsFixed(scaleY, 4) + ");");
                    break;

                case "stretch":
                    shader.addWaveform("stretchWave", tcMod.waveform, null);
                    shader.addLines(
                        "stretchWave = 1.0 / stretchWave;",
                        "vTexCoord *= stretchWave;",
                        "vTexCoord += vec2(0.5 - (0.5 * stretchWave), 0.5 - (0.5 * stretchWave));"
                        );
                    break;

                case "turb":
                    String tName = "turbTime" + i.ToString();
                    shader.addLines(
                        "float " + tName + " = " + ShaderBuilder.toStringAsFixed(tcMod.turbulance.phase, 4) + " + time * " + ShaderBuilder.toStringAsFixed(tcMod.turbulance.freq, 4) + ";",
                        "vTexCoord.s += sin( ( ( position.x + position.z )* 1.0/128.0 * 0.125 + " + tName + " ) * 6.283) * " + ShaderBuilder.toStringAsFixed(tcMod.turbulance.amp, 4) + ';',
                        "vTexCoord.t += sin( ( position.y * 1.0/128.0 * 0.125 + " + tName + " ) * 6.283) * " + ShaderBuilder.toStringAsFixed(tcMod.turbulance.amp, 4) + ";"
                        );
                    break;

                default: break;
                }
            }

            switch (stage.alphaGen)
            {
            case "lightingspecular":
                shader.addAttribs("lightCoord", "vec2");
                shader.addVaryings("vLightCoord", "vec2");
                shader.addLines("vLightCoord = lightCoord;");
                break;

            default:
                break;
            }

            shader.addLines("gl_Position = projectionMat * worldPosition;");


            vertex_shader_src_t vertex_shader = new vertex_shader_src_t();

            vertex_shader.source_code = shader.getSource();
            return(vertex_shader);
        }
Example #39
0
        public static fragment_shader_src_t buildFragmentShader(shader_t stageShader, stage_t stage)
        {
            ShaderBuilder shader = new ShaderBuilder();

            shader.addVaryings("vTexCoord", "vec2");
            shader.addVaryings("vColor", "vec4");

            shader.addUniforms("texture", "sampler2D");
            shader.addUniforms("time", "float");

            shader.addLines("vec4 texColor = texture2D(texture, vTexCoord.st);");

            switch (stage.rgbGen)
            {
            case "vertex":
                shader.addLines("vec3 rgb = texColor.rgb * vColor.rgb;");
                break;

            case "wave":
                shader.addWaveform("rgbWave", stage.rgbWaveform, null);
                shader.addLines("vec3 rgb = texColor.rgb * rgbWave;");
                break;

            default:
                shader.addLines("vec3 rgb = texColor.rgb;");
                break;
            }

            switch (stage.alphaGen)
            {
            case "wave":
                shader.addWaveform("alpha", stage.alphaWaveform, null);
                break;

            case "lightingspecular":
                // For now this is VERY special cased. May not work well with all instances of lightingSpecular
                shader.addUniforms("lightmap", "sampler2D");

                shader.addVaryings("vLightCoord", "vec2");
                shader.addVaryings("vLight", "float");
                shader.addLines(
                    "vec4 light = texture2D(lightmap, vLightCoord.st);",
                    "rgb *= light.rgb;",
                    "rgb += light.rgb * texColor.a * 0.6;",     // This was giving me problems, so I'm ignorning an actual specular calculation for now
                    "float alpha = 1.0;"
                    );
                break;

            default:
                shader.addLines("float alpha = texColor.a;");
                break;
            }

            if (stage.alphaFunc != null)
            {
                switch (stage.alphaFunc)
                {
                case "GT0":
                    shader.addLines("if(alpha == 0.0) { discard; }");
                    break;

                case "LT128":
                    shader.addLines("if(alpha >= 0.5) { discard; }");
                    break;

                case "GE128":
                    shader.addLines("if(alpha < 0.5) { discard; }");
                    break;

                default:
                    break;
                }
            }

            shader.addLines("gl_FragColor = vec4(rgb, alpha);");

            fragment_shader_src_t frag_shader = new fragment_shader_src_t();

            frag_shader.source_code = shader.getSource();
            return(frag_shader);
        }