[9957] Alow sell item for money and extanded coset without momey in same time.
[getmangos.git] / src / game / ObjectMgr.cpp
blobe2ecc13e805d8c888a9e85c4326d580b9979c1cd
1 /*
2 * Copyright (C) 2005-2010 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 "Database/DatabaseEnv.h"
21 #include "Database/SQLStorage.h"
22 #include "Database/SQLStorageImpl.h"
23 #include "Policies/SingletonImp.h"
25 #include "Log.h"
26 #include "MapManager.h"
27 #include "ObjectMgr.h"
28 #include "ObjectGuid.h"
29 #include "SpellMgr.h"
30 #include "UpdateMask.h"
31 #include "World.h"
32 #include "Group.h"
33 #include "Guild.h"
34 #include "ArenaTeam.h"
35 #include "Transports.h"
36 #include "ProgressBar.h"
37 #include "Language.h"
38 #include "GameEventMgr.h"
39 #include "Spell.h"
40 #include "Chat.h"
41 #include "AccountMgr.h"
42 #include "InstanceSaveMgr.h"
43 #include "SpellAuras.h"
44 #include "Util.h"
45 #include "WaypointManager.h"
46 #include "GossipDef.h"
47 #include "Mail.h"
48 #include "InstanceData.h"
50 #include <limits>
52 INSTANTIATE_SINGLETON_1(ObjectMgr);
54 ScriptMapMap sQuestEndScripts;
55 ScriptMapMap sQuestStartScripts;
56 ScriptMapMap sSpellScripts;
57 ScriptMapMap sGameObjectScripts;
58 ScriptMapMap sEventScripts;
59 ScriptMapMap sGossipScripts;
60 ScriptMapMap sCreatureMovementScripts;
62 bool normalizePlayerName(std::string& name)
64 if(name.empty())
65 return false;
67 wchar_t wstr_buf[MAX_INTERNAL_PLAYER_NAME+1];
68 size_t wstr_len = MAX_INTERNAL_PLAYER_NAME;
70 if(!Utf8toWStr(name,&wstr_buf[0],wstr_len))
71 return false;
73 wstr_buf[0] = wcharToUpper(wstr_buf[0]);
74 for(size_t i = 1; i < wstr_len; ++i)
75 wstr_buf[i] = wcharToLower(wstr_buf[i]);
77 if(!WStrToUtf8(wstr_buf,wstr_len,name))
78 return false;
80 return true;
83 LanguageDesc lang_description[LANGUAGES_COUNT] =
85 { LANG_ADDON, 0, 0 },
86 { LANG_UNIVERSAL, 0, 0 },
87 { LANG_ORCISH, 669, SKILL_LANG_ORCISH },
88 { LANG_DARNASSIAN, 671, SKILL_LANG_DARNASSIAN },
89 { LANG_TAURAHE, 670, SKILL_LANG_TAURAHE },
90 { LANG_DWARVISH, 672, SKILL_LANG_DWARVEN },
91 { LANG_COMMON, 668, SKILL_LANG_COMMON },
92 { LANG_DEMONIC, 815, SKILL_LANG_DEMON_TONGUE },
93 { LANG_TITAN, 816, SKILL_LANG_TITAN },
94 { LANG_THALASSIAN, 813, SKILL_LANG_THALASSIAN },
95 { LANG_DRACONIC, 814, SKILL_LANG_DRACONIC },
96 { LANG_KALIMAG, 817, SKILL_LANG_OLD_TONGUE },
97 { LANG_GNOMISH, 7340, SKILL_LANG_GNOMISH },
98 { LANG_TROLL, 7341, SKILL_LANG_TROLL },
99 { LANG_GUTTERSPEAK, 17737, SKILL_LANG_GUTTERSPEAK },
100 { LANG_DRAENEI, 29932, SKILL_LANG_DRAENEI },
101 { LANG_ZOMBIE, 0, 0 },
102 { LANG_GNOMISH_BINARY, 0, 0 },
103 { LANG_GOBLIN_BINARY, 0, 0 }
106 LanguageDesc const* GetLanguageDescByID(uint32 lang)
108 for(int i = 0; i < LANGUAGES_COUNT; ++i)
110 if(uint32(lang_description[i].lang_id) == lang)
111 return &lang_description[i];
114 return NULL;
117 bool SpellClickInfo::IsFitToRequirements(Player const* player) const
119 if(questStart)
121 // not in expected required quest state
122 if (!player || ((!questStartCanActive || !player->IsActiveQuest(questStart)) && !player->GetQuestRewardStatus(questStart)))
123 return false;
126 if(questEnd)
128 // not in expected forbidden quest state
129 if(!player || player->GetQuestRewardStatus(questEnd))
130 return false;
133 return true;
136 template<typename T>
137 T IdGenerator<T>::Generate()
139 if (m_nextGuid >= std::numeric_limits<T>::max()-1)
141 sLog.outError("%s guid overflow!! Can't continue, shutting down server. ",m_name);
142 World::StopNow(ERROR_EXIT_CODE);
144 return m_nextGuid++;
147 template uint32 IdGenerator<uint32>::Generate();
148 template uint64 IdGenerator<uint64>::Generate();
150 ObjectMgr::ObjectMgr() :
151 m_ArenaTeamIds("Arena team ids"),
152 m_AuctionIds("Auction ids"),
153 m_EquipmentSetIds("Equipment set ids"),
154 m_GuildIds("Guild ids"),
155 m_MailIds("Mail ids"),
156 m_PetNumbers("Pet numbers"),
157 m_GroupIds("Group ids")
159 // Only zero condition left, others will be added while loading DB tables
160 mConditions.resize(1);
163 ObjectMgr::~ObjectMgr()
165 for( QuestMap::iterator i = mQuestTemplates.begin( ); i != mQuestTemplates.end( ); ++i )
166 delete i->second;
168 for(PetLevelInfoMap::iterator i = petInfo.begin( ); i != petInfo.end( ); ++i )
169 delete[] i->second;
171 // free only if loaded
172 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
173 delete[] playerClassInfo[class_].levelInfo;
175 for (int race = 0; race < MAX_RACES; ++race)
176 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
177 delete[] playerInfo[race][class_].levelInfo;
179 // free group and guild objects
180 for (GroupMap::iterator itr = mGroupMap.begin(); itr != mGroupMap.end(); ++itr)
181 delete itr->second;
183 for (GuildMap::iterator itr = mGuildMap.begin(); itr != mGuildMap.end(); ++itr)
184 delete itr->second;
186 for (ArenaTeamMap::iterator itr = mArenaTeamMap.begin(); itr != mArenaTeamMap.end(); ++itr)
187 delete itr->second;
189 for (CacheVendorItemMap::iterator itr = m_mCacheVendorItemMap.begin(); itr != m_mCacheVendorItemMap.end(); ++itr)
190 itr->second.Clear();
192 for (CacheTrainerSpellMap::iterator itr = m_mCacheTrainerSpellMap.begin(); itr != m_mCacheTrainerSpellMap.end(); ++itr)
193 itr->second.Clear();
196 Group* ObjectMgr::GetGroupById(uint32 id) const
198 GroupMap::const_iterator itr = mGroupMap.find(id);
199 if (itr != mGroupMap.end())
200 return itr->second;
202 return NULL;
205 Guild* ObjectMgr::GetGuildById(uint32 GuildId) const
207 GuildMap::const_iterator itr = mGuildMap.find(GuildId);
208 if (itr != mGuildMap.end())
209 return itr->second;
211 return NULL;
214 Guild * ObjectMgr::GetGuildByName(const std::string& guildname) const
216 for(GuildMap::const_iterator itr = mGuildMap.begin(); itr != mGuildMap.end(); ++itr)
217 if (itr->second->GetName() == guildname)
218 return itr->second;
220 return NULL;
223 std::string ObjectMgr::GetGuildNameById(uint32 GuildId) const
225 GuildMap::const_iterator itr = mGuildMap.find(GuildId);
226 if (itr != mGuildMap.end())
227 return itr->second->GetName();
229 return "";
232 Guild* ObjectMgr::GetGuildByLeader(const uint64 &guid) const
234 for(GuildMap::const_iterator itr = mGuildMap.begin(); itr != mGuildMap.end(); ++itr)
235 if (itr->second->GetLeader() == guid)
236 return itr->second;
238 return NULL;
241 ArenaTeam* ObjectMgr::GetArenaTeamById(uint32 arenateamid) const
243 ArenaTeamMap::const_iterator itr = mArenaTeamMap.find(arenateamid);
244 if (itr != mArenaTeamMap.end())
245 return itr->second;
247 return NULL;
250 ArenaTeam* ObjectMgr::GetArenaTeamByName(const std::string& arenateamname) const
252 for(ArenaTeamMap::const_iterator itr = mArenaTeamMap.begin(); itr != mArenaTeamMap.end(); ++itr)
253 if (itr->second->GetName() == arenateamname)
254 return itr->second;
256 return NULL;
259 ArenaTeam* ObjectMgr::GetArenaTeamByCaptain(uint64 const& guid) const
261 for(ArenaTeamMap::const_iterator itr = mArenaTeamMap.begin(); itr != mArenaTeamMap.end(); ++itr)
262 if (itr->second->GetCaptain() == guid)
263 return itr->second;
265 return NULL;
268 CreatureInfo const* ObjectMgr::GetCreatureTemplate(uint32 id)
270 return sCreatureStorage.LookupEntry<CreatureInfo>(id);
273 void ObjectMgr::LoadCreatureLocales()
275 mCreatureLocaleMap.clear(); // need for reload case
277 QueryResult *result = WorldDatabase.Query("SELECT entry,name_loc1,subname_loc1,name_loc2,subname_loc2,name_loc3,subname_loc3,name_loc4,subname_loc4,name_loc5,subname_loc5,name_loc6,subname_loc6,name_loc7,subname_loc7,name_loc8,subname_loc8 FROM locales_creature");
279 if(!result)
281 barGoLink bar(1);
283 bar.step();
285 sLog.outString();
286 sLog.outString(">> Loaded 0 creature locale strings. DB table `locales_creature` is empty.");
287 return;
290 barGoLink bar((int)result->GetRowCount());
294 Field *fields = result->Fetch();
295 bar.step();
297 uint32 entry = fields[0].GetUInt32();
299 CreatureLocale& data = mCreatureLocaleMap[entry];
301 for(int i = 1; i < MAX_LOCALE; ++i)
303 std::string str = fields[1+2*(i-1)].GetCppString();
304 if(!str.empty())
306 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
307 if(idx >= 0)
309 if((int32)data.Name.size() <= idx)
310 data.Name.resize(idx+1);
312 data.Name[idx] = str;
315 str = fields[1+2*(i-1)+1].GetCppString();
316 if(!str.empty())
318 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
319 if(idx >= 0)
321 if((int32)data.SubName.size() <= idx)
322 data.SubName.resize(idx+1);
324 data.SubName[idx] = str;
328 } while (result->NextRow());
330 delete result;
332 sLog.outString();
333 sLog.outString( ">> Loaded %lu creature locale strings", (unsigned long)mCreatureLocaleMap.size() );
336 void ObjectMgr::LoadGossipMenuItemsLocales()
338 mGossipMenuItemsLocaleMap.clear(); // need for reload case
340 QueryResult *result = WorldDatabase.Query("SELECT menu_id,id,"
341 "option_text_loc1,box_text_loc1,option_text_loc2,box_text_loc2,"
342 "option_text_loc3,box_text_loc3,option_text_loc4,box_text_loc4,"
343 "option_text_loc5,box_text_loc5,option_text_loc6,box_text_loc6,"
344 "option_text_loc7,box_text_loc7,option_text_loc8,box_text_loc8 "
345 "FROM locales_gossip_menu_option");
347 if(!result)
349 barGoLink bar(1);
351 bar.step();
353 sLog.outString();
354 sLog.outString(">> Loaded 0 gossip_menu_option locale strings. DB table `locales_gossip_menu_option` is empty.");
355 return;
358 barGoLink bar((int)result->GetRowCount());
362 Field *fields = result->Fetch();
363 bar.step();
365 uint16 menuId = fields[0].GetUInt16();
366 uint16 id = fields[1].GetUInt16();
368 GossipMenuItemsLocale& data = mGossipMenuItemsLocaleMap[MAKE_PAIR32(menuId,id)];
370 for(int i = 1; i < MAX_LOCALE; ++i)
372 std::string str = fields[2+2*(i-1)].GetCppString();
373 if(!str.empty())
375 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
376 if(idx >= 0)
378 if((int32)data.OptionText.size() <= idx)
379 data.OptionText.resize(idx+1);
381 data.OptionText[idx] = str;
384 str = fields[2+2*(i-1)+1].GetCppString();
385 if(!str.empty())
387 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
388 if(idx >= 0)
390 if((int32)data.BoxText.size() <= idx)
391 data.BoxText.resize(idx+1);
393 data.BoxText[idx] = str;
397 } while (result->NextRow());
399 delete result;
401 sLog.outString();
402 sLog.outString( ">> Loaded %lu gossip_menu_option locale strings", (unsigned long)mGossipMenuItemsLocaleMap.size() );
405 void ObjectMgr::LoadPointOfInterestLocales()
407 mPointOfInterestLocaleMap.clear(); // need for reload case
409 QueryResult *result = WorldDatabase.Query("SELECT entry,icon_name_loc1,icon_name_loc2,icon_name_loc3,icon_name_loc4,icon_name_loc5,icon_name_loc6,icon_name_loc7,icon_name_loc8 FROM locales_points_of_interest");
411 if(!result)
413 barGoLink bar(1);
415 bar.step();
417 sLog.outString();
418 sLog.outString(">> Loaded 0 points_of_interest locale strings. DB table `locales_points_of_interest` is empty.");
419 return;
422 barGoLink bar((int)result->GetRowCount());
426 Field *fields = result->Fetch();
427 bar.step();
429 uint32 entry = fields[0].GetUInt32();
431 PointOfInterestLocale& data = mPointOfInterestLocaleMap[entry];
433 for(int i = 1; i < MAX_LOCALE; ++i)
435 std::string str = fields[i].GetCppString();
436 if(str.empty())
437 continue;
439 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
440 if(idx >= 0)
442 if((int32)data.IconName.size() <= idx)
443 data.IconName.resize(idx+1);
445 data.IconName[idx] = str;
448 } while (result->NextRow());
450 delete result;
452 sLog.outString();
453 sLog.outString( ">> Loaded %lu points_of_interest locale strings", (unsigned long)mPointOfInterestLocaleMap.size() );
456 struct SQLCreatureLoader : public SQLStorageLoaderBase<SQLCreatureLoader>
458 template<class D>
459 void convert_from_str(uint32 /*field_pos*/, char *src, D &dst)
461 dst = D(sObjectMgr.GetScriptId(src));
465 void ObjectMgr::LoadCreatureTemplates()
467 SQLCreatureLoader loader;
468 loader.Load(sCreatureStorage);
470 sLog.outString( ">> Loaded %u creature definitions", sCreatureStorage.RecordCount );
471 sLog.outString();
473 std::set<uint32> difficultyEntries[MAX_DIFFICULTY - 1]; // already loaded difficulty 1 value in creatures
474 std::set<uint32> hasDifficultyEntries[MAX_DIFFICULTY - 1]; // already loaded creatures with difficulty 1 values
476 // check data correctness
477 for(uint32 i = 1; i < sCreatureStorage.MaxEntry; ++i)
479 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i);
480 if (!cInfo)
481 continue;
483 bool ok = true; // bool to allow continue outside this loop
484 for (uint32 diff = 0; diff < MAX_DIFFICULTY - 1 && ok; ++diff)
486 if (!cInfo->DifficultyEntry[diff])
487 continue;
488 ok = false; // will be set to true at the end of this loop again
490 CreatureInfo const* difficultyInfo = GetCreatureTemplate(cInfo->DifficultyEntry[diff]);
491 if (!difficultyInfo)
493 sLog.outErrorDb("Creature (Entry: %u) have `difficulty_entry_%u`=%u but creature entry %u not exist.",
494 i, diff + 1, cInfo->DifficultyEntry[diff], cInfo->DifficultyEntry[diff]);
495 continue;
498 if (difficultyEntries[diff].find(i) != difficultyEntries[diff].end())
500 sLog.outErrorDb("Creature (Entry: %u) listed as difficulty %u but have value in `difficulty_entry_%u`.", i, diff + 1, diff + 1);
501 continue;
504 bool ok2 = true;
505 for (uint32 diff2 = 0; diff2 < MAX_DIFFICULTY - 1 && ok2; ++diff2)
507 ok2 = false;
508 if (difficultyEntries[diff2].find(cInfo->DifficultyEntry[diff]) != difficultyEntries[diff2].end())
510 sLog.outErrorDb("Creature (Entry: %u) already listed as difficulty %u for another entry.", cInfo->DifficultyEntry[diff], diff2 + 1);
511 continue;
514 if (hasDifficultyEntries[diff2].find(cInfo->DifficultyEntry[diff]) != hasDifficultyEntries[diff2].end())
516 sLog.outErrorDb("Creature (Entry: %u) have `difficulty_entry_%u`=%u but creature entry %u have difficulty %u entry also.",
517 i, diff + 1, cInfo->DifficultyEntry[diff], cInfo->DifficultyEntry[diff], diff2 + 1);
518 continue;
520 ok2 = true;
522 if (!ok2)
523 continue;
525 if (cInfo->unit_class != difficultyInfo->unit_class)
527 sLog.outErrorDb("Creature (Entry: %u, class %u) has different `unit_class` in difficulty %u mode (Entry: %u, class %u).",
528 i, cInfo->unit_class, diff + 1, cInfo->DifficultyEntry[diff], difficultyInfo->unit_class);
529 continue;
532 if (cInfo->npcflag != difficultyInfo->npcflag)
534 sLog.outErrorDb("Creature (Entry: %u) has different `npcflag` in difficulty %u mode (Entry: %u).", i, diff + 1, cInfo->DifficultyEntry[diff]);
535 continue;
538 if (cInfo->trainer_class != difficultyInfo->trainer_class)
540 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_class` in difficulty %u mode (Entry: %u).", i, diff + 1, cInfo->DifficultyEntry[diff]);
541 continue;
544 if (cInfo->trainer_race != difficultyInfo->trainer_race)
546 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_race` in difficulty %u mode (Entry: %u).", i, diff + 1, cInfo->DifficultyEntry[diff]);
547 continue;
550 if (cInfo->trainer_type != difficultyInfo->trainer_type)
552 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_type` in difficulty %u mode (Entry: %u).", i, diff + 1, cInfo->DifficultyEntry[diff]);
553 continue;
556 if (cInfo->trainer_spell != difficultyInfo->trainer_spell)
558 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_spell` in difficulty %u mode (Entry: %u).", i, diff + 1, cInfo->DifficultyEntry[diff]);
559 continue;
562 if (difficultyInfo->AIName && *difficultyInfo->AIName)
564 sLog.outErrorDb("Difficulty %u mode creature (Entry: %u) has `AIName`, but in any case will used difficulty 0 mode creature (Entry: %u) AIName.",
565 diff, cInfo->DifficultyEntry[diff], i);
566 continue;
569 if (difficultyInfo->ScriptID)
571 sLog.outErrorDb("Difficulty %u mode creature (Entry: %u) has `ScriptName`, but in any case will used difficulty 0 mode creature (Entry: %u) ScriptName.",
572 diff, cInfo->DifficultyEntry[diff], i);
573 continue;
576 hasDifficultyEntries[diff].insert(i);
577 difficultyEntries[diff].insert(cInfo->DifficultyEntry[diff]);
578 ok = true;
580 if (!ok)
581 continue;
583 FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction_A);
584 if (!factionTemplate)
585 sLog.outErrorDb("Creature (Entry: %u) has nonexistent faction_A template (%u)", cInfo->Entry, cInfo->faction_A);
587 factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction_H);
588 if (!factionTemplate)
589 sLog.outErrorDb("Creature (Entry: %u) has nonexistent faction_H template (%u)", cInfo->Entry, cInfo->faction_H);
591 // used later for scale
592 CreatureDisplayInfoEntry const* displayScaleEntry = NULL;
594 if (cInfo->DisplayID_A[0])
596 CreatureDisplayInfoEntry const* displayEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->DisplayID_A[0]);
597 if(!displayEntry)
599 sLog.outErrorDb("Creature (Entry: %u) has nonexistent modelid_A (%u), can crash client", cInfo->Entry, cInfo->DisplayID_A[0]);
600 const_cast<CreatureInfo*>(cInfo)->DisplayID_A[0] = 0;
602 else if(!displayScaleEntry)
603 displayScaleEntry = displayEntry;
605 CreatureModelInfo const* minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_A[0]);
606 if (!minfo)
607 sLog.outErrorDb("Creature (Entry: %u) are using modelid_A (%u), but creature_model_info are missing for this model.", cInfo->Entry, cInfo->DisplayID_A[0]);
610 if (cInfo->DisplayID_A[1])
612 CreatureDisplayInfoEntry const* displayEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->DisplayID_A[1]);
613 if(!displayEntry)
615 sLog.outErrorDb("Creature (Entry: %u) has nonexistent modelid_A2 (%u), can crash client", cInfo->Entry, cInfo->DisplayID_A[1]);
616 const_cast<CreatureInfo*>(cInfo)->DisplayID_A[1] = 0;
618 else if(!displayScaleEntry)
619 displayScaleEntry = displayEntry;
621 CreatureModelInfo const* minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_A[1]);
622 if (!minfo)
623 sLog.outErrorDb("Creature (Entry: %u) are using modelid_A2 (%u), but creature_model_info are missing for this model.", cInfo->Entry, cInfo->DisplayID_A[1]);
626 if (cInfo->DisplayID_H[0])
628 CreatureDisplayInfoEntry const* displayEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->DisplayID_H[0]);
629 if(!displayEntry)
631 sLog.outErrorDb("Creature (Entry: %u) has nonexistent modelid_H (%u), can crash client", cInfo->Entry, cInfo->DisplayID_H[0]);
632 const_cast<CreatureInfo*>(cInfo)->DisplayID_H[0] = 0;
634 else if(!displayScaleEntry)
635 displayScaleEntry = displayEntry;
637 CreatureModelInfo const* minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_H[0]);
638 if (!minfo)
639 sLog.outErrorDb("Creature (Entry: %u) are using modelid_H (%u), but creature_model_info are missing for this model.", cInfo->Entry, cInfo->DisplayID_H[0]);
642 if (cInfo->DisplayID_H[1])
644 CreatureDisplayInfoEntry const* displayEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->DisplayID_H[1]);
645 if(!displayEntry)
647 sLog.outErrorDb("Creature (Entry: %u) has nonexistent modelid_H2 (%u), can crash client", cInfo->Entry, cInfo->DisplayID_H[1]);
648 const_cast<CreatureInfo*>(cInfo)->DisplayID_H[1] = 0;
650 else if(!displayScaleEntry)
651 displayScaleEntry = displayEntry;
653 CreatureModelInfo const* minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_H[1]);
654 if (!minfo)
655 sLog.outErrorDb("Creature (Entry: %u) are using modelid_H2 (%u), but creature_model_info are missing for this model.", cInfo->Entry, cInfo->DisplayID_H[1]);
658 if (!displayScaleEntry)
659 sLog.outErrorDb("Creature (Entry: %u) has nonexistent modelid in modelid_A/modelid_A2/modelid_H/modelid_A2", cInfo->Entry);
661 for(int k = 0; k < MAX_KILL_CREDIT; ++k)
663 if(cInfo->KillCredit[k])
665 if(!GetCreatureTemplate(cInfo->KillCredit[k]))
667 sLog.outErrorDb("Creature (Entry: %u) has nonexistent creature entry in `KillCredit%d` (%u)",cInfo->Entry,k+1,cInfo->KillCredit[k]);
668 const_cast<CreatureInfo*>(cInfo)->KillCredit[k] = 0;
673 // use below code for 0-checks for unit_class
674 if (/*!cInfo->unit_class ||*/cInfo->unit_class && ((1 << (cInfo->unit_class-1)) & CLASSMASK_ALL_CREATURES) == 0)
675 sLog.outErrorDb("Creature (Entry: %u) has invalid unit_class(%u) for creature_template", cInfo->Entry, cInfo->unit_class);
677 if(cInfo->dmgschool >= MAX_SPELL_SCHOOL)
679 sLog.outErrorDb("Creature (Entry: %u) has invalid spell school value (%u) in `dmgschool`",cInfo->Entry,cInfo->dmgschool);
680 const_cast<CreatureInfo*>(cInfo)->dmgschool = SPELL_SCHOOL_NORMAL;
683 if(cInfo->baseattacktime == 0)
684 const_cast<CreatureInfo*>(cInfo)->baseattacktime = BASE_ATTACK_TIME;
686 if(cInfo->rangeattacktime == 0)
687 const_cast<CreatureInfo*>(cInfo)->rangeattacktime = BASE_ATTACK_TIME;
689 if(cInfo->npcflag & UNIT_NPC_FLAG_SPELLCLICK)
691 sLog.outErrorDb("Creature (Entry: %u) has dynamic flag UNIT_NPC_FLAG_SPELLCLICK (%u) set, it expect to be set by code base at `npc_spellclick_spells` content.",cInfo->Entry,UNIT_NPC_FLAG_SPELLCLICK);
692 const_cast<CreatureInfo*>(cInfo)->npcflag &= ~UNIT_NPC_FLAG_SPELLCLICK;
695 if((cInfo->npcflag & UNIT_NPC_FLAG_TRAINER) && cInfo->trainer_type >= MAX_TRAINER_TYPE)
696 sLog.outErrorDb("Creature (Entry: %u) has wrong trainer type %u",cInfo->Entry,cInfo->trainer_type);
698 if(cInfo->type && !sCreatureTypeStore.LookupEntry(cInfo->type))
700 sLog.outErrorDb("Creature (Entry: %u) has invalid creature type (%u) in `type`",cInfo->Entry,cInfo->type);
701 const_cast<CreatureInfo*>(cInfo)->type = CREATURE_TYPE_HUMANOID;
704 // must exist or used hidden but used in data horse case
705 if(cInfo->family && !sCreatureFamilyStore.LookupEntry(cInfo->family) && cInfo->family != CREATURE_FAMILY_HORSE_CUSTOM )
707 sLog.outErrorDb("Creature (Entry: %u) has invalid creature family (%u) in `family`",cInfo->Entry,cInfo->family);
708 const_cast<CreatureInfo*>(cInfo)->family = 0;
711 if(cInfo->InhabitType <= 0 || cInfo->InhabitType > INHABIT_ANYWHERE)
713 sLog.outErrorDb("Creature (Entry: %u) has wrong value (%u) in `InhabitType`, creature will not correctly walk/swim/fly",cInfo->Entry,cInfo->InhabitType);
714 const_cast<CreatureInfo*>(cInfo)->InhabitType = INHABIT_ANYWHERE;
717 if(cInfo->PetSpellDataId)
719 CreatureSpellDataEntry const* spellDataId = sCreatureSpellDataStore.LookupEntry(cInfo->PetSpellDataId);
720 if(!spellDataId)
721 sLog.outErrorDb("Creature (Entry: %u) has non-existing PetSpellDataId (%u)", cInfo->Entry, cInfo->PetSpellDataId);
724 for(int j = 0; j < CREATURE_MAX_SPELLS; ++j)
726 if(cInfo->spells[j] && !sSpellStore.LookupEntry(cInfo->spells[j]))
728 sLog.outErrorDb("Creature (Entry: %u) has non-existing Spell%d (%u), set to 0", cInfo->Entry, j+1,cInfo->spells[j]);
729 const_cast<CreatureInfo*>(cInfo)->spells[j] = 0;
733 if(cInfo->MovementType >= MAX_DB_MOTION_TYPE)
735 sLog.outErrorDb("Creature (Entry: %u) has wrong movement generator type (%u), ignore and set to IDLE.",cInfo->Entry,cInfo->MovementType);
736 const_cast<CreatureInfo*>(cInfo)->MovementType = IDLE_MOTION_TYPE;
739 if(cInfo->equipmentId > 0) // 0 no equipment
741 if(!GetEquipmentInfo(cInfo->equipmentId))
743 sLog.outErrorDb("Table `creature_template` have creature (Entry: %u) with equipment_id %u not found in table `creature_equip_template`, set to no equipment.", cInfo->Entry, cInfo->equipmentId);
744 const_cast<CreatureInfo*>(cInfo)->equipmentId = 0;
748 /// if not set custom creature scale then load scale from CreatureDisplayInfo.dbc
749 if(cInfo->scale <= 0.0f)
751 if(displayScaleEntry)
752 const_cast<CreatureInfo*>(cInfo)->scale = displayScaleEntry->scale;
753 else
754 const_cast<CreatureInfo*>(cInfo)->scale = 1.0f;
759 void ObjectMgr::ConvertCreatureAddonAuras(CreatureDataAddon* addon, char const* table, char const* guidEntryStr)
761 // Now add the auras, format "spellid effectindex spellid effectindex..."
762 char *p,*s;
763 std::vector<int> val;
764 s=p=(char*)reinterpret_cast<char const*>(addon->auras);
765 if(p)
767 while (p[0]!=0)
769 ++p;
770 if (p[0]==' ')
772 val.push_back(atoi(s));
773 s=++p;
776 if (p!=s)
777 val.push_back(atoi(s));
779 // free char* loaded memory
780 delete[] (char*)reinterpret_cast<char const*>(addon->auras);
782 // wrong list
783 if (val.size()%2)
785 addon->auras = NULL;
786 sLog.outErrorDb("Creature (%s: %u) has wrong `auras` data in `%s`.",guidEntryStr,addon->guidOrEntry,table);
787 return;
791 // empty list
792 if(val.empty())
794 addon->auras = NULL;
795 return;
798 // replace by new structures array
799 const_cast<CreatureDataAddonAura*&>(addon->auras) = new CreatureDataAddonAura[val.size()/2+1];
801 uint32 i=0;
802 for(uint32 j = 0; j < val.size()/2; ++j)
804 CreatureDataAddonAura& cAura = const_cast<CreatureDataAddonAura&>(addon->auras[i]);
805 cAura.spell_id = uint32(val[2*j+0]);
806 cAura.effect_idx = SpellEffectIndex(val[2*j+1]);
807 if (cAura.effect_idx >= MAX_EFFECT_INDEX)
809 sLog.outErrorDb("Creature (%s: %u) has wrong effect %u for spell %u in `auras` field in `%s`.",guidEntryStr,addon->guidOrEntry,cAura.effect_idx,cAura.spell_id,table);
810 continue;
812 SpellEntry const *AdditionalSpellInfo = sSpellStore.LookupEntry(cAura.spell_id);
813 if (!AdditionalSpellInfo)
815 sLog.outErrorDb("Creature (%s: %u) has wrong spell %u defined in `auras` field in `%s`.",guidEntryStr,addon->guidOrEntry,cAura.spell_id,table);
816 continue;
819 if (!AdditionalSpellInfo->Effect[cAura.effect_idx] || !AdditionalSpellInfo->EffectApplyAuraName[cAura.effect_idx])
821 sLog.outErrorDb("Creature (%s: %u) has not aura effect %u of spell %u defined in `auras` field in `%s`.",guidEntryStr,addon->guidOrEntry,cAura.effect_idx,cAura.spell_id,table);
822 continue;
825 ++i;
828 // fill terminator element (after last added)
829 CreatureDataAddonAura& endAura = const_cast<CreatureDataAddonAura&>(addon->auras[i]);
830 endAura.spell_id = 0;
831 endAura.effect_idx = EFFECT_INDEX_0;
834 void ObjectMgr::LoadCreatureAddons(SQLStorage& creatureaddons, char const* entryName, char const* comment)
836 creatureaddons.Load();
838 sLog.outString(">> Loaded %u %s", creatureaddons.RecordCount, comment);
839 sLog.outString();
841 // check data correctness and convert 'auras'
842 for(uint32 i = 1; i < creatureaddons.MaxEntry; ++i)
844 CreatureDataAddon const* addon = creatureaddons.LookupEntry<CreatureDataAddon>(i);
845 if(!addon)
846 continue;
848 if (addon->mount)
850 if (!sCreatureDisplayInfoStore.LookupEntry(addon->mount))
852 sLog.outErrorDb("Creature (%s %u) have invalid displayInfoId for mount (%u) defined in `%s`.", entryName, addon->guidOrEntry, addon->mount, creatureaddons.GetTableName());
853 const_cast<CreatureDataAddon*>(addon)->mount = 0;
857 if (!sEmotesStore.LookupEntry(addon->emote))
859 sLog.outErrorDb("Creature (%s %u) have invalid emote (%u) defined in `%s`.", entryName, addon->guidOrEntry, addon->emote, creatureaddons.GetTableName());
860 const_cast<CreatureDataAddon*>(addon)->emote = 0;
863 if (addon->splineFlags & (SPLINEFLAG_TRAJECTORY|SPLINEFLAG_UNKNOWN3))
865 sLog.outErrorDb("Creature (%s %u) spline flags mask defined in `%s` include forbidden flags (" I32FMT ") that can crash client, cleanup at load.", entryName, addon->guidOrEntry, creatureaddons.GetTableName(), (SPLINEFLAG_TRAJECTORY|SPLINEFLAG_UNKNOWN3));
866 const_cast<CreatureDataAddon*>(addon)->splineFlags &= ~(SPLINEFLAG_TRAJECTORY|SPLINEFLAG_UNKNOWN3);
869 ConvertCreatureAddonAuras(const_cast<CreatureDataAddon*>(addon), creatureaddons.GetTableName(), entryName);
873 void ObjectMgr::LoadCreatureAddons()
875 LoadCreatureAddons(sCreatureInfoAddonStorage,"Entry","creature template addons");
877 // check entry ids
878 for(uint32 i = 1; i < sCreatureInfoAddonStorage.MaxEntry; ++i)
879 if(CreatureDataAddon const* addon = sCreatureInfoAddonStorage.LookupEntry<CreatureDataAddon>(i))
880 if(!sCreatureStorage.LookupEntry<CreatureInfo>(addon->guidOrEntry))
881 sLog.outErrorDb("Creature (Entry: %u) does not exist but has a record in `%s`",addon->guidOrEntry, sCreatureInfoAddonStorage.GetTableName());
883 LoadCreatureAddons(sCreatureDataAddonStorage,"GUID","creature addons");
885 // check entry ids
886 for(uint32 i = 1; i < sCreatureDataAddonStorage.MaxEntry; ++i)
887 if(CreatureDataAddon const* addon = sCreatureDataAddonStorage.LookupEntry<CreatureDataAddon>(i))
888 if(mCreatureDataMap.find(addon->guidOrEntry)==mCreatureDataMap.end())
889 sLog.outErrorDb("Creature (GUID: %u) does not exist but has a record in `creature_addon`",addon->guidOrEntry);
892 EquipmentInfo const* ObjectMgr::GetEquipmentInfo(uint32 entry)
894 return sEquipmentStorage.LookupEntry<EquipmentInfo>(entry);
897 void ObjectMgr::LoadEquipmentTemplates()
899 sEquipmentStorage.Load();
901 for(uint32 i=0; i < sEquipmentStorage.MaxEntry; ++i)
903 EquipmentInfo const* eqInfo = sEquipmentStorage.LookupEntry<EquipmentInfo>(i);
905 if (!eqInfo)
906 continue;
908 for(uint8 j = 0; j < 3; ++j)
910 if (!eqInfo->equipentry[j])
911 continue;
913 ItemEntry const *dbcitem = sItemStore.LookupEntry(eqInfo->equipentry[j]);
915 if (!dbcitem)
917 sLog.outErrorDb("Unknown item (entry=%u) in creature_equip_template.equipentry%u for entry = %u, forced to 0.", eqInfo->equipentry[j], j+1, i);
918 const_cast<EquipmentInfo*>(eqInfo)->equipentry[j] = 0;
919 continue;
922 if (dbcitem->InventoryType != INVTYPE_WEAPON &&
923 dbcitem->InventoryType != INVTYPE_SHIELD &&
924 dbcitem->InventoryType != INVTYPE_RANGED &&
925 dbcitem->InventoryType != INVTYPE_2HWEAPON &&
926 dbcitem->InventoryType != INVTYPE_WEAPONMAINHAND &&
927 dbcitem->InventoryType != INVTYPE_WEAPONOFFHAND &&
928 dbcitem->InventoryType != INVTYPE_HOLDABLE &&
929 dbcitem->InventoryType != INVTYPE_THROWN &&
930 dbcitem->InventoryType != INVTYPE_RANGEDRIGHT)
932 sLog.outErrorDb("Item (entry=%u) in creature_equip_template.equipentry%u for entry = %u is not equipable in a hand, forced to 0.", eqInfo->equipentry[j], j+1, i);
933 const_cast<EquipmentInfo*>(eqInfo)->equipentry[j] = 0;
937 sLog.outString( ">> Loaded %u equipment template", sEquipmentStorage.RecordCount );
938 sLog.outString();
941 CreatureModelInfo const* ObjectMgr::GetCreatureModelInfo(uint32 modelid)
943 return sCreatureModelStorage.LookupEntry<CreatureModelInfo>(modelid);
946 uint32 ObjectMgr::ChooseDisplayId(uint32 team, const CreatureInfo *cinfo, const CreatureData *data /*= NULL*/)
948 // Load creature model (display id)
949 if (data && data->displayid)
950 return data->displayid;
952 // use defaults from the template
953 uint32 display_id;
955 // DisplayID_A is used if no team is given
956 if (team == HORDE)
958 if(cinfo->DisplayID_H[0])
959 display_id = cinfo->DisplayID_H[1] ? cinfo->DisplayID_H[urand(0,1)] : cinfo->DisplayID_H[0];
960 else
961 display_id = cinfo->DisplayID_H[1];
963 if(!display_id)
964 display_id = cinfo->DisplayID_A[0] ? cinfo->DisplayID_A[0] : cinfo->DisplayID_A[1];
966 else
968 if(cinfo->DisplayID_A[0])
969 display_id = cinfo->DisplayID_A[1] ? cinfo->DisplayID_A[urand(0,1)] : cinfo->DisplayID_A[0];
970 else
971 display_id = cinfo->DisplayID_A[1];
973 if(!display_id)
974 display_id = cinfo->DisplayID_H[0] ? cinfo->DisplayID_H[0] : cinfo->DisplayID_H[1];
977 return display_id;
980 CreatureModelInfo const* ObjectMgr::GetCreatureModelRandomGender(uint32 display_id)
982 CreatureModelInfo const *minfo = GetCreatureModelInfo(display_id);
983 if(!minfo)
984 return NULL;
986 // If a model for another gender exists, 50% chance to use it
987 if(minfo->modelid_other_gender != 0 && urand(0,1) == 0)
989 CreatureModelInfo const *minfo_tmp = GetCreatureModelInfo(minfo->modelid_other_gender);
990 if(!minfo_tmp)
992 sLog.outErrorDb("Model (Entry: %u) has modelid_other_gender %u not found in table `creature_model_info`. ", minfo->modelid, minfo->modelid_other_gender);
993 return minfo; // not fatal, just use the previous one
995 else
996 return minfo_tmp;
998 else
999 return minfo;
1002 void ObjectMgr::LoadCreatureModelInfo()
1004 sCreatureModelStorage.Load();
1006 // post processing
1007 for(uint32 i = 1; i < sCreatureModelStorage.MaxEntry; ++i)
1009 CreatureModelInfo const *minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(i);
1010 if (!minfo)
1011 continue;
1013 if (!sCreatureDisplayInfoStore.LookupEntry(minfo->modelid))
1014 sLog.outErrorDb("Table `creature_model_info` has model for not existed display id (%u).", minfo->modelid);
1016 if (minfo->gender >= MAX_GENDER)
1018 sLog.outErrorDb("Table `creature_model_info` has wrong gender (%u) for display id (%u).", uint32(minfo->gender), minfo->modelid);
1019 const_cast<CreatureModelInfo*>(minfo)->gender = GENDER_MALE;
1022 if (minfo->modelid_other_gender && !sCreatureDisplayInfoStore.LookupEntry(minfo->modelid_other_gender))
1024 sLog.outErrorDb("Table `creature_model_info` has not existed alt.gender model (%u) for existed display id (%u).", minfo->modelid_other_gender, minfo->modelid);
1025 const_cast<CreatureModelInfo*>(minfo)->modelid_other_gender = 0;
1029 sLog.outString( ">> Loaded %u creature model based info", sCreatureModelStorage.RecordCount );
1030 sLog.outString();
1033 void ObjectMgr::LoadCreatures()
1035 uint32 count = 0;
1036 // 0 1 2 3
1037 QueryResult *result = WorldDatabase.Query("SELECT creature.guid, id, map, modelid,"
1038 // 4 5 6 7 8 9 10 11
1039 "equipment_id, position_x, position_y, position_z, orientation, spawntimesecs, spawndist, currentwaypoint,"
1040 // 12 13 14 15 16 17 18 19
1041 "curhealth, curmana, DeathState, MovementType, spawnMask, phaseMask, event, pool_entry "
1042 "FROM creature LEFT OUTER JOIN game_event_creature ON creature.guid = game_event_creature.guid "
1043 "LEFT OUTER JOIN pool_creature ON creature.guid = pool_creature.guid");
1045 if(!result)
1047 barGoLink bar(1);
1049 bar.step();
1051 sLog.outString();
1052 sLog.outErrorDb(">> Loaded 0 creature. DB table `creature` is empty.");
1053 return;
1056 // build single time for check creature data
1057 std::set<uint32> difficultyCreatures[MAX_DIFFICULTY - 1];
1058 for (uint32 i = 0; i < sCreatureStorage.MaxEntry; ++i)
1059 if (CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i))
1060 for (uint32 diff = 0; diff < MAX_DIFFICULTY - 1; ++diff)
1061 if (cInfo->DifficultyEntry[diff])
1062 difficultyCreatures[diff].insert(cInfo->DifficultyEntry[diff]);
1064 // build single time for check spawnmask
1065 std::map<uint32,uint32> spawnMasks;
1066 for(uint32 i = 0; i < sMapStore.GetNumRows(); ++i)
1067 if(sMapStore.LookupEntry(i))
1068 for(int k = 0; k < MAX_DIFFICULTY; ++k)
1069 if (GetMapDifficultyData(i,Difficulty(k)))
1070 spawnMasks[i] |= (1 << k);
1072 barGoLink bar((int)result->GetRowCount());
1076 Field *fields = result->Fetch();
1077 bar.step();
1079 uint32 guid = fields[ 0].GetUInt32();
1080 uint32 entry = fields[ 1].GetUInt32();
1082 CreatureInfo const* cInfo = GetCreatureTemplate(entry);
1083 if(!cInfo)
1085 sLog.outErrorDb("Table `creature` has creature (GUID: %u) with non existing creature entry %u, skipped.", guid, entry);
1086 continue;
1089 CreatureData& data = mCreatureDataMap[guid];
1091 data.id = entry;
1092 data.mapid = fields[ 2].GetUInt32();
1093 data.displayid = fields[ 3].GetUInt32();
1094 data.equipmentId = fields[ 4].GetUInt32();
1095 data.posX = fields[ 5].GetFloat();
1096 data.posY = fields[ 6].GetFloat();
1097 data.posZ = fields[ 7].GetFloat();
1098 data.orientation = fields[ 8].GetFloat();
1099 data.spawntimesecs = fields[ 9].GetUInt32();
1100 data.spawndist = fields[10].GetFloat();
1101 data.currentwaypoint= fields[11].GetUInt32();
1102 data.curhealth = fields[12].GetUInt32();
1103 data.curmana = fields[13].GetUInt32();
1104 data.is_dead = fields[14].GetBool();
1105 data.movementType = fields[15].GetUInt8();
1106 data.spawnMask = fields[16].GetUInt8();
1107 data.phaseMask = fields[17].GetUInt16();
1108 int16 gameEvent = fields[18].GetInt16();
1109 int16 PoolId = fields[19].GetInt16();
1111 MapEntry const* mapEntry = sMapStore.LookupEntry(data.mapid);
1112 if(!mapEntry)
1114 sLog.outErrorDb("Table `creature` have creature (GUID: %u) that spawned at not existed map (Id: %u), skipped.",guid, data.mapid );
1115 continue;
1118 if (data.spawnMask & ~spawnMasks[data.mapid])
1119 sLog.outErrorDb("Table `creature` have creature (GUID: %u) that have wrong spawn mask %u including not supported difficulty modes for map (Id: %u).",guid, data.spawnMask, data.mapid );
1121 bool ok = true;
1122 for (uint32 diff = 0; diff < MAX_DIFFICULTY - 1 && ok; ++diff)
1124 if (difficultyCreatures[diff].find(data.id) != difficultyCreatures[diff].end())
1126 sLog.outErrorDb("Table `creature` have creature (GUID: %u) that listed as difficulty %u template (entry: %u) in `creature_template`, skipped.",
1127 guid, diff + 1, data.id );
1128 ok = false;
1131 if (!ok)
1132 continue;
1134 if(data.equipmentId > 0) // -1 no equipment, 0 use default
1136 if(!GetEquipmentInfo(data.equipmentId))
1138 sLog.outErrorDb("Table `creature` have creature (Entry: %u) with equipment_id %u not found in table `creature_equip_template`, set to no equipment.", data.id, data.equipmentId);
1139 data.equipmentId = -1;
1143 if(cInfo->RegenHealth && data.curhealth < cInfo->minhealth)
1145 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `creature_template`.`RegenHealth`=1 and low current health (%u), `creature_template`.`minhealth`=%u.",guid,data.id,data.curhealth, cInfo->minhealth );
1146 data.curhealth = cInfo->minhealth;
1149 if(cInfo->flags_extra & CREATURE_FLAG_EXTRA_INSTANCE_BIND)
1151 if(!mapEntry || !mapEntry->IsDungeon())
1152 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `creature_template`.`flags_extra` including CREATURE_FLAG_EXTRA_INSTANCE_BIND but creature are not in instance.",guid,data.id);
1155 if(data.curmana < cInfo->minmana)
1157 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with low current mana (%u), `creature_template`.`minmana`=%u.",guid,data.id,data.curmana, cInfo->minmana );
1158 data.curmana = cInfo->minmana;
1161 if(data.spawndist < 0.0f)
1163 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `spawndist`< 0, set to 0.",guid,data.id );
1164 data.spawndist = 0.0f;
1166 else if(data.movementType == RANDOM_MOTION_TYPE)
1168 if(data.spawndist == 0.0f)
1170 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `MovementType`=1 (random movement) but with `spawndist`=0, replace by idle movement type (0).",guid,data.id );
1171 data.movementType = IDLE_MOTION_TYPE;
1174 else if(data.movementType == IDLE_MOTION_TYPE)
1176 if(data.spawndist != 0.0f)
1178 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `MovementType`=0 (idle) have `spawndist`<>0, set to 0.",guid,data.id );
1179 data.spawndist = 0.0f;
1183 if(data.phaseMask==0)
1185 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `phaseMask`=0 (not visible for anyone), set to 1.",guid,data.id );
1186 data.phaseMask = 1;
1189 if (gameEvent==0 && PoolId==0) // if not this is to be managed by GameEvent System or Pool system
1190 AddCreatureToGrid(guid, &data);
1192 ++count;
1194 } while (result->NextRow());
1196 delete result;
1198 sLog.outString();
1199 sLog.outString( ">> Loaded %lu creatures", (unsigned long)mCreatureDataMap.size() );
1202 void ObjectMgr::AddCreatureToGrid(uint32 guid, CreatureData const* data)
1204 uint8 mask = data->spawnMask;
1205 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1207 if(mask & 1)
1209 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1210 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1212 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1213 cell_guids.creatures.insert(guid);
1218 void ObjectMgr::RemoveCreatureFromGrid(uint32 guid, CreatureData const* data)
1220 uint8 mask = data->spawnMask;
1221 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1223 if(mask & 1)
1225 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1226 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1228 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1229 cell_guids.creatures.erase(guid);
1234 void ObjectMgr::LoadGameobjects()
1236 uint32 count = 0;
1238 // 0 1 2 3 4 5 6
1239 QueryResult *result = WorldDatabase.Query("SELECT gameobject.guid, id, map, position_x, position_y, position_z, orientation,"
1240 // 7 8 9 10 11 12 13 14 15 16 17
1241 "rotation0, rotation1, rotation2, rotation3, spawntimesecs, animprogress, state, spawnMask, phaseMask, event, pool_entry "
1242 "FROM gameobject LEFT OUTER JOIN game_event_gameobject ON gameobject.guid = game_event_gameobject.guid "
1243 "LEFT OUTER JOIN pool_gameobject ON gameobject.guid = pool_gameobject.guid");
1245 if(!result)
1247 barGoLink bar(1);
1249 bar.step();
1251 sLog.outString();
1252 sLog.outErrorDb(">> Loaded 0 gameobjects. DB table `gameobject` is empty.");
1253 return;
1256 // build single time for check spawnmask
1257 std::map<uint32,uint32> spawnMasks;
1258 for(uint32 i = 0; i < sMapStore.GetNumRows(); ++i)
1259 if(sMapStore.LookupEntry(i))
1260 for(int k = 0; k < MAX_DIFFICULTY; ++k)
1261 if (GetMapDifficultyData(i,Difficulty(k)))
1262 spawnMasks[i] |= (1 << k);
1264 barGoLink bar((int)result->GetRowCount());
1268 Field *fields = result->Fetch();
1269 bar.step();
1271 uint32 guid = fields[ 0].GetUInt32();
1272 uint32 entry = fields[ 1].GetUInt32();
1274 GameObjectInfo const* gInfo = GetGameObjectInfo(entry);
1275 if (!gInfo)
1277 sLog.outErrorDb("Table `gameobject` has gameobject (GUID: %u) with non existing gameobject entry %u, skipped.", guid, entry);
1278 continue;
1281 if(!gInfo->displayId)
1283 switch(gInfo->type)
1285 // can be invisible always and then not req. display id in like case
1286 case GAMEOBJECT_TYPE_TRAP:
1287 case GAMEOBJECT_TYPE_SPELL_FOCUS:
1288 break;
1289 default:
1290 sLog.outErrorDb("Gameobject (GUID: %u Entry %u GoType: %u) have displayId == 0 and then will always invisible in game.", guid, entry, gInfo->type);
1291 break;
1294 else if (!sGameObjectDisplayInfoStore.LookupEntry(gInfo->displayId))
1296 sLog.outErrorDb("Gameobject (GUID: %u Entry %u GoType: %u) have invalid displayId (%u), not loaded.", guid, entry, gInfo->type, gInfo->displayId);
1297 continue;
1300 GameObjectData& data = mGameObjectDataMap[guid];
1302 data.id = entry;
1303 data.mapid = fields[ 2].GetUInt32();
1304 data.posX = fields[ 3].GetFloat();
1305 data.posY = fields[ 4].GetFloat();
1306 data.posZ = fields[ 5].GetFloat();
1307 data.orientation = fields[ 6].GetFloat();
1308 data.rotation0 = fields[ 7].GetFloat();
1309 data.rotation1 = fields[ 8].GetFloat();
1310 data.rotation2 = fields[ 9].GetFloat();
1311 data.rotation3 = fields[10].GetFloat();
1312 data.spawntimesecs = fields[11].GetInt32();
1314 MapEntry const* mapEntry = sMapStore.LookupEntry(data.mapid);
1315 if(!mapEntry)
1317 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) that spawned at not existed map (Id: %u), skip", guid, data.id, data.mapid);
1318 continue;
1321 if (data.spawnMask & ~spawnMasks[data.mapid])
1322 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) that have wrong spawn mask %u including not supported difficulty modes for map (Id: %u), skip", guid, data.id, data.spawnMask, data.mapid);
1324 if (data.spawntimesecs == 0 && gInfo->IsDespawnAtAction())
1326 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with `spawntimesecs` (0) value, but gameobejct marked as despawnable at action.", guid, data.id);
1329 data.animprogress = fields[12].GetUInt32();
1331 uint32 go_state = fields[13].GetUInt32();
1332 if (go_state >= MAX_GO_STATE)
1334 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with invalid `state` (%u) value, skip", guid, data.id, go_state);
1335 continue;
1337 data.go_state = GOState(go_state);
1339 data.spawnMask = fields[14].GetUInt8();
1340 data.phaseMask = fields[15].GetUInt16();
1341 int16 gameEvent = fields[16].GetInt16();
1342 int16 PoolId = fields[17].GetInt16();
1344 if (data.rotation2 < -1.0f || data.rotation2 > 1.0f)
1346 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with invalid rotation2 (%f) value, skip", guid, data.id, data.rotation2);
1347 continue;
1350 if (data.rotation3 < -1.0f || data.rotation3 > 1.0f)
1352 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with invalid rotation3 (%f) value, skip", guid, data.id, data.rotation3);
1353 continue;
1356 if(!MapManager::IsValidMapCoord(data.mapid, data.posX, data.posY, data.posZ, data.orientation))
1358 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with invalid coordinates, skip", guid, data.id);
1359 continue;
1362 if(data.phaseMask == 0)
1364 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with `phaseMask`=0 (not visible for anyone), set to 1.", guid, data.id);
1365 data.phaseMask = 1;
1368 if (gameEvent == 0 && PoolId == 0) // if not this is to be managed by GameEvent System or Pool system
1369 AddGameobjectToGrid(guid, &data);
1370 ++count;
1372 } while (result->NextRow());
1374 delete result;
1376 sLog.outString();
1377 sLog.outString( ">> Loaded %lu gameobjects", (unsigned long)mGameObjectDataMap.size());
1380 void ObjectMgr::AddGameobjectToGrid(uint32 guid, GameObjectData const* data)
1382 uint8 mask = data->spawnMask;
1383 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1385 if(mask & 1)
1387 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1388 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1390 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1391 cell_guids.gameobjects.insert(guid);
1396 void ObjectMgr::RemoveGameobjectFromGrid(uint32 guid, GameObjectData const* data)
1398 uint8 mask = data->spawnMask;
1399 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1401 if(mask & 1)
1403 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1404 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1406 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1407 cell_guids.gameobjects.erase(guid);
1412 void ObjectMgr::LoadCreatureRespawnTimes()
1414 // remove outdated data
1415 WorldDatabase.DirectExecute("DELETE FROM creature_respawn WHERE respawntime <= UNIX_TIMESTAMP(NOW())");
1417 uint32 count = 0;
1419 QueryResult *result = WorldDatabase.Query("SELECT guid,respawntime,instance FROM creature_respawn");
1421 if(!result)
1423 barGoLink bar(1);
1425 bar.step();
1427 sLog.outString();
1428 sLog.outString(">> Loaded 0 creature respawn time.");
1429 return;
1432 barGoLink bar((int)result->GetRowCount());
1436 Field *fields = result->Fetch();
1437 bar.step();
1439 uint32 loguid = fields[0].GetUInt32();
1440 uint64 respawn_time = fields[1].GetUInt64();
1441 uint32 instance = fields[2].GetUInt32();
1443 mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = time_t(respawn_time);
1445 ++count;
1446 } while (result->NextRow());
1448 delete result;
1450 sLog.outString( ">> Loaded %lu creature respawn times", (unsigned long)mCreatureRespawnTimes.size() );
1451 sLog.outString();
1454 void ObjectMgr::LoadGameobjectRespawnTimes()
1456 // remove outdated data
1457 WorldDatabase.DirectExecute("DELETE FROM gameobject_respawn WHERE respawntime <= UNIX_TIMESTAMP(NOW())");
1459 uint32 count = 0;
1461 QueryResult *result = WorldDatabase.Query("SELECT guid,respawntime,instance FROM gameobject_respawn");
1463 if(!result)
1465 barGoLink bar(1);
1467 bar.step();
1469 sLog.outString();
1470 sLog.outString(">> Loaded 0 gameobject respawn time.");
1471 return;
1474 barGoLink bar((int)result->GetRowCount());
1478 Field *fields = result->Fetch();
1479 bar.step();
1481 uint32 loguid = fields[0].GetUInt32();
1482 uint64 respawn_time = fields[1].GetUInt64();
1483 uint32 instance = fields[2].GetUInt32();
1485 mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = time_t(respawn_time);
1487 ++count;
1488 } while (result->NextRow());
1490 delete result;
1492 sLog.outString( ">> Loaded %lu gameobject respawn times", (unsigned long)mGORespawnTimes.size() );
1493 sLog.outString();
1496 // name must be checked to correctness (if received) before call this function
1497 uint64 ObjectMgr::GetPlayerGUIDByName(std::string name) const
1499 uint64 guid = 0;
1501 CharacterDatabase.escape_string(name);
1503 // Player name safe to sending to DB (checked at login) and this function using
1504 QueryResult *result = CharacterDatabase.PQuery("SELECT guid FROM characters WHERE name = '%s'", name.c_str());
1505 if(result)
1507 guid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
1509 delete result;
1512 return guid;
1515 bool ObjectMgr::GetPlayerNameByGUID(const uint64 &guid, std::string &name) const
1517 // prevent DB access for online player
1518 if(Player* player = GetPlayer(guid))
1520 name = player->GetName();
1521 return true;
1524 QueryResult *result = CharacterDatabase.PQuery("SELECT name FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1526 if(result)
1528 name = (*result)[0].GetCppString();
1529 delete result;
1530 return true;
1533 return false;
1536 uint32 ObjectMgr::GetPlayerTeamByGUID(const uint64 &guid) const
1538 // prevent DB access for online player
1539 if(Player* player = GetPlayer(guid))
1541 return Player::TeamForRace(player->getRace());
1544 QueryResult *result = CharacterDatabase.PQuery("SELECT race FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1546 if(result)
1548 uint8 race = (*result)[0].GetUInt8();
1549 delete result;
1550 return Player::TeamForRace(race);
1553 return 0;
1556 uint32 ObjectMgr::GetPlayerAccountIdByGUID(const uint64 &guid) const
1558 // prevent DB access for online player
1559 if(Player* player = GetPlayer(guid))
1561 return player->GetSession()->GetAccountId();
1564 QueryResult *result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1565 if(result)
1567 uint32 acc = (*result)[0].GetUInt32();
1568 delete result;
1569 return acc;
1572 return 0;
1575 uint32 ObjectMgr::GetPlayerAccountIdByPlayerName(const std::string& name) const
1577 QueryResult *result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'", name.c_str());
1578 if(result)
1580 uint32 acc = (*result)[0].GetUInt32();
1581 delete result;
1582 return acc;
1585 return 0;
1588 void ObjectMgr::LoadItemLocales()
1590 mItemLocaleMap.clear(); // need for reload case
1592 QueryResult *result = WorldDatabase.Query("SELECT entry,name_loc1,description_loc1,name_loc2,description_loc2,name_loc3,description_loc3,name_loc4,description_loc4,name_loc5,description_loc5,name_loc6,description_loc6,name_loc7,description_loc7,name_loc8,description_loc8 FROM locales_item");
1594 if(!result)
1596 barGoLink bar(1);
1598 bar.step();
1600 sLog.outString();
1601 sLog.outString(">> Loaded 0 Item locale strings. DB table `locales_item` is empty.");
1602 return;
1605 barGoLink bar((int)result->GetRowCount());
1609 Field *fields = result->Fetch();
1610 bar.step();
1612 uint32 entry = fields[0].GetUInt32();
1614 ItemLocale& data = mItemLocaleMap[entry];
1616 for(int i = 1; i < MAX_LOCALE; ++i)
1618 std::string str = fields[1+2*(i-1)].GetCppString();
1619 if(!str.empty())
1621 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
1622 if(idx >= 0)
1624 if((int32)data.Name.size() <= idx)
1625 data.Name.resize(idx+1);
1627 data.Name[idx] = str;
1631 str = fields[1+2*(i-1)+1].GetCppString();
1632 if(!str.empty())
1634 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
1635 if(idx >= 0)
1637 if((int32)data.Description.size() <= idx)
1638 data.Description.resize(idx+1);
1640 data.Description[idx] = str;
1644 } while (result->NextRow());
1646 delete result;
1648 sLog.outString();
1649 sLog.outString( ">> Loaded %lu Item locale strings", (unsigned long)mItemLocaleMap.size() );
1652 struct SQLItemLoader : public SQLStorageLoaderBase<SQLItemLoader>
1654 template<class D>
1655 void convert_from_str(uint32 /*field_pos*/, char *src, D &dst)
1657 dst = D(sObjectMgr.GetScriptId(src));
1661 void ObjectMgr::LoadItemPrototypes()
1663 SQLItemLoader loader;
1664 loader.Load(sItemStorage);
1665 sLog.outString( ">> Loaded %u item prototypes", sItemStorage.RecordCount );
1666 sLog.outString();
1668 // check data correctness
1669 for(uint32 i = 1; i < sItemStorage.MaxEntry; ++i)
1671 ItemPrototype const* proto = sItemStorage.LookupEntry<ItemPrototype >(i);
1672 ItemEntry const *dbcitem = sItemStore.LookupEntry(i);
1673 if(!proto)
1675 /* to many errors, and possible not all items really used in game
1676 if (dbcitem)
1677 sLog.outErrorDb("Item (Entry: %u) doesn't exists in DB, but must exist.",i);
1679 continue;
1682 if(dbcitem)
1684 if(proto->Class != dbcitem->Class)
1686 sLog.outErrorDb("Item (Entry: %u) not correct class %u, must be %u (still using DB value).",i,proto->Class,dbcitem->Class);
1687 // It safe let use Class from DB
1689 /* disabled: have some strange wrong cases for Subclass values.
1690 for enable also uncomment Subclass field in ItemEntry structure and in Itemfmt[]
1691 if(proto->SubClass != dbcitem->SubClass)
1693 sLog.outErrorDb("Item (Entry: %u) not correct (Class: %u, Sub: %u) pair, must be (Class: %u, Sub: %u) (still using DB value).",i,proto->Class,proto->SubClass,dbcitem->Class,dbcitem->SubClass);
1694 // It safe let use Subclass from DB
1698 if(proto->Unk0 != dbcitem->Unk0)
1700 sLog.outErrorDb("Item (Entry: %u) not correct %i Unk0, must be %i (still using DB value).",i,proto->Unk0,dbcitem->Unk0);
1701 // It safe let use Unk0 from DB
1704 if(proto->Material != dbcitem->Material)
1706 sLog.outErrorDb("Item (Entry: %u) not correct %i material, must be %i (still using DB value).",i,proto->Material,dbcitem->Material);
1707 // It safe let use Material from DB
1710 if(proto->InventoryType != dbcitem->InventoryType)
1712 sLog.outErrorDb("Item (Entry: %u) not correct %u inventory type, must be %u (still using DB value).",i,proto->InventoryType,dbcitem->InventoryType);
1713 // It safe let use InventoryType from DB
1716 if(proto->DisplayInfoID != dbcitem->DisplayId)
1718 sLog.outErrorDb("Item (Entry: %u) not correct %u display id, must be %u (using it).",i,proto->DisplayInfoID,dbcitem->DisplayId);
1719 const_cast<ItemPrototype*>(proto)->DisplayInfoID = dbcitem->DisplayId;
1721 if(proto->Sheath != dbcitem->Sheath)
1723 sLog.outErrorDb("Item (Entry: %u) not correct %u sheath, must be %u (using it).",i,proto->Sheath,dbcitem->Sheath);
1724 const_cast<ItemPrototype*>(proto)->Sheath = dbcitem->Sheath;
1727 else
1729 sLog.outErrorDb("Item (Entry: %u) not correct (not listed in list of existed items).",i);
1732 if(proto->Class >= MAX_ITEM_CLASS)
1734 sLog.outErrorDb("Item (Entry: %u) has wrong Class value (%u)",i,proto->Class);
1735 const_cast<ItemPrototype*>(proto)->Class = ITEM_CLASS_MISC;
1738 if(proto->SubClass >= MaxItemSubclassValues[proto->Class])
1740 sLog.outErrorDb("Item (Entry: %u) has wrong Subclass value (%u) for class %u",i,proto->SubClass,proto->Class);
1741 const_cast<ItemPrototype*>(proto)->SubClass = 0;// exist for all item classes
1744 if(proto->Quality >= MAX_ITEM_QUALITY)
1746 sLog.outErrorDb("Item (Entry: %u) has wrong Quality value (%u)",i,proto->Quality);
1747 const_cast<ItemPrototype*>(proto)->Quality = ITEM_QUALITY_NORMAL;
1750 if(proto->BuyCount <= 0)
1752 sLog.outErrorDb("Item (Entry: %u) has wrong BuyCount value (%u), set to default(1).",i,proto->BuyCount);
1753 const_cast<ItemPrototype*>(proto)->BuyCount = 1;
1756 if(proto->InventoryType >= MAX_INVTYPE)
1758 sLog.outErrorDb("Item (Entry: %u) has wrong InventoryType value (%u)",i,proto->InventoryType);
1759 const_cast<ItemPrototype*>(proto)->InventoryType = INVTYPE_NON_EQUIP;
1762 if(proto->RequiredSkill >= MAX_SKILL_TYPE)
1764 sLog.outErrorDb("Item (Entry: %u) has wrong RequiredSkill value (%u)",i,proto->RequiredSkill);
1765 const_cast<ItemPrototype*>(proto)->RequiredSkill = 0;
1769 // can be used in equip slot, as page read use in inventory, or spell casting at use
1770 bool req = proto->InventoryType!=INVTYPE_NON_EQUIP || proto->PageText;
1771 if(!req)
1773 for (int j = 0; j < MAX_ITEM_PROTO_SPELLS; ++j)
1775 if(proto->Spells[j].SpellId)
1777 req = true;
1778 break;
1783 if(req)
1785 if(!(proto->AllowableClass & CLASSMASK_ALL_PLAYABLE))
1786 sLog.outErrorDb("Item (Entry: %u) not have in `AllowableClass` any playable classes (%u) and can't be equipped or use.",i,proto->AllowableClass);
1788 if(!(proto->AllowableRace & RACEMASK_ALL_PLAYABLE))
1789 sLog.outErrorDb("Item (Entry: %u) not have in `AllowableRace` any playable races (%u) and can't be equipped or use.",i,proto->AllowableRace);
1793 if(proto->RequiredSpell && !sSpellStore.LookupEntry(proto->RequiredSpell))
1795 sLog.outErrorDb("Item (Entry: %u) have wrong (non-existed) spell in RequiredSpell (%u)",i,proto->RequiredSpell);
1796 const_cast<ItemPrototype*>(proto)->RequiredSpell = 0;
1799 if(proto->RequiredReputationRank >= MAX_REPUTATION_RANK)
1800 sLog.outErrorDb("Item (Entry: %u) has wrong reputation rank in RequiredReputationRank (%u), item can't be used.",i,proto->RequiredReputationRank);
1802 if(proto->RequiredReputationFaction)
1804 if(!sFactionStore.LookupEntry(proto->RequiredReputationFaction))
1806 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) faction in RequiredReputationFaction (%u)",i,proto->RequiredReputationFaction);
1807 const_cast<ItemPrototype*>(proto)->RequiredReputationFaction = 0;
1810 if(proto->RequiredReputationRank == MIN_REPUTATION_RANK)
1811 sLog.outErrorDb("Item (Entry: %u) has min. reputation rank in RequiredReputationRank (0) but RequiredReputationFaction > 0, faction setting is useless.",i);
1813 else if(proto->RequiredReputationRank > MIN_REPUTATION_RANK)
1814 sLog.outErrorDb("Item (Entry: %u) has RequiredReputationFaction ==0 but RequiredReputationRank > 0, rank setting is useless.",i);
1816 if(proto->MaxCount < -1)
1818 sLog.outErrorDb("Item (Entry: %u) has too large negative in maxcount (%i), replace by value (-1) no storing limits.",i,proto->MaxCount);
1819 const_cast<ItemPrototype*>(proto)->MaxCount = -1;
1822 if(proto->Stackable == 0)
1824 sLog.outErrorDb("Item (Entry: %u) has wrong value in stackable (%i), replace by default 1.",i,proto->Stackable);
1825 const_cast<ItemPrototype*>(proto)->Stackable = 1;
1827 else if(proto->Stackable < -1)
1829 sLog.outErrorDb("Item (Entry: %u) has too large negative in stackable (%i), replace by value (-1) no stacking limits.",i,proto->Stackable);
1830 const_cast<ItemPrototype*>(proto)->Stackable = -1;
1832 else if(proto->Stackable > 1000)
1834 sLog.outErrorDb("Item (Entry: %u) has too large value in stackable (%u), replace by hardcoded upper limit (1000).",i,proto->Stackable);
1835 const_cast<ItemPrototype*>(proto)->Stackable = 1000;
1838 if(proto->ContainerSlots > MAX_BAG_SIZE)
1840 sLog.outErrorDb("Item (Entry: %u) has too large value in ContainerSlots (%u), replace by hardcoded limit (%u).",i,proto->ContainerSlots,MAX_BAG_SIZE);
1841 const_cast<ItemPrototype*>(proto)->ContainerSlots = MAX_BAG_SIZE;
1844 if(proto->StatsCount > MAX_ITEM_PROTO_STATS)
1846 sLog.outErrorDb("Item (Entry: %u) has too large value in statscount (%u), replace by hardcoded limit (%u).",i,proto->StatsCount,MAX_ITEM_PROTO_STATS);
1847 const_cast<ItemPrototype*>(proto)->StatsCount = MAX_ITEM_PROTO_STATS;
1850 for (int j = 0; j < MAX_ITEM_PROTO_STATS; ++j)
1852 // for ItemStatValue != 0
1853 if(proto->ItemStat[j].ItemStatValue && proto->ItemStat[j].ItemStatType >= MAX_ITEM_MOD)
1855 sLog.outErrorDb("Item (Entry: %u) has wrong stat_type%d (%u)",i,j+1,proto->ItemStat[j].ItemStatType);
1856 const_cast<ItemPrototype*>(proto)->ItemStat[j].ItemStatType = 0;
1859 switch(proto->ItemStat[j].ItemStatType)
1861 case ITEM_MOD_SPELL_HEALING_DONE:
1862 case ITEM_MOD_SPELL_DAMAGE_DONE:
1863 sLog.outErrorDb("Item (Entry: %u) has deprecated stat_type%d (%u)",i,j+1,proto->ItemStat[j].ItemStatType);
1864 break;
1865 default:
1866 break;
1870 for (int j = 0; j < MAX_ITEM_PROTO_DAMAGES; ++j)
1872 if(proto->Damage[j].DamageType >= MAX_SPELL_SCHOOL)
1874 sLog.outErrorDb("Item (Entry: %u) has wrong dmg_type%d (%u)",i,j+1,proto->Damage[j].DamageType);
1875 const_cast<ItemPrototype*>(proto)->Damage[j].DamageType = 0;
1879 // special format
1880 if((proto->Spells[0].SpellId == SPELL_ID_GENERIC_LEARN) || (proto->Spells[0].SpellId == SPELL_ID_GENERIC_LEARN_PET))
1882 // spell_1
1883 if(proto->Spells[0].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
1885 sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u) for special learning format",i,0+1,proto->Spells[0].SpellTrigger);
1886 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1887 const_cast<ItemPrototype*>(proto)->Spells[0].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1888 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1889 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1892 // spell_2 have learning spell
1893 if(proto->Spells[1].SpellTrigger != ITEM_SPELLTRIGGER_LEARN_SPELL_ID)
1895 sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u) for special learning format.",i,1+1,proto->Spells[1].SpellTrigger);
1896 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1897 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1898 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1900 else if(!proto->Spells[1].SpellId)
1902 sLog.outErrorDb("Item (Entry: %u) not has expected spell in spellid_%d in special learning format.",i,1+1);
1903 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1904 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1906 else
1908 SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[1].SpellId);
1909 if(!spellInfo)
1911 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%u)",i,1+1,proto->Spells[1].SpellId);
1912 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1913 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1914 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1916 // allowed only in special format
1917 else if((proto->Spells[1].SpellId==SPELL_ID_GENERIC_LEARN) || (proto->Spells[1].SpellId==SPELL_ID_GENERIC_LEARN_PET))
1919 sLog.outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%u)",i,1+1,proto->Spells[1].SpellId);
1920 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1921 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1922 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1926 // spell_3*,spell_4*,spell_5* is empty
1927 for (int j = 2; j < MAX_ITEM_PROTO_SPELLS; ++j)
1929 if(proto->Spells[j].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
1931 sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)",i,j+1,proto->Spells[j].SpellTrigger);
1932 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1933 const_cast<ItemPrototype*>(proto)->Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1935 else if(proto->Spells[j].SpellId != 0)
1937 sLog.outErrorDb("Item (Entry: %u) has wrong spell in spellid_%d (%u) for learning special format",i,j+1,proto->Spells[j].SpellId);
1938 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1942 // normal spell list
1943 else
1945 for (int j = 0; j < MAX_ITEM_PROTO_SPELLS; ++j)
1947 if (proto->Spells[j].SpellTrigger >= MAX_ITEM_SPELLTRIGGER || proto->Spells[j].SpellTrigger == ITEM_SPELLTRIGGER_LEARN_SPELL_ID)
1949 sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)",i,j+1,proto->Spells[j].SpellTrigger);
1950 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1951 const_cast<ItemPrototype*>(proto)->Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1953 // on hit can be sued only at weapon
1954 else if (proto->Spells[j].SpellTrigger == ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
1956 if(proto->Class != ITEM_CLASS_WEAPON)
1957 sLog.outErrorDb("Item (Entry: %u) isn't weapon (Class: %u) but has on hit spelltrigger_%d (%u), it will not triggered.",i,proto->Class,j+1,proto->Spells[j].SpellTrigger);
1960 if(proto->Spells[j].SpellId)
1962 SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[j].SpellId);
1963 if(!spellInfo)
1965 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%u)",i,j+1,proto->Spells[j].SpellId);
1966 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1968 // allowed only in special format
1969 else if((proto->Spells[j].SpellId==SPELL_ID_GENERIC_LEARN) || (proto->Spells[j].SpellId==SPELL_ID_GENERIC_LEARN_PET))
1971 sLog.outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%u)",i,j+1,proto->Spells[j].SpellId);
1972 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1978 if(proto->Bonding >= MAX_BIND_TYPE)
1979 sLog.outErrorDb("Item (Entry: %u) has wrong Bonding value (%u)",i,proto->Bonding);
1981 if(proto->PageText && !sPageTextStore.LookupEntry<PageText>(proto->PageText))
1982 sLog.outErrorDb("Item (Entry: %u) has non existing first page (Id:%u)", i,proto->PageText);
1984 if(proto->LockID && !sLockStore.LookupEntry(proto->LockID))
1985 sLog.outErrorDb("Item (Entry: %u) has wrong LockID (%u)",i,proto->LockID);
1987 if(proto->Sheath >= MAX_SHEATHETYPE)
1989 sLog.outErrorDb("Item (Entry: %u) has wrong Sheath (%u)",i,proto->Sheath);
1990 const_cast<ItemPrototype*>(proto)->Sheath = SHEATHETYPE_NONE;
1993 if(proto->RandomProperty && !sItemRandomPropertiesStore.LookupEntry(GetItemEnchantMod(proto->RandomProperty)))
1995 sLog.outErrorDb("Item (Entry: %u) has unknown (wrong or not listed in `item_enchantment_template`) RandomProperty (%u)",i,proto->RandomProperty);
1996 const_cast<ItemPrototype*>(proto)->RandomProperty = 0;
1999 if(proto->RandomSuffix && !sItemRandomSuffixStore.LookupEntry(GetItemEnchantMod(proto->RandomSuffix)))
2001 sLog.outErrorDb("Item (Entry: %u) has wrong RandomSuffix (%u)",i,proto->RandomSuffix);
2002 const_cast<ItemPrototype*>(proto)->RandomSuffix = 0;
2005 if(proto->ItemSet && !sItemSetStore.LookupEntry(proto->ItemSet))
2007 sLog.outErrorDb("Item (Entry: %u) have wrong ItemSet (%u)",i,proto->ItemSet);
2008 const_cast<ItemPrototype*>(proto)->ItemSet = 0;
2011 if(proto->Area && !GetAreaEntryByAreaID(proto->Area))
2012 sLog.outErrorDb("Item (Entry: %u) has wrong Area (%u)",i,proto->Area);
2014 if(proto->Map && !sMapStore.LookupEntry(proto->Map))
2015 sLog.outErrorDb("Item (Entry: %u) has wrong Map (%u)",i,proto->Map);
2017 if(proto->BagFamily)
2019 // check bits
2020 for(uint32 j = 0; j < sizeof(proto->BagFamily)*8; ++j)
2022 uint32 mask = 1 << j;
2023 if((proto->BagFamily & mask)==0)
2024 continue;
2026 ItemBagFamilyEntry const* bf = sItemBagFamilyStore.LookupEntry(j+1);
2027 if(!bf)
2029 sLog.outErrorDb("Item (Entry: %u) has bag family bit set not listed in ItemBagFamily.dbc, remove bit",i);
2030 const_cast<ItemPrototype*>(proto)->BagFamily &= ~mask;
2031 continue;
2034 if(BAG_FAMILY_MASK_CURRENCY_TOKENS & mask)
2036 CurrencyTypesEntry const* ctEntry = sCurrencyTypesStore.LookupEntry(proto->ItemId);
2037 if(!ctEntry)
2039 sLog.outErrorDb("Item (Entry: %u) has currency bag family bit set in BagFamily but not listed in CurrencyTypes.dbc, remove bit",i);
2040 const_cast<ItemPrototype*>(proto)->BagFamily &= ~mask;
2046 if(proto->TotemCategory && !sTotemCategoryStore.LookupEntry(proto->TotemCategory))
2047 sLog.outErrorDb("Item (Entry: %u) has wrong TotemCategory (%u)",i,proto->TotemCategory);
2049 for (int j = 0; j < MAX_ITEM_PROTO_SOCKETS; ++j)
2051 if(proto->Socket[j].Color && (proto->Socket[j].Color & SOCKET_COLOR_ALL) != proto->Socket[j].Color)
2053 sLog.outErrorDb("Item (Entry: %u) has wrong socketColor_%d (%u)",i,j+1,proto->Socket[j].Color);
2054 const_cast<ItemPrototype*>(proto)->Socket[j].Color = 0;
2058 if(proto->GemProperties && !sGemPropertiesStore.LookupEntry(proto->GemProperties))
2059 sLog.outErrorDb("Item (Entry: %u) has wrong GemProperties (%u)",i,proto->GemProperties);
2061 if(proto->FoodType >= MAX_PET_DIET)
2063 sLog.outErrorDb("Item (Entry: %u) has wrong FoodType value (%u)",i,proto->FoodType);
2064 const_cast<ItemPrototype*>(proto)->FoodType = 0;
2067 if(proto->ItemLimitCategory && !sItemLimitCategoryStore.LookupEntry(proto->ItemLimitCategory))
2069 sLog.outErrorDb("Item (Entry: %u) has wrong LimitCategory value (%u)",i,proto->ItemLimitCategory);
2070 const_cast<ItemPrototype*>(proto)->ItemLimitCategory = 0;
2073 if(proto->HolidayId && !sHolidaysStore.LookupEntry(proto->HolidayId))
2075 sLog.outErrorDb("Item (Entry: %u) has wrong HolidayId value (%u)", i, proto->HolidayId);
2076 const_cast<ItemPrototype*>(proto)->HolidayId = 0;
2079 if(proto->ExtraFlags)
2081 if (proto->ExtraFlags & ~ITEM_EXTRA_ALL)
2082 sLog.outErrorDb("Item (Entry: %u) has wrong ExtraFlags (%u) with unused bits set",i,proto->ExtraFlags);
2084 if (proto->ExtraFlags & ITEM_EXTRA_NON_CONSUMABLE)
2086 bool can_be_need = false;
2087 for (int j = 0; j < MAX_ITEM_PROTO_SPELLS; ++j)
2089 if(proto->Spells[j].SpellCharges < 0)
2091 can_be_need = true;
2092 break;
2096 if (!can_be_need)
2098 sLog.outErrorDb("Item (Entry: %u) has redundant non-consumable flag in ExtraFlags, item not have negative charges", i);
2099 const_cast<ItemPrototype*>(proto)->ExtraFlags &= ~ITEM_EXTRA_NON_CONSUMABLE;
2103 if (proto->ExtraFlags & ITEM_EXTRA_REAL_TIME_DURATION)
2105 if (proto->Duration == 0)
2107 sLog.outErrorDb("Item (Entry: %u) has redundant real-time duration flag in ExtraFlags, item not have duration", i);
2108 const_cast<ItemPrototype*>(proto)->ExtraFlags &= ~ITEM_EXTRA_REAL_TIME_DURATION;
2114 // check some dbc referenced items (avoid duplicate reports)
2115 std::set<uint32> notFoundOutfit;
2116 for (uint32 i = 1; i < sCharStartOutfitStore.GetNumRows(); ++i)
2118 CharStartOutfitEntry const* entry = sCharStartOutfitStore.LookupEntry(i);
2119 if (!entry)
2120 continue;
2122 for(int j = 0; j < MAX_OUTFIT_ITEMS; ++j)
2124 if (entry->ItemId[j] <= 0)
2125 continue;
2127 uint32 item_id = entry->ItemId[j];
2129 if (!GetItemPrototype(item_id))
2130 if (item_id != 40582) // nonexistent item by default but referenced in DBC, skip it from errors
2131 notFoundOutfit.insert(item_id);
2135 for(std::set<uint32>::const_iterator itr = notFoundOutfit.begin(); itr != notFoundOutfit.end(); ++itr)
2136 sLog.outErrorDb("Item (Entry: %u) not exist in `item_template` but referenced in `CharStartOutfit.dbc`", *itr);
2139 void ObjectMgr::LoadItemRequiredTarget()
2141 m_ItemRequiredTarget.clear(); // needed for reload case
2143 uint32 count = 0;
2145 QueryResult *result = WorldDatabase.Query("SELECT entry,type,targetEntry FROM item_required_target");
2147 if (!result)
2149 barGoLink bar(1);
2151 bar.step();
2153 sLog.outString();
2154 sLog.outErrorDb(">> Loaded 0 ItemRequiredTarget. DB table `item_required_target` is empty.");
2155 return;
2158 barGoLink bar((int)result->GetRowCount());
2162 Field *fields = result->Fetch();
2163 bar.step();
2165 uint32 uiItemId = fields[0].GetUInt32();
2166 uint32 uiType = fields[1].GetUInt32();
2167 uint32 uiTargetEntry = fields[2].GetUInt32();
2169 ItemPrototype const* pItemProto = sItemStorage.LookupEntry<ItemPrototype>(uiItemId);
2171 if (!pItemProto)
2173 sLog.outErrorDb("Table `item_required_target`: Entry %u listed for TargetEntry %u does not exist in `item_template`.",uiItemId,uiTargetEntry);
2174 continue;
2177 bool bIsItemSpellValid = false;
2179 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
2181 if (SpellEntry const* pSpellInfo = sSpellStore.LookupEntry(pItemProto->Spells[i].SpellId))
2183 if (pItemProto->Spells[i].SpellTrigger == ITEM_SPELLTRIGGER_ON_USE ||
2184 pItemProto->Spells[i].SpellTrigger == ITEM_SPELLTRIGGER_ON_NO_DELAY_USE)
2186 SpellScriptTargetBounds bounds = sSpellMgr.GetSpellScriptTargetBounds(pSpellInfo->Id);
2187 if (bounds.first != bounds.second)
2188 break;
2190 for (int j = 0; j < MAX_EFFECT_INDEX; ++j)
2192 if (pSpellInfo->EffectImplicitTargetA[j] == TARGET_CHAIN_DAMAGE ||
2193 pSpellInfo->EffectImplicitTargetB[j] == TARGET_CHAIN_DAMAGE ||
2194 pSpellInfo->EffectImplicitTargetA[j] == TARGET_DUELVSPLAYER ||
2195 pSpellInfo->EffectImplicitTargetB[j] == TARGET_DUELVSPLAYER)
2197 bIsItemSpellValid = true;
2198 break;
2201 if (bIsItemSpellValid)
2202 break;
2207 if (!bIsItemSpellValid)
2209 sLog.outErrorDb("Table `item_required_target`: Spell used by item %u does not have implicit target TARGET_CHAIN_DAMAGE(6), TARGET_DUELVSPLAYER(25), already listed in `spell_script_target` or doesn't have item spelltrigger.",uiItemId);
2210 continue;
2213 if (!uiType || uiType > MAX_ITEM_REQ_TARGET_TYPE)
2215 sLog.outErrorDb("Table `item_required_target`: Type %u for TargetEntry %u is incorrect.",uiType,uiTargetEntry);
2216 continue;
2219 if (!uiTargetEntry)
2221 sLog.outErrorDb("Table `item_required_target`: TargetEntry == 0 for Type (%u).",uiType);
2222 continue;
2225 if (!sCreatureStorage.LookupEntry<CreatureInfo>(uiTargetEntry))
2227 sLog.outErrorDb("Table `item_required_target`: creature template entry %u does not exist.",uiTargetEntry);
2228 continue;
2231 m_ItemRequiredTarget.insert(ItemRequiredTargetMap::value_type(uiItemId,ItemRequiredTarget(ItemRequiredTargetType(uiType),uiTargetEntry)));
2233 ++count;
2234 } while (result->NextRow());
2236 delete result;
2238 sLog.outString();
2239 sLog.outString(">> Loaded %u Item required targets", count);
2242 void ObjectMgr::LoadPetLevelInfo()
2244 // Loading levels data
2246 // 0 1 2 3 4 5 6 7 8 9
2247 QueryResult *result = WorldDatabase.Query("SELECT creature_entry, level, hp, mana, str, agi, sta, inte, spi, armor FROM pet_levelstats");
2249 uint32 count = 0;
2251 if (!result)
2253 barGoLink bar( 1 );
2254 bar.step();
2256 sLog.outString();
2257 sLog.outString(">> Loaded %u level pet stats definitions", count);
2258 sLog.outErrorDb("Error loading `pet_levelstats` table or empty table.");
2259 return;
2262 barGoLink bar( (int)result->GetRowCount() );
2266 Field* fields = result->Fetch();
2268 uint32 creature_id = fields[0].GetUInt32();
2269 if(!sCreatureStorage.LookupEntry<CreatureInfo>(creature_id))
2271 sLog.outErrorDb("Wrong creature id %u in `pet_levelstats` table, ignoring.",creature_id);
2272 continue;
2275 uint32 current_level = fields[1].GetUInt32();
2276 if(current_level > sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
2278 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2279 sLog.outErrorDb("Wrong (> %u) level %u in `pet_levelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
2280 else
2282 DETAIL_LOG("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `pet_levelstats` table, ignoring.",current_level);
2283 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
2285 continue;
2287 else if(current_level < 1)
2289 sLog.outErrorDb("Wrong (<1) level %u in `pet_levelstats` table, ignoring.",current_level);
2290 continue;
2293 PetLevelInfo*& pInfoMapEntry = petInfo[creature_id];
2295 if(pInfoMapEntry==NULL)
2296 pInfoMapEntry = new PetLevelInfo[sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL)];
2298 // data for level 1 stored in [0] array element, ...
2299 PetLevelInfo* pLevelInfo = &pInfoMapEntry[current_level-1];
2301 pLevelInfo->health = fields[2].GetUInt16();
2302 pLevelInfo->mana = fields[3].GetUInt16();
2303 pLevelInfo->armor = fields[9].GetUInt16();
2305 for (int i = 0; i < MAX_STATS; i++)
2307 pLevelInfo->stats[i] = fields[i+4].GetUInt16();
2310 bar.step();
2311 ++count;
2313 while (result->NextRow());
2315 delete result;
2317 sLog.outString();
2318 sLog.outString( ">> Loaded %u level pet stats definitions", count );
2321 // Fill gaps and check integrity
2322 for (PetLevelInfoMap::iterator itr = petInfo.begin(); itr != petInfo.end(); ++itr)
2324 PetLevelInfo* pInfo = itr->second;
2326 // fatal error if no level 1 data
2327 if(!pInfo || pInfo[0].health == 0 )
2329 sLog.outErrorDb("Creature %u does not have pet stats data for Level 1!",itr->first);
2330 exit(1);
2333 // fill level gaps
2334 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL); ++level)
2336 if(pInfo[level].health == 0)
2338 sLog.outErrorDb("Creature %u has no data for Level %i pet stats data, using data of Level %i.",itr->first,level+1, level);
2339 pInfo[level] = pInfo[level-1];
2345 PetLevelInfo const* ObjectMgr::GetPetLevelInfo(uint32 creature_id, uint32 level) const
2347 if(level > sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
2348 level = sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL);
2350 PetLevelInfoMap::const_iterator itr = petInfo.find(creature_id);
2351 if(itr == petInfo.end())
2352 return NULL;
2354 return &itr->second[level-1]; // data for level 1 stored in [0] array element, ...
2357 void ObjectMgr::LoadPlayerInfo()
2359 // Load playercreate
2361 // 0 1 2 3 4 5 6
2362 QueryResult *result = WorldDatabase.Query("SELECT race, class, map, zone, position_x, position_y, position_z FROM playercreateinfo");
2364 uint32 count = 0;
2366 if (!result)
2368 barGoLink bar( 1 );
2370 sLog.outString();
2371 sLog.outString( ">> Loaded %u player create definitions", count );
2372 sLog.outErrorDb( "Error loading `playercreateinfo` table or empty table.");
2373 exit(1);
2376 barGoLink bar( (int)result->GetRowCount() );
2380 Field* fields = result->Fetch();
2382 uint32 current_race = fields[0].GetUInt32();
2383 uint32 current_class = fields[1].GetUInt32();
2384 uint32 mapId = fields[2].GetUInt32();
2385 uint32 areaId = fields[3].GetUInt32();
2386 float positionX = fields[4].GetFloat();
2387 float positionY = fields[5].GetFloat();
2388 float positionZ = fields[6].GetFloat();
2390 if(current_race >= MAX_RACES)
2392 sLog.outErrorDb("Wrong race %u in `playercreateinfo` table, ignoring.",current_race);
2393 continue;
2396 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(current_race);
2397 if(!rEntry)
2399 sLog.outErrorDb("Wrong race %u in `playercreateinfo` table, ignoring.",current_race);
2400 continue;
2403 if(current_class >= MAX_CLASSES)
2405 sLog.outErrorDb("Wrong class %u in `playercreateinfo` table, ignoring.",current_class);
2406 continue;
2409 if(!sChrClassesStore.LookupEntry(current_class))
2411 sLog.outErrorDb("Wrong class %u in `playercreateinfo` table, ignoring.",current_class);
2412 continue;
2415 // accept DB data only for valid position (and non instanceable)
2416 if( !MapManager::IsValidMapCoord(mapId,positionX,positionY,positionZ) )
2418 sLog.outErrorDb("Wrong home position for class %u race %u pair in `playercreateinfo` table, ignoring.",current_class,current_race);
2419 continue;
2422 if( sMapStore.LookupEntry(mapId)->Instanceable() )
2424 sLog.outErrorDb("Home position in instanceable map for class %u race %u pair in `playercreateinfo` table, ignoring.",current_class,current_race);
2425 continue;
2428 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2430 pInfo->mapId = mapId;
2431 pInfo->areaId = areaId;
2432 pInfo->positionX = positionX;
2433 pInfo->positionY = positionY;
2434 pInfo->positionZ = positionZ;
2436 pInfo->displayId_m = rEntry->model_m;
2437 pInfo->displayId_f = rEntry->model_f;
2439 bar.step();
2440 ++count;
2442 while (result->NextRow());
2444 delete result;
2446 sLog.outString();
2447 sLog.outString( ">> Loaded %u player create definitions", count );
2450 // Load playercreate items
2452 // 0 1 2 3
2453 QueryResult *result = WorldDatabase.Query("SELECT race, class, itemid, amount FROM playercreateinfo_item");
2455 uint32 count = 0;
2457 if (!result)
2459 barGoLink bar( 1 );
2461 bar.step();
2463 sLog.outString();
2464 sLog.outString( ">> Loaded %u custom player create items", count );
2466 else
2468 barGoLink bar( (int)result->GetRowCount() );
2472 Field* fields = result->Fetch();
2474 uint32 current_race = fields[0].GetUInt32();
2475 if(current_race >= MAX_RACES)
2477 sLog.outErrorDb("Wrong race %u in `playercreateinfo_item` table, ignoring.",current_race);
2478 continue;
2481 uint32 current_class = fields[1].GetUInt32();
2482 if(current_class >= MAX_CLASSES)
2484 sLog.outErrorDb("Wrong class %u in `playercreateinfo_item` table, ignoring.",current_class);
2485 continue;
2488 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2490 uint32 item_id = fields[2].GetUInt32();
2492 if(!GetItemPrototype(item_id))
2494 sLog.outErrorDb("Item id %u (race %u class %u) in `playercreateinfo_item` table but not listed in `item_template`, ignoring.",item_id,current_race,current_class);
2495 continue;
2498 uint32 amount = fields[3].GetUInt32();
2500 if(!amount)
2502 sLog.outErrorDb("Item id %u (class %u race %u) have amount==0 in `playercreateinfo_item` table, ignoring.",item_id,current_race,current_class);
2503 continue;
2506 pInfo->item.push_back(PlayerCreateInfoItem( item_id, amount));
2508 bar.step();
2509 ++count;
2511 while(result->NextRow());
2513 delete result;
2515 sLog.outString();
2516 sLog.outString( ">> Loaded %u custom player create items", count );
2520 // Load playercreate spells
2522 // 0 1 2
2523 QueryResult *result = WorldDatabase.Query("SELECT race, class, Spell FROM playercreateinfo_spell");
2525 uint32 count = 0;
2527 if (!result)
2529 barGoLink bar( 1 );
2531 sLog.outString();
2532 sLog.outString( ">> Loaded %u player create spells", count );
2533 sLog.outErrorDb( "Error loading `playercreateinfo_spell` table or empty table.");
2535 else
2537 barGoLink bar( (int)result->GetRowCount() );
2541 Field* fields = result->Fetch();
2543 uint32 current_race = fields[0].GetUInt32();
2544 if(current_race >= MAX_RACES)
2546 sLog.outErrorDb("Wrong race %u in `playercreateinfo_spell` table, ignoring.",current_race);
2547 continue;
2550 uint32 current_class = fields[1].GetUInt32();
2551 if(current_class >= MAX_CLASSES)
2553 sLog.outErrorDb("Wrong class %u in `playercreateinfo_spell` table, ignoring.",current_class);
2554 continue;
2557 uint32 spell_id = fields[2].GetUInt32();
2558 if (!sSpellStore.LookupEntry(spell_id))
2560 sLog.outErrorDb("Non existing spell %u in `playercreateinfo_spell` table, ignoring.", spell_id);
2561 continue;
2564 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2565 pInfo->spell.push_back(spell_id);
2567 bar.step();
2568 ++count;
2570 while( result->NextRow() );
2572 delete result;
2574 sLog.outString();
2575 sLog.outString( ">> Loaded %u player create spells", count );
2579 // Load playercreate actions
2581 // 0 1 2 3 4
2582 QueryResult *result = WorldDatabase.Query("SELECT race, class, button, action, type FROM playercreateinfo_action");
2584 uint32 count = 0;
2586 if (!result)
2588 barGoLink bar( 1 );
2590 sLog.outString();
2591 sLog.outString( ">> Loaded %u player create actions", count );
2592 sLog.outErrorDb( "Error loading `playercreateinfo_action` table or empty table.");
2594 else
2596 barGoLink bar( (int)result->GetRowCount() );
2600 Field* fields = result->Fetch();
2602 uint32 current_race = fields[0].GetUInt32();
2603 if(current_race >= MAX_RACES)
2605 sLog.outErrorDb("Wrong race %u in `playercreateinfo_action` table, ignoring.",current_race);
2606 continue;
2609 uint32 current_class = fields[1].GetUInt32();
2610 if(current_class >= MAX_CLASSES)
2612 sLog.outErrorDb("Wrong class %u in `playercreateinfo_action` table, ignoring.",current_class);
2613 continue;
2616 uint8 action_button = fields[2].GetUInt8();
2617 uint32 action = fields[3].GetUInt32();
2618 uint8 action_type = fields[4].GetUInt8();
2620 if (!Player::IsActionButtonDataValid(action_button,action,action_type,NULL))
2621 continue;
2623 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2624 pInfo->action.push_back(PlayerCreateInfoAction(action_button,action,action_type));
2626 bar.step();
2627 ++count;
2629 while( result->NextRow() );
2631 delete result;
2633 sLog.outString();
2634 sLog.outString( ">> Loaded %u player create actions", count );
2638 // Loading levels data (class only dependent)
2640 // 0 1 2 3
2641 QueryResult *result = WorldDatabase.Query("SELECT class, level, basehp, basemana FROM player_classlevelstats");
2643 uint32 count = 0;
2645 if (!result)
2647 barGoLink bar( 1 );
2649 sLog.outString();
2650 sLog.outString( ">> Loaded %u level health/mana definitions", count );
2651 sLog.outErrorDb( "Error loading `player_classlevelstats` table or empty table.");
2652 exit(1);
2655 barGoLink bar( (int)result->GetRowCount() );
2659 Field* fields = result->Fetch();
2661 uint32 current_class = fields[0].GetUInt32();
2662 if(current_class >= MAX_CLASSES)
2664 sLog.outErrorDb("Wrong class %u in `player_classlevelstats` table, ignoring.",current_class);
2665 continue;
2668 uint32 current_level = fields[1].GetUInt32();
2669 if(current_level == 0)
2671 sLog.outErrorDb("Wrong level %u in `player_classlevelstats` table, ignoring.",current_level);
2672 continue;
2674 else if(current_level > sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
2676 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2677 sLog.outErrorDb("Wrong (> %u) level %u in `player_classlevelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
2678 else
2680 DETAIL_LOG("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_classlevelstats` table, ignoring.",current_level);
2681 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
2683 continue;
2686 PlayerClassInfo* pClassInfo = &playerClassInfo[current_class];
2688 if(!pClassInfo->levelInfo)
2689 pClassInfo->levelInfo = new PlayerClassLevelInfo[sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL)];
2691 PlayerClassLevelInfo* pClassLevelInfo = &pClassInfo->levelInfo[current_level-1];
2693 pClassLevelInfo->basehealth = fields[2].GetUInt16();
2694 pClassLevelInfo->basemana = fields[3].GetUInt16();
2696 bar.step();
2697 ++count;
2699 while (result->NextRow());
2701 delete result;
2703 sLog.outString();
2704 sLog.outString( ">> Loaded %u level health/mana definitions", count );
2707 // Fill gaps and check integrity
2708 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2710 // skip non existed classes
2711 if(!sChrClassesStore.LookupEntry(class_))
2712 continue;
2714 PlayerClassInfo* pClassInfo = &playerClassInfo[class_];
2716 // fatal error if no level 1 data
2717 if(!pClassInfo->levelInfo || pClassInfo->levelInfo[0].basehealth == 0 )
2719 sLog.outErrorDb("Class %i Level 1 does not have health/mana data!",class_);
2720 exit(1);
2723 // fill level gaps
2724 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL); ++level)
2726 if(pClassInfo->levelInfo[level].basehealth == 0)
2728 sLog.outErrorDb("Class %i Level %i does not have health/mana data. Using stats data of level %i.",class_,level+1, level);
2729 pClassInfo->levelInfo[level] = pClassInfo->levelInfo[level-1];
2734 // Loading levels data (class/race dependent)
2736 // 0 1 2 3 4 5 6 7
2737 QueryResult *result = WorldDatabase.Query("SELECT race, class, level, str, agi, sta, inte, spi FROM player_levelstats");
2739 uint32 count = 0;
2741 if (!result)
2743 barGoLink bar( 1 );
2745 sLog.outString();
2746 sLog.outString( ">> Loaded %u level stats definitions", count );
2747 sLog.outErrorDb( "Error loading `player_levelstats` table or empty table.");
2748 exit(1);
2751 barGoLink bar( (int)result->GetRowCount() );
2755 Field* fields = result->Fetch();
2757 uint32 current_race = fields[0].GetUInt32();
2758 if(current_race >= MAX_RACES)
2760 sLog.outErrorDb("Wrong race %u in `player_levelstats` table, ignoring.",current_race);
2761 continue;
2764 uint32 current_class = fields[1].GetUInt32();
2765 if(current_class >= MAX_CLASSES)
2767 sLog.outErrorDb("Wrong class %u in `player_levelstats` table, ignoring.",current_class);
2768 continue;
2771 uint32 current_level = fields[2].GetUInt32();
2772 if(current_level > sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
2774 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2775 sLog.outErrorDb("Wrong (> %u) level %u in `player_levelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
2776 else
2778 DETAIL_LOG("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_levelstats` table, ignoring.",current_level);
2779 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
2781 continue;
2784 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2786 if(!pInfo->levelInfo)
2787 pInfo->levelInfo = new PlayerLevelInfo[sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL)];
2789 PlayerLevelInfo* pLevelInfo = &pInfo->levelInfo[current_level-1];
2791 for (int i = 0; i < MAX_STATS; i++)
2793 pLevelInfo->stats[i] = fields[i+3].GetUInt8();
2796 bar.step();
2797 ++count;
2799 while (result->NextRow());
2801 delete result;
2803 sLog.outString();
2804 sLog.outString( ">> Loaded %u level stats definitions", count );
2807 // Fill gaps and check integrity
2808 for (int race = 0; race < MAX_RACES; ++race)
2810 // skip non existed races
2811 if(!sChrRacesStore.LookupEntry(race))
2812 continue;
2814 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2816 // skip non existed classes
2817 if(!sChrClassesStore.LookupEntry(class_))
2818 continue;
2820 PlayerInfo* pInfo = &playerInfo[race][class_];
2822 // skip non loaded combinations
2823 if(!pInfo->displayId_m || !pInfo->displayId_f)
2824 continue;
2826 // skip expansion races if not playing with expansion
2827 if (sWorld.getConfig(CONFIG_UINT32_EXPANSION) < 1 && (race == RACE_BLOODELF || race == RACE_DRAENEI))
2828 continue;
2830 // skip expansion classes if not playing with expansion
2831 if (sWorld.getConfig(CONFIG_UINT32_EXPANSION) < 2 && class_ == CLASS_DEATH_KNIGHT)
2832 continue;
2834 // fatal error if no level 1 data
2835 if(!pInfo->levelInfo || pInfo->levelInfo[0].stats[0] == 0 )
2837 sLog.outErrorDb("Race %i Class %i Level 1 does not have stats data!",race,class_);
2838 exit(1);
2841 // fill level gaps
2842 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL); ++level)
2844 if(pInfo->levelInfo[level].stats[0] == 0)
2846 sLog.outErrorDb("Race %i Class %i Level %i does not have stats data. Using stats data of level %i.",race,class_,level+1, level);
2847 pInfo->levelInfo[level] = pInfo->levelInfo[level-1];
2853 // Loading xp per level data
2855 mPlayerXPperLevel.resize(sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL));
2856 for (uint32 level = 0; level < sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL); ++level)
2857 mPlayerXPperLevel[level] = 0;
2859 // 0 1
2860 QueryResult *result = WorldDatabase.Query("SELECT lvl, xp_for_next_level FROM player_xp_for_level");
2862 uint32 count = 0;
2864 if (!result)
2866 barGoLink bar( 1 );
2868 sLog.outString();
2869 sLog.outString( ">> Loaded %u xp for level definitions", count );
2870 sLog.outErrorDb( "Error loading `player_xp_for_level` table or empty table.");
2871 exit(1);
2874 barGoLink bar( (int)result->GetRowCount() );
2878 Field* fields = result->Fetch();
2880 uint32 current_level = fields[0].GetUInt32();
2881 uint32 current_xp = fields[1].GetUInt32();
2883 if(current_level >= sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
2885 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2886 sLog.outErrorDb("Wrong (> %u) level %u in `player_xp_for_level` table, ignoring.", STRONG_MAX_LEVEL,current_level);
2887 else
2889 DETAIL_LOG("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_xp_for_levels` table, ignoring.",current_level);
2890 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
2892 continue;
2894 //PlayerXPperLevel
2895 mPlayerXPperLevel[current_level] = current_xp;
2896 bar.step();
2897 ++count;
2899 while (result->NextRow());
2901 delete result;
2903 sLog.outString();
2904 sLog.outString( ">> Loaded %u xp for level definitions", count );
2907 // fill level gaps
2908 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL); ++level)
2910 if( mPlayerXPperLevel[level] == 0)
2912 sLog.outErrorDb("Level %i does not have XP for level data. Using data of level [%i] + 100.",level+1, level);
2913 mPlayerXPperLevel[level] = mPlayerXPperLevel[level-1]+100;
2918 void ObjectMgr::GetPlayerClassLevelInfo(uint32 class_, uint32 level, PlayerClassLevelInfo* info) const
2920 if(level < 1 || class_ >= MAX_CLASSES)
2921 return;
2923 PlayerClassInfo const* pInfo = &playerClassInfo[class_];
2925 if(level > sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
2926 level = sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL);
2928 *info = pInfo->levelInfo[level-1];
2931 void ObjectMgr::GetPlayerLevelInfo(uint32 race, uint32 class_, uint32 level, PlayerLevelInfo* info) const
2933 if(level < 1 || race >= MAX_RACES || class_ >= MAX_CLASSES)
2934 return;
2936 PlayerInfo const* pInfo = &playerInfo[race][class_];
2937 if(pInfo->displayId_m==0 || pInfo->displayId_f==0)
2938 return;
2940 if(level <= sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
2941 *info = pInfo->levelInfo[level-1];
2942 else
2943 BuildPlayerLevelInfo(race,class_,level,info);
2946 void ObjectMgr::BuildPlayerLevelInfo(uint8 race, uint8 _class, uint8 level, PlayerLevelInfo* info) const
2948 // base data (last known level)
2949 *info = playerInfo[race][_class].levelInfo[sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL)-1];
2951 for(int lvl = sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL)-1; lvl < level; ++lvl)
2953 switch(_class)
2955 case CLASS_WARRIOR:
2956 info->stats[STAT_STRENGTH] += (lvl > 23 ? 2: (lvl > 1 ? 1: 0));
2957 info->stats[STAT_STAMINA] += (lvl > 23 ? 2: (lvl > 1 ? 1: 0));
2958 info->stats[STAT_AGILITY] += (lvl > 36 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2959 info->stats[STAT_INTELLECT] += (lvl > 9 && !(lvl%2) ? 1: 0);
2960 info->stats[STAT_SPIRIT] += (lvl > 9 && !(lvl%2) ? 1: 0);
2961 break;
2962 case CLASS_PALADIN:
2963 info->stats[STAT_STRENGTH] += (lvl > 3 ? 1: 0);
2964 info->stats[STAT_STAMINA] += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2965 info->stats[STAT_AGILITY] += (lvl > 38 ? 1: (lvl > 7 && !(lvl%2) ? 1: 0));
2966 info->stats[STAT_INTELLECT] += (lvl > 6 && (lvl%2) ? 1: 0);
2967 info->stats[STAT_SPIRIT] += (lvl > 7 ? 1: 0);
2968 break;
2969 case CLASS_HUNTER:
2970 info->stats[STAT_STRENGTH] += (lvl > 4 ? 1: 0);
2971 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2972 info->stats[STAT_AGILITY] += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2973 info->stats[STAT_INTELLECT] += (lvl > 8 && (lvl%2) ? 1: 0);
2974 info->stats[STAT_SPIRIT] += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2975 break;
2976 case CLASS_ROGUE:
2977 info->stats[STAT_STRENGTH] += (lvl > 5 ? 1: 0);
2978 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2979 info->stats[STAT_AGILITY] += (lvl > 16 ? 2: (lvl > 1 ? 1: 0));
2980 info->stats[STAT_INTELLECT] += (lvl > 8 && !(lvl%2) ? 1: 0);
2981 info->stats[STAT_SPIRIT] += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2982 break;
2983 case CLASS_PRIEST:
2984 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2985 info->stats[STAT_STAMINA] += (lvl > 5 ? 1: 0);
2986 info->stats[STAT_AGILITY] += (lvl > 38 ? 1: (lvl > 8 && (lvl%2) ? 1: 0));
2987 info->stats[STAT_INTELLECT] += (lvl > 22 ? 2: (lvl > 1 ? 1: 0));
2988 info->stats[STAT_SPIRIT] += (lvl > 3 ? 1: 0);
2989 break;
2990 case CLASS_SHAMAN:
2991 info->stats[STAT_STRENGTH] += (lvl > 34 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2992 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2993 info->stats[STAT_AGILITY] += (lvl > 7 && !(lvl%2) ? 1: 0);
2994 info->stats[STAT_INTELLECT] += (lvl > 5 ? 1: 0);
2995 info->stats[STAT_SPIRIT] += (lvl > 4 ? 1: 0);
2996 break;
2997 case CLASS_MAGE:
2998 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2999 info->stats[STAT_STAMINA] += (lvl > 5 ? 1: 0);
3000 info->stats[STAT_AGILITY] += (lvl > 9 && !(lvl%2) ? 1: 0);
3001 info->stats[STAT_INTELLECT] += (lvl > 24 ? 2: (lvl > 1 ? 1: 0));
3002 info->stats[STAT_SPIRIT] += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
3003 break;
3004 case CLASS_WARLOCK:
3005 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
3006 info->stats[STAT_STAMINA] += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
3007 info->stats[STAT_AGILITY] += (lvl > 9 && !(lvl%2) ? 1: 0);
3008 info->stats[STAT_INTELLECT] += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
3009 info->stats[STAT_SPIRIT] += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
3010 break;
3011 case CLASS_DRUID:
3012 info->stats[STAT_STRENGTH] += (lvl > 38 ? 2: (lvl > 6 && (lvl%2) ? 1: 0));
3013 info->stats[STAT_STAMINA] += (lvl > 32 ? 2: (lvl > 4 ? 1: 0));
3014 info->stats[STAT_AGILITY] += (lvl > 38 ? 2: (lvl > 8 && (lvl%2) ? 1: 0));
3015 info->stats[STAT_INTELLECT] += (lvl > 38 ? 3: (lvl > 4 ? 1: 0));
3016 info->stats[STAT_SPIRIT] += (lvl > 38 ? 3: (lvl > 5 ? 1: 0));
3021 void ObjectMgr::LoadGuilds()
3023 Guild *newGuild;
3024 uint32 count = 0;
3026 // 0 1 2 3 4 5 6
3027 QueryResult *result = CharacterDatabase.Query("SELECT guild.guildid,guild.name,leaderguid,EmblemStyle,EmblemColor,BorderStyle,BorderColor,"
3028 // 7 8 9 10 11 12
3029 "BackgroundColor,info,motd,createdate,BankMoney,(SELECT COUNT(guild_bank_tab.guildid) FROM guild_bank_tab WHERE guild_bank_tab.guildid = guild.guildid) "
3030 "FROM guild ORDER BY guildid ASC");
3032 if( !result )
3035 barGoLink bar( 1 );
3037 bar.step();
3039 sLog.outString();
3040 sLog.outString( ">> Loaded %u guild definitions", count );
3041 return;
3044 // load guild ranks
3045 // 0 1 2 3 4
3046 QueryResult *guildRanksResult = CharacterDatabase.Query("SELECT guildid,rid,rname,rights,BankMoneyPerDay FROM guild_rank ORDER BY guildid ASC, rid ASC");
3048 // load guild members
3049 // 0 1 2 3 4 5 6
3050 QueryResult *guildMembersResult = CharacterDatabase.Query("SELECT guildid,guild_member.guid,rank,pnote,offnote,BankResetTimeMoney,BankRemMoney,"
3051 // 7 8 9 10 11 12
3052 "BankResetTimeTab0,BankRemSlotsTab0,BankResetTimeTab1,BankRemSlotsTab1,BankResetTimeTab2,BankRemSlotsTab2,"
3053 // 13 14 15 16 17 18
3054 "BankResetTimeTab3,BankRemSlotsTab3,BankResetTimeTab4,BankRemSlotsTab4,BankResetTimeTab5,BankRemSlotsTab5,"
3055 // 19 20 21 22 23
3056 "characters.name, characters.level, characters.class, characters.zone, characters.logout_time "
3057 "FROM guild_member LEFT JOIN characters ON characters.guid = guild_member.guid ORDER BY guildid ASC");
3059 // load guild bank tab rights
3060 // 0 1 2 3 4
3061 QueryResult *guildBankTabRightsResult = CharacterDatabase.Query("SELECT guildid,TabId,rid,gbright,SlotPerDay FROM guild_bank_right ORDER BY guildid ASC, TabId ASC");
3063 barGoLink bar( (int)result->GetRowCount() );
3067 //Field *fields = result->Fetch();
3069 bar.step();
3070 ++count;
3072 newGuild = new Guild;
3073 if (!newGuild->LoadGuildFromDB(result) ||
3074 !newGuild->LoadRanksFromDB(guildRanksResult) ||
3075 !newGuild->LoadMembersFromDB(guildMembersResult) ||
3076 !newGuild->LoadBankRightsFromDB(guildBankTabRightsResult) ||
3077 !newGuild->CheckGuildStructure()
3080 newGuild->Disband();
3081 delete newGuild;
3082 continue;
3084 newGuild->LoadGuildEventLogFromDB();
3085 newGuild->LoadGuildBankEventLogFromDB();
3086 newGuild->LoadGuildBankFromDB();
3087 AddGuild(newGuild);
3088 } while( result->NextRow() );
3090 delete result;
3091 delete guildRanksResult;
3092 delete guildMembersResult;
3093 delete guildBankTabRightsResult;
3095 //delete unused LogGuid records in guild_eventlog and guild_bank_eventlog table
3096 //you can comment these lines if you don't plan to change CONFIG_UINT32_GUILD_EVENT_LOG_COUNT and CONFIG_UINT32_GUILD_BANK_EVENT_LOG_COUNT
3097 CharacterDatabase.PExecute("DELETE FROM guild_eventlog WHERE LogGuid > '%u'", sWorld.getConfig(CONFIG_UINT32_GUILD_EVENT_LOG_COUNT));
3098 CharacterDatabase.PExecute("DELETE FROM guild_bank_eventlog WHERE LogGuid > '%u'", sWorld.getConfig(CONFIG_UINT32_GUILD_BANK_EVENT_LOG_COUNT));
3100 sLog.outString();
3101 sLog.outString( ">> Loaded %u guild definitions", count );
3104 void ObjectMgr::LoadArenaTeams()
3106 uint32 count = 0;
3108 // 0 1 2 3 4 5
3109 QueryResult *result = CharacterDatabase.Query( "SELECT arena_team.arenateamid,name,captainguid,type,BackgroundColor,EmblemStyle,"
3110 // 6 7 8 9 10 11 12 13 14
3111 "EmblemColor,BorderStyle,BorderColor, rating,games,wins,played,wins2,rank "
3112 "FROM arena_team LEFT JOIN arena_team_stats ON arena_team.arenateamid = arena_team_stats.arenateamid ORDER BY arena_team.arenateamid ASC" );
3114 if( !result )
3117 barGoLink bar( 1 );
3119 bar.step();
3121 sLog.outString();
3122 sLog.outString( ">> Loaded %u arenateam definitions", count );
3123 return;
3126 // load arena_team members
3127 QueryResult *arenaTeamMembersResult = CharacterDatabase.Query(
3128 // 0 1 2 3 4 5 6 7 8
3129 "SELECT arenateamid,member.guid,played_week,wons_week,played_season,wons_season,personal_rating,name,class "
3130 "FROM arena_team_member member LEFT JOIN characters chars on member.guid = chars.guid ORDER BY member.arenateamid ASC");
3132 barGoLink bar( (int)result->GetRowCount() );
3137 bar.step();
3138 ++count;
3140 ArenaTeam *newArenaTeam = new ArenaTeam;
3141 if (!newArenaTeam->LoadArenaTeamFromDB(result) ||
3142 !newArenaTeam->LoadMembersFromDB(arenaTeamMembersResult))
3144 newArenaTeam->Disband(NULL);
3145 delete newArenaTeam;
3146 continue;
3148 AddArenaTeam(newArenaTeam);
3149 }while( result->NextRow() );
3151 delete result;
3152 delete arenaTeamMembersResult;
3154 sLog.outString();
3155 sLog.outString( ">> Loaded %u arenateam definitions", count );
3158 void ObjectMgr::LoadGroups()
3160 // -- loading groups --
3161 uint32 count = 0;
3162 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
3163 QueryResult *result = CharacterDatabase.Query("SELECT mainTank, mainAssistant, lootMethod, looterGuid, lootThreshold, icon1, icon2, icon3, icon4, icon5, icon6, icon7, icon8, isRaid, difficulty, raiddifficulty, leaderGuid, groupId FROM groups");
3165 if (!result)
3167 barGoLink bar( 1 );
3169 bar.step();
3171 sLog.outString();
3172 sLog.outString( ">> Loaded %u group definitions", count );
3173 return;
3176 barGoLink bar( (int)result->GetRowCount() );
3180 bar.step();
3181 Field *fields = result->Fetch();
3182 ++count;
3183 Group *group = new Group;
3184 if (!group->LoadGroupFromDB(fields))
3186 group->Disband();
3187 delete group;
3188 continue;
3190 AddGroup(group);
3191 }while( result->NextRow() );
3193 delete result;
3195 sLog.outString();
3196 sLog.outString( ">> Loaded %u group definitions", count );
3198 // -- loading members --
3199 count = 0;
3200 // 0 1 2 3
3201 result = CharacterDatabase.Query("SELECT memberGuid, assistant, subgroup, groupId FROM group_member ORDER BY groupId");
3202 if (!result)
3204 barGoLink bar2( 1 );
3205 bar2.step();
3207 else
3209 Group* group = NULL; // used as cached pointer for avoid relookup group for each member
3211 barGoLink bar2( (int)result->GetRowCount() );
3214 bar2.step();
3215 Field *fields = result->Fetch();
3216 count++;
3218 uint32 memberGuidlow = fields[0].GetUInt32();
3219 bool assistent = fields[1].GetBool();
3220 uint8 subgroup = fields[2].GetUInt8();
3221 uint32 groupId = fields[3].GetUInt32();
3222 if (!group || group->GetId() != groupId)
3224 group = GetGroupById(groupId);
3225 if (!group)
3227 sLog.outErrorDb("Incorrect entry in group_member table : no group with Id %d for member %d!", groupId, memberGuidlow);
3228 CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", memberGuidlow);
3229 continue;
3233 if (!group->LoadMemberFromDB(memberGuidlow, subgroup, assistent))
3235 sLog.outErrorDb("Incorrect entry in group_member table : member %d cannot be added to player %d's group (Id: %u)!", memberGuidlow, GUID_LOPART(group->GetLeaderGUID()), groupId);
3236 CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", memberGuidlow);
3238 }while( result->NextRow() );
3239 delete result;
3242 // clean groups
3243 // TODO: maybe delete from the DB before loading in this case
3244 for (GroupMap::iterator itr = mGroupMap.begin(); itr != mGroupMap.end();)
3246 if (itr->second->GetMembersCount() < 2)
3248 itr->second->Disband();
3249 delete itr->second;
3250 mGroupMap.erase(itr++);
3252 else
3253 ++itr;
3256 // -- loading instances --
3257 count = 0;
3258 result = CharacterDatabase.Query(
3259 // 0 1 2 3 4 5
3260 "SELECT group_instance.leaderGuid, map, instance, permanent, instance.difficulty, resettime, "
3261 // 6
3262 "(SELECT COUNT(*) FROM character_instance WHERE guid = group_instance.leaderGuid AND instance = group_instance.instance AND permanent = 1 LIMIT 1), "
3263 // 7
3264 " groups.groupId "
3265 "FROM group_instance LEFT JOIN instance ON instance = id LEFT JOIN groups ON groups.leaderGUID = group_instance.leaderGUID ORDER BY leaderGuid"
3268 if (!result)
3270 barGoLink bar2( 1 );
3271 bar2.step();
3273 else
3275 Group* group = NULL; // used as cached pointer for avoid relookup group for each member
3277 barGoLink bar2( (int)result->GetRowCount() );
3280 bar2.step();
3281 Field *fields = result->Fetch();
3282 count++;
3284 uint32 leaderGuidLow = fields[0].GetUInt32();
3285 uint32 mapId = fields[1].GetUInt32();
3286 Difficulty diff = (Difficulty)fields[4].GetUInt8();
3287 uint32 groupId = fields[7].GetUInt32();
3289 if (!group || group->GetId() != groupId)
3291 // find group id in map by leader low guid
3292 group = GetGroupById(groupId);
3293 if (!group)
3295 sLog.outErrorDb("Incorrect entry in group_instance table : no group with leader %d", leaderGuidLow);
3296 continue;
3300 MapEntry const* mapEntry = sMapStore.LookupEntry(mapId);
3301 if (!mapEntry || !mapEntry->IsDungeon())
3303 sLog.outErrorDb("Incorrect entry in group_instance table : no dungeon map %d", mapId);
3304 continue;
3307 if (diff >= (mapEntry->IsRaid() ? MAX_RAID_DIFFICULTY : MAX_DUNGEON_DIFFICULTY))
3309 sLog.outErrorDb("Wrong dungeon difficulty use in group_instance table: %d", diff + 1);
3310 diff = REGULAR_DIFFICULTY; // default for both difficaly types
3313 InstanceSave *save = sInstanceSaveMgr.AddInstanceSave(mapEntry->MapID, fields[2].GetUInt32(), Difficulty(diff), (time_t)fields[5].GetUInt64(), (fields[6].GetUInt32() == 0), true);
3314 group->BindToInstance(save, fields[3].GetBool(), true);
3315 }while( result->NextRow() );
3316 delete result;
3319 sLog.outString();
3320 sLog.outString( ">> Loaded %u group-instance binds total", count );
3322 sLog.outString();
3323 sLog.outString( ">> Loaded %u group members total", count );
3326 void ObjectMgr::LoadQuests()
3328 // For reload case
3329 for(QuestMap::const_iterator itr=mQuestTemplates.begin(); itr != mQuestTemplates.end(); ++itr)
3330 delete itr->second;
3331 mQuestTemplates.clear();
3333 mExclusiveQuestGroups.clear();
3335 // 0 1 2 3 4 5 6 7 8
3336 QueryResult *result = WorldDatabase.Query("SELECT entry, Method, ZoneOrSort, SkillOrClass, MinLevel, QuestLevel, Type, RequiredRaces, RequiredSkillValue,"
3337 // 9 10 11 12 13 14 15 16
3338 "RepObjectiveFaction, RepObjectiveValue, RequiredMinRepFaction, RequiredMinRepValue, RequiredMaxRepFaction, RequiredMaxRepValue, SuggestedPlayers, LimitTime,"
3339 // 17 18 19 20 21 22 23 24 25
3340 "QuestFlags, SpecialFlags, CharTitleId, PlayersSlain, BonusTalents, PrevQuestId, NextQuestId, ExclusiveGroup, NextQuestInChain,"
3341 // 26 27 28 29
3342 "RewXPId, SrcItemId, SrcItemCount, SrcSpell,"
3343 // 30 31 32 33 34 35 36 37 38 39 40
3344 "Title, Details, Objectives, OfferRewardText, RequestItemsText, EndText, CompletedText, ObjectiveText1, ObjectiveText2, ObjectiveText3, ObjectiveText4,"
3345 // 41 42 43 44 45 46 47 48 49 50 51 52
3346 "ReqItemId1, ReqItemId2, ReqItemId3, ReqItemId4, ReqItemId5, ReqItemId6, ReqItemCount1, ReqItemCount2, ReqItemCount3, ReqItemCount4, ReqItemCount5, ReqItemCount6,"
3347 // 53 54 55 56 57 58 59 60
3348 "ReqSourceId1, ReqSourceId2, ReqSourceId3, ReqSourceId4, ReqSourceCount1, ReqSourceCount2, ReqSourceCount3, ReqSourceCount4,"
3349 // 61 62 63 64 65 66 67 68
3350 "ReqCreatureOrGOId1, ReqCreatureOrGOId2, ReqCreatureOrGOId3, ReqCreatureOrGOId4, ReqCreatureOrGOCount1, ReqCreatureOrGOCount2, ReqCreatureOrGOCount3, ReqCreatureOrGOCount4,"
3351 // 69 70 71 72
3352 "ReqSpellCast1, ReqSpellCast2, ReqSpellCast3, ReqSpellCast4,"
3353 // 73 74 75 76 77 78
3354 "RewChoiceItemId1, RewChoiceItemId2, RewChoiceItemId3, RewChoiceItemId4, RewChoiceItemId5, RewChoiceItemId6,"
3355 // 79 80 81 82 83 84
3356 "RewChoiceItemCount1, RewChoiceItemCount2, RewChoiceItemCount3, RewChoiceItemCount4, RewChoiceItemCount5, RewChoiceItemCount6,"
3357 // 85 86 87 88 89 90 91 92
3358 "RewItemId1, RewItemId2, RewItemId3, RewItemId4, RewItemCount1, RewItemCount2, RewItemCount3, RewItemCount4,"
3359 // 93 94 95 96 97
3360 "RewRepFaction1, RewRepFaction2, RewRepFaction3, RewRepFaction4, RewRepFaction5,"
3361 // 98 99 100 101 102
3362 "RewRepValueId1, RewRepValueId2, RewRepValueId3, RewRepValueId4, RewRepValueId5,"
3363 // 103 104 105 106 107
3364 "RewRepValue1, RewRepValue2, RewRepValue3, RewRepValue4, RewRepValue5,"
3365 // 108 109 110 111 112 113
3366 "RewHonorAddition, RewHonorMultiplier, RewOrReqMoney, RewMoneyMaxLevel, RewSpell, RewSpellCast,"
3367 // 114 115 116 117 118 119
3368 "RewMailTemplateId, RewMailDelaySecs, PointMapId, PointX, PointY, PointOpt,"
3369 // 120 121 122 123 124 125 126 127
3370 "DetailsEmote1, DetailsEmote2, DetailsEmote3, DetailsEmote4, DetailsEmoteDelay1, DetailsEmoteDelay2, DetailsEmoteDelay3, DetailsEmoteDelay4,"
3371 // 128 129 130 131 132 133
3372 "IncompleteEmote, CompleteEmote, OfferRewardEmote1, OfferRewardEmote2, OfferRewardEmote3, OfferRewardEmote4,"
3373 // 134 135 136 137
3374 "OfferRewardEmoteDelay1, OfferRewardEmoteDelay2, OfferRewardEmoteDelay3, OfferRewardEmoteDelay4,"
3375 // 138 139
3376 "StartScript, CompleteScript"
3377 " FROM quest_template");
3378 if (result == NULL)
3380 barGoLink bar( 1 );
3381 bar.step();
3383 sLog.outString();
3384 sLog.outString( ">> Loaded 0 quests definitions" );
3385 sLog.outErrorDb("`quest_template` table is empty!");
3386 return;
3389 // create multimap previous quest for each existed quest
3390 // some quests can have many previous maps set by NextQuestId in previous quest
3391 // for example set of race quests can lead to single not race specific quest
3392 barGoLink bar((int) result->GetRowCount() );
3395 bar.step();
3396 Field *fields = result->Fetch();
3398 Quest * newQuest = new Quest(fields);
3399 mQuestTemplates[newQuest->GetQuestId()] = newQuest;
3400 } while( result->NextRow() );
3402 delete result;
3404 // Post processing
3406 std::map<uint32,uint32> usedMailTemplates;
3408 for (QuestMap::iterator iter = mQuestTemplates.begin(); iter != mQuestTemplates.end(); ++iter)
3410 Quest * qinfo = iter->second;
3412 // additional quest integrity checks (GO, creature_template and item_template must be loaded already)
3414 if (qinfo->GetQuestMethod() >= 3)
3416 sLog.outErrorDb("Quest %u has `Method` = %u, expected values are 0, 1 or 2.",qinfo->GetQuestId(),qinfo->GetQuestMethod());
3419 if (qinfo->QuestFlags & ~QUEST_MANGOS_FLAGS_DB_ALLOWED)
3421 sLog.outErrorDb("Quest %u has `SpecialFlags` = %u > max allowed value. Correct `SpecialFlags` to value <= %u",
3422 qinfo->GetQuestId(),qinfo->QuestFlags >> 24,QUEST_MANGOS_FLAGS_DB_ALLOWED >> 24);
3423 qinfo->QuestFlags &= QUEST_MANGOS_FLAGS_DB_ALLOWED;
3426 if (qinfo->QuestFlags & QUEST_FLAGS_DAILY && qinfo->QuestFlags & QUEST_FLAGS_WEEKLY)
3428 sLog.outErrorDb("Weekly Quest %u is marked as daily quest in `QuestFlags`, removed daily flag.",qinfo->GetQuestId());
3429 qinfo->QuestFlags &= ~QUEST_FLAGS_DAILY;
3432 if (qinfo->QuestFlags & QUEST_FLAGS_DAILY)
3434 if (!(qinfo->QuestFlags & QUEST_MANGOS_FLAGS_REPEATABLE))
3436 sLog.outErrorDb("Daily Quest %u not marked as repeatable in `SpecialFlags`, added.",qinfo->GetQuestId());
3437 qinfo->QuestFlags |= QUEST_MANGOS_FLAGS_REPEATABLE;
3441 if (qinfo->QuestFlags & QUEST_FLAGS_WEEKLY)
3443 if (!(qinfo->QuestFlags & QUEST_MANGOS_FLAGS_REPEATABLE))
3445 sLog.outErrorDb("Weekly Quest %u not marked as repeatable in `SpecialFlags`, added.",qinfo->GetQuestId());
3446 qinfo->QuestFlags |= QUEST_MANGOS_FLAGS_REPEATABLE;
3450 if (qinfo->QuestFlags & QUEST_FLAGS_AUTO_REWARDED)
3452 // at auto-reward can be rewarded only RewChoiceItemId[0]
3453 for(int j = 1; j < QUEST_REWARD_CHOICES_COUNT; ++j )
3455 if (uint32 id = qinfo->RewChoiceItemId[j])
3457 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item from `RewChoiceItemId%d` can't be rewarded with quest flag QUEST_FLAGS_AUTO_REWARDED.",
3458 qinfo->GetQuestId(),j+1,id,j+1);
3459 // no changes, quest ignore this data
3464 // client quest log visual (area case)
3465 if (qinfo->ZoneOrSort > 0)
3467 if (!GetAreaEntryByAreaID(qinfo->ZoneOrSort))
3469 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %u (zone case) but zone with this id does not exist.",
3470 qinfo->GetQuestId(),qinfo->ZoneOrSort);
3471 // no changes, quest not dependent from this value but can have problems at client
3474 // client quest log visual (sort case)
3475 if (qinfo->ZoneOrSort < 0)
3477 QuestSortEntry const* qSort = sQuestSortStore.LookupEntry(-int32(qinfo->ZoneOrSort));
3478 if (!qSort)
3480 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (sort case) but quest sort with this id does not exist.",
3481 qinfo->GetQuestId(),qinfo->ZoneOrSort);
3482 // no changes, quest not dependent from this value but can have problems at client (note some may be 0, we must allow this so no check)
3484 //check SkillOrClass value (class case).
3485 if (ClassByQuestSort(-int32(qinfo->ZoneOrSort)))
3487 // SkillOrClass should not have class case when class case already set in ZoneOrSort.
3488 if (qinfo->SkillOrClass < 0)
3490 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (class sort case) and `SkillOrClass` = %i (class case), redundant.",
3491 qinfo->GetQuestId(),qinfo->ZoneOrSort,qinfo->SkillOrClass);
3494 //check for proper SkillOrClass value (skill case)
3495 if (int32 skill_id = SkillByQuestSort(-int32(qinfo->ZoneOrSort)))
3497 // skill is positive value in SkillOrClass
3498 if (qinfo->SkillOrClass != skill_id )
3500 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (skill sort case) but `SkillOrClass` does not have a corresponding value (%i).",
3501 qinfo->GetQuestId(),qinfo->ZoneOrSort,skill_id);
3502 //override, and force proper value here?
3507 // SkillOrClass (class case)
3508 if (qinfo->SkillOrClass < 0)
3510 if (!sChrClassesStore.LookupEntry(-int32(qinfo->SkillOrClass)))
3512 sLog.outErrorDb("Quest %u has `SkillOrClass` = %i (class case) but class (%i) does not exist",
3513 qinfo->GetQuestId(),qinfo->SkillOrClass,-qinfo->SkillOrClass);
3516 // SkillOrClass (skill case)
3517 if (qinfo->SkillOrClass > 0)
3519 if (!sSkillLineStore.LookupEntry(qinfo->SkillOrClass))
3521 sLog.outErrorDb("Quest %u has `SkillOrClass` = %u (skill case) but skill (%i) does not exist",
3522 qinfo->GetQuestId(),qinfo->SkillOrClass,qinfo->SkillOrClass);
3526 if (qinfo->RequiredSkillValue)
3528 if (qinfo->RequiredSkillValue > sWorld.GetConfigMaxSkillValue())
3530 sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but max possible skill is %u, quest can't be done.",
3531 qinfo->GetQuestId(),qinfo->RequiredSkillValue,sWorld.GetConfigMaxSkillValue());
3532 // no changes, quest can't be done for this requirement
3535 if (qinfo->SkillOrClass <= 0)
3537 sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but `SkillOrClass` = %i (class case), value ignored.",
3538 qinfo->GetQuestId(),qinfo->RequiredSkillValue,qinfo->SkillOrClass);
3539 // no changes, quest can't be done for this requirement (fail at wrong skill id)
3542 // else Skill quests can have 0 skill level, this is ok
3544 if (qinfo->RepObjectiveFaction && !sFactionStore.LookupEntry(qinfo->RepObjectiveFaction))
3546 sLog.outErrorDb("Quest %u has `RepObjectiveFaction` = %u but faction template %u does not exist, quest can't be done.",
3547 qinfo->GetQuestId(),qinfo->RepObjectiveFaction,qinfo->RepObjectiveFaction);
3548 // no changes, quest can't be done for this requirement
3551 if (qinfo->RequiredMinRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMinRepFaction))
3553 sLog.outErrorDb("Quest %u has `RequiredMinRepFaction` = %u but faction template %u does not exist, quest can't be done.",
3554 qinfo->GetQuestId(),qinfo->RequiredMinRepFaction,qinfo->RequiredMinRepFaction);
3555 // no changes, quest can't be done for this requirement
3558 if (qinfo->RequiredMaxRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMaxRepFaction))
3560 sLog.outErrorDb("Quest %u has `RequiredMaxRepFaction` = %u but faction template %u does not exist, quest can't be done.",
3561 qinfo->GetQuestId(),qinfo->RequiredMaxRepFaction,qinfo->RequiredMaxRepFaction);
3562 // no changes, quest can't be done for this requirement
3565 if (qinfo->RequiredMinRepValue && qinfo->RequiredMinRepValue > ReputationMgr::Reputation_Cap)
3567 sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but max reputation is %u, quest can't be done.",
3568 qinfo->GetQuestId(),qinfo->RequiredMinRepValue,ReputationMgr::Reputation_Cap);
3569 // no changes, quest can't be done for this requirement
3572 if (qinfo->RequiredMinRepValue && qinfo->RequiredMaxRepValue && qinfo->RequiredMaxRepValue <= qinfo->RequiredMinRepValue)
3574 sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d and `RequiredMinRepValue` = %d, quest can't be done.",
3575 qinfo->GetQuestId(),qinfo->RequiredMaxRepValue,qinfo->RequiredMinRepValue);
3576 // no changes, quest can't be done for this requirement
3579 if (!qinfo->RepObjectiveFaction && qinfo->RepObjectiveValue > 0 )
3581 sLog.outErrorDb("Quest %u has `RepObjectiveValue` = %d but `RepObjectiveFaction` is 0, value has no effect",
3582 qinfo->GetQuestId(),qinfo->RepObjectiveValue);
3583 // warning
3586 if (!qinfo->RequiredMinRepFaction && qinfo->RequiredMinRepValue > 0 )
3588 sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but `RequiredMinRepFaction` is 0, value has no effect",
3589 qinfo->GetQuestId(),qinfo->RequiredMinRepValue);
3590 // warning
3593 if (!qinfo->RequiredMaxRepFaction && qinfo->RequiredMaxRepValue > 0 )
3595 sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d but `RequiredMaxRepFaction` is 0, value has no effect",
3596 qinfo->GetQuestId(),qinfo->RequiredMaxRepValue);
3597 // warning
3600 if (qinfo->CharTitleId && !sCharTitlesStore.LookupEntry(qinfo->CharTitleId))
3602 sLog.outErrorDb("Quest %u has `CharTitleId` = %u but CharTitle Id %u does not exist, quest can't be rewarded with title.",
3603 qinfo->GetQuestId(),qinfo->GetCharTitleId(),qinfo->GetCharTitleId());
3604 qinfo->CharTitleId = 0;
3605 // quest can't reward this title
3608 if (qinfo->SrcItemId)
3610 if (!sItemStorage.LookupEntry<ItemPrototype>(qinfo->SrcItemId))
3612 sLog.outErrorDb("Quest %u has `SrcItemId` = %u but item with entry %u does not exist, quest can't be done.",
3613 qinfo->GetQuestId(),qinfo->SrcItemId,qinfo->SrcItemId);
3614 qinfo->SrcItemId = 0; // quest can't be done for this requirement
3616 else if (qinfo->SrcItemCount==0)
3618 sLog.outErrorDb("Quest %u has `SrcItemId` = %u but `SrcItemCount` = 0, set to 1 but need fix in DB.",
3619 qinfo->GetQuestId(),qinfo->SrcItemId);
3620 qinfo->SrcItemCount = 1; // update to 1 for allow quest work for backward compatibility with DB
3623 else if (qinfo->SrcItemCount>0)
3625 sLog.outErrorDb("Quest %u has `SrcItemId` = 0 but `SrcItemCount` = %u, useless value.",
3626 qinfo->GetQuestId(),qinfo->SrcItemCount);
3627 qinfo->SrcItemCount=0; // no quest work changes in fact
3630 if (qinfo->SrcSpell)
3632 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->SrcSpell);
3633 if (!spellInfo)
3635 sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u doesn't exist, quest can't be done.",
3636 qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
3637 qinfo->SrcSpell = 0; // quest can't be done for this requirement
3639 else if (!SpellMgr::IsSpellValid(spellInfo))
3641 sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u is broken, quest can't be done.",
3642 qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
3643 qinfo->SrcSpell = 0; // quest can't be done for this requirement
3647 for(int j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j )
3649 if (uint32 id = qinfo->ReqItemId[j])
3651 if (qinfo->ReqItemCount[j] == 0)
3653 sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but `ReqItemCount%d` = 0, quest can't be done.",
3654 qinfo->GetQuestId(), j+1, id, j+1);
3655 // no changes, quest can't be done for this requirement
3658 qinfo->SetFlag(QUEST_MANGOS_FLAGS_DELIVER);
3660 if (!sItemStorage.LookupEntry<ItemPrototype>(id))
3662 sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but item with entry %u does not exist, quest can't be done.",
3663 qinfo->GetQuestId(), j+1, id, id);
3664 qinfo->ReqItemCount[j] = 0; // prevent incorrect work of quest
3667 else if (qinfo->ReqItemCount[j] > 0)
3669 sLog.outErrorDb("Quest %u has `ReqItemId%d` = 0 but `ReqItemCount%d` = %u, quest can't be done.",
3670 qinfo->GetQuestId(), j+1, j+1, qinfo->ReqItemCount[j]);
3671 qinfo->ReqItemCount[j] = 0; // prevent incorrect work of quest
3675 for(int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j )
3677 if (uint32 id = qinfo->ReqSourceId[j])
3679 if (!sItemStorage.LookupEntry<ItemPrototype>(id))
3681 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but item with entry %u does not exist, quest can't be done.",
3682 qinfo->GetQuestId(),j+1,id,id);
3683 // no changes, quest can't be done for this requirement
3686 else
3688 if (qinfo->ReqSourceCount[j]>0)
3690 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = 0 but `ReqSourceCount%d` = %u.",
3691 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqSourceCount[j]);
3692 // no changes, quest ignore this data
3697 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3699 if (uint32 id = qinfo->ReqSpell[j])
3701 SpellEntry const* spellInfo = sSpellStore.LookupEntry(id);
3702 if (!spellInfo)
3704 sLog.outErrorDb("Quest %u has `ReqSpellCast%d` = %u but spell %u does not exist, quest can't be done.",
3705 qinfo->GetQuestId(),j+1,id,id);
3706 continue;
3709 if (!qinfo->ReqCreatureOrGOId[j])
3711 bool found = false;
3712 for(int k = 0; k < MAX_EFFECT_INDEX; ++k)
3714 if ((spellInfo->Effect[k] == SPELL_EFFECT_QUEST_COMPLETE && uint32(spellInfo->EffectMiscValue[k]) == qinfo->QuestId) ||
3715 spellInfo->Effect[k] == SPELL_EFFECT_SEND_EVENT)
3717 found = true;
3718 break;
3722 if (found)
3724 if (!qinfo->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3726 sLog.outErrorDb("Spell (id: %u) have SPELL_EFFECT_QUEST_COMPLETE or SPELL_EFFECT_SEND_EVENT for quest %u and ReqCreatureOrGOId%d = 0, but quest not have flag QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT. Quest flags or ReqCreatureOrGOId%d must be fixed, quest modified to enable objective.",spellInfo->Id,qinfo->QuestId,j+1,j+1);
3728 // this will prevent quest completing without objective
3729 const_cast<Quest*>(qinfo)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3732 else
3734 sLog.outErrorDb("Quest %u has `ReqSpellCast%d` = %u and ReqCreatureOrGOId%d = 0 but spell %u does not have SPELL_EFFECT_QUEST_COMPLETE or SPELL_EFFECT_SEND_EVENT effect for this quest, quest can't be done.",
3735 qinfo->GetQuestId(),j+1,id,j+1,id);
3736 // no changes, quest can't be done for this requirement
3742 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3744 int32 id = qinfo->ReqCreatureOrGOId[j];
3745 if (id < 0 && !sGOStorage.LookupEntry<GameObjectInfo>(-id))
3747 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but gameobject %u does not exist, quest can't be done.",
3748 qinfo->GetQuestId(),j+1,id,uint32(-id));
3749 qinfo->ReqCreatureOrGOId[j] = 0; // quest can't be done for this requirement
3752 if (id > 0 && !sCreatureStorage.LookupEntry<CreatureInfo>(id))
3754 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but creature with entry %u does not exist, quest can't be done.",
3755 qinfo->GetQuestId(),j+1,id,uint32(id));
3756 qinfo->ReqCreatureOrGOId[j] = 0; // quest can't be done for this requirement
3759 if (id)
3761 // In fact SpeakTo and Kill are quite same: either you can speak to mob:SpeakTo or you can't:Kill/Cast
3763 qinfo->SetFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO);
3765 if (!qinfo->ReqCreatureOrGOCount[j])
3767 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %u but `ReqCreatureOrGOCount%d` = 0, quest can't be done.",
3768 qinfo->GetQuestId(),j+1,id,j+1);
3769 // no changes, quest can be incorrectly done, but we already report this
3772 else if (qinfo->ReqCreatureOrGOCount[j]>0)
3774 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = 0 but `ReqCreatureOrGOCount%d` = %u.",
3775 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqCreatureOrGOCount[j]);
3776 // no changes, quest ignore this data
3780 for(int j = 0; j < QUEST_REWARD_CHOICES_COUNT; ++j )
3782 if (uint32 id = qinfo->RewChoiceItemId[j])
3784 if (!sItemStorage.LookupEntry<ItemPrototype>(id))
3786 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3787 qinfo->GetQuestId(),j+1,id,id);
3788 qinfo->RewChoiceItemId[j] = 0; // no changes, quest will not reward this
3791 if (!qinfo->RewChoiceItemCount[j])
3793 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but `RewChoiceItemCount%d` = 0, quest can't be done.",
3794 qinfo->GetQuestId(),j+1,id,j+1);
3795 // no changes, quest can't be done
3798 else if (qinfo->RewChoiceItemCount[j]>0)
3800 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = 0 but `RewChoiceItemCount%d` = %u.",
3801 qinfo->GetQuestId(),j+1,j+1,qinfo->RewChoiceItemCount[j]);
3802 // no changes, quest ignore this data
3806 for(int j = 0; j < QUEST_REWARDS_COUNT; ++j )
3808 if (uint32 id = qinfo->RewItemId[j])
3810 if (!sItemStorage.LookupEntry<ItemPrototype>(id))
3812 sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3813 qinfo->GetQuestId(),j+1,id,id);
3814 qinfo->RewItemId[j] = 0; // no changes, quest will not reward this item
3817 if (!qinfo->RewItemCount[j])
3819 sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but `RewItemCount%d` = 0, quest will not reward this item.",
3820 qinfo->GetQuestId(),j+1,id,j+1);
3821 // no changes
3824 else if (qinfo->RewItemCount[j]>0)
3826 sLog.outErrorDb("Quest %u has `RewItemId%d` = 0 but `RewItemCount%d` = %u.",
3827 qinfo->GetQuestId(),j+1,j+1,qinfo->RewItemCount[j]);
3828 // no changes, quest ignore this data
3832 for(int j = 0; j < QUEST_REPUTATIONS_COUNT; ++j)
3834 if (qinfo->RewRepFaction[j])
3836 if (abs(qinfo->RewRepValueId[j]) > 9)
3837 sLog.outErrorDb("Quest %u has RewRepValueId%d = %i but value is not valid.", qinfo->GetQuestId(), j+1, qinfo->RewRepValueId[j]);
3839 if (!sFactionStore.LookupEntry(qinfo->RewRepFaction[j]))
3841 sLog.outErrorDb("Quest %u has `RewRepFaction%d` = %u but raw faction (faction.dbc) %u does not exist, quest will not reward reputation for this faction.",
3842 qinfo->GetQuestId(),j+1,qinfo->RewRepFaction[j] ,qinfo->RewRepFaction[j]);
3843 qinfo->RewRepFaction[j] = 0; // quest will not reward this
3846 else if (qinfo->RewRepValue[j] != 0)
3848 sLog.outErrorDb("Quest %u has `RewRepFaction%d` = 0 but `RewRepValue%d` = %i.",
3849 qinfo->GetQuestId(),j+1,j+1,qinfo->RewRepValue[j]);
3850 // no changes, quest ignore this data
3854 if (qinfo->RewSpell)
3856 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpell);
3858 if (!spellInfo)
3860 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u does not exist, spell removed as display reward.",
3861 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3862 qinfo->RewSpell = 0; // no spell reward will display for this quest
3864 else if (!SpellMgr::IsSpellValid(spellInfo))
3866 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u is broken, quest will not have a spell reward.",
3867 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3868 qinfo->RewSpell = 0; // no spell reward will display for this quest
3870 else if (GetTalentSpellCost(qinfo->RewSpell))
3872 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u is talent, quest will not have a spell reward.",
3873 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3874 qinfo->RewSpell = 0; // no spell reward will display for this quest
3878 if (qinfo->RewSpellCast)
3880 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpellCast);
3882 if (!spellInfo)
3884 sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u does not exist, quest will not have a spell reward.",
3885 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3886 qinfo->RewSpellCast = 0; // no spell will be casted on player
3888 else if (!SpellMgr::IsSpellValid(spellInfo))
3890 sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u is broken, quest will not have a spell reward.",
3891 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3892 qinfo->RewSpellCast = 0; // no spell will be casted on player
3894 else if (GetTalentSpellCost(qinfo->RewSpellCast))
3896 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u is talent, quest will not have a spell reward.",
3897 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3898 qinfo->RewSpellCast = 0; // no spell will be casted on player
3902 if (qinfo->RewMailTemplateId)
3904 if (!sMailTemplateStore.LookupEntry(qinfo->RewMailTemplateId))
3906 sLog.outErrorDb("Quest %u has `RewMailTemplateId` = %u but mail template %u does not exist, quest will not have a mail reward.",
3907 qinfo->GetQuestId(),qinfo->RewMailTemplateId,qinfo->RewMailTemplateId);
3908 qinfo->RewMailTemplateId = 0; // no mail will send to player
3909 qinfo->RewMailDelaySecs = 0; // no mail will send to player
3911 else if (usedMailTemplates.find(qinfo->RewMailTemplateId) != usedMailTemplates.end())
3913 std::map<uint32,uint32>::const_iterator used_mt_itr = usedMailTemplates.find(qinfo->RewMailTemplateId);
3914 sLog.outErrorDb("Quest %u has `RewMailTemplateId` = %u but mail template %u already used for quest %u, quest will not have a mail reward.",
3915 qinfo->GetQuestId(),qinfo->RewMailTemplateId,qinfo->RewMailTemplateId,used_mt_itr->second);
3916 qinfo->RewMailTemplateId = 0; // no mail will send to player
3917 qinfo->RewMailDelaySecs = 0; // no mail will send to player
3919 else
3920 usedMailTemplates[qinfo->RewMailTemplateId] = qinfo->GetQuestId();
3923 if (qinfo->NextQuestInChain)
3925 QuestMap::iterator qNextItr = mQuestTemplates.find(qinfo->NextQuestInChain);
3926 if (qNextItr == mQuestTemplates.end())
3928 sLog.outErrorDb("Quest %u has `NextQuestInChain` = %u but quest %u does not exist, quest chain will not work.",
3929 qinfo->GetQuestId(),qinfo->NextQuestInChain ,qinfo->NextQuestInChain );
3930 qinfo->NextQuestInChain = 0;
3932 else
3933 qNextItr->second->prevChainQuests.push_back(qinfo->GetQuestId());
3936 // fill additional data stores
3937 if (qinfo->PrevQuestId)
3939 if (mQuestTemplates.find(abs(qinfo->GetPrevQuestId())) == mQuestTemplates.end())
3941 sLog.outErrorDb("Quest %d has PrevQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetPrevQuestId());
3943 else
3945 qinfo->prevQuests.push_back(qinfo->PrevQuestId);
3949 if (qinfo->NextQuestId)
3951 QuestMap::iterator qNextItr = mQuestTemplates.find(abs(qinfo->GetNextQuestId()));
3952 if (qNextItr == mQuestTemplates.end())
3954 sLog.outErrorDb("Quest %d has NextQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetNextQuestId());
3956 else
3958 int32 signedQuestId = qinfo->NextQuestId < 0 ? -int32(qinfo->GetQuestId()) : int32(qinfo->GetQuestId());
3959 qNextItr->second->prevQuests.push_back(signedQuestId);
3963 if (qinfo->ExclusiveGroup)
3964 mExclusiveQuestGroups.insert(std::pair<int32, uint32>(qinfo->ExclusiveGroup, qinfo->GetQuestId()));
3965 if (qinfo->LimitTime)
3966 qinfo->SetFlag(QUEST_MANGOS_FLAGS_TIMED);
3969 // check QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT for spell with SPELL_EFFECT_QUEST_COMPLETE
3970 for (uint32 i = 0; i < sSpellStore.GetNumRows(); ++i)
3972 SpellEntry const *spellInfo = sSpellStore.LookupEntry(i);
3973 if (!spellInfo)
3974 continue;
3976 for(int j = 0; j < MAX_EFFECT_INDEX; ++j)
3978 if (spellInfo->Effect[j] != SPELL_EFFECT_QUEST_COMPLETE)
3979 continue;
3981 uint32 quest_id = spellInfo->EffectMiscValue[j];
3983 Quest const* quest = GetQuestTemplate(quest_id);
3985 // some quest referenced in spells not exist (outdated spells)
3986 if (!quest)
3987 continue;
3989 if (!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3991 sLog.outErrorDb("Spell (id: %u) have SPELL_EFFECT_QUEST_COMPLETE for quest %u , but quest does not have SpecialFlags QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT (2) set. Quest SpecialFlags should be corrected to enable this objective.", spellInfo->Id, quest_id);
3993 // The below forced alteration has been disabled because of spell 33824 / quest 10162.
3994 // A startup error will still occur with proper data in quest_template, but it will be possible to sucessfully complete the quest with the expected data.
3996 // this will prevent quest completing without objective
3997 // const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
4002 sLog.outString();
4003 sLog.outString( ">> Loaded %lu quests definitions", (unsigned long)mQuestTemplates.size() );
4006 void ObjectMgr::LoadQuestLocales()
4008 mQuestLocaleMap.clear(); // need for reload case
4010 QueryResult *result = WorldDatabase.Query("SELECT entry,"
4011 "Title_loc1,Details_loc1,Objectives_loc1,OfferRewardText_loc1,RequestItemsText_loc1,EndText_loc1,CompletedText_loc1,ObjectiveText1_loc1,ObjectiveText2_loc1,ObjectiveText3_loc1,ObjectiveText4_loc1,"
4012 "Title_loc2,Details_loc2,Objectives_loc2,OfferRewardText_loc2,RequestItemsText_loc2,EndText_loc2,CompletedText_loc2,ObjectiveText1_loc2,ObjectiveText2_loc2,ObjectiveText3_loc2,ObjectiveText4_loc2,"
4013 "Title_loc3,Details_loc3,Objectives_loc3,OfferRewardText_loc3,RequestItemsText_loc3,EndText_loc3,CompletedText_loc3,ObjectiveText1_loc3,ObjectiveText2_loc3,ObjectiveText3_loc3,ObjectiveText4_loc3,"
4014 "Title_loc4,Details_loc4,Objectives_loc4,OfferRewardText_loc4,RequestItemsText_loc4,EndText_loc4,CompletedText_loc4,ObjectiveText1_loc4,ObjectiveText2_loc4,ObjectiveText3_loc4,ObjectiveText4_loc4,"
4015 "Title_loc5,Details_loc5,Objectives_loc5,OfferRewardText_loc5,RequestItemsText_loc5,EndText_loc5,CompletedText_loc5,ObjectiveText1_loc5,ObjectiveText2_loc5,ObjectiveText3_loc5,ObjectiveText4_loc5,"
4016 "Title_loc6,Details_loc6,Objectives_loc6,OfferRewardText_loc6,RequestItemsText_loc6,EndText_loc6,CompletedText_loc6,ObjectiveText1_loc6,ObjectiveText2_loc6,ObjectiveText3_loc6,ObjectiveText4_loc6,"
4017 "Title_loc7,Details_loc7,Objectives_loc7,OfferRewardText_loc7,RequestItemsText_loc7,EndText_loc7,CompletedText_loc7,ObjectiveText1_loc7,ObjectiveText2_loc7,ObjectiveText3_loc7,ObjectiveText4_loc7,"
4018 "Title_loc8,Details_loc8,Objectives_loc8,OfferRewardText_loc8,RequestItemsText_loc8,EndText_loc8,CompletedText_loc8,ObjectiveText1_loc8,ObjectiveText2_loc8,ObjectiveText3_loc8,ObjectiveText4_loc8"
4019 " FROM locales_quest"
4022 if(!result)
4024 barGoLink bar(1);
4026 bar.step();
4028 sLog.outString();
4029 sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_quest` is empty.");
4030 return;
4033 barGoLink bar((int)result->GetRowCount());
4037 Field *fields = result->Fetch();
4038 bar.step();
4040 uint32 entry = fields[0].GetUInt32();
4042 QuestLocale& data = mQuestLocaleMap[entry];
4044 for(int i = 1; i < MAX_LOCALE; ++i)
4046 std::string str = fields[1+11*(i-1)].GetCppString();
4047 if(!str.empty())
4049 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4050 if(idx >= 0)
4052 if((int32)data.Title.size() <= idx)
4053 data.Title.resize(idx+1);
4055 data.Title[idx] = str;
4058 str = fields[1+11*(i-1)+1].GetCppString();
4059 if(!str.empty())
4061 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4062 if(idx >= 0)
4064 if((int32)data.Details.size() <= idx)
4065 data.Details.resize(idx+1);
4067 data.Details[idx] = str;
4070 str = fields[1+11*(i-1)+2].GetCppString();
4071 if(!str.empty())
4073 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4074 if(idx >= 0)
4076 if((int32)data.Objectives.size() <= idx)
4077 data.Objectives.resize(idx+1);
4079 data.Objectives[idx] = str;
4082 str = fields[1+11*(i-1)+3].GetCppString();
4083 if(!str.empty())
4085 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4086 if(idx >= 0)
4088 if((int32)data.OfferRewardText.size() <= idx)
4089 data.OfferRewardText.resize(idx+1);
4091 data.OfferRewardText[idx] = str;
4094 str = fields[1+11*(i-1)+4].GetCppString();
4095 if(!str.empty())
4097 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4098 if(idx >= 0)
4100 if((int32)data.RequestItemsText.size() <= idx)
4101 data.RequestItemsText.resize(idx+1);
4103 data.RequestItemsText[idx] = str;
4106 str = fields[1+11*(i-1)+5].GetCppString();
4107 if(!str.empty())
4109 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4110 if(idx >= 0)
4112 if((int32)data.EndText.size() <= idx)
4113 data.EndText.resize(idx+1);
4115 data.EndText[idx] = str;
4118 str = fields[1+11*(i-1)+6].GetCppString();
4119 if(!str.empty())
4121 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4122 if(idx >= 0)
4124 if((int32)data.CompletedText.size() <= idx)
4125 data.CompletedText.resize(idx+1);
4127 data.CompletedText[idx] = str;
4130 for(int k = 0; k < 4; ++k)
4132 str = fields[1+11*(i-1)+7+k].GetCppString();
4133 if(!str.empty())
4135 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4136 if(idx >= 0)
4138 if((int32)data.ObjectiveText[k].size() <= idx)
4139 data.ObjectiveText[k].resize(idx+1);
4141 data.ObjectiveText[k][idx] = str;
4146 } while (result->NextRow());
4148 delete result;
4150 sLog.outString();
4151 sLog.outString( ">> Loaded %lu Quest locale strings", (unsigned long)mQuestLocaleMap.size() );
4154 void ObjectMgr::LoadScripts(ScriptMapMap& scripts, char const* tablename)
4156 if(sWorld.IsScriptScheduled()) // function don't must be called in time scripts use.
4157 return;
4159 sLog.outString( "%s :", tablename);
4161 scripts.clear(); // need for reload support
4163 QueryResult *result = WorldDatabase.PQuery( "SELECT id, delay, command, datalong, datalong2, datalong3, datalong4, data_flags, dataint, x, y, z, o FROM %s", tablename );
4165 uint32 count = 0;
4167 if( !result )
4169 barGoLink bar( 1 );
4170 bar.step();
4172 sLog.outString();
4173 sLog.outString( ">> Loaded %u script definitions", count );
4174 return;
4177 barGoLink bar( (int)result->GetRowCount() );
4181 bar.step();
4183 Field *fields = result->Fetch();
4184 ScriptInfo tmp;
4185 tmp.id = fields[0].GetUInt32();
4186 tmp.delay = fields[1].GetUInt32();
4187 tmp.command = fields[2].GetUInt32();
4188 tmp.datalong = fields[3].GetUInt32();
4189 tmp.datalong2 = fields[4].GetUInt32();
4190 tmp.datalong3 = fields[5].GetUInt32();
4191 tmp.datalong4 = fields[6].GetUInt32();
4192 tmp.data_flags = fields[7].GetUInt32();
4193 tmp.dataint = fields[8].GetInt32();
4194 tmp.x = fields[9].GetFloat();
4195 tmp.y = fields[10].GetFloat();
4196 tmp.z = fields[11].GetFloat();
4197 tmp.o = fields[12].GetFloat();
4199 // generic command args check
4200 switch(tmp.command)
4202 case SCRIPT_COMMAND_TALK:
4204 if (tmp.datalong > CHAT_TYPE_ZONE_YELL)
4206 sLog.outErrorDb("Table `%s` has invalid CHAT_TYPE_ (datalong = %u) in SCRIPT_COMMAND_TALK for script id %u", tablename, tmp.datalong, tmp.id);
4207 continue;
4209 if (tmp.datalong2 && !GetCreatureTemplate(tmp.datalong2))
4211 sLog.outErrorDb("Table `%s` has datalong2 = %u in SCRIPT_COMMAND_TALK for script id %u, but this creature_template does not exist.", tablename, tmp.datalong2, tmp.id);
4212 continue;
4214 if (tmp.datalong2 && !tmp.datalong3)
4216 sLog.outErrorDb("Table `%s` has datalong2 = %u in SCRIPT_COMMAND_TALK for script id %u, but search radius is too small (datalong3 = %u).", tablename, tmp.datalong2, tmp.id, tmp.datalong3);
4217 continue;
4219 if (tmp.dataint == 0)
4221 sLog.outErrorDb("Table `%s` has invalid talk text id (dataint = %i) in SCRIPT_COMMAND_TALK for script id %u", tablename, tmp.dataint, tmp.id);
4222 continue;
4224 if (tmp.dataint < MIN_DB_SCRIPT_STRING_ID || tmp.dataint >= MAX_DB_SCRIPT_STRING_ID)
4226 sLog.outErrorDb("Table `%s` has out of range text id (dataint = %i expected %u-%u) in SCRIPT_COMMAND_TALK for script id %u", tablename, tmp.dataint, MIN_DB_SCRIPT_STRING_ID, MAX_DB_SCRIPT_STRING_ID, tmp.id);
4227 continue;
4230 // if(!GetMangosStringLocale(tmp.dataint)) will checked after db_script_string loading
4231 break;
4234 case SCRIPT_COMMAND_EMOTE:
4236 if(!sEmotesStore.LookupEntry(tmp.datalong))
4238 sLog.outErrorDb("Table `%s` has invalid emote id (datalong = %u) in SCRIPT_COMMAND_EMOTE for script id %u",tablename,tmp.datalong,tmp.id);
4239 continue;
4241 break;
4244 case SCRIPT_COMMAND_TELEPORT_TO:
4246 if(!sMapStore.LookupEntry(tmp.datalong))
4248 sLog.outErrorDb("Table `%s` has invalid map (Id: %u) in SCRIPT_COMMAND_TELEPORT_TO for script id %u",tablename,tmp.datalong,tmp.id);
4249 continue;
4252 if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
4254 sLog.outErrorDb("Table `%s` has invalid coordinates (X: %f Y: %f) in SCRIPT_COMMAND_TELEPORT_TO for script id %u",tablename,tmp.x,tmp.y,tmp.id);
4255 continue;
4257 break;
4260 case SCRIPT_COMMAND_KILL_CREDIT:
4262 if (!GetCreatureTemplate(tmp.datalong))
4264 sLog.outErrorDb("Table `%s` has invalid creature (Entry: %u) in SCRIPT_COMMAND_KILL_CREDIT for script id %u",tablename,tmp.datalong,tmp.id);
4265 continue;
4267 break;
4270 case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
4272 if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
4274 sLog.outErrorDb("Table `%s` has invalid coordinates (X: %f Y: %f) in SCRIPT_COMMAND_TEMP_SUMMON_CREATURE for script id %u",tablename,tmp.x,tmp.y,tmp.id);
4275 continue;
4278 if(!GetCreatureTemplate(tmp.datalong))
4280 sLog.outErrorDb("Table `%s` has invalid creature (Entry: %u) in SCRIPT_COMMAND_TEMP_SUMMON_CREATURE for script id %u",tablename,tmp.datalong,tmp.id);
4281 continue;
4283 break;
4286 case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
4288 GameObjectData const* data = GetGOData(tmp.datalong);
4289 if(!data)
4291 sLog.outErrorDb("Table `%s` has invalid gameobject (GUID: %u) in SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,tmp.datalong,tmp.id);
4292 continue;
4295 GameObjectInfo const* info = GetGameObjectInfo(data->id);
4296 if(!info)
4298 sLog.outErrorDb("Table `%s` has gameobject with invalid entry (GUID: %u Entry: %u) in SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,tmp.datalong,data->id,tmp.id);
4299 continue;
4302 if( info->type==GAMEOBJECT_TYPE_FISHINGNODE ||
4303 info->type==GAMEOBJECT_TYPE_FISHINGHOLE ||
4304 info->type==GAMEOBJECT_TYPE_DOOR ||
4305 info->type==GAMEOBJECT_TYPE_BUTTON ||
4306 info->type==GAMEOBJECT_TYPE_TRAP )
4308 sLog.outErrorDb("Table `%s` have gameobject type (%u) unsupported by command SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,info->id,tmp.id);
4309 continue;
4311 break;
4313 case SCRIPT_COMMAND_OPEN_DOOR:
4314 case SCRIPT_COMMAND_CLOSE_DOOR:
4316 GameObjectData const* data = GetGOData(tmp.datalong);
4317 if(!data)
4319 sLog.outErrorDb("Table `%s` has invalid gameobject (GUID: %u) in %s for script id %u",tablename,tmp.datalong,(tmp.command==SCRIPT_COMMAND_OPEN_DOOR ? "SCRIPT_COMMAND_OPEN_DOOR" : "SCRIPT_COMMAND_CLOSE_DOOR"),tmp.id);
4320 continue;
4323 GameObjectInfo const* info = GetGameObjectInfo(data->id);
4324 if(!info)
4326 sLog.outErrorDb("Table `%s` has gameobject with invalid entry (GUID: %u Entry: %u) in %s for script id %u",tablename,tmp.datalong,data->id,(tmp.command==SCRIPT_COMMAND_OPEN_DOOR ? "SCRIPT_COMMAND_OPEN_DOOR" : "SCRIPT_COMMAND_CLOSE_DOOR"),tmp.id);
4327 continue;
4330 if( info->type!=GAMEOBJECT_TYPE_DOOR)
4332 sLog.outErrorDb("Table `%s` has gameobject type (%u) non supported by command %s for script id %u",tablename,info->id,(tmp.command==SCRIPT_COMMAND_OPEN_DOOR ? "SCRIPT_COMMAND_OPEN_DOOR" : "SCRIPT_COMMAND_CLOSE_DOOR"),tmp.id);
4333 continue;
4336 break;
4338 case SCRIPT_COMMAND_QUEST_EXPLORED:
4340 Quest const* quest = GetQuestTemplate(tmp.datalong);
4341 if(!quest)
4343 sLog.outErrorDb("Table `%s` has invalid quest (ID: %u) in SCRIPT_COMMAND_QUEST_EXPLORED in `datalong` for script id %u",tablename,tmp.datalong,tmp.id);
4344 continue;
4347 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
4349 sLog.outErrorDb("Table `%s` has quest (ID: %u) in SCRIPT_COMMAND_QUEST_EXPLORED in `datalong` for script id %u, but quest not have flag QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT in quest flags. Script command or quest flags wrong. Quest modified to require objective.",tablename,tmp.datalong,tmp.id);
4351 // this will prevent quest completing without objective
4352 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
4354 // continue; - quest objective requirement set and command can be allowed
4357 if(float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
4359 sLog.outErrorDb("Table `%s` has too large distance (%u) for exploring objective complete in `datalong2` in SCRIPT_COMMAND_QUEST_EXPLORED in `datalong` for script id %u",
4360 tablename,tmp.datalong2,tmp.id);
4361 continue;
4364 if(tmp.datalong2 && float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
4366 sLog.outErrorDb("Table `%s` has too large distance (%u) for exploring objective complete in `datalong2` in SCRIPT_COMMAND_QUEST_EXPLORED in `datalong` for script id %u, max distance is %f or 0 for disable distance check",
4367 tablename,tmp.datalong2,tmp.id,DEFAULT_VISIBILITY_DISTANCE);
4368 continue;
4371 if(tmp.datalong2 && float(tmp.datalong2) < INTERACTION_DISTANCE)
4373 sLog.outErrorDb("Table `%s` has too small distance (%u) for exploring objective complete in `datalong2` in SCRIPT_COMMAND_QUEST_EXPLORED in `datalong` for script id %u, min distance is %f or 0 for disable distance check",
4374 tablename,tmp.datalong2,tmp.id,INTERACTION_DISTANCE);
4375 continue;
4378 break;
4381 case SCRIPT_COMMAND_REMOVE_AURA:
4383 if(!sSpellStore.LookupEntry(tmp.datalong))
4385 sLog.outErrorDb("Table `%s` using non-existent spell (id: %u) in SCRIPT_COMMAND_REMOVE_AURA or SCRIPT_COMMAND_CAST_SPELL for script id %u",
4386 tablename,tmp.datalong,tmp.id);
4387 continue;
4389 if(tmp.datalong2 & ~0x1) // 1 bits (0,1)
4391 sLog.outErrorDb("Table `%s` using unknown flags in datalong2 (%u)i n SCRIPT_COMMAND_CAST_SPELL for script id %u",
4392 tablename,tmp.datalong2,tmp.id);
4393 continue;
4395 break;
4397 case SCRIPT_COMMAND_CAST_SPELL:
4399 if(!sSpellStore.LookupEntry(tmp.datalong))
4401 sLog.outErrorDb("Table `%s` using non-existent spell (id: %u) in SCRIPT_COMMAND_REMOVE_AURA or SCRIPT_COMMAND_CAST_SPELL for script id %u",
4402 tablename,tmp.datalong,tmp.id);
4403 continue;
4405 if(tmp.datalong2 & ~0x3) // 2 bits
4407 sLog.outErrorDb("Table `%s` using unknown flags in datalong2 (%u)i n SCRIPT_COMMAND_CAST_SPELL for script id %u",
4408 tablename,tmp.datalong2,tmp.id);
4409 continue;
4411 break;
4413 case SCRIPT_COMMAND_CREATE_ITEM:
4415 if (!GetItemPrototype(tmp.datalong))
4417 sLog.outErrorDb("Table `%s` has nonexistent item (entry: %u) in SCRIPT_COMMAND_CREATE_ITEM for script id %u",
4418 tablename, tmp.datalong, tmp.id);
4419 continue;
4421 if (!tmp.datalong2)
4423 sLog.outErrorDb("Table `%s` SCRIPT_COMMAND_CREATE_ITEM but amount is %u for script id %u",
4424 tablename, tmp.datalong2, tmp.id);
4425 continue;
4427 break;
4429 case SCRIPT_COMMAND_DESPAWN_SELF:
4431 // for later, we might consider despawn by database guid, and define in datalong2 as option to despawn self.
4432 break;
4436 if (scripts.find(tmp.id) == scripts.end())
4438 ScriptMap emptyMap;
4439 scripts[tmp.id] = emptyMap;
4441 scripts[tmp.id].insert(std::pair<uint32, ScriptInfo>(tmp.delay, tmp));
4443 ++count;
4444 } while( result->NextRow() );
4446 delete result;
4448 sLog.outString();
4449 sLog.outString( ">> Loaded %u script definitions", count );
4452 void ObjectMgr::LoadGameObjectScripts()
4454 LoadScripts(sGameObjectScripts, "gameobject_scripts");
4456 // check ids
4457 for(ScriptMapMap::const_iterator itr = sGameObjectScripts.begin(); itr != sGameObjectScripts.end(); ++itr)
4459 if(!GetGOData(itr->first))
4460 sLog.outErrorDb("Table `gameobject_scripts` has not existing gameobject (GUID: %u) as script id",itr->first);
4464 void ObjectMgr::LoadQuestEndScripts()
4466 LoadScripts(sQuestEndScripts, "quest_end_scripts");
4468 // check ids
4469 for(ScriptMapMap::const_iterator itr = sQuestEndScripts.begin(); itr != sQuestEndScripts.end(); ++itr)
4471 if(!GetQuestTemplate(itr->first))
4472 sLog.outErrorDb("Table `quest_end_scripts` has not existing quest (Id: %u) as script id",itr->first);
4476 void ObjectMgr::LoadQuestStartScripts()
4478 LoadScripts(sQuestStartScripts,"quest_start_scripts");
4480 // check ids
4481 for(ScriptMapMap::const_iterator itr = sQuestStartScripts.begin(); itr != sQuestStartScripts.end(); ++itr)
4483 if(!GetQuestTemplate(itr->first))
4484 sLog.outErrorDb("Table `quest_start_scripts` has not existing quest (Id: %u) as script id",itr->first);
4488 void ObjectMgr::LoadSpellScripts()
4490 LoadScripts(sSpellScripts, "spell_scripts");
4492 // check ids
4493 for(ScriptMapMap::const_iterator itr = sSpellScripts.begin(); itr != sSpellScripts.end(); ++itr)
4495 SpellEntry const* spellInfo = sSpellStore.LookupEntry(itr->first);
4497 if(!spellInfo)
4499 sLog.outErrorDb("Table `spell_scripts` has not existing spell (Id: %u) as script id",itr->first);
4500 continue;
4503 //check for correct spellEffect
4504 bool found = false;
4505 for(int i = 0; i < MAX_EFFECT_INDEX; ++i)
4507 // skip empty effects
4508 if (!spellInfo->Effect[i])
4509 continue;
4511 if (spellInfo->Effect[i] == SPELL_EFFECT_SCRIPT_EFFECT)
4513 found = true;
4514 break;
4518 if (!found)
4519 sLog.outErrorDb("Table `spell_scripts` has unsupported spell (Id: %u) without SPELL_EFFECT_SCRIPT_EFFECT (%u) spell effect",itr->first,SPELL_EFFECT_SCRIPT_EFFECT);
4523 void ObjectMgr::LoadEventScripts()
4525 LoadScripts(sEventScripts, "event_scripts");
4527 std::set<uint32> evt_scripts;
4529 // Load all possible script entries from gameobjects
4530 for(uint32 i = 1; i < sGOStorage.MaxEntry; ++i)
4531 if (GameObjectInfo const * goInfo = sGOStorage.LookupEntry<GameObjectInfo>(i))
4532 if (uint32 eventId = goInfo->GetEventScriptId())
4533 evt_scripts.insert(eventId);
4535 // Load all possible script entries from spells
4536 for(uint32 i = 1; i < sSpellStore.GetNumRows(); ++i)
4538 SpellEntry const * spell = sSpellStore.LookupEntry(i);
4539 if (spell)
4541 for(int j = 0; j < MAX_EFFECT_INDEX; ++j)
4543 if( spell->Effect[j] == SPELL_EFFECT_SEND_EVENT )
4545 if (spell->EffectMiscValue[j])
4546 evt_scripts.insert(spell->EffectMiscValue[j]);
4552 for(size_t path_idx = 0; path_idx < sTaxiPathNodesByPath.size(); ++path_idx)
4554 for(size_t node_idx = 0; node_idx < sTaxiPathNodesByPath[path_idx].size(); ++node_idx)
4556 TaxiPathNodeEntry const& node = sTaxiPathNodesByPath[path_idx][node_idx];
4558 if (node.arrivalEventID)
4559 evt_scripts.insert(node.arrivalEventID);
4561 if (node.departureEventID)
4562 evt_scripts.insert(node.departureEventID);
4566 // Then check if all scripts are in above list of possible script entries
4567 for(ScriptMapMap::const_iterator itr = sEventScripts.begin(); itr != sEventScripts.end(); ++itr)
4569 std::set<uint32>::const_iterator itr2 = evt_scripts.find(itr->first);
4570 if (itr2 == evt_scripts.end())
4571 sLog.outErrorDb("Table `event_scripts` has script (Id: %u) not referring to any gameobject_template type 10 data2 field, type 3 data6 field, type 13 data 2 field or any spell effect %u or path taxi node data",
4572 itr->first, SPELL_EFFECT_SEND_EVENT);
4576 void ObjectMgr::LoadGossipScripts()
4578 LoadScripts(sGossipScripts, "gossip_scripts");
4580 // checks are done in LoadGossipMenuItems
4583 void ObjectMgr::LoadCreatureMovementScripts()
4585 LoadScripts(sCreatureMovementScripts, "creature_movement_scripts");
4587 // checks are done in WaypointManager::Load
4590 void ObjectMgr::LoadPageTexts()
4592 sPageTextStore.Free(); // for reload case
4594 sPageTextStore.Load();
4595 sLog.outString( ">> Loaded %u page texts", sPageTextStore.RecordCount );
4596 sLog.outString();
4598 for(uint32 i = 1; i < sPageTextStore.MaxEntry; ++i)
4600 // check data correctness
4601 PageText const* page = sPageTextStore.LookupEntry<PageText>(i);
4602 if(!page)
4603 continue;
4605 if(page->Next_Page && !sPageTextStore.LookupEntry<PageText>(page->Next_Page))
4607 sLog.outErrorDb("Page text (Id: %u) has not existing next page (Id:%u)", i,page->Next_Page);
4608 continue;
4611 // detect circular reference
4612 std::set<uint32> checkedPages;
4613 for(PageText const* pageItr = page; pageItr; pageItr = sPageTextStore.LookupEntry<PageText>(pageItr->Next_Page))
4615 if(!pageItr->Next_Page)
4616 break;
4617 checkedPages.insert(pageItr->Page_ID);
4618 if(checkedPages.find(pageItr->Next_Page)!=checkedPages.end())
4620 std::ostringstream ss;
4621 ss<< "The text page(s) ";
4622 for (std::set<uint32>::iterator itr= checkedPages.begin();itr!=checkedPages.end(); ++itr)
4623 ss << *itr << " ";
4624 ss << "create(s) a circular reference, which can cause the server to freeze. Changing Next_Page of page "
4625 << pageItr->Page_ID <<" to 0";
4626 sLog.outErrorDb("%s", ss.str().c_str());
4627 const_cast<PageText*>(pageItr)->Next_Page = 0;
4628 break;
4634 void ObjectMgr::LoadPageTextLocales()
4636 mPageTextLocaleMap.clear(); // need for reload case
4638 QueryResult *result = WorldDatabase.Query("SELECT entry,text_loc1,text_loc2,text_loc3,text_loc4,text_loc5,text_loc6,text_loc7,text_loc8 FROM locales_page_text");
4640 if(!result)
4642 barGoLink bar(1);
4644 bar.step();
4646 sLog.outString();
4647 sLog.outString(">> Loaded 0 PageText locale strings. DB table `locales_page_text` is empty.");
4648 return;
4651 barGoLink bar((int)result->GetRowCount());
4655 Field *fields = result->Fetch();
4656 bar.step();
4658 uint32 entry = fields[0].GetUInt32();
4660 PageTextLocale& data = mPageTextLocaleMap[entry];
4662 for(int i = 1; i < MAX_LOCALE; ++i)
4664 std::string str = fields[i].GetCppString();
4665 if(str.empty())
4666 continue;
4668 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4669 if(idx >= 0)
4671 if((int32)data.Text.size() <= idx)
4672 data.Text.resize(idx+1);
4674 data.Text[idx] = str;
4678 } while (result->NextRow());
4680 delete result;
4682 sLog.outString();
4683 sLog.outString( ">> Loaded %lu PageText locale strings", (unsigned long)mPageTextLocaleMap.size() );
4686 struct SQLInstanceLoader : public SQLStorageLoaderBase<SQLInstanceLoader>
4688 template<class D>
4689 void convert_from_str(uint32 /*field_pos*/, char *src, D &dst)
4691 dst = D(sObjectMgr.GetScriptId(src));
4695 void ObjectMgr::LoadInstanceTemplate()
4697 SQLInstanceLoader loader;
4698 loader.Load(sInstanceTemplate);
4700 for(uint32 i = 0; i < sInstanceTemplate.MaxEntry; i++)
4702 InstanceTemplate const* temp = GetInstanceTemplate(i);
4703 if (!temp)
4704 continue;
4706 MapEntry const* mapEntry = sMapStore.LookupEntry(temp->map);
4707 if (!mapEntry)
4709 sLog.outErrorDb("ObjectMgr::LoadInstanceTemplate: bad mapid %d for template!", temp->map);
4710 sInstanceTemplate.EraseEntry(i);
4711 continue;
4714 if (mapEntry->IsContinent())
4716 sLog.outErrorDb("ObjectMgr::LoadInstanceTemplate: continent mapid %d for template!", temp->map);
4717 sInstanceTemplate.EraseEntry(i);
4718 continue;
4721 if (temp->parent > 0)
4723 // check existence
4724 MapEntry const* parentEntry = sMapStore.LookupEntry(temp->parent);
4725 if (!parentEntry)
4727 sLog.outErrorDb("ObjectMgr::LoadInstanceTemplate: bad parent map id %u for instance template %d template!",
4728 parentEntry->MapID, temp->map);
4729 const_cast<InstanceTemplate*>(temp)->parent = 0;
4730 continue;
4733 if (parentEntry->IsContinent())
4735 sLog.outErrorDb("ObjectMgr::LoadInstanceTemplate: parent point to continent map id %u for instance template %d template, ignored, need be set only for non-continent parents!",
4736 parentEntry->MapID,temp->map);
4737 const_cast<InstanceTemplate*>(temp)->parent = 0;
4738 continue;
4743 sLog.outString( ">> Loaded %u Instance Template definitions", sInstanceTemplate.RecordCount );
4744 sLog.outString();
4747 GossipText const *ObjectMgr::GetGossipText(uint32 Text_ID) const
4749 GossipTextMap::const_iterator itr = mGossipText.find(Text_ID);
4750 if(itr != mGossipText.end())
4751 return &itr->second;
4752 return NULL;
4755 void ObjectMgr::LoadGossipText()
4757 QueryResult *result = WorldDatabase.Query( "SELECT * FROM npc_text" );
4759 int count = 0;
4760 if( !result )
4762 barGoLink bar( 1 );
4763 bar.step();
4765 sLog.outString();
4766 sLog.outString( ">> Loaded %u npc texts", count );
4767 return;
4770 int cic;
4772 barGoLink bar( (int)result->GetRowCount() );
4776 ++count;
4777 cic = 0;
4779 Field *fields = result->Fetch();
4781 bar.step();
4783 uint32 Text_ID = fields[cic++].GetUInt32();
4784 if(!Text_ID)
4786 sLog.outErrorDb("Table `npc_text` has record wit reserved id 0, ignore.");
4787 continue;
4790 GossipText& gText = mGossipText[Text_ID];
4792 for (int i=0; i< 8; i++)
4794 gText.Options[i].Text_0 = fields[cic++].GetCppString();
4795 gText.Options[i].Text_1 = fields[cic++].GetCppString();
4797 gText.Options[i].Language = fields[cic++].GetUInt32();
4798 gText.Options[i].Probability = fields[cic++].GetFloat();
4800 for(int j=0; j < 3; ++j)
4802 gText.Options[i].Emotes[j]._Delay = fields[cic++].GetUInt32();
4803 gText.Options[i].Emotes[j]._Emote = fields[cic++].GetUInt32();
4806 } while( result->NextRow() );
4808 sLog.outString();
4809 sLog.outString( ">> Loaded %u npc texts", count );
4810 delete result;
4813 void ObjectMgr::LoadNpcTextLocales()
4815 mNpcTextLocaleMap.clear(); // need for reload case
4817 QueryResult *result = WorldDatabase.Query("SELECT entry,"
4818 "Text0_0_loc1,Text0_1_loc1,Text1_0_loc1,Text1_1_loc1,Text2_0_loc1,Text2_1_loc1,Text3_0_loc1,Text3_1_loc1,Text4_0_loc1,Text4_1_loc1,Text5_0_loc1,Text5_1_loc1,Text6_0_loc1,Text6_1_loc1,Text7_0_loc1,Text7_1_loc1,"
4819 "Text0_0_loc2,Text0_1_loc2,Text1_0_loc2,Text1_1_loc2,Text2_0_loc2,Text2_1_loc2,Text3_0_loc2,Text3_1_loc1,Text4_0_loc2,Text4_1_loc2,Text5_0_loc2,Text5_1_loc2,Text6_0_loc2,Text6_1_loc2,Text7_0_loc2,Text7_1_loc2,"
4820 "Text0_0_loc3,Text0_1_loc3,Text1_0_loc3,Text1_1_loc3,Text2_0_loc3,Text2_1_loc3,Text3_0_loc3,Text3_1_loc1,Text4_0_loc3,Text4_1_loc3,Text5_0_loc3,Text5_1_loc3,Text6_0_loc3,Text6_1_loc3,Text7_0_loc3,Text7_1_loc3,"
4821 "Text0_0_loc4,Text0_1_loc4,Text1_0_loc4,Text1_1_loc4,Text2_0_loc4,Text2_1_loc4,Text3_0_loc4,Text3_1_loc1,Text4_0_loc4,Text4_1_loc4,Text5_0_loc4,Text5_1_loc4,Text6_0_loc4,Text6_1_loc4,Text7_0_loc4,Text7_1_loc4,"
4822 "Text0_0_loc5,Text0_1_loc5,Text1_0_loc5,Text1_1_loc5,Text2_0_loc5,Text2_1_loc5,Text3_0_loc5,Text3_1_loc1,Text4_0_loc5,Text4_1_loc5,Text5_0_loc5,Text5_1_loc5,Text6_0_loc5,Text6_1_loc5,Text7_0_loc5,Text7_1_loc5,"
4823 "Text0_0_loc6,Text0_1_loc6,Text1_0_loc6,Text1_1_loc6,Text2_0_loc6,Text2_1_loc6,Text3_0_loc6,Text3_1_loc1,Text4_0_loc6,Text4_1_loc6,Text5_0_loc6,Text5_1_loc6,Text6_0_loc6,Text6_1_loc6,Text7_0_loc6,Text7_1_loc6,"
4824 "Text0_0_loc7,Text0_1_loc7,Text1_0_loc7,Text1_1_loc7,Text2_0_loc7,Text2_1_loc7,Text3_0_loc7,Text3_1_loc1,Text4_0_loc7,Text4_1_loc7,Text5_0_loc7,Text5_1_loc7,Text6_0_loc7,Text6_1_loc7,Text7_0_loc7,Text7_1_loc7, "
4825 "Text0_0_loc8,Text0_1_loc8,Text1_0_loc8,Text1_1_loc8,Text2_0_loc8,Text2_1_loc8,Text3_0_loc8,Text3_1_loc1,Text4_0_loc8,Text4_1_loc8,Text5_0_loc8,Text5_1_loc8,Text6_0_loc8,Text6_1_loc8,Text7_0_loc8,Text7_1_loc8 "
4826 " FROM locales_npc_text");
4828 if(!result)
4830 barGoLink bar(1);
4832 bar.step();
4834 sLog.outString();
4835 sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_npc_text` is empty.");
4836 return;
4839 barGoLink bar((int)result->GetRowCount());
4843 Field *fields = result->Fetch();
4844 bar.step();
4846 uint32 entry = fields[0].GetUInt32();
4848 NpcTextLocale& data = mNpcTextLocaleMap[entry];
4850 for(int i=1; i<MAX_LOCALE; ++i)
4852 for(int j=0; j<8; ++j)
4854 std::string str0 = fields[1+8*2*(i-1)+2*j].GetCppString();
4855 if(!str0.empty())
4857 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4858 if(idx >= 0)
4860 if((int32)data.Text_0[j].size() <= idx)
4861 data.Text_0[j].resize(idx+1);
4863 data.Text_0[j][idx] = str0;
4866 std::string str1 = fields[1+8*2*(i-1)+2*j+1].GetCppString();
4867 if(!str1.empty())
4869 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4870 if(idx >= 0)
4872 if((int32)data.Text_1[j].size() <= idx)
4873 data.Text_1[j].resize(idx+1);
4875 data.Text_1[j][idx] = str1;
4880 } while (result->NextRow());
4882 delete result;
4884 sLog.outString();
4885 sLog.outString( ">> Loaded %lu NpcText locale strings", (unsigned long)mNpcTextLocaleMap.size() );
4888 //not very fast function but it is called only once a day, or on starting-up
4889 void ObjectMgr::ReturnOrDeleteOldMails(bool serverUp)
4891 time_t basetime = time(NULL);
4892 DEBUG_LOG("Returning mails current time: hour: %d, minute: %d, second: %d ", localtime(&basetime)->tm_hour, localtime(&basetime)->tm_min, localtime(&basetime)->tm_sec);
4893 //delete all old mails without item and without body immediately, if starting server
4894 if (!serverUp)
4895 CharacterDatabase.PExecute("DELETE FROM mail WHERE expire_time < '" UI64FMTD "' AND has_items = '0' AND body = ''", (uint64)basetime);
4896 // 0 1 2 3 4 5 6 7 8
4897 QueryResult* result = CharacterDatabase.PQuery("SELECT id,messageType,sender,receiver,has_items,expire_time,cod,checked,mailTemplateId FROM mail WHERE expire_time < '" UI64FMTD "'", (uint64)basetime);
4898 if ( !result )
4900 barGoLink bar(1);
4901 bar.step();
4902 sLog.outString();
4903 sLog.outString(">> Only expired mails (need to be return or delete) or DB table `mail` is empty.");
4904 return; // any mails need to be returned or deleted
4907 //std::ostringstream delitems, delmails; //will be here for optimization
4908 //bool deletemail = false, deleteitem = false;
4909 //delitems << "DELETE FROM item_instance WHERE guid IN ( ";
4910 //delmails << "DELETE FROM mail WHERE id IN ( "
4912 barGoLink bar( (int)result->GetRowCount() );
4913 uint32 count = 0;
4914 Field *fields;
4918 bar.step();
4920 fields = result->Fetch();
4921 Mail *m = new Mail;
4922 m->messageID = fields[0].GetUInt32();
4923 m->messageType = fields[1].GetUInt8();
4924 m->sender = fields[2].GetUInt32();
4925 m->receiver = fields[3].GetUInt32();
4926 bool has_items = fields[4].GetBool();
4927 m->expire_time = (time_t)fields[5].GetUInt64();
4928 m->deliver_time = 0;
4929 m->COD = fields[6].GetUInt32();
4930 m->checked = fields[7].GetUInt32();
4931 m->mailTemplateId = fields[8].GetInt16();
4933 Player *pl = 0;
4934 if (serverUp)
4935 pl = GetPlayer((uint64)m->receiver);
4936 if (pl)
4937 { //this code will run very improbably (the time is between 4 and 5 am, in game is online a player, who has old mail
4938 //his in mailbox and he has already listed his mails )
4939 delete m;
4940 continue;
4942 //delete or return mail:
4943 if (has_items)
4945 QueryResult *resultItems = CharacterDatabase.PQuery("SELECT item_guid,item_template FROM mail_items WHERE mail_id='%u'", m->messageID);
4946 if(resultItems)
4950 Field *fields2 = resultItems->Fetch();
4952 uint32 item_guid_low = fields2[0].GetUInt32();
4953 uint32 item_template = fields2[1].GetUInt32();
4955 m->AddItem(item_guid_low, item_template);
4957 while (resultItems->NextRow());
4959 delete resultItems;
4961 //if it is mail from AH, it shouldn't be returned, but deleted
4962 if (m->messageType != MAIL_NORMAL || m->messageType == MAIL_AUCTION || (m->checked & (MAIL_CHECK_MASK_COD_PAYMENT | MAIL_CHECK_MASK_RETURNED)))
4964 // mail open and then not returned
4965 for(std::vector<MailItemInfo>::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
4966 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
4968 else
4970 //mail will be returned:
4971 CharacterDatabase.PExecute("UPDATE mail SET sender = '%u', receiver = '%u', expire_time = '" UI64FMTD "', deliver_time = '" UI64FMTD "',cod = '0', checked = '%u' WHERE id = '%u'", m->receiver, m->sender, (uint64)(basetime + 30*DAY), (uint64)basetime, MAIL_CHECK_MASK_RETURNED, m->messageID);
4972 delete m;
4973 continue;
4977 //deletemail = true;
4978 //delmails << m->messageID << ", ";
4979 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
4980 delete m;
4981 ++count;
4982 } while (result->NextRow());
4983 delete result;
4985 sLog.outString();
4986 sLog.outString( ">> Loaded %u mails", count );
4989 void ObjectMgr::LoadQuestAreaTriggers()
4991 mQuestAreaTriggerMap.clear(); // need for reload case
4993 QueryResult *result = WorldDatabase.Query( "SELECT id,quest FROM areatrigger_involvedrelation" );
4995 uint32 count = 0;
4997 if (!result)
4999 barGoLink bar( 1 );
5000 bar.step();
5002 sLog.outString();
5003 sLog.outString( ">> Loaded %u quest trigger points", count );
5004 return;
5007 barGoLink bar((int) result->GetRowCount() );
5011 ++count;
5012 bar.step();
5014 Field *fields = result->Fetch();
5016 uint32 trigger_ID = fields[0].GetUInt32();
5017 uint32 quest_ID = fields[1].GetUInt32();
5019 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(trigger_ID);
5020 if (!atEntry)
5022 sLog.outErrorDb("Table `areatrigger_involvedrelation` has area trigger (ID: %u) not listed in `AreaTrigger.dbc`.", trigger_ID);
5023 continue;
5026 Quest const* quest = GetQuestTemplate(quest_ID);
5027 if (!quest)
5029 sLog.outErrorDb("Table `areatrigger_involvedrelation` has record (id: %u) for not existing quest %u",trigger_ID,quest_ID);
5030 continue;
5033 if (!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
5035 sLog.outErrorDb("Table `areatrigger_involvedrelation` has record (id: %u) for not quest %u, but quest not have flag QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT. Trigger or quest flags must be fixed, quest modified to require objective.",trigger_ID,quest_ID);
5037 // this will prevent quest completing without objective
5038 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
5040 // continue; - quest modified to required objective and trigger can be allowed.
5043 mQuestAreaTriggerMap[trigger_ID] = quest_ID;
5045 } while( result->NextRow() );
5047 delete result;
5049 sLog.outString();
5050 sLog.outString( ">> Loaded %u quest trigger points", count );
5053 void ObjectMgr::LoadTavernAreaTriggers()
5055 mTavernAreaTriggerSet.clear(); // need for reload case
5057 QueryResult *result = WorldDatabase.Query("SELECT id FROM areatrigger_tavern");
5059 uint32 count = 0;
5061 if (!result)
5063 barGoLink bar( 1 );
5064 bar.step();
5066 sLog.outString();
5067 sLog.outString( ">> Loaded %u tavern triggers", count );
5068 return;
5071 barGoLink bar( (int)result->GetRowCount() );
5075 ++count;
5076 bar.step();
5078 Field *fields = result->Fetch();
5080 uint32 Trigger_ID = fields[0].GetUInt32();
5082 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
5083 if (!atEntry)
5085 sLog.outErrorDb("Table `areatrigger_tavern` has area trigger (ID:%u) not listed in `AreaTrigger.dbc`.", Trigger_ID);
5086 continue;
5089 mTavernAreaTriggerSet.insert(Trigger_ID);
5090 } while( result->NextRow() );
5092 delete result;
5094 sLog.outString();
5095 sLog.outString( ">> Loaded %u tavern triggers", count );
5098 void ObjectMgr::LoadAreaTriggerScripts()
5100 mAreaTriggerScripts.clear(); // need for reload case
5101 QueryResult *result = WorldDatabase.Query("SELECT entry, ScriptName FROM areatrigger_scripts");
5103 uint32 count = 0;
5105 if (!result)
5107 barGoLink bar( 1 );
5108 bar.step();
5110 sLog.outString();
5111 sLog.outString( ">> Loaded %u areatrigger scripts", count );
5112 return;
5115 barGoLink bar( (int)result->GetRowCount() );
5119 ++count;
5120 bar.step();
5122 Field *fields = result->Fetch();
5124 uint32 Trigger_ID = fields[0].GetUInt32();
5125 const char *scriptName = fields[1].GetString();
5127 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
5128 if (!atEntry)
5130 sLog.outErrorDb("Table `areatrigger_scripts` has area trigger (ID:%u) not listed in `AreaTrigger.dbc`.", Trigger_ID);
5131 continue;
5134 mAreaTriggerScripts[Trigger_ID] = GetScriptId(scriptName);
5135 } while( result->NextRow() );
5137 delete result;
5139 sLog.outString();
5140 sLog.outString( ">> Loaded %u areatrigger scripts", count );
5143 uint32 ObjectMgr::GetNearestTaxiNode( float x, float y, float z, uint32 mapid, uint32 team )
5145 bool found = false;
5146 float dist;
5147 uint32 id = 0;
5149 for(uint32 i = 1; i < sTaxiNodesStore.GetNumRows(); ++i)
5151 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(i);
5152 if(!node || node->map_id != mapid || !node->MountCreatureID[team == ALLIANCE ? 1 : 0])
5153 continue;
5155 uint8 field = (uint8)((i - 1) / 32);
5156 uint32 submask = 1<<((i-1)%32);
5158 // skip not taxi network nodes
5159 if((sTaxiNodesMask[field] & submask)==0)
5160 continue;
5162 float dist2 = (node->x - x)*(node->x - x)+(node->y - y)*(node->y - y)+(node->z - z)*(node->z - z);
5163 if(found)
5165 if(dist2 < dist)
5167 dist = dist2;
5168 id = i;
5171 else
5173 found = true;
5174 dist = dist2;
5175 id = i;
5179 return id;
5182 void ObjectMgr::GetTaxiPath( uint32 source, uint32 destination, uint32 &path, uint32 &cost)
5184 TaxiPathSetBySource::iterator src_i = sTaxiPathSetBySource.find(source);
5185 if(src_i==sTaxiPathSetBySource.end())
5187 path = 0;
5188 cost = 0;
5189 return;
5192 TaxiPathSetForSource& pathSet = src_i->second;
5194 TaxiPathSetForSource::iterator dest_i = pathSet.find(destination);
5195 if(dest_i==pathSet.end())
5197 path = 0;
5198 cost = 0;
5199 return;
5202 cost = dest_i->second.price;
5203 path = dest_i->second.ID;
5206 uint32 ObjectMgr::GetTaxiMountDisplayId( uint32 id, uint32 team, bool allowed_alt_team /* = false */)
5208 uint16 mount_entry = 0;
5210 // select mount creature id
5211 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(id);
5212 if(node)
5214 if (team == ALLIANCE)
5216 mount_entry = node->MountCreatureID[1];
5217 if(!mount_entry && allowed_alt_team)
5218 mount_entry = node->MountCreatureID[0];
5220 else if (team == HORDE)
5222 mount_entry = node->MountCreatureID[0];
5224 if(!mount_entry && allowed_alt_team)
5225 mount_entry = node->MountCreatureID[1];
5229 CreatureInfo const *mount_info = GetCreatureTemplate(mount_entry);
5230 if (!mount_info)
5231 return 0;
5233 uint16 mount_id = ChooseDisplayId(team,mount_info);
5234 if (!mount_id)
5235 return 0;
5237 CreatureModelInfo const *minfo = GetCreatureModelRandomGender(mount_id);
5238 if (minfo)
5239 mount_id = minfo->modelid;
5241 return mount_id;
5244 void ObjectMgr::LoadGraveyardZones()
5246 mGraveYardMap.clear(); // need for reload case
5248 QueryResult *result = WorldDatabase.Query("SELECT id,ghost_zone,faction FROM game_graveyard_zone");
5250 uint32 count = 0;
5252 if( !result )
5254 barGoLink bar( 1 );
5255 bar.step();
5257 sLog.outString();
5258 sLog.outString( ">> Loaded %u graveyard-zone links", count );
5259 return;
5262 barGoLink bar( (int)result->GetRowCount() );
5266 ++count;
5267 bar.step();
5269 Field *fields = result->Fetch();
5271 uint32 safeLocId = fields[0].GetUInt32();
5272 uint32 zoneId = fields[1].GetUInt32();
5273 uint32 team = fields[2].GetUInt32();
5275 WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(safeLocId);
5276 if(!entry)
5278 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",safeLocId);
5279 continue;
5282 AreaTableEntry const *areaEntry = GetAreaEntryByAreaID(zoneId);
5283 if(!areaEntry)
5285 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing zone id (%u), skipped.",zoneId);
5286 continue;
5289 if(areaEntry->zone != 0)
5291 sLog.outErrorDb("Table `game_graveyard_zone` has record subzone id (%u) instead of zone, skipped.",zoneId);
5292 continue;
5295 if(team!=0 && team!=HORDE && team!=ALLIANCE)
5297 sLog.outErrorDb("Table `game_graveyard_zone` has record for non player faction (%u), skipped.",team);
5298 continue;
5301 if(!AddGraveYardLink(safeLocId,zoneId,team,false))
5302 sLog.outErrorDb("Table `game_graveyard_zone` has a duplicate record for Graveyard (ID: %u) and Zone (ID: %u), skipped.",safeLocId,zoneId);
5303 } while( result->NextRow() );
5305 delete result;
5307 sLog.outString();
5308 sLog.outString( ">> Loaded %u graveyard-zone links", count );
5311 WorldSafeLocsEntry const *ObjectMgr::GetClosestGraveYard(float x, float y, float z, uint32 MapId, uint32 team)
5313 // search for zone associated closest graveyard
5314 uint32 zoneId = sMapMgr.GetZoneId(MapId,x,y,z);
5316 // Simulate std. algorithm:
5317 // found some graveyard associated to (ghost_zone,ghost_map)
5319 // if mapId == graveyard.mapId (ghost in plain zone or city or battleground) and search graveyard at same map
5320 // then check faction
5321 // if mapId != graveyard.mapId (ghost in instance) and search any graveyard associated
5322 // then check faction
5323 GraveYardMap::const_iterator graveLow = mGraveYardMap.lower_bound(zoneId);
5324 GraveYardMap::const_iterator graveUp = mGraveYardMap.upper_bound(zoneId);
5325 if(graveLow==graveUp)
5327 sLog.outErrorDb("Table `game_graveyard_zone` incomplete: Zone %u Team %u does not have a linked graveyard.",zoneId,team);
5328 return NULL;
5331 // at corpse map
5332 bool foundNear = false;
5333 float distNear;
5334 WorldSafeLocsEntry const* entryNear = NULL;
5336 // at entrance map for corpse map
5337 bool foundEntr = false;
5338 float distEntr;
5339 WorldSafeLocsEntry const* entryEntr = NULL;
5341 // some where other
5342 WorldSafeLocsEntry const* entryFar = NULL;
5344 MapEntry const* mapEntry = sMapStore.LookupEntry(MapId);
5346 for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
5348 GraveYardData const& data = itr->second;
5350 WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(data.safeLocId);
5351 if(!entry)
5353 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",data.safeLocId);
5354 continue;
5357 // skip enemy faction graveyard
5358 // team == 0 case can be at call from .neargrave
5359 if(data.team != 0 && team != 0 && data.team != team)
5360 continue;
5362 // find now nearest graveyard at other (continent) map
5363 if(MapId != entry->map_id)
5365 // if find graveyard at different map from where entrance placed (or no entrance data), use any first
5366 if (!mapEntry ||
5367 mapEntry->ghost_entrance_map < 0 ||
5368 mapEntry->ghost_entrance_map != entry->map_id ||
5369 (mapEntry->ghost_entrance_x == 0 && mapEntry->ghost_entrance_y == 0))
5371 // not have any coordinates for check distance anyway
5372 entryFar = entry;
5373 continue;
5376 // at entrance map calculate distance (2D);
5377 float dist2 = (entry->x - mapEntry->ghost_entrance_x)*(entry->x - mapEntry->ghost_entrance_x)
5378 +(entry->y - mapEntry->ghost_entrance_y)*(entry->y - mapEntry->ghost_entrance_y);
5379 if(foundEntr)
5381 if(dist2 < distEntr)
5383 distEntr = dist2;
5384 entryEntr = entry;
5387 else
5389 foundEntr = true;
5390 distEntr = dist2;
5391 entryEntr = entry;
5394 // find now nearest graveyard at same map
5395 else
5397 float dist2 = (entry->x - x)*(entry->x - x)+(entry->y - y)*(entry->y - y)+(entry->z - z)*(entry->z - z);
5398 if(foundNear)
5400 if(dist2 < distNear)
5402 distNear = dist2;
5403 entryNear = entry;
5406 else
5408 foundNear = true;
5409 distNear = dist2;
5410 entryNear = entry;
5415 if(entryNear)
5416 return entryNear;
5418 if(entryEntr)
5419 return entryEntr;
5421 return entryFar;
5424 GraveYardData const* ObjectMgr::FindGraveYardData(uint32 id, uint32 zoneId)
5426 GraveYardMap::const_iterator graveLow = mGraveYardMap.lower_bound(zoneId);
5427 GraveYardMap::const_iterator graveUp = mGraveYardMap.upper_bound(zoneId);
5429 for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
5431 if(itr->second.safeLocId==id)
5432 return &itr->second;
5435 return NULL;
5438 bool ObjectMgr::AddGraveYardLink(uint32 id, uint32 zoneId, uint32 team, bool inDB)
5440 if(FindGraveYardData(id,zoneId))
5441 return false;
5443 // add link to loaded data
5444 GraveYardData data;
5445 data.safeLocId = id;
5446 data.team = team;
5448 mGraveYardMap.insert(GraveYardMap::value_type(zoneId,data));
5450 // add link to DB
5451 if(inDB)
5453 WorldDatabase.PExecuteLog("INSERT INTO game_graveyard_zone ( id,ghost_zone,faction) "
5454 "VALUES ('%u', '%u','%u')",id,zoneId,team);
5457 return true;
5460 void ObjectMgr::LoadAreaTriggerTeleports()
5462 mAreaTriggers.clear(); // need for reload case
5464 uint32 count = 0;
5466 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13
5467 QueryResult *result = WorldDatabase.Query("SELECT id, required_level, required_item, required_item2, heroic_key, heroic_key2, required_quest_done, required_quest_done_heroic, required_failed_text, target_map, target_position_x, target_position_y, target_position_z, target_orientation FROM areatrigger_teleport");
5468 if (!result)
5471 barGoLink bar( 1 );
5473 bar.step();
5475 sLog.outString();
5476 sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
5477 return;
5480 barGoLink bar( (int)result->GetRowCount() );
5484 Field *fields = result->Fetch();
5486 bar.step();
5488 ++count;
5490 uint32 Trigger_ID = fields[0].GetUInt32();
5492 AreaTrigger at;
5494 at.requiredLevel = fields[1].GetUInt8();
5495 at.requiredItem = fields[2].GetUInt32();
5496 at.requiredItem2 = fields[3].GetUInt32();
5497 at.heroicKey = fields[4].GetUInt32();
5498 at.heroicKey2 = fields[5].GetUInt32();
5499 at.requiredQuest = fields[6].GetUInt32();
5500 at.requiredQuestHeroic = fields[7].GetUInt32();
5501 at.requiredFailedText = fields[8].GetCppString();
5502 at.target_mapId = fields[9].GetUInt32();
5503 at.target_X = fields[10].GetFloat();
5504 at.target_Y = fields[11].GetFloat();
5505 at.target_Z = fields[12].GetFloat();
5506 at.target_Orientation = fields[13].GetFloat();
5508 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
5509 if (!atEntry)
5511 sLog.outErrorDb("Table `areatrigger_teleport` has area trigger (ID:%u) not listed in `AreaTrigger.dbc`.", Trigger_ID);
5512 continue;
5515 if (at.requiredItem)
5517 ItemPrototype const *pProto = GetItemPrototype(at.requiredItem);
5518 if (!pProto)
5520 sLog.outError("Table `areatrigger_teleport` has not existed key item %u for trigger %u, removing key requirement.", at.requiredItem, Trigger_ID);
5521 at.requiredItem = 0;
5525 if (at.requiredItem2)
5527 ItemPrototype const *pProto = GetItemPrototype(at.requiredItem2);
5528 if(!pProto)
5530 sLog.outError("Table `areatrigger_teleport` has not existed second key item %u for trigger %u, remove key requirement.", at.requiredItem2, Trigger_ID);
5531 at.requiredItem2 = 0;
5535 if (at.heroicKey)
5537 ItemPrototype const *pProto = GetItemPrototype(at.heroicKey);
5538 if (!pProto)
5540 sLog.outError("Table `areatrigger_teleport` has not existed heroic key item %u for trigger %u, remove key requirement.", at.heroicKey, Trigger_ID);
5541 at.heroicKey = 0;
5545 if (at.heroicKey2)
5547 ItemPrototype const *pProto = GetItemPrototype(at.heroicKey2);
5548 if (!pProto)
5550 sLog.outError("Table `areatrigger_teleport` has not existed heroic second key item %u for trigger %u, remove key requirement.", at.heroicKey2, Trigger_ID);
5551 at.heroicKey2 = 0;
5555 if (at.requiredQuest)
5557 QuestMap::iterator qReqItr = mQuestTemplates.find(at.requiredQuest);
5558 if (qReqItr == mQuestTemplates.end())
5560 sLog.outErrorDb("Table `areatrigger_teleport` has not existed required quest %u for trigger %u, remove quest done requirement.",at.requiredQuest,Trigger_ID);
5561 at.requiredQuest = 0;
5565 if (at.requiredQuestHeroic)
5567 QuestMap::iterator qReqItr = mQuestTemplates.find(at.requiredQuestHeroic);
5568 if (qReqItr == mQuestTemplates.end())
5570 sLog.outErrorDb("Table `areatrigger_teleport` has not existed required heroic quest %u for trigger %u, remove quest done requirement.",at.requiredQuestHeroic,Trigger_ID);
5571 at.requiredQuestHeroic = 0;
5575 MapEntry const* mapEntry = sMapStore.LookupEntry(at.target_mapId);
5576 if (!mapEntry)
5578 sLog.outErrorDb("Table `areatrigger_teleport` has not existed target map (ID: %u) for Area trigger (ID:%u).", at.target_mapId, Trigger_ID);
5579 continue;
5582 if (at.target_X==0 && at.target_Y==0 && at.target_Z==0)
5584 sLog.outErrorDb("Table `areatrigger_teleport` has area trigger (ID:%u) without target coordinates.",Trigger_ID);
5585 continue;
5588 mAreaTriggers[Trigger_ID] = at;
5590 } while( result->NextRow() );
5592 delete result;
5594 sLog.outString();
5595 sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
5599 * Searches for the areatrigger which teleports players out of the given map (only direct to continent)
5601 AreaTrigger const* ObjectMgr::GetGoBackTrigger(uint32 map_id) const
5603 const MapEntry *mapEntry = sMapStore.LookupEntry(map_id);
5604 if(!mapEntry) return NULL;
5605 for (AreaTriggerMap::const_iterator itr = mAreaTriggers.begin(); itr != mAreaTriggers.end(); ++itr)
5607 if(itr->second.target_mapId == mapEntry->ghost_entrance_map)
5609 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(itr->first);
5610 if(atEntry && atEntry->mapid == map_id)
5611 return &itr->second;
5614 return NULL;
5618 * Searches for the areatrigger which teleports players to the given map
5620 AreaTrigger const* ObjectMgr::GetMapEntranceTrigger(uint32 Map) const
5622 for (AreaTriggerMap::const_iterator itr = mAreaTriggers.begin(); itr != mAreaTriggers.end(); ++itr)
5624 if(itr->second.target_mapId == Map)
5626 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(itr->first);
5627 if(atEntry)
5628 return &itr->second;
5631 return NULL;
5634 void ObjectMgr::PackGroupIds()
5636 // this routine renumbers groups in such a way so they start from 1 and go up
5638 // obtain set of all groups
5639 std::set<uint32> groupIds;
5641 // all valid ids are in the instance table
5642 // any associations to ids not in this table are assumed to be
5643 // cleaned already in CleanupInstances
5644 QueryResult *result = CharacterDatabase.Query("SELECT groupId FROM groups");
5645 if( result )
5649 Field *fields = result->Fetch();
5651 uint32 id = fields[0].GetUInt32();
5653 if (id == 0)
5655 CharacterDatabase.PExecute("DELETE FROM groups WHERE groupId = '%u'", id);
5656 CharacterDatabase.PExecute("DELETE FROM group_member WHERE groupId = '%u'", id);
5657 continue;
5660 groupIds.insert(id);
5662 while (result->NextRow());
5663 delete result;
5666 barGoLink bar( groupIds.size() + 1);
5667 bar.step();
5669 uint32 groupId = 1;
5670 // we do assume std::set is sorted properly on integer value
5671 for (std::set<uint32>::iterator i = groupIds.begin(); i != groupIds.end(); ++i)
5673 if (*i != groupId)
5675 // remap group id
5676 CharacterDatabase.PExecute("UPDATE groups SET groupId = '%u' WHERE groupId = '%u'", groupId, *i);
5677 CharacterDatabase.PExecute("UPDATE group_member SET groupId = '%u' WHERE groupId = '%u'", groupId, *i);
5680 ++groupId;
5681 bar.step();
5684 m_GroupIds.Set(groupId);
5686 sLog.outString( ">> Group Ids remapped, next group id is %u", groupId );
5687 sLog.outString();
5690 void ObjectMgr::SetHighestGuids()
5692 QueryResult *result = CharacterDatabase.Query( "SELECT MAX(guid) FROM characters" );
5693 if( result )
5695 m_CharGuids.Set((*result)[0].GetUInt32()+1);
5696 delete result;
5699 result = WorldDatabase.Query( "SELECT MAX(guid) FROM creature" );
5700 if( result )
5702 m_CreatureGuids.Set((*result)[0].GetUInt32()+1);
5703 delete result;
5706 result = CharacterDatabase.Query( "SELECT MAX(guid) FROM item_instance" );
5707 if( result )
5709 m_ItemGuids.Set((*result)[0].GetUInt32()+1);
5710 delete result;
5713 // Cleanup other tables from not existed guids (>=m_hiItemGuid)
5714 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item >= '%u'", m_ItemGuids.GetNextAfterMaxUsed());
5715 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid >= '%u'", m_ItemGuids.GetNextAfterMaxUsed());
5716 CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE itemguid >= '%u'", m_ItemGuids.GetNextAfterMaxUsed());
5717 CharacterDatabase.PExecute("DELETE FROM guild_bank_item WHERE item_guid >= '%u'", m_ItemGuids.GetNextAfterMaxUsed());
5719 result = WorldDatabase.Query("SELECT MAX(guid) FROM gameobject" );
5720 if( result )
5722 m_GameobjectGuids.Set((*result)[0].GetUInt32()+1);
5723 delete result;
5726 result = CharacterDatabase.Query("SELECT MAX(id) FROM auctionhouse" );
5727 if( result )
5729 m_AuctionIds.Set((*result)[0].GetUInt32()+1);
5730 delete result;
5733 result = CharacterDatabase.Query( "SELECT MAX(id) FROM mail" );
5734 if( result )
5736 m_MailIds.Set((*result)[0].GetUInt32()+1);
5737 delete result;
5740 result = CharacterDatabase.Query( "SELECT MAX(guid) FROM corpse" );
5741 if( result )
5743 m_CorpseGuids.Set((*result)[0].GetUInt32()+1);
5744 delete result;
5747 result = CharacterDatabase.Query("SELECT MAX(arenateamid) FROM arena_team");
5748 if (result)
5750 m_ArenaTeamIds.Set((*result)[0].GetUInt32()+1);
5751 delete result;
5754 result = CharacterDatabase.Query("SELECT MAX(setguid) FROM character_equipmentsets");
5755 if (result)
5757 m_EquipmentSetIds.Set((*result)[0].GetUInt64()+1);
5758 delete result;
5761 result = CharacterDatabase.Query( "SELECT MAX(guildid) FROM guild" );
5762 if (result)
5764 m_GuildIds.Set((*result)[0].GetUInt32()+1);
5765 delete result;
5768 result = CharacterDatabase.Query( "SELECT MAX(groupId) FROM groups" );
5769 if (result)
5771 m_GroupIds.Set((*result)[0].GetUInt32()+1);
5772 delete result;
5776 uint32 ObjectMgr::GenerateLowGuid(HighGuid guidhigh)
5778 switch(guidhigh)
5780 case HIGHGUID_ITEM:
5781 return m_ItemGuids.Generate();
5782 case HIGHGUID_UNIT:
5783 return m_CreatureGuids.Generate();
5784 case HIGHGUID_PLAYER:
5785 return m_CharGuids.Generate();
5786 case HIGHGUID_GAMEOBJECT:
5787 return m_GameobjectGuids.Generate();
5788 case HIGHGUID_CORPSE:
5789 return m_CorpseGuids.Generate();
5790 default:
5791 ASSERT(0);
5794 ASSERT(0);
5795 return 0;
5798 void ObjectMgr::LoadGameObjectLocales()
5800 mGameObjectLocaleMap.clear(); // need for reload case
5802 QueryResult *result = WorldDatabase.Query("SELECT entry,"
5803 "name_loc1,name_loc2,name_loc3,name_loc4,name_loc5,name_loc6,name_loc7,name_loc8,"
5804 "castbarcaption_loc1,castbarcaption_loc2,castbarcaption_loc3,castbarcaption_loc4,"
5805 "castbarcaption_loc5,castbarcaption_loc6,castbarcaption_loc7,castbarcaption_loc8 FROM locales_gameobject");
5807 if(!result)
5809 barGoLink bar(1);
5811 bar.step();
5813 sLog.outString();
5814 sLog.outString(">> Loaded 0 gameobject locale strings. DB table `locales_gameobject` is empty.");
5815 return;
5818 barGoLink bar((int)result->GetRowCount());
5822 Field *fields = result->Fetch();
5823 bar.step();
5825 uint32 entry = fields[0].GetUInt32();
5827 GameObjectLocale& data = mGameObjectLocaleMap[entry];
5829 for(int i = 1; i < MAX_LOCALE; ++i)
5831 std::string str = fields[i].GetCppString();
5832 if(!str.empty())
5834 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5835 if(idx >= 0)
5837 if((int32)data.Name.size() <= idx)
5838 data.Name.resize(idx+1);
5840 data.Name[idx] = str;
5845 for(int i = 1; i < MAX_LOCALE; ++i)
5847 std::string str = fields[i+(MAX_LOCALE-1)].GetCppString();
5848 if(!str.empty())
5850 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5851 if(idx >= 0)
5853 if((int32)data.CastBarCaption.size() <= idx)
5854 data.CastBarCaption.resize(idx+1);
5856 data.CastBarCaption[idx] = str;
5861 } while (result->NextRow());
5863 delete result;
5865 sLog.outString();
5866 sLog.outString( ">> Loaded %lu gameobject locale strings", (unsigned long)mGameObjectLocaleMap.size() );
5869 struct SQLGameObjectLoader : public SQLStorageLoaderBase<SQLGameObjectLoader>
5871 template<class D>
5872 void convert_from_str(uint32 /*field_pos*/, char *src, D &dst)
5874 dst = D(sObjectMgr.GetScriptId(src));
5878 inline void CheckGOLockId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5880 if (sLockStore.LookupEntry(dataN))
5881 return;
5883 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but lock (Id: %u) not found.",
5884 goInfo->id,goInfo->type,N,dataN,dataN);
5887 inline void CheckGOLinkedTrapId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5889 if (GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(dataN))
5891 if (trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5892 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5893 goInfo->id,goInfo->type,N,dataN,dataN,GAMEOBJECT_TYPE_TRAP);
5895 /* disable check for while (too many error reports baout not existed in trap templates
5896 else
5897 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5898 goInfo->id,goInfo->type,N,dataN,dataN);
5902 inline void CheckGOSpellId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5904 if (sSpellStore.LookupEntry(dataN))
5905 return;
5907 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but Spell (Entry %u) not exist.",
5908 goInfo->id,goInfo->type,N,dataN,dataN);
5911 inline void CheckAndFixGOChairHeightId(GameObjectInfo const* goInfo,uint32 const& dataN,uint32 N)
5913 if (dataN <= (UNIT_STAND_STATE_SIT_HIGH_CHAIR-UNIT_STAND_STATE_SIT_LOW_CHAIR) )
5914 return;
5916 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but correct chair height in range 0..%i.",
5917 goInfo->id,goInfo->type,N,dataN,UNIT_STAND_STATE_SIT_HIGH_CHAIR-UNIT_STAND_STATE_SIT_LOW_CHAIR);
5919 // prevent client and server unexpected work
5920 const_cast<uint32&>(dataN) = 0;
5923 inline void CheckGONoDamageImmuneId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5925 // 0/1 correct values
5926 if (dataN <= 1)
5927 return;
5929 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but expected boolean (0/1) noDamageImmune field value.",
5930 goInfo->id,goInfo->type,N,dataN);
5933 inline void CheckGOConsumable(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5935 // 0/1 correct values
5936 if (dataN <= 1)
5937 return;
5939 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but expected boolean (0/1) consumable field value.",
5940 goInfo->id,goInfo->type,N,dataN);
5943 void ObjectMgr::LoadGameobjectInfo()
5945 SQLGameObjectLoader loader;
5946 loader.Load(sGOStorage);
5948 // some checks
5949 for(uint32 id = 1; id < sGOStorage.MaxEntry; id++)
5951 GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(id);
5952 if (!goInfo)
5953 continue;
5955 // some GO types have unused go template, check goInfo->displayId at GO spawn data loading or ignore
5957 switch(goInfo->type)
5959 case GAMEOBJECT_TYPE_DOOR: //0
5961 if (goInfo->door.lockId)
5962 CheckGOLockId(goInfo,goInfo->door.lockId,1);
5963 CheckGONoDamageImmuneId(goInfo,goInfo->door.noDamageImmune,3);
5964 break;
5966 case GAMEOBJECT_TYPE_BUTTON: //1
5968 if (goInfo->button.lockId)
5969 CheckGOLockId(goInfo,goInfo->button.lockId,1);
5970 if (goInfo->button.linkedTrapId) // linked trap
5971 CheckGOLinkedTrapId(goInfo,goInfo->button.linkedTrapId,3);
5972 CheckGONoDamageImmuneId(goInfo,goInfo->button.noDamageImmune,4);
5973 break;
5975 case GAMEOBJECT_TYPE_QUESTGIVER: //2
5977 if (goInfo->questgiver.lockId)
5978 CheckGOLockId(goInfo,goInfo->questgiver.lockId,0);
5979 CheckGONoDamageImmuneId(goInfo,goInfo->questgiver.noDamageImmune,5);
5980 break;
5982 case GAMEOBJECT_TYPE_CHEST: //3
5984 if (goInfo->chest.lockId)
5985 CheckGOLockId(goInfo,goInfo->chest.lockId,0);
5987 CheckGOConsumable(goInfo,goInfo->chest.consumable,3);
5989 if (goInfo->chest.linkedTrapId) // linked trap
5990 CheckGOLinkedTrapId(goInfo,goInfo->chest.linkedTrapId,7);
5991 break;
5993 case GAMEOBJECT_TYPE_TRAP: //6
5995 if (goInfo->trap.lockId)
5996 CheckGOLockId(goInfo,goInfo->trap.lockId,0);
5997 /* disable check for while, too many not existed spells
5998 if (goInfo->trap.spellId) // spell
5999 CheckGOSpellId(goInfo,goInfo->trap.spellId,3);
6001 break;
6003 case GAMEOBJECT_TYPE_CHAIR: //7
6004 CheckAndFixGOChairHeightId(goInfo,goInfo->chair.height,1);
6005 break;
6006 case GAMEOBJECT_TYPE_SPELL_FOCUS: //8
6008 if (goInfo->spellFocus.focusId)
6010 if (!sSpellFocusObjectStore.LookupEntry(goInfo->spellFocus.focusId))
6011 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but SpellFocus (Id: %u) not exist.",
6012 id,goInfo->type,goInfo->spellFocus.focusId,goInfo->spellFocus.focusId);
6015 if (goInfo->spellFocus.linkedTrapId) // linked trap
6016 CheckGOLinkedTrapId(goInfo,goInfo->spellFocus.linkedTrapId,2);
6017 break;
6019 case GAMEOBJECT_TYPE_GOOBER: //10
6021 if (goInfo->goober.lockId)
6022 CheckGOLockId(goInfo,goInfo->goober.lockId,0);
6024 CheckGOConsumable(goInfo,goInfo->goober.consumable,3);
6026 if (goInfo->goober.pageId) // pageId
6028 if (!sPageTextStore.LookupEntry<PageText>(goInfo->goober.pageId))
6029 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data7=%u but PageText (Entry %u) not exist.",
6030 id,goInfo->type,goInfo->goober.pageId,goInfo->goober.pageId);
6032 /* disable check for while, too many not existed spells
6033 if (goInfo->goober.spellId) // spell
6034 CheckGOSpellId(goInfo,goInfo->goober.spellId,10);
6036 CheckGONoDamageImmuneId(goInfo,goInfo->goober.noDamageImmune,11);
6037 if (goInfo->goober.linkedTrapId) // linked trap
6038 CheckGOLinkedTrapId(goInfo,goInfo->goober.linkedTrapId,12);
6039 break;
6041 case GAMEOBJECT_TYPE_AREADAMAGE: //12
6043 if (goInfo->areadamage.lockId)
6044 CheckGOLockId(goInfo,goInfo->areadamage.lockId,0);
6045 break;
6047 case GAMEOBJECT_TYPE_CAMERA: //13
6049 if (goInfo->camera.lockId)
6050 CheckGOLockId(goInfo,goInfo->camera.lockId,0);
6051 break;
6053 case GAMEOBJECT_TYPE_MO_TRANSPORT: //15
6055 if (goInfo->moTransport.taxiPathId)
6057 if (goInfo->moTransport.taxiPathId >= sTaxiPathNodesByPath.size() || sTaxiPathNodesByPath[goInfo->moTransport.taxiPathId].empty())
6058 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but TaxiPath (Id: %u) not exist.",
6059 id,goInfo->type,goInfo->moTransport.taxiPathId,goInfo->moTransport.taxiPathId);
6061 break;
6063 case GAMEOBJECT_TYPE_SUMMONING_RITUAL: //18
6065 /* disable check for while, too many not existed spells
6066 // always must have spell
6067 CheckGOSpellId(goInfo,goInfo->summoningRitual.spellId,1);
6069 break;
6071 case GAMEOBJECT_TYPE_SPELLCASTER: //22
6073 // always must have spell
6074 CheckGOSpellId(goInfo,goInfo->spellcaster.spellId,0);
6075 break;
6077 case GAMEOBJECT_TYPE_FLAGSTAND: //24
6079 if (goInfo->flagstand.lockId)
6080 CheckGOLockId(goInfo,goInfo->flagstand.lockId,0);
6081 CheckGONoDamageImmuneId(goInfo,goInfo->flagstand.noDamageImmune,5);
6082 break;
6084 case GAMEOBJECT_TYPE_FISHINGHOLE: //25
6086 if (goInfo->fishinghole.lockId)
6087 CheckGOLockId(goInfo,goInfo->fishinghole.lockId,4);
6088 break;
6090 case GAMEOBJECT_TYPE_FLAGDROP: //26
6092 if (goInfo->flagdrop.lockId)
6093 CheckGOLockId(goInfo,goInfo->flagdrop.lockId,0);
6094 CheckGONoDamageImmuneId(goInfo,goInfo->flagdrop.noDamageImmune,3);
6095 break;
6097 case GAMEOBJECT_TYPE_BARBER_CHAIR: //32
6098 CheckAndFixGOChairHeightId(goInfo,goInfo->barberChair.chairheight,0);
6099 break;
6103 sLog.outString( ">> Loaded %u game object templates", sGOStorage.RecordCount );
6104 sLog.outString();
6107 void ObjectMgr::LoadExplorationBaseXP()
6109 uint32 count = 0;
6110 QueryResult *result = WorldDatabase.Query("SELECT level,basexp FROM exploration_basexp");
6112 if( !result )
6114 barGoLink bar( 1 );
6116 bar.step();
6118 sLog.outString();
6119 sLog.outString( ">> Loaded %u BaseXP definitions", count );
6120 return;
6123 barGoLink bar( (int)result->GetRowCount() );
6127 bar.step();
6129 Field *fields = result->Fetch();
6130 uint32 level = fields[0].GetUInt32();
6131 uint32 basexp = fields[1].GetUInt32();
6132 mBaseXPTable[level] = basexp;
6133 ++count;
6135 while (result->NextRow());
6137 delete result;
6139 sLog.outString();
6140 sLog.outString( ">> Loaded %u BaseXP definitions", count );
6143 uint32 ObjectMgr::GetBaseXP(uint32 level) const
6145 BaseXPMap::const_iterator itr = mBaseXPTable.find(level);
6146 return itr != mBaseXPTable.end() ? itr->second : 0;
6149 uint32 ObjectMgr::GetXPForLevel(uint32 level) const
6151 if (level < mPlayerXPperLevel.size())
6152 return mPlayerXPperLevel[level];
6153 return 0;
6156 void ObjectMgr::LoadPetNames()
6158 uint32 count = 0;
6159 QueryResult *result = WorldDatabase.Query("SELECT word,entry,half FROM pet_name_generation");
6161 if( !result )
6163 barGoLink bar( 1 );
6165 bar.step();
6167 sLog.outString();
6168 sLog.outString( ">> Loaded %u pet name parts", count );
6169 return;
6172 barGoLink bar( (int)result->GetRowCount() );
6176 bar.step();
6178 Field *fields = result->Fetch();
6179 std::string word = fields[0].GetString();
6180 uint32 entry = fields[1].GetUInt32();
6181 bool half = fields[2].GetBool();
6182 if(half)
6183 PetHalfName1[entry].push_back(word);
6184 else
6185 PetHalfName0[entry].push_back(word);
6186 ++count;
6188 while (result->NextRow());
6189 delete result;
6191 sLog.outString();
6192 sLog.outString( ">> Loaded %u pet name parts", count );
6195 void ObjectMgr::LoadPetNumber()
6197 QueryResult* result = CharacterDatabase.Query("SELECT MAX(id) FROM character_pet");
6198 if(result)
6200 Field *fields = result->Fetch();
6201 m_PetNumbers.Set(fields[0].GetUInt32()+1);
6202 delete result;
6205 barGoLink bar( 1 );
6206 bar.step();
6208 sLog.outString();
6209 sLog.outString( ">> Loaded the max pet number: %d", m_PetNumbers.GetNextAfterMaxUsed()-1);
6212 std::string ObjectMgr::GeneratePetName(uint32 entry)
6214 std::vector<std::string> & list0 = PetHalfName0[entry];
6215 std::vector<std::string> & list1 = PetHalfName1[entry];
6217 if(list0.empty() || list1.empty())
6219 CreatureInfo const *cinfo = GetCreatureTemplate(entry);
6220 char const* petname = GetPetName(cinfo->family, sWorld.GetDefaultDbcLocale());
6221 if(!petname)
6222 petname = cinfo->Name;
6223 return std::string(petname);
6226 return *(list0.begin()+urand(0, list0.size()-1)) + *(list1.begin()+urand(0, list1.size()-1));
6229 void ObjectMgr::LoadCorpses()
6231 uint32 count = 0;
6232 // 0 1 2 3 4 5 6
6233 QueryResult *result = CharacterDatabase.Query("SELECT corpse.guid, player, corpse.position_x, corpse.position_y, corpse.position_z, corpse.orientation, corpse.map, "
6234 // 7 8 9 10 11 12 13 14 15 16 17 18
6235 "time, corpse_type, instance, phaseMask, gender, race, class, playerBytes, playerBytes2, equipmentCache, guildId, playerFlags FROM corpse "
6236 "JOIN characters ON player = characters.guid "
6237 "LEFT JOIN guild_member ON player=guild_member.guid WHERE corpse_type <> 0");
6239 if( !result )
6241 barGoLink bar( 1 );
6243 bar.step();
6245 sLog.outString();
6246 sLog.outString( ">> Loaded %u corpses", count );
6247 return;
6250 barGoLink bar( (int)result->GetRowCount() );
6254 bar.step();
6256 Field *fields = result->Fetch();
6258 uint32 guid = fields[0].GetUInt32();
6260 Corpse *corpse = new Corpse;
6261 if(!corpse->LoadFromDB(guid,fields))
6263 delete corpse;
6264 continue;
6267 sObjectAccessor.AddCorpse(corpse);
6269 ++count;
6271 while (result->NextRow());
6272 delete result;
6274 sLog.outString();
6275 sLog.outString( ">> Loaded %u corpses", count );
6278 void ObjectMgr::LoadReputationOnKill()
6280 uint32 count = 0;
6282 // 0 1 2
6283 QueryResult *result = WorldDatabase.Query("SELECT creature_id, RewOnKillRepFaction1, RewOnKillRepFaction2,"
6284 // 3 4 5 6 7 8 9
6285 "IsTeamAward1, MaxStanding1, RewOnKillRepValue1, IsTeamAward2, MaxStanding2, RewOnKillRepValue2, TeamDependent "
6286 "FROM creature_onkill_reputation");
6288 if(!result)
6290 barGoLink bar(1);
6292 bar.step();
6294 sLog.outString();
6295 sLog.outErrorDb(">> Loaded 0 creature award reputation definitions. DB table `creature_onkill_reputation` is empty.");
6296 return;
6299 barGoLink bar((int)result->GetRowCount());
6303 Field *fields = result->Fetch();
6304 bar.step();
6306 uint32 creature_id = fields[0].GetUInt32();
6308 ReputationOnKillEntry repOnKill;
6309 repOnKill.repfaction1 = fields[1].GetUInt32();
6310 repOnKill.repfaction2 = fields[2].GetUInt32();
6311 repOnKill.is_teamaward1 = fields[3].GetBool();
6312 repOnKill.reputation_max_cap1 = fields[4].GetUInt32();
6313 repOnKill.repvalue1 = fields[5].GetInt32();
6314 repOnKill.is_teamaward2 = fields[6].GetBool();
6315 repOnKill.reputation_max_cap2 = fields[7].GetUInt32();
6316 repOnKill.repvalue2 = fields[8].GetInt32();
6317 repOnKill.team_dependent = fields[9].GetUInt8();
6319 if(!GetCreatureTemplate(creature_id))
6321 sLog.outErrorDb("Table `creature_onkill_reputation` have data for not existed creature entry (%u), skipped",creature_id);
6322 continue;
6325 if(repOnKill.repfaction1)
6327 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(repOnKill.repfaction1);
6328 if(!factionEntry1)
6330 sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction1);
6331 continue;
6335 if(repOnKill.repfaction2)
6337 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(repOnKill.repfaction2);
6338 if(!factionEntry2)
6340 sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction2);
6341 continue;
6345 mRepOnKill[creature_id] = repOnKill;
6347 ++count;
6348 } while (result->NextRow());
6350 delete result;
6352 sLog.outString();
6353 sLog.outString(">> Loaded %u creature award reputation definitions", count);
6356 void ObjectMgr::LoadPointsOfInterest()
6358 mPointsOfInterest.clear(); // need for reload case
6360 uint32 count = 0;
6362 // 0 1 2 3 4 5
6363 QueryResult *result = WorldDatabase.Query("SELECT entry, x, y, icon, flags, data, icon_name FROM points_of_interest");
6365 if(!result)
6367 barGoLink bar(1);
6369 bar.step();
6371 sLog.outString();
6372 sLog.outErrorDb(">> Loaded 0 Points of Interest definitions. DB table `points_of_interest` is empty.");
6373 return;
6376 barGoLink bar((int)result->GetRowCount());
6380 Field *fields = result->Fetch();
6381 bar.step();
6383 uint32 point_id = fields[0].GetUInt32();
6385 PointOfInterest POI;
6386 POI.x = fields[1].GetFloat();
6387 POI.y = fields[2].GetFloat();
6388 POI.icon = fields[3].GetUInt32();
6389 POI.flags = fields[4].GetUInt32();
6390 POI.data = fields[5].GetUInt32();
6391 POI.icon_name = fields[6].GetCppString();
6393 if(!MaNGOS::IsValidMapCoord(POI.x,POI.y))
6395 sLog.outErrorDb("Table `points_of_interest` (Entry: %u) have invalid coordinates (X: %f Y: %f), ignored.",point_id,POI.x,POI.y);
6396 continue;
6399 mPointsOfInterest[point_id] = POI;
6401 ++count;
6402 } while (result->NextRow());
6404 delete result;
6406 sLog.outString();
6407 sLog.outString(">> Loaded %u Points of Interest definitions", count);
6410 void ObjectMgr::LoadQuestPOI()
6412 mQuestPOIMap.clear(); // need for reload case
6414 uint32 count = 0;
6416 // 0 1 2 3 4 5 6 7
6417 QueryResult *result = WorldDatabase.Query("SELECT questId, poiId, objIndex, mapId, mapAreaId, floorId, unk3, unk4 FROM quest_poi");
6419 if(!result)
6421 barGoLink bar(1);
6423 bar.step();
6425 sLog.outString();
6426 sLog.outErrorDb(">> Loaded 0 quest POI definitions. DB table `quest_poi` is empty.");
6427 return;
6430 barGoLink bar((int)result->GetRowCount());
6434 Field *fields = result->Fetch();
6435 bar.step();
6437 uint32 questId = fields[0].GetUInt32();
6438 uint32 poiId = fields[1].GetUInt32();
6439 int32 objIndex = fields[2].GetInt32();
6440 uint32 mapId = fields[3].GetUInt32();
6441 uint32 mapAreaId = fields[4].GetUInt32();
6442 uint32 floorId = fields[5].GetUInt32();
6443 uint32 unk3 = fields[6].GetUInt32();
6444 uint32 unk4 = fields[7].GetUInt32();
6446 QuestPOI POI(poiId, objIndex, mapId, mapAreaId, floorId, unk3, unk4);
6448 mQuestPOIMap[questId].push_back(POI);
6450 ++count;
6451 } while (result->NextRow());
6453 delete result;
6455 QueryResult *points = WorldDatabase.Query("SELECT questId, poiId, x, y FROM quest_poi_points");
6457 if (points)
6461 Field *pointFields = points->Fetch();
6463 uint32 questId = pointFields[0].GetUInt32();
6464 uint32 poiId = pointFields[1].GetUInt32();
6465 int32 x = pointFields[2].GetInt32();
6466 int32 y = pointFields[3].GetInt32();
6468 QuestPOIVector& vect = mQuestPOIMap[questId];
6470 for(QuestPOIVector::iterator itr = vect.begin(); itr != vect.end(); ++itr)
6472 if (itr->PoiId != poiId)
6473 continue;
6475 QuestPOIPoint point(x, y);
6476 itr->points.push_back(point);
6477 break;
6479 } while (points->NextRow());
6481 delete points;
6484 sLog.outString();
6485 sLog.outString(">> Loaded %u quest POI definitions", count);
6488 void ObjectMgr::LoadNPCSpellClickSpells()
6490 uint32 count = 0;
6492 mSpellClickInfoMap.clear();
6493 // 0 1 2 3 4 5
6494 QueryResult *result = WorldDatabase.Query("SELECT npc_entry, spell_id, quest_start, quest_start_active, quest_end, cast_flags FROM npc_spellclick_spells");
6496 if(!result)
6498 barGoLink bar(1);
6500 bar.step();
6502 sLog.outString();
6503 sLog.outErrorDb(">> Loaded 0 spellclick spells. DB table `npc_spellclick_spells` is empty.");
6504 return;
6507 barGoLink bar((int)result->GetRowCount());
6511 Field *fields = result->Fetch();
6512 bar.step();
6514 uint32 npc_entry = fields[0].GetUInt32();
6515 CreatureInfo const* cInfo = GetCreatureTemplate(npc_entry);
6516 if (!cInfo)
6518 sLog.outErrorDb("Table npc_spellclick_spells references unknown creature_template %u. Skipping entry.", npc_entry);
6519 continue;
6522 uint32 spellid = fields[1].GetUInt32();
6523 SpellEntry const *spellinfo = sSpellStore.LookupEntry(spellid);
6524 if (!spellinfo)
6526 sLog.outErrorDb("Table npc_spellclick_spells references unknown spellid %u. Skipping entry.", spellid);
6527 continue;
6530 uint32 quest_start = fields[2].GetUInt32();
6532 // quest might be 0 to enable spellclick independent of any quest
6533 if (quest_start)
6535 if(mQuestTemplates.find(quest_start) == mQuestTemplates.end())
6537 sLog.outErrorDb("Table npc_spellclick_spells references unknown start quest %u. Skipping entry.", quest_start);
6538 continue;
6543 bool quest_start_active = fields[3].GetBool();
6545 uint32 quest_end = fields[4].GetUInt32();
6546 // quest might be 0 to enable spellclick active infinity after start quest
6547 if (quest_end)
6549 if(mQuestTemplates.find(quest_end) == mQuestTemplates.end())
6551 sLog.outErrorDb("Table npc_spellclick_spells references unknown end quest %u. Skipping entry.", quest_end);
6552 continue;
6557 uint8 castFlags = fields[5].GetUInt8();
6558 SpellClickInfo info;
6559 info.spellId = spellid;
6560 info.questStart = quest_start;
6561 info.questStartCanActive = quest_start_active;
6562 info.questEnd = quest_end;
6563 info.castFlags = castFlags;
6564 mSpellClickInfoMap.insert(SpellClickInfoMap::value_type(npc_entry, info));
6566 // mark creature template as spell clickable
6567 const_cast<CreatureInfo*>(cInfo)->npcflag |= UNIT_NPC_FLAG_SPELLCLICK;
6569 ++count;
6570 } while (result->NextRow());
6572 delete result;
6574 sLog.outString();
6575 sLog.outString(">> Loaded %u spellclick definitions", count);
6578 void ObjectMgr::LoadWeatherZoneChances()
6580 uint32 count = 0;
6582 // 0 1 2 3 4 5 6 7 8 9 10 11 12
6583 QueryResult *result = WorldDatabase.Query("SELECT zone, spring_rain_chance, spring_snow_chance, spring_storm_chance, summer_rain_chance, summer_snow_chance, summer_storm_chance, fall_rain_chance, fall_snow_chance, fall_storm_chance, winter_rain_chance, winter_snow_chance, winter_storm_chance FROM game_weather");
6585 if(!result)
6587 barGoLink bar(1);
6589 bar.step();
6591 sLog.outString();
6592 sLog.outErrorDb(">> Loaded 0 weather definitions. DB table `game_weather` is empty.");
6593 return;
6596 barGoLink bar((int)result->GetRowCount());
6600 Field *fields = result->Fetch();
6601 bar.step();
6603 uint32 zone_id = fields[0].GetUInt32();
6605 WeatherZoneChances& wzc = mWeatherZoneMap[zone_id];
6607 for(int season = 0; season < WEATHER_SEASONS; ++season)
6609 wzc.data[season].rainChance = fields[season * (MAX_WEATHER_TYPE-1) + 1].GetUInt32();
6610 wzc.data[season].snowChance = fields[season * (MAX_WEATHER_TYPE-1) + 2].GetUInt32();
6611 wzc.data[season].stormChance = fields[season * (MAX_WEATHER_TYPE-1) + 3].GetUInt32();
6613 if(wzc.data[season].rainChance > 100)
6615 wzc.data[season].rainChance = 25;
6616 sLog.outErrorDb("Weather for zone %u season %u has wrong rain chance > 100%%",zone_id,season);
6619 if(wzc.data[season].snowChance > 100)
6621 wzc.data[season].snowChance = 25;
6622 sLog.outErrorDb("Weather for zone %u season %u has wrong snow chance > 100%%",zone_id,season);
6625 if(wzc.data[season].stormChance > 100)
6627 wzc.data[season].stormChance = 25;
6628 sLog.outErrorDb("Weather for zone %u season %u has wrong storm chance > 100%%",zone_id,season);
6632 ++count;
6633 } while (result->NextRow());
6635 delete result;
6637 sLog.outString();
6638 sLog.outString(">> Loaded %u weather definitions", count);
6641 void ObjectMgr::SaveCreatureRespawnTime(uint32 loguid, uint32 instance, time_t t)
6643 mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
6644 WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
6645 if(t)
6646 WorldDatabase.PExecute("INSERT INTO creature_respawn VALUES ( '%u', '" UI64FMTD "', '%u' )", loguid, uint64(t), instance);
6649 void ObjectMgr::DeleteCreatureData(uint32 guid)
6651 // remove mapid*cellid -> guid_set map
6652 CreatureData const* data = GetCreatureData(guid);
6653 if(data)
6654 RemoveCreatureFromGrid(guid, data);
6656 mCreatureDataMap.erase(guid);
6659 void ObjectMgr::SaveGORespawnTime(uint32 loguid, uint32 instance, time_t t)
6661 mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
6662 WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
6663 if(t)
6664 WorldDatabase.PExecute("INSERT INTO gameobject_respawn VALUES ( '%u', '" UI64FMTD "', '%u' )", loguid, uint64(t), instance);
6667 void ObjectMgr::DeleteRespawnTimeForInstance(uint32 instance)
6669 RespawnTimes::iterator next;
6671 for(RespawnTimes::iterator itr = mGORespawnTimes.begin(); itr != mGORespawnTimes.end(); itr = next)
6673 next = itr;
6674 ++next;
6676 if(GUID_HIPART(itr->first)==instance)
6677 mGORespawnTimes.erase(itr);
6680 for(RespawnTimes::iterator itr = mCreatureRespawnTimes.begin(); itr != mCreatureRespawnTimes.end(); itr = next)
6682 next = itr;
6683 ++next;
6685 if(GUID_HIPART(itr->first)==instance)
6686 mCreatureRespawnTimes.erase(itr);
6689 WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE instance = '%u'", instance);
6690 WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE instance = '%u'", instance);
6693 void ObjectMgr::DeleteGOData(uint32 guid)
6695 // remove mapid*cellid -> guid_set map
6696 GameObjectData const* data = GetGOData(guid);
6697 if(data)
6698 RemoveGameobjectFromGrid(guid, data);
6700 mGameObjectDataMap.erase(guid);
6703 void ObjectMgr::AddCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid, uint32 instance)
6705 // corpses are always added to spawn mode 0 and they are spawned by their instance id
6706 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
6707 cell_guids.corpses[player_guid] = instance;
6710 void ObjectMgr::DeleteCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid)
6712 // corpses are always added to spawn mode 0 and they are spawned by their instance id
6713 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
6714 cell_guids.corpses.erase(player_guid);
6717 void ObjectMgr::LoadQuestRelationsHelper(QuestRelations& map,char const* table)
6719 map.clear(); // need for reload case
6721 uint32 count = 0;
6723 QueryResult *result = WorldDatabase.PQuery("SELECT id,quest FROM %s",table);
6725 if(!result)
6727 barGoLink bar(1);
6729 bar.step();
6731 sLog.outString();
6732 sLog.outErrorDb(">> Loaded 0 quest relations from %s. DB table `%s` is empty.",table,table);
6733 return;
6736 barGoLink bar((int)result->GetRowCount());
6740 Field *fields = result->Fetch();
6741 bar.step();
6743 uint32 id = fields[0].GetUInt32();
6744 uint32 quest = fields[1].GetUInt32();
6746 if(mQuestTemplates.find(quest) == mQuestTemplates.end())
6748 sLog.outErrorDb("Table `%s: Quest %u listed for entry %u does not exist.",table,quest,id);
6749 continue;
6752 map.insert(QuestRelations::value_type(id,quest));
6754 ++count;
6755 } while (result->NextRow());
6757 delete result;
6759 sLog.outString();
6760 sLog.outString(">> Loaded %u quest relations from %s", count,table);
6763 void ObjectMgr::LoadGameobjectQuestRelations()
6765 LoadQuestRelationsHelper(mGOQuestRelations,"gameobject_questrelation");
6767 for(QuestRelations::iterator itr = mGOQuestRelations.begin(); itr != mGOQuestRelations.end(); ++itr)
6769 GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
6770 if(!goInfo)
6771 sLog.outErrorDb("Table `gameobject_questrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
6772 else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
6773 sLog.outErrorDb("Table `gameobject_questrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
6777 void ObjectMgr::LoadGameobjectInvolvedRelations()
6779 LoadQuestRelationsHelper(mGOQuestInvolvedRelations,"gameobject_involvedrelation");
6781 for(QuestRelations::iterator itr = mGOQuestInvolvedRelations.begin(); itr != mGOQuestInvolvedRelations.end(); ++itr)
6783 GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
6784 if(!goInfo)
6785 sLog.outErrorDb("Table `gameobject_involvedrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
6786 else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
6787 sLog.outErrorDb("Table `gameobject_involvedrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
6791 void ObjectMgr::LoadCreatureQuestRelations()
6793 LoadQuestRelationsHelper(mCreatureQuestRelations,"creature_questrelation");
6795 for(QuestRelations::iterator itr = mCreatureQuestRelations.begin(); itr != mCreatureQuestRelations.end(); ++itr)
6797 CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
6798 if(!cInfo)
6799 sLog.outErrorDb("Table `creature_questrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
6800 else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
6801 sLog.outErrorDb("Table `creature_questrelation` has creature entry (%u) for quest %u, but npcflag does not include UNIT_NPC_FLAG_QUESTGIVER",itr->first,itr->second);
6805 void ObjectMgr::LoadCreatureInvolvedRelations()
6807 LoadQuestRelationsHelper(mCreatureQuestInvolvedRelations,"creature_involvedrelation");
6809 for(QuestRelations::iterator itr = mCreatureQuestInvolvedRelations.begin(); itr != mCreatureQuestInvolvedRelations.end(); ++itr)
6811 CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
6812 if(!cInfo)
6813 sLog.outErrorDb("Table `creature_involvedrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
6814 else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
6815 sLog.outErrorDb("Table `creature_involvedrelation` has creature entry (%u) for quest %u, but npcflag does not include UNIT_NPC_FLAG_QUESTGIVER",itr->first,itr->second);
6819 void ObjectMgr::LoadReservedPlayersNames()
6821 m_ReservedNames.clear(); // need for reload case
6823 QueryResult *result = WorldDatabase.Query("SELECT name FROM reserved_name");
6825 uint32 count = 0;
6827 if( !result )
6829 barGoLink bar( 1 );
6830 bar.step();
6832 sLog.outString();
6833 sLog.outString( ">> Loaded %u reserved player names", count );
6834 return;
6837 barGoLink bar((int) result->GetRowCount() );
6839 Field* fields;
6842 bar.step();
6843 fields = result->Fetch();
6844 std::string name= fields[0].GetCppString();
6846 std::wstring wstr;
6847 if(!Utf8toWStr (name,wstr))
6849 sLog.outError("Table `reserved_name` have invalid name: %s", name.c_str() );
6850 continue;
6853 wstrToLower(wstr);
6855 m_ReservedNames.insert(wstr);
6856 ++count;
6857 } while ( result->NextRow() );
6859 delete result;
6861 sLog.outString();
6862 sLog.outString( ">> Loaded %u reserved player names", count );
6865 bool ObjectMgr::IsReservedName( const std::string& name ) const
6867 std::wstring wstr;
6868 if(!Utf8toWStr (name,wstr))
6869 return false;
6871 wstrToLower(wstr);
6873 return m_ReservedNames.find(wstr) != m_ReservedNames.end();
6876 enum LanguageType
6878 LT_BASIC_LATIN = 0x0000,
6879 LT_EXTENDEN_LATIN = 0x0001,
6880 LT_CYRILLIC = 0x0002,
6881 LT_EAST_ASIA = 0x0004,
6882 LT_ANY = 0xFFFF
6885 static LanguageType GetRealmLanguageType(bool create)
6887 switch(sWorld.getConfig(CONFIG_UINT32_REALM_ZONE))
6889 case REALM_ZONE_UNKNOWN: // any language
6890 case REALM_ZONE_DEVELOPMENT:
6891 case REALM_ZONE_TEST_SERVER:
6892 case REALM_ZONE_QA_SERVER:
6893 return LT_ANY;
6894 case REALM_ZONE_UNITED_STATES: // extended-Latin
6895 case REALM_ZONE_OCEANIC:
6896 case REALM_ZONE_LATIN_AMERICA:
6897 case REALM_ZONE_ENGLISH:
6898 case REALM_ZONE_GERMAN:
6899 case REALM_ZONE_FRENCH:
6900 case REALM_ZONE_SPANISH:
6901 return LT_EXTENDEN_LATIN;
6902 case REALM_ZONE_KOREA: // East-Asian
6903 case REALM_ZONE_TAIWAN:
6904 case REALM_ZONE_CHINA:
6905 return LT_EAST_ASIA;
6906 case REALM_ZONE_RUSSIAN: // Cyrillic
6907 return LT_CYRILLIC;
6908 default:
6909 return create ? LT_BASIC_LATIN : LT_ANY; // basic-Latin at create, any at login
6913 bool isValidString(std::wstring wstr, uint32 strictMask, bool numericOrSpace, bool create = false)
6915 if(strictMask==0) // any language, ignore realm
6917 if(isExtendedLatinString(wstr,numericOrSpace))
6918 return true;
6919 if(isCyrillicString(wstr,numericOrSpace))
6920 return true;
6921 if(isEastAsianString(wstr,numericOrSpace))
6922 return true;
6923 return false;
6926 if(strictMask & 0x2) // realm zone specific
6928 LanguageType lt = GetRealmLanguageType(create);
6929 if(lt & LT_EXTENDEN_LATIN)
6930 if(isExtendedLatinString(wstr,numericOrSpace))
6931 return true;
6932 if(lt & LT_CYRILLIC)
6933 if(isCyrillicString(wstr,numericOrSpace))
6934 return true;
6935 if(lt & LT_EAST_ASIA)
6936 if(isEastAsianString(wstr,numericOrSpace))
6937 return true;
6940 if(strictMask & 0x1) // basic Latin
6942 if(isBasicLatinString(wstr,numericOrSpace))
6943 return true;
6946 return false;
6949 uint8 ObjectMgr::CheckPlayerName( const std::string& name, bool create )
6951 std::wstring wname;
6952 if(!Utf8toWStr(name,wname))
6953 return CHAR_NAME_INVALID_CHARACTER;
6955 if(wname.size() > MAX_PLAYER_NAME)
6956 return CHAR_NAME_TOO_LONG;
6958 uint32 minName = sWorld.getConfig(CONFIG_UINT32_MIN_PLAYER_NAME);
6959 if(wname.size() < minName)
6960 return CHAR_NAME_TOO_SHORT;
6962 uint32 strictMask = sWorld.getConfig(CONFIG_UINT32_STRICT_PLAYER_NAMES);
6963 if(!isValidString(wname,strictMask,false,create))
6964 return CHAR_NAME_MIXED_LANGUAGES;
6966 return CHAR_NAME_SUCCESS;
6969 bool ObjectMgr::IsValidCharterName( const std::string& name )
6971 std::wstring wname;
6972 if(!Utf8toWStr(name,wname))
6973 return false;
6975 if(wname.size() > MAX_CHARTER_NAME)
6976 return false;
6978 uint32 minName = sWorld.getConfig(CONFIG_UINT32_MIN_CHARTER_NAME);
6979 if(wname.size() < minName)
6980 return false;
6982 uint32 strictMask = sWorld.getConfig(CONFIG_UINT32_STRICT_CHARTER_NAMES);
6984 return isValidString(wname,strictMask,true);
6987 PetNameInvalidReason ObjectMgr::CheckPetName( const std::string& name )
6989 std::wstring wname;
6990 if(!Utf8toWStr(name,wname))
6991 return PET_NAME_INVALID;
6993 if(wname.size() > MAX_PET_NAME)
6994 return PET_NAME_TOO_LONG;
6996 uint32 minName = sWorld.getConfig(CONFIG_UINT32_MIN_PET_NAME);
6997 if(wname.size() < minName)
6998 return PET_NAME_TOO_SHORT;
7000 uint32 strictMask = sWorld.getConfig(CONFIG_UINT32_STRICT_PET_NAMES);
7001 if(!isValidString(wname,strictMask,false))
7002 return PET_NAME_MIXED_LANGUAGES;
7004 return PET_NAME_SUCCESS;
7007 int ObjectMgr::GetIndexForLocale( LocaleConstant loc )
7009 if(loc==LOCALE_enUS)
7010 return -1;
7012 for(size_t i=0;i < m_LocalForIndex.size(); ++i)
7013 if(m_LocalForIndex[i]==loc)
7014 return i;
7016 return -1;
7019 LocaleConstant ObjectMgr::GetLocaleForIndex(int i)
7021 if (i<0 || i>=(int32)m_LocalForIndex.size())
7022 return LOCALE_enUS;
7024 return m_LocalForIndex[i];
7027 int ObjectMgr::GetOrNewIndexForLocale( LocaleConstant loc )
7029 if(loc==LOCALE_enUS)
7030 return -1;
7032 for(size_t i=0;i < m_LocalForIndex.size(); ++i)
7033 if(m_LocalForIndex[i]==loc)
7034 return i;
7036 m_LocalForIndex.push_back(loc);
7037 return m_LocalForIndex.size()-1;
7040 void ObjectMgr::LoadGameObjectForQuests()
7042 mGameObjectForQuestSet.clear(); // need for reload case
7044 if( !sGOStorage.MaxEntry )
7046 barGoLink bar( 1 );
7047 bar.step();
7048 sLog.outString();
7049 sLog.outString( ">> Loaded 0 GameObjects for quests" );
7050 return;
7053 barGoLink bar( sGOStorage.MaxEntry - 1 );
7054 uint32 count = 0;
7056 // collect GO entries for GO that must activated
7057 for(uint32 go_entry = 1; go_entry < sGOStorage.MaxEntry; ++go_entry)
7059 bar.step();
7060 GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(go_entry);
7061 if(!goInfo)
7062 continue;
7064 switch(goInfo->type)
7066 // scan GO chest with loot including quest items
7067 case GAMEOBJECT_TYPE_CHEST:
7069 uint32 loot_id = goInfo->GetLootId();
7071 // find quest loot for GO
7072 if(LootTemplates_Gameobject.HaveQuestLootFor(loot_id))
7074 mGameObjectForQuestSet.insert(go_entry);
7075 ++count;
7077 break;
7079 case GAMEOBJECT_TYPE_GOOBER:
7081 if(goInfo->goober.questId) //quests objects
7083 mGameObjectForQuestSet.insert(go_entry);
7084 count++;
7086 break;
7088 default:
7089 break;
7093 sLog.outString();
7094 sLog.outString( ">> Loaded %u GameObjects for quests", count );
7097 bool ObjectMgr::LoadMangosStrings(DatabaseType& db, char const* table, int32 min_value, int32 max_value)
7099 int32 start_value = min_value;
7100 int32 end_value = max_value;
7101 // some string can have negative indexes range
7102 if (start_value < 0)
7104 if (end_value >= start_value)
7106 sLog.outErrorDb("Table '%s' attempt loaded with invalid range (%d - %d), strings not loaded.",table,min_value,max_value);
7107 return false;
7110 // real range (max+1,min+1) exaple: (-10,-1000) -> -999...-10+1
7111 std::swap(start_value,end_value);
7112 ++start_value;
7113 ++end_value;
7115 else
7117 if (start_value >= end_value)
7119 sLog.outErrorDb("Table '%s' attempt loaded with invalid range (%d - %d), strings not loaded.",table,min_value,max_value);
7120 return false;
7124 // cleanup affected map part for reloading case
7125 for(MangosStringLocaleMap::iterator itr = mMangosStringLocaleMap.begin(); itr != mMangosStringLocaleMap.end();)
7127 if (itr->first >= start_value && itr->first < end_value)
7128 mMangosStringLocaleMap.erase(itr++);
7129 else
7130 ++itr;
7133 QueryResult *result = db.PQuery("SELECT entry,content_default,content_loc1,content_loc2,content_loc3,content_loc4,content_loc5,content_loc6,content_loc7,content_loc8 FROM %s",table);
7135 if (!result)
7137 barGoLink bar(1);
7139 bar.step();
7141 sLog.outString();
7142 if (min_value == MIN_MANGOS_STRING_ID) // error only in case internal strings
7143 sLog.outErrorDb(">> Loaded 0 mangos strings. DB table `%s` is empty. Cannot continue.",table);
7144 else
7145 sLog.outString(">> Loaded 0 string templates. DB table `%s` is empty.",table);
7146 return false;
7149 uint32 count = 0;
7151 barGoLink bar((int)result->GetRowCount());
7155 Field *fields = result->Fetch();
7156 bar.step();
7158 int32 entry = fields[0].GetInt32();
7160 if (entry==0)
7162 sLog.outErrorDb("Table `%s` contain reserved entry 0, ignored.",table);
7163 continue;
7165 else if (entry < start_value || entry >= end_value)
7167 sLog.outErrorDb("Table `%s` contain entry %i out of allowed range (%d - %d), ignored.",table,entry,min_value,max_value);
7168 continue;
7171 MangosStringLocale& data = mMangosStringLocaleMap[entry];
7173 if (data.Content.size() > 0)
7175 sLog.outErrorDb("Table `%s` contain data for already loaded entry %i (from another table?), ignored.",table,entry);
7176 continue;
7179 data.Content.resize(1);
7180 ++count;
7182 // 0 -> default, idx in to idx+1
7183 data.Content[0] = fields[1].GetCppString();
7185 for(int i = 1; i < MAX_LOCALE; ++i)
7187 std::string str = fields[i+1].GetCppString();
7188 if (!str.empty())
7190 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
7191 if (idx >= 0)
7193 // 0 -> default, idx in to idx+1
7194 if ((int32)data.Content.size() <= idx+1)
7195 data.Content.resize(idx+2);
7197 data.Content[idx+1] = str;
7201 } while (result->NextRow());
7203 delete result;
7205 sLog.outString();
7206 if (min_value == MIN_MANGOS_STRING_ID)
7207 sLog.outString( ">> Loaded %u MaNGOS strings from table %s", count,table);
7208 else
7209 sLog.outString( ">> Loaded %u string templates from %s", count,table);
7211 return true;
7214 const char *ObjectMgr::GetMangosString(int32 entry, int locale_idx) const
7216 // locale_idx==-1 -> default, locale_idx >= 0 in to idx+1
7217 // Content[0] always exist if exist MangosStringLocale
7218 if(MangosStringLocale const *msl = GetMangosStringLocale(entry))
7220 if((int32)msl->Content.size() > locale_idx+1 && !msl->Content[locale_idx+1].empty())
7221 return msl->Content[locale_idx+1].c_str();
7222 else
7223 return msl->Content[0].c_str();
7226 if(entry > 0)
7227 sLog.outErrorDb("Entry %i not found in `mangos_string` table.",entry);
7228 else
7229 sLog.outErrorDb("Mangos string entry %i not found in DB.",entry);
7230 return "<error>";
7233 void ObjectMgr::LoadFishingBaseSkillLevel()
7235 mFishingBaseForArea.clear(); // for reload case
7237 uint32 count = 0;
7238 QueryResult *result = WorldDatabase.Query("SELECT entry,skill FROM skill_fishing_base_level");
7240 if( !result )
7242 barGoLink bar( 1 );
7244 bar.step();
7246 sLog.outString();
7247 sLog.outErrorDb(">> Loaded `skill_fishing_base_level`, table is empty!");
7248 return;
7251 barGoLink bar((int) result->GetRowCount() );
7255 bar.step();
7257 Field *fields = result->Fetch();
7258 uint32 entry = fields[0].GetUInt32();
7259 int32 skill = fields[1].GetInt32();
7261 AreaTableEntry const* fArea = GetAreaEntryByAreaID(entry);
7262 if(!fArea)
7264 sLog.outErrorDb("AreaId %u defined in `skill_fishing_base_level` does not exist",entry);
7265 continue;
7268 mFishingBaseForArea[entry] = skill;
7269 ++count;
7271 while (result->NextRow());
7273 delete result;
7275 sLog.outString();
7276 sLog.outString( ">> Loaded %u areas for fishing base skill level", count );
7279 // Searches for the same condition already in Conditions store
7280 // Returns Id if found, else adds it to Conditions and returns Id
7281 uint16 ObjectMgr::GetConditionId( ConditionType condition, uint32 value1, uint32 value2 )
7283 PlayerCondition lc = PlayerCondition(condition, value1, value2);
7284 for (uint16 i=0; i < mConditions.size(); ++i)
7286 if (lc == mConditions[i])
7287 return i;
7290 mConditions.push_back(lc);
7292 if(mConditions.size() > 0xFFFF)
7294 sLog.outError("Conditions store overflow! Current and later loaded conditions will ignored!");
7295 return 0;
7298 return mConditions.size() - 1;
7301 bool ObjectMgr::CheckDeclinedNames( std::wstring mainpart, DeclinedName const& names )
7303 for(int i =0; i < MAX_DECLINED_NAME_CASES; ++i)
7305 std::wstring wname;
7306 if(!Utf8toWStr(names.name[i],wname))
7307 return false;
7309 if(mainpart!=GetMainPartOfName(wname,i+1))
7310 return false;
7312 return true;
7315 uint32 ObjectMgr::GetAreaTriggerScriptId(uint32 trigger_id)
7317 AreaTriggerScriptMap::const_iterator i = mAreaTriggerScripts.find(trigger_id);
7318 if(i!= mAreaTriggerScripts.end())
7319 return i->second;
7320 return 0;
7323 // Checks if player meets the condition
7324 bool PlayerCondition::Meets(Player const * player) const
7326 if( !player )
7327 return false; // player not present, return false
7329 switch (condition)
7331 case CONDITION_NONE:
7332 return true; // empty condition, always met
7333 case CONDITION_AURA:
7334 return player->HasAura(value1, SpellEffectIndex(value2));
7335 case CONDITION_ITEM:
7336 return player->HasItemCount(value1, value2);
7337 case CONDITION_ITEM_EQUIPPED:
7338 return player->HasItemOrGemWithIdEquipped(value1,1);
7339 case CONDITION_ZONEID:
7340 return player->GetZoneId() == value1;
7341 case CONDITION_REPUTATION_RANK:
7343 FactionEntry const* faction = sFactionStore.LookupEntry(value1);
7344 return faction && player->GetReputationMgr().GetRank(faction) >= ReputationRank(value2);
7346 case CONDITION_TEAM:
7347 return player->GetTeam() == value1;
7348 case CONDITION_SKILL:
7349 return player->HasSkill(value1) && player->GetBaseSkillValue(value1) >= value2;
7350 case CONDITION_QUESTREWARDED:
7351 return player->GetQuestRewardStatus(value1);
7352 case CONDITION_QUESTTAKEN:
7354 QuestStatus status = player->GetQuestStatus(value1);
7355 return (status == QUEST_STATUS_INCOMPLETE);
7357 case CONDITION_AD_COMMISSION_AURA:
7359 Unit::AuraMap const& auras = player->GetAuras();
7360 for(Unit::AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
7361 if((itr->second->GetSpellProto()->Attributes & 0x1000010) && itr->second->GetSpellProto()->SpellVisual[0]==3580)
7362 return true;
7363 return false;
7365 case CONDITION_NO_AURA:
7366 return !player->HasAura(value1, SpellEffectIndex(value2));
7367 case CONDITION_ACTIVE_EVENT:
7368 return sGameEventMgr.IsActiveEvent(value1);
7369 case CONDITION_AREA_FLAG:
7371 if (AreaTableEntry const *pAreaEntry = GetAreaEntryByAreaID(player->GetAreaId()))
7373 if ((!value1 || (pAreaEntry->flags & value1)) && (!value2 || !(pAreaEntry->flags & value2)))
7374 return true;
7376 return false;
7378 case CONDITION_RACE_CLASS:
7379 if ((!value1 || (player->getRaceMask() & value1)) && (!value2 || (player->getClassMask() & value2)))
7380 return true;
7381 return false;
7382 case CONDITION_LEVEL:
7384 switch(value2)
7386 case 0: return player->getLevel() == value1;
7387 case 1: return player->getLevel() >= value1;
7388 case 2: return player->getLevel() <= value1;
7390 return false;
7392 case CONDITION_NOITEM:
7393 return !player->HasItemCount(value1, value2);
7394 case CONDITION_SPELL:
7396 switch(value2)
7398 case 0: return player->HasSpell(value1);
7399 case 1: return !player->HasSpell(value1);
7401 return false;
7403 case CONDITION_INSTANCE_SCRIPT:
7405 // have meaning only for specific map instance script so ignore other maps
7406 if (player->GetMapId() != value1)
7407 return false;
7408 if (InstanceData* data = player->GetInstanceData())
7409 return data->CheckConditionCriteriaMeet(player, value1, value2);
7410 return false;
7412 default:
7413 return false;
7417 // Verification of condition values validity
7418 bool PlayerCondition::IsValid(ConditionType condition, uint32 value1, uint32 value2)
7420 if( condition >= MAX_CONDITION) // Wrong condition type
7422 sLog.outErrorDb("Condition has bad type of %u, skipped ", condition );
7423 return false;
7426 switch (condition)
7428 case CONDITION_AURA:
7430 if(!sSpellStore.LookupEntry(value1))
7432 sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
7433 return false;
7435 if(value2 >= MAX_EFFECT_INDEX)
7437 sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..%u), skipped", value2, MAX_EFFECT_INDEX-1);
7438 return false;
7440 break;
7442 case CONDITION_ITEM:
7443 case CONDITION_NOITEM:
7445 ItemPrototype const *proto = ObjectMgr::GetItemPrototype(value1);
7446 if(!proto)
7448 sLog.outErrorDb("Item condition requires to have non existing item (%u), skipped", value1);
7449 return false;
7452 if(value2 < 1)
7454 sLog.outErrorDb("Item condition useless with count < 1, skipped");
7455 return false;
7457 break;
7459 case CONDITION_ITEM_EQUIPPED:
7461 ItemPrototype const *proto = ObjectMgr::GetItemPrototype(value1);
7462 if(!proto)
7464 sLog.outErrorDb("ItemEquipped condition requires to have non existing item (%u) equipped, skipped", value1);
7465 return false;
7467 break;
7469 case CONDITION_ZONEID:
7471 AreaTableEntry const* areaEntry = GetAreaEntryByAreaID(value1);
7472 if(!areaEntry)
7474 sLog.outErrorDb("Zone condition requires to be in non existing area (%u), skipped", value1);
7475 return false;
7477 if(areaEntry->zone != 0)
7479 sLog.outErrorDb("Zone condition requires to be in area (%u) which is a subzone but zone expected, skipped", value1);
7480 return false;
7482 break;
7484 case CONDITION_REPUTATION_RANK:
7486 FactionEntry const* factionEntry = sFactionStore.LookupEntry(value1);
7487 if(!factionEntry)
7489 sLog.outErrorDb("Reputation condition requires to have reputation non existing faction (%u), skipped", value1);
7490 return false;
7492 break;
7494 case CONDITION_TEAM:
7496 if (value1 != ALLIANCE && value1 != HORDE)
7498 sLog.outErrorDb("Team condition specifies unknown team (%u), skipped", value1);
7499 return false;
7501 break;
7503 case CONDITION_SKILL:
7505 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(value1);
7506 if (!pSkill)
7508 sLog.outErrorDb("Skill condition specifies non-existing skill (%u), skipped", value1);
7509 return false;
7511 if (value2 < 1 || value2 > sWorld.GetConfigMaxSkillValue() )
7513 sLog.outErrorDb("Skill condition specifies invalid skill value (%u), skipped", value2);
7514 return false;
7516 break;
7518 case CONDITION_QUESTREWARDED:
7519 case CONDITION_QUESTTAKEN:
7521 Quest const *Quest = sObjectMgr.GetQuestTemplate(value1);
7522 if (!Quest)
7524 sLog.outErrorDb("Quest condition specifies non-existing quest (%u), skipped", value1);
7525 return false;
7527 if(value2)
7528 sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
7529 break;
7531 case CONDITION_AD_COMMISSION_AURA:
7533 if(value1)
7534 sLog.outErrorDb("Quest condition has useless data in value1 (%u)!", value1);
7535 if(value2)
7536 sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
7537 break;
7539 case CONDITION_NO_AURA:
7541 if(!sSpellStore.LookupEntry(value1))
7543 sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
7544 return false;
7546 if(value2 > MAX_EFFECT_INDEX)
7548 sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..%u), skipped", value2, MAX_EFFECT_INDEX-1);
7549 return false;
7551 break;
7553 case CONDITION_ACTIVE_EVENT:
7555 GameEventMgr::GameEventDataMap const& events = sGameEventMgr.GetEventMap();
7556 if(value1 >=events.size() || !events[value1].isValid())
7558 sLog.outErrorDb("Active event condition requires existed event id (%u), skipped", value1);
7559 return false;
7561 break;
7563 case CONDITION_AREA_FLAG:
7565 if (!value1 && !value2)
7567 sLog.outErrorDb("Area flag condition has both values like 0, skipped");
7568 return false;
7570 break;
7572 case CONDITION_RACE_CLASS:
7574 if (!value1 && !value2)
7576 sLog.outErrorDb("Race_class condition has both values like 0, skipped");
7577 return false;
7580 if (value1 && !(value1 & RACEMASK_ALL_PLAYABLE))
7582 sLog.outErrorDb("Race_class condition has invalid player class %u, skipped", value1);
7583 return false;
7586 if (value2 && !(value2 & CLASSMASK_ALL_PLAYABLE))
7588 sLog.outErrorDb("Race_class condition has invalid race mask %u, skipped", value2);
7589 return false;
7591 break;
7593 case CONDITION_LEVEL:
7595 if (!value1 || value1 > sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
7597 sLog.outErrorDb("Level condition has invalid level %u, skipped", value1);
7598 return false;
7601 if (value2 > 2)
7603 sLog.outErrorDb("Level condition has invalid argument %u (must be 0..2), skipped", value2);
7604 return false;
7607 break;
7609 case CONDITION_SPELL:
7611 if(!sSpellStore.LookupEntry(value1))
7613 sLog.outErrorDb("Spell condition requires to have non existing spell (Id: %d), skipped", value1);
7614 return false;
7617 if (value2 > 1)
7619 sLog.outErrorDb("Spell condition has invalid argument %u (must be 0..1), skipped", value2);
7620 return false;
7623 break;
7625 case CONDITION_INSTANCE_SCRIPT:
7627 MapEntry const* mapEntry = sMapStore.LookupEntry(value1);
7628 if (!mapEntry || !mapEntry->IsDungeon())
7630 sLog.outErrorDb("Instance script condition has not existed map id %u as first arg, skipped", value1);
7631 return false;
7634 break;
7636 case CONDITION_NONE:
7637 break;
7639 return true;
7642 SkillRangeType GetSkillRangeType(SkillLineEntry const *pSkill, bool racial)
7644 switch(pSkill->categoryId)
7646 case SKILL_CATEGORY_LANGUAGES: return SKILL_RANGE_LANGUAGE;
7647 case SKILL_CATEGORY_WEAPON:
7648 if(pSkill->id!=SKILL_FIST_WEAPONS)
7649 return SKILL_RANGE_LEVEL;
7650 else
7651 return SKILL_RANGE_MONO;
7652 case SKILL_CATEGORY_ARMOR:
7653 case SKILL_CATEGORY_CLASS:
7654 if(pSkill->id != SKILL_LOCKPICKING)
7655 return SKILL_RANGE_MONO;
7656 else
7657 return SKILL_RANGE_LEVEL;
7658 case SKILL_CATEGORY_SECONDARY:
7659 case SKILL_CATEGORY_PROFESSION:
7660 // not set skills for professions and racial abilities
7661 if(IsProfessionSkill(pSkill->id))
7662 return SKILL_RANGE_RANK;
7663 else if(racial)
7664 return SKILL_RANGE_NONE;
7665 else
7666 return SKILL_RANGE_MONO;
7667 default:
7668 case SKILL_CATEGORY_ATTRIBUTES: //not found in dbc
7669 case SKILL_CATEGORY_GENERIC: //only GENERIC(DND)
7670 return SKILL_RANGE_NONE;
7674 void ObjectMgr::LoadGameTele()
7676 m_GameTeleMap.clear(); // for reload case
7678 uint32 count = 0;
7679 QueryResult *result = WorldDatabase.Query("SELECT id, position_x, position_y, position_z, orientation, map, name FROM game_tele");
7681 if( !result )
7683 barGoLink bar( 1 );
7685 bar.step();
7687 sLog.outString();
7688 sLog.outErrorDb(">> Loaded `game_tele`, table is empty!");
7689 return;
7692 barGoLink bar( (int)result->GetRowCount() );
7696 bar.step();
7698 Field *fields = result->Fetch();
7700 uint32 id = fields[0].GetUInt32();
7702 GameTele gt;
7704 gt.position_x = fields[1].GetFloat();
7705 gt.position_y = fields[2].GetFloat();
7706 gt.position_z = fields[3].GetFloat();
7707 gt.orientation = fields[4].GetFloat();
7708 gt.mapId = fields[5].GetUInt32();
7709 gt.name = fields[6].GetCppString();
7711 if(!MapManager::IsValidMapCoord(gt.mapId,gt.position_x,gt.position_y,gt.position_z,gt.orientation))
7713 sLog.outErrorDb("Wrong position for id %u (name: %s) in `game_tele` table, ignoring.",id,gt.name.c_str());
7714 continue;
7717 if(!Utf8toWStr(gt.name,gt.wnameLow))
7719 sLog.outErrorDb("Wrong UTF8 name for id %u in `game_tele` table, ignoring.",id);
7720 continue;
7723 wstrToLower( gt.wnameLow );
7725 m_GameTeleMap[id] = gt;
7727 ++count;
7729 while (result->NextRow());
7730 delete result;
7732 sLog.outString();
7733 sLog.outString( ">> Loaded %u GameTeleports", count );
7736 GameTele const* ObjectMgr::GetGameTele(const std::string& name) const
7738 // explicit name case
7739 std::wstring wname;
7740 if(!Utf8toWStr(name,wname))
7741 return false;
7743 // converting string that we try to find to lower case
7744 wstrToLower( wname );
7746 // Alternative first GameTele what contains wnameLow as substring in case no GameTele location found
7747 const GameTele* alt = NULL;
7748 for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
7749 if(itr->second.wnameLow == wname)
7750 return &itr->second;
7751 else if (alt == NULL && itr->second.wnameLow.find(wname) != std::wstring::npos)
7752 alt = &itr->second;
7754 return alt;
7757 bool ObjectMgr::AddGameTele(GameTele& tele)
7759 // find max id
7760 uint32 new_id = 0;
7761 for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
7762 if(itr->first > new_id)
7763 new_id = itr->first;
7765 // use next
7766 ++new_id;
7768 if(!Utf8toWStr(tele.name,tele.wnameLow))
7769 return false;
7771 wstrToLower( tele.wnameLow );
7773 m_GameTeleMap[new_id] = tele;
7775 return WorldDatabase.PExecuteLog("INSERT INTO game_tele (id,position_x,position_y,position_z,orientation,map,name) VALUES (%u,%f,%f,%f,%f,%d,'%s')",
7776 new_id,tele.position_x,tele.position_y,tele.position_z,tele.orientation,tele.mapId,tele.name.c_str());
7779 bool ObjectMgr::DeleteGameTele(const std::string& name)
7781 // explicit name case
7782 std::wstring wname;
7783 if(!Utf8toWStr(name,wname))
7784 return false;
7786 // converting string that we try to find to lower case
7787 wstrToLower( wname );
7789 for(GameTeleMap::iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
7791 if(itr->second.wnameLow == wname)
7793 WorldDatabase.PExecuteLog("DELETE FROM game_tele WHERE name = '%s'",itr->second.name.c_str());
7794 m_GameTeleMap.erase(itr);
7795 return true;
7799 return false;
7802 void ObjectMgr::LoadMailLevelRewards()
7804 m_mailLevelRewardMap.clear(); // for reload case
7806 uint32 count = 0;
7807 QueryResult *result = WorldDatabase.Query("SELECT level, raceMask, mailTemplateId, senderEntry FROM mail_level_reward");
7809 if( !result )
7811 barGoLink bar( 1 );
7813 bar.step();
7815 sLog.outString();
7816 sLog.outErrorDb(">> Loaded `mail_level_reward`, table is empty!");
7817 return;
7820 barGoLink bar((int) result->GetRowCount() );
7824 bar.step();
7826 Field *fields = result->Fetch();
7828 uint8 level = fields[0].GetUInt8();
7829 uint32 raceMask = fields[1].GetUInt32();
7830 uint32 mailTemplateId = fields[2].GetUInt32();
7831 uint32 senderEntry = fields[3].GetUInt32();
7833 if(level > MAX_LEVEL)
7835 sLog.outErrorDb("Table `mail_level_reward` have data for level %u that more supported by client (%u), ignoring.",level,MAX_LEVEL);
7836 continue;
7839 if(!(raceMask & RACEMASK_ALL_PLAYABLE))
7841 sLog.outErrorDb("Table `mail_level_reward` have raceMask (%u) for level %u that not include any player races, ignoring.",raceMask,level);
7842 continue;
7845 if(!sMailTemplateStore.LookupEntry(mailTemplateId))
7847 sLog.outErrorDb("Table `mail_level_reward` have invalid mailTemplateId (%u) for level %u that invalid not include any player races, ignoring.",mailTemplateId,level);
7848 continue;
7851 if(!GetCreatureTemplateStore(senderEntry))
7853 sLog.outErrorDb("Table `mail_level_reward` have not existed sender creature entry (%u) for level %u that invalid not include any player races, ignoring.",senderEntry,level);
7854 continue;
7857 m_mailLevelRewardMap[level].push_back(MailLevelReward(raceMask,mailTemplateId,senderEntry));
7859 ++count;
7861 while (result->NextRow());
7862 delete result;
7864 sLog.outString();
7865 sLog.outString( ">> Loaded %u level dependent mail rewards,", count );
7868 void ObjectMgr::LoadTrainerSpell()
7870 // For reload case
7871 for (CacheTrainerSpellMap::iterator itr = m_mCacheTrainerSpellMap.begin(); itr != m_mCacheTrainerSpellMap.end(); ++itr)
7872 itr->second.Clear();
7873 m_mCacheTrainerSpellMap.clear();
7875 std::set<uint32> skip_trainers;
7877 QueryResult *result = WorldDatabase.Query("SELECT entry, spell,spellcost,reqskill,reqskillvalue,reqlevel FROM npc_trainer");
7879 if( !result )
7881 barGoLink bar( 1 );
7883 bar.step();
7885 sLog.outString();
7886 sLog.outErrorDb(">> Loaded `npc_trainer`, table is empty!");
7887 return;
7890 barGoLink bar( (int)result->GetRowCount() );
7892 std::set<uint32> talentIds;
7894 uint32 count = 0;
7897 bar.step();
7899 Field* fields = result->Fetch();
7901 uint32 entry = fields[0].GetUInt32();
7902 uint32 spell = fields[1].GetUInt32();
7904 CreatureInfo const* cInfo = GetCreatureTemplate(entry);
7906 if(!cInfo)
7908 sLog.outErrorDb("Table `npc_trainer` have entry for not existed creature template (Entry: %u), ignore", entry);
7909 continue;
7912 if(!(cInfo->npcflag & UNIT_NPC_FLAG_TRAINER))
7914 if (skip_trainers.find(entry) == skip_trainers.end())
7916 sLog.outErrorDb("Table `npc_trainer` have data for creature (Entry: %u) without trainer flag, ignore", entry);
7917 skip_trainers.insert(entry);
7919 continue;
7922 SpellEntry const *spellinfo = sSpellStore.LookupEntry(spell);
7923 if(!spellinfo)
7925 sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u ) has non existing spell %u, ignore", entry,spell);
7926 continue;
7929 if(!SpellMgr::IsSpellValid(spellinfo))
7931 sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u) has broken learning spell %u, ignore", entry, spell);
7932 continue;
7935 if(GetTalentSpellCost(spell))
7937 if (talentIds.find(spell) == talentIds.end())
7939 sLog.outErrorDb("Table `npc_trainer` has talent as learning spell %u, ignore", spell);
7940 talentIds.insert(spell);
7942 continue;
7945 TrainerSpellData& data = m_mCacheTrainerSpellMap[entry];
7947 TrainerSpell& trainerSpell = data.spellList[spell];
7948 trainerSpell.spell = spell;
7949 trainerSpell.spellCost = fields[2].GetUInt32();
7950 trainerSpell.reqSkill = fields[3].GetUInt32();
7951 trainerSpell.reqSkillValue = fields[4].GetUInt32();
7952 trainerSpell.reqLevel = fields[5].GetUInt32();
7954 if(!trainerSpell.reqLevel)
7955 trainerSpell.reqLevel = spellinfo->spellLevel;
7957 // calculate learned spell for profession case when stored cast-spell
7958 trainerSpell.learnedSpell = spell;
7959 for(int i = 0; i < MAX_EFFECT_INDEX; ++i)
7961 if (spellinfo->Effect[i] != SPELL_EFFECT_LEARN_SPELL)
7962 continue;
7963 if (SpellMgr::IsProfessionOrRidingSpell(spellinfo->EffectTriggerSpell[i]))
7965 trainerSpell.learnedSpell = spellinfo->EffectTriggerSpell[i];
7966 break;
7970 if(SpellMgr::IsProfessionSpell(trainerSpell.learnedSpell))
7971 data.trainerType = 2;
7973 ++count;
7975 } while (result->NextRow());
7976 delete result;
7978 sLog.outString();
7979 sLog.outString( ">> Loaded %d Trainers", count );
7982 void ObjectMgr::LoadVendors()
7984 // For reload case
7985 for (CacheVendorItemMap::iterator itr = m_mCacheVendorItemMap.begin(); itr != m_mCacheVendorItemMap.end(); ++itr)
7986 itr->second.Clear();
7987 m_mCacheVendorItemMap.clear();
7989 std::set<uint32> skip_vendors;
7991 QueryResult *result = WorldDatabase.Query("SELECT entry, item, maxcount, incrtime, ExtendedCost FROM npc_vendor");
7992 if( !result )
7994 barGoLink bar( 1 );
7996 bar.step();
7998 sLog.outString();
7999 sLog.outErrorDb(">> Loaded `npc_vendor`, table is empty!");
8000 return;
8003 barGoLink bar( (int)result->GetRowCount() );
8005 uint32 count = 0;
8008 bar.step();
8009 Field* fields = result->Fetch();
8011 uint32 entry = fields[0].GetUInt32();
8012 uint32 item_id = fields[1].GetUInt32();
8013 uint32 maxcount = fields[2].GetUInt32();
8014 uint32 incrtime = fields[3].GetUInt32();
8015 int32 ExtendedCost = fields[4].GetInt32();
8017 if(!IsVendorItemValid(entry,item_id,maxcount,incrtime,ExtendedCost,NULL,&skip_vendors))
8018 continue;
8020 VendorItemData& vList = m_mCacheVendorItemMap[entry];
8022 vList.AddItem(item_id,maxcount,incrtime,ExtendedCost);
8023 ++count;
8025 } while (result->NextRow());
8026 delete result;
8028 sLog.outString();
8029 sLog.outString( ">> Loaded %d Vendors ", count );
8032 void ObjectMgr::LoadNpcTextId()
8035 m_mCacheNpcTextIdMap.clear();
8037 QueryResult* result = WorldDatabase.Query("SELECT npc_guid, textid FROM npc_gossip");
8038 if( !result )
8040 barGoLink bar( 1 );
8042 bar.step();
8044 sLog.outString();
8045 sLog.outErrorDb(">> Loaded `npc_gossip`, table is empty!");
8046 return;
8049 barGoLink bar((int) result->GetRowCount() );
8051 uint32 count = 0;
8052 uint32 guid,textid;
8055 bar.step();
8057 Field* fields = result->Fetch();
8059 guid = fields[0].GetUInt32();
8060 textid = fields[1].GetUInt32();
8062 if (!GetCreatureData(guid))
8064 sLog.outErrorDb("Table `npc_gossip` have not existed creature (GUID: %u) entry, ignore. ",guid);
8065 continue;
8067 if (!GetGossipText(textid))
8069 sLog.outErrorDb("Table `npc_gossip` for creature (GUID: %u) have wrong Textid (%u), ignore. ", guid, textid);
8070 continue;
8073 m_mCacheNpcTextIdMap[guid] = textid ;
8074 ++count;
8076 } while (result->NextRow());
8077 delete result;
8079 sLog.outString();
8080 sLog.outString( ">> Loaded %d NpcTextId ", count );
8083 void ObjectMgr::LoadGossipMenu()
8085 m_mGossipMenusMap.clear();
8087 QueryResult* result = WorldDatabase.Query("SELECT entry, text_id, "
8088 "cond_1, cond_1_val_1, cond_1_val_2, cond_2, cond_2_val_1, cond_2_val_2 FROM gossip_menu");
8090 if (!result)
8092 barGoLink bar(1);
8094 bar.step();
8096 sLog.outString();
8097 sLog.outErrorDb(">> Loaded gossip_menu, table is empty!");
8098 return;
8101 barGoLink bar( (int)result->GetRowCount() );
8103 uint32 count = 0;
8107 bar.step();
8109 Field* fields = result->Fetch();
8111 GossipMenus gMenu;
8113 gMenu.entry = fields[0].GetUInt32();
8114 gMenu.text_id = fields[1].GetUInt32();
8116 ConditionType cond_1 = (ConditionType)fields[2].GetUInt32();
8117 uint32 cond_1_val_1 = fields[3].GetUInt32();
8118 uint32 cond_1_val_2 = fields[4].GetUInt32();
8119 ConditionType cond_2 = (ConditionType)fields[5].GetUInt32();
8120 uint32 cond_2_val_1 = fields[6].GetUInt32();
8121 uint32 cond_2_val_2 = fields[7].GetUInt32();
8123 if (!GetGossipText(gMenu.text_id))
8125 sLog.outErrorDb("Table gossip_menu entry %u are using non-existing text_id %u", gMenu.entry, gMenu.text_id);
8126 continue;
8129 if (!PlayerCondition::IsValid(cond_1, cond_1_val_1, cond_1_val_2))
8131 sLog.outErrorDb("Table gossip_menu entry %u, invalid condition 1 for id %u", gMenu.entry, gMenu.text_id);
8132 continue;
8135 if (!PlayerCondition::IsValid(cond_2, cond_2_val_1, cond_2_val_2))
8137 sLog.outErrorDb("Table gossip_menu entry %u, invalid condition 2 for id %u", gMenu.entry, gMenu.text_id);
8138 continue;
8141 gMenu.cond_1 = GetConditionId(cond_1, cond_1_val_1, cond_1_val_2);
8142 gMenu.cond_2 = GetConditionId(cond_2, cond_2_val_1, cond_2_val_2);
8144 m_mGossipMenusMap.insert(GossipMenusMap::value_type(gMenu.entry, gMenu));
8146 ++count;
8148 while(result->NextRow());
8150 delete result;
8152 sLog.outString();
8153 sLog.outString( ">> Loaded %u gossip_menu entries", count);
8156 void ObjectMgr::LoadGossipMenuItems()
8158 m_mGossipMenuItemsMap.clear();
8160 QueryResult *result = WorldDatabase.Query(
8161 "SELECT menu_id, id, option_icon, option_text, option_id, npc_option_npcflag, "
8162 "action_menu_id, action_poi_id, action_script_id, box_coded, box_money, box_text, "
8163 "cond_1, cond_1_val_1, cond_1_val_2, "
8164 "cond_2, cond_2_val_1, cond_2_val_2, "
8165 "cond_3, cond_3_val_1, cond_3_val_2 "
8166 "FROM gossip_menu_option");
8168 if (!result)
8170 barGoLink bar(1);
8172 bar.step();
8174 sLog.outString();
8175 sLog.outErrorDb(">> Loaded gossip_menu_option, table is empty!");
8176 return;
8179 barGoLink bar((int)result->GetRowCount());
8181 uint32 count = 0;
8183 std::set<uint32> gossipScriptSet;
8185 for(ScriptMapMap::const_iterator itr = sGossipScripts.begin(); itr != sGossipScripts.end(); ++itr)
8186 gossipScriptSet.insert(itr->first);
8190 bar.step();
8192 Field* fields = result->Fetch();
8194 GossipMenuItems gMenuItem;
8196 gMenuItem.menu_id = fields[0].GetUInt32();
8197 gMenuItem.id = fields[1].GetUInt32();
8198 gMenuItem.option_icon = fields[2].GetUInt8();
8199 gMenuItem.option_text = fields[3].GetCppString();
8200 gMenuItem.option_id = fields[4].GetUInt32();
8201 gMenuItem.npc_option_npcflag = fields[5].GetUInt32();
8202 gMenuItem.action_menu_id = fields[6].GetUInt32();
8203 gMenuItem.action_poi_id = fields[7].GetUInt32();
8204 gMenuItem.action_script_id = fields[8].GetUInt32();
8205 gMenuItem.box_coded = fields[9].GetUInt8() != 0;
8206 gMenuItem.box_money = fields[10].GetUInt32();
8207 gMenuItem.box_text = fields[11].GetCppString();
8209 ConditionType cond_1 = (ConditionType)fields[12].GetUInt32();
8210 uint32 cond_1_val_1 = fields[13].GetUInt32();
8211 uint32 cond_1_val_2 = fields[14].GetUInt32();
8212 ConditionType cond_2 = (ConditionType)fields[15].GetUInt32();
8213 uint32 cond_2_val_1 = fields[16].GetUInt32();
8214 uint32 cond_2_val_2 = fields[17].GetUInt32();
8215 ConditionType cond_3 = (ConditionType)fields[18].GetUInt32();
8216 uint32 cond_3_val_1 = fields[19].GetUInt32();
8217 uint32 cond_3_val_2 = fields[20].GetUInt32();
8219 if (!PlayerCondition::IsValid(cond_1, cond_1_val_1, cond_1_val_2))
8221 sLog.outErrorDb("Table gossip_menu_option menu %u, invalid condition 1 for id %u", gMenuItem.menu_id, gMenuItem.id);
8222 continue;
8224 if (!PlayerCondition::IsValid(cond_2, cond_2_val_1, cond_2_val_2))
8226 sLog.outErrorDb("Table gossip_menu_option menu %u, invalid condition 2 for id %u", gMenuItem.menu_id, gMenuItem.id);
8227 continue;
8229 if (!PlayerCondition::IsValid(cond_3, cond_3_val_1, cond_3_val_2))
8231 sLog.outErrorDb("Table gossip_menu_option menu %u, invalid condition 3 for id %u", gMenuItem.menu_id, gMenuItem.id);
8232 continue;
8235 if (gMenuItem.option_icon >= GOSSIP_ICON_MAX)
8237 sLog.outErrorDb("Table gossip_menu_option for menu %u, id %u has unknown icon id %u. Replacing with GOSSIP_ICON_CHAT", gMenuItem.menu_id, gMenuItem.id, gMenuItem.option_icon);
8238 gMenuItem.option_icon = GOSSIP_ICON_CHAT;
8241 if (gMenuItem.option_id == GOSSIP_OPTION_NONE)
8242 sLog.outErrorDb("Table gossip_menu_option for menu %u, id %u use option id GOSSIP_OPTION_NONE. Option will never be used", gMenuItem.menu_id, gMenuItem.id);
8244 if (gMenuItem.option_id >= GOSSIP_OPTION_MAX)
8245 sLog.outErrorDb("Table gossip_menu_option for menu %u, id %u has unknown option id %u. Option will not be used", gMenuItem.menu_id, gMenuItem.id, gMenuItem.option_id);
8247 if (gMenuItem.action_poi_id && !GetPointOfInterest(gMenuItem.action_poi_id))
8249 sLog.outErrorDb("Table gossip_menu_option for menu %u, id %u use non-existing action_poi_id %u, ignoring", gMenuItem.menu_id, gMenuItem.id, gMenuItem.action_poi_id);
8250 gMenuItem.action_poi_id = 0;
8253 if (gMenuItem.action_script_id)
8255 if (gMenuItem.option_id != GOSSIP_OPTION_GOSSIP)
8257 sLog.outErrorDb("Table gossip_menu_option for menu %u, id %u have action_script_id %u but option_id is not GOSSIP_OPTION_GOSSIP, ignoring", gMenuItem.menu_id, gMenuItem.id, gMenuItem.action_script_id);
8258 continue;
8261 if (sGossipScripts.find(gMenuItem.action_script_id) == sGossipScripts.end())
8263 sLog.outErrorDb("Table gossip_menu_option for menu %u, id %u have action_script_id %u that does not exist in `gossip_scripts`, ignoring", gMenuItem.menu_id, gMenuItem.id, gMenuItem.action_script_id);
8264 continue;
8267 gossipScriptSet.erase(gMenuItem.action_script_id);
8270 gMenuItem.cond_1 = GetConditionId(cond_1, cond_1_val_1, cond_1_val_2);
8271 gMenuItem.cond_2 = GetConditionId(cond_2, cond_2_val_1, cond_2_val_2);
8272 gMenuItem.cond_3 = GetConditionId(cond_3, cond_3_val_1, cond_3_val_2);
8274 m_mGossipMenuItemsMap.insert(GossipMenuItemsMap::value_type(gMenuItem.menu_id, gMenuItem));
8276 ++count;
8279 while(result->NextRow());
8281 delete result;
8283 if (!gossipScriptSet.empty())
8285 for(std::set<uint32>::const_iterator itr = gossipScriptSet.begin(); itr != gossipScriptSet.end(); ++itr)
8286 sLog.outErrorDb("Table `gossip_scripts` contain unused script, id %u.", *itr);
8289 sLog.outString();
8290 sLog.outString(">> Loaded %u gossip_menu_option entries", count);
8293 void ObjectMgr::AddVendorItem( uint32 entry,uint32 item, uint32 maxcount, uint32 incrtime, int32 extendedcost )
8295 VendorItemData& vList = m_mCacheVendorItemMap[entry];
8296 vList.AddItem(item,maxcount,incrtime,extendedcost);
8298 WorldDatabase.PExecuteLog("INSERT INTO npc_vendor (entry,item,maxcount,incrtime,extendedcost) VALUES('%u','%u','%u','%u','%i')",entry, item, maxcount,incrtime,extendedcost);
8301 bool ObjectMgr::RemoveVendorItem( uint32 entry,uint32 item )
8303 CacheVendorItemMap::iterator iter = m_mCacheVendorItemMap.find(entry);
8304 if(iter == m_mCacheVendorItemMap.end())
8305 return false;
8307 if(!iter->second.RemoveItem(item))
8308 return false;
8310 WorldDatabase.PExecuteLog("DELETE FROM npc_vendor WHERE entry='%u' AND item='%u'",entry, item);
8311 return true;
8314 bool ObjectMgr::IsVendorItemValid( uint32 vendor_entry, uint32 item_id, uint32 maxcount, uint32 incrtime, int32 ExtendedCost, Player* pl, std::set<uint32>* skip_vendors ) const
8316 CreatureInfo const* cInfo = GetCreatureTemplate(vendor_entry);
8317 if(!cInfo)
8319 if(pl)
8320 ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
8321 else
8322 sLog.outErrorDb("Table `npc_vendor` has data for nonexistent creature (Entry: %u), ignoring", vendor_entry);
8323 return false;
8326 if(!(cInfo->npcflag & UNIT_NPC_FLAG_VENDOR))
8328 if(!skip_vendors || skip_vendors->count(vendor_entry)==0)
8330 if(pl)
8331 ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
8332 else
8333 sLog.outErrorDb("Table `npc_vendor` has data for creature (Entry: %u) without vendor flag, ignoring", vendor_entry);
8335 if(skip_vendors)
8336 skip_vendors->insert(vendor_entry);
8338 return false;
8341 if(!GetItemPrototype(item_id))
8343 if(pl)
8344 ChatHandler(pl).PSendSysMessage(LANG_ITEM_NOT_FOUND, item_id);
8345 else
8346 sLog.outErrorDb("Table `npc_vendor` for vendor (Entry: %u) contain nonexistent item (%u), ignoring",vendor_entry,item_id);
8347 return false;
8350 uint32 extCostId = std::abs(ExtendedCost); // negative exclude for vendor price money part
8352 if(extCostId && !sItemExtendedCostStore.LookupEntry(extCostId))
8354 if(pl)
8355 ChatHandler(pl).PSendSysMessage(LANG_EXTENDED_COST_NOT_EXIST,extCostId);
8356 else
8357 sLog.outErrorDb("Table `npc_vendor` contain item (Entry: %u) with wrong ExtendedCost (%u) for vendor (%u), ignoring",item_id,extCostId,vendor_entry);
8358 return false;
8361 if(maxcount > 0 && incrtime == 0)
8363 if(pl)
8364 ChatHandler(pl).PSendSysMessage("MaxCount!=0 (%u) but IncrTime==0", maxcount);
8365 else
8366 sLog.outErrorDb( "Table `npc_vendor` has `maxcount` (%u) for item %u of vendor (Entry: %u) but `incrtime`=0, ignoring", maxcount, item_id, vendor_entry);
8367 return false;
8369 else if(maxcount==0 && incrtime > 0)
8371 if(pl)
8372 ChatHandler(pl).PSendSysMessage("MaxCount==0 but IncrTime<>=0");
8373 else
8374 sLog.outErrorDb( "Table `npc_vendor` has `maxcount`=0 for item %u of vendor (Entry: %u) but `incrtime`<>0, ignoring", item_id, vendor_entry);
8375 return false;
8378 VendorItemData const* vItems = GetNpcVendorItemList(vendor_entry);
8379 if(!vItems)
8380 return true; // later checks for non-empty lists
8382 if(vItems->FindItemCostPair(item_id,ExtendedCost))
8384 if(pl)
8385 ChatHandler(pl).PSendSysMessage(LANG_ITEM_ALREADY_IN_LIST, item_id, ExtendedCost);
8386 else
8387 sLog.outErrorDb( "Table `npc_vendor` has duplicate items %u (with extended cost %u) for vendor (Entry: %u), ignoring", item_id, ExtendedCost, vendor_entry);
8388 return false;
8391 if(vItems->GetItemCount() >= MAX_VENDOR_ITEMS)
8393 if(pl)
8394 ChatHandler(pl).SendSysMessage(LANG_COMMAND_ADDVENDORITEMITEMS);
8395 else
8396 sLog.outErrorDb( "Table `npc_vendor` has too many items (%u >= %i) for vendor (Entry: %u), ignoring", vItems->GetItemCount(), MAX_VENDOR_ITEMS, vendor_entry);
8397 return false;
8400 return true;
8403 void ObjectMgr::LoadScriptNames()
8405 m_scriptNames.push_back("");
8406 QueryResult *result = WorldDatabase.Query(
8407 "SELECT DISTINCT(ScriptName) FROM creature_template WHERE ScriptName <> '' "
8408 "UNION "
8409 "SELECT DISTINCT(ScriptName) FROM gameobject_template WHERE ScriptName <> '' "
8410 "UNION "
8411 "SELECT DISTINCT(ScriptName) FROM item_template WHERE ScriptName <> '' "
8412 "UNION "
8413 "SELECT DISTINCT(ScriptName) FROM areatrigger_scripts WHERE ScriptName <> '' "
8414 "UNION "
8415 "SELECT DISTINCT(script) FROM instance_template WHERE script <> ''");
8417 if( !result )
8419 barGoLink bar( 1 );
8420 bar.step();
8421 sLog.outString();
8422 sLog.outErrorDb(">> Loaded empty set of Script Names!");
8423 return;
8426 barGoLink bar( (int)result->GetRowCount() );
8427 uint32 count = 0;
8431 bar.step();
8432 m_scriptNames.push_back((*result)[0].GetString());
8433 ++count;
8434 } while (result->NextRow());
8435 delete result;
8437 std::sort(m_scriptNames.begin(), m_scriptNames.end());
8438 sLog.outString();
8439 sLog.outString( ">> Loaded %d Script Names", count );
8442 uint32 ObjectMgr::GetScriptId(const char *name)
8444 // use binary search to find the script name in the sorted vector
8445 // assume "" is the first element
8446 if(!name) return 0;
8447 ScriptNameMap::const_iterator itr =
8448 std::lower_bound(m_scriptNames.begin(), m_scriptNames.end(), name);
8449 if(itr == m_scriptNames.end() || *itr != name) return 0;
8450 return uint32(itr - m_scriptNames.begin());
8453 void ObjectMgr::CheckScriptTexts(ScriptMapMap const& scripts,std::set<int32>& ids)
8455 for(ScriptMapMap::const_iterator itrMM = scripts.begin(); itrMM != scripts.end(); ++itrMM)
8457 for(ScriptMap::const_iterator itrM = itrMM->second.begin(); itrM != itrMM->second.end(); ++itrM)
8459 switch(itrM->second.command)
8461 case SCRIPT_COMMAND_TALK:
8463 if(!GetMangosStringLocale (itrM->second.dataint))
8464 sLog.outErrorDb( "Table `db_script_string` is missing string id %u, used in database script id %u.", itrM->second.dataint, itrMM->first);
8466 if (ids.find(itrM->second.dataint) != ids.end())
8467 ids.erase(itrM->second.dataint);
8474 void ObjectMgr::LoadDbScriptStrings()
8476 LoadMangosStrings(WorldDatabase,"db_script_string",MIN_DB_SCRIPT_STRING_ID,MAX_DB_SCRIPT_STRING_ID);
8478 std::set<int32> ids;
8480 for(int32 i = MIN_DB_SCRIPT_STRING_ID; i < MAX_DB_SCRIPT_STRING_ID; ++i)
8481 if(GetMangosStringLocale(i))
8482 ids.insert(i);
8484 CheckScriptTexts(sQuestEndScripts,ids);
8485 CheckScriptTexts(sQuestStartScripts,ids);
8486 CheckScriptTexts(sSpellScripts,ids);
8487 CheckScriptTexts(sGameObjectScripts,ids);
8488 CheckScriptTexts(sEventScripts,ids);
8489 CheckScriptTexts(sGossipScripts,ids);
8490 CheckScriptTexts(sCreatureMovementScripts,ids);
8492 sWaypointMgr.CheckTextsExistance(ids);
8494 for(std::set<int32>::const_iterator itr = ids.begin(); itr != ids.end(); ++itr)
8495 sLog.outErrorDb( "Table `db_script_string` has unused string id %u", *itr);
8498 void ObjectMgr::AddGuild( Guild* guild )
8500 mGuildMap[guild->GetId()] = guild ;
8503 void ObjectMgr::RemoveGuild( uint32 Id )
8505 mGuildMap.erase(Id);
8508 void ObjectMgr::AddGroup( Group* group )
8510 mGroupMap[group->GetId()] = group ;
8513 void ObjectMgr::RemoveGroup( Group* group )
8515 mGroupMap.erase(group->GetId());
8518 void ObjectMgr::AddArenaTeam( ArenaTeam* arenaTeam )
8520 mArenaTeamMap[arenaTeam->GetId()] = arenaTeam;
8523 void ObjectMgr::RemoveArenaTeam( uint32 Id )
8525 mArenaTeamMap.erase(Id);
8528 // Functions for scripting access
8529 uint32 GetAreaTriggerScriptId(uint32 trigger_id)
8531 return sObjectMgr.GetAreaTriggerScriptId(trigger_id);
8534 bool LoadMangosStrings(DatabaseType& db, char const* table,int32 start_value, int32 end_value)
8536 // MAX_DB_SCRIPT_STRING_ID is max allowed negative value for scripts (scrpts can use only more deep negative values
8537 // start/end reversed for negative values
8538 if (start_value > MAX_DB_SCRIPT_STRING_ID || end_value >= start_value)
8540 sLog.outErrorDb("Table '%s' attempt loaded with reserved by mangos range (%d - %d), strings not loaded.",table,start_value,end_value+1);
8541 return false;
8544 return sObjectMgr.LoadMangosStrings(db,table,start_value,end_value);
8547 uint32 MANGOS_DLL_SPEC GetScriptId(const char *name)
8549 return sObjectMgr.GetScriptId(name);
8552 ObjectMgr::ScriptNameMap & GetScriptNames()
8554 return sObjectMgr.GetScriptNames();
8557 CreatureInfo const* GetCreatureTemplateStore(uint32 entry)
8559 return sCreatureStorage.LookupEntry<CreatureInfo>(entry);
8562 Quest const* GetQuestTemplateStore(uint32 entry)
8564 return sObjectMgr.GetQuestTemplate(entry);