-
Notifications
You must be signed in to change notification settings - Fork 572
Expand file tree
/
Copy pathMap.cpp
More file actions
3830 lines (3247 loc) · 134 KB
/
Copy pathMap.cpp
File metadata and controls
3830 lines (3247 loc) · 134 KB
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) 2005-2011 MaNGOS <http://getmangos.com/>
* Copyright (C) 2009-2011 MaNGOSZero <https://github.com/mangos/zero>
* Copyright (C) 2011-2016 Nostalrius <https://nostalrius.org>
* Copyright (C) 2016-2017 Elysium Project <https://github.com/elysium-project>
*
* This program 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 2 of the License, or
* (at your option) any later version.
*
* This program 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 this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "Map.h"
#include "MapManager.h"
#include "Player.h"
#include "GridNotifiers.h"
#include "Log.h"
#include "GridStates.h"
#include "CellImpl.h"
#include "InstanceData.h"
#include "GridNotifiersImpl.h"
#include "Transport.h"
#include "ObjectAccessor.h"
#include "ObjectMgr.h"
#include "World.h"
#include "Group.h"
#include "MapRefManager.h"
#include "DBCEnums.h"
#include "MapPersistentStateMgr.h"
#include "VMapFactory.h"
#include "BattleGroundMgr.h"
#include "DynamicTree.h"
#include "RegularGrid.h"
#include "PathFinder.h"
#include "Detour/Include/DetourNavMesh.h"
#include "Detour/Include/DetourNavMeshQuery.h"
#include "MoveMap.h"
#include "SocialMgr.h"
#include "Chat.h"
#include "MonsterChatBuilder.h"
#include "Weather.h"
#include "MovementBroadcaster.h"
#include "PlayerBroadcaster.h"
#include "GridSearchers.h"
#include "ThreadPool.h"
#include "AuraRemovalMgr.h"
#include "world/world_event_wareffort.h"
#include "CreatureGroups.h"
#include "Geometry.h"
Map::~Map()
{
UnloadAll(true);
if (!m_scriptSchedule.empty())
sScriptMgr.DecreaseScheduledScriptCount(m_scriptSchedule.size());
if (m_persistentState)
m_persistentState->SetUsedByMapState(nullptr); // field pointer can be deleted after this
if (m_data)
{
delete m_data;
m_data = nullptr;
}
//release reference count
if (m_terrainData->Release())
sTerrainMgr.UnloadTerrain(m_terrainData->GetMapId());
if (!m_corpseToRemove.empty())
sLog.Out(LOG_BASIC, LOG_LVL_ERROR, "[MAP] Map %u (instance %u) deleted while there are still corpses to remove", GetId(), GetInstanceId());
delete m_weatherSystem;
m_weatherSystem = nullptr;
}
GenericTransport* Map::GetTransport(ObjectGuid guid)
{
if (ShipTransport* transport = HashMapHolder<ShipTransport>::Find(guid))
return transport;
if (guid.GetEntry())
return GetElevatorTransport(guid);
return nullptr;
}
ElevatorTransport* Map::GetElevatorTransport(ObjectGuid guid)
{
for (auto pTransport : m_transports)
{
if (pTransport->GetObjectGuid() == guid)
return static_cast<ElevatorTransport*>(pTransport);
}
if (auto pTransport = GetGameObject(guid))
return static_cast<ElevatorTransport*>(pTransport);
return nullptr;
}
void Map::LoadMapAndVMap(int gx, int gy)
{
if (m_bLoadedGrids[gx][gy])
return;
GridMap * pInfo = m_terrainData->Load(gx, gy);
if (pInfo)
m_bLoadedGrids[gx][gy] = true;
}
Map::Map(uint32 id, time_t expiry, uint32 InstanceId)
: m_mapEntry(sMapStorage.LookupEntry<MapEntry>(id)),
m_id(id), m_instanceId(InstanceId), m_unloadTimer(0),
m_visibilityDistance(DEFAULT_VISIBILITY_DISTANCE), m_persistentState(nullptr),
m_activeNonPlayersIter(m_activeNonPlayers.end()), m_transportsUpdateIter(m_transports.end()),
m_createTime(time(nullptr)), m_gridExpiry(expiry), m_terrainData(sTerrainMgr.LoadTerrain(id)),
m_data(nullptr), m_scriptId(0), m_unloading(false), m_crashed(false),
m_processingSendObjUpdates(false), m_processingUnitsRelocation(false),
m_updateFinished(false), m_updateDiffMod(0), m_gridActivationDistance(DEFAULT_VISIBILITY_DISTANCE),
m_lastPlayersUpdate(WorldTimer::getMSTime()), m_lastMapUpdate(WorldTimer::getMSTime()),
m_lastCellsUpdate(WorldTimer::getMSTime()), m_inactivePlayersSkippedUpdates(0),
m_objUpdatesThreads(0), m_unitRelocationThreads(0), m_lastPlayerLeftTime(0),
m_lastMvtSpellsUpdate(0), m_bonesCleanupTimer(0), m_uiScriptedEventsTimer(1000)
{
m_CreatureGuids.SetMaxUsedGuid(sObjectMgr.GetFirstTemporaryCreatureLowGuid(), "Creature");
m_GameObjectGuids.SetMaxUsedGuid(sObjectMgr.GetFirstTemporaryGameObjectLowGuid(), "GameObject");
for (uint32 j = 0; j < MAX_NUMBER_OF_GRIDS; ++j)
{
for (uint32 idx = 0; idx < MAX_NUMBER_OF_GRIDS; ++idx)
{
//z code
m_bLoadedGrids[idx][j] = false;
setNGrid(nullptr, idx, j);
}
}
//lets initialize visibility distance for map
Map::InitVisibilityDistance();
//add reference for TerrainData object
m_terrainData->AddRef();
m_persistentState = sMapPersistentStateMgr.AddPersistentState(m_mapEntry, GetInstanceId(), 0, IsDungeon());
m_persistentState->SetUsedByMapState(this);
m_weatherSystem = new WeatherSystem(this);
if (IsContinent())
{
int numObjThreads = (int)sWorld.getConfig(CONFIG_UINT32_MAP_OBJECTSUPDATE_THREADS);
if (numObjThreads > 1)
{
m_objectThreads.reset(new ThreadPool("MapObj", numObjThreads -1));
m_objectThreads->start<ThreadPool::MySQL<ThreadPool::MultiQueue>>();
}
m_motionThreads.reset(new ThreadPool("MapMotion", sWorld.getConfig(CONFIG_UINT32_CONTINENTS_MOTIONUPDATE_THREADS)));
m_visibilityThreads.reset(new ThreadPool("MapVis", std::max((int)sWorld.getConfig(CONFIG_UINT32_MAP_VISIBILITYUPDATE_THREADS) -1,0)));
m_cellThreads.reset(new ThreadPool("MapCell", std::max((int)sWorld.getConfig(CONFIG_UINT32_MTCELLS_THREADS) - 1, 0)));
m_visibilityThreads->start<ThreadPool::MySQL<ThreadPool::MultiQueue>>();
m_cellThreads->start();
m_motionThreads->start();
}
sTransportMgr.SpawnTransportsOnMap(this);
LoadElevatorTransports();
}
// Nostalrius
// Active objects system
class ActiveObjectsGridLoader
{
public:
ActiveObjectsGridLoader(Map* _map) : map(_map) {}
bool operator()(GameObjectDataPair const& dataPair)
{
if (!(dataPair.second.spawn_flags & SPAWN_FLAG_ACTIVE) || dataPair.second.position.mapId != map->GetId())
return false;
// Instanciated continents case
if (map->IsContinent() && map->GetInstanceId() && map->GetInstanceId() != dataPair.second.instanciatedContinentInstanceId)
return false;
Cell c(MaNGOS::ComputeCellPair(dataPair.second.position.x, dataPair.second.position.y));
map->LoadGrid(c, true);
return false;
}
bool operator()(CreatureDataPair const& dataPair)
{
if (!(dataPair.second.spawn_flags & SPAWN_FLAG_ACTIVE) || dataPair.second.position.mapId != map->GetId())
return false;
// Instanciated continents case
if (map->IsContinent() && map->GetInstanceId() && map->GetInstanceId() != dataPair.second.instanciatedContinentInstanceId)
return false;
Cell c(MaNGOS::ComputeCellPair(dataPair.second.position.x, dataPair.second.position.y));
map->LoadGrid(c, true);
return false;
}
Map* map;
};
void Map::SpawnActiveObjects()
{
if (MapPersistentState* state = GetPersistentState())
state->InitPools();
ActiveObjectsGridLoader loader(this);
sObjectMgr.DoGOData(loader);
sObjectMgr.DoCreatureData(loader);
}
void Map::InitVisibilityDistance()
{
//init visibility for continents
m_visibilityDistance = World::GetMaxVisibleDistanceOnContinents();
m_gridActivationDistance = World::GetMaxVisibleDistanceOnContinents();
}
// Template specialization of utility methods
template<class T>
void Map::AddToGrid(T* obj, NGridType* grid, Cell const& cell)
{
(*grid)(cell.CellX(), cell.CellY()).template AddGridObject<T>(obj);
}
template<>
void Map::AddToGrid(GameObject* obj, NGridType* grid, Cell const& cell)
{
(*grid)(cell.CellX(), cell.CellY()).AddGridObject<GameObject>(obj);
obj->SetCurrentCell(cell);
}
template<>
void Map::AddToGrid(Player* obj, NGridType* grid, Cell const& cell)
{
(*grid)(cell.CellX(), cell.CellY()).AddWorldObject(obj);
}
template<>
void Map::AddToGrid(Corpse* obj, NGridType* grid, Cell const& cell)
{
// add to world object registry in grid
if (obj->GetType() != CORPSE_BONES)
(*grid)(cell.CellX(), cell.CellY()).AddWorldObject(obj);
// add to grid object store
else
(*grid)(cell.CellX(), cell.CellY()).AddGridObject(obj);
}
template<>
void Map::AddToGrid(Creature* obj, NGridType* grid, Cell const& cell)
{
// add to world object registry in grid
if (obj->IsPet())
{
(*grid)(cell.CellX(), cell.CellY()).AddWorldObject<Creature>(obj);
obj->SetCurrentCell(cell);
}
// add to grid object store
else
{
(*grid)(cell.CellX(), cell.CellY()).AddGridObject<Creature>(obj);
obj->SetCurrentCell(cell);
}
}
template<class T>
void Map::RemoveFromGrid(T* obj, NGridType* grid, Cell const& cell)
{
(*grid)(cell.CellX(), cell.CellY()).template RemoveGridObject<T>(obj);
}
template<>
void Map::RemoveFromGrid(Player* obj, NGridType* grid, Cell const& cell)
{
(*grid)(cell.CellX(), cell.CellY()).RemoveWorldObject(obj);
}
template<>
void Map::RemoveFromGrid(Corpse* obj, NGridType* grid, Cell const& cell)
{
// remove from world object registry in grid
if (obj->GetType() != CORPSE_BONES)
(*grid)(cell.CellX(), cell.CellY()).RemoveWorldObject(obj);
// remove from grid object store
else
(*grid)(cell.CellX(), cell.CellY()).RemoveGridObject(obj);
}
template<>
void Map::RemoveFromGrid(Creature* obj, NGridType* grid, Cell const& cell)
{
// remove from world object registry in grid
if (obj->IsPet())
(*grid)(cell.CellX(), cell.CellY()).RemoveWorldObject<Creature>(obj);
// remove from grid object store
else
(*grid)(cell.CellX(), cell.CellY()).RemoveGridObject<Creature>(obj);
}
void Map::DeleteFromWorld(Player* player)
{
sObjectAccessor.RemoveObject(player);
delete player;
}
void
Map::EnsureGridCreated(GridPair const& p)
{
if (!getNGrid(p.x_coord, p.y_coord))
{
setNGrid(new NGridType(p.x_coord * MAX_NUMBER_OF_GRIDS + p.y_coord, p.x_coord, p.y_coord, m_gridExpiry, sWorld.getConfig(CONFIG_BOOL_GRID_UNLOAD)),
p.x_coord, p.y_coord);
// build a linkage between this map and NGridType
buildNGridLinkage(getNGrid(p.x_coord, p.y_coord));
getNGrid(p.x_coord, p.y_coord)->SetGridState(GRID_STATE_IDLE);
//z coord
int gx = (MAX_NUMBER_OF_GRIDS - 1) - p.x_coord;
int gy = (MAX_NUMBER_OF_GRIDS - 1) - p.y_coord;
ASSERT(gx < MAX_NUMBER_OF_GRIDS);
ASSERT(gy < MAX_NUMBER_OF_GRIDS);
if (!m_bLoadedGrids[gx][gy])
LoadMapAndVMap(gx, gy);
}
}
void
Map::EnsureGridLoadedAtEnter(Cell const& cell, Player* player)
{
NGridType* grid;
if (EnsureGridLoaded(cell))
{
grid = getNGrid(cell.GridX(), cell.GridY());
if (player)
DEBUG_FILTER_LOG(LOG_FILTER_PLAYER_MOVES, "Player %s enter cell[%u,%u] triggers of loading grid[%u,%u] on map %u", player->GetName(), cell.CellX(), cell.CellY(), cell.GridX(), cell.GridY(), m_id);
else
DEBUG_FILTER_LOG(LOG_FILTER_PLAYER_MOVES, "Active object nearby triggers of loading grid [%u,%u] on map %u", cell.GridX(), cell.GridY(), m_id);
ResetGridExpiry(*getNGrid(cell.GridX(), cell.GridY()), 0.1f);
grid->SetGridState(GRID_STATE_ACTIVE);
}
else
grid = getNGrid(cell.GridX(), cell.GridY());
if (player)
AddToGrid(player, grid, cell);
}
bool Map::EnsureGridLoaded(Cell const& cell)
{
EnsureGridCreated(GridPair(cell.GridX(), cell.GridY()));
NGridType* grid = getNGrid(cell.GridX(), cell.GridY());
if (grid == nullptr)
{
sLog.Out(LOG_BASIC, LOG_LVL_MINIMAL, "[Map%u][CRASH] Grid [%u:%u] NOT loaded !!", m_id, cell.GridX(), cell.GridY());
throw new std::string("Crash AT EnsureGridLoaded");
}
if (!grid->isGridObjectDataLoaded())
{
//it's important to set it loaded before loading!
//otherwise there is a possibility of infinity chain (grid loading will be called many times for the same grid)
//possible scenario:
//active object A(loaded with loader.LoadN call and added to the map)
//summons some active object B, while B added to map grid loading called again and so on..
ASSERT(!m_unloading && "Trying to load grid while unloading the whole map !");
grid->setGridObjectDataLoaded(true);
ObjectGridLoader loader(*grid, this, cell);
loader.LoadN();
// Add resurrectable corpses to world object list in grid
sObjectAccessor.AddCorpsesToGrid(GridPair(cell.GridX(), cell.GridY()), (*grid)(cell.CellX(), cell.CellY()), this);
//Balance();
return true;
}
return false;
}
void Map::ForceLoadGridsAroundPosition(float x, float y)
{
if (!IsLoaded(x, y))
{
CellPair p = MaNGOS::ComputeCellPair(x, y);
Cell cell(p);
EnsureGridLoadedAtEnter(cell);
NULLNotifier notifier = NULLNotifier();
Cell::VisitAllObjects(x, y, this, notifier, GetGridActivationDistance(), false);
}
}
void Map::LoadGrid(Cell const& cell, bool no_unload)
{
EnsureGridLoaded(cell);
if (no_unload)
getNGrid(cell.GridX(), cell.GridY())->setUnloadExplicitLock(true);
}
bool Map::Add(Player* player)
{
player->GetMapRef().link(this, player);
player->SetMap(this);
// update player state for other player and visa-versa
CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
Cell cell(p);
EnsureGridLoadedAtEnter(cell, player);
player->AddToWorld();
player->LoadMapCellsAround(GetGridActivationDistance());
// Order matters! Send the world first, and the player then
// so that closed doors are closed when the player appears.
// Send init first => Can walk through doors at login
// Send objects first => Can not take quests at relogin
SendInitTransports(player);
SendInitSelf(player);
// Clear m_visibleGUIDs in case 2 players entered a map at the same time,
// one could stay invisible from the other until re-zoning.
// Inspired from the TrinityCore way.
if (player->IsBeingTeleportedFar())
player->m_visibleGUIDs.clear();
NGridType* grid = getNGrid(cell.GridX(), cell.GridY());
player->GetViewPoint().Event_AddedToWorld(&(*grid)(cell.CellX(), cell.CellY()));
UpdateObjectVisibility(player, cell, p);
if (m_data)
m_data->OnPlayerEnter(player);
// Remove any buffs defined in instance_aura_removal for the new map
sAuraRemovalMgr.PlayerEnterMap(m_id, player);
player->SetSplineDonePending(false);
// don't clear movement packets during login or we might discard CMSG_SET_ACTIVE_MOVER
if (!player->GetSession()->PlayerLoading())
player->GetSession()->ClearIncomingPacketsByType(PACKET_PROCESS_MOVEMENT);
if (player->m_broadcaster)
player->m_broadcaster->SetInstanceId(GetInstanceId());
return true;
}
void Map::ExistingPlayerLogin(Player* player)
{
// Reset visibility list
for (ObjectGuidSet::const_iterator it = player->m_visibleGUIDs.begin(); it != player->m_visibleGUIDs.end(); ++it)
if (Player* other = GetPlayer(*it))
if (other->m_broadcaster)
other->m_broadcaster->RemoveListener(player);
player->m_visibleGUIDs.clear();
SendInitTransports(player);
SendInitSelf(player);
CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
Cell cell(p);
EnsureGridLoaded(cell);
NGridType* grid = getNGrid(cell.GridX(), cell.GridY());
player->GetViewPoint().Event_AddedToWorld(&(*grid)(cell.CellX(), cell.CellY()));
UpdateObjectVisibility(player, cell, p);
// Refresh aura durations
for (const auto& it : player->GetSpellAuraHolderMap())
it.second->UpdateAuraDuration();
}
template<class T>
void
Map::Add(T* obj)
{
MANGOS_ASSERT(obj);
CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
if (p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
{
sLog.Out(LOG_BASIC, LOG_LVL_ERROR, "Map::Add: Object (GUID: %u TypeId: %u) have invalid coordinates X:%f Y:%f grid cell [%u:%u]", obj->GetGUIDLow(), obj->GetTypeId(), obj->GetPositionX(), obj->GetPositionY(), p.x_coord, p.y_coord);
return;
}
obj->SetMap(this);
Cell cell(p);
if (obj->IsActiveObject() && !IsUnloading())
EnsureGridLoadedAtEnter(cell);
else
EnsureGridCreated(GridPair(cell.GridX(), cell.GridY()));
NGridType* grid = getNGrid(cell.GridX(), cell.GridY());
MANGOS_ASSERT(grid != nullptr);
AddToGrid(obj, grid, cell);
obj->AddToWorld();
if (obj->IsActiveObject() && !IsUnloading())
AddToActive(obj);
sLog.Out(LOG_BASIC, LOG_LVL_DEBUG, "%s enters grid[%u,%u]", obj->GetObjectGuid().GetString().c_str(), cell.GridX(), cell.GridY());
obj->GetViewPoint().Event_AddedToWorld(&(*grid)(cell.CellX(), cell.CellY()));
obj->SetIsNewObject(true);
UpdateObjectVisibility(obj, cell, p);
obj->SetIsNewObject(false);
if (Creature* pCreature = obj->ToCreature())
pCreature->CastSpawnSpell();
}
template<>
void Map::Add(GenericTransport* obj)
{
MANGOS_ASSERT(obj);
//TODO: Needs clean up. An object should not be added to map twice.
if (obj->IsInWorld())
return;
CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
if (p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
{
sLog.Out(LOG_BASIC, LOG_LVL_ERROR, "Map::Add: Transport (GUID: %u TypeId: %u) have invalid coordinates X:%f Y:%f grid cell [%u:%u]", obj->GetGUIDLow(), obj->GetTypeId(), obj->GetPositionX(), obj->GetPositionY(), p.x_coord, p.y_coord);
return; // Should delete object
}
obj->SetMap(this);
obj->AddToWorld();
//sLog.Out(LOG_BASIC, LOG_LVL_DEBUG, "%s enters grid[%u,%u]", obj->GetObjectGuid().GetString().c_str(), cell.GridX(), cell.GridY());
//obj->GetViewPoint().Event_AddedToWorld(&(*grid)(cell.CellX(), cell.CellY()));
m_transports.insert(obj);
// Make sure elevator position is right before sending create packet
if (obj->GetGoType() == GAMEOBJECT_TYPE_TRANSPORT)
obj->Update(0, 0);
// Broadcast creation to players
obj->SendCreateUpdateToMap();
}
template<>
void Map::Add(ShipTransport* obj)
{
Add<GenericTransport>(obj);
}
template<>
void Map::Add(ElevatorTransport* obj)
{
Add<GenericTransport>(obj);
}
void Map::LoadElevatorTransports()
{
ElevatorTransportMapBounds itrPair = sTransportMgr.GetElevatorTransportsForMap(GetId());
for (auto itr = itrPair.first; itr != itrPair.second; itr++)
{
GameObjectData const* pData = sObjectMgr.GetGOData(itr->second);
if (!pData)
{
sLog.Out(LOG_BASIC, LOG_LVL_ERROR, "[Map::LoadElevatorTransports] Invalid elevator guid %u for map %u!", itr->second, itr->first);
continue;
}
GameObjectInfo const* pInfo = sObjectMgr.GetGameObjectTemplate(pData->id);
if (!pInfo)
{
sLog.Out(LOG_BASIC, LOG_LVL_ERROR, "[Map::LoadElevatorTransports] Missing gameobject template %u for guid %u!", pData->id, itr->second);
continue;
}
if (pInfo->type != GAMEOBJECT_TYPE_TRANSPORT)
{
sLog.Out(LOG_BASIC, LOG_LVL_ERROR, "[Map::LoadElevatorTransports] Non-elevator guid %u for map %u!", itr->second, itr->first);
continue;
}
ElevatorTransport* pGo = new ElevatorTransport;
if (!pGo->LoadFromDB(itr->second, this))
{
delete pGo;
continue;
}
Add<ElevatorTransport>(pGo);
}
}
void Map::MessageBroadcast(Player const* player, WorldPacket* msg, bool to_self)
{
CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
if (p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
{
sLog.Out(LOG_BASIC, LOG_LVL_ERROR, "Map::MessageBroadcast: Player (GUID: %u) have invalid coordinates X:%f Y:%f grid cell [%u:%u]", player->GetGUIDLow(), player->GetPositionX(), player->GetPositionY(), p.x_coord, p.y_coord);
return;
}
Cell cell(p);
cell.SetNoCreate();
if (!loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)))
return;
MaNGOS::MessageDeliverer post_man(*player, msg, to_self);
TypeContainerVisitor<MaNGOS::MessageDeliverer, WorldTypeMapContainer > message(post_man);
cell.Visit(p, message, *this, *player, GetVisibilityDistance());
}
void Map::MessageBroadcast(WorldObject const* obj, WorldPacket* msg)
{
CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
if (p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
{
sLog.Out(LOG_BASIC, LOG_LVL_ERROR, "Map::MessageBroadcast: Object (GUID: %u TypeId: %u) have invalid coordinates X:%f Y:%f grid cell [%u:%u]", obj->GetGUIDLow(), obj->GetTypeId(), obj->GetPositionX(), obj->GetPositionY(), p.x_coord, p.y_coord);
return;
}
Cell cell(p);
cell.SetNoCreate();
if (!loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)))
return;
//TODO: currently on continents when Visibility.Distance.InFlight > Visibility.Distance.Continents
//we have alot of blinking mobs because monster move packet send is broken...
MaNGOS::ObjectMessageDeliverer post_man(msg);
TypeContainerVisitor<MaNGOS::ObjectMessageDeliverer, WorldTypeMapContainer > message(post_man);
cell.Visit(p, message, *this, *obj, GetVisibilityDistance());
}
void Map::MessageDistBroadcast(Player const* player, WorldPacket* msg, float dist, bool to_self, bool own_team_only)
{
CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
if (p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
{
sLog.Out(LOG_BASIC, LOG_LVL_ERROR, "Map::MessageBroadcast: Player (GUID: %u) have invalid coordinates X:%f Y:%f grid cell [%u:%u]", player->GetGUIDLow(), player->GetPositionX(), player->GetPositionY(), p.x_coord, p.y_coord);
return;
}
Cell cell(p);
cell.SetNoCreate();
if (!loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)))
return;
MaNGOS::MessageDistDeliverer post_man(*player, msg, dist, to_self, own_team_only);
TypeContainerVisitor<MaNGOS::MessageDistDeliverer , WorldTypeMapContainer > message(post_man);
cell.Visit(p, message, *this, *player, dist);
}
void Map::MessageDistBroadcast(WorldObject const* obj, WorldPacket* msg, float dist)
{
CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
if (p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
{
sLog.Out(LOG_BASIC, LOG_LVL_ERROR, "Map::MessageBroadcast: Object (GUID: %u TypeId: %u) have invalid coordinates X:%f Y:%f grid cell [%u:%u]", obj->GetGUIDLow(), obj->GetTypeId(), obj->GetPositionX(), obj->GetPositionY(), p.x_coord, p.y_coord);
return;
}
Cell cell(p);
cell.SetNoCreate();
if (!loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)))
return;
MaNGOS::ObjectMessageDistDeliverer post_man(*obj, msg, dist);
TypeContainerVisitor<MaNGOS::ObjectMessageDistDeliverer, WorldTypeMapContainer > message(post_man);
cell.Visit(p, message, *this, *obj, dist);
}
bool Map::loaded(GridPair const& p) const
{
NGridType const* grid = getNGrid(p.x_coord, p.y_coord);
return (grid && grid->isGridObjectDataLoaded());
}
void Map::UpdateSync(uint32 const diff)
{
// Needs to be updated here.
// Can lead to map <-> map teleports
for (m_transportsUpdateIter = m_transports.begin(); m_transportsUpdateIter != m_transports.end();)
{
WorldObject* obj = *m_transportsUpdateIter;
++m_transportsUpdateIter;
if (!obj->IsInWorld())
continue;
obj->Update(diff, diff);
}
}
inline void Map::UpdateCellsAroundObject(uint32 now, uint32 diff, WorldObject const* object)
{
if (!object || !object->IsInWorld() || !object->IsPositionValid())
return;
MaNGOS::ObjectUpdater updater(diff, now);
TypeContainerVisitor<MaNGOS::ObjectUpdater, GridTypeMapContainer > grid_object_update(updater);
TypeContainerVisitor<MaNGOS::ObjectUpdater, WorldTypeMapContainer > world_object_update(updater);
//lets update mobs/objects in ALL visible cells around player!
CellArea area = Cell::CalculateCellArea(object->GetPositionX(), object->GetPositionY(), GetGridActivationDistance());
for (uint32 x = area.low_bound.x_coord; x <= area.high_bound.x_coord; ++x)
{
for (uint32 y = area.low_bound.y_coord; y <= area.high_bound.y_coord; ++y)
{
// marked cells are those that have been visited
// don't visit the same cell twice
uint32 cell_id = (y * TOTAL_NUMBER_OF_CELLS_PER_MAP) + x;
if (!isCellMarked(cell_id))
{
markCell(cell_id);
CellPair pair(x, y);
Cell cell(pair);
cell.SetNoCreate();
Visit(cell, grid_object_update);
Visit(cell, world_object_update);
}
}
}
}
inline void Map::MarkCellsAroundObject(WorldObject const* object)
{
if (!object || !object->IsInWorld() || !object->IsPositionValid())
return;
CellArea area = Cell::CalculateCellArea(object->GetPositionX(), object->GetPositionY(), GetGridActivationDistance());
for (uint32 x = area.low_bound.x_coord; x <= area.high_bound.x_coord; ++x)
{
for (uint32 y = area.low_bound.y_coord; y <= area.high_bound.y_coord; ++y)
{
uint32 cell_id = (y * TOTAL_NUMBER_OF_CELLS_PER_MAP) + x;
markCell(cell_id);
}
}
}
inline void Map::UpdateActiveCellsCallback(uint32 diff, uint32 now, uint32 threadId, uint32 totalThreads, uint32 step)
{
MaNGOS::ObjectUpdater updater(diff, now);
TypeContainerVisitor<MaNGOS::ObjectUpdater, GridTypeMapContainer > grid_object_update(updater);
TypeContainerVisitor<MaNGOS::ObjectUpdater, WorldTypeMapContainer > world_object_update(updater);
int safeDistCells = sWorld.getConfig(CONFIG_UINT32_MTCELLS_SAFEDISTANCE) / SIZE_OF_GRID_CELL + 1;
totalThreads *= 2;
threadId = 2 * threadId + step;
for (int y = 0; y < TOTAL_NUMBER_OF_CELLS_PER_MAP; ++y)
{
// Skip grids not for this thread
if ((y / safeDistCells) % totalThreads != threadId)
continue;
for (int x = 0; x < TOTAL_NUMBER_OF_CELLS_PER_MAP; ++x)
{
uint32 cellId = (y * TOTAL_NUMBER_OF_CELLS_PER_MAP) + x;
if (!isCellMarked(cellId))
continue;
CellPair pair(x, y);
Cell cell(pair);
cell.SetNoCreate();
Visit(cell, grid_object_update);
Visit(cell, world_object_update);
}
}
}
inline void Map::UpdateActiveCellsAsynch(uint32 now, uint32 diff)
{
resetMarkedCells();
// Mark all cells that need update
for (m_mapRefIter = m_mapRefManager.begin(); m_mapRefIter != m_mapRefManager.end(); ++m_mapRefIter)
MarkCellsAroundObject(m_mapRefIter->getSource());
for (m_activeNonPlayersIter = m_activeNonPlayers.begin(); m_activeNonPlayersIter != m_activeNonPlayers.end(); ++m_activeNonPlayersIter)
MarkCellsAroundObject(*m_activeNonPlayersIter);
const int nthreads = m_cellThreads->size();
for (int step = 0; step < 2; step++)
{
for (int i = 0; i < nthreads; ++i)
m_cellThreads << [this, diff, now, i, nthreads, step](){
UpdateActiveCellsCallback(diff, now, i, nthreads+1, step);
};
std::future<void> job = m_cellThreads->processWorkload();
UpdateActiveCellsCallback(diff, now, nthreads, nthreads+1, step);
if (job.valid())
job.wait();
}
}
inline void Map::UpdateActiveCellsSynch(uint32 now, uint32 diff)
{
resetMarkedCells();
// the player iterator is stored in the map object
// to make sure calls to Map::Remove don't invalidate it
for (m_mapRefIter = m_mapRefManager.begin(); m_mapRefIter != m_mapRefManager.end(); ++m_mapRefIter)
{
Player* plr = m_mapRefIter->getSource();
UpdateCellsAroundObject(now, diff, plr);
}
// non-player active objects
for (m_activeNonPlayersIter = m_activeNonPlayers.begin(); m_activeNonPlayersIter != m_activeNonPlayers.end();)
{
// skip not in world
WorldObject* obj = *m_activeNonPlayersIter;
// step before processing, in this case if Map::Remove remove next object we correctly
// step to next-next, and if we step to end() then newly added objects can wait next update.
++m_activeNonPlayersIter;
UpdateCellsAroundObject(now, diff, obj);
}
}
inline void Map::UpdateCells(uint32 map_diff)
{
uint32 now = WorldTimer::getMSTime();
uint32 diff = WorldTimer::getMSTimeDiff(m_lastCellsUpdate, now);
if (diff < sWorld.getConfig(CONFIG_UINT32_MAPUPDATE_UPDATE_CELLS_DIFF))
return;
m_lastCellsUpdate = now;
m_currentTime = std::chrono::time_point_cast<std::chrono::milliseconds>(Clock::now());
// update active cells around players and active objects
if (IsContinent() && m_cellThreads->status() == ThreadPool::Status::READY)
UpdateActiveCellsAsynch(now, diff);
else
UpdateActiveCellsSynch(now, diff);
if (IsContinent() && m_motionThreads->status() == ThreadPool::Status::READY && !m_unitsMvtUpdate.empty())
{
for (std::unordered_set<Unit*>::iterator it = m_unitsMvtUpdate.begin(); it != m_unitsMvtUpdate.end(); it++)
m_motionThreads << [it,diff](){
if ((*it)->IsInWorld())
(*it)->GetMotionMaster()->UpdateMotionAsync(diff);
};
m_motionThreads->processWorkload().wait();
}
m_unitsMvtUpdate.clear();
}
void Map::ProcessSessionPackets(PacketProcessing type)
{
TimePoint beginTime = std::chrono::time_point_cast<std::chrono::milliseconds>(Clock::now());
// update worldsessions for existing players
for (m_mapRefIter = m_mapRefManager.begin(); m_mapRefIter != m_mapRefManager.end(); ++m_mapRefIter)
{
Player* plr = m_mapRefIter->getSource();
if (plr && plr->IsInWorld())
{
if (type == PACKET_PROCESS_SPELLS)
plr->UpdateCooldowns(beginTime);
WorldSession* pSession = plr->GetSession();
MapSessionFilter updater(pSession);
updater.SetProcessType(type);
pSession->ProcessPackets(updater);
}
}
auto elapsedTime = std::chrono::time_point_cast<std::chrono::milliseconds>(Clock::now()) - beginTime;
if (sWorld.getConfig(CONFIG_UINT32_PERFLOG_SLOW_MAP_PACKETS) && elapsedTime.count() > sWorld.getConfig(CONFIG_UINT32_PERFLOG_SLOW_MAP_PACKETS))
sLog.Out(LOG_PERFORMANCE, LOG_LVL_BASIC, "Map %u inst %u: %3ums to update packets type %u", GetId(), GetInstanceId(), elapsedTime.count(), type);
}
void Map::UpdateSessionsMovementAndSpellsIfNeeded()
{
uint32 now = WorldTimer::getMSTime();
uint32 diff = WorldTimer::getMSTimeDiff(m_lastMvtSpellsUpdate, now);
if (diff < sWorld.getConfig(CONFIG_UINT32_MAPUPDATE_UPDATE_PACKETS_DIFF))
return;
ProcessSessionPackets(PACKET_PROCESS_MOVEMENT);
ProcessSessionPackets(PACKET_PROCESS_SPELLS);
m_lastMvtSpellsUpdate = WorldTimer::getMSTime();
}
void Map::UpdatePlayers()
{
uint32 now = WorldTimer::getMSTime();
uint32 diff = WorldTimer::getMSTimeDiff(m_lastPlayersUpdate, now);
if (diff < sWorld.getConfig(CONFIG_UINT32_MAPUPDATE_UPDATE_PLAYERS_DIFF))
return;
m_currentTime = std::chrono::time_point_cast<std::chrono::milliseconds>(Clock::now());
++m_inactivePlayersSkippedUpdates;
bool updateInactivePlayers = m_inactivePlayersSkippedUpdates > sWorld.getConfig(CONFIG_UINT32_INACTIVE_PLAYERS_SKIP_UPDATES);
if (!IsContinent())
updateInactivePlayers = true;
for (m_mapRefIter = m_mapRefManager.begin(); m_mapRefIter != m_mapRefManager.end(); ++m_mapRefIter)
{
Player* plr = m_mapRefIter->getSource();
if (!plr || !plr->IsInWorld())
continue;
if (!updateInactivePlayers && (!plr->IsInCombat() && !plr->GetSession()->HasRecentPacket(PACKET_PROCESS_SPELLS) && !plr->HasScheduledEvent()))
{
plr->AddSkippedUpdateTime(diff);
continue;
}
WorldObject::UpdateHelper helper(plr);
helper.UpdateRealTime(now, diff + plr->GetSkippedUpdateTime());
plr->ResetSkippedUpdateTime();
}
if (updateInactivePlayers)
m_inactivePlayersSkippedUpdates = 0;
m_lastPlayersUpdate = now;
}
void Map::DoUpdate(uint32 maxDiff)
{
uint32 now = WorldTimer::getMSTime();
uint32 diff = WorldTimer::getMSTimeDiff(m_lastMapUpdate, now);
if (diff > maxDiff)
diff = maxDiff;
m_lastMapUpdate = now;
if (HavePlayers())
m_lastPlayerLeftTime = now;
Update(diff);
}
void Map::Update(uint32 t_diff)
{
uint32 updateMapTime = WorldTimer::getMSTime();
m_currentTime = std::chrono::time_point_cast<std::chrono::milliseconds>(Clock::now());
m_dynamicTree.update(t_diff);
UpdateSessionsMovementAndSpellsIfNeeded();
// update worldsessions for existing players
for (m_mapRefIter = m_mapRefManager.begin(); m_mapRefIter != m_mapRefManager.end(); ++m_mapRefIter)
{
Player* plr = m_mapRefIter->getSource();
if (plr && plr->IsInWorld())
{
WorldSession* pSession = plr->GetSession();
MapSessionFilter updater(pSession);
pSession->Update(updater);
}
}
uint32 sessionsUpdateTime = WorldTimer::getMSTimeDiffToNow(updateMapTime);
// update players at tick
std::chrono::high_resolution_clock::time_point start = std::chrono::high_resolution_clock::now();
UpdateSessionsMovementAndSpellsIfNeeded();
UpdatePlayers();
uint32 playersUpdateTime = WorldTimer::getMSTimeDiffToNow(updateMapTime) - sessionsUpdateTime;
UpdateCells(t_diff);
uint32 activeCellsUpdateTime = WorldTimer::getMSTimeDiffToNow(updateMapTime) - playersUpdateTime - sessionsUpdateTime;
// Send world objects and item update field changes
SendObjectUpdates();
uint32 objectsUpdateTime = WorldTimer::getMSTimeDiffToNow(updateMapTime) - activeCellsUpdateTime - playersUpdateTime - sessionsUpdateTime;
UpdateVisibilityForRelocations();
uint32 visibilityUpdateTime = WorldTimer::getMSTimeDiffToNow(updateMapTime) - objectsUpdateTime - activeCellsUpdateTime - playersUpdateTime - sessionsUpdateTime;
UpdateSessionsMovementAndSpellsIfNeeded();
UpdatePlayers();
uint32 playersUpdateTime2 = WorldTimer::getMSTimeDiffToNow(updateMapTime) - objectsUpdateTime - activeCellsUpdateTime - playersUpdateTime - sessionsUpdateTime - visibilityUpdateTime;
RemoveCorpses();
RemoveOldBones(t_diff);
updateMapTime = WorldTimer::getMSTimeDiffToNow(updateMapTime);
uint32 additionnalWaitTime = 0;
uint32 additionnalUpdateCounts = 0;
if (!Instanceable())