💿🐜 Antkeeper source code https://antkeeper.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

78 lines
2.2 KiB

  1. /*
  2. * Copyright (C) 2020 Christopher J. Howard
  3. *
  4. * This file is part of Antkeeper source code.
  5. *
  6. * Antkeeper source code is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * Antkeeper source code is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with Antkeeper source code. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. #include "resource-loader.hpp"
  20. #include "stb/stb_image.h"
  21. #include "resources/image.hpp"
  22. #include <cstring>
  23. #include <stdexcept>
  24. #include <physfs.h>
  25. template <>
  26. image* resource_loader<image>::load(resource_manager* resource_manager, PHYSFS_File* file)
  27. {
  28. unsigned char* buffer;
  29. int size;
  30. int width;
  31. int height;
  32. int channels;
  33. bool hdr;
  34. void* pixels;
  35. // Read input stream into buffer
  36. size = static_cast<int>(PHYSFS_fileLength(file));
  37. buffer = new unsigned char[size];
  38. PHYSFS_readBytes(file, buffer, size);
  39. // Determine if image is in an HDR format
  40. hdr = (stbi_is_hdr_from_memory(buffer, size) != 0);
  41. // Set vertical flip on load in order to upload pixels correctly to OpenGL
  42. stbi_set_flip_vertically_on_load(true);
  43. // Load image data
  44. if (hdr)
  45. {
  46. pixels = stbi_loadf_from_memory(buffer, size, &width, &height, &channels, 0);
  47. }
  48. else
  49. {
  50. pixels = stbi_load_from_memory(buffer, size, &width, &height, &channels, 0);
  51. }
  52. // Free file buffer
  53. delete[] buffer;
  54. // Check if image was loaded
  55. if (!pixels)
  56. {
  57. throw std::runtime_error("STBI failed to load image from memory.");
  58. }
  59. ::image* image = new ::image();
  60. image->format(static_cast<unsigned int>(channels), hdr);
  61. image->resize(static_cast<unsigned int>(width), static_cast<unsigned int>(height));
  62. std::memcpy(image->get_pixels(), pixels, width * height * channels * ((hdr) ? sizeof(float) : sizeof(unsigned char)));
  63. // Free loaded image data
  64. stbi_image_free(pixels);
  65. return image;
  66. }