File: RegionManager.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 (490 lines) | stat: -rw-r--r-- 13,908 bytes parent folder | download | duplicates (2)
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
#include "RegionManager.h"

#include "i18n.h"
#include "ibrush.h"
#include "icameraview.h"
#include "iorthoview.h"
#include "ientity.h"
#include "ieclass.h"
#include "imru.h"
#include "ifiletypes.h"
#include "iscenegraph.h"
#include "iselection.h"
#include "imapformat.h"

#include "scenelib.h"
#include "selectionlib.h"
#include "shaderlib.h"
#include "gamelib.h"
#include "string/string.h"

#include "registry/registry.h"
#include "brush/Brush.h"
#include "RegionWalkers.h"
#include "MapFileManager.h"
#include "selection/algorithm/Primitives.h"
#include "selection/algorithm/General.h"
#include "map/MapResource.h"
#include "map/Map.h"
#include "module/StaticModule.h"
#include "command/ExecutionFailure.h"
#include "command/ExecutionNotPossible.h"

#include <memory>

namespace map
{

namespace
{
    typedef std::shared_ptr<RegionManager> RegionManagerPtr;
    const std::string GKEY_PLAYER_START_ECLASS = "/mapFormat/playerStartPoint";
}

RegionManager::RegionManager() :
    _active(false)
{}

bool RegionManager::isEnabled() const
{
    return _active;
}

void RegionManager::disable()
{
    _active = false;

    _bounds = AABB::createFromMinMax(Vector3(1,1,1)*_worldMin, Vector3(1,1,1)*_worldMax);
    // Create a 64 unit border from the max world coord
    _bounds.extents -= Vector3(1,1,1)*64;

    if (GlobalSceneGraph().root())
    {
        // Disable the exclude bit on all the scenegraph nodes
        ExcludeAllWalker walker(false);
        GlobalSceneGraph().root()->traverse(walker);
    }
}

void RegionManager::enable() {
    if (!_bounds.isValid()) {
        return;
    }

    _active = true;

    // Show all elements within the current region / hide the outsiders
    ExcludeRegionedWalker walker(false, _bounds);
    GlobalSceneGraph().root()->traverse(walker);
}

void RegionManager::clear()
{
    for (int i = 0; i < 6; i++) {
        _brushes[i] = scene::INodePtr();
    }

    _playerStart.reset();
}

const AABB& RegionManager::getRegion() const {
    return _bounds;
}

void RegionManager::getMinMax(Vector3& regionMin, Vector3& regionMax) const {
    if (isEnabled()) {
        regionMin = _bounds.origin - _bounds.extents;
        regionMax = _bounds.origin + _bounds.extents;
    }
    else {
        // Set the region corners to the maximum available coords
        regionMin = Vector3(1,1,1)*_worldMin;
        regionMax = Vector3(1,1,1)*_worldMax;
    }
}

AABB RegionManager::getRegionBounds()
{
    if (isEnabled())
    {
        return _bounds;
    }

    // Set the region bounds to the maximum available size
    return AABB(Vector3(0, 0, 0), Vector3(_worldMax, _worldMax, _worldMax));
}

void RegionManager::setRegion(const AABB& aabb, bool autoEnable) {
    _bounds = aabb;

    if (autoEnable) {
        enable();
    }
}

void RegionManager::setRegionFromXY(Vector2 topLeft, Vector2 lowerRight) {
    // Reset the regioning before doing anything else
    disable();

    // Make sure the given coordinates are correctly sorted
    for (unsigned int i = 0; i < 2; i++) {
        if (lowerRight[i] < topLeft[i]) {
            std::swap(lowerRight[i], topLeft[i]);
        }
    }

    Vector3 min(topLeft[0], topLeft[1], _worldMin + 64);
    Vector3 max(lowerRight[0], lowerRight[1], _worldMax - 64);

    // Create an AABB out of the given vectors and set the region (enable() is triggered)
    setRegion(AABB::createFromMinMax(min, max));
}

void RegionManager::addRegionBrushes()
{
    for (int i = 0; i < 6; i++)
    {
        // Create a new brush
        _brushes[i] = GlobalBrushCreator().createBrush();

        // Insert it into worldspawn
        scene::addNodeToContainer(_brushes[i], GlobalMap().findOrInsertWorldspawn());
    }

    // Obtain the size of the region (the corners)
    Vector3 min;
    Vector3 max;
    getMinMax(min, max);

    // Construct the region brushes (use the legacy GtkRadiant method, it works...)
    constructRegionBrushes(_brushes, min, max);

    // Get the player start EClass pointer
    auto eClassPlayerStart = game::current::getValue<std::string>(GKEY_PLAYER_START_ECLASS);
    auto playerStart = GlobalEntityClassManager().findOrInsert(eClassPlayerStart, false);

    // Create the info_player_start entity
    _playerStart = GlobalEntityModule().createEntity(playerStart);

    try
    {
        auto& camView = GlobalCameraManager().getActiveView();

        // Obtain the camera origin = player start point
        Vector3 camOrigin = camView.getCameraOrigin();
        // Get the start angle of the player start point
        auto angle = camView.getCameraAngles()[camera::CAMERA_YAW];

        // Check if the camera origin is within the region
        if (!_bounds.intersects(camOrigin))
        {
            throw cmd::ExecutionFailure(
                _("Warning: Camera not within region, can't set info_player_start.")
            );
        }

        // Set the origin key of the playerStart entity
        _playerStart->getEntity().setKeyValue("origin", string::to_string(camOrigin));
        _playerStart->getEntity().setKeyValue("angle", string::to_string(angle));
    }
    catch (const cmd::ExecutionFailure& ex)
    {
        throw ex; // let this one slip through
    }
    catch (const std::runtime_error&)
    {
        // CamWnd not available, log this
        throw cmd::ExecutionFailure("Failed to read camera position.");
    }

    // Insert the info_player_start into the scenegraph root
    GlobalSceneGraph().root()->addChildNode(_playerStart);
}

void RegionManager::constructRegionBrushes(scene::INodePtr brushes[6], const Vector3& region_mins, const Vector3& region_maxs)
{
	const float THICKNESS = 10;

	{
		// set mins
		Vector3 mins(region_mins[0]-THICKNESS, region_mins[1]-THICKNESS, region_mins[2]-THICKNESS);

		// vary maxs
		for (std::size_t i = 0; i < 3; i++)
		{
			Vector3 maxs(region_maxs[0]+THICKNESS, region_maxs[1]+THICKNESS, region_maxs[2]+THICKNESS);
			maxs[i] = region_mins[i];

			Brush& brush = *Node_getBrush(brushes[i]);
			brush.constructCuboid(AABB::createFromMinMax(mins, maxs),
      							texdef_name_default());
		}
	}

	{
		// set maxs
		Vector3 maxs(region_maxs[0]+THICKNESS, region_maxs[1]+THICKNESS, region_maxs[2]+THICKNESS);

		// vary mins
		for (std::size_t i = 0; i < 3; i++)
		{
			Vector3 mins(region_mins[0]-THICKNESS, region_mins[1]-THICKNESS, region_mins[2]-THICKNESS);
			mins[i] = region_maxs[i];
			Brush& brush = *Node_getBrush(brushes[i+3]);

			brush.constructCuboid(AABB::createFromMinMax(mins, maxs),
      							texdef_name_default());
		}
	}
}

void RegionManager::removeRegionBrushes() {
    for (int i = 0; i < 6; i++) {
        // Remove the brushes from the scene
        if (_brushes[i] != NULL) {
            GlobalMap().findOrInsertWorldspawn()->removeChildNode(_brushes[i]);
            _brushes[i] = scene::INodePtr();
        }
    }

    if (_playerStart)
    {
        GlobalSceneGraph().root()->removeChildNode(_playerStart);
    }
}

// Static members (used as command targets for EventManager)

void RegionManager::disableRegion(const cmd::ArgumentList& args) {
    disable();
    SceneChangeNotify();
}

void RegionManager::setRegionXY(const cmd::ArgumentList& args)
{
    try
    {
        if (!module::GlobalModuleRegistry().moduleExists(MODULE_ORTHOVIEWMANAGER))
        {
            throw std::runtime_error("No ortho view module loaded.");
        }

        // Obtain the current XY orthoview, if there is one
        auto& xyWnd = GlobalOrthoViewManager().getViewByType(OrthoOrientation::XY);
        const auto& origin = xyWnd.getOrigin();

        Vector2 topLeft(
            origin[0] - 0.5f * xyWnd.getWidth() / xyWnd.getScale(),
            origin[1] - 0.5f * xyWnd.getHeight() / xyWnd.getScale()
        );

        Vector2 lowerRight(
            origin[0] + 0.5f * xyWnd.getWidth() / xyWnd.getScale(),
            origin[1] + 0.5f * xyWnd.getHeight() / xyWnd.getScale()
        );

        // Set the bounds from the calculated XY rectangle
        setRegionFromXY(topLeft, lowerRight);

        SceneChangeNotify();
    }
    catch (const std::runtime_error&)
    {
        disable();
        throw cmd::ExecutionFailure(_("Could not set Region: XY Top View not found."));
    }
}

void RegionManager::setRegionFromBrush(const cmd::ArgumentList& args)
{
    const SelectionInfo& info = GlobalSelectionSystem().getSelectionInfo();

    // Check, if exactly one brush is selected
    if (info.brushCount == 1 && info.totalCount == 1) {
        // Get the selected node
        const scene::INodePtr& node = GlobalSelectionSystem().ultimateSelected();

        // Set the bounds of the region to the selection's extents
        setRegion(node->worldAABB());

        // Delete the currently selected brush (undoable command)
        {
            UndoableCommand undo("deleteSelected");
            selection::algorithm::deleteSelection();
        }

        SceneChangeNotify();
    }
    else
    {
        disable();
        throw cmd::ExecutionFailure(_("Could not set Region: please select a single Brush."));
    }
}

void RegionManager::setRegionFromSelection(const cmd::ArgumentList& args)
{
    const SelectionInfo& info = GlobalSelectionSystem().getSelectionInfo();

    // Check, if there is anything selected
    if (info.totalCount > 0)
    {
        if (GlobalSelectionSystem().getSelectionMode() != selection::SelectionMode::Component)
        {
            // Obtain the selection size (its min/max vectors)
            AABB regionBounds = GlobalSelectionSystem().getWorkZone().bounds;

            // Set the region
            setRegion(regionBounds);

            // De-select all the selected items
            GlobalSelectionSystem().setSelectedAll(false);

            // Re-draw the scene
            SceneChangeNotify();
        }
        else
        {
            disable();
            throw cmd::ExecutionNotPossible(_("This command is not available in component mode."));
        }
    }
    else
    {
        disable();
        throw cmd::ExecutionNotPossible(_("Cannot set Region: nothing selected."));
    }
}

void RegionManager::traverseRegion(const scene::INodePtr& root, scene::NodeVisitor& nodeExporter)
{
    // Pass the given Walker on to the ExcludeWalker,
    // which calls the nodeExporter.pre() and .post() methods if the visited item is regioned.
    ExcludeNonRegionedWalker visitor(nodeExporter);
    root->traverseChildren(visitor);
}

void RegionManager::saveRegion(const cmd::ArgumentList& args)
{
    // Query the desired filename from the user
    MapFileSelection fileInfo =
        MapFileManager::getMapFileSelection(false, _("Export region"), filetype::TYPE_REGION);

    if (!fileInfo.fullPath.empty())
	{
        // Filename is ok, start preparation

        // Save the old region
        AABB oldRegionAABB = getRegion();

        // Now check for the effective bounds so that all visible items are included
        AABB visibleBounds = getVisibleBounds();

        // Set the region bounds, but don't traverse the graph!
        setRegion(visibleBounds, false);

        // Add the region brushes
        addRegionBrushes();

		if (!fileInfo.mapFormat)
		{
			fileInfo.mapFormat = GlobalMap().getMapFormatForFilenameSafe(fileInfo.fullPath);
		}

        // Save the map and pass the RegionManager::traverseRegion functor
        // that assures that only regioned items are traversed
        MapResource::saveFile(*fileInfo.mapFormat,
                             GlobalSceneGraph().root(),
                             RegionManager::traverseRegion,
                             fileInfo.fullPath);

        // Remove the region brushes
        removeRegionBrushes();

        // Set the region AABB back to the state before saving
        setRegion(oldRegionAABB, false);

        // Add the filename to the recently used map list
        GlobalMRU().insert(fileInfo.fullPath);
    }
}

void RegionManager::initialiseCommands()
{
    GlobalCommandSystem().addCommand("SaveRegion", std::bind(&RegionManager::saveRegion, this, std::placeholders::_1));
    GlobalCommandSystem().addCommand("RegionOff", std::bind(&RegionManager::disableRegion, this, std::placeholders::_1));
    GlobalCommandSystem().addCommand("RegionSetXY", std::bind(&RegionManager::setRegionXY, this, std::placeholders::_1));
    GlobalCommandSystem().addCommand("RegionSetBrush", std::bind(&RegionManager::setRegionFromBrush, this, std::placeholders::_1));
    GlobalCommandSystem().addCommand("RegionSetSelection", std::bind(&RegionManager::setRegionFromSelection, this, std::placeholders::_1));
}

const std::string& RegionManager::getName() const
{
	static std::string _name(MODULE_REGION_MANAGER);
	return _name;
}

const StringSet& RegionManager::getDependencies() const
{
	static StringSet _dependencies;

	if (_dependencies.empty())
	{
		_dependencies.insert(MODULE_MAP);
		_dependencies.insert(MODULE_COMMANDSYSTEM);
	}

	return _dependencies;
}

void RegionManager::initialiseModule(const IApplicationContext& ctx)
{
	initialiseCommands();

	_worldMin = game::current::getValue<float>("/defaults/minWorldCoord");
	_worldMax = game::current::getValue<float>("/defaults/maxWorldCoord");

	for (int i = 0; i < 6; i++)
	{
		_brushes[i].reset();
	}

	GlobalMap().signal_mapEvent().connect(
		sigc::mem_fun(*this, &RegionManager::onMapEvent));
}

void RegionManager::onMapEvent(IMap::MapEvent ev)
{
	if (ev == IMap::MapUnloading)
	{
		// Turn regioning off when unloading the map
		disable();
		clear();
	}
	else if (ev == IMap::MapLoaded)
	{
		// Disable when a new map has been loaded
		disable();
	}
}

AABB RegionManager::getVisibleBounds()
{
	AABB returnValue;

	GlobalSceneGraph().root()->foreachNode([&](const scene::INodePtr& node)
	{
		if (node->visible())
		{
			returnValue.includeAABB(node->worldAABB());
		}

		return true;
	});

	return returnValue;
}

module::StaticModuleRegistration<RegionManager> staticRegionManagerModule;

} // namespace