root/trunk/src/game/ObjectMgr.cpp @ 9

Revision 6, 248.7 kB (checked in by yumileroy, 17 years ago)

[svn] * Added ACE for Linux and Windows (Thanks Derex for Linux part and partial Windows part)
* Updated to 6721 and 676
* Fixed TrinityScript? logo
* Version updated to 0.2.6721.676

Original author: Neo2003
Date: 2008-10-04 06:17:19-05:00

Line 
1/*
2 * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
3 *
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.
8 *
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.
13 *
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
17 */
18
19#include "Common.h"
20#include "Database/DatabaseEnv.h"
21#include "Database/SQLStorage.h"
22
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 "InstanceSaveMgr.h"
41#include "SpellAuras.h"
42#include "Util.h"
43
44INSTANTIATE_SINGLETON_1(ObjectMgr);
45
46ScriptMapMap sQuestEndScripts;
47ScriptMapMap sQuestStartScripts;
48ScriptMapMap sSpellScripts;
49ScriptMapMap sGameObjectScripts;
50ScriptMapMap sEventScripts;
51
52bool normalizePlayerName(std::string& name)
53{
54    if(name.empty())
55        return false;
56
57    wchar_t wstr_buf[MAX_INTERNAL_PLAYER_NAME+1];
58    size_t wstr_len = MAX_INTERNAL_PLAYER_NAME;
59
60    if(!Utf8toWStr(name,&wstr_buf[0],wstr_len))
61        return false;
62
63    wstr_buf[0] = wcharToUpper(wstr_buf[0]);
64    for(size_t i = 1; i < wstr_len; ++i)
65        wstr_buf[i] = wcharToLower(wstr_buf[i]);
66
67    if(!WStrToUtf8(wstr_buf,wstr_len,name))
68        return false;
69
70    return true;
71}
72
73ObjectMgr::ObjectMgr()
74{
75    m_hiCharGuid        = 1;
76    m_hiCreatureGuid    = 1;
77    m_hiPetGuid         = 1;
78    m_hiItemGuid        = 1;
79    m_hiGoGuid          = 1;
80    m_hiDoGuid          = 1;
81    m_hiCorpseGuid      = 1;
82
83    m_hiPetNumber       = 1;
84
85    mGuildBankTabPrice.resize(GUILD_BANK_MAX_TABS);
86    mGuildBankTabPrice[0] = 100;
87    mGuildBankTabPrice[1] = 250;
88    mGuildBankTabPrice[2] = 500;
89    mGuildBankTabPrice[3] = 1000;
90    mGuildBankTabPrice[4] = 2500;
91    mGuildBankTabPrice[5] = 5000;
92
93    // Only zero condition left, others will be added while loading DB tables
94    mConditions.resize(1);
95}
96
97ObjectMgr::~ObjectMgr()
98{
99    for( QuestMap::iterator i = mQuestTemplates.begin( ); i != mQuestTemplates.end( ); ++ i )
100    {
101        delete i->second;
102    }
103    mQuestTemplates.clear( );
104
105    for( GossipTextMap::iterator i = mGossipText.begin( ); i != mGossipText.end( ); ++ i )
106    {
107        delete i->second;
108    }
109    mGossipText.clear( );
110
111    mAreaTriggers.clear();
112
113    for(PetLevelInfoMap::iterator i = petInfo.begin( ); i != petInfo.end( ); ++ i )
114    {
115        delete[] i->second;
116    }
117    petInfo.clear();
118
119    // free only if loaded
120    for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
121        delete[] playerClassInfo[class_].levelInfo;
122
123    for (int race = 0; race < MAX_RACES; ++race)
124        for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
125            delete[] playerInfo[race][class_].levelInfo;
126
127    // free group and guild objects
128    for (GroupSet::iterator itr = mGroupSet.begin(); itr != mGroupSet.end(); ++itr)
129        delete (*itr);
130    for (GuildSet::iterator itr = mGuildSet.begin(); itr != mGuildSet.end(); ++itr)
131        delete (*itr);
132
133    for(ItemMap::iterator itr = mAitems.begin(); itr != mAitems.end(); ++itr)
134        delete itr->second;
135
136    for (CacheVendorItemMap::iterator itr = m_mCacheVendorItemMap.begin(); itr != m_mCacheVendorItemMap.end(); ++itr)
137        for (VendorItemList::iterator itr2 = itr->second.begin(); itr2 != itr->second.end(); ++itr2)
138            delete (*itr2);
139
140    for (CacheTrainerSpellMap::iterator itr = m_mCacheTrainerSpellMap.begin(); itr != m_mCacheTrainerSpellMap.end(); ++itr)
141        itr->second.Clear();
142}
143
144Group * ObjectMgr::GetGroupByLeader(const uint64 &guid) const
145{
146    for(GroupSet::const_iterator itr = mGroupSet.begin(); itr != mGroupSet.end(); ++itr)
147        if ((*itr)->GetLeaderGUID() == guid)
148            return *itr;
149
150    return NULL;
151}
152
153Guild * ObjectMgr::GetGuildById(const uint32 GuildId) const
154{
155    for(GuildSet::const_iterator itr = mGuildSet.begin(); itr != mGuildSet.end(); itr++)
156        if ((*itr)->GetId() == GuildId)
157            return *itr;
158
159    return NULL;
160}
161
162Guild * ObjectMgr::GetGuildByName(std::string guildname) const
163{
164    for(GuildSet::const_iterator itr = mGuildSet.begin(); itr != mGuildSet.end(); itr++)
165        if ((*itr)->GetName() == guildname)
166            return *itr;
167
168    return NULL;
169}
170
171std::string ObjectMgr::GetGuildNameById(const uint32 GuildId) const
172{
173    for(GuildSet::const_iterator itr = mGuildSet.begin(); itr != mGuildSet.end(); itr++)
174        if ((*itr)->GetId() == GuildId)
175            return (*itr)->GetName();
176
177    return "";
178}
179
180Guild* ObjectMgr::GetGuildByLeader(const uint64 &guid) const
181{
182    for(GuildSet::const_iterator itr = mGuildSet.begin(); itr != mGuildSet.end(); ++itr)
183        if( (*itr)->GetLeader() == guid)
184            return *itr;
185
186    return NULL;
187}
188
189ArenaTeam* ObjectMgr::GetArenaTeamById(const uint32 ArenaTeamId) const
190{
191    for(ArenaTeamSet::const_iterator itr = mArenaTeamSet.begin(); itr != mArenaTeamSet.end(); itr++)
192        if ((*itr)->GetId() == ArenaTeamId)
193            return *itr;
194
195    return NULL;
196}
197
198ArenaTeam* ObjectMgr::GetArenaTeamByName(std::string arenateamname) const
199{
200    for(ArenaTeamSet::const_iterator itr = mArenaTeamSet.begin(); itr != mArenaTeamSet.end(); itr++)
201        if ((*itr)->GetName() == arenateamname)
202            return *itr;
203
204    return NULL;
205}
206
207ArenaTeam* ObjectMgr::GetArenaTeamByCapitan(uint64 const& guid) const
208{
209    for(ArenaTeamSet::const_iterator itr = mArenaTeamSet.begin(); itr != mArenaTeamSet.end(); itr++)
210        if ((*itr)->GetCaptain() == guid)
211            return *itr;
212
213    return NULL;
214}
215
216AuctionHouseObject * ObjectMgr::GetAuctionsMap( uint32 location )
217{
218    switch ( location )
219    {
220        case 6:                                             //horde
221            return & mHordeAuctions;
222            break;
223        case 2:                                             //alliance
224            return & mAllianceAuctions;
225            break;
226        default:                                            //neutral
227            return & mNeutralAuctions;
228    }
229}
230
231uint32 ObjectMgr::GetAuctionCut(uint32 location, uint32 highBid)
232{
233    if (location == 7 && !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_AUCTION))
234        return (uint32) (0.15f * highBid * sWorld.getRate(RATE_AUCTION_CUT));
235    else
236        return (uint32) (0.05f * highBid * sWorld.getRate(RATE_AUCTION_CUT));
237}
238
239uint32 ObjectMgr::GetAuctionDeposit(uint32 location, uint32 time, Item *pItem)
240{
241    float percentance;                                      // in 0..1
242    if ( location == 7 && !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_AUCTION))
243        percentance = 0.75f;
244    else
245        percentance = 0.15f;
246
247    percentance *= sWorld.getRate(RATE_AUCTION_DEPOSIT);
248
249    return uint32( percentance * pItem->GetProto()->SellPrice * pItem->GetCount() * (time / MIN_AUCTION_TIME ) );
250}
251
252/// the sum of outbid is (1% from current bid)*5, if bid is very small, it is 1c
253uint32 ObjectMgr::GetAuctionOutBid(uint32 currentBid)
254{
255    uint32 outbid = (currentBid / 100) * 5;
256    if (!outbid)
257        outbid = 1;
258    return outbid;
259}
260
261//does not clear ram
262void ObjectMgr::SendAuctionWonMail( AuctionEntry *auction )
263{
264    Item *pItem = GetAItem(auction->item_guidlow);
265    if(!pItem)
266        return;
267
268    uint64 bidder_guid = MAKE_NEW_GUID(auction->bidder, 0, HIGHGUID_PLAYER);
269    Player *bidder = GetPlayer(bidder_guid);
270
271    uint32 bidder_accId = 0;
272
273    // data for gm.log
274    if( sWorld.getConfig(CONFIG_GM_LOG_TRADE) )
275    {
276        uint32 bidder_security = 0;
277        std::string bidder_name;
278        if (bidder)
279        {
280            bidder_accId = bidder->GetSession()->GetAccountId();
281            bidder_security = bidder->GetSession()->GetSecurity();
282            bidder_name = bidder->GetName();
283        }
284        else
285        {
286            bidder_accId = GetPlayerAccountIdByGUID(bidder_guid);
287            bidder_security = GetSecurityByAccount(bidder_accId);
288
289            if(bidder_security > SEC_PLAYER )               // not do redundant DB requests
290            {
291                if(!GetPlayerNameByGUID(bidder_guid,bidder_name))
292                    bidder_name = GetMangosStringForDBCLocale(LANG_UNKNOWN);
293            }
294        }
295
296        if( bidder_security > SEC_PLAYER )
297        {
298            std::string owner_name;
299            if(!GetPlayerNameByGUID(auction->owner,owner_name))
300                owner_name = GetMangosStringForDBCLocale(LANG_UNKNOWN);
301
302            uint32 owner_accid = GetPlayerAccountIdByGUID(auction->owner);
303
304            sLog.outCommand("GM %s (Account: %u) won item in auction: %s (Entry: %u Count: %u) and pay money: %u. Original owner %s (Account: %u)",
305                bidder_name.c_str(),bidder_accId,pItem->GetProto()->Name1,pItem->GetEntry(),pItem->GetCount(),auction->bid,owner_name.c_str(),owner_accid);
306        }
307    }
308    else if(!bidder)
309        bidder_accId = GetPlayerAccountIdByGUID(bidder_guid);
310
311    // receiver exist
312    if(bidder || bidder_accId)
313    {
314        std::ostringstream msgAuctionWonSubject;
315        msgAuctionWonSubject << auction->item_template << ":0:" << AUCTION_WON;
316
317        std::ostringstream msgAuctionWonBody;
318        msgAuctionWonBody.width(16);
319        msgAuctionWonBody << std::right << std::hex << auction->owner;
320        msgAuctionWonBody << std::dec << ":" << auction->bid << ":" << auction->buyout;
321        sLog.outDebug( "AuctionWon body string : %s", msgAuctionWonBody.str().c_str() );
322
323        //prepare mail data... :
324        uint32 itemTextId = this->CreateItemText( msgAuctionWonBody.str() );
325
326        // set owner to bidder (to prevent delete item with sender char deleting)
327        // owner in `data` will set at mail receive and item extracting
328        CharacterDatabase.PExecute("UPDATE item_instance SET owner_guid = '%u' WHERE guid='%u'",auction->bidder,pItem->GetGUIDLow());
329        CharacterDatabase.CommitTransaction();
330
331        MailItemsInfo mi;
332        mi.AddItem(auction->item_guidlow, auction->item_template, pItem);
333
334        if (bidder)
335            bidder->GetSession()->SendAuctionBidderNotification( auction->location, auction->Id, bidder_guid, 0, 0, auction->item_template);
336        else
337            RemoveAItem(pItem->GetGUIDLow());               // we have to remove the item, before we delete it !!
338
339        // will delete item or place to receiver mail list
340        WorldSession::SendMailTo(bidder, MAIL_AUCTION, MAIL_STATIONERY_AUCTION, auction->location, auction->bidder, msgAuctionWonSubject.str(), itemTextId, &mi, 0, 0, MAIL_CHECK_MASK_AUCTION);
341    }
342    // receiver not exist
343    else
344    {
345        CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid='%u'", pItem->GetGUIDLow());
346        RemoveAItem(pItem->GetGUIDLow());                   // we have to remove the item, before we delete it !!
347        delete pItem;
348    }
349}
350
351void ObjectMgr::SendAuctionSalePendingMail( AuctionEntry * auction )
352{
353    uint64 owner_guid = MAKE_NEW_GUID(auction->owner, 0, HIGHGUID_PLAYER);
354    Player *owner = GetPlayer(owner_guid);
355
356    // owner exist (online or offline)
357    if(owner || GetPlayerAccountIdByGUID(owner_guid))
358    {
359        std::ostringstream msgAuctionSalePendingSubject;
360        msgAuctionSalePendingSubject << auction->item_template << ":0:" << AUCTION_SALE_PENDING;
361
362        std::ostringstream msgAuctionSalePendingBody;
363        uint32 auctionCut = GetAuctionCut(auction->location, auction->bid);
364
365        time_t distrTime = time(NULL) + HOUR;
366
367        msgAuctionSalePendingBody.width(16);
368        msgAuctionSalePendingBody << std::right << std::hex << auction->bidder;
369        msgAuctionSalePendingBody << std::dec << ":" << auction->bid << ":" << auction->buyout;
370        msgAuctionSalePendingBody << ":" << auction->deposit << ":" << auctionCut << ":0:";
371        msgAuctionSalePendingBody << secsToTimeBitFields(distrTime);
372
373        sLog.outDebug("AuctionSalePending body string : %s", msgAuctionSalePendingBody.str().c_str());
374
375        uint32 itemTextId = this->CreateItemText( msgAuctionSalePendingBody.str() );
376
377        WorldSession::SendMailTo(owner, MAIL_AUCTION, MAIL_STATIONERY_AUCTION, auction->location, auction->owner, msgAuctionSalePendingSubject.str(), itemTextId, NULL, 0, 0, MAIL_CHECK_MASK_AUCTION);
378    }
379}
380
381//call this method to send mail to auction owner, when auction is successful, it does not clear ram
382void ObjectMgr::SendAuctionSuccessfulMail( AuctionEntry * auction )
383{
384    uint64 owner_guid = MAKE_NEW_GUID(auction->owner, 0, HIGHGUID_PLAYER);
385    Player *owner = GetPlayer(owner_guid);
386
387    uint32 owner_accId = 0;
388    if(!owner)
389        owner_accId = GetPlayerAccountIdByGUID(owner_guid);
390
391    // owner exist
392    if(owner || owner_accId)
393    {
394        std::ostringstream msgAuctionSuccessfulSubject;
395        msgAuctionSuccessfulSubject << auction->item_template << ":0:" << AUCTION_SUCCESSFUL;
396
397        std::ostringstream auctionSuccessfulBody;
398        uint32 auctionCut = GetAuctionCut(auction->location, auction->bid);
399
400        auctionSuccessfulBody.width(16);
401        auctionSuccessfulBody << std::right << std::hex << auction->bidder;
402        auctionSuccessfulBody << std::dec << ":" << auction->bid << ":" << auction->buyout;
403        auctionSuccessfulBody << ":" << auction->deposit << ":" << auctionCut;
404
405        sLog.outDebug("AuctionSuccessful body string : %s", auctionSuccessfulBody.str().c_str());
406
407        uint32 itemTextId = this->CreateItemText( auctionSuccessfulBody.str() );
408
409        uint32 profit = auction->bid + auction->deposit - auctionCut;
410
411        if (owner)
412        {
413            //send auction owner notification, bidder must be current!
414            owner->GetSession()->SendAuctionOwnerNotification( auction );
415        }
416
417        WorldSession::SendMailTo(owner, MAIL_AUCTION, MAIL_STATIONERY_AUCTION, auction->location, auction->owner, msgAuctionSuccessfulSubject.str(), itemTextId, NULL, profit, 0, MAIL_CHECK_MASK_AUCTION, HOUR);
418    }
419}
420
421//does not clear ram
422void ObjectMgr::SendAuctionExpiredMail( AuctionEntry * auction )
423{                                                           //return an item in auction to its owner by mail
424    Item *pItem = GetAItem(auction->item_guidlow);
425    if(!pItem)
426    {
427        sLog.outError("Auction item (GUID: %u) not found, and lost.",auction->item_guidlow);
428        return;
429    }
430
431    uint64 owner_guid = MAKE_NEW_GUID(auction->owner, 0, HIGHGUID_PLAYER);
432    Player *owner = GetPlayer(owner_guid);
433
434    uint32 owner_accId = 0;
435    if(!owner)
436        owner_accId = GetPlayerAccountIdByGUID(owner_guid);
437
438    // owner exist
439    if(owner || owner_accId)
440    {
441        std::ostringstream subject;
442        subject << auction->item_template << ":0:" << AUCTION_EXPIRED;
443
444        if ( owner )
445            owner->GetSession()->SendAuctionOwnerNotification( auction );
446        else
447            RemoveAItem(pItem->GetGUIDLow());               // we have to remove the item, before we delete it !!
448
449        MailItemsInfo mi;
450        mi.AddItem(auction->item_guidlow, auction->item_template, pItem);
451
452        // will delete item or place to receiver mail list
453        WorldSession::SendMailTo(owner, MAIL_AUCTION, MAIL_STATIONERY_AUCTION, auction->location, GUID_LOPART(owner_guid), subject.str(), 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
454
455    }
456    // owner not found
457    else
458    {
459        CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid='%u'",pItem->GetGUIDLow());
460        RemoveAItem(pItem->GetGUIDLow());                   // we have to remove the item, before we delete it !!
461        delete pItem;
462    }
463}
464
465CreatureInfo const* ObjectMgr::GetCreatureTemplate(uint32 id)
466{
467    return sCreatureStorage.LookupEntry<CreatureInfo>(id);
468}
469
470void ObjectMgr::LoadCreatureLocales()
471{
472    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");
473
474    if(!result)
475    {
476        barGoLink bar(1);
477
478        bar.step();
479
480        sLog.outString("");
481        sLog.outString(">> Loaded 0 creature locale strings. DB table `locales_creature` is empty.");
482        return;
483    }
484
485    barGoLink bar(result->GetRowCount());
486
487    do
488    {
489        Field *fields = result->Fetch();
490        bar.step();
491
492        uint32 entry = fields[0].GetUInt32();
493
494        CreatureLocale& data = mCreatureLocaleMap[entry];
495
496        for(int i = 1; i < MAX_LOCALE; ++i)
497        {
498            std::string str = fields[1+2*(i-1)].GetCppString();
499            if(!str.empty())
500            {
501                int idx = GetOrNewIndexForLocale(LocaleConstant(i));
502                if(idx >= 0)
503                {
504                    if(data.Name.size() <= idx)
505                        data.Name.resize(idx+1);
506
507                    data.Name[idx] = str;
508                }
509            }
510            str = fields[1+2*(i-1)+1].GetCppString();
511            if(!str.empty())
512            {
513                int idx = GetOrNewIndexForLocale(LocaleConstant(i));
514                if(idx >= 0)
515                {
516                    if(data.SubName.size() <= idx)
517                        data.SubName.resize(idx+1);
518
519                    data.SubName[idx] = str;
520                }
521            }
522        }
523    } while (result->NextRow());
524
525    delete result;
526
527    sLog.outString();
528    sLog.outString( ">> Loaded %u creature locale strings", mCreatureLocaleMap.size() );
529}
530
531void ObjectMgr::LoadCreatureTemplates()
532{
533    sCreatureStorage.Load();
534
535    sLog.outString( ">> Loaded %u creature definitions", sCreatureStorage.RecordCount );
536    sLog.outString();
537
538    std::set<uint32> heroicEntries;                         // already loaded heroic value in creatures
539    std::set<uint32> hasHeroicEntries;                      // already loaded creatures with heroic entry values
540
541    // check data correctness
542    for(uint32 i = 1; i < sCreatureStorage.MaxEntry; ++i)
543    {
544        CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i);
545        if(!cInfo)
546            continue;
547
548        if(cInfo->HeroicEntry)
549        {
550            CreatureInfo const* heroicInfo = GetCreatureTemplate(cInfo->HeroicEntry);
551            if(!heroicInfo)
552            {
553                sLog.outErrorDb("Creature (Entry: %u) have `heroic_entry`=%u but creature entry %u not exist.",cInfo->HeroicEntry,cInfo->HeroicEntry);
554                continue;
555            }
556
557            if(heroicEntries.find(i)!=heroicEntries.end())
558            {
559                sLog.outErrorDb("Creature (Entry: %u) listed as heroic but have value in `heroic_entry`.",i);
560                continue;
561            }
562
563            if(heroicEntries.find(cInfo->HeroicEntry)!=heroicEntries.end())
564            {
565                sLog.outErrorDb("Creature (Entry: %u) already listed as heroic for another entry.",cInfo->HeroicEntry);
566                continue;
567            }
568
569            if(hasHeroicEntries.find(cInfo->HeroicEntry)!=hasHeroicEntries.end())
570            {
571                sLog.outErrorDb("Creature (Entry: %u) have `heroic_entry`=%u but creature entry %u have heroic entry also.",i,cInfo->HeroicEntry,cInfo->HeroicEntry);
572                continue;
573            }
574
575            if(cInfo->npcflag != heroicInfo->npcflag)
576            {
577                sLog.outErrorDb("Creature (Entry: %u) listed in `creature_template_substitution` has different `npcflag` in heroic mode.",i);
578                continue;
579            }
580
581            if(cInfo->classNum != heroicInfo->classNum)
582            {
583                sLog.outErrorDb("Creature (Entry: %u) listed in `creature_template_substitution` has different `classNum` in heroic mode.",i);
584                continue;
585            }
586
587            if(cInfo->race != heroicInfo->race)
588            {
589                sLog.outErrorDb("Creature (Entry: %u) listed in `creature_template_substitution` has different `race` in heroic mode.",i);
590                continue;
591            }
592
593            if(cInfo->trainer_type != heroicInfo->trainer_type)
594            {
595                sLog.outErrorDb("Creature (Entry: %u) listed in `creature_template_substitution` has different `trainer_type` in heroic mode.",i);
596                continue;
597            }
598
599            if(cInfo->trainer_spell != heroicInfo->trainer_spell)
600            {
601                sLog.outErrorDb("Creature (Entry: %u) listed in `creature_template_substitution` has different `trainer_spell` in heroic mode.",i);
602                continue;
603            }
604
605            hasHeroicEntries.insert(i);
606            heroicEntries.insert(cInfo->HeroicEntry);
607        }
608
609        FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction_A);
610        if(!factionTemplate)
611            sLog.outErrorDb("Creature (Entry: %u) has non-existing faction_A template (%u)", cInfo->Entry, cInfo->faction_A);
612
613        factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction_H);
614        if(!factionTemplate)
615            sLog.outErrorDb("Creature (Entry: %u) has non-existing faction_H template (%u)", cInfo->Entry, cInfo->faction_H);
616
617        CreatureModelInfo const* minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_A);
618        if (!minfo)
619            sLog.outErrorDb("Creature (Entry: %u) has non-existing modelId_A (%u)", cInfo->Entry, cInfo->DisplayID_A);
620        minfo = sCreatureModelStorage.LookupEntry<CreatureModelInfo>(cInfo->DisplayID_H);
621        if (!minfo)
622            sLog.outErrorDb("Creature (Entry: %u) has non-existing modelId_H (%u)", cInfo->Entry, cInfo->DisplayID_H);
623
624        if(cInfo->dmgschool >= MAX_SPELL_SCHOOL)
625        {
626            sLog.outErrorDb("Creature (Entry: %u) has invalid spell school value (%u) in `dmgschool`",cInfo->Entry,cInfo->dmgschool);
627            const_cast<CreatureInfo*>(cInfo)->dmgschool = SPELL_SCHOOL_NORMAL;
628        }
629
630        if(cInfo->baseattacktime == 0)
631            const_cast<CreatureInfo*>(cInfo)->baseattacktime  = BASE_ATTACK_TIME;
632
633        if(cInfo->rangeattacktime == 0)
634            const_cast<CreatureInfo*>(cInfo)->rangeattacktime = BASE_ATTACK_TIME;
635
636        if((cInfo->npcflag & UNIT_NPC_FLAG_TRAINER) && cInfo->trainer_type >= MAX_TRAINER_TYPE)
637            sLog.outErrorDb("Creature (Entry: %u) has wrong trainer type %u",cInfo->Entry,cInfo->trainer_type);
638
639        if(cInfo->InhabitType <= 0 || cInfo->InhabitType > INHABIT_ANYWHERE)
640        {
641            sLog.outErrorDb("Creature (Entry: %u) has wrong value (%u) in `InhabitType`, creature will not correctly walk/swim/fly",cInfo->Entry,cInfo->InhabitType);
642            const_cast<CreatureInfo*>(cInfo)->InhabitType = INHABIT_ANYWHERE;
643        }
644
645        if(cInfo->PetSpellDataId)
646        {
647            CreatureSpellDataEntry const* spellDataId = sCreatureSpellDataStore.LookupEntry(cInfo->PetSpellDataId);
648            if(!spellDataId)
649                sLog.outErrorDb("Creature (Entry: %u) has non-existing PetSpellDataId (%u)", cInfo->Entry, cInfo->PetSpellDataId);
650        }
651
652        if(cInfo->MovementType >= MAX_DB_MOTION_TYPE)
653        {
654            sLog.outErrorDb("Creature (Entry: %u) has wrong movement generator type (%u), ignore and set to IDLE.",cInfo->Entry,cInfo->MovementType);
655            const_cast<CreatureInfo*>(cInfo)->MovementType = IDLE_MOTION_TYPE;
656        }
657
658        if(cInfo->equipmentId > 0)                          // 0 no equipment
659        {
660            if(!GetEquipmentInfo(cInfo->equipmentId))
661            {
662                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);
663                const_cast<CreatureInfo*>(cInfo)->equipmentId = 0;
664            }
665        }
666
667        /// if not set custom creature scale then load scale from CreatureDisplayInfo.dbc
668        if(cInfo->scale <= 0.0f)
669        {
670            CreatureDisplayInfoEntry const* ScaleEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->DisplayID_A);
671            const_cast<CreatureInfo*>(cInfo)->scale = ScaleEntry ? ScaleEntry->scale : 1.0f;
672        }
673    }
674}
675
676void ObjectMgr::ConvertCreatureAddonAuras(CreatureDataAddon* addon, char const* table, char const* guidEntryStr)
677{
678    // Now add the auras, format "spellid effectindex spellid effectindex..."
679    char *p,*s;
680    std::vector<int> val;
681    s=p=(char*)reinterpret_cast<char const*>(addon->auras);
682    if(p)
683    {
684        while (p[0]!=0)
685        {
686            ++p;
687            if (p[0]==' ')
688            {
689                val.push_back(atoi(s));
690                s=++p;
691            }
692        }
693        if (p!=s)
694            val.push_back(atoi(s));
695
696        // free char* loaded memory
697        delete[] (char*)reinterpret_cast<char const*>(addon->auras);
698
699        // wrong list
700        if (val.size()%2)
701        {
702            addon->auras = NULL;
703            sLog.outErrorDb("Creature (%s: %u) has wrong `auras` data in `%s`.",guidEntryStr,addon->guidOrEntry,table);
704            return;
705        }
706    }
707
708    // empty list
709    if(val.empty())
710    {
711        addon->auras = NULL;
712        return;
713    }
714
715    // replace by new strucutres array
716    const_cast<CreatureDataAddonAura*&>(addon->auras) = new CreatureDataAddonAura[val.size()/2+1];
717
718    int i=0;
719    for(int j=0;j<val.size()/2;++j)
720    {
721        CreatureDataAddonAura& cAura = const_cast<CreatureDataAddonAura&>(addon->auras[i]);
722        cAura.spell_id = (uint32)val[2*j+0];
723        cAura.effect_idx  = (uint32)val[2*j+1];
724        if ( cAura.effect_idx > 2 )
725        {
726            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);
727            continue;
728        }
729        SpellEntry const *AdditionalSpellInfo = sSpellStore.LookupEntry(cAura.spell_id);
730        if (!AdditionalSpellInfo)
731        {
732            sLog.outErrorDb("Creature (%s: %u) has wrong spell %u defined in `auras` field in `%s`.",guidEntryStr,addon->guidOrEntry,cAura.spell_id,table);
733            continue;
734        }
735
736        if (!AdditionalSpellInfo->Effect[cAura.effect_idx] || !AdditionalSpellInfo->EffectApplyAuraName[cAura.effect_idx])
737        {
738            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);
739            continue;
740        }
741
742        ++i;
743    }
744
745    // fill terminator element (after last added)
746    CreatureDataAddonAura& endAura = const_cast<CreatureDataAddonAura&>(addon->auras[i]);
747    endAura.spell_id   = 0;
748    endAura.effect_idx = 0;
749}
750
751void ObjectMgr::LoadCreatureAddons()
752{
753    sCreatureInfoAddonStorage.Load();
754
755    sLog.outString( ">> Loaded %u creature template addons", sCreatureInfoAddonStorage.RecordCount );
756    sLog.outString();
757
758    // check data correctness and convert 'auras'
759    for(uint32 i = 1; i < sCreatureInfoAddonStorage.MaxEntry; ++i)
760    {
761        CreatureDataAddon const* addon = sCreatureInfoAddonStorage.LookupEntry<CreatureDataAddon>(i);
762        if(!addon)
763            continue;
764
765        ConvertCreatureAddonAuras(const_cast<CreatureDataAddon*>(addon), "creature_template_addon", "Entry");
766
767        if(!sCreatureStorage.LookupEntry<CreatureInfo>(addon->guidOrEntry))
768            sLog.outErrorDb("Creature (Entry: %u) does not exist but has a record in `creature_template_addon`",addon->guidOrEntry);
769    }
770
771    sCreatureDataAddonStorage.Load();
772
773    sLog.outString( ">> Loaded %u creature addons", sCreatureDataAddonStorage.RecordCount );
774    sLog.outString();
775
776    // check data correctness and convert 'auras'
777    for(uint32 i = 1; i < sCreatureDataAddonStorage.MaxEntry; ++i)
778    {
779        CreatureDataAddon const* addon = sCreatureDataAddonStorage.LookupEntry<CreatureDataAddon>(i);
780        if(!addon)
781            continue;
782
783        ConvertCreatureAddonAuras(const_cast<CreatureDataAddon*>(addon), "creature_addon", "GUIDLow");
784
785        if(mCreatureDataMap.find(addon->guidOrEntry)==mCreatureDataMap.end())
786            sLog.outErrorDb("Creature (GUID: %u) does not exist but has a record in `creature_addon`",addon->guidOrEntry);
787    }
788}
789
790EquipmentInfo const* ObjectMgr::GetEquipmentInfo(uint32 entry)
791{
792    return sEquipmentStorage.LookupEntry<EquipmentInfo>(entry);
793}
794
795void ObjectMgr::LoadEquipmentTemplates()
796{
797    sEquipmentStorage.Load();
798
799    sLog.outString( ">> Loaded %u equipment template", sEquipmentStorage.RecordCount );
800    sLog.outString();
801}
802
803CreatureModelInfo const* ObjectMgr::GetCreatureModelInfo(uint32 modelid)
804{
805    return sCreatureModelStorage.LookupEntry<CreatureModelInfo>(modelid);
806}
807
808uint32 ObjectMgr::ChooseDisplayId(uint32 team, const CreatureInfo *cinfo, const CreatureData *data)
809{
810    // Load creature model (display id)
811    uint32 display_id;
812    if (!data || data->displayid == 0)                      // use defaults from the template
813    {
814        // DisplayID_A is used if no team is given
815        if (team == HORDE)
816            display_id = (cinfo->DisplayID_H2 != 0 && urand(0,1) == 0) ? cinfo->DisplayID_H2 : cinfo->DisplayID_H;
817        else
818            display_id = (cinfo->DisplayID_A2 != 0 && urand(0,1) == 0) ? cinfo->DisplayID_A2 : cinfo->DisplayID_A;
819    }
820    else                                                    // overriden in creature data
821        display_id = data->displayid;
822
823    return display_id;
824}
825
826CreatureModelInfo const* ObjectMgr::GetCreatureModelRandomGender(uint32 display_id)
827{
828    CreatureModelInfo const *minfo = GetCreatureModelInfo(display_id);
829    if(!minfo)
830        return NULL;
831
832    // If a model for another gender exists, 50% chance to use it
833    if(minfo->modelid_other_gender != 0 && urand(0,1) == 0)
834    {
835        CreatureModelInfo const *minfo_tmp = GetCreatureModelInfo(minfo->modelid_other_gender);
836        if(!minfo_tmp)
837        {
838            sLog.outErrorDb("Model (Entry: %u) has modelid_other_gender %u not found in table `creature_model_info`. ", minfo->modelid, minfo->modelid_other_gender);
839            return minfo;                                   // not fatal, just use the previous one
840        }
841        else
842            return minfo_tmp;
843    }
844    else
845        return minfo;
846}
847
848void ObjectMgr::LoadCreatureModelInfo()
849{
850    sCreatureModelStorage.Load();
851
852    sLog.outString( ">> Loaded %u creature model based info", sCreatureModelStorage.RecordCount );
853    sLog.outString();
854}
855
856void ObjectMgr::LoadCreatures()
857{
858    uint32 count = 0;
859    //                                                0              1   2    3
860    QueryResult *result = WorldDatabase.Query("SELECT creature.guid, id, map, modelid,"
861    //   4             5           6           7           8            9              10         11
862        "equipment_id, position_x, position_y, position_z, orientation, spawntimesecs, spawndist, currentwaypoint,"
863    //   12         13       14          15            16         17
864        "curhealth, curmana, DeathState, MovementType, spawnMask, event "
865        "FROM creature LEFT OUTER JOIN game_event_creature ON creature.guid = game_event_creature.guid");
866
867    if(!result)
868    {
869        barGoLink bar(1);
870
871        bar.step();
872
873        sLog.outString("");
874        sLog.outErrorDb(">> Loaded 0 creature. DB table `creature` is empty.");
875        return;
876    }
877
878    // build single time for check creature data
879    std::set<uint32> heroicCreatures;
880    for(uint32 i = 0; i < sCreatureStorage.MaxEntry; ++i)
881        if(CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i))
882            if(cInfo->HeroicEntry)
883                heroicCreatures.insert(cInfo->HeroicEntry);
884
885    barGoLink bar(result->GetRowCount());
886
887    do
888    {
889        Field *fields = result->Fetch();
890        bar.step();
891
892        uint32 guid = fields[0].GetUInt32();
893
894        CreatureData& data = mCreatureDataMap[guid];
895
896        data.id             = fields[ 1].GetUInt32();
897        data.mapid          = fields[ 2].GetUInt32();
898        data.displayid      = fields[ 3].GetUInt32();
899        data.equipmentId    = fields[ 4].GetUInt32();
900        data.posX           = fields[ 5].GetFloat();
901        data.posY           = fields[ 6].GetFloat();
902        data.posZ           = fields[ 7].GetFloat();
903        data.orientation    = fields[ 8].GetFloat();
904        data.spawntimesecs  = fields[ 9].GetUInt32();
905        data.spawndist      = fields[10].GetFloat();
906        data.currentwaypoint= fields[11].GetUInt32();
907        data.curhealth      = fields[12].GetUInt32();
908        data.curmana        = fields[13].GetUInt32();
909        data.is_dead        = fields[14].GetBool();
910        data.movementType   = fields[15].GetUInt8();
911        data.spawnMask      = fields[16].GetUInt8();
912        int16 gameEvent     = fields[17].GetInt16();
913
914        CreatureInfo const* cInfo = GetCreatureTemplate(data.id);
915        if(!cInfo)
916        {
917            sLog.outErrorDb("Table `creature` have creature (GUID: %u) with not existed creature entry %u, skipped.",guid,data.id );
918            continue;
919        }
920
921        if(heroicCreatures.find(data.id)!=heroicCreatures.end())
922        {
923            sLog.outErrorDb("Table `creature` have creature (GUID: %u) that listed as heroic template in `creature_template_substitution`, skipped.",guid,data.id );
924            continue;
925        }
926
927        if(data.equipmentId > 0)                            // -1 no equipment, 0 use default
928        {
929            if(!GetEquipmentInfo(data.equipmentId))
930            {
931                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);
932                data.equipmentId = -1;
933            }
934        }
935
936        if(cInfo->RegenHealth && data.curhealth < cInfo->minhealth)
937        {
938            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 );
939            data.curhealth = cInfo->minhealth;
940        }
941
942        if(data.curmana < cInfo->minmana)
943        {
944            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 );
945            data.curmana = cInfo->minmana;
946        }
947
948        if(data.spawndist < 0.0f)
949        {
950            sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `spawndist`< 0, set to 0.",guid,data.id );
951            data.spawndist = 0.0f;
952        }
953        else if(data.movementType == RANDOM_MOTION_TYPE)
954        {
955            if(data.spawndist == 0.0f)
956            {
957                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 );
958                data.movementType = IDLE_MOTION_TYPE;
959            }
960        }
961        else if(data.movementType == IDLE_MOTION_TYPE)
962        {
963            if(data.spawndist != 0.0f)
964            {
965                sLog.outErrorDb("Table `creature` have creature (GUID: %u Entry: %u) with `MovementType`=0 (idle) have `spawndist`<>0, set to 0.",guid,data.id );
966                data.spawndist = 0.0f;
967            }
968        }
969
970        if (gameEvent==0)                                   // if not this is to be managed by GameEvent System
971            AddCreatureToGrid(guid, &data);
972        ++count;
973
974    } while (result->NextRow());
975
976    delete result;
977
978    sLog.outString();
979    sLog.outString( ">> Loaded %u creatures", mCreatureDataMap.size() );
980}
981
982void ObjectMgr::AddCreatureToGrid(uint32 guid, CreatureData const* data)
983{
984    uint8 mask = data->spawnMask;
985    for(uint8 i = 0; mask != 0; i++, mask >>= 1)
986    {
987        if(mask & 1)
988        {
989            CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
990            uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
991
992            CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
993            cell_guids.creatures.insert(guid);
994        }
995    }
996}
997
998void ObjectMgr::RemoveCreatureFromGrid(uint32 guid, CreatureData const* data)
999{
1000    uint8 mask = data->spawnMask;
1001    for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1002    {
1003        if(mask & 1)
1004        {
1005            CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1006            uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1007
1008            CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1009            cell_guids.creatures.erase(guid);
1010        }
1011    }
1012}
1013
1014void ObjectMgr::LoadGameobjects()
1015{
1016    uint32 count = 0;
1017
1018    //                                                0                1   2    3           4           5           6
1019    QueryResult *result = WorldDatabase.Query("SELECT gameobject.guid, id, map, position_x, position_y, position_z, orientation,"
1020    //   7          8          9          10         11             12            13     14         15
1021        "rotation0, rotation1, rotation2, rotation3, spawntimesecs, animprogress, state, spawnMask, event "
1022        "FROM gameobject LEFT OUTER JOIN game_event_gameobject ON gameobject.guid = game_event_gameobject.guid");
1023
1024    if(!result)
1025    {
1026        barGoLink bar(1);
1027
1028        bar.step();
1029
1030        sLog.outString();
1031        sLog.outErrorDb(">> Loaded 0 gameobjects. DB table `gameobject` is empty.");
1032        return;
1033    }
1034
1035    barGoLink bar(result->GetRowCount());
1036
1037    do
1038    {
1039        Field *fields = result->Fetch();
1040        bar.step();
1041
1042        uint32 guid = fields[0].GetUInt32();
1043
1044        GameObjectData& data = mGameObjectDataMap[guid];
1045
1046        data.id             = fields[ 1].GetUInt32();
1047        data.mapid          = fields[ 2].GetUInt32();
1048        data.posX           = fields[ 3].GetFloat();
1049        data.posY           = fields[ 4].GetFloat();
1050        data.posZ           = fields[ 5].GetFloat();
1051        data.orientation    = fields[ 6].GetFloat();
1052        data.rotation0      = fields[ 7].GetFloat();
1053        data.rotation1      = fields[ 8].GetFloat();
1054        data.rotation2      = fields[ 9].GetFloat();
1055        data.rotation3      = fields[10].GetFloat();
1056        data.spawntimesecs  = fields[11].GetInt32();
1057        data.animprogress   = fields[12].GetUInt32();
1058        data.go_state       = fields[13].GetUInt32();
1059        data.spawnMask      = fields[14].GetUInt8();
1060        int16 gameEvent     = fields[15].GetInt16();
1061
1062        GameObjectInfo const* gInfo = GetGameObjectInfo(data.id);
1063        if(!gInfo)
1064        {
1065            sLog.outErrorDb("Table `gameobject` have gameobject (GUID: %u) with not existed gameobject entry %u, skipped.",guid,data.id );
1066            continue;
1067        }
1068
1069        if (gameEvent==0)                                   // if not this is to be managed by GameEvent System
1070            AddGameobjectToGrid(guid, &data);
1071        ++count;
1072
1073    } while (result->NextRow());
1074
1075    delete result;
1076
1077    sLog.outString();
1078    sLog.outString( ">> Loaded %u gameobjects", mGameObjectDataMap.size());
1079}
1080
1081void ObjectMgr::AddGameobjectToGrid(uint32 guid, GameObjectData const* data)
1082{
1083    uint8 mask = data->spawnMask;
1084    for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1085    {
1086        if(mask & 1)
1087        {
1088            CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1089            uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1090
1091            CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1092            cell_guids.gameobjects.insert(guid);
1093        }
1094    }
1095}
1096
1097void ObjectMgr::RemoveGameobjectFromGrid(uint32 guid, GameObjectData const* data)
1098{
1099    uint8 mask = data->spawnMask;
1100    for(uint8 i = 0; mask != 0; i++, mask >>= 1)
1101    {
1102        if(mask & 1)
1103        {
1104            CellPair cell_pair = MaNGOS::ComputeCellPair(data->posX, data->posY);
1105            uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
1106
1107            CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(data->mapid,i)][cell_id];
1108            cell_guids.gameobjects.erase(guid);
1109        }
1110    }
1111}
1112
1113void ObjectMgr::LoadCreatureRespawnTimes()
1114{
1115    // remove outdated data
1116    WorldDatabase.DirectExecute("DELETE FROM creature_respawn WHERE respawntime <= UNIX_TIMESTAMP(NOW())");
1117
1118    uint32 count = 0;
1119
1120    QueryResult *result = WorldDatabase.Query("SELECT guid,respawntime,instance FROM creature_respawn");
1121
1122    if(!result)
1123    {
1124        barGoLink bar(1);
1125
1126        bar.step();
1127
1128        sLog.outString();
1129        sLog.outString(">> Loaded 0 creature respawn time.");
1130        return;
1131    }
1132
1133    barGoLink bar(result->GetRowCount());
1134
1135    do
1136    {
1137        Field *fields = result->Fetch();
1138        bar.step();
1139
1140        uint32 loguid       = fields[0].GetUInt32();
1141        uint64 respawn_time = fields[1].GetUInt64();
1142        uint32 instance     = fields[2].GetUInt32();
1143
1144        mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = time_t(respawn_time);
1145
1146        ++count;
1147    } while (result->NextRow());
1148
1149    delete result;
1150
1151    sLog.outString( ">> Loaded %u creature respawn times", mCreatureRespawnTimes.size() );
1152    sLog.outString();
1153}
1154
1155void ObjectMgr::LoadGameobjectRespawnTimes()
1156{
1157    // remove outdated data
1158    WorldDatabase.DirectExecute("DELETE FROM gameobject_respawn WHERE respawntime <= UNIX_TIMESTAMP(NOW())");
1159
1160    uint32 count = 0;
1161
1162    QueryResult *result = WorldDatabase.Query("SELECT guid,respawntime,instance FROM gameobject_respawn");
1163
1164    if(!result)
1165    {
1166        barGoLink bar(1);
1167
1168        bar.step();
1169
1170        sLog.outString();
1171        sLog.outString(">> Loaded 0 gameobject respawn time.");
1172        return;
1173    }
1174
1175    barGoLink bar(result->GetRowCount());
1176
1177    do
1178    {
1179        Field *fields = result->Fetch();
1180        bar.step();
1181
1182        uint32 loguid       = fields[0].GetUInt32();
1183        uint64 respawn_time = fields[1].GetUInt64();
1184        uint32 instance     = fields[2].GetUInt32();
1185
1186        mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = time_t(respawn_time);
1187
1188        ++count;
1189    } while (result->NextRow());
1190
1191    delete result;
1192
1193    sLog.outString( ">> Loaded %u gameobject respawn times", mGORespawnTimes.size() );
1194    sLog.outString();
1195}
1196
1197// name must be checked to correctness (if received) before call this function
1198uint64 ObjectMgr::GetPlayerGUIDByName(std::string name) const
1199{
1200    uint64 guid = 0;
1201
1202    CharacterDatabase.escape_string(name);
1203
1204    // Player name safe to sending to DB (checked at login) and this function using
1205    QueryResult *result = CharacterDatabase.PQuery("SELECT guid FROM characters WHERE name = '%s'", name.c_str());
1206    if(result)
1207    {
1208        guid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
1209
1210        delete result;
1211    }
1212
1213    return guid;
1214}
1215
1216bool ObjectMgr::GetPlayerNameByGUID(const uint64 &guid, std::string &name) const
1217{
1218    // prevent DB access for online player
1219    if(Player* player = GetPlayer(guid))
1220    {
1221        name = player->GetName();
1222        return true;
1223    }
1224
1225    QueryResult *result = CharacterDatabase.PQuery("SELECT name FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1226
1227    if(result)
1228    {
1229        name = (*result)[0].GetCppString();
1230        delete result;
1231        return true;
1232    }
1233
1234    return false;
1235}
1236
1237uint32 ObjectMgr::GetPlayerTeamByGUID(const uint64 &guid) const
1238{
1239    QueryResult *result = CharacterDatabase.PQuery("SELECT race FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1240
1241    if(result)
1242    {
1243        uint8 race = (*result)[0].GetUInt8();
1244        delete result;
1245        return Player::TeamForRace(race);
1246    }
1247
1248    return 0;
1249}
1250
1251uint32 ObjectMgr::GetPlayerAccountIdByGUID(const uint64 &guid) const
1252{
1253    QueryResult *result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
1254    if(result)
1255    {
1256        uint32 acc = (*result)[0].GetUInt32();
1257        delete result;
1258        return acc;
1259    }
1260
1261    return 0;
1262}
1263
1264uint32 ObjectMgr::GetSecurityByAccount(uint32 acc_id) const
1265{
1266    QueryResult *result = loginDatabase.PQuery("SELECT gmlevel FROM account WHERE id = '%u'", acc_id);
1267    if(result)
1268    {
1269        uint32 sec = (*result)[0].GetUInt32();
1270        delete result;
1271        return sec;
1272    }
1273
1274    return 0;
1275}
1276
1277bool ObjectMgr::GetAccountNameByAccount(uint32 acc_id, std::string &name) const
1278{
1279    QueryResult *result = loginDatabase.PQuery("SELECT username FROM account WHERE id = '%u'", acc_id);
1280    if(result)
1281    {
1282        name = (*result)[0].GetCppString();
1283        delete result;
1284        return true;
1285    }
1286
1287    return false;
1288}
1289
1290uint32 ObjectMgr::GetAccountByAccountName(std::string name) const
1291{
1292    loginDatabase.escape_string(name);
1293    QueryResult *result = loginDatabase.PQuery("SELECT id FROM account WHERE username = '%s'", name.c_str());
1294    if(result)
1295    {
1296        uint32 id = (*result)[0].GetUInt32();
1297        delete result;
1298        return id;
1299    }
1300
1301    return 0;
1302}
1303
1304void ObjectMgr::LoadAuctions()
1305{
1306    QueryResult *result = CharacterDatabase.Query("SELECT COUNT(*) FROM auctionhouse");
1307    if( !result )
1308        return;
1309
1310    Field *fields = result->Fetch();
1311    uint32 AuctionCount=fields[0].GetUInt32();
1312    delete result;
1313
1314    if(!AuctionCount)
1315        return;
1316
1317    result = CharacterDatabase.Query( "SELECT id,auctioneerguid,itemguid,item_template,itemowner,buyoutprice,time,buyguid,lastbid,startbid,deposit,location FROM auctionhouse" );
1318    if( !result )
1319        return;
1320
1321    barGoLink bar( AuctionCount );
1322
1323    AuctionEntry *aItem;
1324
1325    do
1326    {
1327        fields = result->Fetch();
1328
1329        bar.step();
1330
1331        aItem = new AuctionEntry;
1332        aItem->Id = fields[0].GetUInt32();
1333        aItem->auctioneer = fields[1].GetUInt32();
1334        aItem->item_guidlow = fields[2].GetUInt32();
1335        aItem->item_template = fields[3].GetUInt32();
1336        aItem->owner = fields[4].GetUInt32();
1337        aItem->buyout = fields[5].GetUInt32();
1338        aItem->time = fields[6].GetUInt32();
1339        aItem->bidder = fields[7].GetUInt32();
1340        aItem->bid = fields[8].GetUInt32();
1341        aItem->startbid = fields[9].GetUInt32();
1342        aItem->deposit = fields[10].GetUInt32();
1343        aItem->location = fields[11].GetUInt8();
1344        //check if sold item exists
1345        if ( this->GetAItem( aItem->item_guidlow ) )
1346        {
1347            GetAuctionsMap( aItem->location )->AddAuction(aItem);
1348        }
1349        else
1350        {
1351            CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE id = '%u'",aItem->Id);
1352            sLog.outError("Auction %u has not a existing item : %u", aItem->Id, aItem->item_guidlow);
1353            delete aItem;
1354        }
1355    } while (result->NextRow());
1356    delete result;
1357
1358    sLog.outString();
1359    sLog.outString( ">> Loaded %u auctions", AuctionCount );
1360    sLog.outString();
1361}
1362
1363void ObjectMgr::LoadItemLocales()
1364{
1365    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");
1366
1367    if(!result)
1368    {
1369        barGoLink bar(1);
1370
1371        bar.step();
1372
1373        sLog.outString("");
1374        sLog.outString(">> Loaded 0 Item locale strings. DB table `locales_item` is empty.");
1375        return;
1376    }
1377
1378    barGoLink bar(result->GetRowCount());
1379
1380    do
1381    {
1382        Field *fields = result->Fetch();
1383        bar.step();
1384
1385        uint32 entry = fields[0].GetUInt32();
1386
1387        ItemLocale& data = mItemLocaleMap[entry];
1388
1389        for(int i = 1; i < MAX_LOCALE; ++i)
1390        {
1391            std::string str = fields[1+2*(i-1)].GetCppString();
1392            if(!str.empty())
1393            {
1394                int idx = GetOrNewIndexForLocale(LocaleConstant(i));
1395                if(idx >= 0)
1396                {
1397                    if(data.Name.size() <= idx)
1398                        data.Name.resize(idx+1);
1399
1400                    data.Name[idx] = str;
1401                }
1402            }
1403
1404            str = fields[1+2*(i-1)+1].GetCppString();
1405            if(!str.empty())
1406            {
1407                int idx = GetOrNewIndexForLocale(LocaleConstant(i));
1408                if(idx >= 0)
1409                {
1410                    if(data.Description.size() <= idx)
1411                        data.Description.resize(idx+1);
1412
1413                    data.Description[idx] = str;
1414                }
1415            }
1416        }
1417    } while (result->NextRow());
1418
1419    delete result;
1420
1421    sLog.outString();
1422    sLog.outString( ">> Loaded %u Item locale strings", mItemLocaleMap.size() );
1423}
1424
1425void ObjectMgr::LoadItemPrototypes()
1426{
1427    sItemStorage.Load ();
1428    sLog.outString( ">> Loaded %u item prototypes", sItemStorage.RecordCount );
1429    sLog.outString();
1430
1431    // check data correctness
1432    for(uint32 i = 1; i < sItemStorage.MaxEntry; ++i)
1433    {
1434        ItemPrototype const* proto = sItemStorage.LookupEntry<ItemPrototype >(i);
1435        ItemEntry const *dbcitem = sItemStore.LookupEntry(i);
1436        if(!proto)
1437        {
1438            /* to many errors, and possible not all items really used in game
1439            if (dbcitem)
1440                sLog.outErrorDb("Item (Entry: %u) doesn't exists in DB, but must exist.",i);
1441            */
1442            continue;
1443        }
1444
1445        if(dbcitem)
1446        {
1447            if(proto->InventoryType != dbcitem->InventoryType)
1448            {
1449                sLog.outErrorDb("Item (Entry: %u) not correct %u inventory type, must be %u (still using DB value).",i,proto->InventoryType,dbcitem->InventoryType);
1450                // It safe let use InventoryType from DB
1451            }
1452
1453            if(proto->DisplayInfoID != dbcitem->DisplayId)
1454            {
1455                sLog.outErrorDb("Item (Entry: %u) not correct %u display id, must be %u (using it).",i,proto->DisplayInfoID,dbcitem->DisplayId);
1456                const_cast<ItemPrototype*>(proto)->DisplayInfoID = dbcitem->DisplayId;
1457            }
1458            if(proto->Sheath != dbcitem->Sheath)
1459            {
1460                sLog.outErrorDb("Item (Entry: %u) not correct %u sheath, must be %u  (using it).",i,proto->Sheath,dbcitem->Sheath);
1461                const_cast<ItemPrototype*>(proto)->Sheath = dbcitem->Sheath;
1462            }
1463        }
1464        else
1465        {
1466            sLog.outErrorDb("Item (Entry: %u) not correct (not listed in list of existed items).",i);
1467        }
1468
1469        if(proto->Class >= MAX_ITEM_CLASS)
1470        {
1471            sLog.outErrorDb("Item (Entry: %u) has wrong Class value (%u)",i,proto->Class);
1472            const_cast<ItemPrototype*>(proto)->Class = ITEM_CLASS_JUNK;
1473        }
1474
1475        if(proto->SubClass >= MaxItemSubclassValues[proto->Class])
1476        {
1477            sLog.outErrorDb("Item (Entry: %u) has wrong Subclass value (%u) for class %u",i,proto->SubClass,proto->Class);
1478            const_cast<ItemPrototype*>(proto)->SubClass = 0;// exist for all item classes
1479        }
1480
1481        if(proto->Quality >= MAX_ITEM_QUALITY)
1482        {
1483            sLog.outErrorDb("Item (Entry: %u) has wrong Quality value (%u)",i,proto->Quality);
1484            const_cast<ItemPrototype*>(proto)->Quality = ITEM_QUALITY_NORMAL;
1485        }
1486
1487        if(proto->BuyCount <= 0)
1488        {
1489            sLog.outErrorDb("Item (Entry: %u) has wrong BuyCount value (%u), set to default(1).",i,proto->BuyCount);
1490            const_cast<ItemPrototype*>(proto)->BuyCount = 1;
1491        }
1492
1493        if(proto->InventoryType >= MAX_INVTYPE)
1494        {
1495            sLog.outErrorDb("Item (Entry: %u) has wrong InventoryType value (%u)",i,proto->InventoryType);
1496            const_cast<ItemPrototype*>(proto)->InventoryType = INVTYPE_NON_EQUIP;
1497        }
1498
1499        if(proto->RequiredSkill >= MAX_SKILL_TYPE)
1500        {
1501            sLog.outErrorDb("Item (Entry: %u) has wrong RequiredSkill value (%u)",i,proto->RequiredSkill);
1502            const_cast<ItemPrototype*>(proto)->RequiredSkill = 0;
1503        }
1504
1505        if(!(proto->AllowableClass & CLASSMASK_ALL_PLAYABLE))
1506        {
1507            sLog.outErrorDb("Item (Entry: %u) not have in `AllowableClass` any playable classes (%u) and can't be equipped.",i,proto->AllowableClass);
1508        }
1509
1510        if(!(proto->AllowableRace & RACEMASK_ALL_PLAYABLE))
1511        {
1512            sLog.outErrorDb("Item (Entry: %u) not have in `AllowableRace` any playable races (%u) and can't be equipped.",i,proto->AllowableRace);
1513        }
1514
1515        if(proto->RequiredSpell && !sSpellStore.LookupEntry(proto->RequiredSpell))
1516        {
1517            sLog.outErrorDb("Item (Entry: %u) have wrong (non-existed) spell in RequiredSpell (%u)",i,proto->RequiredSpell);
1518            const_cast<ItemPrototype*>(proto)->RequiredSpell = 0;
1519        }
1520
1521        if(proto->RequiredReputationRank >= MAX_REPUTATION_RANK)
1522            sLog.outErrorDb("Item (Entry: %u) has wrong reputation rank in RequiredReputationRank (%u), item can't be used.",i,proto->RequiredReputationRank);
1523
1524        if(proto->RequiredReputationFaction)
1525        {
1526            if(!sFactionStore.LookupEntry(proto->RequiredReputationFaction))
1527            {
1528                sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) faction in RequiredReputationFaction (%u)",i,proto->RequiredReputationFaction);
1529                const_cast<ItemPrototype*>(proto)->RequiredReputationFaction = 0;
1530            }
1531
1532            if(proto->RequiredReputationRank == MIN_REPUTATION_RANK)
1533                sLog.outErrorDb("Item (Entry: %u) has min. reputation rank in RequiredReputationRank (0) but RequiredReputationFaction > 0, faction setting is useless.",i);
1534        }
1535        else if(proto->RequiredReputationRank > MIN_REPUTATION_RANK)
1536            sLog.outErrorDb("Item (Entry: %u) has RequiredReputationFaction ==0 but RequiredReputationRank > 0, rank setting is useless.",i);
1537
1538        if(proto->Stackable==0)
1539        {
1540            sLog.outErrorDb("Item (Entry: %u) has wrong value in stackable (%u), replace by default 1.",i,proto->Stackable);
1541            const_cast<ItemPrototype*>(proto)->Stackable = 1;
1542        }
1543        else if(proto->Stackable > 255)
1544        {
1545            sLog.outErrorDb("Item (Entry: %u) has too large value in stackable (%u), replace by hardcoded upper limit (255).",i,proto->Stackable);
1546            const_cast<ItemPrototype*>(proto)->Stackable = 255;
1547        }
1548
1549        for (int j = 0; j < 10; j++)
1550        {
1551            // for ItemStatValue != 0
1552            if(proto->ItemStat[j].ItemStatValue && proto->ItemStat[j].ItemStatType >= MAX_ITEM_MOD)
1553            {
1554                sLog.outErrorDb("Item (Entry: %u) has wrong stat_type%d (%u)",i,j+1,proto->ItemStat[j].ItemStatType);
1555                const_cast<ItemPrototype*>(proto)->ItemStat[j].ItemStatType = 0;
1556            }
1557        }
1558
1559        for (int j = 0; j < 5; j++)
1560        {
1561            if(proto->Damage[j].DamageType >= MAX_SPELL_SCHOOL)
1562            {
1563                sLog.outErrorDb("Item (Entry: %u) has wrong dmg_type%d (%u)",i,j+1,proto->Damage[j].DamageType);
1564                const_cast<ItemPrototype*>(proto)->Damage[j].DamageType = 0;
1565            }
1566        }
1567
1568        // special format
1569        if(proto->Spells[0].SpellId == SPELL_ID_GENERIC_LEARN)
1570        {
1571            // spell_1
1572            if(proto->Spells[0].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
1573            {
1574                sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u) for special learning format",i,0+1,proto->Spells[0].SpellTrigger);
1575                const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1576                const_cast<ItemPrototype*>(proto)->Spells[0].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1577                const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1578                const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1579            }
1580
1581            // spell_2 have learning spell
1582            if(proto->Spells[1].SpellTrigger != ITEM_SPELLTRIGGER_LEARN_SPELL_ID)
1583            {
1584                sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u) for special learning format.",i,1+1,proto->Spells[1].SpellTrigger);
1585                const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1586                const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1587                const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1588            }
1589            else if(!proto->Spells[1].SpellId)
1590            {
1591                sLog.outErrorDb("Item (Entry: %u) not has expected spell in spellid_%d in special learning format.",i,1+1);
1592                const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1593                const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1594            }
1595            else
1596            {
1597                SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[1].SpellId);
1598                if(!spellInfo)
1599                {
1600                    sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%u)",i,1+1,proto->Spells[1].SpellId);
1601                    const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1602                    const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1603                    const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1604                }
1605                // allowed only in special format
1606                else if(proto->Spells[1].SpellId==SPELL_ID_GENERIC_LEARN)
1607                {
1608                    sLog.outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%u)",i,1+1,proto->Spells[1].SpellId);
1609                    const_cast<ItemPrototype*>(proto)->Spells[0].SpellId = 0;
1610                    const_cast<ItemPrototype*>(proto)->Spells[1].SpellId = 0;
1611                    const_cast<ItemPrototype*>(proto)->Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1612                }
1613            }
1614
1615            // spell_3*,spell_4*,spell_5* is empty
1616            for (int j = 2; j < 5; j++)
1617            {
1618                if(proto->Spells[j].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
1619                {
1620                    sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)",i,j+1,proto->Spells[j].SpellTrigger);
1621                    const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1622                    const_cast<ItemPrototype*>(proto)->Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1623                }
1624                else if(proto->Spells[j].SpellId != 0)
1625                {
1626                    sLog.outErrorDb("Item (Entry: %u) has wrong spell in spellid_%d (%u) for learning special format",i,j+1,proto->Spells[j].SpellId);
1627                    const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1628                }
1629            }
1630        }
1631        // normal spell list
1632        else
1633        {
1634            for (int j = 0; j < 5; j++)
1635            {
1636                if(proto->Spells[j].SpellTrigger >= MAX_ITEM_SPELLTRIGGER || proto->Spells[j].SpellTrigger == ITEM_SPELLTRIGGER_LEARN_SPELL_ID)
1637                {
1638                    sLog.outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)",i,j+1,proto->Spells[j].SpellTrigger);
1639                    const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1640                    const_cast<ItemPrototype*>(proto)->Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE;
1641                }
1642
1643                if(proto->Spells[j].SpellId)
1644                {
1645                    SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[j].SpellId);
1646                    if(!spellInfo)
1647                    {
1648                        sLog.outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%u)",i,j+1,proto->Spells[j].SpellId);
1649                        const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1650                    }
1651                    // allowed only in special format
1652                    else if(proto->Spells[j].SpellId==SPELL_ID_GENERIC_LEARN)
1653                    {
1654                        sLog.outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%u)",i,j+1,proto->Spells[j].SpellId);
1655                        const_cast<ItemPrototype*>(proto)->Spells[j].SpellId = 0;
1656                    }
1657                }
1658            }
1659        }
1660
1661        if(proto->Bonding >= MAX_BIND_TYPE)
1662            sLog.outErrorDb("Item (Entry: %u) has wrong Bonding value (%u)",i,proto->Bonding);
1663
1664        if(proto->PageText && !sPageTextStore.LookupEntry<PageText>(proto->PageText))
1665            sLog.outErrorDb("Item (Entry: %u) has non existing first page (Id:%u)", i,proto->PageText);
1666
1667        if(proto->LockID && !sLockStore.LookupEntry(proto->LockID))
1668            sLog.outErrorDb("Item (Entry: %u) has wrong LockID (%u)",i,proto->LockID);
1669
1670        if(proto->Sheath >= MAX_SHEATHETYPE)
1671        {
1672            sLog.outErrorDb("Item (Entry: %u) has wrong Sheath (%u)",i,proto->Sheath);
1673            const_cast<ItemPrototype*>(proto)->Sheath = SHEATHETYPE_NONE;
1674        }
1675
1676        if(proto->RandomProperty && !sItemRandomPropertiesStore.LookupEntry(GetItemEnchantMod(proto->RandomProperty)))
1677        {
1678            sLog.outErrorDb("Item (Entry: %u) has unknown (wrong or not listed in `item_enchantment_template`) RandomProperty (%u)",i,proto->RandomProperty);
1679            const_cast<ItemPrototype*>(proto)->RandomProperty = 0;
1680        }
1681
1682        if(proto->RandomSuffix && !sItemRandomSuffixStore.LookupEntry(GetItemEnchantMod(proto->RandomSuffix)))
1683        {
1684            sLog.outErrorDb("Item (Entry: %u) has wrong RandomSuffix (%u)",i,proto->RandomSuffix);
1685            const_cast<ItemPrototype*>(proto)->RandomSuffix = 0;
1686        }
1687
1688        if(proto->ItemSet && !sItemSetStore.LookupEntry(proto->ItemSet))
1689        {
1690            sLog.outErrorDb("Item (Entry: %u) have wrong ItemSet (%u)",i,proto->ItemSet);
1691            const_cast<ItemPrototype*>(proto)->ItemSet = 0;
1692        }
1693
1694        if(proto->Area && !GetAreaEntryByAreaID(proto->Area))
1695            sLog.outErrorDb("Item (Entry: %u) has wrong Area (%u)",i,proto->Area);
1696
1697        if(proto->Map && !sMapStore.LookupEntry(proto->Map))
1698            sLog.outErrorDb("Item (Entry: %u) has wrong Map (%u)",i,proto->Map);
1699
1700        if(proto->TotemCategory && !sTotemCategoryStore.LookupEntry(proto->TotemCategory))
1701            sLog.outErrorDb("Item (Entry: %u) has wrong TotemCategory (%u)",i,proto->TotemCategory);
1702
1703        for (int j = 0; j < 3; j++)
1704        {
1705            if(proto->Socket[j].Color && (proto->Socket[j].Color & SOCKET_COLOR_ALL) != proto->Socket[j].Color)
1706            {
1707                sLog.outErrorDb("Item (Entry: %u) has wrong socketColor_%d (%u)",i,j+1,proto->Socket[j].Color);
1708                const_cast<ItemPrototype*>(proto)->Socket[j].Color = 0;
1709            }
1710        }
1711
1712        if(proto->GemProperties && !sGemPropertiesStore.LookupEntry(proto->GemProperties))
1713            sLog.outErrorDb("Item (Entry: %u) has wrong GemProperties (%u)",i,proto->GemProperties);
1714
1715        if(proto->FoodType >= MAX_PET_DIET)
1716        {
1717            sLog.outErrorDb("Item (Entry: %u) has wrong FoodType value (%u)",i,proto->FoodType);
1718            const_cast<ItemPrototype*>(proto)->FoodType = 0;
1719        }
1720    }
1721
1722    // this DBC used currently only for check item templates in DB.
1723    sItemStore.Clear();
1724}
1725
1726void ObjectMgr::LoadAuctionItems()
1727{
1728    QueryResult *result = CharacterDatabase.Query( "SELECT itemguid,item_template FROM auctionhouse" );
1729
1730    if( !result )
1731        return;
1732
1733    barGoLink bar( result->GetRowCount() );
1734
1735    uint32 count = 0;
1736
1737    Field *fields;
1738    do
1739    {
1740        bar.step();
1741
1742        fields = result->Fetch();
1743        uint32 item_guid        = fields[0].GetUInt32();
1744        uint32 item_template    = fields[1].GetUInt32();
1745
1746        ItemPrototype const *proto = GetItemPrototype(item_template);
1747
1748        if(!proto)
1749        {
1750            sLog.outError( "ObjectMgr::LoadAuctionItems: Unknown item (GUID: %u id: #%u) in auction, skipped.", item_guid,item_template);
1751            continue;
1752        }
1753
1754        Item *item = NewItemOrBag(proto);
1755
1756        if(!item->LoadFromDB(item_guid,0))
1757        {
1758            delete item;
1759            continue;
1760        }
1761        AddAItem(item);
1762
1763        ++count;
1764    }
1765    while( result->NextRow() );
1766
1767    delete result;
1768
1769    sLog.outString();
1770    sLog.outString( ">> Loaded %u auction items", count );
1771}
1772
1773void ObjectMgr::LoadPetLevelInfo()
1774{
1775    // Loading levels data
1776    {
1777        //                                                 0               1      2   3     4    5    6    7     8    9
1778        QueryResult *result  = WorldDatabase.Query("SELECT creature_entry, level, hp, mana, str, agi, sta, inte, spi, armor FROM pet_levelstats");
1779
1780        uint32 count = 0;
1781
1782        if (!result)
1783        {
1784            barGoLink bar( 1 );
1785
1786            sLog.outString();
1787            sLog.outString( ">> Loaded %u level pet stats definitions", count );
1788            sLog.outErrorDb( "Error loading `pet_levelstats` table or empty table.");
1789            return;
1790        }
1791
1792        barGoLink bar( result->GetRowCount() );
1793
1794        do
1795        {
1796            Field* fields = result->Fetch();
1797
1798            uint32 creature_id = fields[0].GetUInt32();
1799            if(!sCreatureStorage.LookupEntry<CreatureInfo>(creature_id))
1800            {
1801                sLog.outErrorDb("Wrong creature id %u in `pet_levelstats` table, ignoring.",creature_id);
1802                continue;
1803            }
1804
1805            uint32 current_level = fields[1].GetUInt32();
1806            if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
1807            {
1808                if(current_level > 255)                     // hardcoded level maximum
1809                    sLog.outErrorDb("Wrong (> 255) level %u in `pet_levelstats` table, ignoring.",current_level);
1810                else
1811                    sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `pet_levelstats` table, ignoring.",current_level);
1812                continue;
1813            }
1814            else if(current_level < 1)
1815            {
1816                sLog.outErrorDb("Wrong (<1) level %u in `pet_levelstats` table, ignoring.",current_level);
1817                continue;
1818            }
1819
1820            PetLevelInfo*& pInfoMapEntry = petInfo[creature_id];
1821
1822            if(pInfoMapEntry==NULL)
1823                pInfoMapEntry =  new PetLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
1824
1825            // data for level 1 stored in [0] array element, ...
1826            PetLevelInfo* pLevelInfo = &pInfoMapEntry[current_level-1];
1827
1828            pLevelInfo->health = fields[2].GetUInt16();
1829            pLevelInfo->mana   = fields[3].GetUInt16();
1830            pLevelInfo->armor  = fields[9].GetUInt16();
1831
1832            for (int i = 0; i < MAX_STATS; i++)
1833            {
1834                pLevelInfo->stats[i] = fields[i+4].GetUInt16();
1835            }
1836
1837            bar.step();
1838            ++count;
1839        }
1840        while (result->NextRow());
1841
1842        delete result;
1843
1844        sLog.outString();
1845        sLog.outString( ">> Loaded %u level pet stats definitions", count );
1846    }
1847
1848    // Fill gaps and check integrity
1849    for (PetLevelInfoMap::iterator itr = petInfo.begin(); itr != petInfo.end(); ++itr)
1850    {
1851        PetLevelInfo* pInfo = itr->second;
1852
1853        // fatal error if no level 1 data
1854        if(!pInfo || pInfo[0].health == 0 )
1855        {
1856            sLog.outErrorDb("Creature %u does not have pet stats data for Level 1!",itr->first);
1857            exit(1);
1858        }
1859
1860        // fill level gaps
1861        for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
1862        {
1863            if(pInfo[level].health == 0)
1864            {
1865                sLog.outErrorDb("Creature %u has no data for Level %i pet stats data, using data of Level %i.",itr->first,level+1, level);
1866                pInfo[level] = pInfo[level-1];
1867            }
1868        }
1869    }
1870}
1871
1872PetLevelInfo const* ObjectMgr::GetPetLevelInfo(uint32 creature_id, uint32 level) const
1873{
1874    if(level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
1875        level = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL);
1876
1877    PetLevelInfoMap::const_iterator itr = petInfo.find(creature_id);
1878    if(itr == petInfo.end())
1879        return NULL;
1880
1881    return &itr->second[level-1];                           // data for level 1 stored in [0] array element, ...
1882}
1883
1884void ObjectMgr::LoadPlayerInfo()
1885{
1886    // Load playercreate
1887    {
1888        //                                                0     1      2    3     4           5           6
1889        QueryResult *result = WorldDatabase.Query("SELECT race, class, map, zone, position_x, position_y, position_z FROM playercreateinfo");
1890
1891        uint32 count = 0;
1892
1893        if (!result)
1894        {
1895            barGoLink bar( 1 );
1896
1897            sLog.outString();
1898            sLog.outString( ">> Loaded %u player create definitions", count );
1899            sLog.outErrorDb( "Error loading `playercreateinfo` table or empty table.");
1900            exit(1);
1901        }
1902
1903        barGoLink bar( result->GetRowCount() );
1904
1905        do
1906        {
1907            Field* fields = result->Fetch();
1908
1909            uint32 current_race = fields[0].GetUInt32();
1910            uint32 current_class = fields[1].GetUInt32();
1911            uint32 mapId     = fields[2].GetUInt32();
1912            uint32 zoneId    = fields[3].GetUInt32();
1913            float  positionX = fields[4].GetFloat();
1914            float  positionY = fields[5].GetFloat();
1915            float  positionZ = fields[6].GetFloat();
1916
1917            if(current_race >= MAX_RACES)
1918            {
1919                sLog.outErrorDb("Wrong race %u in `playercreateinfo` table, ignoring.",current_race);
1920                continue;
1921            }
1922
1923            ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(current_race);
1924            if(!rEntry)
1925            {
1926                sLog.outErrorDb("Wrong race %u in `playercreateinfo` table, ignoring.",current_race);
1927                continue;
1928            }
1929
1930            if(current_class >= MAX_CLASSES)
1931            {
1932                sLog.outErrorDb("Wrong class %u in `playercreateinfo` table, ignoring.",current_class);
1933                continue;
1934            }
1935
1936            if(!sChrClassesStore.LookupEntry(current_class))
1937            {
1938                sLog.outErrorDb("Wrong class %u in `playercreateinfo` table, ignoring.",current_class);
1939                continue;
1940            }
1941
1942            // accept DB data only for valid position (and non instanceable)
1943            if( !MapManager::IsValidMapCoord(mapId,positionX,positionY,positionZ) )
1944            {
1945                sLog.outErrorDb("Wrong home position for class %u race %u pair in `playercreateinfo` table, ignoring.",current_class,current_race);
1946                continue;
1947            }
1948
1949            if( sMapStore.LookupEntry(mapId)->Instanceable() )
1950            {
1951                sLog.outErrorDb("Home position in instanceable map for class %u race %u pair in `playercreateinfo` table, ignoring.",current_class,current_race);
1952                continue;
1953            }
1954
1955            PlayerInfo* pInfo = &playerInfo[current_race][current_class];
1956
1957            pInfo->mapId     = mapId;
1958            pInfo->zoneId    = zoneId;
1959            pInfo->positionX = positionX;
1960            pInfo->positionY = positionY;
1961            pInfo->positionZ = positionZ;
1962
1963            pInfo->displayId_m = rEntry->model_m;
1964            pInfo->displayId_f = rEntry->model_f;
1965
1966            bar.step();
1967            ++count;
1968        }
1969        while (result->NextRow());
1970
1971        delete result;
1972
1973        sLog.outString();
1974        sLog.outString( ">> Loaded %u player create definitions", count );
1975    }
1976
1977    // Load playercreate items
1978    {
1979        //                                                0     1      2       3
1980        QueryResult *result = WorldDatabase.Query("SELECT race, class, itemid, amount FROM playercreateinfo_item");
1981
1982        uint32 count = 0;
1983
1984        if (!result)
1985        {
1986            barGoLink bar( 1 );
1987
1988            sLog.outString();
1989            sLog.outString( ">> Loaded %u player create items", count );
1990            sLog.outErrorDb( "Error loading `playercreateinfo_item` table or empty table.");
1991        }
1992        else
1993        {
1994            barGoLink bar( result->GetRowCount() );
1995
1996            do
1997            {
1998                Field* fields = result->Fetch();
1999
2000                uint32 current_race = fields[0].GetUInt32();
2001                if(current_race >= MAX_RACES)
2002                {
2003                    sLog.outErrorDb("Wrong race %u in `playercreateinfo_item` table, ignoring.",current_race);
2004                    continue;
2005                }
2006
2007                uint32 current_class = fields[1].GetUInt32();
2008                if(current_class >= MAX_CLASSES)
2009                {
2010                    sLog.outErrorDb("Wrong class %u in `playercreateinfo_item` table, ignoring.",current_class);
2011                    continue;
2012                }
2013
2014                PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2015
2016                uint32 item_id = fields[2].GetUInt32();
2017
2018                if(!GetItemPrototype(item_id))
2019                {
2020                    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);
2021                    continue;
2022                }
2023
2024                uint32 amount  = fields[3].GetUInt32();
2025
2026                if(!amount)
2027                {
2028                    sLog.outErrorDb("Item id %u (class %u race %u) have amount==0 in `playercreateinfo_item` table, ignoring.",item_id,current_race,current_class);
2029                    continue;
2030                }
2031
2032                pInfo->item.push_back(PlayerCreateInfoItem( item_id, amount));
2033
2034                bar.step();
2035                ++count;
2036            }
2037            while(result->NextRow());
2038
2039            delete result;
2040
2041            sLog.outString();
2042            sLog.outString( ">> Loaded %u player create items", count );
2043        }
2044    }
2045
2046    // Load playercreate spells
2047    {
2048        //                                                0     1      2      3
2049        QueryResult *result = WorldDatabase.Query("SELECT race, class, Spell, Active FROM playercreateinfo_spell");
2050
2051        uint32 count = 0;
2052
2053        if (!result)
2054        {
2055            barGoLink bar( 1 );
2056
2057            sLog.outString();
2058            sLog.outString( ">> Loaded %u player create spells", count );
2059            sLog.outErrorDb( "Error loading `playercreateinfo_spell` table or empty table.");
2060        }
2061        else
2062        {
2063            barGoLink bar( result->GetRowCount() );
2064
2065            do
2066            {
2067                Field* fields = result->Fetch();
2068
2069                uint32 current_race = fields[0].GetUInt32();
2070                if(current_race >= MAX_RACES)
2071                {
2072                    sLog.outErrorDb("Wrong race %u in `playercreateinfo_spell` table, ignoring.",current_race);
2073                    continue;
2074                }
2075
2076                uint32 current_class = fields[1].GetUInt32();
2077                if(current_class >= MAX_CLASSES)
2078                {
2079                    sLog.outErrorDb("Wrong class %u in `playercreateinfo_spell` table, ignoring.",current_class);
2080                    continue;
2081                }
2082
2083                PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2084                pInfo->spell.push_back(CreateSpellPair(fields[2].GetUInt16(), fields[3].GetUInt8()));
2085
2086                bar.step();
2087                ++count;
2088            }
2089            while( result->NextRow() );
2090
2091            delete result;
2092
2093            sLog.outString();
2094            sLog.outString( ">> Loaded %u player create spells", count );
2095        }
2096    }
2097
2098    // Load playercreate actions
2099    {
2100        //                                                0     1      2       3       4     5
2101        QueryResult *result = WorldDatabase.Query("SELECT race, class, button, action, type, misc FROM playercreateinfo_action");
2102
2103        uint32 count = 0;
2104
2105        if (!result)
2106        {
2107            barGoLink bar( 1 );
2108
2109            sLog.outString();
2110            sLog.outString( ">> Loaded %u player create actions", count );
2111            sLog.outErrorDb( "Error loading `playercreateinfo_action` table or empty table.");
2112        }
2113        else
2114        {
2115            barGoLink bar( result->GetRowCount() );
2116
2117            do
2118            {
2119                Field* fields = result->Fetch();
2120
2121                uint32 current_race = fields[0].GetUInt32();
2122                if(current_race >= MAX_RACES)
2123                {
2124                    sLog.outErrorDb("Wrong race %u in `playercreateinfo_action` table, ignoring.",current_race);
2125                    continue;
2126                }
2127
2128                uint32 current_class = fields[1].GetUInt32();
2129                if(current_class >= MAX_CLASSES)
2130                {
2131                    sLog.outErrorDb("Wrong class %u in `playercreateinfo_action` table, ignoring.",current_class);
2132                    continue;
2133                }
2134
2135                PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2136                pInfo->action[0].push_back(fields[2].GetUInt16());
2137                pInfo->action[1].push_back(fields[3].GetUInt16());
2138                pInfo->action[2].push_back(fields[4].GetUInt16());
2139                pInfo->action[3].push_back(fields[5].GetUInt16());
2140
2141                bar.step();
2142                ++count;
2143            }
2144            while( result->NextRow() );
2145
2146            delete result;
2147
2148            sLog.outString();
2149            sLog.outString( ">> Loaded %u player create actions", count );
2150        }
2151    }
2152
2153    // Loading levels data (class only dependent)
2154    {
2155        //                                                 0      1      2       3
2156        QueryResult *result  = WorldDatabase.Query("SELECT class, level, basehp, basemana FROM player_classlevelstats");
2157
2158        uint32 count = 0;
2159
2160        if (!result)
2161        {
2162            barGoLink bar( 1 );
2163
2164            sLog.outString();
2165            sLog.outString( ">> Loaded %u level health/mana definitions", count );
2166            sLog.outErrorDb( "Error loading `player_classlevelstats` table or empty table.");
2167            exit(1);
2168        }
2169
2170        barGoLink bar( result->GetRowCount() );
2171
2172        do
2173        {
2174            Field* fields = result->Fetch();
2175
2176            uint32 current_class = fields[0].GetUInt32();
2177            if(current_class >= MAX_CLASSES)
2178            {
2179                sLog.outErrorDb("Wrong class %u in `player_classlevelstats` table, ignoring.",current_class);
2180                continue;
2181            }
2182
2183            uint32 current_level = fields[1].GetUInt32();
2184            if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2185            {
2186                if(current_level > 255)                     // hardcoded level maximum
2187                    sLog.outErrorDb("Wrong (> 255) level %u in `player_classlevelstats` table, ignoring.",current_level);
2188                else
2189                    sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_classlevelstats` table, ignoring.",current_level);
2190                continue;
2191            }
2192
2193            PlayerClassInfo* pClassInfo = &playerClassInfo[current_class];
2194
2195            if(!pClassInfo->levelInfo)
2196                pClassInfo->levelInfo = new PlayerClassLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
2197
2198            PlayerClassLevelInfo* pClassLevelInfo = &pClassInfo->levelInfo[current_level-1];
2199
2200            pClassLevelInfo->basehealth = fields[2].GetUInt16();
2201            pClassLevelInfo->basemana   = fields[3].GetUInt16();
2202
2203            bar.step();
2204            ++count;
2205        }
2206        while (result->NextRow());
2207
2208        delete result;
2209
2210        sLog.outString();
2211        sLog.outString( ">> Loaded %u level health/mana definitions", count );
2212    }
2213
2214    // Fill gaps and check integrity
2215    for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2216    {
2217        // skip non existed classes
2218        if(!sChrClassesStore.LookupEntry(class_))
2219            continue;
2220
2221        PlayerClassInfo* pClassInfo = &playerClassInfo[class_];
2222
2223        // fatal error if no level 1 data
2224        if(!pClassInfo->levelInfo || pClassInfo->levelInfo[0].basehealth == 0 )
2225        {
2226            sLog.outErrorDb("Class %i Level 1 does not have health/mana data!",class_);
2227            exit(1);
2228        }
2229
2230        // fill level gaps
2231        for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2232        {
2233            if(pClassInfo->levelInfo[level].basehealth == 0)
2234            {
2235                sLog.outErrorDb("Class %i Level %i does not have health/mana data. Using stats data of level %i.",class_,level+1, level);
2236                pClassInfo->levelInfo[level] = pClassInfo->levelInfo[level-1];
2237            }
2238        }
2239    }
2240
2241    // Loading levels data (class/race dependent)
2242    {
2243        //                                                 0     1      2      3    4    5    6    7
2244        QueryResult *result  = WorldDatabase.Query("SELECT race, class, level, str, agi, sta, inte, spi FROM player_levelstats");
2245
2246        uint32 count = 0;
2247
2248        if (!result)
2249        {
2250            barGoLink bar( 1 );
2251
2252            sLog.outString();
2253            sLog.outString( ">> Loaded %u level stats definitions", count );
2254            sLog.outErrorDb( "Error loading `player_levelstats` table or empty table.");
2255            exit(1);
2256        }
2257
2258        barGoLink bar( result->GetRowCount() );
2259
2260        do
2261        {
2262            Field* fields = result->Fetch();
2263
2264            uint32 current_race = fields[0].GetUInt32();
2265            if(current_race >= MAX_RACES)
2266            {
2267                sLog.outErrorDb("Wrong race %u in `player_levelstats` table, ignoring.",current_race);
2268                continue;
2269            }
2270
2271            uint32 current_class = fields[1].GetUInt32();
2272            if(current_class >= MAX_CLASSES)
2273            {
2274                sLog.outErrorDb("Wrong class %u in `player_levelstats` table, ignoring.",current_class);
2275                continue;
2276            }
2277
2278            uint32 current_level = fields[2].GetUInt32();
2279            if(current_level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2280            {
2281                if(current_level > 255)                     // hardcoded level maximum
2282                    sLog.outErrorDb("Wrong (> 255) level %u in `player_levelstats` table, ignoring.",current_level);
2283                else
2284                    sLog.outDetail("Unused (> MaxPlayerLevel in mangosd.conf) level %u in `player_levelstats` table, ignoring.",current_level);
2285                continue;
2286            }
2287
2288            PlayerInfo* pInfo = &playerInfo[current_race][current_class];
2289
2290            if(!pInfo->levelInfo)
2291                pInfo->levelInfo = new PlayerLevelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)];
2292
2293            PlayerLevelInfo* pLevelInfo = &pInfo->levelInfo[current_level-1];
2294
2295            for (int i = 0; i < MAX_STATS; i++)
2296            {
2297                pLevelInfo->stats[i] = fields[i+3].GetUInt8();
2298            }
2299
2300            bar.step();
2301            ++count;
2302        }
2303        while (result->NextRow());
2304
2305        delete result;
2306
2307        sLog.outString();
2308        sLog.outString( ">> Loaded %u level stats definitions", count );
2309    }
2310
2311    // Fill gaps and check integrity
2312    for (int race = 0; race < MAX_RACES; ++race)
2313    {
2314        // skip non existed races
2315        if(!sChrRacesStore.LookupEntry(race))
2316            continue;
2317
2318        for (int class_ = 0; class_ < MAX_CLASSES; ++class_)
2319        {
2320            // skip non existed classes
2321            if(!sChrClassesStore.LookupEntry(class_))
2322                continue;
2323
2324            PlayerInfo* pInfo = &playerInfo[race][class_];
2325
2326            // skip non loaded combinations
2327            if(!pInfo->displayId_m || !pInfo->displayId_f)
2328                continue;
2329
2330            // skip expansion races if not playing with expansion
2331            if (sWorld.getConfig(CONFIG_EXPANSION) < 1 && (race == RACE_BLOODELF || race == RACE_DRAENEI))
2332                continue;
2333
2334            // fatal error if no level 1 data
2335            if(!pInfo->levelInfo || pInfo->levelInfo[0].stats[0] == 0 )
2336            {
2337                sLog.outErrorDb("Race %i Class %i Level 1 does not have stats data!",race,class_);
2338                exit(1);
2339            }
2340
2341            // fill level gaps
2342            for (uint32 level = 1; level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL); ++level)
2343            {
2344                if(pInfo->levelInfo[level].stats[0] == 0)
2345                {
2346                    sLog.outErrorDb("Race %i Class %i Level %i does not have stats data. Using stats data of level %i.",race,class_,level+1, level);
2347                    pInfo->levelInfo[level] = pInfo->levelInfo[level-1];
2348                }
2349            }
2350        }
2351    }
2352}
2353
2354void ObjectMgr::GetPlayerClassLevelInfo(uint32 class_, uint32 level, PlayerClassLevelInfo* info) const
2355{
2356    if(level < 1 || class_ >= MAX_CLASSES)
2357        return;
2358
2359    PlayerClassInfo const* pInfo = &playerClassInfo[class_];
2360
2361    if(level > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2362        level = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL);
2363
2364    *info = pInfo->levelInfo[level-1];
2365}
2366
2367void ObjectMgr::GetPlayerLevelInfo(uint32 race, uint32 class_, uint32 level, PlayerLevelInfo* info) const
2368{
2369    if(level < 1 || race   >= MAX_RACES || class_ >= MAX_CLASSES)
2370        return;
2371
2372    PlayerInfo const* pInfo = &playerInfo[race][class_];
2373    if(pInfo->displayId_m==0 || pInfo->displayId_f==0)
2374        return;
2375
2376    if(level <= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2377        *info = pInfo->levelInfo[level-1];
2378    else
2379        BuildPlayerLevelInfo(race,class_,level,info);
2380}
2381
2382void ObjectMgr::BuildPlayerLevelInfo(uint8 race, uint8 _class, uint8 level, PlayerLevelInfo* info) const
2383{
2384    // base data (last known level)
2385    *info = playerInfo[race][_class].levelInfo[sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)-1];
2386
2387    for(int lvl = sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)-1; lvl < level; ++lvl)
2388    {
2389        switch(_class)
2390        {
2391            case CLASS_WARRIOR:
2392                info->stats[STAT_STRENGTH]  += (lvl > 23 ? 2: (lvl > 1  ? 1: 0));
2393                info->stats[STAT_STAMINA]   += (lvl > 23 ? 2: (lvl > 1  ? 1: 0));
2394                info->stats[STAT_AGILITY]   += (lvl > 36 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2395                info->stats[STAT_INTELLECT] += (lvl > 9 && !(lvl%2) ? 1: 0);
2396                info->stats[STAT_SPIRIT]    += (lvl > 9 && !(lvl%2) ? 1: 0);
2397                break;
2398            case CLASS_PALADIN:
2399                info->stats[STAT_STRENGTH]  += (lvl > 3  ? 1: 0);
2400                info->stats[STAT_STAMINA]   += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2401                info->stats[STAT_AGILITY]   += (lvl > 38 ? 1: (lvl > 7 && !(lvl%2) ? 1: 0));
2402                info->stats[STAT_INTELLECT] += (lvl > 6 && (lvl%2) ? 1: 0);
2403                info->stats[STAT_SPIRIT]    += (lvl > 7 ? 1: 0);
2404                break;
2405            case CLASS_HUNTER:
2406                info->stats[STAT_STRENGTH]  += (lvl > 4  ? 1: 0);
2407                info->stats[STAT_STAMINA]   += (lvl > 4  ? 1: 0);
2408                info->stats[STAT_AGILITY]   += (lvl > 33 ? 2: (lvl > 1 ? 1: 0));
2409                info->stats[STAT_INTELLECT] += (lvl > 8 && (lvl%2) ? 1: 0);
2410                info->stats[STAT_SPIRIT]    += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2411                break;
2412            case CLASS_ROGUE:
2413                info->stats[STAT_STRENGTH]  += (lvl > 5  ? 1: 0);
2414                info->stats[STAT_STAMINA]   += (lvl > 4  ? 1: 0);
2415                info->stats[STAT_AGILITY]   += (lvl > 16 ? 2: (lvl > 1 ? 1: 0));
2416                info->stats[STAT_INTELLECT] += (lvl > 8 && !(lvl%2) ? 1: 0);
2417                info->stats[STAT_SPIRIT]    += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0));
2418                break;
2419            case CLASS_PRIEST:
2420                info->stats[STAT_STRENGTH]  += (lvl > 9 && !(lvl%2) ? 1: 0);
2421                info->stats[STAT_STAMINA]   += (lvl > 5  ? 1: 0);
2422                info->stats[STAT_AGILITY]   += (lvl > 38 ? 1: (lvl > 8 && (lvl%2) ? 1: 0));
2423                info->stats[STAT_INTELLECT] += (lvl > 22 ? 2: (lvl > 1 ? 1: 0));
2424                info->stats[STAT_SPIRIT]    += (lvl > 3  ? 1: 0);
2425                break;
2426            case CLASS_SHAMAN:
2427                info->stats[STAT_STRENGTH]  += (lvl > 34 ? 1: (lvl > 6 && (lvl%2) ? 1: 0));
2428                info->stats[STAT_STAMINA]   += (lvl > 4 ? 1: 0);
2429                info->stats[STAT_AGILITY]   += (lvl > 7 && !(lvl%2) ? 1: 0);
2430                info->stats[STAT_INTELLECT] += (lvl > 5 ? 1: 0);
2431                info->stats[STAT_SPIRIT]    += (lvl > 4 ? 1: 0);
2432                break;
2433            case CLASS_MAGE:
2434                info->stats[STAT_STRENGTH]  += (lvl > 9 && !(lvl%2) ? 1: 0);
2435                info->stats[STAT_STAMINA]   += (lvl > 5  ? 1: 0);
2436                info->stats[STAT_AGILITY]   += (lvl > 9 && !(lvl%2) ? 1: 0);
2437                info->stats[STAT_INTELLECT] += (lvl > 24 ? 2: (lvl > 1 ? 1: 0));
2438                info->stats[STAT_SPIRIT]    += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
2439                break;
2440            case CLASS_WARLOCK:
2441                info->stats[STAT_STRENGTH]  += (lvl > 9 && !(lvl%2) ? 1: 0);
2442                info->stats[STAT_STAMINA]   += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
2443                info->stats[STAT_AGILITY]   += (lvl > 9 && !(lvl%2) ? 1: 0);
2444                info->stats[STAT_INTELLECT] += (lvl > 33 ? 2: (lvl > 2 ? 1: 0));
2445                info->stats[STAT_SPIRIT]    += (lvl > 38 ? 2: (lvl > 3 ? 1: 0));
2446                break;
2447            case CLASS_DRUID:
2448                info->stats[STAT_STRENGTH]  += (lvl > 38 ? 2: (lvl > 6 && (lvl%2) ? 1: 0));
2449                info->stats[STAT_STAMINA]   += (lvl > 32 ? 2: (lvl > 4 ? 1: 0));
2450                info->stats[STAT_AGILITY]   += (lvl > 38 ? 2: (lvl > 8 && (lvl%2) ? 1: 0));
2451                info->stats[STAT_INTELLECT] += (lvl > 38 ? 3: (lvl > 4 ? 1: 0));
2452                info->stats[STAT_SPIRIT]    += (lvl > 38 ? 3: (lvl > 5 ? 1: 0));
2453        }
2454    }
2455}
2456
2457void ObjectMgr::LoadGuilds()
2458{
2459    Guild *newguild;
2460    uint32 count = 0;
2461
2462    QueryResult *result = CharacterDatabase.Query( "SELECT guildid FROM guild" );
2463
2464    if( !result )
2465    {
2466
2467        barGoLink bar( 1 );
2468
2469        bar.step();
2470
2471        sLog.outString();
2472        sLog.outString( ">> Loaded %u guild definitions", count );
2473        return;
2474    }
2475
2476    barGoLink bar( result->GetRowCount() );
2477
2478    do
2479    {
2480        Field *fields = result->Fetch();
2481
2482        bar.step();
2483        ++count;
2484
2485        newguild = new Guild;
2486        if(!newguild->LoadGuildFromDB(fields[0].GetUInt32()))
2487        {
2488            newguild->Disband();
2489            delete newguild;
2490            continue;
2491        }
2492        AddGuild(newguild);
2493
2494    }while( result->NextRow() );
2495
2496    delete result;
2497
2498    sLog.outString();
2499    sLog.outString( ">> Loaded %u guild definitions", count );
2500}
2501
2502void ObjectMgr::LoadArenaTeams()
2503{
2504    uint32 count = 0;
2505
2506    QueryResult *result = CharacterDatabase.Query( "SELECT arenateamid FROM arena_team" );
2507
2508    if( !result )
2509    {
2510
2511        barGoLink bar( 1 );
2512
2513        bar.step();
2514
2515        sLog.outString();
2516        sLog.outString( ">> Loaded %u arenateam definitions", count );
2517        return;
2518    }
2519
2520    barGoLink bar( result->GetRowCount() );
2521
2522    do
2523    {
2524        Field *fields = result->Fetch();
2525
2526        bar.step();
2527        ++count;
2528
2529        ArenaTeam *newarenateam = new ArenaTeam;
2530        if(!newarenateam->LoadArenaTeamFromDB(fields[0].GetUInt32()))
2531        {
2532            delete newarenateam;
2533            continue;
2534        }
2535        AddArenaTeam(newarenateam);
2536    }while( result->NextRow() );
2537
2538    delete result;
2539
2540    sLog.outString();
2541    sLog.outString( ">> Loaded %u arenateam definitions", count );
2542}
2543
2544void ObjectMgr::LoadGroups()
2545{
2546    // -- loading groups --
2547    Group *group = NULL;
2548    uint64 leaderGuid = 0;
2549    uint32 count = 0;
2550    //                                                     0         1              2           3           4              5      6      7      8      9      10     11     12     13      14          15
2551    QueryResult *result = CharacterDatabase.PQuery("SELECT mainTank, mainAssistant, lootMethod, looterGuid, lootThreshold, icon1, icon2, icon3, icon4, icon5, icon6, icon7, icon8, isRaid, difficulty, leaderGuid FROM groups");
2552
2553    if( !result )
2554    {
2555        barGoLink bar( 1 );
2556
2557        bar.step();
2558
2559        sLog.outString();
2560        sLog.outString( ">> Loaded %u group definitions", count );
2561        return;
2562    }
2563
2564    barGoLink bar( result->GetRowCount() );
2565
2566    do
2567    {
2568        bar.step();
2569        Field *fields = result->Fetch();
2570        ++count;
2571        leaderGuid = MAKE_NEW_GUID(fields[15].GetUInt32(),0,HIGHGUID_PLAYER);
2572
2573        group = new Group;
2574        if(!group->LoadGroupFromDB(leaderGuid, result, false))
2575        {
2576            group->Disband();
2577            delete group;
2578            continue;
2579        }
2580        AddGroup(group);
2581    }while( result->NextRow() );
2582
2583    delete result;
2584
2585    sLog.outString();
2586    sLog.outString( ">> Loaded %u group definitions", count );
2587
2588    // -- loading members --
2589    count = 0;
2590    group = NULL;
2591    leaderGuid = 0;
2592    //                                        0           1          2         3
2593    result = CharacterDatabase.PQuery("SELECT memberGuid, assistant, subgroup, leaderGuid FROM group_member ORDER BY leaderGuid");
2594    if(!result)
2595    {
2596        barGoLink bar( 1 );
2597        bar.step();
2598    }
2599    else
2600    {
2601        barGoLink bar( result->GetRowCount() );
2602        do
2603        {
2604            bar.step();
2605            Field *fields = result->Fetch();
2606            count++;
2607            leaderGuid = MAKE_NEW_GUID(fields[3].GetUInt32(), 0, HIGHGUID_PLAYER);
2608            if(!group || group->GetLeaderGUID() != leaderGuid)
2609            {
2610                group = GetGroupByLeader(leaderGuid);
2611                if(!group)
2612                {
2613                    sLog.outErrorDb("Incorrect entry in group_member table : no group with leader %d for member %d!", fields[3].GetUInt32(), fields[0].GetUInt32());
2614                    CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", fields[0].GetUInt32());
2615                    continue;
2616                }
2617            }
2618
2619            if(!group->LoadMemberFromDB(fields[0].GetUInt32(), fields[2].GetUInt8(), fields[1].GetBool()))
2620            {
2621                sLog.outErrorDb("Incorrect entry in group_member table : member %d cannot be added to player %d's group!", fields[0].GetUInt32(), fields[3].GetUInt32());
2622                CharacterDatabase.PExecute("DELETE FROM group_member WHERE memberGuid = '%d'", fields[0].GetUInt32());
2623            }
2624        }while( result->NextRow() );
2625        delete result;
2626    }
2627
2628    // clean groups
2629    // TODO: maybe delete from the DB before loading in this case
2630    for(GroupSet::iterator itr = mGroupSet.begin(); itr != mGroupSet.end();)
2631    {
2632        if((*itr)->GetMembersCount() < 2)
2633        {
2634            (*itr)->Disband();
2635            delete *itr;
2636            mGroupSet.erase(itr++);
2637        }
2638        else
2639            ++itr;
2640    }
2641
2642    // -- loading instances --
2643    count = 0;
2644    group = NULL;
2645    leaderGuid = 0;
2646    result = CharacterDatabase.PQuery(
2647        //      0           1    2         3          4           5
2648        "SELECT leaderGuid, map, instance, permanent, difficulty, resettime, "
2649        // 6
2650        "(SELECT COUNT(*) FROM character_instance WHERE guid = leaderGuid AND instance = group_instance.instance AND permanent = 1 LIMIT 1) "
2651        "FROM group_instance LEFT JOIN instance ON instance = id ORDER BY leaderGuid"
2652    );
2653
2654    if(!result)
2655    {
2656        barGoLink bar( 1 );
2657        bar.step();
2658    }
2659    else
2660    {
2661        barGoLink bar( result->GetRowCount() );
2662        do
2663        {
2664            bar.step();
2665            Field *fields = result->Fetch();
2666            count++;
2667            leaderGuid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
2668            if(!group || group->GetLeaderGUID() != leaderGuid)
2669            {
2670                group = GetGroupByLeader(leaderGuid);
2671                if(!group)
2672                {
2673                    sLog.outErrorDb("Incorrect entry in group_instance table : no group with leader %d", fields[0].GetUInt32());
2674                    continue;
2675                }
2676            }
2677
2678            InstanceSave *save = sInstanceSaveManager.AddInstanceSave(fields[1].GetUInt32(), fields[2].GetUInt32(), fields[4].GetUInt8(), (time_t)fields[5].GetUInt64(), (fields[6].GetUInt32() == 0), true);
2679            group->BindToInstance(save, fields[3].GetBool(), true);
2680        }while( result->NextRow() );
2681        delete result;
2682    }
2683
2684    sLog.outString();
2685    sLog.outString( ">> Loaded %u group-instance binds total", count );
2686
2687    sLog.outString();
2688    sLog.outString( ">> Loaded %u group members total", count );
2689}
2690
2691void ObjectMgr::LoadQuests()
2692{
2693    // For reload case
2694    for(QuestMap::const_iterator itr=mQuestTemplates.begin(); itr != mQuestTemplates.end(); ++itr)
2695        delete itr->second;
2696    mQuestTemplates.clear();
2697
2698    mExclusiveQuestGroups.clear();
2699
2700    //                                                0      1           2             3         4           5     6              7
2701    QueryResult *result = WorldDatabase.Query("SELECT entry, ZoneOrSort, SkillOrClass, MinLevel, QuestLevel, Type, RequiredRaces, RequiredSkillValue,"
2702    //   8                    9                  10                     11                   12                     13                   14                15
2703        "RepObjectiveFaction, RepObjectiveValue, RequiredMinRepFaction, RequiredMinRepValue, RequiredMaxRepFaction, RequiredMaxRepValue, SuggestedPlayers, LimitTime,"
2704    //   16          17            18           19           20           21              22                23         24            25
2705        "QuestFlags, SpecialFlags, CharTitleId, PrevQuestId, NextQuestId, ExclusiveGroup, NextQuestInChain, SrcItemId, SrcItemCount, SrcSpell,"
2706    //   26     27       28          29               30                31       32              33              34              35
2707        "Title, Details, Objectives, OfferRewardText, RequestItemsText, EndText, ObjectiveText1, ObjectiveText2, ObjectiveText3, ObjectiveText4,"
2708    //   36          37          38          39          40             41             42             43
2709        "ReqItemId1, ReqItemId2, ReqItemId3, ReqItemId4, ReqItemCount1, ReqItemCount2, ReqItemCount3, ReqItemCount4,"
2710    //   44            45            46            47            48               49               50               51               52             53             54             55
2711        "ReqSourceId1, ReqSourceId2, ReqSourceId3, ReqSourceId4, ReqSourceCount1, ReqSourceCount2, ReqSourceCount3, ReqSourceCount4, ReqSourceRef1, ReqSourceRef2, ReqSourceRef3, ReqSourceRef4,"
2712    //   56                  57                  58                  59                  60                     61                     62                     63
2713        "ReqCreatureOrGOId1, ReqCreatureOrGOId2, ReqCreatureOrGOId3, ReqCreatureOrGOId4, ReqCreatureOrGOCount1, ReqCreatureOrGOCount2, ReqCreatureOrGOCount3, ReqCreatureOrGOCount4,"
2714    //   64             65             66             67
2715        "ReqSpellCast1, ReqSpellCast2, ReqSpellCast3, ReqSpellCast4,"
2716    //   68                69                70                71                72                73
2717        "RewChoiceItemId1, RewChoiceItemId2, RewChoiceItemId3, RewChoiceItemId4, RewChoiceItemId5, RewChoiceItemId6,"
2718    //   74                   75                   76                   77                   78                   79
2719        "RewChoiceItemCount1, RewChoiceItemCount2, RewChoiceItemCount3, RewChoiceItemCount4, RewChoiceItemCount5, RewChoiceItemCount6,"
2720    //   80          81          82          83          84             85             86             87
2721        "RewItemId1, RewItemId2, RewItemId3, RewItemId4, RewItemCount1, RewItemCount2, RewItemCount3, RewItemCount4,"
2722    //   88              89              90              91              92              93            94            95            96            97
2723        "RewRepFaction1, RewRepFaction2, RewRepFaction3, RewRepFaction4, RewRepFaction5, RewRepValue1, RewRepValue2, RewRepValue3, RewRepValue4, RewRepValue5,"
2724    //   98             99                100       101           102                103               104         105     106     107
2725        "RewOrReqMoney, RewMoneyMaxLevel, RewSpell, RewSpellCast, RewMailTemplateId, RewMailDelaySecs, PointMapId, PointX, PointY, PointOpt,"
2726    //   108            109            110            111           112              113            114                115                116                117
2727        "DetailsEmote1, DetailsEmote2, DetailsEmote3, DetailsEmote4,IncompleteEmote, CompleteEmote, OfferRewardEmote1, OfferRewardEmote2, OfferRewardEmote3, OfferRewardEmote4,"
2728    //   118          119
2729        "StartScript, CompleteScript"
2730        " FROM quest_template");
2731    if(result == NULL)
2732    {
2733        barGoLink bar( 1 );
2734        bar.step();
2735
2736        sLog.outString();
2737        sLog.outString( ">> Loaded 0 quests definitions" );
2738        sLog.outErrorDb("`quest_template` table is empty!");
2739        return;
2740    }
2741
2742    // create multimap previous quest for each existed quest
2743    // some quests can have many previous maps set by NextQuestId in previous quest
2744    // for example set of race quests can lead to single not race specific quest
2745    barGoLink bar( result->GetRowCount() );
2746    do
2747    {
2748        bar.step();
2749        Field *fields = result->Fetch();
2750
2751        Quest * newQuest = new Quest(fields);
2752        mQuestTemplates[newQuest->GetQuestId()] = newQuest;
2753    } while( result->NextRow() );
2754
2755    delete result;
2756
2757    // Post processing
2758    for (QuestMap::iterator iter = mQuestTemplates.begin(); iter != mQuestTemplates.end(); iter++)
2759    {
2760        Quest * qinfo = iter->second;
2761
2762        // additional quest integrity checks (GO, creature_template and item_template must be loaded already)
2763
2764        if (qinfo->QuestFlags & ~QUEST_MANGOS_FLAGS_DB_ALLOWED)
2765        {
2766            sLog.outErrorDb("Quest %u has `SpecialFlags` = %u > max allowed value. Correct `SpecialFlags` to value <= %u",
2767                qinfo->GetQuestId(),qinfo->QuestFlags,QUEST_MANGOS_FLAGS_DB_ALLOWED >> 16);
2768            qinfo->QuestFlags &= QUEST_MANGOS_FLAGS_DB_ALLOWED;
2769        }
2770
2771        if(qinfo->QuestFlags & QUEST_FLAGS_DAILY)
2772        {
2773            if(!(qinfo->QuestFlags & QUEST_MANGOS_FLAGS_REPEATABLE))
2774            {
2775                sLog.outErrorDb("Daily Quest %u not marked as repeatable in `SpecialFlags`, added.",qinfo->GetQuestId());
2776                qinfo->QuestFlags |= QUEST_MANGOS_FLAGS_REPEATABLE;
2777            }
2778        }
2779
2780        if(qinfo->QuestFlags & QUEST_FLAGS_AUTO_REWARDED)
2781        {
2782            // at auto-reward can be rewarded only RewChoiceItemId[0]
2783            for(int j = 1; j < QUEST_REWARD_CHOICES_COUNT; ++j )
2784            {
2785                if(uint32 id = qinfo->RewChoiceItemId[j])
2786                {
2787                    sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item from `RewChoiceItemId%d` can't be rewarded with quest flag QUEST_FLAGS_AUTO_REWARDED.",
2788                        qinfo->GetQuestId(),j+1,id,j+1);
2789                    // no changes, quest ignore this data
2790                }
2791            }
2792        }
2793
2794        // client quest log visual (area case)
2795        if( qinfo->ZoneOrSort > 0 )
2796        {
2797            if(!GetAreaEntryByAreaID(qinfo->ZoneOrSort))
2798            {
2799                sLog.outErrorDb("Quest %u has `ZoneOrSort` = %u (zone case) but zone with this id does not exist.",
2800                    qinfo->GetQuestId(),qinfo->ZoneOrSort);
2801                // no changes, quest not dependent from this value but can have problems at client
2802            }
2803        }
2804        // client quest log visual (sort case)
2805        if( qinfo->ZoneOrSort < 0 )
2806        {
2807            QuestSortEntry const* qSort = sQuestSortStore.LookupEntry(-int32(qinfo->ZoneOrSort));
2808            if( !qSort )
2809            {
2810                sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (sort case) but quest sort with this id does not exist.",
2811                    qinfo->GetQuestId(),qinfo->ZoneOrSort);
2812                // 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)
2813            }
2814            //check SkillOrClass value (class case).
2815            if( ClassByQuestSort(-int32(qinfo->ZoneOrSort)) )
2816            {
2817                // SkillOrClass should not have class case when class case already set in ZoneOrSort.
2818                if(qinfo->SkillOrClass < 0)
2819                {
2820                    sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (class sort case) and `SkillOrClass` = %i (class case), redundant.",
2821                        qinfo->GetQuestId(),qinfo->ZoneOrSort,qinfo->SkillOrClass);
2822                }
2823            }
2824            //check for proper SkillOrClass value (skill case)
2825            if(int32 skill_id =  SkillByQuestSort(-int32(qinfo->ZoneOrSort)))
2826            {
2827                // skill is positive value in SkillOrClass
2828                if(qinfo->SkillOrClass != skill_id )
2829                {
2830                    sLog.outErrorDb("Quest %u has `ZoneOrSort` = %i (skill sort case) but `SkillOrClass` does not have a corresponding value (%i).",
2831                        qinfo->GetQuestId(),qinfo->ZoneOrSort,skill_id);
2832                    //override, and force proper value here?
2833                }
2834            }
2835        }
2836
2837        // SkillOrClass (class case)
2838        if( qinfo->SkillOrClass < 0 )
2839        {
2840            if( !sChrClassesStore.LookupEntry(-int32(qinfo->SkillOrClass)) )
2841            {
2842                sLog.outErrorDb("Quest %u has `SkillOrClass` = %i (class case) but class (%i) does not exist",
2843                    qinfo->GetQuestId(),qinfo->SkillOrClass,-qinfo->SkillOrClass);
2844            }
2845        }
2846        // SkillOrClass (skill case)
2847        if( qinfo->SkillOrClass > 0 )
2848        {
2849            if( !sSkillLineStore.LookupEntry(qinfo->SkillOrClass) )
2850            {
2851                sLog.outErrorDb("Quest %u has `SkillOrClass` = %u (skill case) but skill (%i) does not exist",
2852                    qinfo->GetQuestId(),qinfo->SkillOrClass,qinfo->SkillOrClass);
2853            }
2854        }
2855
2856        if( qinfo->RequiredSkillValue )
2857        {
2858            if( qinfo->RequiredSkillValue > sWorld.GetConfigMaxSkillValue() )
2859            {
2860                sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but max possible skill is %u, quest can't be done.",
2861                    qinfo->GetQuestId(),qinfo->RequiredSkillValue,sWorld.GetConfigMaxSkillValue());
2862                // no changes, quest can't be done for this requirement
2863            }
2864
2865            if( qinfo->SkillOrClass <= 0 )
2866            {
2867                sLog.outErrorDb("Quest %u has `RequiredSkillValue` = %u but `SkillOrClass` = %i (class case), value ignored.",
2868                    qinfo->GetQuestId(),qinfo->RequiredSkillValue,qinfo->SkillOrClass);
2869                // no changes, quest can't be done for this requirement (fail at wrong skill id)
2870            }
2871        }
2872        // else Skill quests can have 0 skill level, this is ok
2873
2874        if(qinfo->RepObjectiveFaction && !sFactionStore.LookupEntry(qinfo->RepObjectiveFaction))
2875        {
2876            sLog.outErrorDb("Quest %u has `RepObjectiveFaction` = %u but faction template %u does not exist, quest can't be done.",
2877                qinfo->GetQuestId(),qinfo->RepObjectiveFaction,qinfo->RepObjectiveFaction);
2878            // no changes, quest can't be done for this requirement
2879        }
2880
2881        if(qinfo->RequiredMinRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMinRepFaction))
2882        {
2883            sLog.outErrorDb("Quest %u has `RequiredMinRepFaction` = %u but faction template %u does not exist, quest can't be done.",
2884                qinfo->GetQuestId(),qinfo->RequiredMinRepFaction,qinfo->RequiredMinRepFaction);
2885            // no changes, quest can't be done for this requirement
2886        }
2887
2888        if(qinfo->RequiredMaxRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMaxRepFaction))
2889        {
2890            sLog.outErrorDb("Quest %u has `RequiredMaxRepFaction` = %u but faction template %u does not exist, quest can't be done.",
2891                qinfo->GetQuestId(),qinfo->RequiredMaxRepFaction,qinfo->RequiredMaxRepFaction);
2892            // no changes, quest can't be done for this requirement
2893        }
2894
2895        if(qinfo->RequiredMinRepValue && qinfo->RequiredMinRepValue > Player::Reputation_Cap)
2896        {
2897            sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but max reputation is %u, quest can't be done.",
2898                qinfo->GetQuestId(),qinfo->RequiredMinRepValue,Player::Reputation_Cap);
2899            // no changes, quest can't be done for this requirement
2900        }
2901
2902        if(qinfo->RequiredMinRepValue && qinfo->RequiredMaxRepValue && qinfo->RequiredMaxRepValue <= qinfo->RequiredMinRepValue)
2903        {
2904            sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d and `RequiredMinRepValue` = %d, quest can't be done.",
2905                qinfo->GetQuestId(),qinfo->RequiredMaxRepValue,qinfo->RequiredMinRepValue);
2906            // no changes, quest can't be done for this requirement
2907        }
2908
2909        if(!qinfo->RepObjectiveFaction && qinfo->RepObjectiveValue > 0 )
2910        {
2911            sLog.outErrorDb("Quest %u has `RepObjectiveValue` = %d but `RepObjectiveFaction` is 0, value has no effect",
2912                qinfo->GetQuestId(),qinfo->RepObjectiveValue);
2913            // warning
2914        }
2915
2916        if(!qinfo->RequiredMinRepFaction && qinfo->RequiredMinRepValue > 0 )
2917        {
2918            sLog.outErrorDb("Quest %u has `RequiredMinRepValue` = %d but `RequiredMinRepFaction` is 0, value has no effect",
2919                qinfo->GetQuestId(),qinfo->RequiredMinRepValue);
2920            // warning
2921        }
2922
2923        if(!qinfo->RequiredMaxRepFaction && qinfo->RequiredMaxRepValue > 0 )
2924        {
2925            sLog.outErrorDb("Quest %u has `RequiredMaxRepValue` = %d but `RequiredMaxRepFaction` is 0, value has no effect",
2926                qinfo->GetQuestId(),qinfo->RequiredMaxRepValue);
2927            // warning
2928        }
2929
2930        if(qinfo->CharTitleId && !sCharTitlesStore.LookupEntry(qinfo->CharTitleId))
2931        {
2932            sLog.outErrorDb("Quest %u has `CharTitleId` = %u but CharTitle Id %u does not exist, quest can't be rewarded with title.",
2933                qinfo->GetQuestId(),qinfo->GetCharTitleId(),qinfo->GetCharTitleId());
2934            qinfo->CharTitleId = 0;
2935            // quest can't reward this title
2936        }
2937
2938        if(qinfo->SrcItemId)
2939        {
2940            if(!sItemStorage.LookupEntry<ItemPrototype>(qinfo->SrcItemId))
2941            {
2942                sLog.outErrorDb("Quest %u has `SrcItemId` = %u but item with entry %u does not exist, quest can't be done.",
2943                    qinfo->GetQuestId(),qinfo->SrcItemId,qinfo->SrcItemId);
2944                qinfo->SrcItemId = 0;                       // quest can't be done for this requirement
2945            }
2946            else if(qinfo->SrcItemCount==0)
2947            {
2948                sLog.outErrorDb("Quest %u has `SrcItemId` = %u but `SrcItemCount` = 0, set to 1 but need fix in DB.",
2949                    qinfo->GetQuestId(),qinfo->SrcItemId);
2950                qinfo->SrcItemCount = 1;                    // update to 1 for allow quest work for backward comptibility with DB
2951            }
2952        }
2953        else if(qinfo->SrcItemCount>0)
2954        {
2955            sLog.outErrorDb("Quest %u has `SrcItemId` = 0 but `SrcItemCount` = %u, useless value.",
2956                qinfo->GetQuestId(),qinfo->SrcItemCount);
2957            qinfo->SrcItemCount=0;                          // no quest work changes in fact
2958        }
2959
2960        if(qinfo->SrcSpell)
2961        {
2962            SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->SrcSpell);
2963            if(!spellInfo)
2964            {
2965                sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u doesn't exist, quest can't be done.",
2966                    qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
2967                qinfo->SrcSpell = 0;                        // quest can't be done for this requirement
2968            }
2969            else if(!SpellMgr::IsSpellValid(spellInfo))
2970            {
2971                sLog.outErrorDb("Quest %u has `SrcSpell` = %u but spell %u is broken, quest can't be done.",
2972                    qinfo->GetQuestId(),qinfo->SrcSpell,qinfo->SrcSpell);
2973                qinfo->SrcSpell = 0;                        // quest can't be done for this requirement
2974            }
2975        }
2976
2977        for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
2978        {
2979            uint32 id = qinfo->ReqItemId[j];
2980            if(id)
2981            {
2982                if(qinfo->ReqItemCount[j]==0)
2983                {
2984                    sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but `ReqItemCount%d` = 0, quest can't be done.",
2985                        qinfo->GetQuestId(),j+1,id,j+1);
2986                    // no changes, quest can't be done for this requirement
2987                }
2988
2989                qinfo->SetFlag(QUEST_MANGOS_FLAGS_DELIVER);
2990
2991                if(!sItemStorage.LookupEntry<ItemPrototype>(id))
2992                {
2993                    sLog.outErrorDb("Quest %u has `ReqItemId%d` = %u but item with entry %u does not exist, quest can't be done.",
2994                        qinfo->GetQuestId(),j+1,id,id);
2995                    qinfo->ReqItemCount[j] = 0;             // prevent incorrect work of quest
2996                }
2997            }
2998            else if(qinfo->ReqItemCount[j]>0)
2999            {
3000                sLog.outErrorDb("Quest %u has `ReqItemId%d` = 0 but `ReqItemCount%d` = %u, quest can't be done.",
3001                    qinfo->GetQuestId(),j+1,j+1,qinfo->ReqItemCount[j]);
3002                qinfo->ReqItemCount[j] = 0;                 // prevent incorrect work of quest
3003            }
3004        }
3005
3006        for(int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j )
3007        {
3008            uint32 id = qinfo->ReqSourceId[j];
3009            if(id)
3010            {
3011                if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3012                {
3013                    sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but item with entry %u does not exist, quest can't be done.",
3014                        qinfo->GetQuestId(),j+1,id,id);
3015                    // no changes, quest can't be done for this requirement
3016                }
3017
3018                if(!qinfo->ReqSourceCount[j])
3019                {
3020                    sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but `ReqSourceCount%d` = 0, quest can't be done.",
3021                        qinfo->GetQuestId(),j+1,id,j+1);
3022                    qinfo->ReqSourceId[j] = 0;              // prevent incorrect work of quest
3023                }
3024
3025                if(!qinfo->ReqSourceRef[j])
3026                {
3027                    sLog.outErrorDb("Quest %u has `ReqSourceId%d` = %u but `ReqSourceRef%d` = 0, quest can't be done.",
3028                        qinfo->GetQuestId(),j+1,id,j+1);
3029                    qinfo->ReqSourceId[j] = 0;              // prevent incorrect work of quest
3030                }
3031            }
3032            else
3033            {
3034                if(qinfo->ReqSourceCount[j]>0)
3035                {
3036                    sLog.outErrorDb("Quest %u has `ReqSourceId%d` = 0 but `ReqSourceCount%d` = %u.",
3037                        qinfo->GetQuestId(),j+1,j+1,qinfo->ReqSourceCount[j]);
3038                    // no changes, quest ignore this data
3039                }
3040
3041                if(qinfo->ReqSourceRef[j]>0)
3042                {
3043                    sLog.outErrorDb("Quest %u has `ReqSourceId%d` = 0 but `ReqSourceRef%d` = %u.",
3044                        qinfo->GetQuestId(),j+1,j+1,qinfo->ReqSourceRef[j]);
3045                    // no changes, quest ignore this data
3046                }
3047            }
3048        }
3049
3050        for(int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j )
3051        {
3052            uint32 ref = qinfo->ReqSourceRef[j];
3053            if(ref)
3054            {
3055                if(ref > QUEST_OBJECTIVES_COUNT)
3056                {
3057                    sLog.outErrorDb("Quest %u has `ReqSourceRef%d` = %u but max value in `ReqSourceRef%d` is %u, quest can't be done.",
3058                        qinfo->GetQuestId(),j+1,ref,j+1,QUEST_OBJECTIVES_COUNT);
3059                    // no changes, quest can't be done for this requirement
3060                }
3061                else
3062                if(!qinfo->ReqItemId[ref-1] && !qinfo->ReqSpell[ref-1])
3063                {
3064                    sLog.outErrorDb("Quest %u has `ReqSourceRef%d` = %u but `ReqItemId%u` = 0 and `ReqSpellCast%u` = 0, quest can't be done.",
3065                        qinfo->GetQuestId(),j+1,ref,ref,ref);
3066                    // no changes, quest can't be done for this requirement
3067                }
3068                else if(qinfo->ReqItemId[ref-1] && qinfo->ReqSpell[ref-1])
3069                {
3070                    sLog.outErrorDb("Quest %u has `ReqItemId%u` = %u and `ReqSpellCast%u` = %u, quest can't have both fields <> 0, then can't be done.",
3071                        qinfo->GetQuestId(),ref,qinfo->ReqItemId[ref-1],ref,qinfo->ReqSpell[ref-1]);
3072                    // no changes, quest can't be done for this requirement
3073                    qinfo->ReqSourceId[j] = 0;              // prevent incorrect work of quest
3074                }
3075            }
3076        }
3077
3078        for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3079        {
3080            uint32 id = qinfo->ReqSpell[j];
3081            if(id)
3082            {
3083                SpellEntry const* spellInfo = sSpellStore.LookupEntry(id);
3084                if(!spellInfo)
3085                {
3086                    sLog.outErrorDb("Quest %u has `ReqSpellCast%d` = %u but spell %u does not exist, quest can't be done.",
3087                        qinfo->GetQuestId(),j+1,id,id);
3088                    // no changes, quest can't be done for this requirement
3089                }
3090
3091                if(!qinfo->ReqCreatureOrGOId[j])
3092                {
3093                    bool found = false;
3094                    for(int k = 0; k < 3; ++k)
3095                    {
3096                        if( spellInfo->Effect[k]==SPELL_EFFECT_QUEST_COMPLETE && uint32(spellInfo->EffectMiscValue[k])==qinfo->QuestId ||
3097                            spellInfo->Effect[k]==SPELL_EFFECT_SEND_EVENT)
3098                        {
3099                            found = true;
3100                            break;
3101                        }
3102                    }
3103
3104                    if(found)
3105                    {
3106                        if(!qinfo->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3107                        {
3108                            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);
3109
3110                            // this will prevent quest completing without objective
3111                            const_cast<Quest*>(qinfo)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3112                        }
3113                    }
3114                    else
3115                    {
3116                        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.",
3117                            qinfo->GetQuestId(),j+1,id,j+1,id);
3118                        // no changes, quest can't be done for this requirement
3119                    }
3120                }
3121            }
3122        }
3123
3124        for(int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j )
3125        {
3126            int32 id = qinfo->ReqCreatureOrGOId[j];
3127            if(id < 0 && !sGOStorage.LookupEntry<GameObjectInfo>(-id))
3128            {
3129                sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but gameobject %u does not exist, quest can't be done.",
3130                    qinfo->GetQuestId(),j+1,id,uint32(-id));
3131                qinfo->ReqCreatureOrGOId[j] = 0;            // quest can't be done for this requirement
3132            }
3133
3134            if(id > 0 && !sCreatureStorage.LookupEntry<CreatureInfo>(id))
3135            {
3136                sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %i but creature with entry %u does not exist, quest can't be done.",
3137                    qinfo->GetQuestId(),j+1,id,uint32(id));
3138                qinfo->ReqCreatureOrGOId[j] = 0;            // quest can't be done for this requirement
3139            }
3140
3141            if(id)
3142            {
3143                // In fact SpeakTo and Kill are quite same: either you can speak to mob:SpeakTo or you can't:Kill/Cast
3144
3145                qinfo->SetFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO);
3146
3147                if(!qinfo->ReqCreatureOrGOCount[j])
3148                {
3149                    sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = %u but `ReqCreatureOrGOCount%d` = 0, quest can't be done.",
3150                        qinfo->GetQuestId(),j+1,id,j+1);
3151                    // no changes, quest can be incorrectly done, but we already report this
3152                }
3153            }
3154            else if(qinfo->ReqCreatureOrGOCount[j]>0)
3155            {
3156                sLog.outErrorDb("Quest %u has `ReqCreatureOrGOId%d` = 0 but `ReqCreatureOrGOCount%d` = %u.",
3157                    qinfo->GetQuestId(),j+1,j+1,qinfo->ReqCreatureOrGOCount[j]);
3158                // no changes, quest ignore this data
3159            }
3160        }
3161
3162        for(int j = 0; j < QUEST_REWARD_CHOICES_COUNT; ++j )
3163        {
3164            uint32 id = qinfo->RewChoiceItemId[j];
3165            if(id)
3166            {
3167                if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3168                {
3169                    sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3170                        qinfo->GetQuestId(),j+1,id,id);
3171                    qinfo->RewChoiceItemId[j] = 0;          // no changes, quest will not reward this
3172                }
3173
3174                if(!qinfo->RewChoiceItemCount[j])
3175                {
3176                    sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = %u but `RewChoiceItemCount%d` = 0, quest can't be done.",
3177                        qinfo->GetQuestId(),j+1,id,j+1);
3178                    // no changes, quest can't be done
3179                }
3180            }
3181            else if(qinfo->RewChoiceItemCount[j]>0)
3182            {
3183                sLog.outErrorDb("Quest %u has `RewChoiceItemId%d` = 0 but `RewChoiceItemCount%d` = %u.",
3184                    qinfo->GetQuestId(),j+1,j+1,qinfo->RewChoiceItemCount[j]);
3185                // no changes, quest ignore this data
3186            }
3187        }
3188
3189        for(int j = 0; j < QUEST_REWARDS_COUNT; ++j )
3190        {
3191            uint32 id = qinfo->RewItemId[j];
3192            if(id)
3193            {
3194                if(!sItemStorage.LookupEntry<ItemPrototype>(id))
3195                {
3196                    sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.",
3197                        qinfo->GetQuestId(),j+1,id,id);
3198                    qinfo->RewItemId[j] = 0;                // no changes, quest will not reward this item
3199                }
3200
3201                if(!qinfo->RewItemCount[j])
3202                {
3203                    sLog.outErrorDb("Quest %u has `RewItemId%d` = %u but `RewItemCount%d` = 0, quest will not reward this item.",
3204                        qinfo->GetQuestId(),j+1,id,j+1);
3205                    // no changes
3206                }
3207            }
3208            else if(qinfo->RewItemCount[j]>0)
3209            {
3210                sLog.outErrorDb("Quest %u has `RewItemId%d` = 0 but `RewItemCount%d` = %u.",
3211                    qinfo->GetQuestId(),j+1,j+1,qinfo->RewItemCount[j]);
3212                // no changes, quest ignore this data
3213            }
3214        }
3215
3216        for(int j = 0; j < QUEST_REPUTATIONS_COUNT; ++j)
3217        {
3218            if(qinfo->RewRepFaction[j])
3219            {
3220                if(!qinfo->RewRepValue[j])
3221                {
3222                    sLog.outErrorDb("Quest %u has `RewRepFaction%d` = %u but `RewRepValue%d` = 0, quest will not reward this reputation.",
3223                        qinfo->GetQuestId(),j+1,qinfo->RewRepValue[j],j+1);
3224                    // no changes
3225                }
3226
3227                if(!sFactionStore.LookupEntry(qinfo->RewRepFaction[j]))
3228                {
3229                    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.",
3230                        qinfo->GetQuestId(),j+1,qinfo->RewRepFaction[j] ,qinfo->RewRepFaction[j] );
3231                    qinfo->RewRepFaction[j] = 0;            // quest will not reward this
3232                }
3233            }
3234            else if(qinfo->RewRepValue[j]!=0)
3235            {
3236                sLog.outErrorDb("Quest %u has `RewRepFaction%d` = 0 but `RewRepValue%d` = %u.",
3237                    qinfo->GetQuestId(),j+1,j+1,qinfo->RewRepValue[j]);
3238                // no changes, quest ignore this data
3239            }
3240        }
3241
3242        if(qinfo->RewSpell)
3243        {
3244            SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpell);
3245
3246            if(!spellInfo)
3247            {
3248                sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u does not exist, spell removed as display reward.",
3249                    qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3250                qinfo->RewSpell = 0;                        // no spell reward will display for this quest
3251            }
3252
3253            else if(!SpellMgr::IsSpellValid(spellInfo))
3254            {
3255                sLog.outErrorDb("Quest %u has `RewSpell` = %u but spell %u is broken, quest can't be done.",
3256                    qinfo->GetQuestId(),qinfo->RewSpell,qinfo->RewSpell);
3257                qinfo->RewSpell = 0;                        // no spell reward will display for this quest
3258            }
3259
3260        }
3261
3262        if(qinfo->RewSpellCast)
3263        {
3264            SpellEntry const* spellInfo = sSpellStore.LookupEntry(qinfo->RewSpellCast);
3265
3266            if(!spellInfo)
3267            {
3268                sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u does not exist, quest will not have a spell reward.",
3269                    qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3270                qinfo->RewSpellCast = 0;                    // no spell will be casted on player
3271            }
3272
3273            else if(!SpellMgr::IsSpellValid(spellInfo))
3274            {
3275                sLog.outErrorDb("Quest %u has `RewSpellCast` = %u but spell %u is broken, quest can't be done.",
3276                    qinfo->GetQuestId(),qinfo->RewSpellCast,qinfo->RewSpellCast);
3277                qinfo->RewSpellCast = 0;                    // no spell will be casted on player
3278            }
3279
3280        }
3281
3282        if(qinfo->RewMailTemplateId)
3283        {
3284            if(!sMailTemplateStore.LookupEntry(qinfo->RewMailTemplateId))
3285            {
3286                sLog.outErrorDb("Quest %u has `RewMailTemplateId` = %u but mail template  %u does not exist, quest will not have a mail reward.",
3287                    qinfo->GetQuestId(),qinfo->RewMailTemplateId,qinfo->RewMailTemplateId);
3288                qinfo->RewMailTemplateId = 0;               // no mail will send to player
3289                qinfo->RewMailDelaySecs = 0;                // no mail will send to player
3290            }
3291        }
3292
3293        if(qinfo->NextQuestInChain)
3294        {
3295            if(mQuestTemplates.find(qinfo->NextQuestInChain) == mQuestTemplates.end())
3296            {
3297                sLog.outErrorDb("Quest %u has `NextQuestInChain` = %u but quest %u does not exist, quest chain will not work.",
3298                    qinfo->GetQuestId(),qinfo->NextQuestInChain ,qinfo->NextQuestInChain );
3299                qinfo->NextQuestInChain = 0;
3300            }
3301            else
3302                mQuestTemplates[qinfo->NextQuestInChain]->prevChainQuests.push_back(qinfo->GetQuestId());
3303        }
3304
3305        // fill additional data stores
3306        if(qinfo->PrevQuestId)
3307        {
3308            if (mQuestTemplates.find(abs(qinfo->GetPrevQuestId())) == mQuestTemplates.end())
3309            {
3310                sLog.outErrorDb("Quest %d has PrevQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetPrevQuestId());
3311            }
3312            else
3313            {
3314                qinfo->prevQuests.push_back(qinfo->PrevQuestId);
3315            }
3316        }
3317
3318        if(qinfo->NextQuestId)
3319        {
3320            if (mQuestTemplates.find(abs(qinfo->GetNextQuestId())) == mQuestTemplates.end())
3321            {
3322                sLog.outErrorDb("Quest %d has NextQuestId %i, but no such quest", qinfo->GetQuestId(), qinfo->GetNextQuestId());
3323            }
3324            else
3325            {
3326                int32 signedQuestId = qinfo->NextQuestId < 0 ? -int32(qinfo->GetQuestId()) : int32(qinfo->GetQuestId());
3327                mQuestTemplates[abs(qinfo->GetNextQuestId())]->prevQuests.push_back(signedQuestId);
3328            }
3329        }
3330
3331        if(qinfo->ExclusiveGroup)
3332            mExclusiveQuestGroups.insert(std::pair<int32, uint32>(qinfo->ExclusiveGroup, qinfo->GetQuestId()));
3333        if(qinfo->LimitTime)
3334            qinfo->SetFlag(QUEST_MANGOS_FLAGS_TIMED);
3335    }
3336
3337    // check QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT for spell with SPELL_EFFECT_QUEST_COMPLETE
3338    for (uint32 i = 0; i < sSpellStore.GetNumRows(); ++i)
3339    {
3340        SpellEntry const *spellInfo = sSpellStore.LookupEntry(i);
3341        if(!spellInfo)
3342            continue;
3343
3344        for(int j = 0; j < 3; ++j)
3345        {
3346            if(spellInfo->Effect[j] != SPELL_EFFECT_QUEST_COMPLETE)
3347                continue;
3348
3349            uint32 quest_id = spellInfo->EffectMiscValue[j];
3350
3351            Quest const* quest = GetQuestTemplate(quest_id);
3352
3353            // some quest referenced in spells not exist (outdataed spells)
3354            if(!quest)
3355                continue;
3356
3357            if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3358            {
3359                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);
3360
3361                // this will prevent quest completing without objective
3362                const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3363            }
3364        }
3365    }
3366
3367    sLog.outString();
3368    sLog.outString( ">> Loaded %u quests definitions", mQuestTemplates.size() );
3369}
3370
3371void ObjectMgr::LoadQuestLocales()
3372{
3373    QueryResult *result = WorldDatabase.Query("SELECT entry,"
3374        "Title_loc1,Details_loc1,Objectives_loc1,OfferRewardText_loc1,RequestItemsText_loc1,EndText_loc1,ObjectiveText1_loc1,ObjectiveText2_loc1,ObjectiveText3_loc1,ObjectiveText4_loc1,"
3375        "Title_loc2,Details_loc2,Objectives_loc2,OfferRewardText_loc2,RequestItemsText_loc2,EndText_loc2,ObjectiveText1_loc2,ObjectiveText2_loc2,ObjectiveText3_loc2,ObjectiveText4_loc2,"
3376        "Title_loc3,Details_loc3,Objectives_loc3,OfferRewardText_loc3,RequestItemsText_loc3,EndText_loc3,ObjectiveText1_loc3,ObjectiveText2_loc3,ObjectiveText3_loc3,ObjectiveText4_loc3,"
3377        "Title_loc4,Details_loc4,Objectives_loc4,OfferRewardText_loc4,RequestItemsText_loc4,EndText_loc4,ObjectiveText1_loc4,ObjectiveText2_loc4,ObjectiveText3_loc4,ObjectiveText4_loc4,"
3378        "Title_loc5,Details_loc5,Objectives_loc5,OfferRewardText_loc5,RequestItemsText_loc5,EndText_loc5,ObjectiveText1_loc5,ObjectiveText2_loc5,ObjectiveText3_loc5,ObjectiveText4_loc5,"
3379        "Title_loc6,Details_loc6,Objectives_loc6,OfferRewardText_loc6,RequestItemsText_loc6,EndText_loc6,ObjectiveText1_loc6,ObjectiveText2_loc6,ObjectiveText3_loc6,ObjectiveText4_loc6,"
3380        "Title_loc7,Details_loc7,Objectives_loc7,OfferRewardText_loc7,RequestItemsText_loc7,EndText_loc7,ObjectiveText1_loc7,ObjectiveText2_loc7,ObjectiveText3_loc7,ObjectiveText4_loc7,"
3381        "Title_loc8,Details_loc8,Objectives_loc8,OfferRewardText_loc8,RequestItemsText_loc8,EndText_loc8,ObjectiveText1_loc8,ObjectiveText2_loc8,ObjectiveText3_loc8,ObjectiveText4_loc8"
3382        " FROM locales_quest"
3383        );
3384
3385    if(!result)
3386    {
3387        barGoLink bar(1);
3388
3389        bar.step();
3390
3391        sLog.outString("");
3392        sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_quest` is empty.");
3393        return;
3394    }
3395
3396    barGoLink bar(result->GetRowCount());
3397
3398    do
3399    {
3400        Field *fields = result->Fetch();
3401        bar.step();
3402
3403        uint32 entry = fields[0].GetUInt32();
3404
3405        QuestLocale& data = mQuestLocaleMap[entry];
3406
3407        for(int i = 1; i < MAX_LOCALE; ++i)
3408        {
3409            std::string str = fields[1+10*(i-1)].GetCppString();
3410            if(!str.empty())
3411            {
3412                int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3413                if(idx >= 0)
3414                {
3415                    if(data.Title.size() <= idx)
3416                        data.Title.resize(idx+1);
3417
3418                    data.Title[idx] = str;
3419                }
3420            }
3421            str = fields[1+10*(i-1)+1].GetCppString();
3422            if(!str.empty())
3423            {
3424                int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3425                if(idx >= 0)
3426                {
3427                    if(data.Details.size() <= idx)
3428                        data.Details.resize(idx+1);
3429
3430                    data.Details[idx] = str;
3431                }
3432            }
3433            str = fields[1+10*(i-1)+2].GetCppString();
3434            if(!str.empty())
3435            {
3436                int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3437                if(idx >= 0)
3438                {
3439                    if(data.Objectives.size() <= idx)
3440                        data.Objectives.resize(idx+1);
3441
3442                    data.Objectives[idx] = str;
3443                }
3444            }
3445            str = fields[1+10*(i-1)+3].GetCppString();
3446            if(!str.empty())
3447            {
3448                int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3449                if(idx >= 0)
3450                {
3451                    if(data.OfferRewardText.size() <= idx)
3452                        data.OfferRewardText.resize(idx+1);
3453
3454                    data.OfferRewardText[idx] = str;
3455                }
3456            }
3457            str = fields[1+10*(i-1)+4].GetCppString();
3458            if(!str.empty())
3459            {
3460                int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3461                if(idx >= 0)
3462                {
3463                    if(data.RequestItemsText.size() <= idx)
3464                        data.RequestItemsText.resize(idx+1);
3465
3466                    data.RequestItemsText[idx] = str;
3467                }
3468            }
3469            str = fields[1+10*(i-1)+5].GetCppString();
3470            if(!str.empty())
3471            {
3472                int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3473                if(idx >= 0)
3474                {
3475                    if(data.EndText.size() <= idx)
3476                        data.EndText.resize(idx+1);
3477
3478                    data.EndText[idx] = str;
3479                }
3480            }
3481            for(int k = 0; k < 4; ++k)
3482            {
3483                str = fields[1+10*(i-1)+6+k].GetCppString();
3484                if(!str.empty())
3485                {
3486                    int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3487                    if(idx >= 0)
3488                    {
3489                        if(data.ObjectiveText[k].size() <= idx)
3490                            data.ObjectiveText[k].resize(idx+1);
3491
3492                        data.ObjectiveText[k][idx] = str;
3493                    }
3494                }
3495            }
3496        }
3497    } while (result->NextRow());
3498
3499    delete result;
3500
3501    sLog.outString();
3502    sLog.outString( ">> Loaded %u Quest locale strings", mQuestLocaleMap.size() );
3503}
3504
3505void ObjectMgr::LoadPetCreateSpells()
3506{
3507    QueryResult *result = WorldDatabase.PQuery("SELECT entry, Spell1, Spell2, Spell3, Spell4 FROM petcreateinfo_spell");
3508    if(!result)
3509    {
3510        barGoLink bar( 1 );
3511        bar.step();
3512
3513        sLog.outString();
3514        sLog.outString( ">> Loaded 0 pet create spells" );
3515        sLog.outErrorDb("`petcreateinfo_spell` table is empty!");
3516        return;
3517    }
3518
3519    uint32 count = 0;
3520
3521    barGoLink bar( result->GetRowCount() );
3522
3523    mPetCreateSpell.clear();
3524
3525    do
3526    {
3527        Field *fields = result->Fetch();
3528        bar.step();
3529
3530        uint32 creature_id = fields[0].GetUInt32();
3531
3532        if(!creature_id || !sCreatureStorage.LookupEntry<CreatureInfo>(creature_id))
3533            continue;
3534
3535        PetCreateSpellEntry PetCreateSpell;
3536        for(int i = 0; i < 4; i++)
3537        {
3538            PetCreateSpell.spellid[i] = fields[i + 1].GetUInt32();
3539
3540            if(PetCreateSpell.spellid[i] && !sSpellStore.LookupEntry(PetCreateSpell.spellid[i]))
3541                sLog.outErrorDb("Spell %u listed in `petcreateinfo_spell` does not exist",PetCreateSpell.spellid[i]);
3542        }
3543
3544        mPetCreateSpell[creature_id] = PetCreateSpell;
3545
3546        ++count;
3547    }
3548    while (result->NextRow());
3549
3550    delete result;
3551
3552    sLog.outString();
3553    sLog.outString( ">> Loaded %u pet create spells", count );
3554}
3555
3556void ObjectMgr::LoadScripts(ScriptMapMap& scripts, char const* tablename)
3557{
3558    if(sWorld.IsScriptScheduled())                          // function don't must be called in time scripts use.
3559        return;
3560
3561    sLog.outString( "%s :", tablename);
3562
3563    scripts.clear();                                        // need for reload support
3564
3565    QueryResult *result = WorldDatabase.PQuery( "SELECT id,delay,command,datalong,datalong2,datatext, x, y, z, o FROM %s", tablename );
3566
3567    uint32 count = 0;
3568
3569    if( !result )
3570    {
3571        barGoLink bar( 1 );
3572        bar.step();
3573
3574        sLog.outString();
3575        sLog.outString( ">> Loaded %u script definitions", count );
3576        return;
3577    }
3578
3579    barGoLink bar( result->GetRowCount() );
3580
3581    do
3582    {
3583        bar.step();
3584
3585        Field *fields = result->Fetch();
3586        ScriptInfo tmp;
3587        tmp.id = fields[0].GetUInt32();
3588        tmp.delay = fields[1].GetUInt32();
3589        tmp.command = fields[2].GetUInt32();
3590        tmp.datalong = fields[3].GetUInt32();
3591        tmp.datalong2 = fields[4].GetUInt32();
3592        tmp.datatext = fields[5].GetCppString();
3593        tmp.x = fields[6].GetFloat();
3594        tmp.y = fields[7].GetFloat();
3595        tmp.z = fields[8].GetFloat();
3596        tmp.o = fields[9].GetFloat();
3597
3598        // generic command args check
3599        switch(tmp.command)
3600        {
3601            case SCRIPT_COMMAND_TALK:
3602            {
3603                if(tmp.datalong > 3)
3604                {
3605                    sLog.outErrorDb("Table `%s` has invalid talk type (datalong = %u) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.datalong,tmp.id);
3606                    continue;
3607                }
3608                break;
3609            }
3610
3611            case SCRIPT_COMMAND_TELEPORT_TO:
3612            {
3613                if(!sMapStore.LookupEntry(tmp.datalong))
3614                {
3615                    sLog.outErrorDb("Table `%s` has invalid map (Id: %u) in SCRIPT_COMMAND_TELEPORT_TO for script id %u",tablename,tmp.datalong,tmp.id);
3616                    continue;
3617                }
3618
3619                if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
3620                {
3621                    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);
3622                    continue;
3623                }
3624                break;
3625            }
3626
3627            case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
3628            {
3629                if(!MaNGOS::IsValidMapCoord(tmp.x,tmp.y,tmp.z,tmp.o))
3630                {
3631                    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);
3632                    continue;
3633                }
3634
3635                if(!GetCreatureTemplate(tmp.datalong))
3636                {
3637                    sLog.outErrorDb("Table `%s` has invalid creature (Entry: %u) in SCRIPT_COMMAND_TEMP_SUMMON_CREATURE for script id %u",tablename,tmp.datalong,tmp.id);
3638                    continue;
3639                }
3640                break;
3641            }
3642
3643            case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
3644            {
3645                GameObjectData const* data = GetGOData(tmp.datalong);
3646                if(!data)
3647                {
3648                    sLog.outErrorDb("Table `%s` has invalid gameobject (GUID: %u) in SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,tmp.datalong,tmp.id);
3649                    continue;
3650                }
3651
3652                GameObjectInfo const* info = GetGameObjectInfo(data->id);
3653                if(!info)
3654                {
3655                    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);
3656                    continue;
3657                }
3658
3659                if( info->type==GAMEOBJECT_TYPE_FISHINGNODE ||
3660                    info->type==GAMEOBJECT_TYPE_FISHINGHOLE ||
3661                    info->type==GAMEOBJECT_TYPE_DOOR        ||
3662                    info->type==GAMEOBJECT_TYPE_BUTTON      ||
3663                    info->type==GAMEOBJECT_TYPE_TRAP )
3664                {
3665                    sLog.outErrorDb("Table `%s` have gameobject type (%u) unsupported by command SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u",tablename,info->id,tmp.id);
3666                    continue;
3667                }
3668                break;
3669            }
3670            case SCRIPT_COMMAND_OPEN_DOOR:
3671            case SCRIPT_COMMAND_CLOSE_DOOR:
3672            {
3673                GameObjectData const* data = GetGOData(tmp.datalong);
3674                if(!data)
3675                {
3676                    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);
3677                    continue;
3678                }
3679
3680                GameObjectInfo const* info = GetGameObjectInfo(data->id);
3681                if(!info)
3682                {
3683                    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);
3684                    continue;
3685                }
3686
3687                if( info->type!=GAMEOBJECT_TYPE_DOOR)
3688                {
3689                    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);
3690                    continue;
3691                }
3692
3693                break;
3694            }
3695            case SCRIPT_COMMAND_QUEST_EXPLORED:
3696            {
3697                Quest const* quest = GetQuestTemplate(tmp.datalong);
3698                if(!quest)
3699                {
3700                    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);
3701                    continue;
3702                }
3703
3704                if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
3705                {
3706                    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);
3707
3708                    // this will prevent quest completing without objective
3709                    const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
3710
3711                    // continue; - quest objective requiremet set and command can be allowed
3712                }
3713
3714                if(float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
3715                {
3716                    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",tablename,tmp.datalong2,tmp.id);
3717                    continue;
3718                }
3719
3720                if(tmp.datalong2 && float(tmp.datalong2) > DEFAULT_VISIBILITY_DISTANCE)
3721                {
3722                    sLog.outErrorDb("Table `%s` has too large distance (%u) for exploring objective complete in `datalong2` in SCRIPT_COMMAND_QUEST_EXPLORED in `datalong` for script id %u, max distance is %u or 0 for disable distance check",tablename,tmp.datalong2,tmp.id,uint32(DEFAULT_VISIBILITY_DISTANCE));
3723                    continue;
3724                }
3725
3726                if(tmp.datalong2 && float(tmp.datalong2) < INTERACTION_DISTANCE)
3727                {
3728                    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 %u or 0 for disable distance check",tablename,tmp.datalong2,tmp.id,uint32(INTERACTION_DISTANCE));
3729                    continue;
3730                }
3731
3732                break;
3733            }
3734
3735            case SCRIPT_COMMAND_REMOVE_AURA:
3736            case SCRIPT_COMMAND_CAST_SPELL:
3737            {
3738                if(!sSpellStore.LookupEntry(tmp.datalong))
3739                {
3740                    sLog.outErrorDb("Table `%s` using non-existent spell (id: %u) in SCRIPT_COMMAND_REMOVE_AURA or SCRIPT_COMMAND_CAST_SPELL for script id %u",tablename,tmp.datalong,tmp.id);
3741                    continue;
3742                }
3743                break;
3744            }
3745        }
3746
3747        if (scripts.find(tmp.id) == scripts.end())
3748        {
3749            ScriptMap emptyMap;
3750            scripts[tmp.id] = emptyMap;
3751        }
3752        scripts[tmp.id].insert(std::pair<uint32, ScriptInfo>(tmp.delay, tmp));
3753
3754        ++count;
3755    } while( result->NextRow() );
3756
3757    delete result;
3758
3759    sLog.outString();
3760    sLog.outString( ">> Loaded %u script definitions", count );
3761}
3762
3763void ObjectMgr::LoadGameObjectScripts()
3764{
3765    LoadScripts(sGameObjectScripts,    "gameobject_scripts");
3766
3767    // check ids
3768    for(ScriptMapMap::const_iterator itr = sGameObjectScripts.begin(); itr != sGameObjectScripts.end(); ++itr)
3769    {
3770        if(!GetGOData(itr->first))
3771            sLog.outErrorDb("Table `gameobject_scripts` has not existing gameobject (GUID: %u) as script id",itr->first);
3772    }
3773}
3774
3775void ObjectMgr::LoadQuestEndScripts()
3776{
3777    LoadScripts(sQuestEndScripts,  "quest_end_scripts");
3778
3779    // check ids
3780    for(ScriptMapMap::const_iterator itr = sQuestEndScripts.begin(); itr != sQuestEndScripts.end(); ++itr)
3781    {
3782        if(!GetQuestTemplate(itr->first))
3783            sLog.outErrorDb("Table `quest_end_scripts` has not existing quest (Id: %u) as script id",itr->first);
3784    }
3785}
3786
3787void ObjectMgr::LoadQuestStartScripts()
3788{
3789    LoadScripts(sQuestStartScripts,"quest_start_scripts");
3790
3791    // check ids
3792    for(ScriptMapMap::const_iterator itr = sQuestStartScripts.begin(); itr != sQuestStartScripts.end(); ++itr)
3793    {
3794        if(!GetQuestTemplate(itr->first))
3795            sLog.outErrorDb("Table `quest_start_scripts` has not existing quest (Id: %u) as script id",itr->first);
3796    }
3797}
3798
3799void ObjectMgr::LoadSpellScripts()
3800{
3801    LoadScripts(sSpellScripts, "spell_scripts");
3802
3803    // check ids
3804    for(ScriptMapMap::const_iterator itr = sSpellScripts.begin(); itr != sSpellScripts.end(); ++itr)
3805    {
3806        SpellEntry const* spellInfo = sSpellStore.LookupEntry(itr->first);
3807
3808        if(!spellInfo)
3809        {
3810            sLog.outErrorDb("Table `spell_scripts` has not existing spell (Id: %u) as script id",itr->first);
3811            continue;
3812        }
3813
3814        //check for correct spellEffect
3815        bool found = false;
3816        for(int i=0; i<3; ++i)
3817        {
3818            // skip empty effects
3819            if( !spellInfo->Effect[i] )
3820                continue;
3821
3822            if( spellInfo->Effect[i] == SPELL_EFFECT_SCRIPT_EFFECT )
3823            {
3824                found =  true;
3825                break;
3826            }
3827        }
3828
3829        if(!found)
3830            sLog.outErrorDb("Table `spell_scripts` has unsupported spell (Id: %u) without SPELL_EFFECT_SCRIPT_EFFECT (%u) spell effect",itr->first,SPELL_EFFECT_SCRIPT_EFFECT);
3831    }
3832}
3833
3834void ObjectMgr::LoadEventScripts()
3835{
3836    LoadScripts(sEventScripts, "event_scripts");
3837
3838    std::set<uint32> evt_scripts;
3839    // Load all possible script entries from gameobjects
3840    for(uint32 i = 1; i < sGOStorage.MaxEntry; ++i)
3841    {
3842        GameObjectInfo const * goInfo = sGOStorage.LookupEntry<GameObjectInfo>(i);
3843        if (goInfo)
3844        {
3845            switch(goInfo->type)
3846            {
3847                case GAMEOBJECT_TYPE_GOOBER:
3848                    if(goInfo->goober.eventId)
3849                        evt_scripts.insert(goInfo->goober.eventId);
3850                    break;
3851                case GAMEOBJECT_TYPE_CHEST:
3852                    if(goInfo->chest.eventId)
3853                        evt_scripts.insert(goInfo->chest.eventId);
3854                    break;
3855                default:
3856                    break;
3857            }
3858        }
3859    }
3860    // Load all possible script entries from spells
3861    for(uint32 i = 1; i < sSpellStore.GetNumRows(); ++i)
3862    {
3863        SpellEntry const * spell = sSpellStore.LookupEntry(i);
3864        if (spell)
3865        {
3866            for(int j=0; j<3; ++j)
3867            {
3868                if( spell->Effect[j] == SPELL_EFFECT_SEND_EVENT )
3869                {
3870                    if (spell->EffectMiscValue[j])
3871                        evt_scripts.insert(spell->EffectMiscValue[j]);
3872                }
3873            }
3874        }
3875    }
3876    // Then check if all scripts are in above list of possible script entries
3877    for(ScriptMapMap::const_iterator itr = sEventScripts.begin(); itr != sEventScripts.end(); ++itr)
3878    {
3879        std::set<uint32>::const_iterator itr2 = evt_scripts.find(itr->first);
3880        if (itr2 == evt_scripts.end())
3881            sLog.outErrorDb("Table `event_scripts` has script (Id: %u) not refering to any gameobject_template type 10 data2 field or type 3 data6 field or any spell effect %u", itr->first, SPELL_EFFECT_SEND_EVENT);
3882    }
3883}
3884
3885void ObjectMgr::LoadItemTexts()
3886{
3887    QueryResult *result = CharacterDatabase.PQuery("SELECT id, text FROM item_text");
3888
3889    uint32 count = 0;
3890
3891    if( !result )
3892    {
3893        barGoLink bar( 1 );
3894        bar.step();
3895
3896        sLog.outString();
3897        sLog.outString( ">> Loaded %u item pages", count );
3898        return;
3899    }
3900
3901    barGoLink bar( result->GetRowCount() );
3902
3903    Field* fields;
3904    do
3905    {
3906        bar.step();
3907
3908        fields = result->Fetch();
3909
3910        mItemTexts[ fields[0].GetUInt32() ] = fields[1].GetCppString();
3911
3912        ++count;
3913
3914    } while ( result->NextRow() );
3915
3916    delete result;
3917
3918    sLog.outString();
3919    sLog.outString( ">> Loaded %u item texts", count );
3920}
3921
3922void ObjectMgr::LoadPageTexts()
3923{
3924    sPageTextStore.Free();                                  // for reload case
3925
3926    sPageTextStore.Load();
3927    sLog.outString( ">> Loaded %u page texts", sPageTextStore.RecordCount );
3928    sLog.outString();
3929
3930    for(uint32 i = 1; i < sPageTextStore.MaxEntry; ++i)
3931    {
3932        // check data correctness
3933        PageText const* page = sPageTextStore.LookupEntry<PageText>(i);
3934        if(!page)
3935            continue;
3936
3937        if(page->Next_Page && !sPageTextStore.LookupEntry<PageText>(page->Next_Page))
3938        {
3939            sLog.outErrorDb("Page text (Id: %u) has not existing next page (Id:%u)", i,page->Next_Page);
3940            continue;
3941        }
3942
3943        // detect circular reference
3944        std::set<uint32> checkedPages;
3945        for(PageText const* pageItr = page; pageItr; pageItr = sPageTextStore.LookupEntry<PageText>(pageItr->Next_Page))
3946        {
3947            if(!pageItr->Next_Page)
3948                break;
3949            checkedPages.insert(pageItr->Page_ID);
3950            if(checkedPages.find(pageItr->Next_Page)!=checkedPages.end())
3951            {
3952                std::ostringstream ss;
3953                ss<< "The text page(s) ";
3954                for (std::set<uint32>::iterator itr= checkedPages.begin();itr!=checkedPages.end(); itr++)
3955                    ss << *itr << " ";
3956                ss << "create(s) a circular reference, which can cause the server to freeze. Changing Next_Page of page "
3957                    << pageItr->Page_ID <<" to 0";
3958                sLog.outErrorDb(ss.str().c_str());
3959                const_cast<PageText*>(pageItr)->Next_Page = 0;
3960                break;
3961            }
3962        }
3963    }
3964}
3965
3966void ObjectMgr::LoadPageTextLocales()
3967{
3968    QueryResult *result = WorldDatabase.PQuery("SELECT entry,text_loc1,text_loc2,text_loc3,text_loc4,text_loc5,text_loc6,text_loc7,text_loc8 FROM locales_page_text");
3969
3970    if(!result)
3971    {
3972        barGoLink bar(1);
3973
3974        bar.step();
3975
3976        sLog.outString("");
3977        sLog.outString(">> Loaded 0 PageText locale strings. DB table `locales_page_text` is empty.");
3978        return;
3979    }
3980
3981    barGoLink bar(result->GetRowCount());
3982
3983    do
3984    {
3985        Field *fields = result->Fetch();
3986        bar.step();
3987
3988        uint32 entry = fields[0].GetUInt32();
3989
3990        PageTextLocale& data = mPageTextLocaleMap[entry];
3991
3992        for(int i = 1; i < MAX_LOCALE; ++i)
3993        {
3994            std::string str = fields[i].GetCppString();
3995            if(str.empty())
3996                continue;
3997
3998            int idx = GetOrNewIndexForLocale(LocaleConstant(i));
3999            if(idx >= 0)
4000            {
4001                if(data.Text.size() <= idx)
4002                    data.Text.resize(idx+1);
4003
4004                data.Text[idx] = str;
4005            }
4006        }
4007
4008    } while (result->NextRow());
4009
4010    delete result;
4011
4012    sLog.outString();
4013    sLog.outString( ">> Loaded %u PageText locale strings", mPageTextLocaleMap.size() );
4014}
4015
4016void ObjectMgr::LoadInstanceTemplate()
4017{
4018    sInstanceTemplate.Load();
4019
4020    for(uint32 i = 0; i < sInstanceTemplate.MaxEntry; i++)
4021    {
4022        InstanceTemplate* temp = (InstanceTemplate*)GetInstanceTemplate(i);
4023        if(!temp) continue;
4024        const MapEntry* entry = sMapStore.LookupEntry(temp->map);
4025        if(!entry)
4026        {
4027            sLog.outErrorDb("ObjectMgr::LoadInstanceTemplate: bad mapid %d for template!", temp->map);
4028            continue;
4029        }
4030        else if(!entry->HasResetTime())
4031            continue;
4032
4033        if(temp->reset_delay == 0)
4034        {
4035            // use defaults from the DBC
4036            if(entry->SupportsHeroicMode())
4037            {
4038                temp->reset_delay = entry->resetTimeHeroic / DAY;
4039            }
4040            else if (entry->resetTimeRaid && entry->map_type == MAP_RAID)
4041            {
4042                temp->reset_delay = entry->resetTimeRaid / DAY;
4043            }
4044        }
4045
4046        // the reset_delay must be atleast one day
4047        temp->reset_delay = std::max((uint32)1, (uint32)(temp->reset_delay * sWorld.getRate(RATE_INSTANCE_RESET_TIME)));
4048    }
4049
4050    sLog.outString( ">> Loaded %u Instance Template definitions", sInstanceTemplate.RecordCount );
4051    sLog.outString();
4052}
4053
4054void ObjectMgr::AddGossipText(GossipText *pGText)
4055{
4056    ASSERT( pGText->Text_ID );
4057    ASSERT( mGossipText.find(pGText->Text_ID) == mGossipText.end() );
4058    mGossipText[pGText->Text_ID] = pGText;
4059}
4060
4061GossipText *ObjectMgr::GetGossipText(uint32 Text_ID)
4062{
4063    GossipTextMap::const_iterator itr;
4064    for (itr = mGossipText.begin(); itr != mGossipText.end(); itr++)
4065    {
4066        if(itr->second->Text_ID == Text_ID)
4067            return itr->second;
4068    }
4069    return NULL;
4070}
4071
4072void ObjectMgr::LoadGossipText()
4073{
4074    GossipText *pGText;
4075    QueryResult *result = WorldDatabase.Query( "SELECT * FROM npc_text" );
4076
4077    int count = 0;
4078    if( !result )
4079    {
4080        barGoLink bar( 1 );
4081        bar.step();
4082
4083        sLog.outString();
4084        sLog.outString( ">> Loaded %u npc texts", count );
4085        return;
4086    }
4087
4088    int cic;
4089
4090    barGoLink bar( result->GetRowCount() );
4091
4092    do
4093    {
4094        ++count;
4095        cic = 0;
4096
4097        Field *fields = result->Fetch();
4098
4099        bar.step();
4100
4101        pGText = new GossipText;
4102        pGText->Text_ID    = fields[cic++].GetUInt32();
4103
4104        for (int i=0; i< 8; i++)
4105        {
4106            pGText->Options[i].Text_0           = fields[cic++].GetCppString();
4107            pGText->Options[i].Text_1           = fields[cic++].GetCppString();
4108
4109            pGText->Options[i].Language         = fields[cic++].GetUInt32();
4110            pGText->Options[i].Probability      = fields[cic++].GetFloat();
4111
4112            pGText->Options[i].Emotes[0]._Delay  = fields[cic++].GetUInt32();
4113            pGText->Options[i].Emotes[0]._Emote  = fields[cic++].GetUInt32();
4114
4115            pGText->Options[i].Emotes[1]._Delay  = fields[cic++].GetUInt32();
4116            pGText->Options[i].Emotes[1]._Emote  = fields[cic++].GetUInt32();
4117
4118            pGText->Options[i].Emotes[2]._Delay  = fields[cic++].GetUInt32();
4119            pGText->Options[i].Emotes[2]._Emote  = fields[cic++].GetUInt32();
4120        }
4121
4122        if ( !pGText->Text_ID ) continue;
4123        AddGossipText( pGText );
4124
4125    } while( result->NextRow() );
4126
4127    sLog.outString();
4128    sLog.outString( ">> Loaded %u npc texts", count );
4129    delete result;
4130}
4131
4132void ObjectMgr::LoadNpcTextLocales()
4133{
4134    QueryResult *result = WorldDatabase.Query("SELECT entry,"
4135        "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,"
4136        "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,"
4137        "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,"
4138        "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,"
4139        "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,"
4140        "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,"
4141        "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, "
4142        "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 "
4143        " FROM locales_npc_text");
4144
4145    if(!result)
4146    {
4147        barGoLink bar(1);
4148
4149        bar.step();
4150
4151        sLog.outString("");
4152        sLog.outString(">> Loaded 0 Quest locale strings. DB table `locales_npc_text` is empty.");
4153        return;
4154    }
4155
4156    barGoLink bar(result->GetRowCount());
4157
4158    do
4159    {
4160        Field *fields = result->Fetch();
4161        bar.step();
4162
4163        uint32 entry = fields[0].GetUInt32();
4164
4165        NpcTextLocale& data = mNpcTextLocaleMap[entry];
4166
4167        for(int i=1; i<MAX_LOCALE; ++i)
4168        {
4169            for(int j=0; j<8; ++j)
4170            {
4171                std::string str0 = fields[1+8*2*(i-1)+2*j].GetCppString();
4172                if(!str0.empty())
4173                {
4174                    int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4175                    if(idx >= 0)
4176                    {
4177                        if(data.Text_0[j].size() <= idx)
4178                            data.Text_0[j].resize(idx+1);
4179
4180                        data.Text_0[j][idx] = str0;
4181                    }
4182                }
4183                std::string str1 = fields[1+8*2*(i-1)+2*j+1].GetCppString();
4184                if(!str1.empty())
4185                {
4186                    int idx = GetOrNewIndexForLocale(LocaleConstant(i));
4187                    if(idx >= 0)
4188                    {
4189                        if(data.Text_1[j].size() <= idx)
4190                            data.Text_1[j].resize(idx+1);
4191
4192                        data.Text_1[j][idx] = str1;
4193                    }
4194                }
4195            }
4196        }
4197    } while (result->NextRow());
4198
4199    delete result;
4200
4201    sLog.outString();
4202    sLog.outString( ">> Loaded %u NpcText locale strings", mNpcTextLocaleMap.size() );
4203}
4204
4205//not very fast function but it is called only once a day, or on starting-up
4206void ObjectMgr::ReturnOrDeleteOldMails(bool serverUp)
4207{
4208    time_t basetime = time(NULL);
4209    sLog.outDebug("Returning mails current time: hour: %d, minute: %d, second: %d ", localtime(&basetime)->tm_hour, localtime(&basetime)->tm_min, localtime(&basetime)->tm_sec);
4210    //delete all old mails without item and without body immediately, if starting server
4211    if (!serverUp)
4212        CharacterDatabase.PExecute("DELETE FROM mail WHERE expire_time < '" I64FMTD "' AND has_items = '0' AND itemTextId = 0", (uint64)basetime);
4213    //                                                     0  1           2      3        4          5         6           7   8       9
4214    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);
4215    if ( !result )
4216        return;                                             // any mails need to be returned or deleted
4217    Field *fields;
4218    //std::ostringstream delitems, delmails; //will be here for optimization
4219    //bool deletemail = false, deleteitem = false;
4220    //delitems << "DELETE FROM item_instance WHERE guid IN ( ";
4221    //delmails << "DELETE FROM mail WHERE id IN ( "
4222    do
4223    {
4224        fields = result->Fetch();
4225        Mail *m = new Mail;
4226        m->messageID = fields[0].GetUInt32();
4227        m->messageType = fields[1].GetUInt8();
4228        m->sender = fields[2].GetUInt32();
4229        m->receiver = fields[3].GetUInt32();
4230        m->itemTextId = fields[4].GetUInt32();
4231        bool has_items = fields[5].GetBool();
4232        m->expire_time = (time_t)fields[6].GetUInt64();
4233        m->deliver_time = 0;
4234        m->COD = fields[7].GetUInt32();
4235        m->checked = fields[8].GetUInt32();
4236        m->mailTemplateId = fields[9].GetInt16();
4237
4238        Player *pl = 0;
4239        if (serverUp)
4240            pl = GetPlayer((uint64)m->receiver);
4241        if (pl && pl->m_mailsLoaded)
4242        {                                                   //this code will run very improbably (the time is between 4 and 5 am, in game is online a player, who has old mail
4243            //his in mailbox and he has already listed his mails )
4244            delete m;
4245            continue;
4246        }
4247        //delete or return mail:
4248        if (has_items)
4249        {
4250            QueryResult *resultItems = CharacterDatabase.PQuery("SELECT item_guid,item_template FROM mail_items WHERE mail_id='%u'", m->messageID);
4251            if(resultItems)
4252            {
4253                do
4254                {
4255                    Field *fields2 = resultItems->Fetch();
4256
4257                    uint32 item_guid_low = fields2[0].GetUInt32();
4258                    uint32 item_template = fields2[1].GetUInt32();
4259
4260                    m->AddItem(item_guid_low, item_template);
4261                }
4262                while (resultItems->NextRow());
4263
4264                delete resultItems;
4265            }
4266            //if it is mail from AH, it shouldn't be returned, but deleted
4267            if (m->messageType != MAIL_NORMAL || (m->checked & (MAIL_CHECK_MASK_AUCTION | MAIL_CHECK_MASK_COD_PAYMENT | MAIL_CHECK_MASK_RETURNED)))
4268            {
4269                // mail open and then not returned
4270                for(std::vector<MailItemInfo>::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
4271                    CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
4272            }
4273            else
4274            {
4275                //mail will be returned:
4276                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);
4277                delete m;
4278                continue;
4279            }
4280        }
4281
4282        if (m->itemTextId)
4283            CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
4284
4285        //deletemail = true;
4286        //delmails << m->messageID << ", ";
4287        CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
4288        delete m;
4289    } while (result->NextRow());
4290    delete result;
4291}
4292
4293void ObjectMgr::LoadQuestAreaTriggers()
4294{
4295    mQuestAreaTriggerMap.clear();                           // need for reload case
4296
4297    QueryResult *result = WorldDatabase.Query( "SELECT id,quest FROM areatrigger_involvedrelation" );
4298
4299    uint32 count = 0;
4300
4301    if( !result )
4302    {
4303        barGoLink bar( 1 );
4304        bar.step();
4305
4306        sLog.outString();
4307        sLog.outString( ">> Loaded %u quest trigger points", count );
4308        return;
4309    }
4310
4311    barGoLink bar( result->GetRowCount() );
4312
4313    do
4314    {
4315        ++count;
4316        bar.step();
4317
4318        Field *fields = result->Fetch();
4319
4320        uint32 trigger_ID = fields[0].GetUInt32();
4321        uint32 quest_ID   = fields[1].GetUInt32();
4322
4323        AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(trigger_ID);
4324        if(!atEntry)
4325        {
4326            sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",trigger_ID);
4327            continue;
4328        }
4329
4330        Quest const* quest = GetQuestTemplate(quest_ID);
4331
4332        if(!quest)
4333        {
4334            sLog.outErrorDb("Table `areatrigger_involvedrelation` has record (id: %u) for not existing quest %u",trigger_ID,quest_ID);
4335            continue;
4336        }
4337
4338        if(!quest->HasFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT))
4339        {
4340            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);
4341
4342            // this will prevent quest completing without objective
4343            const_cast<Quest*>(quest)->SetFlag(QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT);
4344
4345            // continue; - quest modified to required obkective and trigger can be allowed.
4346        }
4347
4348        mQuestAreaTriggerMap[trigger_ID] = quest_ID;
4349
4350    } while( result->NextRow() );
4351
4352    delete result;
4353
4354    sLog.outString();
4355    sLog.outString( ">> Loaded %u quest trigger points", count );
4356}
4357
4358void ObjectMgr::LoadTavernAreaTriggers()
4359{
4360    mTavernAreaTriggerSet.clear();                          // need for reload case
4361
4362    QueryResult *result = WorldDatabase.Query("SELECT id FROM areatrigger_tavern");
4363
4364    uint32 count = 0;
4365
4366    if( !result )
4367    {
4368        barGoLink bar( 1 );
4369        bar.step();
4370
4371        sLog.outString();
4372        sLog.outString( ">> Loaded %u tavern triggers", count );
4373        return;
4374    }
4375
4376    barGoLink bar( result->GetRowCount() );
4377
4378    do
4379    {
4380        ++count;
4381        bar.step();
4382
4383        Field *fields = result->Fetch();
4384
4385        uint32 Trigger_ID      = fields[0].GetUInt32();
4386
4387        AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4388        if(!atEntry)
4389        {
4390            sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4391            continue;
4392        }
4393
4394        mTavernAreaTriggerSet.insert(Trigger_ID);
4395    } while( result->NextRow() );
4396
4397    delete result;
4398
4399    sLog.outString();
4400    sLog.outString( ">> Loaded %u tavern triggers", count );
4401}
4402
4403void ObjectMgr::LoadAreaTriggerScripts()
4404{
4405    mAreaTriggerScripts.clear();                            // need for reload case
4406    QueryResult *result = WorldDatabase.Query("SELECT entry, ScriptName FROM areatrigger_scripts");
4407
4408    uint32 count = 0;
4409
4410    if( !result )
4411    {
4412        barGoLink bar( 1 );
4413        bar.step();
4414
4415        sLog.outString();
4416        sLog.outString( ">> Loaded %u areatrigger scripts", count );
4417        return;
4418    }
4419
4420    barGoLink bar( result->GetRowCount() );
4421
4422    do
4423    {
4424        ++count;
4425        bar.step();
4426
4427        Field *fields = result->Fetch();
4428
4429        uint32 Trigger_ID      = fields[0].GetUInt32();
4430        std::string scriptName = fields[1].GetCppString();
4431
4432        AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4433        if(!atEntry)
4434        {
4435            sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4436            continue;
4437        }
4438        mAreaTriggerScripts[Trigger_ID] = scriptName;
4439    } while( result->NextRow() );
4440
4441    delete result;
4442
4443    sLog.outString();
4444    sLog.outString( ">> Loaded %u areatrigger scripts", count );
4445}
4446uint32 ObjectMgr::GetNearestTaxiNode( float x, float y, float z, uint32 mapid )
4447{
4448    bool found = false;
4449    float dist;
4450    uint32 id = 0;
4451
4452    for(uint32 i = 1; i < sTaxiNodesStore.GetNumRows(); ++i)
4453    {
4454        TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(i);
4455        if(node && node->map_id == mapid)
4456        {
4457            float dist2 = (node->x - x)*(node->x - x)+(node->y - y)*(node->y - y)+(node->z - z)*(node->z - z);
4458            if(found)
4459            {
4460                if(dist2 < dist)
4461                {
4462                    dist = dist2;
4463                    id = i;
4464                }
4465            }
4466            else
4467            {
4468                found = true;
4469                dist = dist2;
4470                id = i;
4471            }
4472        }
4473    }
4474
4475    return id;
4476}
4477
4478void ObjectMgr::GetTaxiPath( uint32 source, uint32 destination, uint32 &path, uint32 &cost)
4479{
4480    TaxiPathSetBySource::iterator src_i = sTaxiPathSetBySource.find(source);
4481    if(src_i==sTaxiPathSetBySource.end())
4482    {
4483        path = 0;
4484        cost = 0;
4485        return;
4486    }
4487
4488    TaxiPathSetForSource& pathSet = src_i->second;
4489
4490    TaxiPathSetForSource::iterator dest_i = pathSet.find(destination);
4491    if(dest_i==pathSet.end())
4492    {
4493        path = 0;
4494        cost = 0;
4495        return;
4496    }
4497
4498    cost = dest_i->second.price;
4499    path = dest_i->second.ID;
4500}
4501
4502uint16 ObjectMgr::GetTaxiMount( uint32 id, uint32 team )
4503{
4504    uint16 mount_entry = 0;
4505    uint16 mount_id = 0;
4506
4507    TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(id);
4508    if(node)
4509    {
4510        if (team == ALLIANCE)
4511        {
4512            mount_entry = node->alliance_mount_type;
4513            CreatureInfo const *ci = GetCreatureTemplate(mount_entry);
4514            if(ci)
4515                mount_id = ci->DisplayID_A;
4516        }
4517        if (team == HORDE)
4518        {
4519            mount_entry = node->horde_mount_type;
4520            CreatureInfo const *ci = GetCreatureTemplate(mount_entry);
4521            if(ci)
4522                mount_id = ci->DisplayID_H;
4523        }
4524    }
4525
4526    CreatureModelInfo const *minfo = GetCreatureModelInfo(mount_id);
4527    if(!minfo)
4528    {
4529        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. ",
4530            mount_entry,id,team,mount_id);
4531
4532        return false;
4533    }
4534    if(minfo->modelid_other_gender!=0)
4535        mount_id = urand(0,1) ? mount_id : minfo->modelid_other_gender;
4536
4537    return mount_id;
4538}
4539
4540void ObjectMgr::GetTaxiPathNodes( uint32 path, Path &pathnodes, std::vector<uint32>& mapIds)
4541{
4542    if(path >= sTaxiPathNodesByPath.size())
4543        return;
4544
4545    TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
4546
4547    pathnodes.Resize(nodeList.size());
4548    mapIds.resize(nodeList.size());
4549
4550    for(size_t i = 0; i < nodeList.size(); ++i)
4551    {
4552        pathnodes[ i ].x = nodeList[i].x;
4553        pathnodes[ i ].y = nodeList[i].y;
4554        pathnodes[ i ].z = nodeList[i].z;
4555
4556        mapIds[i] = nodeList[i].mapid;
4557    }
4558}
4559
4560void ObjectMgr::GetTransportPathNodes( uint32 path, TransportPath &pathnodes )
4561{
4562    if(path >= sTaxiPathNodesByPath.size())
4563        return;
4564
4565    TaxiPathNodeList& nodeList = sTaxiPathNodesByPath[path];
4566
4567    pathnodes.Resize(nodeList.size());
4568
4569    for(size_t i = 0; i < nodeList.size(); ++i)
4570    {
4571        pathnodes[ i ].mapid = nodeList[i].mapid;
4572        pathnodes[ i ].x = nodeList[i].x;
4573        pathnodes[ i ].y = nodeList[i].y;
4574        pathnodes[ i ].z = nodeList[i].z;
4575        pathnodes[ i ].actionFlag = nodeList[i].actionFlag;
4576        pathnodes[ i ].delay = nodeList[i].delay;
4577    }
4578}
4579
4580void ObjectMgr::LoadGraveyardZones()
4581{
4582    mGraveYardMap.clear();                                  // need for reload case
4583
4584    QueryResult *result = WorldDatabase.Query("SELECT id,ghost_zone,faction FROM game_graveyard_zone");
4585
4586    uint32 count = 0;
4587
4588    if( !result )
4589    {
4590        barGoLink bar( 1 );
4591        bar.step();
4592
4593        sLog.outString();
4594        sLog.outString( ">> Loaded %u graveyard-zone links", count );
4595        return;
4596    }
4597
4598    barGoLink bar( result->GetRowCount() );
4599
4600    do
4601    {
4602        ++count;
4603        bar.step();
4604
4605        Field *fields = result->Fetch();
4606
4607        uint32 safeLocId = fields[0].GetUInt32();
4608        uint32 zoneId = fields[1].GetUInt32();
4609        uint32 team   = fields[2].GetUInt32();
4610
4611        WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(safeLocId);
4612        if(!entry)
4613        {
4614            sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",safeLocId);
4615            continue;
4616        }
4617
4618        AreaTableEntry const *areaEntry = GetAreaEntryByAreaID(zoneId);
4619        if(!areaEntry)
4620        {
4621            sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing zone id (%u), skipped.",zoneId);
4622            continue;
4623        }
4624
4625        if(areaEntry->zone != 0)
4626        {
4627            sLog.outErrorDb("Table `game_graveyard_zone` has record subzone id (%u) instead of zone, skipped.",zoneId);
4628            continue;
4629        }
4630
4631        if(team!=0 && team!=HORDE && team!=ALLIANCE)
4632        {
4633            sLog.outErrorDb("Table `game_graveyard_zone` has record for non player faction (%u), skipped.",team);
4634            continue;
4635        }
4636
4637        if(entry->map_id != areaEntry->mapid && team != 0)
4638        {
4639            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);
4640            team = 0;
4641        }
4642
4643        if(!AddGraveYardLink(safeLocId,zoneId,team,false))
4644            sLog.outErrorDb("Table `game_graveyard_zone` has a duplicate record for Garveyard (ID: %u) and Zone (ID: %u), skipped.",safeLocId,zoneId);
4645    } while( result->NextRow() );
4646
4647    delete result;
4648
4649    sLog.outString();
4650    sLog.outString( ">> Loaded %u graveyard-zone links", count );
4651}
4652
4653WorldSafeLocsEntry const *ObjectMgr::GetClosestGraveYard(float x, float y, float z, uint32 MapId, uint32 team)
4654{
4655    // search for zone associated closest graveyard
4656    uint32 zoneId = MapManager::Instance().GetZoneId(MapId,x,y);
4657
4658    // Simulate std. algorithm:
4659    //   found some graveyard associated to (ghost_zone,ghost_map)
4660    //
4661    //   if mapId == graveyard.mapId (ghost in plain zone or city or battleground) and search graveyard at same map
4662    //     then check faction
4663    //   if mapId != graveyard.mapId (ghost in instance) and search any graveyard associated
4664    //     then skip check faction
4665    GraveYardMap::const_iterator graveLow  = mGraveYardMap.lower_bound(zoneId);
4666    GraveYardMap::const_iterator graveUp   = mGraveYardMap.upper_bound(zoneId);
4667    if(graveLow==graveUp)
4668    {
4669        sLog.outErrorDb("Table `game_graveyard_zone` incomplete: Zone %u Team %u does not have a linked graveyard.",zoneId,team);
4670        return NULL;
4671    }
4672
4673    bool foundNear = false;
4674    float distNear;
4675    WorldSafeLocsEntry const* entryNear = NULL;
4676    WorldSafeLocsEntry const* entryFar = NULL;
4677
4678    for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
4679    {
4680        GraveYardData const& data = itr->second;
4681
4682        WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(data.safeLocId);
4683        if(!entry)
4684        {
4685            sLog.outErrorDb("Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.",data.safeLocId);
4686            continue;
4687        }
4688
4689        // remember first graveyard at another map and ignore other
4690        if(MapId != entry->map_id)
4691        {
4692            if(!entryFar)
4693                entryFar = entry;
4694            continue;
4695        }
4696
4697        // skip enemy faction graveyard at same map (normal area, city, or battleground)
4698        // team == 0 case can be at call from .neargrave
4699        if(data.team != 0 && team != 0 && data.team != team)
4700            continue;
4701
4702        // find now nearest graveyard at same map
4703        float dist2 = (entry->x - x)*(entry->x - x)+(entry->y - y)*(entry->y - y)+(entry->z - z)*(entry->z - z);
4704        if(foundNear)
4705        {
4706            if(dist2 < distNear)
4707            {
4708                distNear = dist2;
4709                entryNear = entry;
4710            }
4711        }
4712        else
4713        {
4714            foundNear = true;
4715            distNear = dist2;
4716            entryNear = entry;
4717        }
4718    }
4719
4720    if(entryNear)
4721        return entryNear;
4722
4723    return entryFar;
4724}
4725
4726GraveYardData const* ObjectMgr::FindGraveYardData(uint32 id, uint32 zoneId)
4727{
4728    GraveYardMap::const_iterator graveLow  = mGraveYardMap.lower_bound(zoneId);
4729    GraveYardMap::const_iterator graveUp   = mGraveYardMap.upper_bound(zoneId);
4730
4731    for(GraveYardMap::const_iterator itr = graveLow; itr != graveUp; ++itr)
4732    {
4733        if(itr->second.safeLocId==id)
4734            return &itr->second;
4735    }
4736
4737    return NULL;
4738}
4739
4740bool ObjectMgr::AddGraveYardLink(uint32 id, uint32 zoneId, uint32 team, bool inDB)
4741{
4742    if(FindGraveYardData(id,zoneId))
4743        return false;
4744
4745    // add link to loaded data
4746    GraveYardData data;
4747    data.safeLocId = id;
4748    data.team = team;
4749
4750    mGraveYardMap.insert(GraveYardMap::value_type(zoneId,data));
4751
4752    // add link to DB
4753    if(inDB)
4754    {
4755        WorldDatabase.PExecuteLog("INSERT INTO game_graveyard_zone ( id,ghost_zone,faction) "
4756            "VALUES ('%u', '%u','%u')",id,zoneId,team);
4757    }
4758
4759    return true;
4760}
4761
4762void ObjectMgr::LoadAreaTriggerTeleports()
4763{
4764    mAreaTriggers.clear();                                  // need for reload case
4765
4766    uint32 count = 0;
4767
4768    //                                                0   1               2              3               4           5            6                    7                     8           9                  10                 11                 12
4769    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");
4770    if( !result )
4771    {
4772
4773        barGoLink bar( 1 );
4774
4775        bar.step();
4776
4777        sLog.outString();
4778        sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
4779        return;
4780    }
4781
4782    barGoLink bar( result->GetRowCount() );
4783
4784    do
4785    {
4786        Field *fields = result->Fetch();
4787
4788        bar.step();
4789
4790        ++count;
4791
4792        uint32 Trigger_ID = fields[0].GetUInt32();
4793
4794        AreaTrigger at;
4795
4796        at.requiredLevel      = fields[1].GetUInt8();
4797        at.requiredItem       = fields[2].GetUInt32();
4798        at.requiredItem2      = fields[3].GetUInt32();
4799        at.heroicKey          = fields[4].GetUInt32();
4800        at.heroicKey2         = fields[5].GetUInt32();
4801        at.requiredQuest      = fields[6].GetUInt32();
4802        at.requiredFailedText = fields[7].GetCppString();
4803        at.target_mapId       = fields[8].GetUInt32();
4804        at.target_X           = fields[9].GetFloat();
4805        at.target_Y           = fields[10].GetFloat();
4806        at.target_Z           = fields[11].GetFloat();
4807        at.target_Orientation = fields[12].GetFloat();
4808
4809        AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
4810        if(!atEntry)
4811        {
4812            sLog.outErrorDb("Area trigger (ID:%u) does not exist in `AreaTrigger.dbc`.",Trigger_ID);
4813            continue;
4814        }
4815
4816        if(at.requiredItem)
4817        {
4818            ItemPrototype const *pProto = GetItemPrototype(at.requiredItem);
4819            if(!pProto)
4820            {
4821                sLog.outError("Key item %u does not exist for trigger %u, removing key requirement.", at.requiredItem, Trigger_ID);
4822                at.requiredItem = 0;
4823            }
4824        }
4825        if(at.requiredItem2)
4826        {
4827            ItemPrototype const *pProto = GetItemPrototype(at.requiredItem2);
4828            if(!pProto)
4829            {
4830                sLog.outError("Second item %u not exist for trigger %u, remove key requirement.", at.requiredItem2, Trigger_ID);
4831                at.requiredItem2 = 0;
4832            }
4833        }
4834
4835        if(at.heroicKey)
4836        {
4837            ItemPrototype const *pProto = GetItemPrototype(at.heroicKey);
4838            if(!pProto)
4839            {
4840                sLog.outError("Heroic key item %u not exist for trigger %u, remove key requirement.", at.heroicKey, Trigger_ID);
4841                at.heroicKey = 0;
4842            }
4843        }
4844
4845        if(at.heroicKey2)
4846        {
4847            ItemPrototype const *pProto = GetItemPrototype(at.heroicKey2);
4848            if(!pProto)
4849            {
4850                sLog.outError("Heroic second key item %u not exist for trigger %u, remove key requirement.", at.heroicKey2, Trigger_ID);
4851                at.heroicKey2 = 0;
4852            }
4853        }
4854
4855        if(at.requiredQuest)
4856        {
4857            if(!mQuestTemplates[at.requiredQuest])
4858            {
4859                sLog.outErrorDb("Required Quest %u not exist for trigger %u, remove quest done requirement.",at.requiredQuest,Trigger_ID);
4860                at.requiredQuest = 0;
4861            }
4862        }
4863
4864        MapEntry const* mapEntry = sMapStore.LookupEntry(at.target_mapId);
4865        if(!mapEntry)
4866        {
4867            sLog.outErrorDb("Area trigger (ID:%u) target map (ID: %u) does not exist in `Map.dbc`.",Trigger_ID,at.target_mapId);
4868            continue;
4869        }
4870
4871        if(at.target_X==0 && at.target_Y==0 && at.target_Z==0)
4872        {
4873            sLog.outErrorDb("Area trigger (ID:%u) target coordinates not provided.",Trigger_ID);
4874            continue;
4875        }
4876
4877        mAreaTriggers[Trigger_ID] = at;
4878
4879    } while( result->NextRow() );
4880
4881    delete result;
4882
4883    sLog.outString();
4884    sLog.outString( ">> Loaded %u area trigger teleport definitions", count );
4885}
4886
4887AreaTrigger const* ObjectMgr::GetGoBackTrigger(uint32 Map) const
4888{
4889    const MapEntry *mapEntry = sMapStore.LookupEntry(Map);
4890    if(!mapEntry) return NULL;
4891    for (AreaTriggerMap::const_iterator itr = mAreaTriggers.begin(); itr != mAreaTriggers.end(); itr++)
4892    {
4893        if(itr->second.target_mapId == mapEntry->parent_map)
4894        {
4895            AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(itr->first);
4896            if(atEntry && atEntry->mapid == Map)
4897                return &itr->second;
4898        }
4899    }
4900    return NULL;
4901}
4902
4903void ObjectMgr::SetHighestGuids()
4904{
4905    QueryResult *result = CharacterDatabase.Query( "SELECT MAX(guid) FROM characters" );
4906    if( result )
4907    {
4908        m_hiCharGuid = (*result)[0].GetUInt32()+1;
4909
4910        delete result;
4911    }
4912
4913    result = WorldDatabase.Query( "SELECT MAX(guid) FROM creature" );
4914    if( result )
4915    {
4916        m_hiCreatureGuid = (*result)[0].GetUInt32()+1;
4917
4918        delete result;
4919    }
4920
4921    result = CharacterDatabase.Query( "SELECT MAX(id) FROM character_pet" );
4922    if( result )
4923    {
4924        m_hiPetGuid = (*result)[0].GetUInt32()+1;
4925
4926        delete result;
4927    }
4928
4929    result = CharacterDatabase.Query( "SELECT MAX(guid) FROM item_instance" );
4930    if( result )
4931    {
4932        m_hiItemGuid = (*result)[0].GetUInt32()+1;
4933
4934        delete result;
4935    }
4936
4937    // Cleanup other tables from not existed guids (>=m_hiItemGuid)
4938    CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item >= '%u'", m_hiItemGuid);
4939    CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid >= '%u'", m_hiItemGuid);
4940    CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE itemguid >= '%u'", m_hiItemGuid);
4941    CharacterDatabase.PExecute("DELETE FROM guild_bank_item WHERE item_guid >= '%u'", m_hiItemGuid);
4942
4943    result = WorldDatabase.Query("SELECT MAX(guid) FROM gameobject" );
4944    if( result )
4945    {
4946        m_hiGoGuid = (*result)[0].GetUInt32()+1;
4947
4948        delete result;
4949    }
4950
4951    result = CharacterDatabase.Query("SELECT MAX(id) FROM auctionhouse" );
4952    if( result )
4953    {
4954        m_auctionid = (*result)[0].GetUInt32()+1;
4955
4956        delete result;
4957    }
4958    else
4959    {
4960        m_auctionid = 0;
4961    }
4962    result = CharacterDatabase.Query( "SELECT MAX(id) FROM mail" );
4963    if( result )
4964    {
4965        m_mailid = (*result)[0].GetUInt32()+1;
4966
4967        delete result;
4968    }
4969    else
4970    {
4971        m_mailid = 0;
4972    }
4973    result = CharacterDatabase.Query( "SELECT MAX(id) FROM item_text" );
4974    if( result )
4975    {
4976        m_ItemTextId = (*result)[0].GetUInt32();
4977
4978        delete result;
4979    }
4980    else
4981        m_ItemTextId = 0;
4982
4983    result = CharacterDatabase.Query( "SELECT MAX(guid) FROM corpse" );
4984    if( result )
4985    {
4986        m_hiCorpseGuid = (*result)[0].GetUInt32()+1;
4987
4988        delete result;
4989    }
4990}
4991
4992uint32 ObjectMgr::GenerateAuctionID()
4993{
4994    ++m_auctionid;
4995    if(m_auctionid>=0xFFFFFFFF)
4996    {
4997        sLog.outError("Auctions ids overflow!! Can't continue, shuting down server. ");
4998        sWorld.m_stopEvent = true;
4999    }
5000    return m_auctionid;
5001}
5002
5003uint32 ObjectMgr::GenerateMailID()
5004{
5005    ++m_mailid;
5006    if(m_mailid>=0xFFFFFFFF)
5007    {
5008        sLog.outError("Mail ids overflow!! Can't continue, shuting down server. ");
5009        sWorld.m_stopEvent = true;
5010    }
5011    return m_mailid;
5012}
5013
5014uint32 ObjectMgr::GenerateItemTextID()
5015{
5016    ++m_ItemTextId;
5017    if(m_ItemTextId>=0xFFFFFFFF)
5018    {
5019        sLog.outError("Item text ids overflow!! Can't continue, shuting down server. ");
5020        sWorld.m_stopEvent = true;
5021    }
5022    return m_ItemTextId;
5023}
5024
5025uint32 ObjectMgr::CreateItemText(std::string text)
5026{
5027    uint32 newItemTextId = GenerateItemTextID();
5028    //insert new itempage to container
5029    mItemTexts[ newItemTextId ] = text;
5030    //save new itempage
5031    CharacterDatabase.escape_string(text);
5032    //any Delete query needed, itemTextId is maximum of all ids
5033    std::ostringstream query;
5034    query << "INSERT INTO item_text (id,text) VALUES ( '" << newItemTextId << "', '" << text << "')";
5035    CharacterDatabase.Execute(query.str().c_str());         //needs to be run this way, because mail body may be more than 1024 characters
5036    return newItemTextId;
5037}
5038
5039uint32 ObjectMgr::GenerateLowGuid(HighGuid guidhigh)
5040{
5041    switch(guidhigh)
5042    {
5043        case HIGHGUID_ITEM:
5044            ++m_hiItemGuid;
5045            if(m_hiItemGuid>=0xFFFFFFFF)
5046            {
5047                sLog.outError("Item guid overflow!! Can't continue, shuting down server. ");
5048                sWorld.m_stopEvent = true;
5049            }
5050            return m_hiItemGuid;
5051        case HIGHGUID_UNIT:
5052            ++m_hiCreatureGuid;
5053            if(m_hiCreatureGuid>=0x00FFFFFF)
5054            {
5055                sLog.outError("Creature guid overflow!! Can't continue, shuting down server. ");
5056                sWorld.m_stopEvent = true;
5057            }
5058            return m_hiCreatureGuid;
5059        case HIGHGUID_PET:
5060            ++m_hiPetGuid;
5061            if(m_hiPetGuid>=0x00FFFFFF)
5062            {
5063                sLog.outError("Pet guid overflow!! Can't continue, shuting down server. ");
5064                sWorld.m_stopEvent = true;
5065            }
5066            return m_hiPetGuid;
5067        case HIGHGUID_PLAYER:
5068            ++m_hiCharGuid;
5069            if(m_hiCharGuid>=0xFFFFFFFF)
5070            {
5071                sLog.outError("Players guid overflow!! Can't continue, shuting down server. ");
5072                sWorld.m_stopEvent = true;
5073            }
5074            return m_hiCharGuid;
5075        case HIGHGUID_GAMEOBJECT:
5076            ++m_hiGoGuid;
5077            if(m_hiGoGuid>=0x00FFFFFF)
5078            {
5079                sLog.outError("Gameobject guid overflow!! Can't continue, shuting down server. ");
5080                sWorld.m_stopEvent = true;
5081            }
5082            return m_hiGoGuid;
5083        case HIGHGUID_CORPSE:
5084            ++m_hiCorpseGuid;
5085            if(m_hiCorpseGuid>=0xFFFFFFFF)
5086            {
5087                sLog.outError("Corpse guid overflow!! Can't continue, shuting down server. ");
5088                sWorld.m_stopEvent = true;
5089            }
5090            return m_hiCorpseGuid;
5091        case HIGHGUID_DYNAMICOBJECT:
5092            ++m_hiDoGuid;
5093            if(m_hiDoGuid>=0xFFFFFFFF)
5094            {
5095                sLog.outError("DynamicObject guid overflow!! Can't continue, shuting down server. ");
5096                sWorld.m_stopEvent = true;
5097            }
5098            return m_hiDoGuid;
5099        default:
5100            ASSERT(0);
5101    }
5102
5103    ASSERT(0);
5104    return 0;
5105}
5106
5107void ObjectMgr::LoadGameObjectLocales()
5108{
5109    QueryResult *result = WorldDatabase.Query("SELECT entry,"
5110        "name_loc1,name_loc2,name_loc3,name_loc4,name_loc5,name_loc6,name_loc7,name_loc8,"
5111        "castbarcaption_loc1,castbarcaption_loc2,castbarcaption_loc3,castbarcaption_loc4,"
5112        "castbarcaption_loc5,castbarcaption_loc6,castbarcaption_loc7,castbarcaption_loc8 FROM locales_gameobject");
5113
5114    if(!result)
5115    {
5116        barGoLink bar(1);
5117
5118        bar.step();
5119
5120        sLog.outString("");
5121        sLog.outString(">> Loaded 0 gameobject locale strings. DB table `locales_gameobject` is empty.");
5122        return;
5123    }
5124
5125    barGoLink bar(result->GetRowCount());
5126
5127    do
5128    {
5129        Field *fields = result->Fetch();
5130        bar.step();
5131
5132        uint32 entry = fields[0].GetUInt32();
5133
5134        GameObjectLocale& data = mGameObjectLocaleMap[entry];
5135
5136        for(int i = 1; i < MAX_LOCALE; ++i)
5137        {
5138            std::string str = fields[i].GetCppString();
5139            if(!str.empty())
5140            {
5141                int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5142                if(idx >= 0)
5143                {
5144                    if(data.Name.size() <= idx)
5145                        data.Name.resize(idx+1);
5146
5147                    data.Name[idx] = str;
5148                }
5149            }
5150        }
5151
5152        for(int i = MAX_LOCALE; i < MAX_LOCALE*2-1; ++i)
5153        {
5154            std::string str = fields[i].GetCppString();
5155            if(!str.empty())
5156            {
5157                int idx = GetOrNewIndexForLocale(LocaleConstant(i));
5158                if(idx >= 0)
5159                {
5160                    if(data.CastBarCaption.size() <= idx)
5161                        data.CastBarCaption.resize(idx+1);
5162
5163                    data.CastBarCaption[idx] = str;
5164                }
5165            }
5166        }
5167
5168    } while (result->NextRow());
5169
5170    delete result;
5171
5172    sLog.outString();
5173    sLog.outString( ">> Loaded %u gameobject locale strings", mGameObjectLocaleMap.size() );
5174}
5175
5176void ObjectMgr::LoadGameobjectInfo()
5177{
5178    sGOStorage.Load();
5179
5180    // some checks
5181    for(uint32 id = 1; id < sGOStorage.MaxEntry; id++)
5182    {
5183        GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(id);
5184        if(!goInfo)
5185            continue;
5186
5187        switch(goInfo->type)
5188        {
5189            case GAMEOBJECT_TYPE_DOOR:                      //0
5190            {
5191                if(goInfo->door.lockId)
5192                {
5193                    if(!sLockStore.LookupEntry(goInfo->door.lockId))
5194                        sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but lock (Id: %u) not found.",
5195                            id,goInfo->type,goInfo->door.lockId,goInfo->door.lockId);
5196                }
5197                break;
5198            }
5199            case GAMEOBJECT_TYPE_BUTTON:                    //1
5200            {
5201                if(goInfo->button.lockId)
5202                {
5203                    if(!sLockStore.LookupEntry(goInfo->button.lockId))
5204                        sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but lock (Id: %u) not found.",
5205                            id,goInfo->type,goInfo->button.lockId,goInfo->button.lockId);
5206                }
5207                break;
5208            }
5209            case GAMEOBJECT_TYPE_CHEST:                     //3
5210            {
5211                if(goInfo->chest.lockId)
5212                {
5213                    if(!sLockStore.LookupEntry(goInfo->chest.lockId))
5214                        sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but lock (Id: %u) not found.",
5215                            id,goInfo->type,goInfo->chest.lockId,goInfo->chest.lockId);
5216                }
5217                if(goInfo->chest.linkedTrapId)              // linked trap
5218                {
5219                    if(GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(goInfo->chest.linkedTrapId))
5220                    {
5221                        if(trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5222                            sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data7=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5223                                id,goInfo->type,goInfo->chest.linkedTrapId,goInfo->chest.linkedTrapId,GAMEOBJECT_TYPE_TRAP);
5224                    }
5225                    /* disable check for while
5226                    else
5227                        sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5228                            id,goInfo->type,goInfo->chest.linkedTrapId,goInfo->chest.linkedTrapId);
5229                    */
5230                }
5231                break;
5232            }
5233            case GAMEOBJECT_TYPE_TRAP:                      //6
5234            {
5235                /* disable check for while
5236                if(goInfo->trap.spellId)                    // spell
5237                {
5238                    if(!sSpellStore.LookupEntry(goInfo->trap.spellId))
5239                        sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data3=%u but Spell (Entry %u) not exist.",
5240                            id,goInfo->type,goInfo->trap.spellId,goInfo->trap.spellId);
5241                }
5242                */
5243                break;
5244            }
5245            case GAMEOBJECT_TYPE_CHAIR:                     //7
5246                if(goInfo->chair.height > 2)
5247                {
5248                    sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but correct chair height in range 0..2.",
5249                        id,goInfo->type,goInfo->chair.height);
5250
5251                    // prevent client and server unexpected work
5252                    const_cast<GameObjectInfo*>(goInfo)->chair.height = 0;
5253                }
5254                break;
5255            case GAMEOBJECT_TYPE_SPELL_FOCUS:               //8
5256            {
5257                if(goInfo->spellFocus.focusId)
5258                {
5259                    if(!sSpellFocusObjectStore.LookupEntry(goInfo->spellFocus.focusId))
5260                        sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but SpellFocus (Id: %u) not exist.",
5261                            id,goInfo->type,goInfo->spellFocus.focusId,goInfo->spellFocus.focusId);
5262                }
5263
5264                if(goInfo->spellFocus.linkedTrapId)         // linked trap
5265                {
5266                    if(GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(goInfo->spellFocus.linkedTrapId))
5267                    {
5268                        if(trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5269                            sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5270                                id,goInfo->type,goInfo->spellFocus.linkedTrapId,goInfo->spellFocus.linkedTrapId,GAMEOBJECT_TYPE_TRAP);
5271                    }
5272                    /* disable check for while
5273                    else
5274                        sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5275                            id,goInfo->type,goInfo->spellFocus.linkedTrapId,goInfo->spellFocus.linkedTrapId);
5276                    */
5277                }
5278                break;
5279            }
5280            case GAMEOBJECT_TYPE_GOOBER:                    //10
5281            {
5282                if(goInfo->goober.pageId)                   // pageId
5283                {
5284                    if(!sPageTextStore.LookupEntry<PageText>(goInfo->goober.pageId))
5285                        sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data7=%u but PageText (Entry %u) not exist.",
5286                            id,goInfo->type,goInfo->goober.pageId,goInfo->goober.pageId);
5287                }
5288                /* disable check for while
5289                if(goInfo->goober.spellId)                  // spell
5290                {
5291                    if(!sSpellStore.LookupEntry(goInfo->goober.spellId))
5292                        sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data2=%u but Spell (Entry %u) not exist.",
5293                            id,goInfo->type,goInfo->goober.spellId,goInfo->goober.spellId);
5294                }
5295                */
5296                if(goInfo->goober.linkedTrapId)             // linked trap
5297                {
5298                    if(GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(goInfo->goober.linkedTrapId))
5299                    {
5300                        if(trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
5301                            sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data12=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.",
5302                                id,goInfo->type,goInfo->goober.linkedTrapId,goInfo->goober.linkedTrapId,GAMEOBJECT_TYPE_TRAP);
5303                    }
5304                    /* disable check for while
5305                    else
5306                        sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data12=%u but trap GO (Entry %u) not exist in `gameobject_template`.",
5307                            id,goInfo->type,goInfo->goober.linkedTrapId,goInfo->goober.linkedTrapId);
5308                    */
5309                }
5310                break;
5311            }
5312            case GAMEOBJECT_TYPE_MO_TRANSPORT:              //15
5313            {
5314                if(goInfo->moTransport.taxiPathId)
5315                {
5316                    if(goInfo->moTransport.taxiPathId >= sTaxiPathNodesByPath.size() || sTaxiPathNodesByPath[goInfo->moTransport.taxiPathId].empty())
5317                        sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data0=%u but TaxiPath (Id: %u) not exist.",
5318                            id,goInfo->type,goInfo->moTransport.taxiPathId,goInfo->moTransport.taxiPathId);
5319                }
5320                break;
5321            }
5322            case GAMEOBJECT_TYPE_SUMMONING_RITUAL:          //18
5323            {
5324                /* disabled
5325                if(goInfo->summoningRitual.spellId)
5326                {
5327                    if(!sSpellStore.LookupEntry(goInfo->summoningRitual.spellId))
5328                        sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data1=%u but Spell (Entry %u) not exist.",
5329                            id,goInfo->type,goInfo->summoningRitual.spellId,goInfo->summoningRitual.spellId);
5330                }
5331                */
5332                break;
5333            }
5334            case GAMEOBJECT_TYPE_SPELLCASTER:               //22
5335            {
5336                if(goInfo->spellcaster.spellId)             // spell
5337                {
5338                    if(!sSpellStore.LookupEntry(goInfo->spellcaster.spellId))
5339                        sLog.outErrorDb("Gameobject (Entry: %u GoType: %u) have data3=%u but Spell (Entry %u) not exist.",
5340                            id,goInfo->type,goInfo->spellcaster.spellId,goInfo->spellcaster.spellId);
5341                }
5342                break;
5343            }
5344        }
5345    }
5346
5347    sLog.outString( ">> Loaded %u game object templates", sGOStorage.RecordCount );
5348    sLog.outString();
5349}
5350
5351void ObjectMgr::LoadExplorationBaseXP()
5352{
5353    uint32 count = 0;
5354    QueryResult *result = WorldDatabase.Query("SELECT level,basexp FROM exploration_basexp");
5355
5356    if( !result )
5357    {
5358        barGoLink bar( 1 );
5359
5360        bar.step();
5361
5362        sLog.outString();
5363        sLog.outString( ">> Loaded %u BaseXP definitions", count );
5364        return;
5365    }
5366
5367    barGoLink bar( result->GetRowCount() );
5368
5369    do
5370    {
5371        bar.step();
5372
5373        Field *fields = result->Fetch();
5374        uint32 level  = fields[0].GetUInt32();
5375        uint32 basexp = fields[1].GetUInt32();
5376        mBaseXPTable[level] = basexp;
5377        ++count;
5378    }
5379    while (result->NextRow());
5380
5381    delete result;
5382
5383    sLog.outString();
5384    sLog.outString( ">> Loaded %u BaseXP definitions", count );
5385}
5386
5387uint32 ObjectMgr::GetBaseXP(uint32 level)
5388{
5389    return mBaseXPTable[level] ? mBaseXPTable[level] : 0;
5390}
5391
5392void ObjectMgr::LoadPetNames()
5393{
5394    uint32 count = 0;
5395    QueryResult *result = WorldDatabase.Query("SELECT word,entry,half FROM pet_name_generation");
5396
5397    if( !result )
5398    {
5399        barGoLink bar( 1 );
5400
5401        bar.step();
5402
5403        sLog.outString();
5404        sLog.outString( ">> Loaded %u pet name parts", count );
5405        return;
5406    }
5407
5408    barGoLink bar( result->GetRowCount() );
5409
5410    do
5411    {
5412        bar.step();
5413
5414        Field *fields = result->Fetch();
5415        std::string word = fields[0].GetString();
5416        uint32 entry     = fields[1].GetUInt32();
5417        bool   half      = fields[2].GetBool();
5418        if(half)
5419            PetHalfName1[entry].push_back(word);
5420        else
5421            PetHalfName0[entry].push_back(word);
5422        ++count;
5423    }
5424    while (result->NextRow());
5425    delete result;
5426
5427    sLog.outString();
5428    sLog.outString( ">> Loaded %u pet name parts", count );
5429}
5430
5431void ObjectMgr::LoadPetNumber()
5432{
5433    QueryResult* result = CharacterDatabase.Query("SELECT MAX(id) FROM character_pet");
5434    if(result)
5435    {
5436        Field *fields = result->Fetch();
5437        m_hiPetNumber = fields[0].GetUInt32()+1;
5438        delete result;
5439    }
5440
5441    barGoLink bar( 1 );
5442    bar.step();
5443
5444    sLog.outString();
5445    sLog.outString( ">> Loaded the max pet number: %d", m_hiPetNumber-1);
5446}
5447
5448std::string ObjectMgr::GeneratePetName(uint32 entry)
5449{
5450    std::vector<std::string> & list0 = PetHalfName0[entry];
5451    std::vector<std::string> & list1 = PetHalfName1[entry];
5452
5453    if(list0.empty() || list1.empty())
5454    {
5455        CreatureInfo const *cinfo = GetCreatureTemplate(entry);
5456        char* petname = GetPetName(cinfo->family, sWorld.GetDefaultDbcLocale());
5457        if(!petname)
5458            petname = cinfo->Name;
5459        return std::string(petname);
5460    }
5461
5462    return *(list0.begin()+urand(0, list0.size()-1)) + *(list1.begin()+urand(0, list1.size()-1));
5463}
5464
5465uint32 ObjectMgr::GeneratePetNumber()
5466{
5467    return ++m_hiPetNumber;
5468}
5469
5470void ObjectMgr::LoadCorpses()
5471{
5472    uint32 count = 0;
5473    //                                                     0           1           2           3            4    5     6     7            8         10
5474    QueryResult *result = CharacterDatabase.PQuery("SELECT position_x, position_y, position_z, orientation, map, data, time, corpse_type, instance, guid FROM corpse WHERE corpse_type <> 0");
5475
5476    if( !result )
5477    {
5478        barGoLink bar( 1 );
5479
5480        bar.step();
5481
5482        sLog.outString();
5483        sLog.outString( ">> Loaded %u corpses", count );
5484        return;
5485    }
5486
5487    barGoLink bar( result->GetRowCount() );
5488
5489    do
5490    {
5491        bar.step();
5492
5493        Field *fields = result->Fetch();
5494
5495        uint32 guid = fields[result->GetFieldCount()-1].GetUInt32();
5496
5497        Corpse *corpse = new Corpse;
5498        if(!corpse->LoadFromDB(guid,fields))
5499        {
5500            delete corpse;
5501            continue;
5502        }
5503
5504        ObjectAccessor::Instance().AddCorpse(corpse);
5505
5506        ++count;
5507    }
5508    while (result->NextRow());
5509    delete result;
5510
5511    sLog.outString();
5512    sLog.outString( ">> Loaded %u corpses", count );
5513}
5514
5515void ObjectMgr::LoadReputationOnKill()
5516{
5517    uint32 count = 0;
5518
5519    //                                                0            1                     2
5520    QueryResult *result = WorldDatabase.Query("SELECT creature_id, RewOnKillRepFaction1, RewOnKillRepFaction2,"
5521    //   3             4             5                   6             7             8                   9
5522        "IsTeamAward1, MaxStanding1, RewOnKillRepValue1, IsTeamAward2, MaxStanding2, RewOnKillRepValue2, TeamDependent "
5523        "FROM creature_onkill_reputation");
5524
5525    if(!result)
5526    {
5527        barGoLink bar(1);
5528
5529        bar.step();
5530
5531        sLog.outString();
5532        sLog.outErrorDb(">> Loaded 0 creature award reputation definitions. DB table `creature_onkill_reputation` is empty.");
5533        return;
5534    }
5535
5536    barGoLink bar(result->GetRowCount());
5537
5538    do
5539    {
5540        Field *fields = result->Fetch();
5541        bar.step();
5542
5543        uint32 creature_id = fields[0].GetUInt32();
5544
5545        ReputationOnKillEntry repOnKill;
5546        repOnKill.repfaction1          = fields[1].GetUInt32();
5547        repOnKill.repfaction2          = fields[2].GetUInt32();
5548        repOnKill.is_teamaward1        = fields[3].GetBool();
5549        repOnKill.reputation_max_cap1  = fields[4].GetUInt32();
5550        repOnKill.repvalue1            = fields[5].GetInt32();
5551        repOnKill.is_teamaward2        = fields[6].GetBool();
5552        repOnKill.reputation_max_cap2  = fields[7].GetUInt32();
5553        repOnKill.repvalue2            = fields[8].GetInt32();
5554        repOnKill.team_dependent       = fields[9].GetUInt8();
5555
5556        if(!GetCreatureTemplate(creature_id))
5557        {
5558            sLog.outErrorDb("Table `creature_onkill_reputation` have data for not existed creature entry (%u), skipped",creature_id);
5559            continue;
5560        }
5561
5562        if(repOnKill.repfaction1)
5563        {
5564            FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(repOnKill.repfaction1);
5565            if(!factionEntry1)
5566            {
5567                sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction1);
5568                continue;
5569            }
5570        }
5571
5572        if(repOnKill.repfaction2)
5573        {
5574            FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(repOnKill.repfaction2);
5575            if(!factionEntry2)
5576            {
5577                sLog.outErrorDb("Faction (faction.dbc) %u does not exist but is used in `creature_onkill_reputation`",repOnKill.repfaction2);
5578                continue;
5579            }
5580        }
5581
5582        mRepOnKill[creature_id] = repOnKill;
5583
5584        ++count;
5585    } while (result->NextRow());
5586
5587    delete result;
5588
5589    sLog.outString();
5590    sLog.outString(">> Loaded %u creature award reputation definitions", count);
5591}
5592
5593void ObjectMgr::LoadWeatherZoneChances()
5594{
5595    uint32 count = 0;
5596
5597    //                                                0     1                   2                   3                    4                   5                   6                    7                 8                 9                  10                  11                  12
5598    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");
5599
5600    if(!result)
5601    {
5602        barGoLink bar(1);
5603
5604        bar.step();
5605
5606        sLog.outString();
5607        sLog.outErrorDb(">> Loaded 0 weather definitions. DB table `game_weather` is empty.");
5608        return;
5609    }
5610
5611    barGoLink bar(result->GetRowCount());
5612
5613    do
5614    {
5615        Field *fields = result->Fetch();
5616        bar.step();
5617
5618        uint32 zone_id = fields[0].GetUInt32();
5619
5620        WeatherZoneChances& wzc = mWeatherZoneMap[zone_id];
5621
5622        for(int season = 0; season < WEATHER_SEASONS; ++season)
5623        {
5624            wzc.data[season].rainChance  = fields[season * (MAX_WEATHER_TYPE-1) + 1].GetUInt32();
5625            wzc.data[season].snowChance  = fields[season * (MAX_WEATHER_TYPE-1) + 2].GetUInt32();
5626            wzc.data[season].stormChance = fields[season * (MAX_WEATHER_TYPE-1) + 3].GetUInt32();
5627
5628            if(wzc.data[season].rainChance > 100)
5629            {
5630                wzc.data[season].rainChance = 25;
5631                sLog.outErrorDb("Weather for zone %u season %u has wrong rain chance > 100%",zone_id,season);
5632            }
5633
5634            if(wzc.data[season].snowChance > 100)
5635            {
5636                wzc.data[season].snowChance = 25;
5637                sLog.outErrorDb("Weather for zone %u season %u has wrong snow chance > 100%",zone_id,season);
5638            }
5639
5640            if(wzc.data[season].stormChance > 100)
5641            {
5642                wzc.data[season].stormChance = 25;
5643                sLog.outErrorDb("Weather for zone %u season %u has wrong storm chance > 100%",zone_id,season);
5644            }
5645        }
5646
5647        ++count;
5648    } while (result->NextRow());
5649
5650    delete result;
5651
5652    sLog.outString();
5653    sLog.outString(">> Loaded %u weather definitions", count);
5654}
5655
5656void ObjectMgr::SaveCreatureRespawnTime(uint32 loguid, uint32 instance, time_t t)
5657{
5658    mCreatureRespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
5659    WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
5660    if(t)
5661        WorldDatabase.PExecute("INSERT INTO creature_respawn VALUES ( '%u', '" I64FMTD "', '%u' )", loguid, uint64(t), instance);
5662}
5663
5664void ObjectMgr::DeleteCreatureData(uint32 guid)
5665{
5666    // remove mapid*cellid -> guid_set map
5667    CreatureData const* data = GetCreatureData(guid);
5668    if(data)
5669        RemoveCreatureFromGrid(guid, data);
5670
5671    mCreatureDataMap.erase(guid);
5672}
5673
5674void ObjectMgr::SaveGORespawnTime(uint32 loguid, uint32 instance, time_t t)
5675{
5676    mGORespawnTimes[MAKE_PAIR64(loguid,instance)] = t;
5677    WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE guid = '%u' AND instance = '%u'", loguid, instance);
5678    if(t)
5679        WorldDatabase.PExecute("INSERT INTO gameobject_respawn VALUES ( '%u', '" I64FMTD "', '%u' )", loguid, uint64(t), instance);
5680}
5681
5682void ObjectMgr::DeleteRespawnTimeForInstance(uint32 instance)
5683{
5684    RespawnTimes::iterator next;
5685
5686    for(RespawnTimes::iterator itr = mGORespawnTimes.begin(); itr != mGORespawnTimes.end(); itr = next)
5687    {
5688        next = itr;
5689        ++next;
5690
5691        if(GUID_HIPART(itr->first)==instance)
5692            mGORespawnTimes.erase(itr);
5693    }
5694
5695    for(RespawnTimes::iterator itr = mCreatureRespawnTimes.begin(); itr != mCreatureRespawnTimes.end(); itr = next)
5696    {
5697        next = itr;
5698        ++next;
5699
5700        if(GUID_HIPART(itr->first)==instance)
5701            mCreatureRespawnTimes.erase(itr);
5702    }
5703
5704    WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE instance = '%u'", instance);
5705    WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE instance = '%u'", instance);
5706}
5707
5708void ObjectMgr::DeleteGOData(uint32 guid)
5709{
5710    // remove mapid*cellid -> guid_set map
5711    GameObjectData const* data = GetGOData(guid);
5712    if(data)
5713        RemoveGameobjectFromGrid(guid, data);
5714
5715    mGameObjectDataMap.erase(guid);
5716}
5717
5718void ObjectMgr::AddCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid, uint32 instance)
5719{
5720    // corpses are always added to spawn mode 0 and they are spawned by their instance id
5721    CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
5722    cell_guids.corpses[player_guid] = instance;
5723}
5724
5725void ObjectMgr::DeleteCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid)
5726{
5727    // corpses are always added to spawn mode 0 and they are spawned by their instance id
5728    CellObjectGuids& cell_guids = mMapObjectGuids[MAKE_PAIR32(mapid,0)][cellid];
5729    cell_guids.corpses.erase(player_guid);
5730}
5731
5732void ObjectMgr::LoadQuestRelationsHelper(QuestRelations& map,char const* table)
5733{
5734    map.clear();                                            // need for reload case
5735
5736    uint32 count = 0;
5737
5738    QueryResult *result = WorldDatabase.PQuery("SELECT id,quest FROM %s",table);
5739
5740    if(!result)
5741    {
5742        barGoLink bar(1);
5743
5744        bar.step();
5745
5746        sLog.outString();
5747        sLog.outErrorDb(">> Loaded 0 quest relations from %s. DB table `%s` is empty.",table,table);
5748        return;
5749    }
5750
5751    barGoLink bar(result->GetRowCount());
5752
5753    do
5754    {
5755        Field *fields = result->Fetch();
5756        bar.step();
5757
5758        uint32 id    = fields[0].GetUInt32();
5759        uint32 quest = fields[1].GetUInt32();
5760
5761        if(mQuestTemplates.find(quest) == mQuestTemplates.end())
5762        {
5763            sLog.outErrorDb("Table `%s: Quest %u listed for entry %u does not exist.",table,quest,id);
5764            continue;
5765        }
5766
5767        map.insert(QuestRelations::value_type(id,quest));
5768
5769        ++count;
5770    } while (result->NextRow());
5771
5772    delete result;
5773
5774    sLog.outString();
5775    sLog.outString(">> Loaded %u quest relations from %s", count,table);
5776}
5777
5778void ObjectMgr::LoadGameobjectQuestRelations()
5779{
5780    LoadQuestRelationsHelper(mGOQuestRelations,"gameobject_questrelation");
5781
5782    for(QuestRelations::iterator itr = mGOQuestRelations.begin(); itr != mGOQuestRelations.end(); ++itr)
5783    {
5784        GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
5785        if(!goInfo)
5786            sLog.outErrorDb("Table `gameobject_questrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
5787        else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
5788            sLog.outErrorDb("Table `gameobject_questrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
5789    }
5790}
5791
5792void ObjectMgr::LoadGameobjectInvolvedRelations()
5793{
5794    LoadQuestRelationsHelper(mGOQuestInvolvedRelations,"gameobject_involvedrelation");
5795
5796    for(QuestRelations::iterator itr = mGOQuestInvolvedRelations.begin(); itr != mGOQuestInvolvedRelations.end(); ++itr)
5797    {
5798        GameObjectInfo const* goInfo = GetGameObjectInfo(itr->first);
5799        if(!goInfo)
5800            sLog.outErrorDb("Table `gameobject_involvedrelation` have data for not existed gameobject entry (%u) and existed quest %u",itr->first,itr->second);
5801        else if(goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER)
5802            sLog.outErrorDb("Table `gameobject_involvedrelation` have data gameobject entry (%u) for quest %u, but GO is not GAMEOBJECT_TYPE_QUESTGIVER",itr->first,itr->second);
5803    }
5804}
5805
5806void ObjectMgr::LoadCreatureQuestRelations()
5807{
5808    LoadQuestRelationsHelper(mCreatureQuestRelations,"creature_questrelation");
5809
5810    for(QuestRelations::iterator itr = mCreatureQuestRelations.begin(); itr != mCreatureQuestRelations.end(); ++itr)
5811    {
5812        CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
5813        if(!cInfo)
5814            sLog.outErrorDb("Table `creature_questrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
5815        else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
5816            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);
5817    }
5818}
5819
5820void ObjectMgr::LoadCreatureInvolvedRelations()
5821{
5822    LoadQuestRelationsHelper(mCreatureQuestInvolvedRelations,"creature_involvedrelation");
5823
5824    for(QuestRelations::iterator itr = mCreatureQuestInvolvedRelations.begin(); itr != mCreatureQuestInvolvedRelations.end(); ++itr)
5825    {
5826        CreatureInfo const* cInfo = GetCreatureTemplate(itr->first);
5827        if(!cInfo)
5828            sLog.outErrorDb("Table `creature_involvedrelation` have data for not existed creature entry (%u) and existed quest %u",itr->first,itr->second);
5829        else if(!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER))
5830            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);
5831    }
5832}
5833
5834void ObjectMgr::LoadReservedPlayersNames()
5835{
5836    m_ReservedNames.clear();                                // need for reload case
5837
5838    QueryResult *result = WorldDatabase.PQuery("SELECT name FROM reserved_name");
5839
5840    uint32 count = 0;
5841
5842    if( !result )
5843    {
5844        barGoLink bar( 1 );
5845        bar.step();
5846
5847        sLog.outString();
5848        sLog.outString( ">> Loaded %u reserved player names", count );
5849        return;
5850    }
5851
5852    barGoLink bar( result->GetRowCount() );
5853
5854    Field* fields;
5855    do
5856    {
5857        bar.step();
5858        fields = result->Fetch();
5859        std::string name= fields[0].GetCppString();
5860        if(normalizePlayerName(name))
5861        {
5862            m_ReservedNames.insert(name);
5863            ++count;
5864        }
5865    } while ( result->NextRow() );
5866
5867    delete result;
5868
5869    sLog.outString();
5870    sLog.outString( ">> Loaded %u reserved player names", count );
5871}
5872
5873enum LanguageType
5874{
5875    LT_BASIC_LATIN    = 0x0000,
5876    LT_EXTENDEN_LATIN = 0x0001,
5877    LT_CYRILLIC       = 0x0002,
5878    LT_EAST_ASIA      = 0x0004,
5879    LT_ANY            = 0xFFFF
5880};
5881
5882static LanguageType GetRealmLanguageType(bool create)
5883{
5884    switch(sWorld.getConfig(CONFIG_REALM_ZONE))
5885    {
5886        case REALM_ZONE_UNKNOWN:                            // any language
5887        case REALM_ZONE_DEVELOPMENT:
5888        case REALM_ZONE_TEST_SERVER:
5889        case REALM_ZONE_QA_SERVER:
5890            return LT_ANY;
5891        case REALM_ZONE_UNITED_STATES:                      // extended-Latin
5892        case REALM_ZONE_OCEANIC:
5893        case REALM_ZONE_LATIN_AMERICA:
5894        case REALM_ZONE_ENGLISH:
5895        case REALM_ZONE_GERMAN:
5896        case REALM_ZONE_FRENCH:
5897        case REALM_ZONE_SPANISH:
5898            return LT_EXTENDEN_LATIN;
5899        case REALM_ZONE_KOREA:                              // East-Asian
5900        case REALM_ZONE_TAIWAN:
5901        case REALM_ZONE_CHINA:
5902            return LT_EAST_ASIA;
5903        case REALM_ZONE_RUSSIAN:                            // Cyrillic
5904            return LT_CYRILLIC;
5905        default:
5906            return create ? LT_BASIC_LATIN : LT_ANY;        // basic-Latin at create, any at login
5907    }
5908}
5909
5910bool isValidString(std::wstring wstr, uint32 strictMask, bool numericOrSpace, bool create = false)
5911{
5912    if(strictMask==0)                                       // any language, ignore realm
5913    {
5914        if(isExtendedLatinString(wstr,numericOrSpace))
5915            return true;
5916        if(isCyrillicString(wstr,numericOrSpace))
5917            return true;
5918        if(isEastAsianString(wstr,numericOrSpace))
5919            return true;
5920        return false;
5921    }
5922
5923    if(strictMask & 0x2)                                    // realm zone specific
5924    {
5925        LanguageType lt = GetRealmLanguageType(create);
5926        if(lt & LT_EXTENDEN_LATIN)
5927            if(isExtendedLatinString(wstr,numericOrSpace))
5928                return true;
5929        if(lt & LT_CYRILLIC)
5930            if(isCyrillicString(wstr,numericOrSpace))
5931                return true;
5932        if(lt & LT_EAST_ASIA)
5933            if(isEastAsianString(wstr,numericOrSpace))
5934                return true;
5935    }
5936
5937    if(strictMask & 0x1)                                    // basic latin
5938    {
5939        if(isBasicLatinString(wstr,numericOrSpace))
5940            return true;
5941    }
5942
5943    return false;
5944}
5945
5946bool ObjectMgr::IsValidName( std::string name, bool create )
5947{
5948    std::wstring wname;
5949    if(!Utf8toWStr(name,wname))
5950        return false;
5951
5952    if(wname.size() < 1 || wname.size() > MAX_PLAYER_NAME)
5953        return false;
5954
5955    uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_PLAYER_NAMES);
5956
5957    return isValidString(wname,strictMask,false,create);
5958}
5959
5960bool ObjectMgr::IsValidCharterName( std::string name )
5961{
5962    std::wstring wname;
5963    if(!Utf8toWStr(name,wname))
5964        return false;
5965
5966    if(wname.size() < 1)
5967        return false;
5968
5969    uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_CHARTER_NAMES);
5970
5971    return isValidString(wname,strictMask,true);
5972}
5973
5974bool ObjectMgr::IsValidPetName( std::string name )
5975{
5976    std::wstring wname;
5977    if(!Utf8toWStr(name,wname))
5978        return false;
5979
5980    if(wname.size() < 1)
5981        return false;
5982
5983    uint32 strictMask = sWorld.getConfig(CONFIG_STRICT_PET_NAMES);
5984
5985    return isValidString(wname,strictMask,false);
5986}
5987
5988int ObjectMgr::GetIndexForLocale( LocaleConstant loc )
5989{
5990    if(loc==LOCALE_enUS)
5991        return -1;
5992
5993    for(size_t i=0;i < m_LocalForIndex.size(); ++i)
5994        if(m_LocalForIndex[i]==loc)
5995            return i;
5996
5997    return -1;
5998}
5999
6000LocaleConstant ObjectMgr::GetLocaleForIndex(int i)
6001{
6002    if (i<0 || i>=m_LocalForIndex.size())
6003        return LOCALE_enUS;
6004
6005    return m_LocalForIndex[i];
6006}
6007
6008int ObjectMgr::GetOrNewIndexForLocale( LocaleConstant loc )
6009{
6010    if(loc==LOCALE_enUS)
6011        return -1;
6012
6013    for(size_t i=0;i < m_LocalForIndex.size(); ++i)
6014        if(m_LocalForIndex[i]==loc)
6015            return i;
6016
6017    m_LocalForIndex.push_back(loc);
6018    return m_LocalForIndex.size()-1;
6019}
6020
6021void ObjectMgr::LoadBattleMastersEntry()
6022{
6023    mBattleMastersMap.clear();                              // need for reload case
6024
6025    QueryResult *result = WorldDatabase.Query( "SELECT entry,bg_template FROM battlemaster_entry" );
6026
6027    uint32 count = 0;
6028
6029    if( !result )
6030    {
6031        barGoLink bar( 1 );
6032        bar.step();
6033
6034        sLog.outString();
6035        sLog.outString( ">> Loaded 0 battlemaster entries - table is empty!" );
6036        return;
6037    }
6038
6039    barGoLink bar( result->GetRowCount() );
6040
6041    do
6042    {
6043        ++count;
6044        bar.step();
6045
6046        Field *fields = result->Fetch();
6047
6048        uint32 entry = fields[0].GetUInt32();
6049        uint32 bgTypeId  = fields[1].GetUInt32();
6050
6051        mBattleMastersMap[entry] = bgTypeId;
6052
6053    } while( result->NextRow() );
6054
6055    delete result;
6056
6057    sLog.outString();
6058    sLog.outString( ">> Loaded %u battlemaster entries", count );
6059}
6060
6061void ObjectMgr::LoadGameObjectForQuests()
6062{
6063    mGameObjectForQuestSet.clear();                         // need for reload case
6064
6065    uint32 count = 0;
6066
6067    // collect GO entries for GO that must activated
6068    for(uint32 go_entry = 1; go_entry < sGOStorage.MaxEntry; ++go_entry)
6069    {
6070        GameObjectInfo const* goInfo = sGOStorage.LookupEntry<GameObjectInfo>(go_entry);
6071        if(!goInfo)
6072            continue;
6073
6074        switch(goInfo->type)
6075        {
6076            // scan GO chest with loot including quest items
6077            case GAMEOBJECT_TYPE_CHEST:
6078            {
6079                uint32 loot_id = GameObject::GetLootId(goInfo);
6080
6081                // find quest loot for GO
6082                if(LootTemplates_Gameobject.HaveQuestLootFor(loot_id))
6083                {
6084                    mGameObjectForQuestSet.insert(go_entry);
6085                    ++count;
6086                }
6087                break;
6088            }
6089            case GAMEOBJECT_TYPE_GOOBER:
6090            {
6091                if(goInfo->goober.questId)                  //quests objects
6092                {
6093                    mGameObjectForQuestSet.insert(go_entry);
6094                    count++;
6095                }
6096                break;
6097            }
6098            default:
6099                break;
6100        }
6101    }
6102
6103    sLog.outString();
6104    sLog.outString( ">> Loaded %u GameObject for quests", count );
6105}
6106
6107bool ObjectMgr::LoadMangosStrings(DatabaseType& db, char const* table, int32 min_value, int32 max_value)
6108{
6109    // cleanup affected map part for reloading case
6110    for(MangosStringLocaleMap::iterator itr = mMangosStringLocaleMap.begin(); itr != mMangosStringLocaleMap.end();)
6111    {
6112        if(itr->first >= min_value && itr->first <= max_value)
6113        {
6114            MangosStringLocaleMap::iterator itr2 = itr;
6115            ++itr;
6116            mMangosStringLocaleMap.erase(itr2);
6117        }
6118        else
6119            ++itr;
6120    }
6121
6122    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);
6123
6124    if(!result)
6125    {
6126        barGoLink bar(1);
6127
6128        bar.step();
6129
6130        sLog.outString("");
6131        if(min_value > 0)                                   // error only in case internal strings
6132            sLog.outErrorDb(">> Loaded 0 mangos strings. DB table `%s` is empty. Cannot continue.",table);
6133        else
6134            sLog.outString(">> Loaded 0 string templates. DB table `%s` is empty.",table);
6135        return false;
6136    }
6137
6138    uint32 count = 0;
6139
6140    barGoLink bar(result->GetRowCount());
6141
6142    do
6143    {
6144        Field *fields = result->Fetch();
6145        bar.step();
6146
6147        int32 entry = fields[0].GetInt32();
6148
6149        if(entry==0)
6150        {
6151            sLog.outString("Table `%s` contain reserved entry 0, ignored.",table);
6152            continue;
6153        }
6154        else if(entry < min_value || entry > max_value)
6155        {
6156            int32 start = min_value > 0 ? min_value : max_value;
6157            int32 end   = min_value > 0 ? max_value : min_value;
6158            sLog.outString("Table `%s` contain entry %i out of allowed range (%d - %d), ignored.",table,entry,start,end);
6159            continue;
6160        }
6161
6162        MangosStringLocale& data = mMangosStringLocaleMap[entry];
6163
6164        if(data.Content.size() > 0)
6165        {
6166            sLog.outString("Table `%s` contain data for already loaded entry  %i (from another table?), ignored.",table,entry);
6167            continue;
6168        }
6169
6170        data.Content.resize(1);
6171        ++count;
6172
6173        // 0 -> default, idx in to idx+1
6174        data.Content[0] = fields[1].GetCppString();
6175
6176        for(int i = 1; i < MAX_LOCALE; ++i)
6177        {
6178            std::string str = fields[i+1].GetCppString();
6179            if(!str.empty())
6180            {
6181                int idx = GetOrNewIndexForLocale(LocaleConstant(i));
6182                if(idx >= 0)
6183                {
6184                    // 0 -> default, idx in to idx+1
6185                    if(data.Content.size() <= idx+1)
6186                        data.Content.resize(idx+2);
6187
6188                    data.Content[idx+1] = str;
6189                }
6190            }
6191        }
6192    } while (result->NextRow());
6193
6194    delete result;
6195
6196    sLog.outString();
6197    if(min_value > 0)                                       // internal mangos strings
6198        sLog.outString( ">> Loaded %u MaNGOS strings from table %s", count,table);
6199    else
6200        sLog.outString( ">> Loaded %u string templates from %s", count,table);
6201
6202    return true;
6203}
6204
6205const char *ObjectMgr::GetMangosString(int32 entry, int locale_idx) const
6206{
6207    // locale_idx==-1 -> default, locale_idx >= 0 in to idx+1
6208    // Content[0] always exist if exist MangosStringLocale
6209    if(MangosStringLocale const *msl = GetMangosStringLocale(entry))
6210    {
6211        if(msl->Content.size() > locale_idx+1 && !msl->Content[locale_idx+1].empty())
6212            return msl->Content[locale_idx+1].c_str();
6213        else
6214            return msl->Content[0].c_str();
6215    }
6216
6217    if(entry > 0)
6218        sLog.outErrorDb("Entry %i not found in `mangos_string` table.",entry);
6219    else
6220        sLog.outErrorDb("Mangos string entry %i not found in DB.",entry);
6221    return "<error>";
6222}
6223
6224void ObjectMgr::LoadFishingBaseSkillLevel()
6225{
6226    mFishingBaseForArea.clear();                            // for relaod case
6227
6228    uint32 count = 0;
6229    QueryResult *result = WorldDatabase.Query("SELECT entry,skill FROM skill_fishing_base_level");
6230
6231    if( !result )
6232    {
6233        barGoLink bar( 1 );
6234
6235        bar.step();
6236
6237        sLog.outString();
6238        sLog.outErrorDb(">> Loaded `skill_fishing_base_level`, table is empty!");
6239        return;
6240    }
6241
6242    barGoLink bar( result->GetRowCount() );
6243
6244    do
6245    {
6246        bar.step();
6247
6248        Field *fields = result->Fetch();
6249        uint32 entry  = fields[0].GetUInt32();
6250        int32 skill   = fields[1].GetInt32();
6251
6252        AreaTableEntry const* fArea = GetAreaEntryByAreaID(entry);
6253        if(!fArea)
6254        {
6255            sLog.outErrorDb("AreaId %u defined in `skill_fishing_base_level` does not exist",entry);
6256            continue;
6257        }
6258
6259        mFishingBaseForArea[entry] = skill;
6260        ++count;
6261    }
6262    while (result->NextRow());
6263
6264    delete result;
6265
6266    sLog.outString();
6267    sLog.outString( ">> Loaded %u areas for fishing base skill level", count );
6268}
6269
6270// Searches for the same condition already in Conditions store
6271// Returns Id if found, else adds it to Conditions and returns Id
6272uint16 ObjectMgr::GetConditionId( ConditionType condition, uint32 value1, uint32 value2 )
6273{
6274    PlayerCondition lc = PlayerCondition(condition, value1, value2);
6275    for (uint16 i=0; i < mConditions.size(); ++i)
6276    {
6277        if (lc == mConditions[i])
6278            return i;
6279    }
6280
6281    mConditions.push_back(lc);
6282
6283    if(mConditions.size() > 0xFFFF)
6284    {
6285        sLog.outError("Conditions store overflow! Current and later loaded conditions will ignored!");
6286        return 0;
6287    }
6288
6289    return mConditions.size() - 1;
6290}
6291
6292bool ObjectMgr::CheckDeclinedNames( std::wstring mainpart, DeclinedName const& names )
6293{
6294    for(int i =0; i < MAX_DECLINED_NAME_CASES; ++i)
6295    {
6296        std::wstring wname;
6297        if(!Utf8toWStr(names.name[i],wname))
6298            return false;
6299
6300        if(mainpart!=GetMainPartOfName(wname,i+1))
6301            return false;
6302    }
6303    return true;
6304}
6305
6306const char* ObjectMgr::GetAreaTriggerScriptName(uint32 id)
6307{
6308    AreaTriggerScriptMap::const_iterator i = mAreaTriggerScripts.find(id);
6309    if(i!= mAreaTriggerScripts.end())
6310        return i->second.c_str();
6311    return "";
6312}
6313
6314// Checks if player meets the condition
6315bool PlayerCondition::Meets(Player const * player) const
6316{
6317    if( !player )
6318        return false;                                       // player not present, return false
6319
6320    switch (condition)
6321    {
6322        case CONDITION_NONE:
6323            return true;                                    // empty condition, always met
6324        case CONDITION_AURA:
6325            return player->HasAura(value1, value2);
6326        case CONDITION_ITEM:
6327            return player->HasItemCount(value1, value2);
6328        case CONDITION_ITEM_EQUIPPED:
6329            return player->GetItemOrItemWithGemEquipped(value1) != NULL;
6330        case CONDITION_ZONEID:
6331            return player->GetZoneId() == value1;
6332        case CONDITION_REPUTATION_RANK:
6333        {
6334            FactionEntry const* faction = sFactionStore.LookupEntry(value1);
6335            return faction && player->GetReputationRank(faction) >= value2;
6336        }
6337        case CONDITION_TEAM:
6338            return player->GetTeam() == value1;
6339        case CONDITION_SKILL:
6340            return player->HasSkill(value1) && player->GetBaseSkillValue(value1) >= value2;
6341        case CONDITION_QUESTREWARDED:
6342            return player->GetQuestRewardStatus(value1);
6343        case CONDITION_QUESTTAKEN:
6344        {
6345            QuestStatus status = player->GetQuestStatus(value1);
6346            return (status == QUEST_STATUS_INCOMPLETE);
6347        }
6348        case CONDITION_AD_COMMISSION_AURA:
6349        {
6350            Unit::AuraMap const& auras = player->GetAuras();
6351            for(Unit::AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
6352                if((itr->second->GetSpellProto()->Attributes & 0x1000010) && itr->second->GetSpellProto()->SpellVisual==3580)
6353                    return true;
6354            return false;
6355        }
6356        default:
6357            return false;
6358    }
6359}
6360
6361// Verification of condition values validity
6362bool PlayerCondition::IsValid(ConditionType condition, uint32 value1, uint32 value2)
6363{
6364    if( condition >= MAX_CONDITION)                         // Wrong condition type
6365    {
6366        sLog.outErrorDb("Condition has bad type of %u, skipped ", condition );
6367        return false;
6368    }
6369
6370    switch (condition)
6371    {
6372        case CONDITION_AURA:
6373        {
6374            if(!sSpellStore.LookupEntry(value1))
6375            {
6376                sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
6377                return false;
6378            }
6379            if(value2 > 2)
6380            {
6381                sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..2), skipped", value2);
6382                return false;
6383            }
6384            break;
6385        }
6386        case CONDITION_ITEM:
6387        {
6388            ItemPrototype const *proto = objmgr.GetItemPrototype(value1);
6389            if(!proto)
6390            {
6391                sLog.outErrorDb("Item condition requires to have non existing item (%u), skipped", value1);
6392                return false;
6393            }
6394            break;
6395        }
6396        case CONDITION_ITEM_EQUIPPED:
6397        {
6398            ItemPrototype const *proto = objmgr.GetItemPrototype(value1);
6399            if(!proto)
6400            {
6401                sLog.outErrorDb("ItemEquipped condition requires to have non existing item (%u) equipped, skipped", value1);
6402                return false;
6403            }
6404            break;
6405        }
6406        case CONDITION_ZONEID:
6407        {
6408            AreaTableEntry const* areaEntry = GetAreaEntryByAreaID(value1);
6409            if(!areaEntry)
6410            {
6411                sLog.outErrorDb("Zone condition requires to be in non existing area (%u), skipped", value1);
6412                return false;
6413            }
6414            if(areaEntry->zone != 0)
6415            {
6416                sLog.outErrorDb("Zone condition requires to be in area (%u) which is a subzone but zone expected, skipped", value1);
6417                return false;
6418            }
6419            break;
6420        }
6421        case CONDITION_REPUTATION_RANK:
6422        {
6423            FactionEntry const* factionEntry = sFactionStore.LookupEntry(value1);
6424            if(!factionEntry)
6425            {
6426                sLog.outErrorDb("Reputation condition requires to have reputation non existing faction (%u), skipped", value1);
6427                return false;
6428            }
6429            break;
6430        }
6431        case CONDITION_TEAM:
6432        {
6433            if (value1 != ALLIANCE && value1 != HORDE)
6434            {
6435                sLog.outErrorDb("Team condition specifies unknown team (%u), skipped", value1);
6436                return false;
6437            }
6438            break;
6439        }
6440        case CONDITION_SKILL:
6441        {
6442            SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(value1);
6443            if (!pSkill)
6444            {
6445                sLog.outErrorDb("Skill condition specifies non-existing skill (%u), skipped", value1);
6446                return false;
6447            }
6448            if (value2 < 1 || value2 > sWorld.GetConfigMaxSkillValue() )
6449            {
6450                sLog.outErrorDb("Skill condition specifies invalid skill value (%u), skipped", value2);
6451                return false;
6452            }
6453            break;
6454        }
6455        case CONDITION_QUESTREWARDED:
6456        case CONDITION_QUESTTAKEN:
6457        {
6458            Quest const *Quest = objmgr.GetQuestTemplate(value1);
6459            if (!Quest)
6460            {
6461                sLog.outErrorDb("Quest condition specifies non-existing quest (%u), skipped", value1);
6462                return false;
6463            }
6464            if(value2)
6465                sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
6466            break;
6467        }
6468        case CONDITION_AD_COMMISSION_AURA:
6469        {
6470            if(value1)
6471                sLog.outErrorDb("Quest condition has useless data in value1 (%u)!", value1);
6472            if(value2)
6473                sLog.outErrorDb("Quest condition has useless data in value2 (%u)!", value2);
6474            break;
6475        }
6476    }
6477    return true;
6478}
6479
6480SkillRangeType GetSkillRangeType(SkillLineEntry const *pSkill, bool racial)
6481{
6482    switch(pSkill->categoryId)
6483    {
6484        case SKILL_CATEGORY_LANGUAGES: return SKILL_RANGE_LANGUAGE;
6485        case SKILL_CATEGORY_WEAPON:
6486            if(pSkill->id!=SKILL_FIST_WEAPONS)
6487                return SKILL_RANGE_LEVEL;
6488            else
6489                return SKILL_RANGE_MONO;
6490        case SKILL_CATEGORY_ARMOR:
6491        case SKILL_CATEGORY_CLASS:
6492            if(pSkill->id != SKILL_POISONS && pSkill->id != SKILL_LOCKPICKING)
6493                return SKILL_RANGE_MONO;
6494            else
6495                return SKILL_RANGE_LEVEL;
6496        case SKILL_CATEGORY_SECONDARY:
6497        case SKILL_CATEGORY_PROFESSION:
6498            // not set skills for professions and racial abilities
6499            if(IsProfessionSkill(pSkill->id))
6500                return SKILL_RANGE_RANK;
6501            else if(racial)
6502                return SKILL_RANGE_NONE;
6503            else
6504                return SKILL_RANGE_MONO;
6505        default:
6506        case SKILL_CATEGORY_ATTRIBUTES:                     //not found in dbc
6507        case SKILL_CATEGORY_NOT_DISPLAYED:                  //only GENEREC(DND)
6508            return SKILL_RANGE_NONE;
6509    }
6510}
6511
6512void ObjectMgr::LoadGameTele()
6513{
6514    m_GameTeleMap.clear();                                  // for relaod case
6515
6516    uint32 count = 0;
6517    QueryResult *result = WorldDatabase.Query("SELECT id, position_x, position_y, position_z, orientation, map, name FROM game_tele");
6518
6519    if( !result )
6520    {
6521        barGoLink bar( 1 );
6522
6523        bar.step();
6524
6525        sLog.outString();
6526        sLog.outErrorDb(">> Loaded `game_tele`, table is empty!");
6527        return;
6528    }
6529
6530    barGoLink bar( result->GetRowCount() );
6531
6532    do
6533    {
6534        bar.step();
6535
6536        Field *fields = result->Fetch();
6537
6538        uint32 id         = fields[0].GetUInt32();
6539
6540        GameTele gt;
6541
6542        gt.position_x     = fields[1].GetFloat();
6543        gt.position_y     = fields[2].GetFloat();
6544        gt.position_z     = fields[3].GetFloat();
6545        gt.orientation    = fields[4].GetFloat();
6546        gt.mapId          = fields[5].GetUInt32();
6547        gt.name           = fields[6].GetCppString();
6548
6549        if(!MapManager::IsValidMapCoord(gt.mapId,gt.position_x,gt.position_y,gt.position_z,gt.orientation))
6550        {
6551            sLog.outErrorDb("Wrong position for id %u (name: %s) in `game_tele` table, ignoring.",id,gt.name.c_str());
6552            continue;
6553        }
6554
6555        if(!Utf8toWStr(gt.name,gt.wnameLow))
6556        {
6557            sLog.outErrorDb("Wrong UTF8 name for id %u in `game_tele` table, ignoring.",id);
6558            continue;
6559        }
6560
6561        wstrToLower( gt.wnameLow );
6562
6563        m_GameTeleMap[id] = gt;
6564
6565        ++count;
6566    }
6567    while (result->NextRow());
6568
6569    delete result;
6570
6571    sLog.outString();
6572    sLog.outString( ">> Loaded %u game tele's", count );
6573}
6574
6575GameTele const* ObjectMgr::GetGameTele(std::string name) const
6576{
6577    // explicit name case
6578    std::wstring wname;
6579    if(!Utf8toWStr(name,wname))
6580        return false;
6581
6582    // converting string that we try to find to lower case
6583    wstrToLower( wname );
6584
6585    for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
6586        if(itr->second.wnameLow == wname)
6587            return &itr->second;
6588
6589    return NULL;
6590}
6591
6592bool ObjectMgr::AddGameTele(GameTele& tele)
6593{
6594    // find max id
6595    uint32 new_id = 0;
6596    for(GameTeleMap::const_iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
6597        if(itr->first > new_id)
6598            new_id = itr->first;
6599   
6600    // use next
6601    ++new_id;
6602
6603    if(!Utf8toWStr(tele.name,tele.wnameLow))
6604        return false;
6605
6606    wstrToLower( tele.wnameLow );
6607
6608    m_GameTeleMap[new_id] = tele;
6609
6610    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')",
6611        new_id,tele.position_x,tele.position_y,tele.position_z,tele.orientation,tele.mapId,tele.name.c_str());
6612}
6613
6614bool ObjectMgr::DeleteGameTele(std::string name)
6615{
6616    // explicit name case
6617    std::wstring wname;
6618    if(!Utf8toWStr(name,wname))
6619        return false;
6620
6621    // converting string that we try to find to lower case
6622    wstrToLower( wname );
6623
6624    for(GameTeleMap::iterator itr = m_GameTeleMap.begin(); itr != m_GameTeleMap.end(); ++itr)
6625    {
6626        if(itr->second.wnameLow == wname)
6627        {
6628            WorldDatabase.PExecuteLog("DELETE FROM game_tele WHERE name = '%s'",itr->second.name.c_str());
6629            m_GameTeleMap.erase(itr);
6630            return true;
6631        }
6632    }
6633
6634    return false;
6635}
6636
6637void ObjectMgr::LoadTrainerSpell()
6638{
6639    // For reload case
6640    for (CacheTrainerSpellMap::iterator itr = m_mCacheTrainerSpellMap.begin(); itr != m_mCacheTrainerSpellMap.end(); ++itr)
6641        itr->second.Clear();
6642    m_mCacheTrainerSpellMap.clear();
6643
6644    QueryResult *result = WorldDatabase.PQuery("SELECT entry, spell,spellcost,reqskill,reqskillvalue,reqlevel FROM npc_trainer");
6645
6646    if( !result )
6647    {
6648        barGoLink bar( 1 );
6649
6650        bar.step();
6651
6652        sLog.outString();
6653        sLog.outErrorDb(">> Loaded `npc_trainer`, table is empty!");
6654        return;
6655    }
6656
6657    barGoLink bar( result->GetRowCount() );
6658
6659    uint32 count = 0,entry,spell;
6660    do
6661    {
6662        bar.step();
6663
6664        Field* fields = result->Fetch();
6665
6666        entry  = fields[0].GetUInt32();
6667        spell  = fields[1].GetUInt32();
6668
6669        if(!GetCreatureTemplate(entry))
6670        {
6671            sLog.outErrorDb("Table `npc_trainer` have entry for not existed creature template (Entry: %u), ignore", entry);
6672            continue;
6673        }
6674
6675        SpellEntry const *spellinfo = sSpellStore.LookupEntry(spell);
6676        if(!spellinfo)
6677        {
6678            sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u ) has non existing spell %u, ignore", entry,spell);
6679            continue;
6680        }
6681
6682        if(!SpellMgr::IsSpellValid(spellinfo))
6683        {
6684            sLog.outErrorDb("Table `npc_trainer` for Trainer (Entry: %u) has broken learning spell %u, ignore", entry, spell);
6685            continue;
6686        }
6687
6688        TrainerSpell* pTrainerSpell = new TrainerSpell();
6689        pTrainerSpell->spell         = spell;
6690        pTrainerSpell->spellcost     = fields[2].GetUInt32();
6691        pTrainerSpell->reqskill      = fields[3].GetUInt32();
6692        pTrainerSpell->reqskillvalue = fields[4].GetUInt32();
6693        pTrainerSpell->reqlevel      = fields[5].GetUInt32();
6694
6695        if(!pTrainerSpell->reqlevel)
6696            pTrainerSpell->reqlevel = spellinfo->spellLevel;
6697
6698
6699        TrainerSpellData& data = m_mCacheTrainerSpellMap[entry];
6700
6701        if(SpellMgr::IsProfessionSpell(spell))
6702            data.trainerType = 2;
6703
6704        data.spellList.push_back(pTrainerSpell);
6705        ++count;
6706
6707    } while (result->NextRow());
6708    delete result;
6709
6710    sLog.outString();
6711    sLog.outString( ">> Loaded Trainers %d", count );
6712}
6713
6714void ObjectMgr::LoadVendors()
6715{
6716    // For reload case
6717    for (CacheVendorItemMap::iterator itr = m_mCacheVendorItemMap.begin(); itr != m_mCacheVendorItemMap.end(); ++itr)
6718    {
6719        for (VendorItemList::iterator itr2 = itr->second.begin(); itr2 != itr->second.end(); ++itr2)
6720            delete (*itr2);
6721    }
6722    m_mCacheVendorItemMap.clear();
6723
6724    QueryResult *result = WorldDatabase.PQuery("SELECT entry, item, maxcount, incrtime, ExtendedCost FROM npc_vendor");
6725    if( !result )
6726    {
6727        barGoLink bar( 1 );
6728
6729        bar.step();
6730
6731        sLog.outString();
6732        sLog.outErrorDb(">> Loaded `npc_vendor`, table is empty!");
6733        return;
6734    }
6735
6736    barGoLink bar( result->GetRowCount() );
6737
6738    uint32 count = 0;
6739    uint32 entry, item_id, ExtendedCost;
6740    do
6741    {
6742        bar.step();
6743        Field* fields = result->Fetch();
6744
6745        entry = fields[0].GetUInt32();
6746        if(!GetCreatureTemplate(entry))
6747        {
6748            sLog.outErrorDb("Table `npc_vendor` have data for not existed creature template (Entry: %u), ignore", entry);
6749            continue;
6750        }
6751
6752        item_id  = fields[1].GetUInt32();
6753        if(!GetItemPrototype(item_id))
6754        {
6755            sLog.outErrorDb("Table `npc_vendor` for Vendor (Entry: %u) have in item list non-existed item (%u), ignore",entry,item_id);
6756            continue;
6757        }
6758
6759        ExtendedCost = fields[4].GetUInt32();
6760        if(ExtendedCost && !sItemExtendedCostStore.LookupEntry(ExtendedCost))
6761        {
6762            sLog.outErrorDb("Table `npc_vendor` have Item (Entry: %u) with wrong ExtendedCost (%u) for vendor (%u), ignore",item_id,ExtendedCost,entry);
6763            continue;
6764        }
6765
6766        VendorItemList& vList = m_mCacheVendorItemMap[entry];
6767
6768        if(vList.size() >= MAX_VENDOR_ITEMS)
6769        {
6770            sLog.outErrorDb( "Table `npc_vendor` has too many items (%u >= %i) for vendor (Entry: %u), ignore", vList.size(), MAX_VENDOR_ITEMS, entry);
6771            continue;
6772        }
6773
6774        VendorItem* pVendorItem = new VendorItem();
6775        pVendorItem->item         = item_id;
6776        pVendorItem->maxcount     = fields[2].GetUInt32();
6777        pVendorItem->incrtime     = fields[3].GetUInt32();
6778        pVendorItem->ExtendedCost = ExtendedCost;
6779
6780        vList.push_back(pVendorItem);
6781        ++count;
6782
6783    } while (result->NextRow());
6784    delete result;
6785
6786    sLog.outString();
6787    sLog.outString( ">> Loaded %d Vendors ", count );
6788}
6789
6790void ObjectMgr::LoadNpcTextId()
6791{
6792
6793    m_mCacheNpcTextIdMap.clear();
6794
6795    QueryResult* result = WorldDatabase.PQuery("SELECT npc_guid, textid FROM npc_gossip");
6796    if( !result )
6797    {
6798        barGoLink bar( 1 );
6799
6800        bar.step();
6801
6802        sLog.outString();
6803        sLog.outErrorDb(">> Loaded `npc_gossip`, table is empty!");
6804        return;
6805    }
6806
6807    barGoLink bar( result->GetRowCount() );
6808
6809    uint32 count = 0;
6810    uint32 guid,textid;
6811    do
6812    {
6813        bar.step();
6814
6815        Field* fields = result->Fetch();
6816
6817        guid   = fields[0].GetUInt32();
6818        textid = fields[1].GetUInt32();
6819
6820        if (!GetCreatureData(guid))
6821        {
6822            sLog.outErrorDb("Table `npc_gossip` have not existed creature (GUID: %u) entry, ignore. ",guid);
6823            continue;
6824        }
6825        if (!GetGossipText(textid))
6826        {
6827            sLog.outErrorDb("Table `npc_gossip` for creature (GUID: %u) have wrong Textid (%u), ignore. ", guid, textid);
6828            continue;
6829        }
6830
6831        m_mCacheNpcTextIdMap[guid] = textid ;
6832        ++count;
6833
6834    } while (result->NextRow());
6835    delete result;
6836
6837    sLog.outString();
6838    sLog.outString( ">> Loaded %d NpcTextId ", count );
6839}
6840
6841// Functions for scripting access
6842const char* GetAreaTriggerScriptNameById(uint32 id)
6843{
6844    return objmgr.GetAreaTriggerScriptName(id);
6845}
6846
6847bool LoadMangosStrings(DatabaseType& db, char const* table,int32 start_value, int32 end_value)
6848{
6849    if(start_value >= 0 || start_value <= end_value)        // start/end reversed for negative values
6850    {
6851        sLog.outError("Table '%s' attempt loaded with invalid range (%d - %d), use (%d - %d) instead.",table,start_value,end_value,-1,std::numeric_limits<int32>::min());
6852        start_value = -1;
6853        end_value = std::numeric_limits<int32>::min();
6854    }
6855
6856    // for scripting localized strings allowed use _only_ negative entries
6857    return objmgr.LoadMangosStrings(db,table,end_value,start_value);
6858}
Note: See TracBrowser for help on using the browser.