scene.cpp 59.8 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/scene.h>
M
Matt Pharr 已提交
6

7
#include <pbrt/cpu/aggregates.h>
M
Matt Pharr 已提交
8
#include <pbrt/cpu/integrators.h>
9 10
#ifdef PBRT_BUILD_GPU_RENDERER
#include <pbrt/gpu/memory.h>
11
#endif  // PBRT_BUILD_GPU_RENDERER
M
Matt Pharr 已提交
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
#include <pbrt/materials.h>
#include <pbrt/options.h>
#include <pbrt/paramdict.h>
#include <pbrt/shapes.h>
#include <pbrt/util/args.h>
#include <pbrt/util/check.h>
#include <pbrt/util/color.h>
#include <pbrt/util/colorspace.h>
#include <pbrt/util/file.h>
#include <pbrt/util/memory.h>
#include <pbrt/util/mesh.h>
#include <pbrt/util/parallel.h>
#include <pbrt/util/print.h>
#include <pbrt/util/spectrum.h>
#include <pbrt/util/transform.h>

#include <iostream>
#include <mutex>

namespace pbrt {

33 34
InternCache<std::string> SceneEntity::internedStrings(Allocator{});

M
Matt Pharr 已提交
35 36 37 38 39 40 41 42 43 44 45 46 47 48
template <typename T, typename U>
static std::string ToString(const std::map<T, U> &m) {
    std::string s = "[ ";
    for (const auto &iter : m)
        s += StringPrintf("%s:%s ", iter.first, iter.second);
    s += "]";
    return s;
}

template <typename T, typename U>
static std::string ToString(const std::pair<T, U> &p) {
    return StringPrintf("[ std::pair first: %s second: %s ]", p.first, p.second);
}

M
Matt Pharr 已提交
49
std::string BasicSceneBuilder::ToString() const {
M
Matt Pharr 已提交
50
    return StringPrintf(
M
Matt Pharr 已提交
51
        "[ BasicSceneBuilder camera: %s film: %s sampler: %s integrator: %s "
M
Matt Pharr 已提交
52 53 54 55
        "filter: %s accelerator: %s ]",
        camera, film, sampler, integrator, filter, accelerator);
}

M
Matt Pharr 已提交
56
BasicSceneBuilder::GraphicsState::GraphicsState() {
M
Matt Pharr 已提交
57 58 59 60
    currentMaterialIndex = 0;
}

// API State Macros
61
#define VERIFY_OPTIONS(func)                                   \
M
Matt Pharr 已提交
62
    if (currentBlock == BlockState::WorldBlock) {              \
63 64 65 66
        ErrorExit(&loc,                                        \
                  "Options cannot be set inside world block; " \
                  "\"%s\" is not allowed.",                    \
                  func);                                       \
M
Matt Pharr 已提交
67 68
        return;                                                \
    } else /* swallow trailing semicolon */
69
#define VERIFY_WORLD(func)                                         \
M
Matt Pharr 已提交
70
    if (currentBlock == BlockState::OptionsBlock) {                \
71 72 73 74 75 76
        ErrorExit(&loc,                                            \
                  "Scene description must be inside world block; " \
                  "\"%s\" is not allowed.",                        \
                  func);                                           \
        return;                                                    \
    } else /* swallow trailing semicolon */
M
Matt Pharr 已提交
77

M
Matt Pharr 已提交
78 79 80 81
#define FOR_ACTIVE_TRANSFORMS(expr)                         \
    for (int i = 0; i < MaxTransforms; ++i)                 \
        if (graphicsState.activeTransformBits & (1 << i)) { \
            expr                                            \
M
Matt Pharr 已提交
82 83
        }

M
Matt Pharr 已提交
84 85 86
STAT_COUNTER("Scene/Object instances created", nObjectInstancesCreated);
STAT_COUNTER("Scene/Object instances used", nObjectInstancesUsed);

M
Matt Pharr 已提交
87 88
// BasicSceneBuilder Method Definitions
BasicSceneBuilder::BasicSceneBuilder(BasicScene *scene)
M
Matt Pharr 已提交
89
    : scene(scene)
M
Matt Pharr 已提交
90
#ifdef PBRT_BUILD_GPU_RENDERER
91 92 93
      ,
      transformCache(Options->useGPU ? Allocator(&CUDATrackedMemoryResource::singleton)
                                     : Allocator())
M
Matt Pharr 已提交
94 95
#endif
{
M
Matt Pharr 已提交
96
    // Set scene defaults
97 98 99 100 101
    camera.name = SceneEntity::internedStrings.Lookup("perspective");
    sampler.name = SceneEntity::internedStrings.Lookup("zsobol");
    filter.name = SceneEntity::internedStrings.Lookup("gaussian");
    integrator.name = SceneEntity::internedStrings.Lookup("volpath");
    accelerator.name = SceneEntity::internedStrings.Lookup("bvh");
M
Matt Pharr 已提交
102

103
    film.name = SceneEntity::internedStrings.Lookup("rgb");
M
Matt Pharr 已提交
104
    film.parameters = ParameterDictionary({}, RGBColorSpace::sRGB);
M
Matt Pharr 已提交
105 106 107

    ParameterDictionary dict({}, RGBColorSpace::sRGB);
    currentMaterialIndex = scene->AddMaterial(SceneEntity("diffuse", dict, {}));
M
Matt Pharr 已提交
108
}
M
Matt Pharr 已提交
109

M
Matt Pharr 已提交
110
void BasicSceneBuilder::ReverseOrientation(FileLoc loc) {
M
Matt Pharr 已提交
111 112 113 114
    VERIFY_WORLD("ReverseOrientation");
    graphicsState.reverseOrientation = !graphicsState.reverseOrientation;
}

M
Matt Pharr 已提交
115
void BasicSceneBuilder::ColorSpace(const std::string &name, FileLoc loc) {
M
Matt Pharr 已提交
116 117 118 119
    if (const RGBColorSpace *cs = RGBColorSpace::GetNamed(name))
        graphicsState.colorSpace = cs;
    else
        Error(&loc, "%s: color space unknown", name);
M
Matt Pharr 已提交
120 121
}

M
Matt Pharr 已提交
122
void BasicSceneBuilder::Identity(FileLoc loc) {
M
Matt Pharr 已提交
123
    FOR_ACTIVE_TRANSFORMS(graphicsState.ctm[i] = pbrt::Transform();)
M
Matt Pharr 已提交
124 125
}

M
Matt Pharr 已提交
126
void BasicSceneBuilder::Translate(Float dx, Float dy, Float dz, FileLoc loc) {
M
Matt Pharr 已提交
127 128
    FOR_ACTIVE_TRANSFORMS(graphicsState.ctm[i] = graphicsState.ctm[i] *
                                                 pbrt::Translate(Vector3f(dx, dy, dz));)
M
Matt Pharr 已提交
129 130
}

M
Matt Pharr 已提交
131
void BasicSceneBuilder::CoordinateSystem(const std::string &name, FileLoc loc) {
M
Matt Pharr 已提交
132
    namedCoordinateSystems[name] = graphicsState.ctm;
M
Matt Pharr 已提交
133 134
}

M
Matt Pharr 已提交
135
void BasicSceneBuilder::CoordSysTransform(const std::string &name, FileLoc loc) {
M
Matt Pharr 已提交
136
    if (namedCoordinateSystems.find(name) != namedCoordinateSystems.end())
M
Matt Pharr 已提交
137
        graphicsState.ctm = namedCoordinateSystems[name];
M
Matt Pharr 已提交
138 139 140 141
    else
        Warning(&loc, "Couldn't find named coordinate system \"%s\"", name);
}

M
Matt Pharr 已提交
142
void BasicSceneBuilder::Camera(const std::string &name, ParsedParameterVector params,
M
Matt Pharr 已提交
143
                               FileLoc loc) {
M
Matt Pharr 已提交
144 145 146 147
    ParameterDictionary dict(std::move(params), graphicsState.colorSpace);

    VERIFY_OPTIONS("Camera");

M
Matt Pharr 已提交
148 149
    TransformSet cameraFromWorld = graphicsState.ctm;
    TransformSet worldFromCamera = Inverse(graphicsState.ctm);
M
Matt Pharr 已提交
150 151
    namedCoordinateSystems["camera"] = Inverse(cameraFromWorld);

M
Matt Pharr 已提交
152 153 154
    CameraTransform cameraTransform(
        AnimatedTransform(worldFromCamera[0], graphicsState.transformStartTime,
                          worldFromCamera[1], graphicsState.transformEndTime));
M
Matt Pharr 已提交
155 156 157 158
    renderFromWorld = cameraTransform.RenderFromWorld();

    camera = CameraSceneEntity(name, std::move(dict), loc, cameraTransform,
                               graphicsState.currentOutsideMedium);
M
Matt Pharr 已提交
159 160
}

M
Matt Pharr 已提交
161
void BasicSceneBuilder::AttributeBegin(FileLoc loc) {
M
Matt Pharr 已提交
162
    VERIFY_WORLD("AttributeBegin");
M
Matt Pharr 已提交
163
    pushedGraphicsStates.push_back(graphicsState);
M
Matt Pharr 已提交
164 165 166
    pushStack.push_back(std::make_pair('a', loc));
}

M
Matt Pharr 已提交
167
void BasicSceneBuilder::AttributeEnd(FileLoc loc) {
M
Matt Pharr 已提交
168
    VERIFY_WORLD("AttributeEnd");
M
Matt Pharr 已提交
169
    // Issue error on unmatched _AttributeEnd_
M
Matt Pharr 已提交
170 171 172 173
    if (pushedGraphicsStates.empty()) {
        Error(&loc, "Unmatched AttributeEnd encountered. Ignoring it.");
        return;
    }
M
Matt Pharr 已提交
174

M
Matt Pharr 已提交
175
    // NOTE: must keep the following consistent with code in ObjectEnd
M
Matt Pharr 已提交
176
    graphicsState = std::move(pushedGraphicsStates.back());
M
Matt Pharr 已提交
177 178
    pushedGraphicsStates.pop_back();

M
Matt Pharr 已提交
179
    if (pushStack.back().first == 'o')
M
Matt Pharr 已提交
180 181 182 183 184 185 186 187
        ErrorExitDeferred(&loc,
                          "Mismatched nesting: open ObjectBegin from %s at AttributeEnd",
                          pushStack.back().second);
    else
        CHECK_EQ(pushStack.back().first, 'a');
    pushStack.pop_back();
}

M
Matt Pharr 已提交
188
void BasicSceneBuilder::Attribute(const std::string &target, ParsedParameterVector attrib,
M
Matt Pharr 已提交
189
                                  FileLoc loc) {
M
Matt Pharr 已提交
190 191
    ParsedParameterVector *currentAttributes = nullptr;
    if (target == "shape") {
M
Matt Pharr 已提交
192
        currentAttributes = &graphicsState.shapeAttributes;
M
Matt Pharr 已提交
193
    } else if (target == "light") {
M
Matt Pharr 已提交
194
        currentAttributes = &graphicsState.lightAttributes;
M
Matt Pharr 已提交
195
    } else if (target == "material") {
M
Matt Pharr 已提交
196
        currentAttributes = &graphicsState.materialAttributes;
M
Matt Pharr 已提交
197
    } else if (target == "medium") {
M
Matt Pharr 已提交
198
        currentAttributes = &graphicsState.mediumAttributes;
M
Matt Pharr 已提交
199
    } else if (target == "texture") {
M
Matt Pharr 已提交
200
        currentAttributes = &graphicsState.textureAttributes;
M
Matt Pharr 已提交
201 202 203 204 205 206 207 208 209 210 211 212 213
    } else {
        ErrorExitDeferred(
            &loc,
            "Unknown attribute target \"%s\". Must be \"shape\", \"light\", "
            "\"material\", \"medium\", or \"texture\".",
            target);
        return;
    }

    // Note that we hold on to the current color space and associate it
    // with the parameters...
    for (ParsedParameter *p : attrib) {
        p->mayBeUnused = true;
M
Matt Pharr 已提交
214
        p->colorSpace = graphicsState.colorSpace;
M
Matt Pharr 已提交
215 216 217 218
        currentAttributes->push_back(p);
    }
}

M
Matt Pharr 已提交
219 220 221 222 223 224 225 226
void BasicSceneBuilder::Sampler(const std::string &name, ParsedParameterVector params,
                                FileLoc loc) {
    ParameterDictionary dict(std::move(params), graphicsState.colorSpace);
    VERIFY_OPTIONS("Sampler");
    sampler = SceneEntity(name, std::move(dict), loc);
}

void BasicSceneBuilder::WorldBegin(FileLoc loc) {
M
Matt Pharr 已提交
227
    VERIFY_OPTIONS("WorldBegin");
M
Matt Pharr 已提交
228
    // Reset graphics state for _WorldBegin_
M
Matt Pharr 已提交
229 230
    currentBlock = BlockState::WorldBlock;
    for (int i = 0; i < MaxTransforms; ++i)
M
Matt Pharr 已提交
231
        graphicsState.ctm[i] = pbrt::Transform();
M
Matt Pharr 已提交
232
    graphicsState.activeTransformBits = AllTransformsBits;
M
Matt Pharr 已提交
233
    namedCoordinateSystems["world"] = graphicsState.ctm;
M
Matt Pharr 已提交
234

M
Matt Pharr 已提交
235
    // Pass pre-_WorldBegin_ entities to _scene_
M
Matt Pharr 已提交
236
    scene->SetSampler(std::move(sampler));
M
Matt Pharr 已提交
237 238

    scene->SetFilm(std::move(film));
M
Matt Pharr 已提交
239 240 241 242
    scene->SetIntegrator(std::move(integrator));
    scene->SetFilter(std::move(filter));
    scene->SetAccelerator(std::move(accelerator));
    scene->SetCamera(std::move(camera));
M
Matt Pharr 已提交
243 244
}

M
Matt Pharr 已提交
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
void BasicSceneBuilder::MakeNamedMedium(const std::string &name,
                                        ParsedParameterVector params, FileLoc loc) {
    ParameterDictionary dict(std::move(params), graphicsState.mediumAttributes,
                             graphicsState.colorSpace);
    // Issue error if medium _name_ is multiply-defined
    if (mediumNames.find(name) != mediumNames.end()) {
        ErrorExitDeferred(&loc, "Named medium \"%s\" redefined.", name);
        return;
    }
    mediumNames.insert(name);

    scene->AddMedium(
        TransformedSceneEntity(name, std::move(dict), loc, RenderFromObject()));
}

void BasicSceneBuilder::LightSource(const std::string &name, ParsedParameterVector params,
M
Matt Pharr 已提交
261
                                    FileLoc loc) {
M
Matt Pharr 已提交
262
    VERIFY_WORLD("LightSource");
M
Matt Pharr 已提交
263 264
    ParameterDictionary dict(std::move(params), graphicsState.lightAttributes,
                             graphicsState.colorSpace);
M
Matt Pharr 已提交
265 266
    scene->AddLight(LightSceneEntity(name, std::move(dict), loc, RenderFromObject(),
                                     graphicsState.currentOutsideMedium));
M
Matt Pharr 已提交
267 268
}

M
Matt Pharr 已提交
269
void BasicSceneBuilder::Shape(const std::string &name, ParsedParameterVector params,
M
Matt Pharr 已提交
270
                              FileLoc loc) {
M
Matt Pharr 已提交
271 272
    VERIFY_WORLD("Shape");

M
Matt Pharr 已提交
273 274
    ParameterDictionary dict(std::move(params), graphicsState.shapeAttributes,
                             graphicsState.colorSpace);
M
Matt Pharr 已提交
275 276

    int areaLightIndex = -1;
M
Matt Pharr 已提交
277
    if (!graphicsState.areaLightName.empty()) {
M
Matt Pharr 已提交
278 279 280
        areaLightIndex = scene->AddAreaLight(SceneEntity(graphicsState.areaLightName,
                                                         graphicsState.areaLightParams,
                                                         graphicsState.areaLightLoc));
M
Matt Pharr 已提交
281 282
        if (activeInstanceDefinition)
            Warning(&loc, "Area lights not supported with object instancing");
M
Matt Pharr 已提交
283 284 285
    }

    if (CTMIsAnimated()) {
286
        AnimatedTransform renderFromShape = RenderFromObject();
M
Matt Pharr 已提交
287 288
        const class Transform *identity = transformCache.Lookup(pbrt::Transform());

M
Matt Pharr 已提交
289
        AnimatedShapeSceneEntity entity(
M
Matt Pharr 已提交
290
            {name, std::move(dict), loc, renderFromShape, identity,
M
Matt Pharr 已提交
291 292
             graphicsState.reverseOrientation, graphicsState.currentMaterialIndex,
             graphicsState.currentMaterialName, areaLightIndex,
M
Matt Pharr 已提交
293
             graphicsState.currentInsideMedium, graphicsState.currentOutsideMedium});
M
Matt Pharr 已提交
294

M
Matt Pharr 已提交
295 296 297
        if (activeInstanceDefinition)
            activeInstanceDefinition->entity.animatedShapes.push_back(std::move(entity));
        else
M
Matt Pharr 已提交
298
            scene->AddAnimatedShape(std::move(entity));
M
Matt Pharr 已提交
299
    } else {
M
Matt Pharr 已提交
300 301
        const class Transform *renderFromObject =
            transformCache.Lookup(RenderFromObject(0));
M
Matt Pharr 已提交
302 303 304
        const class Transform *objectFromRender =
            transformCache.Lookup(Inverse(*renderFromObject));

M
Matt Pharr 已提交
305
        ShapeSceneEntity entity(
M
Matt Pharr 已提交
306
            {name, std::move(dict), loc, renderFromObject, objectFromRender,
M
Matt Pharr 已提交
307 308
             graphicsState.reverseOrientation, graphicsState.currentMaterialIndex,
             graphicsState.currentMaterialName, areaLightIndex,
M
Matt Pharr 已提交
309 310 311 312 313
             graphicsState.currentInsideMedium, graphicsState.currentOutsideMedium});
        if (activeInstanceDefinition)
            activeInstanceDefinition->entity.shapes.push_back(std::move(entity));
        else
            shapes.push_back(std::move(entity));
M
Matt Pharr 已提交
314 315 316
    }
}

M
Matt Pharr 已提交
317
void BasicSceneBuilder::ObjectBegin(const std::string &name, FileLoc loc) {
M
Matt Pharr 已提交
318
    VERIFY_WORLD("ObjectBegin");
M
Matt Pharr 已提交
319
    pushedGraphicsStates.push_back(graphicsState);
M
Matt Pharr 已提交
320 321 322

    pushStack.push_back(std::make_pair('o', loc));

M
Matt Pharr 已提交
323
    if (activeInstanceDefinition) {
M
Matt Pharr 已提交
324 325 326 327
        ErrorExitDeferred(&loc, "ObjectBegin called inside of instance definition");
        return;
    }

M
Matt Pharr 已提交
328
    if (instanceNames.find(name) != instanceNames.end()) {
M
Matt Pharr 已提交
329 330 331
        ErrorExitDeferred(&loc, "%s: trying to redefine an object instance", name);
        return;
    }
M
Matt Pharr 已提交
332
    instanceNames.insert(name);
M
Matt Pharr 已提交
333

M
Matt Pharr 已提交
334
    activeInstanceDefinition = new ActiveInstanceDefinition(name, loc);
M
Matt Pharr 已提交
335 336
}

M
Matt Pharr 已提交
337
void BasicSceneBuilder::ObjectEnd(FileLoc loc) {
M
Matt Pharr 已提交
338
    VERIFY_WORLD("ObjectEnd");
M
Matt Pharr 已提交
339
    if (!activeInstanceDefinition) {
M
Matt Pharr 已提交
340 341 342
        ErrorExitDeferred(&loc, "ObjectEnd called outside of instance definition");
        return;
    }
M
Matt Pharr 已提交
343 344 345 346
    if (activeInstanceDefinition->parent) {
        ErrorExitDeferred(&loc, "ObjectEnd called inside Import for instance definition");
        return;
    }
M
Matt Pharr 已提交
347 348

    // NOTE: Must keep the following consistent with AttributeEnd
M
Matt Pharr 已提交
349
    graphicsState = std::move(pushedGraphicsStates.back());
M
Matt Pharr 已提交
350 351 352 353
    pushedGraphicsStates.pop_back();

    ++nObjectInstancesCreated;

M
Matt Pharr 已提交
354
    if (pushStack.back().first == 'a')
M
Matt Pharr 已提交
355 356 357 358 359 360
        ErrorExitDeferred(&loc,
                          "Mismatched nesting: open AttributeBegin from %s at ObjectEnd",
                          pushStack.back().second);
    else
        CHECK_EQ(pushStack.back().first, 'o');
    pushStack.pop_back();
M
Matt Pharr 已提交
361 362 363

    // Otherwise it will be taken care of in MergeImported()
    if (--activeInstanceDefinition->activeImports == 0) {
M
Matt Pharr 已提交
364
        scene->AddInstanceDefinition(std::move(activeInstanceDefinition->entity));
M
Matt Pharr 已提交
365 366 367 368
        delete activeInstanceDefinition;
    }

    activeInstanceDefinition = nullptr;
M
Matt Pharr 已提交
369 370
}

M
Matt Pharr 已提交
371
void BasicSceneBuilder::ObjectInstance(const std::string &name, FileLoc loc) {
M
Matt Pharr 已提交
372 373
    VERIFY_WORLD("ObjectInstance");

M
Matt Pharr 已提交
374
    if (activeInstanceDefinition) {
M
Matt Pharr 已提交
375 376 377 378 379 380 381 382 383
        ErrorExitDeferred(&loc,
                          "ObjectInstance can't be called inside instance definition");
        return;
    }

    class Transform worldFromRender = Inverse(renderFromWorld);

    if (CTMIsAnimated()) {
        AnimatedTransform animatedRenderFromInstance(
M
Matt Pharr 已提交
384 385
            RenderFromObject(0) * worldFromRender, graphicsState.transformStartTime,
            RenderFromObject(1) * worldFromRender, graphicsState.transformEndTime);
M
Matt Pharr 已提交
386

M
Matt Pharr 已提交
387 388
        instanceUses.push_back(
            InstanceSceneEntity(name, loc, animatedRenderFromInstance));
M
Matt Pharr 已提交
389 390
    } else {
        const class Transform *renderFromInstance =
M
Matt Pharr 已提交
391
            transformCache.Lookup(RenderFromObject(0) * worldFromRender);
M
Matt Pharr 已提交
392

M
Matt Pharr 已提交
393
        instanceUses.push_back(InstanceSceneEntity(name, loc, renderFromInstance));
M
Matt Pharr 已提交
394 395 396
    }
}

M
Matt Pharr 已提交
397
void BasicSceneBuilder::EndOfFiles() {
M
Matt Pharr 已提交
398
    if (currentBlock != BlockState::WorldBlock)
M
Matt Pharr 已提交
399 400 401 402 403 404 405 406 407 408
        ErrorExitDeferred("End of files before \"WorldBegin\".");

    // Ensure there are no pushed graphics states
    while (!pushedGraphicsStates.empty()) {
        ErrorExitDeferred("Missing end to AttributeBegin");
        pushedGraphicsStates.pop_back();
    }

    if (errorExit)
        ErrorExit("Fatal errors during scene construction");
409

M
Matt Pharr 已提交
410
    if (!shapes.empty())
M
Matt Pharr 已提交
411
        scene->AddShapes(shapes);
M
Matt Pharr 已提交
412
    if (!instanceUses.empty())
M
Matt Pharr 已提交
413
        scene->AddInstanceUses(instanceUses);
414

M
Matt Pharr 已提交
415
    scene->Done();
M
Matt Pharr 已提交
416 417
}

M
Matt Pharr 已提交
418 419 420 421 422
BasicSceneBuilder *BasicSceneBuilder::CopyForImport() {
    BasicSceneBuilder *importBuilder = new BasicSceneBuilder(scene);
    importBuilder->renderFromWorld = renderFromWorld;
    importBuilder->graphicsState = graphicsState;
    importBuilder->currentBlock = currentBlock;
M
Matt Pharr 已提交
423
    if (activeInstanceDefinition) {
M
Matt Pharr 已提交
424
        importBuilder->activeInstanceDefinition = new ActiveInstanceDefinition(
M
Matt Pharr 已提交
425 426 427 428 429 430 431 432
            activeInstanceDefinition->entity.name, activeInstanceDefinition->entity.loc);

        // In case of nested imports, go up to the true root parent since
        // that's where we need to merge our shapes and that's where the
        // refcount is.
        ActiveInstanceDefinition *parent = activeInstanceDefinition;
        while (parent->parent)
            parent = parent->parent;
M
Matt Pharr 已提交
433
        importBuilder->activeInstanceDefinition->parent = parent;
M
Matt Pharr 已提交
434
        ++parent->activeImports;
435
    }
M
Matt Pharr 已提交
436
    return importBuilder;
437 438
}

M
Matt Pharr 已提交
439
void BasicSceneBuilder::MergeImported(BasicSceneBuilder *imported) {
M
Matt Pharr 已提交
440
    while (!imported->pushedGraphicsStates.empty()) {
441
        ErrorExitDeferred("Missing end to AttributeBegin");
M
Matt Pharr 已提交
442
        imported->pushedGraphicsStates.pop_back();
443 444
    }

M
Matt Pharr 已提交
445
    errorExit |= imported->errorExit;
446

M
Matt Pharr 已提交
447
    if (!imported->shapes.empty())
M
Matt Pharr 已提交
448
        scene->AddShapes(imported->shapes);
M
Matt Pharr 已提交
449
    if (!imported->instanceUses.empty())
M
Matt Pharr 已提交
450
        scene->AddInstanceUses(imported->instanceUses);
451

452 453 454 455 456 457 458 459 460 461
    auto mergeVector = [](auto &base, auto &imported) {
        if (base.empty())
            base = std::move(imported);
        else {
            base.reserve(base.size() + imported.size());
            std::move(std::begin(imported), std::end(imported), std::back_inserter(base));
            imported.clear();
            imported.shrink_to_fit();
        }
    };
M
Matt Pharr 已提交
462 463 464 465
    if (imported->activeInstanceDefinition) {
        ActiveInstanceDefinition *current = imported->activeInstanceDefinition;
        ActiveInstanceDefinition *parent = current->parent;
        CHECK(parent != nullptr);
466

M
Matt Pharr 已提交
467 468 469
        std::lock_guard<std::mutex> lock(parent->mutex);
        mergeVector(parent->entity.shapes, current->entity.shapes);
        mergeVector(parent->entity.animatedShapes, current->entity.animatedShapes);
470

M
Matt Pharr 已提交
471 472 473
        delete current;

        if (--parent->activeImports == 0)
M
Matt Pharr 已提交
474
            scene->AddInstanceDefinition(std::move(parent->entity));
M
Matt Pharr 已提交
475 476 477

        parent->mutex.unlock();
    }
478

479
    auto mergeSet = [this](auto &base, auto &imported, const char *name) {
480 481
        for (const auto &item : imported) {
            if (base.find(item) != base.end())
482
                ErrorExitDeferred("%s: multiply defined %s.", item, name);
483
            base.insert(std::move(item));
484
        }
485
        imported.clear();
486
    };
M
Matt Pharr 已提交
487 488 489
    mergeSet(namedMaterialNames, imported->namedMaterialNames, "named material");
    mergeSet(floatTextureNames, imported->floatTextureNames, "texture");
    mergeSet(spectrumTextureNames, imported->spectrumTextureNames, "texture");
490 491
}

M
Matt Pharr 已提交
492
void BasicSceneBuilder::Option(const std::string &name, const std::string &value,
M
Matt Pharr 已提交
493
                               FileLoc loc) {
M
Matt Pharr 已提交
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 535 536 537 538 539 540 541
    std::string nName = normalizeArg(name);

    if (nName == "disablepixeljitter") {
        if (value == "true")
            Options->disablePixelJitter = true;
        else if (value == "false")
            Options->disablePixelJitter = false;
        else
            ErrorExitDeferred(&loc, "%s: expected \"true\" or \"false\" for option value",
                              value);
    } else if (nName == "disablewavelengthjitter") {
        if (value == "true")
            Options->disableWavelengthJitter = true;
        else if (value == "false")
            Options->disableWavelengthJitter = false;
        else
            ErrorExitDeferred(&loc, "%s: expected \"true\" or \"false\" for option value",
                              value);
    } else if (nName == "msereferenceimage") {
        if (value.size() < 3 || value.front() != '"' || value.back() != '"')
            ErrorExitDeferred(&loc, "%s: expected quoted string for option value", value);
        Options->mseReferenceImage = value.substr(1, value.size() - 2);
    } else if (nName == "msereferenceout") {
        if (value.size() < 3 || value.front() != '"' || value.back() != '"')
            ErrorExitDeferred(&loc, "%s: expected quoted string for option value", value);
        Options->mseReferenceOutput = value.substr(1, value.size() - 2);
    } else if (nName == "seed") {
        Options->seed = std::atoi(value.c_str());
    } else if (nName == "forcediffuse") {
        if (value == "true")
            Options->forceDiffuse = true;
        else if (value == "false")
            Options->forceDiffuse = false;
        else
            ErrorExitDeferred(&loc, "%s: expected \"true\" or \"false\" for option value",
                              value);
    } else if (nName == "pixelstats") {
        if (value == "true")
            Options->recordPixelStatistics = true;
        else if (value == "false")
            Options->recordPixelStatistics = false;
        else
            ErrorExitDeferred(&loc, "%s: expected \"true\" or \"false\" for option value",
                              value);
    } else
        ErrorExitDeferred(&loc, "%s: unknown option", name);
}

M
Matt Pharr 已提交
542
void BasicSceneBuilder::Transform(Float tr[16], FileLoc loc) {
M
Matt Pharr 已提交
543
    FOR_ACTIVE_TRANSFORMS(graphicsState.ctm[i] = Transpose(
M
Matt Pharr 已提交
544 545 546
                              pbrt::Transform(SquareMatrix<4>(pstd::MakeSpan(tr, 16))));)
}

M
Matt Pharr 已提交
547
void BasicSceneBuilder::ConcatTransform(Float tr[16], FileLoc loc) {
M
Matt Pharr 已提交
548 549 550 551
    FOR_ACTIVE_TRANSFORMS(
        graphicsState.ctm[i] =
            graphicsState.ctm[i] *
            Transpose(pbrt::Transform(SquareMatrix<4>(pstd::MakeSpan(tr, 16))));)
M
Matt Pharr 已提交
552 553
}

M
Matt Pharr 已提交
554
void BasicSceneBuilder::Rotate(Float angle, Float dx, Float dy, Float dz, FileLoc loc) {
M
Matt Pharr 已提交
555 556 557
    FOR_ACTIVE_TRANSFORMS(graphicsState.ctm[i] =
                              graphicsState.ctm[i] *
                              pbrt::Rotate(angle, Vector3f(dx, dy, dz));)
M
Matt Pharr 已提交
558 559
}

M
Matt Pharr 已提交
560
void BasicSceneBuilder::Scale(Float sx, Float sy, Float sz, FileLoc loc) {
M
Matt Pharr 已提交
561 562
    FOR_ACTIVE_TRANSFORMS(graphicsState.ctm[i] =
                              graphicsState.ctm[i] * pbrt::Scale(sx, sy, sz);)
M
Matt Pharr 已提交
563 564
}

M
Matt Pharr 已提交
565
void BasicSceneBuilder::LookAt(Float ex, Float ey, Float ez, Float lx, Float ly, Float lz,
M
Matt Pharr 已提交
566
                               Float ux, Float uy, Float uz, FileLoc loc) {
M
Matt Pharr 已提交
567 568
    class Transform lookAt =
        pbrt::LookAt(Point3f(ex, ey, ez), Point3f(lx, ly, lz), Vector3f(ux, uy, uz));
M
Matt Pharr 已提交
569
    FOR_ACTIVE_TRANSFORMS(graphicsState.ctm[i] = graphicsState.ctm[i] * lookAt;);
M
Matt Pharr 已提交
570 571
}

M
Matt Pharr 已提交
572
void BasicSceneBuilder::ActiveTransformAll(FileLoc loc) {
M
Matt Pharr 已提交
573
    graphicsState.activeTransformBits = AllTransformsBits;
M
Matt Pharr 已提交
574 575
}

M
Matt Pharr 已提交
576
void BasicSceneBuilder::ActiveTransformEndTime(FileLoc loc) {
M
Matt Pharr 已提交
577
    graphicsState.activeTransformBits = EndTransformBits;
M
Matt Pharr 已提交
578 579
}

M
Matt Pharr 已提交
580
void BasicSceneBuilder::ActiveTransformStartTime(FileLoc loc) {
M
Matt Pharr 已提交
581
    graphicsState.activeTransformBits = StartTransformBits;
M
Matt Pharr 已提交
582 583
}

M
Matt Pharr 已提交
584
void BasicSceneBuilder::TransformTimes(Float start, Float end, FileLoc loc) {
M
Matt Pharr 已提交
585
    VERIFY_OPTIONS("TransformTimes");
M
Matt Pharr 已提交
586 587
    graphicsState.transformStartTime = start;
    graphicsState.transformEndTime = end;
M
Matt Pharr 已提交
588 589
}

M
Matt Pharr 已提交
590
void BasicSceneBuilder::PixelFilter(const std::string &name, ParsedParameterVector params,
M
Matt Pharr 已提交
591
                                    FileLoc loc) {
M
Matt Pharr 已提交
592
    ParameterDictionary dict(std::move(params), graphicsState.colorSpace);
M
Matt Pharr 已提交
593 594 595 596
    VERIFY_OPTIONS("PixelFilter");
    filter = SceneEntity(name, std::move(dict), loc);
}

M
Matt Pharr 已提交
597
void BasicSceneBuilder::Film(const std::string &type, ParsedParameterVector params,
M
Matt Pharr 已提交
598
                             FileLoc loc) {
M
Matt Pharr 已提交
599
    ParameterDictionary dict(std::move(params), graphicsState.colorSpace);
M
Matt Pharr 已提交
600 601 602 603
    VERIFY_OPTIONS("Film");
    film = SceneEntity(type, std::move(dict), loc);
}

M
Matt Pharr 已提交
604
void BasicSceneBuilder::Accelerator(const std::string &name, ParsedParameterVector params,
M
Matt Pharr 已提交
605
                                    FileLoc loc) {
M
Matt Pharr 已提交
606
    ParameterDictionary dict(std::move(params), graphicsState.colorSpace);
M
Matt Pharr 已提交
607 608 609 610
    VERIFY_OPTIONS("Accelerator");
    accelerator = SceneEntity(name, std::move(dict), loc);
}

M
Matt Pharr 已提交
611
void BasicSceneBuilder::Integrator(const std::string &name, ParsedParameterVector params,
M
Matt Pharr 已提交
612
                                   FileLoc loc) {
M
Matt Pharr 已提交
613
    ParameterDictionary dict(std::move(params), graphicsState.colorSpace);
M
Matt Pharr 已提交
614 615 616 617 618

    VERIFY_OPTIONS("Integrator");
    integrator = SceneEntity(name, std::move(dict), loc);
}

M
Matt Pharr 已提交
619
void BasicSceneBuilder::MediumInterface(const std::string &insideName,
M
Matt Pharr 已提交
620
                                        const std::string &outsideName, FileLoc loc) {
M
Matt Pharr 已提交
621 622
    graphicsState.currentInsideMedium = insideName;
    graphicsState.currentOutsideMedium = outsideName;
M
Matt Pharr 已提交
623 624
}

M
Matt Pharr 已提交
625
void BasicSceneBuilder::Texture(const std::string &name, const std::string &type,
M
Matt Pharr 已提交
626 627
                                const std::string &texname, ParsedParameterVector params,
                                FileLoc loc) {
M
Matt Pharr 已提交
628 629
    VERIFY_WORLD("Texture");

M
Matt Pharr 已提交
630 631
    ParameterDictionary dict(std::move(params), graphicsState.textureAttributes,
                             graphicsState.colorSpace);
M
Matt Pharr 已提交
632 633 634 635 636 637 638

    if (type != "float" && type != "spectrum") {
        ErrorExitDeferred(
            &loc, "%s: texture type unknown. Must be \"float\" or \"spectrum\".", type);
        return;
    }

639 640 641
    std::set<std::string> &names =
        (type == "float") ? floatTextureNames : spectrumTextureNames;
    if (names.find(name) != names.end()) {
642 643 644
        ErrorExitDeferred(&loc, "Redefining texture \"%s\".", name);
        return;
    }
645
    names.insert(name);
M
Matt Pharr 已提交
646

M
Matt Pharr 已提交
647
    if (type == "float")
M
Matt Pharr 已提交
648
        scene->AddFloatTexture(
M
Matt Pharr 已提交
649 650
            name, TextureSceneEntity(texname, std::move(dict), loc, RenderFromObject()));
    else
M
Matt Pharr 已提交
651
        scene->AddSpectrumTexture(
M
Matt Pharr 已提交
652
            name, TextureSceneEntity(texname, std::move(dict), loc, RenderFromObject()));
M
Matt Pharr 已提交
653 654
}

M
Matt Pharr 已提交
655
void BasicSceneBuilder::Material(const std::string &name, ParsedParameterVector params,
M
Matt Pharr 已提交
656
                                 FileLoc loc) {
M
Matt Pharr 已提交
657
    VERIFY_WORLD("Material");
M
Matt Pharr 已提交
658

M
Matt Pharr 已提交
659 660
    ParameterDictionary dict(std::move(params), graphicsState.materialAttributes,
                             graphicsState.colorSpace);
M
Matt Pharr 已提交
661 662

    graphicsState.currentMaterialIndex =
M
Matt Pharr 已提交
663
        scene->AddMaterial(SceneEntity(name, std::move(dict), loc));
M
Matt Pharr 已提交
664
    graphicsState.currentMaterialName.clear();
M
Matt Pharr 已提交
665 666
}

M
Matt Pharr 已提交
667
void BasicSceneBuilder::MakeNamedMaterial(const std::string &name,
M
Matt Pharr 已提交
668
                                          ParsedParameterVector params, FileLoc loc) {
M
Matt Pharr 已提交
669 670
    VERIFY_WORLD("MakeNamedMaterial");

M
Matt Pharr 已提交
671 672
    ParameterDictionary dict(std::move(params), graphicsState.materialAttributes,
                             graphicsState.colorSpace);
M
Matt Pharr 已提交
673

674
    if (namedMaterialNames.find(name) != namedMaterialNames.end()) {
675 676 677
        ErrorExitDeferred(&loc, "%s: named material redefined.", name);
        return;
    }
678
    namedMaterialNames.insert(name);
M
Matt Pharr 已提交
679

M
Matt Pharr 已提交
680
    scene->AddNamedMaterial(name, SceneEntity("", std::move(dict), loc));
M
Matt Pharr 已提交
681 682
}

M
Matt Pharr 已提交
683
void BasicSceneBuilder::NamedMaterial(const std::string &name, FileLoc loc) {
M
Matt Pharr 已提交
684
    VERIFY_WORLD("NamedMaterial");
M
Matt Pharr 已提交
685 686
    graphicsState.currentMaterialName = name;
    graphicsState.currentMaterialIndex = -1;
M
Matt Pharr 已提交
687 688
}

M
Matt Pharr 已提交
689
void BasicSceneBuilder::AreaLightSource(const std::string &name,
M
Matt Pharr 已提交
690
                                        ParsedParameterVector params, FileLoc loc) {
M
Matt Pharr 已提交
691
    VERIFY_WORLD("AreaLightSource");
M
Matt Pharr 已提交
692 693 694 695
    graphicsState.areaLightName = name;
    graphicsState.areaLightParams = ParameterDictionary(
        std::move(params), graphicsState.lightAttributes, graphicsState.colorSpace);
    graphicsState.areaLightLoc = loc;
M
Matt Pharr 已提交
696 697
}

M
Matt Pharr 已提交
698
// BasicScene Method Definitions
M
Matt Pharr 已提交
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
void BasicScene::SetSampler(SceneEntity sampler) {
    this->sampler = std::move(sampler);
}

void BasicScene::AddMedium(TransformedSceneEntity medium) {
    std::lock_guard<std::mutex> lock(mediaMutex);
    // Define _create_ lambda function for _Medium_ creation
    auto create = [=]() {
        std::string type = medium.parameters.GetOneString("type", "");
        // Check for missing medium ``type'' or animated medium transform
        if (type.empty())
            ErrorExit(&medium.loc, "No parameter string \"type\" found for medium.");
        if (medium.renderFromObject.IsAnimated())
            Warning(&medium.loc, "Animated transformation provided for medium. Only the "
                                 "start transform will be used.");

        return Medium::Create(type, medium.parameters,
                              medium.renderFromObject.startTransform, &medium.loc,
                              threadAllocators.Get());
    };

    mediaFutures[medium.name] = RunAsync(create);
}

std::map<std::string, Medium> BasicScene::CreateMedia() {
    std::lock_guard<std::mutex> lock(mediaMutex);
    // Consume futures for asynchronously-created _Medium_ objects
    LOG_VERBOSE("Consume media futures start");
    for (auto &m : mediaFutures) {
        CHECK(mediaMap.find(m.first) == mediaMap.end());
        mediaMap[m.first] = m.second.Get();
    }
    mediaFutures.clear();
    LOG_VERBOSE("Consume media futures finished");

    return mediaMap;
}

Sampler BasicScene::CreateSampler(Point2i res) const {
    Allocator alloc = threadAllocators.Get();
    return Sampler::Create(sampler.name, sampler.parameters, res, &sampler.loc, alloc);
}

Filter BasicScene::CreateFilter() const {
    Allocator alloc = threadAllocators.Get();
    return Filter::Create(filter.name, filter.parameters, &filter.loc, alloc);
}

Film BasicScene::CreateFilm(Float exposureTime, Filter filter) const {
    Allocator alloc = threadAllocators.Get();
    return Film::Create(film.name, film.parameters, exposureTime, camera.cameraTransform,
                        filter, &film.loc, alloc);
}

Camera BasicScene::CreateCamera(Medium cameraMedium, Film film) const {
    Allocator alloc = threadAllocators.Get();
    return Camera::Create(camera.name, camera.parameters, cameraMedium,
                          camera.cameraTransform, film, &camera.loc, alloc);
}

std::unique_ptr<Integrator> BasicScene::CreateIntegrator(
    Camera camera, Sampler sampler, Primitive accel, std::vector<Light> lights) const {
    const RGBColorSpace *integratorColorSpace = film.parameters.ColorSpace();
    return Integrator::Create(integrator.name, integrator.parameters, camera, sampler,
                              accel, lights, integratorColorSpace, &integrator.loc);
}

M
Matt Pharr 已提交
766
BasicScene::BasicScene()
767 768 769
    : threadAllocators([]() {
          pstd::pmr::memory_resource *baseResource = pstd::pmr::get_default_resource();
#ifdef PBRT_BUILD_GPU_RENDERER
M
Matt Pharr 已提交
770
          if (Options->useGPU)
771 772 773 774 775 776 777
              baseResource = &CUDATrackedMemoryResource::singleton;
#endif
          pstd::pmr::monotonic_buffer_resource *resource =
              new pstd::pmr::monotonic_buffer_resource(1024 * 1024, baseResource);
          return Allocator(resource);
      }) {
}
778

M
Matt Pharr 已提交
779
void BasicScene::SetFilm(SceneEntity film) {
M
Matt Pharr 已提交
780 781 782
    this->film = std::move(film);
}

M
Matt Pharr 已提交
783
void BasicScene::SetIntegrator(SceneEntity integrator) {
M
Matt Pharr 已提交
784 785 786
    this->integrator = std::move(integrator);
}

M
Matt Pharr 已提交
787
void BasicScene::SetFilter(SceneEntity filter) {
M
Matt Pharr 已提交
788 789 790
    this->filter = std::move(filter);
}

M
Matt Pharr 已提交
791
void BasicScene::SetAccelerator(SceneEntity accelerator) {
M
Matt Pharr 已提交
792 793 794
    this->accelerator = std::move(accelerator);
}

M
Matt Pharr 已提交
795
void BasicScene::SetCamera(CameraSceneEntity camera) {
M
Matt Pharr 已提交
796 797 798
    this->camera = std::move(camera);
}

M
Matt Pharr 已提交
799
void BasicScene::AddNamedMaterial(std::string name, SceneEntity material) {
800 801
    std::lock_guard<std::mutex> lock(materialMutex);
    startLoadingNormalMaps(material.parameters);
M
Matt Pharr 已提交
802 803 804
    namedMaterials.push_back(std::make_pair(std::move(name), std::move(material)));
}

M
Matt Pharr 已提交
805
int BasicScene::AddMaterial(SceneEntity material) {
M
Matt Pharr 已提交
806 807
    std::lock_guard<std::mutex> lock(materialMutex);
    materials.push_back(std::move(material));
808
    startLoadingNormalMaps(material.parameters);
M
Matt Pharr 已提交
809 810 811
    return materials.size() - 1;
}

M
Matt Pharr 已提交
812
void BasicScene::startLoadingNormalMaps(const ParameterDictionary &parameters) {
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
    std::string filename = parameters.GetOneString("normalmap", "");
    if (filename.empty())
        return;

    // Overload materialMutex, which we already hold, for the futures...
    if (normalMapFutures.find(filename) != normalMapFutures.end())
        // It's already in flight.
        return;

    auto create = [=](std::string filename) {
        Allocator alloc = threadAllocators.Get();
        ImageAndMetadata immeta =
            Image::Read(filename, Allocator(), ColorEncoding::Linear);
        Image &image = immeta.image;
        ImageChannelDesc rgbDesc = image.GetChannelDesc({"R", "G", "B"});
        if (!rgbDesc)
            ErrorExit("%s: normal map image must contain R, G, and B channels", filename);
        Image *normalMap = alloc.new_object<Image>(alloc);
        *normalMap = image.SelectChannels(rgbDesc);

        return normalMap;
    };
    normalMapFutures[filename] = RunAsync(create, filename);
}

M
Matt Pharr 已提交
838
void BasicScene::AddFloatTexture(std::string name, TextureSceneEntity texture) {
839
    if (texture.renderFromObject.IsAnimated())
840 841
        Warning(&texture.loc, "Animated world to texture transforms are not supported. "
                              "Using start transform.");
842 843

    std::lock_guard<std::mutex> lock(textureMutex);
M
Matt Pharr 已提交
844
    if (texture.name != "imagemap" && texture.name != "ptex") {
845 846
        serialFloatTextures.push_back(
            std::make_pair(std::move(name), std::move(texture)));
847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862
        return;
    }

    std::string filename =
        ResolveFilename(texture.parameters.GetOneString("filename", ""));
    if (filename.empty()) {
        Error(&texture.loc, "\"string filename\" not provided for image texture.");
        ++nMissingTextures;
        return;
    }
    if (!FileExists(filename)) {
        Error(&texture.loc, "%s: file not found.", filename);
        ++nMissingTextures;
        return;
    }

863 864 865
    if (loadingTextureFilenames.find(filename) != loadingTextureFilenames.end()) {
        serialFloatTextures.push_back(
            std::make_pair(std::move(name), std::move(texture)));
866 867 868 869 870 871 872 873 874 875 876
        return;
    }
    loadingTextureFilenames.insert(filename);

    auto create = [=](TextureSceneEntity texture) {
        Allocator alloc = threadAllocators.Get();

        pbrt::Transform renderFromTexture = texture.renderFromObject.startTransform;
        // Pass nullptr for the textures, since they shouldn't be accessed
        // anyway.
        TextureParameterDictionary texDict(&texture.parameters, nullptr);
M
Matt Pharr 已提交
877
        return FloatTexture::Create(texture.name, renderFromTexture, texDict,
878
                                    &texture.loc, alloc, Options->useGPU);
879 880
    };
    floatTextureFutures[name] = RunAsync(create, texture);
M
Matt Pharr 已提交
881 882
}

M
Matt Pharr 已提交
883
void BasicScene::AddSpectrumTexture(std::string name, TextureSceneEntity texture) {
884 885
    std::lock_guard<std::mutex> lock(textureMutex);

M
Matt Pharr 已提交
886
    if (texture.name != "imagemap" && texture.name != "ptex") {
887 888
        serialSpectrumTextures.push_back(
            std::make_pair(std::move(name), std::move(texture)));
889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904
        return;
    }

    std::string filename =
        ResolveFilename(texture.parameters.GetOneString("filename", ""));
    if (filename.empty()) {
        Error(&texture.loc, "\"string filename\" not provided for image texture.");
        ++nMissingTextures;
        return;
    }
    if (!FileExists(filename)) {
        Error(&texture.loc, "%s: file not found.", filename);
        ++nMissingTextures;
        return;
    }

905 906 907
    if (loadingTextureFilenames.find(filename) != loadingTextureFilenames.end()) {
        serialSpectrumTextures.push_back(
            std::make_pair(std::move(name), std::move(texture)));
908 909 910 911 912 913 914 915 916 917 918 919 920 921
        return;
    }
    loadingTextureFilenames.insert(filename);

    asyncSpectrumTextures.push_back(std::make_pair(name, texture));

    auto create = [=](TextureSceneEntity texture) {
        Allocator alloc = threadAllocators.Get();

        pbrt::Transform renderFromTexture = texture.renderFromObject.startTransform;
        // nullptr for the textures, as with float textures.
        TextureParameterDictionary texDict(&texture.parameters, nullptr);
        // Only create SpectrumType::Albedo for now; will get the other two
        // types in CreateTextures().
M
Matt Pharr 已提交
922
        return SpectrumTexture::Create(texture.name, renderFromTexture, texDict,
923 924 925 926
                                       SpectrumType::Albedo, &texture.loc, alloc,
                                       Options->useGPU);
    };
    spectrumTextureFutures[name] = RunAsync(create, texture);
M
Matt Pharr 已提交
927 928
}

M
Matt Pharr 已提交
929
void BasicScene::AddLight(LightSceneEntity light) {
M
Matt Pharr 已提交
930
    std::lock_guard<std::mutex> lock(lightMutex);
931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954
    if (!light.medium.empty()) {
        // If the light has a medium associated with it, punt for now since
        // the Medium may not yet be initialized; these lights will be
        // taken care of when CreateLights() is called.  At the cost of
        // some complexity, we could check and see if it's already in the
        // medium map and wait for its in-flight future if it's not yet
        // ready, though the most important case here is probably infinite
        // image lights and those can't have media associated with them
        // anyway...
        lightsWithMedia.push_back(std::move(light));
        return;
    }

    if (light.renderFromObject.IsAnimated())
        Warning(&light.loc,
                "Animated lights aren't supported. Using the start transform.");

    auto create = [this](LightSceneEntity light) {
        return Light::Create(light.name, light.parameters,
                             light.renderFromObject.startTransform,
                             camera.cameraTransform, nullptr /* Medium */, &light.loc,
                             threadAllocators.Get());
    };
    lightFutures.push_back(RunAsync(create, light));
M
Matt Pharr 已提交
955 956
}

M
Matt Pharr 已提交
957
int BasicScene::AddAreaLight(SceneEntity light) {
M
Matt Pharr 已提交
958 959 960 961 962
    std::lock_guard<std::mutex> lock(areaLightMutex);
    areaLights.push_back(std::move(light));
    return areaLights.size() - 1;
}

M
Matt Pharr 已提交
963
void BasicScene::AddShapes(pstd::span<ShapeSceneEntity> s) {
M
Matt Pharr 已提交
964 965 966 967
    std::lock_guard<std::mutex> lock(shapeMutex);
    std::move(std::begin(s), std::end(s), std::back_inserter(shapes));
}

M
Matt Pharr 已提交
968
void BasicScene::AddAnimatedShape(AnimatedShapeSceneEntity shape) {
M
Matt Pharr 已提交
969 970 971 972
    std::lock_guard<std::mutex> lock(animatedShapeMutex);
    animatedShapes.push_back(std::move(shape));
}

M
Matt Pharr 已提交
973
void BasicScene::AddInstanceDefinition(InstanceDefinitionSceneEntity instance) {
M
Matt Pharr 已提交
974 975 976 977 978 979 980
    InstanceDefinitionSceneEntity *def =
        new InstanceDefinitionSceneEntity(std::move(instance));

    std::lock_guard<std::mutex> lock(instanceDefinitionMutex);
    instanceDefinitions[def->name] = def;
}

M
Matt Pharr 已提交
981
void BasicScene::AddInstanceUses(pstd::span<InstanceSceneEntity> in) {
M
Matt Pharr 已提交
982 983 984 985
    std::lock_guard<std::mutex> lock(instanceUseMutex);
    std::move(std::begin(in), std::end(in), std::back_inserter(instances));
}

M
Matt Pharr 已提交
986
void BasicScene::Done() {
987
#if 0
M
Matt Pharr 已提交
988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
    // LOG_VERBOSE messages about any unused textures..
    std::set<std::string> unusedFloatTextures, unusedSpectrumTextures;
    for (const auto f : floatTextures) {
        CHECK(unusedFloatTextures.find(f.first) == unusedFloatTextures.end());
        unusedFloatTextures.insert(f.first);
    }
    for (const auto s : spectrumTextures) {
        CHECK(unusedSpectrumTextures.find(s.first) == unusedSpectrumTextures.end());
        unusedSpectrumTextures.insert(s.first);
    }

    auto checkVec = [&](const ParsedParameterVector &vec) {
        for (const ParsedParameter *p : vec) {
            if (p->type == "texture") {
                if (auto iter = unusedFloatTextures.find(p->strings[0]);
                    iter != unusedFloatTextures.end())
                    unusedFloatTextures.erase(iter);
                else if (auto iter = unusedSpectrumTextures.find(p->strings[0]);
                         iter != unusedSpectrumTextures.end())
                    unusedSpectrumTextures.erase(iter);
            }
        }
    };

    // Walk through everything that uses textures..
    for (const auto &nm : namedMaterials)
        checkVec(nm.second.parameters.GetParameterVector());
    for (const auto &m : materials)
        checkVec(m.parameters.GetParameterVector());
    for (const auto &ft : floatTextures)
        checkVec(ft.second.parameters.GetParameterVector());
    for (const auto &st : spectrumTextures)
        checkVec(st.second.parameters.GetParameterVector());
    for (const auto &s : shapes)
        checkVec(s.parameters.GetParameterVector());
    for (const auto &as : animatedShapes)
        checkVec(as.parameters.GetParameterVector());
    for (const auto &id : instanceDefinitions) {
        for (const auto &s : id.second->shapes)
            checkVec(s.parameters.GetParameterVector());
        for (const auto &as : id.second->animatedShapes)
            checkVec(as.parameters.GetParameterVector());
    }

    LOG_VERBOSE("Scene stats: %d shapes, %d animated shapes, %d instance definitions, "
1033
                "%d instance uses, %d float textures, %d spectrum textures, "
M
Matt Pharr 已提交
1034 1035
                "%d named materials, %d materials",
                shapes.size(), animatedShapes.size(), instanceDefinitions.size(),
1036
                instances.size(), floatTextures.size(),
M
Matt Pharr 已提交
1037 1038 1039 1040 1041 1042 1043
                spectrumTextures.size(), namedMaterials.size(), materials.size());

    // And complain about what's left.
    for (const std::string &s : unusedFloatTextures)
        LOG_VERBOSE("%s: float texture unused in scene", s);
    for (const std::string &s : unusedSpectrumTextures)
        LOG_VERBOSE("%s: spectrum texture unused in scene", s);
1044
#endif
M
Matt Pharr 已提交
1045 1046
}

M
Matt Pharr 已提交
1047 1048 1049
void BasicScene::CreateMaterials(const NamedTextures &textures,
                                 std::map<std::string, pbrt::Material> *namedMaterialsOut,
                                 std::vector<pbrt::Material> *materialsOut) {
1050 1051 1052 1053
    LOG_VERBOSE("Starting to consume normal map futures");
    for (auto &fut : normalMapFutures) {
        CHECK(normalMaps.find(fut.first) == normalMaps.end());
        normalMaps[fut.first] = fut.second.Get();
M
Matt Pharr 已提交
1054
    }
1055 1056
    normalMapFutures.clear();
    LOG_VERBOSE("Finished consuming normal map futures");
M
Matt Pharr 已提交
1057

M
Matt Pharr 已提交
1058 1059 1060 1061
    // Named materials
    for (const auto &nm : namedMaterials) {
        const std::string &name = nm.first;
        const SceneEntity &mtl = nm.second;
1062 1063
        Allocator alloc = threadAllocators.Get();

1064
        if (namedMaterialsOut->find(name) != namedMaterialsOut->end()) {
M
Matt Pharr 已提交
1065
            ErrorExit(&mtl.loc, "%s: trying to redefine named material.", name);
1066 1067
            continue;
        }
M
Matt Pharr 已提交
1068 1069 1070

        std::string type = mtl.parameters.GetOneString("type", "");
        if (type.empty()) {
M
Matt Pharr 已提交
1071 1072 1073
            ErrorExit(&mtl.loc,
                      "%s: \"string type\" not provided in named material's parameters.",
                      name);
M
Matt Pharr 已提交
1074 1075
            continue;
        }
M
Matt Pharr 已提交
1076

1077
        std::string fn = nm.second.parameters.GetOneString("normalmap", "");
1078
        Image *normalMap = !fn.empty() ? normalMaps[fn] : nullptr;
M
Matt Pharr 已提交
1079

1080
        TextureParameterDictionary texDict(&mtl.parameters, &textures);
1081 1082
        class Material m = Material::Create(type, texDict, normalMap, *namedMaterialsOut,
                                            &mtl.loc, alloc);
M
Matt Pharr 已提交
1083 1084 1085 1086 1087 1088
        (*namedMaterialsOut)[name] = m;
    }

    // Regular materials
    materialsOut->reserve(materials.size());
    for (const auto &mtl : materials) {
1089
        Allocator alloc = threadAllocators.Get();
M
Matt Pharr 已提交
1090
        std::string fn = mtl.parameters.GetOneString("normalmap", "");
1091
        Image *normalMap = !fn.empty() ? normalMaps[fn] : nullptr;
M
Matt Pharr 已提交
1092

1093
        TextureParameterDictionary texDict(&mtl.parameters, &textures);
1094 1095
        class Material m = Material::Create(mtl.name, texDict, normalMap,
                                            *namedMaterialsOut, &mtl.loc, alloc);
M
Matt Pharr 已提交
1096 1097 1098 1099
        materialsOut->push_back(m);
    }
}

M
Matt Pharr 已提交
1100
NamedTextures BasicScene::CreateTextures() {
M
Matt Pharr 已提交
1101
    NamedTextures textures;
1102

1103 1104 1105
    if (nMissingTextures > 0)
        ErrorExit("%d missing textures", nMissingTextures);

1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
    // Consume futures
    LOG_VERBOSE("Starting to consume texture futures");
    for (auto &tex : floatTextureFutures)
        textures.floatTextures[tex.first] = tex.second.Get();
    for (auto &tex : spectrumTextureFutures)
        textures.albedoSpectrumTextures[tex.first] = tex.second.Get();
    LOG_VERBOSE("Finished consuming texture futures");

    LOG_VERBOSE("Starting to create remaining textures");
    Allocator alloc = threadAllocators.Get();
    // Create the other SpectrumTypes for the spectrum textures.
    for (const auto &tex : asyncSpectrumTextures) {
1118
        pbrt::Transform renderFromTexture = tex.second.renderFromObject.startTransform;
1119 1120
        // These are all image textures, so nullptr is fine for the
        // textures, as earlier.
1121
        TextureParameterDictionary texDict(&tex.second.parameters, nullptr);
M
Matt Pharr 已提交
1122

1123
        // These should be fast since they should hit the texture cache
1124
        SpectrumTexture unboundedTex = SpectrumTexture::Create(
M
Matt Pharr 已提交
1125
            tex.second.name, renderFromTexture, texDict, SpectrumType::Unbounded,
1126
            &tex.second.loc, alloc, Options->useGPU);
1127
        SpectrumTexture illumTex = SpectrumTexture::Create(
M
Matt Pharr 已提交
1128
            tex.second.name, renderFromTexture, texDict, SpectrumType::Illuminant,
1129
            &tex.second.loc, alloc, Options->useGPU);
1130

1131 1132
        textures.unboundedSpectrumTextures[tex.first] = unboundedTex;
        textures.illuminantSpectrumTextures[tex.first] = illumTex;
1133
    }
M
Matt Pharr 已提交
1134 1135

    // And do the rest serially
1136
    for (auto &tex : serialFloatTextures) {
1137
        Allocator alloc = threadAllocators.Get();
1138 1139 1140

        pbrt::Transform renderFromTexture = tex.second.renderFromObject.startTransform;
        TextureParameterDictionary texDict(&tex.second.parameters, &textures);
M
Matt Pharr 已提交
1141 1142
        FloatTexture t = FloatTexture::Create(tex.second.name, renderFromTexture, texDict,
                                              &tex.second.loc, alloc, Options->useGPU);
1143
        textures.floatTextures[tex.first] = t;
M
Matt Pharr 已提交
1144
    }
1145 1146

    for (auto &tex : serialSpectrumTextures) {
1147
        Allocator alloc = threadAllocators.Get();
M
Matt Pharr 已提交
1148

1149 1150 1151
        if (tex.second.renderFromObject.IsAnimated())
            Warning(&tex.second.loc, "Animated world to texture transform not supported. "
                                     "Using start transform.");
M
Matt Pharr 已提交
1152

1153 1154
        pbrt::Transform renderFromTexture = tex.second.renderFromObject.startTransform;
        TextureParameterDictionary texDict(&tex.second.parameters, &textures);
1155
        SpectrumTexture albedoTex = SpectrumTexture::Create(
M
Matt Pharr 已提交
1156
            tex.second.name, renderFromTexture, texDict, SpectrumType::Albedo,
1157 1158
            &tex.second.loc, alloc, Options->useGPU);
        SpectrumTexture unboundedTex = SpectrumTexture::Create(
M
Matt Pharr 已提交
1159
            tex.second.name, renderFromTexture, texDict, SpectrumType::Unbounded,
1160
            &tex.second.loc, alloc, Options->useGPU);
1161
        SpectrumTexture illumTex = SpectrumTexture::Create(
M
Matt Pharr 已提交
1162
            tex.second.name, renderFromTexture, texDict, SpectrumType::Illuminant,
1163
            &tex.second.loc, alloc, Options->useGPU);
1164 1165 1166 1167

        textures.albedoSpectrumTextures[tex.first] = albedoTex;
        textures.unboundedSpectrumTextures[tex.first] = unboundedTex;
        textures.illuminantSpectrumTextures[tex.first] = illumTex;
M
Matt Pharr 已提交
1168 1169 1170
    }

    LOG_VERBOSE("Done creating textures");
1171
    return textures;
M
Matt Pharr 已提交
1172 1173
}

M
Matt Pharr 已提交
1174
std::vector<Light> BasicScene::CreateLights(
1175
    const NamedTextures &textures,
M
Matt Pharr 已提交
1176
    std::map<int, pstd::vector<Light> *> *shapeIndexToAreaLights) {
1177 1178 1179 1180
    // Ensure that media are all ready
    (void)CreateMedia();

    auto findMedium = [this](const std::string &s, const FileLoc *loc) -> Medium {
1181 1182 1183
        if (s.empty())
            return nullptr;

1184 1185
        auto iter = mediaMap.find(s);
        if (iter == mediaMap.end())
1186 1187 1188 1189
            ErrorExit(loc, "%s: medium not defined", s);
        return iter->second;
    };

1190 1191
    Allocator alloc = threadAllocators.Get();

1192 1193 1194 1195 1196
    auto getAlphaTexture = [&](const ParameterDictionary &parameters,
                               const FileLoc *loc) -> FloatTexture {
        std::string alphaTexName = parameters.GetTexture("alpha");
        if (!alphaTexName.empty()) {
            if (auto iter = textures.floatTextures.find(alphaTexName);
1197 1198 1199 1200 1201
                iter != textures.floatTextures.end()) {
                if (Options->useGPU &&
                    !BasicTextureEvaluator().CanEvaluate({iter->second}, {}))
                    // A warning will be issued elsewhere...
                    return nullptr;
1202
                return iter->second;
1203
            } else
1204 1205 1206 1207 1208 1209 1210 1211
                ErrorExit(loc, "%s: couldn't find float texture for \"alpha\" parameter.",
                          alphaTexName);
        } else if (Float alpha = parameters.GetOneFloat("alpha", 1.f); alpha < 1.f)
            return alloc.new_object<FloatConstantTexture>(alpha);
        else
            return nullptr;
    };

1212
    LOG_VERBOSE("Starting non-future lights");
1213
    std::vector<Light> lights;
1214 1215
    // Lights with media (punted in AddLight() earlier.)
    for (const auto &light : lightsWithMedia) {
1216 1217 1218 1219
        Medium outsideMedium = findMedium(light.medium, &light.loc);
        if (light.renderFromObject.IsAnimated())
            Warning(&light.loc,
                    "Animated lights aren't supported. Using the start transform.");
1220 1221 1222
        Light l = Light::Create(light.name, light.parameters,
                                light.renderFromObject.startTransform,
                                camera.cameraTransform, outsideMedium, &light.loc, alloc);
1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235

        lights.push_back(l);
    }

    // Area Lights
    for (size_t i = 0; i < shapes.size(); ++i) {
        const auto &sh = shapes[i];

        if (sh.lightIndex == -1)
            continue;

        std::string materialName;
        if (!sh.materialName.empty()) {
1236 1237 1238
            auto iter =
                std::find_if(namedMaterials.begin(), namedMaterials.end(),
                             [&](auto iter) { return iter.first == sh.materialName; });
1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
            if (iter == namedMaterials.end())
                ErrorExit(&sh.loc, "%s: no named material defined.", sh.materialName);
            CHECK(iter->second.parameters.GetStringArray("type").size() > 0);
            materialName = iter->second.parameters.GetOneString("type", "");
        } else {
            CHECK_LT(sh.materialIndex, materials.size());
            materialName = materials[sh.materialIndex].name;
        }
        if (materialName == "interface" || materialName == "none" || materialName == "") {
            Warning(&sh.loc, "Ignoring area light specification for shape "
1249
                             "with \"interface\" material.");
1250 1251 1252
            continue;
        }

1253 1254 1255
        pstd::vector<pbrt::Shape> shapeObjects = Shape::Create(
            sh.name, sh.renderFromObject, sh.objectFromRender, sh.reverseOrientation,
            sh.parameters, textures.floatTextures, &sh.loc, alloc);
1256 1257 1258 1259 1260 1261

        FloatTexture alphaTex = getAlphaTexture(sh.parameters, &sh.loc);

        pbrt::MediumInterface mi(findMedium(sh.insideMedium, &sh.loc),
                                 findMedium(sh.outsideMedium, &sh.loc));

1262
        pstd::vector<Light> *shapeLights = new pstd::vector<Light>(alloc);
1263 1264
        const auto &areaLightEntity = areaLights[sh.lightIndex];
        for (pbrt::Shape ps : shapeObjects) {
1265 1266 1267
            Light area = Light::CreateArea(
                areaLightEntity.name, areaLightEntity.parameters, *sh.renderFromObject,
                mi, ps, alphaTex, &areaLightEntity.loc, alloc);
1268 1269 1270 1271 1272 1273
            if (area) {
                lights.push_back(area);
                shapeLights->push_back(area);
            }
        }

M
Matt Pharr 已提交
1274
        (*shapeIndexToAreaLights)[i] = shapeLights;
1275
    }
1276

1277 1278 1279 1280 1281 1282
    LOG_VERBOSE("Finished non-future lights");

    LOG_VERBOSE("Starting to consume non-area light futures");
    for (auto &fut : lightFutures)
        lights.push_back(fut.Get());
    LOG_VERBOSE("Finished consuming non-area light futures");
1283 1284 1285 1286

    return lights;
}

M
Matt Pharr 已提交
1287
Primitive BasicScene::CreateAggregate(
1288
    const NamedTextures &textures,
1289
    const std::map<int, pstd::vector<Light> *> &shapeIndexToAreaLights,
M
Matt Pharr 已提交
1290 1291 1292
    const std::map<std::string, Medium> &media,
    const std::map<std::string, pbrt::Material> &namedMaterials,
    const std::vector<pbrt::Material> &materials) {
1293
    Allocator alloc;
1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
    auto findMedium = [&media](const std::string &s, const FileLoc *loc) -> Medium {
        if (s.empty())
            return nullptr;

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

    // Primitives
    auto getAlphaTexture = [&](const ParameterDictionary &parameters,
                               const FileLoc *loc) -> FloatTexture {
        std::string alphaTexName = parameters.GetTexture("alpha");
        if (!alphaTexName.empty()) {
M
Matt Pharr 已提交
1309 1310 1311
            if (auto iter = textures.floatTextures.find(alphaTexName);
                iter != textures.floatTextures.end())
                return iter->second;
1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
            else
                ErrorExit(loc, "%s: couldn't find float texture for \"alpha\" parameter.",
                          alphaTexName);
        } else if (Float alpha = parameters.GetOneFloat("alpha", 1.f); alpha < 1.f)
            return alloc.new_object<FloatConstantTexture>(alpha);
        else
            return nullptr;
    };

    // Non-animated shapes
    auto CreatePrimitivesForShapes =
        [&](std::vector<ShapeSceneEntity> &shapes) -> std::vector<Primitive> {
        // Parallelize Shape::Create calls, which will in turn
        // parallelize PLY file loading, etc...
        pstd::vector<pstd::vector<pbrt::Shape>> shapeVectors(shapes.size());
        ParallelFor(0, shapes.size(), [&](int64_t i) {
            const auto &sh = shapes[i];
1329 1330 1331
            shapeVectors[i] = Shape::Create(
                sh.name, sh.renderFromObject, sh.objectFromRender, sh.reverseOrientation,
                sh.parameters, textures.floatTextures, &sh.loc, alloc);
1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
        });

        std::vector<Primitive> primitives;
        for (size_t i = 0; i < shapes.size(); ++i) {
            auto &sh = shapes[i];
            pstd::vector<pbrt::Shape> &shapes = shapeVectors[i];
            if (shapes.empty())
                continue;

            FloatTexture alphaTex = getAlphaTexture(sh.parameters, &sh.loc);
            sh.parameters.ReportUnused();  // do now so can grab alpha...

            pbrt::Material mtl = nullptr;
            if (!sh.materialName.empty()) {
                auto iter = namedMaterials.find(sh.materialName);
                if (iter == namedMaterials.end())
                    ErrorExit(&sh.loc, "%s: no named material defined.", sh.materialName);
                mtl = iter->second;
            } else {
                CHECK_LT(sh.materialIndex, materials.size());
                mtl = materials[sh.materialIndex];
            }

            pbrt::MediumInterface mi(findMedium(sh.insideMedium, &sh.loc),
                                     findMedium(sh.outsideMedium, &sh.loc));

            auto iter = shapeIndexToAreaLights.find(i);
            for (size_t j = 0; j < shapes.size(); ++j) {
                // Possibly create area light for shape
                Light area = nullptr;
                // Will not be present in the map if it has an "interface"
                // material...
                if (sh.lightIndex != -1 && iter != shapeIndexToAreaLights.end())
                    area = (*iter->second)[j];

M
Matt Pharr 已提交
1367
                if (!area && !mi.IsMediumTransition() && !alphaTex)
1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393
                    primitives.push_back(new SimplePrimitive(shapes[j], mtl));
                else
                    primitives.push_back(
                        new GeometricPrimitive(shapes[j], mtl, area, mi, alphaTex));
            }
            sh.parameters.FreeParameters();
            sh = ShapeSceneEntity();
        }
        return primitives;
    };

    LOG_VERBOSE("Starting shapes");
    std::vector<Primitive> primitives = CreatePrimitivesForShapes(shapes);

    shapes.clear();
    shapes.shrink_to_fit();

    // Animated shapes
    auto CreatePrimitivesForAnimatedShapes =
        [&](std::vector<AnimatedShapeSceneEntity> &shapes) -> std::vector<Primitive> {
        std::vector<Primitive> primitives;
        primitives.reserve(shapes.size());

        for (auto &sh : shapes) {
            pstd::vector<pbrt::Shape> shapes =
                Shape::Create(sh.name, sh.identity, sh.identity, sh.reverseOrientation,
1394
                              sh.parameters, textures.floatTextures, &sh.loc, alloc);
1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426
            if (shapes.empty())
                continue;

            FloatTexture alphaTex = getAlphaTexture(sh.parameters, &sh.loc);
            sh.parameters.ReportUnused();  // do now so can grab alpha...

            // Create initial shape or shapes for animated shape

            pbrt::Material mtl = nullptr;
            if (!sh.materialName.empty()) {
                auto iter = namedMaterials.find(sh.materialName);
                if (iter == namedMaterials.end())
                    ErrorExit(&sh.loc, "%s: no named material defined.", sh.materialName);
                mtl = iter->second;
            } else {
                CHECK_LT(sh.materialIndex, materials.size());
                mtl = materials[sh.materialIndex];
            }

            pbrt::MediumInterface mi(findMedium(sh.insideMedium, &sh.loc),
                                     findMedium(sh.outsideMedium, &sh.loc));

            std::vector<Primitive> prims;
            for (auto &s : shapes) {
                if (sh.lightIndex != -1) {
                    CHECK(sh.renderFromObject.IsAnimated());
                    ErrorExit(&sh.loc, "Animated area lights are not supported.");
                }

                if (!mi.IsMediumTransition() && !alphaTex)
                    prims.push_back(new SimplePrimitive(s, mtl));
                else
1427 1428
                    prims.push_back(new GeometricPrimitive(
                        s, mtl, nullptr /* area light */, mi, alphaTex));
1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457
            }

            // TODO: could try to be greedy or even segment them according
            // to same sh.renderFromObject...

            // Create single _Primitive_ for _prims_
            if (prims.size() > 1) {
                Primitive bvh = new BVHAggregate(std::move(prims));
                prims.clear();
                prims.push_back(bvh);
            }
            primitives.push_back(new AnimatedPrimitive(prims[0], sh.renderFromObject));

            sh.parameters.FreeParameters();
            sh = AnimatedShapeSceneEntity();
        }
        return primitives;
    };
    std::vector<Primitive> animatedPrimitives =
        CreatePrimitivesForAnimatedShapes(animatedShapes);
    primitives.insert(primitives.end(), animatedPrimitives.begin(),
                      animatedPrimitives.end());

    animatedShapes.clear();
    animatedShapes.shrink_to_fit();
    LOG_VERBOSE("Finished shapes");

    // Instance definitions
    LOG_VERBOSE("Starting instances");
1458
    std::map<InternedString, Primitive> instanceDefinitions;
1459
    std::mutex instanceDefinitionsMutex;
1460
    std::vector<std::map<InternedString, InstanceDefinitionSceneEntity *>::iterator>
1461 1462 1463 1464 1465 1466 1467 1468
        instanceDefinitionIterators;
    for (auto iter = this->instanceDefinitions.begin();
         iter != this->instanceDefinitions.end(); ++iter)
        instanceDefinitionIterators.push_back(iter);
    ParallelFor(0, instanceDefinitionIterators.size(), [&](int64_t i) {
        auto &inst = *instanceDefinitionIterators[i];

        std::vector<Primitive> instancePrimitives =
M
Matt Pharr 已提交
1469
            CreatePrimitivesForShapes(inst.second->shapes);
1470
        std::vector<Primitive> movingInstancePrimitives =
M
Matt Pharr 已提交
1471
            CreatePrimitivesForAnimatedShapes(inst.second->animatedShapes);
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487
        instancePrimitives.insert(instancePrimitives.end(),
                                  movingInstancePrimitives.begin(),
                                  movingInstancePrimitives.end());

        if (instancePrimitives.size() > 1) {
            Primitive bvh = new BVHAggregate(std::move(instancePrimitives));
            instancePrimitives.clear();
            instancePrimitives.push_back(bvh);
        }

        std::lock_guard<std::mutex> lock(instanceDefinitionsMutex);
        if (instancePrimitives.empty())
            instanceDefinitions[inst.first] = nullptr;
        else
            instanceDefinitions[inst.first] = instancePrimitives[0];

M
Matt Pharr 已提交
1488 1489
        delete inst.second;
        inst.second = nullptr;
1490 1491 1492 1493 1494 1495
    });

    this->instanceDefinitions.clear();

    // Instances
    for (const auto &inst : instances) {
1496
        auto iter = instanceDefinitions.find(inst.name);
1497 1498 1499
        if (iter == instanceDefinitions.end())
            ErrorExit(&inst.loc, "%s: object instance not defined", inst.name);

M
Matt Pharr 已提交
1500
        if (!iter->second)
1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518
            // empty instance
            continue;

        if (inst.renderFromInstance)
            primitives.push_back(
                new TransformedPrimitive(iter->second, inst.renderFromInstance));
        else {
            primitives.push_back(
                new AnimatedPrimitive(iter->second, *inst.renderFromInstanceAnim));
            delete inst.renderFromInstanceAnim;
        }
    }

    instances.clear();
    instances.shrink_to_fit();
    LOG_VERBOSE("Finished instances");

    // Accelerator
M
Matt Pharr 已提交
1519
    Primitive aggregate = nullptr;
1520 1521
    LOG_VERBOSE("Starting top-level accelerator");
    if (!primitives.empty())
M
Matt Pharr 已提交
1522 1523
        aggregate = CreateAccelerator(accelerator.name, std::move(primitives),
                                      accelerator.parameters);
1524
    LOG_VERBOSE("Finished top-level accelerator");
M
Matt Pharr 已提交
1525
    return aggregate;
1526 1527
}

M
Matt Pharr 已提交
1528
}  // namespace pbrt