ImageTexture.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // $Id$
  2. using System;
  3. using Sdl;
  4. using OpenGl;
  5. namespace Drawing
  6. {
  7. public sealed class ImageTexture : Texture
  8. {
  9. public float ImageWidth;
  10. public float ImageHeight;
  11. public int refcount;
  12. public ImageTexture(IntPtr surface)
  13. {
  14. Create(surface);
  15. }
  16. private unsafe void Create(IntPtr sdlsurface)
  17. {
  18. Sdl.Surface* surface = (Sdl.Surface*) sdlsurface;
  19. uint width = NextPowerOfTwo((uint) surface->w);
  20. uint height = NextPowerOfTwo((uint) surface->h);
  21. IntPtr pixelbufferp;
  22. if(BitConverter.IsLittleEndian) {
  23. pixelbufferp = SDL.CreateRGBSurface(SDL.SWSURFACE,
  24. (int) width, (int) height, 32,
  25. 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000);
  26. } else {
  27. pixelbufferp = SDL.CreateRGBSurface(SDL.SWSURFACE,
  28. (int) width, (int) height, 32,
  29. 0xff000000, 0x00ff0000, 0x0000ff00, 0x000000ff);
  30. }
  31. if(pixelbufferp == IntPtr.Zero)
  32. throw new Exception("Couldn't create surface texture (out of memory?)");
  33. try {
  34. SDL.SetAlpha(sdlsurface, 0, 0);
  35. SDL.BlitSurface(sdlsurface, IntPtr.Zero, pixelbufferp, IntPtr.Zero);
  36. CreateFromSurface(pixelbufferp, gl.RGBA);
  37. } finally {
  38. SDL.FreeSurface(pixelbufferp);
  39. }
  40. ImageWidth = (float) surface->w;
  41. ImageHeight = (float) surface->h;
  42. }
  43. private static uint NextPowerOfTwo(uint val)
  44. {
  45. uint result = 1;
  46. while(result < val)
  47. result *= 2;
  48. return result;
  49. }
  50. public float UVRight
  51. {
  52. get
  53. {
  54. return ImageWidth / (float) Width;
  55. }
  56. }
  57. public float UVBottom
  58. {
  59. get
  60. {
  61. return ImageHeight / (float) Height;
  62. }
  63. }
  64. public void Ref()
  65. {
  66. refcount++;
  67. }
  68. public void UnRef()
  69. {
  70. refcount--;
  71. if(refcount == 0)
  72. Dispose();
  73. }
  74. }
  75. }