/// <summary> /// Загрузчик текстур с использованием технологий MipMapping и Anisotropic Filtering (если поддерживается аппаратно). /// </summary> /// <param name="imagePath">Путь(и) к текстуре(ам) для загрузки.</param> /// <param name="generateMipMap">Флаг использования технологии MipMapping. Если <b>true</b> - технология будет использована.</param> /// <param name="filterType">Режим фильтрации MipMap текстур.</param> /// <param name="anisotropyLevel">Уровень анизотропной фильтрации (если поддерживается аппаратно). Если <b>-1.0f</b> - будет использован максимальный режим анизотропной фильтрации.</param> public Texture1D(string[] imagePath, bool generateMipMap = true, MipmapTextureFilter filterType = MipmapTextureFilter.LinearMipmapLinear, float anisotropyLevel = -1.0f) { TextureID = new List <uint>(); uint[] tempID = Texture1D.GenImagies(imagePath, generateMipMap, anisotropyLevel, filterType); foreach (uint id in tempID) { TextureID.Add(id); } }
private static uint[] GenImagies(string[] imagePath, bool generateMipMap, float anisotropyLevel, MipmapTextureFilter filterType = MipmapTextureFilter.LinearMipmapLinear) { uint[] glTextureID = new uint[imagePath.Length]; Int32 iterator = 0; foreach (string url in imagePath) { Bitmap image = null; success = false; try { image = new Bitmap(url); #region Bitmap data // если загрузка прошла успешно // сохраняем размеры изображения Int32 width = image.Width; // определяем число бит на пиксель Int32 pixelFormat = 0; Int32 bitsPerPixel = 0; SystemPixelFormat sPixelFormat = image.PixelFormat; switch (sPixelFormat) { case SystemPixelFormat.Format24bppRgb: pixelFormat = (Int32)SystemPixelFormat.Format24bppRgb; bitsPerPixel = 24; break; case SystemPixelFormat.Format32bppRgb: pixelFormat = (Int32)SystemPixelFormat.Format32bppRgb; bitsPerPixel = 32; break; case SystemPixelFormat.Format32bppArgb: pixelFormat = (Int32)SystemPixelFormat.Format32bppArgb; bitsPerPixel = 32; break; case SystemPixelFormat.Format32bppPArgb: pixelFormat = (Int32)SystemPixelFormat.Format32bppPArgb; bitsPerPixel = 32; break; default: pixelFormat = 0; bitsPerPixel = 0; break; } //get the data out of the bitmap SystemBitmapData textureData = image.LockBits( new Rectangle(0, 0, width, 1), System.Drawing.Imaging.ImageLockMode.ReadOnly, (SystemPixelFormat)pixelFormat ); #endregion switch (bitsPerPixel) // в зависимости от полученного результата { // создаем текстуру, используя режим GL_RGB или GL_RGBA case 24: glTextureID[iterator] = MakeGlTexture(24, textureData.Scan0, width, generateMipMap, anisotropyLevel, filterType); // активируем флаг, сигнализирующий загрузку текстуры success = true; break; case 32: glTextureID[iterator] = MakeGlTexture(32, textureData.Scan0, width, generateMipMap, anisotropyLevel, filterType); // активируем флаг, сигнализирующий загрузку текстуры success = true; break; default: success = false; break; } if (success == false) { throw new Exception("wrong image path : " + iterator.ToString()); } // очищаем память image.UnlockBits(textureData); image.Dispose(); iterator++; } catch { throw new Exception("wrong image path or data : " + iterator.ToString()); } } return(glTextureID); }
private Int32 CreateTexture(string imagePath, bool generateMipMap, float anisotropyLevel, TextureWrapMode texWrap = TextureWrapMode.Repeat, MipmapTextureFilter filterType = MipmapTextureFilter.LinearMipmapLinear) { Int32 glTextureID = 0; Bitmap image = null; var success = false; try { image = new Bitmap(imagePath); } catch (ArgumentException) { // Error - file path is invalid return(-1); } Int32 width = image.Width; Int32 height = image.Height; TextureParameters.TexBufferWidth = width; TextureParameters.TexBufferHeight = height; Int32 pixelFormat = 0; Int32 bitsPerPixel = 0; SystemPixelFormat sPixelFormat = image.PixelFormat; switch (sPixelFormat) { case SystemPixelFormat.Format24bppRgb: pixelFormat = (Int32)SystemPixelFormat.Format24bppRgb; bitsPerPixel = 24; break; case SystemPixelFormat.Format32bppRgb: pixelFormat = (Int32)SystemPixelFormat.Format32bppRgb; bitsPerPixel = 32; break; case SystemPixelFormat.Format32bppArgb: pixelFormat = (Int32)SystemPixelFormat.Format32bppArgb; bitsPerPixel = 32; break; case SystemPixelFormat.Format32bppPArgb: pixelFormat = (Int32)SystemPixelFormat.Format32bppPArgb; bitsPerPixel = 32; break; default: pixelFormat = 0; bitsPerPixel = 0; break; } //get the data out of the bitmap SystemBitmapData textureData = image.LockBits( new Rectangle(0, 0, width, height), System.Drawing.Imaging.ImageLockMode.ReadOnly, (SystemPixelFormat)pixelFormat ); switch (bitsPerPixel) { case 24: glTextureID = GenerateTexture(24, textureData.Scan0, width, height, generateMipMap, anisotropyLevel, texWrap, filterType); success = true; break; case 32: glTextureID = GenerateTexture(32, textureData.Scan0, width, height, generateMipMap, anisotropyLevel, texWrap, filterType); success = true; break; default: success = false; break; } try { if (success == false) { throw new BadImageFormatException("wrong image path"); } } catch (BadImageFormatException ex) { throw new EntryPointNotFoundException(ex.Message, ex); } image.UnlockBits(textureData); image.Dispose(); return(glTextureID); }
private static uint MakeGlTexture(Int32 Format, IntPtr pixels, Int32 width, bool generateMipMap, float anisotropyLevel, MipmapTextureFilter filterType) { // идентификатор текстурного объекта uint texObject; // генерируем текстурный объект GL.GenTextures(1, out texObject); // устанавливаем режим упаковки пикселей GL.PixelStore(PixelStoreParameter.UnpackAlignment, 1); // создаем привязку к только что созданной текстуре GL.BindTexture(TextureTarget.Texture1D, texObject); // устанавливаем режим фильтрации и повторения текстуры GL.TexParameter(TextureTarget.Texture1D, TextureParameterName.TextureWrapS, (Int32)TextureWrapMode.Repeat); GL.TexParameter(TextureTarget.Texture1D, TextureParameterName.TextureWrapT, (Int32)TextureWrapMode.Repeat); GL.TexParameter(TextureTarget.Texture1D, TextureParameterName.TextureMagFilter, (Int32)TextureMagFilter.Linear); if (!generateMipMap) { GL.TexParameter(TextureTarget.Texture1D, TextureParameterName.TextureMinFilter, (Int32)TextureMinFilter.Linear); } else { if (CheckForAnisotropicTextureFiltering()) { GL.TexParameter(TextureTarget.Texture1D, (TextureParameterName)ExtTextureFilterAnisotropic.TextureMaxAnisotropyExt, (anisotropyLevel == -1.0f) ? maxAnisotropy : (anisotropyLevel >= maxAnisotropy) ? maxAnisotropy : (anisotropyLevel < 0.0f) ? 0.0f : anisotropyLevel); } GL.TexParameter(TextureTarget.Texture1D, TextureParameterName.TextureMinFilter, (Int32)filterType); GL.TexParameter(TextureTarget.Texture1D, TextureParameterName.GenerateMipmap, 1); GL.TexParameter(TextureTarget.Texture1D, TextureParameterName.TextureLodBias, -0.4f); // might need to use variable to change this value } GL.TexEnv(TextureEnvTarget.TextureEnv, TextureEnvParameter.TextureEnvMode, (Int32)TextureEnvMode.Replace); // создаем RGB или RGBA текстуру switch (Format) { case 24: GL.TexImage1D(TextureTarget.Texture1D, 0, PixelInternalFormat.Rgb, width, 0, PixelFormat.Rgb, PixelType.UnsignedByte, pixels); break; case 32: GL.TexImage1D(TextureTarget.Texture1D, 0, PixelInternalFormat.Rgba, width, 0, PixelFormat.Rgba, PixelType.UnsignedByte, pixels); break; } // возвращаем идентификатор текстурного объекта return(texObject); }
private Int32 GenerateTexture(Int32 format, IntPtr pixels, Int32 width, Int32 height, bool generateMipMap, float anisotropyLevel, TextureWrapMode texWrap, MipmapTextureFilter filterType) { Int32 texObject; GL.GenTextures(1, out texObject); GL.PixelStore(PixelStoreParameter.UnpackAlignment, 1); GL.BindTexture(TextureTarget.Texture2D, texObject); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (Int32)texWrap); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (Int32)texWrap); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (Int32)TextureMagFilter.Linear); if (!generateMipMap) { GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (Int32)TextureMinFilter.Linear); } else { if (CheckForAnisotropicTextureFiltering()) { GL.TexParameter(TextureTarget.Texture2D, (TextureParameterName)ExtTextureFilterAnisotropic.TextureMaxAnisotropyExt, (anisotropyLevel == -1.0f) ? MaxAnisotropy : (anisotropyLevel >= MaxAnisotropy) ? MaxAnisotropy : (anisotropyLevel < 0.0f) ? 0.0f : anisotropyLevel); } GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (Int32)filterType); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.GenerateMipmap, 1); // 1 stands for TRUE statement GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureLodBias, -0.4f); // might need to use variable to change this value } GL.TexEnv(TextureEnvTarget.TextureEnv, TextureEnvParameter.TextureEnvMode, (Int32)TextureEnvMode.Replace); switch (format) { case 24: GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgb, width, height, 0, OpenTK.Graphics.OpenGL.PixelFormat.Bgr, PixelType.UnsignedByte, pixels); break; case 32: GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, width, height, 0, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, pixels); break; } // возвращаем идентификатор текстурного объекта return(texObject); }