Subversion Repository Public Repository

Divide-Framework

This repository has no backups
This repository's network speed is throttled to 100KB/sec

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
#include "Headers/NavMesh.h"
#include "Headers/NavMeshDebugDraw.h"
#include "../Headers/DivideRecast.h"

#include "Core/Headers/ParamHandler.h"
#include "Core/Headers/ApplicationTimer.h"
#include "Managers/Headers/SceneManager.h"

#include <ReCast/DebugUtils/Include/RecastDump.h>
#include <ReCast/DebugUtils/Include/DetourDebugDraw.h>
#include <ReCast/DebugUtils/Include/RecastDebugDraw.h>

#include <SimpleIni.h>

namespace Divide {
namespace AI {
namespace Navigation {

NavigationMesh::NavigationMesh() : GUIDWrapper() {
    ParamHandler& par = ParamHandler::getInstance();
    stringImpl path(par.getParam<stringImpl>("scriptLocation") + "/" +
                    par.getParam<stringImpl>("scenesLocation") + "/" +
                    par.getParam<stringImpl>("currentScene"));

    _debugDrawInterface.reset(new NavMeshDebugDraw());

    _fileName = path + "/navMeshes/";
    _configFile = path + "/navMeshConfig.ini";
    _buildThreaded = true;
    _debugDraw = false;
    _renderConnections = false;
    _renderMode = RENDER_NAVMESH;
    _heightField = nullptr;
    _compactHeightField = nullptr;
    _countourSet = nullptr;
    _polyMesh = nullptr;
    _polyMeshDetail = nullptr;
    _navMesh = nullptr;
    _tempNavMesh = nullptr;
    _navQuery = nullptr;
    _building = false;
}

NavigationMesh::~NavigationMesh() { unload(); }

bool NavigationMesh::unload() {
    if (_buildThread) {
        _buildThread->stopTask();
        while (!_buildThread->isFinished()) {
        }
    }

    if (_navQuery) {
        dtFreeNavMeshQuery(_navQuery);
        _navQuery = 0;
    }

    freeIntermediates(true);
    dtFreeNavMesh(_navMesh);
    dtFreeNavMesh(_tempNavMesh);
    _navMesh = nullptr;
    _tempNavMesh = nullptr;

    return true;
}

void NavigationMesh::freeIntermediates(bool freeAll) {
    _navigationMeshLock.lock();

    rcFreeHeightField(_heightField);
    rcFreeCompactHeightfield(_compactHeightField);
    _heightField = nullptr;
    _compactHeightField = nullptr;

    if (!_saveIntermediates || freeAll) {
        rcFreeContourSet(_countourSet);
        rcFreePolyMesh(_polyMesh);
        rcFreePolyMeshDetail(_polyMeshDetail);
        _countourSet = nullptr;
        _polyMesh = nullptr;
        _polyMeshDetail = nullptr;
    }

    _navigationMeshLock.unlock();
}

namespace {
inline F32 charToFloat(const char* val) {
    return Util::convertData<F32, const char*>(val);
}

inline bool charToBool(const char* val) {
    return Util::convertData<bool, const char*>(val);
}
};

bool NavigationMesh::loadConfigFromFile() {
    // Use SimpleIni library for cross-platform INI parsing
    CSimpleIniA ini;
    ini.SetUnicode();
    ini.LoadFile(_configFile.c_str());

    if (!ini.GetSection("Rasterization") || !ini.GetSection("Agent") ||
        !ini.GetSection("Region") || !ini.GetSection("Polygonization") ||
        !ini.GetSection("DetailMesh"))
        return false;

    // Load all key-value pairs for the "Rasterization" section
    _configParams.setCellSize(
        charToFloat(ini.GetValue("Rasterization", "fCellSize", "0.3")));
    _configParams.setCellHeight(
        charToFloat(ini.GetValue("Rasterization", "fCellHeight", "0.2")));
    _configParams.setTileSize(
        charToFloat(ini.GetValue("Rasterization", "iTileSize", "48")));
    // Load all key-value pairs for the "Agent" section
    _configParams.setAgentHeight(
        charToFloat(ini.GetValue("Agent", "fAgentHeight", "2.5")));
    _configParams.setAgentRadius(
        charToFloat(ini.GetValue("Agent", "fAgentRadius", "0.5")));
    _configParams.setAgentMaxClimb(
        charToFloat(ini.GetValue("Agent", "fAgentMaxClimb", "1")));
    _configParams.setAgentMaxSlope(
        charToFloat(ini.GetValue("Agent", "fAgentMaxSlope", "20")));
    // Load all key-value pairs for the "Region" section
    _configParams.setRegionMergeSize(
        charToFloat(ini.GetValue("Region", "fMergeSize", "20")));
    _configParams.setRegionMinSize(
        charToFloat(ini.GetValue("Region", "fMinSize", "50")));
    // Load all key-value pairs for the "Polygonization" section
    _configParams.setEdgeMaxLen(
        charToFloat(ini.GetValue("Polygonization", "fEdgeMaxLength", "12")));
    _configParams.setEdgeMaxError(
        charToFloat(ini.GetValue("Polygonization", "fEdgeMaxError", "1.3")));
    _configParams.setVertsPerPoly(
        charToFloat(ini.GetValue("Polygonization", "iVertsPerPoly", "6")));
    // Load all key-value pairs for the "DetailMesh" section
    _configParams.setDetailSampleDist(
        charToFloat(ini.GetValue("DetailMesh", "fDetailSampleDist", "6")));
    _configParams.setDetailSampleMaxError(
        charToFloat(ini.GetValue("DetailMesh", "fDetailSampleMaxError", "1")));
    _configParams.setKeepInterResults(
        charToBool(ini.GetValue("DetailMesh", "bKeepInterResults", "false")));

    return true;
}

bool NavigationMesh::build(SceneGraphNode& sgn,
                           CreationCallback creationCompleteCallback,
                           bool threaded) {
    if (!loadConfigFromFile()) {
        Console::errorfn(Locale::get("NAV_MESH_CONFIG_NOT_FOUND"));
        return false;
    }

    _sgn = &sgn;
    _loadCompleteClbk = creationCompleteCallback;

    if (_buildThreaded && threaded) {
        return buildThreaded();
    }

    return buildProcess();
}

bool NavigationMesh::buildThreaded() {
    boost::mutex::scoped_lock sl(_buildLock);

    if (!sl.owns_lock()) {
        return false;
    }

    if (_buildThread) {
        _buildThread->stopTask();
    }

    Kernel& kernel = Application::getInstance().getKernel();
    _buildThread.reset(kernel.AddTask(
        0, 0, DELEGATE_BIND(&NavigationMesh::buildInternal, this)));
    _buildThread->startTask();
    return true;
}

void NavigationMesh::buildInternal() {
    _building = true;
    // Create mesh
    D32 timeStart = Time::ElapsedSeconds();
    bool success = generateMesh();
    if (!success) {
        Console::errorfn(Locale::get("NAV_MESH_GENERATION_INCOMPLETE"),
                         Time::ElapsedSeconds(true) - timeStart);
        return;
    }

    Console::printfn(Locale::get("NAV_MESH_GENERATION_COMPLETE"),
                     Time::ElapsedSeconds(true) - timeStart);

    _navigationMeshLock.lock();
    {
        // Copy new NavigationMesh into old.
        dtNavMesh* old = _navMesh;
        // I am trusting that this is atomic.
        _navMesh = _tempNavMesh;
        dtFreeNavMesh(old);
        _debugDrawInterface->setDirty(true);
        _tempNavMesh = nullptr;

        bool navQueryComplete = createNavigationQuery();
        DIVIDE_ASSERT(
            navQueryComplete,
            "NavigationMesh Error: Navigation query creation failed!");
    }
    _navigationMeshLock.unlock();

    // Free structs used during build
    freeIntermediates(false);

    _building = false;

    if (_loadCompleteClbk) {
        _loadCompleteClbk(this);
    }
}

bool NavigationMesh::buildProcess() {
    _building = true;
    // Create mesh
    D32 timeStart = Time::ElapsedSeconds();
    bool success = generateMesh();
    if (!success) {
        Console::errorfn(Locale::get("NAV_MESH_GENERATION_INCOMPLETE"),
                         Time::ElapsedSeconds(true) - timeStart);
        return false;
    }

    Console::printfn(Locale::get("NAV_MESH_GENERATION_COMPLETE"),
                     Time::ElapsedSeconds(true) - timeStart);

    _navigationMeshLock.lock();
    {
        // Copy new NavigationMesh into old.
        dtNavMesh* old = _navMesh;
        // I am trusting that this is atomic.
        _navMesh = _tempNavMesh;
        dtFreeNavMesh(old);
        _debugDrawInterface->setDirty(true);
        _tempNavMesh = nullptr;

        bool navQueryComplete = createNavigationQuery();
        DIVIDE_ASSERT(
            navQueryComplete,
            "NavigationMesh Error: Navigation query creation failed!");
    }
    _navigationMeshLock.unlock();

    // Free structs used during build
    freeIntermediates(false);

    _building = false;

    if (_loadCompleteClbk) {
        _loadCompleteClbk(this);
    }

    return success;
}

bool NavigationMesh::generateMesh() {
    assert(_sgn != nullptr);

    stringImpl nodeName((_sgn->getNode()->getType() != SceneNodeType::TYPE_ROOT)
                            ? "_node_[_" + _sgn->getName() + "_]"
                            : "_root_node");

    // Parse objects from level into RC-compatible format
    _fileName.append(nodeName);
    _fileName.append(".nm");
    Console::printfn(Locale::get("NAV_MESH_GENERATION_START"),
                     nodeName.c_str());

    NavModelData data;
    stringImpl geometrySaveFile(_fileName);
    Util::replaceStringInPlace(geometrySaveFile, ".nm", ".ig");

    data.clear(false);
    data.setName(nodeName);

    if (!NavigationMeshLoader::loadMeshFile(data, geometrySaveFile.c_str())) {
        if (!NavigationMeshLoader::parse(_sgn->getBoundingBoxConst(), data,
                                         _sgn)) {
            Console::errorfn(Locale::get("ERROR_NAV_PARSE_FAILED"),
                             nodeName.c_str());
        }
    }

    // Check for no geometry
    if (!data.getVertCount()) {
        data.isValid(false);
        return false;
    }

    // Free intermediate and final results
    freeIntermediates(true);
    // Recast initialisation data
    rcContextDivide ctx(true);

    rcConfig cfg;
    memset(&cfg, 0, sizeof(cfg));

    cfg.cs = _configParams.getCellSize();
    cfg.ch = _configParams.getCellHeight();
    cfg.walkableHeight = _configParams.base_getWalkableHeight();
    cfg.walkableClimb = _configParams.base_getWalkableClimb();
    cfg.walkableRadius = _configParams.base_getWalkableRadius();
    cfg.walkableSlopeAngle = _configParams.getAgentMaxSlope();
    cfg.borderSize =
        _configParams.base_getWalkableRadius() + (I32)BORDER_PADDING;
    cfg.detailSampleDist = _configParams.getDetailSampleDist();
    cfg.detailSampleMaxError = _configParams.getDetailSampleMaxError();
    cfg.maxEdgeLen = _configParams.getEdgeMaxLen();
    cfg.maxSimplificationError = _configParams.getEdgeMaxError();
    cfg.maxVertsPerPoly = _configParams.getVertsPerPoly();
    cfg.minRegionArea = _configParams.getRegionMinSize();
    cfg.mergeRegionArea = _configParams.getRegionMergeSize();
    cfg.tileSize = _configParams.getTileSize();

    _saveIntermediates = _configParams.getKeepInterResults();
    rcCalcBounds(data.getVerts(), data.getVertCount(), cfg.bmin, cfg.bmax);
    rcCalcGridSize(cfg.bmin, cfg.bmax, cfg.cs, &cfg.width, &cfg.height);
    Console::printfn(Locale::get("NAV_MESH_BOUNDS"), cfg.bmax[0], cfg.bmax[1],
                     cfg.bmax[2], cfg.bmin[0], cfg.bmin[1], cfg.bmin[2]);

    _extents = vec3<F32>(cfg.bmax[0] - cfg.bmin[0], cfg.bmax[1] - cfg.bmin[1],
                         cfg.bmax[2] - cfg.bmin[2]);

    if (!createPolyMesh(cfg, data, &ctx)) {
        data.isValid(false);
        return false;
    }

    // Detour initialisation data
    dtNavMeshCreateParams params;
    memset(&params, 0, sizeof(params));
    rcVcopy(params.bmax, cfg.bmax);
    rcVcopy(params.bmin, cfg.bmin);

    params.ch = cfg.ch;
    params.cs = cfg.cs;
    params.walkableHeight = cfg.walkableHeight;
    params.walkableRadius = cfg.walkableRadius;
    params.walkableClimb = cfg.walkableClimb;

    params.tileX = 0;
    params.tileY = 0;
    params.tileLayer = 0;
    params.buildBvTree = true;

    params.verts = _polyMesh->verts;
    params.vertCount = _polyMesh->nverts;
    params.polys = _polyMesh->polys;
    params.polyAreas = _polyMesh->areas;
    params.polyFlags = _polyMesh->flags;
    params.polyCount = _polyMesh->npolys;
    params.nvp = _polyMesh->nvp;

    params.detailMeshes = _polyMeshDetail->meshes;
    params.detailVerts = _polyMeshDetail->verts;
    params.detailVertsCount = _polyMeshDetail->nverts;
    params.detailTris = _polyMeshDetail->tris;
    params.detailTriCount = _polyMeshDetail->ntris;

    if (!createNavigationMesh(params)) {
        data.isValid(false);
        return false;
    }

    data.isValid(true);

    return NavigationMeshLoader::saveMeshFile(
        data, geometrySaveFile.c_str());  // input geometry;
}

bool NavigationMesh::createNavigationQuery(U32 maxNodes) {
    _navQuery = dtAllocNavMeshQuery();
    return (_navQuery->init(_navMesh, maxNodes) == DT_SUCCESS);
}

bool NavigationMesh::createPolyMesh(rcConfig& cfg, NavModelData& data,
                                    rcContextDivide* ctx) {
    if (_fileName.empty()) {
        _fileName = data.getName();
    }

    // Create a heightfield to voxelise our input geometry
    _heightField = rcAllocHeightfield();

    if (!_heightField) {
        Console::errorfn(Locale::get("ERROR_NAV_OUT_OF_MEMORY"),
                         "rcAllocHeightfield", _fileName.c_str());
        return false;
    }

    // Reset build times gathering.
    ctx->resetTimers();
    // Start the build process.
    ctx->startTimer(RC_TIMER_TOTAL);
    ctx->log(RC_LOG_PROGRESS, "Building navigation:");
    ctx->log(RC_LOG_PROGRESS, " - %d x %d cells", cfg.width, cfg.height);
    ctx->log(RC_LOG_PROGRESS, " - %.1fK verts, %.1fK tris",
             data.getVertCount() / 1000.0f, data.getTriCount() / 1000.0f);

    if (!rcCreateHeightfield(ctx, *_heightField, cfg.width, cfg.height,
                             cfg.bmin, cfg.bmax, cfg.cs, cfg.ch)) {
        Console::errorfn(Locale::get("ERROR_NAV_HEIGHTFIELD"),
                         _fileName.c_str());
        return false;
    }

    U8* areas = MemoryManager_NEW U8[data.getTriCount()];

    if (!areas) {
        Console::errorfn(Locale::get("ERROR_NAV_OUT_OF_MEMORY"),
                         "areaFlag allocation", _fileName.c_str());
        return false;
    }

    memset(areas, 0, data.getTriCount() * sizeof(U8));

    // Filter triangles by angle and rasterize
    rcMarkWalkableTriangles(ctx, cfg.walkableSlopeAngle, data.getVerts(),
                            data.getVertCount(), data.getTris(),
                            data.getTriCount(), areas);

    rcRasterizeTriangles(ctx, data.getVerts(), data.getVertCount(),
                         data.getTris(), areas, data.getTriCount(),
                         *_heightField, cfg.walkableClimb);

    if (!_saveIntermediates) {
        MemoryManager::DELETE_ARRAY(areas);
    }

    // Filter out areas with low ceilings and other stuff
    rcFilterLowHangingWalkableObstacles(ctx, cfg.walkableClimb, *_heightField);

    rcFilterLedgeSpans(ctx, cfg.walkableHeight, cfg.walkableClimb,
                       *_heightField);

    rcFilterWalkableLowHeightSpans(ctx, cfg.walkableHeight, *_heightField);

    _compactHeightField = rcAllocCompactHeightfield();

    if (!_compactHeightField ||
        !rcBuildCompactHeightfield(ctx, cfg.walkableHeight, cfg.walkableClimb,
                                   *_heightField, *_compactHeightField)) {
        Console::errorfn(Locale::get("ERROR_NAV_COMPACT_HEIGHTFIELD"),
                         _fileName.c_str());
        return false;
    }

    if (!rcErodeWalkableArea(ctx, cfg.walkableRadius, *_compactHeightField)) {
        Console::errorfn(Locale::get("ERROR_NAV_WALKABLE"), _fileName.c_str());
        return false;
    }

    if (false) {
        if (!rcBuildRegionsMonotone(ctx, *_compactHeightField, cfg.borderSize,
                                    cfg.minRegionArea, cfg.mergeRegionArea)) {
            Console::errorfn(Locale::get("ERROR_NAV_REGIONS"),
                             _fileName.c_str());
            return false;
        }
    } else {
        if (!rcBuildDistanceField(ctx, *_compactHeightField)) {
            return false;
        }

        if (!rcBuildRegions(ctx, *_compactHeightField, cfg.borderSize,
                            cfg.minRegionArea, cfg.mergeRegionArea)) {
            return false;
        }
    }

    _countourSet = rcAllocContourSet();
    if (!_countourSet ||
        !rcBuildContours(ctx, *_compactHeightField, cfg.maxSimplificationError,
                         cfg.maxEdgeLen, *_countourSet)) {
        Console::errorfn(Locale::get("ERROR_NAV_COUNTOUR"), _fileName.c_str());
        return false;
    }

    _polyMesh = rcAllocPolyMesh();
    if (!_polyMesh ||
        !rcBuildPolyMesh(ctx, *_countourSet, cfg.maxVertsPerPoly, *_polyMesh)) {
        Console::errorfn(Locale::get("ERROR_NAV_POLY_MESH"), _fileName.c_str());
        return false;
    }

    _polyMeshDetail = rcAllocPolyMeshDetail();
    if (!_polyMeshDetail ||
        !rcBuildPolyMeshDetail(ctx, *_polyMesh, *_compactHeightField,
                               cfg.detailSampleDist, cfg.detailSampleMaxError,
                               *_polyMeshDetail)) {
        Console::errorfn(Locale::get("ERROR_NAV_POLY_MESH_DETAIL"),
                         _fileName.c_str());
        return false;
    }

    // Show performance stats.
    ctx->stopTimer(RC_TIMER_TOTAL);
    duLogBuildTimes(*ctx, ctx->getAccumulatedTime(RC_TIMER_TOTAL));
    ctx->log(RC_LOG_PROGRESS, ">> Polymesh: %d vertices  %d polygons",
             _polyMesh->nverts, _polyMesh->npolys);

    Console::printfn(
        "[RC_LOG_PROGRESS] Polymesh: %d vertices  %d polygons %5.2f ms\n",
        _polyMesh->nverts, _polyMesh->npolys,
        (F32)ctx->getAccumulatedTime(RC_TIMER_TOTAL) / 1000.0f);

    return true;
}

bool NavigationMesh::createNavigationMesh(dtNavMeshCreateParams& params) {
    U8* tileData = nullptr;
    I32 tileDataSize = 0;
    if (!dtCreateNavMeshData(&params, &tileData, &tileDataSize)) {
        Console::errorfn(Locale::get("ERROR_NAV_MESH_DATA"), _fileName.c_str());
        return false;
    }

    _tempNavMesh = dtAllocNavMesh();
    if (!_tempNavMesh) {
        Console::errorfn(Locale::get("ERROR_NAV_DT_OUT_OF_MEMORY"),
                         _fileName.c_str());
        return false;
    }

    dtStatus s = _tempNavMesh->init(tileData, tileDataSize, DT_TILE_FREE_DATA);
    if (dtStatusFailed(s)) {
        Console::errorfn(Locale::get("ERROR_NAV_DT_INIT"), _fileName.c_str());
        return false;
    }

    // Initialise all flags to something helpful.
    for (U32 i = 0; i < (U32)_tempNavMesh->getMaxTiles(); ++i) {
        const dtMeshTile* tile = ((const dtNavMesh*)_tempNavMesh)->getTile(i);

        if (!tile->header) {
            continue;
        }

        const dtPolyRef base = _tempNavMesh->getPolyRefBase(tile);

        for (U32 j = 0; j < (U32)tile->header->polyCount; ++j) {
            const dtPolyRef ref = base | j;
            U16 f = 0;
            _tempNavMesh->getPolyFlags(ref, &f);
            _tempNavMesh->setPolyFlags(ref, f | 1);
        }
    }

    return true;
}

void NavigationMesh::update(const U64 deltaTime) {
    _debugDrawInterface->paused(!_debugDraw);
}

void NavigationMesh::render() {
    RenderMode mode = _renderMode;

    if (_building) {
        mode = RENDER_NAVMESH;
        _debugDrawInterface->overrideColor(duRGBA(255, 0, 0, 80));
    }

    _debugDrawInterface->beginBatch();

    _navigationMeshLock.lock();

    switch (mode) {
        case RENDER_NAVMESH:
            if (_navMesh) {
                duDebugDrawNavMesh(_debugDrawInterface.get(), *_navMesh, 0);
            }
            break;
        case RENDER_CONTOURS:
            if (_countourSet) {
                duDebugDrawContours(_debugDrawInterface.get(), *_countourSet);
            }
            break;
        case RENDER_POLYMESH:
            if (_polyMesh) {
                duDebugDrawPolyMesh(_debugDrawInterface.get(), *_polyMesh);
            }
            break;
        case RENDER_DETAILMESH:
            if (_polyMeshDetail) {
                duDebugDrawPolyMeshDetail(_debugDrawInterface.get(),
                                          *_polyMeshDetail);
            }
            break;
        case RENDER_PORTALS:
            if (_navMesh) {
                duDebugDrawNavMeshPortals(_debugDrawInterface.get(), *_navMesh);
            }
            break;
    }

    if (!_building) {
        if (_countourSet && _renderConnections) {
            duDebugDrawRegionConnections(_debugDrawInterface.get(),
                                         *_countourSet);
        }
    }

    _navigationMeshLock.unlock();

    _debugDrawInterface->endBatch();
}

bool NavigationMesh::load(SceneGraphNode& sgn) {
    if (!_fileName.length()) {
        return false;
    }
    stringImpl file = _fileName;

    file.append("_node_[_" + sgn.getName() + "_]");

    file.append(".nm");
    // Parse objects from level into RC-compatible format
    FILE* fp = fopen(file.c_str(), "rb");
    if (!fp) {
        return false;
    }
    // Read header.
    NavMeshSetHeader header;
    fread(&header, sizeof(NavMeshSetHeader), 1, fp);

    if (header.magic != NAVMESHSET_MAGIC) {
        fclose(fp);
        return false;
    }

    if (header.version != NAVMESHSET_VERSION) {
        fclose(fp);
        return false;
    }

    boost::mutex::scoped_lock(_navigationMeshLock);

    if (_navMesh) {
        dtFreeNavMesh(_navMesh);
    }

    _navMesh = dtAllocNavMesh();

    if (!_navMesh) {
        fclose(fp);
        return false;
    }

    dtStatus status = _navMesh->init(&header.params);

    if (dtStatusFailed(status)) {
        fclose(fp);
        return false;
    }

    // Read tiles.
    for (U32 i = 0; i < (U32)header.numTiles; ++i) {
        NavMeshTileHeader tileHeader;
        fread(&tileHeader, sizeof(tileHeader), 1, fp);
        if (!tileHeader.tileRef || !tileHeader.dataSize) {
            return false;  // break;
        }
        U8* data = (U8*)dtAlloc(tileHeader.dataSize, DT_ALLOC_PERM);

        if (!data) {
            return false;  // break;
        }

        memset(data, 0, tileHeader.dataSize);
        fread(data, tileHeader.dataSize, 1, fp);

        _navMesh->addTile(data, tileHeader.dataSize, DT_TILE_FREE_DATA,
                          tileHeader.tileRef, 0);
    }
    fclose(fp);

    _extents.set(header.extents[0], header.extents[1], header.extents[2]);

    return createNavigationQuery();
}

bool NavigationMesh::save() {
    if (!_fileName.length() || !_navMesh) {
        return false;
    }
    // Save our NavigationMesh into a file to load from next time
    FILE* fp = fopen(_fileName.c_str(), "wb");
    if (!fp) {
        return false;
    }

    boost::mutex::scoped_lock(_navigationMeshLock);

    // Store header.
    NavMeshSetHeader header;
    memcpy(header.extents, &_extents[0], sizeof(F32) * 3);

    header.magic = NAVMESHSET_MAGIC;
    header.version = NAVMESHSET_VERSION;
    header.numTiles = 0;

    for (U32 i = 0; i < (U32)_navMesh->getMaxTiles(); ++i) {
        const dtMeshTile* tile = ((const dtNavMesh*)_navMesh)->getTile(i);

        if (!tile || !tile->header || !tile->dataSize) {
            continue;
        }
        header.numTiles++;
    }

    memcpy(&header.params, _navMesh->getParams(), sizeof(dtNavMeshParams));
    fwrite(&header, sizeof(NavMeshSetHeader), 1, fp);

    // Store tiles.
    for (U32 i = 0; i < (U32)_navMesh->getMaxTiles(); ++i) {
        const dtMeshTile* tile = ((const dtNavMesh*)_navMesh)->getTile(i);

        if (!tile || !tile->header || !tile->dataSize) {
            continue;
        }

        NavMeshTileHeader tileHeader;
        tileHeader.tileRef = _navMesh->getTileRef(tile);
        tileHeader.dataSize = tile->dataSize;

        fwrite(&tileHeader, sizeof(tileHeader), 1, fp);
        fwrite(tile->data, tile->dataSize, 1, fp);
    }

    fclose(fp);

    return true;
}

bool NavigationMesh::getClosestPosition(const vec3<F32>& destination,
                                        const vec3<F32>& extents, F32 delta,
                                        vec3<F32>& result) const {
    dtPolyRef resultPoly;
    return Navigation::DivideRecast::getInstance().findNearestPointOnNavmesh(
        *this, destination, extents, delta, result, resultPoly);
}

bool NavigationMesh::getRandomPosition(vec3<F32>& result) const {
    return Navigation::DivideRecast::getInstance().getRandomNavMeshPoint(
        *this, result);
}

bool NavigationMesh::getRandomPositionInCircle(const vec3<F32>& center,
                                               F32 radius,
                                               const vec3<F32>& extents,
                                               vec3<F32>& result,
                                               U8 maxIters) const {
    return Navigation::DivideRecast::getInstance().getRandomPointAroundCircle(
        *this, center, radius, extents, result, maxIters);
}
};  // namespace Navigation
};  // namespace AI
};  // namespace Divide

Commits for Divide-Framework/trunk/Source Code/AI/PathFinding/NavMeshes/NavMesh.cpp

Diff revisions: vs.
Revision Author Commited Message
365 Diff Diff IonutCava picture IonutCava Sun 08 Mar, 2015 21:26:10 +0000

[Ionut]
- More enum-related type safety changes

354 Diff Diff IonutCava picture IonutCava Fri 20 Feb, 2015 17:17:37 +0000

[Ionut]
- Replaced GLEW with glbinding (requires a CEGUI recompile. It currently crashes)
- Replaced most “SceneGraphNode* const sgn” expressions with "SceneGraphNode& sgn"
- Replaced some pointers to kernel to references to kernel
- Fixed compilation issues with EASTL
- Removed NPOT -> POT texture conversion code. Modern GPUs handle NPOT textures perfectly fine

350 Diff Diff IonutCava picture IonutCava Tue 10 Feb, 2015 16:25:39 +0000

[Ionut]
- Simplified some Util-namespace level functions by using STL algorithms where possible
- Formatted the entire codebase using clang-format with the following style: "{BasedOnStyle: Google, IndentWidth: 4}"
- Attempted to make ProfileTimer thread-safe (temp fix until std::chrono works properly in Visual Studio)

349 Diff Diff IonutCava picture IonutCava Fri 06 Feb, 2015 17:11:39 +0000

[Ionut]
- More raw pointer replacements
- Removed some redundant parameters to a few scene and application functions

348 Diff Diff IonutCava picture IonutCava Thu 05 Feb, 2015 17:13:01 +0000

[Ionut]
- Replaced some raw pointers with smart pointers or direct data members
- Removed redundant SceneGraph pointer from SceneGraphNode

343 Diff Diff IonutCava picture IonutCava Thu 15 Jan, 2015 17:30:12 +0000

[Ionut]
- Refactored 2 singletons into static classes (Console and TerrainLoader)
- Changed some C-casts to static_casts
- Updated copyright notices

338 Diff Diff IonutCava picture IonutCava Thu 08 Jan, 2015 14:17:33 +0000

[Ionut]
- Added Metric, Time and Angle namespaces and moved all related functions to the appropriate one.
- Reworked most dynamic_cast calls to static_cast (with static_assert where possible)
- Moved ProfileTimer and ApplicationTimer to Time namespace
- More .h/.cpp/.inl splitting in core files (mostly Math files)

337 Diff Diff IonutCava picture IonutCava Wed 17 Dec, 2014 17:25:16 +0000

[Ionut]
- Replaced all tabs with 4 spaces (some spacing may be off now. no way to check all the files.)
- Moved implementation details for ParamHandler, BoundingBox, BoundingSphere and ProfileTimer to proper .inl and .cpp files. (more to follow)
- Update all forward declared enums with the required storage type (as requested by the C++11 standard)

333 Diff Diff IonutCava picture IonutCava Tue 09 Dec, 2014 16:15:44 +0000

[Ionut]
- Removed “core.h” and moved everything to their appropriate header files
- Renamed MathClasses to MathMatrices (finally)
- Renamed “-Inl.h” files to ".inl"
- Some String wrapper refactoring
- Update “InstallLibraries.bat” so that it still offers valid options

331 IonutCava picture IonutCava Sat 06 Dec, 2014 20:53:45 +0000

[Ionut]
- Limited line length to 132 characters to improve readability and diff-comparisons
- Refactored memory allocation/deallocation functions
- Fixed a few compatibility issues with HashMap.h
- Fixed a bug in GPU Skinning shaders (cast a float to int)