lid6j86's picture

Texture Manager

Fixed up the class on the error checking side so it makes a little more sense. OOP style error checking definitely takes some getting used to.

It's a simple texture manager:
1. call TexLib.Initialize();
2. add all your textures through AddTexture(textureName, imagePath)

you can query cached textures through ListTextures(). Once you are finished with your textures, call ClearTextureCache() to free the resources up
you can also clear individual textures through RemoveTexture(textureName).

It basically uses a Key/Value listing so you can reference all of your textures by name (much easier to remember than integers).

If you notice any errors, optimizations, or things that would be nice to add please let me know. I'm still pretty much a new guy in this whole OpenGL thing.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
using System.Drawing;
using System.Drawing.Imaging;
using OpenTK.Graphics.OpenGL;
using OpenTK;
using System.IO;
 
namespace TK3
{
    public class TexLib
    {
        //Internal variables
        static Dictionary<string, int> mTexCache; //used to link a memorisable name to a texture buffer
        public static bool mFileLog = true;
 
 
 
 
        /// <summary>
        /// Clear the Texture Buffer List
        /// Enable OpenGL states for texture mapping
        /// </summary>
        public static void Initialize()
        {
            mTexCache = new Dictionary<string, int>();
            GL.Enable(EnableCap.Texture2D);
        }
 
 
 
 
        /// <summary>
        /// Add an image to the texture cache held by OpenGL
        /// </summary>
        /// <param name="pImageName"></param>
        /// <param name="pImagePath"></param>
        public static void AddTexture(string pImageName, string pImagePath)
        {
            int mTexBuffer = default(int);
 
            //ensure there is a path specified
            if(String.IsNullOrEmpty(pImagePath))
            {
                throw new ArgumentException("TexLib Error: AddTexture() - Invalid path supplied");
            }
 
           //create Texture Buffer, store it in the last element of the texture buffers  
            mTexBuffer = GL.GenTexture();
            GL.BindTexture(TextureTarget.Texture2D, mTexBuffer);
 
            //Load BITMAP and send it to OpenGL
            Bitmap image = default(Bitmap);
            BitmapData imageData = default(BitmapData);
 
            try
            {
                //load Bitmap
                image = new Bitmap(pImagePath);
                imageData = image.LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadOnly,
                                           System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            }
            catch(ArgumentException)
            {
                throw new FileNotFoundException("TexLib error: AddTexture() - Cannot find bitmap file");
            }
 
            try
            {
                //send to OpenGL
                GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, imageData.Width, imageData.Height, 0, 
                              OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, imageData.Scan0);
 
 
                //set texture parameters
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
 
                image.UnlockBits(imageData);
            }
            catch (Exception)
            {
                throw new ArgumentException("TexLib Error: AddTexture() - Error binding texture to OpenGL");
            }
 
            //attach TexBuffer to dictionary
            mTexCache.Add(pImageName, mTexBuffer);    
        }
 
 
 
 
        /// <summary>
        /// Removes a texture from the cache
        /// </summary>
        /// <param name="pImageName"></param>
        public static void RemoveTexture(string pImageName)
        {
            if(mTexCache.ContainsKey(pImageName) && GL.IsTexture(mTexCache[pImageName]) )
            {
                GL.DeleteTexture(mTexCache[pImageName]);
                mTexCache.Remove(pImageName);
            }
            else
            {
                throw new KeyNotFoundException("TexLib Error: RemoveTexture() - Texture key not found");
            }
        }
 
 
 
 
        /// <summary>
        /// Clear all texture-related resources
        /// </summary>
        public static void ClearTextureCache()
        {
            foreach (KeyValuePair<string, int> feTexBuffer in mTexCache)
            {
                GL.DeleteTexture(feTexBuffer.Value);
            }
            mTexCache.Clear();    
        }
 
 
 
 
        /// <summary>
        ///Return an integer value of a texture buffer object 
        ///throws KeyNotFoundException if key can't be found
        /// </summary>
        /// <param name="pImageName"></param>
        public static int GetTexture(string pImageName)
        {
            if(mTexCache.ContainsKey(pImageName))
            {
                return mTexCache[pImageName];
            }
            else
            {
                throw new KeyNotFoundException("TexLib Error: GetTexture() - Texture key not found");
            }
        }
 
 
 
 
        /// <summary>
        /// display a list of textures cached
        /// </summary>
        /// <returns></returns>
        public static string ListTextures()
        {
            string texList = "No Textures Cached";
 
            if (mTexCache.Count > 0)
            {
                foreach (KeyValuePair<string, int> feTexBuffer in mTexCache)
                {
                    texList += feTexBuffer.Value + ": " + feTexBuffer.Key + "\n";
                }
            }
            return texList;       
       }
 
    }//END CLASS
}//END NAMESPACE

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
lid6j86's picture

I've been playing around with it a little and realized i have to deal with nullreferenceexception