integrator.cpp 29.1 KB
Newer Older
M
Matt Pharr 已提交
1 2 3 4
// 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

5
#include <pbrt/wavefront/integrator.h>
M
Matt Pharr 已提交
6 7 8 9 10

#include <pbrt/base/medium.h>
#include <pbrt/cameras.h>
#include <pbrt/film.h>
#include <pbrt/filters.h>
11 12 13
#ifdef PBRT_BUILD_GPU_RENDERER
#include <pbrt/gpu/aggregate.h>
#include <pbrt/gpu/memory.h>
14
#endif  // PBRT_BUILD_GPU_RENDERER
M
Matt Pharr 已提交
15 16 17 18 19 20 21 22 23 24 25
#include <pbrt/lights.h>
#include <pbrt/lightsamplers.h>
#include <pbrt/util/color.h>
#include <pbrt/util/colorspace.h>
#include <pbrt/util/display.h>
#include <pbrt/util/file.h>
#include <pbrt/util/image.h>
#include <pbrt/util/log.h>
#include <pbrt/util/print.h>
#include <pbrt/util/progressreporter.h>
#include <pbrt/util/pstd.h>
26
#include <pbrt/util/spectrum.h>
M
Matt Pharr 已提交
27
#include <pbrt/util/stats.h>
M
Matt Pharr 已提交
28
#include <pbrt/util/string.h>
M
Matt Pharr 已提交
29
#include <pbrt/util/taggedptr.h>
30
#include <pbrt/wavefront/aggregate.h>
M
Matt Pharr 已提交
31

32
#include <atomic>
M
Matt Pharr 已提交
33 34 35 36
#include <cstring>
#include <iostream>
#include <map>

37
#ifdef PBRT_BUILD_GPU_RENDERER
M
Matt Pharr 已提交
38 39
#include <cuda.h>
#include <cuda_runtime.h>
40
#endif  // PBRT_BUILD_GPU_RENDERER
M
Matt Pharr 已提交
41 42 43

namespace pbrt {

44
STAT_MEMORY_COUNTER("Memory/Wavefront integrator pixel state", pathIntegratorBytes);
M
Matt Pharr 已提交
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
static void updateMaterialNeeds(
    Material m, pstd::array<bool, Material::NumTags()> *haveBasicEvalMaterial,
    pstd::array<bool, Material::NumTags()> *haveUniversalEvalMaterial,
    bool *haveSubsurface) {
    if (!m)
        return;

    if (MixMaterial *mix = m.CastOrNullptr<MixMaterial>(); mix) {
        // This is a somewhat odd place for this check, but it's convenient...
        if (!m.CanEvaluateTextures(BasicTextureEvaluator()))
            ErrorExit("\"mix\" material has a texture that can't be evaluated with the "
                      "BasicTextureEvaluator, which is all that is currently supported "
                      "int the wavefront renderer--sorry! %s",
                      *mix);

        updateMaterialNeeds(mix->GetMaterial(0), haveBasicEvalMaterial,
                            haveUniversalEvalMaterial, haveSubsurface);
        updateMaterialNeeds(mix->GetMaterial(1), haveBasicEvalMaterial,
                            haveUniversalEvalMaterial, haveSubsurface);
        return;
    }

    *haveSubsurface |= m.HasSubsurfaceScattering();

    FloatTexture displace = m.GetDisplacement();
    if (m.CanEvaluateTextures(BasicTextureEvaluator()) &&
        (!displace || BasicTextureEvaluator().CanEvaluate({displace}, {})))
        (*haveBasicEvalMaterial)[m.Tag()] = true;
    else
        (*haveUniversalEvalMaterial)[m.Tag()] = true;
}
77

78 79
WavefrontPathIntegrator::WavefrontPathIntegrator(
    pstd::pmr::memory_resource *memoryResource, ParsedScene &scene)
80
    : memoryResource(memoryResource) {
81 82
    ThreadLocal<Allocator> threadAllocators([memoryResource]() {
        pstd::pmr::monotonic_buffer_resource *resource =
83
            new pstd::pmr::monotonic_buffer_resource(1024 * 1024, memoryResource);
84 85
        return Allocator(resource);
    });
86

87
    Allocator alloc = threadAllocators.Get();
88

M
Matt Pharr 已提交
89
    // Allocate all of the data structures that represent the scene...
90
    std::map<std::string, Medium> media = scene.CreateMedia();
M
Matt Pharr 已提交
91

92 93 94 95 96
    // "haveMedia" is a bit of a misnomer in that determines both whether
    // queues are allocated for the medium sampling kernels and they are
    // launched as well as whether the ray marching shadow ray kernel is
    // launched... Thus, it will be true if there actually are no media,
    // but some "interface" materials are present in the scene.
M
Matt Pharr 已提交
97 98 99 100 101 102 103 104
    haveMedia = false;
    // Check the shapes...
    for (const auto &shape : scene.shapes)
        if (!shape.insideMedium.empty() || !shape.outsideMedium.empty())
            haveMedia = true;
    for (const auto &shape : scene.animatedShapes)
        if (!shape.insideMedium.empty() || !shape.outsideMedium.empty())
            haveMedia = true;
105 106 107 108 109 110
    for (const auto &mtl : scene.materials)
        if (mtl.name == "interface")
            haveMedia = true;
    for (const auto &namedMtl : scene.namedMaterials)
        if (namedMtl.second.name == "interface")
            haveMedia = true;
M
Matt Pharr 已提交
111

112
    auto findMedium = [&](const std::string &s, const FileLoc *loc) -> Medium {
M
Matt Pharr 已提交
113 114 115 116 117 118 119 120 121 122
        if (s.empty())
            return nullptr;

        auto iter = media.find(s);
        if (iter == media.end())
            ErrorExit(loc, "%s: medium not defined", s);
        haveMedia = true;
        return iter->second;
    };

123 124
    filter = Filter::Create(scene.filter.name, scene.filter.parameters, &scene.filter.loc,
                            alloc);
M
Matt Pharr 已提交
125

126 127
    Float exposureTime = scene.camera.parameters.GetOneFloat("shutterclose", 1.f) -
                         scene.camera.parameters.GetOneFloat("shutteropen", 0.f);
128 129 130 131 132
    if (exposureTime <= 0)
        ErrorExit(&scene.camera.loc,
                  "The specified camera shutter times imply that the shutter "
                  "does not open.  A black image will result.");

133 134
    film = Film::Create(scene.film.name, scene.film.parameters, exposureTime,
                        scene.camera.cameraTransform, filter, &scene.film.loc, alloc);
M
Matt Pharr 已提交
135 136
    initializeVisibleSurface = film.UsesVisibleSurface();

137 138
    sampler = Sampler::Create(scene.sampler.name, scene.sampler.parameters,
                              film.FullResolution(), &scene.sampler.loc, alloc);
139
    samplesPerPixel = sampler.SamplesPerPixel();
M
Matt Pharr 已提交
140

141 142 143
    Medium cameraMedium = findMedium(scene.camera.medium, &scene.camera.loc);
    camera = Camera::Create(scene.camera.name, scene.camera.parameters, cameraMedium,
                            scene.camera.cameraTransform, film, &scene.camera.loc, alloc);
M
Matt Pharr 已提交
144

145 146
    // Textures
    LOG_VERBOSE("Starting to create textures");
147
    NamedTextures textures = scene.CreateTextures(threadAllocators, Options->useGPU);
148 149
    LOG_VERBOSE("Done creating textures");

150
    LOG_VERBOSE("Starting to create lights");
151
    pstd::vector<Light> allLights;
152
    std::map<int, pstd::vector<Light> *> shapeIndexToAreaLights;
153
    infiniteLights = alloc.new_object<pstd::vector<Light>>(alloc);
M
Matt Pharr 已提交
154

155
    for (Light l : scene.CreateLights(textures, &shapeIndexToAreaLights)) {
M
Matt Pharr 已提交
156
        if (l.Is<UniformInfiniteLight>() || l.Is<ImageInfiniteLight>() ||
157
            l.Is<PortalImageInfiniteLight>())
158
            infiniteLights->push_back(l);
M
Matt Pharr 已提交
159 160 161

        allLights.push_back(l);
    }
162
    LOG_VERBOSE("Done creating lights");
M
Matt Pharr 已提交
163

164 165 166
    LOG_VERBOSE("Starting to create materials");
    std::map<std::string, pbrt::Material> namedMaterials;
    std::vector<pbrt::Material> materials;
167
    scene.CreateMaterials(textures, threadAllocators, &namedMaterials, &materials);
168

M
Matt Pharr 已提交
169 170 171
    haveBasicEvalMaterial.fill(false);
    haveUniversalEvalMaterial.fill(false);
    haveSubsurface = false;
172 173 174 175 176 177 178 179
    for (Material m : materials)
        updateMaterialNeeds(m, &haveBasicEvalMaterial, &haveUniversalEvalMaterial,
                            &haveSubsurface);
    for (const auto &m : namedMaterials)
        updateMaterialNeeds(m.second, &haveBasicEvalMaterial, &haveUniversalEvalMaterial,
                            &haveSubsurface);
    LOG_VERBOSE("Finished creating materials");

180 181
    if (Options->useGPU) {
#ifdef PBRT_BUILD_GPU_RENDERER
182 183 184
        CUDATrackedMemoryResource *mr =
            dynamic_cast<CUDATrackedMemoryResource *>(memoryResource);
        CHECK(mr);
185 186
        aggregate = new OptiXAggregate(scene, mr, textures, shapeIndexToAreaLights, media,
                                       namedMaterials, materials);
187 188 189 190
#else
        LOG_FATAL("Options->useGPU was set without PBRT_BUILD_GPU_RENDERER enabled");
#endif
    } else
191 192
        aggregate = new CPUAggregate(scene, textures, shapeIndexToAreaLights, media,
                                     namedMaterials, materials);
M
Matt Pharr 已提交
193 194

    // Preprocess the light sources
195
    for (Light light : allLights)
196
        light.Preprocess(aggregate->Bounds());
M
Matt Pharr 已提交
197 198 199 200 201 202 203 204 205 206 207

    bool haveLights = !allLights.empty();
    for (const auto &m : media)
        haveLights |= m.second.IsEmissive();
    if (!haveLights)
        ErrorExit("No light sources specified");

    std::string lightSamplerName =
        scene.integrator.parameters.GetOneString("lightsampler", "bvh");
    if (allLights.size() == 1)
        lightSamplerName = "uniform";
208
    lightSampler = LightSampler::Create(lightSamplerName, allLights, alloc);
M
Matt Pharr 已提交
209

210
    if (scene.integrator.name != "path" && scene.integrator.name != "volpath")
211
        Warning(&scene.integrator.loc,
212
                "Ignoring specified integrator \"%s\": the wavefront integrator "
213 214
                "always uses a \"volpath\" integrator.",
                scene.integrator.name);
215

M
Matt Pharr 已提交
216 217 218 219
    // Integrator parameters
    regularize = scene.integrator.parameters.GetOneBool("regularize", false);
    maxDepth = scene.integrator.parameters.GetOneInt("maxdepth", 5);

220 221
    // Warn about unsupported stuff...
    if (Options->forceDiffuse)
222
        Warning("The wavefront integrator does not support --force-diffuse.");
223
    if (Options->writePartialImages)
224
        Warning("The wavefront integrator does not support --write-partial-images.");
225
    if (Options->recordPixelStatistics)
226
        Warning("The wavefront integrator does not support --pixelstats.");
227
    if (!Options->mseReferenceImage.empty())
228
        Warning("The wavefront integrator does not support --mse-reference-image.");
229
    if (!Options->mseReferenceOutput.empty())
230
        Warning("The wavefront integrator does not support --mse-reference-out.");
231

232 233
        ///////////////////////////////////////////////////////////////////////////
        // Allocate storage for all of the queues/buffers...
M
Matt Pharr 已提交
234

235
#ifdef PBRT_BUILD_GPU_RENDERER
M
Matt Pharr 已提交
236
    CUDATrackedMemoryResource *mr =
237
        dynamic_cast<CUDATrackedMemoryResource *>(memoryResource);
M
Matt Pharr 已提交
238
    CHECK(mr);
M
Matt Pharr 已提交
239
    size_t startSize = mr->BytesAllocated();
240
#endif  // PBRT_BUILD_GPU_RENDERER
M
Matt Pharr 已提交
241

242
    // Compute number of scanlines to render per pass
M
Matt Pharr 已提交
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
    Vector2i resolution = film.PixelBounds().Diagonal();
    // TODO: make this configurable. Base it on the amount of GPU memory?
    int maxSamples = 1024 * 1024;
    scanlinesPerPass = std::max(1, maxSamples / resolution.x);
    int nPasses = (resolution.y + scanlinesPerPass - 1) / scanlinesPerPass;
    scanlinesPerPass = (resolution.y + nPasses - 1) / nPasses;
    maxQueueSize = resolution.x * scanlinesPerPass;
    LOG_VERBOSE("Will render in %d passes %d scanlines per pass\n", nPasses,
                scanlinesPerPass);

    pixelSampleState = SOA<PixelSampleState>(maxQueueSize, alloc);

    rayQueues[0] = alloc.new_object<RayQueue>(maxQueueSize, alloc);
    rayQueues[1] = alloc.new_object<RayQueue>(maxQueueSize, alloc);

    shadowRayQueue = alloc.new_object<ShadowRayQueue>(maxQueueSize, alloc);

    if (haveSubsurface) {
        bssrdfEvalQueue =
            alloc.new_object<GetBSSRDFAndProbeRayQueue>(maxQueueSize, alloc);
        subsurfaceScatterQueue =
            alloc.new_object<SubsurfaceScatterQueue>(maxQueueSize, alloc);
    }

267
    if (infiniteLights->size())
M
Matt Pharr 已提交
268 269 270 271 272 273 274 275 276 277 278 279 280
        escapedRayQueue = alloc.new_object<EscapedRayQueue>(maxQueueSize, alloc);
    hitAreaLightQueue = alloc.new_object<HitAreaLightQueue>(maxQueueSize, alloc);

    basicEvalMaterialQueue = alloc.new_object<MaterialEvalQueue>(
        maxQueueSize, alloc,
        pstd::MakeConstSpan(&haveBasicEvalMaterial[1], haveBasicEvalMaterial.size() - 1));
    universalEvalMaterialQueue = alloc.new_object<MaterialEvalQueue>(
        maxQueueSize, alloc,
        pstd::MakeConstSpan(&haveUniversalEvalMaterial[1],
                            haveUniversalEvalMaterial.size() - 1));

    if (haveMedia) {
        mediumSampleQueue = alloc.new_object<MediumSampleQueue>(maxQueueSize, alloc);
281 282 283 284 285 286 287 288

        // TODO: in the presence of multiple PhaseFunction implementations,
        // it could be worthwhile to see which are present in the scene and
        // then initialize havePhase accordingly...
        pstd::array<bool, PhaseFunction::NumTags()> havePhase;
        havePhase.fill(true);
        mediumScatterQueue =
            alloc.new_object<MediumScatterQueue>(maxQueueSize, alloc, havePhase);
M
Matt Pharr 已提交
289 290 291 292
    }

    stats = alloc.new_object<Stats>(maxDepth, alloc);

293
#ifdef PBRT_BUILD_GPU_RENDERER
M
Matt Pharr 已提交
294 295
    size_t endSize = mr->BytesAllocated();
    pathIntegratorBytes += endSize - startSize;
296
#endif  // PBRT_BUILD_GPU_RENDERER
M
Matt Pharr 已提交
297 298
}

299 300
// WavefrontPathIntegrator Method Definitions
Float WavefrontPathIntegrator::Render() {
301 302 303
    Bounds2i pixelBounds = film.PixelBounds();
    Vector2i resolution = pixelBounds.Diagonal();
    Timer timer;
304
    // Prefetch allocations to GPU memory
305 306 307 308 309 310
#ifdef PBRT_BUILD_GPU_RENDERER
    if (Options->useGPU) {
        int deviceIndex;
        CUDA_CHECK(cudaGetDevice(&deviceIndex));
        int hasConcurrentManagedAccess;
        CUDA_CHECK(cudaDeviceGetAttribute(&hasConcurrentManagedAccess,
311 312
                                          cudaDevAttrConcurrentManagedAccess,
                                          deviceIndex));
313 314 315 316 317 318 319 320 321 322

        // Copy all of the scene data structures over to GPU memory.  This
        // ensures that there isn't a big performance hitch for the first batch
        // of rays as that stuff is copied over on demand.
        if (hasConcurrentManagedAccess) {
            // Set things up so that we can still have read from the
            // WavefrontPathIntegrator struct on the CPU without hurting
            // performance. (This makes it possible to use the values of things
            // like WavefrontPathIntegrator::haveSubsurface to conditionally launch
            // kernels according to what's in the scene...)
323 324
            CUDA_CHECK(cudaMemAdvise(this, sizeof(*this), cudaMemAdviseSetReadMostly,
                                     /* ignored argument */ 0));
325 326 327 328 329 330 331
            CUDA_CHECK(cudaMemAdvise(this, sizeof(*this),
                                     cudaMemAdviseSetPreferredLocation, deviceIndex));

            // Copy all of the scene data structures over to GPU memory.  This
            // ensures that there isn't a big performance hitch for the first batch
            // of rays as that stuff is copied over on demand.
            CUDATrackedMemoryResource *mr =
332
                dynamic_cast<CUDATrackedMemoryResource *>(memoryResource);
M
Matt Pharr 已提交
333
            CHECK(mr);
334 335 336 337 338 339 340
            mr->PrefetchToGPU();
        } else {
            // TODO: on systems with basic unified memory, just launching a
            // kernel should cause everything to be copied over. Is an empty
            // kernel sufficient?
        }
    }
341
#endif  // PBRT_BUILD_GPU_RENDERER
342

343
    // Launch thread to copy image for display server, if enabled
M
Matt Pharr 已提交
344 345 346 347 348
    RGB *displayRGB = nullptr, *displayRGBHost = nullptr;
    std::atomic<bool> exitCopyThread{false};
    std::thread copyThread;

    if (!Options->displayServer.empty()) {
349 350 351 352
#ifdef PBRT_BUILD_GPU_RENDERER
        if (Options->useGPU) {
            // Allocate staging memory on the GPU to store the current WIP
            // image.
353 354 355 356
            CUDA_CHECK(
                cudaMalloc(&displayRGB, resolution.x * resolution.y * sizeof(RGB)));
            CUDA_CHECK(
                cudaMemset(displayRGB, 0, resolution.x * resolution.y * sizeof(RGB)));
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382

            // Host-side memory for the WIP Image.  We'll just let this leak so
            // that the lambda passed to DisplayDynamic below doesn't access
            // freed memory after Render() returns...
            displayRGBHost = new RGB[resolution.x * resolution.y];

            copyThread = std::thread([&]() {
                GPURegisterThread("DISPLAY_SERVER_COPY_THREAD");

                // Copy back to the CPU using a separate stream so that we can
                // periodically but asynchronously pick up the latest results
                // from the GPU.
                cudaStream_t memcpyStream;
                CUDA_CHECK(cudaStreamCreate(&memcpyStream));
                GPUNameStream(memcpyStream, "DISPLAY_SERVER_COPY_STREAM");

                // Copy back to the host from the GPU buffer, without any
                // synthronization.
                while (!exitCopyThread) {
                    CUDA_CHECK(cudaMemcpyAsync(displayRGBHost, displayRGB,
                                               resolution.x * resolution.y * sizeof(RGB),
                                               cudaMemcpyDeviceToHost, memcpyStream));
                    std::this_thread::sleep_for(std::chrono::milliseconds(50));

                    CUDA_CHECK(cudaStreamSynchronize(memcpyStream));
                }
M
Matt Pharr 已提交
383

384 385 386 387 388 389 390 391 392 393
                // Copy one more time to get the final image before exiting.
                CUDA_CHECK(cudaMemcpy(displayRGBHost, displayRGB,
                                      resolution.x * resolution.y * sizeof(RGB),
                                      cudaMemcpyDeviceToHost));
                CUDA_CHECK(cudaDeviceSynchronize());
            });

            // Now on the CPU side, give the display system a lambda that
            // copies values from |displayRGBHost| into its buffers used for
            // sending messages to the display program (i.e., tev).
394 395
            DisplayDynamic(film.GetFilename(), {resolution.x, resolution.y},
                           {"R", "G", "B"},
396
                           [resolution, displayRGBHost](
397
                               Bounds2i b, pstd::span<pstd::span<Float>> displayValue) {
398 399 400 401 402 403 404 405 406 407
                               int index = 0;
                               for (Point2i p : b) {
                                   RGB rgb = displayRGBHost[p.x + p.y * resolution.x];
                                   displayValue[0][index] = rgb.r;
                                   displayValue[1][index] = rgb.g;
                                   displayValue[2][index] = rgb.b;
                                   ++index;
                               }
                           });
        } else
408 409 410 411 412 413 414 415 416 417 418 419 420 421
#endif  // PBRT_BUILD_GPU_RENDERER
            DisplayDynamic(
                film.GetFilename(), Point2i(pixelBounds.Diagonal()), {"R", "G", "B"},
                [pixelBounds, this](Bounds2i b,
                                    pstd::span<pstd::span<Float>> displayValue) {
                    int index = 0;
                    for (Point2i p : b) {
                        RGB rgb =
                            film.GetPixelRGB(pixelBounds.pMin + p, 1.f /* splat scale */);
                        for (int c = 0; c < 3; ++c)
                            displayValue[c][index] = rgb[c];
                        ++index;
                    }
                });
M
Matt Pharr 已提交
422 423
    }

424
    // Loop over sample indices and evaluate pixel samples
425
    int firstSampleIndex = 0, lastSampleIndex = samplesPerPixel;
426
    // Update sample index range based on debug start, if provided
M
Matt Pharr 已提交
427
    if (!Options->debugStart.empty()) {
428
        std::vector<int> values = SplitStringToInts(Options->debugStart, ',');
429 430
        if (values.size() != 1 && values.size() != 2)
            ErrorExit("Expected either one or two integer values for --debugstart.");
431

432
        firstSampleIndex = values[0];
433 434 435 436
        if (values.size() == 2)
            lastSampleIndex = firstSampleIndex + values[1];
        else
            lastSampleIndex = firstSampleIndex + 1;
M
Matt Pharr 已提交
437 438
    }

439
    ProgressReporter progress(lastSampleIndex - firstSampleIndex, "Rendering",
440
                              Options->quiet, Options->useGPU);
441 442
    for (int sampleIndex = firstSampleIndex; sampleIndex < lastSampleIndex;
         ++sampleIndex) {
M
Matt Pharr 已提交
443 444 445
        // Attempt to work around issue #145.
#if !(defined(PBRT_IS_WINDOWS) && defined(PBRT_BUILD_GPU_RENDERER) && \
      __CUDACC_VER_MAJOR__ == 11 && __CUDACC_VER_MINIOR__ == 1)
446
        CheckCallbackScope _([&]() {
447
            return StringPrintf("Wavefront rendering failed at sample %d. Debug with "
448 449 450
                                "\"--debugstart %d\"\n",
                                sampleIndex, sampleIndex);
        });
M
Matt Pharr 已提交
451
#endif
452

453
        // Render image for sample _sampleIndex_
M
Matt Pharr 已提交
454
        LOG_VERBOSE("Starting to submit work for sample %d", sampleIndex);
M
Matt Pharr 已提交
455 456
        for (int y0 = pixelBounds.pMin.y; y0 < pixelBounds.pMax.y;
             y0 += scanlinesPerPass) {
457
            // Generate camera rays for current scanline range
458
            RayQueue *cameraRayQueue = CurrentRayQueue(0);
459 460
            Do(
                "Reset ray queue", PBRT_CPU_GPU_LAMBDA() {
461
                    PBRT_DBG("Starting scanlines at y0 = %d, sample %d / %d\n", y0,
462
                             sampleIndex, samplesPerPixel);
463 464
                    cameraRayQueue->Reset();
                });
M
Matt Pharr 已提交
465
            GenerateCameraRays(y0, sampleIndex);
466
            Do(
467
                "Update camera ray stats",
468
                PBRT_CPU_GPU_LAMBDA() { stats->cameraRays += cameraRayQueue->Size(); });
M
Matt Pharr 已提交
469

M
Matt Pharr 已提交
470
            // Trace rays and estimate radiance up to maximum ray depth
471
            for (int wavefrontDepth = 0; true; ++wavefrontDepth) {
472
                // Reset queues before tracing rays
473
                RayQueue *nextQueue = NextRayQueue(wavefrontDepth);
474 475
                Do(
                    "Reset queues before tracing rays", PBRT_CPU_GPU_LAMBDA() {
M
Matt Pharr 已提交
476
                        nextQueue->Reset();
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
                        // Reset queues before tracing next batch of rays
                        if (mediumSampleQueue)
                            mediumSampleQueue->Reset();
                        if (mediumScatterQueue)
                            mediumScatterQueue->Reset();

                        if (escapedRayQueue)
                            escapedRayQueue->Reset();
                        hitAreaLightQueue->Reset();

                        basicEvalMaterialQueue->Reset();
                        universalEvalMaterialQueue->Reset();

                        if (bssrdfEvalQueue)
                            bssrdfEvalQueue->Reset();
                        if (subsurfaceScatterQueue)
                            subsurfaceScatterQueue->Reset();
                    });

                // Follow active ray paths and accumulate radiance estimates
497
                GenerateRaySamples(wavefrontDepth, sampleIndex);
498

499
                // Find closest intersections along active rays
500
                aggregate->IntersectClosest(
501 502 503
                    maxQueueSize, CurrentRayQueue(wavefrontDepth), escapedRayQueue,
                    hitAreaLightQueue, basicEvalMaterialQueue, universalEvalMaterialQueue,
                    mediumSampleQueue, NextRayQueue(wavefrontDepth));
M
Matt Pharr 已提交
504

505
                if (wavefrontDepth > 0) {
506
                    // As above, with the indexing...
507
                    RayQueue *statsQueue = CurrentRayQueue(wavefrontDepth);
508 509
                    Do(
                        "Update indirect ray stats", PBRT_CPU_GPU_LAMBDA() {
510
                            stats->indirectRays[wavefrontDepth] += statsQueue->Size();
511
                        });
512
                }
513 514 515 516 517 518 519

                SampleMediumInteraction(wavefrontDepth);

                HandleEscapedRays();

                HandleEmissiveIntersection();

520
                if (wavefrontDepth == maxDepth)
M
Matt Pharr 已提交
521
                    break;
522

523
                EvaluateMaterialsAndBSDFs(wavefrontDepth);
524

525
                // Do immediately so that we have space for shadow rays for subsurface..
526
                TraceShadowRays(wavefrontDepth);
527 528

                SampleSubsurface(wavefrontDepth);
M
Matt Pharr 已提交
529
            }
M
Matt Pharr 已提交
530

M
Matt Pharr 已提交
531
            UpdateFilm();
532
            // Copy updated film pixels to buffer for display
533
#ifdef PBRT_BUILD_GPU_RENDERER
534
            if (Options->useGPU && !Options->displayServer.empty())
535 536
                GPUParallelFor(
                    "Update Display RGB Buffer", maxQueueSize,
537
                    PBRT_CPU_GPU_LAMBDA(int pixelIndex) {
538 539 540 541 542 543 544
                        Point2i pPixel = pixelSampleState.pPixel[pixelIndex];
                        if (!InsideExclusive(pPixel, film.PixelBounds()))
                            return;

                        Point2i p(pPixel - film.PixelBounds().pMin);
                        displayRGB[p.x + p.y * resolution.x] = film.GetPixelRGB(pPixel);
                    });
545
#endif  //  PBRT_BUILD_GPU_RENDERER
M
Matt Pharr 已提交
546 547 548 549 550
        }

        progress.Update();
    }
    progress.Done();
551

552 553 554
#ifdef PBRT_BUILD_GPU_RENDERER
    if (Options->useGPU)
        GPUWait();
555
#endif  // PBRT_BUILD_GPU_RENDERER
556
    Float seconds = timer.ElapsedSeconds();
557
    // Shut down display server thread, if active
558 559 560 561 562 563 564 565
#ifdef PBRT_BUILD_GPU_RENDERER
    if (Options->useGPU) {
        // Wait until rendering is all done before we start to shut down the
        // display stuff..
        if (!Options->displayServer.empty()) {
            exitCopyThread = true;
            copyThread.join();
        }
566

567 568 569
        // Another synchronization to make sure no kernels are running on the
        // GPU so that we can safely access unified memory from the CPU.
        GPUWait();
M
Matt Pharr 已提交
570
    }
571
#endif  // PBRT_BUILD_GPU_RENDERER
M
Matt Pharr 已提交
572

573
    return seconds;
M
Matt Pharr 已提交
574 575
}

576
void WavefrontPathIntegrator::HandleEscapedRays() {
577 578
    if (!escapedRayQueue)
        return;
579 580
    ForAllQueued(
        "Handle escaped rays", escapedRayQueue, maxQueueSize,
581
        PBRT_CPU_GPU_LAMBDA(const EscapedRayWorkItem w) {
582
            // Compute weighted radiance for escaped ray
583
            SampledSpectrum L(0.f);
584
            for (const auto &light : *infiniteLights) {
585 586
                if (SampledSpectrum Le = light.Le(Ray(w.rayo, w.rayd), w.lambda); Le) {
                    // Compute path radiance contribution from infinite light
587 588 589
                    PBRT_DBG("L %f %f %f %f T_hat %f %f %f %f Le %f %f %f %f", L[0], L[1],
                             L[2], L[3], w.T_hat[0], w.T_hat[1], w.T_hat[2], w.T_hat[3],
                             Le[0], Le[1], Le[2], Le[3]);
590
                    PBRT_DBG("pdf uni %f %f %f %f pdf nee %f %f %f %f", w.uniPathPDF[0],
591 592 593
                             w.uniPathPDF[1], w.uniPathPDF[2], w.uniPathPDF[3],
                             w.lightPathPDF[0], w.lightPathPDF[1], w.lightPathPDF[2],
                             w.lightPathPDF[3]);
594

595
                    if (w.depth == 0 || w.specularBounce) {
596 597 598 599 600
                        L += w.T_hat * Le / w.uniPathPDF.Average();
                    } else {
                        // Compute MIS-weighted radiance contribution from infinite light
                        LightSampleContext ctx = w.prevIntrCtx;
                        Float lightChoicePDF = lightSampler.PDF(ctx, light);
601 602
                        SampledSpectrum lightPathPDF = w.lightPathPDF * lightChoicePDF *
                                                       light.PDF_Li(ctx, w.rayd, true);
603 604 605
                        L += w.T_hat * Le / (w.uniPathPDF + lightPathPDF).Average();
                    }
                }
606
            }
607

608
            // Update pixel radiance if ray's radiance is nonzero
609
            if (L) {
610 611
                PBRT_DBG("Added L %f %f %f %f for escaped ray pixel index %d\n", L[0],
                         L[1], L[2], L[3], w.pixelIndex);
612

613 614 615
                L += pixelSampleState.L[w.pixelIndex];
                pixelSampleState.L[w.pixelIndex] = L;
            }
616
        });
M
Matt Pharr 已提交
617 618
}

619
void WavefrontPathIntegrator::HandleEmissiveIntersection() {
M
Matt Pharr 已提交
620 621
    ForAllQueued(
        "Handle emitters hit by indirect rays", hitAreaLightQueue, maxQueueSize,
622
        PBRT_CPU_GPU_LAMBDA(const HitAreaLightWorkItem w) {
623
            // Find emitted radiance from surface that ray hit
M
Matt Pharr 已提交
624
            SampledSpectrum Le = w.areaLight.L(w.p, w.n, w.uv, w.wo, w.lambda);
M
Matt Pharr 已提交
625 626
            if (!Le)
                return;
627
            PBRT_DBG("Got Le %f %f %f %f from hit area light at depth %d\n", Le[0], Le[1],
628
                     Le[2], Le[3], w.depth);
M
Matt Pharr 已提交
629

630
            // Compute area light's weighted radiance contribution to the path
631
            SampledSpectrum L(0.f);
632
            if (w.depth == 0 || w.isSpecularBounce) {
633
                L = w.T_hat * Le / w.uniPathPDF.Average();
M
Matt Pharr 已提交
634
            } else {
635
                // Compute MIS-weighted radiance contribution from area light
636 637
                Vector3f wi = -w.wo;
                LightSampleContext ctx = w.prevIntrCtx;
638
                Float lightChoicePDF = lightSampler.PDF(ctx, w.areaLight);
639
                Float lightPDF = lightChoicePDF * w.areaLight.PDF_Li(ctx, wi, true);
M
Matt Pharr 已提交
640

641 642 643
                SampledSpectrum uniPathPDF = w.uniPathPDF;
                SampledSpectrum lightPathPDF = w.lightPathPDF * lightPDF;
                L = w.T_hat * Le / (uniPathPDF + lightPathPDF).Average();
M
Matt Pharr 已提交
644 645
            }

646
            PBRT_DBG("Added L %f %f %f %f for pixel index %d\n", L[0], L[1], L[2], L[3],
647
                     w.pixelIndex);
648

649
            // Update _L_ in _PixelSampleState_ for area light's radiance
650 651
            L += pixelSampleState.L[w.pixelIndex];
            pixelSampleState.L[w.pixelIndex] = L;
M
Matt Pharr 已提交
652 653 654
        });
}

655
void WavefrontPathIntegrator::TraceShadowRays(int wavefrontDepth) {
656
    if (haveMedia)
657
        aggregate->IntersectShadowTr(maxQueueSize, shadowRayQueue, &pixelSampleState);
658
    else
659
        aggregate->IntersectShadow(maxQueueSize, shadowRayQueue, &pixelSampleState);
660
    // Reset shadow ray queue
661 662
    Do(
        "Reset shadowRayQueue", PBRT_CPU_GPU_LAMBDA() {
663
            stats->shadowRays[wavefrontDepth] += shadowRayQueue->Size();
664 665 666 667
            shadowRayQueue->Reset();
        });
}

668
WavefrontPathIntegrator::Stats::Stats(int maxDepth, Allocator alloc)
M
Matt Pharr 已提交
669 670
    : indirectRays(maxDepth + 1, alloc), shadowRays(maxDepth, alloc) {}

671
std::string WavefrontPathIntegrator::Stats::Print() const {
M
Matt Pharr 已提交
672 673 674 675 676 677 678 679 680 681 682 683 684
    std::string s;
    s += StringPrintf("    %-42s               %12" PRIu64 "\n", "Camera rays",
                      cameraRays);
    for (int i = 1; i < indirectRays.size(); ++i)
        s += StringPrintf("    %-42s               %12" PRIu64 "\n",
                          StringPrintf("Indirect rays, depth %-3d", i), indirectRays[i]);
    for (int i = 0; i < shadowRays.size(); ++i)
        s += StringPrintf("    %-42s               %12" PRIu64 "\n",
                          StringPrintf("Shadow rays, depth %-3d", i), shadowRays[i]);
    return s;
}

}  // namespace pbrt