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};
131 fileFound = libsys->FileTime(m_ConfigFile, FileTime_LastChange, &fileTime);
133 /* If the file is found and hasn't changed, bail out now. */
134 if (fileFound && fileTime == m_ConfigLastChanged)
139 /* If the file wasn't found, and we already have entries, we bail out too.
140 * This case lets us optimize when a user deletes the config file, so we
141 * don't reparse every single time the function is called.
143 if (!fileFound && m_MapLists.size() > 0)
148 m_pMapCycleFile = smcore.FindConVar("mapcyclefile");
150 /* Dump everything we know about. */
151 List<maplist_info_t *> compat;
154 /* All this is to add the default entry back in. */
155 maplist_info_t *pDefList = new maplist_info_t;
157 pDefList->bIsPath = true;
158 smcore.strncopy(pDefList->name, "mapcyclefile", sizeof(pDefList->name));
159 g_pSM->BuildPath(Path_Game,
161 sizeof(pDefList->path),
163 m_pMapCycleFile ? smcore.GetCvarString(m_pMapCycleFile) : "mapcycle.txt");
164 pDefList->last_modified_time = 0;
165 pDefList->pArray = NULL;
166 pDefList->serial = 0;
168 m_ListLookup.insert("mapcyclefile", pDefList);
169 m_MapLists.push_back(pDefList);
171 /* Now parse the config file even if we don't know about it.
172 * This will give us a nice error message.
174 if ((error = textparser->ParseFile_SMC(m_ConfigFile, this, &states))
177 const char *errmsg = textparser->GetSMCErrorString(error);
180 errmsg = "Unknown error";
182 smcore.LogError("[SM] Could not parse file \"%s\"", m_ConfigFile);
183 smcore.LogError("[SM] Error on line %d (col %d): %s", states.line, states.col, errmsg);
187 m_ConfigLastChanged = fileTime;
190 /* Now, re-add compat stuff back in if we can. */
191 List<maplist_info_t *>::iterator iter = compat.begin();
192 while (iter != compat.end())
194 if (m_ListLookup.retrieve((*iter)->name) != NULL)
196 /* The compatibility shim is no longer needed. */
197 delete (*iter)->pArray;
202 m_ListLookup.insert((*iter)->name, (*iter));
203 m_MapLists.push_back((*iter));
205 iter = compat.erase(iter);
208 void ReadSMC_ParseStart()
210 m_CurState = MPS_NONE;
212 m_pCurMapList = NULL;
214 SMCResult ReadSMC_NewSection(const SMCStates *states, const char *name)
219 return SMCResult_Continue;
222 if (m_CurState == MPS_NONE)
224 if (strcmp(name, "MapLists") == 0)
226 m_CurState = MPS_GLOBAL;
233 else if (m_CurState == MPS_GLOBAL)
235 m_pCurMapList = new maplist_info_t;
237 memset(m_pCurMapList, 0, sizeof(maplist_info_t));
238 smcore.strncopy(m_pCurMapList->name, name, sizeof(m_pCurMapList->name));
240 m_CurState = MPS_MAPLIST;
242 else if (m_CurState == MPS_MAPLIST)
247 return SMCResult_Continue;
249 SMCResult ReadSMC_KeyValue(const SMCStates *states, const char *key, const char *value)
251 if (m_IgnoreLevel || m_pCurMapList == NULL)
253 return SMCResult_Continue;
256 if (strcmp(key, "file") == 0)
258 g_pSM->BuildPath(Path_Game,
260 sizeof(m_pCurMapList->path),
263 m_pCurMapList->bIsPath = true;
265 else if (strcmp(key, "target") == 0)
267 smcore.strncopy(m_pCurMapList->path, value, sizeof(m_pCurMapList->path));
268 m_pCurMapList->bIsPath = false;
271 return SMCResult_Continue;
273 SMCResult ReadSMC_LeavingSection(const SMCStates *states)
278 return SMCResult_Continue;
281 if (m_CurState == MPS_MAPLIST)
283 if (m_pCurMapList != NULL
284 && m_pCurMapList->path[0] != '\0'
285 && m_ListLookup.retrieve(m_pCurMapList->name) == NULL)
287 m_ListLookup.insert(m_pCurMapList->name, m_pCurMapList);
288 m_MapLists.push_back(m_pCurMapList);
289 m_pCurMapList = NULL;
293 delete m_pCurMapList;
294 m_pCurMapList = NULL;
296 m_CurState = MPS_GLOBAL;
298 else if (m_CurState == MPS_GLOBAL)
300 m_CurState = MPS_NONE;
303 return SMCResult_Continue;
305 void ReadSMC_ParseEnd(bool halted, bool failed)
307 delete m_pCurMapList;
308 m_pCurMapList = NULL;
310 static int sort_maps_in_adt_array(const void *str1, const void *str2)
312 return strcmp((char *)str1, (char *)str2);
314 CellArray *UpdateMapList(CellArray *pUseArray, const char *name, int *pSerial, unsigned int flags)
317 CellArray *pNewArray = NULL;
318 bool success, free_new_array;
320 free_new_array = false;
322 if ((success = GetMapList(&pNewArray, name, &change_serial)) == false)
324 if ((flags & MAPLIST_FLAG_NO_DEFAULT) != MAPLIST_FLAG_NO_DEFAULT)
326 /* If this list failed, and it's not the default, try the default.
328 if (strcmp(name, "default") != 0)
330 success = GetMapList(&pNewArray, name, &change_serial);
332 /* If either of the last two conditions failed, try again if we can. */
333 if (!success && strcmp(name, "mapcyclefile") != 0)
335 success = GetMapList(&pNewArray, "mapcyclefile", &change_serial);
340 /* If there was a success, and the serial has not changed, bail out. */
341 if (success && *pSerial == change_serial)
347 * If there was a success but no map list, we need to look in the maps folder.
348 * If there was a failure and the flag is specified, we need to look in the maps folder.
350 if ((success && pNewArray == NULL)
351 || (!success && ((flags & MAPLIST_FLAG_MAPSFOLDER) == MAPLIST_FLAG_MAPSFOLDER)))
353 pNewArray = new CellArray(64);
354 free_new_array = true;
358 FileFindHandle_t findHandle;
359 const char *fileName = smcore.filesystem->FindFirstEx("maps/*.bsp", "GAME", &findHandle);
363 char buffer[PLATFORM_MAX_PATH];
365 UTIL_StripExtension(fileName, buffer, sizeof(buffer));
367 if (!engine->IsMapValid(buffer))
369 fileName = smcore.filesystem->FindNext(findHandle);
373 if ((blk = pNewArray->push()) == NULL)
375 fileName = smcore.filesystem->FindNext(findHandle);
379 smcore.strncopy((char *)blk, buffer, 255);
381 fileName = smcore.filesystem->FindNext(findHandle);
384 smcore.filesystem->FindClose(findHandle);
386 /* Remove the array if there were no items. */
387 if (pNewArray->size() == 0)
394 qsort(pNewArray->base(),
396 pNewArray->blocksize() * sizeof(cell_t),
397 sort_maps_in_adt_array);
403 /* If there is still no array by this point, bail out. */
404 if (pNewArray == NULL)
410 *pSerial = change_serial;
412 /* If there is no input array, return something temporary. */
413 if (pUseArray == NULL)
421 return pNewArray->clone();
425 /* Clear the input array if necessary. */
426 if ((flags & MAPLIST_FLAG_CLEARARRAY) == MAPLIST_FLAG_CLEARARRAY)
434 for (size_t i = 0; i < pNewArray->size(); i++)
436 blk_dst = pUseArray->push();
437 blk_src = pNewArray->at(i);
438 smcore.strncopy((char *)blk_dst, (char *)blk_src, pUseArray->blocksize() * sizeof(cell_t));
441 /* Free resources if necessary. */
447 /* Return the array we were given. */
451 bool GetMapList(CellArray **ppArray, const char *name, int *pSerial)
454 maplist_info_t *pMapList, **ppMapList;
456 if ((ppMapList = m_ListLookup.retrieve(name)) == NULL)
461 pMapList = *ppMapList;
463 if (!pMapList->bIsPath)
465 return GetMapList(ppArray, pMapList->path, pSerial);
468 /* If it is a path, and the path is "*", assume all files must be used. */
469 if (strcmp(pMapList->path, "*") == 0)
475 if (m_pMapCycleFile != NULL && strcmp(name, "mapcyclefile") == 0)
477 char path[PLATFORM_MAX_PATH];
478 g_pSM->BuildPath(Path_Game,
482 m_pMapCycleFile ? smcore.GetCvarString(m_pMapCycleFile) : "mapcycle.txt");
484 if (strcmp(path, pMapList->path) != 0)
486 smcore.strncopy(pMapList->path, path, sizeof(pMapList->path));
487 pMapList->last_modified_time = 0;
491 if (!libsys->FileTime(pMapList->path, FileTime_LastChange, &last_time)
492 || last_time > pMapList->last_modified_time)
499 if ((fp = fopen(pMapList->path, "rt")) == NULL)
504 delete pMapList->pArray;
505 pMapList->pArray = new CellArray(64);
507 while (!feof(fp) && fgets(buffer, sizeof(buffer), fp) != NULL)
509 size_t len = strlen(buffer);
510 char *ptr = smcore.TrimWhitespace(buffer, len);
513 || strncmp(ptr, "//", 2) == 0)
517 if (!gamehelpers->IsMapValid(ptr))
521 if ((blk = pMapList->pArray->push()) != NULL)
523 smcore.strncopy((char *)blk, ptr, 255);
529 pMapList->last_modified_time = last_time;
530 pMapList->serial = ++m_nSerialChange;
533 if (pMapList->pArray == NULL || pMapList->pArray->size() == 0)
538 *pSerial = pMapList->serial;
539 *ppArray = pMapList->pArray;
543 void DumpCache(List<maplist_info_t *> *compat_list)
545 m_ListLookup.clear();
547 List<maplist_info_t *>::iterator iter = m_MapLists.begin();
548 while (iter != m_MapLists.end())
550 if (compat_list != NULL && (*iter)->bIsCompat)
552 compat_list->push_back((*iter));
556 delete (*iter)->pArray;
559 iter = m_MapLists.erase(iter);
563 char m_ConfigFile[PLATFORM_MAX_PATH];
564 time_t m_ConfigLastChanged;
565 ConVar *m_pMapCycleFile;
566 KTrie<maplist_info_t *> m_ListLookup;
567 List<maplist_info_t *> m_MapLists;
568 MapListState m_CurState;
569 unsigned int m_IgnoreLevel;
570 maplist_info_t *m_pCurMapList;
574 static cell_t LoadMapList(IPluginContext *pContext, const cell_t *params)
579 CellArray *pArray, *pNewArray;
582 pContext->LocalToPhysAddr(params[2], &addr);
583 pContext->LocalToString(params[3], &str);
586 /* Make sure the input Handle is valid */
588 if (hndl != BAD_HANDLE)
591 HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent);
593 if ((err = handlesys->ReadHandle(hndl, htCellArray, &sec, (void **)&pArray))
596 return pContext->ThrowNativeError("Invalid Handle %x (error %d)", hndl, err);
600 /* Make sure the map list cache is up to date at the root */
601 s_MapLists.UpdateCache();
603 /* Try to get the map list. */
604 if ((pNewArray = s_MapLists.UpdateMapList(pArray, str, addr, flags)) == NULL)
609 /* If the user wanted a new array, create it now. */
610 if (hndl == BAD_HANDLE)
612 if ((hndl = handlesys->CreateHandle(htCellArray, pNewArray, pContext->GetIdentity(), g_pCoreIdent, NULL))
624 static cell_t SetMapListCompatBind(IPluginContext *pContext, const cell_t *params)
628 pContext->LocalToString(params[1], &name);
629 pContext->LocalToString(params[2], &file);
631 s_MapLists.UpdateCache();
632 s_MapLists.AddOrUpdateDefault(name, file);
637 REGISTER_NATIVES(mapListNatives)
639 {"ReadMapList", LoadMapList},
640 {"SetMapListCompatBind", SetMapListCompatBind},