3 * =============================================================================
5 * Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved.
6 * =============================================================================
8 * This program is free software; you can redistribute it and/or modify it under
9 * the terms of the GNU General Public License, version 3.0, as published by the
10 * Free Software Foundation.
12 * This program is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
17 * You should have received a copy of the GNU General Public License along with
18 * this program. If not, see <http://www.gnu.org/licenses/>.
20 * As a special exception, AlliedModders LLC gives you permission to link the
21 * code of this program (as well as its derivative works) to "Half-Life 2," the
22 * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
23 * by the Valve Corporation. You must obey the GNU General Public License in
24 * all respects for all other code used. Additionally, AlliedModders LLC grants
25 * this exception to all derivative works. AlliedModders LLC defines further
26 * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
27 * or <http://www.sourcemod.net/license.php>.
33 #include <sm_trie_tpl.h>
34 #include "common_logic.h"
35 #include "CellArray.h"
36 #include <IGameHelpers.h>
37 #include <ILibrarySys.h>
38 #include <ITextParsers.h>
39 #include <ISourceMod.h>
40 #include "stringutil.h"
42 using namespace SourceHook;
48 char name[PLATFORM_MAX_PATH];
49 char path[PLATFORM_MAX_PATH];
50 time_t last_modified_time;
55 #define MAPLIST_FLAG_MAPSFOLDER (1<<0) /**< On failure, use all maps in the maps folder. */
56 #define MAPLIST_FLAG_CLEARARRAY (1<<1) /**< If an input array is specified, clear it before adding. */
57 #define MAPLIST_FLAG_NO_DEFAULT (1<<2) /**< Do not read "default" or "mapcyclefile" on failure. */
59 class MapLists : public SMGlobalClass, public ITextListener_SMC
71 m_pMapCycleFile = NULL;
72 m_ConfigLastChanged = 0;
75 void OnSourceModAllInitialized()
77 g_pSM->BuildPath(Path_SM, m_ConfigFile, sizeof(m_ConfigFile), "configs/maplists.cfg");
79 void OnSourceModShutdown()
83 void AddOrUpdateDefault(const char *name, const char *file)
85 char path[PLATFORM_MAX_PATH];
86 maplist_info_t *pMapList, **ppMapList;
88 if ((ppMapList = m_ListLookup.retrieve(name)) == NULL)
90 pMapList = new maplist_info_t;
91 pMapList->bIsCompat = true;
92 pMapList->bIsPath = true;
93 pMapList->last_modified_time = 0;
94 smcore.strncopy(pMapList->name, name, sizeof(pMapList->name));
95 pMapList->pArray = NULL;
96 g_pSM->BuildPath(Path_Game, pMapList->path, sizeof(pMapList->path), "%s", file);
98 m_ListLookup.insert(name, pMapList);
99 m_MapLists.push_back(pMapList);
103 pMapList = *ppMapList;
105 /* Don't modify if it's from the config file */
106 if (!pMapList->bIsCompat)
111 g_pSM->BuildPath(Path_Game, path, sizeof(path), "%s", file);
113 /* If the path matches, don't reset the serial/time */
114 if (strcmp(path, pMapList->path) == 0)
119 smcore.strncopy(pMapList->path, path, sizeof(pMapList->path));
120 pMapList->bIsPath = true;
121 pMapList->last_modified_time = 0;
122 pMapList->serial = 0;
129 SMCStates states = {0, 0};
130 const char *pMapCycleFileName;
131 const char *pEngineName;
133 fileFound = libsys->FileTime(m_ConfigFile, FileTime_LastChange, &fileTime);
135 /* If the file is found and hasn't changed, bail out now. */
136 if (fileFound && fileTime == m_ConfigLastChanged)
141 /* If the file wasn't found, and we already have entries, we bail out too.
142 * This case lets us optimize when a user deletes the config file, so we
143 * don't reparse every single time the function is called.
145 if (!fileFound && m_MapLists.size() > 0)
150 m_pMapCycleFile = smcore.FindConVar("mapcyclefile");
152 /* Dump everything we know about. */
153 List<maplist_info_t *> compat;
156 /* All this is to add the default entry back in. */
157 maplist_info_t *pDefList = new maplist_info_t;
159 pDefList->bIsPath = true;
160 smcore.strncopy(pDefList->name, "mapcyclefile", sizeof(pDefList->name));
162 pMapCycleFileName = m_pMapCycleFile ? smcore.GetCvarString(m_pMapCycleFile) : "mapcycle.txt";
164 pEngineName = smcore.GetSourceEngineName();
166 if (strcmp(pEngineName, "tf2") == 0 || strcmp(pEngineName, "css") == 0
167 || strcmp(pEngineName, "dods") == 0 || strcmp(pEngineName, "hl2dm") == 0)
169 // These four games and Source SDK 2013 do a lookup in this order; so shall we.
170 g_pSM->BuildPath(Path_Game,
172 sizeof(pDefList->path),
176 if (!libsys->PathExists(pDefList->path))
178 g_pSM->BuildPath(Path_Game,
180 sizeof(pDefList->path),
184 if (!libsys->PathExists(pDefList->path))
186 g_pSM->BuildPath(Path_Game,
188 sizeof(pDefList->path),
189 "cfg/mapcycle_default.txt");
195 g_pSM->BuildPath(Path_Game,
197 sizeof(pDefList->path),
202 pDefList->last_modified_time = 0;
203 pDefList->pArray = NULL;
204 pDefList->serial = 0;
206 m_ListLookup.insert("mapcyclefile", pDefList);
207 m_MapLists.push_back(pDefList);
209 /* Now parse the config file even if we don't know about it.
210 * This will give us a nice error message.
212 if ((error = textparser->ParseFile_SMC(m_ConfigFile, this, &states))
215 const char *errmsg = textparser->GetSMCErrorString(error);
218 errmsg = "Unknown error";
220 smcore.LogError("[SM] Could not parse file \"%s\"", m_ConfigFile);
221 smcore.LogError("[SM] Error on line %d (col %d): %s", states.line, states.col, errmsg);
225 m_ConfigLastChanged = fileTime;
228 /* Now, re-add compat stuff back in if we can. */
229 List<maplist_info_t *>::iterator iter = compat.begin();
230 while (iter != compat.end())
232 if (m_ListLookup.retrieve((*iter)->name) != NULL)
234 /* The compatibility shim is no longer needed. */
235 delete (*iter)->pArray;
240 m_ListLookup.insert((*iter)->name, (*iter));
241 m_MapLists.push_back((*iter));
243 iter = compat.erase(iter);
246 void ReadSMC_ParseStart()
248 m_CurState = MPS_NONE;
250 m_pCurMapList = NULL;
252 SMCResult ReadSMC_NewSection(const SMCStates *states, const char *name)
257 return SMCResult_Continue;
260 if (m_CurState == MPS_NONE)
262 if (strcmp(name, "MapLists") == 0)
264 m_CurState = MPS_GLOBAL;
271 else if (m_CurState == MPS_GLOBAL)
273 m_pCurMapList = new maplist_info_t;
275 memset(m_pCurMapList, 0, sizeof(maplist_info_t));
276 smcore.strncopy(m_pCurMapList->name, name, sizeof(m_pCurMapList->name));
278 m_CurState = MPS_MAPLIST;
280 else if (m_CurState == MPS_MAPLIST)
285 return SMCResult_Continue;
287 SMCResult ReadSMC_KeyValue(const SMCStates *states, const char *key, const char *value)
289 if (m_IgnoreLevel || m_pCurMapList == NULL)
291 return SMCResult_Continue;
294 if (strcmp(key, "file") == 0)
296 g_pSM->BuildPath(Path_Game,
298 sizeof(m_pCurMapList->path),
301 m_pCurMapList->bIsPath = true;
303 else if (strcmp(key, "target") == 0)
305 smcore.strncopy(m_pCurMapList->path, value, sizeof(m_pCurMapList->path));
306 m_pCurMapList->bIsPath = false;
309 return SMCResult_Continue;
311 SMCResult ReadSMC_LeavingSection(const SMCStates *states)
316 return SMCResult_Continue;
319 if (m_CurState == MPS_MAPLIST)
321 if (m_pCurMapList != NULL
322 && m_pCurMapList->path[0] != '\0'
323 && m_ListLookup.retrieve(m_pCurMapList->name) == NULL)
325 m_ListLookup.insert(m_pCurMapList->name, m_pCurMapList);
326 m_MapLists.push_back(m_pCurMapList);
327 m_pCurMapList = NULL;
331 delete m_pCurMapList;
332 m_pCurMapList = NULL;
334 m_CurState = MPS_GLOBAL;
336 else if (m_CurState == MPS_GLOBAL)
338 m_CurState = MPS_NONE;
341 return SMCResult_Continue;
343 void ReadSMC_ParseEnd(bool halted, bool failed)
345 delete m_pCurMapList;
346 m_pCurMapList = NULL;
348 static int sort_maps_in_adt_array(const void *str1, const void *str2)
350 return strcmp((char *)str1, (char *)str2);
352 CellArray *UpdateMapList(CellArray *pUseArray, const char *name, int *pSerial, unsigned int flags)
355 CellArray *pNewArray = NULL;
356 bool success, free_new_array;
358 free_new_array = false;
360 if ((success = GetMapList(&pNewArray, name, &change_serial)) == false)
362 if ((flags & MAPLIST_FLAG_NO_DEFAULT) != MAPLIST_FLAG_NO_DEFAULT)
364 /* If this list failed, and it's not the default, try the default.
366 if (strcmp(name, "default") != 0)
368 success = GetMapList(&pNewArray, name, &change_serial);
370 /* If either of the last two conditions failed, try again if we can. */
371 if (!success && strcmp(name, "mapcyclefile") != 0)
373 success = GetMapList(&pNewArray, "mapcyclefile", &change_serial);
378 /* If there was a success, and the serial has not changed, bail out. */
379 if (success && *pSerial == change_serial)
385 * If there was a success but no map list, we need to look in the maps folder.
386 * If there was a failure and the flag is specified, we need to look in the maps folder.
388 if ((success && pNewArray == NULL)
389 || (!success && ((flags & MAPLIST_FLAG_MAPSFOLDER) == MAPLIST_FLAG_MAPSFOLDER)))
391 pNewArray = new CellArray(64);
392 free_new_array = true;
396 FileFindHandle_t findHandle;
397 const char *fileName = smcore.filesystem->FindFirstEx("maps/*.bsp", "GAME", &findHandle);
401 char buffer[PLATFORM_MAX_PATH];
403 UTIL_StripExtension(fileName, buffer, sizeof(buffer));
405 if (!engine->IsMapValid(buffer))
407 fileName = smcore.filesystem->FindNext(findHandle);
411 if ((blk = pNewArray->push()) == NULL)
413 fileName = smcore.filesystem->FindNext(findHandle);
417 smcore.strncopy((char *)blk, buffer, 255);
419 fileName = smcore.filesystem->FindNext(findHandle);
422 smcore.filesystem->FindClose(findHandle);
424 /* Remove the array if there were no items. */
425 if (pNewArray->size() == 0)
432 qsort(pNewArray->base(),
434 pNewArray->blocksize() * sizeof(cell_t),
435 sort_maps_in_adt_array);
441 /* If there is still no array by this point, bail out. */
442 if (pNewArray == NULL)
448 *pSerial = change_serial;
450 /* If there is no input array, return something temporary. */
451 if (pUseArray == NULL)
459 return pNewArray->clone();
463 /* Clear the input array if necessary. */
464 if ((flags & MAPLIST_FLAG_CLEARARRAY) == MAPLIST_FLAG_CLEARARRAY)
472 for (size_t i = 0; i < pNewArray->size(); i++)
474 blk_dst = pUseArray->push();
475 blk_src = pNewArray->at(i);
476 smcore.strncopy((char *)blk_dst, (char *)blk_src, pUseArray->blocksize() * sizeof(cell_t));
479 /* Free resources if necessary. */
485 /* Return the array we were given. */
489 bool GetMapList(CellArray **ppArray, const char *name, int *pSerial)
492 maplist_info_t *pMapList, **ppMapList;
494 if ((ppMapList = m_ListLookup.retrieve(name)) == NULL)
499 pMapList = *ppMapList;
501 if (!pMapList->bIsPath)
503 return GetMapList(ppArray, pMapList->path, pSerial);
506 /* If it is a path, and the path is "*", assume all files must be used. */
507 if (strcmp(pMapList->path, "*") == 0)
513 if (m_pMapCycleFile != NULL && strcmp(name, "mapcyclefile") == 0)
515 char path[PLATFORM_MAX_PATH];
516 g_pSM->BuildPath(Path_Game,
520 m_pMapCycleFile ? smcore.GetCvarString(m_pMapCycleFile) : "mapcycle.txt");
522 if (strcmp(path, pMapList->path) != 0)
524 smcore.strncopy(pMapList->path, path, sizeof(pMapList->path));
525 pMapList->last_modified_time = 0;
529 if (!libsys->FileTime(pMapList->path, FileTime_LastChange, &last_time)
530 || last_time > pMapList->last_modified_time)
537 if ((fp = fopen(pMapList->path, "rt")) == NULL)
542 delete pMapList->pArray;
543 pMapList->pArray = new CellArray(64);
545 while (!feof(fp) && fgets(buffer, sizeof(buffer), fp) != NULL)
547 size_t len = strlen(buffer);
548 char *ptr = smcore.TrimWhitespace(buffer, len);
551 || strncmp(ptr, "//", 2) == 0)
555 if (!gamehelpers->IsMapValid(ptr))
559 if ((blk = pMapList->pArray->push()) != NULL)
561 smcore.strncopy((char *)blk, ptr, 255);
567 pMapList->last_modified_time = last_time;
568 pMapList->serial = ++m_nSerialChange;
571 if (pMapList->pArray == NULL || pMapList->pArray->size() == 0)
576 *pSerial = pMapList->serial;
577 *ppArray = pMapList->pArray;
581 void DumpCache(List<maplist_info_t *> *compat_list)
583 m_ListLookup.clear();
585 List<maplist_info_t *>::iterator iter = m_MapLists.begin();
586 while (iter != m_MapLists.end())
588 if (compat_list != NULL && (*iter)->bIsCompat)
590 compat_list->push_back((*iter));
594 delete (*iter)->pArray;
597 iter = m_MapLists.erase(iter);
601 char m_ConfigFile[PLATFORM_MAX_PATH];
602 time_t m_ConfigLastChanged;
603 ConVar *m_pMapCycleFile;
604 KTrie<maplist_info_t *> m_ListLookup;
605 List<maplist_info_t *> m_MapLists;
606 MapListState m_CurState;
607 unsigned int m_IgnoreLevel;
608 maplist_info_t *m_pCurMapList;
612 static cell_t LoadMapList(IPluginContext *pContext, const cell_t *params)
617 CellArray *pArray, *pNewArray;
620 pContext->LocalToPhysAddr(params[2], &addr);
621 pContext->LocalToString(params[3], &str);
624 /* Make sure the input Handle is valid */
626 if (hndl != BAD_HANDLE)
629 HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent);
631 if ((err = handlesys->ReadHandle(hndl, htCellArray, &sec, (void **)&pArray))
634 return pContext->ThrowNativeError("Invalid Handle %x (error %d)", hndl, err);
638 /* Make sure the map list cache is up to date at the root */
639 s_MapLists.UpdateCache();
641 /* Try to get the map list. */
642 if ((pNewArray = s_MapLists.UpdateMapList(pArray, str, addr, flags)) == NULL)
647 /* If the user wanted a new array, create it now. */
648 if (hndl == BAD_HANDLE)
650 if ((hndl = handlesys->CreateHandle(htCellArray, pNewArray, pContext->GetIdentity(), g_pCoreIdent, NULL))
662 static cell_t SetMapListCompatBind(IPluginContext *pContext, const cell_t *params)
666 pContext->LocalToString(params[1], &name);
667 pContext->LocalToString(params[2], &file);
669 s_MapLists.UpdateCache();
670 s_MapLists.AddOrUpdateDefault(name, file);
675 REGISTER_NATIVES(mapListNatives)
677 {"ReadMapList", LoadMapList},
678 {"SetMapListCompatBind", SetMapListCompatBind},