Free, open-source 3D sculpting for Linux, macOS and Windows: dense meshes, remeshing, painting, built-in AI (image/text to 3D), Send to Unreal, game-ready LODs, Gaussian splats and OpenUSD.
C++ 3d3d-sculptingcppdear-imguidigital-sculptingfbxgame-developmentgaussian-splattinggltfimage-to-3dmcpopenglopenusdsculptingtext-to-3dunreal-engine
VDM brush core: vector displacement maps (EXR via vendored tinyexr, .sfvdm), built-in Horn / Ear Curl / Scales / Nostril, VDM plane capture, vdm_* commands, tests
islandmedaef976a0844d
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 3b2e654a..0957d738 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -75,6 +75,8 @@ add_library(sculptforge_core STATICsrc/core/BakeImage.cppsrc/core/Tangents.cppthird_party/mikktspace/mikktspace.c+ src/core/Vdm.cpp+ third_party/tinyexr/tinyexr_impl.cppsrc/core/Matcap.cppsrc/core/Project.cppsrc/core/Guide.cpp@@ -93,12 +95,12 @@ add_library(sculptforge_core STATICsrc/io/BlenderCommands.cppsrc/io/StlIO.cpp)-target_include_directories(sculptforge_core PUBLIC src PRIVATE third_party/stb third_party/ufbx third_party/xatlas third_party/mikktspace)+target_include_directories(sculptforge_core PUBLIC src PRIVATE third_party/stb third_party/ufbx third_party/xatlas third_party/mikktspace third_party/tinyexr)# Third-party C code: compile quietly.if(MSVC)- set_source_files_properties(third_party/ufbx/ufbx.c third_party/xatlas/xatlas.cpp third_party/mikktspace/mikktspace.c PROPERTIES COMPILE_OPTIONS "/w")+ set_source_files_properties(third_party/ufbx/ufbx.c third_party/xatlas/xatlas.cpp third_party/mikktspace/mikktspace.c third_party/tinyexr/tinyexr_impl.cpp PROPERTIES COMPILE_OPTIONS "/w")else()- set_source_files_properties(third_party/ufbx/ufbx.c third_party/xatlas/xatlas.cpp third_party/mikktspace/mikktspace.c PROPERTIES COMPILE_OPTIONS "-w")+ set_source_files_properties(third_party/ufbx/ufbx.c third_party/xatlas/xatlas.cpp third_party/mikktspace/mikktspace.c third_party/tinyexr/tinyexr_impl.cpp PROPERTIES COMPILE_OPTIONS "-w")endif()find_package(Threads REQUIRED)target_link_libraries(sculptforge_core PUBLIC glm::glm Threads::Threads)diff --git a/src/core/BrushLibrary.cpp b/src/core/BrushLibrary.cppindex 8be26142..0f5889f1 100644--- a/src/core/BrushLibrary.cpp+++ b/src/core/BrushLibrary.cpp@@ -4,6 +4,7 @@#include "core/Commands.h"#include "core/Document.h"+#include "core/Vdm.h"#include <algorithm>#include <cctype>@@ -408,6 +409,7 @@ std::vector<std::string> loadBrushLibrary(Document& doc, const BrushLibraryPaths}}doc.activeBrush = active.empty() ? -1 : findBrush(doc, active);+ loadVdmLibrary(doc, paths, messages); // the VDM brush's maps (.sfvdm) live in the same folders (Vdm.cpp)return messages;}diff --git a/src/core/Commands.cpp b/src/core/Commands.cppindex 473263de..c7ceea69 100644--- a/src/core/Commands.cpp+++ b/src/core/Commands.cpp@@ -561,6 +561,7 @@ CommandRegistry::CommandRegistry() {}});registerBrushLibraryCommands(*this); // brush_install, brush_code, brush_delete, ... (BrushLibrary.cpp)registerBrushCommands(*this); // brush_set_alpha (BrushAlpha.cpp)+ registerVdmCommands(*this); // vdm_set, vdm_capture, vdm_stamp, ... (Vdm.cpp)registerRetopoCommands(*this); // qremesh, project_all (RetopoCommands.cpp)add({"stroke",diff --git a/src/core/Document.h b/src/core/Document.hindex cb98db3d..24dfd004 100644--- a/src/core/Document.h+++ b/src/core/Document.h@@ -10,6 +10,7 @@#include "core/Sculpt.h"#include "core/Splats.h"#include "core/Undo.h"+#include "core/Vdm.h"#include <string>#include <utility>@@ -53,6 +54,10 @@ struct Document {int activeBrush = -1; // index into `brushes`, -1 = use a built-in brush typeBrushAlpha brushAlpha; // stamp shaping every brush's falloff (empty = round); brush_set_alphaglm::vec3 paintColor{0.6f, 0.03f, 0.02f}; // current polypaint colour (linear RGB; see set_color)+ // Vector displacement maps for the VDM brush (core/Vdm.h): the built-ins, then the studio and user+ // library's .sfvdm files and any loaded this session. `brushVdm` is the one the VDM brush stamps.+ std::vector<std::shared_ptr<const VectorDisplacement>> vdms = builtinVdms();+ std::shared_ptr<const VectorDisplacement> brushVdm = builtinVdms().front();// Adds or replaces (by name) a recipe and returns its index. Replacing with a// BrushSource::Session recipe keeps the existing brush's origin.int addBrush(BrushRecipe recipe);diff --git a/src/core/PathStroke.cpp b/src/core/PathStroke.cppindex b29ae074..de03b760 100644--- a/src/core/PathStroke.cpp+++ b/src/core/PathStroke.cpp@@ -139,6 +139,7 @@ int strokePath(Document& doc, const BrushRecipe* recipe, BrushType type, const Pbase.frontFacesOnly = recipe && recipe->frontFacesOnly;base.alpha = &doc.brushAlpha;base.alphaUp = up;+ base.vdm = doc.brushVdm.get();int dabs = 0;if (type == BrushType::Move && !recipe) {diff --git a/src/core/Sculpt.cpp b/src/core/Sculpt.cppindex 6e41f95a..d4aacd3b 100644--- a/src/core/Sculpt.cpp+++ b/src/core/Sculpt.cpp@@ -27,6 +27,7 @@ const char* brushName(BrushType type) {case BrushType::Trim: return "Trim";case BrushType::Layer: return "Layer";case BrushType::Nudge: return "Nudge";+ case BrushType::Vdm: return "VDM";default: return "?";}}@@ -303,7 +304,8 @@ void Sculptor::dab(Mesh& mesh, BVH& bvh, BrushType type, const DabParams& p, Symmp.viewDir *= m;mp.strokeDelta *= m;mp.alphaUp *= m;- dabSingle(mesh, bvh, type, mp);+ if (type == BrushType::Vdm) dabVdmSingle(mesh, bvh, mp, m.x * m.y * m.z);+ else dabSingle(mesh, bvh, type, mp);}updateDabNormals(mesh);}diff --git a/src/core/Sculpt.h b/src/core/Sculpt.hindex 7e280740..a2d72339 100644--- a/src/core/Sculpt.h+++ b/src/core/Sculpt.h@@ -14,6 +14,7 @@namespace sf {struct BrushAlpha;+struct VectorDisplacement;enum class BrushType {Standard, Clay, Smooth, Move, Inflate, Crease, Flatten, Pinch,@@ -23,6 +24,7 @@ enum class BrushType {Trim, // Trim Dynamic: a plane cuts away everything above itLayer, // raises to one fixed height per stroke (overlaps never stack)Nudge, // slides the surface sideways along the stroke+ Vdm, // vector displacement: stamps DabParams::vdm (a horn, an ear...) with overhangs (core/Vdm.h)Count};@@ -40,6 +42,7 @@ struct DabParams {const BrushAlpha* alpha = nullptr; // stamp shaping the falloff (null/empty = round)glm::vec3 alphaUp{0.0f, 1.0f, 0.0f}; // world direction of the alpha's top edge (screen up, or rotated)float focal = 0.0f; // ZBrush Focal Shift, -1..1 (see brushFalloff); recipes keep their own tip+ const VectorDisplacement* vdm = nullptr; // the Vdm brush's map (null = the built-in Horn); top edge = alphaUp};struct Symmetry {@@ -115,6 +118,8 @@ public:private:void dabSingle(Mesh& mesh, BVH& bvh, BrushType type, const DabParams& p);void dabRecipeSingle(Mesh& mesh, BVH& bvh, const BrushRecipe& r, const DabParams& p);+ // The Vdm brush (defined in Vdm.cpp); `handedness` -1 for a mirrored pass, so the stamp mirrors exactly.+ void dabVdmSingle(Mesh& mesh, BVH& bvh, const DabParams& p, float handedness);void finishDab(Mesh& mesh, BVH& bvh, std::chrono::steady_clock::time_point clock);void updateDabNormals(Mesh& mesh);void touch(Mesh& mesh, uint32_t v);diff --git a/src/core/Vdm.cpp b/src/core/Vdm.cppnew file mode 100644index 00000000..3032edd2--- /dev/null+++ b/src/core/Vdm.cpp@@ -0,0 +1,842 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+#include "core/Vdm.h"++#include "core/BrushLibrary.h"+#include "core/Commands.h"+#include "core/Document.h"+#include "core/PathStroke.h"+#include "core/Primitives.h"+#include "core/Sculpt.h"+#include "core/ThreadPool.h"++#include "tinyexr.h"++#include <algorithm>+#include <cctype>+#include <cmath>+#include <cstring>+#include <filesystem>+#include <fstream>+#include <iterator>+#include <sstream>++namespace sf {++namespace fs = std::filesystem;++namespace {++constexpr int kMaxVdmSide = 2048;+constexpr char kSfvdmMagic[8] = {'S', 'F', 'V', 'D', 'M', '1', '\n', '\0'};++fs::path utf8Path(const std::string& s) { return fs::path(std::u8string(s.begin(), s.end())); }+std::string pathString(const fs::path& p) {+ const std::u8string s = p.u8string();+ return std::string(s.begin(), s.end());+}+std::string lower(std::string s) {+ std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return char(std::tolower(c)); });+ return s;+}+std::string extensionOf(const std::string& path) { return lower(pathString(utf8Path(path).extension())); }+std::string stemOf(const std::string& path) { return pathString(utf8Path(path).stem()); }++bool readBytes(const std::string& path, std::vector<unsigned char>& out, size_t limit, std::string& error) {+ std::ifstream f(utf8Path(path), std::ios::binary);+ if (!f) {+ error = "Can't open " + path;+ return false;+ }+ f.seekg(0, std::ios::end);+ const std::streamoff size = f.tellg();+ if (size < 0 || size_t(size) > limit) {+ error = path + " is too large";+ return false;+ }+ f.seekg(0);+ out.resize(size_t(size));+ if (size > 0 && !f.read(reinterpret_cast<char*>(out.data()), size)) {+ error = "Can't read " + path;+ return false;+ }+ return true;+}++bool writeBytes(const std::string& path, const void* data, size_t size, std::string& error) {+ std::error_code ec;+ const fs::path p = utf8Path(path);+ if (p.has_parent_path()) fs::create_directories(p.parent_path(), ec);+ std::ofstream f(p, std::ios::binary | std::ios::trunc);+ if (!f || !f.write(static_cast<const char*>(data), std::streamsize(size))) {+ error = "Can't write " + path;+ return false;+ }+ return true;+}++float smooth01(float t) {+ t = std::clamp(t, 0.0f, 1.0f);+ return t * t * (3.0f - 2.0f * t);+}++void applyImport(VectorDisplacement& vdm, const VdmImportOptions& opt) {+ for (glm::vec3& v : vdm.vectors) {+ if (opt.swapYZ) std::swap(v.y, v.z);+ if (opt.flipX) v.x = -v.x;+ if (opt.flipY) v.y = -v.y;+ if (opt.flipZ) v.z = -v.z;+ v *= opt.scale;+ }+}++// --- Procedural maps: f(x, y) is where the point (x, y, 0) of the flat square goes (x, y in -1..1). ---++template <class F>+VectorDisplacement generate(std::string name, int size, F&& f) {+ VectorDisplacement m;+ m.name = std::move(name);+ m.builtin = true;+ m.width = m.height = std::max(size, 8);+ m.vectors.resize(size_t(m.width) * size_t(m.height));+ poolFor(size_t(m.height), [&](size_t b, size_t e) {+ for (size_t row = b; row < e; ++row)+ for (int col = 0; col < m.width; ++col) {+ const float x = (float(col) + 0.5f) / float(m.width) * 2.0f - 1.0f;+ const float y = 1.0f - (float(row) + 0.5f) / float(m.height) * 2.0f;+ m.vectors[row * size_t(m.width) + size_t(col)] = f(x, y) - glm::vec3(x, y, 0.0f);+ }+ }, 16);+ return m;+}++// A tube grown out of the disc of radius `base`: the disc's rim stays put, its centre becomes the tip. The+// centre line bends toward +Y (`bend` radians over `length`; < 0 length digs in instead of rising); the cross+// section flattens to `flat` (along the bend) and tapers with `power`.+struct Tube {+ float base = 0.62f, length = 1.0f, bend = 1.1f, flat = 1.0f, power = 1.3f, rise = 1.6f;+};++glm::vec3 tubePoint(const Tube& h, float x, float y) {+ const float rho = std::sqrt(x * x + y * y);+ if (rho >= h.base) return {x, y, 0.0f};+ const float theta = std::atan2(y, x);+ const float s = 1.0f - rho / h.base; // 0 at the rim, 1 at the tip+ const float len = std::abs(h.length);+ const float t = len * std::pow(s, h.rise); // arc length: slow at first, a soft fillet into the surface+ const float depth = h.length < 0.0f ? -1.0f : 1.0f;+ const float kappa = h.bend / len;+ const float phi = kappa * t;+ glm::vec3 c(0.0f, 0.0f, t * depth);+ if (std::abs(kappa) > 1e-5f) c = glm::vec3(0.0f, (1.0f - std::cos(phi)) / kappa, depth * std::sin(phi) / kappa);+ const glm::vec3 e1(1.0f, 0.0f, 0.0f), e2(0.0f, std::cos(phi), -depth * std::sin(phi));+ const float radius = h.base * std::pow(1.0f - s, h.power);+ const float flat = 1.0f + (h.flat - 1.0f) * smooth01(s / 0.3f);+ return c + radius * (std::cos(theta) * e1 + flat * std::sin(theta) * e2);+}++} // namespace++// ---------------------------------------------------------------------------+// VectorDisplacement+// ---------------------------------------------------------------------------++glm::vec3 VectorDisplacement::sample(float u, float v) const {+ if (empty() || u < -1.0f || u > 1.0f || v < -1.0f || v > 1.0f) return glm::vec3(0.0f);+ // Pixel centres span the square, as BrushAlpha::sample.+ const float px = std::clamp((u * 0.5f + 0.5f) * float(width) - 0.5f, 0.0f, float(width - 1));+ const float py = std::clamp((0.5f - v * 0.5f) * float(height) - 0.5f, 0.0f, float(height - 1));+ const int x0 = int(px), y0 = int(py);+ const int x1 = std::min(x0 + 1, width - 1), y1 = std::min(y0 + 1, height - 1);+ const float tx = px - float(x0), ty = py - float(y0);+ auto at = [&](int x, int y) { return vectors[size_t(y) * size_t(width) + size_t(x)]; };+ const glm::vec3 a = glm::mix(at(x0, y0), at(x1, y0), tx);+ const glm::vec3 b = glm::mix(at(x0, y1), at(x1, y1), tx);+ return glm::mix(a, b, ty);+}++float VectorDisplacement::extent() const {+ float m = 0.0f;+ for (const glm::vec3& v : vectors) m = std::max(m, glm::length(v));+ return m;+}++uint64_t VectorDisplacement::hash() const {+ uint64_t h = 0xcbf29ce484222325ull;+ auto mix = [&h](const void* data, size_t n) {+ const auto* p = static_cast<const unsigned char*>(data);+ for (size_t i = 0; i < n; ++i) h = (h ^ p[i]) * 0x100000001b3ull;+ };+ mix(&width, sizeof width);+ mix(&height, sizeof height);+ mix(vectors.data(), vectors.size() * sizeof(glm::vec3));+ return h;+}++// ---------------------------------------------------------------------------+// Files+// ---------------------------------------------------------------------------++bool decodeVdmExr(const unsigned char* bytes, size_t size, VectorDisplacement& out, std::string& error,+ const VdmImportOptions& opt) {+ if (!bytes || size == 0 || IsEXRFromMemory(bytes, size) != TINYEXR_SUCCESS) {+ error = "Not an OpenEXR file";+ return false;+ }+ float* rgba = nullptr;+ int w = 0, h = 0;+ const char* err = nullptr;+ // tinyexr reads the R, G, B (and A) channels, or a single channel into all four.+ if (LoadEXRFromMemory(&rgba, &w, &h, bytes, size, &err) != TINYEXR_SUCCESS) {+ error = std::string("Can't read the EXR: ") + (err ? err : "unknown error");+ if (err) FreeEXRErrorMessage(err);+ return false;+ }+ if (w <= 0 || h <= 0 || w > kMaxVdmSide || h > kMaxVdmSide) {+ std::free(rgba);+ error = "The EXR must be 1 to " + std::to_string(kMaxVdmSide) + " pixels a side";+ return false;+ }+ // Grayscale (one channel, so R = G = B = A): a height map along the normal.+ EXRVersion version;+ EXRHeader header;+ InitEXRHeader(&header);+ bool gray = false;+ if (ParseEXRVersionFromMemory(&version, bytes, size) == TINYEXR_SUCCESS &&+ ParseEXRHeaderFromMemory(&header, &version, bytes, size, nullptr) == TINYEXR_SUCCESS) {+ gray = header.num_channels == 1;+ FreeEXRHeader(&header);+ }+ out.width = w;+ out.height = h;+ out.vectors.resize(size_t(w) * size_t(h));+ for (size_t i = 0; i < out.vectors.size(); ++i) {+ const float* p = rgba + i * 4;+ glm::vec3 v = gray ? glm::vec3(0.0f, 0.0f, p[0]) : glm::vec3(p[0], p[1], p[2]);+ for (int k = 0; k < 3; ++k)+ if (!std::isfinite(v[k])) v[k] = 0.0f;+ out.vectors[i] = v;+ }+ std::free(rgba);+ applyImport(out, opt);+ return true;+}++bool readVdmExr(const std::string& path, VectorDisplacement& out, std::string& error, const VdmImportOptions& opt) {+ std::vector<unsigned char> bytes;+ if (!readBytes(path, bytes, size_t(1) << 30, error)) return false;+ if (!decodeVdmExr(bytes.data(), bytes.size(), out, error, opt)) {+ error = path + ": " + error;+ return false;+ }+ out.name = stemOf(path);+ out.path = path;+ out.builtin = false;+ return true;+}++bool encodeVdmExr(const VectorDisplacement& vdm, std::vector<unsigned char>& out, std::string& error) {+ if (vdm.empty()) {+ error = "The VDM is empty";+ return false;+ }+ std::vector<float> rgb(vdm.vectors.size() * 3);+ for (size_t i = 0; i < vdm.vectors.size(); ++i) {+ rgb[i * 3] = vdm.vectors[i].x;+ rgb[i * 3 + 1] = vdm.vectors[i].y;+ rgb[i * 3 + 2] = vdm.vectors[i].z;+ }+ unsigned char* buffer = nullptr;+ const char* err = nullptr;+ const int n = SaveEXRToMemory(rgb.data(), vdm.width, vdm.height, 3, 0, &buffer, &err);+ if (n <= 0 || !buffer) {+ error = std::string("Can't encode the EXR: ") + (err ? err : "unknown error");+ if (err) FreeEXRErrorMessage(err);+ std::free(buffer);+ return false;+ }+ out.assign(buffer, buffer + n);+ std::free(buffer);+ return true;+}++bool writeVdmExr(const std::string& path, const VectorDisplacement& vdm, std::string& error) {+ std::vector<unsigned char> bytes;+ return encodeVdmExr(vdm, bytes, error) && writeBytes(path, bytes.data(), bytes.size(), error);+}++bool readVdmFile(const std::string& path, VectorDisplacement& out, std::string& error) {+ std::vector<unsigned char> b;+ if (!readBytes(path, b, size_t(kMaxVdmSide) * kMaxVdmSide * 12 + 4096, error)) return false;+ auto u32 = [&](size_t at) {+ return uint32_t(b[at]) | uint32_t(b[at + 1]) << 8 | uint32_t(b[at + 2]) << 16 | uint32_t(b[at + 3]) << 24;+ };+ if (b.size() < 20 || std::memcmp(b.data(), kSfvdmMagic, 8) != 0) {+ error = path + " is not a SculptForge VDM (.sfvdm)";+ return false;+ }+ const uint32_t w = u32(8), h = u32(12), nameLen = u32(16);+ if (w == 0 || h == 0 || w > uint32_t(kMaxVdmSide) || h > uint32_t(kMaxVdmSide) || nameLen > 1024 ||+ b.size() != 20 + size_t(nameLen) + size_t(w) * h * 12) {+ error = path + " is damaged (bad size)";+ return false;+ }+ out.name.assign(reinterpret_cast<const char*>(b.data() + 20), nameLen);+ if (out.name.empty()) out.name = stemOf(path);+ out.width = int(w);+ out.height = int(h);+ out.vectors.resize(size_t(w) * h);+ const unsigned char* p = b.data() + 20 + nameLen;+ for (size_t i = 0; i < out.vectors.size(); ++i)+ for (int k = 0; k < 3; ++k) {+ const uint32_t bits = uint32_t(p[0]) | uint32_t(p[1]) << 8 | uint32_t(p[2]) << 16 | uint32_t(p[3]) << 24;+ p += 4;+ float f;+ std::memcpy(&f, &bits, 4);+ out.vectors[i][k] = std::isfinite(f) ? f : 0.0f;+ }+ out.path = path;+ out.builtin = false;+ return true;+}++bool writeVdmFile(const std::string& path, const VectorDisplacement& vdm, std::string& error) {+ if (vdm.empty()) {+ error = "The VDM is empty";+ return false;+ }+ std::vector<unsigned char> b(kSfvdmMagic, kSfvdmMagic + 8);+ auto put = [&b](uint32_t v) {+ for (int k = 0; k < 4; ++k) b.push_back(uint8_t(v >> (8 * k)));+ };+ const std::string name = vdm.name.substr(0, 1024);+ put(uint32_t(vdm.width));+ put(uint32_t(vdm.height));+ put(uint32_t(name.size()));+ b.insert(b.end(), name.begin(), name.end());+ b.reserve(b.size() + vdm.vectors.size() * 12);+ for (const glm::vec3& v : vdm.vectors)+ for (int k = 0; k < 3; ++k) {+ uint32_t bits;+ std::memcpy(&bits, &v[k], 4);+ put(bits);+ }+ return writeBytes(path, b.data(), b.size(), error);+}++bool isVdmFile(const std::string& path) {+ const std::string ext = extensionOf(path);+ return ext == ".sfvdm" || ext == ".exr";+}++bool loadVdm(const std::string& path, VectorDisplacement& out, std::string& error, const VdmImportOptions& opt) {+ if (extensionOf(path) == ".sfvdm") {+ if (!readVdmFile(path, out, error)) return false;+ applyImport(out, opt);+ return true;+ }+ return readVdmExr(path, out, error, opt);+}++// ---------------------------------------------------------------------------+// Built-ins+// ---------------------------------------------------------------------------++VectorDisplacement makeHornVdm(int size) {+ Tube h; // a horn that curls over toward the stamp's top+ h.base = 0.62f;+ h.length = 1.05f;+ h.bend = 1.15f;+ h.power = 1.25f;+ return generate("Horn", size, [&](float x, float y) { return tubePoint(h, x, y); });+}++VectorDisplacement makeEarCurlVdm(int size) {+ Tube h; // a flattened, blunt flap that curls right over: an ear rim, a fin, a leaf+ h.base = 0.58f;+ h.length = 1.2f;+ h.bend = 2.6f;+ h.flat = 0.42f;+ h.power = 0.75f;+ h.rise = 1.4f;+ return generate("Ear Curl", size, [&](float x, float y) {+ // The flap leans back toward the stamp's bottom first, so the curl sits over the middle.+ glm::vec3 p = tubePoint(h, x, y + 0.12f);+ p.y -= 0.12f;+ return p;+ });+}++VectorDisplacement makeScalesVdm(int size) {+ // Overlapping scales in staggered rows; each lip is pushed toward the stamp's bottom over the next row.+ struct Scale {+ glm::vec2 c;+ float r;+ };+ std::vector<Scale> scales;+ const float r = 0.25f;+ for (int row = 0; row < 3; ++row) {+ const float y = 0.42f - 0.38f * float(row);+ const int n = row == 1 ? 4 : 3;+ for (int i = 0; i < n; ++i) {+ const float x = (float(i) - float(n - 1) * 0.5f) * 0.38f;+ scales.push_back({glm::vec2(x, y), r});+ }+ }+ return generate("Scales", size, [&](float x, float y) {+ glm::vec3 best(x, y, 0.0f);+ float bestZ = 0.0f;+ for (const Scale& s : scales) {+ const glm::vec2 q = (glm::vec2(x, y) - s.c) / s.r;+ const float d = glm::length(q * glm::vec2(1.0f, 0.85f));+ if (d >= 1.0f) continue;+ const float plateau = smooth01((1.0f - d) / 0.28f);+ const float front = 0.55f + 0.45f * std::clamp((1.0f - q.y) * 0.5f, 0.0f, 1.0f); // higher at the lip+ const float z = 0.13f * plateau * front * (1.0f - 0.3f * d * d);+ if (z <= bestZ) continue;+ bestZ = z;+ best = glm::vec3(x, y - 0.075f * plateau, z); // the lip slides past its edge: an overhang+ }+ return best;+ });+}++VectorDisplacement makeNostrilVdm(int size) {+ Tube h; // a socket that dives in and bends under its top rim+ h.base = 0.6f;+ h.length = -0.75f;+ h.bend = 1.0f;+ h.power = 0.9f;+ h.rise = 1.35f;+ return generate("Nostril", size, [&](float x, float y) {+ glm::vec3 p = tubePoint(h, x, y);+ const float rho = std::sqrt(x * x + y * y);+ if (rho >= h.base) return p;+ // A raised rim that leans in over the opening.+ const float s = 1.0f - rho / h.base;+ const float bump = std::sin(3.14159265f * std::clamp(s / 0.42f, 0.0f, 1.0f));+ const glm::vec2 radial = rho > 1e-6f ? glm::vec2(x, y) / rho : glm::vec2(0.0f);+ p += glm::vec3(-radial * (0.09f * bump), 0.12f * bump);+ return p;+ });+}++const std::vector<std::shared_ptr<const VectorDisplacement>>& builtinVdms() {+ static const std::vector<std::shared_ptr<const VectorDisplacement>> all = [] {+ std::vector<std::shared_ptr<const VectorDisplacement>> v;+ v.push_back(std::make_shared<const VectorDisplacement>(makeHornVdm()));+ v.push_back(std::make_shared<const VectorDisplacement>(makeEarCurlVdm()));+ v.push_back(std::make_shared<const VectorDisplacement>(makeScalesVdm()));+ v.push_back(std::make_shared<const VectorDisplacement>(makeNostrilVdm()));+ return v;+ }();+ return all;+}++std::shared_ptr<const VectorDisplacement> builtinVdm(const std::string& name) {+ for (const auto& v : builtinVdms())+ if (lower(v->name) == lower(name)) return v;+ return nullptr;+}++// ---------------------------------------------------------------------------+// Create VDM from a plane+// ---------------------------------------------------------------------------++Mesh makeVdmPlane(int cells) {+ Mesh m = makePlane(std::clamp(cells, 2, 2000), 2.0f);+ // UVs from the flat start: u along +X, v up the top view (toward -Z).+ m.uvs.resize(m.triangles.size() * 3);+ for (size_t t = 0; t < m.triangles.size(); ++t)+ for (int k = 0; k < 3; ++k) {+ const glm::vec3 p = m.positions[m.triangles[t][k]];+ m.uvs[t * 3 + size_t(k)] = glm::vec2((p.x + 1.0f) * 0.5f, (1.0f - p.z) * 0.5f);+ }+ // The border stays where it is, so the stamp blends into any surface.+ auto& mask = m.ensureMask(0.0f);+ for (uint32_t v = 0; v < m.vertexCount(); ++v) {+ const glm::vec3 p = m.positions[v];+ if (std::max(std::abs(p.x), std::abs(p.z)) > 1.0f - 1e-4f) mask[v] = 1.0f;+ }+ return m;+}++bool captureVdm(const Mesh& mesh, int size, VectorDisplacement& out, std::string& error) {+ if (!mesh.hasUvs() || mesh.uvs.size() != mesh.triangles.size() * 3) {+ error = "The mesh has no UVs to say where each point started: start from Brush > Vector Displacement > New VDM plane";+ return false;+ }+ size = std::clamp(size, 16, kMaxVdmSide);+ out = VectorDisplacement{};+ out.width = out.height = size;+ out.vectors.assign(size_t(size) * size_t(size), glm::vec3(0.0f));+ const float fs = float(size);+ // Rows in parallel: each band rasterizes the triangles that reach it, so no texel is written twice at once.+ const size_t bands = size_t(std::min(size, 64));+ std::vector<std::vector<uint32_t>> inBand(bands);+ for (uint32_t t = 0; t < mesh.triangleCount(); ++t) {+ float lo = 1e9f, hi = -1e9f;+ for (int k = 0; k < 3; ++k) {+ const float py = (1.0f - mesh.uvs[size_t(t) * 3 + size_t(k)].y) * fs - 0.5f;+ lo = std::min(lo, py);+ hi = std::max(hi, py);+ }+ const int r0 = std::max(0, int(std::ceil(lo))), r1 = std::min(size - 1, int(std::floor(hi)));+ if (r0 > r1) continue;+ const size_t b0 = size_t(r0) * bands / size_t(size), b1 = size_t(r1) * bands / size_t(size);+ for (size_t b = b0; b <= b1; ++b) inBand[b].push_back(t);+ }+ poolFor(bands, [&](size_t bb, size_t be) {+ for (size_t band = bb; band < be; ++band) {+ const int rowLo = int(band * size_t(size) / bands), rowHi = int((band + 1) * size_t(size) / bands) - 1;+ for (uint32_t t : inBand[band]) {+ glm::vec2 q[3];+ glm::vec3 d[3];+ for (int k = 0; k < 3; ++k) {+ const glm::vec2 uv = mesh.uvs[size_t(t) * 3 + size_t(k)];+ q[k] = glm::vec2(uv.x * fs - 0.5f, (1.0f - uv.y) * fs - 0.5f);+ const glm::vec3 p = mesh.positions[mesh.triangles[t][k]];+ // Tangent axes of the plane (see makeVdmPlane) minus where the point started.+ d[k] = glm::vec3(p.x, -p.z, p.y) - glm::vec3(uv.x * 2.0f - 1.0f, uv.y * 2.0f - 1.0f, 0.0f);+ }+ const float area = (q[1].x - q[0].x) * (q[2].y - q[0].y) - (q[2].x - q[0].x) * (q[1].y - q[0].y);+ if (std::abs(area) < 1e-12f) continue;+ const int x0 = std::max(0, int(std::ceil(std::min({q[0].x, q[1].x, q[2].x}) - 1e-4f)));+ const int x1 = std::min(size - 1, int(std::floor(std::max({q[0].x, q[1].x, q[2].x}) + 1e-4f)));+ const int y0 = std::max(rowLo, int(std::ceil(std::min({q[0].y, q[1].y, q[2].y}) - 1e-4f)));+ const int y1 = std::min(rowHi, int(std::floor(std::max({q[0].y, q[1].y, q[2].y}) + 1e-4f)));+ for (int y = y0; y <= y1; ++y)+ for (int x = x0; x <= x1; ++x) {+ const glm::vec2 c{float(x), float(y)};+ auto edge = [&](int a, int b) {+ return ((q[b].x - q[a].x) * (c.y - q[a].y) - (c.x - q[a].x) * (q[b].y - q[a].y)) / area;+ };+ const float w0 = edge(1, 2), w1 = edge(2, 0), w2 = edge(0, 1);+ if (w0 < -1e-4f || w1 < -1e-4f || w2 < -1e-4f) continue;+ out.vectors[size_t(y) * size_t(size) + size_t(x)] = d[0] * w0 + d[1] * w1 + d[2] * w2;+ }+ }+ }+ }, 1, 1);+ return true;+}++// ---------------------------------------------------------------------------+// The brush (Sculptor::dabVdmSingle)+// ---------------------------------------------------------------------------++void Sculptor::dabVdmSingle(Mesh& mesh, BVH& bvh, const DabParams& p, float handedness) {+ auto clock = std::chrono::steady_clock::now();+ const VectorDisplacement* vdm = p.vdm && !p.vdm->empty() ? p.vdm : builtinVdms().front().get();+ // The stamp is the brush's square, so the corners reach out to radius x sqrt(2).+ brushVertices(mesh, bvh, p.center, p.radius * 1.4143f, verts_);+ if (verts_.empty()) return;+ const auto& pos = mesh.positions;+ const auto& nrm = mesh.normals;+ if (p.frontFacesOnly) {+ std::erase_if(verts_, [&](uint32_t v) { return glm::dot(nrm[v], p.viewDir) > 0.0f; });+ if (verts_.empty()) return;+ }+ // Area normal under the brush (inside its radius, smoothstep weighted): per-block partials summed in+ // block order, so it doesn't depend on the thread count.+ constexpr size_t kBlock = 4096;+ std::vector<glm::vec3> parts((verts_.size() + kBlock - 1) / kBlock, glm::vec3(0.0f));+ poolFor(verts_.size(), [&](size_t b, size_t e) {+ glm::vec3 acc(0.0f);+ for (size_t i = b; i < e; ++i)+ acc += nrm[verts_[i]] * brushFalloff(glm::distance(pos[verts_[i]], p.center), p.radius);+ parts[b / kBlock] = acc;+ }, kBlock);+ glm::vec3 n(0.0f);+ for (const glm::vec3& part : parts) n += part;+ n = glm::length(n) > 1e-12f ? glm::normalize(n) : -p.viewDir;++ // Tangent frame: Z = the surface, Y = the stamp's top (screen up or the drag), X = right. A mirrored pass+ // flips X too, so the mirrored stamp is the exact mirror image (a mirror swaps the handedness of a cross).+ glm::vec3 up = p.alphaUp - n * glm::dot(p.alphaUp, n);+ if (glm::length(up) < 1e-6f) {+ const glm::vec3 helper = std::abs(n.x) < 0.9f ? glm::vec3(1, 0, 0) : glm::vec3(0, 1, 0);+ up = helper - n * glm::dot(helper, n);+ }+ up = glm::normalize(up);+ const glm::vec3 right = glm::cross(up, n) * handedness;++ const float r = p.radius;+ // Z Intensity 50 (the default) presses the map at its own size; 100 doubles it. Alt digs the shape in+ // (Blender's convention: X and Y stay, Z flips).+ const float amount = 2.0f * std::clamp(p.strength, 0.0f, 1.0f) * std::clamp(p.pressure, 0.0f, 1.0f) * r;+ const float zSign = p.invert ? -1.0f : 1.0f;+ scratch_.resize(verts_.size());+ poolFor(verts_.size(), [&](size_t b, size_t e) {+ for (size_t i = b; i < e; ++i) {+ const glm::vec3 o = pos[verts_[i]] - p.center;+ const float u = glm::dot(o, right) / r, v = glm::dot(o, up) / r;+ const float edge = 1.0f - std::max(std::abs(u), std::abs(v));+ if (edge <= 0.0f) {+ scratch_[i] = glm::vec3(0.0f);+ continue;+ }+ const glm::vec3 d = vdm->sample(u, v) * (amount * smooth01(edge / 0.03f)); // maps whose border isn't 0 fade out+ scratch_[i] = right * d.x + up * d.y + n * (d.z * zSign);+ }+ }, kBlock);+ displaceAll(mesh, verts_, scratch_);+ finishDab(mesh, bvh, clock);+}++// ---------------------------------------------------------------------------+// Library+// ---------------------------------------------------------------------------++std::string vdmFileName(const std::string& name) {+ std::string f = brushFileName(name);+ return f.substr(0, f.size() - std::strlen(".sfbrush")) + ".sfvdm";+}++int findVdm(const Document& doc, const std::string& name) {+ for (size_t i = 0; i < doc.vdms.size(); ++i)+ if (lower(doc.vdms[i]->name) == lower(name)) return int(i);+ return -1;+}++std::shared_ptr<const VectorDisplacement> addVdm(Document& doc, VectorDisplacement vdm) {+ auto shared = std::make_shared<const VectorDisplacement>(std::move(vdm));+ const int i = findVdm(doc, shared->name);+ if (i >= 0) doc.vdms[size_t(i)] = shared;+ else doc.vdms.push_back(shared);+ doc.brushVdm = shared;+ return shared;+}++void loadVdmLibrary(Document& doc, const BrushLibraryPaths& paths, std::vector<std::string>& messages) {+ const std::string current = doc.brushVdm ? doc.brushVdm->name : std::string();+ doc.vdms = builtinVdms();+ auto scan = [&](const std::string& dir, bool user) {+ std::vector<std::string> files;+ std::error_code ec;+ for (fs::directory_iterator it(utf8Path(dir), ec), end; !ec && it != end; it.increment(ec)) {+ std::error_code fileEc;+ if (extensionOf(pathString(it->path())) == ".sfvdm" && it->is_regular_file(fileEc))+ files.push_back(pathString(it->path()));+ }+ std::sort(files.begin(), files.end());+ for (const std::string& f : files) {+ VectorDisplacement v;+ std::string err;+ if (!readVdmFile(f, v, err)) {+ messages.push_back("Skipped " + f + ": " + err);+ continue;+ }+ const int i = findVdm(doc, v.name);+ auto shared = std::make_shared<const VectorDisplacement>(std::move(v));+ if (i < 0) doc.vdms.push_back(shared);+ else if (user || doc.vdms[size_t(i)]->builtin) doc.vdms[size_t(i)] = shared; // user > studio > built-in+ }+ };+ for (const std::string& dir : paths.studioDirs) scan(dir, false);+ if (!paths.userDir.empty()) scan(paths.userDir, true);+ const int i = findVdm(doc, current);+ doc.brushVdm = i >= 0 ? doc.vdms[size_t(i)] : doc.vdms.front();+}++// ---------------------------------------------------------------------------+// Commands+// ---------------------------------------------------------------------------++namespace {++VdmImportOptions importOptions(const Args& a) {+ VdmImportOptions o;+ o.swapYZ = argBool(a, "swap_yz", false);+ o.flipX = argBool(a, "flip_x", false);+ o.flipY = argBool(a, "flip_y", false);+ o.flipZ = argBool(a, "flip_z", false);+ o.scale = float(std::clamp(argNumber(a, "scale", 1.0), -100.0, 100.0));+ return o;+}++// Saves `vdm` into the user library (when there is one); returns the note for the status line.+std::string saveToLibrary(VectorDisplacement& vdm) {+ const std::string dir = brushLibraryPaths().userDir;+ if (dir.empty()) return " (not saved: no brush library)";+ const std::string file = pathString(utf8Path(dir) / utf8Path(vdmFileName(vdm.name)));+ std::string err;+ if (!writeVdmFile(file, vdm, err)) return " (not saved: " + err + ")";+ vdm.path = file;+ return "";+}++} // namespace++void registerVdmCommands(CommandRegistry& registry) {+ using T = ParamSpec::Type;+ const std::vector<ParamSpec> importParams = {+ {"swap_yz", T::Bool, "Swap the map's Y and Z (G and B) channels, for maps made with Y as the normal.", false},+ {"flip_x", T::Bool, "Negate X (R).", false},+ {"flip_y", T::Bool, "Negate Y (G).", false},+ {"flip_z", T::Bool, "Negate Z (B).", false},+ {"scale", T::Number, "Multiply every vector (default 1).", false},+ };+ std::vector<ParamSpec> setParams = {+ {"name", T::String, "A built-in (horn, ear curl, scales, nostril) or library VDM, by name.", false},+ {"path", T::String, "A vector displacement map: 32/16-bit OpenEXR (Blender's format) or .sfvdm. Overrides name.", false},+ {"save", T::Bool, "Keep a loaded file in the brush library (default true).", false},+ };+ setParams.insert(setParams.end(), importParams.begin(), importParams.end());+ registry.add({"vdm_set",+ "Choose the vector displacement map the VDM brush stamps: a built-in, a library VDM, or an EXR file "+ "(RGB = XYZ in the brush's tangent space: X right, Y up, Z out of the surface, in brush radii).",+ setParams,+ [](Document& doc, const Args& a) -> CommandResult {+ const std::string path = argString(a, "path");+ if (!path.empty()) {+ VectorDisplacement v;+ std::string err;+ if (!loadVdm(path, v, err, importOptions(a))) return {false, err};+ std::string note;+ if (argBool(a, "save", true) && extensionOf(path) == ".exr") note = saveToLibrary(v);+ const std::string msg = "VDM '" + v.name + "' (" + std::to_string(v.width) + "x" ++ std::to_string(v.height) + ")" + note;+ addVdm(doc, std::move(v));+ return {true, msg};+ }+ const std::string name = argString(a, "name", "horn");+ const int i = findVdm(doc, name);+ if (i < 0) return {false, "No VDM called " + name + " (vdm_list shows them)"};+ doc.brushVdm = doc.vdms[size_t(i)];+ return {true, "VDM '" + doc.brushVdm->name + "'"};+ }});+ registry.add({"vdm_list", "List the vector displacement maps (built-in and library); * marks the brush's.", {},+ [](Document& doc, const Args&) -> CommandResult {+ std::string s;+ for (const auto& v : doc.vdms) {+ if (!s.empty()) s += ", ";+ s += (v == doc.brushVdm ? "*" : "") + v->name;+ }+ return {true, s};+ }});+ registry.add({"vdm_export",+ "Save the VDM brush's map as a 32-bit float OpenEXR (for Blender's VDM brushes) or .sfvdm.",+ {{"path", T::String, "File to write (.exr or .sfvdm).", true},+ {"name", T::String, "Which VDM (default: the brush's).", false}},+ [](Document& doc, const Args& a) -> CommandResult {+ const std::string path = argString(a, "path");+ std::shared_ptr<const VectorDisplacement> v = doc.brushVdm;+ if (const std::string name = argString(a, "name"); !name.empty()) {+ const int i = findVdm(doc, name);+ if (i < 0) return {false, "No VDM called " + name};+ v = doc.vdms[size_t(i)];+ }+ if (!v) return {false, "No VDM"};+ std::string err;+ const bool ok = extensionOf(path) == ".sfvdm" ? writeVdmFile(path, *v, err) : writeVdmExr(path, *v, err);+ if (!ok) return {false, err};+ return {true, "Exported VDM '" + v->name + "' to " + path};+ }});+ registry.add({"vdm_new_plane",+ "Add a VDM plane to sculpt a new vector displacement brush on (ZBrush's VDM plane template): a flat "+ "2 x 2 grid seen from the top, its border masked; the other SubTools are hidden. Then vdm_capture.",+ {{"resolution", T::Number, "Quads per side (16-1024). Default 256; divide it for finer detail.", false}},+ [](Document& doc, const Args& a) -> CommandResult {+ const int res = std::clamp(int(argNumber(a, "resolution", 256)), 16, 1024);+ for (auto& s : doc.subtools) s.visible = false;+ doc.addSubtool(makeVdmPlane(res), doc.uniqueSubtoolName("VDM Plane"));+ doc.activeSubtoolInfo().visible = true;+ doc.modified = true;+ return {true, "VDM plane (" + std::to_string(res) + " x " + std::to_string(res) ++ "): sculpt it from the top, then Create VDM"};+ }});+ registry.add({"vdm_capture",+ "Create a VDM brush from the active VDM plane: how far each point moved from the flat grid becomes "+ "a new vector displacement map in the brush library (ZBrush: create brush from the VDM plane).",+ {{"name", T::String, "Name of the new VDM (default 'My VDM').", false},+ {"resolution", T::Number, "Map size in pixels (16-2048, default 256; Blender suggests 512 or less).", false},+ {"exr", T::String, "Also write it as a 32-bit OpenEXR here, for Blender.", false},+ {"save", T::Bool, "Keep it in the brush library (default true).", false}},+ [](Document& doc, const Args& a) -> CommandResult {+ VectorDisplacement v;+ std::string err;+ if (!captureVdm(doc.mesh, int(argNumber(a, "resolution", 256)), v, err)) return {false, err};+ v.name = argString(a, "name", "My VDM");+ if (v.name.empty()) v.name = "My VDM";+ if (builtinVdm(v.name)) v.name += " (mine)";+ std::string note;+ if (argBool(a, "save", true)) note = saveToLibrary(v);+ if (const std::string exr = argString(a, "exr"); !exr.empty()) {+ if (!writeVdmExr(exr, v, err)) return {false, err};+ note += ", EXR " + exr;+ }+ const std::string msg = "Created VDM '" + v.name + "' (" + std::to_string(v.width) + " px)" + note;+ addVdm(doc, std::move(v));+ return {true, msg};+ }});+ registry.add({"vdm_stamp",+ "Press the VDM brush once (like a DragRect click): at the surface point a ray along `view` through "+ "`point` hits, `radius` in world units, its top turned by `angle` from the view's up. One undo step.",+ {{"point", T::String, "x,y,z the ray goes through.", true},+ {"view", T::String, "x,y,z view direction into the scene (default 0,0,-1).", false},+ {"radius", T::Number, "Brush radius in world units (default 4% of the model's size).", false},+ {"angle", T::Number, "Rotation in degrees, counter-clockwise on screen (default 0).", false},+ {"strength", T::Number, "Z Intensity 0-1 (default 0.5 = the map's own size; 1 doubles it).", false},+ {"invert", T::Bool, "Dig the shape in (Alt).", false},+ {"symmetry", T::String, "Mirror axes, e.g. \"x\" or \"xz\" (default none).", false}},+ [](Document& doc, const Args& a) -> CommandResult {+ glm::vec3 point, view(0.0f, 0.0f, -1.0f);+ if (!parseVec3(argString(a, "point"), point)) return {false, "Bad point (expected x,y,z)"};+ if (a.count("view") && !parseVec3(argString(a, "view"), view)) return {false, "Bad view (expected x,y,z)"};+ if (glm::length(view) < 1e-6f) return {false, "The view direction must not be zero"};+ view = glm::normalize(view);+ if (doc.mesh.triangleCount() == 0) return {false, "The active SubTool is empty"};+ doc.syncBvh();+ const AABB box = doc.mesh.bounds();+ const float diag = std::max(glm::length(box.extent()), 1e-4f);+ RayHit hit;+ const glm::vec3 origin = point - view * (glm::dot(point - box.center(), view) + diag);+ if (!doc.bvh.raycast(doc.mesh, origin, view, hit)) return {false, "The ray misses the surface"};+ const glm::vec3 helper = std::abs(view.y) > 0.9f ? glm::vec3(0.0f, 0.0f, -1.0f) : glm::vec3(0.0f, 1.0f, 0.0f);+ const glm::vec3 right = glm::normalize(glm::cross(view, helper));+ const glm::vec3 up = glm::cross(right, view);+ const float angle = float(argNumber(a, "angle", 0.0)) * 3.14159265f / 180.0f;+ DabParams p;+ p.center = hit.position;+ p.viewDir = view;+ p.radius = float(argNumber(a, "radius", 0.0));+ if (!(p.radius > 0.0f)) p.radius = diag * 0.04f;+ p.strength = float(std::clamp(argNumber(a, "strength", 0.5), 0.0, 1.0));+ p.invert = argBool(a, "invert", false);+ p.alphaUp = up * std::cos(angle) - right * std::sin(angle);+ p.vdm = doc.brushVdm.get();+ Symmetry sym{false, false, false};+ const std::string axes = lower(argString(a, "symmetry"));+ sym.x = axes.find('x') != std::string::npos;+ sym.y = axes.find('y') != std::string::npos;+ sym.z = axes.find('z') != std::string::npos;+ if (!doc.sculptor.beginStroke(doc.mesh, "VDM", doc.activeLayer))+ return {false, "Active layer weight is 0 - raise it to sculpt into the layer"};+ doc.sculptor.dab(doc.mesh, doc.bvh, BrushType::Vdm, p, sym);+ UndoRecord r = doc.sculptor.endStroke();+ if (!r.empty()) doc.undo.push(std::move(r));+ return {true, "Stamped VDM '" + (doc.brushVdm ? doc.brushVdm->name : std::string("Horn")) + "'"};+ }});+ registry.add({"vdm_delete", "Delete a VDM from your brush library (built-ins and studio VDMs stay).",+ {{"name", T::String, "The VDM to delete.", true}},+ [](Document& doc, const Args& a) -> CommandResult {+ const int i = findVdm(doc, argString(a, "name"));+ if (i < 0) return {false, "No VDM called " + argString(a, "name")};+ const auto v = doc.vdms[size_t(i)];+ const std::string dir = brushLibraryPaths().userDir;+ std::error_code ec;+ const bool inLibrary = !v->builtin && !v->path.empty() && !dir.empty() &&+ fs::equivalent(utf8Path(v->path).parent_path(), utf8Path(dir), ec);+ if (v->builtin) return {false, v->name + " is built in"};+ if (!v->path.empty() && !inLibrary) return {false, v->name + " isn't in your brush library"};+ if (!v->path.empty() && !fs::remove(utf8Path(v->path), ec))+ return {false, "Can't delete " + v->path};+ doc.vdms.erase(doc.vdms.begin() + i);+ if (doc.brushVdm == v) doc.brushVdm = doc.vdms.front();+ // A studio or built-in VDM of the same name comes back on the next library load.+ return {true, "Deleted VDM '" + v->name + "'"};+ }});+}++} // namespace sfdiff --git a/src/core/Vdm.h b/src/core/Vdm.hnew file mode 100644index 00000000..e6cac9cb--- /dev/null+++ b/src/core/Vdm.h@@ -0,0 +1,107 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Vector displacement maps (ZBrush VDM brushes, Blender's "VDM brushes"): a square grid of 3D offsets in the+// brush's tangent frame. One dab of the VDM brush (BrushType::Vdm) moves every vertex under the stamp by its+// texel's vector, so a single click can press a horn, an ear curl or a nostril with overhangs, which a height+// (grayscale alpha) can't.+//+// Convention (the same as Blender's VDM Brush Baker and its Draw brush with "Vector Displacement"):+// - the map covers the brush's square, -1..1 in both directions (1 = the brush radius);+// - R = X, along the stamp's right; G = Y, toward the stamp's top (the image's top row, the drag direction+// of DragRect); B = Z, out of the surface along its normal;+// - values are in brush radii: (0, 0, 0.5) lifts the surface by half the radius.+// Blender bakes the map from a 2 x 2 grid (-1..1) and its brush scales the vector by the radius, so a map from+// Blender stamps the same shape here and ours there. EXR files are read as stored, first scanline = top.+#pragma once++#include <glm/glm.hpp>++#include <cstdint>+#include <memory>+#include <string>+#include <vector>++namespace sf {++class CommandRegistry;+class Mesh;+struct Document;+struct BrushLibraryPaths;++struct VectorDisplacement {+ std::string name = "VDM";+ std::string path; // the .sfvdm / .exr file it came from or is saved to (empty: built-in or unsaved)+ bool builtin = false;+ int width = 0, height = 0;+ std::vector<glm::vec3> vectors; // row-major, row 0 at the top (+Y), tangent space (see above)++ bool empty() const { return vectors.empty(); }+ // u, v in -1..1 (v up). Bilinear; (0, 0, 0) outside the square.+ glm::vec3 sample(float u, float v) const;+ // Largest |vector| (how far the stamp reaches out of its square, in radii).+ float extent() const;+ // Content hash (thumbnail keys, change detection).+ uint64_t hash() const;+};++// How to read the axes of a map made elsewhere (applied in this order: swap, flips, scale).+struct VdmImportOptions {+ bool swapYZ = false; // G and B swapped (Y-up apps)+ bool flipX = false, flipY = false, flipZ = false;+ float scale = 1.0f;+};++// --- Files ---++// OpenEXR (half or float, any compression tinyexr reads: none, RLE, ZIP, ZIPS, PIZ, PXR24, B44 ...). RGB are+// the vector; a one-channel (grayscale) EXR is a plain height map (Z only).+bool readVdmExr(const std::string& path, VectorDisplacement& out, std::string& error, const VdmImportOptions& opt = {});+bool decodeVdmExr(const unsigned char* bytes, size_t size, VectorDisplacement& out, std::string& error,+ const VdmImportOptions& opt = {});+// 32-bit float RGB, ZIP compressed: what Blender's VDM Brush Baker writes at 32 bits.+bool writeVdmExr(const std::string& path, const VectorDisplacement& vdm, std::string& error);+bool encodeVdmExr(const VectorDisplacement& vdm, std::vector<unsigned char>& out, std::string& error);++// Our own format (the brush library keeps VDMs as .sfvdm): "SFVDM1\n\0", u32 width, u32 height, u32 name+// length, the UTF-8 name, then width x height x 3 little-endian float32 (row 0 at the top). At most 2048 px a side.+bool readVdmFile(const std::string& path, VectorDisplacement& out, std::string& error);+bool writeVdmFile(const std::string& path, const VectorDisplacement& vdm, std::string& error);+// By extension: .sfvdm or .exr.+bool loadVdm(const std::string& path, VectorDisplacement& out, std::string& error, const VdmImportOptions& opt = {});+bool isVdmFile(const std::string& path);++// --- Built-ins (procedural, CC0): Horn, Ear Curl, Scales, Nostril ---++const std::vector<std::shared_ptr<const VectorDisplacement>>& builtinVdms();+std::shared_ptr<const VectorDisplacement> builtinVdm(const std::string& name); // case-insensitive; null if unknown+// The four generators (exposed for tests; `size` texels a side).+VectorDisplacement makeHornVdm(int size = 256);+VectorDisplacement makeEarCurlVdm(int size = 256);+VectorDisplacement makeScalesVdm(int size = 256);+VectorDisplacement makeNostrilVdm(int size = 256);++// --- Create VDM from a plane (ZBrush: Brush > Create > from the VDM plane; Blender: VDM Brush Baker) ---++// A flat 2 x 2 grid in the XZ plane facing +Y (the top view), `cells` quads a side, with UVs (they record+// where each vertex started, so its offset can be captured after sculpting) and the outer ring masked.+Mesh makeVdmPlane(int cells = 256);+// Rasterizes (position - start) of every triangle of `mesh` into a `size` x `size` map through its UVs (0..1,+// v up). Map axes: X = world +X, Y = world -Z (up in the top view), Z = world +Y. False without UVs.+bool captureVdm(const Mesh& mesh, int size, VectorDisplacement& out, std::string& error);++// --- Library (VDMs live as .sfvdm files next to the .sfbrush files; see core/BrushLibrary.h) ---++// Resets doc.vdms to the built-ins plus the studio and user library .sfvdm files; keeps the current VDM by name.+void loadVdmLibrary(Document& doc, const BrushLibraryPaths& paths, std::vector<std::string>& messages);+// Adds or replaces (by name) `vdm` in doc.vdms and makes it the brush's VDM; returns it.+std::shared_ptr<const VectorDisplacement> addVdm(Document& doc, VectorDisplacement vdm);+// Index of the VDM called `name` in doc.vdms (case-insensitive), or -1.+int findVdm(const Document& doc, const std::string& name);+// "<name>.sfvdm" made safe on every OS.+std::string vdmFileName(const std::string& name);++// vdm_set, vdm_list, vdm_export, vdm_new_plane, vdm_capture, vdm_stamp, vdm_delete.+void registerVdmCommands(CommandRegistry& registry);++} // namespace sfdiff --git a/tests/test_vdm.cpp b/tests/test_vdm.cppnew file mode 100644index 00000000..26670b86--- /dev/null+++ b/tests/test_vdm.cpp@@ -0,0 +1,390 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Vector displacement brushes (core/Vdm.h): EXR and .sfvdm round trips, the built-ins, capturing a VDM from+// the VDM plane and stamping it back, the tangent frame and rotation, symmetry, mask, invert, undo, the+// library and the commands.+#include "TestHarness.h"++#include "core/BrushLibrary.h"+#include "core/Commands.h"+#include "core/Primitives.h"+#include "core/Sculpt.h"+#include "core/ThreadPool.h"+#include "core/Vdm.h"++#include <algorithm>+#include <cmath>+#include <filesystem>+#include <fstream>++using namespace sf;+namespace fs = std::filesystem;++namespace {++bool run(Document& d, const std::string& name, const Args& args = {}) {+ static CommandRegistry registry;+ const CommandResult r = registry.execute(d, name, args);+ if (!r.ok) std::printf(" %s: %s\n", name.c_str(), r.message.c_str());+ return r.ok;+}++uint32_t nearest(const Mesh& m, const glm::vec3& p) {+ uint32_t best = 0;+ for (uint32_t v = 1; v < m.vertexCount(); ++v)+ if (glm::distance(m.positions[v], p) < glm::distance(m.positions[best], p)) best = v;+ return best;+}++// A small asymmetric map: a lump in the top-right quarter that leans toward +X and +Y.+VectorDisplacement leaningLump(int size = 32) {+ VectorDisplacement v;+ v.name = "Lump";+ v.width = v.height = size;+ v.vectors.resize(size_t(size) * size_t(size));+ for (int y = 0; y < size; ++y)+ for (int x = 0; x < size; ++x) {+ const float u = (float(x) + 0.5f) / float(size) * 2.0f - 1.0f, w = 1.0f - (float(y) + 0.5f) / float(size) * 2.0f;+ const float d = glm::length(glm::vec2(u - 0.3f, w - 0.2f)) / 0.45f;+ const float k = d < 1.0f ? (1.0f - d * d) * (1.0f - d * d) : 0.0f;+ v.vectors[size_t(y) * size_t(size) + size_t(x)] = glm::vec3(0.2f, 0.1f, 0.3f) * k;+ }+ return v;+}++// The deformation sculpted onto the VDM plane in vdm_capture_then_stamp: a lump that leans over to +X (an+// overhang) and toward the top of the map (world -Z).+glm::vec3 sculptedOffset(const glm::vec3& p) {+ const float d = glm::length(glm::vec2(p.x, p.z)) / 0.6f;+ const float k = d < 1.0f ? (1.0f - d * d) * (1.0f - d * d) : 0.0f;+ return glm::vec3(0.35f, 0.4f, -0.15f) * k;+}++struct VdmLibrary {+ fs::path root;+ BrushLibraryPaths saved = brushLibraryPaths();+ explicit VdmLibrary(const char* name) {+ root = fs::temp_directory_path() / (std::string("sculptforge_vdmlib_") + name);+ fs::remove_all(root);+ fs::create_directories(root / "user");+ fs::create_directories(root / "studio");+ brushLibraryPaths() = paths();+ }+ ~VdmLibrary() {+ brushLibraryPaths() = saved;+ std::error_code ec;+ fs::remove_all(root, ec);+ }+ BrushLibraryPaths paths() const { return {(root / "user").string(), {(root / "studio").string()}}; }+};++} // namespace++TEST(vdm_builtins_are_bounded_and_overhang) {+ const auto& all = builtinVdms();+ CHECK(all.size() == 4);+ for (const auto& v : all) {+ CHECK(v->builtin && v->width == 256 && v->height == 256);+ CHECK(v->extent() > 0.1f && v->extent() < 2.0f);+ // Zero along the border, so a stamp blends into any surface.+ float border = 0.0f;+ for (int i = 0; i < v->width; ++i) {+ border = std::max(border, glm::length(v->vectors[size_t(i)]));+ border = std::max(border, glm::length(v->vectors[size_t(v->height - 1) * size_t(v->width) + size_t(i)]));+ border = std::max(border, glm::length(v->vectors[size_t(i) * size_t(v->width)]));+ }+ CHECK(border < 1e-4f);+ // Sideways motion, not just height: what a grayscale alpha can't do.+ float lateral = 0.0f;+ for (const glm::vec3& d : v->vectors) lateral = std::max(lateral, std::hypot(d.x, d.y));+ CHECK(lateral > 0.06f);+ CHECK(builtinVdm(v->name) == v);+ }+ // The horn's tip leans over past its base toward the map's top (+Y): an overhang.+ const auto horn = builtinVdm("horn");+ CHECK(horn != nullptr);+ if (horn) {+ const glm::vec3 tip = horn->sample(0.0f, 0.0f);+ CHECK(tip.z > 0.6f && tip.y > 0.3f);+ }+ // The nostril digs in.+ const auto nostril = builtinVdm("Nostril");+ CHECK(nostril && nostril->sample(0.0f, 0.0f).z < -0.3f);+ CHECK(builtinVdm("nope") == nullptr);+}++TEST(vdm_exr_round_trip) {+ VectorDisplacement v = makeEarCurlVdm(64);+ std::vector<unsigned char> bytes;+ std::string err;+ CHECK(encodeVdmExr(v, bytes, err));+ CHECK(bytes.size() > 100 && bytes[0] == 0x76 && bytes[1] == 0x2f && bytes[2] == 0x31 && bytes[3] == 0x01);+ VectorDisplacement back;+ CHECK(decodeVdmExr(bytes.data(), bytes.size(), back, err));+ CHECK(back.width == 64 && back.height == 64 && back.vectors == v.vectors); // 32-bit float: exact++ const std::string path = tempPath("sculptforge_vdm_round.exr");+ CHECK(writeVdmExr(path, v, err));+ VectorDisplacement file;+ CHECK(loadVdm(path, file, err));+ CHECK(file.vectors == v.vectors && file.name == "sculptforge_vdm_round" && file.path == path && !file.builtin);++ // Import options: swap Y/Z, flips, scale.+ VdmImportOptions opt;+ opt.swapYZ = true;+ opt.flipX = true;+ opt.scale = 2.0f;+ VectorDisplacement swapped;+ CHECK(readVdmExr(path, swapped, err, opt));+ const glm::vec3 a = v.vectors[size_t(30) * 64 + 33], b = swapped.vectors[size_t(30) * 64 + 33];+ CHECK(std::abs(b.x + 2.0f * a.x) < 1e-6f && std::abs(b.y - 2.0f * a.z) < 1e-6f && std::abs(b.z - 2.0f * a.y) < 1e-6f);+ fs::remove(path);++ // Garbage is refused.+ const unsigned char junk[] = {1, 2, 3, 4, 5, 6, 7, 8};+ CHECK(!decodeVdmExr(junk, sizeof junk, back, err) && !err.empty());+ CHECK(!loadVdm(tempPath("sculptforge_no_such.exr"), back, err));+}++TEST(vdm_sfvdm_round_trip_and_damaged_files) {+ VectorDisplacement v = leaningLump(40);+ v.name = "Lümp \"two\"";+ const std::string path = tempPath("sculptforge_vdm_round.sfvdm");+ std::string err;+ CHECK(writeVdmFile(path, v, err));+ VectorDisplacement back;+ CHECK(readVdmFile(path, back, err));+ CHECK(back.name == v.name && back.width == 40 && back.height == 40 && back.vectors == v.vectors);+ CHECK(isVdmFile(path) && isVdmFile("a.EXR") && !isVdmFile("a.png"));+ // Truncated, wrong magic, empty.+ const auto size = fs::file_size(path);+ fs::resize_file(path, size - 7);+ CHECK(!readVdmFile(path, back, err));+ { std::ofstream(path, std::ios::binary) << "SFVDM2\nxxxxxxxxxxxxxxxxxxxxxxx"; }+ CHECK(!readVdmFile(path, back, err));+ { std::ofstream(path, std::ios::binary | std::ios::trunc); }+ CHECK(!readVdmFile(path, back, err));+ fs::remove(path);+ CHECK(!writeVdmFile(path, VectorDisplacement{}, err));+}++TEST(vdm_sample_is_bilinear_and_zero_outside) {+ VectorDisplacement v;+ v.width = v.height = 2;+ v.vectors = {glm::vec3(0, 0, 1), glm::vec3(0, 0, 2), glm::vec3(0, 0, 3), glm::vec3(0, 0, 4)}; // top row first+ CHECK(std::abs(v.sample(0.0f, 0.0f).z - 2.5f) < 1e-5f);+ CHECK(std::abs(v.sample(-0.5f, 0.5f).z - 1.0f) < 1e-5f); // top-left pixel centre+ CHECK(std::abs(v.sample(0.5f, -0.5f).z - 4.0f) < 1e-5f); // bottom-right+ CHECK(v.sample(1.01f, 0.0f) == glm::vec3(0.0f) && v.sample(0.0f, -1.2f) == glm::vec3(0.0f));+}++// Sculpt a known shape onto the VDM plane, capture it, stamp it on another plane at radius 1: every point lands+// where the sculpted plane's point did (Z Intensity 50 = the map's own size).+TEST(vdm_capture_then_stamp_reproduces_the_shape) {+ Document plane = makeDoc(makeVdmPlane(128));+ CHECK(plane.mesh.hasUvs() && plane.mesh.hasMask());+ CHECK(plane.mesh.maskAt(0) == 1.0f && plane.mesh.maskAt(nearest(plane.mesh, glm::vec3(0.0f))) == 0.0f);+ for (glm::vec3& p : plane.mesh.positions) p += sculptedOffset(p);+ plane.mesh.recomputeAllNormals();++ VectorDisplacement captured;+ std::string err;+ CHECK(captureVdm(plane.mesh, 128, captured, err));+ CHECK(captured.width == 128);+ // The map holds the offsets in tangent axes: X = +X, Y = -Z, Z = +Y.+ for (const glm::vec2 uv : {glm::vec2(0.0f, 0.0f), glm::vec2(0.21f, -0.13f), glm::vec2(-0.4f, 0.3f), glm::vec2(0.8f, 0.8f)}) {+ const glm::vec3 world(uv.x, 0.0f, -uv.y);+ const glm::vec3 o = sculptedOffset(world);+ const glm::vec3 m = captured.sample(uv.x, uv.y);+ CHECK(glm::length(m - glm::vec3(o.x, -o.z, o.y)) < 0.01f);+ }+ // No UVs, no capture.+ VectorDisplacement none;+ CHECK(!captureVdm(makePlane(8, 2.0f), 64, none, err) && !err.empty());++ Document target = makeDoc(makePlane(128, 2.0f));+ target.brushVdm = std::make_shared<const VectorDisplacement>(captured);+ CHECK(run(target, "vdm_stamp", {{"point", std::string("0,1,0")}, {"view", std::string("0,-1,0")}, {"radius", 1.0}}));+ float worst = 0.0f;+ const Mesh flat = makePlane(128, 2.0f);+ for (uint32_t v = 0; v < flat.vertexCount(); ++v) {+ const glm::vec3 p = flat.positions[v];+ if (std::max(std::abs(p.x), std::abs(p.z)) > 0.95f) continue; // the 3% border fade+ worst = std::max(worst, glm::distance(target.mesh.positions[v], p + sculptedOffset(p)));+ }+ CHECK(worst < 0.01f);+ // Half the radius: half the offsets, at half the distance.+ Document small = makeDoc(makePlane(128, 2.0f));+ small.brushVdm = target.brushVdm;+ CHECK(run(small, "vdm_stamp", {{"point", std::string("0,1,0")}, {"view", std::string("0,-1,0")}, {"radius", 0.5}}));+ const uint32_t c = nearest(flat, glm::vec3(0.0f));+ CHECK(glm::distance(small.mesh.positions[c], sculptedOffset(glm::vec3(0.0f)) * 0.5f) < 0.01f);+}++TEST(vdm_tangent_frame_rotation_and_normal) {+ // Turning the stamp turns its sideways push: the lump leans to the stamp's +X and +Y.+ auto lump = std::make_shared<const VectorDisplacement>(leaningLump());+ auto leanOf = [&](float angle) {+ Document d = makeDoc(makePlane(96, 2.0f));+ d.brushVdm = lump;+ const auto before = d.mesh.positions;+ CHECK(run(d, "vdm_stamp", {{"point", std::string("0,1,0")}, {"view", std::string("0,-1,0")}, {"radius", 0.9},+ {"angle", double(angle)}}));+ glm::vec3 sum(0.0f);+ for (uint32_t v = 0; v < d.mesh.vertexCount(); ++v) sum += d.mesh.positions[v] - before[v];+ return sum;+ };+ const glm::vec3 a = leanOf(0.0f), b = leanOf(90.0f);+ // Seen from the top (view -Y): right = +X, up = -Z. The lump moves +X, -Z (and up).+ CHECK(a.x > 0.0f && a.z < 0.0f && a.y > 0.0f);+ // 90 degrees counter-clockwise: right -> up (-Z), up -> -right (-X).+ CHECK(std::abs(b.x - a.z) < std::abs(a.x) * 0.05f + 1e-3f);+ CHECK(std::abs(b.z - (-a.x)) < std::abs(a.x) * 0.05f + 1e-3f);+ CHECK(std::abs(b.y - a.y) < a.y * 0.02f);++ // On the side of a sphere, Z goes out along the surface normal there.+ Document s = makeDoc(makeIcosphere(5, 1.0f));+ s.brushVdm = builtinVdm("horn");+ const uint32_t tip = nearest(s.mesh, glm::vec3(1.0f, 0.0f, 0.0f));+ const glm::vec3 before = s.mesh.positions[tip];+ CHECK(run(s, "vdm_stamp", {{"point", std::string("0,0,0")}, {"view", std::string("-1,0,0")}, {"radius", 0.3}}));+ const glm::vec3 moved = s.mesh.positions[tip] - before;+ CHECK(moved.x > 0.15f && std::abs(moved.z) < 0.05f);+}++TEST(vdm_symmetry_mirrors_exactly) {+ Document d = makeDoc(makePlane(64, 2.0f));+ d.brushVdm = std::make_shared<const VectorDisplacement>(leaningLump());+ const auto before = d.mesh.positions;+ CHECK(run(d, "vdm_stamp", {{"point", std::string("0.45,1,0.1")}, {"view", std::string("0,-1,0")}, {"radius", 0.35},+ {"angle", 30.0}, {"symmetry", std::string("x")}}));+ float worst = 0.0f, moved = 0.0f;+ // Mirror pairs by grid index (makePlane: row-major, x fastest): x index i <-> n - i.+ const int n = 64;+ for (int j = 0; j <= n; ++j)+ for (int i = 0; i <= n; ++i) {+ const uint32_t v = uint32_t(j * (n + 1) + i), w = uint32_t(j * (n + 1) + (n - i));+ const glm::vec3 dv = d.mesh.positions[v] - before[v], dw = d.mesh.positions[w] - before[w];+ worst = std::max(worst, glm::length(dw - glm::vec3(-dv.x, dv.y, dv.z)));+ moved = std::max(moved, glm::length(dv));+ }+ CHECK(moved > 0.02f);+ CHECK(worst < 1e-5f);+}++TEST(vdm_respects_mask_invert_and_undo) {+ Document d = makeDoc(makePlane(64, 2.0f));+ d.brushVdm = builtinVdm("horn");+ auto& mask = d.mesh.ensureMask(0.0f);+ for (uint32_t v = 0; v < d.mesh.vertexCount(); ++v)+ if (d.mesh.positions[v].x < 0.0f) mask[v] = 1.0f;+ const auto before = d.mesh.positions;+ const Args at = {{"point", std::string("0,1,0")}, {"view", std::string("0,-1,0")}, {"radius", 0.5}};+ CHECK(run(d, "vdm_stamp", at));+ bool maskedStill = true, rightMoved = false;+ for (uint32_t v = 0; v < d.mesh.vertexCount(); ++v) {+ if (before[v].x < 0.0f && d.mesh.positions[v] != before[v]) maskedStill = false;+ if (before[v].x > 0.05f && glm::distance(d.mesh.positions[v], before[v]) > 0.05f) rightMoved = true;+ }+ CHECK(maskedStill && rightMoved);+ const auto stamped = d.mesh.positions;+ CHECK(run(d, "undo"));+ CHECK(d.mesh.positions == before);+ CHECK(run(d, "redo"));+ CHECK(d.mesh.positions == stamped);++ // Alt: the same sideways motion, the height the other way.+ Document a = makeDoc(makePlane(64, 2.0f)), b = makeDoc(makePlane(64, 2.0f));+ a.brushVdm = b.brushVdm = std::make_shared<const VectorDisplacement>(leaningLump());+ CHECK(run(a, "vdm_stamp", at));+ Args inv = at;+ inv["invert"] = true;+ CHECK(run(b, "vdm_stamp", inv));+ float worst = 0.0f;+ for (uint32_t v = 0; v < a.mesh.vertexCount(); ++v) {+ const glm::vec3 da = a.mesh.positions[v] - before[v], db = b.mesh.positions[v] - before[v];+ worst = std::max(worst, glm::length(db - glm::vec3(da.x, -da.y, da.z)));+ }+ CHECK(worst < 1e-5f);+}++TEST(vdm_is_deterministic_with_and_without_threads) {+ auto stamp = [] {+ Document d = makeDoc(makeIcosphere(6, 1.0f));+ d.brushVdm = builtinVdm("scales");+ CHECK(run(d, "vdm_stamp", {{"point", std::string("0.2,0.3,0")}, {"view", std::string("0,0,-1")}, {"radius", 0.6},+ {"symmetry", std::string("x")}}));+ return d.mesh.positions;+ };+ const auto parallel = stamp();+ ThreadPool::shared().setSerial(true);+ const auto serial = stamp();+ ThreadPool::shared().setSerial(false);+ CHECK(parallel == serial);+ // Capture too.+ Document plane = makeDoc(makeVdmPlane(64));+ for (glm::vec3& p : plane.mesh.positions) p += sculptedOffset(p);+ VectorDisplacement a, b;+ std::string err;+ CHECK(captureVdm(plane.mesh, 96, a, err));+ ThreadPool::shared().setSerial(true);+ CHECK(captureVdm(plane.mesh, 96, b, err));+ ThreadPool::shared().setSerial(false);+ CHECK(a.vectors == b.vectors);+}++TEST(vdm_library_commands) {+ VdmLibrary lib("commands");+ Document d;+ // A studio VDM, then the user's capture.+ VectorDisplacement studio = leaningLump();+ studio.name = "Studio Lump";+ std::string err;+ CHECK(writeVdmFile((lib.root / "studio" / "Studio Lump.sfvdm").string(), studio, err));+ { std::ofstream(lib.root / "user" / "broken.sfvdm", std::ios::binary) << "nope"; }+ const auto messages = loadBrushLibrary(d, lib.paths());+ CHECK(messages.size() == 1); // broken.sfvdm+ CHECK(d.vdms.size() == 5 && findVdm(d, "studio lump") == 4);+ fs::remove(lib.root / "user" / "broken.sfvdm");++ CHECK(run(d, "vdm_new_plane", {{"resolution", 64.0}}));+ CHECK(d.subtoolCount() == 2 && !d.subtools[0].visible && d.activeSubtool == 1 && d.mesh.hasUvs());+ for (glm::vec3& p : d.mesh.positions) p += sculptedOffset(p);+ const std::string exr = (lib.root / "Spike.exr").string();+ CHECK(run(d, "vdm_capture", {{"name", std::string("Spike")}, {"resolution", 64.0}, {"exr", exr}}));+ CHECK(d.brushVdm && d.brushVdm->name == "Spike" && fs::exists(lib.root / "user" / "Spike.sfvdm") && fs::exists(exr));+ CHECK(run(d, "vdm_capture", {{"name", std::string("Horn")}, {"resolution", 32.0}, {"save", false}}));+ CHECK(d.brushVdm->name == "Horn (mine)" && builtinVdm("Horn")->width == 256);++ // A fresh session finds the capture in the library; the EXR loads the same map.+ Document fresh;+ loadBrushLibrary(fresh, lib.paths());+ const int spike = findVdm(fresh, "Spike");+ CHECK(spike >= 0 && fresh.vdms[size_t(spike)]->vectors == d.vdms[size_t(findVdm(d, "Spike"))]->vectors);+ CHECK(run(fresh, "vdm_set", {{"path", exr}, {"save", false}}));+ CHECK(fresh.brushVdm->vectors == fresh.vdms[size_t(spike)]->vectors);+ CHECK(run(fresh, "vdm_set", {{"name", std::string("ear curl")}}) && fresh.brushVdm->name == "Ear Curl");+ CHECK(!run(fresh, "vdm_set", {{"name", std::string("nothing")}}));+ CHECK(run(fresh, "vdm_list"));++ const std::string out = (lib.root / "out.sfvdm").string();+ CHECK(run(fresh, "vdm_export", {{"path", out}, {"name", std::string("Scales")}}));+ VectorDisplacement scales;+ CHECK(readVdmFile(out, scales, err) && scales.vectors == builtinVdm("scales")->vectors);++ // Delete: library VDMs only.+ CHECK(!run(fresh, "vdm_delete", {{"name", std::string("Horn")}}));+ CHECK(!run(fresh, "vdm_delete", {{"name", std::string("Studio Lump")}}));+ // (fresh's Spike is the EXR now, loaded over the library one by name: not deletable from here.)+ CHECK(!run(fresh, "vdm_delete", {{"name", std::string("Spike")}}));+ CHECK(run(d, "vdm_delete", {{"name", std::string("Spike")}}));+ CHECK(!fs::exists(lib.root / "user" / "Spike.sfvdm") && findVdm(d, "Spike") < 0);++ // The stroke command stamps with the brush's VDM too.+ Document s = makeDoc(makePlane(48, 2.0f));+ const auto before = s.mesh.positions;+ CHECK(run(s, "stroke", {{"brush", std::string("vdm")}, {"points", std::string("0,1,0")}, {"view", std::string("0,-1,0")},+ {"radius", 0.5}}));+ CHECK(s.mesh.positions != before);+}diff --git a/third_party/tinyexr/LICENSE b/third_party/tinyexr/LICENSEnew file mode 100644index 00000000..d89add60--- /dev/null+++ b/third_party/tinyexr/LICENSE@@ -0,0 +1,29 @@+BSD 3-Clause License++Copyright (c) 2014 - 2021, Syoyo Fujita and many contributors.+All rights reserved.++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are met:++1. Redistributions of source code must retain the above copyright notice, this+ list of conditions and the following disclaimer.++2. Redistributions in binary form must reproduce the above copyright notice,+ this list of conditions and the following disclaimer in the documentation+ and/or other materials provided with the distribution.++3. Neither the name of the copyright holder nor the names of its+ contributors may be used to endorse or promote products derived from+ this software without specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\ No newline at end of filediff --git a/third_party/tinyexr/SOURCE.txt b/third_party/tinyexr/SOURCE.txtnew file mode 100644index 00000000..bcc85277--- /dev/null+++ b/third_party/tinyexr/SOURCE.txt@@ -0,0 +1,3 @@+tinyexr.h, exr_reader.hh, streamreader.hh and LICENSE from https://github.com/syoyo/tinyexr tag v1.0.13 (BSD 3-Clause; contains OpenEXR code+under the OpenEXR BSD licence, reproduced in tinyexr.h). Unmodified. tinyexr_impl.cpp is ours: it builds the+implementation with stb's zlib (TINYEXR_USE_STB_ZLIB) instead of miniz.diff --git a/third_party/tinyexr/exr_reader.hh b/third_party/tinyexr/exr_reader.hhnew file mode 100644index 00000000..8ea0d666--- /dev/null+++ b/third_party/tinyexr/exr_reader.hh@@ -0,0 +1,191 @@+// SPDX-License-Identifier: BSD-3-Clause+// Copyright (c) 2025, Syoyo Fujita and many contributors.+// All rights reserved.+//+// EXR Reader: Reader class with error stack for safe memory reading++#ifndef TINYEXR_EXR_READER_HH_+#define TINYEXR_EXR_READER_HH_++#include <vector>+#include <string>+#include "streamreader.hh"++namespace tinyexr {++// Reader class that wraps StreamReader and accumulates errors+class Reader {+public:+ Reader(const uint8_t* data, size_t length, Endian endian = Endian::Little)+ : stream_(data, length, endian), has_error_(false) {}++ // Check if any errors have occurred+ bool has_error() const { return has_error_; }++ // Get all accumulated errors+ const std::vector<std::string>& errors() const { return errors_; }++ // Get the most recent error+ std::string last_error() const {+ return errors_.empty() ? "" : errors_.back();+ }++ // Get all errors as a single string+ std::string all_errors() const {+ std::string result;+ for (size_t i = 0; i < errors_.size(); i++) {+ if (i > 0) result += "\n";+ result += errors_[i];+ }+ return result;+ }++ // Clear error stack+ void clear_errors() {+ errors_.clear();+ has_error_ = false;+ }++ // Read n bytes into destination buffer+ bool read(size_t n, uint8_t* dst) {+ if (!stream_.read(n, dst)) {+ add_error("Failed to read " + std::to_string(n) + " bytes at position " ++ std::to_string(stream_.tell()));+ return false;+ }+ return true;+ }++ // Read 1 byte+ bool read1(uint8_t* dst) {+ if (!stream_.read1(dst)) {+ add_error("Failed to read 1 byte at position " ++ std::to_string(stream_.tell()));+ return false;+ }+ return true;+ }++ // Read 2 bytes with endian swap+ bool read2(uint16_t* dst) {+ if (!stream_.read2(dst)) {+ add_error("Failed to read 2 bytes at position " ++ std::to_string(stream_.tell()));+ return false;+ }+ return true;+ }++ // Read 4 bytes with endian swap+ bool read4(uint32_t* dst) {+ if (!stream_.read4(dst)) {+ add_error("Failed to read 4 bytes at position " ++ std::to_string(stream_.tell()));+ return false;+ }+ return true;+ }++ // Read 8 bytes with endian swap+ bool read8(uint64_t* dst) {+ if (!stream_.read8(dst)) {+ add_error("Failed to read 8 bytes at position " ++ std::to_string(stream_.tell()));+ return false;+ }+ return true;+ }++ // Read a null-terminated string up to max_len bytes+ // Returns false if no null terminator found within max_len+ bool read_string(std::string* str, size_t max_len = 256) {+ if (!str) {+ add_error("Null pointer passed to read_string");+ return false;+ }++ str->clear();+ size_t start_pos = stream_.tell();++ for (size_t i = 0; i < max_len; i++) {+ uint8_t c;+ if (!stream_.read1(&c)) {+ add_error("Failed to read string at position " + std::to_string(start_pos));+ return false;+ }+ if (c == '\0') {+ return true;+ }+ str->push_back(static_cast<char>(c));+ }++ add_error("String not null-terminated within " + std::to_string(max_len) ++ " bytes at position " + std::to_string(start_pos));+ return false;+ }++ // Seek to absolute position+ bool seek(size_t pos) {+ if (!stream_.seek(pos)) {+ add_error("Failed to seek to position " + std::to_string(pos));+ return false;+ }+ return true;+ }++ // Seek relative to current position+ bool seek_relative(int64_t offset) {+ size_t current = stream_.tell();+ int64_t new_pos = static_cast<int64_t>(current) + offset;++ if (new_pos < 0) {+ add_error("Seek would move before start of stream");+ return false;+ }++ return seek(static_cast<size_t>(new_pos));+ }++ // Rewind to beginning+ void rewind() {+ stream_.rewind();+ }++ // Get current position+ size_t tell() const {+ return stream_.tell();+ }++ // Get remaining bytes+ size_t remaining() const {+ return stream_.remaining();+ }++ // Check if at end+ bool eof() const {+ return stream_.eof();+ }++ // Get total length+ size_t length() const {+ return stream_.length();+ }++ // Add a custom error message+ void add_error(const std::string& msg) {+ errors_.push_back(msg);+ has_error_ = true;+ }++ // Get direct access to underlying StreamReader (use with caution)+ const StreamReader& stream() const { return stream_; }++private:+ StreamReader stream_;+ std::vector<std::string> errors_;+ bool has_error_;+};++} // namespace tinyexr++#endif // TINYEXR_EXR_READER_HH_diff --git a/third_party/tinyexr/streamreader.hh b/third_party/tinyexr/streamreader.hhnew file mode 100644index 00000000..3dbf278b--- /dev/null+++ b/third_party/tinyexr/streamreader.hh@@ -0,0 +1,171 @@+// SPDX-License-Identifier: BSD-3-Clause+// Copyright (c) 2025, Syoyo Fujita and many contributors.+// All rights reserved.+//+// StreamReader: Simple header-only stream reader with endian support+//+// Part of TinyEXR V2 API (EXPERIMENTAL)++#ifndef TINYEXR_STREAMREADER_HH_+#define TINYEXR_STREAMREADER_HH_++#include <cstdint>+#include <cstring>++namespace tinyexr {++enum class Endian {+ Little,+ Big,+ Native+};++class StreamReader {+public:+ // Constructor: takes memory address, length, and endianness+ StreamReader(const uint8_t* data, size_t length, Endian endian = Endian::Little)+ : data_(data), length_(length), pos_(0), endian_(endian) {+ // Detect native endian+ uint16_t test = 0x0001;+ native_is_little_ = (*reinterpret_cast<uint8_t*>(&test) == 0x01);++ // Determine if we need to swap bytes+ if (endian_ == Endian::Native) {+ needs_swap_ = false;+ } else {+ bool data_is_little = (endian_ == Endian::Little);+ needs_swap_ = (data_is_little != native_is_little_);+ }+ }++ // Read n bytes into destination buffer+ // Returns false on out-of-bounds or error+ bool read(size_t n, uint8_t* dst) {+ if (!dst || n == 0) {+ return false;+ }+ if (pos_ + n > length_) {+ return false; // Out of bounds+ }+ std::memcpy(dst, data_ + pos_, n);+ pos_ += n;+ return true;+ }++ // Read 1 byte (uint8_t)+ bool read1(uint8_t* dst) {+ return read(1, dst);+ }++ // Read 2 bytes (uint16_t) with endian swap if needed+ bool read2(uint16_t* dst) {+ if (!dst) {+ return false;+ }+ uint8_t buf[2];+ if (!read(2, buf)) {+ return false;+ }++ if (needs_swap_) {+ *dst = static_cast<uint16_t>(buf[1]) << 8 |+ static_cast<uint16_t>(buf[0]);+ } else {+ std::memcpy(dst, buf, 2);+ }+ return true;+ }++ // Read 4 bytes (uint32_t) with endian swap if needed+ bool read4(uint32_t* dst) {+ if (!dst) {+ return false;+ }+ uint8_t buf[4];+ if (!read(4, buf)) {+ return false;+ }++ if (needs_swap_) {+ *dst = static_cast<uint32_t>(buf[3]) << 24 |+ static_cast<uint32_t>(buf[2]) << 16 |+ static_cast<uint32_t>(buf[1]) << 8 |+ static_cast<uint32_t>(buf[0]);+ } else {+ std::memcpy(dst, buf, 4);+ }+ return true;+ }++ // Read 8 bytes (uint64_t) with endian swap if needed+ bool read8(uint64_t* dst) {+ if (!dst) {+ return false;+ }+ uint8_t buf[8];+ if (!read(8, buf)) {+ return false;+ }++ if (needs_swap_) {+ *dst = static_cast<uint64_t>(buf[7]) << 56 |+ static_cast<uint64_t>(buf[6]) << 48 |+ static_cast<uint64_t>(buf[5]) << 40 |+ static_cast<uint64_t>(buf[4]) << 32 |+ static_cast<uint64_t>(buf[3]) << 24 |+ static_cast<uint64_t>(buf[2]) << 16 |+ static_cast<uint64_t>(buf[1]) << 8 |+ static_cast<uint64_t>(buf[0]);+ } else {+ std::memcpy(dst, buf, 8);+ }+ return true;+ }++ // Seek to absolute position+ // Returns false if position is out of bounds+ bool seek(size_t pos) {+ if (pos > length_) {+ return false;+ }+ pos_ = pos;+ return true;+ }++ // Rewind to beginning+ void rewind() {+ pos_ = 0;+ }++ // Get current position+ size_t tell() const {+ return pos_;+ }++ // Get remaining bytes+ size_t remaining() const {+ return length_ - pos_;+ }++ // Check if at end+ bool eof() const {+ return pos_ >= length_;+ }++ // Get total length+ size_t length() const {+ return length_;+ }++private:+ const uint8_t* data_;+ size_t length_;+ size_t pos_;+ Endian endian_;+ bool native_is_little_;+ bool needs_swap_;+};++} // namespace tinyexr++#endif // TINYEXR_STREAMREADER_HH_diff --git a/third_party/tinyexr/tinyexr.h b/third_party/tinyexr/tinyexr.hnew file mode 100644index 00000000..dfd71649--- /dev/null+++ b/third_party/tinyexr/tinyexr.h@@ -0,0 +1,11345 @@+#ifndef TINYEXR_H_+#define TINYEXR_H_+/*+Copyright (c) 2014 - 2021, Syoyo Fujita and many contributors.+All rights reserved.++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are met:+ * Redistributions of source code must retain the above copyright+ notice, this list of conditions and the following disclaimer.+ * Redistributions in binary form must reproduce the above copyright+ notice, this list of conditions and the following disclaimer in the+ documentation and/or other materials provided with the distribution.+ * Neither the name of the Syoyo Fujita nor the+ names of its contributors may be used to endorse or promote products+ derived from this software without specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE+DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY+DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND+ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.+*/++// TinyEXR contains some OpenEXR code, which is licensed under ------------++///////////////////////////////////////////////////////////////////////////+//+// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas+// Digital Ltd. LLC+//+// All rights reserved.+//+// Redistribution and use in source and binary forms, with or without+// modification, are permitted provided that the following conditions are+// met:+// * Redistributions of source code must retain the above copyright+// notice, this list of conditions and the following disclaimer.+// * Redistributions in binary form must reproduce the above+// copyright notice, this list of conditions and the following disclaimer+// in the documentation and/or other materials provided with the+// distribution.+// * Neither the name of Industrial Light & Magic nor the names of+// its contributors may be used to endorse or promote products derived+// from this software without specific prior written permission.+//+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.+//+///////////////////////////////////////////////////////////////////////////++// End of OpenEXR license -------------------------------------------------+++//+//+// Do this:+// #define TINYEXR_IMPLEMENTATION+// before you include this file in *one* C or C++ file to create the+// implementation.+//+// // i.e. it should look like this:+// #include ...+// #include ...+// #include ...+// #define TINYEXR_IMPLEMENTATION+// #include "tinyexr.h"+//+//++#include <stddef.h> // for size_t+#include <stdint.h> // guess stdint.h is available(C99)++#ifdef __cplusplus+extern "C" {+#endif++#if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || \+ defined(__i386) || defined(__i486__) || defined(__i486) || \+ defined(i386) || defined(__ia64__) || defined(__x86_64__)+#define TINYEXR_X86_OR_X64_CPU 1+#else+#define TINYEXR_X86_OR_X64_CPU 0+#endif++#if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || TINYEXR_X86_OR_X64_CPU+#define TINYEXR_LITTLE_ENDIAN 1+#else+#define TINYEXR_LITTLE_ENDIAN 0+#endif++// Use miniz or not to decode ZIP format pixel. Linking with zlib+// required if this flag is 0 and TINYEXR_USE_STB_ZLIB is 0.+#ifndef TINYEXR_USE_MINIZ+#define TINYEXR_USE_MINIZ (1)+#endif++// Use the ZIP implementation of stb_image.h and stb_image_write.h.+#ifndef TINYEXR_USE_STB_ZLIB+#define TINYEXR_USE_STB_ZLIB (0)+#endif++// Use nanozlib.+#ifndef TINYEXR_USE_NANOZLIB+#define TINYEXR_USE_NANOZLIB (0)+#endif++// Disable PIZ compression when applying cpplint.+#ifndef TINYEXR_USE_PIZ+#define TINYEXR_USE_PIZ (1)+#endif++#ifndef TINYEXR_USE_ZFP+#define TINYEXR_USE_ZFP (0) // TinyEXR extension.+// http://computation.llnl.gov/projects/floating-point-compression+#endif++#ifndef TINYEXR_USE_THREAD+#define TINYEXR_USE_THREAD (0) // No threaded loading.+#else+// When using threading a reduced custom upperbound can be specified by setting TINYEXR_MAX_THREADS+#ifndef TINYEXR_MAX_THREADS // if not defined define it as 0 meaning upper limit is taken from hardware_concurrency()+#define TINYEXR_MAX_THREADS (0)+#endif+#endif++#ifndef TINYEXR_USE_OPENMP+#ifdef _OPENMP+#define TINYEXR_USE_OPENMP (1)+#else+#define TINYEXR_USE_OPENMP (0)+#endif+#endif++#ifndef TINYEXR_USE_COMPILER_FP16+#define TINYEXR_USE_COMPILER_FP16 (0)+#endif++#if TINYEXR_USE_COMPILER_FP16+#ifndef _MSC_VER+#if defined( __GNUC__ ) || defined( __clang__ )+#if defined( __SSE2__ )+#if ( __GNUC__ > 11 ) || ( __clang_major__ > 14 )+#ifndef __STDC_WANT_IEC_60559_TYPES_EXT__+#define __STDC_WANT_IEC_60559_TYPES_EXT__+#endif+#include <float.h>+#include <math.h>+#define TINYEXR_FP16_COMPILER_TYPE _Float16+#endif+#endif+#if defined( __ARM_NEON__ ) || defined( __ARM_NEON )+#define TINYEXR_FP16_COMPILER_TYPE __fp16+#endif+#endif+#else+#if (defined(_M_IX86) || defined(_M_X64)) && defined(__AVX2__)+#include <intrin.h>+#define TINYEXR_FP16_COMPILER_TYPE uint16_t+#endif+#endif+#endif++#ifdef TINYEXR_FP16_COMPILER_TYPE+#define TINYEXR_HAS_FP16_COMPILER_TYPE (1)+#else+#define TINYEXR_HAS_FP16_COMPILER_TYPE (0)+#endif++#define TINYEXR_SUCCESS (0)+#define TINYEXR_ERROR_INVALID_MAGIC_NUMBER (-1)+#define TINYEXR_ERROR_INVALID_EXR_VERSION (-2)+#define TINYEXR_ERROR_INVALID_ARGUMENT (-3)+#define TINYEXR_ERROR_INVALID_DATA (-4)+#define TINYEXR_ERROR_INVALID_FILE (-5)+#define TINYEXR_ERROR_INVALID_PARAMETER (-6)+#define TINYEXR_ERROR_CANT_OPEN_FILE (-7)+#define TINYEXR_ERROR_UNSUPPORTED_FORMAT (-8)+#define TINYEXR_ERROR_INVALID_HEADER (-9)+#define TINYEXR_ERROR_UNSUPPORTED_FEATURE (-10)+#define TINYEXR_ERROR_CANT_WRITE_FILE (-11)+#define TINYEXR_ERROR_SERIALIZATION_FAILED (-12)+#define TINYEXR_ERROR_LAYER_NOT_FOUND (-13)+#define TINYEXR_ERROR_DATA_TOO_LARGE (-14)++// @note { OpenEXR file format: http://www.openexr.com/openexrfilelayout.pdf }++// pixel type: possible values are: UINT = 0 HALF = 1 FLOAT = 2+#define TINYEXR_PIXELTYPE_UINT (0)+#define TINYEXR_PIXELTYPE_HALF (1)+#define TINYEXR_PIXELTYPE_FLOAT (2)++#define TINYEXR_MAX_HEADER_ATTRIBUTES (1024)+#define TINYEXR_MAX_CUSTOM_ATTRIBUTES (128)++#define TINYEXR_COMPRESSIONTYPE_NONE (0)+#define TINYEXR_COMPRESSIONTYPE_RLE (1)+#define TINYEXR_COMPRESSIONTYPE_ZIPS (2)+#define TINYEXR_COMPRESSIONTYPE_ZIP (3)+#define TINYEXR_COMPRESSIONTYPE_PIZ (4)+#define TINYEXR_COMPRESSIONTYPE_PXR24 (5)+#define TINYEXR_COMPRESSIONTYPE_B44 (6)+#define TINYEXR_COMPRESSIONTYPE_B44A (7)+#define TINYEXR_COMPRESSIONTYPE_DWAA (8) // Not yet supported+#define TINYEXR_COMPRESSIONTYPE_DWAB (9) // Not yet supported+#define TINYEXR_COMPRESSIONTYPE_ZFP (128) // TinyEXR extension++#define TINYEXR_ZFP_COMPRESSIONTYPE_RATE (0)+#define TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION (1)+#define TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY (2)++#define TINYEXR_TILE_ONE_LEVEL (0)+#define TINYEXR_TILE_MIPMAP_LEVELS (1)+#define TINYEXR_TILE_RIPMAP_LEVELS (2)++#define TINYEXR_TILE_ROUND_DOWN (0)+#define TINYEXR_TILE_ROUND_UP (1)++// Spectral EXR types (based on JCGT 2021 paper and spectral-exr format)+// https://jcgt.org/published/0010/03/01/+#define TINYEXR_SPECTRUM_REFLECTIVE (0) // T.{wavelength}nm channels+#define TINYEXR_SPECTRUM_EMISSIVE (1) // S0.{wavelength}nm channels+#define TINYEXR_SPECTRUM_POLARISED (2) // S0-S3.{wavelength}nm channels++typedef struct TEXRVersion {+ int version; // this must be 2+ // tile format image;+ // not zero for only a single-part "normal" tiled file (according to spec.)+ int tiled;+ int long_name; // long name attribute+ // deep image(EXR 2.0);+ // for a multi-part file, indicates that at least one part is of type deep* (according to spec.)+ int non_image;+ int multipart; // multi-part(EXR 2.0)+} EXRVersion;++typedef struct TEXRAttribute {+ char name[256]; // name and type are up to 255 chars long.+ char type[256];+ unsigned char *value; // uint8_t*+ int size;+ int pad0;+} EXRAttribute;++typedef struct TEXRChannelInfo {+ char name[256]; // less than 255 bytes long+ int pixel_type;+ int x_sampling;+ int y_sampling;+ unsigned char p_linear;+ unsigned char pad[3];+} EXRChannelInfo;++typedef struct TEXRTile {+ int offset_x;+ int offset_y;+ int level_x;+ int level_y;++ int width; // actual width in a tile.+ int height; // actual height int a tile.++ unsigned char **images; // image[channels][pixels]+} EXRTile;++typedef struct TEXRBox2i {+ int min_x;+ int min_y;+ int max_x;+ int max_y;+} EXRBox2i;++typedef struct TEXRHeader {+ float pixel_aspect_ratio;+ int line_order;+ EXRBox2i data_window;+ EXRBox2i display_window;+ float screen_window_center[2];+ float screen_window_width;++ int chunk_count;++ // Properties for tiled format(`tiledesc`).+ int tiled;+ int tile_size_x;+ int tile_size_y;+ int tile_level_mode;+ int tile_rounding_mode;++ int long_name;+ // for a single-part file, agree with the version field bit 11+ // for a multi-part file, it is consistent with the type of part+ int non_image;+ int multipart;+ unsigned int header_len;++ // Custom attributes(exludes required attributes(e.g. `channels`,+ // `compression`, etc)+ int num_custom_attributes;+ EXRAttribute *custom_attributes; // array of EXRAttribute. size =+ // `num_custom_attributes`.++ EXRChannelInfo *channels; // [num_channels]++ int *pixel_types; // Loaded pixel type(TINYEXR_PIXELTYPE_*) of `images` for+ // each channel. This is overwritten with `requested_pixel_types` when+ // loading.+ int num_channels;++ int compression_type; // compression type(TINYEXR_COMPRESSIONTYPE_*)+ int *requested_pixel_types; // Filled initially by+ // ParseEXRHeaderFrom(Meomory|File), then users+ // can edit it(only valid for HALF pixel type+ // channel)+ // name attribute required for multipart files;+ // must be unique and non empty (according to spec.);+ // use EXRSetNameAttr for setting value;+ // max 255 character allowed - excluding terminating zero+ char name[256];+} EXRHeader;++typedef struct TEXRMultiPartHeader {+ int num_headers;+ EXRHeader *headers;++} EXRMultiPartHeader;++typedef struct TEXRImage {+ EXRTile *tiles; // Tiled pixel data. The application must reconstruct image+ // from tiles manually. NULL if scanline format.+ struct TEXRImage* next_level; // NULL if scanline format or image is the last level.+ int level_x; // x level index+ int level_y; // y level index++ unsigned char **images; // image[channels][pixels]. NULL if tiled format.++ int width;+ int height;+ int num_channels;++ // Properties for tile format.+ int num_tiles;++} EXRImage;++typedef struct TEXRMultiPartImage {+ int num_images;+ EXRImage *images;++} EXRMultiPartImage;++typedef struct TDeepImage {+ const char **channel_names;+ float ***image; // image[channels][scanlines][samples]+ int **offset_table; // offset_table[scanline][offsets]+ int num_channels;+ int width;+ int height;+ int pad0;+} DeepImage;++// @deprecated { For backward compatibility. Not recommended to use. }+// Loads single-frame OpenEXR image. Assume EXR image contains A(single channel+// alpha) or RGB(A) channels.+// Application must free image data as returned by `out_rgba`+// Result image format is: float x RGBA x width x hight+// Returns negative value and may set error string in `err` when there's an+// error+extern int LoadEXR(float **out_rgba, int *width, int *height,+ const char *filename, const char **err);++// Loads single-frame OpenEXR image by specifying layer name. Assume EXR image+// contains A(single channel alpha) or RGB(A) channels. Application must free+// image data as returned by `out_rgba` Result image format is: float x RGBA x+// width x hight Returns negative value and may set error string in `err` when+// there's an error When the specified layer name is not found in the EXR file,+// the function will return `TINYEXR_ERROR_LAYER_NOT_FOUND`.+extern int LoadEXRWithLayer(float **out_rgba, int *width, int *height,+ const char *filename, const char *layer_name,+ const char **err);++//+// Get layer infos from EXR file.+//+// @param[out] layer_names List of layer names. Application must free memory+// after using this.+// @param[out] num_layers The number of layers+// @param[out] err Error string(will be filled when the function returns error+// code). Free it using FreeEXRErrorMessage after using this value.+//+// @return TINYEXR_SUCCEES upon success.+//+extern int EXRLayers(const char *filename, const char **layer_names[],+ int *num_layers, const char **err);++// @deprecated+// Simple wrapper API for ParseEXRHeaderFromFile.+// checking given file is a EXR file(by just look up header)+// @return TINYEXR_SUCCEES for EXR image, TINYEXR_ERROR_INVALID_HEADER for+// others+extern int IsEXR(const char *filename);++// Simple wrapper API for ParseEXRHeaderFromMemory.+// Check if given data is a EXR image(by just looking up a header section)+// @return TINYEXR_SUCCEES for EXR image, TINYEXR_ERROR_INVALID_HEADER for+// others+extern int IsEXRFromMemory(const unsigned char *memory, size_t size);++// @deprecated+// Saves single-frame OpenEXR image to a buffer. Assume EXR image contains RGB(A) channels.+// components must be 1(Grayscale), 3(RGB) or 4(RGBA).+// Input image format is: `float x width x height`, or `float x RGB(A) x width x+// hight`+// Save image as fp16(HALF) format when `save_as_fp16` is positive non-zero+// value.+// Save image as fp32(FLOAT) format when `save_as_fp16` is 0.+// Use ZIP compression by default.+// `buffer` is the pointer to write EXR data.+// Memory for `buffer` is allocated internally in SaveEXRToMemory.+// Returns the data size of EXR file when the value is positive(up to 2GB EXR data).+// Returns negative value and may set error string in `err` when there's an+// error+extern int SaveEXRToMemory(const float *data, const int width, const int height,+ const int components, const int save_as_fp16,+ unsigned char **buffer, const char **err);++// @deprecated { Not recommended, but handy to use. }+// Saves single-frame OpenEXR image to a buffer. Assume EXR image contains RGB(A) channels.+// components must be 1(Grayscale), 3(RGB) or 4(RGBA).+// Input image format is: `float x width x height`, or `float x RGB(A) x width x+// hight`+// Save image as fp16(HALF) format when `save_as_fp16` is positive non-zero+// value.+// Save image as fp32(FLOAT) format when `save_as_fp16` is 0.+// Use ZIP compression by default.+// Returns TINYEXR_SUCCEES(0) when success.+// Returns negative value and may set error string in `err` when there's an+// error+extern int SaveEXR(const float *data, const int width, const int height,+ const int components, const int save_as_fp16,+ const char *filename, const char **err);++// Returns the number of resolution levels of the image (including the base)+extern int EXRNumLevels(const EXRImage* exr_image);++// Initialize EXRHeader struct+extern void InitEXRHeader(EXRHeader *exr_header);++// Set name attribute of EXRHeader struct (it makes a copy)+extern void EXRSetNameAttr(EXRHeader *exr_header, const char* name);++// Initialize EXRImage struct+extern void InitEXRImage(EXRImage *exr_image);++// Frees internal data of EXRHeader struct+extern int FreeEXRHeader(EXRHeader *exr_header);++// Frees internal data of EXRImage struct+extern int FreeEXRImage(EXRImage *exr_image);++// Frees error message+extern void FreeEXRErrorMessage(const char *msg);++// Parse EXR version header of a file.+extern int ParseEXRVersionFromFile(EXRVersion *version, const char *filename);++// Parse EXR version header from memory-mapped EXR data.+extern int ParseEXRVersionFromMemory(EXRVersion *version,+ const unsigned char *memory, size_t size);++// Parse single-part OpenEXR header from a file and initialize `EXRHeader`.+// When there was an error message, Application must free `err` with+// FreeEXRErrorMessage()+extern int ParseEXRHeaderFromFile(EXRHeader *header, const EXRVersion *version,+ const char *filename, const char **err);++// Parse single-part OpenEXR header from a memory and initialize `EXRHeader`.+// When there was an error message, Application must free `err` with+// FreeEXRErrorMessage()+extern int ParseEXRHeaderFromMemory(EXRHeader *header,+ const EXRVersion *version,+ const unsigned char *memory, size_t size,+ const char **err);++// Parse multi-part OpenEXR headers from a file and initialize `EXRHeader*`+// array.+// When there was an error message, Application must free `err` with+// FreeEXRErrorMessage()+extern int ParseEXRMultipartHeaderFromFile(EXRHeader ***headers,+ int *num_headers,+ const EXRVersion *version,+ const char *filename,+ const char **err);++// Parse multi-part OpenEXR headers from a memory and initialize `EXRHeader*`+// array+// When there was an error message, Application must free `err` with+// FreeEXRErrorMessage()+extern int ParseEXRMultipartHeaderFromMemory(EXRHeader ***headers,+ int *num_headers,+ const EXRVersion *version,+ const unsigned char *memory,+ size_t size, const char **err);++// Loads single-part OpenEXR image from a file.+// Application must setup `ParseEXRHeaderFromFile` before calling this function.+// Application can free EXRImage using `FreeEXRImage`+// Returns negative value and may set error string in `err` when there's an+// error+// When there was an error message, Application must free `err` with+// FreeEXRErrorMessage()+extern int LoadEXRImageFromFile(EXRImage *image, const EXRHeader *header,+ const char *filename, const char **err);++// Loads single-part OpenEXR image from a memory.+// Application must setup `EXRHeader` with+// `ParseEXRHeaderFromMemory` before calling this function.+// Application can free EXRImage using `FreeEXRImage`+// Returns negative value and may set error string in `err` when there's an+// error+// When there was an error message, Application must free `err` with+// FreeEXRErrorMessage()+extern int LoadEXRImageFromMemory(EXRImage *image, const EXRHeader *header,+ const unsigned char *memory,+ const size_t size, const char **err);++// Loads multi-part OpenEXR image from a file.+// Application must setup `ParseEXRMultipartHeaderFromFile` before calling this+// function.+// Application can free EXRImage using `FreeEXRImage`+// Returns negative value and may set error string in `err` when there's an+// error+// When there was an error message, Application must free `err` with+// FreeEXRErrorMessage()+extern int LoadEXRMultipartImageFromFile(EXRImage *images,+ const EXRHeader **headers,+ unsigned int num_parts,+ const char *filename,+ const char **err);++// Loads multi-part OpenEXR image from a memory.+// Application must setup `EXRHeader*` array with+// `ParseEXRMultipartHeaderFromMemory` before calling this function.+// Application can free EXRImage using `FreeEXRImage`+// Returns negative value and may set error string in `err` when there's an+// error+// When there was an error message, Application must free `err` with+// FreeEXRErrorMessage()+extern int LoadEXRMultipartImageFromMemory(EXRImage *images,+ const EXRHeader **headers,+ unsigned int num_parts,+ const unsigned char *memory,+ const size_t size, const char **err);++// Saves multi-channel, single-frame OpenEXR image to a file.+// Returns negative value and may set error string in `err` when there's an+// error+// When there was an error message, Application must free `err` with+// FreeEXRErrorMessage()+extern int SaveEXRImageToFile(const EXRImage *image,+ const EXRHeader *exr_header, const char *filename,+ const char **err);++// Saves multi-channel, single-frame OpenEXR image to a memory.+// Image is compressed using EXRImage.compression value.+// Return the number of bytes if success.+// Return zero and will set error string in `err` when there's an+// error.+// When there was an error message, Application must free `err` with+// FreeEXRErrorMessage()+extern size_t SaveEXRImageToMemory(const EXRImage *image,+ const EXRHeader *exr_header,+ unsigned char **memory, const char **err);++// Saves multi-channel, multi-frame OpenEXR image to a memory.+// Image is compressed using EXRImage.compression value.+// File global attributes (eg. display_window) must be set in the first header.+// Returns negative value and may set error string in `err` when there's an+// error+// When there was an error message, Application must free `err` with+// FreeEXRErrorMessage()+extern int SaveEXRMultipartImageToFile(const EXRImage *images,+ const EXRHeader **exr_headers,+ unsigned int num_parts,+ const char *filename, const char **err);++// Saves multi-channel, multi-frame OpenEXR image to a memory.+// Image is compressed using EXRImage.compression value.+// File global attributes (eg. display_window) must be set in the first header.+// Return the number of bytes if success.+// Return zero and will set error string in `err` when there's an+// error.+// When there was an error message, Application must free `err` with+// FreeEXRErrorMessage()+extern size_t SaveEXRMultipartImageToMemory(const EXRImage *images,+ const EXRHeader **exr_headers,+ unsigned int num_parts,+ unsigned char **memory, const char **err);+// Loads single-frame OpenEXR deep image.+// Application must free memory of variables in DeepImage(image, offset_table)+// Returns negative value and may set error string in `err` when there's an+// error+// When there was an error message, Application must free `err` with+// FreeEXRErrorMessage()+extern int LoadDeepEXR(DeepImage *out_image, const char *filename,+ const char **err);++// NOT YET IMPLEMENTED:+// Saves single-frame OpenEXR deep image.+// Returns negative value and may set error string in `err` when there's an+// error+// extern int SaveDeepEXR(const DeepImage *in_image, const char *filename,+// const char **err);++// NOT YET IMPLEMENTED:+// Loads multi-part OpenEXR deep image.+// Application must free memory of variables in DeepImage(image, offset_table)+// extern int LoadMultiPartDeepEXR(DeepImage **out_image, int num_parts, const+// char *filename,+// const char **err);++// For emscripten.+// Loads single-frame OpenEXR image from memory. Assume EXR image contains+// RGB(A) channels.+// Returns negative value and may set error string in `err` when there's an+// error+// When there was an error message, Application must free `err` with+// FreeEXRErrorMessage()+extern int LoadEXRFromMemory(float **out_rgba, int *width, int *height,+ const unsigned char *memory, size_t size,+ const char **err);++// Spectral EXR API (based on JCGT 2021 paper and spectral-exr format)+// https://jcgt.org/published/0010/03/01/+// https://github.com/afichet/spectral-exr++// Check if an EXR file contains spectral data (has spectralLayoutVersion attribute)+// Returns TINYEXR_SUCCESS if spectral, TINYEXR_ERROR_INVALID_DATA if not+extern int IsSpectralEXR(const char *filename);+extern int IsSpectralEXRFromMemory(const unsigned char *memory, size_t size);++// Get spectrum type from EXR header (TINYEXR_SPECTRUM_REFLECTIVE/EMISSIVE/POLARISED)+// Returns spectrum type, or -1 if not a spectral EXR+extern int EXRGetSpectrumType(const EXRHeader *exr_header);++// Format wavelength with European decimal convention (comma as separator)+// Output format: "550,000000" for 550.0nm+// buffer must be at least 32 bytes+extern void EXRFormatWavelength(char *buffer, size_t buffer_size, float wavelength_nm);++// Create spectral channel name+// For emissive: "S{stokes}.{wavelength}nm" (e.g., "S0.550,000000nm")+// For reflective: "T.{wavelength}nm" (e.g., "T.550,000000nm")+// buffer must be at least 64 bytes+extern void EXRSpectralChannelName(char *buffer, size_t buffer_size,+ float wavelength_nm, int stokes_component);+extern void EXRReflectiveChannelName(char *buffer, size_t buffer_size,+ float wavelength_nm);++// Parse wavelength from spectral channel name+// Returns wavelength in nm, or -1.0 if not a valid spectral channel name+extern float EXRParseSpectralChannelWavelength(const char *channel_name);++// Get Stokes component from channel name (0-3, or -1 if not polarised/invalid)+extern int EXRGetStokesComponent(const char *channel_name);++// Check if channel name is a spectral channel (S{n}.{wavelength}nm or T.{wavelength}nm)+extern int EXRIsSpectralChannel(const char *channel_name);++// Get wavelengths from EXR header channels+// Returns number of unique wavelengths found+// wavelengths array must be pre-allocated, max_wavelengths is its size+extern int EXRGetWavelengths(const EXRHeader *exr_header,+ float *wavelengths, int max_wavelengths);++// Helper to add spectral attributes to an EXRHeader+// This sets spectralLayoutVersion and ROOT/units (or emissiveUnits for emissive)+// spectrum_type: TINYEXR_SPECTRUM_REFLECTIVE, EMISSIVE, or POLARISED+// units: unit string (e.g., "W.m^-2.sr^-1.nm^-1" for radiance)+extern int EXRSetSpectralAttributes(EXRHeader *exr_header,+ int spectrum_type,+ const char *units);++// Get spectral units from EXR header+// Returns NULL if not found, otherwise pointer to units string (valid until header is freed)+extern const char* EXRGetSpectralUnits(const EXRHeader *exr_header);++#ifdef __cplusplus+}+#endif++#endif // TINYEXR_H_++#ifdef TINYEXR_IMPLEMENTATION+#ifndef TINYEXR_IMPLEMENTATION_DEFINED+#define TINYEXR_IMPLEMENTATION_DEFINED++#ifdef _WIN32++#ifndef WIN32_LEAN_AND_MEAN+#define WIN32_LEAN_AND_MEAN+#endif+#ifndef NOMINMAX+#define NOMINMAX+#endif+#include <windows.h> // for UTF-8 and memory-mapping++#if !defined(WINAPI_FAMILY) || (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP)+#define TINYEXR_USE_WIN32_MMAP (1)+#endif++#elif defined(__linux__) || defined(__unix__)+#include <fcntl.h> // for open()+#include <sys/mman.h> // for memory-mapping+#include <sys/stat.h> // for stat+#include <unistd.h> // for close()+#define TINYEXR_USE_POSIX_MMAP (1)+#endif++#include <algorithm>+#include <cmath>+#include <cstdio>+#include <cstdlib>+#include <cstring>+#include <sstream>++//#include <iostream> // debug++#include <limits>+#include <string>+#include <vector>+#include <set>++// Include Reader class with error stack for safer memory reading+#include "exr_reader.hh"++// https://stackoverflow.com/questions/5047971/how-do-i-check-for-c11-support+#if __cplusplus > 199711L || (defined(_MSC_VER) && _MSC_VER >= 1900)+#define TINYEXR_HAS_CXX11 (1)+// C++11+#include <cstdint>++#if TINYEXR_USE_THREAD+#include <atomic>+#include <thread>+#endif++#else // __cplusplus > 199711L+#define TINYEXR_HAS_CXX11 (0)+#endif // __cplusplus > 199711L++#if TINYEXR_USE_OPENMP+#include <omp.h>+#endif++#if defined(TINYEXR_USE_MINIZ) && (TINYEXR_USE_MINIZ==1)+#include <miniz.h>+#else+// Issue #46. Please include your own zlib-compatible API header before+// including `tinyexr.h`+//#include "zlib.h"+#endif++#if defined(TINYEXR_USE_NANOZLIB) && (TINYEXR_USE_NANOZLIB==1)+#define NANOZLIB_IMPLEMENTATION+#include "nanozlib.h"+#endif++#if TINYEXR_USE_STB_ZLIB+// Since we don't know where a project has stb_image.h and stb_image_write.h+// and whether they are in the include path, we don't include them here, and+// instead declare the two relevant functions manually.+// from stb_image.h:+extern "C" int stbi_zlib_decode_buffer(char *obuffer, int olen, const char *ibuffer, int ilen);+// from stb_image_write.h:+extern "C" unsigned char *stbi_zlib_compress(unsigned char *data, int data_len, int *out_len, int quality);+#endif+++#if TINYEXR_USE_ZFP++#ifdef __clang__+#pragma clang diagnostic push+#pragma clang diagnostic ignored "-Weverything"+#endif++#include "zfp.h"++#ifdef __clang__+#pragma clang diagnostic pop+#endif++#endif++// cond: conditional expression+// msg: std::string+// err: std::string*+#define TINYEXR_CHECK_AND_RETURN_MSG(cond, msg, err) do { \+ if (!(cond)) { \+ if (!err) { \+ std::ostringstream ss_e; \+ ss_e << __func__ << "():" << __LINE__ << msg << "\n"; \+ (*err) += ss_e.str(); \+ } \+ return false;\+ } \+ } while(0)++// no error message.+#define TINYEXR_CHECK_AND_RETURN_C(cond, retcode) do { \+ if (!(cond)) { \+ return retcode; \+ } \+ } while(0)++namespace tinyexr {++#if __cplusplus > 199711L+// C++11+typedef uint64_t tinyexr_uint64;+typedef int64_t tinyexr_int64;+#else+// Although `long long` is not a standard type pre C++11, assume it is defined+// as a compiler's extension.+#ifdef __clang__+#pragma clang diagnostic push+#pragma clang diagnostic ignored "-Wc++11-long-long"+#endif+typedef unsigned long long tinyexr_uint64;+typedef long long tinyexr_int64;+#ifdef __clang__+#pragma clang diagnostic pop+#endif+#endif++// static bool IsBigEndian(void) {+// union {+// unsigned int i;+// char c[4];+// } bint = {0x01020304};+//+// return bint.c[0] == 1;+//}++static void SetErrorMessage(const std::string &msg, const char **err) {+ if (err) {+#ifdef _WIN32+ (*err) = _strdup(msg.c_str());+#else+ (*err) = strdup(msg.c_str());+#endif+ }+}++#if 0+static void SetWarningMessage(const std::string &msg, const char **warn) {+ if (warn) {+#ifdef _WIN32+ (*warn) = _strdup(msg.c_str());+#else+ (*warn) = strdup(msg.c_str());+#endif+ }+}+#endif++static const int kEXRVersionSize = 8;++static void inline cpy2(unsigned short *dst_val, const unsigned short *src_val) {+ unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val);+ const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val);++ dst[0] = src[0];+ dst[1] = src[1];+}++static void inline swap2(unsigned short *val) {+#if TINYEXR_LITTLE_ENDIAN+ (void)val;+#else+ unsigned short tmp = *val;+ unsigned char *dst = reinterpret_cast<unsigned char *>(val);+ unsigned char *src = reinterpret_cast<unsigned char *>(&tmp);++ dst[0] = src[1];+ dst[1] = src[0];+#endif+}++#ifdef __clang__+#pragma clang diagnostic push+#pragma clang diagnostic ignored "-Wunused-function"+#endif++#ifdef __GNUC__+#pragma GCC diagnostic push+#pragma GCC diagnostic ignored "-Wunused-function"+#endif+static void inline cpy4(int *dst_val, const int *src_val) {+ unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val);+ const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val);++ dst[0] = src[0];+ dst[1] = src[1];+ dst[2] = src[2];+ dst[3] = src[3];+}++static void inline cpy4(unsigned int *dst_val, const unsigned int *src_val) {+ unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val);+ const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val);++ dst[0] = src[0];+ dst[1] = src[1];+ dst[2] = src[2];+ dst[3] = src[3];+}++static void inline cpy4(float *dst_val, const float *src_val) {+ unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val);+ const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val);++ dst[0] = src[0];+ dst[1] = src[1];+ dst[2] = src[2];+ dst[3] = src[3];+}+#ifdef __clang__+#pragma clang diagnostic pop+#endif++#ifdef __GNUC__+#pragma GCC diagnostic pop+#endif++static void inline swap4(unsigned int *val) {+#if TINYEXR_LITTLE_ENDIAN+ (void)val;+#else+ unsigned int tmp = *val;+ unsigned char *dst = reinterpret_cast<unsigned char *>(val);+ unsigned char *src = reinterpret_cast<unsigned char *>(&tmp);++ dst[0] = src[3];+ dst[1] = src[2];+ dst[2] = src[1];+ dst[3] = src[0];+#endif+}++static void inline swap4(int *val) {+#if TINYEXR_LITTLE_ENDIAN+ (void)val;+#else+ int tmp = *val;+ unsigned char *dst = reinterpret_cast<unsigned char *>(val);+ unsigned char *src = reinterpret_cast<unsigned char *>(&tmp);++ dst[0] = src[3];+ dst[1] = src[2];+ dst[2] = src[1];+ dst[3] = src[0];+#endif+}++static void inline swap4(float *val) {+#if TINYEXR_LITTLE_ENDIAN+ (void)val;+#else+ float tmp = *val;+ unsigned char *dst = reinterpret_cast<unsigned char *>(val);+ unsigned char *src = reinterpret_cast<unsigned char *>(&tmp);++ dst[0] = src[3];+ dst[1] = src[2];+ dst[2] = src[1];+ dst[3] = src[0];+#endif+}++#if 0+static void inline cpy8(tinyexr::tinyexr_uint64 *dst_val, const tinyexr::tinyexr_uint64 *src_val) {+ unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val);+ const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val);++ dst[0] = src[0];+ dst[1] = src[1];+ dst[2] = src[2];+ dst[3] = src[3];+ dst[4] = src[4];+ dst[5] = src[5];+ dst[6] = src[6];+ dst[7] = src[7];+}+#endif++static void inline swap8(tinyexr::tinyexr_uint64 *val) {+#if TINYEXR_LITTLE_ENDIAN+ (void)val;+#else+ tinyexr::tinyexr_uint64 tmp = (*val);+ unsigned char *dst = reinterpret_cast<unsigned char *>(val);+ unsigned char *src = reinterpret_cast<unsigned char *>(&tmp);++ dst[0] = src[7];+ dst[1] = src[6];+ dst[2] = src[5];+ dst[3] = src[4];+ dst[4] = src[3];+ dst[5] = src[2];+ dst[6] = src[1];+ dst[7] = src[0];+#endif+}++// https://gist.github.com/rygorous/2156668+#if TINYEXR_HAS_FP16_COMPILER_TYPE && (TINYEXR_USE_COMPILER_FP16 > 0)+union FP32 {+ float f;+};+#else+union FP32 {+ unsigned int u;+ float f;+ struct {+#if TINYEXR_LITTLE_ENDIAN+ unsigned int Mantissa : 23;+ unsigned int Exponent : 8;+ unsigned int Sign : 1;+#else+ unsigned int Sign : 1;+ unsigned int Exponent : 8;+ unsigned int Mantissa : 23;+#endif+ } s;+};+#endif++#ifdef __clang__+#pragma clang diagnostic push+#pragma clang diagnostic ignored "-Wpadded"+#endif++#if TINYEXR_HAS_FP16_COMPILER_TYPE && (TINYEXR_USE_COMPILER_FP16 > 0)+union FP16 {+ TINYEXR_FP16_COMPILER_TYPE f;+ unsigned short u;+};++#else++union FP16 {+ unsigned short u;+ struct {+#if TINYEXR_LITTLE_ENDIAN+ unsigned int Mantissa : 10;+ unsigned int Exponent : 5;+ unsigned int Sign : 1;+#else+ unsigned int Sign : 1;+ unsigned int Exponent : 5;+ unsigned int Mantissa : 10;+#endif+ } s;+};+#endif++#ifdef __clang__+#pragma clang diagnostic pop+#endif++#if TINYEXR_HAS_FP16_COMPILER_TYPE && (TINYEXR_USE_COMPILER_FP16 > 0)+static inline FP32 half_to_float(FP16 h) {+ FP32 o;+#if defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64)) && defined(__AVX2__)+ o.f =_mm_cvtss_f32(_mm_cvtph_ps(_mm_cvtsi32_si128(static_cast<int> (h.u))));+#else+ o.f = static_cast<float> (h.f);+#endif+ return o;+}+static inline FP16 float_to_half_full(FP32 f) {+ FP16 o;+#if defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64)) && defined(__AVX2__)+ o.f = static_cast<TINYEXR_FP16_COMPILER_TYPE> (_mm_cvtsi128_si32(_mm_cvtps_ph(_mm_set_ss(f.f), _MM_FROUND_CUR_DIRECTION)));+#else+ o.f = static_cast<TINYEXR_FP16_COMPILER_TYPE> (f.f);+#endif+ return o;+}+#else+static FP32 half_to_float(FP16 h) {+ static const FP32 magic = {113 << 23};+ static const unsigned int shifted_exp = 0x7c00+ << 13; // exponent mask after shift+ FP32 o;++ o.u = (h.u & 0x7fffU) << 13U; // exponent/mantissa bits+ unsigned int exp_ = shifted_exp & o.u; // just the exponent+ o.u += (127 - 15) << 23; // exponent adjust++ // handle exponent special cases+ if (exp_ == shifted_exp) // Inf/NaN?+ o.u += (128 - 16) << 23; // extra exp adjust+ else if (exp_ == 0) // Zero/Denormal?+ {+ o.u += 1 << 23; // extra exp adjust+ o.f -= magic.f; // renormalize+ }++ o.u |= (h.u & 0x8000U) << 16U; // sign bit+ return o;+}++static FP16 float_to_half_full(FP32 f) {+ FP16 o = {0};++ // Based on ISPC reference code (with minor modifications)+ if (f.s.Exponent == 0) // Signed zero/denormal (which will underflow)+ o.s.Exponent = 0;+ else if (f.s.Exponent == 255) // Inf or NaN (all exponent bits set)+ {+ o.s.Exponent = 31;+ o.s.Mantissa = f.s.Mantissa ? 0x200 : 0; // NaN->qNaN and Inf->Inf+ } else // Normalized number+ {+ // Exponent unbias the single, then bias the halfp+ int newexp = f.s.Exponent - 127 + 15;+ if (newexp >= 31) // Overflow, return signed infinity+ o.s.Exponent = 31;+ else if (newexp <= 0) // Underflow+ {+ if ((14 - newexp) <= 24) // Mantissa might be non-zero+ {+ unsigned int mant = f.s.Mantissa | 0x800000; // Hidden 1 bit+ o.s.Mantissa = mant >> (14 - newexp);+ if ((mant >> (13 - newexp)) & 1) // Check for rounding+ o.u++; // Round, might overflow into exp bit, but this is OK+ }+ } else {+ o.s.Exponent = static_cast<unsigned int>(newexp);+ o.s.Mantissa = f.s.Mantissa >> 13;+ if (f.s.Mantissa & 0x1000) // Check for rounding+ o.u++; // Round, might overflow to inf, this is OK+ }+ }++ o.s.Sign = f.s.Sign;+ return o;+}+#endif+// NOTE: From OpenEXR code+// #define IMF_INCREASING_Y 0+// #define IMF_DECREASING_Y 1+// #define IMF_RAMDOM_Y 2+//+// #define IMF_NO_COMPRESSION 0+// #define IMF_RLE_COMPRESSION 1+// #define IMF_ZIPS_COMPRESSION 2+// #define IMF_ZIP_COMPRESSION 3+// #define IMF_PIZ_COMPRESSION 4+// #define IMF_PXR24_COMPRESSION 5+// #define IMF_B44_COMPRESSION 6+// #define IMF_B44A_COMPRESSION 7++#ifdef __clang__+#pragma clang diagnostic push++#if __has_warning("-Wzero-as-null-pointer-constant")+#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"+#endif++#endif++static const char *ReadString(std::string *s, const char *ptr, size_t len) {+ // Read untile NULL(\0).+ const char *p = ptr;+ const char *q = ptr;+ while ((size_t(q - ptr) < len) && (*q) != 0) {+ q++;+ }++ if (size_t(q - ptr) >= len) {+ (*s).clear();+ return NULL;+ }++ (*s) = std::string(p, q);++ return q + 1; // skip '\0'+}++static bool ReadAttribute(std::string *name, std::string *type,+ std::vector<unsigned char> *data, size_t *marker_size,+ const char *marker, size_t size) {+ size_t name_len = strnlen(marker, size);+ if (name_len == size) {+ // String does not have a terminating character.+ return false;+ }+ *name = std::string(marker, name_len);++ marker += name_len + 1;+ size -= name_len + 1;++ size_t type_len = strnlen(marker, size);+ if (type_len == size) {+ return false;+ }+ *type = std::string(marker, type_len);++ marker += type_len + 1;+ size -= type_len + 1;++ if (size < sizeof(uint32_t)) {+ return false;+ }++ uint32_t data_len;+ memcpy(&data_len, marker, sizeof(uint32_t));+ tinyexr::swap4(reinterpret_cast<unsigned int *>(&data_len));++ if (data_len == 0) {+ if ((*type).compare("string") == 0) {+ // Accept empty string attribute.++ marker += sizeof(uint32_t);+ size -= sizeof(uint32_t);++ *marker_size = name_len + 1 + type_len + 1 + sizeof(uint32_t);++ data->resize(1);+ (*data)[0] = '\0';++ return true;+ } else {+ return false;+ }+ }++ marker += sizeof(uint32_t);+ size -= sizeof(uint32_t);++ if (size < data_len) {+ return false;+ }++ data->resize(static_cast<size_t>(data_len));+ memcpy(&data->at(0), marker, static_cast<size_t>(data_len));++ *marker_size = name_len + 1 + type_len + 1 + sizeof(uint32_t) + data_len;+ return true;+}++static void WriteAttributeToMemory(std::vector<unsigned char> *out,+ const char *name, const char *type,+ const unsigned char *data, int len) {+ out->insert(out->end(), name, name + strlen(name) + 1);+ out->insert(out->end(), type, type + strlen(type) + 1);++ int outLen = len;+ tinyexr::swap4(&outLen);+ out->insert(out->end(), reinterpret_cast<unsigned char *>(&outLen),+ reinterpret_cast<unsigned char *>(&outLen) + sizeof(int));+ out->insert(out->end(), data, data + len);+}++typedef struct TChannelInfo {+ std::string name; // less than 255 bytes long+ int pixel_type;+ int requested_pixel_type;+ int x_sampling;+ int y_sampling;+ unsigned char p_linear;+ unsigned char pad[3];+} ChannelInfo;++typedef struct {+ int min_x;+ int min_y;+ int max_x;+ int max_y;+} Box2iInfo;++struct HeaderInfo {+ std::vector<tinyexr::ChannelInfo> channels;+ std::vector<EXRAttribute> attributes;++ Box2iInfo data_window;+ int line_order;+ Box2iInfo display_window;+ float screen_window_center[2];+ float screen_window_width;+ float pixel_aspect_ratio;++ int chunk_count;++ // Tiled format+ int tiled; // Non-zero if the part is tiled.+ int tile_size_x;+ int tile_size_y;+ int tile_level_mode;+ int tile_rounding_mode;++ unsigned int header_len;++ int compression_type;++ // required for multi-part or non-image files+ std::string name;+ // required for multi-part or non-image files+ std::string type;++ void clear() {+ channels.clear();+ attributes.clear();++ data_window.min_x = 0;+ data_window.min_y = 0;+ data_window.max_x = 0;+ data_window.max_y = 0;+ line_order = 0;+ display_window.min_x = 0;+ display_window.min_y = 0;+ display_window.max_x = 0;+ display_window.max_y = 0;+ screen_window_center[0] = 0.0f;+ screen_window_center[1] = 0.0f;+ screen_window_width = 0.0f;+ pixel_aspect_ratio = 0.0f;++ chunk_count = 0;++ // Tiled format+ tiled = 0;+ tile_size_x = 0;+ tile_size_y = 0;+ tile_level_mode = 0;+ tile_rounding_mode = 0;++ header_len = 0;+ compression_type = 0;++ name.clear();+ type.clear();+ }+};++static bool ReadChannelInfo(std::vector<ChannelInfo> &channels,+ const std::vector<unsigned char> &data) {+ const char *p = reinterpret_cast<const char *>(&data.at(0));++ for (;;) {+ if ((*p) == 0) {+ break;+ }+ ChannelInfo info;+ info.requested_pixel_type = 0;++ tinyexr_int64 data_len = static_cast<tinyexr_int64>(data.size()) -+ (p - reinterpret_cast<const char *>(data.data()));+ if (data_len < 0) {+ return false;+ }++ p = ReadString(&info.name, p, size_t(data_len));+ if ((p == NULL) && (info.name.empty())) {+ // Buffer overrun. Issue #51.+ return false;+ }++ const unsigned char *data_end =+ reinterpret_cast<const unsigned char *>(p) + 16;+ if (data_end >= (data.data() + data.size())) {+ return false;+ }++ memcpy(&info.pixel_type, p, sizeof(int));+ p += 4;+ info.p_linear = static_cast<unsigned char>(p[0]); // uchar+ p += 1 + 3; // reserved: uchar[3]+ memcpy(&info.x_sampling, p, sizeof(int)); // int+ p += 4;+ memcpy(&info.y_sampling, p, sizeof(int)); // int+ p += 4;++ tinyexr::swap4(&info.pixel_type);+ tinyexr::swap4(&info.x_sampling);+ tinyexr::swap4(&info.y_sampling);++ channels.push_back(info);+ }++ return true;+}++static void WriteChannelInfo(std::vector<unsigned char> &data,+ const std::vector<ChannelInfo> &channels) {+ size_t sz = 0;++ // Calculate total size.+ for (size_t c = 0; c < channels.size(); c++) {+ sz += channels[c].name.length() + 1; // +1 for \0+ sz += 16; // 4 * int+ }+ data.resize(sz + 1);++ unsigned char *p = &data.at(0);++ for (size_t c = 0; c < channels.size(); c++) {+ memcpy(p, channels[c].name.c_str(), channels[c].name.length());+ p += channels[c].name.length();+ (*p) = '\0';+ p++;++ int pixel_type = channels[c].requested_pixel_type;+ int x_sampling = channels[c].x_sampling;+ int y_sampling = channels[c].y_sampling;+ tinyexr::swap4(&pixel_type);+ tinyexr::swap4(&x_sampling);+ tinyexr::swap4(&y_sampling);++ memcpy(p, &pixel_type, sizeof(int));+ p += sizeof(int);++ (*p) = channels[c].p_linear;+ p += 4;++ memcpy(p, &x_sampling, sizeof(int));+ p += sizeof(int);++ memcpy(p, &y_sampling, sizeof(int));+ p += sizeof(int);+ }++ (*p) = '\0';+}++static bool CompressZip(unsigned char *dst,+ tinyexr::tinyexr_uint64 &compressedSize,+ const unsigned char *src, unsigned long src_size) {+ std::vector<unsigned char> tmpBuf(src_size);++ //+ // Apply EXR-specific? postprocess. Grabbed from OpenEXR's+ // ImfZipCompressor.cpp+ //++ //+ // Reorder the pixel data.+ //++ const char *srcPtr = reinterpret_cast<const char *>(src);++ {+ char *t1 = reinterpret_cast<char *>(&tmpBuf.at(0));+ char *t2 = reinterpret_cast<char *>(&tmpBuf.at(0)) + (src_size + 1) / 2;+ const char *stop = srcPtr + src_size;++ for (;;) {+ if (srcPtr < stop)+ *(t1++) = *(srcPtr++);+ else+ break;++ if (srcPtr < stop)+ *(t2++) = *(srcPtr++);+ else+ break;+ }+ }++ //+ // Predictor.+ //++ {+ unsigned char *t = &tmpBuf.at(0) + 1;+ unsigned char *stop = &tmpBuf.at(0) + src_size;+ int p = t[-1];++ while (t < stop) {+ int d = int(t[0]) - p + (128 + 256);+ p = t[0];+ t[0] = static_cast<unsigned char>(d);+ ++t;+ }+ }++#if defined(TINYEXR_USE_MINIZ) && (TINYEXR_USE_MINIZ==1)+ //+ // Compress the data using miniz+ //++ mz_ulong outSize = mz_compressBound(src_size);+ int ret = mz_compress(+ dst, &outSize, static_cast<const unsigned char *>(&tmpBuf.at(0)),+ src_size);+ if (ret != MZ_OK) {+ return false;+ }++ compressedSize = outSize;+#elif defined(TINYEXR_USE_STB_ZLIB) && (TINYEXR_USE_STB_ZLIB==1)+ int outSize;+ unsigned char* ret = stbi_zlib_compress(const_cast<unsigned char*>(&tmpBuf.at(0)), src_size, &outSize, 8);+ if (!ret) {+ return false;+ }+ memcpy(dst, ret, outSize);+ free(ret);++ compressedSize = outSize;+#elif defined(TINYEXR_USE_NANOZLIB) && (TINYEXR_USE_NANOZLIB==1)+ uint64_t dstSize = nanoz_compressBound(static_cast<uint64_t>(src_size));+ int outSize{0};+ unsigned char *ret = nanoz_compress(&tmpBuf.at(0), src_size, &outSize, /* quality */8);+ if (!ret) {+ return false;+ }++ memcpy(dst, ret, outSize);+ free(ret);++ compressedSize = outSize;+#else+ uLong outSize = compressBound(static_cast<uLong>(src_size));+ int ret = compress(dst, &outSize, static_cast<const Bytef *>(&tmpBuf.at(0)),+ src_size);+ if (ret != Z_OK) {+ return false;+ }++ compressedSize = outSize;+#endif++ // Use uncompressed data when compressed data is larger than uncompressed.+ // (Issue 40)+ if (compressedSize >= src_size) {+ compressedSize = src_size;+ memcpy(dst, src, src_size);+ }++ return true;+}++static bool DecompressZip(unsigned char *dst,+ unsigned long *uncompressed_size /* inout */,+ const unsigned char *src, unsigned long src_size) {+ if ((*uncompressed_size) == src_size) {+ // Data is not compressed(Issue 40).+ memcpy(dst, src, src_size);+ return true;+ }+ std::vector<unsigned char> tmpBuf(*uncompressed_size);++#if defined(TINYEXR_USE_MINIZ) && (TINYEXR_USE_MINIZ==1)+ int ret =+ mz_uncompress(&tmpBuf.at(0), uncompressed_size, src, src_size);+ if (MZ_OK != ret) {+ return false;+ }+#elif TINYEXR_USE_STB_ZLIB+ int ret = stbi_zlib_decode_buffer(reinterpret_cast<char*>(&tmpBuf.at(0)),+ *uncompressed_size, reinterpret_cast<const char*>(src), src_size);+ if (ret < 0) {+ return false;+ }+#elif defined(TINYEXR_USE_NANOZLIB) && (TINYEXR_USE_NANOZLIB==1)+ uint64_t dest_size = (*uncompressed_size);+ uint64_t uncomp_size{0};+ nanoz_status_t ret =+ nanoz_uncompress(src, src_size, dest_size, &tmpBuf.at(0), &uncomp_size);+ if (NANOZ_SUCCESS != ret) {+ return false;+ }+ if ((*uncompressed_size) != uncomp_size) {+ return false;+ }+#else+ int ret = uncompress(&tmpBuf.at(0), uncompressed_size, src, src_size);+ if (Z_OK != ret) {+ return false;+ }+#endif++ //+ // Apply EXR-specific? postprocess. Grabbed from OpenEXR's+ // ImfZipCompressor.cpp+ //++ // Predictor.+ {+ unsigned char *t = &tmpBuf.at(0) + 1;+ unsigned char *stop = &tmpBuf.at(0) + (*uncompressed_size);++ while (t < stop) {+ int d = int(t[-1]) + int(t[0]) - 128;+ t[0] = static_cast<unsigned char>(d);+ ++t;+ }+ }++ // Reorder the pixel data.+ {+ const char *t1 = reinterpret_cast<const char *>(&tmpBuf.at(0));+ const char *t2 = reinterpret_cast<const char *>(&tmpBuf.at(0)) ++ (*uncompressed_size + 1) / 2;+ char *s = reinterpret_cast<char *>(dst);+ char *stop = s + (*uncompressed_size);++ for (;;) {+ if (s < stop)+ *(s++) = *(t1++);+ else+ break;++ if (s < stop)+ *(s++) = *(t2++);+ else+ break;+ }+ }++ return true;+}++// RLE code from OpenEXR --------------------------------------++#ifdef __clang__+#pragma clang diagnostic push+#pragma clang diagnostic ignored "-Wsign-conversion"+#if __has_warning("-Wextra-semi-stmt")+#pragma clang diagnostic ignored "-Wextra-semi-stmt"+#endif+#endif++#ifdef _MSC_VER+#pragma warning(push)+#pragma warning(disable : 4204) // nonstandard extension used : non-constant+ // aggregate initializer (also supported by GNU+ // C and C99, so no big deal)+#pragma warning(disable : 4244) // 'initializing': conversion from '__int64' to+ // 'int', possible loss of data+#pragma warning(disable : 4267) // 'argument': conversion from '__int64' to+ // 'int', possible loss of data+#pragma warning(disable : 4996) // 'strdup': The POSIX name for this item is+ // deprecated. Instead, use the ISO C and C+++ // conformant name: _strdup.+#endif++const int MIN_RUN_LENGTH = 3;+const int MAX_RUN_LENGTH = 127;++//+// Compress an array of bytes, using run-length encoding,+// and return the length of the compressed data.+//++static int rleCompress(int inLength, const char in[], signed char out[]) {+ const char *inEnd = in + inLength;+ const char *runStart = in;+ const char *runEnd = in + 1;+ signed char *outWrite = out;++ while (runStart < inEnd) {+ while (runEnd < inEnd && *runStart == *runEnd &&+ runEnd - runStart - 1 < MAX_RUN_LENGTH) {+ ++runEnd;+ }++ if (runEnd - runStart >= MIN_RUN_LENGTH) {+ //+ // Compressible run+ //++ *outWrite++ = static_cast<char>(runEnd - runStart) - 1;+ *outWrite++ = *(reinterpret_cast<const signed char *>(runStart));+ runStart = runEnd;+ } else {+ //+ // Uncompressable run+ //++ while (runEnd < inEnd &&+ ((runEnd + 1 >= inEnd || *runEnd != *(runEnd + 1)) ||+ (runEnd + 2 >= inEnd || *(runEnd + 1) != *(runEnd + 2))) &&+ runEnd - runStart < MAX_RUN_LENGTH) {+ ++runEnd;+ }++ *outWrite++ = static_cast<char>(runStart - runEnd);++ while (runStart < runEnd) {+ *outWrite++ = *(reinterpret_cast<const signed char *>(runStart++));+ }+ }++ ++runEnd;+ }++ return static_cast<int>(outWrite - out);+}++//+// Uncompress an array of bytes compressed with rleCompress().+// Returns the length of the uncompressed data, or 0 if the+// length of the uncompressed data would be more than maxLength.+//++static int rleUncompress(int inLength, int maxLength, const signed char in[],+ char out[]) {+ char *outStart = out;++ while (inLength > 0) {+ if (*in < 0) {+ int count = -(static_cast<int>(*in++));+ inLength -= count + 1;++ // Fixes #116: Add bounds check to in buffer.+ if ((0 > (maxLength -= count)) || (inLength < 0)) return 0;++ memcpy(out, in, count);+ out += count;+ in += count;+ } else {+ int count = *in++;+ inLength -= 2;++ if ((0 > (maxLength -= count + 1)) || (inLength < 0)) return 0;++ memset(out, *reinterpret_cast<const char *>(in), count + 1);+ out += count + 1;++ in++;+ }+ }++ return static_cast<int>(out - outStart);+}++#ifdef __clang__+#pragma clang diagnostic pop+#endif++// End of RLE code from OpenEXR -----------------------------------++static bool CompressRle(unsigned char *dst,+ tinyexr::tinyexr_uint64 &compressedSize,+ const unsigned char *src, unsigned long src_size) {+ std::vector<unsigned char> tmpBuf(src_size);++ //+ // Apply EXR-specific? postprocess. Grabbed from OpenEXR's+ // ImfRleCompressor.cpp+ //++ //+ // Reorder the pixel data.+ //++ const char *srcPtr = reinterpret_cast<const char *>(src);++ {+ char *t1 = reinterpret_cast<char *>(&tmpBuf.at(0));+ char *t2 = reinterpret_cast<char *>(&tmpBuf.at(0)) + (src_size + 1) / 2;+ const char *stop = srcPtr + src_size;++ for (;;) {+ if (srcPtr < stop)+ *(t1++) = *(srcPtr++);+ else+ break;++ if (srcPtr < stop)+ *(t2++) = *(srcPtr++);+ else+ break;+ }+ }++ //+ // Predictor.+ //++ {+ unsigned char *t = &tmpBuf.at(0) + 1;+ unsigned char *stop = &tmpBuf.at(0) + src_size;+ int p = t[-1];++ while (t < stop) {+ int d = int(t[0]) - p + (128 + 256);+ p = t[0];+ t[0] = static_cast<unsigned char>(d);+ ++t;+ }+ }++ // outSize will be (srcSiz * 3) / 2 at max.+ int outSize = rleCompress(static_cast<int>(src_size),+ reinterpret_cast<const char *>(&tmpBuf.at(0)),+ reinterpret_cast<signed char *>(dst));+ TINYEXR_CHECK_AND_RETURN_C(outSize > 0, false);++ compressedSize = static_cast<tinyexr::tinyexr_uint64>(outSize);++ // Use uncompressed data when compressed data is larger than uncompressed.+ // (Issue 40)+ if (compressedSize >= src_size) {+ compressedSize = src_size;+ memcpy(dst, src, src_size);+ }++ return true;+}++static bool DecompressRle(unsigned char *dst,+ const unsigned long uncompressed_size,+ const unsigned char *src, unsigned long src_size) {+ if (uncompressed_size == src_size) {+ // Data is not compressed(Issue 40).+ memcpy(dst, src, src_size);+ return true;+ }++ // Workaround for issue #112.+ // TODO(syoyo): Add more robust out-of-bounds check in `rleUncompress`.+ if (src_size <= 2) {+ return false;+ }++ std::vector<unsigned char> tmpBuf(uncompressed_size);++ int ret = rleUncompress(static_cast<int>(src_size),+ static_cast<int>(uncompressed_size),+ reinterpret_cast<const signed char *>(src),+ reinterpret_cast<char *>(&tmpBuf.at(0)));+ if (ret != static_cast<int>(uncompressed_size)) {+ return false;+ }++ //+ // Apply EXR-specific? postprocess. Grabbed from OpenEXR's+ // ImfRleCompressor.cpp+ //++ // Predictor.+ {+ unsigned char *t = &tmpBuf.at(0) + 1;+ unsigned char *stop = &tmpBuf.at(0) + uncompressed_size;++ while (t < stop) {+ int d = int(t[-1]) + int(t[0]) - 128;+ t[0] = static_cast<unsigned char>(d);+ ++t;+ }+ }++ // Reorder the pixel data.+ {+ const char *t1 = reinterpret_cast<const char *>(&tmpBuf.at(0));+ const char *t2 = reinterpret_cast<const char *>(&tmpBuf.at(0)) ++ (uncompressed_size + 1) / 2;+ char *s = reinterpret_cast<char *>(dst);+ char *stop = s + uncompressed_size;++ for (;;) {+ if (s < stop)+ *(s++) = *(t1++);+ else+ break;++ if (s < stop)+ *(s++) = *(t2++);+ else+ break;+ }+ }++ return true;+}++#if TINYEXR_USE_PIZ++#ifdef __clang__+#pragma clang diagnostic push+#pragma clang diagnostic ignored "-Wc++11-long-long"+#pragma clang diagnostic ignored "-Wold-style-cast"+#pragma clang diagnostic ignored "-Wpadded"+#pragma clang diagnostic ignored "-Wsign-conversion"+#pragma clang diagnostic ignored "-Wc++11-extensions"+#pragma clang diagnostic ignored "-Wconversion"+#pragma clang diagnostic ignored "-Wc++98-compat-pedantic"++#if __has_warning("-Wcast-qual")+#pragma clang diagnostic ignored "-Wcast-qual"+#endif++#if __has_warning("-Wextra-semi-stmt")+#pragma clang diagnostic ignored "-Wextra-semi-stmt"+#endif++#endif++//+// PIZ compress/uncompress, based on OpenEXR's ImfPizCompressor.cpp+//+// -----------------------------------------------------------------+// Copyright (c) 2004, Industrial Light & Magic, a division of Lucas+// Digital Ltd. LLC)+// (3 clause BSD license)+//++struct PIZChannelData {+ unsigned short *start;+ unsigned short *end;+ int nx;+ int ny;+ int ys;+ int size;+};++//-----------------------------------------------------------------------------+//+// 16-bit Haar Wavelet encoding and decoding+//+// The source code in this file is derived from the encoding+// and decoding routines written by Christian Rouet for his+// PIZ image file format.+//+//-----------------------------------------------------------------------------++//+// Wavelet basis functions without modulo arithmetic; they produce+// the best compression ratios when the wavelet-transformed data are+// Huffman-encoded, but the wavelet transform works only for 14-bit+// data (untransformed data values must be less than (1 << 14)).+//++inline void wenc14(unsigned short a, unsigned short b, unsigned short &l,+ unsigned short &h) {+ short as = static_cast<short>(a);+ short bs = static_cast<short>(b);++ short ms = (as + bs) >> 1;+ short ds = as - bs;++ l = static_cast<unsigned short>(ms);+ h = static_cast<unsigned short>(ds);+}++inline void wdec14(unsigned short l, unsigned short h, unsigned short &a,+ unsigned short &b) {+ short ls = static_cast<short>(l);+ short hs = static_cast<short>(h);++ int hi = hs;+ int ai = ls + (hi & 1) + (hi >> 1);++ short as = static_cast<short>(ai);+ short bs = static_cast<short>(ai - hi);++ a = static_cast<unsigned short>(as);+ b = static_cast<unsigned short>(bs);+}++//+// Wavelet basis functions with modulo arithmetic; they work with full+// 16-bit data, but Huffman-encoding the wavelet-transformed data doesn't+// compress the data quite as well.+//++const int NBITS = 16;+const int A_OFFSET = 1 << (NBITS - 1);+const int M_OFFSET = 1 << (NBITS - 1);+const int MOD_MASK = (1 << NBITS) - 1;++inline void wenc16(unsigned short a, unsigned short b, unsigned short &l,+ unsigned short &h) {+ int ao = (a + A_OFFSET) & MOD_MASK;+ int m = ((ao + b) >> 1);+ int d = ao - b;++ if (d < 0) m = (m + M_OFFSET) & MOD_MASK;++ d &= MOD_MASK;++ l = static_cast<unsigned short>(m);+ h = static_cast<unsigned short>(d);+}++inline void wdec16(unsigned short l, unsigned short h, unsigned short &a,+ unsigned short &b) {+ int m = l;+ int d = h;+ int bb = (m - (d >> 1)) & MOD_MASK;+ int aa = (d + bb - A_OFFSET) & MOD_MASK;+ b = static_cast<unsigned short>(bb);+ a = static_cast<unsigned short>(aa);+}++//+// 2D Wavelet encoding:+//++static void wav2Encode(+ unsigned short *in, // io: values are transformed in place+ int nx, // i : x size+ int ox, // i : x offset+ int ny, // i : y size+ int oy, // i : y offset+ unsigned short mx) // i : maximum in[x][y] value+{+ bool w14 = (mx < (1 << 14));+ int n = (nx > ny) ? ny : nx;+ int p = 1; // == 1 << level+ int p2 = 2; // == 1 << (level+1)++ //+ // Hierarchical loop on smaller dimension n+ //++ while (p2 <= n) {+ unsigned short *py = in;+ unsigned short *ey = in + oy * (ny - p2);+ int oy1 = oy * p;+ int oy2 = oy * p2;+ int ox1 = ox * p;+ int ox2 = ox * p2;+ unsigned short i00, i01, i10, i11;++ //+ // Y loop+ //++ for (; py <= ey; py += oy2) {+ unsigned short *px = py;+ unsigned short *ex = py + ox * (nx - p2);++ //+ // X loop+ //++ for (; px <= ex; px += ox2) {+ unsigned short *p01 = px + ox1;+ unsigned short *p10 = px + oy1;+ unsigned short *p11 = p10 + ox1;++ //+ // 2D wavelet encoding+ //++ if (w14) {+ wenc14(*px, *p01, i00, i01);+ wenc14(*p10, *p11, i10, i11);+ wenc14(i00, i10, *px, *p10);+ wenc14(i01, i11, *p01, *p11);+ } else {+ wenc16(*px, *p01, i00, i01);+ wenc16(*p10, *p11, i10, i11);+ wenc16(i00, i10, *px, *p10);+ wenc16(i01, i11, *p01, *p11);+ }+ }++ //+ // Encode (1D) odd column (still in Y loop)+ //++ if (nx & p) {+ unsigned short *p10 = px + oy1;++ if (w14)+ wenc14(*px, *p10, i00, *p10);+ else+ wenc16(*px, *p10, i00, *p10);++ *px = i00;+ }+ }++ //+ // Encode (1D) odd line (must loop in X)+ //++ if (ny & p) {+ unsigned short *px = py;+ unsigned short *ex = py + ox * (nx - p2);++ for (; px <= ex; px += ox2) {+ unsigned short *p01 = px + ox1;++ if (w14)+ wenc14(*px, *p01, i00, *p01);+ else+ wenc16(*px, *p01, i00, *p01);++ *px = i00;+ }+ }++ //+ // Next level+ //++ p = p2;+ p2 <<= 1;+ }+}++//+// 2D Wavelet decoding:+//++static void wav2Decode(+ unsigned short *in, // io: values are transformed in place+ int nx, // i : x size+ int ox, // i : x offset+ int ny, // i : y size+ int oy, // i : y offset+ unsigned short mx) // i : maximum in[x][y] value+{+ bool w14 = (mx < (1 << 14));+ int n = (nx > ny) ? ny : nx;+ int p = 1;+ int p2;++ //+ // Search max level+ //++ while (p <= n) p <<= 1;++ p >>= 1;+ p2 = p;+ p >>= 1;++ //+ // Hierarchical loop on smaller dimension n+ //++ while (p >= 1) {+ unsigned short *py = in;+ unsigned short *ey = in + oy * (ny - p2);+ int oy1 = oy * p;+ int oy2 = oy * p2;+ int ox1 = ox * p;+ int ox2 = ox * p2;+ unsigned short i00, i01, i10, i11;++ //+ // Y loop+ //++ for (; py <= ey; py += oy2) {+ unsigned short *px = py;+ unsigned short *ex = py + ox * (nx - p2);++ //+ // X loop+ //++ for (; px <= ex; px += ox2) {+ unsigned short *p01 = px + ox1;+ unsigned short *p10 = px + oy1;+ unsigned short *p11 = p10 + ox1;++ //+ // 2D wavelet decoding+ //++ if (w14) {+ wdec14(*px, *p10, i00, i10);+ wdec14(*p01, *p11, i01, i11);+ wdec14(i00, i01, *px, *p01);+ wdec14(i10, i11, *p10, *p11);+ } else {+ wdec16(*px, *p10, i00, i10);+ wdec16(*p01, *p11, i01, i11);+ wdec16(i00, i01, *px, *p01);+ wdec16(i10, i11, *p10, *p11);+ }+ }++ //+ // Decode (1D) odd column (still in Y loop)+ //++ if (nx & p) {+ unsigned short *p10 = px + oy1;++ if (w14)+ wdec14(*px, *p10, i00, *p10);+ else+ wdec16(*px, *p10, i00, *p10);++ *px = i00;+ }+ }++ //+ // Decode (1D) odd line (must loop in X)+ //++ if (ny & p) {+ unsigned short *px = py;+ unsigned short *ex = py + ox * (nx - p2);++ for (; px <= ex; px += ox2) {+ unsigned short *p01 = px + ox1;++ if (w14)+ wdec14(*px, *p01, i00, *p01);+ else+ wdec16(*px, *p01, i00, *p01);++ *px = i00;+ }+ }++ //+ // Next level+ //++ p2 = p;+ p >>= 1;+ }+}++//-----------------------------------------------------------------------------+//+// 16-bit Huffman compression and decompression.+//+// The source code in this file is derived from the 8-bit+// Huffman compression and decompression routines written+// by Christian Rouet for his PIZ image file format.+//+//-----------------------------------------------------------------------------++// Adds some modification for tinyexr.++const int HUF_ENCBITS = 16; // literal (value) bit length+const int HUF_DECBITS = 14; // decoding bit size (>= 8)++const int HUF_ENCSIZE = (1 << HUF_ENCBITS) + 1; // encoding table size+const int HUF_DECSIZE = 1 << HUF_DECBITS; // decoding table size+const int HUF_DECMASK = HUF_DECSIZE - 1;++struct HufDec { // short code long code+ //-------------------------------+ unsigned int len : 8; // code length 0+ unsigned int lit : 24; // lit p size+ unsigned int *p; // 0 lits+};++inline long long hufLength(long long code) { return code & 63; }++inline long long hufCode(long long code) { return code >> 6; }++inline void outputBits(int nBits, long long bits, long long &c, int &lc,+ char *&out) {+ c <<= nBits;+ lc += nBits;++ c |= bits;++ while (lc >= 8) *out++ = static_cast<char>((c >> (lc -= 8)));+}++inline long long getBits(int nBits, long long &c, int &lc, const char *&in) {+ while (lc < nBits) {+ c = (c << 8) | *(reinterpret_cast<const unsigned char *>(in++));+ lc += 8;+ }++ lc -= nBits;+ return (c >> lc) & ((1 << nBits) - 1);+}++//+// ENCODING TABLE BUILDING & (UN)PACKING+//++//+// Build a "canonical" Huffman code table:+// - for each (uncompressed) symbol, hcode contains the length+// of the corresponding code (in the compressed data)+// - canonical codes are computed and stored in hcode+// - the rules for constructing canonical codes are as follows:+// * shorter codes (if filled with zeroes to the right)+// have a numerically higher value than longer codes+// * for codes with the same length, numerical values+// increase with numerical symbol values+// - because the canonical code table can be constructed from+// symbol lengths alone, the code table can be transmitted+// without sending the actual code values+// - see http://www.compressconsult.com/huffman/+//++static void hufCanonicalCodeTable(long long hcode[HUF_ENCSIZE]) {+ long long n[59];++ //+ // For each i from 0 through 58, count the+ // number of different codes of length i, and+ // store the count in n[i].+ //++ for (int i = 0; i <= 58; ++i) n[i] = 0;++ for (int i = 0; i < HUF_ENCSIZE; ++i) n[hcode[i]] += 1;++ //+ // For each i from 58 through 1, compute the+ // numerically lowest code with length i, and+ // store that code in n[i].+ //++ long long c = 0;++ for (int i = 58; i > 0; --i) {+ long long nc = ((c + n[i]) >> 1);+ n[i] = c;+ c = nc;+ }++ //+ // hcode[i] contains the length, l, of the+ // code for symbol i. Assign the next available+ // code of length l to the symbol and store both+ // l and the code in hcode[i].+ //++ for (int i = 0; i < HUF_ENCSIZE; ++i) {+ int l = static_cast<int>(hcode[i]);++ if (l > 0) hcode[i] = l | (n[l]++ << 6);+ }+}++//+// Compute Huffman codes (based on frq input) and store them in frq:+// - code structure is : [63:lsb - 6:msb] | [5-0: bit length];+// - max code length is 58 bits;+// - codes outside the range [im-iM] have a null length (unused values);+// - original frequencies are destroyed;+// - encoding tables are used by hufEncode() and hufBuildDecTable();+//++struct FHeapCompare {+ bool operator()(long long *a, long long *b) { return *a > *b; }+};++static bool hufBuildEncTable(+ long long *frq, // io: input frequencies [HUF_ENCSIZE], output table+ int *im, // o: min frq index+ int *iM) // o: max frq index+{+ //+ // This function assumes that when it is called, array frq+ // indicates the frequency of all possible symbols in the data+ // that are to be Huffman-encoded. (frq[i] contains the number+ // of occurrences of symbol i in the data.)+ //+ // The loop below does three things:+ //+ // 1) Finds the minimum and maximum indices that point+ // to non-zero entries in frq:+ //+ // frq[im] != 0, and frq[i] == 0 for all i < im+ // frq[iM] != 0, and frq[i] == 0 for all i > iM+ //+ // 2) Fills array fHeap with pointers to all non-zero+ // entries in frq.+ //+ // 3) Initializes array hlink such that hlink[i] == i+ // for all array entries.+ //++ std::vector<int> hlink(HUF_ENCSIZE);+ std::vector<long long *> fHeap(HUF_ENCSIZE);++ *im = 0;++ while (!frq[*im]) (*im)++;++ int nf = 0;++ for (int i = *im; i < HUF_ENCSIZE; i++) {+ hlink[i] = i;++ if (frq[i]) {+ fHeap[nf] = &frq[i];+ nf++;+ *iM = i;+ }+ }++ //+ // Add a pseudo-symbol, with a frequency count of 1, to frq;+ // adjust the fHeap and hlink array accordingly. Function+ // hufEncode() uses the pseudo-symbol for run-length encoding.+ //++ (*iM)++;+ frq[*iM] = 1;+ fHeap[nf] = &frq[*iM];+ nf++;++ //+ // Build an array, scode, such that scode[i] contains the number+ // of bits assigned to symbol i. Conceptually this is done by+ // constructing a tree whose leaves are the symbols with non-zero+ // frequency:+ //+ // Make a heap that contains all symbols with a non-zero frequency,+ // with the least frequent symbol on top.+ //+ // Repeat until only one symbol is left on the heap:+ //+ // Take the two least frequent symbols off the top of the heap.+ // Create a new node that has first two nodes as children, and+ // whose frequency is the sum of the frequencies of the first+ // two nodes. Put the new node back into the heap.+ //+ // The last node left on the heap is the root of the tree. For each+ // leaf node, the distance between the root and the leaf is the length+ // of the code for the corresponding symbol.+ //+ // The loop below doesn't actually build the tree; instead we compute+ // the distances of the leaves from the root on the fly. When a new+ // node is added to the heap, then that node's descendants are linked+ // into a single linear list that starts at the new node, and the code+ // lengths of the descendants (that is, their distance from the root+ // of the tree) are incremented by one.+ //++ std::make_heap(&fHeap[0], &fHeap[nf], FHeapCompare());++ std::vector<long long> scode(HUF_ENCSIZE);+ memset(scode.data(), 0, sizeof(long long) * HUF_ENCSIZE);++ while (nf > 1) {+ //+ // Find the indices, mm and m, of the two smallest non-zero frq+ // values in fHeap, add the smallest frq to the second-smallest+ // frq, and remove the smallest frq value from fHeap.+ //++ int mm = fHeap[0] - frq;+ std::pop_heap(&fHeap[0], &fHeap[nf], FHeapCompare());+ --nf;++ int m = fHeap[0] - frq;+ std::pop_heap(&fHeap[0], &fHeap[nf], FHeapCompare());++ frq[m] += frq[mm];+ std::push_heap(&fHeap[0], &fHeap[nf], FHeapCompare());++ //+ // The entries in scode are linked into lists with the+ // entries in hlink serving as "next" pointers and with+ // the end of a list marked by hlink[j] == j.+ //+ // Traverse the lists that start at scode[m] and scode[mm].+ // For each element visited, increment the length of the+ // corresponding code by one bit. (If we visit scode[j]+ // during the traversal, then the code for symbol j becomes+ // one bit longer.)+ //+ // Merge the lists that start at scode[m] and scode[mm]+ // into a single list that starts at scode[m].+ //++ //+ // Add a bit to all codes in the first list.+ //++ for (int j = m;; j = hlink[j]) {+ scode[j]++;++ TINYEXR_CHECK_AND_RETURN_C(scode[j] <= 58, false);++ if (hlink[j] == j) {+ //+ // Merge the two lists.+ //++ hlink[j] = mm;+ break;+ }+ }++ //+ // Add a bit to all codes in the second list+ //++ for (int j = mm;; j = hlink[j]) {+ scode[j]++;++ TINYEXR_CHECK_AND_RETURN_C(scode[j] <= 58, false);++ if (hlink[j] == j) break;+ }+ }++ //+ // Build a canonical Huffman code table, replacing the code+ // lengths in scode with (code, code length) pairs. Copy the+ // code table from scode into frq.+ //++ hufCanonicalCodeTable(scode.data());+ memcpy(frq, scode.data(), sizeof(long long) * HUF_ENCSIZE);++ return true;+}++//+// Pack an encoding table:+// - only code lengths, not actual codes, are stored+// - runs of zeroes are compressed as follows:+//+// unpacked packed+// --------------------------------+// 1 zero 0 (6 bits)+// 2 zeroes 59+// 3 zeroes 60+// 4 zeroes 61+// 5 zeroes 62+// n zeroes (6 or more) 63 n-6 (6 + 8 bits)+//++const int SHORT_ZEROCODE_RUN = 59;+const int LONG_ZEROCODE_RUN = 63;+const int SHORTEST_LONG_RUN = 2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN;+const int LONGEST_LONG_RUN = 255 + SHORTEST_LONG_RUN;++static void hufPackEncTable(+ const long long *hcode, // i : encoding table [HUF_ENCSIZE]+ int im, // i : min hcode index+ int iM, // i : max hcode index+ char **pcode) // o: ptr to packed table (updated)+{+ char *p = *pcode;+ long long c = 0;+ int lc = 0;++ for (; im <= iM; im++) {+ int l = hufLength(hcode[im]);++ if (l == 0) {+ int zerun = 1;++ while ((im < iM) && (zerun < LONGEST_LONG_RUN)) {+ if (hufLength(hcode[im + 1]) > 0) break;+ im++;+ zerun++;+ }++ if (zerun >= 2) {+ if (zerun >= SHORTEST_LONG_RUN) {+ outputBits(6, LONG_ZEROCODE_RUN, c, lc, p);+ outputBits(8, zerun - SHORTEST_LONG_RUN, c, lc, p);+ } else {+ outputBits(6, SHORT_ZEROCODE_RUN + zerun - 2, c, lc, p);+ }+ continue;+ }+ }++ outputBits(6, l, c, lc, p);+ }++ if (lc > 0) *p++ = (unsigned char)(c << (8 - lc));++ *pcode = p;+}++//+// Unpack an encoding table packed by hufPackEncTable():+//++static bool hufUnpackEncTable(+ const char **pcode, // io: ptr to packed table (updated)+ int ni, // i : input size (in bytes)+ int im, // i : min hcode index+ int iM, // i : max hcode index+ long long *hcode) // o: encoding table [HUF_ENCSIZE]+{+ memset(hcode, 0, sizeof(long long) * HUF_ENCSIZE);++ const char *p = *pcode;+ long long c = 0;+ int lc = 0;++ for (; im <= iM; im++) {+ if (p - *pcode >= ni) {+ return false;+ }++ long long l = hcode[im] = getBits(6, c, lc, p); // code length++ if (l == (long long)LONG_ZEROCODE_RUN) {+ if (p - *pcode > ni) {+ return false;+ }++ int zerun = getBits(8, c, lc, p) + SHORTEST_LONG_RUN;++ if (im + zerun > iM + 1) {+ return false;+ }++ while (zerun--) hcode[im++] = 0;++ im--;+ } else if (l >= (long long)SHORT_ZEROCODE_RUN) {+ int zerun = l - SHORT_ZEROCODE_RUN + 2;++ if (im + zerun > iM + 1) {+ return false;+ }++ while (zerun--) hcode[im++] = 0;++ im--;+ }+ }++ *pcode = const_cast<char *>(p);++ hufCanonicalCodeTable(hcode);++ return true;+}++//+// DECODING TABLE BUILDING+//++//+// Clear a newly allocated decoding table so that it contains only zeroes.+//++static void hufClearDecTable(HufDec *hdecod) // io: (allocated by caller)+// decoding table [HUF_DECSIZE]+{+ for (int i = 0; i < HUF_DECSIZE; i++) {+ hdecod[i].len = 0;+ hdecod[i].lit = 0;+ hdecod[i].p = NULL;+ }+ // memset(hdecod, 0, sizeof(HufDec) * HUF_DECSIZE);+}++//+// Build a decoding hash table based on the encoding table hcode:+// - short codes (<= HUF_DECBITS) are resolved with a single table access;+// - long code entry allocations are not optimized, because long codes are+// unfrequent;+// - decoding tables are used by hufDecode();+//++static bool hufBuildDecTable(const long long *hcode, // i : encoding table+ int im, // i : min index in hcode+ int iM, // i : max index in hcode+ HufDec *hdecod) // o: (allocated by caller)+// decoding table [HUF_DECSIZE]+{+ //+ // Init hashtable & loop on all codes.+ // Assumes that hufClearDecTable(hdecod) has already been called.+ //++ for (; im <= iM; im++) {+ long long c = hufCode(hcode[im]);+ int l = hufLength(hcode[im]);++ if (c >> l) {+ //+ // Error: c is supposed to be an l-bit code,+ // but c contains a value that is greater+ // than the largest l-bit number.+ //++ // invalidTableEntry();+ return false;+ }++ if (l > HUF_DECBITS) {+ //+ // Long code: add a secondary entry+ //++ HufDec *pl = hdecod + (c >> (l - HUF_DECBITS));++ if (pl->len) {+ //+ // Error: a short code has already+ // been stored in table entry *pl.+ //++ // invalidTableEntry();+ return false;+ }++ pl->lit++;++ if (pl->p) {+ unsigned int *p = pl->p;+ pl->p = new unsigned int[pl->lit];++ for (unsigned int i = 0; i < pl->lit - 1u; ++i) pl->p[i] = p[i];++ delete[] p;+ } else {+ pl->p = new unsigned int[1];+ }++ pl->p[pl->lit - 1] = im;+ } else if (l) {+ //+ // Short code: init all primary entries+ //++ HufDec *pl = hdecod + (c << (HUF_DECBITS - l));++ for (long long i = 1ULL << (HUF_DECBITS - l); i > 0; i--, pl++) {+ if (pl->len || pl->p) {+ //+ // Error: a short code or a long code has+ // already been stored in table entry *pl.+ //++ // invalidTableEntry();+ return false;+ }++ pl->len = l;+ pl->lit = im;+ }+ }+ }++ return true;+}++//+// Free the long code entries of a decoding table built by hufBuildDecTable()+//++static void hufFreeDecTable(HufDec *hdecod) // io: Decoding table+{+ for (int i = 0; i < HUF_DECSIZE; i++) {+ if (hdecod[i].p) {+ delete[] hdecod[i].p;+ hdecod[i].p = 0;+ }+ }+}++//+// ENCODING+//++inline void outputCode(long long code, long long &c, int &lc, char *&out) {+ outputBits(hufLength(code), hufCode(code), c, lc, out);+}++inline void sendCode(long long sCode, int runCount, long long runCode,+ long long &c, int &lc, char *&out) {+ //+ // Output a run of runCount instances of the symbol sCount.+ // Output the symbols explicitly, or if that is shorter, output+ // the sCode symbol once followed by a runCode symbol and runCount+ // expressed as an 8-bit number.+ //++ if (hufLength(sCode) + hufLength(runCode) + 8 < hufLength(sCode) * runCount) {+ outputCode(sCode, c, lc, out);+ outputCode(runCode, c, lc, out);+ outputBits(8, runCount, c, lc, out);+ } else {+ while (runCount-- >= 0) outputCode(sCode, c, lc, out);+ }+}++//+// Encode (compress) ni values based on the Huffman encoding table hcode:+//++static int hufEncode // return: output size (in bits)+ (const long long *hcode, // i : encoding table+ const unsigned short *in, // i : uncompressed input buffer+ const int ni, // i : input buffer size (in bytes)+ int rlc, // i : rl code+ char *out) // o: compressed output buffer+{+ char *outStart = out;+ long long c = 0; // bits not yet written to out+ int lc = 0; // number of valid bits in c (LSB)+ int s = in[0];+ int cs = 0;++ //+ // Loop on input values+ //++ for (int i = 1; i < ni; i++) {+ //+ // Count same values or send code+ //++ if (s == in[i] && cs < 255) {+ cs++;+ } else {+ sendCode(hcode[s], cs, hcode[rlc], c, lc, out);+ cs = 0;+ }++ s = in[i];+ }++ //+ // Send remaining code+ //++ sendCode(hcode[s], cs, hcode[rlc], c, lc, out);++ if (lc) *out = (c << (8 - lc)) & 0xff;++ return (out - outStart) * 8 + lc;+}++//+// DECODING+//++//+// In order to force the compiler to inline them,+// getChar() and getCode() are implemented as macros+// instead of "inline" functions.+//++#define getChar(c, lc, in) \+ { \+ c = (c << 8) | *(unsigned char *)(in++); \+ lc += 8; \+ }++#if 0+#define getCode(po, rlc, c, lc, in, out, ob, oe) \+ { \+ if (po == rlc) { \+ if (lc < 8) getChar(c, lc, in); \+ \+ lc -= 8; \+ \+ unsigned char cs = (c >> lc); \+ \+ if (out + cs > oe) return false; \+ \+ /* TinyEXR issue 78 */ \+ unsigned short s = out[-1]; \+ \+ while (cs-- > 0) *out++ = s; \+ } else if (out < oe) { \+ *out++ = po; \+ } else { \+ return false; \+ } \+ }+#else+static bool getCode(int po, int rlc, long long &c, int &lc, const char *&in,+ const char *in_end, unsigned short *&out,+ const unsigned short *ob, const unsigned short *oe) {+ (void)ob;+ if (po == rlc) {+ if (lc < 8) {+ /* TinyEXR issue 78 */+ /* TinyEXR issue 160. in + 1 -> in */+ if (in >= in_end) {+ return false;+ }++ getChar(c, lc, in);+ }++ lc -= 8;++ unsigned char cs = (c >> lc);++ if (out + cs > oe) return false;++ // Bounds check for safety+ // Issue 100.+ if ((out - 1) < ob) return false;+ unsigned short s = out[-1];++ while (cs-- > 0) *out++ = s;+ } else if (out < oe) {+ *out++ = po;+ } else {+ return false;+ }+ return true;+}+#endif++//+// Decode (uncompress) ni bits based on encoding & decoding tables:+//++static bool hufDecode(const long long *hcode, // i : encoding table+ const HufDec *hdecod, // i : decoding table+ const char *in, // i : compressed input buffer+ int ni, // i : input size (in bits)+ int rlc, // i : run-length code+ int no, // i : expected output size (in bytes)+ unsigned short *out) // o: uncompressed output buffer+{+ long long c = 0;+ int lc = 0;+ unsigned short *outb = out; // begin+ unsigned short *oe = out + no; // end+ const char *ie = in + (ni + 7) / 8; // input byte size++ //+ // Loop on input bytes+ //++ while (in < ie) {+ getChar(c, lc, in);++ //+ // Access decoding table+ //++ while (lc >= HUF_DECBITS) {+ const HufDec pl = hdecod[(c >> (lc - HUF_DECBITS)) & HUF_DECMASK];++ if (pl.len) {+ //+ // Get short code+ //++ lc -= pl.len;+ // std::cout << "lit = " << pl.lit << std::endl;+ // std::cout << "rlc = " << rlc << std::endl;+ // std::cout << "c = " << c << std::endl;+ // std::cout << "lc = " << lc << std::endl;+ // std::cout << "in = " << in << std::endl;+ // std::cout << "out = " << out << std::endl;+ // std::cout << "oe = " << oe << std::endl;+ if (!getCode(pl.lit, rlc, c, lc, in, ie, out, outb, oe)) {+ return false;+ }+ } else {+ if (!pl.p) {+ return false;+ }+ // invalidCode(); // wrong code++ //+ // Search long code+ //++ unsigned int j;++ for (j = 0; j < pl.lit; j++) {+ int l = hufLength(hcode[pl.p[j]]);++ while (lc < l && in < ie) // get more bits+ getChar(c, lc, in);++ if (lc >= l) {+ if (hufCode(hcode[pl.p[j]]) ==+ ((c >> (lc - l)) & (((long long)(1) << l) - 1))) {+ //+ // Found : get long code+ //++ lc -= l;+ if (!getCode(pl.p[j], rlc, c, lc, in, ie, out, outb, oe)) {+ return false;+ }+ break;+ }+ }+ }++ if (j == pl.lit) {+ return false;+ // invalidCode(); // Not found+ }+ }+ }+ }++ //+ // Get remaining (short) codes+ //++ int i = (8 - ni) & 7;+ c >>= i;+ lc -= i;++ while (lc > 0) {+ const HufDec pl = hdecod[(c << (HUF_DECBITS - lc)) & HUF_DECMASK];++ if (pl.len) {+ lc -= pl.len;+ if (!getCode(pl.lit, rlc, c, lc, in, ie, out, outb, oe)) {+ return false;+ }+ } else {+ return false;+ // invalidCode(); // wrong (long) code+ }+ }++ if (out - outb != no) {+ return false;+ }+ // notEnoughData ();++ return true;+}++static void countFrequencies(std::vector<long long> &freq,+ const unsigned short data[/*n*/], int n) {+ for (int i = 0; i < HUF_ENCSIZE; ++i) freq[i] = 0;++ for (int i = 0; i < n; ++i) ++freq[data[i]];+}++static void writeUInt(char buf[4], unsigned int i) {+ unsigned char *b = (unsigned char *)buf;++ b[0] = i;+ b[1] = i >> 8;+ b[2] = i >> 16;+ b[3] = i >> 24;+}++static unsigned int readUInt(const char buf[4]) {+ const unsigned char *b = (const unsigned char *)buf;++ return (b[0] & 0x000000ff) | ((b[1] << 8) & 0x0000ff00) |+ ((b[2] << 16) & 0x00ff0000) | ((b[3] << 24) & 0xff000000);+}++//+// EXTERNAL INTERFACE+//++static int hufCompress(const unsigned short raw[], int nRaw,+ char compressed[]) {+ if (nRaw == 0) return 0;++ std::vector<long long> freq(HUF_ENCSIZE);++ countFrequencies(freq, raw, nRaw);++ int im = 0;+ int iM = 0;+ hufBuildEncTable(freq.data(), &im, &iM);++ char *tableStart = compressed + 20;+ char *tableEnd = tableStart;+ hufPackEncTable(freq.data(), im, iM, &tableEnd);+ int tableLength = tableEnd - tableStart;++ char *dataStart = tableEnd;+ int nBits = hufEncode(freq.data(), raw, nRaw, iM, dataStart);+ int data_length = (nBits + 7) / 8;++ writeUInt(compressed, im);+ writeUInt(compressed + 4, iM);+ writeUInt(compressed + 8, tableLength);+ writeUInt(compressed + 12, nBits);+ writeUInt(compressed + 16, 0); // room for future extensions++ return dataStart + data_length - compressed;+}++static bool hufUncompress(const char compressed[], int nCompressed,+ std::vector<unsigned short> *raw) {+ if (nCompressed == 0) {+ if (raw->size() != 0) return false;++ return false;+ }++ int im = readUInt(compressed);+ int iM = readUInt(compressed + 4);+ // int tableLength = readUInt (compressed + 8);+ int nBits = readUInt(compressed + 12);++ if (im < 0 || im >= HUF_ENCSIZE || iM < 0 || iM >= HUF_ENCSIZE) return false;++ const char *ptr = compressed + 20;++ //+ // Fast decoder needs at least 2x64-bits of compressed data, and+ // needs to be run-able on this platform. Otherwise, fall back+ // to the original decoder+ //++ // if (FastHufDecoder::enabled() && nBits > 128)+ //{+ // FastHufDecoder fhd (ptr, nCompressed - (ptr - compressed), im, iM, iM);+ // fhd.decode ((unsigned char*)ptr, nBits, raw, nRaw);+ //}+ // else+ {+ std::vector<long long> freq(HUF_ENCSIZE);+ std::vector<HufDec> hdec(HUF_DECSIZE);++ hufClearDecTable(&hdec.at(0));++ hufUnpackEncTable(&ptr, nCompressed - (ptr - compressed), im, iM,+ &freq.at(0));++ {+ if (nBits > 8 * (nCompressed - (ptr - compressed))) {+ return false;+ }++ hufBuildDecTable(&freq.at(0), im, iM, &hdec.at(0));+ hufDecode(&freq.at(0), &hdec.at(0), ptr, nBits, iM, raw->size(),+ raw->data());+ }+ // catch (...)+ //{+ // hufFreeDecTable (hdec);+ // throw;+ //}++ hufFreeDecTable(&hdec.at(0));+ }++ return true;+}++//+// Functions to compress the range of values in the pixel data+//++const int USHORT_RANGE = (1 << 16);+const int BITMAP_SIZE = (USHORT_RANGE >> 3);++static void bitmapFromData(const unsigned short data[/*nData*/], int nData,+ unsigned char bitmap[BITMAP_SIZE],+ unsigned short &minNonZero,+ unsigned short &maxNonZero) {+ for (int i = 0; i < BITMAP_SIZE; ++i) bitmap[i] = 0;++ for (int i = 0; i < nData; ++i) bitmap[data[i] >> 3] |= (1 << (data[i] & 7));++ bitmap[0] &= ~1; // zero is not explicitly stored in+ // the bitmap; we assume that the+ // data always contain zeroes+ minNonZero = BITMAP_SIZE - 1;+ maxNonZero = 0;++ for (int i = 0; i < BITMAP_SIZE; ++i) {+ if (bitmap[i]) {+ if (minNonZero > i) minNonZero = i;+ if (maxNonZero < i) maxNonZero = i;+ }+ }+}++static unsigned short forwardLutFromBitmap(+ const unsigned char bitmap[BITMAP_SIZE], unsigned short lut[USHORT_RANGE]) {+ int k = 0;++ for (int i = 0; i < USHORT_RANGE; ++i) {+ if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7))))+ lut[i] = k++;+ else+ lut[i] = 0;+ }++ return k - 1; // maximum value stored in lut[],+} // i.e. number of ones in bitmap minus 1++static unsigned short reverseLutFromBitmap(+ const unsigned char bitmap[BITMAP_SIZE], unsigned short lut[USHORT_RANGE]) {+ int k = 0;++ for (int i = 0; i < USHORT_RANGE; ++i) {+ if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7)))) lut[k++] = i;+ }++ int n = k - 1;++ while (k < USHORT_RANGE) lut[k++] = 0;++ return n; // maximum k where lut[k] is non-zero,+} // i.e. number of ones in bitmap minus 1++static void applyLut(const unsigned short lut[USHORT_RANGE],+ unsigned short data[/*nData*/], int nData) {+ for (int i = 0; i < nData; ++i) data[i] = lut[data[i]];+}++#ifdef __clang__+#pragma clang diagnostic pop+#endif // __clang__++#ifdef _MSC_VER+#pragma warning(pop)+#endif++static bool CompressPiz(unsigned char *outPtr, unsigned int *outSize,+ const unsigned char *inPtr, size_t inSize,+ const std::vector<ChannelInfo> &channelInfo,+ int data_width, int num_lines) {+ std::vector<unsigned char> bitmap(BITMAP_SIZE);+ unsigned short minNonZero;+ unsigned short maxNonZero;++#if !TINYEXR_LITTLE_ENDIAN+ // @todo { PIZ compression on BigEndian architecture. }+ return false;+#endif++ // Assume `inSize` is multiple of 2 or 4.+ std::vector<unsigned short> tmpBuffer(inSize / sizeof(unsigned short));++ std::vector<PIZChannelData> channelData(channelInfo.size());+ unsigned short *tmpBufferEnd = &tmpBuffer.at(0);++ for (size_t c = 0; c < channelData.size(); c++) {+ PIZChannelData &cd = channelData[c];++ cd.start = tmpBufferEnd;+ cd.end = cd.start;++ cd.nx = data_width;+ cd.ny = num_lines;+ // cd.ys = c.channel().ySampling;++ size_t pixelSize = sizeof(int); // UINT and FLOAT+ if (channelInfo[c].requested_pixel_type == TINYEXR_PIXELTYPE_HALF) {+ pixelSize = sizeof(short);+ }++ cd.size = static_cast<int>(pixelSize / sizeof(short));++ tmpBufferEnd += cd.nx * cd.ny * cd.size;+ }++ const unsigned char *ptr = inPtr;+ for (int y = 0; y < num_lines; ++y) {+ for (size_t i = 0; i < channelData.size(); ++i) {+ PIZChannelData &cd = channelData[i];++ // if (modp (y, cd.ys) != 0)+ // continue;++ size_t n = static_cast<size_t>(cd.nx * cd.size);+ memcpy(cd.end, ptr, n * sizeof(unsigned short));+ ptr += n * sizeof(unsigned short);+ cd.end += n;+ }+ }++ bitmapFromData(&tmpBuffer.at(0), static_cast<int>(tmpBuffer.size()),+ bitmap.data(), minNonZero, maxNonZero);++ std::vector<unsigned short> lut(USHORT_RANGE);+ unsigned short maxValue = forwardLutFromBitmap(bitmap.data(), lut.data());+ applyLut(lut.data(), &tmpBuffer.at(0), static_cast<int>(tmpBuffer.size()));++ //+ // Store range compression info in _outBuffer+ //++ char *buf = reinterpret_cast<char *>(outPtr);++ memcpy(buf, &minNonZero, sizeof(unsigned short));+ buf += sizeof(unsigned short);+ memcpy(buf, &maxNonZero, sizeof(unsigned short));+ buf += sizeof(unsigned short);++ if (minNonZero <= maxNonZero) {+ memcpy(buf, reinterpret_cast<char *>(&bitmap[0] + minNonZero),+ maxNonZero - minNonZero + 1);+ buf += maxNonZero - minNonZero + 1;+ }++ //+ // Apply wavelet encoding+ //++ for (size_t i = 0; i < channelData.size(); ++i) {+ PIZChannelData &cd = channelData[i];++ for (int j = 0; j < cd.size; ++j) {+ wav2Encode(cd.start + j, cd.nx, cd.size, cd.ny, cd.nx * cd.size,+ maxValue);+ }+ }++ //+ // Apply Huffman encoding; append the result to _outBuffer+ //++ // length header(4byte), then huff data. Initialize length header with zero,+ // then later fill it by `length`.+ char *lengthPtr = buf;+ int zero = 0;+ memcpy(buf, &zero, sizeof(int));+ buf += sizeof(int);++ int length =+ hufCompress(&tmpBuffer.at(0), static_cast<int>(tmpBuffer.size()), buf);+ memcpy(lengthPtr, &length, sizeof(int));++ (*outSize) = static_cast<unsigned int>(+ (reinterpret_cast<unsigned char *>(buf) - outPtr) ++ static_cast<unsigned int>(length));++ // Use uncompressed data when compressed data is larger than uncompressed.+ // (Issue 40)+ if ((*outSize) >= inSize) {+ (*outSize) = static_cast<unsigned int>(inSize);+ memcpy(outPtr, inPtr, inSize);+ }+ return true;+}++static bool DecompressPiz(unsigned char *outPtr, const unsigned char *inPtr,+ size_t tmpBufSizeInBytes, size_t inLen, int num_channels,+ const EXRChannelInfo *channels, int data_width,+ int num_lines) {+ if (inLen == tmpBufSizeInBytes) {+ // Data is not compressed(Issue 40).+ memcpy(outPtr, inPtr, inLen);+ return true;+ }++ std::vector<unsigned char> bitmap(BITMAP_SIZE);+ unsigned short minNonZero;+ unsigned short maxNonZero;++#if !TINYEXR_LITTLE_ENDIAN+ // @todo { PIZ compression on BigEndian architecture. }+ return false;+#endif++ memset(bitmap.data(), 0, BITMAP_SIZE);++ if (inLen < 4) {+ return false;+ }++ size_t readLen = 0;++ const unsigned char *ptr = inPtr;+ // minNonZero = *(reinterpret_cast<const unsigned short *>(ptr));+ tinyexr::cpy2(&minNonZero, reinterpret_cast<const unsigned short *>(ptr));+ // maxNonZero = *(reinterpret_cast<const unsigned short *>(ptr + 2));+ tinyexr::cpy2(&maxNonZero, reinterpret_cast<const unsigned short *>(ptr + 2));+ ptr += 4;+ readLen += 4;++ if (maxNonZero >= BITMAP_SIZE) {+ return false;+ }++ //printf("maxNonZero = %d\n", maxNonZero);+ //printf("minNonZero = %d\n", minNonZero);+ //printf("len = %d\n", (maxNonZero - minNonZero + 1));+ //printf("BITMAPSIZE - min = %d\n", (BITMAP_SIZE - minNonZero));++ if (minNonZero <= maxNonZero) {+ if (((maxNonZero - minNonZero + 1) + readLen) > inLen) {+ // Input too short+ return false;+ }++ memcpy(reinterpret_cast<char *>(&bitmap[0] + minNonZero), ptr,+ maxNonZero - minNonZero + 1);+ ptr += maxNonZero - minNonZero + 1;+ readLen += maxNonZero - minNonZero + 1;+ } else {+ // Issue 194+ if ((minNonZero == (BITMAP_SIZE - 1)) && (maxNonZero == 0)) {+ // OK. all pixels are zero. And no need to read `bitmap` data.+ } else {+ // invalid minNonZero/maxNonZero combination.+ return false;+ }+ }++ std::vector<unsigned short> lut(USHORT_RANGE);+ memset(lut.data(), 0, sizeof(unsigned short) * USHORT_RANGE);+ unsigned short maxValue = reverseLutFromBitmap(bitmap.data(), lut.data());++ //+ // Huffman decoding+ //++ if ((readLen + 4) > inLen) {+ return false;+ }++ int length=0;++ // length = *(reinterpret_cast<const int *>(ptr));+ tinyexr::cpy4(&length, reinterpret_cast<const int *>(ptr));+ ptr += sizeof(int);++ if (size_t((ptr - inPtr) + length) > inLen) {+ return false;+ }++ std::vector<unsigned short> tmpBuffer(tmpBufSizeInBytes / sizeof(unsigned short));+ hufUncompress(reinterpret_cast<const char *>(ptr), length, &tmpBuffer);++ //+ // Wavelet decoding+ //++ std::vector<PIZChannelData> channelData(static_cast<size_t>(num_channels));++ unsigned short *tmpBufferEnd = &tmpBuffer.at(0);++ for (size_t i = 0; i < static_cast<size_t>(num_channels); ++i) {+ const EXRChannelInfo &chan = channels[i];++ size_t pixelSize = sizeof(int); // UINT and FLOAT+ if (chan.pixel_type == TINYEXR_PIXELTYPE_HALF) {+ pixelSize = sizeof(short);+ }++ channelData[i].start = tmpBufferEnd;+ channelData[i].end = channelData[i].start;+ channelData[i].nx = data_width;+ channelData[i].ny = num_lines;+ // channelData[i].ys = 1;+ channelData[i].size = static_cast<int>(pixelSize / sizeof(short));++ tmpBufferEnd += channelData[i].nx * channelData[i].ny * channelData[i].size;+ }++ for (size_t i = 0; i < channelData.size(); ++i) {+ PIZChannelData &cd = channelData[i];++ for (int j = 0; j < cd.size; ++j) {+ wav2Decode(cd.start + j, cd.nx, cd.size, cd.ny, cd.nx * cd.size,+ maxValue);+ }+ }++ //+ // Expand the pixel data to their original range+ //++ applyLut(lut.data(), &tmpBuffer.at(0), static_cast<int>(tmpBufSizeInBytes / sizeof(unsigned short)));++ for (int y = 0; y < num_lines; y++) {+ for (size_t i = 0; i < channelData.size(); ++i) {+ PIZChannelData &cd = channelData[i];++ // if (modp (y, cd.ys) != 0)+ // continue;++ size_t n = static_cast<size_t>(cd.nx * cd.size);+ memcpy(outPtr, cd.end, static_cast<size_t>(n * sizeof(unsigned short)));+ outPtr += n * sizeof(unsigned short);+ cd.end += n;+ }+ }++ return true;+}+#endif // TINYEXR_USE_PIZ++// ============================================================================+// PXR24 decompression+// ============================================================================++// PXR24 stores 32-bit floats as 24-bit values (truncates 8 mantissa bits)+// HALF and UINT are stored without modification+static bool DecompressPxr24(unsigned char *outPtr, size_t outBufSize,+ const unsigned char *inPtr, size_t inLen,+ int data_width, int num_lines,+ size_t num_channels,+ const EXRChannelInfo *channels) {+ // Calculate the PXR24 data size after zlib decompression+ // PXR24 stores HALF as 2 bytes, UINT as 4 bytes, FLOAT as 3 bytes+ // Data is stored with byte plane separation and delta encoding+ size_t pxr24_size = 0;+ for (size_t c = 0; c < num_channels; c++) {+ int ch_width = data_width; // V1 doesn't handle subsampling in decompression+ int ch_pixels = ch_width * num_lines;++ if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {+ pxr24_size += static_cast<size_t>(ch_pixels) * 4;+ } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {+ pxr24_size += static_cast<size_t>(ch_pixels) * 2;+ } else { // FLOAT+ pxr24_size += static_cast<size_t>(ch_pixels) * 3;+ }+ }++ // Allocate buffer for zlib-decompressed PXR24 data+ std::vector<unsigned char> pxr24_buf(pxr24_size);+ size_t uncomp_size = pxr24_size;++ // PXR24 uses raw zlib compression+ if (pxr24_size == inLen) {+ // Uncompressed - copy directly+ memcpy(pxr24_buf.data(), inPtr, inLen);+ } else {+#if defined(TINYEXR_USE_MINIZ) && (TINYEXR_USE_MINIZ==1)+ mz_ulong dest_len = static_cast<mz_ulong>(pxr24_size);+ int ret = mz_uncompress(pxr24_buf.data(), &dest_len, inPtr, static_cast<mz_ulong>(inLen));+ if (ret != MZ_OK) {+ return false;+ }+ uncomp_size = static_cast<size_t>(dest_len);+#elif defined(TINYEXR_USE_STB_ZLIB) && (TINYEXR_USE_STB_ZLIB==1)+ int outLen = stbi_zlib_decode_buffer(reinterpret_cast<char*>(pxr24_buf.data()),+ static_cast<int>(pxr24_size), reinterpret_cast<const char*>(inPtr), static_cast<int>(inLen));+ if (outLen < 0) {+ return false;+ }+ uncomp_size = static_cast<size_t>(outLen);+#elif defined(TINYEXR_USE_NANOZLIB) && (TINYEXR_USE_NANOZLIB==1)+ uint64_t outLen = 0;+ nanoz_status_t ret = nanoz_uncompress(inPtr, inLen, pxr24_size, pxr24_buf.data(), &outLen);+ if (ret != NANOZ_SUCCESS) {+ return false;+ }+ uncomp_size = static_cast<size_t>(outLen);+#else+ uLongf dest_len = static_cast<uLongf>(pxr24_size);+ int ret = uncompress(pxr24_buf.data(), &dest_len, inPtr, static_cast<uLong>(inLen));+ if (ret != Z_OK) {+ return false;+ }+ uncomp_size = static_cast<size_t>(dest_len);+#endif+ }++ if (uncomp_size != pxr24_size) {+ return false;+ }++ // Convert PXR24 format to standard EXR format+ // PXR24 uses:+ // 1. Byte plane separation: bytes are stored by plane (all high bytes, then next-high, etc.)+ // 2. Delta encoding: each pixel is stored as difference from previous pixel+ const unsigned char* in_p = pxr24_buf.data();+ unsigned char* out_p = outPtr;++ for (int line = 0; line < num_lines; line++) {+ for (size_t c = 0; c < num_channels; c++) {+ int w = data_width;++ if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {+ // UINT: 4 byte planes with delta encoding+ const unsigned char* ptr0 = in_p;+ const unsigned char* ptr1 = in_p + w;+ const unsigned char* ptr2 = in_p + w * 2;+ const unsigned char* ptr3 = in_p + w * 3;+ in_p += w * 4;++ unsigned int pixel = 0;+ for (int x = 0; x < w; x++) {+ unsigned int diff = (static_cast<unsigned int>(ptr0[x]) << 24) |+ (static_cast<unsigned int>(ptr1[x]) << 16) |+ (static_cast<unsigned int>(ptr2[x]) << 8) |+ (static_cast<unsigned int>(ptr3[x]));+ pixel += diff;+ memcpy(out_p, &pixel, 4);+ out_p += 4;+ }+ } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {+ // HALF: 2 byte planes with delta encoding+ const unsigned char* ptr0 = in_p;+ const unsigned char* ptr1 = in_p + w;+ in_p += w * 2;++ unsigned int pixel = 0;+ for (int x = 0; x < w; x++) {+ unsigned int diff = (static_cast<unsigned int>(ptr0[x]) << 8) |+ (static_cast<unsigned int>(ptr1[x]));+ pixel += diff;+ unsigned short h = static_cast<unsigned short>(pixel);+ memcpy(out_p, &h, 2);+ out_p += 2;+ }+ } else { // FLOAT+ // FLOAT: 3 byte planes with delta encoding, expand to 32-bit+ const unsigned char* ptr0 = in_p;+ const unsigned char* ptr1 = in_p + w;+ const unsigned char* ptr2 = in_p + w * 2;+ in_p += w * 3;++ unsigned int pixel = 0;+ for (int x = 0; x < w; x++) {+ // PXR24 stores 24-bit floats with delta encoding+ // The diff is in the upper 24 bits+ unsigned int diff = (static_cast<unsigned int>(ptr0[x]) << 24) |+ (static_cast<unsigned int>(ptr1[x]) << 16) |+ (static_cast<unsigned int>(ptr2[x]) << 8);+ pixel += diff;+ memcpy(out_p, &pixel, 4);+ out_p += 4;+ }+ }+ }+ }++ return true;+}++// ============================================================================+// B44/B44A decompression+// ============================================================================++// B44 compresses 4x4 blocks of HALF values to 14 bytes+// B44A can compress flat regions to 3 bytes++// B44 lookup tables+// expTable: converts half-float value to exp(half/8) for p_linear channels+// logTable: converts half-float value to 8*log(half) for p_linear channels+// Note: These tables are primarily for luminance channels with p_linear attribute+static unsigned short g_b44_exp_table[65536];+static unsigned short g_b44_log_table[65536];+static bool g_b44_tables_initialized = false;++// Half-float conversion helpers for B44 table initialization+static inline float B44HalfToFloat(unsigned short h) {+ union { unsigned int i; float f; } u;++ int s = (h >> 15) & 0x1;+ int e = (h >> 10) & 0x1f;+ int m = h & 0x3ff;++ if (e == 0) {+ if (m == 0) {+ // Zero+ u.i = s << 31;+ return u.f;+ }+ // Denormal+ float f = (float)m / 1024.0f;+ f = f * (1.0f / 16384.0f); // 2^-14+ return s ? -f : f;+ } else if (e == 31) {+ // Inf or NaN+ u.i = (s << 31) | 0x7f800000 | (m << 13);+ return u.f;+ }++ // Normal+ u.i = (s << 31) | ((e + 112) << 23) | (m << 13);+ return u.f;+}++static inline unsigned short B44FloatToHalf(float f) {+ union { unsigned int i; float f; } u;+ u.f = f;++ int s = (u.i >> 31) & 0x1;+ int e = (u.i >> 23) & 0xff;+ int m = u.i & 0x7fffff;++ if (e == 0) {+ return static_cast<unsigned short>(s << 15); // Zero+ } else if (e == 255) {+ // Inf or NaN+ return static_cast<unsigned short>((s << 15) | 0x7c00 | (m >> 13));+ } else if (e < 113) {+ // Too small - denormal or zero+ if (e < 103) return static_cast<unsigned short>(s << 15);+ m = (m | 0x800000) >> (114 - e);+ return static_cast<unsigned short>((s << 15) | (m >> 13));+ } else if (e > 142) {+ // Too large - infinity+ return static_cast<unsigned short>((s << 15) | 0x7c00);+ }++ return static_cast<unsigned short>((s << 15) | ((e - 112) << 10) | (m >> 13));+}++// Initialize B44 exp/log lookup tables (matches OpenEXR algorithm)+static void InitB44Tables() {+ if (g_b44_tables_initialized) return;++ // Generate tables per OpenEXR's b44_table_init.c+ for (int i = 0; i < 65536; i++) {+ unsigned short x = static_cast<unsigned short>(i);++ // expTable: convertFromLinear - exp(half / 8)+ if ((x & 0x7c00) == 0x7c00) {+ // infinity/nan -> 0+ g_b44_exp_table[i] = 0;+ } else if (x >= 0x558c && x < 0x8000) {+ // >= 8 * log(HALF_MAX) -> HALF_MAX+ g_b44_exp_table[i] = 0x7bff;+ } else {+ float f = B44HalfToFloat(x);+ f = static_cast<float>(std::exp(static_cast<double>(f) / 8.0));+ g_b44_exp_table[i] = B44FloatToHalf(f);+ }++ // logTable: convertToLinear - 8 * log(half)+ if ((x & 0x7c00) == 0x7c00) {+ // infinity/nan -> 0+ g_b44_log_table[i] = 0;+ } else if (x > 0x8000) {+ // negative (excluding -0.0) -> 0+ g_b44_log_table[i] = 0;+ } else {+ float f = B44HalfToFloat(x);+ if (f <= 0.0f) {+ g_b44_log_table[i] = 0;+ } else {+ f = static_cast<float>(8.0 * std::log(static_cast<double>(f)));+ g_b44_log_table[i] = B44FloatToHalf(f);+ }+ }+ }++ g_b44_tables_initialized = true;+}++// Convert half to linear-log space (for p_linear channels)+static inline unsigned short B44ConvertFromLinear(unsigned short h) {+ return g_b44_exp_table[h];+}++// Convert linear-log back to half (for p_linear channels)+static inline unsigned short B44ConvertToLinear(unsigned short h) {+ return g_b44_log_table[h];+}++// Unpack one 4x4 block from B44 compressed 14 bytes (matches OpenEXR unpack14)+static void UnpackB44Block(unsigned short dst[16], const unsigned char src[14]) {+ // Extract t[0] (stored as ordered-magnitude value)+ unsigned short s0 = (static_cast<unsigned short>(src[0]) << 8) | src[1];++ // Extract shift and compute bias+ unsigned short shift = src[2] >> 2;+ unsigned short bias = static_cast<unsigned short>(0x20u << shift);++ // Reconstruct t values using running differences+ // Pattern: s[0]->s[4]->s[8]->s[12], then s[0]->s[1], s[4]->s[5], etc.++ unsigned short s4 = static_cast<unsigned short>(+ static_cast<unsigned int>(s0) ++ static_cast<unsigned int>(((static_cast<unsigned int>(src[2]) << 4) |+ (static_cast<unsigned int>(src[3]) >> 4)) & 0x3fu) * (1u << shift) - bias);++ unsigned short s8 = static_cast<unsigned short>(+ static_cast<unsigned int>(s4) ++ static_cast<unsigned int>(((static_cast<unsigned int>(src[3]) << 2) |+ (static_cast<unsigned int>(src[4]) >> 6)) & 0x3fu) * (1u << shift) - bias);++ unsigned short s12 = static_cast<unsigned short>(+ static_cast<unsigned int>(s8) ++ static_cast<unsigned int>(src[4] & 0x3fu) * (1u << shift) - bias);++ unsigned short s1 = static_cast<unsigned short>(+ static_cast<unsigned int>(s0) ++ static_cast<unsigned int>(src[5] >> 2) * (1u << shift) - bias);++ unsigned short s5 = static_cast<unsigned short>(+ static_cast<unsigned int>(s4) ++ static_cast<unsigned int>(((static_cast<unsigned int>(src[5]) << 4) |+ (static_cast<unsigned int>(src[6]) >> 4)) & 0x3fu) * (1u << shift) - bias);++ unsigned short s9 = static_cast<unsigned short>(+ static_cast<unsigned int>(s8) ++ static_cast<unsigned int>(((static_cast<unsigned int>(src[6]) << 2) |+ (static_cast<unsigned int>(src[7]) >> 6)) & 0x3fu) * (1u << shift) - bias);++ unsigned short s13 = static_cast<unsigned short>(+ static_cast<unsigned int>(s12) ++ static_cast<unsigned int>(src[7] & 0x3fu) * (1u << shift) - bias);++ unsigned short s2 = static_cast<unsigned short>(+ static_cast<unsigned int>(s1) ++ static_cast<unsigned int>(src[8] >> 2) * (1u << shift) - bias);++ unsigned short s6 = static_cast<unsigned short>(+ static_cast<unsigned int>(s5) ++ static_cast<unsigned int>(((static_cast<unsigned int>(src[8]) << 4) |+ (static_cast<unsigned int>(src[9]) >> 4)) & 0x3fu) * (1u << shift) - bias);++ unsigned short s10 = static_cast<unsigned short>(+ static_cast<unsigned int>(s9) ++ static_cast<unsigned int>(((static_cast<unsigned int>(src[9]) << 2) |+ (static_cast<unsigned int>(src[10]) >> 6)) & 0x3fu) * (1u << shift) - bias);++ unsigned short s14 = static_cast<unsigned short>(+ static_cast<unsigned int>(s13) ++ static_cast<unsigned int>(src[10] & 0x3fu) * (1u << shift) - bias);++ unsigned short s3 = static_cast<unsigned short>(+ static_cast<unsigned int>(s2) ++ static_cast<unsigned int>(src[11] >> 2) * (1u << shift) - bias);++ unsigned short s7 = static_cast<unsigned short>(+ static_cast<unsigned int>(s6) ++ static_cast<unsigned int>(((static_cast<unsigned int>(src[11]) << 4) |+ (static_cast<unsigned int>(src[12]) >> 4)) & 0x3fu) * (1u << shift) - bias);++ unsigned short s11 = static_cast<unsigned short>(+ static_cast<unsigned int>(s10) ++ static_cast<unsigned int>(((static_cast<unsigned int>(src[12]) << 2) |+ (static_cast<unsigned int>(src[13]) >> 6)) & 0x3fu) * (1u << shift) - bias);++ unsigned short s15 = static_cast<unsigned short>(+ static_cast<unsigned int>(s14) ++ static_cast<unsigned int>(src[13] & 0x3fu) * (1u << shift) - bias);++ // Store t values+ dst[0] = s0; dst[1] = s1; dst[2] = s2; dst[3] = s3;+ dst[4] = s4; dst[5] = s5; dst[6] = s6; dst[7] = s7;+ dst[8] = s8; dst[9] = s9; dst[10] = s10; dst[11] = s11;+ dst[12] = s12; dst[13] = s13; dst[14] = s14; dst[15] = s15;++ // Convert from ordered-magnitude to half-float+ for (int i = 0; i < 16; i++) {+ if (dst[i] & 0x8000) {+ dst[i] &= 0x7fff; // Positive: clear sign bit+ } else {+ dst[i] = ~dst[i]; // Negative: invert all bits+ }+ }+}++// Unpack a 3-byte flat block (all pixels same value)+static void UnpackB44FlatBlock(unsigned short dst[16], const unsigned char src[3]) {+ unsigned short t = (static_cast<unsigned short>(src[0]) << 8) | src[1];++ // Convert from ordered-magnitude to half-float+ unsigned short h;+ if (t & 0x8000) {+ h = t & 0x7fff;+ } else {+ h = ~t;+ }++ for (int i = 0; i < 16; i++) {+ dst[i] = h;+ }+}++static bool DecompressB44(unsigned char *outPtr, size_t outBufSize,+ const unsigned char *inPtr, size_t inLen,+ int data_width, int num_lines,+ size_t num_channels,+ const EXRChannelInfo *channels,+ bool is_b44a) {+ (void)is_b44a; // Flat block detection doesn't depend on B44/B44A for decoding+ InitB44Tables();++ // Validate that the output buffer is large enough for the decoded data.+ // Use overflow-safe arithmetic: overflow in any multiplication or accumulation+ // means the size cannot fit in memory, which is definitely > outBufSize.+ {+ size_t expected_out = 0;+ for (size_t c = 0; c < num_channels; c++) {+ int xs = channels[c].x_sampling > 0 ? channels[c].x_sampling : 1;+ int ys = channels[c].y_sampling > 0 ? channels[c].y_sampling : 1;+ size_t cw = static_cast<size_t>((data_width + xs - 1) / xs);+ size_t ch = static_cast<size_t>((num_lines + ys - 1) / ys);+ size_t bpp = (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) ? 2u : 4u;+ // Check cw * ch overflow+ if (cw != 0 && ch > (SIZE_MAX / cw)) return false;+ size_t pixels = cw * ch;+ // Check pixels * bpp overflow+ if (pixels > (SIZE_MAX / bpp)) return false;+ size_t ch_total = pixels * bpp;+ // Check accumulation overflow+ if (expected_out > SIZE_MAX - ch_total) return false;+ expected_out += ch_total;+ }+ if (expected_out > outBufSize) return false;+ }++ const unsigned char* in_p = inPtr;+ const unsigned char* in_end = inPtr + inLen;++ // First pass: decompress all channels into scratch buffers.+ // For non-HALF channels, save the pointer and byte count so we can copy+ // the raw data to the output buffer in the second pass.+ std::vector<std::vector<unsigned short>> scratch_buffers(num_channels);+ std::vector<const unsigned char *> nonhalf_ptrs(num_channels, nullptr);+ std::vector<size_t> nonhalf_sizes(num_channels, 0);++ for (size_t c = 0; c < num_channels; c++) {+ // Compute per-channel dimensions based on sampling+ int x_sampling = channels[c].x_sampling > 0 ? channels[c].x_sampling : 1;+ int y_sampling = channels[c].y_sampling > 0 ? channels[c].y_sampling : 1;+ int ch_width = (data_width + x_sampling - 1) / x_sampling;+ int ch_height = (num_lines + y_sampling - 1) / y_sampling;++ // B44 only works with HALF pixel types+ if (channels[c].pixel_type != TINYEXR_PIXELTYPE_HALF) {+ // For non-HALF channels, data is stored uncompressed; record position+ size_t ch_bytes = static_cast<size_t>(ch_width) * ch_height;+ if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT ||+ channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {+ ch_bytes *= 4;+ } else {+ ch_bytes *= 2;+ }+ if (in_p + ch_bytes > in_end) return false;+ nonhalf_ptrs[c] = in_p;+ nonhalf_sizes[c] = ch_bytes;+ in_p += ch_bytes;+ continue;+ }++ // Calculate block dimensions (rounded up to multiple of 4)+ int padded_width = ((ch_width + 3) / 4) * 4;+ int padded_height = ((ch_height + 3) / 4) * 4;+ int num_blocks_x = padded_width / 4;+ int num_blocks_y = padded_height / 4;++ // Allocate scratch buffer for this channel+ scratch_buffers[c].resize(static_cast<size_t>(padded_width) * padded_height);++ // Process blocks+ for (int by = 0; by < num_blocks_y; by++) {+ for (int bx = 0; bx < num_blocks_x; bx++) {+ unsigned short block[16];++ if (in_p + 3 > in_end) return false;++ // Check for flat block (shift >= 13)+ if (in_p[2] >= (13 << 2)) {+ // 3-byte flat block+ UnpackB44FlatBlock(block, in_p);+ in_p += 3;+ } else {+ // Regular 14-byte block+ if (in_p + 14 > in_end) return false;+ UnpackB44Block(block, in_p);+ in_p += 14;+ }++ // Apply p_linear conversion (log table) if needed+ if (channels[c].p_linear) {+ for (int i = 0; i < 16; i++) {+ block[i] = g_b44_log_table[block[i]];+ }+ }++ // Store block in scratch buffer+ for (int dy = 0; dy < 4; dy++) {+ int y = by * 4 + dy;+ for (int dx = 0; dx < 4; dx++) {+ int x = bx * 4 + dx;+ scratch_buffers[c][static_cast<size_t>(y) * padded_width + x] = block[dy * 4 + dx];+ }+ }+ }+ }+ }++ // Second pass: copy from scratch buffers to output in per-channel format.+ // Output format: all data for channel 0, then all data for channel 1, etc.+ // ch_offset in DecodePixelData is accumulated per preceding channel sizes.+ unsigned char* out_p = outPtr;+ for (size_t c = 0; c < num_channels; c++) {+ int x_sampling = channels[c].x_sampling > 0 ? channels[c].x_sampling : 1;+ int y_sampling = channels[c].y_sampling > 0 ? channels[c].y_sampling : 1;+ int ch_width = (data_width + x_sampling - 1) / x_sampling;+ int ch_height = (num_lines + y_sampling - 1) / y_sampling;+ int padded_width = ((ch_width + 3) / 4) * 4;++ if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {+ for (int y = 0; y < ch_height; y++) {+ for (int x = 0; x < ch_width; x++) {+ unsigned short val = scratch_buffers[c][static_cast<size_t>(y) * padded_width + x];+ // Write as little-endian bytes so DecodePixelData's swap2 (LE->host)+ // works correctly on both little- and big-endian platforms.+ tinyexr::swap2(&val);+ memcpy(out_p, &val, sizeof(val));+ out_p += sizeof(val);+ }+ }+ } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT ||+ channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {+ // Non-HALF data is stored uncompressed; copy from saved pointer+ if (nonhalf_sizes[c] > 0) {+ memcpy(out_p, nonhalf_ptrs[c], nonhalf_sizes[c]);+ out_p += nonhalf_sizes[c];+ }+ }+ }++ return true;+}++// ============================================================================+// PXR24 compression (encoding)+// ============================================================================++// Convert float32 to float24 (PXR24 format)+static inline unsigned int float_to_float24(float f) {+ union { float f; unsigned int i; } u;+ u.f = f;++ unsigned int s = u.i & 0x80000000;+ unsigned int e = u.i & 0x7f800000;+ unsigned int m = u.i & 0x007fffff;++ if (e == 0x7f800000) {+ if (m) {+ // NaN - preserve sign and 15 leftmost mantissa bits+ m >>= 8;+ return (s >> 8) | (e >> 8) | m | (m == 0 ? 1 : 0);+ } else {+ // Infinity+ return (s >> 8) | (e >> 8);+ }+ }++ // Finite - round mantissa to 15 bits+ unsigned int i = ((e | m) + (m & 0x00000080)) >> 8;++ if (i >= 0x7f8000) {+ // Overflow - truncate instead of round+ i = (e | m) >> 8;+ }++ return (s >> 8) | i;+}++static bool CompressPxr24(std::vector<unsigned char>& outBuf,+ const unsigned char *inPtr, size_t inLen,+ int data_width, int num_lines,+ size_t num_channels,+ const EXRChannelInfo *channels) {+ // PXR24 stores HALF as 2 bytes, UINT as 4 bytes, FLOAT as 3 bytes (truncated)+ // Data is stored with byte plane separation and delta encoding+ size_t pxr24_size = 0;+ for (size_t c = 0; c < num_channels; c++) {+ int ch_pixels = data_width * num_lines;++ if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {+ pxr24_size += static_cast<size_t>(ch_pixels) * 4;+ } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {+ pxr24_size += static_cast<size_t>(ch_pixels) * 2;+ } else { // FLOAT+ pxr24_size += static_cast<size_t>(ch_pixels) * 3;+ }+ }++ // Create PXR24 format data+ std::vector<unsigned char> pxr24_buf(pxr24_size);+ const unsigned char* in_p = inPtr;+ unsigned char* out_p = pxr24_buf.data();++ // PXR24 uses:+ // 1. Byte plane separation: bytes are stored by plane (all high bytes, then next-high, etc.)+ // 2. Delta encoding: each pixel is stored as difference from previous pixel+ for (int line = 0; line < num_lines; line++) {+ for (size_t c = 0; c < num_channels; c++) {+ int w = data_width;++ if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {+ // UINT: 4 byte planes with delta encoding+ unsigned char* ptr0 = out_p;+ unsigned char* ptr1 = out_p + w;+ unsigned char* ptr2 = out_p + w * 2;+ unsigned char* ptr3 = out_p + w * 3;+ out_p += w * 4;++ unsigned int prevPixel = 0;+ for (int x = 0; x < w; x++) {+ unsigned int pixel;+ memcpy(&pixel, in_p, 4);+ in_p += 4;+ unsigned int diff = pixel - prevPixel;+ prevPixel = pixel;++ ptr0[x] = static_cast<unsigned char>(diff >> 24);+ ptr1[x] = static_cast<unsigned char>(diff >> 16);+ ptr2[x] = static_cast<unsigned char>(diff >> 8);+ ptr3[x] = static_cast<unsigned char>(diff);+ }+ } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {+ // HALF: 2 byte planes with delta encoding+ unsigned char* ptr0 = out_p;+ unsigned char* ptr1 = out_p + w;+ out_p += w * 2;++ unsigned int prevPixel = 0;+ for (int x = 0; x < w; x++) {+ unsigned short h;+ memcpy(&h, in_p, 2);+ in_p += 2;+ unsigned int pixel = h;+ unsigned int diff = pixel - prevPixel;+ prevPixel = pixel;++ ptr0[x] = static_cast<unsigned char>(diff >> 8);+ ptr1[x] = static_cast<unsigned char>(diff);+ }+ } else { // FLOAT+ // FLOAT: convert to 24-bit, then 3 byte planes with delta encoding+ unsigned char* ptr0 = out_p;+ unsigned char* ptr1 = out_p + w;+ unsigned char* ptr2 = out_p + w * 2;+ out_p += w * 3;++ unsigned int prevPixel = 0;+ for (int x = 0; x < w; x++) {+ float f;+ memcpy(&f, in_p, 4);+ in_p += 4;+ unsigned int pixel24 = float_to_float24(f);+ unsigned int diff = pixel24 - prevPixel;+ prevPixel = pixel24;++ // Store as 24-bit diff (shifted to upper bits for proper reconstruction)+ ptr0[x] = static_cast<unsigned char>(diff >> 16);+ ptr1[x] = static_cast<unsigned char>(diff >> 8);+ ptr2[x] = static_cast<unsigned char>(diff);+ }+ }+ }+ }++ // Compress with zlib+#if defined(TINYEXR_USE_MINIZ) && (TINYEXR_USE_MINIZ==1)+ mz_ulong dest_len = mz_compressBound(static_cast<mz_ulong>(pxr24_size));+ outBuf.resize(dest_len);+ int ret = mz_compress(outBuf.data(), &dest_len, pxr24_buf.data(), static_cast<mz_ulong>(pxr24_size));+ if (ret != MZ_OK) {+ return false;+ }+ outBuf.resize(static_cast<size_t>(dest_len));+#elif defined(TINYEXR_USE_STB_ZLIB) && (TINYEXR_USE_STB_ZLIB==1)+ int outSize;+ unsigned char* ret = stbi_zlib_compress(pxr24_buf.data(), static_cast<int>(pxr24_size), &outSize, 8);+ if (!ret) {+ return false;+ }+ outBuf.assign(ret, ret + outSize);+ free(ret);+#elif defined(TINYEXR_USE_NANOZLIB) && (TINYEXR_USE_NANOZLIB==1)+ int outSize;+ unsigned char* ret = nanoz_compress(pxr24_buf.data(), pxr24_size, &outSize, 8);+ if (!ret) {+ return false;+ }+ outBuf.assign(ret, ret + outSize);+ free(ret);+#else+ uLongf dest_len = compressBound(static_cast<uLong>(pxr24_size));+ outBuf.resize(static_cast<size_t>(dest_len));+ int ret = compress(outBuf.data(), &dest_len, pxr24_buf.data(), static_cast<uLong>(pxr24_size));+ if (ret != Z_OK) {+ return false;+ }+ outBuf.resize(static_cast<size_t>(dest_len));+#endif++ return true;+}++// Overloaded version that takes ChannelInfo instead of EXRChannelInfo+// Note: Uses requested_pixel_type which is the file format, not the input type+static bool CompressPxr24(std::vector<unsigned char>& outBuf,+ const unsigned char *inPtr, size_t inLen,+ int data_width, int num_lines,+ size_t num_channels,+ const std::vector<ChannelInfo>& channels) {+ // PXR24 stores HALF as 2 bytes, UINT as 4 bytes, FLOAT as 3 bytes (truncated)+ // Data is stored with byte plane separation and delta encoding+ // Use requested_pixel_type which is the actual format in the file+ size_t pxr24_size = 0;+ for (size_t c = 0; c < num_channels; c++) {+ int ch_pixels = data_width * num_lines;+ int file_type = channels[c].requested_pixel_type;++ if (file_type == TINYEXR_PIXELTYPE_UINT) {+ pxr24_size += static_cast<size_t>(ch_pixels) * 4;+ } else if (file_type == TINYEXR_PIXELTYPE_HALF) {+ pxr24_size += static_cast<size_t>(ch_pixels) * 2;+ } else { // FLOAT+ pxr24_size += static_cast<size_t>(ch_pixels) * 3;+ }+ }++ // Create PXR24 format data+ std::vector<unsigned char> pxr24_buf(pxr24_size);+ const unsigned char* in_p = inPtr;+ unsigned char* out_p = pxr24_buf.data();++ // PXR24 uses:+ // 1. Byte plane separation: bytes are stored by plane (all high bytes, then next-high, etc.)+ // 2. Delta encoding: each pixel is stored as difference from previous pixel+ for (int line = 0; line < num_lines; line++) {+ for (size_t c = 0; c < num_channels; c++) {+ int w = data_width;+ int file_type = channels[c].requested_pixel_type;++ if (file_type == TINYEXR_PIXELTYPE_UINT) {+ // UINT: 4 byte planes with delta encoding+ unsigned char* ptr0 = out_p;+ unsigned char* ptr1 = out_p + w;+ unsigned char* ptr2 = out_p + w * 2;+ unsigned char* ptr3 = out_p + w * 3;+ out_p += w * 4;++ unsigned int prevPixel = 0;+ for (int x = 0; x < w; x++) {+ unsigned int pixel;+ memcpy(&pixel, in_p, 4);+ in_p += 4;+ unsigned int diff = pixel - prevPixel;+ prevPixel = pixel;++ ptr0[x] = static_cast<unsigned char>(diff >> 24);+ ptr1[x] = static_cast<unsigned char>(diff >> 16);+ ptr2[x] = static_cast<unsigned char>(diff >> 8);+ ptr3[x] = static_cast<unsigned char>(diff);+ }+ } else if (file_type == TINYEXR_PIXELTYPE_HALF) {+ // HALF: 2 byte planes with delta encoding+ unsigned char* ptr0 = out_p;+ unsigned char* ptr1 = out_p + w;+ out_p += w * 2;++ unsigned int prevPixel = 0;+ for (int x = 0; x < w; x++) {+ unsigned short h;+ memcpy(&h, in_p, 2);+ in_p += 2;+ unsigned int pixel = h;+ unsigned int diff = pixel - prevPixel;+ prevPixel = pixel;++ ptr0[x] = static_cast<unsigned char>(diff >> 8);+ ptr1[x] = static_cast<unsigned char>(diff);+ }+ } else { // FLOAT+ // FLOAT: convert to 24-bit, then 3 byte planes with delta encoding+ unsigned char* ptr0 = out_p;+ unsigned char* ptr1 = out_p + w;+ unsigned char* ptr2 = out_p + w * 2;+ out_p += w * 3;++ unsigned int prevPixel = 0;+ for (int x = 0; x < w; x++) {+ float f;+ memcpy(&f, in_p, 4);+ in_p += 4;+ unsigned int pixel24 = float_to_float24(f);+ unsigned int diff = pixel24 - prevPixel;+ prevPixel = pixel24;++ // Store as 24-bit diff (shifted to upper bits for proper reconstruction)+ ptr0[x] = static_cast<unsigned char>(diff >> 16);+ ptr1[x] = static_cast<unsigned char>(diff >> 8);+ ptr2[x] = static_cast<unsigned char>(diff);+ }+ }+ }+ }++ // Compress with zlib+#if defined(TINYEXR_USE_MINIZ) && (TINYEXR_USE_MINIZ==1)+ mz_ulong dest_len = mz_compressBound(static_cast<mz_ulong>(pxr24_size));+ outBuf.resize(dest_len);+ int ret = mz_compress(outBuf.data(), &dest_len, pxr24_buf.data(), static_cast<mz_ulong>(pxr24_size));+ if (ret != MZ_OK) {+ return false;+ }+ outBuf.resize(static_cast<size_t>(dest_len));+#elif defined(TINYEXR_USE_STB_ZLIB) && (TINYEXR_USE_STB_ZLIB==1)+ int outSize;+ unsigned char* ret = stbi_zlib_compress(pxr24_buf.data(), static_cast<int>(pxr24_size), &outSize, 8);+ if (!ret) {+ return false;+ }+ outBuf.assign(ret, ret + outSize);+ free(ret);+#elif defined(TINYEXR_USE_NANOZLIB) && (TINYEXR_USE_NANOZLIB==1)+ int outSize;+ unsigned char* ret = nanoz_compress(pxr24_buf.data(), pxr24_size, &outSize, 8);+ if (!ret) {+ return false;+ }+ outBuf.assign(ret, ret + outSize);+ free(ret);+#else+ uLongf dest_len = compressBound(static_cast<uLong>(pxr24_size));+ outBuf.resize(static_cast<size_t>(dest_len));+ int ret = compress(outBuf.data(), &dest_len, pxr24_buf.data(), static_cast<uLong>(pxr24_size));+ if (ret != Z_OK) {+ return false;+ }+ outBuf.resize(static_cast<size_t>(dest_len));+#endif++ return true;+}++// ============================================================================+// B44/B44A compression (encoding)+// ============================================================================++// Shift and round for B44 pack (matches OpenEXR's shiftAndRound)+static inline int B44ShiftAndRound(int x, int shift) {+ // Compute y = x * pow(2, -shift), rounded to nearest integer+ // In case of a tie, round to the even one+ x <<= 1;+ int a = (1 << shift) - 1;+ shift += 1;+ int b = (x >> shift) & 1;+ return (x + a + b) >> shift;+}++// Pack a 4x4 block of HALF values into 14 bytes (matches OpenEXR's pack())+// Returns the number of bytes written (14 for normal, 3 for flat if flatfields=true)+static int PackB44Block(unsigned char* out, const unsigned short* block, bool flatfields, bool exactmax) {+ int d[16];+ int r[15];+ int rMin, rMax;+ unsigned short t[16];+ unsigned short tMax;+ int shift = -1;++ const int bias = 0x20;++ // Convert half-float values to ordered-magnitude representation+ // This ensures that if t[i] > t[j], then half[i] > half[j] as floats+ for (int i = 0; i < 16; ++i) {+ if ((block[i] & 0x7c00) == 0x7c00) {+ t[i] = 0x8000; // NaN/Inf -> neutral value+ } else if (block[i] & 0x8000) {+ t[i] = ~block[i]; // Negative: invert all bits+ } else {+ t[i] = block[i] | 0x8000; // Positive: set sign bit+ }+ }++ // Find maximum t value+ tMax = 0;+ for (int i = 0; i < 16; ++i) {+ if (tMax < t[i]) tMax = t[i];+ }++ // Compute running differences and find valid shift+ do {+ shift += 1;++ // Compute absolute differences from tMax, shifted and rounded+ for (int i = 0; i < 16; ++i) {+ d[i] = B44ShiftAndRound(tMax - t[i], shift);+ }++ // Convert to running differences (specific pattern for B44)+ r[0] = d[0] - d[4] + bias;+ r[1] = d[4] - d[8] + bias;+ r[2] = d[8] - d[12] + bias;++ r[3] = d[0] - d[1] + bias;+ r[4] = d[4] - d[5] + bias;+ r[5] = d[8] - d[9] + bias;+ r[6] = d[12] - d[13] + bias;++ r[7] = d[1] - d[2] + bias;+ r[8] = d[5] - d[6] + bias;+ r[9] = d[9] - d[10] + bias;+ r[10] = d[13] - d[14] + bias;++ r[11] = d[2] - d[3] + bias;+ r[12] = d[6] - d[7] + bias;+ r[13] = d[10] - d[11] + bias;+ r[14] = d[14] - d[15] + bias;++ rMin = r[0];+ rMax = r[0];+ for (int i = 1; i < 15; ++i) {+ if (rMin > r[i]) rMin = r[i];+ if (rMax < r[i]) rMax = r[i];+ }+ } while (rMin < 0 || rMax > 0x3f);++ // Check for flat block (all pixels same value)+ if (rMin == bias && rMax == bias && flatfields) {+ // Encode as 3 bytes: t[0] and marker 0xfc+ out[0] = static_cast<unsigned char>(t[0] >> 8);+ out[1] = static_cast<unsigned char>(t[0]);+ out[2] = 0xfc; // Flat block marker (shift >= 13)+ return 3;+ }++ if (exactmax) {+ // Adjust t[0] so the max pixel is represented accurately+ t[0] = tMax - static_cast<unsigned short>(d[0] << shift);+ }++ // Pack t[0], shift, and r[0]..r[14] into 14 bytes+ out[0] = static_cast<unsigned char>(t[0] >> 8);+ out[1] = static_cast<unsigned char>(t[0]);+ out[2] = static_cast<unsigned char>((shift << 2) | (r[0] >> 4));+ out[3] = static_cast<unsigned char>((r[0] << 4) | (r[1] >> 2));+ out[4] = static_cast<unsigned char>((r[1] << 6) | r[2]);+ out[5] = static_cast<unsigned char>((r[3] << 2) | (r[4] >> 4));+ out[6] = static_cast<unsigned char>((r[4] << 4) | (r[5] >> 2));+ out[7] = static_cast<unsigned char>((r[5] << 6) | r[6]);+ out[8] = static_cast<unsigned char>((r[7] << 2) | (r[8] >> 4));+ out[9] = static_cast<unsigned char>((r[8] << 4) | (r[9] >> 2));+ out[10] = static_cast<unsigned char>((r[9] << 6) | r[10]);+ out[11] = static_cast<unsigned char>((r[11] << 2) | (r[12] >> 4));+ out[12] = static_cast<unsigned char>((r[12] << 4) | (r[13] >> 2));+ out[13] = static_cast<unsigned char>((r[13] << 6) | r[14]);++ return 14;+}++static bool CompressB44(std::vector<unsigned char>& outBuf,+ const unsigned char *inPtr, size_t inLen,+ int data_width, int num_lines,+ size_t num_channels,+ const EXRChannelInfo *channels,+ bool is_b44a) {+ // Calculate number of 4x4 blocks+ int num_blocks_x = (data_width + 3) / 4;+ int num_blocks_y = (num_lines + 3) / 4;++ // Estimate output size (14 bytes per block per HALF channel)+ size_t max_size = 0;+ for (size_t c = 0; c < num_channels; c++) {+ if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {+ max_size += static_cast<size_t>(num_blocks_x) * num_blocks_y * 14;+ } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT ||+ channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {+ max_size += static_cast<size_t>(data_width) * num_lines * 4;+ } else {+ max_size += static_cast<size_t>(data_width) * num_lines * 2;+ }+ }++ outBuf.resize(max_size);+ unsigned char* out_p = outBuf.data();++ // Process each channel+ size_t in_offset = 0;+ for (size_t c = 0; c < num_channels; c++) {+ if (channels[c].pixel_type != TINYEXR_PIXELTYPE_HALF) {+ // Non-HALF channels are stored uncompressed+ size_t ch_bytes = static_cast<size_t>(data_width) * num_lines;+ if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT ||+ channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {+ ch_bytes *= 4;+ } else {+ ch_bytes *= 2;+ }+ memcpy(out_p, inPtr + in_offset, ch_bytes);+ out_p += ch_bytes;+ in_offset += ch_bytes;+ continue;+ }++ // Process HALF channel in 4x4 blocks+ const unsigned short* ch_ptr = reinterpret_cast<const unsigned short*>(inPtr + in_offset);++ for (int by = 0; by < num_blocks_y; by++) {+ for (int bx = 0; bx < num_blocks_x; bx++) {+ unsigned short block[16];++ // Gather block pixels with edge replication for padding+ for (int dy = 0; dy < 4; dy++) {+ int y = by * 4 + dy;+ int src_y = (y >= num_lines) ? (num_lines - 1) : y;++ for (int dx = 0; dx < 4; dx++) {+ int x = bx * 4 + dx;+ int src_x = (x >= data_width) ? (data_width - 1) : x;++ block[dy * 4 + dx] = ch_ptr[src_y * data_width + src_x];+ }+ }++ // Pack block - PackB44Block handles flat block detection internally+ // flatfields = is_b44a, exactmax = true (for better accuracy)+ int bytes_written = PackB44Block(out_p, block, is_b44a, true);+ out_p += bytes_written;+ }+ }++ in_offset += static_cast<size_t>(data_width) * num_lines * 2;+ }++ // Resize to actual size+ outBuf.resize(static_cast<size_t>(out_p - outBuf.data()));++ return true;+}++// Overloaded version that takes ChannelInfo instead of EXRChannelInfo+// Note: Uses requested_pixel_type which is the file format, not the input type+static bool CompressB44(std::vector<unsigned char>& outBuf,+ const unsigned char *inPtr, size_t inLen,+ int data_width, int num_lines,+ size_t num_channels,+ const std::vector<ChannelInfo>& channels,+ bool is_b44a) {+ // Calculate number of 4x4 blocks+ int num_blocks_x = (data_width + 3) / 4;+ int num_blocks_y = (num_lines + 3) / 4;++ // Estimate output size - use requested_pixel_type (file format)+ size_t max_size = 0;+ for (size_t c = 0; c < num_channels; c++) {+ int file_type = channels[c].requested_pixel_type;+ if (file_type == TINYEXR_PIXELTYPE_HALF) {+ max_size += static_cast<size_t>(num_blocks_x) * num_blocks_y * 14;+ } else if (file_type == TINYEXR_PIXELTYPE_UINT ||+ file_type == TINYEXR_PIXELTYPE_FLOAT) {+ max_size += static_cast<size_t>(data_width) * num_lines * 4;+ } else {+ max_size += static_cast<size_t>(data_width) * num_lines * 2;+ }+ }++ outBuf.resize(max_size);+ unsigned char* out_p = outBuf.data();++ size_t in_offset = 0;+ for (size_t c = 0; c < num_channels; c++) {+ int file_type = channels[c].requested_pixel_type;+ if (file_type != TINYEXR_PIXELTYPE_HALF) {+ size_t ch_bytes = static_cast<size_t>(data_width) * num_lines;+ if (file_type == TINYEXR_PIXELTYPE_UINT ||+ file_type == TINYEXR_PIXELTYPE_FLOAT) {+ ch_bytes *= 4;+ } else {+ ch_bytes *= 2;+ }+ memcpy(out_p, inPtr + in_offset, ch_bytes);+ out_p += ch_bytes;+ in_offset += ch_bytes;+ continue;+ }++ const unsigned short* ch_ptr = reinterpret_cast<const unsigned short*>(inPtr + in_offset);++ for (int by = 0; by < num_blocks_y; by++) {+ for (int bx = 0; bx < num_blocks_x; bx++) {+ unsigned short block[16];++ // Gather block pixels with edge replication for padding+ for (int dy = 0; dy < 4; dy++) {+ int y = by * 4 + dy;+ int src_y = (y >= num_lines) ? (num_lines - 1) : y;++ for (int dx = 0; dx < 4; dx++) {+ int x = bx * 4 + dx;+ int src_x = (x >= data_width) ? (data_width - 1) : x;++ block[dy * 4 + dx] = ch_ptr[src_y * data_width + src_x];+ }+ }++ // Pack block - PackB44Block handles flat block detection internally+ int bytes_written = PackB44Block(out_p, block, is_b44a, true);+ out_p += bytes_written;+ }+ }++ in_offset += static_cast<size_t>(data_width) * num_lines * 2;+ }++ outBuf.resize(static_cast<size_t>(out_p - outBuf.data()));+ return true;+}++#if TINYEXR_USE_ZFP++struct ZFPCompressionParam {+ double rate;+ unsigned int precision;+ unsigned int __pad0;+ double tolerance;+ int type; // TINYEXR_ZFP_COMPRESSIONTYPE_*+ unsigned int __pad1;++ ZFPCompressionParam() {+ type = TINYEXR_ZFP_COMPRESSIONTYPE_RATE;+ rate = 2.0;+ precision = 0;+ tolerance = 0.0;+ }+};++static bool FindZFPCompressionParam(ZFPCompressionParam *param,+ const EXRAttribute *attributes,+ int num_attributes, std::string *err) {+ bool foundType = false;++ for (int i = 0; i < num_attributes; i++) {+ if ((strcmp(attributes[i].name, "zfpCompressionType") == 0)) {+ if (attributes[i].size == 1) {+ param->type = static_cast<int>(attributes[i].value[0]);+ foundType = true;+ break;+ } else {+ if (err) {+ (*err) +=+ "zfpCompressionType attribute must be uchar(1 byte) type.\n";+ }+ return false;+ }+ }+ }++ if (!foundType) {+ if (err) {+ (*err) += "`zfpCompressionType` attribute not found.\n";+ }+ return false;+ }++ if (param->type == TINYEXR_ZFP_COMPRESSIONTYPE_RATE) {+ for (int i = 0; i < num_attributes; i++) {+ if ((strcmp(attributes[i].name, "zfpCompressionRate") == 0) &&+ (attributes[i].size == 8)) {+ param->rate = *(reinterpret_cast<double *>(attributes[i].value));+ return true;+ }+ }++ if (err) {+ (*err) += "`zfpCompressionRate` attribute not found.\n";+ }++ } else if (param->type == TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION) {+ for (int i = 0; i < num_attributes; i++) {+ if ((strcmp(attributes[i].name, "zfpCompressionPrecision") == 0) &&+ (attributes[i].size == 4)) {+ param->rate = *(reinterpret_cast<int *>(attributes[i].value));+ return true;+ }+ }++ if (err) {+ (*err) += "`zfpCompressionPrecision` attribute not found.\n";+ }++ } else if (param->type == TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY) {+ for (int i = 0; i < num_attributes; i++) {+ if ((strcmp(attributes[i].name, "zfpCompressionTolerance") == 0) &&+ (attributes[i].size == 8)) {+ param->tolerance = *(reinterpret_cast<double *>(attributes[i].value));+ return true;+ }+ }++ if (err) {+ (*err) += "`zfpCompressionTolerance` attribute not found.\n";+ }+ } else {+ if (err) {+ (*err) += "Unknown value specified for `zfpCompressionType`.\n";+ }+ }++ return false;+}++// Assume pixel format is FLOAT for all channels.+static bool DecompressZfp(float *dst, int dst_width, int dst_num_lines,+ size_t num_channels, const unsigned char *src,+ unsigned long src_size,+ const ZFPCompressionParam ¶m) {+ size_t uncompressed_size =+ size_t(dst_width) * size_t(dst_num_lines) * num_channels;++ if (uncompressed_size == src_size) {+ // Data is not compressed(Issue 40).+ memcpy(dst, src, src_size);+ }++ zfp_stream *zfp = NULL;+ zfp_field *field = NULL;++ TINYEXR_CHECK_AND_RETURN_C((dst_width % 4) == 0, false);+ TINYEXR_CHECK_AND_RETURN_C((dst_num_lines % 4) == 0, false);++ if ((size_t(dst_width) & 3U) || (size_t(dst_num_lines) & 3U)) {+ return false;+ }++ field =+ zfp_field_2d(reinterpret_cast<void *>(const_cast<unsigned char *>(src)),+ zfp_type_float, static_cast<unsigned int>(dst_width),+ static_cast<unsigned int>(dst_num_lines) *+ static_cast<unsigned int>(num_channels));+ zfp = zfp_stream_open(NULL);++ if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_RATE) {+ zfp_stream_set_rate(zfp, param.rate, zfp_type_float, /* dimension */ 2,+ /* write random access */ 0);+ } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION) {+ zfp_stream_set_precision(zfp, param.precision);+ } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY) {+ zfp_stream_set_accuracy(zfp, param.tolerance);+ } else {+ return false;+ }++ size_t buf_size = zfp_stream_maximum_size(zfp, field);+ std::vector<unsigned char> buf(buf_size);+ memcpy(&buf.at(0), src, src_size);++ bitstream *stream = stream_open(&buf.at(0), buf_size);+ zfp_stream_set_bit_stream(zfp, stream);+ zfp_stream_rewind(zfp);++ size_t image_size = size_t(dst_width) * size_t(dst_num_lines);++ for (size_t c = 0; c < size_t(num_channels); c++) {+ // decompress 4x4 pixel block.+ for (size_t y = 0; y < size_t(dst_num_lines); y += 4) {+ for (size_t x = 0; x < size_t(dst_width); x += 4) {+ float fblock[16];+ zfp_decode_block_float_2(zfp, fblock);+ for (size_t j = 0; j < 4; j++) {+ for (size_t i = 0; i < 4; i++) {+ dst[c * image_size + ((y + j) * size_t(dst_width) + (x + i))] =+ fblock[j * 4 + i];+ }+ }+ }+ }+ }++ zfp_field_free(field);+ zfp_stream_close(zfp);+ stream_close(stream);++ return true;+}++// Assume pixel format is FLOAT for all channels.+static bool CompressZfp(std::vector<unsigned char> *outBuf,+ unsigned int *outSize, const float *inPtr, int width,+ int num_lines, int num_channels,+ const ZFPCompressionParam ¶m) {+ zfp_stream *zfp = NULL;+ zfp_field *field = NULL;++ TINYEXR_CHECK_AND_RETURN_C((width % 4) == 0, false);+ TINYEXR_CHECK_AND_RETURN_C((num_lines % 4) == 0, false);++ if ((size_t(width) & 3U) || (size_t(num_lines) & 3U)) {+ return false;+ }++ // create input array.+ field = zfp_field_2d(reinterpret_cast<void *>(const_cast<float *>(inPtr)),+ zfp_type_float, static_cast<unsigned int>(width),+ static_cast<unsigned int>(num_lines * num_channels));++ zfp = zfp_stream_open(NULL);++ if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_RATE) {+ zfp_stream_set_rate(zfp, param.rate, zfp_type_float, 2, 0);+ } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION) {+ zfp_stream_set_precision(zfp, param.precision);+ } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY) {+ zfp_stream_set_accuracy(zfp, param.tolerance);+ } else {+ return false;+ }++ size_t buf_size = zfp_stream_maximum_size(zfp, field);++ outBuf->resize(buf_size);++ bitstream *stream = stream_open(&outBuf->at(0), buf_size);+ zfp_stream_set_bit_stream(zfp, stream);+ zfp_field_free(field);++ size_t image_size = size_t(width) * size_t(num_lines);++ for (size_t c = 0; c < size_t(num_channels); c++) {+ // compress 4x4 pixel block.+ for (size_t y = 0; y < size_t(num_lines); y += 4) {+ for (size_t x = 0; x < size_t(width); x += 4) {+ float fblock[16];+ for (size_t j = 0; j < 4; j++) {+ for (size_t i = 0; i < 4; i++) {+ fblock[j * 4 + i] =+ inPtr[c * image_size + ((y + j) * size_t(width) + (x + i))];+ }+ }+ zfp_encode_block_float_2(zfp, fblock);+ }+ }+ }++ zfp_stream_flush(zfp);+ (*outSize) = static_cast<unsigned int>(zfp_stream_compressed_size(zfp));++ zfp_stream_close(zfp);++ return true;+}++#endif++//+// -----------------------------------------------------------------+//++// heuristics+#define TINYEXR_DIMENSION_THRESHOLD (1024 * 8192)++// TODO(syoyo): Refactor function arguments.+static bool DecodePixelData(/* out */ unsigned char **out_images,+ const int *requested_pixel_types,+ const unsigned char *data_ptr, size_t data_len,+ int compression_type, int line_order, int width,+ int height, int x_stride, int y, int line_no,+ int num_lines, size_t pixel_data_size,+ size_t num_attributes,+ const EXRAttribute *attributes, size_t num_channels,+ const EXRChannelInfo *channels,+ const std::vector<size_t> &channel_offset_list) {+ if (compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { // PIZ+#if TINYEXR_USE_PIZ+ if ((width == 0) || (num_lines == 0) || (pixel_data_size == 0)) {+ // Invalid input #90+ return false;+ }++ // Allocate original data size.+ std::vector<unsigned char> outBuf(static_cast<size_t>(+ static_cast<size_t>(width * num_lines) * pixel_data_size));+ size_t tmpBufLen = outBuf.size();++ bool ret = tinyexr::DecompressPiz(+ reinterpret_cast<unsigned char *>(&outBuf.at(0)), data_ptr, tmpBufLen,+ data_len, static_cast<int>(num_channels), channels, width, num_lines);++ if (!ret) {+ return false;+ }++ // For PIZ_COMPRESSION:+ // pixel sample data for channel 0 for scanline 0+ // pixel sample data for channel 1 for scanline 0+ // pixel sample data for channel ... for scanline 0+ // pixel sample data for channel n for scanline 0+ // pixel sample data for channel 0 for scanline 1+ // pixel sample data for channel 1 for scanline 1+ // pixel sample data for channel ... for scanline 1+ // pixel sample data for channel n for scanline 1+ // ...+ for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {+ if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {+ for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {+ const unsigned short *line_ptr = reinterpret_cast<unsigned short *>(+ &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) ++ channel_offset_list[c] * static_cast<size_t>(width)));+ for (size_t u = 0; u < static_cast<size_t>(width); u++) {+ FP16 hf;++ // hf.u = line_ptr[u];+ // use `cpy` to avoid unaligned memory access when compiler's+ // optimization is on.+ tinyexr::cpy2(&(hf.u), line_ptr + u);++ tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u));++ if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {+ unsigned short *image =+ reinterpret_cast<unsigned short **>(out_images)[c];+ if (line_order == 0) {+ image += (static_cast<size_t>(line_no) + v) *+ static_cast<size_t>(x_stride) ++ u;+ } else {+ image += static_cast<size_t>(+ (height - 1 - (line_no + static_cast<int>(v)))) *+ static_cast<size_t>(x_stride) ++ u;+ }+ *image = hf.u;+ } else { // HALF -> FLOAT+ FP32 f32 = half_to_float(hf);+ float *image = reinterpret_cast<float **>(out_images)[c];+ size_t offset = 0;+ if (line_order == 0) {+ offset = (static_cast<size_t>(line_no) + v) *+ static_cast<size_t>(x_stride) ++ u;+ } else {+ offset = static_cast<size_t>(+ (height - 1 - (line_no + static_cast<int>(v)))) *+ static_cast<size_t>(x_stride) ++ u;+ }+ image += offset;+ *image = f32.f;+ }+ }+ }+ } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {+ TINYEXR_CHECK_AND_RETURN_C(requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT, false);++ for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {+ const unsigned int *line_ptr = reinterpret_cast<unsigned int *>(+ &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) ++ channel_offset_list[c] * static_cast<size_t>(width)));+ for (size_t u = 0; u < static_cast<size_t>(width); u++) {+ unsigned int val;+ // val = line_ptr[u];+ tinyexr::cpy4(&val, line_ptr + u);++ tinyexr::swap4(&val);++ unsigned int *image =+ reinterpret_cast<unsigned int **>(out_images)[c];+ if (line_order == 0) {+ image += (static_cast<size_t>(line_no) + v) *+ static_cast<size_t>(x_stride) ++ u;+ } else {+ image += static_cast<size_t>(+ (height - 1 - (line_no + static_cast<int>(v)))) *+ static_cast<size_t>(x_stride) ++ u;+ }+ *image = val;+ }+ }+ } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {+ TINYEXR_CHECK_AND_RETURN_C(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT, false);+ for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {+ const float *line_ptr = reinterpret_cast<float *>(&outBuf.at(+ v * pixel_data_size * static_cast<size_t>(width) ++ channel_offset_list[c] * static_cast<size_t>(width)));+ for (size_t u = 0; u < static_cast<size_t>(width); u++) {+ float val;+ // val = line_ptr[u];+ tinyexr::cpy4(&val, line_ptr + u);++ tinyexr::swap4(reinterpret_cast<unsigned int *>(&val));++ float *image = reinterpret_cast<float **>(out_images)[c];+ if (line_order == 0) {+ image += (static_cast<size_t>(line_no) + v) *+ static_cast<size_t>(x_stride) ++ u;+ } else {+ image += static_cast<size_t>(+ (height - 1 - (line_no + static_cast<int>(v)))) *+ static_cast<size_t>(x_stride) ++ u;+ }+ *image = val;+ }+ }+ } else {+ return false;+ }+ }+#else+ return false;+#endif++ } else if (compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS ||+ compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) {+ // Allocate original data size.+ std::vector<unsigned char> outBuf(static_cast<size_t>(width) *+ static_cast<size_t>(num_lines) *+ pixel_data_size);++ unsigned long dstLen = static_cast<unsigned long>(outBuf.size());+ TINYEXR_CHECK_AND_RETURN_C(dstLen > 0, false);+ if (!tinyexr::DecompressZip(+ reinterpret_cast<unsigned char *>(&outBuf.at(0)), &dstLen, data_ptr,+ static_cast<unsigned long>(data_len))) {+ return false;+ }++ // For ZIP_COMPRESSION:+ // pixel sample data for channel 0 for scanline 0+ // pixel sample data for channel 1 for scanline 0+ // pixel sample data for channel ... for scanline 0+ // pixel sample data for channel n for scanline 0+ // pixel sample data for channel 0 for scanline 1+ // pixel sample data for channel 1 for scanline 1+ // pixel sample data for channel ... for scanline 1+ // pixel sample data for channel n for scanline 1+ // ...+ for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {+ if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {+ for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {+ const unsigned short *line_ptr = reinterpret_cast<unsigned short *>(+ &outBuf.at(v * static_cast<size_t>(pixel_data_size) *+ static_cast<size_t>(width) ++ channel_offset_list[c] * static_cast<size_t>(width)));+ for (size_t u = 0; u < static_cast<size_t>(width); u++) {+ tinyexr::FP16 hf;++ // hf.u = line_ptr[u];+ tinyexr::cpy2(&(hf.u), line_ptr + u);++ tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u));++ if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {+ unsigned short *image =+ reinterpret_cast<unsigned short **>(out_images)[c];+ if (line_order == 0) {+ image += (static_cast<size_t>(line_no) + v) *+ static_cast<size_t>(x_stride) ++ u;+ } else {+ image += (static_cast<size_t>(height) - 1U -+ (static_cast<size_t>(line_no) + v)) *+ static_cast<size_t>(x_stride) ++ u;+ }+ *image = hf.u;+ } else { // HALF -> FLOAT+ tinyexr::FP32 f32 = half_to_float(hf);+ float *image = reinterpret_cast<float **>(out_images)[c];+ size_t offset = 0;+ if (line_order == 0) {+ offset = (static_cast<size_t>(line_no) + v) *+ static_cast<size_t>(x_stride) ++ u;+ } else {+ offset = (static_cast<size_t>(height) - 1U -+ (static_cast<size_t>(line_no) + v)) *+ static_cast<size_t>(x_stride) ++ u;+ }+ image += offset;++ *image = f32.f;+ }+ }+ }+ } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {+ TINYEXR_CHECK_AND_RETURN_C(requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT, false);++ for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {+ const unsigned int *line_ptr = reinterpret_cast<unsigned int *>(+ &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) ++ channel_offset_list[c] * static_cast<size_t>(width)));+ for (size_t u = 0; u < static_cast<size_t>(width); u++) {+ unsigned int val;+ // val = line_ptr[u];+ tinyexr::cpy4(&val, line_ptr + u);++ tinyexr::swap4(&val);++ unsigned int *image =+ reinterpret_cast<unsigned int **>(out_images)[c];+ if (line_order == 0) {+ image += (static_cast<size_t>(line_no) + v) *+ static_cast<size_t>(x_stride) ++ u;+ } else {+ image += (static_cast<size_t>(height) - 1U -+ (static_cast<size_t>(line_no) + v)) *+ static_cast<size_t>(x_stride) ++ u;+ }+ *image = val;+ }+ }+ } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {+ TINYEXR_CHECK_AND_RETURN_C(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT, false);+ for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {+ const float *line_ptr = reinterpret_cast<float *>(+ &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) ++ channel_offset_list[c] * static_cast<size_t>(width)));+ for (size_t u = 0; u < static_cast<size_t>(width); u++) {+ float val;+ // val = line_ptr[u];+ tinyexr::cpy4(&val, line_ptr + u);++ tinyexr::swap4(reinterpret_cast<unsigned int *>(&val));++ float *image = reinterpret_cast<float **>(out_images)[c];+ if (line_order == 0) {+ image += (static_cast<size_t>(line_no) + v) *+ static_cast<size_t>(x_stride) ++ u;+ } else {+ image += (static_cast<size_t>(height) - 1U -+ (static_cast<size_t>(line_no) + v)) *+ static_cast<size_t>(x_stride) ++ u;+ }+ *image = val;+ }+ }+ } else {+ return false;+ }+ }+ } else if (compression_type == TINYEXR_COMPRESSIONTYPE_RLE) {+ // Allocate original data size.+ std::vector<unsigned char> outBuf(static_cast<size_t>(width) *+ static_cast<size_t>(num_lines) *+ pixel_data_size);++ unsigned long dstLen = static_cast<unsigned long>(outBuf.size());+ if (dstLen == 0) {+ return false;+ }++ if (!tinyexr::DecompressRle(+ reinterpret_cast<unsigned char *>(&outBuf.at(0)), dstLen, data_ptr,+ static_cast<unsigned long>(data_len))) {+ return false;+ }++ // For RLE_COMPRESSION:+ // pixel sample data for channel 0 for scanline 0+ // pixel sample data for channel 1 for scanline 0+ // pixel sample data for channel ... for scanline 0+ // pixel sample data for channel n for scanline 0+ // pixel sample data for channel 0 for scanline 1+ // pixel sample data for channel 1 for scanline 1+ // pixel sample data for channel ... for scanline 1+ // pixel sample data for channel n for scanline 1+ // ...+ for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {+ if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {+ for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {+ const unsigned short *line_ptr = reinterpret_cast<unsigned short *>(+ &outBuf.at(v * static_cast<size_t>(pixel_data_size) *+ static_cast<size_t>(width) ++ channel_offset_list[c] * static_cast<size_t>(width)));+ for (size_t u = 0; u < static_cast<size_t>(width); u++) {+ tinyexr::FP16 hf;++ // hf.u = line_ptr[u];+ tinyexr::cpy2(&(hf.u), line_ptr + u);++ tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u));++ if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {+ unsigned short *image =+ reinterpret_cast<unsigned short **>(out_images)[c];+ if (line_order == 0) {+ image += (static_cast<size_t>(line_no) + v) *+ static_cast<size_t>(x_stride) ++ u;+ } else {+ image += (static_cast<size_t>(height) - 1U -+ (static_cast<size_t>(line_no) + v)) *+ static_cast<size_t>(x_stride) ++ u;+ }+ *image = hf.u;+ } else { // HALF -> FLOAT+ tinyexr::FP32 f32 = half_to_float(hf);+ float *image = reinterpret_cast<float **>(out_images)[c];+ if (line_order == 0) {+ image += (static_cast<size_t>(line_no) + v) *+ static_cast<size_t>(x_stride) ++ u;+ } else {+ image += (static_cast<size_t>(height) - 1U -+ (static_cast<size_t>(line_no) + v)) *+ static_cast<size_t>(x_stride) ++ u;+ }+ *image = f32.f;+ }+ }+ }+ } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {+ TINYEXR_CHECK_AND_RETURN_C(requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT, false);++ for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {+ const unsigned int *line_ptr = reinterpret_cast<unsigned int *>(+ &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) ++ channel_offset_list[c] * static_cast<size_t>(width)));+ for (size_t u = 0; u < static_cast<size_t>(width); u++) {+ unsigned int val;+ // val = line_ptr[u];+ tinyexr::cpy4(&val, line_ptr + u);++ tinyexr::swap4(&val);++ unsigned int *image =+ reinterpret_cast<unsigned int **>(out_images)[c];+ if (line_order == 0) {+ image += (static_cast<size_t>(line_no) + v) *+ static_cast<size_t>(x_stride) ++ u;+ } else {+ image += (static_cast<size_t>(height) - 1U -+ (static_cast<size_t>(line_no) + v)) *+ static_cast<size_t>(x_stride) ++ u;+ }+ *image = val;+ }+ }+ } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {+ TINYEXR_CHECK_AND_RETURN_C(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT, false);+ for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {+ const float *line_ptr = reinterpret_cast<float *>(+ &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) ++ channel_offset_list[c] * static_cast<size_t>(width)));+ for (size_t u = 0; u < static_cast<size_t>(width); u++) {+ float val;+ // val = line_ptr[u];+ tinyexr::cpy4(&val, line_ptr + u);++ tinyexr::swap4(reinterpret_cast<unsigned int *>(&val));++ float *image = reinterpret_cast<float **>(out_images)[c];+ if (line_order == 0) {+ image += (static_cast<size_t>(line_no) + v) *+ static_cast<size_t>(x_stride) ++ u;+ } else {+ image += (static_cast<size_t>(height) - 1U -+ (static_cast<size_t>(line_no) + v)) *+ static_cast<size_t>(x_stride) ++ u;+ }+ *image = val;+ }+ }+ } else {+ return false;+ }+ }+ } else if (compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {+#if TINYEXR_USE_ZFP+ tinyexr::ZFPCompressionParam zfp_compression_param;+ std::string e;+ if (!tinyexr::FindZFPCompressionParam(&zfp_compression_param, attributes,+ int(num_attributes), &e)) {+ // This code path should not be reachable.+ return false;+ }++ // Allocate original data size.+ std::vector<unsigned char> outBuf(static_cast<size_t>(width) *+ static_cast<size_t>(num_lines) *+ pixel_data_size);++ unsigned long dstLen = outBuf.size();+ TINYEXR_CHECK_AND_RETURN_C(dstLen > 0, false);+ tinyexr::DecompressZfp(reinterpret_cast<float *>(&outBuf.at(0)), width,+ num_lines, num_channels, data_ptr,+ static_cast<unsigned long>(data_len),+ zfp_compression_param);++ // For ZFP_COMPRESSION:+ // pixel sample data for channel 0 for scanline 0+ // pixel sample data for channel 1 for scanline 0+ // pixel sample data for channel ... for scanline 0+ // pixel sample data for channel n for scanline 0+ // pixel sample data for channel 0 for scanline 1+ // pixel sample data for channel 1 for scanline 1+ // pixel sample data for channel ... for scanline 1+ // pixel sample data for channel n for scanline 1+ // ...+ for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {+ TINYEXR_CHECK_AND_RETURN_C(channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT, false);+ if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {+ TINYEXR_CHECK_AND_RETURN_C(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT, false);+ for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {+ const float *line_ptr = reinterpret_cast<float *>(+ &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) ++ channel_offset_list[c] * static_cast<size_t>(width)));+ for (size_t u = 0; u < static_cast<size_t>(width); u++) {+ float val;+ tinyexr::cpy4(&val, line_ptr + u);++ tinyexr::swap4(reinterpret_cast<unsigned int *>(&val));++ float *image = reinterpret_cast<float **>(out_images)[c];+ if (line_order == 0) {+ image += (static_cast<size_t>(line_no) + v) *+ static_cast<size_t>(x_stride) ++ u;+ } else {+ image += (static_cast<size_t>(height) - 1U -+ (static_cast<size_t>(line_no) + v)) *+ static_cast<size_t>(x_stride) ++ u;+ }+ *image = val;+ }+ }+ } else {+ return false;+ }+ }+#else+ (void)attributes;+ (void)num_attributes;+ (void)num_channels;+ return false;+#endif+ } else if (compression_type == TINYEXR_COMPRESSIONTYPE_PXR24) {+ // PXR24 compression: Use true PXR24 decompression+ // PXR24 truncates FLOAT to 24-bits, HALF/UINT pass through unchanged+ std::vector<unsigned char> outBuf(static_cast<size_t>(width) *+ static_cast<size_t>(num_lines) *+ pixel_data_size);++ if (!tinyexr::DecompressPxr24(+ reinterpret_cast<unsigned char *>(&outBuf.at(0)), outBuf.size(),+ data_ptr, static_cast<size_t>(data_len),+ width, num_lines, static_cast<size_t>(num_channels), channels)) {+ return false;+ }++ // Process decompressed data (same as ZIP path)+ for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {+ if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {+ for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {+ const unsigned short *line_ptr = reinterpret_cast<unsigned short *>(+ &outBuf.at(v * static_cast<size_t>(pixel_data_size) *+ static_cast<size_t>(width) ++ channel_offset_list[c] * static_cast<size_t>(width)));+ for (size_t u = 0; u < static_cast<size_t>(width); u++) {+ tinyexr::FP16 hf;+ tinyexr::cpy2(&(hf.u), line_ptr + u);+ tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u));++ if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {+ unsigned short *image =+ reinterpret_cast<unsigned short **>(out_images)[c];+ if (line_order == 0) {+ image += (static_cast<size_t>(line_no) + v) *+ static_cast<size_t>(x_stride) ++ u;+ } else {+ image += (static_cast<size_t>(height) - 1U -+ (static_cast<size_t>(line_no) + v)) *+ static_cast<size_t>(x_stride) ++ u;+ }+ *image = hf.u;+ } else { // HALF -> FLOAT+ tinyexr::FP32 f32 = half_to_float(hf);+ float *image = reinterpret_cast<float **>(out_images)[c];+ if (line_order == 0) {+ image += (static_cast<size_t>(line_no) + v) *+ static_cast<size_t>(x_stride) ++ u;+ } else {+ image += (static_cast<size_t>(height) - 1U -+ (static_cast<size_t>(line_no) + v)) *+ static_cast<size_t>(x_stride) ++ u;+ }+ *image = f32.f;+ }+ }+ }+ } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {+ TINYEXR_CHECK_AND_RETURN_C(requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT, false);++ for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {+ const unsigned int *line_ptr = reinterpret_cast<unsigned int *>(+ &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) ++ channel_offset_list[c] * static_cast<size_t>(width)));+ for (size_t u = 0; u < static_cast<size_t>(width); u++) {+ unsigned int val;+ tinyexr::cpy4(&val, line_ptr + u);+ tinyexr::swap4(&val);++ unsigned int *image =+ reinterpret_cast<unsigned int **>(out_images)[c];+ if (line_order == 0) {+ image += (static_cast<size_t>(line_no) + v) *+ static_cast<size_t>(x_stride) ++ u;+ } else {+ image += (static_cast<size_t>(height) - 1U -+ (static_cast<size_t>(line_no) + v)) *+ static_cast<size_t>(x_stride) ++ u;+ }+ *image = val;+ }+ }+ } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {+ TINYEXR_CHECK_AND_RETURN_C(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT, false);+ for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {+ const float *line_ptr = reinterpret_cast<float *>(+ &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) ++ channel_offset_list[c] * static_cast<size_t>(width)));+ for (size_t u = 0; u < static_cast<size_t>(width); u++) {+ float val;+ tinyexr::cpy4(&val, line_ptr + u);+ tinyexr::swap4(reinterpret_cast<unsigned int *>(&val));++ float *image = reinterpret_cast<float **>(out_images)[c];+ if (line_order == 0) {+ image += (static_cast<size_t>(line_no) + v) *+ static_cast<size_t>(x_stride) ++ u;+ } else {+ image += (static_cast<size_t>(height) - 1U -+ (static_cast<size_t>(line_no) + v)) *+ static_cast<size_t>(x_stride) ++ u;+ }+ *image = val;+ }+ }+ } else {+ return false;+ }+ }+ } else if (compression_type == TINYEXR_COMPRESSIONTYPE_B44 ||+ compression_type == TINYEXR_COMPRESSIONTYPE_B44A) {+ // B44/B44A compression: Use true B44 block decompression+ // B44 is a lossy block compression for HALF data (4x4 blocks -> 14 bytes)+ bool is_b44a = (compression_type == TINYEXR_COMPRESSIONTYPE_B44A);++ // Compute outBuf size matching DecompressB44's output layout: per-channel+ // sequential data using subsampled dimensions for each channel.+ size_t b44_out_size = 0;+ for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {+ int xs = channels[c].x_sampling > 0 ? channels[c].x_sampling : 1;+ int ys = channels[c].y_sampling > 0 ? channels[c].y_sampling : 1;+ size_t cw = static_cast<size_t>((width + xs - 1) / xs);+ size_t ch = static_cast<size_t>((num_lines + ys - 1) / ys);+ size_t bpp = (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) ? 2u : 4u;+ b44_out_size += cw * ch * bpp;+ }++ std::vector<unsigned char> outBuf(b44_out_size);++ if (!tinyexr::DecompressB44(+ reinterpret_cast<unsigned char *>(&outBuf.at(0)), outBuf.size(),+ data_ptr, static_cast<size_t>(data_len),+ width, num_lines, static_cast<size_t>(num_channels), channels,+ is_b44a)) {+ return false;+ }++ // Process decompressed data - B44 returns data organized per channel,+ // using subsampled dimensions (ch_width/ch_height based on x/y_sampling).+ // Accumulate ch_offset based on actual subsampled sizes of preceding+ // channels to handle mixed channel types and subsampling correctly.+ size_t ch_offset = 0;+ for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {+ int xs = channels[c].x_sampling > 0 ? channels[c].x_sampling : 1;+ int ys = channels[c].y_sampling > 0 ? channels[c].y_sampling : 1;+ size_t ch_width = static_cast<size_t>((width + xs - 1) / xs);+ size_t ch_height = static_cast<size_t>((num_lines + ys - 1) / ys);+ size_t ch_bytes = (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) ? 2 : 4;++ if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {+ for (size_t v = 0; v < ch_height; v++) {+ const unsigned short *line_ptr = reinterpret_cast<unsigned short *>(+ &outBuf.at(ch_offset + v * ch_width * 2));+ for (size_t u = 0; u < ch_width; u++) {+ tinyexr::FP16 hf;+ tinyexr::cpy2(&(hf.u), line_ptr + u);+ // B44 stream stores data in little-endian order (same as the+ // encoder's buf); reverse the byte swap the encoder applied.+ tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u));++ if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {+ unsigned short *image =+ reinterpret_cast<unsigned short **>(out_images)[c];+ if (line_order == 0) {+ image += (static_cast<size_t>(line_no) + v) *+ static_cast<size_t>(x_stride) ++ u;+ } else {+ image += (static_cast<size_t>(height) - 1U -+ (static_cast<size_t>(line_no) + v)) *+ static_cast<size_t>(x_stride) ++ u;+ }+ *image = hf.u;+ } else { // HALF -> FLOAT+ tinyexr::FP32 f32 = half_to_float(hf);+ float *image = reinterpret_cast<float **>(out_images)[c];+ if (line_order == 0) {+ image += (static_cast<size_t>(line_no) + v) *+ static_cast<size_t>(x_stride) ++ u;+ } else {+ image += (static_cast<size_t>(height) - 1U -+ (static_cast<size_t>(line_no) + v)) *+ static_cast<size_t>(x_stride) ++ u;+ }+ *image = f32.f;+ }+ }+ }+ } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {+ TINYEXR_CHECK_AND_RETURN_C(requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT, false);++ for (size_t v = 0; v < ch_height; v++) {+ const unsigned int *line_ptr = reinterpret_cast<unsigned int *>(+ &outBuf.at(ch_offset + v * ch_width * 4));+ for (size_t u = 0; u < ch_width; u++) {+ unsigned int val;+ tinyexr::cpy4(&val, line_ptr + u);+ tinyexr::swap4(&val);++ unsigned int *image =+ reinterpret_cast<unsigned int **>(out_images)[c];+ if (line_order == 0) {+ image += (static_cast<size_t>(line_no) + v) *+ static_cast<size_t>(x_stride) ++ u;+ } else {+ image += (static_cast<size_t>(height) - 1U -+ (static_cast<size_t>(line_no) + v)) *+ static_cast<size_t>(x_stride) ++ u;+ }+ *image = val;+ }+ }+ } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {+ TINYEXR_CHECK_AND_RETURN_C(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT, false);+ for (size_t v = 0; v < ch_height; v++) {+ const float *line_ptr = reinterpret_cast<float *>(+ &outBuf.at(ch_offset + v * ch_width * 4));+ for (size_t u = 0; u < ch_width; u++) {+ float val;+ tinyexr::cpy4(&val, line_ptr + u);+ tinyexr::swap4(reinterpret_cast<unsigned int *>(&val));++ float *image = reinterpret_cast<float **>(out_images)[c];+ if (line_order == 0) {+ image += (static_cast<size_t>(line_no) + v) *+ static_cast<size_t>(x_stride) ++ u;+ } else {+ image += (static_cast<size_t>(height) - 1U -+ (static_cast<size_t>(line_no) + v)) *+ static_cast<size_t>(x_stride) ++ u;+ }+ *image = val;+ }+ }+ } else {+ return false;+ }+ ch_offset += ch_width * ch_height * ch_bytes;+ }+ } else if (compression_type == TINYEXR_COMPRESSIONTYPE_NONE) {+ for (size_t c = 0; c < num_channels; c++) {+ for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {+ if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {+ const unsigned short *line_ptr =+ reinterpret_cast<const unsigned short *>(+ data_ptr + v * pixel_data_size * size_t(width) ++ channel_offset_list[c] * static_cast<size_t>(width));++ if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {+ unsigned short *outLine =+ reinterpret_cast<unsigned short *>(out_images[c]);+ if (line_order == 0) {+ outLine += (size_t(y) + v) * size_t(x_stride);+ } else {+ outLine +=+ (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride);+ }++ for (int u = 0; u < width; u++) {+ tinyexr::FP16 hf;++ // hf.u = line_ptr[u];+ tinyexr::cpy2(&(hf.u), line_ptr + u);++ tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u));++ outLine[u] = hf.u;+ }+ } else if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) {+ float *outLine = reinterpret_cast<float *>(out_images[c]);+ if (line_order == 0) {+ outLine += (size_t(y) + v) * size_t(x_stride);+ } else {+ outLine +=+ (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride);+ }++ if (reinterpret_cast<const unsigned char *>(line_ptr + width) >+ (data_ptr + data_len)) {+ // Insufficient data size+ return false;+ }++ for (int u = 0; u < width; u++) {+ tinyexr::FP16 hf;++ // address may not be aligned. use byte-wise copy for safety.#76+ // hf.u = line_ptr[u];+ tinyexr::cpy2(&(hf.u), line_ptr + u);++ tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u));++ tinyexr::FP32 f32 = half_to_float(hf);++ outLine[u] = f32.f;+ }+ } else {+ return false;+ }+ } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {+ const float *line_ptr = reinterpret_cast<const float *>(+ data_ptr + v * pixel_data_size * size_t(width) ++ channel_offset_list[c] * static_cast<size_t>(width));++ float *outLine = reinterpret_cast<float *>(out_images[c]);+ if (line_order == 0) {+ outLine += (size_t(y) + v) * size_t(x_stride);+ } else {+ outLine +=+ (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride);+ }++ if (reinterpret_cast<const unsigned char *>(line_ptr + width) >+ (data_ptr + data_len)) {+ // Insufficient data size+ return false;+ }++ for (int u = 0; u < width; u++) {+ float val;+ tinyexr::cpy4(&val, line_ptr + u);++ tinyexr::swap4(reinterpret_cast<unsigned int *>(&val));++ outLine[u] = val;+ }+ } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {+ const unsigned int *line_ptr = reinterpret_cast<const unsigned int *>(+ data_ptr + v * pixel_data_size * size_t(width) ++ channel_offset_list[c] * static_cast<size_t>(width));++ unsigned int *outLine =+ reinterpret_cast<unsigned int *>(out_images[c]);+ if (line_order == 0) {+ outLine += (size_t(y) + v) * size_t(x_stride);+ } else {+ outLine +=+ (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride);+ }++ if (reinterpret_cast<const unsigned char *>(line_ptr + width) >+ (data_ptr + data_len)) {+ // Corrupted data+ return false;+ }++ for (int u = 0; u < width; u++) {++ unsigned int val;+ tinyexr::cpy4(&val, line_ptr + u);++ tinyexr::swap4(reinterpret_cast<unsigned int *>(&val));++ outLine[u] = val;+ }+ }+ }+ }+ }++ return true;+}++static bool DecodeTiledPixelData(+ unsigned char **out_images, int *width, int *height,+ const int *requested_pixel_types, const unsigned char *data_ptr,+ size_t data_len, int compression_type, int data_width,+ int data_height, int tile_offset_x, int tile_offset_y, int tile_size_x,+ int tile_size_y, size_t pixel_data_size, size_t num_attributes,+ const EXRAttribute *attributes, size_t num_channels,+ const EXRChannelInfo *channels,+ const std::vector<size_t> &channel_offset_list) {+ // Here, data_width and data_height are the dimensions of the current (sub)level.+ if (tile_size_x * tile_offset_x > data_width ||+ tile_size_y * tile_offset_y > data_height) {+ return false;+ }++ // Compute actual image size in a tile.+ if ((tile_offset_x + 1) * tile_size_x >= data_width) {+ (*width) = data_width - (tile_offset_x * tile_size_x);+ } else {+ (*width) = tile_size_x;+ }++ if ((tile_offset_y + 1) * tile_size_y >= data_height) {+ (*height) = data_height - (tile_offset_y * tile_size_y);+ } else {+ (*height) = tile_size_y;+ }++ // Image size = tile size.+ // Line order within tiles is always increasing.+ return DecodePixelData(out_images, requested_pixel_types, data_ptr, data_len,+ compression_type, /* line_order*/ 0, (*width), tile_size_y,+ /* stride */ tile_size_x, /* y */ 0, /* line_no */ 0,+ (*height), pixel_data_size, num_attributes, attributes,+ num_channels, channels, channel_offset_list);+}++static bool ComputeChannelLayout(std::vector<size_t> *channel_offset_list,+ int *pixel_data_size, size_t *channel_offset,+ int num_channels,+ const EXRChannelInfo *channels) {+ channel_offset_list->resize(static_cast<size_t>(num_channels));++ (*pixel_data_size) = 0;+ (*channel_offset) = 0;++ for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {+ (*channel_offset_list)[c] = (*channel_offset);+ if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {+ (*pixel_data_size) += sizeof(unsigned short);+ (*channel_offset) += sizeof(unsigned short);+ } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {+ (*pixel_data_size) += sizeof(float);+ (*channel_offset) += sizeof(float);+ } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {+ (*pixel_data_size) += sizeof(unsigned int);+ (*channel_offset) += sizeof(unsigned int);+ } else {+ // ???+ return false;+ }+ }+ return true;+}++// TODO: Simply return nullptr when failed to allocate?+static unsigned char **AllocateImage(int num_channels,+ const EXRChannelInfo *channels,+ const int *requested_pixel_types,+ int data_width, int data_height, bool *success) {+ unsigned char **images =+ reinterpret_cast<unsigned char **>(static_cast<float **>(+ malloc(sizeof(float *) * static_cast<size_t>(num_channels))));++ for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {+ images[c] = NULL;+ }++ bool valid = true;++ for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {+ size_t data_len =+ static_cast<size_t>(data_width) * static_cast<size_t>(data_height);+ if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {+ // pixel_data_size += sizeof(unsigned short);+ // channel_offset += sizeof(unsigned short);+ // Alloc internal image for half type.+ if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {+ images[c] =+ reinterpret_cast<unsigned char *>(static_cast<unsigned short *>(+ malloc(sizeof(unsigned short) * data_len)));+ } else if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) {+ images[c] = reinterpret_cast<unsigned char *>(+ static_cast<float *>(malloc(sizeof(float) * data_len)));+ } else {+ images[c] = NULL; // just in case.+ valid = false;+ break;+ }+ } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {+ // pixel_data_size += sizeof(float);+ // channel_offset += sizeof(float);+ images[c] = reinterpret_cast<unsigned char *>(+ static_cast<float *>(malloc(sizeof(float) * data_len)));+ } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {+ // pixel_data_size += sizeof(unsigned int);+ // channel_offset += sizeof(unsigned int);+ images[c] = reinterpret_cast<unsigned char *>(+ static_cast<unsigned int *>(malloc(sizeof(unsigned int) * data_len)));+ } else {+ images[c] = NULL; // just in case.+ valid = false;+ break;+ }+ }++ if (!valid) {+ for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {+ if (images[c]) {+ free(images[c]);+ images[c] = NULL;+ }+ }++ if (success) {+ (*success) = false;+ }+ } else {+ if (success) {+ (*success) = true;+ }+ }++ return images;+}++#ifdef _WIN32+static inline std::wstring UTF8ToWchar(const std::string &str) {+ int wstr_size =+ MultiByteToWideChar(CP_UTF8, 0, str.data(), (int)str.size(), NULL, 0);+ std::wstring wstr(wstr_size, 0);+ MultiByteToWideChar(CP_UTF8, 0, str.data(), (int)str.size(), &wstr[0],+ (int)wstr.size());+ return wstr;+}+#endif+++static int ParseEXRHeader(HeaderInfo *info, bool *empty_header,+ const EXRVersion *version, std::string *err,+ const unsigned char *buf, size_t size) {+ const char *marker = reinterpret_cast<const char *>(&buf[0]);++ if (empty_header) {+ (*empty_header) = false;+ }++ if (version->multipart) {+ if (size > 0 && marker[0] == '\0') {+ // End of header list.+ if (empty_header) {+ (*empty_header) = true;+ }+ return TINYEXR_SUCCESS;+ }+ }++ // According to the spec, the header of every OpenEXR file must contain at+ // least the following attributes:+ //+ // channels chlist+ // compression compression+ // dataWindow box2i+ // displayWindow box2i+ // lineOrder lineOrder+ // pixelAspectRatio float+ // screenWindowCenter v2f+ // screenWindowWidth float+ bool has_channels = false;+ bool has_compression = false;+ bool has_data_window = false;+ bool has_display_window = false;+ bool has_line_order = false;+ bool has_pixel_aspect_ratio = false;+ bool has_screen_window_center = false;+ bool has_screen_window_width = false;+ bool has_name = false;+ bool has_type = false;++ info->name.clear();+ info->type.clear();++ info->data_window.min_x = 0;+ info->data_window.min_y = 0;+ info->data_window.max_x = 0;+ info->data_window.max_y = 0;+ info->line_order = 0; // @fixme+ info->display_window.min_x = 0;+ info->display_window.min_y = 0;+ info->display_window.max_x = 0;+ info->display_window.max_y = 0;+ info->screen_window_center[0] = 0.0f;+ info->screen_window_center[1] = 0.0f;+ info->screen_window_width = -1.0f;+ info->pixel_aspect_ratio = -1.0f;++ info->tiled = 0;+ info->tile_size_x = -1;+ info->tile_size_y = -1;+ info->tile_level_mode = -1;+ info->tile_rounding_mode = -1;++ info->attributes.clear();++ // Read attributes+ size_t orig_size = size;+ for (size_t nattr = 0; nattr < TINYEXR_MAX_HEADER_ATTRIBUTES; nattr++) {+ if (0 == size) {+ if (err) {+ (*err) += "Insufficient data size for attributes.\n";+ }+ return TINYEXR_ERROR_INVALID_DATA;+ } else if (marker[0] == '\0') {+ size--;+ break;+ }++ std::string attr_name;+ std::string attr_type;+ std::vector<unsigned char> data;+ size_t marker_size;+ if (!tinyexr::ReadAttribute(&attr_name, &attr_type, &data, &marker_size,+ marker, size)) {+ if (err) {+ (*err) += "Failed to read attribute.\n";+ }+ return TINYEXR_ERROR_INVALID_DATA;+ }+ marker += marker_size;+ size -= marker_size;++ // For a multipart file, the version field 9th bit is 0.+ if ((version->tiled || version->multipart || version->non_image) && attr_name.compare("tiles") == 0) {+ unsigned int x_size, y_size;+ unsigned char tile_mode;+ if (data.size() != 9) {+ if (err) {+ (*err) += "(ParseEXRHeader) Invalid attribute data size. Attribute data size must be 9.\n";+ }+ return TINYEXR_ERROR_INVALID_DATA;+ }++ memcpy(&x_size, &data.at(0), sizeof(int));+ memcpy(&y_size, &data.at(4), sizeof(int));+ tile_mode = data[8];+ tinyexr::swap4(&x_size);+ tinyexr::swap4(&y_size);++ if (x_size > static_cast<unsigned int>(std::numeric_limits<int>::max()) ||+ y_size > static_cast<unsigned int>(std::numeric_limits<int>::max())) {+ if (err) {+ (*err) = "Tile sizes were invalid.";+ }+ return TINYEXR_ERROR_UNSUPPORTED_FORMAT;+ }++ info->tile_size_x = static_cast<int>(x_size);+ info->tile_size_y = static_cast<int>(y_size);++ // mode = levelMode + roundingMode * 16+ info->tile_level_mode = tile_mode & 0x3;+ info->tile_rounding_mode = (tile_mode >> 4) & 0x1;+ info->tiled = 1;+ } else if (attr_name.compare("compression") == 0) {+ bool ok = false;+ if (data[0] < TINYEXR_COMPRESSIONTYPE_PIZ) {+ ok = true;+ }++ if (data[0] == TINYEXR_COMPRESSIONTYPE_PIZ) {+#if TINYEXR_USE_PIZ+ ok = true;+#else+ if (err) {+ (*err) = "PIZ compression is not supported.";+ }+ return TINYEXR_ERROR_UNSUPPORTED_FORMAT;+#endif+ }++ if (data[0] == TINYEXR_COMPRESSIONTYPE_ZFP) {+#if TINYEXR_USE_ZFP+ ok = true;+#else+ if (err) {+ (*err) = "ZFP compression is not supported.";+ }+ return TINYEXR_ERROR_UNSUPPORTED_FORMAT;+#endif+ }++ // PXR24, B44, B44A compression types+ if (data[0] == TINYEXR_COMPRESSIONTYPE_PXR24 ||+ data[0] == TINYEXR_COMPRESSIONTYPE_B44 ||+ data[0] == TINYEXR_COMPRESSIONTYPE_B44A) {+ ok = true;+ }++ if (!ok) {+ if (err) {+ (*err) = "Unknown compression type.";+ }+ return TINYEXR_ERROR_UNSUPPORTED_FORMAT;+ }++ info->compression_type = static_cast<int>(data[0]);+ has_compression = true;++ } else if (attr_name.compare("channels") == 0) {+ // name: zero-terminated string, from 1 to 255 bytes long+ // pixel type: int, possible values are: UINT = 0 HALF = 1 FLOAT = 2+ // pLinear: unsigned char, possible values are 0 and 1+ // reserved: three chars, should be zero+ // xSampling: int+ // ySampling: int++ if (!ReadChannelInfo(info->channels, data)) {+ if (err) {+ (*err) += "Failed to parse channel info.\n";+ }+ return TINYEXR_ERROR_INVALID_DATA;+ }++ if (info->channels.size() < 1) {+ if (err) {+ (*err) += "# of channels is zero.\n";+ }+ return TINYEXR_ERROR_INVALID_DATA;+ }++ has_channels = true;++ } else if (attr_name.compare("dataWindow") == 0) {+ if (data.size() >= 16) {+ memcpy(&info->data_window.min_x, &data.at(0), sizeof(int));+ memcpy(&info->data_window.min_y, &data.at(4), sizeof(int));+ memcpy(&info->data_window.max_x, &data.at(8), sizeof(int));+ memcpy(&info->data_window.max_y, &data.at(12), sizeof(int));+ tinyexr::swap4(&info->data_window.min_x);+ tinyexr::swap4(&info->data_window.min_y);+ tinyexr::swap4(&info->data_window.max_x);+ tinyexr::swap4(&info->data_window.max_y);+ has_data_window = true;+ }+ } else if (attr_name.compare("displayWindow") == 0) {+ if (data.size() >= 16) {+ memcpy(&info->display_window.min_x, &data.at(0), sizeof(int));+ memcpy(&info->display_window.min_y, &data.at(4), sizeof(int));+ memcpy(&info->display_window.max_x, &data.at(8), sizeof(int));+ memcpy(&info->display_window.max_y, &data.at(12), sizeof(int));+ tinyexr::swap4(&info->display_window.min_x);+ tinyexr::swap4(&info->display_window.min_y);+ tinyexr::swap4(&info->display_window.max_x);+ tinyexr::swap4(&info->display_window.max_y);++ has_display_window = true;+ }+ } else if (attr_name.compare("lineOrder") == 0) {+ if (data.size() >= 1) {+ info->line_order = static_cast<int>(data[0]);+ has_line_order = true;+ }+ } else if (attr_name.compare("pixelAspectRatio") == 0) {+ if (data.size() >= sizeof(float)) {+ memcpy(&info->pixel_aspect_ratio, &data.at(0), sizeof(float));+ tinyexr::swap4(&info->pixel_aspect_ratio);+ has_pixel_aspect_ratio = true;+ }+ } else if (attr_name.compare("screenWindowCenter") == 0) {+ if (data.size() >= 8) {+ memcpy(&info->screen_window_center[0], &data.at(0), sizeof(float));+ memcpy(&info->screen_window_center[1], &data.at(4), sizeof(float));+ tinyexr::swap4(&info->screen_window_center[0]);+ tinyexr::swap4(&info->screen_window_center[1]);+ has_screen_window_center = true;+ }+ } else if (attr_name.compare("screenWindowWidth") == 0) {+ if (data.size() >= sizeof(float)) {+ memcpy(&info->screen_window_width, &data.at(0), sizeof(float));+ tinyexr::swap4(&info->screen_window_width);++ has_screen_window_width = true;+ }+ } else if (attr_name.compare("chunkCount") == 0) {+ if (data.size() >= sizeof(int)) {+ memcpy(&info->chunk_count, &data.at(0), sizeof(int));+ tinyexr::swap4(&info->chunk_count);+ }+ } else if (attr_name.compare("name") == 0) {+ if (!data.empty() && data[0]) {+ data.push_back(0);+ size_t len = strlen(reinterpret_cast<const char*>(&data[0]));+ info->name.resize(len);+ info->name.assign(reinterpret_cast<const char*>(&data[0]), len);+ has_name = true;+ }+ } else if (attr_name.compare("type") == 0) {+ if (!data.empty() && data[0]) {+ data.push_back(0);+ size_t len = strlen(reinterpret_cast<const char*>(&data[0]));+ info->type.resize(len);+ info->type.assign(reinterpret_cast<const char*>(&data[0]), len);+ has_type = true;+ }+ } else {+ // Custom attribute(up to TINYEXR_MAX_CUSTOM_ATTRIBUTES)+ if (info->attributes.size() < TINYEXR_MAX_CUSTOM_ATTRIBUTES) {+ EXRAttribute attrib;+#ifdef _MSC_VER+ strncpy_s(attrib.name, attr_name.c_str(), 255);+ strncpy_s(attrib.type, attr_type.c_str(), 255);+#else+ strncpy(attrib.name, attr_name.c_str(), 255);+ strncpy(attrib.type, attr_type.c_str(), 255);+#endif+ attrib.name[255] = '\0';+ attrib.type[255] = '\0';+ //std::cout << "i = " << info->attributes.size() << ", dsize = " << data.size() << "\n";+ attrib.size = static_cast<int>(data.size());+ attrib.value = static_cast<unsigned char *>(malloc(data.size()));+ memcpy(reinterpret_cast<char *>(attrib.value), &data.at(0),+ data.size());+ info->attributes.push_back(attrib);+ }+ }+ }++ // Check if required attributes exist+ {+ std::stringstream ss_err;++ if (!has_compression) {+ ss_err << "\"compression\" attribute not found in the header."+ << std::endl;+ }++ if (!has_channels) {+ ss_err << "\"channels\" attribute not found in the header." << std::endl;+ }++ if (!has_line_order) {+ ss_err << "\"lineOrder\" attribute not found in the header." << std::endl;+ }++ if (!has_display_window) {+ ss_err << "\"displayWindow\" attribute not found in the header."+ << std::endl;+ }++ if (!has_data_window) {+ ss_err << "\"dataWindow\" attribute not found in the header or invalid."+ << std::endl;+ }++ if (!has_pixel_aspect_ratio) {+ ss_err << "\"pixelAspectRatio\" attribute not found in the header."+ << std::endl;+ }++ if (!has_screen_window_width) {+ ss_err << "\"screenWindowWidth\" attribute not found in the header."+ << std::endl;+ }++ if (!has_screen_window_center) {+ ss_err << "\"screenWindowCenter\" attribute not found in the header."+ << std::endl;+ }++ if (version->multipart || version->non_image) {+ if (!has_name) {+ ss_err << "\"name\" attribute not found in the header."+ << std::endl;+ }+ if (!has_type) {+ ss_err << "\"type\" attribute not found in the header."+ << std::endl;+ }+ }++ if (!(ss_err.str().empty())) {+ if (err) {+ (*err) += ss_err.str();+ }++ return TINYEXR_ERROR_INVALID_HEADER;+ }+ }++ info->header_len = static_cast<unsigned int>(orig_size - size);++ return TINYEXR_SUCCESS;+}++// C++ HeaderInfo to C EXRHeader conversion.+static bool ConvertHeader(EXRHeader *exr_header, const HeaderInfo &info, std::string *warn, std::string *err) {+ exr_header->pixel_aspect_ratio = info.pixel_aspect_ratio;+ exr_header->screen_window_center[0] = info.screen_window_center[0];+ exr_header->screen_window_center[1] = info.screen_window_center[1];+ exr_header->screen_window_width = info.screen_window_width;+ exr_header->chunk_count = info.chunk_count;+ exr_header->display_window.min_x = info.display_window.min_x;+ exr_header->display_window.min_y = info.display_window.min_y;+ exr_header->display_window.max_x = info.display_window.max_x;+ exr_header->display_window.max_y = info.display_window.max_y;+ exr_header->data_window.min_x = info.data_window.min_x;+ exr_header->data_window.min_y = info.data_window.min_y;+ exr_header->data_window.max_x = info.data_window.max_x;+ exr_header->data_window.max_y = info.data_window.max_y;+ exr_header->line_order = info.line_order;+ exr_header->compression_type = info.compression_type;+ exr_header->tiled = info.tiled;+ exr_header->tile_size_x = info.tile_size_x;+ exr_header->tile_size_y = info.tile_size_y;+ exr_header->tile_level_mode = info.tile_level_mode;+ exr_header->tile_rounding_mode = info.tile_rounding_mode;++ EXRSetNameAttr(exr_header, info.name.c_str());+++ if (!info.type.empty()) {+ bool valid = true;+ if (info.type == "scanlineimage") {+ if (exr_header->tiled) {+ if (err) {+ (*err) += "(ConvertHeader) tiled bit must be off for `scanlineimage` type.\n";+ }+ valid = false;+ }+ } else if (info.type == "tiledimage") {+ if (!exr_header->tiled) {+ if (err) {+ (*err) += "(ConvertHeader) tiled bit must be on for `tiledimage` type.\n";+ }+ valid = false;+ }+ } else if (info.type == "deeptile") {+ exr_header->non_image = 1;+ if (!exr_header->tiled) {+ if (err) {+ (*err) += "(ConvertHeader) tiled bit must be on for `deeptile` type.\n";+ }+ valid = false;+ }+ } else if (info.type == "deepscanline") {+ exr_header->non_image = 1;+ if (exr_header->tiled) {+ if (err) {+ (*err) += "(ConvertHeader) tiled bit must be off for `deepscanline` type.\n";+ }+ //valid = false;+ }+ } else {+ if (warn) {+ std::stringstream ss;+ ss << "(ConvertHeader) Unsupported or unknown info.type: " << info.type << "\n";+ (*warn) += ss.str();+ }+ }++ if (!valid) {+ return false;+ }+ }++ exr_header->num_channels = static_cast<int>(info.channels.size());++ exr_header->channels = static_cast<EXRChannelInfo *>(malloc(+ sizeof(EXRChannelInfo) * static_cast<size_t>(exr_header->num_channels)));+ for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) {+#ifdef _MSC_VER+ strncpy_s(exr_header->channels[c].name, info.channels[c].name.c_str(), 255);+#else+ strncpy(exr_header->channels[c].name, info.channels[c].name.c_str(), 255);+#endif+ // manually add '\0' for safety.+ exr_header->channels[c].name[255] = '\0';++ exr_header->channels[c].pixel_type = info.channels[c].pixel_type;+ exr_header->channels[c].p_linear = info.channels[c].p_linear;+ exr_header->channels[c].x_sampling = info.channels[c].x_sampling;+ exr_header->channels[c].y_sampling = info.channels[c].y_sampling;+ }++ exr_header->pixel_types = static_cast<int *>(+ malloc(sizeof(int) * static_cast<size_t>(exr_header->num_channels)));+ for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) {+ exr_header->pixel_types[c] = info.channels[c].pixel_type;+ }++ // Initially fill with values of `pixel_types`+ exr_header->requested_pixel_types = static_cast<int *>(+ malloc(sizeof(int) * static_cast<size_t>(exr_header->num_channels)));+ for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) {+ exr_header->requested_pixel_types[c] = info.channels[c].pixel_type;+ }++ exr_header->num_custom_attributes = static_cast<int>(info.attributes.size());++ if (exr_header->num_custom_attributes > 0) {+ // TODO(syoyo): Report warning when # of attributes exceeds+ // `TINYEXR_MAX_CUSTOM_ATTRIBUTES`+ if (exr_header->num_custom_attributes > TINYEXR_MAX_CUSTOM_ATTRIBUTES) {+ exr_header->num_custom_attributes = TINYEXR_MAX_CUSTOM_ATTRIBUTES;+ }++ exr_header->custom_attributes = static_cast<EXRAttribute *>(malloc(+ sizeof(EXRAttribute) * size_t(exr_header->num_custom_attributes)));++ for (size_t i = 0; i < size_t(exr_header->num_custom_attributes); i++) {+ memcpy(exr_header->custom_attributes[i].name, info.attributes[i].name,+ 256);+ memcpy(exr_header->custom_attributes[i].type, info.attributes[i].type,+ 256);+ exr_header->custom_attributes[i].size = info.attributes[i].size;+ // Just copy pointer+ exr_header->custom_attributes[i].value = info.attributes[i].value;+ }++ } else {+ exr_header->custom_attributes = NULL;+ }++ exr_header->header_len = info.header_len;++ return true;+}++struct OffsetData {+ OffsetData() : num_x_levels(0), num_y_levels(0) {}+ std::vector<std::vector<std::vector <tinyexr::tinyexr_uint64> > > offsets;+ int num_x_levels;+ int num_y_levels;+};++// -1 = error+static int LevelIndex(int lx, int ly, int tile_level_mode, int num_x_levels) {+ switch (tile_level_mode) {+ case TINYEXR_TILE_ONE_LEVEL:+ return 0;++ case TINYEXR_TILE_MIPMAP_LEVELS:+ return lx;++ case TINYEXR_TILE_RIPMAP_LEVELS:+ return lx + ly * num_x_levels;++ default:+ return -1;+ }+ return 0;+}++static int LevelSize(int toplevel_size, int level, int tile_rounding_mode) {+ if (level < 0) {+ return -1;+ }++ int b = static_cast<int>(1u << static_cast<unsigned int>(level));+ int level_size = toplevel_size / b;++ if (tile_rounding_mode == TINYEXR_TILE_ROUND_UP && level_size * b < toplevel_size)+ level_size += 1;++ return std::max(level_size, 1);+}++static int DecodeTiledLevel(EXRImage* exr_image, const EXRHeader* exr_header,+ const OffsetData& offset_data,+ const std::vector<size_t>& channel_offset_list,+ int pixel_data_size,+ const unsigned char* head, const size_t size,+ std::string* err) {+ int num_channels = exr_header->num_channels;++ int level_index = LevelIndex(exr_image->level_x, exr_image->level_y, exr_header->tile_level_mode, offset_data.num_x_levels);+ int num_y_tiles = int(offset_data.offsets[size_t(level_index)].size());+ if (num_y_tiles < 1) {+ return TINYEXR_ERROR_INVALID_DATA;+ }+ int num_x_tiles = int(offset_data.offsets[size_t(level_index)][0].size());+ if (num_x_tiles < 1) {+ return TINYEXR_ERROR_INVALID_DATA;+ }+ int num_tiles = num_x_tiles * num_y_tiles;++ int err_code = TINYEXR_SUCCESS;++ enum {+ EF_SUCCESS = 0,+ EF_INVALID_DATA = 1,+ EF_INSUFFICIENT_DATA = 2,+ EF_FAILED_TO_DECODE = 4+ };+#if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0)+ std::atomic<unsigned> error_flag(EF_SUCCESS);+#else+ unsigned error_flag(EF_SUCCESS);+#endif++ // Although the spec says : "...the data window is subdivided into an array of smaller rectangles...",+ // the IlmImf library allows the dimensions of the tile to be larger (or equal) than the dimensions of the data window.+#if 0+ if ((exr_header->tile_size_x > exr_image->width || exr_header->tile_size_y > exr_image->height) &&+ exr_image->level_x == 0 && exr_image->level_y == 0) {+ if (err) {+ (*err) += "Failed to decode tile data.\n";+ }+ err_code = TINYEXR_ERROR_INVALID_DATA;+ }+#endif+ exr_image->tiles = static_cast<EXRTile*>(+ calloc(static_cast<size_t>(num_tiles), sizeof(EXRTile)));++#if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0)+ std::vector<std::thread> workers;+ std::atomic<int> tile_count(0);++ int num_threads = std::max(1, int(std::thread::hardware_concurrency()));+#if (TINYEXR_MAX_THREADS > 0)+ num_threads = std::min(num_threads,TINYEXR_MAX_THREADS);+#endif+ if (num_threads > int(num_tiles)) {+ num_threads = int(num_tiles);+ }+ for (int t = 0; t < num_threads; t++) {+ workers.emplace_back(std::thread([&]()+ {+ int tile_idx = 0;+ while ((tile_idx = tile_count++) < num_tiles) {++#else+#if TINYEXR_USE_OPENMP+#pragma omp parallel for+#endif+ for (int tile_idx = 0; tile_idx < num_tiles; tile_idx++) {+#endif+ // Allocate memory for each tile.+ bool alloc_success = false;+ exr_image->tiles[tile_idx].images = tinyexr::AllocateImage(+ num_channels, exr_header->channels,+ exr_header->requested_pixel_types, exr_header->tile_size_x,+ exr_header->tile_size_y, &alloc_success);++ if (!alloc_success) {+ error_flag |= EF_INVALID_DATA;+ continue;+ }++ int x_tile = tile_idx % num_x_tiles;+ int y_tile = tile_idx / num_x_tiles;+ // 16 byte: tile coordinates+ // 4 byte : data size+ // ~ : data(uncompressed or compressed)+ tinyexr::tinyexr_uint64 offset = offset_data.offsets[size_t(level_index)][size_t(y_tile)][size_t(x_tile)];+ if (offset + sizeof(int) * 5 > size) {+ // Insufficient data size.+ error_flag |= EF_INSUFFICIENT_DATA;+ continue;+ }++ size_t data_size =+ size_t(size - (offset + sizeof(int) * 5));+ const unsigned char* data_ptr =+ reinterpret_cast<const unsigned char*>(head + offset);++ int tile_coordinates[4];+ memcpy(tile_coordinates, data_ptr, sizeof(int) * 4);+ tinyexr::swap4(&tile_coordinates[0]);+ tinyexr::swap4(&tile_coordinates[1]);+ tinyexr::swap4(&tile_coordinates[2]);+ tinyexr::swap4(&tile_coordinates[3]);++ if (tile_coordinates[2] != exr_image->level_x) {+ // Invalid data.+ error_flag |= EF_INVALID_DATA;+ continue;+ }+ if (tile_coordinates[3] != exr_image->level_y) {+ // Invalid data.+ error_flag |= EF_INVALID_DATA;+ continue;+ }++ int data_len;+ memcpy(&data_len, data_ptr + 16,+ sizeof(int)); // 16 = sizeof(tile_coordinates)+ tinyexr::swap4(&data_len);++ if (data_len < 2 || size_t(data_len) > data_size) {+ // Insufficient data size.+ error_flag |= EF_INSUFFICIENT_DATA;+ continue;+ }++ // Move to data addr: 20 = 16 + 4;+ data_ptr += 20;+ bool ret = tinyexr::DecodeTiledPixelData(+ exr_image->tiles[tile_idx].images,+ &(exr_image->tiles[tile_idx].width),+ &(exr_image->tiles[tile_idx].height),+ exr_header->requested_pixel_types, data_ptr,+ static_cast<size_t>(data_len), exr_header->compression_type,+ exr_image->width, exr_image->height,+ tile_coordinates[0], tile_coordinates[1], exr_header->tile_size_x,+ exr_header->tile_size_y, static_cast<size_t>(pixel_data_size),+ static_cast<size_t>(exr_header->num_custom_attributes),+ exr_header->custom_attributes,+ static_cast<size_t>(exr_header->num_channels),+ exr_header->channels, channel_offset_list);++ if (!ret) {+ // Failed to decode tile data.+ error_flag |= EF_FAILED_TO_DECODE;+ }++ exr_image->tiles[tile_idx].offset_x = tile_coordinates[0];+ exr_image->tiles[tile_idx].offset_y = tile_coordinates[1];+ exr_image->tiles[tile_idx].level_x = tile_coordinates[2];+ exr_image->tiles[tile_idx].level_y = tile_coordinates[3];++#if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0)+ }+ }));+ } // num_thread loop++ for (auto& t : workers) {+ t.join();+ }++#else+ } // parallel for+#endif++ // Even in the event of an error, the reserved memory may be freed.+ exr_image->num_channels = num_channels;+ exr_image->num_tiles = static_cast<int>(num_tiles);++ if (error_flag) err_code = TINYEXR_ERROR_INVALID_DATA;+ if (err) {+ if (error_flag & EF_INSUFFICIENT_DATA) {+ (*err) += "Insufficient data length.\n";+ }+ if (error_flag & EF_FAILED_TO_DECODE) {+ (*err) += "Failed to decode tile data.\n";+ }+ }+ return err_code;+}++static int DecodeChunk(EXRImage *exr_image, const EXRHeader *exr_header,+ const OffsetData& offset_data,+ const unsigned char *head, const size_t size,+ std::string *err) {+ int num_channels = exr_header->num_channels;++ int num_scanline_blocks = 1;+ if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) {+ num_scanline_blocks = 16;+ } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) {+ num_scanline_blocks = 32;+ } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {+ num_scanline_blocks = 16;+ } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PXR24) {+ num_scanline_blocks = 16;+ } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_B44 ||+ exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_B44A) {+ num_scanline_blocks = 32;+ }++#if TINYEXR_USE_ZFP+ if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {+ tinyexr::ZFPCompressionParam zfp_compression_param;+ if (!FindZFPCompressionParam(&zfp_compression_param,+ exr_header->custom_attributes,+ int(exr_header->num_custom_attributes), err)) {+ return TINYEXR_ERROR_INVALID_HEADER;+ }+ }+#endif++ if (exr_header->data_window.max_x < exr_header->data_window.min_x ||+ exr_header->data_window.max_y < exr_header->data_window.min_y) {+ if (err) {+ (*err) += "Invalid data window.\n";+ }+ return TINYEXR_ERROR_INVALID_DATA;+ }++ tinyexr_int64 data_width =+ static_cast<tinyexr_int64>(exr_header->data_window.max_x) - static_cast<tinyexr_int64>(exr_header->data_window.min_x) + static_cast<tinyexr_int64>(1);+ tinyexr_int64 data_height =+ static_cast<tinyexr_int64>(exr_header->data_window.max_y) - static_cast<tinyexr_int64>(exr_header->data_window.min_y) + static_cast<tinyexr_int64>(1);++ if (data_width <= 0) {+ if (err) {+ (*err) += "Invalid data window width.\n";+ }+ return TINYEXR_ERROR_INVALID_DATA;+ }++ if (data_height <= 0) {+ if (err) {+ (*err) += "Invalid data window height.\n";+ }+ return TINYEXR_ERROR_INVALID_DATA;+ }++ // Do not allow too large data_width and data_height. header invalid?+ {+ if ((data_width > TINYEXR_DIMENSION_THRESHOLD) || (data_height > TINYEXR_DIMENSION_THRESHOLD)) {+ if (err) {+ std::stringstream ss;+ ss << "data_with or data_height too large. data_width: " << data_width+ << ", "+ << "data_height = " << data_height << std::endl;+ (*err) += ss.str();+ }+ return TINYEXR_ERROR_INVALID_DATA;+ }+ if (exr_header->tiled) {+ if ((exr_header->tile_size_x > TINYEXR_DIMENSION_THRESHOLD) || (exr_header->tile_size_y > TINYEXR_DIMENSION_THRESHOLD)) {+ if (err) {+ std::stringstream ss;+ ss << "tile with or tile height too large. tile width: " << exr_header->tile_size_x+ << ", "+ << "tile height = " << exr_header->tile_size_y << std::endl;+ (*err) += ss.str();+ }+ return TINYEXR_ERROR_INVALID_DATA;+ }+ }+ }++ const std::vector<tinyexr::tinyexr_uint64>& offsets = offset_data.offsets[0][0];+ size_t num_blocks = offsets.size();++ std::vector<size_t> channel_offset_list;+ int pixel_data_size = 0;+ size_t channel_offset = 0;+ if (!tinyexr::ComputeChannelLayout(&channel_offset_list, &pixel_data_size,+ &channel_offset, num_channels,+ exr_header->channels)) {+ if (err) {+ (*err) += "Failed to compute channel layout.\n";+ }+ return TINYEXR_ERROR_INVALID_DATA;+ }++#if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0)+ std::atomic<bool> invalid_data(false);+#else+ bool invalid_data(false);+#endif++ if (exr_header->tiled) {+ // value check+ if (exr_header->tile_size_x < 0) {+ if (err) {+ std::stringstream ss;+ ss << "Invalid tile size x : " << exr_header->tile_size_x << "\n";+ (*err) += ss.str();+ }+ return TINYEXR_ERROR_INVALID_HEADER;+ }++ if (exr_header->tile_size_y < 0) {+ if (err) {+ std::stringstream ss;+ ss << "Invalid tile size y : " << exr_header->tile_size_y << "\n";+ (*err) += ss.str();+ }+ return TINYEXR_ERROR_INVALID_HEADER;+ }+ if (exr_header->tile_level_mode != TINYEXR_TILE_RIPMAP_LEVELS) {+ EXRImage* level_image = NULL;+ for (int level = 0; level < offset_data.num_x_levels; ++level) {+ if (!level_image) {+ level_image = exr_image;+ } else {+ level_image->next_level = new EXRImage;+ InitEXRImage(level_image->next_level);+ level_image = level_image->next_level;+ }+ level_image->width =+ LevelSize(exr_header->data_window.max_x - exr_header->data_window.min_x + 1, level, exr_header->tile_rounding_mode);+ if (level_image->width < 1) {+ return TINYEXR_ERROR_INVALID_DATA;+ }++ level_image->height =+ LevelSize(exr_header->data_window.max_y - exr_header->data_window.min_y + 1, level, exr_header->tile_rounding_mode);++ if (level_image->height < 1) {+ return TINYEXR_ERROR_INVALID_DATA;+ }++ level_image->level_x = level;+ level_image->level_y = level;++ int ret = DecodeTiledLevel(level_image, exr_header,+ offset_data,+ channel_offset_list,+ pixel_data_size,+ head, size,+ err);+ if (ret != TINYEXR_SUCCESS) return ret;+ }+ } else {+ EXRImage* level_image = NULL;+ for (int level_y = 0; level_y < offset_data.num_y_levels; ++level_y)+ for (int level_x = 0; level_x < offset_data.num_x_levels; ++level_x) {+ if (!level_image) {+ level_image = exr_image;+ } else {+ level_image->next_level = new EXRImage;+ InitEXRImage(level_image->next_level);+ level_image = level_image->next_level;+ }++ level_image->width =+ LevelSize(exr_header->data_window.max_x - exr_header->data_window.min_x + 1, level_x, exr_header->tile_rounding_mode);+ if (level_image->width < 1) {+ return TINYEXR_ERROR_INVALID_DATA;+ }++ level_image->height =+ LevelSize(exr_header->data_window.max_y - exr_header->data_window.min_y + 1, level_y, exr_header->tile_rounding_mode);+ if (level_image->height < 1) {+ return TINYEXR_ERROR_INVALID_DATA;+ }++ level_image->level_x = level_x;+ level_image->level_y = level_y;++ int ret = DecodeTiledLevel(level_image, exr_header,+ offset_data,+ channel_offset_list,+ pixel_data_size,+ head, size,+ err);+ if (ret != TINYEXR_SUCCESS) return ret;+ }+ }+ } else { // scanline format+ // Don't allow too large image(256GB * pixel_data_size or more). Workaround+ // for #104.+ size_t total_data_len =+ size_t(data_width) * size_t(data_height) * size_t(num_channels);+ const bool total_data_len_overflown =+ sizeof(void *) == 8 ? (total_data_len >= 0x4000000000) : false;+ if ((total_data_len == 0) || total_data_len_overflown) {+ if (err) {+ std::stringstream ss;+ ss << "Image data size is zero or too large: width = " << data_width+ << ", height = " << data_height << ", channels = " << num_channels+ << std::endl;+ (*err) += ss.str();+ }+ return TINYEXR_ERROR_INVALID_DATA;+ }++ bool alloc_success = false;+ exr_image->images = tinyexr::AllocateImage(+ num_channels, exr_header->channels, exr_header->requested_pixel_types,+ int(data_width), int(data_height), &alloc_success);++ if (!alloc_success) {+ if (err) {+ std::stringstream ss;+ ss << "Failed to allocate memory for Images. Maybe EXR header is corrupted or Image data size is too large: width = " << data_width+ << ", height = " << data_height << ", channels = " << num_channels+ << std::endl;+ (*err) += ss.str();+ }+ return TINYEXR_ERROR_INVALID_DATA;+ }++#if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0)+ std::vector<std::thread> workers;+ std::atomic<int> y_count(0);++ int num_threads = std::max(1, int(std::thread::hardware_concurrency()));+#if (TINYEXR_MAX_THREADS > 0)+ num_threads = std::min(num_threads,TINYEXR_MAX_THREADS);+#endif+ if (num_threads > int(num_blocks)) {+ num_threads = int(num_blocks);+ }+ for (int t = 0; t < num_threads; t++) {+ workers.emplace_back(std::thread([&]() {+ int y = 0;+ while ((y = y_count++) < int(num_blocks)) {++#else++#if TINYEXR_USE_OPENMP+#pragma omp parallel for+#endif+ for (int y = 0; y < static_cast<int>(num_blocks); y++) {++#endif+ size_t y_idx = static_cast<size_t>(y);++ if (offsets[y_idx] + sizeof(int) * 2 > size) {+ invalid_data = true;+ } else {+ // 4 byte: scan line+ // 4 byte: data size+ // ~ : pixel data(uncompressed or compressed)+ size_t data_size =+ size_t(size - (offsets[y_idx] + sizeof(int) * 2));+ const unsigned char *data_ptr =+ reinterpret_cast<const unsigned char *>(head + offsets[y_idx]);++ int line_no;+ memcpy(&line_no, data_ptr, sizeof(int));+ int data_len;+ memcpy(&data_len, data_ptr + 4, sizeof(int));+ tinyexr::swap4(&line_no);+ tinyexr::swap4(&data_len);++ if (size_t(data_len) > data_size) {+ invalid_data = true;++ } else if ((line_no > (2 << 20)) || (line_no < -(2 << 20))) {+ // Too large value. Assume this is invalid+ // 2**20 = 1048576 = heuristic value.+ invalid_data = true;+ } else if (data_len == 0) {+ // TODO(syoyo): May be ok to raise the threshold for example+ // `data_len < 4`+ invalid_data = true;+ } else {+ // line_no may be negative.+ int end_line_no = (std::min)(line_no + num_scanline_blocks,+ (exr_header->data_window.max_y + 1));++ int num_lines = end_line_no - line_no;++ if (num_lines <= 0) {+ invalid_data = true;+ } else {+ // Move to data addr: 8 = 4 + 4;+ data_ptr += 8;++ // Adjust line_no with data_window.bmin.y++ // overflow check+ tinyexr_int64 lno =+ static_cast<tinyexr_int64>(line_no) -+ static_cast<tinyexr_int64>(exr_header->data_window.min_y);+ if (lno > std::numeric_limits<int>::max()) {+ line_no = -1; // invalid+ } else if (lno < -std::numeric_limits<int>::max()) {+ line_no = -1; // invalid+ } else {+ line_no -= exr_header->data_window.min_y;+ }++ if (line_no < 0) {+ invalid_data = true;+ } else {+ // Line order is increasing because we read in line offset table order.+ if (!tinyexr::DecodePixelData(+ exr_image->images, exr_header->requested_pixel_types,+ data_ptr, static_cast<size_t>(data_len),+ exr_header->compression_type, /* line_order*/ 0,+ int(data_width), int(data_height), int(data_width), y, line_no,+ num_lines, static_cast<size_t>(pixel_data_size),+ static_cast<size_t>(+ exr_header->num_custom_attributes),+ exr_header->custom_attributes,+ static_cast<size_t>(exr_header->num_channels),+ exr_header->channels, channel_offset_list)) {+ invalid_data = true;+ }+ }+ }+ }+ }++#if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0)+ }+ }));+ }++ for (auto &t : workers) {+ t.join();+ }+#else+ } // omp parallel+#endif+ }++ if (invalid_data) {+ if (err) {+ (*err) += "Invalid/Corrupted data found when decoding pixels.\n";+ }++ // free alloced image.+ for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {+ if (exr_image->images[c]) {+ free(exr_image->images[c]);+ exr_image->images[c] = NULL;+ }+ }+ return TINYEXR_ERROR_INVALID_DATA;+ }++ // Overwrite `pixel_type` with `requested_pixel_type`.+ {+ for (int c = 0; c < exr_header->num_channels; c++) {+ exr_header->pixel_types[c] = exr_header->requested_pixel_types[c];+ }+ }++ {+ exr_image->num_channels = num_channels;++ exr_image->width = int(data_width);+ exr_image->height = int(data_height);+ }++ return TINYEXR_SUCCESS;+}++static bool ReconstructLineOffsets(+ std::vector<tinyexr::tinyexr_uint64> *offsets, size_t n,+ const unsigned char *head, const unsigned char *marker, const size_t size) {+ if (head >= marker) {+ return false;+ }+ if (offsets->size() != n) {+ return false;+ }++ for (size_t i = 0; i < n; i++) {+ size_t offset = static_cast<size_t>(marker - head);+ // Offset should not exceed whole EXR file/data size.+ if ((offset + sizeof(tinyexr::tinyexr_uint64)) >= size) {+ return false;+ }++ int y;+ unsigned int data_len;++ memcpy(&y, marker, sizeof(int));+ memcpy(&data_len, marker + 4, sizeof(unsigned int));++ if (data_len >= size) {+ return false;+ }++ tinyexr::swap4(&y);+ tinyexr::swap4(&data_len);++ (*offsets)[i] = offset;++ marker += data_len + 8; // 8 = 4 bytes(y) + 4 bytes(data_len)+ }++ return true;+}+++static int FloorLog2(unsigned x) {+ //+ // For x > 0, floorLog2(y) returns floor(log(x)/log(2)).+ //+ int y = 0;+ while (x > 1) {+ y += 1;+ x >>= 1u;+ }+ return y;+}+++static int CeilLog2(unsigned x) {+ //+ // For x > 0, ceilLog2(y) returns ceil(log(x)/log(2)).+ //+ int y = 0;+ int r = 0;+ while (x > 1) {+ if (x & 1)+ r = 1;++ y += 1;+ x >>= 1u;+ }+ return y + r;+}++static int RoundLog2(int x, int tile_rounding_mode) {+ return (tile_rounding_mode == TINYEXR_TILE_ROUND_DOWN) ? FloorLog2(static_cast<unsigned>(x)) : CeilLog2(static_cast<unsigned>(x));+}++static int CalculateNumXLevels(const EXRHeader* exr_header) {+ int min_x = exr_header->data_window.min_x;+ int max_x = exr_header->data_window.max_x;+ int min_y = exr_header->data_window.min_y;+ int max_y = exr_header->data_window.max_y;++ int num = 0;+ switch (exr_header->tile_level_mode) {+ case TINYEXR_TILE_ONE_LEVEL:++ num = 1;+ break;++ case TINYEXR_TILE_MIPMAP_LEVELS:++ {+ int w = max_x - min_x + 1;+ int h = max_y - min_y + 1;+ num = RoundLog2(std::max(w, h), exr_header->tile_rounding_mode) + 1;+ }+ break;++ case TINYEXR_TILE_RIPMAP_LEVELS:++ {+ int w = max_x - min_x + 1;+ num = RoundLog2(w, exr_header->tile_rounding_mode) + 1;+ }+ break;++ default:++ return -1;+ }++ return num;+}++static int CalculateNumYLevels(const EXRHeader* exr_header) {+ int min_x = exr_header->data_window.min_x;+ int max_x = exr_header->data_window.max_x;+ int min_y = exr_header->data_window.min_y;+ int max_y = exr_header->data_window.max_y;+ int num = 0;++ switch (exr_header->tile_level_mode) {+ case TINYEXR_TILE_ONE_LEVEL:++ num = 1;+ break;++ case TINYEXR_TILE_MIPMAP_LEVELS:++ {+ int w = max_x - min_x + 1;+ int h = max_y - min_y + 1;+ num = RoundLog2(std::max(w, h), exr_header->tile_rounding_mode) + 1;+ }+ break;++ case TINYEXR_TILE_RIPMAP_LEVELS:++ {+ int h = max_y - min_y + 1;+ num = RoundLog2(h, exr_header->tile_rounding_mode) + 1;+ }+ break;++ default:++ return -1;+ }++ return num;+}++static bool CalculateNumTiles(std::vector<int>& numTiles,+ int toplevel_size,+ int size,+ int tile_rounding_mode) {+ for (unsigned i = 0; i < numTiles.size(); i++) {+ int l = LevelSize(toplevel_size, int(i), tile_rounding_mode);+ if (l < 0) {+ return false;+ }+ TINYEXR_CHECK_AND_RETURN_C(l <= std::numeric_limits<int>::max() - size + 1, false);++ numTiles[i] = (l + size - 1) / size;+ }+ return true;+}++static bool PrecalculateTileInfo(std::vector<int>& num_x_tiles,+ std::vector<int>& num_y_tiles,+ const EXRHeader* exr_header) {+ int min_x = exr_header->data_window.min_x;+ int max_x = exr_header->data_window.max_x;+ int min_y = exr_header->data_window.min_y;+ int max_y = exr_header->data_window.max_y;++ int num_x_levels = CalculateNumXLevels(exr_header);++ if (num_x_levels < 0) {+ return false;+ }++ int num_y_levels = CalculateNumYLevels(exr_header);++ if (num_y_levels < 0) {+ return false;+ }++ num_x_tiles.resize(size_t(num_x_levels));+ num_y_tiles.resize(size_t(num_y_levels));++ if (!CalculateNumTiles(num_x_tiles,+ max_x - min_x + 1,+ exr_header->tile_size_x,+ exr_header->tile_rounding_mode)) {+ return false;+ }++ if (!CalculateNumTiles(num_y_tiles,+ max_y - min_y + 1,+ exr_header->tile_size_y,+ exr_header->tile_rounding_mode)) {+ return false;+ }++ return true;+}++static void InitSingleResolutionOffsets(OffsetData& offset_data, size_t num_blocks) {+ offset_data.offsets.resize(1);+ offset_data.offsets[0].resize(1);+ offset_data.offsets[0][0].resize(num_blocks);+ offset_data.num_x_levels = 1;+ offset_data.num_y_levels = 1;+}++// Return sum of tile blocks.+// 0 = error+static int InitTileOffsets(OffsetData& offset_data,+ const EXRHeader* exr_header,+ const std::vector<int>& num_x_tiles,+ const std::vector<int>& num_y_tiles) {+ int num_tile_blocks = 0;+ offset_data.num_x_levels = static_cast<int>(num_x_tiles.size());+ offset_data.num_y_levels = static_cast<int>(num_y_tiles.size());+ switch (exr_header->tile_level_mode) {+ case TINYEXR_TILE_ONE_LEVEL:+ case TINYEXR_TILE_MIPMAP_LEVELS:+ TINYEXR_CHECK_AND_RETURN_C(offset_data.num_x_levels == offset_data.num_y_levels, 0);+ offset_data.offsets.resize(size_t(offset_data.num_x_levels));++ for (unsigned int l = 0; l < offset_data.offsets.size(); ++l) {+ offset_data.offsets[l].resize(size_t(num_y_tiles[l]));++ for (unsigned int dy = 0; dy < offset_data.offsets[l].size(); ++dy) {+ offset_data.offsets[l][dy].resize(size_t(num_x_tiles[l]));+ num_tile_blocks += num_x_tiles[l];+ }+ }+ break;++ case TINYEXR_TILE_RIPMAP_LEVELS:++ offset_data.offsets.resize(static_cast<size_t>(offset_data.num_x_levels) * static_cast<size_t>(offset_data.num_y_levels));++ for (int ly = 0; ly < offset_data.num_y_levels; ++ly) {+ for (int lx = 0; lx < offset_data.num_x_levels; ++lx) {+ int l = ly * offset_data.num_x_levels + lx;+ offset_data.offsets[size_t(l)].resize(size_t(num_y_tiles[size_t(ly)]));++ for (size_t dy = 0; dy < offset_data.offsets[size_t(l)].size(); ++dy) {+ offset_data.offsets[size_t(l)][dy].resize(size_t(num_x_tiles[size_t(lx)]));+ num_tile_blocks += num_x_tiles[size_t(lx)];+ }+ }+ }+ break;++ default:+ return 0;+ }+ return num_tile_blocks;+}++static bool IsAnyOffsetsAreInvalid(const OffsetData& offset_data) {+ for (unsigned int l = 0; l < offset_data.offsets.size(); ++l)+ for (unsigned int dy = 0; dy < offset_data.offsets[l].size(); ++dy)+ for (unsigned int dx = 0; dx < offset_data.offsets[l][dy].size(); ++dx)+ if (reinterpret_cast<const tinyexr::tinyexr_int64&>(offset_data.offsets[l][dy][dx]) <= 0)+ return true;++ return false;+}++static bool isValidTile(const EXRHeader* exr_header,+ const OffsetData& offset_data,+ int dx, int dy, int lx, int ly) {+ if (lx < 0 || ly < 0 || dx < 0 || dy < 0) return false;+ int num_x_levels = offset_data.num_x_levels;+ int num_y_levels = offset_data.num_y_levels;+ switch (exr_header->tile_level_mode) {+ case TINYEXR_TILE_ONE_LEVEL:++ if (lx == 0 &&+ ly == 0 &&+ offset_data.offsets.size() > 0 &&+ offset_data.offsets[0].size() > static_cast<size_t>(dy) &&+ offset_data.offsets[0][size_t(dy)].size() > static_cast<size_t>(dx)) {+ return true;+ }++ break;++ case TINYEXR_TILE_MIPMAP_LEVELS:++ if (lx < num_x_levels &&+ ly < num_y_levels &&+ offset_data.offsets.size() > static_cast<size_t>(lx) &&+ offset_data.offsets[size_t(lx)].size() > static_cast<size_t>(dy) &&+ offset_data.offsets[size_t(lx)][size_t(dy)].size() > static_cast<size_t>(dx)) {+ return true;+ }++ break;++ case TINYEXR_TILE_RIPMAP_LEVELS:+ {+ size_t idx = static_cast<size_t>(lx) + static_cast<size_t>(ly)* static_cast<size_t>(num_x_levels);+ if (lx < num_x_levels &&+ ly < num_y_levels &&+ (offset_data.offsets.size() > idx) &&+ offset_data.offsets[idx].size() > static_cast<size_t>(dy) &&+ offset_data.offsets[idx][size_t(dy)].size() > static_cast<size_t>(dx)) {+ return true;+ }+ }++ break;++ default:++ return false;+ }++ return false;+}++static bool ReconstructTileOffsets(OffsetData& offset_data,+ const EXRHeader* exr_header,+ const unsigned char* head, const unsigned char* marker, const size_t size,+ bool isMultiPartFile,+ bool isDeep) {+ int numXLevels = offset_data.num_x_levels;+ for (unsigned int l = 0; l < offset_data.offsets.size(); ++l) {+ for (unsigned int dy = 0; dy < offset_data.offsets[l].size(); ++dy) {+ for (unsigned int dx = 0; dx < offset_data.offsets[l][dy].size(); ++dx) {+ tinyexr::tinyexr_uint64 tileOffset = tinyexr::tinyexr_uint64(marker - head);+++ if (isMultiPartFile) {+ if ((marker + sizeof(int)) >= (head + size)) {+ return false;+ }++ //int partNumber;+ marker += sizeof(int);+ }++ if ((marker + 4 * sizeof(int)) >= (head + size)) {+ return false;+ }++ int tileX;+ memcpy(&tileX, marker, sizeof(int));+ tinyexr::swap4(&tileX);+ marker += sizeof(int);++ int tileY;+ memcpy(&tileY, marker, sizeof(int));+ tinyexr::swap4(&tileY);+ marker += sizeof(int);++ int levelX;+ memcpy(&levelX, marker, sizeof(int));+ tinyexr::swap4(&levelX);+ marker += sizeof(int);++ int levelY;+ memcpy(&levelY, marker, sizeof(int));+ tinyexr::swap4(&levelY);+ marker += sizeof(int);++ if (isDeep) {+ if ((marker + 2 * sizeof(tinyexr::tinyexr_int64)) >= (head + size)) {+ return false;+ }+ tinyexr::tinyexr_int64 packed_offset_table_size;+ memcpy(&packed_offset_table_size, marker, sizeof(tinyexr::tinyexr_int64));+ tinyexr::swap8(reinterpret_cast<tinyexr::tinyexr_uint64*>(&packed_offset_table_size));+ marker += sizeof(tinyexr::tinyexr_int64);++ tinyexr::tinyexr_int64 packed_sample_size;+ memcpy(&packed_sample_size, marker, sizeof(tinyexr::tinyexr_int64));+ tinyexr::swap8(reinterpret_cast<tinyexr::tinyexr_uint64*>(&packed_sample_size));+ marker += sizeof(tinyexr::tinyexr_int64);++ // next Int64 is unpacked sample size - skip that too+ marker += packed_offset_table_size + packed_sample_size + 8;++ if (marker >= (head + size)) {+ return false;+ }++ } else {++ if ((marker + sizeof(uint32_t)) >= (head + size)) {+ return false;+ }++ uint32_t dataSize;+ memcpy(&dataSize, marker, sizeof(uint32_t));+ tinyexr::swap4(&dataSize);+ marker += sizeof(uint32_t);++ marker += dataSize;++ if (marker >= (head + size)) {+ return false;+ }+ }++ if (!isValidTile(exr_header, offset_data,+ tileX, tileY, levelX, levelY)) {+ return false;+ }++ int level_idx = LevelIndex(levelX, levelY, exr_header->tile_level_mode, numXLevels);+ if (level_idx < 0) {+ return false;+ }++ if (size_t(level_idx) >= offset_data.offsets.size()) {+ return false;+ }++ if (size_t(tileY) >= offset_data.offsets[size_t(level_idx)].size()) {+ return false;+ }++ if (size_t(tileX) >= offset_data.offsets[size_t(level_idx)][size_t(tileY)].size()) {+ return false;+ }++ offset_data.offsets[size_t(level_idx)][size_t(tileY)][size_t(tileX)] = tileOffset;+ }+ }+ }+ return true;+}++// marker output is also+static int ReadOffsets(OffsetData& offset_data,+ const unsigned char* head,+ const unsigned char*& marker,+ const size_t size,+ const char** err) {+ for (unsigned int l = 0; l < offset_data.offsets.size(); ++l) {+ for (unsigned int dy = 0; dy < offset_data.offsets[l].size(); ++dy) {+ for (unsigned int dx = 0; dx < offset_data.offsets[l][dy].size(); ++dx) {+ tinyexr::tinyexr_uint64 offset;+ if ((marker + sizeof(tinyexr_uint64)) >= (head + size)) {+ tinyexr::SetErrorMessage("Insufficient data size in offset table.", err);+ return TINYEXR_ERROR_INVALID_DATA;+ }++ memcpy(&offset, marker, sizeof(tinyexr::tinyexr_uint64));+ tinyexr::swap8(&offset);+ if (offset >= size) {+ tinyexr::SetErrorMessage("Invalid offset value in DecodeEXRImage.", err);+ return TINYEXR_ERROR_INVALID_DATA;+ }+ marker += sizeof(tinyexr::tinyexr_uint64); // = 8+ offset_data.offsets[l][dy][dx] = offset;+ }+ }+ }+ return TINYEXR_SUCCESS;+}++static int DecodeEXRImage(EXRImage *exr_image, const EXRHeader *exr_header,+ const unsigned char *head,+ const unsigned char *marker, const size_t size,+ const char **err) {+ if (exr_image == NULL || exr_header == NULL || head == NULL ||+ marker == NULL || (size <= tinyexr::kEXRVersionSize)) {+ tinyexr::SetErrorMessage("Invalid argument for DecodeEXRImage().", err);+ return TINYEXR_ERROR_INVALID_ARGUMENT;+ }++ int num_scanline_blocks = 1;+ if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) {+ num_scanline_blocks = 16;+ } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) {+ num_scanline_blocks = 32;+ } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {+ num_scanline_blocks = 16;+ } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PXR24) {+ num_scanline_blocks = 16;+ } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_B44 ||+ exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_B44A) {+ num_scanline_blocks = 32;+ }++ if (exr_header->data_window.max_x < exr_header->data_window.min_x ||+ exr_header->data_window.max_x - exr_header->data_window.min_x ==+ std::numeric_limits<int>::max()) {+ // Issue 63+ tinyexr::SetErrorMessage("Invalid data width value", err);+ return TINYEXR_ERROR_INVALID_DATA;+ }+ tinyexr_int64 data_width =+ static_cast<tinyexr_int64>(exr_header->data_window.max_x) - static_cast<tinyexr_int64>(exr_header->data_window.min_x) + static_cast<tinyexr_int64>(1);+ if (data_width <= 0) {+ tinyexr::SetErrorMessage("Invalid data window width value", err);+ return TINYEXR_ERROR_INVALID_DATA;+ }++ if (exr_header->data_window.max_y < exr_header->data_window.min_y ||+ exr_header->data_window.max_y - exr_header->data_window.min_y ==+ std::numeric_limits<int>::max()) {+ tinyexr::SetErrorMessage("Invalid data height value", err);+ return TINYEXR_ERROR_INVALID_DATA;+ }+ tinyexr_int64 data_height =+ static_cast<tinyexr_int64>(exr_header->data_window.max_y) - static_cast<tinyexr_int64>(exr_header->data_window.min_y) + static_cast<tinyexr_int64>(1);++ if (data_height <= 0) {+ tinyexr::SetErrorMessage("Invalid data window height value", err);+ return TINYEXR_ERROR_INVALID_DATA;+ }++ // Do not allow too large data_width and data_height. header invalid?+ {+ if (data_width > TINYEXR_DIMENSION_THRESHOLD) {+ tinyexr::SetErrorMessage("data width too large.", err);+ return TINYEXR_ERROR_INVALID_DATA;+ }+ if (data_height > TINYEXR_DIMENSION_THRESHOLD) {+ tinyexr::SetErrorMessage("data height too large.", err);+ return TINYEXR_ERROR_INVALID_DATA;+ }+ }++ if (exr_header->tiled) {+ if (exr_header->tile_size_x > TINYEXR_DIMENSION_THRESHOLD) {+ tinyexr::SetErrorMessage("tile width too large.", err);+ return TINYEXR_ERROR_INVALID_DATA;+ }+ if (exr_header->tile_size_y > TINYEXR_DIMENSION_THRESHOLD) {+ tinyexr::SetErrorMessage("tile height too large.", err);+ return TINYEXR_ERROR_INVALID_DATA;+ }+ }++ // Read offset tables.+ OffsetData offset_data;+ size_t num_blocks = 0;+ // For a multi-resolution image, the size of the offset table will be calculated from the other attributes of the header.+ // If chunk_count > 0 then chunk_count must be equal to the calculated tile count.+ if (exr_header->tiled) {+ {+ std::vector<int> num_x_tiles, num_y_tiles;+ if (!PrecalculateTileInfo(num_x_tiles, num_y_tiles, exr_header)) {+ tinyexr::SetErrorMessage("Failed to precalculate tile info.", err);+ return TINYEXR_ERROR_INVALID_DATA;+ }+ num_blocks = size_t(InitTileOffsets(offset_data, exr_header, num_x_tiles, num_y_tiles));+ if (exr_header->chunk_count > 0) {+ if (exr_header->chunk_count != static_cast<int>(num_blocks)) {+ tinyexr::SetErrorMessage("Invalid offset table size.", err);+ return TINYEXR_ERROR_INVALID_DATA;+ }+ }+ }++ int ret = ReadOffsets(offset_data, head, marker, size, err);+ if (ret != TINYEXR_SUCCESS) return ret;+ if (IsAnyOffsetsAreInvalid(offset_data)) {+ if (!ReconstructTileOffsets(offset_data, exr_header,+ head, marker, size,+ exr_header->multipart, exr_header->non_image)) {++ tinyexr::SetErrorMessage("Invalid Tile Offsets data.", err);+ return TINYEXR_ERROR_INVALID_DATA;+ }+ }+ } else if (exr_header->chunk_count > 0) {+ // Use `chunkCount` attribute.+ num_blocks = static_cast<size_t>(exr_header->chunk_count);+ InitSingleResolutionOffsets(offset_data, num_blocks);+ } else {+ num_blocks = static_cast<size_t>(data_height) /+ static_cast<size_t>(num_scanline_blocks);+ if (num_blocks * static_cast<size_t>(num_scanline_blocks) <+ static_cast<size_t>(data_height)) {+ num_blocks++;+ }++ InitSingleResolutionOffsets(offset_data, num_blocks);+ }++ if (!exr_header->tiled) {+ std::vector<tinyexr::tinyexr_uint64>& offsets = offset_data.offsets[0][0];+ for (size_t y = 0; y < num_blocks; y++) {+ tinyexr::tinyexr_uint64 offset;+ // Issue #81+ if ((marker + sizeof(tinyexr_uint64)) >= (head + size)) {+ tinyexr::SetErrorMessage("Insufficient data size in offset table.", err);+ return TINYEXR_ERROR_INVALID_DATA;+ }++ memcpy(&offset, marker, sizeof(tinyexr::tinyexr_uint64));+ tinyexr::swap8(&offset);+ if (offset >= size) {+ tinyexr::SetErrorMessage("Invalid offset value in DecodeEXRImage.", err);+ return TINYEXR_ERROR_INVALID_DATA;+ }+ marker += sizeof(tinyexr::tinyexr_uint64); // = 8+ offsets[y] = offset;+ }++ // If line offsets are invalid, we try to reconstruct it.+ // See OpenEXR/IlmImf/ImfScanLineInputFile.cpp::readLineOffsets() for details.+ for (size_t y = 0; y < num_blocks; y++) {+ if (offsets[y] <= 0) {+ // TODO(syoyo) Report as warning?+ // if (err) {+ // stringstream ss;+ // ss << "Incomplete lineOffsets." << std::endl;+ // (*err) += ss.str();+ //}+ bool ret =+ ReconstructLineOffsets(&offsets, num_blocks, head, marker, size);+ if (ret) {+ // OK+ break;+ } else {+ tinyexr::SetErrorMessage(+ "Cannot reconstruct lineOffset table in DecodeEXRImage.", err);+ return TINYEXR_ERROR_INVALID_DATA;+ }+ }+ }+ }++ {+ std::string e;+ int ret = DecodeChunk(exr_image, exr_header, offset_data, head, size, &e);++ if (ret != TINYEXR_SUCCESS) {+ if (!e.empty()) {+ tinyexr::SetErrorMessage(e, err);+ }++#if 1+ FreeEXRImage(exr_image);+#else+ // release memory(if exists)+ if ((exr_header->num_channels > 0) && exr_image && exr_image->images) {+ for (size_t c = 0; c < size_t(exr_header->num_channels); c++) {+ if (exr_image->images[c]) {+ free(exr_image->images[c]);+ exr_image->images[c] = NULL;+ }+ }+ free(exr_image->images);+ exr_image->images = NULL;+ }+#endif+ }++ return ret;+ }+}++static void GetLayers(const EXRHeader &exr_header,+ std::vector<std::string> &layer_names) {+ // Naive implementation+ // Group channels by layers+ // go over all channel names, split by periods+ // collect unique names+ layer_names.clear();+ for (int c = 0; c < exr_header.num_channels; c++) {+ std::string full_name(exr_header.channels[c].name);+ const size_t pos = full_name.find_last_of('.');+ if (pos != std::string::npos && pos != 0 && pos + 1 < full_name.size()) {+ full_name.erase(pos);+ if (std::find(layer_names.begin(), layer_names.end(), full_name) ==+ layer_names.end())+ layer_names.push_back(full_name);+ }+ }+}++struct LayerChannel {+ explicit LayerChannel(size_t i, std::string n) : index(i), name(n) {}+ size_t index;+ std::string name;+};++static void ChannelsInLayer(const EXRHeader &exr_header,+ const std::string &layer_name,+ std::vector<LayerChannel> &channels) {+ channels.clear();+ //std::cout << "layer_name = " << layer_name << "\n";+ for (int c = 0; c < exr_header.num_channels; c++) {+ //std::cout << "chan[" << c << "] = " << exr_header.channels[c].name << "\n";+ std::string ch_name(exr_header.channels[c].name);+ if (layer_name.empty()) {+ const size_t pos = ch_name.find_last_of('.');+ if (pos != std::string::npos && pos < ch_name.size()) {+ if (pos != 0) continue;+ ch_name = ch_name.substr(pos + 1);+ }+ } else {+ const size_t pos = ch_name.find(layer_name + '.');+ if (pos == std::string::npos) continue;+ if (pos == 0) {+ ch_name = ch_name.substr(layer_name.size() + 1);+ }+ }+ LayerChannel ch(size_t(c), ch_name);+ channels.push_back(ch);+ }+}++} // namespace tinyexr++int EXRLayers(const char *filename, const char **layer_names[], int *num_layers,+ const char **err) {+ EXRVersion exr_version;+ EXRHeader exr_header;+ InitEXRHeader(&exr_header);++ {+ int ret = ParseEXRVersionFromFile(&exr_version, filename);+ if (ret != TINYEXR_SUCCESS) {+ tinyexr::SetErrorMessage("Invalid EXR header.", err);+ return ret;+ }++ if (exr_version.multipart || exr_version.non_image) {+ tinyexr::SetErrorMessage(+ "Loading multipart or DeepImage is not supported in LoadEXR() API",+ err);+ return TINYEXR_ERROR_INVALID_DATA; // @fixme.+ }+ }++ int ret = ParseEXRHeaderFromFile(&exr_header, &exr_version, filename, err);+ if (ret != TINYEXR_SUCCESS) {+ FreeEXRHeader(&exr_header);+ return ret;+ }++ std::vector<std::string> layer_vec;+ tinyexr::GetLayers(exr_header, layer_vec);++ (*num_layers) = int(layer_vec.size());+ (*layer_names) = static_cast<const char **>(+ malloc(sizeof(const char *) * static_cast<size_t>(layer_vec.size())));+ for (size_t c = 0; c < static_cast<size_t>(layer_vec.size()); c++) {+#ifdef _MSC_VER+ (*layer_names)[c] = _strdup(layer_vec[c].c_str());+#else+ (*layer_names)[c] = strdup(layer_vec[c].c_str());+#endif+ }++ FreeEXRHeader(&exr_header);+ return TINYEXR_SUCCESS;+}++int LoadEXR(float **out_rgba, int *width, int *height, const char *filename,+ const char **err) {+ return LoadEXRWithLayer(out_rgba, width, height, filename,+ /* layername */ NULL, err);+}++int LoadEXRWithLayer(float **out_rgba, int *width, int *height,+ const char *filename, const char *layername,+ const char **err) {+ if (out_rgba == NULL) {+ tinyexr::SetErrorMessage("Invalid argument for LoadEXR()", err);+ return TINYEXR_ERROR_INVALID_ARGUMENT;+ }++ EXRVersion exr_version;+ EXRImage exr_image;+ EXRHeader exr_header;+ InitEXRHeader(&exr_header);+ InitEXRImage(&exr_image);++ {+ int ret = ParseEXRVersionFromFile(&exr_version, filename);+ if (ret != TINYEXR_SUCCESS) {+ std::stringstream ss;+ ss << "Failed to open EXR file or read version info from EXR file. code("+ << ret << ")";+ tinyexr::SetErrorMessage(ss.str(), err);+ return ret;+ }++ if (exr_version.multipart || exr_version.non_image) {+ tinyexr::SetErrorMessage(+ "Loading multipart or DeepImage is not supported in LoadEXR() API",+ err);+ return TINYEXR_ERROR_INVALID_DATA; // @fixme.+ }+ }++ {+ int ret = ParseEXRHeaderFromFile(&exr_header, &exr_version, filename, err);+ if (ret != TINYEXR_SUCCESS) {+ FreeEXRHeader(&exr_header);+ return ret;+ }+ }++ // Read HALF channel as FLOAT.+ for (int i = 0; i < exr_header.num_channels; i++) {+ if (exr_header.pixel_types[i] == TINYEXR_PIXELTYPE_HALF) {+ exr_header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT;+ }+ }++ // TODO: Probably limit loading to layers (channels) selected by layer index+ {+ int ret = LoadEXRImageFromFile(&exr_image, &exr_header, filename, err);+ if (ret != TINYEXR_SUCCESS) {+ FreeEXRHeader(&exr_header);+ return ret;+ }+ }++ // RGBA+ int idxR = -1;+ int idxG = -1;+ int idxB = -1;+ int idxA = -1;++ std::vector<std::string> layer_names;+ tinyexr::GetLayers(exr_header, layer_names);++ std::vector<tinyexr::LayerChannel> channels;+ tinyexr::ChannelsInLayer(+ exr_header, layername == NULL ? "" : std::string(layername), channels);+++ if (channels.size() < 1) {+ if (layername == NULL) {+ tinyexr::SetErrorMessage("Layer Not Found. Seems EXR contains channels with layer(e.g. `diffuse.R`). if you are using LoadEXR(), please try LoadEXRWithLayer(). LoadEXR() cannot load EXR having channels with layer.", err);++ } else {+ tinyexr::SetErrorMessage("Layer Not Found", err);+ }+ FreeEXRHeader(&exr_header);+ FreeEXRImage(&exr_image);+ return TINYEXR_ERROR_LAYER_NOT_FOUND;+ }++ size_t ch_count = channels.size() < 4 ? channels.size() : 4;+ for (size_t c = 0; c < ch_count; c++) {+ const tinyexr::LayerChannel &ch = channels[c];++ if (ch.name == "R") {+ idxR = int(ch.index);+ } else if (ch.name == "G") {+ idxG = int(ch.index);+ } else if (ch.name == "B") {+ idxB = int(ch.index);+ } else if (ch.name == "A") {+ idxA = int(ch.index);+ }+ }++ if (channels.size() == 1) {+ int chIdx = int(channels.front().index);+ // Grayscale channel only.++ (*out_rgba) = reinterpret_cast<float *>(+ malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) *+ static_cast<size_t>(exr_image.height)));++ if (exr_header.tiled) {+ const size_t tile_size_x = static_cast<size_t>(exr_header.tile_size_x);+ const size_t tile_size_y = static_cast<size_t>(exr_header.tile_size_y);+ for (int it = 0; it < exr_image.num_tiles; it++) {+ for (size_t j = 0; j < tile_size_y; j++) {+ for (size_t i = 0; i < tile_size_x; i++) {+ const size_t ii =+ static_cast<size_t>(exr_image.tiles[it].offset_x) * tile_size_x ++ i;+ const size_t jj =+ static_cast<size_t>(exr_image.tiles[it].offset_y) * tile_size_y ++ j;+ const size_t idx = ii + jj * static_cast<size_t>(exr_image.width);++ // out of region check.+ if (ii >= static_cast<size_t>(exr_image.width)) {+ continue;+ }+ if (jj >= static_cast<size_t>(exr_image.height)) {+ continue;+ }+ const size_t srcIdx = i + j * tile_size_x;+ unsigned char **src = exr_image.tiles[it].images;+ (*out_rgba)[4 * idx + 0] =+ reinterpret_cast<float **>(src)[chIdx][srcIdx];+ (*out_rgba)[4 * idx + 1] =+ reinterpret_cast<float **>(src)[chIdx][srcIdx];+ (*out_rgba)[4 * idx + 2] =+ reinterpret_cast<float **>(src)[chIdx][srcIdx];+ (*out_rgba)[4 * idx + 3] =+ reinterpret_cast<float **>(src)[chIdx][srcIdx];+ }+ }+ }+ } else {+ const size_t pixel_size = static_cast<size_t>(exr_image.width) *+ static_cast<size_t>(exr_image.height);+ for (size_t i = 0; i < pixel_size; i++) {+ const float val =+ reinterpret_cast<float **>(exr_image.images)[chIdx][i];+ (*out_rgba)[4 * i + 0] = val;+ (*out_rgba)[4 * i + 1] = val;+ (*out_rgba)[4 * i + 2] = val;+ (*out_rgba)[4 * i + 3] = val;+ }+ }+ } else {+ // Assume RGB(A)++ if (idxR == -1) {+ tinyexr::SetErrorMessage("R channel not found", err);++ FreeEXRHeader(&exr_header);+ FreeEXRImage(&exr_image);+ return TINYEXR_ERROR_INVALID_DATA;+ }++ if (idxG == -1) {+ tinyexr::SetErrorMessage("G channel not found", err);+ FreeEXRHeader(&exr_header);+ FreeEXRImage(&exr_image);+ return TINYEXR_ERROR_INVALID_DATA;+ }++ if (idxB == -1) {+ tinyexr::SetErrorMessage("B channel not found", err);+ FreeEXRHeader(&exr_header);+ FreeEXRImage(&exr_image);+ return TINYEXR_ERROR_INVALID_DATA;+ }++ (*out_rgba) = reinterpret_cast<float *>(+ malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) *+ static_cast<size_t>(exr_image.height)));+ if (exr_header.tiled) {+ const size_t tile_size_x = static_cast<size_t>(exr_header.tile_size_x);+ const size_t tile_size_y = static_cast<size_t>(exr_header.tile_size_y);+ for (int it = 0; it < exr_image.num_tiles; it++) {+ for (size_t j = 0; j < tile_size_y; j++) {+ for (size_t i = 0; i < tile_size_x; i++) {+ const size_t ii =+ static_cast<size_t>(exr_image.tiles[it].offset_x) *+ tile_size_x ++ i;+ const size_t jj =+ static_cast<size_t>(exr_image.tiles[it].offset_y) *+ tile_size_y ++ j;+ const size_t idx = ii + jj * static_cast<size_t>(exr_image.width);++ // out of region check.+ if (ii >= static_cast<size_t>(exr_image.width)) {+ continue;+ }+ if (jj >= static_cast<size_t>(exr_image.height)) {+ continue;+ }+ const size_t srcIdx = i + j * tile_size_x;+ unsigned char **src = exr_image.tiles[it].images;+ (*out_rgba)[4 * idx + 0] =+ reinterpret_cast<float **>(src)[idxR][srcIdx];+ (*out_rgba)[4 * idx + 1] =+ reinterpret_cast<float **>(src)[idxG][srcIdx];+ (*out_rgba)[4 * idx + 2] =+ reinterpret_cast<float **>(src)[idxB][srcIdx];+ if (idxA != -1) {+ (*out_rgba)[4 * idx + 3] =+ reinterpret_cast<float **>(src)[idxA][srcIdx];+ } else {+ (*out_rgba)[4 * idx + 3] = 1.0;+ }+ }+ }+ }+ } else {+ const size_t pixel_size = static_cast<size_t>(exr_image.width) *+ static_cast<size_t>(exr_image.height);+ for (size_t i = 0; i < pixel_size; i++) {+ (*out_rgba)[4 * i + 0] =+ reinterpret_cast<float **>(exr_image.images)[idxR][i];+ (*out_rgba)[4 * i + 1] =+ reinterpret_cast<float **>(exr_image.images)[idxG][i];+ (*out_rgba)[4 * i + 2] =+ reinterpret_cast<float **>(exr_image.images)[idxB][i];+ if (idxA != -1) {+ (*out_rgba)[4 * i + 3] =+ reinterpret_cast<float **>(exr_image.images)[idxA][i];+ } else {+ (*out_rgba)[4 * i + 3] = 1.0;+ }+ }+ }+ }++ (*width) = exr_image.width;+ (*height) = exr_image.height;++ FreeEXRHeader(&exr_header);+ FreeEXRImage(&exr_image);++ return TINYEXR_SUCCESS;+}++int IsEXR(const char *filename) {+ EXRVersion exr_version;++ int ret = ParseEXRVersionFromFile(&exr_version, filename);+ if (ret != TINYEXR_SUCCESS) {+ return ret;+ }++ return TINYEXR_SUCCESS;+}++int IsEXRFromMemory(const unsigned char *memory, size_t size) {+ EXRVersion exr_version;++ int ret = ParseEXRVersionFromMemory(&exr_version, memory, size);+ if (ret != TINYEXR_SUCCESS) {+ return ret;+ }++ return TINYEXR_SUCCESS;+}++int ParseEXRHeaderFromMemory(EXRHeader *exr_header, const EXRVersion *version,+ const unsigned char *memory, size_t size,+ const char **err) {+ if (memory == NULL || exr_header == NULL) {+ tinyexr::SetErrorMessage(+ "Invalid argument. `memory` or `exr_header` argument is null in "+ "ParseEXRHeaderFromMemory()",+ err);++ // Invalid argument+ return TINYEXR_ERROR_INVALID_ARGUMENT;+ }++ if (size < tinyexr::kEXRVersionSize) {+ tinyexr::SetErrorMessage("Insufficient header/data size.\n", err);+ return TINYEXR_ERROR_INVALID_DATA;+ }++ const unsigned char *marker = memory + tinyexr::kEXRVersionSize;+ size_t marker_size = size - tinyexr::kEXRVersionSize;++ tinyexr::HeaderInfo info;+ info.clear();++ int ret;+ {+ std::string err_str;+ ret = ParseEXRHeader(&info, NULL, version, &err_str, marker, marker_size);++ if (ret != TINYEXR_SUCCESS) {+ if (err && !err_str.empty()) {+ tinyexr::SetErrorMessage(err_str, err);+ }+ }+ }++ {+ std::string warn;+ std::string err_str;++ if (!ConvertHeader(exr_header, info, &warn, &err_str)) {+ // release mem+ for (size_t i = 0; i < info.attributes.size(); i++) {+ if (info.attributes[i].value) {+ free(info.attributes[i].value);+ }+ }+ if (err && !err_str.empty()) {+ tinyexr::SetErrorMessage(err_str, err);+ }+ ret = TINYEXR_ERROR_INVALID_HEADER;+ }+ }++ exr_header->multipart = version->multipart ? 1 : 0;+ exr_header->non_image = version->non_image ? 1 : 0;++ return ret;+}++int LoadEXRFromMemory(float **out_rgba, int *width, int *height,+ const unsigned char *memory, size_t size,+ const char **err) {+ if (out_rgba == NULL || memory == NULL) {+ tinyexr::SetErrorMessage("Invalid argument for LoadEXRFromMemory", err);+ return TINYEXR_ERROR_INVALID_ARGUMENT;+ }++ EXRVersion exr_version;+ EXRImage exr_image;+ EXRHeader exr_header;++ InitEXRHeader(&exr_header);++ int ret = ParseEXRVersionFromMemory(&exr_version, memory, size);+ if (ret != TINYEXR_SUCCESS) {+ std::stringstream ss;+ ss << "Failed to parse EXR version. code(" << ret << ")";+ tinyexr::SetErrorMessage(ss.str(), err);+ return ret;+ }++ ret = ParseEXRHeaderFromMemory(&exr_header, &exr_version, memory, size, err);+ if (ret != TINYEXR_SUCCESS) {+ FreeEXRHeader(&exr_header);+ return ret;+ }++ // Read HALF channel as FLOAT.+ for (int i = 0; i < exr_header.num_channels; i++) {+ if (exr_header.pixel_types[i] == TINYEXR_PIXELTYPE_HALF) {+ exr_header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT;+ }+ }++ InitEXRImage(&exr_image);+ ret = LoadEXRImageFromMemory(&exr_image, &exr_header, memory, size, err);+ if (ret != TINYEXR_SUCCESS) {+ FreeEXRHeader(&exr_header);+ FreeEXRImage(&exr_image);+ return ret;+ }++ // RGBA+ int idxR = -1;+ int idxG = -1;+ int idxB = -1;+ int idxA = -1;+ for (int c = 0; c < exr_header.num_channels; c++) {+ if (strcmp(exr_header.channels[c].name, "R") == 0) {+ idxR = c;+ } else if (strcmp(exr_header.channels[c].name, "G") == 0) {+ idxG = c;+ } else if (strcmp(exr_header.channels[c].name, "B") == 0) {+ idxB = c;+ } else if (strcmp(exr_header.channels[c].name, "A") == 0) {+ idxA = c;+ }+ }++ // TODO(syoyo): Refactor removing same code as used in LoadEXR().+ if (exr_header.num_channels == 1) {+ // Grayscale channel only.++ (*out_rgba) = reinterpret_cast<float *>(+ malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) *+ static_cast<size_t>(exr_image.height)));++ if (exr_header.tiled) {+ const size_t tile_size_x = static_cast<size_t>(exr_header.tile_size_x);+ const size_t tile_size_y = static_cast<size_t>(exr_header.tile_size_y);+ for (int it = 0; it < exr_image.num_tiles; it++) {+ for (size_t j = 0; j < tile_size_y; j++) {+ for (size_t i = 0; i < tile_size_x; i++) {+ const size_t ii =+ static_cast<size_t>(exr_image.tiles[it].offset_x) *+ tile_size_x ++ i;+ const size_t jj =+ static_cast<size_t>(exr_image.tiles[it].offset_y) *+ tile_size_y ++ j;+ const size_t idx = ii + jj * static_cast<size_t>(exr_image.width);++ // out of region check.+ if (ii >= static_cast<size_t>(exr_image.width)) {+ continue;+ }+ if (jj >= static_cast<size_t>(exr_image.height)) {+ continue;+ }+ const size_t srcIdx = i + j * tile_size_x;+ unsigned char **src = exr_image.tiles[it].images;+ (*out_rgba)[4 * idx + 0] =+ reinterpret_cast<float **>(src)[0][srcIdx];+ (*out_rgba)[4 * idx + 1] =+ reinterpret_cast<float **>(src)[0][srcIdx];+ (*out_rgba)[4 * idx + 2] =+ reinterpret_cast<float **>(src)[0][srcIdx];+ (*out_rgba)[4 * idx + 3] =+ reinterpret_cast<float **>(src)[0][srcIdx];+ }+ }+ }+ } else {+ const size_t pixel_size = static_cast<size_t>(exr_image.width) *+ static_cast<size_t>(exr_image.height);+ for (size_t i = 0; i < pixel_size; i++) {+ const float val = reinterpret_cast<float **>(exr_image.images)[0][i];+ (*out_rgba)[4 * i + 0] = val;+ (*out_rgba)[4 * i + 1] = val;+ (*out_rgba)[4 * i + 2] = val;+ (*out_rgba)[4 * i + 3] = val;+ }+ }++ } else {+ // TODO(syoyo): Support non RGBA image.++ if (idxR == -1) {+ tinyexr::SetErrorMessage("R channel not found", err);++ // @todo { free exr_image }+ return TINYEXR_ERROR_INVALID_DATA;+ }++ if (idxG == -1) {+ tinyexr::SetErrorMessage("G channel not found", err);+ // @todo { free exr_image }+ return TINYEXR_ERROR_INVALID_DATA;+ }++ if (idxB == -1) {+ tinyexr::SetErrorMessage("B channel not found", err);+ // @todo { free exr_image }+ return TINYEXR_ERROR_INVALID_DATA;+ }++ (*out_rgba) = reinterpret_cast<float *>(+ malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) *+ static_cast<size_t>(exr_image.height)));++ if (exr_header.tiled) {+ const size_t tile_size_x = static_cast<size_t>(exr_header.tile_size_x);+ const size_t tile_size_y = static_cast<size_t>(exr_header.tile_size_y);+ for (int it = 0; it < exr_image.num_tiles; it++) {+ for (size_t j = 0; j < tile_size_y; j++)+ for (size_t i = 0; i < tile_size_x; i++) {+ const size_t ii =+ static_cast<size_t>(exr_image.tiles[it].offset_x) *+ tile_size_x ++ i;+ const size_t jj =+ static_cast<size_t>(exr_image.tiles[it].offset_y) *+ tile_size_y ++ j;+ const size_t idx = ii + jj * static_cast<size_t>(exr_image.width);++ // out of region check.+ if (ii >= static_cast<size_t>(exr_image.width)) {+ continue;+ }+ if (jj >= static_cast<size_t>(exr_image.height)) {+ continue;+ }+ const size_t srcIdx = i + j * tile_size_x;+ unsigned char **src = exr_image.tiles[it].images;+ (*out_rgba)[4 * idx + 0] =+ reinterpret_cast<float **>(src)[idxR][srcIdx];+ (*out_rgba)[4 * idx + 1] =+ reinterpret_cast<float **>(src)[idxG][srcIdx];+ (*out_rgba)[4 * idx + 2] =+ reinterpret_cast<float **>(src)[idxB][srcIdx];+ if (idxA != -1) {+ (*out_rgba)[4 * idx + 3] =+ reinterpret_cast<float **>(src)[idxA][srcIdx];+ } else {+ (*out_rgba)[4 * idx + 3] = 1.0;+ }+ }+ }+ } else {+ const size_t pixel_size = static_cast<size_t>(exr_image.width) *+ static_cast<size_t>(exr_image.height);+ for (size_t i = 0; i < pixel_size; i++) {+ (*out_rgba)[4 * i + 0] =+ reinterpret_cast<float **>(exr_image.images)[idxR][i];+ (*out_rgba)[4 * i + 1] =+ reinterpret_cast<float **>(exr_image.images)[idxG][i];+ (*out_rgba)[4 * i + 2] =+ reinterpret_cast<float **>(exr_image.images)[idxB][i];+ if (idxA != -1) {+ (*out_rgba)[4 * i + 3] =+ reinterpret_cast<float **>(exr_image.images)[idxA][i];+ } else {+ (*out_rgba)[4 * i + 3] = 1.0;+ }+ }+ }+ }++ (*width) = exr_image.width;+ (*height) = exr_image.height;++ FreeEXRHeader(&exr_header);+ FreeEXRImage(&exr_image);++ return TINYEXR_SUCCESS;+}++// Represents a read-only file mapped to an address space in memory.+// If no memory-mapping API is available, falls back to allocating a buffer+// with a copy of the file's data.+struct MemoryMappedFile {+ unsigned char *data; // To the start of the file's data.+ size_t size; // The size of the file in bytes.+#ifdef TINYEXR_USE_WIN32_MMAP+ HANDLE windows_file;+ HANDLE windows_file_mapping;+#elif defined(TINYEXR_USE_POSIX_MMAP)+ int posix_descriptor;+#endif++ // MemoryMappedFile's constructor tries to map memory to a file.+ // If this succeeds, valid() will return true and all fields+ // are usable; otherwise, valid() will return false.+ MemoryMappedFile(const char *filename) {+ data = NULL;+ size = 0;+#ifdef TINYEXR_USE_WIN32_MMAP+ windows_file_mapping = NULL;+ windows_file =+ CreateFileW(tinyexr::UTF8ToWchar(filename).c_str(), // lpFileName+ GENERIC_READ, // dwDesiredAccess+ FILE_SHARE_READ, // dwShareMode+ NULL, // lpSecurityAttributes+ OPEN_EXISTING, // dwCreationDisposition+ FILE_ATTRIBUTE_READONLY, // dwFlagsAndAttributes+ NULL); // hTemplateFile+ if (windows_file == INVALID_HANDLE_VALUE) {+ return;+ }++ windows_file_mapping = CreateFileMapping(windows_file, // hFile+ NULL, // lpFileMappingAttributes+ PAGE_READONLY, // flProtect+ 0, // dwMaximumSizeHigh+ 0, // dwMaximumSizeLow+ NULL); // lpName+ if (windows_file_mapping == NULL) {+ return;+ }++ data = reinterpret_cast<unsigned char *>(+ MapViewOfFile(windows_file_mapping, // hFileMappingObject+ FILE_MAP_READ, // dwDesiredAccess+ 0, // dwFileOffsetHigh+ 0, // dwFileOffsetLow+ 0)); // dwNumberOfBytesToMap+ if (!data) {+ return;+ }++ LARGE_INTEGER windows_file_size = {};+ if (!GetFileSizeEx(windows_file, &windows_file_size) ||+ static_cast<ULONGLONG>(windows_file_size.QuadPart) >+ std::numeric_limits<size_t>::max()) {+ UnmapViewOfFile(data);+ data = NULL;+ return;+ }+ size = static_cast<size_t>(windows_file_size.QuadPart);+#elif defined(TINYEXR_USE_POSIX_MMAP)+ posix_descriptor = open(filename, O_RDONLY);+ if (posix_descriptor == -1) {+ return;+ }++ struct stat info;+ if (fstat(posix_descriptor, &info) < 0) {+ return;+ }+ // Make sure st_size is in the valid range for a size_t. The second case+ // can only fail if a POSIX implementation defines off_t to be a larger+ // type than size_t - for instance, compiling with _FILE_OFFSET_BITS=64+ // on a 32-bit system. On current 64-bit systems, this check can never+ // fail, so we turn off clang's Wtautological-type-limit-compare warning+ // around this code.+#ifdef __clang__+#pragma clang diagnostic push+#pragma clang diagnostic ignored "-Wtautological-type-limit-compare"+#endif+ if (info.st_size < 0 ||+ info.st_size > std::numeric_limits<ssize_t>::max()) {+ return;+ }+#ifdef __clang__+#pragma clang diagnostic pop+#endif+ size = static_cast<size_t>(info.st_size);++ data = reinterpret_cast<unsigned char *>(+ mmap(0, size, PROT_READ, MAP_SHARED, posix_descriptor, 0));+ if (data == MAP_FAILED) {+ data = nullptr;+ return;+ }+#else+ FILE *fp = fopen(filename, "rb");+ if (!fp) {+ return;+ }++ // Calling fseek(fp, 0, SEEK_END) isn't strictly-conforming C code, but+ // since neither the WIN32 nor POSIX APIs are available in this branch, this+ // is a reasonable fallback option.+ if (fseek(fp, 0, SEEK_END) != 0) {+ fclose(fp);+ return;+ }+ const long ftell_result = ftell(fp);+ if (ftell_result < 0) {+ // Error from ftell+ fclose(fp);+ return;+ }+ size = static_cast<size_t>(ftell_result);+ if (fseek(fp, 0, SEEK_SET) != 0) {+ fclose(fp);+ size = 0;+ return;+ }++ data = reinterpret_cast<unsigned char *>(malloc(size));+ if (!data) {+ size = 0;+ fclose(fp);+ return;+ }+ size_t read_bytes = fread(data, 1, size, fp);+ if (read_bytes != size) {+ // TODO: Try to read data until reading `size` bytes.+ fclose(fp);+ size = 0;+ data = nullptr;+ return;+ }+ fclose(fp);+#endif+ }++ // MemoryMappedFile's destructor closes all its handles.+ ~MemoryMappedFile() {+#ifdef TINYEXR_USE_WIN32_MMAP+ if (data) {+ (void)UnmapViewOfFile(data);+ data = NULL;+ }++ if (windows_file_mapping != NULL) {+ (void)CloseHandle(windows_file_mapping);+ }++ if (windows_file != INVALID_HANDLE_VALUE) {+ (void)CloseHandle(windows_file);+ }+#elif defined(TINYEXR_USE_POSIX_MMAP)+ if (data) {+ (void)munmap(data, size);+ data = NULL;+ }++ if (posix_descriptor != -1) {+ (void)close(posix_descriptor);+ }+#else+ if (data) {+ (void)free(data);+ }+ data = NULL;+#endif+ }++ // A MemoryMappedFile cannot be copied or moved.+ // Only check for this when compiling with C++11 or higher, since deleted+ // function definitions were added then.+#if TINYEXR_HAS_CXX11+#ifdef __clang__+#pragma clang diagnostic push+#pragma clang diagnostic ignored "-Wc++98-compat"+#endif+ MemoryMappedFile(const MemoryMappedFile &) = delete;+ MemoryMappedFile &operator=(const MemoryMappedFile &) = delete;+ MemoryMappedFile(MemoryMappedFile &&other) noexcept = delete;+ MemoryMappedFile &operator=(MemoryMappedFile &&other) noexcept = delete;+#ifdef __clang__+#pragma clang diagnostic pop+#endif+#endif++ // Returns whether this was successfully opened.+ bool valid() const { return data; }+};++int LoadEXRImageFromFile(EXRImage *exr_image, const EXRHeader *exr_header,+ const char *filename, const char **err) {+ if (exr_image == NULL) {+ tinyexr::SetErrorMessage("Invalid argument for LoadEXRImageFromFile", err);+ return TINYEXR_ERROR_INVALID_ARGUMENT;+ }++ MemoryMappedFile file(filename);+ if (!file.valid()) {+ tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err);+ return TINYEXR_ERROR_CANT_OPEN_FILE;+ }++ if (file.size < 16) {+ tinyexr::SetErrorMessage("File size too short : " + std::string(filename),+ err);+ return TINYEXR_ERROR_INVALID_FILE;+ }++ return LoadEXRImageFromMemory(exr_image, exr_header, file.data, file.size,+ err);+}++int LoadEXRImageFromMemory(EXRImage *exr_image, const EXRHeader *exr_header,+ const unsigned char *memory, const size_t size,+ const char **err) {+ if (exr_image == NULL || memory == NULL ||+ (size < tinyexr::kEXRVersionSize)) {+ tinyexr::SetErrorMessage("Invalid argument for LoadEXRImageFromMemory",+ err);+ return TINYEXR_ERROR_INVALID_ARGUMENT;+ }++ if (exr_header->header_len == 0) {+ tinyexr::SetErrorMessage("EXRHeader variable is not initialized.", err);+ return TINYEXR_ERROR_INVALID_ARGUMENT;+ }++ const unsigned char *head = memory;+ const unsigned char *marker = reinterpret_cast<const unsigned char *>(+ memory + exr_header->header_len ++ 8); // +8 for magic number + version header.+ return tinyexr::DecodeEXRImage(exr_image, exr_header, head, marker, size,+ err);+}++namespace tinyexr+{++#ifdef __clang__+#pragma clang diagnostic push+#pragma clang diagnostic ignored "-Wsign-conversion"+#endif++// out_data must be allocated initially with the block-header size+// of the current image(-part) type+static bool EncodePixelData(/* out */ std::vector<unsigned char>& out_data,+ const unsigned char* const* images,+ int compression_type,+ int /*line_order*/,+ int width, // for tiled : tile.width+ int /*height*/, // for tiled : header.tile_size_y+ int x_stride, // for tiled : header.tile_size_x+ int line_no, // for tiled : 0+ int num_lines, // for tiled : tile.height+ size_t pixel_data_size,+ const std::vector<ChannelInfo>& channels,+ const std::vector<size_t>& channel_offset_list,+ std::string *err,+ const void* compression_param = 0) // zfp compression param+{+ size_t buf_size = static_cast<size_t>(width) *+ static_cast<size_t>(num_lines) *+ static_cast<size_t>(pixel_data_size);+ //int last2bit = (buf_size & 3);+ // buf_size must be multiple of four+ //if(last2bit) buf_size += 4 - last2bit;+ std::vector<unsigned char> buf(buf_size);++ size_t start_y = static_cast<size_t>(line_no);+ for (size_t c = 0; c < channels.size(); c++) {+ if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {+ if (channels[c].requested_pixel_type == TINYEXR_PIXELTYPE_FLOAT) {+ for (int y = 0; y < num_lines; y++) {+ // Assume increasing Y+ float *line_ptr = reinterpret_cast<float *>(&buf.at(+ static_cast<size_t>(pixel_data_size * size_t(y) * size_t(width)) ++ channel_offset_list[c] *+ static_cast<size_t>(width)));+ for (int x = 0; x < width; x++) {+ tinyexr::FP16 h16;+ h16.u = reinterpret_cast<const unsigned short * const *>(+ images)[c][(y + start_y) * size_t(x_stride) + size_t(x)];++ tinyexr::FP32 f32 = half_to_float(h16);++ tinyexr::swap4(&f32.f);++ // line_ptr[x] = f32.f;+ tinyexr::cpy4(line_ptr + x, &(f32.f));+ }+ }+ } else if (channels[c].requested_pixel_type == TINYEXR_PIXELTYPE_HALF) {+ for (int y = 0; y < num_lines; y++) {+ // Assume increasing Y+ unsigned short *line_ptr = reinterpret_cast<unsigned short *>(+ &buf.at(static_cast<size_t>(pixel_data_size * y *+ width) ++ channel_offset_list[c] *+ static_cast<size_t>(width)));+ for (int x = 0; x < width; x++) {+ unsigned short val = reinterpret_cast<const unsigned short * const *>(+ images)[c][(y + start_y) * x_stride + x];++ tinyexr::swap2(&val);++ // line_ptr[x] = val;+ tinyexr::cpy2(line_ptr + x, &val);+ }+ }+ } else {+ if (err) {+ (*err) += "Invalid requested_pixel_type.\n";+ }+ return false;+ }++ } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {+ if (channels[c].requested_pixel_type == TINYEXR_PIXELTYPE_HALF) {+ for (int y = 0; y < num_lines; y++) {+ // Assume increasing Y+ unsigned short *line_ptr = reinterpret_cast<unsigned short *>(+ &buf.at(static_cast<size_t>(pixel_data_size * y *+ width) ++ channel_offset_list[c] *+ static_cast<size_t>(width)));+ for (int x = 0; x < width; x++) {+ tinyexr::FP32 f32;+ f32.f = reinterpret_cast<const float * const *>(+ images)[c][(y + start_y) * x_stride + x];++ tinyexr::FP16 h16;+ h16 = float_to_half_full(f32);++ tinyexr::swap2(reinterpret_cast<unsigned short *>(&h16.u));++ // line_ptr[x] = h16.u;+ tinyexr::cpy2(line_ptr + x, &(h16.u));+ }+ }+ } else if (channels[c].requested_pixel_type == TINYEXR_PIXELTYPE_FLOAT) {+ for (int y = 0; y < num_lines; y++) {+ // Assume increasing Y+ float *line_ptr = reinterpret_cast<float *>(&buf.at(+ static_cast<size_t>(pixel_data_size * y * width) ++ channel_offset_list[c] *+ static_cast<size_t>(width)));+ for (int x = 0; x < width; x++) {+ float val = reinterpret_cast<const float * const *>(+ images)[c][(y + start_y) * x_stride + x];++ tinyexr::swap4(&val);++ // line_ptr[x] = val;+ tinyexr::cpy4(line_ptr + x, &val);+ }+ }+ } else {+ if (err) {+ (*err) += "Invalid requested_pixel_type.\n";+ }+ return false;+ }+ } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {+ for (int y = 0; y < num_lines; y++) {+ // Assume increasing Y+ unsigned int *line_ptr = reinterpret_cast<unsigned int *>(&buf.at(+ static_cast<size_t>(pixel_data_size * y * width) ++ channel_offset_list[c] * static_cast<size_t>(width)));+ for (int x = 0; x < width; x++) {+ unsigned int val = reinterpret_cast<const unsigned int * const *>(+ images)[c][(y + start_y) * x_stride + x];++ tinyexr::swap4(&val);++ // line_ptr[x] = val;+ tinyexr::cpy4(line_ptr + x, &val);+ }+ }+ }+ }++ if (compression_type == TINYEXR_COMPRESSIONTYPE_NONE) {+ // 4 byte: scan line+ // 4 byte: data size+ // ~ : pixel data(uncompressed)+ out_data.insert(out_data.end(), buf.begin(), buf.end());++ } else if ((compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS) ||+ (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP)) {+#if defined(TINYEXR_USE_MINIZ) && (TINYEXR_USE_MINIZ==1)+ std::vector<unsigned char> block(mz_compressBound(+ static_cast<unsigned long>(buf.size())));+#elif TINYEXR_USE_STB_ZLIB+ // there is no compressBound() function, so we use a value that+ // is grossly overestimated, but should always work+ std::vector<unsigned char> block(256 + 2 * buf.size());+#elif defined(TINYEXR_USE_NANOZLIB) && (TINYEXR_USE_NANOZLIB == 1)+ std::vector<unsigned char> block(nanoz_compressBound(+ static_cast<unsigned long>(buf.size())));+#else+ std::vector<unsigned char> block(+ compressBound(static_cast<uLong>(buf.size())));+#endif+ tinyexr::tinyexr_uint64 outSize = block.size();++ if (!tinyexr::CompressZip(&block.at(0), outSize,+ reinterpret_cast<const unsigned char *>(&buf.at(0)),+ static_cast<unsigned long>(buf.size()))) {+ if (err) {+ (*err) += "Zip compresssion failed.\n";+ }+ return false;+ }++ // 4 byte: scan line+ // 4 byte: data size+ // ~ : pixel data(compressed)+ unsigned int data_len = static_cast<unsigned int>(outSize); // truncate++ out_data.insert(out_data.end(), block.begin(), block.begin() + data_len);++ } else if (compression_type == TINYEXR_COMPRESSIONTYPE_RLE) {+ // (buf.size() * 3) / 2 would be enough.+ std::vector<unsigned char> block((buf.size() * 3) / 2);++ tinyexr::tinyexr_uint64 outSize = block.size();++ if (!tinyexr::CompressRle(&block.at(0), outSize,+ reinterpret_cast<const unsigned char *>(&buf.at(0)),+ static_cast<unsigned long>(buf.size()))) {+ if (err) {+ (*err) += "RLE compresssion failed.\n";+ }+ return false;+ }++ // 4 byte: scan line+ // 4 byte: data size+ // ~ : pixel data(compressed)+ unsigned int data_len = static_cast<unsigned int>(outSize); // truncate+ out_data.insert(out_data.end(), block.begin(), block.begin() + data_len);++ } else if (compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) {+#if TINYEXR_USE_PIZ+ unsigned int bufLen =+ 8192 + static_cast<unsigned int>(+ 2 * static_cast<unsigned int>(+ buf.size())); // @fixme { compute good bound. }+ std::vector<unsigned char> block(bufLen);+ unsigned int outSize = static_cast<unsigned int>(block.size());++ if (!CompressPiz(&block.at(0), &outSize,+ reinterpret_cast<const unsigned char *>(&buf.at(0)),+ buf.size(), channels, width, num_lines)) {+ if (err) {+ (*err) += "PIZ compresssion failed.\n";+ }+ return false;+ }++ // 4 byte: scan line+ // 4 byte: data size+ // ~ : pixel data(compressed)+ unsigned int data_len = outSize;+ out_data.insert(out_data.end(), block.begin(), block.begin() + data_len);++#else+ if (err) {+ (*err) += "PIZ compression is disabled in this build.\n";+ }+ return false;+#endif+ } else if (compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {+#if TINYEXR_USE_ZFP+ const ZFPCompressionParam* zfp_compression_param = reinterpret_cast<const ZFPCompressionParam*>(compression_param);+ std::vector<unsigned char> block;+ unsigned int outSize;++ tinyexr::CompressZfp(+ &block, &outSize, reinterpret_cast<const float *>(&buf.at(0)),+ width, num_lines, static_cast<int>(channels.size()), *zfp_compression_param);++ // 4 byte: scan line+ // 4 byte: data size+ // ~ : pixel data(compressed)+ unsigned int data_len = outSize;+ out_data.insert(out_data.end(), block.begin(), block.begin() + data_len);++#else+ if (err) {+ (*err) += "ZFP compression is disabled in this build.\n";+ }+ (void)compression_param;+ return false;+#endif+ } else if (compression_type == TINYEXR_COMPRESSIONTYPE_PXR24) {+ // PXR24 compression: True PXR24 (truncates FLOAT to 24-bits + zlib)+ std::vector<unsigned char> block;++ if (!tinyexr::CompressPxr24(block,+ reinterpret_cast<const unsigned char *>(&buf.at(0)),+ buf.size(), width, num_lines,+ channels.size(), channels)) {+ if (err) {+ (*err) += "PXR24 compression failed.\n";+ }+ return false;+ }++ out_data.insert(out_data.end(), block.begin(), block.end());++ } else if (compression_type == TINYEXR_COMPRESSIONTYPE_B44 ||+ compression_type == TINYEXR_COMPRESSIONTYPE_B44A) {+ // B44/B44A compression: True B44 block compression for HALF data+ bool is_b44a = (compression_type == TINYEXR_COMPRESSIONTYPE_B44A);+ std::vector<unsigned char> block;++ // CompressB44 expects per-channel sequential layout, but buf is+ // scanline-interleaved: within each row, channels are stored contiguously+ // (channel_offset_list[c] * width bytes into the row), and rows are+ // stacked. Convert to per-channel sequential before compressing.+ std::vector<unsigned char> seq_buf(buf_size);+ unsigned char *seq_p = seq_buf.data();+ for (size_t c = 0; c < channels.size(); c++) {+ int file_type = channels[c].requested_pixel_type;+ // HALF is 2 bytes; FLOAT and UINT are both 4 bytes+ size_t ch_size = (file_type == TINYEXR_PIXELTYPE_HALF) ? 2 : 4;+ for (int y = 0; y < num_lines; y++) {+ const unsigned char *src =+ &buf[y * pixel_data_size * width + channel_offset_list[c] * width];+ size_t row_bytes = static_cast<size_t>(width) * ch_size;+ memcpy(seq_p, src, row_bytes);+#if !TINYEXR_LITTLE_ENDIAN+ // buf has already been byte-swapped to little-endian for file output.+ // CompressB44 reads HALF values as host-endian unsigned shorts, so+ // un-swap the bytes back to host-endian for correct B44 encoding.+ if (file_type == TINYEXR_PIXELTYPE_HALF) {+ unsigned short *p = reinterpret_cast<unsigned short *>(seq_p);+ for (int x = 0; x < width; x++) {+ tinyexr::swap2(p + x);+ }+ }+#endif+ seq_p += row_bytes;+ }+ }++ if (!tinyexr::CompressB44(block,+ reinterpret_cast<const unsigned char *>(seq_buf.data()),+ seq_buf.size(), width, num_lines,+ channels.size(), channels, is_b44a)) {+ if (err) {+ (*err) += "B44 compression failed.\n";+ }+ return false;+ }++ out_data.insert(out_data.end(), block.begin(), block.end());++ } else {+ return false;+ }++ return true;+}++static int EncodeTiledLevel(const EXRImage* level_image, const EXRHeader* exr_header,+ const std::vector<tinyexr::ChannelInfo>& channels,+ std::vector<std::vector<unsigned char> >& data_list,+ size_t start_index, // for data_list+ int num_x_tiles, int num_y_tiles,+ const std::vector<size_t>& channel_offset_list,+ int pixel_data_size,+ const void* compression_param, // must be set if zfp compression is enabled+ std::string* err) {+ int num_tiles = num_x_tiles * num_y_tiles;+ if (num_tiles != level_image->num_tiles) {+ if (err) {+ (*err) += "Invalid number of tiles in argument.\n";+ }+ return TINYEXR_ERROR_INVALID_ARGUMENT;+ }++ if ((exr_header->tile_size_x > level_image->width || exr_header->tile_size_y > level_image->height) &&+ level_image->level_x == 0 && level_image->level_y == 0) {+ if (err) {+ (*err) += "Failed to encode tile data.\n";+ }+ return TINYEXR_ERROR_INVALID_DATA;+ }+++#if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0)+ std::atomic<bool> invalid_data(false);+#else+ bool invalid_data(false);+#endif++#if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0)+ std::vector<std::thread> workers;+ std::atomic<int> tile_count(0);++ int num_threads = std::max(1, int(std::thread::hardware_concurrency()));+#if (TINYEXR_MAX_THREADS > 0)+ num_threads = std::min(num_threads,TINYEXR_MAX_THREADS);+#endif+ if (num_threads > int(num_tiles)) {+ num_threads = int(num_tiles);+ }++ for (int t = 0; t < num_threads; t++) {+ workers.emplace_back(std::thread([&]() {+ int i = 0;+ while ((i = tile_count++) < num_tiles) {++#else+ // Use signed int since some OpenMP compiler doesn't allow unsigned type for+ // `parallel for`+#if TINYEXR_USE_OPENMP+#pragma omp parallel for+#endif+ for (int i = 0; i < num_tiles; i++) {++#endif+ size_t tile_idx = static_cast<size_t>(i);+ size_t data_idx = tile_idx + start_index;++ int x_tile = i % num_x_tiles;+ int y_tile = i / num_x_tiles;++ EXRTile& tile = level_image->tiles[tile_idx];++ const unsigned char* const* images =+ static_cast<const unsigned char* const*>(tile.images);++ data_list[data_idx].resize(5*sizeof(int));+ size_t data_header_size = data_list[data_idx].size();+ bool ret = EncodePixelData(data_list[data_idx],+ images,+ exr_header->compression_type,+ 0, // increasing y+ tile.width,+ exr_header->tile_size_y,+ exr_header->tile_size_x,+ 0,+ tile.height,+ pixel_data_size,+ channels,+ channel_offset_list,+ err, compression_param);+ if (!ret) {+ invalid_data = true;+ continue;+ }+ if (data_list[data_idx].size() <= data_header_size) {+ invalid_data = true;+ continue;+ }++ int data_len = static_cast<int>(data_list[data_idx].size() - data_header_size);+ //tileX, tileY, levelX, levelY // pixel_data_size(int)+ memcpy(&data_list[data_idx][0], &x_tile, sizeof(int));+ memcpy(&data_list[data_idx][4], &y_tile, sizeof(int));+ memcpy(&data_list[data_idx][8], &level_image->level_x, sizeof(int));+ memcpy(&data_list[data_idx][12], &level_image->level_y, sizeof(int));+ memcpy(&data_list[data_idx][16], &data_len, sizeof(int));++ swap4(reinterpret_cast<int*>(&data_list[data_idx][0]));+ swap4(reinterpret_cast<int*>(&data_list[data_idx][4]));+ swap4(reinterpret_cast<int*>(&data_list[data_idx][8]));+ swap4(reinterpret_cast<int*>(&data_list[data_idx][12]));+ swap4(reinterpret_cast<int*>(&data_list[data_idx][16]));++#if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0)+ }+}));+ }++ for (auto &t : workers) {+ t.join();+ }+#else+ } // omp parallel+#endif++ if (invalid_data) {+ if (err) {+ (*err) += "Failed to encode tile data.\n";+ }+ return TINYEXR_ERROR_INVALID_DATA;+ }+ return TINYEXR_SUCCESS;+}++static int NumScanlines(int compression_type) {+ int num_scanlines = 1;+ if (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) {+ num_scanlines = 16;+ } else if (compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) {+ num_scanlines = 32;+ } else if (compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {+ num_scanlines = 16;+ } else if (compression_type == TINYEXR_COMPRESSIONTYPE_PXR24) {+ num_scanlines = 16; // PXR24 uses 16 scanlines per block (same as ZIP)+ } else if (compression_type == TINYEXR_COMPRESSIONTYPE_B44 ||+ compression_type == TINYEXR_COMPRESSIONTYPE_B44A) {+ num_scanlines = 32; // B44/B44A uses 32 scanlines per block+ }+ return num_scanlines;+}++static int EncodeChunk(const EXRImage* exr_image, const EXRHeader* exr_header,+ const std::vector<ChannelInfo>& channels,+ int num_blocks,+ tinyexr_uint64 chunk_offset, // starting offset of current chunk+ bool is_multipart,+ OffsetData& offset_data, // output block offsets, must be initialized+ std::vector<std::vector<unsigned char> >& data_list, // output+ tinyexr_uint64& total_size, // output: ending offset of current chunk+ std::string* err) {+ int num_scanlines = NumScanlines(exr_header->compression_type);++ data_list.resize(num_blocks);++ std::vector<size_t> channel_offset_list(+ static_cast<size_t>(exr_header->num_channels));++ int pixel_data_size = 0;+ {+ size_t channel_offset = 0;+ for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) {+ channel_offset_list[c] = channel_offset;+ if (channels[c].requested_pixel_type == TINYEXR_PIXELTYPE_HALF) {+ pixel_data_size += sizeof(unsigned short);+ channel_offset += sizeof(unsigned short);+ } else if (channels[c].requested_pixel_type ==+ TINYEXR_PIXELTYPE_FLOAT) {+ pixel_data_size += sizeof(float);+ channel_offset += sizeof(float);+ } else if (channels[c].requested_pixel_type == TINYEXR_PIXELTYPE_UINT) {+ pixel_data_size += sizeof(unsigned int);+ channel_offset += sizeof(unsigned int);+ } else {+ if (err) {+ (*err) += "Invalid requested_pixel_type.\n";+ }+ return TINYEXR_ERROR_INVALID_DATA;+ }+ }+ }++ const void* compression_param = 0;+#if TINYEXR_USE_ZFP+ tinyexr::ZFPCompressionParam zfp_compression_param;++ // Use ZFP compression parameter from custom attributes(if such a parameter+ // exists)+ {+ std::string e;+ bool ret = tinyexr::FindZFPCompressionParam(+ &zfp_compression_param, exr_header->custom_attributes,+ exr_header->num_custom_attributes, &e);++ if (!ret) {+ // Use predefined compression parameter.+ zfp_compression_param.type = 0;+ zfp_compression_param.rate = 2;+ }+ compression_param = &zfp_compression_param;+ }+#endif++ tinyexr_uint64 offset = chunk_offset;+ tinyexr_uint64 doffset = is_multipart ? 4u : 0u;++ if (exr_image->tiles) {+ const EXRImage* level_image = exr_image;+ size_t block_idx = 0;+ //tinyexr::tinyexr_uint64 block_data_size = 0;+ int num_levels = (exr_header->tile_level_mode != TINYEXR_TILE_RIPMAP_LEVELS) ?+ offset_data.num_x_levels : (offset_data.num_x_levels * offset_data.num_y_levels);+ for (int level_index = 0; level_index < num_levels; ++level_index) {+ if (!level_image) {+ if (err) {+ (*err) += "Invalid number of tiled levels for EncodeChunk\n";+ }+ return TINYEXR_ERROR_INVALID_DATA;+ }++ int level_index_from_image = LevelIndex(level_image->level_x, level_image->level_y,+ exr_header->tile_level_mode, offset_data.num_x_levels);+ if (level_index_from_image < 0) {+ if (err) {+ (*err) += "Invalid tile level mode\n";+ }+ return TINYEXR_ERROR_INVALID_DATA;+ }++ if (level_index_from_image != level_index) {+ if (err) {+ (*err) += "Incorrect level ordering in tiled image\n";+ }+ return TINYEXR_ERROR_INVALID_DATA;+ }+ int num_y_tiles = int(offset_data.offsets[level_index].size());+ if (num_y_tiles <= 0) {+ if (err) {+ (*err) += "Invalid Y tile size\n";+ }+ return TINYEXR_ERROR_INVALID_DATA;+ }++ int num_x_tiles = int(offset_data.offsets[level_index][0].size());+ if (num_x_tiles <= 0) {+ if (err) {+ (*err) += "Invalid X tile size\n";+ }+ return TINYEXR_ERROR_INVALID_DATA;+ }++ std::string e;+ int ret = EncodeTiledLevel(level_image,+ exr_header,+ channels,+ data_list,+ block_idx,+ num_x_tiles,+ num_y_tiles,+ channel_offset_list,+ pixel_data_size,+ compression_param,+ &e);+ if (ret != TINYEXR_SUCCESS) {+ if (!e.empty() && err) {+ (*err) += e;+ }+ return ret;+ }++ for (size_t j = 0; j < static_cast<size_t>(num_y_tiles); ++j)+ for (size_t i = 0; i < static_cast<size_t>(num_x_tiles); ++i) {+ offset_data.offsets[level_index][j][i] = offset;+ swap8(reinterpret_cast<tinyexr_uint64*>(&offset_data.offsets[level_index][j][i]));+ offset += data_list[block_idx].size() + doffset;+ //block_data_size += data_list[block_idx].size();+ ++block_idx;+ }+ level_image = level_image->next_level;+ }+ TINYEXR_CHECK_AND_RETURN_C(static_cast<int>(block_idx) == num_blocks, TINYEXR_ERROR_INVALID_DATA);+ total_size = offset;+ } else { // scanlines+ std::vector<tinyexr::tinyexr_uint64>& offsets = offset_data.offsets[0][0];++#if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0)+ std::atomic<bool> invalid_data(false);+ std::vector<std::thread> workers;+ std::atomic<int> block_count(0);++ int num_threads = std::min(std::max(1, int(std::thread::hardware_concurrency())), num_blocks);+#if (TINYEXR_MAX_THREADS > 0)+ num_threads = std::min(num_threads,TINYEXR_MAX_THREADS);+#endif+ for (int t = 0; t < num_threads; t++) {+ workers.emplace_back(std::thread([&]() {+ int i = 0;+ while ((i = block_count++) < num_blocks) {++#else+ bool invalid_data(false);+#if TINYEXR_USE_OPENMP+#pragma omp parallel for+#endif+ for (int i = 0; i < num_blocks; i++) {++#endif+ int start_y = num_scanlines * i;+ int end_Y = (std::min)(num_scanlines * (i + 1), exr_image->height);+ int num_lines = end_Y - start_y;++ const unsigned char* const* images =+ static_cast<const unsigned char* const*>(exr_image->images);++ data_list[i].resize(2*sizeof(int));+ size_t data_header_size = data_list[i].size();++ bool ret = EncodePixelData(data_list[i],+ images,+ exr_header->compression_type,+ 0, // increasing y+ exr_image->width,+ exr_image->height,+ exr_image->width,+ start_y,+ num_lines,+ pixel_data_size,+ channels,+ channel_offset_list,+ err,+ compression_param);+ if (!ret) {+ invalid_data = true;+ continue; // "break" cannot be used with OpenMP+ }+ if (data_list[i].size() <= data_header_size) {+ invalid_data = true;+ continue; // "break" cannot be used with OpenMP+ }+ int data_len = static_cast<int>(data_list[i].size() - data_header_size);+ memcpy(&data_list[i][0], &start_y, sizeof(int));+ memcpy(&data_list[i][4], &data_len, sizeof(int));++ swap4(reinterpret_cast<int*>(&data_list[i][0]));+ swap4(reinterpret_cast<int*>(&data_list[i][4]));+#if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0)+ }+ }));+ }++ for (auto &t : workers) {+ t.join();+ }+#else+ } // omp parallel+#endif++ if (invalid_data) {+ if (err) {+ (*err) += "Failed to encode scanline data.\n";+ }+ return TINYEXR_ERROR_INVALID_DATA;+ }++ for (size_t i = 0; i < static_cast<size_t>(num_blocks); i++) {+ offsets[i] = offset;+ tinyexr::swap8(reinterpret_cast<tinyexr::tinyexr_uint64 *>(&offsets[i]));+ offset += data_list[i].size() + doffset;+ }++ total_size = static_cast<size_t>(offset);+ }+ return TINYEXR_SUCCESS;+}++// can save a single or multi-part image (no deep* formats)+static size_t SaveEXRNPartImageToMemory(const EXRImage* exr_images,+ const EXRHeader** exr_headers,+ unsigned int num_parts,+ unsigned char** memory_out, const char** err) {+ if (exr_images == NULL || exr_headers == NULL || num_parts == 0 ||+ memory_out == NULL) {+ SetErrorMessage("Invalid argument for SaveEXRNPartImageToMemory",+ err);+ return 0;+ }+ {+ for (unsigned int i = 0; i < num_parts; ++i) {+ if (exr_headers[i]->compression_type < 0) {+ SetErrorMessage("Invalid argument for SaveEXRNPartImageToMemory",+ err);+ return 0;+ }+#if !TINYEXR_USE_PIZ+ if (exr_headers[i]->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) {+ SetErrorMessage("PIZ compression is not supported in this build",+ err);+ return 0;+ }+#endif+ if (exr_headers[i]->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {+#if !TINYEXR_USE_ZFP+ SetErrorMessage("ZFP compression is not supported in this build",+ err);+ return 0;+#else+ // All channels must be fp32.+ // No fp16 support in ZFP atm(as of 2023 June)+ // https://github.com/LLNL/fpzip/issues/2+ for (int c = 0; c < exr_headers[i]->num_channels; ++c) {+ if (exr_headers[i]->requested_pixel_types[c] != TINYEXR_PIXELTYPE_FLOAT) {+ SetErrorMessage("Pixel type must be FLOAT for ZFP compression",+ err);+ return 0;+ }+ }+#endif+ }+ }+ }++ std::vector<unsigned char> memory;++ // Header+ {+ const char header[] = { 0x76, 0x2f, 0x31, 0x01 };+ memory.insert(memory.end(), header, header + 4);+ }++ // Version+ // using value from the first header+ int long_name = exr_headers[0]->long_name;+ {+ char marker[] = { 2, 0, 0, 0 };+ /* @todo+ if (exr_header->non_image) {+ marker[1] |= 0x8;+ }+ */+ // tiled+ if (num_parts == 1 && exr_images[0].tiles) {+ marker[1] |= 0x2;+ }+ // long_name+ if (long_name) {+ marker[1] |= 0x4;+ }+ // multipart+ if (num_parts > 1) {+ marker[1] |= 0x10;+ }+ memory.insert(memory.end(), marker, marker + 4);+ }++ int total_chunk_count = 0;+ std::vector<int> chunk_count(num_parts);+ std::vector<OffsetData> offset_data(num_parts);+ for (unsigned int i = 0; i < num_parts; ++i) {+ if (!exr_images[i].tiles) {+ int num_scanlines = NumScanlines(exr_headers[i]->compression_type);+ chunk_count[i] =+ (exr_images[i].height + num_scanlines - 1) / num_scanlines;+ InitSingleResolutionOffsets(offset_data[i], chunk_count[i]);+ total_chunk_count += chunk_count[i];+ } else {+ {+ std::vector<int> num_x_tiles, num_y_tiles;+ if (!PrecalculateTileInfo(num_x_tiles, num_y_tiles, exr_headers[i])) {+ SetErrorMessage("Failed to precalculate Tile info",+ err);+ return TINYEXR_ERROR_INVALID_DATA;+ }+ int ntiles = InitTileOffsets(offset_data[i], exr_headers[i], num_x_tiles, num_y_tiles);+ if (ntiles > 0) {+ chunk_count[i] = ntiles;+ } else {+ SetErrorMessage("Failed to compute Tile offsets",+ err);+ return TINYEXR_ERROR_INVALID_DATA;++ }+ total_chunk_count += chunk_count[i];+ }+ }+ }+ // Write attributes to memory buffer.+ std::vector< std::vector<tinyexr::ChannelInfo> > channels(num_parts);+ {+ std::set<std::string> partnames;+ for (unsigned int i = 0; i < num_parts; ++i) {+ //channels+ {+ std::vector<unsigned char> data;++ for (int c = 0; c < exr_headers[i]->num_channels; c++) {+ tinyexr::ChannelInfo info;+ info.p_linear = 0;+ info.pixel_type = exr_headers[i]->pixel_types[c];+ info.requested_pixel_type = exr_headers[i]->requested_pixel_types[c];+ info.x_sampling = 1;+ info.y_sampling = 1;+ info.name = std::string(exr_headers[i]->channels[c].name);+ channels[i].push_back(info);+ }++ tinyexr::WriteChannelInfo(data, channels[i]);++ tinyexr::WriteAttributeToMemory(&memory, "channels", "chlist", &data.at(0),+ static_cast<int>(data.size()));+ }++ {+ int comp = exr_headers[i]->compression_type;+ swap4(&comp);+ WriteAttributeToMemory(+ &memory, "compression", "compression",+ reinterpret_cast<const unsigned char*>(&comp), 1);+ }++ {+ int data[4] = { 0, 0, exr_images[i].width - 1, exr_images[i].height - 1 };+ swap4(&data[0]);+ swap4(&data[1]);+ swap4(&data[2]);+ swap4(&data[3]);+ WriteAttributeToMemory(+ &memory, "dataWindow", "box2i",+ reinterpret_cast<const unsigned char*>(data), sizeof(int) * 4);++ int data0[4] = { 0, 0, exr_images[0].width - 1, exr_images[0].height - 1 };+ swap4(&data0[0]);+ swap4(&data0[1]);+ swap4(&data0[2]);+ swap4(&data0[3]);+ // Note: must be the same across parts (currently, using value from the first header)+ WriteAttributeToMemory(+ &memory, "displayWindow", "box2i",+ reinterpret_cast<const unsigned char*>(data0), sizeof(int) * 4);+ }++ {+ unsigned char line_order = 0; // @fixme { read line_order from EXRHeader }+ WriteAttributeToMemory(&memory, "lineOrder", "lineOrder",+ &line_order, 1);+ }++ {+ // Note: must be the same across parts+ float aspectRatio = 1.0f;+ swap4(&aspectRatio);+ WriteAttributeToMemory(+ &memory, "pixelAspectRatio", "float",+ reinterpret_cast<const unsigned char*>(&aspectRatio), sizeof(float));+ }++ {+ float center[2] = { 0.0f, 0.0f };+ swap4(¢er[0]);+ swap4(¢er[1]);+ WriteAttributeToMemory(+ &memory, "screenWindowCenter", "v2f",+ reinterpret_cast<const unsigned char*>(center), 2 * sizeof(float));+ }++ {+ float w = 1.0f;+ swap4(&w);+ WriteAttributeToMemory(&memory, "screenWindowWidth", "float",+ reinterpret_cast<const unsigned char*>(&w),+ sizeof(float));+ }++ if (exr_images[i].tiles) {+ unsigned char tile_mode = static_cast<unsigned char>(exr_headers[i]->tile_level_mode & 0x3);+ if (exr_headers[i]->tile_rounding_mode) tile_mode |= (1u << 4u);+ //unsigned char data[9] = { 0, 0, 0, 0, 0, 0, 0, 0, 0 };+ unsigned int datai[3] = { 0, 0, 0 };+ unsigned char* data = reinterpret_cast<unsigned char*>(&datai[0]);+ datai[0] = static_cast<unsigned int>(exr_headers[i]->tile_size_x);+ datai[1] = static_cast<unsigned int>(exr_headers[i]->tile_size_y);+ data[8] = tile_mode;+ swap4(reinterpret_cast<unsigned int*>(&data[0]));+ swap4(reinterpret_cast<unsigned int*>(&data[4]));+ WriteAttributeToMemory(+ &memory, "tiles", "tiledesc",+ reinterpret_cast<const unsigned char*>(data), 9);+ }++ // must be present for multi-part files - according to spec.+ if (num_parts > 1) {+ // name+ {+ size_t len = 0;+ if ((len = strlen(exr_headers[i]->name)) > 0) {+#if TINYEXR_HAS_CXX11+ partnames.emplace(exr_headers[i]->name);+#else+ partnames.insert(std::string(exr_headers[i]->name));+#endif+ if (partnames.size() != i + 1) {+ SetErrorMessage("'name' attributes must be unique for a multi-part file", err);+ return 0;+ }+ WriteAttributeToMemory(+ &memory, "name", "string",+ reinterpret_cast<const unsigned char*>(exr_headers[i]->name),+ static_cast<int>(len));+ } else {+ SetErrorMessage("Invalid 'name' attribute for a multi-part file", err);+ return 0;+ }+ }+ // type+ {+ const char* type = "scanlineimage";+ if (exr_images[i].tiles) type = "tiledimage";+ WriteAttributeToMemory(+ &memory, "type", "string",+ reinterpret_cast<const unsigned char*>(type),+ static_cast<int>(strlen(type)));+ }+ // chunkCount+ {+ WriteAttributeToMemory(+ &memory, "chunkCount", "int",+ reinterpret_cast<const unsigned char*>(&chunk_count[i]),+ 4);+ }+ }++ // Custom attributes+ if (exr_headers[i]->num_custom_attributes > 0) {+ for (int j = 0; j < exr_headers[i]->num_custom_attributes; j++) {+ tinyexr::WriteAttributeToMemory(+ &memory, exr_headers[i]->custom_attributes[j].name,+ exr_headers[i]->custom_attributes[j].type,+ reinterpret_cast<const unsigned char*>(+ exr_headers[i]->custom_attributes[j].value),+ exr_headers[i]->custom_attributes[j].size);+ }+ }++ { // end of header+ memory.push_back(0);+ }+ }+ }+ if (num_parts > 1) {+ // end of header list+ memory.push_back(0);+ }++ tinyexr_uint64 chunk_offset = memory.size() + size_t(total_chunk_count) * sizeof(tinyexr_uint64);++ tinyexr_uint64 total_size = 0;+ std::vector< std::vector< std::vector<unsigned char> > > data_lists(num_parts);+ for (unsigned int i = 0; i < num_parts; ++i) {+ std::string e;+ int ret = EncodeChunk(&exr_images[i], exr_headers[i],+ channels[i],+ chunk_count[i],+ // starting offset of current chunk after part-number+ chunk_offset,+ num_parts > 1,+ offset_data[i], // output: block offsets, must be initialized+ data_lists[i], // output+ total_size, // output+ &e);+ if (ret != TINYEXR_SUCCESS) {+ if (!e.empty()) {+ tinyexr::SetErrorMessage(e, err);+ }+ return 0;+ }+ chunk_offset = total_size;+ }++ // Allocating required memory+ if (total_size == 0) { // something went wrong+ tinyexr::SetErrorMessage("Output memory size is zero", err);+ return TINYEXR_ERROR_INVALID_DATA;+ }+ (*memory_out) = static_cast<unsigned char*>(malloc(size_t(total_size)));++ // Writing header+ memcpy((*memory_out), &memory[0], memory.size());+ unsigned char* memory_ptr = *memory_out + memory.size();+ size_t sum = memory.size();++ // Writing offset data for chunks+ for (unsigned int i = 0; i < num_parts; ++i) {+ if (exr_images[i].tiles) {+ const EXRImage* level_image = &exr_images[i];+ int num_levels = (exr_headers[i]->tile_level_mode != TINYEXR_TILE_RIPMAP_LEVELS) ?+ offset_data[i].num_x_levels : (offset_data[i].num_x_levels * offset_data[i].num_y_levels);+ for (int level_index = 0; level_index < num_levels; ++level_index) {+ for (size_t j = 0; j < offset_data[i].offsets[level_index].size(); ++j) {+ size_t num_bytes = sizeof(tinyexr_uint64) * offset_data[i].offsets[level_index][j].size();+ sum += num_bytes;+ if (sum > total_size) {+ tinyexr::SetErrorMessage("Invalid offset bytes in Tiled Part image.", err);+ return TINYEXR_ERROR_INVALID_DATA;+ }++ memcpy(memory_ptr,+ reinterpret_cast<unsigned char*>(&offset_data[i].offsets[level_index][j][0]),+ num_bytes);+ memory_ptr += num_bytes;+ }+ level_image = level_image->next_level;+ }+ } else {+ size_t num_bytes = sizeof(tinyexr::tinyexr_uint64) * static_cast<size_t>(chunk_count[i]);+ sum += num_bytes;+ if (sum > total_size) {+ tinyexr::SetErrorMessage("Invalid offset bytes in Part image.", err);+ return TINYEXR_ERROR_INVALID_DATA;+ }+ std::vector<tinyexr::tinyexr_uint64>& offsets = offset_data[i].offsets[0][0];+ memcpy(memory_ptr, reinterpret_cast<unsigned char*>(&offsets[0]), num_bytes);+ memory_ptr += num_bytes;+ }+ }++ // Writing chunk data+ for (unsigned int i = 0; i < num_parts; ++i) {+ for (size_t j = 0; j < static_cast<size_t>(chunk_count[i]); ++j) {+ if (num_parts > 1) {+ sum += 4;+ if (sum > total_size) {+ tinyexr::SetErrorMessage("Buffer overrun in reading Part image chunk data.", err);+ return TINYEXR_ERROR_INVALID_DATA;+ }+ unsigned int part_number = i;+ swap4(&part_number);+ memcpy(memory_ptr, &part_number, 4);+ memory_ptr += 4;+ }+ sum += data_lists[i][j].size();+ if (sum > total_size) {+ tinyexr::SetErrorMessage("Buffer overrun in reading Part image chunk data.", err);+ return TINYEXR_ERROR_INVALID_DATA;+ }+ memcpy(memory_ptr, &data_lists[i][j][0], data_lists[i][j].size());+ memory_ptr += data_lists[i][j].size();+ }+ }++ if (sum != total_size) {+ tinyexr::SetErrorMessage("Corrupted Part image chunk data.", err);+ return TINYEXR_ERROR_INVALID_DATA;+ }++ return size_t(total_size); // OK+}++#ifdef __clang__+#pragma clang diagnostic pop+#endif++} // tinyexr++size_t SaveEXRImageToMemory(const EXRImage* exr_image,+ const EXRHeader* exr_header,+ unsigned char** memory_out, const char** err) {+ return tinyexr::SaveEXRNPartImageToMemory(exr_image, &exr_header, 1, memory_out, err);+}++int SaveEXRImageToFile(const EXRImage *exr_image, const EXRHeader *exr_header,+ const char *filename, const char **err) {+ if (exr_image == NULL || filename == NULL ||+ exr_header->compression_type < 0) {+ tinyexr::SetErrorMessage("Invalid argument for SaveEXRImageToFile", err);+ return TINYEXR_ERROR_INVALID_ARGUMENT;+ }++#if !TINYEXR_USE_PIZ+ if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) {+ tinyexr::SetErrorMessage("PIZ compression is not supported in this build",+ err);+ return TINYEXR_ERROR_UNSUPPORTED_FEATURE;+ }+#endif++#if !TINYEXR_USE_ZFP+ if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {+ tinyexr::SetErrorMessage("ZFP compression is not supported in this build",+ err);+ return TINYEXR_ERROR_UNSUPPORTED_FEATURE;+ }+#endif++ FILE *fp = NULL;+#ifdef _WIN32+#if defined(_MSC_VER) || (defined(MINGW_HAS_SECURE_API) && MINGW_HAS_SECURE_API) // MSVC, MinGW GCC, or Clang+ errno_t errcode =+ _wfopen_s(&fp, tinyexr::UTF8ToWchar(filename).c_str(), L"wb");+ if (errcode != 0) {+ tinyexr::SetErrorMessage("Cannot write a file: " + std::string(filename),+ err);+ return TINYEXR_ERROR_CANT_WRITE_FILE;+ }+#else+ // Unknown compiler or MinGW without MINGW_HAS_SECURE_API.+ fp = fopen(filename, "wb");+#endif+#else+ fp = fopen(filename, "wb");+#endif+ if (!fp) {+ tinyexr::SetErrorMessage("Cannot write a file: " + std::string(filename),+ err);+ return TINYEXR_ERROR_CANT_WRITE_FILE;+ }++ unsigned char *mem = NULL;+ size_t mem_size = SaveEXRImageToMemory(exr_image, exr_header, &mem, err);+ if (mem_size == 0) {+ fclose(fp);+ return TINYEXR_ERROR_SERIALIZATION_FAILED;+ }++ size_t written_size = 0;+ if ((mem_size > 0) && mem) {+ written_size = fwrite(mem, 1, mem_size, fp);+ }+ free(mem);++ fclose(fp);++ if (written_size != mem_size) {+ tinyexr::SetErrorMessage("Cannot write a file", err);+ return TINYEXR_ERROR_CANT_WRITE_FILE;+ }++ return TINYEXR_SUCCESS;+}++size_t SaveEXRMultipartImageToMemory(const EXRImage* exr_images,+ const EXRHeader** exr_headers,+ unsigned int num_parts,+ unsigned char** memory_out, const char** err) {+ if (exr_images == NULL || exr_headers == NULL || num_parts == 0 ||+ memory_out == NULL) {+ tinyexr::SetErrorMessage("Invalid argument for SaveEXRNPartImageToMemory",+ err);+ return 0;+ }+ return tinyexr::SaveEXRNPartImageToMemory(exr_images, exr_headers, num_parts, memory_out, err);+}++int SaveEXRMultipartImageToFile(const EXRImage* exr_images,+ const EXRHeader** exr_headers,+ unsigned int num_parts,+ const char* filename,+ const char** err) {+ if (exr_images == NULL || exr_headers == NULL || num_parts == 0) {+ tinyexr::SetErrorMessage("Invalid argument for SaveEXRMultipartImageToFile",+ err);+ return TINYEXR_ERROR_INVALID_ARGUMENT;+ }++ FILE *fp = NULL;+#ifdef _WIN32+#if defined(_MSC_VER) || (defined(MINGW_HAS_SECURE_API) && MINGW_HAS_SECURE_API) // MSVC, MinGW GCC, or Clang.+ errno_t errcode =+ _wfopen_s(&fp, tinyexr::UTF8ToWchar(filename).c_str(), L"wb");+ if (errcode != 0) {+ tinyexr::SetErrorMessage("Cannot write a file: " + std::string(filename),+ err);+ return TINYEXR_ERROR_CANT_WRITE_FILE;+ }+#else+ // Unknown compiler or MinGW without MINGW_HAS_SECURE_API.+ fp = fopen(filename, "wb");+#endif+#else+ fp = fopen(filename, "wb");+#endif+ if (!fp) {+ tinyexr::SetErrorMessage("Cannot write a file: " + std::string(filename),+ err);+ return TINYEXR_ERROR_CANT_WRITE_FILE;+ }++ unsigned char *mem = NULL;+ size_t mem_size = SaveEXRMultipartImageToMemory(exr_images, exr_headers, num_parts, &mem, err);+ if (mem_size == 0) {+ fclose(fp);+ return TINYEXR_ERROR_SERIALIZATION_FAILED;+ }++ size_t written_size = 0;+ if ((mem_size > 0) && mem) {+ written_size = fwrite(mem, 1, mem_size, fp);+ }+ free(mem);++ fclose(fp);++ if (written_size != mem_size) {+ tinyexr::SetErrorMessage("Cannot write a file", err);+ return TINYEXR_ERROR_CANT_WRITE_FILE;+ }++ return TINYEXR_SUCCESS;+}++int LoadDeepEXR(DeepImage *deep_image, const char *filename, const char **err) {+ if (deep_image == NULL) {+ tinyexr::SetErrorMessage("Invalid argument for LoadDeepEXR", err);+ return TINYEXR_ERROR_INVALID_ARGUMENT;+ }++ MemoryMappedFile file(filename);+ if (!file.valid()) {+ tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err);+ return TINYEXR_ERROR_CANT_OPEN_FILE;+ }++ if (file.size == 0) {+ tinyexr::SetErrorMessage("File size is zero : " + std::string(filename),+ err);+ return TINYEXR_ERROR_INVALID_FILE;+ }++ const char *head = reinterpret_cast<const char *>(file.data);+ const char *marker = reinterpret_cast<const char *>(file.data);++ // Header check.+ {+ const char header[] = {0x76, 0x2f, 0x31, 0x01};++ if (memcmp(marker, header, 4) != 0) {+ tinyexr::SetErrorMessage("Invalid magic number", err);+ return TINYEXR_ERROR_INVALID_MAGIC_NUMBER;+ }+ marker += 4;+ }++ // Version, scanline.+ {+ // ver 2.0, scanline, deep bit on(0x800)+ // must be [2, 0, 0, 0]+ if (marker[0] != 2 || marker[1] != 8 || marker[2] != 0 || marker[3] != 0) {+ tinyexr::SetErrorMessage("Unsupported version or scanline", err);+ return TINYEXR_ERROR_UNSUPPORTED_FORMAT;+ }++ marker += 4;+ }++ int dx = -1;+ int dy = -1;+ int dw = -1;+ int dh = -1;+ int num_scanline_blocks = 1; // 16 for ZIP compression.+ int compression_type = -1;+ int num_channels = -1;+ std::vector<tinyexr::ChannelInfo> channels;++ // Read attributes+ size_t size = file.size - tinyexr::kEXRVersionSize;+ for (;;) {+ if (0 == size) {+ return TINYEXR_ERROR_INVALID_DATA;+ } else if (marker[0] == '\0') {+ marker++;+ size--;+ break;+ }++ std::string attr_name;+ std::string attr_type;+ std::vector<unsigned char> data;+ size_t marker_size;+ if (!tinyexr::ReadAttribute(&attr_name, &attr_type, &data, &marker_size,+ marker, size)) {+ std::stringstream ss;+ ss << "Failed to parse attribute\n";+ tinyexr::SetErrorMessage(ss.str(), err);+ return TINYEXR_ERROR_INVALID_DATA;+ }+ marker += marker_size;+ size -= marker_size;++ if (attr_name.compare("compression") == 0) {+ compression_type = data[0];+ if (compression_type > TINYEXR_COMPRESSIONTYPE_B44A) {+ std::stringstream ss;+ ss << "Unsupported compression type : " << compression_type;+ tinyexr::SetErrorMessage(ss.str(), err);+ return TINYEXR_ERROR_UNSUPPORTED_FORMAT;+ }++ if (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) {+ num_scanline_blocks = 16;+ } else if (compression_type == TINYEXR_COMPRESSIONTYPE_B44 ||+ compression_type == TINYEXR_COMPRESSIONTYPE_B44A) {+ num_scanline_blocks = 32;+ }++ } else if (attr_name.compare("channels") == 0) {+ // name: zero-terminated string, from 1 to 255 bytes long+ // pixel type: int, possible values are: UINT = 0 HALF = 1 FLOAT = 2+ // pLinear: unsigned char, possible values are 0 and 1+ // reserved: three chars, should be zero+ // xSampling: int+ // ySampling: int++ if (!tinyexr::ReadChannelInfo(channels, data)) {+ tinyexr::SetErrorMessage("Failed to parse channel info", err);+ return TINYEXR_ERROR_INVALID_DATA;+ }++ num_channels = static_cast<int>(channels.size());++ if (num_channels < 1) {+ tinyexr::SetErrorMessage("Invalid channels format", err);+ return TINYEXR_ERROR_INVALID_DATA;+ }++ } else if (attr_name.compare("dataWindow") == 0) {+ memcpy(&dx, &data.at(0), sizeof(int));+ memcpy(&dy, &data.at(4), sizeof(int));+ memcpy(&dw, &data.at(8), sizeof(int));+ memcpy(&dh, &data.at(12), sizeof(int));+ tinyexr::swap4(&dx);+ tinyexr::swap4(&dy);+ tinyexr::swap4(&dw);+ tinyexr::swap4(&dh);++ } else if (attr_name.compare("displayWindow") == 0) {+ int x;+ int y;+ int w;+ int h;+ memcpy(&x, &data.at(0), sizeof(int));+ memcpy(&y, &data.at(4), sizeof(int));+ memcpy(&w, &data.at(8), sizeof(int));+ memcpy(&h, &data.at(12), sizeof(int));+ tinyexr::swap4(&x);+ tinyexr::swap4(&y);+ tinyexr::swap4(&w);+ tinyexr::swap4(&h);+ }+ }++ TINYEXR_CHECK_AND_RETURN_C(dx >= 0, TINYEXR_ERROR_INVALID_DATA);+ TINYEXR_CHECK_AND_RETURN_C(dy >= 0, TINYEXR_ERROR_INVALID_DATA);+ TINYEXR_CHECK_AND_RETURN_C(dw >= 0, TINYEXR_ERROR_INVALID_DATA);+ TINYEXR_CHECK_AND_RETURN_C(dh >= 0, TINYEXR_ERROR_INVALID_DATA);+ TINYEXR_CHECK_AND_RETURN_C(num_channels >= 1, TINYEXR_ERROR_INVALID_DATA);++ int data_width = dw - dx + 1;+ int data_height = dh - dy + 1;++ // Read offset tables.+ int num_blocks = data_height / num_scanline_blocks;+ if (num_blocks * num_scanline_blocks < data_height) {+ num_blocks++;+ }++ std::vector<tinyexr::tinyexr_int64> offsets(static_cast<size_t>(num_blocks));++ for (size_t y = 0; y < static_cast<size_t>(num_blocks); y++) {+ tinyexr::tinyexr_int64 offset;+ memcpy(&offset, marker, sizeof(tinyexr::tinyexr_int64));+ tinyexr::swap8(reinterpret_cast<tinyexr::tinyexr_uint64 *>(&offset));+ marker += sizeof(tinyexr::tinyexr_int64); // = 8+ offsets[y] = offset;+ }++#if TINYEXR_USE_PIZ+ if ((compression_type == TINYEXR_COMPRESSIONTYPE_NONE) ||+ (compression_type == TINYEXR_COMPRESSIONTYPE_RLE) ||+ (compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS) ||+ (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) ||+ (compression_type == TINYEXR_COMPRESSIONTYPE_PIZ)) {+#else+ if ((compression_type == TINYEXR_COMPRESSIONTYPE_NONE) ||+ (compression_type == TINYEXR_COMPRESSIONTYPE_RLE) ||+ (compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS) ||+ (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP)) {+#endif+ // OK+ } else {+ tinyexr::SetErrorMessage("Unsupported compression format", err);+ return TINYEXR_ERROR_UNSUPPORTED_FORMAT;+ }++ deep_image->image = static_cast<float ***>(+ malloc(sizeof(float **) * static_cast<size_t>(num_channels)));+ for (int c = 0; c < num_channels; c++) {+ deep_image->image[c] = static_cast<float **>(+ malloc(sizeof(float *) * static_cast<size_t>(data_height)));+ for (int y = 0; y < data_height; y++) {+ }+ }++ deep_image->offset_table = static_cast<int **>(+ malloc(sizeof(int *) * static_cast<size_t>(data_height)));+ for (int y = 0; y < data_height; y++) {+ deep_image->offset_table[y] = static_cast<int *>(+ malloc(sizeof(int) * static_cast<size_t>(data_width)));+ }++ for (size_t y = 0; y < static_cast<size_t>(num_blocks); y++) {+ const unsigned char *data_ptr =+ reinterpret_cast<const unsigned char *>(head + offsets[y]);++ // int: y coordinate+ // int64: packed size of pixel offset table+ // int64: packed size of sample data+ // int64: unpacked size of sample data+ // compressed pixel offset table+ // compressed sample data+ int line_no;+ tinyexr::tinyexr_int64 packedOffsetTableSize;+ tinyexr::tinyexr_int64 packedSampleDataSize;+ tinyexr::tinyexr_int64 unpackedSampleDataSize;+ memcpy(&line_no, data_ptr, sizeof(int));+ memcpy(&packedOffsetTableSize, data_ptr + 4,+ sizeof(tinyexr::tinyexr_int64));+ memcpy(&packedSampleDataSize, data_ptr + 12,+ sizeof(tinyexr::tinyexr_int64));+ memcpy(&unpackedSampleDataSize, data_ptr + 20,+ sizeof(tinyexr::tinyexr_int64));++ tinyexr::swap4(&line_no);+ tinyexr::swap8(+ reinterpret_cast<tinyexr::tinyexr_uint64 *>(&packedOffsetTableSize));+ tinyexr::swap8(+ reinterpret_cast<tinyexr::tinyexr_uint64 *>(&packedSampleDataSize));+ tinyexr::swap8(+ reinterpret_cast<tinyexr::tinyexr_uint64 *>(&unpackedSampleDataSize));++ std::vector<int> pixelOffsetTable(static_cast<size_t>(data_width));++ // decode pixel offset table.+ {+ unsigned long dstLen =+ static_cast<unsigned long>(pixelOffsetTable.size() * sizeof(int));+ if (!tinyexr::DecompressZip(+ reinterpret_cast<unsigned char *>(&pixelOffsetTable.at(0)),+ &dstLen, data_ptr + 28,+ static_cast<unsigned long>(packedOffsetTableSize))) {+ return false;+ }++ TINYEXR_CHECK_AND_RETURN_C(dstLen == pixelOffsetTable.size() * sizeof(int), TINYEXR_ERROR_INVALID_DATA);+ for (size_t i = 0; i < static_cast<size_t>(data_width); i++) {+ deep_image->offset_table[y][i] = pixelOffsetTable[i];+ }+ }++ std::vector<unsigned char> sample_data(+ static_cast<size_t>(unpackedSampleDataSize));++ // decode sample data.+ {+ unsigned long dstLen = static_cast<unsigned long>(unpackedSampleDataSize);+ if (dstLen) {+ if (!tinyexr::DecompressZip(+ reinterpret_cast<unsigned char *>(&sample_data.at(0)), &dstLen,+ data_ptr + 28 + packedOffsetTableSize,+ static_cast<unsigned long>(packedSampleDataSize))) {+ return false;+ }+ TINYEXR_CHECK_AND_RETURN_C(dstLen == static_cast<unsigned long>(unpackedSampleDataSize), TINYEXR_ERROR_INVALID_DATA);+ }+ }++ // decode sample+ int sampleSize = -1;+ std::vector<int> channel_offset_list(static_cast<size_t>(num_channels));+ {+ int channel_offset = 0;+ for (size_t i = 0; i < static_cast<size_t>(num_channels); i++) {+ channel_offset_list[i] = channel_offset;+ if (channels[i].pixel_type == TINYEXR_PIXELTYPE_UINT) { // UINT+ channel_offset += 4;+ } else if (channels[i].pixel_type == TINYEXR_PIXELTYPE_HALF) { // half+ channel_offset += 2;+ } else if (channels[i].pixel_type ==+ TINYEXR_PIXELTYPE_FLOAT) { // float+ channel_offset += 4;+ } else {+ tinyexr::SetErrorMessage("Invalid pixel_type in chnnels.", err);+ return TINYEXR_ERROR_INVALID_DATA;+ }+ }+ sampleSize = channel_offset;+ }+ TINYEXR_CHECK_AND_RETURN_C(sampleSize >= 2, TINYEXR_ERROR_INVALID_DATA);++ TINYEXR_CHECK_AND_RETURN_C(static_cast<size_t>(+ pixelOffsetTable[static_cast<size_t>(data_width - 1)] *+ sampleSize) == sample_data.size(), TINYEXR_ERROR_INVALID_DATA);+ int samples_per_line = static_cast<int>(sample_data.size()) / sampleSize;++ //+ // Alloc memory+ //++ //+ // pixel data is stored as image[channels][pixel_samples]+ //+ {+ tinyexr::tinyexr_uint64 data_offset = 0;+ for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {+ deep_image->image[c][y] = static_cast<float *>(+ malloc(sizeof(float) * static_cast<size_t>(samples_per_line)));++ if (channels[c].pixel_type == 0) { // UINT+ for (size_t x = 0; x < static_cast<size_t>(samples_per_line); x++) {+ unsigned int ui;+ unsigned int *src_ptr = reinterpret_cast<unsigned int *>(+ &sample_data.at(size_t(data_offset) + x * sizeof(int)));+ tinyexr::cpy4(&ui, src_ptr);+ deep_image->image[c][y][x] = static_cast<float>(ui); // @fixme+ }+ data_offset +=+ sizeof(unsigned int) * static_cast<size_t>(samples_per_line);+ } else if (channels[c].pixel_type == 1) { // half+ for (size_t x = 0; x < static_cast<size_t>(samples_per_line); x++) {+ tinyexr::FP16 f16;+ const unsigned short *src_ptr = reinterpret_cast<unsigned short *>(+ &sample_data.at(size_t(data_offset) + x * sizeof(short)));+ tinyexr::cpy2(&(f16.u), src_ptr);+ tinyexr::FP32 f32 = half_to_float(f16);+ deep_image->image[c][y][x] = f32.f;+ }+ data_offset += sizeof(short) * static_cast<size_t>(samples_per_line);+ } else { // float+ for (size_t x = 0; x < static_cast<size_t>(samples_per_line); x++) {+ float f;+ const float *src_ptr = reinterpret_cast<float *>(+ &sample_data.at(size_t(data_offset) + x * sizeof(float)));+ tinyexr::cpy4(&f, src_ptr);+ deep_image->image[c][y][x] = f;+ }+ data_offset += sizeof(float) * static_cast<size_t>(samples_per_line);+ }+ }+ }+ } // y++ deep_image->width = data_width;+ deep_image->height = data_height;++ deep_image->channel_names = static_cast<const char **>(+ malloc(sizeof(const char *) * static_cast<size_t>(num_channels)));+ for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {+#ifdef _WIN32+ deep_image->channel_names[c] = _strdup(channels[c].name.c_str());+#else+ deep_image->channel_names[c] = strdup(channels[c].name.c_str());+#endif+ }+ deep_image->num_channels = num_channels;++ return TINYEXR_SUCCESS;+}++void InitEXRImage(EXRImage *exr_image) {+ if (exr_image == NULL) {+ return;+ }++ exr_image->width = 0;+ exr_image->height = 0;+ exr_image->num_channels = 0;++ exr_image->images = NULL;+ exr_image->tiles = NULL;+ exr_image->next_level = NULL;+ exr_image->level_x = 0;+ exr_image->level_y = 0;++ exr_image->num_tiles = 0;+}++void FreeEXRErrorMessage(const char *msg) {+ if (msg) {+ free(reinterpret_cast<void *>(const_cast<char *>(msg)));+ }+ return;+}++void InitEXRHeader(EXRHeader *exr_header) {+ if (exr_header == NULL) {+ return;+ }++ memset(exr_header, 0, sizeof(EXRHeader));+}++int FreeEXRHeader(EXRHeader *exr_header) {+ if (exr_header == NULL) {+ return TINYEXR_ERROR_INVALID_ARGUMENT;+ }++ if (exr_header->channels) {+ free(exr_header->channels);+ }++ if (exr_header->pixel_types) {+ free(exr_header->pixel_types);+ }++ if (exr_header->requested_pixel_types) {+ free(exr_header->requested_pixel_types);+ }++ for (int i = 0; i < exr_header->num_custom_attributes; i++) {+ if (exr_header->custom_attributes[i].value) {+ free(exr_header->custom_attributes[i].value);+ }+ }++ if (exr_header->custom_attributes) {+ free(exr_header->custom_attributes);+ }++ EXRSetNameAttr(exr_header, NULL);++ return TINYEXR_SUCCESS;+}++void EXRSetNameAttr(EXRHeader* exr_header, const char* name) {+ if (exr_header == NULL) {+ return;+ }+ memset(exr_header->name, 0, 256);+ if (name != NULL) {+ size_t len = std::min(strlen(name), size_t(255));+ if (len) {+ memcpy(exr_header->name, name, len);+ }+ }+}++int EXRNumLevels(const EXRImage* exr_image) {+ if (exr_image == NULL) return 0;+ if(exr_image->images) return 1; // scanlines+ int levels = 1;+ const EXRImage* level_image = exr_image;+ while((level_image = level_image->next_level)) ++levels;+ return levels;+}++int FreeEXRImage(EXRImage *exr_image) {+ if (exr_image == NULL) {+ return TINYEXR_ERROR_INVALID_ARGUMENT;+ }++ if (exr_image->next_level) {+ FreeEXRImage(exr_image->next_level);+ delete exr_image->next_level;+ exr_image->next_level = NULL;+ }++ for (int i = 0; i < exr_image->num_channels; i++) {+ if (exr_image->images && exr_image->images[i]) {+ free(exr_image->images[i]);+ exr_image->images[i] = NULL;+ }+ }++ if (exr_image->images) {+ free(exr_image->images);+ exr_image->images = NULL;+ }++ if (exr_image->tiles) {+ for (int tid = 0; tid < exr_image->num_tiles; tid++) {+ for (int i = 0; i < exr_image->num_channels; i++) {+ if (exr_image->tiles[tid].images && exr_image->tiles[tid].images[i]) {+ free(exr_image->tiles[tid].images[i]);+ exr_image->tiles[tid].images[i] = NULL;+ }+ }+ if (exr_image->tiles[tid].images) {+ free(exr_image->tiles[tid].images);+ exr_image->tiles[tid].images = NULL;+ }+ }+ free(exr_image->tiles);+ exr_image->tiles = NULL;+ }++ exr_image->num_channels = 0;+ exr_image->num_tiles = 0;++ return TINYEXR_SUCCESS;+}++int ParseEXRHeaderFromFile(EXRHeader *exr_header, const EXRVersion *exr_version,+ const char *filename, const char **err) {+ if (exr_header == NULL || exr_version == NULL || filename == NULL) {+ tinyexr::SetErrorMessage("Invalid argument for ParseEXRHeaderFromFile",+ err);+ return TINYEXR_ERROR_INVALID_ARGUMENT;+ }++ MemoryMappedFile file(filename);+ if (!file.valid()) {+ tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err);+ return TINYEXR_ERROR_CANT_OPEN_FILE;+ }++ return ParseEXRHeaderFromMemory(exr_header, exr_version, file.data, file.size,+ err);+}++int ParseEXRMultipartHeaderFromMemory(EXRHeader ***exr_headers,+ int *num_headers,+ const EXRVersion *exr_version,+ const unsigned char *memory, size_t size,+ const char **err) {+ if (memory == NULL || exr_headers == NULL || num_headers == NULL ||+ exr_version == NULL) {+ // Invalid argument+ tinyexr::SetErrorMessage(+ "Invalid argument for ParseEXRMultipartHeaderFromMemory", err);+ return TINYEXR_ERROR_INVALID_ARGUMENT;+ }++ if (size < tinyexr::kEXRVersionSize) {+ tinyexr::SetErrorMessage("Data size too short", err);+ return TINYEXR_ERROR_INVALID_DATA;+ }++ const unsigned char *marker = memory + tinyexr::kEXRVersionSize;+ size_t marker_size = size - tinyexr::kEXRVersionSize;++ std::vector<tinyexr::HeaderInfo> infos;++ for (;;) {+ tinyexr::HeaderInfo info;+ info.clear();++ std::string err_str;+ bool empty_header = false;+ int ret = ParseEXRHeader(&info, &empty_header, exr_version, &err_str,+ marker, marker_size);++ if (ret != TINYEXR_SUCCESS) {++ // Free malloc-allocated memory here.+ for (size_t i = 0; i < info.attributes.size(); i++) {+ if (info.attributes[i].value) {+ free(info.attributes[i].value);+ }+ }++ tinyexr::SetErrorMessage(err_str, err);+ return ret;+ }++ if (empty_header) {+ marker += 1; // skip '\0'+ break;+ }++ // `chunkCount` must exist in the header.+ if (info.chunk_count == 0) {++ // Free malloc-allocated memory here.+ for (size_t i = 0; i < info.attributes.size(); i++) {+ if (info.attributes[i].value) {+ free(info.attributes[i].value);+ }+ }++ tinyexr::SetErrorMessage(+ "`chunkCount' attribute is not found in the header.", err);+ return TINYEXR_ERROR_INVALID_DATA;+ }++ infos.push_back(info);++ // move to next header.+ marker += info.header_len;+ size -= info.header_len;+ }++ // allocate memory for EXRHeader and create array of EXRHeader pointers.+ (*exr_headers) =+ static_cast<EXRHeader **>(malloc(sizeof(EXRHeader *) * infos.size()));+++ int retcode = TINYEXR_SUCCESS;++ for (size_t i = 0; i < infos.size(); i++) {+ EXRHeader *exr_header = static_cast<EXRHeader *>(malloc(sizeof(EXRHeader)));+ memset(exr_header, 0, sizeof(EXRHeader));++ std::string warn;+ std::string _err;+ if (!ConvertHeader(exr_header, infos[i], &warn, &_err)) {++ // Free malloc-allocated memory here.+ for (size_t k = 0; k < infos[i].attributes.size(); k++) {+ if (infos[i].attributes[k].value) {+ free(infos[i].attributes[k].value);+ }+ }++ if (!_err.empty()) {+ tinyexr::SetErrorMessage(+ _err, err);+ }+ // continue to converting headers+ retcode = TINYEXR_ERROR_INVALID_HEADER;+ }++ exr_header->multipart = exr_version->multipart ? 1 : 0;++ (*exr_headers)[i] = exr_header;+ }++ (*num_headers) = static_cast<int>(infos.size());++ return retcode;+}++int ParseEXRMultipartHeaderFromFile(EXRHeader ***exr_headers, int *num_headers,+ const EXRVersion *exr_version,+ const char *filename, const char **err) {+ if (exr_headers == NULL || num_headers == NULL || exr_version == NULL ||+ filename == NULL) {+ tinyexr::SetErrorMessage(+ "Invalid argument for ParseEXRMultipartHeaderFromFile()", err);+ return TINYEXR_ERROR_INVALID_ARGUMENT;+ }++ MemoryMappedFile file(filename);+ if (!file.valid()) {+ tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err);+ return TINYEXR_ERROR_CANT_OPEN_FILE;+ }++ return ParseEXRMultipartHeaderFromMemory(+ exr_headers, num_headers, exr_version, file.data, file.size, err);+}++// ========================================================================+// Refactored loader functions using Reader class for safer memory access+// ========================================================================++namespace { // anonymous namespace for internal helpers++// Parse EXR version header using Reader class+static int ParseEXRVersionWithReader(EXRVersion *version, tinyexr::Reader& reader) {+ if (version == NULL) {+ return TINYEXR_ERROR_INVALID_ARGUMENT;+ }++ if (reader.length() < tinyexr::kEXRVersionSize) {+ reader.add_error("Insufficient data size for EXR version header");+ return TINYEXR_ERROR_INVALID_DATA;+ }++ // Check magic number: 0x76, 0x2f, 0x31, 0x01+ uint8_t header[4];+ if (!reader.read(4, header)) {+ return TINYEXR_ERROR_INVALID_DATA;+ }++ const uint8_t expected_header[] = {0x76, 0x2f, 0x31, 0x01};+ if (header[0] != expected_header[0] || header[1] != expected_header[1] ||+ header[2] != expected_header[2] || header[3] != expected_header[3]) {+ reader.add_error("Invalid EXR magic number");+ return TINYEXR_ERROR_INVALID_MAGIC_NUMBER;+ }++ // Parse version byte (must be 2)+ uint8_t version_byte;+ if (!reader.read1(&version_byte)) {+ return TINYEXR_ERROR_INVALID_DATA;+ }++ if (version_byte != 2) {+ reader.add_error("Invalid EXR version");+ return TINYEXR_ERROR_INVALID_EXR_VERSION;+ }++ version->version = 2;++ // Parse flags byte+ uint8_t flags;+ if (!reader.read1(&flags)) {+ return TINYEXR_ERROR_INVALID_DATA;+ }++ version->tiled = (flags & 0x2) ? true : false; // 9th bit+ version->long_name = (flags & 0x4) ? true : false; // 10th bit+ version->non_image = (flags & 0x8) ? true : false; // 11th bit (deep image)+ version->multipart = (flags & 0x10) ? true : false; // 12th bit++ // Skip remaining 2 bytes to complete the 8-byte version header+ uint8_t dummy[2];+ if (!reader.read(2, dummy)) {+ return TINYEXR_ERROR_INVALID_DATA;+ }++ return TINYEXR_SUCCESS;+}++} // anonymous namespace++int ParseEXRVersionFromMemory(EXRVersion *version, const unsigned char *memory,+ size_t size) {+ if (version == NULL || memory == NULL) {+ return TINYEXR_ERROR_INVALID_ARGUMENT;+ }++ if (size < tinyexr::kEXRVersionSize) {+ return TINYEXR_ERROR_INVALID_DATA;+ }++ // Use Reader class for safer memory access+ tinyexr::Reader reader(memory, size, tinyexr::Endian::Little);+ int ret = ParseEXRVersionWithReader(version, reader);++ // Note: errors are accumulated in reader.errors() but not propagated+ // to maintain compatibility with existing API+ return ret;+}++int ParseEXRVersionFromFile(EXRVersion *version, const char *filename) {+ if (filename == NULL) {+ return TINYEXR_ERROR_INVALID_ARGUMENT;+ }++ FILE *fp = NULL;+#ifdef _WIN32+#if defined(_MSC_VER) || (defined(MINGW_HAS_SECURE_API) && MINGW_HAS_SECURE_API) // MSVC, MinGW GCC, or Clang.+ errno_t err = _wfopen_s(&fp, tinyexr::UTF8ToWchar(filename).c_str(), L"rb");+ if (err != 0) {+ // TODO(syoyo): return wfopen_s erro code+ return TINYEXR_ERROR_CANT_OPEN_FILE;+ }+#else+ // Unknown compiler or MinGW without MINGW_HAS_SECURE_API.+ fp = fopen(filename, "rb");+#endif+#else+ fp = fopen(filename, "rb");+#endif+ if (!fp) {+ return TINYEXR_ERROR_CANT_OPEN_FILE;+ }++ // Try to read kEXRVersionSize bytes; if the file is shorter than+ // kEXRVersionSize, this will produce an error. This avoids a call to+ // fseek(fp, 0, SEEK_END), which is not required to be supported by C+ // implementations.+ unsigned char buf[tinyexr::kEXRVersionSize];+ size_t ret = fread(&buf[0], 1, tinyexr::kEXRVersionSize, fp);+ fclose(fp);++ if (ret != tinyexr::kEXRVersionSize) {+ return TINYEXR_ERROR_INVALID_FILE;+ }++ return ParseEXRVersionFromMemory(version, buf, tinyexr::kEXRVersionSize);+}++int LoadEXRMultipartImageFromMemory(EXRImage *exr_images,+ const EXRHeader **exr_headers,+ unsigned int num_parts,+ const unsigned char *memory,+ const size_t size, const char **err) {+ if (exr_images == NULL || exr_headers == NULL || num_parts == 0 ||+ memory == NULL || (size <= tinyexr::kEXRVersionSize)) {+ tinyexr::SetErrorMessage(+ "Invalid argument for LoadEXRMultipartImageFromMemory()", err);+ return TINYEXR_ERROR_INVALID_ARGUMENT;+ }++ // compute total header size.+ size_t total_header_size = 0;+ for (unsigned int i = 0; i < num_parts; i++) {+ if (exr_headers[i]->header_len == 0) {+ tinyexr::SetErrorMessage("EXRHeader variable is not initialized.", err);+ return TINYEXR_ERROR_INVALID_ARGUMENT;+ }++ total_header_size += exr_headers[i]->header_len;+ }++ const char *marker = reinterpret_cast<const char *>(+ memory + total_header_size + 4 ++ 4); // +8 for magic number and version header.++ marker += 1; // Skip empty header.++ // NOTE 1:+ // In multipart image, There is 'part number' before chunk data.+ // 4 byte : part number+ // 4+ : chunk+ //+ // NOTE 2:+ // EXR spec says 'part number' is 'unsigned long' but actually this is+ // 'unsigned int(4 bytes)' in OpenEXR implementation...+ // http://www.openexr.com/openexrfilelayout.pdf++ // Load chunk offset table.+ std::vector<tinyexr::OffsetData> chunk_offset_table_list;+ chunk_offset_table_list.reserve(num_parts);+ for (size_t i = 0; i < static_cast<size_t>(num_parts); i++) {+ chunk_offset_table_list.resize(chunk_offset_table_list.size() + 1);+ tinyexr::OffsetData& offset_data = chunk_offset_table_list.back();+ if (!exr_headers[i]->tiled || exr_headers[i]->tile_level_mode == TINYEXR_TILE_ONE_LEVEL) {+ tinyexr::InitSingleResolutionOffsets(offset_data, size_t(exr_headers[i]->chunk_count));+ std::vector<tinyexr::tinyexr_uint64>& offset_table = offset_data.offsets[0][0];++ for (size_t c = 0; c < offset_table.size(); c++) {+ tinyexr::tinyexr_uint64 offset;+ memcpy(&offset, marker, 8);+ tinyexr::swap8(&offset);++ if (offset >= size) {+ tinyexr::SetErrorMessage("Invalid offset size in EXR header chunks.",+ err);+ return TINYEXR_ERROR_INVALID_DATA;+ }++ offset_table[c] = offset + 4; // +4 to skip 'part number'+ marker += 8;+ }+ } else {+ {+ std::vector<int> num_x_tiles, num_y_tiles;+ if (!tinyexr::PrecalculateTileInfo(num_x_tiles, num_y_tiles, exr_headers[i])) {+ tinyexr::SetErrorMessage("Invalid tile info.", err);+ return TINYEXR_ERROR_INVALID_DATA;+ }+ int num_blocks = InitTileOffsets(offset_data, exr_headers[i], num_x_tiles, num_y_tiles);+ if (num_blocks != exr_headers[i]->chunk_count) {+ tinyexr::SetErrorMessage("Invalid offset table size.", err);+ return TINYEXR_ERROR_INVALID_DATA;+ }+ }+ for (unsigned int l = 0; l < offset_data.offsets.size(); ++l) {+ for (unsigned int dy = 0; dy < offset_data.offsets[l].size(); ++dy) {+ for (unsigned int dx = 0; dx < offset_data.offsets[l][dy].size(); ++dx) {+ tinyexr::tinyexr_uint64 offset;+ memcpy(&offset, marker, sizeof(tinyexr::tinyexr_uint64));+ tinyexr::swap8(&offset);+ if (offset >= size) {+ tinyexr::SetErrorMessage("Invalid offset size in EXR header chunks.",+ err);+ return TINYEXR_ERROR_INVALID_DATA;+ }+ offset_data.offsets[l][dy][dx] = offset + 4; // +4 to skip 'part number'+ marker += sizeof(tinyexr::tinyexr_uint64); // = 8+ }+ }+ }+ }+ }++ // Decode image.+ for (size_t i = 0; i < static_cast<size_t>(num_parts); i++) {+ tinyexr::OffsetData &offset_data = chunk_offset_table_list[i];++ // First check 'part number' is identical to 'i'+ for (unsigned int l = 0; l < offset_data.offsets.size(); ++l)+ for (unsigned int dy = 0; dy < offset_data.offsets[l].size(); ++dy)+ for (unsigned int dx = 0; dx < offset_data.offsets[l][dy].size(); ++dx) {++ const unsigned char *part_number_addr =+ memory + offset_data.offsets[l][dy][dx] - 4; // -4 to move to 'part number' field.+ unsigned int part_no;+ memcpy(&part_no, part_number_addr, sizeof(unsigned int)); // 4+ tinyexr::swap4(&part_no);++ if (part_no != i) {+ tinyexr::SetErrorMessage("Invalid `part number' in EXR header chunks.",+ err);+ return TINYEXR_ERROR_INVALID_DATA;+ }+ }++ std::string e;+ int ret = tinyexr::DecodeChunk(&exr_images[i], exr_headers[i], offset_data,+ memory, size, &e);+ if (ret != TINYEXR_SUCCESS) {+ if (!e.empty()) {+ tinyexr::SetErrorMessage(e, err);+ }+ return ret;+ }+ }++ return TINYEXR_SUCCESS;+}++int LoadEXRMultipartImageFromFile(EXRImage *exr_images,+ const EXRHeader **exr_headers,+ unsigned int num_parts, const char *filename,+ const char **err) {+ if (exr_images == NULL || exr_headers == NULL || num_parts == 0) {+ tinyexr::SetErrorMessage(+ "Invalid argument for LoadEXRMultipartImageFromFile", err);+ return TINYEXR_ERROR_INVALID_ARGUMENT;+ }++ MemoryMappedFile file(filename);+ if (!file.valid()) {+ tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err);+ return TINYEXR_ERROR_CANT_OPEN_FILE;+ }++ return LoadEXRMultipartImageFromMemory(exr_images, exr_headers, num_parts,+ file.data, file.size, err);+}++int SaveEXRToMemory(const float *data, int width, int height, int components,+ const int save_as_fp16, unsigned char **outbuf, const char **err) {++ if ((components == 1) || components == 3 || components == 4) {+ // OK+ } else {+ std::stringstream ss;+ ss << "Unsupported component value : " << components << std::endl;++ tinyexr::SetErrorMessage(ss.str(), err);+ return TINYEXR_ERROR_INVALID_ARGUMENT;+ }++ EXRHeader header;+ InitEXRHeader(&header);++ if ((width < 16) && (height < 16)) {+ // No compression for small image.+ header.compression_type = TINYEXR_COMPRESSIONTYPE_NONE;+ } else {+ header.compression_type = TINYEXR_COMPRESSIONTYPE_ZIP;+ }++ EXRImage image;+ InitEXRImage(&image);++ image.num_channels = components;++ std::vector<float> images[4];++ if (components == 1) {+ images[0].resize(static_cast<size_t>(width * height));+ memcpy(images[0].data(), data, sizeof(float) * size_t(width * height));+ } else {+ images[0].resize(static_cast<size_t>(width * height));+ images[1].resize(static_cast<size_t>(width * height));+ images[2].resize(static_cast<size_t>(width * height));+ images[3].resize(static_cast<size_t>(width * height));++ // Split RGB(A)RGB(A)RGB(A)... into R, G and B(and A) layers+ if (components == 4) {+ for (size_t i = 0; i < static_cast<size_t>(width * height); i++) {+ images[0][i] = data[static_cast<size_t>(components) * i + 0];+ images[1][i] = data[static_cast<size_t>(components) * i + 1];+ images[2][i] = data[static_cast<size_t>(components) * i + 2];+ images[3][i] = data[static_cast<size_t>(components) * i + 3];+ }+ } else {+ for (size_t i = 0; i < static_cast<size_t>(width * height); i++) {+ images[0][i] = data[static_cast<size_t>(components) * i + 0];+ images[1][i] = data[static_cast<size_t>(components) * i + 1];+ images[2][i] = data[static_cast<size_t>(components) * i + 2];+ }+ }+ }++ float *image_ptr[4] = {0, 0, 0, 0};+ if (components == 4) {+ image_ptr[0] = &(images[3].at(0)); // A+ image_ptr[1] = &(images[2].at(0)); // B+ image_ptr[2] = &(images[1].at(0)); // G+ image_ptr[3] = &(images[0].at(0)); // R+ } else if (components == 3) {+ image_ptr[0] = &(images[2].at(0)); // B+ image_ptr[1] = &(images[1].at(0)); // G+ image_ptr[2] = &(images[0].at(0)); // R+ } else if (components == 1) {+ image_ptr[0] = &(images[0].at(0)); // A+ }++ image.images = reinterpret_cast<unsigned char **>(image_ptr);+ image.width = width;+ image.height = height;++ header.num_channels = components;+ header.channels = static_cast<EXRChannelInfo *>(malloc(+ sizeof(EXRChannelInfo) * static_cast<size_t>(header.num_channels)));+ // Must be (A)BGR order, since most of EXR viewers expect this channel order.+ if (components == 4) {+#ifdef _MSC_VER+ strncpy_s(header.channels[0].name, "A", 255);+ strncpy_s(header.channels[1].name, "B", 255);+ strncpy_s(header.channels[2].name, "G", 255);+ strncpy_s(header.channels[3].name, "R", 255);+#else+ strncpy(header.channels[0].name, "A", 255);+ strncpy(header.channels[1].name, "B", 255);+ strncpy(header.channels[2].name, "G", 255);+ strncpy(header.channels[3].name, "R", 255);+#endif+ header.channels[0].name[strlen("A")] = '\0';+ header.channels[1].name[strlen("B")] = '\0';+ header.channels[2].name[strlen("G")] = '\0';+ header.channels[3].name[strlen("R")] = '\0';+ } else if (components == 3) {+#ifdef _MSC_VER+ strncpy_s(header.channels[0].name, "B", 255);+ strncpy_s(header.channels[1].name, "G", 255);+ strncpy_s(header.channels[2].name, "R", 255);+#else+ strncpy(header.channels[0].name, "B", 255);+ strncpy(header.channels[1].name, "G", 255);+ strncpy(header.channels[2].name, "R", 255);+#endif+ header.channels[0].name[strlen("B")] = '\0';+ header.channels[1].name[strlen("G")] = '\0';+ header.channels[2].name[strlen("R")] = '\0';+ } else {+#ifdef _MSC_VER+ strncpy_s(header.channels[0].name, "A", 255);+#else+ strncpy(header.channels[0].name, "A", 255);+#endif+ header.channels[0].name[strlen("A")] = '\0';+ }++ header.pixel_types = static_cast<int *>(+ malloc(sizeof(int) * static_cast<size_t>(header.num_channels)));+ header.requested_pixel_types = static_cast<int *>(+ malloc(sizeof(int) * static_cast<size_t>(header.num_channels)));+ for (int i = 0; i < header.num_channels; i++) {+ header.pixel_types[i] =+ TINYEXR_PIXELTYPE_FLOAT; // pixel type of input image++ if (save_as_fp16 > 0) {+ header.requested_pixel_types[i] =+ TINYEXR_PIXELTYPE_HALF; // save with half(fp16) pixel format+ } else {+ header.requested_pixel_types[i] =+ TINYEXR_PIXELTYPE_FLOAT; // save with float(fp32) pixel format(i.e.+ // no precision reduction)+ }+ }+++ unsigned char *mem_buf;+ size_t mem_size = SaveEXRImageToMemory(&image, &header, &mem_buf, err);++ if (mem_size == 0) {+ return TINYEXR_ERROR_SERIALIZATION_FAILED;+ }++ free(header.channels);+ free(header.pixel_types);+ free(header.requested_pixel_types);++ if (mem_size > size_t(std::numeric_limits<int>::max())) {+ free(mem_buf);+ return TINYEXR_ERROR_DATA_TOO_LARGE;+ }++ (*outbuf) = mem_buf;++ return int(mem_size);+}++int SaveEXR(const float *data, int width, int height, int components,+ const int save_as_fp16, const char *outfilename, const char **err) {+ if ((components == 1) || components == 3 || components == 4) {+ // OK+ } else {+ std::stringstream ss;+ ss << "Unsupported component value : " << components << std::endl;++ tinyexr::SetErrorMessage(ss.str(), err);+ return TINYEXR_ERROR_INVALID_ARGUMENT;+ }++ EXRHeader header;+ InitEXRHeader(&header);++ if ((width < 16) && (height < 16)) {+ // No compression for small image.+ header.compression_type = TINYEXR_COMPRESSIONTYPE_NONE;+ } else {+ header.compression_type = TINYEXR_COMPRESSIONTYPE_ZIP;+ }++ EXRImage image;+ InitEXRImage(&image);++ image.num_channels = components;++ std::vector<float> images[4];+ const size_t pixel_count =+ static_cast<size_t>(width) * static_cast<size_t>(height);++ if (components == 1) {+ images[0].resize(pixel_count);+ memcpy(images[0].data(), data, sizeof(float) * pixel_count);+ } else {+ images[0].resize(pixel_count);+ images[1].resize(pixel_count);+ images[2].resize(pixel_count);+ images[3].resize(pixel_count);++ // Split RGB(A)RGB(A)RGB(A)... into R, G and B(and A) layers+ if (components == 4) {+ for (size_t i = 0; i < pixel_count; i++) {+ images[0][i] = data[static_cast<size_t>(components) * i + 0];+ images[1][i] = data[static_cast<size_t>(components) * i + 1];+ images[2][i] = data[static_cast<size_t>(components) * i + 2];+ images[3][i] = data[static_cast<size_t>(components) * i + 3];+ }+ } else {+ for (size_t i = 0; i < pixel_count; i++) {+ images[0][i] = data[static_cast<size_t>(components) * i + 0];+ images[1][i] = data[static_cast<size_t>(components) * i + 1];+ images[2][i] = data[static_cast<size_t>(components) * i + 2];+ }+ }+ }++ float *image_ptr[4] = {0, 0, 0, 0};+ if (components == 4) {+ image_ptr[0] = &(images[3].at(0)); // A+ image_ptr[1] = &(images[2].at(0)); // B+ image_ptr[2] = &(images[1].at(0)); // G+ image_ptr[3] = &(images[0].at(0)); // R+ } else if (components == 3) {+ image_ptr[0] = &(images[2].at(0)); // B+ image_ptr[1] = &(images[1].at(0)); // G+ image_ptr[2] = &(images[0].at(0)); // R+ } else if (components == 1) {+ image_ptr[0] = &(images[0].at(0)); // A+ }++ image.images = reinterpret_cast<unsigned char **>(image_ptr);+ image.width = width;+ image.height = height;++ header.num_channels = components;+ header.channels = static_cast<EXRChannelInfo *>(malloc(+ sizeof(EXRChannelInfo) * static_cast<size_t>(header.num_channels)));+ // Must be (A)BGR order, since most of EXR viewers expect this channel order.+ if (components == 4) {+#ifdef _MSC_VER+ strncpy_s(header.channels[0].name, "A", 255);+ strncpy_s(header.channels[1].name, "B", 255);+ strncpy_s(header.channels[2].name, "G", 255);+ strncpy_s(header.channels[3].name, "R", 255);+#else+ strncpy(header.channels[0].name, "A", 255);+ strncpy(header.channels[1].name, "B", 255);+ strncpy(header.channels[2].name, "G", 255);+ strncpy(header.channels[3].name, "R", 255);+#endif+ header.channels[0].name[strlen("A")] = '\0';+ header.channels[1].name[strlen("B")] = '\0';+ header.channels[2].name[strlen("G")] = '\0';+ header.channels[3].name[strlen("R")] = '\0';+ } else if (components == 3) {+#ifdef _MSC_VER+ strncpy_s(header.channels[0].name, "B", 255);+ strncpy_s(header.channels[1].name, "G", 255);+ strncpy_s(header.channels[2].name, "R", 255);+#else+ strncpy(header.channels[0].name, "B", 255);+ strncpy(header.channels[1].name, "G", 255);+ strncpy(header.channels[2].name, "R", 255);+#endif+ header.channels[0].name[strlen("B")] = '\0';+ header.channels[1].name[strlen("G")] = '\0';+ header.channels[2].name[strlen("R")] = '\0';+ } else {+#ifdef _MSC_VER+ strncpy_s(header.channels[0].name, "A", 255);+#else+ strncpy(header.channels[0].name, "A", 255);+#endif+ header.channels[0].name[strlen("A")] = '\0';+ }++ header.pixel_types = static_cast<int *>(+ malloc(sizeof(int) * static_cast<size_t>(header.num_channels)));+ header.requested_pixel_types = static_cast<int *>(+ malloc(sizeof(int) * static_cast<size_t>(header.num_channels)));+ for (int i = 0; i < header.num_channels; i++) {+ header.pixel_types[i] =+ TINYEXR_PIXELTYPE_FLOAT; // pixel type of input image++ if (save_as_fp16 > 0) {+ header.requested_pixel_types[i] =+ TINYEXR_PIXELTYPE_HALF; // save with half(fp16) pixel format+ } else {+ header.requested_pixel_types[i] =+ TINYEXR_PIXELTYPE_FLOAT; // save with float(fp32) pixel format(i.e.+ // no precision reduction)+ }+ }++ int ret = SaveEXRImageToFile(&image, &header, outfilename, err);++ free(header.channels);+ free(header.pixel_types);+ free(header.requested_pixel_types);++ return ret;+}++// ----------------------------------------------------------------+// Spectral EXR API implementations+// ----------------------------------------------------------------++// Helper to format wavelength with comma as decimal separator (European convention)+void EXRFormatWavelength(char *buffer, size_t buffer_size, float wavelength_nm) {+ if (!buffer || buffer_size < 16) return;++ // Format with 6 decimal places+ int whole = static_cast<int>(wavelength_nm);+ int frac = static_cast<int>((wavelength_nm - whole) * 1000000.0f + 0.5f);++#ifdef _MSC_VER+ sprintf_s(buffer, buffer_size, "%d,%06d", whole, frac);+#else+ snprintf(buffer, buffer_size, "%d,%06d", whole, frac);+#endif+}++// Create spectral channel name for emissive spectrum+void EXRSpectralChannelName(char *buffer, size_t buffer_size,+ float wavelength_nm, int stokes_component) {+ if (!buffer || buffer_size < 32) return;++ char wavelength_str[32];+ EXRFormatWavelength(wavelength_str, sizeof(wavelength_str), wavelength_nm);++#ifdef _MSC_VER+ sprintf_s(buffer, buffer_size, "S%d.%snm", stokes_component, wavelength_str);+#else+ snprintf(buffer, buffer_size, "S%d.%snm", stokes_component, wavelength_str);+#endif+}++// Create spectral channel name for reflective spectrum+void EXRReflectiveChannelName(char *buffer, size_t buffer_size,+ float wavelength_nm) {+ if (!buffer || buffer_size < 32) return;++ char wavelength_str[32];+ EXRFormatWavelength(wavelength_str, sizeof(wavelength_str), wavelength_nm);++#ifdef _MSC_VER+ sprintf_s(buffer, buffer_size, "T.%snm", wavelength_str);+#else+ snprintf(buffer, buffer_size, "T.%snm", wavelength_str);+#endif+}++// Parse wavelength from spectral channel name+float EXRParseSpectralChannelWavelength(const char *channel_name) {+ if (!channel_name) return -1.0f;++ const char *p = channel_name;++ // Skip prefix: "S{n}." or "T."+ if (*p == 'S' && p[1] >= '0' && p[1] <= '3' && p[2] == '.') {+ p += 3;+ } else if (*p == 'T' && p[1] == '.') {+ p += 2;+ } else {+ return -1.0f;+ }++ // Parse wavelength with comma as decimal separator+ // Format: "550,000000nm"+ char wavelength_str[64];+ size_t len = 0;+ while (*p && *p != 'n' && len < sizeof(wavelength_str) - 1) {+ wavelength_str[len++] = (*p == ',') ? '.' : *p;+ p++;+ }+ wavelength_str[len] = '\0';++ // Check for "nm" suffix+ if (*p != 'n' || p[1] != 'm') {+ return -1.0f;+ }++ return static_cast<float>(atof(wavelength_str));+}++// Get Stokes component from channel name+int EXRGetStokesComponent(const char *channel_name) {+ if (!channel_name) return -1;++ if (channel_name[0] == 'S' &&+ channel_name[1] >= '0' && channel_name[1] <= '3' &&+ channel_name[2] == '.') {+ return channel_name[1] - '0';+ }++ return -1;+}++// Check if channel name is a spectral channel+int EXRIsSpectralChannel(const char *channel_name) {+ if (!channel_name) return 0;++ // Check for "S{n}.{wavelength}nm" pattern+ if (channel_name[0] == 'S' &&+ channel_name[1] >= '0' && channel_name[1] <= '3' &&+ channel_name[2] == '.') {+ return EXRParseSpectralChannelWavelength(channel_name) > 0.0f ? 1 : 0;+ }++ // Check for "T.{wavelength}nm" pattern+ if (channel_name[0] == 'T' && channel_name[1] == '.') {+ return EXRParseSpectralChannelWavelength(channel_name) > 0.0f ? 1 : 0;+ }++ return 0;+}++// Helper to find custom attribute by name+static const EXRAttribute* FindCustomAttribute(const EXRHeader *exr_header,+ const char *name) {+ if (!exr_header || !name) return NULL;++ for (int i = 0; i < exr_header->num_custom_attributes; i++) {+ if (strcmp(exr_header->custom_attributes[i].name, name) == 0) {+ return &exr_header->custom_attributes[i];+ }+ }+ return NULL;+}++// Get spectrum type from EXR header+int EXRGetSpectrumType(const EXRHeader *exr_header) {+ if (!exr_header) return -1;++ // Check for spectralLayoutVersion attribute+ const EXRAttribute *layout_attr = FindCustomAttribute(exr_header, "spectralLayoutVersion");+ if (!layout_attr) return -1;++ // Check channel names to determine type+ int has_stokes = 0;+ int has_reflective = 0;+ int has_emissive = 0;++ for (int i = 0; i < exr_header->num_channels; i++) {+ const char *name = exr_header->channels[i].name;+ if (name[0] == 'T' && name[1] == '.') {+ has_reflective = 1;+ } else if (name[0] == 'S' && name[1] >= '0' && name[1] <= '3' && name[2] == '.') {+ has_emissive = 1;+ if (name[1] != '0') {+ has_stokes = 1;+ }+ }+ }++ if (has_reflective) return TINYEXR_SPECTRUM_REFLECTIVE;+ if (has_stokes) return TINYEXR_SPECTRUM_POLARISED;+ if (has_emissive) return TINYEXR_SPECTRUM_EMISSIVE;++ return -1;+}++// Get wavelengths from EXR header channels+int EXRGetWavelengths(const EXRHeader *exr_header,+ float *wavelengths, int max_wavelengths) {+ if (!exr_header || !wavelengths || max_wavelengths <= 0) return 0;++ int count = 0;++ for (int i = 0; i < exr_header->num_channels && count < max_wavelengths; i++) {+ float wl = EXRParseSpectralChannelWavelength(exr_header->channels[i].name);+ if (wl > 0.0f) {+ // Check if wavelength already in list+ int found = 0;+ for (int j = 0; j < count; j++) {+ if (std::fabs(static_cast<double>(wavelengths[j] - wl)) < 0.01) {+ found = 1;+ break;+ }+ }+ if (!found) {+ wavelengths[count++] = wl;+ }+ }+ }++ // Sort wavelengths+ for (int i = 0; i < count - 1; i++) {+ for (int j = i + 1; j < count; j++) {+ if (wavelengths[i] > wavelengths[j]) {+ float tmp = wavelengths[i];+ wavelengths[i] = wavelengths[j];+ wavelengths[j] = tmp;+ }+ }+ }++ return count;+}++// Get spectral units from EXR header+const char* EXRGetSpectralUnits(const EXRHeader *exr_header) {+ if (!exr_header) return NULL;++ // Try ROOT/units first (spectral-exr format)+ const EXRAttribute *attr = FindCustomAttribute(exr_header, "ROOT/units");+ if (attr && attr->value && attr->size > 0) {+ return reinterpret_cast<const char*>(attr->value);+ }++ // Try emissiveUnits+ attr = FindCustomAttribute(exr_header, "emissiveUnits");+ if (attr && attr->value && attr->size > 0) {+ return reinterpret_cast<const char*>(attr->value);+ }++ return NULL;+}++// Helper to add a string attribute+static int AddStringAttribute(EXRHeader *exr_header, const char *name, const char *value) {+ if (!exr_header || !name || !value) return TINYEXR_ERROR_INVALID_ARGUMENT;++ int new_count = exr_header->num_custom_attributes + 1;+ if (new_count > TINYEXR_MAX_CUSTOM_ATTRIBUTES) {+ return TINYEXR_ERROR_DATA_TOO_LARGE;+ }++ // Reallocate attributes array+ EXRAttribute *new_attrs = static_cast<EXRAttribute*>(+ realloc(exr_header->custom_attributes,+ sizeof(EXRAttribute) * static_cast<size_t>(new_count)));+ if (!new_attrs) {+ return TINYEXR_ERROR_INVALID_DATA;+ }++ exr_header->custom_attributes = new_attrs;+ EXRAttribute *attr = &exr_header->custom_attributes[exr_header->num_custom_attributes];++ // Initialize the new attribute+ memset(attr, 0, sizeof(EXRAttribute));++#ifdef _MSC_VER+ strncpy_s(attr->name, sizeof(attr->name), name, 255);+ strncpy_s(attr->type, sizeof(attr->type), "string", 255);+#else+ strncpy(attr->name, name, 255);+ attr->name[255] = '\0';+ strncpy(attr->type, "string", 255);+ attr->type[255] = '\0';+#endif++ size_t value_len = strlen(value) + 1; // Include null terminator+ attr->value = static_cast<unsigned char*>(malloc(value_len));+ if (!attr->value) {+ return TINYEXR_ERROR_INVALID_DATA;+ }+ memcpy(attr->value, value, value_len);+ attr->size = static_cast<int>(value_len);++ exr_header->num_custom_attributes = new_count;++ return TINYEXR_SUCCESS;+}++// Helper to add an int attribute+static int AddIntAttribute(EXRHeader *exr_header, const char *name, int value) {+ if (!exr_header || !name) return TINYEXR_ERROR_INVALID_ARGUMENT;++ int new_count = exr_header->num_custom_attributes + 1;+ if (new_count > TINYEXR_MAX_CUSTOM_ATTRIBUTES) {+ return TINYEXR_ERROR_DATA_TOO_LARGE;+ }++ // Reallocate attributes array+ EXRAttribute *new_attrs = static_cast<EXRAttribute*>(+ realloc(exr_header->custom_attributes,+ sizeof(EXRAttribute) * static_cast<size_t>(new_count)));+ if (!new_attrs) {+ return TINYEXR_ERROR_INVALID_DATA;+ }++ exr_header->custom_attributes = new_attrs;+ EXRAttribute *attr = &exr_header->custom_attributes[exr_header->num_custom_attributes];++ // Initialize the new attribute+ memset(attr, 0, sizeof(EXRAttribute));++#ifdef _MSC_VER+ strncpy_s(attr->name, sizeof(attr->name), name, 255);+ strncpy_s(attr->type, sizeof(attr->type), "int", 255);+#else+ strncpy(attr->name, name, 255);+ attr->name[255] = '\0';+ strncpy(attr->type, "int", 255);+ attr->type[255] = '\0';+#endif++ attr->value = static_cast<unsigned char*>(malloc(sizeof(int)));+ if (!attr->value) {+ return TINYEXR_ERROR_INVALID_DATA;+ }+ memcpy(attr->value, &value, sizeof(int));+ attr->size = sizeof(int);++ exr_header->num_custom_attributes = new_count;++ return TINYEXR_SUCCESS;+}++// Set spectral attributes on EXR header+int EXRSetSpectralAttributes(EXRHeader *exr_header,+ int spectrum_type,+ const char *units) {+ if (!exr_header) return TINYEXR_ERROR_INVALID_ARGUMENT;++ int ret;++ // Add spectralLayoutVersion (always "1.0")+ ret = AddStringAttribute(exr_header, "spectralLayoutVersion", "1.0");+ if (ret != TINYEXR_SUCCESS) return ret;++ // Add units attribute based on spectrum type+ if (units && strlen(units) > 0) {+ if (spectrum_type == TINYEXR_SPECTRUM_REFLECTIVE) {+ ret = AddStringAttribute(exr_header, "ROOT/units", units);+ } else {+ ret = AddStringAttribute(exr_header, "emissiveUnits", units);+ }+ if (ret != TINYEXR_SUCCESS) return ret;+ }++ // Add polarisation handedness for polarised images+ if (spectrum_type == TINYEXR_SPECTRUM_POLARISED) {+ ret = AddStringAttribute(exr_header, "polarisationHandedness", "left");+ if (ret != TINYEXR_SUCCESS) return ret;+ }++ return TINYEXR_SUCCESS;+}++// Check if file contains spectral data+int IsSpectralEXR(const char *filename) {+ EXRVersion version;+ int ret = ParseEXRVersionFromFile(&version, filename);+ if (ret != TINYEXR_SUCCESS) return ret;++ const char *err = NULL;+ EXRHeader header;+ InitEXRHeader(&header);++ ret = ParseEXRHeaderFromFile(&header, &version, filename, &err);+ if (ret != TINYEXR_SUCCESS) {+ if (err) FreeEXRErrorMessage(err);+ return ret;+ }++ // Check for spectralLayoutVersion attribute+ int is_spectral = (FindCustomAttribute(&header, "spectralLayoutVersion") != NULL);++ FreeEXRHeader(&header);++ return is_spectral ? TINYEXR_SUCCESS : TINYEXR_ERROR_INVALID_DATA;+}++// Check if memory contains spectral EXR data+int IsSpectralEXRFromMemory(const unsigned char *memory, size_t size) {+ if (!memory || size < 8) return TINYEXR_ERROR_INVALID_DATA;++ EXRVersion version;+ int ret = ParseEXRVersionFromMemory(&version, memory, size);+ if (ret != TINYEXR_SUCCESS) return ret;++ const char *err = NULL;+ EXRHeader header;+ InitEXRHeader(&header);++ ret = ParseEXRHeaderFromMemory(&header, &version, memory, size, &err);+ if (ret != TINYEXR_SUCCESS) {+ if (err) FreeEXRErrorMessage(err);+ return ret;+ }++ // Check for spectralLayoutVersion attribute+ int is_spectral = (FindCustomAttribute(&header, "spectralLayoutVersion") != NULL);++ FreeEXRHeader(&header);++ return is_spectral ? TINYEXR_SUCCESS : TINYEXR_ERROR_INVALID_DATA;+}++#ifdef __clang__+// zero-as-null-pointer-constant+#pragma clang diagnostic pop+#endif++#endif // TINYEXR_IMPLEMENTATION_DEFINED+#endif // TINYEXR_IMPLEMENTATIONdiff --git a/third_party/tinyexr/tinyexr_impl.cpp b/third_party/tinyexr/tinyexr_impl.cppnew file mode 100644index 00000000..e822b1f9--- /dev/null+++ b/third_party/tinyexr/tinyexr_impl.cpp@@ -0,0 +1,8 @@+// tinyexr's implementation, built once. ZIP uses the zlib code of the vendored stb_image / stb_image_write+// (compiled in src/core/Image.cpp), so there is no miniz or zlib dependency; no threads, no OpenMP.+#define TINYEXR_USE_MINIZ 0+#define TINYEXR_USE_STB_ZLIB 1+#define TINYEXR_USE_THREAD 0+#define TINYEXR_USE_OPENMP 0+#define TINYEXR_IMPLEMENTATION+#include "tinyexr.h"