[7921] Set pet and for creature owner in Spell::EffectSummon similar other summon...
[getmangos.git] / src / game / GameObject.cpp
bloba0b49afce9017b9020ea0c1f0e67221f0c65dad5
1 /*
2 * Copyright (C) 2005-2009 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 "Common.h"
20 #include "QuestDef.h"
21 #include "GameObject.h"
22 #include "ObjectMgr.h"
23 #include "PoolHandler.h"
24 #include "SpellMgr.h"
25 #include "Spell.h"
26 #include "UpdateMask.h"
27 #include "Opcodes.h"
28 #include "WorldPacket.h"
29 #include "World.h"
30 #include "Database/DatabaseEnv.h"
31 #include "LootMgr.h"
32 #include "GridNotifiers.h"
33 #include "GridNotifiersImpl.h"
34 #include "CellImpl.h"
35 #include "InstanceData.h"
36 #include "BattleGround.h"
37 #include "Util.h"
39 GameObject::GameObject() : WorldObject()
41 m_objectType |= TYPEMASK_GAMEOBJECT;
42 m_objectTypeId = TYPEID_GAMEOBJECT;
43 // 2.3.2 - 0x58
44 m_updateFlag = (UPDATEFLAG_LOWGUID | UPDATEFLAG_HIGHGUID | UPDATEFLAG_HAS_POSITION);
46 m_valuesCount = GAMEOBJECT_END;
47 m_respawnTime = 0;
48 m_respawnDelayTime = 25;
49 m_lootState = GO_NOT_READY;
50 m_spawnedByDefault = true;
51 m_usetimes = 0;
52 m_spellId = 0;
53 m_charges = 5;
54 m_cooldownTime = 0;
55 m_goInfo = NULL;
57 m_DBTableGuid = 0;
60 GameObject::~GameObject()
62 if(m_uint32Values) // field array can be not exist if GameOBject not loaded
64 // Possible crash at access to deleted GO in Unit::m_gameobj
65 uint64 owner_guid = GetOwnerGUID();
66 if(owner_guid)
68 Unit* owner = ObjectAccessor::GetUnit(*this,owner_guid);
69 if(owner)
70 owner->RemoveGameObject(this,false);
71 else if(!IS_PLAYER_GUID(owner_guid))
72 sLog.outError("Delete GameObject (GUID: %u Entry: %u ) that have references in not found creature %u GO list. Crash possible later.",GetGUIDLow(),GetGOInfo()->id,GUID_LOPART(owner_guid));
77 void GameObject::AddToWorld()
79 ///- Register the gameobject for guid lookup
80 if(!IsInWorld()) ObjectAccessor::Instance().AddObject(this);
81 Object::AddToWorld();
84 void GameObject::RemoveFromWorld()
86 ///- Remove the gameobject from the accessor
87 if(IsInWorld()) ObjectAccessor::Instance().RemoveObject(this);
88 Object::RemoveFromWorld();
91 bool GameObject::Create(uint32 guidlow, uint32 name_id, Map *map, uint32 phaseMask, float x, float y, float z, float ang, float rotation0, float rotation1, float rotation2, float rotation3, uint32 animprogress, GOState go_state)
93 Relocate(x,y,z,ang);
94 SetMapId(map->GetId());
95 SetInstanceId(map->GetInstanceId());
96 SetPhaseMask(phaseMask,false);
98 if(!IsPositionValid())
100 sLog.outError("Gameobject (GUID: %u Entry: %u ) not created. Suggested coordinates isn't valid (X: %f Y: %f)",guidlow,name_id,x,y);
101 return false;
104 GameObjectInfo const* goinfo = objmgr.GetGameObjectInfo(name_id);
105 if (!goinfo)
107 sLog.outErrorDb("Gameobject (GUID: %u Entry: %u) not created: it have not exist entry in `gameobject_template`. Map: %u (X: %f Y: %f Z: %f) ang: %f rotation0: %f rotation1: %f rotation2: %f rotation3: %f",guidlow, name_id, map->GetId(), x, y, z, ang, rotation0, rotation1, rotation2, rotation3);
108 return false;
111 Object::_Create(guidlow, goinfo->id, HIGHGUID_GAMEOBJECT);
113 m_goInfo = goinfo;
115 if (goinfo->type >= MAX_GAMEOBJECT_TYPE)
117 sLog.outErrorDb("Gameobject (GUID: %u Entry: %u) not created: it have not exist GO type '%u' in `gameobject_template`. It's will crash client if created.",guidlow,name_id,goinfo->type);
118 return false;
121 SetFloatValue(GAMEOBJECT_POS_X, x);
122 SetFloatValue(GAMEOBJECT_POS_Y, y);
123 SetFloatValue(GAMEOBJECT_POS_Z, z);
125 SetFloatValue(GAMEOBJECT_PARENTROTATION+0, rotation0);
126 SetFloatValue(GAMEOBJECT_PARENTROTATION+1, rotation1);
128 UpdateRotationFields(rotation2,rotation3); // GAMEOBJECT_FACING, GAMEOBJECT_ROTATION, GAMEOBJECT_PARENTROTATION+2/3
130 SetFloatValue(OBJECT_FIELD_SCALE_X, goinfo->size);
132 SetUInt32Value(GAMEOBJECT_FACTION, goinfo->faction);
133 SetUInt32Value(GAMEOBJECT_FLAGS, goinfo->flags);
135 SetEntry(goinfo->id);
137 SetUInt32Value(GAMEOBJECT_DISPLAYID, goinfo->displayId);
139 SetGoState(go_state);
140 SetGoType(GameobjectTypes(goinfo->type));
142 SetGoAnimProgress(animprogress);
144 // Spell charges for GAMEOBJECT_TYPE_SPELLCASTER (22)
145 if (goinfo->type == GAMEOBJECT_TYPE_SPELLCASTER)
146 m_charges = goinfo->spellcaster.charges;
148 //Notify the map's instance data.
149 //Only works if you create the object in it, not if it is moves to that map.
150 //Normally non-players do not teleport to other maps.
151 if(map->IsDungeon() && ((InstanceMap*)map)->GetInstanceData())
153 ((InstanceMap*)map)->GetInstanceData()->OnObjectCreate(this);
156 return true;
159 void GameObject::Update(uint32 /*p_time*/)
161 if (IS_MO_TRANSPORT(GetGUID()))
163 //((Transport*)this)->Update(p_time);
164 return;
167 switch (m_lootState)
169 case GO_NOT_READY:
171 switch(GetGoType())
173 case GAMEOBJECT_TYPE_TRAP:
175 // Arming Time for GAMEOBJECT_TYPE_TRAP (6)
176 Unit* owner = GetOwner();
177 if (owner && ((Player*)owner)->isInCombat())
178 m_cooldownTime = time(NULL) + GetGOInfo()->trap.startDelay;
179 m_lootState = GO_READY;
180 break;
182 case GAMEOBJECT_TYPE_FISHINGNODE:
184 // fishing code (bobber ready)
185 if( time(NULL) > m_respawnTime - FISHING_BOBBER_READY_TIME )
187 // splash bobber (bobber ready now)
188 Unit* caster = GetOwner();
189 if(caster && caster->GetTypeId()==TYPEID_PLAYER)
191 SetGoState(GO_STATE_ACTIVE);
192 SetUInt32Value(GAMEOBJECT_FLAGS, GO_FLAG_NODESPAWN);
194 UpdateData udata;
195 WorldPacket packet;
196 BuildValuesUpdateBlockForPlayer(&udata,((Player*)caster));
197 udata.BuildPacket(&packet);
198 ((Player*)caster)->GetSession()->SendPacket(&packet);
200 WorldPacket data(SMSG_GAMEOBJECT_CUSTOM_ANIM,8+4);
201 data << GetGUID();
202 data << (uint32)(0);
203 ((Player*)caster)->SendMessageToSet(&data,true);
206 m_lootState = GO_READY; // can be successfully open with some chance
208 return;
210 default:
211 m_lootState = GO_READY; // for other GOis same switched without delay to GO_READY
212 break;
214 // NO BREAK for switch (m_lootState)
216 case GO_READY:
218 if (m_respawnTime > 0) // timer on
220 if (m_respawnTime <= time(NULL)) // timer expired
222 m_respawnTime = 0;
223 m_SkillupList.clear();
224 m_usetimes = 0;
226 switch (GetGoType())
228 case GAMEOBJECT_TYPE_FISHINGNODE: // can't fish now
230 Unit* caster = GetOwner();
231 if(caster && caster->GetTypeId()==TYPEID_PLAYER)
233 if(caster->m_currentSpells[CURRENT_CHANNELED_SPELL])
235 caster->m_currentSpells[CURRENT_CHANNELED_SPELL]->SendChannelUpdate(0);
236 caster->m_currentSpells[CURRENT_CHANNELED_SPELL]->finish(false);
239 WorldPacket data(SMSG_FISH_NOT_HOOKED,0);
240 ((Player*)caster)->GetSession()->SendPacket(&data);
242 // can be delete
243 m_lootState = GO_JUST_DEACTIVATED;
244 return;
246 case GAMEOBJECT_TYPE_DOOR:
247 case GAMEOBJECT_TYPE_BUTTON:
248 //we need to open doors if they are closed (add there another condition if this code breaks some usage, but it need to be here for battlegrounds)
249 if (GetGoState() != GO_STATE_READY)
250 ResetDoorOrButton();
251 //flags in AB are type_button and we need to add them here so no break!
252 default:
253 if (!m_spawnedByDefault) // despawn timer
255 // can be despawned or destroyed
256 SetLootState(GO_JUST_DEACTIVATED);
257 return;
259 // respawn timer
260 uint16 poolid = poolhandler.IsPartOfAPool(GetGUIDLow(), TYPEID_GAMEOBJECT);
261 if (poolid)
262 poolhandler.UpdatePool(poolid, GetGUIDLow(), TYPEID_GAMEOBJECT);
263 else
264 GetMap()->Add(this);
265 break;
270 // traps can have time and can not have
271 GameObjectInfo const* goInfo = GetGOInfo();
272 if(goInfo->type == GAMEOBJECT_TYPE_TRAP)
274 // traps
275 Unit* owner = GetOwner();
276 Unit* ok = NULL; // pointer to appropriate target if found any
278 if(m_cooldownTime >= time(NULL))
279 return;
281 bool IsBattleGroundTrap = false;
282 //FIXME: this is activation radius (in different casting radius that must be selected from spell data)
283 //TODO: move activated state code (cast itself) to GO_ACTIVATED, in this place only check activating and set state
284 float radius = goInfo->trap.radius;
285 if(!radius)
287 if(goInfo->trap.cooldown != 3) // cast in other case (at some triggering/linked go/etc explicit call)
288 return;
289 else
291 if(m_respawnTime > 0)
292 break;
294 radius = goInfo->trap.cooldown; // battlegrounds gameobjects has data2 == 0 && data5 == 3
295 IsBattleGroundTrap = true;
299 bool NeedDespawn = (goInfo->trap.charges != 0);
301 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
302 Cell cell(p);
303 cell.data.Part.reserved = ALL_DISTRICT;
305 // Note: this hack with search required until GO casting not implemented
306 // search unfriendly creature
307 if(owner && NeedDespawn) // hunter trap
309 MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck u_check(this, owner, radius);
310 MaNGOS::UnitSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck> checker(this,ok, u_check);
312 CellLock<GridReadGuard> cell_lock(cell, p);
314 TypeContainerVisitor<MaNGOS::UnitSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck>, GridTypeMapContainer > grid_object_checker(checker);
315 cell_lock->Visit(cell_lock, grid_object_checker, *GetMap());
317 // or unfriendly player/pet
318 if(!ok)
320 TypeContainerVisitor<MaNGOS::UnitSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck>, WorldTypeMapContainer > world_object_checker(checker);
321 cell_lock->Visit(cell_lock, world_object_checker, *GetMap());
324 else // environmental trap
326 // environmental damage spells already have around enemies targeting but this not help in case not existed GO casting support
328 // affect only players
329 Player* p_ok = NULL;
330 MaNGOS::AnyPlayerInObjectRangeCheck p_check(this, radius);
331 MaNGOS::PlayerSearcher<MaNGOS::AnyPlayerInObjectRangeCheck> checker(this,p_ok, p_check);
333 CellLock<GridReadGuard> cell_lock(cell, p);
335 TypeContainerVisitor<MaNGOS::PlayerSearcher<MaNGOS::AnyPlayerInObjectRangeCheck>, WorldTypeMapContainer > world_object_checker(checker);
336 cell_lock->Visit(cell_lock, world_object_checker, *GetMap());
337 ok = p_ok;
340 if (ok)
342 Unit *caster = owner ? owner : ok;
344 caster->CastSpell(ok, goInfo->trap.spellId, true, 0, 0, GetGUID());
345 m_cooldownTime = time(NULL) + 4; // 4 seconds
347 if(NeedDespawn)
348 SetLootState(GO_JUST_DEACTIVATED); // can be despawned or destroyed
350 if(IsBattleGroundTrap && ok->GetTypeId() == TYPEID_PLAYER)
352 //BattleGround gameobjects case
353 if(((Player*)ok)->InBattleGround())
354 if(BattleGround *bg = ((Player*)ok)->GetBattleGround())
355 bg->HandleTriggerBuff(GetGUID());
360 if (m_charges && m_usetimes >= m_charges)
361 SetLootState(GO_JUST_DEACTIVATED); // can be despawned or destroyed
363 break;
365 case GO_ACTIVATED:
367 switch(GetGoType())
369 case GAMEOBJECT_TYPE_DOOR:
370 case GAMEOBJECT_TYPE_BUTTON:
371 if (GetAutoCloseTime() && (m_cooldownTime < time(NULL)))
372 ResetDoorOrButton();
373 break;
375 break;
377 case GO_JUST_DEACTIVATED:
379 //if Gameobject should cast spell, then this, but some GOs (type = 10) should be destroyed
380 if (GetGoType() == GAMEOBJECT_TYPE_GOOBER)
382 uint32 spellId = GetGOInfo()->goober.spellId;
384 if(spellId)
386 std::set<uint32>::const_iterator it = m_unique_users.begin();
387 std::set<uint32>::const_iterator end = m_unique_users.end();
388 for (; it != end; it++)
390 Unit* owner = Unit::GetUnit(*this, uint64(*it));
391 if (owner) owner->CastSpell(owner, spellId, false, 0, 0, GetGUID());
394 m_unique_users.clear();
395 m_usetimes = 0;
397 //any return here in case battleground traps
400 if(GetOwnerGUID())
402 m_respawnTime = 0;
403 Delete();
404 return;
407 //burning flags in some battlegrounds, if you find better condition, just add it
408 if (GetGoAnimProgress() > 0)
410 SendObjectDeSpawnAnim(GetGUID());
411 //reset flags
412 SetUInt32Value(GAMEOBJECT_FLAGS, GetGOInfo()->flags);
415 loot.clear();
416 SetLootState(GO_READY);
418 if(!m_respawnDelayTime)
419 return;
421 if(!m_spawnedByDefault)
423 m_respawnTime = 0;
424 return;
427 m_respawnTime = time(NULL) + m_respawnDelayTime;
429 // if option not set then object will be saved at grid unload
430 if(sWorld.getConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY))
431 SaveRespawnTime();
433 ObjectAccessor::UpdateObjectVisibility(this);
435 break;
440 void GameObject::Refresh()
442 // not refresh despawned not casted GO (despawned casted GO destroyed in all cases anyway)
443 if(m_respawnTime > 0 && m_spawnedByDefault)
444 return;
446 if(isSpawned())
447 GetMap()->Add(this);
450 void GameObject::AddUniqueUse(Player* player)
452 AddUse();
453 m_unique_users.insert(player->GetGUIDLow());
456 void GameObject::Delete()
458 SendObjectDeSpawnAnim(GetGUID());
460 SetGoState(GO_STATE_READY);
461 SetUInt32Value(GAMEOBJECT_FLAGS, GetGOInfo()->flags);
463 uint16 poolid = poolhandler.IsPartOfAPool(GetGUIDLow(), TYPEID_GAMEOBJECT);
464 if (poolid)
465 poolhandler.UpdatePool(poolid, GetGUIDLow(), TYPEID_GAMEOBJECT);
466 else
467 AddObjectToRemoveList();
470 void GameObject::getFishLoot(Loot *fishloot, Player* loot_owner)
472 fishloot->clear();
474 uint32 zone, subzone;
475 GetZoneAndAreaId(zone,subzone);
477 // if subzone loot exist use it
478 if(LootTemplates_Fishing.HaveLootFor(subzone))
479 fishloot->FillLoot(subzone, LootTemplates_Fishing, loot_owner,true);
480 // else use zone loot
481 else
482 fishloot->FillLoot(zone, LootTemplates_Fishing, loot_owner,true);
485 void GameObject::SaveToDB()
487 // this should only be used when the gameobject has already been loaded
488 // preferably after adding to map, because mapid may not be valid otherwise
489 GameObjectData const *data = objmgr.GetGOData(m_DBTableGuid);
490 if(!data)
492 sLog.outError("GameObject::SaveToDB failed, cannot get gameobject data!");
493 return;
496 SaveToDB(GetMapId(), data->spawnMask, data->phaseMask);
499 void GameObject::SaveToDB(uint32 mapid, uint8 spawnMask, uint32 phaseMask)
501 const GameObjectInfo *goI = GetGOInfo();
503 if (!goI)
504 return;
506 if (!m_DBTableGuid)
507 m_DBTableGuid = GetGUIDLow();
508 // update in loaded data (changing data only in this place)
509 GameObjectData& data = objmgr.NewGOData(m_DBTableGuid);
511 // data->guid = guid don't must be update at save
512 data.id = GetEntry();
513 data.mapid = mapid;
514 data.phaseMask = phaseMask;
515 data.posX = GetFloatValue(GAMEOBJECT_POS_X);
516 data.posY = GetFloatValue(GAMEOBJECT_POS_Y);
517 data.posZ = GetFloatValue(GAMEOBJECT_POS_Z);
518 data.orientation = GetFloatValue(GAMEOBJECT_FACING);
519 data.rotation0 = GetFloatValue(GAMEOBJECT_PARENTROTATION+0);
520 data.rotation1 = GetFloatValue(GAMEOBJECT_PARENTROTATION+1);
521 data.rotation2 = GetFloatValue(GAMEOBJECT_PARENTROTATION+2);
522 data.rotation3 = GetFloatValue(GAMEOBJECT_PARENTROTATION+3);
523 data.spawntimesecs = m_spawnedByDefault ? m_respawnDelayTime : -(int32)m_respawnDelayTime;
524 data.animprogress = GetGoAnimProgress();
525 data.go_state = GetGoState();
526 data.spawnMask = spawnMask;
528 // updated in DB
529 std::ostringstream ss;
530 ss << "INSERT INTO gameobject VALUES ( "
531 << m_DBTableGuid << ", "
532 << GetEntry() << ", "
533 << mapid << ", "
534 << uint32(spawnMask) << "," // cast to prevent save as symbol
535 << uint16(GetPhaseMask()) << "," // prevent out of range error
536 << GetFloatValue(GAMEOBJECT_POS_X) << ", "
537 << GetFloatValue(GAMEOBJECT_POS_Y) << ", "
538 << GetFloatValue(GAMEOBJECT_POS_Z) << ", "
539 << GetFloatValue(GAMEOBJECT_FACING) << ", "
540 << GetFloatValue(GAMEOBJECT_PARENTROTATION) << ", "
541 << GetFloatValue(GAMEOBJECT_PARENTROTATION+1) << ", "
542 << GetFloatValue(GAMEOBJECT_PARENTROTATION+2) << ", "
543 << GetFloatValue(GAMEOBJECT_PARENTROTATION+3) << ", "
544 << m_respawnDelayTime << ", "
545 << uint32(GetGoAnimProgress()) << ", "
546 << uint32(GetGoState()) << ")";
548 WorldDatabase.BeginTransaction();
549 WorldDatabase.PExecuteLog("DELETE FROM gameobject WHERE guid = '%u'", m_DBTableGuid);
550 WorldDatabase.PExecuteLog( ss.str( ).c_str( ) );
551 WorldDatabase.CommitTransaction();
554 bool GameObject::LoadFromDB(uint32 guid, Map *map)
556 GameObjectData const* data = objmgr.GetGOData(guid);
558 if( !data )
560 sLog.outErrorDb("Gameobject (GUID: %u) not found in table `gameobject`, can't load. ",guid);
561 return false;
564 uint32 entry = data->id;
565 //uint32 map_id = data->mapid; // already used before call
566 uint32 phaseMask = data->phaseMask;
567 float x = data->posX;
568 float y = data->posY;
569 float z = data->posZ;
570 float ang = data->orientation;
572 float rotation0 = data->rotation0;
573 float rotation1 = data->rotation1;
574 float rotation2 = data->rotation2;
575 float rotation3 = data->rotation3;
577 uint32 animprogress = data->animprogress;
578 GOState go_state = data->go_state;
580 m_DBTableGuid = guid;
581 if (map->GetInstanceId() != 0) guid = objmgr.GenerateLowGuid(HIGHGUID_GAMEOBJECT);
583 if (!Create(guid,entry, map, phaseMask, x, y, z, ang, rotation0, rotation1, rotation2, rotation3, animprogress, go_state) )
584 return false;
586 if(!GetDespawnPossibility())
588 SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_NODESPAWN);
589 m_spawnedByDefault = true;
590 m_respawnDelayTime = 0;
591 m_respawnTime = 0;
593 else
595 if(data->spawntimesecs >= 0)
597 m_spawnedByDefault = true;
598 m_respawnDelayTime = data->spawntimesecs;
599 m_respawnTime = objmgr.GetGORespawnTime(m_DBTableGuid, map->GetInstanceId());
601 // ready to respawn
602 if(m_respawnTime && m_respawnTime <= time(NULL))
604 m_respawnTime = 0;
605 objmgr.SaveGORespawnTime(m_DBTableGuid,GetInstanceId(),0);
608 else
610 m_spawnedByDefault = false;
611 m_respawnDelayTime = -data->spawntimesecs;
612 m_respawnTime = 0;
616 return true;
619 void GameObject::DeleteFromDB()
621 objmgr.SaveGORespawnTime(m_DBTableGuid,GetInstanceId(),0);
622 objmgr.DeleteGOData(m_DBTableGuid);
623 WorldDatabase.PExecuteLog("DELETE FROM gameobject WHERE guid = '%u'", m_DBTableGuid);
624 WorldDatabase.PExecuteLog("DELETE FROM game_event_gameobject WHERE guid = '%u'", m_DBTableGuid);
627 GameObjectInfo const *GameObject::GetGOInfo() const
629 return m_goInfo;
632 uint32 GameObject::GetLootId(GameObjectInfo const* ginfo)
634 if (!ginfo)
635 return 0;
637 switch(ginfo->type)
639 case GAMEOBJECT_TYPE_CHEST:
640 return ginfo->chest.lootId;
641 case GAMEOBJECT_TYPE_FISHINGHOLE:
642 return ginfo->fishinghole.lootId;
643 case GAMEOBJECT_TYPE_FISHINGNODE:
644 return ginfo->fishnode.lootId;
645 default:
646 return 0;
650 /*********************************************************/
651 /*** QUEST SYSTEM ***/
652 /*********************************************************/
653 bool GameObject::hasQuest(uint32 quest_id) const
655 QuestRelations const& qr = objmgr.mGOQuestRelations;
656 for(QuestRelations::const_iterator itr = qr.lower_bound(GetEntry()); itr != qr.upper_bound(GetEntry()); ++itr)
658 if(itr->second==quest_id)
659 return true;
661 return false;
664 bool GameObject::hasInvolvedQuest(uint32 quest_id) const
666 QuestRelations const& qr = objmgr.mGOQuestInvolvedRelations;
667 for(QuestRelations::const_iterator itr = qr.lower_bound(GetEntry()); itr != qr.upper_bound(GetEntry()); ++itr)
669 if(itr->second==quest_id)
670 return true;
672 return false;
675 bool GameObject::IsTransport() const
677 // If something is marked as a transport, don't transmit an out of range packet for it.
678 GameObjectInfo const * gInfo = GetGOInfo();
679 if(!gInfo) return false;
680 return gInfo->type == GAMEOBJECT_TYPE_TRANSPORT || gInfo->type == GAMEOBJECT_TYPE_MO_TRANSPORT;
683 Unit* GameObject::GetOwner() const
685 return ObjectAccessor::GetUnit(*this, GetOwnerGUID());
688 void GameObject::SaveRespawnTime()
690 if(m_respawnTime > time(NULL) && m_spawnedByDefault)
691 objmgr.SaveGORespawnTime(m_DBTableGuid,GetInstanceId(),m_respawnTime);
694 bool GameObject::isVisibleForInState(Player const* u, bool inVisibleList) const
696 // Not in world
697 if(!IsInWorld() || !u->IsInWorld())
698 return false;
700 // Transport always visible at this step implementation
701 if(IsTransport() && IsInMap(u))
702 return true;
704 // quick check visibility false cases for non-GM-mode
705 if(!u->isGameMaster())
707 // despawned and then not visible for non-GM in GM-mode
708 if(!isSpawned())
709 return false;
711 // special invisibility cases
712 /* TODO: implement trap stealth, take look at spell 2836
713 if(GetGOInfo()->type == GAMEOBJECT_TYPE_TRAP && GetGOInfo()->trap.stealthed && u->IsHostileTo(GetOwner()))
715 if(check stuff here)
716 return false;
720 // check distance
721 return IsWithinDistInMap(u,World::GetMaxVisibleDistanceForObject() +
722 (inVisibleList ? World::GetVisibleObjectGreyDistance() : 0.0f), false);
725 void GameObject::Respawn()
727 if(m_spawnedByDefault && m_respawnTime > 0)
729 m_respawnTime = time(NULL);
730 objmgr.SaveGORespawnTime(m_DBTableGuid,GetInstanceId(),0);
734 bool GameObject::ActivateToQuest( Player *pTarget)const
736 if(!objmgr.IsGameObjectForQuests(GetEntry()))
737 return false;
739 switch(GetGoType())
741 // scan GO chest with loot including quest items
742 case GAMEOBJECT_TYPE_CHEST:
744 if(LootTemplates_Gameobject.HaveQuestLootForPlayer(GetLootId(), pTarget))
745 return true;
746 break;
748 case GAMEOBJECT_TYPE_GOOBER:
750 if(pTarget->GetQuestStatus(GetGOInfo()->goober.questId) == QUEST_STATUS_INCOMPLETE)
751 return true;
752 break;
754 default:
755 break;
758 return false;
761 void GameObject::TriggeringLinkedGameObject( uint32 trapEntry, Unit* target)
763 GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(trapEntry);
764 if(!trapInfo || trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
765 return;
767 SpellEntry const* trapSpell = sSpellStore.LookupEntry(trapInfo->trap.spellId);
768 if(!trapSpell) // checked at load already
769 return;
771 float range = GetSpellMaxRange(sSpellRangeStore.LookupEntry(trapSpell->rangeIndex));
773 // search nearest linked GO
774 GameObject* trapGO = NULL;
776 // using original GO distance
777 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
778 Cell cell(p);
779 cell.data.Part.reserved = ALL_DISTRICT;
781 MaNGOS::NearestGameObjectEntryInObjectRangeCheck go_check(*target,trapEntry,range);
782 MaNGOS::GameObjectLastSearcher<MaNGOS::NearestGameObjectEntryInObjectRangeCheck> checker(this, trapGO,go_check);
784 TypeContainerVisitor<MaNGOS::GameObjectLastSearcher<MaNGOS::NearestGameObjectEntryInObjectRangeCheck>, GridTypeMapContainer > object_checker(checker);
785 CellLock<GridReadGuard> cell_lock(cell, p);
786 cell_lock->Visit(cell_lock, object_checker, *GetMap());
789 // found correct GO
790 // FIXME: when GO casting will be implemented trap must cast spell to target
791 if(trapGO)
792 target->CastSpell(target,trapSpell,true, 0, 0, GetGUID());
795 GameObject* GameObject::LookupFishingHoleAround(float range)
797 GameObject* ok = NULL;
799 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
800 Cell cell(p);
801 cell.data.Part.reserved = ALL_DISTRICT;
802 MaNGOS::NearestGameObjectFishingHole u_check(*this, range);
803 MaNGOS::GameObjectSearcher<MaNGOS::NearestGameObjectFishingHole> checker(this, ok, u_check);
805 CellLock<GridReadGuard> cell_lock(cell, p);
807 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::NearestGameObjectFishingHole>, GridTypeMapContainer > grid_object_checker(checker);
808 cell_lock->Visit(cell_lock, grid_object_checker, *GetMap());
810 return ok;
813 void GameObject::ResetDoorOrButton()
815 if (m_lootState == GO_READY || m_lootState == GO_JUST_DEACTIVATED)
816 return;
818 SwitchDoorOrButton(false);
819 SetLootState(GO_JUST_DEACTIVATED);
820 m_cooldownTime = 0;
823 void GameObject::UseDoorOrButton(uint32 time_to_restore, bool alternative /* = false */)
825 if(m_lootState != GO_READY)
826 return;
828 if(!time_to_restore)
829 time_to_restore = GetAutoCloseTime();
831 SwitchDoorOrButton(true,alternative);
832 SetLootState(GO_ACTIVATED);
834 m_cooldownTime = time(NULL) + time_to_restore;
837 void GameObject::SwitchDoorOrButton(bool activate, bool alternative /* = false */)
839 if(activate)
840 SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_IN_USE);
841 else
842 RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_IN_USE);
844 if(GetGoState() == GO_STATE_READY) //if closed -> open
845 SetGoState(alternative ? GO_STATE_ACTIVE_ALTERNATIVE : GO_STATE_ACTIVE);
846 else //if open -> close
847 SetGoState(GO_STATE_READY);
850 void GameObject::Use(Unit* user)
852 // by default spell caster is user
853 Unit* spellCaster = user;
854 uint32 spellId = 0;
855 bool triggered = false;
857 switch(GetGoType())
859 case GAMEOBJECT_TYPE_DOOR: //0
860 case GAMEOBJECT_TYPE_BUTTON: //1
861 //doors/buttons never really despawn, only reset to default state/flags
862 UseDoorOrButton();
864 // activate script
865 sWorld.ScriptsStart(sGameObjectScripts, GetDBTableGUIDLow(), spellCaster, this);
866 return;
868 case GAMEOBJECT_TYPE_QUESTGIVER: //2
870 if(user->GetTypeId()!=TYPEID_PLAYER)
871 return;
873 Player* player = (Player*)user;
875 player->PrepareQuestMenu( GetGUID() );
876 player->SendPreparedQuest( GetGUID() );
877 return;
879 //Sitting: Wooden bench, chairs enzz
880 case GAMEOBJECT_TYPE_CHAIR: //7
882 GameObjectInfo const* info = GetGOInfo();
883 if(!info)
884 return;
886 if(user->GetTypeId()!=TYPEID_PLAYER)
887 return;
889 Player* player = (Player*)user;
891 // a chair may have n slots. we have to calculate their positions and teleport the player to the nearest one
893 // check if the db is sane
894 if(info->chair.slots > 0)
896 float lowestDist = DEFAULT_VISIBILITY_DISTANCE;
898 float x_lowest = GetPositionX();
899 float y_lowest = GetPositionY();
901 // the object orientation + 1/2 pi
902 // every slot will be on that straight line
903 float orthogonalOrientation = GetOrientation()+M_PI*0.5f;
904 // find nearest slot
905 for(uint32 i=0; i<info->chair.slots; ++i)
907 // the distance between this slot and the center of the go - imagine a 1D space
908 float relativeDistance = (info->size*i)-(info->size*(info->chair.slots-1)/2.0f);
910 float x_i = GetPositionX() + relativeDistance * cos(orthogonalOrientation);
911 float y_i = GetPositionY() + relativeDistance * sin(orthogonalOrientation);
913 // calculate the distance between the player and this slot
914 float thisDistance = player->GetDistance2d(x_i, y_i);
916 /* debug code. It will spawn a npc on each slot to visualize them.
917 Creature* helper = player->SummonCreature(14496, x_i, y_i, GetPositionZ(), GetOrientation(), TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 10000);
918 std::ostringstream output;
919 output << i << ": thisDist: " << thisDistance;
920 helper->MonsterSay(output.str().c_str(), LANG_UNIVERSAL, 0);
923 if(thisDistance <= lowestDist)
925 lowestDist = thisDistance;
926 x_lowest = x_i;
927 y_lowest = y_i;
930 player->TeleportTo(GetMapId(), x_lowest, y_lowest, GetPositionZ(), GetOrientation(),TELE_TO_NOT_LEAVE_TRANSPORT | TELE_TO_NOT_LEAVE_COMBAT | TELE_TO_NOT_UNSUMMON_PET);
932 else
934 // fallback, will always work
935 player->TeleportTo(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation(),TELE_TO_NOT_LEAVE_TRANSPORT | TELE_TO_NOT_LEAVE_COMBAT | TELE_TO_NOT_UNSUMMON_PET);
937 player->SetStandState(UNIT_STAND_STATE_SIT_LOW_CHAIR+info->chair.height);
938 return;
940 //big gun, its a spell/aura
941 case GAMEOBJECT_TYPE_GOOBER: //10
943 GameObjectInfo const* info = GetGOInfo();
945 if(user->GetTypeId()==TYPEID_PLAYER)
947 Player* player = (Player*)user;
949 // show page
950 if(info->goober.pageId)
952 WorldPacket data(SMSG_GAMEOBJECT_PAGETEXT, 8);
953 data << GetGUID();
954 player->GetSession()->SendPacket(&data);
957 // possible quest objective for active quests
958 player->CastedCreatureOrGO(info->id, GetGUID(), 0);
961 // cast this spell later if provided
962 spellId = info->goober.spellId;
964 break;
966 case GAMEOBJECT_TYPE_CAMERA: //13
968 GameObjectInfo const* info = GetGOInfo();
969 if(!info)
970 return;
972 if(user->GetTypeId()!=TYPEID_PLAYER)
973 return;
975 Player* player = (Player*)user;
977 if (info->camera.cinematicId)
978 player->SendCinematicStart(info->camera.cinematicId);
980 return;
982 //fishing bobber
983 case GAMEOBJECT_TYPE_FISHINGNODE: //17
985 if(user->GetTypeId()!=TYPEID_PLAYER)
986 return;
988 Player* player = (Player*)user;
990 if(player->GetGUID() != GetOwnerGUID())
991 return;
993 switch(getLootState())
995 case GO_READY: // ready for loot
997 // 1) skill must be >= base_zone_skill
998 // 2) if skill == base_zone_skill => 5% chance
999 // 3) chance is linear dependence from (base_zone_skill-skill)
1001 uint32 zone, subzone;
1002 GetZoneAndAreaId(zone,subzone);
1004 int32 zone_skill = objmgr.GetFishingBaseSkillLevel( subzone );
1005 if(!zone_skill)
1006 zone_skill = objmgr.GetFishingBaseSkillLevel( zone );
1008 //provide error, no fishable zone or area should be 0
1009 if(!zone_skill)
1010 sLog.outErrorDb("Fishable areaId %u are not properly defined in `skill_fishing_base_level`.",subzone);
1012 int32 skill = player->GetSkillValue(SKILL_FISHING);
1013 int32 chance = skill - zone_skill + 5;
1014 int32 roll = irand(1,100);
1016 DEBUG_LOG("Fishing check (skill: %i zone min skill: %i chance %i roll: %i",skill,zone_skill,chance,roll);
1018 if(skill >= zone_skill && chance >= roll)
1020 // prevent removing GO at spell cancel
1021 player->RemoveGameObject(this,false);
1022 SetOwnerGUID(player->GetGUID());
1024 //fish catched
1025 player->UpdateFishingSkill();
1027 GameObject* ok = LookupFishingHoleAround(DEFAULT_VISIBILITY_DISTANCE);
1028 if (ok)
1030 player->SendLoot(ok->GetGUID(),LOOT_FISHINGHOLE);
1031 player->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FISH_IN_GAMEOBJECT, ok->GetGOInfo()->id);
1032 SetLootState(GO_JUST_DEACTIVATED);
1034 else
1035 player->SendLoot(GetGUID(),LOOT_FISHING);
1037 else
1039 // fish escaped, can be deleted now
1040 SetLootState(GO_JUST_DEACTIVATED);
1042 WorldPacket data(SMSG_FISH_ESCAPED, 0);
1043 player->GetSession()->SendPacket(&data);
1045 break;
1047 case GO_JUST_DEACTIVATED: // nothing to do, will be deleted at next update
1048 break;
1049 default:
1051 SetLootState(GO_JUST_DEACTIVATED);
1053 WorldPacket data(SMSG_FISH_NOT_HOOKED, 0);
1054 player->GetSession()->SendPacket(&data);
1055 break;
1059 if(player->m_currentSpells[CURRENT_CHANNELED_SPELL])
1061 player->m_currentSpells[CURRENT_CHANNELED_SPELL]->SendChannelUpdate(0);
1062 player->m_currentSpells[CURRENT_CHANNELED_SPELL]->finish();
1064 return;
1067 case GAMEOBJECT_TYPE_SUMMONING_RITUAL: //18
1069 if(user->GetTypeId()!=TYPEID_PLAYER)
1070 return;
1072 Player* player = (Player*)user;
1074 Unit* caster = GetOwner();
1076 GameObjectInfo const* info = GetGOInfo();
1078 if( !caster || caster->GetTypeId()!=TYPEID_PLAYER )
1079 return;
1081 // accept only use by player from same group for caster except caster itself
1082 if(((Player*)caster)==player || !((Player*)caster)->IsInSameRaidWith(player))
1083 return;
1085 AddUniqueUse(player);
1087 // full amount unique participants including original summoner
1088 if(GetUniqueUseCount() < info->summoningRitual.reqParticipants)
1089 return;
1091 // in case summoning ritual caster is GO creator
1092 spellCaster = caster;
1094 if(!caster->m_currentSpells[CURRENT_CHANNELED_SPELL])
1095 return;
1097 spellId = info->summoningRitual.spellId;
1098 if(spellId==62330) // GO store not existed spell, replace by expected
1100 // spell have reagent and mana cost but it not expected use its
1101 // it triggered spell in fact casted at currently channeled GO
1102 spellId = 61993;
1103 triggered = true;
1106 // finish spell
1107 caster->m_currentSpells[CURRENT_CHANNELED_SPELL]->SendChannelUpdate(0);
1108 caster->m_currentSpells[CURRENT_CHANNELED_SPELL]->finish();
1110 // can be deleted now
1111 SetLootState(GO_JUST_DEACTIVATED);
1113 // go to end function to spell casting
1114 break;
1116 case GAMEOBJECT_TYPE_SPELLCASTER: //22
1118 SetUInt32Value(GAMEOBJECT_FLAGS,2);
1120 GameObjectInfo const* info = GetGOInfo();
1121 if(!info)
1122 return;
1124 if(info->spellcaster.partyOnly)
1126 Unit* caster = GetOwner();
1127 if( !caster || caster->GetTypeId()!=TYPEID_PLAYER )
1128 return;
1130 if(user->GetTypeId()!=TYPEID_PLAYER || !((Player*)user)->IsInSameRaidWith((Player*)caster))
1131 return;
1134 spellId = info->spellcaster.spellId;
1136 AddUse();
1137 break;
1139 case GAMEOBJECT_TYPE_MEETINGSTONE: //23
1141 GameObjectInfo const* info = GetGOInfo();
1143 if(user->GetTypeId()!=TYPEID_PLAYER)
1144 return;
1146 Player* player = (Player*)user;
1148 Player* targetPlayer = ObjectAccessor::FindPlayer(player->GetSelection());
1150 // accept only use by player from same group for caster except caster itself
1151 if(!targetPlayer || targetPlayer == player || !targetPlayer->IsInSameGroupWith(player))
1152 return;
1154 //required lvl checks!
1155 uint8 level = player->getLevel();
1156 if (level < info->meetingstone.minLevel || level > info->meetingstone.maxLevel)
1157 return;
1158 level = targetPlayer->getLevel();
1159 if (level < info->meetingstone.minLevel || level > info->meetingstone.maxLevel)
1160 return;
1162 if(info->id==194097)
1163 spellId = 61994; // Ritual of Summoning
1164 else
1165 spellId = 59782; // Summoning Stone Effect
1167 break;
1170 case GAMEOBJECT_TYPE_FLAGSTAND: // 24
1172 if(user->GetTypeId()!=TYPEID_PLAYER)
1173 return;
1175 Player* player = (Player*)user;
1177 if( player->CanUseBattleGroundObject() )
1179 // in battleground check
1180 BattleGround *bg = player->GetBattleGround();
1181 if(!bg)
1182 return;
1183 // BG flag click
1184 // AB:
1185 // 15001
1186 // 15002
1187 // 15003
1188 // 15004
1189 // 15005
1190 bg->EventPlayerClickedOnFlag(player, this);
1191 return; //we don;t need to delete flag ... it is despawned!
1193 break;
1195 case GAMEOBJECT_TYPE_FLAGDROP: // 26
1197 if(user->GetTypeId()!=TYPEID_PLAYER)
1198 return;
1200 Player* player = (Player*)user;
1202 if( player->CanUseBattleGroundObject() )
1204 // in battleground check
1205 BattleGround *bg = player->GetBattleGround();
1206 if(!bg)
1207 return;
1208 // BG flag dropped
1209 // WS:
1210 // 179785 - Silverwing Flag
1211 // 179786 - Warsong Flag
1212 // EotS:
1213 // 184142 - Netherstorm Flag
1214 GameObjectInfo const* info = GetGOInfo();
1215 if(info)
1217 switch(info->id)
1219 case 179785: // Silverwing Flag
1220 // check if it's correct bg
1221 if(bg->GetTypeID() == BATTLEGROUND_WS)
1222 bg->EventPlayerClickedOnFlag(player, this);
1223 break;
1224 case 179786: // Warsong Flag
1225 if(bg->GetTypeID() == BATTLEGROUND_WS)
1226 bg->EventPlayerClickedOnFlag(player, this);
1227 break;
1228 case 184142: // Netherstorm Flag
1229 if(bg->GetTypeID() == BATTLEGROUND_EY)
1230 bg->EventPlayerClickedOnFlag(player, this);
1231 break;
1234 //this cause to call return, all flags must be deleted here!!
1235 spellId = 0;
1236 Delete();
1238 break;
1240 case GAMEOBJECT_TYPE_BARBER_CHAIR: //32
1242 GameObjectInfo const* info = GetGOInfo();
1243 if(!info)
1244 return;
1246 if(user->GetTypeId()!=TYPEID_PLAYER)
1247 return;
1249 Player* player = (Player*)user;
1251 // fallback, will always work
1252 player->TeleportTo(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation(),TELE_TO_NOT_LEAVE_TRANSPORT | TELE_TO_NOT_LEAVE_COMBAT | TELE_TO_NOT_UNSUMMON_PET);
1254 WorldPacket data(SMSG_ENABLE_BARBER_SHOP, 0);
1255 player->GetSession()->SendPacket(&data);
1257 player->SetStandState(UNIT_STAND_STATE_SIT_LOW_CHAIR+info->barberChair.chairheight);
1258 return;
1260 default:
1261 sLog.outDebug("Unknown Object Type %u", GetGoType());
1262 break;
1265 if(!spellId)
1266 return;
1268 SpellEntry const *spellInfo = sSpellStore.LookupEntry( spellId );
1269 if(!spellInfo)
1271 sLog.outError("WORLD: unknown spell id %u at use action for gameobject (Entry: %u GoType: %u )", spellId,GetEntry(),GetGoType());
1272 return;
1275 Spell *spell = new Spell(spellCaster, spellInfo, triggered);
1277 // spell target is user of GO
1278 SpellCastTargets targets;
1279 targets.setUnitTarget( user );
1281 spell->prepare(&targets);
1284 // overwrite WorldObject function for proper name localization
1285 const char* GameObject::GetNameForLocaleIdx(int32 loc_idx) const
1287 if (loc_idx >= 0)
1289 GameObjectLocale const *cl = objmgr.GetGameObjectLocale(GetEntry());
1290 if (cl)
1292 if (cl->Name.size() > loc_idx && !cl->Name[loc_idx].empty())
1293 return cl->Name[loc_idx].c_str();
1297 return GetName();
1300 void GameObject::UpdateRotationFields(float rotation2 /*=0.0f*/, float rotation3 /*=0.0f*/)
1302 static double const atan_pow = atan(pow(2.0f, -20.0f));
1304 SetFloatValue(GAMEOBJECT_FACING, GetOrientation());
1306 double f_rot1 = sin(GetOrientation() / 2.0f);
1307 double f_rot2 = cos(GetOrientation() / 2.0f);
1309 int64 i_rot1 = int64(f_rot1 / atan_pow *(f_rot2 >= 0 ? 1.0f : -1.0f));
1310 int64 rotation = (i_rot1 << 43 >> 43) & 0x00000000001FFFFF;
1311 SetUInt64Value(GAMEOBJECT_ROTATION, rotation);
1313 if(rotation2==0.0f && rotation3==0.0f)
1315 rotation2 = f_rot1;
1316 rotation3 = f_rot2;
1319 SetFloatValue(GAMEOBJECT_PARENTROTATION+2, rotation2);
1320 SetFloatValue(GAMEOBJECT_PARENTROTATION+3, rotation3);