Exemple #1
0
 protected override void Dispose(bool disposing)
 {
     base.Dispose(disposing);
     if (this.scrollBar != null)
     {
         this.scrollBar.Dispose();
         this.scrollBar = (Button)null;
     }
     if (this.selectedVAO != null)
     {
         this.selectedVAO.DisposeChildren = true;
         this.selectedVAO.Dispose();
         this.selectedVAO = (VAO)null;
     }
     if (TextBox.scrollbarTexture != null)
     {
         TextBox.scrollbarTexture.Dispose();
         TextBox.scrollbarTexture = (Texture)null;
     }
     foreach (UIElement vao in this.vaos)
     {
         vao.Dispose();
     }
     this.vaos.Clear();
 }
    void RunVertexShader(VAO vao)
    {
        for (int i = 0; i < vao.vbo.Length;)
        {
            var v0 = Vert(vao.vbo[i]);
            var v1 = Vert(vao.vbo[i + 1]);
            var v2 = Vert(vao.vbo[i + 2]);
            DoNDCCoord(v0);
            DoNDCCoord(v1);
            DoNDCCoord(v2);

            var d01 = v1.vertex - v0.vertex;
            var d02 = v2.vertex - v0.vertex;
            // 顺便 背面剔除 backface culling
            var dimen = d01.x * d02.y - d01.y * d02.x;

            if (dimen < 0)
            {
                vertexList.Add(v0);
                vertexList.Add(v1);
                vertexList.Add(v2);
            }
            i += 3;
        }
    }
Exemple #3
0
        private void UpdateGeometry(Shader shader)
        {
            Mesh mesh     = new Mesh();
            var  roomSize = 8;
            var  plane    = Meshes.CreateQuad(roomSize, roomSize, 2, 2);
            var  xform    = new Transformation();

            xform.TranslateGlobal(0, -roomSize / 2, 0);
            mesh.Add(plane.Transform(xform));
            xform.RotateZGlobal(90f);
            mesh.Add(plane.Transform(xform));
            xform.RotateZGlobal(90f);
            mesh.Add(plane.Transform(xform));
            xform.RotateZGlobal(90f);
            mesh.Add(plane.Transform(xform));
            xform.RotateYGlobal(90f);
            mesh.Add(plane.Transform(xform));
            xform.RotateYGlobal(180f);
            mesh.Add(plane.Transform(xform));

            var sphere = Meshes.CreateSphere(1);

            mesh.Add(sphere);
            var suzanne = Obj2Mesh.FromObj(Resourcen.suzanne);

            mesh.Add(suzanne.Transform(System.Numerics.Matrix4x4.CreateTranslation(2, 2, -2)));
            geometry = VAOLoader.FromMesh(mesh, shader);
        }
Exemple #4
0
        public Planet(string databaseName, PlanetParameters parameters, Planet parent, VAO vao, Texture t)
            : base(vao, t)
        {
            this.parent             = parent;
            this.OrbitalOrientation = -1;
            this.DrawAxisTilt       = true;
            this.DrawOrbit          = true;

            this.AxisTilt           = (float)MathHelper.DegreesToRadians(parameters.AxialTilt[databaseName]);
            this.PlanetRadius       = parameters.PlanetRadius[databaseName];
            this.DistanceFromParent = parameters.DistanceFromSun[databaseName];

            this.RotationalPeriod = parameters.RotationPeriod[databaseName];
            this.OrbitalPeriod    = parameters.OrbitalPeriod[databaseName];

            this.setScale((float)PlanetRadius);

            if (parent != null)
            {
                this.Orbit = new Orbit(this, parent.Translation, this.DistanceFromParent, 120);
                DrawOrbit  = true;
            }

            Vector3[] axisVerts = { new Vector3(0, -2, 0), new Vector3(0, 2, 0) };

            axisLine = new VAO(axisVerts);
        }
        public BackgroundRenderer(IBackground background)
        {
            _program = new ShaderProgram("Shaders/Background.vert", "Shaders/Background.frag");
            _vao     = new VAO();
            var flatBuffer = new VBO();

            using (Bind.These(_vao, flatBuffer))
            {
                var data = new List <float>();
                data.AddRange(new float[] { -1, -1 });
                data.AddRange(background.BottomLeft.ToFloatArray());
                data.AddRange(new float[] { 1, -1 });
                data.AddRange(background.BottomRight.ToFloatArray());
                data.AddRange(new float[] { 1, 1 });
                data.AddRange(background.TopRight.ToFloatArray());
                data.AddRange(new float[] { -1, 1 });
                data.AddRange(background.TopLeft.ToFloatArray());
                var flatData = data.ToArray();
                flatBuffer.Update(flatData, flatData.Length * sizeof(float));
                const int stride = sizeof(float) * 6;

                GL.EnableVertexAttribArray(0);
                GL.VertexAttribPointer(0, 2, VertexAttribPointerType.Float, false, stride, new IntPtr(0));
                GL.EnableVertexAttribArray(1);
                GL.VertexAttribPointer(1, 4, VertexAttribPointerType.Float, false, stride, new IntPtr(sizeof(float) * 2));
            }
        }
        GameObject GetPBRModel(string meshFileName, string albedoMapFile, string normalMapFile, string metallicMapFile, string roughnessMapFile)
        {
            DefaultMesh mesh = contentLoader.Load <DefaultMesh>(meshFileName);
            VAO         geom = VAOLoader.FromMesh(mesh, renderer.GetPBRShader());
            GameObject  go   = new GameObject();
            PBRMaterial mat  = new PBRMaterial();

            go.mesh     = geom;
            go.material = mat;
            //mat.metal = 1.0f;
            //mat.metal = 0f;
            mat.roughness = 0;
            if (albedoMapFile != null)
            {
                ITexture2D albedoMap = contentLoader.Load <ITexture2D>(albedoMapFile);
                mat.albedoMap = albedoMap;
            }
            if (normalMapFile != null && normalMapFile != "")
            {
                ITexture2D normalMap = contentLoader.Load <ITexture2D>(normalMapFile);
                mat.normalMap = normalMap;
            }
            if (metallicMapFile != null)
            {
                ITexture2D metallicMap = contentLoader.Load <ITexture2D>(metallicMapFile);
                mat.metallicMap = metallicMap;
            }
            if (roughnessMapFile != null)
            {
                ITexture2D roughnessMap = contentLoader.Load <ITexture2D>(roughnessMapFile);
                mat.roughnessMap = roughnessMap;
            }
            return(go);
        }
Exemple #7
0
        private void UpdateGeometry(Shader shader)
        {
            geometry = new VAO();
            //generate position arrray on CPU
            var          rnd       = new Random(12);
            Func <float> Rnd01     = () => (float)rnd.NextDouble();
            Func <float> RndCoord  = () => (Rnd01() - 0.5f) * 2.0f;
            var          positions = new Vector2[pointCount];

            for (int i = 0; i < pointCount; ++i)
            {
                positions[i] = new Vector2(RndCoord(), RndCoord());
            }
            //copy positions to GPU
            geometry.SetAttribute(shader.GetAttributeLocation("in_position"), positions, VertexAttribPointerType.Float, 2);
            //generate velocity arrray on CPU
            Func <float> RndSpeed   = () => (Rnd01() - 0.5f) * 0.1f;
            var          velocities = new Vector2[pointCount];

            for (int i = 0; i < pointCount; ++i)
            {
                velocities[i] = new Vector2(RndSpeed(), RndSpeed());
            }
            //copy velocities to GPU
            geometry.SetAttribute(shader.GetAttributeLocation("in_velocity"), velocities, VertexAttribPointerType.Float, 2);
        }
        uint CreateIrradianceMap(int frameBuffer, Matrix4x4 projection, Matrix4x4[] viewMatrices, uint cubeMap)
        {
            DefaultMesh cubeMesh           = Meshes.CreateCubeWithNormals();
            VAO         renderIrradMapCube = VAOLoader.FromMesh(cubeMesh, irradianceMapShader);
            //Create Irradiance Texture
            int fbIrrWidth  = 32;
            int fbIrrHeight = 32;
            int irradMap    = CreateCubeMap(32, 32);

            GL.BindFramebuffer(FramebufferTarget.Framebuffer, frameBuffer);
            //GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, FramebufferAttachment.ColorAttachment0, TextureTarget.TextureCubeMap, irradMap, 0);
            //Render
            //Irradiance Map
            irradianceMapShader.Activate();
            SetSampler(irradianceMapShader.ProgramID, 0, "environmentMap", cubeMap, TextureTarget.TextureCubeMap);
            irradianceMapShader.Uniform("projection", projection, true);

            GL.Viewport(0, 0, fbIrrWidth, fbIrrHeight);
            GL.BindFramebuffer(FramebufferTarget.Framebuffer, frameBuffer);
            for (int i = 0; i < 6; i++)
            {
                irradianceMapShader.Uniform("view", viewMatrices[i], true);
                GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, FramebufferAttachment.ColorAttachment0,
                                        TextureTarget.TextureCubeMapPositiveX + i, irradMap, 0);

                GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

                renderIrradMapCube.Draw();
            }

            GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0);
            return((uint)irradMap);
        }
        private void UpdateGeometry(IShaderProgram shaderProgram)
        {
            geometry = new VAO(PrimitiveType.Points);
            //generate position array on CPU
            var rnd = new Random(12);

            float Rnd01() => (float)rnd.NextDouble();
            float RndCoord() => (Rnd01() - 0.5f) * 2.0f;

            var positions = new Vector2[pointCount];

            for (int i = 0; i < pointCount; ++i)
            {
                positions[i] = new Vector2(RndCoord(), RndCoord());
            }
            //copy positions to GPU
            geometry.SetAttribute(shaderProgram.GetResourceLocation(ShaderResourceType.Attribute, "in_position"), positions, VertexAttribPointerType.Float, 2);
            //generate velocity arrray on CPU
            float RndSpeed() => (Rnd01() - 0.5f) * 0.1f;

            var velocities = new Vector2[pointCount];

            for (int i = 0; i < pointCount; ++i)
            {
                velocities[i] = new Vector2(RndSpeed(), RndSpeed()) * 10.0f;
            }
            //copy velocities to GPU
            geometry.SetAttribute(shaderProgram.GetResourceLocation(ShaderResourceType.Attribute, "in_velocity"), velocities, VertexAttribPointerType.Float, 2);
        }
Exemple #10
0
 public PlanetRing(VAO vbos, Texture t, Planet p)
 {
     this.vao       = vbos;
     this.texture   = t;
     this.parent    = p;
     this.transform = parent.Transform;
 }
 public void Render()
 {
     if (shaderWatcher.CheckForShaderChange())
     {
         //update geometry when shader changes
         geometry = CreateMesh(shaderWatcher.Shader);
     }
     GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
     var shader = shaderWatcher.Shader;
     shader.Begin();
     GL.Uniform3(shader.GetUniformLocation("light1Direction"), new Vector3(-1, -1, -1).Normalized());
     GL.Uniform4(shader.GetUniformLocation("light1Color"), new Color4(1f, 1f, 1f, 1f));
     GL.Uniform3(shader.GetUniformLocation("light2Position"), new Vector3(-1, -1, 1));
     GL.Uniform4(shader.GetUniformLocation("light2Color"), new Color4(1f, .1f, .1f, 1f));
     GL.Uniform3(shader.GetUniformLocation("light3Position"), new Vector3(-2, 2, 2));
     GL.Uniform3(shader.GetUniformLocation("light3Direction"), new Vector3(1, -1, -1).Normalized());
     GL.Uniform1(shader.GetUniformLocation("light3Angle"), Geometry.MathHelper.DegreesToRadians(10f));
     GL.Uniform4(shader.GetUniformLocation("light3Color"), new Color4(0, 0, 1f, 1f));
     GL.Uniform4(shader.GetUniformLocation("ambientLightColor"), new Color4(.1f, .1f, .1f, 1f));
     GL.Uniform4(shader.GetUniformLocation("materialColor"), new Color4(.7f, .9f, .7f, 1f));
     var cam = camera.CalcMatrix().ToOpenTK();
     GL.UniformMatrix4(shader.GetUniformLocation("camera"), true, ref cam);
     GL.Uniform3(shader.GetUniformLocation("cameraPosition"), camera.CalcPosition().ToOpenTK());
     geometry.Draw();
     shader.End();
 }
 public RawModel(VBOArrayF attributes)
 {
     this.shaderAttributes = attributes;
     Buffer = new VAO(this.shaderAttributes);
     VAOManager.genVAO(Buffer);
     VAOManager.setBufferData(OpenTK.Graphics.OpenGL.BufferTarget.ArrayBuffer, Buffer);
 }
Exemple #13
0
        private void UpdateMesh(Shader shader)
        {
            Mesh mesh = Obj2Mesh.FromObj(Resourcen.suzanne);

            geometry = VAOLoader.FromMesh(mesh, shader);

            //per instance attributes
            var          rnd               = new Random(12);
            Func <float> Rnd01             = () => (float)rnd.NextDouble();
            Func <float> RndCoord          = () => (Rnd01() - 0.5f) * 8.0f;
            var          instancePositions = new Vector3[particelCount];

            for (int i = 0; i < particelCount; ++i)
            {
                instancePositions[i] = new Vector3(RndCoord(), RndCoord(), RndCoord());
            }
            geometry.SetAttribute(shader.GetAttributeLocation("instancePosition"), instancePositions, VertexAttribPointerType.Float, 3, true);

            Func <float> RndSpeed       = () => (Rnd01() - 0.5f);
            var          instanceSpeeds = new Vector3[particelCount];

            for (int i = 0; i < particelCount; ++i)
            {
                instanceSpeeds[i] = new Vector3(RndSpeed(), RndSpeed(), RndSpeed());
            }
            geometry.SetAttribute(shader.GetAttributeLocation("instanceSpeed"), instanceSpeeds, VertexAttribPointerType.Float, 3, true);
        }
Exemple #14
0
        public bool Load()
        {
            if (!_loaded)
            {
                _camera  = Game.CurrentScene.PrimaryCamera.GetComponent <Camera>();
                _program = new CubemapShaderProgram();
                _cube    = Geometry.CreateCube(_program, Vector3f.One * -_camera.Far / 2, Vector3f.One * _camera.Far / 2);

                _textureID = GL.GenTexture();
                GL.BindTexture(TextureTarget.TextureCubeMap, _textureID);

                for (uint i = 0; i < _types.Length; i++)
                {
                    try
                    {
                        _loadCubeSide(i);
                    }
                    catch (Exception)
                    {
                        return(false);
                    }
                }

                GL.BindTexture(TextureTarget.TextureCubeMap, 0);

                ResourcesManager.AddDisposableResource(this);

                _loaded = true;
            }

            return(true);
        }
Exemple #15
0
        /// <summary>
        /// Creates a new <c>ChunkMesh</c> renderable.
        /// </summary>
        /// <param name="chunk"></param>
        /// <param name="geometry"></param>
        public ChunkMesh(Chunk chunk, VAO geometry)
        {
            _chunk    = chunk;
            _geometry = geometry;

            Bounds = new AxisAlignedBoundingBox(_chunk.World, _chunk.World + Chunk.Dimensions);
        }
        public TextureRenderer2D(Vector2 position, Vector2 size, Texture texture, Shader shader)
        {
            _texture = texture;
            _shader  = shader;

            DefaultMesh mesh = new DefaultMesh();

            mesh.Position.Add(new Vector3(position.X, position.Y, 0));                   //0
            mesh.Position.Add(new Vector3(position.X + size.X, position.Y, 0));          //1
            mesh.Position.Add(new Vector3(position.X + size.X, position.Y + size.Y, 0)); //2
            mesh.Position.Add(new Vector3(position.X, position.Y + size.Y, 0));          //3

            mesh.TexCoord.Add(new Vector2(0.0f, 0.0f));
            mesh.TexCoord.Add(new Vector2(1.0f, 0.0f));
            mesh.TexCoord.Add(new Vector2(1.0f, 1.0f));
            mesh.TexCoord.Add(new Vector2(0.0f, 1.0f));

            mesh.IDs.Add(0);
            mesh.IDs.Add(2);
            mesh.IDs.Add(1);
            mesh.IDs.Add(0);
            mesh.IDs.Add(3);
            mesh.IDs.Add(2);

            _geometry = VAOLoader.FromMesh(mesh, shader);
        }
Exemple #17
0
        public Deferred(IContentLoader contentLoader, Dictionary <Enums.EntityType, DefaultMesh> meshes)
        {
            _deferredProgram = contentLoader.Load <IShaderProgram>("deferred.*");

            foreach (var meshContainer in meshes)
            {
                VAO geometry = VAOLoader.FromMesh(meshContainer.Value, _deferredProgram);

                if (meshContainer.Value is TBNMesh mesh)
                {
                    var loc = _deferredProgram.GetResourceLocation(ShaderResourceType.Attribute, TBNMesh.TangentName);
                    geometry.SetAttribute(loc, mesh.Tangent.ToArray(), VertexAttribPointerType.Float, 3);

                    loc = _deferredProgram.GetResourceLocation(ShaderResourceType.Attribute, TBNMesh.BitangentName);
                    geometry.SetAttribute(loc, mesh.Bitangent.ToArray(), VertexAttribPointerType.Float, 3);
                }

                _geometries.Add(meshContainer.Key, geometry);
            }

            _defaultMap = contentLoader.Load <ITexture2D>("Nvidia.png");

            _projectilesGenerationNvidia = new ProjectileGeneration(contentLoader, meshes[Enums.EntityType.NvidiaParticle], Enums.EntityType.NvidiaParticle);
            _projectilesGenerationRadeon = new ProjectileGeneration(contentLoader, meshes[Enums.EntityType.RadeonParticle], Enums.EntityType.RadeonParticle);
            _addProjectilesNvidia        = new AddWithDepthTest(contentLoader);
            _addProjectilesRadeon        = new AddWithDepthTest(contentLoader);

            _tesselation    = new Tesselation(contentLoader);
            _addTesselation = new AddWithDepthTest(contentLoader);
        }
Exemple #18
0
        public PolygonLayerRenderer(IEnumerable <PolygonLayer> polygons)
        {
            _program = new ShaderProgram("Shaders/PolygonModel.vert", "Shaders/PolygonModel.frag");
            var polygonModel = polygons.First();

            _vao = new VAO();
            var flatBuffer = new VBO();

            using (Bind.These(_vao, flatBuffer))
            {
                var data = new List <float>();

                foreach (var edge in polygonModel.Polygons.SelectMany(p => p.Edges))
                {
                    count++;
                    data.AddRange(edge.Start.Position.ToArray().Select(d => (float)d));
                    data.AddRange(edge.Start.Color.ToFloatArray());
                    data.AddRange(edge.End.Position.ToArray().Select(d => (float)d));
                    data.AddRange(Color.Aqua.ToFloatArray());
                }

                var flatData = data.ToArray();
                flatBuffer.Update(flatData, flatData.Length * sizeof(float));

                const int stride = sizeof(float) * 7;

                GL.EnableVertexAttribArray(0);
                GL.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, false, stride, new IntPtr(0));
                GL.EnableVertexAttribArray(1);
                GL.VertexAttribPointer(1, 4, VertexAttribPointerType.Float, false, stride, new IntPtr(sizeof(float) * 3));
            }
        }
Exemple #19
0
        public bool Create()
        {
            CheckError("init");

            Shader = new Shader("SilkyNvg-OpenGL-Shader", EdgeAntiAlias, this);
            if (!Shader.Status)
            {
                return(false);
            }

            CheckError("uniform locations");
            Shader.GetUniforms();

            _vao     = new(Gl);
            _vao.Vbo = new(Gl);

            Filter = new StateFilter();

            Shader.BindUniformBlock();

            // Dummy tex will always be at index 0.
            DummyTex = CreateTexture(Texture.Alpha, new Vector2D <uint>(1, 1), 0, null);

            CheckError("create done!");

            Gl.Finish();

            return(true);
        }
 public ImageWithCaption(string titleText, string captionText, string media)
     : this(titleText, captionText)
 {
     image = new Texture(media);
     imageVAO = Utilities.CreateQuad(Shaders.SimpleTexturedShader, Vector2.Zero, new Vector2(904, 410));
     imageModelMatrix = Matrix4.CreateTranslation(new Vector3(72, 720 - 65 - 410, 0));
 }
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            if (scrollBar != null)
            {
                scrollBar.Dispose();
                scrollBar = null;
            }

            if (selectedVAO != null)
            {
                selectedVAO.DisposeChildren = true;
                selectedVAO.Dispose();
                selectedVAO = null;
            }

            if (scrollbarTexture != null)
            {
                scrollbarTexture.Dispose();
                scrollbarTexture = null;
            }

            foreach (var vao in vaos)
            {
                vao.Dispose();
            }
            vaos.Clear();
        }
Exemple #22
0
        public static Shape CreateCircle(VertexAttrib VertexPositionAttrib, float radius = 1, int slices = 64)
        {
            float dtheta = MathHelper.TwoPi / (slices - 1);
            var   theta  = 0f;

            Vector3[] Vertices = new Vector3[slices + 1];
            Vertices[0] = new Vector3(0, 0, 0);
            for (var i = 0; i < slices; i++)
            {
                Vertices[i + 1] = new Vector3((float)Math.Cos(theta) * radius, (float)Math.Sin(theta) * radius, 0);
                theta          += dtheta;
            }

            Buffer <Vector3> VertexBuffer = new Buffer <Vector3>();

            VertexBuffer.Init(BufferTarget.ArrayBuffer, Vertices);

            return(new DynamicShape()
                   .WithVertexAttrib(VertexPositionAttrib, VertexBuffer)
                   .WithDisposeFunction(() => {
                VertexBuffer?.Dispose();
            })
                   .SetDrawFunction((VertexArray VAO) => {
                VAO.DrawArrays(PrimitiveType.TriangleFan, 0, VertexBuffer.ElementCount);
            }));
        }
 public ImageAndText(string titleText, string media, string[] bulletText)
     : this(titleText, bulletText)
 {
     image = new Texture(media);
     imageVAO = Utilities.CreateQuad(Shaders.SimpleTexturedShader, Vector2.Zero, new Vector2(441, 410));
     imageModelMatrix = Matrix4.CreateTranslation(new Vector3(72, 720 - 227 - 410, 0));
 }
Exemple #24
0
 public ColorGradient()
 {
     if (UserInterface.GetElement(nameof(ColorGradient)) != null)
     {
         throw new Exception("Only one color picker can currently exist at once.  This is a limitation I intend to remove soon.");
     }
     this.Program = Shaders.GradientShader;
     this.Program.Use();
     this.Program["hue"].SetValue(new Vector3(this.h, 0.0f, 0.0f));
     this.Program["sel"].SetValue(new Vector2(this.selx, this.sely));
     this.gradientQuad = Geometry.CreateQuad(this.Program, Vector2.Zero, new Vector2(150f, 150f));
     this.RelativeTo   = Corner.TopLeft;
     this.Position     = new Point(30, 50);
     this.Size         = new Point(150, 150);
     this.Name         = nameof(ColorGradient);
     this.OnMouseDown  = (OnMouse)((sender, eventArgs) =>
     {
         this.mouseDown = eventArgs.Button == MouseButton.Left;
         this.UpdateMousePosition(eventArgs.Location.X, eventArgs.Location.Y);
     });
     this.OnMouseUp    = (OnMouse)((sender, eventArgs) => this.mouseDown = eventArgs.Button != MouseButton.Left && this.mouseDown);
     this.OnMouseLeave = (OnMouse)((sender, eventArgs) => this.mouseDown = false);
     this.OnMouseMove  = (OnMouse)((sender, eventArgs) => this.UpdateMousePosition(eventArgs.Location.X, eventArgs.Location.Y));
     this.UpdateColor();
 }
Exemple #25
0
        public static void Draw3DPlotLeft(float[] data, float depth, Vector3 color, Matrix4 viewMatrix, bool log = false)
        {
            if (data.Length < 441) throw new ArgumentException("The argument data was not the correct length.");

            for (int i = 0; i < fftData.Length; i++)
                fftData[i] = new Vector3((log ? Math.Log10(i) * 166 : i) - 441 / 2f, Math.Max(-200, Math.Min(200, 200 * data[i])), depth);
                //fftData[i] = new Vector3(i - 441 / 2f, Math.Max(-200, Math.Min(200, 200 * data[i])), depth);

            if (fftVAO == null)
            {
                int[] array = new int[441];
                for (int i = 0; i < array.Length; i++) array[i] = i;

                fftHandle = GCHandle.Alloc(fftData, GCHandleType.Pinned);
                fftVBO = BufferData(fftVBO, fftData, fftHandle);
                fftVAO = new VAO<Vector3>(Shaders.SimpleColoredShader, fftVBO, "in_position", new VBO<int>(array, BufferTarget.ElementArrayBuffer, BufferUsageHint.StaticDraw));
                fftVAO.DrawMode = BeginMode.LineStrip;
            }
            else fftVBO = BufferData(fftVBO, fftData, fftHandle);

            Shaders.SimpleColoredShader.Use();
            Shaders.SimpleColoredShader["projectionMatrix"].SetValue(Program.uiProjectionMatrix);
            Shaders.SimpleColoredShader["viewMatrix"].SetValue(viewMatrix);
            Shaders.SimpleColoredShader["modelMatrix"].SetValue(Matrix4.CreateTranslation(new Vector3(72 + 441 / 2f, 288, 0)));
            Shaders.SimpleColoredShader["color"].SetValue(color);
            fftVAO.Draw();
        }
        static unsafe void Main(string[] args)
        {
            var Options = WindowOptions.Default;

            Options.Size  = new Silk.NET.Maths.Vector2D <int>(800, 600);
            Options.Title = "LearnOpenGL with Silk.NET";
            var window = Window.Create(Options);

            window.Render += (obj) => {
                GL.GetApi(window).ClearColor(Color.Black);
                GL.GetApi(window).Clear((uint)ClearBufferMask.ColorBufferBit);
                vao.Bind();
                shader.Use();
                GL.GetApi(window).DrawElements((GLEnum)PrimitiveType.Triangles, (uint)Indices.Length, GLEnum.UnsignedInt, null);
            };
            window.Load += () => {
                vbo    = new VBO(GL.GetApi(window), Vertices, GLEnum.StaticDraw);
                ebo    = new EBO(GL.GetApi(window), Indices);
                vao    = new VAO(GL.GetApi(window), vbo, ebo);
                shader = new Abstractions.Shader(GL.GetApi(window), "shader.vert", "shader.frag");
                vao.VertexAttributePointer(0, 3, VertexAttribPointerType.Float, 0, 0);
            };
            window.Closing += () => {
                vbo.Dispose();
                ebo.Dispose();
                vao.Dispose();
                shader.Dispose();
            };
            window.Run();
        }
        public virtual void Load(int width, int height)
        {
            Width = width;
            Height = height;
            _page = new Texture();
            GUIShader = Assets.Fetch<ShaderProgram>("GUI");
            GUIShader.AddUniform("scale");
            VBO = new VBO<VertexPositionNormalTexture>();
            VAO = new VAO<VertexPositionNormalTexture>();
            VBO.Buffer(new[]{
                new VertexPositionNormalTexture{Position = new Vector3(0, Height, 0f),Normal = Vector3.UnitZ,TexCoord = new Vector2(0, Height)},
                new VertexPositionNormalTexture{Position = new Vector3(Width, Height, 0f),Normal = Vector3.UnitZ,TexCoord = new Vector2(Width, Height)},
                new VertexPositionNormalTexture{Position = new Vector3(Width, 0, 0f),Normal = Vector3.UnitZ,TexCoord = new Vector2(Width, 0)},
                new VertexPositionNormalTexture{Position = new Vector3(0, 0, 0),Normal = Vector3.UnitZ,TexCoord = new Vector2(0,0)}
            });
            VAO.Setup(GUIShader, VBO);
            _webView = WebCore.CreateWebView(Width, Height);
            WebCore.BaseDirectory = Path.Combine(Directory.GetCurrentDirectory(), "GUI");
            _webView.FlushAlpha = false;
            _webView.IsTransparent = true;
            _webView.CreateObject("console");
            _webView.SetObjectCallback("console", "log", (sender, e) => Bus.Add(new DebugMessage(Timer.LastTickTime, e.Arguments[0].ToString())));

            _webView.CreateObject("GUI");
            _webView.CreateObject("Bus");

            _webView.LoadFile("index.htm");
        }
Exemple #28
0
        public VisualLevel(IContentLoader contentLoader)
        {
            void Add(ElementType elementType, string resourceName, int sliceID)
            {
                tileTypes.Add(elementType, new Tuple <string, int>(resourceName, sliceID));
            }

            int slice = 0;

            Add(ElementType.Floor, "GroundGravel_Grass", slice++);
            Add(ElementType.Man, "character4", slice++);
            Add(ElementType.Box, ".Crate_Brown", slice++);
            Add(ElementType.Goal, "EndPoint_Red", slice++);
            Add(ElementType.ManOnGoal, "EndPointCharacter", slice++);
            Add(ElementType.BoxOnGoal, "EndPointCrate_Brown", slice++);
            Add(ElementType.Wall, "Wall_Beige", slice++);

            var names = from item in tileTypes select item.Value.Item1;

            texArray    = contentLoader.Load <ITexture2dArray>(names);
            shdTexColor = contentLoader.Load <IShaderProgram>("texColor.*");

            vaoLevelGeometry = new VAO(PrimitiveType.Quads);
            var quadPos = new Vector2[4] {
                Vector2.Zero, Vector2.UnitX, Vector2.One, Vector2.UnitY
            };
            var locPosition = shdTexColor.GetResourceLocation(ShaderResourceType.Attribute, "position");

            vaoLevelGeometry.SetAttribute(locPosition, quadPos);
        }
Exemple #29
0
        public virtual void Draw(ShaderProgram shader, VAO vao, GameWindow gw)
        {
            shader.SetUniform("rect", GlobalBounds);
            shader.SetUniform("color", BackgroundColor);
            shader.SetUniform("borderWidth", BorderWidth);
            shader.SetUniform("borderColor", BorderColor);

            if (BackgroundImage != null)
            {
                BackgroundImage.Bind();
                shader.SetUniform("useTexture", true);
            }
            else
            {
                shader.SetUniform("useTexture", false);
            }

            vao.DrawArrays(OpenTK.Graphics.OpenGL.PrimitiveType.TriangleStrip);

            var temp = this as IText;

            if (temp != null && !string.IsNullOrWhiteSpace(temp.Text))
            {
                GuiManager.setScisor(GlobalBounds, BorderWidth, gw, Parent);
                temp.TextImage.Bind();
                shader.SetUniform("useTexture", true);
                shader.SetUniform("rect", temp.TextBounds);
                shader.SetUniform("borderWidth", 0);

                vao.DrawArrays(OpenTK.Graphics.OpenGL.PrimitiveType.TriangleStrip);
            }
        }
Exemple #30
0
        //public OnMouse OnColorChange { get; set; }
        #endregion

        #region Constructor
        public ColorGradient()
        {
            var colorGradient = UI.GetElement("ColorGradient");

            if (colorGradient != null)
            {
                throw new Exception("Only one color picker can currently exist at once.  This is a limitation I intend to remove soon.");
            }

            this.Program = Shaders.GradientShader;

            this.Program.Use();
            this.Program["hue"].SetValue(new Vector3(h, 0, 0));
            this.Program["sel"].SetValue(new Vector2(selx, sely));
            this.gradientQuad = Geometry.CreateQuad(this.Program, Vector2.Zero, new Vector2(150, 150));

            this.RelativeTo = Corner.TopLeft;
            this.Position   = new Point(30, 50);
            this.Size       = new Point(150, 150);
            this.Name       = "ColorGradient";

            // set up the events for the mouse to move the indicator around
            //this.OnMouseDown = new OnMouse((sender, eventArgs) =>
            //{
            //    mouseDown = (eventArgs.Button == MouseButton.Left);
            //    UpdateMousePosition(eventArgs.Location.X, eventArgs.Location.Y);
            //});
            //this.OnMouseUp = new OnMouse((sender, eventArgs) => mouseDown = (eventArgs.Button == MouseButton.Left ? false : mouseDown));
            //this.OnMouseLeave = new OnMouse((sender, eventArgs) => mouseDown = false);
            //this.OnMouseMove = new OnMouse((sender, eventArgs) => UpdateMousePosition(eventArgs.Location.X, eventArgs.Location.Y));

            UpdateColor();
        }
Exemple #31
0
        public SphereCut(IContentLoader contentLoader, float size)
        {
            _sphereCutProgram = contentLoader.Load <IShaderProgram>("imageOnGeometry.*");

            var sphere = Meshes.CreateSphere(size, 5).SwitchHandedness();

            _sphereGeometry = VAOLoader.FromMesh(sphere, _sphereCutProgram);
        }
        public ProjectileGeneration(IContentLoader contentLoader, DefaultMesh triangleMesh, Enums.EntityType triangleType)
        {
            _projectileGenerationProgram = contentLoader.Load <IShaderProgram>(new[] { "ProjectileGeneration.vert", "deferred.frag" });
            _trianglesGeometry           = VAOLoader.FromMesh(triangleMesh, _projectileGenerationProgram);
            _triangleType = triangleType;

            _add = new AddWithDepthTest(contentLoader);
        }
Exemple #33
0
 public virtual void DrawToPickBuffer(ShaderProgram shader, VAO vao, GameWindow gw)
 {
     shader.SetUniform("color", new Vector4(PickBufferColor.X / 255, PickBufferColor.Y / 255, PickBufferColor.Z / 255, PickBufferColor.W / 255));
     shader.SetUniform("rect", GlobalBounds);
     shader.SetUniform("borderWidth", 0);
     shader.SetUniform("useTexture", false);
     vao.DrawArrays(OpenTK.Graphics.OpenGL.PrimitiveType.TriangleStrip);
 }
Exemple #34
0
        public FillRenderer(Game game, GL gl)
        {
            _game = game;
            _gl   = gl;

            _shader = ResourceManager.LoadShader("fillVertexShader", "fillFragmentShader");
            _vao    = ResourceManager.CreateVao();
        }
Exemple #35
0
        private void UpdateGeometry(Shader shader)
        {
            Mesh mesh = new Mesh();

            //mesh.Add(Meshes.CreateSphere(.7f, 3));
            mesh.Add(Obj2Mesh.FromObj(Resourcen.suzanne));
            geometry = VAOLoader.FromMesh(mesh, shader);
        }
 private static VAO CreateMesh(Shader shader)
 {
     Mesh mesh = Obj2Mesh.FromObj(Resourcen.suzanne);
     var vao = new VAO();
     vao.SetAttribute(shader.GetAttributeLocation("position"), mesh.positions.ToArray(), VertexAttribPointerType.Float, 3);
     vao.SetAttribute(shader.GetAttributeLocation("normal"), mesh.normals.ToArray(), VertexAttribPointerType.Float, 3);
     vao.SetID(mesh.ids.ToArray(), PrimitiveType.Triangles);
     return vao;
 }
 private static VAO CreateMesh(Shader shader)
 {
     Mesh mesh = Meshes.CreateSphere(0.03f, 2);
     var vao = new VAO();
     vao.SetAttribute(shader.GetAttributeLocation("position"), mesh.positions.ToArray(), VertexAttribPointerType.Float, 3);
     vao.SetAttribute(shader.GetAttributeLocation("normal"), mesh.normals.ToArray(), VertexAttribPointerType.Float, 3);
     vao.SetID(mesh.ids.ToArray(), PrimitiveType.Triangles);
     return vao;
 }
        public MainVisual()
        {
            var sVertex = Encoding.UTF8.GetString(Resourcen.vertex);
            var sFragment = Encoding.UTF8.GetString(Resourcen.fragment);
            shader = ShaderLoader.FromStrings(sVertex, sFragment);

            geometry = CreateMesh(shader);

            CreatePerInstanceAttributes(geometry, shader);

            GL.Enable(EnableCap.DepthTest);
        }
        public MainVisual()
        {
            camera.FarClip = 500;
            camera.Distance = 30;
            var sVertex = Encoding.UTF8.GetString(Resourcen.vertex);
            var sFragment = Encoding.UTF8.GetString(Resourcen.fragment);
            shader = ShaderLoader.FromStrings(sVertex, sFragment);
            geometry = CreateMesh(shader);

            GL.Enable(EnableCap.DepthTest);
            GL.Enable(EnableCap.CullFace);
            timeSource.Start();
        }
Exemple #40
0
        public TwoImages(string titleText, string media1, string media2)
        {
            title = new Text(Text.FontSize._72pt, titleText, Common.TitleColor);
            title.ModelMatrix = Matrix4.CreateTranslation(new Vector3(80, 720 - 120, 0));

            image1 = new Texture(media1);
            image1VAO = Utilities.CreateQuad(Shaders.SimpleTexturedShader, Vector2.Zero, new Vector2(441, 410));
            image1ModelMatrix = Matrix4.CreateTranslation(new Vector3(72, 720 - 227 - 410, 0));

            image2 = new Texture(media2);
            image2VAO = Utilities.CreateQuad(Shaders.SimpleTexturedShader, Vector2.Zero, new Vector2(441, 410));
            image2ModelMatrix = Matrix4.CreateTranslation(new Vector3(535, 720 - 227 - 410, 0));
        }
        public Billboard(ShaderProgram program, Texture texture, Vector3[] locations, Vector3[] colors)
        {
            this.Program = program;
            this.Texture = texture;

            int[] elements = new int[locations.Length];
            for (int i = 0; i < elements.Length; i++) elements[i] = i;

            this.billboard = new VAO(program, new VBO<Vector3>(locations), new VBO<Vector3>(colors), new VBO<int>(elements));
            this.billboard.DrawMode = BeginMode.Points;
            this.billboard.DisposeChildren = true;
            this.Color = new Vector4(1, 1, 1, 1);
        }
        public MainVisual()
        {
            shaderWatcher = new ShaderFileDebugger("../../LightingExample/Resources/vertex.vert"
                , "../../LightingExample/Resources/fragment.frag"
                , Resourcen.vertex, Resourcen.fragment);
            geometry = CreateMesh(shaderWatcher.Shader);

            camera.FarClip = 20;
            camera.Distance = 5;
            camera.FovY = 30;

            GL.Enable(EnableCap.DepthTest);
            GL.Enable(EnableCap.CullFace);
        }
        private static void CreatePerInstanceAttributes(VAO vao, Shader shader)
        {
            //per instance attributes
            var rnd = new Random(12);
            Func<float> Rnd01 = () => (float)rnd.NextDouble();
            Func<float> RndCoord = () => (Rnd01() - 0.5f) * 2.0f;
            var instancePositions = new Vector3[particelCount];
            for (int i = 0; i < particelCount; ++i)
            {
                instancePositions[i] = new Vector3(RndCoord(), RndCoord(), RndCoord());
            }
            vao.SetAttribute(shader.GetAttributeLocation("instancePosition"), instancePositions, VertexAttribPointerType.Float, 3, true);

            //todo: students: add per instance attribute speed here
            //var locInstSpeed = shader.GetAttributeLocation("instanceSpeed");
        }
        public void Render()
        {
            if (shaderWatcher.CheckForShaderChange())
            {
                //update geometry when shader changes
                geometry = CreateMesh(shaderWatcher.Shader);
            }
            GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
            var shader = shaderWatcher.Shader;
            shader.Begin();
            GL.Uniform4(shader.GetUniformLocation("lightColor"), new Color4(1f, 1f, 1f, 1f));
            GL.Uniform3(shader.GetUniformLocation("lightPosition"), new Vector3(1, 1, 4));
            GL.Uniform4(shader.GetUniformLocation("ambientLightColor"), new Color4(.2f, .2f, .2f, 1f));
            GL.Uniform4(shader.GetUniformLocation("materialColor"), new Color4(1f, .5f, .5f, 1f));
            Matrix4 cam = camera.CalcMatrix().ToOpenTK();
            GL.UniformMatrix4(shader.GetUniformLocation("camera"), true, ref cam);
            GL.Uniform3(shader.GetUniformLocation("cameraPosition"), camera.CalcPosition().ToOpenTK());

            geometry.Draw();
            shader.End();
        }
Exemple #45
0
        public void Load()
        {
            _program = _assets.Fetch<ShaderProgram>("Main");
            _vbo = new VBO();
            data = new List<Vertex>();
            _tex = _assets.Fetch<Texture>("blank.png");

            const float size = 1f;
            data.Add(new Vertex { Position = new Vector3(0, 0, 0), Colour = Color.Blue.ToVector4() });
            data.Add(new Vertex { Position = new Vector3(size, 0, 0), Colour = Color.Blue.ToVector4() });

            data.Add(new Vertex { Position = new Vector3(0, 0, 0), Colour = Color.Red.ToVector4() });
            data.Add(new Vertex { Position = new Vector3(0, size, 0), Colour = Color.Red.ToVector4() });

            data.Add(new Vertex { Position = new Vector3(0, 0, 0), Colour = Color.Green.ToVector4() });
            data.Add(new Vertex { Position = new Vector3(0, 0, size), Colour = Color.Green.ToVector4() });

            _vbo.Buffer(data.ToArray());
            _vao = new VAO(_program, _vbo);
            Loaded = true;
        }
        public void Load()
        {
            _program = _assets.Fetch<ShaderProgram>("Main");
            _vbo = new VBO();
            _data = new List<Vertex>();

            _tex = _assets.Fetch<Texture>("blank.png");
            stl = new STLLoader("Media/Models/testship.stl");
            var col = Color.FromArgb(255, 94, 169, 198);

            foreach (var element in stl.Elements)
            {
                _data.Add(new Vertex { Position = element.P1.ToVector3(), Normal = element.Normal.ToVector3(), Colour = new Vector4(col.R / 255f, col.G / 255f, col.B / 255f, col.A / 255f) });
                _data.Add(new Vertex { Position = element.P2.ToVector3(), Normal = element.Normal.ToVector3(), Colour = new Vector4(col.R / 255f, col.G / 255f, col.B / 255f, col.A / 255f) });
                _data.Add(new Vertex { Position = element.P3.ToVector3(), Normal = element.Normal.ToVector3(), Colour = new Vector4(col.R / 255f, col.G / 255f, col.B / 255f, col.A / 255f) });
            }

            _vbo.Buffer(_data.ToArray());
            _vao = new VAO(_program, _vbo);

            Loaded = true;
        }
Exemple #47
0
        public void Load()
        {
            _program = _assets.Fetch<ShaderProgram>("Main");
            _vbo = new VBO();
            _tex = _assets.Fetch<Texture>("star.png");
            data = new List<Vertex>();
            var rnd = new Random();
            for (var i = 0; i < 150; i++)
            {
                //rnd.NextDouble()

                var x = rnd.NextFloat(-80f, 80f);
                var y = rnd.NextFloat(-80f, 80f);

                var z = rnd.NextFloat(0f, 10f) - 60.0f;
                AddStar((float)rnd.NextDouble() + 0.1f, new Vector3(x, y,z));
            }

            _vbo.Buffer(data.ToArray());
            _vao = new VAO(_program, _vbo);
            Loaded = true;
        }
Exemple #48
0
        public static void DrawSineLeft(Vector3 color, float f, float a = 100f, float t = 0f)
        {
            if (sineLeft == null)
            {
                Vector3[] sineArray = new Vector3[441];
                int[] elementArray = new int[sineArray.Length];
                for (int i = 0; i < sineArray.Length; i++)
                {
                    sineArray[i] = new Vector3(i - 441 / 2f, 288, 0);
                    elementArray[i] = i;
                }
                VBO<Vector3> sineListVBO = new VBO<Vector3>(sineArray);
                VBO<int> elementListVBO = new VBO<int>(elementArray, BufferTarget.ElementArrayBuffer);
                sineLeft = new VAO<Vector3>(Shaders.SineShader, sineListVBO, "in_position", elementListVBO);
                sineLeft.DrawMode = BeginMode.LineStrip;
            }

            Shaders.SineShader.Use();
            Shaders.SineShader["projectionMatrix"].SetValue(Program.uiProjectionMatrix);
            Shaders.SineShader["viewMatrix"].SetValue(Matrix4.Identity);
            Shaders.SineShader["modelMatrix"].SetValue(Matrix4.CreateTranslation(new Vector3(72 + 441 / 2f, 0, 0)));
            Shaders.SineShader["color"].SetValue(color);
            Shaders.SineShader["timeAmplitudeFrequency"].SetValue(new Vector3(t, a, f));
            Gl.LineWidth(2f);
            sineLeft.Draw();
        }
Exemple #49
0
        protected override void OnLoad(EventArgs e)
        {
            GL.Enable(EnableCap.Texture2D);
            GL.Enable(EnableCap.CullFace);
            GL.Enable(EnableCap.DepthTest);
            GL.Enable(EnableCap.Blend);
            GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);
            _fbo = new FBO(Width,Height);
            _assetManager.Load();
            _shader = _assetManager.Shader<DefaultShaderProgram>();

            var data = new List<OpenGLVertex>
            {
                new OpenGLVertex {Position = new Vector3(-1, -1, 0),TexCoord = new Vector2(0,0)},
                new OpenGLVertex {Position = new Vector3(1, -1, 0),TexCoord = new Vector2(1,0)},
                new OpenGLVertex {Position = new Vector3(1, 1, 0),TexCoord = new Vector2(1,1)},
                new OpenGLVertex {Position = new Vector3(-1, 1, 0),TexCoord = new Vector2(0,1)}
            };

            _vbo = new VBO(data){BeginMode = BeginMode.Quads};
            _vao = new VAO(_assetManager.Shader<FlatShaderProgram>(), _vbo);

            var dotdata = new List<OpenGLVertex>
            {
                new OpenGLVertex {Position = new Vector3(0, 0, 0)},
                new OpenGLVertex {Position = new Vector3(10, 10, 0)},
            };
            _dotsvbo = new VBO(dotdata) { BeginMode = BeginMode.Lines };
            _dotsvao = new VAO(_assetManager.Shader<BasicShaderProgram>(), _dotsvbo);

            _viewManager.Load();

            Bus.Add(new DebugMessage(Timer.LastTickTime, "Loaded OpenGL Window"));
            var err = GL.GetError();
            if (err != ErrorCode.NoError)
                Console.WriteLine("Error at OnLoad: " + err);
        }
        private void Debug()
        {
            var vbo = new VBO();
            foreach (var element in stl.Elements)
            {
                float x = (float)((element.P1.X + element.P2.X + element.P3.X) / 3.0f);
                float y = (float)((element.P1.Y + element.P2.Y + element.P3.Y) / 3.0f);
                float z = (float)((element.P1.Z + element.P2.Z + element.P3.Z) / 3.0f);
                vbo.Data.Add(new Vertex { Position = new Vector3(x,y,z), Colour = Color.Purple.ToVector4() });
                vbo.Data.Add(new Vertex { Position = new Vector3(x, y, z) + (element.Normal * 0.2).ToVector3(), Colour = Color.Purple.ToVector4() });
            }
            vbo.Buffer();
            var vao = new VAO(_program, vbo);

            using (Bind.Shader(_program))
            using (Bind.Texture(_tex))
            using (new Bind(vao))
            {
                _program.UpdateUniform("position", _gameObject.Transformation.ToMatrix4());
                GL.DrawArrays(BeginMode.Lines, 0, vbo.Count);
            }
        }
Exemple #51
0
        public void RenderWithVAOSimple(ShaderProgram program)
        {
            if (chunkVAO == null)
            {
                List<Vector3> vertices = new List<Vector3>();
                List<int> elements = new List<int>();
                for (int x = 0 + offsetX; x < 32 + offsetX; x++)
                {
                    for (int y = 0 + offsetZ; y < 32 + offsetZ; y++)
                    {
                        float h = Noise.Generate((x + 32) / 32f, (y + 32) / 45f);
                        h = (float)Math.Round(h * 8);
                        if(h < 0)
                        {
                            h = -h;
                        }
                        //for(float test = -10; test <= h; h--)
                        AddCube(new Vector3(x, 0, y), new Vector3(x + 1, h + 1, y + 1), vertices, elements);

                    }
                }

                Vector3[] vertex = vertices.ToArray();
                int[] element = elements.ToArray();
                Vector3[] normals = OpenGL.Geometry.CalculateNormals(vertex, element);
                vertCount = vertex.Length;
                chunkVAO = new VAO(program, new VBO<Vector3>(vertex), new VBO<Vector3>(normals), new VBO<int>(element, BufferTarget.ElementArrayBuffer, BufferUsageHint.StaticRead));
            }

            program["model_matrix"].SetValue(ModelMatrix);

            chunkVAO.Draw();
        }
Exemple #52
0
        public static void Init()
        {
            BackgroundQuad = Utilities.CreateQuad(Shaders.SimpleTexturedShader);
            BackgroundTexture = new Texture("media/background.png");
            BulletTexture = new Texture("media/bullet.png");
            BulletQuad = Utilities.CreateQuad(Shaders.SimpleTexturedShader, Vector2.Zero, new Vector2(24, 24));

            VBO<Vector3> vertices = new VBO<Vector3>(new Vector3[] { new Vector3(0, 0, 0), new Vector3(1, 0, 0), new Vector3(1, 1, 0), new Vector3(0, 1, 0) });
            VBO<int> indices = new VBO<int>(new int[] { 0, 1, 2, 3, 0 }, BufferTarget.ElementArrayBuffer);
            BoxQuad = new VAO(Shaders.SimpleColoredShader, vertices, indices);
            BoxQuad.DrawMode = BeginMode.LineStrip;

            indices = new VBO<int>(new int[] { 0, 1, 2, 3 }, BufferTarget.ElementArrayBuffer);
            StencilQuad = new VAO(Shaders.SimpleColoredShader, vertices, indices);
            StencilQuad.DrawMode = BeginMode.Quads;

            vertices = new VBO<Vector3>(new Vector3[] { new Vector3(0.5, -0.01, 0), new Vector3(0.5, 1.01, 0), new Vector3(-0.01, 0.5, 0), new Vector3(1.01, 0.5, 0) });
            indices = new VBO<int>(new int[] { 2, 3, 0, 1 }, BufferTarget.ElementArrayBuffer);
            CrosshairVAO = new VAO(Shaders.SimpleColoredShader, vertices, indices);
            CrosshairVAO.DrawMode = BeginMode.Lines;

            Shaders.FontShader.Use();
            Shaders.FontShader["viewMatrix"].SetValue(Matrix4.Identity);

            Shaders.SimpleColoredShader.Use();
            Shaders.SimpleColoredShader["viewMatrix"].SetValue(Matrix4.Identity);
        }
Exemple #53
0
 private void Dispose(bool disposing)
 {
     if (VAO != null)
     {
         VAO.DisposeChildren = true;
         VAO.Dispose();
         VAO = null;
     }
 }
Exemple #54
0
        protected override void OnLoad(EventArgs e)
        {
            GL.Enable(EnableCap.Texture2D);
            GL.Enable(EnableCap.CullFace);
            GL.Enable(EnableCap.DepthTest);
            GL.Enable(EnableCap.Blend);
            GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);
            GL.PointSize(5f);

            _ubo = new CameraUBO();
            _shader = new BasicShaderProgram(_ubo);

            _vao = new VAO(_shader, new VBO(new List<Vertex>(FetchData(_tree))) { BeginMode = BeginMode.Quads });

            var green = new Color4(0.156f, 0.627f, 0.353f, 1.0f).ToVector4();
            var data = new List<Vertex>();

            foreach (var element in stl.Elements)
            {
                data.Add(new Vertex { Colour = green, Position = element.P1.ToVector3() });
                data.Add(new Vertex { Colour = green, Position = element.P2.ToVector3() });
                data.Add(new Vertex { Colour = green, Position = element.P3.ToVector3() });
            }

            _vao2 = new VAO(_shader, new VBO(data) { BeginMode = BeginMode.Triangles });

            var filled = _tree.Flatten().Where(o => o.State == NodeState.Filled).ToArray();

            _vaoFilled = new VAO(_shader, new VBO(new List<Vertex>(FetchDataSolid(filled))) { BeginMode = BeginMode.Quads });

            var err = GL.GetError();
            if (err != ErrorCode.NoError)
                Console.WriteLine("Error at OnLoad: " + err);
        }
Exemple #55
0
        public void RenderWithVAOGreedy(ShaderProgram program, bool draw = true)
        {
            if (chunkVAO == null)
            {
                List<Vector3> vertices = new List<Vector3>();
                List<int> elements = new List<int>();

                for (int d = 0; d < 3; d++)
                {
                    int i, j, k, l, w, h, u = (d + 1) % 3, v = (d + 2) % 3;
                    int[] x = new int[3];
                    int[] q = new int[3];
                    bool[] mask = new bool[32 * 32];

                    q[d] = 1;

                    for (x[d] = -1; x[d] < 32; )
                    {
                        // Compute the mask
                        int n = 0;
                        for (x[v] = 0; x[v] < 32; ++x[v])
                        {
                            for (x[u] = 0; x[u] < 32; ++x[u])
                            {
                                mask[n++] = (0 <= x[d] ? data(x[0], x[1], x[2]) : false) !=
                                    (x[d] < 32 - 1 ? data(x[0] + q[0], x[1] + q[1], x[2] + q[2]) : false);
                            }
                        }

                        // Increment x[d]
                        ++x[d];

                        // Generate mesh for mask using lexicographic ordering
                        n = 0;
                        for (j = 0; j < 32; ++j)
                        {
                            for (i = 0; i < 32; )
                            {
                                if (mask[n])
                                {
                                    // Compute width
                                    for (w = 1; i + w < 32 && mask[n + w]; ++w) ;

                                    // Compute height (this is slightly awkward
                                    var done = false;
                                    for (h = 1; j + h < 32; ++h)
                                    {
                                        for (k = 0; k < w; ++k)
                                        {
                                            if (!mask[n + k + h * 32])
                                            {
                                                done = true;
                                                break;
                                            }
                                        }
                                        if (done) break;
                                    }

                                    // Add quad
                                    x[u] = i; x[v] = j;
                                    int[] du = new int[3];
                                    int[] dv = new int[3];
                                    du[u] = w;
                                    dv[v] = h;

                                    AddFace(new Vector3(x[0], x[1], x[2]),
                                            new Vector3(x[0] + du[0], x[1] + du[1], x[2] + du[2]),
                                            new Vector3(x[0] + du[0] + dv[0], x[1] + du[1] + dv[1], x[2] + du[2] + dv[2]),
                                            new Vector3(x[0] + dv[0], x[1] + dv[1], x[2] + dv[2]), vertices, elements);

                                    // Zero-out mask
                                    for (l = 0; l < h; ++l)
                                    {
                                        for (k = 0; k < w; ++k)
                                        {
                                            mask[n + k + l * 32] = false;
                                        }
                                    }

                                    // Increment counters and continue
                                    i += w; n += w;
                                }
                                else
                                {
                                    ++i; ++n;
                                }
                            }
                        }
                    }
                }

                Vector3[] vertex = vertices.ToArray();
                int[] element = elements.ToArray();
                Vector3[] normals = OpenGL.Geometry.CalculateNormals(vertex, element);

                chunkVAO = new VAO(program, new VBO<Vector3>(vertex), new VBO<Vector3>(normals), new VBO<int>(element, BufferTarget.ElementArrayBuffer, BufferUsageHint.StaticRead));
            }

            if (draw)
            {
                program["model_matrix"].SetValue(ModelMatrix);

                chunkVAO.Draw();
            }
        }