summaryrefslogtreecommitdiff
path: root/graphics/asymptote/cudareflect/EXRFiles.cc
blob: 3d9060f79d1ea23ff58b6ca2af51b1e31c853543 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include "EXRFiles.h"

EXRFile::EXRFile(std::string const& input)
{
    char const* err = nullptr;
    if (LoadEXR(&flt, &width, &height, input.c_str(), &err) != TINYEXR_SUCCESS)
    {
        if (err)
        {
            std::cerr << "TinyEXR ERROR: " << err << std::endl;
            FreeEXRErrorMessage(err);
            exit(1);
        }
    }
}

OEXRFile::OEXRFile(std::vector<float3> const& dat, int width, int height, int compressionType) :
    width(std::move(width)), height(std::move(height)),
    compressionType(compressionType), infos(3)
{
    for (float3 const& col : dat)
    {
        r.push_back(col.x);
        g.push_back(col.y);
        b.push_back(col.z);
        //a.push_back(col.w);
    }

    for (int i = 0; i < 3; ++i)
    {
        pixelType.push_back(TINYEXR_PIXELTYPE_FLOAT);
        reqPixelType.push_back(TINYEXR_PIXELTYPE_FLOAT);
    }

    initChannelInfo();
    initHeader();
}

OEXRFile::OEXRFile(std::vector<float2> const& dat, int width, int height, int compressionType) :
    width(std::move(width)), height(std::move(height)),
    compressionType(compressionType), infos(3)
{
    for (float2 const& col : dat)
    {
        r.push_back(col.x);
        g.push_back(col.y);
        b.push_back(0);
        //a.push_back(col.w);
    }

    for (int i = 0; i < 3; ++i)
    {
        pixelType.push_back(TINYEXR_PIXELTYPE_FLOAT);
        reqPixelType.push_back(TINYEXR_PIXELTYPE_FLOAT);
    }

    initChannelInfo();
    initHeader();
}

void OEXRFile::initChannelInfo()
{
    infos.resize(4);
    // strcpy(infos[0].name, "A");
    strcpy(infos[0].name, "B");
    strcpy(infos[1].name, "G");
    strcpy(infos[2].name, "R");

    for (auto& info : infos)
    {
        info.name[1] = '\0';
    }
}

void OEXRFile::initHeader()
{
    InitEXRHeader(&hd);
    hd.num_channels = 3;
    hd.channels = infos.data();
    hd.pixel_types = pixelType.data();
    hd.requested_pixel_types = reqPixelType.data();
    hd.compression_type = compressionType;
}

void OEXRFile::write(std::string const& filename)
{
    EXRImage im;
    InitEXRImage(&im);
    im.num_channels = 3;
    im.width = width;
    im.height = height;

    std::array<float*, 3> arr{ b.data(), g.data(), r.data() };

    im.images = reinterpret_cast<unsigned char**>(arr.data());

    char const* err = nullptr;
    if (SaveEXRImageToFile(&im, &hd, filename.c_str(), &err) != TINYEXR_SUCCESS)
    {
        std::cerr << "TinyEXR ERROR: " << err << std::endl;
        FreeEXRErrorMessage(err);
        exit(1);
    }
}