image.nim 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. # author: Ethosa
  2. import
  3. ../thirdparty/opengl,
  4. ../thirdparty/sdl2,
  5. ../thirdparty/sdl2/image,
  6. vector2,
  7. exceptions
  8. type
  9. GlTextureObj* = object of RootObj
  10. texture*: Gluint
  11. size*: Vector2Obj
  12. proc load*(file: string, x, y: var float, mode: Glenum = GL_RGB): Gluint =
  13. ## Loads image from file and returns texture ID.
  14. ##
  15. ## Arguments:
  16. ## - `file` - image path.
  17. var
  18. surface = image.load(file) # load image from file
  19. textureid: Gluint
  20. when defined(debug):
  21. if surface.isNil():
  22. raise newException(ResourceError, "image \"" & file & "\" not loaded!")
  23. x = surface.w.float
  24. y = surface.h.float
  25. # OpenGL:
  26. glGenTextures(1, textureid.addr)
  27. glBindTexture(GL_TEXTURE_2D, textureid)
  28. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
  29. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
  30. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)
  31. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)
  32. glTexImage2D(GL_TEXTURE_2D, 0, mode.GLint, surface.w, surface.h, 0, mode, GL_UNSIGNED_BYTE, surface.pixels)
  33. glBindTexture(GL_TEXTURE_2D, 0)
  34. # free memory
  35. surface.freeSurface()
  36. surface = nil
  37. textureid
  38. proc load*(file: string, mode: Glenum = GL_RGB): GlTextureObj =
  39. ## Loads GL texture.
  40. ##
  41. ## Arguments:
  42. ## - `file` - image path.
  43. var
  44. x: float = 0f
  45. y: float = 0f
  46. textureid: Gluint
  47. textureid = load(file, x, y, mode)
  48. GlTextureObj(texture: textureid, size: Vector2(x, y))