🛠️🐜 Antkeeper superbuild with dependencies included 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.

79 lines
1.9 KiB

  1. #include <vector>
  2. #include <emscripten/bind.h>
  3. #define TINYEXR_IMPLEMENTATION
  4. #include "tinyexr.h"
  5. using namespace emscripten;
  6. ///
  7. /// Simple C++ wrapper class for Emscripten
  8. ///
  9. class EXRLoader {
  10. public:
  11. ///
  12. /// `binary` is the buffer for EXR binary(e.g. buffer read by fs.readFileSync)
  13. /// std::string can be used as UInt8Array in JS layer.
  14. ///
  15. EXRLoader(const std::string &binary) {
  16. const float *ptr = reinterpret_cast<const float *>(binary.data());
  17. float *rgba = nullptr;
  18. width_ = -1;
  19. height_ = -1;
  20. const char *err = nullptr;
  21. error_.clear();
  22. result_ = LoadEXRFromMemory(
  23. &rgba, &width_, &height_,
  24. reinterpret_cast<const unsigned char *>(binary.data()), binary.size(),
  25. &err);
  26. if (TINYEXR_SUCCESS == result_) {
  27. image_.resize(size_t(width_ * height_ * 4));
  28. memcpy(image_.data(), rgba, sizeof(float) * size_t(width_ * height_ * 4));
  29. free(rgba);
  30. } else {
  31. if (err) {
  32. error_ = std::string(err);
  33. }
  34. }
  35. }
  36. ~EXRLoader() {}
  37. // Return as memory views
  38. emscripten::val getBytes() const {
  39. return emscripten::val(
  40. emscripten::typed_memory_view(image_.size(), image_.data()));
  41. }
  42. bool ok() const { return (TINYEXR_SUCCESS == result_); }
  43. const std::string error() const { return error_; }
  44. int width() const { return width_; }
  45. int height() const { return height_; }
  46. private:
  47. std::vector<float> image_; // RGBA
  48. int width_;
  49. int height_;
  50. int result_;
  51. std::string error_;
  52. };
  53. // Register STL
  54. EMSCRIPTEN_BINDINGS(stl_wrappters) { register_vector<float>("VectorFloat"); }
  55. EMSCRIPTEN_BINDINGS(tinyexr_module) {
  56. class_<EXRLoader>("EXRLoader")
  57. .constructor<const std::string &>()
  58. .function("getBytes", &EXRLoader::getBytes)
  59. .function("ok", &EXRLoader::ok)
  60. .function("error", &EXRLoader::error)
  61. .function("width", &EXRLoader::width)
  62. .function("height", &EXRLoader::height);
  63. }