Ejemplo n.º 1
0
        private Texture loadRaw(TextureUpload upload, WrapMode wrapModeS = WrapMode.None, WrapMode wrapModeT = WrapMode.None)
        {
            if (upload == null)
            {
                return(null);
            }

            TextureGL glTexture = null;

            if (Atlas != null)
            {
                if ((glTexture = Atlas.Add(upload.Width, upload.Height, wrapModeS, wrapModeT)) == null)
                {
                    Logger.Log(
                        $"Texture requested ({upload.Width}x{upload.Height}) which exceeds {nameof(TextureStore)}'s atlas size ({max_atlas_size}x{max_atlas_size}) - bypassing atlasing. Consider using {nameof(LargeTextureStore)}.",
                        LoggingTarget.Performance);
                }
            }

            glTexture ??= new TextureGLSingle(upload.Width, upload.Height, manualMipmaps, filteringMode, wrapModeS, wrapModeT);

            Texture tex = new Texture(glTexture)
            {
                ScaleAdjust = ScaleAdjust
            };

            tex.SetData(upload);

            return(tex);
        }
Ejemplo n.º 2
0
        public TextureWithRefCount(TextureGL textureGl, ReferenceCount count)
            : base(textureGl)
        {
            this.count = count;

            count.Increment();
        }
Ejemplo n.º 3
0
 /// <summary>
 /// Enqueues a texture to be uploaded in the next frame.
 /// </summary>
 /// <param name="texture">The texture to be uploaded.</param>
 public static void EnqueueTextureUpload(TextureGL texture)
 {
     if (host != null)
     {
         expensive_operations_queue.Enqueue(() => texture.Upload());
     }
 }
Ejemplo n.º 4
0
        protected override void InitializeService()
        {
            TextureGL      patch6             = materialManager.Texture("res/images/ninepatch6.png", false);
            TextureGL      patch7             = materialManager.Texture("res/images/ninepatch7.png", false);
            Vector2        padding            = new Vector2(6.0f, 6.0f);
            Vector2        innerPadding       = new Vector2(2.0f, 2.0f);
            NinePatchStyle ninePatchStyle     = new NinePatchStyle(patch6);
            NinePatchStyle foreNinePatchStyle = new NinePatchStyle(patch7);

            Style.NullPadding = new Style(
                new Vector2(0.0f, 0.0f),
                new Vector2(0.0f, 0.0f),
                null,
                null,
                null
                );
            Style.Background = new Style(
                padding,
                innerPadding,
                (textRenderer != null) ? textRenderer.FontStyle : null,
                ninePatchStyle,
                renderer.Programs["Ninepatch"]
                );
            Style.Foreground = new Style(
                padding,
                innerPadding,
                (textRenderer != null) ? textRenderer.FontStyle : null,
                foreNinePatchStyle,
                renderer.Programs["Font"]
                );
            Style.Default = Style.Background;
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Binds a texture to draw with.
        /// </summary>
        /// <param name="texture">The texture to bind.</param>
        /// <param name="unit">The texture unit to bind it to.</param>
        /// <param name="wrapModeS">The texture wrap mode in horizontal direction.</param>
        /// <param name="wrapModeT">The texture wrap mode in vertical direction.</param>
        /// <returns>true if the provided texture was not already bound (causing a binding change).</returns>
        public static bool BindTexture(TextureGL texture, TextureUnit unit = TextureUnit.Texture0, WrapMode wrapModeS = WrapMode.None, WrapMode wrapModeT = WrapMode.None)
        {
            bool didBind = BindTexture(texture?.TextureId ?? 0, unit, wrapModeS, wrapModeT);

            last_bound_texture_is_atlas[GetTextureUnitId(unit)] = texture is TextureGLAtlas;

            return(didBind);
        }
Ejemplo n.º 6
0
        public void Quad(TextureGL texture)
        {
            float   z          = 10.0f;
            Vector3 bottomLeft = new Vector3(4.0f, 4.0f, z);
            Vector3 topRight   = bottomLeft + new Vector3(texture.Size.Width, texture.Size.Height, z);

            Quad(bottomLeft, topRight);
        }
Ejemplo n.º 7
0
 public Texture(TextureGL textureGl)
 {
     if (textureGl == null)
     {
         throw new ArgumentNullException(nameof(textureGl));
     }
     TextureGL = textureGl;
 }
Ejemplo n.º 8
0
        /// <summary>
        /// Binds a texture to draw with.
        /// </summary>
        /// <param name="texture">The texture to bind.</param>
        /// <param name="unit">The texture unit to bind it to.</param>
        /// <returns>true if the provided texture was not already bound (causing a binding change).</returns>
        public static bool BindTexture(TextureGL texture, TextureUnit unit = TextureUnit.Texture0)
        {
            bool didBind = BindTexture(texture?.TextureId ?? 0, unit);

            last_bound_texture_is_atlas[GetTextureUnitId(unit)] = texture is TextureGLAtlas;

            return(didBind);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Enqueues a texture to be uploaded in the next frame.
        /// </summary>
        /// <param name="texture">The texture to be uploaded.</param>
        public static void EnqueueTextureUpload(TextureGL texture)
        {
            if (!HasContext)
            {
                return;
            }

            resetScheduler.Add(() => texture.Upload());
        }
Ejemplo n.º 10
0
        public TextureGL Texture(string path, bool generateMipmaps)
        {
            if (materials.ContainsKey(path))
            {
                return(textures[path]);
            }
            var texture = new TextureGL(new Image(path), true);

            textures[path] = texture;
            return(texture);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Binds a texture to darw with.
        /// </summary>
        /// <param name="texture"></param>
        public static void BindTexture(TextureGL texture)
        {
            if (lastBoundTexture != texture)
            {
                FlushCurrentBatch();

                GL.BindTexture(TextureTarget.Texture2D, texture?.TextureId ?? 0);
                lastBoundTexture = texture;

                FrameStatistics.Increment(StatisticsCounterType.TextureBinds);
            }
        }
Ejemplo n.º 12
0
        public void TestAtlasSecondRowAddRespectsWhitePixelSize()
        {
            const int atlas_size = 1024;

            var atlas = new TextureAtlas(atlas_size, atlas_size);

            TextureGL texture = atlas.Add(atlas_size - 2 * TextureAtlas.PADDING, 64);

            RectangleF rect = texture.GetTextureRect(null);

            Assert.GreaterOrEqual(atlas_size * rect.X, TextureAtlas.PADDING, message: "Texture has insufficient padding");
            Assert.GreaterOrEqual(atlas_size * rect.Y, TextureAtlas.WHITE_PIXEL_SIZE + TextureAtlas.PADDING, message: "Texture is placed on top of the white pixel");
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Enqueues a texture to be uploaded in the next frame.
        /// </summary>
        /// <param name="texture">The texture to be uploaded.</param>
        public static void EnqueueTextureUpload(TextureGL texture)
        {
            if (texture.IsQueuedForUpload)
            {
                return;
            }

            if (host != null)
            {
                texture.IsQueuedForUpload = true;
                texture_upload_queue.Enqueue(texture);
            }
        }
Ejemplo n.º 14
0
        protected override void InitializeService()
        {
            renderer.Resize       += new EventHandler <EventArgs>(renderer_Resize);
            quadRenderer           = new QuadRenderer(renderer);
            blit                   = renderer.Programs["VisualizeOpenRL"];
            texture                = new TextureGL(128, 128, PixelFormat.Rgba, PixelInternalFormat.Rg32f);
            material               = materialManager.MakeMaterial("VisualizeOpenRL");
            material.DepthState    = DepthState.Disabled;
            material.FaceCullState = FaceCullState.Disabled;

            UpdateQuad();
            InitializeOpenRL();
        }
Ejemplo n.º 15
0
        private void Dispose(bool isDisposing)
        {
            if (IsDisposed)
            {
                return;
            }
            IsDisposed = true;

            if (TextureGL != null)
            {
                TextureGL.Dispose();
                TextureGL = null;
            }
        }
Ejemplo n.º 16
0
        protected void DrawClipped <T>(ref T polygon, TextureGL texture, ColourInfo drawColour, RectangleF?textureRect = null, Action <TexturedVertex2D> vertexAction = null,
                                       Vector2?inflationPercentage = null)
            where T : IConvexPolygon
        {
            var maskingQuad = GLWrapper.CurrentMaskingInfo.ConservativeScreenSpaceQuad;

            var            clipper       = new ConvexPolygonClipper <Quad, T>(ref maskingQuad, ref polygon);
            Span <Vector2> buffer        = stackalloc Vector2[clipper.GetClipBufferSize()];
            Span <Vector2> clippedRegion = clipper.Clip(buffer);

            for (int i = 2; i < clippedRegion.Length; i++)
            {
                DrawTriangle(texture, new Triangle(clippedRegion[0], clippedRegion[i - 1], clippedRegion[i]), drawColour, textureRect, vertexAction, inflationPercentage);
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Binds a texture to darw with.
        /// </summary>
        /// <param name="texture">The texture to bind.</param>
        /// <param name="unit">The texture unit to bind it to.</param>
        public static void BindTexture(TextureGL texture, TextureUnit unit = TextureUnit.Texture0)
        {
            var index = GetTextureUnitId(unit);

            if (last_bound_texture[index] != texture)
            {
                FlushCurrentBatch();

                GL.ActiveTexture(unit);
                GL.BindTexture(TextureTarget.Texture2D, texture?.TextureId ?? 0);
                last_bound_texture[index] = texture;

                FrameStatistics.Increment(StatisticsCounterType.TextureBinds);
            }
        }
Ejemplo n.º 18
0
        protected override void Dispose(bool isDisposing)
        {
            if (IsDisposed)
            {
                throw new ObjectDisposedException($"{nameof(TextureWithRefCount)} should never be disposed more than once");
            }

            base.Dispose(isDisposing);

            TextureGL?.Dereference();
            if (isDisposing)
            {
                GC.SuppressFinalize(this);
            }
        }
Ejemplo n.º 19
0
        internal FrameBuffer(bool withTexture = true)
        {
            frameBuffer = GL.GenFramebuffer();

            if (withTexture)
            {
                Texture = new TextureGLSingle(1, 1);
                Texture.SetData(new byte[0]);
                Texture.Upload();

                Bind();

                GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, FramebufferSlot.ColorAttachment0, TextureTarget.Texture2D, Texture.TextureId, 0);
                GLWrapper.BindTexture(0);

                Unbind();
            }
        }
Ejemplo n.º 20
0
        public FrameBuffer(bool withTexture = true)
        {
            frameBuffer = GL.GenFramebuffer();

            if (withTexture)
            {
                Texture = new TextureGLSingle(1, 1);
                Texture.SetData(new TextureUpload(0));
                Texture.Upload();

                Bind();

                GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, All.ColorAttachment0, TextureTarget2d.Texture2D, Texture.TextureId, 0);
                GLWrapper.BindTexture(0);

                Unbind();
            }
        }
Ejemplo n.º 21
0
        private void InitializeTextureUnits()
        {
            //  Bind a dummy texture to all texture units
            byte[] whiteData = new byte[4];
            whiteData[0] = 255;
            whiteData[1] = 255;
            whiteData[2] = 255;
            whiteData[3] = 255;
            dummyTexture = new TextureGL(1, 1, PixelFormat.Rgba, PixelInternalFormat.Rgba);
            dummyTexture.Upload(whiteData, 0);
            nearestSampler           = new SamplerGL1();
            nearestSampler.MinFilter = TextureMinFilter.Nearest;
            nearestSampler.MagFilter = TextureMagFilter.Nearest;
            nearestSampler.Wrap      = TextureWrapMode.ClampToEdge;
            int textureUnits = 4;

            try
            {
                GL.GetInteger(GetPName.MaxTextureUnits, out textureUnits);
            }
            catch (Exception)
            {
            }
            for (int i = 0; i < textureUnits; ++i)
            {
                try
                {
                    GL.ActiveTexture(TextureUnit.Texture0 + i);
                    dummyTexture.Apply();
                    nearestSampler.Apply(i, TextureTarget.Texture2D);
                }
                catch (Exception)
                {
                }
            }

            float[] zeros = { 0.0f, 0.0f, 0.0f, 0.0f };
            for (int i = 0; i < 8; ++i)
            {
                GL.Light(LightName.Light0 + i, LightParameter.Ambient, zeros);
            }
        }
Ejemplo n.º 22
0
        public void UnbindTexture(string key, TextureGL texture)
        {
            var samplerUniform = Samplers.Global.Sampler(key);

            if (samplerUniform == null)
            {
                return;
            }

            int textureUnitIndex = samplerUniform.TextureUnitIndex;

            if (textureUnitIndex == -1)
            {
                return;
            }

            GL.ActiveTexture(TextureUnit.Texture0 + textureUnitIndex);
            texture.Unbind();

            // \todo cache textures? textures[key] = texture;
        }
Ejemplo n.º 23
0
        protected override void InitializeService()
        {
            {
                Image whiteImage = new Image(16, 16, 1.0f, 1.0f, 1.0f, 1.0f);
                var   white      = textures["White"] = new TextureGL(whiteImage, true);
            }

            int lightCount = example.Renderer.Configuration.maxLightCount;

            if (RenderStack.Graphics.Configuration.useGl1 == false)
            {
                System.Single[] whiteData = new System.Single[lightCount];
                for (int i = 0; i < lightCount; ++i)
                {
                    whiteData[i] = 1.0f;
                }
                var noShadow = textures["NoShadow"] = new TextureGL(1, 1, PixelFormat.Red, PixelInternalFormat.R16f, lightCount);
                noShadow.Upload(whiteData, 0);
            }

            EnableSeamlessCubemaps();
        }
Ejemplo n.º 24
0
        private void testWithSize(int width, int height)
        {
            TextureAtlas atlas   = new TextureAtlas(1024, 1024);
            TextureGL    texture = atlas.Add(width, height);

            if (texture != null)
            {
                Assert.AreEqual(texture.Width, width, message: $"Width: {texture.Width} != {width} for texture {width}x{height}");
                Assert.AreEqual(texture.Height, height, message: $"Height: {texture.Height} != {height} for texture {width}x{height}");

                RectangleF rect = texture.GetTextureRect(null);
                Assert.LessOrEqual(rect.X + rect.Width, 1, message: $"Returned texture is wider than TextureAtlas for texture {width}x{height}");
                Assert.LessOrEqual(rect.Y + rect.Height, 1, message: $"Returned texture is taller than TextureAtlas for texture {width}x{height}");
            }
            else
            {
                Assert.True(width > 1024 - TextureAtlas.PADDING * 2 || height > 1024 - TextureAtlas.PADDING * 2 ||
                            (width > 1024 - TextureAtlas.PADDING * 2 - TextureAtlas.WHITE_PIXEL_SIZE &&
                             height > 1024 - TextureAtlas.PADDING * 2 - TextureAtlas.WHITE_PIXEL_SIZE),
                            message: $"Returned texture is null, but should have fit: {width}x{height}");
            }
        }
Ejemplo n.º 25
0
        float ReadRedAverage(HemicubeFramebuffer fbo)
        {
            TextureGL texture = framebuffer[(int)fbo][FramebufferAttachment.ColorAttachment0];

            texture.GenerateMipmap();

            // TODO AccessViolatonException
            bool found = false;

            while (
                (found == false) &&
                (smallestMipmapLevel >= 0)
                )
            {
                try
                {
                    framebuffer[(int)fbo].AttachTextureLevel(FramebufferAttachment.ColorAttachment0, smallestMipmapLevel);
                    found = true;
                }
                catch (Exception)
                {
                    System.Diagnostics.Trace.TraceWarning("TODO");
                    --smallestMipmapLevel;
                }
                if (smallestMipmapLevel == -1)
                {
                    System.Diagnostics.Trace.TraceWarning("TODO");
                    return(0);
                }
            }
            float[] pixels = new float[4];
            float[] depths = new float[4];
            GL.ReadBuffer(ReadBufferMode.ColorAttachment0);
            GL.ReadPixels <float>(0, 0, 1, 1, PixelFormat.Red, PixelType.Float, pixels);
            framebuffer[(int)fbo].AttachTextureLevel(FramebufferAttachment.ColorAttachment0, 0);

            return(pixels[0]);
        }
        protected override void InitializeService()
        {
            renderer.Resize += new EventHandler <EventArgs>(renderer_Resize);

            depthTexture = new TextureGL(renderer.Width, renderer.Height, PixelFormat.Red, PixelInternalFormat.R32f);
            quadRenderer = new QuadRenderer(renderer);
            {
                var m = materialManager.MakeMaterial("VisualizeDepth");
                m.DepthState    = DepthState.Disabled;
                m.FaceCullState = FaceCullState.Disabled;
            }

            stencilTexture      = new TextureGL(renderer.Width, renderer.Height, PixelFormat.Red, PixelInternalFormat.R8);
            stencilQuadRenderer = new QuadRenderer(renderer);
            {
                var m = materialManager.MakeMaterial("VisualizeStencil");
                m.DepthState    = DepthState.Disabled;
                m.FaceCullState = FaceCullState.Disabled;
            }

            depthReadBuffer   = new float[extra + renderer.Width * renderer.Height];
            stencilReadBuffer = new byte[extra + renderer.Width * renderer.Height];
        }
Ejemplo n.º 27
0
 public Texture(TextureGL textureGl)
 {
     Debug.Assert(textureGl != null);
     TextureGL = textureGl;
 }
Ejemplo n.º 28
0
 public TextureWithRefCount(TextureGL textureGl)
     : base(textureGl)
 {
     TextureGL.Reference();
 }
Ejemplo n.º 29
0
 public void UnbindTexture(string key, TextureGL texture)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 30
0
 public TextureWhitePixel(TextureGL textureGl)
     : base(textureGl)
 {
 }
Ejemplo n.º 31
0
        // =====================================================================
        // Updating
        // =====================================================================
        // =====================================================================
        // Shortcuts
        // =====================================================================
        // =====================================================================
        // Overrides
        // =====================================================================
        // =====================================================================
        // Private functions
        // =====================================================================
        private void InitGL()
        {
            GL.ClearColor(GlobalSettings.BackgroundColor);

            GL.Enable(EnableCap.Texture2D);
            GL.ShadeModel(ShadingModel.Smooth); // Enable Smooth Shading
            GL.Enable(EnableCap.DepthTest); // Enables Depth Testing
            GL.DepthFunc(DepthFunction.Lequal); // The Type Of Depth Testing To Do
            GL.Hint(HintTarget.PerspectiveCorrectionHint, HintMode.Nicest); // Really Nice Perspective Calculations
            GL.Enable(EnableCap.Blend);
            GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);
            GL.TexEnv(TextureEnvTarget.TextureEnv, TextureEnvParameter.TextureEnvMode, (int)TextureEnvMode.Modulate);

            _toolboxUpNormal = new TextureGL(Resources.buttong);
            _toolboxUpHover = new TextureGL(Resources.buttong_2);
            _toolboxDownNormal = new TextureGL(Resources.buttong_down);
            _toolboxDownHover = new TextureGL(Resources.buttong_down2);
            _cubeSides = new TextureGL(Resources.cube_sides);
            _cubeSides.SetMipmapping(true);
            _cubeSides.SetRepeat(true);

            _font = new TextureGL(Resources.tinyfont);
            _font.SetMipmapping(false);
            _font.SetRepeat(false);

            _grassTop = new TextureGL(GlobalSettings.GetDataURI("grass.png"));
            _grassTop.SetMipmapping(false);
            _grassTop.SetRepeat(true);

            _dynamicOverlay = new BackgroundImage("Dynamic", "Dynamic", null);
            _dynamicOverlay.Item = mDYNAMICOVERLAYToolStripMenuItem;
            _backgrounds.Add(_dynamicOverlay);

            foreach (string file in Directory.GetFiles(GlobalSettings.GetDataURI("Overlays"), "*.png"))
            {
                try
                {
                    var image = new TextureGL(file);
                    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest);
                    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Nearest);
                    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.Clamp);
                    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.Clamp);

                    _backgrounds.Add(new BackgroundImage(file, Path.GetFileNameWithoutExtension(file), image));
                }
                catch
                {
                    MessageBox.Show(this, string.Format(GetLanguageString("B_MSG_OVERLAYERROR"), file));
                }
            }

            int index = 0;
            foreach (BackgroundImage b in _backgrounds)
            {
                ToolStripMenuItem item = b.Item ?? new ToolStripMenuItem(b.Name);
                b.Item = item;

                if (b.Path == GlobalSettings.LastBackground)
                {
                    item.Checked = true;
                    _selectedBackground = index;
                }

                item.Click += item_Clicked;
                item.Tag = index++;

                if (!backgroundsToolStripMenuItem.DropDownItems.Contains(item))
                    backgroundsToolStripMenuItem.DropDownItems.Add(item);
            }

            _previewPaint = new TextureGL();
            GlobalDirtiness.CurrentSkin = new TextureGL();
            _alphaTex = new TextureGL();

            var arra = new byte[64 * 32];
            _previewPaint.Upload(arra, 64, 32);
            _previewPaint.SetMipmapping(false);
            _previewPaint.SetRepeat(false);

            GlobalDirtiness.CurrentSkin.Upload(arra, 64, 32);
            GlobalDirtiness.CurrentSkin.SetMipmapping(false);
            GlobalDirtiness.CurrentSkin.SetRepeat(false);

            arra = new byte[]
            {
                127,
                127,
                127,
                255,
                80,
                80,
                80,
                255,
                80,
                80,
                80,
                255,
                127,
                127,
                127,
                255
            };

            _alphaTex.Upload(arra, 2, 2);
            _alphaTex.SetMipmapping(false);
            _alphaTex.SetRepeat(true);

            bool supportsArrays = GL.GetString(StringName.Extensions).Contains("GL_EXT_vertex_array");
            bool forceImmediate = GlobalSettings.RenderMode == 0;

            clientArraysToolStripMenuItem.Enabled = supportsArrays;

            if (supportsArrays && !forceImmediate)
            {
                MeshRenderer = new ClientArrayRenderer();
                clientArraysToolStripMenuItem.Checked = true;
                GlobalSettings.RenderMode = 1;
            }
            else
            {
                MeshRenderer = new ImmediateRenderer();
                immediateToolStripMenuItem.Checked = true;
                GlobalSettings.RenderMode = 0;
            }
        }
Ejemplo n.º 32
0
        private Texture GetPaintTexture(int width, int height)
        {
            if (!_charPaintSizes.ContainsKey(new Size(width, height)))
            {
                var tex = new TextureGL();

                var arra = new int[width * height];
                unsafe
                {
                    fixed (int* texData = arra)
                    {
                        int* d = texData;

                        for (int y = 0; y < height; ++y)
                        {
                            for (int x = 0; x < width; ++x)
                            {
                                *d = ((y * width) + x) | (255 << 24);
                                d++;
                            }
                        }
                    }
                }

                tex.Upload(arra, width, height);
                tex.SetMipmapping(false);
                tex.SetRepeat(false);

                _charPaintSizes.Add(new Size(width, height), tex);

                return tex;
            }

            return _charPaintSizes[new Size(width, height)];
        }