/// <summary>
        ///
        /// </summary>
        /// <param name="arg"></param>
        /// <param name="x">mouse position(Left Down is (0, 0)).</param>
        /// <param name="y">mouse position(Left Down is (0, 0)).</param>
        /// <param name="lastVertexId"></param>
        /// <param name="modernRenderer"></param>
        /// <returns></returns>
        internal override uint[] Search(PickEventArgs arg,
                                        uint lastVertexId, ZeroIndexPicker picker)
        {
            OneIndexBuffer buffer = GLBuffer.Create(IndexBufferElementType.UInt, 6, DrawMode.Lines, BufferUsage.StaticDraw);

            unsafe
            {
                var array = (uint *)buffer.MapBuffer(MapBufferAccess.WriteOnly);
                array[0] = lastVertexId - 2; array[1] = lastVertexId - 0;
                array[2] = lastVertexId - 4; array[3] = lastVertexId - 2;
                array[4] = lastVertexId - 0; array[5] = lastVertexId - 4;
                buffer.UnmapBuffer();
            }

            picker.Renderer.Render4InnerPicking(arg, buffer);
            uint id = ColorCodedPicking.ReadStageVertexId(arg.X, arg.Y);

            buffer.Dispose();

            if (id + 4 == lastVertexId)
            {
                return(new uint[] { id + 4, id, });
            }
            else
            {
                return(new uint[] { id - 2, id, });
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="arg"></param>
        /// <param name="lastVertexId"></param>
        /// <param name="picker"></param>
        /// <returns></returns>
        internal override uint[] Search(PickingEventArgs arg,
                                        uint lastVertexId, DrawArraysPicker picker)
        {
            IndexBuffer buffer = GLBuffer.Create(IndexBufferElementType.UInt, 6, BufferUsage.StaticDraw);

            unsafe
            {
                var array = (uint *)buffer.MapBuffer(MapBufferAccess.WriteOnly);
                array[0] = lastVertexId - 2; array[1] = lastVertexId - 0;
                array[2] = lastVertexId - 4; array[3] = lastVertexId - 2;
                array[4] = lastVertexId - 0; array[5] = lastVertexId - 4;
                buffer.UnmapBuffer();
            }
            var cmd = new DrawElementsCmd(buffer, DrawMode.Lines);

            picker.Node.Render4InnerPicking(arg, ControlMode.ByFrame, cmd);
            uint id = ColorCodedPicking.ReadStageVertexId(arg.X, arg.Y);

            buffer.Dispose();

            if (id + 4 == lastVertexId)
            {
                return(new uint[] { id + 4, id, });
            }
            else
            {
                return(new uint[] { id - 2, id, });
            }
        }
Example #3
0
 public GLBuffer CreateBuffer(string bufferName, BufferTarget target)
 {
     this.Bind();
     GLBuffer buffer = new GLBuffer(target);
     this.arrays.Add(bufferName, buffer);
     return buffer;
 }
Example #4
0
        protected override void OnHandleCreated(EventArgs e)
        {
            base.OnHandleCreated(e);

            _display = new EGLDisplay(Handle);

            _program = LoadProgram(@"
				attribute vec4 vPosition;
				void main()            
				{                          
					gl_Position = vPosition;
				}
			"            , @"
				precision mediump float; 
				void main()
				{
					gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
				}
			"            );

            float[] vertices =
            {
                0.0f,   0.5f, 0.0f,
                -0.5f, -0.5f, 0.0f,
                0.5f,  -0.5f, 0.0f
            };

            _buffer = new GLBuffer <float>(vertices.Length);

            _buffer.Put(vertices);
        }
        private unsafe void InitLighting()
        {
            LoadLightingShaders();

            RegenerateLightingRenderTargets();

            // Occlusion VAO.
            // Only handles positions, no other vertex data necessary.
            _occlusionVao = new GLHandle(GL.GenVertexArray());
            GL.BindVertexArray(_occlusionVao.Handle);

            ObjectLabelMaybe(ObjectLabelIdentifier.VertexArray, _occlusionVao, nameof(_occlusionVao));

            _occlusionVbo = new GLBuffer(this, BufferTarget.ArrayBuffer, BufferUsageHint.DynamicDraw,
                                         nameof(_occlusionVbo));

            _occlusionEbo = new GLBuffer(this, BufferTarget.ElementArrayBuffer, BufferUsageHint.DynamicDraw,
                                         nameof(_occlusionEbo));

            GL.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, false, sizeof(Vector3), IntPtr.Zero);
            GL.EnableVertexAttribArray(0);

            // FOV FBO.
            _fovRenderTarget = CreateRenderTarget((ShadowMapSize, 1),
                                                  new RenderTargetFormatParameters(RenderTargetColorFormat.R32F, true),
                                                  new TextureSampleParameters {
                WrapMode = TextureWrapMode.Repeat
            }, "FOV depth render target");

            _fovDepthTextureObject = _fovRenderTarget.Texture;
        }
Example #6
0
        private void DrawInitVertices()
        {
            //Console.WriteLine(WGL.wglGetCurrentContext());
            _verticesPositionBuffer  = GLBuffer.Create();
            _verticesNormalBuffer    = GLBuffer.Create();
            _verticesTexcoordsBuffer = GLBuffer.Create();
            _verticesColorsBuffer    = GLBuffer.Create();
            _verticesWeightsBuffer   = GLBuffer.Create();
            _shader = new GLShader(
                typeof(OpenglGpuImpl).Assembly.GetManifestResourceStream("CSPspEmu.Core.Gpu.Impl.Opengl.shader.vert")
                .ReadAllContentsAsString(),
                typeof(OpenglGpuImpl).Assembly.GetManifestResourceStream("CSPspEmu.Core.Gpu.Impl.Opengl.shader.frag")
                .ReadAllContentsAsString()
                );
            Console.WriteLine("###################################");
            foreach (var uniform in _shader.Uniforms)
            {
                Console.WriteLine(uniform);
            }
            foreach (var attribute in _shader.Attributes)
            {
                Console.WriteLine(attribute);
            }
            Console.WriteLine("###################################");

            _shader.BindUniformsAndAttributes(ShaderInfo);
        }
        } = new Dictionary <object, object>();                                                            // tag to user data, optional

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="name">Name of set</param>
        /// <param name="rlist">Render list to draw into</param>
        /// <param name="textures"> number of 2D textures to allow maximum (limited by GL)</param>
        /// <param name="estimateditemspergroup">Estimated objects per group, this adds on vertext buffer space to allow for mat4 alignment. Smaller means more allowance.</param>
        /// <param name="mingroups">Minimum number of groups</param>
        /// <param name="objectshader">Shader for objects</param>
        /// <param name="objectbuffer">Object buffer to use</param>
        /// <param name="objectvertexes">Number of object vertexes</param>
        /// <param name="objrc">The object render state control</param>
        /// <param name="objpt">The object draw primitive type</param>
        /// <param name="textshader">Text shader for labels</param>
        /// <param name="texturesize">The size of the label</param>
        /// <param name="textrc">The text render state</param>
        /// <param name="textureformat">The texture format for the text</param>
        /// <param name="debuglimittexturedepth">For debug, set this to limit maximum number of entries. 0 = off</param>
        public GLSetOfObjectsWithLabels(string name,
                                        GLRenderProgramSortedList rlist,
                                        int textures,
                                        int estimateditemspergroup,
                                        int mingroups,                                                                                                      // minimum number of groups
                                        IGLProgramShader objectshader, GLBuffer objectbuffer, int objectvertexes, GLRenderState objrc, PrimitiveType objpt, // object shader, buffer, vertexes and its rendercontrol
                                        IGLProgramShader textshader, Size texturesize, GLRenderState textrc, SizedInternalFormat textureformat,             // text shader, text size, and rendercontrol
                                        int debuglimittexturedepth = 0)                                                                                     // set to limit texture depth per set
        {
            this.name     = name;
            this.robjects = rlist;
            this.textures = textures;
            this.estimateditemspergroup = estimateditemspergroup;
            this.mingroups           = mingroups;
            this.objectshader        = objectshader;
            this.objectbuffer        = objectbuffer;
            this.objectvertexescount = objectvertexes;
            this.objrc             = objrc;
            this.objpt             = objpt;
            this.textshader        = textshader;
            this.texturesize       = texturesize;
            this.textrc            = textrc;
            this.textureformat     = textureformat;
            this.limittexturedepth = debuglimittexturedepth;
        }
Example #8
0
        private unsafe void CreateMiscGLObjects()
        {
            // Quad drawing.
            {
                var quadVertices = new[]
                {
                    new Vertex2D(1, 0, 1, 1),
                    new Vertex2D(0, 0, 0, 1),
                    new Vertex2D(1, 1, 1, 0),
                    new Vertex2D(0, 1, 0, 0)
                };

                QuadVBO = new GLBuffer <Vertex2D>(this, BufferTarget.ArrayBuffer, BufferUsageHint.StaticDraw, quadVertices,
                                                  nameof(QuadVBO));

                QuadVAO = new GLHandle((uint)GL.GenVertexArray());
                GL.BindVertexArray(QuadVAO.Handle);
                ObjectLabelMaybe(ObjectLabelIdentifier.VertexArray, QuadVAO, nameof(QuadVAO));
                // Vertex Coords
                GL.VertexAttribPointer(0, 2, VertexAttribPointerType.Float, false, Vertex2D.SizeOf, 0);
                GL.EnableVertexAttribArray(0);
                // Texture Coords.
                GL.VertexAttribPointer(1, 2, VertexAttribPointerType.Float, false, Vertex2D.SizeOf, 2 * sizeof(float));
                GL.EnableVertexAttribArray(1);
            }

            // Batch rendering
            {
                BatchVBO = new GLBuffer(this, BufferTarget.ArrayBuffer, BufferUsageHint.DynamicDraw,
                                        Vertex2D.SizeOf * BatchVertexData.Length, nameof(BatchVBO));

                BatchVAO = new GLHandle(GL.GenVertexArray());
                GL.BindVertexArray(BatchVAO.Handle);
                ObjectLabelMaybe(ObjectLabelIdentifier.VertexArray, BatchVAO, nameof(BatchVAO));
                // Vertex Coords
                GL.VertexAttribPointer(0, 2, VertexAttribPointerType.Float, false, Vertex2D.SizeOf, 0);
                GL.EnableVertexAttribArray(0);
                // Texture Coords.
                GL.VertexAttribPointer(1, 2, VertexAttribPointerType.Float, false, Vertex2D.SizeOf, 2 * sizeof(float));
                GL.EnableVertexAttribArray(1);

                BatchEBO = new GLBuffer(this, BufferTarget.ElementArrayBuffer, BufferUsageHint.DynamicDraw,
                                        sizeof(ushort) * BatchIndexData.Length, nameof(BatchEBO));
            }

            ProjViewUBO = new GLBuffer(this, BufferTarget.UniformBuffer, BufferUsageHint.StreamDraw, nameof(ProjViewUBO));
            ProjViewUBO.Reallocate(sizeof(ProjViewMatrices));

            GL.BindBufferBase(BufferRangeTarget.UniformBuffer, ProjViewBindingIndex, ProjViewUBO.ObjectHandle);

            UniformConstantsUBO = new GLBuffer(this, BufferTarget.UniformBuffer, BufferUsageHint.StreamDraw,
                                               nameof(UniformConstantsUBO));
            UniformConstantsUBO.Reallocate(sizeof(UniformConstants));

            GL.BindBufferBase(BufferRangeTarget.UniformBuffer, UniformConstantsBindingIndex,
                              UniformConstantsUBO.ObjectHandle);

            EntityPostRenderTarget = CreateRenderTarget(Vector2i.One * 4 * EyeManager.PIXELSPERMETER,
                                                        RenderTargetColorFormat.Rgba8Srgb, name: nameof(EntityPostRenderTarget), hasStencilBuffer: true);
        }
        protected override void DoInitialize()
        {
            {
                // particleSimulator-fountain.comp is also OK.
                var shaderCode = new ShaderCode(File.ReadAllText(@"shaders\ParticleSimulatorRenderer\particleSimulator.comp"), ShaderType.ComputeShader);
                this.computeProgram = shaderCode.CreateProgram();
            }
            {
                GLBuffer buffer  = this.positionBuffer;
                Texture  texture = buffer.DumpBufferTexture(OpenGL.GL_RGBA32F, autoDispose: false);
                texture.Initialize();
                this.positionTexture = texture;
            }
            {
                GLBuffer buffer  = this.velocityBuffer;
                Texture  texture = buffer.DumpBufferTexture(OpenGL.GL_RGBA32F, autoDispose: false);
                texture.Initialize();
                this.velocityTexture = texture;
            }
            {
                const int     length = 64;
                UniformBuffer buffer = UniformBuffer.Create(typeof(vec4), length, BufferUsage.DynamicCopy);
                buffer.Bind();
                glBindBufferBase((uint)BindBufferBaseTarget.UniformBuffer, 0, buffer.BufferId);
                buffer.Unbind();
                this.attractorBuffer = buffer;

                OpenGL.CheckError();
            }
        }
Example #10
0
        public IndexBuffer GetIndexBuffer()
        {
            if (this.indexBuffer == null)
            {
                int            length = this.SideLength * (this.SideLength - 1) * 2;
                OneIndexBuffer buffer = GLBuffer.Create(IndexBufferElementType.UInt, length, DrawMode.TriangleStrip, BufferUsage.StaticDraw);
                unsafe
                {
                    IntPtr pointer = buffer.MapBuffer(MapBufferAccess.WriteOnly);
                    var    array   = (uint *)pointer;
                    for (int k = 0; k < this.SideLength - 1; k++)
                    {
                        for (int i = 0; i < this.SideLength; i++)
                        {
                            if (k % 2 == 0)
                            {
                                array[(i + k * this.SideLength) * 2 + 0] = (uint)(i + (k + 1) * this.SideLength);
                                array[(i + k * this.SideLength) * 2 + 1] = (uint)(i + (k + 0) * this.SideLength);
                            }
                            else
                            {
                                array[(i + k * this.SideLength) * 2 + 0] = (uint)(this.SideLength - 1 - i + (k + 0) * this.SideLength);
                                array[(i + k * this.SideLength) * 2 + 1] = (uint)(this.SideLength - 1 - i + (k + 1) * this.SideLength);
                            }
                        }
                    }
                    buffer.UnmapBuffer();
                }
                this.indexBuffer = buffer;
            }

            return(this.indexBuffer);
        }
Example #11
0
        private MapChunkData _initChunkBuffers(IMapGrid grid, IMapChunk chunk)
        {
            var vao = (uint)GL.GenVertexArray();

            GL.BindVertexArray(vao);

            var vboSize = _verticesPerChunk(chunk) * Vertex2D.SizeOf;
            var eboSize = _indicesPerChunk(chunk) * sizeof(ushort);

            var vbo = new GLBuffer(this, BufferTarget.ArrayBuffer, BufferUsageHint.DynamicDraw,
                                   vboSize, $"Grid {grid.Index} chunk {chunk.Indices} VBO");
            var ebo = new GLBuffer(this, BufferTarget.ElementArrayBuffer, BufferUsageHint.DynamicDraw,
                                   eboSize, $"Grid {grid.Index} chunk {chunk.Indices} EBO");

            ObjectLabelMaybe(ObjectLabelIdentifier.VertexArray, vao, $"Grid {grid.Index} chunk {chunk.Indices} VAO");
            // Vertex Coords
            GL.VertexAttribPointer(0, 2, VertexAttribPointerType.Float, false, Vertex2D.SizeOf, 0);
            GL.EnableVertexAttribArray(0);
            // Texture Coords.
            GL.VertexAttribPointer(1, 2, VertexAttribPointerType.Float, false, Vertex2D.SizeOf, 2 * sizeof(float));
            GL.EnableVertexAttribArray(1);

            // Assign VBO and EBO to VAO.
            // OpenGL 3.x is such a good API.
            vbo.Use();
            ebo.Use();

            var datum = new MapChunkData(vao, vbo, ebo)
            {
                Dirty = true
            };

            _mapChunkData[grid.Index].Add(chunk.Indices, datum);
            return(datum);
        }
Example #12
0
        /// <summary>
        /// 在三角形图元中拾取指定位置的Line
        /// </summary>
        /// <param name="arg"></param>
        /// <param name="flatColorVertexId">三角形图元的最后一个顶点</param>
        /// <param name="picker"></param>
        /// <returns></returns>
        internal override uint[] Search(PickingEventArgs arg,
                                        uint flatColorVertexId, DrawArraysPicker picker)
        {
            // 创建临时索引
            IndexBuffer buffer = GLBuffer.Create(IndexBufferElementType.UInt, 6, BufferUsage.StaticDraw);

            unsafe
            {
                var array = (uint *)buffer.MapBuffer(MapBufferAccess.WriteOnly);
                array[0] = flatColorVertexId - 1; array[1] = flatColorVertexId - 0;
                array[2] = flatColorVertexId - 2; array[3] = flatColorVertexId - 1;
                array[4] = flatColorVertexId - 0; array[5] = flatColorVertexId - 2;
                buffer.UnmapBuffer();
            }
            var cmd = new DrawElementsCmd(buffer, DrawMode.Lines);

            // 用临时索引渲染此三角形图元(仅渲染此三角形图元)
            picker.Node.Render4InnerPicking(arg, cmd);
            // id是拾取到的Line的Last Vertex Id
            uint id = ColorCodedPicking.ReadStageVertexId(arg.X, arg.Y);

            buffer.Dispose();

            // 对比临时索引,找到那个Line
            if (id + 2 == flatColorVertexId)
            {
                return(new uint[] { id + 2, id, });
            }
            else
            {
                return(new uint[] { id - 1, id, });
            }
        }
 /// <summary> Construct, on an item list, a buffer with this size </summary>
 public GLMatrixBufferWithGenerations(GLItemsList items, int maximumsize)
 {
     MatrixBuffer = new GLBuffer();
     items.Add(MatrixBuffer);
     Max = maximumsize;
     MatrixBuffer.AllocateBytes(Max * GLLayoutStandards.Mat4size);
     MatrixBuffer.AddPosition(0);        // CreateMatrix4 needs to have a position
 }
 public WellRenderer()
 {
     _vbo = new GLBuffer <GenericVertex>(BufferTarget.ArrayBuffer);
     _vbo.Bind();
     _vbo.SetSize(
         LineRenderer.StartingLineCount * wellsize,
         BufferUsageHint.DynamicDraw);
     _vbo.Unbind();
 }
Example #15
0
 private void CreateIndirect(int indirectbuffer)
 {
     while (Indirects.Count < indirectbuffer + 1)
     {
         var buf = new GLBuffer(indirectsize, true, bufferusage);
         items.Add(buf);
         Indirects.Add(buf);
     }
 }
Example #16
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="items">Item list to store buffers into</param>
 /// <param name="vertsize">Size of vertex buffer</param>
 /// <param name="indirectsize">Size of indirect buffer</param>
 /// <param name="std430">Std430 layout</param>
 /// <param name="bufferusagehint">Buffer usage hint</param>
 public GLVertexBufferIndirect(GLItemsList items, int vertsize, int indirectsize, bool std430 = false, BufferUsageHint bufferusagehint = BufferUsageHint.StaticDraw)
 {
     this.items        = items;
     this.indirectsize = indirectsize;
     this.bufferusage  = bufferusagehint;
     this.context      = GLStatics.GetContext();
     Vertex            = new GLBuffer(vertsize, std430, bufferusagehint);
     items.Add(Vertex);
 }
Example #17
0
        public Rain()
        {
            buffer = new GLBuffer(2000, 200);

            shader = new Shader();
            shader.Attach(ShaderTypes.Vertex, "Rain.vert");
            shader.Attach(ShaderTypes.Geometry, "Rain.geom");
            shader.Attach(ShaderTypes.Fragment, "Rain.frag");
            shader.AddAttribute <float>(3, GL_FLOAT);
            shader.Initialize();
        }
Example #18
0
 public LineAccelRenderer()
 {
     _accelbuffer = new GLBuffer <GenericVertex>(BufferTarget.ArrayBuffer);
     _accelbuffer.Bind();
     _accelbuffer.SetSize((LineRenderer.StartingLineCount / 2) * 3, BufferUsageHint.DynamicDraw, false);
     _accelbuffer.Unbind();
     _accelibo = new GLBuffer <int>(BufferTarget.ElementArrayBuffer);
     _accelibo.Bind();
     _accelibo.SetSize((LineRenderer.StartingLineCount / 2) * 3, BufferUsageHint.DynamicDraw, false);
     _accelibo.Unbind();
 }
Example #19
0
 /// <summary> Called by render list and executes the operation </summary>
 public override void Execute(GLMatrixCalc c)
 {
     GLTransformFeedback.End();
     for (int i = 0; i < TransformFeedbackOperation.VaryingBuffers.Length; i++)
     {
         //System.Diagnostics.Debug.WriteLine($"TF {TransformFeedbackOperation.Id} bp {i}");
         GLBuffer.UnbindTransformFeedback(i, TransformFeedbackOperation.Id);
     }
     GLStatics.Check();
     GLTransformFeedback.UnBind();
     GLStatics.Check();
 }
Example #20
0
        private void AddedNewGroup(int groupno, GLBuffer matrixbuffer)      // callback due to new group added, we need a texture and a RI
        {
            var texture = new GLTexture2DArray();

            items.Add(texture);
            texture.CreateOrUpdateTexture(bitmapsize.Width, bitmapsize.Height, matrixbuffers.Matricesperbuffer, textureformat, texmipmaplevels);
            grouptextureslist.Add(texture); // need to keep these for later addition

            var rd             = new RenderData(texture);
            var renderableItem = GLRenderableItem.CreateMatrix4(items, OpenTK.Graphics.OpenGL4.PrimitiveType.Quads, renderstate, matrixbuffer, 0, 4, rd, ic: 0);     //drawcount=4 (4 vertexes made up by shader), ic will be set in Add.

            renderlist.Add(shader, name + ":" + groupno, renderableItem);
            grouprenderlist.Add(renderableItem);
        }
Example #21
0
 private GLShaderFilter(int Width, int Height, GLShader Shader)
 {
     this.Shader = Shader;
     SetSize(Width, Height);
     this.PositionBuffer = GLBuffer.Create().SetData<float>(new float[] {
         -1f, -1f,
         +1f, -1f,
         -1f, +1f,
         +1f, +1f,
     });
     this.TexcoordsBuffer = GLBuffer.Create().SetData<float>(new float[] {
         0f, 0f,
         1f, 0f,
         0f, 1f,
         1f, 1f,
     });
 }
Example #22
0
        public LineRenderer(Shader sh)
        {
            if (sh == null)
            {
                throw new ArgumentNullException("shader");
            }
            _shader = sh;
            _vbo    = new GLBuffer <LineVertex>(BufferTarget.ArrayBuffer);
            _ibo    = new GLBuffer <int>(BufferTarget.ElementArrayBuffer);
            _vbo.Bind();
            _vbo.SetSize(StartingLineCount * linesize, BufferUsageHint.DynamicDraw);
            _vbo.Unbind();

            _ibo.Bind();
            _ibo.SetSize(StartingLineCount * linesize, BufferUsageHint.DynamicDraw);
            _ibo.Unbind();
        }
Example #23
0
        private bool disposedValue = false; // To detect redundant calls

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    CurrentTexture.Dispose();
                    Dot.Dispose();
                }


                ibo = null;
                vbo = null;
                // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
                // TODO: set large fields to null.

                disposedValue = true;
            }
        }
        /// <summary>
        /// Random stars in a box, filling a buffer
        /// </summary>
        /// <param name="buffer">GL Buffer</param>
        /// <param name="number">Count</param>
        /// <param name="left">Left side of box</param>
        /// <param name="right">Right side of box</param>
        /// <param name="front">Front side of box</param>
        /// <param name="back">Back side of box</param>
        /// <param name="top">Top side of box</param>
        /// <param name="bottom">Bottom side of box</param>
        /// <param name="rnd">Random class to get values from, or null for autocreate</param>
        /// <param name="seed">Seed for random class if rnd=null </param>
        /// <param name="w">Value for Vector4.w</param>
        /// <returns>Vector4[]</returns>

        public static void RandomStars4(GLBuffer buffer, int number, float left, float right, float front, float back, float top, float bottom,
                                        Random rnd = null, int seed = 23, float w = 1)
        {
            if (rnd == null)
            {
                rnd = new Random(seed);
            }

            buffer.AlignFloat();

            for (int s = 0; s < number; s++)
            {
                float[] a = new float[] { rnd.Next(100000) * (right - left) / 100000.0f + left,
                                          rnd.Next(100000) * (top - bottom) / 100000.0f + bottom,
                                          rnd.Next(100000) * (back - front) / 100000.0f + front,
                                          w };
                buffer.WriteCont(a);
            }
        }
Example #25
0
            public GLVertexArrayObject(ShaderProgram shader, float[] positionData, float[] colorData)
            {
                if (shader != null) //duh?
                {
                    //create the buffer objects for position and color data
                    positionBuffer = new GLBuffer(positionData);
                    colorBuffer    = new GLBuffer(colorData);
                    //get an ID for a VAO in the gpu vram. it's not created yet
                    VAO_ID = Gl.GenVertexArray();
                    //now create the VAO and tell OpenGL we want to use it
                    Gl.BindVertexArray(VAO_ID);

                    //tell OpenGL that we are now currently working on the position buffer
                    Gl.BindBuffer(BufferTarget.ArrayBuffer, positionBuffer.BufferID);
                    //tell OpenGL how to interpret the data that is contained inside this buffer
                    //here's what each argument of the function does. this is a very important function.

                    //this buffer contains the data that should be passed to the variable in the shader
                    //  that is at the location specified by attribPositionLoc, aka the "aPosition" variable
                    //there are 3 pieces of data that this variable uses per vertex
                    //the data is of type float
                    //the data describes a position in the virtual 3D space, as opposed to the 2D space on your screen
                    //  (aka OpenGL has to calculate where the 3D point will end up on the 2D screen.
                    //      its the whole 3D depth calculation thingy idk how to explain)
                    //the size of the gap between data for one vertex and data for the next vertex is 0
                    //start processing the data 0 bytes past the location specified
                    Gl.VertexAttribPointer((uint)shader.attribPositionLoc, 3, VertexAttribType.Float, false, 0, IntPtr.Zero);

                    //turn on this attribute
                    Gl.EnableVertexAttribArray((uint)shader.attribPositionLoc);

                    //same as above but for the color buffer
                    Gl.BindBuffer(BufferTarget.ArrayBuffer, colorBuffer.BufferID);
                    Gl.VertexAttribPointer((uint)shader.attribColorLoc, 3, VertexAttribType.Float, false, 0, IntPtr.Zero);
                    Gl.EnableVertexAttribArray((uint)shader.attribColorLoc);
                    //tell OpenGL we want to use the VAO at location 0
                    //there's no VAO there
                    //this basically has the effect of unbinding the VAO, so that we keep its saved state data and dont
                    //  accidentally mess with it further
                    Gl.BindVertexArray(0);
                }
            }
Example #26
0
        public Program() : base(1280, 720, "OpenGL Framework test")
        {
            VSync = VSyncMode.Off;

            Console.Title = $"{GL.GetString(StringName.Vendor)} OpenGL {GL.GetString(StringName.Version)} GLSL {GL.GetString(StringName.ShadingLanguageVersion)}";

            vb = new GLBuffer <Vertex>();
            vb.SetData(VertexFactory.GetQuad());

            batch = new BatchRenderer2D();

            tex = new Texture2D("./lmao.png");

            shader = new Shader("./vert.glsl", "./frag.glsl");
            shader.AddUniform("projectionMatrix");
            shader.AddUniform("inputColor");
            shader.AddUniform("tex");

            GL.ActiveTexture(TextureUnit.Texture0);
        }
Example #27
0
        private void CreateGrid()
        {
            var vertices = new List <Vector3>();

            for (float i = -10; i <= 10; i += 0.5f)
            {
                vertices.Add(new Vector3(i, 0, -10));
                vertices.Add(new Vector3(i, 0, 10));
                vertices.Add(new Vector3(-10, 0, i));
                vertices.Add(new Vector3(10, 0, i));
            }

            mGridVertexArrayId = GL.GenVertexArray();
            GL.BindVertexArray(mGridVertexArrayId);

            mGridVertexBuffer = new GLBuffer <Vector3>(BufferTarget.ArrayBuffer, vertices.ToArray(), 12, BufferUsageHint.StaticDraw);

            GL.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, false, mGridVertexBuffer.Stride, 0);
            GL.EnableVertexAttribArray(0);
        }
Example #28
0
        public Model(ObjFile objModel, int groupNum, ShaderProgram program)
        {
            var group = objModel.Groups[groupNum];
            var tempPos = new List<Vector3> ();
            var tempTex = new List<Vector2> ();
            foreach (ObjFace f in group.Faces) {
                foreach (ObjFaceVertex vert in f.Vertices) {
                    tempPos.Add (objModel.Vertices[vert.VertexIndex - 1]);
                    tempTex.Add (objModel.Textures[vert.TextureIndex - 1]);
                }
            }
            var v_pos = new GLBuffer<Vector3> (GLBufferSettings.StaticDraw3FloatArray, tempPos);
            var v_tex = new GLBuffer<Vector2> (GLBufferSettings.StaticDraw2FloatArray, tempTex);
            var m_ind = new GLBuffer<uint> (GLBufferSettings.StaticIndices, Array.ConvertAll<int, uint> (Enumerable.Range (0, tempPos.Count).ToArray (), x => (uint) x));
            Geometry = new Geometry (BeginMode.Quads)
                .AddBuffer ("v_pos", v_pos)
                .AddBuffer ("v_tex", v_tex);

            Position = Vector3.Zero;
            Scale = Vector3.One;
            Rotation = Vector3.Zero;
        }
Example #29
0
        protected override void Initialize()
        {
            texture = Content.Load <Texture2D> ("particles_test.png", TextureConfiguration.Nearest);

            program = Content.Load <ShaderProgram> ("particle");

            positions = new GLBuffer <Vector4> (GLBufferSettings.StaticDraw4FloatArray, pos);
            texCoords = new GLBuffer <Vector2> (GLBufferSettings.StaticDraw2FloatArray, textureCoords);
            colors    = new GLBuffer <Vector4> (GLBufferSettings.StaticDraw4FloatArray, col);

            abo = GL.GenVertexArray();
            GL.BindVertexArray(abo);
            positions.PointTo(program.Attrib("v_pos"));
            texCoords.PointTo(program.Attrib("v_tex"));
            colors.PointTo(program.Attrib("v_col"));

            camera = new Camera(60f, Resolution, 0.1f, 64f);

            camera.SetRelativePosition(new Vector3(0, 0, 5));

            base.Initialize();
        }
Example #30
0
        protected override void Initialize()
        {
            texture = Content.Load<Texture2D> ("particles_test.png", TextureConfiguration.Nearest);

            program = Content.Load<ShaderProgram> ("particle");

            positions = new GLBuffer<Vector4> (GLBufferSettings.StaticDraw4FloatArray, pos);
            texCoords = new GLBuffer<Vector2> (GLBufferSettings.StaticDraw2FloatArray, textureCoords);
            colors = new GLBuffer<Vector4> (GLBufferSettings.StaticDraw4FloatArray, col);

            abo = GL.GenVertexArray ();
            GL.BindVertexArray (abo);
            positions.PointTo (program.Attrib ("v_pos"));
            texCoords.PointTo (program.Attrib ("v_tex"));
            colors.PointTo (program.Attrib ("v_col"));

            camera = new Camera (60f, Resolution, 0.1f, 64f);

            camera.SetRelativePosition (new Vector3 (0, 0, 5));

            base.Initialize ();
        }
Example #31
0
        /// <summary>
        /// Constructor, set up the query.
        /// See <href>"https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glBeginQueryIndexed.xhtml"</href>
        /// </summary>
        /// <param name="target">Target may be one of GL_SAMPLES_PASSED, GL_ANY_SAMPLES_PASSED, GL_ANY_SAMPLES_PASSED_CONSERVATIVE, GL_TIME_ELAPSED, GL_TIMESTAMP, GL_PRIMITIVES_GENERATED or GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN. (use openTK IDs)</param>
        /// <param name="index">index of query, normally 0</param>
        /// <param name="createnow">Create query now, or wait until Execute</param>
        /// <param name="querybuffer">Optional, for GLOperationEndQuery, a buffer to store the query data into. Caller must allocate buffer</param>
        public GLOperationQuery(QueryTarget target, int index = 0, bool createnow = false, GLBuffer querybuffer = null)
        {
            this.Target      = target;
            this.Index       = index;
            this.QueryBuffer = querybuffer;

            int id = 0;

            if (createnow)
            {
                GL.CreateQueries(Target, 1, out id);
            }
            else
            {
                GL.GenQueries(1, out id);
            }

            GLStatics.RegisterAllocation(typeof(GLOperationQuery));

            System.Diagnostics.Debug.Assert(id != 0);
            GLStatics.Check();
            this.Id = id;
        }
Example #32
0
        private void Form1_Load(object sender, EventArgs e)
        {
            this.ClientSize = new System.Drawing.Size(800, 600);

            GL = new renderX(800, 600, this.Handle);
            GL.Clear();

            vertexBuffer = new GLBuffer(renderX.PrimitiveTypes.Cube(), 5, MemoryLocation.Heap);
            cubeShader   = new Shader(CubeVS, CubeFS, GLRenderMode.Triangle);

            cameraPosition = new Vector3(0, 0, -100);
            cameraRotation = new Vector3(0, 0, 0);

            GL.SetMatrixData(90, 160, 0);

            GL.ForceCameraPosition(cameraPosition);
            GL.ForceCameraRotation(cameraRotation);

            GL.SetFaceCulling(true, false);


            texture2d    = new GLTexture("container2.png", MemoryLocation.Heap, DuringLoad.Flip);
            TEXTURE_ADDR = (int *)texture2d.GetAddress();

            textureHeight         = texture2d.Height;
            textureWidthMinusOne  = texture2d.Width - 1;
            textureHeightMinusOne = texture2d.Height - 1;


            Timer timer = new Timer();

            timer.Interval = 15;
            timer.Tick    += timer_Tick;

            timer.Start();
        }
Example #33
0
        public GridPrimitive(int gridSize, int gridSpacing)
        {
            // thanks Skyth
            var vertices = new List <Vector3>();

            for (int i = -gridSize; i <= gridSize; i += gridSpacing)
            {
                vertices.Add(new Vector3(i, 0, -gridSize));
                vertices.Add(new Vector3(i, 0, gridSize));
                vertices.Add(new Vector3(-gridSize, 0, i));
                vertices.Add(new Vector3(gridSize, 0, i));
            }

            mMinZ        = vertices.Min(x => x.Z);
            mVertexArray = GL.GenVertexArray();
            GL.BindVertexArray(mVertexArray);

            mVertexBuffer = new GLBuffer <Vector3>(BufferTarget.ArrayBuffer, vertices.ToArray());

            GL.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, false, mVertexBuffer.Stride, 0);
            GL.EnableVertexAttribArray(0);

            mShader = ShaderStore.Instance.Get("line");
        }
        private void Initialize()
        {
            Smaa = new Smaa();

            var prefix = @"
				#ifndef GL_ES
				#version 330
				#endif
			"            ;

            Shader = new GLShader(
                prefix +
                "attribute vec4 position; attribute vec4 texCoords; varying vec2 v_texCoord; void main() { gl_Position = position; v_texCoord = texCoords.xy; }",
                prefix +
                "uniform sampler2D texture; varying vec2 v_texCoord; void main() { gl_FragColor = texture2D(texture, v_texCoord); }"
                );

            VertexBuffer = GLBuffer.Create()
                           .SetData(CSharpPlatform.RectangleF.FromCoords(-1, -1, +1, +1).GetFloat2TriangleStripCoords());

            Shader.BindUniformsAndAttributes(ShaderInfo);

            // TestTexture = GLTexture.Create().SetFormat(TextureFormat.RGBA).SetSize(2, 2).SetData(new uint[] { 0xFF0000FF, 0xFF00FFFF, 0xFFFF00FF, 0xFFFFFFFF });
        }
Example #35
0
        /// <summary>
        /// Initializes a new instance of the <see cref="nginz.SpriteBatch"/> class.
        /// </summary>
        /// <param name = "game">The game.</param>
        /// <param name="shader">Shader.</param>
        public SpriteBatch(Game game, ShaderProgram shader = null)
        {
            // Set the game
            Game = game;

            // Compile predefined shaders if no shader program is given
            if (shader == null) {
                var vertShader = new VertexShader (vert_source);
                var fragShader = new FragmentShader (frag_source);
                Program = new ShaderProgram (vertShader, fragShader);
                Program.Link ();
            } else
                Program = shader;

            // Create the optimal buffer settings
            var settings = new GLBufferSettings {
                AttribSize = 0,
                Hint = BufferUsageHint.DynamicDraw,
                Normalized = false,
                Offset = 0,
                Target = BufferTarget.ArrayBuffer,
                Type = VertexAttribPointerType.Float
            };

            // Create temp variables for indices
            int indPtr = 0;
            var tempIndices = new uint[MAX_INDICES];

            // Fill temporary indices
            for (uint i = 0; i < MAX_VERTICES; i += 4) {

                // Triangle 1
                tempIndices [indPtr++] = i;
                tempIndices [indPtr++] = i + 1;
                tempIndices [indPtr++] = i + 2;

                // Triangle 2
                tempIndices [indPtr++] = i + 1;
                tempIndices [indPtr++] = i + 3;
                tempIndices [indPtr++] = i + 2;
            }

            // Set camera
            InternalCamera = new Camera (60f, game.Resolution, 0, 16, type: ProjectionType.Orthographic);

            // Set current texture
            CurrentTexture = Texture2D.Dot;

            // Generate array buffer object
            abo = GL.GenVertexArray ();

            // Create vertex buffer object
            vbo = new GLBufferDynamic<Vertex2D> (settings, Vertex2D.Size, MAX_VERTICES);

            // Create index buffer object
            ibo = new GLBuffer<uint> (GLBufferSettings.DynamicIndices, tempIndices);

            // Initialize vertices
            Vertices = new Vertex2D[MAX_VERTICES];

            framebuffer = new Framebuffer (FramebufferTarget.Framebuffer, Game.Resolution.Width, game.Resolution.Height)
                            .AttachTexture (FboAttachment.DiffuseAttachment, DrawBuffersEnum.ColorAttachment0, PixelInternalFormat.Rgb, PixelFormat.Rgb, PixelType.UnsignedByte, InterpolationMode.Linear);
        }
Example #36
0
        private void Initialize()
        {
            Smaa = new Smaa();

            Shader = new GLShader(
                "attribute vec4 position; attribute vec4 texCoords; varying vec2 v_texCoord; void main() { gl_Position = position; v_texCoord = texCoords.xy; }",
                "uniform sampler2D texture; varying vec2 v_texCoord; void main() { gl_FragColor = texture2D(texture, v_texCoord); }"
            );

            VertexBuffer = GLBuffer.Create().SetData(CSharpPlatform.RectangleF.FromCoords(-1, -1, +1, +1).GetFloat2TriangleStripCoords());

            Shader.BindUniformsAndAttributes(ShaderInfo);

            // TestTexture = GLTexture.Create().SetFormat(TextureFormat.RGBA).SetSize(2, 2).SetData(new uint[] { 0xFF0000FF, 0xFF00FFFF, 0xFFFF00FF, 0xFFFFFFFF });
        }
Example #37
0
        //GLTexture TestTexture;
        public void DrawVram(bool EnableSmaa)
        {
            if (Shader == null) Initialize();

            //int RectWidth = 512;
            //int RectHeight = 272;
            var Rectangle = IGuiWindowInfo.ClientRectangle;

            GL.glClearColor(0, 0, 0, 1);
            GL.glClear(GL.GL_COLOR_BUFFER_BIT);
            //IGuiWindowInfo.SwapBuffers();
            //return;

            if (
                (PspDisplay.CurrentInfo.Enabled || PspDisplay.CurrentInfo.PlayingVideo)
            )
            {
                GetTex((Tex) =>
                {
                    //Console.Out.WriteLineColored(ConsoleColor.Red, "{0}", Tex.Texture);
                    if (Tex != null && Tex.Color.Texture != 0)
                    {
                        var TexColor = Tex.Color;
                        var TexDepth = Tex.Depth;

                        if (EnableSmaa)
                        {
                            if (TexDepth.Texture != 0)
                            {
                                TexColor = Smaa.Process(TexColor, TexDepth);
                            }
                        }

                        GL.glViewport(Rectangle.X, Rectangle.Y, Rectangle.Width, Rectangle.Height);

                        Shader.Draw(GLGeometry.GL_TRIANGLE_STRIP, 4, () =>
                        {
                            var TextureRect = CSharpPlatform.RectangleF.FromCoords(0, 0, (float)PspDisplay.CurrentInfo.Width / 512f, (float)PspDisplay.CurrentInfo.Height / 272f);
                            if (TextureVerticalFlip) TextureRect = TextureRect.VFlip();
                            TexCoordsBuffer = GLBuffer.Create().SetData(TextureRect.GetFloat2TriangleStripCoords());

                            ShaderInfo.texture.Set(GLTextureUnit.CreateAtIndex(0).SetFiltering(GLScaleFilter.Nearest).SetWrap(GLWrap.ClampToEdge).SetTexture(TexColor));
                            //ShaderInfo.texture.Set(GLTextureUnit.CreateAtIndex(0).SetFiltering(GLScaleFilter.Nearest).SetWrap(GLWrap.ClampToEdge).SetTexture(TexDepth));
                            ShaderInfo.position.SetData<float>(VertexBuffer, 2);
                            ShaderInfo.texCoords.SetData<float>(TexCoordsBuffer, 2);
                        });
                    }
                });
            }

            IGuiWindowInfo.SwapBuffers();
        }
Example #38
0
        public Voxel(Shader shader)
            : base()
        {
            this.shader = shader;
            geometry = new VertexArray(PrimitiveType.Triangles);
            vertex = geometry.CreateBuffer("vertex", BufferTarget.ArrayBuffer);
            colors = geometry.CreateBuffer("colors", BufferTarget.ArrayBuffer);
            normal = geometry.CreateBuffer("normal", BufferTarget.ArrayBuffer);

            Byte3[] colorData =  ColorData(new Byte3(255, 0, 0), new Byte3(0, 255, 255),
                                           new Byte3(0, 255, 0), new Byte3(255, 0, 255),
                                           new Byte3(0, 0, 255), new Byte3(255, 255, 0));
            vertex.BufferData<Byte3>(ref vertexData);
            colors.BufferData<Byte3>(ref colorData);
            normal.BufferData<SByte3>(ref normalData);

            geometry.AddPointer("vertex", new VertexAttribute(this.shader, "vPosition", VertexAttribPointerType.UnsignedByte, 3, 0, false));
            geometry.AddPointer("colors", new VertexAttribute(this.shader, "vColor", VertexAttribPointerType.UnsignedByte, 3, 0, true));
            geometry.AddPointer("normal", new VertexAttribute(this.shader, "vNormal", VertexAttribPointerType.Byte, 3, 0, true));
        }