[7915] Implement more stricted checks and limitations at loading creature addon data.
[getmangos.git] / src / game / ObjectMgr.cpp
blob199daef5bb82a1714b3abc1dd234268e342c8dd8
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 // Only zero condition left, others will be added while loading DB tables
127 mConditions.resize(1);
130 ObjectMgr::~ObjectMgr()
132 for( QuestMap::iterator i = mQuestTemplates.begin( ); i != mQuestTemplates.end( ); ++i )
133 delete i->second;
135 for(PetLevelInfoMap::iterator i = petInfo.begin( ); i != petInfo.end( ); ++i )
136 delete[] i->second;
138 // free only if loaded
139 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
140 delete[] playerClassInfo[class_].levelInfo;
142 for (int race = 0; race < MAX_RACES; ++race)
143 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
144 delete[] playerInfo[race][class_].levelInfo;
146 // free group and guild objects
147 for (GroupSet::iterator itr = mGroupSet.begin(); itr != mGroupSet.end(); ++itr)
148 delete (*itr);
150 for (GuildMap::iterator itr = mGuildMap.begin(); itr != mGuildMap.end(); ++itr)
151 delete itr->second;
153 for (CacheVendorItemMap::iterator itr = m_mCacheVendorItemMap.begin(); itr != m_mCacheVendorItemMap.end(); ++itr)
154 itr->second.Clear();
156 for (CacheTrainerSpellMap::iterator itr = m_mCacheTrainerSpellMap.begin(); itr != m_mCacheTrainerSpellMap.end(); ++itr)
157 itr->second.Clear();
160 Group * ObjectMgr::GetGroupByLeader(const uint64 &guid) const
162 for(GroupSet::const_iterator itr = mGroupSet.begin(); itr != mGroupSet.end(); ++itr)
163 if ((*itr)->GetLeaderGUID() == guid)
164 return *itr;
166 return NULL;
169 Guild * ObjectMgr::GetGuildById(uint32 GuildId) const
171 GuildMap::const_iterator itr = mGuildMap.find(GuildId);
172 if (itr != mGuildMap.end())
173 return itr->second;
175 return NULL;
178 Guild * ObjectMgr::GetGuildByName(const std::string& guildname) const
180 for(GuildMap::const_iterator itr = mGuildMap.begin(); itr != mGuildMap.end(); ++itr)
181 if (itr->second->GetName() == guildname)
182 return itr->second;
184 return NULL;
187 std::string ObjectMgr::GetGuildNameById(uint32 GuildId) const
189 GuildMap::const_iterator itr = mGuildMap.find(GuildId);
190 if (itr != mGuildMap.end())
191 return itr->second->GetName();
193 return "";
196 Guild* ObjectMgr::GetGuildByLeader(const uint64 &guid) const
198 for(GuildMap::const_iterator itr = mGuildMap.begin(); itr != mGuildMap.end(); ++itr)
199 if (itr->second->GetLeader() == guid)
200 return itr->second;
202 return NULL;
205 void ObjectMgr::AddGuild(Guild* guild)
207 mGuildMap[guild->GetId()] = guild;
210 void ObjectMgr::RemoveGuild(uint32 Id)
212 mGuildMap.erase(Id);
215 ArenaTeam* ObjectMgr::GetArenaTeamById(uint32 arenateamid) const
217 ArenaTeamMap::const_iterator itr = mArenaTeamMap.find(arenateamid);
218 if (itr != mArenaTeamMap.end())
219 return itr->second;
221 return NULL;
224 ArenaTeam* ObjectMgr::GetArenaTeamByName(const std::string& arenateamname) const
226 for(ArenaTeamMap::const_iterator itr = mArenaTeamMap.begin(); itr != mArenaTeamMap.end(); ++itr)
227 if (itr->second->GetName() == arenateamname)
228 return itr->second;
230 return NULL;
233 ArenaTeam* ObjectMgr::GetArenaTeamByCaptain(uint64 const& guid) const
235 for(ArenaTeamMap::const_iterator itr = mArenaTeamMap.begin(); itr != mArenaTeamMap.end(); ++itr)
236 if (itr->second->GetCaptain() == guid)
237 return itr->second;
239 return NULL;
242 void ObjectMgr::AddArenaTeam(ArenaTeam* arenaTeam)
244 mArenaTeamMap[arenaTeam->GetId()] = arenaTeam;
247 void ObjectMgr::RemoveArenaTeam(uint32 Id)
249 mArenaTeamMap.erase(Id);
252 CreatureInfo const* ObjectMgr::GetCreatureTemplate(uint32 id)
254 return sCreatureStorage.LookupEntry<CreatureInfo>(id);
257 void ObjectMgr::LoadCreatureLocales()
259 mCreatureLocaleMap.clear(); // need for reload case
261 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");
263 if(!result)
265 barGoLink bar(1);
267 bar.step();
269 sLog.outString();
270 sLog.outString(">> Loaded 0 creature locale strings. DB table `locales_creature` is empty.");
271 return;
274 barGoLink bar(result->GetRowCount());
278 Field *fields = result->Fetch();
279 bar.step();
281 uint32 entry = fields[0].GetUInt32();
283 CreatureLocale& data = mCreatureLocaleMap[entry];
285 for(int i = 1; i < MAX_LOCALE; ++i)
287 std::string str = fields[1+2*(i-1)].GetCppString();
288 if(!str.empty())
290 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
291 if(idx >= 0)
293 if(data.Name.size() <= idx)
294 data.Name.resize(idx+1);
296 data.Name[idx] = str;
299 str = fields[1+2*(i-1)+1].GetCppString();
300 if(!str.empty())
302 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
303 if(idx >= 0)
305 if(data.SubName.size() <= idx)
306 data.SubName.resize(idx+1);
308 data.SubName[idx] = str;
312 } while (result->NextRow());
314 delete result;
316 sLog.outString();
317 sLog.outString( ">> Loaded %lu creature locale strings", (unsigned long)mCreatureLocaleMap.size() );
320 void ObjectMgr::LoadNpcOptionLocales()
322 mNpcOptionLocaleMap.clear(); // need for reload case
324 QueryResult *result = WorldDatabase.Query("SELECT entry,"
325 "option_text_loc1,box_text_loc1,option_text_loc2,box_text_loc2,"
326 "option_text_loc3,box_text_loc3,option_text_loc4,box_text_loc4,"
327 "option_text_loc5,box_text_loc5,option_text_loc6,box_text_loc6,"
328 "option_text_loc7,box_text_loc7,option_text_loc8,box_text_loc8 "
329 "FROM locales_npc_option");
331 if(!result)
333 barGoLink bar(1);
335 bar.step();
337 sLog.outString();
338 sLog.outString(">> Loaded 0 npc_option locale strings. DB table `locales_npc_option` is empty.");
339 return;
342 barGoLink bar(result->GetRowCount());
346 Field *fields = result->Fetch();
347 bar.step();
349 uint32 entry = fields[0].GetUInt32();
351 NpcOptionLocale& data = mNpcOptionLocaleMap[entry];
353 for(int i = 1; i < MAX_LOCALE; ++i)
355 std::string str = fields[1+2*(i-1)].GetCppString();
356 if(!str.empty())
358 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
359 if(idx >= 0)
361 if(data.OptionText.size() <= idx)
362 data.OptionText.resize(idx+1);
364 data.OptionText[idx] = str;
367 str = fields[1+2*(i-1)+1].GetCppString();
368 if(!str.empty())
370 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
371 if(idx >= 0)
373 if(data.BoxText.size() <= idx)
374 data.BoxText.resize(idx+1);
376 data.BoxText[idx] = str;
380 } while (result->NextRow());
382 delete result;
384 sLog.outString();
385 sLog.outString( ">> Loaded %lu npc_option locale strings", (unsigned long)mNpcOptionLocaleMap.size() );
388 void ObjectMgr::LoadPointOfInterestLocales()
390 mPointOfInterestLocaleMap.clear(); // need for reload case
392 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");
394 if(!result)
396 barGoLink bar(1);
398 bar.step();
400 sLog.outString();
401 sLog.outString(">> Loaded 0 points_of_interest locale strings. DB table `locales_points_of_interest` is empty.");
402 return;
405 barGoLink bar(result->GetRowCount());
409 Field *fields = result->Fetch();
410 bar.step();
412 uint32 entry = fields[0].GetUInt32();
414 PointOfInterestLocale& data = mPointOfInterestLocaleMap[entry];
416 for(int i = 1; i < MAX_LOCALE; ++i)
418 std::string str = fields[i].GetCppString();
419 if(str.empty())
420 continue;
422 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
423 if(idx >= 0)
425 if(data.IconName.size() <= idx)
426 data.IconName.resize(idx+1);
428 data.IconName[idx] = str;
431 } while (result->NextRow());
433 delete result;
435 sLog.outString();
436 sLog.outString( ">> Loaded %lu points_of_interest locale strings", (unsigned long)mPointOfInterestLocaleMap.size() );
439 struct SQLCreatureLoader : public SQLStorageLoaderBase<SQLCreatureLoader>
441 template<class D>
442 void convert_from_str(uint32 /*field_pos*/, char *src, D &dst)
444 dst = D(objmgr.GetScriptId(src));
448 void ObjectMgr::LoadCreatureTemplates()
450 SQLCreatureLoader loader;
451 loader.Load(sCreatureStorage);
453 sLog.outString( ">> Loaded %u creature definitions", sCreatureStorage.RecordCount );
454 sLog.outString();
456 std::set<uint32> heroicEntries; // already loaded heroic value in creatures
457 std::set<uint32> hasHeroicEntries; // already loaded creatures with heroic entry values
459 // check data correctness
460 for(uint32 i = 1; i < sCreatureStorage.MaxEntry; ++i)
462 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i);
463 if(!cInfo)
464 continue;
466 if(cInfo->HeroicEntry)
468 CreatureInfo const* heroicInfo = GetCreatureTemplate(cInfo->HeroicEntry);
469 if(!heroicInfo)
471 sLog.outErrorDb("Creature (Entry: %u) have `heroic_entry`=%u but creature entry %u not exist.",cInfo->HeroicEntry,cInfo->HeroicEntry);
472 continue;
475 if(heroicEntries.find(i)!=heroicEntries.end())
477 sLog.outErrorDb("Creature (Entry: %u) listed as heroic but have value in `heroic_entry`.",i);
478 continue;
481 if(heroicEntries.find(cInfo->HeroicEntry)!=heroicEntries.end())
483 sLog.outErrorDb("Creature (Entry: %u) already listed as heroic for another entry.",cInfo->HeroicEntry);
484 continue;
487 if(hasHeroicEntries.find(cInfo->HeroicEntry)!=hasHeroicEntries.end())
489 sLog.outErrorDb("Creature (Entry: %u) have `heroic_entry`=%u but creature entry %u have heroic entry also.",i,cInfo->HeroicEntry,cInfo->HeroicEntry);
490 continue;
493 if(cInfo->unit_class != heroicInfo->unit_class)
495 sLog.outErrorDb("Creature (Entry: %u, class %u) has different `unit_class` in heroic mode (Entry: %u, class %u).",i, cInfo->unit_class, cInfo->HeroicEntry, heroicInfo->unit_class);
496 continue;
499 if(cInfo->npcflag != heroicInfo->npcflag)
501 sLog.outErrorDb("Creature (Entry: %u) has different `npcflag` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
502 continue;
505 if(cInfo->trainer_class != heroicInfo->trainer_class)
507 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_class` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
508 continue;
511 if(cInfo->trainer_race != heroicInfo->trainer_race)
513 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_race` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
514 continue;
517 if(cInfo->trainer_type != heroicInfo->trainer_type)
519 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_type` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
520 continue;
523 if(cInfo->trainer_spell != heroicInfo->trainer_spell)
525 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_spell` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
526 continue;
529 if(heroicInfo->AIName && *heroicInfo->AIName)
531 sLog.outErrorDb("Heroic mode creature (Entry: %u) has `AIName`, but in any case will used normal mode creature (Entry: %u) AIName.",cInfo->HeroicEntry,i);
532 continue;
535 if(heroicInfo->ScriptID)
537 sLog.outErrorDb("Heroic mode creature (Entry: %u) has `ScriptName`, but in any case will used normal mode creature (Entry: %u) ScriptName.",cInfo->HeroicEntry,i);
538 continue;
541 hasHeroicEntries.insert(i);
542 heroicEntries.insert(cInfo->HeroicEntry);
545 FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction_A);
546 if(!factionTemplate)
547 sLog.outErrorDb("Creature (Entry: %u) has non-existing faction_A template (%u)", cInfo->Entry, cInfo->faction_A);
549 factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction_H);
550 if(!factionTemplate)
551 sLog.outErrorDb("Creature (Entry: %u) has non-existing faction_H template (%u)", cInfo->Entry, cInfo->faction_H);
553 CreatureModelInfo const* minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_A);
554 if (!minfo)
555 sLog.outErrorDb("Creature (Entry: %u) has non-existing modelId_A (%u)", cInfo->Entry, cInfo->DisplayID_A);
556 minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_H);
557 if (!minfo)
558 sLog.outErrorDb("Creature (Entry: %u) has non-existing modelId_H (%u)", cInfo->Entry, cInfo->DisplayID_H);
560 if (cInfo->unit_class && ((1 << (cInfo->unit_class-1)) & CLASSMASK_ALL_CREATURES) == 0)
561 sLog.outErrorDb("Creature (Entry: %u) has invalid unit_class(%u) for creature_template", cInfo->Entry, cInfo->unit_class);
563 if(cInfo->dmgschool >= MAX_SPELL_SCHOOL)
565 sLog.outErrorDb("Creature (Entry: %u) has invalid spell school value (%u) in `dmgschool`",cInfo->Entry,cInfo->dmgschool);
566 const_cast<CreatureInfo*>(cInfo)->dmgschool = SPELL_SCHOOL_NORMAL;
569 if(cInfo->baseattacktime == 0)
570 const_cast<CreatureInfo*>(cInfo)->baseattacktime = BASE_ATTACK_TIME;
572 if(cInfo->rangeattacktime == 0)
573 const_cast<CreatureInfo*>(cInfo)->rangeattacktime = BASE_ATTACK_TIME;
575 if((cInfo->npcflag & UNIT_NPC_FLAG_TRAINER) && cInfo->trainer_type >= MAX_TRAINER_TYPE)
576 sLog.outErrorDb("Creature (Entry: %u) has wrong trainer type %u",cInfo->Entry,cInfo->trainer_type);
578 if(cInfo->type && !sCreatureTypeStore.LookupEntry(cInfo->type))
580 sLog.outErrorDb("Creature (Entry: %u) has invalid creature type (%u) in `type`",cInfo->Entry,cInfo->type);
581 const_cast<CreatureInfo*>(cInfo)->type = CREATURE_TYPE_HUMANOID;
584 // must exist or used hidden but used in data horse case
585 if(cInfo->family && !sCreatureFamilyStore.LookupEntry(cInfo->family) && cInfo->family != CREATURE_FAMILY_HORSE_CUSTOM )
587 sLog.outErrorDb("Creature (Entry: %u) has invalid creature family (%u) in `family`",cInfo->Entry,cInfo->family);
588 const_cast<CreatureInfo*>(cInfo)->family = 0;
591 if(cInfo->InhabitType <= 0 || cInfo->InhabitType > INHABIT_ANYWHERE)
593 sLog.outErrorDb("Creature (Entry: %u) has wrong value (%u) in `InhabitType`, creature will not correctly walk/swim/fly",cInfo->Entry,cInfo->InhabitType);
594 const_cast<CreatureInfo*>(cInfo)->InhabitType = INHABIT_ANYWHERE;
597 if(cInfo->PetSpellDataId)
599 CreatureSpellDataEntry const* spellDataId = sCreatureSpellDataStore.LookupEntry(cInfo->PetSpellDataId);
600 if(!spellDataId)
601 sLog.outErrorDb("Creature (Entry: %u) has non-existing PetSpellDataId (%u)", cInfo->Entry, cInfo->PetSpellDataId);
604 for(int j = 0; j < CREATURE_MAX_SPELLS; ++j)
606 if(cInfo->spells[j] && !sSpellStore.LookupEntry(cInfo->spells[j]))
608 sLog.outErrorDb("Creature (Entry: %u) has non-existing Spell%d (%u), set to 0", cInfo->Entry, j+1,cInfo->spells[j]);
609 const_cast<CreatureInfo*>(cInfo)->spells[j] = 0;
613 if(cInfo->MovementType >= MAX_DB_MOTION_TYPE)
615 sLog.outErrorDb("Creature (Entry: %u) has wrong movement generator type (%u), ignore and set to IDLE.",cInfo->Entry,cInfo->MovementType);
616 const_cast<CreatureInfo*>(cInfo)->MovementType = IDLE_MOTION_TYPE;
619 if(cInfo->equipmentId > 0) // 0 no equipment
621 if(!GetEquipmentInfo(cInfo->equipmentId))
623 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);
624 const_cast<CreatureInfo*>(cInfo)->equipmentId = 0;
628 /// if not set custom creature scale then load scale from CreatureDisplayInfo.dbc
629 if(cInfo->scale <= 0.0f)
631 CreatureDisplayInfoEntry const* ScaleEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->DisplayID_A);
632 const_cast<CreatureInfo*>(cInfo)->scale = ScaleEntry ? ScaleEntry->scale : 1.0f;
637 void ObjectMgr::ConvertCreatureAddonAuras(CreatureDataAddon* addon, char const* table, char const* guidEntryStr)
639 // Now add the auras, format "spellid effectindex spellid effectindex..."
640 char *p,*s;
641 std::vector<int> val;
642 s=p=(char*)reinterpret_cast<char const*>(addon->auras);
643 if(p)
645 while (p[0]!=0)
647 ++p;
648 if (p[0]==' ')
650 val.push_back(atoi(s));
651 s=++p;
654 if (p!=s)
655 val.push_back(atoi(s));
657 // free char* loaded memory
658 delete[] (char*)reinterpret_cast<char const*>(addon->auras);
660 // wrong list
661 if (val.size()%2)
663 addon->auras = NULL;
664 sLog.outErrorDb("Creature (%s: %u) has wrong `auras` data in `%s`.",guidEntryStr,addon->guidOrEntry,table);
665 return;
669 // empty list
670 if(val.empty())
672 addon->auras = NULL;
673 return;
676 // replace by new structures array
677 const_cast<CreatureDataAddonAura*&>(addon->auras) = new CreatureDataAddonAura[val.size()/2+1];
679 int i=0;
680 for(int j=0;j<val.size()/2;++j)
682 CreatureDataAddonAura& cAura = const_cast<CreatureDataAddonAura&>(addon->auras[i]);
683 cAura.spell_id = (uint32)val[2*j+0];
684 cAura.effect_idx = (uint32)val[2*j+1];
685 if ( cAura.effect_idx > 2 )
687 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);
688 continue;
690 SpellEntry const *AdditionalSpellInfo = sSpellStore.LookupEntry(cAura.spell_id);
691 if (!AdditionalSpellInfo)
693 sLog.outErrorDb("Creature (%s: %u) has wrong spell %u defined in `auras` field in `%s`.",guidEntryStr,addon->guidOrEntry,cAura.spell_id,table);
694 continue;
697 if (!AdditionalSpellInfo->Effect[cAura.effect_idx] || !AdditionalSpellInfo->EffectApplyAuraName[cAura.effect_idx])
699 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);
700 continue;
703 ++i;
706 // fill terminator element (after last added)
707 CreatureDataAddonAura& endAura = const_cast<CreatureDataAddonAura&>(addon->auras[i]);
708 endAura.spell_id = 0;
709 endAura.effect_idx = 0;
712 void ObjectMgr::LoadCreatureAddons()
714 sCreatureInfoAddonStorage.Load();
716 sLog.outString( ">> Loaded %u creature template addons", sCreatureInfoAddonStorage.RecordCount );
717 sLog.outString();
719 // check data correctness and convert 'auras'
720 for(uint32 i = 1; i < sCreatureInfoAddonStorage.MaxEntry; ++i)
722 CreatureDataAddon const* addon = sCreatureInfoAddonStorage.LookupEntry<CreatureDataAddon>(i);
723 if(!addon)
724 continue;
726 if (addon->mount)
728 if (!sCreatureDisplayInfoStore.LookupEntry(addon->mount))
729 sLog.outErrorDb("Creature (Entry %u) have invalid displayInfoId for mount (%u) defined in `creature_template_addon`.",addon->guidOrEntry, addon->mount);
732 if (!sEmotesStore.LookupEntry(addon->emote))
733 sLog.outErrorDb("Creature (Entry %u) have invalid emote (%u) defined in `creature_template_addon`.",addon->guidOrEntry, addon->emote);
735 ConvertCreatureAddonAuras(const_cast<CreatureDataAddon*>(addon), "creature_template_addon", "Entry");
737 if(!sCreatureStorage.LookupEntry<CreatureInfo>(addon->guidOrEntry))
738 sLog.outErrorDb("Creature (Entry: %u) does not exist but has a record in `creature_template_addon`",addon->guidOrEntry);
741 sCreatureDataAddonStorage.Load();
743 sLog.outString( ">> Loaded %u creature addons", sCreatureDataAddonStorage.RecordCount );
744 sLog.outString();
746 // check data correctness and convert 'auras'
747 for(uint32 i = 1; i < sCreatureDataAddonStorage.MaxEntry; ++i)
749 CreatureDataAddon const* addon = sCreatureDataAddonStorage.LookupEntry<CreatureDataAddon>(i);
750 if(!addon)
751 continue;
753 if (addon->mount)
755 if (!sCreatureDisplayInfoStore.LookupEntry(addon->mount))
756 sLog.outErrorDb("Creature (GUID %u) have invalid displayInfoId for mount (%u) defined in `creature_addon`.",addon->guidOrEntry, addon->mount);
759 if (!sEmotesStore.LookupEntry(addon->emote))
760 sLog.outErrorDb("Creature (GUID %u) have invalid emote (%u) defined in `creature_addon`.",addon->guidOrEntry, addon->emote);
762 ConvertCreatureAddonAuras(const_cast<CreatureDataAddon*>(addon), "creature_addon", "GUIDLow");
764 if(mCreatureDataMap.find(addon->guidOrEntry)==mCreatureDataMap.end())
765 sLog.outErrorDb("Creature (GUID: %u) does not exist but has a record in `creature_addon`",addon->guidOrEntry);
769 EquipmentInfo const* ObjectMgr::GetEquipmentInfo(uint32 entry)
771 return sEquipmentStorage.LookupEntry<EquipmentInfo>(entry);
774 void ObjectMgr::LoadEquipmentTemplates()
776 sEquipmentStorage.Load();
778 for(uint32 i=0; i< sEquipmentStorage.MaxEntry; ++i)
780 EquipmentInfo const* eqInfo = sEquipmentStorage.LookupEntry<EquipmentInfo>(i);
782 if(!eqInfo)
783 continue;
785 for(uint8 j=0; j<3; j++)
787 if(!eqInfo->equipentry[j])
788 continue;
790 ItemEntry const *dbcitem = sItemStore.LookupEntry(eqInfo->equipentry[j]);
792 if(!dbcitem)
794 sLog.outErrorDb("Unknown item (entry=%u) in creature_equip_template.equipentry%u for entry = %u, forced to 0.", eqInfo->equipentry[j], j+1, i);
795 const_cast<EquipmentInfo*>(eqInfo)->equipentry[j] = 0;
796 continue;
799 if(dbcitem->InventoryType != INVTYPE_WEAPON &&
800 dbcitem->InventoryType != INVTYPE_SHIELD &&
801 dbcitem->InventoryType != INVTYPE_RANGED &&
802 dbcitem->InventoryType != INVTYPE_2HWEAPON &&
803 dbcitem->InventoryType != INVTYPE_WEAPONMAINHAND &&
804 dbcitem->InventoryType != INVTYPE_WEAPONOFFHAND &&
805 dbcitem->InventoryType != INVTYPE_HOLDABLE &&
806 dbcitem->InventoryType != INVTYPE_THROWN &&
807 dbcitem->InventoryType != INVTYPE_RANGEDRIGHT)
809 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);
810 const_cast<EquipmentInfo*>(eqInfo)->equipentry[j] = 0;
814 sLog.outString( ">> Loaded %u equipment template", sEquipmentStorage.RecordCount );
815 sLog.outString();
817 // Creature items can be not listed in item_template
818 //sItemStore.Clear(); -- so used in spell casting
821 CreatureModelInfo const* ObjectMgr::GetCreatureModelInfo(uint32 modelid)
823 return sCreatureModelStorage.LookupEntry<CreatureModelInfo>(modelid);
826 uint32 ObjectMgr::ChooseDisplayId(uint32 team, const CreatureInfo *cinfo, const CreatureData *data)
828 // Load creature model (display id)
829 uint32 display_id;
830 if (!data || data->displayid == 0) // use defaults from the template
832 // DisplayID_A is used if no team is given
833 if (team == HORDE)
834 display_id = (cinfo->DisplayID_H2 != 0 && urand(0,1) == 0) ? cinfo->DisplayID_H2 : cinfo->DisplayID_H;
835 else
836 display_id = (cinfo->DisplayID_A2 != 0 && urand(0,1) == 0) ? cinfo->DisplayID_A2 : cinfo->DisplayID_A;
838 else // overridden in creature data
839 display_id = data->displayid;
841 return display_id;
844 CreatureModelInfo const* ObjectMgr::GetCreatureModelRandomGender(uint32 display_id)
846 CreatureModelInfo const *minfo = GetCreatureModelInfo(display_id);
847 if(!minfo)
848 return NULL;
850 // If a model for another gender exists, 50% chance to use it
851 if(minfo->modelid_other_gender != 0 && urand(0,1) == 0)
853 CreatureModelInfo const *minfo_tmp = GetCreatureModelInfo(minfo->modelid_other_gender);
854 if(!minfo_tmp)
856 sLog.outErrorDb("Model (Entry: %u) has modelid_other_gender %u not found in table `creature_model_info`. ", minfo->modelid, minfo->modelid_other_gender);
857 return minfo; // not fatal, just use the previous one
859 else
860 return minfo_tmp;
862 else
863 return minfo;
866 void ObjectMgr::LoadCreatureModelInfo()
868 sCreatureModelStorage.Load();
870 sLog.outString( ">> Loaded %u creature model based info", sCreatureModelStorage.RecordCount );
871 sLog.outString();
874 void ObjectMgr::LoadCreatures()
876 uint32 count = 0;
877 // 0 1 2 3
878 QueryResult *result = WorldDatabase.Query("SELECT creature.guid, id, map, modelid,"
879 // 4 5 6 7 8 9 10 11
880 "equipment_id, position_x, position_y, position_z, orientation, spawntimesecs, spawndist, currentwaypoint,"
881 // 12 13 14 15 16 17 18 19
882 "curhealth, curmana, DeathState, MovementType, spawnMask, phaseMask, event, pool_entry "
883 "FROM creature LEFT OUTER JOIN game_event_creature ON creature.guid = game_event_creature.guid "
884 "LEFT OUTER JOIN pool_creature ON creature.guid = pool_creature.guid");
886 if(!result)
888 barGoLink bar(1);
890 bar.step();
892 sLog.outString();
893 sLog.outErrorDb(">> Loaded 0 creature. DB table `creature` is empty.");
894 return;
897 // build single time for check creature data
898 std::set<uint32> heroicCreatures;
899 for(uint32 i = 0; i < sCreatureStorage.MaxEntry; ++i)
900 if(CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i))
901 if(cInfo->HeroicEntry)
902 heroicCreatures.insert(cInfo->HeroicEntry);
904 barGoLink bar(result->GetRowCount());
908 Field *fields = result->Fetch();
909 bar.step();
911 uint32 guid = fields[ 0].GetUInt32();
912 uint32 entry = fields[ 1].GetUInt32();
914 CreatureInfo const* cInfo = GetCreatureTemplate(entry);
915 if(!cInfo)
917 sLog.outErrorDb("Table `creature` has creature (GUID: %u) with non existing creature entry %u, skipped.", guid, entry);
918 continue;
921 CreatureData& data = mCreatureDataMap[guid];
923 data.id = entry;
924 data.mapid = fields[ 2].GetUInt32();
925 data.displayid = fields[ 3].GetUInt32();
926 data.equipmentId = fields[ 4].GetUInt32();
927 data.posX = fields[ 5].GetFloat();
928 data.posY = fields[ 6].GetFloat();
929 data.posZ = fields[ 7].GetFloat();
930 data.orientation = fields[ 8].GetFloat();
931 data.spawntimesecs = fields[ 9].GetUInt32();
932 data.spawndist = fields[10].GetFloat();
933 data.currentwaypoint= fields[11].GetUInt32();
934 data.curhealth = fields[12].GetUInt32();
935 data.curmana = fields[13].GetUInt32();
936 data.is_dead = fields[14].GetBool();
937 data.movementType = fields[15].GetUInt8();
938 data.spawnMask = fields[16].GetUInt8();
939 data.phaseMask = fields[17].GetUInt16();
940 int16 gameEvent = fields[18].GetInt16();
941 int16 PoolId = fields[19].GetInt16();
943 if(heroicCreatures.find(data.id)!=heroicCreatures.end())
945 sLog.outErrorDb("Table `creature` have creature (GUID: %u) that listed as heroic template in `creature_template`, skipped.",guid,data.id );
946 continue;
949 if(data.equipmentId > 0) // -1 no equipment, 0 use default
951 if(!GetEquipmentInfo(data.equipmentId))
953 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);
954 data.equipmentId = -1;
958 if(cInfo->RegenHealth && data.curhealth < cInfo->minhealth)
960 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 );
961 data.curhealth = cInfo->minhealth;
964 if(cInfo->flags_extra & CREATURE_FLAG_EXTRA_INSTANCE_BIND)
966 MapEntry const* map = sMapStore.LookupEntry(data.mapid);
967 if(!map || !map->IsDungeon())
968 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);
971 if(data.curmana < cInfo->minmana)
973 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 );
974 data.curmana = cInfo->minmana;
977 if(data.spawndist < 0.0f)
979 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `spawndist`< 0, set to 0.",guid,data.id );
980 data.spawndist = 0.0f;
982 else if(data.movementType == RANDOM_MOTION_TYPE)
984 if(data.spawndist == 0.0f)
986 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 );
987 data.movementType = IDLE_MOTION_TYPE;
990 else if(data.movementType == IDLE_MOTION_TYPE)
992 if(data.spawndist != 0.0f)
994 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `MovementType`=0 (idle) have `spawndist`<>0, set to 0.",guid,data.id );
995 data.spawndist = 0.0f;
999 if(data.phaseMask==0)
1001 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `phaseMask`=0 (not visible for anyone), set to 1.",guid,data.id );
1002 data.phaseMask = 1;
1005 if (gameEvent==0 && PoolId==0) // if not this is to be managed by GameEvent System or Pool system
1006 AddCreatureToGrid(guid, &data);
1008 ++count;
1010 } while (result->NextRow());
1012 delete result;
1014 sLog.outString();
1015 sLog.outString( ">> Loaded %lu creatures", (unsigned long)mCreatureDataMap.size() );
1018 void ObjectMgr::AddCreatureToGrid(uint32 guid, CreatureData const* data)
1020 uint8 mask = data->spawnMask;
1021 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1023 if(mask & 1)
1025 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1026 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1028 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1029 cell_guids.creatures.insert(guid);
1034 void ObjectMgr::RemoveCreatureFromGrid(uint32 guid, CreatureData const* data)
1036 uint8 mask = data->spawnMask;
1037 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1039 if(mask & 1)
1041 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1042 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1044 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1045 cell_guids.creatures.erase(guid);
1050 void ObjectMgr::LoadGameobjects()
1052 uint32 count = 0;
1054 // 0 1 2 3 4 5 6
1055 QueryResult *result = WorldDatabase.Query("SELECT gameobject.guid, id, map, position_x, position_y, position_z, orientation,"
1056 // 7 8 9 10 11 12 13 14 15 16 17
1057 "rotation0, rotation1, rotation2, rotation3, spawntimesecs, animprogress, state, spawnMask, phaseMask, event, pool_entry "
1058 "FROM gameobject LEFT OUTER JOIN game_event_gameobject ON gameobject.guid = game_event_gameobject.guid "
1059 "LEFT OUTER JOIN pool_gameobject ON gameobject.guid = pool_gameobject.guid");
1061 if(!result)
1063 barGoLink bar(1);
1065 bar.step();
1067 sLog.outString();
1068 sLog.outErrorDb(">> Loaded 0 gameobjects. DB table `gameobject` is empty.");
1069 return;
1072 barGoLink bar(result->GetRowCount());
1076 Field *fields = result->Fetch();
1077 bar.step();
1079 uint32 guid = fields[ 0].GetUInt32();
1080 uint32 entry = fields[ 1].GetUInt32();
1082 GameObjectInfo const* gInfo = GetGameObjectInfo(entry);
1083 if(!gInfo)
1085 sLog.outErrorDb("Table `gameobject` has gameobject (GUID: %u) with non existing gameobject entry %u, skipped.", guid, entry);
1086 continue;
1089 GameObjectData& data = mGameObjectDataMap[guid];
1091 data.id = entry;
1092 data.mapid = fields[ 2].GetUInt32();
1093 data.posX = fields[ 3].GetFloat();
1094 data.posY = fields[ 4].GetFloat();
1095 data.posZ = fields[ 5].GetFloat();
1096 data.orientation = fields[ 6].GetFloat();
1097 data.rotation0 = fields[ 7].GetFloat();
1098 data.rotation1 = fields[ 8].GetFloat();
1099 data.rotation2 = fields[ 9].GetFloat();
1100 data.rotation3 = fields[10].GetFloat();
1101 data.spawntimesecs = fields[11].GetInt32();
1102 data.animprogress = fields[12].GetUInt32();
1104 uint32 go_state = fields[13].GetUInt32();
1105 if (go_state >= MAX_GO_STATE)
1107 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with invalid `state` (%u) value, skip",guid,data.id,go_state);
1108 continue;
1110 data.go_state = GOState(go_state);
1112 data.spawnMask = fields[14].GetUInt8();
1113 data.phaseMask = fields[15].GetUInt16();
1114 int16 gameEvent = fields[16].GetInt16();
1115 int16 PoolId = fields[17].GetInt16();
1117 if(data.rotation2 < -1.0f || data.rotation2 > 1.0f)
1119 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with invalid rotation2 (%f) value, skip",guid,data.id,data.rotation2 );
1120 continue;
1123 if(data.rotation3 < -1.0f || data.rotation3 > 1.0f)
1125 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with invalid rotation3 (%f) value, skip",guid,data.id,data.rotation3 );
1126 continue;
1129 if(!MapManager::IsValidMapCoord(data.mapid,data.posX,data.posY,data.posZ,data.orientation))
1131 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with invalid coordinates, skip",guid,data.id );
1132 continue;
1135 if(data.phaseMask==0)
1137 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u Entry: %u) with `phaseMask`=0 (not visible for anyone), set to 1.",guid,data.id );
1138 data.phaseMask = 1;
1141 if (gameEvent==0 && PoolId==0) // if not this is to be managed by GameEvent System or Pool system
1142 AddGameobjectToGrid(guid, &data);
1143 ++count;
1145 } while (result->NextRow());
1147 delete result;
1149 sLog.outString();
1150 sLog.outString( ">> Loaded %lu gameobjects", (unsigned long)mGameObjectDataMap.size());
1153 void ObjectMgr::AddGameobjectToGrid(uint32 guid, GameObjectData const* data)
1155 uint8 mask = data->spawnMask;
1156 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1158 if(mask & 1)
1160 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1161 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1163 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1164 cell_guids.gameobjects.insert(guid);
1169 void ObjectMgr::RemoveGameobjectFromGrid(uint32 guid, GameObjectData const* data)
1171 uint8 mask = data->spawnMask;
1172 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1174 if(mask & 1)
1176 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1177 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1179 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1180 cell_guids.gameobjects.erase(guid);
1185 void ObjectMgr::LoadCreatureRespawnTimes()
1187 // remove outdated data
1188 WorldDatabase.DirectExecute("DELETE FROM creature_respawn WHERE respawntime <= UNIX_TIMESTAMP(NOW())");
1190 uint32 count = 0;
1192 QueryResult *result = WorldDatabase.Query("SELECT guid,respawntime,instance FROM creature_respawn");
1194 if(!result)
1196 barGoLink bar(1);
1198 bar.step();
1200 sLog.outString();
1201 sLog.outString(">> Loaded 0 creature respawn time.");
1202 return;
1205 barGoLink bar(result->GetRowCount());
1209 Field *fields = result->Fetch();
1210 bar.step();
1212 uint32 loguid = fields[0].GetUInt32();
1213 uint64 respawn_time = fields[1].GetUInt64();
1214 uint32 instance = fields[2].GetUInt32();
1216 mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = time_t(respawn_time);
1218 ++count;
1219 } while (result->NextRow());
1221 delete result;
1223 sLog.outString( ">> Loaded %lu creature respawn times", (unsigned long)mCreatureRespawnTimes.size() );
1224 sLog.outString();
1227 void ObjectMgr::LoadGameobjectRespawnTimes()
1229 // remove outdated data
1230 WorldDatabase.DirectExecute("DELETE FROM gameobject_respawn WHERE respawntime <= UNIX_TIMESTAMP(NOW())");
1232 uint32 count = 0;
1234 QueryResult *result = WorldDatabase.Query("SELECT guid,respawntime,instance FROM gameobject_respawn");
1236 if(!result)
1238 barGoLink bar(1);
1240 bar.step();
1242 sLog.outString();
1243 sLog.outString(">> Loaded 0 gameobject respawn time.");
1244 return;
1247 barGoLink bar(result->GetRowCount());
1251 Field *fields = result->Fetch();
1252 bar.step();
1254 uint32 loguid = fields[0].GetUInt32();
1255 uint64 respawn_time = fields[1].GetUInt64();
1256 uint32 instance = fields[2].GetUInt32();
1258 mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = time_t(respawn_time);
1260 ++count;
1261 } while (result->NextRow());
1263 delete result;
1265 sLog.outString( ">> Loaded %lu gameobject respawn times", (unsigned long)mGORespawnTimes.size() );
1266 sLog.outString();
1269 // name must be checked to correctness (if received) before call this function
1270 uint64 ObjectMgr::GetPlayerGUIDByName(std::string name) const
1272 uint64 guid = 0;
1274 CharacterDatabase.escape_string(name);
1276 // Player name safe to sending to DB (checked at login) and this function using
1277 QueryResult *result = CharacterDatabase.PQuery("SELECT guid FROM characters WHERE name = '%s'", name.c_str());
1278 if(result)
1280 guid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
1282 delete result;
1285 return guid;
1288 bool ObjectMgr::GetPlayerNameByGUID(const uint64 &guid, std::string &name) const
1290 // prevent DB access for online player
1291 if(Player* player = GetPlayer(guid))
1293 name = player->GetName();
1294 return true;
1297 QueryResult *result = CharacterDatabase.PQuery("SELECT name FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1299 if(result)
1301 name = (*result)[0].GetCppString();
1302 delete result;
1303 return true;
1306 return false;
1309 uint32 ObjectMgr::GetPlayerTeamByGUID(const uint64 &guid) const
1311 QueryResult *result = CharacterDatabase.PQuery("SELECT race FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1313 if(result)
1315 uint8 race = (*result)[0].GetUInt8();
1316 delete result;
1317 return Player::TeamForRace(race);
1320 return 0;
1323 uint32 ObjectMgr::GetPlayerAccountIdByGUID(const uint64 &guid) const
1325 QueryResult *result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1326 if(result)
1328 uint32 acc = (*result)[0].GetUInt32();
1329 delete result;
1330 return acc;
1333 return 0;
1336 uint32 ObjectMgr::GetPlayerAccountIdByPlayerName(const std::string& name) const
1338 QueryResult *result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'", name.c_str());
1339 if(result)
1341 uint32 acc = (*result)[0].GetUInt32();
1342 delete result;
1343 return acc;
1346 return 0;
1349 void ObjectMgr::LoadItemLocales()
1351 mItemLocaleMap.clear(); // need for reload case
1353 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");
1355 if(!result)
1357 barGoLink bar(1);
1359 bar.step();
1361 sLog.outString();
1362 sLog.outString(">> Loaded 0 Item locale strings. DB table `locales_item` is empty.");
1363 return;
1366 barGoLink bar(result->GetRowCount());
1370 Field *fields = result->Fetch();
1371 bar.step();
1373 uint32 entry = fields[0].GetUInt32();
1375 ItemLocale& data = mItemLocaleMap[entry];
1377 for(int i = 1; i < MAX_LOCALE; ++i)
1379 std::string str = fields[1+2*(i-1)].GetCppString();
1380 if(!str.empty())
1382 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
1383 if(idx >= 0)
1385 if(data.Name.size() <= idx)
1386 data.Name.resize(idx+1);
1388 data.Name[idx] = str;
1392 str = fields[1+2*(i-1)+1].GetCppString();
1393 if(!str.empty())
1395 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
1396 if(idx >= 0)
1398 if(data.Description.size() <= idx)
1399 data.Description.resize(idx+1);
1401 data.Description[idx] = str;
1405 } while (result->NextRow());
1407 delete result;
1409 sLog.outString();
1410 sLog.outString( ">> Loaded %lu Item locale strings", (unsigned long)mItemLocaleMap.size() );
1413 struct SQLItemLoader : public SQLStorageLoaderBase<SQLItemLoader>
1415 template<class D>
1416 void convert_from_str(uint32 /*field_pos*/, char *src, D &dst)
1418 dst = D(objmgr.GetScriptId(src));
1422 void ObjectMgr::LoadItemPrototypes()
1424 SQLItemLoader loader;
1425 loader.Load(sItemStorage);
1426 sLog.outString( ">> Loaded %u item prototypes", sItemStorage.RecordCount );
1427 sLog.outString();
1429 // check data correctness
1430 for(uint32 i = 1; i < sItemStorage.MaxEntry; ++i)
1432 ItemPrototype const* proto = sItemStorage.LookupEntry<ItemPrototype >(i);
1433 ItemEntry const *dbcitem = sItemStore.LookupEntry(i);
1434 if(!proto)
1436 /* to many errors, and possible not all items really used in game
1437 if (dbcitem)
1438 sLog.outErrorDb("Item (Entry: %u) doesn't exists in DB, but must exist.",i);
1440 continue;
1443 if(dbcitem)
1445 if(proto->Class != dbcitem->Class)
1447 sLog.outErrorDb("Item (Entry: %u) not correct class %u, must be %u (still using DB value).",i,proto->Class,dbcitem->Class);
1448 // It safe let use Class from DB
1450 /* disabled: have some strange wrong cases for Subclass values.
1451 for enable also uncomment Subclass field in ItemEntry structure and in Itemfmt[]
1452 if(proto->SubClass != dbcitem->SubClass)
1454 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);
1455 // It safe let use Subclass from DB
1459 if(proto->Unk0 != dbcitem->Unk0)
1461 sLog.outErrorDb("Item (Entry: %u) not correct %i Unk0, must be %i (still using DB value).",i,proto->Unk0,dbcitem->Unk0);
1462 // It safe let use Unk0 from DB
1465 if(proto->Material != dbcitem->Material)
1467 sLog.outErrorDb("Item (Entry: %u) not correct %i material, must be %i (still using DB value).",i,proto->Material,dbcitem->Material);
1468 // It safe let use Material from DB
1471 if(proto->InventoryType != dbcitem->InventoryType)
1473 sLog.outErrorDb("Item (Entry: %u) not correct %u inventory type, must be %u (still using DB value).",i,proto->InventoryType,dbcitem->InventoryType);
1474 // It safe let use InventoryType from DB
1477 if(proto->DisplayInfoID != dbcitem->DisplayId)
1479 sLog.outErrorDb("Item (Entry: %u) not correct %u display id, must be %u (using it).",i,proto->DisplayInfoID,dbcitem->DisplayId);
1480 const_cast<ItemPrototype*>(proto)->DisplayInfoID = dbcitem->DisplayId;
1482 if(proto->Sheath != dbcitem->Sheath)
1484 sLog.outErrorDb("Item (Entry: %u) not correct %u sheath, must be %u (using it).",i,proto->Sheath,dbcitem->Sheath);
1485 const_cast<ItemPrototype*>(proto)->Sheath = dbcitem->Sheath;
1488 else
1490 sLog.outErrorDb("Item (Entry: %u) not correct (not listed in list of existed items).",i);
1493 if(proto->Class >= MAX_ITEM_CLASS)
1495 sLog.outErrorDb("Item (Entry: %u) has wrong Class value (%u)",i,proto->Class);
1496 const_cast<ItemPrototype*>(proto)->Class = ITEM_CLASS_MISC;
1499 if(proto->SubClass >= MaxItemSubclassValues[proto->Class])
1501 sLog.outErrorDb("Item (Entry: %u) has wrong Subclass value (%u) for class %u",i,proto->SubClass,proto->Class);
1502 const_cast<ItemPrototype*>(proto)->SubClass = 0;// exist for all item classes
1505 if(proto->Quality >= MAX_ITEM_QUALITY)
1507 sLog.outErrorDb("Item (Entry: %u) has wrong Quality value (%u)",i,proto->Quality);
1508 const_cast<ItemPrototype*>(proto)->Quality = ITEM_QUALITY_NORMAL;
1511 if(proto->BuyCount <= 0)
1513 sLog.outErrorDb("Item (Entry: %u) has wrong BuyCount value (%u), set to default(1).",i,proto->BuyCount);
1514 const_cast<ItemPrototype*>(proto)->BuyCount = 1;
1517 if(proto->InventoryType >= MAX_INVTYPE)
1519 sLog.outErrorDb("Item (Entry: %u) has wrong InventoryType value (%u)",i,proto->InventoryType);
1520 const_cast<ItemPrototype*>(proto)->InventoryType = INVTYPE_NON_EQUIP;
1523 if(proto->RequiredSkill >= MAX_SKILL_TYPE)
1525 sLog.outErrorDb("Item (Entry: %u) has wrong RequiredSkill value (%u)",i,proto->RequiredSkill);
1526 const_cast<ItemPrototype*>(proto)->RequiredSkill = 0;
1531 // can be used in equip slot, as page read use in inventory, or spell casting at use
1532 bool req = proto->InventoryType!=INVTYPE_NON_EQUIP || proto->PageText;
1533 if(!req)
1535 for (int j = 0; j < MAX_ITEM_PROTO_SPELLS; ++j)
1537 if(proto->Spells[j].SpellId)
1539 req = true;
1540 break;
1545 if(req)
1547 if(!(proto->AllowableClass & CLASSMASK_ALL_PLAYABLE))
1548 sLog.outErrorDb("Item (Entry: %u) not have in `AllowableClass` any playable classes (%u) and can't be equipped or use.",i,proto->AllowableClass);
1550 if(!(proto->AllowableRace & RACEMASK_ALL_PLAYABLE))
1551 sLog.outErrorDb("Item (Entry: %u) not have in `AllowableRace` any playable races (%u) and can't be equipped or use.",i,proto->AllowableRace);
1555 if(proto->RequiredSpell && !sSpellStore.LookupEntry(proto->RequiredSpell))
1557 sLog.outErrorDb("Item (Entry: %u) have wrong (non-existed) spell in RequiredSpell (%u)",i,proto->RequiredSpell);
1558 const_cast<ItemPrototype*>(proto)->RequiredSpell = 0;
1561 if(proto->RequiredReputationRank >= MAX_REPUTATION_RANK)
1562 sLog.outErrorDb("Item (Entry: %u) has wrong reputation rank in RequiredReputationRank (%u), item can't be used.",i,proto->RequiredReputationRank);
1564 if(proto->RequiredReputationFaction)
1566 if(!sFactionStore.LookupEntry(proto->RequiredReputationFaction))
1568 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) faction in RequiredReputationFaction (%u)",i,proto->RequiredReputationFaction);
1569 const_cast<ItemPrototype*>(proto)->RequiredReputationFaction = 0;
1572 if(proto->RequiredReputationRank == MIN_REPUTATION_RANK)
1573 sLog.outErrorDb("Item (Entry: %u) has min. reputation rank in RequiredReputationRank (0) but RequiredReputationFaction > 0, faction setting is useless.",i);
1575 else if(proto->RequiredReputationRank > MIN_REPUTATION_RANK)
1576 sLog.outErrorDb("Item (Entry: %u) has RequiredReputationFaction ==0 but RequiredReputationRank > 0, rank setting is useless.",i);
1578 if(proto->MaxCount < -1)
1580 sLog.outErrorDb("Item (Entry: %u) has too large negative in maxcount (%i), replace by value (-1) no storing limits.",i,proto->MaxCount);
1581 const_cast<ItemPrototype*>(proto)->MaxCount = -1;
1584 if(proto->Stackable==0)
1586 sLog.outErrorDb("Item (Entry: %u) has wrong value in stackable (%i), replace by default 1.",i,proto->Stackable);
1587 const_cast<ItemPrototype*>(proto)->Stackable = 1;
1589 else if(proto->Stackable < -1)
1591 sLog.outErrorDb("Item (Entry: %u) has too large negative in stackable (%i), replace by value (-1) no stacking limits.",i,proto->Stackable);
1592 const_cast<ItemPrototype*>(proto)->Stackable = -1;
1594 else if(proto->Stackable > 255)
1596 sLog.outErrorDb("Item (Entry: %u) has too large value in stackable (%u), replace by hardcoded upper limit (255).",i,proto->Stackable);
1597 const_cast<ItemPrototype*>(proto)->Stackable = 255;
1600 if(proto->StatsCount > MAX_ITEM_PROTO_STATS)
1602 sLog.outErrorDb("Item (Entry: %u) has too large value in statscount (%u), replace by hardcoded limit (%u).",i,proto->StatsCount,MAX_ITEM_PROTO_STATS);
1603 const_cast<ItemPrototype*>(proto)->StatsCount = MAX_ITEM_PROTO_STATS;
1606 for (int j = 0; j < MAX_ITEM_PROTO_STATS; ++j)
1608 // for ItemStatValue != 0
1609 if(proto->ItemStat[j].ItemStatValue && proto->ItemStat[j].ItemStatType >= MAX_ITEM_MOD)
1611 sLog.outErrorDb("Item (Entry: %u) has wrong stat_type%d (%u)",i,j+1,proto->ItemStat[j].ItemStatType);
1612 const_cast<ItemPrototype*>(proto)->ItemStat[j].ItemStatType = 0;
1616 for (int j = 0; j < MAX_ITEM_PROTO_DAMAGES; ++j)
1618 if(proto->Damage[j].DamageType >= MAX_SPELL_SCHOOL)
1620 sLog.outErrorDb("Item (Entry: %u) has wrong dmg_type%d (%u)",i,j+1,proto->Damage[j].DamageType);
1621 const_cast<ItemPrototype*>(proto)->Damage[j].DamageType = 0;
1625 // special format
1626 if((proto->Spells[0].SpellId == SPELL_ID_GENERIC_LEARN) || (proto->Spells[0].SpellId == SPELL_ID_GENERIC_LEARN_PET))
1628 // spell_1
1629 if(proto->Spells[0].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
1631 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);
1632 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1633 const_cast<ItemPrototype*>(proto)->Spells[0].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1634 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1635 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1638 // spell_2 have learning spell
1639 if(proto->Spells[1].SpellTrigger != ITEM_SPELLTRIGGER_LEARN_SPELL_ID)
1641 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);
1642 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1643 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1644 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1646 else if(!proto->Spells[1].SpellId)
1648 sLog.outErrorDb("Item (Entry: %u) not has expected spell in spellid_%d in special learning format.",i,1+1);
1649 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1650 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1652 else
1654 SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[1].SpellId);
1655 if(!spellInfo)
1657 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%u)",i,1+1,proto->Spells[1].SpellId);
1658 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1659 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1660 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1662 // allowed only in special format
1663 else if((proto->Spells[1].SpellId==SPELL_ID_GENERIC_LEARN) || (proto->Spells[1].SpellId==SPELL_ID_GENERIC_LEARN_PET))
1665 sLog.outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%u)",i,1+1,proto->Spells[1].SpellId);
1666 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1667 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1668 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1672 // spell_3*,spell_4*,spell_5* is empty
1673 for (int j = 2; j < MAX_ITEM_PROTO_SPELLS; ++j)
1675 if(proto->Spells[j].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
1677 sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)",i,j+1,proto->Spells[j].SpellTrigger);
1678 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1679 const_cast<ItemPrototype*>(proto)->Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1681 else if(proto->Spells[j].SpellId != 0)
1683 sLog.outErrorDb("Item (Entry: %u) has wrong spell in spellid_%d (%u) for learning special format",i,j+1,proto->Spells[j].SpellId);
1684 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1688 // normal spell list
1689 else
1691 for (int j = 0; j < MAX_ITEM_PROTO_SPELLS; ++j)
1693 if(proto->Spells[j].SpellTrigger >= MAX_ITEM_SPELLTRIGGER || proto->Spells[j].SpellTrigger == ITEM_SPELLTRIGGER_LEARN_SPELL_ID)
1695 sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)",i,j+1,proto->Spells[j].SpellTrigger);
1696 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1697 const_cast<ItemPrototype*>(proto)->Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1700 if(proto->Spells[j].SpellId)
1702 SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[j].SpellId);
1703 if(!spellInfo)
1705 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%u)",i,j+1,proto->Spells[j].SpellId);
1706 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1708 // allowed only in special format
1709 else if((proto->Spells[j].SpellId==SPELL_ID_GENERIC_LEARN) || (proto->Spells[j].SpellId==SPELL_ID_GENERIC_LEARN_PET))
1711 sLog.outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%u)",i,j+1,proto->Spells[j].SpellId);
1712 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1718 if(proto->Bonding >= MAX_BIND_TYPE)
1719 sLog.outErrorDb("Item (Entry: %u) has wrong Bonding value (%u)",i,proto->Bonding);
1721 if(proto->PageText && !sPageTextStore.LookupEntry<PageText>(proto->PageText))
1722 sLog.outErrorDb("Item (Entry: %u) has non existing first page (Id:%u)", i,proto->PageText);
1724 if(proto->LockID && !sLockStore.LookupEntry(proto->LockID))
1725 sLog.outErrorDb("Item (Entry: %u) has wrong LockID (%u)",i,proto->LockID);
1727 if(proto->Sheath >= MAX_SHEATHETYPE)
1729 sLog.outErrorDb("Item (Entry: %u) has wrong Sheath (%u)",i,proto->Sheath);
1730 const_cast<ItemPrototype*>(proto)->Sheath = SHEATHETYPE_NONE;
1733 if(proto->RandomProperty && !sItemRandomPropertiesStore.LookupEntry(GetItemEnchantMod(proto->RandomProperty)))
1735 sLog.outErrorDb("Item (Entry: %u) has unknown (wrong or not listed in `item_enchantment_template`) RandomProperty (%u)",i,proto->RandomProperty);
1736 const_cast<ItemPrototype*>(proto)->RandomProperty = 0;
1739 if(proto->RandomSuffix && !sItemRandomSuffixStore.LookupEntry(GetItemEnchantMod(proto->RandomSuffix)))
1741 sLog.outErrorDb("Item (Entry: %u) has wrong RandomSuffix (%u)",i,proto->RandomSuffix);
1742 const_cast<ItemPrototype*>(proto)->RandomSuffix = 0;
1745 if(proto->ItemSet && !sItemSetStore.LookupEntry(proto->ItemSet))
1747 sLog.outErrorDb("Item (Entry: %u) have wrong ItemSet (%u)",i,proto->ItemSet);
1748 const_cast<ItemPrototype*>(proto)->ItemSet = 0;
1751 if(proto->Area && !GetAreaEntryByAreaID(proto->Area))
1752 sLog.outErrorDb("Item (Entry: %u) has wrong Area (%u)",i,proto->Area);
1754 if(proto->Map && !sMapStore.LookupEntry(proto->Map))
1755 sLog.outErrorDb("Item (Entry: %u) has wrong Map (%u)",i,proto->Map);
1757 if(proto->BagFamily)
1759 // check bits
1760 for(uint32 j = 0; j < sizeof(proto->BagFamily)*8; ++j)
1762 uint32 mask = 1 << j;
1763 if((proto->BagFamily & mask)==0)
1764 continue;
1766 ItemBagFamilyEntry const* bf = sItemBagFamilyStore.LookupEntry(j+1);
1767 if(!bf)
1769 sLog.outErrorDb("Item (Entry: %u) has bag family bit set not listed in ItemBagFamily.dbc, remove bit",i);
1770 const_cast<ItemPrototype*>(proto)->BagFamily &= ~mask;
1771 continue;
1774 if(BAG_FAMILY_MASK_CURRENCY_TOKENS & mask)
1776 CurrencyTypesEntry const* ctEntry = sCurrencyTypesStore.LookupEntry(proto->ItemId);
1777 if(!ctEntry)
1779 sLog.outErrorDb("Item (Entry: %u) has currency bag family bit set in BagFamily but not listed in CurrencyTypes.dbc, remove bit",i);
1780 const_cast<ItemPrototype*>(proto)->BagFamily &= ~mask;
1786 if(proto->TotemCategory && !sTotemCategoryStore.LookupEntry(proto->TotemCategory))
1787 sLog.outErrorDb("Item (Entry: %u) has wrong TotemCategory (%u)",i,proto->TotemCategory);
1789 for (int j = 0; j < MAX_ITEM_PROTO_SOCKETS; j++)
1791 if(proto->Socket[j].Color && (proto->Socket[j].Color & SOCKET_COLOR_ALL) != proto->Socket[j].Color)
1793 sLog.outErrorDb("Item (Entry: %u) has wrong socketColor_%d (%u)",i,j+1,proto->Socket[j].Color);
1794 const_cast<ItemPrototype*>(proto)->Socket[j].Color = 0;
1798 if(proto->GemProperties && !sGemPropertiesStore.LookupEntry(proto->GemProperties))
1799 sLog.outErrorDb("Item (Entry: %u) has wrong GemProperties (%u)",i,proto->GemProperties);
1801 if(proto->FoodType >= MAX_PET_DIET)
1803 sLog.outErrorDb("Item (Entry: %u) has wrong FoodType value (%u)",i,proto->FoodType);
1804 const_cast<ItemPrototype*>(proto)->FoodType = 0;
1807 if(proto->ItemLimitCategory && !sItemLimitCategoryStore.LookupEntry(proto->ItemLimitCategory))
1809 sLog.outErrorDb("Item (Entry: %u) has wrong LimitCategory value (%u)",i,proto->ItemLimitCategory);
1810 const_cast<ItemPrototype*>(proto)->ItemLimitCategory = 0;
1815 void ObjectMgr::LoadPetLevelInfo()
1817 // Loading levels data
1819 // 0 1 2 3 4 5 6 7 8 9
1820 QueryResult *result = WorldDatabase.Query("SELECT creature_entry, level, hp, mana, str, agi, sta, inte, spi, armor FROM pet_levelstats");
1822 uint32 count = 0;
1824 if (!result)
1826 barGoLink bar( 1 );
1828 sLog.outString();
1829 sLog.outString( ">> Loaded %u level pet stats definitions", count );
1830 sLog.outErrorDb( "Error loading `pet_levelstats` table or empty table.");
1831 return;
1834 barGoLink bar( result->GetRowCount() );
1838 Field* fields = result->Fetch();
1840 uint32 creature_id = fields[0].GetUInt32();
1841 if(!sCreatureStorage.LookupEntry<CreatureInfo>(creature_id))
1843 sLog.outErrorDb("Wrong creature id %u in `pet_levelstats` table, ignoring.",creature_id);
1844 continue;
1847 uint32 current_level = fields[1].GetUInt32();
1848 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
1850 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
1851 sLog.outErrorDb("Wrong (> %u) level %u in `pet_levelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
1852 else
1854 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `pet_levelstats` table, ignoring.",current_level);
1855 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
1857 continue;
1859 else if(current_level < 1)
1861 sLog.outErrorDb("Wrong (<1) level %u in `pet_levelstats` table, ignoring.",current_level);
1862 continue;
1865 PetLevelInfo*& pInfoMapEntry = petInfo[creature_id];
1867 if(pInfoMapEntry==NULL)
1868 pInfoMapEntry = new PetLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
1870 // data for level 1 stored in [0] array element, ...
1871 PetLevelInfo* pLevelInfo = &pInfoMapEntry[current_level-1];
1873 pLevelInfo->health = fields[2].GetUInt16();
1874 pLevelInfo->mana = fields[3].GetUInt16();
1875 pLevelInfo->armor = fields[9].GetUInt16();
1877 for (int i = 0; i < MAX_STATS; i++)
1879 pLevelInfo->stats[i] = fields[i+4].GetUInt16();
1882 bar.step();
1883 ++count;
1885 while (result->NextRow());
1887 delete result;
1889 sLog.outString();
1890 sLog.outString( ">> Loaded %u level pet stats definitions", count );
1893 // Fill gaps and check integrity
1894 for (PetLevelInfoMap::iterator itr = petInfo.begin(); itr != petInfo.end(); ++itr)
1896 PetLevelInfo* pInfo = itr->second;
1898 // fatal error if no level 1 data
1899 if(!pInfo || pInfo[0].health == 0 )
1901 sLog.outErrorDb("Creature %u does not have pet stats data for Level 1!",itr->first);
1902 exit(1);
1905 // fill level gaps
1906 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
1908 if(pInfo[level].health == 0)
1910 sLog.outErrorDb("Creature %u has no data for Level %i pet stats data, using data of Level %i.",itr->first,level+1, level);
1911 pInfo[level] = pInfo[level-1];
1917 PetLevelInfo const* ObjectMgr::GetPetLevelInfo(uint32 creature_id, uint32 level) const
1919 if(level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
1920 level = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL);
1922 PetLevelInfoMap::const_iterator itr = petInfo.find(creature_id);
1923 if(itr == petInfo.end())
1924 return NULL;
1926 return &itr->second[level-1]; // data for level 1 stored in [0] array element, ...
1929 void ObjectMgr::LoadPlayerInfo()
1931 // Load playercreate
1933 // 0 1 2 3 4 5 6
1934 QueryResult *result = WorldDatabase.Query("SELECT race, class, map, zone, position_x, position_y, position_z FROM playercreateinfo");
1936 uint32 count = 0;
1938 if (!result)
1940 barGoLink bar( 1 );
1942 sLog.outString();
1943 sLog.outString( ">> Loaded %u player create definitions", count );
1944 sLog.outErrorDb( "Error loading `playercreateinfo` table or empty table.");
1945 exit(1);
1948 barGoLink bar( result->GetRowCount() );
1952 Field* fields = result->Fetch();
1954 uint32 current_race = fields[0].GetUInt32();
1955 uint32 current_class = fields[1].GetUInt32();
1956 uint32 mapId = fields[2].GetUInt32();
1957 uint32 zoneId = fields[3].GetUInt32();
1958 float positionX = fields[4].GetFloat();
1959 float positionY = fields[5].GetFloat();
1960 float positionZ = fields[6].GetFloat();
1962 if(current_race >= MAX_RACES)
1964 sLog.outErrorDb("Wrong race %u in `playercreateinfo` table, ignoring.",current_race);
1965 continue;
1968 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(current_race);
1969 if(!rEntry)
1971 sLog.outErrorDb("Wrong race %u in `playercreateinfo` table, ignoring.",current_race);
1972 continue;
1975 if(current_class >= MAX_CLASSES)
1977 sLog.outErrorDb("Wrong class %u in `playercreateinfo` table, ignoring.",current_class);
1978 continue;
1981 if(!sChrClassesStore.LookupEntry(current_class))
1983 sLog.outErrorDb("Wrong class %u in `playercreateinfo` table, ignoring.",current_class);
1984 continue;
1987 // accept DB data only for valid position (and non instanceable)
1988 if( !MapManager::IsValidMapCoord(mapId,positionX,positionY,positionZ) )
1990 sLog.outErrorDb("Wrong home position for class %u race %u pair in `playercreateinfo` table, ignoring.",current_class,current_race);
1991 continue;
1994 if( sMapStore.LookupEntry(mapId)->Instanceable() )
1996 sLog.outErrorDb("Home position in instanceable map for class %u race %u pair in `playercreateinfo` table, ignoring.",current_class,current_race);
1997 continue;
2000 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2002 pInfo->mapId = mapId;
2003 pInfo->zoneId = zoneId;
2004 pInfo->positionX = positionX;
2005 pInfo->positionY = positionY;
2006 pInfo->positionZ = positionZ;
2008 pInfo->displayId_m = rEntry->model_m;
2009 pInfo->displayId_f = rEntry->model_f;
2011 bar.step();
2012 ++count;
2014 while (result->NextRow());
2016 delete result;
2018 sLog.outString();
2019 sLog.outString( ">> Loaded %u player create definitions", count );
2022 // Load playercreate items
2024 // 0 1 2 3
2025 QueryResult *result = WorldDatabase.Query("SELECT race, class, itemid, amount FROM playercreateinfo_item");
2027 uint32 count = 0;
2029 if (!result)
2031 barGoLink bar( 1 );
2033 bar.step();
2035 sLog.outString();
2036 sLog.outString( ">> Loaded %u custom player create items", count );
2038 else
2040 barGoLink bar( result->GetRowCount() );
2044 Field* fields = result->Fetch();
2046 uint32 current_race = fields[0].GetUInt32();
2047 if(current_race >= MAX_RACES)
2049 sLog.outErrorDb("Wrong race %u in `playercreateinfo_item` table, ignoring.",current_race);
2050 continue;
2053 uint32 current_class = fields[1].GetUInt32();
2054 if(current_class >= MAX_CLASSES)
2056 sLog.outErrorDb("Wrong class %u in `playercreateinfo_item` table, ignoring.",current_class);
2057 continue;
2060 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2062 uint32 item_id = fields[2].GetUInt32();
2064 if(!GetItemPrototype(item_id))
2066 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);
2067 continue;
2070 uint32 amount = fields[3].GetUInt32();
2072 if(!amount)
2074 sLog.outErrorDb("Item id %u (class %u race %u) have amount==0 in `playercreateinfo_item` table, ignoring.",item_id,current_race,current_class);
2075 continue;
2078 pInfo->item.push_back(PlayerCreateInfoItem( item_id, amount));
2080 bar.step();
2081 ++count;
2083 while(result->NextRow());
2085 delete result;
2087 sLog.outString();
2088 sLog.outString( ">> Loaded %u custom player create items", count );
2092 // Load playercreate spells
2094 // 0 1 2
2095 QueryResult *result = WorldDatabase.Query("SELECT race, class, Spell FROM playercreateinfo_spell");
2097 uint32 count = 0;
2099 if (!result)
2101 barGoLink bar( 1 );
2103 sLog.outString();
2104 sLog.outString( ">> Loaded %u player create spells", count );
2105 sLog.outErrorDb( "Error loading `playercreateinfo_spell` table or empty table.");
2107 else
2109 barGoLink bar( result->GetRowCount() );
2113 Field* fields = result->Fetch();
2115 uint32 current_race = fields[0].GetUInt32();
2116 if(current_race >= MAX_RACES)
2118 sLog.outErrorDb("Wrong race %u in `playercreateinfo_spell` table, ignoring.",current_race);
2119 continue;
2122 uint32 current_class = fields[1].GetUInt32();
2123 if(current_class >= MAX_CLASSES)
2125 sLog.outErrorDb("Wrong class %u in `playercreateinfo_spell` table, ignoring.",current_class);
2126 continue;
2129 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2130 pInfo->spell.push_back(fields[2].GetUInt32());
2132 bar.step();
2133 ++count;
2135 while( result->NextRow() );
2137 delete result;
2139 sLog.outString();
2140 sLog.outString( ">> Loaded %u player create spells", count );
2144 // Load playercreate actions
2146 // 0 1 2 3 4 5
2147 QueryResult *result = WorldDatabase.Query("SELECT race, class, button, action, type, misc FROM playercreateinfo_action");
2149 uint32 count = 0;
2151 if (!result)
2153 barGoLink bar( 1 );
2155 sLog.outString();
2156 sLog.outString( ">> Loaded %u player create actions", count );
2157 sLog.outErrorDb( "Error loading `playercreateinfo_action` table or empty table.");
2159 else
2161 barGoLink bar( result->GetRowCount() );
2165 Field* fields = result->Fetch();
2167 uint32 current_race = fields[0].GetUInt32();
2168 if(current_race >= MAX_RACES)
2170 sLog.outErrorDb("Wrong race %u in `playercreateinfo_action` table, ignoring.",current_race);
2171 continue;
2174 uint32 current_class = fields[1].GetUInt32();
2175 if(current_class >= MAX_CLASSES)
2177 sLog.outErrorDb("Wrong class %u in `playercreateinfo_action` table, ignoring.",current_class);
2178 continue;
2181 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2182 pInfo->action[0].push_back(fields[2].GetUInt16());
2183 pInfo->action[1].push_back(fields[3].GetUInt16());
2184 pInfo->action[2].push_back(fields[4].GetUInt16());
2185 pInfo->action[3].push_back(fields[5].GetUInt16());
2187 bar.step();
2188 ++count;
2190 while( result->NextRow() );
2192 delete result;
2194 sLog.outString();
2195 sLog.outString( ">> Loaded %u player create actions", count );
2199 // Loading levels data (class only dependent)
2201 // 0 1 2 3
2202 QueryResult *result = WorldDatabase.Query("SELECT class, level, basehp, basemana FROM player_classlevelstats");
2204 uint32 count = 0;
2206 if (!result)
2208 barGoLink bar( 1 );
2210 sLog.outString();
2211 sLog.outString( ">> Loaded %u level health/mana definitions", count );
2212 sLog.outErrorDb( "Error loading `player_classlevelstats` table or empty table.");
2213 exit(1);
2216 barGoLink bar( result->GetRowCount() );
2220 Field* fields = result->Fetch();
2222 uint32 current_class = fields[0].GetUInt32();
2223 if(current_class >= MAX_CLASSES)
2225 sLog.outErrorDb("Wrong class %u in `player_classlevelstats` table, ignoring.",current_class);
2226 continue;
2229 uint32 current_level = fields[1].GetUInt32();
2230 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2232 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2233 sLog.outErrorDb("Wrong (> %u) level %u in `player_classlevelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
2234 else
2236 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_classlevelstats` table, ignoring.",current_level);
2237 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
2239 continue;
2242 PlayerClassInfo* pClassInfo = &playerClassInfo[current_class];
2244 if(!pClassInfo->levelInfo)
2245 pClassInfo->levelInfo = new PlayerClassLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
2247 PlayerClassLevelInfo* pClassLevelInfo = &pClassInfo->levelInfo[current_level-1];
2249 pClassLevelInfo->basehealth = fields[2].GetUInt16();
2250 pClassLevelInfo->basemana = fields[3].GetUInt16();
2252 bar.step();
2253 ++count;
2255 while (result->NextRow());
2257 delete result;
2259 sLog.outString();
2260 sLog.outString( ">> Loaded %u level health/mana definitions", count );
2263 // Fill gaps and check integrity
2264 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2266 // skip non existed classes
2267 if(!sChrClassesStore.LookupEntry(class_))
2268 continue;
2270 PlayerClassInfo* pClassInfo = &playerClassInfo[class_];
2272 // fatal error if no level 1 data
2273 if(!pClassInfo->levelInfo || pClassInfo->levelInfo[0].basehealth == 0 )
2275 sLog.outErrorDb("Class %i Level 1 does not have health/mana data!",class_);
2276 exit(1);
2279 // fill level gaps
2280 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2282 if(pClassInfo->levelInfo[level].basehealth == 0)
2284 sLog.outErrorDb("Class %i Level %i does not have health/mana data. Using stats data of level %i.",class_,level+1, level);
2285 pClassInfo->levelInfo[level] = pClassInfo->levelInfo[level-1];
2290 // Loading levels data (class/race dependent)
2292 // 0 1 2 3 4 5 6 7
2293 QueryResult *result = WorldDatabase.Query("SELECT race, class, level, str, agi, sta, inte, spi FROM player_levelstats");
2295 uint32 count = 0;
2297 if (!result)
2299 barGoLink bar( 1 );
2301 sLog.outString();
2302 sLog.outString( ">> Loaded %u level stats definitions", count );
2303 sLog.outErrorDb( "Error loading `player_levelstats` table or empty table.");
2304 exit(1);
2307 barGoLink bar( result->GetRowCount() );
2311 Field* fields = result->Fetch();
2313 uint32 current_race = fields[0].GetUInt32();
2314 if(current_race >= MAX_RACES)
2316 sLog.outErrorDb("Wrong race %u in `player_levelstats` table, ignoring.",current_race);
2317 continue;
2320 uint32 current_class = fields[1].GetUInt32();
2321 if(current_class >= MAX_CLASSES)
2323 sLog.outErrorDb("Wrong class %u in `player_levelstats` table, ignoring.",current_class);
2324 continue;
2327 uint32 current_level = fields[2].GetUInt32();
2328 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2330 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2331 sLog.outErrorDb("Wrong (> %u) level %u in `player_levelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
2332 else
2334 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_levelstats` table, ignoring.",current_level);
2335 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
2337 continue;
2340 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2342 if(!pInfo->levelInfo)
2343 pInfo->levelInfo = new PlayerLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
2345 PlayerLevelInfo* pLevelInfo = &pInfo->levelInfo[current_level-1];
2347 for (int i = 0; i < MAX_STATS; i++)
2349 pLevelInfo->stats[i] = fields[i+3].GetUInt8();
2352 bar.step();
2353 ++count;
2355 while (result->NextRow());
2357 delete result;
2359 sLog.outString();
2360 sLog.outString( ">> Loaded %u level stats definitions", count );
2363 // Fill gaps and check integrity
2364 for (int race = 0; race < MAX_RACES; ++race)
2366 // skip non existed races
2367 if(!sChrRacesStore.LookupEntry(race))
2368 continue;
2370 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2372 // skip non existed classes
2373 if(!sChrClassesStore.LookupEntry(class_))
2374 continue;
2376 PlayerInfo* pInfo = &playerInfo[race][class_];
2378 // skip non loaded combinations
2379 if(!pInfo->displayId_m || !pInfo->displayId_f)
2380 continue;
2382 // skip expansion races if not playing with expansion
2383 if (sWorld.getConfig(CONFIG_EXPANSION) < 1 && (race == RACE_BLOODELF || race == RACE_DRAENEI))
2384 continue;
2386 // skip expansion classes if not playing with expansion
2387 if (sWorld.getConfig(CONFIG_EXPANSION) < 2 && class_ == CLASS_DEATH_KNIGHT)
2388 continue;
2390 // fatal error if no level 1 data
2391 if(!pInfo->levelInfo || pInfo->levelInfo[0].stats[0] == 0 )
2393 sLog.outErrorDb("Race %i Class %i Level 1 does not have stats data!",race,class_);
2394 exit(1);
2397 // fill level gaps
2398 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2400 if(pInfo->levelInfo[level].stats[0] == 0)
2402 sLog.outErrorDb("Race %i Class %i Level %i does not have stats data. Using stats data of level %i.",race,class_,level+1, level);
2403 pInfo->levelInfo[level] = pInfo->levelInfo[level-1];
2409 // Loading xp per level data
2411 mPlayerXPperLevel.resize(sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL));
2412 for (uint32 level = 0; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2413 mPlayerXPperLevel[level] = 0;
2415 // 0 1
2416 QueryResult *result = WorldDatabase.Query("SELECT lvl, xp_for_next_level FROM player_xp_for_level");
2418 uint32 count = 0;
2420 if (!result)
2422 barGoLink bar( 1 );
2424 sLog.outString();
2425 sLog.outString( ">> Loaded %u xp for level definitions", count );
2426 sLog.outErrorDb( "Error loading `player_xp_for_level` table or empty table.");
2427 exit(1);
2430 barGoLink bar( result->GetRowCount() );
2434 Field* fields = result->Fetch();
2436 uint32 current_level = fields[0].GetUInt32();
2437 uint32 current_xp = fields[1].GetUInt32();
2439 if(current_level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2441 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2442 sLog.outErrorDb("Wrong (> %u) level %u in `player_xp_for_level` table, ignoring.", STRONG_MAX_LEVEL,current_level);
2443 else
2445 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_xp_for_levels` table, ignoring.",current_level);
2446 ++count; // make result loading percent "expected" correct in case disabled detail mode for example.
2448 continue;
2450 //PlayerXPperLevel
2451 mPlayerXPperLevel[current_level] = current_xp;
2452 bar.step();
2453 ++count;
2455 while (result->NextRow());
2457 delete result;
2459 sLog.outString();
2460 sLog.outString( ">> Loaded %u xp for level definitions", count );
2463 // fill level gaps
2464 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2466 if( mPlayerXPperLevel[level] == 0)
2468 sLog.outErrorDb("Level %i does not have XP for level data. Using data of level [%i] + 100.",level+1, level);
2469 mPlayerXPperLevel[level] = mPlayerXPperLevel[level-1]+100;
2474 void ObjectMgr::GetPlayerClassLevelInfo(uint32 class_, uint32 level, PlayerClassLevelInfo* info) const
2476 if(level < 1 || class_ >= MAX_CLASSES)
2477 return;
2479 PlayerClassInfo const* pInfo = &playerClassInfo[class_];
2481 if(level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2482 level = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL);
2484 *info = pInfo->levelInfo[level-1];
2487 void ObjectMgr::GetPlayerLevelInfo(uint32 race, uint32 class_, uint32 level, PlayerLevelInfo* info) const
2489 if(level < 1 || race >= MAX_RACES || class_ >= MAX_CLASSES)
2490 return;
2492 PlayerInfo const* pInfo = &playerInfo[race][class_];
2493 if(pInfo->displayId_m==0 || pInfo->displayId_f==0)
2494 return;
2496 if(level <= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2497 *info = pInfo->levelInfo[level-1];
2498 else
2499 BuildPlayerLevelInfo(race,class_,level,info);
2502 void ObjectMgr::BuildPlayerLevelInfo(uint8 race, uint8 _class, uint8 level, PlayerLevelInfo* info) const
2504 // base data (last known level)
2505 *info = playerInfo[race][_class].levelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)-1];
2507 for(int lvl = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)-1; lvl < level; ++lvl)
2509 switch(_class)
2511 case CLASS_WARRIOR:
2512 info->stats[STAT_STRENGTH] += (lvl > 23 ? 2: (lvl > 1 ? 1: 0));
2513 info->stats[STAT_STAMINA] += (lvl > 23 ? 2: (lvl > 1 ? 1: 0));
2514 info->stats[STAT_AGILITY] += (lvl > 36 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2515 info->stats[STAT_INTELLECT] += (lvl > 9 && !(lvl%2) ? 1: 0);
2516 info->stats[STAT_SPIRIT] += (lvl > 9 && !(lvl%2) ? 1: 0);
2517 break;
2518 case CLASS_PALADIN:
2519 info->stats[STAT_STRENGTH] += (lvl > 3 ? 1: 0);
2520 info->stats[STAT_STAMINA] += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2521 info->stats[STAT_AGILITY] += (lvl > 38 ? 1: (lvl > 7 && !(lvl%2) ? 1: 0));
2522 info->stats[STAT_INTELLECT] += (lvl > 6 && (lvl%2) ? 1: 0);
2523 info->stats[STAT_SPIRIT] += (lvl > 7 ? 1: 0);
2524 break;
2525 case CLASS_HUNTER:
2526 info->stats[STAT_STRENGTH] += (lvl > 4 ? 1: 0);
2527 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2528 info->stats[STAT_AGILITY] += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2529 info->stats[STAT_INTELLECT] += (lvl > 8 && (lvl%2) ? 1: 0);
2530 info->stats[STAT_SPIRIT] += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2531 break;
2532 case CLASS_ROGUE:
2533 info->stats[STAT_STRENGTH] += (lvl > 5 ? 1: 0);
2534 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2535 info->stats[STAT_AGILITY] += (lvl > 16 ? 2: (lvl > 1 ? 1: 0));
2536 info->stats[STAT_INTELLECT] += (lvl > 8 && !(lvl%2) ? 1: 0);
2537 info->stats[STAT_SPIRIT] += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2538 break;
2539 case CLASS_PRIEST:
2540 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2541 info->stats[STAT_STAMINA] += (lvl > 5 ? 1: 0);
2542 info->stats[STAT_AGILITY] += (lvl > 38 ? 1: (lvl > 8 && (lvl%2) ? 1: 0));
2543 info->stats[STAT_INTELLECT] += (lvl > 22 ? 2: (lvl > 1 ? 1: 0));
2544 info->stats[STAT_SPIRIT] += (lvl > 3 ? 1: 0);
2545 break;
2546 case CLASS_SHAMAN:
2547 info->stats[STAT_STRENGTH] += (lvl > 34 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2548 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2549 info->stats[STAT_AGILITY] += (lvl > 7 && !(lvl%2) ? 1: 0);
2550 info->stats[STAT_INTELLECT] += (lvl > 5 ? 1: 0);
2551 info->stats[STAT_SPIRIT] += (lvl > 4 ? 1: 0);
2552 break;
2553 case CLASS_MAGE:
2554 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2555 info->stats[STAT_STAMINA] += (lvl > 5 ? 1: 0);
2556 info->stats[STAT_AGILITY] += (lvl > 9 && !(lvl%2) ? 1: 0);
2557 info->stats[STAT_INTELLECT] += (lvl > 24 ? 2: (lvl > 1 ? 1: 0));
2558 info->stats[STAT_SPIRIT] += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
2559 break;
2560 case CLASS_WARLOCK:
2561 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2562 info->stats[STAT_STAMINA] += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
2563 info->stats[STAT_AGILITY] += (lvl > 9 && !(lvl%2) ? 1: 0);
2564 info->stats[STAT_INTELLECT] += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
2565 info->stats[STAT_SPIRIT] += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
2566 break;
2567 case CLASS_DRUID:
2568 info->stats[STAT_STRENGTH] += (lvl > 38 ? 2: (lvl > 6 && (lvl%2) ? 1: 0));
2569 info->stats[STAT_STAMINA] += (lvl > 32 ? 2: (lvl > 4 ? 1: 0));
2570 info->stats[STAT_AGILITY] += (lvl > 38 ? 2: (lvl > 8 && (lvl%2) ? 1: 0));
2571 info->stats[STAT_INTELLECT] += (lvl > 38 ? 3: (lvl > 4 ? 1: 0));
2572 info->stats[STAT_SPIRIT] += (lvl > 38 ? 3: (lvl > 5 ? 1: 0));
2577 void ObjectMgr::LoadGuilds()
2579 Guild *newguild;
2580 uint32 count = 0;
2582 QueryResult *result = CharacterDatabase.Query( "SELECT guildid FROM guild" );
2584 if( !result )
2587 barGoLink bar( 1 );
2589 bar.step();
2591 sLog.outString();
2592 sLog.outString( ">> Loaded %u guild definitions", count );
2593 return;
2596 barGoLink bar( result->GetRowCount() );
2600 Field *fields = result->Fetch();
2602 bar.step();
2603 ++count;
2605 newguild = new Guild;
2606 if(!newguild->LoadGuildFromDB(fields[0].GetUInt32()))
2608 newguild->Disband();
2609 delete newguild;
2610 continue;
2612 AddGuild(newguild);
2614 }while( result->NextRow() );
2616 delete result;
2618 sLog.outString();
2619 sLog.outString( ">> Loaded %u guild definitions", count );
2622 void ObjectMgr::LoadArenaTeams()
2624 uint32 count = 0;
2626 QueryResult *result = CharacterDatabase.Query( "SELECT arenateamid FROM arena_team" );
2628 if( !result )
2631 barGoLink bar( 1 );
2633 bar.step();
2635 sLog.outString();
2636 sLog.outString( ">> Loaded %u arenateam definitions", count );
2637 return;
2640 barGoLink bar( result->GetRowCount() );
2644 Field *fields = result->Fetch();
2646 bar.step();
2647 ++count;
2649 ArenaTeam *newarenateam = new ArenaTeam;
2650 if(!newarenateam->LoadArenaTeamFromDB(fields[0].GetUInt32()))
2652 delete newarenateam;
2653 continue;
2655 AddArenaTeam(newarenateam);
2656 }while( result->NextRow() );
2658 delete result;
2660 sLog.outString();
2661 sLog.outString( ">> Loaded %u arenateam definitions", count );
2664 void ObjectMgr::LoadGroups()
2666 // -- loading groups --
2667 Group *group = NULL;
2668 uint64 leaderGuid = 0;
2669 uint32 count = 0;
2670 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
2671 QueryResult *result = CharacterDatabase.Query("SELECT mainTank, mainAssistant, lootMethod, looterGuid, lootThreshold, icon1, icon2, icon3, icon4, icon5, icon6, icon7, icon8, isRaid, difficulty, leaderGuid FROM groups");
2673 if( !result )
2675 barGoLink bar( 1 );
2677 bar.step();
2679 sLog.outString();
2680 sLog.outString( ">> Loaded %u group definitions", count );
2681 return;
2684 barGoLink bar( result->GetRowCount() );
2688 bar.step();
2689 Field *fields = result->Fetch();
2690 ++count;
2691 leaderGuid = MAKE_NEW_GUID(fields[15].GetUInt32(),0,HIGHGUID_PLAYER);
2693 group = new Group;
2694 if(!group->LoadGroupFromDB(leaderGuid, result, false))
2696 group->Disband();
2697 delete group;
2698 continue;
2700 AddGroup(group);
2701 }while( result->NextRow() );
2703 delete result;
2705 sLog.outString();
2706 sLog.outString( ">> Loaded %u group definitions", count );
2708 // -- loading members --
2709 count = 0;
2710 group = NULL;
2711 leaderGuid = 0;
2712 // 0 1 2 3
2713 result = CharacterDatabase.Query("SELECT memberGuid, assistant, subgroup, leaderGuid FROM group_member ORDER BY leaderGuid");
2714 if(!result)
2716 barGoLink bar2( 1 );
2717 bar2.step();
2719 else
2721 barGoLink bar2( result->GetRowCount() );
2724 bar2.step();
2725 Field *fields = result->Fetch();
2726 count++;
2727 leaderGuid = MAKE_NEW_GUID(fields[3].GetUInt32(), 0, HIGHGUID_PLAYER);
2728 if(!group || group->GetLeaderGUID() != leaderGuid)
2730 group = GetGroupByLeader(leaderGuid);
2731 if(!group)
2733 sLog.outErrorDb("Incorrect entry in group_member table : no group with leader %d for member %d!", fields[3].GetUInt32(), fields[0].GetUInt32());
2734 CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", fields[0].GetUInt32());
2735 continue;
2739 if(!group->LoadMemberFromDB(fields[0].GetUInt32(), fields[2].GetUInt8(), fields[1].GetBool()))
2741 sLog.outErrorDb("Incorrect entry in group_member table : member %d cannot be added to player %d's group!", fields[0].GetUInt32(), fields[3].GetUInt32());
2742 CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", fields[0].GetUInt32());
2744 }while( result->NextRow() );
2745 delete result;
2748 // clean groups
2749 // TODO: maybe delete from the DB before loading in this case
2750 for(GroupSet::iterator itr = mGroupSet.begin(); itr != mGroupSet.end();)
2752 if((*itr)->GetMembersCount() < 2)
2754 (*itr)->Disband();
2755 delete *itr;
2756 mGroupSet.erase(itr++);
2758 else
2759 ++itr;
2762 // -- loading instances --
2763 count = 0;
2764 group = NULL;
2765 leaderGuid = 0;
2766 result = CharacterDatabase.Query(
2767 // 0 1 2 3 4 5
2768 "SELECT leaderGuid, map, instance, permanent, difficulty, resettime, "
2769 // 6
2770 "(SELECT COUNT(*) FROM character_instance WHERE guid = leaderGuid AND instance = group_instance.instance AND permanent = 1 LIMIT 1) "
2771 "FROM group_instance LEFT JOIN instance ON instance = id ORDER BY leaderGuid"
2774 if(!result)
2776 barGoLink bar2( 1 );
2777 bar2.step();
2779 else
2781 barGoLink bar2( result->GetRowCount() );
2784 bar2.step();
2785 Field *fields = result->Fetch();
2786 count++;
2787 leaderGuid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
2788 if(!group || group->GetLeaderGUID() != leaderGuid)
2790 group = GetGroupByLeader(leaderGuid);
2791 if(!group)
2793 sLog.outErrorDb("Incorrect entry in group_instance table : no group with leader %d", fields[0].GetUInt32());
2794 continue;
2798 MapEntry const* mapEntry = sMapStore.LookupEntry(fields[1].GetUInt32());
2799 if(!mapEntry || !mapEntry->IsDungeon())
2801 sLog.outErrorDb("Incorrect entry in group_instance table : no dungeon map %d", fields[1].GetUInt32());
2802 continue;
2805 InstanceSave *save = sInstanceSaveManager.AddInstanceSave(mapEntry->MapID, fields[2].GetUInt32(), fields[4].GetUInt8(), (time_t)fields[5].GetUInt64(), (fields[6].GetUInt32() == 0), true);
2806 group->BindToInstance(save, fields[3].GetBool(), true);
2807 }while( result->NextRow() );
2808 delete result;
2811 sLog.outString();
2812 sLog.outString( ">> Loaded %u group-instance binds total", count );
2814 sLog.outString();
2815 sLog.outString( ">> Loaded %u group members total", count );
2818 void ObjectMgr::LoadQuests()
2820 // For reload case
2821 for(QuestMap::const_iterator itr=mQuestTemplates.begin(); itr != mQuestTemplates.end(); ++itr)
2822 delete itr->second;
2823 mQuestTemplates.clear();
2825 mExclusiveQuestGroups.clear();
2827 // 0 1 2 3 4 5 6 7 8
2828 QueryResult *result = WorldDatabase.Query("SELECT entry, Method, ZoneOrSort, SkillOrClass, MinLevel, QuestLevel, Type, RequiredRaces, RequiredSkillValue,"
2829 // 9 10 11 12 13 14 15 16
2830 "RepObjectiveFaction, RepObjectiveValue, RequiredMinRepFaction, RequiredMinRepValue, RequiredMaxRepFaction, RequiredMaxRepValue, SuggestedPlayers, LimitTime,"
2831 // 17 18 19 20 21 22 23 24 25 26 27 28
2832 "QuestFlags, SpecialFlags, CharTitleId, PlayersSlain, BonusTalents, PrevQuestId, NextQuestId, ExclusiveGroup, NextQuestInChain, SrcItemId, SrcItemCount, SrcSpell,"
2833 // 29 30 31 32 33 34 35 36 37 38
2834 "Title, Details, Objectives, OfferRewardText, RequestItemsText, EndText, ObjectiveText1, ObjectiveText2, ObjectiveText3, ObjectiveText4,"
2835 // 39 40 41 42 43 44 45 46
2836 "ReqItemId1, ReqItemId2, ReqItemId3, ReqItemId4, ReqItemCount1, ReqItemCount2, ReqItemCount3, ReqItemCount4,"
2837 // 47 48 49 50 51 52 53 54
2838 "ReqSourceId1, ReqSourceId2, ReqSourceId3, ReqSourceId4, ReqSourceCount1, ReqSourceCount2, ReqSourceCount3, ReqSourceCount4,"
2839 // 55 56 57 58 59 60 61 62
2840 "ReqCreatureOrGOId1, ReqCreatureOrGOId2, ReqCreatureOrGOId3, ReqCreatureOrGOId4, ReqCreatureOrGOCount1, ReqCreatureOrGOCount2, ReqCreatureOrGOCount3, ReqCreatureOrGOCount4,"
2841 // 63 64 65 66
2842 "ReqSpellCast1, ReqSpellCast2, ReqSpellCast3, ReqSpellCast4,"
2843 // 67 68 69 70 71 72
2844 "RewChoiceItemId1, RewChoiceItemId2, RewChoiceItemId3, RewChoiceItemId4, RewChoiceItemId5, RewChoiceItemId6,"
2845 // 73 74 75 76 77 78
2846 "RewChoiceItemCount1, RewChoiceItemCount2, RewChoiceItemCount3, RewChoiceItemCount4, RewChoiceItemCount5, RewChoiceItemCount6,"
2847 // 79 80 81 82 83 84 85 86
2848 "RewItemId1, RewItemId2, RewItemId3, RewItemId4, RewItemCount1, RewItemCount2, RewItemCount3, RewItemCount4,"
2849 // 87 88 89 90 91 92 93 94 95 96
2850 "RewRepFaction1, RewRepFaction2, RewRepFaction3, RewRepFaction4, RewRepFaction5, RewRepValue1, RewRepValue2, RewRepValue3, RewRepValue4, RewRepValue5,"
2851 // 97 98 99 100 101 102 103 104 105 106 107
2852 "RewHonorableKills, RewOrReqMoney, RewMoneyMaxLevel, RewSpell, RewSpellCast, RewMailTemplateId, RewMailDelaySecs, PointMapId, PointX, PointY, PointOpt,"
2853 // 108 109 110 111 112 113 114 115 116 117
2854 "DetailsEmote1, DetailsEmote2, DetailsEmote3, DetailsEmote4, IncompleteEmote, CompleteEmote, OfferRewardEmote1, OfferRewardEmote2, OfferRewardEmote3, OfferRewardEmote4,"
2855 // 118 119
2856 "StartScript, CompleteScript"
2857 " FROM quest_template");
2858 if(result == NULL)
2860 barGoLink bar( 1 );
2861 bar.step();
2863 sLog.outString();
2864 sLog.outString( ">> Loaded 0 quests definitions" );
2865 sLog.outErrorDb("`quest_template` table is empty!");
2866 return;
2869 // create multimap previous quest for each existed quest
2870 // some quests can have many previous maps set by NextQuestId in previous quest
2871 // for example set of race quests can lead to single not race specific quest
2872 barGoLink bar( result->GetRowCount() );
2875 bar.step();
2876 Field *fields = result->Fetch();
2878 Quest * newQuest = new Quest(fields);
2879 mQuestTemplates[newQuest->GetQuestId()] = newQuest;
2880 } while( result->NextRow() );
2882 delete result;
2884 // Post processing
2885 for (QuestMap::iterator iter = mQuestTemplates.begin(); iter != mQuestTemplates.end(); ++iter)
2887 Quest * qinfo = iter->second;
2889 // additional quest integrity checks (GO, creature_template and item_template must be loaded already)
2891 if( qinfo->GetQuestMethod() >= 3 )
2893 sLog.outErrorDb("Quest %u has `Method` = %u, expected values are 0, 1 or 2.",qinfo->GetQuestId(),qinfo->GetQuestMethod());
2896 if (qinfo->QuestFlags & ~QUEST_MANGOS_FLAGS_DB_ALLOWED)
2898 sLog.outErrorDb("Quest %u has `SpecialFlags` = %u > max allowed value. Correct `SpecialFlags` to value <= %u",
2899 qinfo->GetQuestId(),qinfo->QuestFlags,QUEST_MANGOS_FLAGS_DB_ALLOWED >> 16);
2900 qinfo->QuestFlags &= QUEST_MANGOS_FLAGS_DB_ALLOWED;
2903 if(qinfo->QuestFlags & QUEST_FLAGS_DAILY)
2905 if(!(qinfo->QuestFlags & QUEST_MANGOS_FLAGS_REPEATABLE))
2907 sLog.outErrorDb("Daily Quest %u not marked as repeatable in `SpecialFlags`, added.",qinfo->GetQuestId());
2908 qinfo->QuestFlags |= QUEST_MANGOS_FLAGS_REPEATABLE;
2912 if(qinfo->QuestFlags & QUEST_FLAGS_AUTO_REWARDED)
2914 // at auto-reward can be rewarded only RewChoiceItemId[0]
2915 for(int j = 1; j < QUEST_REWARD_CHOICES_COUNT; ++j )
2917 if(uint32 id = qinfo->RewChoiceItemId[j])
2919 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item from `RewChoiceItemId%d` can't be rewarded with quest flag QUEST_FLAGS_AUTO_REWARDED.",
2920 qinfo->GetQuestId(),j+1,id,j+1);
2921 // no changes, quest ignore this data
2926 // client quest log visual (area case)
2927 if( qinfo->ZoneOrSort > 0 )
2929 if(!GetAreaEntryByAreaID(qinfo->ZoneOrSort))
2931 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %u (zone case) but zone with this id does not exist.",
2932 qinfo->GetQuestId(),qinfo->ZoneOrSort);
2933 // no changes, quest not dependent from this value but can have problems at client
2936 // client quest log visual (sort case)
2937 if( qinfo->ZoneOrSort < 0 )
2939 QuestSortEntry const* qSort = sQuestSortStore.LookupEntry(-int32(qinfo->ZoneOrSort));
2940 if( !qSort )
2942 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (sort case) but quest sort with this id does not exist.",
2943 qinfo->GetQuestId(),qinfo->ZoneOrSort);
2944 // 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)
2946 //check SkillOrClass value (class case).
2947 if( ClassByQuestSort(-int32(qinfo->ZoneOrSort)) )
2949 // SkillOrClass should not have class case when class case already set in ZoneOrSort.
2950 if(qinfo->SkillOrClass < 0)
2952 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (class sort case) and `SkillOrClass` = %i (class case), redundant.",
2953 qinfo->GetQuestId(),qinfo->ZoneOrSort,qinfo->SkillOrClass);
2956 //check for proper SkillOrClass value (skill case)
2957 if(int32 skill_id = SkillByQuestSort(-int32(qinfo->ZoneOrSort)))
2959 // skill is positive value in SkillOrClass
2960 if(qinfo->SkillOrClass != skill_id )
2962 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (skill sort case) but `SkillOrClass` does not have a corresponding value (%i).",
2963 qinfo->GetQuestId(),qinfo->ZoneOrSort,skill_id);
2964 //override, and force proper value here?
2969 // SkillOrClass (class case)
2970 if( qinfo->SkillOrClass < 0 )
2972 if( !sChrClassesStore.LookupEntry(-int32(qinfo->SkillOrClass)) )
2974 sLog.outErrorDb("Quest %u has `SkillOrClass` = %i (class case) but class (%i) does not exist",
2975 qinfo->GetQuestId(),qinfo->SkillOrClass,-qinfo->SkillOrClass);
2978 // SkillOrClass (skill case)
2979 if( qinfo->SkillOrClass > 0 )
2981 if( !sSkillLineStore.LookupEntry(qinfo->SkillOrClass) )
2983 sLog.outErrorDb("Quest %u has `SkillOrClass` = %u (skill case) but skill (%i) does not exist",
2984 qinfo->GetQuestId(),qinfo->SkillOrClass,qinfo->SkillOrClass);
2988 if( qinfo->RequiredSkillValue )
2990 if( qinfo->RequiredSkillValue > sWorld.GetConfigMaxSkillValue() )
2992 sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but max possible skill is %u, quest can't be done.",
2993 qinfo->GetQuestId(),qinfo->RequiredSkillValue,sWorld.GetConfigMaxSkillValue());
2994 // no changes, quest can't be done for this requirement
2997 if( qinfo->SkillOrClass <= 0 )
2999 sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but `SkillOrClass` = %i (class case), value ignored.",
3000 qinfo->GetQuestId(),qinfo->RequiredSkillValue,qinfo->SkillOrClass);
3001 // no changes, quest can't be done for this requirement (fail at wrong skill id)
3004 // else Skill quests can have 0 skill level, this is ok
3006 if(qinfo->RepObjectiveFaction && !sFactionStore.LookupEntry(qinfo->RepObjectiveFaction))
3008 sLog.outErrorDb("Quest %u has `RepObjectiveFaction` = %u but faction template %u does not exist, quest can't be done.",
3009 qinfo->GetQuestId(),qinfo->RepObjectiveFaction,qinfo->RepObjectiveFaction);
3010 // no changes, quest can't be done for this requirement
3013 if(qinfo->RequiredMinRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMinRepFaction))
3015 sLog.outErrorDb("Quest %u has `RequiredMinRepFaction` = %u but faction template %u does not exist, quest can't be done.",
3016 qinfo->GetQuestId(),qinfo->RequiredMinRepFaction,qinfo->RequiredMinRepFaction);
3017 // no changes, quest can't be done for this requirement
3020 if(qinfo->RequiredMaxRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMaxRepFaction))
3022 sLog.outErrorDb("Quest %u has `RequiredMaxRepFaction` = %u but faction template %u does not exist, quest can't be done.",
3023 qinfo->GetQuestId(),qinfo->RequiredMaxRepFaction,qinfo->RequiredMaxRepFaction);
3024 // no changes, quest can't be done for this requirement
3027 if(qinfo->RequiredMinRepValue && qinfo->RequiredMinRepValue > ReputationMgr::Reputation_Cap)
3029 sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but max reputation is %u, quest can't be done.",
3030 qinfo->GetQuestId(),qinfo->RequiredMinRepValue,ReputationMgr::Reputation_Cap);
3031 // no changes, quest can't be done for this requirement
3034 if(qinfo->RequiredMinRepValue && qinfo->RequiredMaxRepValue && qinfo->RequiredMaxRepValue <= qinfo->RequiredMinRepValue)
3036 sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d and `RequiredMinRepValue` = %d, quest can't be done.",
3037 qinfo->GetQuestId(),qinfo->RequiredMaxRepValue,qinfo->RequiredMinRepValue);
3038 // no changes, quest can't be done for this requirement
3041 if(!qinfo->RepObjectiveFaction && qinfo->RepObjectiveValue > 0 )
3043 sLog.outErrorDb("Quest %u has `RepObjectiveValue` = %d but `RepObjectiveFaction` is 0, value has no effect",
3044 qinfo->GetQuestId(),qinfo->RepObjectiveValue);
3045 // warning
3048 if(!qinfo->RequiredMinRepFaction && qinfo->RequiredMinRepValue > 0 )
3050 sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but `RequiredMinRepFaction` is 0, value has no effect",
3051 qinfo->GetQuestId(),qinfo->RequiredMinRepValue);
3052 // warning
3055 if(!qinfo->RequiredMaxRepFaction && qinfo->RequiredMaxRepValue > 0 )
3057 sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d but `RequiredMaxRepFaction` is 0, value has no effect",
3058 qinfo->GetQuestId(),qinfo->RequiredMaxRepValue);
3059 // warning
3062 if(qinfo->CharTitleId && !sCharTitlesStore.LookupEntry(qinfo->CharTitleId))
3064 sLog.outErrorDb("Quest %u has `CharTitleId` = %u but CharTitle Id %u does not exist, quest can't be rewarded with title.",
3065 qinfo->GetQuestId(),qinfo->GetCharTitleId(),qinfo->GetCharTitleId());
3066 qinfo->CharTitleId = 0;
3067 // quest can't reward this title
3070 if(qinfo->SrcItemId)
3072 if(!sItemStorage.LookupEntry<ItemPrototype>(qinfo->SrcItemId))
3074 sLog.outErrorDb("Quest %u has `SrcItemId` = %u but item with entry %u does not exist, quest can't be done.",
3075 qinfo->GetQuestId(),qinfo->SrcItemId,qinfo->SrcItemId);
3076 qinfo->SrcItemId = 0; // quest can't be done for this requirement
3078 else if(qinfo->SrcItemCount==0)
3080 sLog.outErrorDb("Quest %u has `SrcItemId` = %u but `SrcItemCount` = 0, set to 1 but need fix in DB.",
3081 qinfo->GetQuestId(),qinfo->SrcItemId);
3082 qinfo->SrcItemCount = 1; // update to 1 for allow quest work for backward compatibility with DB
3085 else if(qinfo->SrcItemCount>0)
3087 sLog.outErrorDb("Quest %u has `SrcItemId` = 0 but `SrcItemCount` = %u, useless value.",
3088 qinfo->GetQuestId(),qinfo->SrcItemCount);
3089 qinfo->SrcItemCount=0; // no quest work changes in fact
3092 if(qinfo->SrcSpell)
3094 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->SrcSpell);
3095 if(!spellInfo)
3097 sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u doesn't exist, quest can't be done.",
3098 qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
3099 qinfo->SrcSpell = 0; // quest can't be done for this requirement
3101 else if(!SpellMgr::IsSpellValid(spellInfo))
3103 sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u is broken, quest can't be done.",
3104 qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
3105 qinfo->SrcSpell = 0; // quest can't be done for this requirement
3109 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3111 uint32 id = qinfo->ReqItemId[j];
3112 if(id)
3114 if(qinfo->ReqItemCount[j]==0)
3116 sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but `ReqItemCount%d` = 0, quest can't be done.",
3117 qinfo->GetQuestId(),j+1,id,j+1);
3118 // no changes, quest can't be done for this requirement
3121 qinfo->SetFlag(QUEST_MANGOS_FLAGS_DELIVER);
3123 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3125 sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but item with entry %u does not exist, quest can't be done.",
3126 qinfo->GetQuestId(),j+1,id,id);
3127 qinfo->ReqItemCount[j] = 0; // prevent incorrect work of quest
3130 else if(qinfo->ReqItemCount[j]>0)
3132 sLog.outErrorDb("Quest %u has `ReqItemId%d` = 0 but `ReqItemCount%d` = %u, quest can't be done.",
3133 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqItemCount[j]);
3134 qinfo->ReqItemCount[j] = 0; // prevent incorrect work of quest
3138 for(int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j )
3140 uint32 id = qinfo->ReqSourceId[j];
3141 if(id)
3143 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3145 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but item with entry %u does not exist, quest can't be done.",
3146 qinfo->GetQuestId(),j+1,id,id);
3147 // no changes, quest can't be done for this requirement
3150 else
3152 if(qinfo->ReqSourceCount[j]>0)
3154 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = 0 but `ReqSourceCount%d` = %u.",
3155 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqSourceCount[j]);
3156 // no changes, quest ignore this data
3161 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3163 uint32 id = qinfo->ReqSpell[j];
3164 if(id)
3166 SpellEntry const* spellInfo = sSpellStore.LookupEntry(id);
3167 if(!spellInfo)
3169 sLog.outErrorDb("Quest %u has `ReqSpellCast%d` = %u but spell %u does not exist, quest can't be done.",
3170 qinfo->GetQuestId(),j+1,id,id);
3171 continue;
3174 if(!qinfo->ReqCreatureOrGOId[j])
3176 bool found = false;
3177 for(int k = 0; k < 3; ++k)
3179 if( spellInfo->Effect[k]==SPELL_EFFECT_QUEST_COMPLETE && uint32(spellInfo->EffectMiscValue[k])==qinfo->QuestId ||
3180 spellInfo->Effect[k]==SPELL_EFFECT_SEND_EVENT)
3182 found = true;
3183 break;
3187 if(found)
3189 if(!qinfo->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3191 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);
3193 // this will prevent quest completing without objective
3194 const_cast<Quest*>(qinfo)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3197 else
3199 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.",
3200 qinfo->GetQuestId(),j+1,id,j+1,id);
3201 // no changes, quest can't be done for this requirement
3207 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3209 int32 id = qinfo->ReqCreatureOrGOId[j];
3210 if(id < 0 && !sGOStorage.LookupEntry<GameObjectInfo>(-id))
3212 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but gameobject %u does not exist, quest can't be done.",
3213 qinfo->GetQuestId(),j+1,id,uint32(-id));
3214 qinfo->ReqCreatureOrGOId[j] = 0; // quest can't be done for this requirement
3217 if(id > 0 && !sCreatureStorage.LookupEntry<CreatureInfo>(id))
3219 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but creature with entry %u does not exist, quest can't be done.",
3220 qinfo->GetQuestId(),j+1,id,uint32(id));
3221 qinfo->ReqCreatureOrGOId[j] = 0; // quest can't be done for this requirement
3224 if(id)
3226 // In fact SpeakTo and Kill are quite same: either you can speak to mob:SpeakTo or you can't:Kill/Cast
3228 qinfo->SetFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO);
3230 if(!qinfo->ReqCreatureOrGOCount[j])
3232 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %u but `ReqCreatureOrGOCount%d` = 0, quest can't be done.",
3233 qinfo->GetQuestId(),j+1,id,j+1);
3234 // no changes, quest can be incorrectly done, but we already report this
3237 else if(qinfo->ReqCreatureOrGOCount[j]>0)
3239 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = 0 but `ReqCreatureOrGOCount%d` = %u.",
3240 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqCreatureOrGOCount[j]);
3241 // no changes, quest ignore this data
3245 for(int j = 0; j < QUEST_REWARD_CHOICES_COUNT; ++j )
3247 uint32 id = qinfo->RewChoiceItemId[j];
3248 if(id)
3250 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3252 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3253 qinfo->GetQuestId(),j+1,id,id);
3254 qinfo->RewChoiceItemId[j] = 0; // no changes, quest will not reward this
3257 if(!qinfo->RewChoiceItemCount[j])
3259 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but `RewChoiceItemCount%d` = 0, quest can't be done.",
3260 qinfo->GetQuestId(),j+1,id,j+1);
3261 // no changes, quest can't be done
3264 else if(qinfo->RewChoiceItemCount[j]>0)
3266 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = 0 but `RewChoiceItemCount%d` = %u.",
3267 qinfo->GetQuestId(),j+1,j+1,qinfo->RewChoiceItemCount[j]);
3268 // no changes, quest ignore this data
3272 for(int j = 0; j < QUEST_REWARDS_COUNT; ++j )
3274 uint32 id = qinfo->RewItemId[j];
3275 if(id)
3277 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3279 sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3280 qinfo->GetQuestId(),j+1,id,id);
3281 qinfo->RewItemId[j] = 0; // no changes, quest will not reward this item
3284 if(!qinfo->RewItemCount[j])
3286 sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but `RewItemCount%d` = 0, quest will not reward this item.",
3287 qinfo->GetQuestId(),j+1,id,j+1);
3288 // no changes
3291 else if(qinfo->RewItemCount[j]>0)
3293 sLog.outErrorDb("Quest %u has `RewItemId%d` = 0 but `RewItemCount%d` = %u.",
3294 qinfo->GetQuestId(),j+1,j+1,qinfo->RewItemCount[j]);
3295 // no changes, quest ignore this data
3299 for(int j = 0; j < QUEST_REPUTATIONS_COUNT; ++j)
3301 if(qinfo->RewRepFaction[j])
3303 if(!qinfo->RewRepValue[j])
3305 sLog.outErrorDb("Quest %u has `RewRepFaction%d` = %u but `RewRepValue%d` = 0, quest will not reward this reputation.",
3306 qinfo->GetQuestId(),j+1,qinfo->RewRepValue[j],j+1);
3307 // no changes
3310 if(!sFactionStore.LookupEntry(qinfo->RewRepFaction[j]))
3312 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.",
3313 qinfo->GetQuestId(),j+1,qinfo->RewRepFaction[j] ,qinfo->RewRepFaction[j] );
3314 qinfo->RewRepFaction[j] = 0; // quest will not reward this
3317 else if(qinfo->RewRepValue[j]!=0)
3319 sLog.outErrorDb("Quest %u has `RewRepFaction%d` = 0 but `RewRepValue%d` = %u.",
3320 qinfo->GetQuestId(),j+1,j+1,qinfo->RewRepValue[j]);
3321 // no changes, quest ignore this data
3325 if(qinfo->RewSpell)
3327 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpell);
3329 if(!spellInfo)
3331 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u does not exist, spell removed as display reward.",
3332 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3333 qinfo->RewSpell = 0; // no spell reward will display for this quest
3336 else if(!SpellMgr::IsSpellValid(spellInfo))
3338 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u is broken, quest can't be done.",
3339 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3340 qinfo->RewSpell = 0; // no spell reward will display for this quest
3345 if(qinfo->RewSpellCast)
3347 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpellCast);
3349 if(!spellInfo)
3351 sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u does not exist, quest will not have a spell reward.",
3352 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3353 qinfo->RewSpellCast = 0; // no spell will be casted on player
3356 else if(!SpellMgr::IsSpellValid(spellInfo))
3358 sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u is broken, quest can't be done.",
3359 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3360 qinfo->RewSpellCast = 0; // no spell will be casted on player
3365 if(qinfo->RewMailTemplateId)
3367 if(!sMailTemplateStore.LookupEntry(qinfo->RewMailTemplateId))
3369 sLog.outErrorDb("Quest %u has `RewMailTemplateId` = %u but mail template %u does not exist, quest will not have a mail reward.",
3370 qinfo->GetQuestId(),qinfo->RewMailTemplateId,qinfo->RewMailTemplateId);
3371 qinfo->RewMailTemplateId = 0; // no mail will send to player
3372 qinfo->RewMailDelaySecs = 0; // no mail will send to player
3376 if(qinfo->NextQuestInChain)
3378 QuestMap::iterator qNextItr = mQuestTemplates.find(qinfo->NextQuestInChain);
3379 if(qNextItr == mQuestTemplates.end())
3381 sLog.outErrorDb("Quest %u has `NextQuestInChain` = %u but quest %u does not exist, quest chain will not work.",
3382 qinfo->GetQuestId(),qinfo->NextQuestInChain ,qinfo->NextQuestInChain );
3383 qinfo->NextQuestInChain = 0;
3385 else
3386 qNextItr->second->prevChainQuests.push_back(qinfo->GetQuestId());
3389 // fill additional data stores
3390 if(qinfo->PrevQuestId)
3392 if (mQuestTemplates.find(abs(qinfo->GetPrevQuestId())) == mQuestTemplates.end())
3394 sLog.outErrorDb("Quest %d has PrevQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetPrevQuestId());
3396 else
3398 qinfo->prevQuests.push_back(qinfo->PrevQuestId);
3402 if(qinfo->NextQuestId)
3404 QuestMap::iterator qNextItr = mQuestTemplates.find(abs(qinfo->GetNextQuestId()));
3405 if (qNextItr == mQuestTemplates.end())
3407 sLog.outErrorDb("Quest %d has NextQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetNextQuestId());
3409 else
3411 int32 signedQuestId = qinfo->NextQuestId < 0 ? -int32(qinfo->GetQuestId()) : int32(qinfo->GetQuestId());
3412 qNextItr->second->prevQuests.push_back(signedQuestId);
3416 if(qinfo->ExclusiveGroup)
3417 mExclusiveQuestGroups.insert(std::pair<int32, uint32>(qinfo->ExclusiveGroup, qinfo->GetQuestId()));
3418 if(qinfo->LimitTime)
3419 qinfo->SetFlag(QUEST_MANGOS_FLAGS_TIMED);
3422 // check QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT for spell with SPELL_EFFECT_QUEST_COMPLETE
3423 for (uint32 i = 0; i < sSpellStore.GetNumRows(); ++i)
3425 SpellEntry const *spellInfo = sSpellStore.LookupEntry(i);
3426 if(!spellInfo)
3427 continue;
3429 for(int j = 0; j < 3; ++j)
3431 if(spellInfo->Effect[j] != SPELL_EFFECT_QUEST_COMPLETE)
3432 continue;
3434 uint32 quest_id = spellInfo->EffectMiscValue[j];
3436 Quest const* quest = GetQuestTemplate(quest_id);
3438 // some quest referenced in spells not exist (outdated spells)
3439 if(!quest)
3440 continue;
3442 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3444 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);
3446 // this will prevent quest completing without objective
3447 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3452 sLog.outString();
3453 sLog.outString( ">> Loaded %lu quests definitions", (unsigned long)mQuestTemplates.size() );
3456 void ObjectMgr::LoadQuestLocales()
3458 mQuestLocaleMap.clear(); // need for reload case
3460 QueryResult *result = WorldDatabase.Query("SELECT entry,"
3461 "Title_loc1,Details_loc1,Objectives_loc1,OfferRewardText_loc1,RequestItemsText_loc1,EndText_loc1,ObjectiveText1_loc1,ObjectiveText2_loc1,ObjectiveText3_loc1,ObjectiveText4_loc1,"
3462 "Title_loc2,Details_loc2,Objectives_loc2,OfferRewardText_loc2,RequestItemsText_loc2,EndText_loc2,ObjectiveText1_loc2,ObjectiveText2_loc2,ObjectiveText3_loc2,ObjectiveText4_loc2,"
3463 "Title_loc3,Details_loc3,Objectives_loc3,OfferRewardText_loc3,RequestItemsText_loc3,EndText_loc3,ObjectiveText1_loc3,ObjectiveText2_loc3,ObjectiveText3_loc3,ObjectiveText4_loc3,"
3464 "Title_loc4,Details_loc4,Objectives_loc4,OfferRewardText_loc4,RequestItemsText_loc4,EndText_loc4,ObjectiveText1_loc4,ObjectiveText2_loc4,ObjectiveText3_loc4,ObjectiveText4_loc4,"
3465 "Title_loc5,Details_loc5,Objectives_loc5,OfferRewardText_loc5,RequestItemsText_loc5,EndText_loc5,ObjectiveText1_loc5,ObjectiveText2_loc5,ObjectiveText3_loc5,ObjectiveText4_loc5,"
3466 "Title_loc6,Details_loc6,Objectives_loc6,OfferRewardText_loc6,RequestItemsText_loc6,EndText_loc6,ObjectiveText1_loc6,ObjectiveText2_loc6,ObjectiveText3_loc6,ObjectiveText4_loc6,"
3467 "Title_loc7,Details_loc7,Objectives_loc7,OfferRewardText_loc7,RequestItemsText_loc7,EndText_loc7,ObjectiveText1_loc7,ObjectiveText2_loc7,ObjectiveText3_loc7,ObjectiveText4_loc7,"
3468 "Title_loc8,Details_loc8,Objectives_loc8,OfferRewardText_loc8,RequestItemsText_loc8,EndText_loc8,ObjectiveText1_loc8,ObjectiveText2_loc8,ObjectiveText3_loc8,ObjectiveText4_loc8"
3469 " FROM locales_quest"
3472 if(!result)
3474 barGoLink bar(1);
3476 bar.step();
3478 sLog.outString();
3479 sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_quest` is empty.");
3480 return;
3483 barGoLink bar(result->GetRowCount());
3487 Field *fields = result->Fetch();
3488 bar.step();
3490 uint32 entry = fields[0].GetUInt32();
3492 QuestLocale& data = mQuestLocaleMap[entry];
3494 for(int i = 1; i < MAX_LOCALE; ++i)
3496 std::string str = fields[1+10*(i-1)].GetCppString();
3497 if(!str.empty())
3499 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3500 if(idx >= 0)
3502 if(data.Title.size() <= idx)
3503 data.Title.resize(idx+1);
3505 data.Title[idx] = str;
3508 str = fields[1+10*(i-1)+1].GetCppString();
3509 if(!str.empty())
3511 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3512 if(idx >= 0)
3514 if(data.Details.size() <= idx)
3515 data.Details.resize(idx+1);
3517 data.Details[idx] = str;
3520 str = fields[1+10*(i-1)+2].GetCppString();
3521 if(!str.empty())
3523 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3524 if(idx >= 0)
3526 if(data.Objectives.size() <= idx)
3527 data.Objectives.resize(idx+1);
3529 data.Objectives[idx] = str;
3532 str = fields[1+10*(i-1)+3].GetCppString();
3533 if(!str.empty())
3535 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3536 if(idx >= 0)
3538 if(data.OfferRewardText.size() <= idx)
3539 data.OfferRewardText.resize(idx+1);
3541 data.OfferRewardText[idx] = str;
3544 str = fields[1+10*(i-1)+4].GetCppString();
3545 if(!str.empty())
3547 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3548 if(idx >= 0)
3550 if(data.RequestItemsText.size() <= idx)
3551 data.RequestItemsText.resize(idx+1);
3553 data.RequestItemsText[idx] = str;
3556 str = fields[1+10*(i-1)+5].GetCppString();
3557 if(!str.empty())
3559 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3560 if(idx >= 0)
3562 if(data.EndText.size() <= idx)
3563 data.EndText.resize(idx+1);
3565 data.EndText[idx] = str;
3568 for(int k = 0; k < 4; ++k)
3570 str = fields[1+10*(i-1)+6+k].GetCppString();
3571 if(!str.empty())
3573 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3574 if(idx >= 0)
3576 if(data.ObjectiveText[k].size() <= idx)
3577 data.ObjectiveText[k].resize(idx+1);
3579 data.ObjectiveText[k][idx] = str;
3584 } while (result->NextRow());
3586 delete result;
3588 sLog.outString();
3589 sLog.outString( ">> Loaded %lu Quest locale strings", (unsigned long)mQuestLocaleMap.size() );
3592 void ObjectMgr::LoadScripts(ScriptMapMap& scripts, char const* tablename)
3594 if(sWorld.IsScriptScheduled()) // function don't must be called in time scripts use.
3595 return;
3597 sLog.outString( "%s :", tablename);
3599 scripts.clear(); // need for reload support
3601 QueryResult *result = WorldDatabase.PQuery( "SELECT id,delay,command,datalong,datalong2,dataint, x, y, z, o FROM %s", tablename );
3603 uint32 count = 0;
3605 if( !result )
3607 barGoLink bar( 1 );
3608 bar.step();
3610 sLog.outString();
3611 sLog.outString( ">> Loaded %u script definitions", count );
3612 return;
3615 barGoLink bar( result->GetRowCount() );
3619 bar.step();
3621 Field *fields = result->Fetch();
3622 ScriptInfo tmp;
3623 tmp.id = fields[0].GetUInt32();
3624 tmp.delay = fields[1].GetUInt32();
3625 tmp.command = fields[2].GetUInt32();
3626 tmp.datalong = fields[3].GetUInt32();
3627 tmp.datalong2 = fields[4].GetUInt32();
3628 tmp.dataint = fields[5].GetInt32();
3629 tmp.x = fields[6].GetFloat();
3630 tmp.y = fields[7].GetFloat();
3631 tmp.z = fields[8].GetFloat();
3632 tmp.o = fields[9].GetFloat();
3634 // generic command args check
3635 switch(tmp.command)
3637 case SCRIPT_COMMAND_TALK:
3639 if(tmp.datalong > 3)
3641 sLog.outErrorDb("Table `%s` has invalid talk type (datalong = %u) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.datalong,tmp.id);
3642 continue;
3644 if(tmp.dataint==0)
3646 sLog.outErrorDb("Table `%s` has invalid talk text id (dataint = %i) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.dataint,tmp.id);
3647 continue;
3649 if(tmp.dataint < MIN_DB_SCRIPT_STRING_ID || tmp.dataint >= MAX_DB_SCRIPT_STRING_ID)
3651 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);
3652 continue;
3655 // if(!objmgr.GetMangosStringLocale(tmp.dataint)) will checked after db_script_string loading
3656 break;
3659 case SCRIPT_COMMAND_EMOTE:
3661 if(!sEmotesStore.LookupEntry(tmp.datalong))
3663 sLog.outErrorDb("Table `%s` has invalid emote id (datalong = %u) in SCRIPT_COMMAND_EMOTE for script id %u",tablename,tmp.datalong,tmp.id);
3664 continue;
3666 break;
3669 case SCRIPT_COMMAND_TELEPORT_TO:
3671 if(!sMapStore.LookupEntry(tmp.datalong))
3673 sLog.outErrorDb("Table `%s` has invalid map (Id: %u) in SCRIPT_COMMAND_TELEPORT_TO for script id %u",tablename,tmp.datalong,tmp.id);
3674 continue;
3677 if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
3679 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);
3680 continue;
3682 break;
3685 case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
3687 if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
3689 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);
3690 continue;
3693 if(!GetCreatureTemplate(tmp.datalong))
3695 sLog.outErrorDb("Table `%s` has invalid creature (Entry: %u) in SCRIPT_COMMAND_TEMP_SUMMON_CREATURE for script id %u",tablename,tmp.datalong,tmp.id);
3696 continue;
3698 break;
3701 case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
3703 GameObjectData const* data = GetGOData(tmp.datalong);
3704 if(!data)
3706 sLog.outErrorDb("Table `%s` has invalid gameobject (GUID: %u) in SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,tmp.datalong,tmp.id);
3707 continue;
3710 GameObjectInfo const* info = GetGameObjectInfo(data->id);
3711 if(!info)
3713 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);
3714 continue;
3717 if( info->type==GAMEOBJECT_TYPE_FISHINGNODE ||
3718 info->type==GAMEOBJECT_TYPE_FISHINGHOLE ||
3719 info->type==GAMEOBJECT_TYPE_DOOR ||
3720 info->type==GAMEOBJECT_TYPE_BUTTON ||
3721 info->type==GAMEOBJECT_TYPE_TRAP )
3723 sLog.outErrorDb("Table `%s` have gameobject type (%u) unsupported by command SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,info->id,tmp.id);
3724 continue;
3726 break;
3728 case SCRIPT_COMMAND_OPEN_DOOR:
3729 case SCRIPT_COMMAND_CLOSE_DOOR:
3731 GameObjectData const* data = GetGOData(tmp.datalong);
3732 if(!data)
3734 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);
3735 continue;
3738 GameObjectInfo const* info = GetGameObjectInfo(data->id);
3739 if(!info)
3741 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);
3742 continue;
3745 if( info->type!=GAMEOBJECT_TYPE_DOOR)
3747 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);
3748 continue;
3751 break;
3753 case SCRIPT_COMMAND_QUEST_EXPLORED:
3755 Quest const* quest = GetQuestTemplate(tmp.datalong);
3756 if(!quest)
3758 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);
3759 continue;
3762 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3764 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);
3766 // this will prevent quest completing without objective
3767 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3769 // continue; - quest objective requirement set and command can be allowed
3772 if(float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
3774 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",
3775 tablename,tmp.datalong2,tmp.id);
3776 continue;
3779 if(tmp.datalong2 && float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
3781 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",
3782 tablename,tmp.datalong2,tmp.id,DEFAULT_VISIBILITY_DISTANCE);
3783 continue;
3786 if(tmp.datalong2 && float(tmp.datalong2) < INTERACTION_DISTANCE)
3788 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",
3789 tablename,tmp.datalong2,tmp.id,INTERACTION_DISTANCE);
3790 continue;
3793 break;
3796 case SCRIPT_COMMAND_REMOVE_AURA:
3798 if(!sSpellStore.LookupEntry(tmp.datalong))
3800 sLog.outErrorDb("Table `%s` using non-existent spell (id: %u) in SCRIPT_COMMAND_REMOVE_AURA or SCRIPT_COMMAND_CAST_SPELL for script id %u",
3801 tablename,tmp.datalong,tmp.id);
3802 continue;
3804 if(tmp.datalong2 & ~0x1) // 1 bits (0,1)
3806 sLog.outErrorDb("Table `%s` using unknown flags in datalong2 (%u)i n SCRIPT_COMMAND_CAST_SPELL for script id %u",
3807 tablename,tmp.datalong2,tmp.id);
3808 continue;
3810 break;
3812 case SCRIPT_COMMAND_CAST_SPELL:
3814 if(!sSpellStore.LookupEntry(tmp.datalong))
3816 sLog.outErrorDb("Table `%s` using non-existent spell (id: %u) in SCRIPT_COMMAND_REMOVE_AURA or SCRIPT_COMMAND_CAST_SPELL for script id %u",
3817 tablename,tmp.datalong,tmp.id);
3818 continue;
3820 if(tmp.datalong2 & ~0x3) // 2 bits
3822 sLog.outErrorDb("Table `%s` using unknown flags in datalong2 (%u)i n SCRIPT_COMMAND_CAST_SPELL for script id %u",
3823 tablename,tmp.datalong2,tmp.id);
3824 continue;
3826 break;
3830 if (scripts.find(tmp.id) == scripts.end())
3832 ScriptMap emptyMap;
3833 scripts[tmp.id] = emptyMap;
3835 scripts[tmp.id].insert(std::pair<uint32, ScriptInfo>(tmp.delay, tmp));
3837 ++count;
3838 } while( result->NextRow() );
3840 delete result;
3842 sLog.outString();
3843 sLog.outString( ">> Loaded %u script definitions", count );
3846 void ObjectMgr::LoadGameObjectScripts()
3848 LoadScripts(sGameObjectScripts, "gameobject_scripts");
3850 // check ids
3851 for(ScriptMapMap::const_iterator itr = sGameObjectScripts.begin(); itr != sGameObjectScripts.end(); ++itr)
3853 if(!GetGOData(itr->first))
3854 sLog.outErrorDb("Table `gameobject_scripts` has not existing gameobject (GUID: %u) as script id",itr->first);
3858 void ObjectMgr::LoadQuestEndScripts()
3860 LoadScripts(sQuestEndScripts, "quest_end_scripts");
3862 // check ids
3863 for(ScriptMapMap::const_iterator itr = sQuestEndScripts.begin(); itr != sQuestEndScripts.end(); ++itr)
3865 if(!GetQuestTemplate(itr->first))
3866 sLog.outErrorDb("Table `quest_end_scripts` has not existing quest (Id: %u) as script id",itr->first);
3870 void ObjectMgr::LoadQuestStartScripts()
3872 LoadScripts(sQuestStartScripts,"quest_start_scripts");
3874 // check ids
3875 for(ScriptMapMap::const_iterator itr = sQuestStartScripts.begin(); itr != sQuestStartScripts.end(); ++itr)
3877 if(!GetQuestTemplate(itr->first))
3878 sLog.outErrorDb("Table `quest_start_scripts` has not existing quest (Id: %u) as script id",itr->first);
3882 void ObjectMgr::LoadSpellScripts()
3884 LoadScripts(sSpellScripts, "spell_scripts");
3886 // check ids
3887 for(ScriptMapMap::const_iterator itr = sSpellScripts.begin(); itr != sSpellScripts.end(); ++itr)
3889 SpellEntry const* spellInfo = sSpellStore.LookupEntry(itr->first);
3891 if(!spellInfo)
3893 sLog.outErrorDb("Table `spell_scripts` has not existing spell (Id: %u) as script id",itr->first);
3894 continue;
3897 //check for correct spellEffect
3898 bool found = false;
3899 for(int i=0; i<3; ++i)
3901 // skip empty effects
3902 if( !spellInfo->Effect[i] )
3903 continue;
3905 if( spellInfo->Effect[i] == SPELL_EFFECT_SCRIPT_EFFECT )
3907 found = true;
3908 break;
3912 if(!found)
3913 sLog.outErrorDb("Table `spell_scripts` has unsupported spell (Id: %u) without SPELL_EFFECT_SCRIPT_EFFECT (%u) spell effect",itr->first,SPELL_EFFECT_SCRIPT_EFFECT);
3917 void ObjectMgr::LoadEventScripts()
3919 LoadScripts(sEventScripts, "event_scripts");
3921 std::set<uint32> evt_scripts;
3922 // Load all possible script entries from gameobjects
3923 for(uint32 i = 1; i < sGOStorage.MaxEntry; ++i)
3925 GameObjectInfo const * goInfo = sGOStorage.LookupEntry<GameObjectInfo>(i);
3926 if (goInfo)
3928 switch(goInfo->type)
3930 case GAMEOBJECT_TYPE_GOOBER:
3931 if(goInfo->goober.eventId)
3932 evt_scripts.insert(goInfo->goober.eventId);
3933 break;
3934 case GAMEOBJECT_TYPE_CHEST:
3935 if(goInfo->chest.eventId)
3936 evt_scripts.insert(goInfo->chest.eventId);
3937 break;
3938 default:
3939 break;
3943 // Load all possible script entries from spells
3944 for(uint32 i = 1; i < sSpellStore.GetNumRows(); ++i)
3946 SpellEntry const * spell = sSpellStore.LookupEntry(i);
3947 if (spell)
3949 for(int j=0; j<3; ++j)
3951 if( spell->Effect[j] == SPELL_EFFECT_SEND_EVENT )
3953 if (spell->EffectMiscValue[j])
3954 evt_scripts.insert(spell->EffectMiscValue[j]);
3959 // Then check if all scripts are in above list of possible script entries
3960 for(ScriptMapMap::const_iterator itr = sEventScripts.begin(); itr != sEventScripts.end(); ++itr)
3962 std::set<uint32>::const_iterator itr2 = evt_scripts.find(itr->first);
3963 if (itr2 == evt_scripts.end())
3964 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);
3968 void ObjectMgr::LoadItemTexts()
3970 QueryResult *result = CharacterDatabase.Query("SELECT id, text FROM item_text");
3972 uint32 count = 0;
3974 if( !result )
3976 barGoLink bar( 1 );
3977 bar.step();
3979 sLog.outString();
3980 sLog.outString( ">> Loaded %u item pages", count );
3981 return;
3984 barGoLink bar( result->GetRowCount() );
3986 Field* fields;
3989 bar.step();
3991 fields = result->Fetch();
3993 mItemTexts[ fields[0].GetUInt32() ] = fields[1].GetCppString();
3995 ++count;
3997 } while ( result->NextRow() );
3999 delete result;
4001 sLog.outString();
4002 sLog.outString( ">> Loaded %u item texts", count );
4005 void ObjectMgr::LoadPageTexts()
4007 sPageTextStore.Free(); // for reload case
4009 sPageTextStore.Load();
4010 sLog.outString( ">> Loaded %u page texts", sPageTextStore.RecordCount );
4011 sLog.outString();
4013 for(uint32 i = 1; i < sPageTextStore.MaxEntry; ++i)
4015 // check data correctness
4016 PageText const* page = sPageTextStore.LookupEntry<PageText>(i);
4017 if(!page)
4018 continue;
4020 if(page->Next_Page && !sPageTextStore.LookupEntry<PageText>(page->Next_Page))
4022 sLog.outErrorDb("Page text (Id: %u) has not existing next page (Id:%u)", i,page->Next_Page);
4023 continue;
4026 // detect circular reference
4027 std::set<uint32> checkedPages;
4028 for(PageText const* pageItr = page; pageItr; pageItr = sPageTextStore.LookupEntry<PageText>(pageItr->Next_Page))
4030 if(!pageItr->Next_Page)
4031 break;
4032 checkedPages.insert(pageItr->Page_ID);
4033 if(checkedPages.find(pageItr->Next_Page)!=checkedPages.end())
4035 std::ostringstream ss;
4036 ss<< "The text page(s) ";
4037 for (std::set<uint32>::iterator itr= checkedPages.begin();itr!=checkedPages.end(); ++itr)
4038 ss << *itr << " ";
4039 ss << "create(s) a circular reference, which can cause the server to freeze. Changing Next_Page of page "
4040 << pageItr->Page_ID <<" to 0";
4041 sLog.outErrorDb(ss.str().c_str());
4042 const_cast<PageText*>(pageItr)->Next_Page = 0;
4043 break;
4049 void ObjectMgr::LoadPageTextLocales()
4051 mPageTextLocaleMap.clear(); // need for reload case
4053 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");
4055 if(!result)
4057 barGoLink bar(1);
4059 bar.step();
4061 sLog.outString();
4062 sLog.outString(">> Loaded 0 PageText locale strings. DB table `locales_page_text` is empty.");
4063 return;
4066 barGoLink bar(result->GetRowCount());
4070 Field *fields = result->Fetch();
4071 bar.step();
4073 uint32 entry = fields[0].GetUInt32();
4075 PageTextLocale& data = mPageTextLocaleMap[entry];
4077 for(int i = 1; i < MAX_LOCALE; ++i)
4079 std::string str = fields[i].GetCppString();
4080 if(str.empty())
4081 continue;
4083 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4084 if(idx >= 0)
4086 if(data.Text.size() <= idx)
4087 data.Text.resize(idx+1);
4089 data.Text[idx] = str;
4093 } while (result->NextRow());
4095 delete result;
4097 sLog.outString();
4098 sLog.outString( ">> Loaded %lu PageText locale strings", (unsigned long)mPageTextLocaleMap.size() );
4101 struct SQLInstanceLoader : public SQLStorageLoaderBase<SQLInstanceLoader>
4103 template<class D>
4104 void convert_from_str(uint32 /*field_pos*/, char *src, D &dst)
4106 dst = D(objmgr.GetScriptId(src));
4110 void ObjectMgr::LoadInstanceTemplate()
4112 SQLInstanceLoader loader;
4113 loader.Load(sInstanceTemplate);
4115 for(uint32 i = 0; i < sInstanceTemplate.MaxEntry; i++)
4117 InstanceTemplate* temp = (InstanceTemplate*)GetInstanceTemplate(i);
4118 if(!temp) continue;
4119 const MapEntry* entry = sMapStore.LookupEntry(temp->map);
4120 if(!entry)
4122 sLog.outErrorDb("ObjectMgr::LoadInstanceTemplate: bad mapid %d for template!", temp->map);
4123 continue;
4125 else if(!entry->HasResetTime())
4126 continue;
4128 //FIXME: now exist heroic instance, normal/heroic raid instances
4129 // entry->resetTimeHeroic store reset time for both heroic mode instance (raid and non-raid)
4130 // entry->resetTimeRaid store reset time for normal raid only
4131 // for current state entry->resetTimeRaid == entry->resetTimeHeroic in case raid instances with heroic mode.
4132 // but at some point wee need implement reset time dependent from raid instance mode
4133 if(temp->reset_delay == 0)
4135 // use defaults from the DBC
4136 if(entry->resetTimeHeroic) // for both raid and non raids, read above
4138 temp->reset_delay = entry->resetTimeHeroic / DAY;
4140 else if (entry->resetTimeRaid && entry->map_type == MAP_RAID)
4141 // for normal raid only
4143 temp->reset_delay = entry->resetTimeRaid / DAY;
4147 // the reset_delay must be at least one day
4148 temp->reset_delay = std::max((uint32)1, (uint32)(temp->reset_delay * sWorld.getRate(RATE_INSTANCE_RESET_TIME)));
4151 sLog.outString( ">> Loaded %u Instance Template definitions", sInstanceTemplate.RecordCount );
4152 sLog.outString();
4155 GossipText const *ObjectMgr::GetGossipText(uint32 Text_ID) const
4157 GossipTextMap::const_iterator itr = mGossipText.find(Text_ID);
4158 if(itr != mGossipText.end())
4159 return &itr->second;
4160 return NULL;
4163 void ObjectMgr::LoadGossipText()
4165 QueryResult *result = WorldDatabase.Query( "SELECT * FROM npc_text" );
4167 int count = 0;
4168 if( !result )
4170 barGoLink bar( 1 );
4171 bar.step();
4173 sLog.outString();
4174 sLog.outString( ">> Loaded %u npc texts", count );
4175 return;
4178 int cic;
4180 barGoLink bar( result->GetRowCount() );
4184 ++count;
4185 cic = 0;
4187 Field *fields = result->Fetch();
4189 bar.step();
4191 uint32 Text_ID = fields[cic++].GetUInt32();
4192 if(!Text_ID)
4194 sLog.outErrorDb("Table `npc_text` has record wit reserved id 0, ignore.");
4195 continue;
4198 GossipText& gText = mGossipText[Text_ID];
4200 for (int i=0; i< 8; i++)
4202 gText.Options[i].Text_0 = fields[cic++].GetCppString();
4203 gText.Options[i].Text_1 = fields[cic++].GetCppString();
4205 gText.Options[i].Language = fields[cic++].GetUInt32();
4206 gText.Options[i].Probability = fields[cic++].GetFloat();
4208 for(int j=0; j < 3; ++j)
4210 gText.Options[i].Emotes[j]._Delay = fields[cic++].GetUInt32();
4211 gText.Options[i].Emotes[j]._Emote = fields[cic++].GetUInt32();
4214 } while( result->NextRow() );
4216 sLog.outString();
4217 sLog.outString( ">> Loaded %u npc texts", count );
4218 delete result;
4221 void ObjectMgr::LoadNpcTextLocales()
4223 mNpcTextLocaleMap.clear(); // need for reload case
4225 QueryResult *result = WorldDatabase.Query("SELECT entry,"
4226 "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,"
4227 "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,"
4228 "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,"
4229 "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,"
4230 "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,"
4231 "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,"
4232 "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, "
4233 "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 "
4234 " FROM locales_npc_text");
4236 if(!result)
4238 barGoLink bar(1);
4240 bar.step();
4242 sLog.outString();
4243 sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_npc_text` is empty.");
4244 return;
4247 barGoLink bar(result->GetRowCount());
4251 Field *fields = result->Fetch();
4252 bar.step();
4254 uint32 entry = fields[0].GetUInt32();
4256 NpcTextLocale& data = mNpcTextLocaleMap[entry];
4258 for(int i=1; i<MAX_LOCALE; ++i)
4260 for(int j=0; j<8; ++j)
4262 std::string str0 = fields[1+8*2*(i-1)+2*j].GetCppString();
4263 if(!str0.empty())
4265 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4266 if(idx >= 0)
4268 if(data.Text_0[j].size() <= idx)
4269 data.Text_0[j].resize(idx+1);
4271 data.Text_0[j][idx] = str0;
4274 std::string str1 = fields[1+8*2*(i-1)+2*j+1].GetCppString();
4275 if(!str1.empty())
4277 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4278 if(idx >= 0)
4280 if(data.Text_1[j].size() <= idx)
4281 data.Text_1[j].resize(idx+1);
4283 data.Text_1[j][idx] = str1;
4288 } while (result->NextRow());
4290 delete result;
4292 sLog.outString();
4293 sLog.outString( ">> Loaded %lu NpcText locale strings", (unsigned long)mNpcTextLocaleMap.size() );
4296 //not very fast function but it is called only once a day, or on starting-up
4297 void ObjectMgr::ReturnOrDeleteOldMails(bool serverUp)
4299 time_t basetime = time(NULL);
4300 sLog.outDebug("Returning mails current time: hour: %d, minute: %d, second: %d ", localtime(&basetime)->tm_hour, localtime(&basetime)->tm_min, localtime(&basetime)->tm_sec);
4301 //delete all old mails without item and without body immediately, if starting server
4302 if (!serverUp)
4303 CharacterDatabase.PExecute("DELETE FROM mail WHERE expire_time < '" I64FMTD "' AND has_items = '0' AND itemTextId = 0", (uint64)basetime);
4304 // 0 1 2 3 4 5 6 7 8 9
4305 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);
4306 if ( !result )
4308 barGoLink bar(1);
4309 bar.step();
4310 sLog.outString();
4311 sLog.outString(">> Only expired mails (need to be return or delete) or DB table `mail` is empty.");
4312 return; // any mails need to be returned or deleted
4315 //std::ostringstream delitems, delmails; //will be here for optimization
4316 //bool deletemail = false, deleteitem = false;
4317 //delitems << "DELETE FROM item_instance WHERE guid IN ( ";
4318 //delmails << "DELETE FROM mail WHERE id IN ( "
4320 barGoLink bar( result->GetRowCount() );
4321 uint32 count = 0;
4322 Field *fields;
4326 bar.step();
4328 fields = result->Fetch();
4329 Mail *m = new Mail;
4330 m->messageID = fields[0].GetUInt32();
4331 m->messageType = fields[1].GetUInt8();
4332 m->sender = fields[2].GetUInt32();
4333 m->receiver = fields[3].GetUInt32();
4334 m->itemTextId = fields[4].GetUInt32();
4335 bool has_items = fields[5].GetBool();
4336 m->expire_time = (time_t)fields[6].GetUInt64();
4337 m->deliver_time = 0;
4338 m->COD = fields[7].GetUInt32();
4339 m->checked = fields[8].GetUInt32();
4340 m->mailTemplateId = fields[9].GetInt16();
4342 Player *pl = 0;
4343 if (serverUp)
4344 pl = GetPlayer((uint64)m->receiver);
4345 if (pl && pl->m_mailsLoaded)
4346 { //this code will run very improbably (the time is between 4 and 5 am, in game is online a player, who has old mail
4347 //his in mailbox and he has already listed his mails )
4348 delete m;
4349 continue;
4351 //delete or return mail:
4352 if (has_items)
4354 QueryResult *resultItems = CharacterDatabase.PQuery("SELECT item_guid,item_template FROM mail_items WHERE mail_id='%u'", m->messageID);
4355 if(resultItems)
4359 Field *fields2 = resultItems->Fetch();
4361 uint32 item_guid_low = fields2[0].GetUInt32();
4362 uint32 item_template = fields2[1].GetUInt32();
4364 m->AddItem(item_guid_low, item_template);
4366 while (resultItems->NextRow());
4368 delete resultItems;
4370 //if it is mail from AH, it shouldn't be returned, but deleted
4371 if (m->messageType != MAIL_NORMAL || (m->checked & (MAIL_CHECK_MASK_AUCTION | MAIL_CHECK_MASK_COD_PAYMENT | MAIL_CHECK_MASK_RETURNED)))
4373 // mail open and then not returned
4374 for(std::vector<MailItemInfo>::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
4375 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
4377 else
4379 //mail will be returned:
4380 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);
4381 delete m;
4382 continue;
4386 if (m->itemTextId)
4387 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
4389 //deletemail = true;
4390 //delmails << m->messageID << ", ";
4391 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
4392 delete m;
4393 ++count;
4394 } while (result->NextRow());
4395 delete result;
4397 sLog.outString();
4398 sLog.outString( ">> Loaded %u mails", count );
4401 void ObjectMgr::LoadQuestAreaTriggers()
4403 mQuestAreaTriggerMap.clear(); // need for reload case
4405 QueryResult *result = WorldDatabase.Query( "SELECT id,quest FROM areatrigger_involvedrelation" );
4407 uint32 count = 0;
4409 if( !result )
4411 barGoLink bar( 1 );
4412 bar.step();
4414 sLog.outString();
4415 sLog.outString( ">> Loaded %u quest trigger points", count );
4416 return;
4419 barGoLink bar( result->GetRowCount() );
4423 ++count;
4424 bar.step();
4426 Field *fields = result->Fetch();
4428 uint32 trigger_ID = fields[0].GetUInt32();
4429 uint32 quest_ID = fields[1].GetUInt32();
4431 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(trigger_ID);
4432 if(!atEntry)
4434 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",trigger_ID);
4435 continue;
4438 Quest const* quest = GetQuestTemplate(quest_ID);
4440 if(!quest)
4442 sLog.outErrorDb("Table `areatrigger_involvedrelation` has record (id: %u) for not existing quest %u",trigger_ID,quest_ID);
4443 continue;
4446 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
4448 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);
4450 // this will prevent quest completing without objective
4451 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
4453 // continue; - quest modified to required objective and trigger can be allowed.
4456 mQuestAreaTriggerMap[trigger_ID] = quest_ID;
4458 } while( result->NextRow() );
4460 delete result;
4462 sLog.outString();
4463 sLog.outString( ">> Loaded %u quest trigger points", count );
4466 void ObjectMgr::LoadTavernAreaTriggers()
4468 mTavernAreaTriggerSet.clear(); // need for reload case
4470 QueryResult *result = WorldDatabase.Query("SELECT id FROM areatrigger_tavern");
4472 uint32 count = 0;
4474 if( !result )
4476 barGoLink bar( 1 );
4477 bar.step();
4479 sLog.outString();
4480 sLog.outString( ">> Loaded %u tavern triggers", count );
4481 return;
4484 barGoLink bar( result->GetRowCount() );
4488 ++count;
4489 bar.step();
4491 Field *fields = result->Fetch();
4493 uint32 Trigger_ID = fields[0].GetUInt32();
4495 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4496 if(!atEntry)
4498 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4499 continue;
4502 mTavernAreaTriggerSet.insert(Trigger_ID);
4503 } while( result->NextRow() );
4505 delete result;
4507 sLog.outString();
4508 sLog.outString( ">> Loaded %u tavern triggers", count );
4511 void ObjectMgr::LoadAreaTriggerScripts()
4513 mAreaTriggerScripts.clear(); // need for reload case
4514 QueryResult *result = WorldDatabase.Query("SELECT entry, ScriptName FROM areatrigger_scripts");
4516 uint32 count = 0;
4518 if( !result )
4520 barGoLink bar( 1 );
4521 bar.step();
4523 sLog.outString();
4524 sLog.outString( ">> Loaded %u areatrigger scripts", count );
4525 return;
4528 barGoLink bar( result->GetRowCount() );
4532 ++count;
4533 bar.step();
4535 Field *fields = result->Fetch();
4537 uint32 Trigger_ID = fields[0].GetUInt32();
4538 const char *scriptName = fields[1].GetString();
4540 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4541 if(!atEntry)
4543 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4544 continue;
4546 mAreaTriggerScripts[Trigger_ID] = GetScriptId(scriptName);
4547 } while( result->NextRow() );
4549 delete result;
4551 sLog.outString();
4552 sLog.outString( ">> Loaded %u areatrigger scripts", count );
4555 uint32 ObjectMgr::GetNearestTaxiNode( float x, float y, float z, uint32 mapid, uint32 team )
4557 bool found = false;
4558 float dist;
4559 uint32 id = 0;
4561 for(uint32 i = 1; i < sTaxiNodesStore.GetNumRows(); ++i)
4563 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(i);
4564 if(!node || node->map_id != mapid || !node->MountCreatureID[team == ALLIANCE ? 1 : 0])
4565 continue;
4567 uint8 field = (uint8)((i - 1) / 32);
4568 uint32 submask = 1<<((i-1)%32);
4570 // skip not taxi network nodes
4571 if((sTaxiNodesMask[field] & submask)==0)
4572 continue;
4574 float dist2 = (node->x - x)*(node->x - x)+(node->y - y)*(node->y - y)+(node->z - z)*(node->z - z);
4575 if(found)
4577 if(dist2 < dist)
4579 dist = dist2;
4580 id = i;
4583 else
4585 found = true;
4586 dist = dist2;
4587 id = i;
4591 return id;
4594 void ObjectMgr::GetTaxiPath( uint32 source, uint32 destination, uint32 &path, uint32 &cost)
4596 TaxiPathSetBySource::iterator src_i = sTaxiPathSetBySource.find(source);
4597 if(src_i==sTaxiPathSetBySource.end())
4599 path = 0;
4600 cost = 0;
4601 return;
4604 TaxiPathSetForSource& pathSet = src_i->second;
4606 TaxiPathSetForSource::iterator dest_i = pathSet.find(destination);
4607 if(dest_i==pathSet.end())
4609 path = 0;
4610 cost = 0;
4611 return;
4614 cost = dest_i->second.price;
4615 path = dest_i->second.ID;
4618 uint16 ObjectMgr::GetTaxiMount( uint32 id, uint32 team, bool allowed_alt_team /* = false */)
4620 uint16 mount_entry = 0;
4621 uint16 mount_id = 0;
4623 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(id);
4624 if(node)
4626 if (team == ALLIANCE)
4628 mount_entry = node->MountCreatureID[1];
4629 if(!mount_entry && allowed_alt_team)
4630 mount_entry = node->MountCreatureID[0];
4632 CreatureInfo const *ci = GetCreatureTemplate(mount_entry);
4633 if(ci)
4634 mount_id = ci->DisplayID_A;
4636 if (team == HORDE)
4638 mount_entry = node->MountCreatureID[0];
4640 if(!mount_entry && allowed_alt_team)
4641 mount_entry = node->MountCreatureID[1];
4643 CreatureInfo const *ci = GetCreatureTemplate(mount_entry);
4644 if(ci)
4645 mount_id = ci->DisplayID_H;
4649 CreatureModelInfo const *minfo = GetCreatureModelInfo(mount_id);
4650 if(!minfo)
4652 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. ",
4653 mount_entry,id,team,mount_id);
4655 return false;
4657 if(minfo->modelid_other_gender!=0)
4658 mount_id = urand(0,1) ? mount_id : minfo->modelid_other_gender;
4660 return mount_id;
4663 void ObjectMgr::GetTaxiPathNodes( uint32 path, Path &pathnodes, std::vector<uint32>& mapIds)
4665 if(path >= sTaxiPathNodesByPath.size())
4666 return;
4668 TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
4670 pathnodes.Resize(nodeList.size());
4671 mapIds.resize(nodeList.size());
4673 for(size_t i = 0; i < nodeList.size(); ++i)
4675 pathnodes[ i ].x = nodeList[i].x;
4676 pathnodes[ i ].y = nodeList[i].y;
4677 pathnodes[ i ].z = nodeList[i].z;
4679 mapIds[i] = nodeList[i].mapid;
4683 void ObjectMgr::GetTransportPathNodes( uint32 path, TransportPath &pathnodes )
4685 if(path >= sTaxiPathNodesByPath.size())
4686 return;
4688 TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
4690 pathnodes.Resize(nodeList.size());
4692 for(size_t i = 0; i < nodeList.size(); ++i)
4694 pathnodes[ i ].mapid = nodeList[i].mapid;
4695 pathnodes[ i ].x = nodeList[i].x;
4696 pathnodes[ i ].y = nodeList[i].y;
4697 pathnodes[ i ].z = nodeList[i].z;
4698 pathnodes[ i ].actionFlag = nodeList[i].actionFlag;
4699 pathnodes[ i ].delay = nodeList[i].delay;
4703 void ObjectMgr::LoadGraveyardZones()
4705 mGraveYardMap.clear(); // need for reload case
4707 QueryResult *result = WorldDatabase.Query("SELECT id,ghost_zone,faction FROM game_graveyard_zone");
4709 uint32 count = 0;
4711 if( !result )
4713 barGoLink bar( 1 );
4714 bar.step();
4716 sLog.outString();
4717 sLog.outString( ">> Loaded %u graveyard-zone links", count );
4718 return;
4721 barGoLink bar( result->GetRowCount() );
4725 ++count;
4726 bar.step();
4728 Field *fields = result->Fetch();
4730 uint32 safeLocId = fields[0].GetUInt32();
4731 uint32 zoneId = fields[1].GetUInt32();
4732 uint32 team = fields[2].GetUInt32();
4734 WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(safeLocId);
4735 if(!entry)
4737 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",safeLocId);
4738 continue;
4741 AreaTableEntry const *areaEntry = GetAreaEntryByAreaID(zoneId);
4742 if(!areaEntry)
4744 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing zone id (%u), skipped.",zoneId);
4745 continue;
4748 if(areaEntry->zone != 0)
4750 sLog.outErrorDb("Table `game_graveyard_zone` has record subzone id (%u) instead of zone, skipped.",zoneId);
4751 continue;
4754 if(team!=0 && team!=HORDE && team!=ALLIANCE)
4756 sLog.outErrorDb("Table `game_graveyard_zone` has record for non player faction (%u), skipped.",team);
4757 continue;
4760 if(!AddGraveYardLink(safeLocId,zoneId,team,false))
4761 sLog.outErrorDb("Table `game_graveyard_zone` has a duplicate record for Graveyard (ID: %u) and Zone (ID: %u), skipped.",safeLocId,zoneId);
4762 } while( result->NextRow() );
4764 delete result;
4766 sLog.outString();
4767 sLog.outString( ">> Loaded %u graveyard-zone links", count );
4770 WorldSafeLocsEntry const *ObjectMgr::GetClosestGraveYard(float x, float y, float z, uint32 MapId, uint32 team)
4772 // search for zone associated closest graveyard
4773 uint32 zoneId = MapManager::Instance().GetZoneId(MapId,x,y,z);
4775 // Simulate std. algorithm:
4776 // found some graveyard associated to (ghost_zone,ghost_map)
4778 // if mapId == graveyard.mapId (ghost in plain zone or city or battleground) and search graveyard at same map
4779 // then check faction
4780 // if mapId != graveyard.mapId (ghost in instance) and search any graveyard associated
4781 // then check faction
4782 GraveYardMap::const_iterator graveLow = mGraveYardMap.lower_bound(zoneId);
4783 GraveYardMap::const_iterator graveUp = mGraveYardMap.upper_bound(zoneId);
4784 if(graveLow==graveUp)
4786 sLog.outErrorDb("Table `game_graveyard_zone` incomplete: Zone %u Team %u does not have a linked graveyard.",zoneId,team);
4787 return NULL;
4790 // at corpse map
4791 bool foundNear = false;
4792 float distNear;
4793 WorldSafeLocsEntry const* entryNear = NULL;
4795 // at entrance map for corpse map
4796 bool foundEntr = false;
4797 float distEntr;
4798 WorldSafeLocsEntry const* entryEntr = NULL;
4800 // some where other
4801 WorldSafeLocsEntry const* entryFar = NULL;
4803 MapEntry const* mapEntry = sMapStore.LookupEntry(MapId);
4805 for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
4807 GraveYardData const& data = itr->second;
4809 WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(data.safeLocId);
4810 if(!entry)
4812 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",data.safeLocId);
4813 continue;
4816 // skip enemy faction graveyard
4817 // team == 0 case can be at call from .neargrave
4818 if(data.team != 0 && team != 0 && data.team != team)
4819 continue;
4821 // find now nearest graveyard at other map
4822 if(MapId != entry->map_id)
4824 // if find graveyard at different map from where entrance placed (or no entrance data), use any first
4825 if (!mapEntry ||
4826 mapEntry->entrance_map < 0 ||
4827 mapEntry->entrance_map != entry->map_id ||
4828 (mapEntry->entrance_x == 0 && mapEntry->entrance_y == 0))
4830 // not have any corrdinates for check distance anyway
4831 entryFar = entry;
4832 continue;
4835 // at entrance map calculate distance (2D);
4836 float dist2 = (entry->x - mapEntry->entrance_x)*(entry->x - mapEntry->entrance_x)
4837 +(entry->y - mapEntry->entrance_y)*(entry->y - mapEntry->entrance_y);
4838 if(foundEntr)
4840 if(dist2 < distEntr)
4842 distEntr = dist2;
4843 entryEntr = entry;
4846 else
4848 foundEntr = true;
4849 distEntr = dist2;
4850 entryEntr = entry;
4853 // find now nearest graveyard at same map
4854 else
4856 float dist2 = (entry->x - x)*(entry->x - x)+(entry->y - y)*(entry->y - y)+(entry->z - z)*(entry->z - z);
4857 if(foundNear)
4859 if(dist2 < distNear)
4861 distNear = dist2;
4862 entryNear = entry;
4865 else
4867 foundNear = true;
4868 distNear = dist2;
4869 entryNear = entry;
4874 if(entryNear)
4875 return entryNear;
4877 if(entryEntr)
4878 return entryEntr;
4880 return entryFar;
4883 GraveYardData const* ObjectMgr::FindGraveYardData(uint32 id, uint32 zoneId)
4885 GraveYardMap::const_iterator graveLow = mGraveYardMap.lower_bound(zoneId);
4886 GraveYardMap::const_iterator graveUp = mGraveYardMap.upper_bound(zoneId);
4888 for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
4890 if(itr->second.safeLocId==id)
4891 return &itr->second;
4894 return NULL;
4897 bool ObjectMgr::AddGraveYardLink(uint32 id, uint32 zoneId, uint32 team, bool inDB)
4899 if(FindGraveYardData(id,zoneId))
4900 return false;
4902 // add link to loaded data
4903 GraveYardData data;
4904 data.safeLocId = id;
4905 data.team = team;
4907 mGraveYardMap.insert(GraveYardMap::value_type(zoneId,data));
4909 // add link to DB
4910 if(inDB)
4912 WorldDatabase.PExecuteLog("INSERT INTO game_graveyard_zone ( id,ghost_zone,faction) "
4913 "VALUES ('%u', '%u','%u')",id,zoneId,team);
4916 return true;
4919 void ObjectMgr::LoadAreaTriggerTeleports()
4921 mAreaTriggers.clear(); // need for reload case
4923 uint32 count = 0;
4925 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13
4926 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");
4927 if( !result )
4930 barGoLink bar( 1 );
4932 bar.step();
4934 sLog.outString();
4935 sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
4936 return;
4939 barGoLink bar( result->GetRowCount() );
4943 Field *fields = result->Fetch();
4945 bar.step();
4947 ++count;
4949 uint32 Trigger_ID = fields[0].GetUInt32();
4951 AreaTrigger at;
4953 at.requiredLevel = fields[1].GetUInt8();
4954 at.requiredItem = fields[2].GetUInt32();
4955 at.requiredItem2 = fields[3].GetUInt32();
4956 at.heroicKey = fields[4].GetUInt32();
4957 at.heroicKey2 = fields[5].GetUInt32();
4958 at.requiredQuest = fields[6].GetUInt32();
4959 at.requiredQuestHeroic = fields[7].GetUInt32();
4960 at.requiredFailedText = fields[8].GetCppString();
4961 at.target_mapId = fields[9].GetUInt32();
4962 at.target_X = fields[10].GetFloat();
4963 at.target_Y = fields[11].GetFloat();
4964 at.target_Z = fields[12].GetFloat();
4965 at.target_Orientation = fields[13].GetFloat();
4967 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4968 if(!atEntry)
4970 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4971 continue;
4974 if(at.requiredItem)
4976 ItemPrototype const *pProto = GetItemPrototype(at.requiredItem);
4977 if(!pProto)
4979 sLog.outError("Key item %u does not exist for trigger %u, removing key requirement.", at.requiredItem, Trigger_ID);
4980 at.requiredItem = 0;
4983 if(at.requiredItem2)
4985 ItemPrototype const *pProto = GetItemPrototype(at.requiredItem2);
4986 if(!pProto)
4988 sLog.outError("Second item %u not exist for trigger %u, remove key requirement.", at.requiredItem2, Trigger_ID);
4989 at.requiredItem2 = 0;
4993 if(at.heroicKey)
4995 ItemPrototype const *pProto = GetItemPrototype(at.heroicKey);
4996 if(!pProto)
4998 sLog.outError("Heroic key item %u not exist for trigger %u, remove key requirement.", at.heroicKey, Trigger_ID);
4999 at.heroicKey = 0;
5003 if(at.heroicKey2)
5005 ItemPrototype const *pProto = GetItemPrototype(at.heroicKey2);
5006 if(!pProto)
5008 sLog.outError("Heroic second key item %u not exist for trigger %u, remove key requirement.", at.heroicKey2, Trigger_ID);
5009 at.heroicKey2 = 0;
5013 if(at.requiredQuest)
5015 QuestMap::iterator qReqItr = mQuestTemplates.find(at.requiredQuest);
5016 if(qReqItr == mQuestTemplates.end())
5018 sLog.outErrorDb("Required Quest %u not exist for trigger %u, remove quest done requirement.",at.requiredQuest,Trigger_ID);
5019 at.requiredQuest = 0;
5023 if(at.requiredQuestHeroic)
5025 QuestMap::iterator qReqItr = mQuestTemplates.find(at.requiredQuestHeroic);
5026 if(qReqItr == mQuestTemplates.end())
5028 sLog.outErrorDb("Required Quest %u not exist for trigger %u, remove quest done requirement.",at.requiredQuestHeroic,Trigger_ID);
5029 at.requiredQuestHeroic = 0;
5033 MapEntry const* mapEntry = sMapStore.LookupEntry(at.target_mapId);
5034 if(!mapEntry)
5036 sLog.outErrorDb("Area trigger (ID:%u) target map (ID: %u) does not exist in `Map.dbc`.",Trigger_ID,at.target_mapId);
5037 continue;
5040 if(at.target_X==0 && at.target_Y==0 && at.target_Z==0)
5042 sLog.outErrorDb("Area trigger (ID:%u) target coordinates not provided.",Trigger_ID);
5043 continue;
5046 mAreaTriggers[Trigger_ID] = at;
5048 } while( result->NextRow() );
5050 delete result;
5052 sLog.outString();
5053 sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
5057 * Searches for the areatrigger which teleports players out of the given map
5059 AreaTrigger const* ObjectMgr::GetGoBackTrigger(uint32 Map) const
5061 const MapEntry *mapEntry = sMapStore.LookupEntry(Map);
5062 if(!mapEntry) return NULL;
5063 for (AreaTriggerMap::const_iterator itr = mAreaTriggers.begin(); itr != mAreaTriggers.end(); ++itr)
5065 if(itr->second.target_mapId == mapEntry->entrance_map)
5067 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(itr->first);
5068 if(atEntry && atEntry->mapid == Map)
5069 return &itr->second;
5072 return NULL;
5076 * Searches for the areatrigger which teleports players to the given map
5078 AreaTrigger const* ObjectMgr::GetMapEntranceTrigger(uint32 Map) const
5080 for (AreaTriggerMap::const_iterator itr = mAreaTriggers.begin(); itr != mAreaTriggers.end(); ++itr)
5082 if(itr->second.target_mapId == Map)
5084 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(itr->first);
5085 if(atEntry)
5086 return &itr->second;
5089 return NULL;
5092 void ObjectMgr::SetHighestGuids()
5094 QueryResult *result = CharacterDatabase.Query( "SELECT MAX(guid) FROM characters" );
5095 if( result )
5097 m_hiCharGuid = (*result)[0].GetUInt32()+1;
5098 delete result;
5101 result = WorldDatabase.Query( "SELECT MAX(guid) FROM creature" );
5102 if( result )
5104 m_hiCreatureGuid = (*result)[0].GetUInt32()+1;
5105 delete result;
5108 result = CharacterDatabase.Query( "SELECT MAX(guid) FROM item_instance" );
5109 if( result )
5111 m_hiItemGuid = (*result)[0].GetUInt32()+1;
5112 delete result;
5115 // Cleanup other tables from not existed guids (>=m_hiItemGuid)
5116 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item >= '%u'", m_hiItemGuid);
5117 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid >= '%u'", m_hiItemGuid);
5118 CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE itemguid >= '%u'", m_hiItemGuid);
5119 CharacterDatabase.PExecute("DELETE FROM guild_bank_item WHERE item_guid >= '%u'", m_hiItemGuid);
5121 result = WorldDatabase.Query("SELECT MAX(guid) FROM gameobject" );
5122 if( result )
5124 m_hiGoGuid = (*result)[0].GetUInt32()+1;
5125 delete result;
5128 result = CharacterDatabase.Query("SELECT MAX(id) FROM auctionhouse" );
5129 if( result )
5131 m_auctionid = (*result)[0].GetUInt32()+1;
5132 delete result;
5135 result = CharacterDatabase.Query( "SELECT MAX(id) FROM mail" );
5136 if( result )
5138 m_mailid = (*result)[0].GetUInt32()+1;
5139 delete result;
5142 result = CharacterDatabase.Query( "SELECT MAX(id) FROM item_text" );
5143 if( result )
5145 m_ItemTextId = (*result)[0].GetUInt32()+1;
5146 delete result;
5149 result = CharacterDatabase.Query( "SELECT MAX(guid) FROM corpse" );
5150 if( result )
5152 m_hiCorpseGuid = (*result)[0].GetUInt32()+1;
5153 delete result;
5156 result = CharacterDatabase.Query("SELECT MAX(arenateamid) FROM arena_team");
5157 if (result)
5159 m_arenaTeamId = (*result)[0].GetUInt32()+1;
5160 delete result;
5163 result = CharacterDatabase.Query( "SELECT MAX(guildid) FROM guild" );
5164 if (result)
5166 m_guildId = (*result)[0].GetUInt32()+1;
5167 delete result;
5171 uint32 ObjectMgr::GenerateArenaTeamId()
5173 if(m_arenaTeamId>=0xFFFFFFFE)
5175 sLog.outError("Arena team ids overflow!! Can't continue, shutting down server. ");
5176 World::StopNow(ERROR_EXIT_CODE);
5178 return m_arenaTeamId++;
5181 uint32 ObjectMgr::GenerateAuctionID()
5183 if(m_auctionid>=0xFFFFFFFE)
5185 sLog.outError("Auctions ids overflow!! Can't continue, shutting down server. ");
5186 World::StopNow(ERROR_EXIT_CODE);
5188 return m_auctionid++;
5191 uint32 ObjectMgr::GenerateGuildId()
5193 if(m_guildId>=0xFFFFFFFE)
5195 sLog.outError("Guild ids overflow!! Can't continue, shutting down server. ");
5196 World::StopNow(ERROR_EXIT_CODE);
5198 return m_guildId++;
5201 uint32 ObjectMgr::GenerateMailID()
5203 if(m_mailid>=0xFFFFFFFE)
5205 sLog.outError("Mail ids overflow!! Can't continue, shutting down server. ");
5206 World::StopNow(ERROR_EXIT_CODE);
5208 return m_mailid++;
5211 uint32 ObjectMgr::GenerateItemTextID()
5213 if(m_ItemTextId>=0xFFFFFFFE)
5215 sLog.outError("Item text ids overflow!! Can't continue, shutting down server. ");
5216 World::StopNow(ERROR_EXIT_CODE);
5218 return m_ItemTextId++;
5221 uint32 ObjectMgr::CreateItemText(std::string text)
5223 uint32 newItemTextId = GenerateItemTextID();
5224 //insert new itempage to container
5225 mItemTexts[ newItemTextId ] = text;
5226 //save new itempage
5227 CharacterDatabase.escape_string(text);
5228 //any Delete query needed, itemTextId is maximum of all ids
5229 std::ostringstream query;
5230 query << "INSERT INTO item_text (id,text) VALUES ( '" << newItemTextId << "', '" << text << "')";
5231 CharacterDatabase.Execute(query.str().c_str()); //needs to be run this way, because mail body may be more than 1024 characters
5232 return newItemTextId;
5235 uint32 ObjectMgr::GenerateLowGuid(HighGuid guidhigh)
5237 switch(guidhigh)
5239 case HIGHGUID_ITEM:
5240 if(m_hiItemGuid>=0xFFFFFFFE)
5242 sLog.outError("Item guid overflow!! Can't continue, shutting down server. ");
5243 World::StopNow(ERROR_EXIT_CODE);
5245 return m_hiItemGuid++;
5246 case HIGHGUID_UNIT:
5247 if(m_hiCreatureGuid>=0x00FFFFFE)
5249 sLog.outError("Creature guid overflow!! Can't continue, shutting down server. ");
5250 World::StopNow(ERROR_EXIT_CODE);
5252 return m_hiCreatureGuid++;
5253 case HIGHGUID_PET:
5254 if(m_hiPetGuid>=0x00FFFFFE)
5256 sLog.outError("Pet guid overflow!! Can't continue, shutting down server. ");
5257 World::StopNow(ERROR_EXIT_CODE);
5259 return m_hiPetGuid++;
5260 case HIGHGUID_VEHICLE:
5261 if(m_hiVehicleGuid>=0x00FFFFFF)
5263 sLog.outError("Vehicle guid overflow!! Can't continue, shutting down server. ");
5264 World::StopNow(ERROR_EXIT_CODE);
5266 return m_hiVehicleGuid++;
5267 case HIGHGUID_PLAYER:
5268 if(m_hiCharGuid>=0xFFFFFFFE)
5270 sLog.outError("Players guid overflow!! Can't continue, shutting down server. ");
5271 World::StopNow(ERROR_EXIT_CODE);
5273 return m_hiCharGuid++;
5274 case HIGHGUID_GAMEOBJECT:
5275 if(m_hiGoGuid>=0x00FFFFFE)
5277 sLog.outError("Gameobject guid overflow!! Can't continue, shutting down server. ");
5278 World::StopNow(ERROR_EXIT_CODE);
5280 return m_hiGoGuid++;
5281 case HIGHGUID_CORPSE:
5282 if(m_hiCorpseGuid>=0xFFFFFFFE)
5284 sLog.outError("Corpse guid overflow!! Can't continue, shutting down server. ");
5285 World::StopNow(ERROR_EXIT_CODE);
5287 return m_hiCorpseGuid++;
5288 case HIGHGUID_DYNAMICOBJECT:
5289 if(m_hiDoGuid>=0xFFFFFFFE)
5291 sLog.outError("DynamicObject guid overflow!! Can't continue, shutting down server. ");
5292 World::StopNow(ERROR_EXIT_CODE);
5294 return m_hiDoGuid++;
5295 default:
5296 ASSERT(0);
5299 ASSERT(0);
5300 return 0;
5303 void ObjectMgr::LoadGameObjectLocales()
5305 mGameObjectLocaleMap.clear(); // need for reload case
5307 QueryResult *result = WorldDatabase.Query("SELECT entry,"
5308 "name_loc1,name_loc2,name_loc3,name_loc4,name_loc5,name_loc6,name_loc7,name_loc8,"
5309 "castbarcaption_loc1,castbarcaption_loc2,castbarcaption_loc3,castbarcaption_loc4,"
5310 "castbarcaption_loc5,castbarcaption_loc6,castbarcaption_loc7,castbarcaption_loc8 FROM locales_gameobject");
5312 if(!result)
5314 barGoLink bar(1);
5316 bar.step();
5318 sLog.outString();
5319 sLog.outString(">> Loaded 0 gameobject locale strings. DB table `locales_gameobject` is empty.");
5320 return;
5323 barGoLink bar(result->GetRowCount());
5327 Field *fields = result->Fetch();
5328 bar.step();
5330 uint32 entry = fields[0].GetUInt32();
5332 GameObjectLocale& data = mGameObjectLocaleMap[entry];
5334 for(int i = 1; i < MAX_LOCALE; ++i)
5336 std::string str = fields[i].GetCppString();
5337 if(!str.empty())
5339 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5340 if(idx >= 0)
5342 if(data.Name.size() <= idx)
5343 data.Name.resize(idx+1);
5345 data.Name[idx] = str;
5350 for(int i = 1; i < MAX_LOCALE; ++i)
5352 std::string str = fields[i+(MAX_LOCALE-1)].GetCppString();
5353 if(!str.empty())
5355 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5356 if(idx >= 0)
5358 if(data.CastBarCaption.size() <= idx)
5359 data.CastBarCaption.resize(idx+1);
5361 data.CastBarCaption[idx] = str;
5366 } while (result->NextRow());
5368 delete result;
5370 sLog.outString();
5371 sLog.outString( ">> Loaded %lu gameobject locale strings", (unsigned long)mGameObjectLocaleMap.size() );
5374 struct SQLGameObjectLoader : public SQLStorageLoaderBase<SQLGameObjectLoader>
5376 template<class D>
5377 void convert_from_str(uint32 /*field_pos*/, char *src, D &dst)
5379 dst = D(objmgr.GetScriptId(src));
5383 inline void CheckGOLockId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5385 if (sLockStore.LookupEntry(dataN))
5386 return;
5388 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but lock (Id: %u) not found.",
5389 goInfo->id,goInfo->type,N,goInfo->door.lockId,goInfo->door.lockId);
5392 inline void CheckGOLinkedTrapId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5394 if (GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(dataN))
5396 if (trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5397 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5398 goInfo->id,goInfo->type,N,dataN,dataN,GAMEOBJECT_TYPE_TRAP);
5400 /* disable check for while (too many error reports baout not existed in trap templates
5401 else
5402 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5403 goInfo->id,goInfo->type,N,dataN,dataN);
5407 inline void CheckGOSpellId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5409 if (sSpellStore.LookupEntry(dataN))
5410 return;
5412 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but Spell (Entry %u) not exist.",
5413 goInfo->id,goInfo->type,N,dataN,dataN);
5416 inline void CheckAndFixGOChairHeightId(GameObjectInfo const* goInfo,uint32 const& dataN,uint32 N)
5418 if (dataN <= (UNIT_STAND_STATE_SIT_HIGH_CHAIR-UNIT_STAND_STATE_SIT_LOW_CHAIR) )
5419 return;
5421 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but correct chair height in range 0..%i.",
5422 goInfo->id,goInfo->type,N,dataN,UNIT_STAND_STATE_SIT_HIGH_CHAIR-UNIT_STAND_STATE_SIT_LOW_CHAIR);
5424 // prevent client and server unexpected work
5425 const_cast<uint32&>(dataN) = 0;
5428 inline void CheckGONoDamageImmuneId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5430 // 0/1 correct values
5431 if (dataN <= 1)
5432 return;
5434 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but expected boolean (0/1) noDamageImmune field value.",
5435 goInfo->id,goInfo->type,N,dataN);
5438 void ObjectMgr::LoadGameobjectInfo()
5440 SQLGameObjectLoader loader;
5441 loader.Load(sGOStorage);
5443 // some checks
5444 for(uint32 id = 1; id < sGOStorage.MaxEntry; id++)
5446 GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(id);
5447 if (!goInfo)
5448 continue;
5450 switch(goInfo->type)
5452 case GAMEOBJECT_TYPE_DOOR: //0
5454 if (goInfo->door.lockId)
5455 CheckGOLockId(goInfo,goInfo->door.lockId,1);
5456 CheckGONoDamageImmuneId(goInfo,goInfo->door.noDamageImmune,3);
5457 break;
5459 case GAMEOBJECT_TYPE_BUTTON: //1
5461 if (goInfo->button.lockId)
5462 CheckGOLockId(goInfo,goInfo->button.lockId,1);
5463 CheckGONoDamageImmuneId(goInfo,goInfo->button.noDamageImmune,4);
5464 break;
5466 case GAMEOBJECT_TYPE_QUESTGIVER: //2
5468 if (goInfo->questgiver.lockId)
5469 CheckGOLockId(goInfo,goInfo->questgiver.lockId,0);
5470 CheckGONoDamageImmuneId(goInfo,goInfo->questgiver.noDamageImmune,5);
5471 break;
5473 case GAMEOBJECT_TYPE_CHEST: //3
5475 if (goInfo->chest.lockId)
5476 CheckGOLockId(goInfo,goInfo->chest.lockId,0);
5478 if (goInfo->chest.linkedTrapId) // linked trap
5479 CheckGOLinkedTrapId(goInfo,goInfo->chest.linkedTrapId,7);
5480 break;
5482 case GAMEOBJECT_TYPE_TRAP: //6
5484 if (goInfo->trap.lockId)
5485 CheckGOLockId(goInfo,goInfo->trap.lockId,0);
5486 /* disable check for while, too many not existed spells
5487 if (goInfo->trap.spellId) // spell
5488 CheckGOSpellId(goInfo,goInfo->trap.spellId,3);
5490 break;
5492 case GAMEOBJECT_TYPE_CHAIR: //7
5493 CheckAndFixGOChairHeightId(goInfo,goInfo->chair.height,1);
5494 break;
5495 case GAMEOBJECT_TYPE_SPELL_FOCUS: //8
5497 if (goInfo->spellFocus.focusId)
5499 if (!sSpellFocusObjectStore.LookupEntry(goInfo->spellFocus.focusId))
5500 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but SpellFocus (Id: %u) not exist.",
5501 id,goInfo->type,goInfo->spellFocus.focusId,goInfo->spellFocus.focusId);
5504 if (goInfo->spellFocus.linkedTrapId) // linked trap
5505 CheckGOLinkedTrapId(goInfo,goInfo->spellFocus.linkedTrapId,2);
5506 break;
5508 case GAMEOBJECT_TYPE_GOOBER: //10
5510 if (goInfo->goober.lockId)
5511 CheckGOLockId(goInfo,goInfo->goober.lockId,0);
5513 if (goInfo->goober.pageId) // pageId
5515 if (!sPageTextStore.LookupEntry<PageText>(goInfo->goober.pageId))
5516 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data7=%u but PageText (Entry %u) not exist.",
5517 id,goInfo->type,goInfo->goober.pageId,goInfo->goober.pageId);
5519 /* disable check for while, too many not existed spells
5520 if (goInfo->goober.spellId) // spell
5521 CheckGOSpellId(goInfo,goInfo->goober.spellId,10);
5523 CheckGONoDamageImmuneId(goInfo,goInfo->goober.noDamageImmune,11);
5524 if (goInfo->goober.linkedTrapId) // linked trap
5525 CheckGOLinkedTrapId(goInfo,goInfo->goober.linkedTrapId,12);
5526 break;
5528 case GAMEOBJECT_TYPE_AREADAMAGE: //12
5530 if (goInfo->areadamage.lockId)
5531 CheckGOLockId(goInfo,goInfo->areadamage.lockId,0);
5532 break;
5534 case GAMEOBJECT_TYPE_CAMERA: //13
5536 if (goInfo->camera.lockId)
5537 CheckGOLockId(goInfo,goInfo->camera.lockId,0);
5538 break;
5540 case GAMEOBJECT_TYPE_MO_TRANSPORT: //15
5542 if (goInfo->moTransport.taxiPathId)
5544 if (goInfo->moTransport.taxiPathId >= sTaxiPathNodesByPath.size() || sTaxiPathNodesByPath[goInfo->moTransport.taxiPathId].empty())
5545 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but TaxiPath (Id: %u) not exist.",
5546 id,goInfo->type,goInfo->moTransport.taxiPathId,goInfo->moTransport.taxiPathId);
5548 break;
5550 case GAMEOBJECT_TYPE_SUMMONING_RITUAL: //18
5552 /* disable check for while, too many not existed spells
5553 // always must have spell
5554 CheckGOSpellId(goInfo,goInfo->summoningRitual.spellId,1);
5556 break;
5558 case GAMEOBJECT_TYPE_SPELLCASTER: //22
5560 // always must have spell
5561 CheckGOSpellId(goInfo,goInfo->spellcaster.spellId,0);
5562 break;
5564 case GAMEOBJECT_TYPE_FLAGSTAND: //24
5566 if (goInfo->flagstand.lockId)
5567 CheckGOLockId(goInfo,goInfo->flagstand.lockId,0);
5568 CheckGONoDamageImmuneId(goInfo,goInfo->flagstand.noDamageImmune,5);
5569 break;
5571 case GAMEOBJECT_TYPE_FISHINGHOLE: //25
5573 if (goInfo->fishinghole.lockId)
5574 CheckGOLockId(goInfo,goInfo->fishinghole.lockId,4);
5575 break;
5577 case GAMEOBJECT_TYPE_FLAGDROP: //26
5579 if (goInfo->flagdrop.lockId)
5580 CheckGOLockId(goInfo,goInfo->flagdrop.lockId,0);
5581 CheckGONoDamageImmuneId(goInfo,goInfo->flagdrop.noDamageImmune,3);
5582 break;
5584 case GAMEOBJECT_TYPE_BARBER_CHAIR: //32
5585 CheckAndFixGOChairHeightId(goInfo,goInfo->barberChair.chairheight,0);
5586 break;
5590 sLog.outString( ">> Loaded %u game object templates", sGOStorage.RecordCount );
5591 sLog.outString();
5594 void ObjectMgr::LoadExplorationBaseXP()
5596 uint32 count = 0;
5597 QueryResult *result = WorldDatabase.Query("SELECT level,basexp FROM exploration_basexp");
5599 if( !result )
5601 barGoLink bar( 1 );
5603 bar.step();
5605 sLog.outString();
5606 sLog.outString( ">> Loaded %u BaseXP definitions", count );
5607 return;
5610 barGoLink bar( result->GetRowCount() );
5614 bar.step();
5616 Field *fields = result->Fetch();
5617 uint32 level = fields[0].GetUInt32();
5618 uint32 basexp = fields[1].GetUInt32();
5619 mBaseXPTable[level] = basexp;
5620 ++count;
5622 while (result->NextRow());
5624 delete result;
5626 sLog.outString();
5627 sLog.outString( ">> Loaded %u BaseXP definitions", count );
5630 uint32 ObjectMgr::GetBaseXP(uint32 level)
5632 return mBaseXPTable[level] ? mBaseXPTable[level] : 0;
5635 uint32 ObjectMgr::GetXPForLevel(uint32 level)
5637 if (level < mPlayerXPperLevel.size())
5638 return mPlayerXPperLevel[level];
5639 return 0;
5642 void ObjectMgr::LoadPetNames()
5644 uint32 count = 0;
5645 QueryResult *result = WorldDatabase.Query("SELECT word,entry,half FROM pet_name_generation");
5647 if( !result )
5649 barGoLink bar( 1 );
5651 bar.step();
5653 sLog.outString();
5654 sLog.outString( ">> Loaded %u pet name parts", count );
5655 return;
5658 barGoLink bar( result->GetRowCount() );
5662 bar.step();
5664 Field *fields = result->Fetch();
5665 std::string word = fields[0].GetString();
5666 uint32 entry = fields[1].GetUInt32();
5667 bool half = fields[2].GetBool();
5668 if(half)
5669 PetHalfName1[entry].push_back(word);
5670 else
5671 PetHalfName0[entry].push_back(word);
5672 ++count;
5674 while (result->NextRow());
5675 delete result;
5677 sLog.outString();
5678 sLog.outString( ">> Loaded %u pet name parts", count );
5681 void ObjectMgr::LoadPetNumber()
5683 QueryResult* result = CharacterDatabase.Query("SELECT MAX(id) FROM character_pet");
5684 if(result)
5686 Field *fields = result->Fetch();
5687 m_hiPetNumber = fields[0].GetUInt32()+1;
5688 delete result;
5691 barGoLink bar( 1 );
5692 bar.step();
5694 sLog.outString();
5695 sLog.outString( ">> Loaded the max pet number: %d", m_hiPetNumber-1);
5698 std::string ObjectMgr::GeneratePetName(uint32 entry)
5700 std::vector<std::string> & list0 = PetHalfName0[entry];
5701 std::vector<std::string> & list1 = PetHalfName1[entry];
5703 if(list0.empty() || list1.empty())
5705 CreatureInfo const *cinfo = GetCreatureTemplate(entry);
5706 char* petname = GetPetName(cinfo->family, sWorld.GetDefaultDbcLocale());
5707 if(!petname)
5708 petname = cinfo->Name;
5709 return std::string(petname);
5712 return *(list0.begin()+urand(0, list0.size()-1)) + *(list1.begin()+urand(0, list1.size()-1));
5715 uint32 ObjectMgr::GeneratePetNumber()
5717 return ++m_hiPetNumber;
5720 void ObjectMgr::LoadCorpses()
5722 uint32 count = 0;
5723 // 0 1 2 3 4 5 6 7 8 10
5724 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");
5726 if( !result )
5728 barGoLink bar( 1 );
5730 bar.step();
5732 sLog.outString();
5733 sLog.outString( ">> Loaded %u corpses", count );
5734 return;
5737 barGoLink bar( result->GetRowCount() );
5741 bar.step();
5743 Field *fields = result->Fetch();
5745 uint32 guid = fields[result->GetFieldCount()-1].GetUInt32();
5747 Corpse *corpse = new Corpse;
5748 if(!corpse->LoadFromDB(guid,fields))
5750 delete corpse;
5751 continue;
5754 ObjectAccessor::Instance().AddCorpse(corpse);
5756 ++count;
5758 while (result->NextRow());
5759 delete result;
5761 sLog.outString();
5762 sLog.outString( ">> Loaded %u corpses", count );
5765 void ObjectMgr::LoadReputationOnKill()
5767 uint32 count = 0;
5769 // 0 1 2
5770 QueryResult *result = WorldDatabase.Query("SELECT creature_id, RewOnKillRepFaction1, RewOnKillRepFaction2,"
5771 // 3 4 5 6 7 8 9
5772 "IsTeamAward1, MaxStanding1, RewOnKillRepValue1, IsTeamAward2, MaxStanding2, RewOnKillRepValue2, TeamDependent "
5773 "FROM creature_onkill_reputation");
5775 if(!result)
5777 barGoLink bar(1);
5779 bar.step();
5781 sLog.outString();
5782 sLog.outErrorDb(">> Loaded 0 creature award reputation definitions. DB table `creature_onkill_reputation` is empty.");
5783 return;
5786 barGoLink bar(result->GetRowCount());
5790 Field *fields = result->Fetch();
5791 bar.step();
5793 uint32 creature_id = fields[0].GetUInt32();
5795 ReputationOnKillEntry repOnKill;
5796 repOnKill.repfaction1 = fields[1].GetUInt32();
5797 repOnKill.repfaction2 = fields[2].GetUInt32();
5798 repOnKill.is_teamaward1 = fields[3].GetBool();
5799 repOnKill.reputation_max_cap1 = fields[4].GetUInt32();
5800 repOnKill.repvalue1 = fields[5].GetInt32();
5801 repOnKill.is_teamaward2 = fields[6].GetBool();
5802 repOnKill.reputation_max_cap2 = fields[7].GetUInt32();
5803 repOnKill.repvalue2 = fields[8].GetInt32();
5804 repOnKill.team_dependent = fields[9].GetUInt8();
5806 if(!GetCreatureTemplate(creature_id))
5808 sLog.outErrorDb("Table `creature_onkill_reputation` have data for not existed creature entry (%u), skipped",creature_id);
5809 continue;
5812 if(repOnKill.repfaction1)
5814 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(repOnKill.repfaction1);
5815 if(!factionEntry1)
5817 sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction1);
5818 continue;
5822 if(repOnKill.repfaction2)
5824 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(repOnKill.repfaction2);
5825 if(!factionEntry2)
5827 sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction2);
5828 continue;
5832 mRepOnKill[creature_id] = repOnKill;
5834 ++count;
5835 } while (result->NextRow());
5837 delete result;
5839 sLog.outString();
5840 sLog.outString(">> Loaded %u creature award reputation definitions", count);
5843 void ObjectMgr::LoadPointsOfInterest()
5845 uint32 count = 0;
5847 // 0 1 2 3 4 5
5848 QueryResult *result = WorldDatabase.Query("SELECT entry, x, y, icon, flags, data, icon_name FROM points_of_interest");
5850 if(!result)
5852 barGoLink bar(1);
5854 bar.step();
5856 sLog.outString();
5857 sLog.outErrorDb(">> Loaded 0 Points of Interest definitions. DB table `points_of_interest` is empty.");
5858 return;
5861 barGoLink bar(result->GetRowCount());
5865 Field *fields = result->Fetch();
5866 bar.step();
5868 uint32 point_id = fields[0].GetUInt32();
5870 PointOfInterest POI;
5871 POI.x = fields[1].GetFloat();
5872 POI.y = fields[2].GetFloat();
5873 POI.icon = fields[3].GetUInt32();
5874 POI.flags = fields[4].GetUInt32();
5875 POI.data = fields[5].GetUInt32();
5876 POI.icon_name = fields[6].GetCppString();
5878 if(!MaNGOS::IsValidMapCoord(POI.x,POI.y))
5880 sLog.outErrorDb("Table `points_of_interest` (Entry: %u) have invalid coordinates (X: %f Y: %f), ignored.",point_id,POI.x,POI.y);
5881 continue;
5884 mPointsOfInterest[point_id] = POI;
5886 ++count;
5887 } while (result->NextRow());
5889 delete result;
5891 sLog.outString();
5892 sLog.outString(">> Loaded %u Points of Interest definitions", count);
5895 void ObjectMgr::LoadNPCSpellClickSpells()
5897 uint32 count = 0;
5899 mSpellClickInfoMap.clear();
5901 QueryResult *result = WorldDatabase.Query("SELECT npc_entry, spell_id, quest_id, cast_flags FROM npc_spellclick_spells");
5903 if(!result)
5905 barGoLink bar(1);
5907 bar.step();
5909 sLog.outString();
5910 sLog.outErrorDb(">> Loaded 0 spellclick spells. DB table `npc_spellclick_spells` is empty.");
5911 return;
5914 barGoLink bar(result->GetRowCount());
5918 Field *fields = result->Fetch();
5919 bar.step();
5921 uint32 npc_entry = fields[0].GetUInt32();
5922 CreatureInfo const* cInfo = GetCreatureTemplate(npc_entry);
5923 if (!cInfo)
5925 sLog.outErrorDb("Table npc_spellclick_spells references unknown creature_template %u. Skipping entry.", npc_entry);
5926 continue;
5929 uint32 spellid = fields[1].GetUInt32();
5930 SpellEntry const *spellinfo = sSpellStore.LookupEntry(spellid);
5931 if (!spellinfo)
5933 sLog.outErrorDb("Table npc_spellclick_spells references unknown spellid %u. Skipping entry.", spellid);
5934 continue;
5937 uint32 quest = fields[2].GetUInt32();
5939 // quest might be 0 to enable spellclick independent of any quest
5940 if (quest)
5942 if(mQuestTemplates.find(quest) == mQuestTemplates.end())
5944 sLog.outErrorDb("Table npc_spellclick_spells references unknown quest %u. Skipping entry.", spellid);
5945 continue;
5950 uint8 castFlags = fields[3].GetUInt8();
5951 SpellClickInfo info;
5952 info.spellId = spellid;
5953 info.questId = quest;
5954 info.castFlags = castFlags;
5955 mSpellClickInfoMap.insert(SpellClickInfoMap::value_type(npc_entry, info));
5956 ++count;
5957 } while (result->NextRow());
5959 delete result;
5961 sLog.outString();
5962 sLog.outString(">> Loaded %u spellclick definitions", count);
5965 void ObjectMgr::LoadWeatherZoneChances()
5967 uint32 count = 0;
5969 // 0 1 2 3 4 5 6 7 8 9 10 11 12
5970 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");
5972 if(!result)
5974 barGoLink bar(1);
5976 bar.step();
5978 sLog.outString();
5979 sLog.outErrorDb(">> Loaded 0 weather definitions. DB table `game_weather` is empty.");
5980 return;
5983 barGoLink bar(result->GetRowCount());
5987 Field *fields = result->Fetch();
5988 bar.step();
5990 uint32 zone_id = fields[0].GetUInt32();
5992 WeatherZoneChances& wzc = mWeatherZoneMap[zone_id];
5994 for(int season = 0; season < WEATHER_SEASONS; ++season)
5996 wzc.data[season].rainChance = fields[season * (MAX_WEATHER_TYPE-1) + 1].GetUInt32();
5997 wzc.data[season].snowChance = fields[season * (MAX_WEATHER_TYPE-1) + 2].GetUInt32();
5998 wzc.data[season].stormChance = fields[season * (MAX_WEATHER_TYPE-1) + 3].GetUInt32();
6000 if(wzc.data[season].rainChance > 100)
6002 wzc.data[season].rainChance = 25;
6003 sLog.outErrorDb("Weather for zone %u season %u has wrong rain chance > 100%%",zone_id,season);
6006 if(wzc.data[season].snowChance > 100)
6008 wzc.data[season].snowChance = 25;
6009 sLog.outErrorDb("Weather for zone %u season %u has wrong snow chance > 100%%",zone_id,season);
6012 if(wzc.data[season].stormChance > 100)
6014 wzc.data[season].stormChance = 25;
6015 sLog.outErrorDb("Weather for zone %u season %u has wrong storm chance > 100%%",zone_id,season);
6019 ++count;
6020 } while (result->NextRow());
6022 delete result;
6024 sLog.outString();
6025 sLog.outString(">> Loaded %u weather definitions", count);
6028 void ObjectMgr::SaveCreatureRespawnTime(uint32 loguid, uint32 instance, time_t t)
6030 mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
6031 WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
6032 if(t)
6033 WorldDatabase.PExecute("INSERT INTO creature_respawn VALUES ( '%u', '" I64FMTD "', '%u' )", loguid, uint64(t), instance);
6036 void ObjectMgr::DeleteCreatureData(uint32 guid)
6038 // remove mapid*cellid -> guid_set map
6039 CreatureData const* data = GetCreatureData(guid);
6040 if(data)
6041 RemoveCreatureFromGrid(guid, data);
6043 mCreatureDataMap.erase(guid);
6046 void ObjectMgr::SaveGORespawnTime(uint32 loguid, uint32 instance, time_t t)
6048 mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
6049 WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
6050 if(t)
6051 WorldDatabase.PExecute("INSERT INTO gameobject_respawn VALUES ( '%u', '" I64FMTD "', '%u' )", loguid, uint64(t), instance);
6054 void ObjectMgr::DeleteRespawnTimeForInstance(uint32 instance)
6056 RespawnTimes::iterator next;
6058 for(RespawnTimes::iterator itr = mGORespawnTimes.begin(); itr != mGORespawnTimes.end(); itr = next)
6060 next = itr;
6061 ++next;
6063 if(GUID_HIPART(itr->first)==instance)
6064 mGORespawnTimes.erase(itr);
6067 for(RespawnTimes::iterator itr = mCreatureRespawnTimes.begin(); itr != mCreatureRespawnTimes.end(); itr = next)
6069 next = itr;
6070 ++next;
6072 if(GUID_HIPART(itr->first)==instance)
6073 mCreatureRespawnTimes.erase(itr);
6076 WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE instance = '%u'", instance);
6077 WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE instance = '%u'", instance);
6080 void ObjectMgr::DeleteGOData(uint32 guid)
6082 // remove mapid*cellid -> guid_set map
6083 GameObjectData const* data = GetGOData(guid);
6084 if(data)
6085 RemoveGameobjectFromGrid(guid, data);
6087 mGameObjectDataMap.erase(guid);
6090 void ObjectMgr::AddCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid, uint32 instance)
6092 // corpses are always added to spawn mode 0 and they are spawned by their instance id
6093 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
6094 cell_guids.corpses[player_guid] = instance;
6097 void ObjectMgr::DeleteCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid)
6099 // corpses are always added to spawn mode 0 and they are spawned by their instance id
6100 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
6101 cell_guids.corpses.erase(player_guid);
6104 void ObjectMgr::LoadQuestRelationsHelper(QuestRelations& map,char const* table)
6106 map.clear(); // need for reload case
6108 uint32 count = 0;
6110 QueryResult *result = WorldDatabase.PQuery("SELECT id,quest FROM %s",table);
6112 if(!result)
6114 barGoLink bar(1);
6116 bar.step();
6118 sLog.outString();
6119 sLog.outErrorDb(">> Loaded 0 quest relations from %s. DB table `%s` is empty.",table,table);
6120 return;
6123 barGoLink bar(result->GetRowCount());
6127 Field *fields = result->Fetch();
6128 bar.step();
6130 uint32 id = fields[0].GetUInt32();
6131 uint32 quest = fields[1].GetUInt32();
6133 if(mQuestTemplates.find(quest) == mQuestTemplates.end())
6135 sLog.outErrorDb("Table `%s: Quest %u listed for entry %u does not exist.",table,quest,id);
6136 continue;
6139 map.insert(QuestRelations::value_type(id,quest));
6141 ++count;
6142 } while (result->NextRow());
6144 delete result;
6146 sLog.outString();
6147 sLog.outString(">> Loaded %u quest relations from %s", count,table);
6150 void ObjectMgr::LoadGameobjectQuestRelations()
6152 LoadQuestRelationsHelper(mGOQuestRelations,"gameobject_questrelation");
6154 for(QuestRelations::iterator itr = mGOQuestRelations.begin(); itr != mGOQuestRelations.end(); ++itr)
6156 GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
6157 if(!goInfo)
6158 sLog.outErrorDb("Table `gameobject_questrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
6159 else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
6160 sLog.outErrorDb("Table `gameobject_questrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
6164 void ObjectMgr::LoadGameobjectInvolvedRelations()
6166 LoadQuestRelationsHelper(mGOQuestInvolvedRelations,"gameobject_involvedrelation");
6168 for(QuestRelations::iterator itr = mGOQuestInvolvedRelations.begin(); itr != mGOQuestInvolvedRelations.end(); ++itr)
6170 GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
6171 if(!goInfo)
6172 sLog.outErrorDb("Table `gameobject_involvedrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
6173 else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
6174 sLog.outErrorDb("Table `gameobject_involvedrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
6178 void ObjectMgr::LoadCreatureQuestRelations()
6180 LoadQuestRelationsHelper(mCreatureQuestRelations,"creature_questrelation");
6182 for(QuestRelations::iterator itr = mCreatureQuestRelations.begin(); itr != mCreatureQuestRelations.end(); ++itr)
6184 CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
6185 if(!cInfo)
6186 sLog.outErrorDb("Table `creature_questrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
6187 else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
6188 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);
6192 void ObjectMgr::LoadCreatureInvolvedRelations()
6194 LoadQuestRelationsHelper(mCreatureQuestInvolvedRelations,"creature_involvedrelation");
6196 for(QuestRelations::iterator itr = mCreatureQuestInvolvedRelations.begin(); itr != mCreatureQuestInvolvedRelations.end(); ++itr)
6198 CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
6199 if(!cInfo)
6200 sLog.outErrorDb("Table `creature_involvedrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
6201 else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
6202 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);
6206 void ObjectMgr::LoadReservedPlayersNames()
6208 m_ReservedNames.clear(); // need for reload case
6210 QueryResult *result = WorldDatabase.Query("SELECT name FROM reserved_name");
6212 uint32 count = 0;
6214 if( !result )
6216 barGoLink bar( 1 );
6217 bar.step();
6219 sLog.outString();
6220 sLog.outString( ">> Loaded %u reserved player names", count );
6221 return;
6224 barGoLink bar( result->GetRowCount() );
6226 Field* fields;
6229 bar.step();
6230 fields = result->Fetch();
6231 std::string name= fields[0].GetCppString();
6233 std::wstring wstr;
6234 if(!Utf8toWStr (name,wstr))
6236 sLog.outError("Table `reserved_name` have invalid name: %s", name.c_str() );
6237 continue;
6240 wstrToLower(wstr);
6242 m_ReservedNames.insert(wstr);
6243 ++count;
6244 } while ( result->NextRow() );
6246 delete result;
6248 sLog.outString();
6249 sLog.outString( ">> Loaded %u reserved player names", count );
6252 bool ObjectMgr::IsReservedName( const std::string& name ) const
6254 std::wstring wstr;
6255 if(!Utf8toWStr (name,wstr))
6256 return false;
6258 wstrToLower(wstr);
6260 return m_ReservedNames.find(wstr) != m_ReservedNames.end();
6263 enum LanguageType
6265 LT_BASIC_LATIN = 0x0000,
6266 LT_EXTENDEN_LATIN = 0x0001,
6267 LT_CYRILLIC = 0x0002,
6268 LT_EAST_ASIA = 0x0004,
6269 LT_ANY = 0xFFFF
6272 static LanguageType GetRealmLanguageType(bool create)
6274 switch(sWorld.getConfig(CONFIG_REALM_ZONE))
6276 case REALM_ZONE_UNKNOWN: // any language
6277 case REALM_ZONE_DEVELOPMENT:
6278 case REALM_ZONE_TEST_SERVER:
6279 case REALM_ZONE_QA_SERVER:
6280 return LT_ANY;
6281 case REALM_ZONE_UNITED_STATES: // extended-Latin
6282 case REALM_ZONE_OCEANIC:
6283 case REALM_ZONE_LATIN_AMERICA:
6284 case REALM_ZONE_ENGLISH:
6285 case REALM_ZONE_GERMAN:
6286 case REALM_ZONE_FRENCH:
6287 case REALM_ZONE_SPANISH:
6288 return LT_EXTENDEN_LATIN;
6289 case REALM_ZONE_KOREA: // East-Asian
6290 case REALM_ZONE_TAIWAN:
6291 case REALM_ZONE_CHINA:
6292 return LT_EAST_ASIA;
6293 case REALM_ZONE_RUSSIAN: // Cyrillic
6294 return LT_CYRILLIC;
6295 default:
6296 return create ? LT_BASIC_LATIN : LT_ANY; // basic-Latin at create, any at login
6300 bool isValidString(std::wstring wstr, uint32 strictMask, bool numericOrSpace, bool create = false)
6302 if(strictMask==0) // any language, ignore realm
6304 if(isExtendedLatinString(wstr,numericOrSpace))
6305 return true;
6306 if(isCyrillicString(wstr,numericOrSpace))
6307 return true;
6308 if(isEastAsianString(wstr,numericOrSpace))
6309 return true;
6310 return false;
6313 if(strictMask & 0x2) // realm zone specific
6315 LanguageType lt = GetRealmLanguageType(create);
6316 if(lt & LT_EXTENDEN_LATIN)
6317 if(isExtendedLatinString(wstr,numericOrSpace))
6318 return true;
6319 if(lt & LT_CYRILLIC)
6320 if(isCyrillicString(wstr,numericOrSpace))
6321 return true;
6322 if(lt & LT_EAST_ASIA)
6323 if(isEastAsianString(wstr,numericOrSpace))
6324 return true;
6327 if(strictMask & 0x1) // basic Latin
6329 if(isBasicLatinString(wstr,numericOrSpace))
6330 return true;
6333 return false;
6336 bool ObjectMgr::IsValidName( const std::string& name, bool create )
6338 std::wstring wname;
6339 if(!Utf8toWStr(name,wname))
6340 return false;
6342 if(wname.size() < 1 || wname.size() > MAX_PLAYER_NAME)
6343 return false;
6345 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_PLAYER_NAMES);
6347 return isValidString(wname,strictMask,false,create);
6350 bool ObjectMgr::IsValidCharterName( const std::string& name )
6352 std::wstring wname;
6353 if(!Utf8toWStr(name,wname))
6354 return false;
6356 if(wname.size() < 1)
6357 return false;
6359 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_CHARTER_NAMES);
6361 return isValidString(wname,strictMask,true);
6364 bool ObjectMgr::IsValidPetName( const std::string& name )
6366 std::wstring wname;
6367 if(!Utf8toWStr(name,wname))
6368 return false;
6370 if(wname.size() < 1)
6371 return false;
6373 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_PET_NAMES);
6375 return isValidString(wname,strictMask,false);
6378 int ObjectMgr::GetIndexForLocale( LocaleConstant loc )
6380 if(loc==LOCALE_enUS)
6381 return -1;
6383 for(size_t i=0;i < m_LocalForIndex.size(); ++i)
6384 if(m_LocalForIndex[i]==loc)
6385 return i;
6387 return -1;
6390 LocaleConstant ObjectMgr::GetLocaleForIndex(int i)
6392 if (i<0 || i>=m_LocalForIndex.size())
6393 return LOCALE_enUS;
6395 return m_LocalForIndex[i];
6398 int ObjectMgr::GetOrNewIndexForLocale( LocaleConstant loc )
6400 if(loc==LOCALE_enUS)
6401 return -1;
6403 for(size_t i=0;i < m_LocalForIndex.size(); ++i)
6404 if(m_LocalForIndex[i]==loc)
6405 return i;
6407 m_LocalForIndex.push_back(loc);
6408 return m_LocalForIndex.size()-1;
6411 void ObjectMgr::LoadGameObjectForQuests()
6413 mGameObjectForQuestSet.clear(); // need for reload case
6415 if( !sGOStorage.MaxEntry )
6417 barGoLink bar( 1 );
6418 bar.step();
6419 sLog.outString();
6420 sLog.outString( ">> Loaded 0 GameObjects for quests" );
6421 return;
6424 barGoLink bar( sGOStorage.MaxEntry - 1 );
6425 uint32 count = 0;
6427 // collect GO entries for GO that must activated
6428 for(uint32 go_entry = 1; go_entry < sGOStorage.MaxEntry; ++go_entry)
6430 bar.step();
6431 GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(go_entry);
6432 if(!goInfo)
6433 continue;
6435 switch(goInfo->type)
6437 // scan GO chest with loot including quest items
6438 case GAMEOBJECT_TYPE_CHEST:
6440 uint32 loot_id = GameObject::GetLootId(goInfo);
6442 // find quest loot for GO
6443 if(LootTemplates_Gameobject.HaveQuestLootFor(loot_id))
6445 mGameObjectForQuestSet.insert(go_entry);
6446 ++count;
6448 break;
6450 case GAMEOBJECT_TYPE_GOOBER:
6452 if(goInfo->goober.questId) //quests objects
6454 mGameObjectForQuestSet.insert(go_entry);
6455 count++;
6457 break;
6459 default:
6460 break;
6464 sLog.outString();
6465 sLog.outString( ">> Loaded %u GameObjects for quests", count );
6468 bool ObjectMgr::LoadMangosStrings(DatabaseType& db, char const* table, int32 min_value, int32 max_value)
6470 int32 start_value = min_value;
6471 int32 end_value = max_value;
6472 // some string can have negative indexes range
6473 if (start_value < 0)
6475 if (end_value >= start_value)
6477 sLog.outErrorDb("Table '%s' attempt loaded with invalid range (%d - %d), strings not loaded.",table,min_value,max_value);
6478 return false;
6481 // real range (max+1,min+1) exaple: (-10,-1000) -> -999...-10+1
6482 std::swap(start_value,end_value);
6483 ++start_value;
6484 ++end_value;
6486 else
6488 if (start_value >= end_value)
6490 sLog.outErrorDb("Table '%s' attempt loaded with invalid range (%d - %d), strings not loaded.",table,min_value,max_value);
6491 return false;
6495 // cleanup affected map part for reloading case
6496 for(MangosStringLocaleMap::iterator itr = mMangosStringLocaleMap.begin(); itr != mMangosStringLocaleMap.end();)
6498 if (itr->first >= start_value && itr->first < end_value)
6499 mMangosStringLocaleMap.erase(itr++);
6500 else
6501 ++itr;
6504 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);
6506 if (!result)
6508 barGoLink bar(1);
6510 bar.step();
6512 sLog.outString();
6513 if (min_value == MIN_MANGOS_STRING_ID) // error only in case internal strings
6514 sLog.outErrorDb(">> Loaded 0 mangos strings. DB table `%s` is empty. Cannot continue.",table);
6515 else
6516 sLog.outString(">> Loaded 0 string templates. DB table `%s` is empty.",table);
6517 return false;
6520 uint32 count = 0;
6522 barGoLink bar(result->GetRowCount());
6526 Field *fields = result->Fetch();
6527 bar.step();
6529 int32 entry = fields[0].GetInt32();
6531 if (entry==0)
6533 sLog.outErrorDb("Table `%s` contain reserved entry 0, ignored.",table);
6534 continue;
6536 else if (entry < start_value || entry >= end_value)
6538 sLog.outErrorDb("Table `%s` contain entry %i out of allowed range (%d - %d), ignored.",table,entry,min_value,max_value);
6539 continue;
6542 MangosStringLocale& data = mMangosStringLocaleMap[entry];
6544 if (data.Content.size() > 0)
6546 sLog.outErrorDb("Table `%s` contain data for already loaded entry %i (from another table?), ignored.",table,entry);
6547 continue;
6550 data.Content.resize(1);
6551 ++count;
6553 // 0 -> default, idx in to idx+1
6554 data.Content[0] = fields[1].GetCppString();
6556 for(int i = 1; i < MAX_LOCALE; ++i)
6558 std::string str = fields[i+1].GetCppString();
6559 if (!str.empty())
6561 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
6562 if (idx >= 0)
6564 // 0 -> default, idx in to idx+1
6565 if (data.Content.size() <= idx+1)
6566 data.Content.resize(idx+2);
6568 data.Content[idx+1] = str;
6572 } while (result->NextRow());
6574 delete result;
6576 sLog.outString();
6577 if (min_value == MIN_MANGOS_STRING_ID)
6578 sLog.outString( ">> Loaded %u MaNGOS strings from table %s", count,table);
6579 else
6580 sLog.outString( ">> Loaded %u string templates from %s", count,table);
6582 return true;
6585 const char *ObjectMgr::GetMangosString(int32 entry, int locale_idx) const
6587 // locale_idx==-1 -> default, locale_idx >= 0 in to idx+1
6588 // Content[0] always exist if exist MangosStringLocale
6589 if(MangosStringLocale const *msl = GetMangosStringLocale(entry))
6591 if(msl->Content.size() > locale_idx+1 && !msl->Content[locale_idx+1].empty())
6592 return msl->Content[locale_idx+1].c_str();
6593 else
6594 return msl->Content[0].c_str();
6597 if(entry > 0)
6598 sLog.outErrorDb("Entry %i not found in `mangos_string` table.",entry);
6599 else
6600 sLog.outErrorDb("Mangos string entry %i not found in DB.",entry);
6601 return "<error>";
6604 void ObjectMgr::LoadFishingBaseSkillLevel()
6606 mFishingBaseForArea.clear(); // for reload case
6608 uint32 count = 0;
6609 QueryResult *result = WorldDatabase.Query("SELECT entry,skill FROM skill_fishing_base_level");
6611 if( !result )
6613 barGoLink bar( 1 );
6615 bar.step();
6617 sLog.outString();
6618 sLog.outErrorDb(">> Loaded `skill_fishing_base_level`, table is empty!");
6619 return;
6622 barGoLink bar( result->GetRowCount() );
6626 bar.step();
6628 Field *fields = result->Fetch();
6629 uint32 entry = fields[0].GetUInt32();
6630 int32 skill = fields[1].GetInt32();
6632 AreaTableEntry const* fArea = GetAreaEntryByAreaID(entry);
6633 if(!fArea)
6635 sLog.outErrorDb("AreaId %u defined in `skill_fishing_base_level` does not exist",entry);
6636 continue;
6639 mFishingBaseForArea[entry] = skill;
6640 ++count;
6642 while (result->NextRow());
6644 delete result;
6646 sLog.outString();
6647 sLog.outString( ">> Loaded %u areas for fishing base skill level", count );
6650 // Searches for the same condition already in Conditions store
6651 // Returns Id if found, else adds it to Conditions and returns Id
6652 uint16 ObjectMgr::GetConditionId( ConditionType condition, uint32 value1, uint32 value2 )
6654 PlayerCondition lc = PlayerCondition(condition, value1, value2);
6655 for (uint16 i=0; i < mConditions.size(); ++i)
6657 if (lc == mConditions[i])
6658 return i;
6661 mConditions.push_back(lc);
6663 if(mConditions.size() > 0xFFFF)
6665 sLog.outError("Conditions store overflow! Current and later loaded conditions will ignored!");
6666 return 0;
6669 return mConditions.size() - 1;
6672 bool ObjectMgr::CheckDeclinedNames( std::wstring mainpart, DeclinedName const& names )
6674 for(int i =0; i < MAX_DECLINED_NAME_CASES; ++i)
6676 std::wstring wname;
6677 if(!Utf8toWStr(names.name[i],wname))
6678 return false;
6680 if(mainpart!=GetMainPartOfName(wname,i+1))
6681 return false;
6683 return true;
6686 uint32 ObjectMgr::GetAreaTriggerScriptId(uint32 trigger_id)
6688 AreaTriggerScriptMap::const_iterator i = mAreaTriggerScripts.find(trigger_id);
6689 if(i!= mAreaTriggerScripts.end())
6690 return i->second;
6691 return 0;
6694 // Checks if player meets the condition
6695 bool PlayerCondition::Meets(Player const * player) const
6697 if( !player )
6698 return false; // player not present, return false
6700 switch (condition)
6702 case CONDITION_NONE:
6703 return true; // empty condition, always met
6704 case CONDITION_AURA:
6705 return player->HasAura(value1, value2);
6706 case CONDITION_ITEM:
6707 return player->HasItemCount(value1, value2);
6708 case CONDITION_ITEM_EQUIPPED:
6709 return player->HasItemOrGemWithIdEquipped(value1,1);
6710 case CONDITION_ZONEID:
6711 return player->GetZoneId() == value1;
6712 case CONDITION_REPUTATION_RANK:
6714 FactionEntry const* faction = sFactionStore.LookupEntry(value1);
6715 return faction && player->GetReputationMgr().GetRank(faction) >= value2;
6717 case CONDITION_TEAM:
6718 return player->GetTeam() == value1;
6719 case CONDITION_SKILL:
6720 return player->HasSkill(value1) && player->GetBaseSkillValue(value1) >= value2;
6721 case CONDITION_QUESTREWARDED:
6722 return player->GetQuestRewardStatus(value1);
6723 case CONDITION_QUESTTAKEN:
6725 QuestStatus status = player->GetQuestStatus(value1);
6726 return (status == QUEST_STATUS_INCOMPLETE);
6728 case CONDITION_AD_COMMISSION_AURA:
6730 Unit::AuraMap const& auras = player->GetAuras();
6731 for(Unit::AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
6732 if((itr->second->GetSpellProto()->Attributes & 0x1000010) && itr->second->GetSpellProto()->SpellVisual[0]==3580)
6733 return true;
6734 return false;
6736 case CONDITION_NO_AURA:
6737 return !player->HasAura(value1, value2);
6738 case CONDITION_ACTIVE_EVENT:
6739 return gameeventmgr.IsActiveEvent(value1);
6740 default:
6741 return false;
6745 // Verification of condition values validity
6746 bool PlayerCondition::IsValid(ConditionType condition, uint32 value1, uint32 value2)
6748 if( condition >= MAX_CONDITION) // Wrong condition type
6750 sLog.outErrorDb("Condition has bad type of %u, skipped ", condition );
6751 return false;
6754 switch (condition)
6756 case CONDITION_AURA:
6758 if(!sSpellStore.LookupEntry(value1))
6760 sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
6761 return false;
6763 if(value2 > 2)
6765 sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..2), skipped", value2);
6766 return false;
6768 break;
6770 case CONDITION_ITEM:
6772 ItemPrototype const *proto = objmgr.GetItemPrototype(value1);
6773 if(!proto)
6775 sLog.outErrorDb("Item condition requires to have non existing item (%u), skipped", value1);
6776 return false;
6778 break;
6780 case CONDITION_ITEM_EQUIPPED:
6782 ItemPrototype const *proto = objmgr.GetItemPrototype(value1);
6783 if(!proto)
6785 sLog.outErrorDb("ItemEquipped condition requires to have non existing item (%u) equipped, skipped", value1);
6786 return false;
6788 break;
6790 case CONDITION_ZONEID:
6792 AreaTableEntry const* areaEntry = GetAreaEntryByAreaID(value1);
6793 if(!areaEntry)
6795 sLog.outErrorDb("Zone condition requires to be in non existing area (%u), skipped", value1);
6796 return false;
6798 if(areaEntry->zone != 0)
6800 sLog.outErrorDb("Zone condition requires to be in area (%u) which is a subzone but zone expected, skipped", value1);
6801 return false;
6803 break;
6805 case CONDITION_REPUTATION_RANK:
6807 FactionEntry const* factionEntry = sFactionStore.LookupEntry(value1);
6808 if(!factionEntry)
6810 sLog.outErrorDb("Reputation condition requires to have reputation non existing faction (%u), skipped", value1);
6811 return false;
6813 break;
6815 case CONDITION_TEAM:
6817 if (value1 != ALLIANCE && value1 != HORDE)
6819 sLog.outErrorDb("Team condition specifies unknown team (%u), skipped", value1);
6820 return false;
6822 break;
6824 case CONDITION_SKILL:
6826 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(value1);
6827 if (!pSkill)
6829 sLog.outErrorDb("Skill condition specifies non-existing skill (%u), skipped", value1);
6830 return false;
6832 if (value2 < 1 || value2 > sWorld.GetConfigMaxSkillValue() )
6834 sLog.outErrorDb("Skill condition specifies invalid skill value (%u), skipped", value2);
6835 return false;
6837 break;
6839 case CONDITION_QUESTREWARDED:
6840 case CONDITION_QUESTTAKEN:
6842 Quest const *Quest = objmgr.GetQuestTemplate(value1);
6843 if (!Quest)
6845 sLog.outErrorDb("Quest condition specifies non-existing quest (%u), skipped", value1);
6846 return false;
6848 if(value2)
6849 sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
6850 break;
6852 case CONDITION_AD_COMMISSION_AURA:
6854 if(value1)
6855 sLog.outErrorDb("Quest condition has useless data in value1 (%u)!", value1);
6856 if(value2)
6857 sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
6858 break;
6860 case CONDITION_NO_AURA:
6862 if(!sSpellStore.LookupEntry(value1))
6864 sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
6865 return false;
6867 if(value2 > 2)
6869 sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..2), skipped", value2);
6870 return false;
6872 break;
6874 case CONDITION_ACTIVE_EVENT:
6876 GameEventMgr::GameEventDataMap const& events = gameeventmgr.GetEventMap();
6877 if(value1 >=events.size() || !events[value1].isValid())
6879 sLog.outErrorDb("Active event condition requires existed event id (%u), skipped", value1);
6880 return false;
6882 break;
6884 case CONDITION_NONE:
6885 break;
6887 return true;
6890 SkillRangeType GetSkillRangeType(SkillLineEntry const *pSkill, bool racial)
6892 switch(pSkill->categoryId)
6894 case SKILL_CATEGORY_LANGUAGES: return SKILL_RANGE_LANGUAGE;
6895 case SKILL_CATEGORY_WEAPON:
6896 if(pSkill->id!=SKILL_FIST_WEAPONS)
6897 return SKILL_RANGE_LEVEL;
6898 else
6899 return SKILL_RANGE_MONO;
6900 case SKILL_CATEGORY_ARMOR:
6901 case SKILL_CATEGORY_CLASS:
6902 if(pSkill->id != SKILL_LOCKPICKING)
6903 return SKILL_RANGE_MONO;
6904 else
6905 return SKILL_RANGE_LEVEL;
6906 case SKILL_CATEGORY_SECONDARY:
6907 case SKILL_CATEGORY_PROFESSION:
6908 // not set skills for professions and racial abilities
6909 if(IsProfessionSkill(pSkill->id))
6910 return SKILL_RANGE_RANK;
6911 else if(racial)
6912 return SKILL_RANGE_NONE;
6913 else
6914 return SKILL_RANGE_MONO;
6915 default:
6916 case SKILL_CATEGORY_ATTRIBUTES: //not found in dbc
6917 case SKILL_CATEGORY_GENERIC: //only GENERIC(DND)
6918 return SKILL_RANGE_NONE;
6922 void ObjectMgr::LoadGameTele()
6924 m_GameTeleMap.clear(); // for reload case
6926 uint32 count = 0;
6927 QueryResult *result = WorldDatabase.Query("SELECT id, position_x, position_y, position_z, orientation, map, name FROM game_tele");
6929 if( !result )
6931 barGoLink bar( 1 );
6933 bar.step();
6935 sLog.outString();
6936 sLog.outErrorDb(">> Loaded `game_tele`, table is empty!");
6937 return;
6940 barGoLink bar( result->GetRowCount() );
6944 bar.step();
6946 Field *fields = result->Fetch();
6948 uint32 id = fields[0].GetUInt32();
6950 GameTele gt;
6952 gt.position_x = fields[1].GetFloat();
6953 gt.position_y = fields[2].GetFloat();
6954 gt.position_z = fields[3].GetFloat();
6955 gt.orientation = fields[4].GetFloat();
6956 gt.mapId = fields[5].GetUInt32();
6957 gt.name = fields[6].GetCppString();
6959 if(!MapManager::IsValidMapCoord(gt.mapId,gt.position_x,gt.position_y,gt.position_z,gt.orientation))
6961 sLog.outErrorDb("Wrong position for id %u (name: %s) in `game_tele` table, ignoring.",id,gt.name.c_str());
6962 continue;
6965 if(!Utf8toWStr(gt.name,gt.wnameLow))
6967 sLog.outErrorDb("Wrong UTF8 name for id %u in `game_tele` table, ignoring.",id);
6968 continue;
6971 wstrToLower( gt.wnameLow );
6973 m_GameTeleMap[id] = gt;
6975 ++count;
6977 while (result->NextRow());
6978 delete result;
6980 sLog.outString();
6981 sLog.outString( ">> Loaded %u GameTeleports", count );
6984 GameTele const* ObjectMgr::GetGameTele(const std::string& name) const
6986 // explicit name case
6987 std::wstring wname;
6988 if(!Utf8toWStr(name,wname))
6989 return false;
6991 // converting string that we try to find to lower case
6992 wstrToLower( wname );
6994 // Alternative first GameTele what contains wnameLow as substring in case no GameTele location found
6995 const GameTele* alt = NULL;
6996 for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
6997 if(itr->second.wnameLow == wname)
6998 return &itr->second;
6999 else if (alt == NULL && itr->second.wnameLow.find(wname) != std::wstring::npos)
7000 alt = &itr->second;
7002 return alt;
7005 bool ObjectMgr::AddGameTele(GameTele& tele)
7007 // find max id
7008 uint32 new_id = 0;
7009 for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
7010 if(itr->first > new_id)
7011 new_id = itr->first;
7013 // use next
7014 ++new_id;
7016 if(!Utf8toWStr(tele.name,tele.wnameLow))
7017 return false;
7019 wstrToLower( tele.wnameLow );
7021 m_GameTeleMap[new_id] = tele;
7023 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')",
7024 new_id,tele.position_x,tele.position_y,tele.position_z,tele.orientation,tele.mapId,tele.name.c_str());
7027 bool ObjectMgr::DeleteGameTele(const std::string& name)
7029 // explicit name case
7030 std::wstring wname;
7031 if(!Utf8toWStr(name,wname))
7032 return false;
7034 // converting string that we try to find to lower case
7035 wstrToLower( wname );
7037 for(GameTeleMap::iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
7039 if(itr->second.wnameLow == wname)
7041 WorldDatabase.PExecuteLog("DELETE FROM game_tele WHERE name = '%s'",itr->second.name.c_str());
7042 m_GameTeleMap.erase(itr);
7043 return true;
7047 return false;
7050 void ObjectMgr::LoadTrainerSpell()
7052 // For reload case
7053 for (CacheTrainerSpellMap::iterator itr = m_mCacheTrainerSpellMap.begin(); itr != m_mCacheTrainerSpellMap.end(); ++itr)
7054 itr->second.Clear();
7055 m_mCacheTrainerSpellMap.clear();
7057 std::set<uint32> skip_trainers;
7059 QueryResult *result = WorldDatabase.Query("SELECT entry, spell,spellcost,reqskill,reqskillvalue,reqlevel FROM npc_trainer");
7061 if( !result )
7063 barGoLink bar( 1 );
7065 bar.step();
7067 sLog.outString();
7068 sLog.outErrorDb(">> Loaded `npc_trainer`, table is empty!");
7069 return;
7072 barGoLink bar( result->GetRowCount() );
7074 uint32 count = 0;
7077 bar.step();
7079 Field* fields = result->Fetch();
7081 uint32 entry = fields[0].GetUInt32();
7082 uint32 spell = fields[1].GetUInt32();
7084 CreatureInfo const* cInfo = GetCreatureTemplate(entry);
7086 if(!cInfo)
7088 sLog.outErrorDb("Table `npc_trainer` have entry for not existed creature template (Entry: %u), ignore", entry);
7089 continue;
7092 if(!(cInfo->npcflag & UNIT_NPC_FLAG_TRAINER))
7094 if(skip_trainers.count(entry) == 0)
7096 sLog.outErrorDb("Table `npc_trainer` have data for not creature template (Entry: %u) without trainer flag, ignore", entry);
7097 skip_trainers.insert(entry);
7099 continue;
7102 SpellEntry const *spellinfo = sSpellStore.LookupEntry(spell);
7103 if(!spellinfo)
7105 sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u ) has non existing spell %u, ignore", entry,spell);
7106 continue;
7109 if(!SpellMgr::IsSpellValid(spellinfo))
7111 sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u) has broken learning spell %u, ignore", entry, spell);
7112 continue;
7115 TrainerSpellData& data = m_mCacheTrainerSpellMap[entry];
7117 TrainerSpell& trainerSpell = data.spellList[spell];
7118 trainerSpell.spell = spell;
7119 trainerSpell.spellCost = fields[2].GetUInt32();
7120 trainerSpell.reqSkill = fields[3].GetUInt32();
7121 trainerSpell.reqSkillValue = fields[4].GetUInt32();
7122 trainerSpell.reqLevel = fields[5].GetUInt32();
7124 if(!trainerSpell.reqLevel)
7125 trainerSpell.reqLevel = spellinfo->spellLevel;
7127 // calculate learned spell for profession case when stored cast-spell
7128 trainerSpell.learnedSpell = spell;
7129 for(int i = 0; i <3; ++i)
7131 if(spellinfo->Effect[i] != SPELL_EFFECT_LEARN_SPELL)
7132 continue;
7133 if(SpellMgr::IsProfessionOrRidingSpell(spellinfo->EffectTriggerSpell[i]))
7135 trainerSpell.learnedSpell = spellinfo->EffectTriggerSpell[i];
7136 break;
7140 if(SpellMgr::IsProfessionSpell(trainerSpell.learnedSpell))
7141 data.trainerType = 2;
7143 ++count;
7145 } while (result->NextRow());
7146 delete result;
7148 sLog.outString();
7149 sLog.outString( ">> Loaded %d Trainers", count );
7152 void ObjectMgr::LoadVendors()
7154 // For reload case
7155 for (CacheVendorItemMap::iterator itr = m_mCacheVendorItemMap.begin(); itr != m_mCacheVendorItemMap.end(); ++itr)
7156 itr->second.Clear();
7157 m_mCacheVendorItemMap.clear();
7159 std::set<uint32> skip_vendors;
7161 QueryResult *result = WorldDatabase.Query("SELECT entry, item, maxcount, incrtime, ExtendedCost FROM npc_vendor");
7162 if( !result )
7164 barGoLink bar( 1 );
7166 bar.step();
7168 sLog.outString();
7169 sLog.outErrorDb(">> Loaded `npc_vendor`, table is empty!");
7170 return;
7173 barGoLink bar( result->GetRowCount() );
7175 uint32 count = 0;
7178 bar.step();
7179 Field* fields = result->Fetch();
7181 uint32 entry = fields[0].GetUInt32();
7182 uint32 item_id = fields[1].GetUInt32();
7183 uint32 maxcount = fields[2].GetUInt32();
7184 uint32 incrtime = fields[3].GetUInt32();
7185 uint32 ExtendedCost = fields[4].GetUInt32();
7187 if(!IsVendorItemValid(entry,item_id,maxcount,incrtime,ExtendedCost,NULL,&skip_vendors))
7188 continue;
7190 VendorItemData& vList = m_mCacheVendorItemMap[entry];
7192 vList.AddItem(item_id,maxcount,incrtime,ExtendedCost);
7193 ++count;
7195 } while (result->NextRow());
7196 delete result;
7198 sLog.outString();
7199 sLog.outString( ">> Loaded %d Vendors ", count );
7202 void ObjectMgr::LoadNpcTextId()
7205 m_mCacheNpcTextIdMap.clear();
7207 QueryResult* result = WorldDatabase.Query("SELECT npc_guid, textid FROM npc_gossip");
7208 if( !result )
7210 barGoLink bar( 1 );
7212 bar.step();
7214 sLog.outString();
7215 sLog.outErrorDb(">> Loaded `npc_gossip`, table is empty!");
7216 return;
7219 barGoLink bar( result->GetRowCount() );
7221 uint32 count = 0;
7222 uint32 guid,textid;
7225 bar.step();
7227 Field* fields = result->Fetch();
7229 guid = fields[0].GetUInt32();
7230 textid = fields[1].GetUInt32();
7232 if (!GetCreatureData(guid))
7234 sLog.outErrorDb("Table `npc_gossip` have not existed creature (GUID: %u) entry, ignore. ",guid);
7235 continue;
7237 if (!GetGossipText(textid))
7239 sLog.outErrorDb("Table `npc_gossip` for creature (GUID: %u) have wrong Textid (%u), ignore. ", guid, textid);
7240 continue;
7243 m_mCacheNpcTextIdMap[guid] = textid ;
7244 ++count;
7246 } while (result->NextRow());
7247 delete result;
7249 sLog.outString();
7250 sLog.outString( ">> Loaded %d NpcTextId ", count );
7253 void ObjectMgr::LoadNpcOptions()
7255 m_mCacheNpcOptionList.clear(); // For reload case
7257 QueryResult *result = WorldDatabase.Query(
7258 // 0 1 2 3 4 5 6 7 8
7259 "SELECT id,gossip_id,npcflag,icon,action,box_money,coded,option_text,box_text "
7260 "FROM npc_option");
7262 if( !result )
7264 barGoLink bar( 1 );
7266 bar.step();
7268 sLog.outString();
7269 sLog.outErrorDb(">> Loaded `npc_option`, table is empty!");
7270 return;
7273 barGoLink bar( result->GetRowCount() );
7275 uint32 count = 0;
7279 bar.step();
7281 Field* fields = result->Fetch();
7283 GossipOption go;
7284 go.Id = fields[0].GetUInt32();
7285 go.GossipId = fields[1].GetUInt32();
7286 go.NpcFlag = fields[2].GetUInt32();
7287 go.Icon = fields[3].GetUInt32();
7288 go.Action = fields[4].GetUInt32();
7289 go.BoxMoney = fields[5].GetUInt32();
7290 go.Coded = fields[6].GetUInt8()!=0;
7291 go.OptionText = fields[7].GetCppString();
7292 go.BoxText = fields[8].GetCppString();
7294 m_mCacheNpcOptionList.push_back(go);
7296 ++count;
7298 } while (result->NextRow());
7299 delete result;
7301 sLog.outString();
7302 sLog.outString( ">> Loaded %d npc_option entries", count );
7305 void ObjectMgr::AddVendorItem( uint32 entry,uint32 item, uint32 maxcount, uint32 incrtime, uint32 extendedcost )
7307 VendorItemData& vList = m_mCacheVendorItemMap[entry];
7308 vList.AddItem(item,maxcount,incrtime,extendedcost);
7310 WorldDatabase.PExecuteLog("INSERT INTO npc_vendor (entry,item,maxcount,incrtime,extendedcost) VALUES('%u','%u','%u','%u','%u')",entry, item, maxcount,incrtime,extendedcost);
7313 bool ObjectMgr::RemoveVendorItem( uint32 entry,uint32 item )
7315 CacheVendorItemMap::iterator iter = m_mCacheVendorItemMap.find(entry);
7316 if(iter == m_mCacheVendorItemMap.end())
7317 return false;
7319 if(!iter->second.FindItem(item))
7320 return false;
7322 iter->second.RemoveItem(item);
7323 WorldDatabase.PExecuteLog("DELETE FROM npc_vendor WHERE entry='%u' AND item='%u'",entry, item);
7324 return true;
7327 bool ObjectMgr::IsVendorItemValid( uint32 vendor_entry, uint32 item_id, uint32 maxcount, uint32 incrtime, uint32 ExtendedCost, Player* pl, std::set<uint32>* skip_vendors ) const
7329 CreatureInfo const* cInfo = GetCreatureTemplate(vendor_entry);
7330 if(!cInfo)
7332 if(pl)
7333 ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
7334 else
7335 sLog.outErrorDb("Table `npc_vendor` have data for not existed creature template (Entry: %u), ignore", vendor_entry);
7336 return false;
7339 if(!(cInfo->npcflag & UNIT_NPC_FLAG_VENDOR))
7341 if(!skip_vendors || skip_vendors->count(vendor_entry)==0)
7343 if(pl)
7344 ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
7345 else
7346 sLog.outErrorDb("Table `npc_vendor` have data for not creature template (Entry: %u) without vendor flag, ignore", vendor_entry);
7348 if(skip_vendors)
7349 skip_vendors->insert(vendor_entry);
7351 return false;
7354 if(!GetItemPrototype(item_id))
7356 if(pl)
7357 ChatHandler(pl).PSendSysMessage(LANG_ITEM_NOT_FOUND, item_id);
7358 else
7359 sLog.outErrorDb("Table `npc_vendor` for Vendor (Entry: %u) have in item list non-existed item (%u), ignore",vendor_entry,item_id);
7360 return false;
7363 if(ExtendedCost && !sItemExtendedCostStore.LookupEntry(ExtendedCost))
7365 if(pl)
7366 ChatHandler(pl).PSendSysMessage(LANG_EXTENDED_COST_NOT_EXIST,ExtendedCost);
7367 else
7368 sLog.outErrorDb("Table `npc_vendor` have Item (Entry: %u) with wrong ExtendedCost (%u) for vendor (%u), ignore",item_id,ExtendedCost,vendor_entry);
7369 return false;
7372 if(maxcount > 0 && incrtime == 0)
7374 if(pl)
7375 ChatHandler(pl).PSendSysMessage("MaxCount!=0 (%u) but IncrTime==0", maxcount);
7376 else
7377 sLog.outErrorDb( "Table `npc_vendor` has `maxcount` (%u) for item %u of vendor (Entry: %u) but `incrtime`=0, ignore", maxcount, item_id, vendor_entry);
7378 return false;
7380 else if(maxcount==0 && incrtime > 0)
7382 if(pl)
7383 ChatHandler(pl).PSendSysMessage("MaxCount==0 but IncrTime<>=0");
7384 else
7385 sLog.outErrorDb( "Table `npc_vendor` has `maxcount`=0 for item %u of vendor (Entry: %u) but `incrtime`<>0, ignore", item_id, vendor_entry);
7386 return false;
7389 VendorItemData const* vItems = GetNpcVendorItemList(vendor_entry);
7390 if(!vItems)
7391 return true; // later checks for non-empty lists
7393 if(vItems->FindItem(item_id))
7395 if(pl)
7396 ChatHandler(pl).PSendSysMessage(LANG_ITEM_ALREADY_IN_LIST,item_id);
7397 else
7398 sLog.outErrorDb( "Table `npc_vendor` has duplicate items %u for vendor (Entry: %u), ignore", item_id, vendor_entry);
7399 return false;
7402 if(vItems->GetItemCount() >= MAX_VENDOR_ITEMS)
7404 if(pl)
7405 ChatHandler(pl).SendSysMessage(LANG_COMMAND_ADDVENDORITEMITEMS);
7406 else
7407 sLog.outErrorDb( "Table `npc_vendor` has too many items (%u >= %i) for vendor (Entry: %u), ignore", vItems->GetItemCount(), MAX_VENDOR_ITEMS, vendor_entry);
7408 return false;
7411 return true;
7414 void ObjectMgr::LoadScriptNames()
7416 m_scriptNames.push_back("");
7417 QueryResult *result = WorldDatabase.Query(
7418 "SELECT DISTINCT(ScriptName) FROM creature_template WHERE ScriptName <> '' "
7419 "UNION "
7420 "SELECT DISTINCT(ScriptName) FROM gameobject_template WHERE ScriptName <> '' "
7421 "UNION "
7422 "SELECT DISTINCT(ScriptName) FROM item_template WHERE ScriptName <> '' "
7423 "UNION "
7424 "SELECT DISTINCT(ScriptName) FROM areatrigger_scripts WHERE ScriptName <> '' "
7425 "UNION "
7426 "SELECT DISTINCT(script) FROM instance_template WHERE script <> ''");
7428 if( !result )
7430 barGoLink bar( 1 );
7431 bar.step();
7432 sLog.outString();
7433 sLog.outErrorDb(">> Loaded empty set of Script Names!");
7434 return;
7437 barGoLink bar( result->GetRowCount() );
7438 uint32 count = 0;
7442 bar.step();
7443 m_scriptNames.push_back((*result)[0].GetString());
7444 ++count;
7445 } while (result->NextRow());
7446 delete result;
7448 std::sort(m_scriptNames.begin(), m_scriptNames.end());
7449 sLog.outString();
7450 sLog.outString( ">> Loaded %d Script Names", count );
7453 uint32 ObjectMgr::GetScriptId(const char *name)
7455 // use binary search to find the script name in the sorted vector
7456 // assume "" is the first element
7457 if(!name) return 0;
7458 ScriptNameMap::const_iterator itr =
7459 std::lower_bound(m_scriptNames.begin(), m_scriptNames.end(), name);
7460 if(itr == m_scriptNames.end() || *itr != name) return 0;
7461 return itr - m_scriptNames.begin();
7464 void ObjectMgr::CheckScripts(ScriptMapMap const& scripts,std::set<int32>& ids)
7466 for(ScriptMapMap::const_iterator itrMM = scripts.begin(); itrMM != scripts.end(); ++itrMM)
7468 for(ScriptMap::const_iterator itrM = itrMM->second.begin(); itrM != itrMM->second.end(); ++itrM)
7470 switch(itrM->second.command)
7472 case SCRIPT_COMMAND_TALK:
7474 if(!GetMangosStringLocale (itrM->second.dataint))
7475 sLog.outErrorDb( "Table `db_script_string` not has string id %u used db script (ID: %u)", itrM->second.dataint, itrMM->first);
7477 if(ids.count(itrM->second.dataint))
7478 ids.erase(itrM->second.dataint);
7485 void ObjectMgr::LoadDbScriptStrings()
7487 LoadMangosStrings(WorldDatabase,"db_script_string",MIN_DB_SCRIPT_STRING_ID,MAX_DB_SCRIPT_STRING_ID);
7489 std::set<int32> ids;
7491 for(int32 i = MIN_DB_SCRIPT_STRING_ID; i < MAX_DB_SCRIPT_STRING_ID; ++i)
7492 if(GetMangosStringLocale(i))
7493 ids.insert(i);
7495 CheckScripts(sQuestEndScripts,ids);
7496 CheckScripts(sQuestStartScripts,ids);
7497 CheckScripts(sSpellScripts,ids);
7498 CheckScripts(sGameObjectScripts,ids);
7499 CheckScripts(sEventScripts,ids);
7501 WaypointMgr.CheckTextsExistance(ids);
7503 for(std::set<int32>::const_iterator itr = ids.begin(); itr != ids.end(); ++itr)
7504 sLog.outErrorDb( "Table `db_script_string` has unused string id %u", *itr);
7507 // Functions for scripting access
7508 uint32 GetAreaTriggerScriptId(uint32 trigger_id)
7510 return objmgr.GetAreaTriggerScriptId(trigger_id);
7513 bool LoadMangosStrings(DatabaseType& db, char const* table,int32 start_value, int32 end_value)
7515 // MAX_DB_SCRIPT_STRING_ID is max allowed negative value for scripts (scrpts can use only more deep negative values
7516 // start/end reversed for negative values
7517 if (start_value > MAX_DB_SCRIPT_STRING_ID || end_value >= start_value)
7519 sLog.outErrorDb("Table '%s' attempt loaded with reserved by mangos range (%d - %d), strings not loaded.",table,start_value,end_value+1);
7520 return false;
7523 return objmgr.LoadMangosStrings(db,table,start_value,end_value);
7526 uint32 MANGOS_DLL_SPEC GetScriptId(const char *name)
7528 return objmgr.GetScriptId(name);
7531 ObjectMgr::ScriptNameMap & GetScriptNames()
7533 return objmgr.GetScriptNames();
7536 CreatureInfo const* GetCreatureTemplateStore(uint32 entry)
7538 return sCreatureStorage.LookupEntry<CreatureInfo>(entry);
7541 Quest const* GetQuestTemplateStore(uint32 entry)
7543 return objmgr.GetQuestTemplate(entry);