/// <inheritdoc />
        public void Add(IPolygon data)
        {
            foreach (var layer in RenderLayers)
            {
                layer.Reset(true);
            }

            // Always clear Voronoi layer.
            RenderLayers[4].Reset(true);

            int i = 0;

            // Ensure linear numbering of polygon vertices.
            foreach (var p in data.Points)
            {
                p.ID = i++;
            }

            bounds = data.Bounds();

            zoom.Initialize(bounds);

            RenderLayers[2].SetPoints(VertexBuffer.Create(data.Points, bounds));
            RenderLayers[2].SetIndices(IndexBuffer.Create(data.Segments, 2));

            RenderLayers[3].SetPoints(RenderLayers[2].Points);
        }
        /// <inheritdoc />
        public void Add(IMesh data, bool reset)
        {
            foreach (var layer in RenderLayers)
            {
                layer.Reset(reset);
            }

            // Always clear voronoi layer.
            RenderLayers[4].Reset(true);

            // Save reference to mesh.
            mesh   = data;
            bounds = data.Bounds;

            // Ensure linear numbering of vertices.
            mesh.Renumber();

            zoom.Initialize(bounds);

            RenderLayers[1].SetPoints(VertexBuffer.Create(data.Vertices, bounds));
            RenderLayers[1].SetIndices(IndexBuffer.Create(data.Edges, 2));

            RenderLayers[2].SetPoints(RenderLayers[1].Points);
            RenderLayers[2].SetIndices(IndexBuffer.Create(data.Segments, 2));

            RenderLayers[3].SetPoints(RenderLayers[1].Points, false);
        }
Beispiel #3
0
        /// <summary>
        ///
        /// </summary>
        void LoadContent()
        {
            SafeDispose(ref factory);

            skySphere   = Game.Content.Load <Scene>("skySphere");
            cloudSphere = Game.Content.Load <Scene>("cloudSphere");
            clouds      = Game.Content.Load <Texture2D>("clouds|srgb");
            cirrus      = Game.Content.Load <Texture2D>("cirrus|srgb");
            noise       = Game.Content.Load <Texture2D>("cloudNoise");
            arrows      = Game.Content.Load <Texture2D>("arrowsAll");

            vertexBufferBlur = new VertexBuffer(Game.GraphicsDevice, typeof(VertexColorTextureTBN), 6);
            vertexBuffers    = skySphere.Meshes
                               .Select(mesh => VertexBuffer.Create(Game.GraphicsDevice, mesh.Vertices.Select(v => VertexColorTextureTBN.Convert(v)).ToArray()))
                               .ToArray();

            indexBuffers = skySphere.Meshes
                           .Select(mesh => IndexBuffer.Create(Game.GraphicsDevice, mesh.GetIndices()))
                           .ToArray();

            cloudVertexBuffers = cloudSphere.Meshes
                                 .Select(mesh => VertexBuffer.Create(Game.GraphicsDevice, mesh.Vertices.Select(v => VertexColorTextureTBN.Convert(v)).ToArray()))
                                 .ToArray();

            cloudIndexBuffers = cloudSphere.Meshes
                                .Select(mesh => IndexBuffer.Create(Game.GraphicsDevice, mesh.GetIndices()))
                                .ToArray();

            sky     = Game.Content.Load <Ubershader>("sky");
            factory = new StateFactory(sky, typeof(SkyFlags), (ps, i) => EnumFunc(ps, (SkyFlags)i));
        }
Beispiel #4
0
        protected override void OnLoad(EventArgs e)
        {
            VSync = VSyncMode.On;

            GL.ClearColor(0.1f, 0.2f, 0.5f, 0.0f);
            GL.Enable(EnableCap.DepthTest);

            float aspectRatio = ClientSize.Width / (float)(ClientSize.Height);

            Matrix4.CreatePerspectiveFieldOfView((float)Math.PI / 4, aspectRatio, 1, 100, out projectionMatrix);
            modelviewMatrix = Matrix4.LookAt(new Vector3(0, 3, 5), new Vector3(0, 0, 0), new Vector3(0, 1, 0));

            shader = new Program(vertexShaderSource, fragmentShaderSource);
            shader.Bind();
            shader.UniformMatrix4("camera", false, ref projectionMatrix);
            shader.UniformMatrix4("model", false, ref modelviewMatrix);
            shader.Unbind();

            positionVbo = VertexBuffer.Create(VertexFormat.PositionTexture, positionVboData);
            //normalVbo = VertexBuffer.Create(new VertexFormat(new List<VertexAttribute>() { new VertexAttribute(VertexUsage.TextureCoordinate, VertexAttribPointerType.Float, 0, 2) }), textureVboData);

            indexVbo = IndexBuffer.Create(indicesVboData);
            vao      = new VertexArray(positionVbo, indexVbo);
            Utilities.CheckGLError();
            vao.AddBinding(shader.VertexAttribute("vert").Slot, VertexUsage.Position);
            vao.AddBinding(shader.VertexAttribute("vertTexCoord").Slot, VertexUsage.TextureCoordinate);
            Utilities.CheckGLError();
            Bitmap bmp = new Bitmap(@"..\..\..\Resources\wooden-crate.jpg");

            texture = Texture2D.Create(bmp, TextureMinFilter.Linear, TextureMagFilter.Linear);
        }
Beispiel #5
0
        protected override void OnLoad(EventArgs e)
        {
            VSync = VSyncMode.On;

            GL.ClearColor(0.1f, 0.2f, 0.5f, 0.0f);
            GL.Enable(EnableCap.DepthTest);

            float aspectRatio = ClientSize.Width / (float)(ClientSize.Height);

            Matrix4.CreatePerspectiveFieldOfView((float)Math.PI / 4, aspectRatio, 1, 100, out projectionMatrix);
            modelviewMatrix = Matrix4.LookAt(new Vector3(0, 3, 5), new Vector3(0, 0, 0), new Vector3(0, 1, 0));

            shader = new Program(vertexShaderSource, fragmentShaderSource);
            shader.Bind();
            shader.UniformMatrix4("projection_matrix", false, ref projectionMatrix);
            shader.UniformMatrix4("modelview_matrix", false, ref modelviewMatrix);
            shader.Unbind();

            positionVbo = VertexBuffer.Create(new VertexFormat(new List <VertexAttribute>()
            {
                new VertexAttribute(VertexUsage.Position, VertexAttribPointerType.Float, 0, 3)
            }), positionVboData);
            normalVbo = VertexBuffer.Create(new VertexFormat(new List <VertexAttribute>()
            {
                new VertexAttribute(VertexUsage.Normal, VertexAttribPointerType.Float, 0, 3)
            }), positionVboData);
            indexVbo = IndexBuffer.Create(indicesVboData);
            vao      = new VertexArray(positionVbo, indexVbo);
            Utilities.CheckGLError();
            vao.AddBinding(shader.VertexAttribute("in_position").Slot, 3, VertexAttribPointerType.Float, false, 3 * sizeof(float), 0);
            vao.AddBinding(shader.VertexAttribute("in_normal").Slot, 3, VertexAttribPointerType.Float, false, 3 * sizeof(float), 0);
            Utilities.CheckGLError();
        }
        private VertexBuffer GetPositionBuffer(string varNameInShader)
        {
            int          dimSize = this.DataSource.DimenSize;
            int          length  = dimSize;
            VertexBuffer buffer  = VertexBuffer.Create(typeof(HexahedronPosition), length, VBOConfig.Vec3, varNameInShader, BufferUsage.StaticDraw);

            unsafe
            {
                IntPtr pointer = buffer.MapBuffer(MapBufferAccess.WriteOnly);
                var    array = (HexahedronPosition *)pointer;
                int    I, J, K;
                for (int gridIndex = 0; gridIndex < dimSize; gridIndex++)
                {
                    this.DataSource.InvertIJK(gridIndex, out I, out J, out K);
                    array[gridIndex].FLT = this.DataSource.Position + this.DataSource.PointFLT(I, J, K);
                    array[gridIndex].FRT = this.DataSource.Position + this.DataSource.PointFRT(I, J, K);
                    array[gridIndex].BRT = this.DataSource.Position + this.DataSource.PointBRT(I, J, K);
                    array[gridIndex].BLT = this.DataSource.Position + this.DataSource.PointBLT(I, J, K);
                    array[gridIndex].FLB = this.DataSource.Position + this.DataSource.PointFLB(I, J, K);
                    array[gridIndex].FRB = this.DataSource.Position + this.DataSource.PointFRB(I, J, K);
                    array[gridIndex].BRB = this.DataSource.Position + this.DataSource.PointBRB(I, J, K);
                    array[gridIndex].BLB = this.DataSource.Position + this.DataSource.PointBLB(I, J, K);
                }
                buffer.UnmapBuffer();
            }

            return(buffer);
        }
Beispiel #7
0
    static CloudComponent()
    {
        VertexPositions.Create(new Vector3[]
        {
            new Vector3(-0.5f, +0.5f, 0),
            new Vector3(+0.5f, +0.5f, 0),
            new Vector3(-0.5f, -0.5f, 0),
            new Vector3(+0.5f, -0.5f, 0),
        }, Accessibility.None);

        VertexTextureCoords.Create(new Vector2[]
        {
            new Vector2(0, 0),
            new Vector2(1, 0),
            new Vector2(0, 1),
            new Vector2(1, 1),
        }, Accessibility.None);

        VertexShader.CreateFromFile("res/shader/CloudVertexShader.hlsl");
        PixelShader.CreateFromFile("res/shader/CloudPixelShader.hlsl");

        VertexLayout.Create(new VertexElement[]
        {
            new VertexElement("POSITION", 0, Format.Float3, 0, 0, VertexElement.Classification.VertexData, 0),
            new VertexElement("TEXCOORD", 0, Format.Float2, 1, 0, VertexElement.Classification.VertexData, 0),
            new VertexElement("WVP", 0, Format.Float4, 2, sizeof(float) * 0, VertexElement.Classification.InstanceData, 1),
            new VertexElement("WVP", 1, Format.Float4, 2, sizeof(float) * 4, VertexElement.Classification.InstanceData, 1),
            new VertexElement("WVP", 2, Format.Float4, 2, sizeof(float) * 8, VertexElement.Classification.InstanceData, 1),
            new VertexElement("WVP", 3, Format.Float4, 2, sizeof(float) * 12, VertexElement.Classification.InstanceData, 1),
        }, VertexShader);

        Texture.Create("res/texture/cloud.dds", Accessibility.None);
    }
    static GunBulletSmokeComponent()
    {
        VertexPositions.Create(new Vector3[]
        {
            new Vector3(-0.5f, +1, 0),
            new Vector3(+0.5f, +1, 0),
            new Vector3(-0.5f, 0, 0),
            new Vector3(+0.5f, 0, 0),
        }, Accessibility.None);

        VertexTextureCoords.Create(new Vector2[]
        {
            new Vector2(0, 0),
            new Vector2(1, 0),
            new Vector2(0, 1),
            new Vector2(1, 1),
        }, Accessibility.None);

        VertexShader.CreateFromFile("res/shader/GunBulletSmokeVertexShader.hlsl");
        PixelShader.CreateFromFile("res/shader/GunBulletSmokePixelShader.hlsl");

        VertexLayout.Create(new VertexElement[]
        {
            new VertexElement("POSITION", 0, Format.Float3, 0, 0, VertexElement.Classification.VertexData, 0),
            new VertexElement("TEXCOORD", 0, Format.Float2, 1, 0, VertexElement.Classification.VertexData, 0),
        }, VertexShader);

        Texture.Create("res/texture/water.dds", Accessibility.None);
    }
Beispiel #9
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="bufferName"></param>
        /// <param name="varNameInShader"></param>
        /// <returns></returns>
        public VertexBuffer GetVertexAttributeBuffer(string bufferName, string varNameInShader)
        {
            if (bufferName == position)
            {
                if (this.positionBuffer == null)
                {
                    int          length = this.markerCount * 2;
                    VertexBuffer buffer = VertexBuffer.Create(typeof(vec3), length, VBOConfig.Vec3, varNameInShader, BufferUsage.StaticDraw);
                    unsafe
                    {
                        IntPtr pointer = buffer.MapBuffer(MapBufferAccess.WriteOnly);
                        var    array   = (vec3 *)pointer;
                        for (int i = 0; i < this.markerCount; i++)
                        {
                            array[i * 2 + 0] = new vec3(-0.5f + (float)i / (float)(this.markerCount - 1), 0.5f, 0);
                            array[i * 2 + 1] = new vec3(-0.5f + (float)i / (float)(this.markerCount - 1), -0.5f, 0);
                        }
                        buffer.UnmapBuffer();
                    }

                    this.positionBuffer = buffer;
                }
                return(this.positionBuffer);
            }
            else
            {
                throw new NotImplementedException();
            }
        }
Beispiel #10
0
        /// <summary>
        /// 把坐标轴画上 绿X 红Y 蓝Z
        /// </summary>
        private void drawCoorAxis()
        {
            if (axisGlProgram != null)
            {
                axisGlProgram.Bind(gl);
                axisGlProgram.SetUniformMatrix4(gl, "viewMatrix", viewMatrix.to_array());


                var vertexBufferArray = new VertexBufferArray();
                vertexBufferArray.Create(gl);
                vertexBufferArray.Bind(gl);

                var vertexDataBuffer = new VertexBuffer();
                vertexDataBuffer.Create(gl);
                vertexDataBuffer.Bind(gl);
                vertexDataBuffer.SetData(gl, index_in_vPosition, axisData, false, 3);

                var colorDataBuffer = new VertexBuffer();
                colorDataBuffer.Create(gl);
                colorDataBuffer.Bind(gl);
                colorDataBuffer.SetData(gl, index_in_vColor, axisColor, false, 3);

                //  Draw the square.
                gl.DrawArrays(OpenGL.GL_LINES, 0, 6);

                //  Unbind our vertex array and shader.
                vertexDataBuffer.Unbind(gl);
                colorDataBuffer.Unbind(gl);
                vertexBufferArray.Unbind(gl);
                axisGlProgram.Unbind(gl);
            }
        }
Beispiel #11
0
        protected override void DoInitialize()
        {
            base.DoInitialize();

            {
                // velocity
                var buffer = VertexBuffer.Create(typeof(vec4), ParticleModel.particleCount, VBOConfig.Vec4, "empty", BufferUsage.DynamicCopy);
                unsafe
                {
                    var random = new Random();
                    var array  = (vec4 *)buffer.MapBuffer(MapBufferAccess.WriteOnly);
                    for (int i = 0; i < ParticleModel.particleCount; i++)
                    {
                        array[i] = new vec4(
                            (float)(random.NextDouble() - 0.5) * 0.2f,
                            (float)(random.NextDouble() - 0.5) * 0.2f,
                            (float)(random.NextDouble() - 0.5) * 0.2f,
                            0);
                    }
                    buffer.UnmapBuffer();
                }
                this.VelocityBuffer = buffer;
            }

            this.PositionBuffer = this.DataSource.GetVertexAttributeBuffer(ParticleModel.strPosition, null);
        }
Beispiel #12
0
        private void drawPoints()
        {
            if (mainGlProgram != null)
            {
                mainGlProgram.Bind(gl);
                mainGlProgram.SetUniformMatrix4(gl, "viewMatrix", viewMatrix.to_array());


                // 同样数组对象不用调用glVertexAttribPointer,可以用它封装好的方式
                var vertexBufferArray = new VertexBufferArray();
                vertexBufferArray.Create(gl);
                vertexBufferArray.Bind(gl);


                var vertexDataBuffer = new VertexBuffer();
                vertexDataBuffer.Create(gl);
                vertexDataBuffer.Bind(gl);
                vertexDataBuffer.SetData(gl, index_in_vPosition, pointData, false, 3);

                //  Draw the square.
                gl.DrawArrays(OpenGL.GL_POINTS, 0, SumPoints.Count);

                //  Unbind our vertex array and shader.
                vertexDataBuffer.Unbind(gl);
                vertexBufferArray.Unbind(gl);
                mainGlProgram.Unbind(gl);
            }
        }
Beispiel #13
0
        /// <summary>
        /// Creates the geometry for the square, also creating the vertex buffer array.
        /// </summary>
        /// <param name="gl">The OpenGL instance.</param>
        private void CreateVertices(OpenGL gl)
        {
            //GeneratePoints(out vertices, out  colors);
            GenerateModel(out positions, out colors);

            //  Create the vertex array object.
            vertexBufferArray = new VertexBufferArray();
            vertexBufferArray.Create(gl);
            vertexBufferArray.Bind(gl);

            //  Create a vertex buffer for the vertex data.
            var vertexDataBuffer = new VertexBuffer();

            vertexDataBuffer.Create(gl);
            vertexDataBuffer.Bind(gl);
            vertexDataBuffer.SetData(gl, 0, positions, false, 3);

            //  Now do the same for the colour data.
            var colourDataBuffer = new VertexBuffer();

            colourDataBuffer.Create(gl);
            colourDataBuffer.Bind(gl);
            colourDataBuffer.SetData(gl, 1, colors, false, 3);

            //  Unbind the vertex array, we've finished specifying data for it.
            vertexBufferArray.Unbind(gl);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="bufferName"></param>
        /// <returns></returns>
        public IEnumerable <VertexBuffer> GetVertexAttribute(string bufferName)
        {
            if (bufferName == strPosition)
            {
                if (this.positionBuffer == null)
                {
                    this.positionBuffer = VertexBuffer.Create(typeof(GlyphPosition), this.Capacity, VBOConfig.Vec2, BufferUsage.DynamicDraw);
                }

                yield return(this.positionBuffer);
            }
            else if (bufferName == strTexCoord)
            {
                if (this.texCoordBuffer == null)
                {
                    this.texCoordBuffer = VertexBuffer.Create(typeof(GlyphTexCoord), this.Capacity, VBOConfig.Vec2, BufferUsage.DynamicDraw);
                }

                yield return(this.texCoordBuffer);
            }
            else
            {
                throw new ArgumentException();
            }
        }
Beispiel #15
0
        /// <summary>
        ///
        /// </summary>
        internal void CreateVertexAndIndexBuffers(GraphicsDevice device)
        {
            indexBuffer = IndexBuffer.Create(device, GetIndices());

            bool skinned = false;

            foreach (var v in Vertices)
            {
                if (v.SkinIndices != Int4.Zero)
                {
                    skinned = true;
                    break;
                }
            }

            IsSkinned = skinned;


            if (skinned)
            {
                vertexBuffer = VertexBuffer.Create(device, Vertices.Select(v => VertexColorTextureTBNSkinned.Convert(v)).ToArray());
            }
            else
            {
                vertexBuffer = VertexBuffer.Create(device, Vertices.Select(v => VertexColorTextureTBNRigid.Convert(v)).ToArray());
            }
        }
Beispiel #16
0
        /// <summary>
        /// 初始化Vbo
        /// </summary>
        private void InitVbo()
        {
            var gl = openGLControl.OpenGL;

            vertexBufferArray = new VertexBufferArray();
            vertexBufferArray.Create(gl);
            vertexBufferArray.Bind(gl);

            //  Create a vertex buffer for the vertex data.
            var vertexDataBuffer = new VertexBuffer();

            vertexDataBuffer.Create(gl);
            vertexDataBuffer.Bind(gl);
            vertexDataBuffer.SetData(gl, 0, vertices, false, 3);

            //  Now do the same for the colour data.
            var colourDataBuffer = new VertexBuffer();

            colourDataBuffer.Create(gl);
            colourDataBuffer.Bind(gl);
            colourDataBuffer.SetData(gl, 1, colors, false, 3);

            //  Unbind the vertex array, we've finished specifying data for it.
            vertexBufferArray.Unbind(gl);
        }
Beispiel #17
0
        /// <summary>
        ///
        /// </summary>
        void LoadContent()
        {
            SafeDispose(ref factory);
            SafeDispose(ref vertexBuffers);
            SafeDispose(ref indexBuffers);

            surfaceShader = Game.Content.Load <Ubershader>("surface");
            factory       = new StateFactory(surfaceShader, typeof(SurfaceFlags), Primitive.TriangleList, VertexInputElement.FromStructure <VertexColorTextureTBN>());


            scene = Game.Content.Load <Scene>(@"Scenes\testScene");

            vertexBuffers = scene.Meshes
                            .Select(mesh => VertexBuffer.Create(Game.GraphicsDevice, mesh.Vertices.Select(v => VertexColorTextureTBN.Convert(v)).ToArray()))
                            .ToArray();

            indexBuffers = scene.Meshes
                           .Select(mesh => IndexBuffer.Create(Game.GraphicsDevice, mesh.GetIndices()))
                           .ToArray();


            surfaceProps = scene.Materials
                           .Select(mtrl => new SurfaceProperties()
            {
                Diffuse   = LoadTexture2D(mtrl.TexturePath, "|srgb", defaultDiffuse),
                Specular  = LoadTexture2D(mtrl.TexturePath, "_spec", defaultSpecular),
                NormalMap = LoadTexture2D(mtrl.TexturePath, "_local", defaultNormalMap),
                Emission  = LoadTexture2D(mtrl.TexturePath, "_glow|srgb", defaultEmission),
            })
                           .ToArray();
        }
Beispiel #18
0
        private VertexBufferArray CreateVertexBufferArray(OpenGL gl, PrimordialObject primordialObject)
        {
            vertexBufferArray = new VertexBufferArray();
            vertexBufferArray.Create(gl);
            vertexBufferArray.Bind(gl);

            vertexDataBuffer = new VertexBuffer();
            vertexDataBuffer.Create(gl);
            vertexDataBuffer.Bind(gl);
            //  for(int i = 0; i<100; i++) {
            //  var sendDataTime = _stopwatch.ElapsedMilliseconds;
            gl.BufferData(OpenGL.GL_ARRAY_BUFFER, primordialObject.VertexData, OpenGL.GL_STATIC_DRAW);
            //  File.AppendAllText(fileTitle + "Data.txt", (_stopwatch.ElapsedMilliseconds - sendDataTime).ToString() + "\n");
            // }
            gl.VertexAttribPointer(attributeIndexPosition, 4, OpenGL.GL_FLOAT, false, 3 * 4 * sizeof(float), IntPtr.Zero);
            gl.EnableVertexAttribArray(0);


            gl.VertexAttribPointer(attributeIndexColour, 4, OpenGL.GL_FLOAT, false, 3 * 4 * sizeof(float), IntPtr.Add(IntPtr.Zero, 4 * sizeof(float)));
            gl.EnableVertexAttribArray(1);

            gl.VertexAttribPointer(attributeIndexNormal, 4, OpenGL.GL_FLOAT, false, 3 * 4 * sizeof(float), IntPtr.Add(IntPtr.Zero, 8 * sizeof(float)));
            gl.EnableVertexAttribArray(2);
            vertexDataBuffer.Unbind(gl);
            vertexBufferArray.Unbind(gl);
            return(vertexBufferArray);
        }
        public TransformFeedbackCalculator(int maxItemCount)
        {
            this.MaxItemCount = maxItemCount;

            var program = new ShaderProgram();
            //program.Initialize(varyings, ShaderProgram.BufferMode.InterLeaved, vertexShader);
            var varyings = new string[] { "outValue" };

            glTransformFeedbackVaryings(program.ProgramId, varyings.Length, varyings, GL.GL_INTERLEAVED_ATTRIBS);
            var vertexShader = new VertexShader(vertexCode);

            vertexShader.Initialize();
            glAttachShader(program.ProgramId, vertexShader.ShaderId);
            glLinkProgram(program.ProgramId);
            program.CheckLinkStatus();

            VertexBuffer vbo     = VertexBuffer.Create(typeof(float), maxItemCount, VBOConfig.Float, BufferUsage.StaticDraw);
            var          drawCmd = new DrawArraysCmd(DrawMode.Points, maxItemCount);
            var          vao     = new VertexArrayObject(drawCmd, program, new VertexShaderAttribute[] { new VertexShaderAttribute(vbo, "inValue") });
            uint         index   = 0;
            VertexBuffer tbo     = VertexBuffer.Create(typeof(float), maxItemCount, VBOConfig.Float, BufferUsage.StaticRead);

            glBindBufferBase(GL.GL_TRANSFORM_FEEDBACK_BUFFER, index, tbo.BufferId);

            {
                this.program      = program;
                this.inputBuffer  = vbo;
                this.outputBuffer = tbo;
                this.vao          = vao;
                this.drawCommand  = drawCmd;
            }
        }
Beispiel #20
0
            public VertexBuffer GetVertexAttributeBuffer(string bufferName, string varNameInShader)
            {
                if (bufferName == strPosition)
                {
                    if (this.positionBuffer == null)
                    {
                        int          length = particleCount;
                        VertexBuffer buffer = VertexBuffer.Create(typeof(vec3), length, VBOConfig.Vec3, varNameInShader, BufferUsage.StaticDraw);
                        unsafe
                        {
                            IntPtr pointer = buffer.MapBuffer(MapBufferAccess.WriteOnly);
                            var    array   = (vec3 *)pointer;
                            for (int i = 0; i < particleCount; i++)
                            {
                                double beta  = random.NextDouble() * Math.PI;
                                double theta = random.NextDouble() * Math.PI * 2;
                                float  x     = (float)(a * Math.Sin(beta) * Math.Cos(theta));
                                float  y     = (float)(b * Math.Sin(beta) * Math.Sin(theta));
                                float  z     = (float)(c * Math.Cos(beta));
                                array[i] = new vec3(x, y, z);
                            }
                            buffer.UnmapBuffer();
                        }

                        this.positionBuffer = buffer;
                    }

                    return(this.positionBuffer);
                }
                else
                {
                    throw new ArgumentException();
                }
            }
Beispiel #21
0
        /// <inheritdoc/>
        protected override void OnLoadingContent()
        {
            this.content = ContentManager.Create("Content");

            this.sprite      = content.Load <Sprite>("Sprites/Hexagons");
            this.spriteFont  = content.Load <SpriteFont>("Fonts/SegoeUI");
            this.spriteBatch = SpriteBatch.Create();

            this.blankTexture = Texture2D.Create(1, 1);
            this.blankTexture.SetData(new[] { Color.White });

            this.effect = BasicEffect.Create();

            this.vbuffer = VertexBuffer.Create <VertexPositionColor>(3);
            this.vbuffer.SetData <VertexPositionColor>(new[]
            {
                new VertexPositionColor(new Vector3(0, 1, 0), Color.Red),
                new VertexPositionColor(new Vector3(1, -1, 0), Color.Lime),
                new VertexPositionColor(new Vector3(-1, -1, 0), Color.Blue),
            });

            this.geometryStream = GeometryStream.Create();
            this.geometryStream.Attach(this.vbuffer);

            GC.Collect(2);

            base.OnLoadingContent();
        }
Beispiel #22
0
        private void CreateVerticesForSquare2(OpenGL gl, float[] vert, float[] col, float[] nrm)
        {
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_VideoController");
            string graphicsCard = string.Empty;

            foreach (ManagementObject obj in searcher.Get())
            {
                if (obj["CurrentBitsPerPixel"] != null && obj["CurrentHorizontalResolution"] != null)
                {
                    graphicsCard = obj["Name"].ToString();
                }
            }

            string[]      checkname1 = graphicsCard.Split(' ');
            List <string> checkname2 = new List <string>(checkname1);
            string        match      = checkname2.FirstOrDefault(element => element.Equals("nvidia",
                                                                                           StringComparison.CurrentCultureIgnoreCase));
            var vertices = nrm;
            var colors   = vert; // Colors for our vertices
            var normals  = col;


            if (match != null)
            {
                vertices = vert;
                colors   = col; // Colors for our vertices
                normals  = nrm;
            }


            //  Create the vertex array object.
            vertexBufferArray = new VertexBufferArray();
            vertexBufferArray.Create(gl);
            vertexBufferArray.Bind(gl);

            //  Create a vertex buffer for the vertex data.
            var vertexDataBuffer = new VertexBuffer();

            vertexDataBuffer.Create(gl);
            vertexDataBuffer.Bind(gl);
            vertexDataBuffer.SetData(gl, 0, vertices, false, 3);

            //  Now do the same for the colour data.
            var colourDataBuffer = new VertexBuffer();

            colourDataBuffer.Create(gl);
            colourDataBuffer.Bind(gl);
            colourDataBuffer.SetData(gl, 1, colors, false, 3);

            var normalDataBuffer = new VertexBuffer();

            normalDataBuffer.Create(gl);
            normalDataBuffer.Bind(gl);
            normalDataBuffer.SetData(gl, 2, normals, false, 3);


            //  Unbind the vertex array, we've finished specifying data for it.
            vertexBufferArray.Unbind(gl);
        }
Beispiel #23
0
 private void CreateVertexBuffer()
 {
     _vertexBuffer?.Dispose();
     _vertexBuffer = VertexBuffer.Create <VertexPosition2Color>(RenderContext,
                                                                _vertexBufferSize,
                                                                BufferUsageHint.StreamDraw,
                                                                true);
     _vertexBuffer.Label = "LineBatch2D VertexBuffer";
 }
        /// <summary>
        ///
        /// </summary>
        /// <param name="bufferName"></param>
        /// <param name="varNameInShader"></param>
        /// <returns></returns>
        public VertexBuffer GetVertexAttributeBuffer(string bufferName, string varNameInShader)
        {
            if (bufferName == position)
            {
                if (this.positionBuffer == null)
                {
                    int          length = (this.quadCount + 1) * 2;
                    VertexBuffer buffer = VertexBuffer.Create(typeof(vec3), length, VBOConfig.Vec3, varNameInShader, BufferUsage.StaticDraw);
                    unsafe
                    {
                        IntPtr pointer = buffer.MapBuffer(MapBufferAccess.WriteOnly);
                        var    array   = (vec3 *)pointer;
                        for (int i = 0; i < (this.quadCount + 1); i++)
                        {
                            array[i * 2 + 0] = new vec3(-0.5f + (float)i / (float)(this.quadCount), 0.5f, 0);
                            array[i * 2 + 1] = new vec3(-0.5f + (float)i / (float)(this.quadCount), -0.5f, 0);
                        }
                        buffer.UnmapBuffer();
                    }

                    this.positionBuffer = buffer;
                }
                return(positionBuffer);
            }
            else if (bufferName == color)
            {
                if (this.colorBuffer == null)
                {
                    int          length = (this.quadCount + 1) * 2;
                    VertexBuffer buffer = VertexBuffer.Create(typeof(vec3), length, VBOConfig.Vec3, varNameInShader, BufferUsage.StaticDraw);
                    unsafe
                    {
                        IntPtr pointer = buffer.MapBuffer(MapBufferAccess.WriteOnly);
                        var    array   = (vec3 *)pointer;
                        for (int i = 0; i < (this.quadCount + 1); i++)
                        {
                            int x = this.bitmap.Width * i / this.quadCount;
                            if (x == this.bitmap.Width)
                            {
                                x = this.bitmap.Width - 1;
                            }
                            vec3 value = this.bitmap.GetPixel(x, 0).ToVec3();
                            array[i * 2 + 0] = value;
                            array[i * 2 + 1] = value;
                        }
                        buffer.UnmapBuffer();
                    }

                    this.colorBuffer = buffer;
                }
                return(colorBuffer);
            }
            else
            {
                throw new NotImplementedException();
            }
        }
Beispiel #25
0
 private void CreateVertexBuffer()
 {
     _vertexBuffer?.Dispose();
     _vertexBuffer = VertexBuffer.Create <VertexPosition2TextureColor>(ParentContext,
                                                                       _vertexBufferSize,
                                                                       BufferUsageHint.StreamDraw,
                                                                       true);
     _vertexBuffer.Label = "SpriteBatch VertexBuffer";
 }
Beispiel #26
0
        private VertexArray Init()
        {
            var va = VertexArray.Create();
            var vb = VertexBuffer.Create(Vertices);

            vb.BufferLayout = new BufferLayout(BufferLayout);
            va.AddVertexBuffer(vb);
            va.SetIndexBuffer(IndexBuffer.Create(Indices));
            return(va);
        }
Beispiel #27
0
    static SkyComponent()
    {
        // 円周方向の分割数
        const int Slices = 16;

        // Y方向の分割数
        const int Stacks = 8;

        List <Vector3> positions = new List <Vector3>();

        for (int i = 0; i < Stacks + 1; i++)
        {
            float y = 1.0f - 2.0f * (float)i / Stacks;
            float r = sqrt(1 - y * y);
            for (int j = 0; j < Slices + 1; j++)
            {
                float   t = (float)j / Slices * 3.14159f * 2;
                float   x = r * cos(t);
                float   z = r * sin(t);
                Vector3 v = new Vector3(x / 2, y / 2, z / 2);
                positions.Add(v);
            }
        }
        VertexBuffer.Create(positions.ToArray(), Accessibility.None);

        List <int> indices = new List <int>();

        for (int i = 0; i < Stacks; i++)
        {
            for (int j = 0; j < Slices; j++)
            {
                int i0 = (Slices + 1) * i + j;
                int i1 = i0 + 1;
                int i2 = (Slices + 1) * (i + 1) + j;
                int i3 = i2 + 1;
                indices.Add(i0);
                indices.Add(i2);
                indices.Add(i1);
                indices.Add(i1);
                indices.Add(i2);
                indices.Add(i3);
            }
        }
        IndexBuffer.Create(indices.ToArray(), Accessibility.None);

        Texture.CreateCubeMap("res/texture/skybox.dds", Accessibility.None);

        VertexShader.CreateFromFile("res/shader/SkyVertexShader.hlsl");
        PixelShader.CreateFromFile("res/shader/SkyPixelShader.hlsl");

        VertexLayout.Create(new VertexElement[]
        {
            new VertexElement("POSITION", 0, Format.Float3, 0, 0, VertexElement.Classification.VertexData, 0),
        }, VertexShader);
    }
        public void UltravioletGraphics_CanRenderSprites_WhenUsingCustomVertexElementNames()
        {
            var effect            = default(Effect);
            var vertexDeclaration = default(VertexDeclaration);
            var vertexBuffer      = default(VertexBuffer);
            var geometryStream    = default(GeometryStream);

            var result = GivenAnUltravioletApplication()
                         .WithContent(content =>
            {
                effect = content.Load <Effect>("Effects\\NamedVertexElements.vert");

                vertexDeclaration = new VertexDeclaration(new[] {
                    new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0, "my_position"),
                    new VertexElement(sizeof(Single) * 3, VertexElementFormat.Color, VertexElementUsage.Color, 0, "my_color")
                });

                vertexBuffer = VertexBuffer.Create(vertexDeclaration, 3);
                vertexBuffer.SetData(new[]
                {
                    new VertexPositionColor(new Vector3(0, 1, 0), Color.Red),
                    new VertexPositionColor(new Vector3(1, -1, 0), Color.Lime),
                    new VertexPositionColor(new Vector3(-1, -1, 0), Color.Blue),
                });

                geometryStream = GeometryStream.Create();
                geometryStream.Attach(vertexBuffer);
            })
                         .Render(uv =>
            {
                var gfx         = uv.GetGraphics();
                var window      = uv.GetPlatform().Windows.GetPrimary();
                var viewport    = new Viewport(0, 0, window.Compositor.Width, window.Compositor.Height);
                var aspectRatio = viewport.Width / (float)viewport.Height;

                gfx.SetViewport(viewport);

                effect.Parameters["World"].SetValue(Matrix.Identity);
                effect.Parameters["View"].SetValue(Matrix.CreateLookAt(new Vector3(0, 0, 5), Vector3.Zero, Vector3.Up));
                effect.Parameters["Projection"].SetValue(Matrix.CreatePerspectiveFieldOfView((float)Math.PI / 4f, aspectRatio, 1f, 1000f));
                effect.Parameters["DiffuseColor"].SetValue(Color.White);

                foreach (var pass in effect.CurrentTechnique.Passes)
                {
                    pass.Apply();

                    gfx.SetRasterizerState(RasterizerState.CullNone);
                    gfx.SetGeometryStream(geometryStream);
                    gfx.DrawPrimitives(PrimitiveType.TriangleList, 0, 1);
                }
            });

            TheResultingImage(result)
            .ShouldMatch(@"Resources/Expected/Graphics/UltravioletGraphics_CanRenderSprites_WhenUsingCustomVertexElementNames.png");
        }
        public override void Render(NkHandle Userdata, GL_Texture Texture, NkRect ClipRect, uint Offset, uint Count)
        {
            float[] vert   = new float[Count * 2];
            float[] uvs    = new float[Count * 2];
            float[] colors = new float[Count * 4];

            for (int i = 0; i < Count; i++)
            {
                NkVertex V = Verts[Inds[Offset + i]];
                vert[i * 2]     = V.Position.X;
                vert[i * 2 + 1] = V.Position.Y;

                uvs[i * 2]     = V.UV.X;
                uvs[i * 2 + 1] = V.UV.Y;

                NkColor color = V.Color;
                colors[i * 4]     = color.R;
                colors[i * 4 + 1] = color.G;
                colors[i * 4 + 2] = color.B;
                colors[i * 4 + 3] = color.A;
            }



            var vertexDataBuffer = new VertexBuffer();

            vertexDataBuffer.Create(gl);
            vertexDataBuffer.Bind(gl);


            vertexDataBuffer.SetDataV2F(gl, 0, rawData, NkVertex.SIZE * (int)Count, false, 3);

            //    vertexDataBuffer.SetData(gl, 0, vert, false, 2);

            var colourDataBuffer = new VertexBuffer();

            colourDataBuffer.Create(gl);
            colourDataBuffer.Bind(gl);
            colourDataBuffer.SetData(gl, 1, colors, false, 4);

            var uvDataBuffer = new VertexBuffer();

            uvDataBuffer.Create(gl);
            uvDataBuffer.Bind(gl);
            uvDataBuffer.SetData(gl, 2, uvs, false, 2);

            gl.ActiveTexture(OpenGL.GL_TEXTURE0);
            gl.BindTexture(OpenGL.GL_TEXTURE_2D, Texture.TextureName);
            glScissor2(window.DisplayHeight, (int)ClipRect.X, (int)ClipRect.Y, (int)ClipRect.W, (int)ClipRect.H);
            gl.DrawArrays(OpenGL.GL_TRIANGLES, 0, (int)Count);

            vertexDataBuffer.Unbind(gl);
            //  colourDataBuffer.Unbind(gl);
            //  uvDataBuffer.Unbind(gl);
        }
Beispiel #30
0
        /// <summary>
        /// Creates the geometry for the square, also creating the vertex buffer array.
        /// </summary>
        /// <param name="gl">The OpenGL instance.</param>
        private void CreateVerticesForSquare(OpenGL gl)
        {
            var vertices = new float[18];

            vertices[0]  = -1.0f; vertices[1] = -1.0f; vertices[2] = 0.0f;   // Bottom left corner
            vertices[3]  = -1.0f; vertices[4] = 1.0f; vertices[5] = 0.0f;    // Top left corner
            vertices[6]  = 1.0f; vertices[7] = 1.0f; vertices[8] = 0.0f;     // Top Right corner
            vertices[9]  = 1.0f; vertices[10] = -1.0f; vertices[11] = 0.0f;  // Bottom right corner
            vertices[12] = -1.0f; vertices[13] = -1.0f; vertices[14] = 0.0f; // Bottom left corner
            vertices[15] = 1.0f; vertices[16] = 1.0f; vertices[17] = 0.0f;   // Top Right corner

            var texcoords = new float[12];

            texcoords[0]  = 0.0f; texcoords[1] = 0.0f;
            texcoords[2]  = 0.0f; texcoords[3] = 1.0f;
            texcoords[4]  = 1.0f; texcoords[5] = 1.0f;
            texcoords[6]  = 1.0f; texcoords[7] = 0.0f;
            texcoords[8]  = 0.0f; texcoords[9] = 0.0f;
            texcoords[10] = 1.0f; texcoords[11] = 1.0f;

            //  Create the vertex array object.
            vertexBufferArray = new VertexBufferArray();
            vertexBufferArray.Create(gl);
            vertexBufferArray.Bind(gl);

            texCoordsBufferArray = new VertexBufferArray();
            texCoordsBufferArray.Create(gl);
            texCoordsBufferArray.Bind(gl);


            //  Create a vertex buffer for the vertex data.
            var vertexDataBuffer = new VertexBuffer();

            vertexDataBuffer.Create(gl);
            vertexDataBuffer.Bind(gl);
            vertexDataBuffer.SetData(gl, 0, vertices, false, 3);

            var texCoordsBuffer = new VertexBuffer();

            texCoordsBuffer.Create(gl);
            texCoordsBuffer.Bind(gl);
            texCoordsBuffer.SetData(gl, 1, texcoords, false, 2);

            //  Now do the same for the colour data.

            /*var colourDataBuffer = new VertexBuffer();
             * colourDataBuffer.Create(gl);
             * colourDataBuffer.Bind(gl);
             * colourDataBuffer.SetData(gl, 1, colors, false, 3);*/

            //  Unbind the vertex array, we've finished specifying data for it.
            vertexBufferArray.Unbind(gl);
            texCoordsBufferArray.Unbind(gl);
        }
Beispiel #31
0
        /// <summary>
        /// Creates the geometry for the square, also creating the vertex buffer array.
        /// </summary>
        /// <param name="gl">The OpenGL instance.</param>
        private void CreateVerticesForSquare(OpenGL gl)
        {
            var vertices = new float[18];
            var colors = new float[18]; // Colors for our vertices
            vertices[0] = -0.5f; vertices[1] = -0.5f; vertices[2] = 0.0f; // Bottom left corner
            colors[0] = 1.0f; colors[1] = 1.0f; colors[2] = 1.0f; // Bottom left corner
            vertices[3] = -0.5f; vertices[4] = 0.5f; vertices[5] = 0.0f; // Top left corner
            colors[3] = 1.0f; colors[4] = 0.0f; colors[5] = 0.0f; // Top left corner
            vertices[6] = 0.5f; vertices[7] = 0.5f; vertices[8] = 0.0f; // Top Right corner
            colors[6] = 0.0f; colors[7] = 1.0f; colors[8] = 0.0f; // Top Right corner
            vertices[9] = 0.5f; vertices[10] = -0.5f; vertices[11] = 0.0f; // Bottom right corner
            colors[9] = 0.0f; colors[10] = 0.0f; colors[11] = 1.0f; // Bottom right corner
            vertices[12] = -0.5f; vertices[13] = -0.5f; vertices[14] = 0.0f; // Bottom left corner
            colors[12] = 1.0f; colors[13] = 1.0f; colors[14] = 1.0f; // Bottom left corner
            vertices[15] = 0.5f; vertices[16] = 0.5f; vertices[17] = 0.0f; // Top Right corner
            colors[15] = 0.0f; colors[16] = 1.0f; colors[17] = 0.0f; // Top Right corner

            //  Create the vertex array object.
            vertexBufferArray = new VertexBufferArray();
            vertexBufferArray.Create(gl);
            vertexBufferArray.Bind(gl);

            //  Create a vertex buffer for the vertex data.
            var vertexDataBuffer = new VertexBuffer();
            vertexDataBuffer.Create(gl);
            vertexDataBuffer.Bind(gl);
            vertexDataBuffer.SetData(gl, 0, vertices, false, 3);

            //  Now do the same for the colour data.
            var colourDataBuffer = new VertexBuffer();
            colourDataBuffer.Create(gl);
            colourDataBuffer.Bind(gl);
            colourDataBuffer.SetData(gl, 1, colors, false, 3);

            //  Unbind the vertex array, we've finished specifying data for it.
            vertexBufferArray.Unbind(gl);
        }