[7945] Implement support quest data for DetailsEmoteDelay and OfferRewardEmoteDelay...
[getmangos.git] / src / game / ObjectMgr.cpp
blob0f1fbdb04b211bbd3e395b1bd68757f03e686125
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
2854 "DetailsEmote1, DetailsEmote2, DetailsEmote3, DetailsEmote4, DetailsEmoteDelay1, DetailsEmoteDelay2, DetailsEmoteDelay3, DetailsEmoteDelay4,"
2855 // 116 117 118 119 120 121
2856 "IncompleteEmote, CompleteEmote, OfferRewardEmote1, OfferRewardEmote2, OfferRewardEmote3, OfferRewardEmote4,"
2857 // 122 123 124 125
2858 "OfferRewardEmoteDelay1, OfferRewardEmoteDelay2, OfferRewardEmoteDelay3, OfferRewardEmoteDelay4,"
2859 // 126 127
2860 "StartScript, CompleteScript"
2861 " FROM quest_template");
2862 if(result == NULL)
2864 barGoLink bar( 1 );
2865 bar.step();
2867 sLog.outString();
2868 sLog.outString( ">> Loaded 0 quests definitions" );
2869 sLog.outErrorDb("`quest_template` table is empty!");
2870 return;
2873 // create multimap previous quest for each existed quest
2874 // some quests can have many previous maps set by NextQuestId in previous quest
2875 // for example set of race quests can lead to single not race specific quest
2876 barGoLink bar( result->GetRowCount() );
2879 bar.step();
2880 Field *fields = result->Fetch();
2882 Quest * newQuest = new Quest(fields);
2883 mQuestTemplates[newQuest->GetQuestId()] = newQuest;
2884 } while( result->NextRow() );
2886 delete result;
2888 // Post processing
2889 for (QuestMap::iterator iter = mQuestTemplates.begin(); iter != mQuestTemplates.end(); ++iter)
2891 Quest * qinfo = iter->second;
2893 // additional quest integrity checks (GO, creature_template and item_template must be loaded already)
2895 if( qinfo->GetQuestMethod() >= 3 )
2897 sLog.outErrorDb("Quest %u has `Method` = %u, expected values are 0, 1 or 2.",qinfo->GetQuestId(),qinfo->GetQuestMethod());
2900 if (qinfo->QuestFlags & ~QUEST_MANGOS_FLAGS_DB_ALLOWED)
2902 sLog.outErrorDb("Quest %u has `SpecialFlags` = %u > max allowed value. Correct `SpecialFlags` to value <= %u",
2903 qinfo->GetQuestId(),qinfo->QuestFlags,QUEST_MANGOS_FLAGS_DB_ALLOWED >> 16);
2904 qinfo->QuestFlags &= QUEST_MANGOS_FLAGS_DB_ALLOWED;
2907 if(qinfo->QuestFlags & QUEST_FLAGS_DAILY)
2909 if(!(qinfo->QuestFlags & QUEST_MANGOS_FLAGS_REPEATABLE))
2911 sLog.outErrorDb("Daily Quest %u not marked as repeatable in `SpecialFlags`, added.",qinfo->GetQuestId());
2912 qinfo->QuestFlags |= QUEST_MANGOS_FLAGS_REPEATABLE;
2916 if(qinfo->QuestFlags & QUEST_FLAGS_AUTO_REWARDED)
2918 // at auto-reward can be rewarded only RewChoiceItemId[0]
2919 for(int j = 1; j < QUEST_REWARD_CHOICES_COUNT; ++j )
2921 if(uint32 id = qinfo->RewChoiceItemId[j])
2923 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item from `RewChoiceItemId%d` can't be rewarded with quest flag QUEST_FLAGS_AUTO_REWARDED.",
2924 qinfo->GetQuestId(),j+1,id,j+1);
2925 // no changes, quest ignore this data
2930 // client quest log visual (area case)
2931 if( qinfo->ZoneOrSort > 0 )
2933 if(!GetAreaEntryByAreaID(qinfo->ZoneOrSort))
2935 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %u (zone case) but zone with this id does not exist.",
2936 qinfo->GetQuestId(),qinfo->ZoneOrSort);
2937 // no changes, quest not dependent from this value but can have problems at client
2940 // client quest log visual (sort case)
2941 if( qinfo->ZoneOrSort < 0 )
2943 QuestSortEntry const* qSort = sQuestSortStore.LookupEntry(-int32(qinfo->ZoneOrSort));
2944 if( !qSort )
2946 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (sort case) but quest sort with this id does not exist.",
2947 qinfo->GetQuestId(),qinfo->ZoneOrSort);
2948 // 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)
2950 //check SkillOrClass value (class case).
2951 if( ClassByQuestSort(-int32(qinfo->ZoneOrSort)) )
2953 // SkillOrClass should not have class case when class case already set in ZoneOrSort.
2954 if(qinfo->SkillOrClass < 0)
2956 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (class sort case) and `SkillOrClass` = %i (class case), redundant.",
2957 qinfo->GetQuestId(),qinfo->ZoneOrSort,qinfo->SkillOrClass);
2960 //check for proper SkillOrClass value (skill case)
2961 if(int32 skill_id = SkillByQuestSort(-int32(qinfo->ZoneOrSort)))
2963 // skill is positive value in SkillOrClass
2964 if(qinfo->SkillOrClass != skill_id )
2966 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (skill sort case) but `SkillOrClass` does not have a corresponding value (%i).",
2967 qinfo->GetQuestId(),qinfo->ZoneOrSort,skill_id);
2968 //override, and force proper value here?
2973 // SkillOrClass (class case)
2974 if( qinfo->SkillOrClass < 0 )
2976 if( !sChrClassesStore.LookupEntry(-int32(qinfo->SkillOrClass)) )
2978 sLog.outErrorDb("Quest %u has `SkillOrClass` = %i (class case) but class (%i) does not exist",
2979 qinfo->GetQuestId(),qinfo->SkillOrClass,-qinfo->SkillOrClass);
2982 // SkillOrClass (skill case)
2983 if( qinfo->SkillOrClass > 0 )
2985 if( !sSkillLineStore.LookupEntry(qinfo->SkillOrClass) )
2987 sLog.outErrorDb("Quest %u has `SkillOrClass` = %u (skill case) but skill (%i) does not exist",
2988 qinfo->GetQuestId(),qinfo->SkillOrClass,qinfo->SkillOrClass);
2992 if( qinfo->RequiredSkillValue )
2994 if( qinfo->RequiredSkillValue > sWorld.GetConfigMaxSkillValue() )
2996 sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but max possible skill is %u, quest can't be done.",
2997 qinfo->GetQuestId(),qinfo->RequiredSkillValue,sWorld.GetConfigMaxSkillValue());
2998 // no changes, quest can't be done for this requirement
3001 if( qinfo->SkillOrClass <= 0 )
3003 sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but `SkillOrClass` = %i (class case), value ignored.",
3004 qinfo->GetQuestId(),qinfo->RequiredSkillValue,qinfo->SkillOrClass);
3005 // no changes, quest can't be done for this requirement (fail at wrong skill id)
3008 // else Skill quests can have 0 skill level, this is ok
3010 if(qinfo->RepObjectiveFaction && !sFactionStore.LookupEntry(qinfo->RepObjectiveFaction))
3012 sLog.outErrorDb("Quest %u has `RepObjectiveFaction` = %u but faction template %u does not exist, quest can't be done.",
3013 qinfo->GetQuestId(),qinfo->RepObjectiveFaction,qinfo->RepObjectiveFaction);
3014 // no changes, quest can't be done for this requirement
3017 if(qinfo->RequiredMinRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMinRepFaction))
3019 sLog.outErrorDb("Quest %u has `RequiredMinRepFaction` = %u but faction template %u does not exist, quest can't be done.",
3020 qinfo->GetQuestId(),qinfo->RequiredMinRepFaction,qinfo->RequiredMinRepFaction);
3021 // no changes, quest can't be done for this requirement
3024 if(qinfo->RequiredMaxRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMaxRepFaction))
3026 sLog.outErrorDb("Quest %u has `RequiredMaxRepFaction` = %u but faction template %u does not exist, quest can't be done.",
3027 qinfo->GetQuestId(),qinfo->RequiredMaxRepFaction,qinfo->RequiredMaxRepFaction);
3028 // no changes, quest can't be done for this requirement
3031 if(qinfo->RequiredMinRepValue && qinfo->RequiredMinRepValue > ReputationMgr::Reputation_Cap)
3033 sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but max reputation is %u, quest can't be done.",
3034 qinfo->GetQuestId(),qinfo->RequiredMinRepValue,ReputationMgr::Reputation_Cap);
3035 // no changes, quest can't be done for this requirement
3038 if(qinfo->RequiredMinRepValue && qinfo->RequiredMaxRepValue && qinfo->RequiredMaxRepValue <= qinfo->RequiredMinRepValue)
3040 sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d and `RequiredMinRepValue` = %d, quest can't be done.",
3041 qinfo->GetQuestId(),qinfo->RequiredMaxRepValue,qinfo->RequiredMinRepValue);
3042 // no changes, quest can't be done for this requirement
3045 if(!qinfo->RepObjectiveFaction && qinfo->RepObjectiveValue > 0 )
3047 sLog.outErrorDb("Quest %u has `RepObjectiveValue` = %d but `RepObjectiveFaction` is 0, value has no effect",
3048 qinfo->GetQuestId(),qinfo->RepObjectiveValue);
3049 // warning
3052 if(!qinfo->RequiredMinRepFaction && qinfo->RequiredMinRepValue > 0 )
3054 sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but `RequiredMinRepFaction` is 0, value has no effect",
3055 qinfo->GetQuestId(),qinfo->RequiredMinRepValue);
3056 // warning
3059 if(!qinfo->RequiredMaxRepFaction && qinfo->RequiredMaxRepValue > 0 )
3061 sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d but `RequiredMaxRepFaction` is 0, value has no effect",
3062 qinfo->GetQuestId(),qinfo->RequiredMaxRepValue);
3063 // warning
3066 if(qinfo->CharTitleId && !sCharTitlesStore.LookupEntry(qinfo->CharTitleId))
3068 sLog.outErrorDb("Quest %u has `CharTitleId` = %u but CharTitle Id %u does not exist, quest can't be rewarded with title.",
3069 qinfo->GetQuestId(),qinfo->GetCharTitleId(),qinfo->GetCharTitleId());
3070 qinfo->CharTitleId = 0;
3071 // quest can't reward this title
3074 if(qinfo->SrcItemId)
3076 if(!sItemStorage.LookupEntry<ItemPrototype>(qinfo->SrcItemId))
3078 sLog.outErrorDb("Quest %u has `SrcItemId` = %u but item with entry %u does not exist, quest can't be done.",
3079 qinfo->GetQuestId(),qinfo->SrcItemId,qinfo->SrcItemId);
3080 qinfo->SrcItemId = 0; // quest can't be done for this requirement
3082 else if(qinfo->SrcItemCount==0)
3084 sLog.outErrorDb("Quest %u has `SrcItemId` = %u but `SrcItemCount` = 0, set to 1 but need fix in DB.",
3085 qinfo->GetQuestId(),qinfo->SrcItemId);
3086 qinfo->SrcItemCount = 1; // update to 1 for allow quest work for backward compatibility with DB
3089 else if(qinfo->SrcItemCount>0)
3091 sLog.outErrorDb("Quest %u has `SrcItemId` = 0 but `SrcItemCount` = %u, useless value.",
3092 qinfo->GetQuestId(),qinfo->SrcItemCount);
3093 qinfo->SrcItemCount=0; // no quest work changes in fact
3096 if(qinfo->SrcSpell)
3098 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->SrcSpell);
3099 if(!spellInfo)
3101 sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u doesn't exist, quest can't be done.",
3102 qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
3103 qinfo->SrcSpell = 0; // quest can't be done for this requirement
3105 else if(!SpellMgr::IsSpellValid(spellInfo))
3107 sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u is broken, quest can't be done.",
3108 qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
3109 qinfo->SrcSpell = 0; // quest can't be done for this requirement
3113 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3115 uint32 id = qinfo->ReqItemId[j];
3116 if(id)
3118 if(qinfo->ReqItemCount[j]==0)
3120 sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but `ReqItemCount%d` = 0, quest can't be done.",
3121 qinfo->GetQuestId(),j+1,id,j+1);
3122 // no changes, quest can't be done for this requirement
3125 qinfo->SetFlag(QUEST_MANGOS_FLAGS_DELIVER);
3127 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3129 sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but item with entry %u does not exist, quest can't be done.",
3130 qinfo->GetQuestId(),j+1,id,id);
3131 qinfo->ReqItemCount[j] = 0; // prevent incorrect work of quest
3134 else if(qinfo->ReqItemCount[j]>0)
3136 sLog.outErrorDb("Quest %u has `ReqItemId%d` = 0 but `ReqItemCount%d` = %u, quest can't be done.",
3137 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqItemCount[j]);
3138 qinfo->ReqItemCount[j] = 0; // prevent incorrect work of quest
3142 for(int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j )
3144 uint32 id = qinfo->ReqSourceId[j];
3145 if(id)
3147 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3149 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but item with entry %u does not exist, quest can't be done.",
3150 qinfo->GetQuestId(),j+1,id,id);
3151 // no changes, quest can't be done for this requirement
3154 else
3156 if(qinfo->ReqSourceCount[j]>0)
3158 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = 0 but `ReqSourceCount%d` = %u.",
3159 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqSourceCount[j]);
3160 // no changes, quest ignore this data
3165 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3167 uint32 id = qinfo->ReqSpell[j];
3168 if(id)
3170 SpellEntry const* spellInfo = sSpellStore.LookupEntry(id);
3171 if(!spellInfo)
3173 sLog.outErrorDb("Quest %u has `ReqSpellCast%d` = %u but spell %u does not exist, quest can't be done.",
3174 qinfo->GetQuestId(),j+1,id,id);
3175 continue;
3178 if(!qinfo->ReqCreatureOrGOId[j])
3180 bool found = false;
3181 for(int k = 0; k < 3; ++k)
3183 if( spellInfo->Effect[k]==SPELL_EFFECT_QUEST_COMPLETE && uint32(spellInfo->EffectMiscValue[k])==qinfo->QuestId ||
3184 spellInfo->Effect[k]==SPELL_EFFECT_SEND_EVENT)
3186 found = true;
3187 break;
3191 if(found)
3193 if(!qinfo->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3195 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);
3197 // this will prevent quest completing without objective
3198 const_cast<Quest*>(qinfo)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3201 else
3203 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.",
3204 qinfo->GetQuestId(),j+1,id,j+1,id);
3205 // no changes, quest can't be done for this requirement
3211 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3213 int32 id = qinfo->ReqCreatureOrGOId[j];
3214 if(id < 0 && !sGOStorage.LookupEntry<GameObjectInfo>(-id))
3216 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but gameobject %u does not exist, quest can't be done.",
3217 qinfo->GetQuestId(),j+1,id,uint32(-id));
3218 qinfo->ReqCreatureOrGOId[j] = 0; // quest can't be done for this requirement
3221 if(id > 0 && !sCreatureStorage.LookupEntry<CreatureInfo>(id))
3223 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but creature with entry %u does not exist, quest can't be done.",
3224 qinfo->GetQuestId(),j+1,id,uint32(id));
3225 qinfo->ReqCreatureOrGOId[j] = 0; // quest can't be done for this requirement
3228 if(id)
3230 // In fact SpeakTo and Kill are quite same: either you can speak to mob:SpeakTo or you can't:Kill/Cast
3232 qinfo->SetFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO);
3234 if(!qinfo->ReqCreatureOrGOCount[j])
3236 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %u but `ReqCreatureOrGOCount%d` = 0, quest can't be done.",
3237 qinfo->GetQuestId(),j+1,id,j+1);
3238 // no changes, quest can be incorrectly done, but we already report this
3241 else if(qinfo->ReqCreatureOrGOCount[j]>0)
3243 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = 0 but `ReqCreatureOrGOCount%d` = %u.",
3244 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqCreatureOrGOCount[j]);
3245 // no changes, quest ignore this data
3249 for(int j = 0; j < QUEST_REWARD_CHOICES_COUNT; ++j )
3251 uint32 id = qinfo->RewChoiceItemId[j];
3252 if(id)
3254 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3256 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3257 qinfo->GetQuestId(),j+1,id,id);
3258 qinfo->RewChoiceItemId[j] = 0; // no changes, quest will not reward this
3261 if(!qinfo->RewChoiceItemCount[j])
3263 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but `RewChoiceItemCount%d` = 0, quest can't be done.",
3264 qinfo->GetQuestId(),j+1,id,j+1);
3265 // no changes, quest can't be done
3268 else if(qinfo->RewChoiceItemCount[j]>0)
3270 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = 0 but `RewChoiceItemCount%d` = %u.",
3271 qinfo->GetQuestId(),j+1,j+1,qinfo->RewChoiceItemCount[j]);
3272 // no changes, quest ignore this data
3276 for(int j = 0; j < QUEST_REWARDS_COUNT; ++j )
3278 uint32 id = qinfo->RewItemId[j];
3279 if(id)
3281 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3283 sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3284 qinfo->GetQuestId(),j+1,id,id);
3285 qinfo->RewItemId[j] = 0; // no changes, quest will not reward this item
3288 if(!qinfo->RewItemCount[j])
3290 sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but `RewItemCount%d` = 0, quest will not reward this item.",
3291 qinfo->GetQuestId(),j+1,id,j+1);
3292 // no changes
3295 else if(qinfo->RewItemCount[j]>0)
3297 sLog.outErrorDb("Quest %u has `RewItemId%d` = 0 but `RewItemCount%d` = %u.",
3298 qinfo->GetQuestId(),j+1,j+1,qinfo->RewItemCount[j]);
3299 // no changes, quest ignore this data
3303 for(int j = 0; j < QUEST_REPUTATIONS_COUNT; ++j)
3305 if(qinfo->RewRepFaction[j])
3307 if(!qinfo->RewRepValue[j])
3309 sLog.outErrorDb("Quest %u has `RewRepFaction%d` = %u but `RewRepValue%d` = 0, quest will not reward this reputation.",
3310 qinfo->GetQuestId(),j+1,qinfo->RewRepValue[j],j+1);
3311 // no changes
3314 if(!sFactionStore.LookupEntry(qinfo->RewRepFaction[j]))
3316 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.",
3317 qinfo->GetQuestId(),j+1,qinfo->RewRepFaction[j] ,qinfo->RewRepFaction[j] );
3318 qinfo->RewRepFaction[j] = 0; // quest will not reward this
3321 else if(qinfo->RewRepValue[j]!=0)
3323 sLog.outErrorDb("Quest %u has `RewRepFaction%d` = 0 but `RewRepValue%d` = %u.",
3324 qinfo->GetQuestId(),j+1,j+1,qinfo->RewRepValue[j]);
3325 // no changes, quest ignore this data
3329 if(qinfo->RewSpell)
3331 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpell);
3333 if(!spellInfo)
3335 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u does not exist, spell removed as display reward.",
3336 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3337 qinfo->RewSpell = 0; // no spell reward will display for this quest
3340 else if(!SpellMgr::IsSpellValid(spellInfo))
3342 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u is broken, quest can't be done.",
3343 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3344 qinfo->RewSpell = 0; // no spell reward will display for this quest
3349 if(qinfo->RewSpellCast)
3351 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpellCast);
3353 if(!spellInfo)
3355 sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u does not exist, quest will not have a spell reward.",
3356 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3357 qinfo->RewSpellCast = 0; // no spell will be casted on player
3360 else if(!SpellMgr::IsSpellValid(spellInfo))
3362 sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u is broken, quest can't be done.",
3363 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3364 qinfo->RewSpellCast = 0; // no spell will be casted on player
3369 if(qinfo->RewMailTemplateId)
3371 if(!sMailTemplateStore.LookupEntry(qinfo->RewMailTemplateId))
3373 sLog.outErrorDb("Quest %u has `RewMailTemplateId` = %u but mail template %u does not exist, quest will not have a mail reward.",
3374 qinfo->GetQuestId(),qinfo->RewMailTemplateId,qinfo->RewMailTemplateId);
3375 qinfo->RewMailTemplateId = 0; // no mail will send to player
3376 qinfo->RewMailDelaySecs = 0; // no mail will send to player
3380 if(qinfo->NextQuestInChain)
3382 QuestMap::iterator qNextItr = mQuestTemplates.find(qinfo->NextQuestInChain);
3383 if(qNextItr == mQuestTemplates.end())
3385 sLog.outErrorDb("Quest %u has `NextQuestInChain` = %u but quest %u does not exist, quest chain will not work.",
3386 qinfo->GetQuestId(),qinfo->NextQuestInChain ,qinfo->NextQuestInChain );
3387 qinfo->NextQuestInChain = 0;
3389 else
3390 qNextItr->second->prevChainQuests.push_back(qinfo->GetQuestId());
3393 // fill additional data stores
3394 if(qinfo->PrevQuestId)
3396 if (mQuestTemplates.find(abs(qinfo->GetPrevQuestId())) == mQuestTemplates.end())
3398 sLog.outErrorDb("Quest %d has PrevQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetPrevQuestId());
3400 else
3402 qinfo->prevQuests.push_back(qinfo->PrevQuestId);
3406 if(qinfo->NextQuestId)
3408 QuestMap::iterator qNextItr = mQuestTemplates.find(abs(qinfo->GetNextQuestId()));
3409 if (qNextItr == mQuestTemplates.end())
3411 sLog.outErrorDb("Quest %d has NextQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetNextQuestId());
3413 else
3415 int32 signedQuestId = qinfo->NextQuestId < 0 ? -int32(qinfo->GetQuestId()) : int32(qinfo->GetQuestId());
3416 qNextItr->second->prevQuests.push_back(signedQuestId);
3420 if(qinfo->ExclusiveGroup)
3421 mExclusiveQuestGroups.insert(std::pair<int32, uint32>(qinfo->ExclusiveGroup, qinfo->GetQuestId()));
3422 if(qinfo->LimitTime)
3423 qinfo->SetFlag(QUEST_MANGOS_FLAGS_TIMED);
3426 // check QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT for spell with SPELL_EFFECT_QUEST_COMPLETE
3427 for (uint32 i = 0; i < sSpellStore.GetNumRows(); ++i)
3429 SpellEntry const *spellInfo = sSpellStore.LookupEntry(i);
3430 if(!spellInfo)
3431 continue;
3433 for(int j = 0; j < 3; ++j)
3435 if(spellInfo->Effect[j] != SPELL_EFFECT_QUEST_COMPLETE)
3436 continue;
3438 uint32 quest_id = spellInfo->EffectMiscValue[j];
3440 Quest const* quest = GetQuestTemplate(quest_id);
3442 // some quest referenced in spells not exist (outdated spells)
3443 if(!quest)
3444 continue;
3446 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3448 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);
3450 // this will prevent quest completing without objective
3451 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3456 sLog.outString();
3457 sLog.outString( ">> Loaded %lu quests definitions", (unsigned long)mQuestTemplates.size() );
3460 void ObjectMgr::LoadQuestLocales()
3462 mQuestLocaleMap.clear(); // need for reload case
3464 QueryResult *result = WorldDatabase.Query("SELECT entry,"
3465 "Title_loc1,Details_loc1,Objectives_loc1,OfferRewardText_loc1,RequestItemsText_loc1,EndText_loc1,ObjectiveText1_loc1,ObjectiveText2_loc1,ObjectiveText3_loc1,ObjectiveText4_loc1,"
3466 "Title_loc2,Details_loc2,Objectives_loc2,OfferRewardText_loc2,RequestItemsText_loc2,EndText_loc2,ObjectiveText1_loc2,ObjectiveText2_loc2,ObjectiveText3_loc2,ObjectiveText4_loc2,"
3467 "Title_loc3,Details_loc3,Objectives_loc3,OfferRewardText_loc3,RequestItemsText_loc3,EndText_loc3,ObjectiveText1_loc3,ObjectiveText2_loc3,ObjectiveText3_loc3,ObjectiveText4_loc3,"
3468 "Title_loc4,Details_loc4,Objectives_loc4,OfferRewardText_loc4,RequestItemsText_loc4,EndText_loc4,ObjectiveText1_loc4,ObjectiveText2_loc4,ObjectiveText3_loc4,ObjectiveText4_loc4,"
3469 "Title_loc5,Details_loc5,Objectives_loc5,OfferRewardText_loc5,RequestItemsText_loc5,EndText_loc5,ObjectiveText1_loc5,ObjectiveText2_loc5,ObjectiveText3_loc5,ObjectiveText4_loc5,"
3470 "Title_loc6,Details_loc6,Objectives_loc6,OfferRewardText_loc6,RequestItemsText_loc6,EndText_loc6,ObjectiveText1_loc6,ObjectiveText2_loc6,ObjectiveText3_loc6,ObjectiveText4_loc6,"
3471 "Title_loc7,Details_loc7,Objectives_loc7,OfferRewardText_loc7,RequestItemsText_loc7,EndText_loc7,ObjectiveText1_loc7,ObjectiveText2_loc7,ObjectiveText3_loc7,ObjectiveText4_loc7,"
3472 "Title_loc8,Details_loc8,Objectives_loc8,OfferRewardText_loc8,RequestItemsText_loc8,EndText_loc8,ObjectiveText1_loc8,ObjectiveText2_loc8,ObjectiveText3_loc8,ObjectiveText4_loc8"
3473 " FROM locales_quest"
3476 if(!result)
3478 barGoLink bar(1);
3480 bar.step();
3482 sLog.outString();
3483 sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_quest` is empty.");
3484 return;
3487 barGoLink bar(result->GetRowCount());
3491 Field *fields = result->Fetch();
3492 bar.step();
3494 uint32 entry = fields[0].GetUInt32();
3496 QuestLocale& data = mQuestLocaleMap[entry];
3498 for(int i = 1; i < MAX_LOCALE; ++i)
3500 std::string str = fields[1+10*(i-1)].GetCppString();
3501 if(!str.empty())
3503 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3504 if(idx >= 0)
3506 if(data.Title.size() <= idx)
3507 data.Title.resize(idx+1);
3509 data.Title[idx] = str;
3512 str = fields[1+10*(i-1)+1].GetCppString();
3513 if(!str.empty())
3515 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3516 if(idx >= 0)
3518 if(data.Details.size() <= idx)
3519 data.Details.resize(idx+1);
3521 data.Details[idx] = str;
3524 str = fields[1+10*(i-1)+2].GetCppString();
3525 if(!str.empty())
3527 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3528 if(idx >= 0)
3530 if(data.Objectives.size() <= idx)
3531 data.Objectives.resize(idx+1);
3533 data.Objectives[idx] = str;
3536 str = fields[1+10*(i-1)+3].GetCppString();
3537 if(!str.empty())
3539 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3540 if(idx >= 0)
3542 if(data.OfferRewardText.size() <= idx)
3543 data.OfferRewardText.resize(idx+1);
3545 data.OfferRewardText[idx] = str;
3548 str = fields[1+10*(i-1)+4].GetCppString();
3549 if(!str.empty())
3551 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3552 if(idx >= 0)
3554 if(data.RequestItemsText.size() <= idx)
3555 data.RequestItemsText.resize(idx+1);
3557 data.RequestItemsText[idx] = str;
3560 str = fields[1+10*(i-1)+5].GetCppString();
3561 if(!str.empty())
3563 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3564 if(idx >= 0)
3566 if(data.EndText.size() <= idx)
3567 data.EndText.resize(idx+1);
3569 data.EndText[idx] = str;
3572 for(int k = 0; k < 4; ++k)
3574 str = fields[1+10*(i-1)+6+k].GetCppString();
3575 if(!str.empty())
3577 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3578 if(idx >= 0)
3580 if(data.ObjectiveText[k].size() <= idx)
3581 data.ObjectiveText[k].resize(idx+1);
3583 data.ObjectiveText[k][idx] = str;
3588 } while (result->NextRow());
3590 delete result;
3592 sLog.outString();
3593 sLog.outString( ">> Loaded %lu Quest locale strings", (unsigned long)mQuestLocaleMap.size() );
3596 void ObjectMgr::LoadScripts(ScriptMapMap& scripts, char const* tablename)
3598 if(sWorld.IsScriptScheduled()) // function don't must be called in time scripts use.
3599 return;
3601 sLog.outString( "%s :", tablename);
3603 scripts.clear(); // need for reload support
3605 QueryResult *result = WorldDatabase.PQuery( "SELECT id,delay,command,datalong,datalong2,dataint, x, y, z, o FROM %s", tablename );
3607 uint32 count = 0;
3609 if( !result )
3611 barGoLink bar( 1 );
3612 bar.step();
3614 sLog.outString();
3615 sLog.outString( ">> Loaded %u script definitions", count );
3616 return;
3619 barGoLink bar( result->GetRowCount() );
3623 bar.step();
3625 Field *fields = result->Fetch();
3626 ScriptInfo tmp;
3627 tmp.id = fields[0].GetUInt32();
3628 tmp.delay = fields[1].GetUInt32();
3629 tmp.command = fields[2].GetUInt32();
3630 tmp.datalong = fields[3].GetUInt32();
3631 tmp.datalong2 = fields[4].GetUInt32();
3632 tmp.dataint = fields[5].GetInt32();
3633 tmp.x = fields[6].GetFloat();
3634 tmp.y = fields[7].GetFloat();
3635 tmp.z = fields[8].GetFloat();
3636 tmp.o = fields[9].GetFloat();
3638 // generic command args check
3639 switch(tmp.command)
3641 case SCRIPT_COMMAND_TALK:
3643 if(tmp.datalong > 3)
3645 sLog.outErrorDb("Table `%s` has invalid talk type (datalong = %u) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.datalong,tmp.id);
3646 continue;
3648 if(tmp.dataint==0)
3650 sLog.outErrorDb("Table `%s` has invalid talk text id (dataint = %i) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.dataint,tmp.id);
3651 continue;
3653 if(tmp.dataint < MIN_DB_SCRIPT_STRING_ID || tmp.dataint >= MAX_DB_SCRIPT_STRING_ID)
3655 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);
3656 continue;
3659 // if(!objmgr.GetMangosStringLocale(tmp.dataint)) will checked after db_script_string loading
3660 break;
3663 case SCRIPT_COMMAND_EMOTE:
3665 if(!sEmotesStore.LookupEntry(tmp.datalong))
3667 sLog.outErrorDb("Table `%s` has invalid emote id (datalong = %u) in SCRIPT_COMMAND_EMOTE for script id %u",tablename,tmp.datalong,tmp.id);
3668 continue;
3670 break;
3673 case SCRIPT_COMMAND_TELEPORT_TO:
3675 if(!sMapStore.LookupEntry(tmp.datalong))
3677 sLog.outErrorDb("Table `%s` has invalid map (Id: %u) in SCRIPT_COMMAND_TELEPORT_TO for script id %u",tablename,tmp.datalong,tmp.id);
3678 continue;
3681 if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
3683 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);
3684 continue;
3686 break;
3689 case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
3691 if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
3693 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);
3694 continue;
3697 if(!GetCreatureTemplate(tmp.datalong))
3699 sLog.outErrorDb("Table `%s` has invalid creature (Entry: %u) in SCRIPT_COMMAND_TEMP_SUMMON_CREATURE for script id %u",tablename,tmp.datalong,tmp.id);
3700 continue;
3702 break;
3705 case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
3707 GameObjectData const* data = GetGOData(tmp.datalong);
3708 if(!data)
3710 sLog.outErrorDb("Table `%s` has invalid gameobject (GUID: %u) in SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,tmp.datalong,tmp.id);
3711 continue;
3714 GameObjectInfo const* info = GetGameObjectInfo(data->id);
3715 if(!info)
3717 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);
3718 continue;
3721 if( info->type==GAMEOBJECT_TYPE_FISHINGNODE ||
3722 info->type==GAMEOBJECT_TYPE_FISHINGHOLE ||
3723 info->type==GAMEOBJECT_TYPE_DOOR ||
3724 info->type==GAMEOBJECT_TYPE_BUTTON ||
3725 info->type==GAMEOBJECT_TYPE_TRAP )
3727 sLog.outErrorDb("Table `%s` have gameobject type (%u) unsupported by command SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,info->id,tmp.id);
3728 continue;
3730 break;
3732 case SCRIPT_COMMAND_OPEN_DOOR:
3733 case SCRIPT_COMMAND_CLOSE_DOOR:
3735 GameObjectData const* data = GetGOData(tmp.datalong);
3736 if(!data)
3738 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);
3739 continue;
3742 GameObjectInfo const* info = GetGameObjectInfo(data->id);
3743 if(!info)
3745 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);
3746 continue;
3749 if( info->type!=GAMEOBJECT_TYPE_DOOR)
3751 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);
3752 continue;
3755 break;
3757 case SCRIPT_COMMAND_QUEST_EXPLORED:
3759 Quest const* quest = GetQuestTemplate(tmp.datalong);
3760 if(!quest)
3762 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);
3763 continue;
3766 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3768 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);
3770 // this will prevent quest completing without objective
3771 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3773 // continue; - quest objective requirement set and command can be allowed
3776 if(float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
3778 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",
3779 tablename,tmp.datalong2,tmp.id);
3780 continue;
3783 if(tmp.datalong2 && float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
3785 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",
3786 tablename,tmp.datalong2,tmp.id,DEFAULT_VISIBILITY_DISTANCE);
3787 continue;
3790 if(tmp.datalong2 && float(tmp.datalong2) < INTERACTION_DISTANCE)
3792 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",
3793 tablename,tmp.datalong2,tmp.id,INTERACTION_DISTANCE);
3794 continue;
3797 break;
3800 case SCRIPT_COMMAND_REMOVE_AURA:
3802 if(!sSpellStore.LookupEntry(tmp.datalong))
3804 sLog.outErrorDb("Table `%s` using non-existent spell (id: %u) in SCRIPT_COMMAND_REMOVE_AURA or SCRIPT_COMMAND_CAST_SPELL for script id %u",
3805 tablename,tmp.datalong,tmp.id);
3806 continue;
3808 if(tmp.datalong2 & ~0x1) // 1 bits (0,1)
3810 sLog.outErrorDb("Table `%s` using unknown flags in datalong2 (%u)i n SCRIPT_COMMAND_CAST_SPELL for script id %u",
3811 tablename,tmp.datalong2,tmp.id);
3812 continue;
3814 break;
3816 case SCRIPT_COMMAND_CAST_SPELL:
3818 if(!sSpellStore.LookupEntry(tmp.datalong))
3820 sLog.outErrorDb("Table `%s` using non-existent spell (id: %u) in SCRIPT_COMMAND_REMOVE_AURA or SCRIPT_COMMAND_CAST_SPELL for script id %u",
3821 tablename,tmp.datalong,tmp.id);
3822 continue;
3824 if(tmp.datalong2 & ~0x3) // 2 bits
3826 sLog.outErrorDb("Table `%s` using unknown flags in datalong2 (%u)i n SCRIPT_COMMAND_CAST_SPELL for script id %u",
3827 tablename,tmp.datalong2,tmp.id);
3828 continue;
3830 break;
3834 if (scripts.find(tmp.id) == scripts.end())
3836 ScriptMap emptyMap;
3837 scripts[tmp.id] = emptyMap;
3839 scripts[tmp.id].insert(std::pair<uint32, ScriptInfo>(tmp.delay, tmp));
3841 ++count;
3842 } while( result->NextRow() );
3844 delete result;
3846 sLog.outString();
3847 sLog.outString( ">> Loaded %u script definitions", count );
3850 void ObjectMgr::LoadGameObjectScripts()
3852 LoadScripts(sGameObjectScripts, "gameobject_scripts");
3854 // check ids
3855 for(ScriptMapMap::const_iterator itr = sGameObjectScripts.begin(); itr != sGameObjectScripts.end(); ++itr)
3857 if(!GetGOData(itr->first))
3858 sLog.outErrorDb("Table `gameobject_scripts` has not existing gameobject (GUID: %u) as script id",itr->first);
3862 void ObjectMgr::LoadQuestEndScripts()
3864 LoadScripts(sQuestEndScripts, "quest_end_scripts");
3866 // check ids
3867 for(ScriptMapMap::const_iterator itr = sQuestEndScripts.begin(); itr != sQuestEndScripts.end(); ++itr)
3869 if(!GetQuestTemplate(itr->first))
3870 sLog.outErrorDb("Table `quest_end_scripts` has not existing quest (Id: %u) as script id",itr->first);
3874 void ObjectMgr::LoadQuestStartScripts()
3876 LoadScripts(sQuestStartScripts,"quest_start_scripts");
3878 // check ids
3879 for(ScriptMapMap::const_iterator itr = sQuestStartScripts.begin(); itr != sQuestStartScripts.end(); ++itr)
3881 if(!GetQuestTemplate(itr->first))
3882 sLog.outErrorDb("Table `quest_start_scripts` has not existing quest (Id: %u) as script id",itr->first);
3886 void ObjectMgr::LoadSpellScripts()
3888 LoadScripts(sSpellScripts, "spell_scripts");
3890 // check ids
3891 for(ScriptMapMap::const_iterator itr = sSpellScripts.begin(); itr != sSpellScripts.end(); ++itr)
3893 SpellEntry const* spellInfo = sSpellStore.LookupEntry(itr->first);
3895 if(!spellInfo)
3897 sLog.outErrorDb("Table `spell_scripts` has not existing spell (Id: %u) as script id",itr->first);
3898 continue;
3901 //check for correct spellEffect
3902 bool found = false;
3903 for(int i=0; i<3; ++i)
3905 // skip empty effects
3906 if( !spellInfo->Effect[i] )
3907 continue;
3909 if( spellInfo->Effect[i] == SPELL_EFFECT_SCRIPT_EFFECT )
3911 found = true;
3912 break;
3916 if(!found)
3917 sLog.outErrorDb("Table `spell_scripts` has unsupported spell (Id: %u) without SPELL_EFFECT_SCRIPT_EFFECT (%u) spell effect",itr->first,SPELL_EFFECT_SCRIPT_EFFECT);
3921 void ObjectMgr::LoadEventScripts()
3923 LoadScripts(sEventScripts, "event_scripts");
3925 std::set<uint32> evt_scripts;
3926 // Load all possible script entries from gameobjects
3927 for(uint32 i = 1; i < sGOStorage.MaxEntry; ++i)
3929 GameObjectInfo const * goInfo = sGOStorage.LookupEntry<GameObjectInfo>(i);
3930 if (goInfo)
3932 switch(goInfo->type)
3934 case GAMEOBJECT_TYPE_GOOBER:
3935 if (goInfo->goober.eventId)
3936 evt_scripts.insert(goInfo->goober.eventId);
3937 break;
3938 case GAMEOBJECT_TYPE_CHEST:
3939 if (goInfo->chest.eventId)
3940 evt_scripts.insert(goInfo->chest.eventId);
3941 break;
3942 case GAMEOBJECT_TYPE_CAMERA:
3943 if (goInfo->camera.eventID)
3944 evt_scripts.insert(goInfo->camera.eventID);
3945 default:
3946 break;
3950 // Load all possible script entries from spells
3951 for(uint32 i = 1; i < sSpellStore.GetNumRows(); ++i)
3953 SpellEntry const * spell = sSpellStore.LookupEntry(i);
3954 if (spell)
3956 for(int j=0; j<3; ++j)
3958 if( spell->Effect[j] == SPELL_EFFECT_SEND_EVENT )
3960 if (spell->EffectMiscValue[j])
3961 evt_scripts.insert(spell->EffectMiscValue[j]);
3966 // Then check if all scripts are in above list of possible script entries
3967 for(ScriptMapMap::const_iterator itr = sEventScripts.begin(); itr != sEventScripts.end(); ++itr)
3969 std::set<uint32>::const_iterator itr2 = evt_scripts.find(itr->first);
3970 if (itr2 == evt_scripts.end())
3971 sLog.outErrorDb("Table `event_scripts` has script (Id: %u) not referring to any gameobject_template type 10 data2 field, type 3 data6 field, type 13 data 2 field or any spell effect %u",
3972 itr->first, SPELL_EFFECT_SEND_EVENT);
3976 void ObjectMgr::LoadItemTexts()
3978 QueryResult *result = CharacterDatabase.Query("SELECT id, text FROM item_text");
3980 uint32 count = 0;
3982 if( !result )
3984 barGoLink bar( 1 );
3985 bar.step();
3987 sLog.outString();
3988 sLog.outString( ">> Loaded %u item pages", count );
3989 return;
3992 barGoLink bar( result->GetRowCount() );
3994 Field* fields;
3997 bar.step();
3999 fields = result->Fetch();
4001 mItemTexts[ fields[0].GetUInt32() ] = fields[1].GetCppString();
4003 ++count;
4005 } while ( result->NextRow() );
4007 delete result;
4009 sLog.outString();
4010 sLog.outString( ">> Loaded %u item texts", count );
4013 void ObjectMgr::LoadPageTexts()
4015 sPageTextStore.Free(); // for reload case
4017 sPageTextStore.Load();
4018 sLog.outString( ">> Loaded %u page texts", sPageTextStore.RecordCount );
4019 sLog.outString();
4021 for(uint32 i = 1; i < sPageTextStore.MaxEntry; ++i)
4023 // check data correctness
4024 PageText const* page = sPageTextStore.LookupEntry<PageText>(i);
4025 if(!page)
4026 continue;
4028 if(page->Next_Page && !sPageTextStore.LookupEntry<PageText>(page->Next_Page))
4030 sLog.outErrorDb("Page text (Id: %u) has not existing next page (Id:%u)", i,page->Next_Page);
4031 continue;
4034 // detect circular reference
4035 std::set<uint32> checkedPages;
4036 for(PageText const* pageItr = page; pageItr; pageItr = sPageTextStore.LookupEntry<PageText>(pageItr->Next_Page))
4038 if(!pageItr->Next_Page)
4039 break;
4040 checkedPages.insert(pageItr->Page_ID);
4041 if(checkedPages.find(pageItr->Next_Page)!=checkedPages.end())
4043 std::ostringstream ss;
4044 ss<< "The text page(s) ";
4045 for (std::set<uint32>::iterator itr= checkedPages.begin();itr!=checkedPages.end(); ++itr)
4046 ss << *itr << " ";
4047 ss << "create(s) a circular reference, which can cause the server to freeze. Changing Next_Page of page "
4048 << pageItr->Page_ID <<" to 0";
4049 sLog.outErrorDb(ss.str().c_str());
4050 const_cast<PageText*>(pageItr)->Next_Page = 0;
4051 break;
4057 void ObjectMgr::LoadPageTextLocales()
4059 mPageTextLocaleMap.clear(); // need for reload case
4061 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");
4063 if(!result)
4065 barGoLink bar(1);
4067 bar.step();
4069 sLog.outString();
4070 sLog.outString(">> Loaded 0 PageText locale strings. DB table `locales_page_text` is empty.");
4071 return;
4074 barGoLink bar(result->GetRowCount());
4078 Field *fields = result->Fetch();
4079 bar.step();
4081 uint32 entry = fields[0].GetUInt32();
4083 PageTextLocale& data = mPageTextLocaleMap[entry];
4085 for(int i = 1; i < MAX_LOCALE; ++i)
4087 std::string str = fields[i].GetCppString();
4088 if(str.empty())
4089 continue;
4091 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4092 if(idx >= 0)
4094 if(data.Text.size() <= idx)
4095 data.Text.resize(idx+1);
4097 data.Text[idx] = str;
4101 } while (result->NextRow());
4103 delete result;
4105 sLog.outString();
4106 sLog.outString( ">> Loaded %lu PageText locale strings", (unsigned long)mPageTextLocaleMap.size() );
4109 struct SQLInstanceLoader : public SQLStorageLoaderBase<SQLInstanceLoader>
4111 template<class D>
4112 void convert_from_str(uint32 /*field_pos*/, char *src, D &dst)
4114 dst = D(objmgr.GetScriptId(src));
4118 void ObjectMgr::LoadInstanceTemplate()
4120 SQLInstanceLoader loader;
4121 loader.Load(sInstanceTemplate);
4123 for(uint32 i = 0; i < sInstanceTemplate.MaxEntry; i++)
4125 InstanceTemplate* temp = (InstanceTemplate*)GetInstanceTemplate(i);
4126 if(!temp) continue;
4127 const MapEntry* entry = sMapStore.LookupEntry(temp->map);
4128 if(!entry)
4130 sLog.outErrorDb("ObjectMgr::LoadInstanceTemplate: bad mapid %d for template!", temp->map);
4131 continue;
4133 else if(!entry->HasResetTime())
4134 continue;
4136 //FIXME: now exist heroic instance, normal/heroic raid instances
4137 // entry->resetTimeHeroic store reset time for both heroic mode instance (raid and non-raid)
4138 // entry->resetTimeRaid store reset time for normal raid only
4139 // for current state entry->resetTimeRaid == entry->resetTimeHeroic in case raid instances with heroic mode.
4140 // but at some point wee need implement reset time dependent from raid instance mode
4141 if(temp->reset_delay == 0)
4143 // use defaults from the DBC
4144 if(entry->resetTimeHeroic) // for both raid and non raids, read above
4146 temp->reset_delay = entry->resetTimeHeroic / DAY;
4148 else if (entry->resetTimeRaid && entry->map_type == MAP_RAID)
4149 // for normal raid only
4151 temp->reset_delay = entry->resetTimeRaid / DAY;
4155 // the reset_delay must be at least one day
4156 temp->reset_delay = std::max((uint32)1, (uint32)(temp->reset_delay * sWorld.getRate(RATE_INSTANCE_RESET_TIME)));
4159 sLog.outString( ">> Loaded %u Instance Template definitions", sInstanceTemplate.RecordCount );
4160 sLog.outString();
4163 GossipText const *ObjectMgr::GetGossipText(uint32 Text_ID) const
4165 GossipTextMap::const_iterator itr = mGossipText.find(Text_ID);
4166 if(itr != mGossipText.end())
4167 return &itr->second;
4168 return NULL;
4171 void ObjectMgr::LoadGossipText()
4173 QueryResult *result = WorldDatabase.Query( "SELECT * FROM npc_text" );
4175 int count = 0;
4176 if( !result )
4178 barGoLink bar( 1 );
4179 bar.step();
4181 sLog.outString();
4182 sLog.outString( ">> Loaded %u npc texts", count );
4183 return;
4186 int cic;
4188 barGoLink bar( result->GetRowCount() );
4192 ++count;
4193 cic = 0;
4195 Field *fields = result->Fetch();
4197 bar.step();
4199 uint32 Text_ID = fields[cic++].GetUInt32();
4200 if(!Text_ID)
4202 sLog.outErrorDb("Table `npc_text` has record wit reserved id 0, ignore.");
4203 continue;
4206 GossipText& gText = mGossipText[Text_ID];
4208 for (int i=0; i< 8; i++)
4210 gText.Options[i].Text_0 = fields[cic++].GetCppString();
4211 gText.Options[i].Text_1 = fields[cic++].GetCppString();
4213 gText.Options[i].Language = fields[cic++].GetUInt32();
4214 gText.Options[i].Probability = fields[cic++].GetFloat();
4216 for(int j=0; j < 3; ++j)
4218 gText.Options[i].Emotes[j]._Delay = fields[cic++].GetUInt32();
4219 gText.Options[i].Emotes[j]._Emote = fields[cic++].GetUInt32();
4222 } while( result->NextRow() );
4224 sLog.outString();
4225 sLog.outString( ">> Loaded %u npc texts", count );
4226 delete result;
4229 void ObjectMgr::LoadNpcTextLocales()
4231 mNpcTextLocaleMap.clear(); // need for reload case
4233 QueryResult *result = WorldDatabase.Query("SELECT entry,"
4234 "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,"
4235 "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,"
4236 "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,"
4237 "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,"
4238 "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,"
4239 "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,"
4240 "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, "
4241 "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 "
4242 " FROM locales_npc_text");
4244 if(!result)
4246 barGoLink bar(1);
4248 bar.step();
4250 sLog.outString();
4251 sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_npc_text` is empty.");
4252 return;
4255 barGoLink bar(result->GetRowCount());
4259 Field *fields = result->Fetch();
4260 bar.step();
4262 uint32 entry = fields[0].GetUInt32();
4264 NpcTextLocale& data = mNpcTextLocaleMap[entry];
4266 for(int i=1; i<MAX_LOCALE; ++i)
4268 for(int j=0; j<8; ++j)
4270 std::string str0 = fields[1+8*2*(i-1)+2*j].GetCppString();
4271 if(!str0.empty())
4273 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4274 if(idx >= 0)
4276 if(data.Text_0[j].size() <= idx)
4277 data.Text_0[j].resize(idx+1);
4279 data.Text_0[j][idx] = str0;
4282 std::string str1 = fields[1+8*2*(i-1)+2*j+1].GetCppString();
4283 if(!str1.empty())
4285 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4286 if(idx >= 0)
4288 if(data.Text_1[j].size() <= idx)
4289 data.Text_1[j].resize(idx+1);
4291 data.Text_1[j][idx] = str1;
4296 } while (result->NextRow());
4298 delete result;
4300 sLog.outString();
4301 sLog.outString( ">> Loaded %lu NpcText locale strings", (unsigned long)mNpcTextLocaleMap.size() );
4304 //not very fast function but it is called only once a day, or on starting-up
4305 void ObjectMgr::ReturnOrDeleteOldMails(bool serverUp)
4307 time_t basetime = time(NULL);
4308 sLog.outDebug("Returning mails current time: hour: %d, minute: %d, second: %d ", localtime(&basetime)->tm_hour, localtime(&basetime)->tm_min, localtime(&basetime)->tm_sec);
4309 //delete all old mails without item and without body immediately, if starting server
4310 if (!serverUp)
4311 CharacterDatabase.PExecute("DELETE FROM mail WHERE expire_time < '" UI64FMTD "' AND has_items = '0' AND itemTextId = 0", (uint64)basetime);
4312 // 0 1 2 3 4 5 6 7 8 9
4313 QueryResult* result = CharacterDatabase.PQuery("SELECT id,messageType,sender,receiver,itemTextId,has_items,expire_time,cod,checked,mailTemplateId FROM mail WHERE expire_time < '" UI64FMTD "'", (uint64)basetime);
4314 if ( !result )
4316 barGoLink bar(1);
4317 bar.step();
4318 sLog.outString();
4319 sLog.outString(">> Only expired mails (need to be return or delete) or DB table `mail` is empty.");
4320 return; // any mails need to be returned or deleted
4323 //std::ostringstream delitems, delmails; //will be here for optimization
4324 //bool deletemail = false, deleteitem = false;
4325 //delitems << "DELETE FROM item_instance WHERE guid IN ( ";
4326 //delmails << "DELETE FROM mail WHERE id IN ( "
4328 barGoLink bar( result->GetRowCount() );
4329 uint32 count = 0;
4330 Field *fields;
4334 bar.step();
4336 fields = result->Fetch();
4337 Mail *m = new Mail;
4338 m->messageID = fields[0].GetUInt32();
4339 m->messageType = fields[1].GetUInt8();
4340 m->sender = fields[2].GetUInt32();
4341 m->receiver = fields[3].GetUInt32();
4342 m->itemTextId = fields[4].GetUInt32();
4343 bool has_items = fields[5].GetBool();
4344 m->expire_time = (time_t)fields[6].GetUInt64();
4345 m->deliver_time = 0;
4346 m->COD = fields[7].GetUInt32();
4347 m->checked = fields[8].GetUInt32();
4348 m->mailTemplateId = fields[9].GetInt16();
4350 Player *pl = 0;
4351 if (serverUp)
4352 pl = GetPlayer((uint64)m->receiver);
4353 if (pl && pl->m_mailsLoaded)
4354 { //this code will run very improbably (the time is between 4 and 5 am, in game is online a player, who has old mail
4355 //his in mailbox and he has already listed his mails )
4356 delete m;
4357 continue;
4359 //delete or return mail:
4360 if (has_items)
4362 QueryResult *resultItems = CharacterDatabase.PQuery("SELECT item_guid,item_template FROM mail_items WHERE mail_id='%u'", m->messageID);
4363 if(resultItems)
4367 Field *fields2 = resultItems->Fetch();
4369 uint32 item_guid_low = fields2[0].GetUInt32();
4370 uint32 item_template = fields2[1].GetUInt32();
4372 m->AddItem(item_guid_low, item_template);
4374 while (resultItems->NextRow());
4376 delete resultItems;
4378 //if it is mail from AH, it shouldn't be returned, but deleted
4379 if (m->messageType != MAIL_NORMAL || (m->checked & (MAIL_CHECK_MASK_AUCTION | MAIL_CHECK_MASK_COD_PAYMENT | MAIL_CHECK_MASK_RETURNED)))
4381 // mail open and then not returned
4382 for(std::vector<MailItemInfo>::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
4383 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
4385 else
4387 //mail will be returned:
4388 CharacterDatabase.PExecute("UPDATE mail SET sender = '%u', receiver = '%u', expire_time = '" UI64FMTD "', deliver_time = '" UI64FMTD "',cod = '0', checked = '%u' WHERE id = '%u'", m->receiver, m->sender, (uint64)(basetime + 30*DAY), (uint64)basetime, MAIL_CHECK_MASK_RETURNED, m->messageID);
4389 delete m;
4390 continue;
4394 if (m->itemTextId)
4395 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
4397 //deletemail = true;
4398 //delmails << m->messageID << ", ";
4399 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
4400 delete m;
4401 ++count;
4402 } while (result->NextRow());
4403 delete result;
4405 sLog.outString();
4406 sLog.outString( ">> Loaded %u mails", count );
4409 void ObjectMgr::LoadQuestAreaTriggers()
4411 mQuestAreaTriggerMap.clear(); // need for reload case
4413 QueryResult *result = WorldDatabase.Query( "SELECT id,quest FROM areatrigger_involvedrelation" );
4415 uint32 count = 0;
4417 if( !result )
4419 barGoLink bar( 1 );
4420 bar.step();
4422 sLog.outString();
4423 sLog.outString( ">> Loaded %u quest trigger points", count );
4424 return;
4427 barGoLink bar( result->GetRowCount() );
4431 ++count;
4432 bar.step();
4434 Field *fields = result->Fetch();
4436 uint32 trigger_ID = fields[0].GetUInt32();
4437 uint32 quest_ID = fields[1].GetUInt32();
4439 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(trigger_ID);
4440 if(!atEntry)
4442 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",trigger_ID);
4443 continue;
4446 Quest const* quest = GetQuestTemplate(quest_ID);
4448 if(!quest)
4450 sLog.outErrorDb("Table `areatrigger_involvedrelation` has record (id: %u) for not existing quest %u",trigger_ID,quest_ID);
4451 continue;
4454 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
4456 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);
4458 // this will prevent quest completing without objective
4459 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
4461 // continue; - quest modified to required objective and trigger can be allowed.
4464 mQuestAreaTriggerMap[trigger_ID] = quest_ID;
4466 } while( result->NextRow() );
4468 delete result;
4470 sLog.outString();
4471 sLog.outString( ">> Loaded %u quest trigger points", count );
4474 void ObjectMgr::LoadTavernAreaTriggers()
4476 mTavernAreaTriggerSet.clear(); // need for reload case
4478 QueryResult *result = WorldDatabase.Query("SELECT id FROM areatrigger_tavern");
4480 uint32 count = 0;
4482 if( !result )
4484 barGoLink bar( 1 );
4485 bar.step();
4487 sLog.outString();
4488 sLog.outString( ">> Loaded %u tavern triggers", count );
4489 return;
4492 barGoLink bar( result->GetRowCount() );
4496 ++count;
4497 bar.step();
4499 Field *fields = result->Fetch();
4501 uint32 Trigger_ID = fields[0].GetUInt32();
4503 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4504 if(!atEntry)
4506 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4507 continue;
4510 mTavernAreaTriggerSet.insert(Trigger_ID);
4511 } while( result->NextRow() );
4513 delete result;
4515 sLog.outString();
4516 sLog.outString( ">> Loaded %u tavern triggers", count );
4519 void ObjectMgr::LoadAreaTriggerScripts()
4521 mAreaTriggerScripts.clear(); // need for reload case
4522 QueryResult *result = WorldDatabase.Query("SELECT entry, ScriptName FROM areatrigger_scripts");
4524 uint32 count = 0;
4526 if( !result )
4528 barGoLink bar( 1 );
4529 bar.step();
4531 sLog.outString();
4532 sLog.outString( ">> Loaded %u areatrigger scripts", count );
4533 return;
4536 barGoLink bar( result->GetRowCount() );
4540 ++count;
4541 bar.step();
4543 Field *fields = result->Fetch();
4545 uint32 Trigger_ID = fields[0].GetUInt32();
4546 const char *scriptName = fields[1].GetString();
4548 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4549 if(!atEntry)
4551 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4552 continue;
4554 mAreaTriggerScripts[Trigger_ID] = GetScriptId(scriptName);
4555 } while( result->NextRow() );
4557 delete result;
4559 sLog.outString();
4560 sLog.outString( ">> Loaded %u areatrigger scripts", count );
4563 uint32 ObjectMgr::GetNearestTaxiNode( float x, float y, float z, uint32 mapid, uint32 team )
4565 bool found = false;
4566 float dist;
4567 uint32 id = 0;
4569 for(uint32 i = 1; i < sTaxiNodesStore.GetNumRows(); ++i)
4571 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(i);
4572 if(!node || node->map_id != mapid || !node->MountCreatureID[team == ALLIANCE ? 1 : 0])
4573 continue;
4575 uint8 field = (uint8)((i - 1) / 32);
4576 uint32 submask = 1<<((i-1)%32);
4578 // skip not taxi network nodes
4579 if((sTaxiNodesMask[field] & submask)==0)
4580 continue;
4582 float dist2 = (node->x - x)*(node->x - x)+(node->y - y)*(node->y - y)+(node->z - z)*(node->z - z);
4583 if(found)
4585 if(dist2 < dist)
4587 dist = dist2;
4588 id = i;
4591 else
4593 found = true;
4594 dist = dist2;
4595 id = i;
4599 return id;
4602 void ObjectMgr::GetTaxiPath( uint32 source, uint32 destination, uint32 &path, uint32 &cost)
4604 TaxiPathSetBySource::iterator src_i = sTaxiPathSetBySource.find(source);
4605 if(src_i==sTaxiPathSetBySource.end())
4607 path = 0;
4608 cost = 0;
4609 return;
4612 TaxiPathSetForSource& pathSet = src_i->second;
4614 TaxiPathSetForSource::iterator dest_i = pathSet.find(destination);
4615 if(dest_i==pathSet.end())
4617 path = 0;
4618 cost = 0;
4619 return;
4622 cost = dest_i->second.price;
4623 path = dest_i->second.ID;
4626 uint16 ObjectMgr::GetTaxiMount( uint32 id, uint32 team, bool allowed_alt_team /* = false */)
4628 uint16 mount_entry = 0;
4629 uint16 mount_id = 0;
4631 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(id);
4632 if(node)
4634 if (team == ALLIANCE)
4636 mount_entry = node->MountCreatureID[1];
4637 if(!mount_entry && allowed_alt_team)
4638 mount_entry = node->MountCreatureID[0];
4640 CreatureInfo const *ci = GetCreatureTemplate(mount_entry);
4641 if(ci)
4642 mount_id = ci->DisplayID_A;
4644 if (team == HORDE)
4646 mount_entry = node->MountCreatureID[0];
4648 if(!mount_entry && allowed_alt_team)
4649 mount_entry = node->MountCreatureID[1];
4651 CreatureInfo const *ci = GetCreatureTemplate(mount_entry);
4652 if(ci)
4653 mount_id = ci->DisplayID_H;
4657 CreatureModelInfo const *minfo = GetCreatureModelInfo(mount_id);
4658 if(!minfo)
4660 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. ",
4661 mount_entry,id,team,mount_id);
4663 return false;
4665 if(minfo->modelid_other_gender!=0)
4666 mount_id = urand(0,1) ? mount_id : minfo->modelid_other_gender;
4668 return mount_id;
4671 void ObjectMgr::GetTaxiPathNodes( uint32 path, Path &pathnodes, std::vector<uint32>& mapIds)
4673 if(path >= sTaxiPathNodesByPath.size())
4674 return;
4676 TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
4678 pathnodes.Resize(nodeList.size());
4679 mapIds.resize(nodeList.size());
4681 for(size_t i = 0; i < nodeList.size(); ++i)
4683 pathnodes[ i ].x = nodeList[i].x;
4684 pathnodes[ i ].y = nodeList[i].y;
4685 pathnodes[ i ].z = nodeList[i].z;
4687 mapIds[i] = nodeList[i].mapid;
4691 void ObjectMgr::GetTransportPathNodes( uint32 path, TransportPath &pathnodes )
4693 if(path >= sTaxiPathNodesByPath.size())
4694 return;
4696 TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
4698 pathnodes.Resize(nodeList.size());
4700 for(size_t i = 0; i < nodeList.size(); ++i)
4702 pathnodes[ i ].mapid = nodeList[i].mapid;
4703 pathnodes[ i ].x = nodeList[i].x;
4704 pathnodes[ i ].y = nodeList[i].y;
4705 pathnodes[ i ].z = nodeList[i].z;
4706 pathnodes[ i ].actionFlag = nodeList[i].actionFlag;
4707 pathnodes[ i ].delay = nodeList[i].delay;
4711 void ObjectMgr::LoadGraveyardZones()
4713 mGraveYardMap.clear(); // need for reload case
4715 QueryResult *result = WorldDatabase.Query("SELECT id,ghost_zone,faction FROM game_graveyard_zone");
4717 uint32 count = 0;
4719 if( !result )
4721 barGoLink bar( 1 );
4722 bar.step();
4724 sLog.outString();
4725 sLog.outString( ">> Loaded %u graveyard-zone links", count );
4726 return;
4729 barGoLink bar( result->GetRowCount() );
4733 ++count;
4734 bar.step();
4736 Field *fields = result->Fetch();
4738 uint32 safeLocId = fields[0].GetUInt32();
4739 uint32 zoneId = fields[1].GetUInt32();
4740 uint32 team = fields[2].GetUInt32();
4742 WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(safeLocId);
4743 if(!entry)
4745 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",safeLocId);
4746 continue;
4749 AreaTableEntry const *areaEntry = GetAreaEntryByAreaID(zoneId);
4750 if(!areaEntry)
4752 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing zone id (%u), skipped.",zoneId);
4753 continue;
4756 if(areaEntry->zone != 0)
4758 sLog.outErrorDb("Table `game_graveyard_zone` has record subzone id (%u) instead of zone, skipped.",zoneId);
4759 continue;
4762 if(team!=0 && team!=HORDE && team!=ALLIANCE)
4764 sLog.outErrorDb("Table `game_graveyard_zone` has record for non player faction (%u), skipped.",team);
4765 continue;
4768 if(!AddGraveYardLink(safeLocId,zoneId,team,false))
4769 sLog.outErrorDb("Table `game_graveyard_zone` has a duplicate record for Graveyard (ID: %u) and Zone (ID: %u), skipped.",safeLocId,zoneId);
4770 } while( result->NextRow() );
4772 delete result;
4774 sLog.outString();
4775 sLog.outString( ">> Loaded %u graveyard-zone links", count );
4778 WorldSafeLocsEntry const *ObjectMgr::GetClosestGraveYard(float x, float y, float z, uint32 MapId, uint32 team)
4780 // search for zone associated closest graveyard
4781 uint32 zoneId = MapManager::Instance().GetZoneId(MapId,x,y,z);
4783 // Simulate std. algorithm:
4784 // found some graveyard associated to (ghost_zone,ghost_map)
4786 // if mapId == graveyard.mapId (ghost in plain zone or city or battleground) and search graveyard at same map
4787 // then check faction
4788 // if mapId != graveyard.mapId (ghost in instance) and search any graveyard associated
4789 // then check faction
4790 GraveYardMap::const_iterator graveLow = mGraveYardMap.lower_bound(zoneId);
4791 GraveYardMap::const_iterator graveUp = mGraveYardMap.upper_bound(zoneId);
4792 if(graveLow==graveUp)
4794 sLog.outErrorDb("Table `game_graveyard_zone` incomplete: Zone %u Team %u does not have a linked graveyard.",zoneId,team);
4795 return NULL;
4798 // at corpse map
4799 bool foundNear = false;
4800 float distNear;
4801 WorldSafeLocsEntry const* entryNear = NULL;
4803 // at entrance map for corpse map
4804 bool foundEntr = false;
4805 float distEntr;
4806 WorldSafeLocsEntry const* entryEntr = NULL;
4808 // some where other
4809 WorldSafeLocsEntry const* entryFar = NULL;
4811 MapEntry const* mapEntry = sMapStore.LookupEntry(MapId);
4813 for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
4815 GraveYardData const& data = itr->second;
4817 WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(data.safeLocId);
4818 if(!entry)
4820 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",data.safeLocId);
4821 continue;
4824 // skip enemy faction graveyard
4825 // team == 0 case can be at call from .neargrave
4826 if(data.team != 0 && team != 0 && data.team != team)
4827 continue;
4829 // find now nearest graveyard at other map
4830 if(MapId != entry->map_id)
4832 // if find graveyard at different map from where entrance placed (or no entrance data), use any first
4833 if (!mapEntry ||
4834 mapEntry->entrance_map < 0 ||
4835 mapEntry->entrance_map != entry->map_id ||
4836 (mapEntry->entrance_x == 0 && mapEntry->entrance_y == 0))
4838 // not have any corrdinates for check distance anyway
4839 entryFar = entry;
4840 continue;
4843 // at entrance map calculate distance (2D);
4844 float dist2 = (entry->x - mapEntry->entrance_x)*(entry->x - mapEntry->entrance_x)
4845 +(entry->y - mapEntry->entrance_y)*(entry->y - mapEntry->entrance_y);
4846 if(foundEntr)
4848 if(dist2 < distEntr)
4850 distEntr = dist2;
4851 entryEntr = entry;
4854 else
4856 foundEntr = true;
4857 distEntr = dist2;
4858 entryEntr = entry;
4861 // find now nearest graveyard at same map
4862 else
4864 float dist2 = (entry->x - x)*(entry->x - x)+(entry->y - y)*(entry->y - y)+(entry->z - z)*(entry->z - z);
4865 if(foundNear)
4867 if(dist2 < distNear)
4869 distNear = dist2;
4870 entryNear = entry;
4873 else
4875 foundNear = true;
4876 distNear = dist2;
4877 entryNear = entry;
4882 if(entryNear)
4883 return entryNear;
4885 if(entryEntr)
4886 return entryEntr;
4888 return entryFar;
4891 GraveYardData const* ObjectMgr::FindGraveYardData(uint32 id, uint32 zoneId)
4893 GraveYardMap::const_iterator graveLow = mGraveYardMap.lower_bound(zoneId);
4894 GraveYardMap::const_iterator graveUp = mGraveYardMap.upper_bound(zoneId);
4896 for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
4898 if(itr->second.safeLocId==id)
4899 return &itr->second;
4902 return NULL;
4905 bool ObjectMgr::AddGraveYardLink(uint32 id, uint32 zoneId, uint32 team, bool inDB)
4907 if(FindGraveYardData(id,zoneId))
4908 return false;
4910 // add link to loaded data
4911 GraveYardData data;
4912 data.safeLocId = id;
4913 data.team = team;
4915 mGraveYardMap.insert(GraveYardMap::value_type(zoneId,data));
4917 // add link to DB
4918 if(inDB)
4920 WorldDatabase.PExecuteLog("INSERT INTO game_graveyard_zone ( id,ghost_zone,faction) "
4921 "VALUES ('%u', '%u','%u')",id,zoneId,team);
4924 return true;
4927 void ObjectMgr::LoadAreaTriggerTeleports()
4929 mAreaTriggers.clear(); // need for reload case
4931 uint32 count = 0;
4933 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13
4934 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");
4935 if( !result )
4938 barGoLink bar( 1 );
4940 bar.step();
4942 sLog.outString();
4943 sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
4944 return;
4947 barGoLink bar( result->GetRowCount() );
4951 Field *fields = result->Fetch();
4953 bar.step();
4955 ++count;
4957 uint32 Trigger_ID = fields[0].GetUInt32();
4959 AreaTrigger at;
4961 at.requiredLevel = fields[1].GetUInt8();
4962 at.requiredItem = fields[2].GetUInt32();
4963 at.requiredItem2 = fields[3].GetUInt32();
4964 at.heroicKey = fields[4].GetUInt32();
4965 at.heroicKey2 = fields[5].GetUInt32();
4966 at.requiredQuest = fields[6].GetUInt32();
4967 at.requiredQuestHeroic = fields[7].GetUInt32();
4968 at.requiredFailedText = fields[8].GetCppString();
4969 at.target_mapId = fields[9].GetUInt32();
4970 at.target_X = fields[10].GetFloat();
4971 at.target_Y = fields[11].GetFloat();
4972 at.target_Z = fields[12].GetFloat();
4973 at.target_Orientation = fields[13].GetFloat();
4975 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4976 if(!atEntry)
4978 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4979 continue;
4982 if(at.requiredItem)
4984 ItemPrototype const *pProto = GetItemPrototype(at.requiredItem);
4985 if(!pProto)
4987 sLog.outError("Key item %u does not exist for trigger %u, removing key requirement.", at.requiredItem, Trigger_ID);
4988 at.requiredItem = 0;
4991 if(at.requiredItem2)
4993 ItemPrototype const *pProto = GetItemPrototype(at.requiredItem2);
4994 if(!pProto)
4996 sLog.outError("Second item %u not exist for trigger %u, remove key requirement.", at.requiredItem2, Trigger_ID);
4997 at.requiredItem2 = 0;
5001 if(at.heroicKey)
5003 ItemPrototype const *pProto = GetItemPrototype(at.heroicKey);
5004 if(!pProto)
5006 sLog.outError("Heroic key item %u not exist for trigger %u, remove key requirement.", at.heroicKey, Trigger_ID);
5007 at.heroicKey = 0;
5011 if(at.heroicKey2)
5013 ItemPrototype const *pProto = GetItemPrototype(at.heroicKey2);
5014 if(!pProto)
5016 sLog.outError("Heroic second key item %u not exist for trigger %u, remove key requirement.", at.heroicKey2, Trigger_ID);
5017 at.heroicKey2 = 0;
5021 if(at.requiredQuest)
5023 QuestMap::iterator qReqItr = mQuestTemplates.find(at.requiredQuest);
5024 if(qReqItr == mQuestTemplates.end())
5026 sLog.outErrorDb("Required Quest %u not exist for trigger %u, remove quest done requirement.",at.requiredQuest,Trigger_ID);
5027 at.requiredQuest = 0;
5031 if(at.requiredQuestHeroic)
5033 QuestMap::iterator qReqItr = mQuestTemplates.find(at.requiredQuestHeroic);
5034 if(qReqItr == mQuestTemplates.end())
5036 sLog.outErrorDb("Required Quest %u not exist for trigger %u, remove quest done requirement.",at.requiredQuestHeroic,Trigger_ID);
5037 at.requiredQuestHeroic = 0;
5041 MapEntry const* mapEntry = sMapStore.LookupEntry(at.target_mapId);
5042 if(!mapEntry)
5044 sLog.outErrorDb("Area trigger (ID:%u) target map (ID: %u) does not exist in `Map.dbc`.",Trigger_ID,at.target_mapId);
5045 continue;
5048 if(at.target_X==0 && at.target_Y==0 && at.target_Z==0)
5050 sLog.outErrorDb("Area trigger (ID:%u) target coordinates not provided.",Trigger_ID);
5051 continue;
5054 mAreaTriggers[Trigger_ID] = at;
5056 } while( result->NextRow() );
5058 delete result;
5060 sLog.outString();
5061 sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
5065 * Searches for the areatrigger which teleports players out of the given map
5067 AreaTrigger const* ObjectMgr::GetGoBackTrigger(uint32 Map) const
5069 const MapEntry *mapEntry = sMapStore.LookupEntry(Map);
5070 if(!mapEntry) return NULL;
5071 for (AreaTriggerMap::const_iterator itr = mAreaTriggers.begin(); itr != mAreaTriggers.end(); ++itr)
5073 if(itr->second.target_mapId == mapEntry->entrance_map)
5075 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(itr->first);
5076 if(atEntry && atEntry->mapid == Map)
5077 return &itr->second;
5080 return NULL;
5084 * Searches for the areatrigger which teleports players to the given map
5086 AreaTrigger const* ObjectMgr::GetMapEntranceTrigger(uint32 Map) const
5088 for (AreaTriggerMap::const_iterator itr = mAreaTriggers.begin(); itr != mAreaTriggers.end(); ++itr)
5090 if(itr->second.target_mapId == Map)
5092 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(itr->first);
5093 if(atEntry)
5094 return &itr->second;
5097 return NULL;
5100 void ObjectMgr::SetHighestGuids()
5102 QueryResult *result = CharacterDatabase.Query( "SELECT MAX(guid) FROM characters" );
5103 if( result )
5105 m_hiCharGuid = (*result)[0].GetUInt32()+1;
5106 delete result;
5109 result = WorldDatabase.Query( "SELECT MAX(guid) FROM creature" );
5110 if( result )
5112 m_hiCreatureGuid = (*result)[0].GetUInt32()+1;
5113 delete result;
5116 result = CharacterDatabase.Query( "SELECT MAX(guid) FROM item_instance" );
5117 if( result )
5119 m_hiItemGuid = (*result)[0].GetUInt32()+1;
5120 delete result;
5123 // Cleanup other tables from not existed guids (>=m_hiItemGuid)
5124 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item >= '%u'", m_hiItemGuid);
5125 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid >= '%u'", m_hiItemGuid);
5126 CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE itemguid >= '%u'", m_hiItemGuid);
5127 CharacterDatabase.PExecute("DELETE FROM guild_bank_item WHERE item_guid >= '%u'", m_hiItemGuid);
5129 result = WorldDatabase.Query("SELECT MAX(guid) FROM gameobject" );
5130 if( result )
5132 m_hiGoGuid = (*result)[0].GetUInt32()+1;
5133 delete result;
5136 result = CharacterDatabase.Query("SELECT MAX(id) FROM auctionhouse" );
5137 if( result )
5139 m_auctionid = (*result)[0].GetUInt32()+1;
5140 delete result;
5143 result = CharacterDatabase.Query( "SELECT MAX(id) FROM mail" );
5144 if( result )
5146 m_mailid = (*result)[0].GetUInt32()+1;
5147 delete result;
5150 result = CharacterDatabase.Query( "SELECT MAX(id) FROM item_text" );
5151 if( result )
5153 m_ItemTextId = (*result)[0].GetUInt32()+1;
5154 delete result;
5157 result = CharacterDatabase.Query( "SELECT MAX(guid) FROM corpse" );
5158 if( result )
5160 m_hiCorpseGuid = (*result)[0].GetUInt32()+1;
5161 delete result;
5164 result = CharacterDatabase.Query("SELECT MAX(arenateamid) FROM arena_team");
5165 if (result)
5167 m_arenaTeamId = (*result)[0].GetUInt32()+1;
5168 delete result;
5171 result = CharacterDatabase.Query( "SELECT MAX(guildid) FROM guild" );
5172 if (result)
5174 m_guildId = (*result)[0].GetUInt32()+1;
5175 delete result;
5179 uint32 ObjectMgr::GenerateArenaTeamId()
5181 if(m_arenaTeamId>=0xFFFFFFFE)
5183 sLog.outError("Arena team ids overflow!! Can't continue, shutting down server. ");
5184 World::StopNow(ERROR_EXIT_CODE);
5186 return m_arenaTeamId++;
5189 uint32 ObjectMgr::GenerateAuctionID()
5191 if(m_auctionid>=0xFFFFFFFE)
5193 sLog.outError("Auctions ids overflow!! Can't continue, shutting down server. ");
5194 World::StopNow(ERROR_EXIT_CODE);
5196 return m_auctionid++;
5199 uint32 ObjectMgr::GenerateGuildId()
5201 if(m_guildId>=0xFFFFFFFE)
5203 sLog.outError("Guild ids overflow!! Can't continue, shutting down server. ");
5204 World::StopNow(ERROR_EXIT_CODE);
5206 return m_guildId++;
5209 uint32 ObjectMgr::GenerateMailID()
5211 if(m_mailid>=0xFFFFFFFE)
5213 sLog.outError("Mail ids overflow!! Can't continue, shutting down server. ");
5214 World::StopNow(ERROR_EXIT_CODE);
5216 return m_mailid++;
5219 uint32 ObjectMgr::GenerateItemTextID()
5221 if(m_ItemTextId>=0xFFFFFFFE)
5223 sLog.outError("Item text ids overflow!! Can't continue, shutting down server. ");
5224 World::StopNow(ERROR_EXIT_CODE);
5226 return m_ItemTextId++;
5229 uint32 ObjectMgr::CreateItemText(std::string text)
5231 uint32 newItemTextId = GenerateItemTextID();
5232 //insert new itempage to container
5233 mItemTexts[ newItemTextId ] = text;
5234 //save new itempage
5235 CharacterDatabase.escape_string(text);
5236 //any Delete query needed, itemTextId is maximum of all ids
5237 std::ostringstream query;
5238 query << "INSERT INTO item_text (id,text) VALUES ( '" << newItemTextId << "', '" << text << "')";
5239 CharacterDatabase.Execute(query.str().c_str()); //needs to be run this way, because mail body may be more than 1024 characters
5240 return newItemTextId;
5243 uint32 ObjectMgr::GenerateLowGuid(HighGuid guidhigh)
5245 switch(guidhigh)
5247 case HIGHGUID_ITEM:
5248 if(m_hiItemGuid>=0xFFFFFFFE)
5250 sLog.outError("Item guid overflow!! Can't continue, shutting down server. ");
5251 World::StopNow(ERROR_EXIT_CODE);
5253 return m_hiItemGuid++;
5254 case HIGHGUID_UNIT:
5255 if(m_hiCreatureGuid>=0x00FFFFFE)
5257 sLog.outError("Creature guid overflow!! Can't continue, shutting down server. ");
5258 World::StopNow(ERROR_EXIT_CODE);
5260 return m_hiCreatureGuid++;
5261 case HIGHGUID_PET:
5262 if(m_hiPetGuid>=0x00FFFFFE)
5264 sLog.outError("Pet guid overflow!! Can't continue, shutting down server. ");
5265 World::StopNow(ERROR_EXIT_CODE);
5267 return m_hiPetGuid++;
5268 case HIGHGUID_VEHICLE:
5269 if(m_hiVehicleGuid>=0x00FFFFFF)
5271 sLog.outError("Vehicle guid overflow!! Can't continue, shutting down server. ");
5272 World::StopNow(ERROR_EXIT_CODE);
5274 return m_hiVehicleGuid++;
5275 case HIGHGUID_PLAYER:
5276 if(m_hiCharGuid>=0xFFFFFFFE)
5278 sLog.outError("Players guid overflow!! Can't continue, shutting down server. ");
5279 World::StopNow(ERROR_EXIT_CODE);
5281 return m_hiCharGuid++;
5282 case HIGHGUID_GAMEOBJECT:
5283 if(m_hiGoGuid>=0x00FFFFFE)
5285 sLog.outError("Gameobject guid overflow!! Can't continue, shutting down server. ");
5286 World::StopNow(ERROR_EXIT_CODE);
5288 return m_hiGoGuid++;
5289 case HIGHGUID_CORPSE:
5290 if(m_hiCorpseGuid>=0xFFFFFFFE)
5292 sLog.outError("Corpse guid overflow!! Can't continue, shutting down server. ");
5293 World::StopNow(ERROR_EXIT_CODE);
5295 return m_hiCorpseGuid++;
5296 case HIGHGUID_DYNAMICOBJECT:
5297 if(m_hiDoGuid>=0xFFFFFFFE)
5299 sLog.outError("DynamicObject guid overflow!! Can't continue, shutting down server. ");
5300 World::StopNow(ERROR_EXIT_CODE);
5302 return m_hiDoGuid++;
5303 default:
5304 ASSERT(0);
5307 ASSERT(0);
5308 return 0;
5311 void ObjectMgr::LoadGameObjectLocales()
5313 mGameObjectLocaleMap.clear(); // need for reload case
5315 QueryResult *result = WorldDatabase.Query("SELECT entry,"
5316 "name_loc1,name_loc2,name_loc3,name_loc4,name_loc5,name_loc6,name_loc7,name_loc8,"
5317 "castbarcaption_loc1,castbarcaption_loc2,castbarcaption_loc3,castbarcaption_loc4,"
5318 "castbarcaption_loc5,castbarcaption_loc6,castbarcaption_loc7,castbarcaption_loc8 FROM locales_gameobject");
5320 if(!result)
5322 barGoLink bar(1);
5324 bar.step();
5326 sLog.outString();
5327 sLog.outString(">> Loaded 0 gameobject locale strings. DB table `locales_gameobject` is empty.");
5328 return;
5331 barGoLink bar(result->GetRowCount());
5335 Field *fields = result->Fetch();
5336 bar.step();
5338 uint32 entry = fields[0].GetUInt32();
5340 GameObjectLocale& data = mGameObjectLocaleMap[entry];
5342 for(int i = 1; i < MAX_LOCALE; ++i)
5344 std::string str = fields[i].GetCppString();
5345 if(!str.empty())
5347 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5348 if(idx >= 0)
5350 if(data.Name.size() <= idx)
5351 data.Name.resize(idx+1);
5353 data.Name[idx] = str;
5358 for(int i = 1; i < MAX_LOCALE; ++i)
5360 std::string str = fields[i+(MAX_LOCALE-1)].GetCppString();
5361 if(!str.empty())
5363 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5364 if(idx >= 0)
5366 if(data.CastBarCaption.size() <= idx)
5367 data.CastBarCaption.resize(idx+1);
5369 data.CastBarCaption[idx] = str;
5374 } while (result->NextRow());
5376 delete result;
5378 sLog.outString();
5379 sLog.outString( ">> Loaded %lu gameobject locale strings", (unsigned long)mGameObjectLocaleMap.size() );
5382 struct SQLGameObjectLoader : public SQLStorageLoaderBase<SQLGameObjectLoader>
5384 template<class D>
5385 void convert_from_str(uint32 /*field_pos*/, char *src, D &dst)
5387 dst = D(objmgr.GetScriptId(src));
5391 inline void CheckGOLockId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5393 if (sLockStore.LookupEntry(dataN))
5394 return;
5396 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but lock (Id: %u) not found.",
5397 goInfo->id,goInfo->type,N,goInfo->door.lockId,goInfo->door.lockId);
5400 inline void CheckGOLinkedTrapId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5402 if (GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(dataN))
5404 if (trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5405 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5406 goInfo->id,goInfo->type,N,dataN,dataN,GAMEOBJECT_TYPE_TRAP);
5408 /* disable check for while (too many error reports baout not existed in trap templates
5409 else
5410 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5411 goInfo->id,goInfo->type,N,dataN,dataN);
5415 inline void CheckGOSpellId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5417 if (sSpellStore.LookupEntry(dataN))
5418 return;
5420 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but Spell (Entry %u) not exist.",
5421 goInfo->id,goInfo->type,N,dataN,dataN);
5424 inline void CheckAndFixGOChairHeightId(GameObjectInfo const* goInfo,uint32 const& dataN,uint32 N)
5426 if (dataN <= (UNIT_STAND_STATE_SIT_HIGH_CHAIR-UNIT_STAND_STATE_SIT_LOW_CHAIR) )
5427 return;
5429 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but correct chair height in range 0..%i.",
5430 goInfo->id,goInfo->type,N,dataN,UNIT_STAND_STATE_SIT_HIGH_CHAIR-UNIT_STAND_STATE_SIT_LOW_CHAIR);
5432 // prevent client and server unexpected work
5433 const_cast<uint32&>(dataN) = 0;
5436 inline void CheckGONoDamageImmuneId(GameObjectInfo const* goInfo,uint32 dataN,uint32 N)
5438 // 0/1 correct values
5439 if (dataN <= 1)
5440 return;
5442 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but expected boolean (0/1) noDamageImmune field value.",
5443 goInfo->id,goInfo->type,N,dataN);
5446 void ObjectMgr::LoadGameobjectInfo()
5448 SQLGameObjectLoader loader;
5449 loader.Load(sGOStorage);
5451 // some checks
5452 for(uint32 id = 1; id < sGOStorage.MaxEntry; id++)
5454 GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(id);
5455 if (!goInfo)
5456 continue;
5458 switch(goInfo->type)
5460 case GAMEOBJECT_TYPE_DOOR: //0
5462 if (goInfo->door.lockId)
5463 CheckGOLockId(goInfo,goInfo->door.lockId,1);
5464 CheckGONoDamageImmuneId(goInfo,goInfo->door.noDamageImmune,3);
5465 break;
5467 case GAMEOBJECT_TYPE_BUTTON: //1
5469 if (goInfo->button.lockId)
5470 CheckGOLockId(goInfo,goInfo->button.lockId,1);
5471 CheckGONoDamageImmuneId(goInfo,goInfo->button.noDamageImmune,4);
5472 break;
5474 case GAMEOBJECT_TYPE_QUESTGIVER: //2
5476 if (goInfo->questgiver.lockId)
5477 CheckGOLockId(goInfo,goInfo->questgiver.lockId,0);
5478 CheckGONoDamageImmuneId(goInfo,goInfo->questgiver.noDamageImmune,5);
5479 break;
5481 case GAMEOBJECT_TYPE_CHEST: //3
5483 if (goInfo->chest.lockId)
5484 CheckGOLockId(goInfo,goInfo->chest.lockId,0);
5486 if (goInfo->chest.linkedTrapId) // linked trap
5487 CheckGOLinkedTrapId(goInfo,goInfo->chest.linkedTrapId,7);
5488 break;
5490 case GAMEOBJECT_TYPE_TRAP: //6
5492 if (goInfo->trap.lockId)
5493 CheckGOLockId(goInfo,goInfo->trap.lockId,0);
5494 /* disable check for while, too many not existed spells
5495 if (goInfo->trap.spellId) // spell
5496 CheckGOSpellId(goInfo,goInfo->trap.spellId,3);
5498 break;
5500 case GAMEOBJECT_TYPE_CHAIR: //7
5501 CheckAndFixGOChairHeightId(goInfo,goInfo->chair.height,1);
5502 break;
5503 case GAMEOBJECT_TYPE_SPELL_FOCUS: //8
5505 if (goInfo->spellFocus.focusId)
5507 if (!sSpellFocusObjectStore.LookupEntry(goInfo->spellFocus.focusId))
5508 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but SpellFocus (Id: %u) not exist.",
5509 id,goInfo->type,goInfo->spellFocus.focusId,goInfo->spellFocus.focusId);
5512 if (goInfo->spellFocus.linkedTrapId) // linked trap
5513 CheckGOLinkedTrapId(goInfo,goInfo->spellFocus.linkedTrapId,2);
5514 break;
5516 case GAMEOBJECT_TYPE_GOOBER: //10
5518 if (goInfo->goober.lockId)
5519 CheckGOLockId(goInfo,goInfo->goober.lockId,0);
5521 if (goInfo->goober.pageId) // pageId
5523 if (!sPageTextStore.LookupEntry<PageText>(goInfo->goober.pageId))
5524 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data7=%u but PageText (Entry %u) not exist.",
5525 id,goInfo->type,goInfo->goober.pageId,goInfo->goober.pageId);
5527 /* disable check for while, too many not existed spells
5528 if (goInfo->goober.spellId) // spell
5529 CheckGOSpellId(goInfo,goInfo->goober.spellId,10);
5531 CheckGONoDamageImmuneId(goInfo,goInfo->goober.noDamageImmune,11);
5532 if (goInfo->goober.linkedTrapId) // linked trap
5533 CheckGOLinkedTrapId(goInfo,goInfo->goober.linkedTrapId,12);
5534 break;
5536 case GAMEOBJECT_TYPE_AREADAMAGE: //12
5538 if (goInfo->areadamage.lockId)
5539 CheckGOLockId(goInfo,goInfo->areadamage.lockId,0);
5540 break;
5542 case GAMEOBJECT_TYPE_CAMERA: //13
5544 if (goInfo->camera.lockId)
5545 CheckGOLockId(goInfo,goInfo->camera.lockId,0);
5546 break;
5548 case GAMEOBJECT_TYPE_MO_TRANSPORT: //15
5550 if (goInfo->moTransport.taxiPathId)
5552 if (goInfo->moTransport.taxiPathId >= sTaxiPathNodesByPath.size() || sTaxiPathNodesByPath[goInfo->moTransport.taxiPathId].empty())
5553 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but TaxiPath (Id: %u) not exist.",
5554 id,goInfo->type,goInfo->moTransport.taxiPathId,goInfo->moTransport.taxiPathId);
5556 break;
5558 case GAMEOBJECT_TYPE_SUMMONING_RITUAL: //18
5560 /* disable check for while, too many not existed spells
5561 // always must have spell
5562 CheckGOSpellId(goInfo,goInfo->summoningRitual.spellId,1);
5564 break;
5566 case GAMEOBJECT_TYPE_SPELLCASTER: //22
5568 // always must have spell
5569 CheckGOSpellId(goInfo,goInfo->spellcaster.spellId,0);
5570 break;
5572 case GAMEOBJECT_TYPE_FLAGSTAND: //24
5574 if (goInfo->flagstand.lockId)
5575 CheckGOLockId(goInfo,goInfo->flagstand.lockId,0);
5576 CheckGONoDamageImmuneId(goInfo,goInfo->flagstand.noDamageImmune,5);
5577 break;
5579 case GAMEOBJECT_TYPE_FISHINGHOLE: //25
5581 if (goInfo->fishinghole.lockId)
5582 CheckGOLockId(goInfo,goInfo->fishinghole.lockId,4);
5583 break;
5585 case GAMEOBJECT_TYPE_FLAGDROP: //26
5587 if (goInfo->flagdrop.lockId)
5588 CheckGOLockId(goInfo,goInfo->flagdrop.lockId,0);
5589 CheckGONoDamageImmuneId(goInfo,goInfo->flagdrop.noDamageImmune,3);
5590 break;
5592 case GAMEOBJECT_TYPE_BARBER_CHAIR: //32
5593 CheckAndFixGOChairHeightId(goInfo,goInfo->barberChair.chairheight,0);
5594 break;
5598 sLog.outString( ">> Loaded %u game object templates", sGOStorage.RecordCount );
5599 sLog.outString();
5602 void ObjectMgr::LoadExplorationBaseXP()
5604 uint32 count = 0;
5605 QueryResult *result = WorldDatabase.Query("SELECT level,basexp FROM exploration_basexp");
5607 if( !result )
5609 barGoLink bar( 1 );
5611 bar.step();
5613 sLog.outString();
5614 sLog.outString( ">> Loaded %u BaseXP definitions", count );
5615 return;
5618 barGoLink bar( result->GetRowCount() );
5622 bar.step();
5624 Field *fields = result->Fetch();
5625 uint32 level = fields[0].GetUInt32();
5626 uint32 basexp = fields[1].GetUInt32();
5627 mBaseXPTable[level] = basexp;
5628 ++count;
5630 while (result->NextRow());
5632 delete result;
5634 sLog.outString();
5635 sLog.outString( ">> Loaded %u BaseXP definitions", count );
5638 uint32 ObjectMgr::GetBaseXP(uint32 level)
5640 return mBaseXPTable[level] ? mBaseXPTable[level] : 0;
5643 uint32 ObjectMgr::GetXPForLevel(uint32 level)
5645 if (level < mPlayerXPperLevel.size())
5646 return mPlayerXPperLevel[level];
5647 return 0;
5650 void ObjectMgr::LoadPetNames()
5652 uint32 count = 0;
5653 QueryResult *result = WorldDatabase.Query("SELECT word,entry,half FROM pet_name_generation");
5655 if( !result )
5657 barGoLink bar( 1 );
5659 bar.step();
5661 sLog.outString();
5662 sLog.outString( ">> Loaded %u pet name parts", count );
5663 return;
5666 barGoLink bar( result->GetRowCount() );
5670 bar.step();
5672 Field *fields = result->Fetch();
5673 std::string word = fields[0].GetString();
5674 uint32 entry = fields[1].GetUInt32();
5675 bool half = fields[2].GetBool();
5676 if(half)
5677 PetHalfName1[entry].push_back(word);
5678 else
5679 PetHalfName0[entry].push_back(word);
5680 ++count;
5682 while (result->NextRow());
5683 delete result;
5685 sLog.outString();
5686 sLog.outString( ">> Loaded %u pet name parts", count );
5689 void ObjectMgr::LoadPetNumber()
5691 QueryResult* result = CharacterDatabase.Query("SELECT MAX(id) FROM character_pet");
5692 if(result)
5694 Field *fields = result->Fetch();
5695 m_hiPetNumber = fields[0].GetUInt32()+1;
5696 delete result;
5699 barGoLink bar( 1 );
5700 bar.step();
5702 sLog.outString();
5703 sLog.outString( ">> Loaded the max pet number: %d", m_hiPetNumber-1);
5706 std::string ObjectMgr::GeneratePetName(uint32 entry)
5708 std::vector<std::string> & list0 = PetHalfName0[entry];
5709 std::vector<std::string> & list1 = PetHalfName1[entry];
5711 if(list0.empty() || list1.empty())
5713 CreatureInfo const *cinfo = GetCreatureTemplate(entry);
5714 char* petname = GetPetName(cinfo->family, sWorld.GetDefaultDbcLocale());
5715 if(!petname)
5716 petname = cinfo->Name;
5717 return std::string(petname);
5720 return *(list0.begin()+urand(0, list0.size()-1)) + *(list1.begin()+urand(0, list1.size()-1));
5723 uint32 ObjectMgr::GeneratePetNumber()
5725 return ++m_hiPetNumber;
5728 void ObjectMgr::LoadCorpses()
5730 uint32 count = 0;
5731 // 0 1 2 3 4 5 6 7 8 10
5732 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");
5734 if( !result )
5736 barGoLink bar( 1 );
5738 bar.step();
5740 sLog.outString();
5741 sLog.outString( ">> Loaded %u corpses", count );
5742 return;
5745 barGoLink bar( result->GetRowCount() );
5749 bar.step();
5751 Field *fields = result->Fetch();
5753 uint32 guid = fields[result->GetFieldCount()-1].GetUInt32();
5755 Corpse *corpse = new Corpse;
5756 if(!corpse->LoadFromDB(guid,fields))
5758 delete corpse;
5759 continue;
5762 ObjectAccessor::Instance().AddCorpse(corpse);
5764 ++count;
5766 while (result->NextRow());
5767 delete result;
5769 sLog.outString();
5770 sLog.outString( ">> Loaded %u corpses", count );
5773 void ObjectMgr::LoadReputationOnKill()
5775 uint32 count = 0;
5777 // 0 1 2
5778 QueryResult *result = WorldDatabase.Query("SELECT creature_id, RewOnKillRepFaction1, RewOnKillRepFaction2,"
5779 // 3 4 5 6 7 8 9
5780 "IsTeamAward1, MaxStanding1, RewOnKillRepValue1, IsTeamAward2, MaxStanding2, RewOnKillRepValue2, TeamDependent "
5781 "FROM creature_onkill_reputation");
5783 if(!result)
5785 barGoLink bar(1);
5787 bar.step();
5789 sLog.outString();
5790 sLog.outErrorDb(">> Loaded 0 creature award reputation definitions. DB table `creature_onkill_reputation` is empty.");
5791 return;
5794 barGoLink bar(result->GetRowCount());
5798 Field *fields = result->Fetch();
5799 bar.step();
5801 uint32 creature_id = fields[0].GetUInt32();
5803 ReputationOnKillEntry repOnKill;
5804 repOnKill.repfaction1 = fields[1].GetUInt32();
5805 repOnKill.repfaction2 = fields[2].GetUInt32();
5806 repOnKill.is_teamaward1 = fields[3].GetBool();
5807 repOnKill.reputation_max_cap1 = fields[4].GetUInt32();
5808 repOnKill.repvalue1 = fields[5].GetInt32();
5809 repOnKill.is_teamaward2 = fields[6].GetBool();
5810 repOnKill.reputation_max_cap2 = fields[7].GetUInt32();
5811 repOnKill.repvalue2 = fields[8].GetInt32();
5812 repOnKill.team_dependent = fields[9].GetUInt8();
5814 if(!GetCreatureTemplate(creature_id))
5816 sLog.outErrorDb("Table `creature_onkill_reputation` have data for not existed creature entry (%u), skipped",creature_id);
5817 continue;
5820 if(repOnKill.repfaction1)
5822 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(repOnKill.repfaction1);
5823 if(!factionEntry1)
5825 sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction1);
5826 continue;
5830 if(repOnKill.repfaction2)
5832 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(repOnKill.repfaction2);
5833 if(!factionEntry2)
5835 sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction2);
5836 continue;
5840 mRepOnKill[creature_id] = repOnKill;
5842 ++count;
5843 } while (result->NextRow());
5845 delete result;
5847 sLog.outString();
5848 sLog.outString(">> Loaded %u creature award reputation definitions", count);
5851 void ObjectMgr::LoadPointsOfInterest()
5853 uint32 count = 0;
5855 // 0 1 2 3 4 5
5856 QueryResult *result = WorldDatabase.Query("SELECT entry, x, y, icon, flags, data, icon_name FROM points_of_interest");
5858 if(!result)
5860 barGoLink bar(1);
5862 bar.step();
5864 sLog.outString();
5865 sLog.outErrorDb(">> Loaded 0 Points of Interest definitions. DB table `points_of_interest` is empty.");
5866 return;
5869 barGoLink bar(result->GetRowCount());
5873 Field *fields = result->Fetch();
5874 bar.step();
5876 uint32 point_id = fields[0].GetUInt32();
5878 PointOfInterest POI;
5879 POI.x = fields[1].GetFloat();
5880 POI.y = fields[2].GetFloat();
5881 POI.icon = fields[3].GetUInt32();
5882 POI.flags = fields[4].GetUInt32();
5883 POI.data = fields[5].GetUInt32();
5884 POI.icon_name = fields[6].GetCppString();
5886 if(!MaNGOS::IsValidMapCoord(POI.x,POI.y))
5888 sLog.outErrorDb("Table `points_of_interest` (Entry: %u) have invalid coordinates (X: %f Y: %f), ignored.",point_id,POI.x,POI.y);
5889 continue;
5892 mPointsOfInterest[point_id] = POI;
5894 ++count;
5895 } while (result->NextRow());
5897 delete result;
5899 sLog.outString();
5900 sLog.outString(">> Loaded %u Points of Interest definitions", count);
5903 void ObjectMgr::LoadNPCSpellClickSpells()
5905 uint32 count = 0;
5907 mSpellClickInfoMap.clear();
5909 QueryResult *result = WorldDatabase.Query("SELECT npc_entry, spell_id, quest_id, cast_flags FROM npc_spellclick_spells");
5911 if(!result)
5913 barGoLink bar(1);
5915 bar.step();
5917 sLog.outString();
5918 sLog.outErrorDb(">> Loaded 0 spellclick spells. DB table `npc_spellclick_spells` is empty.");
5919 return;
5922 barGoLink bar(result->GetRowCount());
5926 Field *fields = result->Fetch();
5927 bar.step();
5929 uint32 npc_entry = fields[0].GetUInt32();
5930 CreatureInfo const* cInfo = GetCreatureTemplate(npc_entry);
5931 if (!cInfo)
5933 sLog.outErrorDb("Table npc_spellclick_spells references unknown creature_template %u. Skipping entry.", npc_entry);
5934 continue;
5937 uint32 spellid = fields[1].GetUInt32();
5938 SpellEntry const *spellinfo = sSpellStore.LookupEntry(spellid);
5939 if (!spellinfo)
5941 sLog.outErrorDb("Table npc_spellclick_spells references unknown spellid %u. Skipping entry.", spellid);
5942 continue;
5945 uint32 quest = fields[2].GetUInt32();
5947 // quest might be 0 to enable spellclick independent of any quest
5948 if (quest)
5950 if(mQuestTemplates.find(quest) == mQuestTemplates.end())
5952 sLog.outErrorDb("Table npc_spellclick_spells references unknown quest %u. Skipping entry.", spellid);
5953 continue;
5958 uint8 castFlags = fields[3].GetUInt8();
5959 SpellClickInfo info;
5960 info.spellId = spellid;
5961 info.questId = quest;
5962 info.castFlags = castFlags;
5963 mSpellClickInfoMap.insert(SpellClickInfoMap::value_type(npc_entry, info));
5964 ++count;
5965 } while (result->NextRow());
5967 delete result;
5969 sLog.outString();
5970 sLog.outString(">> Loaded %u spellclick definitions", count);
5973 void ObjectMgr::LoadWeatherZoneChances()
5975 uint32 count = 0;
5977 // 0 1 2 3 4 5 6 7 8 9 10 11 12
5978 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");
5980 if(!result)
5982 barGoLink bar(1);
5984 bar.step();
5986 sLog.outString();
5987 sLog.outErrorDb(">> Loaded 0 weather definitions. DB table `game_weather` is empty.");
5988 return;
5991 barGoLink bar(result->GetRowCount());
5995 Field *fields = result->Fetch();
5996 bar.step();
5998 uint32 zone_id = fields[0].GetUInt32();
6000 WeatherZoneChances& wzc = mWeatherZoneMap[zone_id];
6002 for(int season = 0; season < WEATHER_SEASONS; ++season)
6004 wzc.data[season].rainChance = fields[season * (MAX_WEATHER_TYPE-1) + 1].GetUInt32();
6005 wzc.data[season].snowChance = fields[season * (MAX_WEATHER_TYPE-1) + 2].GetUInt32();
6006 wzc.data[season].stormChance = fields[season * (MAX_WEATHER_TYPE-1) + 3].GetUInt32();
6008 if(wzc.data[season].rainChance > 100)
6010 wzc.data[season].rainChance = 25;
6011 sLog.outErrorDb("Weather for zone %u season %u has wrong rain chance > 100%%",zone_id,season);
6014 if(wzc.data[season].snowChance > 100)
6016 wzc.data[season].snowChance = 25;
6017 sLog.outErrorDb("Weather for zone %u season %u has wrong snow chance > 100%%",zone_id,season);
6020 if(wzc.data[season].stormChance > 100)
6022 wzc.data[season].stormChance = 25;
6023 sLog.outErrorDb("Weather for zone %u season %u has wrong storm chance > 100%%",zone_id,season);
6027 ++count;
6028 } while (result->NextRow());
6030 delete result;
6032 sLog.outString();
6033 sLog.outString(">> Loaded %u weather definitions", count);
6036 void ObjectMgr::SaveCreatureRespawnTime(uint32 loguid, uint32 instance, time_t t)
6038 mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
6039 WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
6040 if(t)
6041 WorldDatabase.PExecute("INSERT INTO creature_respawn VALUES ( '%u', '" UI64FMTD "', '%u' )", loguid, uint64(t), instance);
6044 void ObjectMgr::DeleteCreatureData(uint32 guid)
6046 // remove mapid*cellid -> guid_set map
6047 CreatureData const* data = GetCreatureData(guid);
6048 if(data)
6049 RemoveCreatureFromGrid(guid, data);
6051 mCreatureDataMap.erase(guid);
6054 void ObjectMgr::SaveGORespawnTime(uint32 loguid, uint32 instance, time_t t)
6056 mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
6057 WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
6058 if(t)
6059 WorldDatabase.PExecute("INSERT INTO gameobject_respawn VALUES ( '%u', '" UI64FMTD "', '%u' )", loguid, uint64(t), instance);
6062 void ObjectMgr::DeleteRespawnTimeForInstance(uint32 instance)
6064 RespawnTimes::iterator next;
6066 for(RespawnTimes::iterator itr = mGORespawnTimes.begin(); itr != mGORespawnTimes.end(); itr = next)
6068 next = itr;
6069 ++next;
6071 if(GUID_HIPART(itr->first)==instance)
6072 mGORespawnTimes.erase(itr);
6075 for(RespawnTimes::iterator itr = mCreatureRespawnTimes.begin(); itr != mCreatureRespawnTimes.end(); itr = next)
6077 next = itr;
6078 ++next;
6080 if(GUID_HIPART(itr->first)==instance)
6081 mCreatureRespawnTimes.erase(itr);
6084 WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE instance = '%u'", instance);
6085 WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE instance = '%u'", instance);
6088 void ObjectMgr::DeleteGOData(uint32 guid)
6090 // remove mapid*cellid -> guid_set map
6091 GameObjectData const* data = GetGOData(guid);
6092 if(data)
6093 RemoveGameobjectFromGrid(guid, data);
6095 mGameObjectDataMap.erase(guid);
6098 void ObjectMgr::AddCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid, uint32 instance)
6100 // corpses are always added to spawn mode 0 and they are spawned by their instance id
6101 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
6102 cell_guids.corpses[player_guid] = instance;
6105 void ObjectMgr::DeleteCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid)
6107 // corpses are always added to spawn mode 0 and they are spawned by their instance id
6108 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
6109 cell_guids.corpses.erase(player_guid);
6112 void ObjectMgr::LoadQuestRelationsHelper(QuestRelations& map,char const* table)
6114 map.clear(); // need for reload case
6116 uint32 count = 0;
6118 QueryResult *result = WorldDatabase.PQuery("SELECT id,quest FROM %s",table);
6120 if(!result)
6122 barGoLink bar(1);
6124 bar.step();
6126 sLog.outString();
6127 sLog.outErrorDb(">> Loaded 0 quest relations from %s. DB table `%s` is empty.",table,table);
6128 return;
6131 barGoLink bar(result->GetRowCount());
6135 Field *fields = result->Fetch();
6136 bar.step();
6138 uint32 id = fields[0].GetUInt32();
6139 uint32 quest = fields[1].GetUInt32();
6141 if(mQuestTemplates.find(quest) == mQuestTemplates.end())
6143 sLog.outErrorDb("Table `%s: Quest %u listed for entry %u does not exist.",table,quest,id);
6144 continue;
6147 map.insert(QuestRelations::value_type(id,quest));
6149 ++count;
6150 } while (result->NextRow());
6152 delete result;
6154 sLog.outString();
6155 sLog.outString(">> Loaded %u quest relations from %s", count,table);
6158 void ObjectMgr::LoadGameobjectQuestRelations()
6160 LoadQuestRelationsHelper(mGOQuestRelations,"gameobject_questrelation");
6162 for(QuestRelations::iterator itr = mGOQuestRelations.begin(); itr != mGOQuestRelations.end(); ++itr)
6164 GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
6165 if(!goInfo)
6166 sLog.outErrorDb("Table `gameobject_questrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
6167 else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
6168 sLog.outErrorDb("Table `gameobject_questrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
6172 void ObjectMgr::LoadGameobjectInvolvedRelations()
6174 LoadQuestRelationsHelper(mGOQuestInvolvedRelations,"gameobject_involvedrelation");
6176 for(QuestRelations::iterator itr = mGOQuestInvolvedRelations.begin(); itr != mGOQuestInvolvedRelations.end(); ++itr)
6178 GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
6179 if(!goInfo)
6180 sLog.outErrorDb("Table `gameobject_involvedrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
6181 else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
6182 sLog.outErrorDb("Table `gameobject_involvedrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
6186 void ObjectMgr::LoadCreatureQuestRelations()
6188 LoadQuestRelationsHelper(mCreatureQuestRelations,"creature_questrelation");
6190 for(QuestRelations::iterator itr = mCreatureQuestRelations.begin(); itr != mCreatureQuestRelations.end(); ++itr)
6192 CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
6193 if(!cInfo)
6194 sLog.outErrorDb("Table `creature_questrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
6195 else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
6196 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);
6200 void ObjectMgr::LoadCreatureInvolvedRelations()
6202 LoadQuestRelationsHelper(mCreatureQuestInvolvedRelations,"creature_involvedrelation");
6204 for(QuestRelations::iterator itr = mCreatureQuestInvolvedRelations.begin(); itr != mCreatureQuestInvolvedRelations.end(); ++itr)
6206 CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
6207 if(!cInfo)
6208 sLog.outErrorDb("Table `creature_involvedrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
6209 else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
6210 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);
6214 void ObjectMgr::LoadReservedPlayersNames()
6216 m_ReservedNames.clear(); // need for reload case
6218 QueryResult *result = WorldDatabase.Query("SELECT name FROM reserved_name");
6220 uint32 count = 0;
6222 if( !result )
6224 barGoLink bar( 1 );
6225 bar.step();
6227 sLog.outString();
6228 sLog.outString( ">> Loaded %u reserved player names", count );
6229 return;
6232 barGoLink bar( result->GetRowCount() );
6234 Field* fields;
6237 bar.step();
6238 fields = result->Fetch();
6239 std::string name= fields[0].GetCppString();
6241 std::wstring wstr;
6242 if(!Utf8toWStr (name,wstr))
6244 sLog.outError("Table `reserved_name` have invalid name: %s", name.c_str() );
6245 continue;
6248 wstrToLower(wstr);
6250 m_ReservedNames.insert(wstr);
6251 ++count;
6252 } while ( result->NextRow() );
6254 delete result;
6256 sLog.outString();
6257 sLog.outString( ">> Loaded %u reserved player names", count );
6260 bool ObjectMgr::IsReservedName( const std::string& name ) const
6262 std::wstring wstr;
6263 if(!Utf8toWStr (name,wstr))
6264 return false;
6266 wstrToLower(wstr);
6268 return m_ReservedNames.find(wstr) != m_ReservedNames.end();
6271 enum LanguageType
6273 LT_BASIC_LATIN = 0x0000,
6274 LT_EXTENDEN_LATIN = 0x0001,
6275 LT_CYRILLIC = 0x0002,
6276 LT_EAST_ASIA = 0x0004,
6277 LT_ANY = 0xFFFF
6280 static LanguageType GetRealmLanguageType(bool create)
6282 switch(sWorld.getConfig(CONFIG_REALM_ZONE))
6284 case REALM_ZONE_UNKNOWN: // any language
6285 case REALM_ZONE_DEVELOPMENT:
6286 case REALM_ZONE_TEST_SERVER:
6287 case REALM_ZONE_QA_SERVER:
6288 return LT_ANY;
6289 case REALM_ZONE_UNITED_STATES: // extended-Latin
6290 case REALM_ZONE_OCEANIC:
6291 case REALM_ZONE_LATIN_AMERICA:
6292 case REALM_ZONE_ENGLISH:
6293 case REALM_ZONE_GERMAN:
6294 case REALM_ZONE_FRENCH:
6295 case REALM_ZONE_SPANISH:
6296 return LT_EXTENDEN_LATIN;
6297 case REALM_ZONE_KOREA: // East-Asian
6298 case REALM_ZONE_TAIWAN:
6299 case REALM_ZONE_CHINA:
6300 return LT_EAST_ASIA;
6301 case REALM_ZONE_RUSSIAN: // Cyrillic
6302 return LT_CYRILLIC;
6303 default:
6304 return create ? LT_BASIC_LATIN : LT_ANY; // basic-Latin at create, any at login
6308 bool isValidString(std::wstring wstr, uint32 strictMask, bool numericOrSpace, bool create = false)
6310 if(strictMask==0) // any language, ignore realm
6312 if(isExtendedLatinString(wstr,numericOrSpace))
6313 return true;
6314 if(isCyrillicString(wstr,numericOrSpace))
6315 return true;
6316 if(isEastAsianString(wstr,numericOrSpace))
6317 return true;
6318 return false;
6321 if(strictMask & 0x2) // realm zone specific
6323 LanguageType lt = GetRealmLanguageType(create);
6324 if(lt & LT_EXTENDEN_LATIN)
6325 if(isExtendedLatinString(wstr,numericOrSpace))
6326 return true;
6327 if(lt & LT_CYRILLIC)
6328 if(isCyrillicString(wstr,numericOrSpace))
6329 return true;
6330 if(lt & LT_EAST_ASIA)
6331 if(isEastAsianString(wstr,numericOrSpace))
6332 return true;
6335 if(strictMask & 0x1) // basic Latin
6337 if(isBasicLatinString(wstr,numericOrSpace))
6338 return true;
6341 return false;
6344 bool ObjectMgr::IsValidName( const std::string& name, bool create )
6346 std::wstring wname;
6347 if(!Utf8toWStr(name,wname))
6348 return false;
6350 if(wname.size() < 1 || wname.size() > MAX_PLAYER_NAME)
6351 return false;
6353 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_PLAYER_NAMES);
6355 return isValidString(wname,strictMask,false,create);
6358 bool ObjectMgr::IsValidCharterName( const std::string& name )
6360 std::wstring wname;
6361 if(!Utf8toWStr(name,wname))
6362 return false;
6364 if(wname.size() < 1)
6365 return false;
6367 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_CHARTER_NAMES);
6369 return isValidString(wname,strictMask,true);
6372 bool ObjectMgr::IsValidPetName( const std::string& name )
6374 std::wstring wname;
6375 if(!Utf8toWStr(name,wname))
6376 return false;
6378 if(wname.size() < 1)
6379 return false;
6381 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_PET_NAMES);
6383 return isValidString(wname,strictMask,false);
6386 int ObjectMgr::GetIndexForLocale( LocaleConstant loc )
6388 if(loc==LOCALE_enUS)
6389 return -1;
6391 for(size_t i=0;i < m_LocalForIndex.size(); ++i)
6392 if(m_LocalForIndex[i]==loc)
6393 return i;
6395 return -1;
6398 LocaleConstant ObjectMgr::GetLocaleForIndex(int i)
6400 if (i<0 || i>=m_LocalForIndex.size())
6401 return LOCALE_enUS;
6403 return m_LocalForIndex[i];
6406 int ObjectMgr::GetOrNewIndexForLocale( LocaleConstant loc )
6408 if(loc==LOCALE_enUS)
6409 return -1;
6411 for(size_t i=0;i < m_LocalForIndex.size(); ++i)
6412 if(m_LocalForIndex[i]==loc)
6413 return i;
6415 m_LocalForIndex.push_back(loc);
6416 return m_LocalForIndex.size()-1;
6419 void ObjectMgr::LoadGameObjectForQuests()
6421 mGameObjectForQuestSet.clear(); // need for reload case
6423 if( !sGOStorage.MaxEntry )
6425 barGoLink bar( 1 );
6426 bar.step();
6427 sLog.outString();
6428 sLog.outString( ">> Loaded 0 GameObjects for quests" );
6429 return;
6432 barGoLink bar( sGOStorage.MaxEntry - 1 );
6433 uint32 count = 0;
6435 // collect GO entries for GO that must activated
6436 for(uint32 go_entry = 1; go_entry < sGOStorage.MaxEntry; ++go_entry)
6438 bar.step();
6439 GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(go_entry);
6440 if(!goInfo)
6441 continue;
6443 switch(goInfo->type)
6445 // scan GO chest with loot including quest items
6446 case GAMEOBJECT_TYPE_CHEST:
6448 uint32 loot_id = GameObject::GetLootId(goInfo);
6450 // find quest loot for GO
6451 if(LootTemplates_Gameobject.HaveQuestLootFor(loot_id))
6453 mGameObjectForQuestSet.insert(go_entry);
6454 ++count;
6456 break;
6458 case GAMEOBJECT_TYPE_GOOBER:
6460 if(goInfo->goober.questId) //quests objects
6462 mGameObjectForQuestSet.insert(go_entry);
6463 count++;
6465 break;
6467 default:
6468 break;
6472 sLog.outString();
6473 sLog.outString( ">> Loaded %u GameObjects for quests", count );
6476 bool ObjectMgr::LoadMangosStrings(DatabaseType& db, char const* table, int32 min_value, int32 max_value)
6478 int32 start_value = min_value;
6479 int32 end_value = max_value;
6480 // some string can have negative indexes range
6481 if (start_value < 0)
6483 if (end_value >= start_value)
6485 sLog.outErrorDb("Table '%s' attempt loaded with invalid range (%d - %d), strings not loaded.",table,min_value,max_value);
6486 return false;
6489 // real range (max+1,min+1) exaple: (-10,-1000) -> -999...-10+1
6490 std::swap(start_value,end_value);
6491 ++start_value;
6492 ++end_value;
6494 else
6496 if (start_value >= end_value)
6498 sLog.outErrorDb("Table '%s' attempt loaded with invalid range (%d - %d), strings not loaded.",table,min_value,max_value);
6499 return false;
6503 // cleanup affected map part for reloading case
6504 for(MangosStringLocaleMap::iterator itr = mMangosStringLocaleMap.begin(); itr != mMangosStringLocaleMap.end();)
6506 if (itr->first >= start_value && itr->first < end_value)
6507 mMangosStringLocaleMap.erase(itr++);
6508 else
6509 ++itr;
6512 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);
6514 if (!result)
6516 barGoLink bar(1);
6518 bar.step();
6520 sLog.outString();
6521 if (min_value == MIN_MANGOS_STRING_ID) // error only in case internal strings
6522 sLog.outErrorDb(">> Loaded 0 mangos strings. DB table `%s` is empty. Cannot continue.",table);
6523 else
6524 sLog.outString(">> Loaded 0 string templates. DB table `%s` is empty.",table);
6525 return false;
6528 uint32 count = 0;
6530 barGoLink bar(result->GetRowCount());
6534 Field *fields = result->Fetch();
6535 bar.step();
6537 int32 entry = fields[0].GetInt32();
6539 if (entry==0)
6541 sLog.outErrorDb("Table `%s` contain reserved entry 0, ignored.",table);
6542 continue;
6544 else if (entry < start_value || entry >= end_value)
6546 sLog.outErrorDb("Table `%s` contain entry %i out of allowed range (%d - %d), ignored.",table,entry,min_value,max_value);
6547 continue;
6550 MangosStringLocale& data = mMangosStringLocaleMap[entry];
6552 if (data.Content.size() > 0)
6554 sLog.outErrorDb("Table `%s` contain data for already loaded entry %i (from another table?), ignored.",table,entry);
6555 continue;
6558 data.Content.resize(1);
6559 ++count;
6561 // 0 -> default, idx in to idx+1
6562 data.Content[0] = fields[1].GetCppString();
6564 for(int i = 1; i < MAX_LOCALE; ++i)
6566 std::string str = fields[i+1].GetCppString();
6567 if (!str.empty())
6569 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
6570 if (idx >= 0)
6572 // 0 -> default, idx in to idx+1
6573 if (data.Content.size() <= idx+1)
6574 data.Content.resize(idx+2);
6576 data.Content[idx+1] = str;
6580 } while (result->NextRow());
6582 delete result;
6584 sLog.outString();
6585 if (min_value == MIN_MANGOS_STRING_ID)
6586 sLog.outString( ">> Loaded %u MaNGOS strings from table %s", count,table);
6587 else
6588 sLog.outString( ">> Loaded %u string templates from %s", count,table);
6590 return true;
6593 const char *ObjectMgr::GetMangosString(int32 entry, int locale_idx) const
6595 // locale_idx==-1 -> default, locale_idx >= 0 in to idx+1
6596 // Content[0] always exist if exist MangosStringLocale
6597 if(MangosStringLocale const *msl = GetMangosStringLocale(entry))
6599 if(msl->Content.size() > locale_idx+1 && !msl->Content[locale_idx+1].empty())
6600 return msl->Content[locale_idx+1].c_str();
6601 else
6602 return msl->Content[0].c_str();
6605 if(entry > 0)
6606 sLog.outErrorDb("Entry %i not found in `mangos_string` table.",entry);
6607 else
6608 sLog.outErrorDb("Mangos string entry %i not found in DB.",entry);
6609 return "<error>";
6612 void ObjectMgr::LoadFishingBaseSkillLevel()
6614 mFishingBaseForArea.clear(); // for reload case
6616 uint32 count = 0;
6617 QueryResult *result = WorldDatabase.Query("SELECT entry,skill FROM skill_fishing_base_level");
6619 if( !result )
6621 barGoLink bar( 1 );
6623 bar.step();
6625 sLog.outString();
6626 sLog.outErrorDb(">> Loaded `skill_fishing_base_level`, table is empty!");
6627 return;
6630 barGoLink bar( result->GetRowCount() );
6634 bar.step();
6636 Field *fields = result->Fetch();
6637 uint32 entry = fields[0].GetUInt32();
6638 int32 skill = fields[1].GetInt32();
6640 AreaTableEntry const* fArea = GetAreaEntryByAreaID(entry);
6641 if(!fArea)
6643 sLog.outErrorDb("AreaId %u defined in `skill_fishing_base_level` does not exist",entry);
6644 continue;
6647 mFishingBaseForArea[entry] = skill;
6648 ++count;
6650 while (result->NextRow());
6652 delete result;
6654 sLog.outString();
6655 sLog.outString( ">> Loaded %u areas for fishing base skill level", count );
6658 // Searches for the same condition already in Conditions store
6659 // Returns Id if found, else adds it to Conditions and returns Id
6660 uint16 ObjectMgr::GetConditionId( ConditionType condition, uint32 value1, uint32 value2 )
6662 PlayerCondition lc = PlayerCondition(condition, value1, value2);
6663 for (uint16 i=0; i < mConditions.size(); ++i)
6665 if (lc == mConditions[i])
6666 return i;
6669 mConditions.push_back(lc);
6671 if(mConditions.size() > 0xFFFF)
6673 sLog.outError("Conditions store overflow! Current and later loaded conditions will ignored!");
6674 return 0;
6677 return mConditions.size() - 1;
6680 bool ObjectMgr::CheckDeclinedNames( std::wstring mainpart, DeclinedName const& names )
6682 for(int i =0; i < MAX_DECLINED_NAME_CASES; ++i)
6684 std::wstring wname;
6685 if(!Utf8toWStr(names.name[i],wname))
6686 return false;
6688 if(mainpart!=GetMainPartOfName(wname,i+1))
6689 return false;
6691 return true;
6694 uint32 ObjectMgr::GetAreaTriggerScriptId(uint32 trigger_id)
6696 AreaTriggerScriptMap::const_iterator i = mAreaTriggerScripts.find(trigger_id);
6697 if(i!= mAreaTriggerScripts.end())
6698 return i->second;
6699 return 0;
6702 // Checks if player meets the condition
6703 bool PlayerCondition::Meets(Player const * player) const
6705 if( !player )
6706 return false; // player not present, return false
6708 switch (condition)
6710 case CONDITION_NONE:
6711 return true; // empty condition, always met
6712 case CONDITION_AURA:
6713 return player->HasAura(value1, value2);
6714 case CONDITION_ITEM:
6715 return player->HasItemCount(value1, value2);
6716 case CONDITION_ITEM_EQUIPPED:
6717 return player->HasItemOrGemWithIdEquipped(value1,1);
6718 case CONDITION_ZONEID:
6719 return player->GetZoneId() == value1;
6720 case CONDITION_REPUTATION_RANK:
6722 FactionEntry const* faction = sFactionStore.LookupEntry(value1);
6723 return faction && player->GetReputationMgr().GetRank(faction) >= value2;
6725 case CONDITION_TEAM:
6726 return player->GetTeam() == value1;
6727 case CONDITION_SKILL:
6728 return player->HasSkill(value1) && player->GetBaseSkillValue(value1) >= value2;
6729 case CONDITION_QUESTREWARDED:
6730 return player->GetQuestRewardStatus(value1);
6731 case CONDITION_QUESTTAKEN:
6733 QuestStatus status = player->GetQuestStatus(value1);
6734 return (status == QUEST_STATUS_INCOMPLETE);
6736 case CONDITION_AD_COMMISSION_AURA:
6738 Unit::AuraMap const& auras = player->GetAuras();
6739 for(Unit::AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
6740 if((itr->second->GetSpellProto()->Attributes & 0x1000010) && itr->second->GetSpellProto()->SpellVisual[0]==3580)
6741 return true;
6742 return false;
6744 case CONDITION_NO_AURA:
6745 return !player->HasAura(value1, value2);
6746 case CONDITION_ACTIVE_EVENT:
6747 return gameeventmgr.IsActiveEvent(value1);
6748 default:
6749 return false;
6753 // Verification of condition values validity
6754 bool PlayerCondition::IsValid(ConditionType condition, uint32 value1, uint32 value2)
6756 if( condition >= MAX_CONDITION) // Wrong condition type
6758 sLog.outErrorDb("Condition has bad type of %u, skipped ", condition );
6759 return false;
6762 switch (condition)
6764 case CONDITION_AURA:
6766 if(!sSpellStore.LookupEntry(value1))
6768 sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
6769 return false;
6771 if(value2 > 2)
6773 sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..2), skipped", value2);
6774 return false;
6776 break;
6778 case CONDITION_ITEM:
6780 ItemPrototype const *proto = objmgr.GetItemPrototype(value1);
6781 if(!proto)
6783 sLog.outErrorDb("Item condition requires to have non existing item (%u), skipped", value1);
6784 return false;
6786 break;
6788 case CONDITION_ITEM_EQUIPPED:
6790 ItemPrototype const *proto = objmgr.GetItemPrototype(value1);
6791 if(!proto)
6793 sLog.outErrorDb("ItemEquipped condition requires to have non existing item (%u) equipped, skipped", value1);
6794 return false;
6796 break;
6798 case CONDITION_ZONEID:
6800 AreaTableEntry const* areaEntry = GetAreaEntryByAreaID(value1);
6801 if(!areaEntry)
6803 sLog.outErrorDb("Zone condition requires to be in non existing area (%u), skipped", value1);
6804 return false;
6806 if(areaEntry->zone != 0)
6808 sLog.outErrorDb("Zone condition requires to be in area (%u) which is a subzone but zone expected, skipped", value1);
6809 return false;
6811 break;
6813 case CONDITION_REPUTATION_RANK:
6815 FactionEntry const* factionEntry = sFactionStore.LookupEntry(value1);
6816 if(!factionEntry)
6818 sLog.outErrorDb("Reputation condition requires to have reputation non existing faction (%u), skipped", value1);
6819 return false;
6821 break;
6823 case CONDITION_TEAM:
6825 if (value1 != ALLIANCE && value1 != HORDE)
6827 sLog.outErrorDb("Team condition specifies unknown team (%u), skipped", value1);
6828 return false;
6830 break;
6832 case CONDITION_SKILL:
6834 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(value1);
6835 if (!pSkill)
6837 sLog.outErrorDb("Skill condition specifies non-existing skill (%u), skipped", value1);
6838 return false;
6840 if (value2 < 1 || value2 > sWorld.GetConfigMaxSkillValue() )
6842 sLog.outErrorDb("Skill condition specifies invalid skill value (%u), skipped", value2);
6843 return false;
6845 break;
6847 case CONDITION_QUESTREWARDED:
6848 case CONDITION_QUESTTAKEN:
6850 Quest const *Quest = objmgr.GetQuestTemplate(value1);
6851 if (!Quest)
6853 sLog.outErrorDb("Quest condition specifies non-existing quest (%u), skipped", value1);
6854 return false;
6856 if(value2)
6857 sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
6858 break;
6860 case CONDITION_AD_COMMISSION_AURA:
6862 if(value1)
6863 sLog.outErrorDb("Quest condition has useless data in value1 (%u)!", value1);
6864 if(value2)
6865 sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
6866 break;
6868 case CONDITION_NO_AURA:
6870 if(!sSpellStore.LookupEntry(value1))
6872 sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
6873 return false;
6875 if(value2 > 2)
6877 sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..2), skipped", value2);
6878 return false;
6880 break;
6882 case CONDITION_ACTIVE_EVENT:
6884 GameEventMgr::GameEventDataMap const& events = gameeventmgr.GetEventMap();
6885 if(value1 >=events.size() || !events[value1].isValid())
6887 sLog.outErrorDb("Active event condition requires existed event id (%u), skipped", value1);
6888 return false;
6890 break;
6892 case CONDITION_NONE:
6893 break;
6895 return true;
6898 SkillRangeType GetSkillRangeType(SkillLineEntry const *pSkill, bool racial)
6900 switch(pSkill->categoryId)
6902 case SKILL_CATEGORY_LANGUAGES: return SKILL_RANGE_LANGUAGE;
6903 case SKILL_CATEGORY_WEAPON:
6904 if(pSkill->id!=SKILL_FIST_WEAPONS)
6905 return SKILL_RANGE_LEVEL;
6906 else
6907 return SKILL_RANGE_MONO;
6908 case SKILL_CATEGORY_ARMOR:
6909 case SKILL_CATEGORY_CLASS:
6910 if(pSkill->id != SKILL_LOCKPICKING)
6911 return SKILL_RANGE_MONO;
6912 else
6913 return SKILL_RANGE_LEVEL;
6914 case SKILL_CATEGORY_SECONDARY:
6915 case SKILL_CATEGORY_PROFESSION:
6916 // not set skills for professions and racial abilities
6917 if(IsProfessionSkill(pSkill->id))
6918 return SKILL_RANGE_RANK;
6919 else if(racial)
6920 return SKILL_RANGE_NONE;
6921 else
6922 return SKILL_RANGE_MONO;
6923 default:
6924 case SKILL_CATEGORY_ATTRIBUTES: //not found in dbc
6925 case SKILL_CATEGORY_GENERIC: //only GENERIC(DND)
6926 return SKILL_RANGE_NONE;
6930 void ObjectMgr::LoadGameTele()
6932 m_GameTeleMap.clear(); // for reload case
6934 uint32 count = 0;
6935 QueryResult *result = WorldDatabase.Query("SELECT id, position_x, position_y, position_z, orientation, map, name FROM game_tele");
6937 if( !result )
6939 barGoLink bar( 1 );
6941 bar.step();
6943 sLog.outString();
6944 sLog.outErrorDb(">> Loaded `game_tele`, table is empty!");
6945 return;
6948 barGoLink bar( result->GetRowCount() );
6952 bar.step();
6954 Field *fields = result->Fetch();
6956 uint32 id = fields[0].GetUInt32();
6958 GameTele gt;
6960 gt.position_x = fields[1].GetFloat();
6961 gt.position_y = fields[2].GetFloat();
6962 gt.position_z = fields[3].GetFloat();
6963 gt.orientation = fields[4].GetFloat();
6964 gt.mapId = fields[5].GetUInt32();
6965 gt.name = fields[6].GetCppString();
6967 if(!MapManager::IsValidMapCoord(gt.mapId,gt.position_x,gt.position_y,gt.position_z,gt.orientation))
6969 sLog.outErrorDb("Wrong position for id %u (name: %s) in `game_tele` table, ignoring.",id,gt.name.c_str());
6970 continue;
6973 if(!Utf8toWStr(gt.name,gt.wnameLow))
6975 sLog.outErrorDb("Wrong UTF8 name for id %u in `game_tele` table, ignoring.",id);
6976 continue;
6979 wstrToLower( gt.wnameLow );
6981 m_GameTeleMap[id] = gt;
6983 ++count;
6985 while (result->NextRow());
6986 delete result;
6988 sLog.outString();
6989 sLog.outString( ">> Loaded %u GameTeleports", count );
6992 GameTele const* ObjectMgr::GetGameTele(const std::string& name) const
6994 // explicit name case
6995 std::wstring wname;
6996 if(!Utf8toWStr(name,wname))
6997 return false;
6999 // converting string that we try to find to lower case
7000 wstrToLower( wname );
7002 // Alternative first GameTele what contains wnameLow as substring in case no GameTele location found
7003 const GameTele* alt = NULL;
7004 for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
7005 if(itr->second.wnameLow == wname)
7006 return &itr->second;
7007 else if (alt == NULL && itr->second.wnameLow.find(wname) != std::wstring::npos)
7008 alt = &itr->second;
7010 return alt;
7013 bool ObjectMgr::AddGameTele(GameTele& tele)
7015 // find max id
7016 uint32 new_id = 0;
7017 for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
7018 if(itr->first > new_id)
7019 new_id = itr->first;
7021 // use next
7022 ++new_id;
7024 if(!Utf8toWStr(tele.name,tele.wnameLow))
7025 return false;
7027 wstrToLower( tele.wnameLow );
7029 m_GameTeleMap[new_id] = tele;
7031 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')",
7032 new_id,tele.position_x,tele.position_y,tele.position_z,tele.orientation,tele.mapId,tele.name.c_str());
7035 bool ObjectMgr::DeleteGameTele(const std::string& name)
7037 // explicit name case
7038 std::wstring wname;
7039 if(!Utf8toWStr(name,wname))
7040 return false;
7042 // converting string that we try to find to lower case
7043 wstrToLower( wname );
7045 for(GameTeleMap::iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
7047 if(itr->second.wnameLow == wname)
7049 WorldDatabase.PExecuteLog("DELETE FROM game_tele WHERE name = '%s'",itr->second.name.c_str());
7050 m_GameTeleMap.erase(itr);
7051 return true;
7055 return false;
7058 void ObjectMgr::LoadTrainerSpell()
7060 // For reload case
7061 for (CacheTrainerSpellMap::iterator itr = m_mCacheTrainerSpellMap.begin(); itr != m_mCacheTrainerSpellMap.end(); ++itr)
7062 itr->second.Clear();
7063 m_mCacheTrainerSpellMap.clear();
7065 std::set<uint32> skip_trainers;
7067 QueryResult *result = WorldDatabase.Query("SELECT entry, spell,spellcost,reqskill,reqskillvalue,reqlevel FROM npc_trainer");
7069 if( !result )
7071 barGoLink bar( 1 );
7073 bar.step();
7075 sLog.outString();
7076 sLog.outErrorDb(">> Loaded `npc_trainer`, table is empty!");
7077 return;
7080 barGoLink bar( result->GetRowCount() );
7082 uint32 count = 0;
7085 bar.step();
7087 Field* fields = result->Fetch();
7089 uint32 entry = fields[0].GetUInt32();
7090 uint32 spell = fields[1].GetUInt32();
7092 CreatureInfo const* cInfo = GetCreatureTemplate(entry);
7094 if(!cInfo)
7096 sLog.outErrorDb("Table `npc_trainer` have entry for not existed creature template (Entry: %u), ignore", entry);
7097 continue;
7100 if(!(cInfo->npcflag & UNIT_NPC_FLAG_TRAINER))
7102 if(skip_trainers.count(entry) == 0)
7104 sLog.outErrorDb("Table `npc_trainer` have data for not creature template (Entry: %u) without trainer flag, ignore", entry);
7105 skip_trainers.insert(entry);
7107 continue;
7110 SpellEntry const *spellinfo = sSpellStore.LookupEntry(spell);
7111 if(!spellinfo)
7113 sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u ) has non existing spell %u, ignore", entry,spell);
7114 continue;
7117 if(!SpellMgr::IsSpellValid(spellinfo))
7119 sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u) has broken learning spell %u, ignore", entry, spell);
7120 continue;
7123 TrainerSpellData& data = m_mCacheTrainerSpellMap[entry];
7125 TrainerSpell& trainerSpell = data.spellList[spell];
7126 trainerSpell.spell = spell;
7127 trainerSpell.spellCost = fields[2].GetUInt32();
7128 trainerSpell.reqSkill = fields[3].GetUInt32();
7129 trainerSpell.reqSkillValue = fields[4].GetUInt32();
7130 trainerSpell.reqLevel = fields[5].GetUInt32();
7132 if(!trainerSpell.reqLevel)
7133 trainerSpell.reqLevel = spellinfo->spellLevel;
7135 // calculate learned spell for profession case when stored cast-spell
7136 trainerSpell.learnedSpell = spell;
7137 for(int i = 0; i <3; ++i)
7139 if(spellinfo->Effect[i] != SPELL_EFFECT_LEARN_SPELL)
7140 continue;
7141 if(SpellMgr::IsProfessionOrRidingSpell(spellinfo->EffectTriggerSpell[i]))
7143 trainerSpell.learnedSpell = spellinfo->EffectTriggerSpell[i];
7144 break;
7148 if(SpellMgr::IsProfessionSpell(trainerSpell.learnedSpell))
7149 data.trainerType = 2;
7151 ++count;
7153 } while (result->NextRow());
7154 delete result;
7156 sLog.outString();
7157 sLog.outString( ">> Loaded %d Trainers", count );
7160 void ObjectMgr::LoadVendors()
7162 // For reload case
7163 for (CacheVendorItemMap::iterator itr = m_mCacheVendorItemMap.begin(); itr != m_mCacheVendorItemMap.end(); ++itr)
7164 itr->second.Clear();
7165 m_mCacheVendorItemMap.clear();
7167 std::set<uint32> skip_vendors;
7169 QueryResult *result = WorldDatabase.Query("SELECT entry, item, maxcount, incrtime, ExtendedCost FROM npc_vendor");
7170 if( !result )
7172 barGoLink bar( 1 );
7174 bar.step();
7176 sLog.outString();
7177 sLog.outErrorDb(">> Loaded `npc_vendor`, table is empty!");
7178 return;
7181 barGoLink bar( result->GetRowCount() );
7183 uint32 count = 0;
7186 bar.step();
7187 Field* fields = result->Fetch();
7189 uint32 entry = fields[0].GetUInt32();
7190 uint32 item_id = fields[1].GetUInt32();
7191 uint32 maxcount = fields[2].GetUInt32();
7192 uint32 incrtime = fields[3].GetUInt32();
7193 uint32 ExtendedCost = fields[4].GetUInt32();
7195 if(!IsVendorItemValid(entry,item_id,maxcount,incrtime,ExtendedCost,NULL,&skip_vendors))
7196 continue;
7198 VendorItemData& vList = m_mCacheVendorItemMap[entry];
7200 vList.AddItem(item_id,maxcount,incrtime,ExtendedCost);
7201 ++count;
7203 } while (result->NextRow());
7204 delete result;
7206 sLog.outString();
7207 sLog.outString( ">> Loaded %d Vendors ", count );
7210 void ObjectMgr::LoadNpcTextId()
7213 m_mCacheNpcTextIdMap.clear();
7215 QueryResult* result = WorldDatabase.Query("SELECT npc_guid, textid FROM npc_gossip");
7216 if( !result )
7218 barGoLink bar( 1 );
7220 bar.step();
7222 sLog.outString();
7223 sLog.outErrorDb(">> Loaded `npc_gossip`, table is empty!");
7224 return;
7227 barGoLink bar( result->GetRowCount() );
7229 uint32 count = 0;
7230 uint32 guid,textid;
7233 bar.step();
7235 Field* fields = result->Fetch();
7237 guid = fields[0].GetUInt32();
7238 textid = fields[1].GetUInt32();
7240 if (!GetCreatureData(guid))
7242 sLog.outErrorDb("Table `npc_gossip` have not existed creature (GUID: %u) entry, ignore. ",guid);
7243 continue;
7245 if (!GetGossipText(textid))
7247 sLog.outErrorDb("Table `npc_gossip` for creature (GUID: %u) have wrong Textid (%u), ignore. ", guid, textid);
7248 continue;
7251 m_mCacheNpcTextIdMap[guid] = textid ;
7252 ++count;
7254 } while (result->NextRow());
7255 delete result;
7257 sLog.outString();
7258 sLog.outString( ">> Loaded %d NpcTextId ", count );
7261 void ObjectMgr::LoadNpcOptions()
7263 m_mCacheNpcOptionList.clear(); // For reload case
7265 QueryResult *result = WorldDatabase.Query(
7266 // 0 1 2 3 4 5 6 7 8
7267 "SELECT id,gossip_id,npcflag,icon,action,box_money,coded,option_text,box_text "
7268 "FROM npc_option");
7270 if( !result )
7272 barGoLink bar( 1 );
7274 bar.step();
7276 sLog.outString();
7277 sLog.outErrorDb(">> Loaded `npc_option`, table is empty!");
7278 return;
7281 barGoLink bar( result->GetRowCount() );
7283 uint32 count = 0;
7287 bar.step();
7289 Field* fields = result->Fetch();
7291 GossipOption go;
7292 go.Id = fields[0].GetUInt32();
7293 go.GossipId = fields[1].GetUInt32();
7294 go.NpcFlag = fields[2].GetUInt32();
7295 go.Icon = fields[3].GetUInt32();
7296 go.Action = fields[4].GetUInt32();
7297 go.BoxMoney = fields[5].GetUInt32();
7298 go.Coded = fields[6].GetUInt8()!=0;
7299 go.OptionText = fields[7].GetCppString();
7300 go.BoxText = fields[8].GetCppString();
7302 m_mCacheNpcOptionList.push_back(go);
7304 ++count;
7306 } while (result->NextRow());
7307 delete result;
7309 sLog.outString();
7310 sLog.outString( ">> Loaded %d npc_option entries", count );
7313 void ObjectMgr::AddVendorItem( uint32 entry,uint32 item, uint32 maxcount, uint32 incrtime, uint32 extendedcost )
7315 VendorItemData& vList = m_mCacheVendorItemMap[entry];
7316 vList.AddItem(item,maxcount,incrtime,extendedcost);
7318 WorldDatabase.PExecuteLog("INSERT INTO npc_vendor (entry,item,maxcount,incrtime,extendedcost) VALUES('%u','%u','%u','%u','%u')",entry, item, maxcount,incrtime,extendedcost);
7321 bool ObjectMgr::RemoveVendorItem( uint32 entry,uint32 item )
7323 CacheVendorItemMap::iterator iter = m_mCacheVendorItemMap.find(entry);
7324 if(iter == m_mCacheVendorItemMap.end())
7325 return false;
7327 if(!iter->second.FindItem(item))
7328 return false;
7330 iter->second.RemoveItem(item);
7331 WorldDatabase.PExecuteLog("DELETE FROM npc_vendor WHERE entry='%u' AND item='%u'",entry, item);
7332 return true;
7335 bool ObjectMgr::IsVendorItemValid( uint32 vendor_entry, uint32 item_id, uint32 maxcount, uint32 incrtime, uint32 ExtendedCost, Player* pl, std::set<uint32>* skip_vendors ) const
7337 CreatureInfo const* cInfo = GetCreatureTemplate(vendor_entry);
7338 if(!cInfo)
7340 if(pl)
7341 ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
7342 else
7343 sLog.outErrorDb("Table `npc_vendor` have data for not existed creature template (Entry: %u), ignore", vendor_entry);
7344 return false;
7347 if(!(cInfo->npcflag & UNIT_NPC_FLAG_VENDOR))
7349 if(!skip_vendors || skip_vendors->count(vendor_entry)==0)
7351 if(pl)
7352 ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
7353 else
7354 sLog.outErrorDb("Table `npc_vendor` have data for not creature template (Entry: %u) without vendor flag, ignore", vendor_entry);
7356 if(skip_vendors)
7357 skip_vendors->insert(vendor_entry);
7359 return false;
7362 if(!GetItemPrototype(item_id))
7364 if(pl)
7365 ChatHandler(pl).PSendSysMessage(LANG_ITEM_NOT_FOUND, item_id);
7366 else
7367 sLog.outErrorDb("Table `npc_vendor` for Vendor (Entry: %u) have in item list non-existed item (%u), ignore",vendor_entry,item_id);
7368 return false;
7371 if(ExtendedCost && !sItemExtendedCostStore.LookupEntry(ExtendedCost))
7373 if(pl)
7374 ChatHandler(pl).PSendSysMessage(LANG_EXTENDED_COST_NOT_EXIST,ExtendedCost);
7375 else
7376 sLog.outErrorDb("Table `npc_vendor` have Item (Entry: %u) with wrong ExtendedCost (%u) for vendor (%u), ignore",item_id,ExtendedCost,vendor_entry);
7377 return false;
7380 if(maxcount > 0 && incrtime == 0)
7382 if(pl)
7383 ChatHandler(pl).PSendSysMessage("MaxCount!=0 (%u) but IncrTime==0", maxcount);
7384 else
7385 sLog.outErrorDb( "Table `npc_vendor` has `maxcount` (%u) for item %u of vendor (Entry: %u) but `incrtime`=0, ignore", maxcount, item_id, vendor_entry);
7386 return false;
7388 else if(maxcount==0 && incrtime > 0)
7390 if(pl)
7391 ChatHandler(pl).PSendSysMessage("MaxCount==0 but IncrTime<>=0");
7392 else
7393 sLog.outErrorDb( "Table `npc_vendor` has `maxcount`=0 for item %u of vendor (Entry: %u) but `incrtime`<>0, ignore", item_id, vendor_entry);
7394 return false;
7397 VendorItemData const* vItems = GetNpcVendorItemList(vendor_entry);
7398 if(!vItems)
7399 return true; // later checks for non-empty lists
7401 if(vItems->FindItem(item_id))
7403 if(pl)
7404 ChatHandler(pl).PSendSysMessage(LANG_ITEM_ALREADY_IN_LIST,item_id);
7405 else
7406 sLog.outErrorDb( "Table `npc_vendor` has duplicate items %u for vendor (Entry: %u), ignore", item_id, vendor_entry);
7407 return false;
7410 if(vItems->GetItemCount() >= MAX_VENDOR_ITEMS)
7412 if(pl)
7413 ChatHandler(pl).SendSysMessage(LANG_COMMAND_ADDVENDORITEMITEMS);
7414 else
7415 sLog.outErrorDb( "Table `npc_vendor` has too many items (%u >= %i) for vendor (Entry: %u), ignore", vItems->GetItemCount(), MAX_VENDOR_ITEMS, vendor_entry);
7416 return false;
7419 return true;
7422 void ObjectMgr::LoadScriptNames()
7424 m_scriptNames.push_back("");
7425 QueryResult *result = WorldDatabase.Query(
7426 "SELECT DISTINCT(ScriptName) FROM creature_template WHERE ScriptName <> '' "
7427 "UNION "
7428 "SELECT DISTINCT(ScriptName) FROM gameobject_template WHERE ScriptName <> '' "
7429 "UNION "
7430 "SELECT DISTINCT(ScriptName) FROM item_template WHERE ScriptName <> '' "
7431 "UNION "
7432 "SELECT DISTINCT(ScriptName) FROM areatrigger_scripts WHERE ScriptName <> '' "
7433 "UNION "
7434 "SELECT DISTINCT(script) FROM instance_template WHERE script <> ''");
7436 if( !result )
7438 barGoLink bar( 1 );
7439 bar.step();
7440 sLog.outString();
7441 sLog.outErrorDb(">> Loaded empty set of Script Names!");
7442 return;
7445 barGoLink bar( result->GetRowCount() );
7446 uint32 count = 0;
7450 bar.step();
7451 m_scriptNames.push_back((*result)[0].GetString());
7452 ++count;
7453 } while (result->NextRow());
7454 delete result;
7456 std::sort(m_scriptNames.begin(), m_scriptNames.end());
7457 sLog.outString();
7458 sLog.outString( ">> Loaded %d Script Names", count );
7461 uint32 ObjectMgr::GetScriptId(const char *name)
7463 // use binary search to find the script name in the sorted vector
7464 // assume "" is the first element
7465 if(!name) return 0;
7466 ScriptNameMap::const_iterator itr =
7467 std::lower_bound(m_scriptNames.begin(), m_scriptNames.end(), name);
7468 if(itr == m_scriptNames.end() || *itr != name) return 0;
7469 return itr - m_scriptNames.begin();
7472 void ObjectMgr::CheckScripts(ScriptMapMap const& scripts,std::set<int32>& ids)
7474 for(ScriptMapMap::const_iterator itrMM = scripts.begin(); itrMM != scripts.end(); ++itrMM)
7476 for(ScriptMap::const_iterator itrM = itrMM->second.begin(); itrM != itrMM->second.end(); ++itrM)
7478 switch(itrM->second.command)
7480 case SCRIPT_COMMAND_TALK:
7482 if(!GetMangosStringLocale (itrM->second.dataint))
7483 sLog.outErrorDb( "Table `db_script_string` not has string id %u used db script (ID: %u)", itrM->second.dataint, itrMM->first);
7485 if(ids.count(itrM->second.dataint))
7486 ids.erase(itrM->second.dataint);
7493 void ObjectMgr::LoadDbScriptStrings()
7495 LoadMangosStrings(WorldDatabase,"db_script_string",MIN_DB_SCRIPT_STRING_ID,MAX_DB_SCRIPT_STRING_ID);
7497 std::set<int32> ids;
7499 for(int32 i = MIN_DB_SCRIPT_STRING_ID; i < MAX_DB_SCRIPT_STRING_ID; ++i)
7500 if(GetMangosStringLocale(i))
7501 ids.insert(i);
7503 CheckScripts(sQuestEndScripts,ids);
7504 CheckScripts(sQuestStartScripts,ids);
7505 CheckScripts(sSpellScripts,ids);
7506 CheckScripts(sGameObjectScripts,ids);
7507 CheckScripts(sEventScripts,ids);
7509 WaypointMgr.CheckTextsExistance(ids);
7511 for(std::set<int32>::const_iterator itr = ids.begin(); itr != ids.end(); ++itr)
7512 sLog.outErrorDb( "Table `db_script_string` has unused string id %u", *itr);
7515 // Functions for scripting access
7516 uint32 GetAreaTriggerScriptId(uint32 trigger_id)
7518 return objmgr.GetAreaTriggerScriptId(trigger_id);
7521 bool LoadMangosStrings(DatabaseType& db, char const* table,int32 start_value, int32 end_value)
7523 // MAX_DB_SCRIPT_STRING_ID is max allowed negative value for scripts (scrpts can use only more deep negative values
7524 // start/end reversed for negative values
7525 if (start_value > MAX_DB_SCRIPT_STRING_ID || end_value >= start_value)
7527 sLog.outErrorDb("Table '%s' attempt loaded with reserved by mangos range (%d - %d), strings not loaded.",table,start_value,end_value+1);
7528 return false;
7531 return objmgr.LoadMangosStrings(db,table,start_value,end_value);
7534 uint32 MANGOS_DLL_SPEC GetScriptId(const char *name)
7536 return objmgr.GetScriptId(name);
7539 ObjectMgr::ScriptNameMap & GetScriptNames()
7541 return objmgr.GetScriptNames();
7544 CreatureInfo const* GetCreatureTemplateStore(uint32 entry)
7546 return sCreatureStorage.LookupEntry<CreatureInfo>(entry);
7549 Quest const* GetQuestTemplateStore(uint32 entry)
7551 return objmgr.GetQuestTemplate(entry);