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->Format(pBuffer, maxlen, "cfg/%s", pMapCycleFileName);
99 if (!smcore.filesystem->FileExists(pBuffer, "GAME"))
101 g_pSM->Format(pBuffer, maxlen, "%s", pMapCycleFileName);
103 if (!smcore.filesystem->FileExists(pBuffer, "GAME"))
105 g_pSM->Format(pBuffer, maxlen, "cfg/mapcycle_default.txt");
111 g_pSM->Format(pBuffer, maxlen, "%s", pMapCycleFileName);
114 void AddOrUpdateDefault(const char *name, const char *file)
116 char path[PLATFORM_MAX_PATH];
117 maplist_info_t *pMapList;
119 if (!m_ListLookup.retrieve(name, &pMapList))
121 pMapList = new maplist_info_t;
122 pMapList->bIsCompat = true;
123 pMapList->bIsPath = true;
124 pMapList->last_modified_time = 0;
125 smcore.strncopy(pMapList->name, name, sizeof(pMapList->name));
126 pMapList->pArray = NULL;
127 smcore.strncopy(pMapList->path, file, sizeof(pMapList->path));
128 pMapList->serial = 0;
129 m_ListLookup.insert(name, pMapList);
130 m_MapLists.push_back(pMapList);
134 /* Don't modify if it's from the config file */
135 if (!pMapList->bIsCompat)
138 smcore.strncopy(path, file, sizeof(path));
140 /* If the path matches, don't reset the serial/time */
141 if (strcmp(path, pMapList->path) == 0)
144 smcore.strncopy(pMapList->path, path, sizeof(pMapList->path));
145 pMapList->bIsPath = true;
146 pMapList->last_modified_time = 0;
147 pMapList->serial = 0;
154 SMCStates states = {0, 0};
156 fileFound = libsys->FileTime(m_ConfigFile, FileTime_LastChange, &fileTime);
158 /* If the file is found and hasn't changed, bail out now. */
159 if (fileFound && fileTime == m_ConfigLastChanged)
164 /* If the file wasn't found, and we already have entries, we bail out too.
165 * This case lets us optimize when a user deletes the config file, so we
166 * don't reparse every single time the function is called.
168 if (!fileFound && m_MapLists.size() > 0)
173 m_pMapCycleFile = smcore.FindConVar("mapcyclefile");
175 /* Dump everything we know about. */
176 List<maplist_info_t *> compat;
179 /* All this is to add the default entry back in. */
180 maplist_info_t *pDefList = new maplist_info_t;
182 pDefList->bIsPath = true;
183 smcore.strncopy(pDefList->name, "mapcyclefile", sizeof(pDefList->name));
185 GetMapCycleFilePath(pDefList->path, sizeof(pDefList->path));
187 pDefList->last_modified_time = 0;
188 pDefList->pArray = NULL;
189 pDefList->serial = 0;
191 m_ListLookup.insert("mapcyclefile", pDefList);
192 m_MapLists.push_back(pDefList);
194 /* Now parse the config file even if we don't know about it.
195 * This will give us a nice error message.
197 if ((error = textparser->ParseFile_SMC(m_ConfigFile, this, &states))
200 const char *errmsg = textparser->GetSMCErrorString(error);
203 errmsg = "Unknown error";
205 smcore.LogError("[SM] Could not parse file \"%s\"", m_ConfigFile);
206 smcore.LogError("[SM] Error on line %d (col %d): %s", states.line, states.col, errmsg);
210 m_ConfigLastChanged = fileTime;
213 /* Now, re-add compat stuff back in if we can. */
214 List<maplist_info_t *>::iterator iter = compat.begin();
215 while (iter != compat.end())
217 if (m_ListLookup.contains((*iter)->name))
219 /* The compatibility shim is no longer needed. */
220 delete (*iter)->pArray;
225 m_ListLookup.insert((*iter)->name, (*iter));
226 m_MapLists.push_back((*iter));
228 iter = compat.erase(iter);
231 void ReadSMC_ParseStart()
233 m_CurState = MPS_NONE;
235 m_pCurMapList = NULL;
237 SMCResult ReadSMC_NewSection(const SMCStates *states, const char *name)
242 return SMCResult_Continue;
245 if (m_CurState == MPS_NONE)
247 if (strcmp(name, "MapLists") == 0)
249 m_CurState = MPS_GLOBAL;
256 else if (m_CurState == MPS_GLOBAL)
258 m_pCurMapList = new maplist_info_t;
260 memset(m_pCurMapList, 0, sizeof(maplist_info_t));
261 smcore.strncopy(m_pCurMapList->name, name, sizeof(m_pCurMapList->name));
263 m_CurState = MPS_MAPLIST;
265 else if (m_CurState == MPS_MAPLIST)
270 return SMCResult_Continue;
272 SMCResult ReadSMC_KeyValue(const SMCStates *states, const char *key, const char *value)
274 if (m_IgnoreLevel || m_pCurMapList == NULL)
276 return SMCResult_Continue;
279 if (strcmp(key, "file") == 0)
281 smcore.strncopy(m_pCurMapList->path, value, sizeof(m_pCurMapList->path));
282 m_pCurMapList->bIsPath = true;
284 else if (strcmp(key, "target") == 0)
286 smcore.strncopy(m_pCurMapList->path, value, sizeof(m_pCurMapList->path));
287 m_pCurMapList->bIsPath = false;
290 return SMCResult_Continue;
292 SMCResult ReadSMC_LeavingSection(const SMCStates *states)
297 return SMCResult_Continue;
300 if (m_CurState == MPS_MAPLIST)
302 if (m_pCurMapList != NULL
303 && m_pCurMapList->path[0] != '\0'
304 && !m_ListLookup.contains(m_pCurMapList->name))
306 m_ListLookup.insert(m_pCurMapList->name, m_pCurMapList);
307 m_MapLists.push_back(m_pCurMapList);
308 m_pCurMapList = NULL;
312 delete m_pCurMapList;
313 m_pCurMapList = NULL;
315 m_CurState = MPS_GLOBAL;
317 else if (m_CurState == MPS_GLOBAL)
319 m_CurState = MPS_NONE;
322 return SMCResult_Continue;
324 void ReadSMC_ParseEnd(bool halted, bool failed)
326 delete m_pCurMapList;
327 m_pCurMapList = NULL;
329 static int sort_maps_in_adt_array(const void *str1, const void *str2)
331 return strcmp((char *)str1, (char *)str2);
333 CellArray *UpdateMapList(CellArray *pUseArray, const char *name, int *pSerial, unsigned int flags)
336 CellArray *pNewArray = NULL;
337 bool success, free_new_array;
339 free_new_array = false;
341 if ((success = GetMapList(&pNewArray, name, &change_serial)) == false)
343 if ((flags & MAPLIST_FLAG_NO_DEFAULT) != MAPLIST_FLAG_NO_DEFAULT)
345 /* If this list failed, and it's not the default, try the default.
347 if (strcmp(name, "default") != 0)
349 success = GetMapList(&pNewArray, name, &change_serial);
351 /* If either of the last two conditions failed, try again if we can. */
352 if (!success && strcmp(name, "mapcyclefile") != 0)
354 success = GetMapList(&pNewArray, "mapcyclefile", &change_serial);
359 /* If there was a success, and the serial has not changed, bail out. */
360 if (success && *pSerial == change_serial)
366 * If there was a success but no map list, we need to look in the maps folder.
367 * If there was a failure and the flag is specified, we need to look in the maps folder.
369 if ((success && pNewArray == NULL)
370 || (!success && ((flags & MAPLIST_FLAG_MAPSFOLDER) == MAPLIST_FLAG_MAPSFOLDER)))
372 pNewArray = new CellArray(64);
373 free_new_array = true;
377 FileFindHandle_t findHandle;
378 const char *fileName = smcore.filesystem->FindFirstEx("maps/*.bsp", "GAME", &findHandle);
382 char buffer[PLATFORM_MAX_PATH];
384 UTIL_StripExtension(fileName, buffer, sizeof(buffer));
386 if (!engine->IsMapValid(buffer))
388 fileName = smcore.filesystem->FindNext(findHandle);
392 if ((blk = pNewArray->push()) == NULL)
394 fileName = smcore.filesystem->FindNext(findHandle);
398 smcore.strncopy((char *)blk, buffer, 255);
400 fileName = smcore.filesystem->FindNext(findHandle);
403 smcore.filesystem->FindClose(findHandle);
405 /* Remove the array if there were no items. */
406 if (pNewArray->size() == 0)
413 qsort(pNewArray->base(),
415 pNewArray->blocksize() * sizeof(cell_t),
416 sort_maps_in_adt_array);
422 /* If there is still no array by this point, bail out. */
423 if (pNewArray == NULL)
429 *pSerial = change_serial;
431 /* If there is no input array, return something temporary. */
432 if (pUseArray == NULL)
440 return pNewArray->clone();
444 /* Clear the input array if necessary. */
445 if ((flags & MAPLIST_FLAG_CLEARARRAY) == MAPLIST_FLAG_CLEARARRAY)
453 for (size_t i = 0; i < pNewArray->size(); i++)
455 blk_dst = pUseArray->push();
456 blk_src = pNewArray->at(i);
457 smcore.strncopy((char *)blk_dst, (char *)blk_src, pUseArray->blocksize() * sizeof(cell_t));
460 /* Free resources if necessary. */
466 /* Return the array we were given. */
470 bool GetMapList(CellArray **ppArray, const char *name, int *pSerial)
473 maplist_info_t *pMapList;
475 if (!m_ListLookup.retrieve(name, &pMapList))
478 if (!pMapList->bIsPath)
479 return GetMapList(ppArray, pMapList->path, pSerial);
481 /* If it is a path, and the path is "*", assume all files must be used. */
482 if (strcmp(pMapList->path, "*") == 0)
488 if (m_pMapCycleFile != NULL && strcmp(name, "mapcyclefile") == 0)
490 char path[PLATFORM_MAX_PATH];
491 GetMapCycleFilePath(path, sizeof(path));
493 if (strcmp(path, pMapList->path) != 0)
495 smcore.strncopy(pMapList->path, path, sizeof(pMapList->path));
496 pMapList->last_modified_time = 0;
500 if (!libsys->FileTime(pMapList->path, FileTime_LastChange, &last_time)
501 || last_time > pMapList->last_modified_time)
508 if ((fp = smcore.filesystem->Open(pMapList->path, "rt", "GAME")) == NULL)
513 delete pMapList->pArray;
514 pMapList->pArray = new CellArray(64);
516 while (!smcore.filesystem->EndOfFile(fp) && smcore.filesystem->ReadLine(buffer, sizeof(buffer), fp) != NULL)
518 size_t len = strlen(buffer);
519 char *ptr = smcore.TrimWhitespace(buffer, len);
522 || strncmp(ptr, "//", 2) == 0)
527 if (strcmp(smcore.GetSourceEngineName(), "insurgency") == 0)
529 // Insurgency (presumably?) doesn't allow spaces in map names
530 // and does use a space to delimit the map name from the map mode
543 if (!gamehelpers->IsMapValid(ptr))
548 if ((blk = pMapList->pArray->push()) != NULL)
550 smcore.strncopy((char *)blk, ptr, 255);
554 smcore.filesystem->Close(fp);
556 pMapList->last_modified_time = last_time;
557 pMapList->serial = ++m_nSerialChange;
560 if (pMapList->pArray == NULL || pMapList->pArray->size() == 0)
565 *pSerial = pMapList->serial;
566 *ppArray = pMapList->pArray;
570 void DumpCache(List<maplist_info_t *> *compat_list)
572 m_ListLookup.clear();
574 List<maplist_info_t *>::iterator iter = m_MapLists.begin();
575 while (iter != m_MapLists.end())
577 if (compat_list != NULL && (*iter)->bIsCompat)
579 compat_list->push_back((*iter));
583 delete (*iter)->pArray;
586 iter = m_MapLists.erase(iter);
590 char m_ConfigFile[PLATFORM_MAX_PATH];
591 time_t m_ConfigLastChanged;
592 ConVar *m_pMapCycleFile;
593 NameHashSet<maplist_info_t *> m_ListLookup;
594 List<maplist_info_t *> m_MapLists;
595 MapListState m_CurState;
596 unsigned int m_IgnoreLevel;
597 maplist_info_t *m_pCurMapList;
601 static cell_t LoadMapList(IPluginContext *pContext, const cell_t *params)
606 CellArray *pArray, *pNewArray;
609 pContext->LocalToPhysAddr(params[2], &addr);
610 pContext->LocalToString(params[3], &str);
613 /* Make sure the input Handle is valid */
615 if (hndl != BAD_HANDLE)
618 HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent);
620 if ((err = handlesys->ReadHandle(hndl, htCellArray, &sec, (void **)&pArray))
623 return pContext->ThrowNativeError("Invalid Handle %x (error %d)", hndl, err);
627 /* Make sure the map list cache is up to date at the root */
628 s_MapLists.UpdateCache();
630 /* Try to get the map list. */
631 if ((pNewArray = s_MapLists.UpdateMapList(pArray, str, addr, flags)) == NULL)
636 /* If the user wanted a new array, create it now. */
637 if (hndl == BAD_HANDLE)
639 if ((hndl = handlesys->CreateHandle(htCellArray, pNewArray, pContext->GetIdentity(), g_pCoreIdent, NULL))
651 static cell_t SetMapListCompatBind(IPluginContext *pContext, const cell_t *params)
655 pContext->LocalToString(params[1], &name);
656 pContext->LocalToString(params[2], &file);
658 s_MapLists.UpdateCache();
659 s_MapLists.AddOrUpdateDefault(name, file);
664 REGISTER_NATIVES(mapListNatives)
666 {"ReadMapList", LoadMapList},
667 {"SetMapListCompatBind", SetMapListCompatBind},