Fixed spell.dbc structure
[getmangos.git] / src / game / GameObject.cpp
blob2544640c5e53c93875eacbf6e8b42cd97601112b
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 "Common.h"
20 #include "QuestDef.h"
21 #include "GameObject.h"
22 #include "ObjectMgr.h"
23 #include "SpellMgr.h"
24 #include "Spell.h"
25 #include "UpdateMask.h"
26 #include "Opcodes.h"
27 #include "WorldPacket.h"
28 #include "WorldSession.h"
29 #include "World.h"
30 #include "Database/DatabaseEnv.h"
31 #include "MapManager.h"
32 #include "LootMgr.h"
33 #include "GridNotifiers.h"
34 #include "GridNotifiersImpl.h"
35 #include "CellImpl.h"
36 #include "InstanceData.h"
37 #include "BattleGround.h"
38 #include "Util.h"
40 GameObject::GameObject() : WorldObject()
42 m_objectType |= TYPEMASK_GAMEOBJECT;
43 m_objectTypeId = TYPEID_GAMEOBJECT;
44 // 2.3.2 - 0x58
45 m_updateFlag = (UPDATEFLAG_LOWGUID | UPDATEFLAG_HIGHGUID | UPDATEFLAG_HASPOSITION);
47 m_valuesCount = GAMEOBJECT_END;
48 m_respawnTime = 0;
49 m_respawnDelayTime = 25;
50 m_lootState = GO_NOT_READY;
51 m_spawnedByDefault = true;
52 m_usetimes = 0;
53 m_spellId = 0;
54 m_charges = 5;
55 m_cooldownTime = 0;
56 m_goInfo = NULL;
58 m_DBTableGuid = 0;
61 GameObject::~GameObject()
63 if(m_uint32Values) // field array can be not exist if GameOBject not loaded
65 // crash possable at access to deleted GO in Unit::m_gameobj
66 uint64 owner_guid = GetOwnerGUID();
67 if(owner_guid)
69 Unit* owner = ObjectAccessor::GetUnit(*this,owner_guid);
70 if(owner)
71 owner->RemoveGameObject(this,false);
72 else if(!IS_PLAYER_GUID(owner_guid))
73 sLog.outError("Delete GameObject (GUID: %u Entry: %u ) that have references in not found creature %u GO list. Crash possable later.",GetGUIDLow(),GetGOInfo()->id,GUID_LOPART(owner_guid));
78 void GameObject::AddToWorld()
80 ///- Register the gameobject for guid lookup
81 if(!IsInWorld()) ObjectAccessor::Instance().AddObject(this);
82 Object::AddToWorld();
85 void GameObject::RemoveFromWorld()
87 ///- Remove the gameobject from the accessor
88 if(IsInWorld()) ObjectAccessor::Instance().RemoveObject(this);
89 Object::RemoveFromWorld();
92 bool GameObject::Create(uint32 guidlow, uint32 name_id, Map *map, float x, float y, float z, float ang, float rotation0, float rotation1, float rotation2, float rotation3, uint32 animprogress, uint32 go_state)
94 Relocate(x,y,z,ang);
95 SetMapId(map->GetId());
96 SetInstanceId(map->GetInstanceId());
98 if(!IsPositionValid())
100 sLog.outError("ERROR: 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);
124 SetFloatValue(GAMEOBJECT_FACING, ang); //this is not facing angle
126 int64 rotation = 0;
128 float f_rot1 = sin(ang / 2.0f);
129 int64 i_rot1 = f_rot1 / atan(pow(2.0f, -20.0f));
130 rotation |= (i_rot1 << 43 >> 43) & 0x00000000001FFFFF;
132 //float f_rot2 = sin(0.0f / 2.0f);
133 //int64 i_rot2 = f_rot2 / atan(pow(2.0f, -20.0f));
134 //rotation |= (((i_rot2 << 22) >> 32) >> 11) & 0x000003FFFFE00000;
136 //float f_rot3 = sin(0.0f / 2.0f);
137 //int64 i_rot3 = f_rot3 / atan(pow(2.0f, -21.0f));
138 //rotation |= (i_rot3 >> 42) & 0x7FFFFC0000000000;
140 SetUInt64Value(GAMEOBJECT_ROTATION, rotation);
142 SetFloatValue(GAMEOBJECT_PARENTROTATION+0, rotation0);
143 SetFloatValue(GAMEOBJECT_PARENTROTATION+1, rotation1);
144 SetFloatValue(GAMEOBJECT_PARENTROTATION+2, rotation2);
145 SetFloatValue(GAMEOBJECT_PARENTROTATION+3, rotation3);
147 SetFloatValue(OBJECT_FIELD_SCALE_X, goinfo->size);
149 SetUInt32Value(GAMEOBJECT_FACTION, goinfo->faction);
150 SetUInt32Value(GAMEOBJECT_FLAGS, goinfo->flags);
152 SetEntry(goinfo->id);
154 SetUInt32Value(GAMEOBJECT_DISPLAYID, goinfo->displayId);
156 SetGoState(go_state);
157 SetGoType(GameobjectTypes(goinfo->type));
159 SetGoAnimProgress(animprogress);
161 // Spell charges for GAMEOBJECT_TYPE_SPELLCASTER (22)
162 if (goinfo->type == GAMEOBJECT_TYPE_SPELLCASTER)
163 m_charges = goinfo->spellcaster.charges;
165 //Notify the map's instance data.
166 //Only works if you create the object in it, not if it is moves to that map.
167 //Normally non-players do not teleport to other maps.
168 if(map->IsDungeon() && ((InstanceMap*)map)->GetInstanceData())
170 ((InstanceMap*)map)->GetInstanceData()->OnObjectCreate(this);
173 return true;
176 void GameObject::Update(uint32 /*p_time*/)
178 if (IS_MO_TRANSPORT(GetGUID()))
180 //((Transport*)this)->Update(p_time);
181 return;
184 switch (m_lootState)
186 case GO_NOT_READY:
188 switch(GetGoType())
190 case GAMEOBJECT_TYPE_TRAP:
192 // Arming Time for GAMEOBJECT_TYPE_TRAP (6)
193 Unit* owner = GetOwner();
194 if (owner && ((Player*)owner)->isInCombat())
195 m_cooldownTime = time(NULL) + GetGOInfo()->trap.startDelay;
196 m_lootState = GO_READY;
197 break;
199 case GAMEOBJECT_TYPE_FISHINGNODE:
201 // fishing code (bobber ready)
202 if( time(NULL) > m_respawnTime - FISHING_BOBBER_READY_TIME )
204 // splash bobber (bobber ready now)
205 Unit* caster = GetOwner();
206 if(caster && caster->GetTypeId()==TYPEID_PLAYER)
208 SetGoState(0);
209 SetUInt32Value(GAMEOBJECT_FLAGS, GO_FLAG_NODESPAWN);
211 UpdateData udata;
212 WorldPacket packet;
213 BuildValuesUpdateBlockForPlayer(&udata,((Player*)caster));
214 udata.BuildPacket(&packet);
215 ((Player*)caster)->GetSession()->SendPacket(&packet);
217 WorldPacket data(SMSG_GAMEOBJECT_CUSTOM_ANIM,8+4);
218 data << GetGUID();
219 data << (uint32)(0);
220 ((Player*)caster)->SendMessageToSet(&data,true);
223 m_lootState = GO_READY; // can be succesfully open with some chance
225 return;
227 default:
228 m_lootState = GO_READY; // for other GOis same switched without delay to GO_READY
229 break;
231 // NO BREAK for switch (m_lootState)
233 case GO_READY:
235 if (m_respawnTime > 0) // timer on
237 if (m_respawnTime <= time(NULL)) // timer expired
239 m_respawnTime = 0;
240 m_SkillupList.clear();
241 m_usetimes = 0;
243 switch (GetGoType())
245 case GAMEOBJECT_TYPE_FISHINGNODE: // can't fish now
247 Unit* caster = GetOwner();
248 if(caster && caster->GetTypeId()==TYPEID_PLAYER)
250 if(caster->m_currentSpells[CURRENT_CHANNELED_SPELL])
252 caster->m_currentSpells[CURRENT_CHANNELED_SPELL]->SendChannelUpdate(0);
253 caster->m_currentSpells[CURRENT_CHANNELED_SPELL]->finish(false);
256 WorldPacket data(SMSG_FISH_NOT_HOOKED,0);
257 ((Player*)caster)->GetSession()->SendPacket(&data);
259 // can be delete
260 m_lootState = GO_JUST_DEACTIVATED;
261 return;
263 case GAMEOBJECT_TYPE_DOOR:
264 case GAMEOBJECT_TYPE_BUTTON:
265 //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)
266 if( !GetGoState() )
267 SwitchDoorOrButton(false);
268 //flags in AB are type_button and we need to add them here so no break!
269 default:
270 if(!m_spawnedByDefault) // despawn timer
272 // can be despawned or destroyed
273 SetLootState(GO_JUST_DEACTIVATED);
274 return;
276 // respawn timer
277 MapManager::Instance().GetMap(GetMapId(), this)->Add(this);
278 break;
283 // traps can have time and can not have
284 GameObjectInfo const* goInfo = GetGOInfo();
285 if(goInfo->type == GAMEOBJECT_TYPE_TRAP)
287 // traps
288 Unit* owner = GetOwner();
289 Unit* ok = NULL; // pointer to appropriate target if found any
291 if(m_cooldownTime >= time(NULL))
292 return;
294 bool IsBattleGroundTrap = false;
295 //FIXME: this is activation radius (in different casting radius that must be selected from spell data)
296 //TODO: move activated state code (cast itself) to GO_ACTIVATED, in this place only check activating and set state
297 float radius = goInfo->trap.radius;
298 if(!radius)
300 if(goInfo->trap.cooldown != 3) // cast in other case (at some triggring/linked go/etc explicit call)
301 return;
302 else
304 if(m_respawnTime > 0)
305 break;
307 radius = goInfo->trap.cooldown; // battlegrounds gameobjects has data2 == 0 && data5 == 3
308 IsBattleGroundTrap = true;
312 bool NeedDespawn = (goInfo->trap.charges != 0);
314 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
315 Cell cell(p);
316 cell.data.Part.reserved = ALL_DISTRICT;
318 // Note: this hack with search required until GO casting not implemented
319 // search unfriendly creature
320 if(owner && NeedDespawn) // hunter trap
322 MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck u_check(this, owner, radius);
323 MaNGOS::UnitSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck> checker(ok, u_check);
325 CellLock<GridReadGuard> cell_lock(cell, p);
327 TypeContainerVisitor<MaNGOS::UnitSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck>, GridTypeMapContainer > grid_object_checker(checker);
328 cell_lock->Visit(cell_lock, grid_object_checker, *MapManager::Instance().GetMap(GetMapId(), this));
330 // or unfriendly player/pet
331 if(!ok)
333 TypeContainerVisitor<MaNGOS::UnitSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck>, WorldTypeMapContainer > world_object_checker(checker);
334 cell_lock->Visit(cell_lock, world_object_checker, *MapManager::Instance().GetMap(GetMapId(), this));
337 else // environmental trap
339 // environmental damage spells already have around enemies targeting but this not help in case not existed GO casting support
341 // affect only players
342 Player* p_ok = NULL;
343 MaNGOS::AnyPlayerInObjectRangeCheck p_check(this, radius);
344 MaNGOS::PlayerSearcher<MaNGOS::AnyPlayerInObjectRangeCheck> checker(p_ok, p_check);
346 CellLock<GridReadGuard> cell_lock(cell, p);
348 TypeContainerVisitor<MaNGOS::PlayerSearcher<MaNGOS::AnyPlayerInObjectRangeCheck>, WorldTypeMapContainer > world_object_checker(checker);
349 cell_lock->Visit(cell_lock, world_object_checker, *MapManager::Instance().GetMap(GetMapId(), this));
350 ok = p_ok;
353 if (ok)
355 Unit *caster = owner ? owner : ok;
357 caster->CastSpell(ok, goInfo->trap.spellId, true);
358 m_cooldownTime = time(NULL) + 4; // 4 seconds
360 if(NeedDespawn)
361 SetLootState(GO_JUST_DEACTIVATED); // can be despawned or destroyed
363 if(IsBattleGroundTrap && ok->GetTypeId() == TYPEID_PLAYER)
365 //BattleGround gameobjects case
366 if(((Player*)ok)->InBattleGround())
367 if(BattleGround *bg = ((Player*)ok)->GetBattleGround())
368 bg->HandleTriggerBuff(GetGUID());
373 if (m_charges && m_usetimes >= m_charges)
374 SetLootState(GO_JUST_DEACTIVATED); // can be despawned or destroyed
376 break;
378 case GO_ACTIVATED:
380 switch(GetGoType())
382 case GAMEOBJECT_TYPE_DOOR:
383 case GAMEOBJECT_TYPE_BUTTON:
384 if(GetAutoCloseTime() && (m_cooldownTime < time(NULL)))
386 SwitchDoorOrButton(false);
387 SetLootState(GO_JUST_DEACTIVATED);
389 break;
391 break;
393 case GO_JUST_DEACTIVATED:
395 //if Gameobject should cast spell, then this, but some GOs (type = 10) should be destroyed
396 if (GetGoType() == GAMEOBJECT_TYPE_GOOBER)
398 uint32 spellId = GetGOInfo()->goober.spellId;
400 if(spellId)
402 std::set<uint32>::iterator it = m_unique_users.begin();
403 std::set<uint32>::iterator end = m_unique_users.end();
404 for (; it != end; it++)
406 Unit* owner = Unit::GetUnit(*this, uint64(*it));
407 if (owner) owner->CastSpell(owner, spellId, false);
410 m_unique_users.clear();
411 m_usetimes = 0;
413 //any return here in case battleground traps
416 if(GetOwnerGUID())
418 m_respawnTime = 0;
419 Delete();
420 return;
423 //burning flags in some battlegrounds, if you find better condition, just add it
424 if (GetGoAnimProgress() > 0)
426 SendObjectDeSpawnAnim(this->GetGUID());
427 //reset flags
428 SetUInt32Value(GAMEOBJECT_FLAGS, GetGOInfo()->flags);
431 loot.clear();
432 SetLootState(GO_READY);
434 if(!m_respawnDelayTime)
435 return;
437 if(!m_spawnedByDefault)
439 m_respawnTime = 0;
440 return;
443 m_respawnTime = time(NULL) + m_respawnDelayTime;
445 // if option not set then object will be saved at grid unload
446 if(sWorld.getConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY))
447 SaveRespawnTime();
449 ObjectAccessor::UpdateObjectVisibility(this);
451 break;
456 void GameObject::Refresh()
458 // not refresh despawned not casted GO (despawned casted GO destroyed in all cases anyway)
459 if(m_respawnTime > 0 && m_spawnedByDefault)
460 return;
462 if(isSpawned())
463 MapManager::Instance().GetMap(GetMapId(), this)->Add(this);
466 void GameObject::AddUniqueUse(Player* player)
468 AddUse();
469 m_unique_users.insert(player->GetGUIDLow());
472 void GameObject::Delete()
474 SendObjectDeSpawnAnim(GetGUID());
476 SetGoState(1);
477 SetUInt32Value(GAMEOBJECT_FLAGS, GetGOInfo()->flags);
479 AddObjectToRemoveList();
482 void GameObject::getFishLoot(Loot *fishloot)
484 fishloot->clear();
486 uint32 subzone = GetAreaId();
488 // if subzone loot exist use it
489 if(LootTemplates_Fishing.HaveLootFor(subzone))
490 fishloot->FillLoot(subzone, LootTemplates_Fishing, NULL);
491 // else use zone loot
492 else
493 fishloot->FillLoot(GetZoneId(), LootTemplates_Fishing, NULL);
496 void GameObject::SaveToDB()
498 // this should only be used when the gameobject has already been loaded
499 // perferably after adding to map, because mapid may not be valid otherwise
500 GameObjectData const *data = objmgr.GetGOData(m_DBTableGuid);
501 if(!data)
503 sLog.outError("GameObject::SaveToDB failed, cannot get gameobject data!");
504 return;
507 SaveToDB(GetMapId(), data->spawnMask);
510 void GameObject::SaveToDB(uint32 mapid, uint8 spawnMask)
512 const GameObjectInfo *goI = GetGOInfo();
514 if (!goI)
515 return;
517 if (!m_DBTableGuid)
518 m_DBTableGuid = GetGUIDLow();
519 // update in loaded data (changing data only in this place)
520 GameObjectData& data = objmgr.NewGOData(m_DBTableGuid);
522 // data->guid = guid don't must be update at save
523 data.id = GetEntry();
524 data.mapid = mapid;
525 data.posX = GetFloatValue(GAMEOBJECT_POS_X);
526 data.posY = GetFloatValue(GAMEOBJECT_POS_Y);
527 data.posZ = GetFloatValue(GAMEOBJECT_POS_Z);
528 data.orientation = GetFloatValue(GAMEOBJECT_FACING);
529 data.rotation0 = GetFloatValue(GAMEOBJECT_PARENTROTATION+0);
530 data.rotation1 = GetFloatValue(GAMEOBJECT_PARENTROTATION+1);
531 data.rotation2 = GetFloatValue(GAMEOBJECT_PARENTROTATION+2);
532 data.rotation3 = GetFloatValue(GAMEOBJECT_PARENTROTATION+3);
533 data.spawntimesecs = m_spawnedByDefault ? m_respawnDelayTime : -(int32)m_respawnDelayTime;
534 data.animprogress = GetGoAnimProgress();
535 data.go_state = GetGoState();
536 data.spawnMask = spawnMask;
538 // updated in DB
539 std::ostringstream ss;
540 ss << "INSERT INTO gameobject VALUES ( "
541 << m_DBTableGuid << ", "
542 << GetEntry() << ", "
543 << mapid << ", "
544 << (uint32)spawnMask << ", "
545 << GetFloatValue(GAMEOBJECT_POS_X) << ", "
546 << GetFloatValue(GAMEOBJECT_POS_Y) << ", "
547 << GetFloatValue(GAMEOBJECT_POS_Z) << ", "
548 << GetFloatValue(GAMEOBJECT_FACING) << ", "
549 << GetFloatValue(GAMEOBJECT_PARENTROTATION) << ", "
550 << GetFloatValue(GAMEOBJECT_PARENTROTATION+1) << ", "
551 << GetFloatValue(GAMEOBJECT_PARENTROTATION+2) << ", "
552 << GetFloatValue(GAMEOBJECT_PARENTROTATION+3) << ", "
553 << m_respawnDelayTime << ", "
554 << (uint32)GetGoAnimProgress() << ", "
555 << (uint32)GetGoState() << ")";
557 WorldDatabase.BeginTransaction();
558 WorldDatabase.PExecuteLog("DELETE FROM gameobject WHERE guid = '%u'", m_DBTableGuid);
559 WorldDatabase.PExecuteLog( ss.str( ).c_str( ) );
560 WorldDatabase.CommitTransaction();
563 bool GameObject::LoadFromDB(uint32 guid, Map *map)
565 GameObjectData const* data = objmgr.GetGOData(guid);
567 if( !data )
569 sLog.outErrorDb("ERROR: Gameobject (GUID: %u) not found in table `gameobject`, can't load. ",guid);
570 return false;
573 uint32 entry = data->id;
574 uint32 map_id = data->mapid;
575 float x = data->posX;
576 float y = data->posY;
577 float z = data->posZ;
578 float ang = data->orientation;
580 float rotation0 = data->rotation0;
581 float rotation1 = data->rotation1;
582 float rotation2 = data->rotation2;
583 float rotation3 = data->rotation3;
585 uint32 animprogress = data->animprogress;
586 uint32 go_state = data->go_state;
588 m_DBTableGuid = guid;
589 if (map->GetInstanceId() != 0) guid = objmgr.GenerateLowGuid(HIGHGUID_GAMEOBJECT);
591 if (!Create(guid,entry, map, x, y, z, ang, rotation0, rotation1, rotation2, rotation3, animprogress, go_state) )
592 return false;
594 switch(GetGOInfo()->type)
596 case GAMEOBJECT_TYPE_DOOR:
597 case GAMEOBJECT_TYPE_BUTTON:
598 /* this code (in comment) isn't correct because in battlegrounds we need despawnable doors and buttons, pls remove
599 SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_NODESPAWN);
600 m_spawnedByDefault = true;
601 m_respawnDelayTime = 0;
602 m_respawnTime = 0;
603 break;*/
604 default:
605 if(data->spawntimesecs >= 0)
607 m_spawnedByDefault = true;
608 m_respawnDelayTime = data->spawntimesecs;
609 m_respawnTime = objmgr.GetGORespawnTime(m_DBTableGuid, map->GetInstanceId());
611 // ready to respawn
612 if(m_respawnTime && m_respawnTime <= time(NULL))
614 m_respawnTime = 0;
615 objmgr.SaveGORespawnTime(m_DBTableGuid,GetInstanceId(),0);
618 else
620 m_spawnedByDefault = false;
621 m_respawnDelayTime = -data->spawntimesecs;
622 m_respawnTime = 0;
624 break;
627 return true;
630 void GameObject::DeleteFromDB()
632 objmgr.SaveGORespawnTime(m_DBTableGuid,GetInstanceId(),0);
633 objmgr.DeleteGOData(m_DBTableGuid);
634 WorldDatabase.PExecuteLog("DELETE FROM gameobject WHERE guid = '%u'", m_DBTableGuid);
635 WorldDatabase.PExecuteLog("DELETE FROM game_event_gameobject WHERE guid = '%u'", m_DBTableGuid);
638 GameObject* GameObject::GetGameObject(WorldObject& object, uint64 guid)
640 return ObjectAccessor::GetGameObject(object,guid);
643 GameObjectInfo const *GameObject::GetGOInfo() const
645 return m_goInfo;
648 uint32 GameObject::GetLootId(GameObjectInfo const* ginfo)
650 if (!ginfo)
651 return 0;
653 switch(ginfo->type)
655 case GAMEOBJECT_TYPE_CHEST:
656 return ginfo->chest.lootId;
657 case GAMEOBJECT_TYPE_FISHINGHOLE:
658 return ginfo->fishinghole.lootId;
659 case GAMEOBJECT_TYPE_FISHINGNODE:
660 return ginfo->fishnode.lootId;
661 default:
662 return 0;
666 /*********************************************************/
667 /*** QUEST SYSTEM ***/
668 /*********************************************************/
669 bool GameObject::hasQuest(uint32 quest_id) const
671 QuestRelations const& qr = objmgr.mGOQuestRelations;
672 for(QuestRelations::const_iterator itr = qr.lower_bound(GetEntry()); itr != qr.upper_bound(GetEntry()); ++itr)
674 if(itr->second==quest_id)
675 return true;
677 return false;
680 bool GameObject::hasInvolvedQuest(uint32 quest_id) const
682 QuestRelations const& qr = objmgr.mGOQuestInvolvedRelations;
683 for(QuestRelations::const_iterator itr = qr.lower_bound(GetEntry()); itr != qr.upper_bound(GetEntry()); ++itr)
685 if(itr->second==quest_id)
686 return true;
688 return false;
691 bool GameObject::IsTransport() const
693 // If something is marked as a transport, don't transmit an out of range packet for it.
694 GameObjectInfo const * gInfo = GetGOInfo();
695 if(!gInfo) return false;
696 return gInfo->type == GAMEOBJECT_TYPE_TRANSPORT || gInfo->type == GAMEOBJECT_TYPE_MO_TRANSPORT;
699 Unit* GameObject::GetOwner() const
701 return ObjectAccessor::GetUnit(*this, GetOwnerGUID());
704 void GameObject::SaveRespawnTime()
706 if(m_respawnTime > time(NULL) && m_spawnedByDefault)
707 objmgr.SaveGORespawnTime(m_DBTableGuid,GetInstanceId(),m_respawnTime);
710 bool GameObject::isVisibleForInState(Player const* u, bool inVisibleList) const
712 // Not in world
713 if(!IsInWorld() || !u->IsInWorld())
714 return false;
716 // Transport always visible at this step implementation
717 if(IsTransport() && IsInMap(u))
718 return true;
720 // quick check visibility false cases for non-GM-mode
721 if(!u->isGameMaster())
723 // despawned and then not visible for non-GM in GM-mode
724 if(!isSpawned())
725 return false;
727 // special invisibility cases
728 /* TODO: implement trap stealth, take look at spell 2836
729 if(GetGOInfo()->type == GAMEOBJECT_TYPE_TRAP && GetGOInfo()->trap.stealthed && u->IsHostileTo(GetOwner()))
731 if(check stuff here)
732 return false;
735 // Smuggled Mana Cell required 10 invisibility type detection/state
736 if(GetEntry()==187039 && ((u->m_detectInvisibilityMask | u->m_invisibilityMask) & (1<<10))==0)
737 return false;
740 // check distance
741 return IsWithinDistInMap(u,World::GetMaxVisibleDistanceForObject() +
742 (inVisibleList ? World::GetVisibleObjectGreyDistance() : 0.0f) );
745 void GameObject::Respawn()
747 if(m_spawnedByDefault && m_respawnTime > 0)
749 m_respawnTime = time(NULL);
750 objmgr.SaveGORespawnTime(m_DBTableGuid,GetInstanceId(),0);
754 bool GameObject::ActivateToQuest( Player *pTarget)const
756 if(!objmgr.IsGameObjectForQuests(GetEntry()))
757 return false;
759 switch(GetGoType())
761 // scan GO chest with loot including quest items
762 case GAMEOBJECT_TYPE_CHEST:
764 if(LootTemplates_Gameobject.HaveQuestLootForPlayer(GetLootId(), pTarget))
765 return true;
766 break;
768 case GAMEOBJECT_TYPE_GOOBER:
770 if(pTarget->GetQuestStatus(GetGOInfo()->goober.questId) == QUEST_STATUS_INCOMPLETE)
771 return true;
772 break;
774 default:
775 break;
778 return false;
781 void GameObject::TriggeringLinkedGameObject( uint32 trapEntry, Unit* target)
783 GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(trapEntry);
784 if(!trapInfo || trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
785 return;
787 SpellEntry const* trapSpell = sSpellStore.LookupEntry(trapInfo->trap.spellId);
788 if(!trapSpell) // checked at load already
789 return;
791 float range = GetSpellMaxRange(sSpellRangeStore.LookupEntry(trapSpell->rangeIndex));
793 // search nearest linked GO
794 GameObject* trapGO = NULL;
796 // using original GO distance
797 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
798 Cell cell(p);
799 cell.data.Part.reserved = ALL_DISTRICT;
801 MaNGOS::NearestGameObjectEntryInObjectRangeCheck go_check(*target,trapEntry,range);
802 MaNGOS::GameObjectLastSearcher<MaNGOS::NearestGameObjectEntryInObjectRangeCheck> checker(trapGO,go_check);
804 TypeContainerVisitor<MaNGOS::GameObjectLastSearcher<MaNGOS::NearestGameObjectEntryInObjectRangeCheck>, GridTypeMapContainer > object_checker(checker);
805 CellLock<GridReadGuard> cell_lock(cell, p);
806 cell_lock->Visit(cell_lock, object_checker, *MapManager::Instance().GetMap(GetMapId(), this));
809 // found correct GO
810 // FIXME: when GO casting will be implemented trap must cast spell to target
811 if(trapGO)
812 target->CastSpell(target,trapSpell,true);
815 GameObject* GameObject::LookupFishingHoleAround(float range)
817 GameObject* ok = NULL;
819 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
820 Cell cell(p);
821 cell.data.Part.reserved = ALL_DISTRICT;
822 MaNGOS::NearestGameObjectFishingHole u_check(*this, range);
823 MaNGOS::GameObjectSearcher<MaNGOS::NearestGameObjectFishingHole> checker(ok, u_check);
825 CellLock<GridReadGuard> cell_lock(cell, p);
827 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::NearestGameObjectFishingHole>, GridTypeMapContainer > grid_object_checker(checker);
828 cell_lock->Visit(cell_lock, grid_object_checker, *MapManager::Instance().GetMap(GetMapId(), this));
830 return ok;
833 void GameObject::UseDoorOrButton(uint32 time_to_restore)
835 if(m_lootState != GO_READY)
836 return;
838 if(!time_to_restore)
839 time_to_restore = GetAutoCloseTime();
841 SwitchDoorOrButton(true);
842 SetLootState(GO_ACTIVATED);
844 m_cooldownTime = time(NULL) + time_to_restore;
848 void GameObject::SwitchDoorOrButton(bool activate)
850 if(activate)
851 SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_IN_USE);
852 else
853 RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_IN_USE);
855 if(GetGoState()) //if closed -> open
856 SetGoState(0);
857 else //if open -> close
858 SetGoState(1);
861 void GameObject::Use(Unit* user)
863 // by default spell caster is user
864 Unit* spellCaster = user;
865 uint32 spellId = 0;
867 switch(GetGoType())
869 case GAMEOBJECT_TYPE_DOOR: //0
870 case GAMEOBJECT_TYPE_BUTTON: //1
871 //doors/buttons never really despawn, only reset to default state/flags
872 UseDoorOrButton();
874 // activate script
875 sWorld.ScriptsStart(sGameObjectScripts, GetDBTableGUIDLow(), spellCaster, this);
876 return;
878 case GAMEOBJECT_TYPE_QUESTGIVER: //2
880 if(user->GetTypeId()!=TYPEID_PLAYER)
881 return;
883 Player* player = (Player*)user;
885 player->PrepareQuestMenu( GetGUID() );
886 player->SendPreparedQuest( GetGUID() );
887 return;
889 //Sitting: Wooden bench, chairs enzz
890 case GAMEOBJECT_TYPE_CHAIR: //7
892 GameObjectInfo const* info = GetGOInfo();
893 if(!info)
894 return;
896 if(user->GetTypeId()!=TYPEID_PLAYER)
897 return;
899 Player* player = (Player*)user;
901 // a chair may have n slots. we have to calculate their positions and teleport the player to the nearest one
903 // check if the db is sane
904 if(info->chair.slots > 0)
906 float lowestDist = DEFAULT_VISIBILITY_DISTANCE;
908 float x_lowest = GetPositionX();
909 float y_lowest = GetPositionY();
911 // the object orientation + 1/2 pi
912 // every slot will be on that straight line
913 float orthogonalOrientation = GetOrientation()+M_PI*0.5f;
914 // find nearest slot
915 for(uint32 i=0; i<info->chair.slots; i++)
917 // the distance between this slot and the center of the go - imagine a 1D space
918 float relativeDistance = (info->size*i)-(info->size*(info->chair.slots-1)/2.0f);
920 float x_i = GetPositionX() + relativeDistance * cos(orthogonalOrientation);
921 float y_i = GetPositionY() + relativeDistance * sin(orthogonalOrientation);
923 // calculate the distance between the player and this slot
924 float thisDistance = player->GetDistance2d(x_i, y_i);
926 /* debug code. It will spawn a npc on each slot to visualize them.
927 Creature* helper = player->SummonCreature(14496, x_i, y_i, GetPositionZ(), GetOrientation(), TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 10000);
928 std::ostringstream output;
929 output << i << ": thisDist: " << thisDistance;
930 helper->MonsterSay(output.str().c_str(), LANG_UNIVERSAL, 0);
933 if(thisDistance <= lowestDist)
935 lowestDist = thisDistance;
936 x_lowest = x_i;
937 y_lowest = y_i;
940 player->TeleportTo(GetMapId(), x_lowest, y_lowest, GetPositionZ(), GetOrientation(),TELE_TO_NOT_LEAVE_TRANSPORT | TELE_TO_NOT_LEAVE_COMBAT | TELE_TO_NOT_UNSUMMON_PET);
942 else
944 // fallback, will always work
945 player->TeleportTo(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation(),TELE_TO_NOT_LEAVE_TRANSPORT | TELE_TO_NOT_LEAVE_COMBAT | TELE_TO_NOT_UNSUMMON_PET);
947 player->SetStandState(PLAYER_STATE_SIT_LOW_CHAIR+info->chair.height);
948 return;
950 //big gun, its a spell/aura
951 case GAMEOBJECT_TYPE_GOOBER: //10
953 GameObjectInfo const* info = GetGOInfo();
955 if(user->GetTypeId()==TYPEID_PLAYER)
957 Player* player = (Player*)user;
959 // show page
960 if(info->goober.pageId)
962 WorldPacket data(SMSG_GAMEOBJECT_PAGETEXT, 8);
963 data << GetGUID();
964 player->GetSession()->SendPacket(&data);
967 // possible quest objective for active quests
968 player->CastedCreatureOrGO(info->id, GetGUID(), 0);
971 // cast this spell later if provided
972 spellId = info->goober.spellId;
974 break;
976 case GAMEOBJECT_TYPE_CAMERA: //13
978 GameObjectInfo const* info = GetGOInfo();
979 if(!info)
980 return;
982 if(user->GetTypeId()!=TYPEID_PLAYER)
983 return;
985 Player* player = (Player*)user;
987 if(info->camera.cinematicId)
989 WorldPacket data(SMSG_TRIGGER_CINEMATIC, 4);
990 data << info->camera.cinematicId;
991 player->GetSession()->SendPacket(&data);
993 return;
995 //fishing bobber
996 case GAMEOBJECT_TYPE_FISHINGNODE: //17
998 if(user->GetTypeId()!=TYPEID_PLAYER)
999 return;
1001 Player* player = (Player*)user;
1003 if(player->GetGUID() != GetOwnerGUID())
1004 return;
1006 switch(getLootState())
1008 case GO_READY: // ready for loot
1010 // 1) skill must be >= base_zone_skill
1011 // 2) if skill == base_zone_skill => 5% chance
1012 // 3) chance is linear dependence from (base_zone_skill-skill)
1014 uint32 subzone = GetAreaId();
1016 int32 zone_skill = objmgr.GetFishingBaseSkillLevel( subzone );
1017 if(!zone_skill)
1018 zone_skill = objmgr.GetFishingBaseSkillLevel( GetZoneId() );
1020 //provide error, no fishable zone or area should be 0
1021 if(!zone_skill)
1022 sLog.outErrorDb("Fishable areaId %u are not properly defined in `skill_fishing_base_level`.",subzone);
1024 int32 skill = player->GetSkillValue(SKILL_FISHING);
1025 int32 chance = skill - zone_skill + 5;
1026 int32 roll = irand(1,100);
1028 DEBUG_LOG("Fishing check (skill: %i zone min skill: %i chance %i roll: %i",skill,zone_skill,chance,roll);
1030 if(skill >= zone_skill && chance >= roll)
1032 // prevent removing GO at spell cancel
1033 player->RemoveGameObject(this,false);
1034 SetOwnerGUID(player->GetGUID());
1036 //fish catched
1037 player->UpdateFishingSkill();
1039 GameObject* ok = LookupFishingHoleAround(DEFAULT_VISIBILITY_DISTANCE);
1040 if (ok)
1042 player->SendLoot(ok->GetGUID(),LOOT_FISHINGHOLE);
1043 SetLootState(GO_JUST_DEACTIVATED);
1045 else
1046 player->SendLoot(GetGUID(),LOOT_FISHING);
1048 else
1050 // fish escaped, can be deleted now
1051 SetLootState(GO_JUST_DEACTIVATED);
1053 WorldPacket data(SMSG_FISH_ESCAPED, 0);
1054 player->GetSession()->SendPacket(&data);
1056 break;
1058 case GO_JUST_DEACTIVATED: // nothing to do, will be deleted at next update
1059 break;
1060 default:
1062 SetLootState(GO_JUST_DEACTIVATED);
1064 WorldPacket data(SMSG_FISH_NOT_HOOKED, 0);
1065 player->GetSession()->SendPacket(&data);
1066 break;
1070 if(player->m_currentSpells[CURRENT_CHANNELED_SPELL])
1072 player->m_currentSpells[CURRENT_CHANNELED_SPELL]->SendChannelUpdate(0);
1073 player->m_currentSpells[CURRENT_CHANNELED_SPELL]->finish();
1075 return;
1078 case GAMEOBJECT_TYPE_SUMMONING_RITUAL: //18
1080 if(user->GetTypeId()!=TYPEID_PLAYER)
1081 return;
1083 Player* player = (Player*)user;
1085 Unit* caster = GetOwner();
1087 GameObjectInfo const* info = GetGOInfo();
1089 if( !caster || caster->GetTypeId()!=TYPEID_PLAYER )
1090 return;
1092 // accept only use by player from same group for caster except caster itself
1093 if(((Player*)caster)==player || !((Player*)caster)->IsInSameRaidWith(player))
1094 return;
1096 AddUniqueUse(player);
1098 // full amount unique participants including original summoner
1099 if(GetUniqueUseCount() < info->summoningRitual.reqParticipants)
1100 return;
1102 // in case summoning ritual caster is GO creator
1103 spellCaster = caster;
1105 if(!caster->m_currentSpells[CURRENT_CHANNELED_SPELL])
1106 return;
1108 spellId = info->summoningRitual.spellId;
1110 // finish spell
1111 caster->m_currentSpells[CURRENT_CHANNELED_SPELL]->SendChannelUpdate(0);
1112 caster->m_currentSpells[CURRENT_CHANNELED_SPELL]->finish();
1114 // can be deleted now
1115 SetLootState(GO_JUST_DEACTIVATED);
1117 // go to end function to spell casting
1118 break;
1120 case GAMEOBJECT_TYPE_SPELLCASTER: //22
1122 SetUInt32Value(GAMEOBJECT_FLAGS,2);
1124 GameObjectInfo const* info = GetGOInfo();
1125 if(!info)
1126 return;
1128 if(info->spellcaster.partyOnly)
1130 Unit* caster = GetOwner();
1131 if( !caster || caster->GetTypeId()!=TYPEID_PLAYER )
1132 return;
1134 if(user->GetTypeId()!=TYPEID_PLAYER || !((Player*)user)->IsInSameRaidWith((Player*)caster))
1135 return;
1138 spellId = info->spellcaster.spellId;
1140 AddUse();
1141 break;
1143 case GAMEOBJECT_TYPE_MEETINGSTONE: //23
1145 GameObjectInfo const* info = GetGOInfo();
1147 if(user->GetTypeId()!=TYPEID_PLAYER)
1148 return;
1150 Player* player = (Player*)user;
1152 Player* targetPlayer = ObjectAccessor::FindPlayer(player->GetSelection());
1154 // accept only use by player from same group for caster except caster itself
1155 if(!targetPlayer || targetPlayer == player || !targetPlayer->IsInSameGroupWith(player))
1156 return;
1158 //required lvl checks!
1159 uint8 level = player->getLevel();
1160 if (level < info->meetingstone.minLevel || level > info->meetingstone.maxLevel)
1161 return;
1162 level = targetPlayer->getLevel();
1163 if (level < info->meetingstone.minLevel || level > info->meetingstone.maxLevel)
1164 return;
1166 spellId = 23598;
1168 break;
1171 case GAMEOBJECT_TYPE_FLAGSTAND: // 24
1173 if(user->GetTypeId()!=TYPEID_PLAYER)
1174 return;
1176 Player* player = (Player*)user;
1178 if( player->isAllowUseBattleGroundObject() )
1180 // in battleground check
1181 BattleGround *bg = player->GetBattleGround();
1182 if(!bg)
1183 return;
1184 // BG flag click
1185 // AB:
1186 // 15001
1187 // 15002
1188 // 15003
1189 // 15004
1190 // 15005
1191 bg->EventPlayerClickedOnFlag(player, this);
1192 return; //we don;t need to delete flag ... it is despawned!
1194 break;
1196 case GAMEOBJECT_TYPE_FLAGDROP: // 26
1198 if(user->GetTypeId()!=TYPEID_PLAYER)
1199 return;
1201 Player* player = (Player*)user;
1203 if( player->isAllowUseBattleGroundObject() )
1205 // in battleground check
1206 BattleGround *bg = player->GetBattleGround();
1207 if(!bg)
1208 return;
1209 // BG flag dropped
1210 // WS:
1211 // 179785 - Silverwing Flag
1212 // 179786 - Warsong Flag
1213 // EotS:
1214 // 184142 - Netherstorm Flag
1215 GameObjectInfo const* info = GetGOInfo();
1216 if(info)
1218 switch(info->id)
1220 case 179785: // Silverwing Flag
1221 // check if it's correct bg
1222 if(bg->GetTypeID() == BATTLEGROUND_WS)
1223 bg->EventPlayerClickedOnFlag(player, this);
1224 break;
1225 case 179786: // Warsong Flag
1226 if(bg->GetTypeID() == BATTLEGROUND_WS)
1227 bg->EventPlayerClickedOnFlag(player, this);
1228 break;
1229 case 184142: // Netherstorm Flag
1230 if(bg->GetTypeID() == BATTLEGROUND_EY)
1231 bg->EventPlayerClickedOnFlag(player, this);
1232 break;
1235 //this cause to call return, all flags must be deleted here!!
1236 spellId = 0;
1237 Delete();
1239 break;
1241 case GAMEOBJECT_TYPE_BARBER_CHAIR: //32
1243 GameObjectInfo const* info = GetGOInfo();
1244 if(!info)
1245 return;
1247 if(user->GetTypeId()!=TYPEID_PLAYER)
1248 return;
1250 Player* player = (Player*)user;
1252 // fallback, will always work
1253 player->TeleportTo(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation(),TELE_TO_NOT_LEAVE_TRANSPORT | TELE_TO_NOT_LEAVE_COMBAT | TELE_TO_NOT_UNSUMMON_PET);
1255 WorldPacket data(SMSG_ENABLE_BARBER_SHOP, 0);
1256 player->GetSession()->SendPacket(&data);
1258 player->SetStandState(PLAYER_STATE_SIT_LOW_CHAIR+info->barberChair.chairheight);
1259 return;
1261 default:
1262 sLog.outDebug("Unknown Object Type %u", GetGoType());
1263 break;
1266 if(!spellId)
1267 return;
1269 SpellEntry const *spellInfo = sSpellStore.LookupEntry( spellId );
1270 if(!spellInfo)
1272 sLog.outError("WORLD: unknown spell id %u at use action for gameobject (Entry: %u GoType: %u )", spellId,GetEntry(),GetGoType());
1273 return;
1276 Spell *spell = new Spell(spellCaster, spellInfo, false);
1278 // spell target is user of GO
1279 SpellCastTargets targets;
1280 targets.setUnitTarget( user );
1282 spell->prepare(&targets);