Updated some enums
[getmangos.git] / src / game / ObjectMgr.cpp
blob8c5986394277f55ea363d8d789898715708fed77
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"
23 #include "Log.h"
24 #include "MapManager.h"
25 #include "ObjectMgr.h"
26 #include "SpellMgr.h"
27 #include "UpdateMask.h"
28 #include "World.h"
29 #include "WorldSession.h"
30 #include "Group.h"
31 #include "Guild.h"
32 #include "ArenaTeam.h"
33 #include "Transports.h"
34 #include "ProgressBar.h"
35 #include "Policies/SingletonImp.h"
36 #include "Language.h"
37 #include "GameEvent.h"
38 #include "Spell.h"
39 #include "Chat.h"
40 #include "AccountMgr.h"
41 #include "InstanceSaveMgr.h"
42 #include "SpellAuras.h"
43 #include "Util.h"
45 INSTANTIATE_SINGLETON_1(ObjectMgr);
47 ScriptMapMap sQuestEndScripts;
48 ScriptMapMap sQuestStartScripts;
49 ScriptMapMap sSpellScripts;
50 ScriptMapMap sGameObjectScripts;
51 ScriptMapMap sEventScripts;
53 bool normalizePlayerName(std::string& name)
55 if(name.empty())
56 return false;
58 wchar_t wstr_buf[MAX_INTERNAL_PLAYER_NAME+1];
59 size_t wstr_len = MAX_INTERNAL_PLAYER_NAME;
61 if(!Utf8toWStr(name,&wstr_buf[0],wstr_len))
62 return false;
64 wstr_buf[0] = wcharToUpper(wstr_buf[0]);
65 for(size_t i = 1; i < wstr_len; ++i)
66 wstr_buf[i] = wcharToLower(wstr_buf[i]);
68 if(!WStrToUtf8(wstr_buf,wstr_len,name))
69 return false;
71 return true;
74 LanguageDesc lang_description[LANGUAGES_COUNT] =
76 { LANG_ADDON, 0, 0 },
77 { LANG_UNIVERSAL, 0, 0 },
78 { LANG_ORCISH, 669, SKILL_LANG_ORCISH },
79 { LANG_DARNASSIAN, 671, SKILL_LANG_DARNASSIAN },
80 { LANG_TAURAHE, 670, SKILL_LANG_TAURAHE },
81 { LANG_DWARVISH, 672, SKILL_LANG_DWARVEN },
82 { LANG_COMMON, 668, SKILL_LANG_COMMON },
83 { LANG_DEMONIC, 815, SKILL_LANG_DEMON_TONGUE },
84 { LANG_TITAN, 816, SKILL_LANG_TITAN },
85 { LANG_THALASSIAN, 813, SKILL_LANG_THALASSIAN },
86 { LANG_DRACONIC, 814, SKILL_LANG_DRACONIC },
87 { LANG_KALIMAG, 817, SKILL_LANG_OLD_TONGUE },
88 { LANG_GNOMISH, 7340, SKILL_LANG_GNOMISH },
89 { LANG_TROLL, 7341, SKILL_LANG_TROLL },
90 { LANG_GUTTERSPEAK, 17737, SKILL_LANG_GUTTERSPEAK },
91 { LANG_DRAENEI, 29932, SKILL_LANG_DRAENEI },
92 { LANG_ZOMBIE, 0, 0 },
93 { LANG_GNOMISH_BINARY, 0, 0 },
94 { LANG_GOBLIN_BINARY, 0, 0 }
97 LanguageDesc const* GetLanguageDescByID(uint32 lang)
99 for(int i = 0; i < LANGUAGES_COUNT; ++i)
101 if(uint32(lang_description[i].lang_id) == lang)
102 return &lang_description[i];
105 return NULL;
108 ObjectMgr::ObjectMgr()
110 m_hiCharGuid = 1;
111 m_hiCreatureGuid = 1;
112 m_hiPetGuid = 1;
113 m_hiItemGuid = 1;
114 m_hiGoGuid = 1;
115 m_hiDoGuid = 1;
116 m_hiCorpseGuid = 1;
118 m_hiPetNumber = 1;
120 mGuildBankTabPrice.resize(GUILD_BANK_MAX_TABS);
121 mGuildBankTabPrice[0] = 100;
122 mGuildBankTabPrice[1] = 250;
123 mGuildBankTabPrice[2] = 500;
124 mGuildBankTabPrice[3] = 1000;
125 mGuildBankTabPrice[4] = 2500;
126 mGuildBankTabPrice[5] = 5000;
128 // Only zero condition left, others will be added while loading DB tables
129 mConditions.resize(1);
132 ObjectMgr::~ObjectMgr()
134 for( QuestMap::iterator i = mQuestTemplates.begin( ); i != mQuestTemplates.end( ); ++ i )
136 delete i->second;
138 mQuestTemplates.clear( );
140 for( GossipTextMap::iterator i = mGossipText.begin( ); i != mGossipText.end( ); ++ i )
142 delete i->second;
144 mGossipText.clear( );
146 mAreaTriggers.clear();
148 for(PetLevelInfoMap::iterator i = petInfo.begin( ); i != petInfo.end( ); ++ i )
150 delete[] i->second;
152 petInfo.clear();
154 // free only if loaded
155 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
156 delete[] playerClassInfo[class_].levelInfo;
158 for (int race = 0; race < MAX_RACES; ++race)
159 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
160 delete[] playerInfo[race][class_].levelInfo;
162 // free group and guild objects
163 for (GroupSet::iterator itr = mGroupSet.begin(); itr != mGroupSet.end(); ++itr)
164 delete (*itr);
165 for (GuildSet::iterator itr = mGuildSet.begin(); itr != mGuildSet.end(); ++itr)
166 delete (*itr);
168 for(ItemMap::iterator itr = mAitems.begin(); itr != mAitems.end(); ++itr)
169 delete itr->second;
171 for (CacheVendorItemMap::iterator itr = m_mCacheVendorItemMap.begin(); itr != m_mCacheVendorItemMap.end(); ++itr)
172 itr->second.Clear();
174 for (CacheTrainerSpellMap::iterator itr = m_mCacheTrainerSpellMap.begin(); itr != m_mCacheTrainerSpellMap.end(); ++itr)
175 itr->second.Clear();
178 Group * ObjectMgr::GetGroupByLeader(const uint64 &guid) const
180 for(GroupSet::const_iterator itr = mGroupSet.begin(); itr != mGroupSet.end(); ++itr)
181 if ((*itr)->GetLeaderGUID() == guid)
182 return *itr;
184 return NULL;
187 Guild * ObjectMgr::GetGuildById(const uint32 GuildId) const
189 for(GuildSet::const_iterator itr = mGuildSet.begin(); itr != mGuildSet.end(); itr++)
190 if ((*itr)->GetId() == GuildId)
191 return *itr;
193 return NULL;
196 Guild * ObjectMgr::GetGuildByName(std::string guildname) const
198 for(GuildSet::const_iterator itr = mGuildSet.begin(); itr != mGuildSet.end(); itr++)
199 if ((*itr)->GetName() == guildname)
200 return *itr;
202 return NULL;
205 std::string ObjectMgr::GetGuildNameById(const uint32 GuildId) const
207 for(GuildSet::const_iterator itr = mGuildSet.begin(); itr != mGuildSet.end(); itr++)
208 if ((*itr)->GetId() == GuildId)
209 return (*itr)->GetName();
211 return "";
214 Guild* ObjectMgr::GetGuildByLeader(const uint64 &guid) const
216 for(GuildSet::const_iterator itr = mGuildSet.begin(); itr != mGuildSet.end(); ++itr)
217 if( (*itr)->GetLeader() == guid)
218 return *itr;
220 return NULL;
223 ArenaTeam* ObjectMgr::GetArenaTeamById(const uint32 ArenaTeamId) const
225 for(ArenaTeamSet::const_iterator itr = mArenaTeamSet.begin(); itr != mArenaTeamSet.end(); itr++)
226 if ((*itr)->GetId() == ArenaTeamId)
227 return *itr;
229 return NULL;
232 ArenaTeam* ObjectMgr::GetArenaTeamByName(std::string arenateamname) const
234 for(ArenaTeamSet::const_iterator itr = mArenaTeamSet.begin(); itr != mArenaTeamSet.end(); itr++)
235 if ((*itr)->GetName() == arenateamname)
236 return *itr;
238 return NULL;
241 ArenaTeam* ObjectMgr::GetArenaTeamByCapitan(uint64 const& guid) const
243 for(ArenaTeamSet::const_iterator itr = mArenaTeamSet.begin(); itr != mArenaTeamSet.end(); itr++)
244 if ((*itr)->GetCaptain() == guid)
245 return *itr;
247 return NULL;
250 AuctionHouseObject * ObjectMgr::GetAuctionsMap( uint32 location )
252 switch ( location )
254 case 6: //horde
255 return & mHordeAuctions;
256 break;
257 case 2: //alliance
258 return & mAllianceAuctions;
259 break;
260 default: //neutral
261 return & mNeutralAuctions;
265 uint32 ObjectMgr::GetAuctionCut(uint32 location, uint32 highBid)
267 if (location == 7 && !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_AUCTION))
268 return (uint32) (0.15f * highBid * sWorld.getRate(RATE_AUCTION_CUT));
269 else
270 return (uint32) (0.05f * highBid * sWorld.getRate(RATE_AUCTION_CUT));
273 uint32 ObjectMgr::GetAuctionDeposit(uint32 location, uint32 time, Item *pItem)
275 float percentance; // in 0..1
276 if ( location == 7 && !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_AUCTION))
277 percentance = 0.75f;
278 else
279 percentance = 0.15f;
281 percentance *= sWorld.getRate(RATE_AUCTION_DEPOSIT);
283 return uint32( percentance * pItem->GetProto()->SellPrice * pItem->GetCount() * (time / MIN_AUCTION_TIME ) );
286 /// the sum of outbid is (1% from current bid)*5, if bid is very small, it is 1c
287 uint32 ObjectMgr::GetAuctionOutBid(uint32 currentBid)
289 uint32 outbid = (currentBid / 100) * 5;
290 if (!outbid)
291 outbid = 1;
292 return outbid;
295 //does not clear ram
296 void ObjectMgr::SendAuctionWonMail( AuctionEntry *auction )
298 Item *pItem = GetAItem(auction->item_guidlow);
299 if(!pItem)
300 return;
302 uint64 bidder_guid = MAKE_NEW_GUID(auction->bidder, 0, HIGHGUID_PLAYER);
303 Player *bidder = GetPlayer(bidder_guid);
305 uint32 bidder_accId = 0;
307 // data for gm.log
308 if( sWorld.getConfig(CONFIG_GM_LOG_TRADE) )
310 uint32 bidder_security = 0;
311 std::string bidder_name;
312 if (bidder)
314 bidder_accId = bidder->GetSession()->GetAccountId();
315 bidder_security = bidder->GetSession()->GetSecurity();
316 bidder_name = bidder->GetName();
318 else
320 bidder_accId = GetPlayerAccountIdByGUID(bidder_guid);
321 bidder_security = accmgr.GetSecurity(bidder_accId);
323 if(bidder_security > SEC_PLAYER ) // not do redundant DB requests
325 if(!GetPlayerNameByGUID(bidder_guid,bidder_name))
326 bidder_name = GetMangosStringForDBCLocale(LANG_UNKNOWN);
330 if( bidder_security > SEC_PLAYER )
332 std::string owner_name;
333 if(!GetPlayerNameByGUID(auction->owner,owner_name))
334 owner_name = GetMangosStringForDBCLocale(LANG_UNKNOWN);
336 uint32 owner_accid = GetPlayerAccountIdByGUID(auction->owner);
338 sLog.outCommand("GM %s (Account: %u) won item in auction: %s (Entry: %u Count: %u) and pay money: %u. Original owner %s (Account: %u)",
339 bidder_name.c_str(),bidder_accId,pItem->GetProto()->Name1,pItem->GetEntry(),pItem->GetCount(),auction->bid,owner_name.c_str(),owner_accid);
342 else if(!bidder)
343 bidder_accId = GetPlayerAccountIdByGUID(bidder_guid);
345 // receiver exist
346 if(bidder || bidder_accId)
348 std::ostringstream msgAuctionWonSubject;
349 msgAuctionWonSubject << auction->item_template << ":0:" << AUCTION_WON;
351 std::ostringstream msgAuctionWonBody;
352 msgAuctionWonBody.width(16);
353 msgAuctionWonBody << std::right << std::hex << auction->owner;
354 msgAuctionWonBody << std::dec << ":" << auction->bid << ":" << auction->buyout;
355 sLog.outDebug( "AuctionWon body string : %s", msgAuctionWonBody.str().c_str() );
357 //prepare mail data... :
358 uint32 itemTextId = CreateItemText( msgAuctionWonBody.str() );
360 // set owner to bidder (to prevent delete item with sender char deleting)
361 // owner in `data` will set at mail receive and item extracting
362 CharacterDatabase.PExecute("UPDATE item_instance SET owner_guid = '%u' WHERE guid='%u'",auction->bidder,pItem->GetGUIDLow());
363 CharacterDatabase.CommitTransaction();
365 MailItemsInfo mi;
366 mi.AddItem(auction->item_guidlow, auction->item_template, pItem);
368 if (bidder)
369 bidder->GetSession()->SendAuctionBidderNotification( auction->location, auction->Id, bidder_guid, 0, 0, auction->item_template);
370 else
371 RemoveAItem(pItem->GetGUIDLow()); // we have to remove the item, before we delete it !!
373 // will delete item or place to receiver mail list
374 WorldSession::SendMailTo(bidder, MAIL_AUCTION, MAIL_STATIONERY_AUCTION, auction->location, auction->bidder, msgAuctionWonSubject.str(), itemTextId, &mi, 0, 0, MAIL_CHECK_MASK_AUCTION);
376 // receiver not exist
377 else
379 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid='%u'", pItem->GetGUIDLow());
380 RemoveAItem(pItem->GetGUIDLow()); // we have to remove the item, before we delete it !!
381 delete pItem;
385 void ObjectMgr::SendAuctionSalePendingMail( AuctionEntry * auction )
387 uint64 owner_guid = MAKE_NEW_GUID(auction->owner, 0, HIGHGUID_PLAYER);
388 Player *owner = GetPlayer(owner_guid);
390 // owner exist (online or offline)
391 if(owner || GetPlayerAccountIdByGUID(owner_guid))
393 std::ostringstream msgAuctionSalePendingSubject;
394 msgAuctionSalePendingSubject << auction->item_template << ":0:" << AUCTION_SALE_PENDING;
396 std::ostringstream msgAuctionSalePendingBody;
397 uint32 auctionCut = GetAuctionCut(auction->location, auction->bid);
399 time_t distrTime = time(NULL) + HOUR;
401 msgAuctionSalePendingBody.width(16);
402 msgAuctionSalePendingBody << std::right << std::hex << auction->bidder;
403 msgAuctionSalePendingBody << std::dec << ":" << auction->bid << ":" << auction->buyout;
404 msgAuctionSalePendingBody << ":" << auction->deposit << ":" << auctionCut << ":0:";
405 msgAuctionSalePendingBody << secsToTimeBitFields(distrTime);
407 sLog.outDebug("AuctionSalePending body string : %s", msgAuctionSalePendingBody.str().c_str());
409 uint32 itemTextId = CreateItemText( msgAuctionSalePendingBody.str() );
411 WorldSession::SendMailTo(owner, MAIL_AUCTION, MAIL_STATIONERY_AUCTION, auction->location, auction->owner, msgAuctionSalePendingSubject.str(), itemTextId, NULL, 0, 0, MAIL_CHECK_MASK_AUCTION);
415 //call this method to send mail to auction owner, when auction is successful, it does not clear ram
416 void ObjectMgr::SendAuctionSuccessfulMail( AuctionEntry * auction )
418 uint64 owner_guid = MAKE_NEW_GUID(auction->owner, 0, HIGHGUID_PLAYER);
419 Player *owner = GetPlayer(owner_guid);
421 uint32 owner_accId = 0;
422 if(!owner)
423 owner_accId = GetPlayerAccountIdByGUID(owner_guid);
425 // owner exist
426 if(owner || owner_accId)
428 std::ostringstream msgAuctionSuccessfulSubject;
429 msgAuctionSuccessfulSubject << auction->item_template << ":0:" << AUCTION_SUCCESSFUL;
431 std::ostringstream auctionSuccessfulBody;
432 uint32 auctionCut = GetAuctionCut(auction->location, auction->bid);
434 auctionSuccessfulBody.width(16);
435 auctionSuccessfulBody << std::right << std::hex << auction->bidder;
436 auctionSuccessfulBody << std::dec << ":" << auction->bid << ":" << auction->buyout;
437 auctionSuccessfulBody << ":" << auction->deposit << ":" << auctionCut;
439 sLog.outDebug("AuctionSuccessful body string : %s", auctionSuccessfulBody.str().c_str());
441 uint32 itemTextId = CreateItemText( auctionSuccessfulBody.str() );
443 uint32 profit = auction->bid + auction->deposit - auctionCut;
445 if (owner)
447 //send auction owner notification, bidder must be current!
448 owner->GetSession()->SendAuctionOwnerNotification( auction );
451 WorldSession::SendMailTo(owner, MAIL_AUCTION, MAIL_STATIONERY_AUCTION, auction->location, auction->owner, msgAuctionSuccessfulSubject.str(), itemTextId, NULL, profit, 0, MAIL_CHECK_MASK_AUCTION, HOUR);
455 //does not clear ram
456 void ObjectMgr::SendAuctionExpiredMail( AuctionEntry * auction )
457 { //return an item in auction to its owner by mail
458 Item *pItem = GetAItem(auction->item_guidlow);
459 if(!pItem)
461 sLog.outError("Auction item (GUID: %u) not found, and lost.",auction->item_guidlow);
462 return;
465 uint64 owner_guid = MAKE_NEW_GUID(auction->owner, 0, HIGHGUID_PLAYER);
466 Player *owner = GetPlayer(owner_guid);
468 uint32 owner_accId = 0;
469 if(!owner)
470 owner_accId = GetPlayerAccountIdByGUID(owner_guid);
472 // owner exist
473 if(owner || owner_accId)
475 std::ostringstream subject;
476 subject << auction->item_template << ":0:" << AUCTION_EXPIRED;
478 if ( owner )
479 owner->GetSession()->SendAuctionOwnerNotification( auction );
480 else
481 RemoveAItem(pItem->GetGUIDLow()); // we have to remove the item, before we delete it !!
483 MailItemsInfo mi;
484 mi.AddItem(auction->item_guidlow, auction->item_template, pItem);
486 // will delete item or place to receiver mail list
487 WorldSession::SendMailTo(owner, MAIL_AUCTION, MAIL_STATIONERY_AUCTION, auction->location, GUID_LOPART(owner_guid), subject.str(), 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
489 // owner not found
490 else
492 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid='%u'",pItem->GetGUIDLow());
493 RemoveAItem(pItem->GetGUIDLow()); // we have to remove the item, before we delete it !!
494 delete pItem;
498 CreatureInfo const* ObjectMgr::GetCreatureTemplate(uint32 id)
500 return sCreatureStorage.LookupEntry<CreatureInfo>(id);
503 void ObjectMgr::LoadCreatureLocales()
505 mCreatureLocaleMap.clear(); // need for reload case
507 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");
509 if(!result)
511 barGoLink bar(1);
513 bar.step();
515 sLog.outString("");
516 sLog.outString(">> Loaded 0 creature locale strings. DB table `locales_creature` is empty.");
517 return;
520 barGoLink bar(result->GetRowCount());
524 Field *fields = result->Fetch();
525 bar.step();
527 uint32 entry = fields[0].GetUInt32();
529 CreatureLocale& data = mCreatureLocaleMap[entry];
531 for(int i = 1; i < MAX_LOCALE; ++i)
533 std::string str = fields[1+2*(i-1)].GetCppString();
534 if(!str.empty())
536 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
537 if(idx >= 0)
539 if(data.Name.size() <= idx)
540 data.Name.resize(idx+1);
542 data.Name[idx] = str;
545 str = fields[1+2*(i-1)+1].GetCppString();
546 if(!str.empty())
548 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
549 if(idx >= 0)
551 if(data.SubName.size() <= idx)
552 data.SubName.resize(idx+1);
554 data.SubName[idx] = str;
558 } while (result->NextRow());
560 delete result;
562 sLog.outString();
563 sLog.outString( ">> Loaded %u creature locale strings", mCreatureLocaleMap.size() );
566 void ObjectMgr::LoadCompletedAchievements()
568 QueryResult *result = CharacterDatabase.Query("SELECT achievement FROM character_achievement GROUP BY achievement");
570 if(!result)
571 return;
575 Field *fields = result->Fetch();
576 allCompletedAchievements.insert(fields[0].GetUInt32());
577 } while(result->NextRow());
579 delete result;
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 void ObjectMgr::LoadCreatureTemplates()
652 sCreatureStorage.Load();
654 sLog.outString( ">> Loaded %u creature definitions", sCreatureStorage.RecordCount );
655 sLog.outString();
657 std::set<uint32> heroicEntries; // already loaded heroic value in creatures
658 std::set<uint32> hasHeroicEntries; // already loaded creatures with heroic entry values
660 // check data correctness
661 for(uint32 i = 1; i < sCreatureStorage.MaxEntry; ++i)
663 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i);
664 if(!cInfo)
665 continue;
667 if(cInfo->HeroicEntry)
669 CreatureInfo const* heroicInfo = GetCreatureTemplate(cInfo->HeroicEntry);
670 if(!heroicInfo)
672 sLog.outErrorDb("Creature (Entry: %u) have `heroic_entry`=%u but creature entry %u not exist.",cInfo->HeroicEntry,cInfo->HeroicEntry);
673 continue;
676 if(heroicEntries.find(i)!=heroicEntries.end())
678 sLog.outErrorDb("Creature (Entry: %u) listed as heroic but have value in `heroic_entry`.",i);
679 continue;
682 if(heroicEntries.find(cInfo->HeroicEntry)!=heroicEntries.end())
684 sLog.outErrorDb("Creature (Entry: %u) already listed as heroic for another entry.",cInfo->HeroicEntry);
685 continue;
688 if(hasHeroicEntries.find(cInfo->HeroicEntry)!=hasHeroicEntries.end())
690 sLog.outErrorDb("Creature (Entry: %u) have `heroic_entry`=%u but creature entry %u have heroic entry also.",i,cInfo->HeroicEntry,cInfo->HeroicEntry);
691 continue;
694 if(cInfo->npcflag != heroicInfo->npcflag)
696 sLog.outErrorDb("Creature (Entry: %u) has different `npcflag` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
697 continue;
700 if(cInfo->classNum != heroicInfo->classNum)
702 sLog.outErrorDb("Creature (Entry: %u) has different `classNum` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
703 continue;
706 if(cInfo->race != heroicInfo->race)
708 sLog.outErrorDb("Creature (Entry: %u) has different `race` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
709 continue;
712 if(cInfo->trainer_type != heroicInfo->trainer_type)
714 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_type` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
715 continue;
718 if(cInfo->trainer_spell != heroicInfo->trainer_spell)
720 sLog.outErrorDb("Creature (Entry: %u) has different `trainer_spell` in heroic mode (Entry: %u).",i,cInfo->HeroicEntry);
721 continue;
724 hasHeroicEntries.insert(i);
725 heroicEntries.insert(cInfo->HeroicEntry);
728 FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction_A);
729 if(!factionTemplate)
730 sLog.outErrorDb("Creature (Entry: %u) has non-existing faction_A template (%u)", cInfo->Entry, cInfo->faction_A);
732 factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction_H);
733 if(!factionTemplate)
734 sLog.outErrorDb("Creature (Entry: %u) has non-existing faction_H template (%u)", cInfo->Entry, cInfo->faction_H);
736 CreatureModelInfo const* minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_A);
737 if (!minfo)
738 sLog.outErrorDb("Creature (Entry: %u) has non-existing modelId_A (%u)", cInfo->Entry, cInfo->DisplayID_A);
739 minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_H);
740 if (!minfo)
741 sLog.outErrorDb("Creature (Entry: %u) has non-existing modelId_H (%u)", cInfo->Entry, cInfo->DisplayID_H);
743 if(cInfo->dmgschool >= MAX_SPELL_SCHOOL)
745 sLog.outErrorDb("Creature (Entry: %u) has invalid spell school value (%u) in `dmgschool`",cInfo->Entry,cInfo->dmgschool);
746 const_cast<CreatureInfo*>(cInfo)->dmgschool = SPELL_SCHOOL_NORMAL;
749 if(cInfo->baseattacktime == 0)
750 const_cast<CreatureInfo*>(cInfo)->baseattacktime = BASE_ATTACK_TIME;
752 if(cInfo->rangeattacktime == 0)
753 const_cast<CreatureInfo*>(cInfo)->rangeattacktime = BASE_ATTACK_TIME;
755 if((cInfo->npcflag & UNIT_NPC_FLAG_TRAINER) && cInfo->trainer_type >= MAX_TRAINER_TYPE)
756 sLog.outErrorDb("Creature (Entry: %u) has wrong trainer type %u",cInfo->Entry,cInfo->trainer_type);
758 if(cInfo->InhabitType <= 0 || cInfo->InhabitType > INHABIT_ANYWHERE)
760 sLog.outErrorDb("Creature (Entry: %u) has wrong value (%u) in `InhabitType`, creature will not correctly walk/swim/fly",cInfo->Entry,cInfo->InhabitType);
761 const_cast<CreatureInfo*>(cInfo)->InhabitType = INHABIT_ANYWHERE;
764 if(cInfo->PetSpellDataId)
766 CreatureSpellDataEntry const* spellDataId = sCreatureSpellDataStore.LookupEntry(cInfo->PetSpellDataId);
767 if(!spellDataId)
768 sLog.outErrorDb("Creature (Entry: %u) has non-existing PetSpellDataId (%u)", cInfo->Entry, cInfo->PetSpellDataId);
771 if(cInfo->MovementType >= MAX_DB_MOTION_TYPE)
773 sLog.outErrorDb("Creature (Entry: %u) has wrong movement generator type (%u), ignore and set to IDLE.",cInfo->Entry,cInfo->MovementType);
774 const_cast<CreatureInfo*>(cInfo)->MovementType = IDLE_MOTION_TYPE;
777 if(cInfo->equipmentId > 0) // 0 no equipment
779 if(!GetEquipmentInfo(cInfo->equipmentId))
781 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);
782 const_cast<CreatureInfo*>(cInfo)->equipmentId = 0;
786 /// if not set custom creature scale then load scale from CreatureDisplayInfo.dbc
787 if(cInfo->scale <= 0.0f)
789 CreatureDisplayInfoEntry const* ScaleEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->DisplayID_A);
790 const_cast<CreatureInfo*>(cInfo)->scale = ScaleEntry ? ScaleEntry->scale : 1.0f;
795 void ObjectMgr::ConvertCreatureAddonAuras(CreatureDataAddon* addon, char const* table, char const* guidEntryStr)
797 // Now add the auras, format "spellid effectindex spellid effectindex..."
798 char *p,*s;
799 std::vector<int> val;
800 s=p=(char*)reinterpret_cast<char const*>(addon->auras);
801 if(p)
803 while (p[0]!=0)
805 ++p;
806 if (p[0]==' ')
808 val.push_back(atoi(s));
809 s=++p;
812 if (p!=s)
813 val.push_back(atoi(s));
815 // free char* loaded memory
816 delete[] (char*)reinterpret_cast<char const*>(addon->auras);
818 // wrong list
819 if (val.size()%2)
821 addon->auras = NULL;
822 sLog.outErrorDb("Creature (%s: %u) has wrong `auras` data in `%s`.",guidEntryStr,addon->guidOrEntry,table);
823 return;
827 // empty list
828 if(val.empty())
830 addon->auras = NULL;
831 return;
834 // replace by new structures array
835 const_cast<CreatureDataAddonAura*&>(addon->auras) = new CreatureDataAddonAura[val.size()/2+1];
837 int i=0;
838 for(int j=0;j<val.size()/2;++j)
840 CreatureDataAddonAura& cAura = const_cast<CreatureDataAddonAura&>(addon->auras[i]);
841 cAura.spell_id = (uint32)val[2*j+0];
842 cAura.effect_idx = (uint32)val[2*j+1];
843 if ( cAura.effect_idx > 2 )
845 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);
846 continue;
848 SpellEntry const *AdditionalSpellInfo = sSpellStore.LookupEntry(cAura.spell_id);
849 if (!AdditionalSpellInfo)
851 sLog.outErrorDb("Creature (%s: %u) has wrong spell %u defined in `auras` field in `%s`.",guidEntryStr,addon->guidOrEntry,cAura.spell_id,table);
852 continue;
855 if (!AdditionalSpellInfo->Effect[cAura.effect_idx] || !AdditionalSpellInfo->EffectApplyAuraName[cAura.effect_idx])
857 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);
858 continue;
861 ++i;
864 // fill terminator element (after last added)
865 CreatureDataAddonAura& endAura = const_cast<CreatureDataAddonAura&>(addon->auras[i]);
866 endAura.spell_id = 0;
867 endAura.effect_idx = 0;
870 void ObjectMgr::LoadCreatureAddons()
872 sCreatureInfoAddonStorage.Load();
874 sLog.outString( ">> Loaded %u creature template addons", sCreatureInfoAddonStorage.RecordCount );
875 sLog.outString();
877 // check data correctness and convert 'auras'
878 for(uint32 i = 1; i < sCreatureInfoAddonStorage.MaxEntry; ++i)
880 CreatureDataAddon const* addon = sCreatureInfoAddonStorage.LookupEntry<CreatureDataAddon>(i);
881 if(!addon)
882 continue;
884 ConvertCreatureAddonAuras(const_cast<CreatureDataAddon*>(addon), "creature_template_addon", "Entry");
886 if(!sCreatureStorage.LookupEntry<CreatureInfo>(addon->guidOrEntry))
887 sLog.outErrorDb("Creature (Entry: %u) does not exist but has a record in `creature_template_addon`",addon->guidOrEntry);
890 sCreatureDataAddonStorage.Load();
892 sLog.outString( ">> Loaded %u creature addons", sCreatureDataAddonStorage.RecordCount );
893 sLog.outString();
895 // check data correctness and convert 'auras'
896 for(uint32 i = 1; i < sCreatureDataAddonStorage.MaxEntry; ++i)
898 CreatureDataAddon const* addon = sCreatureDataAddonStorage.LookupEntry<CreatureDataAddon>(i);
899 if(!addon)
900 continue;
902 ConvertCreatureAddonAuras(const_cast<CreatureDataAddon*>(addon), "creature_addon", "GUIDLow");
904 if(mCreatureDataMap.find(addon->guidOrEntry)==mCreatureDataMap.end())
905 sLog.outErrorDb("Creature (GUID: %u) does not exist but has a record in `creature_addon`",addon->guidOrEntry);
909 EquipmentInfo const* ObjectMgr::GetEquipmentInfo(uint32 entry)
911 return sEquipmentStorage.LookupEntry<EquipmentInfo>(entry);
914 void ObjectMgr::LoadEquipmentTemplates()
916 sEquipmentStorage.Load();
918 for(uint32 i=0; i< sEquipmentStorage.MaxEntry; ++i)
920 EquipmentInfo const* eqInfo = sEquipmentStorage.LookupEntry<EquipmentInfo>(i);
922 if(!eqInfo)
923 continue;
925 for(uint8 j=0; j<3; j++)
927 if(!eqInfo->equipentry[j])
928 continue;
930 ItemPrototype const* proto = objmgr.GetItemPrototype(eqInfo->equipentry[j]);
932 if(!proto)
934 sLog.outErrorDb("Unknown item (entry=%u) in creature_equip_template.equipentry%u for entry = %u, forced to 0.", eqInfo->equipentry[j], j+1, i);
935 const_cast<EquipmentInfo*>(eqInfo)->equipentry[j] = 0;
936 continue;
939 if(proto->InventoryType != INVTYPE_WEAPON &&
940 proto->InventoryType != INVTYPE_SHIELD &&
941 proto->InventoryType != INVTYPE_RANGED &&
942 proto->InventoryType != INVTYPE_2HWEAPON &&
943 proto->InventoryType != INVTYPE_WEAPONMAINHAND &&
944 proto->InventoryType != INVTYPE_WEAPONOFFHAND &&
945 proto->InventoryType != INVTYPE_HOLDABLE &&
946 proto->InventoryType != INVTYPE_THROWN &&
947 proto->InventoryType != INVTYPE_RANGEDRIGHT)
949 sLog.outErrorDb("Item (entry=%u) in creature_equip_template.equipentry%u for entry = %u is not equipable in a hand, forced to 0.", eqInfo->equipentry[j], j+1, i);
950 const_cast<EquipmentInfo*>(eqInfo)->equipentry[j] = 0;
954 sLog.outString( ">> Loaded %u equipment template", sEquipmentStorage.RecordCount );
955 sLog.outString();
958 CreatureModelInfo const* ObjectMgr::GetCreatureModelInfo(uint32 modelid)
960 return sCreatureModelStorage.LookupEntry<CreatureModelInfo>(modelid);
963 uint32 ObjectMgr::ChooseDisplayId(uint32 team, const CreatureInfo *cinfo, const CreatureData *data)
965 // Load creature model (display id)
966 uint32 display_id;
967 if (!data || data->displayid == 0) // use defaults from the template
969 // DisplayID_A is used if no team is given
970 if (team == HORDE)
971 display_id = (cinfo->DisplayID_H2 != 0 && urand(0,1) == 0) ? cinfo->DisplayID_H2 : cinfo->DisplayID_H;
972 else
973 display_id = (cinfo->DisplayID_A2 != 0 && urand(0,1) == 0) ? cinfo->DisplayID_A2 : cinfo->DisplayID_A;
975 else // overridden in creature data
976 display_id = data->displayid;
978 return display_id;
981 CreatureModelInfo const* ObjectMgr::GetCreatureModelRandomGender(uint32 display_id)
983 CreatureModelInfo const *minfo = GetCreatureModelInfo(display_id);
984 if(!minfo)
985 return NULL;
987 // If a model for another gender exists, 50% chance to use it
988 if(minfo->modelid_other_gender != 0 && urand(0,1) == 0)
990 CreatureModelInfo const *minfo_tmp = GetCreatureModelInfo(minfo->modelid_other_gender);
991 if(!minfo_tmp)
993 sLog.outErrorDb("Model (Entry: %u) has modelid_other_gender %u not found in table `creature_model_info`. ", minfo->modelid, minfo->modelid_other_gender);
994 return minfo; // not fatal, just use the previous one
996 else
997 return minfo_tmp;
999 else
1000 return minfo;
1003 void ObjectMgr::LoadCreatureModelInfo()
1005 sCreatureModelStorage.Load();
1007 sLog.outString( ">> Loaded %u creature model based info", sCreatureModelStorage.RecordCount );
1008 sLog.outString();
1011 void ObjectMgr::LoadCreatures()
1013 uint32 count = 0;
1014 // 0 1 2 3
1015 QueryResult *result = WorldDatabase.Query("SELECT creature.guid, id, map, modelid,"
1016 // 4 5 6 7 8 9 10 11
1017 "equipment_id, position_x, position_y, position_z, orientation, spawntimesecs, spawndist, currentwaypoint,"
1018 // 12 13 14 15 16 17
1019 "curhealth, curmana, DeathState, MovementType, spawnMask, event "
1020 "FROM creature LEFT OUTER JOIN game_event_creature ON creature.guid = game_event_creature.guid");
1022 if(!result)
1024 barGoLink bar(1);
1026 bar.step();
1028 sLog.outString("");
1029 sLog.outErrorDb(">> Loaded 0 creature. DB table `creature` is empty.");
1030 return;
1033 // build single time for check creature data
1034 std::set<uint32> heroicCreatures;
1035 for(uint32 i = 0; i < sCreatureStorage.MaxEntry; ++i)
1036 if(CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i))
1037 if(cInfo->HeroicEntry)
1038 heroicCreatures.insert(cInfo->HeroicEntry);
1040 barGoLink bar(result->GetRowCount());
1044 Field *fields = result->Fetch();
1045 bar.step();
1047 uint32 guid = fields[0].GetUInt32();
1049 CreatureData& data = mCreatureDataMap[guid];
1051 data.id = fields[ 1].GetUInt32();
1052 data.mapid = fields[ 2].GetUInt32();
1053 data.displayid = fields[ 3].GetUInt32();
1054 data.equipmentId = fields[ 4].GetUInt32();
1055 data.posX = fields[ 5].GetFloat();
1056 data.posY = fields[ 6].GetFloat();
1057 data.posZ = fields[ 7].GetFloat();
1058 data.orientation = fields[ 8].GetFloat();
1059 data.spawntimesecs = fields[ 9].GetUInt32();
1060 data.spawndist = fields[10].GetFloat();
1061 data.currentwaypoint= fields[11].GetUInt32();
1062 data.curhealth = fields[12].GetUInt32();
1063 data.curmana = fields[13].GetUInt32();
1064 data.is_dead = fields[14].GetBool();
1065 data.movementType = fields[15].GetUInt8();
1066 data.spawnMask = fields[16].GetUInt8();
1067 int16 gameEvent = fields[17].GetInt16();
1069 CreatureInfo const* cInfo = GetCreatureTemplate(data.id);
1070 if(!cInfo)
1072 sLog.outErrorDb("Table `creature` have creature (GUID: %u) with not existed creature entry %u, skipped.",guid,data.id );
1073 continue;
1076 if(heroicCreatures.find(data.id)!=heroicCreatures.end())
1078 sLog.outErrorDb("Table `creature` have creature (GUID: %u) that listed as heroic template in `creature_template`, skipped.",guid,data.id );
1079 continue;
1082 if(data.equipmentId > 0) // -1 no equipment, 0 use default
1084 if(!GetEquipmentInfo(data.equipmentId))
1086 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);
1087 data.equipmentId = -1;
1091 if(cInfo->RegenHealth && data.curhealth < cInfo->minhealth)
1093 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 );
1094 data.curhealth = cInfo->minhealth;
1097 if(data.curmana < cInfo->minmana)
1099 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 );
1100 data.curmana = cInfo->minmana;
1103 if(data.spawndist < 0.0f)
1105 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `spawndist`< 0, set to 0.",guid,data.id );
1106 data.spawndist = 0.0f;
1108 else if(data.movementType == RANDOM_MOTION_TYPE)
1110 if(data.spawndist == 0.0f)
1112 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 );
1113 data.movementType = IDLE_MOTION_TYPE;
1116 else if(data.movementType == IDLE_MOTION_TYPE)
1118 if(data.spawndist != 0.0f)
1120 sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `MovementType`=0 (idle) have `spawndist`<>0, set to 0.",guid,data.id );
1121 data.spawndist = 0.0f;
1125 if (gameEvent==0) // if not this is to be managed by GameEvent System
1126 AddCreatureToGrid(guid, &data);
1127 ++count;
1129 } while (result->NextRow());
1131 delete result;
1133 sLog.outString();
1134 sLog.outString( ">> Loaded %u creatures", mCreatureDataMap.size() );
1137 void ObjectMgr::AddCreatureToGrid(uint32 guid, CreatureData const* data)
1139 uint8 mask = data->spawnMask;
1140 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1142 if(mask & 1)
1144 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1145 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1147 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1148 cell_guids.creatures.insert(guid);
1153 void ObjectMgr::RemoveCreatureFromGrid(uint32 guid, CreatureData const* data)
1155 uint8 mask = data->spawnMask;
1156 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1158 if(mask & 1)
1160 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1161 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1163 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1164 cell_guids.creatures.erase(guid);
1169 void ObjectMgr::LoadGameobjects()
1171 uint32 count = 0;
1173 // 0 1 2 3 4 5 6
1174 QueryResult *result = WorldDatabase.Query("SELECT gameobject.guid, id, map, position_x, position_y, position_z, orientation,"
1175 // 7 8 9 10 11 12 13 14 15
1176 "rotation0, rotation1, rotation2, rotation3, spawntimesecs, animprogress, state, spawnMask, event "
1177 "FROM gameobject LEFT OUTER JOIN game_event_gameobject ON gameobject.guid = game_event_gameobject.guid");
1179 if(!result)
1181 barGoLink bar(1);
1183 bar.step();
1185 sLog.outString();
1186 sLog.outErrorDb(">> Loaded 0 gameobjects. DB table `gameobject` is empty.");
1187 return;
1190 barGoLink bar(result->GetRowCount());
1194 Field *fields = result->Fetch();
1195 bar.step();
1197 uint32 guid = fields[0].GetUInt32();
1199 GameObjectData& data = mGameObjectDataMap[guid];
1201 data.id = fields[ 1].GetUInt32();
1202 data.mapid = fields[ 2].GetUInt32();
1203 data.posX = fields[ 3].GetFloat();
1204 data.posY = fields[ 4].GetFloat();
1205 data.posZ = fields[ 5].GetFloat();
1206 data.orientation = fields[ 6].GetFloat();
1207 data.rotation0 = fields[ 7].GetFloat();
1208 data.rotation1 = fields[ 8].GetFloat();
1209 data.rotation2 = fields[ 9].GetFloat();
1210 data.rotation3 = fields[10].GetFloat();
1211 data.spawntimesecs = fields[11].GetInt32();
1212 data.animprogress = fields[12].GetUInt32();
1213 data.go_state = fields[13].GetUInt32();
1214 data.spawnMask = fields[14].GetUInt8();
1215 int16 gameEvent = fields[15].GetInt16();
1217 GameObjectInfo const* gInfo = GetGameObjectInfo(data.id);
1218 if(!gInfo)
1220 sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u) with not existed gameobject entry %u, skipped.",guid,data.id );
1221 continue;
1224 if (gameEvent==0) // if not this is to be managed by GameEvent System
1225 AddGameobjectToGrid(guid, &data);
1226 ++count;
1228 } while (result->NextRow());
1230 delete result;
1232 sLog.outString();
1233 sLog.outString( ">> Loaded %u gameobjects", mGameObjectDataMap.size());
1236 void ObjectMgr::AddGameobjectToGrid(uint32 guid, GameObjectData const* data)
1238 uint8 mask = data->spawnMask;
1239 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1241 if(mask & 1)
1243 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1244 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1246 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1247 cell_guids.gameobjects.insert(guid);
1252 void ObjectMgr::RemoveGameobjectFromGrid(uint32 guid, GameObjectData const* data)
1254 uint8 mask = data->spawnMask;
1255 for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1257 if(mask & 1)
1259 CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1260 uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1262 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1263 cell_guids.gameobjects.erase(guid);
1268 void ObjectMgr::LoadCreatureRespawnTimes()
1270 // remove outdated data
1271 WorldDatabase.DirectExecute("DELETE FROM creature_respawn WHERE respawntime <= UNIX_TIMESTAMP(NOW())");
1273 uint32 count = 0;
1275 QueryResult *result = WorldDatabase.Query("SELECT guid,respawntime,instance FROM creature_respawn");
1277 if(!result)
1279 barGoLink bar(1);
1281 bar.step();
1283 sLog.outString();
1284 sLog.outString(">> Loaded 0 creature respawn time.");
1285 return;
1288 barGoLink bar(result->GetRowCount());
1292 Field *fields = result->Fetch();
1293 bar.step();
1295 uint32 loguid = fields[0].GetUInt32();
1296 uint64 respawn_time = fields[1].GetUInt64();
1297 uint32 instance = fields[2].GetUInt32();
1299 mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = time_t(respawn_time);
1301 ++count;
1302 } while (result->NextRow());
1304 delete result;
1306 sLog.outString( ">> Loaded %u creature respawn times", mCreatureRespawnTimes.size() );
1307 sLog.outString();
1310 void ObjectMgr::LoadGameobjectRespawnTimes()
1312 // remove outdated data
1313 WorldDatabase.DirectExecute("DELETE FROM gameobject_respawn WHERE respawntime <= UNIX_TIMESTAMP(NOW())");
1315 uint32 count = 0;
1317 QueryResult *result = WorldDatabase.Query("SELECT guid,respawntime,instance FROM gameobject_respawn");
1319 if(!result)
1321 barGoLink bar(1);
1323 bar.step();
1325 sLog.outString();
1326 sLog.outString(">> Loaded 0 gameobject respawn time.");
1327 return;
1330 barGoLink bar(result->GetRowCount());
1334 Field *fields = result->Fetch();
1335 bar.step();
1337 uint32 loguid = fields[0].GetUInt32();
1338 uint64 respawn_time = fields[1].GetUInt64();
1339 uint32 instance = fields[2].GetUInt32();
1341 mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = time_t(respawn_time);
1343 ++count;
1344 } while (result->NextRow());
1346 delete result;
1348 sLog.outString( ">> Loaded %u gameobject respawn times", mGORespawnTimes.size() );
1349 sLog.outString();
1352 // name must be checked to correctness (if received) before call this function
1353 uint64 ObjectMgr::GetPlayerGUIDByName(std::string name) const
1355 uint64 guid = 0;
1357 CharacterDatabase.escape_string(name);
1359 // Player name safe to sending to DB (checked at login) and this function using
1360 QueryResult *result = CharacterDatabase.PQuery("SELECT guid FROM characters WHERE name = '%s'", name.c_str());
1361 if(result)
1363 guid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
1365 delete result;
1368 return guid;
1371 bool ObjectMgr::GetPlayerNameByGUID(const uint64 &guid, std::string &name) const
1373 // prevent DB access for online player
1374 if(Player* player = GetPlayer(guid))
1376 name = player->GetName();
1377 return true;
1380 QueryResult *result = CharacterDatabase.PQuery("SELECT name FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1382 if(result)
1384 name = (*result)[0].GetCppString();
1385 delete result;
1386 return true;
1389 return false;
1392 uint32 ObjectMgr::GetPlayerTeamByGUID(const uint64 &guid) const
1394 QueryResult *result = CharacterDatabase.PQuery("SELECT race FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1396 if(result)
1398 uint8 race = (*result)[0].GetUInt8();
1399 delete result;
1400 return Player::TeamForRace(race);
1403 return 0;
1406 uint32 ObjectMgr::GetPlayerAccountIdByGUID(const uint64 &guid) const
1408 QueryResult *result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1409 if(result)
1411 uint32 acc = (*result)[0].GetUInt32();
1412 delete result;
1413 return acc;
1416 return 0;
1419 uint32 ObjectMgr::GetPlayerAccountIdByPlayerName(std::string name) const
1421 QueryResult *result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'", name.c_str());
1422 if(result)
1424 uint32 acc = (*result)[0].GetUInt32();
1425 delete result;
1426 return acc;
1429 return 0;
1432 void ObjectMgr::LoadAuctions()
1434 QueryResult *result = CharacterDatabase.Query("SELECT COUNT(*) FROM auctionhouse");
1435 if( !result )
1436 return;
1438 Field *fields = result->Fetch();
1439 uint32 AuctionCount=fields[0].GetUInt32();
1440 delete result;
1442 if(!AuctionCount)
1443 return;
1445 result = CharacterDatabase.Query( "SELECT id,auctioneerguid,itemguid,item_template,itemowner,buyoutprice,time,buyguid,lastbid,startbid,deposit,location FROM auctionhouse" );
1446 if( !result )
1447 return;
1449 barGoLink bar( AuctionCount );
1451 AuctionEntry *aItem;
1455 fields = result->Fetch();
1457 bar.step();
1459 aItem = new AuctionEntry;
1460 aItem->Id = fields[0].GetUInt32();
1461 aItem->auctioneer = fields[1].GetUInt32();
1462 aItem->item_guidlow = fields[2].GetUInt32();
1463 aItem->item_template = fields[3].GetUInt32();
1464 aItem->owner = fields[4].GetUInt32();
1465 aItem->buyout = fields[5].GetUInt32();
1466 aItem->time = fields[6].GetUInt32();
1467 aItem->bidder = fields[7].GetUInt32();
1468 aItem->bid = fields[8].GetUInt32();
1469 aItem->startbid = fields[9].GetUInt32();
1470 aItem->deposit = fields[10].GetUInt32();
1471 aItem->location = fields[11].GetUInt8();
1472 //check if sold item exists
1473 if ( GetAItem( aItem->item_guidlow ) )
1475 GetAuctionsMap( aItem->location )->AddAuction(aItem);
1477 else
1479 CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE id = '%u'",aItem->Id);
1480 sLog.outError("Auction %u has not a existing item : %u", aItem->Id, aItem->item_guidlow);
1481 delete aItem;
1483 } while (result->NextRow());
1484 delete result;
1486 sLog.outString();
1487 sLog.outString( ">> Loaded %u auctions", AuctionCount );
1488 sLog.outString();
1491 void ObjectMgr::LoadItemLocales()
1493 mItemLocaleMap.clear(); // need for reload case
1495 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");
1497 if(!result)
1499 barGoLink bar(1);
1501 bar.step();
1503 sLog.outString("");
1504 sLog.outString(">> Loaded 0 Item locale strings. DB table `locales_item` is empty.");
1505 return;
1508 barGoLink bar(result->GetRowCount());
1512 Field *fields = result->Fetch();
1513 bar.step();
1515 uint32 entry = fields[0].GetUInt32();
1517 ItemLocale& data = mItemLocaleMap[entry];
1519 for(int i = 1; i < MAX_LOCALE; ++i)
1521 std::string str = fields[1+2*(i-1)].GetCppString();
1522 if(!str.empty())
1524 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
1525 if(idx >= 0)
1527 if(data.Name.size() <= idx)
1528 data.Name.resize(idx+1);
1530 data.Name[idx] = str;
1534 str = fields[1+2*(i-1)+1].GetCppString();
1535 if(!str.empty())
1537 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
1538 if(idx >= 0)
1540 if(data.Description.size() <= idx)
1541 data.Description.resize(idx+1);
1543 data.Description[idx] = str;
1547 } while (result->NextRow());
1549 delete result;
1551 sLog.outString();
1552 sLog.outString( ">> Loaded %u Item locale strings", mItemLocaleMap.size() );
1555 void ObjectMgr::LoadItemPrototypes()
1557 sItemStorage.Load ();
1558 sLog.outString( ">> Loaded %u item prototypes", sItemStorage.RecordCount );
1559 sLog.outString();
1561 // check data correctness
1562 for(uint32 i = 1; i < sItemStorage.MaxEntry; ++i)
1564 ItemPrototype const* proto = sItemStorage.LookupEntry<ItemPrototype >(i);
1565 ItemEntry const *dbcitem = sItemStore.LookupEntry(i);
1566 if(!proto)
1568 /* to many errors, and possible not all items really used in game
1569 if (dbcitem)
1570 sLog.outErrorDb("Item (Entry: %u) doesn't exists in DB, but must exist.",i);
1572 continue;
1575 if(dbcitem)
1577 if(proto->InventoryType != dbcitem->InventoryType)
1579 sLog.outErrorDb("Item (Entry: %u) not correct %u inventory type, must be %u (still using DB value).",i,proto->InventoryType,dbcitem->InventoryType);
1580 // It safe let use InventoryType from DB
1583 if(proto->DisplayInfoID != dbcitem->DisplayId)
1585 sLog.outErrorDb("Item (Entry: %u) not correct %u display id, must be %u (using it).",i,proto->DisplayInfoID,dbcitem->DisplayId);
1586 const_cast<ItemPrototype*>(proto)->DisplayInfoID = dbcitem->DisplayId;
1588 if(proto->Sheath != dbcitem->Sheath)
1590 sLog.outErrorDb("Item (Entry: %u) not correct %u sheath, must be %u (using it).",i,proto->Sheath,dbcitem->Sheath);
1591 const_cast<ItemPrototype*>(proto)->Sheath = dbcitem->Sheath;
1594 else
1596 sLog.outErrorDb("Item (Entry: %u) not correct (not listed in list of existed items).",i);
1599 if(proto->Class >= MAX_ITEM_CLASS)
1601 sLog.outErrorDb("Item (Entry: %u) has wrong Class value (%u)",i,proto->Class);
1602 const_cast<ItemPrototype*>(proto)->Class = ITEM_CLASS_MISC;
1605 if(proto->SubClass >= MaxItemSubclassValues[proto->Class])
1607 sLog.outErrorDb("Item (Entry: %u) has wrong Subclass value (%u) for class %u",i,proto->SubClass,proto->Class);
1608 const_cast<ItemPrototype*>(proto)->SubClass = 0;// exist for all item classes
1611 if(proto->Quality >= MAX_ITEM_QUALITY)
1613 sLog.outErrorDb("Item (Entry: %u) has wrong Quality value (%u)",i,proto->Quality);
1614 const_cast<ItemPrototype*>(proto)->Quality = ITEM_QUALITY_NORMAL;
1617 if(proto->BuyCount <= 0)
1619 sLog.outErrorDb("Item (Entry: %u) has wrong BuyCount value (%u), set to default(1).",i,proto->BuyCount);
1620 const_cast<ItemPrototype*>(proto)->BuyCount = 1;
1623 if(proto->InventoryType >= MAX_INVTYPE)
1625 sLog.outErrorDb("Item (Entry: %u) has wrong InventoryType value (%u)",i,proto->InventoryType);
1626 const_cast<ItemPrototype*>(proto)->InventoryType = INVTYPE_NON_EQUIP;
1629 if(proto->RequiredSkill >= MAX_SKILL_TYPE)
1631 sLog.outErrorDb("Item (Entry: %u) has wrong RequiredSkill value (%u)",i,proto->RequiredSkill);
1632 const_cast<ItemPrototype*>(proto)->RequiredSkill = 0;
1635 if(!(proto->AllowableClass & CLASSMASK_ALL_PLAYABLE))
1637 sLog.outErrorDb("Item (Entry: %u) not have in `AllowableClass` any playable classes (%u) and can't be equipped.",i,proto->AllowableClass);
1640 if(!(proto->AllowableRace & RACEMASK_ALL_PLAYABLE))
1642 sLog.outErrorDb("Item (Entry: %u) not have in `AllowableRace` any playable races (%u) and can't be equipped.",i,proto->AllowableRace);
1645 if(proto->RequiredSpell && !sSpellStore.LookupEntry(proto->RequiredSpell))
1647 sLog.outErrorDb("Item (Entry: %u) have wrong (non-existed) spell in RequiredSpell (%u)",i,proto->RequiredSpell);
1648 const_cast<ItemPrototype*>(proto)->RequiredSpell = 0;
1651 if(proto->RequiredReputationRank >= MAX_REPUTATION_RANK)
1652 sLog.outErrorDb("Item (Entry: %u) has wrong reputation rank in RequiredReputationRank (%u), item can't be used.",i,proto->RequiredReputationRank);
1654 if(proto->RequiredReputationFaction)
1656 if(!sFactionStore.LookupEntry(proto->RequiredReputationFaction))
1658 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) faction in RequiredReputationFaction (%u)",i,proto->RequiredReputationFaction);
1659 const_cast<ItemPrototype*>(proto)->RequiredReputationFaction = 0;
1662 if(proto->RequiredReputationRank == MIN_REPUTATION_RANK)
1663 sLog.outErrorDb("Item (Entry: %u) has min. reputation rank in RequiredReputationRank (0) but RequiredReputationFaction > 0, faction setting is useless.",i);
1665 else if(proto->RequiredReputationRank > MIN_REPUTATION_RANK)
1666 sLog.outErrorDb("Item (Entry: %u) has RequiredReputationFaction ==0 but RequiredReputationRank > 0, rank setting is useless.",i);
1668 if(proto->Stackable==0)
1670 sLog.outErrorDb("Item (Entry: %u) has wrong value in stackable (%u), replace by default 1.",i,proto->Stackable);
1671 const_cast<ItemPrototype*>(proto)->Stackable = 1;
1673 else if(proto->Stackable > 255)
1675 sLog.outErrorDb("Item (Entry: %u) has too large value in stackable (%u), replace by hardcoded upper limit (255).",i,proto->Stackable);
1676 const_cast<ItemPrototype*>(proto)->Stackable = 255;
1679 for (int j = 0; j < 10; j++)
1681 // for ItemStatValue != 0
1682 if(proto->ItemStat[j].ItemStatValue && proto->ItemStat[j].ItemStatType >= MAX_ITEM_MOD)
1684 sLog.outErrorDb("Item (Entry: %u) has wrong stat_type%d (%u)",i,j+1,proto->ItemStat[j].ItemStatType);
1685 const_cast<ItemPrototype*>(proto)->ItemStat[j].ItemStatType = 0;
1689 for (int j = 0; j < 5; j++)
1691 if(proto->Damage[j].DamageType >= MAX_SPELL_SCHOOL)
1693 sLog.outErrorDb("Item (Entry: %u) has wrong dmg_type%d (%u)",i,j+1,proto->Damage[j].DamageType);
1694 const_cast<ItemPrototype*>(proto)->Damage[j].DamageType = 0;
1698 // special format
1699 if((proto->Spells[0].SpellId == SPELL_ID_GENERIC_LEARN) || (proto->Spells[0].SpellId == SPELL_ID_GENERIC_LEARN_PET))
1701 // spell_1
1702 if(proto->Spells[0].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
1704 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);
1705 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1706 const_cast<ItemPrototype*>(proto)->Spells[0].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1707 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1708 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1711 // spell_2 have learning spell
1712 if(proto->Spells[1].SpellTrigger != ITEM_SPELLTRIGGER_LEARN_SPELL_ID)
1714 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);
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 else if(!proto->Spells[1].SpellId)
1721 sLog.outErrorDb("Item (Entry: %u) not has expected spell in spellid_%d in special learning format.",i,1+1);
1722 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1723 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1725 else
1727 SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[1].SpellId);
1728 if(!spellInfo)
1730 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%u)",i,1+1,proto->Spells[1].SpellId);
1731 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1732 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1733 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1735 // allowed only in special format
1736 else if((proto->Spells[1].SpellId==SPELL_ID_GENERIC_LEARN) || (proto->Spells[1].SpellId==SPELL_ID_GENERIC_LEARN_PET))
1738 sLog.outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%u)",i,1+1,proto->Spells[1].SpellId);
1739 const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1740 const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1741 const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1745 // spell_3*,spell_4*,spell_5* is empty
1746 for (int j = 2; j < 5; j++)
1748 if(proto->Spells[j].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
1750 sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)",i,j+1,proto->Spells[j].SpellTrigger);
1751 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1752 const_cast<ItemPrototype*>(proto)->Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1754 else if(proto->Spells[j].SpellId != 0)
1756 sLog.outErrorDb("Item (Entry: %u) has wrong spell in spellid_%d (%u) for learning special format",i,j+1,proto->Spells[j].SpellId);
1757 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1761 // normal spell list
1762 else
1764 for (int j = 0; j < 5; j++)
1766 if(proto->Spells[j].SpellTrigger >= MAX_ITEM_SPELLTRIGGER || proto->Spells[j].SpellTrigger == ITEM_SPELLTRIGGER_LEARN_SPELL_ID)
1768 sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)",i,j+1,proto->Spells[j].SpellTrigger);
1769 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1770 const_cast<ItemPrototype*>(proto)->Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1773 if(proto->Spells[j].SpellId)
1775 SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[j].SpellId);
1776 if(!spellInfo)
1778 sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%u)",i,j+1,proto->Spells[j].SpellId);
1779 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1781 // allowed only in special format
1782 else if((proto->Spells[j].SpellId==SPELL_ID_GENERIC_LEARN) || (proto->Spells[j].SpellId==SPELL_ID_GENERIC_LEARN_PET))
1784 sLog.outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%u)",i,j+1,proto->Spells[j].SpellId);
1785 const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1791 if(proto->Bonding >= MAX_BIND_TYPE)
1792 sLog.outErrorDb("Item (Entry: %u) has wrong Bonding value (%u)",i,proto->Bonding);
1794 if(proto->PageText && !sPageTextStore.LookupEntry<PageText>(proto->PageText))
1795 sLog.outErrorDb("Item (Entry: %u) has non existing first page (Id:%u)", i,proto->PageText);
1797 if(proto->LockID && !sLockStore.LookupEntry(proto->LockID))
1798 sLog.outErrorDb("Item (Entry: %u) has wrong LockID (%u)",i,proto->LockID);
1800 if(proto->Sheath >= MAX_SHEATHETYPE)
1802 sLog.outErrorDb("Item (Entry: %u) has wrong Sheath (%u)",i,proto->Sheath);
1803 const_cast<ItemPrototype*>(proto)->Sheath = SHEATHETYPE_NONE;
1806 if(proto->RandomProperty && !sItemRandomPropertiesStore.LookupEntry(GetItemEnchantMod(proto->RandomProperty)))
1808 sLog.outErrorDb("Item (Entry: %u) has unknown (wrong or not listed in `item_enchantment_template`) RandomProperty (%u)",i,proto->RandomProperty);
1809 const_cast<ItemPrototype*>(proto)->RandomProperty = 0;
1812 if(proto->RandomSuffix && !sItemRandomSuffixStore.LookupEntry(GetItemEnchantMod(proto->RandomSuffix)))
1814 sLog.outErrorDb("Item (Entry: %u) has wrong RandomSuffix (%u)",i,proto->RandomSuffix);
1815 const_cast<ItemPrototype*>(proto)->RandomSuffix = 0;
1818 if(proto->ItemSet && !sItemSetStore.LookupEntry(proto->ItemSet))
1820 sLog.outErrorDb("Item (Entry: %u) have wrong ItemSet (%u)",i,proto->ItemSet);
1821 const_cast<ItemPrototype*>(proto)->ItemSet = 0;
1824 if(proto->Area && !GetAreaEntryByAreaID(proto->Area))
1825 sLog.outErrorDb("Item (Entry: %u) has wrong Area (%u)",i,proto->Area);
1827 if(proto->Map && !sMapStore.LookupEntry(proto->Map))
1828 sLog.outErrorDb("Item (Entry: %u) has wrong Map (%u)",i,proto->Map);
1830 if(proto->TotemCategory && !sTotemCategoryStore.LookupEntry(proto->TotemCategory))
1831 sLog.outErrorDb("Item (Entry: %u) has wrong TotemCategory (%u)",i,proto->TotemCategory);
1833 for (int j = 0; j < 3; j++)
1835 if(proto->Socket[j].Color && (proto->Socket[j].Color & SOCKET_COLOR_ALL) != proto->Socket[j].Color)
1837 sLog.outErrorDb("Item (Entry: %u) has wrong socketColor_%d (%u)",i,j+1,proto->Socket[j].Color);
1838 const_cast<ItemPrototype*>(proto)->Socket[j].Color = 0;
1842 if(proto->GemProperties && !sGemPropertiesStore.LookupEntry(proto->GemProperties))
1843 sLog.outErrorDb("Item (Entry: %u) has wrong GemProperties (%u)",i,proto->GemProperties);
1845 if(proto->FoodType >= MAX_PET_DIET)
1847 sLog.outErrorDb("Item (Entry: %u) has wrong FoodType value (%u)",i,proto->FoodType);
1848 const_cast<ItemPrototype*>(proto)->FoodType = 0;
1852 // this DBC used currently only for check item templates in DB.
1853 sItemStore.Clear();
1856 void ObjectMgr::LoadAuctionItems()
1858 QueryResult *result = CharacterDatabase.Query( "SELECT itemguid,item_template FROM auctionhouse" );
1860 if( !result )
1861 return;
1863 barGoLink bar( result->GetRowCount() );
1865 uint32 count = 0;
1867 Field *fields;
1870 bar.step();
1872 fields = result->Fetch();
1873 uint32 item_guid = fields[0].GetUInt32();
1874 uint32 item_template = fields[1].GetUInt32();
1876 ItemPrototype const *proto = GetItemPrototype(item_template);
1878 if(!proto)
1880 sLog.outError( "ObjectMgr::LoadAuctionItems: Unknown item (GUID: %u id: #%u) in auction, skipped.", item_guid,item_template);
1881 continue;
1884 Item *item = NewItemOrBag(proto);
1886 if(!item->LoadFromDB(item_guid,0))
1888 delete item;
1889 continue;
1891 AddAItem(item);
1893 ++count;
1895 while( result->NextRow() );
1897 delete result;
1899 sLog.outString();
1900 sLog.outString( ">> Loaded %u auction items", count );
1903 void ObjectMgr::LoadPetLevelInfo()
1905 // Loading levels data
1907 // 0 1 2 3 4 5 6 7 8 9
1908 QueryResult *result = WorldDatabase.Query("SELECT creature_entry, level, hp, mana, str, agi, sta, inte, spi, armor FROM pet_levelstats");
1910 uint32 count = 0;
1912 if (!result)
1914 barGoLink bar( 1 );
1916 sLog.outString();
1917 sLog.outString( ">> Loaded %u level pet stats definitions", count );
1918 sLog.outErrorDb( "Error loading `pet_levelstats` table or empty table.");
1919 return;
1922 barGoLink bar( result->GetRowCount() );
1926 Field* fields = result->Fetch();
1928 uint32 creature_id = fields[0].GetUInt32();
1929 if(!sCreatureStorage.LookupEntry<CreatureInfo>(creature_id))
1931 sLog.outErrorDb("Wrong creature id %u in `pet_levelstats` table, ignoring.",creature_id);
1932 continue;
1935 uint32 current_level = fields[1].GetUInt32();
1936 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
1938 if(current_level > 255) // hardcoded level maximum
1939 sLog.outErrorDb("Wrong (> 255) level %u in `pet_levelstats` table, ignoring.",current_level);
1940 else
1941 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `pet_levelstats` table, ignoring.",current_level);
1942 continue;
1944 else if(current_level < 1)
1946 sLog.outErrorDb("Wrong (<1) level %u in `pet_levelstats` table, ignoring.",current_level);
1947 continue;
1950 PetLevelInfo*& pInfoMapEntry = petInfo[creature_id];
1952 if(pInfoMapEntry==NULL)
1953 pInfoMapEntry = new PetLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
1955 // data for level 1 stored in [0] array element, ...
1956 PetLevelInfo* pLevelInfo = &pInfoMapEntry[current_level-1];
1958 pLevelInfo->health = fields[2].GetUInt16();
1959 pLevelInfo->mana = fields[3].GetUInt16();
1960 pLevelInfo->armor = fields[9].GetUInt16();
1962 for (int i = 0; i < MAX_STATS; i++)
1964 pLevelInfo->stats[i] = fields[i+4].GetUInt16();
1967 bar.step();
1968 ++count;
1970 while (result->NextRow());
1972 delete result;
1974 sLog.outString();
1975 sLog.outString( ">> Loaded %u level pet stats definitions", count );
1978 // Fill gaps and check integrity
1979 for (PetLevelInfoMap::iterator itr = petInfo.begin(); itr != petInfo.end(); ++itr)
1981 PetLevelInfo* pInfo = itr->second;
1983 // fatal error if no level 1 data
1984 if(!pInfo || pInfo[0].health == 0 )
1986 sLog.outErrorDb("Creature %u does not have pet stats data for Level 1!",itr->first);
1987 exit(1);
1990 // fill level gaps
1991 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
1993 if(pInfo[level].health == 0)
1995 sLog.outErrorDb("Creature %u has no data for Level %i pet stats data, using data of Level %i.",itr->first,level+1, level);
1996 pInfo[level] = pInfo[level-1];
2002 PetLevelInfo const* ObjectMgr::GetPetLevelInfo(uint32 creature_id, uint32 level) const
2004 if(level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2005 level = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL);
2007 PetLevelInfoMap::const_iterator itr = petInfo.find(creature_id);
2008 if(itr == petInfo.end())
2009 return NULL;
2011 return &itr->second[level-1]; // data for level 1 stored in [0] array element, ...
2014 void ObjectMgr::LoadPlayerInfo()
2016 // Load playercreate
2018 // 0 1 2 3 4 5 6
2019 QueryResult *result = WorldDatabase.Query("SELECT race, class, map, zone, position_x, position_y, position_z FROM playercreateinfo");
2021 uint32 count = 0;
2023 if (!result)
2025 barGoLink bar( 1 );
2027 sLog.outString();
2028 sLog.outString( ">> Loaded %u player create definitions", count );
2029 sLog.outErrorDb( "Error loading `playercreateinfo` table or empty table.");
2030 exit(1);
2033 barGoLink bar( result->GetRowCount() );
2037 Field* fields = result->Fetch();
2039 uint32 current_race = fields[0].GetUInt32();
2040 uint32 current_class = fields[1].GetUInt32();
2041 uint32 mapId = fields[2].GetUInt32();
2042 uint32 zoneId = fields[3].GetUInt32();
2043 float positionX = fields[4].GetFloat();
2044 float positionY = fields[5].GetFloat();
2045 float positionZ = fields[6].GetFloat();
2047 if(current_race >= MAX_RACES)
2049 sLog.outErrorDb("Wrong race %u in `playercreateinfo` table, ignoring.",current_race);
2050 continue;
2053 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(current_race);
2054 if(!rEntry)
2056 sLog.outErrorDb("Wrong race %u in `playercreateinfo` table, ignoring.",current_race);
2057 continue;
2060 if(current_class >= MAX_CLASSES)
2062 sLog.outErrorDb("Wrong class %u in `playercreateinfo` table, ignoring.",current_class);
2063 continue;
2066 if(!sChrClassesStore.LookupEntry(current_class))
2068 sLog.outErrorDb("Wrong class %u in `playercreateinfo` table, ignoring.",current_class);
2069 continue;
2072 // accept DB data only for valid position (and non instanceable)
2073 if( !MapManager::IsValidMapCoord(mapId,positionX,positionY,positionZ) )
2075 sLog.outErrorDb("Wrong home position for class %u race %u pair in `playercreateinfo` table, ignoring.",current_class,current_race);
2076 continue;
2079 if( sMapStore.LookupEntry(mapId)->Instanceable() )
2081 sLog.outErrorDb("Home position in instanceable map for class %u race %u pair in `playercreateinfo` table, ignoring.",current_class,current_race);
2082 continue;
2085 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2087 pInfo->mapId = mapId;
2088 pInfo->zoneId = zoneId;
2089 pInfo->positionX = positionX;
2090 pInfo->positionY = positionY;
2091 pInfo->positionZ = positionZ;
2093 pInfo->displayId_m = rEntry->model_m;
2094 pInfo->displayId_f = rEntry->model_f;
2096 bar.step();
2097 ++count;
2099 while (result->NextRow());
2101 delete result;
2103 sLog.outString();
2104 sLog.outString( ">> Loaded %u player create definitions", count );
2107 // Load playercreate items
2109 // 0 1 2 3
2110 QueryResult *result = WorldDatabase.Query("SELECT race, class, itemid, amount FROM playercreateinfo_item");
2112 uint32 count = 0;
2114 if (!result)
2116 barGoLink bar( 1 );
2118 sLog.outString();
2119 sLog.outString( ">> Loaded %u player create items", count );
2120 sLog.outErrorDb( "Error loading `playercreateinfo_item` table or empty table.");
2122 else
2124 barGoLink bar( result->GetRowCount() );
2128 Field* fields = result->Fetch();
2130 uint32 current_race = fields[0].GetUInt32();
2131 if(current_race >= MAX_RACES)
2133 sLog.outErrorDb("Wrong race %u in `playercreateinfo_item` table, ignoring.",current_race);
2134 continue;
2137 uint32 current_class = fields[1].GetUInt32();
2138 if(current_class >= MAX_CLASSES)
2140 sLog.outErrorDb("Wrong class %u in `playercreateinfo_item` table, ignoring.",current_class);
2141 continue;
2144 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2146 uint32 item_id = fields[2].GetUInt32();
2148 if(!GetItemPrototype(item_id))
2150 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);
2151 continue;
2154 uint32 amount = fields[3].GetUInt32();
2156 if(!amount)
2158 sLog.outErrorDb("Item id %u (class %u race %u) have amount==0 in `playercreateinfo_item` table, ignoring.",item_id,current_race,current_class);
2159 continue;
2162 pInfo->item.push_back(PlayerCreateInfoItem( item_id, amount));
2164 bar.step();
2165 ++count;
2167 while(result->NextRow());
2169 delete result;
2171 sLog.outString();
2172 sLog.outString( ">> Loaded %u player create items", count );
2176 // Load playercreate spells
2178 // 0 1 2 3
2179 QueryResult *result = WorldDatabase.Query("SELECT race, class, Spell, Active FROM playercreateinfo_spell");
2181 uint32 count = 0;
2183 if (!result)
2185 barGoLink bar( 1 );
2187 sLog.outString();
2188 sLog.outString( ">> Loaded %u player create spells", count );
2189 sLog.outErrorDb( "Error loading `playercreateinfo_spell` table or empty table.");
2191 else
2193 barGoLink bar( result->GetRowCount() );
2197 Field* fields = result->Fetch();
2199 uint32 current_race = fields[0].GetUInt32();
2200 if(current_race >= MAX_RACES)
2202 sLog.outErrorDb("Wrong race %u in `playercreateinfo_spell` table, ignoring.",current_race);
2203 continue;
2206 uint32 current_class = fields[1].GetUInt32();
2207 if(current_class >= MAX_CLASSES)
2209 sLog.outErrorDb("Wrong class %u in `playercreateinfo_spell` table, ignoring.",current_class);
2210 continue;
2213 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2214 pInfo->spell.push_back(CreateSpellPair(fields[2].GetUInt16(), fields[3].GetUInt8()));
2216 bar.step();
2217 ++count;
2219 while( result->NextRow() );
2221 delete result;
2223 sLog.outString();
2224 sLog.outString( ">> Loaded %u player create spells", count );
2228 // Load playercreate actions
2230 // 0 1 2 3 4 5
2231 QueryResult *result = WorldDatabase.Query("SELECT race, class, button, action, type, misc FROM playercreateinfo_action");
2233 uint32 count = 0;
2235 if (!result)
2237 barGoLink bar( 1 );
2239 sLog.outString();
2240 sLog.outString( ">> Loaded %u player create actions", count );
2241 sLog.outErrorDb( "Error loading `playercreateinfo_action` table or empty table.");
2243 else
2245 barGoLink bar( result->GetRowCount() );
2249 Field* fields = result->Fetch();
2251 uint32 current_race = fields[0].GetUInt32();
2252 if(current_race >= MAX_RACES)
2254 sLog.outErrorDb("Wrong race %u in `playercreateinfo_action` table, ignoring.",current_race);
2255 continue;
2258 uint32 current_class = fields[1].GetUInt32();
2259 if(current_class >= MAX_CLASSES)
2261 sLog.outErrorDb("Wrong class %u in `playercreateinfo_action` table, ignoring.",current_class);
2262 continue;
2265 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2266 pInfo->action[0].push_back(fields[2].GetUInt16());
2267 pInfo->action[1].push_back(fields[3].GetUInt16());
2268 pInfo->action[2].push_back(fields[4].GetUInt16());
2269 pInfo->action[3].push_back(fields[5].GetUInt16());
2271 bar.step();
2272 ++count;
2274 while( result->NextRow() );
2276 delete result;
2278 sLog.outString();
2279 sLog.outString( ">> Loaded %u player create actions", count );
2283 // Loading levels data (class only dependent)
2285 // 0 1 2 3
2286 QueryResult *result = WorldDatabase.Query("SELECT class, level, basehp, basemana FROM player_classlevelstats");
2288 uint32 count = 0;
2290 if (!result)
2292 barGoLink bar( 1 );
2294 sLog.outString();
2295 sLog.outString( ">> Loaded %u level health/mana definitions", count );
2296 sLog.outErrorDb( "Error loading `player_classlevelstats` table or empty table.");
2297 exit(1);
2300 barGoLink bar( result->GetRowCount() );
2304 Field* fields = result->Fetch();
2306 uint32 current_class = fields[0].GetUInt32();
2307 if(current_class >= MAX_CLASSES)
2309 sLog.outErrorDb("Wrong class %u in `player_classlevelstats` table, ignoring.",current_class);
2310 continue;
2313 uint32 current_level = fields[1].GetUInt32();
2314 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2316 if(current_level > 255) // hardcoded level maximum
2317 sLog.outErrorDb("Wrong (> 255) level %u in `player_classlevelstats` table, ignoring.",current_level);
2318 else
2319 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_classlevelstats` table, ignoring.",current_level);
2320 continue;
2323 PlayerClassInfo* pClassInfo = &playerClassInfo[current_class];
2325 if(!pClassInfo->levelInfo)
2326 pClassInfo->levelInfo = new PlayerClassLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
2328 PlayerClassLevelInfo* pClassLevelInfo = &pClassInfo->levelInfo[current_level-1];
2330 pClassLevelInfo->basehealth = fields[2].GetUInt16();
2331 pClassLevelInfo->basemana = fields[3].GetUInt16();
2333 bar.step();
2334 ++count;
2336 while (result->NextRow());
2338 delete result;
2340 sLog.outString();
2341 sLog.outString( ">> Loaded %u level health/mana definitions", count );
2344 // Fill gaps and check integrity
2345 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2347 // skip non existed classes
2348 if(!sChrClassesStore.LookupEntry(class_))
2349 continue;
2351 PlayerClassInfo* pClassInfo = &playerClassInfo[class_];
2353 // fatal error if no level 1 data
2354 if(!pClassInfo->levelInfo || pClassInfo->levelInfo[0].basehealth == 0 )
2356 sLog.outErrorDb("Class %i Level 1 does not have health/mana data!",class_);
2357 exit(1);
2360 // fill level gaps
2361 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2363 if(pClassInfo->levelInfo[level].basehealth == 0)
2365 sLog.outErrorDb("Class %i Level %i does not have health/mana data. Using stats data of level %i.",class_,level+1, level);
2366 pClassInfo->levelInfo[level] = pClassInfo->levelInfo[level-1];
2371 // Loading levels data (class/race dependent)
2373 // 0 1 2 3 4 5 6 7
2374 QueryResult *result = WorldDatabase.Query("SELECT race, class, level, str, agi, sta, inte, spi FROM player_levelstats");
2376 uint32 count = 0;
2378 if (!result)
2380 barGoLink bar( 1 );
2382 sLog.outString();
2383 sLog.outString( ">> Loaded %u level stats definitions", count );
2384 sLog.outErrorDb( "Error loading `player_levelstats` table or empty table.");
2385 exit(1);
2388 barGoLink bar( result->GetRowCount() );
2392 Field* fields = result->Fetch();
2394 uint32 current_race = fields[0].GetUInt32();
2395 if(current_race >= MAX_RACES)
2397 sLog.outErrorDb("Wrong race %u in `player_levelstats` table, ignoring.",current_race);
2398 continue;
2401 uint32 current_class = fields[1].GetUInt32();
2402 if(current_class >= MAX_CLASSES)
2404 sLog.outErrorDb("Wrong class %u in `player_levelstats` table, ignoring.",current_class);
2405 continue;
2408 uint32 current_level = fields[2].GetUInt32();
2409 if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2411 if(current_level > 255) // hardcoded level maximum
2412 sLog.outErrorDb("Wrong (> 255) level %u in `player_levelstats` table, ignoring.",current_level);
2413 else
2414 sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_levelstats` table, ignoring.",current_level);
2415 continue;
2418 PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2420 if(!pInfo->levelInfo)
2421 pInfo->levelInfo = new PlayerLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
2423 PlayerLevelInfo* pLevelInfo = &pInfo->levelInfo[current_level-1];
2425 for (int i = 0; i < MAX_STATS; i++)
2427 pLevelInfo->stats[i] = fields[i+3].GetUInt8();
2430 bar.step();
2431 ++count;
2433 while (result->NextRow());
2435 delete result;
2437 sLog.outString();
2438 sLog.outString( ">> Loaded %u level stats definitions", count );
2441 // Fill gaps and check integrity
2442 for (int race = 0; race < MAX_RACES; ++race)
2444 // skip non existed races
2445 if(!sChrRacesStore.LookupEntry(race))
2446 continue;
2448 for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2450 // skip non existed classes
2451 if(!sChrClassesStore.LookupEntry(class_))
2452 continue;
2454 PlayerInfo* pInfo = &playerInfo[race][class_];
2456 // skip non loaded combinations
2457 if(!pInfo->displayId_m || !pInfo->displayId_f)
2458 continue;
2460 // skip expansion races if not playing with expansion
2461 if (sWorld.getConfig(CONFIG_EXPANSION) < 1 && (race == RACE_BLOODELF || race == RACE_DRAENEI))
2462 continue;
2464 // skip expansion classes if not playing with expansion
2465 if (sWorld.getConfig(CONFIG_EXPANSION) < 2 && class_ == CLASS_DEATH_KNIGHT)
2466 continue;
2468 // fatal error if no level 1 data
2469 if(!pInfo->levelInfo || pInfo->levelInfo[0].stats[0] == 0 )
2471 sLog.outErrorDb("Race %i Class %i Level 1 does not have stats data!",race,class_);
2472 exit(1);
2475 // fill level gaps
2476 for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2478 if(pInfo->levelInfo[level].stats[0] == 0)
2480 sLog.outErrorDb("Race %i Class %i Level %i does not have stats data. Using stats data of level %i.",race,class_,level+1, level);
2481 pInfo->levelInfo[level] = pInfo->levelInfo[level-1];
2488 void ObjectMgr::GetPlayerClassLevelInfo(uint32 class_, uint32 level, PlayerClassLevelInfo* info) const
2490 if(level < 1 || class_ >= MAX_CLASSES)
2491 return;
2493 PlayerClassInfo const* pInfo = &playerClassInfo[class_];
2495 if(level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2496 level = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL);
2498 *info = pInfo->levelInfo[level-1];
2501 void ObjectMgr::GetPlayerLevelInfo(uint32 race, uint32 class_, uint32 level, PlayerLevelInfo* info) const
2503 if(level < 1 || race >= MAX_RACES || class_ >= MAX_CLASSES)
2504 return;
2506 PlayerInfo const* pInfo = &playerInfo[race][class_];
2507 if(pInfo->displayId_m==0 || pInfo->displayId_f==0)
2508 return;
2510 if(level <= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2511 *info = pInfo->levelInfo[level-1];
2512 else
2513 BuildPlayerLevelInfo(race,class_,level,info);
2516 void ObjectMgr::BuildPlayerLevelInfo(uint8 race, uint8 _class, uint8 level, PlayerLevelInfo* info) const
2518 // base data (last known level)
2519 *info = playerInfo[race][_class].levelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)-1];
2521 for(int lvl = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)-1; lvl < level; ++lvl)
2523 switch(_class)
2525 case CLASS_WARRIOR:
2526 info->stats[STAT_STRENGTH] += (lvl > 23 ? 2: (lvl > 1 ? 1: 0));
2527 info->stats[STAT_STAMINA] += (lvl > 23 ? 2: (lvl > 1 ? 1: 0));
2528 info->stats[STAT_AGILITY] += (lvl > 36 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2529 info->stats[STAT_INTELLECT] += (lvl > 9 && !(lvl%2) ? 1: 0);
2530 info->stats[STAT_SPIRIT] += (lvl > 9 && !(lvl%2) ? 1: 0);
2531 break;
2532 case CLASS_PALADIN:
2533 info->stats[STAT_STRENGTH] += (lvl > 3 ? 1: 0);
2534 info->stats[STAT_STAMINA] += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2535 info->stats[STAT_AGILITY] += (lvl > 38 ? 1: (lvl > 7 && !(lvl%2) ? 1: 0));
2536 info->stats[STAT_INTELLECT] += (lvl > 6 && (lvl%2) ? 1: 0);
2537 info->stats[STAT_SPIRIT] += (lvl > 7 ? 1: 0);
2538 break;
2539 case CLASS_HUNTER:
2540 info->stats[STAT_STRENGTH] += (lvl > 4 ? 1: 0);
2541 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2542 info->stats[STAT_AGILITY] += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2543 info->stats[STAT_INTELLECT] += (lvl > 8 && (lvl%2) ? 1: 0);
2544 info->stats[STAT_SPIRIT] += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2545 break;
2546 case CLASS_ROGUE:
2547 info->stats[STAT_STRENGTH] += (lvl > 5 ? 1: 0);
2548 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2549 info->stats[STAT_AGILITY] += (lvl > 16 ? 2: (lvl > 1 ? 1: 0));
2550 info->stats[STAT_INTELLECT] += (lvl > 8 && !(lvl%2) ? 1: 0);
2551 info->stats[STAT_SPIRIT] += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2552 break;
2553 case CLASS_PRIEST:
2554 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2555 info->stats[STAT_STAMINA] += (lvl > 5 ? 1: 0);
2556 info->stats[STAT_AGILITY] += (lvl > 38 ? 1: (lvl > 8 && (lvl%2) ? 1: 0));
2557 info->stats[STAT_INTELLECT] += (lvl > 22 ? 2: (lvl > 1 ? 1: 0));
2558 info->stats[STAT_SPIRIT] += (lvl > 3 ? 1: 0);
2559 break;
2560 case CLASS_SHAMAN:
2561 info->stats[STAT_STRENGTH] += (lvl > 34 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2562 info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0);
2563 info->stats[STAT_AGILITY] += (lvl > 7 && !(lvl%2) ? 1: 0);
2564 info->stats[STAT_INTELLECT] += (lvl > 5 ? 1: 0);
2565 info->stats[STAT_SPIRIT] += (lvl > 4 ? 1: 0);
2566 break;
2567 case CLASS_MAGE:
2568 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2569 info->stats[STAT_STAMINA] += (lvl > 5 ? 1: 0);
2570 info->stats[STAT_AGILITY] += (lvl > 9 && !(lvl%2) ? 1: 0);
2571 info->stats[STAT_INTELLECT] += (lvl > 24 ? 2: (lvl > 1 ? 1: 0));
2572 info->stats[STAT_SPIRIT] += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
2573 break;
2574 case CLASS_WARLOCK:
2575 info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0);
2576 info->stats[STAT_STAMINA] += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
2577 info->stats[STAT_AGILITY] += (lvl > 9 && !(lvl%2) ? 1: 0);
2578 info->stats[STAT_INTELLECT] += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
2579 info->stats[STAT_SPIRIT] += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
2580 break;
2581 case CLASS_DRUID:
2582 info->stats[STAT_STRENGTH] += (lvl > 38 ? 2: (lvl > 6 && (lvl%2) ? 1: 0));
2583 info->stats[STAT_STAMINA] += (lvl > 32 ? 2: (lvl > 4 ? 1: 0));
2584 info->stats[STAT_AGILITY] += (lvl > 38 ? 2: (lvl > 8 && (lvl%2) ? 1: 0));
2585 info->stats[STAT_INTELLECT] += (lvl > 38 ? 3: (lvl > 4 ? 1: 0));
2586 info->stats[STAT_SPIRIT] += (lvl > 38 ? 3: (lvl > 5 ? 1: 0));
2591 void ObjectMgr::LoadGuilds()
2593 Guild *newguild;
2594 uint32 count = 0;
2596 QueryResult *result = CharacterDatabase.Query( "SELECT guildid FROM guild" );
2598 if( !result )
2601 barGoLink bar( 1 );
2603 bar.step();
2605 sLog.outString();
2606 sLog.outString( ">> Loaded %u guild definitions", count );
2607 return;
2610 barGoLink bar( result->GetRowCount() );
2614 Field *fields = result->Fetch();
2616 bar.step();
2617 ++count;
2619 newguild = new Guild;
2620 if(!newguild->LoadGuildFromDB(fields[0].GetUInt32()))
2622 newguild->Disband();
2623 delete newguild;
2624 continue;
2626 AddGuild(newguild);
2628 }while( result->NextRow() );
2630 delete result;
2632 sLog.outString();
2633 sLog.outString( ">> Loaded %u guild definitions", count );
2636 void ObjectMgr::LoadArenaTeams()
2638 uint32 count = 0;
2640 QueryResult *result = CharacterDatabase.Query( "SELECT arenateamid FROM arena_team" );
2642 if( !result )
2645 barGoLink bar( 1 );
2647 bar.step();
2649 sLog.outString();
2650 sLog.outString( ">> Loaded %u arenateam definitions", count );
2651 return;
2654 barGoLink bar( result->GetRowCount() );
2658 Field *fields = result->Fetch();
2660 bar.step();
2661 ++count;
2663 ArenaTeam *newarenateam = new ArenaTeam;
2664 if(!newarenateam->LoadArenaTeamFromDB(fields[0].GetUInt32()))
2666 delete newarenateam;
2667 continue;
2669 AddArenaTeam(newarenateam);
2670 }while( result->NextRow() );
2672 delete result;
2674 sLog.outString();
2675 sLog.outString( ">> Loaded %u arenateam definitions", count );
2678 void ObjectMgr::LoadGroups()
2680 // -- loading groups --
2681 Group *group = NULL;
2682 uint64 leaderGuid = 0;
2683 uint32 count = 0;
2684 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
2685 QueryResult *result = CharacterDatabase.Query("SELECT mainTank, mainAssistant, lootMethod, looterGuid, lootThreshold, icon1, icon2, icon3, icon4, icon5, icon6, icon7, icon8, isRaid, difficulty, leaderGuid FROM groups");
2687 if( !result )
2689 barGoLink bar( 1 );
2691 bar.step();
2693 sLog.outString();
2694 sLog.outString( ">> Loaded %u group definitions", count );
2695 return;
2698 barGoLink bar( result->GetRowCount() );
2702 bar.step();
2703 Field *fields = result->Fetch();
2704 ++count;
2705 leaderGuid = MAKE_NEW_GUID(fields[15].GetUInt32(),0,HIGHGUID_PLAYER);
2707 group = new Group;
2708 if(!group->LoadGroupFromDB(leaderGuid, result, false))
2710 group->Disband();
2711 delete group;
2712 continue;
2714 AddGroup(group);
2715 }while( result->NextRow() );
2717 delete result;
2719 sLog.outString();
2720 sLog.outString( ">> Loaded %u group definitions", count );
2722 // -- loading members --
2723 count = 0;
2724 group = NULL;
2725 leaderGuid = 0;
2726 // 0 1 2 3
2727 result = CharacterDatabase.Query("SELECT memberGuid, assistant, subgroup, leaderGuid FROM group_member ORDER BY leaderGuid");
2728 if(!result)
2730 barGoLink bar( 1 );
2731 bar.step();
2733 else
2735 barGoLink bar( result->GetRowCount() );
2738 bar.step();
2739 Field *fields = result->Fetch();
2740 count++;
2741 leaderGuid = MAKE_NEW_GUID(fields[3].GetUInt32(), 0, HIGHGUID_PLAYER);
2742 if(!group || group->GetLeaderGUID() != leaderGuid)
2744 group = GetGroupByLeader(leaderGuid);
2745 if(!group)
2747 sLog.outErrorDb("Incorrect entry in group_member table : no group with leader %d for member %d!", fields[3].GetUInt32(), fields[0].GetUInt32());
2748 CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", fields[0].GetUInt32());
2749 continue;
2753 if(!group->LoadMemberFromDB(fields[0].GetUInt32(), fields[2].GetUInt8(), fields[1].GetBool()))
2755 sLog.outErrorDb("Incorrect entry in group_member table : member %d cannot be added to player %d's group!", fields[0].GetUInt32(), fields[3].GetUInt32());
2756 CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", fields[0].GetUInt32());
2758 }while( result->NextRow() );
2759 delete result;
2762 // clean groups
2763 // TODO: maybe delete from the DB before loading in this case
2764 for(GroupSet::iterator itr = mGroupSet.begin(); itr != mGroupSet.end();)
2766 if((*itr)->GetMembersCount() < 2)
2768 (*itr)->Disband();
2769 delete *itr;
2770 mGroupSet.erase(itr++);
2772 else
2773 ++itr;
2776 // -- loading instances --
2777 count = 0;
2778 group = NULL;
2779 leaderGuid = 0;
2780 result = CharacterDatabase.Query(
2781 // 0 1 2 3 4 5
2782 "SELECT leaderGuid, map, instance, permanent, difficulty, resettime, "
2783 // 6
2784 "(SELECT COUNT(*) FROM character_instance WHERE guid = leaderGuid AND instance = group_instance.instance AND permanent = 1 LIMIT 1) "
2785 "FROM group_instance LEFT JOIN instance ON instance = id ORDER BY leaderGuid"
2788 if(!result)
2790 barGoLink bar( 1 );
2791 bar.step();
2793 else
2795 barGoLink bar( result->GetRowCount() );
2798 bar.step();
2799 Field *fields = result->Fetch();
2800 count++;
2801 leaderGuid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
2802 if(!group || group->GetLeaderGUID() != leaderGuid)
2804 group = GetGroupByLeader(leaderGuid);
2805 if(!group)
2807 sLog.outErrorDb("Incorrect entry in group_instance table : no group with leader %d", fields[0].GetUInt32());
2808 continue;
2812 InstanceSave *save = sInstanceSaveManager.AddInstanceSave(fields[1].GetUInt32(), fields[2].GetUInt32(), fields[4].GetUInt8(), (time_t)fields[5].GetUInt64(), (fields[6].GetUInt32() == 0), true);
2813 group->BindToInstance(save, fields[3].GetBool(), true);
2814 }while( result->NextRow() );
2815 delete result;
2818 sLog.outString();
2819 sLog.outString( ">> Loaded %u group-instance binds total", count );
2821 sLog.outString();
2822 sLog.outString( ">> Loaded %u group members total", count );
2825 void ObjectMgr::LoadQuests()
2827 // For reload case
2828 for(QuestMap::const_iterator itr=mQuestTemplates.begin(); itr != mQuestTemplates.end(); ++itr)
2829 delete itr->second;
2830 mQuestTemplates.clear();
2832 mExclusiveQuestGroups.clear();
2834 // 0 1 2 3 4 5 6 7 8
2835 QueryResult *result = WorldDatabase.Query("SELECT entry, Method, ZoneOrSort, SkillOrClass, MinLevel, QuestLevel, Type, RequiredRaces, RequiredSkillValue,"
2836 // 9 10 11 12 13 14 15 16
2837 "RepObjectiveFaction, RepObjectiveValue, RequiredMinRepFaction, RequiredMinRepValue, RequiredMaxRepFaction, RequiredMaxRepValue, SuggestedPlayers, LimitTime,"
2838 // 17 18 19 20 21 22 23 24 25 26 27 28
2839 "QuestFlags, SpecialFlags, CharTitleId, PlayersSlain, BonusTalents, PrevQuestId, NextQuestId, ExclusiveGroup, NextQuestInChain, SrcItemId, SrcItemCount, SrcSpell,"
2840 // 29 30 31 32 33 34 35 36 37 38
2841 "Title, Details, Objectives, OfferRewardText, RequestItemsText, EndText, ObjectiveText1, ObjectiveText2, ObjectiveText3, ObjectiveText4,"
2842 // 39 40 41 42 43 44 45 46
2843 "ReqItemId1, ReqItemId2, ReqItemId3, ReqItemId4, ReqItemCount1, ReqItemCount2, ReqItemCount3, ReqItemCount4,"
2844 // 47 48 49 50 51 52 53 54 55 56 57 58
2845 "ReqSourceId1, ReqSourceId2, ReqSourceId3, ReqSourceId4, ReqSourceCount1, ReqSourceCount2, ReqSourceCount3, ReqSourceCount4, ReqSourceRef1, ReqSourceRef2, ReqSourceRef3, ReqSourceRef4,"
2846 // 59 60 61 62 63 64 65 66
2847 "ReqCreatureOrGOId1, ReqCreatureOrGOId2, ReqCreatureOrGOId3, ReqCreatureOrGOId4, ReqCreatureOrGOCount1, ReqCreatureOrGOCount2, ReqCreatureOrGOCount3, ReqCreatureOrGOCount4,"
2848 // 67 68 69 70
2849 "ReqSpellCast1, ReqSpellCast2, ReqSpellCast3, ReqSpellCast4,"
2850 // 71 72 73 74 75 76
2851 "RewChoiceItemId1, RewChoiceItemId2, RewChoiceItemId3, RewChoiceItemId4, RewChoiceItemId5, RewChoiceItemId6,"
2852 // 77 78 79 80 81 82
2853 "RewChoiceItemCount1, RewChoiceItemCount2, RewChoiceItemCount3, RewChoiceItemCount4, RewChoiceItemCount5, RewChoiceItemCount6,"
2854 // 83 84 85 86 87 88 89 90
2855 "RewItemId1, RewItemId2, RewItemId3, RewItemId4, RewItemCount1, RewItemCount2, RewItemCount3, RewItemCount4,"
2856 // 91 92 93 94 95 96 97 98 99 100
2857 "RewRepFaction1, RewRepFaction2, RewRepFaction3, RewRepFaction4, RewRepFaction5, RewRepValue1, RewRepValue2, RewRepValue3, RewRepValue4, RewRepValue5,"
2858 // 101 102 103 104 105 106 107 108 109 110 111
2859 "RewHonorableKills, RewOrReqMoney, RewMoneyMaxLevel, RewSpell, RewSpellCast, RewMailTemplateId, RewMailDelaySecs, PointMapId, PointX, PointY, PointOpt,"
2860 // 112 113 114 115 116 117 118 119 120 121
2861 "DetailsEmote1, DetailsEmote2, DetailsEmote3, DetailsEmote4,IncompleteEmote, CompleteEmote, OfferRewardEmote1, OfferRewardEmote2, OfferRewardEmote3, OfferRewardEmote4,"
2862 // 122 123
2863 "StartScript, CompleteScript"
2864 " FROM quest_template");
2865 if(result == NULL)
2867 barGoLink bar( 1 );
2868 bar.step();
2870 sLog.outString();
2871 sLog.outString( ">> Loaded 0 quests definitions" );
2872 sLog.outErrorDb("`quest_template` table is empty!");
2873 return;
2876 // create multimap previous quest for each existed quest
2877 // some quests can have many previous maps set by NextQuestId in previous quest
2878 // for example set of race quests can lead to single not race specific quest
2879 barGoLink bar( result->GetRowCount() );
2882 bar.step();
2883 Field *fields = result->Fetch();
2885 Quest * newQuest = new Quest(fields);
2886 mQuestTemplates[newQuest->GetQuestId()] = newQuest;
2887 } while( result->NextRow() );
2889 delete result;
2891 // Post processing
2892 for (QuestMap::iterator iter = mQuestTemplates.begin(); iter != mQuestTemplates.end(); iter++)
2894 Quest * qinfo = iter->second;
2896 // additional quest integrity checks (GO, creature_template and item_template must be loaded already)
2898 if( qinfo->GetQuestMethod() >= 3 )
2900 sLog.outErrorDb("Quest %u has `Method` = %u, expected values are 0, 1 or 2.",qinfo->GetQuestId(),qinfo->GetQuestMethod());
2903 if (qinfo->QuestFlags & ~QUEST_MANGOS_FLAGS_DB_ALLOWED)
2905 sLog.outErrorDb("Quest %u has `SpecialFlags` = %u > max allowed value. Correct `SpecialFlags` to value <= %u",
2906 qinfo->GetQuestId(),qinfo->QuestFlags,QUEST_MANGOS_FLAGS_DB_ALLOWED >> 16);
2907 qinfo->QuestFlags &= QUEST_MANGOS_FLAGS_DB_ALLOWED;
2910 if(qinfo->QuestFlags & QUEST_FLAGS_DAILY)
2912 if(!(qinfo->QuestFlags & QUEST_MANGOS_FLAGS_REPEATABLE))
2914 sLog.outErrorDb("Daily Quest %u not marked as repeatable in `SpecialFlags`, added.",qinfo->GetQuestId());
2915 qinfo->QuestFlags |= QUEST_MANGOS_FLAGS_REPEATABLE;
2919 if(qinfo->QuestFlags & QUEST_FLAGS_AUTO_REWARDED)
2921 // at auto-reward can be rewarded only RewChoiceItemId[0]
2922 for(int j = 1; j < QUEST_REWARD_CHOICES_COUNT; ++j )
2924 if(uint32 id = qinfo->RewChoiceItemId[j])
2926 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item from `RewChoiceItemId%d` can't be rewarded with quest flag QUEST_FLAGS_AUTO_REWARDED.",
2927 qinfo->GetQuestId(),j+1,id,j+1);
2928 // no changes, quest ignore this data
2933 // client quest log visual (area case)
2934 if( qinfo->ZoneOrSort > 0 )
2936 if(!GetAreaEntryByAreaID(qinfo->ZoneOrSort))
2938 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %u (zone case) but zone with this id does not exist.",
2939 qinfo->GetQuestId(),qinfo->ZoneOrSort);
2940 // no changes, quest not dependent from this value but can have problems at client
2943 // client quest log visual (sort case)
2944 if( qinfo->ZoneOrSort < 0 )
2946 QuestSortEntry const* qSort = sQuestSortStore.LookupEntry(-int32(qinfo->ZoneOrSort));
2947 if( !qSort )
2949 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (sort case) but quest sort with this id does not exist.",
2950 qinfo->GetQuestId(),qinfo->ZoneOrSort);
2951 // 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)
2953 //check SkillOrClass value (class case).
2954 if( ClassByQuestSort(-int32(qinfo->ZoneOrSort)) )
2956 // SkillOrClass should not have class case when class case already set in ZoneOrSort.
2957 if(qinfo->SkillOrClass < 0)
2959 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (class sort case) and `SkillOrClass` = %i (class case), redundant.",
2960 qinfo->GetQuestId(),qinfo->ZoneOrSort,qinfo->SkillOrClass);
2963 //check for proper SkillOrClass value (skill case)
2964 if(int32 skill_id = SkillByQuestSort(-int32(qinfo->ZoneOrSort)))
2966 // skill is positive value in SkillOrClass
2967 if(qinfo->SkillOrClass != skill_id )
2969 sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (skill sort case) but `SkillOrClass` does not have a corresponding value (%i).",
2970 qinfo->GetQuestId(),qinfo->ZoneOrSort,skill_id);
2971 //override, and force proper value here?
2976 // SkillOrClass (class case)
2977 if( qinfo->SkillOrClass < 0 )
2979 if( !sChrClassesStore.LookupEntry(-int32(qinfo->SkillOrClass)) )
2981 sLog.outErrorDb("Quest %u has `SkillOrClass` = %i (class case) but class (%i) does not exist",
2982 qinfo->GetQuestId(),qinfo->SkillOrClass,-qinfo->SkillOrClass);
2985 // SkillOrClass (skill case)
2986 if( qinfo->SkillOrClass > 0 )
2988 if( !sSkillLineStore.LookupEntry(qinfo->SkillOrClass) )
2990 sLog.outErrorDb("Quest %u has `SkillOrClass` = %u (skill case) but skill (%i) does not exist",
2991 qinfo->GetQuestId(),qinfo->SkillOrClass,qinfo->SkillOrClass);
2995 if( qinfo->RequiredSkillValue )
2997 if( qinfo->RequiredSkillValue > sWorld.GetConfigMaxSkillValue() )
2999 sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but max possible skill is %u, quest can't be done.",
3000 qinfo->GetQuestId(),qinfo->RequiredSkillValue,sWorld.GetConfigMaxSkillValue());
3001 // no changes, quest can't be done for this requirement
3004 if( qinfo->SkillOrClass <= 0 )
3006 sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but `SkillOrClass` = %i (class case), value ignored.",
3007 qinfo->GetQuestId(),qinfo->RequiredSkillValue,qinfo->SkillOrClass);
3008 // no changes, quest can't be done for this requirement (fail at wrong skill id)
3011 // else Skill quests can have 0 skill level, this is ok
3013 if(qinfo->RepObjectiveFaction && !sFactionStore.LookupEntry(qinfo->RepObjectiveFaction))
3015 sLog.outErrorDb("Quest %u has `RepObjectiveFaction` = %u but faction template %u does not exist, quest can't be done.",
3016 qinfo->GetQuestId(),qinfo->RepObjectiveFaction,qinfo->RepObjectiveFaction);
3017 // no changes, quest can't be done for this requirement
3020 if(qinfo->RequiredMinRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMinRepFaction))
3022 sLog.outErrorDb("Quest %u has `RequiredMinRepFaction` = %u but faction template %u does not exist, quest can't be done.",
3023 qinfo->GetQuestId(),qinfo->RequiredMinRepFaction,qinfo->RequiredMinRepFaction);
3024 // no changes, quest can't be done for this requirement
3027 if(qinfo->RequiredMaxRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMaxRepFaction))
3029 sLog.outErrorDb("Quest %u has `RequiredMaxRepFaction` = %u but faction template %u does not exist, quest can't be done.",
3030 qinfo->GetQuestId(),qinfo->RequiredMaxRepFaction,qinfo->RequiredMaxRepFaction);
3031 // no changes, quest can't be done for this requirement
3034 if(qinfo->RequiredMinRepValue && qinfo->RequiredMinRepValue > Player::Reputation_Cap)
3036 sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but max reputation is %u, quest can't be done.",
3037 qinfo->GetQuestId(),qinfo->RequiredMinRepValue,Player::Reputation_Cap);
3038 // no changes, quest can't be done for this requirement
3041 if(qinfo->RequiredMinRepValue && qinfo->RequiredMaxRepValue && qinfo->RequiredMaxRepValue <= qinfo->RequiredMinRepValue)
3043 sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d and `RequiredMinRepValue` = %d, quest can't be done.",
3044 qinfo->GetQuestId(),qinfo->RequiredMaxRepValue,qinfo->RequiredMinRepValue);
3045 // no changes, quest can't be done for this requirement
3048 if(!qinfo->RepObjectiveFaction && qinfo->RepObjectiveValue > 0 )
3050 sLog.outErrorDb("Quest %u has `RepObjectiveValue` = %d but `RepObjectiveFaction` is 0, value has no effect",
3051 qinfo->GetQuestId(),qinfo->RepObjectiveValue);
3052 // warning
3055 if(!qinfo->RequiredMinRepFaction && qinfo->RequiredMinRepValue > 0 )
3057 sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but `RequiredMinRepFaction` is 0, value has no effect",
3058 qinfo->GetQuestId(),qinfo->RequiredMinRepValue);
3059 // warning
3062 if(!qinfo->RequiredMaxRepFaction && qinfo->RequiredMaxRepValue > 0 )
3064 sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d but `RequiredMaxRepFaction` is 0, value has no effect",
3065 qinfo->GetQuestId(),qinfo->RequiredMaxRepValue);
3066 // warning
3069 if(qinfo->CharTitleId && !sCharTitlesStore.LookupEntry(qinfo->CharTitleId))
3071 sLog.outErrorDb("Quest %u has `CharTitleId` = %u but CharTitle Id %u does not exist, quest can't be rewarded with title.",
3072 qinfo->GetQuestId(),qinfo->GetCharTitleId(),qinfo->GetCharTitleId());
3073 qinfo->CharTitleId = 0;
3074 // quest can't reward this title
3077 if(qinfo->SrcItemId)
3079 if(!sItemStorage.LookupEntry<ItemPrototype>(qinfo->SrcItemId))
3081 sLog.outErrorDb("Quest %u has `SrcItemId` = %u but item with entry %u does not exist, quest can't be done.",
3082 qinfo->GetQuestId(),qinfo->SrcItemId,qinfo->SrcItemId);
3083 qinfo->SrcItemId = 0; // quest can't be done for this requirement
3085 else if(qinfo->SrcItemCount==0)
3087 sLog.outErrorDb("Quest %u has `SrcItemId` = %u but `SrcItemCount` = 0, set to 1 but need fix in DB.",
3088 qinfo->GetQuestId(),qinfo->SrcItemId);
3089 qinfo->SrcItemCount = 1; // update to 1 for allow quest work for backward compatibility with DB
3092 else if(qinfo->SrcItemCount>0)
3094 sLog.outErrorDb("Quest %u has `SrcItemId` = 0 but `SrcItemCount` = %u, useless value.",
3095 qinfo->GetQuestId(),qinfo->SrcItemCount);
3096 qinfo->SrcItemCount=0; // no quest work changes in fact
3099 if(qinfo->SrcSpell)
3101 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->SrcSpell);
3102 if(!spellInfo)
3104 sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u doesn't exist, quest can't be done.",
3105 qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
3106 qinfo->SrcSpell = 0; // quest can't be done for this requirement
3108 else if(!SpellMgr::IsSpellValid(spellInfo))
3110 sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u is broken, quest can't be done.",
3111 qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
3112 qinfo->SrcSpell = 0; // quest can't be done for this requirement
3116 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3118 uint32 id = qinfo->ReqItemId[j];
3119 if(id)
3121 if(qinfo->ReqItemCount[j]==0)
3123 sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but `ReqItemCount%d` = 0, quest can't be done.",
3124 qinfo->GetQuestId(),j+1,id,j+1);
3125 // no changes, quest can't be done for this requirement
3128 qinfo->SetFlag(QUEST_MANGOS_FLAGS_DELIVER);
3130 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3132 sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but item with entry %u does not exist, quest can't be done.",
3133 qinfo->GetQuestId(),j+1,id,id);
3134 qinfo->ReqItemCount[j] = 0; // prevent incorrect work of quest
3137 else if(qinfo->ReqItemCount[j]>0)
3139 sLog.outErrorDb("Quest %u has `ReqItemId%d` = 0 but `ReqItemCount%d` = %u, quest can't be done.",
3140 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqItemCount[j]);
3141 qinfo->ReqItemCount[j] = 0; // prevent incorrect work of quest
3145 for(int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j )
3147 uint32 id = qinfo->ReqSourceId[j];
3148 if(id)
3150 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3152 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but item with entry %u does not exist, quest can't be done.",
3153 qinfo->GetQuestId(),j+1,id,id);
3154 // no changes, quest can't be done for this requirement
3157 if(!qinfo->ReqSourceCount[j])
3159 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but `ReqSourceCount%d` = 0, quest can't be done.",
3160 qinfo->GetQuestId(),j+1,id,j+1);
3161 qinfo->ReqSourceId[j] = 0; // prevent incorrect work of quest
3164 if(!qinfo->ReqSourceRef[j])
3166 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but `ReqSourceRef%d` = 0, quest can't be done.",
3167 qinfo->GetQuestId(),j+1,id,j+1);
3168 qinfo->ReqSourceId[j] = 0; // prevent incorrect work of quest
3171 else
3173 if(qinfo->ReqSourceCount[j]>0)
3175 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = 0 but `ReqSourceCount%d` = %u.",
3176 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqSourceCount[j]);
3177 // no changes, quest ignore this data
3180 if(qinfo->ReqSourceRef[j]>0)
3182 sLog.outErrorDb("Quest %u has `ReqSourceId%d` = 0 but `ReqSourceRef%d` = %u.",
3183 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqSourceRef[j]);
3184 // no changes, quest ignore this data
3189 for(int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j )
3191 uint32 ref = qinfo->ReqSourceRef[j];
3192 if(ref)
3194 if(ref > QUEST_OBJECTIVES_COUNT)
3196 sLog.outErrorDb("Quest %u has `ReqSourceRef%d` = %u but max value in `ReqSourceRef%d` is %u, quest can't be done.",
3197 qinfo->GetQuestId(),j+1,ref,j+1,QUEST_OBJECTIVES_COUNT);
3198 // no changes, quest can't be done for this requirement
3200 else
3201 if(!qinfo->ReqItemId[ref-1] && !qinfo->ReqSpell[ref-1])
3203 sLog.outErrorDb("Quest %u has `ReqSourceRef%d` = %u but `ReqItemId%u` = 0 and `ReqSpellCast%u` = 0, quest can't be done.",
3204 qinfo->GetQuestId(),j+1,ref,ref,ref);
3205 // no changes, quest can't be done for this requirement
3207 else if(qinfo->ReqItemId[ref-1] && qinfo->ReqSpell[ref-1])
3209 sLog.outErrorDb("Quest %u has `ReqItemId%u` = %u and `ReqSpellCast%u` = %u, quest can't have both fields <> 0, then can't be done.",
3210 qinfo->GetQuestId(),ref,qinfo->ReqItemId[ref-1],ref,qinfo->ReqSpell[ref-1]);
3211 // no changes, quest can't be done for this requirement
3212 qinfo->ReqSourceId[j] = 0; // prevent incorrect work of quest
3217 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3219 uint32 id = qinfo->ReqSpell[j];
3220 if(id)
3222 SpellEntry const* spellInfo = sSpellStore.LookupEntry(id);
3223 if(!spellInfo)
3225 sLog.outErrorDb("Quest %u has `ReqSpellCast%d` = %u but spell %u does not exist, quest can't be done.",
3226 qinfo->GetQuestId(),j+1,id,id);
3227 // no changes, quest can't be done for this requirement
3230 if(!qinfo->ReqCreatureOrGOId[j])
3232 bool found = false;
3233 for(int k = 0; k < 3; ++k)
3235 if( spellInfo->Effect[k]==SPELL_EFFECT_QUEST_COMPLETE && uint32(spellInfo->EffectMiscValue[k])==qinfo->QuestId ||
3236 spellInfo->Effect[k]==SPELL_EFFECT_SEND_EVENT)
3238 found = true;
3239 break;
3243 if(found)
3245 if(!qinfo->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3247 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);
3249 // this will prevent quest completing without objective
3250 const_cast<Quest*>(qinfo)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3253 else
3255 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.",
3256 qinfo->GetQuestId(),j+1,id,j+1,id);
3257 // no changes, quest can't be done for this requirement
3263 for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3265 int32 id = qinfo->ReqCreatureOrGOId[j];
3266 if(id < 0 && !sGOStorage.LookupEntry<GameObjectInfo>(-id))
3268 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but gameobject %u does not exist, quest can't be done.",
3269 qinfo->GetQuestId(),j+1,id,uint32(-id));
3270 qinfo->ReqCreatureOrGOId[j] = 0; // quest can't be done for this requirement
3273 if(id > 0 && !sCreatureStorage.LookupEntry<CreatureInfo>(id))
3275 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but creature with entry %u does not exist, quest can't be done.",
3276 qinfo->GetQuestId(),j+1,id,uint32(id));
3277 qinfo->ReqCreatureOrGOId[j] = 0; // quest can't be done for this requirement
3280 if(id)
3282 // In fact SpeakTo and Kill are quite same: either you can speak to mob:SpeakTo or you can't:Kill/Cast
3284 qinfo->SetFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO);
3286 if(!qinfo->ReqCreatureOrGOCount[j])
3288 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %u but `ReqCreatureOrGOCount%d` = 0, quest can't be done.",
3289 qinfo->GetQuestId(),j+1,id,j+1);
3290 // no changes, quest can be incorrectly done, but we already report this
3293 else if(qinfo->ReqCreatureOrGOCount[j]>0)
3295 sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = 0 but `ReqCreatureOrGOCount%d` = %u.",
3296 qinfo->GetQuestId(),j+1,j+1,qinfo->ReqCreatureOrGOCount[j]);
3297 // no changes, quest ignore this data
3301 for(int j = 0; j < QUEST_REWARD_CHOICES_COUNT; ++j )
3303 uint32 id = qinfo->RewChoiceItemId[j];
3304 if(id)
3306 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3308 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3309 qinfo->GetQuestId(),j+1,id,id);
3310 qinfo->RewChoiceItemId[j] = 0; // no changes, quest will not reward this
3313 if(!qinfo->RewChoiceItemCount[j])
3315 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but `RewChoiceItemCount%d` = 0, quest can't be done.",
3316 qinfo->GetQuestId(),j+1,id,j+1);
3317 // no changes, quest can't be done
3320 else if(qinfo->RewChoiceItemCount[j]>0)
3322 sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = 0 but `RewChoiceItemCount%d` = %u.",
3323 qinfo->GetQuestId(),j+1,j+1,qinfo->RewChoiceItemCount[j]);
3324 // no changes, quest ignore this data
3328 for(int j = 0; j < QUEST_REWARDS_COUNT; ++j )
3330 uint32 id = qinfo->RewItemId[j];
3331 if(id)
3333 if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3335 sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3336 qinfo->GetQuestId(),j+1,id,id);
3337 qinfo->RewItemId[j] = 0; // no changes, quest will not reward this item
3340 if(!qinfo->RewItemCount[j])
3342 sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but `RewItemCount%d` = 0, quest will not reward this item.",
3343 qinfo->GetQuestId(),j+1,id,j+1);
3344 // no changes
3347 else if(qinfo->RewItemCount[j]>0)
3349 sLog.outErrorDb("Quest %u has `RewItemId%d` = 0 but `RewItemCount%d` = %u.",
3350 qinfo->GetQuestId(),j+1,j+1,qinfo->RewItemCount[j]);
3351 // no changes, quest ignore this data
3355 for(int j = 0; j < QUEST_REPUTATIONS_COUNT; ++j)
3357 if(qinfo->RewRepFaction[j])
3359 if(!qinfo->RewRepValue[j])
3361 sLog.outErrorDb("Quest %u has `RewRepFaction%d` = %u but `RewRepValue%d` = 0, quest will not reward this reputation.",
3362 qinfo->GetQuestId(),j+1,qinfo->RewRepValue[j],j+1);
3363 // no changes
3366 if(!sFactionStore.LookupEntry(qinfo->RewRepFaction[j]))
3368 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.",
3369 qinfo->GetQuestId(),j+1,qinfo->RewRepFaction[j] ,qinfo->RewRepFaction[j] );
3370 qinfo->RewRepFaction[j] = 0; // quest will not reward this
3373 else if(qinfo->RewRepValue[j]!=0)
3375 sLog.outErrorDb("Quest %u has `RewRepFaction%d` = 0 but `RewRepValue%d` = %u.",
3376 qinfo->GetQuestId(),j+1,j+1,qinfo->RewRepValue[j]);
3377 // no changes, quest ignore this data
3381 if(qinfo->RewSpell)
3383 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpell);
3385 if(!spellInfo)
3387 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u does not exist, spell removed as display reward.",
3388 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3389 qinfo->RewSpell = 0; // no spell reward will display for this quest
3392 else if(!SpellMgr::IsSpellValid(spellInfo))
3394 sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u is broken, quest can't be done.",
3395 qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3396 qinfo->RewSpell = 0; // no spell reward will display for this quest
3401 if(qinfo->RewSpellCast)
3403 SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpellCast);
3405 if(!spellInfo)
3407 sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u does not exist, quest will not have a spell reward.",
3408 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3409 qinfo->RewSpellCast = 0; // no spell will be casted on player
3412 else if(!SpellMgr::IsSpellValid(spellInfo))
3414 sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u is broken, quest can't be done.",
3415 qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3416 qinfo->RewSpellCast = 0; // no spell will be casted on player
3421 if(qinfo->RewMailTemplateId)
3423 if(!sMailTemplateStore.LookupEntry(qinfo->RewMailTemplateId))
3425 sLog.outErrorDb("Quest %u has `RewMailTemplateId` = %u but mail template %u does not exist, quest will not have a mail reward.",
3426 qinfo->GetQuestId(),qinfo->RewMailTemplateId,qinfo->RewMailTemplateId);
3427 qinfo->RewMailTemplateId = 0; // no mail will send to player
3428 qinfo->RewMailDelaySecs = 0; // no mail will send to player
3432 if(qinfo->NextQuestInChain)
3434 if(mQuestTemplates.find(qinfo->NextQuestInChain) == mQuestTemplates.end())
3436 sLog.outErrorDb("Quest %u has `NextQuestInChain` = %u but quest %u does not exist, quest chain will not work.",
3437 qinfo->GetQuestId(),qinfo->NextQuestInChain ,qinfo->NextQuestInChain );
3438 qinfo->NextQuestInChain = 0;
3440 else
3441 mQuestTemplates[qinfo->NextQuestInChain]->prevChainQuests.push_back(qinfo->GetQuestId());
3444 // fill additional data stores
3445 if(qinfo->PrevQuestId)
3447 if (mQuestTemplates.find(abs(qinfo->GetPrevQuestId())) == mQuestTemplates.end())
3449 sLog.outErrorDb("Quest %d has PrevQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetPrevQuestId());
3451 else
3453 qinfo->prevQuests.push_back(qinfo->PrevQuestId);
3457 if(qinfo->NextQuestId)
3459 if (mQuestTemplates.find(abs(qinfo->GetNextQuestId())) == mQuestTemplates.end())
3461 sLog.outErrorDb("Quest %d has NextQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetNextQuestId());
3463 else
3465 int32 signedQuestId = qinfo->NextQuestId < 0 ? -int32(qinfo->GetQuestId()) : int32(qinfo->GetQuestId());
3466 mQuestTemplates[abs(qinfo->GetNextQuestId())]->prevQuests.push_back(signedQuestId);
3470 if(qinfo->ExclusiveGroup)
3471 mExclusiveQuestGroups.insert(std::pair<int32, uint32>(qinfo->ExclusiveGroup, qinfo->GetQuestId()));
3472 if(qinfo->LimitTime)
3473 qinfo->SetFlag(QUEST_MANGOS_FLAGS_TIMED);
3476 // check QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT for spell with SPELL_EFFECT_QUEST_COMPLETE
3477 for (uint32 i = 0; i < sSpellStore.GetNumRows(); ++i)
3479 SpellEntry const *spellInfo = sSpellStore.LookupEntry(i);
3480 if(!spellInfo)
3481 continue;
3483 for(int j = 0; j < 3; ++j)
3485 if(spellInfo->Effect[j] != SPELL_EFFECT_QUEST_COMPLETE)
3486 continue;
3488 uint32 quest_id = spellInfo->EffectMiscValue[j];
3490 Quest const* quest = GetQuestTemplate(quest_id);
3492 // some quest referenced in spells not exist (outdated spells)
3493 if(!quest)
3494 continue;
3496 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3498 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);
3500 // this will prevent quest completing without objective
3501 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3506 sLog.outString();
3507 sLog.outString( ">> Loaded %u quests definitions", mQuestTemplates.size() );
3510 void ObjectMgr::LoadQuestLocales()
3512 mQuestLocaleMap.clear(); // need for reload case
3514 QueryResult *result = WorldDatabase.Query("SELECT entry,"
3515 "Title_loc1,Details_loc1,Objectives_loc1,OfferRewardText_loc1,RequestItemsText_loc1,EndText_loc1,ObjectiveText1_loc1,ObjectiveText2_loc1,ObjectiveText3_loc1,ObjectiveText4_loc1,"
3516 "Title_loc2,Details_loc2,Objectives_loc2,OfferRewardText_loc2,RequestItemsText_loc2,EndText_loc2,ObjectiveText1_loc2,ObjectiveText2_loc2,ObjectiveText3_loc2,ObjectiveText4_loc2,"
3517 "Title_loc3,Details_loc3,Objectives_loc3,OfferRewardText_loc3,RequestItemsText_loc3,EndText_loc3,ObjectiveText1_loc3,ObjectiveText2_loc3,ObjectiveText3_loc3,ObjectiveText4_loc3,"
3518 "Title_loc4,Details_loc4,Objectives_loc4,OfferRewardText_loc4,RequestItemsText_loc4,EndText_loc4,ObjectiveText1_loc4,ObjectiveText2_loc4,ObjectiveText3_loc4,ObjectiveText4_loc4,"
3519 "Title_loc5,Details_loc5,Objectives_loc5,OfferRewardText_loc5,RequestItemsText_loc5,EndText_loc5,ObjectiveText1_loc5,ObjectiveText2_loc5,ObjectiveText3_loc5,ObjectiveText4_loc5,"
3520 "Title_loc6,Details_loc6,Objectives_loc6,OfferRewardText_loc6,RequestItemsText_loc6,EndText_loc6,ObjectiveText1_loc6,ObjectiveText2_loc6,ObjectiveText3_loc6,ObjectiveText4_loc6,"
3521 "Title_loc7,Details_loc7,Objectives_loc7,OfferRewardText_loc7,RequestItemsText_loc7,EndText_loc7,ObjectiveText1_loc7,ObjectiveText2_loc7,ObjectiveText3_loc7,ObjectiveText4_loc7,"
3522 "Title_loc8,Details_loc8,Objectives_loc8,OfferRewardText_loc8,RequestItemsText_loc8,EndText_loc8,ObjectiveText1_loc8,ObjectiveText2_loc8,ObjectiveText3_loc8,ObjectiveText4_loc8"
3523 " FROM locales_quest"
3526 if(!result)
3528 barGoLink bar(1);
3530 bar.step();
3532 sLog.outString("");
3533 sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_quest` is empty.");
3534 return;
3537 barGoLink bar(result->GetRowCount());
3541 Field *fields = result->Fetch();
3542 bar.step();
3544 uint32 entry = fields[0].GetUInt32();
3546 QuestLocale& data = mQuestLocaleMap[entry];
3548 for(int i = 1; i < MAX_LOCALE; ++i)
3550 std::string str = fields[1+10*(i-1)].GetCppString();
3551 if(!str.empty())
3553 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3554 if(idx >= 0)
3556 if(data.Title.size() <= idx)
3557 data.Title.resize(idx+1);
3559 data.Title[idx] = str;
3562 str = fields[1+10*(i-1)+1].GetCppString();
3563 if(!str.empty())
3565 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3566 if(idx >= 0)
3568 if(data.Details.size() <= idx)
3569 data.Details.resize(idx+1);
3571 data.Details[idx] = str;
3574 str = fields[1+10*(i-1)+2].GetCppString();
3575 if(!str.empty())
3577 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3578 if(idx >= 0)
3580 if(data.Objectives.size() <= idx)
3581 data.Objectives.resize(idx+1);
3583 data.Objectives[idx] = str;
3586 str = fields[1+10*(i-1)+3].GetCppString();
3587 if(!str.empty())
3589 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3590 if(idx >= 0)
3592 if(data.OfferRewardText.size() <= idx)
3593 data.OfferRewardText.resize(idx+1);
3595 data.OfferRewardText[idx] = str;
3598 str = fields[1+10*(i-1)+4].GetCppString();
3599 if(!str.empty())
3601 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3602 if(idx >= 0)
3604 if(data.RequestItemsText.size() <= idx)
3605 data.RequestItemsText.resize(idx+1);
3607 data.RequestItemsText[idx] = str;
3610 str = fields[1+10*(i-1)+5].GetCppString();
3611 if(!str.empty())
3613 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3614 if(idx >= 0)
3616 if(data.EndText.size() <= idx)
3617 data.EndText.resize(idx+1);
3619 data.EndText[idx] = str;
3622 for(int k = 0; k < 4; ++k)
3624 str = fields[1+10*(i-1)+6+k].GetCppString();
3625 if(!str.empty())
3627 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3628 if(idx >= 0)
3630 if(data.ObjectiveText[k].size() <= idx)
3631 data.ObjectiveText[k].resize(idx+1);
3633 data.ObjectiveText[k][idx] = str;
3638 } while (result->NextRow());
3640 delete result;
3642 sLog.outString();
3643 sLog.outString( ">> Loaded %u Quest locale strings", mQuestLocaleMap.size() );
3646 void ObjectMgr::LoadPetCreateSpells()
3648 QueryResult *result = WorldDatabase.Query("SELECT entry, Spell1, Spell2, Spell3, Spell4 FROM petcreateinfo_spell");
3649 if(!result)
3651 barGoLink bar( 1 );
3652 bar.step();
3654 sLog.outString();
3655 sLog.outString( ">> Loaded 0 pet create spells" );
3656 sLog.outErrorDb("`petcreateinfo_spell` table is empty!");
3657 return;
3660 uint32 count = 0;
3662 barGoLink bar( result->GetRowCount() );
3664 mPetCreateSpell.clear();
3668 Field *fields = result->Fetch();
3669 bar.step();
3671 uint32 creature_id = fields[0].GetUInt32();
3673 if(!creature_id || !sCreatureStorage.LookupEntry<CreatureInfo>(creature_id))
3674 continue;
3676 PetCreateSpellEntry PetCreateSpell;
3677 for(int i = 0; i < 4; i++)
3679 PetCreateSpell.spellid[i] = fields[i + 1].GetUInt32();
3681 if(PetCreateSpell.spellid[i] && !sSpellStore.LookupEntry(PetCreateSpell.spellid[i]))
3682 sLog.outErrorDb("Spell %u listed in `petcreateinfo_spell` does not exist",PetCreateSpell.spellid[i]);
3685 mPetCreateSpell[creature_id] = PetCreateSpell;
3687 ++count;
3689 while (result->NextRow());
3691 delete result;
3693 sLog.outString();
3694 sLog.outString( ">> Loaded %u pet create spells", count );
3697 void ObjectMgr::LoadScripts(ScriptMapMap& scripts, char const* tablename)
3699 if(sWorld.IsScriptScheduled()) // function don't must be called in time scripts use.
3700 return;
3702 sLog.outString( "%s :", tablename);
3704 scripts.clear(); // need for reload support
3706 QueryResult *result = WorldDatabase.PQuery( "SELECT id,delay,command,datalong,datalong2,datatext, x, y, z, o FROM %s", tablename );
3708 uint32 count = 0;
3710 if( !result )
3712 barGoLink bar( 1 );
3713 bar.step();
3715 sLog.outString();
3716 sLog.outString( ">> Loaded %u script definitions", count );
3717 return;
3720 barGoLink bar( result->GetRowCount() );
3724 bar.step();
3726 Field *fields = result->Fetch();
3727 ScriptInfo tmp;
3728 tmp.id = fields[0].GetUInt32();
3729 tmp.delay = fields[1].GetUInt32();
3730 tmp.command = fields[2].GetUInt32();
3731 tmp.datalong = fields[3].GetUInt32();
3732 tmp.datalong2 = fields[4].GetUInt32();
3733 tmp.datatext = fields[5].GetCppString();
3734 tmp.x = fields[6].GetFloat();
3735 tmp.y = fields[7].GetFloat();
3736 tmp.z = fields[8].GetFloat();
3737 tmp.o = fields[9].GetFloat();
3739 // generic command args check
3740 switch(tmp.command)
3742 case SCRIPT_COMMAND_TALK:
3744 if(tmp.datalong > 3)
3746 sLog.outErrorDb("Table `%s` has invalid talk type (datalong = %u) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.datalong,tmp.id);
3747 continue;
3749 break;
3752 case SCRIPT_COMMAND_TELEPORT_TO:
3754 if(!sMapStore.LookupEntry(tmp.datalong))
3756 sLog.outErrorDb("Table `%s` has invalid map (Id: %u) in SCRIPT_COMMAND_TELEPORT_TO for script id %u",tablename,tmp.datalong,tmp.id);
3757 continue;
3760 if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
3762 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);
3763 continue;
3765 break;
3768 case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
3770 if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
3772 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);
3773 continue;
3776 if(!GetCreatureTemplate(tmp.datalong))
3778 sLog.outErrorDb("Table `%s` has invalid creature (Entry: %u) in SCRIPT_COMMAND_TEMP_SUMMON_CREATURE for script id %u",tablename,tmp.datalong,tmp.id);
3779 continue;
3781 break;
3784 case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
3786 GameObjectData const* data = GetGOData(tmp.datalong);
3787 if(!data)
3789 sLog.outErrorDb("Table `%s` has invalid gameobject (GUID: %u) in SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,tmp.datalong,tmp.id);
3790 continue;
3793 GameObjectInfo const* info = GetGameObjectInfo(data->id);
3794 if(!info)
3796 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);
3797 continue;
3800 if( info->type==GAMEOBJECT_TYPE_FISHINGNODE ||
3801 info->type==GAMEOBJECT_TYPE_FISHINGHOLE ||
3802 info->type==GAMEOBJECT_TYPE_DOOR ||
3803 info->type==GAMEOBJECT_TYPE_BUTTON ||
3804 info->type==GAMEOBJECT_TYPE_TRAP )
3806 sLog.outErrorDb("Table `%s` have gameobject type (%u) unsupported by command SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,info->id,tmp.id);
3807 continue;
3809 break;
3811 case SCRIPT_COMMAND_OPEN_DOOR:
3812 case SCRIPT_COMMAND_CLOSE_DOOR:
3814 GameObjectData const* data = GetGOData(tmp.datalong);
3815 if(!data)
3817 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);
3818 continue;
3821 GameObjectInfo const* info = GetGameObjectInfo(data->id);
3822 if(!info)
3824 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);
3825 continue;
3828 if( info->type!=GAMEOBJECT_TYPE_DOOR)
3830 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);
3831 continue;
3834 break;
3836 case SCRIPT_COMMAND_QUEST_EXPLORED:
3838 Quest const* quest = GetQuestTemplate(tmp.datalong);
3839 if(!quest)
3841 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);
3842 continue;
3845 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3847 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);
3849 // this will prevent quest completing without objective
3850 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3852 // continue; - quest objective requirement set and command can be allowed
3855 if(float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
3857 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",
3858 tablename,tmp.datalong2,tmp.id);
3859 continue;
3862 if(tmp.datalong2 && float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
3864 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",
3865 tablename,tmp.datalong2,tmp.id,DEFAULT_VISIBILITY_DISTANCE);
3866 continue;
3869 if(tmp.datalong2 && float(tmp.datalong2) < INTERACTION_DISTANCE)
3871 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",
3872 tablename,tmp.datalong2,tmp.id,INTERACTION_DISTANCE);
3873 continue;
3876 break;
3879 case SCRIPT_COMMAND_REMOVE_AURA:
3880 case SCRIPT_COMMAND_CAST_SPELL:
3882 if(!sSpellStore.LookupEntry(tmp.datalong))
3884 sLog.outErrorDb("Table `%s` using non-existent spell (id: %u) in SCRIPT_COMMAND_REMOVE_AURA or SCRIPT_COMMAND_CAST_SPELL for script id %u",
3885 tablename,tmp.datalong,tmp.id);
3886 continue;
3888 break;
3892 if (scripts.find(tmp.id) == scripts.end())
3894 ScriptMap emptyMap;
3895 scripts[tmp.id] = emptyMap;
3897 scripts[tmp.id].insert(std::pair<uint32, ScriptInfo>(tmp.delay, tmp));
3899 ++count;
3900 } while( result->NextRow() );
3902 delete result;
3904 sLog.outString();
3905 sLog.outString( ">> Loaded %u script definitions", count );
3908 void ObjectMgr::LoadGameObjectScripts()
3910 LoadScripts(sGameObjectScripts, "gameobject_scripts");
3912 // check ids
3913 for(ScriptMapMap::const_iterator itr = sGameObjectScripts.begin(); itr != sGameObjectScripts.end(); ++itr)
3915 if(!GetGOData(itr->first))
3916 sLog.outErrorDb("Table `gameobject_scripts` has not existing gameobject (GUID: %u) as script id",itr->first);
3920 void ObjectMgr::LoadQuestEndScripts()
3922 LoadScripts(sQuestEndScripts, "quest_end_scripts");
3924 // check ids
3925 for(ScriptMapMap::const_iterator itr = sQuestEndScripts.begin(); itr != sQuestEndScripts.end(); ++itr)
3927 if(!GetQuestTemplate(itr->first))
3928 sLog.outErrorDb("Table `quest_end_scripts` has not existing quest (Id: %u) as script id",itr->first);
3932 void ObjectMgr::LoadQuestStartScripts()
3934 LoadScripts(sQuestStartScripts,"quest_start_scripts");
3936 // check ids
3937 for(ScriptMapMap::const_iterator itr = sQuestStartScripts.begin(); itr != sQuestStartScripts.end(); ++itr)
3939 if(!GetQuestTemplate(itr->first))
3940 sLog.outErrorDb("Table `quest_start_scripts` has not existing quest (Id: %u) as script id",itr->first);
3944 void ObjectMgr::LoadSpellScripts()
3946 LoadScripts(sSpellScripts, "spell_scripts");
3948 // check ids
3949 for(ScriptMapMap::const_iterator itr = sSpellScripts.begin(); itr != sSpellScripts.end(); ++itr)
3951 SpellEntry const* spellInfo = sSpellStore.LookupEntry(itr->first);
3953 if(!spellInfo)
3955 sLog.outErrorDb("Table `spell_scripts` has not existing spell (Id: %u) as script id",itr->first);
3956 continue;
3959 //check for correct spellEffect
3960 bool found = false;
3961 for(int i=0; i<3; ++i)
3963 // skip empty effects
3964 if( !spellInfo->Effect[i] )
3965 continue;
3967 if( spellInfo->Effect[i] == SPELL_EFFECT_SCRIPT_EFFECT )
3969 found = true;
3970 break;
3974 if(!found)
3975 sLog.outErrorDb("Table `spell_scripts` has unsupported spell (Id: %u) without SPELL_EFFECT_SCRIPT_EFFECT (%u) spell effect",itr->first,SPELL_EFFECT_SCRIPT_EFFECT);
3979 void ObjectMgr::LoadEventScripts()
3981 LoadScripts(sEventScripts, "event_scripts");
3983 std::set<uint32> evt_scripts;
3984 // Load all possible script entries from gameobjects
3985 for(uint32 i = 1; i < sGOStorage.MaxEntry; ++i)
3987 GameObjectInfo const * goInfo = sGOStorage.LookupEntry<GameObjectInfo>(i);
3988 if (goInfo)
3990 switch(goInfo->type)
3992 case GAMEOBJECT_TYPE_GOOBER:
3993 if(goInfo->goober.eventId)
3994 evt_scripts.insert(goInfo->goober.eventId);
3995 break;
3996 case GAMEOBJECT_TYPE_CHEST:
3997 if(goInfo->chest.eventId)
3998 evt_scripts.insert(goInfo->chest.eventId);
3999 break;
4000 default:
4001 break;
4005 // Load all possible script entries from spells
4006 for(uint32 i = 1; i < sSpellStore.GetNumRows(); ++i)
4008 SpellEntry const * spell = sSpellStore.LookupEntry(i);
4009 if (spell)
4011 for(int j=0; j<3; ++j)
4013 if( spell->Effect[j] == SPELL_EFFECT_SEND_EVENT )
4015 if (spell->EffectMiscValue[j])
4016 evt_scripts.insert(spell->EffectMiscValue[j]);
4021 // Then check if all scripts are in above list of possible script entries
4022 for(ScriptMapMap::const_iterator itr = sEventScripts.begin(); itr != sEventScripts.end(); ++itr)
4024 std::set<uint32>::const_iterator itr2 = evt_scripts.find(itr->first);
4025 if (itr2 == evt_scripts.end())
4026 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);
4030 void ObjectMgr::LoadItemTexts()
4032 QueryResult *result = CharacterDatabase.Query("SELECT id, text FROM item_text");
4034 uint32 count = 0;
4036 if( !result )
4038 barGoLink bar( 1 );
4039 bar.step();
4041 sLog.outString();
4042 sLog.outString( ">> Loaded %u item pages", count );
4043 return;
4046 barGoLink bar( result->GetRowCount() );
4048 Field* fields;
4051 bar.step();
4053 fields = result->Fetch();
4055 mItemTexts[ fields[0].GetUInt32() ] = fields[1].GetCppString();
4057 ++count;
4059 } while ( result->NextRow() );
4061 delete result;
4063 sLog.outString();
4064 sLog.outString( ">> Loaded %u item texts", count );
4067 void ObjectMgr::LoadPageTexts()
4069 sPageTextStore.Free(); // for reload case
4071 sPageTextStore.Load();
4072 sLog.outString( ">> Loaded %u page texts", sPageTextStore.RecordCount );
4073 sLog.outString();
4075 for(uint32 i = 1; i < sPageTextStore.MaxEntry; ++i)
4077 // check data correctness
4078 PageText const* page = sPageTextStore.LookupEntry<PageText>(i);
4079 if(!page)
4080 continue;
4082 if(page->Next_Page && !sPageTextStore.LookupEntry<PageText>(page->Next_Page))
4084 sLog.outErrorDb("Page text (Id: %u) has not existing next page (Id:%u)", i,page->Next_Page);
4085 continue;
4088 // detect circular reference
4089 std::set<uint32> checkedPages;
4090 for(PageText const* pageItr = page; pageItr; pageItr = sPageTextStore.LookupEntry<PageText>(pageItr->Next_Page))
4092 if(!pageItr->Next_Page)
4093 break;
4094 checkedPages.insert(pageItr->Page_ID);
4095 if(checkedPages.find(pageItr->Next_Page)!=checkedPages.end())
4097 std::ostringstream ss;
4098 ss<< "The text page(s) ";
4099 for (std::set<uint32>::iterator itr= checkedPages.begin();itr!=checkedPages.end(); itr++)
4100 ss << *itr << " ";
4101 ss << "create(s) a circular reference, which can cause the server to freeze. Changing Next_Page of page "
4102 << pageItr->Page_ID <<" to 0";
4103 sLog.outErrorDb(ss.str().c_str());
4104 const_cast<PageText*>(pageItr)->Next_Page = 0;
4105 break;
4111 void ObjectMgr::LoadPageTextLocales()
4113 mPageTextLocaleMap.clear(); // need for reload case
4115 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");
4117 if(!result)
4119 barGoLink bar(1);
4121 bar.step();
4123 sLog.outString("");
4124 sLog.outString(">> Loaded 0 PageText locale strings. DB table `locales_page_text` is empty.");
4125 return;
4128 barGoLink bar(result->GetRowCount());
4132 Field *fields = result->Fetch();
4133 bar.step();
4135 uint32 entry = fields[0].GetUInt32();
4137 PageTextLocale& data = mPageTextLocaleMap[entry];
4139 for(int i = 1; i < MAX_LOCALE; ++i)
4141 std::string str = fields[i].GetCppString();
4142 if(str.empty())
4143 continue;
4145 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4146 if(idx >= 0)
4148 if(data.Text.size() <= idx)
4149 data.Text.resize(idx+1);
4151 data.Text[idx] = str;
4155 } while (result->NextRow());
4157 delete result;
4159 sLog.outString();
4160 sLog.outString( ">> Loaded %u PageText locale strings", mPageTextLocaleMap.size() );
4163 void ObjectMgr::LoadInstanceTemplate()
4165 sInstanceTemplate.Load();
4167 for(uint32 i = 0; i < sInstanceTemplate.MaxEntry; i++)
4169 InstanceTemplate* temp = (InstanceTemplate*)GetInstanceTemplate(i);
4170 if(!temp) continue;
4171 const MapEntry* entry = sMapStore.LookupEntry(temp->map);
4172 if(!entry)
4174 sLog.outErrorDb("ObjectMgr::LoadInstanceTemplate: bad mapid %d for template!", temp->map);
4175 continue;
4177 else if(!entry->HasResetTime())
4178 continue;
4180 if(temp->reset_delay == 0)
4182 // use defaults from the DBC
4183 if(entry->SupportsHeroicMode())
4185 temp->reset_delay = entry->resetTimeHeroic / DAY;
4187 else if (entry->resetTimeRaid && entry->map_type == MAP_RAID)
4189 temp->reset_delay = entry->resetTimeRaid / DAY;
4193 // the reset_delay must be at least one day
4194 temp->reset_delay = std::max((uint32)1, (uint32)(temp->reset_delay * sWorld.getRate(RATE_INSTANCE_RESET_TIME)));
4197 sLog.outString( ">> Loaded %u Instance Template definitions", sInstanceTemplate.RecordCount );
4198 sLog.outString();
4201 void ObjectMgr::AddGossipText(GossipText *pGText)
4203 ASSERT( pGText->Text_ID );
4204 ASSERT( mGossipText.find(pGText->Text_ID) == mGossipText.end() );
4205 mGossipText[pGText->Text_ID] = pGText;
4208 GossipText *ObjectMgr::GetGossipText(uint32 Text_ID)
4210 GossipTextMap::const_iterator itr;
4211 for (itr = mGossipText.begin(); itr != mGossipText.end(); itr++)
4213 if(itr->second->Text_ID == Text_ID)
4214 return itr->second;
4216 return NULL;
4219 void ObjectMgr::LoadGossipText()
4221 GossipText *pGText;
4222 QueryResult *result = WorldDatabase.Query( "SELECT * FROM npc_text" );
4224 int count = 0;
4225 if( !result )
4227 barGoLink bar( 1 );
4228 bar.step();
4230 sLog.outString();
4231 sLog.outString( ">> Loaded %u npc texts", count );
4232 return;
4235 int cic;
4237 barGoLink bar( result->GetRowCount() );
4241 ++count;
4242 cic = 0;
4244 Field *fields = result->Fetch();
4246 bar.step();
4248 pGText = new GossipText;
4249 pGText->Text_ID = fields[cic++].GetUInt32();
4251 for (int i=0; i< 8; i++)
4253 pGText->Options[i].Text_0 = fields[cic++].GetCppString();
4254 pGText->Options[i].Text_1 = fields[cic++].GetCppString();
4256 pGText->Options[i].Language = fields[cic++].GetUInt32();
4257 pGText->Options[i].Probability = fields[cic++].GetFloat();
4259 pGText->Options[i].Emotes[0]._Delay = fields[cic++].GetUInt32();
4260 pGText->Options[i].Emotes[0]._Emote = fields[cic++].GetUInt32();
4262 pGText->Options[i].Emotes[1]._Delay = fields[cic++].GetUInt32();
4263 pGText->Options[i].Emotes[1]._Emote = fields[cic++].GetUInt32();
4265 pGText->Options[i].Emotes[2]._Delay = fields[cic++].GetUInt32();
4266 pGText->Options[i].Emotes[2]._Emote = fields[cic++].GetUInt32();
4269 if ( !pGText->Text_ID ) continue;
4270 AddGossipText( pGText );
4272 } while( result->NextRow() );
4274 sLog.outString();
4275 sLog.outString( ">> Loaded %u npc texts", count );
4276 delete result;
4279 void ObjectMgr::LoadNpcTextLocales()
4281 mNpcTextLocaleMap.clear(); // need for reload case
4283 QueryResult *result = WorldDatabase.Query("SELECT entry,"
4284 "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,"
4285 "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,"
4286 "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,"
4287 "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,"
4288 "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,"
4289 "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,"
4290 "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, "
4291 "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 "
4292 " FROM locales_npc_text");
4294 if(!result)
4296 barGoLink bar(1);
4298 bar.step();
4300 sLog.outString("");
4301 sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_npc_text` is empty.");
4302 return;
4305 barGoLink bar(result->GetRowCount());
4309 Field *fields = result->Fetch();
4310 bar.step();
4312 uint32 entry = fields[0].GetUInt32();
4314 NpcTextLocale& data = mNpcTextLocaleMap[entry];
4316 for(int i=1; i<MAX_LOCALE; ++i)
4318 for(int j=0; j<8; ++j)
4320 std::string str0 = fields[1+8*2*(i-1)+2*j].GetCppString();
4321 if(!str0.empty())
4323 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4324 if(idx >= 0)
4326 if(data.Text_0[j].size() <= idx)
4327 data.Text_0[j].resize(idx+1);
4329 data.Text_0[j][idx] = str0;
4332 std::string str1 = fields[1+8*2*(i-1)+2*j+1].GetCppString();
4333 if(!str1.empty())
4335 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4336 if(idx >= 0)
4338 if(data.Text_1[j].size() <= idx)
4339 data.Text_1[j].resize(idx+1);
4341 data.Text_1[j][idx] = str1;
4346 } while (result->NextRow());
4348 delete result;
4350 sLog.outString();
4351 sLog.outString( ">> Loaded %u NpcText locale strings", mNpcTextLocaleMap.size() );
4354 //not very fast function but it is called only once a day, or on starting-up
4355 void ObjectMgr::ReturnOrDeleteOldMails(bool serverUp)
4357 time_t basetime = time(NULL);
4358 sLog.outDebug("Returning mails current time: hour: %d, minute: %d, second: %d ", localtime(&basetime)->tm_hour, localtime(&basetime)->tm_min, localtime(&basetime)->tm_sec);
4359 //delete all old mails without item and without body immediately, if starting server
4360 if (!serverUp)
4361 CharacterDatabase.PExecute("DELETE FROM mail WHERE expire_time < '" I64FMTD "' AND has_items = '0' AND itemTextId = 0", (uint64)basetime);
4362 // 0 1 2 3 4 5 6 7 8 9
4363 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);
4364 if ( !result )
4365 return; // any mails need to be returned or deleted
4366 Field *fields;
4367 //std::ostringstream delitems, delmails; //will be here for optimization
4368 //bool deletemail = false, deleteitem = false;
4369 //delitems << "DELETE FROM item_instance WHERE guid IN ( ";
4370 //delmails << "DELETE FROM mail WHERE id IN ( "
4373 fields = result->Fetch();
4374 Mail *m = new Mail;
4375 m->messageID = fields[0].GetUInt32();
4376 m->messageType = fields[1].GetUInt8();
4377 m->sender = fields[2].GetUInt32();
4378 m->receiver = fields[3].GetUInt32();
4379 m->itemTextId = fields[4].GetUInt32();
4380 bool has_items = fields[5].GetBool();
4381 m->expire_time = (time_t)fields[6].GetUInt64();
4382 m->deliver_time = 0;
4383 m->COD = fields[7].GetUInt32();
4384 m->checked = fields[8].GetUInt32();
4385 m->mailTemplateId = fields[9].GetInt16();
4387 Player *pl = 0;
4388 if (serverUp)
4389 pl = GetPlayer((uint64)m->receiver);
4390 if (pl && pl->m_mailsLoaded)
4391 { //this code will run very improbably (the time is between 4 and 5 am, in game is online a player, who has old mail
4392 //his in mailbox and he has already listed his mails )
4393 delete m;
4394 continue;
4396 //delete or return mail:
4397 if (has_items)
4399 QueryResult *resultItems = CharacterDatabase.PQuery("SELECT item_guid,item_template FROM mail_items WHERE mail_id='%u'", m->messageID);
4400 if(resultItems)
4404 Field *fields2 = resultItems->Fetch();
4406 uint32 item_guid_low = fields2[0].GetUInt32();
4407 uint32 item_template = fields2[1].GetUInt32();
4409 m->AddItem(item_guid_low, item_template);
4411 while (resultItems->NextRow());
4413 delete resultItems;
4415 //if it is mail from AH, it shouldn't be returned, but deleted
4416 if (m->messageType != MAIL_NORMAL || (m->checked & (MAIL_CHECK_MASK_AUCTION | MAIL_CHECK_MASK_COD_PAYMENT | MAIL_CHECK_MASK_RETURNED)))
4418 // mail open and then not returned
4419 for(std::vector<MailItemInfo>::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
4420 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
4422 else
4424 //mail will be returned:
4425 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);
4426 delete m;
4427 continue;
4431 if (m->itemTextId)
4432 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
4434 //deletemail = true;
4435 //delmails << m->messageID << ", ";
4436 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
4437 delete m;
4438 } while (result->NextRow());
4439 delete result;
4442 void ObjectMgr::LoadQuestAreaTriggers()
4444 mQuestAreaTriggerMap.clear(); // need for reload case
4446 QueryResult *result = WorldDatabase.Query( "SELECT id,quest FROM areatrigger_involvedrelation" );
4448 uint32 count = 0;
4450 if( !result )
4452 barGoLink bar( 1 );
4453 bar.step();
4455 sLog.outString();
4456 sLog.outString( ">> Loaded %u quest trigger points", count );
4457 return;
4460 barGoLink bar( result->GetRowCount() );
4464 ++count;
4465 bar.step();
4467 Field *fields = result->Fetch();
4469 uint32 trigger_ID = fields[0].GetUInt32();
4470 uint32 quest_ID = fields[1].GetUInt32();
4472 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(trigger_ID);
4473 if(!atEntry)
4475 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",trigger_ID);
4476 continue;
4479 Quest const* quest = GetQuestTemplate(quest_ID);
4481 if(!quest)
4483 sLog.outErrorDb("Table `areatrigger_involvedrelation` has record (id: %u) for not existing quest %u",trigger_ID,quest_ID);
4484 continue;
4487 if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
4489 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);
4491 // this will prevent quest completing without objective
4492 const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
4494 // continue; - quest modified to required objective and trigger can be allowed.
4497 mQuestAreaTriggerMap[trigger_ID] = quest_ID;
4499 } while( result->NextRow() );
4501 delete result;
4503 sLog.outString();
4504 sLog.outString( ">> Loaded %u quest trigger points", count );
4507 void ObjectMgr::LoadTavernAreaTriggers()
4509 mTavernAreaTriggerSet.clear(); // need for reload case
4511 QueryResult *result = WorldDatabase.Query("SELECT id FROM areatrigger_tavern");
4513 uint32 count = 0;
4515 if( !result )
4517 barGoLink bar( 1 );
4518 bar.step();
4520 sLog.outString();
4521 sLog.outString( ">> Loaded %u tavern triggers", count );
4522 return;
4525 barGoLink bar( result->GetRowCount() );
4529 ++count;
4530 bar.step();
4532 Field *fields = result->Fetch();
4534 uint32 Trigger_ID = fields[0].GetUInt32();
4536 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4537 if(!atEntry)
4539 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4540 continue;
4543 mTavernAreaTriggerSet.insert(Trigger_ID);
4544 } while( result->NextRow() );
4546 delete result;
4548 sLog.outString();
4549 sLog.outString( ">> Loaded %u tavern triggers", count );
4552 void ObjectMgr::LoadAreaTriggerScripts()
4554 mAreaTriggerScripts.clear(); // need for reload case
4555 QueryResult *result = WorldDatabase.Query("SELECT entry, ScriptName FROM areatrigger_scripts");
4557 uint32 count = 0;
4559 if( !result )
4561 barGoLink bar( 1 );
4562 bar.step();
4564 sLog.outString();
4565 sLog.outString( ">> Loaded %u areatrigger scripts", count );
4566 return;
4569 barGoLink bar( result->GetRowCount() );
4573 ++count;
4574 bar.step();
4576 Field *fields = result->Fetch();
4578 uint32 Trigger_ID = fields[0].GetUInt32();
4579 std::string scriptName = fields[1].GetCppString();
4581 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4582 if(!atEntry)
4584 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4585 continue;
4587 mAreaTriggerScripts[Trigger_ID] = scriptName;
4588 } while( result->NextRow() );
4590 delete result;
4592 sLog.outString();
4593 sLog.outString( ">> Loaded %u areatrigger scripts", count );
4596 uint32 ObjectMgr::GetNearestTaxiNode( float x, float y, float z, uint32 mapid )
4598 bool found = false;
4599 float dist;
4600 uint32 id = 0;
4602 for(uint32 i = 1; i < sTaxiNodesStore.GetNumRows(); ++i)
4604 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(i);
4605 if(node && node->map_id == mapid)
4607 float dist2 = (node->x - x)*(node->x - x)+(node->y - y)*(node->y - y)+(node->z - z)*(node->z - z);
4608 if(found)
4610 if(dist2 < dist)
4612 dist = dist2;
4613 id = i;
4616 else
4618 found = true;
4619 dist = dist2;
4620 id = i;
4625 return id;
4628 void ObjectMgr::GetTaxiPath( uint32 source, uint32 destination, uint32 &path, uint32 &cost)
4630 TaxiPathSetBySource::iterator src_i = sTaxiPathSetBySource.find(source);
4631 if(src_i==sTaxiPathSetBySource.end())
4633 path = 0;
4634 cost = 0;
4635 return;
4638 TaxiPathSetForSource& pathSet = src_i->second;
4640 TaxiPathSetForSource::iterator dest_i = pathSet.find(destination);
4641 if(dest_i==pathSet.end())
4643 path = 0;
4644 cost = 0;
4645 return;
4648 cost = dest_i->second.price;
4649 path = dest_i->second.ID;
4652 uint16 ObjectMgr::GetTaxiMount( uint32 id, uint32 team )
4654 uint16 mount_entry = 0;
4655 uint16 mount_id = 0;
4657 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(id);
4658 if(node)
4660 if (team == ALLIANCE)
4662 mount_entry = node->alliance_mount_type;
4663 CreatureInfo const *ci = GetCreatureTemplate(mount_entry);
4664 if(ci)
4665 mount_id = ci->DisplayID_A;
4667 if (team == HORDE)
4669 mount_entry = node->horde_mount_type;
4670 CreatureInfo const *ci = GetCreatureTemplate(mount_entry);
4671 if(ci)
4672 mount_id = ci->DisplayID_H;
4676 CreatureModelInfo const *minfo = GetCreatureModelInfo(mount_id);
4677 if(!minfo)
4679 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. ",
4680 mount_entry,id,team,mount_id);
4682 return false;
4684 if(minfo->modelid_other_gender!=0)
4685 mount_id = urand(0,1) ? mount_id : minfo->modelid_other_gender;
4687 return mount_id;
4690 void ObjectMgr::GetTaxiPathNodes( uint32 path, Path &pathnodes, std::vector<uint32>& mapIds)
4692 if(path >= sTaxiPathNodesByPath.size())
4693 return;
4695 TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
4697 pathnodes.Resize(nodeList.size());
4698 mapIds.resize(nodeList.size());
4700 for(size_t i = 0; i < nodeList.size(); ++i)
4702 pathnodes[ i ].x = nodeList[i].x;
4703 pathnodes[ i ].y = nodeList[i].y;
4704 pathnodes[ i ].z = nodeList[i].z;
4706 mapIds[i] = nodeList[i].mapid;
4710 void ObjectMgr::GetTransportPathNodes( uint32 path, TransportPath &pathnodes )
4712 if(path >= sTaxiPathNodesByPath.size())
4713 return;
4715 TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
4717 pathnodes.Resize(nodeList.size());
4719 for(size_t i = 0; i < nodeList.size(); ++i)
4721 pathnodes[ i ].mapid = nodeList[i].mapid;
4722 pathnodes[ i ].x = nodeList[i].x;
4723 pathnodes[ i ].y = nodeList[i].y;
4724 pathnodes[ i ].z = nodeList[i].z;
4725 pathnodes[ i ].actionFlag = nodeList[i].actionFlag;
4726 pathnodes[ i ].delay = nodeList[i].delay;
4730 void ObjectMgr::LoadGraveyardZones()
4732 mGraveYardMap.clear(); // need for reload case
4734 QueryResult *result = WorldDatabase.Query("SELECT id,ghost_zone,faction FROM game_graveyard_zone");
4736 uint32 count = 0;
4738 if( !result )
4740 barGoLink bar( 1 );
4741 bar.step();
4743 sLog.outString();
4744 sLog.outString( ">> Loaded %u graveyard-zone links", count );
4745 return;
4748 barGoLink bar( result->GetRowCount() );
4752 ++count;
4753 bar.step();
4755 Field *fields = result->Fetch();
4757 uint32 safeLocId = fields[0].GetUInt32();
4758 uint32 zoneId = fields[1].GetUInt32();
4759 uint32 team = fields[2].GetUInt32();
4761 WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(safeLocId);
4762 if(!entry)
4764 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",safeLocId);
4765 continue;
4768 AreaTableEntry const *areaEntry = GetAreaEntryByAreaID(zoneId);
4769 if(!areaEntry)
4771 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing zone id (%u), skipped.",zoneId);
4772 continue;
4775 if(areaEntry->zone != 0)
4777 sLog.outErrorDb("Table `game_graveyard_zone` has record subzone id (%u) instead of zone, skipped.",zoneId);
4778 continue;
4781 if(team!=0 && team!=HORDE && team!=ALLIANCE)
4783 sLog.outErrorDb("Table `game_graveyard_zone` has record for non player faction (%u), skipped.",team);
4784 continue;
4787 if(entry->map_id != areaEntry->mapid && team != 0)
4789 sLog.outErrorDb("Table `game_graveyard_zone` has record for ghost zone (%u) at map %u and graveyard (%u) at map %u for team %u, but in case maps are different, player faction setting is ignored. Use faction 0 instead.",zoneId,areaEntry->mapid, safeLocId, entry->map_id, team);
4790 team = 0;
4793 if(!AddGraveYardLink(safeLocId,zoneId,team,false))
4794 sLog.outErrorDb("Table `game_graveyard_zone` has a duplicate record for Graveyard (ID: %u) and Zone (ID: %u), skipped.",safeLocId,zoneId);
4795 } while( result->NextRow() );
4797 delete result;
4799 sLog.outString();
4800 sLog.outString( ">> Loaded %u graveyard-zone links", count );
4803 WorldSafeLocsEntry const *ObjectMgr::GetClosestGraveYard(float x, float y, float z, uint32 MapId, uint32 team)
4805 // search for zone associated closest graveyard
4806 uint32 zoneId = MapManager::Instance().GetZoneId(MapId,x,y);
4808 // Simulate std. algorithm:
4809 // found some graveyard associated to (ghost_zone,ghost_map)
4811 // if mapId == graveyard.mapId (ghost in plain zone or city or battleground) and search graveyard at same map
4812 // then check faction
4813 // if mapId != graveyard.mapId (ghost in instance) and search any graveyard associated
4814 // then skip check faction
4815 GraveYardMap::const_iterator graveLow = mGraveYardMap.lower_bound(zoneId);
4816 GraveYardMap::const_iterator graveUp = mGraveYardMap.upper_bound(zoneId);
4817 if(graveLow==graveUp)
4819 sLog.outErrorDb("Table `game_graveyard_zone` incomplete: Zone %u Team %u does not have a linked graveyard.",zoneId,team);
4820 return NULL;
4823 bool foundNear = false;
4824 float distNear;
4825 WorldSafeLocsEntry const* entryNear = NULL;
4826 WorldSafeLocsEntry const* entryFar = NULL;
4828 for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
4830 GraveYardData const& data = itr->second;
4832 WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(data.safeLocId);
4833 if(!entry)
4835 sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",data.safeLocId);
4836 continue;
4839 // remember first graveyard at another map and ignore other
4840 if(MapId != entry->map_id)
4842 if(!entryFar)
4843 entryFar = entry;
4844 continue;
4847 // skip enemy faction graveyard at same map (normal area, city, or battleground)
4848 // team == 0 case can be at call from .neargrave
4849 if(data.team != 0 && team != 0 && data.team != team)
4850 continue;
4852 // find now nearest graveyard at same map
4853 float dist2 = (entry->x - x)*(entry->x - x)+(entry->y - y)*(entry->y - y)+(entry->z - z)*(entry->z - z);
4854 if(foundNear)
4856 if(dist2 < distNear)
4858 distNear = dist2;
4859 entryNear = entry;
4862 else
4864 foundNear = true;
4865 distNear = dist2;
4866 entryNear = entry;
4870 if(entryNear)
4871 return entryNear;
4873 return entryFar;
4876 GraveYardData const* ObjectMgr::FindGraveYardData(uint32 id, uint32 zoneId)
4878 GraveYardMap::const_iterator graveLow = mGraveYardMap.lower_bound(zoneId);
4879 GraveYardMap::const_iterator graveUp = mGraveYardMap.upper_bound(zoneId);
4881 for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
4883 if(itr->second.safeLocId==id)
4884 return &itr->second;
4887 return NULL;
4890 bool ObjectMgr::AddGraveYardLink(uint32 id, uint32 zoneId, uint32 team, bool inDB)
4892 if(FindGraveYardData(id,zoneId))
4893 return false;
4895 // add link to loaded data
4896 GraveYardData data;
4897 data.safeLocId = id;
4898 data.team = team;
4900 mGraveYardMap.insert(GraveYardMap::value_type(zoneId,data));
4902 // add link to DB
4903 if(inDB)
4905 WorldDatabase.PExecuteLog("INSERT INTO game_graveyard_zone ( id,ghost_zone,faction) "
4906 "VALUES ('%u', '%u','%u')",id,zoneId,team);
4909 return true;
4912 void ObjectMgr::LoadAreaTriggerTeleports()
4914 mAreaTriggers.clear(); // need for reload case
4916 uint32 count = 0;
4918 // 0 1 2 3 4 5 6 7 8 9 10 11 12
4919 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");
4920 if( !result )
4923 barGoLink bar( 1 );
4925 bar.step();
4927 sLog.outString();
4928 sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
4929 return;
4932 barGoLink bar( result->GetRowCount() );
4936 Field *fields = result->Fetch();
4938 bar.step();
4940 ++count;
4942 uint32 Trigger_ID = fields[0].GetUInt32();
4944 AreaTrigger at;
4946 at.requiredLevel = fields[1].GetUInt8();
4947 at.requiredItem = fields[2].GetUInt32();
4948 at.requiredItem2 = fields[3].GetUInt32();
4949 at.heroicKey = fields[4].GetUInt32();
4950 at.heroicKey2 = fields[5].GetUInt32();
4951 at.requiredQuest = fields[6].GetUInt32();
4952 at.requiredFailedText = fields[7].GetCppString();
4953 at.target_mapId = fields[8].GetUInt32();
4954 at.target_X = fields[9].GetFloat();
4955 at.target_Y = fields[10].GetFloat();
4956 at.target_Z = fields[11].GetFloat();
4957 at.target_Orientation = fields[12].GetFloat();
4959 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4960 if(!atEntry)
4962 sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4963 continue;
4966 if(at.requiredItem)
4968 ItemPrototype const *pProto = GetItemPrototype(at.requiredItem);
4969 if(!pProto)
4971 sLog.outError("Key item %u does not exist for trigger %u, removing key requirement.", at.requiredItem, Trigger_ID);
4972 at.requiredItem = 0;
4975 if(at.requiredItem2)
4977 ItemPrototype const *pProto = GetItemPrototype(at.requiredItem2);
4978 if(!pProto)
4980 sLog.outError("Second item %u not exist for trigger %u, remove key requirement.", at.requiredItem2, Trigger_ID);
4981 at.requiredItem2 = 0;
4985 if(at.heroicKey)
4987 ItemPrototype const *pProto = GetItemPrototype(at.heroicKey);
4988 if(!pProto)
4990 sLog.outError("Heroic key item %u not exist for trigger %u, remove key requirement.", at.heroicKey, Trigger_ID);
4991 at.heroicKey = 0;
4995 if(at.heroicKey2)
4997 ItemPrototype const *pProto = GetItemPrototype(at.heroicKey2);
4998 if(!pProto)
5000 sLog.outError("Heroic second key item %u not exist for trigger %u, remove key requirement.", at.heroicKey2, Trigger_ID);
5001 at.heroicKey2 = 0;
5005 if(at.requiredQuest)
5007 if(!mQuestTemplates[at.requiredQuest])
5009 sLog.outErrorDb("Required Quest %u not exist for trigger %u, remove quest done requirement.",at.requiredQuest,Trigger_ID);
5010 at.requiredQuest = 0;
5014 MapEntry const* mapEntry = sMapStore.LookupEntry(at.target_mapId);
5015 if(!mapEntry)
5017 sLog.outErrorDb("Area trigger (ID:%u) target map (ID: %u) does not exist in `Map.dbc`.",Trigger_ID,at.target_mapId);
5018 continue;
5021 if(at.target_X==0 && at.target_Y==0 && at.target_Z==0)
5023 sLog.outErrorDb("Area trigger (ID:%u) target coordinates not provided.",Trigger_ID);
5024 continue;
5027 mAreaTriggers[Trigger_ID] = at;
5029 } while( result->NextRow() );
5031 delete result;
5033 sLog.outString();
5034 sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
5037 AreaTrigger const* ObjectMgr::GetGoBackTrigger(uint32 Map) const
5039 const MapEntry *mapEntry = sMapStore.LookupEntry(Map);
5040 if(!mapEntry) return NULL;
5041 for (AreaTriggerMap::const_iterator itr = mAreaTriggers.begin(); itr != mAreaTriggers.end(); itr++)
5043 if(itr->second.target_mapId == mapEntry->entrance_map)
5045 AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(itr->first);
5046 if(atEntry && atEntry->mapid == Map)
5047 return &itr->second;
5050 return NULL;
5053 void ObjectMgr::SetHighestGuids()
5055 QueryResult *result = CharacterDatabase.Query( "SELECT MAX(guid) FROM characters" );
5056 if( result )
5058 m_hiCharGuid = (*result)[0].GetUInt32()+1;
5060 delete result;
5063 result = WorldDatabase.Query( "SELECT MAX(guid) FROM creature" );
5064 if( result )
5066 m_hiCreatureGuid = (*result)[0].GetUInt32()+1;
5068 delete result;
5071 // pet guids are not saved to DB, set to 0 (pet guid != pet id)
5072 m_hiPetGuid = 0;
5074 result = CharacterDatabase.Query( "SELECT MAX(guid) FROM item_instance" );
5075 if( result )
5077 m_hiItemGuid = (*result)[0].GetUInt32()+1;
5079 delete result;
5082 // Cleanup other tables from not existed guids (>=m_hiItemGuid)
5083 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item >= '%u'", m_hiItemGuid);
5084 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid >= '%u'", m_hiItemGuid);
5085 CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE itemguid >= '%u'", m_hiItemGuid);
5086 CharacterDatabase.PExecute("DELETE FROM guild_bank_item WHERE item_guid >= '%u'", m_hiItemGuid);
5088 result = WorldDatabase.Query("SELECT MAX(guid) FROM gameobject" );
5089 if( result )
5091 m_hiGoGuid = (*result)[0].GetUInt32()+1;
5093 delete result;
5096 result = CharacterDatabase.Query("SELECT MAX(id) FROM auctionhouse" );
5097 if( result )
5099 m_auctionid = (*result)[0].GetUInt32()+1;
5101 delete result;
5103 else
5105 m_auctionid = 0;
5107 result = CharacterDatabase.Query( "SELECT MAX(id) FROM mail" );
5108 if( result )
5110 m_mailid = (*result)[0].GetUInt32()+1;
5112 delete result;
5114 else
5116 m_mailid = 0;
5118 result = CharacterDatabase.Query( "SELECT MAX(id) FROM item_text" );
5119 if( result )
5121 m_ItemTextId = (*result)[0].GetUInt32();
5123 delete result;
5125 else
5126 m_ItemTextId = 0;
5128 result = CharacterDatabase.Query( "SELECT MAX(guid) FROM corpse" );
5129 if( result )
5131 m_hiCorpseGuid = (*result)[0].GetUInt32()+1;
5133 delete result;
5136 result = CharacterDatabase.Query("SELECT MAX(arenateamid) FROM arena_team");
5137 if (result)
5139 m_arenaTeamId = (*result)[0].GetUInt32()+1;
5141 delete result;
5144 result = CharacterDatabase.Query( "SELECT MAX(guildid) FROM guild" );
5145 if (result)
5147 m_guildId = (*result)[0].GetUInt32()+1;
5149 delete result;
5153 uint32 ObjectMgr::GenerateArenaTeamId()
5155 ++m_arenaTeamId;
5156 if(m_arenaTeamId>=0xFFFFFFFF)
5158 sLog.outError("Arena team ids overflow!! Can't continue, shutting down server. ");
5159 sWorld.m_stopEvent = true;
5161 return m_arenaTeamId;
5164 uint32 ObjectMgr::GenerateGuildId()
5166 ++m_guildId;
5167 if(m_guildId>=0xFFFFFFFF)
5169 sLog.outError("Guild ids overflow!! Can't continue, shutting down server. ");
5170 sWorld.m_stopEvent = true;
5172 return m_guildId;
5175 uint32 ObjectMgr::GenerateAuctionID()
5177 ++m_auctionid;
5178 if(m_auctionid>=0xFFFFFFFF)
5180 sLog.outError("Auctions ids overflow!! Can't continue, shutting down server. ");
5181 sWorld.m_stopEvent = true;
5183 return m_auctionid;
5186 uint32 ObjectMgr::GenerateMailID()
5188 ++m_mailid;
5189 if(m_mailid>=0xFFFFFFFF)
5191 sLog.outError("Mail ids overflow!! Can't continue, shutting down server. ");
5192 sWorld.m_stopEvent = true;
5194 return m_mailid;
5197 uint32 ObjectMgr::GenerateItemTextID()
5199 ++m_ItemTextId;
5200 if(m_ItemTextId>=0xFFFFFFFF)
5202 sLog.outError("Item text ids overflow!! Can't continue, shutting down server. ");
5203 sWorld.m_stopEvent = true;
5205 return m_ItemTextId;
5208 uint32 ObjectMgr::CreateItemText(std::string text)
5210 uint32 newItemTextId = GenerateItemTextID();
5211 //insert new itempage to container
5212 mItemTexts[ newItemTextId ] = text;
5213 //save new itempage
5214 CharacterDatabase.escape_string(text);
5215 //any Delete query needed, itemTextId is maximum of all ids
5216 std::ostringstream query;
5217 query << "INSERT INTO item_text (id,text) VALUES ( '" << newItemTextId << "', '" << text << "')";
5218 CharacterDatabase.Execute(query.str().c_str()); //needs to be run this way, because mail body may be more than 1024 characters
5219 return newItemTextId;
5222 uint32 ObjectMgr::GenerateLowGuid(HighGuid guidhigh)
5224 switch(guidhigh)
5226 case HIGHGUID_ITEM:
5227 ++m_hiItemGuid;
5228 if(m_hiItemGuid>=0xFFFFFFFF)
5230 sLog.outError("Item guid overflow!! Can't continue, shutting down server. ");
5231 sWorld.m_stopEvent = true;
5233 return m_hiItemGuid;
5234 case HIGHGUID_UNIT:
5235 ++m_hiCreatureGuid;
5236 if(m_hiCreatureGuid>=0x00FFFFFF)
5238 sLog.outError("Creature guid overflow!! Can't continue, shutting down server. ");
5239 sWorld.m_stopEvent = true;
5241 return m_hiCreatureGuid;
5242 case HIGHGUID_PET:
5243 ++m_hiPetGuid;
5244 if(m_hiPetGuid>=0x00FFFFFF)
5246 sLog.outError("Pet guid overflow!! Can't continue, shutting down server. ");
5247 sWorld.m_stopEvent = true;
5249 return m_hiPetGuid;
5250 case HIGHGUID_PLAYER:
5251 ++m_hiCharGuid;
5252 if(m_hiCharGuid>=0xFFFFFFFF)
5254 sLog.outError("Players guid overflow!! Can't continue, shutting down server. ");
5255 sWorld.m_stopEvent = true;
5257 return m_hiCharGuid;
5258 case HIGHGUID_GAMEOBJECT:
5259 ++m_hiGoGuid;
5260 if(m_hiGoGuid>=0x00FFFFFF)
5262 sLog.outError("Gameobject guid overflow!! Can't continue, shutting down server. ");
5263 sWorld.m_stopEvent = true;
5265 return m_hiGoGuid;
5266 case HIGHGUID_CORPSE:
5267 ++m_hiCorpseGuid;
5268 if(m_hiCorpseGuid>=0xFFFFFFFF)
5270 sLog.outError("Corpse guid overflow!! Can't continue, shutting down server. ");
5271 sWorld.m_stopEvent = true;
5273 return m_hiCorpseGuid;
5274 case HIGHGUID_DYNAMICOBJECT:
5275 ++m_hiDoGuid;
5276 if(m_hiDoGuid>=0xFFFFFFFF)
5278 sLog.outError("DynamicObject guid overflow!! Can't continue, shutting down server. ");
5279 sWorld.m_stopEvent = true;
5281 return m_hiDoGuid;
5282 default:
5283 ASSERT(0);
5286 ASSERT(0);
5287 return 0;
5290 void ObjectMgr::LoadGameObjectLocales()
5292 mGameObjectLocaleMap.clear(); // need for reload case
5294 QueryResult *result = WorldDatabase.Query("SELECT entry,"
5295 "name_loc1,name_loc2,name_loc3,name_loc4,name_loc5,name_loc6,name_loc7,name_loc8,"
5296 "castbarcaption_loc1,castbarcaption_loc2,castbarcaption_loc3,castbarcaption_loc4,"
5297 "castbarcaption_loc5,castbarcaption_loc6,castbarcaption_loc7,castbarcaption_loc8 FROM locales_gameobject");
5299 if(!result)
5301 barGoLink bar(1);
5303 bar.step();
5305 sLog.outString("");
5306 sLog.outString(">> Loaded 0 gameobject locale strings. DB table `locales_gameobject` is empty.");
5307 return;
5310 barGoLink bar(result->GetRowCount());
5314 Field *fields = result->Fetch();
5315 bar.step();
5317 uint32 entry = fields[0].GetUInt32();
5319 GameObjectLocale& data = mGameObjectLocaleMap[entry];
5321 for(int i = 1; i < MAX_LOCALE; ++i)
5323 std::string str = fields[i].GetCppString();
5324 if(!str.empty())
5326 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5327 if(idx >= 0)
5329 if(data.Name.size() <= idx)
5330 data.Name.resize(idx+1);
5332 data.Name[idx] = str;
5337 for(int i = MAX_LOCALE; i < MAX_LOCALE*2-1; ++i)
5339 std::string str = fields[i].GetCppString();
5340 if(!str.empty())
5342 int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5343 if(idx >= 0)
5345 if(data.CastBarCaption.size() <= idx)
5346 data.CastBarCaption.resize(idx+1);
5348 data.CastBarCaption[idx] = str;
5353 } while (result->NextRow());
5355 delete result;
5357 sLog.outString();
5358 sLog.outString( ">> Loaded %u gameobject locale strings", mGameObjectLocaleMap.size() );
5361 void ObjectMgr::LoadGameobjectInfo()
5363 sGOStorage.Load();
5365 // some checks
5366 for(uint32 id = 1; id < sGOStorage.MaxEntry; id++)
5368 GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(id);
5369 if(!goInfo)
5370 continue;
5372 switch(goInfo->type)
5374 case GAMEOBJECT_TYPE_DOOR: //0
5376 if(goInfo->door.lockId)
5378 if(!sLockStore.LookupEntry(goInfo->door.lockId))
5379 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but lock (Id: %u) not found.",
5380 id,goInfo->type,goInfo->door.lockId,goInfo->door.lockId);
5382 break;
5384 case GAMEOBJECT_TYPE_BUTTON: //1
5386 if(goInfo->button.lockId)
5388 if(!sLockStore.LookupEntry(goInfo->button.lockId))
5389 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but lock (Id: %u) not found.",
5390 id,goInfo->type,goInfo->button.lockId,goInfo->button.lockId);
5392 break;
5394 case GAMEOBJECT_TYPE_CHEST: //3
5396 if(goInfo->chest.lockId)
5398 if(!sLockStore.LookupEntry(goInfo->chest.lockId))
5399 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but lock (Id: %u) not found.",
5400 id,goInfo->type,goInfo->chest.lockId,goInfo->chest.lockId);
5402 if(goInfo->chest.linkedTrapId) // linked trap
5404 if(GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(goInfo->chest.linkedTrapId))
5406 if(trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5407 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data7=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5408 id,goInfo->type,goInfo->chest.linkedTrapId,goInfo->chest.linkedTrapId,GAMEOBJECT_TYPE_TRAP);
5410 /* disable check for while
5411 else
5412 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5413 id,goInfo->type,goInfo->chest.linkedTrapId,goInfo->chest.linkedTrapId);
5416 break;
5418 case GAMEOBJECT_TYPE_TRAP: //6
5420 /* disable check for while
5421 if(goInfo->trap.spellId) // spell
5423 if(!sSpellStore.LookupEntry(goInfo->trap.spellId))
5424 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data3=%u but Spell (Entry %u) not exist.",
5425 id,goInfo->type,goInfo->trap.spellId,goInfo->trap.spellId);
5428 break;
5430 case GAMEOBJECT_TYPE_CHAIR: //7
5431 if(goInfo->chair.height > 2)
5433 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but correct chair height in range 0..2.",
5434 id,goInfo->type,goInfo->chair.height);
5436 // prevent client and server unexpected work
5437 const_cast<GameObjectInfo*>(goInfo)->chair.height = 0;
5439 break;
5440 case GAMEOBJECT_TYPE_SPELL_FOCUS: //8
5442 if(goInfo->spellFocus.focusId)
5444 if(!sSpellFocusObjectStore.LookupEntry(goInfo->spellFocus.focusId))
5445 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but SpellFocus (Id: %u) not exist.",
5446 id,goInfo->type,goInfo->spellFocus.focusId,goInfo->spellFocus.focusId);
5449 if(goInfo->spellFocus.linkedTrapId) // linked trap
5451 if(GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(goInfo->spellFocus.linkedTrapId))
5453 if(trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5454 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5455 id,goInfo->type,goInfo->spellFocus.linkedTrapId,goInfo->spellFocus.linkedTrapId,GAMEOBJECT_TYPE_TRAP);
5457 /* disable check for while
5458 else
5459 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5460 id,goInfo->type,goInfo->spellFocus.linkedTrapId,goInfo->spellFocus.linkedTrapId);
5463 break;
5465 case GAMEOBJECT_TYPE_GOOBER: //10
5467 if(goInfo->goober.pageId) // pageId
5469 if(!sPageTextStore.LookupEntry<PageText>(goInfo->goober.pageId))
5470 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data7=%u but PageText (Entry %u) not exist.",
5471 id,goInfo->type,goInfo->goober.pageId,goInfo->goober.pageId);
5473 /* disable check for while
5474 if(goInfo->goober.spellId) // spell
5476 if(!sSpellStore.LookupEntry(goInfo->goober.spellId))
5477 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but Spell (Entry %u) not exist.",
5478 id,goInfo->type,goInfo->goober.spellId,goInfo->goober.spellId);
5481 if(goInfo->goober.linkedTrapId) // linked trap
5483 if(GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(goInfo->goober.linkedTrapId))
5485 if(trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5486 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data12=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5487 id,goInfo->type,goInfo->goober.linkedTrapId,goInfo->goober.linkedTrapId,GAMEOBJECT_TYPE_TRAP);
5489 /* disable check for while
5490 else
5491 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data12=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5492 id,goInfo->type,goInfo->goober.linkedTrapId,goInfo->goober.linkedTrapId);
5495 break;
5497 case GAMEOBJECT_TYPE_MO_TRANSPORT: //15
5499 if(goInfo->moTransport.taxiPathId)
5501 if(goInfo->moTransport.taxiPathId >= sTaxiPathNodesByPath.size() || sTaxiPathNodesByPath[goInfo->moTransport.taxiPathId].empty())
5502 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but TaxiPath (Id: %u) not exist.",
5503 id,goInfo->type,goInfo->moTransport.taxiPathId,goInfo->moTransport.taxiPathId);
5505 break;
5507 case GAMEOBJECT_TYPE_SUMMONING_RITUAL: //18
5509 /* disabled
5510 if(goInfo->summoningRitual.spellId)
5512 if(!sSpellStore.LookupEntry(goInfo->summoningRitual.spellId))
5513 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but Spell (Entry %u) not exist.",
5514 id,goInfo->type,goInfo->summoningRitual.spellId,goInfo->summoningRitual.spellId);
5517 break;
5519 case GAMEOBJECT_TYPE_SPELLCASTER: //22
5521 if(goInfo->spellcaster.spellId) // spell
5523 if(!sSpellStore.LookupEntry(goInfo->spellcaster.spellId))
5524 sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data3=%u but Spell (Entry %u) not exist.",
5525 id,goInfo->type,goInfo->spellcaster.spellId,goInfo->spellcaster.spellId);
5527 break;
5532 sLog.outString( ">> Loaded %u game object templates", sGOStorage.RecordCount );
5533 sLog.outString();
5536 void ObjectMgr::LoadExplorationBaseXP()
5538 uint32 count = 0;
5539 QueryResult *result = WorldDatabase.Query("SELECT level,basexp FROM exploration_basexp");
5541 if( !result )
5543 barGoLink bar( 1 );
5545 bar.step();
5547 sLog.outString();
5548 sLog.outString( ">> Loaded %u BaseXP definitions", count );
5549 return;
5552 barGoLink bar( result->GetRowCount() );
5556 bar.step();
5558 Field *fields = result->Fetch();
5559 uint32 level = fields[0].GetUInt32();
5560 uint32 basexp = fields[1].GetUInt32();
5561 mBaseXPTable[level] = basexp;
5562 ++count;
5564 while (result->NextRow());
5566 delete result;
5568 sLog.outString();
5569 sLog.outString( ">> Loaded %u BaseXP definitions", count );
5572 uint32 ObjectMgr::GetBaseXP(uint32 level)
5574 return mBaseXPTable[level] ? mBaseXPTable[level] : 0;
5577 void ObjectMgr::LoadPetNames()
5579 uint32 count = 0;
5580 QueryResult *result = WorldDatabase.Query("SELECT word,entry,half FROM pet_name_generation");
5582 if( !result )
5584 barGoLink bar( 1 );
5586 bar.step();
5588 sLog.outString();
5589 sLog.outString( ">> Loaded %u pet name parts", count );
5590 return;
5593 barGoLink bar( result->GetRowCount() );
5597 bar.step();
5599 Field *fields = result->Fetch();
5600 std::string word = fields[0].GetString();
5601 uint32 entry = fields[1].GetUInt32();
5602 bool half = fields[2].GetBool();
5603 if(half)
5604 PetHalfName1[entry].push_back(word);
5605 else
5606 PetHalfName0[entry].push_back(word);
5607 ++count;
5609 while (result->NextRow());
5610 delete result;
5612 sLog.outString();
5613 sLog.outString( ">> Loaded %u pet name parts", count );
5616 void ObjectMgr::LoadPetNumber()
5618 QueryResult* result = CharacterDatabase.Query("SELECT MAX(id) FROM character_pet");
5619 if(result)
5621 Field *fields = result->Fetch();
5622 m_hiPetNumber = fields[0].GetUInt32()+1;
5623 delete result;
5626 barGoLink bar( 1 );
5627 bar.step();
5629 sLog.outString();
5630 sLog.outString( ">> Loaded the max pet number: %d", m_hiPetNumber-1);
5633 std::string ObjectMgr::GeneratePetName(uint32 entry)
5635 std::vector<std::string> & list0 = PetHalfName0[entry];
5636 std::vector<std::string> & list1 = PetHalfName1[entry];
5638 if(list0.empty() || list1.empty())
5640 CreatureInfo const *cinfo = GetCreatureTemplate(entry);
5641 char* petname = GetPetName(cinfo->family, sWorld.GetDefaultDbcLocale());
5642 if(!petname)
5643 petname = cinfo->Name;
5644 return std::string(petname);
5647 return *(list0.begin()+urand(0, list0.size()-1)) + *(list1.begin()+urand(0, list1.size()-1));
5650 uint32 ObjectMgr::GeneratePetNumber()
5652 return ++m_hiPetNumber;
5655 void ObjectMgr::LoadCorpses()
5657 uint32 count = 0;
5658 // 0 1 2 3 4 5 6 7 8 10
5659 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");
5661 if( !result )
5663 barGoLink bar( 1 );
5665 bar.step();
5667 sLog.outString();
5668 sLog.outString( ">> Loaded %u corpses", count );
5669 return;
5672 barGoLink bar( result->GetRowCount() );
5676 bar.step();
5678 Field *fields = result->Fetch();
5680 uint32 guid = fields[result->GetFieldCount()-1].GetUInt32();
5682 Corpse *corpse = new Corpse;
5683 if(!corpse->LoadFromDB(guid,fields))
5685 delete corpse;
5686 continue;
5689 ObjectAccessor::Instance().AddCorpse(corpse);
5691 ++count;
5693 while (result->NextRow());
5694 delete result;
5696 sLog.outString();
5697 sLog.outString( ">> Loaded %u corpses", count );
5700 void ObjectMgr::LoadReputationOnKill()
5702 uint32 count = 0;
5704 // 0 1 2
5705 QueryResult *result = WorldDatabase.Query("SELECT creature_id, RewOnKillRepFaction1, RewOnKillRepFaction2,"
5706 // 3 4 5 6 7 8 9
5707 "IsTeamAward1, MaxStanding1, RewOnKillRepValue1, IsTeamAward2, MaxStanding2, RewOnKillRepValue2, TeamDependent "
5708 "FROM creature_onkill_reputation");
5710 if(!result)
5712 barGoLink bar(1);
5714 bar.step();
5716 sLog.outString();
5717 sLog.outErrorDb(">> Loaded 0 creature award reputation definitions. DB table `creature_onkill_reputation` is empty.");
5718 return;
5721 barGoLink bar(result->GetRowCount());
5725 Field *fields = result->Fetch();
5726 bar.step();
5728 uint32 creature_id = fields[0].GetUInt32();
5730 ReputationOnKillEntry repOnKill;
5731 repOnKill.repfaction1 = fields[1].GetUInt32();
5732 repOnKill.repfaction2 = fields[2].GetUInt32();
5733 repOnKill.is_teamaward1 = fields[3].GetBool();
5734 repOnKill.reputation_max_cap1 = fields[4].GetUInt32();
5735 repOnKill.repvalue1 = fields[5].GetInt32();
5736 repOnKill.is_teamaward2 = fields[6].GetBool();
5737 repOnKill.reputation_max_cap2 = fields[7].GetUInt32();
5738 repOnKill.repvalue2 = fields[8].GetInt32();
5739 repOnKill.team_dependent = fields[9].GetUInt8();
5741 if(!GetCreatureTemplate(creature_id))
5743 sLog.outErrorDb("Table `creature_onkill_reputation` have data for not existed creature entry (%u), skipped",creature_id);
5744 continue;
5747 if(repOnKill.repfaction1)
5749 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(repOnKill.repfaction1);
5750 if(!factionEntry1)
5752 sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction1);
5753 continue;
5757 if(repOnKill.repfaction2)
5759 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(repOnKill.repfaction2);
5760 if(!factionEntry2)
5762 sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction2);
5763 continue;
5767 mRepOnKill[creature_id] = repOnKill;
5769 ++count;
5770 } while (result->NextRow());
5772 delete result;
5774 sLog.outString();
5775 sLog.outString(">> Loaded %u creature award reputation definitions", count);
5778 void ObjectMgr::LoadWeatherZoneChances()
5780 uint32 count = 0;
5782 // 0 1 2 3 4 5 6 7 8 9 10 11 12
5783 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");
5785 if(!result)
5787 barGoLink bar(1);
5789 bar.step();
5791 sLog.outString();
5792 sLog.outErrorDb(">> Loaded 0 weather definitions. DB table `game_weather` is empty.");
5793 return;
5796 barGoLink bar(result->GetRowCount());
5800 Field *fields = result->Fetch();
5801 bar.step();
5803 uint32 zone_id = fields[0].GetUInt32();
5805 WeatherZoneChances& wzc = mWeatherZoneMap[zone_id];
5807 for(int season = 0; season < WEATHER_SEASONS; ++season)
5809 wzc.data[season].rainChance = fields[season * (MAX_WEATHER_TYPE-1) + 1].GetUInt32();
5810 wzc.data[season].snowChance = fields[season * (MAX_WEATHER_TYPE-1) + 2].GetUInt32();
5811 wzc.data[season].stormChance = fields[season * (MAX_WEATHER_TYPE-1) + 3].GetUInt32();
5813 if(wzc.data[season].rainChance > 100)
5815 wzc.data[season].rainChance = 25;
5816 sLog.outErrorDb("Weather for zone %u season %u has wrong rain chance > 100%",zone_id,season);
5819 if(wzc.data[season].snowChance > 100)
5821 wzc.data[season].snowChance = 25;
5822 sLog.outErrorDb("Weather for zone %u season %u has wrong snow chance > 100%",zone_id,season);
5825 if(wzc.data[season].stormChance > 100)
5827 wzc.data[season].stormChance = 25;
5828 sLog.outErrorDb("Weather for zone %u season %u has wrong storm chance > 100%",zone_id,season);
5832 ++count;
5833 } while (result->NextRow());
5835 delete result;
5837 sLog.outString();
5838 sLog.outString(">> Loaded %u weather definitions", count);
5841 void ObjectMgr::SaveCreatureRespawnTime(uint32 loguid, uint32 instance, time_t t)
5843 mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
5844 WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
5845 if(t)
5846 WorldDatabase.PExecute("INSERT INTO creature_respawn VALUES ( '%u', '" I64FMTD "', '%u' )", loguid, uint64(t), instance);
5849 void ObjectMgr::DeleteCreatureData(uint32 guid)
5851 // remove mapid*cellid -> guid_set map
5852 CreatureData const* data = GetCreatureData(guid);
5853 if(data)
5854 RemoveCreatureFromGrid(guid, data);
5856 mCreatureDataMap.erase(guid);
5859 void ObjectMgr::SaveGORespawnTime(uint32 loguid, uint32 instance, time_t t)
5861 mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
5862 WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
5863 if(t)
5864 WorldDatabase.PExecute("INSERT INTO gameobject_respawn VALUES ( '%u', '" I64FMTD "', '%u' )", loguid, uint64(t), instance);
5867 void ObjectMgr::DeleteRespawnTimeForInstance(uint32 instance)
5869 RespawnTimes::iterator next;
5871 for(RespawnTimes::iterator itr = mGORespawnTimes.begin(); itr != mGORespawnTimes.end(); itr = next)
5873 next = itr;
5874 ++next;
5876 if(GUID_HIPART(itr->first)==instance)
5877 mGORespawnTimes.erase(itr);
5880 for(RespawnTimes::iterator itr = mCreatureRespawnTimes.begin(); itr != mCreatureRespawnTimes.end(); itr = next)
5882 next = itr;
5883 ++next;
5885 if(GUID_HIPART(itr->first)==instance)
5886 mCreatureRespawnTimes.erase(itr);
5889 WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE instance = '%u'", instance);
5890 WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE instance = '%u'", instance);
5893 void ObjectMgr::DeleteGOData(uint32 guid)
5895 // remove mapid*cellid -> guid_set map
5896 GameObjectData const* data = GetGOData(guid);
5897 if(data)
5898 RemoveGameobjectFromGrid(guid, data);
5900 mGameObjectDataMap.erase(guid);
5903 void ObjectMgr::AddCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid, uint32 instance)
5905 // corpses are always added to spawn mode 0 and they are spawned by their instance id
5906 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
5907 cell_guids.corpses[player_guid] = instance;
5910 void ObjectMgr::DeleteCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid)
5912 // corpses are always added to spawn mode 0 and they are spawned by their instance id
5913 CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
5914 cell_guids.corpses.erase(player_guid);
5917 void ObjectMgr::LoadQuestRelationsHelper(QuestRelations& map,char const* table)
5919 map.clear(); // need for reload case
5921 uint32 count = 0;
5923 QueryResult *result = WorldDatabase.PQuery("SELECT id,quest FROM %s",table);
5925 if(!result)
5927 barGoLink bar(1);
5929 bar.step();
5931 sLog.outString();
5932 sLog.outErrorDb(">> Loaded 0 quest relations from %s. DB table `%s` is empty.",table,table);
5933 return;
5936 barGoLink bar(result->GetRowCount());
5940 Field *fields = result->Fetch();
5941 bar.step();
5943 uint32 id = fields[0].GetUInt32();
5944 uint32 quest = fields[1].GetUInt32();
5946 if(mQuestTemplates.find(quest) == mQuestTemplates.end())
5948 sLog.outErrorDb("Table `%s: Quest %u listed for entry %u does not exist.",table,quest,id);
5949 continue;
5952 map.insert(QuestRelations::value_type(id,quest));
5954 ++count;
5955 } while (result->NextRow());
5957 delete result;
5959 sLog.outString();
5960 sLog.outString(">> Loaded %u quest relations from %s", count,table);
5963 void ObjectMgr::LoadGameobjectQuestRelations()
5965 LoadQuestRelationsHelper(mGOQuestRelations,"gameobject_questrelation");
5967 for(QuestRelations::iterator itr = mGOQuestRelations.begin(); itr != mGOQuestRelations.end(); ++itr)
5969 GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
5970 if(!goInfo)
5971 sLog.outErrorDb("Table `gameobject_questrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
5972 else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
5973 sLog.outErrorDb("Table `gameobject_questrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
5977 void ObjectMgr::LoadGameobjectInvolvedRelations()
5979 LoadQuestRelationsHelper(mGOQuestInvolvedRelations,"gameobject_involvedrelation");
5981 for(QuestRelations::iterator itr = mGOQuestInvolvedRelations.begin(); itr != mGOQuestInvolvedRelations.end(); ++itr)
5983 GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
5984 if(!goInfo)
5985 sLog.outErrorDb("Table `gameobject_involvedrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
5986 else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
5987 sLog.outErrorDb("Table `gameobject_involvedrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
5991 void ObjectMgr::LoadCreatureQuestRelations()
5993 LoadQuestRelationsHelper(mCreatureQuestRelations,"creature_questrelation");
5995 for(QuestRelations::iterator itr = mCreatureQuestRelations.begin(); itr != mCreatureQuestRelations.end(); ++itr)
5997 CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
5998 if(!cInfo)
5999 sLog.outErrorDb("Table `creature_questrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
6000 else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
6001 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);
6005 void ObjectMgr::LoadCreatureInvolvedRelations()
6007 LoadQuestRelationsHelper(mCreatureQuestInvolvedRelations,"creature_involvedrelation");
6009 for(QuestRelations::iterator itr = mCreatureQuestInvolvedRelations.begin(); itr != mCreatureQuestInvolvedRelations.end(); ++itr)
6011 CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
6012 if(!cInfo)
6013 sLog.outErrorDb("Table `creature_involvedrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
6014 else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
6015 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);
6019 void ObjectMgr::LoadReservedPlayersNames()
6021 m_ReservedNames.clear(); // need for reload case
6023 QueryResult *result = WorldDatabase.Query("SELECT name FROM reserved_name");
6025 uint32 count = 0;
6027 if( !result )
6029 barGoLink bar( 1 );
6030 bar.step();
6032 sLog.outString();
6033 sLog.outString( ">> Loaded %u reserved player names", count );
6034 return;
6037 barGoLink bar( result->GetRowCount() );
6039 Field* fields;
6042 bar.step();
6043 fields = result->Fetch();
6044 std::string name= fields[0].GetCppString();
6045 if(normalizePlayerName(name))
6047 m_ReservedNames.insert(name);
6048 ++count;
6050 } while ( result->NextRow() );
6052 delete result;
6054 sLog.outString();
6055 sLog.outString( ">> Loaded %u reserved player names", count );
6058 enum LanguageType
6060 LT_BASIC_LATIN = 0x0000,
6061 LT_EXTENDEN_LATIN = 0x0001,
6062 LT_CYRILLIC = 0x0002,
6063 LT_EAST_ASIA = 0x0004,
6064 LT_ANY = 0xFFFF
6067 static LanguageType GetRealmLanguageType(bool create)
6069 switch(sWorld.getConfig(CONFIG_REALM_ZONE))
6071 case REALM_ZONE_UNKNOWN: // any language
6072 case REALM_ZONE_DEVELOPMENT:
6073 case REALM_ZONE_TEST_SERVER:
6074 case REALM_ZONE_QA_SERVER:
6075 return LT_ANY;
6076 case REALM_ZONE_UNITED_STATES: // extended-Latin
6077 case REALM_ZONE_OCEANIC:
6078 case REALM_ZONE_LATIN_AMERICA:
6079 case REALM_ZONE_ENGLISH:
6080 case REALM_ZONE_GERMAN:
6081 case REALM_ZONE_FRENCH:
6082 case REALM_ZONE_SPANISH:
6083 return LT_EXTENDEN_LATIN;
6084 case REALM_ZONE_KOREA: // East-Asian
6085 case REALM_ZONE_TAIWAN:
6086 case REALM_ZONE_CHINA:
6087 return LT_EAST_ASIA;
6088 case REALM_ZONE_RUSSIAN: // Cyrillic
6089 return LT_CYRILLIC;
6090 default:
6091 return create ? LT_BASIC_LATIN : LT_ANY; // basic-Latin at create, any at login
6095 bool isValidString(std::wstring wstr, uint32 strictMask, bool numericOrSpace, bool create = false)
6097 if(strictMask==0) // any language, ignore realm
6099 if(isExtendedLatinString(wstr,numericOrSpace))
6100 return true;
6101 if(isCyrillicString(wstr,numericOrSpace))
6102 return true;
6103 if(isEastAsianString(wstr,numericOrSpace))
6104 return true;
6105 return false;
6108 if(strictMask & 0x2) // realm zone specific
6110 LanguageType lt = GetRealmLanguageType(create);
6111 if(lt & LT_EXTENDEN_LATIN)
6112 if(isExtendedLatinString(wstr,numericOrSpace))
6113 return true;
6114 if(lt & LT_CYRILLIC)
6115 if(isCyrillicString(wstr,numericOrSpace))
6116 return true;
6117 if(lt & LT_EAST_ASIA)
6118 if(isEastAsianString(wstr,numericOrSpace))
6119 return true;
6122 if(strictMask & 0x1) // basic Latin
6124 if(isBasicLatinString(wstr,numericOrSpace))
6125 return true;
6128 return false;
6131 bool ObjectMgr::IsValidName( std::string name, bool create )
6133 std::wstring wname;
6134 if(!Utf8toWStr(name,wname))
6135 return false;
6137 if(wname.size() < 1 || wname.size() > MAX_PLAYER_NAME)
6138 return false;
6140 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_PLAYER_NAMES);
6142 return isValidString(wname,strictMask,false,create);
6145 bool ObjectMgr::IsValidCharterName( std::string name )
6147 std::wstring wname;
6148 if(!Utf8toWStr(name,wname))
6149 return false;
6151 if(wname.size() < 1)
6152 return false;
6154 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_CHARTER_NAMES);
6156 return isValidString(wname,strictMask,true);
6159 bool ObjectMgr::IsValidPetName( std::string name )
6161 std::wstring wname;
6162 if(!Utf8toWStr(name,wname))
6163 return false;
6165 if(wname.size() < 1)
6166 return false;
6168 uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_PET_NAMES);
6170 return isValidString(wname,strictMask,false);
6173 int ObjectMgr::GetIndexForLocale( LocaleConstant loc )
6175 if(loc==LOCALE_enUS)
6176 return -1;
6178 for(size_t i=0;i < m_LocalForIndex.size(); ++i)
6179 if(m_LocalForIndex[i]==loc)
6180 return i;
6182 return -1;
6185 LocaleConstant ObjectMgr::GetLocaleForIndex(int i)
6187 if (i<0 || i>=m_LocalForIndex.size())
6188 return LOCALE_enUS;
6190 return m_LocalForIndex[i];
6193 int ObjectMgr::GetOrNewIndexForLocale( LocaleConstant loc )
6195 if(loc==LOCALE_enUS)
6196 return -1;
6198 for(size_t i=0;i < m_LocalForIndex.size(); ++i)
6199 if(m_LocalForIndex[i]==loc)
6200 return i;
6202 m_LocalForIndex.push_back(loc);
6203 return m_LocalForIndex.size()-1;
6206 AchievementCriteriaEntryList const& ObjectMgr::GetAchievementCriteriaByType(AchievementCriteriaTypes type)
6208 return m_AchievementCriteriasByType[type];
6211 void ObjectMgr::LoadAchievementCriteriaList()
6213 for (uint32 entryId = 0; entryId<sAchievementCriteriaStore.GetNumRows(); entryId++)
6215 AchievementCriteriaEntry const* criteria = sAchievementCriteriaStore.LookupEntry(entryId);
6216 if(!criteria)
6217 continue;
6219 m_AchievementCriteriasByType[criteria->requiredType].push_back(criteria);
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 > 0) // 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 > 0) // internal mangos 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 const char* ObjectMgr::GetAreaTriggerScriptName(uint32 id)
6510 AreaTriggerScriptMap::const_iterator i = mAreaTriggerScripts.find(id);
6511 if(i!= mAreaTriggerScripts.end())
6512 return i->second.c_str();
6513 return "";
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[0]==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_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_GENERIC: //only GENERIC(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(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(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 // Functions for scripting access
7225 const char* GetAreaTriggerScriptNameById(uint32 id)
7227 return objmgr.GetAreaTriggerScriptName(id);
7230 bool LoadMangosStrings(DatabaseType& db, char const* table,int32 start_value, int32 end_value)
7232 if(start_value >= 0 || start_value <= end_value) // start/end reversed for negative values
7234 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());
7235 start_value = -1;
7236 end_value = std::numeric_limits<int32>::min();
7239 // for scripting localized strings allowed use _only_ negative entries
7240 return objmgr.LoadMangosStrings(db,table,end_value,start_value);