2 * vim: set ts=4 sw=4 tw=99 noet :
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_namehashset.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;
54 static inline bool matches(const char *key, const maplist_info_t *value)
56 return strcmp(value->name, key) == 0;
60 #define MAPLIST_FLAG_MAPSFOLDER (1<<0) /**< On failure, use all maps in the maps folder. */
61 #define MAPLIST_FLAG_CLEARARRAY (1<<1) /**< If an input array is specified, clear it before adding. */
62 #define MAPLIST_FLAG_NO_DEFAULT (1<<2) /**< Do not read "default" or "mapcyclefile" on failure. */
64 class MapLists : public SMGlobalClass, public ITextListener_SMC
76 m_pMapCycleFile = NULL;
77 m_ConfigLastChanged = 0;
80 void OnSourceModAllInitialized()
82 g_pSM->BuildPath(Path_SM, m_ConfigFile, sizeof(m_ConfigFile), "configs/maplists.cfg");
84 void OnSourceModShutdown()
88 void GetMapCycleFilePath(char *pBuffer, int maxlen)
90 const char *pEngineName = smcore.GetSourceEngineName();
91 const char *pMapCycleFileName = m_pMapCycleFile ? smcore.GetCvarString(m_pMapCycleFile) : "mapcycle.txt";
93 if (strcmp(pEngineName, "tf2") == 0 || strcmp(pEngineName, "css") == 0
94 || strcmp(pEngineName, "dods") == 0 || strcmp(pEngineName, "hl2dm") == 0)
96 // These four games and Source SDK 2013 do a lookup in this order; so shall we.
97 g_pSM->BuildPath(Path_Game,
103 if (!libsys->PathExists(pBuffer))
105 g_pSM->BuildPath(Path_Game,
111 if (!libsys->PathExists(pBuffer))
113 g_pSM->BuildPath(Path_Game,
116 "cfg/mapcycle_default.txt");
122 g_pSM->BuildPath(Path_Game,
129 void AddOrUpdateDefault(const char *name, const char *file)
131 char path[PLATFORM_MAX_PATH];
132 maplist_info_t *pMapList;
134 if (!m_ListLookup.retrieve(name, &pMapList))
136 pMapList = new maplist_info_t;
137 pMapList->bIsCompat = true;
138 pMapList->bIsPath = true;
139 pMapList->last_modified_time = 0;
140 smcore.strncopy(pMapList->name, name, sizeof(pMapList->name));
141 pMapList->pArray = NULL;
142 g_pSM->BuildPath(Path_Game, pMapList->path, sizeof(pMapList->path), "%s", file);
143 pMapList->serial = 0;
144 m_ListLookup.insert(name, pMapList);
145 m_MapLists.push_back(pMapList);
149 /* Don't modify if it's from the config file */
150 if (!pMapList->bIsCompat)
153 g_pSM->BuildPath(Path_Game, path, sizeof(path), "%s", file);
155 /* If the path matches, don't reset the serial/time */
156 if (strcmp(path, pMapList->path) == 0)
159 smcore.strncopy(pMapList->path, path, sizeof(pMapList->path));
160 pMapList->bIsPath = true;
161 pMapList->last_modified_time = 0;
162 pMapList->serial = 0;
169 SMCStates states = {0, 0};
171 fileFound = libsys->FileTime(m_ConfigFile, FileTime_LastChange, &fileTime);
173 /* If the file is found and hasn't changed, bail out now. */
174 if (fileFound && fileTime == m_ConfigLastChanged)
179 /* If the file wasn't found, and we already have entries, we bail out too.
180 * This case lets us optimize when a user deletes the config file, so we
181 * don't reparse every single time the function is called.
183 if (!fileFound && m_MapLists.size() > 0)
188 m_pMapCycleFile = smcore.FindConVar("mapcyclefile");
190 /* Dump everything we know about. */
191 List<maplist_info_t *> compat;
194 /* All this is to add the default entry back in. */
195 maplist_info_t *pDefList = new maplist_info_t;
197 pDefList->bIsPath = true;
198 smcore.strncopy(pDefList->name, "mapcyclefile", sizeof(pDefList->name));
200 GetMapCycleFilePath(pDefList->path, 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.contains((*iter)->name))
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.contains(m_pCurMapList->name))
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;
494 if (!m_ListLookup.retrieve(name, &pMapList))
497 if (!pMapList->bIsPath)
498 return GetMapList(ppArray, pMapList->path, pSerial);
500 /* If it is a path, and the path is "*", assume all files must be used. */
501 if (strcmp(pMapList->path, "*") == 0)
507 if (m_pMapCycleFile != NULL && strcmp(name, "mapcyclefile") == 0)
509 char path[PLATFORM_MAX_PATH];
510 GetMapCycleFilePath(path, sizeof(path));
512 if (strcmp(path, pMapList->path) != 0)
514 smcore.strncopy(pMapList->path, path, sizeof(pMapList->path));
515 pMapList->last_modified_time = 0;
519 if (!libsys->FileTime(pMapList->path, FileTime_LastChange, &last_time)
520 || last_time > pMapList->last_modified_time)
527 if ((fp = fopen(pMapList->path, "rt")) == NULL)
532 delete pMapList->pArray;
533 pMapList->pArray = new CellArray(64);
535 while (!feof(fp) && fgets(buffer, sizeof(buffer), fp) != NULL)
537 size_t len = strlen(buffer);
538 char *ptr = smcore.TrimWhitespace(buffer, len);
541 || strncmp(ptr, "//", 2) == 0)
545 if (!gamehelpers->IsMapValid(ptr))
549 if ((blk = pMapList->pArray->push()) != NULL)
551 smcore.strncopy((char *)blk, ptr, 255);
557 pMapList->last_modified_time = last_time;
558 pMapList->serial = ++m_nSerialChange;
561 if (pMapList->pArray == NULL || pMapList->pArray->size() == 0)
566 *pSerial = pMapList->serial;
567 *ppArray = pMapList->pArray;
571 void DumpCache(List<maplist_info_t *> *compat_list)
573 m_ListLookup.clear();
575 List<maplist_info_t *>::iterator iter = m_MapLists.begin();
576 while (iter != m_MapLists.end())
578 if (compat_list != NULL && (*iter)->bIsCompat)
580 compat_list->push_back((*iter));
584 delete (*iter)->pArray;
587 iter = m_MapLists.erase(iter);
591 char m_ConfigFile[PLATFORM_MAX_PATH];
592 time_t m_ConfigLastChanged;
593 ConVar *m_pMapCycleFile;
594 NameHashSet<maplist_info_t *> m_ListLookup;
595 List<maplist_info_t *> m_MapLists;
596 MapListState m_CurState;
597 unsigned int m_IgnoreLevel;
598 maplist_info_t *m_pCurMapList;
602 static cell_t LoadMapList(IPluginContext *pContext, const cell_t *params)
607 CellArray *pArray, *pNewArray;
610 pContext->LocalToPhysAddr(params[2], &addr);
611 pContext->LocalToString(params[3], &str);
614 /* Make sure the input Handle is valid */
616 if (hndl != BAD_HANDLE)
619 HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent);
621 if ((err = handlesys->ReadHandle(hndl, htCellArray, &sec, (void **)&pArray))
624 return pContext->ThrowNativeError("Invalid Handle %x (error %d)", hndl, err);
628 /* Make sure the map list cache is up to date at the root */
629 s_MapLists.UpdateCache();
631 /* Try to get the map list. */
632 if ((pNewArray = s_MapLists.UpdateMapList(pArray, str, addr, flags)) == NULL)
637 /* If the user wanted a new array, create it now. */
638 if (hndl == BAD_HANDLE)
640 if ((hndl = handlesys->CreateHandle(htCellArray, pNewArray, pContext->GetIdentity(), g_pCoreIdent, NULL))
652 static cell_t SetMapListCompatBind(IPluginContext *pContext, const cell_t *params)
656 pContext->LocalToString(params[1], &name);
657 pContext->LocalToString(params[2], &file);
659 s_MapLists.UpdateCache();
660 s_MapLists.AddOrUpdateDefault(name, file);
665 REGISTER_NATIVES(mapListNatives)
667 {"ReadMapList", LoadMapList},
668 {"SetMapListCompatBind", SetMapListCompatBind},