2

I've been trying to draw a timer on the screen in openTK (in c#), and to do this I have been generating new textures and deleting old ones, but my program still hogs up memory until it crashes because there's not enough space for another bitmap.

here's what I'm doing:

        text_bmp = new Bitmap(width, height);
        text_bmp_gfx = Graphics.FromImage(text_bmp);
        text_bmp_gfx.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
        text_bmp_gfx.Clear(Color.Transparent);
        text_bmp_gfx.DrawString(music.getCurrentTime(), new Font("Exo 2", 12), drawBrush, new PointF(0.0F, 0.0F));
        text_bmp_gfx.DrawString(timer.Elapsed.ToString(), new Font("Exo 2", 12), drawBrush, new PointF(0.0F, 18.0F));
        GL.DeleteTexture(TextTexture);
        TextTexture = ContentPipe.LoadTextureFromBitmap(text_bmp);
        GL.BindTexture(TextureTarget.Texture2D, TextTexture);

where content pipe.loadtexturefrombitmap is this function:

public static int LoadTextureFromBitmap(Bitmap bmp)
    {
        int id = GL.GenTexture();
        GL.BindTexture(TextureTarget.Texture2D, id);
        BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
        GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, data.Width, data.Height, 0, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0);
        bmp.UnlockBits(data);
        GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.Clamp);
        GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.Clamp);
        GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
        GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
        bmp = null;
        return id;
    }

to be perfectly honest the second part was copied from a youtube tutorial, so I'm not sure how it works.

I think the problem is that I'm not properly deallocating memory from openTK textures after I don't need them, so I'm generating massive amounts of images, but I don't know how to fix this.

genpfault
  • 51,148
  • 11
  • 85
  • 139
maboesanman
  • 387
  • 4
  • 15

1 Answers1

1

for those finding this, there are two important parts:

call dispose() on BOTH the bitmap and graphics objects

manually garbage collect.

making 60 large images a second is a bit much for automatic garbage collection apparently, so i call garbage collect once a frame and it works great!

maboesanman
  • 387
  • 4
  • 15