-
Notifications
You must be signed in to change notification settings - Fork 227
/
MapDocument.cpp
5226 lines (4561 loc) · 149 KB
/
MapDocument.cpp
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
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (C) 2010-2017 Kristian Duske
This file is part of TrenchBroom.
TrenchBroom is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
TrenchBroom is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with TrenchBroom. If not, see <http://www.gnu.org/licenses/>.
*/
#include "View/MapDocument.h"
#include "Assets/AssetUtils.h"
#include "Assets/EntityDefinition.h"
#include "Assets/EntityDefinitionFileSpec.h"
#include "Assets/EntityDefinitionGroup.h"
#include "Assets/EntityDefinitionManager.h"
#include "Assets/EntityModelManager.h"
#include "Assets/Texture.h"
#include "Assets/TextureManager.h"
#include "EL/ELExceptions.h"
#include "Error.h"
#include "Exceptions.h"
#include "IO/DiskFileSystem.h"
#include "IO/DiskIO.h"
#include "IO/ExportOptions.h"
#include "IO/GameConfigParser.h"
#include "IO/PathInfo.h"
#include "IO/SimpleParserStatus.h"
#include "IO/SystemPaths.h"
#include "Model/BezierPatch.h"
#include "Model/Brush.h"
#include "Model/BrushBuilder.h"
#include "Model/BrushFace.h"
#include "Model/BrushGeometry.h"
#include "Model/BrushNode.h"
#include "Model/ChangeBrushFaceAttributesRequest.h"
#include "Model/EditorContext.h"
#include "Model/EmptyBrushEntityValidator.h"
#include "Model/EmptyGroupValidator.h"
#include "Model/EmptyPropertyKeyValidator.h"
#include "Model/EmptyPropertyValueValidator.h"
#include "Model/Entity.h"
#include "Model/EntityNode.h"
#include "Model/EntityProperties.h"
#include "Model/Game.h"
#include "Model/GameFactory.h"
#include "Model/GroupNode.h"
#include "Model/InvalidTextureScaleValidator.h"
#include "Model/LayerNode.h"
#include "Model/LinkSourceValidator.h"
#include "Model/LinkTargetValidator.h"
#include "Model/LinkedGroupUtils.h"
#include "Model/LockState.h"
#include "Model/LongPropertyKeyValidator.h"
#include "Model/LongPropertyValueValidator.h"
#include "Model/MissingClassnameValidator.h"
#include "Model/MissingDefinitionValidator.h"
#include "Model/MissingModValidator.h"
#include "Model/MixedBrushContentsValidator.h"
#include "Model/ModelUtils.h"
#include "Model/Node.h"
#include "Model/NodeContents.h"
#include "Model/NodeQueries.h"
#include "Model/NonIntegerVerticesValidator.h"
#include "Model/PatchNode.h"
#include "Model/PointEntityWithBrushesValidator.h"
#include "Model/Polyhedron.h"
#include "Model/Polyhedron3.h"
#include "Model/PropertyKeyWithDoubleQuotationMarksValidator.h"
#include "Model/PropertyValueWithDoubleQuotationMarksValidator.h"
#include "Model/SoftMapBoundsValidator.h"
#include "Model/TagManager.h"
#include "Model/VisibilityState.h"
#include "Model/WorldBoundsValidator.h"
#include "Model/WorldNode.h"
#include "PreferenceManager.h"
#include "Preferences.h"
#include "Uuid.h"
#include "View/Actions.h"
#include "View/AddRemoveNodesCommand.h"
#include "View/BrushVertexCommands.h"
#include "View/CurrentGroupCommand.h"
#include "View/Grid.h"
#include "View/MapTextEncoding.h"
#include "View/PasteType.h"
#include "View/ReparentNodesCommand.h"
#include "View/RepeatStack.h"
#include "View/SelectionCommand.h"
#include "View/SetCurrentLayerCommand.h"
#include "View/SetLinkIdsCommand.h"
#include "View/SetLockStateCommand.h"
#include "View/SetVisibilityCommand.h"
#include "View/SwapNodeContentsCommand.h"
#include "View/TransactionScope.h"
#include "View/UpdateLinkedGroupsCommand.h"
#include "View/UpdateLinkedGroupsHelper.h"
#include "View/ViewEffectsService.h"
#include "kdl/collection_utils.h"
#include "kdl/grouped_range.h"
#include "kdl/map_utils.h"
#include "kdl/memory_utils.h"
#include "kdl/overload.h"
#include "kdl/parallel.h"
#include "kdl/result.h"
#include "kdl/result_fold.h"
#include "kdl/string_format.h"
#include "kdl/vector_set.h"
#include "kdl/vector_utils.h"
#include "vm/polygon.h"
#include "vm/util.h"
#include "vm/vec.h"
#include "vm/vec_io.h"
#include <algorithm>
#include <cassert>
#include <cstdlib> // for std::abs
#include <map>
#include <mutex>
#include <sstream>
#include <string>
#include <type_traits>
#include <unordered_map>
#include <vector>
namespace TrenchBroom::View
{
namespace
{
template <typename T>
auto collectContainingGroups(const std::vector<T*>& nodes)
{
auto result = std::vector<Model::GroupNode*>{};
Model::Node::visitAll(
nodes,
kdl::overload(
[](const Model::WorldNode*) {},
[](const Model::LayerNode*) {},
[&](Model::GroupNode* groupNode) {
if (auto* containingGroupNode = groupNode->containingGroup())
{
result.push_back(containingGroupNode);
}
},
[&](Model::EntityNode* entityNode) {
if (auto* containingGroupNode = entityNode->containingGroup())
{
result.push_back(containingGroupNode);
}
},
[&](Model::BrushNode* brushNode) {
if (auto* containingGroupNode = brushNode->containingGroup())
{
result.push_back(containingGroupNode);
}
},
[&](Model::PatchNode* patchNode) {
if (auto* containingGroupNode = patchNode->containingGroup())
{
result.push_back(containingGroupNode);
}
}));
return kdl::vec_sort_and_remove_duplicates(std::move(result));
}
std::vector<Model::GroupNode*> collectGroupsOrContainers(
const std::vector<Model::Node*>& nodes)
{
auto result = std::vector<Model::GroupNode*>{};
Model::Node::visitAll(
nodes,
kdl::overload(
[](const Model::WorldNode*) {},
[](const Model::LayerNode*) {},
[&](Model::GroupNode* groupNode) { result.push_back(groupNode); },
[&](Model::EntityNode* entityNode) {
if (auto* containingGroup = entityNode->containingGroup())
{
result.push_back(containingGroup);
}
},
[&](Model::BrushNode* brushNode) {
if (auto* containingGroup = brushNode->containingGroup())
{
result.push_back(containingGroup);
}
},
[&](Model::PatchNode* patchNode) {
if (auto* containingGroup = patchNode->containingGroup())
{
result.push_back(containingGroup);
}
}));
return kdl::vec_sort_and_remove_duplicates(std::move(result));
}
/**
* Applies the given lambda to a copy of the contents of each of the given nodes and
* returns a vector of pairs of the original node and the modified contents.
*
* The lambda L needs three overloads:
* - bool operator()(Model::Entity&);
* - bool operator()(Model::Brush&);
* - bool operator()(Model::BezierPatch&);
*
* The given node contents should be modified in place and the lambda should return true
* if it was applied successfully and false otherwise.
*
* Returns a vector of pairs which map each node to its modified contents if the lambda
* succeeded for every given node, or an empty optional otherwise.
*/
template <typename N, typename L>
std::optional<std::vector<std::pair<Model::Node*, Model::NodeContents>>>
applyToNodeContents(const std::vector<N*>& nodes, L lambda)
{
using NodeContentType = std::
variant<Model::Layer, Model::Group, Model::Entity, Model::Brush, Model::BezierPatch>;
auto newNodes = std::vector<std::pair<Model::Node*, Model::NodeContents>>{};
newNodes.reserve(nodes.size());
bool success = true;
std::transform(
std::begin(nodes), std::end(nodes), std::back_inserter(newNodes), [&](auto* node) {
NodeContentType nodeContents = node->accept(kdl::overload(
[](const Model::WorldNode* worldNode) -> NodeContentType {
return worldNode->entity();
},
[](const Model::LayerNode* layerNode) -> NodeContentType {
return layerNode->layer();
},
[](const Model::GroupNode* groupNode) -> NodeContentType {
return groupNode->group();
},
[](const Model::EntityNode* entityNode) -> NodeContentType {
return entityNode->entity();
},
[](const Model::BrushNode* brushNode) -> NodeContentType {
return brushNode->brush();
},
[](const Model::PatchNode* patchNode) -> NodeContentType {
return patchNode->patch();
}));
success = success && std::visit(lambda, nodeContents);
return std::make_pair(node, Model::NodeContents(std::move(nodeContents)));
});
return success ? std::make_optional(newNodes) : std::nullopt;
}
/**
* Applies the given lambda to a copy of the contents of each of the given nodes and swaps
* the node contents if the given lambda succeeds for all node contents.
*
* The lambda L needs three overloads:
* - bool operator()(Model::Entity&);
* - bool operator()(Model::Brush&);
* - bool operator()(Model::BezierPatch&);
*
* The given node contents should be modified in place and the lambda should return true
* if it was applied successfully and false otherwise.
*
* For each linked group in the given list of linked groups, its changes are distributed
* to the connected members of its link set.
*
* Returns true if the given lambda could be applied successfully to all node contents and
* false otherwise. If the lambda fails, then no node contents will be swapped, and the
* original nodes remain unmodified.
*/
template <typename N, typename L>
bool applyAndSwap(
MapDocument& document,
const std::string& commandName,
const std::vector<N*>& nodes,
std::vector<Model::GroupNode*> changedLinkedGroups,
L lambda)
{
if (nodes.empty())
{
return true;
}
if (auto newNodes = applyToNodeContents(nodes, std::move(lambda)))
{
return document.swapNodeContents(
commandName, std::move(*newNodes), std::move(changedLinkedGroups));
}
return false;
}
/**
* Applies the given lambda to a copy of each of the given faces.
*
* Specifically, each brush node of the given faces has its contents copied and the lambda
* applied to the copied faces. If the lambda succeeds for each face, the node contents
* are subsequently swapped.
*
* The lambda L needs to accept brush faces:
* - bool operator()(Model::BrushFace&);
*
* The given node contents should be modified in place and the lambda should return true
* if it was applied successfully and false otherwise.
*
* For each linked group in the given list of linked groups, its changes are distributed
* to the connected members of its link set.
*
* Returns true if the given lambda could be applied successfully to each face and false
* otherwise. If the lambda fails, then no node contents will be swapped, and the original
* nodes remain unmodified.
*/
template <typename L>
bool applyAndSwap(
MapDocument& document,
const std::string& commandName,
const std::vector<Model::BrushFaceHandle>& faces,
L lambda)
{
if (faces.empty())
{
return true;
}
auto brushes = std::unordered_map<Model::BrushNode*, Model::Brush>{};
bool success = true;
std::for_each(std::begin(faces), std::end(faces), [&](const auto& faceHandle) {
auto* brushNode = faceHandle.node();
auto it = brushes.find(brushNode);
if (it == std::end(brushes))
{
it = brushes.emplace(brushNode, brushNode->brush()).first;
}
auto& brush = it->second;
success = success && lambda(brush.face(faceHandle.faceIndex()));
});
if (success)
{
auto newNodes = std::vector<std::pair<Model::Node*, Model::NodeContents>>{};
newNodes.reserve(brushes.size());
for (auto& [brushNode, brush] : brushes)
{
newNodes.emplace_back(brushNode, Model::NodeContents(std::move(brush)));
}
auto changedLinkedGroups = collectContainingGroups(
kdl::vec_transform(newNodes, [](const auto& p) { return p.first; }));
document.swapNodeContents(
commandName, std::move(newNodes), std::move(changedLinkedGroups));
}
return success;
}
} // namespace
const vm::bbox3 MapDocument::DefaultWorldBounds(-32768.0, 32768.0);
const std::string MapDocument::DefaultDocumentName("unnamed.map");
MapDocument::MapDocument()
: m_worldBounds(DefaultWorldBounds)
, m_world(nullptr)
, m_entityDefinitionManager(std::make_unique<Assets::EntityDefinitionManager>())
, m_entityModelManager(std::make_unique<Assets::EntityModelManager>(
pref(Preferences::TextureMagFilter), pref(Preferences::TextureMinFilter), logger()))
, m_textureManager(std::make_unique<Assets::TextureManager>(
pref(Preferences::TextureMagFilter), pref(Preferences::TextureMinFilter), logger()))
, m_tagManager(std::make_unique<Model::TagManager>())
, m_editorContext(std::make_unique<Model::EditorContext>())
, m_grid(std::make_unique<Grid>(4))
, m_path(DefaultDocumentName)
, m_lastSaveModificationCount(0)
, m_modificationCount(0)
, m_currentLayer(nullptr)
, m_currentTextureName(Model::BrushFaceAttributes::NoTextureName)
, m_lastSelectionBounds(0.0, 32.0)
, m_selectionBoundsValid(true)
, m_viewEffectsService(nullptr)
, m_repeatStack(std::make_unique<RepeatStack>())
{
connectObservers();
}
MapDocument::~MapDocument()
{
if (isPointFileLoaded())
{
unloadPointFile();
}
if (isPortalFileLoaded())
{
unloadPortalFile();
}
clearWorld();
}
Logger& MapDocument::logger()
{
return *this;
}
std::shared_ptr<Model::Game> MapDocument::game() const
{
return m_game;
}
const vm::bbox3& MapDocument::worldBounds() const
{
return m_worldBounds;
}
Model::WorldNode* MapDocument::world() const
{
return m_world.get();
}
bool MapDocument::isGamePathPreference(const std::filesystem::path& path) const
{
return m_game.get() != nullptr && m_game->isGamePathPreference(path);
}
Model::LayerNode* MapDocument::currentLayer() const
{
ensure(m_currentLayer != nullptr, "currentLayer is null");
return m_currentLayer;
}
/**
* Sets the current layer immediately, without adding a Command to the undo stack.
*/
Model::LayerNode* MapDocument::performSetCurrentLayer(Model::LayerNode* currentLayer)
{
ensure(currentLayer != nullptr, "currentLayer is null");
Model::LayerNode* oldCurrentLayer = m_currentLayer;
m_currentLayer = currentLayer;
currentLayerDidChangeNotifier(m_currentLayer);
return oldCurrentLayer;
}
void MapDocument::setCurrentLayer(Model::LayerNode* currentLayer)
{
ensure(m_currentLayer != nullptr, "old currentLayer is null");
ensure(currentLayer != nullptr, "new currentLayer is null");
auto transaction = Transaction{*this, "Set Current Layer"};
while (currentGroup() != nullptr)
{
closeGroup();
}
const auto descendants = Model::collectDescendants({m_currentLayer});
downgradeShownToInherit(descendants);
downgradeUnlockedToInherit(descendants);
executeAndStore(SetCurrentLayerCommand::set(currentLayer));
transaction.commit();
}
bool MapDocument::canSetCurrentLayer(Model::LayerNode* currentLayer) const
{
return m_currentLayer != currentLayer;
}
Model::GroupNode* MapDocument::currentGroup() const
{
return m_editorContext->currentGroup();
}
Model::Node* MapDocument::currentGroupOrWorld() const
{
Model::Node* result = currentGroup();
if (result == nullptr)
{
result = m_world.get();
}
return result;
}
Model::Node* MapDocument::parentForNodes(const std::vector<Model::Node*>& nodes) const
{
if (nodes.empty())
{
// No reference nodes, so return either the current group (if open) or current layer
Model::Node* result = currentGroup();
if (result == nullptr)
{
result = currentLayer();
}
return result;
}
Model::GroupNode* parentGroup = Model::findContainingGroup(nodes.at(0));
if (parentGroup != nullptr)
{
return parentGroup;
}
Model::LayerNode* parentLayer = Model::findContainingLayer(nodes.at(0));
ensure(parentLayer != nullptr, "no parent layer");
return parentLayer;
}
Model::EditorContext& MapDocument::editorContext() const
{
return *m_editorContext;
}
Assets::EntityDefinitionManager& MapDocument::entityDefinitionManager()
{
return *m_entityDefinitionManager;
}
Assets::EntityModelManager& MapDocument::entityModelManager()
{
return *m_entityModelManager;
}
Assets::TextureManager& MapDocument::textureManager()
{
return *m_textureManager;
}
Grid& MapDocument::grid() const
{
return *m_grid;
}
Model::PointTrace* MapDocument::pointFile()
{
return m_pointFile ? &m_pointFile->trace : nullptr;
}
const Model::PortalFile* MapDocument::portalFile() const
{
return m_portalFile ? &m_portalFile->portalFile : nullptr;
}
void MapDocument::setViewEffectsService(ViewEffectsService* viewEffectsService)
{
m_viewEffectsService = viewEffectsService;
}
void MapDocument::createTagActions()
{
const auto& actionManager = ActionManager::instance();
m_tagActions = actionManager.createTagActions(m_tagManager->smartTags());
}
void MapDocument::clearTagActions()
{
m_tagActions.clear();
}
void MapDocument::createEntityDefinitionActions()
{
const auto& actionManager = ActionManager::instance();
m_entityDefinitionActions =
actionManager.createEntityDefinitionActions(m_entityDefinitionManager->definitions());
}
Result<void> MapDocument::newDocument(
const Model::MapFormat mapFormat,
const vm::bbox3& worldBounds,
std::shared_ptr<Model::Game> game)
{
info("Creating new document");
clearRepeatableCommands();
doClearCommandProcessor();
clearDocument();
return createWorld(mapFormat, worldBounds, game).transform([&]() {
loadAssets();
registerValidators();
registerSmartTags();
createTagActions();
clearModificationCount();
documentWasNewedNotifier(this);
});
}
Result<void> MapDocument::loadDocument(
const Model::MapFormat mapFormat,
const vm::bbox3& worldBounds,
std::shared_ptr<Model::Game> game,
const std::filesystem::path& path)
{
info("Loading document from " + path.string());
clearRepeatableCommands();
doClearCommandProcessor();
clearDocument();
return loadWorld(mapFormat, worldBounds, game, path).transform([&]() {
loadAssets();
registerValidators();
registerSmartTags();
createTagActions();
documentWasLoadedNotifier(this);
});
}
void MapDocument::saveDocument()
{
doSaveDocument(m_path);
}
void MapDocument::saveDocumentAs(const std::filesystem::path& path)
{
doSaveDocument(path);
}
void MapDocument::saveDocumentTo(const std::filesystem::path& path)
{
ensure(m_game.get() != nullptr, "game is null");
ensure(m_world, "world is null");
m_game->writeMap(*m_world, path).transform_error([&](const auto& e) {
error() << "Could not save document: " << e.msg;
});
}
Result<void> MapDocument::exportDocumentAs(const IO::ExportOptions& options)
{
return m_game->exportMap(*m_world, options);
}
void MapDocument::doSaveDocument(const std::filesystem::path& path)
{
saveDocumentTo(path);
setLastSaveModificationCount();
setPath(path);
documentWasSavedNotifier(this);
}
void MapDocument::clearDocument()
{
if (m_world)
{
documentWillBeClearedNotifier(this);
m_editorContext->reset();
clearSelection();
unloadAssets();
clearTagActions();
clearWorld();
clearModificationCount();
documentWasClearedNotifier(this);
}
}
MapTextEncoding MapDocument::encoding() const
{
return MapTextEncoding::Quake;
}
std::string MapDocument::serializeSelectedNodes()
{
std::stringstream stream;
m_game->writeNodesToStream(*m_world, m_selectedNodes.nodes(), stream);
return stream.str();
}
std::string MapDocument::serializeSelectedBrushFaces()
{
std::stringstream stream;
const auto faces =
kdl::vec_transform(m_selectedBrushFaces, [](const auto& h) { return h.face(); });
m_game->writeBrushFacesToStream(*m_world, faces, stream);
return stream.str();
}
PasteType MapDocument::paste(const std::string& str)
{
// Try parsing as entities, then as brushes, in all compatible formats
const std::vector<Model::Node*> nodes =
m_game->parseNodes(str, m_world->mapFormat(), m_worldBounds, logger());
if (!nodes.empty())
{
if (pasteNodes(nodes))
{
return PasteType::Node;
}
return PasteType::Failed;
}
// Try parsing as brush faces
try
{
const std::vector<Model::BrushFace> faces =
m_game->parseBrushFaces(str, m_world->mapFormat(), m_worldBounds, logger());
if (!faces.empty() && pasteBrushFaces(faces))
{
return PasteType::BrushFace;
}
}
catch (const ParserException& e)
{
error() << "Could not parse clipboard contents: " << e.what();
}
return PasteType::Failed;
}
namespace
{
auto extractNodesToPaste(const std::vector<Model::Node*>& nodes, Model::Node* parent)
{
auto nodesToDetach = std::vector<Model::Node*>{};
auto nodesToDelete = std::vector<Model::Node*>{};
auto nodesToAdd = std::map<Model::Node*, std::vector<Model::Node*>>{};
for (auto* node : nodes)
{
node->accept(kdl::overload(
[&](auto&& thisLambda, Model::WorldNode* world) {
world->visitChildren(thisLambda);
nodesToDelete.push_back(world);
},
[&](auto&& thisLambda, Model::LayerNode* layer) {
layer->visitChildren(thisLambda);
nodesToDetach.push_back(layer);
nodesToDelete.push_back(layer);
},
[&](Model::GroupNode* group) {
nodesToDetach.push_back(group);
nodesToAdd[parent].push_back(group);
},
[&](auto&& thisLambda, Model::EntityNode* entityNode) {
if (Model::isWorldspawn(entityNode->entity().classname()))
{
entityNode->visitChildren(thisLambda);
nodesToDetach.push_back(entityNode);
nodesToDelete.push_back(entityNode);
}
else
{
nodesToDetach.push_back(entityNode);
nodesToAdd[parent].push_back(entityNode);
}
},
[&](Model::BrushNode* brush) {
nodesToDetach.push_back(brush);
nodesToAdd[parent].push_back(brush);
},
[&](Model::PatchNode* patch) {
nodesToDetach.push_back(patch);
nodesToAdd[parent].push_back(patch);
}));
}
for (auto* node : nodesToDetach)
{
if (auto* nodeParent = node->parent())
{
nodeParent->removeChild(node);
}
}
kdl::vec_clear_and_delete(nodesToDelete);
return nodesToAdd;
}
std::vector<Model::IdType> allPersistentGroupIds(const Model::Node& root)
{
auto result = std::vector<Model::IdType>{};
root.accept(kdl::overload(
[](auto&& thisLambda, const Model::WorldNode* worldNode) {
worldNode->visitChildren(thisLambda);
},
[](auto&& thisLambda, const Model::LayerNode* layerNode) {
layerNode->visitChildren(thisLambda);
},
[&](auto&& thisLambda, const Model::GroupNode* groupNode) {
if (const auto persistentId = groupNode->persistentId())
{
result.push_back(*persistentId);
}
groupNode->visitChildren(thisLambda);
},
[](const Model::EntityNode*) {},
[](const Model::BrushNode*) {},
[](const Model::PatchNode*) {}));
return result;
}
void fixRedundantPersistentIds(
const std::map<Model::Node*, std::vector<Model::Node*>>& nodesToAdd,
const std::vector<Model::IdType>& existingPersistentGroupIds)
{
auto persistentGroupIds = kdl::vector_set{existingPersistentGroupIds};
for (auto& [newParent, nodesToAddToParent] : nodesToAdd)
{
for (auto* node : nodesToAddToParent)
{
node->accept(kdl::overload(
[&](auto&& thisLambda, Model::WorldNode* worldNode) {
worldNode->visitChildren(thisLambda);
},
[&](auto&& thisLambda, Model::LayerNode* layerNode) {
layerNode->visitChildren(thisLambda);
},
[&](auto&& thisLambda, Model::GroupNode* groupNode) {
if (const auto persistentGroupId = groupNode->persistentId())
{
if (!persistentGroupIds.insert(*persistentGroupId).second)
{
// a group with this ID is already in the map or being pasted
groupNode->resetPersistentId();
}
}
groupNode->visitChildren(thisLambda);
},
[](Model::EntityNode*) {},
[](Model::BrushNode*) {},
[](Model::PatchNode*) {}));
}
}
}
void fixRecursiveLinkedGroups(
const std::map<Model::Node*, std::vector<Model::Node*>>& nodesToAdd, Logger& logger)
{
for (auto& [newParent, nodesToAddToParent] : nodesToAdd)
{
const auto linkedGroupIds =
kdl::vec_sort(Model::collectParentLinkedGroupIds(*newParent));
for (auto* node : nodesToAddToParent)
{
node->accept(kdl::overload(
[&](auto&& thisLambda, Model::WorldNode* worldNode) {
worldNode->visitChildren(thisLambda);
},
[&](auto&& thisLambda, Model::LayerNode* layerNode) {
layerNode->visitChildren(thisLambda);
},
[&](auto&& thisLambda, Model::GroupNode* groupNode) {
const auto& linkId = groupNode->linkId();
if (std::binary_search(linkedGroupIds.begin(), linkedGroupIds.end(), linkId))
{
logger.warn() << "Unlinking recursive linked group with ID '" << linkId
<< "'";
auto group = groupNode->group();
group.setTransformation(vm::mat4x4d::identity());
groupNode->setGroup(std::move(group));
groupNode->setLinkId(generateUuid());
}
groupNode->visitChildren(thisLambda);
},
[](Model::EntityNode*) {},
[](Model::BrushNode*) {},
[](Model::PatchNode*) {}));
}
}
}
void copyAndSetLinkIds(
const std::map<Model::Node*, std::vector<Model::Node*>>& nodesToAdd,
Model::WorldNode& worldNode,
Logger& logger)
{
const auto groupsToAdd = kdl::vec_sort(
Model::collectGroups(kdl::vec_flatten(kdl::map_values(nodesToAdd))),
Model::compareGroupNodesByLinkId);
const auto groupsByLinkId = kdl::make_grouped_range(
groupsToAdd,
[](const auto* lhs, const auto* rhs) { return lhs->linkId() == rhs->linkId(); });
for (const auto& linkedGroupsToAdd : groupsByLinkId)
{
const auto& linkId = linkedGroupsToAdd.front()->linkId();
const auto existingLinkedNodes = Model::collectNodesWithLinkId({&worldNode}, linkId);
if (!existingLinkedNodes.empty())
{
if (
auto* existingLinkedGroup =
dynamic_cast<Model::GroupNode*>(existingLinkedNodes.front()))
{
const auto errors = Model::copyAndSetLinkIds(
*existingLinkedGroup,
std::vector(linkedGroupsToAdd.begin(), linkedGroupsToAdd.end()));
for (const auto& error : errors)
{
logger.warn() << "Could not paste linked groups: " + error.msg;
}
}
}
}
}
} // namespace
bool MapDocument::pasteNodes(const std::vector<Model::Node*>& nodes)
{
const auto nodesToAdd = extractNodesToPaste(nodes, parentForNodes());
fixRedundantPersistentIds(nodesToAdd, allPersistentGroupIds(*m_world.get()));
fixRecursiveLinkedGroups(nodesToAdd, *this);
copyAndSetLinkIds(nodesToAdd, *m_world, *this);
auto transaction = Transaction{*this, "Paste Nodes"};
const auto addedNodes = addNodes(nodesToAdd);
if (addedNodes.empty())
{
transaction.cancel();
return false;
}
deselectAll();
selectNodes(Model::collectSelectableNodes(addedNodes, editorContext()));
transaction.commit();
return true;
}
bool MapDocument::pasteBrushFaces(const std::vector<Model::BrushFace>& faces)
{
assert(!faces.empty());
return setFaceAttributesExceptContentFlags(faces.back().attributes());
}
void MapDocument::loadPointFile(std::filesystem::path path)
{
static_assert(
!std::is_reference<decltype(path)>::value,
"path must be passed by value because reloadPointFile() passes m_pointFilePath");
if (isPointFileLoaded())
{
unloadPointFile();
}
IO::Disk::withInputStream(path, [&](auto& stream) {
return Model::loadPointFile(stream).transform([&](auto trace) {
info() << "Loaded point file " << path;
m_pointFile = PointFile{std::move(trace), std::move(path)};
pointFileWasLoadedNotifier();
});
}).transform_error([&](auto e) {
error() << "Couldn't load portal file " << path << ": " << e.msg;
m_pointFile = {};
});
}
bool MapDocument::isPointFileLoaded() const
{
return m_pointFile != std::nullopt;
}
bool MapDocument::canReloadPointFile() const
{
return isPointFileLoaded();
}
void MapDocument::reloadPointFile()
{
assert(isPointFileLoaded());
loadPointFile(m_pointFile->path);
}
void MapDocument::unloadPointFile()
{
assert(isPointFileLoaded());
m_pointFile = std::nullopt;
info() << "Unloaded point file";
pointFileWasUnloadedNotifier();
}
void MapDocument::loadPortalFile(std::filesystem::path path)
{
static_assert(
!std::is_reference<decltype(path)>::value,
"path must be passed by value because reloadPortalFile() passes m_portalFilePath");