/
Primitives.cpp
707 lines (569 loc) · 18 KB
/
Primitives.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
#include "Primitives.h"
#include <fstream>
#include "i18n.h"
#include "igroupnode.h"
#include "ientity.h"
#include "itextstream.h"
#include "iundo.h"
#include "imainframe.h"
#include "brush/BrushModule.h"
#include "brush/BrushVisit.h"
#include "patch/PatchSceneWalk.h"
#include "patch/PatchNode.h"
#include "string/string.h"
#include "brush/export/CollisionModel.h"
#include "wxutil/dialog/MessageBox.h"
#include "map/Map.h"
#include "os/fs.h"
#include "gamelib.h"
#include "ui/modelselector/ModelSelector.h"
#include "ui/texturebrowser/TextureBrowser.h"
#include "ui/brush/QuerySidesDialog.h"
#include "settings/GameManager.h"
#include "selection/shaderclipboard/ShaderClipboard.h"
#include "scenelib.h"
#include "selectionlib.h"
#include "string/case_conv.h"
#include <fmt/format.h>
#include "ModelFinder.h"
#include "xyview/GlobalXYWnd.h"
namespace selection
{
namespace algorithm
{
namespace
{
const char* const GKEY_CM_EXT = "/defaults/collisionModelExt";
const char* const GKEY_NODRAW_SHADER = "/defaults/nodrawShader";
const char* const GKEY_VISPORTAL_SHADER = "/defaults/visportalShader";
const char* const GKEY_MONSTERCLIP_SHADER = "/defaults/monsterClipShader";
const std::string ERRSTR_WRONG_SELECTION =
"Can't export, create and select a func_* entity\
containing the collision hull primitives.";
}
void forEachSelectedFaceComponent(const std::function<void(Face&)>& functor)
{
std::for_each(FaceInstance::Selection().begin(), FaceInstance::Selection().end(),
[&] (FaceInstance* instance) { functor(instance->getFace()); });
}
int selectedFaceCount()
{
return static_cast<int>(FaceInstance::Selection().size());
}
Patch& getLastSelectedPatch() {
if (GlobalSelectionSystem().getSelectionInfo().totalCount > 0 &&
GlobalSelectionSystem().getSelectionInfo().patchCount > 0)
{
// Retrieve the last selected instance
const scene::INodePtr& node = GlobalSelectionSystem().ultimateSelected();
// Try to cast it onto a patch
Patch* patch = Node_getPatch(node);
// Return or throw
if (patch != NULL) {
return *patch;
}
else {
throw selection::InvalidSelectionException(_("No patches selected."));
}
}
else {
throw selection::InvalidSelectionException(_("No patches selected."));
}
}
PatchPtrVector getSelectedPatches()
{
PatchPtrVector returnVector;
GlobalSelectionSystem().foreachPatch([&] (Patch& patch)
{
returnVector.push_back(std::static_pointer_cast<PatchNode>(patch.getPatchNode().shared_from_this()));
});
return returnVector;
}
BrushPtrVector getSelectedBrushes()
{
BrushPtrVector returnVector;
GlobalSelectionSystem().foreachBrush([&] (Brush& brush)
{
returnVector.push_back(std::static_pointer_cast<BrushNode>(brush.getBrushNode().shared_from_this()));
});
return returnVector;
}
Face& getLastSelectedFace()
{
if (selectedFaceCount() == 1)
{
return FaceInstance::Selection().back()->getFace();
}
else
{
throw selection::InvalidSelectionException(string::to_string(selectedFaceCount()));
}
}
FacePtrVector getSelectedFaces()
{
FacePtrVector vector;
// Cycle through all selected faces and fill the vector
std::for_each(FaceInstance::Selection().begin(), FaceInstance::Selection().end(),
[&] (FaceInstance* instance) { vector.push_back(&instance->getFace()); });
return vector;
}
// Try to create a CM from the selected entity
void createCMFromSelection(const cmd::ArgumentList& args) {
// Check the current selection state
const SelectionInfo& info = GlobalSelectionSystem().getSelectionInfo();
if (info.totalCount == info.entityCount && info.totalCount == 1) {
// Retrieve the node, instance and entity
const scene::INodePtr& entityNode = GlobalSelectionSystem().ultimateSelected();
// Try to retrieve the group node
scene::GroupNodePtr groupNode = Node_getGroupNode(entityNode);
// Remove the entity origin from the brushes
if (groupNode != NULL) {
groupNode->removeOriginFromChildren();
// Deselect the node
Node_setSelected(entityNode, false);
// Select all the child nodes
entityNode->foreachNode([] (const scene::INodePtr& child)->bool
{
Node_setSelected(child, true);
return true;
});
BrushPtrVector brushes = algorithm::getSelectedBrushes();
// Create a new collisionmodel on the heap using a shared_ptr
cmutil::CollisionModelPtr cm(new cmutil::CollisionModel());
// Add all the brushes to the collision model
for (std::size_t i = 0; i < brushes.size(); i++) {
cm->addBrush(brushes[i]->getBrush());
}
ui::ModelSelectorResult modelAndSkin = ui::ModelSelector::chooseModel("", false, false);
std::string basePath = GlobalGameManager().getModPath();
std::string modelPath = basePath + modelAndSkin.model;
std::string newExtension = "." + game::current::getValue<std::string>(GKEY_CM_EXT);
// Set the model string to correctly associate the clipmodel
cm->setModel(modelAndSkin.model);
try {
// create the new autosave filename by changing the extension
fs::path cmPath = os::replaceExtension(modelPath, newExtension);
// Open the stream to the output file
std::ofstream outfile(cmPath.string().c_str());
if (outfile.is_open()) {
// Insert the CollisionModel into the stream
outfile << *cm;
// Close the file
outfile.close();
rMessage() << "CollisionModel saved to " << cmPath.string() << std::endl;
}
else {
wxutil::Messagebox::ShowError(
fmt::format("Couldn't save to file: {0}", cmPath.string()));
}
}
catch (const fs::filesystem_error& f) {
rError() << "CollisionModel: " << f.what() << std::endl;
}
// De-select the child brushes
GlobalSelectionSystem().setSelectedAll(false);
// Re-add the origin to the brushes
groupNode->addOriginToChildren();
// Re-select the node
Node_setSelected(entityNode, true);
}
}
else {
wxutil::Messagebox::ShowError(
_(ERRSTR_WRONG_SELECTION.c_str()));
}
}
/**
* greebo: Functor class which creates a decal patch for each visited face instance.
*/
class DecalPatchCreator
{
int _unsuitableWindings;
typedef std::list<FaceInstance*> FaceInstanceList;
FaceInstanceList _faceInstances;
public:
DecalPatchCreator() :
_unsuitableWindings(0)
{}
void createDecals() {
for (FaceInstanceList::iterator i = _faceInstances.begin(); i != _faceInstances.end(); ++i) {
// Get the winding
const Winding& winding = (*i)->getFace().getWinding();
// Create a new decal patch
scene::INodePtr patchNode = GlobalPatchCreator(PatchDefType::Def3).createPatch();
if (patchNode == NULL) {
wxutil::Messagebox::ShowError(_("Could not create patch."));
return;
}
Patch* patch = Node_getPatch(patchNode);
assert(patch != NULL); // must not fail
// Set the tesselation of that 3x3 patch
patch->setDims(3,3);
patch->setFixedSubdivisions(true, Subdivisions(1,1));
if (winding.size() == 4)
{
// Rectangular face, set the coordinates
patch->ctrlAt(0,0).vertex = winding[0].vertex;
patch->ctrlAt(2,0).vertex = winding[1].vertex;
patch->ctrlAt(1,0).vertex = (patch->ctrlAt(0,0).vertex + patch->ctrlAt(2,0).vertex)/2;
patch->ctrlAt(0,1).vertex = (winding[0].vertex + winding[3].vertex)/2;
patch->ctrlAt(2,1).vertex = (winding[1].vertex + winding[2].vertex)/2;
patch->ctrlAt(1,1).vertex = (patch->ctrlAt(0,1).vertex + patch->ctrlAt(2,1).vertex)/2;
patch->ctrlAt(2,2).vertex = winding[2].vertex;
patch->ctrlAt(0,2).vertex = winding[3].vertex;
patch->ctrlAt(1,2).vertex = (patch->ctrlAt(2,2).vertex + patch->ctrlAt(0,2).vertex)/2;
}
else
{
// Non-rectangular face, try to find 4 vertices co-planar with the face
// We have at least 3 points, so use them
Vector3 points[4] = {
winding[0].vertex,
winding[1].vertex,
winding[2].vertex,
Vector3(0,0,0) // to be calculated
};
// Triangular patches are supported, collapse the fourth point with the third one
if (winding.size() == 3)
{
points[3] = points[2];
}
else
{
// Generic polygon, just assume a fourth point in the same plane
points[3] = points[1] + (points[0] - points[1]) + (points[2] - points[1]);
}
patch->ctrlAt(0,0).vertex = points[0];
patch->ctrlAt(2,0).vertex = points[1];
patch->ctrlAt(1,0).vertex = (patch->ctrlAt(0,0).vertex + patch->ctrlAt(2,0).vertex)/2;
patch->ctrlAt(0,1).vertex = (points[0] + points[3])/2;
patch->ctrlAt(2,1).vertex = (points[1] + points[2])/2;
patch->ctrlAt(1,1).vertex = (patch->ctrlAt(0,1).vertex + patch->ctrlAt(2,1).vertex)/2;
patch->ctrlAt(2,2).vertex = points[2];
patch->ctrlAt(0,2).vertex = points[3];
patch->ctrlAt(1,2).vertex = (patch->ctrlAt(2,2).vertex + patch->ctrlAt(0,2).vertex)/2;
}
// Use the texture in the clipboard, if it's a decal texture
Texturable& clipboard = GlobalShaderClipboard().getSource();
if (!clipboard.empty())
{
if (clipboard.getShader().find("decals") != std::string::npos)
{
patch->setShader(clipboard.getShader());
}
}
// Fit the texture on it
patch->SetTextureRepeat(1,1);
patch->FlipTexture(1);
// Insert the patch into worldspawn
scene::INodePtr worldSpawnNode = GlobalMap().findOrInsertWorldspawn();
assert(worldSpawnNode); // This must be non-NULL, otherwise we won't have faces
worldSpawnNode->addChildNode(patchNode);
// Deselect the face instance
(*i)->setSelected(SelectionSystem::eFace, false);
// Select the patch
Node_setSelected(patchNode, true);
}
}
void operator() (FaceInstance& faceInstance)
{
// Skip non-contributing faces
if (faceInstance.getFace().contributes())
{
_faceInstances.push_back(&faceInstance);
}
else
{
// Fail on this winding, de-select and skip
faceInstance.setSelected(SelectionSystem::eFace, false);
_unsuitableWindings++;
}
}
int getNumUnsuitableWindings() const
{
return _unsuitableWindings;
}
};
void createDecalsForSelectedFaces(const cmd::ArgumentList& args) {
// Sanity check
if (FaceInstance::Selection().empty())
{
wxutil::Messagebox::ShowError(_("No faces selected."));
return;
}
// Create a scoped undocmd object
UndoableCommand cmd("createDecalsForSelectedFaces");
// greebo: For each face, create a patch with fixed tesselation
DecalPatchCreator creator;
std::for_each(FaceInstance::Selection().begin(), FaceInstance::Selection().end(),
[&] (FaceInstance* instance) { creator.operator()(*instance); });
// Issue the command
creator.createDecals();
// Check how many faces were not suitable
int unsuitableWindings = creator.getNumUnsuitableWindings();
if (unsuitableWindings > 0) {
wxutil::Messagebox::ShowError(
fmt::format(_("{0:d} faces were not suitable (had more than 4 vertices)."), unsuitableWindings)
);
}
}
void makeVisportal(const cmd::ArgumentList& args)
{
BrushPtrVector brushes = getSelectedBrushes();
if (brushes.size() <= 0)
{
wxutil::Messagebox::ShowError(_("No brushes selected."));
return;
}
// Create a scoped undocmd object
UndoableCommand cmd("brushMakeVisportal");
for (std::size_t i = 0; i < brushes.size(); i++)
{
Brush& brush = brushes[i]->getBrush();
// don't allow empty brushes
if (brush.getNumFaces() == 0) continue;
// Set all faces to nodraw first
brush.setShader(game::current::getValue<std::string>(GKEY_NODRAW_SHADER));
// Find the largest face (in terms of area)
Face* largestFace = NULL;
float largestArea = 0;
brush.forEachFace([&] (Face& face)
{
if (largestFace == NULL)
{
largestFace = &face;
}
// Calculate face area
float area = 0;
Winding& winding = face.getWinding();
const Vector3& centroid = face.centroid();
for (std::size_t i = 0; i < winding.size(); i++)
{
Vector3 edge1 = centroid - winding[i].vertex;
Vector3 edge2 = centroid - winding[(i+1) % winding.size()].vertex;
area += edge1.crossProduct(edge2).getLength() * 0.5f;
}
if (area > largestArea)
{
largestArea = area;
largestFace = &face;
}
});
// We don't allow empty brushes so face must be non-NULL at this point
assert(largestFace != NULL);
largestFace->setShader(game::current::getValue<std::string>(GKEY_VISPORTAL_SHADER));
}
}
void surroundWithMonsterclip(const cmd::ArgumentList& args)
{
UndoableCommand command("addMonsterclip");
// create a ModelFinder and retrieve the modelList
ModelFinder visitor;
GlobalSelectionSystem().foreachSelected(visitor);
// Retrieve the list with all the found models from the visitor
auto list = visitor.getList();
for (const auto& model : list)
{
// retrieve the AABB
AABB brushAABB(model->worldAABB());
// create the brush
scene::INodePtr brushNode(GlobalBrushCreator().createBrush());
brushNode->assignToLayers(model->getLayers());
if (brushNode != NULL) {
scene::addNodeToContainer(brushNode, GlobalMap().findOrInsertWorldspawn());
Brush* theBrush = Node_getBrush(brushNode);
std::string clipShader = game::current::getValue<std::string>(GKEY_MONSTERCLIP_SHADER);
resizeBrushToBounds(*theBrush, brushAABB, clipShader);
}
}
}
void resizeBrushToBounds(Brush& brush, const AABB& aabb, const std::string& shader)
{
brush.constructCuboid(aabb, shader);
SceneChangeNotify();
}
void resizeBrushesToBounds(const AABB& aabb, const std::string& shader)
{
if (GlobalSelectionSystem().getSelectionInfo().brushCount == 0)
{
wxutil::Messagebox::ShowError(_("No brushes selected."));
return;
}
GlobalSelectionSystem().foreachBrush([&] (Brush& brush)
{
brush.constructCuboid(aabb, shader);
});
SceneChangeNotify();
}
int GetViewAxis()
{
switch(GlobalXYWnd().getActiveViewType())
{
case XY:
return 2;
case XZ:
return 1;
case YZ:
return 0;
}
return 2;
}
void constructBrushPrefab(Brush& brush, EBrushPrefab type, const AABB& bounds, std::size_t sides, const std::string& shader)
{
switch(type)
{
case eBrushCuboid:
{
UndoableCommand undo("brushCuboid");
brush.constructCuboid(bounds, shader);
}
break;
case eBrushPrism:
{
int axis = GetViewAxis();
std::ostringstream command;
command << "brushPrism -sides " << sides << " -axis " << axis;
UndoableCommand undo(command.str());
brush.constructPrism(bounds, sides, axis, shader);
}
break;
case eBrushCone:
{
std::ostringstream command;
command << "brushCone -sides " << sides;
UndoableCommand undo(command.str());
brush.constructCone(bounds, sides, shader);
}
break;
case eBrushSphere:
{
std::ostringstream command;
command << "brushSphere -sides " << sides;
UndoableCommand undo(command.str());
brush.constructSphere(bounds, sides, shader);
}
break;
default:
break;
}
}
void constructBrushPrefabs(EBrushPrefab type, std::size_t sides, const std::string& shader)
{
GlobalSelectionSystem().foreachBrush([&] (Brush& brush)
{
AABB bounds = brush.localAABB(); // copy bounds because the brush will be modified
constructBrushPrefab(brush, type, bounds, sides, shader);
});
SceneChangeNotify();
}
void brushMakePrefab(const cmd::ArgumentList& args)
{
if (args.size() != 1)
{
rError() << "Usage: " << std::endl
<< "BrushMakePrefab " << eBrushCuboid << " --> cuboid " << std::endl
<< "BrushMakePrefab " << eBrushPrism << " --> prism " << std::endl
<< "BrushMakePrefab " << eBrushCone << " --> cone " << std::endl
<< "BrushMakePrefab " << eBrushSphere << " --> sphere " << std::endl;
return;
}
if (GlobalSelectionSystem().getSelectionInfo().brushCount == 0)
{
// Display a modal error dialog
wxutil::Messagebox::ShowError(_("At least one brush must be selected for this operation."));
return;
}
// First argument contains the number of sides
int input = args[0].getInt();
if (input >= eBrushCuboid && input < eNumPrefabTypes)
{
// Boundary checks passed
EBrushPrefab type = static_cast<EBrushPrefab>(input);
int minSides = 3;
int maxSides = static_cast<int>(Brush::PRISM_MAX_SIDES);
const std::string& shader = GlobalTextureBrowser().getSelectedShader();
switch (type)
{
case eBrushCuboid:
// Cuboids don't need to query the number of sides
constructBrushPrefabs(type, 0, shader);
return;
case eBrushPrism:
minSides = static_cast<int>(Brush::PRISM_MIN_SIDES);
maxSides = static_cast<int>(Brush::PRISM_MAX_SIDES);
break;
case eBrushCone:
minSides = static_cast<int>(Brush::CONE_MIN_SIDES);
maxSides = static_cast<int>(Brush::CONE_MAX_SIDES);
break;
case eBrushSphere:
minSides = static_cast<int>(Brush::SPHERE_MIN_SIDES);
maxSides = static_cast<int>(Brush::SPHERE_MAX_SIDES);
break;
default:
maxSides = 9999;
};
int sides = ui::QuerySidesDialog::QueryNumberOfSides(minSides, maxSides);
if (sides != -1)
{
constructBrushPrefabs(type, sides, shader);
}
}
else
{
rError() << "BrushMakePrefab: invalid prefab type. Allowed types are: " << std::endl
<< eBrushCuboid << " = cuboid " << std::endl
<< eBrushPrism << " = prism " << std::endl
<< eBrushCone << " = cone " << std::endl
<< eBrushSphere << " = sphere " << std::endl;
}
}
void brushMakeSided(const cmd::ArgumentList& args)
{
if (args.size() != 1)
{
rError() << "Usage: BrushMakeSided <numSides>" << std::endl;
return;
}
// First argument contains the number of sides
int input = args[0].getInt();
if (input < 0)
{
rError() << "BrushMakeSide: invalid number of sides: " << input << std::endl;
return;
}
std::size_t numSides = static_cast<std::size_t>(input);
constructBrushPrefabs(eBrushPrism, numSides, GlobalTextureBrowser().getSelectedShader());
}
void brushSetDetailFlag(const cmd::ArgumentList& args)
{
if (args.size() != 1)
{
rError() << "Usage: BrushSetDetailFlag [detail|structural]" << std::endl;
return;
}
// First argument contains the number of sides
std::string arg = string::to_lower_copy(args[0].getString());
if (arg == "detail")
{
UndoableCommand undo("BrushMakeDetail");
GlobalSelectionSystem().foreachBrush([&] (Brush& brush)
{
brush.setDetailFlag(IBrush::Detail);
});
}
else if (arg == "structural")
{
UndoableCommand undo("BrushMakeStructural");
GlobalSelectionSystem().foreachBrush([&] (Brush& brush)
{
brush.setDetailFlag(IBrush::Structural);
});
}
else
{
rError() << "Usage: BrushMakeDetail [detail|structural]" << std::endl;
}
}
} // namespace algorithm
} // namespace selection