Texture.cpp 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // ----------------------------------------------------------------
  2. // From Game Programming in C++ by Sanjay Madhav
  3. // Copyright (C) 2017 Sanjay Madhav. All rights reserved.
  4. //
  5. // Released under the BSD License
  6. // See LICENSE in root directory for full details.
  7. // ----------------------------------------------------------------
  8. #include "Texture.h"
  9. #include <SOIL/SOIL.h>
  10. #include <GL/glew.h>
  11. #include <SDL/SDL.h>
  12. Texture::Texture()
  13. :mTextureID(0)
  14. ,mWidth(0)
  15. ,mHeight(0)
  16. {
  17. }
  18. Texture::~Texture()
  19. {
  20. }
  21. bool Texture::Load(const std::string& fileName)
  22. {
  23. int channels = 0;
  24. unsigned char* image = SOIL_load_image(fileName.c_str(),
  25. &mWidth, &mHeight, &channels, SOIL_LOAD_AUTO);
  26. if (image == nullptr)
  27. {
  28. SDL_Log("SOIL failed to load image %s: %s", fileName.c_str(), SOIL_last_result());
  29. return false;
  30. }
  31. int format = GL_RGB;
  32. if (channels == 4)
  33. {
  34. format = GL_RGBA;
  35. }
  36. glGenTextures(1, &mTextureID);
  37. glBindTexture(GL_TEXTURE_2D, mTextureID);
  38. glTexImage2D(GL_TEXTURE_2D, 0, format, mWidth, mHeight, 0, format,
  39. GL_UNSIGNED_BYTE, image);
  40. SOIL_free_image_data(image);
  41. // Enable linear filtering
  42. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  43. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  44. return true;
  45. }
  46. void Texture::Unload()
  47. {
  48. glDeleteTextures(1, &mTextureID);
  49. }
  50. void Texture::SetActive()
  51. {
  52. glBindTexture(GL_TEXTURE_2D, mTextureID);
  53. }