image.cpp 63.0 KB
Newer Older
M
Matt Pharr 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys.
// The pbrt source code is licensed under the Apache License, Version 2.0.
// SPDX: Apache-2.0

#include <pbrt/util/image.h>

#include <pbrt/util/bluenoise.h>
#include <pbrt/util/color.h>
#include <pbrt/util/colorspace.h>
#include <pbrt/util/error.h>
#include <pbrt/util/file.h>
#include <pbrt/util/math.h>
#include <pbrt/util/parallel.h>
#include <pbrt/util/print.h>
#include <pbrt/util/pstd.h>
#include <pbrt/util/string.h>

18 19
// No need, since we need to do our own file i/o to support UTF-8 filenames.
#define LODEPNG_NO_COMPILE_DISK
M
Matt Pharr 已提交
20
#include <lodepng/lodepng.h>
21

M
Matt Pharr 已提交
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
#ifndef PBRT_IS_GPU_CODE
// Work around conflict with "half".
#include <ImfChannelList.h>
#include <ImfChromaticitiesAttribute.h>
#include <ImfFloatAttribute.h>
#include <ImfFrameBuffer.h>
#include <ImfInputFile.h>
#include <ImfIntAttribute.h>
#include <ImfMatrixAttribute.h>
#include <ImfOutputFile.h>
#include <ImfStringVectorAttribute.h>
#endif

#include <cmath>
#include <numeric>

// use lodepng and get 16-bit.
#define STBI_NO_PNG
// too old school
#define STBI_NO_PIC
#define STBI_ASSERT CHECK
M
Matt Pharr 已提交
43
#define STBI_WINDOWS_UTF8
M
Matt Pharr 已提交
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
#include <stb/stb_image.h>

namespace pbrt {

std::string ToString(PixelFormat format) {
    switch (format) {
    case PixelFormat::U256:
        return "U256";
    case PixelFormat::Half:
        return "Half";
    case PixelFormat::Float:
        return "Float";
    default:
        LOG_FATAL("Unhandled PixelFormat in FormatName()");
        return "";
    }
}

int TexelBytes(PixelFormat format) {
    switch (format) {
    case PixelFormat::U256:
        return 1;
    case PixelFormat::Half:
        return 2;
    case PixelFormat::Float:
        return 4;
    default:
        LOG_FATAL("Unhandled PixelFormat in TexelBytes()");
        return 0;
    }
}

std::string ImageChannelValues::ToString() const {
    return StringPrintf("[ ImageChannelValues %s ]", ((InlinedVector<Float, 4> &)*this));
}

std::string ImageChannelDesc::ToString() const {
    return StringPrintf("[ ImageChannelDesc offset: %s ]", offset);
}

std::string ImageMetadata::ToString() const {
    return StringPrintf("[ ImageMetadata renderTimeSeconds: %s cameraFromWorld: %s "
                        "NDCFromWorld: %s pixelBounds: %s fullResolution: %s "
M
Matt Pharr 已提交
87
                        "samplesPerPixel: %s MSE: %s colorSpace: %s ]",
M
Matt Pharr 已提交
88
                        renderTimeSeconds, cameraFromWorld, NDCFromWorld, pixelBounds,
M
Matt Pharr 已提交
89
                        fullResolution, samplesPerPixel, MSE, colorSpace);
M
Matt Pharr 已提交
90 91 92 93 94 95 96 97 98
}

const RGBColorSpace *ImageMetadata::GetColorSpace() const {
    if (colorSpace && *colorSpace)
        return *colorSpace;
    return RGBColorSpace::sRGB;
}

template <typename F>
99
void ForExtent(const Bounds2i &extent, WrapMode2D wrapMode, const Image &image, F op) {
M
Matt Pharr 已提交
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
    CHECK_LT(extent.pMin.x, extent.pMax.x);
    CHECK_LT(extent.pMin.y, extent.pMax.y);

    int nx = extent.pMax[0] - extent.pMin[0];
    int nc = image.NChannels();
    if (Intersect(extent, Bounds2i({0, 0}, image.Resolution())) == extent) {
        // All in bounds
        for (int y = extent.pMin[1]; y < extent.pMax[1]; ++y) {
            int offset = image.PixelOffset({extent.pMin[0], y});
            for (int x = 0; x < nx; ++x)
                for (int c = 0; c < nc; ++c)
                    op(offset++);
        }
    } else {
        for (int y = extent.pMin[1]; y < extent.pMax[1]; ++y) {
            for (int x = 0; x < nx; ++x) {
                Point2i p(extent.pMin[0] + x, y);
                // FIXME: this will return false on Black wrap mode
                CHECK(RemapPixelCoords(&p, image.Resolution(), wrapMode));
                int offset = image.PixelOffset(p);
                for (int c = 0; c < nc; ++c)
                    op(offset++);
            }
        }
    }
}

// Image Method Definitions
128 129
pstd::vector<Image> Image::GeneratePyramid(Image image, WrapMode2D wrapMode,
                                           Allocator alloc) {
M
Matt Pharr 已提交
130 131
    PixelFormat origFormat = image.format;
    int nChannels = image.NChannels();
132
    ColorEncoding origEncoding = image.encoding;
133
    // Prepare _image_ for building pyramid
134
    if (!IsPowerOf2(image.resolution[0]) || !IsPowerOf2(image.resolution[1]))
135
        image = image.FloatResizeUp(
M
Matt Pharr 已提交
136 137
            {RoundUpPow2(image.resolution[0]), RoundUpPow2(image.resolution[1])},
            wrapMode);
138
    else if (!Is32Bit(image.format))
M
Matt Pharr 已提交
139 140 141
        image = image.ConvertToFormat(PixelFormat::Float);
    CHECK(Is32Bit(image.format));

142
    // Initialize levels of pyramid from _image_
M
Matt Pharr 已提交
143 144 145 146
    int nLevels = 1 + Log2Int(std::max(image.resolution[0], image.resolution[1]));
    pstd::vector<Image> pyramid(alloc);
    pyramid.reserve(nLevels);
    for (int i = 0; i < nLevels - 1; ++i) {
147
        // Initialize $i+1$st level from $i$th level and copy $i$th into pyramid
M
Matt Pharr 已提交
148
        pyramid.push_back(
149 150 151 152
            Image(origFormat, image.resolution, image.channelNames, origEncoding, alloc));
        // Initialize _nextImage_ for $i+1$st level
        Point2i nextResolution(std::max(1, image.resolution[0] / 2),
                               std::max(1, image.resolution[1] / 2));
M
Matt Pharr 已提交
153 154
        Image nextImage(image.format, nextResolution, image.channelNames, origEncoding);

155
        // Compute offsets from pixel to the 4 neighbors used for down filtering
156 157 158
        int srcDeltas[4] = {0, nChannels, nChannels * image.resolution[0],
                            nChannels * (image.resolution[0] + 1)};
        if (image.resolution[0] == 1) {
M
Matt Pharr 已提交
159 160 161
            srcDeltas[1] = 0;
            srcDeltas[3] -= nChannels;
        }
162
        if (image.resolution[1] == 1) {
M
Matt Pharr 已提交
163
            srcDeltas[2] = 0;
164
            srcDeltas[3] -= nChannels * image.resolution[0];
M
Matt Pharr 已提交
165 166
        }

167
        // Downsample _image_ to create next level and update _pyramid_
168
        ParallelFor(0, nextResolution[1], [&](int64_t y) {
169
            // Loop over pixels in scanline $y$ and downfilter for the next pyramid level
170 171
            int srcOffset = image.PixelOffset({0, 2 * int(y)});
            int nextOffset = nextImage.PixelOffset({0, int(y)});
172 173
            for (int x = 0; x < nextResolution[0]; ++x, srcOffset += nChannels)
                for (int c = 0; c < nChannels; ++c, ++srcOffset, ++nextOffset)
174 175 176
                    nextImage.p32[nextOffset] =
                        (image.p32[srcOffset] + image.p32[srcOffset + srcDeltas[1]] +
                         image.p32[srcOffset + srcDeltas[2]] +
177 178
                         image.p32[srcOffset + srcDeltas[3]]) /
                        4;
M
Matt Pharr 已提交
179

180
            // Copy 2 scalines from _image_ out to its pyramid level
181
            int yStart = 2 * y;
182
            int yEnd = std::min(2 * int(y) + 2, image.resolution[1]);
183
            int offset = image.PixelOffset({0, yStart});
184 185
            size_t count = (yEnd - yStart) * nChannels * image.resolution[0];
            pyramid[i].CopyRectIn(Bounds2i({0, yStart}, {image.resolution[0], yEnd}),
186 187
                                  {image.p32.data() + offset, count});
        });
M
Matt Pharr 已提交
188 189 190
        image = std::move(nextImage);
    }

191 192 193
    // Initialize top level of pyramid and return it
    CHECK(image.resolution[0] == 1 && image.resolution[1] == 1);
    pyramid.push_back(Image(origFormat, {1, 1}, image.channelNames, origEncoding, alloc));
M
Matt Pharr 已提交
194 195 196 197 198
    pyramid[nLevels - 1].CopyRectIn({{0, 0}, {1, 1}},
                                    {image.p32.data(), size_t(nChannels)});
    return pyramid;
}

199
bool Image::HasAnyInfinitePixels() const {
200 201
    if (format == PixelFormat::U256)
        return false;
M
Matt Pharr 已提交
202

203 204 205 206 207 208 209 210 211
    for (int y = 0; y < resolution.y; ++y)
        for (int x = 0; x < resolution.x; ++x)
            for (int c = 0; c < NChannels(); ++c)
                if (IsInf(GetChannel({x, y}, c)))
                    return true;
    return false;
}

bool Image::HasAnyNaNPixels() const {
212 213
    if (format == PixelFormat::U256)
        return false;
M
Matt Pharr 已提交
214

215 216 217 218 219 220 221 222
    for (int y = 0; y < resolution.y; ++y)
        for (int x = 0; x < resolution.x; ++x)
            for (int c = 0; c < NChannels(); ++c)
                if (IsNaN(GetChannel({x, y}, c)))
                    return true;
    return false;
}

M
Matt Pharr 已提交
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
Image Image::GaussianFilter(const ImageChannelDesc &desc, int halfWidth,
                            Float sigma) const {
    // Compute filter weights
    std::vector<Float> wts(2 * halfWidth + 1, Float(0));
    for (int d = 0; d < 2 * halfWidth + 1; ++d)
        wts[d] = Gaussian(d - halfWidth, 0, sigma);

    // Normalize weights
    Float wtSum = std::accumulate(wts.begin(), wts.end(), Float(0));
    for (Float &w : wts)
        w /= wtSum;

    // Separable blur; first blur in x into blurx, selecting out the
    // desired channels along the way.
    Image blurx(PixelFormat::Float, resolution, ChannelNames(desc));
    int nc = desc.size();
    ParallelFor(0, resolution.y, [&](int64_t y0, int64_t y1) {
        for (int y = y0; y < y1; ++y) {
            for (int x = 0; x < resolution.x; ++x) {
                ImageChannelValues result(desc.size());
                for (int r = -halfWidth; r <= halfWidth; ++r) {
                    ImageChannelValues cv = GetChannels({x + r, y}, desc);
                    for (int c = 0; c < nc; ++c)
                        result[c] += wts[r + halfWidth] * cv[c];
                }
                blurx.SetChannels({x, y}, result);
            }
        }
    });

    // Now blur in y from blur x to the result; blurx has just the
    // channels we want already.
    Image blury(PixelFormat::Float, resolution, ChannelNames(desc));
    ParallelFor(0, resolution.y, [&](int64_t y0, int64_t y1) {
        for (int y = y0; y < y1; ++y) {
            for (int x = 0; x < resolution.x; ++x) {
                ImageChannelValues result(desc.size());
                for (int r = -halfWidth; r <= halfWidth; ++r) {
                    ImageChannelValues cv = blurx.GetChannels({x, y + r});
                    for (int c = 0; c < nc; ++c)
                        result[c] += wts[r + halfWidth] * cv[c];
                }
                blury.SetChannels({x, y}, result);
            }
        }
    });
    return blury;
}

272
std::vector<ResampleWeight> Image::ResampleWeights(int oldRes, int newRes) {
M
Matt Pharr 已提交
273 274
    CHECK_GE(newRes, oldRes);
    std::vector<ResampleWeight> wt(newRes);
275
    Float filterRadius = 2, tau = 2;
M
Matt Pharr 已提交
276
    for (int i = 0; i < newRes; ++i) {
277
        // Compute image resampling weights for _i_th pixel
M
Matt Pharr 已提交
278
        Float center = (i + .5f) * oldRes / newRes;
279
        wt[i].firstPixel = pstd::floor((center - filterRadius) + 0.5f);
M
Matt Pharr 已提交
280
        for (int j = 0; j < 4; ++j) {
281 282
            Float pos = wt[i].firstPixel + j + .5f;
            wt[i].weight[j] = WindowedSinc(pos - center, filterRadius, tau);
M
Matt Pharr 已提交
283 284
        }

285
        // Normalize filter weights for pixel resampling
M
Matt Pharr 已提交
286 287 288 289 290 291 292 293
        Float invSumWts =
            1 / (wt[i].weight[0] + wt[i].weight[1] + wt[i].weight[2] + wt[i].weight[3]);
        for (int j = 0; j < 4; ++j)
            wt[i].weight[j] *= invSumWts;
    }
    return wt;
}

294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
Image Image::FloatResizeUp(Point2i newRes, WrapMode2D wrapMode) const {
    CHECK_GE(newRes.x, resolution.x);
    CHECK_GE(newRes.y, resolution.y);
    Image resampledImage(PixelFormat::Float, newRes, channelNames);
    // Compute $x$ and $y$ resampling weights for image resizing
    std::vector<ResampleWeight> xWeights, yWeights;
    xWeights = ResampleWeights(resolution[0], newRes[0]);
    yWeights = ResampleWeights(resolution[1], newRes[1]);

    // Resize image in parallel, working by tiles
    ParallelFor2D(Bounds2i({0, 0}, newRes), [&](Bounds2i outExtent) {
        // Determine extent in source image and copy pixel values to _inBuf_
        Bounds2i inExtent(Point2i(xWeights[outExtent.pMin.x].firstPixel,
                                  yWeights[outExtent.pMin.y].firstPixel),
                          Point2i(xWeights[outExtent.pMax.x - 1].firstPixel + 4,
                                  yWeights[outExtent.pMax.y - 1].firstPixel + 4));
        std::vector<float> inBuf(NChannels() * inExtent.Area());
        CopyRectOut(inExtent, pstd::span<float>(inBuf), wrapMode);

        // Resize image in the $x$ dimension
        // Compute image extents and allocate _xBuf_
        int nxOut = outExtent.pMax.x - outExtent.pMin.x;
        int nyOut = outExtent.pMax.y - outExtent.pMin.y;
        int nxIn = inExtent.pMax.x - inExtent.pMin.x;
        int nyIn = inExtent.pMax.y - inExtent.pMin.y;
        std::vector<float> xBuf(NChannels() * nyIn * nxOut);
M
Matt Pharr 已提交
320 321

        int xBufOffset = 0;
322 323 324
        for (int yOut = inExtent.pMin.y; yOut < inExtent.pMax.y; ++yOut) {
            for (int xOut = outExtent.pMin.x; xOut < outExtent.pMax.x; ++xOut) {
                // Resample image pixel _(xOut, yOut)_
M
Matt Pharr 已提交
325 326
                DCHECK(xOut >= 0 && xOut < xWeights.size());
                const ResampleWeight &rsw = xWeights[xOut];
327
                // Compute _inOffset_ into _inBuf_ for _(xOut, yOut)_
M
Matt Pharr 已提交
328
                // w.r.t. inBuf
329
                int xIn = rsw.firstPixel - inExtent.pMin.x;
M
Matt Pharr 已提交
330 331
                DCHECK_GE(xIn, 0);
                DCHECK_LT(xIn + 3, nxIn);
332 333
                int yIn = yOut - inExtent.pMin.y;
                int inOffset = NChannels() * (xIn + yIn * nxIn);
M
Matt Pharr 已提交
334 335
                DCHECK_GE(inOffset, 0);
                DCHECK_LT(inOffset + 3 * NChannels(), inBuf.size());
336 337 338 339 340 341

                for (int c = 0; c < NChannels(); ++c, ++xBufOffset, ++inOffset)
                    xBuf[xBufOffset] = rsw.weight[0] * inBuf[inOffset] +
                                       rsw.weight[1] * inBuf[inOffset + NChannels()] +
                                       rsw.weight[2] * inBuf[inOffset + 2 * NChannels()] +
                                       rsw.weight[3] * inBuf[inOffset + 3 * NChannels()];
M
Matt Pharr 已提交
342 343 344
            }
        }

345 346
        // Resize image in the $y$ dimension
        std::vector<float> outBuf(NChannels() * nxOut * nyOut);
M
Matt Pharr 已提交
347 348 349 350 351 352
        for (int x = 0; x < nxOut; ++x) {
            for (int y = 0; y < nyOut; ++y) {
                int yOut = y + outExtent[0][1];
                DCHECK(yOut >= 0 && yOut < yWeights.size());
                const ResampleWeight &rsw = yWeights[yOut];

353
                DCHECK_GE(rsw.firstPixel - inExtent[0][1], 0);
M
Matt Pharr 已提交
354
                int xBufOffset =
355
                    NChannels() * (x + nxOut * (rsw.firstPixel - inExtent[0][1]));
M
Matt Pharr 已提交
356 357 358 359 360 361 362 363 364 365 366 367 368
                DCHECK_GE(xBufOffset, 0);
                int step = NChannels() * nxOut;
                DCHECK_LT(xBufOffset + 3 * step, xBuf.size());

                int outOffset = NChannels() * (x + y * nxOut);
                for (int c = 0; c < NChannels(); ++c, ++outOffset, ++xBufOffset)
                    outBuf[outOffset] =
                        std::max<Float>(0, (rsw.weight[0] * xBuf[xBufOffset] +
                                            rsw.weight[1] * xBuf[xBufOffset + step] +
                                            rsw.weight[2] * xBuf[xBufOffset + 2 * step] +
                                            rsw.weight[3] * xBuf[xBufOffset + 3 * step]));
            }
        }
369 370

        // Copy resampled image pixels out into _resampledImage_
M
Matt Pharr 已提交
371 372 373 374 375 376
        resampledImage.CopyRectIn(outExtent, outBuf);
    });

    return resampledImage;
}

377
Image::Image(PixelFormat format, Point2i resolution,
378
             pstd::span<const std::string> channels, ColorEncoding encoding,
379 380 381 382 383 384 385 386 387 388
             Allocator alloc)
    : format(format),
      resolution(resolution),
      channelNames(channels.begin(), channels.end()),
      encoding(encoding),
      p8(alloc),
      p16(alloc),
      p32(alloc) {
    if (Is8Bit(format)) {
        p8.resize(NChannels() * resolution[0] * resolution[1]);
M
Matt Pharr 已提交
389
        CHECK(encoding);
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
    } else if (Is16Bit(format))
        p16.resize(NChannels() * resolution[0] * resolution[1]);
    else if (Is32Bit(format))
        p32.resize(NChannels() * resolution[0] * resolution[1]);
    else
        LOG_FATAL("Unhandled format in Image::Image()");
}

ImageChannelDesc Image::GetChannelDesc(
    pstd::span<const std::string> requestedChannels) const {
    ImageChannelDesc desc;
    desc.offset.resize(requestedChannels.size());
    for (size_t i = 0; i < requestedChannels.size(); ++i) {
        size_t j;
        for (j = 0; j < channelNames.size(); ++j)
            if (requestedChannels[i] == channelNames[j]) {
                desc.offset[i] = j;
                break;
            }
        if (j == channelNames.size())
            return {};
    }

    return desc;
}

ImageChannelValues Image::GetChannels(Point2i p, const ImageChannelDesc &desc,
                                      WrapMode2D wrapMode) const {
    ImageChannelValues cv(desc.offset.size(), Float(0));
    if (!RemapPixelCoords(&p, resolution, wrapMode))
        return cv;

    size_t pixelOffset = PixelOffset(p);
    switch (format) {
    case PixelFormat::U256: {
        for (int i = 0; i < desc.offset.size(); ++i)
            encoding.ToLinear({&p8[pixelOffset + desc.offset[i]], 1}, {&cv[i], 1});
        break;
    }
    case PixelFormat::Half: {
        for (int i = 0; i < desc.offset.size(); ++i)
            cv[i] = Float(p16[pixelOffset + desc.offset[i]]);
        break;
    }
    case PixelFormat::Float: {
        for (int i = 0; i < desc.offset.size(); ++i)
            cv[i] = p32[pixelOffset + desc.offset[i]];
        break;
    }
    default:
        LOG_FATAL("Unhandled PixelFormat");
    }

    return cv;
}

void Image::SetChannels(Point2i p, const ImageChannelDesc &desc,
                        pstd::span<const Float> values) {
    CHECK_LE(values.size(), NChannels());
    for (size_t i = 0; i < values.size(); ++i)
        SetChannel(p, desc.offset[i], values[i]);
}

M
Matt Pharr 已提交
453
Image::Image(pstd::vector<uint8_t> p8c, Point2i resolution,
454
             pstd::span<const std::string> channels, ColorEncoding encoding)
M
Matt Pharr 已提交
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
    : format(PixelFormat::U256),
      resolution(resolution),
      channelNames(channels.begin(), channels.end()),
      encoding(encoding),
      p8(std::move(p8c)) {
    CHECK_EQ(p8.size(), NChannels() * resolution[0] * resolution[1]);
}

Image::Image(pstd::vector<Half> p16c, Point2i resolution,
             pstd::span<const std::string> channels)
    : format(PixelFormat::Half),
      resolution(resolution),
      channelNames(channels.begin(), channels.end()),
      p16(std::move(p16c)) {
    CHECK_EQ(p16.size(), NChannels() * resolution[0] * resolution[1]);
    CHECK(Is16Bit(format));
}

Image::Image(pstd::vector<float> p32c, Point2i resolution,
             pstd::span<const std::string> channels)
    : format(PixelFormat::Float),
      resolution(resolution),
      channelNames(channels.begin(), channels.end()),
      p32(std::move(p32c)) {
    CHECK_EQ(p32.size(), NChannels() * resolution[0] * resolution[1]);
    CHECK(Is32Bit(format));
}

483
Image Image::ConvertToFormat(PixelFormat newFormat, ColorEncoding encoding) const {
M
Matt Pharr 已提交
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
    if (newFormat == format)
        return *this;

    Image newImage(newFormat, resolution, channelNames, encoding);
    for (int y = 0; y < resolution.y; ++y)
        for (int x = 0; x < resolution.x; ++x)
            for (int c = 0; c < NChannels(); ++c)
                newImage.SetChannel({x, y}, c, GetChannel({x, y}, c));
    return newImage;
}

ImageChannelValues Image::GetChannels(Point2i p, WrapMode2D wrapMode) const {
    ImageChannelValues cv(NChannels(), Float(0));
    if (!RemapPixelCoords(&p, resolution, wrapMode))
        return cv;

    size_t pixelOffset = PixelOffset(p);
    switch (format) {
    case PixelFormat::U256: {
        encoding.ToLinear({&p8[pixelOffset], size_t(NChannels())},
                          {&cv[0], size_t(NChannels())});
        break;
    }
    case PixelFormat::Half: {
        for (int i = 0; i < NChannels(); ++i)
            cv[i] = Float(p16[pixelOffset + i]);
        break;
    }
    case PixelFormat::Float: {
        for (int i = 0; i < NChannels(); ++i)
            cv[i] = p32[pixelOffset + i];
        break;
    }
    default:
        LOG_FATAL("Unhandled PixelFormat");
    }

    return cv;
}

std::vector<std::string> Image::ChannelNames() const {
    return {channelNames.begin(), channelNames.end()};
}

std::vector<std::string> Image::ChannelNames(const ImageChannelDesc &desc) const {
    std::vector<std::string> names;
    for (int i = 0; i < desc.size(); ++i)
        names.push_back(channelNames[desc.offset[i]]);
    return names;
}

535 536
ImageChannelValues Image::MAE(const ImageChannelDesc &desc, const Image &ref,
                              Image *errorImage) const {
M
Matt Pharr 已提交
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
    std::vector<double> sumError(desc.size(), 0.);

    ImageChannelDesc refDesc = ref.GetChannelDesc(ChannelNames(desc));
    CHECK((bool)refDesc);
    CHECK_EQ(Resolution(), ref.Resolution());

    if (errorImage)
        *errorImage = Image(PixelFormat::Float, Resolution(), ChannelNames());

    for (int y = 0; y < Resolution().y; ++y)
        for (int x = 0; x < Resolution().x; ++x) {
            ImageChannelValues v = GetChannels({x, y}, desc);
            ImageChannelValues vref = ref.GetChannels({x, y}, refDesc);

            for (int c = 0; c < desc.size(); ++c) {
                Float error = v[c] - vref[c];
553
                if (IsInf(error))
M
Matt Pharr 已提交
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
                    continue;
                sumError[c] += error;
                if (errorImage)
                    errorImage->SetChannel({x, y}, c, error);
            }
        }

    ImageChannelValues error(desc.size());
    for (int c = 0; c < desc.size(); ++c)
        error[c] = sumError[c] / (Resolution().x * Resolution().y);
    return error;
}

ImageChannelValues Image::MSE(const ImageChannelDesc &desc, const Image &ref,
                              Image *mseImage) const {
    std::vector<double> sumSE(desc.size(), 0.);

    ImageChannelDesc refDesc = ref.GetChannelDesc(ChannelNames(desc));
    if (!refDesc)
        ErrorExit("Channels not found in image: %s", ChannelNames(desc));

    CHECK_EQ(Resolution(), ref.Resolution());

    if (mseImage)
        *mseImage = Image(PixelFormat::Float, Resolution(), ChannelNames());

    for (int y = 0; y < Resolution().y; ++y)
        for (int x = 0; x < Resolution().x; ++x) {
            ImageChannelValues v = GetChannels({x, y}, desc);
            ImageChannelValues vref = ref.GetChannels({x, y}, refDesc);

            for (int c = 0; c < desc.size(); ++c) {
                Float se = Sqr(v[c] - vref[c]);
587
                if (IsInf(se))
M
Matt Pharr 已提交
588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
                    continue;
                sumSE[c] += se;
                if (mseImage)
                    mseImage->SetChannel({x, y}, c, se);
            }
        }

    ImageChannelValues mse(desc.size());
    for (int c = 0; c < desc.size(); ++c)
        mse[c] = sumSE[c] / (Resolution().x * Resolution().y);
    return mse;
}

ImageChannelValues Image::MRSE(const ImageChannelDesc &desc, const Image &ref,
                               Image *mrseImage) const {
    std::vector<double> sumRSE(desc.size(), 0.);

    ImageChannelDesc refDesc = ref.GetChannelDesc(ChannelNames(desc));
    CHECK((bool)refDesc);
    CHECK_EQ(Resolution(), ref.Resolution());

    if (mrseImage)
        *mrseImage = Image(PixelFormat::Float, Resolution(), ChannelNames());

    for (int y = 0; y < Resolution().y; ++y)
        for (int x = 0; x < Resolution().x; ++x) {
            ImageChannelValues v = GetChannels({x, y}, desc);
            ImageChannelValues vref = ref.GetChannels({x, y}, refDesc);

            for (int c = 0; c < desc.size(); ++c) {
                Float rse = Sqr(v[c] - vref[c]) / Sqr(vref[c] + 0.01);
619
                if (IsInf(rse))
M
Matt Pharr 已提交
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
                    continue;
                sumRSE[c] += rse;
                if (mrseImage)
                    mrseImage->SetChannel({x, y}, c, rse);
            }
        }

    ImageChannelValues mrse(desc.size());
    for (int c = 0; c < desc.size(); ++c)
        mrse[c] = sumRSE[c] / (Resolution().x * Resolution().y);
    return mrse;
}

ImageChannelValues Image::Average(const ImageChannelDesc &desc) const {
    std::vector<double> sum(desc.size(), 0.);

    for (int y = 0; y < Resolution().y; ++y)
        for (int x = 0; x < Resolution().x; ++x) {
            ImageChannelValues v = GetChannels({x, y}, desc);
            for (int c = 0; c < desc.size(); ++c)
                sum[c] += v[c];
        }

    ImageChannelValues average(desc.size());
    for (int c = 0; c < desc.size(); ++c)
        average[c] = sum[c] / (Resolution().x * Resolution().y);
    return average;
}

void Image::CopyRectOut(const Bounds2i &extent, pstd::span<float> buf,
650
                        WrapMode2D wrapMode) const {
M
Matt Pharr 已提交
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
    CHECK_GE(buf.size(), extent.Area() * NChannels());

    auto bufIter = buf.begin();
    switch (format) {
    case PixelFormat::U256:
        if (Intersect(extent, Bounds2i({0, 0}, resolution)) == extent) {
            // All in bounds
            size_t count = NChannels() * (extent.pMax.x - extent.pMin.x);
            for (int y = extent.pMin.y; y < extent.pMax.y; ++y) {
                // Convert scanlines all at once.
                size_t offset = PixelOffset({extent.pMin.x, y});
#ifdef PBRT_FLOAT_AS_DOUBLE
                for (int i = 0; i < count; ++i) {
                    Float v;
                    encoding.ToLinear({&p8[offset + i], 1}, {&v, 1});
                    *bufIter++ = v;
                }
#else
                encoding.ToLinear({&p8[offset], count}, {&*bufIter, count});
                bufIter += count;
671
#endif
M
Matt Pharr 已提交
672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862
            }
        } else {
            ForExtent(extent, wrapMode, *this, [&bufIter, this](int offset) {
#ifdef PBRT_FLOAT_AS_DOUBLE
                Float v;
                encoding.ToLinear({&p8[offset], 1}, {&v, 1});
                *bufIter = v;
#else
                encoding.ToLinear({&p8[offset], 1}, {&*bufIter, 1});
#endif
                ++bufIter;
            });
        }
        break;

    case PixelFormat::Half:
        ForExtent(extent, wrapMode, *this,
                  [&bufIter, this](int offset) { *bufIter++ = Float(p16[offset]); });
        break;

    case PixelFormat::Float:
        ForExtent(extent, wrapMode, *this,
                  [&bufIter, this](int offset) { *bufIter++ = Float(p32[offset]); });
        break;

    default:
        LOG_FATAL("Unhandled PixelFormat");
    }
}

void Image::CopyRectIn(const Bounds2i &extent, pstd::span<const float> buf) {
    CHECK_GE(buf.size(), extent.Area() * NChannels());

    auto bufIter = buf.begin();
    switch (format) {
    case PixelFormat::U256:
        if (Intersect(extent, Bounds2i({0, 0}, resolution)) == extent) {
            // All in bounds
            size_t count = NChannels() * (extent.pMax.x - extent.pMin.x);
            for (int y = extent.pMin.y; y < extent.pMax.y; ++y) {
                // Convert scanlines all at once.
                size_t offset = PixelOffset({extent.pMin.x, y});
#ifdef PBRT_FLOAT_AS_DOUBLE
                for (int i = 0; i < count; ++i) {
                    Float v = *bufIter++;
                    encoding.FromLinear({&v, 1}, {&p8[offset + i], 1});
                }
#else
                encoding.FromLinear({&*bufIter, count}, {&p8[offset], count});
                bufIter += count;
#endif
            }
        } else
            ForExtent(extent, WrapMode::Clamp, *this, [&bufIter, this](int offset) {
                Float v = *bufIter++;
                encoding.FromLinear({&v, 1}, {&p8[offset], 1});
            });
        break;

    case PixelFormat::Half:
        ForExtent(extent, WrapMode::Clamp, *this,
                  [&bufIter, this](int offset) { p16[offset] = Half(*bufIter++); });
        break;

    case PixelFormat::Float:
        ForExtent(extent, WrapMode::Clamp, *this,
                  [&bufIter, this](int offset) { p32[offset] = *bufIter++; });
        break;

    default:
        LOG_FATAL("Unhandled PixelFormat");
    }
}

ImageChannelValues Image::LookupNearest(Point2f p, WrapMode2D wrapMode) const {
    ImageChannelValues cv(NChannels(), Float(0));
    for (int c = 0; c < NChannels(); ++c)
        cv[c] = LookupNearestChannel(p, c, wrapMode);
    return cv;
}

ImageChannelValues Image::LookupNearest(Point2f p, const ImageChannelDesc &desc,
                                        WrapMode2D wrapMode) const {
    ImageChannelValues cv(desc.offset.size(), Float(0));
    for (int i = 0; i < desc.offset.size(); ++i)
        cv[i] = LookupNearestChannel(p, desc.offset[i], wrapMode);
    return cv;
}

ImageChannelValues Image::Bilerp(Point2f p, WrapMode2D wrapMode) const {
    ImageChannelValues cv(NChannels(), Float(0));
    for (int c = 0; c < NChannels(); ++c)
        cv[c] = BilerpChannel(p, c, wrapMode);
    return cv;
}

ImageChannelValues Image::Bilerp(Point2f p, const ImageChannelDesc &desc,
                                 WrapMode2D wrapMode) const {
    ImageChannelValues cv(desc.offset.size(), Float(0));
    for (int i = 0; i < desc.offset.size(); ++i)
        cv[i] = BilerpChannel(p, desc.offset[i], wrapMode);
    return cv;
}

void Image::SetChannels(Point2i p, const ImageChannelValues &values) {
    CHECK_LE(values.size(), NChannels());
    int i = 0;
    for (auto iter = values.begin(); iter != values.end(); ++iter, ++i)
        SetChannel(p, i, *iter);
}

void Image::SetChannels(Point2i p, pstd::span<const Float> values) {
    CHECK_LE(values.size(), NChannels());
    for (size_t i = 0; i < values.size(); ++i)
        SetChannel(p, i, values[i]);
}

void Image::FlipY() {
    for (int y = 0; y < resolution.y / 2; ++y) {
        for (int x = 0; x < resolution.x; ++x) {
            size_t o1 = PixelOffset({x, y}), o2 = PixelOffset({x, resolution.y - 1 - y});
            for (int c = 0; c < NChannels(); ++c) {
                if (Is8Bit(format))
                    pstd::swap(p8[o1 + c], p8[o2 + c]);
                else if (Is16Bit(format))
                    pstd::swap(p16[o1 + c], p16[o2 + c]);
                else if (Is32Bit(format))
                    pstd::swap(p32[o1 + c], p32[o2 + c]);
                else
                    LOG_FATAL("unexpected format");
            }
        }
    }
}

Image Image::JointBilateralFilter(const ImageChannelDesc &toFilterDesc, int halfWidth,
                                  const Float xySigma[2],
                                  const ImageChannelDesc &jointDesc,
                                  const ImageChannelValues &jointSigma) const {
    CHECK_EQ(jointDesc.size(), jointSigma.size());
    Image result(PixelFormat::Float, resolution, ChannelNames(toFilterDesc));

    std::vector<Float> fx, fy;
    for (int i = 0; i <= halfWidth; ++i) {
        fx.push_back(Gaussian(i, 0, xySigma[0]));
        fy.push_back(Gaussian(i, 0, xySigma[1]));
    }

    ParallelFor(0, resolution.y, [&](int64_t y0, int64_t y1) {
        for (int y = y0; y < y1; ++y) {
            for (int x = 0; x < resolution.x; ++x) {
                ImageChannelValues jointPixelChannels = GetChannels({x, y}, jointDesc);
                ImageChannelValues filteredSum(toFilterDesc.size(), Float(0));
                Float weightSum = 0;

                for (int dy = -halfWidth + 1; dy < halfWidth; ++dy) {
                    if (y + dy < 0 || y + dy >= resolution.y)
                        continue;
                    for (int dx = -halfWidth + 1; dx < halfWidth; ++dx) {
                        for (int dx = -halfWidth + 1; dx < halfWidth; ++dx) {
                            if (x + dx < 0 || x + dx >= resolution.x)
                                continue;
                            ImageChannelValues jointOtherChannels =
                                GetChannels({x + dx, y + dy}, jointDesc);
                            Float weight = fx[std::abs(dx)] * fy[std::abs(dy)];
                            for (int c = 0; c < jointDesc.size(); ++c)
                                weight *= Gaussian(jointPixelChannels[c],
                                                   jointOtherChannels[c], jointSigma[c]);
                            weightSum += weight;

                            ImageChannelValues filterChannels =
                                GetChannels({x + dx, y + dy}, toFilterDesc);
                            for (int c = 0; c < filterChannels.size(); ++c)
                                filteredSum[c] += weight * filterChannels[c];
                        }
                    }
                }
                if (weightSum > 0)
                    for (int c = 0; c < filteredSum.size(); ++c)
                        filteredSum[c] /= weightSum;
                result.SetChannels({x, y}, filteredSum);
            }
        }
    });

    return result;
}

// ImageIO Local Declarations
static ImageAndMetadata ReadEXR(const std::string &name, Allocator alloc);
static ImageAndMetadata ReadPNG(const std::string &name, Allocator alloc,
863
                                ColorEncoding encoding);
M
Matt Pharr 已提交
864 865 866 867
static ImageAndMetadata ReadPFM(const std::string &filename, Allocator alloc);
static ImageAndMetadata ReadHDR(const std::string &filename, Allocator alloc);

// ImageIO Function Definitions
M
Matt Pharr 已提交
868
ImageAndMetadata Image::Read(std::string name, Allocator alloc, ColorEncoding encoding) {
M
Matt Pharr 已提交
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885
    if (HasExtension(name, "exr"))
        return ReadEXR(name, alloc);
    else if (HasExtension(name, "png"))
        return ReadPNG(name, alloc, encoding);
    else if (HasExtension(name, "pfm"))
        return ReadPFM(name, alloc);
    else if (HasExtension(name, "hdr"))
        return ReadHDR(name, alloc);
    else {
        int x, y, n;
        unsigned char *data = stbi_load(name.c_str(), &x, &y, &n, 0);
        if (data) {
            pstd::vector<uint8_t> pixels(data, data + x * y * n, alloc);
            stbi_image_free(data);
            switch (n) {
            case 1:
                return ImageAndMetadata{
886
                    Image(std::move(pixels), {x, y}, {"Y"}, ColorEncoding::sRGB),
M
Matt Pharr 已提交
887 888
                    ImageMetadata()};
            case 2: {
889
                Image image(std::move(pixels), {x, y}, {"Y", "A"}, ColorEncoding::sRGB);
M
Matt Pharr 已提交
890 891 892 893 894
                return ImageAndMetadata{image.SelectChannels(image.GetChannelDesc({"Y"})),
                                        ImageMetadata()};
            }
            case 3:
                return ImageAndMetadata{Image(std::move(pixels), {x, y}, {"R", "G", "B"},
895
                                              ColorEncoding::sRGB),
M
Matt Pharr 已提交
896 897 898
                                        ImageMetadata()};
            case 4: {
                Image image(std::move(pixels), {x, y}, {"R", "G", "B", "A"},
899
                            ColorEncoding::sRGB);
M
Matt Pharr 已提交
900 901 902 903 904 905 906 907 908 909 910 911
                return ImageAndMetadata{
                    image.SelectChannels(image.GetChannelDesc({"R", "G", "B"})),
                    ImageMetadata()};
            }
            default:
                ErrorExit("%s: %d channel image unsupported.", name, n);
            }
        } else
            ErrorExit("%s: no support for reading images with this extension", name);
    }
}

912
bool Image::Write(std::string name, const ImageMetadata &metadata) const {
M
Matt Pharr 已提交
913 914 915 916 917 918
    if (metadata.pixelBounds)
        CHECK_EQ(metadata.pixelBounds->Area(), resolution.x * resolution.y);

    if (HasExtension(name, "exr"))
        return WriteEXR(name, metadata);

919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936
    if (NChannels() > 4) {
        Error("%s: unable to write an %d channel image in this format.", name,
              NChannels());
        return false;
    }

    const Image *image = this;
    Image rgbImage;
    if (NChannels() == 4) {
        ImageChannelDesc desc = GetChannelDesc({"R", "G", "B", "A"});
        if (desc) {
            rgbImage = SelectChannels(GetChannelDesc({"R", "G", "B"}));
            image = &rgbImage;
        } else {
            Error("%s: unable to write an 4 channel image that is not RGBA.", name);
            return false;
        }
    }
M
Matt Pharr 已提交
937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973
    if (NChannels() == 3 && *metadata.GetColorSpace() != *RGBColorSpace::sRGB)
        Warning("%s: writing image with non-sRGB color space to a format that "
                "doesn't store color spaces.",
                name);

    if (NChannels() == 3) {
        // Order as RGB
        ImageChannelDesc desc = GetChannelDesc({"R", "G", "B"});
        if (!desc)
            Warning("%s: 3-channels but doesn't have R, G, and B. "
                    "Image may be garbled.",
                    name);
        else {
            rgbImage = SelectChannels(desc);
            image = &rgbImage;
        }
    }

    if (HasExtension(name, "pfm"))
        return image->WritePFM(name, metadata);
    else if (HasExtension(name, "png"))
        return image->WritePNG(name, metadata);
    else {
        Error("%s: no support for writing images with this extension", name);
        return false;
    }
}

///////////////////////////////////////////////////////////////////////////
// OpenEXR

static Imf::FrameBuffer imageToFrameBuffer(const Image &image,
                                           const ImageChannelDesc &desc,
                                           const Imath::Box2i &dataWindow) {
    size_t xStride = image.NChannels() * TexelBytes(image.Format());
    size_t yStride = image.Resolution().x * xStride;
    // Would be nice to use PixelOffset(-dw.min.x, -dw.min.y) but
L
luz paz 已提交
974
    // it checks to make sure the coordinates are >= 0 (which
M
Matt Pharr 已提交
975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
    // usually makes sense...)
    char *originPtr = (((char *)image.RawPointer({0, 0})) - dataWindow.min.x * xStride -
                       dataWindow.min.y * yStride);

    Imf::FrameBuffer fb;
    std::vector<std::string> channelNames = image.ChannelNames();
    switch (image.Format()) {
    case PixelFormat::Half:
        for (int channelIndex : desc.offset)
            fb.insert(channelNames[channelIndex],
                      Imf::Slice(Imf::HALF, originPtr + channelIndex * sizeof(Half),
                                 xStride, yStride));
        break;
    case PixelFormat::Float:
        for (int channelIndex : desc.offset)
            fb.insert(channelNames[channelIndex],
                      Imf::Slice(Imf::FLOAT, originPtr + channelIndex * sizeof(float),
                                 xStride, yStride));
        break;
    default:
        LOG_FATAL("Unexpected image format");
    }
    return fb;
}

static ImageAndMetadata ReadEXR(const std::string &name, Allocator alloc) {
    try {
        Imf::InputFile file(name.c_str());
        Imath::Box2i dw = file.header().dataWindow();

        ImageMetadata metadata;
        const Imf::FloatAttribute *renderTimeAttrib =
            file.header().findTypedAttribute<Imf::FloatAttribute>("renderTimeSeconds");
M
Matt Pharr 已提交
1008
        if (renderTimeAttrib)
M
Matt Pharr 已提交
1009 1010 1011 1012
            metadata.renderTimeSeconds = renderTimeAttrib->value();

        const Imf::M44fAttribute *worldToCameraAttrib =
            file.header().findTypedAttribute<Imf::M44fAttribute>("worldToCamera");
M
Matt Pharr 已提交
1013
        if (worldToCameraAttrib) {
M
Matt Pharr 已提交
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
            SquareMatrix<4> m;
            for (int i = 0; i < 4; ++i)
                for (int j = 0; j < 4; ++j)
                    // Can't memcpy since Float may be a double...
                    m[i][j] = worldToCameraAttrib->value().getValue()[4 * i + j];
            metadata.cameraFromWorld = m;
        }

        const Imf::M44fAttribute *worldToNDCAttrib =
            file.header().findTypedAttribute<Imf::M44fAttribute>("worldToNDC");
M
Matt Pharr 已提交
1024
        if (worldToNDCAttrib) {
M
Matt Pharr 已提交
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
            SquareMatrix<4> m;
            for (int i = 0; i < 4; ++i)
                for (int j = 0; j < 4; ++j)
                    m[i][j] = worldToNDCAttrib->value().getValue()[4 * i + j];
            metadata.NDCFromWorld = m;
        }

        // OpenEXR uses inclusive pixel bounds; adjust to non-inclusive
        // (the convention pbrt uses) in the values returned.
        metadata.pixelBounds = {{dw.min.x, dw.min.y}, {dw.max.x + 1, dw.max.y + 1}};

        Imath::Box2i dispw = file.header().displayWindow();
        metadata.fullResolution =
            Point2i(dispw.max.x - dispw.min.x + 1, dispw.max.y - dispw.min.y + 1);

        const Imf::IntAttribute *sppAttrib =
            file.header().findTypedAttribute<Imf::IntAttribute>("samplesPerPixel");
M
Matt Pharr 已提交
1042
        if (sppAttrib)
M
Matt Pharr 已提交
1043 1044 1045 1046
            metadata.samplesPerPixel = sppAttrib->value();

        const Imf::FloatAttribute *mseAttrib =
            file.header().findTypedAttribute<Imf::FloatAttribute>("MSE");
M
Matt Pharr 已提交
1047
        if (mseAttrib)
M
Matt Pharr 已提交
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
            metadata.MSE = mseAttrib->value();

        // Find any string vector attributes
        for (auto iter = file.header().begin(); iter != file.header().end(); ++iter) {
            if (strcmp(iter.attribute().typeName(), "stringvector") == 0) {
                Imf::StringVectorAttribute &sv =
                    (Imf::StringVectorAttribute &)iter.attribute();
                metadata.stringVectors[iter.name()] = sv.value();
            }
        }

        // Figure out the color space
        const RGBColorSpace *colorSpace = RGBColorSpace::sRGB;  // default
        const Imf::ChromaticitiesAttribute *chromaticitiesAttrib =
            file.header().findTypedAttribute<Imf::ChromaticitiesAttribute>(
                "chromaticities");
M
Matt Pharr 已提交
1064
        if (chromaticitiesAttrib) {
M
Matt Pharr 已提交
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
            Imf::Chromaticities c = chromaticitiesAttrib->value();
            const RGBColorSpace *cs = RGBColorSpace::Lookup(
                Point2f(c.red.x, c.red.y), Point2f(c.green.x, c.green.y),
                Point2f(c.blue.x, c.blue.y), Point2f(c.white.x, c.white.y));
            if (!cs) {
                Warning("Couldn't find supported color space that matches "
                        "chromaticities: "
                        "r (%f, %f) g (%f, %f) b (%f, %f), w (%f, %f). Using sRGB.",
                        c.red.x, c.red.y, c.green.x, c.green.y, c.blue.x, c.blue.y,
                        c.white.x, c.white.y);
                metadata.colorSpace = RGBColorSpace::sRGB;
            } else
                metadata.colorSpace = cs;
        }

        int width = dw.max.x - dw.min.x + 1;
        int height = dw.max.y - dw.min.y + 1;

        std::vector<std::string> channelNames;
        int nChannels = 0;
        Imf::PixelType pixelType;
        const Imf::ChannelList &channels = file.header().channels();
        for (auto iter = channels.begin(); iter != channels.end(); ++iter) {
            if (nChannels++ == 0)
                pixelType = iter.channel().type;
            else {
                // TODO: someday handle mixed types but seems like a
                // bother...
                if (pixelType != iter.channel().type)
                    LOG_FATAL("ReadEXR() doesn't currently support images with "
                              "multiple channel types.");
            }
            channelNames.push_back(iter.name());
        }

        CHECK(pixelType == Imf::HALF || pixelType == Imf::FLOAT);
        Image image(pixelType == Imf::HALF ? PixelFormat::Half : PixelFormat::Float,
                    {width, height}, channelNames, nullptr, alloc);
        file.setFrameBuffer(imageToFrameBuffer(image, image.AllChannelsDesc(), dw));
        file.readPixels(dw.min.y, dw.max.y);

        LOG_VERBOSE("Read EXR image %s (%d x %d)", name, width, height);
        return ImageAndMetadata{std::move(image), metadata};
    } catch (const std::exception &e) {
        ErrorExit("Unable to read image file \"%s\": %s", name, e.what());
    }

    return {};
}

bool Image::WriteEXR(const std::string &name, const ImageMetadata &metadata) const {
    if (Is8Bit(format))
        return ConvertToFormat(PixelFormat::Half).WriteEXR(name, metadata);
    CHECK(Is16Bit(format) || Is32Bit(format));

    try {
        Imath::Box2i displayWindow, dataWindow;
        if (metadata.fullResolution)
            // Agan, -1 offsets to handle inclusive indexing in OpenEXR...
            displayWindow = {Imath::V2i(0, 0),
                             Imath::V2i(metadata.fullResolution->x - 1,
                                        metadata.fullResolution->y - 1)};
        else
            displayWindow = {Imath::V2i(0, 0),
                             Imath::V2i(resolution.x - 1, resolution.y - 1)};

        if (metadata.pixelBounds)
            dataWindow = {
                Imath::V2i(metadata.pixelBounds->pMin.x, metadata.pixelBounds->pMin.y),
                Imath::V2i(metadata.pixelBounds->pMax.x - 1,
                           metadata.pixelBounds->pMax.y - 1)};
        else
            dataWindow = {Imath::V2i(0, 0),
                          Imath::V2i(resolution.x - 1, resolution.y - 1)};

        Imf::FrameBuffer fb = imageToFrameBuffer(*this, AllChannelsDesc(), dataWindow);

        Imf::Header header(displayWindow, dataWindow);
        for (auto iter = fb.begin(); iter != fb.end(); ++iter)
            header.channels().insert(iter.name(), iter.slice().type);

        if (metadata.renderTimeSeconds)
            header.insert("renderTimeSeconds",
                          Imf::FloatAttribute(*metadata.renderTimeSeconds));
        if (metadata.cameraFromWorld) {
            float m[4][4];
            for (int i = 0; i < 4; ++i)
                for (int j = 0; j < 4; ++j)
                    m[i][j] = (*metadata.cameraFromWorld)[i][j];
            header.insert("worldToCamera", Imf::M44fAttribute(m));
        }
        if (metadata.NDCFromWorld) {
            float m[4][4];
            for (int i = 0; i < 4; ++i)
                for (int j = 0; j < 4; ++j)
                    m[i][j] = (*metadata.NDCFromWorld)[i][j];
            header.insert("worldToNDC", Imf::M44fAttribute(m));
        }
        if (metadata.samplesPerPixel)
            header.insert("samplesPerPixel",
                          Imf::IntAttribute(*metadata.samplesPerPixel));
        if (metadata.MSE)
            header.insert("MSE", Imf::FloatAttribute(*metadata.MSE));
        for (const auto &iter : metadata.stringVectors)
            header.insert(iter.first, Imf::StringVectorAttribute(iter.second));

        // The OpenEXR spec says that the default is sRGB if no
        // chromaticities are provided.  It should be innocuous to write
        // the sRGB primaries anyway, but for completely indecipherable
        // reasons, OSX's Preview.app decides to gamma correct the pixels
        // in EXR files if it finds primaries.  So, we don't write them in
        // that case in the interests of nicer looking images on the
        // screen.
        if (*metadata.GetColorSpace() != *RGBColorSpace::sRGB) {
            const RGBColorSpace &cs = *metadata.GetColorSpace();
            Imf::Chromaticities chromaticities(
                Imath::V2f(cs.r.x, cs.r.y), Imath::V2f(cs.g.x, cs.g.y),
                Imath::V2f(cs.b.x, cs.b.y), Imath::V2f(cs.w.x, cs.w.y));
            header.insert("chromaticities", Imf::ChromaticitiesAttribute(chromaticities));
        }

        Imf::OutputFile file(name.c_str(), header);
        file.setFrameBuffer(fb);
        file.writePixels(resolution.y);
    } catch (const std::exception &exc) {
        Error("%s: error writing EXR: %s", name.c_str(), exc.what());
        return false;
    }

    return true;
}

///////////////////////////////////////////////////////////////////////////
// PNG Function Definitions

static ImageAndMetadata ReadPNG(const std::string &name, Allocator alloc,
1201
                                ColorEncoding encoding) {
M
Matt Pharr 已提交
1202 1203
    std::string contents = ReadFileContents(name);

M
Matt Pharr 已提交
1204
    if (!encoding)
1205
        encoding = ColorEncoding::sRGB;
M
Matt Pharr 已提交
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236

    unsigned width, height;
    LodePNGState state;
    lodepng_state_init(&state);
    unsigned int error = lodepng_inspect(
        &width, &height, &state, (const unsigned char *)contents.data(), contents.size());
    if (error != 0)
        ErrorExit("%s: %s", name, lodepng_error_text(error));

    Image image(alloc);
    switch (state.info_png.color.colortype) {
    case LCT_GREY:
    case LCT_GREY_ALPHA: {
        std::vector<unsigned char> buf;
        int bpp = state.info_png.color.bitdepth == 16 ? 16 : 8;
        error =
            lodepng::decode(buf, width, height, (const unsigned char *)contents.data(),
                            contents.size(), LCT_GREY, bpp);
        if (error != 0)
            ErrorExit("%s: %s", name, lodepng_error_text(error));

        if (state.info_png.color.bitdepth == 16) {
            image = Image(PixelFormat::Half, Point2i(width, height), {"Y"});
            auto bufIter = buf.begin();
            for (unsigned int y = 0; y < height; ++y)
                for (unsigned int x = 0; x < width; ++x, bufIter += 2) {
                    // Convert from little endian.
                    Float v = (((int)bufIter[0] << 8) + (int)bufIter[1]) / 65535.f;
                    v = encoding.ToFloatLinear(v);
                    image.SetChannel(Point2i(x, y), 0, v);
                }
M
Matt Pharr 已提交
1237
            DCHECK(bufIter == buf.end());
M
Matt Pharr 已提交
1238 1239 1240 1241 1242 1243 1244 1245 1246
        } else {
            image = Image(PixelFormat::U256, Point2i(width, height), {"Y"}, encoding);
            std::copy(buf.begin(), buf.end(), (uint8_t *)image.RawPointer({0, 0}));
        }
        return ImageAndMetadata{image, ImageMetadata()};
    }
    default: {
        std::vector<unsigned char> buf;
        int bpp = state.info_png.color.bitdepth == 16 ? 16 : 8;
1247
        bool hasAlpha = (state.info_png.color.colortype == LCT_RGBA);
L
luz paz 已提交
1248
        // Force RGB if it's paletted or whatever.
M
Matt Pharr 已提交
1249 1250
        error =
            lodepng::decode(buf, width, height, (const unsigned char *)contents.data(),
1251
                            contents.size(), hasAlpha ? LCT_RGBA : LCT_RGB, bpp);
M
Matt Pharr 已提交
1252 1253 1254 1255 1256 1257
        if (error != 0)
            ErrorExit("%s: %s", name, lodepng_error_text(error));

        ImageMetadata metadata;
        metadata.colorSpace = RGBColorSpace::sRGB;
        if (state.info_png.color.bitdepth == 16) {
1258 1259 1260 1261 1262 1263
            if (hasAlpha) {
                image = Image(PixelFormat::Half, Point2i(width, height),
                              {"R", "G", "B", "A"});
                auto bufIter = buf.begin();
                for (unsigned int y = 0; y < height; ++y)
                    for (unsigned int x = 0; x < width; ++x, bufIter += 8) {
M
Matt Pharr 已提交
1264
                        DCHECK(bufIter < buf.end());
1265 1266 1267 1268 1269 1270 1271 1272 1273 1274
                        // Convert from little endian.
                        Float rgba[4] = {
                            (((int)bufIter[0] << 8) + (int)bufIter[1]) / 65535.f,
                            (((int)bufIter[2] << 8) + (int)bufIter[3]) / 65535.f,
                            (((int)bufIter[4] << 8) + (int)bufIter[5]) / 65535.f,
                            (((int)bufIter[6] << 8) + (int)bufIter[7]) / 65535.f};
                        for (int c = 0; c < 4; ++c) {
                            rgba[c] = encoding.ToFloatLinear(rgba[c]);
                            image.SetChannel(Point2i(x, y), c, rgba[c]);
                        }
M
Matt Pharr 已提交
1275
                    }
M
Matt Pharr 已提交
1276
                DCHECK(bufIter == buf.end());
1277 1278 1279 1280 1281
            } else {
                image = Image(PixelFormat::Half, Point2i(width, height), {"R", "G", "B"});
                auto bufIter = buf.begin();
                for (unsigned int y = 0; y < height; ++y)
                    for (unsigned int x = 0; x < width; ++x, bufIter += 6) {
M
Matt Pharr 已提交
1282
                        DCHECK(bufIter < buf.end());
1283 1284 1285 1286 1287 1288 1289 1290 1291 1292
                        // Convert from little endian.
                        Float rgb[3] = {
                            (((int)bufIter[0] << 8) + (int)bufIter[1]) / 65535.f,
                            (((int)bufIter[2] << 8) + (int)bufIter[3]) / 65535.f,
                            (((int)bufIter[4] << 8) + (int)bufIter[5]) / 65535.f};
                        for (int c = 0; c < 3; ++c) {
                            rgb[c] = encoding.ToFloatLinear(rgb[c]);
                            image.SetChannel(Point2i(x, y), c, rgb[c]);
                        }
                    }
M
Matt Pharr 已提交
1293
                DCHECK(bufIter == buf.end());
1294 1295 1296 1297 1298
            }
        } else if (hasAlpha) {
            image = Image(PixelFormat::U256, Point2i(width, height), {"R", "G", "B", "A"},
                          encoding);
            std::copy(buf.begin(), buf.end(), (uint8_t *)image.RawPointer({0, 0}));
M
Matt Pharr 已提交
1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
        } else {
            image = Image(PixelFormat::U256, Point2i(width, height), {"R", "G", "B"},
                          encoding);
            std::copy(buf.begin(), buf.end(), (uint8_t *)image.RawPointer({0, 0}));
        }
        return ImageAndMetadata{image, metadata};
    }
    }
}

Image Image::SelectChannels(const ImageChannelDesc &desc, Allocator alloc) const {
    std::vector<std::string> descChannelNames;
    // TODO: descChannelNames = ChannelNames(desc)
    for (size_t i = 0; i < desc.offset.size(); ++i)
        descChannelNames.push_back(channelNames[desc.offset[i]]);

    Image image(format, resolution, descChannelNames, encoding, alloc);
1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343
    switch (format) {
    case PixelFormat::U256:
        for (int y = 0; y < resolution.y; ++y)
            for (int x = 0; x < resolution.x; ++x) {
                const uint8_t *src = (const uint8_t *)RawPointer({x, y});
                uint8_t *dst = (uint8_t *)image.RawPointer({x, y});
                for (size_t i = 0; i < desc.offset.size(); ++i)
                    dst[i] = src[desc.offset[i]];
            }
        break;
    case PixelFormat::Half:
        for (int y = 0; y < resolution.y; ++y)
            for (int x = 0; x < resolution.x; ++x) {
                const Half *src = (const Half *)RawPointer({x, y});
                Half *dst = (Half *)image.RawPointer({x, y});
                for (size_t i = 0; i < desc.offset.size(); ++i)
                    dst[i] = src[desc.offset[i]];
            }
        break;
    case PixelFormat::Float:
        for (int y = 0; y < resolution.y; ++y)
            for (int x = 0; x < resolution.x; ++x) {
                const float *src = (const float *)RawPointer({x, y});
                float *dst = (float *)image.RawPointer({x, y});
                for (size_t i = 0; i < desc.offset.size(); ++i)
                    dst[i] = src[desc.offset[i]];
            }
        break;
1344 1345
    default:
        LOG_FATAL("Unhandled PixelFormat");
1346
    }
1347

M
Matt Pharr 已提交
1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368
    return image;
}

Image Image::Crop(const Bounds2i &bounds, Allocator alloc) const {
    CHECK_GT(bounds.Area(), 0);
    CHECK(bounds.pMin.x >= 0 && bounds.pMin.y >= 0);
    Image image(format, Point2i(bounds.pMax - bounds.pMin), channelNames, encoding,
                alloc);
    for (Point2i p : bounds)
        for (int c = 0; c < NChannels(); ++c)
            image.SetChannel(Point2i(p - bounds.pMin), c, GetChannel(p, c));
    return image;
}

std::string Image::ToString() const {
    return StringPrintf("[ Image format: %s resolution: %s channelNames: %s "
                        "encoding: %s ]",
                        format, resolution, channelNames,
                        encoding ? encoding.ToString().c_str() : "(nullptr)");
}

1369
bool Image::WritePNG(const std::string &filename, const ImageMetadata &metadata) const {
M
Matt Pharr 已提交
1370 1371 1372
    unsigned int error = 0;
    int nOutOfGamut = 0;

1373 1374 1375
    unsigned char *png;
    size_t pngSize;

M
Matt Pharr 已提交
1376 1377
    if (format == PixelFormat::U256) {
        if (NChannels() == 1)
1378 1379
            error = lodepng_encode_memory(&png, &pngSize, p8.data(), resolution.x,
                                          resolution.y, LCT_GREY, 8 /* bitdepth */);
M
Matt Pharr 已提交
1380 1381 1382
        else if (NChannels() == 3)
            // TODO: it would be nice to store the color encoding used in the
            // PNG metadata...
1383 1384
            error = lodepng_encode_memory(&png, &pngSize, p8.data(), resolution.x,
                                          resolution.y, LCT_RGB, 8);
M
Matt Pharr 已提交
1385 1386 1387 1388 1389 1390 1391 1392 1393 1394
        else
            LOG_FATAL("Unhandled channel count in WritePNG(): %d", NChannels());
    } else if (NChannels() == 3) {
        // It may not actually be RGB, but that's what PNG's going to
        // assume..
        std::unique_ptr<uint8_t[]> rgb8 =
            std::make_unique<uint8_t[]>(3 * resolution.x * resolution.y);
        for (int y = 0; y < resolution.y; ++y)
            for (int x = 0; x < resolution.x; ++x)
                for (int c = 0; c < 3; ++c) {
M
Matt Pharr 已提交
1395
                    Float dither = -.5f + BlueNoise(c, {x, y});
M
Matt Pharr 已提交
1396 1397 1398 1399 1400 1401
                    Float v = GetChannel({x, y}, c);
                    if (v < 0 || v > 1)
                        ++nOutOfGamut;
                    rgb8[3 * (y * resolution.x + x) + c] = LinearToSRGB8(v, dither);
                }

1402 1403
        error = lodepng_encode_memory(&png, &pngSize, rgb8.get(), resolution.x,
                                      resolution.y, LCT_RGB, 8);
M
Matt Pharr 已提交
1404 1405 1406 1407 1408
    } else if (NChannels() == 1) {
        std::unique_ptr<uint8_t[]> y8 =
            std::make_unique<uint8_t[]>(resolution.x * resolution.y);
        for (int y = 0; y < resolution.y; ++y)
            for (int x = 0; x < resolution.x; ++x) {
M
Matt Pharr 已提交
1409
                Float dither = -.5f + BlueNoise(0, {x, y});
M
Matt Pharr 已提交
1410 1411 1412 1413 1414 1415
                Float v = GetChannel({x, y}, 0);
                if (v < 0 || v > 1)
                    ++nOutOfGamut;
                y8[y * resolution.x + x] = LinearToSRGB8(v, dither);
            }

1416 1417
        error = lodepng_encode_memory(&png, &pngSize, y8.get(), resolution.x,
                                      resolution.y, LCT_GREY, 8 /* bitdepth */);
M
Matt Pharr 已提交
1418 1419 1420
    }

    if (nOutOfGamut > 0)
1421
        Warning("%s: %d out of gamut pixel channels clamped to [0,1].", filename,
M
Matt Pharr 已提交
1422 1423
                nOutOfGamut);

1424 1425 1426 1427 1428 1429 1430 1431 1432 1433
    if (error == 0) {
        std::string encodedPNG(png, png + pngSize);
        if (!WriteFileContents(filename, encodedPNG))
            Error("%s: error writing PNG.", filename);
    } else
        Error("%s: %s", filename, lodepng_error_text(error));

    free(png);

    return error == 0;
M
Matt Pharr 已提交
1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508
}

///////////////////////////////////////////////////////////////////////////
// PFM Function Definitions

/*
 * PFM reader/writer code courtesy Jiawen "Kevin" Chen
 * (http://people.csail.mit.edu/jiawen/)
 */

static constexpr bool hostLittleEndian =
#if defined(__BYTE_ORDER__)
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
    true
#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
    false
#else
#error "__BYTE_ORDER__ defined but has unexpected value"
#endif
#else
#if defined(__LITTLE_ENDIAN__) || defined(__i386__) || defined(__x86_64__) || \
    defined(_WIN32) || defined(WIN32)
    true
#elif defined(__BIG_ENDIAN__)
    false
#elif defined(__sparc) || defined(__sparc__)
    false
#else
#error "Can't detect machine endian-ness at compile-time."
#endif
#endif
    ;

#define BUFFER_SIZE 80

static inline int isWhitespace(char c) {
    return static_cast<int>(c == ' ' || c == '\n' || c == '\t');
}

// Reads a "word" from the fp and puts it into buffer and adds a null
// terminator.  i.e. it keeps reading until whitespace is reached.  Returns
// the number of characters read *not* including the whitespace, and
// returns -1 on an error.
static int readWord(FILE *fp, char *buffer, int bufferLength) {
    int n;
    int c;

    if (bufferLength < 1)
        return -1;

    n = 0;
    c = fgetc(fp);
    while (c != EOF && (isWhitespace(c) == 0) && n < bufferLength) {
        buffer[n] = c;
        ++n;
        c = fgetc(fp);
    }

    if (n < bufferLength) {
        buffer[n] = '\0';
        return n;
    }

    return -1;
}

static ImageAndMetadata ReadPFM(const std::string &filename, Allocator alloc) {
    pstd::vector<float> rgb32(alloc);
    char buffer[BUFFER_SIZE];
    unsigned int nFloats;
    int nChannels, width, height;
    float scale;
    bool fileLittleEndian;
    ImageMetadata metadata;

M
Matt Pharr 已提交
1509
    FILE *fp = FOpenRead(filename);
M
Matt Pharr 已提交
1510
    if (!fp)
M
Matt Pharr 已提交
1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577
        ErrorExit("%s: unable to open PFM file", filename);

    // read either "Pf" or "PF"
    if (readWord(fp, buffer, BUFFER_SIZE) == -1)
        ErrorExit("%s: unable to read PFM file", filename);

    if (strcmp(buffer, "Pf") == 0)
        nChannels = 1;
    else if (strcmp(buffer, "PF") == 0)
        nChannels = 3;
    else
        ErrorExit("%s: unable to decode PFM file type \"%c%c\"", filename, buffer[0],
                  buffer[1]);

    // read the rest of the header
    // read width
    if (readWord(fp, buffer, BUFFER_SIZE) == -1)
        goto fail;
    if (!Atoi(buffer, &width))
        ErrorExit("%s: unable to decode width \"%s\"", filename, buffer);

    // read height
    if (readWord(fp, buffer, BUFFER_SIZE) == -1)
        goto fail;
    if (!Atoi(buffer, &height))
        ErrorExit("%s: unable to decode height \"%s\"", filename, buffer);

    // read scale
    if (readWord(fp, buffer, BUFFER_SIZE) == -1)
        goto fail;
    if (!Atof(buffer, &scale))
        ErrorExit("%s: unable to decode scale \"%s\"", filename, buffer);

    // read the data
    nFloats = nChannels * width * height;
    rgb32.resize(nFloats);
    for (int y = height - 1; y >= 0; --y)
        if (fread(&rgb32[nChannels * y * width], sizeof(float), nChannels * width, fp) !=
            nChannels * width)
            goto fail;

    // apply endian conversian and scale if appropriate
    fileLittleEndian = (scale < 0.f);
    if (hostLittleEndian ^ fileLittleEndian) {
        uint8_t bytes[4];
        for (unsigned int i = 0; i < nFloats; ++i) {
            memcpy(bytes, &rgb32[i], 4);
            pstd::swap(bytes[0], bytes[3]);
            pstd::swap(bytes[1], bytes[2]);
            memcpy(&rgb32[i], bytes, 4);
        }
    }
    if (std::abs(scale) != 1.f)
        for (unsigned int i = 0; i < nFloats; ++i)
            rgb32[i] *= std::abs(scale);

    fclose(fp);
    LOG_VERBOSE("Read PFM image %s (%d x %d)", filename, width, height);
    metadata.colorSpace = RGBColorSpace::sRGB;
    if (nChannels == 1)
        return ImageAndMetadata{Image(std::move(rgb32), {width, height}, {"Y"}),
                                metadata};
    else
        return ImageAndMetadata{Image(std::move(rgb32), {width, height}, {"R", "G", "B"}),
                                metadata};

fail:
M
Matt Pharr 已提交
1578
    if (fp)
M
Matt Pharr 已提交
1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613
        fclose(fp);
    ErrorExit("%s: premature end of file in PFM file", filename);
}

static ImageAndMetadata ReadHDR(const std::string &filename, Allocator alloc) {
    int x, y, n;
    float *data = stbi_loadf(filename.c_str(), &x, &y, &n, 0);
    if (!data)
        ErrorExit("%s: %s", filename, stbi_failure_reason());

    pstd::vector<float> pixels(data, data + x * y * n, alloc);
    stbi_image_free(data);

    switch (n) {
    case 1:
        return ImageAndMetadata{Image(std::move(pixels), {x, y}, {"Y"}), ImageMetadata()};
    case 2: {
        Image image(std::move(pixels), {x, y}, {"Y", "A"});
        return ImageAndMetadata{image.SelectChannels(image.GetChannelDesc({"Y"})),
                                ImageMetadata()};
    }
    case 3:
        return ImageAndMetadata{Image(std::move(pixels), {x, y}, {"R", "G", "B"}),
                                ImageMetadata()};
    case 4: {
        Image image(std::move(pixels), {x, y}, {"R", "G", "B", "A"});
        return ImageAndMetadata{
            image.SelectChannels(image.GetChannelDesc({"R", "G", "B"})), ImageMetadata()};
    }
    default:
        ErrorExit("%s: %d channel image unsupported.", filename, n);
    }
}

bool Image::WritePFM(const std::string &filename, const ImageMetadata &metadata) const {
M
Matt Pharr 已提交
1614
    FILE *fp = FOpenWrite(filename);
M
Matt Pharr 已提交
1615
    if (!fp) {
M
Matt Pharr 已提交
1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668
        Error("Unable to open output PFM file \"%s\"", filename);
        return false;
    }

    std::unique_ptr<float[]> scanline = std::make_unique<float[]>(3 * resolution.x);
    float scale;

    // only write 3 channel PFMs here...
    if (fprintf(fp, "PF\n") < 0)
        goto fail;

    // write the width and height, which must be positive
    if (fprintf(fp, "%d %d\n", resolution.x, resolution.y) < 0)
        goto fail;

    // write the scale, which encodes endianness
    scale = hostLittleEndian ? -1.f : 1.f;
    if (fprintf(fp, "%f\n", scale) < 0)
        goto fail;

    // write the data from bottom left to upper right as specified by
    // http://netpbm.sourceforge.net/doc/pfm.html
    // The raster is a sequence of pixels, packed one after another, with no
    // delimiters of any kind. They are grouped by row, with the pixels in each
    // row ordered left to right and the rows ordered bottom to top.
    for (int y = resolution.y - 1; y >= 0; y--) {
        for (int x = 0; x < resolution.x; ++x) {
            if (NChannels() == 1) {
                Float v = GetChannel({x, y}, 0);
                scanline[3 * x] = scanline[3 * x + 1] = scanline[3 * x + 2] = v;
            } else {
                CHECK_EQ(3, NChannels());
                for (int c = 0; c < 3; ++c)
                    // Assign element-wise in case Float is typedefed as
                    // 'double'.
                    scanline[3 * x + c] = GetChannel({x, y}, c);
            }
        }
        if (fwrite(&scanline[0], sizeof(float), 3 * resolution.x, fp) <
            (size_t)(3 * resolution.x))
            goto fail;
    }

    fclose(fp);
    return true;

fail:
    Error("Error writing PFM file \"%s\"", filename);
    fclose(fp);
    return false;
}

}  // namespace pbrt