[7438] My typos in ObjectMgr::LoadAreaTriggerTeleports
[AHbot.git] / src / game / ObjectMgr.cpp
blob89b38c2202580b8fe6e2518437099b0b6df7e0fc
1 /*
2 * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include "Common.h"
20 #include "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 "SpellMgr.h"
29 #include "UpdateMask.h"
30 #include "World.h"
31 #include "Group.h"
32 #include "Guild.h"
33 #include "ArenaTeam.h"
34 #include "Transports.h"
35 #include "ProgressBar.h"
36 #include "Language.h"
37 #include "GameEventMgr.h"
38 #include "Spell.h"
39 #include "Chat.h"
40 #include "AccountMgr.h"
41 #include "InstanceSaveMgr.h"
42 #include "SpellAuras.h"
43 #include "Util.h"
44 #include "WaypointManager.h"
46 INSTANTIATE_SINGLETON_1(ObjectMgr);
48 ScriptMapMap sQuestEndScripts;
49 ScriptMapMap sQuestStartScripts;
50 ScriptMapMap sSpellScripts;
51 ScriptMapMap sGameObjectScripts;
52 ScriptMapMap sEventScripts;
54 bool normalizePlayerName(std::string& name)
56 if(name.empty())
57 return false;
59 wchar_t wstr_buf[MAX_INTERNAL_PLAYER_NAME+1];
60 size_t wstr_len = MAX_INTERNAL_PLAYER_NAME;
62 if(!Utf8toWStr(name,&wstr_buf[0],wstr_len))
63 return false;
65 wstr_buf[0] = wcharToUpper(wstr_buf[0]);
66 for(size_t i = 1; i < wstr_len; ++i)
67 wstr_buf[i] = wcharToLower(wstr_buf[i]);
69 if(!WStrToUtf8(wstr_buf,wstr_len,name))
70 return false;
72 return true;
75 LanguageDesc lang_description[LANGUAGES_COUNT] =
77 { LANG_ADDON, 0, 0 },
78 { LANG_UNIVERSAL, 0, 0 },
79 { LANG_ORCISH, 669, SKILL_LANG_ORCISH },
80 { LANG_DARNASSIAN, 671, SKILL_LANG_DARNASSIAN },
81 { LANG_TAURAHE, 670, SKILL_LANG_TAURAHE },
82 { LANG_DWARVISH, 672, SKILL_LANG_DWARVEN },
83 { LANG_COMMON, 668, SKILL_LANG_COMMON },
84 { LANG_DEMONIC, 815, SKILL_LANG_DEMON_TONGUE },
85 { LANG_TITAN, 816, SKILL_LANG_TITAN },
86 { LANG_THALASSIAN, 813, SKILL_LANG_THALASSIAN },
87 { LANG_DRACONIC, 814, SKILL_LANG_DRACONIC },
88 { LANG_KALIMAG, 817, SKILL_LANG_OLD_TONGUE },
89 { LANG_GNOMISH, 7340, SKILL_LANG_GNOMISH },
90 { LANG_TROLL, 7341, SKILL_LANG_TROLL },
91 { LANG_GUTTERSPEAK, 17737, SKILL_LANG_GUTTERSPEAK },
92 { LANG_DRAENEI, 29932, SKILL_LANG_DRAENEI },
93 { LANG_ZOMBIE, 0, 0 },
94 { LANG_GNOMISH_BINARY, 0, 0 },
95 { LANG_GOBLIN_BINARY, 0, 0 }
98 LanguageDesc const* GetLanguageDescByID(uint32 lang)
100 for(int i = 0; i < LANGUAGES_COUNT; ++i)
102 if(uint32(lang_description[i].lang_id) == lang)
103 return &lang_description[i];
106 return NULL;
109 ObjectMgr::ObjectMgr()
111 m_hiCharGuid = 1;
112 m_hiCreatureGuid = 1;
113 m_hiPetGuid = 1;
114 m_hiVehicleGuid = 1;
115 m_hiItemGuid = 1;
116 m_hiGoGuid = 1;
117 m_hiDoGuid = 1;
118 m_hiCorpseGuid = 1;
119 m_hiPetNumber = 1;
120 m_ItemTextId = 1;
121 m_mailid = 1;
122 m_guildId = 1;
123 m_arenaTeamId = 1;
124 m_auctionid = 1;
126 mGuildBankTabPrice.resize(GUILD_BANK_MAX_TABS);
127 mGuildBankTabPrice[0] = 100;
128 mGuildBankTabPrice[1] = 250;
129 mGuildBankTabPrice[2] = 500;
130 mGuildBankTabPrice[3] = 1000;
131 mGuildBankTabPrice[4] = 2500;
132 mGuildBankTabPrice[5] = 5000;
134 // Only zero condition left, others will be added while loading DB tables
135 mConditions.resize(1);
138 ObjectMgr::~ObjectMgr()
140 for( QuestMap::iterator i = mQuestTemplates.begin( ); i != mQuestTemplates.end( ); ++i )
141 delete i->second;
143 for(PetLevelInfoMap::iterator i = petInfo.begin( ); i != petInfo.end( ); ++i )
144 delete[] i->second;
146 // free only if loaded
147 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
148 delete[] playerClassInfo[class_].levelInfo;
150 for (int race = 0; race < MAX_RACES; ++race)
151 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
152 delete[] playerInfo[race][class_].levelInfo;
154 // free group and guild objects
155 for (GroupSet::iterator itr = mGroupSet.begin(); itr != mGroupSet.end(); ++itr)
156 delete (*itr);
158 for (GuildMap::iterator itr = mGuildMap.begin(); itr != mGuildMap.end(); ++itr)
159 delete itr->second;
161 for (CacheVendorItemMap::iterator itr = m_mCacheVendorItemMap.begin(); itr != m_mCacheVendorItemMap.end(); ++itr)
162 itr->second.Clear();
164 for (CacheTrainerSpellMap::iterator itr = m_mCacheTrainerSpellMap.begin(); itr != m_mCacheTrainerSpellMap.end(); ++itr)
165 itr->second.Clear();
168 Group * ObjectMgr::GetGroupByLeader(const uint64 &guid) const
170 for(GroupSet::const_iterator itr = mGroupSet.begin(); itr != mGroupSet.end(); ++itr)
171 if ((*itr)->GetLeaderGUID() == guid)
172 return *itr;
174 return NULL;
177 Guild * ObjectMgr::GetGuildById(uint32 GuildId) const
179 GuildMap::const_iterator itr = mGuildMap.find(GuildId);
180 if (itr != mGuildMap.end())
181 return itr->second;
183 return NULL;
186 Guild * ObjectMgr::GetGuildByName(const std::string& guildname) const
188 for(GuildMap::const_iterator itr = mGuildMap.begin(); itr != mGuildMap.end(); ++itr)
189 if (itr->second->GetName() == guildname)
190 return itr->second;
192 return NULL;
195 std::string ObjectMgr::GetGuildNameById(uint32 GuildId) const
197 GuildMap::const_iterator itr = mGuildMap.find(GuildId);
198 if (itr != mGuildMap.end())
199 return itr->second->GetName();
201 return "";
204 Guild* ObjectMgr::GetGuildByLeader(const uint64 &guid) const
206 for(GuildMap::const_iterator itr = mGuildMap.begin(); itr != mGuildMap.end(); ++itr)
207 if (itr->second->GetLeader() == guid)
208 return itr->second;
210 return NULL;
213 void ObjectMgr::AddGuild(Guild* guild)
215 mGuildMap[guild->GetId()] = guild;
218 void ObjectMgr::RemoveGuild(uint32 Id)
220 mGuildMap.erase(Id);
223 ArenaTeam* ObjectMgr::GetArenaTeamById(uint32 arenateamid) const
225 ArenaTeamMap::const_iterator itr = mArenaTeamMap.find(arenateamid);
226 if (itr != mArenaTeamMap.end())
227 return itr->second;
229 return NULL;
232 ArenaTeam* ObjectMgr::GetArenaTeamByName(const std::string& arenateamname) const
234 for(ArenaTeamMap::const_iterator itr = mArenaTeamMap.begin(); itr != mArenaTeamMap.end(); ++itr)
235 if (itr->second->GetName() == arenateamname)
236 return itr->second;
238 return NULL;
241 ArenaTeam* ObjectMgr::GetArenaTeamByCaptain(uint64 const& guid) const
243 for(ArenaTeamMap::const_iterator itr = mArenaTeamMap.begin(); itr != mArenaTeamMap.end(); ++itr)
244 if (itr->second->GetCaptain() == guid)
245 return itr->second;
247 return NULL;
250 void ObjectMgr::AddArenaTeam(ArenaTeam* arenaTeam)
252 mArenaTeamMap[arenaTeam->GetId()] = arenaTeam;
255 void ObjectMgr::RemoveArenaTeam(uint32 Id)
257 mArenaTeamMap.erase(Id);
260 CreatureInfo const* ObjectMgr::GetCreatureTemplate(uint32 id)
262 return sCreatureStorage.LookupEntry<CreatureInfo>(id);
265 void ObjectMgr::LoadCreatureLocales()
267 mCreatureLocaleMap.clear(); // need for reload case
269 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");
271 if(!result)
273 barGoLink bar(1);
275 bar.step();
277 sLog.outString();
278 sLog.outString(">> Loaded 0 creature locale strings. DB table `locales_creature` is empty.");
279 return;
282 barGoLink bar(result->GetRowCount());
286 Field *fields = result->Fetch();
287 bar.step();
289 uint32 entry = fields[0].GetUInt32();
291 CreatureLocale& data = mCreatureLocaleMap[entry];
293 for(int i = 1; i < MAX_LOCALE; ++i)
295 std::string str = fields[1+2*(i-1)].GetCppString();
296 if(!str.empty())
298 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
299 if(idx >= 0)
301 if(data.Name.size() <= idx)
302 data.Name.resize(idx+1);
304 data.Name[idx] = str;
307 str = fields[1+2*(i-1)+1].GetCppString();
308 if(!str.empty())
310 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
311 if(idx >= 0)
313 if(data.SubName.size() <= idx)
314 data.SubName.resize(idx+1);
316 data.SubName[idx] = str;
320 } while (result->NextRow());
322 delete result;
324 sLog.outString();
325 sLog.outString( ">> Loaded %u creature locale strings", mCreatureLocaleMap.size() );
328 void ObjectMgr::LoadNpcOptionLocales()
330 mNpcOptionLocaleMap.clear(); // need for reload case
332 QueryResult *result = WorldDatabase.Query("SELECT entry,"
333 "option_text_loc1,box_text_loc1,option_text_loc2,box_text_loc2,"
334 "option_text_loc3,box_text_loc3,option_text_loc4,box_text_loc4,"
335 "option_text_loc5,box_text_loc5,option_text_loc6,box_text_loc6,"
336 "option_text_loc7,box_text_loc7,option_text_loc8,box_text_loc8 "
337 "FROM locales_npc_option");
339 if(!result)
341 barGoLink bar(1);
343 bar.step();
345 sLog.outString();
346 sLog.outString(">> Loaded 0 npc_option locale strings. DB table `locales_npc_option` is empty.");
347 return;
350 barGoLink bar(result->GetRowCount());
354 Field *fields = result->Fetch();
355 bar.step();
357 uint32 entry = fields[0].GetUInt32();
359 NpcOptionLocale& data = mNpcOptionLocaleMap[entry];
361 for(int i = 1; i < MAX_LOCALE; ++i)
363 std::string str = fields[1+2*(i-1)].GetCppString();
364 if(!str.empty())
366 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
367 if(idx >= 0)
369 if(data.OptionText.size() <= idx)
370 data.OptionText.resize(idx+1);
372 data.OptionText[idx] = str;
375 str = fields[1+2*(i-1)+1].GetCppString();
376 if(!str.empty())
378 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
379 if(idx >= 0)
381 if(data.BoxText.size() <= idx)
382 data.BoxText.resize(idx+1);
384 data.BoxText[idx] = str;
388 } while (result->NextRow());
390 delete result;
392 sLog.outString();
393 sLog.outString( ">> Loaded %u npc_option locale strings", mNpcOptionLocaleMap.size() );
396 void ObjectMgr::LoadPointOfInterestLocales()
398 mPointOfInterestLocaleMap.clear(); // need for reload case
400 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");
402 if(!result)
404 barGoLink bar(1);
406 bar.step();
408 sLog.outString();
409 sLog.outString(">> Loaded 0 points_of_interest locale strings. DB table `locales_points_of_interest` is empty.");
410 return;
413 barGoLink bar(result->GetRowCount());
417 Field *fields = result->Fetch();
418 bar.step();
420 uint32 entry = fields[0].GetUInt32();
422 PointOfInterestLocale& data = mPointOfInterestLocaleMap[entry];
424 for(int i = 1; i < MAX_LOCALE; ++i)
426 std::string str = fields[i].GetCppString();
427 if(str.empty())
428 continue;
430 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
431 if(idx >= 0)
433 if(data.IconName.size() <= idx)
434 data.IconName.resize(idx+1);
436 data.IconName[idx] = str;
439 } while (result->NextRow());
441 delete result;
443 sLog.outString();
444 sLog.outString( ">> Loaded %u points_of_interest locale strings", mPointOfInterestLocaleMap.size() );
447 struct SQLCreatureLoader : public SQLStorageLoaderBase<SQLCreatureLoader>
449 template<class D>
450 void convert_from_str(uint32 field_pos, char *src, D &dst)
452 dst = D(objmgr.GetScriptId(src));
456 void ObjectMgr::LoadCreatureTemplates()
458 SQLCreatureLoader loader;
459 loader.Load(sCreatureStorage);
461 sLog.outString( ">> Loaded %u creature definitions", sCreatureStorage.RecordCount );
462 sLog.outString();
464 std::set<uint32> heroicEntries; // already loaded heroic value in creatures
465 std::set<uint32> hasHeroicEntries; // already loaded creatures with heroic entry values
467 // check data correctness
468 for(uint32 i = 1; i < sCreatureStorage.MaxEntry; ++i)
470 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i);
471 if(!cInfo)
472 continue;
474 if(cInfo->HeroicEntry)
476 CreatureInfo const* heroicInfo = GetCreatureTemplate(cInfo->HeroicEntry);
477 if(!heroicInfo)
479 sLog.outErrorDb("Creature (Entry: %u) have `heroic_entry`=%u but creature entry %u not exist.",cInfo->HeroicEntry,cInfo->HeroicEntry);
480 continue;
483 if(heroicEntries.find(i)!=heroicEntries.end())
485 sLog.outErrorDb("Creature (Entry: %u) listed as heroic but have value in `heroic_entry`.",i);
486 continue;
489 if(heroicEntries.find(cInfo->HeroicEntry)!=heroicEntries.end())
491 sLog.outErrorDb("Creature (Entry: %u) already listed as heroic for another entry.",cInfo->HeroicEntry);
492 continue;
495 if(hasHeroicEntries.find(cInfo->HeroicEntry)!=hasHeroicEntries.end())
497 sLog.outErrorDb("Creature (Entry: %u) have `heroic_entry`=%u but creature entry %u have heroic entry also.",i,cInfo->HeroicEntry,cInfo->HeroicEntry);
498 continue;
501 if(cInfo->npcflag != heroicInfo->npcflag)
503 sLog.outErrorDb("Creature (Entry: %u) has different `npcflag` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
504 continue;
507 if(cInfo->classNum != heroicInfo->classNum)
509 sLog.outErrorDb("Creature (Entry: %u) has different `classNum` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
510 continue;
513 if(cInfo->race != heroicInfo->race)
515 sLog.outErrorDb("Creature (Entry: %u) has different `race` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
516 continue;
519 if(cInfo->trainer_type != heroicInfo->trainer_type)
521 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_type` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
522 continue;
525 if(cInfo->trainer_spell != heroicInfo->trainer_spell)
527 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_spell` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
528 continue;
531 hasHeroicEntries.insert(i);
532 heroicEntries.insert(cInfo->HeroicEntry);
535 FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction_A);
536 if(!factionTemplate)
537 sLog.outErrorDb("Creature (Entry: %u) has non-existing faction_A template (%u)", cInfo->Entry, cInfo->faction_A);
539 factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction_H);
540 if(!factionTemplate)
541 sLog.outErrorDb("Creature (Entry: %u) has non-existing faction_H template (%u)", cInfo->Entry, cInfo->faction_H);
543 CreatureModelInfo const* minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_A);
544 if (!minfo)
545 sLog.outErrorDb("Creature (Entry: %u) has non-existing modelId_A (%u)", cInfo->Entry, cInfo->DisplayID_A);
546 minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_H);
547 if (!minfo)
548 sLog.outErrorDb("Creature (Entry: %u) has non-existing modelId_H (%u)", cInfo->Entry, cInfo->DisplayID_H);
550 if(cInfo->dmgschool >= MAX_SPELL_SCHOOL)
552 sLog.outErrorDb("Creature (Entry: %u) has invalid spell school value (%u) in `dmgschool`",cInfo->Entry,cInfo->dmgschool);
553 const_cast<CreatureInfo*>(cInfo)->dmgschool = SPELL_SCHOOL_NORMAL;
556 if(cInfo->baseattacktime == 0)
557 const_cast<CreatureInfo*>(cInfo)->baseattacktime = BASE_ATTACK_TIME;
559 if(cInfo->rangeattacktime == 0)
560 const_cast<CreatureInfo*>(cInfo)->rangeattacktime = BASE_ATTACK_TIME;
562 if((cInfo->npcflag & UNIT_NPC_FLAG_TRAINER) && cInfo->trainer_type >= MAX_TRAINER_TYPE)
563 sLog.outErrorDb("Creature (Entry: %u) has wrong trainer type %u",cInfo->Entry,cInfo->trainer_type);
565 if(cInfo->type && !sCreatureTypeStore.LookupEntry(cInfo->type))
567 sLog.outErrorDb("Creature (Entry: %u) has invalid creature type (%u) in `type`",cInfo->Entry,cInfo->type);
568 const_cast<CreatureInfo*>(cInfo)->type = CREATURE_TYPE_HUMANOID;
571 // must exist or used hidden but used in data horse case
572 if(cInfo->family && !sCreatureFamilyStore.LookupEntry(cInfo->family) && cInfo->family != CREATURE_FAMILY_HORSE_CUSTOM )
574 sLog.outErrorDb("Creature (Entry: %u) has invalid creature family (%u) in `family`",cInfo->Entry,cInfo->family);
575 const_cast<CreatureInfo*>(cInfo)->family = 0;
578 if(cInfo->InhabitType <= 0 || cInfo->InhabitType > INHABIT_ANYWHERE)
580 sLog.outErrorDb("Creature (Entry: %u) has wrong value (%u) in `InhabitType`, creature will not correctly walk/swim/fly",cInfo->Entry,cInfo->InhabitType);
581 const_cast<CreatureInfo*>(cInfo)->InhabitType = INHABIT_ANYWHERE;
584 if(cInfo->PetSpellDataId)
586 CreatureSpellDataEntry const* spellDataId = sCreatureSpellDataStore.LookupEntry(cInfo->PetSpellDataId);
587 if(!spellDataId)
588 sLog.outErrorDb("Creature (Entry: %u) has non-existing PetSpellDataId (%u)", cInfo->Entry, cInfo->PetSpellDataId);
591 for(int i = 0; i < CREATURE_MAX_SPELLS; ++i)
593 if(cInfo->spells[i] && !sSpellStore.LookupEntry(cInfo->spells[i]))
595 sLog.outErrorDb("Creature (Entry: %u) has non-existing Spell%d (%u), set to 0", cInfo->Entry, i+1,cInfo->spells[i]);
596 const_cast<CreatureInfo*>(cInfo)->spells[i] = 0;
600 if(cInfo->MovementType >= MAX_DB_MOTION_TYPE)
602 sLog.outErrorDb("Creature (Entry: %u) has wrong movement generator type (%u), ignore and set to IDLE.",cInfo->Entry,cInfo->MovementType);
603 const_cast<CreatureInfo*>(cInfo)->MovementType = IDLE_MOTION_TYPE;
606 if(cInfo->equipmentId > 0) // 0 no equipment
608 if(!GetEquipmentInfo(cInfo->equipmentId))
610 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);
611 const_cast<CreatureInfo*>(cInfo)->equipmentId = 0;
615 /// if not set custom creature scale then load scale from CreatureDisplayInfo.dbc
616 if(cInfo->scale <= 0.0f)
618 CreatureDisplayInfoEntry const* ScaleEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->DisplayID_A);
619 const_cast<CreatureInfo*>(cInfo)->scale = ScaleEntry ? ScaleEntry->scale : 1.0f;
624 void ObjectMgr::ConvertCreatureAddonAuras(CreatureDataAddon* addon, char const* table, char const* guidEntryStr)
626 // Now add the auras, format "spellid effectindex spellid effectindex..."
627 char *p,*s;
628 std::vector<int> val;
629 s=p=(char*)reinterpret_cast<char const*>(addon->auras);
630 if(p)
632 while (p[0]!=0)
634 ++p;
635 if (p[0]==' ')
637 val.push_back(atoi(s));
638 s=++p;
641 if (p!=s)
642 val.push_back(atoi(s));
644 // free char* loaded memory
645 delete[] (char*)reinterpret_cast<char const*>(addon->auras);
647 // wrong list
648 if (val.size()%2)
650 addon->auras = NULL;
651 sLog.outErrorDb("Creature (%s: %u) has wrong `auras` data in `%s`.",guidEntryStr,addon->guidOrEntry,table);
652 return;
656 // empty list
657 if(val.empty())
659 addon->auras = NULL;
660 return;
663 // replace by new structures array
664 const_cast<CreatureDataAddonAura*&>(addon->auras) = new CreatureDataAddonAura[val.size()/2+1];
666 int i=0;
667 for(int j=0;j<val.size()/2;++j)
669 CreatureDataAddonAura& cAura = const_cast<CreatureDataAddonAura&>(addon->auras[i]);
670 cAura.spell_id = (uint32)val[2*j+0];
671 cAura.effect_idx = (uint32)val[2*j+1];
672 if ( cAura.effect_idx > 2 )
674 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);
675 continue;
677 SpellEntry const *AdditionalSpellInfo = sSpellStore.LookupEntry(cAura.spell_id);
678 if (!AdditionalSpellInfo)
680 sLog.outErrorDb("Creature (%s: %u) has wrong spell %u defined in `auras` field in `%s`.",guidEntryStr,addon->guidOrEntry,cAura.spell_id,table);
681 continue;
684 if (!AdditionalSpellInfo->Effect[cAura.effect_idx] || !AdditionalSpellInfo->EffectApplyAuraName[cAura.effect_idx])
686 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);
687 continue;
690 ++i;
693 // fill terminator element (after last added)
694 CreatureDataAddonAura& endAura = const_cast<CreatureDataAddonAura&>(addon->auras[i]);
695 endAura.spell_id = 0;
696 endAura.effect_idx = 0;
699 void ObjectMgr::LoadCreatureAddons()
701 sCreatureInfoAddonStorage.Load();
703 sLog.outString( ">> Loaded %u creature template addons", sCreatureInfoAddonStorage.RecordCount );
704 sLog.outString();
706 // check data correctness and convert 'auras'
707 for(uint32 i = 1; i < sCreatureInfoAddonStorage.MaxEntry; ++i)
709 CreatureDataAddon const* addon = sCreatureInfoAddonStorage.LookupEntry<CreatureDataAddon>(i);
710 if(!addon)
711 continue;
713 ConvertCreatureAddonAuras(const_cast<CreatureDataAddon*>(addon), "creature_template_addon", "Entry");
715 if(!sCreatureStorage.LookupEntry<CreatureInfo>(addon->guidOrEntry))
716 sLog.outErrorDb("Creature (Entry: %u) does not exist but has a record in `creature_template_addon`",addon->guidOrEntry);
719 sCreatureDataAddonStorage.Load();
721 sLog.outString( ">> Loaded %u creature addons", sCreatureDataAddonStorage.RecordCount );
722 sLog.outString();
724 // check data correctness and convert 'auras'
725 for(uint32 i = 1; i < sCreatureDataAddonStorage.MaxEntry; ++i)
727 CreatureDataAddon const* addon = sCreatureDataAddonStorage.LookupEntry<CreatureDataAddon>(i);
728 if(!addon)
729 continue;
731 ConvertCreatureAddonAuras(const_cast<CreatureDataAddon*>(addon), "creature_addon", "GUIDLow");
733 if(mCreatureDataMap.find(addon->guidOrEntry)==mCreatureDataMap.end())
734 sLog.outErrorDb("Creature (GUID: %u) does not exist but has a record in `creature_addon`",addon->guidOrEntry);
738 EquipmentInfo const* ObjectMgr::GetEquipmentInfo(uint32 entry)
740 return sEquipmentStorage.LookupEntry<EquipmentInfo>(entry);
743 void ObjectMgr::LoadEquipmentTemplates()
745 sEquipmentStorage.Load();
747 for(uint32 i=0; i< sEquipmentStorage.MaxEntry; ++i)
749 EquipmentInfo const* eqInfo = sEquipmentStorage.LookupEntry<EquipmentInfo>(i);
751 if(!eqInfo)
752 continue;
754 for(uint8 j=0; j<3; j++)
756 if(!eqInfo->equipentry[j])
757 continue;
759 ItemEntry const *dbcitem = sItemStore.LookupEntry(eqInfo->equipentry[j]);
761 if(!dbcitem)
763 sLog.outErrorDb("Unknown item (entry=%u) in creature_equip_template.equipentry%u for entry = %u, forced to 0.", eqInfo->equipentry[j], j+1, i);
764 const_cast<EquipmentInfo*>(eqInfo)->equipentry[j] = 0;
765 continue;
768 if(dbcitem->InventoryType != INVTYPE_WEAPON &&
769 dbcitem->InventoryType != INVTYPE_SHIELD &&
770 dbcitem->InventoryType != INVTYPE_RANGED &&
771 dbcitem->InventoryType != INVTYPE_2HWEAPON &&
772 dbcitem->InventoryType != INVTYPE_WEAPONMAINHAND &&
773 dbcitem->InventoryType != INVTYPE_WEAPONOFFHAND &&
774 dbcitem->InventoryType != INVTYPE_HOLDABLE &&
775 dbcitem->InventoryType != INVTYPE_THROWN &&
776 dbcitem->InventoryType != INVTYPE_RANGEDRIGHT)
778 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);
779 const_cast<EquipmentInfo*>(eqInfo)->equipentry[j] = 0;
783 sLog.outString( ">> Loaded %u equipment template", sEquipmentStorage.RecordCount );
784 sLog.outString();
786 // This DBC is currently only used for item templates and creature equipments checks.
787 sItemStore.Clear();
790 CreatureModelInfo const* ObjectMgr::GetCreatureModelInfo(uint32 modelid)
792 return sCreatureModelStorage.LookupEntry<CreatureModelInfo>(modelid);
795 uint32 ObjectMgr::ChooseDisplayId(uint32 team, const CreatureInfo *cinfo, const CreatureData *data)
797 // Load creature model (display id)
798 uint32 display_id;
799 if (!data || data->displayid == 0) // use defaults from the template
801 // DisplayID_A is used if no team is given
802 if (team == HORDE)
803 display_id = (cinfo->DisplayID_H2 != 0 && urand(0,1) == 0) ? cinfo->DisplayID_H2 : cinfo->DisplayID_H;
804 else
805 display_id = (cinfo->DisplayID_A2 != 0 && urand(0,1) == 0) ? cinfo->DisplayID_A2 : cinfo->DisplayID_A;
807 else // overridden in creature data
808 display_id = data->displayid;
810 return display_id;
813 CreatureModelInfo const* ObjectMgr::GetCreatureModelRandomGender(uint32 display_id)
815 CreatureModelInfo const *minfo = GetCreatureModelInfo(display_id);
816 if(!minfo)
817 return NULL;
819 // If a model for another gender exists, 50% chance to use it
820 if(minfo->modelid_other_gender != 0 && urand(0,1) == 0)
822 CreatureModelInfo const *minfo_tmp = GetCreatureModelInfo(minfo->modelid_other_gender);
823 if(!minfo_tmp)
825 sLog.outErrorDb("Model (Entry: %u) has modelid_other_gender %u not found in table `creature_model_info`. ", minfo->modelid, minfo->modelid_other_gender);
826 return minfo; // not fatal, just use the previous one
828 else
829 return minfo_tmp;
831 else
832 return minfo;
835 void ObjectMgr::LoadCreatureModelInfo()
837 sCreatureModelStorage.Load();
839 sLog.outString( ">> Loaded %u creature model based info", sCreatureModelStorage.RecordCount );
840 sLog.outString();
843 void ObjectMgr::LoadCreatures()
845 uint32 count = 0;
846 // 0 1 2 3
847 QueryResult *result = WorldDatabase.Query("SELECT creature.guid, id, map, modelid,"
848 // 4 5 6 7 8 9 10 11
849 "equipment_id, position_x, position_y, position_z, orientation, spawntimesecs, spawndist, currentwaypoint,"
850 // 12 13 14 15 16 17 18 19
851 "curhealth, curmana, DeathState, MovementType, spawnMask, phaseMask, event, pool_entry "
852 "FROM creature LEFT OUTER JOIN game_event_creature ON creature.guid = game_event_creature.guid "
853 "LEFT OUTER JOIN pool_creature ON creature.guid = pool_creature.guid");
855 if(!result)
857 barGoLink bar(1);
859 bar.step();
861 sLog.outString();
862 sLog.outErrorDb(">> Loaded 0 creature. DB table `creature` is empty.");
863 return;
866 // build single time for check creature data
867 std::set<uint32> heroicCreatures;
868 for(uint32 i = 0; i < sCreatureStorage.MaxEntry; ++i)
869 if(CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i))
870 if(cInfo->HeroicEntry)
871 heroicCreatures.insert(cInfo->HeroicEntry);
873 barGoLink bar(result->GetRowCount());
877 Field *fields = result->Fetch();
878 bar.step();
880 uint32 guid = fields[ 0].GetUInt32();
881 uint32 entry = fields[ 1].GetUInt32();
883 CreatureInfo const* cInfo = GetCreatureTemplate(entry);
884 if(!cInfo)
886 sLog.outErrorDb("Table `creature` has creature (GUID: %u) with non existing creature entry %u, skipped.", guid, entry);
887 continue;
890 CreatureData& data = mCreatureDataMap[guid];
892 data.id = entry;
893 data.mapid = fields[ 2].GetUInt32();
894 data.displayid = fields[ 3].GetUInt32();
895 data.equipmentId = fields[ 4].GetUInt32();
896 data.posX = fields[ 5].GetFloat();
897 data.posY = fields[ 6].GetFloat();
898 data.posZ = fields[ 7].GetFloat();
899 data.orientation = fields[ 8].GetFloat();
900 data.spawntimesecs = fields[ 9].GetUInt32();
901 data.spawndist = fields[10].GetFloat();
902 data.currentwaypoint= fields[11].GetUInt32();
903 data.curhealth = fields[12].GetUInt32();
904 data.curmana = fields[13].GetUInt32();
905 data.is_dead = fields[14].GetBool();
906 data.movementType = fields[15].GetUInt8();
907 data.spawnMask = fields[16].GetUInt8();
908 data.phaseMask = fields[17].GetUInt16();
909 int16 gameEvent = fields[18].GetInt16();
910 int16 PoolId = fields[19].GetInt16();
912 if(heroicCreatures.find(data.id)!=heroicCreatures.end())
914 sLog.outErrorDb("Table `creature` have creature (GUID: %u) that listed as heroic template in `creature_template`, skipped.",guid,data.id );
915 continue;
918 if(data.equipmentId > 0) // -1 no equipment, 0 use default
920 if(!GetEquipmentInfo(data.equipmentId))
922 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);
923 data.equipmentId = -1;
927 if(cInfo->RegenHealth && data.curhealth < cInfo->minhealth)
929 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 );
930 data.curhealth = cInfo->minhealth;
933 if(cInfo->flags_extra & CREATURE_FLAG_EXTRA_INSTANCE_BIND)
935 MapEntry const* map = sMapStore.LookupEntry(data.mapid);
936 if(!map || !map->IsDungeon())
937 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);
940 if(data.curmana < cInfo->minmana)
942 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 );
943 data.curmana = cInfo->minmana;
946 if(data.spawndist < 0.0f)
948 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `spawndist`< 0, set to 0.",guid,data.id );
949 data.spawndist = 0.0f;
951 else if(data.movementType == RANDOM_MOTION_TYPE)
953 if(data.spawndist == 0.0f)
955 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 );
956 data.movementType = IDLE_MOTION_TYPE;
959 else if(data.movementType == IDLE_MOTION_TYPE)
961 if(data.spawndist != 0.0f)
963 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `MovementType`=0 (idle) have `spawndist`<>0, set to 0.",guid,data.id );
964 data.spawndist = 0.0f;
968 if(data.phaseMask==0)
970 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `phaseMask`=0 (not visible for anyone), set to 1.",guid,data.id );
971 data.phaseMask = 1;
974 if (gameEvent==0 && PoolId==0) // if not this is to be managed by GameEvent System or Pool system
975 AddCreatureToGrid(guid, &data);
977 ++count;
979 } while (result->NextRow());
981 delete result;
983 sLog.outString();
984 sLog.outString( ">> Loaded %u creatures", mCreatureDataMap.size() );
987 void ObjectMgr::AddCreatureToGrid(uint32 guid, CreatureData const* data)
989 uint8 mask = data->spawnMask;
990 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
992 if(mask & 1)
994 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
995 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
997 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
998 cell_guids.creatures.insert(guid);
1003 void ObjectMgr::RemoveCreatureFromGrid(uint32 guid, CreatureData const* data)
1005 uint8 mask = data->spawnMask;
1006 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1008 if(mask & 1)
1010 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1011 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1013 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1014 cell_guids.creatures.erase(guid);
1019 void ObjectMgr::LoadGameobjects()
1021 uint32 count = 0;
1023 // 0 1 2 3 4 5 6
1024 QueryResult *result = WorldDatabase.Query("SELECT gameobject.guid, id, map, position_x, position_y, position_z, orientation,"
1025 // 7 8 9 10 11 12 13 14 15 16 17
1026 "rotation0, rotation1, rotation2, rotation3, spawntimesecs, animprogress, state, spawnMask, phaseMask, event, pool_entry "
1027 "FROM gameobject LEFT OUTER JOIN game_event_gameobject ON gameobject.guid = game_event_gameobject.guid "
1028 "LEFT OUTER JOIN pool_gameobject ON gameobject.guid = pool_gameobject.guid");
1030 if(!result)
1032 barGoLink bar(1);
1034 bar.step();
1036 sLog.outString();
1037 sLog.outErrorDb(">> Loaded 0 gameobjects. DB table `gameobject` is empty.");
1038 return;
1041 barGoLink bar(result->GetRowCount());
1045 Field *fields = result->Fetch();
1046 bar.step();
1048 uint32 guid = fields[ 0].GetUInt32();
1049 uint32 entry = fields[ 1].GetUInt32();
1051 GameObjectInfo const* gInfo = GetGameObjectInfo(entry);
1052 if(!gInfo)
1054 sLog.outErrorDb("Table `gameobject` has gameobject (GUID: %u) with non existing gameobject entry %u, skipped.", guid, entry);
1055 continue;
1058 GameObjectData& data = mGameObjectDataMap[guid];
1060 data.id = entry;
1061 data.mapid = fields[ 2].GetUInt32();
1062 data.posX = fields[ 3].GetFloat();
1063 data.posY = fields[ 4].GetFloat();
1064 data.posZ = fields[ 5].GetFloat();
1065 data.orientation = fields[ 6].GetFloat();
1066 data.rotation0 = fields[ 7].GetFloat();
1067 data.rotation1 = fields[ 8].GetFloat();
1068 data.rotation2 = fields[ 9].GetFloat();
1069 data.rotation3 = fields[10].GetFloat();
1070 data.spawntimesecs = fields[11].GetInt32();
1071 data.animprogress = fields[12].GetUInt32();
1072 data.go_state = fields[13].GetUInt32();
1073 data.spawnMask = fields[14].GetUInt8();
1074 data.phaseMask = fields[15].GetUInt16();
1075 int16 gameEvent = fields[16].GetInt16();
1076 int16 PoolId = fields[17].GetInt16();
1078 if(data.phaseMask==0)
1080 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with `phaseMask`=0 (not visible for anyone), set to 1.",guid,data.id );
1081 data.phaseMask = 1;
1084 if (gameEvent==0 && PoolId==0) // if not this is to be managed by GameEvent System or Pool system
1085 AddGameobjectToGrid(guid, &data);
1086 ++count;
1088 } while (result->NextRow());
1090 delete result;
1092 sLog.outString();
1093 sLog.outString( ">> Loaded %u gameobjects", mGameObjectDataMap.size());
1096 void ObjectMgr::AddGameobjectToGrid(uint32 guid, GameObjectData const* data)
1098 uint8 mask = data->spawnMask;
1099 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1101 if(mask & 1)
1103 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1104 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1106 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1107 cell_guids.gameobjects.insert(guid);
1112 void ObjectMgr::RemoveGameobjectFromGrid(uint32 guid, GameObjectData const* data)
1114 uint8 mask = data->spawnMask;
1115 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1117 if(mask & 1)
1119 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1120 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1122 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1123 cell_guids.gameobjects.erase(guid);
1128 void ObjectMgr::LoadCreatureRespawnTimes()
1130 // remove outdated data
1131 WorldDatabase.DirectExecute("DELETE FROM creature_respawn WHERE respawntime <= UNIX_TIMESTAMP(NOW())");
1133 uint32 count = 0;
1135 QueryResult *result = WorldDatabase.Query("SELECT guid,respawntime,instance FROM creature_respawn");
1137 if(!result)
1139 barGoLink bar(1);
1141 bar.step();
1143 sLog.outString();
1144 sLog.outString(">> Loaded 0 creature respawn time.");
1145 return;
1148 barGoLink bar(result->GetRowCount());
1152 Field *fields = result->Fetch();
1153 bar.step();
1155 uint32 loguid = fields[0].GetUInt32();
1156 uint64 respawn_time = fields[1].GetUInt64();
1157 uint32 instance = fields[2].GetUInt32();
1159 mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = time_t(respawn_time);
1161 ++count;
1162 } while (result->NextRow());
1164 delete result;
1166 sLog.outString( ">> Loaded %u creature respawn times", mCreatureRespawnTimes.size() );
1167 sLog.outString();
1170 void ObjectMgr::LoadGameobjectRespawnTimes()
1172 // remove outdated data
1173 WorldDatabase.DirectExecute("DELETE FROM gameobject_respawn WHERE respawntime <= UNIX_TIMESTAMP(NOW())");
1175 uint32 count = 0;
1177 QueryResult *result = WorldDatabase.Query("SELECT guid,respawntime,instance FROM gameobject_respawn");
1179 if(!result)
1181 barGoLink bar(1);
1183 bar.step();
1185 sLog.outString();
1186 sLog.outString(">> Loaded 0 gameobject respawn time.");
1187 return;
1190 barGoLink bar(result->GetRowCount());
1194 Field *fields = result->Fetch();
1195 bar.step();
1197 uint32 loguid = fields[0].GetUInt32();
1198 uint64 respawn_time = fields[1].GetUInt64();
1199 uint32 instance = fields[2].GetUInt32();
1201 mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = time_t(respawn_time);
1203 ++count;
1204 } while (result->NextRow());
1206 delete result;
1208 sLog.outString( ">> Loaded %u gameobject respawn times", mGORespawnTimes.size() );
1209 sLog.outString();
1212 // name must be checked to correctness (if received) before call this function
1213 uint64 ObjectMgr::GetPlayerGUIDByName(std::string name) const
1215 uint64 guid = 0;
1217 CharacterDatabase.escape_string(name);
1219 // Player name safe to sending to DB (checked at login) and this function using
1220 QueryResult *result = CharacterDatabase.PQuery("SELECT guid FROM characters WHERE name = '%s'", name.c_str());
1221 if(result)
1223 guid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
1225 delete result;
1228 return guid;
1231 bool ObjectMgr::GetPlayerNameByGUID(const uint64 &guid, std::string &name) const
1233 // prevent DB access for online player
1234 if(Player* player = GetPlayer(guid))
1236 name = player->GetName();
1237 return true;
1240 QueryResult *result = CharacterDatabase.PQuery("SELECT name FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1242 if(result)
1244 name = (*result)[0].GetCppString();
1245 delete result;
1246 return true;
1249 return false;
1252 uint32 ObjectMgr::GetPlayerTeamByGUID(const uint64 &guid) const
1254 QueryResult *result = CharacterDatabase.PQuery("SELECT race FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1256 if(result)
1258 uint8 race = (*result)[0].GetUInt8();
1259 delete result;
1260 return Player::TeamForRace(race);
1263 return 0;
1266 uint32 ObjectMgr::GetPlayerAccountIdByGUID(const uint64 &guid) const
1268 QueryResult *result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1269 if(result)
1271 uint32 acc = (*result)[0].GetUInt32();
1272 delete result;
1273 return acc;
1276 return 0;
1279 uint32 ObjectMgr::GetPlayerAccountIdByPlayerName(const std::string& name) const
1281 QueryResult *result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'", name.c_str());
1282 if(result)
1284 uint32 acc = (*result)[0].GetUInt32();
1285 delete result;
1286 return acc;
1289 return 0;
1292 void ObjectMgr::LoadItemLocales()
1294 mItemLocaleMap.clear(); // need for reload case
1296 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");
1298 if(!result)
1300 barGoLink bar(1);
1302 bar.step();
1304 sLog.outString();
1305 sLog.outString(">> Loaded 0 Item locale strings. DB table `locales_item` is empty.");
1306 return;
1309 barGoLink bar(result->GetRowCount());
1313 Field *fields = result->Fetch();
1314 bar.step();
1316 uint32 entry = fields[0].GetUInt32();
1318 ItemLocale& data = mItemLocaleMap[entry];
1320 for(int i = 1; i < MAX_LOCALE; ++i)
1322 std::string str = fields[1+2*(i-1)].GetCppString();
1323 if(!str.empty())
1325 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
1326 if(idx >= 0)
1328 if(data.Name.size() <= idx)
1329 data.Name.resize(idx+1);
1331 data.Name[idx] = str;
1335 str = fields[1+2*(i-1)+1].GetCppString();
1336 if(!str.empty())
1338 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
1339 if(idx >= 0)
1341 if(data.Description.size() <= idx)
1342 data.Description.resize(idx+1);
1344 data.Description[idx] = str;
1348 } while (result->NextRow());
1350 delete result;
1352 sLog.outString();
1353 sLog.outString( ">> Loaded %u Item locale strings", mItemLocaleMap.size() );
1356 struct SQLItemLoader : public SQLStorageLoaderBase<SQLItemLoader>
1358 template<class D>
1359 void convert_from_str(uint32 field_pos, char *src, D &dst)
1361 dst = D(objmgr.GetScriptId(src));
1365 void ObjectMgr::LoadItemPrototypes()
1367 SQLItemLoader loader;
1368 loader.Load(sItemStorage);
1369 sLog.outString( ">> Loaded %u item prototypes", sItemStorage.RecordCount );
1370 sLog.outString();
1372 // check data correctness
1373 for(uint32 i = 1; i < sItemStorage.MaxEntry; ++i)
1375 ItemPrototype const* proto = sItemStorage.LookupEntry<ItemPrototype >(i);
1376 ItemEntry const *dbcitem = sItemStore.LookupEntry(i);
1377 if(!proto)
1379 /* to many errors, and possible not all items really used in game
1380 if (dbcitem)
1381 sLog.outErrorDb("Item (Entry: %u) doesn't exists in DB, but must exist.",i);
1383 continue;
1386 if(dbcitem)
1388 if(proto->Class != dbcitem->Class)
1390 sLog.outErrorDb("Item (Entry: %u) not correct class %u, must be %u (still using DB value).",i,proto->Class,dbcitem->Class);
1391 // It safe let use Class from DB
1393 /* disabled: have some strange wrong cases for Subclass values.
1394 for enable also uncomment Subclass field in ItemEntry structure and in Itemfmt[]
1395 if(proto->SubClass != dbcitem->SubClass)
1397 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);
1398 // It safe let use Subclass from DB
1402 if(proto->Unk0 != dbcitem->Unk0)
1404 sLog.outErrorDb("Item (Entry: %u) not correct %i Unk0, must be %i (still using DB value).",i,proto->Unk0,dbcitem->Unk0);
1405 // It safe let use Unk0 from DB
1408 if(proto->Material != dbcitem->Material)
1410 sLog.outErrorDb("Item (Entry: %u) not correct %i material, must be %i (still using DB value).",i,proto->Material,dbcitem->Material);
1411 // It safe let use Material from DB
1414 if(proto->InventoryType != dbcitem->InventoryType)
1416 sLog.outErrorDb("Item (Entry: %u) not correct %u inventory type, must be %u (still using DB value).",i,proto->InventoryType,dbcitem->InventoryType);
1417 // It safe let use InventoryType from DB
1420 if(proto->DisplayInfoID != dbcitem->DisplayId)
1422 sLog.outErrorDb("Item (Entry: %u) not correct %u display id, must be %u (using it).",i,proto->DisplayInfoID,dbcitem->DisplayId);
1423 const_cast<ItemPrototype*>(proto)->DisplayInfoID = dbcitem->DisplayId;
1425 if(proto->Sheath != dbcitem->Sheath)
1427 sLog.outErrorDb("Item (Entry: %u) not correct %u sheath, must be %u (using it).",i,proto->Sheath,dbcitem->Sheath);
1428 const_cast<ItemPrototype*>(proto)->Sheath = dbcitem->Sheath;
1431 else
1433 sLog.outErrorDb("Item (Entry: %u) not correct (not listed in list of existed items).",i);
1436 if(proto->Class >= MAX_ITEM_CLASS)
1438 sLog.outErrorDb("Item (Entry: %u) has wrong Class value (%u)",i,proto->Class);
1439 const_cast<ItemPrototype*>(proto)->Class = ITEM_CLASS_MISC;
1442 if(proto->SubClass >= MaxItemSubclassValues[proto->Class])
1444 sLog.outErrorDb("Item (Entry: %u) has wrong Subclass value (%u) for class %u",i,proto->SubClass,proto->Class);
1445 const_cast<ItemPrototype*>(proto)->SubClass = 0;// exist for all item classes
1448 if(proto->Quality >= MAX_ITEM_QUALITY)
1450 sLog.outErrorDb("Item (Entry: %u) has wrong Quality value (%u)",i,proto->Quality);
1451 const_cast<ItemPrototype*>(proto)->Quality = ITEM_QUALITY_NORMAL;
1454 if(proto->BuyCount <= 0)
1456 sLog.outErrorDb("Item (Entry: %u) has wrong BuyCount value (%u), set to default(1).",i,proto->BuyCount);
1457 const_cast<ItemPrototype*>(proto)->BuyCount = 1;
1460 if(proto->InventoryType >= MAX_INVTYPE)
1462 sLog.outErrorDb("Item (Entry: %u) has wrong InventoryType value (%u)",i,proto->InventoryType);
1463 const_cast<ItemPrototype*>(proto)->InventoryType = INVTYPE_NON_EQUIP;
1466 if(proto->RequiredSkill >= MAX_SKILL_TYPE)
1468 sLog.outErrorDb("Item (Entry: %u) has wrong RequiredSkill value (%u)",i,proto->RequiredSkill);
1469 const_cast<ItemPrototype*>(proto)->RequiredSkill = 0;
1474 // can be used in equip slot, as page read use in inventory, or spell casting at use
1475 bool req = proto->InventoryType!=INVTYPE_NON_EQUIP || proto->PageText;
1476 if(!req)
1478 for (int j = 0; j < MAX_ITEM_PROTO_SPELLS; ++j)
1480 if(proto->Spells[j].SpellId)
1482 req = true;
1483 break;
1488 if(req)
1490 if(!(proto->AllowableClass & CLASSMASK_ALL_PLAYABLE))
1491 sLog.outErrorDb("Item (Entry: %u) not have in `AllowableClass` any playable classes (%u) and can't be equipped or use.",i,proto->AllowableClass);
1493 if(!(proto->AllowableRace & RACEMASK_ALL_PLAYABLE))
1494 sLog.outErrorDb("Item (Entry: %u) not have in `AllowableRace` any playable races (%u) and can't be equipped or use.",i,proto->AllowableRace);
1498 if(proto->RequiredSpell && !sSpellStore.LookupEntry(proto->RequiredSpell))
1500 sLog.outErrorDb("Item (Entry: %u) have wrong (non-existed) spell in RequiredSpell (%u)",i,proto->RequiredSpell);
1501 const_cast<ItemPrototype*>(proto)->RequiredSpell = 0;
1504 if(proto->RequiredReputationRank >= MAX_REPUTATION_RANK)
1505 sLog.outErrorDb("Item (Entry: %u) has wrong reputation rank in RequiredReputationRank (%u), item can't be used.",i,proto->RequiredReputationRank);
1507 if(proto->RequiredReputationFaction)
1509 if(!sFactionStore.LookupEntry(proto->RequiredReputationFaction))
1511 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) faction in RequiredReputationFaction (%u)",i,proto->RequiredReputationFaction);
1512 const_cast<ItemPrototype*>(proto)->RequiredReputationFaction = 0;
1515 if(proto->RequiredReputationRank == MIN_REPUTATION_RANK)
1516 sLog.outErrorDb("Item (Entry: %u) has min. reputation rank in RequiredReputationRank (0) but RequiredReputationFaction > 0, faction setting is useless.",i);
1518 else if(proto->RequiredReputationRank > MIN_REPUTATION_RANK)
1519 sLog.outErrorDb("Item (Entry: %u) has RequiredReputationFaction ==0 but RequiredReputationRank > 0, rank setting is useless.",i);
1521 if(proto->MaxCount < -1)
1523 sLog.outErrorDb("Item (Entry: %u) has too large negative in maxcount (%i), replace by value (-1) no storing limits.",i,proto->MaxCount);
1524 const_cast<ItemPrototype*>(proto)->MaxCount = -1;
1527 if(proto->Stackable==0)
1529 sLog.outErrorDb("Item (Entry: %u) has wrong value in stackable (%i), replace by default 1.",i,proto->Stackable);
1530 const_cast<ItemPrototype*>(proto)->Stackable = 1;
1532 else if(proto->Stackable < -1)
1534 sLog.outErrorDb("Item (Entry: %u) has too large negative in stackable (%i), replace by value (-1) no stacking limits.",i,proto->Stackable);
1535 const_cast<ItemPrototype*>(proto)->Stackable = -1;
1537 else if(proto->Stackable > 255)
1539 sLog.outErrorDb("Item (Entry: %u) has too large value in stackable (%u), replace by hardcoded upper limit (255).",i,proto->Stackable);
1540 const_cast<ItemPrototype*>(proto)->Stackable = 255;
1543 if(proto->StatsCount > MAX_ITEM_PROTO_STATS)
1545 sLog.outErrorDb("Item (Entry: %u) has too large value in statscount (%u), replace by hardcoded limit (%u).",i,proto->StatsCount,MAX_ITEM_PROTO_STATS);
1546 const_cast<ItemPrototype*>(proto)->StatsCount = MAX_ITEM_PROTO_STATS;
1549 for (int j = 0; j < MAX_ITEM_PROTO_STATS; ++j)
1551 // for ItemStatValue != 0
1552 if(proto->ItemStat[j].ItemStatValue && proto->ItemStat[j].ItemStatType >= MAX_ITEM_MOD)
1554 sLog.outErrorDb("Item (Entry: %u) has wrong stat_type%d (%u)",i,j+1,proto->ItemStat[j].ItemStatType);
1555 const_cast<ItemPrototype*>(proto)->ItemStat[j].ItemStatType = 0;
1559 for (int j = 0; j < MAX_ITEM_PROTO_DAMAGES; ++j)
1561 if(proto->Damage[j].DamageType >= MAX_SPELL_SCHOOL)
1563 sLog.outErrorDb("Item (Entry: %u) has wrong dmg_type%d (%u)",i,j+1,proto->Damage[j].DamageType);
1564 const_cast<ItemPrototype*>(proto)->Damage[j].DamageType = 0;
1568 // special format
1569 if((proto->Spells[0].SpellId == SPELL_ID_GENERIC_LEARN) || (proto->Spells[0].SpellId == SPELL_ID_GENERIC_LEARN_PET))
1571 // spell_1
1572 if(proto->Spells[0].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
1574 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);
1575 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1576 const_cast<ItemPrototype*>(proto)->Spells[0].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1577 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1578 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1581 // spell_2 have learning spell
1582 if(proto->Spells[1].SpellTrigger != ITEM_SPELLTRIGGER_LEARN_SPELL_ID)
1584 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);
1585 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1586 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1587 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1589 else if(!proto->Spells[1].SpellId)
1591 sLog.outErrorDb("Item (Entry: %u) not has expected spell in spellid_%d in special learning format.",i,1+1);
1592 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1593 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1595 else
1597 SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[1].SpellId);
1598 if(!spellInfo)
1600 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%u)",i,1+1,proto->Spells[1].SpellId);
1601 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1602 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1603 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1605 // allowed only in special format
1606 else if((proto->Spells[1].SpellId==SPELL_ID_GENERIC_LEARN) || (proto->Spells[1].SpellId==SPELL_ID_GENERIC_LEARN_PET))
1608 sLog.outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%u)",i,1+1,proto->Spells[1].SpellId);
1609 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1610 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1611 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1615 // spell_3*,spell_4*,spell_5* is empty
1616 for (int j = 2; j < MAX_ITEM_PROTO_SPELLS; ++j)
1618 if(proto->Spells[j].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
1620 sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)",i,j+1,proto->Spells[j].SpellTrigger);
1621 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1622 const_cast<ItemPrototype*>(proto)->Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1624 else if(proto->Spells[j].SpellId != 0)
1626 sLog.outErrorDb("Item (Entry: %u) has wrong spell in spellid_%d (%u) for learning special format",i,j+1,proto->Spells[j].SpellId);
1627 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1631 // normal spell list
1632 else
1634 for (int j = 0; j < MAX_ITEM_PROTO_SPELLS; ++j)
1636 if(proto->Spells[j].SpellTrigger >= MAX_ITEM_SPELLTRIGGER || proto->Spells[j].SpellTrigger == ITEM_SPELLTRIGGER_LEARN_SPELL_ID)
1638 sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)",i,j+1,proto->Spells[j].SpellTrigger);
1639 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1640 const_cast<ItemPrototype*>(proto)->Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1643 if(proto->Spells[j].SpellId)
1645 SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[j].SpellId);
1646 if(!spellInfo)
1648 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%u)",i,j+1,proto->Spells[j].SpellId);
1649 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1651 // allowed only in special format
1652 else if((proto->Spells[j].SpellId==SPELL_ID_GENERIC_LEARN) || (proto->Spells[j].SpellId==SPELL_ID_GENERIC_LEARN_PET))
1654 sLog.outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%u)",i,j+1,proto->Spells[j].SpellId);
1655 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1661 if(proto->Bonding >= MAX_BIND_TYPE)
1662 sLog.outErrorDb("Item (Entry: %u) has wrong Bonding value (%u)",i,proto->Bonding);
1664 if(proto->PageText && !sPageTextStore.LookupEntry<PageText>(proto->PageText))
1665 sLog.outErrorDb("Item (Entry: %u) has non existing first page (Id:%u)", i,proto->PageText);
1667 if(proto->LockID && !sLockStore.LookupEntry(proto->LockID))
1668 sLog.outErrorDb("Item (Entry: %u) has wrong LockID (%u)",i,proto->LockID);
1670 if(proto->Sheath >= MAX_SHEATHETYPE)
1672 sLog.outErrorDb("Item (Entry: %u) has wrong Sheath (%u)",i,proto->Sheath);
1673 const_cast<ItemPrototype*>(proto)->Sheath = SHEATHETYPE_NONE;
1676 if(proto->RandomProperty && !sItemRandomPropertiesStore.LookupEntry(GetItemEnchantMod(proto->RandomProperty)))
1678 sLog.outErrorDb("Item (Entry: %u) has unknown (wrong or not listed in `item_enchantment_template`) RandomProperty (%u)",i,proto->RandomProperty);
1679 const_cast<ItemPrototype*>(proto)->RandomProperty = 0;
1682 if(proto->RandomSuffix && !sItemRandomSuffixStore.LookupEntry(GetItemEnchantMod(proto->RandomSuffix)))
1684 sLog.outErrorDb("Item (Entry: %u) has wrong RandomSuffix (%u)",i,proto->RandomSuffix);
1685 const_cast<ItemPrototype*>(proto)->RandomSuffix = 0;
1688 if(proto->ItemSet && !sItemSetStore.LookupEntry(proto->ItemSet))
1690 sLog.outErrorDb("Item (Entry: %u) have wrong ItemSet (%u)",i,proto->ItemSet);
1691 const_cast<ItemPrototype*>(proto)->ItemSet = 0;
1694 if(proto->Area && !GetAreaEntryByAreaID(proto->Area))
1695 sLog.outErrorDb("Item (Entry: %u) has wrong Area (%u)",i,proto->Area);
1697 if(proto->Map && !sMapStore.LookupEntry(proto->Map))
1698 sLog.outErrorDb("Item (Entry: %u) has wrong Map (%u)",i,proto->Map);
1700 if(proto->TotemCategory && !sTotemCategoryStore.LookupEntry(proto->TotemCategory))
1701 sLog.outErrorDb("Item (Entry: %u) has wrong TotemCategory (%u)",i,proto->TotemCategory);
1703 for (int j = 0; j < MAX_ITEM_PROTO_SOCKETS; j++)
1705 if(proto->Socket[j].Color && (proto->Socket[j].Color & SOCKET_COLOR_ALL) != proto->Socket[j].Color)
1707 sLog.outErrorDb("Item (Entry: %u) has wrong socketColor_%d (%u)",i,j+1,proto->Socket[j].Color);
1708 const_cast<ItemPrototype*>(proto)->Socket[j].Color = 0;
1712 if(proto->GemProperties && !sGemPropertiesStore.LookupEntry(proto->GemProperties))
1713 sLog.outErrorDb("Item (Entry: %u) has wrong GemProperties (%u)",i,proto->GemProperties);
1715 if(proto->FoodType >= MAX_PET_DIET)
1717 sLog.outErrorDb("Item (Entry: %u) has wrong FoodType value (%u)",i,proto->FoodType);
1718 const_cast<ItemPrototype*>(proto)->FoodType = 0;
1721 if(proto->ItemLimitCategory && !sItemLimitCategoryStore.LookupEntry(proto->ItemLimitCategory))
1723 sLog.outErrorDb("Item (Entry: %u) has wrong LimitCategory value (%u)",i,proto->ItemLimitCategory);
1724 const_cast<ItemPrototype*>(proto)->ItemLimitCategory = 0;
1729 void ObjectMgr::LoadPetLevelInfo()
1731 // Loading levels data
1733 // 0 1 2 3 4 5 6 7 8 9
1734 QueryResult *result = WorldDatabase.Query("SELECT creature_entry, level, hp, mana, str, agi, sta, inte, spi, armor FROM pet_levelstats");
1736 uint32 count = 0;
1738 if (!result)
1740 barGoLink bar( 1 );
1742 sLog.outString();
1743 sLog.outString( ">> Loaded %u level pet stats definitions", count );
1744 sLog.outErrorDb( "Error loading `pet_levelstats` table or empty table.");
1745 return;
1748 barGoLink bar( result->GetRowCount() );
1752 Field* fields = result->Fetch();
1754 uint32 creature_id = fields[0].GetUInt32();
1755 if(!sCreatureStorage.LookupEntry<CreatureInfo>(creature_id))
1757 sLog.outErrorDb("Wrong creature id %u in `pet_levelstats` table, ignoring.",creature_id);
1758 continue;
1761 uint32 current_level = fields[1].GetUInt32();
1762 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
1764 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
1765 sLog.outErrorDb("Wrong (> %u) level %u in `pet_levelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
1766 else
1768 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `pet_levelstats` table, ignoring.",current_level);
1769 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
1771 continue;
1773 else if(current_level < 1)
1775 sLog.outErrorDb("Wrong (<1) level %u in `pet_levelstats` table, ignoring.",current_level);
1776 continue;
1779 PetLevelInfo*& pInfoMapEntry = petInfo[creature_id];
1781 if(pInfoMapEntry==NULL)
1782 pInfoMapEntry = new PetLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
1784 // data for level 1 stored in [0] array element, ...
1785 PetLevelInfo* pLevelInfo = &pInfoMapEntry[current_level-1];
1787 pLevelInfo->health = fields[2].GetUInt16();
1788 pLevelInfo->mana = fields[3].GetUInt16();
1789 pLevelInfo->armor = fields[9].GetUInt16();
1791 for (int i = 0; i < MAX_STATS; i++)
1793 pLevelInfo->stats[i] = fields[i+4].GetUInt16();
1796 bar.step();
1797 ++count;
1799 while (result->NextRow());
1801 delete result;
1803 sLog.outString();
1804 sLog.outString( ">> Loaded %u level pet stats definitions", count );
1807 // Fill gaps and check integrity
1808 for (PetLevelInfoMap::iterator itr = petInfo.begin(); itr != petInfo.end(); ++itr)
1810 PetLevelInfo* pInfo = itr->second;
1812 // fatal error if no level 1 data
1813 if(!pInfo || pInfo[0].health == 0 )
1815 sLog.outErrorDb("Creature %u does not have pet stats data for Level 1!",itr->first);
1816 exit(1);
1819 // fill level gaps
1820 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
1822 if(pInfo[level].health == 0)
1824 sLog.outErrorDb("Creature %u has no data for Level %i pet stats data, using data of Level %i.",itr->first,level+1, level);
1825 pInfo[level] = pInfo[level-1];
1831 PetLevelInfo const* ObjectMgr::GetPetLevelInfo(uint32 creature_id, uint32 level) const
1833 if(level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
1834 level = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL);
1836 PetLevelInfoMap::const_iterator itr = petInfo.find(creature_id);
1837 if(itr == petInfo.end())
1838 return NULL;
1840 return &itr->second[level-1]; // data for level 1 stored in [0] array element, ...
1843 void ObjectMgr::LoadPlayerInfo()
1845 // Load playercreate
1847 // 0 1 2 3 4 5 6
1848 QueryResult *result = WorldDatabase.Query("SELECT race, class, map, zone, position_x, position_y, position_z FROM playercreateinfo");
1850 uint32 count = 0;
1852 if (!result)
1854 barGoLink bar( 1 );
1856 sLog.outString();
1857 sLog.outString( ">> Loaded %u player create definitions", count );
1858 sLog.outErrorDb( "Error loading `playercreateinfo` table or empty table.");
1859 exit(1);
1862 barGoLink bar( result->GetRowCount() );
1866 Field* fields = result->Fetch();
1868 uint32 current_race = fields[0].GetUInt32();
1869 uint32 current_class = fields[1].GetUInt32();
1870 uint32 mapId = fields[2].GetUInt32();
1871 uint32 zoneId = fields[3].GetUInt32();
1872 float positionX = fields[4].GetFloat();
1873 float positionY = fields[5].GetFloat();
1874 float positionZ = fields[6].GetFloat();
1876 if(current_race >= MAX_RACES)
1878 sLog.outErrorDb("Wrong race %u in `playercreateinfo` table, ignoring.",current_race);
1879 continue;
1882 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(current_race);
1883 if(!rEntry)
1885 sLog.outErrorDb("Wrong race %u in `playercreateinfo` table, ignoring.",current_race);
1886 continue;
1889 if(current_class >= MAX_CLASSES)
1891 sLog.outErrorDb("Wrong class %u in `playercreateinfo` table, ignoring.",current_class);
1892 continue;
1895 if(!sChrClassesStore.LookupEntry(current_class))
1897 sLog.outErrorDb("Wrong class %u in `playercreateinfo` table, ignoring.",current_class);
1898 continue;
1901 // accept DB data only for valid position (and non instanceable)
1902 if( !MapManager::IsValidMapCoord(mapId,positionX,positionY,positionZ) )
1904 sLog.outErrorDb("Wrong home position for class %u race %u pair in `playercreateinfo` table, ignoring.",current_class,current_race);
1905 continue;
1908 if( sMapStore.LookupEntry(mapId)->Instanceable() )
1910 sLog.outErrorDb("Home position in instanceable map for class %u race %u pair in `playercreateinfo` table, ignoring.",current_class,current_race);
1911 continue;
1914 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
1916 pInfo->mapId = mapId;
1917 pInfo->zoneId = zoneId;
1918 pInfo->positionX = positionX;
1919 pInfo->positionY = positionY;
1920 pInfo->positionZ = positionZ;
1922 pInfo->displayId_m = rEntry->model_m;
1923 pInfo->displayId_f = rEntry->model_f;
1925 bar.step();
1926 ++count;
1928 while (result->NextRow());
1930 delete result;
1932 sLog.outString();
1933 sLog.outString( ">> Loaded %u player create definitions", count );
1936 // Load playercreate items
1938 // 0 1 2 3
1939 QueryResult *result = WorldDatabase.Query("SELECT race, class, itemid, amount FROM playercreateinfo_item");
1941 uint32 count = 0;
1943 if (!result)
1945 barGoLink bar( 1 );
1947 bar.step();
1949 sLog.outString();
1950 sLog.outString( ">> Loaded %u custom player create items", count );
1952 else
1954 barGoLink bar( result->GetRowCount() );
1958 Field* fields = result->Fetch();
1960 uint32 current_race = fields[0].GetUInt32();
1961 if(current_race >= MAX_RACES)
1963 sLog.outErrorDb("Wrong race %u in `playercreateinfo_item` table, ignoring.",current_race);
1964 continue;
1967 uint32 current_class = fields[1].GetUInt32();
1968 if(current_class >= MAX_CLASSES)
1970 sLog.outErrorDb("Wrong class %u in `playercreateinfo_item` table, ignoring.",current_class);
1971 continue;
1974 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
1976 uint32 item_id = fields[2].GetUInt32();
1978 if(!GetItemPrototype(item_id))
1980 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);
1981 continue;
1984 uint32 amount = fields[3].GetUInt32();
1986 if(!amount)
1988 sLog.outErrorDb("Item id %u (class %u race %u) have amount==0 in `playercreateinfo_item` table, ignoring.",item_id,current_race,current_class);
1989 continue;
1992 pInfo->item.push_back(PlayerCreateInfoItem( item_id, amount));
1994 bar.step();
1995 ++count;
1997 while(result->NextRow());
1999 delete result;
2001 sLog.outString();
2002 sLog.outString( ">> Loaded %u custom player create items", count );
2006 // Load playercreate spells
2008 // 0 1 2
2009 QueryResult *result = WorldDatabase.Query("SELECT race, class, Spell FROM playercreateinfo_spell");
2011 uint32 count = 0;
2013 if (!result)
2015 barGoLink bar( 1 );
2017 sLog.outString();
2018 sLog.outString( ">> Loaded %u player create spells", count );
2019 sLog.outErrorDb( "Error loading `playercreateinfo_spell` table or empty table.");
2021 else
2023 barGoLink bar( result->GetRowCount() );
2027 Field* fields = result->Fetch();
2029 uint32 current_race = fields[0].GetUInt32();
2030 if(current_race >= MAX_RACES)
2032 sLog.outErrorDb("Wrong race %u in `playercreateinfo_spell` table, ignoring.",current_race);
2033 continue;
2036 uint32 current_class = fields[1].GetUInt32();
2037 if(current_class >= MAX_CLASSES)
2039 sLog.outErrorDb("Wrong class %u in `playercreateinfo_spell` table, ignoring.",current_class);
2040 continue;
2043 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2044 pInfo->spell.push_back(fields[2].GetUInt32());
2046 bar.step();
2047 ++count;
2049 while( result->NextRow() );
2051 delete result;
2053 sLog.outString();
2054 sLog.outString( ">> Loaded %u player create spells", count );
2058 // Load playercreate actions
2060 // 0 1 2 3 4 5
2061 QueryResult *result = WorldDatabase.Query("SELECT race, class, button, action, type, misc FROM playercreateinfo_action");
2063 uint32 count = 0;
2065 if (!result)
2067 barGoLink bar( 1 );
2069 sLog.outString();
2070 sLog.outString( ">> Loaded %u player create actions", count );
2071 sLog.outErrorDb( "Error loading `playercreateinfo_action` table or empty table.");
2073 else
2075 barGoLink bar( result->GetRowCount() );
2079 Field* fields = result->Fetch();
2081 uint32 current_race = fields[0].GetUInt32();
2082 if(current_race >= MAX_RACES)
2084 sLog.outErrorDb("Wrong race %u in `playercreateinfo_action` table, ignoring.",current_race);
2085 continue;
2088 uint32 current_class = fields[1].GetUInt32();
2089 if(current_class >= MAX_CLASSES)
2091 sLog.outErrorDb("Wrong class %u in `playercreateinfo_action` table, ignoring.",current_class);
2092 continue;
2095 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2096 pInfo->action[0].push_back(fields[2].GetUInt16());
2097 pInfo->action[1].push_back(fields[3].GetUInt16());
2098 pInfo->action[2].push_back(fields[4].GetUInt16());
2099 pInfo->action[3].push_back(fields[5].GetUInt16());
2101 bar.step();
2102 ++count;
2104 while( result->NextRow() );
2106 delete result;
2108 sLog.outString();
2109 sLog.outString( ">> Loaded %u player create actions", count );
2113 // Loading levels data (class only dependent)
2115 // 0 1 2 3
2116 QueryResult *result = WorldDatabase.Query("SELECT class, level, basehp, basemana FROM player_classlevelstats");
2118 uint32 count = 0;
2120 if (!result)
2122 barGoLink bar( 1 );
2124 sLog.outString();
2125 sLog.outString( ">> Loaded %u level health/mana definitions", count );
2126 sLog.outErrorDb( "Error loading `player_classlevelstats` table or empty table.");
2127 exit(1);
2130 barGoLink bar( result->GetRowCount() );
2134 Field* fields = result->Fetch();
2136 uint32 current_class = fields[0].GetUInt32();
2137 if(current_class >= MAX_CLASSES)
2139 sLog.outErrorDb("Wrong class %u in `player_classlevelstats` table, ignoring.",current_class);
2140 continue;
2143 uint32 current_level = fields[1].GetUInt32();
2144 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2146 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2147 sLog.outErrorDb("Wrong (> %u) level %u in `player_classlevelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
2148 else
2150 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_classlevelstats` table, ignoring.",current_level);
2151 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
2153 continue;
2156 PlayerClassInfo* pClassInfo = &playerClassInfo[current_class];
2158 if(!pClassInfo->levelInfo)
2159 pClassInfo->levelInfo = new PlayerClassLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
2161 PlayerClassLevelInfo* pClassLevelInfo = &pClassInfo->levelInfo[current_level-1];
2163 pClassLevelInfo->basehealth = fields[2].GetUInt16();
2164 pClassLevelInfo->basemana = fields[3].GetUInt16();
2166 bar.step();
2167 ++count;
2169 while (result->NextRow());
2171 delete result;
2173 sLog.outString();
2174 sLog.outString( ">> Loaded %u level health/mana definitions", count );
2177 // Fill gaps and check integrity
2178 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2180 // skip non existed classes
2181 if(!sChrClassesStore.LookupEntry(class_))
2182 continue;
2184 PlayerClassInfo* pClassInfo = &playerClassInfo[class_];
2186 // fatal error if no level 1 data
2187 if(!pClassInfo->levelInfo || pClassInfo->levelInfo[0].basehealth == 0 )
2189 sLog.outErrorDb("Class %i Level 1 does not have health/mana data!",class_);
2190 exit(1);
2193 // fill level gaps
2194 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2196 if(pClassInfo->levelInfo[level].basehealth == 0)
2198 sLog.outErrorDb("Class %i Level %i does not have health/mana data. Using stats data of level %i.",class_,level+1, level);
2199 pClassInfo->levelInfo[level] = pClassInfo->levelInfo[level-1];
2204 // Loading levels data (class/race dependent)
2206 // 0 1 2 3 4 5 6 7
2207 QueryResult *result = WorldDatabase.Query("SELECT race, class, level, str, agi, sta, inte, spi FROM player_levelstats");
2209 uint32 count = 0;
2211 if (!result)
2213 barGoLink bar( 1 );
2215 sLog.outString();
2216 sLog.outString( ">> Loaded %u level stats definitions", count );
2217 sLog.outErrorDb( "Error loading `player_levelstats` table or empty table.");
2218 exit(1);
2221 barGoLink bar( result->GetRowCount() );
2225 Field* fields = result->Fetch();
2227 uint32 current_race = fields[0].GetUInt32();
2228 if(current_race >= MAX_RACES)
2230 sLog.outErrorDb("Wrong race %u in `player_levelstats` table, ignoring.",current_race);
2231 continue;
2234 uint32 current_class = fields[1].GetUInt32();
2235 if(current_class >= MAX_CLASSES)
2237 sLog.outErrorDb("Wrong class %u in `player_levelstats` table, ignoring.",current_class);
2238 continue;
2241 uint32 current_level = fields[2].GetUInt32();
2242 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2244 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2245 sLog.outErrorDb("Wrong (> %u) level %u in `player_levelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
2246 else
2248 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_levelstats` table, ignoring.",current_level);
2249 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
2251 continue;
2254 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2256 if(!pInfo->levelInfo)
2257 pInfo->levelInfo = new PlayerLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
2259 PlayerLevelInfo* pLevelInfo = &pInfo->levelInfo[current_level-1];
2261 for (int i = 0; i < MAX_STATS; i++)
2263 pLevelInfo->stats[i] = fields[i+3].GetUInt8();
2266 bar.step();
2267 ++count;
2269 while (result->NextRow());
2271 delete result;
2273 sLog.outString();
2274 sLog.outString( ">> Loaded %u level stats definitions", count );
2277 // Fill gaps and check integrity
2278 for (int race = 0; race < MAX_RACES; ++race)
2280 // skip non existed races
2281 if(!sChrRacesStore.LookupEntry(race))
2282 continue;
2284 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2286 // skip non existed classes
2287 if(!sChrClassesStore.LookupEntry(class_))
2288 continue;
2290 PlayerInfo* pInfo = &playerInfo[race][class_];
2292 // skip non loaded combinations
2293 if(!pInfo->displayId_m || !pInfo->displayId_f)
2294 continue;
2296 // skip expansion races if not playing with expansion
2297 if (sWorld.getConfig(CONFIG_EXPANSION) < 1 && (race == RACE_BLOODELF || race == RACE_DRAENEI))
2298 continue;
2300 // skip expansion classes if not playing with expansion
2301 if (sWorld.getConfig(CONFIG_EXPANSION) < 2 && class_ == CLASS_DEATH_KNIGHT)
2302 continue;
2304 // fatal error if no level 1 data
2305 if(!pInfo->levelInfo || pInfo->levelInfo[0].stats[0] == 0 )
2307 sLog.outErrorDb("Race %i Class %i Level 1 does not have stats data!",race,class_);
2308 exit(1);
2311 // fill level gaps
2312 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2314 if(pInfo->levelInfo[level].stats[0] == 0)
2316 sLog.outErrorDb("Race %i Class %i Level %i does not have stats data. Using stats data of level %i.",race,class_,level+1, level);
2317 pInfo->levelInfo[level] = pInfo->levelInfo[level-1];
2323 // Loading xp per level data
2325 mPlayerXPperLevel.resize(sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL));
2326 for (uint32 level = 0; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2327 mPlayerXPperLevel[level] = 0;
2329 // 0 1
2330 QueryResult *result = WorldDatabase.Query("SELECT lvl, xp_for_next_level FROM player_xp_for_level");
2332 uint32 count = 0;
2334 if (!result)
2336 barGoLink bar( 1 );
2338 sLog.outString();
2339 sLog.outString( ">> Loaded %u xp for level definitions", count );
2340 sLog.outErrorDb( "Error loading `player_xp_for_level` table or empty table.");
2341 exit(1);
2344 barGoLink bar( result->GetRowCount() );
2348 Field* fields = result->Fetch();
2350 uint32 current_level = fields[0].GetUInt32();
2351 uint32 current_xp = fields[1].GetUInt32();
2353 if(current_level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2355 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2356 sLog.outErrorDb("Wrong (> %u) level %u in `player_xp_for_level` table, ignoring.", STRONG_MAX_LEVEL,current_level);
2357 else
2359 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_xp_for_levels` table, ignoring.",current_level);
2360 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
2362 continue;
2364 //PlayerXPperLevel
2365 mPlayerXPperLevel[current_level] = current_xp;
2366 bar.step();
2367 ++count;
2369 while (result->NextRow());
2371 delete result;
2373 sLog.outString();
2374 sLog.outString( ">> Loaded %u xp for level definitions", count );
2377 // fill level gaps
2378 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2380 if( mPlayerXPperLevel[level] == 0)
2382 sLog.outErrorDb("Level %i does not have XP for level data. Using data of level [%i] + 100.",level+1, level);
2383 mPlayerXPperLevel[level] = mPlayerXPperLevel[level-1]+100;
2388 void ObjectMgr::GetPlayerClassLevelInfo(uint32 class_, uint32 level, PlayerClassLevelInfo* info) const
2390 if(level < 1 || class_ >= MAX_CLASSES)
2391 return;
2393 PlayerClassInfo const* pInfo = &playerClassInfo[class_];
2395 if(level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2396 level = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL);
2398 *info = pInfo->levelInfo[level-1];
2401 void ObjectMgr::GetPlayerLevelInfo(uint32 race, uint32 class_, uint32 level, PlayerLevelInfo* info) const
2403 if(level < 1 || race >= MAX_RACES || class_ >= MAX_CLASSES)
2404 return;
2406 PlayerInfo const* pInfo = &playerInfo[race][class_];
2407 if(pInfo->displayId_m==0 || pInfo->displayId_f==0)
2408 return;
2410 if(level <= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2411 *info = pInfo->levelInfo[level-1];
2412 else
2413 BuildPlayerLevelInfo(race,class_,level,info);
2416 void ObjectMgr::BuildPlayerLevelInfo(uint8 race, uint8 _class, uint8 level, PlayerLevelInfo* info) const
2418 // base data (last known level)
2419 *info = playerInfo[race][_class].levelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)-1];
2421 for(int lvl = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)-1; lvl < level; ++lvl)
2423 switch(_class)
2425 case CLASS_WARRIOR:
2426 info->stats[STAT_STRENGTH] += (lvl > 23 ? 2: (lvl > 1 ? 1: 0));
2427 info->stats[STAT_STAMINA] += (lvl > 23 ? 2: (lvl > 1 ? 1: 0));
2428 info->stats[STAT_AGILITY] += (lvl > 36 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2429 info->stats[STAT_INTELLECT] += (lvl > 9 && !(lvl%2) ? 1: 0);
2430 info->stats[STAT_SPIRIT] += (lvl > 9 && !(lvl%2) ? 1: 0);
2431 break;
2432 case CLASS_PALADIN:
2433 info->stats[STAT_STRENGTH] += (lvl > 3 ? 1: 0);
2434 info->stats[STAT_STAMINA] += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2435 info->stats[STAT_AGILITY] += (lvl > 38 ? 1: (lvl > 7 && !(lvl%2) ? 1: 0));
2436 info->stats[STAT_INTELLECT] += (lvl > 6 && (lvl%2) ? 1: 0);
2437 info->stats[STAT_SPIRIT] += (lvl > 7 ? 1: 0);
2438 break;
2439 case CLASS_HUNTER:
2440 info->stats[STAT_STRENGTH] += (lvl > 4 ? 1: 0);
2441 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2442 info->stats[STAT_AGILITY] += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2443 info->stats[STAT_INTELLECT] += (lvl > 8 && (lvl%2) ? 1: 0);
2444 info->stats[STAT_SPIRIT] += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2445 break;
2446 case CLASS_ROGUE:
2447 info->stats[STAT_STRENGTH] += (lvl > 5 ? 1: 0);
2448 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2449 info->stats[STAT_AGILITY] += (lvl > 16 ? 2: (lvl > 1 ? 1: 0));
2450 info->stats[STAT_INTELLECT] += (lvl > 8 && !(lvl%2) ? 1: 0);
2451 info->stats[STAT_SPIRIT] += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2452 break;
2453 case CLASS_PRIEST:
2454 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2455 info->stats[STAT_STAMINA] += (lvl > 5 ? 1: 0);
2456 info->stats[STAT_AGILITY] += (lvl > 38 ? 1: (lvl > 8 && (lvl%2) ? 1: 0));
2457 info->stats[STAT_INTELLECT] += (lvl > 22 ? 2: (lvl > 1 ? 1: 0));
2458 info->stats[STAT_SPIRIT] += (lvl > 3 ? 1: 0);
2459 break;
2460 case CLASS_SHAMAN:
2461 info->stats[STAT_STRENGTH] += (lvl > 34 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2462 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2463 info->stats[STAT_AGILITY] += (lvl > 7 && !(lvl%2) ? 1: 0);
2464 info->stats[STAT_INTELLECT] += (lvl > 5 ? 1: 0);
2465 info->stats[STAT_SPIRIT] += (lvl > 4 ? 1: 0);
2466 break;
2467 case CLASS_MAGE:
2468 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2469 info->stats[STAT_STAMINA] += (lvl > 5 ? 1: 0);
2470 info->stats[STAT_AGILITY] += (lvl > 9 && !(lvl%2) ? 1: 0);
2471 info->stats[STAT_INTELLECT] += (lvl > 24 ? 2: (lvl > 1 ? 1: 0));
2472 info->stats[STAT_SPIRIT] += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
2473 break;
2474 case CLASS_WARLOCK:
2475 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2476 info->stats[STAT_STAMINA] += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
2477 info->stats[STAT_AGILITY] += (lvl > 9 && !(lvl%2) ? 1: 0);
2478 info->stats[STAT_INTELLECT] += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
2479 info->stats[STAT_SPIRIT] += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
2480 break;
2481 case CLASS_DRUID:
2482 info->stats[STAT_STRENGTH] += (lvl > 38 ? 2: (lvl > 6 && (lvl%2) ? 1: 0));
2483 info->stats[STAT_STAMINA] += (lvl > 32 ? 2: (lvl > 4 ? 1: 0));
2484 info->stats[STAT_AGILITY] += (lvl > 38 ? 2: (lvl > 8 && (lvl%2) ? 1: 0));
2485 info->stats[STAT_INTELLECT] += (lvl > 38 ? 3: (lvl > 4 ? 1: 0));
2486 info->stats[STAT_SPIRIT] += (lvl > 38 ? 3: (lvl > 5 ? 1: 0));
2491 void ObjectMgr::LoadGuilds()
2493 Guild *newguild;
2494 uint32 count = 0;
2496 QueryResult *result = CharacterDatabase.Query( "SELECT guildid FROM guild" );
2498 if( !result )
2501 barGoLink bar( 1 );
2503 bar.step();
2505 sLog.outString();
2506 sLog.outString( ">> Loaded %u guild definitions", count );
2507 return;
2510 barGoLink bar( result->GetRowCount() );
2514 Field *fields = result->Fetch();
2516 bar.step();
2517 ++count;
2519 newguild = new Guild;
2520 if(!newguild->LoadGuildFromDB(fields[0].GetUInt32()))
2522 newguild->Disband();
2523 delete newguild;
2524 continue;
2526 AddGuild(newguild);
2528 }while( result->NextRow() );
2530 delete result;
2532 sLog.outString();
2533 sLog.outString( ">> Loaded %u guild definitions", count );
2536 void ObjectMgr::LoadArenaTeams()
2538 uint32 count = 0;
2540 QueryResult *result = CharacterDatabase.Query( "SELECT arenateamid FROM arena_team" );
2542 if( !result )
2545 barGoLink bar( 1 );
2547 bar.step();
2549 sLog.outString();
2550 sLog.outString( ">> Loaded %u arenateam definitions", count );
2551 return;
2554 barGoLink bar( result->GetRowCount() );
2558 Field *fields = result->Fetch();
2560 bar.step();
2561 ++count;
2563 ArenaTeam *newarenateam = new ArenaTeam;
2564 if(!newarenateam->LoadArenaTeamFromDB(fields[0].GetUInt32()))
2566 delete newarenateam;
2567 continue;
2569 AddArenaTeam(newarenateam);
2570 }while( result->NextRow() );
2572 delete result;
2574 sLog.outString();
2575 sLog.outString( ">> Loaded %u arenateam definitions", count );
2578 void ObjectMgr::LoadGroups()
2580 // -- loading groups --
2581 Group *group = NULL;
2582 uint64 leaderGuid = 0;
2583 uint32 count = 0;
2584 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
2585 QueryResult *result = CharacterDatabase.Query("SELECT mainTank, mainAssistant, lootMethod, looterGuid, lootThreshold, icon1, icon2, icon3, icon4, icon5, icon6, icon7, icon8, isRaid, difficulty, leaderGuid FROM groups");
2587 if( !result )
2589 barGoLink bar( 1 );
2591 bar.step();
2593 sLog.outString();
2594 sLog.outString( ">> Loaded %u group definitions", count );
2595 return;
2598 barGoLink bar( result->GetRowCount() );
2602 bar.step();
2603 Field *fields = result->Fetch();
2604 ++count;
2605 leaderGuid = MAKE_NEW_GUID(fields[15].GetUInt32(),0,HIGHGUID_PLAYER);
2607 group = new Group;
2608 if(!group->LoadGroupFromDB(leaderGuid, result, false))
2610 group->Disband();
2611 delete group;
2612 continue;
2614 AddGroup(group);
2615 }while( result->NextRow() );
2617 delete result;
2619 sLog.outString();
2620 sLog.outString( ">> Loaded %u group definitions", count );
2622 // -- loading members --
2623 count = 0;
2624 group = NULL;
2625 leaderGuid = 0;
2626 // 0 1 2 3
2627 result = CharacterDatabase.Query("SELECT memberGuid, assistant, subgroup, leaderGuid FROM group_member ORDER BY leaderGuid");
2628 if(!result)
2630 barGoLink bar( 1 );
2631 bar.step();
2633 else
2635 barGoLink bar( result->GetRowCount() );
2638 bar.step();
2639 Field *fields = result->Fetch();
2640 count++;
2641 leaderGuid = MAKE_NEW_GUID(fields[3].GetUInt32(), 0, HIGHGUID_PLAYER);
2642 if(!group || group->GetLeaderGUID() != leaderGuid)
2644 group = GetGroupByLeader(leaderGuid);
2645 if(!group)
2647 sLog.outErrorDb("Incorrect entry in group_member table : no group with leader %d for member %d!", fields[3].GetUInt32(), fields[0].GetUInt32());
2648 CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", fields[0].GetUInt32());
2649 continue;
2653 if(!group->LoadMemberFromDB(fields[0].GetUInt32(), fields[2].GetUInt8(), fields[1].GetBool()))
2655 sLog.outErrorDb("Incorrect entry in group_member table : member %d cannot be added to player %d's group!", fields[0].GetUInt32(), fields[3].GetUInt32());
2656 CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", fields[0].GetUInt32());
2658 }while( result->NextRow() );
2659 delete result;
2662 // clean groups
2663 // TODO: maybe delete from the DB before loading in this case
2664 for(GroupSet::iterator itr = mGroupSet.begin(); itr != mGroupSet.end();)
2666 if((*itr)->GetMembersCount() < 2)
2668 (*itr)->Disband();
2669 delete *itr;
2670 mGroupSet.erase(itr++);
2672 else
2673 ++itr;
2676 // -- loading instances --
2677 count = 0;
2678 group = NULL;
2679 leaderGuid = 0;
2680 result = CharacterDatabase.Query(
2681 // 0 1 2 3 4 5
2682 "SELECT leaderGuid, map, instance, permanent, difficulty, resettime, "
2683 // 6
2684 "(SELECT COUNT(*) FROM character_instance WHERE guid = leaderGuid AND instance = group_instance.instance AND permanent = 1 LIMIT 1) "
2685 "FROM group_instance LEFT JOIN instance ON instance = id ORDER BY leaderGuid"
2688 if(!result)
2690 barGoLink bar( 1 );
2691 bar.step();
2693 else
2695 barGoLink bar( result->GetRowCount() );
2698 bar.step();
2699 Field *fields = result->Fetch();
2700 count++;
2701 leaderGuid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
2702 if(!group || group->GetLeaderGUID() != leaderGuid)
2704 group = GetGroupByLeader(leaderGuid);
2705 if(!group)
2707 sLog.outErrorDb("Incorrect entry in group_instance table : no group with leader %d", fields[0].GetUInt32());
2708 continue;
2712 InstanceSave *save = sInstanceSaveManager.AddInstanceSave(fields[1].GetUInt32(), fields[2].GetUInt32(), fields[4].GetUInt8(), (time_t)fields[5].GetUInt64(), (fields[6].GetUInt32() == 0), true);
2713 group->BindToInstance(save, fields[3].GetBool(), true);
2714 }while( result->NextRow() );
2715 delete result;
2718 sLog.outString();
2719 sLog.outString( ">> Loaded %u group-instance binds total", count );
2721 sLog.outString();
2722 sLog.outString( ">> Loaded %u group members total", count );
2725 void ObjectMgr::LoadQuests()
2727 // For reload case
2728 for(QuestMap::const_iterator itr=mQuestTemplates.begin(); itr != mQuestTemplates.end(); ++itr)
2729 delete itr->second;
2730 mQuestTemplates.clear();
2732 mExclusiveQuestGroups.clear();
2734 // 0 1 2 3 4 5 6 7 8
2735 QueryResult *result = WorldDatabase.Query("SELECT entry, Method, ZoneOrSort, SkillOrClass, MinLevel, QuestLevel, Type, RequiredRaces, RequiredSkillValue,"
2736 // 9 10 11 12 13 14 15 16
2737 "RepObjectiveFaction, RepObjectiveValue, RequiredMinRepFaction, RequiredMinRepValue, RequiredMaxRepFaction, RequiredMaxRepValue, SuggestedPlayers, LimitTime,"
2738 // 17 18 19 20 21 22 23 24 25 26 27 28
2739 "QuestFlags, SpecialFlags, CharTitleId, PlayersSlain, BonusTalents, PrevQuestId, NextQuestId, ExclusiveGroup, NextQuestInChain, SrcItemId, SrcItemCount, SrcSpell,"
2740 // 29 30 31 32 33 34 35 36 37 38
2741 "Title, Details, Objectives, OfferRewardText, RequestItemsText, EndText, ObjectiveText1, ObjectiveText2, ObjectiveText3, ObjectiveText4,"
2742 // 39 40 41 42 43 44 45 46
2743 "ReqItemId1, ReqItemId2, ReqItemId3, ReqItemId4, ReqItemCount1, ReqItemCount2, ReqItemCount3, ReqItemCount4,"
2744 // 47 48 49 50 51 52 53 54
2745 "ReqSourceId1, ReqSourceId2, ReqSourceId3, ReqSourceId4, ReqSourceCount1, ReqSourceCount2, ReqSourceCount3, ReqSourceCount4,"
2746 // 55 56 57 58 59 60 61 62
2747 "ReqCreatureOrGOId1, ReqCreatureOrGOId2, ReqCreatureOrGOId3, ReqCreatureOrGOId4, ReqCreatureOrGOCount1, ReqCreatureOrGOCount2, ReqCreatureOrGOCount3, ReqCreatureOrGOCount4,"
2748 // 63 64 65 66
2749 "ReqSpellCast1, ReqSpellCast2, ReqSpellCast3, ReqSpellCast4,"
2750 // 67 68 69 70 71 72
2751 "RewChoiceItemId1, RewChoiceItemId2, RewChoiceItemId3, RewChoiceItemId4, RewChoiceItemId5, RewChoiceItemId6,"
2752 // 73 74 75 76 77 78
2753 "RewChoiceItemCount1, RewChoiceItemCount2, RewChoiceItemCount3, RewChoiceItemCount4, RewChoiceItemCount5, RewChoiceItemCount6,"
2754 // 79 80 81 82 83 84 85 86
2755 "RewItemId1, RewItemId2, RewItemId3, RewItemId4, RewItemCount1, RewItemCount2, RewItemCount3, RewItemCount4,"
2756 // 87 88 89 90 91 92 93 94 95 96
2757 "RewRepFaction1, RewRepFaction2, RewRepFaction3, RewRepFaction4, RewRepFaction5, RewRepValue1, RewRepValue2, RewRepValue3, RewRepValue4, RewRepValue5,"
2758 // 97 98 99 100 101 102 103 104 105 106 107
2759 "RewHonorableKills, RewOrReqMoney, RewMoneyMaxLevel, RewSpell, RewSpellCast, RewMailTemplateId, RewMailDelaySecs, PointMapId, PointX, PointY, PointOpt,"
2760 // 108 109 110 111 112 113 114 115 116 117
2761 "DetailsEmote1, DetailsEmote2, DetailsEmote3, DetailsEmote4, IncompleteEmote, CompleteEmote, OfferRewardEmote1, OfferRewardEmote2, OfferRewardEmote3, OfferRewardEmote4,"
2762 // 118 119
2763 "StartScript, CompleteScript"
2764 " FROM quest_template");
2765 if(result == NULL)
2767 barGoLink bar( 1 );
2768 bar.step();
2770 sLog.outString();
2771 sLog.outString( ">> Loaded 0 quests definitions" );
2772 sLog.outErrorDb("`quest_template` table is empty!");
2773 return;
2776 // create multimap previous quest for each existed quest
2777 // some quests can have many previous maps set by NextQuestId in previous quest
2778 // for example set of race quests can lead to single not race specific quest
2779 barGoLink bar( result->GetRowCount() );
2782 bar.step();
2783 Field *fields = result->Fetch();
2785 Quest * newQuest = new Quest(fields);
2786 mQuestTemplates[newQuest->GetQuestId()] = newQuest;
2787 } while( result->NextRow() );
2789 delete result;
2791 // Post processing
2792 for (QuestMap::iterator iter = mQuestTemplates.begin(); iter != mQuestTemplates.end(); ++iter)
2794 Quest * qinfo = iter->second;
2796 // additional quest integrity checks (GO, creature_template and item_template must be loaded already)
2798 if( qinfo->GetQuestMethod() >= 3 )
2800 sLog.outErrorDb("Quest %u has `Method` = %u, expected values are 0, 1 or 2.",qinfo->GetQuestId(),qinfo->GetQuestMethod());
2803 if (qinfo->QuestFlags & ~QUEST_MANGOS_FLAGS_DB_ALLOWED)
2805 sLog.outErrorDb("Quest %u has `SpecialFlags` = %u > max allowed value. Correct `SpecialFlags` to value <= %u",
2806 qinfo->GetQuestId(),qinfo->QuestFlags,QUEST_MANGOS_FLAGS_DB_ALLOWED >> 16);
2807 qinfo->QuestFlags &= QUEST_MANGOS_FLAGS_DB_ALLOWED;
2810 if(qinfo->QuestFlags & QUEST_FLAGS_DAILY)
2812 if(!(qinfo->QuestFlags & QUEST_MANGOS_FLAGS_REPEATABLE))
2814 sLog.outErrorDb("Daily Quest %u not marked as repeatable in `SpecialFlags`, added.",qinfo->GetQuestId());
2815 qinfo->QuestFlags |= QUEST_MANGOS_FLAGS_REPEATABLE;
2819 if(qinfo->QuestFlags & QUEST_FLAGS_AUTO_REWARDED)
2821 // at auto-reward can be rewarded only RewChoiceItemId[0]
2822 for(int j = 1; j < QUEST_REWARD_CHOICES_COUNT; ++j )
2824 if(uint32 id = qinfo->RewChoiceItemId[j])
2826 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item from `RewChoiceItemId%d` can't be rewarded with quest flag QUEST_FLAGS_AUTO_REWARDED.",
2827 qinfo->GetQuestId(),j+1,id,j+1);
2828 // no changes, quest ignore this data
2833 // client quest log visual (area case)
2834 if( qinfo->ZoneOrSort > 0 )
2836 if(!GetAreaEntryByAreaID(qinfo->ZoneOrSort))
2838 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %u (zone case) but zone with this id does not exist.",
2839 qinfo->GetQuestId(),qinfo->ZoneOrSort);
2840 // no changes, quest not dependent from this value but can have problems at client
2843 // client quest log visual (sort case)
2844 if( qinfo->ZoneOrSort < 0 )
2846 QuestSortEntry const* qSort = sQuestSortStore.LookupEntry(-int32(qinfo->ZoneOrSort));
2847 if( !qSort )
2849 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (sort case) but quest sort with this id does not exist.",
2850 qinfo->GetQuestId(),qinfo->ZoneOrSort);
2851 // 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)
2853 //check SkillOrClass value (class case).
2854 if( ClassByQuestSort(-int32(qinfo->ZoneOrSort)) )
2856 // SkillOrClass should not have class case when class case already set in ZoneOrSort.
2857 if(qinfo->SkillOrClass < 0)
2859 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (class sort case) and `SkillOrClass` = %i (class case), redundant.",
2860 qinfo->GetQuestId(),qinfo->ZoneOrSort,qinfo->SkillOrClass);
2863 //check for proper SkillOrClass value (skill case)
2864 if(int32 skill_id = SkillByQuestSort(-int32(qinfo->ZoneOrSort)))
2866 // skill is positive value in SkillOrClass
2867 if(qinfo->SkillOrClass != skill_id )
2869 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (skill sort case) but `SkillOrClass` does not have a corresponding value (%i).",
2870 qinfo->GetQuestId(),qinfo->ZoneOrSort,skill_id);
2871 //override, and force proper value here?
2876 // SkillOrClass (class case)
2877 if( qinfo->SkillOrClass < 0 )
2879 if( !sChrClassesStore.LookupEntry(-int32(qinfo->SkillOrClass)) )
2881 sLog.outErrorDb("Quest %u has `SkillOrClass` = %i (class case) but class (%i) does not exist",
2882 qinfo->GetQuestId(),qinfo->SkillOrClass,-qinfo->SkillOrClass);
2885 // SkillOrClass (skill case)
2886 if( qinfo->SkillOrClass > 0 )
2888 if( !sSkillLineStore.LookupEntry(qinfo->SkillOrClass) )
2890 sLog.outErrorDb("Quest %u has `SkillOrClass` = %u (skill case) but skill (%i) does not exist",
2891 qinfo->GetQuestId(),qinfo->SkillOrClass,qinfo->SkillOrClass);
2895 if( qinfo->RequiredSkillValue )
2897 if( qinfo->RequiredSkillValue > sWorld.GetConfigMaxSkillValue() )
2899 sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but max possible skill is %u, quest can't be done.",
2900 qinfo->GetQuestId(),qinfo->RequiredSkillValue,sWorld.GetConfigMaxSkillValue());
2901 // no changes, quest can't be done for this requirement
2904 if( qinfo->SkillOrClass <= 0 )
2906 sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but `SkillOrClass` = %i (class case), value ignored.",
2907 qinfo->GetQuestId(),qinfo->RequiredSkillValue,qinfo->SkillOrClass);
2908 // no changes, quest can't be done for this requirement (fail at wrong skill id)
2911 // else Skill quests can have 0 skill level, this is ok
2913 if(qinfo->RepObjectiveFaction && !sFactionStore.LookupEntry(qinfo->RepObjectiveFaction))
2915 sLog.outErrorDb("Quest %u has `RepObjectiveFaction` = %u but faction template %u does not exist, quest can't be done.",
2916 qinfo->GetQuestId(),qinfo->RepObjectiveFaction,qinfo->RepObjectiveFaction);
2917 // no changes, quest can't be done for this requirement
2920 if(qinfo->RequiredMinRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMinRepFaction))
2922 sLog.outErrorDb("Quest %u has `RequiredMinRepFaction` = %u but faction template %u does not exist, quest can't be done.",
2923 qinfo->GetQuestId(),qinfo->RequiredMinRepFaction,qinfo->RequiredMinRepFaction);
2924 // no changes, quest can't be done for this requirement
2927 if(qinfo->RequiredMaxRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMaxRepFaction))
2929 sLog.outErrorDb("Quest %u has `RequiredMaxRepFaction` = %u but faction template %u does not exist, quest can't be done.",
2930 qinfo->GetQuestId(),qinfo->RequiredMaxRepFaction,qinfo->RequiredMaxRepFaction);
2931 // no changes, quest can't be done for this requirement
2934 if(qinfo->RequiredMinRepValue && qinfo->RequiredMinRepValue > Player::Reputation_Cap)
2936 sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but max reputation is %u, quest can't be done.",
2937 qinfo->GetQuestId(),qinfo->RequiredMinRepValue,Player::Reputation_Cap);
2938 // no changes, quest can't be done for this requirement
2941 if(qinfo->RequiredMinRepValue && qinfo->RequiredMaxRepValue && qinfo->RequiredMaxRepValue <= qinfo->RequiredMinRepValue)
2943 sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d and `RequiredMinRepValue` = %d, quest can't be done.",
2944 qinfo->GetQuestId(),qinfo->RequiredMaxRepValue,qinfo->RequiredMinRepValue);
2945 // no changes, quest can't be done for this requirement
2948 if(!qinfo->RepObjectiveFaction && qinfo->RepObjectiveValue > 0 )
2950 sLog.outErrorDb("Quest %u has `RepObjectiveValue` = %d but `RepObjectiveFaction` is 0, value has no effect",
2951 qinfo->GetQuestId(),qinfo->RepObjectiveValue);
2952 // warning
2955 if(!qinfo->RequiredMinRepFaction && qinfo->RequiredMinRepValue > 0 )
2957 sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but `RequiredMinRepFaction` is 0, value has no effect",
2958 qinfo->GetQuestId(),qinfo->RequiredMinRepValue);
2959 // warning
2962 if(!qinfo->RequiredMaxRepFaction && qinfo->RequiredMaxRepValue > 0 )
2964 sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d but `RequiredMaxRepFaction` is 0, value has no effect",
2965 qinfo->GetQuestId(),qinfo->RequiredMaxRepValue);
2966 // warning
2969 if(qinfo->CharTitleId && !sCharTitlesStore.LookupEntry(qinfo->CharTitleId))
2971 sLog.outErrorDb("Quest %u has `CharTitleId` = %u but CharTitle Id %u does not exist, quest can't be rewarded with title.",
2972 qinfo->GetQuestId(),qinfo->GetCharTitleId(),qinfo->GetCharTitleId());
2973 qinfo->CharTitleId = 0;
2974 // quest can't reward this title
2977 if(qinfo->SrcItemId)
2979 if(!sItemStorage.LookupEntry<ItemPrototype>(qinfo->SrcItemId))
2981 sLog.outErrorDb("Quest %u has `SrcItemId` = %u but item with entry %u does not exist, quest can't be done.",
2982 qinfo->GetQuestId(),qinfo->SrcItemId,qinfo->SrcItemId);
2983 qinfo->SrcItemId = 0; // quest can't be done for this requirement
2985 else if(qinfo->SrcItemCount==0)
2987 sLog.outErrorDb("Quest %u has `SrcItemId` = %u but `SrcItemCount` = 0, set to 1 but need fix in DB.",
2988 qinfo->GetQuestId(),qinfo->SrcItemId);
2989 qinfo->SrcItemCount = 1; // update to 1 for allow quest work for backward compatibility with DB
2992 else if(qinfo->SrcItemCount>0)
2994 sLog.outErrorDb("Quest %u has `SrcItemId` = 0 but `SrcItemCount` = %u, useless value.",
2995 qinfo->GetQuestId(),qinfo->SrcItemCount);
2996 qinfo->SrcItemCount=0; // no quest work changes in fact
2999 if(qinfo->SrcSpell)
3001 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->SrcSpell);
3002 if(!spellInfo)
3004 sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u doesn't exist, quest can't be done.",
3005 qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
3006 qinfo->SrcSpell = 0; // quest can't be done for this requirement
3008 else if(!SpellMgr::IsSpellValid(spellInfo))
3010 sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u is broken, quest can't be done.",
3011 qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
3012 qinfo->SrcSpell = 0; // quest can't be done for this requirement
3016 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3018 uint32 id = qinfo->ReqItemId[j];
3019 if(id)
3021 if(qinfo->ReqItemCount[j]==0)
3023 sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but `ReqItemCount%d` = 0, quest can't be done.",
3024 qinfo->GetQuestId(),j+1,id,j+1);
3025 // no changes, quest can't be done for this requirement
3028 qinfo->SetFlag(QUEST_MANGOS_FLAGS_DELIVER);
3030 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3032 sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but item with entry %u does not exist, quest can't be done.",
3033 qinfo->GetQuestId(),j+1,id,id);
3034 qinfo->ReqItemCount[j] = 0; // prevent incorrect work of quest
3037 else if(qinfo->ReqItemCount[j]>0)
3039 sLog.outErrorDb("Quest %u has `ReqItemId%d` = 0 but `ReqItemCount%d` = %u, quest can't be done.",
3040 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqItemCount[j]);
3041 qinfo->ReqItemCount[j] = 0; // prevent incorrect work of quest
3045 for(int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j )
3047 uint32 id = qinfo->ReqSourceId[j];
3048 if(id)
3050 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3052 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but item with entry %u does not exist, quest can't be done.",
3053 qinfo->GetQuestId(),j+1,id,id);
3054 // no changes, quest can't be done for this requirement
3057 else
3059 if(qinfo->ReqSourceCount[j]>0)
3061 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = 0 but `ReqSourceCount%d` = %u.",
3062 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqSourceCount[j]);
3063 // no changes, quest ignore this data
3068 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3070 uint32 id = qinfo->ReqSpell[j];
3071 if(id)
3073 SpellEntry const* spellInfo = sSpellStore.LookupEntry(id);
3074 if(!spellInfo)
3076 sLog.outErrorDb("Quest %u has `ReqSpellCast%d` = %u but spell %u does not exist, quest can't be done.",
3077 qinfo->GetQuestId(),j+1,id,id);
3078 // no changes, quest can't be done for this requirement
3081 if(!qinfo->ReqCreatureOrGOId[j])
3083 bool found = false;
3084 for(int k = 0; k < 3; ++k)
3086 if( spellInfo->Effect[k]==SPELL_EFFECT_QUEST_COMPLETE && uint32(spellInfo->EffectMiscValue[k])==qinfo->QuestId ||
3087 spellInfo->Effect[k]==SPELL_EFFECT_SEND_EVENT)
3089 found = true;
3090 break;
3094 if(found)
3096 if(!qinfo->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3098 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);
3100 // this will prevent quest completing without objective
3101 const_cast<Quest*>(qinfo)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3104 else
3106 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.",
3107 qinfo->GetQuestId(),j+1,id,j+1,id);
3108 // no changes, quest can't be done for this requirement
3114 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3116 int32 id = qinfo->ReqCreatureOrGOId[j];
3117 if(id < 0 && !sGOStorage.LookupEntry<GameObjectInfo>(-id))
3119 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but gameobject %u does not exist, quest can't be done.",
3120 qinfo->GetQuestId(),j+1,id,uint32(-id));
3121 qinfo->ReqCreatureOrGOId[j] = 0; // quest can't be done for this requirement
3124 if(id > 0 && !sCreatureStorage.LookupEntry<CreatureInfo>(id))
3126 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but creature with entry %u does not exist, quest can't be done.",
3127 qinfo->GetQuestId(),j+1,id,uint32(id));
3128 qinfo->ReqCreatureOrGOId[j] = 0; // quest can't be done for this requirement
3131 if(id)
3133 // In fact SpeakTo and Kill are quite same: either you can speak to mob:SpeakTo or you can't:Kill/Cast
3135 qinfo->SetFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO);
3137 if(!qinfo->ReqCreatureOrGOCount[j])
3139 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %u but `ReqCreatureOrGOCount%d` = 0, quest can't be done.",
3140 qinfo->GetQuestId(),j+1,id,j+1);
3141 // no changes, quest can be incorrectly done, but we already report this
3144 else if(qinfo->ReqCreatureOrGOCount[j]>0)
3146 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = 0 but `ReqCreatureOrGOCount%d` = %u.",
3147 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqCreatureOrGOCount[j]);
3148 // no changes, quest ignore this data
3152 for(int j = 0; j < QUEST_REWARD_CHOICES_COUNT; ++j )
3154 uint32 id = qinfo->RewChoiceItemId[j];
3155 if(id)
3157 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3159 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3160 qinfo->GetQuestId(),j+1,id,id);
3161 qinfo->RewChoiceItemId[j] = 0; // no changes, quest will not reward this
3164 if(!qinfo->RewChoiceItemCount[j])
3166 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but `RewChoiceItemCount%d` = 0, quest can't be done.",
3167 qinfo->GetQuestId(),j+1,id,j+1);
3168 // no changes, quest can't be done
3171 else if(qinfo->RewChoiceItemCount[j]>0)
3173 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = 0 but `RewChoiceItemCount%d` = %u.",
3174 qinfo->GetQuestId(),j+1,j+1,qinfo->RewChoiceItemCount[j]);
3175 // no changes, quest ignore this data
3179 for(int j = 0; j < QUEST_REWARDS_COUNT; ++j )
3181 uint32 id = qinfo->RewItemId[j];
3182 if(id)
3184 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3186 sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3187 qinfo->GetQuestId(),j+1,id,id);
3188 qinfo->RewItemId[j] = 0; // no changes, quest will not reward this item
3191 if(!qinfo->RewItemCount[j])
3193 sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but `RewItemCount%d` = 0, quest will not reward this item.",
3194 qinfo->GetQuestId(),j+1,id,j+1);
3195 // no changes
3198 else if(qinfo->RewItemCount[j]>0)
3200 sLog.outErrorDb("Quest %u has `RewItemId%d` = 0 but `RewItemCount%d` = %u.",
3201 qinfo->GetQuestId(),j+1,j+1,qinfo->RewItemCount[j]);
3202 // no changes, quest ignore this data
3206 for(int j = 0; j < QUEST_REPUTATIONS_COUNT; ++j)
3208 if(qinfo->RewRepFaction[j])
3210 if(!qinfo->RewRepValue[j])
3212 sLog.outErrorDb("Quest %u has `RewRepFaction%d` = %u but `RewRepValue%d` = 0, quest will not reward this reputation.",
3213 qinfo->GetQuestId(),j+1,qinfo->RewRepValue[j],j+1);
3214 // no changes
3217 if(!sFactionStore.LookupEntry(qinfo->RewRepFaction[j]))
3219 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.",
3220 qinfo->GetQuestId(),j+1,qinfo->RewRepFaction[j] ,qinfo->RewRepFaction[j] );
3221 qinfo->RewRepFaction[j] = 0; // quest will not reward this
3224 else if(qinfo->RewRepValue[j]!=0)
3226 sLog.outErrorDb("Quest %u has `RewRepFaction%d` = 0 but `RewRepValue%d` = %u.",
3227 qinfo->GetQuestId(),j+1,j+1,qinfo->RewRepValue[j]);
3228 // no changes, quest ignore this data
3232 if(qinfo->RewSpell)
3234 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpell);
3236 if(!spellInfo)
3238 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u does not exist, spell removed as display reward.",
3239 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3240 qinfo->RewSpell = 0; // no spell reward will display for this quest
3243 else if(!SpellMgr::IsSpellValid(spellInfo))
3245 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u is broken, quest can't be done.",
3246 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3247 qinfo->RewSpell = 0; // no spell reward will display for this quest
3252 if(qinfo->RewSpellCast)
3254 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpellCast);
3256 if(!spellInfo)
3258 sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u does not exist, quest will not have a spell reward.",
3259 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3260 qinfo->RewSpellCast = 0; // no spell will be casted on player
3263 else if(!SpellMgr::IsSpellValid(spellInfo))
3265 sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u is broken, quest can't be done.",
3266 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3267 qinfo->RewSpellCast = 0; // no spell will be casted on player
3272 if(qinfo->RewMailTemplateId)
3274 if(!sMailTemplateStore.LookupEntry(qinfo->RewMailTemplateId))
3276 sLog.outErrorDb("Quest %u has `RewMailTemplateId` = %u but mail template %u does not exist, quest will not have a mail reward.",
3277 qinfo->GetQuestId(),qinfo->RewMailTemplateId,qinfo->RewMailTemplateId);
3278 qinfo->RewMailTemplateId = 0; // no mail will send to player
3279 qinfo->RewMailDelaySecs = 0; // no mail will send to player
3283 if(qinfo->NextQuestInChain)
3285 QuestMap::iterator qNextItr = mQuestTemplates.find(qinfo->NextQuestInChain);
3286 if(qNextItr == mQuestTemplates.end())
3288 sLog.outErrorDb("Quest %u has `NextQuestInChain` = %u but quest %u does not exist, quest chain will not work.",
3289 qinfo->GetQuestId(),qinfo->NextQuestInChain ,qinfo->NextQuestInChain );
3290 qinfo->NextQuestInChain = 0;
3292 else
3293 qNextItr->second->prevChainQuests.push_back(qinfo->GetQuestId());
3296 // fill additional data stores
3297 if(qinfo->PrevQuestId)
3299 if (mQuestTemplates.find(abs(qinfo->GetPrevQuestId())) == mQuestTemplates.end())
3301 sLog.outErrorDb("Quest %d has PrevQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetPrevQuestId());
3303 else
3305 qinfo->prevQuests.push_back(qinfo->PrevQuestId);
3309 if(qinfo->NextQuestId)
3311 QuestMap::iterator qNextItr = mQuestTemplates.find(abs(qinfo->GetNextQuestId()));
3312 if (qNextItr == mQuestTemplates.end())
3314 sLog.outErrorDb("Quest %d has NextQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetNextQuestId());
3316 else
3318 int32 signedQuestId = qinfo->NextQuestId < 0 ? -int32(qinfo->GetQuestId()) : int32(qinfo->GetQuestId());
3319 qNextItr->second->prevQuests.push_back(signedQuestId);
3323 if(qinfo->ExclusiveGroup)
3324 mExclusiveQuestGroups.insert(std::pair<int32, uint32>(qinfo->ExclusiveGroup, qinfo->GetQuestId()));
3325 if(qinfo->LimitTime)
3326 qinfo->SetFlag(QUEST_MANGOS_FLAGS_TIMED);
3329 // check QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT for spell with SPELL_EFFECT_QUEST_COMPLETE
3330 for (uint32 i = 0; i < sSpellStore.GetNumRows(); ++i)
3332 SpellEntry const *spellInfo = sSpellStore.LookupEntry(i);
3333 if(!spellInfo)
3334 continue;
3336 for(int j = 0; j < 3; ++j)
3338 if(spellInfo->Effect[j] != SPELL_EFFECT_QUEST_COMPLETE)
3339 continue;
3341 uint32 quest_id = spellInfo->EffectMiscValue[j];
3343 Quest const* quest = GetQuestTemplate(quest_id);
3345 // some quest referenced in spells not exist (outdated spells)
3346 if(!quest)
3347 continue;
3349 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3351 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);
3353 // this will prevent quest completing without objective
3354 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3359 sLog.outString();
3360 sLog.outString( ">> Loaded %u quests definitions", mQuestTemplates.size() );
3363 void ObjectMgr::LoadQuestLocales()
3365 mQuestLocaleMap.clear(); // need for reload case
3367 QueryResult *result = WorldDatabase.Query("SELECT entry,"
3368 "Title_loc1,Details_loc1,Objectives_loc1,OfferRewardText_loc1,RequestItemsText_loc1,EndText_loc1,ObjectiveText1_loc1,ObjectiveText2_loc1,ObjectiveText3_loc1,ObjectiveText4_loc1,"
3369 "Title_loc2,Details_loc2,Objectives_loc2,OfferRewardText_loc2,RequestItemsText_loc2,EndText_loc2,ObjectiveText1_loc2,ObjectiveText2_loc2,ObjectiveText3_loc2,ObjectiveText4_loc2,"
3370 "Title_loc3,Details_loc3,Objectives_loc3,OfferRewardText_loc3,RequestItemsText_loc3,EndText_loc3,ObjectiveText1_loc3,ObjectiveText2_loc3,ObjectiveText3_loc3,ObjectiveText4_loc3,"
3371 "Title_loc4,Details_loc4,Objectives_loc4,OfferRewardText_loc4,RequestItemsText_loc4,EndText_loc4,ObjectiveText1_loc4,ObjectiveText2_loc4,ObjectiveText3_loc4,ObjectiveText4_loc4,"
3372 "Title_loc5,Details_loc5,Objectives_loc5,OfferRewardText_loc5,RequestItemsText_loc5,EndText_loc5,ObjectiveText1_loc5,ObjectiveText2_loc5,ObjectiveText3_loc5,ObjectiveText4_loc5,"
3373 "Title_loc6,Details_loc6,Objectives_loc6,OfferRewardText_loc6,RequestItemsText_loc6,EndText_loc6,ObjectiveText1_loc6,ObjectiveText2_loc6,ObjectiveText3_loc6,ObjectiveText4_loc6,"
3374 "Title_loc7,Details_loc7,Objectives_loc7,OfferRewardText_loc7,RequestItemsText_loc7,EndText_loc7,ObjectiveText1_loc7,ObjectiveText2_loc7,ObjectiveText3_loc7,ObjectiveText4_loc7,"
3375 "Title_loc8,Details_loc8,Objectives_loc8,OfferRewardText_loc8,RequestItemsText_loc8,EndText_loc8,ObjectiveText1_loc8,ObjectiveText2_loc8,ObjectiveText3_loc8,ObjectiveText4_loc8"
3376 " FROM locales_quest"
3379 if(!result)
3381 barGoLink bar(1);
3383 bar.step();
3385 sLog.outString();
3386 sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_quest` is empty.");
3387 return;
3390 barGoLink bar(result->GetRowCount());
3394 Field *fields = result->Fetch();
3395 bar.step();
3397 uint32 entry = fields[0].GetUInt32();
3399 QuestLocale& data = mQuestLocaleMap[entry];
3401 for(int i = 1; i < MAX_LOCALE; ++i)
3403 std::string str = fields[1+10*(i-1)].GetCppString();
3404 if(!str.empty())
3406 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3407 if(idx >= 0)
3409 if(data.Title.size() <= idx)
3410 data.Title.resize(idx+1);
3412 data.Title[idx] = str;
3415 str = fields[1+10*(i-1)+1].GetCppString();
3416 if(!str.empty())
3418 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3419 if(idx >= 0)
3421 if(data.Details.size() <= idx)
3422 data.Details.resize(idx+1);
3424 data.Details[idx] = str;
3427 str = fields[1+10*(i-1)+2].GetCppString();
3428 if(!str.empty())
3430 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3431 if(idx >= 0)
3433 if(data.Objectives.size() <= idx)
3434 data.Objectives.resize(idx+1);
3436 data.Objectives[idx] = str;
3439 str = fields[1+10*(i-1)+3].GetCppString();
3440 if(!str.empty())
3442 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3443 if(idx >= 0)
3445 if(data.OfferRewardText.size() <= idx)
3446 data.OfferRewardText.resize(idx+1);
3448 data.OfferRewardText[idx] = str;
3451 str = fields[1+10*(i-1)+4].GetCppString();
3452 if(!str.empty())
3454 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3455 if(idx >= 0)
3457 if(data.RequestItemsText.size() <= idx)
3458 data.RequestItemsText.resize(idx+1);
3460 data.RequestItemsText[idx] = str;
3463 str = fields[1+10*(i-1)+5].GetCppString();
3464 if(!str.empty())
3466 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3467 if(idx >= 0)
3469 if(data.EndText.size() <= idx)
3470 data.EndText.resize(idx+1);
3472 data.EndText[idx] = str;
3475 for(int k = 0; k < 4; ++k)
3477 str = fields[1+10*(i-1)+6+k].GetCppString();
3478 if(!str.empty())
3480 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3481 if(idx >= 0)
3483 if(data.ObjectiveText[k].size() <= idx)
3484 data.ObjectiveText[k].resize(idx+1);
3486 data.ObjectiveText[k][idx] = str;
3491 } while (result->NextRow());
3493 delete result;
3495 sLog.outString();
3496 sLog.outString( ">> Loaded %u Quest locale strings", mQuestLocaleMap.size() );
3499 void ObjectMgr::LoadPetCreateSpells()
3501 QueryResult *result = WorldDatabase.Query("SELECT entry, Spell1, Spell2, Spell3, Spell4 FROM petcreateinfo_spell");
3502 if(!result)
3504 barGoLink bar( 1 );
3505 bar.step();
3507 sLog.outString();
3508 sLog.outString( ">> Loaded 0 pet create spells" );
3509 sLog.outErrorDb("`petcreateinfo_spell` table is empty!");
3510 return;
3513 uint32 count = 0;
3515 barGoLink bar( result->GetRowCount() );
3517 mPetCreateSpell.clear();
3521 Field *fields = result->Fetch();
3522 bar.step();
3524 uint32 creature_id = fields[0].GetUInt32();
3526 if(!creature_id || !sCreatureStorage.LookupEntry<CreatureInfo>(creature_id))
3527 continue;
3529 PetCreateSpellEntry PetCreateSpell;
3530 for(int i = 0; i < 4; i++)
3532 PetCreateSpell.spellid[i] = fields[i + 1].GetUInt32();
3534 if(PetCreateSpell.spellid[i] && !sSpellStore.LookupEntry(PetCreateSpell.spellid[i]))
3535 sLog.outErrorDb("Spell %u listed in `petcreateinfo_spell` does not exist",PetCreateSpell.spellid[i]);
3538 mPetCreateSpell[creature_id] = PetCreateSpell;
3540 ++count;
3542 while (result->NextRow());
3544 delete result;
3546 sLog.outString();
3547 sLog.outString( ">> Loaded %u pet create spells", count );
3550 void ObjectMgr::LoadScripts(ScriptMapMap& scripts, char const* tablename)
3552 if(sWorld.IsScriptScheduled()) // function don't must be called in time scripts use.
3553 return;
3555 sLog.outString( "%s :", tablename);
3557 scripts.clear(); // need for reload support
3559 QueryResult *result = WorldDatabase.PQuery( "SELECT id,delay,command,datalong,datalong2,dataint, x, y, z, o FROM %s", tablename );
3561 uint32 count = 0;
3563 if( !result )
3565 barGoLink bar( 1 );
3566 bar.step();
3568 sLog.outString();
3569 sLog.outString( ">> Loaded %u script definitions", count );
3570 return;
3573 barGoLink bar( result->GetRowCount() );
3577 bar.step();
3579 Field *fields = result->Fetch();
3580 ScriptInfo tmp;
3581 tmp.id = fields[0].GetUInt32();
3582 tmp.delay = fields[1].GetUInt32();
3583 tmp.command = fields[2].GetUInt32();
3584 tmp.datalong = fields[3].GetUInt32();
3585 tmp.datalong2 = fields[4].GetUInt32();
3586 tmp.dataint = fields[5].GetInt32();
3587 tmp.x = fields[6].GetFloat();
3588 tmp.y = fields[7].GetFloat();
3589 tmp.z = fields[8].GetFloat();
3590 tmp.o = fields[9].GetFloat();
3592 // generic command args check
3593 switch(tmp.command)
3595 case SCRIPT_COMMAND_TALK:
3597 if(tmp.datalong > 3)
3599 sLog.outErrorDb("Table `%s` has invalid talk type (datalong = %u) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.datalong,tmp.id);
3600 continue;
3602 if(tmp.dataint==0)
3604 sLog.outErrorDb("Table `%s` has invalid talk text id (dataint = %i) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.dataint,tmp.id);
3605 continue;
3607 if(tmp.dataint < MIN_DB_SCRIPT_STRING_ID || tmp.dataint >= MAX_DB_SCRIPT_STRING_ID)
3609 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);
3610 continue;
3613 // if(!objmgr.GetMangosStringLocale(tmp.dataint)) will checked after db_script_string loading
3614 break;
3617 case SCRIPT_COMMAND_TELEPORT_TO:
3619 if(!sMapStore.LookupEntry(tmp.datalong))
3621 sLog.outErrorDb("Table `%s` has invalid map (Id: %u) in SCRIPT_COMMAND_TELEPORT_TO for script id %u",tablename,tmp.datalong,tmp.id);
3622 continue;
3625 if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
3627 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);
3628 continue;
3630 break;
3633 case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
3635 if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
3637 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);
3638 continue;
3641 if(!GetCreatureTemplate(tmp.datalong))
3643 sLog.outErrorDb("Table `%s` has invalid creature (Entry: %u) in SCRIPT_COMMAND_TEMP_SUMMON_CREATURE for script id %u",tablename,tmp.datalong,tmp.id);
3644 continue;
3646 break;
3649 case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
3651 GameObjectData const* data = GetGOData(tmp.datalong);
3652 if(!data)
3654 sLog.outErrorDb("Table `%s` has invalid gameobject (GUID: %u) in SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,tmp.datalong,tmp.id);
3655 continue;
3658 GameObjectInfo const* info = GetGameObjectInfo(data->id);
3659 if(!info)
3661 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);
3662 continue;
3665 if( info->type==GAMEOBJECT_TYPE_FISHINGNODE ||
3666 info->type==GAMEOBJECT_TYPE_FISHINGHOLE ||
3667 info->type==GAMEOBJECT_TYPE_DOOR ||
3668 info->type==GAMEOBJECT_TYPE_BUTTON ||
3669 info->type==GAMEOBJECT_TYPE_TRAP )
3671 sLog.outErrorDb("Table `%s` have gameobject type (%u) unsupported by command SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,info->id,tmp.id);
3672 continue;
3674 break;
3676 case SCRIPT_COMMAND_OPEN_DOOR:
3677 case SCRIPT_COMMAND_CLOSE_DOOR:
3679 GameObjectData const* data = GetGOData(tmp.datalong);
3680 if(!data)
3682 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);
3683 continue;
3686 GameObjectInfo const* info = GetGameObjectInfo(data->id);
3687 if(!info)
3689 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);
3690 continue;
3693 if( info->type!=GAMEOBJECT_TYPE_DOOR)
3695 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);
3696 continue;
3699 break;
3701 case SCRIPT_COMMAND_QUEST_EXPLORED:
3703 Quest const* quest = GetQuestTemplate(tmp.datalong);
3704 if(!quest)
3706 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);
3707 continue;
3710 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3712 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);
3714 // this will prevent quest completing without objective
3715 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3717 // continue; - quest objective requirement set and command can be allowed
3720 if(float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
3722 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",
3723 tablename,tmp.datalong2,tmp.id);
3724 continue;
3727 if(tmp.datalong2 && float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
3729 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",
3730 tablename,tmp.datalong2,tmp.id,DEFAULT_VISIBILITY_DISTANCE);
3731 continue;
3734 if(tmp.datalong2 && float(tmp.datalong2) < INTERACTION_DISTANCE)
3736 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",
3737 tablename,tmp.datalong2,tmp.id,INTERACTION_DISTANCE);
3738 continue;
3741 break;
3744 case SCRIPT_COMMAND_REMOVE_AURA:
3746 if(!sSpellStore.LookupEntry(tmp.datalong))
3748 sLog.outErrorDb("Table `%s` using non-existent spell (id: %u) in SCRIPT_COMMAND_REMOVE_AURA or SCRIPT_COMMAND_CAST_SPELL for script id %u",
3749 tablename,tmp.datalong,tmp.id);
3750 continue;
3752 if(tmp.datalong2 & ~0x1) // 1 bits (0,1)
3754 sLog.outErrorDb("Table `%s` using unknown flags in datalong2 (%u)i n SCRIPT_COMMAND_CAST_SPELL for script id %u",
3755 tablename,tmp.datalong2,tmp.id);
3756 continue;
3758 break;
3760 case SCRIPT_COMMAND_CAST_SPELL:
3762 if(!sSpellStore.LookupEntry(tmp.datalong))
3764 sLog.outErrorDb("Table `%s` using non-existent spell (id: %u) in SCRIPT_COMMAND_REMOVE_AURA or SCRIPT_COMMAND_CAST_SPELL for script id %u",
3765 tablename,tmp.datalong,tmp.id);
3766 continue;
3768 if(tmp.datalong2 & ~0x3) // 2 bits
3770 sLog.outErrorDb("Table `%s` using unknown flags in datalong2 (%u)i n SCRIPT_COMMAND_CAST_SPELL for script id %u",
3771 tablename,tmp.datalong2,tmp.id);
3772 continue;
3774 break;
3778 if (scripts.find(tmp.id) == scripts.end())
3780 ScriptMap emptyMap;
3781 scripts[tmp.id] = emptyMap;
3783 scripts[tmp.id].insert(std::pair<uint32, ScriptInfo>(tmp.delay, tmp));
3785 ++count;
3786 } while( result->NextRow() );
3788 delete result;
3790 sLog.outString();
3791 sLog.outString( ">> Loaded %u script definitions", count );
3794 void ObjectMgr::LoadGameObjectScripts()
3796 LoadScripts(sGameObjectScripts, "gameobject_scripts");
3798 // check ids
3799 for(ScriptMapMap::const_iterator itr = sGameObjectScripts.begin(); itr != sGameObjectScripts.end(); ++itr)
3801 if(!GetGOData(itr->first))
3802 sLog.outErrorDb("Table `gameobject_scripts` has not existing gameobject (GUID: %u) as script id",itr->first);
3806 void ObjectMgr::LoadQuestEndScripts()
3808 LoadScripts(sQuestEndScripts, "quest_end_scripts");
3810 // check ids
3811 for(ScriptMapMap::const_iterator itr = sQuestEndScripts.begin(); itr != sQuestEndScripts.end(); ++itr)
3813 if(!GetQuestTemplate(itr->first))
3814 sLog.outErrorDb("Table `quest_end_scripts` has not existing quest (Id: %u) as script id",itr->first);
3818 void ObjectMgr::LoadQuestStartScripts()
3820 LoadScripts(sQuestStartScripts,"quest_start_scripts");
3822 // check ids
3823 for(ScriptMapMap::const_iterator itr = sQuestStartScripts.begin(); itr != sQuestStartScripts.end(); ++itr)
3825 if(!GetQuestTemplate(itr->first))
3826 sLog.outErrorDb("Table `quest_start_scripts` has not existing quest (Id: %u) as script id",itr->first);
3830 void ObjectMgr::LoadSpellScripts()
3832 LoadScripts(sSpellScripts, "spell_scripts");
3834 // check ids
3835 for(ScriptMapMap::const_iterator itr = sSpellScripts.begin(); itr != sSpellScripts.end(); ++itr)
3837 SpellEntry const* spellInfo = sSpellStore.LookupEntry(itr->first);
3839 if(!spellInfo)
3841 sLog.outErrorDb("Table `spell_scripts` has not existing spell (Id: %u) as script id",itr->first);
3842 continue;
3845 //check for correct spellEffect
3846 bool found = false;
3847 for(int i=0; i<3; ++i)
3849 // skip empty effects
3850 if( !spellInfo->Effect[i] )
3851 continue;
3853 if( spellInfo->Effect[i] == SPELL_EFFECT_SCRIPT_EFFECT )
3855 found = true;
3856 break;
3860 if(!found)
3861 sLog.outErrorDb("Table `spell_scripts` has unsupported spell (Id: %u) without SPELL_EFFECT_SCRIPT_EFFECT (%u) spell effect",itr->first,SPELL_EFFECT_SCRIPT_EFFECT);
3865 void ObjectMgr::LoadEventScripts()
3867 LoadScripts(sEventScripts, "event_scripts");
3869 std::set<uint32> evt_scripts;
3870 // Load all possible script entries from gameobjects
3871 for(uint32 i = 1; i < sGOStorage.MaxEntry; ++i)
3873 GameObjectInfo const * goInfo = sGOStorage.LookupEntry<GameObjectInfo>(i);
3874 if (goInfo)
3876 switch(goInfo->type)
3878 case GAMEOBJECT_TYPE_GOOBER:
3879 if(goInfo->goober.eventId)
3880 evt_scripts.insert(goInfo->goober.eventId);
3881 break;
3882 case GAMEOBJECT_TYPE_CHEST:
3883 if(goInfo->chest.eventId)
3884 evt_scripts.insert(goInfo->chest.eventId);
3885 break;
3886 default:
3887 break;
3891 // Load all possible script entries from spells
3892 for(uint32 i = 1; i < sSpellStore.GetNumRows(); ++i)
3894 SpellEntry const * spell = sSpellStore.LookupEntry(i);
3895 if (spell)
3897 for(int j=0; j<3; ++j)
3899 if( spell->Effect[j] == SPELL_EFFECT_SEND_EVENT )
3901 if (spell->EffectMiscValue[j])
3902 evt_scripts.insert(spell->EffectMiscValue[j]);
3907 // Then check if all scripts are in above list of possible script entries
3908 for(ScriptMapMap::const_iterator itr = sEventScripts.begin(); itr != sEventScripts.end(); ++itr)
3910 std::set<uint32>::const_iterator itr2 = evt_scripts.find(itr->first);
3911 if (itr2 == evt_scripts.end())
3912 sLog.outErrorDb("Table `event_scripts` has script (Id: %u) not referring to any gameobject_template type 10 data2 field or type 3 data6 field or any spell effect %u", itr->first, SPELL_EFFECT_SEND_EVENT);
3916 void ObjectMgr::LoadItemTexts()
3918 QueryResult *result = CharacterDatabase.Query("SELECT id, text FROM item_text");
3920 uint32 count = 0;
3922 if( !result )
3924 barGoLink bar( 1 );
3925 bar.step();
3927 sLog.outString();
3928 sLog.outString( ">> Loaded %u item pages", count );
3929 return;
3932 barGoLink bar( result->GetRowCount() );
3934 Field* fields;
3937 bar.step();
3939 fields = result->Fetch();
3941 mItemTexts[ fields[0].GetUInt32() ] = fields[1].GetCppString();
3943 ++count;
3945 } while ( result->NextRow() );
3947 delete result;
3949 sLog.outString();
3950 sLog.outString( ">> Loaded %u item texts", count );
3953 void ObjectMgr::LoadPageTexts()
3955 sPageTextStore.Free(); // for reload case
3957 sPageTextStore.Load();
3958 sLog.outString( ">> Loaded %u page texts", sPageTextStore.RecordCount );
3959 sLog.outString();
3961 for(uint32 i = 1; i < sPageTextStore.MaxEntry; ++i)
3963 // check data correctness
3964 PageText const* page = sPageTextStore.LookupEntry<PageText>(i);
3965 if(!page)
3966 continue;
3968 if(page->Next_Page && !sPageTextStore.LookupEntry<PageText>(page->Next_Page))
3970 sLog.outErrorDb("Page text (Id: %u) has not existing next page (Id:%u)", i,page->Next_Page);
3971 continue;
3974 // detect circular reference
3975 std::set<uint32> checkedPages;
3976 for(PageText const* pageItr = page; pageItr; pageItr = sPageTextStore.LookupEntry<PageText>(pageItr->Next_Page))
3978 if(!pageItr->Next_Page)
3979 break;
3980 checkedPages.insert(pageItr->Page_ID);
3981 if(checkedPages.find(pageItr->Next_Page)!=checkedPages.end())
3983 std::ostringstream ss;
3984 ss<< "The text page(s) ";
3985 for (std::set<uint32>::iterator itr= checkedPages.begin();itr!=checkedPages.end(); ++itr)
3986 ss << *itr << " ";
3987 ss << "create(s) a circular reference, which can cause the server to freeze. Changing Next_Page of page "
3988 << pageItr->Page_ID <<" to 0";
3989 sLog.outErrorDb(ss.str().c_str());
3990 const_cast<PageText*>(pageItr)->Next_Page = 0;
3991 break;
3997 void ObjectMgr::LoadPageTextLocales()
3999 mPageTextLocaleMap.clear(); // need for reload case
4001 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");
4003 if(!result)
4005 barGoLink bar(1);
4007 bar.step();
4009 sLog.outString();
4010 sLog.outString(">> Loaded 0 PageText locale strings. DB table `locales_page_text` is empty.");
4011 return;
4014 barGoLink bar(result->GetRowCount());
4018 Field *fields = result->Fetch();
4019 bar.step();
4021 uint32 entry = fields[0].GetUInt32();
4023 PageTextLocale& data = mPageTextLocaleMap[entry];
4025 for(int i = 1; i < MAX_LOCALE; ++i)
4027 std::string str = fields[i].GetCppString();
4028 if(str.empty())
4029 continue;
4031 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4032 if(idx >= 0)
4034 if(data.Text.size() <= idx)
4035 data.Text.resize(idx+1);
4037 data.Text[idx] = str;
4041 } while (result->NextRow());
4043 delete result;
4045 sLog.outString();
4046 sLog.outString( ">> Loaded %u PageText locale strings", mPageTextLocaleMap.size() );
4049 struct SQLInstanceLoader : public SQLStorageLoaderBase<SQLInstanceLoader>
4051 template<class D>
4052 void convert_from_str(uint32 field_pos, char *src, D &dst)
4054 dst = D(objmgr.GetScriptId(src));
4058 void ObjectMgr::LoadInstanceTemplate()
4060 SQLInstanceLoader loader;
4061 loader.Load(sInstanceTemplate);
4063 for(uint32 i = 0; i < sInstanceTemplate.MaxEntry; i++)
4065 InstanceTemplate* temp = (InstanceTemplate*)GetInstanceTemplate(i);
4066 if(!temp) continue;
4067 const MapEntry* entry = sMapStore.LookupEntry(temp->map);
4068 if(!entry)
4070 sLog.outErrorDb("ObjectMgr::LoadInstanceTemplate: bad mapid %d for template!", temp->map);
4071 continue;
4073 else if(!entry->HasResetTime())
4074 continue;
4076 //FIXME: now exist heroic instance, normal/heroic raid instances
4077 // entry->resetTimeHeroic store reset time for both heroic mode instance (raid and non-raid)
4078 // entry->resetTimeRaid store reset time for normal raid only
4079 // for current state entry->resetTimeRaid == entry->resetTimeHeroic in case raid instances with heroic mode.
4080 // but at some point wee need implement reset time dependent from raid instance mode
4081 if(temp->reset_delay == 0)
4083 // use defaults from the DBC
4084 if(entry->resetTimeHeroic) // for both raid and non raids, read above
4086 temp->reset_delay = entry->resetTimeHeroic / DAY;
4088 else if (entry->resetTimeRaid && entry->map_type == MAP_RAID)
4089 // for normal raid only
4091 temp->reset_delay = entry->resetTimeRaid / DAY;
4095 // the reset_delay must be at least one day
4096 temp->reset_delay = std::max((uint32)1, (uint32)(temp->reset_delay * sWorld.getRate(RATE_INSTANCE_RESET_TIME)));
4099 sLog.outString( ">> Loaded %u Instance Template definitions", sInstanceTemplate.RecordCount );
4100 sLog.outString();
4103 GossipText const *ObjectMgr::GetGossipText(uint32 Text_ID) const
4105 GossipTextMap::const_iterator itr = mGossipText.find(Text_ID);
4106 if(itr != mGossipText.end())
4107 return &itr->second;
4108 return NULL;
4111 void ObjectMgr::LoadGossipText()
4113 QueryResult *result = WorldDatabase.Query( "SELECT * FROM npc_text" );
4115 int count = 0;
4116 if( !result )
4118 barGoLink bar( 1 );
4119 bar.step();
4121 sLog.outString();
4122 sLog.outString( ">> Loaded %u npc texts", count );
4123 return;
4126 int cic;
4128 barGoLink bar( result->GetRowCount() );
4132 ++count;
4133 cic = 0;
4135 Field *fields = result->Fetch();
4137 bar.step();
4139 uint32 Text_ID = fields[cic++].GetUInt32();
4140 if(!Text_ID)
4142 sLog.outErrorDb("Table `npc_text` has record wit reserved id 0, ignore.");
4143 continue;
4146 GossipText& gText = mGossipText[Text_ID];
4148 for (int i=0; i< 8; i++)
4150 gText.Options[i].Text_0 = fields[cic++].GetCppString();
4151 gText.Options[i].Text_1 = fields[cic++].GetCppString();
4153 gText.Options[i].Language = fields[cic++].GetUInt32();
4154 gText.Options[i].Probability = fields[cic++].GetFloat();
4156 for(int j=0; j < 3; ++j)
4158 gText.Options[i].Emotes[j]._Delay = fields[cic++].GetUInt32();
4159 gText.Options[i].Emotes[j]._Emote = fields[cic++].GetUInt32();
4162 } while( result->NextRow() );
4164 sLog.outString();
4165 sLog.outString( ">> Loaded %u npc texts", count );
4166 delete result;
4169 void ObjectMgr::LoadNpcTextLocales()
4171 mNpcTextLocaleMap.clear(); // need for reload case
4173 QueryResult *result = WorldDatabase.Query("SELECT entry,"
4174 "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,"
4175 "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,"
4176 "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,"
4177 "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,"
4178 "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,"
4179 "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,"
4180 "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, "
4181 "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 "
4182 " FROM locales_npc_text");
4184 if(!result)
4186 barGoLink bar(1);
4188 bar.step();
4190 sLog.outString();
4191 sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_npc_text` is empty.");
4192 return;
4195 barGoLink bar(result->GetRowCount());
4199 Field *fields = result->Fetch();
4200 bar.step();
4202 uint32 entry = fields[0].GetUInt32();
4204 NpcTextLocale& data = mNpcTextLocaleMap[entry];
4206 for(int i=1; i<MAX_LOCALE; ++i)
4208 for(int j=0; j<8; ++j)
4210 std::string str0 = fields[1+8*2*(i-1)+2*j].GetCppString();
4211 if(!str0.empty())
4213 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4214 if(idx >= 0)
4216 if(data.Text_0[j].size() <= idx)
4217 data.Text_0[j].resize(idx+1);
4219 data.Text_0[j][idx] = str0;
4222 std::string str1 = fields[1+8*2*(i-1)+2*j+1].GetCppString();
4223 if(!str1.empty())
4225 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4226 if(idx >= 0)
4228 if(data.Text_1[j].size() <= idx)
4229 data.Text_1[j].resize(idx+1);
4231 data.Text_1[j][idx] = str1;
4236 } while (result->NextRow());
4238 delete result;
4240 sLog.outString();
4241 sLog.outString( ">> Loaded %u NpcText locale strings", mNpcTextLocaleMap.size() );
4244 //not very fast function but it is called only once a day, or on starting-up
4245 void ObjectMgr::ReturnOrDeleteOldMails(bool serverUp)
4247 time_t basetime = time(NULL);
4248 sLog.outDebug("Returning mails current time: hour: %d, minute: %d, second: %d ", localtime(&basetime)->tm_hour, localtime(&basetime)->tm_min, localtime(&basetime)->tm_sec);
4249 //delete all old mails without item and without body immediately, if starting server
4250 if (!serverUp)
4251 CharacterDatabase.PExecute("DELETE FROM mail WHERE expire_time < '" I64FMTD "' AND has_items = '0' AND itemTextId = 0", (uint64)basetime);
4252 // 0 1 2 3 4 5 6 7 8 9
4253 QueryResult* result = CharacterDatabase.PQuery("SELECT id,messageType,sender,receiver,itemTextId,has_items,expire_time,cod,checked,mailTemplateId FROM mail WHERE expire_time < '" I64FMTD "'", (uint64)basetime);
4254 if ( !result )
4256 barGoLink bar(1);
4257 bar.step();
4258 sLog.outString();
4259 sLog.outString(">> Only expired mails (need to be return or delete) or DB table `mail` is empty.");
4260 return; // any mails need to be returned or deleted
4263 //std::ostringstream delitems, delmails; //will be here for optimization
4264 //bool deletemail = false, deleteitem = false;
4265 //delitems << "DELETE FROM item_instance WHERE guid IN ( ";
4266 //delmails << "DELETE FROM mail WHERE id IN ( "
4268 barGoLink bar( result->GetRowCount() );
4269 uint32 count = 0;
4270 Field *fields;
4274 bar.step();
4276 fields = result->Fetch();
4277 Mail *m = new Mail;
4278 m->messageID = fields[0].GetUInt32();
4279 m->messageType = fields[1].GetUInt8();
4280 m->sender = fields[2].GetUInt32();
4281 m->receiver = fields[3].GetUInt32();
4282 m->itemTextId = fields[4].GetUInt32();
4283 bool has_items = fields[5].GetBool();
4284 m->expire_time = (time_t)fields[6].GetUInt64();
4285 m->deliver_time = 0;
4286 m->COD = fields[7].GetUInt32();
4287 m->checked = fields[8].GetUInt32();
4288 m->mailTemplateId = fields[9].GetInt16();
4290 Player *pl = 0;
4291 if (serverUp)
4292 pl = GetPlayer((uint64)m->receiver);
4293 if (pl && pl->m_mailsLoaded)
4294 { //this code will run very improbably (the time is between 4 and 5 am, in game is online a player, who has old mail
4295 //his in mailbox and he has already listed his mails )
4296 delete m;
4297 continue;
4299 //delete or return mail:
4300 if (has_items)
4302 QueryResult *resultItems = CharacterDatabase.PQuery("SELECT item_guid,item_template FROM mail_items WHERE mail_id='%u'", m->messageID);
4303 if(resultItems)
4307 Field *fields2 = resultItems->Fetch();
4309 uint32 item_guid_low = fields2[0].GetUInt32();
4310 uint32 item_template = fields2[1].GetUInt32();
4312 m->AddItem(item_guid_low, item_template);
4314 while (resultItems->NextRow());
4316 delete resultItems;
4318 //if it is mail from AH, it shouldn't be returned, but deleted
4319 if (m->messageType != MAIL_NORMAL || (m->checked & (MAIL_CHECK_MASK_AUCTION | MAIL_CHECK_MASK_COD_PAYMENT | MAIL_CHECK_MASK_RETURNED)))
4321 // mail open and then not returned
4322 for(std::vector<MailItemInfo>::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
4323 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
4325 else
4327 //mail will be returned:
4328 CharacterDatabase.PExecute("UPDATE mail SET sender = '%u', receiver = '%u', expire_time = '" I64FMTD "', deliver_time = '" I64FMTD "',cod = '0', checked = '%u' WHERE id = '%u'", m->receiver, m->sender, (uint64)(basetime + 30*DAY), (uint64)basetime, MAIL_CHECK_MASK_RETURNED, m->messageID);
4329 delete m;
4330 continue;
4334 if (m->itemTextId)
4335 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
4337 //deletemail = true;
4338 //delmails << m->messageID << ", ";
4339 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
4340 delete m;
4341 ++count;
4342 } while (result->NextRow());
4343 delete result;
4345 sLog.outString();
4346 sLog.outString( ">> Loaded %u mails", count );
4349 void ObjectMgr::LoadQuestAreaTriggers()
4351 mQuestAreaTriggerMap.clear(); // need for reload case
4353 QueryResult *result = WorldDatabase.Query( "SELECT id,quest FROM areatrigger_involvedrelation" );
4355 uint32 count = 0;
4357 if( !result )
4359 barGoLink bar( 1 );
4360 bar.step();
4362 sLog.outString();
4363 sLog.outString( ">> Loaded %u quest trigger points", count );
4364 return;
4367 barGoLink bar( result->GetRowCount() );
4371 ++count;
4372 bar.step();
4374 Field *fields = result->Fetch();
4376 uint32 trigger_ID = fields[0].GetUInt32();
4377 uint32 quest_ID = fields[1].GetUInt32();
4379 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(trigger_ID);
4380 if(!atEntry)
4382 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",trigger_ID);
4383 continue;
4386 Quest const* quest = GetQuestTemplate(quest_ID);
4388 if(!quest)
4390 sLog.outErrorDb("Table `areatrigger_involvedrelation` has record (id: %u) for not existing quest %u",trigger_ID,quest_ID);
4391 continue;
4394 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
4396 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);
4398 // this will prevent quest completing without objective
4399 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
4401 // continue; - quest modified to required objective and trigger can be allowed.
4404 mQuestAreaTriggerMap[trigger_ID] = quest_ID;
4406 } while( result->NextRow() );
4408 delete result;
4410 sLog.outString();
4411 sLog.outString( ">> Loaded %u quest trigger points", count );
4414 void ObjectMgr::LoadTavernAreaTriggers()
4416 mTavernAreaTriggerSet.clear(); // need for reload case
4418 QueryResult *result = WorldDatabase.Query("SELECT id FROM areatrigger_tavern");
4420 uint32 count = 0;
4422 if( !result )
4424 barGoLink bar( 1 );
4425 bar.step();
4427 sLog.outString();
4428 sLog.outString( ">> Loaded %u tavern triggers", count );
4429 return;
4432 barGoLink bar( result->GetRowCount() );
4436 ++count;
4437 bar.step();
4439 Field *fields = result->Fetch();
4441 uint32 Trigger_ID = fields[0].GetUInt32();
4443 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4444 if(!atEntry)
4446 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4447 continue;
4450 mTavernAreaTriggerSet.insert(Trigger_ID);
4451 } while( result->NextRow() );
4453 delete result;
4455 sLog.outString();
4456 sLog.outString( ">> Loaded %u tavern triggers", count );
4459 void ObjectMgr::LoadAreaTriggerScripts()
4461 mAreaTriggerScripts.clear(); // need for reload case
4462 QueryResult *result = WorldDatabase.Query("SELECT entry, ScriptName FROM areatrigger_scripts");
4464 uint32 count = 0;
4466 if( !result )
4468 barGoLink bar( 1 );
4469 bar.step();
4471 sLog.outString();
4472 sLog.outString( ">> Loaded %u areatrigger scripts", count );
4473 return;
4476 barGoLink bar( result->GetRowCount() );
4480 ++count;
4481 bar.step();
4483 Field *fields = result->Fetch();
4485 uint32 Trigger_ID = fields[0].GetUInt32();
4486 const char *scriptName = fields[1].GetString();
4488 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4489 if(!atEntry)
4491 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4492 continue;
4494 mAreaTriggerScripts[Trigger_ID] = GetScriptId(scriptName);
4495 } while( result->NextRow() );
4497 delete result;
4499 sLog.outString();
4500 sLog.outString( ">> Loaded %u areatrigger scripts", count );
4503 uint32 ObjectMgr::GetNearestTaxiNode( float x, float y, float z, uint32 mapid, uint32 team )
4505 bool found = false;
4506 float dist;
4507 uint32 id = 0;
4509 for(uint32 i = 1; i < sTaxiNodesStore.GetNumRows(); ++i)
4511 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(i);
4512 if(!node || node->map_id != mapid || !node->MountCreatureID[team == ALLIANCE ? 1 : 0])
4513 continue;
4515 uint8 field = (uint8)((i - 1) / 32);
4516 uint32 submask = 1<<((i-1)%32);
4518 // skip not taxi network nodes
4519 if((sTaxiNodesMask[field] & submask)==0)
4520 continue;
4522 float dist2 = (node->x - x)*(node->x - x)+(node->y - y)*(node->y - y)+(node->z - z)*(node->z - z);
4523 if(found)
4525 if(dist2 < dist)
4527 dist = dist2;
4528 id = i;
4531 else
4533 found = true;
4534 dist = dist2;
4535 id = i;
4539 return id;
4542 void ObjectMgr::GetTaxiPath( uint32 source, uint32 destination, uint32 &path, uint32 &cost)
4544 TaxiPathSetBySource::iterator src_i = sTaxiPathSetBySource.find(source);
4545 if(src_i==sTaxiPathSetBySource.end())
4547 path = 0;
4548 cost = 0;
4549 return;
4552 TaxiPathSetForSource& pathSet = src_i->second;
4554 TaxiPathSetForSource::iterator dest_i = pathSet.find(destination);
4555 if(dest_i==pathSet.end())
4557 path = 0;
4558 cost = 0;
4559 return;
4562 cost = dest_i->second.price;
4563 path = dest_i->second.ID;
4566 uint16 ObjectMgr::GetTaxiMount( uint32 id, uint32 team )
4568 uint16 mount_entry = 0;
4569 uint16 mount_id = 0;
4571 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(id);
4572 if(node)
4574 if (team == ALLIANCE)
4576 mount_entry = node->MountCreatureID[1];
4577 CreatureInfo const *ci = GetCreatureTemplate(mount_entry);
4578 if(ci)
4579 mount_id = ci->DisplayID_A;
4581 if (team == HORDE)
4583 mount_entry = node->MountCreatureID[0];
4584 CreatureInfo const *ci = GetCreatureTemplate(mount_entry);
4585 if(ci)
4586 mount_id = ci->DisplayID_H;
4590 CreatureModelInfo const *minfo = GetCreatureModelInfo(mount_id);
4591 if(!minfo)
4593 sLog.outErrorDb("Taxi mount (Entry: %u) for taxi node (Id: %u) for team %u has model %u not found in table `creature_model_info`, can't load. ",
4594 mount_entry,id,team,mount_id);
4596 return false;
4598 if(minfo->modelid_other_gender!=0)
4599 mount_id = urand(0,1) ? mount_id : minfo->modelid_other_gender;
4601 return mount_id;
4604 void ObjectMgr::GetTaxiPathNodes( uint32 path, Path &pathnodes, std::vector<uint32>& mapIds)
4606 if(path >= sTaxiPathNodesByPath.size())
4607 return;
4609 TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
4611 pathnodes.Resize(nodeList.size());
4612 mapIds.resize(nodeList.size());
4614 for(size_t i = 0; i < nodeList.size(); ++i)
4616 pathnodes[ i ].x = nodeList[i].x;
4617 pathnodes[ i ].y = nodeList[i].y;
4618 pathnodes[ i ].z = nodeList[i].z;
4620 mapIds[i] = nodeList[i].mapid;
4624 void ObjectMgr::GetTransportPathNodes( uint32 path, TransportPath &pathnodes )
4626 if(path >= sTaxiPathNodesByPath.size())
4627 return;
4629 TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
4631 pathnodes.Resize(nodeList.size());
4633 for(size_t i = 0; i < nodeList.size(); ++i)
4635 pathnodes[ i ].mapid = nodeList[i].mapid;
4636 pathnodes[ i ].x = nodeList[i].x;
4637 pathnodes[ i ].y = nodeList[i].y;
4638 pathnodes[ i ].z = nodeList[i].z;
4639 pathnodes[ i ].actionFlag = nodeList[i].actionFlag;
4640 pathnodes[ i ].delay = nodeList[i].delay;
4644 void ObjectMgr::LoadGraveyardZones()
4646 mGraveYardMap.clear(); // need for reload case
4648 QueryResult *result = WorldDatabase.Query("SELECT id,ghost_zone,faction FROM game_graveyard_zone");
4650 uint32 count = 0;
4652 if( !result )
4654 barGoLink bar( 1 );
4655 bar.step();
4657 sLog.outString();
4658 sLog.outString( ">> Loaded %u graveyard-zone links", count );
4659 return;
4662 barGoLink bar( result->GetRowCount() );
4666 ++count;
4667 bar.step();
4669 Field *fields = result->Fetch();
4671 uint32 safeLocId = fields[0].GetUInt32();
4672 uint32 zoneId = fields[1].GetUInt32();
4673 uint32 team = fields[2].GetUInt32();
4675 WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(safeLocId);
4676 if(!entry)
4678 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",safeLocId);
4679 continue;
4682 AreaTableEntry const *areaEntry = GetAreaEntryByAreaID(zoneId);
4683 if(!areaEntry)
4685 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing zone id (%u), skipped.",zoneId);
4686 continue;
4689 if(areaEntry->zone != 0)
4691 sLog.outErrorDb("Table `game_graveyard_zone` has record subzone id (%u) instead of zone, skipped.",zoneId);
4692 continue;
4695 if(team!=0 && team!=HORDE && team!=ALLIANCE)
4697 sLog.outErrorDb("Table `game_graveyard_zone` has record for non player faction (%u), skipped.",team);
4698 continue;
4701 if(!AddGraveYardLink(safeLocId,zoneId,team,false))
4702 sLog.outErrorDb("Table `game_graveyard_zone` has a duplicate record for Graveyard (ID: %u) and Zone (ID: %u), skipped.",safeLocId,zoneId);
4703 } while( result->NextRow() );
4705 delete result;
4707 sLog.outString();
4708 sLog.outString( ">> Loaded %u graveyard-zone links", count );
4711 WorldSafeLocsEntry const *ObjectMgr::GetClosestGraveYard(float x, float y, float z, uint32 MapId, uint32 team)
4713 // search for zone associated closest graveyard
4714 uint32 zoneId = MapManager::Instance().GetZoneId(MapId,x,y,z);
4716 // Simulate std. algorithm:
4717 // found some graveyard associated to (ghost_zone,ghost_map)
4719 // if mapId == graveyard.mapId (ghost in plain zone or city or battleground) and search graveyard at same map
4720 // then check faction
4721 // if mapId != graveyard.mapId (ghost in instance) and search any graveyard associated
4722 // then check faction
4723 GraveYardMap::const_iterator graveLow = mGraveYardMap.lower_bound(zoneId);
4724 GraveYardMap::const_iterator graveUp = mGraveYardMap.upper_bound(zoneId);
4725 if(graveLow==graveUp)
4727 sLog.outErrorDb("Table `game_graveyard_zone` incomplete: Zone %u Team %u does not have a linked graveyard.",zoneId,team);
4728 return NULL;
4731 // at corpse map
4732 bool foundNear = false;
4733 float distNear;
4734 WorldSafeLocsEntry const* entryNear = NULL;
4736 // at entrance map for corpse map
4737 bool foundEntr = false;
4738 float distEntr;
4739 WorldSafeLocsEntry const* entryEntr = NULL;
4741 // some where other
4742 WorldSafeLocsEntry const* entryFar = NULL;
4744 MapEntry const* mapEntry = sMapStore.LookupEntry(MapId);
4746 for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
4748 GraveYardData const& data = itr->second;
4750 WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(data.safeLocId);
4751 if(!entry)
4753 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",data.safeLocId);
4754 continue;
4757 // skip enemy faction graveyard
4758 // team == 0 case can be at call from .neargrave
4759 if(data.team != 0 && team != 0 && data.team != team)
4760 continue;
4762 // find now nearest graveyard at other map
4763 if(MapId != entry->map_id)
4765 // if find graveyard at different map from where entrance placed (or no entrance data), use any first
4766 if (!mapEntry || mapEntry->entrance_map < 0 || mapEntry->entrance_map != entry->map_id ||
4767 mapEntry->entrance_x == 0 && mapEntry->entrance_y == 0)
4769 // not have any corrdinates for check distance anyway
4770 entryFar = entry;
4771 continue;
4774 // at entrance map calculate distance (2D);
4775 float dist2 = (entry->x - mapEntry->entrance_x)*(entry->x - mapEntry->entrance_x)
4776 +(entry->y - mapEntry->entrance_y)*(entry->y - mapEntry->entrance_y);
4777 if(foundEntr)
4779 if(dist2 < distEntr)
4781 distEntr = dist2;
4782 entryEntr = entry;
4785 else
4787 foundEntr = true;
4788 distEntr = dist2;
4789 entryEntr = entry;
4792 // find now nearest graveyard at same map
4793 else
4795 float dist2 = (entry->x - x)*(entry->x - x)+(entry->y - y)*(entry->y - y)+(entry->z - z)*(entry->z - z);
4796 if(foundNear)
4798 if(dist2 < distNear)
4800 distNear = dist2;
4801 entryNear = entry;
4804 else
4806 foundNear = true;
4807 distNear = dist2;
4808 entryNear = entry;
4813 if(entryNear)
4814 return entryNear;
4816 if(entryEntr)
4817 return entryEntr;
4819 return entryFar;
4822 GraveYardData const* ObjectMgr::FindGraveYardData(uint32 id, uint32 zoneId)
4824 GraveYardMap::const_iterator graveLow = mGraveYardMap.lower_bound(zoneId);
4825 GraveYardMap::const_iterator graveUp = mGraveYardMap.upper_bound(zoneId);
4827 for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
4829 if(itr->second.safeLocId==id)
4830 return &itr->second;
4833 return NULL;
4836 bool ObjectMgr::AddGraveYardLink(uint32 id, uint32 zoneId, uint32 team, bool inDB)
4838 if(FindGraveYardData(id,zoneId))
4839 return false;
4841 // add link to loaded data
4842 GraveYardData data;
4843 data.safeLocId = id;
4844 data.team = team;
4846 mGraveYardMap.insert(GraveYardMap::value_type(zoneId,data));
4848 // add link to DB
4849 if(inDB)
4851 WorldDatabase.PExecuteLog("INSERT INTO game_graveyard_zone ( id,ghost_zone,faction) "
4852 "VALUES ('%u', '%u','%u')",id,zoneId,team);
4855 return true;
4858 void ObjectMgr::LoadAreaTriggerTeleports()
4860 mAreaTriggers.clear(); // need for reload case
4862 uint32 count = 0;
4864 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13
4865 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");
4866 if( !result )
4869 barGoLink bar( 1 );
4871 bar.step();
4873 sLog.outString();
4874 sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
4875 return;
4878 barGoLink bar( result->GetRowCount() );
4882 Field *fields = result->Fetch();
4884 bar.step();
4886 ++count;
4888 uint32 Trigger_ID = fields[0].GetUInt32();
4890 AreaTrigger at;
4892 at.requiredLevel = fields[1].GetUInt8();
4893 at.requiredItem = fields[2].GetUInt32();
4894 at.requiredItem2 = fields[3].GetUInt32();
4895 at.heroicKey = fields[4].GetUInt32();
4896 at.heroicKey2 = fields[5].GetUInt32();
4897 at.requiredQuest = fields[6].GetUInt32();
4898 at.requiredQuestHeroic = fields[7].GetUInt32();
4899 at.requiredFailedText = fields[8].GetCppString();
4900 at.target_mapId = fields[9].GetUInt32();
4901 at.target_X = fields[10].GetFloat();
4902 at.target_Y = fields[11].GetFloat();
4903 at.target_Z = fields[12].GetFloat();
4904 at.target_Orientation = fields[13].GetFloat();
4906 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4907 if(!atEntry)
4909 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4910 continue;
4913 if(at.requiredItem)
4915 ItemPrototype const *pProto = GetItemPrototype(at.requiredItem);
4916 if(!pProto)
4918 sLog.outError("Key item %u does not exist for trigger %u, removing key requirement.", at.requiredItem, Trigger_ID);
4919 at.requiredItem = 0;
4922 if(at.requiredItem2)
4924 ItemPrototype const *pProto = GetItemPrototype(at.requiredItem2);
4925 if(!pProto)
4927 sLog.outError("Second item %u not exist for trigger %u, remove key requirement.", at.requiredItem2, Trigger_ID);
4928 at.requiredItem2 = 0;
4932 if(at.heroicKey)
4934 ItemPrototype const *pProto = GetItemPrototype(at.heroicKey);
4935 if(!pProto)
4937 sLog.outError("Heroic key item %u not exist for trigger %u, remove key requirement.", at.heroicKey, Trigger_ID);
4938 at.heroicKey = 0;
4942 if(at.heroicKey2)
4944 ItemPrototype const *pProto = GetItemPrototype(at.heroicKey2);
4945 if(!pProto)
4947 sLog.outError("Heroic second key item %u not exist for trigger %u, remove key requirement.", at.heroicKey2, Trigger_ID);
4948 at.heroicKey2 = 0;
4952 if(at.requiredQuest)
4954 QuestMap::iterator qReqItr = mQuestTemplates.find(at.requiredQuest);
4955 if(qReqItr == mQuestTemplates.end())
4957 sLog.outErrorDb("Required Quest %u not exist for trigger %u, remove quest done requirement.",at.requiredQuest,Trigger_ID);
4958 at.requiredQuest = 0;
4962 if(at.requiredQuestHeroic)
4964 QuestMap::iterator qReqItr = mQuestTemplates.find(at.requiredQuestHeroic);
4965 if(qReqItr == mQuestTemplates.end())
4967 sLog.outErrorDb("Required Quest %u not exist for trigger %u, remove quest done requirement.",at.requiredQuestHeroic,Trigger_ID);
4968 at.requiredQuestHeroic = 0;
4972 MapEntry const* mapEntry = sMapStore.LookupEntry(at.target_mapId);
4973 if(!mapEntry)
4975 sLog.outErrorDb("Area trigger (ID:%u) target map (ID: %u) does not exist in `Map.dbc`.",Trigger_ID,at.target_mapId);
4976 continue;
4979 if(at.target_X==0 && at.target_Y==0 && at.target_Z==0)
4981 sLog.outErrorDb("Area trigger (ID:%u) target coordinates not provided.",Trigger_ID);
4982 continue;
4985 mAreaTriggers[Trigger_ID] = at;
4987 } while( result->NextRow() );
4989 delete result;
4991 sLog.outString();
4992 sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
4996 * Searches for the areatrigger which teleports players out of the given map
4998 AreaTrigger const* ObjectMgr::GetGoBackTrigger(uint32 Map) const
5000 const MapEntry *mapEntry = sMapStore.LookupEntry(Map);
5001 if(!mapEntry) return NULL;
5002 for (AreaTriggerMap::const_iterator itr = mAreaTriggers.begin(); itr != mAreaTriggers.end(); ++itr)
5004 if(itr->second.target_mapId == mapEntry->entrance_map)
5006 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(itr->first);
5007 if(atEntry && atEntry->mapid == Map)
5008 return &itr->second;
5011 return NULL;
5015 * Searches for the areatrigger which teleports players to the given map
5017 AreaTrigger const* ObjectMgr::GetMapEntranceTrigger(uint32 Map) const
5019 for (AreaTriggerMap::const_iterator itr = mAreaTriggers.begin(); itr != mAreaTriggers.end(); ++itr)
5021 if(itr->second.target_mapId == Map)
5023 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(itr->first);
5024 if(atEntry)
5025 return &itr->second;
5028 return NULL;
5031 void ObjectMgr::SetHighestGuids()
5033 QueryResult *result = CharacterDatabase.Query( "SELECT MAX(guid) FROM characters" );
5034 if( result )
5036 m_hiCharGuid = (*result)[0].GetUInt32()+1;
5037 delete result;
5040 result = WorldDatabase.Query( "SELECT MAX(guid) FROM creature" );
5041 if( result )
5043 m_hiCreatureGuid = (*result)[0].GetUInt32()+1;
5044 delete result;
5047 result = CharacterDatabase.Query( "SELECT MAX(guid) FROM item_instance" );
5048 if( result )
5050 m_hiItemGuid = (*result)[0].GetUInt32()+1;
5051 delete result;
5054 // Cleanup other tables from not existed guids (>=m_hiItemGuid)
5055 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item >= '%u'", m_hiItemGuid);
5056 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid >= '%u'", m_hiItemGuid);
5057 CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE itemguid >= '%u'", m_hiItemGuid);
5058 CharacterDatabase.PExecute("DELETE FROM guild_bank_item WHERE item_guid >= '%u'", m_hiItemGuid);
5060 result = WorldDatabase.Query("SELECT MAX(guid) FROM gameobject" );
5061 if( result )
5063 m_hiGoGuid = (*result)[0].GetUInt32()+1;
5064 delete result;
5067 result = CharacterDatabase.Query("SELECT MAX(id) FROM auctionhouse" );
5068 if( result )
5070 m_auctionid = (*result)[0].GetUInt32()+1;
5071 delete result;
5074 result = CharacterDatabase.Query( "SELECT MAX(id) FROM mail" );
5075 if( result )
5077 m_mailid = (*result)[0].GetUInt32()+1;
5078 delete result;
5081 result = CharacterDatabase.Query( "SELECT MAX(id) FROM item_text" );
5082 if( result )
5084 m_ItemTextId = (*result)[0].GetUInt32()+1;
5085 delete result;
5088 result = CharacterDatabase.Query( "SELECT MAX(guid) FROM corpse" );
5089 if( result )
5091 m_hiCorpseGuid = (*result)[0].GetUInt32()+1;
5092 delete result;
5095 result = CharacterDatabase.Query("SELECT MAX(arenateamid) FROM arena_team");
5096 if (result)
5098 m_arenaTeamId = (*result)[0].GetUInt32()+1;
5099 delete result;
5102 result = CharacterDatabase.Query( "SELECT MAX(guildid) FROM guild" );
5103 if (result)
5105 m_guildId = (*result)[0].GetUInt32()+1;
5106 delete result;
5110 uint32 ObjectMgr::GenerateArenaTeamId()
5112 if(m_arenaTeamId>=0xFFFFFFFE)
5114 sLog.outError("Arena team ids overflow!! Can't continue, shutting down server. ");
5115 World::StopNow(ERROR_EXIT_CODE);
5117 return m_arenaTeamId++;
5120 uint32 ObjectMgr::GenerateAuctionID()
5122 if(m_auctionid>=0xFFFFFFFE)
5124 sLog.outError("Auctions ids overflow!! Can't continue, shutting down server. ");
5125 World::StopNow(ERROR_EXIT_CODE);
5127 return m_auctionid++;
5130 uint32 ObjectMgr::GenerateGuildId()
5132 if(m_guildId>=0xFFFFFFFE)
5134 sLog.outError("Guild ids overflow!! Can't continue, shutting down server. ");
5135 World::StopNow(ERROR_EXIT_CODE);
5137 return m_guildId++;
5140 uint32 ObjectMgr::GenerateMailID()
5142 if(m_mailid>=0xFFFFFFFE)
5144 sLog.outError("Mail ids overflow!! Can't continue, shutting down server. ");
5145 World::StopNow(ERROR_EXIT_CODE);
5147 return m_mailid++;
5150 uint32 ObjectMgr::GenerateItemTextID()
5152 if(m_ItemTextId>=0xFFFFFFFE)
5154 sLog.outError("Item text ids overflow!! Can't continue, shutting down server. ");
5155 World::StopNow(ERROR_EXIT_CODE);
5157 return m_ItemTextId++;
5160 uint32 ObjectMgr::CreateItemText(std::string text)
5162 uint32 newItemTextId = GenerateItemTextID();
5163 //insert new itempage to container
5164 mItemTexts[ newItemTextId ] = text;
5165 //save new itempage
5166 CharacterDatabase.escape_string(text);
5167 //any Delete query needed, itemTextId is maximum of all ids
5168 std::ostringstream query;
5169 query << "INSERT INTO item_text (id,text) VALUES ( '" << newItemTextId << "', '" << text << "')";
5170 CharacterDatabase.Execute(query.str().c_str()); //needs to be run this way, because mail body may be more than 1024 characters
5171 return newItemTextId;
5174 uint32 ObjectMgr::GenerateLowGuid(HighGuid guidhigh)
5176 switch(guidhigh)
5178 case HIGHGUID_ITEM:
5179 if(m_hiItemGuid>=0xFFFFFFFE)
5181 sLog.outError("Item guid overflow!! Can't continue, shutting down server. ");
5182 World::StopNow(ERROR_EXIT_CODE);
5184 return m_hiItemGuid++;
5185 case HIGHGUID_UNIT:
5186 if(m_hiCreatureGuid>=0x00FFFFFE)
5188 sLog.outError("Creature guid overflow!! Can't continue, shutting down server. ");
5189 World::StopNow(ERROR_EXIT_CODE);
5191 return m_hiCreatureGuid++;
5192 case HIGHGUID_PET:
5193 if(m_hiPetGuid>=0x00FFFFFE)
5195 sLog.outError("Pet guid overflow!! Can't continue, shutting down server. ");
5196 World::StopNow(ERROR_EXIT_CODE);
5198 return m_hiPetGuid++;
5199 case HIGHGUID_VEHICLE:
5200 if(m_hiVehicleGuid>=0x00FFFFFF)
5202 sLog.outError("Vehicle guid overflow!! Can't continue, shutting down server. ");
5203 World::StopNow(ERROR_EXIT_CODE);
5205 return m_hiVehicleGuid++;
5206 case HIGHGUID_PLAYER:
5207 if(m_hiCharGuid>=0xFFFFFFFE)
5209 sLog.outError("Players guid overflow!! Can't continue, shutting down server. ");
5210 World::StopNow(ERROR_EXIT_CODE);
5212 return m_hiCharGuid++;
5213 case HIGHGUID_GAMEOBJECT:
5214 if(m_hiGoGuid>=0x00FFFFFE)
5216 sLog.outError("Gameobject guid overflow!! Can't continue, shutting down server. ");
5217 World::StopNow(ERROR_EXIT_CODE);
5219 return m_hiGoGuid++;
5220 case HIGHGUID_CORPSE:
5221 if(m_hiCorpseGuid>=0xFFFFFFFE)
5223 sLog.outError("Corpse guid overflow!! Can't continue, shutting down server. ");
5224 World::StopNow(ERROR_EXIT_CODE);
5226 return m_hiCorpseGuid++;
5227 case HIGHGUID_DYNAMICOBJECT:
5228 if(m_hiDoGuid>=0xFFFFFFFE)
5230 sLog.outError("DynamicObject guid overflow!! Can't continue, shutting down server. ");
5231 World::StopNow(ERROR_EXIT_CODE);
5233 return m_hiDoGuid++;
5234 default:
5235 ASSERT(0);
5238 ASSERT(0);
5239 return 0;
5242 void ObjectMgr::LoadGameObjectLocales()
5244 mGameObjectLocaleMap.clear(); // need for reload case
5246 QueryResult *result = WorldDatabase.Query("SELECT entry,"
5247 "name_loc1,name_loc2,name_loc3,name_loc4,name_loc5,name_loc6,name_loc7,name_loc8,"
5248 "castbarcaption_loc1,castbarcaption_loc2,castbarcaption_loc3,castbarcaption_loc4,"
5249 "castbarcaption_loc5,castbarcaption_loc6,castbarcaption_loc7,castbarcaption_loc8 FROM locales_gameobject");
5251 if(!result)
5253 barGoLink bar(1);
5255 bar.step();
5257 sLog.outString();
5258 sLog.outString(">> Loaded 0 gameobject locale strings. DB table `locales_gameobject` is empty.");
5259 return;
5262 barGoLink bar(result->GetRowCount());
5266 Field *fields = result->Fetch();
5267 bar.step();
5269 uint32 entry = fields[0].GetUInt32();
5271 GameObjectLocale& data = mGameObjectLocaleMap[entry];
5273 for(int i = 1; i < MAX_LOCALE; ++i)
5275 std::string str = fields[i].GetCppString();
5276 if(!str.empty())
5278 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5279 if(idx >= 0)
5281 if(data.Name.size() <= idx)
5282 data.Name.resize(idx+1);
5284 data.Name[idx] = str;
5289 for(int i = 1; i < MAX_LOCALE; ++i)
5291 std::string str = fields[i+(MAX_LOCALE-1)].GetCppString();
5292 if(!str.empty())
5294 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5295 if(idx >= 0)
5297 if(data.CastBarCaption.size() <= idx)
5298 data.CastBarCaption.resize(idx+1);
5300 data.CastBarCaption[idx] = str;
5305 } while (result->NextRow());
5307 delete result;
5309 sLog.outString();
5310 sLog.outString( ">> Loaded %u gameobject locale strings", mGameObjectLocaleMap.size() );
5313 struct SQLGameObjectLoader : public SQLStorageLoaderBase<SQLGameObjectLoader>
5315 template<class D>
5316 void convert_from_str(uint32 field_pos, char *src, D &dst)
5318 dst = D(objmgr.GetScriptId(src));
5322 void ObjectMgr::LoadGameobjectInfo()
5324 SQLGameObjectLoader loader;
5325 loader.Load(sGOStorage);
5327 // some checks
5328 for(uint32 id = 1; id < sGOStorage.MaxEntry; id++)
5330 GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(id);
5331 if(!goInfo)
5332 continue;
5334 switch(goInfo->type)
5336 case GAMEOBJECT_TYPE_DOOR: //0
5338 if(goInfo->door.lockId)
5340 if(!sLockStore.LookupEntry(goInfo->door.lockId))
5341 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but lock (Id: %u) not found.",
5342 id,goInfo->type,goInfo->door.lockId,goInfo->door.lockId);
5344 break;
5346 case GAMEOBJECT_TYPE_BUTTON: //1
5348 if(goInfo->button.lockId)
5350 if(!sLockStore.LookupEntry(goInfo->button.lockId))
5351 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but lock (Id: %u) not found.",
5352 id,goInfo->type,goInfo->button.lockId,goInfo->button.lockId);
5354 break;
5356 case GAMEOBJECT_TYPE_CHEST: //3
5358 if(goInfo->chest.lockId)
5360 if(!sLockStore.LookupEntry(goInfo->chest.lockId))
5361 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but lock (Id: %u) not found.",
5362 id,goInfo->type,goInfo->chest.lockId,goInfo->chest.lockId);
5364 if(goInfo->chest.linkedTrapId) // linked trap
5366 if(GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(goInfo->chest.linkedTrapId))
5368 if(trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5369 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data7=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5370 id,goInfo->type,goInfo->chest.linkedTrapId,goInfo->chest.linkedTrapId,GAMEOBJECT_TYPE_TRAP);
5372 /* disable check for while
5373 else
5374 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5375 id,goInfo->type,goInfo->chest.linkedTrapId,goInfo->chest.linkedTrapId);
5378 break;
5380 case GAMEOBJECT_TYPE_TRAP: //6
5382 /* disable check for while
5383 if(goInfo->trap.spellId) // spell
5385 if(!sSpellStore.LookupEntry(goInfo->trap.spellId))
5386 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data3=%u but Spell (Entry %u) not exist.",
5387 id,goInfo->type,goInfo->trap.spellId,goInfo->trap.spellId);
5390 break;
5392 case GAMEOBJECT_TYPE_CHAIR: //7
5393 if(goInfo->chair.height > (UNIT_STAND_STATE_SIT_HIGH_CHAIR-UNIT_STAND_STATE_SIT_LOW_CHAIR) )
5395 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but correct chair height in range 0..%i.",
5396 id,goInfo->type,goInfo->chair.height,UNIT_STAND_STATE_SIT_HIGH_CHAIR-UNIT_STAND_STATE_SIT_LOW_CHAIR);
5398 // prevent client and server unexpected work
5399 const_cast<GameObjectInfo*>(goInfo)->chair.height = 0;
5401 break;
5402 case GAMEOBJECT_TYPE_SPELL_FOCUS: //8
5404 if(goInfo->spellFocus.focusId)
5406 if(!sSpellFocusObjectStore.LookupEntry(goInfo->spellFocus.focusId))
5407 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but SpellFocus (Id: %u) not exist.",
5408 id,goInfo->type,goInfo->spellFocus.focusId,goInfo->spellFocus.focusId);
5411 if(goInfo->spellFocus.linkedTrapId) // linked trap
5413 if(GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(goInfo->spellFocus.linkedTrapId))
5415 if(trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5416 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5417 id,goInfo->type,goInfo->spellFocus.linkedTrapId,goInfo->spellFocus.linkedTrapId,GAMEOBJECT_TYPE_TRAP);
5419 /* disable check for while
5420 else
5421 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5422 id,goInfo->type,goInfo->spellFocus.linkedTrapId,goInfo->spellFocus.linkedTrapId);
5425 break;
5427 case GAMEOBJECT_TYPE_GOOBER: //10
5429 if(goInfo->goober.pageId) // pageId
5431 if(!sPageTextStore.LookupEntry<PageText>(goInfo->goober.pageId))
5432 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data7=%u but PageText (Entry %u) not exist.",
5433 id,goInfo->type,goInfo->goober.pageId,goInfo->goober.pageId);
5435 /* disable check for while
5436 if(goInfo->goober.spellId) // spell
5438 if(!sSpellStore.LookupEntry(goInfo->goober.spellId))
5439 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but Spell (Entry %u) not exist.",
5440 id,goInfo->type,goInfo->goober.spellId,goInfo->goober.spellId);
5443 if(goInfo->goober.linkedTrapId) // linked trap
5445 if(GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(goInfo->goober.linkedTrapId))
5447 if(trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5448 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data12=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5449 id,goInfo->type,goInfo->goober.linkedTrapId,goInfo->goober.linkedTrapId,GAMEOBJECT_TYPE_TRAP);
5451 /* disable check for while
5452 else
5453 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data12=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5454 id,goInfo->type,goInfo->goober.linkedTrapId,goInfo->goober.linkedTrapId);
5457 break;
5459 case GAMEOBJECT_TYPE_MO_TRANSPORT: //15
5461 if(goInfo->moTransport.taxiPathId)
5463 if(goInfo->moTransport.taxiPathId >= sTaxiPathNodesByPath.size() || sTaxiPathNodesByPath[goInfo->moTransport.taxiPathId].empty())
5464 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but TaxiPath (Id: %u) not exist.",
5465 id,goInfo->type,goInfo->moTransport.taxiPathId,goInfo->moTransport.taxiPathId);
5467 break;
5469 case GAMEOBJECT_TYPE_SUMMONING_RITUAL: //18
5471 /* disabled
5472 if(goInfo->summoningRitual.spellId)
5474 if(!sSpellStore.LookupEntry(goInfo->summoningRitual.spellId))
5475 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but Spell (Entry %u) not exist.",
5476 id,goInfo->type,goInfo->summoningRitual.spellId,goInfo->summoningRitual.spellId);
5479 break;
5481 case GAMEOBJECT_TYPE_SPELLCASTER: //22
5483 if(goInfo->spellcaster.spellId) // spell
5485 if(!sSpellStore.LookupEntry(goInfo->spellcaster.spellId))
5486 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data3=%u but Spell (Entry %u) not exist.",
5487 id,goInfo->type,goInfo->spellcaster.spellId,goInfo->spellcaster.spellId);
5489 break;
5491 case GAMEOBJECT_TYPE_BARBER_CHAIR: //32
5492 if(goInfo->barberChair.chairheight > (UNIT_STAND_STATE_SIT_HIGH_CHAIR-UNIT_STAND_STATE_SIT_LOW_CHAIR) )
5494 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but correct chair height in range 0..%i.",
5495 id,goInfo->type,goInfo->barberChair.chairheight,UNIT_STAND_STATE_SIT_HIGH_CHAIR-UNIT_STAND_STATE_SIT_LOW_CHAIR);
5497 // prevent client and server unexpected work
5498 const_cast<GameObjectInfo*>(goInfo)->barberChair.chairheight = 0;
5500 break;
5504 sLog.outString( ">> Loaded %u game object templates", sGOStorage.RecordCount );
5505 sLog.outString();
5508 void ObjectMgr::LoadExplorationBaseXP()
5510 uint32 count = 0;
5511 QueryResult *result = WorldDatabase.Query("SELECT level,basexp FROM exploration_basexp");
5513 if( !result )
5515 barGoLink bar( 1 );
5517 bar.step();
5519 sLog.outString();
5520 sLog.outString( ">> Loaded %u BaseXP definitions", count );
5521 return;
5524 barGoLink bar( result->GetRowCount() );
5528 bar.step();
5530 Field *fields = result->Fetch();
5531 uint32 level = fields[0].GetUInt32();
5532 uint32 basexp = fields[1].GetUInt32();
5533 mBaseXPTable[level] = basexp;
5534 ++count;
5536 while (result->NextRow());
5538 delete result;
5540 sLog.outString();
5541 sLog.outString( ">> Loaded %u BaseXP definitions", count );
5544 uint32 ObjectMgr::GetBaseXP(uint32 level)
5546 return mBaseXPTable[level] ? mBaseXPTable[level] : 0;
5549 uint32 ObjectMgr::GetXPForLevel(uint32 level)
5551 if (level < mPlayerXPperLevel.size())
5552 return mPlayerXPperLevel[level];
5553 return 0;
5556 void ObjectMgr::LoadPetNames()
5558 uint32 count = 0;
5559 QueryResult *result = WorldDatabase.Query("SELECT word,entry,half FROM pet_name_generation");
5561 if( !result )
5563 barGoLink bar( 1 );
5565 bar.step();
5567 sLog.outString();
5568 sLog.outString( ">> Loaded %u pet name parts", count );
5569 return;
5572 barGoLink bar( result->GetRowCount() );
5576 bar.step();
5578 Field *fields = result->Fetch();
5579 std::string word = fields[0].GetString();
5580 uint32 entry = fields[1].GetUInt32();
5581 bool half = fields[2].GetBool();
5582 if(half)
5583 PetHalfName1[entry].push_back(word);
5584 else
5585 PetHalfName0[entry].push_back(word);
5586 ++count;
5588 while (result->NextRow());
5589 delete result;
5591 sLog.outString();
5592 sLog.outString( ">> Loaded %u pet name parts", count );
5595 void ObjectMgr::LoadPetNumber()
5597 QueryResult* result = CharacterDatabase.Query("SELECT MAX(id) FROM character_pet");
5598 if(result)
5600 Field *fields = result->Fetch();
5601 m_hiPetNumber = fields[0].GetUInt32()+1;
5602 delete result;
5605 barGoLink bar( 1 );
5606 bar.step();
5608 sLog.outString();
5609 sLog.outString( ">> Loaded the max pet number: %d", m_hiPetNumber-1);
5612 std::string ObjectMgr::GeneratePetName(uint32 entry)
5614 std::vector<std::string> & list0 = PetHalfName0[entry];
5615 std::vector<std::string> & list1 = PetHalfName1[entry];
5617 if(list0.empty() || list1.empty())
5619 CreatureInfo const *cinfo = GetCreatureTemplate(entry);
5620 char* petname = GetPetName(cinfo->family, sWorld.GetDefaultDbcLocale());
5621 if(!petname)
5622 petname = cinfo->Name;
5623 return std::string(petname);
5626 return *(list0.begin()+urand(0, list0.size()-1)) + *(list1.begin()+urand(0, list1.size()-1));
5629 uint32 ObjectMgr::GeneratePetNumber()
5631 return ++m_hiPetNumber;
5634 void ObjectMgr::LoadCorpses()
5636 uint32 count = 0;
5637 // 0 1 2 3 4 5 6 7 8 10
5638 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");
5640 if( !result )
5642 barGoLink bar( 1 );
5644 bar.step();
5646 sLog.outString();
5647 sLog.outString( ">> Loaded %u corpses", count );
5648 return;
5651 barGoLink bar( result->GetRowCount() );
5655 bar.step();
5657 Field *fields = result->Fetch();
5659 uint32 guid = fields[result->GetFieldCount()-1].GetUInt32();
5661 Corpse *corpse = new Corpse;
5662 if(!corpse->LoadFromDB(guid,fields))
5664 delete corpse;
5665 continue;
5668 ObjectAccessor::Instance().AddCorpse(corpse);
5670 ++count;
5672 while (result->NextRow());
5673 delete result;
5675 sLog.outString();
5676 sLog.outString( ">> Loaded %u corpses", count );
5679 void ObjectMgr::LoadReputationOnKill()
5681 uint32 count = 0;
5683 // 0 1 2
5684 QueryResult *result = WorldDatabase.Query("SELECT creature_id, RewOnKillRepFaction1, RewOnKillRepFaction2,"
5685 // 3 4 5 6 7 8 9
5686 "IsTeamAward1, MaxStanding1, RewOnKillRepValue1, IsTeamAward2, MaxStanding2, RewOnKillRepValue2, TeamDependent "
5687 "FROM creature_onkill_reputation");
5689 if(!result)
5691 barGoLink bar(1);
5693 bar.step();
5695 sLog.outString();
5696 sLog.outErrorDb(">> Loaded 0 creature award reputation definitions. DB table `creature_onkill_reputation` is empty.");
5697 return;
5700 barGoLink bar(result->GetRowCount());
5704 Field *fields = result->Fetch();
5705 bar.step();
5707 uint32 creature_id = fields[0].GetUInt32();
5709 ReputationOnKillEntry repOnKill;
5710 repOnKill.repfaction1 = fields[1].GetUInt32();
5711 repOnKill.repfaction2 = fields[2].GetUInt32();
5712 repOnKill.is_teamaward1 = fields[3].GetBool();
5713 repOnKill.reputation_max_cap1 = fields[4].GetUInt32();
5714 repOnKill.repvalue1 = fields[5].GetInt32();
5715 repOnKill.is_teamaward2 = fields[6].GetBool();
5716 repOnKill.reputation_max_cap2 = fields[7].GetUInt32();
5717 repOnKill.repvalue2 = fields[8].GetInt32();
5718 repOnKill.team_dependent = fields[9].GetUInt8();
5720 if(!GetCreatureTemplate(creature_id))
5722 sLog.outErrorDb("Table `creature_onkill_reputation` have data for not existed creature entry (%u), skipped",creature_id);
5723 continue;
5726 if(repOnKill.repfaction1)
5728 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(repOnKill.repfaction1);
5729 if(!factionEntry1)
5731 sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction1);
5732 continue;
5736 if(repOnKill.repfaction2)
5738 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(repOnKill.repfaction2);
5739 if(!factionEntry2)
5741 sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction2);
5742 continue;
5746 mRepOnKill[creature_id] = repOnKill;
5748 ++count;
5749 } while (result->NextRow());
5751 delete result;
5753 sLog.outString();
5754 sLog.outString(">> Loaded %u creature award reputation definitions", count);
5757 void ObjectMgr::LoadPointsOfInterest()
5759 uint32 count = 0;
5761 // 0 1 2 3 4 5
5762 QueryResult *result = WorldDatabase.Query("SELECT entry, x, y, icon, flags, data, icon_name FROM points_of_interest");
5764 if(!result)
5766 barGoLink bar(1);
5768 bar.step();
5770 sLog.outString();
5771 sLog.outErrorDb(">> Loaded 0 Points of Interest definitions. DB table `points_of_interest` is empty.");
5772 return;
5775 barGoLink bar(result->GetRowCount());
5779 Field *fields = result->Fetch();
5780 bar.step();
5782 uint32 point_id = fields[0].GetUInt32();
5784 PointOfInterest POI;
5785 POI.x = fields[1].GetFloat();
5786 POI.y = fields[2].GetFloat();
5787 POI.icon = fields[3].GetUInt32();
5788 POI.flags = fields[4].GetUInt32();
5789 POI.data = fields[5].GetUInt32();
5790 POI.icon_name = fields[6].GetCppString();
5792 if(!MaNGOS::IsValidMapCoord(POI.x,POI.y))
5794 sLog.outErrorDb("Table `points_of_interest` (Entry: %u) have invalid coordinates (X: %f Y: %f), ignored.",point_id,POI.x,POI.y);
5795 continue;
5798 mPointsOfInterest[point_id] = POI;
5800 ++count;
5801 } while (result->NextRow());
5803 delete result;
5805 sLog.outString();
5806 sLog.outString(">> Loaded %u Points of Interest definitions", count);
5809 void ObjectMgr::LoadWeatherZoneChances()
5811 uint32 count = 0;
5813 // 0 1 2 3 4 5 6 7 8 9 10 11 12
5814 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");
5816 if(!result)
5818 barGoLink bar(1);
5820 bar.step();
5822 sLog.outString();
5823 sLog.outErrorDb(">> Loaded 0 weather definitions. DB table `game_weather` is empty.");
5824 return;
5827 barGoLink bar(result->GetRowCount());
5831 Field *fields = result->Fetch();
5832 bar.step();
5834 uint32 zone_id = fields[0].GetUInt32();
5836 WeatherZoneChances& wzc = mWeatherZoneMap[zone_id];
5838 for(int season = 0; season < WEATHER_SEASONS; ++season)
5840 wzc.data[season].rainChance = fields[season * (MAX_WEATHER_TYPE-1) + 1].GetUInt32();
5841 wzc.data[season].snowChance = fields[season * (MAX_WEATHER_TYPE-1) + 2].GetUInt32();
5842 wzc.data[season].stormChance = fields[season * (MAX_WEATHER_TYPE-1) + 3].GetUInt32();
5844 if(wzc.data[season].rainChance > 100)
5846 wzc.data[season].rainChance = 25;
5847 sLog.outErrorDb("Weather for zone %u season %u has wrong rain chance > 100%%",zone_id,season);
5850 if(wzc.data[season].snowChance > 100)
5852 wzc.data[season].snowChance = 25;
5853 sLog.outErrorDb("Weather for zone %u season %u has wrong snow chance > 100%%",zone_id,season);
5856 if(wzc.data[season].stormChance > 100)
5858 wzc.data[season].stormChance = 25;
5859 sLog.outErrorDb("Weather for zone %u season %u has wrong storm chance > 100%%",zone_id,season);
5863 ++count;
5864 } while (result->NextRow());
5866 delete result;
5868 sLog.outString();
5869 sLog.outString(">> Loaded %u weather definitions", count);
5872 void ObjectMgr::SaveCreatureRespawnTime(uint32 loguid, uint32 instance, time_t t)
5874 mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
5875 WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
5876 if(t)
5877 WorldDatabase.PExecute("INSERT INTO creature_respawn VALUES ( '%u', '" I64FMTD "', '%u' )", loguid, uint64(t), instance);
5880 void ObjectMgr::DeleteCreatureData(uint32 guid)
5882 // remove mapid*cellid -> guid_set map
5883 CreatureData const* data = GetCreatureData(guid);
5884 if(data)
5885 RemoveCreatureFromGrid(guid, data);
5887 mCreatureDataMap.erase(guid);
5890 void ObjectMgr::SaveGORespawnTime(uint32 loguid, uint32 instance, time_t t)
5892 mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
5893 WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
5894 if(t)
5895 WorldDatabase.PExecute("INSERT INTO gameobject_respawn VALUES ( '%u', '" I64FMTD "', '%u' )", loguid, uint64(t), instance);
5898 void ObjectMgr::DeleteRespawnTimeForInstance(uint32 instance)
5900 RespawnTimes::iterator next;
5902 for(RespawnTimes::iterator itr = mGORespawnTimes.begin(); itr != mGORespawnTimes.end(); itr = next)
5904 next = itr;
5905 ++next;
5907 if(GUID_HIPART(itr->first)==instance)
5908 mGORespawnTimes.erase(itr);
5911 for(RespawnTimes::iterator itr = mCreatureRespawnTimes.begin(); itr != mCreatureRespawnTimes.end(); itr = next)
5913 next = itr;
5914 ++next;
5916 if(GUID_HIPART(itr->first)==instance)
5917 mCreatureRespawnTimes.erase(itr);
5920 WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE instance = '%u'", instance);
5921 WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE instance = '%u'", instance);
5924 void ObjectMgr::DeleteGOData(uint32 guid)
5926 // remove mapid*cellid -> guid_set map
5927 GameObjectData const* data = GetGOData(guid);
5928 if(data)
5929 RemoveGameobjectFromGrid(guid, data);
5931 mGameObjectDataMap.erase(guid);
5934 void ObjectMgr::AddCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid, uint32 instance)
5936 // corpses are always added to spawn mode 0 and they are spawned by their instance id
5937 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
5938 cell_guids.corpses[player_guid] = instance;
5941 void ObjectMgr::DeleteCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid)
5943 // corpses are always added to spawn mode 0 and they are spawned by their instance id
5944 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
5945 cell_guids.corpses.erase(player_guid);
5948 void ObjectMgr::LoadQuestRelationsHelper(QuestRelations& map,char const* table)
5950 map.clear(); // need for reload case
5952 uint32 count = 0;
5954 QueryResult *result = WorldDatabase.PQuery("SELECT id,quest FROM %s",table);
5956 if(!result)
5958 barGoLink bar(1);
5960 bar.step();
5962 sLog.outString();
5963 sLog.outErrorDb(">> Loaded 0 quest relations from %s. DB table `%s` is empty.",table,table);
5964 return;
5967 barGoLink bar(result->GetRowCount());
5971 Field *fields = result->Fetch();
5972 bar.step();
5974 uint32 id = fields[0].GetUInt32();
5975 uint32 quest = fields[1].GetUInt32();
5977 if(mQuestTemplates.find(quest) == mQuestTemplates.end())
5979 sLog.outErrorDb("Table `%s: Quest %u listed for entry %u does not exist.",table,quest,id);
5980 continue;
5983 map.insert(QuestRelations::value_type(id,quest));
5985 ++count;
5986 } while (result->NextRow());
5988 delete result;
5990 sLog.outString();
5991 sLog.outString(">> Loaded %u quest relations from %s", count,table);
5994 void ObjectMgr::LoadGameobjectQuestRelations()
5996 LoadQuestRelationsHelper(mGOQuestRelations,"gameobject_questrelation");
5998 for(QuestRelations::iterator itr = mGOQuestRelations.begin(); itr != mGOQuestRelations.end(); ++itr)
6000 GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
6001 if(!goInfo)
6002 sLog.outErrorDb("Table `gameobject_questrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
6003 else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
6004 sLog.outErrorDb("Table `gameobject_questrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
6008 void ObjectMgr::LoadGameobjectInvolvedRelations()
6010 LoadQuestRelationsHelper(mGOQuestInvolvedRelations,"gameobject_involvedrelation");
6012 for(QuestRelations::iterator itr = mGOQuestInvolvedRelations.begin(); itr != mGOQuestInvolvedRelations.end(); ++itr)
6014 GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
6015 if(!goInfo)
6016 sLog.outErrorDb("Table `gameobject_involvedrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
6017 else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
6018 sLog.outErrorDb("Table `gameobject_involvedrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
6022 void ObjectMgr::LoadCreatureQuestRelations()
6024 LoadQuestRelationsHelper(mCreatureQuestRelations,"creature_questrelation");
6026 for(QuestRelations::iterator itr = mCreatureQuestRelations.begin(); itr != mCreatureQuestRelations.end(); ++itr)
6028 CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
6029 if(!cInfo)
6030 sLog.outErrorDb("Table `creature_questrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
6031 else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
6032 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);
6036 void ObjectMgr::LoadCreatureInvolvedRelations()
6038 LoadQuestRelationsHelper(mCreatureQuestInvolvedRelations,"creature_involvedrelation");
6040 for(QuestRelations::iterator itr = mCreatureQuestInvolvedRelations.begin(); itr != mCreatureQuestInvolvedRelations.end(); ++itr)
6042 CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
6043 if(!cInfo)
6044 sLog.outErrorDb("Table `creature_involvedrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
6045 else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
6046 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);
6050 void ObjectMgr::LoadReservedPlayersNames()
6052 m_ReservedNames.clear(); // need for reload case
6054 QueryResult *result = WorldDatabase.Query("SELECT name FROM reserved_name");
6056 uint32 count = 0;
6058 if( !result )
6060 barGoLink bar( 1 );
6061 bar.step();
6063 sLog.outString();
6064 sLog.outString( ">> Loaded %u reserved player names", count );
6065 return;
6068 barGoLink bar( result->GetRowCount() );
6070 Field* fields;
6073 bar.step();
6074 fields = result->Fetch();
6075 std::string name= fields[0].GetCppString();
6077 std::wstring wstr;
6078 if(!Utf8toWStr (name,wstr))
6080 sLog.outError("Table `reserved_name` have invalid name: %s", name.c_str() );
6081 continue;
6084 wstrToLower(wstr);
6086 m_ReservedNames.insert(wstr);
6087 ++count;
6088 } while ( result->NextRow() );
6090 delete result;
6092 sLog.outString();
6093 sLog.outString( ">> Loaded %u reserved player names", count );
6096 bool ObjectMgr::IsReservedName( const std::string& name ) const
6098 std::wstring wstr;
6099 if(!Utf8toWStr (name,wstr))
6100 return false;
6102 wstrToLower(wstr);
6104 return m_ReservedNames.find(wstr) != m_ReservedNames.end();
6107 enum LanguageType
6109 LT_BASIC_LATIN = 0x0000,
6110 LT_EXTENDEN_LATIN = 0x0001,
6111 LT_CYRILLIC = 0x0002,
6112 LT_EAST_ASIA = 0x0004,
6113 LT_ANY = 0xFFFF
6116 static LanguageType GetRealmLanguageType(bool create)
6118 switch(sWorld.getConfig(CONFIG_REALM_ZONE))
6120 case REALM_ZONE_UNKNOWN: // any language
6121 case REALM_ZONE_DEVELOPMENT:
6122 case REALM_ZONE_TEST_SERVER:
6123 case REALM_ZONE_QA_SERVER:
6124 return LT_ANY;
6125 case REALM_ZONE_UNITED_STATES: // extended-Latin
6126 case REALM_ZONE_OCEANIC:
6127 case REALM_ZONE_LATIN_AMERICA:
6128 case REALM_ZONE_ENGLISH:
6129 case REALM_ZONE_GERMAN:
6130 case REALM_ZONE_FRENCH:
6131 case REALM_ZONE_SPANISH:
6132 return LT_EXTENDEN_LATIN;
6133 case REALM_ZONE_KOREA: // East-Asian
6134 case REALM_ZONE_TAIWAN:
6135 case REALM_ZONE_CHINA:
6136 return LT_EAST_ASIA;
6137 case REALM_ZONE_RUSSIAN: // Cyrillic
6138 return LT_CYRILLIC;
6139 default:
6140 return create ? LT_BASIC_LATIN : LT_ANY; // basic-Latin at create, any at login
6144 bool isValidString(std::wstring wstr, uint32 strictMask, bool numericOrSpace, bool create = false)
6146 if(strictMask==0) // any language, ignore realm
6148 if(isExtendedLatinString(wstr,numericOrSpace))
6149 return true;
6150 if(isCyrillicString(wstr,numericOrSpace))
6151 return true;
6152 if(isEastAsianString(wstr,numericOrSpace))
6153 return true;
6154 return false;
6157 if(strictMask & 0x2) // realm zone specific
6159 LanguageType lt = GetRealmLanguageType(create);
6160 if(lt & LT_EXTENDEN_LATIN)
6161 if(isExtendedLatinString(wstr,numericOrSpace))
6162 return true;
6163 if(lt & LT_CYRILLIC)
6164 if(isCyrillicString(wstr,numericOrSpace))
6165 return true;
6166 if(lt & LT_EAST_ASIA)
6167 if(isEastAsianString(wstr,numericOrSpace))
6168 return true;
6171 if(strictMask & 0x1) // basic Latin
6173 if(isBasicLatinString(wstr,numericOrSpace))
6174 return true;
6177 return false;
6180 bool ObjectMgr::IsValidName( const std::string& name, bool create )
6182 std::wstring wname;
6183 if(!Utf8toWStr(name,wname))
6184 return false;
6186 if(wname.size() < 1 || wname.size() > MAX_PLAYER_NAME)
6187 return false;
6189 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_PLAYER_NAMES);
6191 return isValidString(wname,strictMask,false,create);
6194 bool ObjectMgr::IsValidCharterName( const std::string& name )
6196 std::wstring wname;
6197 if(!Utf8toWStr(name,wname))
6198 return false;
6200 if(wname.size() < 1)
6201 return false;
6203 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_CHARTER_NAMES);
6205 return isValidString(wname,strictMask,true);
6208 bool ObjectMgr::IsValidPetName( const std::string& name )
6210 std::wstring wname;
6211 if(!Utf8toWStr(name,wname))
6212 return false;
6214 if(wname.size() < 1)
6215 return false;
6217 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_PET_NAMES);
6219 return isValidString(wname,strictMask,false);
6222 int ObjectMgr::GetIndexForLocale( LocaleConstant loc )
6224 if(loc==LOCALE_enUS)
6225 return -1;
6227 for(size_t i=0;i < m_LocalForIndex.size(); ++i)
6228 if(m_LocalForIndex[i]==loc)
6229 return i;
6231 return -1;
6234 LocaleConstant ObjectMgr::GetLocaleForIndex(int i)
6236 if (i<0 || i>=m_LocalForIndex.size())
6237 return LOCALE_enUS;
6239 return m_LocalForIndex[i];
6242 int ObjectMgr::GetOrNewIndexForLocale( LocaleConstant loc )
6244 if(loc==LOCALE_enUS)
6245 return -1;
6247 for(size_t i=0;i < m_LocalForIndex.size(); ++i)
6248 if(m_LocalForIndex[i]==loc)
6249 return i;
6251 m_LocalForIndex.push_back(loc);
6252 return m_LocalForIndex.size()-1;
6255 void ObjectMgr::LoadGameObjectForQuests()
6257 mGameObjectForQuestSet.clear(); // need for reload case
6259 if( !sGOStorage.MaxEntry )
6261 barGoLink bar( 1 );
6262 bar.step();
6263 sLog.outString();
6264 sLog.outString( ">> Loaded 0 GameObjects for quests" );
6265 return;
6268 barGoLink bar( sGOStorage.MaxEntry - 1 );
6269 uint32 count = 0;
6271 // collect GO entries for GO that must activated
6272 for(uint32 go_entry = 1; go_entry < sGOStorage.MaxEntry; ++go_entry)
6274 bar.step();
6275 GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(go_entry);
6276 if(!goInfo)
6277 continue;
6279 switch(goInfo->type)
6281 // scan GO chest with loot including quest items
6282 case GAMEOBJECT_TYPE_CHEST:
6284 uint32 loot_id = GameObject::GetLootId(goInfo);
6286 // find quest loot for GO
6287 if(LootTemplates_Gameobject.HaveQuestLootFor(loot_id))
6289 mGameObjectForQuestSet.insert(go_entry);
6290 ++count;
6292 break;
6294 case GAMEOBJECT_TYPE_GOOBER:
6296 if(goInfo->goober.questId) //quests objects
6298 mGameObjectForQuestSet.insert(go_entry);
6299 count++;
6301 break;
6303 default:
6304 break;
6308 sLog.outString();
6309 sLog.outString( ">> Loaded %u GameObjects for quests", count );
6312 bool ObjectMgr::LoadMangosStrings(DatabaseType& db, char const* table, int32 min_value, int32 max_value)
6314 // cleanup affected map part for reloading case
6315 for(MangosStringLocaleMap::iterator itr = mMangosStringLocaleMap.begin(); itr != mMangosStringLocaleMap.end();)
6317 if(itr->first >= min_value && itr->first <= max_value)
6319 MangosStringLocaleMap::iterator itr2 = itr;
6320 ++itr;
6321 mMangosStringLocaleMap.erase(itr2);
6323 else
6324 ++itr;
6327 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);
6329 if(!result)
6331 barGoLink bar(1);
6333 bar.step();
6335 sLog.outString();
6336 if(min_value == MIN_MANGOS_STRING_ID) // error only in case internal strings
6337 sLog.outErrorDb(">> Loaded 0 mangos strings. DB table `%s` is empty. Cannot continue.",table);
6338 else
6339 sLog.outString(">> Loaded 0 string templates. DB table `%s` is empty.",table);
6340 return false;
6343 uint32 count = 0;
6345 barGoLink bar(result->GetRowCount());
6349 Field *fields = result->Fetch();
6350 bar.step();
6352 int32 entry = fields[0].GetInt32();
6354 if(entry==0)
6356 sLog.outErrorDb("Table `%s` contain reserved entry 0, ignored.",table);
6357 continue;
6359 else if(entry < min_value || entry > max_value)
6361 int32 start = min_value > 0 ? min_value : max_value;
6362 int32 end = min_value > 0 ? max_value : min_value;
6363 sLog.outErrorDb("Table `%s` contain entry %i out of allowed range (%d - %d), ignored.",table,entry,start,end);
6364 continue;
6367 MangosStringLocale& data = mMangosStringLocaleMap[entry];
6369 if(data.Content.size() > 0)
6371 sLog.outErrorDb("Table `%s` contain data for already loaded entry %i (from another table?), ignored.",table,entry);
6372 continue;
6375 data.Content.resize(1);
6376 ++count;
6378 // 0 -> default, idx in to idx+1
6379 data.Content[0] = fields[1].GetCppString();
6381 for(int i = 1; i < MAX_LOCALE; ++i)
6383 std::string str = fields[i+1].GetCppString();
6384 if(!str.empty())
6386 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
6387 if(idx >= 0)
6389 // 0 -> default, idx in to idx+1
6390 if(data.Content.size() <= idx+1)
6391 data.Content.resize(idx+2);
6393 data.Content[idx+1] = str;
6397 } while (result->NextRow());
6399 delete result;
6401 sLog.outString();
6402 if(min_value == MIN_MANGOS_STRING_ID) // error only in case internal strings
6403 sLog.outString( ">> Loaded %u MaNGOS strings from table %s", count,table);
6404 else
6405 sLog.outString( ">> Loaded %u string templates from %s", count,table);
6407 return true;
6410 const char *ObjectMgr::GetMangosString(int32 entry, int locale_idx) const
6412 // locale_idx==-1 -> default, locale_idx >= 0 in to idx+1
6413 // Content[0] always exist if exist MangosStringLocale
6414 if(MangosStringLocale const *msl = GetMangosStringLocale(entry))
6416 if(msl->Content.size() > locale_idx+1 && !msl->Content[locale_idx+1].empty())
6417 return msl->Content[locale_idx+1].c_str();
6418 else
6419 return msl->Content[0].c_str();
6422 if(entry > 0)
6423 sLog.outErrorDb("Entry %i not found in `mangos_string` table.",entry);
6424 else
6425 sLog.outErrorDb("Mangos string entry %i not found in DB.",entry);
6426 return "<error>";
6429 void ObjectMgr::LoadFishingBaseSkillLevel()
6431 mFishingBaseForArea.clear(); // for reload case
6433 uint32 count = 0;
6434 QueryResult *result = WorldDatabase.Query("SELECT entry,skill FROM skill_fishing_base_level");
6436 if( !result )
6438 barGoLink bar( 1 );
6440 bar.step();
6442 sLog.outString();
6443 sLog.outErrorDb(">> Loaded `skill_fishing_base_level`, table is empty!");
6444 return;
6447 barGoLink bar( result->GetRowCount() );
6451 bar.step();
6453 Field *fields = result->Fetch();
6454 uint32 entry = fields[0].GetUInt32();
6455 int32 skill = fields[1].GetInt32();
6457 AreaTableEntry const* fArea = GetAreaEntryByAreaID(entry);
6458 if(!fArea)
6460 sLog.outErrorDb("AreaId %u defined in `skill_fishing_base_level` does not exist",entry);
6461 continue;
6464 mFishingBaseForArea[entry] = skill;
6465 ++count;
6467 while (result->NextRow());
6469 delete result;
6471 sLog.outString();
6472 sLog.outString( ">> Loaded %u areas for fishing base skill level", count );
6475 // Searches for the same condition already in Conditions store
6476 // Returns Id if found, else adds it to Conditions and returns Id
6477 uint16 ObjectMgr::GetConditionId( ConditionType condition, uint32 value1, uint32 value2 )
6479 PlayerCondition lc = PlayerCondition(condition, value1, value2);
6480 for (uint16 i=0; i < mConditions.size(); ++i)
6482 if (lc == mConditions[i])
6483 return i;
6486 mConditions.push_back(lc);
6488 if(mConditions.size() > 0xFFFF)
6490 sLog.outError("Conditions store overflow! Current and later loaded conditions will ignored!");
6491 return 0;
6494 return mConditions.size() - 1;
6497 bool ObjectMgr::CheckDeclinedNames( std::wstring mainpart, DeclinedName const& names )
6499 for(int i =0; i < MAX_DECLINED_NAME_CASES; ++i)
6501 std::wstring wname;
6502 if(!Utf8toWStr(names.name[i],wname))
6503 return false;
6505 if(mainpart!=GetMainPartOfName(wname,i+1))
6506 return false;
6508 return true;
6511 uint32 ObjectMgr::GetAreaTriggerScriptId(uint32 trigger_id)
6513 AreaTriggerScriptMap::const_iterator i = mAreaTriggerScripts.find(trigger_id);
6514 if(i!= mAreaTriggerScripts.end())
6515 return i->second;
6516 return 0;
6519 // Checks if player meets the condition
6520 bool PlayerCondition::Meets(Player const * player) const
6522 if( !player )
6523 return false; // player not present, return false
6525 switch (condition)
6527 case CONDITION_NONE:
6528 return true; // empty condition, always met
6529 case CONDITION_AURA:
6530 return player->HasAura(value1, value2);
6531 case CONDITION_ITEM:
6532 return player->HasItemCount(value1, value2);
6533 case CONDITION_ITEM_EQUIPPED:
6534 return player->HasItemOrGemWithIdEquipped(value1,1);
6535 case CONDITION_ZONEID:
6536 return player->GetZoneId() == value1;
6537 case CONDITION_REPUTATION_RANK:
6539 FactionEntry const* faction = sFactionStore.LookupEntry(value1);
6540 return faction && player->GetReputationRank(faction) >= value2;
6542 case CONDITION_TEAM:
6543 return player->GetTeam() == value1;
6544 case CONDITION_SKILL:
6545 return player->HasSkill(value1) && player->GetBaseSkillValue(value1) >= value2;
6546 case CONDITION_QUESTREWARDED:
6547 return player->GetQuestRewardStatus(value1);
6548 case CONDITION_QUESTTAKEN:
6550 QuestStatus status = player->GetQuestStatus(value1);
6551 return (status == QUEST_STATUS_INCOMPLETE);
6553 case CONDITION_AD_COMMISSION_AURA:
6555 Unit::AuraMap const& auras = player->GetAuras();
6556 for(Unit::AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
6557 if((itr->second->GetSpellProto()->Attributes & 0x1000010) && itr->second->GetSpellProto()->SpellVisual[0]==3580)
6558 return true;
6559 return false;
6561 case CONDITION_NO_AURA:
6562 return !player->HasAura(value1, value2);
6563 case CONDITION_ACTIVE_EVENT:
6564 return gameeventmgr.IsActiveEvent(value1);
6565 default:
6566 return false;
6570 // Verification of condition values validity
6571 bool PlayerCondition::IsValid(ConditionType condition, uint32 value1, uint32 value2)
6573 if( condition >= MAX_CONDITION) // Wrong condition type
6575 sLog.outErrorDb("Condition has bad type of %u, skipped ", condition );
6576 return false;
6579 switch (condition)
6581 case CONDITION_AURA:
6583 if(!sSpellStore.LookupEntry(value1))
6585 sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
6586 return false;
6588 if(value2 > 2)
6590 sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..2), skipped", value2);
6591 return false;
6593 break;
6595 case CONDITION_ITEM:
6597 ItemPrototype const *proto = objmgr.GetItemPrototype(value1);
6598 if(!proto)
6600 sLog.outErrorDb("Item condition requires to have non existing item (%u), skipped", value1);
6601 return false;
6603 break;
6605 case CONDITION_ITEM_EQUIPPED:
6607 ItemPrototype const *proto = objmgr.GetItemPrototype(value1);
6608 if(!proto)
6610 sLog.outErrorDb("ItemEquipped condition requires to have non existing item (%u) equipped, skipped", value1);
6611 return false;
6613 break;
6615 case CONDITION_ZONEID:
6617 AreaTableEntry const* areaEntry = GetAreaEntryByAreaID(value1);
6618 if(!areaEntry)
6620 sLog.outErrorDb("Zone condition requires to be in non existing area (%u), skipped", value1);
6621 return false;
6623 if(areaEntry->zone != 0)
6625 sLog.outErrorDb("Zone condition requires to be in area (%u) which is a subzone but zone expected, skipped", value1);
6626 return false;
6628 break;
6630 case CONDITION_REPUTATION_RANK:
6632 FactionEntry const* factionEntry = sFactionStore.LookupEntry(value1);
6633 if(!factionEntry)
6635 sLog.outErrorDb("Reputation condition requires to have reputation non existing faction (%u), skipped", value1);
6636 return false;
6638 break;
6640 case CONDITION_TEAM:
6642 if (value1 != ALLIANCE && value1 != HORDE)
6644 sLog.outErrorDb("Team condition specifies unknown team (%u), skipped", value1);
6645 return false;
6647 break;
6649 case CONDITION_SKILL:
6651 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(value1);
6652 if (!pSkill)
6654 sLog.outErrorDb("Skill condition specifies non-existing skill (%u), skipped", value1);
6655 return false;
6657 if (value2 < 1 || value2 > sWorld.GetConfigMaxSkillValue() )
6659 sLog.outErrorDb("Skill condition specifies invalid skill value (%u), skipped", value2);
6660 return false;
6662 break;
6664 case CONDITION_QUESTREWARDED:
6665 case CONDITION_QUESTTAKEN:
6667 Quest const *Quest = objmgr.GetQuestTemplate(value1);
6668 if (!Quest)
6670 sLog.outErrorDb("Quest condition specifies non-existing quest (%u), skipped", value1);
6671 return false;
6673 if(value2)
6674 sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
6675 break;
6677 case CONDITION_AD_COMMISSION_AURA:
6679 if(value1)
6680 sLog.outErrorDb("Quest condition has useless data in value1 (%u)!", value1);
6681 if(value2)
6682 sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
6683 break;
6685 case CONDITION_NO_AURA:
6687 if(!sSpellStore.LookupEntry(value1))
6689 sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
6690 return false;
6692 if(value2 > 2)
6694 sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..2), skipped", value2);
6695 return false;
6697 break;
6699 case CONDITION_ACTIVE_EVENT:
6701 GameEventMgr::GameEventDataMap const& events = gameeventmgr.GetEventMap();
6702 if(value1 >=events.size() || !events[value1].isValid())
6704 sLog.outErrorDb("Active event condition requires existed event id (%u), skipped", value1);
6705 return false;
6707 break;
6710 return true;
6713 SkillRangeType GetSkillRangeType(SkillLineEntry const *pSkill, bool racial)
6715 switch(pSkill->categoryId)
6717 case SKILL_CATEGORY_LANGUAGES: return SKILL_RANGE_LANGUAGE;
6718 case SKILL_CATEGORY_WEAPON:
6719 if(pSkill->id!=SKILL_FIST_WEAPONS)
6720 return SKILL_RANGE_LEVEL;
6721 else
6722 return SKILL_RANGE_MONO;
6723 case SKILL_CATEGORY_ARMOR:
6724 case SKILL_CATEGORY_CLASS:
6725 if(pSkill->id != SKILL_LOCKPICKING)
6726 return SKILL_RANGE_MONO;
6727 else
6728 return SKILL_RANGE_LEVEL;
6729 case SKILL_CATEGORY_SECONDARY:
6730 case SKILL_CATEGORY_PROFESSION:
6731 // not set skills for professions and racial abilities
6732 if(IsProfessionSkill(pSkill->id))
6733 return SKILL_RANGE_RANK;
6734 else if(racial)
6735 return SKILL_RANGE_NONE;
6736 else
6737 return SKILL_RANGE_MONO;
6738 default:
6739 case SKILL_CATEGORY_ATTRIBUTES: //not found in dbc
6740 case SKILL_CATEGORY_GENERIC: //only GENERIC(DND)
6741 return SKILL_RANGE_NONE;
6745 void ObjectMgr::LoadGameTele()
6747 m_GameTeleMap.clear(); // for reload case
6749 uint32 count = 0;
6750 QueryResult *result = WorldDatabase.Query("SELECT id, position_x, position_y, position_z, orientation, map, name FROM game_tele");
6752 if( !result )
6754 barGoLink bar( 1 );
6756 bar.step();
6758 sLog.outString();
6759 sLog.outErrorDb(">> Loaded `game_tele`, table is empty!");
6760 return;
6763 barGoLink bar( result->GetRowCount() );
6767 bar.step();
6769 Field *fields = result->Fetch();
6771 uint32 id = fields[0].GetUInt32();
6773 GameTele gt;
6775 gt.position_x = fields[1].GetFloat();
6776 gt.position_y = fields[2].GetFloat();
6777 gt.position_z = fields[3].GetFloat();
6778 gt.orientation = fields[4].GetFloat();
6779 gt.mapId = fields[5].GetUInt32();
6780 gt.name = fields[6].GetCppString();
6782 if(!MapManager::IsValidMapCoord(gt.mapId,gt.position_x,gt.position_y,gt.position_z,gt.orientation))
6784 sLog.outErrorDb("Wrong position for id %u (name: %s) in `game_tele` table, ignoring.",id,gt.name.c_str());
6785 continue;
6788 if(!Utf8toWStr(gt.name,gt.wnameLow))
6790 sLog.outErrorDb("Wrong UTF8 name for id %u in `game_tele` table, ignoring.",id);
6791 continue;
6794 wstrToLower( gt.wnameLow );
6796 m_GameTeleMap[id] = gt;
6798 ++count;
6800 while (result->NextRow());
6801 delete result;
6803 sLog.outString();
6804 sLog.outString( ">> Loaded %u GameTeleports", count );
6807 GameTele const* ObjectMgr::GetGameTele(const std::string& name) const
6809 // explicit name case
6810 std::wstring wname;
6811 if(!Utf8toWStr(name,wname))
6812 return false;
6814 // converting string that we try to find to lower case
6815 wstrToLower( wname );
6817 // Alternative first GameTele what contains wnameLow as substring in case no GameTele location found
6818 const GameTele* alt = NULL;
6819 for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
6820 if(itr->second.wnameLow == wname)
6821 return &itr->second;
6822 else if (alt == NULL && itr->second.wnameLow.find(wname) != std::wstring::npos)
6823 alt = &itr->second;
6825 return alt;
6828 bool ObjectMgr::AddGameTele(GameTele& tele)
6830 // find max id
6831 uint32 new_id = 0;
6832 for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
6833 if(itr->first > new_id)
6834 new_id = itr->first;
6836 // use next
6837 ++new_id;
6839 if(!Utf8toWStr(tele.name,tele.wnameLow))
6840 return false;
6842 wstrToLower( tele.wnameLow );
6844 m_GameTeleMap[new_id] = tele;
6846 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')",
6847 new_id,tele.position_x,tele.position_y,tele.position_z,tele.orientation,tele.mapId,tele.name.c_str());
6850 bool ObjectMgr::DeleteGameTele(const std::string& name)
6852 // explicit name case
6853 std::wstring wname;
6854 if(!Utf8toWStr(name,wname))
6855 return false;
6857 // converting string that we try to find to lower case
6858 wstrToLower( wname );
6860 for(GameTeleMap::iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
6862 if(itr->second.wnameLow == wname)
6864 WorldDatabase.PExecuteLog("DELETE FROM game_tele WHERE name = '%s'",itr->second.name.c_str());
6865 m_GameTeleMap.erase(itr);
6866 return true;
6870 return false;
6873 void ObjectMgr::LoadTrainerSpell()
6875 // For reload case
6876 for (CacheTrainerSpellMap::iterator itr = m_mCacheTrainerSpellMap.begin(); itr != m_mCacheTrainerSpellMap.end(); ++itr)
6877 itr->second.Clear();
6878 m_mCacheTrainerSpellMap.clear();
6880 std::set<uint32> skip_trainers;
6882 QueryResult *result = WorldDatabase.Query("SELECT entry, spell,spellcost,reqskill,reqskillvalue,reqlevel FROM npc_trainer");
6884 if( !result )
6886 barGoLink bar( 1 );
6888 bar.step();
6890 sLog.outString();
6891 sLog.outErrorDb(">> Loaded `npc_trainer`, table is empty!");
6892 return;
6895 barGoLink bar( result->GetRowCount() );
6897 uint32 count = 0;
6900 bar.step();
6902 Field* fields = result->Fetch();
6904 uint32 entry = fields[0].GetUInt32();
6905 uint32 spell = fields[1].GetUInt32();
6907 CreatureInfo const* cInfo = GetCreatureTemplate(entry);
6909 if(!cInfo)
6911 sLog.outErrorDb("Table `npc_trainer` have entry for not existed creature template (Entry: %u), ignore", entry);
6912 continue;
6915 if(!(cInfo->npcflag & UNIT_NPC_FLAG_TRAINER))
6917 if(skip_trainers.count(entry) == 0)
6919 sLog.outErrorDb("Table `npc_trainer` have data for not creature template (Entry: %u) without trainer flag, ignore", entry);
6920 skip_trainers.insert(entry);
6922 continue;
6925 SpellEntry const *spellinfo = sSpellStore.LookupEntry(spell);
6926 if(!spellinfo)
6928 sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u ) has non existing spell %u, ignore", entry,spell);
6929 continue;
6932 if(!SpellMgr::IsSpellValid(spellinfo))
6934 sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u) has broken learning spell %u, ignore", entry, spell);
6935 continue;
6938 TrainerSpellData& data = m_mCacheTrainerSpellMap[entry];
6940 TrainerSpell& trainerSpell = data.spellList[spell];
6941 trainerSpell.spell = spell;
6942 trainerSpell.spellCost = fields[2].GetUInt32();
6943 trainerSpell.reqSkill = fields[3].GetUInt32();
6944 trainerSpell.reqSkillValue = fields[4].GetUInt32();
6945 trainerSpell.reqLevel = fields[5].GetUInt32();
6947 if(!trainerSpell.reqLevel)
6948 trainerSpell.reqLevel = spellinfo->spellLevel;
6950 // calculate learned spell for profession case when stored cast-spell
6951 trainerSpell.learnedSpell = spell;
6952 for(int i = 0; i <3; ++i)
6954 if(spellinfo->Effect[i] != SPELL_EFFECT_LEARN_SPELL)
6955 continue;
6956 if(SpellMgr::IsProfessionOrRidingSpell(spellinfo->EffectTriggerSpell[i]))
6958 trainerSpell.learnedSpell = spellinfo->EffectTriggerSpell[i];
6959 break;
6963 if(SpellMgr::IsProfessionSpell(trainerSpell.learnedSpell))
6964 data.trainerType = 2;
6966 ++count;
6968 } while (result->NextRow());
6969 delete result;
6971 sLog.outString();
6972 sLog.outString( ">> Loaded %d Trainers", count );
6975 void ObjectMgr::LoadVendors()
6977 // For reload case
6978 for (CacheVendorItemMap::iterator itr = m_mCacheVendorItemMap.begin(); itr != m_mCacheVendorItemMap.end(); ++itr)
6979 itr->second.Clear();
6980 m_mCacheVendorItemMap.clear();
6982 std::set<uint32> skip_vendors;
6984 QueryResult *result = WorldDatabase.Query("SELECT entry, item, maxcount, incrtime, ExtendedCost FROM npc_vendor");
6985 if( !result )
6987 barGoLink bar( 1 );
6989 bar.step();
6991 sLog.outString();
6992 sLog.outErrorDb(">> Loaded `npc_vendor`, table is empty!");
6993 return;
6996 barGoLink bar( result->GetRowCount() );
6998 uint32 count = 0;
7001 bar.step();
7002 Field* fields = result->Fetch();
7004 uint32 entry = fields[0].GetUInt32();
7005 uint32 item_id = fields[1].GetUInt32();
7006 uint32 maxcount = fields[2].GetUInt32();
7007 uint32 incrtime = fields[3].GetUInt32();
7008 uint32 ExtendedCost = fields[4].GetUInt32();
7010 if(!IsVendorItemValid(entry,item_id,maxcount,incrtime,ExtendedCost,NULL,&skip_vendors))
7011 continue;
7013 VendorItemData& vList = m_mCacheVendorItemMap[entry];
7015 vList.AddItem(item_id,maxcount,incrtime,ExtendedCost);
7016 ++count;
7018 } while (result->NextRow());
7019 delete result;
7021 sLog.outString();
7022 sLog.outString( ">> Loaded %d Vendors ", count );
7025 void ObjectMgr::LoadNpcTextId()
7028 m_mCacheNpcTextIdMap.clear();
7030 QueryResult* result = WorldDatabase.Query("SELECT npc_guid, textid FROM npc_gossip");
7031 if( !result )
7033 barGoLink bar( 1 );
7035 bar.step();
7037 sLog.outString();
7038 sLog.outErrorDb(">> Loaded `npc_gossip`, table is empty!");
7039 return;
7042 barGoLink bar( result->GetRowCount() );
7044 uint32 count = 0;
7045 uint32 guid,textid;
7048 bar.step();
7050 Field* fields = result->Fetch();
7052 guid = fields[0].GetUInt32();
7053 textid = fields[1].GetUInt32();
7055 if (!GetCreatureData(guid))
7057 sLog.outErrorDb("Table `npc_gossip` have not existed creature (GUID: %u) entry, ignore. ",guid);
7058 continue;
7060 if (!GetGossipText(textid))
7062 sLog.outErrorDb("Table `npc_gossip` for creature (GUID: %u) have wrong Textid (%u), ignore. ", guid, textid);
7063 continue;
7066 m_mCacheNpcTextIdMap[guid] = textid ;
7067 ++count;
7069 } while (result->NextRow());
7070 delete result;
7072 sLog.outString();
7073 sLog.outString( ">> Loaded %d NpcTextId ", count );
7076 void ObjectMgr::LoadNpcOptions()
7078 m_mCacheNpcOptionList.clear(); // For reload case
7080 QueryResult *result = WorldDatabase.Query(
7081 // 0 1 2 3 4 5 6 7 8
7082 "SELECT id,gossip_id,npcflag,icon,action,box_money,coded,option_text,box_text "
7083 "FROM npc_option");
7085 if( !result )
7087 barGoLink bar( 1 );
7089 bar.step();
7091 sLog.outString();
7092 sLog.outErrorDb(">> Loaded `npc_option`, table is empty!");
7093 return;
7096 barGoLink bar( result->GetRowCount() );
7098 uint32 count = 0;
7102 bar.step();
7104 Field* fields = result->Fetch();
7106 GossipOption go;
7107 go.Id = fields[0].GetUInt32();
7108 go.GossipId = fields[1].GetUInt32();
7109 go.NpcFlag = fields[2].GetUInt32();
7110 go.Icon = fields[3].GetUInt32();
7111 go.Action = fields[4].GetUInt32();
7112 go.BoxMoney = fields[5].GetUInt32();
7113 go.Coded = fields[6].GetUInt8()!=0;
7114 go.OptionText = fields[7].GetCppString();
7115 go.BoxText = fields[8].GetCppString();
7117 m_mCacheNpcOptionList.push_back(go);
7119 ++count;
7121 } while (result->NextRow());
7122 delete result;
7124 sLog.outString();
7125 sLog.outString( ">> Loaded %d npc_option entries", count );
7128 void ObjectMgr::AddVendorItem( uint32 entry,uint32 item, uint32 maxcount, uint32 incrtime, uint32 extendedcost )
7130 VendorItemData& vList = m_mCacheVendorItemMap[entry];
7131 vList.AddItem(item,maxcount,incrtime,extendedcost);
7133 WorldDatabase.PExecuteLog("INSERT INTO npc_vendor (entry,item,maxcount,incrtime,extendedcost) VALUES('%u','%u','%u','%u','%u')",entry, item, maxcount,incrtime,extendedcost);
7136 bool ObjectMgr::RemoveVendorItem( uint32 entry,uint32 item )
7138 CacheVendorItemMap::iterator iter = m_mCacheVendorItemMap.find(entry);
7139 if(iter == m_mCacheVendorItemMap.end())
7140 return false;
7142 if(!iter->second.FindItem(item))
7143 return false;
7145 iter->second.RemoveItem(item);
7146 WorldDatabase.PExecuteLog("DELETE FROM npc_vendor WHERE entry='%u' AND item='%u'",entry, item);
7147 return true;
7150 bool ObjectMgr::IsVendorItemValid( uint32 vendor_entry, uint32 item_id, uint32 maxcount, uint32 incrtime, uint32 ExtendedCost, Player* pl, std::set<uint32>* skip_vendors ) const
7152 CreatureInfo const* cInfo = GetCreatureTemplate(vendor_entry);
7153 if(!cInfo)
7155 if(pl)
7156 ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
7157 else
7158 sLog.outErrorDb("Table `npc_vendor` have data for not existed creature template (Entry: %u), ignore", vendor_entry);
7159 return false;
7162 if(!(cInfo->npcflag & UNIT_NPC_FLAG_VENDOR))
7164 if(!skip_vendors || skip_vendors->count(vendor_entry)==0)
7166 if(pl)
7167 ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
7168 else
7169 sLog.outErrorDb("Table `npc_vendor` have data for not creature template (Entry: %u) without vendor flag, ignore", vendor_entry);
7171 if(skip_vendors)
7172 skip_vendors->insert(vendor_entry);
7174 return false;
7177 if(!GetItemPrototype(item_id))
7179 if(pl)
7180 ChatHandler(pl).PSendSysMessage(LANG_ITEM_NOT_FOUND, item_id);
7181 else
7182 sLog.outErrorDb("Table `npc_vendor` for Vendor (Entry: %u) have in item list non-existed item (%u), ignore",vendor_entry,item_id);
7183 return false;
7186 if(ExtendedCost && !sItemExtendedCostStore.LookupEntry(ExtendedCost))
7188 if(pl)
7189 ChatHandler(pl).PSendSysMessage(LANG_EXTENDED_COST_NOT_EXIST,ExtendedCost);
7190 else
7191 sLog.outErrorDb("Table `npc_vendor` have Item (Entry: %u) with wrong ExtendedCost (%u) for vendor (%u), ignore",item_id,ExtendedCost,vendor_entry);
7192 return false;
7195 if(maxcount > 0 && incrtime == 0)
7197 if(pl)
7198 ChatHandler(pl).PSendSysMessage("MaxCount!=0 (%u) but IncrTime==0", maxcount);
7199 else
7200 sLog.outErrorDb( "Table `npc_vendor` has `maxcount` (%u) for item %u of vendor (Entry: %u) but `incrtime`=0, ignore", maxcount, item_id, vendor_entry);
7201 return false;
7203 else if(maxcount==0 && incrtime > 0)
7205 if(pl)
7206 ChatHandler(pl).PSendSysMessage("MaxCount==0 but IncrTime<>=0");
7207 else
7208 sLog.outErrorDb( "Table `npc_vendor` has `maxcount`=0 for item %u of vendor (Entry: %u) but `incrtime`<>0, ignore", item_id, vendor_entry);
7209 return false;
7212 VendorItemData const* vItems = GetNpcVendorItemList(vendor_entry);
7213 if(!vItems)
7214 return true; // later checks for non-empty lists
7216 if(vItems->FindItem(item_id))
7218 if(pl)
7219 ChatHandler(pl).PSendSysMessage(LANG_ITEM_ALREADY_IN_LIST,item_id);
7220 else
7221 sLog.outErrorDb( "Table `npc_vendor` has duplicate items %u for vendor (Entry: %u), ignore", item_id, vendor_entry);
7222 return false;
7225 if(vItems->GetItemCount() >= MAX_VENDOR_ITEMS)
7227 if(pl)
7228 ChatHandler(pl).SendSysMessage(LANG_COMMAND_ADDVENDORITEMITEMS);
7229 else
7230 sLog.outErrorDb( "Table `npc_vendor` has too many items (%u >= %i) for vendor (Entry: %u), ignore", vItems->GetItemCount(), MAX_VENDOR_ITEMS, vendor_entry);
7231 return false;
7234 return true;
7237 void ObjectMgr::LoadScriptNames()
7239 m_scriptNames.push_back("");
7240 QueryResult *result = WorldDatabase.Query(
7241 "SELECT DISTINCT(ScriptName) FROM creature_template WHERE ScriptName <> '' "
7242 "UNION "
7243 "SELECT DISTINCT(ScriptName) FROM gameobject_template WHERE ScriptName <> '' "
7244 "UNION "
7245 "SELECT DISTINCT(ScriptName) FROM item_template WHERE ScriptName <> '' "
7246 "UNION "
7247 "SELECT DISTINCT(ScriptName) FROM areatrigger_scripts WHERE ScriptName <> '' "
7248 "UNION "
7249 "SELECT DISTINCT(script) FROM instance_template WHERE script <> ''");
7251 if( !result )
7253 barGoLink bar( 1 );
7254 bar.step();
7255 sLog.outString();
7256 sLog.outErrorDb(">> Loaded empty set of Script Names!");
7257 return;
7260 barGoLink bar( result->GetRowCount() );
7261 uint32 count = 0;
7265 bar.step();
7266 m_scriptNames.push_back((*result)[0].GetString());
7267 ++count;
7268 } while (result->NextRow());
7269 delete result;
7271 std::sort(m_scriptNames.begin(), m_scriptNames.end());
7272 sLog.outString();
7273 sLog.outString( ">> Loaded %d Script Names", count );
7276 uint32 ObjectMgr::GetScriptId(const char *name)
7278 // use binary search to find the script name in the sorted vector
7279 // assume "" is the first element
7280 if(!name) return 0;
7281 ScriptNameMap::const_iterator itr =
7282 std::lower_bound(m_scriptNames.begin(), m_scriptNames.end(), name);
7283 if(itr == m_scriptNames.end() || *itr != name) return 0;
7284 return itr - m_scriptNames.begin();
7287 void ObjectMgr::CheckScripts(ScriptMapMap const& scripts,std::set<int32>& ids)
7289 for(ScriptMapMap::const_iterator itrMM = scripts.begin(); itrMM != scripts.end(); ++itrMM)
7291 for(ScriptMap::const_iterator itrM = itrMM->second.begin(); itrM != itrMM->second.end(); ++itrM)
7293 if(itrM->second.dataint)
7295 if(!GetMangosStringLocale (itrM->second.dataint))
7296 sLog.outErrorDb( "Table `db_script_string` has not existed string id %u", itrM->first);
7298 if(ids.count(itrM->second.dataint))
7299 ids.erase(itrM->second.dataint);
7305 void ObjectMgr::LoadDbScriptStrings()
7307 LoadMangosStrings(WorldDatabase,"db_script_string",MIN_DB_SCRIPT_STRING_ID,MAX_DB_SCRIPT_STRING_ID);
7309 std::set<int32> ids;
7311 for(int32 i = MIN_DB_SCRIPT_STRING_ID; i < MAX_DB_SCRIPT_STRING_ID; ++i)
7312 if(GetMangosStringLocale(i))
7313 ids.insert(i);
7315 CheckScripts(sQuestEndScripts,ids);
7316 CheckScripts(sQuestStartScripts,ids);
7317 CheckScripts(sSpellScripts,ids);
7318 CheckScripts(sGameObjectScripts,ids);
7319 CheckScripts(sEventScripts,ids);
7321 WaypointMgr.CheckTextsExistance(ids);
7323 for(std::set<int32>::const_iterator itr = ids.begin(); itr != ids.end(); ++itr)
7324 sLog.outErrorDb( "Table `db_script_string` has unused string id %u", *itr);
7327 // Functions for scripting access
7328 uint32 GetAreaTriggerScriptId(uint32 trigger_id)
7330 return objmgr.GetAreaTriggerScriptId(trigger_id);
7333 bool LoadMangosStrings(DatabaseType& db, char const* table,int32 start_value, int32 end_value)
7335 if(start_value >= 0 || start_value <= end_value) // start/end reversed for negative values
7337 sLog.outErrorDb("Table '%s' attempt loaded with invalid range (%d - %d), use (%d - %d) instead.",table,start_value,end_value,-1,std::numeric_limits<int32>::min());
7338 start_value = -1;
7339 end_value = std::numeric_limits<int32>::min();
7342 // for scripting localized strings allowed use _only_ negative entries
7343 return objmgr.LoadMangosStrings(db,table,end_value,start_value);
7346 uint32 MANGOS_DLL_SPEC GetScriptId(const char *name)
7348 return objmgr.GetScriptId(name);
7351 ObjectMgr::ScriptNameMap & GetScriptNames()
7353 return objmgr.GetScriptNames();
7356 CreatureInfo const* GetCreatureTemplateStore(uint32 entry)
7358 return sCreatureStorage.LookupEntry<CreatureInfo>(entry);
7361 Quest const* GetQuestTemplateStore(uint32 entry)
7363 return objmgr.GetQuestTemplate(entry);