File: ModelExport.cpp

package info (click to toggle)
darkradiant 3.9.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 41,080 kB
  • sloc: cpp: 264,743; ansic: 10,659; python: 1,852; xml: 1,650; sh: 92; makefile: 21
file content (709 lines) | stat: -rw-r--r-- 28,462 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
#include "RadiantTest.h"

#include "imodel.h"
#include "imodelcache.h"
#include "imap.h"
#include "ieclass.h"
#include "ientity.h"
#include "ModelExportOptions.h"
#include "algorithm/Primitives.h"
#include "algorithm/Scene.h"
#include "scenelib.h"
#include "os/file.h"
#include "os/path.h"
#include "string/case_conv.h"

namespace test
{

using ModelExportTest = RadiantTest;

TEST_F(ModelExportTest, ExportPatchMesh)
{
    // Load a map with a cylinder patch
    loadMap("modelexport_patch.map");

    auto patchNode = algorithm::findFirstPatchWithMaterial(GlobalMapModule().findOrInsertWorldspawn(),
        "textures/darkmod/wood/boards/ship_hull_medium");
    EXPECT_TRUE(patchNode);

    Node_setSelected(patchNode, true);

    // Choose a file in our temp data folder
    std::string modRelativePath = "models/temp/temp_patch.lwo";

    fs::path outputFilename = _context.getTestProjectPath();
    outputFilename /= modRelativePath;
    os::makeDirectory(outputFilename.parent_path().string());

    auto exporter = GlobalModelFormatManager().getExporter("lwo");

    cmd::ArgumentList argList;

    // ExportSelectedAsModel <Path> <ExportFormat> [<ExportOrigin>] [<OriginEntityName>] [<CustomOrigin>][<SkipCaulk>][<ReplaceSelectionWithModel>][<ExportLightsAsObjects>]
    argList.push_back(outputFilename.string());
    argList.push_back(std::string("lwo"));
    argList.push_back(model::getExportOriginString(model::ModelExportOrigin::SelectionCenter)); // centerObjects
    argList.push_back(std::string()); // OriginEntityName
    argList.push_back(Vector3()); // CustomOrigin
    argList.push_back(true); // skipCaulk
    argList.push_back(false); // replaceSelectionWithModel
    argList.push_back(false); // exportLightsAsObjects

    GlobalCommandSystem().executeCommand("ExportSelectedAsModel", argList);

    auto model = GlobalModelCache().getModel(modRelativePath);

    EXPECT_TRUE(model);

    // We expect exactly the same amount of vertices as in the patch mesh
    // This ensures that no vertices have been duplicated or faces separated
    auto patch = std::dynamic_pointer_cast<IPatchNode>(patchNode);
    EXPECT_EQ(model->getVertexCount(), patch->getPatch().getTesselatedPatchMesh().vertices.size());

    // Clean up the file
    fs::remove(outputFilename);
}

// #5658: Model exporter failed to write the file if the folder doesn't exist
TEST_F(ModelExportTest, ExportFolderNotExisting)
{
    // Load a map with a cylinder patch
    loadMap("modelexport_patch.map");

    auto patchNode = algorithm::findFirstPatchWithMaterial(GlobalMapModule().findOrInsertWorldspawn(),
        "textures/darkmod/wood/boards/ship_hull_medium");
    EXPECT_TRUE(patchNode);

    Node_setSelected(patchNode, true);

    // A temporary location
    fs::path outputFolder = _context.getTemporaryDataPath();
    outputFolder /= "nonexistingfolder";

    EXPECT_FALSE(fs::exists(outputFolder)) << "Output folder shouldn't exist";

    auto exporter = GlobalModelFormatManager().getExporter("lwo");

    constexpr const char* filename = "test.lwo";
    auto outputPath = outputFolder / filename;

    EXPECT_NO_THROW(exporter->exportToPath(outputFolder.string(), filename)) << "Exporter failed to export to " << outputPath;

    EXPECT_TRUE(fs::exists(outputPath)) << "Exporter didn't create the file " << outputPath;
}

inline bool surfaceHasVertex(const model::IModelSurface& surface, const std::function<bool(const MeshVertex&)>& functor)
{
    for (int i = 0; i < surface.getNumVertices(); ++i)
    {
        if (functor(surface.getVertex(i)))
        {
            return true;
        }
    }

    return false;
}

const std::string CustomMaterialName = "custom_surface_name";
const Vector4 VertexColour1(0.1, 0.2, 0.3, 0.11);
const Vector4 VertexColour2(0.4, 0.5, 0.6, 0.12);
const Vector4 VertexColour3(0.7, 0.8, 0.9, 0.13);

inline model::ModelNodePtr getChildModelNode(const scene::INodePtr& entity)
{
    // Locate the IModel node among the entity's children
    model::ModelNodePtr model;

    entity->foreachNode([&](const scene::INodePtr& node)
    {
        if (Node_isModel(node))
        {
            model = Node_getModel(node);
        }
        return true;
    });

    return model;
}

inline void checkVertexColoursOfExportedModel(const model::IModelExporterPtr& exporter, const std::string& outputPath_)
{
    fs::path outputPath = outputPath_;
    outputPath /= "models/";
    fs::path filename = "dummy.lwo";

    EXPECT_FALSE(fs::exists(outputPath / filename)) << filename << " already exists in " << outputPath.string();

    exporter->exportToPath(outputPath.string(), filename.string());

    EXPECT_TRUE(fs::exists(outputPath / filename)) << filename << " should exists in " << outputPath.string();

    try
    {
        // Create a func_static using this new model
        auto eclass = GlobalEntityClassManager().findClass("func_static");
        auto entity = GlobalEntityModule().createEntity(eclass);

        scene::addNodeToContainer(entity, GlobalMapModule().getRoot());

        // This should assign the model node to the entity
        Node_getEntity(entity)->setKeyValue("model", "models/" + filename.string());

        // Locate the IModel node among the entity's children
        model::ModelNodePtr model = getChildModelNode(entity);

        EXPECT_TRUE(model) << "Could not locate the model node of the entity";

        EXPECT_EQ(model->getIModel().getSurfaceCount(), 1);

        const auto& surface = model->getIModel().getSurface(0);
        EXPECT_EQ(surface.getDefaultMaterial(), CustomMaterialName);

        EXPECT_EQ(surface.getNumVertices(), 3);

        // The three colours we exported need to be present in the mesh
        EXPECT_TRUE(surfaceHasVertex(surface, [&](const MeshVertex& vertex)
        {
            return math::isNear(vertex.colour, VertexColour1, 0.01);
        }));
        EXPECT_TRUE(surfaceHasVertex(surface, [&](const MeshVertex& vertex)
        {
            return math::isNear(vertex.colour, VertexColour2, 0.01);
        }));
        EXPECT_TRUE(surfaceHasVertex(surface, [&](const MeshVertex& vertex)
        {
            return math::isNear(vertex.colour, VertexColour3, 0.01);
        }));

        fs::remove(outputPath / filename);
    }
    catch (const std::exception&)
    {
        fs::remove(outputPath / filename);
        throw;
    }
}

// #5717: LWO Model exporter didn't write any vertex colours
TEST_F(ModelExportTest, LwoVertexColoursAddedByPolygon)
{
    auto exporter = GlobalModelFormatManager().getExporter("lwo");
    EXPECT_TRUE(exporter);

    // Create a few vertices with custom colours
    std::vector<model::ModelPolygon> polys;

    polys.emplace_back(model::ModelPolygon
    {
        MeshVertex(Vertex3(1,0,0), Normal3(1,0,0), TexCoord2f(1,0), VertexColour1),
        MeshVertex(Vertex3(0,1,0), Normal3(1,0,0), TexCoord2f(0,0), VertexColour2),
        MeshVertex(Vertex3(1,1,0), Normal3(1,0,0), TexCoord2f(1,0), VertexColour3)
    });

    exporter->addPolygons(CustomMaterialName, polys, Matrix4::getIdentity());

    checkVertexColoursOfExportedModel(exporter, _context.getTestProjectPath());
}

class TestModelSurface :
    public model::IIndexedModelSurface
{
public:
    std::vector<MeshVertex> vertices;
    std::vector<unsigned int> indices;

    int getNumVertices() const override
    {
        return static_cast<int>(vertices.size());
    }

    int getNumTriangles() const override
    {
        return static_cast<int>(indices.size() / 3);
    }

    const MeshVertex& getVertex(int vertexNum) const override
    {
        return vertices[vertexNum];
    }

    model::ModelPolygon getPolygon(int polygonNum) const override
    {
        return model::ModelPolygon
        {
            vertices[polygonNum * 3 + 0],
            vertices[polygonNum * 3 + 1],
            vertices[polygonNum * 3 + 2]
        };
    }

    const std::string& getDefaultMaterial() const override
    {
        return CustomMaterialName;
    }

    const std::string& getActiveMaterial() const override
    {
        return getDefaultMaterial();
    }

    const std::vector<MeshVertex>& getVertexArray() const override
    {
        return vertices;
    }

    const std::vector<unsigned int>& getIndexArray() const override
    {
        return indices;
    }

    const AABB& getSurfaceBounds() const override
    {
        static AABB aabb;
        aabb = AABB();

        for (const auto& vertex : vertices)
        {
            aabb.includePoint(vertex);
        }

        return aabb;
    }
};

TEST_F(ModelExportTest, LwoVertexColoursAddedBySurface)
{
    auto exporter = GlobalModelFormatManager().getExporter("lwo");
    EXPECT_TRUE(exporter);

    // Create a few vertices with custom colours
    TestModelSurface surface;

    surface.vertices.emplace_back(Vertex3(1, 0, 0), Normal3(1, 0, 0), TexCoord2f(1, 0), VertexColour1);
    surface.vertices.emplace_back(Vertex3(0, 1, 0), Normal3(1, 0, 0), TexCoord2f(0, 0), VertexColour2);
    surface.vertices.emplace_back(Vertex3(1, 1, 0), Normal3(1, 0, 0), TexCoord2f(1, 0), VertexColour3);
    surface.indices.push_back(0);
    surface.indices.push_back(1);
    surface.indices.push_back(2);

    exporter->addSurface(surface, Matrix4::getIdentity());

    checkVertexColoursOfExportedModel(exporter, _context.getTestProjectPath());
}

inline void runConverterCode(const std::string& inputPath, const std::string& outputPath)
{
    auto extension = string::to_upper_copy(os::getExtension(outputPath));

    EXPECT_FALSE(fs::exists(outputPath)) << outputPath << " already exists";

    // Invoke the converter code
    GlobalCommandSystem().executeCommand("ConvertModel", cmd::ArgumentList{ inputPath, outputPath, extension });

    EXPECT_TRUE(fs::exists(outputPath)) << outputPath << " should have been created";

    auto importer = GlobalModelFormatManager().getImporter(extension);
    auto exportedModel = importer->loadModelFromPath(outputPath);

    EXPECT_TRUE(exportedModel);
    EXPECT_EQ(exportedModel->getSurfaceCount(), 3);
    EXPECT_EQ(exportedModel->getVertexCount(), 180);
    EXPECT_EQ(exportedModel->getPolyCount(), 258);
}

TEST_F(ModelExportTest, ConvertLwoToAse)
{
    auto outputPath = _context.getTemporaryDataPath() + "conversiontest.ase";
    runConverterCode(_context.getTestProjectPath() + "models/torch.lwo", outputPath);
}

TEST_F(ModelExportTest, ConvertFbxToAse)
{
    auto outputPath = _context.getTemporaryDataPath() + "conversiontest.ase";
    auto extension = string::to_upper_copy(os::getExtension(outputPath));
    auto inputPath = _context.getTestResourcePath() + "fbx/test_cube.fbx";

    EXPECT_FALSE(fs::exists(outputPath)) << outputPath << " already exists";

    // Invoke the converter code
    GlobalCommandSystem().executeCommand("ConvertModel", cmd::ArgumentList{ inputPath, outputPath, extension });

    EXPECT_TRUE(fs::exists(outputPath)) << outputPath << " should have been created";

    auto importer = GlobalModelFormatManager().getImporter(extension);
    auto exportedModel = importer->loadModelFromPath(outputPath);

    EXPECT_TRUE(exportedModel) << "No FBX model has been created";
    EXPECT_EQ(exportedModel->getSurfaceCount(), 1);
    EXPECT_EQ(exportedModel->getSurface(0).getDefaultMaterial(), "phong1");
    EXPECT_EQ(exportedModel->getVertexCount(), 24);
    EXPECT_EQ(exportedModel->getPolyCount(), 12);
}

TEST_F(ModelExportTest, ConvertAseToLwo)
{
    // Convert the torch to ASE first, then back to LWO
    auto aseOutputPath = _context.getTemporaryDataPath() + "conversiontest.ase";
    runConverterCode(_context.getTestProjectPath() + "models/torch.lwo", aseOutputPath);

    auto lwoOutputPath = _context.getTemporaryDataPath() + "conversiontest.lwo";
    runConverterCode(aseOutputPath, lwoOutputPath);
}

// #5659: Exporting a model should be reloaded automatically
TEST_F(ModelExportTest, ExportedModelTriggersEntityRefresh)
{
    auto originalModelMaterial = "textures/numbers/1";
    auto changedModelMaterial = "textures/numbers/2";
    auto modRelativePath = "models/refresh_test.ase";
    auto aseOutputPath = _context.getTestProjectPath() + modRelativePath;

    auto brush = algorithm::createCubicBrush(
        GlobalMapModule().findOrInsertWorldspawn(), Vector3(0, 0, 0), originalModelMaterial);

    GlobalSelectionSystem().setSelectedAll(false);
    Node_setSelected(brush, true);

    // Export this model to the mod-relative location
    GlobalCommandSystem().executeCommand("ExportSelectedAsModel", { aseOutputPath, cmd::Argument("ase") });

    // Create two entities referencing this new model
    auto eclass = GlobalEntityClassManager().findClass("func_static");
    auto entity1 = GlobalEntityModule().createEntity(eclass);
    auto entity2 = GlobalEntityModule().createEntity(eclass);

    scene::addNodeToContainer(entity1, GlobalMapModule().getRoot());
    scene::addNodeToContainer(entity2, GlobalMapModule().getRoot());

    // This should assign the model node to the entity
    Node_getEntity(entity1)->setKeyValue("model", modRelativePath);
    Node_getEntity(entity2)->setKeyValue("model", modRelativePath);
    model::ModelNodePtr model1 = getChildModelNode(entity1);
    model::ModelNodePtr model2 = getChildModelNode(entity2);

    EXPECT_TRUE(model1) << "Could not locate the model node of the entity";
    EXPECT_TRUE(model2) << "Could not locate the model node of the entity";
    EXPECT_EQ(model1->getIModel().getSurface(0).getDefaultMaterial(), originalModelMaterial);
    EXPECT_EQ(model2->getIModel().getSurface(0).getDefaultMaterial(), originalModelMaterial);

    // Now change the brush texture and re-export the model
    Node_getIBrush(brush)->setShader(changedModelMaterial);

    GlobalSelectionSystem().setSelectedAll(false);
    Node_setSelected(brush, true);

    // Re-export this model to the mod-relative location
    GlobalCommandSystem().executeCommand("ExportSelectedAsModel", { aseOutputPath, cmd::Argument("ase") });

    // If all went well, the entity has automatically refreshed its model
    model1 = getChildModelNode(entity1);
    model2 = getChildModelNode(entity2);

    EXPECT_TRUE(model1) << "Could not locate the model node of the entity";
    EXPECT_TRUE(model2) << "Could not locate the model node of the entity";
    EXPECT_EQ(model1->getIModel().getSurface(0).getDefaultMaterial(), changedModelMaterial);
    EXPECT_EQ(model2->getIModel().getSurface(0).getDefaultMaterial(), changedModelMaterial);

    fs::remove(aseOutputPath);
}

// #5705: "Replace Selection with exported Model" should preserve spawnargs
// #5858: "Replace Selection with exported Model" sets classname to "func_static".
TEST_F(ModelExportTest, ExportedModelInheritsSpawnargs)
{
    auto modelPath = "models/torch.lwo";
    auto exportedModelPath = "models/export_test.lwo";
    auto fullModelPath = _context.getTestProjectPath() + exportedModelPath;

    // Create an entity referencing this new model, let's use a mover door
    auto eclass = GlobalEntityClassManager().findClass("atdm:mover_door");
    auto entity = GlobalEntityModule().createEntity(eclass);

    scene::addNodeToContainer(entity, GlobalMapModule().getRoot());

    // This should assign the model node to the entity
    Node_getEntity(entity)->setKeyValue("model", modelPath);

    auto brush = algorithm::createCubicBrush(
        GlobalMapModule().findOrInsertWorldspawn(), Vector3(0, 0, 0), "textures/numbers/1");

    // Add another entity, which is just around to be selected
    auto entity2 = GlobalEntityModule().createEntity(eclass);
    scene::addNodeToContainer(entity2, GlobalMapModule().getRoot());
    Node_getEntity(entity2)->setKeyValue("name", "HenryTheFifth");
    Node_getEntity(entity2)->setKeyValue("henrys_key", "henrys_value");

    // Set some spawnargs which should be preserved after export and give it a name
    Node_getEntity(entity)->setKeyValue("name", "HarryTheTorch");
    Node_getEntity(entity)->setKeyValue("dummy1", "value1");
    Node_getEntity(entity)->setKeyValue("dummy2", "value2");

    // Select the named entity as last item, it should dictate which spawnargs to preserve
    GlobalSelectionSystem().setSelectedAll(false);
    Node_setSelected(brush, true);
    Node_setSelected(entity2, true);
    Node_setSelected(entity, true);

    // Export this model to a mod-relative location

    cmd::ArgumentList argList;

    // ExportSelectedAsModel <Path> <ExportFormat> [<ExportOrigin>] [<OriginEntityName>] [<CustomOrigin>][<SkipCaulk>][<ReplaceSelectionWithModel>][<ExportLightsAsObjects>]
    argList.push_back(fullModelPath);
    argList.push_back(os::getExtension(exportedModelPath)); // lwo
    argList.push_back(model::getExportOriginString(model::ModelExportOrigin::MapOrigin)); // don't center objects
    argList.push_back(std::string()); // OriginEntityName
    argList.push_back(Vector3()); // CustomOrigin
    argList.push_back(false); // skipCaulk
    argList.push_back(true); // replaceSelectionWithModel
    argList.push_back(false); // exportLightsAsObjects

    GlobalCommandSystem().executeCommand("ExportSelectedAsModel", argList);

    // The entities and the brush should have been replaced (remove from the scene, no parent)
    EXPECT_FALSE(entity->getParent());
    EXPECT_FALSE(entity2->getParent());
    EXPECT_FALSE(brush->getParent());

    // Henry the fifth should be gone
    auto henry = algorithm::getEntityByName(GlobalMapModule().getRoot(), "HenryTheFifth");
    EXPECT_FALSE(henry);

    auto newEntityNode = algorithm::getEntityByName(GlobalMapModule().getRoot(), "HarryTheTorch");

    EXPECT_TRUE(newEntityNode) << "Could not locate the named entity after replacing it with a model";
    auto newEntity = Node_getEntity(newEntityNode);

    EXPECT_EQ(newEntity->getKeyValue("name"), "HarryTheTorch");
    EXPECT_EQ(newEntity->getKeyValue("model"), exportedModelPath);
    EXPECT_EQ(newEntity->getKeyValue("dummy1"), "value1");
    EXPECT_EQ(newEntity->getKeyValue("dummy2"), "value2");
    EXPECT_EQ(newEntity->getKeyValue("classname"), "atdm:mover_door");
    EXPECT_EQ(newEntity->getEntityClass()->getDeclName(), "atdm:mover_door");

    // This one should not have been inherited, it was belonging to the other entity
    EXPECT_EQ(newEntity->getKeyValue("henrys_key"), "");

    fs::remove(fullModelPath);
}

// #55687: "Replace Selection with exported Model" should accumulate layers of selection
TEST_F(ModelExportTest, ExportedModelInheritsLayers)
{
    auto modelPath = "models/torch.lwo";
    auto exportedModelPath = "models/export_test.lwo";
    auto fullModelPath = _context.getTestProjectPath() + exportedModelPath;

    // Create an entity referencing this new model
    auto eclass = GlobalEntityClassManager().findClass("func_static");
    auto entity = GlobalEntityModule().createEntity(eclass);

    scene::addNodeToContainer(entity, GlobalMapModule().getRoot());

    // This should assign the model node to the entity
    Node_getEntity(entity)->setKeyValue("model", modelPath);

    auto brush1 = algorithm::createCubicBrush(
        GlobalMapModule().findOrInsertWorldspawn(), Vector3(0, 0, 0), "textures/numbers/1");
    auto brush2 = algorithm::createCubicBrush(
        GlobalMapModule().findOrInsertWorldspawn(), Vector3(0, 0, 0), "textures/numbers/2");
    auto brush3 = algorithm::createCubicBrush(
        GlobalMapModule().findOrInsertWorldspawn(), Vector3(0, 0, 0), "textures/numbers/3");

    auto layer1 = GlobalMapModule().getRoot()->getLayerManager().createLayer("Layer1");
    auto layer2 = GlobalMapModule().getRoot()->getLayerManager().createLayer("Layer2");
    auto layer3 = GlobalMapModule().getRoot()->getLayerManager().createLayer("Layer3");

    // Assign the objects to a few layers
    entity->assignToLayers(scene::LayerList{ layer1, layer2 });
    brush1->assignToLayers(scene::LayerList{ layer1 });
    brush2->assignToLayers(scene::LayerList{ layer2 });
    brush3->assignToLayers(scene::LayerList{ layer3 });

    // Select the objects
    GlobalSelectionSystem().setSelectedAll(false);
    Node_setSelected(entity, true);
    Node_setSelected(brush1, true);
    Node_setSelected(brush2, true);
    Node_setSelected(brush3, true);

    // Export this model to a mod-relative location

    cmd::ArgumentList argList;

    // ExportSelectedAsModel <Path> <ExportFormat> [<ExportOrigin>] [<OriginEntityName>] [<CustomOrigin>][<SkipCaulk>][<ReplaceSelectionWithModel>][<ExportLightsAsObjects>]
    argList.push_back(fullModelPath);
    argList.push_back(os::getExtension(exportedModelPath)); // lwo
    argList.push_back(model::getExportOriginString(model::ModelExportOrigin::MapOrigin)); // don't center objects
    argList.push_back(std::string()); // OriginEntityName
    argList.push_back(Vector3()); // CustomOrigin
    argList.push_back(false); // skipCaulk
    argList.push_back(true); // replaceSelectionWithModel
    argList.push_back(false); // exportLightsAsObjects

    GlobalCommandSystem().executeCommand("ExportSelectedAsModel", argList);

    // The entities and the brush should have been replaced (remove from the scene, no parent)
    EXPECT_FALSE(entity->getParent()) << "Node should have been removed from the scene";
    EXPECT_FALSE(brush1->getParent()) << "Node should have been removed from the scene";
    EXPECT_FALSE(brush2->getParent()) << "Node should have been removed from the scene";
    EXPECT_FALSE(brush3->getParent()) << "Node should have been removed from the scene";

    EXPECT_EQ(GlobalSelectionSystem().countSelected(), 1) << "One item should be selected after export";
    auto newEntity = GlobalSelectionSystem().ultimateSelected();

    EXPECT_EQ(Node_getEntity(newEntity)->getKeyValue("model"), exportedModelPath);

    // Check the layers of this new entity, it should contain the union of all layers
    auto layers = newEntity->getLayers();
    EXPECT_EQ(layers.size(), 3) << "New model should be part of 3 layers";
    EXPECT_EQ(layers.count(layer1), 1) << "New model should be part of Layer 1";
    EXPECT_EQ(layers.count(layer2), 1) << "New model should be part of Layer 2";
    EXPECT_EQ(layers.count(layer3), 1) << "New model should be part of Layer 3";

    fs::remove(fullModelPath);
}

TEST_F(ModelExportTest, ExportUsingEntityOrigin)
{
    auto modelPath = "models/torch.lwo";
    auto exportedModelPath = "models/export_test.lwo";
    auto fullModelPath = _context.getTestProjectPath() + exportedModelPath;

    // Create an entity referencing this new model
    auto eclass = GlobalEntityClassManager().findClass("func_static");
    auto entity = GlobalEntityModule().createEntity(eclass);

    scene::addNodeToContainer(entity, GlobalMapModule().getRoot());

    // This should assign the model node to the entity
    Node_getEntity(entity)->setKeyValue("model", modelPath);
    // Offset this entity from the origin
    Node_getEntity(entity)->setKeyValue("origin", "300 400 50");

    Node_setSelected(entity, true);

    // Choose a file in our temp data folder
    std::string modRelativePath = "models/temp/temp_model_keeping_origin.lwo";

    fs::path outputFilename = _context.getTestProjectPath();
    outputFilename /= modRelativePath;
    os::makeDirectory(outputFilename.parent_path().string());

    auto exporter = GlobalModelFormatManager().getExporter("lwo");

    cmd::ArgumentList argList;

    // ExportSelectedAsModel <Path> <ExportFormat> [<ExportOrigin>] [<OriginEntityName>] [<CustomOrigin>][<SkipCaulk>][<ReplaceSelectionWithModel>][<ExportLightsAsObjects>]
    argList.push_back(outputFilename.string());
    argList.push_back(std::string("lwo"));
    argList.push_back(model::getExportOriginString(model::ModelExportOrigin::EntityOrigin)); // center objects
    argList.push_back(Node_getEntity(entity)->getKeyValue("name")); // OriginEntityName
    argList.push_back(Vector3()); // CustomOrigin
    argList.push_back(true); // skipCaulk
    argList.push_back(false); // replaceSelectionWithModel
    argList.push_back(false); // exportLightsAsObjects

    GlobalCommandSystem().executeCommand("ExportSelectedAsModel", argList);

    auto model = GlobalModelCache().getModel(modRelativePath);
    EXPECT_TRUE(model);

    // Model should be centered around the entity's origin
    auto entityOrigin = string::convert<Vector3>(entity->getEntity().getKeyValue("origin"));
    EXPECT_TRUE(math::isNear(model->localAABB().getOrigin(), entity->worldAABB().getOrigin() - entityOrigin, 0.01));
    EXPECT_TRUE(math::isNear(model->localAABB().getExtents(), entity->worldAABB().getExtents(), 0.01));

    // Clean up the file
    fs::remove(outputFilename);
}

TEST_F(ModelExportTest, ExportUsingCustomOrigin)
{
    auto modelPath = "models/torch.lwo";
    auto exportedModelPath = "models/export_test.lwo";
    auto fullModelPath = _context.getTestProjectPath() + exportedModelPath;

    // Create an entity referencing this new model
    auto eclass = GlobalEntityClassManager().findClass("func_static");
    auto entity = GlobalEntityModule().createEntity(eclass);
    scene::addNodeToContainer(entity, GlobalMapModule().getRoot());

    // This should assign the model node to the entity
    Node_getEntity(entity)->setKeyValue("model", modelPath);
    // Offset this entity from the origin
    Node_getEntity(entity)->setKeyValue("origin", "300 400 50");

    Node_setSelected(entity, true);

    // Choose a file in our temp data folder
    std::string modRelativePath = "models/temp/temp_model_keeping_origin.lwo";

    fs::path outputFilename = _context.getTestProjectPath();
    outputFilename /= modRelativePath;
    os::makeDirectory(outputFilename.parent_path().string());

    auto exporter = GlobalModelFormatManager().getExporter("lwo");

    Vector3 customOrigin(70, -17, 600);
    cmd::ArgumentList argList;

    // ExportSelectedAsModel <Path> <ExportFormat> [<ExportOrigin>] [<OriginEntityName>] [<CustomOrigin>][<SkipCaulk>][<ReplaceSelectionWithModel>][<ExportLightsAsObjects>]
    argList.push_back(outputFilename.string());
    argList.push_back(std::string("lwo"));
    argList.push_back(model::getExportOriginString(model::ModelExportOrigin::CustomOrigin)); // center objects
    argList.push_back(std::string()); // OriginEntityName
    argList.push_back(customOrigin); // CustomOrigin
    argList.push_back(true); // skipCaulk
    argList.push_back(false); // replaceSelectionWithModel
    argList.push_back(false); // exportLightsAsObjects

    GlobalCommandSystem().executeCommand("ExportSelectedAsModel", argList);

    auto model = GlobalModelCache().getModel(modRelativePath);
    EXPECT_TRUE(model);

    // Model should be centered around the custom origin
    EXPECT_TRUE(math::isNear(model->localAABB().getOrigin(), entity->worldAABB().getOrigin() - customOrigin, 0.01));
    EXPECT_TRUE(math::isNear(model->localAABB().getExtents(), entity->worldAABB().getExtents(), 0.01));

    // Clean up the file
    fs::remove(outputFilename);
}

// #5997: ExportSelectedAsCollisionModel should auto-create any necessary folders
TEST_F(ModelExportTest, ExportSelectedAsCollisionModelCreatesFolder)
{
    // Create a func_static
    auto eclass = GlobalEntityClassManager().findClass("func_static");
    auto entity = GlobalEntityModule().createEntity(eclass);
    scene::addNodeToContainer(entity, GlobalMapModule().getRoot());

    auto brush = algorithm::createCubicBrush(entity, Vector3(50, 50, 50));

    // Select just the entity
    GlobalSelectionSystem().setSelectedAll(false);
    Node_setSelected(entity, true);

    auto relativeModelPath = "models/some_folder_not_existing_outside_pk4s/testcube.ase";
    auto expectedPhysicalPath = _context.getTestProjectPath() + relativeModelPath;
    expectedPhysicalPath = os::replaceExtension(expectedPhysicalPath, "cm");

    // Make sure the folder is not there
    fs::remove_all(os::getDirectory(expectedPhysicalPath));
    EXPECT_FALSE(os::fileOrDirExists(os::getDirectory(expectedPhysicalPath))) << "Folder should not exist yet";
    EXPECT_FALSE(os::fileOrDirExists(expectedPhysicalPath)) << "Export CM should not exist yet";

    // Export the selection as collision mesh for the torch model
    GlobalCommandSystem().executeCommand("ExportSelectedAsCollisionModel", { relativeModelPath });

    // Both file and folder need to exist, just check the file
    EXPECT_TRUE(os::fileOrDirExists(expectedPhysicalPath)) << "Folder should have been created by ExportSelectedAsCollisionModel";

    // Remove the folder after the test is done
    fs::remove_all(os::getDirectory(expectedPhysicalPath));
}

}