* Fix some warlock talent work
[getmangos.git] / src / game / ObjectAccessor.cpp
blob5ce16ca3c655db0596ae33883622c97a075e9b64
1 /*
2 * Copyright (C) 2005-2008 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include "ObjectAccessor.h"
20 #include "ObjectMgr.h"
21 #include "Policies/SingletonImp.h"
22 #include "Player.h"
23 #include "Creature.h"
24 #include "GameObject.h"
25 #include "DynamicObject.h"
26 #include "Corpse.h"
27 #include "WorldSession.h"
28 #include "WorldPacket.h"
29 #include "Item.h"
30 #include "Corpse.h"
31 #include "GridNotifiers.h"
32 #include "MapManager.h"
33 #include "Map.h"
34 #include "CellImpl.h"
35 #include "GridNotifiersImpl.h"
36 #include "Opcodes.h"
37 #include "ObjectDefines.h"
38 #include "MapInstanced.h"
40 #include <cmath>
42 #define CLASS_LOCK MaNGOS::ClassLevelLockable<ObjectAccessor, ZThread::FastMutex>
43 INSTANTIATE_SINGLETON_2(ObjectAccessor, CLASS_LOCK);
44 INSTANTIATE_CLASS_MUTEX(ObjectAccessor, ZThread::FastMutex);
46 namespace MaNGOS
48 struct MANGOS_DLL_DECL BuildUpdateForPlayer
50 Player &i_player;
51 UpdateDataMapType &i_updatePlayers;
53 BuildUpdateForPlayer(Player &player, UpdateDataMapType &data_map) : i_player(player), i_updatePlayers(data_map) {}
55 void Visit(PlayerMapType &m)
57 for(PlayerMapType::iterator iter=m.begin(); iter != m.end(); ++iter)
59 if( iter->getSource() == &i_player )
60 continue;
62 UpdateDataMapType::iterator iter2 = i_updatePlayers.find(iter->getSource());
63 if( iter2 == i_updatePlayers.end() )
65 std::pair<UpdateDataMapType::iterator, bool> p = i_updatePlayers.insert( ObjectAccessor::UpdateDataValueType(iter->getSource(), UpdateData()) );
66 assert(p.second);
67 iter2 = p.first;
70 i_player.BuildValuesUpdateBlockForPlayer(&iter2->second, iter2->first);
74 template<class SKIP> void Visit(GridRefManager<SKIP> &) {}
78 ObjectAccessor::ObjectAccessor() {}
79 ObjectAccessor::~ObjectAccessor() {}
81 Creature*
82 ObjectAccessor::GetNPCIfCanInteractWith(Player const &player, uint64 guid, uint32 npcflagmask)
84 // unit checks
85 if (!guid)
86 return NULL;
88 // exist
89 Creature *unit = GetCreature(player, guid);
90 if (!unit)
91 return NULL;
93 // player check
94 if(!player.CanInteractWithNPCs(!unit->isSpiritService()))
95 return NULL;
97 // appropriate npc type
98 if(npcflagmask && !unit->HasFlag( UNIT_NPC_FLAGS, npcflagmask ))
99 return NULL;
101 // alive or spirit healer
102 if(!unit->isAlive() && (!unit->isSpiritService() || player.isAlive() ))
103 return NULL;
105 // not allow interaction under control
106 if(unit->GetCharmerOrOwnerGUID())
107 return NULL;
109 // not enemy
110 if( unit->IsHostileTo(&player))
111 return NULL;
113 // not unfriendly
114 FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(unit->getFaction());
115 if(factionTemplate)
117 FactionEntry const* faction = sFactionStore.LookupEntry(factionTemplate->faction);
118 if( faction->reputationListID >= 0 && player.GetReputationRank(faction) <= REP_UNFRIENDLY)
119 return NULL;
122 // not too far
123 if(!unit->IsWithinDistInMap(&player,INTERACTION_DISTANCE))
124 return NULL;
126 return unit;
129 Creature*
130 ObjectAccessor::GetCreatureOrPet(WorldObject const &u, uint64 guid)
132 if(Creature *unit = GetPet(guid))
133 return unit;
135 return GetCreature(u, guid);
138 Creature*
139 ObjectAccessor::GetCreature(WorldObject const &u, uint64 guid)
141 Creature * ret = GetObjectInWorld(guid, (Creature*)NULL);
142 if(!ret)
143 return NULL;
145 if(ret->GetMapId() != u.GetMapId())
146 return NULL;
148 if(ret->GetInstanceId() != u.GetInstanceId())
149 return NULL;
151 return ret;
154 Unit*
155 ObjectAccessor::GetUnit(WorldObject const &u, uint64 guid)
157 if(!guid)
158 return NULL;
160 if(IS_PLAYER_GUID(guid))
161 return FindPlayer(guid);
163 return GetCreatureOrPet(u, guid);
166 Corpse*
167 ObjectAccessor::GetCorpse(WorldObject const &u, uint64 guid)
169 Corpse * ret = GetObjectInWorld(guid, (Corpse*)NULL);
170 if(ret && ret->GetMapId() != u.GetMapId()) ret = NULL;
171 return ret;
174 Object* ObjectAccessor::GetObjectByTypeMask(Player const &p, uint64 guid, uint32 typemask)
176 Object *obj = NULL;
178 if(typemask & TYPEMASK_PLAYER)
180 obj = FindPlayer(guid);
181 if(obj) return obj;
184 if(typemask & TYPEMASK_UNIT)
186 obj = GetCreatureOrPet(p,guid);
187 if(obj) return obj;
190 if(typemask & TYPEMASK_GAMEOBJECT)
192 obj = GetGameObject(p,guid);
193 if(obj) return obj;
196 if(typemask & TYPEMASK_DYNAMICOBJECT)
198 obj = GetDynamicObject(p,guid);
199 if(obj) return obj;
202 if(typemask & TYPEMASK_ITEM)
204 obj = p.GetItemByGuid( guid );
205 if(obj) return obj;
208 return NULL;
211 GameObject*
212 ObjectAccessor::GetGameObject(WorldObject const &u, uint64 guid)
214 GameObject * ret = GetObjectInWorld(guid, (GameObject*)NULL);
215 if(ret && ret->GetMapId() != u.GetMapId()) ret = NULL;
216 return ret;
219 DynamicObject*
220 ObjectAccessor::GetDynamicObject(Unit const &u, uint64 guid)
222 DynamicObject * ret = GetObjectInWorld(guid, (DynamicObject*)NULL);
223 if(ret && ret->GetMapId() != u.GetMapId()) ret = NULL;
224 return ret;
227 Player*
228 ObjectAccessor::FindPlayer(uint64 guid)
230 return GetObjectInWorld(guid, (Player*)NULL);
233 Player*
234 ObjectAccessor::FindPlayerByName(const char *name)
236 //TODO: Player Guard
237 HashMapHolder<Player>::MapType& m = HashMapHolder<Player>::GetContainer();
238 HashMapHolder<Player>::MapType::iterator iter = m.begin();
239 for(; iter != m.end(); ++iter)
240 if( ::strcmp(name, iter->second->GetName()) == 0 )
241 return iter->second;
242 return NULL;
245 void
246 ObjectAccessor::SaveAllPlayers()
248 Guard guard(*HashMapHolder<Player*>::GetLock());
249 HashMapHolder<Player>::MapType& m = HashMapHolder<Player>::GetContainer();
250 HashMapHolder<Player>::MapType::iterator itr = m.begin();
251 for(; itr != m.end(); ++itr)
252 itr->second->SaveToDB();
255 void
256 ObjectAccessor::UpdateObject(Object* obj, Player* exceptPlayer)
258 UpdateDataMapType update_players;
259 obj->BuildUpdate(update_players);
261 WorldPacket packet;
262 for(UpdateDataMapType::iterator iter = update_players.begin(); iter != update_players.end(); ++iter)
264 if(iter->first == exceptPlayer)
265 continue;
267 iter->second.BuildPacket(&packet);
268 iter->first->GetSession()->SendPacket(&packet);
269 packet.clear();
273 void
274 ObjectAccessor::AddUpdateObject(Object *obj)
276 Guard guard(i_updateGuard);
277 i_objects.insert(obj);
280 void
281 ObjectAccessor::RemoveUpdateObject(Object *obj)
283 Guard guard(i_updateGuard);
284 std::set<Object *>::iterator iter = i_objects.find(obj);
285 if( iter != i_objects.end() )
286 i_objects.erase( iter );
289 void
290 ObjectAccessor::_buildUpdateObject(Object *obj, UpdateDataMapType &update_players)
292 bool build_for_all = true;
293 Player *pl = NULL;
294 if( obj->isType(TYPEMASK_ITEM) )
296 Item *item = static_cast<Item *>(obj);
297 pl = item->GetOwner();
298 build_for_all = false;
301 if( pl != NULL )
302 _buildPacket(pl, obj, update_players);
304 // Capt: okey for all those fools who think its a real fix
305 // THIS IS A TEMP FIX
306 if( build_for_all )
308 WorldObject * temp = dynamic_cast<WorldObject*>(obj);
310 //assert(dynamic_cast<WorldObject*>(obj)!=NULL);
311 if (temp)
312 _buildChangeObjectForPlayer(temp, update_players);
313 else
314 sLog.outDebug("ObjectAccessor: Ln 405 Temp bug fix");
318 void
319 ObjectAccessor::_buildPacket(Player *pl, Object *obj, UpdateDataMapType &update_players)
321 UpdateDataMapType::iterator iter = update_players.find(pl);
323 if( iter == update_players.end() )
325 std::pair<UpdateDataMapType::iterator, bool> p = update_players.insert( UpdateDataValueType(pl, UpdateData()) );
326 assert(p.second);
327 iter = p.first;
330 obj->BuildValuesUpdateBlockForPlayer(&iter->second, iter->first);
333 void
334 ObjectAccessor::_buildChangeObjectForPlayer(WorldObject *obj, UpdateDataMapType &update_players)
336 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
337 Cell cell(p);
338 cell.data.Part.reserved = ALL_DISTRICT;
339 cell.SetNoCreate();
340 WorldObjectChangeAccumulator notifier(*obj, update_players);
341 TypeContainerVisitor<WorldObjectChangeAccumulator, WorldTypeMapContainer > player_notifier(notifier);
342 CellLock<GridReadGuard> cell_lock(cell, p);
343 cell_lock->Visit(cell_lock, player_notifier, *obj->GetMap());
346 Pet*
347 ObjectAccessor::GetPet(uint64 guid)
349 return GetObjectInWorld(guid, (Pet*)NULL);
352 Corpse*
353 ObjectAccessor::GetCorpseForPlayerGUID(uint64 guid)
355 Guard guard(i_corpseGuard);
357 Player2CorpsesMapType::iterator iter = i_player2corpse.find(guid);
358 if( iter == i_player2corpse.end() ) return NULL;
360 assert(iter->second->GetType() != CORPSE_BONES);
362 return iter->second;
365 void
366 ObjectAccessor::RemoveCorpse(Corpse *corpse)
368 assert(corpse && corpse->GetType() != CORPSE_BONES);
370 Guard guard(i_corpseGuard);
371 Player2CorpsesMapType::iterator iter = i_player2corpse.find(corpse->GetOwnerGUID());
372 if( iter == i_player2corpse.end() )
373 return;
375 // build mapid*cellid -> guid_set map
376 CellPair cell_pair = MaNGOS::ComputeCellPair(corpse->GetPositionX(), corpse->GetPositionY());
377 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
379 objmgr.DeleteCorpseCellData(corpse->GetMapId(),cell_id,corpse->GetOwnerGUID());
380 corpse->RemoveFromWorld();
382 i_player2corpse.erase(iter);
385 void
386 ObjectAccessor::AddCorpse(Corpse *corpse)
388 assert(corpse && corpse->GetType() != CORPSE_BONES);
390 Guard guard(i_corpseGuard);
391 assert(i_player2corpse.find(corpse->GetOwnerGUID()) == i_player2corpse.end());
392 i_player2corpse[corpse->GetOwnerGUID()] = corpse;
394 // build mapid*cellid -> guid_set map
395 CellPair cell_pair = MaNGOS::ComputeCellPair(corpse->GetPositionX(), corpse->GetPositionY());
396 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
398 objmgr.AddCorpseCellData(corpse->GetMapId(),cell_id,corpse->GetOwnerGUID(),corpse->GetInstanceId());
401 void
402 ObjectAccessor::AddCorpsesToGrid(GridPair const& gridpair,GridType& grid,Map* map)
404 Guard guard(i_corpseGuard);
405 for(Player2CorpsesMapType::iterator iter = i_player2corpse.begin(); iter != i_player2corpse.end(); ++iter)
406 if(iter->second->GetGrid()==gridpair)
408 // verify, if the corpse in our instance (add only corpses which are)
409 if (map->Instanceable())
411 if (iter->second->GetInstanceId() == map->GetInstanceId())
413 grid.AddWorldObject(iter->second,iter->second->GetGUID());
416 else
418 grid.AddWorldObject(iter->second,iter->second->GetGUID());
423 Corpse*
424 ObjectAccessor::ConvertCorpseForPlayer(uint64 player_guid)
426 Corpse *corpse = GetCorpseForPlayerGUID(player_guid);
427 if(!corpse)
429 //in fact this function is called from several places
430 //even when player doesn't have a corpse, not an error
431 //sLog.outError("ERROR: Try remove corpse that not in map for GUID %ul", player_guid);
432 return NULL;
435 DEBUG_LOG("Deleting Corpse and spawning bones.\n");
437 // remove corpse from player_guid -> corpse map
438 RemoveCorpse(corpse);
440 // remove resurrectble corpse from grid object registry (loaded state checked into call)
441 // do not load the map if it's not loaded
442 Map *map = MapManager::Instance().FindMap(corpse->GetMapId(), corpse->GetInstanceId());
443 if(map) map->Remove(corpse,false);
445 // remove corpse from DB
446 corpse->DeleteFromDB();
448 Corpse *bones = NULL;
449 // create the bones only if the map and the grid is loaded at the corpse's location
450 if(map && !map->IsRemovalGrid(corpse->GetPositionX(), corpse->GetPositionY()))
452 // Create bones, don't change Corpse
453 bones = new Corpse;
454 bones->Create(corpse->GetGUIDLow());
456 for (int i = 3; i < CORPSE_END; i++) // don't overwrite guid and object type
457 bones->SetUInt32Value(i, corpse->GetUInt32Value(i));
459 bones->SetGrid(corpse->GetGrid());
460 // bones->m_time = m_time; // don't overwrite time
461 // bones->m_inWorld = m_inWorld; // don't overwrite world state
462 // bones->m_type = m_type; // don't overwrite type
463 bones->Relocate(corpse->GetPositionX(), corpse->GetPositionY(), corpse->GetPositionZ(), corpse->GetOrientation());
464 bones->SetMapId(corpse->GetMapId());
465 bones->SetInstanceId(corpse->GetInstanceId());
467 bones->SetUInt32Value(CORPSE_FIELD_FLAGS, CORPSE_FLAG_UNK2 | CORPSE_FLAG_BONES);
468 bones->SetUInt64Value(CORPSE_FIELD_OWNER, 0);
470 for (int i = 0; i < EQUIPMENT_SLOT_END; i++)
472 if(corpse->GetUInt32Value(CORPSE_FIELD_ITEM + i))
473 bones->SetUInt32Value(CORPSE_FIELD_ITEM + i, 0);
476 // add bones in grid store if grid loaded where corpse placed
477 map->Add(bones);
480 // all references to the corpse should be removed at this point
481 delete corpse;
483 return bones;
486 void
487 ObjectAccessor::Update(uint32 diff)
489 UpdateDataMapType update_players;
491 Guard guard(i_updateGuard);
492 while(!i_objects.empty())
494 Object* obj = *i_objects.begin();
495 i_objects.erase(i_objects.begin());
496 if (!obj)
497 continue;
498 _buildUpdateObject(obj, update_players);
499 obj->ClearUpdateMask(false);
503 WorldPacket packet; // here we allocate a std::vector with a size of 0x10000
504 for(UpdateDataMapType::iterator iter = update_players.begin(); iter != update_players.end(); ++iter)
506 iter->second.BuildPacket(&packet);
507 iter->first->GetSession()->SendPacket(&packet);
508 packet.clear(); // clean the string
512 void
513 ObjectAccessor::UpdatePlayers(uint32 diff)
515 HashMapHolder<Player>::MapType& playerMap = HashMapHolder<Player>::GetContainer();
516 for(HashMapHolder<Player>::MapType::iterator iter = playerMap.begin(); iter != playerMap.end(); ++iter)
517 if(iter->second->IsInWorld())
518 iter->second->Update(diff);
521 void
522 ObjectAccessor::WorldObjectChangeAccumulator::Visit(PlayerMapType &m)
524 for(PlayerMapType::iterator iter = m.begin(); iter != m.end(); ++iter)
525 if(iter->getSource()->HaveAtClient(&i_object))
526 ObjectAccessor::_buildPacket(iter->getSource(), &i_object, i_updateDatas);
529 void
530 ObjectAccessor::UpdateObjectVisibility(WorldObject *obj)
532 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
533 Cell cell(p);
535 obj->GetMap()->UpdateObjectVisibility(obj,cell,p);
538 void ObjectAccessor::UpdateVisibilityForPlayer( Player* player )
540 CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
541 Cell cell(p);
542 Map* m = player->GetMap();
544 m->UpdatePlayerVisibility(player,cell,p);
545 m->UpdateObjectsVisibilityFor(player,cell,p);
548 /// Define the static member of HashMapHolder
550 template <class T> UNORDERED_MAP< uint64, T* > HashMapHolder<T>::m_objectMap;
551 template <class T> ZThread::FastMutex HashMapHolder<T>::i_lock;
553 /// Global definitions for the hashmap storage
555 template class HashMapHolder<Player>;
556 template class HashMapHolder<Pet>;
557 template class HashMapHolder<GameObject>;
558 template class HashMapHolder<DynamicObject>;
559 template class HashMapHolder<Creature>;
560 template class HashMapHolder<Corpse>;
562 template Player* ObjectAccessor::GetObjectInWorld<Player>(uint32 mapid, float x, float y, uint64 guid, Player* /*fake*/);
563 template Pet* ObjectAccessor::GetObjectInWorld<Pet>(uint32 mapid, float x, float y, uint64 guid, Pet* /*fake*/);
564 template Creature* ObjectAccessor::GetObjectInWorld<Creature>(uint32 mapid, float x, float y, uint64 guid, Creature* /*fake*/);
565 template Corpse* ObjectAccessor::GetObjectInWorld<Corpse>(uint32 mapid, float x, float y, uint64 guid, Corpse* /*fake*/);
566 template GameObject* ObjectAccessor::GetObjectInWorld<GameObject>(uint32 mapid, float x, float y, uint64 guid, GameObject* /*fake*/);
567 template DynamicObject* ObjectAccessor::GetObjectInWorld<DynamicObject>(uint32 mapid, float x, float y, uint64 guid, DynamicObject* /*fake*/);