tileset.nim 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. # author: Ethosa
  2. import
  3. ../thirdparty/opengl,
  4. ../thirdparty/sdl2,
  5. ../thirdparty/sdl2/image,
  6. vector2,
  7. exceptions
  8. type
  9. TileSetObj* = ref object
  10. grid*, size*: Vector2Obj
  11. texture*: Gluint
  12. # --- Public --- #
  13. proc TileSet*(img: string, tile_size: Vector2Obj, mode: Glenum = GL_RGB): TileSetObj =
  14. ## Creates a new TileSet from image
  15. var
  16. surface = image.load(img) # load image from file
  17. textureid: Gluint = 0
  18. when defined(debug):
  19. if surface.isNil():
  20. raise newException(ResourceError, "image \"" & img & "\" not loaded!")
  21. glGenTextures(1, textureid.addr)
  22. glBindTexture(GL_TEXTURE_2D, textureid)
  23. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
  24. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
  25. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)
  26. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)
  27. glTexImage2D(GL_TEXTURE_2D, 0, mode.GLint, surface.w, surface.h, 0, mode, GL_UNSIGNED_BYTE, surface.pixels)
  28. glBindTexture(GL_TEXTURE_2D, 0)
  29. result = TileSetObj(
  30. grid: tile_size,
  31. size: Vector2(surface.w.float, surface.h.float),
  32. texture: textureid
  33. )
  34. surface.freeSurface()
  35. surface = nil
  36. proc draw*(self: TileSetObj, tilex, tiley, x, y, z: float) =
  37. ## Draws tile at position `tilex`,`tiley` to `x`,`y` position.
  38. if self.texture > 0:
  39. let
  40. texx1 = self.grid.x*tilex / self.size.x
  41. texy1 = self.grid.y*tiley / self.size.y
  42. texx2 = self.grid.x*(tilex+1f) / self.size.x
  43. texy2 = self.grid.y*(tiley+1f) / self.size.y
  44. glPushMatrix()
  45. glTranslatef(x, y, z)
  46. glBindTexture(GL_TEXTURE_2D, self.texture)
  47. glBegin(GL_QUADS)
  48. glTexCoord2f(texx1, texy1)
  49. glVertex3f(0, 0, 0)
  50. glTexCoord2f(texx1, texy2)
  51. glVertex3f(0, -self.grid.y, 0)
  52. glTexCoord2f(texx2, texy2)
  53. glVertex3f(self.grid.x, -self.grid.y, 0)
  54. glTexCoord2f(texx2, texy1)
  55. glVertex3f(self.grid.x, 0, 0)
  56. glEnd()
  57. glBindTexture(GL_TEXTURE_2D, 0)
  58. glPopMatrix()