Exemple #1
0
        public void ExampleCreateArrayBufferObject(GraphicsContext ctx)
        {
            using (ArrayBuffer <Vertex3f> vertexPosition = new ArrayBuffer <Vertex3f>(BufferUsage.StaticDraw)) {
                // Define CPU data
                vertexPosition.Create(new Vertex3f[] {
                    Vertex3f.UnitX, Vertex3f.UnitY, Vertex3f.UnitZ
                });
                // Create GPU data
                vertexPosition.Create(ctx);
            }

            using (ArrayBuffer <ColorRGBAF> vertexColor = new ArrayBuffer <ColorRGBAF>(BufferUsage.StaticDraw)) {
                // Define GPU items count
                vertexColor.Create(256);
                // Reserve GPU memory
                vertexColor.Create(ctx);
                // Update
                vertexColor.Create(ctx, new ColorRGBAF[] { ColorRGBAF.ColorRed, ColorRGBAF.ColorGreen, ColorRGBAF.ColorBlue });
            }

            // By ArrayBufferItemType
            using (ArrayBuffer buffer = ArrayBuffer.CreateArrayObject(ArrayBufferItemType.Float3x3, BufferUsage.StaticDraw)) {
                // ...
            }
        }
Exemple #2
0
        public void ArrayBuffer_TestCreateImmutable()
        {
            using (ArrayBuffer arrayBuffer = new ArrayBuffer(ArrayBufferItemType.Float4, MapBufferUsageMask.DynamicStorageBit)) {
                // Using MapBufferUsageMask constructor make array buffer immutable
                Assert.IsTrue(arrayBuffer.Immutable);

                // Create on-line
                Assert.DoesNotThrow(() => arrayBuffer.Create(_Context, 16));
                // Being immutable, it cannot change size
                Assert.Throws <GlException>(() => arrayBuffer.Create(_Context, 32));
            }
        }
Exemple #3
0
        public void ArrayBuffer_TestCreateNonImmutable()
        {
            using (ArrayBuffer arrayBuffer = new ArrayBuffer(ArrayBufferItemType.Float4, BufferUsage.DynamicDraw)) {
                // Using BufferUsage constructor make array buffer mutable
                Assert.IsFalse(arrayBuffer.Immutable);

                // Create on-line
                Assert.DoesNotThrow(() => arrayBuffer.Create(_Context, 16));
                // Being mutable, is can be reset even if size
                Assert.DoesNotThrow(() => arrayBuffer.Create(_Context, 32));
            }
        }
Exemple #4
0
        public static VertexArrays CreateCone(float radius, float height, uint dr)
        {
            VertexArrays vertexArray = new VertexArrays();

            // Vertex generation
            Vertex3f[] position      = new Vertex3f[dr + 2];
            int        positionIndex = 0;

            position[positionIndex++] = new Vertex3f(0.0f, 0.0f, -height);

            double angleStep = Math.PI * 2.0 / dr;

            for (double angle = 0.0f; angle <= Math.PI * 2.0; angle += angleStep)
            {
                float x = radius * (float)Math.Cos(angle);
                float y = radius * (float)Math.Sin(angle);

                Debug.Assert(positionIndex < position.Length);
                position[positionIndex++] = new Vertex3f(x, y, 0.0f);
            }
            position[positionIndex++] = position[1];

            // Buffer definition
            ArrayBuffer <Vertex3f> positionBuffer = new ArrayBuffer <Vertex3f>();

            positionBuffer.Create(position);
            vertexArray.SetArray(positionBuffer, VertexArraySemantic.Position);

            vertexArray.SetElementArray(PrimitiveType.TriangleFan);

            return(vertexArray);
        }
Exemple #5
0
        /// <summary>
        /// Create a sphere.
        /// </summary>
        /// <param name="radius">
        /// A <see cref="Single"/> that specifies the radius of the sphere.
        /// </param>
        /// <param name="slices">
        /// A <see cref="Int32"/> that specifies the number of horizontal subdivisions of the sphere.
        /// </param>
        /// <param name="stacks">
        /// A <see cref="Int32"/> that specifies the number of vertical subdivisions of the sphere.
        /// </param>
        /// <returns>
        /// It returns a <see cref="Objects.VertexArrays"/> defining the following semantics:
        /// - Positions
        /// - Normals
        /// </returns>
        public static VertexArrays CreateSphere(float radius, int slices, int stacks)
        {
            VertexArrays vertexArray = new VertexArrays();

            // Vertex generation
            Vertex3f[] position, normal;
            ushort[]   indices;
            int        vertexCount;

            GenerateSphere(radius, slices, stacks, out position, out normal, out indices, out vertexCount);

            // Buffer definition
            ArrayBuffer <Vertex3f> positionBuffer = new ArrayBuffer <Vertex3f>();

            positionBuffer.Create(position);
            vertexArray.SetArray(positionBuffer, VertexArraySemantic.Position);

            ArrayBuffer <Vertex3f> normalBuffer = new ArrayBuffer <Vertex3f>();

            normalBuffer.Create(normal);
            vertexArray.SetArray(normalBuffer, VertexArraySemantic.Normal);

            ElementBuffer <ushort> elementBuffer = new ElementBuffer <ushort>();

            elementBuffer.Create(indices);
            vertexArray.SetElementArray(PrimitiveType.TriangleStrip, elementBuffer);

            return(vertexArray);
        }
Exemple #6
0
        protected override void CreateGpuBuffer(Buffer buffer)
        {
            ArrayBuffer arrayBuffer = (ArrayBuffer)buffer;

            // Create CPU buffer with 16 elements
            arrayBuffer.Create(_Context, 16);
        }
        /// <summary>
        /// Create vertex arrays representing the bounding box, using lines delimiting the box volume.
        /// </summary>
        /// <returns>
        /// It returns a <see cref="VertexArrays"/> representing a normalized bounding box volume.
        /// </returns>
        private static VertexArrays CreateBoundingBoxArrays()
        {
            VertexArrays           bboxArray          = new VertexArrays();
            ArrayBuffer <Vertex3f> bboxVPositionArray = new ArrayBuffer <Vertex3f>();

            bboxVPositionArray.Create(new Vertex3f[] {
                // Lower
                new Vertex3f(-0.5f, -0.5f, -0.5f), new Vertex3f(+0.5f, -0.5f, -0.5f),
                new Vertex3f(+0.5f, -0.5f, -0.5f), new Vertex3f(+0.5f, -0.5f, +0.5f),
                new Vertex3f(+0.5f, -0.5f, +0.5f), new Vertex3f(-0.5f, -0.5f, +0.5f),
                new Vertex3f(-0.5f, -0.5f, +0.5f), new Vertex3f(-0.5f, -0.5f, -0.5f),
                // Upper
                new Vertex3f(-0.5f, +0.5f, -0.5f), new Vertex3f(+0.5f, +0.5f, -0.5f),
                new Vertex3f(+0.5f, +0.5f, -0.5f), new Vertex3f(+0.5f, +0.5f, +0.5f),
                new Vertex3f(+0.5f, +0.5f, +0.5f), new Vertex3f(-0.5f, +0.5f, +0.5f),
                new Vertex3f(-0.5f, +0.5f, +0.5f), new Vertex3f(-0.5f, +0.5f, -0.5f),
                // Verticals
                new Vertex3f(-0.5f, -0.5f, -0.5f), new Vertex3f(-0.5f, +0.5f, -0.5f),
                new Vertex3f(+0.5f, -0.5f, -0.5f), new Vertex3f(+0.5f, +0.5f, -0.5f),
                new Vertex3f(+0.5f, -0.5f, +0.5f), new Vertex3f(+0.5f, +0.5f, +0.5f),
                new Vertex3f(-0.5f, -0.5f, +0.5f), new Vertex3f(-0.5f, +0.5f, +0.5f),
            });
            bboxArray.SetArray(bboxVPositionArray, VertexArraySemantic.Position);

            bboxArray.SetElementArray(PrimitiveType.Lines);

            return(bboxArray);
        }
Exemple #8
0
        private SceneObjectGeometry CreateCubeGeometry()
        {
            SceneObjectGeometry cubeGeometry = new SceneObjectGeometry("Cube");

            #region State

            cubeGeometry.ObjectState.DefineState(new CullFaceState(FrontFaceDirection.Ccw, CullFaceMode.Back));
            cubeGeometry.ObjectState.DefineState(new TransformState());

            MaterialState cubeMaterialState = new MaterialState();
            cubeMaterialState.FrontMaterial           = new MaterialState.Material(ColorRGBAF.ColorWhite * 0.5f);
            cubeMaterialState.FrontMaterial.Ambient   = ColorRGBAF.ColorBlack;
            cubeMaterialState.FrontMaterial.Diffuse   = ColorRGBAF.ColorWhite * 0.5f;
            cubeMaterialState.FrontMaterial.Specular  = ColorRGBAF.ColorWhite * 0.5f;
            cubeMaterialState.FrontMaterial.Shininess = 10.0f;
            cubeGeometry.ObjectState.DefineState(cubeMaterialState);

            #endregion

            #region Vertex Arrays

            if (_CubeArrayPosition == null)
            {
                _CubeArrayPosition = new ArrayBuffer <Vertex3f>();
                _CubeArrayPosition.Create(ArrayPosition);
            }

            if (_CubeArrayColor == null)
            {
                _CubeArrayColor = new ArrayBuffer <ColorRGBF>();
                _CubeArrayColor.Create(ArrayColors);
            }

            if (_CubeArrayNormal == null)
            {
                _CubeArrayNormal = new ArrayBuffer <Vertex3f>();
                _CubeArrayNormal.Create(ArrayNormals);
            }

            if (_CubeArrays == null)
            {
                _CubeArrays = new VertexArrays();
                _CubeArrays.SetArray(_CubeArrayPosition, VertexArraySemantic.Position);
                _CubeArrays.SetArray(_CubeArrayColor, VertexArraySemantic.Color);
                _CubeArrays.SetArray(_CubeArrayNormal, VertexArraySemantic.Normal);
                _CubeArrays.SetElementArray(PrimitiveType.Triangles);
            }

            cubeGeometry.VertexArray = _CubeArrays;

            #endregion

            #region Program

            cubeGeometry.BoundingVolume = new BoundingBox(-Vertex3f.One * _CubeSize, Vertex3f.One * _CubeSize);

            #endregion

            return(cubeGeometry);
        }
Exemple #9
0
        private SceneObjectGeometry CreateSphere(string material)
        {
            SceneObjectGeometry sphereGeometry = new SceneObjectGeometry("Sphere");

            sphereGeometry.ObjectState.DefineState(new CullFaceState(FrontFaceDirection.Ccw, CullFaceMode.Back));
            sphereGeometry.ObjectState.DefineState(new TransformState());
            sphereGeometry.LocalModelView = Matrix4x4f.Translated(0.0f, 4.0f, 0.0f);

            sphereGeometry.VertexArray = VertexArrays.CreateSphere(4.0f, 32, 32);

            ArrayBuffer <Vertex2f> texCoordBuffer = new ArrayBuffer <Vertex2f>();

            texCoordBuffer.Create(sphereGeometry.VertexArray.ArrayLength);
            sphereGeometry.VertexArray.SetArray(texCoordBuffer, VertexArraySemantic.TexCoord);

            ArrayBuffer <Vertex3f> tanCoordBuffer = new ArrayBuffer <Vertex3f>();

            tanCoordBuffer.Create(sphereGeometry.VertexArray.ArrayLength);
            sphereGeometry.VertexArray.SetArray(tanCoordBuffer, VertexArraySemantic.Tangent);

            ArrayBuffer <Vertex3f> bitanCoordBuffer = new ArrayBuffer <Vertex3f>();

            bitanCoordBuffer.Create(sphereGeometry.VertexArray.ArrayLength);
            sphereGeometry.VertexArray.SetArray(bitanCoordBuffer, VertexArraySemantic.Bitangent);

            sphereGeometry.VertexArray.GenerateTexCoords(new VertexArrayTexGen.Sphere());
            sphereGeometry.VertexArray.GenerateTangents();

            sphereGeometry.ProgramTag = ShadersLibrary.Instance.CreateProgramTag("OpenGL.Standard+PhongFragment");

            SetSphereMaterial(sphereGeometry, material);

            return(sphereGeometry);
        }
Exemple #10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <param name="dx"></param>
        /// <param name="dy"></param>
        /// <returns></returns>
        public static VertexArrays CreatePlane(float x, float y, float z, uint dx, uint dy)
        {
            VertexArrays vertexArray = new VertexArrays();

            // Vertex generation
            Vertex3f[] position = new Vertex3f[(dx + 1) * (dy + 1)];
            float      x2 = x / 2.0f, y2 = y / 2.0f;
            float      vdx = x / dx, vdy = y / dy;
            int        vidx = 0;

            for (float vy = -y2; vy <= y2; vy += vdy)
            {
                for (float vx = -x2; vx <= x2; vx += vdx)
                {
                    Debug.Assert(vidx < position.Length);
                    position[vidx++] = new Vertex3f(vx, vy, z);
                }
            }

            // Elements generation
            List <uint> indices      = new List <uint>();
            uint        restartIndex = ElementBuffer <uint> .DefaultRestartIndex;
            uint        vstride      = dx + 1;

            for (uint i = 0; i < dy; i++)
            {
                uint yoffset = i * vstride;

                // Triangle strip start
                indices.Add(yoffset + vstride);

                for (uint ix = 0; ix < dx; ix++)
                {
                    uint xoffset = yoffset + ix;

                    indices.Add(xoffset);
                    indices.Add(xoffset + vstride + 1);
                }

                indices.Add(yoffset + vstride - 1);

                indices.Add(restartIndex);
            }

            // Buffer definition
            ArrayBuffer <Vertex3f> positionBuffer = new ArrayBuffer <Vertex3f>();

            positionBuffer.Create(position);
            vertexArray.SetArray(positionBuffer, VertexArraySemantic.Position);

            ElementBuffer <uint> elementBuffer = new ElementBuffer <uint>();

            elementBuffer.Create(indices.ToArray());
            elementBuffer.RestartIndexEnabled = true;
            vertexArray.SetElementArray(PrimitiveType.TriangleStrip, elementBuffer);

            return(vertexArray);
        }
Exemple #11
0
        private void LinkShadowMapResources(GraphicsContext ctx)
        {
            LinkResource(_ShadowMapQuad = new VertexArrays());

            ArrayBuffer <Vertex2f> positionArray = new ArrayBuffer <Vertex2f>(BufferUsage.StaticDraw);

            positionArray.Create(new Vertex2f[] {
                new Vertex2f(0.0f, 0.0f), new Vertex2f(1.0f, 0.0f), new Vertex2f(1.0f, 1.0f),
                new Vertex2f(0.0f, 1.0f), new Vertex2f(0.0f, 0.0f), new Vertex2f(1.0f, 1.0f),
            });
            positionArray.Create(ctx);

            _ShadowMapQuad.SetArray(positionArray, VertexArraySemantic.Position);
            _ShadowMapQuad.SetArray(positionArray, VertexArraySemantic.TexCoord);
            _ShadowMapQuad.SetElementArray(PrimitiveType.Triangles);
            _ShadowMapQuad.Create(ctx);

            LinkResource(_ShadowMapDebugProgram = ctx.CreateProgram("OpenGL.Specialized+Depth"));
        }
Exemple #12
0
        /// <summary>
        /// Create a <see cref="ArrayBufferBase"/> for testing.
        /// </summary>
        /// <returns>
        /// It returns the <see cref="ArrayBufferBase"/> instance to test.
        /// </returns>
        private void CreateClientInstance(Buffer buffer)
        {
            if (buffer.GetType() == typeof(ArrayBuffer))
            {
                ArrayBuffer arrayBufferObject = (ArrayBuffer)buffer;

                arrayBufferObject.Create(CreateTestArray());
            }
            else if (buffer.GetType() == typeof(ElementBuffer))
            {
                ElementBuffer elementBufferObject = (ElementBuffer)buffer;

                elementBufferObject.Create(CreateTestArray());
            }
        }
Exemple #13
0
            public VertexArrays CreateArrays(ObjContext objContext)
            {
                if (objContext == null)
                {
                    throw new ArgumentNullException("objContext");
                }

                VertexArrays        vertexArray = new VertexArrays();
                List <ObjFaceCoord> coords      = new List <ObjFaceCoord>();
                bool hasTexCoord = Material.DiffuseTexture != null;
                bool hasNormals  = false;
                bool hasTanCoord = hasTexCoord && Material.NormalTexture != null;

                foreach (ObjFace f in Faces)
                {
                    hasTexCoord |= f.HasTexCoord;
                    hasNormals  |= f.HasNormal;
                    coords.AddRange(f.Triangulate());
                }

                uint vertexCount = (uint)coords.Count;

                Vertex4f[] position = new Vertex4f[vertexCount];
                Vertex3f[] normal   = hasNormals ? new Vertex3f[vertexCount] : null;
                Vertex2f[] texcoord = new Vertex2f[vertexCount];

                for (int i = 0; i < position.Length; i++)
                {
                    Debug.Assert(coords[i].VertexIndex < objContext.Vertices.Count);
                    position[i] = objContext.Vertices[coords[i].VertexIndex];

                    if (hasTexCoord)
                    {
                        Debug.Assert(coords[i].TexCoordIndex < objContext.TextureCoords.Count);
                        texcoord[i] = objContext.TextureCoords[coords[i].TexCoordIndex];
                    }

                    if (hasNormals)
                    {
                        Debug.Assert(coords[i].NormalIndex < objContext.Normals.Count);
                        normal[i] = objContext.Normals[coords[i].NormalIndex];
                    }
                }

                // Position (mandatory)
                ArrayBuffer <Vertex4f> positionBuffer = new ArrayBuffer <Vertex4f>();

                positionBuffer.Create(position);
                vertexArray.SetArray(positionBuffer, VertexArraySemantic.Position);

                // Layout (triangles)
                vertexArray.SetElementArray(PrimitiveType.Triangles);

                // Texture
                if (hasTexCoord)
                {
                    ArrayBuffer <Vertex2f> texCoordBuffer = new ArrayBuffer <Vertex2f>();
                    texCoordBuffer.Create(texcoord);
                    vertexArray.SetArray(texCoordBuffer, VertexArraySemantic.TexCoord);
                }

                // Normals
                if (hasNormals)
                {
                    ArrayBuffer <Vertex3f> normalBuffer = new ArrayBuffer <Vertex3f>();
                    normalBuffer.Create(normal);
                    vertexArray.SetArray(normalBuffer, VertexArraySemantic.Normal);
                }
                else
                {
                    ArrayBuffer <Vertex3f> normalBuffer = new ArrayBuffer <Vertex3f>();
                    normalBuffer.Create(vertexCount);
                    vertexArray.SetArray(normalBuffer, VertexArraySemantic.Normal);
                    // XXX vertexArray.GenerateNormals();
                }

                // Tangents
                if (hasTanCoord)
                {
                    ArrayBuffer <Vertex3f> tanCoordBuffer = new ArrayBuffer <Vertex3f>();
                    tanCoordBuffer.Create(vertexCount);
                    vertexArray.SetArray(tanCoordBuffer, VertexArraySemantic.Tangent);

                    ArrayBuffer <Vertex3f> bitanCoordBuffer = new ArrayBuffer <Vertex3f>();
                    bitanCoordBuffer.Create(vertexCount);
                    vertexArray.SetArray(bitanCoordBuffer, VertexArraySemantic.Bitangent);

                    // XXX vertexArray.GenerateTangents();
                }

                return(vertexArray);
            }
Exemple #14
0
        /// <summary>
        /// Create a <see cref="VertexArrays"/> for rendering glyphs.
        /// </summary>
        private void LinkSharedResources(GraphicsContext ctx)
        {
            CheckCurrentContext(ctx);

            string resourceClassId = "OpenGL.Objects.FontPatch";
            string resourceBaseId  = String.Format("{0}.{1}-{2}-{3}", resourceClassId, Family, Size, Style);

            string vertexArrayId = resourceBaseId + ".VertexArray";
            string glyphDbId     = resourceBaseId + ".GlyphDb";

            #region Vertex Arrays

            _VertexArrays = (VertexArrays)ctx.GetSharedResource(vertexArrayId);
            Dictionary <char, Glyph> glyphsDb = null;

            if (_VertexArrays == null)
            {
                _VertexArrays = new VertexArrays();

                List <GlyphPolygons> glyphPolygons  = GenerateGlyphs(Family, Size, Style);
                List <Vertex2f>      glyphsVertices = new List <Vertex2f>();
                GlyphPolygons        gGlyph         = null;
                uint gVertexIndex = 0;

                glyphsDb = new Dictionary <char, Glyph>();

                using (Tessellator tessellator = new Tessellator()) {
                    tessellator.Begin += delegate(object sender, TessellatorBeginEventArgs e) {
                        gVertexIndex = (uint)glyphsVertices.Count;
                    };
                    tessellator.End += delegate(object sender, EventArgs e) {
                        // Create element (range)
                        int glyphIndex = _VertexArrays.SetElementArray(PrimitiveType.Triangles, gVertexIndex, (uint)glyphsVertices.Count - gVertexIndex);

                        glyphsDb.Add(gGlyph.GlyphChar, new Glyph(gGlyph.GlyphChar, gGlyph.GlyphSize, glyphIndex));
                    };
                    tessellator.Vertex += delegate(object sender, TessellatorVertexEventArgs e) {
                        glyphsVertices.Add((Vertex2f)e.Vertex);
                    };

                    // Tessellate all glyphs
                    foreach (GlyphPolygons glyph in glyphPolygons)
                    {
                        gGlyph = glyph;

                        if (glyph.Contours.Count == 0)
                        {
                            glyphsDb.Add(gGlyph.GlyphChar, new Glyph(gGlyph.GlyphChar, gGlyph.GlyphSize, -1));
                            continue;
                        }

                        tessellator.BeginPolygon();
                        foreach (List <Vertex2f> countour in glyph.Contours)
                        {
                            tessellator.AddContour(countour.ToArray(), Vertex3f.UnitZ);
                        }
                        tessellator.EndPolygon();
                    }
                }

                // Element vertices
                ArrayBuffer <Vertex2f> gVertexPosition = new ArrayBuffer <Vertex2f>();
                gVertexPosition.Create(glyphsVertices.ToArray());
                _VertexArrays.SetArray(gVertexPosition, VertexArraySemantic.Position);

                // Share
                ctx.SetSharedResource(vertexArrayId, _VertexArrays);
            }
            LinkResource(_VertexArrays);

            #endregion

            #region Glyph Metadata

            _Glyphs = (Dictionary <char, Glyph>)ctx.GetSharedResource(glyphDbId);

            if (glyphsDb != null)
            {
                _Glyphs = glyphsDb;
            }
            if (_Glyphs == null)
            {
                throw new InvalidProgramException("no glyph metadata");
            }

            // Share
            ctx.SetSharedResource(glyphDbId, _Glyphs);

            #endregion
        }
Exemple #15
0
        /// <summary>
        /// Create resources for rendering glyphs.
        /// </summary>
        /// <param name="ctx"></param>
        private void LinkSharedResources(GraphicsContext ctx)
        {
            CheckCurrentContext(ctx);

            StringFormat stringFormat = StringFormat.GenericTypographic;

            // Font-wide resources
            string resourceClassId = "OpenGL.Objects.FontTextureArray2d";
            string resourceBaseId  = String.Format("{0}.{1}-{2}-{3}", resourceClassId, Family, Size, Style);

            #region Instanced Arrays

            if (ctx.Extensions.InstancedArrays)
            {
                string instanceArrayId = resourceClassId + ".InstanceArray";

                _GlyphInstances = (ArrayBufferObjectInterleaved <GlyphInstance>)ctx.GetSharedResource(instanceArrayId);

                if (_GlyphInstances == null)
                {
                    _GlyphInstances = new ArrayBufferObjectInterleaved <GlyphInstance>(MapBufferUsageMask.MapWriteBit);
                    _GlyphInstances.Create(256);
                    // Share
                    ctx.SetSharedResource(instanceArrayId, _GlyphInstances);
                }
                LinkResource(_GlyphInstances);
            }
            else
            {
                _GlyphInstances = null;
            }

            #endregion

            #region Vertex Array

            string vertexArrayId = resourceClassId + ".VertexArray";

            _VertexArrays = (VertexArrays)ctx.GetSharedResource(vertexArrayId);

            if (_VertexArrays == null)
            {
                _VertexArrays = new VertexArrays();

                ArrayBuffer <Vertex2f> arrayPosition = new ArrayBuffer <Vertex2f>();
                arrayPosition.Create(new Vertex2f[] {
                    new Vertex2f(0.0f, 1.0f),
                    new Vertex2f(0.0f, 0.0f),
                    new Vertex2f(1.0f, 1.0f),
                    new Vertex2f(1.0f, 0.0f),
                });
                _VertexArrays.SetArray(arrayPosition, VertexArraySemantic.Position);
                if (ctx.Extensions.InstancedArrays)
                {
                    _VertexArrays.SetInstancedArray(_GlyphInstances, 0, 1, "glo_GlyphModelViewProjection");
                    _VertexArrays.SetInstancedArray(_GlyphInstances, 1, 1, "glo_GlyphVertexParams");
                    _VertexArrays.SetInstancedArray(_GlyphInstances, 2, 1, "glo_GlyphTexParams");
                }
                _VertexArrays.SetElementArray(PrimitiveType.TriangleStrip);
                // Share
                ctx.SetSharedResource(vertexArrayId, _VertexArrays);
            }
            LinkResource(_VertexArrays);

            #endregion

            #region Glyphs Metadata

            string glyphDbId = resourceBaseId + ".GlyphDb";

            _GlyphMetadata = (Dictionary <char, Glyph>)ctx.GetSharedResource(glyphDbId);

            if (_GlyphMetadata == null)
            {
                _GlyphMetadata = new Dictionary <char, Glyph>();

                char[] fontChars = GetFontCharacters().ToCharArray();
                uint   layer     = 0;

                using (Bitmap bitmap = new Bitmap(1, 1))
                    using (Graphics g = Graphics.FromImage(bitmap))
                        using (System.Drawing.Font font = new System.Drawing.Font(Family, Size, Style))
                        {
                            // Avoid grid fitting
                            g.TextRenderingHint = TextRenderingHint.AntiAlias;

                            float glyphHeight = font.GetHeight();

                            foreach (char c in fontChars)
                            {
                                SizeF glyphSize;

                                switch (c)
                                {
                                case ' ':
                                    glyphSize = g.MeasureString(c.ToString(), font, 0, StringFormat.GenericDefault);
                                    break;

                                default:
                                    glyphSize = g.MeasureString(c.ToString(), font, 0, stringFormat);
                                    break;
                                }

                                Glyph glyph = new Glyph(c, glyphSize, layer++, new SizeF(1.0f, 1.0f));

                                _GlyphMetadata.Add(c, glyph);
                            }
                        }

                // Share
                ctx.SetSharedResource(glyphDbId, _GlyphMetadata);
            }

            #endregion

            #region Glyph Sampler

            string samplerId = resourceBaseId + ".Sampler";

            Sampler sampler = (Sampler)ctx.GetSharedResource(samplerId);

            if (sampler == null)
            {
                sampler = new Sampler();
                sampler.Parameters.MinFilter = TextureMinFilter.Linear;
            }

            #endregion

            #region Glyph Texture

            string textureId = resourceBaseId + ".Texture";

            _FontTexture = (TextureArray2d)ctx.GetSharedResource(textureId);

            if (_FontTexture == null)
            {
                // Get the size required for all glyphs
                float w = 0.0f, h = 0.0f;
                uint  z = 0;

                foreach (Glyph glyph in _GlyphMetadata.Values)
                {
                    w = Math.Max(w, glyph.GlyphSize.Width);
                    h = Math.Max(h, glyph.GlyphSize.Height);
                    z = Math.Max(z, glyph.Layer);
                }

                // Create texture
                _FontTexture         = new TextureArray2d();
                _FontTexture.Sampler = sampler;
                _FontTexture.Create(ctx, (uint)Math.Ceiling(w), (uint)Math.Ceiling(h), z + 1, PixelLayout.R8, 1);

                using (System.Drawing.Font font = new System.Drawing.Font(Family, Size, Style))
                    using (Brush brush = new SolidBrush(Color.White))
                    {
                        foreach (Glyph glyph in _GlyphMetadata.Values)
                        {
                            using (Bitmap bitmap = new Bitmap((int)_FontTexture.Width, (int)_FontTexture.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb))
                                using (Graphics g = Graphics.FromImage(bitmap)) {
                                    // Recompute texture scaling
                                    glyph.TexScale = new SizeF(
                                        glyph.GlyphSize.Width / bitmap.Width,
                                        glyph.GlyphSize.Height / bitmap.Height
                                        );

                                    // Avoid grid fitting
                                    g.TextRenderingHint = TextRenderingHint.AntiAlias;
                                    g.Clear(Color.Black);

                                    g.DrawString(glyph.GlyphChar.ToString(), font, brush, 0.0f, 0.0f, stringFormat);

                                    _FontTexture.Create(ctx, PixelLayout.R8, bitmap, glyph.Layer);
                                }
                        }
                    }

                // Share
                ctx.SetSharedResource(textureId, _FontTexture);
            }
            LinkResource(_FontTexture);

            #endregion
        }
Exemple #16
0
        private void VisionControl_ContextCreated(object sender, OpenGL.GlControlEventArgs e)
        {
            // Create GL context abstraction
            _GraphicsContext = new GraphicsContext(e.DeviceContext, e.RenderContext);

            // Create texture
            _FramebufferTexture = new Texture2d(1024, 1024, PixelLayout.RGB24);
            _FramebufferTexture.SamplerParams.MagFilter = TextureMagFilter.Linear;
            _FramebufferTexture.SamplerParams.MinFilter = TextureMinFilter.Linear;
            _FramebufferTexture.Create(_GraphicsContext);

            // Create framebuffer
            _Framebuffer = new Framebuffer();
            _Framebuffer.AttachColor(0, _FramebufferTexture);
            _Framebuffer.Create(_GraphicsContext);

            // Create shader (standard)
            _ProgramStd = _GraphicsContext.CreateProgram("OpenGL.Standard");
            _ProgramStd.Create(_GraphicsContext);

            // Create program (standard + texture)
            _ProgramStdTex = _GraphicsContext.CreateProgram("OpenGL.Standard+Texture");
            _ProgramStdTex.Create(_GraphicsContext);

            // Create vertex arrays (square)
            ArrayBuffer <Vertex2f> quadBuffer = new ArrayBuffer <Vertex2f>(BufferUsage.StaticDraw);

            quadBuffer.Create(new Vertex2f[] {
                new Vertex2f(-0.5f, +0.5f),
                new Vertex2f(-0.5f, -0.5f),
                new Vertex2f(+0.5f, +0.5f),
                new Vertex2f(+0.5f, -0.5f),
            });

            _ArraysQuad = new VertexArrays();
            _ArraysQuad.SetArray(quadBuffer, VertexArraySemantic.Position);
            _ArraysQuad.SetElementArray(PrimitiveType.TriangleStrip);
            _ArraysQuad.Create(_GraphicsContext);

            // Create vertex arrays (square)
            ArrayBuffer <Vertex2f> postquadBuffer = new ArrayBuffer <Vertex2f>(BufferUsage.StaticDraw);

            postquadBuffer.Create(new Vertex2f[] {
                new Vertex2f(0.0f, 1.0f),
                new Vertex2f(0.0f, 0.0f),
                new Vertex2f(1.0f, 1.0f),
                new Vertex2f(1.0f, 0.0f),
            });

            _ArraysPostQuad = new VertexArrays();
            _ArraysPostQuad.SetArray(postquadBuffer, VertexArraySemantic.Position);
            _ArraysPostQuad.SetArray(postquadBuffer, VertexArraySemantic.TexCoord);
            _ArraysPostQuad.SetElementArray(PrimitiveType.TriangleStrip);
            _ArraysPostQuad.Create(_GraphicsContext);

            // Create vertex arrays (optical markers)
            _BufferOpticalMarkers = new ArrayBuffer <Vertex2f>(BufferUsage.DynamicDraw);
            _BufferOpticalMarkers.Create(10000 * 2);

            _ArraysOpticalMarkers = new VertexArrays();
            _ArraysOpticalMarkers.SetArray(_BufferOpticalMarkers, VertexArraySemantic.Position);
            _ArraysOpticalMarkers.SetElementArray(PrimitiveType.Lines);
            _ArraysOpticalMarkers.Create(_GraphicsContext);
        }