[6922] Whitespace and newline fixes
[getmangos.git] / src / game / ObjectMgr.cpp
blob0b1c0d3570457bb16746376d7424e908e36ef68d
1 /*
2 * Copyright (C) 2005-2008 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"
24 #include "Log.h"
25 #include "MapManager.h"
26 #include "ObjectMgr.h"
27 #include "SpellMgr.h"
28 #include "UpdateMask.h"
29 #include "World.h"
30 #include "WorldSession.h"
31 #include "Group.h"
32 #include "Guild.h"
33 #include "ArenaTeam.h"
34 #include "Transports.h"
35 #include "ProgressBar.h"
36 #include "Policies/SingletonImp.h"
37 #include "Language.h"
38 #include "GameEvent.h"
39 #include "Spell.h"
40 #include "Chat.h"
41 #include "AccountMgr.h"
42 #include "InstanceSaveMgr.h"
43 #include "SpellAuras.h"
44 #include "Util.h"
45 #include "WaypointManager.h"
47 INSTANTIATE_SINGLETON_1(ObjectMgr);
49 ScriptMapMap sQuestEndScripts;
50 ScriptMapMap sQuestStartScripts;
51 ScriptMapMap sSpellScripts;
52 ScriptMapMap sGameObjectScripts;
53 ScriptMapMap sEventScripts;
55 bool normalizePlayerName(std::string& name)
57 if(name.empty())
58 return false;
60 wchar_t wstr_buf[MAX_INTERNAL_PLAYER_NAME+1];
61 size_t wstr_len = MAX_INTERNAL_PLAYER_NAME;
63 if(!Utf8toWStr(name,&wstr_buf[0],wstr_len))
64 return false;
66 wstr_buf[0] = wcharToUpper(wstr_buf[0]);
67 for(size_t i = 1; i < wstr_len; ++i)
68 wstr_buf[i] = wcharToLower(wstr_buf[i]);
70 if(!WStrToUtf8(wstr_buf,wstr_len,name))
71 return false;
73 return true;
76 LanguageDesc lang_description[LANGUAGES_COUNT] =
78 { LANG_ADDON, 0, 0 },
79 { LANG_UNIVERSAL, 0, 0 },
80 { LANG_ORCISH, 669, SKILL_LANG_ORCISH },
81 { LANG_DARNASSIAN, 671, SKILL_LANG_DARNASSIAN },
82 { LANG_TAURAHE, 670, SKILL_LANG_TAURAHE },
83 { LANG_DWARVISH, 672, SKILL_LANG_DWARVEN },
84 { LANG_COMMON, 668, SKILL_LANG_COMMON },
85 { LANG_DEMONIC, 815, SKILL_LANG_DEMON_TONGUE },
86 { LANG_TITAN, 816, SKILL_LANG_TITAN },
87 { LANG_THALASSIAN, 813, SKILL_LANG_THALASSIAN },
88 { LANG_DRACONIC, 814, SKILL_LANG_DRACONIC },
89 { LANG_KALIMAG, 817, SKILL_LANG_OLD_TONGUE },
90 { LANG_GNOMISH, 7340, SKILL_LANG_GNOMISH },
91 { LANG_TROLL, 7341, SKILL_LANG_TROLL },
92 { LANG_GUTTERSPEAK, 17737, SKILL_LANG_GUTTERSPEAK },
93 { LANG_DRAENEI, 29932, SKILL_LANG_DRAENEI },
94 { LANG_ZOMBIE, 0, 0 },
95 { LANG_GNOMISH_BINARY, 0, 0 },
96 { LANG_GOBLIN_BINARY, 0, 0 }
99 LanguageDesc const* GetLanguageDescByID(uint32 lang)
101 for(int i = 0; i < LANGUAGES_COUNT; ++i)
103 if(uint32(lang_description[i].lang_id) == lang)
104 return &lang_description[i];
107 return NULL;
110 ObjectMgr::ObjectMgr()
112 m_hiCharGuid = 1;
113 m_hiCreatureGuid = 1;
114 m_hiPetGuid = 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_auctionid = 1;
123 m_guildId = 1;
124 m_arenaTeamId = 1;
126 mGuildBankTabPrice.resize(GUILD_BANK_MAX_TABS);
127 mGuildBankTabPrice[0] = 100;
128 mGuildBankTabPrice[1] = 250;
129 mGuildBankTabPrice[2] = 500;
130 mGuildBankTabPrice[3] = 1000;
131 mGuildBankTabPrice[4] = 2500;
132 mGuildBankTabPrice[5] = 5000;
134 // Only zero condition left, others will be added while loading DB tables
135 mConditions.resize(1);
138 ObjectMgr::~ObjectMgr()
140 for( QuestMap::iterator i = mQuestTemplates.begin( ); i != mQuestTemplates.end( ); ++i )
142 delete i->second;
144 mQuestTemplates.clear( );
146 for( GossipTextMap::iterator i = mGossipText.begin( ); i != mGossipText.end( ); ++i )
148 delete i->second;
150 mGossipText.clear( );
152 mAreaTriggers.clear();
154 for(PetLevelInfoMap::iterator i = petInfo.begin( ); i != petInfo.end( ); ++i )
156 delete[] i->second;
158 petInfo.clear();
160 // free only if loaded
161 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
162 delete[] playerClassInfo[class_].levelInfo;
164 for (int race = 0; race < MAX_RACES; ++race)
165 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
166 delete[] playerInfo[race][class_].levelInfo;
168 // free group and guild objects
169 for (GroupSet::iterator itr = mGroupSet.begin(); itr != mGroupSet.end(); ++itr)
170 delete (*itr);
171 for (GuildSet::iterator itr = mGuildSet.begin(); itr != mGuildSet.end(); ++itr)
172 delete (*itr);
174 for(ItemMap::iterator itr = mAitems.begin(); itr != mAitems.end(); ++itr)
175 delete itr->second;
177 for (CacheVendorItemMap::iterator itr = m_mCacheVendorItemMap.begin(); itr != m_mCacheVendorItemMap.end(); ++itr)
178 itr->second.Clear();
180 for (CacheTrainerSpellMap::iterator itr = m_mCacheTrainerSpellMap.begin(); itr != m_mCacheTrainerSpellMap.end(); ++itr)
181 itr->second.Clear();
184 Group * ObjectMgr::GetGroupByLeader(const uint64 &guid) const
186 for(GroupSet::const_iterator itr = mGroupSet.begin(); itr != mGroupSet.end(); ++itr)
187 if ((*itr)->GetLeaderGUID() == guid)
188 return *itr;
190 return NULL;
193 Guild * ObjectMgr::GetGuildById(const uint32 GuildId) const
195 for(GuildSet::const_iterator itr = mGuildSet.begin(); itr != mGuildSet.end(); ++itr)
196 if ((*itr)->GetId() == GuildId)
197 return *itr;
199 return NULL;
202 Guild * ObjectMgr::GetGuildByName(const std::string& guildname) const
204 for(GuildSet::const_iterator itr = mGuildSet.begin(); itr != mGuildSet.end(); ++itr)
205 if ((*itr)->GetName() == guildname)
206 return *itr;
208 return NULL;
211 std::string ObjectMgr::GetGuildNameById(const uint32 GuildId) const
213 for(GuildSet::const_iterator itr = mGuildSet.begin(); itr != mGuildSet.end(); ++itr)
214 if ((*itr)->GetId() == GuildId)
215 return (*itr)->GetName();
217 return "";
220 Guild* ObjectMgr::GetGuildByLeader(const uint64 &guid) const
222 for(GuildSet::const_iterator itr = mGuildSet.begin(); itr != mGuildSet.end(); ++itr)
223 if( (*itr)->GetLeader() == guid)
224 return *itr;
226 return NULL;
229 ArenaTeam* ObjectMgr::GetArenaTeamById(const uint32 arenateamid) const
231 ArenaTeamMap::const_iterator itr = mArenaTeamMap.find(arenateamid);
232 if (itr != mArenaTeamMap.end())
233 return itr->second;
235 return NULL;
238 ArenaTeam* ObjectMgr::GetArenaTeamByName(const std::string& arenateamname) const
240 for(ArenaTeamMap::const_iterator itr = mArenaTeamMap.begin(); itr != mArenaTeamMap.end(); ++itr)
241 if (itr->second->GetName() == arenateamname)
242 return itr->second;
244 return NULL;
247 ArenaTeam* ObjectMgr::GetArenaTeamByCaptain(uint64 const& guid) const
249 for(ArenaTeamMap::const_iterator itr = mArenaTeamMap.begin(); itr != mArenaTeamMap.end(); ++itr)
250 if (itr->second->GetCaptain() == guid)
251 return itr->second;
253 return NULL;
256 void ObjectMgr::AddArenaTeam(ArenaTeam* arenaTeam)
258 mArenaTeamMap[arenaTeam->GetId()] = arenaTeam;
261 void ObjectMgr::RemoveArenaTeam(ArenaTeam* arenaTeam)
263 mArenaTeamMap.erase( arenaTeam->GetId() );
266 AuctionHouseObject * ObjectMgr::GetAuctionsMap( uint32 location )
268 switch ( location )
270 case 6: //horde
271 return & mHordeAuctions;
272 break;
273 case 2: //alliance
274 return & mAllianceAuctions;
275 break;
276 default: //neutral
277 return & mNeutralAuctions;
281 uint32 ObjectMgr::GetAuctionCut(uint32 location, uint32 highBid)
283 if (location == 7 && !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_AUCTION))
284 return (uint32) (0.15f * highBid * sWorld.getRate(RATE_AUCTION_CUT));
285 else
286 return (uint32) (0.05f * highBid * sWorld.getRate(RATE_AUCTION_CUT));
289 uint32 ObjectMgr::GetAuctionDeposit(uint32 location, uint32 time, Item *pItem)
291 float percentance; // in 0..1
292 if ( location == 7 && !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_AUCTION))
293 percentance = 0.75f;
294 else
295 percentance = 0.15f;
297 percentance *= sWorld.getRate(RATE_AUCTION_DEPOSIT);
299 return uint32( percentance * pItem->GetProto()->SellPrice * pItem->GetCount() * (time / MIN_AUCTION_TIME ) );
302 /// the sum of outbid is (1% from current bid)*5, if bid is very small, it is 1c
303 uint32 ObjectMgr::GetAuctionOutBid(uint32 currentBid)
305 uint32 outbid = (currentBid / 100) * 5;
306 if (!outbid)
307 outbid = 1;
308 return outbid;
311 //does not clear ram
312 void ObjectMgr::SendAuctionWonMail( AuctionEntry *auction )
314 Item *pItem = GetAItem(auction->item_guidlow);
315 if(!pItem)
316 return;
318 uint64 bidder_guid = MAKE_NEW_GUID(auction->bidder, 0, HIGHGUID_PLAYER);
319 Player *bidder = GetPlayer(bidder_guid);
321 uint32 bidder_accId = 0;
323 // data for gm.log
324 if( sWorld.getConfig(CONFIG_GM_LOG_TRADE) )
326 uint32 bidder_security = 0;
327 std::string bidder_name;
328 if (bidder)
330 bidder_accId = bidder->GetSession()->GetAccountId();
331 bidder_security = bidder->GetSession()->GetSecurity();
332 bidder_name = bidder->GetName();
334 else
336 bidder_accId = GetPlayerAccountIdByGUID(bidder_guid);
337 bidder_security = accmgr.GetSecurity(bidder_accId);
339 if(bidder_security > SEC_PLAYER ) // not do redundant DB requests
341 if(!GetPlayerNameByGUID(bidder_guid,bidder_name))
342 bidder_name = GetMangosStringForDBCLocale(LANG_UNKNOWN);
346 if( bidder_security > SEC_PLAYER )
348 std::string owner_name;
349 if(!GetPlayerNameByGUID(auction->owner,owner_name))
350 owner_name = GetMangosStringForDBCLocale(LANG_UNKNOWN);
352 uint32 owner_accid = GetPlayerAccountIdByGUID(auction->owner);
354 sLog.outCommand(bidder_accId,"GM %s (Account: %u) won item in auction: %s (Entry: %u Count: %u) and pay money: %u. Original owner %s (Account: %u)",
355 bidder_name.c_str(),bidder_accId,pItem->GetProto()->Name1,pItem->GetEntry(),pItem->GetCount(),auction->bid,owner_name.c_str(),owner_accid);
358 else if(!bidder)
359 bidder_accId = GetPlayerAccountIdByGUID(bidder_guid);
361 // receiver exist
362 if(bidder || bidder_accId)
364 std::ostringstream msgAuctionWonSubject;
365 msgAuctionWonSubject << auction->item_template << ":0:" << AUCTION_WON;
367 std::ostringstream msgAuctionWonBody;
368 msgAuctionWonBody.width(16);
369 msgAuctionWonBody << std::right << std::hex << auction->owner;
370 msgAuctionWonBody << std::dec << ":" << auction->bid << ":" << auction->buyout;
371 sLog.outDebug( "AuctionWon body string : %s", msgAuctionWonBody.str().c_str() );
373 //prepare mail data... :
374 uint32 itemTextId = CreateItemText( msgAuctionWonBody.str() );
376 // set owner to bidder (to prevent delete item with sender char deleting)
377 // owner in `data` will set at mail receive and item extracting
378 CharacterDatabase.PExecute("UPDATE item_instance SET owner_guid = '%u' WHERE guid='%u'",auction->bidder,pItem->GetGUIDLow());
379 CharacterDatabase.CommitTransaction();
381 MailItemsInfo mi;
382 mi.AddItem(auction->item_guidlow, auction->item_template, pItem);
384 if (bidder)
385 bidder->GetSession()->SendAuctionBidderNotification( auction->location, auction->Id, bidder_guid, 0, 0, auction->item_template);
386 else
387 RemoveAItem(pItem->GetGUIDLow()); // we have to remove the item, before we delete it !!
389 // will delete item or place to receiver mail list
390 WorldSession::SendMailTo(bidder, MAIL_AUCTION, MAIL_STATIONERY_AUCTION, auction->location, auction->bidder, msgAuctionWonSubject.str(), itemTextId, &mi, 0, 0, MAIL_CHECK_MASK_AUCTION);
392 // receiver not exist
393 else
395 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid='%u'", pItem->GetGUIDLow());
396 RemoveAItem(pItem->GetGUIDLow()); // we have to remove the item, before we delete it !!
397 delete pItem;
401 void ObjectMgr::SendAuctionSalePendingMail( AuctionEntry * auction )
403 uint64 owner_guid = MAKE_NEW_GUID(auction->owner, 0, HIGHGUID_PLAYER);
404 Player *owner = GetPlayer(owner_guid);
406 // owner exist (online or offline)
407 if(owner || GetPlayerAccountIdByGUID(owner_guid))
409 std::ostringstream msgAuctionSalePendingSubject;
410 msgAuctionSalePendingSubject << auction->item_template << ":0:" << AUCTION_SALE_PENDING;
412 std::ostringstream msgAuctionSalePendingBody;
413 uint32 auctionCut = GetAuctionCut(auction->location, auction->bid);
415 time_t distrTime = time(NULL) + HOUR;
417 msgAuctionSalePendingBody.width(16);
418 msgAuctionSalePendingBody << std::right << std::hex << auction->bidder;
419 msgAuctionSalePendingBody << std::dec << ":" << auction->bid << ":" << auction->buyout;
420 msgAuctionSalePendingBody << ":" << auction->deposit << ":" << auctionCut << ":0:";
421 msgAuctionSalePendingBody << secsToTimeBitFields(distrTime);
423 sLog.outDebug("AuctionSalePending body string : %s", msgAuctionSalePendingBody.str().c_str());
425 uint32 itemTextId = CreateItemText( msgAuctionSalePendingBody.str() );
427 WorldSession::SendMailTo(owner, MAIL_AUCTION, MAIL_STATIONERY_AUCTION, auction->location, auction->owner, msgAuctionSalePendingSubject.str(), itemTextId, NULL, 0, 0, MAIL_CHECK_MASK_AUCTION);
431 //call this method to send mail to auction owner, when auction is successful, it does not clear ram
432 void ObjectMgr::SendAuctionSuccessfulMail( AuctionEntry * auction )
434 uint64 owner_guid = MAKE_NEW_GUID(auction->owner, 0, HIGHGUID_PLAYER);
435 Player *owner = GetPlayer(owner_guid);
437 uint32 owner_accId = 0;
438 if(!owner)
439 owner_accId = GetPlayerAccountIdByGUID(owner_guid);
441 // owner exist
442 if(owner || owner_accId)
444 std::ostringstream msgAuctionSuccessfulSubject;
445 msgAuctionSuccessfulSubject << auction->item_template << ":0:" << AUCTION_SUCCESSFUL;
447 std::ostringstream auctionSuccessfulBody;
448 uint32 auctionCut = GetAuctionCut(auction->location, auction->bid);
450 auctionSuccessfulBody.width(16);
451 auctionSuccessfulBody << std::right << std::hex << auction->bidder;
452 auctionSuccessfulBody << std::dec << ":" << auction->bid << ":" << auction->buyout;
453 auctionSuccessfulBody << ":" << auction->deposit << ":" << auctionCut;
455 sLog.outDebug("AuctionSuccessful body string : %s", auctionSuccessfulBody.str().c_str());
457 uint32 itemTextId = CreateItemText( auctionSuccessfulBody.str() );
459 uint32 profit = auction->bid + auction->deposit - auctionCut;
461 if (owner)
463 //send auction owner notification, bidder must be current!
464 owner->GetSession()->SendAuctionOwnerNotification( auction );
467 WorldSession::SendMailTo(owner, MAIL_AUCTION, MAIL_STATIONERY_AUCTION, auction->location, auction->owner, msgAuctionSuccessfulSubject.str(), itemTextId, NULL, profit, 0, MAIL_CHECK_MASK_AUCTION, HOUR);
471 //does not clear ram
472 void ObjectMgr::SendAuctionExpiredMail( AuctionEntry * auction )
473 { //return an item in auction to its owner by mail
474 Item *pItem = GetAItem(auction->item_guidlow);
475 if(!pItem)
477 sLog.outError("Auction item (GUID: %u) not found, and lost.",auction->item_guidlow);
478 return;
481 uint64 owner_guid = MAKE_NEW_GUID(auction->owner, 0, HIGHGUID_PLAYER);
482 Player *owner = GetPlayer(owner_guid);
484 uint32 owner_accId = 0;
485 if(!owner)
486 owner_accId = GetPlayerAccountIdByGUID(owner_guid);
488 // owner exist
489 if(owner || owner_accId)
491 std::ostringstream subject;
492 subject << auction->item_template << ":0:" << AUCTION_EXPIRED;
494 if ( owner )
495 owner->GetSession()->SendAuctionOwnerNotification( auction );
496 else
497 RemoveAItem(pItem->GetGUIDLow()); // we have to remove the item, before we delete it !!
499 MailItemsInfo mi;
500 mi.AddItem(auction->item_guidlow, auction->item_template, pItem);
502 // will delete item or place to receiver mail list
503 WorldSession::SendMailTo(owner, MAIL_AUCTION, MAIL_STATIONERY_AUCTION, auction->location, GUID_LOPART(owner_guid), subject.str(), 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
505 // owner not found
506 else
508 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid='%u'",pItem->GetGUIDLow());
509 RemoveAItem(pItem->GetGUIDLow()); // we have to remove the item, before we delete it !!
510 delete pItem;
514 CreatureInfo const* ObjectMgr::GetCreatureTemplate(uint32 id)
516 return sCreatureStorage.LookupEntry<CreatureInfo>(id);
519 void ObjectMgr::LoadCreatureLocales()
521 mCreatureLocaleMap.clear(); // need for reload case
523 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");
525 if(!result)
527 barGoLink bar(1);
529 bar.step();
531 sLog.outString("");
532 sLog.outString(">> Loaded 0 creature locale strings. DB table `locales_creature` is empty.");
533 return;
536 barGoLink bar(result->GetRowCount());
540 Field *fields = result->Fetch();
541 bar.step();
543 uint32 entry = fields[0].GetUInt32();
545 CreatureLocale& data = mCreatureLocaleMap[entry];
547 for(int i = 1; i < MAX_LOCALE; ++i)
549 std::string str = fields[1+2*(i-1)].GetCppString();
550 if(!str.empty())
552 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
553 if(idx >= 0)
555 if(data.Name.size() <= idx)
556 data.Name.resize(idx+1);
558 data.Name[idx] = str;
561 str = fields[1+2*(i-1)+1].GetCppString();
562 if(!str.empty())
564 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
565 if(idx >= 0)
567 if(data.SubName.size() <= idx)
568 data.SubName.resize(idx+1);
570 data.SubName[idx] = str;
574 } while (result->NextRow());
576 delete result;
578 sLog.outString();
579 sLog.outString( ">> Loaded %u creature locale strings", mCreatureLocaleMap.size() );
582 void ObjectMgr::LoadNpcOptionLocales()
584 mNpcOptionLocaleMap.clear(); // need for reload case
586 QueryResult *result = WorldDatabase.Query("SELECT entry,"
587 "option_text_loc1,box_text_loc1,option_text_loc2,box_text_loc2,"
588 "option_text_loc3,box_text_loc3,option_text_loc4,box_text_loc4,"
589 "option_text_loc5,box_text_loc5,option_text_loc6,box_text_loc6,"
590 "option_text_loc7,box_text_loc7,option_text_loc8,box_text_loc8 "
591 "FROM locales_npc_option");
593 if(!result)
595 barGoLink bar(1);
597 bar.step();
599 sLog.outString("");
600 sLog.outString(">> Loaded 0 npc_option locale strings. DB table `locales_npc_option` is empty.");
601 return;
604 barGoLink bar(result->GetRowCount());
608 Field *fields = result->Fetch();
609 bar.step();
611 uint32 entry = fields[0].GetUInt32();
613 NpcOptionLocale& data = mNpcOptionLocaleMap[entry];
615 for(int i = 1; i < MAX_LOCALE; ++i)
617 std::string str = fields[1+2*(i-1)].GetCppString();
618 if(!str.empty())
620 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
621 if(idx >= 0)
623 if(data.OptionText.size() <= idx)
624 data.OptionText.resize(idx+1);
626 data.OptionText[idx] = str;
629 str = fields[1+2*(i-1)+1].GetCppString();
630 if(!str.empty())
632 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
633 if(idx >= 0)
635 if(data.BoxText.size() <= idx)
636 data.BoxText.resize(idx+1);
638 data.BoxText[idx] = str;
642 } while (result->NextRow());
644 delete result;
646 sLog.outString();
647 sLog.outString( ">> Loaded %u npc_option locale strings", mNpcOptionLocaleMap.size() );
650 struct SQLCreatureLoader : public SQLStorageLoaderBase<SQLCreatureLoader>
652 template<class D>
653 void convert_from_str(uint32 field_pos, char *src, D &dst)
655 dst = D(objmgr.GetScriptId(src));
659 void ObjectMgr::LoadCreatureTemplates()
661 SQLCreatureLoader loader;
662 loader.Load(sCreatureStorage);
664 sLog.outString( ">> Loaded %u creature definitions", sCreatureStorage.RecordCount );
665 sLog.outString();
667 std::set<uint32> heroicEntries; // already loaded heroic value in creatures
668 std::set<uint32> hasHeroicEntries; // already loaded creatures with heroic entry values
670 // check data correctness
671 for(uint32 i = 1; i < sCreatureStorage.MaxEntry; ++i)
673 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i);
674 if(!cInfo)
675 continue;
677 if(cInfo->HeroicEntry)
679 CreatureInfo const* heroicInfo = GetCreatureTemplate(cInfo->HeroicEntry);
680 if(!heroicInfo)
682 sLog.outErrorDb("Creature (Entry: %u) have `heroic_entry`=%u but creature entry %u not exist.",cInfo->HeroicEntry,cInfo->HeroicEntry);
683 continue;
686 if(heroicEntries.find(i)!=heroicEntries.end())
688 sLog.outErrorDb("Creature (Entry: %u) listed as heroic but have value in `heroic_entry`.",i);
689 continue;
692 if(heroicEntries.find(cInfo->HeroicEntry)!=heroicEntries.end())
694 sLog.outErrorDb("Creature (Entry: %u) already listed as heroic for another entry.",cInfo->HeroicEntry);
695 continue;
698 if(hasHeroicEntries.find(cInfo->HeroicEntry)!=hasHeroicEntries.end())
700 sLog.outErrorDb("Creature (Entry: %u) have `heroic_entry`=%u but creature entry %u have heroic entry also.",i,cInfo->HeroicEntry,cInfo->HeroicEntry);
701 continue;
704 if(cInfo->npcflag != heroicInfo->npcflag)
706 sLog.outErrorDb("Creature (Entry: %u) has different `npcflag` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
707 continue;
710 if(cInfo->classNum != heroicInfo->classNum)
712 sLog.outErrorDb("Creature (Entry: %u) has different `classNum` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
713 continue;
716 if(cInfo->race != heroicInfo->race)
718 sLog.outErrorDb("Creature (Entry: %u) has different `race` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
719 continue;
722 if(cInfo->trainer_type != heroicInfo->trainer_type)
724 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_type` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
725 continue;
728 if(cInfo->trainer_spell != heroicInfo->trainer_spell)
730 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_spell` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
731 continue;
734 hasHeroicEntries.insert(i);
735 heroicEntries.insert(cInfo->HeroicEntry);
738 FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction_A);
739 if(!factionTemplate)
740 sLog.outErrorDb("Creature (Entry: %u) has non-existing faction_A template (%u)", cInfo->Entry, cInfo->faction_A);
742 factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction_H);
743 if(!factionTemplate)
744 sLog.outErrorDb("Creature (Entry: %u) has non-existing faction_H template (%u)", cInfo->Entry, cInfo->faction_H);
746 CreatureModelInfo const* minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_A);
747 if (!minfo)
748 sLog.outErrorDb("Creature (Entry: %u) has non-existing modelId_A (%u)", cInfo->Entry, cInfo->DisplayID_A);
749 minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_H);
750 if (!minfo)
751 sLog.outErrorDb("Creature (Entry: %u) has non-existing modelId_H (%u)", cInfo->Entry, cInfo->DisplayID_H);
753 if(cInfo->dmgschool >= MAX_SPELL_SCHOOL)
755 sLog.outErrorDb("Creature (Entry: %u) has invalid spell school value (%u) in `dmgschool`",cInfo->Entry,cInfo->dmgschool);
756 const_cast<CreatureInfo*>(cInfo)->dmgschool = SPELL_SCHOOL_NORMAL;
759 if(cInfo->baseattacktime == 0)
760 const_cast<CreatureInfo*>(cInfo)->baseattacktime = BASE_ATTACK_TIME;
762 if(cInfo->rangeattacktime == 0)
763 const_cast<CreatureInfo*>(cInfo)->rangeattacktime = BASE_ATTACK_TIME;
765 if((cInfo->npcflag & UNIT_NPC_FLAG_TRAINER) && cInfo->trainer_type >= MAX_TRAINER_TYPE)
766 sLog.outErrorDb("Creature (Entry: %u) has wrong trainer type %u",cInfo->Entry,cInfo->trainer_type);
768 if(cInfo->InhabitType <= 0 || cInfo->InhabitType > INHABIT_ANYWHERE)
770 sLog.outErrorDb("Creature (Entry: %u) has wrong value (%u) in `InhabitType`, creature will not correctly walk/swim/fly",cInfo->Entry,cInfo->InhabitType);
771 const_cast<CreatureInfo*>(cInfo)->InhabitType = INHABIT_ANYWHERE;
774 if(cInfo->PetSpellDataId)
776 CreatureSpellDataEntry const* spellDataId = sCreatureSpellDataStore.LookupEntry(cInfo->PetSpellDataId);
777 if(!spellDataId)
778 sLog.outErrorDb("Creature (Entry: %u) has non-existing PetSpellDataId (%u)", cInfo->Entry, cInfo->PetSpellDataId);
781 if(cInfo->MovementType >= MAX_DB_MOTION_TYPE)
783 sLog.outErrorDb("Creature (Entry: %u) has wrong movement generator type (%u), ignore and set to IDLE.",cInfo->Entry,cInfo->MovementType);
784 const_cast<CreatureInfo*>(cInfo)->MovementType = IDLE_MOTION_TYPE;
787 if(cInfo->equipmentId > 0) // 0 no equipment
789 if(!GetEquipmentInfo(cInfo->equipmentId))
791 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);
792 const_cast<CreatureInfo*>(cInfo)->equipmentId = 0;
796 /// if not set custom creature scale then load scale from CreatureDisplayInfo.dbc
797 if(cInfo->scale <= 0.0f)
799 CreatureDisplayInfoEntry const* ScaleEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->DisplayID_A);
800 const_cast<CreatureInfo*>(cInfo)->scale = ScaleEntry ? ScaleEntry->scale : 1.0f;
805 void ObjectMgr::ConvertCreatureAddonAuras(CreatureDataAddon* addon, char const* table, char const* guidEntryStr)
807 // Now add the auras, format "spellid effectindex spellid effectindex..."
808 char *p,*s;
809 std::vector<int> val;
810 s=p=(char*)reinterpret_cast<char const*>(addon->auras);
811 if(p)
813 while (p[0]!=0)
815 ++p;
816 if (p[0]==' ')
818 val.push_back(atoi(s));
819 s=++p;
822 if (p!=s)
823 val.push_back(atoi(s));
825 // free char* loaded memory
826 delete[] (char*)reinterpret_cast<char const*>(addon->auras);
828 // wrong list
829 if (val.size()%2)
831 addon->auras = NULL;
832 sLog.outErrorDb("Creature (%s: %u) has wrong `auras` data in `%s`.",guidEntryStr,addon->guidOrEntry,table);
833 return;
837 // empty list
838 if(val.empty())
840 addon->auras = NULL;
841 return;
844 // replace by new structures array
845 const_cast<CreatureDataAddonAura*&>(addon->auras) = new CreatureDataAddonAura[val.size()/2+1];
847 int i=0;
848 for(int j=0;j<val.size()/2;++j)
850 CreatureDataAddonAura& cAura = const_cast<CreatureDataAddonAura&>(addon->auras[i]);
851 cAura.spell_id = (uint32)val[2*j+0];
852 cAura.effect_idx = (uint32)val[2*j+1];
853 if ( cAura.effect_idx > 2 )
855 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);
856 continue;
858 SpellEntry const *AdditionalSpellInfo = sSpellStore.LookupEntry(cAura.spell_id);
859 if (!AdditionalSpellInfo)
861 sLog.outErrorDb("Creature (%s: %u) has wrong spell %u defined in `auras` field in `%s`.",guidEntryStr,addon->guidOrEntry,cAura.spell_id,table);
862 continue;
865 if (!AdditionalSpellInfo->Effect[cAura.effect_idx] || !AdditionalSpellInfo->EffectApplyAuraName[cAura.effect_idx])
867 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);
868 continue;
871 ++i;
874 // fill terminator element (after last added)
875 CreatureDataAddonAura& endAura = const_cast<CreatureDataAddonAura&>(addon->auras[i]);
876 endAura.spell_id = 0;
877 endAura.effect_idx = 0;
880 void ObjectMgr::LoadCreatureAddons()
882 sCreatureInfoAddonStorage.Load();
884 sLog.outString( ">> Loaded %u creature template addons", sCreatureInfoAddonStorage.RecordCount );
885 sLog.outString();
887 // check data correctness and convert 'auras'
888 for(uint32 i = 1; i < sCreatureInfoAddonStorage.MaxEntry; ++i)
890 CreatureDataAddon const* addon = sCreatureInfoAddonStorage.LookupEntry<CreatureDataAddon>(i);
891 if(!addon)
892 continue;
894 ConvertCreatureAddonAuras(const_cast<CreatureDataAddon*>(addon), "creature_template_addon", "Entry");
896 if(!sCreatureStorage.LookupEntry<CreatureInfo>(addon->guidOrEntry))
897 sLog.outErrorDb("Creature (Entry: %u) does not exist but has a record in `creature_template_addon`",addon->guidOrEntry);
900 sCreatureDataAddonStorage.Load();
902 sLog.outString( ">> Loaded %u creature addons", sCreatureDataAddonStorage.RecordCount );
903 sLog.outString();
905 // check data correctness and convert 'auras'
906 for(uint32 i = 1; i < sCreatureDataAddonStorage.MaxEntry; ++i)
908 CreatureDataAddon const* addon = sCreatureDataAddonStorage.LookupEntry<CreatureDataAddon>(i);
909 if(!addon)
910 continue;
912 ConvertCreatureAddonAuras(const_cast<CreatureDataAddon*>(addon), "creature_addon", "GUIDLow");
914 if(mCreatureDataMap.find(addon->guidOrEntry)==mCreatureDataMap.end())
915 sLog.outErrorDb("Creature (GUID: %u) does not exist but has a record in `creature_addon`",addon->guidOrEntry);
919 EquipmentInfo const* ObjectMgr::GetEquipmentInfo(uint32 entry)
921 return sEquipmentStorage.LookupEntry<EquipmentInfo>(entry);
924 void ObjectMgr::LoadEquipmentTemplates()
926 sEquipmentStorage.Load();
928 sLog.outString( ">> Loaded %u equipment template", sEquipmentStorage.RecordCount );
929 sLog.outString();
932 CreatureModelInfo const* ObjectMgr::GetCreatureModelInfo(uint32 modelid)
934 return sCreatureModelStorage.LookupEntry<CreatureModelInfo>(modelid);
937 uint32 ObjectMgr::ChooseDisplayId(uint32 team, const CreatureInfo *cinfo, const CreatureData *data)
939 // Load creature model (display id)
940 uint32 display_id;
941 if (!data || data->displayid == 0) // use defaults from the template
943 // DisplayID_A is used if no team is given
944 if (team == HORDE)
945 display_id = (cinfo->DisplayID_H2 != 0 && urand(0,1) == 0) ? cinfo->DisplayID_H2 : cinfo->DisplayID_H;
946 else
947 display_id = (cinfo->DisplayID_A2 != 0 && urand(0,1) == 0) ? cinfo->DisplayID_A2 : cinfo->DisplayID_A;
949 else // overridden in creature data
950 display_id = data->displayid;
952 return display_id;
955 CreatureModelInfo const* ObjectMgr::GetCreatureModelRandomGender(uint32 display_id)
957 CreatureModelInfo const *minfo = GetCreatureModelInfo(display_id);
958 if(!minfo)
959 return NULL;
961 // If a model for another gender exists, 50% chance to use it
962 if(minfo->modelid_other_gender != 0 && urand(0,1) == 0)
964 CreatureModelInfo const *minfo_tmp = GetCreatureModelInfo(minfo->modelid_other_gender);
965 if(!minfo_tmp)
967 sLog.outErrorDb("Model (Entry: %u) has modelid_other_gender %u not found in table `creature_model_info`. ", minfo->modelid, minfo->modelid_other_gender);
968 return minfo; // not fatal, just use the previous one
970 else
971 return minfo_tmp;
973 else
974 return minfo;
977 void ObjectMgr::LoadCreatureModelInfo()
979 sCreatureModelStorage.Load();
981 sLog.outString( ">> Loaded %u creature model based info", sCreatureModelStorage.RecordCount );
982 sLog.outString();
985 void ObjectMgr::LoadCreatures()
987 uint32 count = 0;
988 // 0 1 2 3
989 QueryResult *result = WorldDatabase.Query("SELECT creature.guid, id, map, modelid,"
990 // 4 5 6 7 8 9 10 11
991 "equipment_id, position_x, position_y, position_z, orientation, spawntimesecs, spawndist, currentwaypoint,"
992 // 12 13 14 15 16 17
993 "curhealth, curmana, DeathState, MovementType, spawnMask, event "
994 "FROM creature LEFT OUTER JOIN game_event_creature ON creature.guid = game_event_creature.guid");
996 if(!result)
998 barGoLink bar(1);
1000 bar.step();
1002 sLog.outString("");
1003 sLog.outErrorDb(">> Loaded 0 creature. DB table `creature` is empty.");
1004 return;
1007 // build single time for check creature data
1008 std::set<uint32> heroicCreatures;
1009 for(uint32 i = 0; i < sCreatureStorage.MaxEntry; ++i)
1010 if(CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i))
1011 if(cInfo->HeroicEntry)
1012 heroicCreatures.insert(cInfo->HeroicEntry);
1014 barGoLink bar(result->GetRowCount());
1018 Field *fields = result->Fetch();
1019 bar.step();
1021 uint32 guid = fields[0].GetUInt32();
1023 CreatureData& data = mCreatureDataMap[guid];
1025 data.id = fields[ 1].GetUInt32();
1026 data.mapid = fields[ 2].GetUInt32();
1027 data.displayid = fields[ 3].GetUInt32();
1028 data.equipmentId = fields[ 4].GetUInt32();
1029 data.posX = fields[ 5].GetFloat();
1030 data.posY = fields[ 6].GetFloat();
1031 data.posZ = fields[ 7].GetFloat();
1032 data.orientation = fields[ 8].GetFloat();
1033 data.spawntimesecs = fields[ 9].GetUInt32();
1034 data.spawndist = fields[10].GetFloat();
1035 data.currentwaypoint= fields[11].GetUInt32();
1036 data.curhealth = fields[12].GetUInt32();
1037 data.curmana = fields[13].GetUInt32();
1038 data.is_dead = fields[14].GetBool();
1039 data.movementType = fields[15].GetUInt8();
1040 data.spawnMask = fields[16].GetUInt8();
1041 int16 gameEvent = fields[17].GetInt16();
1043 CreatureInfo const* cInfo = GetCreatureTemplate(data.id);
1044 if(!cInfo)
1046 sLog.outErrorDb("Table `creature` have creature (GUID: %u) with not existed creature entry %u, skipped.",guid,data.id );
1047 continue;
1050 if(heroicCreatures.find(data.id)!=heroicCreatures.end())
1052 sLog.outErrorDb("Table `creature` have creature (GUID: %u) that listed as heroic template in `creature_template`, skipped.",guid,data.id );
1053 continue;
1056 if(data.equipmentId > 0) // -1 no equipment, 0 use default
1058 if(!GetEquipmentInfo(data.equipmentId))
1060 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);
1061 data.equipmentId = -1;
1065 if(cInfo->RegenHealth && data.curhealth < cInfo->minhealth)
1067 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 );
1068 data.curhealth = cInfo->minhealth;
1071 if(data.curmana < cInfo->minmana)
1073 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 );
1074 data.curmana = cInfo->minmana;
1077 if(data.spawndist < 0.0f)
1079 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `spawndist`< 0, set to 0.",guid,data.id );
1080 data.spawndist = 0.0f;
1082 else if(data.movementType == RANDOM_MOTION_TYPE)
1084 if(data.spawndist == 0.0f)
1086 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 );
1087 data.movementType = IDLE_MOTION_TYPE;
1090 else if(data.movementType == IDLE_MOTION_TYPE)
1092 if(data.spawndist != 0.0f)
1094 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `MovementType`=0 (idle) have `spawndist`<>0, set to 0.",guid,data.id );
1095 data.spawndist = 0.0f;
1099 if (gameEvent==0) // if not this is to be managed by GameEvent System
1100 AddCreatureToGrid(guid, &data);
1101 ++count;
1103 } while (result->NextRow());
1105 delete result;
1107 sLog.outString();
1108 sLog.outString( ">> Loaded %u creatures", mCreatureDataMap.size() );
1111 void ObjectMgr::AddCreatureToGrid(uint32 guid, CreatureData const* data)
1113 uint8 mask = data->spawnMask;
1114 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1116 if(mask & 1)
1118 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1119 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1121 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1122 cell_guids.creatures.insert(guid);
1127 void ObjectMgr::RemoveCreatureFromGrid(uint32 guid, CreatureData const* data)
1129 uint8 mask = data->spawnMask;
1130 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1132 if(mask & 1)
1134 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1135 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1137 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1138 cell_guids.creatures.erase(guid);
1143 void ObjectMgr::LoadGameobjects()
1145 uint32 count = 0;
1147 // 0 1 2 3 4 5 6
1148 QueryResult *result = WorldDatabase.Query("SELECT gameobject.guid, id, map, position_x, position_y, position_z, orientation,"
1149 // 7 8 9 10 11 12 13 14 15
1150 "rotation0, rotation1, rotation2, rotation3, spawntimesecs, animprogress, state, spawnMask, event "
1151 "FROM gameobject LEFT OUTER JOIN game_event_gameobject ON gameobject.guid = game_event_gameobject.guid");
1153 if(!result)
1155 barGoLink bar(1);
1157 bar.step();
1159 sLog.outString();
1160 sLog.outErrorDb(">> Loaded 0 gameobjects. DB table `gameobject` is empty.");
1161 return;
1164 barGoLink bar(result->GetRowCount());
1168 Field *fields = result->Fetch();
1169 bar.step();
1171 uint32 guid = fields[0].GetUInt32();
1173 GameObjectData& data = mGameObjectDataMap[guid];
1175 data.id = fields[ 1].GetUInt32();
1176 data.mapid = fields[ 2].GetUInt32();
1177 data.posX = fields[ 3].GetFloat();
1178 data.posY = fields[ 4].GetFloat();
1179 data.posZ = fields[ 5].GetFloat();
1180 data.orientation = fields[ 6].GetFloat();
1181 data.rotation0 = fields[ 7].GetFloat();
1182 data.rotation1 = fields[ 8].GetFloat();
1183 data.rotation2 = fields[ 9].GetFloat();
1184 data.rotation3 = fields[10].GetFloat();
1185 data.spawntimesecs = fields[11].GetInt32();
1186 data.animprogress = fields[12].GetUInt32();
1187 data.go_state = fields[13].GetUInt32();
1188 data.spawnMask = fields[14].GetUInt8();
1189 int16 gameEvent = fields[15].GetInt16();
1191 GameObjectInfo const* gInfo = GetGameObjectInfo(data.id);
1192 if(!gInfo)
1194 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u) with not existed gameobject entry %u, skipped.",guid,data.id );
1195 continue;
1198 if (gameEvent==0) // if not this is to be managed by GameEvent System
1199 AddGameobjectToGrid(guid, &data);
1200 ++count;
1202 } while (result->NextRow());
1204 delete result;
1206 sLog.outString();
1207 sLog.outString( ">> Loaded %u gameobjects", mGameObjectDataMap.size());
1210 void ObjectMgr::AddGameobjectToGrid(uint32 guid, GameObjectData const* data)
1212 uint8 mask = data->spawnMask;
1213 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1215 if(mask & 1)
1217 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1218 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1220 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1221 cell_guids.gameobjects.insert(guid);
1226 void ObjectMgr::RemoveGameobjectFromGrid(uint32 guid, GameObjectData const* data)
1228 uint8 mask = data->spawnMask;
1229 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1231 if(mask & 1)
1233 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1234 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1236 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1237 cell_guids.gameobjects.erase(guid);
1242 void ObjectMgr::LoadCreatureRespawnTimes()
1244 // remove outdated data
1245 WorldDatabase.DirectExecute("DELETE FROM creature_respawn WHERE respawntime <= UNIX_TIMESTAMP(NOW())");
1247 uint32 count = 0;
1249 QueryResult *result = WorldDatabase.Query("SELECT guid,respawntime,instance FROM creature_respawn");
1251 if(!result)
1253 barGoLink bar(1);
1255 bar.step();
1257 sLog.outString();
1258 sLog.outString(">> Loaded 0 creature respawn time.");
1259 return;
1262 barGoLink bar(result->GetRowCount());
1266 Field *fields = result->Fetch();
1267 bar.step();
1269 uint32 loguid = fields[0].GetUInt32();
1270 uint64 respawn_time = fields[1].GetUInt64();
1271 uint32 instance = fields[2].GetUInt32();
1273 mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = time_t(respawn_time);
1275 ++count;
1276 } while (result->NextRow());
1278 delete result;
1280 sLog.outString( ">> Loaded %u creature respawn times", mCreatureRespawnTimes.size() );
1281 sLog.outString();
1284 void ObjectMgr::LoadGameobjectRespawnTimes()
1286 // remove outdated data
1287 WorldDatabase.DirectExecute("DELETE FROM gameobject_respawn WHERE respawntime <= UNIX_TIMESTAMP(NOW())");
1289 uint32 count = 0;
1291 QueryResult *result = WorldDatabase.Query("SELECT guid,respawntime,instance FROM gameobject_respawn");
1293 if(!result)
1295 barGoLink bar(1);
1297 bar.step();
1299 sLog.outString();
1300 sLog.outString(">> Loaded 0 gameobject respawn time.");
1301 return;
1304 barGoLink bar(result->GetRowCount());
1308 Field *fields = result->Fetch();
1309 bar.step();
1311 uint32 loguid = fields[0].GetUInt32();
1312 uint64 respawn_time = fields[1].GetUInt64();
1313 uint32 instance = fields[2].GetUInt32();
1315 mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = time_t(respawn_time);
1317 ++count;
1318 } while (result->NextRow());
1320 delete result;
1322 sLog.outString( ">> Loaded %u gameobject respawn times", mGORespawnTimes.size() );
1323 sLog.outString();
1326 // name must be checked to correctness (if received) before call this function
1327 uint64 ObjectMgr::GetPlayerGUIDByName(std::string name) const
1329 uint64 guid = 0;
1331 CharacterDatabase.escape_string(name);
1333 // Player name safe to sending to DB (checked at login) and this function using
1334 QueryResult *result = CharacterDatabase.PQuery("SELECT guid FROM characters WHERE name = '%s'", name.c_str());
1335 if(result)
1337 guid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
1339 delete result;
1342 return guid;
1345 bool ObjectMgr::GetPlayerNameByGUID(const uint64 &guid, std::string &name) const
1347 // prevent DB access for online player
1348 if(Player* player = GetPlayer(guid))
1350 name = player->GetName();
1351 return true;
1354 QueryResult *result = CharacterDatabase.PQuery("SELECT name FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1356 if(result)
1358 name = (*result)[0].GetCppString();
1359 delete result;
1360 return true;
1363 return false;
1366 uint32 ObjectMgr::GetPlayerTeamByGUID(const uint64 &guid) const
1368 QueryResult *result = CharacterDatabase.PQuery("SELECT race FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1370 if(result)
1372 uint8 race = (*result)[0].GetUInt8();
1373 delete result;
1374 return Player::TeamForRace(race);
1377 return 0;
1380 uint32 ObjectMgr::GetPlayerAccountIdByGUID(const uint64 &guid) const
1382 QueryResult *result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1383 if(result)
1385 uint32 acc = (*result)[0].GetUInt32();
1386 delete result;
1387 return acc;
1390 return 0;
1393 uint32 ObjectMgr::GetPlayerAccountIdByPlayerName(const std::string& name) const
1395 QueryResult *result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'", name.c_str());
1396 if(result)
1398 uint32 acc = (*result)[0].GetUInt32();
1399 delete result;
1400 return acc;
1403 return 0;
1406 void ObjectMgr::LoadAuctions()
1408 QueryResult *result = CharacterDatabase.Query("SELECT COUNT(*) FROM auctionhouse");
1409 if( !result )
1410 return;
1412 Field *fields = result->Fetch();
1413 uint32 AuctionCount=fields[0].GetUInt32();
1414 delete result;
1416 if(!AuctionCount)
1417 return;
1419 result = CharacterDatabase.Query( "SELECT id,auctioneerguid,itemguid,item_template,itemowner,buyoutprice,time,buyguid,lastbid,startbid,deposit,location FROM auctionhouse" );
1420 if( !result )
1421 return;
1423 barGoLink bar( AuctionCount );
1425 AuctionEntry *aItem;
1429 fields = result->Fetch();
1431 bar.step();
1433 aItem = new AuctionEntry;
1434 aItem->Id = fields[0].GetUInt32();
1435 aItem->auctioneer = fields[1].GetUInt32();
1436 aItem->item_guidlow = fields[2].GetUInt32();
1437 aItem->item_template = fields[3].GetUInt32();
1438 aItem->owner = fields[4].GetUInt32();
1439 aItem->buyout = fields[5].GetUInt32();
1440 aItem->time = fields[6].GetUInt32();
1441 aItem->bidder = fields[7].GetUInt32();
1442 aItem->bid = fields[8].GetUInt32();
1443 aItem->startbid = fields[9].GetUInt32();
1444 aItem->deposit = fields[10].GetUInt32();
1445 aItem->location = fields[11].GetUInt8();
1446 //check if sold item exists
1447 if ( GetAItem( aItem->item_guidlow ) )
1449 GetAuctionsMap( aItem->location )->AddAuction(aItem);
1451 else
1453 CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE id = '%u'",aItem->Id);
1454 sLog.outError("Auction %u has not a existing item : %u", aItem->Id, aItem->item_guidlow);
1455 delete aItem;
1457 } while (result->NextRow());
1458 delete result;
1460 sLog.outString();
1461 sLog.outString( ">> Loaded %u auctions", AuctionCount );
1462 sLog.outString();
1465 void ObjectMgr::LoadItemLocales()
1467 mItemLocaleMap.clear(); // need for reload case
1469 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");
1471 if(!result)
1473 barGoLink bar(1);
1475 bar.step();
1477 sLog.outString("");
1478 sLog.outString(">> Loaded 0 Item locale strings. DB table `locales_item` is empty.");
1479 return;
1482 barGoLink bar(result->GetRowCount());
1486 Field *fields = result->Fetch();
1487 bar.step();
1489 uint32 entry = fields[0].GetUInt32();
1491 ItemLocale& data = mItemLocaleMap[entry];
1493 for(int i = 1; i < MAX_LOCALE; ++i)
1495 std::string str = fields[1+2*(i-1)].GetCppString();
1496 if(!str.empty())
1498 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
1499 if(idx >= 0)
1501 if(data.Name.size() <= idx)
1502 data.Name.resize(idx+1);
1504 data.Name[idx] = str;
1508 str = fields[1+2*(i-1)+1].GetCppString();
1509 if(!str.empty())
1511 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
1512 if(idx >= 0)
1514 if(data.Description.size() <= idx)
1515 data.Description.resize(idx+1);
1517 data.Description[idx] = str;
1521 } while (result->NextRow());
1523 delete result;
1525 sLog.outString();
1526 sLog.outString( ">> Loaded %u Item locale strings", mItemLocaleMap.size() );
1529 struct SQLItemLoader : public SQLStorageLoaderBase<SQLItemLoader>
1531 template<class D>
1532 void convert_from_str(uint32 field_pos, char *src, D &dst)
1534 dst = D(objmgr.GetScriptId(src));
1538 void ObjectMgr::LoadItemPrototypes()
1540 SQLItemLoader loader;
1541 loader.Load(sItemStorage);
1542 sLog.outString( ">> Loaded %u item prototypes", sItemStorage.RecordCount );
1543 sLog.outString();
1545 // check data correctness
1546 for(uint32 i = 1; i < sItemStorage.MaxEntry; ++i)
1548 ItemPrototype const* proto = sItemStorage.LookupEntry<ItemPrototype >(i);
1549 ItemEntry const *dbcitem = sItemStore.LookupEntry(i);
1550 if(!proto)
1552 /* to many errors, and possible not all items really used in game
1553 if (dbcitem)
1554 sLog.outErrorDb("Item (Entry: %u) doesn't exists in DB, but must exist.",i);
1556 continue;
1559 if(dbcitem)
1561 if(proto->InventoryType != dbcitem->InventoryType)
1563 sLog.outErrorDb("Item (Entry: %u) not correct %u inventory type, must be %u (still using DB value).",i,proto->InventoryType,dbcitem->InventoryType);
1564 // It safe let use InventoryType from DB
1567 if(proto->DisplayInfoID != dbcitem->DisplayId)
1569 sLog.outErrorDb("Item (Entry: %u) not correct %u display id, must be %u (using it).",i,proto->DisplayInfoID,dbcitem->DisplayId);
1570 const_cast<ItemPrototype*>(proto)->DisplayInfoID = dbcitem->DisplayId;
1572 if(proto->Sheath != dbcitem->Sheath)
1574 sLog.outErrorDb("Item (Entry: %u) not correct %u sheath, must be %u (using it).",i,proto->Sheath,dbcitem->Sheath);
1575 const_cast<ItemPrototype*>(proto)->Sheath = dbcitem->Sheath;
1578 else
1580 sLog.outErrorDb("Item (Entry: %u) not correct (not listed in list of existed items).",i);
1583 if(proto->Class >= MAX_ITEM_CLASS)
1585 sLog.outErrorDb("Item (Entry: %u) has wrong Class value (%u)",i,proto->Class);
1586 const_cast<ItemPrototype*>(proto)->Class = ITEM_CLASS_JUNK;
1589 if(proto->SubClass >= MaxItemSubclassValues[proto->Class])
1591 sLog.outErrorDb("Item (Entry: %u) has wrong Subclass value (%u) for class %u",i,proto->SubClass,proto->Class);
1592 const_cast<ItemPrototype*>(proto)->SubClass = 0;// exist for all item classes
1595 if(proto->Quality >= MAX_ITEM_QUALITY)
1597 sLog.outErrorDb("Item (Entry: %u) has wrong Quality value (%u)",i,proto->Quality);
1598 const_cast<ItemPrototype*>(proto)->Quality = ITEM_QUALITY_NORMAL;
1601 if(proto->BuyCount <= 0)
1603 sLog.outErrorDb("Item (Entry: %u) has wrong BuyCount value (%u), set to default(1).",i,proto->BuyCount);
1604 const_cast<ItemPrototype*>(proto)->BuyCount = 1;
1607 if(proto->InventoryType >= MAX_INVTYPE)
1609 sLog.outErrorDb("Item (Entry: %u) has wrong InventoryType value (%u)",i,proto->InventoryType);
1610 const_cast<ItemPrototype*>(proto)->InventoryType = INVTYPE_NON_EQUIP;
1613 if(proto->RequiredSkill >= MAX_SKILL_TYPE)
1615 sLog.outErrorDb("Item (Entry: %u) has wrong RequiredSkill value (%u)",i,proto->RequiredSkill);
1616 const_cast<ItemPrototype*>(proto)->RequiredSkill = 0;
1619 if(!(proto->AllowableClass & CLASSMASK_ALL_PLAYABLE))
1621 sLog.outErrorDb("Item (Entry: %u) not have in `AllowableClass` any playable classes (%u) and can't be equipped.",i,proto->AllowableClass);
1624 if(!(proto->AllowableRace & RACEMASK_ALL_PLAYABLE))
1626 sLog.outErrorDb("Item (Entry: %u) not have in `AllowableRace` any playable races (%u) and can't be equipped.",i,proto->AllowableRace);
1629 if(proto->RequiredSpell && !sSpellStore.LookupEntry(proto->RequiredSpell))
1631 sLog.outErrorDb("Item (Entry: %u) have wrong (non-existed) spell in RequiredSpell (%u)",i,proto->RequiredSpell);
1632 const_cast<ItemPrototype*>(proto)->RequiredSpell = 0;
1635 if(proto->RequiredReputationRank >= MAX_REPUTATION_RANK)
1636 sLog.outErrorDb("Item (Entry: %u) has wrong reputation rank in RequiredReputationRank (%u), item can't be used.",i,proto->RequiredReputationRank);
1638 if(proto->RequiredReputationFaction)
1640 if(!sFactionStore.LookupEntry(proto->RequiredReputationFaction))
1642 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) faction in RequiredReputationFaction (%u)",i,proto->RequiredReputationFaction);
1643 const_cast<ItemPrototype*>(proto)->RequiredReputationFaction = 0;
1646 if(proto->RequiredReputationRank == MIN_REPUTATION_RANK)
1647 sLog.outErrorDb("Item (Entry: %u) has min. reputation rank in RequiredReputationRank (0) but RequiredReputationFaction > 0, faction setting is useless.",i);
1649 else if(proto->RequiredReputationRank > MIN_REPUTATION_RANK)
1650 sLog.outErrorDb("Item (Entry: %u) has RequiredReputationFaction ==0 but RequiredReputationRank > 0, rank setting is useless.",i);
1652 if(proto->Stackable==0)
1654 sLog.outErrorDb("Item (Entry: %u) has wrong value in stackable (%u), replace by default 1.",i,proto->Stackable);
1655 const_cast<ItemPrototype*>(proto)->Stackable = 1;
1657 else if(proto->Stackable > 255)
1659 sLog.outErrorDb("Item (Entry: %u) has too large value in stackable (%u), replace by hardcoded upper limit (255).",i,proto->Stackable);
1660 const_cast<ItemPrototype*>(proto)->Stackable = 255;
1663 for (int j = 0; j < 10; j++)
1665 // for ItemStatValue != 0
1666 if(proto->ItemStat[j].ItemStatValue && proto->ItemStat[j].ItemStatType >= MAX_ITEM_MOD)
1668 sLog.outErrorDb("Item (Entry: %u) has wrong stat_type%d (%u)",i,j+1,proto->ItemStat[j].ItemStatType);
1669 const_cast<ItemPrototype*>(proto)->ItemStat[j].ItemStatType = 0;
1673 for (int j = 0; j < 5; j++)
1675 if(proto->Damage[j].DamageType >= MAX_SPELL_SCHOOL)
1677 sLog.outErrorDb("Item (Entry: %u) has wrong dmg_type%d (%u)",i,j+1,proto->Damage[j].DamageType);
1678 const_cast<ItemPrototype*>(proto)->Damage[j].DamageType = 0;
1682 // special format
1683 if(proto->Spells[0].SpellId == SPELL_ID_GENERIC_LEARN)
1685 // spell_1
1686 if(proto->Spells[0].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
1688 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);
1689 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1690 const_cast<ItemPrototype*>(proto)->Spells[0].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1691 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1692 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1695 // spell_2 have learning spell
1696 if(proto->Spells[1].SpellTrigger != ITEM_SPELLTRIGGER_LEARN_SPELL_ID)
1698 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);
1699 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1700 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1701 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1703 else if(!proto->Spells[1].SpellId)
1705 sLog.outErrorDb("Item (Entry: %u) not has expected spell in spellid_%d in special learning format.",i,1+1);
1706 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1707 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1709 else
1711 SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[1].SpellId);
1712 if(!spellInfo)
1714 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%u)",i,1+1,proto->Spells[1].SpellId);
1715 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1716 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1717 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1719 // allowed only in special format
1720 else if(proto->Spells[1].SpellId==SPELL_ID_GENERIC_LEARN)
1722 sLog.outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%u)",i,1+1,proto->Spells[1].SpellId);
1723 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1724 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1725 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1729 // spell_3*,spell_4*,spell_5* is empty
1730 for (int j = 2; j < 5; j++)
1732 if(proto->Spells[j].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
1734 sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)",i,j+1,proto->Spells[j].SpellTrigger);
1735 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1736 const_cast<ItemPrototype*>(proto)->Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1738 else if(proto->Spells[j].SpellId != 0)
1740 sLog.outErrorDb("Item (Entry: %u) has wrong spell in spellid_%d (%u) for learning special format",i,j+1,proto->Spells[j].SpellId);
1741 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1745 // normal spell list
1746 else
1748 for (int j = 0; j < 5; j++)
1750 if(proto->Spells[j].SpellTrigger >= MAX_ITEM_SPELLTRIGGER || proto->Spells[j].SpellTrigger == ITEM_SPELLTRIGGER_LEARN_SPELL_ID)
1752 sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)",i,j+1,proto->Spells[j].SpellTrigger);
1753 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1754 const_cast<ItemPrototype*>(proto)->Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1757 if(proto->Spells[j].SpellId)
1759 SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[j].SpellId);
1760 if(!spellInfo)
1762 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%u)",i,j+1,proto->Spells[j].SpellId);
1763 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1765 // allowed only in special format
1766 else if(proto->Spells[j].SpellId==SPELL_ID_GENERIC_LEARN)
1768 sLog.outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%u)",i,j+1,proto->Spells[j].SpellId);
1769 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1775 if(proto->Bonding >= MAX_BIND_TYPE)
1776 sLog.outErrorDb("Item (Entry: %u) has wrong Bonding value (%u)",i,proto->Bonding);
1778 if(proto->PageText && !sPageTextStore.LookupEntry<PageText>(proto->PageText))
1779 sLog.outErrorDb("Item (Entry: %u) has non existing first page (Id:%u)", i,proto->PageText);
1781 if(proto->LockID && !sLockStore.LookupEntry(proto->LockID))
1782 sLog.outErrorDb("Item (Entry: %u) has wrong LockID (%u)",i,proto->LockID);
1784 if(proto->Sheath >= MAX_SHEATHETYPE)
1786 sLog.outErrorDb("Item (Entry: %u) has wrong Sheath (%u)",i,proto->Sheath);
1787 const_cast<ItemPrototype*>(proto)->Sheath = SHEATHETYPE_NONE;
1790 if(proto->RandomProperty && !sItemRandomPropertiesStore.LookupEntry(GetItemEnchantMod(proto->RandomProperty)))
1792 sLog.outErrorDb("Item (Entry: %u) has unknown (wrong or not listed in `item_enchantment_template`) RandomProperty (%u)",i,proto->RandomProperty);
1793 const_cast<ItemPrototype*>(proto)->RandomProperty = 0;
1796 if(proto->RandomSuffix && !sItemRandomSuffixStore.LookupEntry(GetItemEnchantMod(proto->RandomSuffix)))
1798 sLog.outErrorDb("Item (Entry: %u) has wrong RandomSuffix (%u)",i,proto->RandomSuffix);
1799 const_cast<ItemPrototype*>(proto)->RandomSuffix = 0;
1802 if(proto->ItemSet && !sItemSetStore.LookupEntry(proto->ItemSet))
1804 sLog.outErrorDb("Item (Entry: %u) have wrong ItemSet (%u)",i,proto->ItemSet);
1805 const_cast<ItemPrototype*>(proto)->ItemSet = 0;
1808 if(proto->Area && !GetAreaEntryByAreaID(proto->Area))
1809 sLog.outErrorDb("Item (Entry: %u) has wrong Area (%u)",i,proto->Area);
1811 if(proto->Map && !sMapStore.LookupEntry(proto->Map))
1812 sLog.outErrorDb("Item (Entry: %u) has wrong Map (%u)",i,proto->Map);
1814 if(proto->TotemCategory && !sTotemCategoryStore.LookupEntry(proto->TotemCategory))
1815 sLog.outErrorDb("Item (Entry: %u) has wrong TotemCategory (%u)",i,proto->TotemCategory);
1817 for (int j = 0; j < 3; j++)
1819 if(proto->Socket[j].Color && (proto->Socket[j].Color & SOCKET_COLOR_ALL) != proto->Socket[j].Color)
1821 sLog.outErrorDb("Item (Entry: %u) has wrong socketColor_%d (%u)",i,j+1,proto->Socket[j].Color);
1822 const_cast<ItemPrototype*>(proto)->Socket[j].Color = 0;
1826 if(proto->GemProperties && !sGemPropertiesStore.LookupEntry(proto->GemProperties))
1827 sLog.outErrorDb("Item (Entry: %u) has wrong GemProperties (%u)",i,proto->GemProperties);
1829 if(proto->FoodType >= MAX_PET_DIET)
1831 sLog.outErrorDb("Item (Entry: %u) has wrong FoodType value (%u)",i,proto->FoodType);
1832 const_cast<ItemPrototype*>(proto)->FoodType = 0;
1836 // this DBC used currently only for check item templates in DB.
1837 sItemStore.Clear();
1840 void ObjectMgr::LoadAuctionItems()
1842 QueryResult *result = CharacterDatabase.Query( "SELECT itemguid,item_template FROM auctionhouse" );
1844 if( !result )
1845 return;
1847 barGoLink bar( result->GetRowCount() );
1849 uint32 count = 0;
1851 Field *fields;
1854 bar.step();
1856 fields = result->Fetch();
1857 uint32 item_guid = fields[0].GetUInt32();
1858 uint32 item_template = fields[1].GetUInt32();
1860 ItemPrototype const *proto = GetItemPrototype(item_template);
1862 if(!proto)
1864 sLog.outError( "ObjectMgr::LoadAuctionItems: Unknown item (GUID: %u id: #%u) in auction, skipped.", item_guid,item_template);
1865 continue;
1868 Item *item = NewItemOrBag(proto);
1870 if(!item->LoadFromDB(item_guid,0))
1872 delete item;
1873 continue;
1875 AddAItem(item);
1877 ++count;
1879 while( result->NextRow() );
1881 delete result;
1883 sLog.outString();
1884 sLog.outString( ">> Loaded %u auction items", count );
1887 void ObjectMgr::LoadPetLevelInfo()
1889 // Loading levels data
1891 // 0 1 2 3 4 5 6 7 8 9
1892 QueryResult *result = WorldDatabase.Query("SELECT creature_entry, level, hp, mana, str, agi, sta, inte, spi, armor FROM pet_levelstats");
1894 uint32 count = 0;
1896 if (!result)
1898 barGoLink bar( 1 );
1900 sLog.outString();
1901 sLog.outString( ">> Loaded %u level pet stats definitions", count );
1902 sLog.outErrorDb( "Error loading `pet_levelstats` table or empty table.");
1903 return;
1906 barGoLink bar( result->GetRowCount() );
1910 Field* fields = result->Fetch();
1912 uint32 creature_id = fields[0].GetUInt32();
1913 if(!sCreatureStorage.LookupEntry<CreatureInfo>(creature_id))
1915 sLog.outErrorDb("Wrong creature id %u in `pet_levelstats` table, ignoring.",creature_id);
1916 continue;
1919 uint32 current_level = fields[1].GetUInt32();
1920 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
1922 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
1923 sLog.outErrorDb("Wrong (> %u) level %u in `pet_levelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
1924 else
1925 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `pet_levelstats` table, ignoring.",current_level);
1926 continue;
1928 else if(current_level < 1)
1930 sLog.outErrorDb("Wrong (<1) level %u in `pet_levelstats` table, ignoring.",current_level);
1931 continue;
1934 PetLevelInfo*& pInfoMapEntry = petInfo[creature_id];
1936 if(pInfoMapEntry==NULL)
1937 pInfoMapEntry = new PetLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
1939 // data for level 1 stored in [0] array element, ...
1940 PetLevelInfo* pLevelInfo = &pInfoMapEntry[current_level-1];
1942 pLevelInfo->health = fields[2].GetUInt16();
1943 pLevelInfo->mana = fields[3].GetUInt16();
1944 pLevelInfo->armor = fields[9].GetUInt16();
1946 for (int i = 0; i < MAX_STATS; i++)
1948 pLevelInfo->stats[i] = fields[i+4].GetUInt16();
1951 bar.step();
1952 ++count;
1954 while (result->NextRow());
1956 delete result;
1958 sLog.outString();
1959 sLog.outString( ">> Loaded %u level pet stats definitions", count );
1962 // Fill gaps and check integrity
1963 for (PetLevelInfoMap::iterator itr = petInfo.begin(); itr != petInfo.end(); ++itr)
1965 PetLevelInfo* pInfo = itr->second;
1967 // fatal error if no level 1 data
1968 if(!pInfo || pInfo[0].health == 0 )
1970 sLog.outErrorDb("Creature %u does not have pet stats data for Level 1!",itr->first);
1971 exit(1);
1974 // fill level gaps
1975 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
1977 if(pInfo[level].health == 0)
1979 sLog.outErrorDb("Creature %u has no data for Level %i pet stats data, using data of Level %i.",itr->first,level+1, level);
1980 pInfo[level] = pInfo[level-1];
1986 PetLevelInfo const* ObjectMgr::GetPetLevelInfo(uint32 creature_id, uint32 level) const
1988 if(level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
1989 level = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL);
1991 PetLevelInfoMap::const_iterator itr = petInfo.find(creature_id);
1992 if(itr == petInfo.end())
1993 return NULL;
1995 return &itr->second[level-1]; // data for level 1 stored in [0] array element, ...
1998 void ObjectMgr::LoadPlayerInfo()
2000 // Load playercreate
2002 // 0 1 2 3 4 5 6
2003 QueryResult *result = WorldDatabase.Query("SELECT race, class, map, zone, position_x, position_y, position_z FROM playercreateinfo");
2005 uint32 count = 0;
2007 if (!result)
2009 barGoLink bar( 1 );
2011 sLog.outString();
2012 sLog.outString( ">> Loaded %u player create definitions", count );
2013 sLog.outErrorDb( "Error loading `playercreateinfo` table or empty table.");
2014 exit(1);
2017 barGoLink bar( result->GetRowCount() );
2021 Field* fields = result->Fetch();
2023 uint32 current_race = fields[0].GetUInt32();
2024 uint32 current_class = fields[1].GetUInt32();
2025 uint32 mapId = fields[2].GetUInt32();
2026 uint32 zoneId = fields[3].GetUInt32();
2027 float positionX = fields[4].GetFloat();
2028 float positionY = fields[5].GetFloat();
2029 float positionZ = fields[6].GetFloat();
2031 if(current_race >= MAX_RACES)
2033 sLog.outErrorDb("Wrong race %u in `playercreateinfo` table, ignoring.",current_race);
2034 continue;
2037 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(current_race);
2038 if(!rEntry)
2040 sLog.outErrorDb("Wrong race %u in `playercreateinfo` table, ignoring.",current_race);
2041 continue;
2044 if(current_class >= MAX_CLASSES)
2046 sLog.outErrorDb("Wrong class %u in `playercreateinfo` table, ignoring.",current_class);
2047 continue;
2050 if(!sChrClassesStore.LookupEntry(current_class))
2052 sLog.outErrorDb("Wrong class %u in `playercreateinfo` table, ignoring.",current_class);
2053 continue;
2056 // accept DB data only for valid position (and non instanceable)
2057 if( !MapManager::IsValidMapCoord(mapId,positionX,positionY,positionZ) )
2059 sLog.outErrorDb("Wrong home position for class %u race %u pair in `playercreateinfo` table, ignoring.",current_class,current_race);
2060 continue;
2063 if( sMapStore.LookupEntry(mapId)->Instanceable() )
2065 sLog.outErrorDb("Home position in instanceable map for class %u race %u pair in `playercreateinfo` table, ignoring.",current_class,current_race);
2066 continue;
2069 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2071 pInfo->mapId = mapId;
2072 pInfo->zoneId = zoneId;
2073 pInfo->positionX = positionX;
2074 pInfo->positionY = positionY;
2075 pInfo->positionZ = positionZ;
2077 pInfo->displayId_m = rEntry->model_m;
2078 pInfo->displayId_f = rEntry->model_f;
2080 bar.step();
2081 ++count;
2083 while (result->NextRow());
2085 delete result;
2087 sLog.outString();
2088 sLog.outString( ">> Loaded %u player create definitions", count );
2091 // Load playercreate items
2093 // 0 1 2 3
2094 QueryResult *result = WorldDatabase.Query("SELECT race, class, itemid, amount FROM playercreateinfo_item");
2096 uint32 count = 0;
2098 if (!result)
2100 barGoLink bar( 1 );
2102 sLog.outString();
2103 sLog.outString( ">> Loaded %u custom player create items", count );
2105 else
2107 barGoLink bar( result->GetRowCount() );
2111 Field* fields = result->Fetch();
2113 uint32 current_race = fields[0].GetUInt32();
2114 if(current_race >= MAX_RACES)
2116 sLog.outErrorDb("Wrong race %u in `playercreateinfo_item` table, ignoring.",current_race);
2117 continue;
2120 uint32 current_class = fields[1].GetUInt32();
2121 if(current_class >= MAX_CLASSES)
2123 sLog.outErrorDb("Wrong class %u in `playercreateinfo_item` table, ignoring.",current_class);
2124 continue;
2127 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2129 uint32 item_id = fields[2].GetUInt32();
2131 if(!GetItemPrototype(item_id))
2133 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);
2134 continue;
2137 uint32 amount = fields[3].GetUInt32();
2139 if(!amount)
2141 sLog.outErrorDb("Item id %u (class %u race %u) have amount==0 in `playercreateinfo_item` table, ignoring.",item_id,current_race,current_class);
2142 continue;
2145 pInfo->item.push_back(PlayerCreateInfoItem( item_id, amount));
2147 bar.step();
2148 ++count;
2150 while(result->NextRow());
2152 delete result;
2154 sLog.outString();
2155 sLog.outString( ">> Loaded %u custom player create items", count );
2159 // Load playercreate spells
2161 // 0 1 2 3
2162 QueryResult *result = WorldDatabase.Query("SELECT race, class, Spell, Active FROM playercreateinfo_spell");
2164 uint32 count = 0;
2166 if (!result)
2168 barGoLink bar( 1 );
2170 sLog.outString();
2171 sLog.outString( ">> Loaded %u player create spells", count );
2172 sLog.outErrorDb( "Error loading `playercreateinfo_spell` table or empty table.");
2174 else
2176 barGoLink bar( result->GetRowCount() );
2180 Field* fields = result->Fetch();
2182 uint32 current_race = fields[0].GetUInt32();
2183 if(current_race >= MAX_RACES)
2185 sLog.outErrorDb("Wrong race %u in `playercreateinfo_spell` table, ignoring.",current_race);
2186 continue;
2189 uint32 current_class = fields[1].GetUInt32();
2190 if(current_class >= MAX_CLASSES)
2192 sLog.outErrorDb("Wrong class %u in `playercreateinfo_spell` table, ignoring.",current_class);
2193 continue;
2196 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2197 pInfo->spell.push_back(CreateSpellPair(fields[2].GetUInt16(), fields[3].GetUInt8()));
2199 bar.step();
2200 ++count;
2202 while( result->NextRow() );
2204 delete result;
2206 sLog.outString();
2207 sLog.outString( ">> Loaded %u player create spells", count );
2211 // Load playercreate actions
2213 // 0 1 2 3 4 5
2214 QueryResult *result = WorldDatabase.Query("SELECT race, class, button, action, type, misc FROM playercreateinfo_action");
2216 uint32 count = 0;
2218 if (!result)
2220 barGoLink bar( 1 );
2222 sLog.outString();
2223 sLog.outString( ">> Loaded %u player create actions", count );
2224 sLog.outErrorDb( "Error loading `playercreateinfo_action` table or empty table.");
2226 else
2228 barGoLink bar( result->GetRowCount() );
2232 Field* fields = result->Fetch();
2234 uint32 current_race = fields[0].GetUInt32();
2235 if(current_race >= MAX_RACES)
2237 sLog.outErrorDb("Wrong race %u in `playercreateinfo_action` table, ignoring.",current_race);
2238 continue;
2241 uint32 current_class = fields[1].GetUInt32();
2242 if(current_class >= MAX_CLASSES)
2244 sLog.outErrorDb("Wrong class %u in `playercreateinfo_action` table, ignoring.",current_class);
2245 continue;
2248 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2249 pInfo->action[0].push_back(fields[2].GetUInt16());
2250 pInfo->action[1].push_back(fields[3].GetUInt16());
2251 pInfo->action[2].push_back(fields[4].GetUInt16());
2252 pInfo->action[3].push_back(fields[5].GetUInt16());
2254 bar.step();
2255 ++count;
2257 while( result->NextRow() );
2259 delete result;
2261 sLog.outString();
2262 sLog.outString( ">> Loaded %u player create actions", count );
2266 // Loading levels data (class only dependent)
2268 // 0 1 2 3
2269 QueryResult *result = WorldDatabase.Query("SELECT class, level, basehp, basemana FROM player_classlevelstats");
2271 uint32 count = 0;
2273 if (!result)
2275 barGoLink bar( 1 );
2277 sLog.outString();
2278 sLog.outString( ">> Loaded %u level health/mana definitions", count );
2279 sLog.outErrorDb( "Error loading `player_classlevelstats` table or empty table.");
2280 exit(1);
2283 barGoLink bar( result->GetRowCount() );
2287 Field* fields = result->Fetch();
2289 uint32 current_class = fields[0].GetUInt32();
2290 if(current_class >= MAX_CLASSES)
2292 sLog.outErrorDb("Wrong class %u in `player_classlevelstats` table, ignoring.",current_class);
2293 continue;
2296 uint32 current_level = fields[1].GetUInt32();
2297 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2299 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2300 sLog.outErrorDb("Wrong (> %u) level %u in `player_classlevelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
2301 else
2302 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_classlevelstats` table, ignoring.",current_level);
2303 continue;
2306 PlayerClassInfo* pClassInfo = &playerClassInfo[current_class];
2308 if(!pClassInfo->levelInfo)
2309 pClassInfo->levelInfo = new PlayerClassLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
2311 PlayerClassLevelInfo* pClassLevelInfo = &pClassInfo->levelInfo[current_level-1];
2313 pClassLevelInfo->basehealth = fields[2].GetUInt16();
2314 pClassLevelInfo->basemana = fields[3].GetUInt16();
2316 bar.step();
2317 ++count;
2319 while (result->NextRow());
2321 delete result;
2323 sLog.outString();
2324 sLog.outString( ">> Loaded %u level health/mana definitions", count );
2327 // Fill gaps and check integrity
2328 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2330 // skip non existed classes
2331 if(!sChrClassesStore.LookupEntry(class_))
2332 continue;
2334 PlayerClassInfo* pClassInfo = &playerClassInfo[class_];
2336 // fatal error if no level 1 data
2337 if(!pClassInfo->levelInfo || pClassInfo->levelInfo[0].basehealth == 0 )
2339 sLog.outErrorDb("Class %i Level 1 does not have health/mana data!",class_);
2340 exit(1);
2343 // fill level gaps
2344 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2346 if(pClassInfo->levelInfo[level].basehealth == 0)
2348 sLog.outErrorDb("Class %i Level %i does not have health/mana data. Using stats data of level %i.",class_,level+1, level);
2349 pClassInfo->levelInfo[level] = pClassInfo->levelInfo[level-1];
2354 // Loading levels data (class/race dependent)
2356 // 0 1 2 3 4 5 6 7
2357 QueryResult *result = WorldDatabase.Query("SELECT race, class, level, str, agi, sta, inte, spi FROM player_levelstats");
2359 uint32 count = 0;
2361 if (!result)
2363 barGoLink bar( 1 );
2365 sLog.outString();
2366 sLog.outString( ">> Loaded %u level stats definitions", count );
2367 sLog.outErrorDb( "Error loading `player_levelstats` table or empty table.");
2368 exit(1);
2371 barGoLink bar( result->GetRowCount() );
2375 Field* fields = result->Fetch();
2377 uint32 current_race = fields[0].GetUInt32();
2378 if(current_race >= MAX_RACES)
2380 sLog.outErrorDb("Wrong race %u in `player_levelstats` table, ignoring.",current_race);
2381 continue;
2384 uint32 current_class = fields[1].GetUInt32();
2385 if(current_class >= MAX_CLASSES)
2387 sLog.outErrorDb("Wrong class %u in `player_levelstats` table, ignoring.",current_class);
2388 continue;
2391 uint32 current_level = fields[2].GetUInt32();
2392 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2394 if(current_level > STRONG_MAX_LEVEL) // hardcoded level maximum
2395 sLog.outErrorDb("Wrong (> %u) level %u in `player_levelstats` table, ignoring.",STRONG_MAX_LEVEL,current_level);
2396 else
2397 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_levelstats` table, ignoring.",current_level);
2398 continue;
2401 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2403 if(!pInfo->levelInfo)
2404 pInfo->levelInfo = new PlayerLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
2406 PlayerLevelInfo* pLevelInfo = &pInfo->levelInfo[current_level-1];
2408 for (int i = 0; i < MAX_STATS; i++)
2410 pLevelInfo->stats[i] = fields[i+3].GetUInt8();
2413 bar.step();
2414 ++count;
2416 while (result->NextRow());
2418 delete result;
2420 sLog.outString();
2421 sLog.outString( ">> Loaded %u level stats definitions", count );
2424 // Fill gaps and check integrity
2425 for (int race = 0; race < MAX_RACES; ++race)
2427 // skip non existed races
2428 if(!sChrRacesStore.LookupEntry(race))
2429 continue;
2431 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2433 // skip non existed classes
2434 if(!sChrClassesStore.LookupEntry(class_))
2435 continue;
2437 PlayerInfo* pInfo = &playerInfo[race][class_];
2439 // skip non loaded combinations
2440 if(!pInfo->displayId_m || !pInfo->displayId_f)
2441 continue;
2443 // skip expansion races if not playing with expansion
2444 if (sWorld.getConfig(CONFIG_EXPANSION) < 1 && (race == RACE_BLOODELF || race == RACE_DRAENEI))
2445 continue;
2447 // skip expansion classes if not playing with expansion
2448 if (sWorld.getConfig(CONFIG_EXPANSION) < 2 && class_ == CLASS_DEATH_KNIGHT)
2449 continue;
2451 // fatal error if no level 1 data
2452 if(!pInfo->levelInfo || pInfo->levelInfo[0].stats[0] == 0 )
2454 sLog.outErrorDb("Race %i Class %i Level 1 does not have stats data!",race,class_);
2455 exit(1);
2458 // fill level gaps
2459 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2461 if(pInfo->levelInfo[level].stats[0] == 0)
2463 sLog.outErrorDb("Race %i Class %i Level %i does not have stats data. Using stats data of level %i.",race,class_,level+1, level);
2464 pInfo->levelInfo[level] = pInfo->levelInfo[level-1];
2471 void ObjectMgr::GetPlayerClassLevelInfo(uint32 class_, uint32 level, PlayerClassLevelInfo* info) const
2473 if(level < 1 || class_ >= MAX_CLASSES)
2474 return;
2476 PlayerClassInfo const* pInfo = &playerClassInfo[class_];
2478 if(level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2479 level = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL);
2481 *info = pInfo->levelInfo[level-1];
2484 void ObjectMgr::GetPlayerLevelInfo(uint32 race, uint32 class_, uint32 level, PlayerLevelInfo* info) const
2486 if(level < 1 || race >= MAX_RACES || class_ >= MAX_CLASSES)
2487 return;
2489 PlayerInfo const* pInfo = &playerInfo[race][class_];
2490 if(pInfo->displayId_m==0 || pInfo->displayId_f==0)
2491 return;
2493 if(level <= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2494 *info = pInfo->levelInfo[level-1];
2495 else
2496 BuildPlayerLevelInfo(race,class_,level,info);
2499 void ObjectMgr::BuildPlayerLevelInfo(uint8 race, uint8 _class, uint8 level, PlayerLevelInfo* info) const
2501 // base data (last known level)
2502 *info = playerInfo[race][_class].levelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)-1];
2504 for(int lvl = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)-1; lvl < level; ++lvl)
2506 switch(_class)
2508 case CLASS_WARRIOR:
2509 info->stats[STAT_STRENGTH] += (lvl > 23 ? 2: (lvl > 1 ? 1: 0));
2510 info->stats[STAT_STAMINA] += (lvl > 23 ? 2: (lvl > 1 ? 1: 0));
2511 info->stats[STAT_AGILITY] += (lvl > 36 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2512 info->stats[STAT_INTELLECT] += (lvl > 9 && !(lvl%2) ? 1: 0);
2513 info->stats[STAT_SPIRIT] += (lvl > 9 && !(lvl%2) ? 1: 0);
2514 break;
2515 case CLASS_PALADIN:
2516 info->stats[STAT_STRENGTH] += (lvl > 3 ? 1: 0);
2517 info->stats[STAT_STAMINA] += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2518 info->stats[STAT_AGILITY] += (lvl > 38 ? 1: (lvl > 7 && !(lvl%2) ? 1: 0));
2519 info->stats[STAT_INTELLECT] += (lvl > 6 && (lvl%2) ? 1: 0);
2520 info->stats[STAT_SPIRIT] += (lvl > 7 ? 1: 0);
2521 break;
2522 case CLASS_HUNTER:
2523 info->stats[STAT_STRENGTH] += (lvl > 4 ? 1: 0);
2524 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2525 info->stats[STAT_AGILITY] += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2526 info->stats[STAT_INTELLECT] += (lvl > 8 && (lvl%2) ? 1: 0);
2527 info->stats[STAT_SPIRIT] += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2528 break;
2529 case CLASS_ROGUE:
2530 info->stats[STAT_STRENGTH] += (lvl > 5 ? 1: 0);
2531 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2532 info->stats[STAT_AGILITY] += (lvl > 16 ? 2: (lvl > 1 ? 1: 0));
2533 info->stats[STAT_INTELLECT] += (lvl > 8 && !(lvl%2) ? 1: 0);
2534 info->stats[STAT_SPIRIT] += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2535 break;
2536 case CLASS_PRIEST:
2537 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2538 info->stats[STAT_STAMINA] += (lvl > 5 ? 1: 0);
2539 info->stats[STAT_AGILITY] += (lvl > 38 ? 1: (lvl > 8 && (lvl%2) ? 1: 0));
2540 info->stats[STAT_INTELLECT] += (lvl > 22 ? 2: (lvl > 1 ? 1: 0));
2541 info->stats[STAT_SPIRIT] += (lvl > 3 ? 1: 0);
2542 break;
2543 case CLASS_SHAMAN:
2544 info->stats[STAT_STRENGTH] += (lvl > 34 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2545 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2546 info->stats[STAT_AGILITY] += (lvl > 7 && !(lvl%2) ? 1: 0);
2547 info->stats[STAT_INTELLECT] += (lvl > 5 ? 1: 0);
2548 info->stats[STAT_SPIRIT] += (lvl > 4 ? 1: 0);
2549 break;
2550 case CLASS_MAGE:
2551 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2552 info->stats[STAT_STAMINA] += (lvl > 5 ? 1: 0);
2553 info->stats[STAT_AGILITY] += (lvl > 9 && !(lvl%2) ? 1: 0);
2554 info->stats[STAT_INTELLECT] += (lvl > 24 ? 2: (lvl > 1 ? 1: 0));
2555 info->stats[STAT_SPIRIT] += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
2556 break;
2557 case CLASS_WARLOCK:
2558 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2559 info->stats[STAT_STAMINA] += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
2560 info->stats[STAT_AGILITY] += (lvl > 9 && !(lvl%2) ? 1: 0);
2561 info->stats[STAT_INTELLECT] += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
2562 info->stats[STAT_SPIRIT] += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
2563 break;
2564 case CLASS_DRUID:
2565 info->stats[STAT_STRENGTH] += (lvl > 38 ? 2: (lvl > 6 && (lvl%2) ? 1: 0));
2566 info->stats[STAT_STAMINA] += (lvl > 32 ? 2: (lvl > 4 ? 1: 0));
2567 info->stats[STAT_AGILITY] += (lvl > 38 ? 2: (lvl > 8 && (lvl%2) ? 1: 0));
2568 info->stats[STAT_INTELLECT] += (lvl > 38 ? 3: (lvl > 4 ? 1: 0));
2569 info->stats[STAT_SPIRIT] += (lvl > 38 ? 3: (lvl > 5 ? 1: 0));
2574 void ObjectMgr::LoadGuilds()
2576 Guild *newguild;
2577 uint32 count = 0;
2579 QueryResult *result = CharacterDatabase.Query( "SELECT guildid FROM guild" );
2581 if( !result )
2584 barGoLink bar( 1 );
2586 bar.step();
2588 sLog.outString();
2589 sLog.outString( ">> Loaded %u guild definitions", count );
2590 return;
2593 barGoLink bar( result->GetRowCount() );
2597 Field *fields = result->Fetch();
2599 bar.step();
2600 ++count;
2602 newguild = new Guild;
2603 if(!newguild->LoadGuildFromDB(fields[0].GetUInt32()))
2605 newguild->Disband();
2606 delete newguild;
2607 continue;
2609 AddGuild(newguild);
2611 }while( result->NextRow() );
2613 delete result;
2615 sLog.outString();
2616 sLog.outString( ">> Loaded %u guild definitions", count );
2619 void ObjectMgr::LoadArenaTeams()
2621 uint32 count = 0;
2623 QueryResult *result = CharacterDatabase.Query( "SELECT arenateamid FROM arena_team" );
2625 if( !result )
2628 barGoLink bar( 1 );
2630 bar.step();
2632 sLog.outString();
2633 sLog.outString( ">> Loaded %u arenateam definitions", count );
2634 return;
2637 barGoLink bar( result->GetRowCount() );
2641 Field *fields = result->Fetch();
2643 bar.step();
2644 ++count;
2646 ArenaTeam *newarenateam = new ArenaTeam;
2647 if(!newarenateam->LoadArenaTeamFromDB(fields[0].GetUInt32()))
2649 delete newarenateam;
2650 continue;
2652 AddArenaTeam(newarenateam);
2653 }while( result->NextRow() );
2655 delete result;
2657 sLog.outString();
2658 sLog.outString( ">> Loaded %u arenateam definitions", count );
2661 void ObjectMgr::LoadGroups()
2663 // -- loading groups --
2664 Group *group = NULL;
2665 uint64 leaderGuid = 0;
2666 uint32 count = 0;
2667 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
2668 QueryResult *result = CharacterDatabase.Query("SELECT mainTank, mainAssistant, lootMethod, looterGuid, lootThreshold, icon1, icon2, icon3, icon4, icon5, icon6, icon7, icon8, isRaid, difficulty, leaderGuid FROM groups");
2670 if( !result )
2672 barGoLink bar( 1 );
2674 bar.step();
2676 sLog.outString();
2677 sLog.outString( ">> Loaded %u group definitions", count );
2678 return;
2681 barGoLink bar( result->GetRowCount() );
2685 bar.step();
2686 Field *fields = result->Fetch();
2687 ++count;
2688 leaderGuid = MAKE_NEW_GUID(fields[15].GetUInt32(),0,HIGHGUID_PLAYER);
2690 group = new Group;
2691 if(!group->LoadGroupFromDB(leaderGuid, result, false))
2693 group->Disband();
2694 delete group;
2695 continue;
2697 AddGroup(group);
2698 }while( result->NextRow() );
2700 delete result;
2702 sLog.outString();
2703 sLog.outString( ">> Loaded %u group definitions", count );
2705 // -- loading members --
2706 count = 0;
2707 group = NULL;
2708 leaderGuid = 0;
2709 // 0 1 2 3
2710 result = CharacterDatabase.Query("SELECT memberGuid, assistant, subgroup, leaderGuid FROM group_member ORDER BY leaderGuid");
2711 if(!result)
2713 barGoLink bar( 1 );
2714 bar.step();
2716 else
2718 barGoLink bar( result->GetRowCount() );
2721 bar.step();
2722 Field *fields = result->Fetch();
2723 count++;
2724 leaderGuid = MAKE_NEW_GUID(fields[3].GetUInt32(), 0, HIGHGUID_PLAYER);
2725 if(!group || group->GetLeaderGUID() != leaderGuid)
2727 group = GetGroupByLeader(leaderGuid);
2728 if(!group)
2730 sLog.outErrorDb("Incorrect entry in group_member table : no group with leader %d for member %d!", fields[3].GetUInt32(), fields[0].GetUInt32());
2731 CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", fields[0].GetUInt32());
2732 continue;
2736 if(!group->LoadMemberFromDB(fields[0].GetUInt32(), fields[2].GetUInt8(), fields[1].GetBool()))
2738 sLog.outErrorDb("Incorrect entry in group_member table : member %d cannot be added to player %d's group!", fields[0].GetUInt32(), fields[3].GetUInt32());
2739 CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", fields[0].GetUInt32());
2741 }while( result->NextRow() );
2742 delete result;
2745 // clean groups
2746 // TODO: maybe delete from the DB before loading in this case
2747 for(GroupSet::iterator itr = mGroupSet.begin(); itr != mGroupSet.end();)
2749 if((*itr)->GetMembersCount() < 2)
2751 (*itr)->Disband();
2752 delete *itr;
2753 mGroupSet.erase(itr++);
2755 else
2756 ++itr;
2759 // -- loading instances --
2760 count = 0;
2761 group = NULL;
2762 leaderGuid = 0;
2763 result = CharacterDatabase.Query(
2764 // 0 1 2 3 4 5
2765 "SELECT leaderGuid, map, instance, permanent, difficulty, resettime, "
2766 // 6
2767 "(SELECT COUNT(*) FROM character_instance WHERE guid = leaderGuid AND instance = group_instance.instance AND permanent = 1 LIMIT 1) "
2768 "FROM group_instance LEFT JOIN instance ON instance = id ORDER BY leaderGuid"
2771 if(!result)
2773 barGoLink bar( 1 );
2774 bar.step();
2776 else
2778 barGoLink bar( result->GetRowCount() );
2781 bar.step();
2782 Field *fields = result->Fetch();
2783 count++;
2784 leaderGuid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
2785 if(!group || group->GetLeaderGUID() != leaderGuid)
2787 group = GetGroupByLeader(leaderGuid);
2788 if(!group)
2790 sLog.outErrorDb("Incorrect entry in group_instance table : no group with leader %d", fields[0].GetUInt32());
2791 continue;
2795 InstanceSave *save = sInstanceSaveManager.AddInstanceSave(fields[1].GetUInt32(), fields[2].GetUInt32(), fields[4].GetUInt8(), (time_t)fields[5].GetUInt64(), (fields[6].GetUInt32() == 0), true);
2796 group->BindToInstance(save, fields[3].GetBool(), true);
2797 }while( result->NextRow() );
2798 delete result;
2801 sLog.outString();
2802 sLog.outString( ">> Loaded %u group-instance binds total", count );
2804 sLog.outString();
2805 sLog.outString( ">> Loaded %u group members total", count );
2808 void ObjectMgr::LoadQuests()
2810 // For reload case
2811 for(QuestMap::const_iterator itr=mQuestTemplates.begin(); itr != mQuestTemplates.end(); ++itr)
2812 delete itr->second;
2813 mQuestTemplates.clear();
2815 mExclusiveQuestGroups.clear();
2817 // 0 1 2 3 4 5 6 7 8
2818 QueryResult *result = WorldDatabase.Query("SELECT entry, Method, ZoneOrSort, SkillOrClass, MinLevel, QuestLevel, Type, RequiredRaces, RequiredSkillValue,"
2819 // 9 10 11 12 13 14 15 16
2820 "RepObjectiveFaction, RepObjectiveValue, RequiredMinRepFaction, RequiredMinRepValue, RequiredMaxRepFaction, RequiredMaxRepValue, SuggestedPlayers, LimitTime,"
2821 // 17 18 19 20 21 22 23 24 25 26
2822 "QuestFlags, SpecialFlags, CharTitleId, PrevQuestId, NextQuestId, ExclusiveGroup, NextQuestInChain, SrcItemId, SrcItemCount, SrcSpell,"
2823 // 27 28 29 30 31 32 33 34 35 36
2824 "Title, Details, Objectives, OfferRewardText, RequestItemsText, EndText, ObjectiveText1, ObjectiveText2, ObjectiveText3, ObjectiveText4,"
2825 // 37 38 39 40 41 42 43 44
2826 "ReqItemId1, ReqItemId2, ReqItemId3, ReqItemId4, ReqItemCount1, ReqItemCount2, ReqItemCount3, ReqItemCount4,"
2827 // 45 46 47 48 49 50 51 52 53 54 54 55
2828 "ReqSourceId1, ReqSourceId2, ReqSourceId3, ReqSourceId4, ReqSourceCount1, ReqSourceCount2, ReqSourceCount3, ReqSourceCount4, ReqSourceRef1, ReqSourceRef2, ReqSourceRef3, ReqSourceRef4,"
2829 // 57 58 59 60 61 62 63 64
2830 "ReqCreatureOrGOId1, ReqCreatureOrGOId2, ReqCreatureOrGOId3, ReqCreatureOrGOId4, ReqCreatureOrGOCount1, ReqCreatureOrGOCount2, ReqCreatureOrGOCount3, ReqCreatureOrGOCount4,"
2831 // 65 66 67 68
2832 "ReqSpellCast1, ReqSpellCast2, ReqSpellCast3, ReqSpellCast4,"
2833 // 69 70 71 72 73 74
2834 "RewChoiceItemId1, RewChoiceItemId2, RewChoiceItemId3, RewChoiceItemId4, RewChoiceItemId5, RewChoiceItemId6,"
2835 // 75 76 77 78 79 80
2836 "RewChoiceItemCount1, RewChoiceItemCount2, RewChoiceItemCount3, RewChoiceItemCount4, RewChoiceItemCount5, RewChoiceItemCount6,"
2837 // 81 82 83 84 85 86 87 88
2838 "RewItemId1, RewItemId2, RewItemId3, RewItemId4, RewItemCount1, RewItemCount2, RewItemCount3, RewItemCount4,"
2839 // 89 90 91 92 93 94 95 96 97 98
2840 "RewRepFaction1, RewRepFaction2, RewRepFaction3, RewRepFaction4, RewRepFaction5, RewRepValue1, RewRepValue2, RewRepValue3, RewRepValue4, RewRepValue5,"
2841 // 99 100 101 102 103 104 105 106 107 108 109
2842 "RewHonorableKills, RewOrReqMoney, RewMoneyMaxLevel, RewSpell, RewSpellCast, RewMailTemplateId, RewMailDelaySecs, PointMapId, PointX, PointY, PointOpt,"
2843 // 110 111 112 113 114 115 116 117 118 119
2844 "DetailsEmote1, DetailsEmote2, DetailsEmote3, DetailsEmote4,IncompleteEmote, CompleteEmote, OfferRewardEmote1, OfferRewardEmote2, OfferRewardEmote3, OfferRewardEmote4,"
2845 // 120 121
2846 "StartScript, CompleteScript"
2847 " FROM quest_template");
2848 if(result == NULL)
2850 barGoLink bar( 1 );
2851 bar.step();
2853 sLog.outString();
2854 sLog.outString( ">> Loaded 0 quests definitions" );
2855 sLog.outErrorDb("`quest_template` table is empty!");
2856 return;
2859 // create multimap previous quest for each existed quest
2860 // some quests can have many previous maps set by NextQuestId in previous quest
2861 // for example set of race quests can lead to single not race specific quest
2862 barGoLink bar( result->GetRowCount() );
2865 bar.step();
2866 Field *fields = result->Fetch();
2868 Quest * newQuest = new Quest(fields);
2869 mQuestTemplates[newQuest->GetQuestId()] = newQuest;
2870 } while( result->NextRow() );
2872 delete result;
2874 // Post processing
2875 for (QuestMap::iterator iter = mQuestTemplates.begin(); iter != mQuestTemplates.end(); ++iter)
2877 Quest * qinfo = iter->second;
2879 // additional quest integrity checks (GO, creature_template and item_template must be loaded already)
2881 if( qinfo->GetQuestMethod() >= 3 )
2883 sLog.outErrorDb("Quest %u has `Method` = %u, expected values are 0, 1 or 2.",qinfo->GetQuestId(),qinfo->GetQuestMethod());
2886 if (qinfo->QuestFlags & ~QUEST_MANGOS_FLAGS_DB_ALLOWED)
2888 sLog.outErrorDb("Quest %u has `SpecialFlags` = %u > max allowed value. Correct `SpecialFlags` to value <= %u",
2889 qinfo->GetQuestId(),qinfo->QuestFlags,QUEST_MANGOS_FLAGS_DB_ALLOWED >> 16);
2890 qinfo->QuestFlags &= QUEST_MANGOS_FLAGS_DB_ALLOWED;
2893 if(qinfo->QuestFlags & QUEST_FLAGS_DAILY)
2895 if(!(qinfo->QuestFlags & QUEST_MANGOS_FLAGS_REPEATABLE))
2897 sLog.outErrorDb("Daily Quest %u not marked as repeatable in `SpecialFlags`, added.",qinfo->GetQuestId());
2898 qinfo->QuestFlags |= QUEST_MANGOS_FLAGS_REPEATABLE;
2902 if(qinfo->QuestFlags & QUEST_FLAGS_AUTO_REWARDED)
2904 // at auto-reward can be rewarded only RewChoiceItemId[0]
2905 for(int j = 1; j < QUEST_REWARD_CHOICES_COUNT; ++j )
2907 if(uint32 id = qinfo->RewChoiceItemId[j])
2909 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item from `RewChoiceItemId%d` can't be rewarded with quest flag QUEST_FLAGS_AUTO_REWARDED.",
2910 qinfo->GetQuestId(),j+1,id,j+1);
2911 // no changes, quest ignore this data
2916 // client quest log visual (area case)
2917 if( qinfo->ZoneOrSort > 0 )
2919 if(!GetAreaEntryByAreaID(qinfo->ZoneOrSort))
2921 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %u (zone case) but zone with this id does not exist.",
2922 qinfo->GetQuestId(),qinfo->ZoneOrSort);
2923 // no changes, quest not dependent from this value but can have problems at client
2926 // client quest log visual (sort case)
2927 if( qinfo->ZoneOrSort < 0 )
2929 QuestSortEntry const* qSort = sQuestSortStore.LookupEntry(-int32(qinfo->ZoneOrSort));
2930 if( !qSort )
2932 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (sort case) but quest sort with this id does not exist.",
2933 qinfo->GetQuestId(),qinfo->ZoneOrSort);
2934 // 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)
2936 //check SkillOrClass value (class case).
2937 if( ClassByQuestSort(-int32(qinfo->ZoneOrSort)) )
2939 // SkillOrClass should not have class case when class case already set in ZoneOrSort.
2940 if(qinfo->SkillOrClass < 0)
2942 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (class sort case) and `SkillOrClass` = %i (class case), redundant.",
2943 qinfo->GetQuestId(),qinfo->ZoneOrSort,qinfo->SkillOrClass);
2946 //check for proper SkillOrClass value (skill case)
2947 if(int32 skill_id = SkillByQuestSort(-int32(qinfo->ZoneOrSort)))
2949 // skill is positive value in SkillOrClass
2950 if(qinfo->SkillOrClass != skill_id )
2952 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (skill sort case) but `SkillOrClass` does not have a corresponding value (%i).",
2953 qinfo->GetQuestId(),qinfo->ZoneOrSort,skill_id);
2954 //override, and force proper value here?
2959 // SkillOrClass (class case)
2960 if( qinfo->SkillOrClass < 0 )
2962 if( !sChrClassesStore.LookupEntry(-int32(qinfo->SkillOrClass)) )
2964 sLog.outErrorDb("Quest %u has `SkillOrClass` = %i (class case) but class (%i) does not exist",
2965 qinfo->GetQuestId(),qinfo->SkillOrClass,-qinfo->SkillOrClass);
2968 // SkillOrClass (skill case)
2969 if( qinfo->SkillOrClass > 0 )
2971 if( !sSkillLineStore.LookupEntry(qinfo->SkillOrClass) )
2973 sLog.outErrorDb("Quest %u has `SkillOrClass` = %u (skill case) but skill (%i) does not exist",
2974 qinfo->GetQuestId(),qinfo->SkillOrClass,qinfo->SkillOrClass);
2978 if( qinfo->RequiredSkillValue )
2980 if( qinfo->RequiredSkillValue > sWorld.GetConfigMaxSkillValue() )
2982 sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but max possible skill is %u, quest can't be done.",
2983 qinfo->GetQuestId(),qinfo->RequiredSkillValue,sWorld.GetConfigMaxSkillValue());
2984 // no changes, quest can't be done for this requirement
2987 if( qinfo->SkillOrClass <= 0 )
2989 sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but `SkillOrClass` = %i (class case), value ignored.",
2990 qinfo->GetQuestId(),qinfo->RequiredSkillValue,qinfo->SkillOrClass);
2991 // no changes, quest can't be done for this requirement (fail at wrong skill id)
2994 // else Skill quests can have 0 skill level, this is ok
2996 if(qinfo->RepObjectiveFaction && !sFactionStore.LookupEntry(qinfo->RepObjectiveFaction))
2998 sLog.outErrorDb("Quest %u has `RepObjectiveFaction` = %u but faction template %u does not exist, quest can't be done.",
2999 qinfo->GetQuestId(),qinfo->RepObjectiveFaction,qinfo->RepObjectiveFaction);
3000 // no changes, quest can't be done for this requirement
3003 if(qinfo->RequiredMinRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMinRepFaction))
3005 sLog.outErrorDb("Quest %u has `RequiredMinRepFaction` = %u but faction template %u does not exist, quest can't be done.",
3006 qinfo->GetQuestId(),qinfo->RequiredMinRepFaction,qinfo->RequiredMinRepFaction);
3007 // no changes, quest can't be done for this requirement
3010 if(qinfo->RequiredMaxRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMaxRepFaction))
3012 sLog.outErrorDb("Quest %u has `RequiredMaxRepFaction` = %u but faction template %u does not exist, quest can't be done.",
3013 qinfo->GetQuestId(),qinfo->RequiredMaxRepFaction,qinfo->RequiredMaxRepFaction);
3014 // no changes, quest can't be done for this requirement
3017 if(qinfo->RequiredMinRepValue && qinfo->RequiredMinRepValue > Player::Reputation_Cap)
3019 sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but max reputation is %u, quest can't be done.",
3020 qinfo->GetQuestId(),qinfo->RequiredMinRepValue,Player::Reputation_Cap);
3021 // no changes, quest can't be done for this requirement
3024 if(qinfo->RequiredMinRepValue && qinfo->RequiredMaxRepValue && qinfo->RequiredMaxRepValue <= qinfo->RequiredMinRepValue)
3026 sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d and `RequiredMinRepValue` = %d, quest can't be done.",
3027 qinfo->GetQuestId(),qinfo->RequiredMaxRepValue,qinfo->RequiredMinRepValue);
3028 // no changes, quest can't be done for this requirement
3031 if(!qinfo->RepObjectiveFaction && qinfo->RepObjectiveValue > 0 )
3033 sLog.outErrorDb("Quest %u has `RepObjectiveValue` = %d but `RepObjectiveFaction` is 0, value has no effect",
3034 qinfo->GetQuestId(),qinfo->RepObjectiveValue);
3035 // warning
3038 if(!qinfo->RequiredMinRepFaction && qinfo->RequiredMinRepValue > 0 )
3040 sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but `RequiredMinRepFaction` is 0, value has no effect",
3041 qinfo->GetQuestId(),qinfo->RequiredMinRepValue);
3042 // warning
3045 if(!qinfo->RequiredMaxRepFaction && qinfo->RequiredMaxRepValue > 0 )
3047 sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d but `RequiredMaxRepFaction` is 0, value has no effect",
3048 qinfo->GetQuestId(),qinfo->RequiredMaxRepValue);
3049 // warning
3052 if(qinfo->CharTitleId && !sCharTitlesStore.LookupEntry(qinfo->CharTitleId))
3054 sLog.outErrorDb("Quest %u has `CharTitleId` = %u but CharTitle Id %u does not exist, quest can't be rewarded with title.",
3055 qinfo->GetQuestId(),qinfo->GetCharTitleId(),qinfo->GetCharTitleId());
3056 qinfo->CharTitleId = 0;
3057 // quest can't reward this title
3060 if(qinfo->SrcItemId)
3062 if(!sItemStorage.LookupEntry<ItemPrototype>(qinfo->SrcItemId))
3064 sLog.outErrorDb("Quest %u has `SrcItemId` = %u but item with entry %u does not exist, quest can't be done.",
3065 qinfo->GetQuestId(),qinfo->SrcItemId,qinfo->SrcItemId);
3066 qinfo->SrcItemId = 0; // quest can't be done for this requirement
3068 else if(qinfo->SrcItemCount==0)
3070 sLog.outErrorDb("Quest %u has `SrcItemId` = %u but `SrcItemCount` = 0, set to 1 but need fix in DB.",
3071 qinfo->GetQuestId(),qinfo->SrcItemId);
3072 qinfo->SrcItemCount = 1; // update to 1 for allow quest work for backward compatibility with DB
3075 else if(qinfo->SrcItemCount>0)
3077 sLog.outErrorDb("Quest %u has `SrcItemId` = 0 but `SrcItemCount` = %u, useless value.",
3078 qinfo->GetQuestId(),qinfo->SrcItemCount);
3079 qinfo->SrcItemCount=0; // no quest work changes in fact
3082 if(qinfo->SrcSpell)
3084 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->SrcSpell);
3085 if(!spellInfo)
3087 sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u doesn't exist, quest can't be done.",
3088 qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
3089 qinfo->SrcSpell = 0; // quest can't be done for this requirement
3091 else if(!SpellMgr::IsSpellValid(spellInfo))
3093 sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u is broken, quest can't be done.",
3094 qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
3095 qinfo->SrcSpell = 0; // quest can't be done for this requirement
3099 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3101 uint32 id = qinfo->ReqItemId[j];
3102 if(id)
3104 if(qinfo->ReqItemCount[j]==0)
3106 sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but `ReqItemCount%d` = 0, quest can't be done.",
3107 qinfo->GetQuestId(),j+1,id,j+1);
3108 // no changes, quest can't be done for this requirement
3111 qinfo->SetFlag(QUEST_MANGOS_FLAGS_DELIVER);
3113 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3115 sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but item with entry %u does not exist, quest can't be done.",
3116 qinfo->GetQuestId(),j+1,id,id);
3117 qinfo->ReqItemCount[j] = 0; // prevent incorrect work of quest
3120 else if(qinfo->ReqItemCount[j]>0)
3122 sLog.outErrorDb("Quest %u has `ReqItemId%d` = 0 but `ReqItemCount%d` = %u, quest can't be done.",
3123 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqItemCount[j]);
3124 qinfo->ReqItemCount[j] = 0; // prevent incorrect work of quest
3128 for(int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j )
3130 uint32 id = qinfo->ReqSourceId[j];
3131 if(id)
3133 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3135 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but item with entry %u does not exist, quest can't be done.",
3136 qinfo->GetQuestId(),j+1,id,id);
3137 // no changes, quest can't be done for this requirement
3140 if(!qinfo->ReqSourceCount[j])
3142 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but `ReqSourceCount%d` = 0, quest can't be done.",
3143 qinfo->GetQuestId(),j+1,id,j+1);
3144 qinfo->ReqSourceId[j] = 0; // prevent incorrect work of quest
3147 if(!qinfo->ReqSourceRef[j])
3149 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but `ReqSourceRef%d` = 0, quest can't be done.",
3150 qinfo->GetQuestId(),j+1,id,j+1);
3151 qinfo->ReqSourceId[j] = 0; // prevent incorrect work of quest
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
3163 if(qinfo->ReqSourceRef[j]>0)
3165 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = 0 but `ReqSourceRef%d` = %u.",
3166 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqSourceRef[j]);
3167 // no changes, quest ignore this data
3172 for(int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j )
3174 uint32 ref = qinfo->ReqSourceRef[j];
3175 if(ref)
3177 if(ref > QUEST_OBJECTIVES_COUNT)
3179 sLog.outErrorDb("Quest %u has `ReqSourceRef%d` = %u but max value in `ReqSourceRef%d` is %u, quest can't be done.",
3180 qinfo->GetQuestId(),j+1,ref,j+1,QUEST_OBJECTIVES_COUNT);
3181 // no changes, quest can't be done for this requirement
3183 else
3184 if(!qinfo->ReqItemId[ref-1] && !qinfo->ReqSpell[ref-1])
3186 sLog.outErrorDb("Quest %u has `ReqSourceRef%d` = %u but `ReqItemId%u` = 0 and `ReqSpellCast%u` = 0, quest can't be done.",
3187 qinfo->GetQuestId(),j+1,ref,ref,ref);
3188 // no changes, quest can't be done for this requirement
3190 else if(qinfo->ReqItemId[ref-1] && qinfo->ReqSpell[ref-1])
3192 sLog.outErrorDb("Quest %u has `ReqItemId%u` = %u and `ReqSpellCast%u` = %u, quest can't have both fields <> 0, then can't be done.",
3193 qinfo->GetQuestId(),ref,qinfo->ReqItemId[ref-1],ref,qinfo->ReqSpell[ref-1]);
3194 // no changes, quest can't be done for this requirement
3195 qinfo->ReqSourceId[j] = 0; // prevent incorrect work of quest
3200 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3202 uint32 id = qinfo->ReqSpell[j];
3203 if(id)
3205 SpellEntry const* spellInfo = sSpellStore.LookupEntry(id);
3206 if(!spellInfo)
3208 sLog.outErrorDb("Quest %u has `ReqSpellCast%d` = %u but spell %u does not exist, quest can't be done.",
3209 qinfo->GetQuestId(),j+1,id,id);
3210 // no changes, quest can't be done for this requirement
3213 if(!qinfo->ReqCreatureOrGOId[j])
3215 bool found = false;
3216 for(int k = 0; k < 3; ++k)
3218 if( spellInfo->Effect[k]==SPELL_EFFECT_QUEST_COMPLETE && uint32(spellInfo->EffectMiscValue[k])==qinfo->QuestId ||
3219 spellInfo->Effect[k]==SPELL_EFFECT_SEND_EVENT)
3221 found = true;
3222 break;
3226 if(found)
3228 if(!qinfo->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3230 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);
3232 // this will prevent quest completing without objective
3233 const_cast<Quest*>(qinfo)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3236 else
3238 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.",
3239 qinfo->GetQuestId(),j+1,id,j+1,id);
3240 // no changes, quest can't be done for this requirement
3246 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3248 int32 id = qinfo->ReqCreatureOrGOId[j];
3249 if(id < 0 && !sGOStorage.LookupEntry<GameObjectInfo>(-id))
3251 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but gameobject %u does not exist, quest can't be done.",
3252 qinfo->GetQuestId(),j+1,id,uint32(-id));
3253 qinfo->ReqCreatureOrGOId[j] = 0; // quest can't be done for this requirement
3256 if(id > 0 && !sCreatureStorage.LookupEntry<CreatureInfo>(id))
3258 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but creature with entry %u does not exist, quest can't be done.",
3259 qinfo->GetQuestId(),j+1,id,uint32(id));
3260 qinfo->ReqCreatureOrGOId[j] = 0; // quest can't be done for this requirement
3263 if(id)
3265 // In fact SpeakTo and Kill are quite same: either you can speak to mob:SpeakTo or you can't:Kill/Cast
3267 qinfo->SetFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO);
3269 if(!qinfo->ReqCreatureOrGOCount[j])
3271 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %u but `ReqCreatureOrGOCount%d` = 0, quest can't be done.",
3272 qinfo->GetQuestId(),j+1,id,j+1);
3273 // no changes, quest can be incorrectly done, but we already report this
3276 else if(qinfo->ReqCreatureOrGOCount[j]>0)
3278 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = 0 but `ReqCreatureOrGOCount%d` = %u.",
3279 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqCreatureOrGOCount[j]);
3280 // no changes, quest ignore this data
3284 for(int j = 0; j < QUEST_REWARD_CHOICES_COUNT; ++j )
3286 uint32 id = qinfo->RewChoiceItemId[j];
3287 if(id)
3289 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3291 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3292 qinfo->GetQuestId(),j+1,id,id);
3293 qinfo->RewChoiceItemId[j] = 0; // no changes, quest will not reward this
3296 if(!qinfo->RewChoiceItemCount[j])
3298 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but `RewChoiceItemCount%d` = 0, quest can't be done.",
3299 qinfo->GetQuestId(),j+1,id,j+1);
3300 // no changes, quest can't be done
3303 else if(qinfo->RewChoiceItemCount[j]>0)
3305 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = 0 but `RewChoiceItemCount%d` = %u.",
3306 qinfo->GetQuestId(),j+1,j+1,qinfo->RewChoiceItemCount[j]);
3307 // no changes, quest ignore this data
3311 for(int j = 0; j < QUEST_REWARDS_COUNT; ++j )
3313 uint32 id = qinfo->RewItemId[j];
3314 if(id)
3316 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3318 sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3319 qinfo->GetQuestId(),j+1,id,id);
3320 qinfo->RewItemId[j] = 0; // no changes, quest will not reward this item
3323 if(!qinfo->RewItemCount[j])
3325 sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but `RewItemCount%d` = 0, quest will not reward this item.",
3326 qinfo->GetQuestId(),j+1,id,j+1);
3327 // no changes
3330 else if(qinfo->RewItemCount[j]>0)
3332 sLog.outErrorDb("Quest %u has `RewItemId%d` = 0 but `RewItemCount%d` = %u.",
3333 qinfo->GetQuestId(),j+1,j+1,qinfo->RewItemCount[j]);
3334 // no changes, quest ignore this data
3338 for(int j = 0; j < QUEST_REPUTATIONS_COUNT; ++j)
3340 if(qinfo->RewRepFaction[j])
3342 if(!qinfo->RewRepValue[j])
3344 sLog.outErrorDb("Quest %u has `RewRepFaction%d` = %u but `RewRepValue%d` = 0, quest will not reward this reputation.",
3345 qinfo->GetQuestId(),j+1,qinfo->RewRepValue[j],j+1);
3346 // no changes
3349 if(!sFactionStore.LookupEntry(qinfo->RewRepFaction[j]))
3351 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.",
3352 qinfo->GetQuestId(),j+1,qinfo->RewRepFaction[j] ,qinfo->RewRepFaction[j] );
3353 qinfo->RewRepFaction[j] = 0; // quest will not reward this
3356 else if(qinfo->RewRepValue[j]!=0)
3358 sLog.outErrorDb("Quest %u has `RewRepFaction%d` = 0 but `RewRepValue%d` = %u.",
3359 qinfo->GetQuestId(),j+1,j+1,qinfo->RewRepValue[j]);
3360 // no changes, quest ignore this data
3364 if(qinfo->RewSpell)
3366 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpell);
3368 if(!spellInfo)
3370 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u does not exist, spell removed as display reward.",
3371 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3372 qinfo->RewSpell = 0; // no spell reward will display for this quest
3375 else if(!SpellMgr::IsSpellValid(spellInfo))
3377 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u is broken, quest can't be done.",
3378 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3379 qinfo->RewSpell = 0; // no spell reward will display for this quest
3384 if(qinfo->RewSpellCast)
3386 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpellCast);
3388 if(!spellInfo)
3390 sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u does not exist, quest will not have a spell reward.",
3391 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3392 qinfo->RewSpellCast = 0; // no spell will be casted on player
3395 else if(!SpellMgr::IsSpellValid(spellInfo))
3397 sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u is broken, quest can't be done.",
3398 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3399 qinfo->RewSpellCast = 0; // no spell will be casted on player
3404 if(qinfo->RewMailTemplateId)
3406 if(!sMailTemplateStore.LookupEntry(qinfo->RewMailTemplateId))
3408 sLog.outErrorDb("Quest %u has `RewMailTemplateId` = %u but mail template %u does not exist, quest will not have a mail reward.",
3409 qinfo->GetQuestId(),qinfo->RewMailTemplateId,qinfo->RewMailTemplateId);
3410 qinfo->RewMailTemplateId = 0; // no mail will send to player
3411 qinfo->RewMailDelaySecs = 0; // no mail will send to player
3415 if(qinfo->NextQuestInChain)
3417 if(mQuestTemplates.find(qinfo->NextQuestInChain) == mQuestTemplates.end())
3419 sLog.outErrorDb("Quest %u has `NextQuestInChain` = %u but quest %u does not exist, quest chain will not work.",
3420 qinfo->GetQuestId(),qinfo->NextQuestInChain ,qinfo->NextQuestInChain );
3421 qinfo->NextQuestInChain = 0;
3423 else
3424 mQuestTemplates[qinfo->NextQuestInChain]->prevChainQuests.push_back(qinfo->GetQuestId());
3427 // fill additional data stores
3428 if(qinfo->PrevQuestId)
3430 if (mQuestTemplates.find(abs(qinfo->GetPrevQuestId())) == mQuestTemplates.end())
3432 sLog.outErrorDb("Quest %d has PrevQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetPrevQuestId());
3434 else
3436 qinfo->prevQuests.push_back(qinfo->PrevQuestId);
3440 if(qinfo->NextQuestId)
3442 if (mQuestTemplates.find(abs(qinfo->GetNextQuestId())) == mQuestTemplates.end())
3444 sLog.outErrorDb("Quest %d has NextQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetNextQuestId());
3446 else
3448 int32 signedQuestId = qinfo->NextQuestId < 0 ? -int32(qinfo->GetQuestId()) : int32(qinfo->GetQuestId());
3449 mQuestTemplates[abs(qinfo->GetNextQuestId())]->prevQuests.push_back(signedQuestId);
3453 if(qinfo->ExclusiveGroup)
3454 mExclusiveQuestGroups.insert(std::pair<int32, uint32>(qinfo->ExclusiveGroup, qinfo->GetQuestId()));
3455 if(qinfo->LimitTime)
3456 qinfo->SetFlag(QUEST_MANGOS_FLAGS_TIMED);
3459 // check QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT for spell with SPELL_EFFECT_QUEST_COMPLETE
3460 for (uint32 i = 0; i < sSpellStore.GetNumRows(); ++i)
3462 SpellEntry const *spellInfo = sSpellStore.LookupEntry(i);
3463 if(!spellInfo)
3464 continue;
3466 for(int j = 0; j < 3; ++j)
3468 if(spellInfo->Effect[j] != SPELL_EFFECT_QUEST_COMPLETE)
3469 continue;
3471 uint32 quest_id = spellInfo->EffectMiscValue[j];
3473 Quest const* quest = GetQuestTemplate(quest_id);
3475 // some quest referenced in spells not exist (outdated spells)
3476 if(!quest)
3477 continue;
3479 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3481 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);
3483 // this will prevent quest completing without objective
3484 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3489 sLog.outString();
3490 sLog.outString( ">> Loaded %u quests definitions", mQuestTemplates.size() );
3493 void ObjectMgr::LoadQuestLocales()
3495 mQuestLocaleMap.clear(); // need for reload case
3497 QueryResult *result = WorldDatabase.Query("SELECT entry,"
3498 "Title_loc1,Details_loc1,Objectives_loc1,OfferRewardText_loc1,RequestItemsText_loc1,EndText_loc1,ObjectiveText1_loc1,ObjectiveText2_loc1,ObjectiveText3_loc1,ObjectiveText4_loc1,"
3499 "Title_loc2,Details_loc2,Objectives_loc2,OfferRewardText_loc2,RequestItemsText_loc2,EndText_loc2,ObjectiveText1_loc2,ObjectiveText2_loc2,ObjectiveText3_loc2,ObjectiveText4_loc2,"
3500 "Title_loc3,Details_loc3,Objectives_loc3,OfferRewardText_loc3,RequestItemsText_loc3,EndText_loc3,ObjectiveText1_loc3,ObjectiveText2_loc3,ObjectiveText3_loc3,ObjectiveText4_loc3,"
3501 "Title_loc4,Details_loc4,Objectives_loc4,OfferRewardText_loc4,RequestItemsText_loc4,EndText_loc4,ObjectiveText1_loc4,ObjectiveText2_loc4,ObjectiveText3_loc4,ObjectiveText4_loc4,"
3502 "Title_loc5,Details_loc5,Objectives_loc5,OfferRewardText_loc5,RequestItemsText_loc5,EndText_loc5,ObjectiveText1_loc5,ObjectiveText2_loc5,ObjectiveText3_loc5,ObjectiveText4_loc5,"
3503 "Title_loc6,Details_loc6,Objectives_loc6,OfferRewardText_loc6,RequestItemsText_loc6,EndText_loc6,ObjectiveText1_loc6,ObjectiveText2_loc6,ObjectiveText3_loc6,ObjectiveText4_loc6,"
3504 "Title_loc7,Details_loc7,Objectives_loc7,OfferRewardText_loc7,RequestItemsText_loc7,EndText_loc7,ObjectiveText1_loc7,ObjectiveText2_loc7,ObjectiveText3_loc7,ObjectiveText4_loc7,"
3505 "Title_loc8,Details_loc8,Objectives_loc8,OfferRewardText_loc8,RequestItemsText_loc8,EndText_loc8,ObjectiveText1_loc8,ObjectiveText2_loc8,ObjectiveText3_loc8,ObjectiveText4_loc8"
3506 " FROM locales_quest"
3509 if(!result)
3511 barGoLink bar(1);
3513 bar.step();
3515 sLog.outString("");
3516 sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_quest` is empty.");
3517 return;
3520 barGoLink bar(result->GetRowCount());
3524 Field *fields = result->Fetch();
3525 bar.step();
3527 uint32 entry = fields[0].GetUInt32();
3529 QuestLocale& data = mQuestLocaleMap[entry];
3531 for(int i = 1; i < MAX_LOCALE; ++i)
3533 std::string str = fields[1+10*(i-1)].GetCppString();
3534 if(!str.empty())
3536 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3537 if(idx >= 0)
3539 if(data.Title.size() <= idx)
3540 data.Title.resize(idx+1);
3542 data.Title[idx] = str;
3545 str = fields[1+10*(i-1)+1].GetCppString();
3546 if(!str.empty())
3548 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3549 if(idx >= 0)
3551 if(data.Details.size() <= idx)
3552 data.Details.resize(idx+1);
3554 data.Details[idx] = str;
3557 str = fields[1+10*(i-1)+2].GetCppString();
3558 if(!str.empty())
3560 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3561 if(idx >= 0)
3563 if(data.Objectives.size() <= idx)
3564 data.Objectives.resize(idx+1);
3566 data.Objectives[idx] = str;
3569 str = fields[1+10*(i-1)+3].GetCppString();
3570 if(!str.empty())
3572 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3573 if(idx >= 0)
3575 if(data.OfferRewardText.size() <= idx)
3576 data.OfferRewardText.resize(idx+1);
3578 data.OfferRewardText[idx] = str;
3581 str = fields[1+10*(i-1)+4].GetCppString();
3582 if(!str.empty())
3584 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3585 if(idx >= 0)
3587 if(data.RequestItemsText.size() <= idx)
3588 data.RequestItemsText.resize(idx+1);
3590 data.RequestItemsText[idx] = str;
3593 str = fields[1+10*(i-1)+5].GetCppString();
3594 if(!str.empty())
3596 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3597 if(idx >= 0)
3599 if(data.EndText.size() <= idx)
3600 data.EndText.resize(idx+1);
3602 data.EndText[idx] = str;
3605 for(int k = 0; k < 4; ++k)
3607 str = fields[1+10*(i-1)+6+k].GetCppString();
3608 if(!str.empty())
3610 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3611 if(idx >= 0)
3613 if(data.ObjectiveText[k].size() <= idx)
3614 data.ObjectiveText[k].resize(idx+1);
3616 data.ObjectiveText[k][idx] = str;
3621 } while (result->NextRow());
3623 delete result;
3625 sLog.outString();
3626 sLog.outString( ">> Loaded %u Quest locale strings", mQuestLocaleMap.size() );
3629 void ObjectMgr::LoadPetCreateSpells()
3631 QueryResult *result = WorldDatabase.Query("SELECT entry, Spell1, Spell2, Spell3, Spell4 FROM petcreateinfo_spell");
3632 if(!result)
3634 barGoLink bar( 1 );
3635 bar.step();
3637 sLog.outString();
3638 sLog.outString( ">> Loaded 0 pet create spells" );
3639 sLog.outErrorDb("`petcreateinfo_spell` table is empty!");
3640 return;
3643 uint32 count = 0;
3645 barGoLink bar( result->GetRowCount() );
3647 mPetCreateSpell.clear();
3651 Field *fields = result->Fetch();
3652 bar.step();
3654 uint32 creature_id = fields[0].GetUInt32();
3656 if(!creature_id || !sCreatureStorage.LookupEntry<CreatureInfo>(creature_id))
3657 continue;
3659 PetCreateSpellEntry PetCreateSpell;
3660 for(int i = 0; i < 4; i++)
3662 PetCreateSpell.spellid[i] = fields[i + 1].GetUInt32();
3664 if(PetCreateSpell.spellid[i] && !sSpellStore.LookupEntry(PetCreateSpell.spellid[i]))
3665 sLog.outErrorDb("Spell %u listed in `petcreateinfo_spell` does not exist",PetCreateSpell.spellid[i]);
3668 mPetCreateSpell[creature_id] = PetCreateSpell;
3670 ++count;
3672 while (result->NextRow());
3674 delete result;
3676 sLog.outString();
3677 sLog.outString( ">> Loaded %u pet create spells", count );
3680 void ObjectMgr::LoadScripts(ScriptMapMap& scripts, char const* tablename)
3682 if(sWorld.IsScriptScheduled()) // function don't must be called in time scripts use.
3683 return;
3685 sLog.outString( "%s :", tablename);
3687 scripts.clear(); // need for reload support
3689 QueryResult *result = WorldDatabase.PQuery( "SELECT id,delay,command,datalong,datalong2,dataint, x, y, z, o FROM %s", tablename );
3691 uint32 count = 0;
3693 if( !result )
3695 barGoLink bar( 1 );
3696 bar.step();
3698 sLog.outString();
3699 sLog.outString( ">> Loaded %u script definitions", count );
3700 return;
3703 barGoLink bar( result->GetRowCount() );
3707 bar.step();
3709 Field *fields = result->Fetch();
3710 ScriptInfo tmp;
3711 tmp.id = fields[0].GetUInt32();
3712 tmp.delay = fields[1].GetUInt32();
3713 tmp.command = fields[2].GetUInt32();
3714 tmp.datalong = fields[3].GetUInt32();
3715 tmp.datalong2 = fields[4].GetUInt32();
3716 tmp.dataint = fields[5].GetInt32();
3717 tmp.x = fields[6].GetFloat();
3718 tmp.y = fields[7].GetFloat();
3719 tmp.z = fields[8].GetFloat();
3720 tmp.o = fields[9].GetFloat();
3722 // generic command args check
3723 switch(tmp.command)
3725 case SCRIPT_COMMAND_TALK:
3727 if(tmp.datalong > 3)
3729 sLog.outErrorDb("Table `%s` has invalid talk type (datalong = %u) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.datalong,tmp.id);
3730 continue;
3732 if(tmp.dataint==0)
3734 sLog.outErrorDb("Table `%s` has invalid talk text id (dataint = %i) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.dataint,tmp.id);
3735 continue;
3737 if(tmp.dataint < MIN_DB_SCRIPT_STRING_ID || tmp.dataint >= MAX_DB_SCRIPT_STRING_ID)
3739 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);
3740 continue;
3743 // if(!objmgr.GetMangosStringLocale(tmp.dataint)) will checked after db_script_string loading
3744 break;
3747 case SCRIPT_COMMAND_TELEPORT_TO:
3749 if(!sMapStore.LookupEntry(tmp.datalong))
3751 sLog.outErrorDb("Table `%s` has invalid map (Id: %u) in SCRIPT_COMMAND_TELEPORT_TO for script id %u",tablename,tmp.datalong,tmp.id);
3752 continue;
3755 if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
3757 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);
3758 continue;
3760 break;
3763 case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
3765 if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
3767 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);
3768 continue;
3771 if(!GetCreatureTemplate(tmp.datalong))
3773 sLog.outErrorDb("Table `%s` has invalid creature (Entry: %u) in SCRIPT_COMMAND_TEMP_SUMMON_CREATURE for script id %u",tablename,tmp.datalong,tmp.id);
3774 continue;
3776 break;
3779 case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
3781 GameObjectData const* data = GetGOData(tmp.datalong);
3782 if(!data)
3784 sLog.outErrorDb("Table `%s` has invalid gameobject (GUID: %u) in SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,tmp.datalong,tmp.id);
3785 continue;
3788 GameObjectInfo const* info = GetGameObjectInfo(data->id);
3789 if(!info)
3791 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);
3792 continue;
3795 if( info->type==GAMEOBJECT_TYPE_FISHINGNODE ||
3796 info->type==GAMEOBJECT_TYPE_FISHINGHOLE ||
3797 info->type==GAMEOBJECT_TYPE_DOOR ||
3798 info->type==GAMEOBJECT_TYPE_BUTTON ||
3799 info->type==GAMEOBJECT_TYPE_TRAP )
3801 sLog.outErrorDb("Table `%s` have gameobject type (%u) unsupported by command SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,info->id,tmp.id);
3802 continue;
3804 break;
3806 case SCRIPT_COMMAND_OPEN_DOOR:
3807 case SCRIPT_COMMAND_CLOSE_DOOR:
3809 GameObjectData const* data = GetGOData(tmp.datalong);
3810 if(!data)
3812 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);
3813 continue;
3816 GameObjectInfo const* info = GetGameObjectInfo(data->id);
3817 if(!info)
3819 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);
3820 continue;
3823 if( info->type!=GAMEOBJECT_TYPE_DOOR)
3825 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);
3826 continue;
3829 break;
3831 case SCRIPT_COMMAND_QUEST_EXPLORED:
3833 Quest const* quest = GetQuestTemplate(tmp.datalong);
3834 if(!quest)
3836 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);
3837 continue;
3840 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3842 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);
3844 // this will prevent quest completing without objective
3845 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3847 // continue; - quest objective requirement set and command can be allowed
3850 if(float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
3852 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",
3853 tablename,tmp.datalong2,tmp.id);
3854 continue;
3857 if(tmp.datalong2 && float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
3859 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",
3860 tablename,tmp.datalong2,tmp.id,DEFAULT_VISIBILITY_DISTANCE);
3861 continue;
3864 if(tmp.datalong2 && float(tmp.datalong2) < INTERACTION_DISTANCE)
3866 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",
3867 tablename,tmp.datalong2,tmp.id,INTERACTION_DISTANCE);
3868 continue;
3871 break;
3874 case SCRIPT_COMMAND_REMOVE_AURA:
3875 case SCRIPT_COMMAND_CAST_SPELL:
3877 if(!sSpellStore.LookupEntry(tmp.datalong))
3879 sLog.outErrorDb("Table `%s` using non-existent spell (id: %u) in SCRIPT_COMMAND_REMOVE_AURA or SCRIPT_COMMAND_CAST_SPELL for script id %u",
3880 tablename,tmp.datalong,tmp.id);
3881 continue;
3883 break;
3887 if (scripts.find(tmp.id) == scripts.end())
3889 ScriptMap emptyMap;
3890 scripts[tmp.id] = emptyMap;
3892 scripts[tmp.id].insert(std::pair<uint32, ScriptInfo>(tmp.delay, tmp));
3894 ++count;
3895 } while( result->NextRow() );
3897 delete result;
3899 sLog.outString();
3900 sLog.outString( ">> Loaded %u script definitions", count );
3903 void ObjectMgr::LoadGameObjectScripts()
3905 LoadScripts(sGameObjectScripts, "gameobject_scripts");
3907 // check ids
3908 for(ScriptMapMap::const_iterator itr = sGameObjectScripts.begin(); itr != sGameObjectScripts.end(); ++itr)
3910 if(!GetGOData(itr->first))
3911 sLog.outErrorDb("Table `gameobject_scripts` has not existing gameobject (GUID: %u) as script id",itr->first);
3915 void ObjectMgr::LoadQuestEndScripts()
3917 LoadScripts(sQuestEndScripts, "quest_end_scripts");
3919 // check ids
3920 for(ScriptMapMap::const_iterator itr = sQuestEndScripts.begin(); itr != sQuestEndScripts.end(); ++itr)
3922 if(!GetQuestTemplate(itr->first))
3923 sLog.outErrorDb("Table `quest_end_scripts` has not existing quest (Id: %u) as script id",itr->first);
3927 void ObjectMgr::LoadQuestStartScripts()
3929 LoadScripts(sQuestStartScripts,"quest_start_scripts");
3931 // check ids
3932 for(ScriptMapMap::const_iterator itr = sQuestStartScripts.begin(); itr != sQuestStartScripts.end(); ++itr)
3934 if(!GetQuestTemplate(itr->first))
3935 sLog.outErrorDb("Table `quest_start_scripts` has not existing quest (Id: %u) as script id",itr->first);
3939 void ObjectMgr::LoadSpellScripts()
3941 LoadScripts(sSpellScripts, "spell_scripts");
3943 // check ids
3944 for(ScriptMapMap::const_iterator itr = sSpellScripts.begin(); itr != sSpellScripts.end(); ++itr)
3946 SpellEntry const* spellInfo = sSpellStore.LookupEntry(itr->first);
3948 if(!spellInfo)
3950 sLog.outErrorDb("Table `spell_scripts` has not existing spell (Id: %u) as script id",itr->first);
3951 continue;
3954 //check for correct spellEffect
3955 bool found = false;
3956 for(int i=0; i<3; ++i)
3958 // skip empty effects
3959 if( !spellInfo->Effect[i] )
3960 continue;
3962 if( spellInfo->Effect[i] == SPELL_EFFECT_SCRIPT_EFFECT )
3964 found = true;
3965 break;
3969 if(!found)
3970 sLog.outErrorDb("Table `spell_scripts` has unsupported spell (Id: %u) without SPELL_EFFECT_SCRIPT_EFFECT (%u) spell effect",itr->first,SPELL_EFFECT_SCRIPT_EFFECT);
3974 void ObjectMgr::LoadEventScripts()
3976 LoadScripts(sEventScripts, "event_scripts");
3978 std::set<uint32> evt_scripts;
3979 // Load all possible script entries from gameobjects
3980 for(uint32 i = 1; i < sGOStorage.MaxEntry; ++i)
3982 GameObjectInfo const * goInfo = sGOStorage.LookupEntry<GameObjectInfo>(i);
3983 if (goInfo)
3985 switch(goInfo->type)
3987 case GAMEOBJECT_TYPE_GOOBER:
3988 if(goInfo->goober.eventId)
3989 evt_scripts.insert(goInfo->goober.eventId);
3990 break;
3991 case GAMEOBJECT_TYPE_CHEST:
3992 if(goInfo->chest.eventId)
3993 evt_scripts.insert(goInfo->chest.eventId);
3994 break;
3995 default:
3996 break;
4000 // Load all possible script entries from spells
4001 for(uint32 i = 1; i < sSpellStore.GetNumRows(); ++i)
4003 SpellEntry const * spell = sSpellStore.LookupEntry(i);
4004 if (spell)
4006 for(int j=0; j<3; ++j)
4008 if( spell->Effect[j] == SPELL_EFFECT_SEND_EVENT )
4010 if (spell->EffectMiscValue[j])
4011 evt_scripts.insert(spell->EffectMiscValue[j]);
4016 // Then check if all scripts are in above list of possible script entries
4017 for(ScriptMapMap::const_iterator itr = sEventScripts.begin(); itr != sEventScripts.end(); ++itr)
4019 std::set<uint32>::const_iterator itr2 = evt_scripts.find(itr->first);
4020 if (itr2 == evt_scripts.end())
4021 sLog.outErrorDb("Table `event_scripts` has script (Id: %u) not referring to any gameobject_template type 10 data2 field or type 3 data6 field or any spell effect %u", itr->first, SPELL_EFFECT_SEND_EVENT);
4025 void ObjectMgr::LoadItemTexts()
4027 QueryResult *result = CharacterDatabase.Query("SELECT id, text FROM item_text");
4029 uint32 count = 0;
4031 if( !result )
4033 barGoLink bar( 1 );
4034 bar.step();
4036 sLog.outString();
4037 sLog.outString( ">> Loaded %u item pages", count );
4038 return;
4041 barGoLink bar( result->GetRowCount() );
4043 Field* fields;
4046 bar.step();
4048 fields = result->Fetch();
4050 mItemTexts[ fields[0].GetUInt32() ] = fields[1].GetCppString();
4052 ++count;
4054 } while ( result->NextRow() );
4056 delete result;
4058 sLog.outString();
4059 sLog.outString( ">> Loaded %u item texts", count );
4062 void ObjectMgr::LoadPageTexts()
4064 sPageTextStore.Free(); // for reload case
4066 sPageTextStore.Load();
4067 sLog.outString( ">> Loaded %u page texts", sPageTextStore.RecordCount );
4068 sLog.outString();
4070 for(uint32 i = 1; i < sPageTextStore.MaxEntry; ++i)
4072 // check data correctness
4073 PageText const* page = sPageTextStore.LookupEntry<PageText>(i);
4074 if(!page)
4075 continue;
4077 if(page->Next_Page && !sPageTextStore.LookupEntry<PageText>(page->Next_Page))
4079 sLog.outErrorDb("Page text (Id: %u) has not existing next page (Id:%u)", i,page->Next_Page);
4080 continue;
4083 // detect circular reference
4084 std::set<uint32> checkedPages;
4085 for(PageText const* pageItr = page; pageItr; pageItr = sPageTextStore.LookupEntry<PageText>(pageItr->Next_Page))
4087 if(!pageItr->Next_Page)
4088 break;
4089 checkedPages.insert(pageItr->Page_ID);
4090 if(checkedPages.find(pageItr->Next_Page)!=checkedPages.end())
4092 std::ostringstream ss;
4093 ss<< "The text page(s) ";
4094 for (std::set<uint32>::iterator itr= checkedPages.begin();itr!=checkedPages.end(); ++itr)
4095 ss << *itr << " ";
4096 ss << "create(s) a circular reference, which can cause the server to freeze. Changing Next_Page of page "
4097 << pageItr->Page_ID <<" to 0";
4098 sLog.outErrorDb(ss.str().c_str());
4099 const_cast<PageText*>(pageItr)->Next_Page = 0;
4100 break;
4106 void ObjectMgr::LoadPageTextLocales()
4108 mPageTextLocaleMap.clear(); // need for reload case
4110 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");
4112 if(!result)
4114 barGoLink bar(1);
4116 bar.step();
4118 sLog.outString("");
4119 sLog.outString(">> Loaded 0 PageText locale strings. DB table `locales_page_text` is empty.");
4120 return;
4123 barGoLink bar(result->GetRowCount());
4127 Field *fields = result->Fetch();
4128 bar.step();
4130 uint32 entry = fields[0].GetUInt32();
4132 PageTextLocale& data = mPageTextLocaleMap[entry];
4134 for(int i = 1; i < MAX_LOCALE; ++i)
4136 std::string str = fields[i].GetCppString();
4137 if(str.empty())
4138 continue;
4140 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4141 if(idx >= 0)
4143 if(data.Text.size() <= idx)
4144 data.Text.resize(idx+1);
4146 data.Text[idx] = str;
4150 } while (result->NextRow());
4152 delete result;
4154 sLog.outString();
4155 sLog.outString( ">> Loaded %u PageText locale strings", mPageTextLocaleMap.size() );
4158 struct SQLInstanceLoader : public SQLStorageLoaderBase<SQLInstanceLoader>
4160 template<class D>
4161 void convert_from_str(uint32 field_pos, char *src, D &dst)
4163 dst = D(objmgr.GetScriptId(src));
4167 void ObjectMgr::LoadInstanceTemplate()
4169 SQLInstanceLoader loader;
4170 loader.Load(sInstanceTemplate);
4172 for(uint32 i = 0; i < sInstanceTemplate.MaxEntry; i++)
4174 InstanceTemplate* temp = (InstanceTemplate*)GetInstanceTemplate(i);
4175 if(!temp) continue;
4176 const MapEntry* entry = sMapStore.LookupEntry(temp->map);
4177 if(!entry)
4179 sLog.outErrorDb("ObjectMgr::LoadInstanceTemplate: bad mapid %d for template!", temp->map);
4180 continue;
4182 else if(!entry->HasResetTime())
4183 continue;
4185 if(temp->reset_delay == 0)
4187 // use defaults from the DBC
4188 if(entry->SupportsHeroicMode())
4190 temp->reset_delay = entry->resetTimeHeroic / DAY;
4192 else if (entry->resetTimeRaid && entry->map_type == MAP_RAID)
4194 temp->reset_delay = entry->resetTimeRaid / DAY;
4198 // the reset_delay must be at least one day
4199 temp->reset_delay = std::max((uint32)1, (uint32)(temp->reset_delay * sWorld.getRate(RATE_INSTANCE_RESET_TIME)));
4202 sLog.outString( ">> Loaded %u Instance Template definitions", sInstanceTemplate.RecordCount );
4203 sLog.outString();
4206 void ObjectMgr::AddGossipText(GossipText *pGText)
4208 ASSERT( pGText->Text_ID );
4209 ASSERT( mGossipText.find(pGText->Text_ID) == mGossipText.end() );
4210 mGossipText[pGText->Text_ID] = pGText;
4213 GossipText *ObjectMgr::GetGossipText(uint32 Text_ID)
4215 GossipTextMap::const_iterator itr;
4216 for (itr = mGossipText.begin(); itr != mGossipText.end(); ++itr)
4218 if(itr->second->Text_ID == Text_ID)
4219 return itr->second;
4221 return NULL;
4224 void ObjectMgr::LoadGossipText()
4226 GossipText *pGText;
4227 QueryResult *result = WorldDatabase.Query( "SELECT * FROM npc_text" );
4229 int count = 0;
4230 if( !result )
4232 barGoLink bar( 1 );
4233 bar.step();
4235 sLog.outString();
4236 sLog.outString( ">> Loaded %u npc texts", count );
4237 return;
4240 int cic;
4242 barGoLink bar( result->GetRowCount() );
4246 ++count;
4247 cic = 0;
4249 Field *fields = result->Fetch();
4251 bar.step();
4253 pGText = new GossipText;
4254 pGText->Text_ID = fields[cic++].GetUInt32();
4256 for (int i=0; i< 8; i++)
4258 pGText->Options[i].Text_0 = fields[cic++].GetCppString();
4259 pGText->Options[i].Text_1 = fields[cic++].GetCppString();
4261 pGText->Options[i].Language = fields[cic++].GetUInt32();
4262 pGText->Options[i].Probability = fields[cic++].GetFloat();
4264 pGText->Options[i].Emotes[0]._Delay = fields[cic++].GetUInt32();
4265 pGText->Options[i].Emotes[0]._Emote = fields[cic++].GetUInt32();
4267 pGText->Options[i].Emotes[1]._Delay = fields[cic++].GetUInt32();
4268 pGText->Options[i].Emotes[1]._Emote = fields[cic++].GetUInt32();
4270 pGText->Options[i].Emotes[2]._Delay = fields[cic++].GetUInt32();
4271 pGText->Options[i].Emotes[2]._Emote = fields[cic++].GetUInt32();
4274 if ( !pGText->Text_ID ) continue;
4275 AddGossipText( pGText );
4277 } while( result->NextRow() );
4279 sLog.outString();
4280 sLog.outString( ">> Loaded %u npc texts", count );
4281 delete result;
4284 void ObjectMgr::LoadNpcTextLocales()
4286 mNpcTextLocaleMap.clear(); // need for reload case
4288 QueryResult *result = WorldDatabase.Query("SELECT entry,"
4289 "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,"
4290 "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,"
4291 "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,"
4292 "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,"
4293 "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,"
4294 "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,"
4295 "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, "
4296 "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 "
4297 " FROM locales_npc_text");
4299 if(!result)
4301 barGoLink bar(1);
4303 bar.step();
4305 sLog.outString("");
4306 sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_npc_text` is empty.");
4307 return;
4310 barGoLink bar(result->GetRowCount());
4314 Field *fields = result->Fetch();
4315 bar.step();
4317 uint32 entry = fields[0].GetUInt32();
4319 NpcTextLocale& data = mNpcTextLocaleMap[entry];
4321 for(int i=1; i<MAX_LOCALE; ++i)
4323 for(int j=0; j<8; ++j)
4325 std::string str0 = fields[1+8*2*(i-1)+2*j].GetCppString();
4326 if(!str0.empty())
4328 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4329 if(idx >= 0)
4331 if(data.Text_0[j].size() <= idx)
4332 data.Text_0[j].resize(idx+1);
4334 data.Text_0[j][idx] = str0;
4337 std::string str1 = fields[1+8*2*(i-1)+2*j+1].GetCppString();
4338 if(!str1.empty())
4340 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4341 if(idx >= 0)
4343 if(data.Text_1[j].size() <= idx)
4344 data.Text_1[j].resize(idx+1);
4346 data.Text_1[j][idx] = str1;
4351 } while (result->NextRow());
4353 delete result;
4355 sLog.outString();
4356 sLog.outString( ">> Loaded %u NpcText locale strings", mNpcTextLocaleMap.size() );
4359 //not very fast function but it is called only once a day, or on starting-up
4360 void ObjectMgr::ReturnOrDeleteOldMails(bool serverUp)
4362 time_t basetime = time(NULL);
4363 sLog.outDebug("Returning mails current time: hour: %d, minute: %d, second: %d ", localtime(&basetime)->tm_hour, localtime(&basetime)->tm_min, localtime(&basetime)->tm_sec);
4364 //delete all old mails without item and without body immediately, if starting server
4365 if (!serverUp)
4366 CharacterDatabase.PExecute("DELETE FROM mail WHERE expire_time < '" I64FMTD "' AND has_items = '0' AND itemTextId = 0", (uint64)basetime);
4367 // 0 1 2 3 4 5 6 7 8 9
4368 QueryResult* result = CharacterDatabase.PQuery("SELECT id,messageType,sender,receiver,itemTextId,has_items,expire_time,cod,checked,mailTemplateId FROM mail WHERE expire_time < '" I64FMTD "'", (uint64)basetime);
4369 if ( !result )
4370 return; // any mails need to be returned or deleted
4371 Field *fields;
4372 //std::ostringstream delitems, delmails; //will be here for optimization
4373 //bool deletemail = false, deleteitem = false;
4374 //delitems << "DELETE FROM item_instance WHERE guid IN ( ";
4375 //delmails << "DELETE FROM mail WHERE id IN ( "
4378 fields = result->Fetch();
4379 Mail *m = new Mail;
4380 m->messageID = fields[0].GetUInt32();
4381 m->messageType = fields[1].GetUInt8();
4382 m->sender = fields[2].GetUInt32();
4383 m->receiver = fields[3].GetUInt32();
4384 m->itemTextId = fields[4].GetUInt32();
4385 bool has_items = fields[5].GetBool();
4386 m->expire_time = (time_t)fields[6].GetUInt64();
4387 m->deliver_time = 0;
4388 m->COD = fields[7].GetUInt32();
4389 m->checked = fields[8].GetUInt32();
4390 m->mailTemplateId = fields[9].GetInt16();
4392 Player *pl = 0;
4393 if (serverUp)
4394 pl = GetPlayer((uint64)m->receiver);
4395 if (pl && pl->m_mailsLoaded)
4396 { //this code will run very improbably (the time is between 4 and 5 am, in game is online a player, who has old mail
4397 //his in mailbox and he has already listed his mails )
4398 delete m;
4399 continue;
4401 //delete or return mail:
4402 if (has_items)
4404 QueryResult *resultItems = CharacterDatabase.PQuery("SELECT item_guid,item_template FROM mail_items WHERE mail_id='%u'", m->messageID);
4405 if(resultItems)
4409 Field *fields2 = resultItems->Fetch();
4411 uint32 item_guid_low = fields2[0].GetUInt32();
4412 uint32 item_template = fields2[1].GetUInt32();
4414 m->AddItem(item_guid_low, item_template);
4416 while (resultItems->NextRow());
4418 delete resultItems;
4420 //if it is mail from AH, it shouldn't be returned, but deleted
4421 if (m->messageType != MAIL_NORMAL || (m->checked & (MAIL_CHECK_MASK_AUCTION | MAIL_CHECK_MASK_COD_PAYMENT | MAIL_CHECK_MASK_RETURNED)))
4423 // mail open and then not returned
4424 for(std::vector<MailItemInfo>::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
4425 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
4427 else
4429 //mail will be returned:
4430 CharacterDatabase.PExecute("UPDATE mail SET sender = '%u', receiver = '%u', expire_time = '" I64FMTD "', deliver_time = '" I64FMTD "',cod = '0', checked = '%u' WHERE id = '%u'", m->receiver, m->sender, (uint64)(basetime + 30*DAY), (uint64)basetime, MAIL_CHECK_MASK_RETURNED, m->messageID);
4431 delete m;
4432 continue;
4436 if (m->itemTextId)
4437 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
4439 //deletemail = true;
4440 //delmails << m->messageID << ", ";
4441 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
4442 delete m;
4443 } while (result->NextRow());
4444 delete result;
4447 void ObjectMgr::LoadQuestAreaTriggers()
4449 mQuestAreaTriggerMap.clear(); // need for reload case
4451 QueryResult *result = WorldDatabase.Query( "SELECT id,quest FROM areatrigger_involvedrelation" );
4453 uint32 count = 0;
4455 if( !result )
4457 barGoLink bar( 1 );
4458 bar.step();
4460 sLog.outString();
4461 sLog.outString( ">> Loaded %u quest trigger points", count );
4462 return;
4465 barGoLink bar( result->GetRowCount() );
4469 ++count;
4470 bar.step();
4472 Field *fields = result->Fetch();
4474 uint32 trigger_ID = fields[0].GetUInt32();
4475 uint32 quest_ID = fields[1].GetUInt32();
4477 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(trigger_ID);
4478 if(!atEntry)
4480 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",trigger_ID);
4481 continue;
4484 Quest const* quest = GetQuestTemplate(quest_ID);
4486 if(!quest)
4488 sLog.outErrorDb("Table `areatrigger_involvedrelation` has record (id: %u) for not existing quest %u",trigger_ID,quest_ID);
4489 continue;
4492 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
4494 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);
4496 // this will prevent quest completing without objective
4497 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
4499 // continue; - quest modified to required objective and trigger can be allowed.
4502 mQuestAreaTriggerMap[trigger_ID] = quest_ID;
4504 } while( result->NextRow() );
4506 delete result;
4508 sLog.outString();
4509 sLog.outString( ">> Loaded %u quest trigger points", count );
4512 void ObjectMgr::LoadTavernAreaTriggers()
4514 mTavernAreaTriggerSet.clear(); // need for reload case
4516 QueryResult *result = WorldDatabase.Query("SELECT id FROM areatrigger_tavern");
4518 uint32 count = 0;
4520 if( !result )
4522 barGoLink bar( 1 );
4523 bar.step();
4525 sLog.outString();
4526 sLog.outString( ">> Loaded %u tavern triggers", count );
4527 return;
4530 barGoLink bar( result->GetRowCount() );
4534 ++count;
4535 bar.step();
4537 Field *fields = result->Fetch();
4539 uint32 Trigger_ID = fields[0].GetUInt32();
4541 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4542 if(!atEntry)
4544 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4545 continue;
4548 mTavernAreaTriggerSet.insert(Trigger_ID);
4549 } while( result->NextRow() );
4551 delete result;
4553 sLog.outString();
4554 sLog.outString( ">> Loaded %u tavern triggers", count );
4557 void ObjectMgr::LoadAreaTriggerScripts()
4559 mAreaTriggerScripts.clear(); // need for reload case
4560 QueryResult *result = WorldDatabase.Query("SELECT entry, ScriptName FROM areatrigger_scripts");
4562 uint32 count = 0;
4564 if( !result )
4566 barGoLink bar( 1 );
4567 bar.step();
4569 sLog.outString();
4570 sLog.outString( ">> Loaded %u areatrigger scripts", count );
4571 return;
4574 barGoLink bar( result->GetRowCount() );
4578 ++count;
4579 bar.step();
4581 Field *fields = result->Fetch();
4583 uint32 Trigger_ID = fields[0].GetUInt32();
4584 const char *scriptName = fields[1].GetString();
4586 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4587 if(!atEntry)
4589 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4590 continue;
4592 mAreaTriggerScripts[Trigger_ID] = GetScriptId(scriptName);
4593 } while( result->NextRow() );
4595 delete result;
4597 sLog.outString();
4598 sLog.outString( ">> Loaded %u areatrigger scripts", count );
4601 uint32 ObjectMgr::GetNearestTaxiNode( float x, float y, float z, uint32 mapid )
4603 bool found = false;
4604 float dist;
4605 uint32 id = 0;
4607 for(uint32 i = 1; i < sTaxiNodesStore.GetNumRows(); ++i)
4609 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(i);
4610 if(node && node->map_id == mapid)
4612 float dist2 = (node->x - x)*(node->x - x)+(node->y - y)*(node->y - y)+(node->z - z)*(node->z - z);
4613 if(found)
4615 if(dist2 < dist)
4617 dist = dist2;
4618 id = i;
4621 else
4623 found = true;
4624 dist = dist2;
4625 id = i;
4630 return id;
4633 void ObjectMgr::GetTaxiPath( uint32 source, uint32 destination, uint32 &path, uint32 &cost)
4635 TaxiPathSetBySource::iterator src_i = sTaxiPathSetBySource.find(source);
4636 if(src_i==sTaxiPathSetBySource.end())
4638 path = 0;
4639 cost = 0;
4640 return;
4643 TaxiPathSetForSource& pathSet = src_i->second;
4645 TaxiPathSetForSource::iterator dest_i = pathSet.find(destination);
4646 if(dest_i==pathSet.end())
4648 path = 0;
4649 cost = 0;
4650 return;
4653 cost = dest_i->second.price;
4654 path = dest_i->second.ID;
4657 uint16 ObjectMgr::GetTaxiMount( uint32 id, uint32 team )
4659 uint16 mount_entry = 0;
4660 uint16 mount_id = 0;
4662 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(id);
4663 if(node)
4665 if (team == ALLIANCE)
4667 mount_entry = node->alliance_mount_type;
4668 CreatureInfo const *ci = GetCreatureTemplate(mount_entry);
4669 if(ci)
4670 mount_id = ci->DisplayID_A;
4672 if (team == HORDE)
4674 mount_entry = node->horde_mount_type;
4675 CreatureInfo const *ci = GetCreatureTemplate(mount_entry);
4676 if(ci)
4677 mount_id = ci->DisplayID_H;
4681 CreatureModelInfo const *minfo = GetCreatureModelInfo(mount_id);
4682 if(!minfo)
4684 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. ",
4685 mount_entry,id,team,mount_id);
4687 return false;
4689 if(minfo->modelid_other_gender!=0)
4690 mount_id = urand(0,1) ? mount_id : minfo->modelid_other_gender;
4692 return mount_id;
4695 void ObjectMgr::GetTaxiPathNodes( uint32 path, Path &pathnodes, std::vector<uint32>& mapIds)
4697 if(path >= sTaxiPathNodesByPath.size())
4698 return;
4700 TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
4702 pathnodes.Resize(nodeList.size());
4703 mapIds.resize(nodeList.size());
4705 for(size_t i = 0; i < nodeList.size(); ++i)
4707 pathnodes[ i ].x = nodeList[i].x;
4708 pathnodes[ i ].y = nodeList[i].y;
4709 pathnodes[ i ].z = nodeList[i].z;
4711 mapIds[i] = nodeList[i].mapid;
4715 void ObjectMgr::GetTransportPathNodes( uint32 path, TransportPath &pathnodes )
4717 if(path >= sTaxiPathNodesByPath.size())
4718 return;
4720 TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
4722 pathnodes.Resize(nodeList.size());
4724 for(size_t i = 0; i < nodeList.size(); ++i)
4726 pathnodes[ i ].mapid = nodeList[i].mapid;
4727 pathnodes[ i ].x = nodeList[i].x;
4728 pathnodes[ i ].y = nodeList[i].y;
4729 pathnodes[ i ].z = nodeList[i].z;
4730 pathnodes[ i ].actionFlag = nodeList[i].actionFlag;
4731 pathnodes[ i ].delay = nodeList[i].delay;
4735 void ObjectMgr::LoadGraveyardZones()
4737 mGraveYardMap.clear(); // need for reload case
4739 QueryResult *result = WorldDatabase.Query("SELECT id,ghost_zone,faction FROM game_graveyard_zone");
4741 uint32 count = 0;
4743 if( !result )
4745 barGoLink bar( 1 );
4746 bar.step();
4748 sLog.outString();
4749 sLog.outString( ">> Loaded %u graveyard-zone links", count );
4750 return;
4753 barGoLink bar( result->GetRowCount() );
4757 ++count;
4758 bar.step();
4760 Field *fields = result->Fetch();
4762 uint32 safeLocId = fields[0].GetUInt32();
4763 uint32 zoneId = fields[1].GetUInt32();
4764 uint32 team = fields[2].GetUInt32();
4766 WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(safeLocId);
4767 if(!entry)
4769 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",safeLocId);
4770 continue;
4773 AreaTableEntry const *areaEntry = GetAreaEntryByAreaID(zoneId);
4774 if(!areaEntry)
4776 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing zone id (%u), skipped.",zoneId);
4777 continue;
4780 if(areaEntry->zone != 0)
4782 sLog.outErrorDb("Table `game_graveyard_zone` has record subzone id (%u) instead of zone, skipped.",zoneId);
4783 continue;
4786 if(team!=0 && team!=HORDE && team!=ALLIANCE)
4788 sLog.outErrorDb("Table `game_graveyard_zone` has record for non player faction (%u), skipped.",team);
4789 continue;
4792 if(!AddGraveYardLink(safeLocId,zoneId,team,false))
4793 sLog.outErrorDb("Table `game_graveyard_zone` has a duplicate record for Graveyard (ID: %u) and Zone (ID: %u), skipped.",safeLocId,zoneId);
4794 } while( result->NextRow() );
4796 delete result;
4798 sLog.outString();
4799 sLog.outString( ">> Loaded %u graveyard-zone links", count );
4802 WorldSafeLocsEntry const *ObjectMgr::GetClosestGraveYard(float x, float y, float z, uint32 MapId, uint32 team)
4804 // search for zone associated closest graveyard
4805 uint32 zoneId = MapManager::Instance().GetZoneId(MapId,x,y);
4807 // Simulate std. algorithm:
4808 // found some graveyard associated to (ghost_zone,ghost_map)
4810 // if mapId == graveyard.mapId (ghost in plain zone or city or battleground) and search graveyard at same map
4811 // then check faction
4812 // if mapId != graveyard.mapId (ghost in instance) and search any graveyard associated
4813 // then check faction
4814 GraveYardMap::const_iterator graveLow = mGraveYardMap.lower_bound(zoneId);
4815 GraveYardMap::const_iterator graveUp = mGraveYardMap.upper_bound(zoneId);
4816 if(graveLow==graveUp)
4818 sLog.outErrorDb("Table `game_graveyard_zone` incomplete: Zone %u Team %u does not have a linked graveyard.",zoneId,team);
4819 return NULL;
4822 // at corpse map
4823 bool foundNear = false;
4824 float distNear;
4825 WorldSafeLocsEntry const* entryNear = NULL;
4827 // at entrance map for corpse map
4828 bool foundEntr = false;
4829 float distEntr;
4830 WorldSafeLocsEntry const* entryEntr = NULL;
4832 // some where other
4833 WorldSafeLocsEntry const* entryFar = NULL;
4835 MapEntry const* mapEntry = sMapStore.LookupEntry(MapId);
4837 for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
4839 GraveYardData const& data = itr->second;
4841 WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(data.safeLocId);
4842 if(!entry)
4844 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",data.safeLocId);
4845 continue;
4848 // skip enemy faction graveyard
4849 // team == 0 case can be at call from .neargrave
4850 if(data.team != 0 && team != 0 && data.team != team)
4851 continue;
4853 // find now nearest graveyard at other map
4854 if(MapId != entry->map_id)
4856 // if find graveyard at different map from where entrance placed (or no entrance data), use any first
4857 if (!mapEntry || mapEntry->entrance_map < 0 || mapEntry->entrance_map != entry->map_id ||
4858 mapEntry->entrance_x == 0 && mapEntry->entrance_y == 0)
4860 // not have any corrdinates for check distance anyway
4861 entryFar = entry;
4862 continue;
4865 // at entrance map calculate distance (2D);
4866 float dist2 = (entry->x - mapEntry->entrance_x)*(entry->x - mapEntry->entrance_x)
4867 +(entry->y - mapEntry->entrance_y)*(entry->y - mapEntry->entrance_y);
4868 if(foundEntr)
4870 if(dist2 < distEntr)
4872 distEntr = dist2;
4873 entryEntr = entry;
4876 else
4878 foundEntr = true;
4879 distEntr = dist2;
4880 entryEntr = entry;
4883 // find now nearest graveyard at same map
4884 else
4886 float dist2 = (entry->x - x)*(entry->x - x)+(entry->y - y)*(entry->y - y)+(entry->z - z)*(entry->z - z);
4887 if(foundNear)
4889 if(dist2 < distNear)
4891 distNear = dist2;
4892 entryNear = entry;
4895 else
4897 foundNear = true;
4898 distNear = dist2;
4899 entryNear = entry;
4904 if(entryNear)
4905 return entryNear;
4907 if(entryEntr)
4908 return entryEntr;
4910 return entryFar;
4913 GraveYardData const* ObjectMgr::FindGraveYardData(uint32 id, uint32 zoneId)
4915 GraveYardMap::const_iterator graveLow = mGraveYardMap.lower_bound(zoneId);
4916 GraveYardMap::const_iterator graveUp = mGraveYardMap.upper_bound(zoneId);
4918 for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
4920 if(itr->second.safeLocId==id)
4921 return &itr->second;
4924 return NULL;
4927 bool ObjectMgr::AddGraveYardLink(uint32 id, uint32 zoneId, uint32 team, bool inDB)
4929 if(FindGraveYardData(id,zoneId))
4930 return false;
4932 // add link to loaded data
4933 GraveYardData data;
4934 data.safeLocId = id;
4935 data.team = team;
4937 mGraveYardMap.insert(GraveYardMap::value_type(zoneId,data));
4939 // add link to DB
4940 if(inDB)
4942 WorldDatabase.PExecuteLog("INSERT INTO game_graveyard_zone ( id,ghost_zone,faction) "
4943 "VALUES ('%u', '%u','%u')",id,zoneId,team);
4946 return true;
4949 void ObjectMgr::LoadAreaTriggerTeleports()
4951 mAreaTriggers.clear(); // need for reload case
4953 uint32 count = 0;
4955 // 0 1 2 3 4 5 6 7 8 9 10 11 12
4956 QueryResult *result = WorldDatabase.Query("SELECT id, required_level, required_item, required_item2, heroic_key, heroic_key2, required_quest_done, required_failed_text, target_map, target_position_x, target_position_y, target_position_z, target_orientation FROM areatrigger_teleport");
4957 if( !result )
4960 barGoLink bar( 1 );
4962 bar.step();
4964 sLog.outString();
4965 sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
4966 return;
4969 barGoLink bar( result->GetRowCount() );
4973 Field *fields = result->Fetch();
4975 bar.step();
4977 ++count;
4979 uint32 Trigger_ID = fields[0].GetUInt32();
4981 AreaTrigger at;
4983 at.requiredLevel = fields[1].GetUInt8();
4984 at.requiredItem = fields[2].GetUInt32();
4985 at.requiredItem2 = fields[3].GetUInt32();
4986 at.heroicKey = fields[4].GetUInt32();
4987 at.heroicKey2 = fields[5].GetUInt32();
4988 at.requiredQuest = fields[6].GetUInt32();
4989 at.requiredFailedText = fields[7].GetCppString();
4990 at.target_mapId = fields[8].GetUInt32();
4991 at.target_X = fields[9].GetFloat();
4992 at.target_Y = fields[10].GetFloat();
4993 at.target_Z = fields[11].GetFloat();
4994 at.target_Orientation = fields[12].GetFloat();
4996 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4997 if(!atEntry)
4999 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
5000 continue;
5003 if(at.requiredItem)
5005 ItemPrototype const *pProto = GetItemPrototype(at.requiredItem);
5006 if(!pProto)
5008 sLog.outError("Key item %u does not exist for trigger %u, removing key requirement.", at.requiredItem, Trigger_ID);
5009 at.requiredItem = 0;
5012 if(at.requiredItem2)
5014 ItemPrototype const *pProto = GetItemPrototype(at.requiredItem2);
5015 if(!pProto)
5017 sLog.outError("Second item %u not exist for trigger %u, remove key requirement.", at.requiredItem2, Trigger_ID);
5018 at.requiredItem2 = 0;
5022 if(at.heroicKey)
5024 ItemPrototype const *pProto = GetItemPrototype(at.heroicKey);
5025 if(!pProto)
5027 sLog.outError("Heroic key item %u not exist for trigger %u, remove key requirement.", at.heroicKey, Trigger_ID);
5028 at.heroicKey = 0;
5032 if(at.heroicKey2)
5034 ItemPrototype const *pProto = GetItemPrototype(at.heroicKey2);
5035 if(!pProto)
5037 sLog.outError("Heroic second key item %u not exist for trigger %u, remove key requirement.", at.heroicKey2, Trigger_ID);
5038 at.heroicKey2 = 0;
5042 if(at.requiredQuest)
5044 if(!mQuestTemplates[at.requiredQuest])
5046 sLog.outErrorDb("Required Quest %u not exist for trigger %u, remove quest done requirement.",at.requiredQuest,Trigger_ID);
5047 at.requiredQuest = 0;
5051 MapEntry const* mapEntry = sMapStore.LookupEntry(at.target_mapId);
5052 if(!mapEntry)
5054 sLog.outErrorDb("Area trigger (ID:%u) target map (ID: %u) does not exist in `Map.dbc`.",Trigger_ID,at.target_mapId);
5055 continue;
5058 if(at.target_X==0 && at.target_Y==0 && at.target_Z==0)
5060 sLog.outErrorDb("Area trigger (ID:%u) target coordinates not provided.",Trigger_ID);
5061 continue;
5064 mAreaTriggers[Trigger_ID] = at;
5066 } while( result->NextRow() );
5068 delete result;
5070 sLog.outString();
5071 sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
5074 AreaTrigger const* ObjectMgr::GetGoBackTrigger(uint32 Map) const
5076 const MapEntry *mapEntry = sMapStore.LookupEntry(Map);
5077 if(!mapEntry) return NULL;
5078 for (AreaTriggerMap::const_iterator itr = mAreaTriggers.begin(); itr != mAreaTriggers.end(); ++itr)
5080 if(itr->second.target_mapId == mapEntry->entrance_map)
5082 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(itr->first);
5083 if(atEntry && atEntry->mapid == Map)
5084 return &itr->second;
5087 return NULL;
5090 void ObjectMgr::SetHighestGuids()
5092 QueryResult *result = CharacterDatabase.Query( "SELECT MAX(guid) FROM characters" );
5093 if( result )
5095 m_hiCharGuid = (*result)[0].GetUInt32()+1;
5096 delete result;
5099 result = WorldDatabase.Query( "SELECT MAX(guid) FROM creature" );
5100 if( result )
5102 m_hiCreatureGuid = (*result)[0].GetUInt32()+1;
5103 delete result;
5106 // pet guids are not saved to DB, set to 0 (pet guid != pet id)
5107 m_hiPetGuid = 0;
5109 result = CharacterDatabase.Query( "SELECT MAX(guid) FROM item_instance" );
5110 if( result )
5112 m_hiItemGuid = (*result)[0].GetUInt32()+1;
5113 delete result;
5116 // Cleanup other tables from not existed guids (>=m_hiItemGuid)
5117 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item >= '%u'", m_hiItemGuid);
5118 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid >= '%u'", m_hiItemGuid);
5119 CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE itemguid >= '%u'", m_hiItemGuid);
5120 CharacterDatabase.PExecute("DELETE FROM guild_bank_item WHERE item_guid >= '%u'", m_hiItemGuid);
5122 result = WorldDatabase.Query("SELECT MAX(guid) FROM gameobject" );
5123 if( result )
5125 m_hiGoGuid = (*result)[0].GetUInt32()+1;
5126 delete result;
5129 result = CharacterDatabase.Query("SELECT MAX(id) FROM auctionhouse" );
5130 if( result )
5132 m_auctionid = (*result)[0].GetUInt32()+1;
5133 delete result;
5136 result = CharacterDatabase.Query( "SELECT MAX(id) FROM mail" );
5137 if( result )
5139 m_mailid = (*result)[0].GetUInt32()+1;
5140 delete result;
5143 result = CharacterDatabase.Query( "SELECT MAX(id) FROM item_text" );
5144 if( result )
5146 m_ItemTextId = (*result)[0].GetUInt32()+1;
5147 delete result;
5150 result = CharacterDatabase.Query( "SELECT MAX(guid) FROM corpse" );
5151 if( result )
5153 m_hiCorpseGuid = (*result)[0].GetUInt32()+1;
5154 delete result;
5157 result = CharacterDatabase.Query("SELECT MAX(arenateamid) FROM arena_team");
5158 if (result)
5160 m_arenaTeamId = (*result)[0].GetUInt32()+1;
5161 delete result;
5164 result = CharacterDatabase.Query( "SELECT MAX(guildid) FROM guild" );
5165 if (result)
5167 m_guildId = (*result)[0].GetUInt32()+1;
5168 delete result;
5172 uint32 ObjectMgr::GenerateArenaTeamId()
5174 if(m_arenaTeamId>=0xFFFFFFFE)
5176 sLog.outError("Arena team ids overflow!! Can't continue, shutting down server. ");
5177 World::StopNow(ERROR_EXIT_CODE);
5179 return m_arenaTeamId++;
5182 uint32 ObjectMgr::GenerateGuildId()
5184 if(m_guildId>=0xFFFFFFFE)
5186 sLog.outError("Guild ids overflow!! Can't continue, shutting down server. ");
5187 World::StopNow(ERROR_EXIT_CODE);
5189 return m_guildId++;
5192 uint32 ObjectMgr::GenerateAuctionID()
5194 if(m_auctionid>=0xFFFFFFFE)
5196 sLog.outError("Auctions ids overflow!! Can't continue, shutting down server. ");
5197 World::StopNow(ERROR_EXIT_CODE);
5199 return m_auctionid++;
5202 uint32 ObjectMgr::GenerateMailID()
5204 if(m_mailid>=0xFFFFFFFE)
5206 sLog.outError("Mail ids overflow!! Can't continue, shutting down server. ");
5207 World::StopNow(ERROR_EXIT_CODE);
5209 return m_mailid++;
5212 uint32 ObjectMgr::GenerateItemTextID()
5214 if(m_ItemTextId>=0xFFFFFFFE)
5216 sLog.outError("Item text ids overflow!! Can't continue, shutting down server. ");
5217 World::StopNow(ERROR_EXIT_CODE);
5219 return m_ItemTextId++;
5222 uint32 ObjectMgr::CreateItemText(std::string text)
5224 uint32 newItemTextId = GenerateItemTextID();
5225 //insert new itempage to container
5226 mItemTexts[ newItemTextId ] = text;
5227 //save new itempage
5228 CharacterDatabase.escape_string(text);
5229 //any Delete query needed, itemTextId is maximum of all ids
5230 std::ostringstream query;
5231 query << "INSERT INTO item_text (id,text) VALUES ( '" << newItemTextId << "', '" << text << "')";
5232 CharacterDatabase.Execute(query.str().c_str()); //needs to be run this way, because mail body may be more than 1024 characters
5233 return newItemTextId;
5236 uint32 ObjectMgr::GenerateLowGuid(HighGuid guidhigh)
5238 switch(guidhigh)
5240 case HIGHGUID_ITEM:
5241 if(m_hiItemGuid>=0xFFFFFFFE)
5243 sLog.outError("Item guid overflow!! Can't continue, shutting down server. ");
5244 World::StopNow(ERROR_EXIT_CODE);
5246 return m_hiItemGuid++;
5247 case HIGHGUID_UNIT:
5248 if(m_hiCreatureGuid>=0x00FFFFFE)
5250 sLog.outError("Creature guid overflow!! Can't continue, shutting down server. ");
5251 World::StopNow(ERROR_EXIT_CODE);
5253 return m_hiCreatureGuid++;
5254 case HIGHGUID_PET:
5255 if(m_hiPetGuid>=0x00FFFFFE)
5257 sLog.outError("Pet guid overflow!! Can't continue, shutting down server. ");
5258 World::StopNow(ERROR_EXIT_CODE);
5260 return m_hiPetGuid++;
5261 case HIGHGUID_PLAYER:
5262 if(m_hiCharGuid>=0xFFFFFFFE)
5264 sLog.outError("Players guid overflow!! Can't continue, shutting down server. ");
5265 World::StopNow(ERROR_EXIT_CODE);
5267 return m_hiCharGuid++;
5268 case HIGHGUID_GAMEOBJECT:
5269 if(m_hiGoGuid>=0x00FFFFFE)
5271 sLog.outError("Gameobject guid overflow!! Can't continue, shutting down server. ");
5272 World::StopNow(ERROR_EXIT_CODE);
5274 return m_hiGoGuid++;
5275 case HIGHGUID_CORPSE:
5276 if(m_hiCorpseGuid>=0xFFFFFFFE)
5278 sLog.outError("Corpse guid overflow!! Can't continue, shutting down server. ");
5279 World::StopNow(ERROR_EXIT_CODE);
5281 return m_hiCorpseGuid++;
5282 case HIGHGUID_DYNAMICOBJECT:
5283 if(m_hiDoGuid>=0xFFFFFFFE)
5285 sLog.outError("DynamicObject guid overflow!! Can't continue, shutting down server. ");
5286 World::StopNow(ERROR_EXIT_CODE);
5288 return m_hiDoGuid++;
5289 default:
5290 ASSERT(0);
5293 ASSERT(0);
5294 return 0;
5297 void ObjectMgr::LoadGameObjectLocales()
5299 mGameObjectLocaleMap.clear(); // need for reload case
5301 QueryResult *result = WorldDatabase.Query("SELECT entry,"
5302 "name_loc1,name_loc2,name_loc3,name_loc4,name_loc5,name_loc6,name_loc7,name_loc8,"
5303 "castbarcaption_loc1,castbarcaption_loc2,castbarcaption_loc3,castbarcaption_loc4,"
5304 "castbarcaption_loc5,castbarcaption_loc6,castbarcaption_loc7,castbarcaption_loc8 FROM locales_gameobject");
5306 if(!result)
5308 barGoLink bar(1);
5310 bar.step();
5312 sLog.outString("");
5313 sLog.outString(">> Loaded 0 gameobject locale strings. DB table `locales_gameobject` is empty.");
5314 return;
5317 barGoLink bar(result->GetRowCount());
5321 Field *fields = result->Fetch();
5322 bar.step();
5324 uint32 entry = fields[0].GetUInt32();
5326 GameObjectLocale& data = mGameObjectLocaleMap[entry];
5328 for(int i = 1; i < MAX_LOCALE; ++i)
5330 std::string str = fields[i].GetCppString();
5331 if(!str.empty())
5333 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5334 if(idx >= 0)
5336 if(data.Name.size() <= idx)
5337 data.Name.resize(idx+1);
5339 data.Name[idx] = str;
5344 for(int i = MAX_LOCALE; i < MAX_LOCALE*2-1; ++i)
5346 std::string str = fields[i].GetCppString();
5347 if(!str.empty())
5349 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5350 if(idx >= 0)
5352 if(data.CastBarCaption.size() <= idx)
5353 data.CastBarCaption.resize(idx+1);
5355 data.CastBarCaption[idx] = str;
5360 } while (result->NextRow());
5362 delete result;
5364 sLog.outString();
5365 sLog.outString( ">> Loaded %u gameobject locale strings", mGameObjectLocaleMap.size() );
5368 struct SQLGameObjectLoader : public SQLStorageLoaderBase<SQLGameObjectLoader>
5370 template<class D>
5371 void convert_from_str(uint32 field_pos, char *src, D &dst)
5373 dst = D(objmgr.GetScriptId(src));
5377 void ObjectMgr::LoadGameobjectInfo()
5379 SQLGameObjectLoader loader;
5380 loader.Load(sGOStorage);
5382 // some checks
5383 for(uint32 id = 1; id < sGOStorage.MaxEntry; id++)
5385 GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(id);
5386 if(!goInfo)
5387 continue;
5389 switch(goInfo->type)
5391 case GAMEOBJECT_TYPE_DOOR: //0
5393 if(goInfo->door.lockId)
5395 if(!sLockStore.LookupEntry(goInfo->door.lockId))
5396 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but lock (Id: %u) not found.",
5397 id,goInfo->type,goInfo->door.lockId,goInfo->door.lockId);
5399 break;
5401 case GAMEOBJECT_TYPE_BUTTON: //1
5403 if(goInfo->button.lockId)
5405 if(!sLockStore.LookupEntry(goInfo->button.lockId))
5406 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but lock (Id: %u) not found.",
5407 id,goInfo->type,goInfo->button.lockId,goInfo->button.lockId);
5409 break;
5411 case GAMEOBJECT_TYPE_CHEST: //3
5413 if(goInfo->chest.lockId)
5415 if(!sLockStore.LookupEntry(goInfo->chest.lockId))
5416 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but lock (Id: %u) not found.",
5417 id,goInfo->type,goInfo->chest.lockId,goInfo->chest.lockId);
5419 if(goInfo->chest.linkedTrapId) // linked trap
5421 if(GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(goInfo->chest.linkedTrapId))
5423 if(trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5424 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data7=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5425 id,goInfo->type,goInfo->chest.linkedTrapId,goInfo->chest.linkedTrapId,GAMEOBJECT_TYPE_TRAP);
5427 /* disable check for while
5428 else
5429 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5430 id,goInfo->type,goInfo->chest.linkedTrapId,goInfo->chest.linkedTrapId);
5433 break;
5435 case GAMEOBJECT_TYPE_TRAP: //6
5437 /* disable check for while
5438 if(goInfo->trap.spellId) // spell
5440 if(!sSpellStore.LookupEntry(goInfo->trap.spellId))
5441 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data3=%u but Spell (Entry %u) not exist.",
5442 id,goInfo->type,goInfo->trap.spellId,goInfo->trap.spellId);
5445 break;
5447 case GAMEOBJECT_TYPE_CHAIR: //7
5448 if(goInfo->chair.height > 2)
5450 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but correct chair height in range 0..2.",
5451 id,goInfo->type,goInfo->chair.height);
5453 // prevent client and server unexpected work
5454 const_cast<GameObjectInfo*>(goInfo)->chair.height = 0;
5456 break;
5457 case GAMEOBJECT_TYPE_SPELL_FOCUS: //8
5459 if(goInfo->spellFocus.focusId)
5461 if(!sSpellFocusObjectStore.LookupEntry(goInfo->spellFocus.focusId))
5462 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but SpellFocus (Id: %u) not exist.",
5463 id,goInfo->type,goInfo->spellFocus.focusId,goInfo->spellFocus.focusId);
5466 if(goInfo->spellFocus.linkedTrapId) // linked trap
5468 if(GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(goInfo->spellFocus.linkedTrapId))
5470 if(trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5471 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5472 id,goInfo->type,goInfo->spellFocus.linkedTrapId,goInfo->spellFocus.linkedTrapId,GAMEOBJECT_TYPE_TRAP);
5474 /* disable check for while
5475 else
5476 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5477 id,goInfo->type,goInfo->spellFocus.linkedTrapId,goInfo->spellFocus.linkedTrapId);
5480 break;
5482 case GAMEOBJECT_TYPE_GOOBER: //10
5484 if(goInfo->goober.pageId) // pageId
5486 if(!sPageTextStore.LookupEntry<PageText>(goInfo->goober.pageId))
5487 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data7=%u but PageText (Entry %u) not exist.",
5488 id,goInfo->type,goInfo->goober.pageId,goInfo->goober.pageId);
5490 /* disable check for while
5491 if(goInfo->goober.spellId) // spell
5493 if(!sSpellStore.LookupEntry(goInfo->goober.spellId))
5494 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but Spell (Entry %u) not exist.",
5495 id,goInfo->type,goInfo->goober.spellId,goInfo->goober.spellId);
5498 if(goInfo->goober.linkedTrapId) // linked trap
5500 if(GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(goInfo->goober.linkedTrapId))
5502 if(trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5503 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data12=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5504 id,goInfo->type,goInfo->goober.linkedTrapId,goInfo->goober.linkedTrapId,GAMEOBJECT_TYPE_TRAP);
5506 /* disable check for while
5507 else
5508 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data12=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5509 id,goInfo->type,goInfo->goober.linkedTrapId,goInfo->goober.linkedTrapId);
5512 break;
5514 case GAMEOBJECT_TYPE_MO_TRANSPORT: //15
5516 if(goInfo->moTransport.taxiPathId)
5518 if(goInfo->moTransport.taxiPathId >= sTaxiPathNodesByPath.size() || sTaxiPathNodesByPath[goInfo->moTransport.taxiPathId].empty())
5519 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but TaxiPath (Id: %u) not exist.",
5520 id,goInfo->type,goInfo->moTransport.taxiPathId,goInfo->moTransport.taxiPathId);
5522 break;
5524 case GAMEOBJECT_TYPE_SUMMONING_RITUAL: //18
5526 /* disabled
5527 if(goInfo->summoningRitual.spellId)
5529 if(!sSpellStore.LookupEntry(goInfo->summoningRitual.spellId))
5530 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but Spell (Entry %u) not exist.",
5531 id,goInfo->type,goInfo->summoningRitual.spellId,goInfo->summoningRitual.spellId);
5534 break;
5536 case GAMEOBJECT_TYPE_SPELLCASTER: //22
5538 if(goInfo->spellcaster.spellId) // spell
5540 if(!sSpellStore.LookupEntry(goInfo->spellcaster.spellId))
5541 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data3=%u but Spell (Entry %u) not exist.",
5542 id,goInfo->type,goInfo->spellcaster.spellId,goInfo->spellcaster.spellId);
5544 break;
5549 sLog.outString( ">> Loaded %u game object templates", sGOStorage.RecordCount );
5550 sLog.outString();
5553 void ObjectMgr::LoadExplorationBaseXP()
5555 uint32 count = 0;
5556 QueryResult *result = WorldDatabase.Query("SELECT level,basexp FROM exploration_basexp");
5558 if( !result )
5560 barGoLink bar( 1 );
5562 bar.step();
5564 sLog.outString();
5565 sLog.outString( ">> Loaded %u BaseXP definitions", count );
5566 return;
5569 barGoLink bar( result->GetRowCount() );
5573 bar.step();
5575 Field *fields = result->Fetch();
5576 uint32 level = fields[0].GetUInt32();
5577 uint32 basexp = fields[1].GetUInt32();
5578 mBaseXPTable[level] = basexp;
5579 ++count;
5581 while (result->NextRow());
5583 delete result;
5585 sLog.outString();
5586 sLog.outString( ">> Loaded %u BaseXP definitions", count );
5589 uint32 ObjectMgr::GetBaseXP(uint32 level)
5591 return mBaseXPTable[level] ? mBaseXPTable[level] : 0;
5594 void ObjectMgr::LoadPetNames()
5596 uint32 count = 0;
5597 QueryResult *result = WorldDatabase.Query("SELECT word,entry,half FROM pet_name_generation");
5599 if( !result )
5601 barGoLink bar( 1 );
5603 bar.step();
5605 sLog.outString();
5606 sLog.outString( ">> Loaded %u pet name parts", count );
5607 return;
5610 barGoLink bar( result->GetRowCount() );
5614 bar.step();
5616 Field *fields = result->Fetch();
5617 std::string word = fields[0].GetString();
5618 uint32 entry = fields[1].GetUInt32();
5619 bool half = fields[2].GetBool();
5620 if(half)
5621 PetHalfName1[entry].push_back(word);
5622 else
5623 PetHalfName0[entry].push_back(word);
5624 ++count;
5626 while (result->NextRow());
5627 delete result;
5629 sLog.outString();
5630 sLog.outString( ">> Loaded %u pet name parts", count );
5633 void ObjectMgr::LoadPetNumber()
5635 QueryResult* result = CharacterDatabase.Query("SELECT MAX(id) FROM character_pet");
5636 if(result)
5638 Field *fields = result->Fetch();
5639 m_hiPetNumber = fields[0].GetUInt32()+1;
5640 delete result;
5643 barGoLink bar( 1 );
5644 bar.step();
5646 sLog.outString();
5647 sLog.outString( ">> Loaded the max pet number: %d", m_hiPetNumber-1);
5650 std::string ObjectMgr::GeneratePetName(uint32 entry)
5652 std::vector<std::string> & list0 = PetHalfName0[entry];
5653 std::vector<std::string> & list1 = PetHalfName1[entry];
5655 if(list0.empty() || list1.empty())
5657 CreatureInfo const *cinfo = GetCreatureTemplate(entry);
5658 char* petname = GetPetName(cinfo->family, sWorld.GetDefaultDbcLocale());
5659 if(!petname)
5660 petname = cinfo->Name;
5661 return std::string(petname);
5664 return *(list0.begin()+urand(0, list0.size()-1)) + *(list1.begin()+urand(0, list1.size()-1));
5667 uint32 ObjectMgr::GeneratePetNumber()
5669 return ++m_hiPetNumber;
5672 void ObjectMgr::LoadCorpses()
5674 uint32 count = 0;
5675 // 0 1 2 3 4 5 6 7 8 10
5676 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");
5678 if( !result )
5680 barGoLink bar( 1 );
5682 bar.step();
5684 sLog.outString();
5685 sLog.outString( ">> Loaded %u corpses", count );
5686 return;
5689 barGoLink bar( result->GetRowCount() );
5693 bar.step();
5695 Field *fields = result->Fetch();
5697 uint32 guid = fields[result->GetFieldCount()-1].GetUInt32();
5699 Corpse *corpse = new Corpse;
5700 if(!corpse->LoadFromDB(guid,fields))
5702 delete corpse;
5703 continue;
5706 ObjectAccessor::Instance().AddCorpse(corpse);
5708 ++count;
5710 while (result->NextRow());
5711 delete result;
5713 sLog.outString();
5714 sLog.outString( ">> Loaded %u corpses", count );
5717 void ObjectMgr::LoadReputationOnKill()
5719 uint32 count = 0;
5721 // 0 1 2
5722 QueryResult *result = WorldDatabase.Query("SELECT creature_id, RewOnKillRepFaction1, RewOnKillRepFaction2,"
5723 // 3 4 5 6 7 8 9
5724 "IsTeamAward1, MaxStanding1, RewOnKillRepValue1, IsTeamAward2, MaxStanding2, RewOnKillRepValue2, TeamDependent "
5725 "FROM creature_onkill_reputation");
5727 if(!result)
5729 barGoLink bar(1);
5731 bar.step();
5733 sLog.outString();
5734 sLog.outErrorDb(">> Loaded 0 creature award reputation definitions. DB table `creature_onkill_reputation` is empty.");
5735 return;
5738 barGoLink bar(result->GetRowCount());
5742 Field *fields = result->Fetch();
5743 bar.step();
5745 uint32 creature_id = fields[0].GetUInt32();
5747 ReputationOnKillEntry repOnKill;
5748 repOnKill.repfaction1 = fields[1].GetUInt32();
5749 repOnKill.repfaction2 = fields[2].GetUInt32();
5750 repOnKill.is_teamaward1 = fields[3].GetBool();
5751 repOnKill.reputation_max_cap1 = fields[4].GetUInt32();
5752 repOnKill.repvalue1 = fields[5].GetInt32();
5753 repOnKill.is_teamaward2 = fields[6].GetBool();
5754 repOnKill.reputation_max_cap2 = fields[7].GetUInt32();
5755 repOnKill.repvalue2 = fields[8].GetInt32();
5756 repOnKill.team_dependent = fields[9].GetUInt8();
5758 if(!GetCreatureTemplate(creature_id))
5760 sLog.outErrorDb("Table `creature_onkill_reputation` have data for not existed creature entry (%u), skipped",creature_id);
5761 continue;
5764 if(repOnKill.repfaction1)
5766 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(repOnKill.repfaction1);
5767 if(!factionEntry1)
5769 sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction1);
5770 continue;
5774 if(repOnKill.repfaction2)
5776 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(repOnKill.repfaction2);
5777 if(!factionEntry2)
5779 sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction2);
5780 continue;
5784 mRepOnKill[creature_id] = repOnKill;
5786 ++count;
5787 } while (result->NextRow());
5789 delete result;
5791 sLog.outString();
5792 sLog.outString(">> Loaded %u creature award reputation definitions", count);
5795 void ObjectMgr::LoadWeatherZoneChances()
5797 uint32 count = 0;
5799 // 0 1 2 3 4 5 6 7 8 9 10 11 12
5800 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");
5802 if(!result)
5804 barGoLink bar(1);
5806 bar.step();
5808 sLog.outString();
5809 sLog.outErrorDb(">> Loaded 0 weather definitions. DB table `game_weather` is empty.");
5810 return;
5813 barGoLink bar(result->GetRowCount());
5817 Field *fields = result->Fetch();
5818 bar.step();
5820 uint32 zone_id = fields[0].GetUInt32();
5822 WeatherZoneChances& wzc = mWeatherZoneMap[zone_id];
5824 for(int season = 0; season < WEATHER_SEASONS; ++season)
5826 wzc.data[season].rainChance = fields[season * (MAX_WEATHER_TYPE-1) + 1].GetUInt32();
5827 wzc.data[season].snowChance = fields[season * (MAX_WEATHER_TYPE-1) + 2].GetUInt32();
5828 wzc.data[season].stormChance = fields[season * (MAX_WEATHER_TYPE-1) + 3].GetUInt32();
5830 if(wzc.data[season].rainChance > 100)
5832 wzc.data[season].rainChance = 25;
5833 sLog.outErrorDb("Weather for zone %u season %u has wrong rain chance > 100%",zone_id,season);
5836 if(wzc.data[season].snowChance > 100)
5838 wzc.data[season].snowChance = 25;
5839 sLog.outErrorDb("Weather for zone %u season %u has wrong snow chance > 100%",zone_id,season);
5842 if(wzc.data[season].stormChance > 100)
5844 wzc.data[season].stormChance = 25;
5845 sLog.outErrorDb("Weather for zone %u season %u has wrong storm chance > 100%",zone_id,season);
5849 ++count;
5850 } while (result->NextRow());
5852 delete result;
5854 sLog.outString();
5855 sLog.outString(">> Loaded %u weather definitions", count);
5858 void ObjectMgr::SaveCreatureRespawnTime(uint32 loguid, uint32 instance, time_t t)
5860 mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
5861 WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
5862 if(t)
5863 WorldDatabase.PExecute("INSERT INTO creature_respawn VALUES ( '%u', '" I64FMTD "', '%u' )", loguid, uint64(t), instance);
5866 void ObjectMgr::DeleteCreatureData(uint32 guid)
5868 // remove mapid*cellid -> guid_set map
5869 CreatureData const* data = GetCreatureData(guid);
5870 if(data)
5871 RemoveCreatureFromGrid(guid, data);
5873 mCreatureDataMap.erase(guid);
5876 void ObjectMgr::SaveGORespawnTime(uint32 loguid, uint32 instance, time_t t)
5878 mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
5879 WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
5880 if(t)
5881 WorldDatabase.PExecute("INSERT INTO gameobject_respawn VALUES ( '%u', '" I64FMTD "', '%u' )", loguid, uint64(t), instance);
5884 void ObjectMgr::DeleteRespawnTimeForInstance(uint32 instance)
5886 RespawnTimes::iterator next;
5888 for(RespawnTimes::iterator itr = mGORespawnTimes.begin(); itr != mGORespawnTimes.end(); itr = next)
5890 next = itr;
5891 ++next;
5893 if(GUID_HIPART(itr->first)==instance)
5894 mGORespawnTimes.erase(itr);
5897 for(RespawnTimes::iterator itr = mCreatureRespawnTimes.begin(); itr != mCreatureRespawnTimes.end(); itr = next)
5899 next = itr;
5900 ++next;
5902 if(GUID_HIPART(itr->first)==instance)
5903 mCreatureRespawnTimes.erase(itr);
5906 WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE instance = '%u'", instance);
5907 WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE instance = '%u'", instance);
5910 void ObjectMgr::DeleteGOData(uint32 guid)
5912 // remove mapid*cellid -> guid_set map
5913 GameObjectData const* data = GetGOData(guid);
5914 if(data)
5915 RemoveGameobjectFromGrid(guid, data);
5917 mGameObjectDataMap.erase(guid);
5920 void ObjectMgr::AddCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid, uint32 instance)
5922 // corpses are always added to spawn mode 0 and they are spawned by their instance id
5923 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
5924 cell_guids.corpses[player_guid] = instance;
5927 void ObjectMgr::DeleteCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid)
5929 // corpses are always added to spawn mode 0 and they are spawned by their instance id
5930 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
5931 cell_guids.corpses.erase(player_guid);
5934 void ObjectMgr::LoadQuestRelationsHelper(QuestRelations& map,char const* table)
5936 map.clear(); // need for reload case
5938 uint32 count = 0;
5940 QueryResult *result = WorldDatabase.PQuery("SELECT id,quest FROM %s",table);
5942 if(!result)
5944 barGoLink bar(1);
5946 bar.step();
5948 sLog.outString();
5949 sLog.outErrorDb(">> Loaded 0 quest relations from %s. DB table `%s` is empty.",table,table);
5950 return;
5953 barGoLink bar(result->GetRowCount());
5957 Field *fields = result->Fetch();
5958 bar.step();
5960 uint32 id = fields[0].GetUInt32();
5961 uint32 quest = fields[1].GetUInt32();
5963 if(mQuestTemplates.find(quest) == mQuestTemplates.end())
5965 sLog.outErrorDb("Table `%s: Quest %u listed for entry %u does not exist.",table,quest,id);
5966 continue;
5969 map.insert(QuestRelations::value_type(id,quest));
5971 ++count;
5972 } while (result->NextRow());
5974 delete result;
5976 sLog.outString();
5977 sLog.outString(">> Loaded %u quest relations from %s", count,table);
5980 void ObjectMgr::LoadGameobjectQuestRelations()
5982 LoadQuestRelationsHelper(mGOQuestRelations,"gameobject_questrelation");
5984 for(QuestRelations::iterator itr = mGOQuestRelations.begin(); itr != mGOQuestRelations.end(); ++itr)
5986 GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
5987 if(!goInfo)
5988 sLog.outErrorDb("Table `gameobject_questrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
5989 else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
5990 sLog.outErrorDb("Table `gameobject_questrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
5994 void ObjectMgr::LoadGameobjectInvolvedRelations()
5996 LoadQuestRelationsHelper(mGOQuestInvolvedRelations,"gameobject_involvedrelation");
5998 for(QuestRelations::iterator itr = mGOQuestInvolvedRelations.begin(); itr != mGOQuestInvolvedRelations.end(); ++itr)
6000 GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
6001 if(!goInfo)
6002 sLog.outErrorDb("Table `gameobject_involvedrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
6003 else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
6004 sLog.outErrorDb("Table `gameobject_involvedrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
6008 void ObjectMgr::LoadCreatureQuestRelations()
6010 LoadQuestRelationsHelper(mCreatureQuestRelations,"creature_questrelation");
6012 for(QuestRelations::iterator itr = mCreatureQuestRelations.begin(); itr != mCreatureQuestRelations.end(); ++itr)
6014 CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
6015 if(!cInfo)
6016 sLog.outErrorDb("Table `creature_questrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
6017 else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
6018 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);
6022 void ObjectMgr::LoadCreatureInvolvedRelations()
6024 LoadQuestRelationsHelper(mCreatureQuestInvolvedRelations,"creature_involvedrelation");
6026 for(QuestRelations::iterator itr = mCreatureQuestInvolvedRelations.begin(); itr != mCreatureQuestInvolvedRelations.end(); ++itr)
6028 CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
6029 if(!cInfo)
6030 sLog.outErrorDb("Table `creature_involvedrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
6031 else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
6032 sLog.outErrorDb("Table `creature_involvedrelation` has creature entry (%u) for quest %u, but npcflag does not include UNIT_NPC_FLAG_QUESTGIVER",itr->first,itr->second);
6036 void ObjectMgr::LoadReservedPlayersNames()
6038 m_ReservedNames.clear(); // need for reload case
6040 QueryResult *result = WorldDatabase.Query("SELECT name FROM reserved_name");
6042 uint32 count = 0;
6044 if( !result )
6046 barGoLink bar( 1 );
6047 bar.step();
6049 sLog.outString();
6050 sLog.outString( ">> Loaded %u reserved player names", count );
6051 return;
6054 barGoLink bar( result->GetRowCount() );
6056 Field* fields;
6059 bar.step();
6060 fields = result->Fetch();
6061 std::string name= fields[0].GetCppString();
6062 if(normalizePlayerName(name))
6064 m_ReservedNames.insert(name);
6065 ++count;
6067 } while ( result->NextRow() );
6069 delete result;
6071 sLog.outString();
6072 sLog.outString( ">> Loaded %u reserved player names", count );
6075 enum LanguageType
6077 LT_BASIC_LATIN = 0x0000,
6078 LT_EXTENDEN_LATIN = 0x0001,
6079 LT_CYRILLIC = 0x0002,
6080 LT_EAST_ASIA = 0x0004,
6081 LT_ANY = 0xFFFF
6084 static LanguageType GetRealmLanguageType(bool create)
6086 switch(sWorld.getConfig(CONFIG_REALM_ZONE))
6088 case REALM_ZONE_UNKNOWN: // any language
6089 case REALM_ZONE_DEVELOPMENT:
6090 case REALM_ZONE_TEST_SERVER:
6091 case REALM_ZONE_QA_SERVER:
6092 return LT_ANY;
6093 case REALM_ZONE_UNITED_STATES: // extended-Latin
6094 case REALM_ZONE_OCEANIC:
6095 case REALM_ZONE_LATIN_AMERICA:
6096 case REALM_ZONE_ENGLISH:
6097 case REALM_ZONE_GERMAN:
6098 case REALM_ZONE_FRENCH:
6099 case REALM_ZONE_SPANISH:
6100 return LT_EXTENDEN_LATIN;
6101 case REALM_ZONE_KOREA: // East-Asian
6102 case REALM_ZONE_TAIWAN:
6103 case REALM_ZONE_CHINA:
6104 return LT_EAST_ASIA;
6105 case REALM_ZONE_RUSSIAN: // Cyrillic
6106 return LT_CYRILLIC;
6107 default:
6108 return create ? LT_BASIC_LATIN : LT_ANY; // basic-Latin at create, any at login
6112 bool isValidString(std::wstring wstr, uint32 strictMask, bool numericOrSpace, bool create = false)
6114 if(strictMask==0) // any language, ignore realm
6116 if(isExtendedLatinString(wstr,numericOrSpace))
6117 return true;
6118 if(isCyrillicString(wstr,numericOrSpace))
6119 return true;
6120 if(isEastAsianString(wstr,numericOrSpace))
6121 return true;
6122 return false;
6125 if(strictMask & 0x2) // realm zone specific
6127 LanguageType lt = GetRealmLanguageType(create);
6128 if(lt & LT_EXTENDEN_LATIN)
6129 if(isExtendedLatinString(wstr,numericOrSpace))
6130 return true;
6131 if(lt & LT_CYRILLIC)
6132 if(isCyrillicString(wstr,numericOrSpace))
6133 return true;
6134 if(lt & LT_EAST_ASIA)
6135 if(isEastAsianString(wstr,numericOrSpace))
6136 return true;
6139 if(strictMask & 0x1) // basic Latin
6141 if(isBasicLatinString(wstr,numericOrSpace))
6142 return true;
6145 return false;
6148 bool ObjectMgr::IsValidName( const std::string& name, bool create )
6150 std::wstring wname;
6151 if(!Utf8toWStr(name,wname))
6152 return false;
6154 if(wname.size() < 1 || wname.size() > MAX_PLAYER_NAME)
6155 return false;
6157 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_PLAYER_NAMES);
6159 return isValidString(wname,strictMask,false,create);
6162 bool ObjectMgr::IsValidCharterName( const std::string& name )
6164 std::wstring wname;
6165 if(!Utf8toWStr(name,wname))
6166 return false;
6168 if(wname.size() < 1)
6169 return false;
6171 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_CHARTER_NAMES);
6173 return isValidString(wname,strictMask,true);
6176 bool ObjectMgr::IsValidPetName( const std::string& name )
6178 std::wstring wname;
6179 if(!Utf8toWStr(name,wname))
6180 return false;
6182 if(wname.size() < 1)
6183 return false;
6185 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_PET_NAMES);
6187 return isValidString(wname,strictMask,false);
6190 int ObjectMgr::GetIndexForLocale( LocaleConstant loc )
6192 if(loc==LOCALE_enUS)
6193 return -1;
6195 for(size_t i=0;i < m_LocalForIndex.size(); ++i)
6196 if(m_LocalForIndex[i]==loc)
6197 return i;
6199 return -1;
6202 LocaleConstant ObjectMgr::GetLocaleForIndex(int i)
6204 if (i<0 || i>=m_LocalForIndex.size())
6205 return LOCALE_enUS;
6207 return m_LocalForIndex[i];
6210 int ObjectMgr::GetOrNewIndexForLocale( LocaleConstant loc )
6212 if(loc==LOCALE_enUS)
6213 return -1;
6215 for(size_t i=0;i < m_LocalForIndex.size(); ++i)
6216 if(m_LocalForIndex[i]==loc)
6217 return i;
6219 m_LocalForIndex.push_back(loc);
6220 return m_LocalForIndex.size()-1;
6223 void ObjectMgr::LoadBattleMastersEntry()
6225 mBattleMastersMap.clear(); // need for reload case
6227 QueryResult *result = WorldDatabase.Query( "SELECT entry,bg_template FROM battlemaster_entry" );
6229 uint32 count = 0;
6231 if( !result )
6233 barGoLink bar( 1 );
6234 bar.step();
6236 sLog.outString();
6237 sLog.outString( ">> Loaded 0 battlemaster entries - table is empty!" );
6238 return;
6241 barGoLink bar( result->GetRowCount() );
6245 ++count;
6246 bar.step();
6248 Field *fields = result->Fetch();
6250 uint32 entry = fields[0].GetUInt32();
6251 uint32 bgTypeId = fields[1].GetUInt32();
6253 mBattleMastersMap[entry] = bgTypeId;
6255 } while( result->NextRow() );
6257 delete result;
6259 sLog.outString();
6260 sLog.outString( ">> Loaded %u battlemaster entries", count );
6263 void ObjectMgr::LoadGameObjectForQuests()
6265 mGameObjectForQuestSet.clear(); // need for reload case
6267 uint32 count = 0;
6269 // collect GO entries for GO that must activated
6270 for(uint32 go_entry = 1; go_entry < sGOStorage.MaxEntry; ++go_entry)
6272 GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(go_entry);
6273 if(!goInfo)
6274 continue;
6276 switch(goInfo->type)
6278 // scan GO chest with loot including quest items
6279 case GAMEOBJECT_TYPE_CHEST:
6281 uint32 loot_id = GameObject::GetLootId(goInfo);
6283 // find quest loot for GO
6284 if(LootTemplates_Gameobject.HaveQuestLootFor(loot_id))
6286 mGameObjectForQuestSet.insert(go_entry);
6287 ++count;
6289 break;
6291 case GAMEOBJECT_TYPE_GOOBER:
6293 if(goInfo->goober.questId) //quests objects
6295 mGameObjectForQuestSet.insert(go_entry);
6296 count++;
6298 break;
6300 default:
6301 break;
6305 sLog.outString();
6306 sLog.outString( ">> Loaded %u GameObject for quests", count );
6309 bool ObjectMgr::LoadMangosStrings(DatabaseType& db, char const* table, int32 min_value, int32 max_value)
6311 // cleanup affected map part for reloading case
6312 for(MangosStringLocaleMap::iterator itr = mMangosStringLocaleMap.begin(); itr != mMangosStringLocaleMap.end();)
6314 if(itr->first >= min_value && itr->first <= max_value)
6316 MangosStringLocaleMap::iterator itr2 = itr;
6317 ++itr;
6318 mMangosStringLocaleMap.erase(itr2);
6320 else
6321 ++itr;
6324 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);
6326 if(!result)
6328 barGoLink bar(1);
6330 bar.step();
6332 sLog.outString("");
6333 if(min_value == MIN_MANGOS_STRING_ID) // error only in case internal strings
6334 sLog.outErrorDb(">> Loaded 0 mangos strings. DB table `%s` is empty. Cannot continue.",table);
6335 else
6336 sLog.outString(">> Loaded 0 string templates. DB table `%s` is empty.",table);
6337 return false;
6340 uint32 count = 0;
6342 barGoLink bar(result->GetRowCount());
6346 Field *fields = result->Fetch();
6347 bar.step();
6349 int32 entry = fields[0].GetInt32();
6351 if(entry==0)
6353 sLog.outErrorDb("Table `%s` contain reserved entry 0, ignored.",table);
6354 continue;
6356 else if(entry < min_value || entry > max_value)
6358 int32 start = min_value > 0 ? min_value : max_value;
6359 int32 end = min_value > 0 ? max_value : min_value;
6360 sLog.outErrorDb("Table `%s` contain entry %i out of allowed range (%d - %d), ignored.",table,entry,start,end);
6361 continue;
6364 MangosStringLocale& data = mMangosStringLocaleMap[entry];
6366 if(data.Content.size() > 0)
6368 sLog.outErrorDb("Table `%s` contain data for already loaded entry %i (from another table?), ignored.",table,entry);
6369 continue;
6372 data.Content.resize(1);
6373 ++count;
6375 // 0 -> default, idx in to idx+1
6376 data.Content[0] = fields[1].GetCppString();
6378 for(int i = 1; i < MAX_LOCALE; ++i)
6380 std::string str = fields[i+1].GetCppString();
6381 if(!str.empty())
6383 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
6384 if(idx >= 0)
6386 // 0 -> default, idx in to idx+1
6387 if(data.Content.size() <= idx+1)
6388 data.Content.resize(idx+2);
6390 data.Content[idx+1] = str;
6394 } while (result->NextRow());
6396 delete result;
6398 sLog.outString();
6399 if(min_value == MIN_MANGOS_STRING_ID) // error only in case internal strings
6400 sLog.outString( ">> Loaded %u MaNGOS strings from table %s", count,table);
6401 else
6402 sLog.outString( ">> Loaded %u string templates from %s", count,table);
6404 return true;
6407 const char *ObjectMgr::GetMangosString(int32 entry, int locale_idx) const
6409 // locale_idx==-1 -> default, locale_idx >= 0 in to idx+1
6410 // Content[0] always exist if exist MangosStringLocale
6411 if(MangosStringLocale const *msl = GetMangosStringLocale(entry))
6413 if(msl->Content.size() > locale_idx+1 && !msl->Content[locale_idx+1].empty())
6414 return msl->Content[locale_idx+1].c_str();
6415 else
6416 return msl->Content[0].c_str();
6419 if(entry > 0)
6420 sLog.outErrorDb("Entry %i not found in `mangos_string` table.",entry);
6421 else
6422 sLog.outErrorDb("Mangos string entry %i not found in DB.",entry);
6423 return "<error>";
6426 void ObjectMgr::LoadFishingBaseSkillLevel()
6428 mFishingBaseForArea.clear(); // for reload case
6430 uint32 count = 0;
6431 QueryResult *result = WorldDatabase.Query("SELECT entry,skill FROM skill_fishing_base_level");
6433 if( !result )
6435 barGoLink bar( 1 );
6437 bar.step();
6439 sLog.outString();
6440 sLog.outErrorDb(">> Loaded `skill_fishing_base_level`, table is empty!");
6441 return;
6444 barGoLink bar( result->GetRowCount() );
6448 bar.step();
6450 Field *fields = result->Fetch();
6451 uint32 entry = fields[0].GetUInt32();
6452 int32 skill = fields[1].GetInt32();
6454 AreaTableEntry const* fArea = GetAreaEntryByAreaID(entry);
6455 if(!fArea)
6457 sLog.outErrorDb("AreaId %u defined in `skill_fishing_base_level` does not exist",entry);
6458 continue;
6461 mFishingBaseForArea[entry] = skill;
6462 ++count;
6464 while (result->NextRow());
6466 delete result;
6468 sLog.outString();
6469 sLog.outString( ">> Loaded %u areas for fishing base skill level", count );
6472 // Searches for the same condition already in Conditions store
6473 // Returns Id if found, else adds it to Conditions and returns Id
6474 uint16 ObjectMgr::GetConditionId( ConditionType condition, uint32 value1, uint32 value2 )
6476 PlayerCondition lc = PlayerCondition(condition, value1, value2);
6477 for (uint16 i=0; i < mConditions.size(); ++i)
6479 if (lc == mConditions[i])
6480 return i;
6483 mConditions.push_back(lc);
6485 if(mConditions.size() > 0xFFFF)
6487 sLog.outError("Conditions store overflow! Current and later loaded conditions will ignored!");
6488 return 0;
6491 return mConditions.size() - 1;
6494 bool ObjectMgr::CheckDeclinedNames( std::wstring mainpart, DeclinedName const& names )
6496 for(int i =0; i < MAX_DECLINED_NAME_CASES; ++i)
6498 std::wstring wname;
6499 if(!Utf8toWStr(names.name[i],wname))
6500 return false;
6502 if(mainpart!=GetMainPartOfName(wname,i+1))
6503 return false;
6505 return true;
6508 uint32 ObjectMgr::GetAreaTriggerScriptId(uint32 trigger_id)
6510 AreaTriggerScriptMap::const_iterator i = mAreaTriggerScripts.find(trigger_id);
6511 if(i!= mAreaTriggerScripts.end())
6512 return i->second;
6513 return 0;
6516 // Checks if player meets the condition
6517 bool PlayerCondition::Meets(Player const * player) const
6519 if( !player )
6520 return false; // player not present, return false
6522 switch (condition)
6524 case CONDITION_NONE:
6525 return true; // empty condition, always met
6526 case CONDITION_AURA:
6527 return player->HasAura(value1, value2);
6528 case CONDITION_ITEM:
6529 return player->HasItemCount(value1, value2);
6530 case CONDITION_ITEM_EQUIPPED:
6531 return player->GetItemOrItemWithGemEquipped(value1) != NULL;
6532 case CONDITION_ZONEID:
6533 return player->GetZoneId() == value1;
6534 case CONDITION_REPUTATION_RANK:
6536 FactionEntry const* faction = sFactionStore.LookupEntry(value1);
6537 return faction && player->GetReputationRank(faction) >= value2;
6539 case CONDITION_TEAM:
6540 return player->GetTeam() == value1;
6541 case CONDITION_SKILL:
6542 return player->HasSkill(value1) && player->GetBaseSkillValue(value1) >= value2;
6543 case CONDITION_QUESTREWARDED:
6544 return player->GetQuestRewardStatus(value1);
6545 case CONDITION_QUESTTAKEN:
6547 QuestStatus status = player->GetQuestStatus(value1);
6548 return (status == QUEST_STATUS_INCOMPLETE);
6550 case CONDITION_AD_COMMISSION_AURA:
6552 Unit::AuraMap const& auras = player->GetAuras();
6553 for(Unit::AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
6554 if((itr->second->GetSpellProto()->Attributes & 0x1000010) && itr->second->GetSpellProto()->SpellVisual==3580)
6555 return true;
6556 return false;
6558 case CONDITION_NO_AURA:
6559 return !player->HasAura(value1, value2);
6560 case CONDITION_ACTIVE_EVENT:
6561 return gameeventmgr.IsActiveEvent(value1);
6562 default:
6563 return false;
6567 // Verification of condition values validity
6568 bool PlayerCondition::IsValid(ConditionType condition, uint32 value1, uint32 value2)
6570 if( condition >= MAX_CONDITION) // Wrong condition type
6572 sLog.outErrorDb("Condition has bad type of %u, skipped ", condition );
6573 return false;
6576 switch (condition)
6578 case CONDITION_AURA:
6580 if(!sSpellStore.LookupEntry(value1))
6582 sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
6583 return false;
6585 if(value2 > 2)
6587 sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..2), skipped", value2);
6588 return false;
6590 break;
6592 case CONDITION_ITEM:
6594 ItemPrototype const *proto = objmgr.GetItemPrototype(value1);
6595 if(!proto)
6597 sLog.outErrorDb("Item condition requires to have non existing item (%u), skipped", value1);
6598 return false;
6600 break;
6602 case CONDITION_ITEM_EQUIPPED:
6604 ItemPrototype const *proto = objmgr.GetItemPrototype(value1);
6605 if(!proto)
6607 sLog.outErrorDb("ItemEquipped condition requires to have non existing item (%u) equipped, skipped", value1);
6608 return false;
6610 break;
6612 case CONDITION_ZONEID:
6614 AreaTableEntry const* areaEntry = GetAreaEntryByAreaID(value1);
6615 if(!areaEntry)
6617 sLog.outErrorDb("Zone condition requires to be in non existing area (%u), skipped", value1);
6618 return false;
6620 if(areaEntry->zone != 0)
6622 sLog.outErrorDb("Zone condition requires to be in area (%u) which is a subzone but zone expected, skipped", value1);
6623 return false;
6625 break;
6627 case CONDITION_REPUTATION_RANK:
6629 FactionEntry const* factionEntry = sFactionStore.LookupEntry(value1);
6630 if(!factionEntry)
6632 sLog.outErrorDb("Reputation condition requires to have reputation non existing faction (%u), skipped", value1);
6633 return false;
6635 break;
6637 case CONDITION_TEAM:
6639 if (value1 != ALLIANCE && value1 != HORDE)
6641 sLog.outErrorDb("Team condition specifies unknown team (%u), skipped", value1);
6642 return false;
6644 break;
6646 case CONDITION_SKILL:
6648 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(value1);
6649 if (!pSkill)
6651 sLog.outErrorDb("Skill condition specifies non-existing skill (%u), skipped", value1);
6652 return false;
6654 if (value2 < 1 || value2 > sWorld.GetConfigMaxSkillValue() )
6656 sLog.outErrorDb("Skill condition specifies invalid skill value (%u), skipped", value2);
6657 return false;
6659 break;
6661 case CONDITION_QUESTREWARDED:
6662 case CONDITION_QUESTTAKEN:
6664 Quest const *Quest = objmgr.GetQuestTemplate(value1);
6665 if (!Quest)
6667 sLog.outErrorDb("Quest condition specifies non-existing quest (%u), skipped", value1);
6668 return false;
6670 if(value2)
6671 sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
6672 break;
6674 case CONDITION_AD_COMMISSION_AURA:
6676 if(value1)
6677 sLog.outErrorDb("Quest condition has useless data in value1 (%u)!", value1);
6678 if(value2)
6679 sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
6680 break;
6682 case CONDITION_NO_AURA:
6684 if(!sSpellStore.LookupEntry(value1))
6686 sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
6687 return false;
6689 if(value2 > 2)
6691 sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..2), skipped", value2);
6692 return false;
6694 break;
6696 case CONDITION_ACTIVE_EVENT:
6698 GameEvent::GameEventDataMap const& events = gameeventmgr.GetEventMap();
6699 if(value1 >=events.size() || !events[value1].isValid())
6701 sLog.outErrorDb("Active event condition requires existed event id (%u), skipped", value1);
6702 return false;
6704 break;
6707 return true;
6710 SkillRangeType GetSkillRangeType(SkillLineEntry const *pSkill, bool racial)
6712 switch(pSkill->categoryId)
6714 case SKILL_CATEGORY_LANGUAGES: return SKILL_RANGE_LANGUAGE;
6715 case SKILL_CATEGORY_WEAPON:
6716 if(pSkill->id!=SKILL_FIST_WEAPONS)
6717 return SKILL_RANGE_LEVEL;
6718 else
6719 return SKILL_RANGE_MONO;
6720 case SKILL_CATEGORY_ARMOR:
6721 case SKILL_CATEGORY_CLASS:
6722 if(pSkill->id != SKILL_POISONS && pSkill->id != SKILL_LOCKPICKING)
6723 return SKILL_RANGE_MONO;
6724 else
6725 return SKILL_RANGE_LEVEL;
6726 case SKILL_CATEGORY_SECONDARY:
6727 case SKILL_CATEGORY_PROFESSION:
6728 // not set skills for professions and racial abilities
6729 if(IsProfessionSkill(pSkill->id))
6730 return SKILL_RANGE_RANK;
6731 else if(racial)
6732 return SKILL_RANGE_NONE;
6733 else
6734 return SKILL_RANGE_MONO;
6735 default:
6736 case SKILL_CATEGORY_ATTRIBUTES: //not found in dbc
6737 case SKILL_CATEGORY_NOT_DISPLAYED: //only GENEREC(DND)
6738 return SKILL_RANGE_NONE;
6742 void ObjectMgr::LoadGameTele()
6744 m_GameTeleMap.clear(); // for reload case
6746 uint32 count = 0;
6747 QueryResult *result = WorldDatabase.Query("SELECT id, position_x, position_y, position_z, orientation, map, name FROM game_tele");
6749 if( !result )
6751 barGoLink bar( 1 );
6753 bar.step();
6755 sLog.outString();
6756 sLog.outErrorDb(">> Loaded `game_tele`, table is empty!");
6757 return;
6760 barGoLink bar( result->GetRowCount() );
6764 bar.step();
6766 Field *fields = result->Fetch();
6768 uint32 id = fields[0].GetUInt32();
6770 GameTele gt;
6772 gt.position_x = fields[1].GetFloat();
6773 gt.position_y = fields[2].GetFloat();
6774 gt.position_z = fields[3].GetFloat();
6775 gt.orientation = fields[4].GetFloat();
6776 gt.mapId = fields[5].GetUInt32();
6777 gt.name = fields[6].GetCppString();
6779 if(!MapManager::IsValidMapCoord(gt.mapId,gt.position_x,gt.position_y,gt.position_z,gt.orientation))
6781 sLog.outErrorDb("Wrong position for id %u (name: %s) in `game_tele` table, ignoring.",id,gt.name.c_str());
6782 continue;
6785 if(!Utf8toWStr(gt.name,gt.wnameLow))
6787 sLog.outErrorDb("Wrong UTF8 name for id %u in `game_tele` table, ignoring.",id);
6788 continue;
6791 wstrToLower( gt.wnameLow );
6793 m_GameTeleMap[id] = gt;
6795 ++count;
6797 while (result->NextRow());
6799 delete result;
6801 sLog.outString();
6802 sLog.outString( ">> Loaded %u game tele's", count );
6805 GameTele const* ObjectMgr::GetGameTele(const std::string& name) const
6807 // explicit name case
6808 std::wstring wname;
6809 if(!Utf8toWStr(name,wname))
6810 return false;
6812 // converting string that we try to find to lower case
6813 wstrToLower( wname );
6815 // Alternative first GameTele what contains wnameLow as substring in case no GameTele location found
6816 const GameTele* alt = NULL;
6817 for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
6818 if(itr->second.wnameLow == wname)
6819 return &itr->second;
6820 else if (alt == NULL && itr->second.wnameLow.find(wname) != std::wstring::npos)
6821 alt = &itr->second;
6823 return alt;
6826 bool ObjectMgr::AddGameTele(GameTele& tele)
6828 // find max id
6829 uint32 new_id = 0;
6830 for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
6831 if(itr->first > new_id)
6832 new_id = itr->first;
6834 // use next
6835 ++new_id;
6837 if(!Utf8toWStr(tele.name,tele.wnameLow))
6838 return false;
6840 wstrToLower( tele.wnameLow );
6842 m_GameTeleMap[new_id] = tele;
6844 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')",
6845 new_id,tele.position_x,tele.position_y,tele.position_z,tele.orientation,tele.mapId,tele.name.c_str());
6848 bool ObjectMgr::DeleteGameTele(const std::string& name)
6850 // explicit name case
6851 std::wstring wname;
6852 if(!Utf8toWStr(name,wname))
6853 return false;
6855 // converting string that we try to find to lower case
6856 wstrToLower( wname );
6858 for(GameTeleMap::iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
6860 if(itr->second.wnameLow == wname)
6862 WorldDatabase.PExecuteLog("DELETE FROM game_tele WHERE name = '%s'",itr->second.name.c_str());
6863 m_GameTeleMap.erase(itr);
6864 return true;
6868 return false;
6871 void ObjectMgr::LoadTrainerSpell()
6873 // For reload case
6874 for (CacheTrainerSpellMap::iterator itr = m_mCacheTrainerSpellMap.begin(); itr != m_mCacheTrainerSpellMap.end(); ++itr)
6875 itr->second.Clear();
6876 m_mCacheTrainerSpellMap.clear();
6878 std::set<uint32> skip_trainers;
6880 QueryResult *result = WorldDatabase.Query("SELECT entry, spell,spellcost,reqskill,reqskillvalue,reqlevel FROM npc_trainer");
6882 if( !result )
6884 barGoLink bar( 1 );
6886 bar.step();
6888 sLog.outString();
6889 sLog.outErrorDb(">> Loaded `npc_trainer`, table is empty!");
6890 return;
6893 barGoLink bar( result->GetRowCount() );
6895 uint32 count = 0;
6898 bar.step();
6900 Field* fields = result->Fetch();
6902 uint32 entry = fields[0].GetUInt32();
6903 uint32 spell = fields[1].GetUInt32();
6905 CreatureInfo const* cInfo = GetCreatureTemplate(entry);
6907 if(!cInfo)
6909 sLog.outErrorDb("Table `npc_trainer` have entry for not existed creature template (Entry: %u), ignore", entry);
6910 continue;
6913 if(!(cInfo->npcflag & UNIT_NPC_FLAG_TRAINER))
6915 if(skip_trainers.count(entry) == 0)
6917 sLog.outErrorDb("Table `npc_trainer` have data for not creature template (Entry: %u) without trainer flag, ignore", entry);
6918 skip_trainers.insert(entry);
6920 continue;
6923 SpellEntry const *spellinfo = sSpellStore.LookupEntry(spell);
6924 if(!spellinfo)
6926 sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u ) has non existing spell %u, ignore", entry,spell);
6927 continue;
6930 if(!SpellMgr::IsSpellValid(spellinfo))
6932 sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u) has broken learning spell %u, ignore", entry, spell);
6933 continue;
6936 TrainerSpell* pTrainerSpell = new TrainerSpell();
6937 pTrainerSpell->spell = spell;
6938 pTrainerSpell->spellcost = fields[2].GetUInt32();
6939 pTrainerSpell->reqskill = fields[3].GetUInt32();
6940 pTrainerSpell->reqskillvalue = fields[4].GetUInt32();
6941 pTrainerSpell->reqlevel = fields[5].GetUInt32();
6943 if(!pTrainerSpell->reqlevel)
6944 pTrainerSpell->reqlevel = spellinfo->spellLevel;
6947 TrainerSpellData& data = m_mCacheTrainerSpellMap[entry];
6949 if(SpellMgr::IsProfessionSpell(spell))
6950 data.trainerType = 2;
6952 data.spellList.push_back(pTrainerSpell);
6953 ++count;
6955 } while (result->NextRow());
6956 delete result;
6958 sLog.outString();
6959 sLog.outString( ">> Loaded Trainers %d", count );
6962 void ObjectMgr::LoadVendors()
6964 // For reload case
6965 for (CacheVendorItemMap::iterator itr = m_mCacheVendorItemMap.begin(); itr != m_mCacheVendorItemMap.end(); ++itr)
6966 itr->second.Clear();
6967 m_mCacheVendorItemMap.clear();
6969 std::set<uint32> skip_vendors;
6971 QueryResult *result = WorldDatabase.Query("SELECT entry, item, maxcount, incrtime, ExtendedCost FROM npc_vendor");
6972 if( !result )
6974 barGoLink bar( 1 );
6976 bar.step();
6978 sLog.outString();
6979 sLog.outErrorDb(">> Loaded `npc_vendor`, table is empty!");
6980 return;
6983 barGoLink bar( result->GetRowCount() );
6985 uint32 count = 0;
6988 bar.step();
6989 Field* fields = result->Fetch();
6991 uint32 entry = fields[0].GetUInt32();
6992 uint32 item_id = fields[1].GetUInt32();
6993 uint32 maxcount = fields[2].GetUInt32();
6994 uint32 incrtime = fields[3].GetUInt32();
6995 uint32 ExtendedCost = fields[4].GetUInt32();
6997 if(!IsVendorItemValid(entry,item_id,maxcount,incrtime,ExtendedCost,NULL,&skip_vendors))
6998 continue;
7000 VendorItemData& vList = m_mCacheVendorItemMap[entry];
7002 vList.AddItem(item_id,maxcount,incrtime,ExtendedCost);
7003 ++count;
7005 } while (result->NextRow());
7006 delete result;
7008 sLog.outString();
7009 sLog.outString( ">> Loaded %d Vendors ", count );
7012 void ObjectMgr::LoadNpcTextId()
7015 m_mCacheNpcTextIdMap.clear();
7017 QueryResult* result = WorldDatabase.Query("SELECT npc_guid, textid FROM npc_gossip");
7018 if( !result )
7020 barGoLink bar( 1 );
7022 bar.step();
7024 sLog.outString();
7025 sLog.outErrorDb(">> Loaded `npc_gossip`, table is empty!");
7026 return;
7029 barGoLink bar( result->GetRowCount() );
7031 uint32 count = 0;
7032 uint32 guid,textid;
7035 bar.step();
7037 Field* fields = result->Fetch();
7039 guid = fields[0].GetUInt32();
7040 textid = fields[1].GetUInt32();
7042 if (!GetCreatureData(guid))
7044 sLog.outErrorDb("Table `npc_gossip` have not existed creature (GUID: %u) entry, ignore. ",guid);
7045 continue;
7047 if (!GetGossipText(textid))
7049 sLog.outErrorDb("Table `npc_gossip` for creature (GUID: %u) have wrong Textid (%u), ignore. ", guid, textid);
7050 continue;
7053 m_mCacheNpcTextIdMap[guid] = textid ;
7054 ++count;
7056 } while (result->NextRow());
7057 delete result;
7059 sLog.outString();
7060 sLog.outString( ">> Loaded %d NpcTextId ", count );
7063 void ObjectMgr::LoadNpcOptions()
7065 m_mCacheNpcOptionList.clear(); // For reload case
7067 QueryResult *result = WorldDatabase.Query(
7068 // 0 1 2 3 4 5 6 7 8
7069 "SELECT id,gossip_id,npcflag,icon,action,box_money,coded,option_text,box_text "
7070 "FROM npc_option");
7072 if( !result )
7074 barGoLink bar( 1 );
7076 bar.step();
7078 sLog.outString();
7079 sLog.outErrorDb(">> Loaded `npc_option`, table is empty!");
7080 return;
7083 barGoLink bar( result->GetRowCount() );
7085 uint32 count = 0;
7089 bar.step();
7091 Field* fields = result->Fetch();
7093 GossipOption go;
7094 go.Id = fields[0].GetUInt32();
7095 go.GossipId = fields[1].GetUInt32();
7096 go.NpcFlag = fields[2].GetUInt32();
7097 go.Icon = fields[3].GetUInt32();
7098 go.Action = fields[4].GetUInt32();
7099 go.BoxMoney = fields[5].GetUInt32();
7100 go.Coded = fields[6].GetUInt8()!=0;
7101 go.OptionText = fields[7].GetCppString();
7102 go.BoxText = fields[8].GetCppString();
7104 m_mCacheNpcOptionList.push_back(go);
7106 ++count;
7108 } while (result->NextRow());
7109 delete result;
7111 sLog.outString();
7112 sLog.outString( ">> Loaded %d npc_option entries", count );
7115 void ObjectMgr::AddVendorItem( uint32 entry,uint32 item, uint32 maxcount, uint32 incrtime, uint32 extendedcost )
7117 VendorItemData& vList = m_mCacheVendorItemMap[entry];
7118 vList.AddItem(item,maxcount,incrtime,extendedcost);
7120 WorldDatabase.PExecuteLog("INSERT INTO npc_vendor (entry,item,maxcount,incrtime,extendedcost) VALUES('%u','%u','%u','%u','%u')",entry, item, maxcount,incrtime,extendedcost);
7123 bool ObjectMgr::RemoveVendorItem( uint32 entry,uint32 item )
7125 CacheVendorItemMap::iterator iter = m_mCacheVendorItemMap.find(entry);
7126 if(iter == m_mCacheVendorItemMap.end())
7127 return false;
7129 if(!iter->second.FindItem(item))
7130 return false;
7132 iter->second.RemoveItem(item);
7133 WorldDatabase.PExecuteLog("DELETE FROM npc_vendor WHERE entry='%u' AND item='%u'",entry, item);
7134 return true;
7137 bool ObjectMgr::IsVendorItemValid( uint32 vendor_entry, uint32 item_id, uint32 maxcount, uint32 incrtime, uint32 ExtendedCost, Player* pl, std::set<uint32>* skip_vendors ) const
7139 CreatureInfo const* cInfo = GetCreatureTemplate(vendor_entry);
7140 if(!cInfo)
7142 if(pl)
7143 ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
7144 else
7145 sLog.outErrorDb("Table `npc_vendor` have data for not existed creature template (Entry: %u), ignore", vendor_entry);
7146 return false;
7149 if(!(cInfo->npcflag & UNIT_NPC_FLAG_VENDOR))
7151 if(!skip_vendors || skip_vendors->count(vendor_entry)==0)
7153 if(pl)
7154 ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION);
7155 else
7156 sLog.outErrorDb("Table `npc_vendor` have data for not creature template (Entry: %u) without vendor flag, ignore", vendor_entry);
7158 if(skip_vendors)
7159 skip_vendors->insert(vendor_entry);
7161 return false;
7164 if(!GetItemPrototype(item_id))
7166 if(pl)
7167 ChatHandler(pl).PSendSysMessage(LANG_ITEM_NOT_FOUND, item_id);
7168 else
7169 sLog.outErrorDb("Table `npc_vendor` for Vendor (Entry: %u) have in item list non-existed item (%u), ignore",vendor_entry,item_id);
7170 return false;
7173 if(ExtendedCost && !sItemExtendedCostStore.LookupEntry(ExtendedCost))
7175 if(pl)
7176 ChatHandler(pl).PSendSysMessage(LANG_EXTENDED_COST_NOT_EXIST,ExtendedCost);
7177 else
7178 sLog.outErrorDb("Table `npc_vendor` have Item (Entry: %u) with wrong ExtendedCost (%u) for vendor (%u), ignore",item_id,ExtendedCost,vendor_entry);
7179 return false;
7182 if(maxcount > 0 && incrtime == 0)
7184 if(pl)
7185 ChatHandler(pl).PSendSysMessage("MaxCount!=0 (%u) but IncrTime==0", maxcount);
7186 else
7187 sLog.outErrorDb( "Table `npc_vendor` has `maxcount` (%u) for item %u of vendor (Entry: %u) but `incrtime`=0, ignore", maxcount, item_id, vendor_entry);
7188 return false;
7190 else if(maxcount==0 && incrtime > 0)
7192 if(pl)
7193 ChatHandler(pl).PSendSysMessage("MaxCount==0 but IncrTime<>=0");
7194 else
7195 sLog.outErrorDb( "Table `npc_vendor` has `maxcount`=0 for item %u of vendor (Entry: %u) but `incrtime`<>0, ignore", item_id, vendor_entry);
7196 return false;
7199 VendorItemData const* vItems = GetNpcVendorItemList(vendor_entry);
7200 if(!vItems)
7201 return true; // later checks for non-empty lists
7203 if(vItems->FindItem(item_id))
7205 if(pl)
7206 ChatHandler(pl).PSendSysMessage(LANG_ITEM_ALREADY_IN_LIST,item_id);
7207 else
7208 sLog.outErrorDb( "Table `npc_vendor` has duplicate items %u for vendor (Entry: %u), ignore", item_id, vendor_entry);
7209 return false;
7212 if(vItems->GetItemCount() >= MAX_VENDOR_ITEMS)
7214 if(pl)
7215 ChatHandler(pl).SendSysMessage(LANG_COMMAND_ADDVENDORITEMITEMS);
7216 else
7217 sLog.outErrorDb( "Table `npc_vendor` has too many items (%u >= %i) for vendor (Entry: %u), ignore", vItems->GetItemCount(), MAX_VENDOR_ITEMS, vendor_entry);
7218 return false;
7221 return true;
7224 void ObjectMgr::LoadScriptNames()
7226 m_scriptNames.push_back("");
7227 QueryResult *result = WorldDatabase.Query(
7228 "SELECT DISTINCT(ScriptName) FROM creature_template WHERE ScriptName <> '' "
7229 "UNION "
7230 "SELECT DISTINCT(ScriptName) FROM gameobject_template WHERE ScriptName <> '' "
7231 "UNION "
7232 "SELECT DISTINCT(ScriptName) FROM item_template WHERE ScriptName <> '' "
7233 "UNION "
7234 "SELECT DISTINCT(ScriptName) FROM areatrigger_scripts WHERE ScriptName <> '' "
7235 "UNION "
7236 "SELECT DISTINCT(script) FROM instance_template WHERE script <> ''");
7237 if(result)
7241 m_scriptNames.push_back((*result)[0].GetString());
7242 } while (result->NextRow());
7243 delete result;
7246 std::sort(m_scriptNames.begin(), m_scriptNames.end());
7249 uint32 ObjectMgr::GetScriptId(const char *name)
7251 // use binary search to find the script name in the sorted vector
7252 // assume "" is the first element
7253 if(!name) return 0;
7254 ScriptNameMap::const_iterator itr =
7255 std::lower_bound(m_scriptNames.begin(), m_scriptNames.end(), name);
7256 if(itr == m_scriptNames.end() || *itr != name) return 0;
7257 return itr - m_scriptNames.begin();
7260 void ObjectMgr::CheckScripts(ScriptMapMap const& scripts,std::set<int32>& ids)
7262 for(ScriptMapMap::const_iterator itrMM = scripts.begin(); itrMM != scripts.end(); ++itrMM)
7264 for(ScriptMap::const_iterator itrM = itrMM->second.begin(); itrM != itrMM->second.end(); ++itrM)
7266 if(itrM->second.dataint)
7268 if(!GetMangosStringLocale (itrM->second.dataint))
7269 sLog.outErrorDb( "Table `db_script_string` has not existed string id %u", itrM->first);
7271 if(ids.count(itrM->second.dataint))
7272 ids.erase(itrM->second.dataint);
7278 void ObjectMgr::LoadDbScriptStrings()
7280 LoadMangosStrings(WorldDatabase,"db_script_string",MIN_DB_SCRIPT_STRING_ID,MAX_DB_SCRIPT_STRING_ID);
7282 std::set<int32> ids;
7284 for(int32 i = MIN_DB_SCRIPT_STRING_ID; i < MAX_DB_SCRIPT_STRING_ID; ++i)
7285 if(GetMangosStringLocale(i))
7286 ids.insert(i);
7288 CheckScripts(sQuestEndScripts,ids);
7289 CheckScripts(sQuestStartScripts,ids);
7290 CheckScripts(sSpellScripts,ids);
7291 CheckScripts(sGameObjectScripts,ids);
7292 CheckScripts(sEventScripts,ids);
7294 WaypointMgr.CheckTextsExistance(ids);
7296 for(std::set<int32>::const_iterator itr = ids.begin(); itr != ids.end(); ++itr)
7297 sLog.outErrorDb( "Table `db_script_string` has unused string id %u", *itr);
7300 // Functions for scripting access
7301 uint32 GetAreaTriggerScriptId(uint32 trigger_id)
7303 return objmgr.GetAreaTriggerScriptId(trigger_id);
7306 bool LoadMangosStrings(DatabaseType& db, char const* table,int32 start_value, int32 end_value)
7308 if(start_value >= 0 || start_value <= end_value) // start/end reversed for negative values
7310 sLog.outErrorDb("Table '%s' attempt loaded with invalid range (%d - %d), use (%d - %d) instead.",table,start_value,end_value,-1,std::numeric_limits<int32>::min());
7311 start_value = -1;
7312 end_value = std::numeric_limits<int32>::min();
7315 // for scripting localized strings allowed use _only_ negative entries
7316 return objmgr.LoadMangosStrings(db,table,end_value,start_value);
7319 uint32 MANGOS_DLL_SPEC GetScriptId(const char *name)
7321 return objmgr.GetScriptId(name);
7324 ObjectMgr::ScriptNameMap & GetScriptNames()
7326 return objmgr.GetScriptNames();