[9290] Some cleanups in realmd, no functional changes
[getmangos.git] / src / game / ObjectMgr.cpp
bloba15243256bfb5963af0d666d433712263be16a6a
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 "ObjectDefines.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"
48 INSTANTIATE_SINGLETON_1(ObjectMgr);
50 ScriptMapMap sQuestEndScripts;
51 ScriptMapMap sQuestStartScripts;
52 ScriptMapMap sSpellScripts;
53 ScriptMapMap sGameObjectScripts;
54 ScriptMapMap sEventScripts;
55 ScriptMapMap sGossipScripts;
57 bool normalizePlayerName(std::string& name)
59 if(name.empty())
60 return false;
62 wchar_t wstr_buf[MAX_INTERNAL_PLAYER_NAME+1];
63 size_t wstr_len = MAX_INTERNAL_PLAYER_NAME;
65 if(!Utf8toWStr(name,&wstr_buf[0],wstr_len))
66 return false;
68 wstr_buf[0] = wcharToUpper(wstr_buf[0]);
69 for(size_t i = 1; i < wstr_len; ++i)
70 wstr_buf[i] = wcharToLower(wstr_buf[i]);
72 if(!WStrToUtf8(wstr_buf,wstr_len,name))
73 return false;
75 return true;
78 LanguageDesc lang_description[LANGUAGES_COUNT] =
80 { LANG_ADDON, 0, 0 },
81 { LANG_UNIVERSAL, 0, 0 },
82 { LANG_ORCISH, 669, SKILL_LANG_ORCISH },
83 { LANG_DARNASSIAN, 671, SKILL_LANG_DARNASSIAN },
84 { LANG_TAURAHE, 670, SKILL_LANG_TAURAHE },
85 { LANG_DWARVISH, 672, SKILL_LANG_DWARVEN },
86 { LANG_COMMON, 668, SKILL_LANG_COMMON },
87 { LANG_DEMONIC, 815, SKILL_LANG_DEMON_TONGUE },
88 { LANG_TITAN, 816, SKILL_LANG_TITAN },
89 { LANG_THALASSIAN, 813, SKILL_LANG_THALASSIAN },
90 { LANG_DRACONIC, 814, SKILL_LANG_DRACONIC },
91 { LANG_KALIMAG, 817, SKILL_LANG_OLD_TONGUE },
92 { LANG_GNOMISH, 7340, SKILL_LANG_GNOMISH },
93 { LANG_TROLL, 7341, SKILL_LANG_TROLL },
94 { LANG_GUTTERSPEAK, 17737, SKILL_LANG_GUTTERSPEAK },
95 { LANG_DRAENEI, 29932, SKILL_LANG_DRAENEI },
96 { LANG_ZOMBIE, 0, 0 },
97 { LANG_GNOMISH_BINARY, 0, 0 },
98 { LANG_GOBLIN_BINARY, 0, 0 }
101 LanguageDesc const* GetLanguageDescByID(uint32 lang)
103 for(int i = 0; i < LANGUAGES_COUNT; ++i)
105 if(uint32(lang_description[i].lang_id) == lang)
106 return &lang_description[i];
109 return NULL;
112 bool SpellClickInfo::IsFitToRequirements(Player const* player) const
114 if(questStart)
116 // not in expected required quest state
117 if (!player || ((!questStartCanActive || !player->IsActiveQuest(questStart)) && !player->GetQuestRewardStatus(questStart)))
118 return false;
121 if(questEnd)
123 // not in expected forbidden quest state
124 if(!player || player->GetQuestRewardStatus(questEnd))
125 return false;
128 return true;
131 ObjectMgr::ObjectMgr()
133 m_hiCharGuid = 1;
134 m_hiCreatureGuid = 1;
135 m_hiItemGuid = 1;
136 m_hiGoGuid = 1;
137 m_hiCorpseGuid = 1;
138 m_hiPetNumber = 1;
139 m_ItemTextId = 1;
140 m_mailid = 1;
141 m_equipmentSetGuid = 1;
142 m_guildId = 1;
143 m_arenaTeamId = 1;
144 m_auctionid = 1;
146 // Only zero condition left, others will be added while loading DB tables
147 mConditions.resize(1);
150 ObjectMgr::~ObjectMgr()
152 for( QuestMap::iterator i = mQuestTemplates.begin( ); i != mQuestTemplates.end( ); ++i )
153 delete i->second;
155 for(PetLevelInfoMap::iterator i = petInfo.begin( ); i != petInfo.end( ); ++i )
156 delete[] i->second;
158 // free only if loaded
159 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
160 delete[] playerClassInfo[class_].levelInfo;
162 for (int race = 0; race < MAX_RACES; ++race)
163 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
164 delete[] playerInfo[race][class_].levelInfo;
166 // free group and guild objects
167 for (GroupMap::iterator itr = mGroupMap.begin(); itr != mGroupMap.end(); ++itr)
168 delete itr->second;
170 for (GuildMap::iterator itr = mGuildMap.begin(); itr != mGuildMap.end(); ++itr)
171 delete itr->second;
173 for (ArenaTeamMap::iterator itr = mArenaTeamMap.begin(); itr != mArenaTeamMap.end(); ++itr)
174 delete itr->second;
176 for (CacheVendorItemMap::iterator itr = m_mCacheVendorItemMap.begin(); itr != m_mCacheVendorItemMap.end(); ++itr)
177 itr->second.Clear();
179 for (CacheTrainerSpellMap::iterator itr = m_mCacheTrainerSpellMap.begin(); itr != m_mCacheTrainerSpellMap.end(); ++itr)
180 itr->second.Clear();
183 Group * ObjectMgr::GetGroupByLeaderLowGUID(uint32 guid) const
185 GroupMap::const_iterator itr = mGroupMap.find(guid);
186 if (itr != mGroupMap.end())
187 return itr->second;
189 return NULL;
192 Guild * ObjectMgr::GetGuildById(uint32 GuildId) const
194 GuildMap::const_iterator itr = mGuildMap.find(GuildId);
195 if (itr != mGuildMap.end())
196 return itr->second;
198 return NULL;
201 Guild * ObjectMgr::GetGuildByName(const std::string& guildname) const
203 for(GuildMap::const_iterator itr = mGuildMap.begin(); itr != mGuildMap.end(); ++itr)
204 if (itr->second->GetName() == guildname)
205 return itr->second;
207 return NULL;
210 std::string ObjectMgr::GetGuildNameById(uint32 GuildId) const
212 GuildMap::const_iterator itr = mGuildMap.find(GuildId);
213 if (itr != mGuildMap.end())
214 return itr->second->GetName();
216 return "";
219 Guild* ObjectMgr::GetGuildByLeader(const uint64 &guid) const
221 for(GuildMap::const_iterator itr = mGuildMap.begin(); itr != mGuildMap.end(); ++itr)
222 if (itr->second->GetLeader() == guid)
223 return itr->second;
225 return NULL;
228 ArenaTeam* ObjectMgr::GetArenaTeamById(uint32 arenateamid) const
230 ArenaTeamMap::const_iterator itr = mArenaTeamMap.find(arenateamid);
231 if (itr != mArenaTeamMap.end())
232 return itr->second;
234 return NULL;
237 ArenaTeam* ObjectMgr::GetArenaTeamByName(const std::string& arenateamname) const
239 for(ArenaTeamMap::const_iterator itr = mArenaTeamMap.begin(); itr != mArenaTeamMap.end(); ++itr)
240 if (itr->second->GetName() == arenateamname)
241 return itr->second;
243 return NULL;
246 ArenaTeam* ObjectMgr::GetArenaTeamByCaptain(uint64 const& guid) const
248 for(ArenaTeamMap::const_iterator itr = mArenaTeamMap.begin(); itr != mArenaTeamMap.end(); ++itr)
249 if (itr->second->GetCaptain() == guid)
250 return itr->second;
252 return NULL;
255 CreatureInfo const* ObjectMgr::GetCreatureTemplate(uint32 id)
257 return sCreatureStorage.LookupEntry<CreatureInfo>(id);
260 void ObjectMgr::LoadCreatureLocales()
262 mCreatureLocaleMap.clear(); // need for reload case
264 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");
266 if(!result)
268 barGoLink bar(1);
270 bar.step();
272 sLog.outString();
273 sLog.outString(">> Loaded 0 creature locale strings. DB table `locales_creature` is empty.");
274 return;
277 barGoLink bar(result->GetRowCount());
281 Field *fields = result->Fetch();
282 bar.step();
284 uint32 entry = fields[0].GetUInt32();
286 CreatureLocale& data = mCreatureLocaleMap[entry];
288 for(int i = 1; i < MAX_LOCALE; ++i)
290 std::string str = fields[1+2*(i-1)].GetCppString();
291 if(!str.empty())
293 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
294 if(idx >= 0)
296 if(data.Name.size() <= idx)
297 data.Name.resize(idx+1);
299 data.Name[idx] = str;
302 str = fields[1+2*(i-1)+1].GetCppString();
303 if(!str.empty())
305 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
306 if(idx >= 0)
308 if(data.SubName.size() <= idx)
309 data.SubName.resize(idx+1);
311 data.SubName[idx] = str;
315 } while (result->NextRow());
317 delete result;
319 sLog.outString();
320 sLog.outString( ">> Loaded %lu creature locale strings", (unsigned long)mCreatureLocaleMap.size() );
323 void ObjectMgr::LoadGossipMenuItemsLocales()
325 mGossipMenuItemsLocaleMap.clear(); // need for reload case
327 QueryResult *result = WorldDatabase.Query("SELECT menu_id,id,"
328 "option_text_loc1,box_text_loc1,option_text_loc2,box_text_loc2,"
329 "option_text_loc3,box_text_loc3,option_text_loc4,box_text_loc4,"
330 "option_text_loc5,box_text_loc5,option_text_loc6,box_text_loc6,"
331 "option_text_loc7,box_text_loc7,option_text_loc8,box_text_loc8 "
332 "FROM locales_gossip_menu_option");
334 if(!result)
336 barGoLink bar(1);
338 bar.step();
340 sLog.outString();
341 sLog.outString(">> Loaded 0 gossip_menu_option locale strings. DB table `locales_gossip_menu_option` is empty.");
342 return;
345 barGoLink bar(result->GetRowCount());
349 Field *fields = result->Fetch();
350 bar.step();
352 uint16 menuId = fields[0].GetUInt16();
353 uint16 id = fields[1].GetUInt16();
355 GossipMenuItemsLocale& data = mGossipMenuItemsLocaleMap[MAKE_PAIR32(menuId,id)];
357 for(int i = 1; i < MAX_LOCALE; ++i)
359 std::string str = fields[2+2*(i-1)].GetCppString();
360 if(!str.empty())
362 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
363 if(idx >= 0)
365 if(data.OptionText.size() <= idx)
366 data.OptionText.resize(idx+1);
368 data.OptionText[idx] = str;
371 str = fields[2+2*(i-1)+1].GetCppString();
372 if(!str.empty())
374 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
375 if(idx >= 0)
377 if(data.BoxText.size() <= idx)
378 data.BoxText.resize(idx+1);
380 data.BoxText[idx] = str;
384 } while (result->NextRow());
386 delete result;
388 sLog.outString();
389 sLog.outString( ">> Loaded %lu gossip_menu_option locale strings", (unsigned long)mGossipMenuItemsLocaleMap.size() );
392 void ObjectMgr::LoadPointOfInterestLocales()
394 mPointOfInterestLocaleMap.clear(); // need for reload case
396 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");
398 if(!result)
400 barGoLink bar(1);
402 bar.step();
404 sLog.outString();
405 sLog.outString(">> Loaded 0 points_of_interest locale strings. DB table `locales_points_of_interest` is empty.");
406 return;
409 barGoLink bar(result->GetRowCount());
413 Field *fields = result->Fetch();
414 bar.step();
416 uint32 entry = fields[0].GetUInt32();
418 PointOfInterestLocale& data = mPointOfInterestLocaleMap[entry];
420 for(int i = 1; i < MAX_LOCALE; ++i)
422 std::string str = fields[i].GetCppString();
423 if(str.empty())
424 continue;
426 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
427 if(idx >= 0)
429 if(data.IconName.size() <= idx)
430 data.IconName.resize(idx+1);
432 data.IconName[idx] = str;
435 } while (result->NextRow());
437 delete result;
439 sLog.outString();
440 sLog.outString( ">> Loaded %lu points_of_interest locale strings", (unsigned long)mPointOfInterestLocaleMap.size() );
443 struct SQLCreatureLoader : public SQLStorageLoaderBase<SQLCreatureLoader>
445 template<class D>
446 void convert_from_str(uint32 /*field_pos*/, char *src, D &dst)
448 dst = D(sObjectMgr.GetScriptId(src));
452 void ObjectMgr::LoadCreatureTemplates()
454 SQLCreatureLoader loader;
455 loader.Load(sCreatureStorage);
457 sLog.outString( ">> Loaded %u creature definitions", sCreatureStorage.RecordCount );
458 sLog.outString();
460 std::set<uint32> difficultyEntries[MAX_DIFFICULTY - 1]; // already loaded difficulty 1 value in creatures
461 std::set<uint32> hasDifficultyEntries[MAX_DIFFICULTY - 1]; // already loaded creatures with difficulty 1 values
463 // check data correctness
464 for(uint32 i = 1; i < sCreatureStorage.MaxEntry; ++i)
466 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i);
467 if (!cInfo)
468 continue;
470 bool ok = true; // bool to allow continue outside this loop
471 for (uint32 diff = 0; diff < MAX_DIFFICULTY - 1 && ok; ++diff)
473 if (!cInfo->DifficultyEntry[diff])
474 continue;
475 ok = false; // will be set to true at the end of this loop again
477 CreatureInfo const* difficultyInfo = GetCreatureTemplate(cInfo->DifficultyEntry[diff]);
478 if (!difficultyInfo)
480 sLog.outErrorDb("Creature (Entry: %u) have `difficulty_entry_%u`=%u but creature entry %u not exist.",
481 i, diff + 1, cInfo->DifficultyEntry[diff], cInfo->DifficultyEntry[diff]);
482 continue;
485 if (difficultyEntries[diff].find(i) != difficultyEntries[diff].end())
487 sLog.outErrorDb("Creature (Entry: %u) listed as difficulty %u but have value in `difficulty_entry_%u`.", i, diff + 1, diff + 1);
488 continue;
491 bool ok2 = true;
492 for (uint32 diff2 = 0; diff2 < MAX_DIFFICULTY - 1 && ok2; ++diff2)
494 ok2 = false;
495 if (difficultyEntries[diff2].find(cInfo->DifficultyEntry[diff]) != difficultyEntries[diff2].end())
497 sLog.outErrorDb("Creature (Entry: %u) already listed as difficulty %u for another entry.", cInfo->DifficultyEntry[diff], diff2 + 1);
498 continue;
501 if (hasDifficultyEntries[diff2].find(cInfo->DifficultyEntry[diff]) != hasDifficultyEntries[diff2].end())
503 sLog.outErrorDb("Creature (Entry: %u) have `difficulty_entry_%u`=%u but creature entry %u have difficulty %u entry also.",
504 i, diff + 1, cInfo->DifficultyEntry[diff], cInfo->DifficultyEntry[diff], diff2 + 1);
505 continue;
507 ok2 = true;
509 if (!ok2)
510 continue;
512 if (cInfo->unit_class != difficultyInfo->unit_class)
514 sLog.outErrorDb("Creature (Entry: %u, class %u) has different `unit_class` in difficulty %u mode (Entry: %u, class %u).",
515 i, cInfo->unit_class, diff + 1, cInfo->DifficultyEntry[diff], difficultyInfo->unit_class);
516 continue;
519 if (cInfo->npcflag != difficultyInfo->npcflag)
521 sLog.outErrorDb("Creature (Entry: %u) has different `npcflag` in difficulty %u mode (Entry: %u).", i, diff + 1, cInfo->DifficultyEntry[diff]);
522 continue;
525 if (cInfo->trainer_class != difficultyInfo->trainer_class)
527 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_class` in difficulty %u mode (Entry: %u).", i, diff + 1, cInfo->DifficultyEntry[diff]);
528 continue;
531 if (cInfo->trainer_race != difficultyInfo->trainer_race)
533 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_race` in difficulty %u mode (Entry: %u).", i, diff + 1, cInfo->DifficultyEntry[diff]);
534 continue;
537 if (cInfo->trainer_type != difficultyInfo->trainer_type)
539 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_type` in difficulty %u mode (Entry: %u).", i, diff + 1, cInfo->DifficultyEntry[diff]);
540 continue;
543 if (cInfo->trainer_spell != difficultyInfo->trainer_spell)
545 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_spell` in difficulty %u mode (Entry: %u).", i, diff + 1, cInfo->DifficultyEntry[diff]);
546 continue;
549 if (difficultyInfo->AIName && *difficultyInfo->AIName)
551 sLog.outErrorDb("Difficulty %u mode creature (Entry: %u) has `AIName`, but in any case will used difficulty 0 mode creature (Entry: %u) AIName.",
552 diff, cInfo->DifficultyEntry[diff], i);
553 continue;
556 if (difficultyInfo->ScriptID)
558 sLog.outErrorDb("Difficulty %u mode creature (Entry: %u) has `ScriptName`, but in any case will used difficulty 0 mode creature (Entry: %u) ScriptName.",
559 diff, cInfo->DifficultyEntry[diff], i);
560 continue;
563 hasDifficultyEntries[diff].insert(i);
564 difficultyEntries[diff].insert(cInfo->DifficultyEntry[diff]);
565 ok = true;
567 if (!ok)
568 continue;
570 FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction_A);
571 if (!factionTemplate)
572 sLog.outErrorDb("Creature (Entry: %u) has non-existing faction_A template (%u)", cInfo->Entry, cInfo->faction_A);
574 factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction_H);
575 if (!factionTemplate)
576 sLog.outErrorDb("Creature (Entry: %u) has non-existing faction_H template (%u)", cInfo->Entry, cInfo->faction_H);
578 // used later for scale
579 CreatureDisplayInfoEntry const* displayScaleEntry = NULL;
581 if (cInfo->DisplayID_A[0])
583 CreatureDisplayInfoEntry const* displayEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->DisplayID_A[0]);
584 if(!displayEntry)
586 sLog.outErrorDb("Creature (Entry: %u) has non-existing DisplayID_A id (%u), can crash client", cInfo->Entry, cInfo->DisplayID_A[0]);
587 const_cast<CreatureInfo*>(cInfo)->DisplayID_A[0] = 0;
589 else if(!displayScaleEntry)
590 displayScaleEntry = displayEntry;
592 CreatureModelInfo const* minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_A[0]);
593 if (!minfo)
594 sLog.outErrorDb("Creature (Entry: %u) not has model data for DisplayID_A (%u)", cInfo->Entry, cInfo->DisplayID_A[0]);
597 if (cInfo->DisplayID_A[1])
599 CreatureDisplayInfoEntry const* displayEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->DisplayID_A[1]);
600 if(!displayEntry)
602 sLog.outErrorDb("Creature (Entry: %u) has non-existing DisplayID_A2 id (%u), can crash client", cInfo->Entry, cInfo->DisplayID_A[1]);
603 const_cast<CreatureInfo*>(cInfo)->DisplayID_A[1] = 0;
605 else if(!displayScaleEntry)
606 displayScaleEntry = displayEntry;
608 CreatureModelInfo const* minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_A[1]);
609 if (!minfo)
610 sLog.outErrorDb("Creature (Entry: %u) not has model data for DisplayID_A2 (%u)", cInfo->Entry, cInfo->DisplayID_A[1]);
613 if (cInfo->DisplayID_H[0])
615 CreatureDisplayInfoEntry const* displayEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->DisplayID_H[0]);
616 if(!displayEntry)
618 sLog.outErrorDb("Creature (Entry: %u) has non-existing DisplayID_H id (%u), can crash client", cInfo->Entry, cInfo->DisplayID_H[0]);
619 const_cast<CreatureInfo*>(cInfo)->DisplayID_H[0] = 0;
621 else if(!displayScaleEntry)
622 displayScaleEntry = displayEntry;
624 CreatureModelInfo const* minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_H[0]);
625 if (!minfo)
626 sLog.outErrorDb("Creature (Entry: %u) not has model data for DisplayID_H (%u)", cInfo->Entry, cInfo->DisplayID_H[0]);
629 if (cInfo->DisplayID_H[1])
631 CreatureDisplayInfoEntry const* displayEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->DisplayID_H[1]);
632 if(!displayEntry)
634 sLog.outErrorDb("Creature (Entry: %u) has non-existing DisplayID_H2 id (%u), can crash client", cInfo->Entry, cInfo->DisplayID_H[1]);
635 const_cast<CreatureInfo*>(cInfo)->DisplayID_H[1] = 0;
637 else if(!displayScaleEntry)
638 displayScaleEntry = displayEntry;
640 CreatureModelInfo const* minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_H[1]);
641 if (!minfo)
642 sLog.outErrorDb("Creature (Entry: %u) not has model data for DisplayID_H2 (%u)", cInfo->Entry, cInfo->DisplayID_H[1]);
645 if (!displayScaleEntry)
646 sLog.outErrorDb("Creature (Entry: %u) not has any existed display id in DisplayID_A/DisplayID_A2/DisplayID_H/DisplayID_H2", cInfo->Entry);
648 for(int k = 0; k < MAX_KILL_CREDIT; ++k)
650 if(cInfo->KillCredit[k])
652 if(!GetCreatureTemplate(cInfo->KillCredit[k]))
654 sLog.outErrorDb("Creature (Entry: %u) has not existed creature entry in `KillCredit%d` (%u)",cInfo->Entry,k+1,cInfo->KillCredit[k]);
655 const_cast<CreatureInfo*>(cInfo)->KillCredit[k] = 0;
660 // use below code for 0-checks for unit_class
661 if (/*!cInfo->unit_class ||*/cInfo->unit_class && ((1 << (cInfo->unit_class-1)) & CLASSMASK_ALL_CREATURES) == 0)
662 sLog.outErrorDb("Creature (Entry: %u) has invalid unit_class(%u) for creature_template", cInfo->Entry, cInfo->unit_class);
664 if(cInfo->dmgschool >= MAX_SPELL_SCHOOL)
666 sLog.outErrorDb("Creature (Entry: %u) has invalid spell school value (%u) in `dmgschool`",cInfo->Entry,cInfo->dmgschool);
667 const_cast<CreatureInfo*>(cInfo)->dmgschool = SPELL_SCHOOL_NORMAL;
670 if(cInfo->baseattacktime == 0)
671 const_cast<CreatureInfo*>(cInfo)->baseattacktime = BASE_ATTACK_TIME;
673 if(cInfo->rangeattacktime == 0)
674 const_cast<CreatureInfo*>(cInfo)->rangeattacktime = BASE_ATTACK_TIME;
676 if(cInfo->npcflag & UNIT_NPC_FLAG_SPELLCLICK)
678 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);
679 const_cast<CreatureInfo*>(cInfo)->npcflag &= ~UNIT_NPC_FLAG_SPELLCLICK;
682 if((cInfo->npcflag & UNIT_NPC_FLAG_TRAINER) && cInfo->trainer_type >= MAX_TRAINER_TYPE)
683 sLog.outErrorDb("Creature (Entry: %u) has wrong trainer type %u",cInfo->Entry,cInfo->trainer_type);
685 if(cInfo->type && !sCreatureTypeStore.LookupEntry(cInfo->type))
687 sLog.outErrorDb("Creature (Entry: %u) has invalid creature type (%u) in `type`",cInfo->Entry,cInfo->type);
688 const_cast<CreatureInfo*>(cInfo)->type = CREATURE_TYPE_HUMANOID;
691 // must exist or used hidden but used in data horse case
692 if(cInfo->family && !sCreatureFamilyStore.LookupEntry(cInfo->family) && cInfo->family != CREATURE_FAMILY_HORSE_CUSTOM )
694 sLog.outErrorDb("Creature (Entry: %u) has invalid creature family (%u) in `family`",cInfo->Entry,cInfo->family);
695 const_cast<CreatureInfo*>(cInfo)->family = 0;
698 if(cInfo->InhabitType <= 0 || cInfo->InhabitType > INHABIT_ANYWHERE)
700 sLog.outErrorDb("Creature (Entry: %u) has wrong value (%u) in `InhabitType`, creature will not correctly walk/swim/fly",cInfo->Entry,cInfo->InhabitType);
701 const_cast<CreatureInfo*>(cInfo)->InhabitType = INHABIT_ANYWHERE;
704 if(cInfo->PetSpellDataId)
706 CreatureSpellDataEntry const* spellDataId = sCreatureSpellDataStore.LookupEntry(cInfo->PetSpellDataId);
707 if(!spellDataId)
708 sLog.outErrorDb("Creature (Entry: %u) has non-existing PetSpellDataId (%u)", cInfo->Entry, cInfo->PetSpellDataId);
711 for(int j = 0; j < CREATURE_MAX_SPELLS; ++j)
713 if(cInfo->spells[j] && !sSpellStore.LookupEntry(cInfo->spells[j]))
715 sLog.outErrorDb("Creature (Entry: %u) has non-existing Spell%d (%u), set to 0", cInfo->Entry, j+1,cInfo->spells[j]);
716 const_cast<CreatureInfo*>(cInfo)->spells[j] = 0;
720 if(cInfo->MovementType >= MAX_DB_MOTION_TYPE)
722 sLog.outErrorDb("Creature (Entry: %u) has wrong movement generator type (%u), ignore and set to IDLE.",cInfo->Entry,cInfo->MovementType);
723 const_cast<CreatureInfo*>(cInfo)->MovementType = IDLE_MOTION_TYPE;
726 if(cInfo->equipmentId > 0) // 0 no equipment
728 if(!GetEquipmentInfo(cInfo->equipmentId))
730 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);
731 const_cast<CreatureInfo*>(cInfo)->equipmentId = 0;
735 /// if not set custom creature scale then load scale from CreatureDisplayInfo.dbc
736 if(cInfo->scale <= 0.0f)
738 if(displayScaleEntry)
739 const_cast<CreatureInfo*>(cInfo)->scale = displayScaleEntry->scale;
740 else
741 const_cast<CreatureInfo*>(cInfo)->scale = 1.0f;
746 void ObjectMgr::ConvertCreatureAddonAuras(CreatureDataAddon* addon, char const* table, char const* guidEntryStr)
748 // Now add the auras, format "spellid effectindex spellid effectindex..."
749 char *p,*s;
750 std::vector<int> val;
751 s=p=(char*)reinterpret_cast<char const*>(addon->auras);
752 if(p)
754 while (p[0]!=0)
756 ++p;
757 if (p[0]==' ')
759 val.push_back(atoi(s));
760 s=++p;
763 if (p!=s)
764 val.push_back(atoi(s));
766 // free char* loaded memory
767 delete[] (char*)reinterpret_cast<char const*>(addon->auras);
769 // wrong list
770 if (val.size()%2)
772 addon->auras = NULL;
773 sLog.outErrorDb("Creature (%s: %u) has wrong `auras` data in `%s`.",guidEntryStr,addon->guidOrEntry,table);
774 return;
778 // empty list
779 if(val.empty())
781 addon->auras = NULL;
782 return;
785 // replace by new structures array
786 const_cast<CreatureDataAddonAura*&>(addon->auras) = new CreatureDataAddonAura[val.size()/2+1];
788 uint32 i=0;
789 for(uint32 j = 0; j < val.size()/2; ++j)
791 CreatureDataAddonAura& cAura = const_cast<CreatureDataAddonAura&>(addon->auras[i]);
792 cAura.spell_id = (uint32)val[2*j+0];
793 cAura.effect_idx = (uint32)val[2*j+1];
794 if ( cAura.effect_idx > 2 )
796 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);
797 continue;
799 SpellEntry const *AdditionalSpellInfo = sSpellStore.LookupEntry(cAura.spell_id);
800 if (!AdditionalSpellInfo)
802 sLog.outErrorDb("Creature (%s: %u) has wrong spell %u defined in `auras` field in `%s`.",guidEntryStr,addon->guidOrEntry,cAura.spell_id,table);
803 continue;
806 if (!AdditionalSpellInfo->Effect[cAura.effect_idx] || !AdditionalSpellInfo->EffectApplyAuraName[cAura.effect_idx])
808 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);
809 continue;
812 ++i;
815 // fill terminator element (after last added)
816 CreatureDataAddonAura& endAura = const_cast<CreatureDataAddonAura&>(addon->auras[i]);
817 endAura.spell_id = 0;
818 endAura.effect_idx = 0;
821 void ObjectMgr::LoadCreatureAddons(SQLStorage& creatureaddons, char const* entryName, char const* comment)
823 creatureaddons.Load();
825 sLog.outString(">> Loaded %u %s", creatureaddons.RecordCount, comment);
826 sLog.outString();
828 // check data correctness and convert 'auras'
829 for(uint32 i = 1; i < creatureaddons.MaxEntry; ++i)
831 CreatureDataAddon const* addon = creatureaddons.LookupEntry<CreatureDataAddon>(i);
832 if(!addon)
833 continue;
835 if (addon->mount)
837 if (!sCreatureDisplayInfoStore.LookupEntry(addon->mount))
839 sLog.outErrorDb("Creature (%s %u) have invalid displayInfoId for mount (%u) defined in `%s`.", entryName, addon->guidOrEntry, addon->mount, creatureaddons.GetTableName());
840 const_cast<CreatureDataAddon*>(addon)->mount = 0;
844 if (!sEmotesStore.LookupEntry(addon->emote))
845 sLog.outErrorDb("Creature (%s %u) have invalid emote (%u) defined in `%s`.", entryName, addon->guidOrEntry, addon->emote, creatureaddons.GetTableName());
847 if (addon->move_flags & (MONSTER_MOVE_UNK1|MONSTER_MOVE_UNK4))
849 sLog.outErrorDb("Creature (%s %u) movement flags mask defined in `%s` include forbidden flags (" I32FMT ") that can crash client, cleanup at load.", entryName, addon->guidOrEntry, creatureaddons.GetTableName(), (MONSTER_MOVE_UNK1|MONSTER_MOVE_UNK4));
850 const_cast<CreatureDataAddon*>(addon)->move_flags &= ~(MONSTER_MOVE_UNK1|MONSTER_MOVE_UNK4);
853 ConvertCreatureAddonAuras(const_cast<CreatureDataAddon*>(addon), creatureaddons.GetTableName(), entryName);
857 void ObjectMgr::LoadCreatureAddons()
859 LoadCreatureAddons(sCreatureInfoAddonStorage,"Entry","creature template addons");
861 // check entry ids
862 for(uint32 i = 1; i < sCreatureInfoAddonStorage.MaxEntry; ++i)
863 if(CreatureDataAddon const* addon = sCreatureInfoAddonStorage.LookupEntry<CreatureDataAddon>(i))
864 if(!sCreatureStorage.LookupEntry<CreatureInfo>(addon->guidOrEntry))
865 sLog.outErrorDb("Creature (Entry: %u) does not exist but has a record in `%s`",addon->guidOrEntry, sCreatureInfoAddonStorage.GetTableName());
867 LoadCreatureAddons(sCreatureDataAddonStorage,"GUID","creature addons");
869 // check entry ids
870 for(uint32 i = 1; i < sCreatureDataAddonStorage.MaxEntry; ++i)
871 if(CreatureDataAddon const* addon = sCreatureDataAddonStorage.LookupEntry<CreatureDataAddon>(i))
872 if(mCreatureDataMap.find(addon->guidOrEntry)==mCreatureDataMap.end())
873 sLog.outErrorDb("Creature (GUID: %u) does not exist but has a record in `creature_addon`",addon->guidOrEntry);
876 EquipmentInfo const* ObjectMgr::GetEquipmentInfo(uint32 entry)
878 return sEquipmentStorage.LookupEntry<EquipmentInfo>(entry);
881 void ObjectMgr::LoadEquipmentTemplates()
883 sEquipmentStorage.Load();
885 for(uint32 i=0; i< sEquipmentStorage.MaxEntry; ++i)
887 EquipmentInfo const* eqInfo = sEquipmentStorage.LookupEntry<EquipmentInfo>(i);
889 if(!eqInfo)
890 continue;
892 for(uint8 j=0; j<3; j++)
894 if(!eqInfo->equipentry[j])
895 continue;
897 ItemEntry const *dbcitem = sItemStore.LookupEntry(eqInfo->equipentry[j]);
899 if(!dbcitem)
901 sLog.outErrorDb("Unknown item (entry=%u) in creature_equip_template.equipentry%u for entry = %u, forced to 0.", eqInfo->equipentry[j], j+1, i);
902 const_cast<EquipmentInfo*>(eqInfo)->equipentry[j] = 0;
903 continue;
906 if(dbcitem->InventoryType != INVTYPE_WEAPON &&
907 dbcitem->InventoryType != INVTYPE_SHIELD &&
908 dbcitem->InventoryType != INVTYPE_RANGED &&
909 dbcitem->InventoryType != INVTYPE_2HWEAPON &&
910 dbcitem->InventoryType != INVTYPE_WEAPONMAINHAND &&
911 dbcitem->InventoryType != INVTYPE_WEAPONOFFHAND &&
912 dbcitem->InventoryType != INVTYPE_HOLDABLE &&
913 dbcitem->InventoryType != INVTYPE_THROWN &&
914 dbcitem->InventoryType != INVTYPE_RANGEDRIGHT)
916 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);
917 const_cast<EquipmentInfo*>(eqInfo)->equipentry[j] = 0;
921 sLog.outString( ">> Loaded %u equipment template", sEquipmentStorage.RecordCount );
922 sLog.outString();
925 CreatureModelInfo const* ObjectMgr::GetCreatureModelInfo(uint32 modelid)
927 return sCreatureModelStorage.LookupEntry<CreatureModelInfo>(modelid);
930 uint32 ObjectMgr::ChooseDisplayId(uint32 team, const CreatureInfo *cinfo, const CreatureData *data /*= NULL*/)
932 // Load creature model (display id)
933 if (data && data->displayid)
934 return data->displayid;
936 // use defaults from the template
937 uint32 display_id;
939 // DisplayID_A is used if no team is given
940 if (team == HORDE)
942 if(cinfo->DisplayID_H[0])
943 display_id = cinfo->DisplayID_H[1] ? cinfo->DisplayID_H[urand(0,1)] : cinfo->DisplayID_H[0];
944 else
945 display_id = cinfo->DisplayID_H[1];
947 if(!display_id)
948 display_id = cinfo->DisplayID_A[0] ? cinfo->DisplayID_A[0] : cinfo->DisplayID_A[1];
950 else
952 if(cinfo->DisplayID_A[0])
953 display_id = cinfo->DisplayID_A[1] ? cinfo->DisplayID_A[urand(0,1)] : cinfo->DisplayID_A[0];
954 else
955 display_id = cinfo->DisplayID_A[1];
957 if(!display_id)
958 display_id = cinfo->DisplayID_H[0] ? cinfo->DisplayID_H[0] : cinfo->DisplayID_H[1];
961 return display_id;
964 CreatureModelInfo const* ObjectMgr::GetCreatureModelRandomGender(uint32 display_id)
966 CreatureModelInfo const *minfo = GetCreatureModelInfo(display_id);
967 if(!minfo)
968 return NULL;
970 // If a model for another gender exists, 50% chance to use it
971 if(minfo->modelid_other_gender != 0 && urand(0,1) == 0)
973 CreatureModelInfo const *minfo_tmp = GetCreatureModelInfo(minfo->modelid_other_gender);
974 if(!minfo_tmp)
976 sLog.outErrorDb("Model (Entry: %u) has modelid_other_gender %u not found in table `creature_model_info`. ", minfo->modelid, minfo->modelid_other_gender);
977 return minfo; // not fatal, just use the previous one
979 else
980 return minfo_tmp;
982 else
983 return minfo;
986 void ObjectMgr::LoadCreatureModelInfo()
988 sCreatureModelStorage.Load();
990 // post processing
991 for(uint32 i = 1; i < sCreatureModelStorage.MaxEntry; ++i)
993 CreatureModelInfo const *minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(i);
994 if (!minfo)
995 continue;
997 if (!sCreatureDisplayInfoStore.LookupEntry(minfo->modelid))
998 sLog.outErrorDb("Table `creature_model_info` has model for not existed display id (%u).", minfo->modelid);
1000 if (minfo->gender > GENDER_NONE)
1002 sLog.outErrorDb("Table `creature_model_info` has wrong gender (%u) for display id (%u).", uint32(minfo->gender), minfo->modelid);
1003 const_cast<CreatureModelInfo*>(minfo)->gender = GENDER_MALE;
1006 if (minfo->modelid_other_gender && !sCreatureDisplayInfoStore.LookupEntry(minfo->modelid_other_gender))
1008 sLog.outErrorDb("Table `creature_model_info` has not existed alt.gender model (%u) for existed display id (%u).", minfo->modelid_other_gender, minfo->modelid);
1009 const_cast<CreatureModelInfo*>(minfo)->modelid_other_gender = 0;
1013 sLog.outString( ">> Loaded %u creature model based info", sCreatureModelStorage.RecordCount );
1014 sLog.outString();
1017 void ObjectMgr::LoadCreatures()
1019 uint32 count = 0;
1020 // 0 1 2 3
1021 QueryResult *result = WorldDatabase.Query("SELECT creature.guid, id, map, modelid,"
1022 // 4 5 6 7 8 9 10 11
1023 "equipment_id, position_x, position_y, position_z, orientation, spawntimesecs, spawndist, currentwaypoint,"
1024 // 12 13 14 15 16 17 18 19
1025 "curhealth, curmana, DeathState, MovementType, spawnMask, phaseMask, event, pool_entry "
1026 "FROM creature LEFT OUTER JOIN game_event_creature ON creature.guid = game_event_creature.guid "
1027 "LEFT OUTER JOIN pool_creature ON creature.guid = pool_creature.guid");
1029 if(!result)
1031 barGoLink bar(1);
1033 bar.step();
1035 sLog.outString();
1036 sLog.outErrorDb(">> Loaded 0 creature. DB table `creature` is empty.");
1037 return;
1040 // build single time for check creature data
1041 std::set<uint32> difficultyCreatures[MAX_DIFFICULTY - 1];
1042 for (uint32 i = 0; i < sCreatureStorage.MaxEntry; ++i)
1043 if (CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i))
1044 for (uint32 diff = 0; diff < MAX_DIFFICULTY - 1; ++diff)
1045 if (cInfo->DifficultyEntry[diff])
1046 difficultyCreatures[diff].insert(cInfo->DifficultyEntry[diff]);
1048 // build single time for check spawnmask
1049 std::map<uint32,uint32> spawnMasks;
1050 for(uint32 i = 0; i < sMapStore.GetNumRows(); ++i)
1051 if(sMapStore.LookupEntry(i))
1052 for(int k = 0; k < MAX_DIFFICULTY; ++k)
1053 if (GetMapDifficultyData(i,Difficulty(k)))
1054 spawnMasks[i] |= (1 << k);
1056 barGoLink bar(result->GetRowCount());
1060 Field *fields = result->Fetch();
1061 bar.step();
1063 uint32 guid = fields[ 0].GetUInt32();
1064 uint32 entry = fields[ 1].GetUInt32();
1066 CreatureInfo const* cInfo = GetCreatureTemplate(entry);
1067 if(!cInfo)
1069 sLog.outErrorDb("Table `creature` has creature (GUID: %u) with non existing creature entry %u, skipped.", guid, entry);
1070 continue;
1073 CreatureData& data = mCreatureDataMap[guid];
1075 data.id = entry;
1076 data.mapid = fields[ 2].GetUInt32();
1077 data.displayid = fields[ 3].GetUInt32();
1078 data.equipmentId = fields[ 4].GetUInt32();
1079 data.posX = fields[ 5].GetFloat();
1080 data.posY = fields[ 6].GetFloat();
1081 data.posZ = fields[ 7].GetFloat();
1082 data.orientation = fields[ 8].GetFloat();
1083 data.spawntimesecs = fields[ 9].GetUInt32();
1084 data.spawndist = fields[10].GetFloat();
1085 data.currentwaypoint= fields[11].GetUInt32();
1086 data.curhealth = fields[12].GetUInt32();
1087 data.curmana = fields[13].GetUInt32();
1088 data.is_dead = fields[14].GetBool();
1089 data.movementType = fields[15].GetUInt8();
1090 data.spawnMask = fields[16].GetUInt8();
1091 data.phaseMask = fields[17].GetUInt16();
1092 int16 gameEvent = fields[18].GetInt16();
1093 int16 PoolId = fields[19].GetInt16();
1095 MapEntry const* mapEntry = sMapStore.LookupEntry(data.mapid);
1096 if(!mapEntry)
1098 sLog.outErrorDb("Table `creature` have creature (GUID: %u) that spawned at not existed map (Id: %u), skipped.",guid, data.mapid );
1099 continue;
1102 if (data.spawnMask & ~spawnMasks[data.mapid])
1103 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 );
1105 bool ok = true;
1106 for (uint32 diff = 0; diff < MAX_DIFFICULTY - 1 && ok; ++diff)
1108 if (difficultyCreatures[diff].find(data.id) != difficultyCreatures[diff].end())
1110 sLog.outErrorDb("Table `creature` have creature (GUID: %u) that listed as difficulty %u template (entry: %u) in `creature_template`, skipped.",
1111 guid, diff + 1, data.id );
1112 ok = false;
1115 if (!ok)
1116 continue;
1118 if(data.equipmentId > 0) // -1 no equipment, 0 use default
1120 if(!GetEquipmentInfo(data.equipmentId))
1122 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);
1123 data.equipmentId = -1;
1127 if(cInfo->RegenHealth && data.curhealth < cInfo->minhealth)
1129 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 );
1130 data.curhealth = cInfo->minhealth;
1133 if(cInfo->flags_extra & CREATURE_FLAG_EXTRA_INSTANCE_BIND)
1135 if(!mapEntry || !mapEntry->IsDungeon())
1136 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);
1139 if(data.curmana < cInfo->minmana)
1141 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 );
1142 data.curmana = cInfo->minmana;
1145 if(data.spawndist < 0.0f)
1147 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `spawndist`< 0, set to 0.",guid,data.id );
1148 data.spawndist = 0.0f;
1150 else if(data.movementType == RANDOM_MOTION_TYPE)
1152 if(data.spawndist == 0.0f)
1154 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 );
1155 data.movementType = IDLE_MOTION_TYPE;
1158 else if(data.movementType == IDLE_MOTION_TYPE)
1160 if(data.spawndist != 0.0f)
1162 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `MovementType`=0 (idle) have `spawndist`<>0, set to 0.",guid,data.id );
1163 data.spawndist = 0.0f;
1167 if(data.phaseMask==0)
1169 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `phaseMask`=0 (not visible for anyone), set to 1.",guid,data.id );
1170 data.phaseMask = 1;
1173 if (gameEvent==0 && PoolId==0) // if not this is to be managed by GameEvent System or Pool system
1174 AddCreatureToGrid(guid, &data);
1176 ++count;
1178 } while (result->NextRow());
1180 delete result;
1182 sLog.outString();
1183 sLog.outString( ">> Loaded %lu creatures", (unsigned long)mCreatureDataMap.size() );
1186 void ObjectMgr::AddCreatureToGrid(uint32 guid, CreatureData const* data)
1188 uint8 mask = data->spawnMask;
1189 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1191 if(mask & 1)
1193 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1194 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1196 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1197 cell_guids.creatures.insert(guid);
1202 void ObjectMgr::RemoveCreatureFromGrid(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.erase(guid);
1218 void ObjectMgr::LoadGameobjects()
1220 uint32 count = 0;
1222 // 0 1 2 3 4 5 6
1223 QueryResult *result = WorldDatabase.Query("SELECT gameobject.guid, id, map, position_x, position_y, position_z, orientation,"
1224 // 7 8 9 10 11 12 13 14 15 16 17
1225 "rotation0, rotation1, rotation2, rotation3, spawntimesecs, animprogress, state, spawnMask, phaseMask, event, pool_entry "
1226 "FROM gameobject LEFT OUTER JOIN game_event_gameobject ON gameobject.guid = game_event_gameobject.guid "
1227 "LEFT OUTER JOIN pool_gameobject ON gameobject.guid = pool_gameobject.guid");
1229 if(!result)
1231 barGoLink bar(1);
1233 bar.step();
1235 sLog.outString();
1236 sLog.outErrorDb(">> Loaded 0 gameobjects. DB table `gameobject` is empty.");
1237 return;
1240 // build single time for check spawnmask
1241 std::map<uint32,uint32> spawnMasks;
1242 for(uint32 i = 0; i < sMapStore.GetNumRows(); ++i)
1243 if(sMapStore.LookupEntry(i))
1244 for(int k = 0; k < MAX_DIFFICULTY; ++k)
1245 if (GetMapDifficultyData(i,Difficulty(k)))
1246 spawnMasks[i] |= (1 << k);
1248 barGoLink bar(result->GetRowCount());
1252 Field *fields = result->Fetch();
1253 bar.step();
1255 uint32 guid = fields[ 0].GetUInt32();
1256 uint32 entry = fields[ 1].GetUInt32();
1258 GameObjectInfo const* gInfo = GetGameObjectInfo(entry);
1259 if (!gInfo)
1261 sLog.outErrorDb("Table `gameobject` has gameobject (GUID: %u) with non existing gameobject entry %u, skipped.", guid, entry);
1262 continue;
1265 if(!gInfo->displayId)
1267 switch(gInfo->type)
1269 // can be invisible always and then not req. display id in like case
1270 case GAMEOBJECT_TYPE_TRAP:
1271 case GAMEOBJECT_TYPE_SPELL_FOCUS:
1272 break;
1273 default:
1274 sLog.outErrorDb("Gameobject (GUID: %u Entry %u GoType: %u) have displayId == 0 and then will always invisible in game.", guid, entry, gInfo->type);
1275 break;
1278 else if (!sGameObjectDisplayInfoStore.LookupEntry(gInfo->displayId))
1280 sLog.outErrorDb("Gameobject (GUID: %u Entry %u GoType: %u) have invalid displayId (%u), not loaded.", guid, entry, gInfo->type, gInfo->displayId);
1281 continue;
1284 GameObjectData& data = mGameObjectDataMap[guid];
1286 data.id = entry;
1287 data.mapid = fields[ 2].GetUInt32();
1288 data.posX = fields[ 3].GetFloat();
1289 data.posY = fields[ 4].GetFloat();
1290 data.posZ = fields[ 5].GetFloat();
1291 data.orientation = fields[ 6].GetFloat();
1292 data.rotation0 = fields[ 7].GetFloat();
1293 data.rotation1 = fields[ 8].GetFloat();
1294 data.rotation2 = fields[ 9].GetFloat();
1295 data.rotation3 = fields[10].GetFloat();
1296 data.spawntimesecs = fields[11].GetInt32();
1298 MapEntry const* mapEntry = sMapStore.LookupEntry(data.mapid);
1299 if(!mapEntry)
1301 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) that spawned at not existed map (Id: %u), skip", guid, data.id, data.mapid);
1302 continue;
1305 if (data.spawnMask & ~spawnMasks[data.mapid])
1306 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);
1308 if (data.spawntimesecs == 0 && gInfo->IsDespawnAtAction())
1310 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with `spawntimesecs` (0) value, but gameobejct marked as despawnable at action.", guid, data.id);
1313 data.animprogress = fields[12].GetUInt32();
1315 uint32 go_state = fields[13].GetUInt32();
1316 if (go_state >= MAX_GO_STATE)
1318 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with invalid `state` (%u) value, skip", guid, data.id, go_state);
1319 continue;
1321 data.go_state = GOState(go_state);
1323 data.spawnMask = fields[14].GetUInt8();
1324 data.phaseMask = fields[15].GetUInt16();
1325 int16 gameEvent = fields[16].GetInt16();
1326 int16 PoolId = fields[17].GetInt16();
1328 if (data.rotation2 < -1.0f || data.rotation2 > 1.0f)
1330 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with invalid rotation2 (%f) value, skip", guid, data.id, data.rotation2);
1331 continue;
1334 if (data.rotation3 < -1.0f || data.rotation3 > 1.0f)
1336 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with invalid rotation3 (%f) value, skip", guid, data.id, data.rotation3);
1337 continue;
1340 if(!MapManager::IsValidMapCoord(data.mapid, data.posX, data.posY, data.posZ, data.orientation))
1342 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with invalid coordinates, skip", guid, data.id);
1343 continue;
1346 if(data.phaseMask == 0)
1348 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with `phaseMask`=0 (not visible for anyone), set to 1.", guid, data.id);
1349 data.phaseMask = 1;
1352 if (gameEvent == 0 && PoolId == 0) // if not this is to be managed by GameEvent System or Pool system
1353 AddGameobjectToGrid(guid, &data);
1354 ++count;
1356 } while (result->NextRow());
1358 delete result;
1360 sLog.outString();
1361 sLog.outString( ">> Loaded %lu gameobjects", (unsigned long)mGameObjectDataMap.size());
1364 void ObjectMgr::AddGameobjectToGrid(uint32 guid, GameObjectData const* data)
1366 uint8 mask = data->spawnMask;
1367 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1369 if(mask & 1)
1371 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1372 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1374 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1375 cell_guids.gameobjects.insert(guid);
1380 void ObjectMgr::RemoveGameobjectFromGrid(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.erase(guid);
1396 void ObjectMgr::LoadCreatureRespawnTimes()
1398 // remove outdated data
1399 WorldDatabase.DirectExecute("DELETE FROM creature_respawn WHERE respawntime <= UNIX_TIMESTAMP(NOW())");
1401 uint32 count = 0;
1403 QueryResult *result = WorldDatabase.Query("SELECT guid,respawntime,instance FROM creature_respawn");
1405 if(!result)
1407 barGoLink bar(1);
1409 bar.step();
1411 sLog.outString();
1412 sLog.outString(">> Loaded 0 creature respawn time.");
1413 return;
1416 barGoLink bar(result->GetRowCount());
1420 Field *fields = result->Fetch();
1421 bar.step();
1423 uint32 loguid = fields[0].GetUInt32();
1424 uint64 respawn_time = fields[1].GetUInt64();
1425 uint32 instance = fields[2].GetUInt32();
1427 mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = time_t(respawn_time);
1429 ++count;
1430 } while (result->NextRow());
1432 delete result;
1434 sLog.outString( ">> Loaded %lu creature respawn times", (unsigned long)mCreatureRespawnTimes.size() );
1435 sLog.outString();
1438 void ObjectMgr::LoadGameobjectRespawnTimes()
1440 // remove outdated data
1441 WorldDatabase.DirectExecute("DELETE FROM gameobject_respawn WHERE respawntime <= UNIX_TIMESTAMP(NOW())");
1443 uint32 count = 0;
1445 QueryResult *result = WorldDatabase.Query("SELECT guid,respawntime,instance FROM gameobject_respawn");
1447 if(!result)
1449 barGoLink bar(1);
1451 bar.step();
1453 sLog.outString();
1454 sLog.outString(">> Loaded 0 gameobject respawn time.");
1455 return;
1458 barGoLink bar(result->GetRowCount());
1462 Field *fields = result->Fetch();
1463 bar.step();
1465 uint32 loguid = fields[0].GetUInt32();
1466 uint64 respawn_time = fields[1].GetUInt64();
1467 uint32 instance = fields[2].GetUInt32();
1469 mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = time_t(respawn_time);
1471 ++count;
1472 } while (result->NextRow());
1474 delete result;
1476 sLog.outString( ">> Loaded %lu gameobject respawn times", (unsigned long)mGORespawnTimes.size() );
1477 sLog.outString();
1480 // name must be checked to correctness (if received) before call this function
1481 uint64 ObjectMgr::GetPlayerGUIDByName(std::string name) const
1483 uint64 guid = 0;
1485 CharacterDatabase.escape_string(name);
1487 // Player name safe to sending to DB (checked at login) and this function using
1488 QueryResult *result = CharacterDatabase.PQuery("SELECT guid FROM characters WHERE name = '%s'", name.c_str());
1489 if(result)
1491 guid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
1493 delete result;
1496 return guid;
1499 bool ObjectMgr::GetPlayerNameByGUID(const uint64 &guid, std::string &name) const
1501 // prevent DB access for online player
1502 if(Player* player = GetPlayer(guid))
1504 name = player->GetName();
1505 return true;
1508 QueryResult *result = CharacterDatabase.PQuery("SELECT name FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1510 if(result)
1512 name = (*result)[0].GetCppString();
1513 delete result;
1514 return true;
1517 return false;
1520 uint32 ObjectMgr::GetPlayerTeamByGUID(const uint64 &guid) const
1522 // prevent DB access for online player
1523 if(Player* player = GetPlayer(guid))
1525 return Player::TeamForRace(player->getRace());
1528 QueryResult *result = CharacterDatabase.PQuery("SELECT race FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1530 if(result)
1532 uint8 race = (*result)[0].GetUInt8();
1533 delete result;
1534 return Player::TeamForRace(race);
1537 return 0;
1540 uint32 ObjectMgr::GetPlayerAccountIdByGUID(const uint64 &guid) const
1542 // prevent DB access for online player
1543 if(Player* player = GetPlayer(guid))
1545 return player->GetSession()->GetAccountId();
1548 QueryResult *result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1549 if(result)
1551 uint32 acc = (*result)[0].GetUInt32();
1552 delete result;
1553 return acc;
1556 return 0;
1559 uint32 ObjectMgr::GetPlayerAccountIdByPlayerName(const std::string& name) const
1561 QueryResult *result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'", name.c_str());
1562 if(result)
1564 uint32 acc = (*result)[0].GetUInt32();
1565 delete result;
1566 return acc;
1569 return 0;
1572 void ObjectMgr::LoadItemLocales()
1574 mItemLocaleMap.clear(); // need for reload case
1576 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");
1578 if(!result)
1580 barGoLink bar(1);
1582 bar.step();
1584 sLog.outString();
1585 sLog.outString(">> Loaded 0 Item locale strings. DB table `locales_item` is empty.");
1586 return;
1589 barGoLink bar(result->GetRowCount());
1593 Field *fields = result->Fetch();
1594 bar.step();
1596 uint32 entry = fields[0].GetUInt32();
1598 ItemLocale& data = mItemLocaleMap[entry];
1600 for(int i = 1; i < MAX_LOCALE; ++i)
1602 std::string str = fields[1+2*(i-1)].GetCppString();
1603 if(!str.empty())
1605 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
1606 if(idx >= 0)
1608 if(data.Name.size() <= idx)
1609 data.Name.resize(idx+1);
1611 data.Name[idx] = str;
1615 str = fields[1+2*(i-1)+1].GetCppString();
1616 if(!str.empty())
1618 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
1619 if(idx >= 0)
1621 if(data.Description.size() <= idx)
1622 data.Description.resize(idx+1);
1624 data.Description[idx] = str;
1628 } while (result->NextRow());
1630 delete result;
1632 sLog.outString();
1633 sLog.outString( ">> Loaded %lu Item locale strings", (unsigned long)mItemLocaleMap.size() );
1636 struct SQLItemLoader : public SQLStorageLoaderBase<SQLItemLoader>
1638 template<class D>
1639 void convert_from_str(uint32 /*field_pos*/, char *src, D &dst)
1641 dst = D(sObjectMgr.GetScriptId(src));
1645 void ObjectMgr::LoadItemPrototypes()
1647 SQLItemLoader loader;
1648 loader.Load(sItemStorage);
1649 sLog.outString( ">> Loaded %u item prototypes", sItemStorage.RecordCount );
1650 sLog.outString();
1652 // check data correctness
1653 for(uint32 i = 1; i < sItemStorage.MaxEntry; ++i)
1655 ItemPrototype const* proto = sItemStorage.LookupEntry<ItemPrototype >(i);
1656 ItemEntry const *dbcitem = sItemStore.LookupEntry(i);
1657 if(!proto)
1659 /* to many errors, and possible not all items really used in game
1660 if (dbcitem)
1661 sLog.outErrorDb("Item (Entry: %u) doesn't exists in DB, but must exist.",i);
1663 continue;
1666 if(dbcitem)
1668 if(proto->Class != dbcitem->Class)
1670 sLog.outErrorDb("Item (Entry: %u) not correct class %u, must be %u (still using DB value).",i,proto->Class,dbcitem->Class);
1671 // It safe let use Class from DB
1673 /* disabled: have some strange wrong cases for Subclass values.
1674 for enable also uncomment Subclass field in ItemEntry structure and in Itemfmt[]
1675 if(proto->SubClass != dbcitem->SubClass)
1677 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);
1678 // It safe let use Subclass from DB
1682 if(proto->Unk0 != dbcitem->Unk0)
1684 sLog.outErrorDb("Item (Entry: %u) not correct %i Unk0, must be %i (still using DB value).",i,proto->Unk0,dbcitem->Unk0);
1685 // It safe let use Unk0 from DB
1688 if(proto->Material != dbcitem->Material)
1690 sLog.outErrorDb("Item (Entry: %u) not correct %i material, must be %i (still using DB value).",i,proto->Material,dbcitem->Material);
1691 // It safe let use Material from DB
1694 if(proto->InventoryType != dbcitem->InventoryType)
1696 sLog.outErrorDb("Item (Entry: %u) not correct %u inventory type, must be %u (still using DB value).",i,proto->InventoryType,dbcitem->InventoryType);
1697 // It safe let use InventoryType from DB
1700 if(proto->DisplayInfoID != dbcitem->DisplayId)
1702 sLog.outErrorDb("Item (Entry: %u) not correct %u display id, must be %u (using it).",i,proto->DisplayInfoID,dbcitem->DisplayId);
1703 const_cast<ItemPrototype*>(proto)->DisplayInfoID = dbcitem->DisplayId;
1705 if(proto->Sheath != dbcitem->Sheath)
1707 sLog.outErrorDb("Item (Entry: %u) not correct %u sheath, must be %u (using it).",i,proto->Sheath,dbcitem->Sheath);
1708 const_cast<ItemPrototype*>(proto)->Sheath = dbcitem->Sheath;
1711 else
1713 sLog.outErrorDb("Item (Entry: %u) not correct (not listed in list of existed items).",i);
1716 if(proto->Class >= MAX_ITEM_CLASS)
1718 sLog.outErrorDb("Item (Entry: %u) has wrong Class value (%u)",i,proto->Class);
1719 const_cast<ItemPrototype*>(proto)->Class = ITEM_CLASS_MISC;
1722 if(proto->SubClass >= MaxItemSubclassValues[proto->Class])
1724 sLog.outErrorDb("Item (Entry: %u) has wrong Subclass value (%u) for class %u",i,proto->SubClass,proto->Class);
1725 const_cast<ItemPrototype*>(proto)->SubClass = 0;// exist for all item classes
1728 if(proto->Quality >= MAX_ITEM_QUALITY)
1730 sLog.outErrorDb("Item (Entry: %u) has wrong Quality value (%u)",i,proto->Quality);
1731 const_cast<ItemPrototype*>(proto)->Quality = ITEM_QUALITY_NORMAL;
1734 if(proto->BuyCount <= 0)
1736 sLog.outErrorDb("Item (Entry: %u) has wrong BuyCount value (%u), set to default(1).",i,proto->BuyCount);
1737 const_cast<ItemPrototype*>(proto)->BuyCount = 1;
1740 if(proto->InventoryType >= MAX_INVTYPE)
1742 sLog.outErrorDb("Item (Entry: %u) has wrong InventoryType value (%u)",i,proto->InventoryType);
1743 const_cast<ItemPrototype*>(proto)->InventoryType = INVTYPE_NON_EQUIP;
1746 if(proto->RequiredSkill >= MAX_SKILL_TYPE)
1748 sLog.outErrorDb("Item (Entry: %u) has wrong RequiredSkill value (%u)",i,proto->RequiredSkill);
1749 const_cast<ItemPrototype*>(proto)->RequiredSkill = 0;
1753 // can be used in equip slot, as page read use in inventory, or spell casting at use
1754 bool req = proto->InventoryType!=INVTYPE_NON_EQUIP || proto->PageText;
1755 if(!req)
1757 for (int j = 0; j < MAX_ITEM_PROTO_SPELLS; ++j)
1759 if(proto->Spells[j].SpellId)
1761 req = true;
1762 break;
1767 if(req)
1769 if(!(proto->AllowableClass & CLASSMASK_ALL_PLAYABLE))
1770 sLog.outErrorDb("Item (Entry: %u) not have in `AllowableClass` any playable classes (%u) and can't be equipped or use.",i,proto->AllowableClass);
1772 if(!(proto->AllowableRace & RACEMASK_ALL_PLAYABLE))
1773 sLog.outErrorDb("Item (Entry: %u) not have in `AllowableRace` any playable races (%u) and can't be equipped or use.",i,proto->AllowableRace);
1777 if(proto->RequiredSpell && !sSpellStore.LookupEntry(proto->RequiredSpell))
1779 sLog.outErrorDb("Item (Entry: %u) have wrong (non-existed) spell in RequiredSpell (%u)",i,proto->RequiredSpell);
1780 const_cast<ItemPrototype*>(proto)->RequiredSpell = 0;
1783 if(proto->RequiredReputationRank >= MAX_REPUTATION_RANK)
1784 sLog.outErrorDb("Item (Entry: %u) has wrong reputation rank in RequiredReputationRank (%u), item can't be used.",i,proto->RequiredReputationRank);
1786 if(proto->RequiredReputationFaction)
1788 if(!sFactionStore.LookupEntry(proto->RequiredReputationFaction))
1790 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) faction in RequiredReputationFaction (%u)",i,proto->RequiredReputationFaction);
1791 const_cast<ItemPrototype*>(proto)->RequiredReputationFaction = 0;
1794 if(proto->RequiredReputationRank == MIN_REPUTATION_RANK)
1795 sLog.outErrorDb("Item (Entry: %u) has min. reputation rank in RequiredReputationRank (0) but RequiredReputationFaction > 0, faction setting is useless.",i);
1797 else if(proto->RequiredReputationRank > MIN_REPUTATION_RANK)
1798 sLog.outErrorDb("Item (Entry: %u) has RequiredReputationFaction ==0 but RequiredReputationRank > 0, rank setting is useless.",i);
1800 if(proto->MaxCount < -1)
1802 sLog.outErrorDb("Item (Entry: %u) has too large negative in maxcount (%i), replace by value (-1) no storing limits.",i,proto->MaxCount);
1803 const_cast<ItemPrototype*>(proto)->MaxCount = -1;
1806 if(proto->Stackable == 0)
1808 sLog.outErrorDb("Item (Entry: %u) has wrong value in stackable (%i), replace by default 1.",i,proto->Stackable);
1809 const_cast<ItemPrototype*>(proto)->Stackable = 1;
1811 else if(proto->Stackable < -1)
1813 sLog.outErrorDb("Item (Entry: %u) has too large negative in stackable (%i), replace by value (-1) no stacking limits.",i,proto->Stackable);
1814 const_cast<ItemPrototype*>(proto)->Stackable = -1;
1816 else if(proto->Stackable > 1000)
1818 sLog.outErrorDb("Item (Entry: %u) has too large value in stackable (%u), replace by hardcoded upper limit (1000).",i,proto->Stackable);
1819 const_cast<ItemPrototype*>(proto)->Stackable = 1000;
1822 if(proto->ContainerSlots > MAX_BAG_SIZE)
1824 sLog.outErrorDb("Item (Entry: %u) has too large value in ContainerSlots (%u), replace by hardcoded limit (%u).",i,proto->ContainerSlots,MAX_BAG_SIZE);
1825 const_cast<ItemPrototype*>(proto)->ContainerSlots = MAX_BAG_SIZE;
1828 if(proto->StatsCount > MAX_ITEM_PROTO_STATS)
1830 sLog.outErrorDb("Item (Entry: %u) has too large value in statscount (%u), replace by hardcoded limit (%u).",i,proto->StatsCount,MAX_ITEM_PROTO_STATS);
1831 const_cast<ItemPrototype*>(proto)->StatsCount = MAX_ITEM_PROTO_STATS;
1834 for (int j = 0; j < MAX_ITEM_PROTO_STATS; ++j)
1836 // for ItemStatValue != 0
1837 if(proto->ItemStat[j].ItemStatValue && proto->ItemStat[j].ItemStatType >= MAX_ITEM_MOD)
1839 sLog.outErrorDb("Item (Entry: %u) has wrong stat_type%d (%u)",i,j+1,proto->ItemStat[j].ItemStatType);
1840 const_cast<ItemPrototype*>(proto)->ItemStat[j].ItemStatType = 0;
1843 switch(proto->ItemStat[j].ItemStatType)
1845 case ITEM_MOD_SPELL_HEALING_DONE:
1846 case ITEM_MOD_SPELL_DAMAGE_DONE:
1847 sLog.outErrorDb("Item (Entry: %u) has deprecated stat_type%d (%u)",i,j+1,proto->ItemStat[j].ItemStatType);
1848 break;
1849 default:
1850 break;
1854 for (int j = 0; j < MAX_ITEM_PROTO_DAMAGES; ++j)
1856 if(proto->Damage[j].DamageType >= MAX_SPELL_SCHOOL)
1858 sLog.outErrorDb("Item (Entry: %u) has wrong dmg_type%d (%u)",i,j+1,proto->Damage[j].DamageType);
1859 const_cast<ItemPrototype*>(proto)->Damage[j].DamageType = 0;
1863 // special format
1864 if((proto->Spells[0].SpellId == SPELL_ID_GENERIC_LEARN) || (proto->Spells[0].SpellId == SPELL_ID_GENERIC_LEARN_PET))
1866 // spell_1
1867 if(proto->Spells[0].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
1869 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);
1870 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1871 const_cast<ItemPrototype*>(proto)->Spells[0].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1872 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1873 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1876 // spell_2 have learning spell
1877 if(proto->Spells[1].SpellTrigger != ITEM_SPELLTRIGGER_LEARN_SPELL_ID)
1879 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);
1880 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1881 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1882 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1884 else if(!proto->Spells[1].SpellId)
1886 sLog.outErrorDb("Item (Entry: %u) not has expected spell in spellid_%d in special learning format.",i,1+1);
1887 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1888 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1890 else
1892 SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[1].SpellId);
1893 if(!spellInfo)
1895 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%u)",i,1+1,proto->Spells[1].SpellId);
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 // allowed only in special format
1901 else if((proto->Spells[1].SpellId==SPELL_ID_GENERIC_LEARN) || (proto->Spells[1].SpellId==SPELL_ID_GENERIC_LEARN_PET))
1903 sLog.outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%u)",i,1+1,proto->Spells[1].SpellId);
1904 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1905 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1906 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1910 // spell_3*,spell_4*,spell_5* is empty
1911 for (int j = 2; j < MAX_ITEM_PROTO_SPELLS; ++j)
1913 if(proto->Spells[j].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
1915 sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)",i,j+1,proto->Spells[j].SpellTrigger);
1916 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1917 const_cast<ItemPrototype*>(proto)->Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1919 else if(proto->Spells[j].SpellId != 0)
1921 sLog.outErrorDb("Item (Entry: %u) has wrong spell in spellid_%d (%u) for learning special format",i,j+1,proto->Spells[j].SpellId);
1922 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1926 // normal spell list
1927 else
1929 for (int j = 0; j < MAX_ITEM_PROTO_SPELLS; ++j)
1931 if (proto->Spells[j].SpellTrigger >= MAX_ITEM_SPELLTRIGGER || proto->Spells[j].SpellTrigger == ITEM_SPELLTRIGGER_LEARN_SPELL_ID)
1933 sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)",i,j+1,proto->Spells[j].SpellTrigger);
1934 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1935 const_cast<ItemPrototype*>(proto)->Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1937 // on hit can be sued only at weapon
1938 else if (proto->Spells[j].SpellTrigger == ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
1940 if(proto->Class != ITEM_CLASS_WEAPON)
1941 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);
1944 if(proto->Spells[j].SpellId)
1946 SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[j].SpellId);
1947 if(!spellInfo)
1949 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%u)",i,j+1,proto->Spells[j].SpellId);
1950 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1952 // allowed only in special format
1953 else if((proto->Spells[j].SpellId==SPELL_ID_GENERIC_LEARN) || (proto->Spells[j].SpellId==SPELL_ID_GENERIC_LEARN_PET))
1955 sLog.outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%u)",i,j+1,proto->Spells[j].SpellId);
1956 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1962 if(proto->Bonding >= MAX_BIND_TYPE)
1963 sLog.outErrorDb("Item (Entry: %u) has wrong Bonding value (%u)",i,proto->Bonding);
1965 if(proto->PageText && !sPageTextStore.LookupEntry<PageText>(proto->PageText))
1966 sLog.outErrorDb("Item (Entry: %u) has non existing first page (Id:%u)", i,proto->PageText);
1968 if(proto->LockID && !sLockStore.LookupEntry(proto->LockID))
1969 sLog.outErrorDb("Item (Entry: %u) has wrong LockID (%u)",i,proto->LockID);
1971 if(proto->Sheath >= MAX_SHEATHETYPE)
1973 sLog.outErrorDb("Item (Entry: %u) has wrong Sheath (%u)",i,proto->Sheath);
1974 const_cast<ItemPrototype*>(proto)->Sheath = SHEATHETYPE_NONE;
1977 if(proto->RandomProperty && !sItemRandomPropertiesStore.LookupEntry(GetItemEnchantMod(proto->RandomProperty)))
1979 sLog.outErrorDb("Item (Entry: %u) has unknown (wrong or not listed in `item_enchantment_template`) RandomProperty (%u)",i,proto->RandomProperty);
1980 const_cast<ItemPrototype*>(proto)->RandomProperty = 0;
1983 if(proto->RandomSuffix && !sItemRandomSuffixStore.LookupEntry(GetItemEnchantMod(proto->RandomSuffix)))
1985 sLog.outErrorDb("Item (Entry: %u) has wrong RandomSuffix (%u)",i,proto->RandomSuffix);
1986 const_cast<ItemPrototype*>(proto)->RandomSuffix = 0;
1989 if(proto->ItemSet && !sItemSetStore.LookupEntry(proto->ItemSet))
1991 sLog.outErrorDb("Item (Entry: %u) have wrong ItemSet (%u)",i,proto->ItemSet);
1992 const_cast<ItemPrototype*>(proto)->ItemSet = 0;
1995 if(proto->Area && !GetAreaEntryByAreaID(proto->Area))
1996 sLog.outErrorDb("Item (Entry: %u) has wrong Area (%u)",i,proto->Area);
1998 if(proto->Map && !sMapStore.LookupEntry(proto->Map))
1999 sLog.outErrorDb("Item (Entry: %u) has wrong Map (%u)",i,proto->Map);
2001 if(proto->BagFamily)
2003 // check bits
2004 for(uint32 j = 0; j < sizeof(proto->BagFamily)*8; ++j)
2006 uint32 mask = 1 << j;
2007 if((proto->BagFamily & mask)==0)
2008 continue;
2010 ItemBagFamilyEntry const* bf = sItemBagFamilyStore.LookupEntry(j+1);
2011 if(!bf)
2013 sLog.outErrorDb("Item (Entry: %u) has bag family bit set not listed in ItemBagFamily.dbc, remove bit",i);
2014 const_cast<ItemPrototype*>(proto)->BagFamily &= ~mask;
2015 continue;
2018 if(BAG_FAMILY_MASK_CURRENCY_TOKENS & mask)
2020 CurrencyTypesEntry const* ctEntry = sCurrencyTypesStore.LookupEntry(proto->ItemId);
2021 if(!ctEntry)
2023 sLog.outErrorDb("Item (Entry: %u) has currency bag family bit set in BagFamily but not listed in CurrencyTypes.dbc, remove bit",i);
2024 const_cast<ItemPrototype*>(proto)->BagFamily &= ~mask;
2030 if(proto->TotemCategory && !sTotemCategoryStore.LookupEntry(proto->TotemCategory))
2031 sLog.outErrorDb("Item (Entry: %u) has wrong TotemCategory (%u)",i,proto->TotemCategory);
2033 for (int j = 0; j < MAX_ITEM_PROTO_SOCKETS; ++j)
2035 if(proto->Socket[j].Color && (proto->Socket[j].Color & SOCKET_COLOR_ALL) != proto->Socket[j].Color)
2037 sLog.outErrorDb("Item (Entry: %u) has wrong socketColor_%d (%u)",i,j+1,proto->Socket[j].Color);
2038 const_cast<ItemPrototype*>(proto)->Socket[j].Color = 0;
2042 if(proto->GemProperties && !sGemPropertiesStore.LookupEntry(proto->GemProperties))
2043 sLog.outErrorDb("Item (Entry: %u) has wrong GemProperties (%u)",i,proto->GemProperties);
2045 if(proto->FoodType >= MAX_PET_DIET)
2047 sLog.outErrorDb("Item (Entry: %u) has wrong FoodType value (%u)",i,proto->FoodType);
2048 const_cast<ItemPrototype*>(proto)->FoodType = 0;
2051 if(proto->ItemLimitCategory && !sItemLimitCategoryStore.LookupEntry(proto->ItemLimitCategory))
2053 sLog.outErrorDb("Item (Entry: %u) has wrong LimitCategory value (%u)",i,proto->ItemLimitCategory);
2054 const_cast<ItemPrototype*>(proto)->ItemLimitCategory = 0;
2057 if(proto->HolidayId && !sHolidaysStore.LookupEntry(proto->HolidayId))
2059 sLog.outErrorDb("Item (Entry: %u) has wrong HolidayId value (%u)", i, proto->HolidayId);
2060 const_cast<ItemPrototype*>(proto)->HolidayId = 0;
2064 // check some dbc referenced items (avoid duplicate reports)
2065 std::set<uint32> notFoundOutfit;
2066 for (uint32 i = 1; i < sCharStartOutfitStore.GetNumRows(); ++i)
2068 CharStartOutfitEntry const* entry = sCharStartOutfitStore.LookupEntry(i);
2069 if (!entry)
2070 continue;
2072 for(int j = 0; j < MAX_OUTFIT_ITEMS; ++j)
2074 if(entry->ItemId[j] <= 0)
2075 continue;
2077 uint32 item_id = entry->ItemId[j];
2079 if(!GetItemPrototype(item_id))
2080 notFoundOutfit.insert(item_id);
2084 for(std::set<uint32>::const_iterator itr = notFoundOutfit.begin(); itr != notFoundOutfit.end(); ++itr)
2085 sLog.outErrorDb("Item (Entry: %u) not exist in `item_template` but referenced in `CharStartOutfit.dbc`", *itr);
2088 void ObjectMgr::LoadItemRequiredTarget()
2090 m_ItemRequiredTarget.clear(); // needed for reload case
2092 uint32 count = 0;
2094 QueryResult *result = WorldDatabase.Query("SELECT entry,type,targetEntry FROM item_required_target");
2096 if (!result)
2098 barGoLink bar(1);
2100 bar.step();
2102 sLog.outString();
2103 sLog.outErrorDb(">> Loaded 0 ItemRequiredTarget. DB table `item_required_target` is empty.");
2104 return;
2107 barGoLink bar(result->GetRowCount());
2111 Field *fields = result->Fetch();
2112 bar.step();
2114 uint32 uiItemId = fields[0].GetUInt32();
2115 uint32 uiType = fields[1].GetUInt32();
2116 uint32 uiTargetEntry = fields[2].GetUInt32();
2118 ItemPrototype const* pItemProto = sItemStorage.LookupEntry<ItemPrototype>(uiItemId);
2120 if (!pItemProto)
2122 sLog.outErrorDb("Table `item_required_target`: Entry %u listed for TargetEntry %u does not exist in `item_template`.",uiItemId,uiTargetEntry);
2123 continue;
2126 bool bIsItemSpellValid = false;
2128 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
2130 if (SpellEntry const* pSpellInfo = sSpellStore.LookupEntry(pItemProto->Spells[i].SpellId))
2132 if (pItemProto->Spells[i].SpellTrigger == ITEM_SPELLTRIGGER_ON_USE ||
2133 pItemProto->Spells[i].SpellTrigger == ITEM_SPELLTRIGGER_ON_NO_DELAY_USE)
2135 SpellScriptTargetBounds bounds = sSpellMgr.GetSpellScriptTargetBounds(pSpellInfo->Id);
2136 if (bounds.first != bounds.second)
2137 break;
2139 for (int j = 0; j < 3; ++j)
2141 if (pSpellInfo->EffectImplicitTargetA[j] == TARGET_CHAIN_DAMAGE ||
2142 pSpellInfo->EffectImplicitTargetB[j] == TARGET_CHAIN_DAMAGE ||
2143 pSpellInfo->EffectImplicitTargetA[j] == TARGET_DUELVSPLAYER ||
2144 pSpellInfo->EffectImplicitTargetB[j] == TARGET_DUELVSPLAYER)
2146 bIsItemSpellValid = true;
2147 break;
2150 if (bIsItemSpellValid)
2151 break;
2156 if (!bIsItemSpellValid)
2158 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);
2159 continue;
2162 if (!uiType || uiType > MAX_ITEM_REQ_TARGET_TYPE)
2164 sLog.outErrorDb("Table `item_required_target`: Type %u for TargetEntry %u is incorrect.",uiType,uiTargetEntry);
2165 continue;
2168 if (!uiTargetEntry)
2170 sLog.outErrorDb("Table `item_required_target`: TargetEntry == 0 for Type (%u).",uiType);
2171 continue;
2174 if (!sCreatureStorage.LookupEntry<CreatureInfo>(uiTargetEntry))
2176 sLog.outErrorDb("Table `item_required_target`: creature template entry %u does not exist.",uiTargetEntry);
2177 continue;
2180 m_ItemRequiredTarget.insert(ItemRequiredTargetMap::value_type(uiItemId,ItemRequiredTarget(ItemRequiredTargetType(uiType),uiTargetEntry)));
2182 ++count;
2183 } while (result->NextRow());
2185 delete result;
2187 sLog.outString();
2188 sLog.outString(">> Loaded %u Item required targets", count);
2191 void ObjectMgr::LoadPetLevelInfo()
2193 // Loading levels data
2195 // 0 1 2 3 4 5 6 7 8 9
2196 QueryResult *result = WorldDatabase.Query("SELECT creature_entry, level, hp, mana, str, agi, sta, inte, spi, armor FROM pet_levelstats");
2198 uint32 count = 0;
2200 if (!result)
2202 barGoLink bar( 1 );
2203 bar.step();
2205 sLog.outString();
2206 sLog.outString(">> Loaded %u level pet stats definitions", count);
2207 sLog.outErrorDb("Error loading `pet_levelstats` table or empty table.");
2208 return;
2211 barGoLink bar( result->GetRowCount() );
2215 Field* fields = result->Fetch();
2217 uint32 creature_id = fields[0].GetUInt32();
2218 if(!sCreatureStorage.LookupEntry<CreatureInfo>(creature_id))
2220 sLog.outErrorDb("Wrong creature id %u in `pet_levelstats` table, ignoring.",creature_id);
2221 continue;
2224 uint32 current_level = fields[1].GetUInt32();
2225 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2227 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2228 sLog.outErrorDb("Wrong (> %u) level %u in `pet_levelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
2229 else
2231 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `pet_levelstats` table, ignoring.",current_level);
2232 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
2234 continue;
2236 else if(current_level < 1)
2238 sLog.outErrorDb("Wrong (<1) level %u in `pet_levelstats` table, ignoring.",current_level);
2239 continue;
2242 PetLevelInfo*& pInfoMapEntry = petInfo[creature_id];
2244 if(pInfoMapEntry==NULL)
2245 pInfoMapEntry = new PetLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
2247 // data for level 1 stored in [0] array element, ...
2248 PetLevelInfo* pLevelInfo = &pInfoMapEntry[current_level-1];
2250 pLevelInfo->health = fields[2].GetUInt16();
2251 pLevelInfo->mana = fields[3].GetUInt16();
2252 pLevelInfo->armor = fields[9].GetUInt16();
2254 for (int i = 0; i < MAX_STATS; i++)
2256 pLevelInfo->stats[i] = fields[i+4].GetUInt16();
2259 bar.step();
2260 ++count;
2262 while (result->NextRow());
2264 delete result;
2266 sLog.outString();
2267 sLog.outString( ">> Loaded %u level pet stats definitions", count );
2270 // Fill gaps and check integrity
2271 for (PetLevelInfoMap::iterator itr = petInfo.begin(); itr != petInfo.end(); ++itr)
2273 PetLevelInfo* pInfo = itr->second;
2275 // fatal error if no level 1 data
2276 if(!pInfo || pInfo[0].health == 0 )
2278 sLog.outErrorDb("Creature %u does not have pet stats data for Level 1!",itr->first);
2279 exit(1);
2282 // fill level gaps
2283 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2285 if(pInfo[level].health == 0)
2287 sLog.outErrorDb("Creature %u has no data for Level %i pet stats data, using data of Level %i.",itr->first,level+1, level);
2288 pInfo[level] = pInfo[level-1];
2294 PetLevelInfo const* ObjectMgr::GetPetLevelInfo(uint32 creature_id, uint32 level) const
2296 if(level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2297 level = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL);
2299 PetLevelInfoMap::const_iterator itr = petInfo.find(creature_id);
2300 if(itr == petInfo.end())
2301 return NULL;
2303 return &itr->second[level-1]; // data for level 1 stored in [0] array element, ...
2306 void ObjectMgr::LoadPlayerInfo()
2308 // Load playercreate
2310 // 0 1 2 3 4 5 6
2311 QueryResult *result = WorldDatabase.Query("SELECT race, class, map, zone, position_x, position_y, position_z FROM playercreateinfo");
2313 uint32 count = 0;
2315 if (!result)
2317 barGoLink bar( 1 );
2319 sLog.outString();
2320 sLog.outString( ">> Loaded %u player create definitions", count );
2321 sLog.outErrorDb( "Error loading `playercreateinfo` table or empty table.");
2322 exit(1);
2325 barGoLink bar( result->GetRowCount() );
2329 Field* fields = result->Fetch();
2331 uint32 current_race = fields[0].GetUInt32();
2332 uint32 current_class = fields[1].GetUInt32();
2333 uint32 mapId = fields[2].GetUInt32();
2334 uint32 zoneId = fields[3].GetUInt32();
2335 float positionX = fields[4].GetFloat();
2336 float positionY = fields[5].GetFloat();
2337 float positionZ = fields[6].GetFloat();
2339 if(current_race >= MAX_RACES)
2341 sLog.outErrorDb("Wrong race %u in `playercreateinfo` table, ignoring.",current_race);
2342 continue;
2345 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(current_race);
2346 if(!rEntry)
2348 sLog.outErrorDb("Wrong race %u in `playercreateinfo` table, ignoring.",current_race);
2349 continue;
2352 if(current_class >= MAX_CLASSES)
2354 sLog.outErrorDb("Wrong class %u in `playercreateinfo` table, ignoring.",current_class);
2355 continue;
2358 if(!sChrClassesStore.LookupEntry(current_class))
2360 sLog.outErrorDb("Wrong class %u in `playercreateinfo` table, ignoring.",current_class);
2361 continue;
2364 // accept DB data only for valid position (and non instanceable)
2365 if( !MapManager::IsValidMapCoord(mapId,positionX,positionY,positionZ) )
2367 sLog.outErrorDb("Wrong home position for class %u race %u pair in `playercreateinfo` table, ignoring.",current_class,current_race);
2368 continue;
2371 if( sMapStore.LookupEntry(mapId)->Instanceable() )
2373 sLog.outErrorDb("Home position in instanceable map for class %u race %u pair in `playercreateinfo` table, ignoring.",current_class,current_race);
2374 continue;
2377 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2379 pInfo->mapId = mapId;
2380 pInfo->zoneId = zoneId;
2381 pInfo->positionX = positionX;
2382 pInfo->positionY = positionY;
2383 pInfo->positionZ = positionZ;
2385 pInfo->displayId_m = rEntry->model_m;
2386 pInfo->displayId_f = rEntry->model_f;
2388 bar.step();
2389 ++count;
2391 while (result->NextRow());
2393 delete result;
2395 sLog.outString();
2396 sLog.outString( ">> Loaded %u player create definitions", count );
2399 // Load playercreate items
2401 // 0 1 2 3
2402 QueryResult *result = WorldDatabase.Query("SELECT race, class, itemid, amount FROM playercreateinfo_item");
2404 uint32 count = 0;
2406 if (!result)
2408 barGoLink bar( 1 );
2410 bar.step();
2412 sLog.outString();
2413 sLog.outString( ">> Loaded %u custom player create items", count );
2415 else
2417 barGoLink bar( result->GetRowCount() );
2421 Field* fields = result->Fetch();
2423 uint32 current_race = fields[0].GetUInt32();
2424 if(current_race >= MAX_RACES)
2426 sLog.outErrorDb("Wrong race %u in `playercreateinfo_item` table, ignoring.",current_race);
2427 continue;
2430 uint32 current_class = fields[1].GetUInt32();
2431 if(current_class >= MAX_CLASSES)
2433 sLog.outErrorDb("Wrong class %u in `playercreateinfo_item` table, ignoring.",current_class);
2434 continue;
2437 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2439 uint32 item_id = fields[2].GetUInt32();
2441 if(!GetItemPrototype(item_id))
2443 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);
2444 continue;
2447 uint32 amount = fields[3].GetUInt32();
2449 if(!amount)
2451 sLog.outErrorDb("Item id %u (class %u race %u) have amount==0 in `playercreateinfo_item` table, ignoring.",item_id,current_race,current_class);
2452 continue;
2455 pInfo->item.push_back(PlayerCreateInfoItem( item_id, amount));
2457 bar.step();
2458 ++count;
2460 while(result->NextRow());
2462 delete result;
2464 sLog.outString();
2465 sLog.outString( ">> Loaded %u custom player create items", count );
2469 // Load playercreate spells
2471 // 0 1 2
2472 QueryResult *result = WorldDatabase.Query("SELECT race, class, Spell FROM playercreateinfo_spell");
2474 uint32 count = 0;
2476 if (!result)
2478 barGoLink bar( 1 );
2480 sLog.outString();
2481 sLog.outString( ">> Loaded %u player create spells", count );
2482 sLog.outErrorDb( "Error loading `playercreateinfo_spell` table or empty table.");
2484 else
2486 barGoLink bar( result->GetRowCount() );
2490 Field* fields = result->Fetch();
2492 uint32 current_race = fields[0].GetUInt32();
2493 if(current_race >= MAX_RACES)
2495 sLog.outErrorDb("Wrong race %u in `playercreateinfo_spell` table, ignoring.",current_race);
2496 continue;
2499 uint32 current_class = fields[1].GetUInt32();
2500 if(current_class >= MAX_CLASSES)
2502 sLog.outErrorDb("Wrong class %u in `playercreateinfo_spell` table, ignoring.",current_class);
2503 continue;
2506 uint32 spell_id = fields[2].GetUInt32();
2507 if (!sSpellStore.LookupEntry(spell_id))
2509 sLog.outErrorDb("Non existing spell %u in `playercreateinfo_spell` table, ignoring.", spell_id);
2510 continue;
2513 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2514 pInfo->spell.push_back(spell_id);
2516 bar.step();
2517 ++count;
2519 while( result->NextRow() );
2521 delete result;
2523 sLog.outString();
2524 sLog.outString( ">> Loaded %u player create spells", count );
2528 // Load playercreate actions
2530 // 0 1 2 3 4
2531 QueryResult *result = WorldDatabase.Query("SELECT race, class, button, action, type FROM playercreateinfo_action");
2533 uint32 count = 0;
2535 if (!result)
2537 barGoLink bar( 1 );
2539 sLog.outString();
2540 sLog.outString( ">> Loaded %u player create actions", count );
2541 sLog.outErrorDb( "Error loading `playercreateinfo_action` table or empty table.");
2543 else
2545 barGoLink bar( result->GetRowCount() );
2549 Field* fields = result->Fetch();
2551 uint32 current_race = fields[0].GetUInt32();
2552 if(current_race >= MAX_RACES)
2554 sLog.outErrorDb("Wrong race %u in `playercreateinfo_action` table, ignoring.",current_race);
2555 continue;
2558 uint32 current_class = fields[1].GetUInt32();
2559 if(current_class >= MAX_CLASSES)
2561 sLog.outErrorDb("Wrong class %u in `playercreateinfo_action` table, ignoring.",current_class);
2562 continue;
2565 uint8 action_button = fields[2].GetUInt8();
2566 uint32 action = fields[3].GetUInt32();
2567 uint8 action_type = fields[4].GetUInt8();
2569 if (!Player::IsActionButtonDataValid(action_button,action,action_type,NULL))
2570 continue;
2572 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2573 pInfo->action.push_back(PlayerCreateInfoAction(action_button,action,action_type));
2575 bar.step();
2576 ++count;
2578 while( result->NextRow() );
2580 delete result;
2582 sLog.outString();
2583 sLog.outString( ">> Loaded %u player create actions", count );
2587 // Loading levels data (class only dependent)
2589 // 0 1 2 3
2590 QueryResult *result = WorldDatabase.Query("SELECT class, level, basehp, basemana FROM player_classlevelstats");
2592 uint32 count = 0;
2594 if (!result)
2596 barGoLink bar( 1 );
2598 sLog.outString();
2599 sLog.outString( ">> Loaded %u level health/mana definitions", count );
2600 sLog.outErrorDb( "Error loading `player_classlevelstats` table or empty table.");
2601 exit(1);
2604 barGoLink bar( result->GetRowCount() );
2608 Field* fields = result->Fetch();
2610 uint32 current_class = fields[0].GetUInt32();
2611 if(current_class >= MAX_CLASSES)
2613 sLog.outErrorDb("Wrong class %u in `player_classlevelstats` table, ignoring.",current_class);
2614 continue;
2617 uint32 current_level = fields[1].GetUInt32();
2618 if(current_level == 0)
2620 sLog.outErrorDb("Wrong level %u in `player_classlevelstats` table, ignoring.",current_level);
2621 continue;
2623 else if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2625 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2626 sLog.outErrorDb("Wrong (> %u) level %u in `player_classlevelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
2627 else
2629 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_classlevelstats` table, ignoring.",current_level);
2630 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
2632 continue;
2635 PlayerClassInfo* pClassInfo = &playerClassInfo[current_class];
2637 if(!pClassInfo->levelInfo)
2638 pClassInfo->levelInfo = new PlayerClassLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
2640 PlayerClassLevelInfo* pClassLevelInfo = &pClassInfo->levelInfo[current_level-1];
2642 pClassLevelInfo->basehealth = fields[2].GetUInt16();
2643 pClassLevelInfo->basemana = fields[3].GetUInt16();
2645 bar.step();
2646 ++count;
2648 while (result->NextRow());
2650 delete result;
2652 sLog.outString();
2653 sLog.outString( ">> Loaded %u level health/mana definitions", count );
2656 // Fill gaps and check integrity
2657 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2659 // skip non existed classes
2660 if(!sChrClassesStore.LookupEntry(class_))
2661 continue;
2663 PlayerClassInfo* pClassInfo = &playerClassInfo[class_];
2665 // fatal error if no level 1 data
2666 if(!pClassInfo->levelInfo || pClassInfo->levelInfo[0].basehealth == 0 )
2668 sLog.outErrorDb("Class %i Level 1 does not have health/mana data!",class_);
2669 exit(1);
2672 // fill level gaps
2673 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2675 if(pClassInfo->levelInfo[level].basehealth == 0)
2677 sLog.outErrorDb("Class %i Level %i does not have health/mana data. Using stats data of level %i.",class_,level+1, level);
2678 pClassInfo->levelInfo[level] = pClassInfo->levelInfo[level-1];
2683 // Loading levels data (class/race dependent)
2685 // 0 1 2 3 4 5 6 7
2686 QueryResult *result = WorldDatabase.Query("SELECT race, class, level, str, agi, sta, inte, spi FROM player_levelstats");
2688 uint32 count = 0;
2690 if (!result)
2692 barGoLink bar( 1 );
2694 sLog.outString();
2695 sLog.outString( ">> Loaded %u level stats definitions", count );
2696 sLog.outErrorDb( "Error loading `player_levelstats` table or empty table.");
2697 exit(1);
2700 barGoLink bar( result->GetRowCount() );
2704 Field* fields = result->Fetch();
2706 uint32 current_race = fields[0].GetUInt32();
2707 if(current_race >= MAX_RACES)
2709 sLog.outErrorDb("Wrong race %u in `player_levelstats` table, ignoring.",current_race);
2710 continue;
2713 uint32 current_class = fields[1].GetUInt32();
2714 if(current_class >= MAX_CLASSES)
2716 sLog.outErrorDb("Wrong class %u in `player_levelstats` table, ignoring.",current_class);
2717 continue;
2720 uint32 current_level = fields[2].GetUInt32();
2721 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2723 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2724 sLog.outErrorDb("Wrong (> %u) level %u in `player_levelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
2725 else
2727 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_levelstats` table, ignoring.",current_level);
2728 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
2730 continue;
2733 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2735 if(!pInfo->levelInfo)
2736 pInfo->levelInfo = new PlayerLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
2738 PlayerLevelInfo* pLevelInfo = &pInfo->levelInfo[current_level-1];
2740 for (int i = 0; i < MAX_STATS; i++)
2742 pLevelInfo->stats[i] = fields[i+3].GetUInt8();
2745 bar.step();
2746 ++count;
2748 while (result->NextRow());
2750 delete result;
2752 sLog.outString();
2753 sLog.outString( ">> Loaded %u level stats definitions", count );
2756 // Fill gaps and check integrity
2757 for (int race = 0; race < MAX_RACES; ++race)
2759 // skip non existed races
2760 if(!sChrRacesStore.LookupEntry(race))
2761 continue;
2763 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2765 // skip non existed classes
2766 if(!sChrClassesStore.LookupEntry(class_))
2767 continue;
2769 PlayerInfo* pInfo = &playerInfo[race][class_];
2771 // skip non loaded combinations
2772 if(!pInfo->displayId_m || !pInfo->displayId_f)
2773 continue;
2775 // skip expansion races if not playing with expansion
2776 if (sWorld.getConfig(CONFIG_EXPANSION) < 1 && (race == RACE_BLOODELF || race == RACE_DRAENEI))
2777 continue;
2779 // skip expansion classes if not playing with expansion
2780 if (sWorld.getConfig(CONFIG_EXPANSION) < 2 && class_ == CLASS_DEATH_KNIGHT)
2781 continue;
2783 // fatal error if no level 1 data
2784 if(!pInfo->levelInfo || pInfo->levelInfo[0].stats[0] == 0 )
2786 sLog.outErrorDb("Race %i Class %i Level 1 does not have stats data!",race,class_);
2787 exit(1);
2790 // fill level gaps
2791 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2793 if(pInfo->levelInfo[level].stats[0] == 0)
2795 sLog.outErrorDb("Race %i Class %i Level %i does not have stats data. Using stats data of level %i.",race,class_,level+1, level);
2796 pInfo->levelInfo[level] = pInfo->levelInfo[level-1];
2802 // Loading xp per level data
2804 mPlayerXPperLevel.resize(sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL));
2805 for (uint32 level = 0; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2806 mPlayerXPperLevel[level] = 0;
2808 // 0 1
2809 QueryResult *result = WorldDatabase.Query("SELECT lvl, xp_for_next_level FROM player_xp_for_level");
2811 uint32 count = 0;
2813 if (!result)
2815 barGoLink bar( 1 );
2817 sLog.outString();
2818 sLog.outString( ">> Loaded %u xp for level definitions", count );
2819 sLog.outErrorDb( "Error loading `player_xp_for_level` table or empty table.");
2820 exit(1);
2823 barGoLink bar( result->GetRowCount() );
2827 Field* fields = result->Fetch();
2829 uint32 current_level = fields[0].GetUInt32();
2830 uint32 current_xp = fields[1].GetUInt32();
2832 if(current_level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2834 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2835 sLog.outErrorDb("Wrong (> %u) level %u in `player_xp_for_level` table, ignoring.", STRONG_MAX_LEVEL,current_level);
2836 else
2838 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_xp_for_levels` table, ignoring.",current_level);
2839 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
2841 continue;
2843 //PlayerXPperLevel
2844 mPlayerXPperLevel[current_level] = current_xp;
2845 bar.step();
2846 ++count;
2848 while (result->NextRow());
2850 delete result;
2852 sLog.outString();
2853 sLog.outString( ">> Loaded %u xp for level definitions", count );
2856 // fill level gaps
2857 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2859 if( mPlayerXPperLevel[level] == 0)
2861 sLog.outErrorDb("Level %i does not have XP for level data. Using data of level [%i] + 100.",level+1, level);
2862 mPlayerXPperLevel[level] = mPlayerXPperLevel[level-1]+100;
2867 void ObjectMgr::GetPlayerClassLevelInfo(uint32 class_, uint32 level, PlayerClassLevelInfo* info) const
2869 if(level < 1 || class_ >= MAX_CLASSES)
2870 return;
2872 PlayerClassInfo const* pInfo = &playerClassInfo[class_];
2874 if(level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2875 level = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL);
2877 *info = pInfo->levelInfo[level-1];
2880 void ObjectMgr::GetPlayerLevelInfo(uint32 race, uint32 class_, uint32 level, PlayerLevelInfo* info) const
2882 if(level < 1 || race >= MAX_RACES || class_ >= MAX_CLASSES)
2883 return;
2885 PlayerInfo const* pInfo = &playerInfo[race][class_];
2886 if(pInfo->displayId_m==0 || pInfo->displayId_f==0)
2887 return;
2889 if(level <= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2890 *info = pInfo->levelInfo[level-1];
2891 else
2892 BuildPlayerLevelInfo(race,class_,level,info);
2895 void ObjectMgr::BuildPlayerLevelInfo(uint8 race, uint8 _class, uint8 level, PlayerLevelInfo* info) const
2897 // base data (last known level)
2898 *info = playerInfo[race][_class].levelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)-1];
2900 for(int lvl = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)-1; lvl < level; ++lvl)
2902 switch(_class)
2904 case CLASS_WARRIOR:
2905 info->stats[STAT_STRENGTH] += (lvl > 23 ? 2: (lvl > 1 ? 1: 0));
2906 info->stats[STAT_STAMINA] += (lvl > 23 ? 2: (lvl > 1 ? 1: 0));
2907 info->stats[STAT_AGILITY] += (lvl > 36 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2908 info->stats[STAT_INTELLECT] += (lvl > 9 && !(lvl%2) ? 1: 0);
2909 info->stats[STAT_SPIRIT] += (lvl > 9 && !(lvl%2) ? 1: 0);
2910 break;
2911 case CLASS_PALADIN:
2912 info->stats[STAT_STRENGTH] += (lvl > 3 ? 1: 0);
2913 info->stats[STAT_STAMINA] += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2914 info->stats[STAT_AGILITY] += (lvl > 38 ? 1: (lvl > 7 && !(lvl%2) ? 1: 0));
2915 info->stats[STAT_INTELLECT] += (lvl > 6 && (lvl%2) ? 1: 0);
2916 info->stats[STAT_SPIRIT] += (lvl > 7 ? 1: 0);
2917 break;
2918 case CLASS_HUNTER:
2919 info->stats[STAT_STRENGTH] += (lvl > 4 ? 1: 0);
2920 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2921 info->stats[STAT_AGILITY] += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2922 info->stats[STAT_INTELLECT] += (lvl > 8 && (lvl%2) ? 1: 0);
2923 info->stats[STAT_SPIRIT] += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2924 break;
2925 case CLASS_ROGUE:
2926 info->stats[STAT_STRENGTH] += (lvl > 5 ? 1: 0);
2927 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2928 info->stats[STAT_AGILITY] += (lvl > 16 ? 2: (lvl > 1 ? 1: 0));
2929 info->stats[STAT_INTELLECT] += (lvl > 8 && !(lvl%2) ? 1: 0);
2930 info->stats[STAT_SPIRIT] += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2931 break;
2932 case CLASS_PRIEST:
2933 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2934 info->stats[STAT_STAMINA] += (lvl > 5 ? 1: 0);
2935 info->stats[STAT_AGILITY] += (lvl > 38 ? 1: (lvl > 8 && (lvl%2) ? 1: 0));
2936 info->stats[STAT_INTELLECT] += (lvl > 22 ? 2: (lvl > 1 ? 1: 0));
2937 info->stats[STAT_SPIRIT] += (lvl > 3 ? 1: 0);
2938 break;
2939 case CLASS_SHAMAN:
2940 info->stats[STAT_STRENGTH] += (lvl > 34 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2941 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2942 info->stats[STAT_AGILITY] += (lvl > 7 && !(lvl%2) ? 1: 0);
2943 info->stats[STAT_INTELLECT] += (lvl > 5 ? 1: 0);
2944 info->stats[STAT_SPIRIT] += (lvl > 4 ? 1: 0);
2945 break;
2946 case CLASS_MAGE:
2947 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2948 info->stats[STAT_STAMINA] += (lvl > 5 ? 1: 0);
2949 info->stats[STAT_AGILITY] += (lvl > 9 && !(lvl%2) ? 1: 0);
2950 info->stats[STAT_INTELLECT] += (lvl > 24 ? 2: (lvl > 1 ? 1: 0));
2951 info->stats[STAT_SPIRIT] += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
2952 break;
2953 case CLASS_WARLOCK:
2954 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2955 info->stats[STAT_STAMINA] += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
2956 info->stats[STAT_AGILITY] += (lvl > 9 && !(lvl%2) ? 1: 0);
2957 info->stats[STAT_INTELLECT] += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
2958 info->stats[STAT_SPIRIT] += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
2959 break;
2960 case CLASS_DRUID:
2961 info->stats[STAT_STRENGTH] += (lvl > 38 ? 2: (lvl > 6 && (lvl%2) ? 1: 0));
2962 info->stats[STAT_STAMINA] += (lvl > 32 ? 2: (lvl > 4 ? 1: 0));
2963 info->stats[STAT_AGILITY] += (lvl > 38 ? 2: (lvl > 8 && (lvl%2) ? 1: 0));
2964 info->stats[STAT_INTELLECT] += (lvl > 38 ? 3: (lvl > 4 ? 1: 0));
2965 info->stats[STAT_SPIRIT] += (lvl > 38 ? 3: (lvl > 5 ? 1: 0));
2970 void ObjectMgr::LoadGuilds()
2972 Guild *newGuild;
2973 uint32 count = 0;
2975 // 0 1 2 3 4 5 6
2976 QueryResult *result = CharacterDatabase.Query("SELECT guild.guildid,guild.name,leaderguid,EmblemStyle,EmblemColor,BorderStyle,BorderColor,"
2977 // 7 8 9 10 11 12
2978 "BackgroundColor,info,motd,createdate,BankMoney,(SELECT COUNT(guild_bank_tab.guildid) FROM guild_bank_tab WHERE guild_bank_tab.guildid = guild.guildid) "
2979 "FROM guild ORDER BY guildid ASC");
2981 if( !result )
2984 barGoLink bar( 1 );
2986 bar.step();
2988 sLog.outString();
2989 sLog.outString( ">> Loaded %u guild definitions", count );
2990 return;
2993 // load guild ranks
2994 // 0 1 2 3 4
2995 QueryResult *guildRanksResult = CharacterDatabase.Query("SELECT guildid,rid,rname,rights,BankMoneyPerDay FROM guild_rank ORDER BY guildid ASC, rid ASC");
2997 // load guild members
2998 // 0 1 2 3 4 5 6
2999 QueryResult *guildMembersResult = CharacterDatabase.Query("SELECT guildid,guild_member.guid,rank,pnote,offnote,BankResetTimeMoney,BankRemMoney,"
3000 // 7 8 9 10 11 12
3001 "BankResetTimeTab0,BankRemSlotsTab0,BankResetTimeTab1,BankRemSlotsTab1,BankResetTimeTab2,BankRemSlotsTab2,"
3002 // 13 14 15 16 17 18
3003 "BankResetTimeTab3,BankRemSlotsTab3,BankResetTimeTab4,BankRemSlotsTab4,BankResetTimeTab5,BankRemSlotsTab5,"
3004 // 19 20 21 22 23
3005 "characters.name, characters.level, characters.class, characters.zone, characters.logout_time "
3006 "FROM guild_member LEFT JOIN characters ON characters.guid = guild_member.guid ORDER BY guildid ASC");
3008 // load guild bank tab rights
3009 // 0 1 2 3 4
3010 QueryResult *guildBankTabRightsResult = CharacterDatabase.Query("SELECT guildid,TabId,rid,gbright,SlotPerDay FROM guild_bank_right ORDER BY guildid ASC, TabId ASC");
3012 barGoLink bar( result->GetRowCount() );
3016 //Field *fields = result->Fetch();
3018 bar.step();
3019 ++count;
3021 newGuild = new Guild;
3022 if (!newGuild->LoadGuildFromDB(result) ||
3023 !newGuild->LoadRanksFromDB(guildRanksResult) ||
3024 !newGuild->LoadMembersFromDB(guildMembersResult) ||
3025 !newGuild->LoadBankRightsFromDB(guildBankTabRightsResult) ||
3026 !newGuild->CheckGuildStructure()
3029 newGuild->Disband();
3030 delete newGuild;
3031 continue;
3033 newGuild->LoadGuildEventLogFromDB();
3034 newGuild->LoadGuildBankEventLogFromDB();
3035 newGuild->LoadGuildBankFromDB();
3036 AddGuild(newGuild);
3037 } while( result->NextRow() );
3039 delete result;
3040 delete guildRanksResult;
3041 delete guildMembersResult;
3042 delete guildBankTabRightsResult;
3044 //delete unused LogGuid records in guild_eventlog and guild_bank_eventlog table
3045 //you can comment these lines if you don't plan to change CONFIG_GUILD_EVENT_LOG_COUNT and CONFIG_GUILD_BANK_EVENT_LOG_COUNT
3046 CharacterDatabase.PQuery("DELETE FROM guild_eventlog WHERE LogGuid > '%u'", sWorld.getConfig(CONFIG_GUILD_EVENT_LOG_COUNT));
3047 CharacterDatabase.PQuery("DELETE FROM guild_bank_eventlog WHERE LogGuid > '%u'", sWorld.getConfig(CONFIG_GUILD_BANK_EVENT_LOG_COUNT));
3049 sLog.outString();
3050 sLog.outString( ">> Loaded %u guild definitions", count );
3053 void ObjectMgr::LoadArenaTeams()
3055 uint32 count = 0;
3057 // 0 1 2 3 4 5
3058 QueryResult *result = CharacterDatabase.Query( "SELECT arena_team.arenateamid,name,captainguid,type,BackgroundColor,EmblemStyle,"
3059 // 6 7 8 9 10 11 12 13 14
3060 "EmblemColor,BorderStyle,BorderColor, rating,games,wins,played,wins2,rank "
3061 "FROM arena_team LEFT JOIN arena_team_stats ON arena_team.arenateamid = arena_team_stats.arenateamid ORDER BY arena_team.arenateamid ASC" );
3063 if( !result )
3066 barGoLink bar( 1 );
3068 bar.step();
3070 sLog.outString();
3071 sLog.outString( ">> Loaded %u arenateam definitions", count );
3072 return;
3075 // load arena_team members
3076 QueryResult *arenaTeamMembersResult = CharacterDatabase.Query(
3077 // 0 1 2 3 4 5 6 7 8
3078 "SELECT arenateamid,member.guid,played_week,wons_week,played_season,wons_season,personal_rating,name,class "
3079 "FROM arena_team_member member LEFT JOIN characters chars on member.guid = chars.guid ORDER BY member.arenateamid ASC");
3081 barGoLink bar( result->GetRowCount() );
3085 Field *fields = result->Fetch();
3087 bar.step();
3088 ++count;
3090 ArenaTeam *newArenaTeam = new ArenaTeam;
3091 if (!newArenaTeam->LoadArenaTeamFromDB(result) ||
3092 !newArenaTeam->LoadMembersFromDB(arenaTeamMembersResult))
3094 newArenaTeam->Disband(NULL);
3095 delete newArenaTeam;
3096 continue;
3098 AddArenaTeam(newArenaTeam);
3099 }while( result->NextRow() );
3101 delete result;
3102 delete arenaTeamMembersResult;
3104 sLog.outString();
3105 sLog.outString( ">> Loaded %u arenateam definitions", count );
3108 void ObjectMgr::LoadGroups()
3110 // -- loading groups --
3111 uint32 count = 0;
3112 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
3113 QueryResult *result = CharacterDatabase.Query("SELECT mainTank, mainAssistant, lootMethod, looterGuid, lootThreshold, icon1, icon2, icon3, icon4, icon5, icon6, icon7, icon8, isRaid, difficulty, raiddifficulty, leaderGuid FROM groups");
3115 if( !result )
3117 barGoLink bar( 1 );
3119 bar.step();
3121 sLog.outString();
3122 sLog.outString( ">> Loaded %u group definitions", count );
3123 return;
3126 barGoLink bar( result->GetRowCount() );
3130 bar.step();
3131 Field *fields = result->Fetch();
3132 ++count;
3133 uint64 leaderGuid = MAKE_NEW_GUID(fields[16].GetUInt32(),0,HIGHGUID_PLAYER);
3134 Group *group = new Group;
3135 if(!group->LoadGroupFromDB(leaderGuid, result, false))
3137 group->Disband();
3138 delete group;
3139 continue;
3141 AddGroup(group);
3142 }while( result->NextRow() );
3144 delete result;
3146 sLog.outString();
3147 sLog.outString( ">> Loaded %u group definitions", count );
3149 // -- loading members --
3150 count = 0;
3151 // 0 1 2 3
3152 result = CharacterDatabase.Query("SELECT memberGuid, assistant, subgroup, leaderGuid FROM group_member ORDER BY leaderGuid");
3153 if(!result)
3155 barGoLink bar2( 1 );
3156 bar2.step();
3158 else
3160 Group* group = NULL; // used as cached pointer for avoid relookup group for each member
3162 barGoLink bar2( result->GetRowCount() );
3165 bar2.step();
3166 Field *fields = result->Fetch();
3167 count++;
3169 uint32 memberGuidlow = fields[0].GetUInt32();
3170 bool assistent = fields[1].GetBool();
3171 uint8 subgroup = fields[2].GetUInt8();
3172 uint32 leaderGuidLow = fields[3].GetUInt32();
3173 if(!group || GUID_LOPART(group->GetLeaderGUID()) != leaderGuidLow)
3175 group = GetGroupByLeaderLowGUID(leaderGuidLow);
3176 if(!group)
3178 sLog.outErrorDb("Incorrect entry in group_member table : no group with leader %d for member %d!", leaderGuidLow, memberGuidlow);
3179 CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", memberGuidlow);
3180 continue;
3184 if(!group->LoadMemberFromDB(memberGuidlow, subgroup, assistent))
3186 sLog.outErrorDb("Incorrect entry in group_member table : member %d cannot be added to player %d's group!", memberGuidlow, leaderGuidLow);
3187 CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", memberGuidlow);
3189 }while( result->NextRow() );
3190 delete result;
3193 // clean groups
3194 // TODO: maybe delete from the DB before loading in this case
3195 for (GroupMap::iterator itr = mGroupMap.begin(); itr != mGroupMap.end();)
3197 if (itr->second->GetMembersCount() < 2)
3199 itr->second->Disband();
3200 delete itr->second;
3201 mGroupMap.erase(itr++);
3203 else
3204 ++itr;
3207 // -- loading instances --
3208 count = 0;
3209 result = CharacterDatabase.Query(
3210 // 0 1 2 3 4 5
3211 "SELECT leaderGuid, map, instance, permanent, difficulty, resettime, "
3212 // 6
3213 "(SELECT COUNT(*) FROM character_instance WHERE guid = leaderGuid AND instance = group_instance.instance AND permanent = 1 LIMIT 1) "
3214 "FROM group_instance LEFT JOIN instance ON instance = id ORDER BY leaderGuid"
3217 if(!result)
3219 barGoLink bar2( 1 );
3220 bar2.step();
3222 else
3224 Group* group = NULL; // used as cached pointer for avoid relookup group for each member
3226 barGoLink bar2( result->GetRowCount() );
3229 bar2.step();
3230 Field *fields = result->Fetch();
3231 count++;
3233 uint32 leaderGuidLow = fields[0].GetUInt32();
3234 uint32 mapId = fields[1].GetUInt32();
3235 uint32 diff = fields[4].GetUInt8();
3237 if(!group || GUID_LOPART(group->GetLeaderGUID()) != leaderGuidLow)
3239 group = GetGroupByLeaderLowGUID(leaderGuidLow);
3240 if(!group)
3242 sLog.outErrorDb("Incorrect entry in group_instance table : no group with leader %d", leaderGuidLow);
3243 continue;
3247 MapEntry const* mapEntry = sMapStore.LookupEntry(mapId);
3248 if(!mapEntry || !mapEntry->IsDungeon())
3250 sLog.outErrorDb("Incorrect entry in group_instance table : no dungeon map %d", mapId);
3251 continue;
3254 if(diff >= (mapEntry->IsRaid() ? MAX_RAID_DIFFICULTY : MAX_DUNGEON_DIFFICULTY))
3256 sLog.outErrorDb("Wrong dungeon difficulty use in group_instance table: %d", diff + 1);
3257 diff = 0; // default for both difficaly types
3260 InstanceSave *save = sInstanceSaveMgr.AddInstanceSave(mapEntry->MapID, fields[2].GetUInt32(), Difficulty(diff), (time_t)fields[5].GetUInt64(), (fields[6].GetUInt32() == 0), true);
3261 group->BindToInstance(save, fields[3].GetBool(), true);
3262 }while( result->NextRow() );
3263 delete result;
3266 sLog.outString();
3267 sLog.outString( ">> Loaded %u group-instance binds total", count );
3269 sLog.outString();
3270 sLog.outString( ">> Loaded %u group members total", count );
3273 void ObjectMgr::LoadQuests()
3275 // For reload case
3276 for(QuestMap::const_iterator itr=mQuestTemplates.begin(); itr != mQuestTemplates.end(); ++itr)
3277 delete itr->second;
3278 mQuestTemplates.clear();
3280 mExclusiveQuestGroups.clear();
3282 // 0 1 2 3 4 5 6 7 8
3283 QueryResult *result = WorldDatabase.Query("SELECT entry, Method, ZoneOrSort, SkillOrClass, MinLevel, QuestLevel, Type, RequiredRaces, RequiredSkillValue,"
3284 // 9 10 11 12 13 14 15 16
3285 "RepObjectiveFaction, RepObjectiveValue, RequiredMinRepFaction, RequiredMinRepValue, RequiredMaxRepFaction, RequiredMaxRepValue, SuggestedPlayers, LimitTime,"
3286 // 17 18 19 20 21 22 23 24 25 26 27 28
3287 "QuestFlags, SpecialFlags, CharTitleId, PlayersSlain, BonusTalents, PrevQuestId, NextQuestId, ExclusiveGroup, NextQuestInChain, SrcItemId, SrcItemCount, SrcSpell,"
3288 // 29 30 31 32 33 34 35 36 37 38
3289 "Title, Details, Objectives, OfferRewardText, RequestItemsText, EndText, ObjectiveText1, ObjectiveText2, ObjectiveText3, ObjectiveText4,"
3290 // 39 40 41 42 43 44 45 46 47 48 49 50
3291 "ReqItemId1, ReqItemId2, ReqItemId3, ReqItemId4, ReqItemId5, ReqItemId6, ReqItemCount1, ReqItemCount2, ReqItemCount3, ReqItemCount4, ReqItemCount5, ReqItemCount6,"
3292 // 51 52 53 54 55 56 57 58
3293 "ReqSourceId1, ReqSourceId2, ReqSourceId3, ReqSourceId4, ReqSourceCount1, ReqSourceCount2, ReqSourceCount3, ReqSourceCount4,"
3294 // 59 60 61 62 63 64 65 66
3295 "ReqCreatureOrGOId1, ReqCreatureOrGOId2, ReqCreatureOrGOId3, ReqCreatureOrGOId4, ReqCreatureOrGOCount1, ReqCreatureOrGOCount2, ReqCreatureOrGOCount3, ReqCreatureOrGOCount4,"
3296 // 67 68 69 70
3297 "ReqSpellCast1, ReqSpellCast2, ReqSpellCast3, ReqSpellCast4,"
3298 // 71 72 73 74 75 76
3299 "RewChoiceItemId1, RewChoiceItemId2, RewChoiceItemId3, RewChoiceItemId4, RewChoiceItemId5, RewChoiceItemId6,"
3300 // 77 78 79 80 81 82
3301 "RewChoiceItemCount1, RewChoiceItemCount2, RewChoiceItemCount3, RewChoiceItemCount4, RewChoiceItemCount5, RewChoiceItemCount6,"
3302 // 83 84 85 86 87 88 89 90
3303 "RewItemId1, RewItemId2, RewItemId3, RewItemId4, RewItemCount1, RewItemCount2, RewItemCount3, RewItemCount4,"
3304 // 91 92 93 94 95 96 97 98 99 100
3305 "RewRepFaction1, RewRepFaction2, RewRepFaction3, RewRepFaction4, RewRepFaction5, RewRepValue1, RewRepValue2, RewRepValue3, RewRepValue4, RewRepValue5,"
3306 // 101 102 103 104 105 106 107 108 109 110 111
3307 "RewHonorableKills, RewOrReqMoney, RewMoneyMaxLevel, RewSpell, RewSpellCast, RewMailTemplateId, RewMailDelaySecs, PointMapId, PointX, PointY, PointOpt,"
3308 // 112 113 114 115 116 117 118 119
3309 "DetailsEmote1, DetailsEmote2, DetailsEmote3, DetailsEmote4, DetailsEmoteDelay1, DetailsEmoteDelay2, DetailsEmoteDelay3, DetailsEmoteDelay4,"
3310 // 120 121 122 123 124 125
3311 "IncompleteEmote, CompleteEmote, OfferRewardEmote1, OfferRewardEmote2, OfferRewardEmote3, OfferRewardEmote4,"
3312 // 126 127 128 129
3313 "OfferRewardEmoteDelay1, OfferRewardEmoteDelay2, OfferRewardEmoteDelay3, OfferRewardEmoteDelay4,"
3314 // 130 131
3315 "StartScript, CompleteScript"
3316 " FROM quest_template");
3317 if(result == NULL)
3319 barGoLink bar( 1 );
3320 bar.step();
3322 sLog.outString();
3323 sLog.outString( ">> Loaded 0 quests definitions" );
3324 sLog.outErrorDb("`quest_template` table is empty!");
3325 return;
3328 // create multimap previous quest for each existed quest
3329 // some quests can have many previous maps set by NextQuestId in previous quest
3330 // for example set of race quests can lead to single not race specific quest
3331 barGoLink bar( result->GetRowCount() );
3334 bar.step();
3335 Field *fields = result->Fetch();
3337 Quest * newQuest = new Quest(fields);
3338 mQuestTemplates[newQuest->GetQuestId()] = newQuest;
3339 } while( result->NextRow() );
3341 delete result;
3343 // Post processing
3345 std::map<uint32,uint32> usedMailTemplates;
3347 for (QuestMap::iterator iter = mQuestTemplates.begin(); iter != mQuestTemplates.end(); ++iter)
3349 Quest * qinfo = iter->second;
3351 // additional quest integrity checks (GO, creature_template and item_template must be loaded already)
3353 if( qinfo->GetQuestMethod() >= 3 )
3355 sLog.outErrorDb("Quest %u has `Method` = %u, expected values are 0, 1 or 2.",qinfo->GetQuestId(),qinfo->GetQuestMethod());
3358 if (qinfo->QuestFlags & ~QUEST_MANGOS_FLAGS_DB_ALLOWED)
3360 sLog.outErrorDb("Quest %u has `SpecialFlags` = %u > max allowed value. Correct `SpecialFlags` to value <= %u",
3361 qinfo->GetQuestId(),qinfo->QuestFlags >> 24,QUEST_MANGOS_FLAGS_DB_ALLOWED >> 24);
3362 qinfo->QuestFlags &= QUEST_MANGOS_FLAGS_DB_ALLOWED;
3365 if(qinfo->QuestFlags & QUEST_FLAGS_DAILY)
3367 if(!(qinfo->QuestFlags & QUEST_MANGOS_FLAGS_REPEATABLE))
3369 sLog.outErrorDb("Daily Quest %u not marked as repeatable in `SpecialFlags`, added.",qinfo->GetQuestId());
3370 qinfo->QuestFlags |= QUEST_MANGOS_FLAGS_REPEATABLE;
3374 if(qinfo->QuestFlags & QUEST_FLAGS_AUTO_REWARDED)
3376 // at auto-reward can be rewarded only RewChoiceItemId[0]
3377 for(int j = 1; j < QUEST_REWARD_CHOICES_COUNT; ++j )
3379 if(uint32 id = qinfo->RewChoiceItemId[j])
3381 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item from `RewChoiceItemId%d` can't be rewarded with quest flag QUEST_FLAGS_AUTO_REWARDED.",
3382 qinfo->GetQuestId(),j+1,id,j+1);
3383 // no changes, quest ignore this data
3388 // client quest log visual (area case)
3389 if( qinfo->ZoneOrSort > 0 )
3391 if(!GetAreaEntryByAreaID(qinfo->ZoneOrSort))
3393 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %u (zone case) but zone with this id does not exist.",
3394 qinfo->GetQuestId(),qinfo->ZoneOrSort);
3395 // no changes, quest not dependent from this value but can have problems at client
3398 // client quest log visual (sort case)
3399 if( qinfo->ZoneOrSort < 0 )
3401 QuestSortEntry const* qSort = sQuestSortStore.LookupEntry(-int32(qinfo->ZoneOrSort));
3402 if( !qSort )
3404 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (sort case) but quest sort with this id does not exist.",
3405 qinfo->GetQuestId(),qinfo->ZoneOrSort);
3406 // 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)
3408 //check SkillOrClass value (class case).
3409 if( ClassByQuestSort(-int32(qinfo->ZoneOrSort)) )
3411 // SkillOrClass should not have class case when class case already set in ZoneOrSort.
3412 if(qinfo->SkillOrClass < 0)
3414 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (class sort case) and `SkillOrClass` = %i (class case), redundant.",
3415 qinfo->GetQuestId(),qinfo->ZoneOrSort,qinfo->SkillOrClass);
3418 //check for proper SkillOrClass value (skill case)
3419 if(int32 skill_id = SkillByQuestSort(-int32(qinfo->ZoneOrSort)))
3421 // skill is positive value in SkillOrClass
3422 if(qinfo->SkillOrClass != skill_id )
3424 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (skill sort case) but `SkillOrClass` does not have a corresponding value (%i).",
3425 qinfo->GetQuestId(),qinfo->ZoneOrSort,skill_id);
3426 //override, and force proper value here?
3431 // SkillOrClass (class case)
3432 if( qinfo->SkillOrClass < 0 )
3434 if( !sChrClassesStore.LookupEntry(-int32(qinfo->SkillOrClass)) )
3436 sLog.outErrorDb("Quest %u has `SkillOrClass` = %i (class case) but class (%i) does not exist",
3437 qinfo->GetQuestId(),qinfo->SkillOrClass,-qinfo->SkillOrClass);
3440 // SkillOrClass (skill case)
3441 if( qinfo->SkillOrClass > 0 )
3443 if( !sSkillLineStore.LookupEntry(qinfo->SkillOrClass) )
3445 sLog.outErrorDb("Quest %u has `SkillOrClass` = %u (skill case) but skill (%i) does not exist",
3446 qinfo->GetQuestId(),qinfo->SkillOrClass,qinfo->SkillOrClass);
3450 if( qinfo->RequiredSkillValue )
3452 if( qinfo->RequiredSkillValue > sWorld.GetConfigMaxSkillValue() )
3454 sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but max possible skill is %u, quest can't be done.",
3455 qinfo->GetQuestId(),qinfo->RequiredSkillValue,sWorld.GetConfigMaxSkillValue());
3456 // no changes, quest can't be done for this requirement
3459 if( qinfo->SkillOrClass <= 0 )
3461 sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but `SkillOrClass` = %i (class case), value ignored.",
3462 qinfo->GetQuestId(),qinfo->RequiredSkillValue,qinfo->SkillOrClass);
3463 // no changes, quest can't be done for this requirement (fail at wrong skill id)
3466 // else Skill quests can have 0 skill level, this is ok
3468 if(qinfo->RepObjectiveFaction && !sFactionStore.LookupEntry(qinfo->RepObjectiveFaction))
3470 sLog.outErrorDb("Quest %u has `RepObjectiveFaction` = %u but faction template %u does not exist, quest can't be done.",
3471 qinfo->GetQuestId(),qinfo->RepObjectiveFaction,qinfo->RepObjectiveFaction);
3472 // no changes, quest can't be done for this requirement
3475 if(qinfo->RequiredMinRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMinRepFaction))
3477 sLog.outErrorDb("Quest %u has `RequiredMinRepFaction` = %u but faction template %u does not exist, quest can't be done.",
3478 qinfo->GetQuestId(),qinfo->RequiredMinRepFaction,qinfo->RequiredMinRepFaction);
3479 // no changes, quest can't be done for this requirement
3482 if(qinfo->RequiredMaxRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMaxRepFaction))
3484 sLog.outErrorDb("Quest %u has `RequiredMaxRepFaction` = %u but faction template %u does not exist, quest can't be done.",
3485 qinfo->GetQuestId(),qinfo->RequiredMaxRepFaction,qinfo->RequiredMaxRepFaction);
3486 // no changes, quest can't be done for this requirement
3489 if(qinfo->RequiredMinRepValue && qinfo->RequiredMinRepValue > ReputationMgr::Reputation_Cap)
3491 sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but max reputation is %u, quest can't be done.",
3492 qinfo->GetQuestId(),qinfo->RequiredMinRepValue,ReputationMgr::Reputation_Cap);
3493 // no changes, quest can't be done for this requirement
3496 if(qinfo->RequiredMinRepValue && qinfo->RequiredMaxRepValue && qinfo->RequiredMaxRepValue <= qinfo->RequiredMinRepValue)
3498 sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d and `RequiredMinRepValue` = %d, quest can't be done.",
3499 qinfo->GetQuestId(),qinfo->RequiredMaxRepValue,qinfo->RequiredMinRepValue);
3500 // no changes, quest can't be done for this requirement
3503 if(!qinfo->RepObjectiveFaction && qinfo->RepObjectiveValue > 0 )
3505 sLog.outErrorDb("Quest %u has `RepObjectiveValue` = %d but `RepObjectiveFaction` is 0, value has no effect",
3506 qinfo->GetQuestId(),qinfo->RepObjectiveValue);
3507 // warning
3510 if(!qinfo->RequiredMinRepFaction && qinfo->RequiredMinRepValue > 0 )
3512 sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but `RequiredMinRepFaction` is 0, value has no effect",
3513 qinfo->GetQuestId(),qinfo->RequiredMinRepValue);
3514 // warning
3517 if(!qinfo->RequiredMaxRepFaction && qinfo->RequiredMaxRepValue > 0 )
3519 sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d but `RequiredMaxRepFaction` is 0, value has no effect",
3520 qinfo->GetQuestId(),qinfo->RequiredMaxRepValue);
3521 // warning
3524 if(qinfo->CharTitleId && !sCharTitlesStore.LookupEntry(qinfo->CharTitleId))
3526 sLog.outErrorDb("Quest %u has `CharTitleId` = %u but CharTitle Id %u does not exist, quest can't be rewarded with title.",
3527 qinfo->GetQuestId(),qinfo->GetCharTitleId(),qinfo->GetCharTitleId());
3528 qinfo->CharTitleId = 0;
3529 // quest can't reward this title
3532 if(qinfo->SrcItemId)
3534 if(!sItemStorage.LookupEntry<ItemPrototype>(qinfo->SrcItemId))
3536 sLog.outErrorDb("Quest %u has `SrcItemId` = %u but item with entry %u does not exist, quest can't be done.",
3537 qinfo->GetQuestId(),qinfo->SrcItemId,qinfo->SrcItemId);
3538 qinfo->SrcItemId = 0; // quest can't be done for this requirement
3540 else if(qinfo->SrcItemCount==0)
3542 sLog.outErrorDb("Quest %u has `SrcItemId` = %u but `SrcItemCount` = 0, set to 1 but need fix in DB.",
3543 qinfo->GetQuestId(),qinfo->SrcItemId);
3544 qinfo->SrcItemCount = 1; // update to 1 for allow quest work for backward compatibility with DB
3547 else if(qinfo->SrcItemCount>0)
3549 sLog.outErrorDb("Quest %u has `SrcItemId` = 0 but `SrcItemCount` = %u, useless value.",
3550 qinfo->GetQuestId(),qinfo->SrcItemCount);
3551 qinfo->SrcItemCount=0; // no quest work changes in fact
3554 if(qinfo->SrcSpell)
3556 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->SrcSpell);
3557 if(!spellInfo)
3559 sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u doesn't exist, quest can't be done.",
3560 qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
3561 qinfo->SrcSpell = 0; // quest can't be done for this requirement
3563 else if(!SpellMgr::IsSpellValid(spellInfo))
3565 sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u is broken, quest can't be done.",
3566 qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
3567 qinfo->SrcSpell = 0; // quest can't be done for this requirement
3571 for(int j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j )
3573 uint32 id = qinfo->ReqItemId[j];
3574 if(id)
3576 if(qinfo->ReqItemCount[j] == 0)
3578 sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but `ReqItemCount%d` = 0, quest can't be done.",
3579 qinfo->GetQuestId(), j+1, id, j+1);
3580 // no changes, quest can't be done for this requirement
3583 qinfo->SetFlag(QUEST_MANGOS_FLAGS_DELIVER);
3585 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3587 sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but item with entry %u does not exist, quest can't be done.",
3588 qinfo->GetQuestId(), j+1, id, id);
3589 qinfo->ReqItemCount[j] = 0; // prevent incorrect work of quest
3592 else if(qinfo->ReqItemCount[j] > 0)
3594 sLog.outErrorDb("Quest %u has `ReqItemId%d` = 0 but `ReqItemCount%d` = %u, quest can't be done.",
3595 qinfo->GetQuestId(), j+1, j+1, qinfo->ReqItemCount[j]);
3596 qinfo->ReqItemCount[j] = 0; // prevent incorrect work of quest
3600 for(int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j )
3602 uint32 id = qinfo->ReqSourceId[j];
3603 if(id)
3605 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3607 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but item with entry %u does not exist, quest can't be done.",
3608 qinfo->GetQuestId(),j+1,id,id);
3609 // no changes, quest can't be done for this requirement
3612 else
3614 if(qinfo->ReqSourceCount[j]>0)
3616 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = 0 but `ReqSourceCount%d` = %u.",
3617 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqSourceCount[j]);
3618 // no changes, quest ignore this data
3623 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3625 uint32 id = qinfo->ReqSpell[j];
3626 if(id)
3628 SpellEntry const* spellInfo = sSpellStore.LookupEntry(id);
3629 if(!spellInfo)
3631 sLog.outErrorDb("Quest %u has `ReqSpellCast%d` = %u but spell %u does not exist, quest can't be done.",
3632 qinfo->GetQuestId(),j+1,id,id);
3633 continue;
3636 if(!qinfo->ReqCreatureOrGOId[j])
3638 bool found = false;
3639 for(int k = 0; k < 3; ++k)
3641 if ((spellInfo->Effect[k] == SPELL_EFFECT_QUEST_COMPLETE && uint32(spellInfo->EffectMiscValue[k]) == qinfo->QuestId) ||
3642 spellInfo->Effect[k] == SPELL_EFFECT_SEND_EVENT)
3644 found = true;
3645 break;
3649 if(found)
3651 if(!qinfo->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3653 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);
3655 // this will prevent quest completing without objective
3656 const_cast<Quest*>(qinfo)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3659 else
3661 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.",
3662 qinfo->GetQuestId(),j+1,id,j+1,id);
3663 // no changes, quest can't be done for this requirement
3669 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3671 int32 id = qinfo->ReqCreatureOrGOId[j];
3672 if(id < 0 && !sGOStorage.LookupEntry<GameObjectInfo>(-id))
3674 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but gameobject %u does not exist, quest can't be done.",
3675 qinfo->GetQuestId(),j+1,id,uint32(-id));
3676 qinfo->ReqCreatureOrGOId[j] = 0; // quest can't be done for this requirement
3679 if(id > 0 && !sCreatureStorage.LookupEntry<CreatureInfo>(id))
3681 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but creature with entry %u does not exist, quest can't be done.",
3682 qinfo->GetQuestId(),j+1,id,uint32(id));
3683 qinfo->ReqCreatureOrGOId[j] = 0; // quest can't be done for this requirement
3686 if(id)
3688 // In fact SpeakTo and Kill are quite same: either you can speak to mob:SpeakTo or you can't:Kill/Cast
3690 qinfo->SetFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO);
3692 if(!qinfo->ReqCreatureOrGOCount[j])
3694 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %u but `ReqCreatureOrGOCount%d` = 0, quest can't be done.",
3695 qinfo->GetQuestId(),j+1,id,j+1);
3696 // no changes, quest can be incorrectly done, but we already report this
3699 else if(qinfo->ReqCreatureOrGOCount[j]>0)
3701 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = 0 but `ReqCreatureOrGOCount%d` = %u.",
3702 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqCreatureOrGOCount[j]);
3703 // no changes, quest ignore this data
3707 for(int j = 0; j < QUEST_REWARD_CHOICES_COUNT; ++j )
3709 uint32 id = qinfo->RewChoiceItemId[j];
3710 if(id)
3712 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3714 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3715 qinfo->GetQuestId(),j+1,id,id);
3716 qinfo->RewChoiceItemId[j] = 0; // no changes, quest will not reward this
3719 if(!qinfo->RewChoiceItemCount[j])
3721 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but `RewChoiceItemCount%d` = 0, quest can't be done.",
3722 qinfo->GetQuestId(),j+1,id,j+1);
3723 // no changes, quest can't be done
3726 else if(qinfo->RewChoiceItemCount[j]>0)
3728 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = 0 but `RewChoiceItemCount%d` = %u.",
3729 qinfo->GetQuestId(),j+1,j+1,qinfo->RewChoiceItemCount[j]);
3730 // no changes, quest ignore this data
3734 for(int j = 0; j < QUEST_REWARDS_COUNT; ++j )
3736 uint32 id = qinfo->RewItemId[j];
3737 if(id)
3739 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3741 sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3742 qinfo->GetQuestId(),j+1,id,id);
3743 qinfo->RewItemId[j] = 0; // no changes, quest will not reward this item
3746 if(!qinfo->RewItemCount[j])
3748 sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but `RewItemCount%d` = 0, quest will not reward this item.",
3749 qinfo->GetQuestId(),j+1,id,j+1);
3750 // no changes
3753 else if(qinfo->RewItemCount[j]>0)
3755 sLog.outErrorDb("Quest %u has `RewItemId%d` = 0 but `RewItemCount%d` = %u.",
3756 qinfo->GetQuestId(),j+1,j+1,qinfo->RewItemCount[j]);
3757 // no changes, quest ignore this data
3761 for(int j = 0; j < QUEST_REPUTATIONS_COUNT; ++j)
3763 if(qinfo->RewRepFaction[j])
3765 if(!qinfo->RewRepValue[j])
3767 sLog.outErrorDb("Quest %u has `RewRepFaction%d` = %u but `RewRepValue%d` = 0, quest will not reward this reputation.",
3768 qinfo->GetQuestId(),j+1,qinfo->RewRepValue[j],j+1);
3769 // no changes
3772 if(!sFactionStore.LookupEntry(qinfo->RewRepFaction[j]))
3774 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.",
3775 qinfo->GetQuestId(),j+1,qinfo->RewRepFaction[j] ,qinfo->RewRepFaction[j] );
3776 qinfo->RewRepFaction[j] = 0; // quest will not reward this
3779 else if(qinfo->RewRepValue[j]!=0)
3781 sLog.outErrorDb("Quest %u has `RewRepFaction%d` = 0 but `RewRepValue%d` = %u.",
3782 qinfo->GetQuestId(),j+1,j+1,qinfo->RewRepValue[j]);
3783 // no changes, quest ignore this data
3787 if(qinfo->RewSpell)
3789 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpell);
3791 if(!spellInfo)
3793 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u does not exist, spell removed as display reward.",
3794 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3795 qinfo->RewSpell = 0; // no spell reward will display for this quest
3797 else if(!SpellMgr::IsSpellValid(spellInfo))
3799 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u is broken, quest will not have a spell reward.",
3800 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3801 qinfo->RewSpell = 0; // no spell reward will display for this quest
3803 else if(GetTalentSpellCost(qinfo->RewSpell))
3805 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u is talent, quest will not have a spell reward.",
3806 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3807 qinfo->RewSpell = 0; // no spell reward will display for this quest
3811 if(qinfo->RewSpellCast)
3813 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpellCast);
3815 if(!spellInfo)
3817 sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u does not exist, quest will not have a spell reward.",
3818 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3819 qinfo->RewSpellCast = 0; // no spell will be casted on player
3821 else if(!SpellMgr::IsSpellValid(spellInfo))
3823 sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u is broken, quest will not have a spell reward.",
3824 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3825 qinfo->RewSpellCast = 0; // no spell will be casted on player
3827 else if(GetTalentSpellCost(qinfo->RewSpellCast))
3829 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u is talent, quest will not have a spell reward.",
3830 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3831 qinfo->RewSpellCast = 0; // no spell will be casted on player
3835 if (qinfo->RewMailTemplateId)
3837 if (!sMailTemplateStore.LookupEntry(qinfo->RewMailTemplateId))
3839 sLog.outErrorDb("Quest %u has `RewMailTemplateId` = %u but mail template %u does not exist, quest will not have a mail reward.",
3840 qinfo->GetQuestId(),qinfo->RewMailTemplateId,qinfo->RewMailTemplateId);
3841 qinfo->RewMailTemplateId = 0; // no mail will send to player
3842 qinfo->RewMailDelaySecs = 0; // no mail will send to player
3844 else if (usedMailTemplates.find(qinfo->RewMailTemplateId) != usedMailTemplates.end())
3846 std::map<uint32,uint32>::const_iterator used_mt_itr = usedMailTemplates.find(qinfo->RewMailTemplateId);
3847 sLog.outErrorDb("Quest %u has `RewMailTemplateId` = %u but mail template %u already used for quest %u, quest will not have a mail reward.",
3848 qinfo->GetQuestId(),qinfo->RewMailTemplateId,qinfo->RewMailTemplateId,used_mt_itr->second);
3849 qinfo->RewMailTemplateId = 0; // no mail will send to player
3850 qinfo->RewMailDelaySecs = 0; // no mail will send to player
3852 else
3853 usedMailTemplates[qinfo->RewMailTemplateId] = qinfo->GetQuestId();
3856 if (qinfo->NextQuestInChain)
3858 QuestMap::iterator qNextItr = mQuestTemplates.find(qinfo->NextQuestInChain);
3859 if (qNextItr == mQuestTemplates.end())
3861 sLog.outErrorDb("Quest %u has `NextQuestInChain` = %u but quest %u does not exist, quest chain will not work.",
3862 qinfo->GetQuestId(),qinfo->NextQuestInChain ,qinfo->NextQuestInChain );
3863 qinfo->NextQuestInChain = 0;
3865 else
3866 qNextItr->second->prevChainQuests.push_back(qinfo->GetQuestId());
3869 // fill additional data stores
3870 if (qinfo->PrevQuestId)
3872 if (mQuestTemplates.find(abs(qinfo->GetPrevQuestId())) == mQuestTemplates.end())
3874 sLog.outErrorDb("Quest %d has PrevQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetPrevQuestId());
3876 else
3878 qinfo->prevQuests.push_back(qinfo->PrevQuestId);
3882 if(qinfo->NextQuestId)
3884 QuestMap::iterator qNextItr = mQuestTemplates.find(abs(qinfo->GetNextQuestId()));
3885 if (qNextItr == mQuestTemplates.end())
3887 sLog.outErrorDb("Quest %d has NextQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetNextQuestId());
3889 else
3891 int32 signedQuestId = qinfo->NextQuestId < 0 ? -int32(qinfo->GetQuestId()) : int32(qinfo->GetQuestId());
3892 qNextItr->second->prevQuests.push_back(signedQuestId);
3896 if(qinfo->ExclusiveGroup)
3897 mExclusiveQuestGroups.insert(std::pair<int32, uint32>(qinfo->ExclusiveGroup, qinfo->GetQuestId()));
3898 if(qinfo->LimitTime)
3899 qinfo->SetFlag(QUEST_MANGOS_FLAGS_TIMED);
3902 // check QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT for spell with SPELL_EFFECT_QUEST_COMPLETE
3903 for (uint32 i = 0; i < sSpellStore.GetNumRows(); ++i)
3905 SpellEntry const *spellInfo = sSpellStore.LookupEntry(i);
3906 if(!spellInfo)
3907 continue;
3909 for(int j = 0; j < 3; ++j)
3911 if(spellInfo->Effect[j] != SPELL_EFFECT_QUEST_COMPLETE)
3912 continue;
3914 uint32 quest_id = spellInfo->EffectMiscValue[j];
3916 Quest const* quest = GetQuestTemplate(quest_id);
3918 // some quest referenced in spells not exist (outdated spells)
3919 if(!quest)
3920 continue;
3922 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3924 sLog.outErrorDb("Spell (id: %u) have SPELL_EFFECT_QUEST_COMPLETE for quest %u , but quest not have flag QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT. Quest flags must be fixed, quest modified to enable objective.",spellInfo->Id,quest_id);
3926 // this will prevent quest completing without objective
3927 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3932 sLog.outString();
3933 sLog.outString( ">> Loaded %lu quests definitions", (unsigned long)mQuestTemplates.size() );
3936 void ObjectMgr::LoadQuestLocales()
3938 mQuestLocaleMap.clear(); // need for reload case
3940 QueryResult *result = WorldDatabase.Query("SELECT entry,"
3941 "Title_loc1,Details_loc1,Objectives_loc1,OfferRewardText_loc1,RequestItemsText_loc1,EndText_loc1,ObjectiveText1_loc1,ObjectiveText2_loc1,ObjectiveText3_loc1,ObjectiveText4_loc1,"
3942 "Title_loc2,Details_loc2,Objectives_loc2,OfferRewardText_loc2,RequestItemsText_loc2,EndText_loc2,ObjectiveText1_loc2,ObjectiveText2_loc2,ObjectiveText3_loc2,ObjectiveText4_loc2,"
3943 "Title_loc3,Details_loc3,Objectives_loc3,OfferRewardText_loc3,RequestItemsText_loc3,EndText_loc3,ObjectiveText1_loc3,ObjectiveText2_loc3,ObjectiveText3_loc3,ObjectiveText4_loc3,"
3944 "Title_loc4,Details_loc4,Objectives_loc4,OfferRewardText_loc4,RequestItemsText_loc4,EndText_loc4,ObjectiveText1_loc4,ObjectiveText2_loc4,ObjectiveText3_loc4,ObjectiveText4_loc4,"
3945 "Title_loc5,Details_loc5,Objectives_loc5,OfferRewardText_loc5,RequestItemsText_loc5,EndText_loc5,ObjectiveText1_loc5,ObjectiveText2_loc5,ObjectiveText3_loc5,ObjectiveText4_loc5,"
3946 "Title_loc6,Details_loc6,Objectives_loc6,OfferRewardText_loc6,RequestItemsText_loc6,EndText_loc6,ObjectiveText1_loc6,ObjectiveText2_loc6,ObjectiveText3_loc6,ObjectiveText4_loc6,"
3947 "Title_loc7,Details_loc7,Objectives_loc7,OfferRewardText_loc7,RequestItemsText_loc7,EndText_loc7,ObjectiveText1_loc7,ObjectiveText2_loc7,ObjectiveText3_loc7,ObjectiveText4_loc7,"
3948 "Title_loc8,Details_loc8,Objectives_loc8,OfferRewardText_loc8,RequestItemsText_loc8,EndText_loc8,ObjectiveText1_loc8,ObjectiveText2_loc8,ObjectiveText3_loc8,ObjectiveText4_loc8"
3949 " FROM locales_quest"
3952 if(!result)
3954 barGoLink bar(1);
3956 bar.step();
3958 sLog.outString();
3959 sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_quest` is empty.");
3960 return;
3963 barGoLink bar(result->GetRowCount());
3967 Field *fields = result->Fetch();
3968 bar.step();
3970 uint32 entry = fields[0].GetUInt32();
3972 QuestLocale& data = mQuestLocaleMap[entry];
3974 for(int i = 1; i < MAX_LOCALE; ++i)
3976 std::string str = fields[1+10*(i-1)].GetCppString();
3977 if(!str.empty())
3979 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3980 if(idx >= 0)
3982 if(data.Title.size() <= idx)
3983 data.Title.resize(idx+1);
3985 data.Title[idx] = str;
3988 str = fields[1+10*(i-1)+1].GetCppString();
3989 if(!str.empty())
3991 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3992 if(idx >= 0)
3994 if(data.Details.size() <= idx)
3995 data.Details.resize(idx+1);
3997 data.Details[idx] = str;
4000 str = fields[1+10*(i-1)+2].GetCppString();
4001 if(!str.empty())
4003 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4004 if(idx >= 0)
4006 if(data.Objectives.size() <= idx)
4007 data.Objectives.resize(idx+1);
4009 data.Objectives[idx] = str;
4012 str = fields[1+10*(i-1)+3].GetCppString();
4013 if(!str.empty())
4015 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4016 if(idx >= 0)
4018 if(data.OfferRewardText.size() <= idx)
4019 data.OfferRewardText.resize(idx+1);
4021 data.OfferRewardText[idx] = str;
4024 str = fields[1+10*(i-1)+4].GetCppString();
4025 if(!str.empty())
4027 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4028 if(idx >= 0)
4030 if(data.RequestItemsText.size() <= idx)
4031 data.RequestItemsText.resize(idx+1);
4033 data.RequestItemsText[idx] = str;
4036 str = fields[1+10*(i-1)+5].GetCppString();
4037 if(!str.empty())
4039 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4040 if(idx >= 0)
4042 if(data.EndText.size() <= idx)
4043 data.EndText.resize(idx+1);
4045 data.EndText[idx] = str;
4048 for(int k = 0; k < 4; ++k)
4050 str = fields[1+10*(i-1)+6+k].GetCppString();
4051 if(!str.empty())
4053 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4054 if(idx >= 0)
4056 if(data.ObjectiveText[k].size() <= idx)
4057 data.ObjectiveText[k].resize(idx+1);
4059 data.ObjectiveText[k][idx] = str;
4064 } while (result->NextRow());
4066 delete result;
4068 sLog.outString();
4069 sLog.outString( ">> Loaded %lu Quest locale strings", (unsigned long)mQuestLocaleMap.size() );
4072 void ObjectMgr::LoadScripts(ScriptMapMap& scripts, char const* tablename)
4074 if(sWorld.IsScriptScheduled()) // function don't must be called in time scripts use.
4075 return;
4077 sLog.outString( "%s :", tablename);
4079 scripts.clear(); // need for reload support
4081 QueryResult *result = WorldDatabase.PQuery( "SELECT id,delay,command,datalong,datalong2,dataint, x, y, z, o FROM %s", tablename );
4083 uint32 count = 0;
4085 if( !result )
4087 barGoLink bar( 1 );
4088 bar.step();
4090 sLog.outString();
4091 sLog.outString( ">> Loaded %u script definitions", count );
4092 return;
4095 barGoLink bar( result->GetRowCount() );
4099 bar.step();
4101 Field *fields = result->Fetch();
4102 ScriptInfo tmp;
4103 tmp.id = fields[0].GetUInt32();
4104 tmp.delay = fields[1].GetUInt32();
4105 tmp.command = fields[2].GetUInt32();
4106 tmp.datalong = fields[3].GetUInt32();
4107 tmp.datalong2 = fields[4].GetUInt32();
4108 tmp.dataint = fields[5].GetInt32();
4109 tmp.x = fields[6].GetFloat();
4110 tmp.y = fields[7].GetFloat();
4111 tmp.z = fields[8].GetFloat();
4112 tmp.o = fields[9].GetFloat();
4114 // generic command args check
4115 switch(tmp.command)
4117 case SCRIPT_COMMAND_TALK:
4119 if(tmp.datalong > 3)
4121 sLog.outErrorDb("Table `%s` has invalid talk type (datalong = %u) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.datalong,tmp.id);
4122 continue;
4124 if(tmp.dataint==0)
4126 sLog.outErrorDb("Table `%s` has invalid talk text id (dataint = %i) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.dataint,tmp.id);
4127 continue;
4129 if(tmp.dataint < MIN_DB_SCRIPT_STRING_ID || tmp.dataint >= MAX_DB_SCRIPT_STRING_ID)
4131 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);
4132 continue;
4135 // if(!GetMangosStringLocale(tmp.dataint)) will checked after db_script_string loading
4136 break;
4139 case SCRIPT_COMMAND_EMOTE:
4141 if(!sEmotesStore.LookupEntry(tmp.datalong))
4143 sLog.outErrorDb("Table `%s` has invalid emote id (datalong = %u) in SCRIPT_COMMAND_EMOTE for script id %u",tablename,tmp.datalong,tmp.id);
4144 continue;
4146 break;
4149 case SCRIPT_COMMAND_TELEPORT_TO:
4151 if(!sMapStore.LookupEntry(tmp.datalong))
4153 sLog.outErrorDb("Table `%s` has invalid map (Id: %u) in SCRIPT_COMMAND_TELEPORT_TO for script id %u",tablename,tmp.datalong,tmp.id);
4154 continue;
4157 if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
4159 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);
4160 continue;
4162 break;
4165 case SCRIPT_COMMAND_KILL_CREDIT:
4167 if (!GetCreatureTemplate(tmp.datalong))
4169 sLog.outErrorDb("Table `%s` has invalid creature (Entry: %u) in SCRIPT_COMMAND_KILL_CREDIT for script id %u",tablename,tmp.datalong,tmp.id);
4170 continue;
4172 break;
4175 case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
4177 if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
4179 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);
4180 continue;
4183 if(!GetCreatureTemplate(tmp.datalong))
4185 sLog.outErrorDb("Table `%s` has invalid creature (Entry: %u) in SCRIPT_COMMAND_TEMP_SUMMON_CREATURE for script id %u",tablename,tmp.datalong,tmp.id);
4186 continue;
4188 break;
4191 case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
4193 GameObjectData const* data = GetGOData(tmp.datalong);
4194 if(!data)
4196 sLog.outErrorDb("Table `%s` has invalid gameobject (GUID: %u) in SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,tmp.datalong,tmp.id);
4197 continue;
4200 GameObjectInfo const* info = GetGameObjectInfo(data->id);
4201 if(!info)
4203 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);
4204 continue;
4207 if( info->type==GAMEOBJECT_TYPE_FISHINGNODE ||
4208 info->type==GAMEOBJECT_TYPE_FISHINGHOLE ||
4209 info->type==GAMEOBJECT_TYPE_DOOR ||
4210 info->type==GAMEOBJECT_TYPE_BUTTON ||
4211 info->type==GAMEOBJECT_TYPE_TRAP )
4213 sLog.outErrorDb("Table `%s` have gameobject type (%u) unsupported by command SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,info->id,tmp.id);
4214 continue;
4216 break;
4218 case SCRIPT_COMMAND_OPEN_DOOR:
4219 case SCRIPT_COMMAND_CLOSE_DOOR:
4221 GameObjectData const* data = GetGOData(tmp.datalong);
4222 if(!data)
4224 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);
4225 continue;
4228 GameObjectInfo const* info = GetGameObjectInfo(data->id);
4229 if(!info)
4231 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);
4232 continue;
4235 if( info->type!=GAMEOBJECT_TYPE_DOOR)
4237 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);
4238 continue;
4241 break;
4243 case SCRIPT_COMMAND_QUEST_EXPLORED:
4245 Quest const* quest = GetQuestTemplate(tmp.datalong);
4246 if(!quest)
4248 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);
4249 continue;
4252 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
4254 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);
4256 // this will prevent quest completing without objective
4257 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
4259 // continue; - quest objective requirement set and command can be allowed
4262 if(float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
4264 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",
4265 tablename,tmp.datalong2,tmp.id);
4266 continue;
4269 if(tmp.datalong2 && float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
4271 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",
4272 tablename,tmp.datalong2,tmp.id,DEFAULT_VISIBILITY_DISTANCE);
4273 continue;
4276 if(tmp.datalong2 && float(tmp.datalong2) < INTERACTION_DISTANCE)
4278 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",
4279 tablename,tmp.datalong2,tmp.id,INTERACTION_DISTANCE);
4280 continue;
4283 break;
4286 case SCRIPT_COMMAND_REMOVE_AURA:
4288 if(!sSpellStore.LookupEntry(tmp.datalong))
4290 sLog.outErrorDb("Table `%s` using non-existent spell (id: %u) in SCRIPT_COMMAND_REMOVE_AURA or SCRIPT_COMMAND_CAST_SPELL for script id %u",
4291 tablename,tmp.datalong,tmp.id);
4292 continue;
4294 if(tmp.datalong2 & ~0x1) // 1 bits (0,1)
4296 sLog.outErrorDb("Table `%s` using unknown flags in datalong2 (%u)i n SCRIPT_COMMAND_CAST_SPELL for script id %u",
4297 tablename,tmp.datalong2,tmp.id);
4298 continue;
4300 break;
4302 case SCRIPT_COMMAND_CAST_SPELL:
4304 if(!sSpellStore.LookupEntry(tmp.datalong))
4306 sLog.outErrorDb("Table `%s` using non-existent spell (id: %u) in SCRIPT_COMMAND_REMOVE_AURA or SCRIPT_COMMAND_CAST_SPELL for script id %u",
4307 tablename,tmp.datalong,tmp.id);
4308 continue;
4310 if(tmp.datalong2 & ~0x3) // 2 bits
4312 sLog.outErrorDb("Table `%s` using unknown flags in datalong2 (%u)i n SCRIPT_COMMAND_CAST_SPELL for script id %u",
4313 tablename,tmp.datalong2,tmp.id);
4314 continue;
4316 break;
4320 if (scripts.find(tmp.id) == scripts.end())
4322 ScriptMap emptyMap;
4323 scripts[tmp.id] = emptyMap;
4325 scripts[tmp.id].insert(std::pair<uint32, ScriptInfo>(tmp.delay, tmp));
4327 ++count;
4328 } while( result->NextRow() );
4330 delete result;
4332 sLog.outString();
4333 sLog.outString( ">> Loaded %u script definitions", count );
4336 void ObjectMgr::LoadGameObjectScripts()
4338 LoadScripts(sGameObjectScripts, "gameobject_scripts");
4340 // check ids
4341 for(ScriptMapMap::const_iterator itr = sGameObjectScripts.begin(); itr != sGameObjectScripts.end(); ++itr)
4343 if(!GetGOData(itr->first))
4344 sLog.outErrorDb("Table `gameobject_scripts` has not existing gameobject (GUID: %u) as script id",itr->first);
4348 void ObjectMgr::LoadQuestEndScripts()
4350 LoadScripts(sQuestEndScripts, "quest_end_scripts");
4352 // check ids
4353 for(ScriptMapMap::const_iterator itr = sQuestEndScripts.begin(); itr != sQuestEndScripts.end(); ++itr)
4355 if(!GetQuestTemplate(itr->first))
4356 sLog.outErrorDb("Table `quest_end_scripts` has not existing quest (Id: %u) as script id",itr->first);
4360 void ObjectMgr::LoadQuestStartScripts()
4362 LoadScripts(sQuestStartScripts,"quest_start_scripts");
4364 // check ids
4365 for(ScriptMapMap::const_iterator itr = sQuestStartScripts.begin(); itr != sQuestStartScripts.end(); ++itr)
4367 if(!GetQuestTemplate(itr->first))
4368 sLog.outErrorDb("Table `quest_start_scripts` has not existing quest (Id: %u) as script id",itr->first);
4372 void ObjectMgr::LoadSpellScripts()
4374 LoadScripts(sSpellScripts, "spell_scripts");
4376 // check ids
4377 for(ScriptMapMap::const_iterator itr = sSpellScripts.begin(); itr != sSpellScripts.end(); ++itr)
4379 SpellEntry const* spellInfo = sSpellStore.LookupEntry(itr->first);
4381 if(!spellInfo)
4383 sLog.outErrorDb("Table `spell_scripts` has not existing spell (Id: %u) as script id",itr->first);
4384 continue;
4387 //check for correct spellEffect
4388 bool found = false;
4389 for(int i=0; i<3; ++i)
4391 // skip empty effects
4392 if( !spellInfo->Effect[i] )
4393 continue;
4395 if( spellInfo->Effect[i] == SPELL_EFFECT_SCRIPT_EFFECT )
4397 found = true;
4398 break;
4402 if(!found)
4403 sLog.outErrorDb("Table `spell_scripts` has unsupported spell (Id: %u) without SPELL_EFFECT_SCRIPT_EFFECT (%u) spell effect",itr->first,SPELL_EFFECT_SCRIPT_EFFECT);
4407 void ObjectMgr::LoadEventScripts()
4409 LoadScripts(sEventScripts, "event_scripts");
4411 std::set<uint32> evt_scripts;
4412 // Load all possible script entries from gameobjects
4413 for(uint32 i = 1; i < sGOStorage.MaxEntry; ++i)
4415 GameObjectInfo const * goInfo = sGOStorage.LookupEntry<GameObjectInfo>(i);
4416 if (goInfo)
4418 switch(goInfo->type)
4420 case GAMEOBJECT_TYPE_GOOBER:
4421 if (goInfo->goober.eventId)
4422 evt_scripts.insert(goInfo->goober.eventId);
4423 break;
4424 case GAMEOBJECT_TYPE_CHEST:
4425 if (goInfo->chest.eventId)
4426 evt_scripts.insert(goInfo->chest.eventId);
4427 break;
4428 case GAMEOBJECT_TYPE_CAMERA:
4429 if (goInfo->camera.eventID)
4430 evt_scripts.insert(goInfo->camera.eventID);
4431 default:
4432 break;
4436 // Load all possible script entries from spells
4437 for(uint32 i = 1; i < sSpellStore.GetNumRows(); ++i)
4439 SpellEntry const * spell = sSpellStore.LookupEntry(i);
4440 if (spell)
4442 for(int j=0; j<3; ++j)
4444 if( spell->Effect[j] == SPELL_EFFECT_SEND_EVENT )
4446 if (spell->EffectMiscValue[j])
4447 evt_scripts.insert(spell->EffectMiscValue[j]);
4452 // Then check if all scripts are in above list of possible script entries
4453 for(ScriptMapMap::const_iterator itr = sEventScripts.begin(); itr != sEventScripts.end(); ++itr)
4455 std::set<uint32>::const_iterator itr2 = evt_scripts.find(itr->first);
4456 if (itr2 == evt_scripts.end())
4457 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",
4458 itr->first, SPELL_EFFECT_SEND_EVENT);
4462 void ObjectMgr::LoadGossipScripts()
4464 LoadScripts(sGossipScripts, "gossip_scripts");
4466 // checks are done in LoadGossipMenuItems
4469 void ObjectMgr::LoadItemTexts()
4471 QueryResult *result = CharacterDatabase.Query("SELECT id, text FROM item_text");
4473 uint32 count = 0;
4475 if( !result )
4477 barGoLink bar( 1 );
4478 bar.step();
4480 sLog.outString();
4481 sLog.outString( ">> Loaded %u item pages", count );
4482 return;
4485 barGoLink bar( result->GetRowCount() );
4487 Field* fields;
4490 bar.step();
4492 fields = result->Fetch();
4494 mItemTexts[ fields[0].GetUInt32() ] = fields[1].GetCppString();
4496 ++count;
4498 } while ( result->NextRow() );
4500 delete result;
4502 sLog.outString();
4503 sLog.outString( ">> Loaded %u item texts", count );
4506 void ObjectMgr::LoadPageTexts()
4508 sPageTextStore.Free(); // for reload case
4510 sPageTextStore.Load();
4511 sLog.outString( ">> Loaded %u page texts", sPageTextStore.RecordCount );
4512 sLog.outString();
4514 for(uint32 i = 1; i < sPageTextStore.MaxEntry; ++i)
4516 // check data correctness
4517 PageText const* page = sPageTextStore.LookupEntry<PageText>(i);
4518 if(!page)
4519 continue;
4521 if(page->Next_Page && !sPageTextStore.LookupEntry<PageText>(page->Next_Page))
4523 sLog.outErrorDb("Page text (Id: %u) has not existing next page (Id:%u)", i,page->Next_Page);
4524 continue;
4527 // detect circular reference
4528 std::set<uint32> checkedPages;
4529 for(PageText const* pageItr = page; pageItr; pageItr = sPageTextStore.LookupEntry<PageText>(pageItr->Next_Page))
4531 if(!pageItr->Next_Page)
4532 break;
4533 checkedPages.insert(pageItr->Page_ID);
4534 if(checkedPages.find(pageItr->Next_Page)!=checkedPages.end())
4536 std::ostringstream ss;
4537 ss<< "The text page(s) ";
4538 for (std::set<uint32>::iterator itr= checkedPages.begin();itr!=checkedPages.end(); ++itr)
4539 ss << *itr << " ";
4540 ss << "create(s) a circular reference, which can cause the server to freeze. Changing Next_Page of page "
4541 << pageItr->Page_ID <<" to 0";
4542 sLog.outErrorDb("%s", ss.str().c_str());
4543 const_cast<PageText*>(pageItr)->Next_Page = 0;
4544 break;
4550 void ObjectMgr::LoadPageTextLocales()
4552 mPageTextLocaleMap.clear(); // need for reload case
4554 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");
4556 if(!result)
4558 barGoLink bar(1);
4560 bar.step();
4562 sLog.outString();
4563 sLog.outString(">> Loaded 0 PageText locale strings. DB table `locales_page_text` is empty.");
4564 return;
4567 barGoLink bar(result->GetRowCount());
4571 Field *fields = result->Fetch();
4572 bar.step();
4574 uint32 entry = fields[0].GetUInt32();
4576 PageTextLocale& data = mPageTextLocaleMap[entry];
4578 for(int i = 1; i < MAX_LOCALE; ++i)
4580 std::string str = fields[i].GetCppString();
4581 if(str.empty())
4582 continue;
4584 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4585 if(idx >= 0)
4587 if(data.Text.size() <= idx)
4588 data.Text.resize(idx+1);
4590 data.Text[idx] = str;
4594 } while (result->NextRow());
4596 delete result;
4598 sLog.outString();
4599 sLog.outString( ">> Loaded %lu PageText locale strings", (unsigned long)mPageTextLocaleMap.size() );
4602 struct SQLInstanceLoader : public SQLStorageLoaderBase<SQLInstanceLoader>
4604 template<class D>
4605 void convert_from_str(uint32 /*field_pos*/, char *src, D &dst)
4607 dst = D(sObjectMgr.GetScriptId(src));
4611 void ObjectMgr::LoadInstanceTemplate()
4613 SQLInstanceLoader loader;
4614 loader.Load(sInstanceTemplate);
4616 for(uint32 i = 0; i < sInstanceTemplate.MaxEntry; i++)
4618 InstanceTemplate* temp = (InstanceTemplate*)GetInstanceTemplate(i);
4619 if(!temp)
4620 continue;
4622 if(!MapManager::IsValidMAP(temp->map))
4623 sLog.outErrorDb("ObjectMgr::LoadInstanceTemplate: bad mapid %d for template!", temp->map);
4625 if(!MapManager::IsValidMapCoord(temp->parent,temp->startLocX,temp->startLocY,temp->startLocZ,temp->startLocO))
4627 sLog.outErrorDb("ObjectMgr::LoadInstanceTemplate: bad parent entrance coordinates for map id %d template!", temp->map);
4628 temp->parent = 0; // will have wrong continent 0 parent, at least existed
4632 sLog.outString( ">> Loaded %u Instance Template definitions", sInstanceTemplate.RecordCount );
4633 sLog.outString();
4636 GossipText const *ObjectMgr::GetGossipText(uint32 Text_ID) const
4638 GossipTextMap::const_iterator itr = mGossipText.find(Text_ID);
4639 if(itr != mGossipText.end())
4640 return &itr->second;
4641 return NULL;
4644 void ObjectMgr::LoadGossipText()
4646 QueryResult *result = WorldDatabase.Query( "SELECT * FROM npc_text" );
4648 int count = 0;
4649 if( !result )
4651 barGoLink bar( 1 );
4652 bar.step();
4654 sLog.outString();
4655 sLog.outString( ">> Loaded %u npc texts", count );
4656 return;
4659 int cic;
4661 barGoLink bar( result->GetRowCount() );
4665 ++count;
4666 cic = 0;
4668 Field *fields = result->Fetch();
4670 bar.step();
4672 uint32 Text_ID = fields[cic++].GetUInt32();
4673 if(!Text_ID)
4675 sLog.outErrorDb("Table `npc_text` has record wit reserved id 0, ignore.");
4676 continue;
4679 GossipText& gText = mGossipText[Text_ID];
4681 for (int i=0; i< 8; i++)
4683 gText.Options[i].Text_0 = fields[cic++].GetCppString();
4684 gText.Options[i].Text_1 = fields[cic++].GetCppString();
4686 gText.Options[i].Language = fields[cic++].GetUInt32();
4687 gText.Options[i].Probability = fields[cic++].GetFloat();
4689 for(int j=0; j < 3; ++j)
4691 gText.Options[i].Emotes[j]._Delay = fields[cic++].GetUInt32();
4692 gText.Options[i].Emotes[j]._Emote = fields[cic++].GetUInt32();
4695 } while( result->NextRow() );
4697 sLog.outString();
4698 sLog.outString( ">> Loaded %u npc texts", count );
4699 delete result;
4702 void ObjectMgr::LoadNpcTextLocales()
4704 mNpcTextLocaleMap.clear(); // need for reload case
4706 QueryResult *result = WorldDatabase.Query("SELECT entry,"
4707 "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,"
4708 "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,"
4709 "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,"
4710 "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,"
4711 "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,"
4712 "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,"
4713 "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, "
4714 "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 "
4715 " FROM locales_npc_text");
4717 if(!result)
4719 barGoLink bar(1);
4721 bar.step();
4723 sLog.outString();
4724 sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_npc_text` is empty.");
4725 return;
4728 barGoLink bar(result->GetRowCount());
4732 Field *fields = result->Fetch();
4733 bar.step();
4735 uint32 entry = fields[0].GetUInt32();
4737 NpcTextLocale& data = mNpcTextLocaleMap[entry];
4739 for(int i=1; i<MAX_LOCALE; ++i)
4741 for(int j=0; j<8; ++j)
4743 std::string str0 = fields[1+8*2*(i-1)+2*j].GetCppString();
4744 if(!str0.empty())
4746 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4747 if(idx >= 0)
4749 if(data.Text_0[j].size() <= idx)
4750 data.Text_0[j].resize(idx+1);
4752 data.Text_0[j][idx] = str0;
4755 std::string str1 = fields[1+8*2*(i-1)+2*j+1].GetCppString();
4756 if(!str1.empty())
4758 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4759 if(idx >= 0)
4761 if(data.Text_1[j].size() <= idx)
4762 data.Text_1[j].resize(idx+1);
4764 data.Text_1[j][idx] = str1;
4769 } while (result->NextRow());
4771 delete result;
4773 sLog.outString();
4774 sLog.outString( ">> Loaded %lu NpcText locale strings", (unsigned long)mNpcTextLocaleMap.size() );
4777 //not very fast function but it is called only once a day, or on starting-up
4778 void ObjectMgr::ReturnOrDeleteOldMails(bool serverUp)
4780 time_t basetime = time(NULL);
4781 sLog.outDebug("Returning mails current time: hour: %d, minute: %d, second: %d ", localtime(&basetime)->tm_hour, localtime(&basetime)->tm_min, localtime(&basetime)->tm_sec);
4782 //delete all old mails without item and without body immediately, if starting server
4783 if (!serverUp)
4784 CharacterDatabase.PExecute("DELETE FROM mail WHERE expire_time < '" UI64FMTD "' AND has_items = '0' AND itemTextId = 0", (uint64)basetime);
4785 // 0 1 2 3 4 5 6 7 8 9
4786 QueryResult* result = CharacterDatabase.PQuery("SELECT id,messageType,sender,receiver,itemTextId,has_items,expire_time,cod,checked,mailTemplateId FROM mail WHERE expire_time < '" UI64FMTD "'", (uint64)basetime);
4787 if ( !result )
4789 barGoLink bar(1);
4790 bar.step();
4791 sLog.outString();
4792 sLog.outString(">> Only expired mails (need to be return or delete) or DB table `mail` is empty.");
4793 return; // any mails need to be returned or deleted
4796 //std::ostringstream delitems, delmails; //will be here for optimization
4797 //bool deletemail = false, deleteitem = false;
4798 //delitems << "DELETE FROM item_instance WHERE guid IN ( ";
4799 //delmails << "DELETE FROM mail WHERE id IN ( "
4801 barGoLink bar( result->GetRowCount() );
4802 uint32 count = 0;
4803 Field *fields;
4807 bar.step();
4809 fields = result->Fetch();
4810 Mail *m = new Mail;
4811 m->messageID = fields[0].GetUInt32();
4812 m->messageType = fields[1].GetUInt8();
4813 m->sender = fields[2].GetUInt32();
4814 m->receiver = fields[3].GetUInt32();
4815 m->itemTextId = fields[4].GetUInt32();
4816 bool has_items = fields[5].GetBool();
4817 m->expire_time = (time_t)fields[6].GetUInt64();
4818 m->deliver_time = 0;
4819 m->COD = fields[7].GetUInt32();
4820 m->checked = fields[8].GetUInt32();
4821 m->mailTemplateId = fields[9].GetInt16();
4823 Player *pl = 0;
4824 if (serverUp)
4825 pl = GetPlayer((uint64)m->receiver);
4826 if (pl)
4827 { //this code will run very improbably (the time is between 4 and 5 am, in game is online a player, who has old mail
4828 //his in mailbox and he has already listed his mails )
4829 delete m;
4830 continue;
4832 //delete or return mail:
4833 if (has_items)
4835 QueryResult *resultItems = CharacterDatabase.PQuery("SELECT item_guid,item_template FROM mail_items WHERE mail_id='%u'", m->messageID);
4836 if(resultItems)
4840 Field *fields2 = resultItems->Fetch();
4842 uint32 item_guid_low = fields2[0].GetUInt32();
4843 uint32 item_template = fields2[1].GetUInt32();
4845 m->AddItem(item_guid_low, item_template);
4847 while (resultItems->NextRow());
4849 delete resultItems;
4851 //if it is mail from AH, it shouldn't be returned, but deleted
4852 if (m->messageType != MAIL_NORMAL || (m->checked & (MAIL_CHECK_MASK_AUCTION | MAIL_CHECK_MASK_COD_PAYMENT | MAIL_CHECK_MASK_RETURNED)))
4854 // mail open and then not returned
4855 for(std::vector<MailItemInfo>::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
4856 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
4858 else
4860 //mail will be returned:
4861 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);
4862 delete m;
4863 continue;
4867 if (m->itemTextId)
4868 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
4870 //deletemail = true;
4871 //delmails << m->messageID << ", ";
4872 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
4873 delete m;
4874 ++count;
4875 } while (result->NextRow());
4876 delete result;
4878 sLog.outString();
4879 sLog.outString( ">> Loaded %u mails", count );
4882 void ObjectMgr::LoadQuestAreaTriggers()
4884 mQuestAreaTriggerMap.clear(); // need for reload case
4886 QueryResult *result = WorldDatabase.Query( "SELECT id,quest FROM areatrigger_involvedrelation" );
4888 uint32 count = 0;
4890 if( !result )
4892 barGoLink bar( 1 );
4893 bar.step();
4895 sLog.outString();
4896 sLog.outString( ">> Loaded %u quest trigger points", count );
4897 return;
4900 barGoLink bar( result->GetRowCount() );
4904 ++count;
4905 bar.step();
4907 Field *fields = result->Fetch();
4909 uint32 trigger_ID = fields[0].GetUInt32();
4910 uint32 quest_ID = fields[1].GetUInt32();
4912 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(trigger_ID);
4913 if(!atEntry)
4915 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",trigger_ID);
4916 continue;
4919 Quest const* quest = GetQuestTemplate(quest_ID);
4921 if(!quest)
4923 sLog.outErrorDb("Table `areatrigger_involvedrelation` has record (id: %u) for not existing quest %u",trigger_ID,quest_ID);
4924 continue;
4927 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
4929 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);
4931 // this will prevent quest completing without objective
4932 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
4934 // continue; - quest modified to required objective and trigger can be allowed.
4937 mQuestAreaTriggerMap[trigger_ID] = quest_ID;
4939 } while( result->NextRow() );
4941 delete result;
4943 sLog.outString();
4944 sLog.outString( ">> Loaded %u quest trigger points", count );
4947 void ObjectMgr::LoadTavernAreaTriggers()
4949 mTavernAreaTriggerSet.clear(); // need for reload case
4951 QueryResult *result = WorldDatabase.Query("SELECT id FROM areatrigger_tavern");
4953 uint32 count = 0;
4955 if( !result )
4957 barGoLink bar( 1 );
4958 bar.step();
4960 sLog.outString();
4961 sLog.outString( ">> Loaded %u tavern triggers", count );
4962 return;
4965 barGoLink bar( result->GetRowCount() );
4969 ++count;
4970 bar.step();
4972 Field *fields = result->Fetch();
4974 uint32 Trigger_ID = fields[0].GetUInt32();
4976 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4977 if(!atEntry)
4979 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4980 continue;
4983 mTavernAreaTriggerSet.insert(Trigger_ID);
4984 } while( result->NextRow() );
4986 delete result;
4988 sLog.outString();
4989 sLog.outString( ">> Loaded %u tavern triggers", count );
4992 void ObjectMgr::LoadAreaTriggerScripts()
4994 mAreaTriggerScripts.clear(); // need for reload case
4995 QueryResult *result = WorldDatabase.Query("SELECT entry, ScriptName FROM areatrigger_scripts");
4997 uint32 count = 0;
4999 if( !result )
5001 barGoLink bar( 1 );
5002 bar.step();
5004 sLog.outString();
5005 sLog.outString( ">> Loaded %u areatrigger scripts", count );
5006 return;
5009 barGoLink bar( result->GetRowCount() );
5013 ++count;
5014 bar.step();
5016 Field *fields = result->Fetch();
5018 uint32 Trigger_ID = fields[0].GetUInt32();
5019 const char *scriptName = fields[1].GetString();
5021 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
5022 if(!atEntry)
5024 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
5025 continue;
5027 mAreaTriggerScripts[Trigger_ID] = GetScriptId(scriptName);
5028 } while( result->NextRow() );
5030 delete result;
5032 sLog.outString();
5033 sLog.outString( ">> Loaded %u areatrigger scripts", count );
5036 uint32 ObjectMgr::GetNearestTaxiNode( float x, float y, float z, uint32 mapid, uint32 team )
5038 bool found = false;
5039 float dist;
5040 uint32 id = 0;
5042 for(uint32 i = 1; i < sTaxiNodesStore.GetNumRows(); ++i)
5044 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(i);
5045 if(!node || node->map_id != mapid || !node->MountCreatureID[team == ALLIANCE ? 1 : 0])
5046 continue;
5048 uint8 field = (uint8)((i - 1) / 32);
5049 uint32 submask = 1<<((i-1)%32);
5051 // skip not taxi network nodes
5052 if((sTaxiNodesMask[field] & submask)==0)
5053 continue;
5055 float dist2 = (node->x - x)*(node->x - x)+(node->y - y)*(node->y - y)+(node->z - z)*(node->z - z);
5056 if(found)
5058 if(dist2 < dist)
5060 dist = dist2;
5061 id = i;
5064 else
5066 found = true;
5067 dist = dist2;
5068 id = i;
5072 return id;
5075 void ObjectMgr::GetTaxiPath( uint32 source, uint32 destination, uint32 &path, uint32 &cost)
5077 TaxiPathSetBySource::iterator src_i = sTaxiPathSetBySource.find(source);
5078 if(src_i==sTaxiPathSetBySource.end())
5080 path = 0;
5081 cost = 0;
5082 return;
5085 TaxiPathSetForSource& pathSet = src_i->second;
5087 TaxiPathSetForSource::iterator dest_i = pathSet.find(destination);
5088 if(dest_i==pathSet.end())
5090 path = 0;
5091 cost = 0;
5092 return;
5095 cost = dest_i->second.price;
5096 path = dest_i->second.ID;
5099 uint32 ObjectMgr::GetTaxiMountDisplayId( uint32 id, uint32 team, bool allowed_alt_team /* = false */)
5101 uint16 mount_entry = 0;
5103 // select mount creature id
5104 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(id);
5105 if(node)
5107 if (team == ALLIANCE)
5109 mount_entry = node->MountCreatureID[1];
5110 if(!mount_entry && allowed_alt_team)
5111 mount_entry = node->MountCreatureID[0];
5113 else if (team == HORDE)
5115 mount_entry = node->MountCreatureID[0];
5117 if(!mount_entry && allowed_alt_team)
5118 mount_entry = node->MountCreatureID[1];
5122 CreatureInfo const *mount_info = GetCreatureTemplate(mount_entry);
5123 if (!mount_info)
5124 return 0;
5126 uint16 mount_id = ChooseDisplayId(team,mount_info);
5127 if (!mount_id)
5128 return 0;
5130 CreatureModelInfo const *minfo = GetCreatureModelRandomGender(mount_id);
5131 if (minfo)
5132 mount_id = minfo->modelid;
5134 return mount_id;
5137 void ObjectMgr::GetTaxiPathNodes( uint32 path, Path &pathnodes, std::vector<uint32>& mapIds)
5139 if(path >= sTaxiPathNodesByPath.size())
5140 return;
5142 TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
5144 pathnodes.Resize(nodeList.size());
5145 mapIds.resize(nodeList.size());
5147 for(size_t i = 0; i < nodeList.size(); ++i)
5149 pathnodes[ i ].x = nodeList[i].x;
5150 pathnodes[ i ].y = nodeList[i].y;
5151 pathnodes[ i ].z = nodeList[i].z;
5153 mapIds[i] = nodeList[i].mapid;
5157 void ObjectMgr::GetTransportPathNodes( uint32 path, TransportPath &pathnodes )
5159 if(path >= sTaxiPathNodesByPath.size())
5160 return;
5162 TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
5164 pathnodes.Resize(nodeList.size());
5166 for(size_t i = 0; i < nodeList.size(); ++i)
5168 pathnodes[ i ].mapid = nodeList[i].mapid;
5169 pathnodes[ i ].x = nodeList[i].x;
5170 pathnodes[ i ].y = nodeList[i].y;
5171 pathnodes[ i ].z = nodeList[i].z;
5172 pathnodes[ i ].actionFlag = nodeList[i].actionFlag;
5173 pathnodes[ i ].delay = nodeList[i].delay;
5177 void ObjectMgr::LoadGraveyardZones()
5179 mGraveYardMap.clear(); // need for reload case
5181 QueryResult *result = WorldDatabase.Query("SELECT id,ghost_zone,faction FROM game_graveyard_zone");
5183 uint32 count = 0;
5185 if( !result )
5187 barGoLink bar( 1 );
5188 bar.step();
5190 sLog.outString();
5191 sLog.outString( ">> Loaded %u graveyard-zone links", count );
5192 return;
5195 barGoLink bar( result->GetRowCount() );
5199 ++count;
5200 bar.step();
5202 Field *fields = result->Fetch();
5204 uint32 safeLocId = fields[0].GetUInt32();
5205 uint32 zoneId = fields[1].GetUInt32();
5206 uint32 team = fields[2].GetUInt32();
5208 WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(safeLocId);
5209 if(!entry)
5211 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",safeLocId);
5212 continue;
5215 AreaTableEntry const *areaEntry = GetAreaEntryByAreaID(zoneId);
5216 if(!areaEntry)
5218 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing zone id (%u), skipped.",zoneId);
5219 continue;
5222 if(areaEntry->zone != 0)
5224 sLog.outErrorDb("Table `game_graveyard_zone` has record subzone id (%u) instead of zone, skipped.",zoneId);
5225 continue;
5228 if(team!=0 && team!=HORDE && team!=ALLIANCE)
5230 sLog.outErrorDb("Table `game_graveyard_zone` has record for non player faction (%u), skipped.",team);
5231 continue;
5234 if(!AddGraveYardLink(safeLocId,zoneId,team,false))
5235 sLog.outErrorDb("Table `game_graveyard_zone` has a duplicate record for Graveyard (ID: %u) and Zone (ID: %u), skipped.",safeLocId,zoneId);
5236 } while( result->NextRow() );
5238 delete result;
5240 sLog.outString();
5241 sLog.outString( ">> Loaded %u graveyard-zone links", count );
5244 WorldSafeLocsEntry const *ObjectMgr::GetClosestGraveYard(float x, float y, float z, uint32 MapId, uint32 team)
5246 // search for zone associated closest graveyard
5247 uint32 zoneId = sMapMgr.GetZoneId(MapId,x,y,z);
5249 // Simulate std. algorithm:
5250 // found some graveyard associated to (ghost_zone,ghost_map)
5252 // if mapId == graveyard.mapId (ghost in plain zone or city or battleground) and search graveyard at same map
5253 // then check faction
5254 // if mapId != graveyard.mapId (ghost in instance) and search any graveyard associated
5255 // then check faction
5256 GraveYardMap::const_iterator graveLow = mGraveYardMap.lower_bound(zoneId);
5257 GraveYardMap::const_iterator graveUp = mGraveYardMap.upper_bound(zoneId);
5258 if(graveLow==graveUp)
5260 sLog.outErrorDb("Table `game_graveyard_zone` incomplete: Zone %u Team %u does not have a linked graveyard.",zoneId,team);
5261 return NULL;
5264 // at corpse map
5265 bool foundNear = false;
5266 float distNear;
5267 WorldSafeLocsEntry const* entryNear = NULL;
5269 // at entrance map for corpse map
5270 bool foundEntr = false;
5271 float distEntr;
5272 WorldSafeLocsEntry const* entryEntr = NULL;
5274 // some where other
5275 WorldSafeLocsEntry const* entryFar = NULL;
5277 MapEntry const* mapEntry = sMapStore.LookupEntry(MapId);
5279 for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
5281 GraveYardData const& data = itr->second;
5283 WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(data.safeLocId);
5284 if(!entry)
5286 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",data.safeLocId);
5287 continue;
5290 // skip enemy faction graveyard
5291 // team == 0 case can be at call from .neargrave
5292 if(data.team != 0 && team != 0 && data.team != team)
5293 continue;
5295 // find now nearest graveyard at other map
5296 if(MapId != entry->map_id)
5298 // if find graveyard at different map from where entrance placed (or no entrance data), use any first
5299 if (!mapEntry ||
5300 mapEntry->entrance_map < 0 ||
5301 mapEntry->entrance_map != entry->map_id ||
5302 (mapEntry->entrance_x == 0 && mapEntry->entrance_y == 0))
5304 // not have any corrdinates for check distance anyway
5305 entryFar = entry;
5306 continue;
5309 // at entrance map calculate distance (2D);
5310 float dist2 = (entry->x - mapEntry->entrance_x)*(entry->x - mapEntry->entrance_x)
5311 +(entry->y - mapEntry->entrance_y)*(entry->y - mapEntry->entrance_y);
5312 if(foundEntr)
5314 if(dist2 < distEntr)
5316 distEntr = dist2;
5317 entryEntr = entry;
5320 else
5322 foundEntr = true;
5323 distEntr = dist2;
5324 entryEntr = entry;
5327 // find now nearest graveyard at same map
5328 else
5330 float dist2 = (entry->x - x)*(entry->x - x)+(entry->y - y)*(entry->y - y)+(entry->z - z)*(entry->z - z);
5331 if(foundNear)
5333 if(dist2 < distNear)
5335 distNear = dist2;
5336 entryNear = entry;
5339 else
5341 foundNear = true;
5342 distNear = dist2;
5343 entryNear = entry;
5348 if(entryNear)
5349 return entryNear;
5351 if(entryEntr)
5352 return entryEntr;
5354 return entryFar;
5357 GraveYardData const* ObjectMgr::FindGraveYardData(uint32 id, uint32 zoneId)
5359 GraveYardMap::const_iterator graveLow = mGraveYardMap.lower_bound(zoneId);
5360 GraveYardMap::const_iterator graveUp = mGraveYardMap.upper_bound(zoneId);
5362 for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
5364 if(itr->second.safeLocId==id)
5365 return &itr->second;
5368 return NULL;
5371 bool ObjectMgr::AddGraveYardLink(uint32 id, uint32 zoneId, uint32 team, bool inDB)
5373 if(FindGraveYardData(id,zoneId))
5374 return false;
5376 // add link to loaded data
5377 GraveYardData data;
5378 data.safeLocId = id;
5379 data.team = team;
5381 mGraveYardMap.insert(GraveYardMap::value_type(zoneId,data));
5383 // add link to DB
5384 if(inDB)
5386 WorldDatabase.PExecuteLog("INSERT INTO game_graveyard_zone ( id,ghost_zone,faction) "
5387 "VALUES ('%u', '%u','%u')",id,zoneId,team);
5390 return true;
5393 void ObjectMgr::LoadAreaTriggerTeleports()
5395 mAreaTriggers.clear(); // need for reload case
5397 uint32 count = 0;
5399 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13
5400 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");
5401 if( !result )
5404 barGoLink bar( 1 );
5406 bar.step();
5408 sLog.outString();
5409 sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
5410 return;
5413 barGoLink bar( result->GetRowCount() );
5417 Field *fields = result->Fetch();
5419 bar.step();
5421 ++count;
5423 uint32 Trigger_ID = fields[0].GetUInt32();
5425 AreaTrigger at;
5427 at.requiredLevel = fields[1].GetUInt8();
5428 at.requiredItem = fields[2].GetUInt32();
5429 at.requiredItem2 = fields[3].GetUInt32();
5430 at.heroicKey = fields[4].GetUInt32();
5431 at.heroicKey2 = fields[5].GetUInt32();
5432 at.requiredQuest = fields[6].GetUInt32();
5433 at.requiredQuestHeroic = fields[7].GetUInt32();
5434 at.requiredFailedText = fields[8].GetCppString();
5435 at.target_mapId = fields[9].GetUInt32();
5436 at.target_X = fields[10].GetFloat();
5437 at.target_Y = fields[11].GetFloat();
5438 at.target_Z = fields[12].GetFloat();
5439 at.target_Orientation = fields[13].GetFloat();
5441 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
5442 if(!atEntry)
5444 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
5445 continue;
5448 if(at.requiredItem)
5450 ItemPrototype const *pProto = GetItemPrototype(at.requiredItem);
5451 if(!pProto)
5453 sLog.outError("Key item %u does not exist for trigger %u, removing key requirement.", at.requiredItem, Trigger_ID);
5454 at.requiredItem = 0;
5457 if(at.requiredItem2)
5459 ItemPrototype const *pProto = GetItemPrototype(at.requiredItem2);
5460 if(!pProto)
5462 sLog.outError("Second item %u not exist for trigger %u, remove key requirement.", at.requiredItem2, Trigger_ID);
5463 at.requiredItem2 = 0;
5467 if(at.heroicKey)
5469 ItemPrototype const *pProto = GetItemPrototype(at.heroicKey);
5470 if(!pProto)
5472 sLog.outError("Heroic key item %u not exist for trigger %u, remove key requirement.", at.heroicKey, Trigger_ID);
5473 at.heroicKey = 0;
5477 if(at.heroicKey2)
5479 ItemPrototype const *pProto = GetItemPrototype(at.heroicKey2);
5480 if(!pProto)
5482 sLog.outError("Heroic second key item %u not exist for trigger %u, remove key requirement.", at.heroicKey2, Trigger_ID);
5483 at.heroicKey2 = 0;
5487 if(at.requiredQuest)
5489 QuestMap::iterator qReqItr = mQuestTemplates.find(at.requiredQuest);
5490 if(qReqItr == mQuestTemplates.end())
5492 sLog.outErrorDb("Required Quest %u not exist for trigger %u, remove quest done requirement.",at.requiredQuest,Trigger_ID);
5493 at.requiredQuest = 0;
5497 if(at.requiredQuestHeroic)
5499 QuestMap::iterator qReqItr = mQuestTemplates.find(at.requiredQuestHeroic);
5500 if(qReqItr == mQuestTemplates.end())
5502 sLog.outErrorDb("Required Quest %u not exist for trigger %u, remove quest done requirement.",at.requiredQuestHeroic,Trigger_ID);
5503 at.requiredQuestHeroic = 0;
5507 MapEntry const* mapEntry = sMapStore.LookupEntry(at.target_mapId);
5508 if(!mapEntry)
5510 sLog.outErrorDb("Area trigger (ID:%u) target map (ID: %u) does not exist in `Map.dbc`.",Trigger_ID,at.target_mapId);
5511 continue;
5514 if(at.target_X==0 && at.target_Y==0 && at.target_Z==0)
5516 sLog.outErrorDb("Area trigger (ID:%u) target coordinates not provided.",Trigger_ID);
5517 continue;
5520 mAreaTriggers[Trigger_ID] = at;
5522 } while( result->NextRow() );
5524 delete result;
5526 sLog.outString();
5527 sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
5531 * Searches for the areatrigger which teleports players out of the given map
5533 AreaTrigger const* ObjectMgr::GetGoBackTrigger(uint32 Map) const
5535 const MapEntry *mapEntry = sMapStore.LookupEntry(Map);
5536 if(!mapEntry) return NULL;
5537 for (AreaTriggerMap::const_iterator itr = mAreaTriggers.begin(); itr != mAreaTriggers.end(); ++itr)
5539 if(itr->second.target_mapId == mapEntry->entrance_map)
5541 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(itr->first);
5542 if(atEntry && atEntry->mapid == Map)
5543 return &itr->second;
5546 return NULL;
5550 * Searches for the areatrigger which teleports players to the given map
5552 AreaTrigger const* ObjectMgr::GetMapEntranceTrigger(uint32 Map) const
5554 for (AreaTriggerMap::const_iterator itr = mAreaTriggers.begin(); itr != mAreaTriggers.end(); ++itr)
5556 if(itr->second.target_mapId == Map)
5558 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(itr->first);
5559 if(atEntry)
5560 return &itr->second;
5563 return NULL;
5566 void ObjectMgr::SetHighestGuids()
5568 QueryResult *result = CharacterDatabase.Query( "SELECT MAX(guid) FROM characters" );
5569 if( result )
5571 m_hiCharGuid = (*result)[0].GetUInt32()+1;
5572 delete result;
5575 result = WorldDatabase.Query( "SELECT MAX(guid) FROM creature" );
5576 if( result )
5578 m_hiCreatureGuid = (*result)[0].GetUInt32()+1;
5579 delete result;
5582 result = CharacterDatabase.Query( "SELECT MAX(guid) FROM item_instance" );
5583 if( result )
5585 m_hiItemGuid = (*result)[0].GetUInt32()+1;
5586 delete result;
5589 // Cleanup other tables from not existed guids (>=m_hiItemGuid)
5590 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item >= '%u'", m_hiItemGuid);
5591 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid >= '%u'", m_hiItemGuid);
5592 CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE itemguid >= '%u'", m_hiItemGuid);
5593 CharacterDatabase.PExecute("DELETE FROM guild_bank_item WHERE item_guid >= '%u'", m_hiItemGuid);
5595 result = WorldDatabase.Query("SELECT MAX(guid) FROM gameobject" );
5596 if( result )
5598 m_hiGoGuid = (*result)[0].GetUInt32()+1;
5599 delete result;
5602 result = CharacterDatabase.Query("SELECT MAX(id) FROM auctionhouse" );
5603 if( result )
5605 m_auctionid = (*result)[0].GetUInt32()+1;
5606 delete result;
5609 result = CharacterDatabase.Query( "SELECT MAX(id) FROM mail" );
5610 if( result )
5612 m_mailid = (*result)[0].GetUInt32()+1;
5613 delete result;
5616 result = CharacterDatabase.Query( "SELECT MAX(id) FROM item_text" );
5617 if( result )
5619 m_ItemTextId = (*result)[0].GetUInt32()+1;
5620 delete result;
5623 result = CharacterDatabase.Query( "SELECT MAX(guid) FROM corpse" );
5624 if( result )
5626 m_hiCorpseGuid = (*result)[0].GetUInt32()+1;
5627 delete result;
5630 result = CharacterDatabase.Query("SELECT MAX(arenateamid) FROM arena_team");
5631 if (result)
5633 m_arenaTeamId = (*result)[0].GetUInt32()+1;
5634 delete result;
5637 result = CharacterDatabase.Query("SELECT MAX(setguid) FROM character_equipmentsets");
5638 if (result)
5640 m_equipmentSetGuid = (*result)[0].GetUInt64()+1;
5641 delete result;
5644 result = CharacterDatabase.Query( "SELECT MAX(guildid) FROM guild" );
5645 if (result)
5647 m_guildId = (*result)[0].GetUInt32()+1;
5648 delete result;
5652 uint32 ObjectMgr::GenerateArenaTeamId()
5654 if(m_arenaTeamId>=0xFFFFFFFE)
5656 sLog.outError("Arena team ids overflow!! Can't continue, shutting down server. ");
5657 World::StopNow(ERROR_EXIT_CODE);
5659 return m_arenaTeamId++;
5662 uint32 ObjectMgr::GenerateAuctionID()
5664 if(m_auctionid>=0xFFFFFFFE)
5666 sLog.outError("Auctions ids overflow!! Can't continue, shutting down server. ");
5667 World::StopNow(ERROR_EXIT_CODE);
5669 return m_auctionid++;
5672 uint64 ObjectMgr::GenerateEquipmentSetGuid()
5674 if(m_equipmentSetGuid>=0xFFFFFFFFFFFFFFFEll)
5676 sLog.outError("EquipmentSet guid overflow!! Can't continue, shutting down server. ");
5677 World::StopNow(ERROR_EXIT_CODE);
5679 return m_equipmentSetGuid++;
5682 uint32 ObjectMgr::GenerateGuildId()
5684 if(m_guildId>=0xFFFFFFFE)
5686 sLog.outError("Guild ids overflow!! Can't continue, shutting down server. ");
5687 World::StopNow(ERROR_EXIT_CODE);
5689 return m_guildId++;
5692 uint32 ObjectMgr::GenerateMailID()
5694 if(m_mailid>=0xFFFFFFFE)
5696 sLog.outError("Mail ids overflow!! Can't continue, shutting down server. ");
5697 World::StopNow(ERROR_EXIT_CODE);
5699 return m_mailid++;
5702 uint32 ObjectMgr::GenerateItemTextID()
5704 if(m_ItemTextId>=0xFFFFFFFE)
5706 sLog.outError("Item text ids overflow!! Can't continue, shutting down server. ");
5707 World::StopNow(ERROR_EXIT_CODE);
5709 return m_ItemTextId++;
5712 uint32 ObjectMgr::CreateItemText(std::string text)
5714 uint32 newItemTextId = GenerateItemTextID();
5715 //insert new itempage to container
5716 mItemTexts[ newItemTextId ] = text;
5717 //save new itempage
5718 CharacterDatabase.escape_string(text);
5719 //any Delete query needed, itemTextId is maximum of all ids
5720 std::ostringstream query;
5721 query << "INSERT INTO item_text (id,text) VALUES ( '" << newItemTextId << "', '" << text << "')";
5722 CharacterDatabase.Execute(query.str().c_str()); //needs to be run this way, because mail body may be more than 1024 characters
5723 return newItemTextId;
5726 uint32 ObjectMgr::GenerateLowGuid(HighGuid guidhigh)
5728 switch(guidhigh)
5730 case HIGHGUID_ITEM:
5731 if(m_hiItemGuid>=0xFFFFFFFE)
5733 sLog.outError("Item guid overflow!! Can't continue, shutting down server. ");
5734 World::StopNow(ERROR_EXIT_CODE);
5736 return m_hiItemGuid++;
5737 case HIGHGUID_UNIT:
5738 if(m_hiCreatureGuid>=0x00FFFFFE)
5740 sLog.outError("Creature guid overflow!! Can't continue, shutting down server. ");
5741 World::StopNow(ERROR_EXIT_CODE);
5743 return m_hiCreatureGuid++;
5744 case HIGHGUID_PLAYER:
5745 if(m_hiCharGuid>=0xFFFFFFFE)
5747 sLog.outError("Players guid overflow!! Can't continue, shutting down server. ");
5748 World::StopNow(ERROR_EXIT_CODE);
5750 return m_hiCharGuid++;
5751 case HIGHGUID_GAMEOBJECT:
5752 if(m_hiGoGuid>=0x00FFFFFE)
5754 sLog.outError("Gameobject guid overflow!! Can't continue, shutting down server. ");
5755 World::StopNow(ERROR_EXIT_CODE);
5757 return m_hiGoGuid++;
5758 case HIGHGUID_CORPSE:
5759 if(m_hiCorpseGuid>=0xFFFFFFFE)
5761 sLog.outError("Corpse guid overflow!! Can't continue, shutting down server. ");
5762 World::StopNow(ERROR_EXIT_CODE);
5764 return m_hiCorpseGuid++;
5765 default:
5766 ASSERT(0);
5769 ASSERT(0);
5770 return 0;
5773 void ObjectMgr::LoadGameObjectLocales()
5775 mGameObjectLocaleMap.clear(); // need for reload case
5777 QueryResult *result = WorldDatabase.Query("SELECT entry,"
5778 "name_loc1,name_loc2,name_loc3,name_loc4,name_loc5,name_loc6,name_loc7,name_loc8,"
5779 "castbarcaption_loc1,castbarcaption_loc2,castbarcaption_loc3,castbarcaption_loc4,"
5780 "castbarcaption_loc5,castbarcaption_loc6,castbarcaption_loc7,castbarcaption_loc8 FROM locales_gameobject");
5782 if(!result)
5784 barGoLink bar(1);
5786 bar.step();
5788 sLog.outString();
5789 sLog.outString(">> Loaded 0 gameobject locale strings. DB table `locales_gameobject` is empty.");
5790 return;
5793 barGoLink bar(result->GetRowCount());
5797 Field *fields = result->Fetch();
5798 bar.step();
5800 uint32 entry = fields[0].GetUInt32();
5802 GameObjectLocale& data = mGameObjectLocaleMap[entry];
5804 for(int i = 1; i < MAX_LOCALE; ++i)
5806 std::string str = fields[i].GetCppString();
5807 if(!str.empty())
5809 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5810 if(idx >= 0)
5812 if(data.Name.size() <= idx)
5813 data.Name.resize(idx+1);
5815 data.Name[idx] = str;
5820 for(int i = 1; i < MAX_LOCALE; ++i)
5822 std::string str = fields[i+(MAX_LOCALE-1)].GetCppString();
5823 if(!str.empty())
5825 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5826 if(idx >= 0)
5828 if(data.CastBarCaption.size() <= idx)
5829 data.CastBarCaption.resize(idx+1);
5831 data.CastBarCaption[idx] = str;
5836 } while (result->NextRow());
5838 delete result;
5840 sLog.outString();
5841 sLog.outString( ">> Loaded %lu gameobject locale strings", (unsigned long)mGameObjectLocaleMap.size() );
5844 struct SQLGameObjectLoader : public SQLStorageLoaderBase<SQLGameObjectLoader>
5846 template<class D>
5847 void convert_from_str(uint32 /*field_pos*/, char *src, D &dst)
5849 dst = D(sObjectMgr.GetScriptId(src));
5853 inline void CheckGOLockId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5855 if (sLockStore.LookupEntry(dataN))
5856 return;
5858 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but lock (Id: %u) not found.",
5859 goInfo->id,goInfo->type,N,dataN,dataN);
5862 inline void CheckGOLinkedTrapId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5864 if (GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(dataN))
5866 if (trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5867 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5868 goInfo->id,goInfo->type,N,dataN,dataN,GAMEOBJECT_TYPE_TRAP);
5870 /* disable check for while (too many error reports baout not existed in trap templates
5871 else
5872 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5873 goInfo->id,goInfo->type,N,dataN,dataN);
5877 inline void CheckGOSpellId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5879 if (sSpellStore.LookupEntry(dataN))
5880 return;
5882 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but Spell (Entry %u) not exist.",
5883 goInfo->id,goInfo->type,N,dataN,dataN);
5886 inline void CheckAndFixGOChairHeightId(GameObjectInfo const* goInfo,uint32 const& dataN,uint32 N)
5888 if (dataN <= (UNIT_STAND_STATE_SIT_HIGH_CHAIR-UNIT_STAND_STATE_SIT_LOW_CHAIR) )
5889 return;
5891 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but correct chair height in range 0..%i.",
5892 goInfo->id,goInfo->type,N,dataN,UNIT_STAND_STATE_SIT_HIGH_CHAIR-UNIT_STAND_STATE_SIT_LOW_CHAIR);
5894 // prevent client and server unexpected work
5895 const_cast<uint32&>(dataN) = 0;
5898 inline void CheckGONoDamageImmuneId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5900 // 0/1 correct values
5901 if (dataN <= 1)
5902 return;
5904 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but expected boolean (0/1) noDamageImmune field value.",
5905 goInfo->id,goInfo->type,N,dataN);
5908 inline void CheckGOConsumable(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5910 // 0/1 correct values
5911 if (dataN <= 1)
5912 return;
5914 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but expected boolean (0/1) consumable field value.",
5915 goInfo->id,goInfo->type,N,dataN);
5918 void ObjectMgr::LoadGameobjectInfo()
5920 SQLGameObjectLoader loader;
5921 loader.Load(sGOStorage);
5923 // some checks
5924 for(uint32 id = 1; id < sGOStorage.MaxEntry; id++)
5926 GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(id);
5927 if (!goInfo)
5928 continue;
5930 // some GO types have unused go template, check goInfo->displayId at GO spawn data loading or ignore
5932 switch(goInfo->type)
5934 case GAMEOBJECT_TYPE_DOOR: //0
5936 if (goInfo->door.lockId)
5937 CheckGOLockId(goInfo,goInfo->door.lockId,1);
5938 CheckGONoDamageImmuneId(goInfo,goInfo->door.noDamageImmune,3);
5939 break;
5941 case GAMEOBJECT_TYPE_BUTTON: //1
5943 if (goInfo->button.lockId)
5944 CheckGOLockId(goInfo,goInfo->button.lockId,1);
5945 CheckGONoDamageImmuneId(goInfo,goInfo->button.noDamageImmune,4);
5946 break;
5948 case GAMEOBJECT_TYPE_QUESTGIVER: //2
5950 if (goInfo->questgiver.lockId)
5951 CheckGOLockId(goInfo,goInfo->questgiver.lockId,0);
5952 CheckGONoDamageImmuneId(goInfo,goInfo->questgiver.noDamageImmune,5);
5953 break;
5955 case GAMEOBJECT_TYPE_CHEST: //3
5957 if (goInfo->chest.lockId)
5958 CheckGOLockId(goInfo,goInfo->chest.lockId,0);
5960 CheckGOConsumable(goInfo,goInfo->chest.consumable,3);
5962 if (goInfo->chest.linkedTrapId) // linked trap
5963 CheckGOLinkedTrapId(goInfo,goInfo->chest.linkedTrapId,7);
5964 break;
5966 case GAMEOBJECT_TYPE_TRAP: //6
5968 if (goInfo->trap.lockId)
5969 CheckGOLockId(goInfo,goInfo->trap.lockId,0);
5970 /* disable check for while, too many not existed spells
5971 if (goInfo->trap.spellId) // spell
5972 CheckGOSpellId(goInfo,goInfo->trap.spellId,3);
5974 break;
5976 case GAMEOBJECT_TYPE_CHAIR: //7
5977 CheckAndFixGOChairHeightId(goInfo,goInfo->chair.height,1);
5978 break;
5979 case GAMEOBJECT_TYPE_SPELL_FOCUS: //8
5981 if (goInfo->spellFocus.focusId)
5983 if (!sSpellFocusObjectStore.LookupEntry(goInfo->spellFocus.focusId))
5984 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but SpellFocus (Id: %u) not exist.",
5985 id,goInfo->type,goInfo->spellFocus.focusId,goInfo->spellFocus.focusId);
5988 if (goInfo->spellFocus.linkedTrapId) // linked trap
5989 CheckGOLinkedTrapId(goInfo,goInfo->spellFocus.linkedTrapId,2);
5990 break;
5992 case GAMEOBJECT_TYPE_GOOBER: //10
5994 if (goInfo->goober.lockId)
5995 CheckGOLockId(goInfo,goInfo->goober.lockId,0);
5997 CheckGOConsumable(goInfo,goInfo->goober.consumable,3);
5999 if (goInfo->goober.pageId) // pageId
6001 if (!sPageTextStore.LookupEntry<PageText>(goInfo->goober.pageId))
6002 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data7=%u but PageText (Entry %u) not exist.",
6003 id,goInfo->type,goInfo->goober.pageId,goInfo->goober.pageId);
6005 /* disable check for while, too many not existed spells
6006 if (goInfo->goober.spellId) // spell
6007 CheckGOSpellId(goInfo,goInfo->goober.spellId,10);
6009 CheckGONoDamageImmuneId(goInfo,goInfo->goober.noDamageImmune,11);
6010 if (goInfo->goober.linkedTrapId) // linked trap
6011 CheckGOLinkedTrapId(goInfo,goInfo->goober.linkedTrapId,12);
6012 break;
6014 case GAMEOBJECT_TYPE_AREADAMAGE: //12
6016 if (goInfo->areadamage.lockId)
6017 CheckGOLockId(goInfo,goInfo->areadamage.lockId,0);
6018 break;
6020 case GAMEOBJECT_TYPE_CAMERA: //13
6022 if (goInfo->camera.lockId)
6023 CheckGOLockId(goInfo,goInfo->camera.lockId,0);
6024 break;
6026 case GAMEOBJECT_TYPE_MO_TRANSPORT: //15
6028 if (goInfo->moTransport.taxiPathId)
6030 if (goInfo->moTransport.taxiPathId >= sTaxiPathNodesByPath.size() || sTaxiPathNodesByPath[goInfo->moTransport.taxiPathId].empty())
6031 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but TaxiPath (Id: %u) not exist.",
6032 id,goInfo->type,goInfo->moTransport.taxiPathId,goInfo->moTransport.taxiPathId);
6034 break;
6036 case GAMEOBJECT_TYPE_SUMMONING_RITUAL: //18
6038 /* disable check for while, too many not existed spells
6039 // always must have spell
6040 CheckGOSpellId(goInfo,goInfo->summoningRitual.spellId,1);
6042 break;
6044 case GAMEOBJECT_TYPE_SPELLCASTER: //22
6046 // always must have spell
6047 CheckGOSpellId(goInfo,goInfo->spellcaster.spellId,0);
6048 break;
6050 case GAMEOBJECT_TYPE_FLAGSTAND: //24
6052 if (goInfo->flagstand.lockId)
6053 CheckGOLockId(goInfo,goInfo->flagstand.lockId,0);
6054 CheckGONoDamageImmuneId(goInfo,goInfo->flagstand.noDamageImmune,5);
6055 break;
6057 case GAMEOBJECT_TYPE_FISHINGHOLE: //25
6059 if (goInfo->fishinghole.lockId)
6060 CheckGOLockId(goInfo,goInfo->fishinghole.lockId,4);
6061 break;
6063 case GAMEOBJECT_TYPE_FLAGDROP: //26
6065 if (goInfo->flagdrop.lockId)
6066 CheckGOLockId(goInfo,goInfo->flagdrop.lockId,0);
6067 CheckGONoDamageImmuneId(goInfo,goInfo->flagdrop.noDamageImmune,3);
6068 break;
6070 case GAMEOBJECT_TYPE_BARBER_CHAIR: //32
6071 CheckAndFixGOChairHeightId(goInfo,goInfo->barberChair.chairheight,0);
6072 break;
6076 sLog.outString( ">> Loaded %u game object templates", sGOStorage.RecordCount );
6077 sLog.outString();
6080 void ObjectMgr::LoadExplorationBaseXP()
6082 uint32 count = 0;
6083 QueryResult *result = WorldDatabase.Query("SELECT level,basexp FROM exploration_basexp");
6085 if( !result )
6087 barGoLink bar( 1 );
6089 bar.step();
6091 sLog.outString();
6092 sLog.outString( ">> Loaded %u BaseXP definitions", count );
6093 return;
6096 barGoLink bar( result->GetRowCount() );
6100 bar.step();
6102 Field *fields = result->Fetch();
6103 uint32 level = fields[0].GetUInt32();
6104 uint32 basexp = fields[1].GetUInt32();
6105 mBaseXPTable[level] = basexp;
6106 ++count;
6108 while (result->NextRow());
6110 delete result;
6112 sLog.outString();
6113 sLog.outString( ">> Loaded %u BaseXP definitions", count );
6116 uint32 ObjectMgr::GetBaseXP(uint32 level) const
6118 BaseXPMap::const_iterator itr = mBaseXPTable.find(level);
6119 return itr != mBaseXPTable.end() ? itr->second : 0;
6122 uint32 ObjectMgr::GetXPForLevel(uint32 level) const
6124 if (level < mPlayerXPperLevel.size())
6125 return mPlayerXPperLevel[level];
6126 return 0;
6129 void ObjectMgr::LoadPetNames()
6131 uint32 count = 0;
6132 QueryResult *result = WorldDatabase.Query("SELECT word,entry,half FROM pet_name_generation");
6134 if( !result )
6136 barGoLink bar( 1 );
6138 bar.step();
6140 sLog.outString();
6141 sLog.outString( ">> Loaded %u pet name parts", count );
6142 return;
6145 barGoLink bar( result->GetRowCount() );
6149 bar.step();
6151 Field *fields = result->Fetch();
6152 std::string word = fields[0].GetString();
6153 uint32 entry = fields[1].GetUInt32();
6154 bool half = fields[2].GetBool();
6155 if(half)
6156 PetHalfName1[entry].push_back(word);
6157 else
6158 PetHalfName0[entry].push_back(word);
6159 ++count;
6161 while (result->NextRow());
6162 delete result;
6164 sLog.outString();
6165 sLog.outString( ">> Loaded %u pet name parts", count );
6168 void ObjectMgr::LoadPetNumber()
6170 QueryResult* result = CharacterDatabase.Query("SELECT MAX(id) FROM character_pet");
6171 if(result)
6173 Field *fields = result->Fetch();
6174 m_hiPetNumber = fields[0].GetUInt32()+1;
6175 delete result;
6178 barGoLink bar( 1 );
6179 bar.step();
6181 sLog.outString();
6182 sLog.outString( ">> Loaded the max pet number: %d", m_hiPetNumber-1);
6185 std::string ObjectMgr::GeneratePetName(uint32 entry)
6187 std::vector<std::string> & list0 = PetHalfName0[entry];
6188 std::vector<std::string> & list1 = PetHalfName1[entry];
6190 if(list0.empty() || list1.empty())
6192 CreatureInfo const *cinfo = GetCreatureTemplate(entry);
6193 char* petname = GetPetName(cinfo->family, sWorld.GetDefaultDbcLocale());
6194 if(!petname)
6195 petname = cinfo->Name;
6196 return std::string(petname);
6199 return *(list0.begin()+urand(0, list0.size()-1)) + *(list1.begin()+urand(0, list1.size()-1));
6202 uint32 ObjectMgr::GeneratePetNumber()
6204 return ++m_hiPetNumber;
6207 void ObjectMgr::LoadCorpses()
6209 uint32 count = 0;
6210 // 0 1 2 3 4 5 6 7 8 10
6211 QueryResult *result = CharacterDatabase.Query("SELECT position_x, position_y, position_z, orientation, map, data, time, corpse_type, instance, guid FROM corpse WHERE corpse_type <> 0");
6213 if( !result )
6215 barGoLink bar( 1 );
6217 bar.step();
6219 sLog.outString();
6220 sLog.outString( ">> Loaded %u corpses", count );
6221 return;
6224 barGoLink bar( result->GetRowCount() );
6228 bar.step();
6230 Field *fields = result->Fetch();
6232 uint32 guid = fields[result->GetFieldCount()-1].GetUInt32();
6234 Corpse *corpse = new Corpse;
6235 if(!corpse->LoadFromDB(guid,fields))
6237 delete corpse;
6238 continue;
6241 sObjectAccessor.AddCorpse(corpse);
6243 ++count;
6245 while (result->NextRow());
6246 delete result;
6248 sLog.outString();
6249 sLog.outString( ">> Loaded %u corpses", count );
6252 void ObjectMgr::LoadReputationOnKill()
6254 uint32 count = 0;
6256 // 0 1 2
6257 QueryResult *result = WorldDatabase.Query("SELECT creature_id, RewOnKillRepFaction1, RewOnKillRepFaction2,"
6258 // 3 4 5 6 7 8 9
6259 "IsTeamAward1, MaxStanding1, RewOnKillRepValue1, IsTeamAward2, MaxStanding2, RewOnKillRepValue2, TeamDependent "
6260 "FROM creature_onkill_reputation");
6262 if(!result)
6264 barGoLink bar(1);
6266 bar.step();
6268 sLog.outString();
6269 sLog.outErrorDb(">> Loaded 0 creature award reputation definitions. DB table `creature_onkill_reputation` is empty.");
6270 return;
6273 barGoLink bar(result->GetRowCount());
6277 Field *fields = result->Fetch();
6278 bar.step();
6280 uint32 creature_id = fields[0].GetUInt32();
6282 ReputationOnKillEntry repOnKill;
6283 repOnKill.repfaction1 = fields[1].GetUInt32();
6284 repOnKill.repfaction2 = fields[2].GetUInt32();
6285 repOnKill.is_teamaward1 = fields[3].GetBool();
6286 repOnKill.reputation_max_cap1 = fields[4].GetUInt32();
6287 repOnKill.repvalue1 = fields[5].GetInt32();
6288 repOnKill.is_teamaward2 = fields[6].GetBool();
6289 repOnKill.reputation_max_cap2 = fields[7].GetUInt32();
6290 repOnKill.repvalue2 = fields[8].GetInt32();
6291 repOnKill.team_dependent = fields[9].GetUInt8();
6293 if(!GetCreatureTemplate(creature_id))
6295 sLog.outErrorDb("Table `creature_onkill_reputation` have data for not existed creature entry (%u), skipped",creature_id);
6296 continue;
6299 if(repOnKill.repfaction1)
6301 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(repOnKill.repfaction1);
6302 if(!factionEntry1)
6304 sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction1);
6305 continue;
6309 if(repOnKill.repfaction2)
6311 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(repOnKill.repfaction2);
6312 if(!factionEntry2)
6314 sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction2);
6315 continue;
6319 mRepOnKill[creature_id] = repOnKill;
6321 ++count;
6322 } while (result->NextRow());
6324 delete result;
6326 sLog.outString();
6327 sLog.outString(">> Loaded %u creature award reputation definitions", count);
6330 void ObjectMgr::LoadPointsOfInterest()
6332 uint32 count = 0;
6334 // 0 1 2 3 4 5
6335 QueryResult *result = WorldDatabase.Query("SELECT entry, x, y, icon, flags, data, icon_name FROM points_of_interest");
6337 if(!result)
6339 barGoLink bar(1);
6341 bar.step();
6343 sLog.outString();
6344 sLog.outErrorDb(">> Loaded 0 Points of Interest definitions. DB table `points_of_interest` is empty.");
6345 return;
6348 barGoLink bar(result->GetRowCount());
6352 Field *fields = result->Fetch();
6353 bar.step();
6355 uint32 point_id = fields[0].GetUInt32();
6357 PointOfInterest POI;
6358 POI.x = fields[1].GetFloat();
6359 POI.y = fields[2].GetFloat();
6360 POI.icon = fields[3].GetUInt32();
6361 POI.flags = fields[4].GetUInt32();
6362 POI.data = fields[5].GetUInt32();
6363 POI.icon_name = fields[6].GetCppString();
6365 if(!MaNGOS::IsValidMapCoord(POI.x,POI.y))
6367 sLog.outErrorDb("Table `points_of_interest` (Entry: %u) have invalid coordinates (X: %f Y: %f), ignored.",point_id,POI.x,POI.y);
6368 continue;
6371 mPointsOfInterest[point_id] = POI;
6373 ++count;
6374 } while (result->NextRow());
6376 delete result;
6378 sLog.outString();
6379 sLog.outString(">> Loaded %u Points of Interest definitions", count);
6382 void ObjectMgr::LoadQuestPOI()
6384 uint32 count = 0;
6386 // 0 1 2 3 4 5 6
6387 QueryResult *result = WorldDatabase.Query("SELECT questId, objIndex, mapId, unk1, unk2, unk3, unk4 FROM quest_poi");
6389 if(!result)
6391 barGoLink bar(1);
6393 bar.step();
6395 sLog.outString();
6396 sLog.outErrorDb(">> Loaded 0 quest POI definitions. DB table `quest_poi` is empty.");
6397 return;
6400 barGoLink bar(result->GetRowCount());
6404 Field *fields = result->Fetch();
6405 bar.step();
6407 uint32 questId = fields[0].GetUInt32();
6408 int32 objIndex = fields[1].GetInt32();
6409 uint32 mapId = fields[2].GetUInt32();
6410 uint32 unk1 = fields[3].GetUInt32();
6411 uint32 unk2 = fields[4].GetUInt32();
6412 uint32 unk3 = fields[5].GetUInt32();
6413 uint32 unk4 = fields[6].GetUInt32();
6415 QuestPOI POI(objIndex, mapId, unk1, unk2, unk3, unk4);
6417 QueryResult *points = WorldDatabase.PQuery("SELECT x, y FROM quest_poi_points WHERE questId='%u' AND objIndex='%i'", questId, objIndex);
6419 if(points)
6423 Field *pointFields = points->Fetch();
6424 int32 x = pointFields[0].GetInt32();
6425 int32 y = pointFields[1].GetInt32();
6426 QuestPOIPoint point(x, y);
6427 POI.points.push_back(point);
6428 } while (points->NextRow());
6430 delete points;
6433 mQuestPOIMap[questId].push_back(POI);
6435 ++count;
6436 } while (result->NextRow());
6438 delete result;
6440 sLog.outString();
6441 sLog.outString(">> Loaded %u quest POI definitions", count);
6444 void ObjectMgr::LoadNPCSpellClickSpells()
6446 uint32 count = 0;
6448 mSpellClickInfoMap.clear();
6449 // 0 1 2 3 4 5
6450 QueryResult *result = WorldDatabase.Query("SELECT npc_entry, spell_id, quest_start, quest_start_active, quest_end, cast_flags FROM npc_spellclick_spells");
6452 if(!result)
6454 barGoLink bar(1);
6456 bar.step();
6458 sLog.outString();
6459 sLog.outErrorDb(">> Loaded 0 spellclick spells. DB table `npc_spellclick_spells` is empty.");
6460 return;
6463 barGoLink bar(result->GetRowCount());
6467 Field *fields = result->Fetch();
6468 bar.step();
6470 uint32 npc_entry = fields[0].GetUInt32();
6471 CreatureInfo const* cInfo = GetCreatureTemplate(npc_entry);
6472 if (!cInfo)
6474 sLog.outErrorDb("Table npc_spellclick_spells references unknown creature_template %u. Skipping entry.", npc_entry);
6475 continue;
6478 uint32 spellid = fields[1].GetUInt32();
6479 SpellEntry const *spellinfo = sSpellStore.LookupEntry(spellid);
6480 if (!spellinfo)
6482 sLog.outErrorDb("Table npc_spellclick_spells references unknown spellid %u. Skipping entry.", spellid);
6483 continue;
6486 uint32 quest_start = fields[2].GetUInt32();
6488 // quest might be 0 to enable spellclick independent of any quest
6489 if (quest_start)
6491 if(mQuestTemplates.find(quest_start) == mQuestTemplates.end())
6493 sLog.outErrorDb("Table npc_spellclick_spells references unknown start quest %u. Skipping entry.", quest_start);
6494 continue;
6499 bool quest_start_active = fields[3].GetBool();
6501 uint32 quest_end = fields[4].GetUInt32();
6502 // quest might be 0 to enable spellclick active infinity after start quest
6503 if (quest_end)
6505 if(mQuestTemplates.find(quest_end) == mQuestTemplates.end())
6507 sLog.outErrorDb("Table npc_spellclick_spells references unknown end quest %u. Skipping entry.", quest_end);
6508 continue;
6513 uint8 castFlags = fields[5].GetUInt8();
6514 SpellClickInfo info;
6515 info.spellId = spellid;
6516 info.questStart = quest_start;
6517 info.questStartCanActive = quest_start_active;
6518 info.questEnd = quest_end;
6519 info.castFlags = castFlags;
6520 mSpellClickInfoMap.insert(SpellClickInfoMap::value_type(npc_entry, info));
6522 // mark creature template as spell clickable
6523 const_cast<CreatureInfo*>(cInfo)->npcflag |= UNIT_NPC_FLAG_SPELLCLICK;
6525 ++count;
6526 } while (result->NextRow());
6528 delete result;
6530 sLog.outString();
6531 sLog.outString(">> Loaded %u spellclick definitions", count);
6534 void ObjectMgr::LoadWeatherZoneChances()
6536 uint32 count = 0;
6538 // 0 1 2 3 4 5 6 7 8 9 10 11 12
6539 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");
6541 if(!result)
6543 barGoLink bar(1);
6545 bar.step();
6547 sLog.outString();
6548 sLog.outErrorDb(">> Loaded 0 weather definitions. DB table `game_weather` is empty.");
6549 return;
6552 barGoLink bar(result->GetRowCount());
6556 Field *fields = result->Fetch();
6557 bar.step();
6559 uint32 zone_id = fields[0].GetUInt32();
6561 WeatherZoneChances& wzc = mWeatherZoneMap[zone_id];
6563 for(int season = 0; season < WEATHER_SEASONS; ++season)
6565 wzc.data[season].rainChance = fields[season * (MAX_WEATHER_TYPE-1) + 1].GetUInt32();
6566 wzc.data[season].snowChance = fields[season * (MAX_WEATHER_TYPE-1) + 2].GetUInt32();
6567 wzc.data[season].stormChance = fields[season * (MAX_WEATHER_TYPE-1) + 3].GetUInt32();
6569 if(wzc.data[season].rainChance > 100)
6571 wzc.data[season].rainChance = 25;
6572 sLog.outErrorDb("Weather for zone %u season %u has wrong rain chance > 100%%",zone_id,season);
6575 if(wzc.data[season].snowChance > 100)
6577 wzc.data[season].snowChance = 25;
6578 sLog.outErrorDb("Weather for zone %u season %u has wrong snow chance > 100%%",zone_id,season);
6581 if(wzc.data[season].stormChance > 100)
6583 wzc.data[season].stormChance = 25;
6584 sLog.outErrorDb("Weather for zone %u season %u has wrong storm chance > 100%%",zone_id,season);
6588 ++count;
6589 } while (result->NextRow());
6591 delete result;
6593 sLog.outString();
6594 sLog.outString(">> Loaded %u weather definitions", count);
6597 void ObjectMgr::SaveCreatureRespawnTime(uint32 loguid, uint32 instance, time_t t)
6599 mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
6600 WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
6601 if(t)
6602 WorldDatabase.PExecute("INSERT INTO creature_respawn VALUES ( '%u', '" UI64FMTD "', '%u' )", loguid, uint64(t), instance);
6605 void ObjectMgr::DeleteCreatureData(uint32 guid)
6607 // remove mapid*cellid -> guid_set map
6608 CreatureData const* data = GetCreatureData(guid);
6609 if(data)
6610 RemoveCreatureFromGrid(guid, data);
6612 mCreatureDataMap.erase(guid);
6615 void ObjectMgr::SaveGORespawnTime(uint32 loguid, uint32 instance, time_t t)
6617 mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
6618 WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
6619 if(t)
6620 WorldDatabase.PExecute("INSERT INTO gameobject_respawn VALUES ( '%u', '" UI64FMTD "', '%u' )", loguid, uint64(t), instance);
6623 void ObjectMgr::DeleteRespawnTimeForInstance(uint32 instance)
6625 RespawnTimes::iterator next;
6627 for(RespawnTimes::iterator itr = mGORespawnTimes.begin(); itr != mGORespawnTimes.end(); itr = next)
6629 next = itr;
6630 ++next;
6632 if(GUID_HIPART(itr->first)==instance)
6633 mGORespawnTimes.erase(itr);
6636 for(RespawnTimes::iterator itr = mCreatureRespawnTimes.begin(); itr != mCreatureRespawnTimes.end(); itr = next)
6638 next = itr;
6639 ++next;
6641 if(GUID_HIPART(itr->first)==instance)
6642 mCreatureRespawnTimes.erase(itr);
6645 WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE instance = '%u'", instance);
6646 WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE instance = '%u'", instance);
6649 void ObjectMgr::DeleteGOData(uint32 guid)
6651 // remove mapid*cellid -> guid_set map
6652 GameObjectData const* data = GetGOData(guid);
6653 if(data)
6654 RemoveGameobjectFromGrid(guid, data);
6656 mGameObjectDataMap.erase(guid);
6659 void ObjectMgr::AddCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid, uint32 instance)
6661 // corpses are always added to spawn mode 0 and they are spawned by their instance id
6662 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
6663 cell_guids.corpses[player_guid] = instance;
6666 void ObjectMgr::DeleteCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid)
6668 // corpses are always added to spawn mode 0 and they are spawned by their instance id
6669 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
6670 cell_guids.corpses.erase(player_guid);
6673 void ObjectMgr::LoadQuestRelationsHelper(QuestRelations& map,char const* table)
6675 map.clear(); // need for reload case
6677 uint32 count = 0;
6679 QueryResult *result = WorldDatabase.PQuery("SELECT id,quest FROM %s",table);
6681 if(!result)
6683 barGoLink bar(1);
6685 bar.step();
6687 sLog.outString();
6688 sLog.outErrorDb(">> Loaded 0 quest relations from %s. DB table `%s` is empty.",table,table);
6689 return;
6692 barGoLink bar(result->GetRowCount());
6696 Field *fields = result->Fetch();
6697 bar.step();
6699 uint32 id = fields[0].GetUInt32();
6700 uint32 quest = fields[1].GetUInt32();
6702 if(mQuestTemplates.find(quest) == mQuestTemplates.end())
6704 sLog.outErrorDb("Table `%s: Quest %u listed for entry %u does not exist.",table,quest,id);
6705 continue;
6708 map.insert(QuestRelations::value_type(id,quest));
6710 ++count;
6711 } while (result->NextRow());
6713 delete result;
6715 sLog.outString();
6716 sLog.outString(">> Loaded %u quest relations from %s", count,table);
6719 void ObjectMgr::LoadGameobjectQuestRelations()
6721 LoadQuestRelationsHelper(mGOQuestRelations,"gameobject_questrelation");
6723 for(QuestRelations::iterator itr = mGOQuestRelations.begin(); itr != mGOQuestRelations.end(); ++itr)
6725 GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
6726 if(!goInfo)
6727 sLog.outErrorDb("Table `gameobject_questrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
6728 else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
6729 sLog.outErrorDb("Table `gameobject_questrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
6733 void ObjectMgr::LoadGameobjectInvolvedRelations()
6735 LoadQuestRelationsHelper(mGOQuestInvolvedRelations,"gameobject_involvedrelation");
6737 for(QuestRelations::iterator itr = mGOQuestInvolvedRelations.begin(); itr != mGOQuestInvolvedRelations.end(); ++itr)
6739 GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
6740 if(!goInfo)
6741 sLog.outErrorDb("Table `gameobject_involvedrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
6742 else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
6743 sLog.outErrorDb("Table `gameobject_involvedrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
6747 void ObjectMgr::LoadCreatureQuestRelations()
6749 LoadQuestRelationsHelper(mCreatureQuestRelations,"creature_questrelation");
6751 for(QuestRelations::iterator itr = mCreatureQuestRelations.begin(); itr != mCreatureQuestRelations.end(); ++itr)
6753 CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
6754 if(!cInfo)
6755 sLog.outErrorDb("Table `creature_questrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
6756 else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
6757 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);
6761 void ObjectMgr::LoadCreatureInvolvedRelations()
6763 LoadQuestRelationsHelper(mCreatureQuestInvolvedRelations,"creature_involvedrelation");
6765 for(QuestRelations::iterator itr = mCreatureQuestInvolvedRelations.begin(); itr != mCreatureQuestInvolvedRelations.end(); ++itr)
6767 CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
6768 if(!cInfo)
6769 sLog.outErrorDb("Table `creature_involvedrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
6770 else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
6771 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);
6775 void ObjectMgr::LoadReservedPlayersNames()
6777 m_ReservedNames.clear(); // need for reload case
6779 QueryResult *result = WorldDatabase.Query("SELECT name FROM reserved_name");
6781 uint32 count = 0;
6783 if( !result )
6785 barGoLink bar( 1 );
6786 bar.step();
6788 sLog.outString();
6789 sLog.outString( ">> Loaded %u reserved player names", count );
6790 return;
6793 barGoLink bar( result->GetRowCount() );
6795 Field* fields;
6798 bar.step();
6799 fields = result->Fetch();
6800 std::string name= fields[0].GetCppString();
6802 std::wstring wstr;
6803 if(!Utf8toWStr (name,wstr))
6805 sLog.outError("Table `reserved_name` have invalid name: %s", name.c_str() );
6806 continue;
6809 wstrToLower(wstr);
6811 m_ReservedNames.insert(wstr);
6812 ++count;
6813 } while ( result->NextRow() );
6815 delete result;
6817 sLog.outString();
6818 sLog.outString( ">> Loaded %u reserved player names", count );
6821 bool ObjectMgr::IsReservedName( const std::string& name ) const
6823 std::wstring wstr;
6824 if(!Utf8toWStr (name,wstr))
6825 return false;
6827 wstrToLower(wstr);
6829 return m_ReservedNames.find(wstr) != m_ReservedNames.end();
6832 enum LanguageType
6834 LT_BASIC_LATIN = 0x0000,
6835 LT_EXTENDEN_LATIN = 0x0001,
6836 LT_CYRILLIC = 0x0002,
6837 LT_EAST_ASIA = 0x0004,
6838 LT_ANY = 0xFFFF
6841 static LanguageType GetRealmLanguageType(bool create)
6843 switch(sWorld.getConfig(CONFIG_REALM_ZONE))
6845 case REALM_ZONE_UNKNOWN: // any language
6846 case REALM_ZONE_DEVELOPMENT:
6847 case REALM_ZONE_TEST_SERVER:
6848 case REALM_ZONE_QA_SERVER:
6849 return LT_ANY;
6850 case REALM_ZONE_UNITED_STATES: // extended-Latin
6851 case REALM_ZONE_OCEANIC:
6852 case REALM_ZONE_LATIN_AMERICA:
6853 case REALM_ZONE_ENGLISH:
6854 case REALM_ZONE_GERMAN:
6855 case REALM_ZONE_FRENCH:
6856 case REALM_ZONE_SPANISH:
6857 return LT_EXTENDEN_LATIN;
6858 case REALM_ZONE_KOREA: // East-Asian
6859 case REALM_ZONE_TAIWAN:
6860 case REALM_ZONE_CHINA:
6861 return LT_EAST_ASIA;
6862 case REALM_ZONE_RUSSIAN: // Cyrillic
6863 return LT_CYRILLIC;
6864 default:
6865 return create ? LT_BASIC_LATIN : LT_ANY; // basic-Latin at create, any at login
6869 bool isValidString(std::wstring wstr, uint32 strictMask, bool numericOrSpace, bool create = false)
6871 if(strictMask==0) // any language, ignore realm
6873 if(isExtendedLatinString(wstr,numericOrSpace))
6874 return true;
6875 if(isCyrillicString(wstr,numericOrSpace))
6876 return true;
6877 if(isEastAsianString(wstr,numericOrSpace))
6878 return true;
6879 return false;
6882 if(strictMask & 0x2) // realm zone specific
6884 LanguageType lt = GetRealmLanguageType(create);
6885 if(lt & LT_EXTENDEN_LATIN)
6886 if(isExtendedLatinString(wstr,numericOrSpace))
6887 return true;
6888 if(lt & LT_CYRILLIC)
6889 if(isCyrillicString(wstr,numericOrSpace))
6890 return true;
6891 if(lt & LT_EAST_ASIA)
6892 if(isEastAsianString(wstr,numericOrSpace))
6893 return true;
6896 if(strictMask & 0x1) // basic Latin
6898 if(isBasicLatinString(wstr,numericOrSpace))
6899 return true;
6902 return false;
6905 uint8 ObjectMgr::CheckPlayerName( const std::string& name, bool create )
6907 std::wstring wname;
6908 if(!Utf8toWStr(name,wname))
6909 return CHAR_NAME_INVALID_CHARACTER;
6911 if(wname.size() > MAX_PLAYER_NAME)
6912 return CHAR_NAME_TOO_LONG;
6914 uint32 minName = sWorld.getConfig(CONFIG_MIN_PLAYER_NAME);
6915 if(wname.size() < minName)
6916 return CHAR_NAME_TOO_SHORT;
6918 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_PLAYER_NAMES);
6919 if(!isValidString(wname,strictMask,false,create))
6920 return CHAR_NAME_MIXED_LANGUAGES;
6922 return CHAR_NAME_SUCCESS;
6925 bool ObjectMgr::IsValidCharterName( const std::string& name )
6927 std::wstring wname;
6928 if(!Utf8toWStr(name,wname))
6929 return false;
6931 if(wname.size() > MAX_CHARTER_NAME)
6932 return false;
6934 uint32 minName = sWorld.getConfig(CONFIG_MIN_CHARTER_NAME);
6935 if(wname.size() < minName)
6936 return false;
6938 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_CHARTER_NAMES);
6940 return isValidString(wname,strictMask,true);
6943 PetNameInvalidReason ObjectMgr::CheckPetName( const std::string& name )
6945 std::wstring wname;
6946 if(!Utf8toWStr(name,wname))
6947 return PET_NAME_INVALID;
6949 if(wname.size() > MAX_PET_NAME)
6950 return PET_NAME_TOO_LONG;
6952 uint32 minName = sWorld.getConfig(CONFIG_MIN_PET_NAME);
6953 if(wname.size() < minName)
6954 return PET_NAME_TOO_SHORT;
6956 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_PET_NAMES);
6957 if(!isValidString(wname,strictMask,false))
6958 return PET_NAME_MIXED_LANGUAGES;
6960 return PET_NAME_SUCCESS;
6963 int ObjectMgr::GetIndexForLocale( LocaleConstant loc )
6965 if(loc==LOCALE_enUS)
6966 return -1;
6968 for(size_t i=0;i < m_LocalForIndex.size(); ++i)
6969 if(m_LocalForIndex[i]==loc)
6970 return i;
6972 return -1;
6975 LocaleConstant ObjectMgr::GetLocaleForIndex(int i)
6977 if (i<0 || i>=m_LocalForIndex.size())
6978 return LOCALE_enUS;
6980 return m_LocalForIndex[i];
6983 int ObjectMgr::GetOrNewIndexForLocale( LocaleConstant loc )
6985 if(loc==LOCALE_enUS)
6986 return -1;
6988 for(size_t i=0;i < m_LocalForIndex.size(); ++i)
6989 if(m_LocalForIndex[i]==loc)
6990 return i;
6992 m_LocalForIndex.push_back(loc);
6993 return m_LocalForIndex.size()-1;
6996 void ObjectMgr::LoadGameObjectForQuests()
6998 mGameObjectForQuestSet.clear(); // need for reload case
7000 if( !sGOStorage.MaxEntry )
7002 barGoLink bar( 1 );
7003 bar.step();
7004 sLog.outString();
7005 sLog.outString( ">> Loaded 0 GameObjects for quests" );
7006 return;
7009 barGoLink bar( sGOStorage.MaxEntry - 1 );
7010 uint32 count = 0;
7012 // collect GO entries for GO that must activated
7013 for(uint32 go_entry = 1; go_entry < sGOStorage.MaxEntry; ++go_entry)
7015 bar.step();
7016 GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(go_entry);
7017 if(!goInfo)
7018 continue;
7020 switch(goInfo->type)
7022 // scan GO chest with loot including quest items
7023 case GAMEOBJECT_TYPE_CHEST:
7025 uint32 loot_id = goInfo->GetLootId();
7027 // find quest loot for GO
7028 if(LootTemplates_Gameobject.HaveQuestLootFor(loot_id))
7030 mGameObjectForQuestSet.insert(go_entry);
7031 ++count;
7033 break;
7035 case GAMEOBJECT_TYPE_GOOBER:
7037 if(goInfo->goober.questId) //quests objects
7039 mGameObjectForQuestSet.insert(go_entry);
7040 count++;
7042 break;
7044 default:
7045 break;
7049 sLog.outString();
7050 sLog.outString( ">> Loaded %u GameObjects for quests", count );
7053 bool ObjectMgr::LoadMangosStrings(DatabaseType& db, char const* table, int32 min_value, int32 max_value)
7055 int32 start_value = min_value;
7056 int32 end_value = max_value;
7057 // some string can have negative indexes range
7058 if (start_value < 0)
7060 if (end_value >= start_value)
7062 sLog.outErrorDb("Table '%s' attempt loaded with invalid range (%d - %d), strings not loaded.",table,min_value,max_value);
7063 return false;
7066 // real range (max+1,min+1) exaple: (-10,-1000) -> -999...-10+1
7067 std::swap(start_value,end_value);
7068 ++start_value;
7069 ++end_value;
7071 else
7073 if (start_value >= end_value)
7075 sLog.outErrorDb("Table '%s' attempt loaded with invalid range (%d - %d), strings not loaded.",table,min_value,max_value);
7076 return false;
7080 // cleanup affected map part for reloading case
7081 for(MangosStringLocaleMap::iterator itr = mMangosStringLocaleMap.begin(); itr != mMangosStringLocaleMap.end();)
7083 if (itr->first >= start_value && itr->first < end_value)
7084 mMangosStringLocaleMap.erase(itr++);
7085 else
7086 ++itr;
7089 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);
7091 if (!result)
7093 barGoLink bar(1);
7095 bar.step();
7097 sLog.outString();
7098 if (min_value == MIN_MANGOS_STRING_ID) // error only in case internal strings
7099 sLog.outErrorDb(">> Loaded 0 mangos strings. DB table `%s` is empty. Cannot continue.",table);
7100 else
7101 sLog.outString(">> Loaded 0 string templates. DB table `%s` is empty.",table);
7102 return false;
7105 uint32 count = 0;
7107 barGoLink bar(result->GetRowCount());
7111 Field *fields = result->Fetch();
7112 bar.step();
7114 int32 entry = fields[0].GetInt32();
7116 if (entry==0)
7118 sLog.outErrorDb("Table `%s` contain reserved entry 0, ignored.",table);
7119 continue;
7121 else if (entry < start_value || entry >= end_value)
7123 sLog.outErrorDb("Table `%s` contain entry %i out of allowed range (%d - %d), ignored.",table,entry,min_value,max_value);
7124 continue;
7127 MangosStringLocale& data = mMangosStringLocaleMap[entry];
7129 if (data.Content.size() > 0)
7131 sLog.outErrorDb("Table `%s` contain data for already loaded entry %i (from another table?), ignored.",table,entry);
7132 continue;
7135 data.Content.resize(1);
7136 ++count;
7138 // 0 -> default, idx in to idx+1
7139 data.Content[0] = fields[1].GetCppString();
7141 for(int i = 1; i < MAX_LOCALE; ++i)
7143 std::string str = fields[i+1].GetCppString();
7144 if (!str.empty())
7146 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
7147 if (idx >= 0)
7149 // 0 -> default, idx in to idx+1
7150 if (data.Content.size() <= idx+1)
7151 data.Content.resize(idx+2);
7153 data.Content[idx+1] = str;
7157 } while (result->NextRow());
7159 delete result;
7161 sLog.outString();
7162 if (min_value == MIN_MANGOS_STRING_ID)
7163 sLog.outString( ">> Loaded %u MaNGOS strings from table %s", count,table);
7164 else
7165 sLog.outString( ">> Loaded %u string templates from %s", count,table);
7167 return true;
7170 const char *ObjectMgr::GetMangosString(int32 entry, int locale_idx) const
7172 // locale_idx==-1 -> default, locale_idx >= 0 in to idx+1
7173 // Content[0] always exist if exist MangosStringLocale
7174 if(MangosStringLocale const *msl = GetMangosStringLocale(entry))
7176 if(msl->Content.size() > locale_idx+1 && !msl->Content[locale_idx+1].empty())
7177 return msl->Content[locale_idx+1].c_str();
7178 else
7179 return msl->Content[0].c_str();
7182 if(entry > 0)
7183 sLog.outErrorDb("Entry %i not found in `mangos_string` table.",entry);
7184 else
7185 sLog.outErrorDb("Mangos string entry %i not found in DB.",entry);
7186 return "<error>";
7189 void ObjectMgr::LoadFishingBaseSkillLevel()
7191 mFishingBaseForArea.clear(); // for reload case
7193 uint32 count = 0;
7194 QueryResult *result = WorldDatabase.Query("SELECT entry,skill FROM skill_fishing_base_level");
7196 if( !result )
7198 barGoLink bar( 1 );
7200 bar.step();
7202 sLog.outString();
7203 sLog.outErrorDb(">> Loaded `skill_fishing_base_level`, table is empty!");
7204 return;
7207 barGoLink bar( result->GetRowCount() );
7211 bar.step();
7213 Field *fields = result->Fetch();
7214 uint32 entry = fields[0].GetUInt32();
7215 int32 skill = fields[1].GetInt32();
7217 AreaTableEntry const* fArea = GetAreaEntryByAreaID(entry);
7218 if(!fArea)
7220 sLog.outErrorDb("AreaId %u defined in `skill_fishing_base_level` does not exist",entry);
7221 continue;
7224 mFishingBaseForArea[entry] = skill;
7225 ++count;
7227 while (result->NextRow());
7229 delete result;
7231 sLog.outString();
7232 sLog.outString( ">> Loaded %u areas for fishing base skill level", count );
7235 // Searches for the same condition already in Conditions store
7236 // Returns Id if found, else adds it to Conditions and returns Id
7237 uint16 ObjectMgr::GetConditionId( ConditionType condition, uint32 value1, uint32 value2 )
7239 PlayerCondition lc = PlayerCondition(condition, value1, value2);
7240 for (uint16 i=0; i < mConditions.size(); ++i)
7242 if (lc == mConditions[i])
7243 return i;
7246 mConditions.push_back(lc);
7248 if(mConditions.size() > 0xFFFF)
7250 sLog.outError("Conditions store overflow! Current and later loaded conditions will ignored!");
7251 return 0;
7254 return mConditions.size() - 1;
7257 bool ObjectMgr::CheckDeclinedNames( std::wstring mainpart, DeclinedName const& names )
7259 for(int i =0; i < MAX_DECLINED_NAME_CASES; ++i)
7261 std::wstring wname;
7262 if(!Utf8toWStr(names.name[i],wname))
7263 return false;
7265 if(mainpart!=GetMainPartOfName(wname,i+1))
7266 return false;
7268 return true;
7271 uint32 ObjectMgr::GetAreaTriggerScriptId(uint32 trigger_id)
7273 AreaTriggerScriptMap::const_iterator i = mAreaTriggerScripts.find(trigger_id);
7274 if(i!= mAreaTriggerScripts.end())
7275 return i->second;
7276 return 0;
7279 // Checks if player meets the condition
7280 bool PlayerCondition::Meets(Player const * player) const
7282 if( !player )
7283 return false; // player not present, return false
7285 switch (condition)
7287 case CONDITION_NONE:
7288 return true; // empty condition, always met
7289 case CONDITION_AURA:
7290 return player->HasAura(value1, value2);
7291 case CONDITION_ITEM:
7292 return player->HasItemCount(value1, value2);
7293 case CONDITION_ITEM_EQUIPPED:
7294 return player->HasItemOrGemWithIdEquipped(value1,1);
7295 case CONDITION_ZONEID:
7296 return player->GetZoneId() == value1;
7297 case CONDITION_REPUTATION_RANK:
7299 FactionEntry const* faction = sFactionStore.LookupEntry(value1);
7300 return faction && player->GetReputationMgr().GetRank(faction) >= int32(value2);
7302 case CONDITION_TEAM:
7303 return player->GetTeam() == value1;
7304 case CONDITION_SKILL:
7305 return player->HasSkill(value1) && player->GetBaseSkillValue(value1) >= value2;
7306 case CONDITION_QUESTREWARDED:
7307 return player->GetQuestRewardStatus(value1);
7308 case CONDITION_QUESTTAKEN:
7310 QuestStatus status = player->GetQuestStatus(value1);
7311 return (status == QUEST_STATUS_INCOMPLETE);
7313 case CONDITION_AD_COMMISSION_AURA:
7315 Unit::AuraMap const& auras = player->GetAuras();
7316 for(Unit::AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
7317 if((itr->second->GetSpellProto()->Attributes & 0x1000010) && itr->second->GetSpellProto()->SpellVisual[0]==3580)
7318 return true;
7319 return false;
7321 case CONDITION_NO_AURA:
7322 return !player->HasAura(value1, value2);
7323 case CONDITION_ACTIVE_EVENT:
7324 return sGameEventMgr.IsActiveEvent(value1);
7325 case CONDITION_AREA_FLAG:
7327 if (AreaTableEntry const *pAreaEntry = GetAreaEntryByAreaID(player->GetAreaId()))
7329 if ((!value1 || (pAreaEntry->flags & value1)) && (!value2 || !(pAreaEntry->flags & value2)))
7330 return true;
7332 return false;
7334 case CONDITION_RACE_CLASS:
7335 if ((!value1 || (player->getRaceMask() & value1)) && (!value2 || (player->getClassMask() & value2)))
7336 return true;
7337 return false;
7338 case CONDITION_LEVEL:
7340 switch(value2)
7342 case 0: return player->getLevel() == value1;
7343 case 1: return player->getLevel() >= value1;
7344 case 2: return player->getLevel() <= value1;
7346 return false;
7348 default:
7349 return false;
7353 // Verification of condition values validity
7354 bool PlayerCondition::IsValid(ConditionType condition, uint32 value1, uint32 value2)
7356 if( condition >= MAX_CONDITION) // Wrong condition type
7358 sLog.outErrorDb("Condition has bad type of %u, skipped ", condition );
7359 return false;
7362 switch (condition)
7364 case CONDITION_AURA:
7366 if(!sSpellStore.LookupEntry(value1))
7368 sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
7369 return false;
7371 if(value2 > 2)
7373 sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..2), skipped", value2);
7374 return false;
7376 break;
7378 case CONDITION_ITEM:
7380 ItemPrototype const *proto = ObjectMgr::GetItemPrototype(value1);
7381 if(!proto)
7383 sLog.outErrorDb("Item condition requires to have non existing item (%u), skipped", value1);
7384 return false;
7386 break;
7388 case CONDITION_ITEM_EQUIPPED:
7390 ItemPrototype const *proto = ObjectMgr::GetItemPrototype(value1);
7391 if(!proto)
7393 sLog.outErrorDb("ItemEquipped condition requires to have non existing item (%u) equipped, skipped", value1);
7394 return false;
7396 break;
7398 case CONDITION_ZONEID:
7400 AreaTableEntry const* areaEntry = GetAreaEntryByAreaID(value1);
7401 if(!areaEntry)
7403 sLog.outErrorDb("Zone condition requires to be in non existing area (%u), skipped", value1);
7404 return false;
7406 if(areaEntry->zone != 0)
7408 sLog.outErrorDb("Zone condition requires to be in area (%u) which is a subzone but zone expected, skipped", value1);
7409 return false;
7411 break;
7413 case CONDITION_REPUTATION_RANK:
7415 FactionEntry const* factionEntry = sFactionStore.LookupEntry(value1);
7416 if(!factionEntry)
7418 sLog.outErrorDb("Reputation condition requires to have reputation non existing faction (%u), skipped", value1);
7419 return false;
7421 break;
7423 case CONDITION_TEAM:
7425 if (value1 != ALLIANCE && value1 != HORDE)
7427 sLog.outErrorDb("Team condition specifies unknown team (%u), skipped", value1);
7428 return false;
7430 break;
7432 case CONDITION_SKILL:
7434 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(value1);
7435 if (!pSkill)
7437 sLog.outErrorDb("Skill condition specifies non-existing skill (%u), skipped", value1);
7438 return false;
7440 if (value2 < 1 || value2 > sWorld.GetConfigMaxSkillValue() )
7442 sLog.outErrorDb("Skill condition specifies invalid skill value (%u), skipped", value2);
7443 return false;
7445 break;
7447 case CONDITION_QUESTREWARDED:
7448 case CONDITION_QUESTTAKEN:
7450 Quest const *Quest = sObjectMgr.GetQuestTemplate(value1);
7451 if (!Quest)
7453 sLog.outErrorDb("Quest condition specifies non-existing quest (%u), skipped", value1);
7454 return false;
7456 if(value2)
7457 sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
7458 break;
7460 case CONDITION_AD_COMMISSION_AURA:
7462 if(value1)
7463 sLog.outErrorDb("Quest condition has useless data in value1 (%u)!", value1);
7464 if(value2)
7465 sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
7466 break;
7468 case CONDITION_NO_AURA:
7470 if(!sSpellStore.LookupEntry(value1))
7472 sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
7473 return false;
7475 if(value2 > 2)
7477 sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..2), skipped", value2);
7478 return false;
7480 break;
7482 case CONDITION_ACTIVE_EVENT:
7484 GameEventMgr::GameEventDataMap const& events = sGameEventMgr.GetEventMap();
7485 if(value1 >=events.size() || !events[value1].isValid())
7487 sLog.outErrorDb("Active event condition requires existed event id (%u), skipped", value1);
7488 return false;
7490 break;
7492 case CONDITION_AREA_FLAG:
7494 if (!value1 && !value2)
7496 sLog.outErrorDb("Area flag condition has both values like 0, skipped");
7497 return false;
7499 break;
7501 case CONDITION_RACE_CLASS:
7503 if (!value1 && !value2)
7505 sLog.outErrorDb("Race_class condition has both values like 0, skipped");
7506 return false;
7509 if (value1 && !(value1 & RACEMASK_ALL_PLAYABLE))
7511 sLog.outErrorDb("Race_class condition has invalid player class %u, skipped", value1);
7512 return false;
7515 if (value2 && !(value2 & CLASSMASK_ALL_PLAYABLE))
7517 sLog.outErrorDb("Race_class condition has invalid race mask %u, skipped", value2);
7518 return false;
7520 break;
7522 case CONDITION_LEVEL:
7524 if (!value1 || value1 > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
7526 sLog.outErrorDb("Level condition has invalid level %u, skipped", value1);
7527 return false;
7530 if (value2 > 2)
7532 sLog.outErrorDb("Level condition has invalid argument %u (must be 0..2), skipped", value2);
7533 return false;
7536 break;
7538 case CONDITION_NONE:
7539 break;
7541 return true;
7544 SkillRangeType GetSkillRangeType(SkillLineEntry const *pSkill, bool racial)
7546 switch(pSkill->categoryId)
7548 case SKILL_CATEGORY_LANGUAGES: return SKILL_RANGE_LANGUAGE;
7549 case SKILL_CATEGORY_WEAPON:
7550 if(pSkill->id!=SKILL_FIST_WEAPONS)
7551 return SKILL_RANGE_LEVEL;
7552 else
7553 return SKILL_RANGE_MONO;
7554 case SKILL_CATEGORY_ARMOR:
7555 case SKILL_CATEGORY_CLASS:
7556 if(pSkill->id != SKILL_LOCKPICKING)
7557 return SKILL_RANGE_MONO;
7558 else
7559 return SKILL_RANGE_LEVEL;
7560 case SKILL_CATEGORY_SECONDARY:
7561 case SKILL_CATEGORY_PROFESSION:
7562 // not set skills for professions and racial abilities
7563 if(IsProfessionSkill(pSkill->id))
7564 return SKILL_RANGE_RANK;
7565 else if(racial)
7566 return SKILL_RANGE_NONE;
7567 else
7568 return SKILL_RANGE_MONO;
7569 default:
7570 case SKILL_CATEGORY_ATTRIBUTES: //not found in dbc
7571 case SKILL_CATEGORY_GENERIC: //only GENERIC(DND)
7572 return SKILL_RANGE_NONE;
7576 void ObjectMgr::LoadGameTele()
7578 m_GameTeleMap.clear(); // for reload case
7580 uint32 count = 0;
7581 QueryResult *result = WorldDatabase.Query("SELECT id, position_x, position_y, position_z, orientation, map, name FROM game_tele");
7583 if( !result )
7585 barGoLink bar( 1 );
7587 bar.step();
7589 sLog.outString();
7590 sLog.outErrorDb(">> Loaded `game_tele`, table is empty!");
7591 return;
7594 barGoLink bar( result->GetRowCount() );
7598 bar.step();
7600 Field *fields = result->Fetch();
7602 uint32 id = fields[0].GetUInt32();
7604 GameTele gt;
7606 gt.position_x = fields[1].GetFloat();
7607 gt.position_y = fields[2].GetFloat();
7608 gt.position_z = fields[3].GetFloat();
7609 gt.orientation = fields[4].GetFloat();
7610 gt.mapId = fields[5].GetUInt32();
7611 gt.name = fields[6].GetCppString();
7613 if(!MapManager::IsValidMapCoord(gt.mapId,gt.position_x,gt.position_y,gt.position_z,gt.orientation))
7615 sLog.outErrorDb("Wrong position for id %u (name: %s) in `game_tele` table, ignoring.",id,gt.name.c_str());
7616 continue;
7619 if(!Utf8toWStr(gt.name,gt.wnameLow))
7621 sLog.outErrorDb("Wrong UTF8 name for id %u in `game_tele` table, ignoring.",id);
7622 continue;
7625 wstrToLower( gt.wnameLow );
7627 m_GameTeleMap[id] = gt;
7629 ++count;
7631 while (result->NextRow());
7632 delete result;
7634 sLog.outString();
7635 sLog.outString( ">> Loaded %u GameTeleports", count );
7638 GameTele const* ObjectMgr::GetGameTele(const std::string& name) const
7640 // explicit name case
7641 std::wstring wname;
7642 if(!Utf8toWStr(name,wname))
7643 return false;
7645 // converting string that we try to find to lower case
7646 wstrToLower( wname );
7648 // Alternative first GameTele what contains wnameLow as substring in case no GameTele location found
7649 const GameTele* alt = NULL;
7650 for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
7651 if(itr->second.wnameLow == wname)
7652 return &itr->second;
7653 else if (alt == NULL && itr->second.wnameLow.find(wname) != std::wstring::npos)
7654 alt = &itr->second;
7656 return alt;
7659 bool ObjectMgr::AddGameTele(GameTele& tele)
7661 // find max id
7662 uint32 new_id = 0;
7663 for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
7664 if(itr->first > new_id)
7665 new_id = itr->first;
7667 // use next
7668 ++new_id;
7670 if(!Utf8toWStr(tele.name,tele.wnameLow))
7671 return false;
7673 wstrToLower( tele.wnameLow );
7675 m_GameTeleMap[new_id] = tele;
7677 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')",
7678 new_id,tele.position_x,tele.position_y,tele.position_z,tele.orientation,tele.mapId,tele.name.c_str());
7681 bool ObjectMgr::DeleteGameTele(const std::string& name)
7683 // explicit name case
7684 std::wstring wname;
7685 if(!Utf8toWStr(name,wname))
7686 return false;
7688 // converting string that we try to find to lower case
7689 wstrToLower( wname );
7691 for(GameTeleMap::iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
7693 if(itr->second.wnameLow == wname)
7695 WorldDatabase.PExecuteLog("DELETE FROM game_tele WHERE name = '%s'",itr->second.name.c_str());
7696 m_GameTeleMap.erase(itr);
7697 return true;
7701 return false;
7704 void ObjectMgr::LoadMailLevelRewards()
7706 m_mailLevelRewardMap.clear(); // for reload case
7708 uint32 count = 0;
7709 QueryResult *result = WorldDatabase.Query("SELECT level, raceMask, mailTemplateId, senderEntry FROM mail_level_reward");
7711 if( !result )
7713 barGoLink bar( 1 );
7715 bar.step();
7717 sLog.outString();
7718 sLog.outErrorDb(">> Loaded `mail_level_reward`, table is empty!");
7719 return;
7722 barGoLink bar( result->GetRowCount() );
7726 bar.step();
7728 Field *fields = result->Fetch();
7730 uint8 level = fields[0].GetUInt8();
7731 uint32 raceMask = fields[1].GetUInt32();
7732 uint32 mailTemplateId = fields[2].GetUInt32();
7733 uint32 senderEntry = fields[3].GetUInt32();
7735 if(level > MAX_LEVEL)
7737 sLog.outErrorDb("Table `mail_level_reward` have data for level %u that more supported by client (%u), ignoring.",level,MAX_LEVEL);
7738 continue;
7741 if(!(raceMask & RACEMASK_ALL_PLAYABLE))
7743 sLog.outErrorDb("Table `mail_level_reward` have raceMask (%u) for level %u that not include any player races, ignoring.",raceMask,level);
7744 continue;
7747 if(!sMailTemplateStore.LookupEntry(mailTemplateId))
7749 sLog.outErrorDb("Table `mail_level_reward` have invalid mailTemplateId (%u) for level %u that invalid not include any player races, ignoring.",mailTemplateId,level);
7750 continue;
7753 if(!GetCreatureTemplateStore(senderEntry))
7755 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);
7756 continue;
7759 m_mailLevelRewardMap[level].push_back(MailLevelReward(raceMask,mailTemplateId,senderEntry));
7761 ++count;
7763 while (result->NextRow());
7764 delete result;
7766 sLog.outString();
7767 sLog.outString( ">> Loaded %u level dependent mail rewards,", count );
7770 void ObjectMgr::LoadTrainerSpell()
7772 // For reload case
7773 for (CacheTrainerSpellMap::iterator itr = m_mCacheTrainerSpellMap.begin(); itr != m_mCacheTrainerSpellMap.end(); ++itr)
7774 itr->second.Clear();
7775 m_mCacheTrainerSpellMap.clear();
7777 std::set<uint32> skip_trainers;
7779 QueryResult *result = WorldDatabase.Query("SELECT entry, spell,spellcost,reqskill,reqskillvalue,reqlevel FROM npc_trainer");
7781 if( !result )
7783 barGoLink bar( 1 );
7785 bar.step();
7787 sLog.outString();
7788 sLog.outErrorDb(">> Loaded `npc_trainer`, table is empty!");
7789 return;
7792 barGoLink bar( result->GetRowCount() );
7794 std::set<uint32> talentIds;
7796 uint32 count = 0;
7799 bar.step();
7801 Field* fields = result->Fetch();
7803 uint32 entry = fields[0].GetUInt32();
7804 uint32 spell = fields[1].GetUInt32();
7806 CreatureInfo const* cInfo = GetCreatureTemplate(entry);
7808 if(!cInfo)
7810 sLog.outErrorDb("Table `npc_trainer` have entry for not existed creature template (Entry: %u), ignore", entry);
7811 continue;
7814 if(!(cInfo->npcflag & UNIT_NPC_FLAG_TRAINER))
7816 if (skip_trainers.find(entry) == skip_trainers.end())
7818 sLog.outErrorDb("Table `npc_trainer` have data for not creature template (Entry: %u) without trainer flag, ignore", entry);
7819 skip_trainers.insert(entry);
7821 continue;
7824 SpellEntry const *spellinfo = sSpellStore.LookupEntry(spell);
7825 if(!spellinfo)
7827 sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u ) has non existing spell %u, ignore", entry,spell);
7828 continue;
7831 if(!SpellMgr::IsSpellValid(spellinfo))
7833 sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u) has broken learning spell %u, ignore", entry, spell);
7834 continue;
7837 if(GetTalentSpellCost(spell))
7839 if (talentIds.find(spell) == talentIds.end())
7841 sLog.outErrorDb("Table `npc_trainer` has talent as learning spell %u, ignore", spell);
7842 talentIds.insert(spell);
7844 continue;
7847 TrainerSpellData& data = m_mCacheTrainerSpellMap[entry];
7849 TrainerSpell& trainerSpell = data.spellList[spell];
7850 trainerSpell.spell = spell;
7851 trainerSpell.spellCost = fields[2].GetUInt32();
7852 trainerSpell.reqSkill = fields[3].GetUInt32();
7853 trainerSpell.reqSkillValue = fields[4].GetUInt32();
7854 trainerSpell.reqLevel = fields[5].GetUInt32();
7856 if(!trainerSpell.reqLevel)
7857 trainerSpell.reqLevel = spellinfo->spellLevel;
7859 // calculate learned spell for profession case when stored cast-spell
7860 trainerSpell.learnedSpell = spell;
7861 for(int i = 0; i <3; ++i)
7863 if(spellinfo->Effect[i] != SPELL_EFFECT_LEARN_SPELL)
7864 continue;
7865 if(SpellMgr::IsProfessionOrRidingSpell(spellinfo->EffectTriggerSpell[i]))
7867 trainerSpell.learnedSpell = spellinfo->EffectTriggerSpell[i];
7868 break;
7872 if(SpellMgr::IsProfessionSpell(trainerSpell.learnedSpell))
7873 data.trainerType = 2;
7875 ++count;
7877 } while (result->NextRow());
7878 delete result;
7880 sLog.outString();
7881 sLog.outString( ">> Loaded %d Trainers", count );
7884 void ObjectMgr::LoadVendors()
7886 // For reload case
7887 for (CacheVendorItemMap::iterator itr = m_mCacheVendorItemMap.begin(); itr != m_mCacheVendorItemMap.end(); ++itr)
7888 itr->second.Clear();
7889 m_mCacheVendorItemMap.clear();
7891 std::set<uint32> skip_vendors;
7893 QueryResult *result = WorldDatabase.Query("SELECT entry, item, maxcount, incrtime, ExtendedCost FROM npc_vendor");
7894 if( !result )
7896 barGoLink bar( 1 );
7898 bar.step();
7900 sLog.outString();
7901 sLog.outErrorDb(">> Loaded `npc_vendor`, table is empty!");
7902 return;
7905 barGoLink bar( result->GetRowCount() );
7907 uint32 count = 0;
7910 bar.step();
7911 Field* fields = result->Fetch();
7913 uint32 entry = fields[0].GetUInt32();
7914 uint32 item_id = fields[1].GetUInt32();
7915 uint32 maxcount = fields[2].GetUInt32();
7916 uint32 incrtime = fields[3].GetUInt32();
7917 uint32 ExtendedCost = fields[4].GetUInt32();
7919 if(!IsVendorItemValid(entry,item_id,maxcount,incrtime,ExtendedCost,NULL,&skip_vendors))
7920 continue;
7922 VendorItemData& vList = m_mCacheVendorItemMap[entry];
7924 vList.AddItem(item_id,maxcount,incrtime,ExtendedCost);
7925 ++count;
7927 } while (result->NextRow());
7928 delete result;
7930 sLog.outString();
7931 sLog.outString( ">> Loaded %d Vendors ", count );
7934 void ObjectMgr::LoadNpcTextId()
7937 m_mCacheNpcTextIdMap.clear();
7939 QueryResult* result = WorldDatabase.Query("SELECT npc_guid, textid FROM npc_gossip");
7940 if( !result )
7942 barGoLink bar( 1 );
7944 bar.step();
7946 sLog.outString();
7947 sLog.outErrorDb(">> Loaded `npc_gossip`, table is empty!");
7948 return;
7951 barGoLink bar( result->GetRowCount() );
7953 uint32 count = 0;
7954 uint32 guid,textid;
7957 bar.step();
7959 Field* fields = result->Fetch();
7961 guid = fields[0].GetUInt32();
7962 textid = fields[1].GetUInt32();
7964 if (!GetCreatureData(guid))
7966 sLog.outErrorDb("Table `npc_gossip` have not existed creature (GUID: %u) entry, ignore. ",guid);
7967 continue;
7969 if (!GetGossipText(textid))
7971 sLog.outErrorDb("Table `npc_gossip` for creature (GUID: %u) have wrong Textid (%u), ignore. ", guid, textid);
7972 continue;
7975 m_mCacheNpcTextIdMap[guid] = textid ;
7976 ++count;
7978 } while (result->NextRow());
7979 delete result;
7981 sLog.outString();
7982 sLog.outString( ">> Loaded %d NpcTextId ", count );
7985 void ObjectMgr::LoadGossipMenu()
7987 m_mGossipMenusMap.clear();
7989 QueryResult* result = WorldDatabase.Query("SELECT entry, text_id, "
7990 "cond_1, cond_1_val_1, cond_1_val_2, cond_2, cond_2_val_1, cond_2_val_2 FROM gossip_menu");
7992 if (!result)
7994 barGoLink bar(1);
7996 bar.step();
7998 sLog.outString();
7999 sLog.outErrorDb(">> Loaded gossip_menu, table is empty!");
8000 return;
8003 barGoLink bar( result->GetRowCount() );
8005 uint32 count = 0;
8009 bar.step();
8011 Field* fields = result->Fetch();
8013 GossipMenus gMenu;
8015 gMenu.entry = fields[0].GetUInt32();
8016 gMenu.text_id = fields[1].GetUInt32();
8018 ConditionType cond_1 = (ConditionType)fields[2].GetUInt32();
8019 uint32 cond_1_val_1 = fields[3].GetUInt32();
8020 uint32 cond_1_val_2 = fields[4].GetUInt32();
8021 ConditionType cond_2 = (ConditionType)fields[5].GetUInt32();
8022 uint32 cond_2_val_1 = fields[6].GetUInt32();
8023 uint32 cond_2_val_2 = fields[7].GetUInt32();
8025 if (!GetGossipText(gMenu.text_id))
8027 sLog.outErrorDb("Table gossip_menu entry %u are using non-existing text_id %u", gMenu.entry, gMenu.text_id);
8028 continue;
8031 if (!PlayerCondition::IsValid(cond_1, cond_1_val_1, cond_1_val_2))
8033 sLog.outErrorDb("Table gossip_menu entry %u, invalid condition 1 for id %u", gMenu.entry, gMenu.text_id);
8034 continue;
8037 if (!PlayerCondition::IsValid(cond_2, cond_2_val_1, cond_2_val_2))
8039 sLog.outErrorDb("Table gossip_menu entry %u, invalid condition 2 for id %u", gMenu.entry, gMenu.text_id);
8040 continue;
8043 gMenu.cond_1 = GetConditionId(cond_1, cond_1_val_1, cond_1_val_2);
8044 gMenu.cond_2 = GetConditionId(cond_2, cond_2_val_1, cond_2_val_2);
8046 m_mGossipMenusMap.insert(GossipMenusMap::value_type(gMenu.entry, gMenu));
8048 ++count;
8050 while(result->NextRow());
8052 delete result;
8054 sLog.outString();
8055 sLog.outString( ">> Loaded %u gossip_menu entries", count);
8058 void ObjectMgr::LoadGossipMenuItems()
8060 m_mGossipMenuItemsMap.clear();
8062 QueryResult *result = WorldDatabase.Query(
8063 "SELECT menu_id, id, option_icon, option_text, option_id, npc_option_npcflag, "
8064 "action_menu_id, action_poi_id, action_script_id, box_coded, box_money, box_text, "
8065 "cond_1, cond_1_val_1, cond_1_val_2, "
8066 "cond_2, cond_2_val_1, cond_2_val_2, "
8067 "cond_3, cond_3_val_1, cond_3_val_2 "
8068 "FROM gossip_menu_option");
8070 if (!result)
8072 barGoLink bar(1);
8074 bar.step();
8076 sLog.outString();
8077 sLog.outErrorDb(">> Loaded gossip_menu_option, table is empty!");
8078 return;
8081 barGoLink bar(result->GetRowCount());
8083 uint32 count = 0;
8085 std::set<uint32> gossipScriptSet;
8087 for(ScriptMapMap::const_iterator itr = sGossipScripts.begin(); itr != sGossipScripts.end(); ++itr)
8088 gossipScriptSet.insert(itr->first);
8092 bar.step();
8094 Field* fields = result->Fetch();
8096 GossipMenuItems gMenuItem;
8098 gMenuItem.menu_id = fields[0].GetUInt32();
8099 gMenuItem.id = fields[1].GetUInt32();
8100 gMenuItem.option_icon = fields[2].GetUInt8();
8101 gMenuItem.option_text = fields[3].GetCppString();
8102 gMenuItem.option_id = fields[4].GetUInt32();
8103 gMenuItem.npc_option_npcflag = fields[5].GetUInt32();
8104 gMenuItem.action_menu_id = fields[6].GetUInt32();
8105 gMenuItem.action_poi_id = fields[7].GetUInt32();
8106 gMenuItem.action_script_id = fields[8].GetUInt32();
8107 gMenuItem.box_coded = fields[9].GetUInt8() != 0;
8108 gMenuItem.box_money = fields[10].GetUInt32();
8109 gMenuItem.box_text = fields[11].GetCppString();
8111 ConditionType cond_1 = (ConditionType)fields[12].GetUInt32();
8112 uint32 cond_1_val_1 = fields[13].GetUInt32();
8113 uint32 cond_1_val_2 = fields[14].GetUInt32();
8114 ConditionType cond_2 = (ConditionType)fields[15].GetUInt32();
8115 uint32 cond_2_val_1 = fields[16].GetUInt32();
8116 uint32 cond_2_val_2 = fields[17].GetUInt32();
8117 ConditionType cond_3 = (ConditionType)fields[18].GetUInt32();
8118 uint32 cond_3_val_1 = fields[19].GetUInt32();
8119 uint32 cond_3_val_2 = fields[20].GetUInt32();
8121 if (!PlayerCondition::IsValid(cond_1, cond_1_val_1, cond_1_val_2))
8123 sLog.outErrorDb("Table gossip_menu_option menu %u, invalid condition 1 for id %u", gMenuItem.menu_id, gMenuItem.id);
8124 continue;
8126 if (!PlayerCondition::IsValid(cond_2, cond_2_val_1, cond_2_val_2))
8128 sLog.outErrorDb("Table gossip_menu_option menu %u, invalid condition 2 for id %u", gMenuItem.menu_id, gMenuItem.id);
8129 continue;
8131 if (!PlayerCondition::IsValid(cond_3, cond_3_val_1, cond_3_val_2))
8133 sLog.outErrorDb("Table gossip_menu_option menu %u, invalid condition 3 for id %u", gMenuItem.menu_id, gMenuItem.id);
8134 continue;
8137 if (gMenuItem.option_icon >= GOSSIP_ICON_MAX)
8139 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);
8140 gMenuItem.option_icon = GOSSIP_ICON_CHAT;
8143 if (gMenuItem.option_id == GOSSIP_OPTION_NONE)
8144 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);
8146 if (gMenuItem.option_id >= GOSSIP_OPTION_MAX)
8147 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);
8149 if (gMenuItem.action_poi_id && !GetPointOfInterest(gMenuItem.action_poi_id))
8151 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);
8152 gMenuItem.action_poi_id = 0;
8155 if (gMenuItem.action_script_id)
8157 if (gMenuItem.option_id != GOSSIP_OPTION_GOSSIP)
8159 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);
8160 continue;
8163 if (sGossipScripts.find(gMenuItem.action_script_id) == sGossipScripts.end())
8165 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);
8166 continue;
8169 gossipScriptSet.erase(gMenuItem.action_script_id);
8172 gMenuItem.cond_1 = GetConditionId(cond_1, cond_1_val_1, cond_1_val_2);
8173 gMenuItem.cond_2 = GetConditionId(cond_2, cond_2_val_1, cond_2_val_2);
8174 gMenuItem.cond_3 = GetConditionId(cond_3, cond_3_val_1, cond_3_val_2);
8176 m_mGossipMenuItemsMap.insert(GossipMenuItemsMap::value_type(gMenuItem.menu_id, gMenuItem));
8178 ++count;
8181 while(result->NextRow());
8183 delete result;
8185 if (!gossipScriptSet.empty())
8187 for(std::set<uint32>::const_iterator itr = gossipScriptSet.begin(); itr != gossipScriptSet.end(); ++itr)
8188 sLog.outErrorDb("Table `gossip_scripts` contain unused script, id %u.", *itr);
8191 sLog.outString();
8192 sLog.outString(">> Loaded %u gossip_menu_option entries", count);
8195 void ObjectMgr::AddVendorItem( uint32 entry,uint32 item, uint32 maxcount, uint32 incrtime, uint32 extendedcost )
8197 VendorItemData& vList = m_mCacheVendorItemMap[entry];
8198 vList.AddItem(item,maxcount,incrtime,extendedcost);
8200 WorldDatabase.PExecuteLog("INSERT INTO npc_vendor (entry,item,maxcount,incrtime,extendedcost) VALUES('%u','%u','%u','%u','%u')",entry, item, maxcount,incrtime,extendedcost);
8203 bool ObjectMgr::RemoveVendorItem( uint32 entry,uint32 item )
8205 CacheVendorItemMap::iterator iter = m_mCacheVendorItemMap.find(entry);
8206 if(iter == m_mCacheVendorItemMap.end())
8207 return false;
8209 if(!iter->second.FindItem(item))
8210 return false;
8212 iter->second.RemoveItem(item);
8213 WorldDatabase.PExecuteLog("DELETE FROM npc_vendor WHERE entry='%u' AND item='%u'",entry, item);
8214 return true;
8217 bool ObjectMgr::IsVendorItemValid( uint32 vendor_entry, uint32 item_id, uint32 maxcount, uint32 incrtime, uint32 ExtendedCost, Player* pl, std::set<uint32>* skip_vendors ) const
8219 CreatureInfo const* cInfo = GetCreatureTemplate(vendor_entry);
8220 if(!cInfo)
8222 if(pl)
8223 ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
8224 else
8225 sLog.outErrorDb("Table `npc_vendor` have data for not existed creature template (Entry: %u), ignore", vendor_entry);
8226 return false;
8229 if(!(cInfo->npcflag & UNIT_NPC_FLAG_VENDOR))
8231 if(!skip_vendors || skip_vendors->count(vendor_entry)==0)
8233 if(pl)
8234 ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
8235 else
8236 sLog.outErrorDb("Table `npc_vendor` have data for not creature template (Entry: %u) without vendor flag, ignore", vendor_entry);
8238 if(skip_vendors)
8239 skip_vendors->insert(vendor_entry);
8241 return false;
8244 if(!GetItemPrototype(item_id))
8246 if(pl)
8247 ChatHandler(pl).PSendSysMessage(LANG_ITEM_NOT_FOUND, item_id);
8248 else
8249 sLog.outErrorDb("Table `npc_vendor` for Vendor (Entry: %u) have in item list non-existed item (%u), ignore",vendor_entry,item_id);
8250 return false;
8253 if(ExtendedCost && !sItemExtendedCostStore.LookupEntry(ExtendedCost))
8255 if(pl)
8256 ChatHandler(pl).PSendSysMessage(LANG_EXTENDED_COST_NOT_EXIST,ExtendedCost);
8257 else
8258 sLog.outErrorDb("Table `npc_vendor` have Item (Entry: %u) with wrong ExtendedCost (%u) for vendor (%u), ignore",item_id,ExtendedCost,vendor_entry);
8259 return false;
8262 if(maxcount > 0 && incrtime == 0)
8264 if(pl)
8265 ChatHandler(pl).PSendSysMessage("MaxCount!=0 (%u) but IncrTime==0", maxcount);
8266 else
8267 sLog.outErrorDb( "Table `npc_vendor` has `maxcount` (%u) for item %u of vendor (Entry: %u) but `incrtime`=0, ignore", maxcount, item_id, vendor_entry);
8268 return false;
8270 else if(maxcount==0 && incrtime > 0)
8272 if(pl)
8273 ChatHandler(pl).PSendSysMessage("MaxCount==0 but IncrTime<>=0");
8274 else
8275 sLog.outErrorDb( "Table `npc_vendor` has `maxcount`=0 for item %u of vendor (Entry: %u) but `incrtime`<>0, ignore", item_id, vendor_entry);
8276 return false;
8279 VendorItemData const* vItems = GetNpcVendorItemList(vendor_entry);
8280 if(!vItems)
8281 return true; // later checks for non-empty lists
8283 if(vItems->FindItem(item_id))
8285 if(pl)
8286 ChatHandler(pl).PSendSysMessage(LANG_ITEM_ALREADY_IN_LIST,item_id);
8287 else
8288 sLog.outErrorDb( "Table `npc_vendor` has duplicate items %u for vendor (Entry: %u), ignore", item_id, vendor_entry);
8289 return false;
8292 if(vItems->GetItemCount() >= MAX_VENDOR_ITEMS)
8294 if(pl)
8295 ChatHandler(pl).SendSysMessage(LANG_COMMAND_ADDVENDORITEMITEMS);
8296 else
8297 sLog.outErrorDb( "Table `npc_vendor` has too many items (%u >= %i) for vendor (Entry: %u), ignore", vItems->GetItemCount(), MAX_VENDOR_ITEMS, vendor_entry);
8298 return false;
8301 return true;
8304 void ObjectMgr::LoadScriptNames()
8306 m_scriptNames.push_back("");
8307 QueryResult *result = WorldDatabase.Query(
8308 "SELECT DISTINCT(ScriptName) FROM creature_template WHERE ScriptName <> '' "
8309 "UNION "
8310 "SELECT DISTINCT(ScriptName) FROM gameobject_template WHERE ScriptName <> '' "
8311 "UNION "
8312 "SELECT DISTINCT(ScriptName) FROM item_template WHERE ScriptName <> '' "
8313 "UNION "
8314 "SELECT DISTINCT(ScriptName) FROM areatrigger_scripts WHERE ScriptName <> '' "
8315 "UNION "
8316 "SELECT DISTINCT(script) FROM instance_template WHERE script <> ''");
8318 if( !result )
8320 barGoLink bar( 1 );
8321 bar.step();
8322 sLog.outString();
8323 sLog.outErrorDb(">> Loaded empty set of Script Names!");
8324 return;
8327 barGoLink bar( result->GetRowCount() );
8328 uint32 count = 0;
8332 bar.step();
8333 m_scriptNames.push_back((*result)[0].GetString());
8334 ++count;
8335 } while (result->NextRow());
8336 delete result;
8338 std::sort(m_scriptNames.begin(), m_scriptNames.end());
8339 sLog.outString();
8340 sLog.outString( ">> Loaded %d Script Names", count );
8343 uint32 ObjectMgr::GetScriptId(const char *name)
8345 // use binary search to find the script name in the sorted vector
8346 // assume "" is the first element
8347 if(!name) return 0;
8348 ScriptNameMap::const_iterator itr =
8349 std::lower_bound(m_scriptNames.begin(), m_scriptNames.end(), name);
8350 if(itr == m_scriptNames.end() || *itr != name) return 0;
8351 return itr - m_scriptNames.begin();
8354 void ObjectMgr::CheckScripts(ScriptMapMap const& scripts,std::set<int32>& ids)
8356 for(ScriptMapMap::const_iterator itrMM = scripts.begin(); itrMM != scripts.end(); ++itrMM)
8358 for(ScriptMap::const_iterator itrM = itrMM->second.begin(); itrM != itrMM->second.end(); ++itrM)
8360 switch(itrM->second.command)
8362 case SCRIPT_COMMAND_TALK:
8364 if(!GetMangosStringLocale (itrM->second.dataint))
8365 sLog.outErrorDb( "Table `db_script_string` is missing string id %u, used in database script id %u.", itrM->second.dataint, itrMM->first);
8367 if (ids.find(itrM->second.dataint) != ids.end())
8368 ids.erase(itrM->second.dataint);
8375 void ObjectMgr::LoadDbScriptStrings()
8377 LoadMangosStrings(WorldDatabase,"db_script_string",MIN_DB_SCRIPT_STRING_ID,MAX_DB_SCRIPT_STRING_ID);
8379 std::set<int32> ids;
8381 for(int32 i = MIN_DB_SCRIPT_STRING_ID; i < MAX_DB_SCRIPT_STRING_ID; ++i)
8382 if(GetMangosStringLocale(i))
8383 ids.insert(i);
8385 CheckScripts(sQuestEndScripts,ids);
8386 CheckScripts(sQuestStartScripts,ids);
8387 CheckScripts(sSpellScripts,ids);
8388 CheckScripts(sGameObjectScripts,ids);
8389 CheckScripts(sEventScripts,ids);
8390 CheckScripts(sGossipScripts,ids);
8392 sWaypointMgr.CheckTextsExistance(ids);
8394 for(std::set<int32>::const_iterator itr = ids.begin(); itr != ids.end(); ++itr)
8395 sLog.outErrorDb( "Table `db_script_string` has unused string id %u", *itr);
8398 void ObjectMgr::AddGuild( Guild* guild )
8400 mGuildMap[guild->GetId()] = guild ;
8403 void ObjectMgr::RemoveGuild( uint32 Id )
8405 mGuildMap.erase(Id);
8408 void ObjectMgr::AddGroup( Group* group )
8410 mGroupMap[GUID_LOPART(group->GetLeaderGUID())] = group ;
8413 void ObjectMgr::RemoveGroup( Group* group )
8415 mGroupMap.erase(GUID_LOPART(group->GetLeaderGUID()));
8418 void ObjectMgr::UpdateGroup( uint32 old_guidlow, Group* group )
8420 mGroupMap.erase(old_guidlow);
8421 AddGroup(group);
8424 void ObjectMgr::AddArenaTeam( ArenaTeam* arenaTeam )
8426 mArenaTeamMap[arenaTeam->GetId()] = arenaTeam;
8429 void ObjectMgr::RemoveArenaTeam( uint32 Id )
8431 mArenaTeamMap.erase(Id);
8434 // Functions for scripting access
8435 uint32 GetAreaTriggerScriptId(uint32 trigger_id)
8437 return sObjectMgr.GetAreaTriggerScriptId(trigger_id);
8440 bool LoadMangosStrings(DatabaseType& db, char const* table,int32 start_value, int32 end_value)
8442 // MAX_DB_SCRIPT_STRING_ID is max allowed negative value for scripts (scrpts can use only more deep negative values
8443 // start/end reversed for negative values
8444 if (start_value > MAX_DB_SCRIPT_STRING_ID || end_value >= start_value)
8446 sLog.outErrorDb("Table '%s' attempt loaded with reserved by mangos range (%d - %d), strings not loaded.",table,start_value,end_value+1);
8447 return false;
8450 return sObjectMgr.LoadMangosStrings(db,table,start_value,end_value);
8453 uint32 MANGOS_DLL_SPEC GetScriptId(const char *name)
8455 return sObjectMgr.GetScriptId(name);
8458 ObjectMgr::ScriptNameMap & GetScriptNames()
8460 return sObjectMgr.GetScriptNames();
8463 CreatureInfo const* GetCreatureTemplateStore(uint32 entry)
8465 return sCreatureStorage.LookupEntry<CreatureInfo>(entry);
8468 Quest const* GetQuestTemplateStore(uint32 entry)
8470 return sObjectMgr.GetQuestTemplate(entry);