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

Revision 18, 253.3 kB (checked in by yumileroy, 17 years ago)

[svn] * Little fix in RandomMovementGenerator?
* Updated to 6731 and 680

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