root/trunk/src/game/InstanceSaveMgr.cpp @ 100

Revision 44, 25.0 kB (checked in by yumileroy, 17 years ago)

[svn] * Merge Temp dev SVN with Assembla.
* Changes include:

  • Implementation of w12x's Outdoor PvP and Game Event Systems.
  • Temporary removal of IRC Chat Bot (until infinite loop when disabled is fixed).
  • All mangos -> trinity (to convert your mangos_string table, please run mangos_string_to_trinity_string.sql).
  • Improved Config cleanup.
  • And many more changes.

Original author: Seline
Date: 2008-10-14 11:57:03-05:00

Line 
1/*
2/* Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
3 *
4 * Thanks to the original authors: ScriptDev2 <https://scriptdev2.svn.sourceforge.net/>
5 *
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 */
21
22#include "InstanceSaveMgr.h"
23#include "Common.h"
24#include "Database/SQLStorage.h"
25
26#include "Player.h"
27#include "GridNotifiers.h"
28#include "WorldSession.h"
29#include "Log.h"
30#include "GridStates.h"
31#include "CellImpl.h"
32#include "Map.h"
33#include "MapManager.h"
34#include "MapInstanced.h"
35#include "InstanceSaveMgr.h"
36#include "Timer.h"
37#include "GridNotifiersImpl.h"
38#include "Config/ConfigEnv.h"
39#include "Transports.h"
40#include "ObjectAccessor.h"
41#include "ObjectMgr.h"
42#include "World.h"
43#include "Group.h"
44#include "InstanceData.h"
45#include "ProgressBar.h"
46
47INSTANTIATE_SINGLETON_1( InstanceSaveManager );
48
49InstanceSaveManager::InstanceSaveManager() : lock_instLists(false)
50{
51}
52
53InstanceSaveManager::~InstanceSaveManager()
54{
55    // it is undefined whether this or objectmgr will be unloaded first
56    // so we must be prepared for both cases
57    lock_instLists = true;
58    for (InstanceSaveHashMap::iterator itr = m_instanceSaveById.begin(); itr != m_instanceSaveById.end(); ++itr)
59    {
60        InstanceSave *save = itr->second;
61        for(InstanceSave::PlayerListType::iterator itr = save->m_playerList.begin(), next = itr; itr != save->m_playerList.end(); itr = next)
62        {
63            ++next;
64            (*itr)->UnbindInstance(save->GetMapId(), save->GetDifficulty(), true);
65        }
66        save->m_playerList.clear();
67        for(InstanceSave::GroupListType::iterator itr = save->m_groupList.begin(), next = itr; itr != save->m_groupList.end(); itr = next)
68        {
69            ++next;
70            (*itr)->UnbindInstance(save->GetMapId(), save->GetDifficulty(), true);
71        }
72        save->m_groupList.clear();
73        delete save;
74    }
75}
76
77/*
78- adding instance into manager
79- called from InstanceMap::Add, _LoadBoundInstances, LoadGroups
80*/
81InstanceSave* InstanceSaveManager::AddInstanceSave(uint32 mapId, uint32 instanceId, uint8 difficulty, time_t resetTime, bool canReset, bool load)
82{
83    InstanceSave *save = GetInstanceSave(instanceId);
84    if(save) return save;
85
86    const MapEntry* entry = sMapStore.LookupEntry(mapId);
87    if(!entry || instanceId == 0)
88    {
89        sLog.outError("InstanceSaveManager::AddInstanceSave: mapid = %d, instanceid = %d!", mapId, instanceId);
90        return NULL;
91    }
92
93    if(!resetTime)
94    {
95        // initialize reset time
96        // for normal instances if no creatures are killed the instance will reset in two hours
97        if(entry->map_type == MAP_RAID || difficulty == DIFFICULTY_HEROIC)
98            resetTime = GetResetTimeFor(mapId);
99        else
100        {
101            resetTime = time(NULL) + 2 * HOUR;
102            // normally this will be removed soon after in InstanceMap::Add, prevent error
103            ScheduleReset(true, resetTime, InstResetEvent(0, mapId, instanceId));
104        }
105    }
106
107    sLog.outDebug("InstanceSaveManager::AddInstanceSave: mapid = %d, instanceid = %d", mapId, instanceId);
108
109    save = new InstanceSave(mapId, instanceId, difficulty, resetTime, canReset);
110    if(!load) save->SaveToDB();
111
112    m_instanceSaveById[instanceId] = save;
113    return save;
114}
115
116InstanceSave *InstanceSaveManager::GetInstanceSave(uint32 InstanceId)
117{
118    InstanceSaveHashMap::iterator itr = m_instanceSaveById.find(InstanceId);
119    return itr != m_instanceSaveById.end() ? itr->second : NULL;
120}
121
122void InstanceSaveManager::DeleteInstanceFromDB(uint32 instanceid)
123{
124    CharacterDatabase.BeginTransaction();
125    CharacterDatabase.PExecute("DELETE FROM instance WHERE id = '%u'", instanceid);
126    CharacterDatabase.PExecute("DELETE FROM character_instance WHERE instance = '%u'", instanceid);
127    CharacterDatabase.PExecute("DELETE FROM group_instance WHERE instance = '%u'", instanceid);
128    CharacterDatabase.CommitTransaction();
129    // respawn times should be deleted only when the map gets unloaded
130}
131
132void InstanceSaveManager::RemoveInstanceSave(uint32 InstanceId)
133{
134    InstanceSaveHashMap::iterator itr = m_instanceSaveById.find( InstanceId );
135    if(itr != m_instanceSaveById.end())
136    {
137        // save the resettime for normal instances only when they get unloaded
138        if(time_t resettime = itr->second->GetResetTimeForDB())
139            CharacterDatabase.PExecute("UPDATE instance SET resettime = '"I64FMTD"' WHERE id = '%u'", (uint64)resettime, InstanceId);
140        delete itr->second;
141        m_instanceSaveById.erase(itr);
142    }
143}
144
145InstanceSave::InstanceSave(uint16 MapId, uint32 InstanceId, uint8 difficulty,
146                           time_t resetTime, bool canReset)
147: m_mapid(MapId), m_instanceid(InstanceId), m_resetTime(resetTime),
148  m_difficulty(difficulty), m_canReset(canReset)
149{
150}
151
152InstanceSave::~InstanceSave()
153{
154    // the players and groups must be unbound before deleting the save
155    assert(m_playerList.empty() && m_groupList.empty());
156}
157
158/*
159    Called from AddInstanceSave
160*/
161void InstanceSave::SaveToDB()
162{
163    // save instance data too
164    std::string data;
165
166    Map *map = MapManager::Instance().FindMap(m_instanceid, GetMapId());
167    if(map)
168    {
169        assert(map->IsDungeon());
170        InstanceData *iData = ((InstanceMap *)map)->GetInstanceData();
171        if(iData && iData->Save())
172        {
173            data = iData->Save();
174            CharacterDatabase.escape_string(data);
175        }
176    }
177
178    CharacterDatabase.PExecute("INSERT INTO instance VALUES ('%u', '%u', '"I64FMTD"', '%u', '%s')", m_instanceid, GetMapId(), (uint64)GetResetTimeForDB(), GetDifficulty(), data.c_str());
179}
180
181time_t InstanceSave::GetResetTimeForDB()
182{
183    // only save the reset time for normal instances
184    const MapEntry *entry = sMapStore.LookupEntry(GetMapId());
185    if(!entry || entry->map_type == MAP_RAID || GetDifficulty() == DIFFICULTY_HEROIC)
186        return 0;
187    else
188        return GetResetTime();
189}
190
191// to cache or not to cache, that is the question
192InstanceTemplate const* InstanceSave::GetTemplate()
193{
194    return objmgr.GetInstanceTemplate(m_mapid);
195}
196
197MapEntry const* InstanceSave::GetMapEntry()
198{
199    return sMapStore.LookupEntry(m_mapid);
200}
201
202void InstanceSave::DeleteFromDB()
203{
204    InstanceSaveManager::DeleteInstanceFromDB(GetInstanceId());
205}
206
207/* true if the instance save is still valid */
208bool InstanceSave::UnloadIfEmpty()
209{
210    if(m_playerList.empty() && m_groupList.empty())
211    {
212        if(!sInstanceSaveManager.lock_instLists)
213            sInstanceSaveManager.RemoveInstanceSave(GetInstanceId());
214        return false;
215    }
216    else
217        return true;
218}
219
220void InstanceSaveManager::_DelHelper(DatabaseType &db, const char *fields, const char *table, const char *queryTail,...)
221{
222    Tokens fieldTokens = StrSplit(fields, ", ");
223    assert(fieldTokens.size() != 0);
224
225    va_list ap;
226    char szQueryTail [MAX_QUERY_LEN];
227    va_start(ap, queryTail);
228    int res = vsnprintf( szQueryTail, MAX_QUERY_LEN, queryTail, ap );
229    va_end(ap);
230
231    QueryResult *result = db.PQuery("SELECT %s FROM %s %s", fields, table, szQueryTail);
232    if(result)
233    {
234        do
235        {
236            Field *fields = result->Fetch();
237            std::ostringstream ss;
238            for(size_t i = 0; i < fieldTokens.size(); i++)
239            {
240                std::string fieldValue = fields[i].GetCppString();
241                db.escape_string(fieldValue);
242                ss << (i != 0 ? " AND " : "") << fieldTokens[i] << " = '" << fieldValue << "'";
243            }
244            db.DirectPExecute("DELETE FROM %s WHERE %s", table, ss.str().c_str());
245        } while (result->NextRow());
246        delete result;
247    }
248}
249
250void InstanceSaveManager::CleanupInstances()
251{
252    uint64 now = (uint64)time(NULL);
253
254    barGoLink bar(2);
255    bar.step();
256
257    // load reset times and clean expired instances
258    sInstanceSaveManager.LoadResetTimes();
259
260    // clean character/group - instance binds with invalid group/characters
261    _DelHelper(CharacterDatabase, "character_instance.guid, instance", "character_instance", "LEFT JOIN characters ON character_instance.guid = characters.guid WHERE characters.guid IS NULL");
262    _DelHelper(CharacterDatabase, "group_instance.leaderGuid, instance", "group_instance", "LEFT JOIN characters ON group_instance.leaderGuid = characters.guid LEFT JOIN groups ON group_instance.leaderGuid = groups.leaderGuid WHERE characters.guid IS NULL OR groups.leaderGuid IS NULL");
263
264    // clean instances that do not have any players or groups bound to them
265    _DelHelper(CharacterDatabase, "id, map, difficulty", "instance", "LEFT JOIN character_instance ON character_instance.instance = id LEFT JOIN group_instance ON group_instance.instance = id WHERE character_instance.instance IS NULL AND group_instance.instance IS NULL");
266
267    // clean invalid instance references in other tables
268    _DelHelper(CharacterDatabase, "character_instance.guid, instance", "character_instance", "LEFT JOIN instance ON character_instance.instance = instance.id WHERE instance.id IS NULL");
269    _DelHelper(CharacterDatabase, "group_instance.leaderGuid, instance", "group_instance", "LEFT JOIN instance ON group_instance.instance = instance.id WHERE instance.id IS NULL");
270
271    // creature_respawn and gameobject_respawn are in another database
272    // first, obtain total instance set
273    std::set< uint32 > InstanceSet;
274    QueryResult *result = CharacterDatabase.PQuery("SELECT id FROM instance");
275    if( result )
276    {
277        do
278        {
279            Field *fields = result->Fetch();
280            InstanceSet.insert(fields[0].GetUInt32());
281        }
282        while (result->NextRow());
283        delete result;
284    }
285
286    // creature_respawn
287    result = WorldDatabase.PQuery("SELECT DISTINCT(instance) FROM creature_respawn WHERE instance <> 0");
288    if( result )
289    {
290        do
291        {
292            Field *fields = result->Fetch();
293            if(InstanceSet.find(fields[0].GetUInt32()) == InstanceSet.end())
294                WorldDatabase.DirectPExecute("DELETE FROM creature_respawn WHERE instance = '%u'", fields[0].GetUInt32());
295        }
296        while (result->NextRow());
297        delete result;
298    }
299
300    // gameobject_respawn
301    result = WorldDatabase.PQuery("SELECT DISTINCT(instance) FROM gameobject_respawn WHERE instance <> 0");
302    if( result )
303    {
304        do
305        {
306            Field *fields = result->Fetch();
307            if(InstanceSet.find(fields[0].GetUInt32()) == InstanceSet.end())
308                WorldDatabase.DirectPExecute("DELETE FROM gameobject_respawn WHERE instance = '%u'", fields[0].GetUInt32());
309        }
310        while (result->NextRow());
311        delete result;
312    }
313
314    bar.step();
315    sLog.outString();
316    sLog.outString( ">> Initialized %u instances", (uint32)InstanceSet.size());
317}
318
319void InstanceSaveManager::PackInstances()
320{
321    // this routine renumbers player instance associations in such a way so they start from 1 and go up
322    // TODO: this can be done a LOT more efficiently
323
324    // obtain set of all associations
325    std::set< uint32 > InstanceSet;
326
327    // all valid ids are in the instance table
328    // any associations to ids not in this table are assumed to be
329    // cleaned already in CleanupInstances
330    QueryResult *result = CharacterDatabase.PQuery("SELECT id FROM instance");
331    if( result )
332    {
333        do
334        {
335            Field *fields = result->Fetch();
336            InstanceSet.insert(fields[0].GetUInt32());
337        }
338        while (result->NextRow());
339        delete result;
340    }
341
342    barGoLink bar( InstanceSet.size() + 1);
343    bar.step();
344
345    uint32 InstanceNumber = 1;
346    // we do assume std::set is sorted properly on integer value
347    for (std::set< uint32 >::iterator i = InstanceSet.begin(); i != InstanceSet.end(); i++)
348    {
349        if (*i != InstanceNumber)
350        {
351            // remap instance id
352            WorldDatabase.PExecute("UPDATE creature_respawn SET instance = '%u' WHERE instance = '%u'", InstanceNumber, *i);
353            WorldDatabase.PExecute("UPDATE gameobject_respawn SET instance = '%u' WHERE instance = '%u'", InstanceNumber, *i);
354            CharacterDatabase.PExecute("UPDATE corpse SET instance = '%u' WHERE instance = '%u'", InstanceNumber, *i);
355            CharacterDatabase.PExecute("UPDATE character_instance SET instance = '%u' WHERE instance = '%u'", InstanceNumber, *i);
356            CharacterDatabase.PExecute("UPDATE instance SET id = '%u' WHERE id = '%u'", InstanceNumber, *i);
357            CharacterDatabase.PExecute("UPDATE group_instance SET instance = '%u' WHERE instance = '%u'", InstanceNumber, *i);
358        }
359
360        ++InstanceNumber;
361        bar.step();
362    }
363
364    sLog.outString();
365    sLog.outString( ">> Instance numbers remapped, next instance id is %u", InstanceNumber );
366}
367
368void InstanceSaveManager::LoadResetTimes()
369{
370    time_t now = time(NULL);
371    time_t today = (now / DAY) * DAY;
372
373    // NOTE: Use DirectPExecute for tables that will be queried later
374
375    // get the current reset times for normal instances (these may need to be updated)
376    // these are only kept in memory for InstanceSaves that are loaded later
377    // resettime = 0 in the DB for raid/heroic instances so those are skipped
378    typedef std::map<uint32, std::pair<uint32, uint64> > ResetTimeMapType;
379    ResetTimeMapType InstResetTime;
380    QueryResult *result = CharacterDatabase.PQuery("SELECT id, map, resettime FROM instance WHERE resettime > 0");
381    if( result )
382    {
383        do
384        {
385            if(uint64 resettime = (*result)[2].GetUInt64())
386            {
387                uint32 id = (*result)[0].GetUInt32();
388                uint32 mapid = (*result)[1].GetUInt32();
389                InstResetTime[id] = std::pair<uint32, uint64>(mapid, resettime);
390            }
391        }
392        while (result->NextRow());
393        delete result;
394
395        // update reset time for normal instances with the max creature respawn time + X hours
396        result = WorldDatabase.PQuery("SELECT MAX(respawntime), instance FROM creature_respawn WHERE instance > 0 GROUP BY instance");
397        if( result )
398        {
399            do
400            {
401                Field *fields = result->Fetch();
402                uint32 instance = fields[1].GetUInt32();
403                uint64 resettime = fields[0].GetUInt64() + 2 * HOUR;
404                ResetTimeMapType::iterator itr = InstResetTime.find(instance);
405                if(itr != InstResetTime.end() && itr->second.second != resettime)
406                {
407                    CharacterDatabase.DirectPExecute("UPDATE instance SET resettime = '"I64FMTD"' WHERE id = '%u'", resettime, instance);
408                    itr->second.second = resettime;
409                }
410            }
411            while (result->NextRow());
412            delete result;
413        }
414
415        // schedule the reset times
416        for(ResetTimeMapType::iterator itr = InstResetTime.begin(); itr != InstResetTime.end(); ++itr)
417            if(itr->second.second > now)
418                ScheduleReset(true, itr->second.second, InstResetEvent(0, itr->second.first, itr->first));
419    }
420
421    // load the global respawn times for raid/heroic instances
422    uint32 diff = sWorld.getConfig(CONFIG_INSTANCE_RESET_TIME_HOUR) * HOUR;
423    m_resetTimeByMapId.resize(sMapStore.GetNumRows()+1);
424    result = CharacterDatabase.Query("SELECT mapid, resettime FROM instance_reset");
425    if(result)
426    {
427        do
428        {
429            Field *fields = result->Fetch();
430            uint32 mapid = fields[0].GetUInt32();
431            if(!objmgr.GetInstanceTemplate(mapid))
432            {
433                sLog.outError("InstanceSaveManager::LoadResetTimes: invalid mapid %u in instance_reset!", mapid);
434                CharacterDatabase.DirectPExecute("DELETE FROM instance_reset WHERE mapid = '%u'", mapid);
435                continue;
436            }
437
438            // update the reset time if the hour in the configs changes
439            uint64 oldresettime = fields[1].GetUInt64();
440            uint64 newresettime = (oldresettime / DAY) * DAY + diff;
441            if(oldresettime != newresettime)
442                CharacterDatabase.DirectPExecute("UPDATE instance_reset SET resettime = '"I64FMTD"' WHERE mapid = '%u'", newresettime, mapid);
443
444            m_resetTimeByMapId[mapid] = newresettime;
445        } while(result->NextRow());
446        delete result;
447    }
448
449    // clean expired instances, references to them will be deleted in CleanupInstances
450    // must be done before calculating new reset times
451    _DelHelper(CharacterDatabase, "id, map, difficulty", "instance", "LEFT JOIN instance_reset ON mapid = map WHERE (instance.resettime < '"I64FMTD"' AND instance.resettime > '0') OR (NOT instance_reset.resettime IS NULL AND instance_reset.resettime < '"I64FMTD"')",  (uint64)now, (uint64)now);
452
453    // calculate new global reset times for expired instances and those that have never been reset yet
454    // add the global reset times to the priority queue
455    for(uint32 i = 0; i < sInstanceTemplate.MaxEntry; i++)
456    {
457        InstanceTemplate* temp = (InstanceTemplate*)objmgr.GetInstanceTemplate(i);
458        if(!temp) continue;
459        // only raid/heroic maps have a global reset time
460        const MapEntry* entry = sMapStore.LookupEntry(temp->map);
461        if(!entry || !entry->HasResetTime())
462            continue;
463
464        uint32 period = temp->reset_delay * DAY;
465        assert(period != 0);
466        time_t t = m_resetTimeByMapId[temp->map];
467        if(!t)
468        {
469            // initialize the reset time
470            t = today + period + diff;
471            CharacterDatabase.DirectPExecute("INSERT INTO instance_reset VALUES ('%u','"I64FMTD"')", i, (uint64)t);
472        }
473
474        if(t < now)
475        {
476            // assume that expired instances have already been cleaned
477            // calculate the next reset time
478            t = (t / DAY) * DAY;
479            t += ((today - t) / period + 1) * period + diff;
480            CharacterDatabase.DirectPExecute("UPDATE instance_reset SET resettime = '"I64FMTD"' WHERE mapid = '%u'", (uint64)t, i);
481        }
482
483        m_resetTimeByMapId[temp->map] = t;
484
485        // schedule the global reset/warning
486        uint8 type = 1;
487        static int tim[4] = {3600, 900, 300, 60};
488        for(; type < 4; type++)
489            if(t - tim[type-1] > now) break;
490        ScheduleReset(true, t - tim[type-1], InstResetEvent(type, i));
491    }
492}
493
494void InstanceSaveManager::ScheduleReset(bool add, time_t time, InstResetEvent event)
495{
496    if(add) m_resetTimeQueue.insert(std::pair<time_t, InstResetEvent>(time, event));
497    else
498    {
499        // find the event in the queue and remove it
500        ResetTimeQueue::iterator itr;
501        std::pair<ResetTimeQueue::iterator, ResetTimeQueue::iterator> range;
502        range = m_resetTimeQueue.equal_range(time);
503        for(itr = range.first; itr != range.second; ++itr)
504            if(itr->second == event) { m_resetTimeQueue.erase(itr); return; }
505        // in case the reset time changed (should happen very rarely), we search the whole queue
506        if(itr == range.second)
507        {
508            for(itr = m_resetTimeQueue.begin(); itr != m_resetTimeQueue.end(); ++itr)
509                if(itr->second == event) { m_resetTimeQueue.erase(itr); return; }
510            if(itr == m_resetTimeQueue.end())
511                sLog.outError("InstanceSaveManager::ScheduleReset: cannot cancel the reset, the event(%d,%d,%d) was not found!", event.type, event.mapid, event.instanceId);
512        }
513    }
514}
515
516void InstanceSaveManager::Update()
517{
518    time_t now = time(NULL), t;
519    while(!m_resetTimeQueue.empty() && (t = m_resetTimeQueue.begin()->first) < now)
520    {
521        InstResetEvent &event = m_resetTimeQueue.begin()->second;
522        if(event.type == 0)
523        {
524            // for individual normal instances, max creature respawn + X hours
525            _ResetInstance(event.mapid, event.instanceId);
526            m_resetTimeQueue.erase(m_resetTimeQueue.begin());
527        }
528        else
529        {
530            // global reset/warning for a certain map
531            time_t resetTime = GetResetTimeFor(event.mapid);
532            _ResetOrWarnAll(event.mapid, event.type != 4, resetTime - now);
533            if(event.type != 4)
534            {
535                // schedule the next warning/reset
536                event.type++;
537                static int tim[4] = {3600, 900, 300, 60};
538                ScheduleReset(true, resetTime - tim[event.type-1], event);
539            }
540            m_resetTimeQueue.erase(m_resetTimeQueue.begin());
541        }
542    }
543}
544
545void InstanceSaveManager::_ResetSave(InstanceSaveHashMap::iterator &itr)
546{
547    // unbind all players bound to the instance
548    // do not allow UnbindInstance to automatically unload the InstanceSaves
549    lock_instLists = true;
550    InstanceSave::PlayerListType &pList = itr->second->m_playerList;
551    while(!pList.empty())
552    {
553        Player *player = *(pList.begin());
554        player->UnbindInstance(itr->second->GetMapId(), itr->second->GetDifficulty(), true);
555    }
556    InstanceSave::GroupListType &gList = itr->second->m_groupList;
557    while(!gList.empty())
558    {
559        Group *group = *(gList.begin());
560        group->UnbindInstance(itr->second->GetMapId(), itr->second->GetDifficulty(), true);
561    }
562    m_instanceSaveById.erase(itr++);
563    lock_instLists = false;
564}
565
566void InstanceSaveManager::_ResetInstance(uint32 mapid, uint32 instanceId)
567{
568    sLog.outDebug("InstanceSaveMgr::_ResetInstance %u, %u", mapid, instanceId);
569    Map *map = (MapInstanced*)MapManager::Instance().GetBaseMap(mapid);
570    if(!map->Instanceable())
571        return;
572
573    InstanceSaveHashMap::iterator itr = m_instanceSaveById.find(instanceId);
574    if(itr != m_instanceSaveById.end()) _ResetSave(itr);
575    DeleteInstanceFromDB(instanceId);                       // even if save not loaded
576
577    Map* iMap = ((MapInstanced*)map)->FindMap(instanceId);
578    if(iMap && iMap->IsDungeon()) ((InstanceMap*)iMap)->Reset(INSTANCE_RESET_RESPAWN_DELAY);
579    else objmgr.DeleteRespawnTimeForInstance(instanceId);   // even if map is not loaded
580}
581
582void InstanceSaveManager::_ResetOrWarnAll(uint32 mapid, bool warn, uint32 timeLeft)
583{
584    // global reset for all instances of the given map
585    // note: this isn't fast but it's meant to be executed very rarely
586    Map *map = (MapInstanced*)MapManager::Instance().GetBaseMap(mapid);
587    if(!map->Instanceable())
588        return;
589    uint64 now = (uint64)time(NULL);
590
591    if(!warn)
592    {
593        // this is called one minute before the reset time
594        InstanceTemplate* temp = (InstanceTemplate*)objmgr.GetInstanceTemplate(mapid);
595        if(!temp || !temp->reset_delay)
596        {
597            sLog.outError("InstanceSaveManager::ResetOrWarnAll: no instance template or reset delay for map %d", mapid);
598            return;
599        }
600
601        // remove all binds to instances of the given map
602        for(InstanceSaveHashMap::iterator itr = m_instanceSaveById.begin(); itr != m_instanceSaveById.end();)
603        {
604            if(itr->second->GetMapId() == mapid)
605                _ResetSave(itr);
606            else
607                ++itr;
608        }
609
610        // delete them from the DB, even if not loaded
611        CharacterDatabase.BeginTransaction();
612        CharacterDatabase.PExecute("DELETE FROM character_instance USING character_instance LEFT JOIN instance ON character_instance.instance = id WHERE map = '%u'", mapid);
613        CharacterDatabase.PExecute("DELETE FROM group_instance USING group_instance LEFT JOIN instance ON group_instance.instance = id WHERE map = '%u'", mapid);
614        CharacterDatabase.PExecute("DELETE FROM instance WHERE map = '%u'", mapid);
615        CharacterDatabase.CommitTransaction();
616
617        // calculate the next reset time
618        uint32 diff = sWorld.getConfig(CONFIG_INSTANCE_RESET_TIME_HOUR) * HOUR;
619        uint32 period = temp->reset_delay * DAY;
620        uint64 next_reset = ((now + timeLeft + MINUTE) / DAY * DAY) + period + diff;
621        // update it in the DB
622        CharacterDatabase.PExecute("UPDATE instance_reset SET resettime = '"I64FMTD"' WHERE mapid = '%d'", next_reset, mapid);
623    }
624
625    MapInstanced::InstancedMaps &instMaps = ((MapInstanced*)map)->GetInstancedMaps();
626    MapInstanced::InstancedMaps::iterator mitr;
627    for(mitr = instMaps.begin(); mitr != instMaps.end(); ++mitr)
628    {
629        Map *map = mitr->second;
630        if(!map->IsDungeon()) continue;
631        if(warn) ((InstanceMap*)map)->SendResetWarnings(timeLeft);
632        else ((InstanceMap*)map)->Reset(INSTANCE_RESET_GLOBAL);
633    }
634
635    // TODO: delete creature/gameobject respawn times even if the maps are not loaded
636}
637
638uint32 InstanceSaveManager::GetNumBoundPlayersTotal()
639{
640    uint32 ret = 0;
641    for(InstanceSaveHashMap::iterator itr = m_instanceSaveById.begin(); itr != m_instanceSaveById.end(); ++itr)
642        ret += itr->second->GetPlayerCount();
643    return ret;
644}
645
646uint32 InstanceSaveManager::GetNumBoundGroupsTotal()
647{
648    uint32 ret = 0;
649    for(InstanceSaveHashMap::iterator itr = m_instanceSaveById.begin(); itr != m_instanceSaveById.end(); ++itr)
650        ret += itr->second->GetGroupCount();
651    return ret;
652}
Note: See TracBrowser for help on using the browser.