Merge branch 'master' into 330
[getmangos.git] / src / game / ObjectMgr.cpp
blob497ec4db297af160f954e7387b16e02b883a022d
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 (GroupSet::iterator itr = mGroupSet.begin(); itr != mGroupSet.end(); ++itr)
168 delete (*itr);
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::GetGroupByLeader(const uint64 &guid) const
185 for(GroupSet::const_iterator itr = mGroupSet.begin(); itr != mGroupSet.end(); ++itr)
186 if ((*itr)->GetLeaderGUID() == guid)
187 return *itr;
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 void ObjectMgr::AddGuild(Guild* guild)
230 mGuildMap[guild->GetId()] = guild;
233 void ObjectMgr::RemoveGuild(uint32 Id)
235 mGuildMap.erase(Id);
238 ArenaTeam* ObjectMgr::GetArenaTeamById(uint32 arenateamid) const
240 ArenaTeamMap::const_iterator itr = mArenaTeamMap.find(arenateamid);
241 if (itr != mArenaTeamMap.end())
242 return itr->second;
244 return NULL;
247 ArenaTeam* ObjectMgr::GetArenaTeamByName(const std::string& arenateamname) const
249 for(ArenaTeamMap::const_iterator itr = mArenaTeamMap.begin(); itr != mArenaTeamMap.end(); ++itr)
250 if (itr->second->GetName() == arenateamname)
251 return itr->second;
253 return NULL;
256 ArenaTeam* ObjectMgr::GetArenaTeamByCaptain(uint64 const& guid) const
258 for(ArenaTeamMap::const_iterator itr = mArenaTeamMap.begin(); itr != mArenaTeamMap.end(); ++itr)
259 if (itr->second->GetCaptain() == guid)
260 return itr->second;
262 return NULL;
265 void ObjectMgr::AddArenaTeam(ArenaTeam* arenaTeam)
267 mArenaTeamMap[arenaTeam->GetId()] = arenaTeam;
270 void ObjectMgr::RemoveArenaTeam(uint32 Id)
272 mArenaTeamMap.erase(Id);
275 CreatureInfo const* ObjectMgr::GetCreatureTemplate(uint32 id)
277 return sCreatureStorage.LookupEntry<CreatureInfo>(id);
280 void ObjectMgr::LoadCreatureLocales()
282 mCreatureLocaleMap.clear(); // need for reload case
284 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");
286 if(!result)
288 barGoLink bar(1);
290 bar.step();
292 sLog.outString();
293 sLog.outString(">> Loaded 0 creature locale strings. DB table `locales_creature` is empty.");
294 return;
297 barGoLink bar(result->GetRowCount());
301 Field *fields = result->Fetch();
302 bar.step();
304 uint32 entry = fields[0].GetUInt32();
306 CreatureLocale& data = mCreatureLocaleMap[entry];
308 for(int i = 1; i < MAX_LOCALE; ++i)
310 std::string str = fields[1+2*(i-1)].GetCppString();
311 if(!str.empty())
313 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
314 if(idx >= 0)
316 if(data.Name.size() <= idx)
317 data.Name.resize(idx+1);
319 data.Name[idx] = str;
322 str = fields[1+2*(i-1)+1].GetCppString();
323 if(!str.empty())
325 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
326 if(idx >= 0)
328 if(data.SubName.size() <= idx)
329 data.SubName.resize(idx+1);
331 data.SubName[idx] = str;
335 } while (result->NextRow());
337 delete result;
339 sLog.outString();
340 sLog.outString( ">> Loaded %lu creature locale strings", (unsigned long)mCreatureLocaleMap.size() );
343 void ObjectMgr::LoadGossipMenuItemsLocales()
345 mGossipMenuItemsLocaleMap.clear(); // need for reload case
347 QueryResult *result = WorldDatabase.Query("SELECT menu_id,id,"
348 "option_text_loc1,box_text_loc1,option_text_loc2,box_text_loc2,"
349 "option_text_loc3,box_text_loc3,option_text_loc4,box_text_loc4,"
350 "option_text_loc5,box_text_loc5,option_text_loc6,box_text_loc6,"
351 "option_text_loc7,box_text_loc7,option_text_loc8,box_text_loc8 "
352 "FROM locales_gossip_menu_option");
354 if(!result)
356 barGoLink bar(1);
358 bar.step();
360 sLog.outString();
361 sLog.outString(">> Loaded 0 gossip_menu_option locale strings. DB table `locales_gossip_menu_option` is empty.");
362 return;
365 barGoLink bar(result->GetRowCount());
369 Field *fields = result->Fetch();
370 bar.step();
372 uint16 menuId = fields[0].GetUInt16();
373 uint16 id = fields[1].GetUInt16();
375 GossipMenuItemsLocale& data = mGossipMenuItemsLocaleMap[MAKE_PAIR32(menuId,id)];
377 for(int i = 1; i < MAX_LOCALE; ++i)
379 std::string str = fields[2+2*(i-1)].GetCppString();
380 if(!str.empty())
382 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
383 if(idx >= 0)
385 if(data.OptionText.size() <= idx)
386 data.OptionText.resize(idx+1);
388 data.OptionText[idx] = str;
391 str = fields[2+2*(i-1)+1].GetCppString();
392 if(!str.empty())
394 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
395 if(idx >= 0)
397 if(data.BoxText.size() <= idx)
398 data.BoxText.resize(idx+1);
400 data.BoxText[idx] = str;
404 } while (result->NextRow());
406 delete result;
408 sLog.outString();
409 sLog.outString( ">> Loaded %lu gossip_menu_option locale strings", (unsigned long)mGossipMenuItemsLocaleMap.size() );
412 void ObjectMgr::LoadPointOfInterestLocales()
414 mPointOfInterestLocaleMap.clear(); // need for reload case
416 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");
418 if(!result)
420 barGoLink bar(1);
422 bar.step();
424 sLog.outString();
425 sLog.outString(">> Loaded 0 points_of_interest locale strings. DB table `locales_points_of_interest` is empty.");
426 return;
429 barGoLink bar(result->GetRowCount());
433 Field *fields = result->Fetch();
434 bar.step();
436 uint32 entry = fields[0].GetUInt32();
438 PointOfInterestLocale& data = mPointOfInterestLocaleMap[entry];
440 for(int i = 1; i < MAX_LOCALE; ++i)
442 std::string str = fields[i].GetCppString();
443 if(str.empty())
444 continue;
446 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
447 if(idx >= 0)
449 if(data.IconName.size() <= idx)
450 data.IconName.resize(idx+1);
452 data.IconName[idx] = str;
455 } while (result->NextRow());
457 delete result;
459 sLog.outString();
460 sLog.outString( ">> Loaded %lu points_of_interest locale strings", (unsigned long)mPointOfInterestLocaleMap.size() );
463 struct SQLCreatureLoader : public SQLStorageLoaderBase<SQLCreatureLoader>
465 template<class D>
466 void convert_from_str(uint32 /*field_pos*/, char *src, D &dst)
468 dst = D(sObjectMgr.GetScriptId(src));
472 void ObjectMgr::LoadCreatureTemplates()
474 SQLCreatureLoader loader;
475 loader.Load(sCreatureStorage);
477 sLog.outString( ">> Loaded %u creature definitions", sCreatureStorage.RecordCount );
478 sLog.outString();
480 std::set<uint32> difficultyEntries[MAX_DIFFICULTY - 1]; // already loaded difficulty 1 value in creatures
481 std::set<uint32> hasDifficultyEntries[MAX_DIFFICULTY - 1]; // already loaded creatures with difficulty 1 values
483 // check data correctness
484 for(uint32 i = 1; i < sCreatureStorage.MaxEntry; ++i)
486 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i);
487 if (!cInfo)
488 continue;
490 bool ok = true; // bool to allow continue outside this loop
491 for (uint32 diff = 0; diff < MAX_DIFFICULTY - 1 && ok; ++diff)
493 if (!cInfo->DifficultyEntry[diff])
494 continue;
495 ok = false; // will be set to true at the end of this loop again
497 CreatureInfo const* difficultyInfo = GetCreatureTemplate(cInfo->DifficultyEntry[diff]);
498 if (!difficultyInfo)
500 sLog.outErrorDb("Creature (Entry: %u) have `difficulty_entry_%u`=%u but creature entry %u not exist.",
501 i, diff + 1, cInfo->DifficultyEntry[diff], cInfo->DifficultyEntry[diff]);
502 continue;
505 if (difficultyEntries[diff].find(i) != difficultyEntries[diff].end())
507 sLog.outErrorDb("Creature (Entry: %u) listed as difficulty %u but have value in `difficulty_entry_%u`.", i, diff + 1, diff + 1);
508 continue;
511 bool ok2 = true;
512 for (uint32 diff2 = 0; diff2 < MAX_DIFFICULTY - 1 && ok2; ++diff2)
514 ok2 = false;
515 if (difficultyEntries[diff2].find(cInfo->DifficultyEntry[diff]) != difficultyEntries[diff2].end())
517 sLog.outErrorDb("Creature (Entry: %u) already listed as difficulty %u for another entry.", cInfo->DifficultyEntry[diff], diff2 + 1);
518 continue;
521 if (hasDifficultyEntries[diff2].find(cInfo->DifficultyEntry[diff]) != hasDifficultyEntries[diff2].end())
523 sLog.outErrorDb("Creature (Entry: %u) have `difficulty_entry_%u`=%u but creature entry %u have difficulty %u entry also.",
524 i, diff + 1, cInfo->DifficultyEntry[diff], cInfo->DifficultyEntry[diff], diff2 + 1);
525 continue;
527 ok2 = true;
529 if (!ok2)
530 continue;
532 if (cInfo->unit_class != difficultyInfo->unit_class)
534 sLog.outErrorDb("Creature (Entry: %u, class %u) has different `unit_class` in difficulty %u mode (Entry: %u, class %u).",
535 i, cInfo->unit_class, diff + 1, cInfo->DifficultyEntry[diff], difficultyInfo->unit_class);
536 continue;
539 if (cInfo->npcflag != difficultyInfo->npcflag)
541 sLog.outErrorDb("Creature (Entry: %u) has different `npcflag` in difficulty %u mode (Entry: %u).", i, diff + 1, cInfo->DifficultyEntry[diff]);
542 continue;
545 if (cInfo->trainer_class != difficultyInfo->trainer_class)
547 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_class` in difficulty %u mode (Entry: %u).", i, diff + 1, cInfo->DifficultyEntry[diff]);
548 continue;
551 if (cInfo->trainer_race != difficultyInfo->trainer_race)
553 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_race` in difficulty %u mode (Entry: %u).", i, diff + 1, cInfo->DifficultyEntry[diff]);
554 continue;
557 if (cInfo->trainer_type != difficultyInfo->trainer_type)
559 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_type` in difficulty %u mode (Entry: %u).", i, diff + 1, cInfo->DifficultyEntry[diff]);
560 continue;
563 if (cInfo->trainer_spell != difficultyInfo->trainer_spell)
565 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_spell` in difficulty %u mode (Entry: %u).", i, diff + 1, cInfo->DifficultyEntry[diff]);
566 continue;
569 if (difficultyInfo->AIName && *difficultyInfo->AIName)
571 sLog.outErrorDb("Difficulty %u mode creature (Entry: %u) has `AIName`, but in any case will used difficulty 0 mode creature (Entry: %u) AIName.",
572 diff, cInfo->DifficultyEntry[diff], i);
573 continue;
576 if (difficultyInfo->ScriptID)
578 sLog.outErrorDb("Difficulty %u mode creature (Entry: %u) has `ScriptName`, but in any case will used difficulty 0 mode creature (Entry: %u) ScriptName.",
579 diff, cInfo->DifficultyEntry[diff], i);
580 continue;
583 hasDifficultyEntries[diff].insert(i);
584 difficultyEntries[diff].insert(cInfo->DifficultyEntry[diff]);
585 ok = true;
587 if (!ok)
588 continue;
590 FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction_A);
591 if (!factionTemplate)
592 sLog.outErrorDb("Creature (Entry: %u) has non-existing faction_A template (%u)", cInfo->Entry, cInfo->faction_A);
594 factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction_H);
595 if (!factionTemplate)
596 sLog.outErrorDb("Creature (Entry: %u) has non-existing faction_H template (%u)", cInfo->Entry, cInfo->faction_H);
598 // used later for scale
599 CreatureDisplayInfoEntry const* displayScaleEntry = NULL;
601 if (cInfo->DisplayID_A[0])
603 CreatureDisplayInfoEntry const* displayEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->DisplayID_A[0]);
604 if(!displayEntry)
606 sLog.outErrorDb("Creature (Entry: %u) has non-existing DisplayID_A id (%u), can crash client", cInfo->Entry, cInfo->DisplayID_A[0]);
607 const_cast<CreatureInfo*>(cInfo)->DisplayID_A[0] = 0;
609 else if(!displayScaleEntry)
610 displayScaleEntry = displayEntry;
612 CreatureModelInfo const* minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_A[0]);
613 if (!minfo)
614 sLog.outErrorDb("Creature (Entry: %u) not has model data for DisplayID_A (%u)", cInfo->Entry, cInfo->DisplayID_A[0]);
617 if (cInfo->DisplayID_A[1])
619 CreatureDisplayInfoEntry const* displayEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->DisplayID_A[1]);
620 if(!displayEntry)
622 sLog.outErrorDb("Creature (Entry: %u) has non-existing DisplayID_A2 id (%u), can crash client", cInfo->Entry, cInfo->DisplayID_A[1]);
623 const_cast<CreatureInfo*>(cInfo)->DisplayID_A[1] = 0;
625 else if(!displayScaleEntry)
626 displayScaleEntry = displayEntry;
628 CreatureModelInfo const* minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_A[1]);
629 if (!minfo)
630 sLog.outErrorDb("Creature (Entry: %u) not has model data for DisplayID_A2 (%u)", cInfo->Entry, cInfo->DisplayID_A[1]);
633 if (cInfo->DisplayID_H[0])
635 CreatureDisplayInfoEntry const* displayEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->DisplayID_H[0]);
636 if(!displayEntry)
638 sLog.outErrorDb("Creature (Entry: %u) has non-existing DisplayID_H id (%u), can crash client", cInfo->Entry, cInfo->DisplayID_H[0]);
639 const_cast<CreatureInfo*>(cInfo)->DisplayID_H[0] = 0;
641 else if(!displayScaleEntry)
642 displayScaleEntry = displayEntry;
644 CreatureModelInfo const* minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_H[0]);
645 if (!minfo)
646 sLog.outErrorDb("Creature (Entry: %u) not has model data for DisplayID_H (%u)", cInfo->Entry, cInfo->DisplayID_H[0]);
649 if (cInfo->DisplayID_H[1])
651 CreatureDisplayInfoEntry const* displayEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->DisplayID_H[1]);
652 if(!displayEntry)
654 sLog.outErrorDb("Creature (Entry: %u) has non-existing DisplayID_H2 id (%u), can crash client", cInfo->Entry, cInfo->DisplayID_H[1]);
655 const_cast<CreatureInfo*>(cInfo)->DisplayID_H[1] = 0;
657 else if(!displayScaleEntry)
658 displayScaleEntry = displayEntry;
660 CreatureModelInfo const* minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_H[1]);
661 if (!minfo)
662 sLog.outErrorDb("Creature (Entry: %u) not has model data for DisplayID_H2 (%u)", cInfo->Entry, cInfo->DisplayID_H[1]);
665 if (!displayScaleEntry)
666 sLog.outErrorDb("Creature (Entry: %u) not has any existed display id in DisplayID_A/DisplayID_A2/DisplayID_H/DisplayID_H2", cInfo->Entry);
668 for(int k = 0; k < MAX_KILL_CREDIT; ++k)
670 if(cInfo->KillCredit[k])
672 if(!GetCreatureTemplate(cInfo->KillCredit[k]))
674 sLog.outErrorDb("Creature (Entry: %u) has not existed creature entry in `KillCredit%d` (%u)",cInfo->Entry,k+1,cInfo->KillCredit[k]);
675 const_cast<CreatureInfo*>(cInfo)->KillCredit[k] = 0;
680 if (cInfo->unit_class && ((1 << (cInfo->unit_class-1)) & CLASSMASK_ALL_CREATURES) == 0)
681 sLog.outErrorDb("Creature (Entry: %u) has invalid unit_class(%u) for creature_template", cInfo->Entry, cInfo->unit_class);
683 if(cInfo->dmgschool >= MAX_SPELL_SCHOOL)
685 sLog.outErrorDb("Creature (Entry: %u) has invalid spell school value (%u) in `dmgschool`",cInfo->Entry,cInfo->dmgschool);
686 const_cast<CreatureInfo*>(cInfo)->dmgschool = SPELL_SCHOOL_NORMAL;
689 if(cInfo->baseattacktime == 0)
690 const_cast<CreatureInfo*>(cInfo)->baseattacktime = BASE_ATTACK_TIME;
692 if(cInfo->rangeattacktime == 0)
693 const_cast<CreatureInfo*>(cInfo)->rangeattacktime = BASE_ATTACK_TIME;
695 if(cInfo->npcflag & UNIT_NPC_FLAG_SPELLCLICK)
697 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);
698 const_cast<CreatureInfo*>(cInfo)->npcflag &= ~UNIT_NPC_FLAG_SPELLCLICK;
701 if((cInfo->npcflag & UNIT_NPC_FLAG_TRAINER) && cInfo->trainer_type >= MAX_TRAINER_TYPE)
702 sLog.outErrorDb("Creature (Entry: %u) has wrong trainer type %u",cInfo->Entry,cInfo->trainer_type);
704 if(cInfo->type && !sCreatureTypeStore.LookupEntry(cInfo->type))
706 sLog.outErrorDb("Creature (Entry: %u) has invalid creature type (%u) in `type`",cInfo->Entry,cInfo->type);
707 const_cast<CreatureInfo*>(cInfo)->type = CREATURE_TYPE_HUMANOID;
710 // must exist or used hidden but used in data horse case
711 if(cInfo->family && !sCreatureFamilyStore.LookupEntry(cInfo->family) && cInfo->family != CREATURE_FAMILY_HORSE_CUSTOM )
713 sLog.outErrorDb("Creature (Entry: %u) has invalid creature family (%u) in `family`",cInfo->Entry,cInfo->family);
714 const_cast<CreatureInfo*>(cInfo)->family = 0;
717 if(cInfo->InhabitType <= 0 || cInfo->InhabitType > INHABIT_ANYWHERE)
719 sLog.outErrorDb("Creature (Entry: %u) has wrong value (%u) in `InhabitType`, creature will not correctly walk/swim/fly",cInfo->Entry,cInfo->InhabitType);
720 const_cast<CreatureInfo*>(cInfo)->InhabitType = INHABIT_ANYWHERE;
723 if(cInfo->PetSpellDataId)
725 CreatureSpellDataEntry const* spellDataId = sCreatureSpellDataStore.LookupEntry(cInfo->PetSpellDataId);
726 if(!spellDataId)
727 sLog.outErrorDb("Creature (Entry: %u) has non-existing PetSpellDataId (%u)", cInfo->Entry, cInfo->PetSpellDataId);
730 for(int j = 0; j < CREATURE_MAX_SPELLS; ++j)
732 if(cInfo->spells[j] && !sSpellStore.LookupEntry(cInfo->spells[j]))
734 sLog.outErrorDb("Creature (Entry: %u) has non-existing Spell%d (%u), set to 0", cInfo->Entry, j+1,cInfo->spells[j]);
735 const_cast<CreatureInfo*>(cInfo)->spells[j] = 0;
739 if(cInfo->MovementType >= MAX_DB_MOTION_TYPE)
741 sLog.outErrorDb("Creature (Entry: %u) has wrong movement generator type (%u), ignore and set to IDLE.",cInfo->Entry,cInfo->MovementType);
742 const_cast<CreatureInfo*>(cInfo)->MovementType = IDLE_MOTION_TYPE;
745 if(cInfo->equipmentId > 0) // 0 no equipment
747 if(!GetEquipmentInfo(cInfo->equipmentId))
749 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);
750 const_cast<CreatureInfo*>(cInfo)->equipmentId = 0;
754 /// if not set custom creature scale then load scale from CreatureDisplayInfo.dbc
755 if(cInfo->scale <= 0.0f)
757 if(displayScaleEntry)
758 const_cast<CreatureInfo*>(cInfo)->scale = displayScaleEntry->scale;
759 else
760 const_cast<CreatureInfo*>(cInfo)->scale = 1.0f;
765 void ObjectMgr::ConvertCreatureAddonAuras(CreatureDataAddon* addon, char const* table, char const* guidEntryStr)
767 // Now add the auras, format "spellid effectindex spellid effectindex..."
768 char *p,*s;
769 std::vector<int> val;
770 s=p=(char*)reinterpret_cast<char const*>(addon->auras);
771 if(p)
773 while (p[0]!=0)
775 ++p;
776 if (p[0]==' ')
778 val.push_back(atoi(s));
779 s=++p;
782 if (p!=s)
783 val.push_back(atoi(s));
785 // free char* loaded memory
786 delete[] (char*)reinterpret_cast<char const*>(addon->auras);
788 // wrong list
789 if (val.size()%2)
791 addon->auras = NULL;
792 sLog.outErrorDb("Creature (%s: %u) has wrong `auras` data in `%s`.",guidEntryStr,addon->guidOrEntry,table);
793 return;
797 // empty list
798 if(val.empty())
800 addon->auras = NULL;
801 return;
804 // replace by new structures array
805 const_cast<CreatureDataAddonAura*&>(addon->auras) = new CreatureDataAddonAura[val.size()/2+1];
807 uint32 i=0;
808 for(uint32 j = 0; j < val.size()/2; ++j)
810 CreatureDataAddonAura& cAura = const_cast<CreatureDataAddonAura&>(addon->auras[i]);
811 cAura.spell_id = (uint32)val[2*j+0];
812 cAura.effect_idx = (uint32)val[2*j+1];
813 if ( cAura.effect_idx > 2 )
815 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);
816 continue;
818 SpellEntry const *AdditionalSpellInfo = sSpellStore.LookupEntry(cAura.spell_id);
819 if (!AdditionalSpellInfo)
821 sLog.outErrorDb("Creature (%s: %u) has wrong spell %u defined in `auras` field in `%s`.",guidEntryStr,addon->guidOrEntry,cAura.spell_id,table);
822 continue;
825 if (!AdditionalSpellInfo->Effect[cAura.effect_idx] || !AdditionalSpellInfo->EffectApplyAuraName[cAura.effect_idx])
827 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);
828 continue;
831 ++i;
834 // fill terminator element (after last added)
835 CreatureDataAddonAura& endAura = const_cast<CreatureDataAddonAura&>(addon->auras[i]);
836 endAura.spell_id = 0;
837 endAura.effect_idx = 0;
840 void ObjectMgr::LoadCreatureAddons(SQLStorage& creatureaddons, char const* entryName, char const* comment)
842 creatureaddons.Load();
844 sLog.outString(">> Loaded %u %s", creatureaddons.RecordCount, comment);
845 sLog.outString();
847 // check data correctness and convert 'auras'
848 for(uint32 i = 1; i < creatureaddons.MaxEntry; ++i)
850 CreatureDataAddon const* addon = creatureaddons.LookupEntry<CreatureDataAddon>(i);
851 if(!addon)
852 continue;
854 if (addon->mount)
856 if (!sCreatureDisplayInfoStore.LookupEntry(addon->mount))
858 sLog.outErrorDb("Creature (%s %u) have invalid displayInfoId for mount (%u) defined in `%s`.", entryName, addon->guidOrEntry, addon->mount, creatureaddons.GetTableName());
859 const_cast<CreatureDataAddon*>(addon)->mount = 0;
863 if (!sEmotesStore.LookupEntry(addon->emote))
864 sLog.outErrorDb("Creature (%s %u) have invalid emote (%u) defined in `%s`.", entryName, addon->guidOrEntry, addon->emote, creatureaddons.GetTableName());
866 if (addon->move_flags & (MONSTER_MOVE_UNK1|MONSTER_MOVE_UNK4))
868 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));
869 const_cast<CreatureDataAddon*>(addon)->move_flags &= ~(MONSTER_MOVE_UNK1|MONSTER_MOVE_UNK4);
872 ConvertCreatureAddonAuras(const_cast<CreatureDataAddon*>(addon), creatureaddons.GetTableName(), entryName);
876 void ObjectMgr::LoadCreatureAddons()
878 LoadCreatureAddons(sCreatureInfoAddonStorage,"Entry","creature template addons");
880 // check entry ids
881 for(uint32 i = 1; i < sCreatureInfoAddonStorage.MaxEntry; ++i)
882 if(CreatureDataAddon const* addon = sCreatureInfoAddonStorage.LookupEntry<CreatureDataAddon>(i))
883 if(!sCreatureStorage.LookupEntry<CreatureInfo>(addon->guidOrEntry))
884 sLog.outErrorDb("Creature (Entry: %u) does not exist but has a record in `%s`",addon->guidOrEntry, sCreatureInfoAddonStorage.GetTableName());
886 LoadCreatureAddons(sCreatureDataAddonStorage,"GUID","creature addons");
888 // check entry ids
889 for(uint32 i = 1; i < sCreatureDataAddonStorage.MaxEntry; ++i)
890 if(CreatureDataAddon const* addon = sCreatureDataAddonStorage.LookupEntry<CreatureDataAddon>(i))
891 if(mCreatureDataMap.find(addon->guidOrEntry)==mCreatureDataMap.end())
892 sLog.outErrorDb("Creature (GUID: %u) does not exist but has a record in `creature_addon`",addon->guidOrEntry);
895 EquipmentInfo const* ObjectMgr::GetEquipmentInfo(uint32 entry)
897 return sEquipmentStorage.LookupEntry<EquipmentInfo>(entry);
900 void ObjectMgr::LoadEquipmentTemplates()
902 sEquipmentStorage.Load();
904 for(uint32 i=0; i< sEquipmentStorage.MaxEntry; ++i)
906 EquipmentInfo const* eqInfo = sEquipmentStorage.LookupEntry<EquipmentInfo>(i);
908 if(!eqInfo)
909 continue;
911 for(uint8 j=0; j<3; j++)
913 if(!eqInfo->equipentry[j])
914 continue;
916 ItemEntry const *dbcitem = sItemStore.LookupEntry(eqInfo->equipentry[j]);
918 if(!dbcitem)
920 sLog.outErrorDb("Unknown item (entry=%u) in creature_equip_template.equipentry%u for entry = %u, forced to 0.", eqInfo->equipentry[j], j+1, i);
921 const_cast<EquipmentInfo*>(eqInfo)->equipentry[j] = 0;
922 continue;
925 if(dbcitem->InventoryType != INVTYPE_WEAPON &&
926 dbcitem->InventoryType != INVTYPE_SHIELD &&
927 dbcitem->InventoryType != INVTYPE_RANGED &&
928 dbcitem->InventoryType != INVTYPE_2HWEAPON &&
929 dbcitem->InventoryType != INVTYPE_WEAPONMAINHAND &&
930 dbcitem->InventoryType != INVTYPE_WEAPONOFFHAND &&
931 dbcitem->InventoryType != INVTYPE_HOLDABLE &&
932 dbcitem->InventoryType != INVTYPE_THROWN &&
933 dbcitem->InventoryType != INVTYPE_RANGEDRIGHT)
935 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);
936 const_cast<EquipmentInfo*>(eqInfo)->equipentry[j] = 0;
940 sLog.outString( ">> Loaded %u equipment template", sEquipmentStorage.RecordCount );
941 sLog.outString();
944 CreatureModelInfo const* ObjectMgr::GetCreatureModelInfo(uint32 modelid)
946 return sCreatureModelStorage.LookupEntry<CreatureModelInfo>(modelid);
949 uint32 ObjectMgr::ChooseDisplayId(uint32 team, const CreatureInfo *cinfo, const CreatureData *data /*= NULL*/)
951 // Load creature model (display id)
952 if (data && data->displayid)
953 return data->displayid;
955 // use defaults from the template
956 uint32 display_id;
958 // DisplayID_A is used if no team is given
959 if (team == HORDE)
961 if(cinfo->DisplayID_H[0])
962 display_id = cinfo->DisplayID_H[1] ? cinfo->DisplayID_H[urand(0,1)] : cinfo->DisplayID_H[0];
963 else
964 display_id = cinfo->DisplayID_H[1];
966 if(!display_id)
967 display_id = cinfo->DisplayID_A[0] ? cinfo->DisplayID_A[0] : cinfo->DisplayID_A[1];
969 else
971 if(cinfo->DisplayID_A[0])
972 display_id = cinfo->DisplayID_A[1] ? cinfo->DisplayID_A[urand(0,1)] : cinfo->DisplayID_A[0];
973 else
974 display_id = cinfo->DisplayID_A[1];
976 if(!display_id)
977 display_id = cinfo->DisplayID_H[0] ? cinfo->DisplayID_H[0] : cinfo->DisplayID_H[1];
980 return display_id;
983 CreatureModelInfo const* ObjectMgr::GetCreatureModelRandomGender(uint32 display_id)
985 CreatureModelInfo const *minfo = GetCreatureModelInfo(display_id);
986 if(!minfo)
987 return NULL;
989 // If a model for another gender exists, 50% chance to use it
990 if(minfo->modelid_other_gender != 0 && urand(0,1) == 0)
992 CreatureModelInfo const *minfo_tmp = GetCreatureModelInfo(minfo->modelid_other_gender);
993 if(!minfo_tmp)
995 sLog.outErrorDb("Model (Entry: %u) has modelid_other_gender %u not found in table `creature_model_info`. ", minfo->modelid, minfo->modelid_other_gender);
996 return minfo; // not fatal, just use the previous one
998 else
999 return minfo_tmp;
1001 else
1002 return minfo;
1005 void ObjectMgr::LoadCreatureModelInfo()
1007 sCreatureModelStorage.Load();
1009 // post processing
1010 for(uint32 i = 1; i < sCreatureModelStorage.MaxEntry; ++i)
1012 CreatureModelInfo const *minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(i);
1013 if (!minfo)
1014 continue;
1016 if (!sCreatureDisplayInfoStore.LookupEntry(minfo->modelid))
1017 sLog.outErrorDb("Table `creature_model_info` has model for not existed display id (%u).", minfo->modelid);
1019 if (minfo->gender > GENDER_NONE)
1021 sLog.outErrorDb("Table `creature_model_info` has wrong gender (%u) for display id (%u).", uint32(minfo->gender), minfo->modelid);
1022 const_cast<CreatureModelInfo*>(minfo)->gender = GENDER_MALE;
1025 if (minfo->modelid_other_gender && !sCreatureDisplayInfoStore.LookupEntry(minfo->modelid_other_gender))
1027 sLog.outErrorDb("Table `creature_model_info` has not existed alt.gender model (%u) for existed display id (%u).", minfo->modelid_other_gender, minfo->modelid);
1028 const_cast<CreatureModelInfo*>(minfo)->modelid_other_gender = 0;
1032 sLog.outString( ">> Loaded %u creature model based info", sCreatureModelStorage.RecordCount );
1033 sLog.outString();
1036 void ObjectMgr::LoadCreatures()
1038 uint32 count = 0;
1039 // 0 1 2 3
1040 QueryResult *result = WorldDatabase.Query("SELECT creature.guid, id, map, modelid,"
1041 // 4 5 6 7 8 9 10 11
1042 "equipment_id, position_x, position_y, position_z, orientation, spawntimesecs, spawndist, currentwaypoint,"
1043 // 12 13 14 15 16 17 18 19
1044 "curhealth, curmana, DeathState, MovementType, spawnMask, phaseMask, event, pool_entry "
1045 "FROM creature LEFT OUTER JOIN game_event_creature ON creature.guid = game_event_creature.guid "
1046 "LEFT OUTER JOIN pool_creature ON creature.guid = pool_creature.guid");
1048 if(!result)
1050 barGoLink bar(1);
1052 bar.step();
1054 sLog.outString();
1055 sLog.outErrorDb(">> Loaded 0 creature. DB table `creature` is empty.");
1056 return;
1059 // build single time for check creature data
1060 std::set<uint32> difficultyCreatures[MAX_DIFFICULTY - 1];
1061 for (uint32 i = 0; i < sCreatureStorage.MaxEntry; ++i)
1062 if (CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i))
1063 for (uint32 diff = 0; diff < MAX_DIFFICULTY - 1; ++diff)
1064 if (cInfo->DifficultyEntry[diff])
1065 difficultyCreatures[diff].insert(cInfo->DifficultyEntry[diff]);
1067 // build single time for check spawnmask
1068 std::map<uint32,uint32> spawnMasks;
1069 for(uint32 i = 0; i < sMapStore.GetNumRows(); ++i)
1070 if(sMapStore.LookupEntry(i))
1071 for(int k = 0; k < MAX_DIFFICULTY; ++k)
1072 if (GetMapDifficultyData(i,Difficulty(k)))
1073 spawnMasks[i] |= (1 << k);
1075 barGoLink bar(result->GetRowCount());
1079 Field *fields = result->Fetch();
1080 bar.step();
1082 uint32 guid = fields[ 0].GetUInt32();
1083 uint32 entry = fields[ 1].GetUInt32();
1085 CreatureInfo const* cInfo = GetCreatureTemplate(entry);
1086 if(!cInfo)
1088 sLog.outErrorDb("Table `creature` has creature (GUID: %u) with non existing creature entry %u, skipped.", guid, entry);
1089 continue;
1092 CreatureData& data = mCreatureDataMap[guid];
1094 data.id = entry;
1095 data.mapid = fields[ 2].GetUInt32();
1096 data.displayid = fields[ 3].GetUInt32();
1097 data.equipmentId = fields[ 4].GetUInt32();
1098 data.posX = fields[ 5].GetFloat();
1099 data.posY = fields[ 6].GetFloat();
1100 data.posZ = fields[ 7].GetFloat();
1101 data.orientation = fields[ 8].GetFloat();
1102 data.spawntimesecs = fields[ 9].GetUInt32();
1103 data.spawndist = fields[10].GetFloat();
1104 data.currentwaypoint= fields[11].GetUInt32();
1105 data.curhealth = fields[12].GetUInt32();
1106 data.curmana = fields[13].GetUInt32();
1107 data.is_dead = fields[14].GetBool();
1108 data.movementType = fields[15].GetUInt8();
1109 data.spawnMask = fields[16].GetUInt8();
1110 data.phaseMask = fields[17].GetUInt16();
1111 int16 gameEvent = fields[18].GetInt16();
1112 int16 PoolId = fields[19].GetInt16();
1114 MapEntry const* mapEntry = sMapStore.LookupEntry(data.mapid);
1115 if(!mapEntry)
1117 sLog.outErrorDb("Table `creature` have creature (GUID: %u) that spawned at not existed map (Id: %u), skipped.",guid, data.mapid );
1118 continue;
1121 if (data.spawnMask & ~spawnMasks[data.mapid])
1122 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 );
1124 bool ok = true;
1125 for (uint32 diff = 0; diff < MAX_DIFFICULTY - 1 && ok; ++diff)
1127 if (difficultyCreatures[diff].find(data.id) != difficultyCreatures[diff].end())
1129 sLog.outErrorDb("Table `creature` have creature (GUID: %u) that listed as difficulty %u template (entry: %u) in `creature_template`, skipped.",
1130 guid, diff + 1, data.id );
1131 ok = false;
1134 if (!ok)
1135 continue;
1137 if(data.equipmentId > 0) // -1 no equipment, 0 use default
1139 if(!GetEquipmentInfo(data.equipmentId))
1141 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);
1142 data.equipmentId = -1;
1146 if(cInfo->RegenHealth && data.curhealth < cInfo->minhealth)
1148 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 );
1149 data.curhealth = cInfo->minhealth;
1152 if(cInfo->flags_extra & CREATURE_FLAG_EXTRA_INSTANCE_BIND)
1154 if(!mapEntry || !mapEntry->IsDungeon())
1155 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);
1158 if(data.curmana < cInfo->minmana)
1160 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 );
1161 data.curmana = cInfo->minmana;
1164 if(data.spawndist < 0.0f)
1166 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `spawndist`< 0, set to 0.",guid,data.id );
1167 data.spawndist = 0.0f;
1169 else if(data.movementType == RANDOM_MOTION_TYPE)
1171 if(data.spawndist == 0.0f)
1173 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 );
1174 data.movementType = IDLE_MOTION_TYPE;
1177 else if(data.movementType == IDLE_MOTION_TYPE)
1179 if(data.spawndist != 0.0f)
1181 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `MovementType`=0 (idle) have `spawndist`<>0, set to 0.",guid,data.id );
1182 data.spawndist = 0.0f;
1186 if(data.phaseMask==0)
1188 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `phaseMask`=0 (not visible for anyone), set to 1.",guid,data.id );
1189 data.phaseMask = 1;
1192 if (gameEvent==0 && PoolId==0) // if not this is to be managed by GameEvent System or Pool system
1193 AddCreatureToGrid(guid, &data);
1195 ++count;
1197 } while (result->NextRow());
1199 delete result;
1201 sLog.outString();
1202 sLog.outString( ">> Loaded %lu creatures", (unsigned long)mCreatureDataMap.size() );
1205 void ObjectMgr::AddCreatureToGrid(uint32 guid, CreatureData const* data)
1207 uint8 mask = data->spawnMask;
1208 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1210 if(mask & 1)
1212 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1213 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1215 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1216 cell_guids.creatures.insert(guid);
1221 void ObjectMgr::RemoveCreatureFromGrid(uint32 guid, CreatureData const* data)
1223 uint8 mask = data->spawnMask;
1224 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1226 if(mask & 1)
1228 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1229 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1231 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1232 cell_guids.creatures.erase(guid);
1237 void ObjectMgr::LoadGameobjects()
1239 uint32 count = 0;
1241 // 0 1 2 3 4 5 6
1242 QueryResult *result = WorldDatabase.Query("SELECT gameobject.guid, id, map, position_x, position_y, position_z, orientation,"
1243 // 7 8 9 10 11 12 13 14 15 16 17
1244 "rotation0, rotation1, rotation2, rotation3, spawntimesecs, animprogress, state, spawnMask, phaseMask, event, pool_entry "
1245 "FROM gameobject LEFT OUTER JOIN game_event_gameobject ON gameobject.guid = game_event_gameobject.guid "
1246 "LEFT OUTER JOIN pool_gameobject ON gameobject.guid = pool_gameobject.guid");
1248 if(!result)
1250 barGoLink bar(1);
1252 bar.step();
1254 sLog.outString();
1255 sLog.outErrorDb(">> Loaded 0 gameobjects. DB table `gameobject` is empty.");
1256 return;
1259 // build single time for check spawnmask
1260 std::map<uint32,uint32> spawnMasks;
1261 for(uint32 i = 0; i < sMapStore.GetNumRows(); ++i)
1262 if(sMapStore.LookupEntry(i))
1263 for(int k = 0; k < MAX_DIFFICULTY; ++k)
1264 if (GetMapDifficultyData(i,Difficulty(k)))
1265 spawnMasks[i] |= (1 << k);
1267 barGoLink bar(result->GetRowCount());
1271 Field *fields = result->Fetch();
1272 bar.step();
1274 uint32 guid = fields[ 0].GetUInt32();
1275 uint32 entry = fields[ 1].GetUInt32();
1277 GameObjectInfo const* gInfo = GetGameObjectInfo(entry);
1278 if (!gInfo)
1280 sLog.outErrorDb("Table `gameobject` has gameobject (GUID: %u) with non existing gameobject entry %u, skipped.", guid, entry);
1281 continue;
1284 if(!gInfo->displayId)
1286 switch(gInfo->type)
1288 // can be invisible always and then not req. display id in like case
1289 case GAMEOBJECT_TYPE_TRAP:
1290 case GAMEOBJECT_TYPE_SPELL_FOCUS:
1291 break;
1292 default:
1293 sLog.outErrorDb("Gameobject (GUID: %u Entry %u GoType: %u) have displayId == 0 and then will always invisible in game.", guid, entry, gInfo->type);
1294 break;
1297 else if (!sGameObjectDisplayInfoStore.LookupEntry(gInfo->displayId))
1299 sLog.outErrorDb("Gameobject (GUID: %u Entry %u GoType: %u) have invalid displayId (%u), not loaded.", guid, entry, gInfo->type, gInfo->displayId);
1300 continue;
1303 GameObjectData& data = mGameObjectDataMap[guid];
1305 data.id = entry;
1306 data.mapid = fields[ 2].GetUInt32();
1307 data.posX = fields[ 3].GetFloat();
1308 data.posY = fields[ 4].GetFloat();
1309 data.posZ = fields[ 5].GetFloat();
1310 data.orientation = fields[ 6].GetFloat();
1311 data.rotation0 = fields[ 7].GetFloat();
1312 data.rotation1 = fields[ 8].GetFloat();
1313 data.rotation2 = fields[ 9].GetFloat();
1314 data.rotation3 = fields[10].GetFloat();
1315 data.spawntimesecs = fields[11].GetInt32();
1317 MapEntry const* mapEntry = sMapStore.LookupEntry(data.mapid);
1318 if(!mapEntry)
1320 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) that spawned at not existed map (Id: %u), skip", guid, data.id, data.mapid);
1321 continue;
1324 if (data.spawnMask & ~spawnMasks[data.mapid])
1325 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);
1327 if (data.spawntimesecs == 0 && gInfo->IsDespawnAtAction())
1329 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with `spawntimesecs` (0) value, but gameobejct marked as despawnable at action.", guid, data.id);
1332 data.animprogress = fields[12].GetUInt32();
1334 uint32 go_state = fields[13].GetUInt32();
1335 if (go_state >= MAX_GO_STATE)
1337 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with invalid `state` (%u) value, skip", guid, data.id, go_state);
1338 continue;
1340 data.go_state = GOState(go_state);
1342 data.spawnMask = fields[14].GetUInt8();
1343 data.phaseMask = fields[15].GetUInt16();
1344 int16 gameEvent = fields[16].GetInt16();
1345 int16 PoolId = fields[17].GetInt16();
1347 if (data.rotation2 < -1.0f || data.rotation2 > 1.0f)
1349 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with invalid rotation2 (%f) value, skip", guid, data.id, data.rotation2);
1350 continue;
1353 if (data.rotation3 < -1.0f || data.rotation3 > 1.0f)
1355 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with invalid rotation3 (%f) value, skip", guid, data.id, data.rotation3);
1356 continue;
1359 if(!MapManager::IsValidMapCoord(data.mapid, data.posX, data.posY, data.posZ, data.orientation))
1361 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with invalid coordinates, skip", guid, data.id);
1362 continue;
1365 if(data.phaseMask == 0)
1367 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with `phaseMask`=0 (not visible for anyone), set to 1.", guid, data.id);
1368 data.phaseMask = 1;
1371 if (gameEvent == 0 && PoolId == 0) // if not this is to be managed by GameEvent System or Pool system
1372 AddGameobjectToGrid(guid, &data);
1373 ++count;
1375 } while (result->NextRow());
1377 delete result;
1379 sLog.outString();
1380 sLog.outString( ">> Loaded %lu gameobjects", (unsigned long)mGameObjectDataMap.size());
1383 void ObjectMgr::AddGameobjectToGrid(uint32 guid, GameObjectData const* data)
1385 uint8 mask = data->spawnMask;
1386 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1388 if(mask & 1)
1390 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1391 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1393 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1394 cell_guids.gameobjects.insert(guid);
1399 void ObjectMgr::RemoveGameobjectFromGrid(uint32 guid, GameObjectData const* data)
1401 uint8 mask = data->spawnMask;
1402 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1404 if(mask & 1)
1406 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1407 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1409 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1410 cell_guids.gameobjects.erase(guid);
1415 void ObjectMgr::LoadCreatureRespawnTimes()
1417 // remove outdated data
1418 WorldDatabase.DirectExecute("DELETE FROM creature_respawn WHERE respawntime <= UNIX_TIMESTAMP(NOW())");
1420 uint32 count = 0;
1422 QueryResult *result = WorldDatabase.Query("SELECT guid,respawntime,instance FROM creature_respawn");
1424 if(!result)
1426 barGoLink bar(1);
1428 bar.step();
1430 sLog.outString();
1431 sLog.outString(">> Loaded 0 creature respawn time.");
1432 return;
1435 barGoLink bar(result->GetRowCount());
1439 Field *fields = result->Fetch();
1440 bar.step();
1442 uint32 loguid = fields[0].GetUInt32();
1443 uint64 respawn_time = fields[1].GetUInt64();
1444 uint32 instance = fields[2].GetUInt32();
1446 mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = time_t(respawn_time);
1448 ++count;
1449 } while (result->NextRow());
1451 delete result;
1453 sLog.outString( ">> Loaded %lu creature respawn times", (unsigned long)mCreatureRespawnTimes.size() );
1454 sLog.outString();
1457 void ObjectMgr::LoadGameobjectRespawnTimes()
1459 // remove outdated data
1460 WorldDatabase.DirectExecute("DELETE FROM gameobject_respawn WHERE respawntime <= UNIX_TIMESTAMP(NOW())");
1462 uint32 count = 0;
1464 QueryResult *result = WorldDatabase.Query("SELECT guid,respawntime,instance FROM gameobject_respawn");
1466 if(!result)
1468 barGoLink bar(1);
1470 bar.step();
1472 sLog.outString();
1473 sLog.outString(">> Loaded 0 gameobject respawn time.");
1474 return;
1477 barGoLink bar(result->GetRowCount());
1481 Field *fields = result->Fetch();
1482 bar.step();
1484 uint32 loguid = fields[0].GetUInt32();
1485 uint64 respawn_time = fields[1].GetUInt64();
1486 uint32 instance = fields[2].GetUInt32();
1488 mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = time_t(respawn_time);
1490 ++count;
1491 } while (result->NextRow());
1493 delete result;
1495 sLog.outString( ">> Loaded %lu gameobject respawn times", (unsigned long)mGORespawnTimes.size() );
1496 sLog.outString();
1499 // name must be checked to correctness (if received) before call this function
1500 uint64 ObjectMgr::GetPlayerGUIDByName(std::string name) const
1502 uint64 guid = 0;
1504 CharacterDatabase.escape_string(name);
1506 // Player name safe to sending to DB (checked at login) and this function using
1507 QueryResult *result = CharacterDatabase.PQuery("SELECT guid FROM characters WHERE name = '%s'", name.c_str());
1508 if(result)
1510 guid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
1512 delete result;
1515 return guid;
1518 bool ObjectMgr::GetPlayerNameByGUID(const uint64 &guid, std::string &name) const
1520 // prevent DB access for online player
1521 if(Player* player = GetPlayer(guid))
1523 name = player->GetName();
1524 return true;
1527 QueryResult *result = CharacterDatabase.PQuery("SELECT name FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1529 if(result)
1531 name = (*result)[0].GetCppString();
1532 delete result;
1533 return true;
1536 return false;
1539 uint32 ObjectMgr::GetPlayerTeamByGUID(const uint64 &guid) const
1541 // prevent DB access for online player
1542 if(Player* player = GetPlayer(guid))
1544 return Player::TeamForRace(player->getRace());
1547 QueryResult *result = CharacterDatabase.PQuery("SELECT race FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1549 if(result)
1551 uint8 race = (*result)[0].GetUInt8();
1552 delete result;
1553 return Player::TeamForRace(race);
1556 return 0;
1559 uint32 ObjectMgr::GetPlayerAccountIdByGUID(const uint64 &guid) const
1561 // prevent DB access for online player
1562 if(Player* player = GetPlayer(guid))
1564 return player->GetSession()->GetAccountId();
1567 QueryResult *result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1568 if(result)
1570 uint32 acc = (*result)[0].GetUInt32();
1571 delete result;
1572 return acc;
1575 return 0;
1578 uint32 ObjectMgr::GetPlayerAccountIdByPlayerName(const std::string& name) const
1580 QueryResult *result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'", name.c_str());
1581 if(result)
1583 uint32 acc = (*result)[0].GetUInt32();
1584 delete result;
1585 return acc;
1588 return 0;
1591 void ObjectMgr::LoadItemLocales()
1593 mItemLocaleMap.clear(); // need for reload case
1595 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");
1597 if(!result)
1599 barGoLink bar(1);
1601 bar.step();
1603 sLog.outString();
1604 sLog.outString(">> Loaded 0 Item locale strings. DB table `locales_item` is empty.");
1605 return;
1608 barGoLink bar(result->GetRowCount());
1612 Field *fields = result->Fetch();
1613 bar.step();
1615 uint32 entry = fields[0].GetUInt32();
1617 ItemLocale& data = mItemLocaleMap[entry];
1619 for(int i = 1; i < MAX_LOCALE; ++i)
1621 std::string str = fields[1+2*(i-1)].GetCppString();
1622 if(!str.empty())
1624 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
1625 if(idx >= 0)
1627 if(data.Name.size() <= idx)
1628 data.Name.resize(idx+1);
1630 data.Name[idx] = str;
1634 str = fields[1+2*(i-1)+1].GetCppString();
1635 if(!str.empty())
1637 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
1638 if(idx >= 0)
1640 if(data.Description.size() <= idx)
1641 data.Description.resize(idx+1);
1643 data.Description[idx] = str;
1647 } while (result->NextRow());
1649 delete result;
1651 sLog.outString();
1652 sLog.outString( ">> Loaded %lu Item locale strings", (unsigned long)mItemLocaleMap.size() );
1655 struct SQLItemLoader : public SQLStorageLoaderBase<SQLItemLoader>
1657 template<class D>
1658 void convert_from_str(uint32 /*field_pos*/, char *src, D &dst)
1660 dst = D(sObjectMgr.GetScriptId(src));
1664 void ObjectMgr::LoadItemPrototypes()
1666 SQLItemLoader loader;
1667 loader.Load(sItemStorage);
1668 sLog.outString( ">> Loaded %u item prototypes", sItemStorage.RecordCount );
1669 sLog.outString();
1671 // check data correctness
1672 for(uint32 i = 1; i < sItemStorage.MaxEntry; ++i)
1674 ItemPrototype const* proto = sItemStorage.LookupEntry<ItemPrototype >(i);
1675 ItemEntry const *dbcitem = sItemStore.LookupEntry(i);
1676 if(!proto)
1678 /* to many errors, and possible not all items really used in game
1679 if (dbcitem)
1680 sLog.outErrorDb("Item (Entry: %u) doesn't exists in DB, but must exist.",i);
1682 continue;
1685 if(dbcitem)
1687 if(proto->Class != dbcitem->Class)
1689 sLog.outErrorDb("Item (Entry: %u) not correct class %u, must be %u (still using DB value).",i,proto->Class,dbcitem->Class);
1690 // It safe let use Class from DB
1692 /* disabled: have some strange wrong cases for Subclass values.
1693 for enable also uncomment Subclass field in ItemEntry structure and in Itemfmt[]
1694 if(proto->SubClass != dbcitem->SubClass)
1696 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);
1697 // It safe let use Subclass from DB
1701 if(proto->Unk0 != dbcitem->Unk0)
1703 sLog.outErrorDb("Item (Entry: %u) not correct %i Unk0, must be %i (still using DB value).",i,proto->Unk0,dbcitem->Unk0);
1704 // It safe let use Unk0 from DB
1707 if(proto->Material != dbcitem->Material)
1709 sLog.outErrorDb("Item (Entry: %u) not correct %i material, must be %i (still using DB value).",i,proto->Material,dbcitem->Material);
1710 // It safe let use Material from DB
1713 if(proto->InventoryType != dbcitem->InventoryType)
1715 sLog.outErrorDb("Item (Entry: %u) not correct %u inventory type, must be %u (still using DB value).",i,proto->InventoryType,dbcitem->InventoryType);
1716 // It safe let use InventoryType from DB
1719 if(proto->DisplayInfoID != dbcitem->DisplayId)
1721 sLog.outErrorDb("Item (Entry: %u) not correct %u display id, must be %u (using it).",i,proto->DisplayInfoID,dbcitem->DisplayId);
1722 const_cast<ItemPrototype*>(proto)->DisplayInfoID = dbcitem->DisplayId;
1724 if(proto->Sheath != dbcitem->Sheath)
1726 sLog.outErrorDb("Item (Entry: %u) not correct %u sheath, must be %u (using it).",i,proto->Sheath,dbcitem->Sheath);
1727 const_cast<ItemPrototype*>(proto)->Sheath = dbcitem->Sheath;
1730 else
1732 sLog.outErrorDb("Item (Entry: %u) not correct (not listed in list of existed items).",i);
1735 if(proto->Class >= MAX_ITEM_CLASS)
1737 sLog.outErrorDb("Item (Entry: %u) has wrong Class value (%u)",i,proto->Class);
1738 const_cast<ItemPrototype*>(proto)->Class = ITEM_CLASS_MISC;
1741 if(proto->SubClass >= MaxItemSubclassValues[proto->Class])
1743 sLog.outErrorDb("Item (Entry: %u) has wrong Subclass value (%u) for class %u",i,proto->SubClass,proto->Class);
1744 const_cast<ItemPrototype*>(proto)->SubClass = 0;// exist for all item classes
1747 if(proto->Quality >= MAX_ITEM_QUALITY)
1749 sLog.outErrorDb("Item (Entry: %u) has wrong Quality value (%u)",i,proto->Quality);
1750 const_cast<ItemPrototype*>(proto)->Quality = ITEM_QUALITY_NORMAL;
1753 if(proto->BuyCount <= 0)
1755 sLog.outErrorDb("Item (Entry: %u) has wrong BuyCount value (%u), set to default(1).",i,proto->BuyCount);
1756 const_cast<ItemPrototype*>(proto)->BuyCount = 1;
1759 if(proto->InventoryType >= MAX_INVTYPE)
1761 sLog.outErrorDb("Item (Entry: %u) has wrong InventoryType value (%u)",i,proto->InventoryType);
1762 const_cast<ItemPrototype*>(proto)->InventoryType = INVTYPE_NON_EQUIP;
1765 if(proto->RequiredSkill >= MAX_SKILL_TYPE)
1767 sLog.outErrorDb("Item (Entry: %u) has wrong RequiredSkill value (%u)",i,proto->RequiredSkill);
1768 const_cast<ItemPrototype*>(proto)->RequiredSkill = 0;
1772 // can be used in equip slot, as page read use in inventory, or spell casting at use
1773 bool req = proto->InventoryType!=INVTYPE_NON_EQUIP || proto->PageText;
1774 if(!req)
1776 for (int j = 0; j < MAX_ITEM_PROTO_SPELLS; ++j)
1778 if(proto->Spells[j].SpellId)
1780 req = true;
1781 break;
1786 if(req)
1788 if(!(proto->AllowableClass & CLASSMASK_ALL_PLAYABLE))
1789 sLog.outErrorDb("Item (Entry: %u) not have in `AllowableClass` any playable classes (%u) and can't be equipped or use.",i,proto->AllowableClass);
1791 if(!(proto->AllowableRace & RACEMASK_ALL_PLAYABLE))
1792 sLog.outErrorDb("Item (Entry: %u) not have in `AllowableRace` any playable races (%u) and can't be equipped or use.",i,proto->AllowableRace);
1796 if(proto->RequiredSpell && !sSpellStore.LookupEntry(proto->RequiredSpell))
1798 sLog.outErrorDb("Item (Entry: %u) have wrong (non-existed) spell in RequiredSpell (%u)",i,proto->RequiredSpell);
1799 const_cast<ItemPrototype*>(proto)->RequiredSpell = 0;
1802 if(proto->RequiredReputationRank >= MAX_REPUTATION_RANK)
1803 sLog.outErrorDb("Item (Entry: %u) has wrong reputation rank in RequiredReputationRank (%u), item can't be used.",i,proto->RequiredReputationRank);
1805 if(proto->RequiredReputationFaction)
1807 if(!sFactionStore.LookupEntry(proto->RequiredReputationFaction))
1809 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) faction in RequiredReputationFaction (%u)",i,proto->RequiredReputationFaction);
1810 const_cast<ItemPrototype*>(proto)->RequiredReputationFaction = 0;
1813 if(proto->RequiredReputationRank == MIN_REPUTATION_RANK)
1814 sLog.outErrorDb("Item (Entry: %u) has min. reputation rank in RequiredReputationRank (0) but RequiredReputationFaction > 0, faction setting is useless.",i);
1816 else if(proto->RequiredReputationRank > MIN_REPUTATION_RANK)
1817 sLog.outErrorDb("Item (Entry: %u) has RequiredReputationFaction ==0 but RequiredReputationRank > 0, rank setting is useless.",i);
1819 if(proto->MaxCount < -1)
1821 sLog.outErrorDb("Item (Entry: %u) has too large negative in maxcount (%i), replace by value (-1) no storing limits.",i,proto->MaxCount);
1822 const_cast<ItemPrototype*>(proto)->MaxCount = -1;
1825 if(proto->Stackable == 0)
1827 sLog.outErrorDb("Item (Entry: %u) has wrong value in stackable (%i), replace by default 1.",i,proto->Stackable);
1828 const_cast<ItemPrototype*>(proto)->Stackable = 1;
1830 else if(proto->Stackable < -1)
1832 sLog.outErrorDb("Item (Entry: %u) has too large negative in stackable (%i), replace by value (-1) no stacking limits.",i,proto->Stackable);
1833 const_cast<ItemPrototype*>(proto)->Stackable = -1;
1835 else if(proto->Stackable > 1000)
1837 sLog.outErrorDb("Item (Entry: %u) has too large value in stackable (%u), replace by hardcoded upper limit (1000).",i,proto->Stackable);
1838 const_cast<ItemPrototype*>(proto)->Stackable = 1000;
1841 if(proto->ContainerSlots > MAX_BAG_SIZE)
1843 sLog.outErrorDb("Item (Entry: %u) has too large value in ContainerSlots (%u), replace by hardcoded limit (%u).",i,proto->ContainerSlots,MAX_BAG_SIZE);
1844 const_cast<ItemPrototype*>(proto)->ContainerSlots = MAX_BAG_SIZE;
1847 if(proto->StatsCount > MAX_ITEM_PROTO_STATS)
1849 sLog.outErrorDb("Item (Entry: %u) has too large value in statscount (%u), replace by hardcoded limit (%u).",i,proto->StatsCount,MAX_ITEM_PROTO_STATS);
1850 const_cast<ItemPrototype*>(proto)->StatsCount = MAX_ITEM_PROTO_STATS;
1853 for (int j = 0; j < MAX_ITEM_PROTO_STATS; ++j)
1855 // for ItemStatValue != 0
1856 if(proto->ItemStat[j].ItemStatValue && proto->ItemStat[j].ItemStatType >= MAX_ITEM_MOD)
1858 sLog.outErrorDb("Item (Entry: %u) has wrong stat_type%d (%u)",i,j+1,proto->ItemStat[j].ItemStatType);
1859 const_cast<ItemPrototype*>(proto)->ItemStat[j].ItemStatType = 0;
1862 switch(proto->ItemStat[j].ItemStatType)
1864 case ITEM_MOD_SPELL_HEALING_DONE:
1865 case ITEM_MOD_SPELL_DAMAGE_DONE:
1866 sLog.outErrorDb("Item (Entry: %u) has deprecated stat_type%d (%u)",i,j+1,proto->ItemStat[j].ItemStatType);
1867 break;
1868 default:
1869 break;
1873 for (int j = 0; j < MAX_ITEM_PROTO_DAMAGES; ++j)
1875 if(proto->Damage[j].DamageType >= MAX_SPELL_SCHOOL)
1877 sLog.outErrorDb("Item (Entry: %u) has wrong dmg_type%d (%u)",i,j+1,proto->Damage[j].DamageType);
1878 const_cast<ItemPrototype*>(proto)->Damage[j].DamageType = 0;
1882 // special format
1883 if((proto->Spells[0].SpellId == SPELL_ID_GENERIC_LEARN) || (proto->Spells[0].SpellId == SPELL_ID_GENERIC_LEARN_PET))
1885 // spell_1
1886 if(proto->Spells[0].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
1888 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);
1889 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1890 const_cast<ItemPrototype*>(proto)->Spells[0].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1891 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1892 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1895 // spell_2 have learning spell
1896 if(proto->Spells[1].SpellTrigger != ITEM_SPELLTRIGGER_LEARN_SPELL_ID)
1898 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);
1899 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1900 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1901 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1903 else if(!proto->Spells[1].SpellId)
1905 sLog.outErrorDb("Item (Entry: %u) not has expected spell in spellid_%d in special learning format.",i,1+1);
1906 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1907 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1909 else
1911 SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[1].SpellId);
1912 if(!spellInfo)
1914 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%u)",i,1+1,proto->Spells[1].SpellId);
1915 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1916 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1917 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1919 // allowed only in special format
1920 else if((proto->Spells[1].SpellId==SPELL_ID_GENERIC_LEARN) || (proto->Spells[1].SpellId==SPELL_ID_GENERIC_LEARN_PET))
1922 sLog.outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%u)",i,1+1,proto->Spells[1].SpellId);
1923 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1924 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1925 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1929 // spell_3*,spell_4*,spell_5* is empty
1930 for (int j = 2; j < MAX_ITEM_PROTO_SPELLS; ++j)
1932 if(proto->Spells[j].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
1934 sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)",i,j+1,proto->Spells[j].SpellTrigger);
1935 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1936 const_cast<ItemPrototype*>(proto)->Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1938 else if(proto->Spells[j].SpellId != 0)
1940 sLog.outErrorDb("Item (Entry: %u) has wrong spell in spellid_%d (%u) for learning special format",i,j+1,proto->Spells[j].SpellId);
1941 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1945 // normal spell list
1946 else
1948 for (int j = 0; j < MAX_ITEM_PROTO_SPELLS; ++j)
1950 if (proto->Spells[j].SpellTrigger >= MAX_ITEM_SPELLTRIGGER || proto->Spells[j].SpellTrigger == ITEM_SPELLTRIGGER_LEARN_SPELL_ID)
1952 sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)",i,j+1,proto->Spells[j].SpellTrigger);
1953 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1954 const_cast<ItemPrototype*>(proto)->Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1956 // on hit can be sued only at weapon
1957 else if (proto->Spells[j].SpellTrigger == ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
1959 if(proto->Class != ITEM_CLASS_WEAPON)
1960 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);
1963 if(proto->Spells[j].SpellId)
1965 SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[j].SpellId);
1966 if(!spellInfo)
1968 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%u)",i,j+1,proto->Spells[j].SpellId);
1969 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1971 // allowed only in special format
1972 else if((proto->Spells[j].SpellId==SPELL_ID_GENERIC_LEARN) || (proto->Spells[j].SpellId==SPELL_ID_GENERIC_LEARN_PET))
1974 sLog.outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%u)",i,j+1,proto->Spells[j].SpellId);
1975 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1981 if(proto->Bonding >= MAX_BIND_TYPE)
1982 sLog.outErrorDb("Item (Entry: %u) has wrong Bonding value (%u)",i,proto->Bonding);
1984 if(proto->PageText && !sPageTextStore.LookupEntry<PageText>(proto->PageText))
1985 sLog.outErrorDb("Item (Entry: %u) has non existing first page (Id:%u)", i,proto->PageText);
1987 if(proto->LockID && !sLockStore.LookupEntry(proto->LockID))
1988 sLog.outErrorDb("Item (Entry: %u) has wrong LockID (%u)",i,proto->LockID);
1990 if(proto->Sheath >= MAX_SHEATHETYPE)
1992 sLog.outErrorDb("Item (Entry: %u) has wrong Sheath (%u)",i,proto->Sheath);
1993 const_cast<ItemPrototype*>(proto)->Sheath = SHEATHETYPE_NONE;
1996 if(proto->RandomProperty && !sItemRandomPropertiesStore.LookupEntry(GetItemEnchantMod(proto->RandomProperty)))
1998 sLog.outErrorDb("Item (Entry: %u) has unknown (wrong or not listed in `item_enchantment_template`) RandomProperty (%u)",i,proto->RandomProperty);
1999 const_cast<ItemPrototype*>(proto)->RandomProperty = 0;
2002 if(proto->RandomSuffix && !sItemRandomSuffixStore.LookupEntry(GetItemEnchantMod(proto->RandomSuffix)))
2004 sLog.outErrorDb("Item (Entry: %u) has wrong RandomSuffix (%u)",i,proto->RandomSuffix);
2005 const_cast<ItemPrototype*>(proto)->RandomSuffix = 0;
2008 if(proto->ItemSet && !sItemSetStore.LookupEntry(proto->ItemSet))
2010 sLog.outErrorDb("Item (Entry: %u) have wrong ItemSet (%u)",i,proto->ItemSet);
2011 const_cast<ItemPrototype*>(proto)->ItemSet = 0;
2014 if(proto->Area && !GetAreaEntryByAreaID(proto->Area))
2015 sLog.outErrorDb("Item (Entry: %u) has wrong Area (%u)",i,proto->Area);
2017 if(proto->Map && !sMapStore.LookupEntry(proto->Map))
2018 sLog.outErrorDb("Item (Entry: %u) has wrong Map (%u)",i,proto->Map);
2020 if(proto->BagFamily)
2022 // check bits
2023 for(uint32 j = 0; j < sizeof(proto->BagFamily)*8; ++j)
2025 uint32 mask = 1 << j;
2026 if((proto->BagFamily & mask)==0)
2027 continue;
2029 ItemBagFamilyEntry const* bf = sItemBagFamilyStore.LookupEntry(j+1);
2030 if(!bf)
2032 sLog.outErrorDb("Item (Entry: %u) has bag family bit set not listed in ItemBagFamily.dbc, remove bit",i);
2033 const_cast<ItemPrototype*>(proto)->BagFamily &= ~mask;
2034 continue;
2037 if(BAG_FAMILY_MASK_CURRENCY_TOKENS & mask)
2039 CurrencyTypesEntry const* ctEntry = sCurrencyTypesStore.LookupEntry(proto->ItemId);
2040 if(!ctEntry)
2042 sLog.outErrorDb("Item (Entry: %u) has currency bag family bit set in BagFamily but not listed in CurrencyTypes.dbc, remove bit",i);
2043 const_cast<ItemPrototype*>(proto)->BagFamily &= ~mask;
2049 if(proto->TotemCategory && !sTotemCategoryStore.LookupEntry(proto->TotemCategory))
2050 sLog.outErrorDb("Item (Entry: %u) has wrong TotemCategory (%u)",i,proto->TotemCategory);
2052 for (int j = 0; j < MAX_ITEM_PROTO_SOCKETS; ++j)
2054 if(proto->Socket[j].Color && (proto->Socket[j].Color & SOCKET_COLOR_ALL) != proto->Socket[j].Color)
2056 sLog.outErrorDb("Item (Entry: %u) has wrong socketColor_%d (%u)",i,j+1,proto->Socket[j].Color);
2057 const_cast<ItemPrototype*>(proto)->Socket[j].Color = 0;
2061 if(proto->GemProperties && !sGemPropertiesStore.LookupEntry(proto->GemProperties))
2062 sLog.outErrorDb("Item (Entry: %u) has wrong GemProperties (%u)",i,proto->GemProperties);
2064 if(proto->FoodType >= MAX_PET_DIET)
2066 sLog.outErrorDb("Item (Entry: %u) has wrong FoodType value (%u)",i,proto->FoodType);
2067 const_cast<ItemPrototype*>(proto)->FoodType = 0;
2070 if(proto->ItemLimitCategory && !sItemLimitCategoryStore.LookupEntry(proto->ItemLimitCategory))
2072 sLog.outErrorDb("Item (Entry: %u) has wrong LimitCategory value (%u)",i,proto->ItemLimitCategory);
2073 const_cast<ItemPrototype*>(proto)->ItemLimitCategory = 0;
2076 if(proto->HolidayId && !sHolidaysStore.LookupEntry(proto->HolidayId))
2078 sLog.outErrorDb("Item (Entry: %u) has wrong HolidayId value (%u)", i, proto->HolidayId);
2079 const_cast<ItemPrototype*>(proto)->HolidayId = 0;
2084 void ObjectMgr::LoadItemRequiredTarget()
2086 m_ItemRequiredTarget.clear(); // needed for reload case
2088 uint32 count = 0;
2090 QueryResult *result = WorldDatabase.Query("SELECT entry,type,targetEntry FROM item_required_target");
2092 if (!result)
2094 barGoLink bar(1);
2096 bar.step();
2098 sLog.outString();
2099 sLog.outErrorDb(">> Loaded 0 ItemRequiredTarget. DB table `item_required_target` is empty.");
2100 return;
2103 barGoLink bar(result->GetRowCount());
2107 Field *fields = result->Fetch();
2108 bar.step();
2110 uint32 uiItemId = fields[0].GetUInt32();
2111 uint32 uiType = fields[1].GetUInt32();
2112 uint32 uiTargetEntry = fields[2].GetUInt32();
2114 ItemPrototype const* pItemProto = sItemStorage.LookupEntry<ItemPrototype>(uiItemId);
2116 if (!pItemProto)
2118 sLog.outErrorDb("Table `item_required_target`: Entry %u listed for TargetEntry %u does not exist in `item_template`.",uiItemId,uiTargetEntry);
2119 continue;
2122 bool bIsItemSpellValid = false;
2124 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
2126 if (SpellEntry const* pSpellInfo = sSpellStore.LookupEntry(pItemProto->Spells[i].SpellId))
2128 if (pItemProto->Spells[i].SpellTrigger == ITEM_SPELLTRIGGER_ON_USE ||
2129 pItemProto->Spells[i].SpellTrigger == ITEM_SPELLTRIGGER_ON_NO_DELAY_USE)
2131 SpellScriptTargetBounds bounds = sSpellMgr.GetSpellScriptTargetBounds(pSpellInfo->Id);
2132 if (bounds.first != bounds.second)
2133 break;
2135 for (int j = 0; j < 3; ++j)
2137 if (pSpellInfo->EffectImplicitTargetA[j] == TARGET_CHAIN_DAMAGE ||
2138 pSpellInfo->EffectImplicitTargetB[j] == TARGET_CHAIN_DAMAGE ||
2139 pSpellInfo->EffectImplicitTargetA[j] == TARGET_DUELVSPLAYER ||
2140 pSpellInfo->EffectImplicitTargetB[j] == TARGET_DUELVSPLAYER)
2142 bIsItemSpellValid = true;
2143 break;
2146 if (bIsItemSpellValid)
2147 break;
2152 if (!bIsItemSpellValid)
2154 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);
2155 continue;
2158 if (!uiType || uiType > MAX_ITEM_REQ_TARGET_TYPE)
2160 sLog.outErrorDb("Table `item_required_target`: Type %u for TargetEntry %u is incorrect.",uiType,uiTargetEntry);
2161 continue;
2164 if (!uiTargetEntry)
2166 sLog.outErrorDb("Table `item_required_target`: TargetEntry == 0 for Type (%u).",uiType);
2167 continue;
2170 if (!sCreatureStorage.LookupEntry<CreatureInfo>(uiTargetEntry))
2172 sLog.outErrorDb("Table `item_required_target`: creature template entry %u does not exist.",uiTargetEntry);
2173 continue;
2176 m_ItemRequiredTarget.insert(ItemRequiredTargetMap::value_type(uiItemId,ItemRequiredTarget(ItemRequiredTargetType(uiType),uiTargetEntry)));
2178 ++count;
2179 } while (result->NextRow());
2181 delete result;
2183 sLog.outString();
2184 sLog.outString(">> Loaded %u Item required targets", count);
2187 void ObjectMgr::LoadPetLevelInfo()
2189 // Loading levels data
2191 // 0 1 2 3 4 5 6 7 8 9
2192 QueryResult *result = WorldDatabase.Query("SELECT creature_entry, level, hp, mana, str, agi, sta, inte, spi, armor FROM pet_levelstats");
2194 uint32 count = 0;
2196 if (!result)
2198 barGoLink bar( 1 );
2199 bar.step();
2201 sLog.outString();
2202 sLog.outString(">> Loaded %u level pet stats definitions", count);
2203 sLog.outErrorDb("Error loading `pet_levelstats` table or empty table.");
2204 return;
2207 barGoLink bar( result->GetRowCount() );
2211 Field* fields = result->Fetch();
2213 uint32 creature_id = fields[0].GetUInt32();
2214 if(!sCreatureStorage.LookupEntry<CreatureInfo>(creature_id))
2216 sLog.outErrorDb("Wrong creature id %u in `pet_levelstats` table, ignoring.",creature_id);
2217 continue;
2220 uint32 current_level = fields[1].GetUInt32();
2221 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2223 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2224 sLog.outErrorDb("Wrong (> %u) level %u in `pet_levelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
2225 else
2227 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `pet_levelstats` table, ignoring.",current_level);
2228 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
2230 continue;
2232 else if(current_level < 1)
2234 sLog.outErrorDb("Wrong (<1) level %u in `pet_levelstats` table, ignoring.",current_level);
2235 continue;
2238 PetLevelInfo*& pInfoMapEntry = petInfo[creature_id];
2240 if(pInfoMapEntry==NULL)
2241 pInfoMapEntry = new PetLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
2243 // data for level 1 stored in [0] array element, ...
2244 PetLevelInfo* pLevelInfo = &pInfoMapEntry[current_level-1];
2246 pLevelInfo->health = fields[2].GetUInt16();
2247 pLevelInfo->mana = fields[3].GetUInt16();
2248 pLevelInfo->armor = fields[9].GetUInt16();
2250 for (int i = 0; i < MAX_STATS; i++)
2252 pLevelInfo->stats[i] = fields[i+4].GetUInt16();
2255 bar.step();
2256 ++count;
2258 while (result->NextRow());
2260 delete result;
2262 sLog.outString();
2263 sLog.outString( ">> Loaded %u level pet stats definitions", count );
2266 // Fill gaps and check integrity
2267 for (PetLevelInfoMap::iterator itr = petInfo.begin(); itr != petInfo.end(); ++itr)
2269 PetLevelInfo* pInfo = itr->second;
2271 // fatal error if no level 1 data
2272 if(!pInfo || pInfo[0].health == 0 )
2274 sLog.outErrorDb("Creature %u does not have pet stats data for Level 1!",itr->first);
2275 exit(1);
2278 // fill level gaps
2279 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2281 if(pInfo[level].health == 0)
2283 sLog.outErrorDb("Creature %u has no data for Level %i pet stats data, using data of Level %i.",itr->first,level+1, level);
2284 pInfo[level] = pInfo[level-1];
2290 PetLevelInfo const* ObjectMgr::GetPetLevelInfo(uint32 creature_id, uint32 level) const
2292 if(level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2293 level = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL);
2295 PetLevelInfoMap::const_iterator itr = petInfo.find(creature_id);
2296 if(itr == petInfo.end())
2297 return NULL;
2299 return &itr->second[level-1]; // data for level 1 stored in [0] array element, ...
2302 void ObjectMgr::LoadPlayerInfo()
2304 // Load playercreate
2306 // 0 1 2 3 4 5 6
2307 QueryResult *result = WorldDatabase.Query("SELECT race, class, map, zone, position_x, position_y, position_z FROM playercreateinfo");
2309 uint32 count = 0;
2311 if (!result)
2313 barGoLink bar( 1 );
2315 sLog.outString();
2316 sLog.outString( ">> Loaded %u player create definitions", count );
2317 sLog.outErrorDb( "Error loading `playercreateinfo` table or empty table.");
2318 exit(1);
2321 barGoLink bar( result->GetRowCount() );
2325 Field* fields = result->Fetch();
2327 uint32 current_race = fields[0].GetUInt32();
2328 uint32 current_class = fields[1].GetUInt32();
2329 uint32 mapId = fields[2].GetUInt32();
2330 uint32 zoneId = fields[3].GetUInt32();
2331 float positionX = fields[4].GetFloat();
2332 float positionY = fields[5].GetFloat();
2333 float positionZ = fields[6].GetFloat();
2335 if(current_race >= MAX_RACES)
2337 sLog.outErrorDb("Wrong race %u in `playercreateinfo` table, ignoring.",current_race);
2338 continue;
2341 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(current_race);
2342 if(!rEntry)
2344 sLog.outErrorDb("Wrong race %u in `playercreateinfo` table, ignoring.",current_race);
2345 continue;
2348 if(current_class >= MAX_CLASSES)
2350 sLog.outErrorDb("Wrong class %u in `playercreateinfo` table, ignoring.",current_class);
2351 continue;
2354 if(!sChrClassesStore.LookupEntry(current_class))
2356 sLog.outErrorDb("Wrong class %u in `playercreateinfo` table, ignoring.",current_class);
2357 continue;
2360 // accept DB data only for valid position (and non instanceable)
2361 if( !MapManager::IsValidMapCoord(mapId,positionX,positionY,positionZ) )
2363 sLog.outErrorDb("Wrong home position for class %u race %u pair in `playercreateinfo` table, ignoring.",current_class,current_race);
2364 continue;
2367 if( sMapStore.LookupEntry(mapId)->Instanceable() )
2369 sLog.outErrorDb("Home position in instanceable map for class %u race %u pair in `playercreateinfo` table, ignoring.",current_class,current_race);
2370 continue;
2373 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2375 pInfo->mapId = mapId;
2376 pInfo->zoneId = zoneId;
2377 pInfo->positionX = positionX;
2378 pInfo->positionY = positionY;
2379 pInfo->positionZ = positionZ;
2381 pInfo->displayId_m = rEntry->model_m;
2382 pInfo->displayId_f = rEntry->model_f;
2384 bar.step();
2385 ++count;
2387 while (result->NextRow());
2389 delete result;
2391 sLog.outString();
2392 sLog.outString( ">> Loaded %u player create definitions", count );
2395 // Load playercreate items
2397 // 0 1 2 3
2398 QueryResult *result = WorldDatabase.Query("SELECT race, class, itemid, amount FROM playercreateinfo_item");
2400 uint32 count = 0;
2402 if (!result)
2404 barGoLink bar( 1 );
2406 bar.step();
2408 sLog.outString();
2409 sLog.outString( ">> Loaded %u custom player create items", count );
2411 else
2413 barGoLink bar( result->GetRowCount() );
2417 Field* fields = result->Fetch();
2419 uint32 current_race = fields[0].GetUInt32();
2420 if(current_race >= MAX_RACES)
2422 sLog.outErrorDb("Wrong race %u in `playercreateinfo_item` table, ignoring.",current_race);
2423 continue;
2426 uint32 current_class = fields[1].GetUInt32();
2427 if(current_class >= MAX_CLASSES)
2429 sLog.outErrorDb("Wrong class %u in `playercreateinfo_item` table, ignoring.",current_class);
2430 continue;
2433 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2435 uint32 item_id = fields[2].GetUInt32();
2437 if(!GetItemPrototype(item_id))
2439 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);
2440 continue;
2443 uint32 amount = fields[3].GetUInt32();
2445 if(!amount)
2447 sLog.outErrorDb("Item id %u (class %u race %u) have amount==0 in `playercreateinfo_item` table, ignoring.",item_id,current_race,current_class);
2448 continue;
2451 pInfo->item.push_back(PlayerCreateInfoItem( item_id, amount));
2453 bar.step();
2454 ++count;
2456 while(result->NextRow());
2458 delete result;
2460 sLog.outString();
2461 sLog.outString( ">> Loaded %u custom player create items", count );
2465 // Load playercreate spells
2467 // 0 1 2
2468 QueryResult *result = WorldDatabase.Query("SELECT race, class, Spell FROM playercreateinfo_spell");
2470 uint32 count = 0;
2472 if (!result)
2474 barGoLink bar( 1 );
2476 sLog.outString();
2477 sLog.outString( ">> Loaded %u player create spells", count );
2478 sLog.outErrorDb( "Error loading `playercreateinfo_spell` table or empty table.");
2480 else
2482 barGoLink bar( result->GetRowCount() );
2486 Field* fields = result->Fetch();
2488 uint32 current_race = fields[0].GetUInt32();
2489 if(current_race >= MAX_RACES)
2491 sLog.outErrorDb("Wrong race %u in `playercreateinfo_spell` table, ignoring.",current_race);
2492 continue;
2495 uint32 current_class = fields[1].GetUInt32();
2496 if(current_class >= MAX_CLASSES)
2498 sLog.outErrorDb("Wrong class %u in `playercreateinfo_spell` table, ignoring.",current_class);
2499 continue;
2502 uint32 spell_id = fields[2].GetUInt32();
2503 if (!sSpellStore.LookupEntry(spell_id))
2505 sLog.outErrorDb("Non existing spell %u in `playercreateinfo_spell` table, ignoring.", spell_id);
2506 continue;
2509 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2510 pInfo->spell.push_back(spell_id);
2512 bar.step();
2513 ++count;
2515 while( result->NextRow() );
2517 delete result;
2519 sLog.outString();
2520 sLog.outString( ">> Loaded %u player create spells", count );
2524 // Load playercreate actions
2526 // 0 1 2 3 4
2527 QueryResult *result = WorldDatabase.Query("SELECT race, class, button, action, type FROM playercreateinfo_action");
2529 uint32 count = 0;
2531 if (!result)
2533 barGoLink bar( 1 );
2535 sLog.outString();
2536 sLog.outString( ">> Loaded %u player create actions", count );
2537 sLog.outErrorDb( "Error loading `playercreateinfo_action` table or empty table.");
2539 else
2541 barGoLink bar( result->GetRowCount() );
2545 Field* fields = result->Fetch();
2547 uint32 current_race = fields[0].GetUInt32();
2548 if(current_race >= MAX_RACES)
2550 sLog.outErrorDb("Wrong race %u in `playercreateinfo_action` table, ignoring.",current_race);
2551 continue;
2554 uint32 current_class = fields[1].GetUInt32();
2555 if(current_class >= MAX_CLASSES)
2557 sLog.outErrorDb("Wrong class %u in `playercreateinfo_action` table, ignoring.",current_class);
2558 continue;
2561 uint8 action_button = fields[2].GetUInt8();
2562 uint32 action = fields[3].GetUInt32();
2563 uint8 action_type = fields[4].GetUInt8();
2565 if (!Player::IsActionButtonDataValid(action_button,action,action_type,NULL))
2566 continue;
2568 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2569 pInfo->action.push_back(PlayerCreateInfoAction(action_button,action,action_type));
2571 bar.step();
2572 ++count;
2574 while( result->NextRow() );
2576 delete result;
2578 sLog.outString();
2579 sLog.outString( ">> Loaded %u player create actions", count );
2583 // Loading levels data (class only dependent)
2585 // 0 1 2 3
2586 QueryResult *result = WorldDatabase.Query("SELECT class, level, basehp, basemana FROM player_classlevelstats");
2588 uint32 count = 0;
2590 if (!result)
2592 barGoLink bar( 1 );
2594 sLog.outString();
2595 sLog.outString( ">> Loaded %u level health/mana definitions", count );
2596 sLog.outErrorDb( "Error loading `player_classlevelstats` table or empty table.");
2597 exit(1);
2600 barGoLink bar( result->GetRowCount() );
2604 Field* fields = result->Fetch();
2606 uint32 current_class = fields[0].GetUInt32();
2607 if(current_class >= MAX_CLASSES)
2609 sLog.outErrorDb("Wrong class %u in `player_classlevelstats` table, ignoring.",current_class);
2610 continue;
2613 uint32 current_level = fields[1].GetUInt32();
2614 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2616 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2617 sLog.outErrorDb("Wrong (> %u) level %u in `player_classlevelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
2618 else
2620 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_classlevelstats` table, ignoring.",current_level);
2621 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
2623 continue;
2626 PlayerClassInfo* pClassInfo = &playerClassInfo[current_class];
2628 if(!pClassInfo->levelInfo)
2629 pClassInfo->levelInfo = new PlayerClassLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
2631 PlayerClassLevelInfo* pClassLevelInfo = &pClassInfo->levelInfo[current_level-1];
2633 pClassLevelInfo->basehealth = fields[2].GetUInt16();
2634 pClassLevelInfo->basemana = fields[3].GetUInt16();
2636 bar.step();
2637 ++count;
2639 while (result->NextRow());
2641 delete result;
2643 sLog.outString();
2644 sLog.outString( ">> Loaded %u level health/mana definitions", count );
2647 // Fill gaps and check integrity
2648 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2650 // skip non existed classes
2651 if(!sChrClassesStore.LookupEntry(class_))
2652 continue;
2654 PlayerClassInfo* pClassInfo = &playerClassInfo[class_];
2656 // fatal error if no level 1 data
2657 if(!pClassInfo->levelInfo || pClassInfo->levelInfo[0].basehealth == 0 )
2659 sLog.outErrorDb("Class %i Level 1 does not have health/mana data!",class_);
2660 exit(1);
2663 // fill level gaps
2664 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2666 if(pClassInfo->levelInfo[level].basehealth == 0)
2668 sLog.outErrorDb("Class %i Level %i does not have health/mana data. Using stats data of level %i.",class_,level+1, level);
2669 pClassInfo->levelInfo[level] = pClassInfo->levelInfo[level-1];
2674 // Loading levels data (class/race dependent)
2676 // 0 1 2 3 4 5 6 7
2677 QueryResult *result = WorldDatabase.Query("SELECT race, class, level, str, agi, sta, inte, spi FROM player_levelstats");
2679 uint32 count = 0;
2681 if (!result)
2683 barGoLink bar( 1 );
2685 sLog.outString();
2686 sLog.outString( ">> Loaded %u level stats definitions", count );
2687 sLog.outErrorDb( "Error loading `player_levelstats` table or empty table.");
2688 exit(1);
2691 barGoLink bar( result->GetRowCount() );
2695 Field* fields = result->Fetch();
2697 uint32 current_race = fields[0].GetUInt32();
2698 if(current_race >= MAX_RACES)
2700 sLog.outErrorDb("Wrong race %u in `player_levelstats` table, ignoring.",current_race);
2701 continue;
2704 uint32 current_class = fields[1].GetUInt32();
2705 if(current_class >= MAX_CLASSES)
2707 sLog.outErrorDb("Wrong class %u in `player_levelstats` table, ignoring.",current_class);
2708 continue;
2711 uint32 current_level = fields[2].GetUInt32();
2712 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2714 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2715 sLog.outErrorDb("Wrong (> %u) level %u in `player_levelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
2716 else
2718 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_levelstats` table, ignoring.",current_level);
2719 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
2721 continue;
2724 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2726 if(!pInfo->levelInfo)
2727 pInfo->levelInfo = new PlayerLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
2729 PlayerLevelInfo* pLevelInfo = &pInfo->levelInfo[current_level-1];
2731 for (int i = 0; i < MAX_STATS; i++)
2733 pLevelInfo->stats[i] = fields[i+3].GetUInt8();
2736 bar.step();
2737 ++count;
2739 while (result->NextRow());
2741 delete result;
2743 sLog.outString();
2744 sLog.outString( ">> Loaded %u level stats definitions", count );
2747 // Fill gaps and check integrity
2748 for (int race = 0; race < MAX_RACES; ++race)
2750 // skip non existed races
2751 if(!sChrRacesStore.LookupEntry(race))
2752 continue;
2754 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2756 // skip non existed classes
2757 if(!sChrClassesStore.LookupEntry(class_))
2758 continue;
2760 PlayerInfo* pInfo = &playerInfo[race][class_];
2762 // skip non loaded combinations
2763 if(!pInfo->displayId_m || !pInfo->displayId_f)
2764 continue;
2766 // skip expansion races if not playing with expansion
2767 if (sWorld.getConfig(CONFIG_EXPANSION) < 1 && (race == RACE_BLOODELF || race == RACE_DRAENEI))
2768 continue;
2770 // skip expansion classes if not playing with expansion
2771 if (sWorld.getConfig(CONFIG_EXPANSION) < 2 && class_ == CLASS_DEATH_KNIGHT)
2772 continue;
2774 // fatal error if no level 1 data
2775 if(!pInfo->levelInfo || pInfo->levelInfo[0].stats[0] == 0 )
2777 sLog.outErrorDb("Race %i Class %i Level 1 does not have stats data!",race,class_);
2778 exit(1);
2781 // fill level gaps
2782 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2784 if(pInfo->levelInfo[level].stats[0] == 0)
2786 sLog.outErrorDb("Race %i Class %i Level %i does not have stats data. Using stats data of level %i.",race,class_,level+1, level);
2787 pInfo->levelInfo[level] = pInfo->levelInfo[level-1];
2793 // Loading xp per level data
2795 mPlayerXPperLevel.resize(sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL));
2796 for (uint32 level = 0; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2797 mPlayerXPperLevel[level] = 0;
2799 // 0 1
2800 QueryResult *result = WorldDatabase.Query("SELECT lvl, xp_for_next_level FROM player_xp_for_level");
2802 uint32 count = 0;
2804 if (!result)
2806 barGoLink bar( 1 );
2808 sLog.outString();
2809 sLog.outString( ">> Loaded %u xp for level definitions", count );
2810 sLog.outErrorDb( "Error loading `player_xp_for_level` table or empty table.");
2811 exit(1);
2814 barGoLink bar( result->GetRowCount() );
2818 Field* fields = result->Fetch();
2820 uint32 current_level = fields[0].GetUInt32();
2821 uint32 current_xp = fields[1].GetUInt32();
2823 if(current_level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2825 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2826 sLog.outErrorDb("Wrong (> %u) level %u in `player_xp_for_level` table, ignoring.", STRONG_MAX_LEVEL,current_level);
2827 else
2829 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_xp_for_levels` table, ignoring.",current_level);
2830 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
2832 continue;
2834 //PlayerXPperLevel
2835 mPlayerXPperLevel[current_level] = current_xp;
2836 bar.step();
2837 ++count;
2839 while (result->NextRow());
2841 delete result;
2843 sLog.outString();
2844 sLog.outString( ">> Loaded %u xp for level definitions", count );
2847 // fill level gaps
2848 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2850 if( mPlayerXPperLevel[level] == 0)
2852 sLog.outErrorDb("Level %i does not have XP for level data. Using data of level [%i] + 100.",level+1, level);
2853 mPlayerXPperLevel[level] = mPlayerXPperLevel[level-1]+100;
2858 void ObjectMgr::GetPlayerClassLevelInfo(uint32 class_, uint32 level, PlayerClassLevelInfo* info) const
2860 if(level < 1 || class_ >= MAX_CLASSES)
2861 return;
2863 PlayerClassInfo const* pInfo = &playerClassInfo[class_];
2865 if(level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2866 level = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL);
2868 *info = pInfo->levelInfo[level-1];
2871 void ObjectMgr::GetPlayerLevelInfo(uint32 race, uint32 class_, uint32 level, PlayerLevelInfo* info) const
2873 if(level < 1 || race >= MAX_RACES || class_ >= MAX_CLASSES)
2874 return;
2876 PlayerInfo const* pInfo = &playerInfo[race][class_];
2877 if(pInfo->displayId_m==0 || pInfo->displayId_f==0)
2878 return;
2880 if(level <= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2881 *info = pInfo->levelInfo[level-1];
2882 else
2883 BuildPlayerLevelInfo(race,class_,level,info);
2886 void ObjectMgr::BuildPlayerLevelInfo(uint8 race, uint8 _class, uint8 level, PlayerLevelInfo* info) const
2888 // base data (last known level)
2889 *info = playerInfo[race][_class].levelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)-1];
2891 for(int lvl = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)-1; lvl < level; ++lvl)
2893 switch(_class)
2895 case CLASS_WARRIOR:
2896 info->stats[STAT_STRENGTH] += (lvl > 23 ? 2: (lvl > 1 ? 1: 0));
2897 info->stats[STAT_STAMINA] += (lvl > 23 ? 2: (lvl > 1 ? 1: 0));
2898 info->stats[STAT_AGILITY] += (lvl > 36 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2899 info->stats[STAT_INTELLECT] += (lvl > 9 && !(lvl%2) ? 1: 0);
2900 info->stats[STAT_SPIRIT] += (lvl > 9 && !(lvl%2) ? 1: 0);
2901 break;
2902 case CLASS_PALADIN:
2903 info->stats[STAT_STRENGTH] += (lvl > 3 ? 1: 0);
2904 info->stats[STAT_STAMINA] += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2905 info->stats[STAT_AGILITY] += (lvl > 38 ? 1: (lvl > 7 && !(lvl%2) ? 1: 0));
2906 info->stats[STAT_INTELLECT] += (lvl > 6 && (lvl%2) ? 1: 0);
2907 info->stats[STAT_SPIRIT] += (lvl > 7 ? 1: 0);
2908 break;
2909 case CLASS_HUNTER:
2910 info->stats[STAT_STRENGTH] += (lvl > 4 ? 1: 0);
2911 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2912 info->stats[STAT_AGILITY] += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2913 info->stats[STAT_INTELLECT] += (lvl > 8 && (lvl%2) ? 1: 0);
2914 info->stats[STAT_SPIRIT] += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2915 break;
2916 case CLASS_ROGUE:
2917 info->stats[STAT_STRENGTH] += (lvl > 5 ? 1: 0);
2918 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2919 info->stats[STAT_AGILITY] += (lvl > 16 ? 2: (lvl > 1 ? 1: 0));
2920 info->stats[STAT_INTELLECT] += (lvl > 8 && !(lvl%2) ? 1: 0);
2921 info->stats[STAT_SPIRIT] += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2922 break;
2923 case CLASS_PRIEST:
2924 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2925 info->stats[STAT_STAMINA] += (lvl > 5 ? 1: 0);
2926 info->stats[STAT_AGILITY] += (lvl > 38 ? 1: (lvl > 8 && (lvl%2) ? 1: 0));
2927 info->stats[STAT_INTELLECT] += (lvl > 22 ? 2: (lvl > 1 ? 1: 0));
2928 info->stats[STAT_SPIRIT] += (lvl > 3 ? 1: 0);
2929 break;
2930 case CLASS_SHAMAN:
2931 info->stats[STAT_STRENGTH] += (lvl > 34 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2932 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2933 info->stats[STAT_AGILITY] += (lvl > 7 && !(lvl%2) ? 1: 0);
2934 info->stats[STAT_INTELLECT] += (lvl > 5 ? 1: 0);
2935 info->stats[STAT_SPIRIT] += (lvl > 4 ? 1: 0);
2936 break;
2937 case CLASS_MAGE:
2938 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2939 info->stats[STAT_STAMINA] += (lvl > 5 ? 1: 0);
2940 info->stats[STAT_AGILITY] += (lvl > 9 && !(lvl%2) ? 1: 0);
2941 info->stats[STAT_INTELLECT] += (lvl > 24 ? 2: (lvl > 1 ? 1: 0));
2942 info->stats[STAT_SPIRIT] += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
2943 break;
2944 case CLASS_WARLOCK:
2945 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2946 info->stats[STAT_STAMINA] += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
2947 info->stats[STAT_AGILITY] += (lvl > 9 && !(lvl%2) ? 1: 0);
2948 info->stats[STAT_INTELLECT] += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
2949 info->stats[STAT_SPIRIT] += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
2950 break;
2951 case CLASS_DRUID:
2952 info->stats[STAT_STRENGTH] += (lvl > 38 ? 2: (lvl > 6 && (lvl%2) ? 1: 0));
2953 info->stats[STAT_STAMINA] += (lvl > 32 ? 2: (lvl > 4 ? 1: 0));
2954 info->stats[STAT_AGILITY] += (lvl > 38 ? 2: (lvl > 8 && (lvl%2) ? 1: 0));
2955 info->stats[STAT_INTELLECT] += (lvl > 38 ? 3: (lvl > 4 ? 1: 0));
2956 info->stats[STAT_SPIRIT] += (lvl > 38 ? 3: (lvl > 5 ? 1: 0));
2961 void ObjectMgr::LoadGuilds()
2963 Guild *newGuild;
2964 uint32 count = 0;
2966 // 0 1 2 3 4 5 6
2967 QueryResult *result = CharacterDatabase.Query("SELECT guild.guildid,guild.name,leaderguid,EmblemStyle,EmblemColor,BorderStyle,BorderColor,"
2968 // 7 8 9 10 11 12
2969 "BackgroundColor,info,motd,createdate,BankMoney,(SELECT COUNT(guild_bank_tab.guildid) FROM guild_bank_tab WHERE guild_bank_tab.guildid = guild.guildid) "
2970 "FROM guild ORDER BY guildid ASC");
2972 if( !result )
2975 barGoLink bar( 1 );
2977 bar.step();
2979 sLog.outString();
2980 sLog.outString( ">> Loaded %u guild definitions", count );
2981 return;
2984 // load guild ranks
2985 // 0 1 2 3 4
2986 QueryResult *guildRanksResult = CharacterDatabase.Query("SELECT guildid,rid,rname,rights,BankMoneyPerDay FROM guild_rank ORDER BY guildid ASC, rid ASC");
2988 // load guild members
2989 // 0 1 2 3 4 5 6
2990 QueryResult *guildMembersResult = CharacterDatabase.Query("SELECT guildid,guild_member.guid,rank,pnote,offnote,BankResetTimeMoney,BankRemMoney,"
2991 // 7 8 9 10 11 12
2992 "BankResetTimeTab0,BankRemSlotsTab0,BankResetTimeTab1,BankRemSlotsTab1,BankResetTimeTab2,BankRemSlotsTab2,"
2993 // 13 14 15 16 17 18
2994 "BankResetTimeTab3,BankRemSlotsTab3,BankResetTimeTab4,BankRemSlotsTab4,BankResetTimeTab5,BankRemSlotsTab5,"
2995 // 19 20 21 22 23
2996 "characters.name, characters.level, characters.class, characters.zone, characters.logout_time "
2997 "FROM guild_member LEFT JOIN characters ON characters.guid = guild_member.guid ORDER BY guildid ASC");
2999 // load guild bank tab rights
3000 // 0 1 2 3 4
3001 QueryResult *guildBankTabRightsResult = CharacterDatabase.Query("SELECT guildid,TabId,rid,gbright,SlotPerDay FROM guild_bank_right ORDER BY guildid ASC, TabId ASC");
3003 barGoLink bar( result->GetRowCount() );
3007 //Field *fields = result->Fetch();
3009 bar.step();
3010 ++count;
3012 newGuild = new Guild;
3013 if (!newGuild->LoadGuildFromDB(result) ||
3014 !newGuild->LoadRanksFromDB(guildRanksResult) ||
3015 !newGuild->LoadMembersFromDB(guildMembersResult) ||
3016 !newGuild->LoadBankRightsFromDB(guildBankTabRightsResult) ||
3017 !newGuild->CheckGuildStructure()
3020 newGuild->Disband();
3021 delete newGuild;
3022 continue;
3024 newGuild->LoadGuildEventLogFromDB();
3025 newGuild->LoadGuildBankEventLogFromDB();
3026 newGuild->LoadGuildBankFromDB();
3027 AddGuild(newGuild);
3028 } while( result->NextRow() );
3030 delete result;
3031 delete guildRanksResult;
3032 delete guildMembersResult;
3033 delete guildBankTabRightsResult;
3035 //delete unused LogGuid records in guild_eventlog and guild_bank_eventlog table
3036 //you can comment these lines if you don't plan to change CONFIG_GUILD_EVENT_LOG_COUNT and CONFIG_GUILD_BANK_EVENT_LOG_COUNT
3037 CharacterDatabase.PQuery("DELETE FROM guild_eventlog WHERE LogGuid > '%u'", sWorld.getConfig(CONFIG_GUILD_EVENT_LOG_COUNT));
3038 CharacterDatabase.PQuery("DELETE FROM guild_bank_eventlog WHERE LogGuid > '%u'", sWorld.getConfig(CONFIG_GUILD_BANK_EVENT_LOG_COUNT));
3040 sLog.outString();
3041 sLog.outString( ">> Loaded %u guild definitions", count );
3044 void ObjectMgr::LoadArenaTeams()
3046 uint32 count = 0;
3048 // 0 1 2 3 4 5
3049 QueryResult *result = CharacterDatabase.Query( "SELECT arena_team.arenateamid,name,captainguid,type,BackgroundColor,EmblemStyle,"
3050 // 6 7 8 9 10 11 12 13 14
3051 "EmblemColor,BorderStyle,BorderColor, rating,games,wins,played,wins2,rank "
3052 "FROM arena_team LEFT JOIN arena_team_stats ON arena_team.arenateamid = arena_team_stats.arenateamid ORDER BY arena_team.arenateamid ASC" );
3054 if( !result )
3057 barGoLink bar( 1 );
3059 bar.step();
3061 sLog.outString();
3062 sLog.outString( ">> Loaded %u arenateam definitions", count );
3063 return;
3066 // load arena_team members
3067 QueryResult *arenaTeamMembersResult = CharacterDatabase.Query(
3068 // 0 1 2 3 4 5 6 7 8
3069 "SELECT arenateamid,member.guid,played_week,wons_week,played_season,wons_season,personal_rating,name,class "
3070 "FROM arena_team_member member LEFT JOIN characters chars on member.guid = chars.guid ORDER BY member.arenateamid ASC");
3072 barGoLink bar( result->GetRowCount() );
3076 Field *fields = result->Fetch();
3078 bar.step();
3079 ++count;
3081 ArenaTeam *newArenaTeam = new ArenaTeam;
3082 if (!newArenaTeam->LoadArenaTeamFromDB(result) ||
3083 !newArenaTeam->LoadMembersFromDB(arenaTeamMembersResult))
3085 newArenaTeam->Disband(NULL);
3086 delete newArenaTeam;
3087 continue;
3089 AddArenaTeam(newArenaTeam);
3090 }while( result->NextRow() );
3092 delete result;
3093 delete arenaTeamMembersResult;
3095 sLog.outString();
3096 sLog.outString( ">> Loaded %u arenateam definitions", count );
3099 void ObjectMgr::LoadGroups()
3101 // -- loading groups --
3102 Group *group = NULL;
3103 uint64 leaderGuid = 0;
3104 uint32 count = 0;
3105 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
3106 QueryResult *result = CharacterDatabase.Query("SELECT mainTank, mainAssistant, lootMethod, looterGuid, lootThreshold, icon1, icon2, icon3, icon4, icon5, icon6, icon7, icon8, isRaid, difficulty, raiddifficulty, leaderGuid FROM groups");
3108 if( !result )
3110 barGoLink bar( 1 );
3112 bar.step();
3114 sLog.outString();
3115 sLog.outString( ">> Loaded %u group definitions", count );
3116 return;
3119 barGoLink bar( result->GetRowCount() );
3123 bar.step();
3124 Field *fields = result->Fetch();
3125 ++count;
3126 leaderGuid = MAKE_NEW_GUID(fields[16].GetUInt32(),0,HIGHGUID_PLAYER);
3128 group = new Group;
3129 if(!group->LoadGroupFromDB(leaderGuid, result, false))
3131 group->Disband();
3132 delete group;
3133 continue;
3135 AddGroup(group);
3136 }while( result->NextRow() );
3138 delete result;
3140 sLog.outString();
3141 sLog.outString( ">> Loaded %u group definitions", count );
3143 // -- loading members --
3144 count = 0;
3145 group = NULL;
3146 leaderGuid = 0;
3147 // 0 1 2 3
3148 result = CharacterDatabase.Query("SELECT memberGuid, assistant, subgroup, leaderGuid FROM group_member ORDER BY leaderGuid");
3149 if(!result)
3151 barGoLink bar2( 1 );
3152 bar2.step();
3154 else
3156 barGoLink bar2( result->GetRowCount() );
3159 bar2.step();
3160 Field *fields = result->Fetch();
3161 count++;
3162 leaderGuid = MAKE_NEW_GUID(fields[3].GetUInt32(), 0, HIGHGUID_PLAYER);
3163 if(!group || group->GetLeaderGUID() != leaderGuid)
3165 group = GetGroupByLeader(leaderGuid);
3166 if(!group)
3168 sLog.outErrorDb("Incorrect entry in group_member table : no group with leader %d for member %d!", fields[3].GetUInt32(), fields[0].GetUInt32());
3169 CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", fields[0].GetUInt32());
3170 continue;
3174 if(!group->LoadMemberFromDB(fields[0].GetUInt32(), fields[2].GetUInt8(), fields[1].GetBool()))
3176 sLog.outErrorDb("Incorrect entry in group_member table : member %d cannot be added to player %d's group!", fields[0].GetUInt32(), fields[3].GetUInt32());
3177 CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", fields[0].GetUInt32());
3179 }while( result->NextRow() );
3180 delete result;
3183 // clean groups
3184 // TODO: maybe delete from the DB before loading in this case
3185 for(GroupSet::iterator itr = mGroupSet.begin(); itr != mGroupSet.end();)
3187 if((*itr)->GetMembersCount() < 2)
3189 (*itr)->Disband();
3190 delete *itr;
3191 mGroupSet.erase(itr++);
3193 else
3194 ++itr;
3197 // -- loading instances --
3198 count = 0;
3199 group = NULL;
3200 leaderGuid = 0;
3201 result = CharacterDatabase.Query(
3202 // 0 1 2 3 4 5
3203 "SELECT leaderGuid, map, instance, permanent, difficulty, resettime, "
3204 // 6
3205 "(SELECT COUNT(*) FROM character_instance WHERE guid = leaderGuid AND instance = group_instance.instance AND permanent = 1 LIMIT 1) "
3206 "FROM group_instance LEFT JOIN instance ON instance = id ORDER BY leaderGuid"
3209 if(!result)
3211 barGoLink bar2( 1 );
3212 bar2.step();
3214 else
3216 barGoLink bar2( result->GetRowCount() );
3219 bar2.step();
3220 Field *fields = result->Fetch();
3221 count++;
3222 leaderGuid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
3223 if(!group || group->GetLeaderGUID() != leaderGuid)
3225 group = GetGroupByLeader(leaderGuid);
3226 if(!group)
3228 sLog.outErrorDb("Incorrect entry in group_instance table : no group with leader %d", fields[0].GetUInt32());
3229 continue;
3233 MapEntry const* mapEntry = sMapStore.LookupEntry(fields[1].GetUInt32());
3234 if(!mapEntry || !mapEntry->IsDungeon())
3236 sLog.outErrorDb("Incorrect entry in group_instance table : no dungeon map %d", fields[1].GetUInt32());
3237 continue;
3240 uint32 diff = fields[4].GetUInt8();
3241 if(diff >= (mapEntry->IsRaid() ? MAX_RAID_DIFFICULTY : MAX_DUNGEON_DIFFICULTY))
3243 sLog.outErrorDb("Wrong dungeon difficulty use in group_instance table: %d", diff + 1);
3244 diff = 0; // default for both difficaly types
3247 InstanceSave *save = sInstanceSaveMgr.AddInstanceSave(mapEntry->MapID, fields[2].GetUInt32(), Difficulty(diff), (time_t)fields[5].GetUInt64(), (fields[6].GetUInt32() == 0), true);
3248 group->BindToInstance(save, fields[3].GetBool(), true);
3249 }while( result->NextRow() );
3250 delete result;
3253 sLog.outString();
3254 sLog.outString( ">> Loaded %u group-instance binds total", count );
3256 sLog.outString();
3257 sLog.outString( ">> Loaded %u group members total", count );
3260 void ObjectMgr::LoadQuests()
3262 // For reload case
3263 for(QuestMap::const_iterator itr=mQuestTemplates.begin(); itr != mQuestTemplates.end(); ++itr)
3264 delete itr->second;
3265 mQuestTemplates.clear();
3267 mExclusiveQuestGroups.clear();
3269 // 0 1 2 3 4 5 6 7 8
3270 QueryResult *result = WorldDatabase.Query("SELECT entry, Method, ZoneOrSort, SkillOrClass, MinLevel, QuestLevel, Type, RequiredRaces, RequiredSkillValue,"
3271 // 9 10 11 12 13 14 15 16
3272 "RepObjectiveFaction, RepObjectiveValue, RequiredMinRepFaction, RequiredMinRepValue, RequiredMaxRepFaction, RequiredMaxRepValue, SuggestedPlayers, LimitTime,"
3273 // 17 18 19 20 21 22 23 24 25 26 27 28
3274 "QuestFlags, SpecialFlags, CharTitleId, PlayersSlain, BonusTalents, PrevQuestId, NextQuestId, ExclusiveGroup, NextQuestInChain, SrcItemId, SrcItemCount, SrcSpell,"
3275 // 29 30 31 32 33 34 35 36 37 38
3276 "Title, Details, Objectives, OfferRewardText, RequestItemsText, EndText, ObjectiveText1, ObjectiveText2, ObjectiveText3, ObjectiveText4,"
3277 // 39 40 41 42 43 44 45 46 47 48 49 50
3278 "ReqItemId1, ReqItemId2, ReqItemId3, ReqItemId4, ReqItemId5, ReqItemId6, ReqItemCount1, ReqItemCount2, ReqItemCount3, ReqItemCount4, ReqItemCount5, ReqItemCount6,"
3279 // 51 52 53 54 55 56 57 58
3280 "ReqSourceId1, ReqSourceId2, ReqSourceId3, ReqSourceId4, ReqSourceCount1, ReqSourceCount2, ReqSourceCount3, ReqSourceCount4,"
3281 // 59 60 61 62 63 64 65 66
3282 "ReqCreatureOrGOId1, ReqCreatureOrGOId2, ReqCreatureOrGOId3, ReqCreatureOrGOId4, ReqCreatureOrGOCount1, ReqCreatureOrGOCount2, ReqCreatureOrGOCount3, ReqCreatureOrGOCount4,"
3283 // 67 68 69 70
3284 "ReqSpellCast1, ReqSpellCast2, ReqSpellCast3, ReqSpellCast4,"
3285 // 71 72 73 74 75 76
3286 "RewChoiceItemId1, RewChoiceItemId2, RewChoiceItemId3, RewChoiceItemId4, RewChoiceItemId5, RewChoiceItemId6,"
3287 // 77 78 79 80 81 82
3288 "RewChoiceItemCount1, RewChoiceItemCount2, RewChoiceItemCount3, RewChoiceItemCount4, RewChoiceItemCount5, RewChoiceItemCount6,"
3289 // 83 84 85 86 87 88 89 90
3290 "RewItemId1, RewItemId2, RewItemId3, RewItemId4, RewItemCount1, RewItemCount2, RewItemCount3, RewItemCount4,"
3291 // 91 92 93 94 95 96 97 98 99 100
3292 "RewRepFaction1, RewRepFaction2, RewRepFaction3, RewRepFaction4, RewRepFaction5, RewRepValue1, RewRepValue2, RewRepValue3, RewRepValue4, RewRepValue5,"
3293 // 101 102 103 104 105 106 107 108 109 110 111
3294 "RewHonorableKills, RewOrReqMoney, RewMoneyMaxLevel, RewSpell, RewSpellCast, RewMailTemplateId, RewMailDelaySecs, PointMapId, PointX, PointY, PointOpt,"
3295 // 112 113 114 115 116 117 118 119
3296 "DetailsEmote1, DetailsEmote2, DetailsEmote3, DetailsEmote4, DetailsEmoteDelay1, DetailsEmoteDelay2, DetailsEmoteDelay3, DetailsEmoteDelay4,"
3297 // 120 121 122 123 124 125
3298 "IncompleteEmote, CompleteEmote, OfferRewardEmote1, OfferRewardEmote2, OfferRewardEmote3, OfferRewardEmote4,"
3299 // 126 127 128 129
3300 "OfferRewardEmoteDelay1, OfferRewardEmoteDelay2, OfferRewardEmoteDelay3, OfferRewardEmoteDelay4,"
3301 // 130 131
3302 "StartScript, CompleteScript"
3303 " FROM quest_template");
3304 if(result == NULL)
3306 barGoLink bar( 1 );
3307 bar.step();
3309 sLog.outString();
3310 sLog.outString( ">> Loaded 0 quests definitions" );
3311 sLog.outErrorDb("`quest_template` table is empty!");
3312 return;
3315 // create multimap previous quest for each existed quest
3316 // some quests can have many previous maps set by NextQuestId in previous quest
3317 // for example set of race quests can lead to single not race specific quest
3318 barGoLink bar( result->GetRowCount() );
3321 bar.step();
3322 Field *fields = result->Fetch();
3324 Quest * newQuest = new Quest(fields);
3325 mQuestTemplates[newQuest->GetQuestId()] = newQuest;
3326 } while( result->NextRow() );
3328 delete result;
3330 // Post processing
3332 std::map<uint32,uint32> usedMailTemplates;
3334 for (QuestMap::iterator iter = mQuestTemplates.begin(); iter != mQuestTemplates.end(); ++iter)
3336 Quest * qinfo = iter->second;
3338 // additional quest integrity checks (GO, creature_template and item_template must be loaded already)
3340 if( qinfo->GetQuestMethod() >= 3 )
3342 sLog.outErrorDb("Quest %u has `Method` = %u, expected values are 0, 1 or 2.",qinfo->GetQuestId(),qinfo->GetQuestMethod());
3345 if (qinfo->QuestFlags & ~QUEST_MANGOS_FLAGS_DB_ALLOWED)
3347 sLog.outErrorDb("Quest %u has `SpecialFlags` = %u > max allowed value. Correct `SpecialFlags` to value <= %u",
3348 qinfo->GetQuestId(),qinfo->QuestFlags >> 24,QUEST_MANGOS_FLAGS_DB_ALLOWED >> 24);
3349 qinfo->QuestFlags &= QUEST_MANGOS_FLAGS_DB_ALLOWED;
3352 if(qinfo->QuestFlags & QUEST_FLAGS_DAILY)
3354 if(!(qinfo->QuestFlags & QUEST_MANGOS_FLAGS_REPEATABLE))
3356 sLog.outErrorDb("Daily Quest %u not marked as repeatable in `SpecialFlags`, added.",qinfo->GetQuestId());
3357 qinfo->QuestFlags |= QUEST_MANGOS_FLAGS_REPEATABLE;
3361 if(qinfo->QuestFlags & QUEST_FLAGS_AUTO_REWARDED)
3363 // at auto-reward can be rewarded only RewChoiceItemId[0]
3364 for(int j = 1; j < QUEST_REWARD_CHOICES_COUNT; ++j )
3366 if(uint32 id = qinfo->RewChoiceItemId[j])
3368 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item from `RewChoiceItemId%d` can't be rewarded with quest flag QUEST_FLAGS_AUTO_REWARDED.",
3369 qinfo->GetQuestId(),j+1,id,j+1);
3370 // no changes, quest ignore this data
3375 // client quest log visual (area case)
3376 if( qinfo->ZoneOrSort > 0 )
3378 if(!GetAreaEntryByAreaID(qinfo->ZoneOrSort))
3380 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %u (zone case) but zone with this id does not exist.",
3381 qinfo->GetQuestId(),qinfo->ZoneOrSort);
3382 // no changes, quest not dependent from this value but can have problems at client
3385 // client quest log visual (sort case)
3386 if( qinfo->ZoneOrSort < 0 )
3388 QuestSortEntry const* qSort = sQuestSortStore.LookupEntry(-int32(qinfo->ZoneOrSort));
3389 if( !qSort )
3391 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (sort case) but quest sort with this id does not exist.",
3392 qinfo->GetQuestId(),qinfo->ZoneOrSort);
3393 // 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)
3395 //check SkillOrClass value (class case).
3396 if( ClassByQuestSort(-int32(qinfo->ZoneOrSort)) )
3398 // SkillOrClass should not have class case when class case already set in ZoneOrSort.
3399 if(qinfo->SkillOrClass < 0)
3401 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (class sort case) and `SkillOrClass` = %i (class case), redundant.",
3402 qinfo->GetQuestId(),qinfo->ZoneOrSort,qinfo->SkillOrClass);
3405 //check for proper SkillOrClass value (skill case)
3406 if(int32 skill_id = SkillByQuestSort(-int32(qinfo->ZoneOrSort)))
3408 // skill is positive value in SkillOrClass
3409 if(qinfo->SkillOrClass != skill_id )
3411 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (skill sort case) but `SkillOrClass` does not have a corresponding value (%i).",
3412 qinfo->GetQuestId(),qinfo->ZoneOrSort,skill_id);
3413 //override, and force proper value here?
3418 // SkillOrClass (class case)
3419 if( qinfo->SkillOrClass < 0 )
3421 if( !sChrClassesStore.LookupEntry(-int32(qinfo->SkillOrClass)) )
3423 sLog.outErrorDb("Quest %u has `SkillOrClass` = %i (class case) but class (%i) does not exist",
3424 qinfo->GetQuestId(),qinfo->SkillOrClass,-qinfo->SkillOrClass);
3427 // SkillOrClass (skill case)
3428 if( qinfo->SkillOrClass > 0 )
3430 if( !sSkillLineStore.LookupEntry(qinfo->SkillOrClass) )
3432 sLog.outErrorDb("Quest %u has `SkillOrClass` = %u (skill case) but skill (%i) does not exist",
3433 qinfo->GetQuestId(),qinfo->SkillOrClass,qinfo->SkillOrClass);
3437 if( qinfo->RequiredSkillValue )
3439 if( qinfo->RequiredSkillValue > sWorld.GetConfigMaxSkillValue() )
3441 sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but max possible skill is %u, quest can't be done.",
3442 qinfo->GetQuestId(),qinfo->RequiredSkillValue,sWorld.GetConfigMaxSkillValue());
3443 // no changes, quest can't be done for this requirement
3446 if( qinfo->SkillOrClass <= 0 )
3448 sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but `SkillOrClass` = %i (class case), value ignored.",
3449 qinfo->GetQuestId(),qinfo->RequiredSkillValue,qinfo->SkillOrClass);
3450 // no changes, quest can't be done for this requirement (fail at wrong skill id)
3453 // else Skill quests can have 0 skill level, this is ok
3455 if(qinfo->RepObjectiveFaction && !sFactionStore.LookupEntry(qinfo->RepObjectiveFaction))
3457 sLog.outErrorDb("Quest %u has `RepObjectiveFaction` = %u but faction template %u does not exist, quest can't be done.",
3458 qinfo->GetQuestId(),qinfo->RepObjectiveFaction,qinfo->RepObjectiveFaction);
3459 // no changes, quest can't be done for this requirement
3462 if(qinfo->RequiredMinRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMinRepFaction))
3464 sLog.outErrorDb("Quest %u has `RequiredMinRepFaction` = %u but faction template %u does not exist, quest can't be done.",
3465 qinfo->GetQuestId(),qinfo->RequiredMinRepFaction,qinfo->RequiredMinRepFaction);
3466 // no changes, quest can't be done for this requirement
3469 if(qinfo->RequiredMaxRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMaxRepFaction))
3471 sLog.outErrorDb("Quest %u has `RequiredMaxRepFaction` = %u but faction template %u does not exist, quest can't be done.",
3472 qinfo->GetQuestId(),qinfo->RequiredMaxRepFaction,qinfo->RequiredMaxRepFaction);
3473 // no changes, quest can't be done for this requirement
3476 if(qinfo->RequiredMinRepValue && qinfo->RequiredMinRepValue > ReputationMgr::Reputation_Cap)
3478 sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but max reputation is %u, quest can't be done.",
3479 qinfo->GetQuestId(),qinfo->RequiredMinRepValue,ReputationMgr::Reputation_Cap);
3480 // no changes, quest can't be done for this requirement
3483 if(qinfo->RequiredMinRepValue && qinfo->RequiredMaxRepValue && qinfo->RequiredMaxRepValue <= qinfo->RequiredMinRepValue)
3485 sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d and `RequiredMinRepValue` = %d, quest can't be done.",
3486 qinfo->GetQuestId(),qinfo->RequiredMaxRepValue,qinfo->RequiredMinRepValue);
3487 // no changes, quest can't be done for this requirement
3490 if(!qinfo->RepObjectiveFaction && qinfo->RepObjectiveValue > 0 )
3492 sLog.outErrorDb("Quest %u has `RepObjectiveValue` = %d but `RepObjectiveFaction` is 0, value has no effect",
3493 qinfo->GetQuestId(),qinfo->RepObjectiveValue);
3494 // warning
3497 if(!qinfo->RequiredMinRepFaction && qinfo->RequiredMinRepValue > 0 )
3499 sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but `RequiredMinRepFaction` is 0, value has no effect",
3500 qinfo->GetQuestId(),qinfo->RequiredMinRepValue);
3501 // warning
3504 if(!qinfo->RequiredMaxRepFaction && qinfo->RequiredMaxRepValue > 0 )
3506 sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d but `RequiredMaxRepFaction` is 0, value has no effect",
3507 qinfo->GetQuestId(),qinfo->RequiredMaxRepValue);
3508 // warning
3511 if(qinfo->CharTitleId && !sCharTitlesStore.LookupEntry(qinfo->CharTitleId))
3513 sLog.outErrorDb("Quest %u has `CharTitleId` = %u but CharTitle Id %u does not exist, quest can't be rewarded with title.",
3514 qinfo->GetQuestId(),qinfo->GetCharTitleId(),qinfo->GetCharTitleId());
3515 qinfo->CharTitleId = 0;
3516 // quest can't reward this title
3519 if(qinfo->SrcItemId)
3521 if(!sItemStorage.LookupEntry<ItemPrototype>(qinfo->SrcItemId))
3523 sLog.outErrorDb("Quest %u has `SrcItemId` = %u but item with entry %u does not exist, quest can't be done.",
3524 qinfo->GetQuestId(),qinfo->SrcItemId,qinfo->SrcItemId);
3525 qinfo->SrcItemId = 0; // quest can't be done for this requirement
3527 else if(qinfo->SrcItemCount==0)
3529 sLog.outErrorDb("Quest %u has `SrcItemId` = %u but `SrcItemCount` = 0, set to 1 but need fix in DB.",
3530 qinfo->GetQuestId(),qinfo->SrcItemId);
3531 qinfo->SrcItemCount = 1; // update to 1 for allow quest work for backward compatibility with DB
3534 else if(qinfo->SrcItemCount>0)
3536 sLog.outErrorDb("Quest %u has `SrcItemId` = 0 but `SrcItemCount` = %u, useless value.",
3537 qinfo->GetQuestId(),qinfo->SrcItemCount);
3538 qinfo->SrcItemCount=0; // no quest work changes in fact
3541 if(qinfo->SrcSpell)
3543 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->SrcSpell);
3544 if(!spellInfo)
3546 sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u doesn't exist, quest can't be done.",
3547 qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
3548 qinfo->SrcSpell = 0; // quest can't be done for this requirement
3550 else if(!SpellMgr::IsSpellValid(spellInfo))
3552 sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u is broken, quest can't be done.",
3553 qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
3554 qinfo->SrcSpell = 0; // quest can't be done for this requirement
3558 for(int j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j )
3560 uint32 id = qinfo->ReqItemId[j];
3561 if(id)
3563 if(qinfo->ReqItemCount[j] == 0)
3565 sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but `ReqItemCount%d` = 0, quest can't be done.",
3566 qinfo->GetQuestId(), j+1, id, j+1);
3567 // no changes, quest can't be done for this requirement
3570 qinfo->SetFlag(QUEST_MANGOS_FLAGS_DELIVER);
3572 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3574 sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but item with entry %u does not exist, quest can't be done.",
3575 qinfo->GetQuestId(), j+1, id, id);
3576 qinfo->ReqItemCount[j] = 0; // prevent incorrect work of quest
3579 else if(qinfo->ReqItemCount[j] > 0)
3581 sLog.outErrorDb("Quest %u has `ReqItemId%d` = 0 but `ReqItemCount%d` = %u, quest can't be done.",
3582 qinfo->GetQuestId(), j+1, j+1, qinfo->ReqItemCount[j]);
3583 qinfo->ReqItemCount[j] = 0; // prevent incorrect work of quest
3587 for(int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j )
3589 uint32 id = qinfo->ReqSourceId[j];
3590 if(id)
3592 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3594 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but item with entry %u does not exist, quest can't be done.",
3595 qinfo->GetQuestId(),j+1,id,id);
3596 // no changes, quest can't be done for this requirement
3599 else
3601 if(qinfo->ReqSourceCount[j]>0)
3603 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = 0 but `ReqSourceCount%d` = %u.",
3604 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqSourceCount[j]);
3605 // no changes, quest ignore this data
3610 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3612 uint32 id = qinfo->ReqSpell[j];
3613 if(id)
3615 SpellEntry const* spellInfo = sSpellStore.LookupEntry(id);
3616 if(!spellInfo)
3618 sLog.outErrorDb("Quest %u has `ReqSpellCast%d` = %u but spell %u does not exist, quest can't be done.",
3619 qinfo->GetQuestId(),j+1,id,id);
3620 continue;
3623 if(!qinfo->ReqCreatureOrGOId[j])
3625 bool found = false;
3626 for(int k = 0; k < 3; ++k)
3628 if ((spellInfo->Effect[k] == SPELL_EFFECT_QUEST_COMPLETE && uint32(spellInfo->EffectMiscValue[k]) == qinfo->QuestId) ||
3629 spellInfo->Effect[k] == SPELL_EFFECT_SEND_EVENT)
3631 found = true;
3632 break;
3636 if(found)
3638 if(!qinfo->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3640 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);
3642 // this will prevent quest completing without objective
3643 const_cast<Quest*>(qinfo)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3646 else
3648 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.",
3649 qinfo->GetQuestId(),j+1,id,j+1,id);
3650 // no changes, quest can't be done for this requirement
3656 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3658 int32 id = qinfo->ReqCreatureOrGOId[j];
3659 if(id < 0 && !sGOStorage.LookupEntry<GameObjectInfo>(-id))
3661 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but gameobject %u does not exist, quest can't be done.",
3662 qinfo->GetQuestId(),j+1,id,uint32(-id));
3663 qinfo->ReqCreatureOrGOId[j] = 0; // quest can't be done for this requirement
3666 if(id > 0 && !sCreatureStorage.LookupEntry<CreatureInfo>(id))
3668 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but creature with entry %u does not exist, quest can't be done.",
3669 qinfo->GetQuestId(),j+1,id,uint32(id));
3670 qinfo->ReqCreatureOrGOId[j] = 0; // quest can't be done for this requirement
3673 if(id)
3675 // In fact SpeakTo and Kill are quite same: either you can speak to mob:SpeakTo or you can't:Kill/Cast
3677 qinfo->SetFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO);
3679 if(!qinfo->ReqCreatureOrGOCount[j])
3681 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %u but `ReqCreatureOrGOCount%d` = 0, quest can't be done.",
3682 qinfo->GetQuestId(),j+1,id,j+1);
3683 // no changes, quest can be incorrectly done, but we already report this
3686 else if(qinfo->ReqCreatureOrGOCount[j]>0)
3688 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = 0 but `ReqCreatureOrGOCount%d` = %u.",
3689 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqCreatureOrGOCount[j]);
3690 // no changes, quest ignore this data
3694 for(int j = 0; j < QUEST_REWARD_CHOICES_COUNT; ++j )
3696 uint32 id = qinfo->RewChoiceItemId[j];
3697 if(id)
3699 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3701 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3702 qinfo->GetQuestId(),j+1,id,id);
3703 qinfo->RewChoiceItemId[j] = 0; // no changes, quest will not reward this
3706 if(!qinfo->RewChoiceItemCount[j])
3708 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but `RewChoiceItemCount%d` = 0, quest can't be done.",
3709 qinfo->GetQuestId(),j+1,id,j+1);
3710 // no changes, quest can't be done
3713 else if(qinfo->RewChoiceItemCount[j]>0)
3715 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = 0 but `RewChoiceItemCount%d` = %u.",
3716 qinfo->GetQuestId(),j+1,j+1,qinfo->RewChoiceItemCount[j]);
3717 // no changes, quest ignore this data
3721 for(int j = 0; j < QUEST_REWARDS_COUNT; ++j )
3723 uint32 id = qinfo->RewItemId[j];
3724 if(id)
3726 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3728 sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3729 qinfo->GetQuestId(),j+1,id,id);
3730 qinfo->RewItemId[j] = 0; // no changes, quest will not reward this item
3733 if(!qinfo->RewItemCount[j])
3735 sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but `RewItemCount%d` = 0, quest will not reward this item.",
3736 qinfo->GetQuestId(),j+1,id,j+1);
3737 // no changes
3740 else if(qinfo->RewItemCount[j]>0)
3742 sLog.outErrorDb("Quest %u has `RewItemId%d` = 0 but `RewItemCount%d` = %u.",
3743 qinfo->GetQuestId(),j+1,j+1,qinfo->RewItemCount[j]);
3744 // no changes, quest ignore this data
3748 for(int j = 0; j < QUEST_REPUTATIONS_COUNT; ++j)
3750 if(qinfo->RewRepFaction[j])
3752 if(!qinfo->RewRepValue[j])
3754 sLog.outErrorDb("Quest %u has `RewRepFaction%d` = %u but `RewRepValue%d` = 0, quest will not reward this reputation.",
3755 qinfo->GetQuestId(),j+1,qinfo->RewRepValue[j],j+1);
3756 // no changes
3759 if(!sFactionStore.LookupEntry(qinfo->RewRepFaction[j]))
3761 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.",
3762 qinfo->GetQuestId(),j+1,qinfo->RewRepFaction[j] ,qinfo->RewRepFaction[j] );
3763 qinfo->RewRepFaction[j] = 0; // quest will not reward this
3766 else if(qinfo->RewRepValue[j]!=0)
3768 sLog.outErrorDb("Quest %u has `RewRepFaction%d` = 0 but `RewRepValue%d` = %u.",
3769 qinfo->GetQuestId(),j+1,j+1,qinfo->RewRepValue[j]);
3770 // no changes, quest ignore this data
3774 if(qinfo->RewSpell)
3776 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpell);
3778 if(!spellInfo)
3780 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u does not exist, spell removed as display reward.",
3781 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3782 qinfo->RewSpell = 0; // no spell reward will display for this quest
3784 else if(!SpellMgr::IsSpellValid(spellInfo))
3786 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u is broken, quest will not have a spell reward.",
3787 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3788 qinfo->RewSpell = 0; // no spell reward will display for this quest
3790 else if(GetTalentSpellCost(qinfo->RewSpell))
3792 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u is talent, quest will not have a spell reward.",
3793 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3794 qinfo->RewSpell = 0; // no spell reward will display for this quest
3798 if(qinfo->RewSpellCast)
3800 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpellCast);
3802 if(!spellInfo)
3804 sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u does not exist, quest will not have a spell reward.",
3805 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3806 qinfo->RewSpellCast = 0; // no spell will be casted on player
3808 else if(!SpellMgr::IsSpellValid(spellInfo))
3810 sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u is broken, quest will not have a spell reward.",
3811 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3812 qinfo->RewSpellCast = 0; // no spell will be casted on player
3814 else if(GetTalentSpellCost(qinfo->RewSpellCast))
3816 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u is talent, quest will not have a spell reward.",
3817 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3818 qinfo->RewSpellCast = 0; // no spell will be casted on player
3822 if (qinfo->RewMailTemplateId)
3824 if (!sMailTemplateStore.LookupEntry(qinfo->RewMailTemplateId))
3826 sLog.outErrorDb("Quest %u has `RewMailTemplateId` = %u but mail template %u does not exist, quest will not have a mail reward.",
3827 qinfo->GetQuestId(),qinfo->RewMailTemplateId,qinfo->RewMailTemplateId);
3828 qinfo->RewMailTemplateId = 0; // no mail will send to player
3829 qinfo->RewMailDelaySecs = 0; // no mail will send to player
3831 else if (usedMailTemplates.find(qinfo->RewMailTemplateId) != usedMailTemplates.end())
3833 std::map<uint32,uint32>::const_iterator used_mt_itr = usedMailTemplates.find(qinfo->RewMailTemplateId);
3834 sLog.outErrorDb("Quest %u has `RewMailTemplateId` = %u but mail template %u already used for quest %u, quest will not have a mail reward.",
3835 qinfo->GetQuestId(),qinfo->RewMailTemplateId,qinfo->RewMailTemplateId,used_mt_itr->second);
3836 qinfo->RewMailTemplateId = 0; // no mail will send to player
3837 qinfo->RewMailDelaySecs = 0; // no mail will send to player
3839 else
3840 usedMailTemplates[qinfo->RewMailTemplateId] = qinfo->GetQuestId();
3843 if (qinfo->NextQuestInChain)
3845 QuestMap::iterator qNextItr = mQuestTemplates.find(qinfo->NextQuestInChain);
3846 if (qNextItr == mQuestTemplates.end())
3848 sLog.outErrorDb("Quest %u has `NextQuestInChain` = %u but quest %u does not exist, quest chain will not work.",
3849 qinfo->GetQuestId(),qinfo->NextQuestInChain ,qinfo->NextQuestInChain );
3850 qinfo->NextQuestInChain = 0;
3852 else
3853 qNextItr->second->prevChainQuests.push_back(qinfo->GetQuestId());
3856 // fill additional data stores
3857 if (qinfo->PrevQuestId)
3859 if (mQuestTemplates.find(abs(qinfo->GetPrevQuestId())) == mQuestTemplates.end())
3861 sLog.outErrorDb("Quest %d has PrevQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetPrevQuestId());
3863 else
3865 qinfo->prevQuests.push_back(qinfo->PrevQuestId);
3869 if(qinfo->NextQuestId)
3871 QuestMap::iterator qNextItr = mQuestTemplates.find(abs(qinfo->GetNextQuestId()));
3872 if (qNextItr == mQuestTemplates.end())
3874 sLog.outErrorDb("Quest %d has NextQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetNextQuestId());
3876 else
3878 int32 signedQuestId = qinfo->NextQuestId < 0 ? -int32(qinfo->GetQuestId()) : int32(qinfo->GetQuestId());
3879 qNextItr->second->prevQuests.push_back(signedQuestId);
3883 if(qinfo->ExclusiveGroup)
3884 mExclusiveQuestGroups.insert(std::pair<int32, uint32>(qinfo->ExclusiveGroup, qinfo->GetQuestId()));
3885 if(qinfo->LimitTime)
3886 qinfo->SetFlag(QUEST_MANGOS_FLAGS_TIMED);
3889 // check QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT for spell with SPELL_EFFECT_QUEST_COMPLETE
3890 for (uint32 i = 0; i < sSpellStore.GetNumRows(); ++i)
3892 SpellEntry const *spellInfo = sSpellStore.LookupEntry(i);
3893 if(!spellInfo)
3894 continue;
3896 for(int j = 0; j < 3; ++j)
3898 if(spellInfo->Effect[j] != SPELL_EFFECT_QUEST_COMPLETE)
3899 continue;
3901 uint32 quest_id = spellInfo->EffectMiscValue[j];
3903 Quest const* quest = GetQuestTemplate(quest_id);
3905 // some quest referenced in spells not exist (outdated spells)
3906 if(!quest)
3907 continue;
3909 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3911 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);
3913 // this will prevent quest completing without objective
3914 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3919 sLog.outString();
3920 sLog.outString( ">> Loaded %lu quests definitions", (unsigned long)mQuestTemplates.size() );
3923 void ObjectMgr::LoadQuestLocales()
3925 mQuestLocaleMap.clear(); // need for reload case
3927 QueryResult *result = WorldDatabase.Query("SELECT entry,"
3928 "Title_loc1,Details_loc1,Objectives_loc1,OfferRewardText_loc1,RequestItemsText_loc1,EndText_loc1,ObjectiveText1_loc1,ObjectiveText2_loc1,ObjectiveText3_loc1,ObjectiveText4_loc1,"
3929 "Title_loc2,Details_loc2,Objectives_loc2,OfferRewardText_loc2,RequestItemsText_loc2,EndText_loc2,ObjectiveText1_loc2,ObjectiveText2_loc2,ObjectiveText3_loc2,ObjectiveText4_loc2,"
3930 "Title_loc3,Details_loc3,Objectives_loc3,OfferRewardText_loc3,RequestItemsText_loc3,EndText_loc3,ObjectiveText1_loc3,ObjectiveText2_loc3,ObjectiveText3_loc3,ObjectiveText4_loc3,"
3931 "Title_loc4,Details_loc4,Objectives_loc4,OfferRewardText_loc4,RequestItemsText_loc4,EndText_loc4,ObjectiveText1_loc4,ObjectiveText2_loc4,ObjectiveText3_loc4,ObjectiveText4_loc4,"
3932 "Title_loc5,Details_loc5,Objectives_loc5,OfferRewardText_loc5,RequestItemsText_loc5,EndText_loc5,ObjectiveText1_loc5,ObjectiveText2_loc5,ObjectiveText3_loc5,ObjectiveText4_loc5,"
3933 "Title_loc6,Details_loc6,Objectives_loc6,OfferRewardText_loc6,RequestItemsText_loc6,EndText_loc6,ObjectiveText1_loc6,ObjectiveText2_loc6,ObjectiveText3_loc6,ObjectiveText4_loc6,"
3934 "Title_loc7,Details_loc7,Objectives_loc7,OfferRewardText_loc7,RequestItemsText_loc7,EndText_loc7,ObjectiveText1_loc7,ObjectiveText2_loc7,ObjectiveText3_loc7,ObjectiveText4_loc7,"
3935 "Title_loc8,Details_loc8,Objectives_loc8,OfferRewardText_loc8,RequestItemsText_loc8,EndText_loc8,ObjectiveText1_loc8,ObjectiveText2_loc8,ObjectiveText3_loc8,ObjectiveText4_loc8"
3936 " FROM locales_quest"
3939 if(!result)
3941 barGoLink bar(1);
3943 bar.step();
3945 sLog.outString();
3946 sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_quest` is empty.");
3947 return;
3950 barGoLink bar(result->GetRowCount());
3954 Field *fields = result->Fetch();
3955 bar.step();
3957 uint32 entry = fields[0].GetUInt32();
3959 QuestLocale& data = mQuestLocaleMap[entry];
3961 for(int i = 1; i < MAX_LOCALE; ++i)
3963 std::string str = fields[1+10*(i-1)].GetCppString();
3964 if(!str.empty())
3966 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3967 if(idx >= 0)
3969 if(data.Title.size() <= idx)
3970 data.Title.resize(idx+1);
3972 data.Title[idx] = str;
3975 str = fields[1+10*(i-1)+1].GetCppString();
3976 if(!str.empty())
3978 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3979 if(idx >= 0)
3981 if(data.Details.size() <= idx)
3982 data.Details.resize(idx+1);
3984 data.Details[idx] = str;
3987 str = fields[1+10*(i-1)+2].GetCppString();
3988 if(!str.empty())
3990 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3991 if(idx >= 0)
3993 if(data.Objectives.size() <= idx)
3994 data.Objectives.resize(idx+1);
3996 data.Objectives[idx] = str;
3999 str = fields[1+10*(i-1)+3].GetCppString();
4000 if(!str.empty())
4002 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4003 if(idx >= 0)
4005 if(data.OfferRewardText.size() <= idx)
4006 data.OfferRewardText.resize(idx+1);
4008 data.OfferRewardText[idx] = str;
4011 str = fields[1+10*(i-1)+4].GetCppString();
4012 if(!str.empty())
4014 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4015 if(idx >= 0)
4017 if(data.RequestItemsText.size() <= idx)
4018 data.RequestItemsText.resize(idx+1);
4020 data.RequestItemsText[idx] = str;
4023 str = fields[1+10*(i-1)+5].GetCppString();
4024 if(!str.empty())
4026 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4027 if(idx >= 0)
4029 if(data.EndText.size() <= idx)
4030 data.EndText.resize(idx+1);
4032 data.EndText[idx] = str;
4035 for(int k = 0; k < 4; ++k)
4037 str = fields[1+10*(i-1)+6+k].GetCppString();
4038 if(!str.empty())
4040 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4041 if(idx >= 0)
4043 if(data.ObjectiveText[k].size() <= idx)
4044 data.ObjectiveText[k].resize(idx+1);
4046 data.ObjectiveText[k][idx] = str;
4051 } while (result->NextRow());
4053 delete result;
4055 sLog.outString();
4056 sLog.outString( ">> Loaded %lu Quest locale strings", (unsigned long)mQuestLocaleMap.size() );
4059 void ObjectMgr::LoadScripts(ScriptMapMap& scripts, char const* tablename)
4061 if(sWorld.IsScriptScheduled()) // function don't must be called in time scripts use.
4062 return;
4064 sLog.outString( "%s :", tablename);
4066 scripts.clear(); // need for reload support
4068 QueryResult *result = WorldDatabase.PQuery( "SELECT id,delay,command,datalong,datalong2,dataint, x, y, z, o FROM %s", tablename );
4070 uint32 count = 0;
4072 if( !result )
4074 barGoLink bar( 1 );
4075 bar.step();
4077 sLog.outString();
4078 sLog.outString( ">> Loaded %u script definitions", count );
4079 return;
4082 barGoLink bar( result->GetRowCount() );
4086 bar.step();
4088 Field *fields = result->Fetch();
4089 ScriptInfo tmp;
4090 tmp.id = fields[0].GetUInt32();
4091 tmp.delay = fields[1].GetUInt32();
4092 tmp.command = fields[2].GetUInt32();
4093 tmp.datalong = fields[3].GetUInt32();
4094 tmp.datalong2 = fields[4].GetUInt32();
4095 tmp.dataint = fields[5].GetInt32();
4096 tmp.x = fields[6].GetFloat();
4097 tmp.y = fields[7].GetFloat();
4098 tmp.z = fields[8].GetFloat();
4099 tmp.o = fields[9].GetFloat();
4101 // generic command args check
4102 switch(tmp.command)
4104 case SCRIPT_COMMAND_TALK:
4106 if(tmp.datalong > 3)
4108 sLog.outErrorDb("Table `%s` has invalid talk type (datalong = %u) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.datalong,tmp.id);
4109 continue;
4111 if(tmp.dataint==0)
4113 sLog.outErrorDb("Table `%s` has invalid talk text id (dataint = %i) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.dataint,tmp.id);
4114 continue;
4116 if(tmp.dataint < MIN_DB_SCRIPT_STRING_ID || tmp.dataint >= MAX_DB_SCRIPT_STRING_ID)
4118 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);
4119 continue;
4122 // if(!GetMangosStringLocale(tmp.dataint)) will checked after db_script_string loading
4123 break;
4126 case SCRIPT_COMMAND_EMOTE:
4128 if(!sEmotesStore.LookupEntry(tmp.datalong))
4130 sLog.outErrorDb("Table `%s` has invalid emote id (datalong = %u) in SCRIPT_COMMAND_EMOTE for script id %u",tablename,tmp.datalong,tmp.id);
4131 continue;
4133 break;
4136 case SCRIPT_COMMAND_TELEPORT_TO:
4138 if(!sMapStore.LookupEntry(tmp.datalong))
4140 sLog.outErrorDb("Table `%s` has invalid map (Id: %u) in SCRIPT_COMMAND_TELEPORT_TO for script id %u",tablename,tmp.datalong,tmp.id);
4141 continue;
4144 if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
4146 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);
4147 continue;
4149 break;
4152 case SCRIPT_COMMAND_KILL_CREDIT:
4154 if (!GetCreatureTemplate(tmp.datalong))
4156 sLog.outErrorDb("Table `%s` has invalid creature (Entry: %u) in SCRIPT_COMMAND_KILL_CREDIT for script id %u",tablename,tmp.datalong,tmp.id);
4157 continue;
4159 break;
4162 case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
4164 if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
4166 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);
4167 continue;
4170 if(!GetCreatureTemplate(tmp.datalong))
4172 sLog.outErrorDb("Table `%s` has invalid creature (Entry: %u) in SCRIPT_COMMAND_TEMP_SUMMON_CREATURE for script id %u",tablename,tmp.datalong,tmp.id);
4173 continue;
4175 break;
4178 case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
4180 GameObjectData const* data = GetGOData(tmp.datalong);
4181 if(!data)
4183 sLog.outErrorDb("Table `%s` has invalid gameobject (GUID: %u) in SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,tmp.datalong,tmp.id);
4184 continue;
4187 GameObjectInfo const* info = GetGameObjectInfo(data->id);
4188 if(!info)
4190 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);
4191 continue;
4194 if( info->type==GAMEOBJECT_TYPE_FISHINGNODE ||
4195 info->type==GAMEOBJECT_TYPE_FISHINGHOLE ||
4196 info->type==GAMEOBJECT_TYPE_DOOR ||
4197 info->type==GAMEOBJECT_TYPE_BUTTON ||
4198 info->type==GAMEOBJECT_TYPE_TRAP )
4200 sLog.outErrorDb("Table `%s` have gameobject type (%u) unsupported by command SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,info->id,tmp.id);
4201 continue;
4203 break;
4205 case SCRIPT_COMMAND_OPEN_DOOR:
4206 case SCRIPT_COMMAND_CLOSE_DOOR:
4208 GameObjectData const* data = GetGOData(tmp.datalong);
4209 if(!data)
4211 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);
4212 continue;
4215 GameObjectInfo const* info = GetGameObjectInfo(data->id);
4216 if(!info)
4218 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);
4219 continue;
4222 if( info->type!=GAMEOBJECT_TYPE_DOOR)
4224 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);
4225 continue;
4228 break;
4230 case SCRIPT_COMMAND_QUEST_EXPLORED:
4232 Quest const* quest = GetQuestTemplate(tmp.datalong);
4233 if(!quest)
4235 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);
4236 continue;
4239 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
4241 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);
4243 // this will prevent quest completing without objective
4244 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
4246 // continue; - quest objective requirement set and command can be allowed
4249 if(float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
4251 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",
4252 tablename,tmp.datalong2,tmp.id);
4253 continue;
4256 if(tmp.datalong2 && float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
4258 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",
4259 tablename,tmp.datalong2,tmp.id,DEFAULT_VISIBILITY_DISTANCE);
4260 continue;
4263 if(tmp.datalong2 && float(tmp.datalong2) < INTERACTION_DISTANCE)
4265 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",
4266 tablename,tmp.datalong2,tmp.id,INTERACTION_DISTANCE);
4267 continue;
4270 break;
4273 case SCRIPT_COMMAND_REMOVE_AURA:
4275 if(!sSpellStore.LookupEntry(tmp.datalong))
4277 sLog.outErrorDb("Table `%s` using non-existent spell (id: %u) in SCRIPT_COMMAND_REMOVE_AURA or SCRIPT_COMMAND_CAST_SPELL for script id %u",
4278 tablename,tmp.datalong,tmp.id);
4279 continue;
4281 if(tmp.datalong2 & ~0x1) // 1 bits (0,1)
4283 sLog.outErrorDb("Table `%s` using unknown flags in datalong2 (%u)i n SCRIPT_COMMAND_CAST_SPELL for script id %u",
4284 tablename,tmp.datalong2,tmp.id);
4285 continue;
4287 break;
4289 case SCRIPT_COMMAND_CAST_SPELL:
4291 if(!sSpellStore.LookupEntry(tmp.datalong))
4293 sLog.outErrorDb("Table `%s` using non-existent spell (id: %u) in SCRIPT_COMMAND_REMOVE_AURA or SCRIPT_COMMAND_CAST_SPELL for script id %u",
4294 tablename,tmp.datalong,tmp.id);
4295 continue;
4297 if(tmp.datalong2 & ~0x3) // 2 bits
4299 sLog.outErrorDb("Table `%s` using unknown flags in datalong2 (%u)i n SCRIPT_COMMAND_CAST_SPELL for script id %u",
4300 tablename,tmp.datalong2,tmp.id);
4301 continue;
4303 break;
4307 if (scripts.find(tmp.id) == scripts.end())
4309 ScriptMap emptyMap;
4310 scripts[tmp.id] = emptyMap;
4312 scripts[tmp.id].insert(std::pair<uint32, ScriptInfo>(tmp.delay, tmp));
4314 ++count;
4315 } while( result->NextRow() );
4317 delete result;
4319 sLog.outString();
4320 sLog.outString( ">> Loaded %u script definitions", count );
4323 void ObjectMgr::LoadGameObjectScripts()
4325 LoadScripts(sGameObjectScripts, "gameobject_scripts");
4327 // check ids
4328 for(ScriptMapMap::const_iterator itr = sGameObjectScripts.begin(); itr != sGameObjectScripts.end(); ++itr)
4330 if(!GetGOData(itr->first))
4331 sLog.outErrorDb("Table `gameobject_scripts` has not existing gameobject (GUID: %u) as script id",itr->first);
4335 void ObjectMgr::LoadQuestEndScripts()
4337 LoadScripts(sQuestEndScripts, "quest_end_scripts");
4339 // check ids
4340 for(ScriptMapMap::const_iterator itr = sQuestEndScripts.begin(); itr != sQuestEndScripts.end(); ++itr)
4342 if(!GetQuestTemplate(itr->first))
4343 sLog.outErrorDb("Table `quest_end_scripts` has not existing quest (Id: %u) as script id",itr->first);
4347 void ObjectMgr::LoadQuestStartScripts()
4349 LoadScripts(sQuestStartScripts,"quest_start_scripts");
4351 // check ids
4352 for(ScriptMapMap::const_iterator itr = sQuestStartScripts.begin(); itr != sQuestStartScripts.end(); ++itr)
4354 if(!GetQuestTemplate(itr->first))
4355 sLog.outErrorDb("Table `quest_start_scripts` has not existing quest (Id: %u) as script id",itr->first);
4359 void ObjectMgr::LoadSpellScripts()
4361 LoadScripts(sSpellScripts, "spell_scripts");
4363 // check ids
4364 for(ScriptMapMap::const_iterator itr = sSpellScripts.begin(); itr != sSpellScripts.end(); ++itr)
4366 SpellEntry const* spellInfo = sSpellStore.LookupEntry(itr->first);
4368 if(!spellInfo)
4370 sLog.outErrorDb("Table `spell_scripts` has not existing spell (Id: %u) as script id",itr->first);
4371 continue;
4374 //check for correct spellEffect
4375 bool found = false;
4376 for(int i=0; i<3; ++i)
4378 // skip empty effects
4379 if( !spellInfo->Effect[i] )
4380 continue;
4382 if( spellInfo->Effect[i] == SPELL_EFFECT_SCRIPT_EFFECT )
4384 found = true;
4385 break;
4389 if(!found)
4390 sLog.outErrorDb("Table `spell_scripts` has unsupported spell (Id: %u) without SPELL_EFFECT_SCRIPT_EFFECT (%u) spell effect",itr->first,SPELL_EFFECT_SCRIPT_EFFECT);
4394 void ObjectMgr::LoadEventScripts()
4396 LoadScripts(sEventScripts, "event_scripts");
4398 std::set<uint32> evt_scripts;
4399 // Load all possible script entries from gameobjects
4400 for(uint32 i = 1; i < sGOStorage.MaxEntry; ++i)
4402 GameObjectInfo const * goInfo = sGOStorage.LookupEntry<GameObjectInfo>(i);
4403 if (goInfo)
4405 switch(goInfo->type)
4407 case GAMEOBJECT_TYPE_GOOBER:
4408 if (goInfo->goober.eventId)
4409 evt_scripts.insert(goInfo->goober.eventId);
4410 break;
4411 case GAMEOBJECT_TYPE_CHEST:
4412 if (goInfo->chest.eventId)
4413 evt_scripts.insert(goInfo->chest.eventId);
4414 break;
4415 case GAMEOBJECT_TYPE_CAMERA:
4416 if (goInfo->camera.eventID)
4417 evt_scripts.insert(goInfo->camera.eventID);
4418 default:
4419 break;
4423 // Load all possible script entries from spells
4424 for(uint32 i = 1; i < sSpellStore.GetNumRows(); ++i)
4426 SpellEntry const * spell = sSpellStore.LookupEntry(i);
4427 if (spell)
4429 for(int j=0; j<3; ++j)
4431 if( spell->Effect[j] == SPELL_EFFECT_SEND_EVENT )
4433 if (spell->EffectMiscValue[j])
4434 evt_scripts.insert(spell->EffectMiscValue[j]);
4439 // Then check if all scripts are in above list of possible script entries
4440 for(ScriptMapMap::const_iterator itr = sEventScripts.begin(); itr != sEventScripts.end(); ++itr)
4442 std::set<uint32>::const_iterator itr2 = evt_scripts.find(itr->first);
4443 if (itr2 == evt_scripts.end())
4444 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",
4445 itr->first, SPELL_EFFECT_SEND_EVENT);
4449 void ObjectMgr::LoadGossipScripts()
4451 LoadScripts(sGossipScripts, "gossip_scripts");
4453 // checks are done in LoadGossipMenuItems
4456 void ObjectMgr::LoadItemTexts()
4458 QueryResult *result = CharacterDatabase.Query("SELECT id, text FROM item_text");
4460 uint32 count = 0;
4462 if( !result )
4464 barGoLink bar( 1 );
4465 bar.step();
4467 sLog.outString();
4468 sLog.outString( ">> Loaded %u item pages", count );
4469 return;
4472 barGoLink bar( result->GetRowCount() );
4474 Field* fields;
4477 bar.step();
4479 fields = result->Fetch();
4481 mItemTexts[ fields[0].GetUInt32() ] = fields[1].GetCppString();
4483 ++count;
4485 } while ( result->NextRow() );
4487 delete result;
4489 sLog.outString();
4490 sLog.outString( ">> Loaded %u item texts", count );
4493 void ObjectMgr::LoadPageTexts()
4495 sPageTextStore.Free(); // for reload case
4497 sPageTextStore.Load();
4498 sLog.outString( ">> Loaded %u page texts", sPageTextStore.RecordCount );
4499 sLog.outString();
4501 for(uint32 i = 1; i < sPageTextStore.MaxEntry; ++i)
4503 // check data correctness
4504 PageText const* page = sPageTextStore.LookupEntry<PageText>(i);
4505 if(!page)
4506 continue;
4508 if(page->Next_Page && !sPageTextStore.LookupEntry<PageText>(page->Next_Page))
4510 sLog.outErrorDb("Page text (Id: %u) has not existing next page (Id:%u)", i,page->Next_Page);
4511 continue;
4514 // detect circular reference
4515 std::set<uint32> checkedPages;
4516 for(PageText const* pageItr = page; pageItr; pageItr = sPageTextStore.LookupEntry<PageText>(pageItr->Next_Page))
4518 if(!pageItr->Next_Page)
4519 break;
4520 checkedPages.insert(pageItr->Page_ID);
4521 if(checkedPages.find(pageItr->Next_Page)!=checkedPages.end())
4523 std::ostringstream ss;
4524 ss<< "The text page(s) ";
4525 for (std::set<uint32>::iterator itr= checkedPages.begin();itr!=checkedPages.end(); ++itr)
4526 ss << *itr << " ";
4527 ss << "create(s) a circular reference, which can cause the server to freeze. Changing Next_Page of page "
4528 << pageItr->Page_ID <<" to 0";
4529 sLog.outErrorDb("%s", ss.str().c_str());
4530 const_cast<PageText*>(pageItr)->Next_Page = 0;
4531 break;
4537 void ObjectMgr::LoadPageTextLocales()
4539 mPageTextLocaleMap.clear(); // need for reload case
4541 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");
4543 if(!result)
4545 barGoLink bar(1);
4547 bar.step();
4549 sLog.outString();
4550 sLog.outString(">> Loaded 0 PageText locale strings. DB table `locales_page_text` is empty.");
4551 return;
4554 barGoLink bar(result->GetRowCount());
4558 Field *fields = result->Fetch();
4559 bar.step();
4561 uint32 entry = fields[0].GetUInt32();
4563 PageTextLocale& data = mPageTextLocaleMap[entry];
4565 for(int i = 1; i < MAX_LOCALE; ++i)
4567 std::string str = fields[i].GetCppString();
4568 if(str.empty())
4569 continue;
4571 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4572 if(idx >= 0)
4574 if(data.Text.size() <= idx)
4575 data.Text.resize(idx+1);
4577 data.Text[idx] = str;
4581 } while (result->NextRow());
4583 delete result;
4585 sLog.outString();
4586 sLog.outString( ">> Loaded %lu PageText locale strings", (unsigned long)mPageTextLocaleMap.size() );
4589 struct SQLInstanceLoader : public SQLStorageLoaderBase<SQLInstanceLoader>
4591 template<class D>
4592 void convert_from_str(uint32 /*field_pos*/, char *src, D &dst)
4594 dst = D(sObjectMgr.GetScriptId(src));
4598 void ObjectMgr::LoadInstanceTemplate()
4600 SQLInstanceLoader loader;
4601 loader.Load(sInstanceTemplate);
4603 for(uint32 i = 0; i < sInstanceTemplate.MaxEntry; i++)
4605 InstanceTemplate* temp = (InstanceTemplate*)GetInstanceTemplate(i);
4606 if(!temp)
4607 continue;
4609 if(!MapManager::IsValidMAP(temp->map))
4610 sLog.outErrorDb("ObjectMgr::LoadInstanceTemplate: bad mapid %d for template!", temp->map);
4612 if(!MapManager::IsValidMapCoord(temp->parent,temp->startLocX,temp->startLocY,temp->startLocZ,temp->startLocO))
4614 sLog.outErrorDb("ObjectMgr::LoadInstanceTemplate: bad parent entrance coordinates for map id %d template!", temp->map);
4615 temp->parent = 0; // will have wrong continent 0 parent, at least existed
4619 sLog.outString( ">> Loaded %u Instance Template definitions", sInstanceTemplate.RecordCount );
4620 sLog.outString();
4623 GossipText const *ObjectMgr::GetGossipText(uint32 Text_ID) const
4625 GossipTextMap::const_iterator itr = mGossipText.find(Text_ID);
4626 if(itr != mGossipText.end())
4627 return &itr->second;
4628 return NULL;
4631 void ObjectMgr::LoadGossipText()
4633 QueryResult *result = WorldDatabase.Query( "SELECT * FROM npc_text" );
4635 int count = 0;
4636 if( !result )
4638 barGoLink bar( 1 );
4639 bar.step();
4641 sLog.outString();
4642 sLog.outString( ">> Loaded %u npc texts", count );
4643 return;
4646 int cic;
4648 barGoLink bar( result->GetRowCount() );
4652 ++count;
4653 cic = 0;
4655 Field *fields = result->Fetch();
4657 bar.step();
4659 uint32 Text_ID = fields[cic++].GetUInt32();
4660 if(!Text_ID)
4662 sLog.outErrorDb("Table `npc_text` has record wit reserved id 0, ignore.");
4663 continue;
4666 GossipText& gText = mGossipText[Text_ID];
4668 for (int i=0; i< 8; i++)
4670 gText.Options[i].Text_0 = fields[cic++].GetCppString();
4671 gText.Options[i].Text_1 = fields[cic++].GetCppString();
4673 gText.Options[i].Language = fields[cic++].GetUInt32();
4674 gText.Options[i].Probability = fields[cic++].GetFloat();
4676 for(int j=0; j < 3; ++j)
4678 gText.Options[i].Emotes[j]._Delay = fields[cic++].GetUInt32();
4679 gText.Options[i].Emotes[j]._Emote = fields[cic++].GetUInt32();
4682 } while( result->NextRow() );
4684 sLog.outString();
4685 sLog.outString( ">> Loaded %u npc texts", count );
4686 delete result;
4689 void ObjectMgr::LoadNpcTextLocales()
4691 mNpcTextLocaleMap.clear(); // need for reload case
4693 QueryResult *result = WorldDatabase.Query("SELECT entry,"
4694 "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,"
4695 "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,"
4696 "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,"
4697 "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,"
4698 "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,"
4699 "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,"
4700 "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, "
4701 "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 "
4702 " FROM locales_npc_text");
4704 if(!result)
4706 barGoLink bar(1);
4708 bar.step();
4710 sLog.outString();
4711 sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_npc_text` is empty.");
4712 return;
4715 barGoLink bar(result->GetRowCount());
4719 Field *fields = result->Fetch();
4720 bar.step();
4722 uint32 entry = fields[0].GetUInt32();
4724 NpcTextLocale& data = mNpcTextLocaleMap[entry];
4726 for(int i=1; i<MAX_LOCALE; ++i)
4728 for(int j=0; j<8; ++j)
4730 std::string str0 = fields[1+8*2*(i-1)+2*j].GetCppString();
4731 if(!str0.empty())
4733 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4734 if(idx >= 0)
4736 if(data.Text_0[j].size() <= idx)
4737 data.Text_0[j].resize(idx+1);
4739 data.Text_0[j][idx] = str0;
4742 std::string str1 = fields[1+8*2*(i-1)+2*j+1].GetCppString();
4743 if(!str1.empty())
4745 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4746 if(idx >= 0)
4748 if(data.Text_1[j].size() <= idx)
4749 data.Text_1[j].resize(idx+1);
4751 data.Text_1[j][idx] = str1;
4756 } while (result->NextRow());
4758 delete result;
4760 sLog.outString();
4761 sLog.outString( ">> Loaded %lu NpcText locale strings", (unsigned long)mNpcTextLocaleMap.size() );
4764 //not very fast function but it is called only once a day, or on starting-up
4765 void ObjectMgr::ReturnOrDeleteOldMails(bool serverUp)
4767 time_t basetime = time(NULL);
4768 sLog.outDebug("Returning mails current time: hour: %d, minute: %d, second: %d ", localtime(&basetime)->tm_hour, localtime(&basetime)->tm_min, localtime(&basetime)->tm_sec);
4769 //delete all old mails without item and without body immediately, if starting server
4770 if (!serverUp)
4771 CharacterDatabase.PExecute("DELETE FROM mail WHERE expire_time < '" UI64FMTD "' AND has_items = '0' AND itemTextId = 0", (uint64)basetime);
4772 // 0 1 2 3 4 5 6 7 8 9
4773 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);
4774 if ( !result )
4776 barGoLink bar(1);
4777 bar.step();
4778 sLog.outString();
4779 sLog.outString(">> Only expired mails (need to be return or delete) or DB table `mail` is empty.");
4780 return; // any mails need to be returned or deleted
4783 //std::ostringstream delitems, delmails; //will be here for optimization
4784 //bool deletemail = false, deleteitem = false;
4785 //delitems << "DELETE FROM item_instance WHERE guid IN ( ";
4786 //delmails << "DELETE FROM mail WHERE id IN ( "
4788 barGoLink bar( result->GetRowCount() );
4789 uint32 count = 0;
4790 Field *fields;
4794 bar.step();
4796 fields = result->Fetch();
4797 Mail *m = new Mail;
4798 m->messageID = fields[0].GetUInt32();
4799 m->messageType = fields[1].GetUInt8();
4800 m->sender = fields[2].GetUInt32();
4801 m->receiver = fields[3].GetUInt32();
4802 m->itemTextId = fields[4].GetUInt32();
4803 bool has_items = fields[5].GetBool();
4804 m->expire_time = (time_t)fields[6].GetUInt64();
4805 m->deliver_time = 0;
4806 m->COD = fields[7].GetUInt32();
4807 m->checked = fields[8].GetUInt32();
4808 m->mailTemplateId = fields[9].GetInt16();
4810 Player *pl = 0;
4811 if (serverUp)
4812 pl = GetPlayer((uint64)m->receiver);
4813 if (pl)
4814 { //this code will run very improbably (the time is between 4 and 5 am, in game is online a player, who has old mail
4815 //his in mailbox and he has already listed his mails )
4816 delete m;
4817 continue;
4819 //delete or return mail:
4820 if (has_items)
4822 QueryResult *resultItems = CharacterDatabase.PQuery("SELECT item_guid,item_template FROM mail_items WHERE mail_id='%u'", m->messageID);
4823 if(resultItems)
4827 Field *fields2 = resultItems->Fetch();
4829 uint32 item_guid_low = fields2[0].GetUInt32();
4830 uint32 item_template = fields2[1].GetUInt32();
4832 m->AddItem(item_guid_low, item_template);
4834 while (resultItems->NextRow());
4836 delete resultItems;
4838 //if it is mail from AH, it shouldn't be returned, but deleted
4839 if (m->messageType != MAIL_NORMAL || (m->checked & (MAIL_CHECK_MASK_AUCTION | MAIL_CHECK_MASK_COD_PAYMENT | MAIL_CHECK_MASK_RETURNED)))
4841 // mail open and then not returned
4842 for(std::vector<MailItemInfo>::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
4843 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
4845 else
4847 //mail will be returned:
4848 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);
4849 delete m;
4850 continue;
4854 if (m->itemTextId)
4855 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
4857 //deletemail = true;
4858 //delmails << m->messageID << ", ";
4859 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
4860 delete m;
4861 ++count;
4862 } while (result->NextRow());
4863 delete result;
4865 sLog.outString();
4866 sLog.outString( ">> Loaded %u mails", count );
4869 void ObjectMgr::LoadQuestAreaTriggers()
4871 mQuestAreaTriggerMap.clear(); // need for reload case
4873 QueryResult *result = WorldDatabase.Query( "SELECT id,quest FROM areatrigger_involvedrelation" );
4875 uint32 count = 0;
4877 if( !result )
4879 barGoLink bar( 1 );
4880 bar.step();
4882 sLog.outString();
4883 sLog.outString( ">> Loaded %u quest trigger points", count );
4884 return;
4887 barGoLink bar( result->GetRowCount() );
4891 ++count;
4892 bar.step();
4894 Field *fields = result->Fetch();
4896 uint32 trigger_ID = fields[0].GetUInt32();
4897 uint32 quest_ID = fields[1].GetUInt32();
4899 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(trigger_ID);
4900 if(!atEntry)
4902 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",trigger_ID);
4903 continue;
4906 Quest const* quest = GetQuestTemplate(quest_ID);
4908 if(!quest)
4910 sLog.outErrorDb("Table `areatrigger_involvedrelation` has record (id: %u) for not existing quest %u",trigger_ID,quest_ID);
4911 continue;
4914 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
4916 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);
4918 // this will prevent quest completing without objective
4919 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
4921 // continue; - quest modified to required objective and trigger can be allowed.
4924 mQuestAreaTriggerMap[trigger_ID] = quest_ID;
4926 } while( result->NextRow() );
4928 delete result;
4930 sLog.outString();
4931 sLog.outString( ">> Loaded %u quest trigger points", count );
4934 void ObjectMgr::LoadTavernAreaTriggers()
4936 mTavernAreaTriggerSet.clear(); // need for reload case
4938 QueryResult *result = WorldDatabase.Query("SELECT id FROM areatrigger_tavern");
4940 uint32 count = 0;
4942 if( !result )
4944 barGoLink bar( 1 );
4945 bar.step();
4947 sLog.outString();
4948 sLog.outString( ">> Loaded %u tavern triggers", count );
4949 return;
4952 barGoLink bar( result->GetRowCount() );
4956 ++count;
4957 bar.step();
4959 Field *fields = result->Fetch();
4961 uint32 Trigger_ID = fields[0].GetUInt32();
4963 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4964 if(!atEntry)
4966 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4967 continue;
4970 mTavernAreaTriggerSet.insert(Trigger_ID);
4971 } while( result->NextRow() );
4973 delete result;
4975 sLog.outString();
4976 sLog.outString( ">> Loaded %u tavern triggers", count );
4979 void ObjectMgr::LoadAreaTriggerScripts()
4981 mAreaTriggerScripts.clear(); // need for reload case
4982 QueryResult *result = WorldDatabase.Query("SELECT entry, ScriptName FROM areatrigger_scripts");
4984 uint32 count = 0;
4986 if( !result )
4988 barGoLink bar( 1 );
4989 bar.step();
4991 sLog.outString();
4992 sLog.outString( ">> Loaded %u areatrigger scripts", count );
4993 return;
4996 barGoLink bar( result->GetRowCount() );
5000 ++count;
5001 bar.step();
5003 Field *fields = result->Fetch();
5005 uint32 Trigger_ID = fields[0].GetUInt32();
5006 const char *scriptName = fields[1].GetString();
5008 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
5009 if(!atEntry)
5011 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
5012 continue;
5014 mAreaTriggerScripts[Trigger_ID] = GetScriptId(scriptName);
5015 } while( result->NextRow() );
5017 delete result;
5019 sLog.outString();
5020 sLog.outString( ">> Loaded %u areatrigger scripts", count );
5023 uint32 ObjectMgr::GetNearestTaxiNode( float x, float y, float z, uint32 mapid, uint32 team )
5025 bool found = false;
5026 float dist;
5027 uint32 id = 0;
5029 for(uint32 i = 1; i < sTaxiNodesStore.GetNumRows(); ++i)
5031 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(i);
5032 if(!node || node->map_id != mapid || !node->MountCreatureID[team == ALLIANCE ? 1 : 0])
5033 continue;
5035 uint8 field = (uint8)((i - 1) / 32);
5036 uint32 submask = 1<<((i-1)%32);
5038 // skip not taxi network nodes
5039 if((sTaxiNodesMask[field] & submask)==0)
5040 continue;
5042 float dist2 = (node->x - x)*(node->x - x)+(node->y - y)*(node->y - y)+(node->z - z)*(node->z - z);
5043 if(found)
5045 if(dist2 < dist)
5047 dist = dist2;
5048 id = i;
5051 else
5053 found = true;
5054 dist = dist2;
5055 id = i;
5059 return id;
5062 void ObjectMgr::GetTaxiPath( uint32 source, uint32 destination, uint32 &path, uint32 &cost)
5064 TaxiPathSetBySource::iterator src_i = sTaxiPathSetBySource.find(source);
5065 if(src_i==sTaxiPathSetBySource.end())
5067 path = 0;
5068 cost = 0;
5069 return;
5072 TaxiPathSetForSource& pathSet = src_i->second;
5074 TaxiPathSetForSource::iterator dest_i = pathSet.find(destination);
5075 if(dest_i==pathSet.end())
5077 path = 0;
5078 cost = 0;
5079 return;
5082 cost = dest_i->second.price;
5083 path = dest_i->second.ID;
5086 uint32 ObjectMgr::GetTaxiMountDisplayId( uint32 id, uint32 team, bool allowed_alt_team /* = false */)
5088 uint16 mount_entry = 0;
5090 // select mount creature id
5091 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(id);
5092 if(node)
5094 if (team == ALLIANCE)
5096 mount_entry = node->MountCreatureID[1];
5097 if(!mount_entry && allowed_alt_team)
5098 mount_entry = node->MountCreatureID[0];
5100 else if (team == HORDE)
5102 mount_entry = node->MountCreatureID[0];
5104 if(!mount_entry && allowed_alt_team)
5105 mount_entry = node->MountCreatureID[1];
5109 CreatureInfo const *mount_info = GetCreatureTemplate(mount_entry);
5110 if (!mount_info)
5111 return 0;
5113 uint16 mount_id = ChooseDisplayId(team,mount_info);
5114 if (!mount_id)
5115 return 0;
5117 CreatureModelInfo const *minfo = GetCreatureModelRandomGender(mount_id);
5118 if (minfo)
5119 mount_id = minfo->modelid;
5121 return mount_id;
5124 void ObjectMgr::GetTaxiPathNodes( uint32 path, Path &pathnodes, std::vector<uint32>& mapIds)
5126 if(path >= sTaxiPathNodesByPath.size())
5127 return;
5129 TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
5131 pathnodes.Resize(nodeList.size());
5132 mapIds.resize(nodeList.size());
5134 for(size_t i = 0; i < nodeList.size(); ++i)
5136 pathnodes[ i ].x = nodeList[i].x;
5137 pathnodes[ i ].y = nodeList[i].y;
5138 pathnodes[ i ].z = nodeList[i].z;
5140 mapIds[i] = nodeList[i].mapid;
5144 void ObjectMgr::GetTransportPathNodes( uint32 path, TransportPath &pathnodes )
5146 if(path >= sTaxiPathNodesByPath.size())
5147 return;
5149 TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
5151 pathnodes.Resize(nodeList.size());
5153 for(size_t i = 0; i < nodeList.size(); ++i)
5155 pathnodes[ i ].mapid = nodeList[i].mapid;
5156 pathnodes[ i ].x = nodeList[i].x;
5157 pathnodes[ i ].y = nodeList[i].y;
5158 pathnodes[ i ].z = nodeList[i].z;
5159 pathnodes[ i ].actionFlag = nodeList[i].actionFlag;
5160 pathnodes[ i ].delay = nodeList[i].delay;
5164 void ObjectMgr::LoadGraveyardZones()
5166 mGraveYardMap.clear(); // need for reload case
5168 QueryResult *result = WorldDatabase.Query("SELECT id,ghost_zone,faction FROM game_graveyard_zone");
5170 uint32 count = 0;
5172 if( !result )
5174 barGoLink bar( 1 );
5175 bar.step();
5177 sLog.outString();
5178 sLog.outString( ">> Loaded %u graveyard-zone links", count );
5179 return;
5182 barGoLink bar( result->GetRowCount() );
5186 ++count;
5187 bar.step();
5189 Field *fields = result->Fetch();
5191 uint32 safeLocId = fields[0].GetUInt32();
5192 uint32 zoneId = fields[1].GetUInt32();
5193 uint32 team = fields[2].GetUInt32();
5195 WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(safeLocId);
5196 if(!entry)
5198 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",safeLocId);
5199 continue;
5202 AreaTableEntry const *areaEntry = GetAreaEntryByAreaID(zoneId);
5203 if(!areaEntry)
5205 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing zone id (%u), skipped.",zoneId);
5206 continue;
5209 if(areaEntry->zone != 0)
5211 sLog.outErrorDb("Table `game_graveyard_zone` has record subzone id (%u) instead of zone, skipped.",zoneId);
5212 continue;
5215 if(team!=0 && team!=HORDE && team!=ALLIANCE)
5217 sLog.outErrorDb("Table `game_graveyard_zone` has record for non player faction (%u), skipped.",team);
5218 continue;
5221 if(!AddGraveYardLink(safeLocId,zoneId,team,false))
5222 sLog.outErrorDb("Table `game_graveyard_zone` has a duplicate record for Graveyard (ID: %u) and Zone (ID: %u), skipped.",safeLocId,zoneId);
5223 } while( result->NextRow() );
5225 delete result;
5227 sLog.outString();
5228 sLog.outString( ">> Loaded %u graveyard-zone links", count );
5231 WorldSafeLocsEntry const *ObjectMgr::GetClosestGraveYard(float x, float y, float z, uint32 MapId, uint32 team)
5233 // search for zone associated closest graveyard
5234 uint32 zoneId = sMapMgr.GetZoneId(MapId,x,y,z);
5236 // Simulate std. algorithm:
5237 // found some graveyard associated to (ghost_zone,ghost_map)
5239 // if mapId == graveyard.mapId (ghost in plain zone or city or battleground) and search graveyard at same map
5240 // then check faction
5241 // if mapId != graveyard.mapId (ghost in instance) and search any graveyard associated
5242 // then check faction
5243 GraveYardMap::const_iterator graveLow = mGraveYardMap.lower_bound(zoneId);
5244 GraveYardMap::const_iterator graveUp = mGraveYardMap.upper_bound(zoneId);
5245 if(graveLow==graveUp)
5247 sLog.outErrorDb("Table `game_graveyard_zone` incomplete: Zone %u Team %u does not have a linked graveyard.",zoneId,team);
5248 return NULL;
5251 // at corpse map
5252 bool foundNear = false;
5253 float distNear;
5254 WorldSafeLocsEntry const* entryNear = NULL;
5256 // at entrance map for corpse map
5257 bool foundEntr = false;
5258 float distEntr;
5259 WorldSafeLocsEntry const* entryEntr = NULL;
5261 // some where other
5262 WorldSafeLocsEntry const* entryFar = NULL;
5264 MapEntry const* mapEntry = sMapStore.LookupEntry(MapId);
5266 for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
5268 GraveYardData const& data = itr->second;
5270 WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(data.safeLocId);
5271 if(!entry)
5273 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",data.safeLocId);
5274 continue;
5277 // skip enemy faction graveyard
5278 // team == 0 case can be at call from .neargrave
5279 if(data.team != 0 && team != 0 && data.team != team)
5280 continue;
5282 // find now nearest graveyard at other map
5283 if(MapId != entry->map_id)
5285 // if find graveyard at different map from where entrance placed (or no entrance data), use any first
5286 if (!mapEntry ||
5287 mapEntry->entrance_map < 0 ||
5288 mapEntry->entrance_map != entry->map_id ||
5289 (mapEntry->entrance_x == 0 && mapEntry->entrance_y == 0))
5291 // not have any corrdinates for check distance anyway
5292 entryFar = entry;
5293 continue;
5296 // at entrance map calculate distance (2D);
5297 float dist2 = (entry->x - mapEntry->entrance_x)*(entry->x - mapEntry->entrance_x)
5298 +(entry->y - mapEntry->entrance_y)*(entry->y - mapEntry->entrance_y);
5299 if(foundEntr)
5301 if(dist2 < distEntr)
5303 distEntr = dist2;
5304 entryEntr = entry;
5307 else
5309 foundEntr = true;
5310 distEntr = dist2;
5311 entryEntr = entry;
5314 // find now nearest graveyard at same map
5315 else
5317 float dist2 = (entry->x - x)*(entry->x - x)+(entry->y - y)*(entry->y - y)+(entry->z - z)*(entry->z - z);
5318 if(foundNear)
5320 if(dist2 < distNear)
5322 distNear = dist2;
5323 entryNear = entry;
5326 else
5328 foundNear = true;
5329 distNear = dist2;
5330 entryNear = entry;
5335 if(entryNear)
5336 return entryNear;
5338 if(entryEntr)
5339 return entryEntr;
5341 return entryFar;
5344 GraveYardData const* ObjectMgr::FindGraveYardData(uint32 id, uint32 zoneId)
5346 GraveYardMap::const_iterator graveLow = mGraveYardMap.lower_bound(zoneId);
5347 GraveYardMap::const_iterator graveUp = mGraveYardMap.upper_bound(zoneId);
5349 for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
5351 if(itr->second.safeLocId==id)
5352 return &itr->second;
5355 return NULL;
5358 bool ObjectMgr::AddGraveYardLink(uint32 id, uint32 zoneId, uint32 team, bool inDB)
5360 if(FindGraveYardData(id,zoneId))
5361 return false;
5363 // add link to loaded data
5364 GraveYardData data;
5365 data.safeLocId = id;
5366 data.team = team;
5368 mGraveYardMap.insert(GraveYardMap::value_type(zoneId,data));
5370 // add link to DB
5371 if(inDB)
5373 WorldDatabase.PExecuteLog("INSERT INTO game_graveyard_zone ( id,ghost_zone,faction) "
5374 "VALUES ('%u', '%u','%u')",id,zoneId,team);
5377 return true;
5380 void ObjectMgr::LoadAreaTriggerTeleports()
5382 mAreaTriggers.clear(); // need for reload case
5384 uint32 count = 0;
5386 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13
5387 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");
5388 if( !result )
5391 barGoLink bar( 1 );
5393 bar.step();
5395 sLog.outString();
5396 sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
5397 return;
5400 barGoLink bar( result->GetRowCount() );
5404 Field *fields = result->Fetch();
5406 bar.step();
5408 ++count;
5410 uint32 Trigger_ID = fields[0].GetUInt32();
5412 AreaTrigger at;
5414 at.requiredLevel = fields[1].GetUInt8();
5415 at.requiredItem = fields[2].GetUInt32();
5416 at.requiredItem2 = fields[3].GetUInt32();
5417 at.heroicKey = fields[4].GetUInt32();
5418 at.heroicKey2 = fields[5].GetUInt32();
5419 at.requiredQuest = fields[6].GetUInt32();
5420 at.requiredQuestHeroic = fields[7].GetUInt32();
5421 at.requiredFailedText = fields[8].GetCppString();
5422 at.target_mapId = fields[9].GetUInt32();
5423 at.target_X = fields[10].GetFloat();
5424 at.target_Y = fields[11].GetFloat();
5425 at.target_Z = fields[12].GetFloat();
5426 at.target_Orientation = fields[13].GetFloat();
5428 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
5429 if(!atEntry)
5431 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
5432 continue;
5435 if(at.requiredItem)
5437 ItemPrototype const *pProto = GetItemPrototype(at.requiredItem);
5438 if(!pProto)
5440 sLog.outError("Key item %u does not exist for trigger %u, removing key requirement.", at.requiredItem, Trigger_ID);
5441 at.requiredItem = 0;
5444 if(at.requiredItem2)
5446 ItemPrototype const *pProto = GetItemPrototype(at.requiredItem2);
5447 if(!pProto)
5449 sLog.outError("Second item %u not exist for trigger %u, remove key requirement.", at.requiredItem2, Trigger_ID);
5450 at.requiredItem2 = 0;
5454 if(at.heroicKey)
5456 ItemPrototype const *pProto = GetItemPrototype(at.heroicKey);
5457 if(!pProto)
5459 sLog.outError("Heroic key item %u not exist for trigger %u, remove key requirement.", at.heroicKey, Trigger_ID);
5460 at.heroicKey = 0;
5464 if(at.heroicKey2)
5466 ItemPrototype const *pProto = GetItemPrototype(at.heroicKey2);
5467 if(!pProto)
5469 sLog.outError("Heroic second key item %u not exist for trigger %u, remove key requirement.", at.heroicKey2, Trigger_ID);
5470 at.heroicKey2 = 0;
5474 if(at.requiredQuest)
5476 QuestMap::iterator qReqItr = mQuestTemplates.find(at.requiredQuest);
5477 if(qReqItr == mQuestTemplates.end())
5479 sLog.outErrorDb("Required Quest %u not exist for trigger %u, remove quest done requirement.",at.requiredQuest,Trigger_ID);
5480 at.requiredQuest = 0;
5484 if(at.requiredQuestHeroic)
5486 QuestMap::iterator qReqItr = mQuestTemplates.find(at.requiredQuestHeroic);
5487 if(qReqItr == mQuestTemplates.end())
5489 sLog.outErrorDb("Required Quest %u not exist for trigger %u, remove quest done requirement.",at.requiredQuestHeroic,Trigger_ID);
5490 at.requiredQuestHeroic = 0;
5494 MapEntry const* mapEntry = sMapStore.LookupEntry(at.target_mapId);
5495 if(!mapEntry)
5497 sLog.outErrorDb("Area trigger (ID:%u) target map (ID: %u) does not exist in `Map.dbc`.",Trigger_ID,at.target_mapId);
5498 continue;
5501 if(at.target_X==0 && at.target_Y==0 && at.target_Z==0)
5503 sLog.outErrorDb("Area trigger (ID:%u) target coordinates not provided.",Trigger_ID);
5504 continue;
5507 mAreaTriggers[Trigger_ID] = at;
5509 } while( result->NextRow() );
5511 delete result;
5513 sLog.outString();
5514 sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
5518 * Searches for the areatrigger which teleports players out of the given map
5520 AreaTrigger const* ObjectMgr::GetGoBackTrigger(uint32 Map) const
5522 const MapEntry *mapEntry = sMapStore.LookupEntry(Map);
5523 if(!mapEntry) return NULL;
5524 for (AreaTriggerMap::const_iterator itr = mAreaTriggers.begin(); itr != mAreaTriggers.end(); ++itr)
5526 if(itr->second.target_mapId == mapEntry->entrance_map)
5528 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(itr->first);
5529 if(atEntry && atEntry->mapid == Map)
5530 return &itr->second;
5533 return NULL;
5537 * Searches for the areatrigger which teleports players to the given map
5539 AreaTrigger const* ObjectMgr::GetMapEntranceTrigger(uint32 Map) const
5541 for (AreaTriggerMap::const_iterator itr = mAreaTriggers.begin(); itr != mAreaTriggers.end(); ++itr)
5543 if(itr->second.target_mapId == Map)
5545 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(itr->first);
5546 if(atEntry)
5547 return &itr->second;
5550 return NULL;
5553 void ObjectMgr::SetHighestGuids()
5555 QueryResult *result = CharacterDatabase.Query( "SELECT MAX(guid) FROM characters" );
5556 if( result )
5558 m_hiCharGuid = (*result)[0].GetUInt32()+1;
5559 delete result;
5562 result = WorldDatabase.Query( "SELECT MAX(guid) FROM creature" );
5563 if( result )
5565 m_hiCreatureGuid = (*result)[0].GetUInt32()+1;
5566 delete result;
5569 result = CharacterDatabase.Query( "SELECT MAX(guid) FROM item_instance" );
5570 if( result )
5572 m_hiItemGuid = (*result)[0].GetUInt32()+1;
5573 delete result;
5576 // Cleanup other tables from not existed guids (>=m_hiItemGuid)
5577 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item >= '%u'", m_hiItemGuid);
5578 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid >= '%u'", m_hiItemGuid);
5579 CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE itemguid >= '%u'", m_hiItemGuid);
5580 CharacterDatabase.PExecute("DELETE FROM guild_bank_item WHERE item_guid >= '%u'", m_hiItemGuid);
5582 result = WorldDatabase.Query("SELECT MAX(guid) FROM gameobject" );
5583 if( result )
5585 m_hiGoGuid = (*result)[0].GetUInt32()+1;
5586 delete result;
5589 result = CharacterDatabase.Query("SELECT MAX(id) FROM auctionhouse" );
5590 if( result )
5592 m_auctionid = (*result)[0].GetUInt32()+1;
5593 delete result;
5596 result = CharacterDatabase.Query( "SELECT MAX(id) FROM mail" );
5597 if( result )
5599 m_mailid = (*result)[0].GetUInt32()+1;
5600 delete result;
5603 result = CharacterDatabase.Query( "SELECT MAX(id) FROM item_text" );
5604 if( result )
5606 m_ItemTextId = (*result)[0].GetUInt32()+1;
5607 delete result;
5610 result = CharacterDatabase.Query( "SELECT MAX(guid) FROM corpse" );
5611 if( result )
5613 m_hiCorpseGuid = (*result)[0].GetUInt32()+1;
5614 delete result;
5617 result = CharacterDatabase.Query("SELECT MAX(arenateamid) FROM arena_team");
5618 if (result)
5620 m_arenaTeamId = (*result)[0].GetUInt32()+1;
5621 delete result;
5624 result = CharacterDatabase.Query("SELECT MAX(setguid) FROM character_equipmentsets");
5625 if (result)
5627 m_equipmentSetGuid = (*result)[0].GetUInt64()+1;
5628 delete result;
5631 result = CharacterDatabase.Query( "SELECT MAX(guildid) FROM guild" );
5632 if (result)
5634 m_guildId = (*result)[0].GetUInt32()+1;
5635 delete result;
5639 uint32 ObjectMgr::GenerateArenaTeamId()
5641 if(m_arenaTeamId>=0xFFFFFFFE)
5643 sLog.outError("Arena team ids overflow!! Can't continue, shutting down server. ");
5644 World::StopNow(ERROR_EXIT_CODE);
5646 return m_arenaTeamId++;
5649 uint32 ObjectMgr::GenerateAuctionID()
5651 if(m_auctionid>=0xFFFFFFFE)
5653 sLog.outError("Auctions ids overflow!! Can't continue, shutting down server. ");
5654 World::StopNow(ERROR_EXIT_CODE);
5656 return m_auctionid++;
5659 uint64 ObjectMgr::GenerateEquipmentSetGuid()
5661 if(m_equipmentSetGuid>=0xFFFFFFFFFFFFFFFEll)
5663 sLog.outError("EquipmentSet guid overflow!! Can't continue, shutting down server. ");
5664 World::StopNow(ERROR_EXIT_CODE);
5666 return m_equipmentSetGuid++;
5669 uint32 ObjectMgr::GenerateGuildId()
5671 if(m_guildId>=0xFFFFFFFE)
5673 sLog.outError("Guild ids overflow!! Can't continue, shutting down server. ");
5674 World::StopNow(ERROR_EXIT_CODE);
5676 return m_guildId++;
5679 uint32 ObjectMgr::GenerateMailID()
5681 if(m_mailid>=0xFFFFFFFE)
5683 sLog.outError("Mail ids overflow!! Can't continue, shutting down server. ");
5684 World::StopNow(ERROR_EXIT_CODE);
5686 return m_mailid++;
5689 uint32 ObjectMgr::GenerateItemTextID()
5691 if(m_ItemTextId>=0xFFFFFFFE)
5693 sLog.outError("Item text ids overflow!! Can't continue, shutting down server. ");
5694 World::StopNow(ERROR_EXIT_CODE);
5696 return m_ItemTextId++;
5699 uint32 ObjectMgr::CreateItemText(std::string text)
5701 uint32 newItemTextId = GenerateItemTextID();
5702 //insert new itempage to container
5703 mItemTexts[ newItemTextId ] = text;
5704 //save new itempage
5705 CharacterDatabase.escape_string(text);
5706 //any Delete query needed, itemTextId is maximum of all ids
5707 std::ostringstream query;
5708 query << "INSERT INTO item_text (id,text) VALUES ( '" << newItemTextId << "', '" << text << "')";
5709 CharacterDatabase.Execute(query.str().c_str()); //needs to be run this way, because mail body may be more than 1024 characters
5710 return newItemTextId;
5713 uint32 ObjectMgr::GenerateLowGuid(HighGuid guidhigh)
5715 switch(guidhigh)
5717 case HIGHGUID_ITEM:
5718 if(m_hiItemGuid>=0xFFFFFFFE)
5720 sLog.outError("Item guid overflow!! Can't continue, shutting down server. ");
5721 World::StopNow(ERROR_EXIT_CODE);
5723 return m_hiItemGuid++;
5724 case HIGHGUID_UNIT:
5725 if(m_hiCreatureGuid>=0x00FFFFFE)
5727 sLog.outError("Creature guid overflow!! Can't continue, shutting down server. ");
5728 World::StopNow(ERROR_EXIT_CODE);
5730 return m_hiCreatureGuid++;
5731 case HIGHGUID_PLAYER:
5732 if(m_hiCharGuid>=0xFFFFFFFE)
5734 sLog.outError("Players guid overflow!! Can't continue, shutting down server. ");
5735 World::StopNow(ERROR_EXIT_CODE);
5737 return m_hiCharGuid++;
5738 case HIGHGUID_GAMEOBJECT:
5739 if(m_hiGoGuid>=0x00FFFFFE)
5741 sLog.outError("Gameobject guid overflow!! Can't continue, shutting down server. ");
5742 World::StopNow(ERROR_EXIT_CODE);
5744 return m_hiGoGuid++;
5745 case HIGHGUID_CORPSE:
5746 if(m_hiCorpseGuid>=0xFFFFFFFE)
5748 sLog.outError("Corpse guid overflow!! Can't continue, shutting down server. ");
5749 World::StopNow(ERROR_EXIT_CODE);
5751 return m_hiCorpseGuid++;
5752 default:
5753 ASSERT(0);
5756 ASSERT(0);
5757 return 0;
5760 void ObjectMgr::LoadGameObjectLocales()
5762 mGameObjectLocaleMap.clear(); // need for reload case
5764 QueryResult *result = WorldDatabase.Query("SELECT entry,"
5765 "name_loc1,name_loc2,name_loc3,name_loc4,name_loc5,name_loc6,name_loc7,name_loc8,"
5766 "castbarcaption_loc1,castbarcaption_loc2,castbarcaption_loc3,castbarcaption_loc4,"
5767 "castbarcaption_loc5,castbarcaption_loc6,castbarcaption_loc7,castbarcaption_loc8 FROM locales_gameobject");
5769 if(!result)
5771 barGoLink bar(1);
5773 bar.step();
5775 sLog.outString();
5776 sLog.outString(">> Loaded 0 gameobject locale strings. DB table `locales_gameobject` is empty.");
5777 return;
5780 barGoLink bar(result->GetRowCount());
5784 Field *fields = result->Fetch();
5785 bar.step();
5787 uint32 entry = fields[0].GetUInt32();
5789 GameObjectLocale& data = mGameObjectLocaleMap[entry];
5791 for(int i = 1; i < MAX_LOCALE; ++i)
5793 std::string str = fields[i].GetCppString();
5794 if(!str.empty())
5796 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5797 if(idx >= 0)
5799 if(data.Name.size() <= idx)
5800 data.Name.resize(idx+1);
5802 data.Name[idx] = str;
5807 for(int i = 1; i < MAX_LOCALE; ++i)
5809 std::string str = fields[i+(MAX_LOCALE-1)].GetCppString();
5810 if(!str.empty())
5812 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5813 if(idx >= 0)
5815 if(data.CastBarCaption.size() <= idx)
5816 data.CastBarCaption.resize(idx+1);
5818 data.CastBarCaption[idx] = str;
5823 } while (result->NextRow());
5825 delete result;
5827 sLog.outString();
5828 sLog.outString( ">> Loaded %lu gameobject locale strings", (unsigned long)mGameObjectLocaleMap.size() );
5831 struct SQLGameObjectLoader : public SQLStorageLoaderBase<SQLGameObjectLoader>
5833 template<class D>
5834 void convert_from_str(uint32 /*field_pos*/, char *src, D &dst)
5836 dst = D(sObjectMgr.GetScriptId(src));
5840 inline void CheckGOLockId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5842 if (sLockStore.LookupEntry(dataN))
5843 return;
5845 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but lock (Id: %u) not found.",
5846 goInfo->id,goInfo->type,N,goInfo->door.lockId,goInfo->door.lockId);
5849 inline void CheckGOLinkedTrapId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5851 if (GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(dataN))
5853 if (trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5854 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5855 goInfo->id,goInfo->type,N,dataN,dataN,GAMEOBJECT_TYPE_TRAP);
5857 /* disable check for while (too many error reports baout not existed in trap templates
5858 else
5859 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5860 goInfo->id,goInfo->type,N,dataN,dataN);
5864 inline void CheckGOSpellId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5866 if (sSpellStore.LookupEntry(dataN))
5867 return;
5869 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but Spell (Entry %u) not exist.",
5870 goInfo->id,goInfo->type,N,dataN,dataN);
5873 inline void CheckAndFixGOChairHeightId(GameObjectInfo const* goInfo,uint32 const& dataN,uint32 N)
5875 if (dataN <= (UNIT_STAND_STATE_SIT_HIGH_CHAIR-UNIT_STAND_STATE_SIT_LOW_CHAIR) )
5876 return;
5878 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but correct chair height in range 0..%i.",
5879 goInfo->id,goInfo->type,N,dataN,UNIT_STAND_STATE_SIT_HIGH_CHAIR-UNIT_STAND_STATE_SIT_LOW_CHAIR);
5881 // prevent client and server unexpected work
5882 const_cast<uint32&>(dataN) = 0;
5885 inline void CheckGONoDamageImmuneId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5887 // 0/1 correct values
5888 if (dataN <= 1)
5889 return;
5891 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but expected boolean (0/1) noDamageImmune field value.",
5892 goInfo->id,goInfo->type,N,dataN);
5895 inline void CheckGOConsumable(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5897 // 0/1 correct values
5898 if (dataN <= 1)
5899 return;
5901 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but expected boolean (0/1) consumable field value.",
5902 goInfo->id,goInfo->type,N,dataN);
5905 void ObjectMgr::LoadGameobjectInfo()
5907 SQLGameObjectLoader loader;
5908 loader.Load(sGOStorage);
5910 // some checks
5911 for(uint32 id = 1; id < sGOStorage.MaxEntry; id++)
5913 GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(id);
5914 if (!goInfo)
5915 continue;
5917 // some GO types have unused go template, check goInfo->displayId at GO spawn data loading or ignore
5919 switch(goInfo->type)
5921 case GAMEOBJECT_TYPE_DOOR: //0
5923 if (goInfo->door.lockId)
5924 CheckGOLockId(goInfo,goInfo->door.lockId,1);
5925 CheckGONoDamageImmuneId(goInfo,goInfo->door.noDamageImmune,3);
5926 break;
5928 case GAMEOBJECT_TYPE_BUTTON: //1
5930 if (goInfo->button.lockId)
5931 CheckGOLockId(goInfo,goInfo->button.lockId,1);
5932 CheckGONoDamageImmuneId(goInfo,goInfo->button.noDamageImmune,4);
5933 break;
5935 case GAMEOBJECT_TYPE_QUESTGIVER: //2
5937 if (goInfo->questgiver.lockId)
5938 CheckGOLockId(goInfo,goInfo->questgiver.lockId,0);
5939 CheckGONoDamageImmuneId(goInfo,goInfo->questgiver.noDamageImmune,5);
5940 break;
5942 case GAMEOBJECT_TYPE_CHEST: //3
5944 if (goInfo->chest.lockId)
5945 CheckGOLockId(goInfo,goInfo->chest.lockId,0);
5947 CheckGOConsumable(goInfo,goInfo->chest.consumable,3);
5949 if (goInfo->chest.linkedTrapId) // linked trap
5950 CheckGOLinkedTrapId(goInfo,goInfo->chest.linkedTrapId,7);
5951 break;
5953 case GAMEOBJECT_TYPE_TRAP: //6
5955 if (goInfo->trap.lockId)
5956 CheckGOLockId(goInfo,goInfo->trap.lockId,0);
5957 /* disable check for while, too many not existed spells
5958 if (goInfo->trap.spellId) // spell
5959 CheckGOSpellId(goInfo,goInfo->trap.spellId,3);
5961 break;
5963 case GAMEOBJECT_TYPE_CHAIR: //7
5964 CheckAndFixGOChairHeightId(goInfo,goInfo->chair.height,1);
5965 break;
5966 case GAMEOBJECT_TYPE_SPELL_FOCUS: //8
5968 if (goInfo->spellFocus.focusId)
5970 if (!sSpellFocusObjectStore.LookupEntry(goInfo->spellFocus.focusId))
5971 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but SpellFocus (Id: %u) not exist.",
5972 id,goInfo->type,goInfo->spellFocus.focusId,goInfo->spellFocus.focusId);
5975 if (goInfo->spellFocus.linkedTrapId) // linked trap
5976 CheckGOLinkedTrapId(goInfo,goInfo->spellFocus.linkedTrapId,2);
5977 break;
5979 case GAMEOBJECT_TYPE_GOOBER: //10
5981 if (goInfo->goober.lockId)
5982 CheckGOLockId(goInfo,goInfo->goober.lockId,0);
5984 CheckGOConsumable(goInfo,goInfo->goober.consumable,3);
5986 if (goInfo->goober.pageId) // pageId
5988 if (!sPageTextStore.LookupEntry<PageText>(goInfo->goober.pageId))
5989 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data7=%u but PageText (Entry %u) not exist.",
5990 id,goInfo->type,goInfo->goober.pageId,goInfo->goober.pageId);
5992 /* disable check for while, too many not existed spells
5993 if (goInfo->goober.spellId) // spell
5994 CheckGOSpellId(goInfo,goInfo->goober.spellId,10);
5996 CheckGONoDamageImmuneId(goInfo,goInfo->goober.noDamageImmune,11);
5997 if (goInfo->goober.linkedTrapId) // linked trap
5998 CheckGOLinkedTrapId(goInfo,goInfo->goober.linkedTrapId,12);
5999 break;
6001 case GAMEOBJECT_TYPE_AREADAMAGE: //12
6003 if (goInfo->areadamage.lockId)
6004 CheckGOLockId(goInfo,goInfo->areadamage.lockId,0);
6005 break;
6007 case GAMEOBJECT_TYPE_CAMERA: //13
6009 if (goInfo->camera.lockId)
6010 CheckGOLockId(goInfo,goInfo->camera.lockId,0);
6011 break;
6013 case GAMEOBJECT_TYPE_MO_TRANSPORT: //15
6015 if (goInfo->moTransport.taxiPathId)
6017 if (goInfo->moTransport.taxiPathId >= sTaxiPathNodesByPath.size() || sTaxiPathNodesByPath[goInfo->moTransport.taxiPathId].empty())
6018 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but TaxiPath (Id: %u) not exist.",
6019 id,goInfo->type,goInfo->moTransport.taxiPathId,goInfo->moTransport.taxiPathId);
6021 break;
6023 case GAMEOBJECT_TYPE_SUMMONING_RITUAL: //18
6025 /* disable check for while, too many not existed spells
6026 // always must have spell
6027 CheckGOSpellId(goInfo,goInfo->summoningRitual.spellId,1);
6029 break;
6031 case GAMEOBJECT_TYPE_SPELLCASTER: //22
6033 // always must have spell
6034 CheckGOSpellId(goInfo,goInfo->spellcaster.spellId,0);
6035 break;
6037 case GAMEOBJECT_TYPE_FLAGSTAND: //24
6039 if (goInfo->flagstand.lockId)
6040 CheckGOLockId(goInfo,goInfo->flagstand.lockId,0);
6041 CheckGONoDamageImmuneId(goInfo,goInfo->flagstand.noDamageImmune,5);
6042 break;
6044 case GAMEOBJECT_TYPE_FISHINGHOLE: //25
6046 if (goInfo->fishinghole.lockId)
6047 CheckGOLockId(goInfo,goInfo->fishinghole.lockId,4);
6048 break;
6050 case GAMEOBJECT_TYPE_FLAGDROP: //26
6052 if (goInfo->flagdrop.lockId)
6053 CheckGOLockId(goInfo,goInfo->flagdrop.lockId,0);
6054 CheckGONoDamageImmuneId(goInfo,goInfo->flagdrop.noDamageImmune,3);
6055 break;
6057 case GAMEOBJECT_TYPE_BARBER_CHAIR: //32
6058 CheckAndFixGOChairHeightId(goInfo,goInfo->barberChair.chairheight,0);
6059 break;
6063 sLog.outString( ">> Loaded %u game object templates", sGOStorage.RecordCount );
6064 sLog.outString();
6067 void ObjectMgr::LoadExplorationBaseXP()
6069 uint32 count = 0;
6070 QueryResult *result = WorldDatabase.Query("SELECT level,basexp FROM exploration_basexp");
6072 if( !result )
6074 barGoLink bar( 1 );
6076 bar.step();
6078 sLog.outString();
6079 sLog.outString( ">> Loaded %u BaseXP definitions", count );
6080 return;
6083 barGoLink bar( result->GetRowCount() );
6087 bar.step();
6089 Field *fields = result->Fetch();
6090 uint32 level = fields[0].GetUInt32();
6091 uint32 basexp = fields[1].GetUInt32();
6092 mBaseXPTable[level] = basexp;
6093 ++count;
6095 while (result->NextRow());
6097 delete result;
6099 sLog.outString();
6100 sLog.outString( ">> Loaded %u BaseXP definitions", count );
6103 uint32 ObjectMgr::GetBaseXP(uint32 level)
6105 return mBaseXPTable[level] ? mBaseXPTable[level] : 0;
6108 uint32 ObjectMgr::GetXPForLevel(uint32 level)
6110 if (level < mPlayerXPperLevel.size())
6111 return mPlayerXPperLevel[level];
6112 return 0;
6115 void ObjectMgr::LoadPetNames()
6117 uint32 count = 0;
6118 QueryResult *result = WorldDatabase.Query("SELECT word,entry,half FROM pet_name_generation");
6120 if( !result )
6122 barGoLink bar( 1 );
6124 bar.step();
6126 sLog.outString();
6127 sLog.outString( ">> Loaded %u pet name parts", count );
6128 return;
6131 barGoLink bar( result->GetRowCount() );
6135 bar.step();
6137 Field *fields = result->Fetch();
6138 std::string word = fields[0].GetString();
6139 uint32 entry = fields[1].GetUInt32();
6140 bool half = fields[2].GetBool();
6141 if(half)
6142 PetHalfName1[entry].push_back(word);
6143 else
6144 PetHalfName0[entry].push_back(word);
6145 ++count;
6147 while (result->NextRow());
6148 delete result;
6150 sLog.outString();
6151 sLog.outString( ">> Loaded %u pet name parts", count );
6154 void ObjectMgr::LoadPetNumber()
6156 QueryResult* result = CharacterDatabase.Query("SELECT MAX(id) FROM character_pet");
6157 if(result)
6159 Field *fields = result->Fetch();
6160 m_hiPetNumber = fields[0].GetUInt32()+1;
6161 delete result;
6164 barGoLink bar( 1 );
6165 bar.step();
6167 sLog.outString();
6168 sLog.outString( ">> Loaded the max pet number: %d", m_hiPetNumber-1);
6171 std::string ObjectMgr::GeneratePetName(uint32 entry)
6173 std::vector<std::string> & list0 = PetHalfName0[entry];
6174 std::vector<std::string> & list1 = PetHalfName1[entry];
6176 if(list0.empty() || list1.empty())
6178 CreatureInfo const *cinfo = GetCreatureTemplate(entry);
6179 char* petname = GetPetName(cinfo->family, sWorld.GetDefaultDbcLocale());
6180 if(!petname)
6181 petname = cinfo->Name;
6182 return std::string(petname);
6185 return *(list0.begin()+urand(0, list0.size()-1)) + *(list1.begin()+urand(0, list1.size()-1));
6188 uint32 ObjectMgr::GeneratePetNumber()
6190 return ++m_hiPetNumber;
6193 void ObjectMgr::LoadCorpses()
6195 uint32 count = 0;
6196 // 0 1 2 3 4 5 6 7 8 10
6197 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");
6199 if( !result )
6201 barGoLink bar( 1 );
6203 bar.step();
6205 sLog.outString();
6206 sLog.outString( ">> Loaded %u corpses", count );
6207 return;
6210 barGoLink bar( result->GetRowCount() );
6214 bar.step();
6216 Field *fields = result->Fetch();
6218 uint32 guid = fields[result->GetFieldCount()-1].GetUInt32();
6220 Corpse *corpse = new Corpse;
6221 if(!corpse->LoadFromDB(guid,fields))
6223 delete corpse;
6224 continue;
6227 sObjectAccessor.AddCorpse(corpse);
6229 ++count;
6231 while (result->NextRow());
6232 delete result;
6234 sLog.outString();
6235 sLog.outString( ">> Loaded %u corpses", count );
6238 void ObjectMgr::LoadReputationOnKill()
6240 uint32 count = 0;
6242 // 0 1 2
6243 QueryResult *result = WorldDatabase.Query("SELECT creature_id, RewOnKillRepFaction1, RewOnKillRepFaction2,"
6244 // 3 4 5 6 7 8 9
6245 "IsTeamAward1, MaxStanding1, RewOnKillRepValue1, IsTeamAward2, MaxStanding2, RewOnKillRepValue2, TeamDependent "
6246 "FROM creature_onkill_reputation");
6248 if(!result)
6250 barGoLink bar(1);
6252 bar.step();
6254 sLog.outString();
6255 sLog.outErrorDb(">> Loaded 0 creature award reputation definitions. DB table `creature_onkill_reputation` is empty.");
6256 return;
6259 barGoLink bar(result->GetRowCount());
6263 Field *fields = result->Fetch();
6264 bar.step();
6266 uint32 creature_id = fields[0].GetUInt32();
6268 ReputationOnKillEntry repOnKill;
6269 repOnKill.repfaction1 = fields[1].GetUInt32();
6270 repOnKill.repfaction2 = fields[2].GetUInt32();
6271 repOnKill.is_teamaward1 = fields[3].GetBool();
6272 repOnKill.reputation_max_cap1 = fields[4].GetUInt32();
6273 repOnKill.repvalue1 = fields[5].GetInt32();
6274 repOnKill.is_teamaward2 = fields[6].GetBool();
6275 repOnKill.reputation_max_cap2 = fields[7].GetUInt32();
6276 repOnKill.repvalue2 = fields[8].GetInt32();
6277 repOnKill.team_dependent = fields[9].GetUInt8();
6279 if(!GetCreatureTemplate(creature_id))
6281 sLog.outErrorDb("Table `creature_onkill_reputation` have data for not existed creature entry (%u), skipped",creature_id);
6282 continue;
6285 if(repOnKill.repfaction1)
6287 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(repOnKill.repfaction1);
6288 if(!factionEntry1)
6290 sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction1);
6291 continue;
6295 if(repOnKill.repfaction2)
6297 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(repOnKill.repfaction2);
6298 if(!factionEntry2)
6300 sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction2);
6301 continue;
6305 mRepOnKill[creature_id] = repOnKill;
6307 ++count;
6308 } while (result->NextRow());
6310 delete result;
6312 sLog.outString();
6313 sLog.outString(">> Loaded %u creature award reputation definitions", count);
6316 void ObjectMgr::LoadPointsOfInterest()
6318 uint32 count = 0;
6320 // 0 1 2 3 4 5
6321 QueryResult *result = WorldDatabase.Query("SELECT entry, x, y, icon, flags, data, icon_name FROM points_of_interest");
6323 if(!result)
6325 barGoLink bar(1);
6327 bar.step();
6329 sLog.outString();
6330 sLog.outErrorDb(">> Loaded 0 Points of Interest definitions. DB table `points_of_interest` is empty.");
6331 return;
6334 barGoLink bar(result->GetRowCount());
6338 Field *fields = result->Fetch();
6339 bar.step();
6341 uint32 point_id = fields[0].GetUInt32();
6343 PointOfInterest POI;
6344 POI.x = fields[1].GetFloat();
6345 POI.y = fields[2].GetFloat();
6346 POI.icon = fields[3].GetUInt32();
6347 POI.flags = fields[4].GetUInt32();
6348 POI.data = fields[5].GetUInt32();
6349 POI.icon_name = fields[6].GetCppString();
6351 if(!MaNGOS::IsValidMapCoord(POI.x,POI.y))
6353 sLog.outErrorDb("Table `points_of_interest` (Entry: %u) have invalid coordinates (X: %f Y: %f), ignored.",point_id,POI.x,POI.y);
6354 continue;
6357 mPointsOfInterest[point_id] = POI;
6359 ++count;
6360 } while (result->NextRow());
6362 delete result;
6364 sLog.outString();
6365 sLog.outString(">> Loaded %u Points of Interest definitions", count);
6368 void ObjectMgr::LoadQuestPOI()
6370 uint32 count = 0;
6372 // 0 1 2 3 4 5 6
6373 QueryResult *result = WorldDatabase.Query("SELECT questId, objIndex, mapId, unk1, unk2, unk3, unk4 FROM quest_poi");
6375 if(!result)
6377 barGoLink bar(1);
6379 bar.step();
6381 sLog.outString();
6382 sLog.outErrorDb(">> Loaded 0 quest POI definitions. DB table `quest_poi` is empty.");
6383 return;
6386 barGoLink bar(result->GetRowCount());
6390 Field *fields = result->Fetch();
6391 bar.step();
6393 uint32 questId = fields[0].GetUInt32();
6394 int32 objIndex = fields[1].GetInt32();
6395 uint32 mapId = fields[2].GetUInt32();
6396 uint32 unk1 = fields[3].GetUInt32();
6397 uint32 unk2 = fields[4].GetUInt32();
6398 uint32 unk3 = fields[5].GetUInt32();
6399 uint32 unk4 = fields[6].GetUInt32();
6401 QuestPOI POI(objIndex, mapId, unk1, unk2, unk3, unk4);
6403 QueryResult *points = WorldDatabase.PQuery("SELECT x, y FROM quest_poi_points WHERE questId='%u' AND objIndex='%i'", questId, objIndex);
6405 if(points)
6409 Field *pointFields = points->Fetch();
6410 int32 x = pointFields[0].GetInt32();
6411 int32 y = pointFields[1].GetInt32();
6412 QuestPOIPoint point(x, y);
6413 POI.points.push_back(point);
6414 } while (points->NextRow());
6416 delete points;
6419 mQuestPOIMap[questId].push_back(POI);
6421 ++count;
6422 } while (result->NextRow());
6424 delete result;
6426 sLog.outString();
6427 sLog.outString(">> Loaded %u quest POI definitions", count);
6430 void ObjectMgr::LoadNPCSpellClickSpells()
6432 uint32 count = 0;
6434 mSpellClickInfoMap.clear();
6435 // 0 1 2 3 4 5
6436 QueryResult *result = WorldDatabase.Query("SELECT npc_entry, spell_id, quest_start, quest_start_active, quest_end, cast_flags FROM npc_spellclick_spells");
6438 if(!result)
6440 barGoLink bar(1);
6442 bar.step();
6444 sLog.outString();
6445 sLog.outErrorDb(">> Loaded 0 spellclick spells. DB table `npc_spellclick_spells` is empty.");
6446 return;
6449 barGoLink bar(result->GetRowCount());
6453 Field *fields = result->Fetch();
6454 bar.step();
6456 uint32 npc_entry = fields[0].GetUInt32();
6457 CreatureInfo const* cInfo = GetCreatureTemplate(npc_entry);
6458 if (!cInfo)
6460 sLog.outErrorDb("Table npc_spellclick_spells references unknown creature_template %u. Skipping entry.", npc_entry);
6461 continue;
6464 uint32 spellid = fields[1].GetUInt32();
6465 SpellEntry const *spellinfo = sSpellStore.LookupEntry(spellid);
6466 if (!spellinfo)
6468 sLog.outErrorDb("Table npc_spellclick_spells references unknown spellid %u. Skipping entry.", spellid);
6469 continue;
6472 uint32 quest_start = fields[2].GetUInt32();
6474 // quest might be 0 to enable spellclick independent of any quest
6475 if (quest_start)
6477 if(mQuestTemplates.find(quest_start) == mQuestTemplates.end())
6479 sLog.outErrorDb("Table npc_spellclick_spells references unknown start quest %u. Skipping entry.", quest_start);
6480 continue;
6485 bool quest_start_active = fields[3].GetBool();
6487 uint32 quest_end = fields[4].GetUInt32();
6488 // quest might be 0 to enable spellclick active infinity after start quest
6489 if (quest_end)
6491 if(mQuestTemplates.find(quest_end) == mQuestTemplates.end())
6493 sLog.outErrorDb("Table npc_spellclick_spells references unknown end quest %u. Skipping entry.", quest_end);
6494 continue;
6499 uint8 castFlags = fields[5].GetUInt8();
6500 SpellClickInfo info;
6501 info.spellId = spellid;
6502 info.questStart = quest_start;
6503 info.questStartCanActive = quest_start_active;
6504 info.questEnd = quest_end;
6505 info.castFlags = castFlags;
6506 mSpellClickInfoMap.insert(SpellClickInfoMap::value_type(npc_entry, info));
6508 // mark creature template as spell clickable
6509 const_cast<CreatureInfo*>(cInfo)->npcflag |= UNIT_NPC_FLAG_SPELLCLICK;
6511 ++count;
6512 } while (result->NextRow());
6514 delete result;
6516 sLog.outString();
6517 sLog.outString(">> Loaded %u spellclick definitions", count);
6520 void ObjectMgr::LoadWeatherZoneChances()
6522 uint32 count = 0;
6524 // 0 1 2 3 4 5 6 7 8 9 10 11 12
6525 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");
6527 if(!result)
6529 barGoLink bar(1);
6531 bar.step();
6533 sLog.outString();
6534 sLog.outErrorDb(">> Loaded 0 weather definitions. DB table `game_weather` is empty.");
6535 return;
6538 barGoLink bar(result->GetRowCount());
6542 Field *fields = result->Fetch();
6543 bar.step();
6545 uint32 zone_id = fields[0].GetUInt32();
6547 WeatherZoneChances& wzc = mWeatherZoneMap[zone_id];
6549 for(int season = 0; season < WEATHER_SEASONS; ++season)
6551 wzc.data[season].rainChance = fields[season * (MAX_WEATHER_TYPE-1) + 1].GetUInt32();
6552 wzc.data[season].snowChance = fields[season * (MAX_WEATHER_TYPE-1) + 2].GetUInt32();
6553 wzc.data[season].stormChance = fields[season * (MAX_WEATHER_TYPE-1) + 3].GetUInt32();
6555 if(wzc.data[season].rainChance > 100)
6557 wzc.data[season].rainChance = 25;
6558 sLog.outErrorDb("Weather for zone %u season %u has wrong rain chance > 100%%",zone_id,season);
6561 if(wzc.data[season].snowChance > 100)
6563 wzc.data[season].snowChance = 25;
6564 sLog.outErrorDb("Weather for zone %u season %u has wrong snow chance > 100%%",zone_id,season);
6567 if(wzc.data[season].stormChance > 100)
6569 wzc.data[season].stormChance = 25;
6570 sLog.outErrorDb("Weather for zone %u season %u has wrong storm chance > 100%%",zone_id,season);
6574 ++count;
6575 } while (result->NextRow());
6577 delete result;
6579 sLog.outString();
6580 sLog.outString(">> Loaded %u weather definitions", count);
6583 void ObjectMgr::SaveCreatureRespawnTime(uint32 loguid, uint32 instance, time_t t)
6585 mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
6586 WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
6587 if(t)
6588 WorldDatabase.PExecute("INSERT INTO creature_respawn VALUES ( '%u', '" UI64FMTD "', '%u' )", loguid, uint64(t), instance);
6591 void ObjectMgr::DeleteCreatureData(uint32 guid)
6593 // remove mapid*cellid -> guid_set map
6594 CreatureData const* data = GetCreatureData(guid);
6595 if(data)
6596 RemoveCreatureFromGrid(guid, data);
6598 mCreatureDataMap.erase(guid);
6601 void ObjectMgr::SaveGORespawnTime(uint32 loguid, uint32 instance, time_t t)
6603 mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
6604 WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
6605 if(t)
6606 WorldDatabase.PExecute("INSERT INTO gameobject_respawn VALUES ( '%u', '" UI64FMTD "', '%u' )", loguid, uint64(t), instance);
6609 void ObjectMgr::DeleteRespawnTimeForInstance(uint32 instance)
6611 RespawnTimes::iterator next;
6613 for(RespawnTimes::iterator itr = mGORespawnTimes.begin(); itr != mGORespawnTimes.end(); itr = next)
6615 next = itr;
6616 ++next;
6618 if(GUID_HIPART(itr->first)==instance)
6619 mGORespawnTimes.erase(itr);
6622 for(RespawnTimes::iterator itr = mCreatureRespawnTimes.begin(); itr != mCreatureRespawnTimes.end(); itr = next)
6624 next = itr;
6625 ++next;
6627 if(GUID_HIPART(itr->first)==instance)
6628 mCreatureRespawnTimes.erase(itr);
6631 WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE instance = '%u'", instance);
6632 WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE instance = '%u'", instance);
6635 void ObjectMgr::DeleteGOData(uint32 guid)
6637 // remove mapid*cellid -> guid_set map
6638 GameObjectData const* data = GetGOData(guid);
6639 if(data)
6640 RemoveGameobjectFromGrid(guid, data);
6642 mGameObjectDataMap.erase(guid);
6645 void ObjectMgr::AddCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid, uint32 instance)
6647 // corpses are always added to spawn mode 0 and they are spawned by their instance id
6648 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
6649 cell_guids.corpses[player_guid] = instance;
6652 void ObjectMgr::DeleteCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid)
6654 // corpses are always added to spawn mode 0 and they are spawned by their instance id
6655 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
6656 cell_guids.corpses.erase(player_guid);
6659 void ObjectMgr::LoadQuestRelationsHelper(QuestRelations& map,char const* table)
6661 map.clear(); // need for reload case
6663 uint32 count = 0;
6665 QueryResult *result = WorldDatabase.PQuery("SELECT id,quest FROM %s",table);
6667 if(!result)
6669 barGoLink bar(1);
6671 bar.step();
6673 sLog.outString();
6674 sLog.outErrorDb(">> Loaded 0 quest relations from %s. DB table `%s` is empty.",table,table);
6675 return;
6678 barGoLink bar(result->GetRowCount());
6682 Field *fields = result->Fetch();
6683 bar.step();
6685 uint32 id = fields[0].GetUInt32();
6686 uint32 quest = fields[1].GetUInt32();
6688 if(mQuestTemplates.find(quest) == mQuestTemplates.end())
6690 sLog.outErrorDb("Table `%s: Quest %u listed for entry %u does not exist.",table,quest,id);
6691 continue;
6694 map.insert(QuestRelations::value_type(id,quest));
6696 ++count;
6697 } while (result->NextRow());
6699 delete result;
6701 sLog.outString();
6702 sLog.outString(">> Loaded %u quest relations from %s", count,table);
6705 void ObjectMgr::LoadGameobjectQuestRelations()
6707 LoadQuestRelationsHelper(mGOQuestRelations,"gameobject_questrelation");
6709 for(QuestRelations::iterator itr = mGOQuestRelations.begin(); itr != mGOQuestRelations.end(); ++itr)
6711 GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
6712 if(!goInfo)
6713 sLog.outErrorDb("Table `gameobject_questrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
6714 else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
6715 sLog.outErrorDb("Table `gameobject_questrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
6719 void ObjectMgr::LoadGameobjectInvolvedRelations()
6721 LoadQuestRelationsHelper(mGOQuestInvolvedRelations,"gameobject_involvedrelation");
6723 for(QuestRelations::iterator itr = mGOQuestInvolvedRelations.begin(); itr != mGOQuestInvolvedRelations.end(); ++itr)
6725 GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
6726 if(!goInfo)
6727 sLog.outErrorDb("Table `gameobject_involvedrelation` 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_involvedrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
6733 void ObjectMgr::LoadCreatureQuestRelations()
6735 LoadQuestRelationsHelper(mCreatureQuestRelations,"creature_questrelation");
6737 for(QuestRelations::iterator itr = mCreatureQuestRelations.begin(); itr != mCreatureQuestRelations.end(); ++itr)
6739 CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
6740 if(!cInfo)
6741 sLog.outErrorDb("Table `creature_questrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
6742 else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
6743 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);
6747 void ObjectMgr::LoadCreatureInvolvedRelations()
6749 LoadQuestRelationsHelper(mCreatureQuestInvolvedRelations,"creature_involvedrelation");
6751 for(QuestRelations::iterator itr = mCreatureQuestInvolvedRelations.begin(); itr != mCreatureQuestInvolvedRelations.end(); ++itr)
6753 CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
6754 if(!cInfo)
6755 sLog.outErrorDb("Table `creature_involvedrelation` 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_involvedrelation` has creature entry (%u) for quest %u, but npcflag does not include UNIT_NPC_FLAG_QUESTGIVER",itr->first,itr->second);
6761 void ObjectMgr::LoadReservedPlayersNames()
6763 m_ReservedNames.clear(); // need for reload case
6765 QueryResult *result = WorldDatabase.Query("SELECT name FROM reserved_name");
6767 uint32 count = 0;
6769 if( !result )
6771 barGoLink bar( 1 );
6772 bar.step();
6774 sLog.outString();
6775 sLog.outString( ">> Loaded %u reserved player names", count );
6776 return;
6779 barGoLink bar( result->GetRowCount() );
6781 Field* fields;
6784 bar.step();
6785 fields = result->Fetch();
6786 std::string name= fields[0].GetCppString();
6788 std::wstring wstr;
6789 if(!Utf8toWStr (name,wstr))
6791 sLog.outError("Table `reserved_name` have invalid name: %s", name.c_str() );
6792 continue;
6795 wstrToLower(wstr);
6797 m_ReservedNames.insert(wstr);
6798 ++count;
6799 } while ( result->NextRow() );
6801 delete result;
6803 sLog.outString();
6804 sLog.outString( ">> Loaded %u reserved player names", count );
6807 bool ObjectMgr::IsReservedName( const std::string& name ) const
6809 std::wstring wstr;
6810 if(!Utf8toWStr (name,wstr))
6811 return false;
6813 wstrToLower(wstr);
6815 return m_ReservedNames.find(wstr) != m_ReservedNames.end();
6818 enum LanguageType
6820 LT_BASIC_LATIN = 0x0000,
6821 LT_EXTENDEN_LATIN = 0x0001,
6822 LT_CYRILLIC = 0x0002,
6823 LT_EAST_ASIA = 0x0004,
6824 LT_ANY = 0xFFFF
6827 static LanguageType GetRealmLanguageType(bool create)
6829 switch(sWorld.getConfig(CONFIG_REALM_ZONE))
6831 case REALM_ZONE_UNKNOWN: // any language
6832 case REALM_ZONE_DEVELOPMENT:
6833 case REALM_ZONE_TEST_SERVER:
6834 case REALM_ZONE_QA_SERVER:
6835 return LT_ANY;
6836 case REALM_ZONE_UNITED_STATES: // extended-Latin
6837 case REALM_ZONE_OCEANIC:
6838 case REALM_ZONE_LATIN_AMERICA:
6839 case REALM_ZONE_ENGLISH:
6840 case REALM_ZONE_GERMAN:
6841 case REALM_ZONE_FRENCH:
6842 case REALM_ZONE_SPANISH:
6843 return LT_EXTENDEN_LATIN;
6844 case REALM_ZONE_KOREA: // East-Asian
6845 case REALM_ZONE_TAIWAN:
6846 case REALM_ZONE_CHINA:
6847 return LT_EAST_ASIA;
6848 case REALM_ZONE_RUSSIAN: // Cyrillic
6849 return LT_CYRILLIC;
6850 default:
6851 return create ? LT_BASIC_LATIN : LT_ANY; // basic-Latin at create, any at login
6855 bool isValidString(std::wstring wstr, uint32 strictMask, bool numericOrSpace, bool create = false)
6857 if(strictMask==0) // any language, ignore realm
6859 if(isExtendedLatinString(wstr,numericOrSpace))
6860 return true;
6861 if(isCyrillicString(wstr,numericOrSpace))
6862 return true;
6863 if(isEastAsianString(wstr,numericOrSpace))
6864 return true;
6865 return false;
6868 if(strictMask & 0x2) // realm zone specific
6870 LanguageType lt = GetRealmLanguageType(create);
6871 if(lt & LT_EXTENDEN_LATIN)
6872 if(isExtendedLatinString(wstr,numericOrSpace))
6873 return true;
6874 if(lt & LT_CYRILLIC)
6875 if(isCyrillicString(wstr,numericOrSpace))
6876 return true;
6877 if(lt & LT_EAST_ASIA)
6878 if(isEastAsianString(wstr,numericOrSpace))
6879 return true;
6882 if(strictMask & 0x1) // basic Latin
6884 if(isBasicLatinString(wstr,numericOrSpace))
6885 return true;
6888 return false;
6891 uint8 ObjectMgr::CheckPlayerName( const std::string& name, bool create )
6893 std::wstring wname;
6894 if(!Utf8toWStr(name,wname))
6895 return CHAR_NAME_INVALID_CHARACTER;
6897 if(wname.size() > MAX_PLAYER_NAME)
6898 return CHAR_NAME_TOO_LONG;
6900 uint32 minName = sWorld.getConfig(CONFIG_MIN_PLAYER_NAME);
6901 if(wname.size() < minName)
6902 return CHAR_NAME_TOO_SHORT;
6904 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_PLAYER_NAMES);
6905 if(!isValidString(wname,strictMask,false,create))
6906 return CHAR_NAME_MIXED_LANGUAGES;
6908 return CHAR_NAME_SUCCESS;
6911 bool ObjectMgr::IsValidCharterName( const std::string& name )
6913 std::wstring wname;
6914 if(!Utf8toWStr(name,wname))
6915 return false;
6917 if(wname.size() > MAX_CHARTER_NAME)
6918 return false;
6920 uint32 minName = sWorld.getConfig(CONFIG_MIN_CHARTER_NAME);
6921 if(wname.size() < minName)
6922 return false;
6924 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_CHARTER_NAMES);
6926 return isValidString(wname,strictMask,true);
6929 PetNameInvalidReason ObjectMgr::CheckPetName( const std::string& name )
6931 std::wstring wname;
6932 if(!Utf8toWStr(name,wname))
6933 return PET_NAME_INVALID;
6935 if(wname.size() > MAX_PET_NAME)
6936 return PET_NAME_TOO_LONG;
6938 uint32 minName = sWorld.getConfig(CONFIG_MIN_PET_NAME);
6939 if(wname.size() < minName)
6940 return PET_NAME_TOO_SHORT;
6942 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_PET_NAMES);
6943 if(!isValidString(wname,strictMask,false))
6944 return PET_NAME_MIXED_LANGUAGES;
6946 return PET_NAME_SUCCESS;
6949 int ObjectMgr::GetIndexForLocale( LocaleConstant loc )
6951 if(loc==LOCALE_enUS)
6952 return -1;
6954 for(size_t i=0;i < m_LocalForIndex.size(); ++i)
6955 if(m_LocalForIndex[i]==loc)
6956 return i;
6958 return -1;
6961 LocaleConstant ObjectMgr::GetLocaleForIndex(int i)
6963 if (i<0 || i>=m_LocalForIndex.size())
6964 return LOCALE_enUS;
6966 return m_LocalForIndex[i];
6969 int ObjectMgr::GetOrNewIndexForLocale( LocaleConstant loc )
6971 if(loc==LOCALE_enUS)
6972 return -1;
6974 for(size_t i=0;i < m_LocalForIndex.size(); ++i)
6975 if(m_LocalForIndex[i]==loc)
6976 return i;
6978 m_LocalForIndex.push_back(loc);
6979 return m_LocalForIndex.size()-1;
6982 void ObjectMgr::LoadGameObjectForQuests()
6984 mGameObjectForQuestSet.clear(); // need for reload case
6986 if( !sGOStorage.MaxEntry )
6988 barGoLink bar( 1 );
6989 bar.step();
6990 sLog.outString();
6991 sLog.outString( ">> Loaded 0 GameObjects for quests" );
6992 return;
6995 barGoLink bar( sGOStorage.MaxEntry - 1 );
6996 uint32 count = 0;
6998 // collect GO entries for GO that must activated
6999 for(uint32 go_entry = 1; go_entry < sGOStorage.MaxEntry; ++go_entry)
7001 bar.step();
7002 GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(go_entry);
7003 if(!goInfo)
7004 continue;
7006 switch(goInfo->type)
7008 // scan GO chest with loot including quest items
7009 case GAMEOBJECT_TYPE_CHEST:
7011 uint32 loot_id = goInfo->GetLootId();
7013 // find quest loot for GO
7014 if(LootTemplates_Gameobject.HaveQuestLootFor(loot_id))
7016 mGameObjectForQuestSet.insert(go_entry);
7017 ++count;
7019 break;
7021 case GAMEOBJECT_TYPE_GOOBER:
7023 if(goInfo->goober.questId) //quests objects
7025 mGameObjectForQuestSet.insert(go_entry);
7026 count++;
7028 break;
7030 default:
7031 break;
7035 sLog.outString();
7036 sLog.outString( ">> Loaded %u GameObjects for quests", count );
7039 bool ObjectMgr::LoadMangosStrings(DatabaseType& db, char const* table, int32 min_value, int32 max_value)
7041 int32 start_value = min_value;
7042 int32 end_value = max_value;
7043 // some string can have negative indexes range
7044 if (start_value < 0)
7046 if (end_value >= start_value)
7048 sLog.outErrorDb("Table '%s' attempt loaded with invalid range (%d - %d), strings not loaded.",table,min_value,max_value);
7049 return false;
7052 // real range (max+1,min+1) exaple: (-10,-1000) -> -999...-10+1
7053 std::swap(start_value,end_value);
7054 ++start_value;
7055 ++end_value;
7057 else
7059 if (start_value >= end_value)
7061 sLog.outErrorDb("Table '%s' attempt loaded with invalid range (%d - %d), strings not loaded.",table,min_value,max_value);
7062 return false;
7066 // cleanup affected map part for reloading case
7067 for(MangosStringLocaleMap::iterator itr = mMangosStringLocaleMap.begin(); itr != mMangosStringLocaleMap.end();)
7069 if (itr->first >= start_value && itr->first < end_value)
7070 mMangosStringLocaleMap.erase(itr++);
7071 else
7072 ++itr;
7075 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);
7077 if (!result)
7079 barGoLink bar(1);
7081 bar.step();
7083 sLog.outString();
7084 if (min_value == MIN_MANGOS_STRING_ID) // error only in case internal strings
7085 sLog.outErrorDb(">> Loaded 0 mangos strings. DB table `%s` is empty. Cannot continue.",table);
7086 else
7087 sLog.outString(">> Loaded 0 string templates. DB table `%s` is empty.",table);
7088 return false;
7091 uint32 count = 0;
7093 barGoLink bar(result->GetRowCount());
7097 Field *fields = result->Fetch();
7098 bar.step();
7100 int32 entry = fields[0].GetInt32();
7102 if (entry==0)
7104 sLog.outErrorDb("Table `%s` contain reserved entry 0, ignored.",table);
7105 continue;
7107 else if (entry < start_value || entry >= end_value)
7109 sLog.outErrorDb("Table `%s` contain entry %i out of allowed range (%d - %d), ignored.",table,entry,min_value,max_value);
7110 continue;
7113 MangosStringLocale& data = mMangosStringLocaleMap[entry];
7115 if (data.Content.size() > 0)
7117 sLog.outErrorDb("Table `%s` contain data for already loaded entry %i (from another table?), ignored.",table,entry);
7118 continue;
7121 data.Content.resize(1);
7122 ++count;
7124 // 0 -> default, idx in to idx+1
7125 data.Content[0] = fields[1].GetCppString();
7127 for(int i = 1; i < MAX_LOCALE; ++i)
7129 std::string str = fields[i+1].GetCppString();
7130 if (!str.empty())
7132 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
7133 if (idx >= 0)
7135 // 0 -> default, idx in to idx+1
7136 if (data.Content.size() <= idx+1)
7137 data.Content.resize(idx+2);
7139 data.Content[idx+1] = str;
7143 } while (result->NextRow());
7145 delete result;
7147 sLog.outString();
7148 if (min_value == MIN_MANGOS_STRING_ID)
7149 sLog.outString( ">> Loaded %u MaNGOS strings from table %s", count,table);
7150 else
7151 sLog.outString( ">> Loaded %u string templates from %s", count,table);
7153 return true;
7156 const char *ObjectMgr::GetMangosString(int32 entry, int locale_idx) const
7158 // locale_idx==-1 -> default, locale_idx >= 0 in to idx+1
7159 // Content[0] always exist if exist MangosStringLocale
7160 if(MangosStringLocale const *msl = GetMangosStringLocale(entry))
7162 if(msl->Content.size() > locale_idx+1 && !msl->Content[locale_idx+1].empty())
7163 return msl->Content[locale_idx+1].c_str();
7164 else
7165 return msl->Content[0].c_str();
7168 if(entry > 0)
7169 sLog.outErrorDb("Entry %i not found in `mangos_string` table.",entry);
7170 else
7171 sLog.outErrorDb("Mangos string entry %i not found in DB.",entry);
7172 return "<error>";
7175 void ObjectMgr::LoadFishingBaseSkillLevel()
7177 mFishingBaseForArea.clear(); // for reload case
7179 uint32 count = 0;
7180 QueryResult *result = WorldDatabase.Query("SELECT entry,skill FROM skill_fishing_base_level");
7182 if( !result )
7184 barGoLink bar( 1 );
7186 bar.step();
7188 sLog.outString();
7189 sLog.outErrorDb(">> Loaded `skill_fishing_base_level`, table is empty!");
7190 return;
7193 barGoLink bar( result->GetRowCount() );
7197 bar.step();
7199 Field *fields = result->Fetch();
7200 uint32 entry = fields[0].GetUInt32();
7201 int32 skill = fields[1].GetInt32();
7203 AreaTableEntry const* fArea = GetAreaEntryByAreaID(entry);
7204 if(!fArea)
7206 sLog.outErrorDb("AreaId %u defined in `skill_fishing_base_level` does not exist",entry);
7207 continue;
7210 mFishingBaseForArea[entry] = skill;
7211 ++count;
7213 while (result->NextRow());
7215 delete result;
7217 sLog.outString();
7218 sLog.outString( ">> Loaded %u areas for fishing base skill level", count );
7221 // Searches for the same condition already in Conditions store
7222 // Returns Id if found, else adds it to Conditions and returns Id
7223 uint16 ObjectMgr::GetConditionId( ConditionType condition, uint32 value1, uint32 value2 )
7225 PlayerCondition lc = PlayerCondition(condition, value1, value2);
7226 for (uint16 i=0; i < mConditions.size(); ++i)
7228 if (lc == mConditions[i])
7229 return i;
7232 mConditions.push_back(lc);
7234 if(mConditions.size() > 0xFFFF)
7236 sLog.outError("Conditions store overflow! Current and later loaded conditions will ignored!");
7237 return 0;
7240 return mConditions.size() - 1;
7243 bool ObjectMgr::CheckDeclinedNames( std::wstring mainpart, DeclinedName const& names )
7245 for(int i =0; i < MAX_DECLINED_NAME_CASES; ++i)
7247 std::wstring wname;
7248 if(!Utf8toWStr(names.name[i],wname))
7249 return false;
7251 if(mainpart!=GetMainPartOfName(wname,i+1))
7252 return false;
7254 return true;
7257 uint32 ObjectMgr::GetAreaTriggerScriptId(uint32 trigger_id)
7259 AreaTriggerScriptMap::const_iterator i = mAreaTriggerScripts.find(trigger_id);
7260 if(i!= mAreaTriggerScripts.end())
7261 return i->second;
7262 return 0;
7265 // Checks if player meets the condition
7266 bool PlayerCondition::Meets(Player const * player) const
7268 if( !player )
7269 return false; // player not present, return false
7271 switch (condition)
7273 case CONDITION_NONE:
7274 return true; // empty condition, always met
7275 case CONDITION_AURA:
7276 return player->HasAura(value1, value2);
7277 case CONDITION_ITEM:
7278 return player->HasItemCount(value1, value2);
7279 case CONDITION_ITEM_EQUIPPED:
7280 return player->HasItemOrGemWithIdEquipped(value1,1);
7281 case CONDITION_ZONEID:
7282 return player->GetZoneId() == value1;
7283 case CONDITION_REPUTATION_RANK:
7285 FactionEntry const* faction = sFactionStore.LookupEntry(value1);
7286 return faction && player->GetReputationMgr().GetRank(faction) >= int32(value2);
7288 case CONDITION_TEAM:
7289 return player->GetTeam() == value1;
7290 case CONDITION_SKILL:
7291 return player->HasSkill(value1) && player->GetBaseSkillValue(value1) >= value2;
7292 case CONDITION_QUESTREWARDED:
7293 return player->GetQuestRewardStatus(value1);
7294 case CONDITION_QUESTTAKEN:
7296 QuestStatus status = player->GetQuestStatus(value1);
7297 return (status == QUEST_STATUS_INCOMPLETE);
7299 case CONDITION_AD_COMMISSION_AURA:
7301 Unit::AuraMap const& auras = player->GetAuras();
7302 for(Unit::AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
7303 if((itr->second->GetSpellProto()->Attributes & 0x1000010) && itr->second->GetSpellProto()->SpellVisual[0]==3580)
7304 return true;
7305 return false;
7307 case CONDITION_NO_AURA:
7308 return !player->HasAura(value1, value2);
7309 case CONDITION_ACTIVE_EVENT:
7310 return sGameEventMgr.IsActiveEvent(value1);
7311 case CONDITION_AREA_FLAG:
7313 if (AreaTableEntry const *pAreaEntry = GetAreaEntryByAreaID(player->GetAreaId()))
7315 if ((!value1 || (pAreaEntry->flags & value1)) && (!value2 || !(pAreaEntry->flags & value2)))
7316 return true;
7318 return false;
7320 case CONDITION_RACE_CLASS:
7321 if ((!value1 || (player->getRaceMask() & value1)) && (!value2 || (player->getClassMask() & value2)))
7322 return true;
7323 return false;
7324 case CONDITION_LEVEL:
7326 switch(value2)
7328 case 0: return player->getLevel() == value1;
7329 case 1: return player->getLevel() >= value1;
7330 case 2: return player->getLevel() <= value1;
7332 return false;
7334 default:
7335 return false;
7339 // Verification of condition values validity
7340 bool PlayerCondition::IsValid(ConditionType condition, uint32 value1, uint32 value2)
7342 if( condition >= MAX_CONDITION) // Wrong condition type
7344 sLog.outErrorDb("Condition has bad type of %u, skipped ", condition );
7345 return false;
7348 switch (condition)
7350 case CONDITION_AURA:
7352 if(!sSpellStore.LookupEntry(value1))
7354 sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
7355 return false;
7357 if(value2 > 2)
7359 sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..2), skipped", value2);
7360 return false;
7362 break;
7364 case CONDITION_ITEM:
7366 ItemPrototype const *proto = ObjectMgr::GetItemPrototype(value1);
7367 if(!proto)
7369 sLog.outErrorDb("Item condition requires to have non existing item (%u), skipped", value1);
7370 return false;
7372 break;
7374 case CONDITION_ITEM_EQUIPPED:
7376 ItemPrototype const *proto = ObjectMgr::GetItemPrototype(value1);
7377 if(!proto)
7379 sLog.outErrorDb("ItemEquipped condition requires to have non existing item (%u) equipped, skipped", value1);
7380 return false;
7382 break;
7384 case CONDITION_ZONEID:
7386 AreaTableEntry const* areaEntry = GetAreaEntryByAreaID(value1);
7387 if(!areaEntry)
7389 sLog.outErrorDb("Zone condition requires to be in non existing area (%u), skipped", value1);
7390 return false;
7392 if(areaEntry->zone != 0)
7394 sLog.outErrorDb("Zone condition requires to be in area (%u) which is a subzone but zone expected, skipped", value1);
7395 return false;
7397 break;
7399 case CONDITION_REPUTATION_RANK:
7401 FactionEntry const* factionEntry = sFactionStore.LookupEntry(value1);
7402 if(!factionEntry)
7404 sLog.outErrorDb("Reputation condition requires to have reputation non existing faction (%u), skipped", value1);
7405 return false;
7407 break;
7409 case CONDITION_TEAM:
7411 if (value1 != ALLIANCE && value1 != HORDE)
7413 sLog.outErrorDb("Team condition specifies unknown team (%u), skipped", value1);
7414 return false;
7416 break;
7418 case CONDITION_SKILL:
7420 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(value1);
7421 if (!pSkill)
7423 sLog.outErrorDb("Skill condition specifies non-existing skill (%u), skipped", value1);
7424 return false;
7426 if (value2 < 1 || value2 > sWorld.GetConfigMaxSkillValue() )
7428 sLog.outErrorDb("Skill condition specifies invalid skill value (%u), skipped", value2);
7429 return false;
7431 break;
7433 case CONDITION_QUESTREWARDED:
7434 case CONDITION_QUESTTAKEN:
7436 Quest const *Quest = sObjectMgr.GetQuestTemplate(value1);
7437 if (!Quest)
7439 sLog.outErrorDb("Quest condition specifies non-existing quest (%u), skipped", value1);
7440 return false;
7442 if(value2)
7443 sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
7444 break;
7446 case CONDITION_AD_COMMISSION_AURA:
7448 if(value1)
7449 sLog.outErrorDb("Quest condition has useless data in value1 (%u)!", value1);
7450 if(value2)
7451 sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
7452 break;
7454 case CONDITION_NO_AURA:
7456 if(!sSpellStore.LookupEntry(value1))
7458 sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
7459 return false;
7461 if(value2 > 2)
7463 sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..2), skipped", value2);
7464 return false;
7466 break;
7468 case CONDITION_ACTIVE_EVENT:
7470 GameEventMgr::GameEventDataMap const& events = sGameEventMgr.GetEventMap();
7471 if(value1 >=events.size() || !events[value1].isValid())
7473 sLog.outErrorDb("Active event condition requires existed event id (%u), skipped", value1);
7474 return false;
7476 break;
7478 case CONDITION_AREA_FLAG:
7480 if (!value1 && !value2)
7482 sLog.outErrorDb("Area flag condition has both values like 0, skipped");
7483 return false;
7485 break;
7487 case CONDITION_RACE_CLASS:
7489 if (!value1 && !value2)
7491 sLog.outErrorDb("Race_class condition has both values like 0, skipped");
7492 return false;
7495 if (value1 && !(value1 & RACEMASK_ALL_PLAYABLE))
7497 sLog.outErrorDb("Race_class condition has invalid player class %u, skipped", value1);
7498 return false;
7501 if (value2 && !(value2 & CLASSMASK_ALL_PLAYABLE))
7503 sLog.outErrorDb("Race_class condition has invalid race mask %u, skipped", value2);
7504 return false;
7506 break;
7508 case CONDITION_LEVEL:
7510 if (!value1 || value1 > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
7512 sLog.outErrorDb("Level condition has invalid level %u, skipped", value1);
7513 return false;
7516 if (value2 > 2)
7518 sLog.outErrorDb("Level condition has invalid argument %u (must be 0..2), skipped", value2);
7519 return false;
7522 break;
7524 case CONDITION_NONE:
7525 break;
7527 return true;
7530 SkillRangeType GetSkillRangeType(SkillLineEntry const *pSkill, bool racial)
7532 switch(pSkill->categoryId)
7534 case SKILL_CATEGORY_LANGUAGES: return SKILL_RANGE_LANGUAGE;
7535 case SKILL_CATEGORY_WEAPON:
7536 if(pSkill->id!=SKILL_FIST_WEAPONS)
7537 return SKILL_RANGE_LEVEL;
7538 else
7539 return SKILL_RANGE_MONO;
7540 case SKILL_CATEGORY_ARMOR:
7541 case SKILL_CATEGORY_CLASS:
7542 if(pSkill->id != SKILL_LOCKPICKING)
7543 return SKILL_RANGE_MONO;
7544 else
7545 return SKILL_RANGE_LEVEL;
7546 case SKILL_CATEGORY_SECONDARY:
7547 case SKILL_CATEGORY_PROFESSION:
7548 // not set skills for professions and racial abilities
7549 if(IsProfessionSkill(pSkill->id))
7550 return SKILL_RANGE_RANK;
7551 else if(racial)
7552 return SKILL_RANGE_NONE;
7553 else
7554 return SKILL_RANGE_MONO;
7555 default:
7556 case SKILL_CATEGORY_ATTRIBUTES: //not found in dbc
7557 case SKILL_CATEGORY_GENERIC: //only GENERIC(DND)
7558 return SKILL_RANGE_NONE;
7562 void ObjectMgr::LoadGameTele()
7564 m_GameTeleMap.clear(); // for reload case
7566 uint32 count = 0;
7567 QueryResult *result = WorldDatabase.Query("SELECT id, position_x, position_y, position_z, orientation, map, name FROM game_tele");
7569 if( !result )
7571 barGoLink bar( 1 );
7573 bar.step();
7575 sLog.outString();
7576 sLog.outErrorDb(">> Loaded `game_tele`, table is empty!");
7577 return;
7580 barGoLink bar( result->GetRowCount() );
7584 bar.step();
7586 Field *fields = result->Fetch();
7588 uint32 id = fields[0].GetUInt32();
7590 GameTele gt;
7592 gt.position_x = fields[1].GetFloat();
7593 gt.position_y = fields[2].GetFloat();
7594 gt.position_z = fields[3].GetFloat();
7595 gt.orientation = fields[4].GetFloat();
7596 gt.mapId = fields[5].GetUInt32();
7597 gt.name = fields[6].GetCppString();
7599 if(!MapManager::IsValidMapCoord(gt.mapId,gt.position_x,gt.position_y,gt.position_z,gt.orientation))
7601 sLog.outErrorDb("Wrong position for id %u (name: %s) in `game_tele` table, ignoring.",id,gt.name.c_str());
7602 continue;
7605 if(!Utf8toWStr(gt.name,gt.wnameLow))
7607 sLog.outErrorDb("Wrong UTF8 name for id %u in `game_tele` table, ignoring.",id);
7608 continue;
7611 wstrToLower( gt.wnameLow );
7613 m_GameTeleMap[id] = gt;
7615 ++count;
7617 while (result->NextRow());
7618 delete result;
7620 sLog.outString();
7621 sLog.outString( ">> Loaded %u GameTeleports", count );
7624 GameTele const* ObjectMgr::GetGameTele(const std::string& name) const
7626 // explicit name case
7627 std::wstring wname;
7628 if(!Utf8toWStr(name,wname))
7629 return false;
7631 // converting string that we try to find to lower case
7632 wstrToLower( wname );
7634 // Alternative first GameTele what contains wnameLow as substring in case no GameTele location found
7635 const GameTele* alt = NULL;
7636 for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
7637 if(itr->second.wnameLow == wname)
7638 return &itr->second;
7639 else if (alt == NULL && itr->second.wnameLow.find(wname) != std::wstring::npos)
7640 alt = &itr->second;
7642 return alt;
7645 bool ObjectMgr::AddGameTele(GameTele& tele)
7647 // find max id
7648 uint32 new_id = 0;
7649 for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
7650 if(itr->first > new_id)
7651 new_id = itr->first;
7653 // use next
7654 ++new_id;
7656 if(!Utf8toWStr(tele.name,tele.wnameLow))
7657 return false;
7659 wstrToLower( tele.wnameLow );
7661 m_GameTeleMap[new_id] = tele;
7663 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')",
7664 new_id,tele.position_x,tele.position_y,tele.position_z,tele.orientation,tele.mapId,tele.name.c_str());
7667 bool ObjectMgr::DeleteGameTele(const std::string& name)
7669 // explicit name case
7670 std::wstring wname;
7671 if(!Utf8toWStr(name,wname))
7672 return false;
7674 // converting string that we try to find to lower case
7675 wstrToLower( wname );
7677 for(GameTeleMap::iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
7679 if(itr->second.wnameLow == wname)
7681 WorldDatabase.PExecuteLog("DELETE FROM game_tele WHERE name = '%s'",itr->second.name.c_str());
7682 m_GameTeleMap.erase(itr);
7683 return true;
7687 return false;
7690 void ObjectMgr::LoadMailLevelRewards()
7692 m_mailLevelRewardMap.clear(); // for reload case
7694 uint32 count = 0;
7695 QueryResult *result = WorldDatabase.Query("SELECT level, raceMask, mailTemplateId, senderEntry FROM mail_level_reward");
7697 if( !result )
7699 barGoLink bar( 1 );
7701 bar.step();
7703 sLog.outString();
7704 sLog.outErrorDb(">> Loaded `mail_level_reward`, table is empty!");
7705 return;
7708 barGoLink bar( result->GetRowCount() );
7712 bar.step();
7714 Field *fields = result->Fetch();
7716 uint8 level = fields[0].GetUInt8();
7717 uint32 raceMask = fields[1].GetUInt32();
7718 uint32 mailTemplateId = fields[2].GetUInt32();
7719 uint32 senderEntry = fields[3].GetUInt32();
7721 if(level > MAX_LEVEL)
7723 sLog.outErrorDb("Table `mail_level_reward` have data for level %u that more supported by client (%u), ignoring.",level,MAX_LEVEL);
7724 continue;
7727 if(!(raceMask & RACEMASK_ALL_PLAYABLE))
7729 sLog.outErrorDb("Table `mail_level_reward` have raceMask (%u) for level %u that not include any player races, ignoring.",raceMask,level);
7730 continue;
7733 if(!sMailTemplateStore.LookupEntry(mailTemplateId))
7735 sLog.outErrorDb("Table `mail_level_reward` have invalid mailTemplateId (%u) for level %u that invalid not include any player races, ignoring.",mailTemplateId,level);
7736 continue;
7739 if(!GetCreatureTemplateStore(senderEntry))
7741 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);
7742 continue;
7745 m_mailLevelRewardMap[level].push_back(MailLevelReward(raceMask,mailTemplateId,senderEntry));
7747 ++count;
7749 while (result->NextRow());
7750 delete result;
7752 sLog.outString();
7753 sLog.outString( ">> Loaded %u level dependent mail rewards,", count );
7756 void ObjectMgr::LoadTrainerSpell()
7758 // For reload case
7759 for (CacheTrainerSpellMap::iterator itr = m_mCacheTrainerSpellMap.begin(); itr != m_mCacheTrainerSpellMap.end(); ++itr)
7760 itr->second.Clear();
7761 m_mCacheTrainerSpellMap.clear();
7763 std::set<uint32> skip_trainers;
7765 QueryResult *result = WorldDatabase.Query("SELECT entry, spell,spellcost,reqskill,reqskillvalue,reqlevel FROM npc_trainer");
7767 if( !result )
7769 barGoLink bar( 1 );
7771 bar.step();
7773 sLog.outString();
7774 sLog.outErrorDb(">> Loaded `npc_trainer`, table is empty!");
7775 return;
7778 barGoLink bar( result->GetRowCount() );
7780 std::set<uint32> talentIds;
7782 uint32 count = 0;
7785 bar.step();
7787 Field* fields = result->Fetch();
7789 uint32 entry = fields[0].GetUInt32();
7790 uint32 spell = fields[1].GetUInt32();
7792 CreatureInfo const* cInfo = GetCreatureTemplate(entry);
7794 if(!cInfo)
7796 sLog.outErrorDb("Table `npc_trainer` have entry for not existed creature template (Entry: %u), ignore", entry);
7797 continue;
7800 if(!(cInfo->npcflag & UNIT_NPC_FLAG_TRAINER))
7802 if(skip_trainers.count(entry) == 0)
7804 sLog.outErrorDb("Table `npc_trainer` have data for not creature template (Entry: %u) without trainer flag, ignore", entry);
7805 skip_trainers.insert(entry);
7807 continue;
7810 SpellEntry const *spellinfo = sSpellStore.LookupEntry(spell);
7811 if(!spellinfo)
7813 sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u ) has non existing spell %u, ignore", entry,spell);
7814 continue;
7817 if(!SpellMgr::IsSpellValid(spellinfo))
7819 sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u) has broken learning spell %u, ignore", entry, spell);
7820 continue;
7823 if(GetTalentSpellCost(spell))
7825 if(talentIds.count(spell)==0)
7827 sLog.outErrorDb("Table `npc_trainer` has talent as learning spell %u, ignore", spell);
7828 talentIds.insert(spell);
7830 continue;
7833 TrainerSpellData& data = m_mCacheTrainerSpellMap[entry];
7835 TrainerSpell& trainerSpell = data.spellList[spell];
7836 trainerSpell.spell = spell;
7837 trainerSpell.spellCost = fields[2].GetUInt32();
7838 trainerSpell.reqSkill = fields[3].GetUInt32();
7839 trainerSpell.reqSkillValue = fields[4].GetUInt32();
7840 trainerSpell.reqLevel = fields[5].GetUInt32();
7842 if(!trainerSpell.reqLevel)
7843 trainerSpell.reqLevel = spellinfo->spellLevel;
7845 // calculate learned spell for profession case when stored cast-spell
7846 trainerSpell.learnedSpell = spell;
7847 for(int i = 0; i <3; ++i)
7849 if(spellinfo->Effect[i] != SPELL_EFFECT_LEARN_SPELL)
7850 continue;
7851 if(SpellMgr::IsProfessionOrRidingSpell(spellinfo->EffectTriggerSpell[i]))
7853 trainerSpell.learnedSpell = spellinfo->EffectTriggerSpell[i];
7854 break;
7858 if(SpellMgr::IsProfessionSpell(trainerSpell.learnedSpell))
7859 data.trainerType = 2;
7861 ++count;
7863 } while (result->NextRow());
7864 delete result;
7866 sLog.outString();
7867 sLog.outString( ">> Loaded %d Trainers", count );
7870 void ObjectMgr::LoadVendors()
7872 // For reload case
7873 for (CacheVendorItemMap::iterator itr = m_mCacheVendorItemMap.begin(); itr != m_mCacheVendorItemMap.end(); ++itr)
7874 itr->second.Clear();
7875 m_mCacheVendorItemMap.clear();
7877 std::set<uint32> skip_vendors;
7879 QueryResult *result = WorldDatabase.Query("SELECT entry, item, maxcount, incrtime, ExtendedCost FROM npc_vendor");
7880 if( !result )
7882 barGoLink bar( 1 );
7884 bar.step();
7886 sLog.outString();
7887 sLog.outErrorDb(">> Loaded `npc_vendor`, table is empty!");
7888 return;
7891 barGoLink bar( result->GetRowCount() );
7893 uint32 count = 0;
7896 bar.step();
7897 Field* fields = result->Fetch();
7899 uint32 entry = fields[0].GetUInt32();
7900 uint32 item_id = fields[1].GetUInt32();
7901 uint32 maxcount = fields[2].GetUInt32();
7902 uint32 incrtime = fields[3].GetUInt32();
7903 uint32 ExtendedCost = fields[4].GetUInt32();
7905 if(!IsVendorItemValid(entry,item_id,maxcount,incrtime,ExtendedCost,NULL,&skip_vendors))
7906 continue;
7908 VendorItemData& vList = m_mCacheVendorItemMap[entry];
7910 vList.AddItem(item_id,maxcount,incrtime,ExtendedCost);
7911 ++count;
7913 } while (result->NextRow());
7914 delete result;
7916 sLog.outString();
7917 sLog.outString( ">> Loaded %d Vendors ", count );
7920 void ObjectMgr::LoadNpcTextId()
7923 m_mCacheNpcTextIdMap.clear();
7925 QueryResult* result = WorldDatabase.Query("SELECT npc_guid, textid FROM npc_gossip");
7926 if( !result )
7928 barGoLink bar( 1 );
7930 bar.step();
7932 sLog.outString();
7933 sLog.outErrorDb(">> Loaded `npc_gossip`, table is empty!");
7934 return;
7937 barGoLink bar( result->GetRowCount() );
7939 uint32 count = 0;
7940 uint32 guid,textid;
7943 bar.step();
7945 Field* fields = result->Fetch();
7947 guid = fields[0].GetUInt32();
7948 textid = fields[1].GetUInt32();
7950 if (!GetCreatureData(guid))
7952 sLog.outErrorDb("Table `npc_gossip` have not existed creature (GUID: %u) entry, ignore. ",guid);
7953 continue;
7955 if (!GetGossipText(textid))
7957 sLog.outErrorDb("Table `npc_gossip` for creature (GUID: %u) have wrong Textid (%u), ignore. ", guid, textid);
7958 continue;
7961 m_mCacheNpcTextIdMap[guid] = textid ;
7962 ++count;
7964 } while (result->NextRow());
7965 delete result;
7967 sLog.outString();
7968 sLog.outString( ">> Loaded %d NpcTextId ", count );
7971 void ObjectMgr::LoadGossipMenu()
7973 m_mGossipMenusMap.clear();
7975 QueryResult* result = WorldDatabase.Query("SELECT entry, text_id, "
7976 "cond_1, cond_1_val_1, cond_1_val_2, cond_2, cond_2_val_1, cond_2_val_2 FROM gossip_menu");
7978 if (!result)
7980 barGoLink bar(1);
7982 bar.step();
7984 sLog.outString();
7985 sLog.outErrorDb(">> Loaded gossip_menu, table is empty!");
7986 return;
7989 barGoLink bar( result->GetRowCount() );
7991 uint32 count = 0;
7995 bar.step();
7997 Field* fields = result->Fetch();
7999 GossipMenus gMenu;
8001 gMenu.entry = fields[0].GetUInt32();
8002 gMenu.text_id = fields[1].GetUInt32();
8004 ConditionType cond_1 = (ConditionType)fields[2].GetUInt32();
8005 uint32 cond_1_val_1 = fields[3].GetUInt32();
8006 uint32 cond_1_val_2 = fields[4].GetUInt32();
8007 ConditionType cond_2 = (ConditionType)fields[5].GetUInt32();
8008 uint32 cond_2_val_1 = fields[6].GetUInt32();
8009 uint32 cond_2_val_2 = fields[7].GetUInt32();
8011 if (!GetGossipText(gMenu.text_id))
8013 sLog.outErrorDb("Table gossip_menu entry %u are using non-existing text_id %u", gMenu.entry, gMenu.text_id);
8014 continue;
8017 if (!PlayerCondition::IsValid(cond_1, cond_1_val_1, cond_1_val_2))
8019 sLog.outErrorDb("Table gossip_menu entry %u, invalid condition 1 for id %u", gMenu.entry, gMenu.text_id);
8020 continue;
8023 if (!PlayerCondition::IsValid(cond_2, cond_2_val_1, cond_2_val_2))
8025 sLog.outErrorDb("Table gossip_menu entry %u, invalid condition 2 for id %u", gMenu.entry, gMenu.text_id);
8026 continue;
8029 gMenu.cond_1 = GetConditionId(cond_1, cond_1_val_1, cond_1_val_2);
8030 gMenu.cond_2 = GetConditionId(cond_2, cond_2_val_1, cond_2_val_2);
8032 m_mGossipMenusMap.insert(GossipMenusMap::value_type(gMenu.entry, gMenu));
8034 ++count;
8036 while(result->NextRow());
8038 delete result;
8040 sLog.outString();
8041 sLog.outString( ">> Loaded %u gossip_menu entries", count);
8044 void ObjectMgr::LoadGossipMenuItems()
8046 m_mGossipMenuItemsMap.clear();
8048 QueryResult *result = WorldDatabase.Query(
8049 "SELECT menu_id, id, option_icon, option_text, option_id, npc_option_npcflag, "
8050 "action_menu_id, action_poi_id, action_script_id, box_coded, box_money, box_text, "
8051 "cond_1, cond_1_val_1, cond_1_val_2, "
8052 "cond_2, cond_2_val_1, cond_2_val_2, "
8053 "cond_3, cond_3_val_1, cond_3_val_2 "
8054 "FROM gossip_menu_option");
8056 if (!result)
8058 barGoLink bar(1);
8060 bar.step();
8062 sLog.outString();
8063 sLog.outErrorDb(">> Loaded gossip_menu_option, table is empty!");
8064 return;
8067 barGoLink bar(result->GetRowCount());
8069 uint32 count = 0;
8071 std::set<uint32> gossipScriptSet;
8073 for(ScriptMapMap::const_iterator itr = sGossipScripts.begin(); itr != sGossipScripts.end(); ++itr)
8074 gossipScriptSet.insert(itr->first);
8078 bar.step();
8080 Field* fields = result->Fetch();
8082 GossipMenuItems gMenuItem;
8084 gMenuItem.menu_id = fields[0].GetUInt32();
8085 gMenuItem.id = fields[1].GetUInt32();
8086 gMenuItem.option_icon = fields[2].GetUInt8();
8087 gMenuItem.option_text = fields[3].GetCppString();
8088 gMenuItem.option_id = fields[4].GetUInt32();
8089 gMenuItem.npc_option_npcflag = fields[5].GetUInt32();
8090 gMenuItem.action_menu_id = fields[6].GetUInt32();
8091 gMenuItem.action_poi_id = fields[7].GetUInt32();
8092 gMenuItem.action_script_id = fields[8].GetUInt32();
8093 gMenuItem.box_coded = fields[9].GetUInt8() != 0;
8094 gMenuItem.box_money = fields[10].GetUInt32();
8095 gMenuItem.box_text = fields[11].GetCppString();
8097 ConditionType cond_1 = (ConditionType)fields[12].GetUInt32();
8098 uint32 cond_1_val_1 = fields[13].GetUInt32();
8099 uint32 cond_1_val_2 = fields[14].GetUInt32();
8100 ConditionType cond_2 = (ConditionType)fields[15].GetUInt32();
8101 uint32 cond_2_val_1 = fields[16].GetUInt32();
8102 uint32 cond_2_val_2 = fields[17].GetUInt32();
8103 ConditionType cond_3 = (ConditionType)fields[18].GetUInt32();
8104 uint32 cond_3_val_1 = fields[19].GetUInt32();
8105 uint32 cond_3_val_2 = fields[20].GetUInt32();
8107 if (!PlayerCondition::IsValid(cond_1, cond_1_val_1, cond_1_val_2))
8109 sLog.outErrorDb("Table gossip_menu_option menu %u, invalid condition 1 for id %u", gMenuItem.menu_id, gMenuItem.id);
8110 continue;
8112 if (!PlayerCondition::IsValid(cond_2, cond_2_val_1, cond_2_val_2))
8114 sLog.outErrorDb("Table gossip_menu_option menu %u, invalid condition 2 for id %u", gMenuItem.menu_id, gMenuItem.id);
8115 continue;
8117 if (!PlayerCondition::IsValid(cond_3, cond_3_val_1, cond_3_val_2))
8119 sLog.outErrorDb("Table gossip_menu_option menu %u, invalid condition 3 for id %u", gMenuItem.menu_id, gMenuItem.id);
8120 continue;
8123 if (gMenuItem.option_icon >= GOSSIP_ICON_MAX)
8125 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);
8126 gMenuItem.option_icon = GOSSIP_ICON_CHAT;
8129 if (gMenuItem.option_id == GOSSIP_OPTION_NONE)
8130 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);
8132 if (gMenuItem.option_id >= GOSSIP_OPTION_MAX)
8133 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);
8135 if (gMenuItem.action_poi_id && !GetPointOfInterest(gMenuItem.action_poi_id))
8137 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);
8138 gMenuItem.action_poi_id = 0;
8141 if (gMenuItem.action_script_id)
8143 if (gMenuItem.option_id != GOSSIP_OPTION_GOSSIP)
8145 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);
8146 continue;
8149 if (sGossipScripts.find(gMenuItem.action_script_id) == sGossipScripts.end())
8151 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);
8152 continue;
8155 gossipScriptSet.erase(gMenuItem.action_script_id);
8158 gMenuItem.cond_1 = GetConditionId(cond_1, cond_1_val_1, cond_1_val_2);
8159 gMenuItem.cond_2 = GetConditionId(cond_2, cond_2_val_1, cond_2_val_2);
8160 gMenuItem.cond_3 = GetConditionId(cond_3, cond_3_val_1, cond_3_val_2);
8162 m_mGossipMenuItemsMap.insert(GossipMenuItemsMap::value_type(gMenuItem.menu_id, gMenuItem));
8164 ++count;
8167 while(result->NextRow());
8169 delete result;
8171 if (!gossipScriptSet.empty())
8173 for(std::set<uint32>::const_iterator itr = gossipScriptSet.begin(); itr != gossipScriptSet.end(); ++itr)
8174 sLog.outErrorDb("Table `gossip_scripts` contain unused script, id %u.", *itr);
8177 sLog.outString();
8178 sLog.outString(">> Loaded %u gossip_menu_option entries", count);
8181 void ObjectMgr::AddVendorItem( uint32 entry,uint32 item, uint32 maxcount, uint32 incrtime, uint32 extendedcost )
8183 VendorItemData& vList = m_mCacheVendorItemMap[entry];
8184 vList.AddItem(item,maxcount,incrtime,extendedcost);
8186 WorldDatabase.PExecuteLog("INSERT INTO npc_vendor (entry,item,maxcount,incrtime,extendedcost) VALUES('%u','%u','%u','%u','%u')",entry, item, maxcount,incrtime,extendedcost);
8189 bool ObjectMgr::RemoveVendorItem( uint32 entry,uint32 item )
8191 CacheVendorItemMap::iterator iter = m_mCacheVendorItemMap.find(entry);
8192 if(iter == m_mCacheVendorItemMap.end())
8193 return false;
8195 if(!iter->second.FindItem(item))
8196 return false;
8198 iter->second.RemoveItem(item);
8199 WorldDatabase.PExecuteLog("DELETE FROM npc_vendor WHERE entry='%u' AND item='%u'",entry, item);
8200 return true;
8203 bool ObjectMgr::IsVendorItemValid( uint32 vendor_entry, uint32 item_id, uint32 maxcount, uint32 incrtime, uint32 ExtendedCost, Player* pl, std::set<uint32>* skip_vendors ) const
8205 CreatureInfo const* cInfo = GetCreatureTemplate(vendor_entry);
8206 if(!cInfo)
8208 if(pl)
8209 ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
8210 else
8211 sLog.outErrorDb("Table `npc_vendor` have data for not existed creature template (Entry: %u), ignore", vendor_entry);
8212 return false;
8215 if(!(cInfo->npcflag & UNIT_NPC_FLAG_VENDOR))
8217 if(!skip_vendors || skip_vendors->count(vendor_entry)==0)
8219 if(pl)
8220 ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
8221 else
8222 sLog.outErrorDb("Table `npc_vendor` have data for not creature template (Entry: %u) without vendor flag, ignore", vendor_entry);
8224 if(skip_vendors)
8225 skip_vendors->insert(vendor_entry);
8227 return false;
8230 if(!GetItemPrototype(item_id))
8232 if(pl)
8233 ChatHandler(pl).PSendSysMessage(LANG_ITEM_NOT_FOUND, item_id);
8234 else
8235 sLog.outErrorDb("Table `npc_vendor` for Vendor (Entry: %u) have in item list non-existed item (%u), ignore",vendor_entry,item_id);
8236 return false;
8239 if(ExtendedCost && !sItemExtendedCostStore.LookupEntry(ExtendedCost))
8241 if(pl)
8242 ChatHandler(pl).PSendSysMessage(LANG_EXTENDED_COST_NOT_EXIST,ExtendedCost);
8243 else
8244 sLog.outErrorDb("Table `npc_vendor` have Item (Entry: %u) with wrong ExtendedCost (%u) for vendor (%u), ignore",item_id,ExtendedCost,vendor_entry);
8245 return false;
8248 if(maxcount > 0 && incrtime == 0)
8250 if(pl)
8251 ChatHandler(pl).PSendSysMessage("MaxCount!=0 (%u) but IncrTime==0", maxcount);
8252 else
8253 sLog.outErrorDb( "Table `npc_vendor` has `maxcount` (%u) for item %u of vendor (Entry: %u) but `incrtime`=0, ignore", maxcount, item_id, vendor_entry);
8254 return false;
8256 else if(maxcount==0 && incrtime > 0)
8258 if(pl)
8259 ChatHandler(pl).PSendSysMessage("MaxCount==0 but IncrTime<>=0");
8260 else
8261 sLog.outErrorDb( "Table `npc_vendor` has `maxcount`=0 for item %u of vendor (Entry: %u) but `incrtime`<>0, ignore", item_id, vendor_entry);
8262 return false;
8265 VendorItemData const* vItems = GetNpcVendorItemList(vendor_entry);
8266 if(!vItems)
8267 return true; // later checks for non-empty lists
8269 if(vItems->FindItem(item_id))
8271 if(pl)
8272 ChatHandler(pl).PSendSysMessage(LANG_ITEM_ALREADY_IN_LIST,item_id);
8273 else
8274 sLog.outErrorDb( "Table `npc_vendor` has duplicate items %u for vendor (Entry: %u), ignore", item_id, vendor_entry);
8275 return false;
8278 if(vItems->GetItemCount() >= MAX_VENDOR_ITEMS)
8280 if(pl)
8281 ChatHandler(pl).SendSysMessage(LANG_COMMAND_ADDVENDORITEMITEMS);
8282 else
8283 sLog.outErrorDb( "Table `npc_vendor` has too many items (%u >= %i) for vendor (Entry: %u), ignore", vItems->GetItemCount(), MAX_VENDOR_ITEMS, vendor_entry);
8284 return false;
8287 return true;
8290 void ObjectMgr::LoadScriptNames()
8292 m_scriptNames.push_back("");
8293 QueryResult *result = WorldDatabase.Query(
8294 "SELECT DISTINCT(ScriptName) FROM creature_template WHERE ScriptName <> '' "
8295 "UNION "
8296 "SELECT DISTINCT(ScriptName) FROM gameobject_template WHERE ScriptName <> '' "
8297 "UNION "
8298 "SELECT DISTINCT(ScriptName) FROM item_template WHERE ScriptName <> '' "
8299 "UNION "
8300 "SELECT DISTINCT(ScriptName) FROM areatrigger_scripts WHERE ScriptName <> '' "
8301 "UNION "
8302 "SELECT DISTINCT(script) FROM instance_template WHERE script <> ''");
8304 if( !result )
8306 barGoLink bar( 1 );
8307 bar.step();
8308 sLog.outString();
8309 sLog.outErrorDb(">> Loaded empty set of Script Names!");
8310 return;
8313 barGoLink bar( result->GetRowCount() );
8314 uint32 count = 0;
8318 bar.step();
8319 m_scriptNames.push_back((*result)[0].GetString());
8320 ++count;
8321 } while (result->NextRow());
8322 delete result;
8324 std::sort(m_scriptNames.begin(), m_scriptNames.end());
8325 sLog.outString();
8326 sLog.outString( ">> Loaded %d Script Names", count );
8329 uint32 ObjectMgr::GetScriptId(const char *name)
8331 // use binary search to find the script name in the sorted vector
8332 // assume "" is the first element
8333 if(!name) return 0;
8334 ScriptNameMap::const_iterator itr =
8335 std::lower_bound(m_scriptNames.begin(), m_scriptNames.end(), name);
8336 if(itr == m_scriptNames.end() || *itr != name) return 0;
8337 return itr - m_scriptNames.begin();
8340 void ObjectMgr::CheckScripts(ScriptMapMap const& scripts,std::set<int32>& ids)
8342 for(ScriptMapMap::const_iterator itrMM = scripts.begin(); itrMM != scripts.end(); ++itrMM)
8344 for(ScriptMap::const_iterator itrM = itrMM->second.begin(); itrM != itrMM->second.end(); ++itrM)
8346 switch(itrM->second.command)
8348 case SCRIPT_COMMAND_TALK:
8350 if(!GetMangosStringLocale (itrM->second.dataint))
8351 sLog.outErrorDb( "Table `db_script_string` is missing string id %u, used in database script id %u.", itrM->second.dataint, itrMM->first);
8353 if(ids.count(itrM->second.dataint))
8354 ids.erase(itrM->second.dataint);
8361 void ObjectMgr::LoadDbScriptStrings()
8363 LoadMangosStrings(WorldDatabase,"db_script_string",MIN_DB_SCRIPT_STRING_ID,MAX_DB_SCRIPT_STRING_ID);
8365 std::set<int32> ids;
8367 for(int32 i = MIN_DB_SCRIPT_STRING_ID; i < MAX_DB_SCRIPT_STRING_ID; ++i)
8368 if(GetMangosStringLocale(i))
8369 ids.insert(i);
8371 CheckScripts(sQuestEndScripts,ids);
8372 CheckScripts(sQuestStartScripts,ids);
8373 CheckScripts(sSpellScripts,ids);
8374 CheckScripts(sGameObjectScripts,ids);
8375 CheckScripts(sEventScripts,ids);
8376 CheckScripts(sGossipScripts,ids);
8378 sWaypointMgr.CheckTextsExistance(ids);
8380 for(std::set<int32>::const_iterator itr = ids.begin(); itr != ids.end(); ++itr)
8381 sLog.outErrorDb( "Table `db_script_string` has unused string id %u", *itr);
8384 // Functions for scripting access
8385 uint32 GetAreaTriggerScriptId(uint32 trigger_id)
8387 return sObjectMgr.GetAreaTriggerScriptId(trigger_id);
8390 bool LoadMangosStrings(DatabaseType& db, char const* table,int32 start_value, int32 end_value)
8392 // MAX_DB_SCRIPT_STRING_ID is max allowed negative value for scripts (scrpts can use only more deep negative values
8393 // start/end reversed for negative values
8394 if (start_value > MAX_DB_SCRIPT_STRING_ID || end_value >= start_value)
8396 sLog.outErrorDb("Table '%s' attempt loaded with reserved by mangos range (%d - %d), strings not loaded.",table,start_value,end_value+1);
8397 return false;
8400 return sObjectMgr.LoadMangosStrings(db,table,start_value,end_value);
8403 uint32 MANGOS_DLL_SPEC GetScriptId(const char *name)
8405 return sObjectMgr.GetScriptId(name);
8408 ObjectMgr::ScriptNameMap & GetScriptNames()
8410 return sObjectMgr.GetScriptNames();
8413 CreatureInfo const* GetCreatureTemplateStore(uint32 entry)
8415 return sCreatureStorage.LookupEntry<CreatureInfo>(entry);
8418 Quest const* GetQuestTemplateStore(uint32 entry)
8420 return sObjectMgr.GetQuestTemplate(entry);