]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/common/mapinfo.qc
Perform an expensive search to locate the .arena and .defi files of Quake 3 maps...
[xonotic/xonotic-data.pk3dir.git] / qcsrc / common / mapinfo.qc
1 #include "mapinfo.qh"
2 #if defined(CSQC)
3     #include "../client/defs.qh"
4     #include "util.qh"
5     #include <common/weapons/_all.qh>
6 #elif defined(MENUQC)
7 #elif defined(SVQC)
8     #include "util.qh"
9     #include <common/monsters/_mod.qh>
10 #endif
11
12 #ifdef MENUQC
13 #define WARN_COND false
14 #else
15 bool autocvar_g_mapinfo_ignore_warnings;
16 #define WARN_COND (!autocvar_g_mapinfo_ignore_warnings && MapInfo_Map_bspname == mi_shortname)
17 #endif
18
19 // generic string stuff
20
21 int _MapInfo_Cache_Active;
22 int _MapInfo_Cache_DB_NameToIndex;
23 int _MapInfo_Cache_Buf_IndexToMapData;
24
25 void MapInfo_Cache_Destroy()
26 {
27         if(!_MapInfo_Cache_Active)
28                 return;
29
30         db_close(_MapInfo_Cache_DB_NameToIndex);
31         buf_del(_MapInfo_Cache_Buf_IndexToMapData);
32         _MapInfo_Cache_Active = 0;
33 }
34
35 void MapInfo_Cache_Create()
36 {
37         MapInfo_Cache_Destroy();
38         _MapInfo_Cache_DB_NameToIndex = db_create();
39         _MapInfo_Cache_Buf_IndexToMapData = buf_create();
40         _MapInfo_Cache_Active = 1;
41 }
42
43 void MapInfo_Cache_Invalidate()
44 {
45         if(!_MapInfo_Cache_Active)
46                 return;
47
48         MapInfo_Cache_Create();
49 }
50
51 void MapInfo_Cache_Store()
52 {
53         float i;
54         string s;
55         if(!_MapInfo_Cache_Active)
56                 return;
57
58         s = db_get(_MapInfo_Cache_DB_NameToIndex, MapInfo_Map_bspname);
59         if(s == "")
60         {
61                 i = buf_getsize(_MapInfo_Cache_Buf_IndexToMapData);
62                 db_put(_MapInfo_Cache_DB_NameToIndex, MapInfo_Map_bspname, ftos(i));
63         }
64         else
65                 i = stof(s);
66
67         // now store all the stuff
68         bufstr_set(_MapInfo_Cache_Buf_IndexToMapData,   i, MapInfo_Map_bspname);
69         bufstr_set(_MapInfo_Cache_Buf_IndexToMapData, ++i, MapInfo_Map_title);
70         bufstr_set(_MapInfo_Cache_Buf_IndexToMapData, ++i, MapInfo_Map_titlestring);
71         bufstr_set(_MapInfo_Cache_Buf_IndexToMapData, ++i, MapInfo_Map_description);
72         bufstr_set(_MapInfo_Cache_Buf_IndexToMapData, ++i, MapInfo_Map_author);
73         bufstr_set(_MapInfo_Cache_Buf_IndexToMapData, ++i, ftos(MapInfo_Map_supportedGametypes));
74         bufstr_set(_MapInfo_Cache_Buf_IndexToMapData, ++i, ftos(MapInfo_Map_supportedFeatures));
75         bufstr_set(_MapInfo_Cache_Buf_IndexToMapData, ++i, ftos(MapInfo_Map_flags));
76 }
77
78 float MapInfo_Cache_Retrieve(string map)
79 {
80         float i;
81         string s;
82         if(!_MapInfo_Cache_Active)
83                 return 0;
84
85         s = db_get(_MapInfo_Cache_DB_NameToIndex, map);
86         if(s == "")
87                 return 0;
88         i = stof(s);
89
90         // now retrieve all the stuff
91         MapInfo_Map_bspname = bufstr_get(_MapInfo_Cache_Buf_IndexToMapData, i);
92         MapInfo_Map_title = bufstr_get(_MapInfo_Cache_Buf_IndexToMapData, ++i);
93         MapInfo_Map_titlestring = bufstr_get(_MapInfo_Cache_Buf_IndexToMapData, ++i);
94         MapInfo_Map_description = bufstr_get(_MapInfo_Cache_Buf_IndexToMapData, ++i);
95         MapInfo_Map_author = bufstr_get(_MapInfo_Cache_Buf_IndexToMapData, ++i);
96         MapInfo_Map_supportedGametypes = stof(bufstr_get(_MapInfo_Cache_Buf_IndexToMapData, ++i));
97         MapInfo_Map_supportedFeatures = stof(bufstr_get(_MapInfo_Cache_Buf_IndexToMapData, ++i));
98         MapInfo_Map_flags = stof(bufstr_get(_MapInfo_Cache_Buf_IndexToMapData, ++i));
99
100         return 1;
101 }
102
103 // GLOB HANDLING (for all BSP files)
104 float _MapInfo_globopen;
105 float _MapInfo_globcount;
106 float _MapInfo_globhandle;
107 string _MapInfo_GlobItem(float i)
108 {
109         string s;
110         if(!_MapInfo_globopen)
111                 return string_null;
112         s = search_getfilename(_MapInfo_globhandle, i);
113         return substring(s, 5, strlen(s) - 9); // without maps/ and .bsp
114 }
115
116 void MapInfo_Enumerate()
117 {
118         if(_MapInfo_globopen)
119         {
120                 search_end(_MapInfo_globhandle);
121                 _MapInfo_globopen = 0;
122         }
123         MapInfo_Cache_Invalidate();
124         _MapInfo_globhandle = search_begin("maps/*.bsp", true, true);
125         if(_MapInfo_globhandle >= 0)
126         {
127                 _MapInfo_globcount = search_getsize(_MapInfo_globhandle);
128                 _MapInfo_globopen = 1;
129         }
130         else
131                 _MapInfo_globcount = 0;
132 }
133
134 // filter the info by game type mask (updates MapInfo_count)
135 //
136 float _MapInfo_filtered;
137 float _MapInfo_filtered_allocated;
138 float MapInfo_FilterList_Lookup(float i)
139 {
140         return stof(bufstr_get(_MapInfo_filtered, i));
141 }
142
143 void _MapInfo_FilterList_swap(float i, float j, entity pass)
144 {
145         string h;
146         h = bufstr_get(_MapInfo_filtered, i);
147         bufstr_set(_MapInfo_filtered, i, bufstr_get(_MapInfo_filtered, j));
148         bufstr_set(_MapInfo_filtered, j, h);
149 }
150
151 float _MapInfo_FilterList_cmp(float i, float j, entity pass)
152 {
153         string a, b;
154         a = _MapInfo_GlobItem(stof(bufstr_get(_MapInfo_filtered, i)));
155         b = _MapInfo_GlobItem(stof(bufstr_get(_MapInfo_filtered, j)));
156         return strcasecmp(a, b);
157 }
158
159 float MapInfo_FilterGametype(Gametype pGametype, int pFeatures, int pFlagsRequired, int pFlagsForbidden, bool pAbortOnGenerate)
160 {
161         return _MapInfo_FilterGametype(pGametype.m_flags, pFeatures, pFlagsRequired, pFlagsForbidden, pAbortOnGenerate);
162 }
163 float _MapInfo_FilterGametype(int pGametype, int pFeatures, int pFlagsRequired, int pFlagsForbidden, bool pAbortOnGenerate)
164 {
165         float i, j;
166         if (!_MapInfo_filtered_allocated)
167         {
168                 _MapInfo_filtered_allocated = 1;
169                 _MapInfo_filtered = buf_create();
170         }
171         MapInfo_count = 0;
172         for(i = 0, j = -1; i < _MapInfo_globcount; ++i)
173         {
174                 if(MapInfo_Get_ByName(_MapInfo_GlobItem(i), 1, NULL) == 2) // if we generated one... BAIL OUT and let the caller continue in the next frame.
175                         if(pAbortOnGenerate)
176                         {
177                                 LOG_TRACE("Autogenerated a .mapinfo, doing the rest later.");
178                                 MapInfo_progress = i / _MapInfo_globcount;
179                                 return 0;
180                         }
181                 if((MapInfo_Map_supportedGametypes & pGametype) != 0)
182                 if((MapInfo_Map_supportedFeatures & pFeatures) == pFeatures)
183                 if((MapInfo_Map_flags & pFlagsForbidden) == 0)
184                 if((MapInfo_Map_flags & pFlagsRequired) == pFlagsRequired)
185                         bufstr_set(_MapInfo_filtered, ++j, ftos(i));
186         }
187         MapInfo_count = j + 1;
188         MapInfo_ClearTemps();
189
190         // sometimes the glob isn't sorted nicely, so fix it here...
191         heapsort(MapInfo_count, _MapInfo_FilterList_swap, _MapInfo_FilterList_cmp, NULL);
192
193         return 1;
194 }
195 void MapInfo_FilterString(string sf)
196 {
197         // this function further filters _MapInfo_filtered, which is prepared by MapInfo_FilterGametype by string
198         float i, j;
199         string title;
200
201         for(i = 0, j = -1; i < MapInfo_count; ++i)
202         {
203                 if (MapInfo_Get_ByID(i))
204                 {
205                         // prepare for keyword filter
206                         if (MapInfo_Map_title && strstrofs(MapInfo_Map_title, "<TITLE>", 0) == -1)
207                                 title = MapInfo_Map_title;
208                         else
209                                 title = MapInfo_Map_bspname;
210                         // keyword filter
211                         if((strstrofs(strtolower(title), strtolower(sf), 0)) >= 0)
212                                 bufstr_set(_MapInfo_filtered, ++j, bufstr_get(_MapInfo_filtered, i));
213                 }
214         }
215         MapInfo_count = j + 1;
216         MapInfo_ClearTemps();
217
218         // sometimes the glob isn't sorted nicely, so fix it here...
219         heapsort(MapInfo_count, _MapInfo_FilterList_swap, _MapInfo_FilterList_cmp, NULL);
220 }
221
222 void MapInfo_Filter_Free()
223 {
224         if(_MapInfo_filtered_allocated)
225         {
226                 buf_del(_MapInfo_filtered);
227                 _MapInfo_filtered_allocated = 0;
228         }
229 }
230
231 // load info about the i-th map into the MapInfo_Map_* globals
232 string MapInfo_BSPName_ByID(float i)
233 {
234         return _MapInfo_GlobItem(MapInfo_FilterList_Lookup(i));
235 }
236
237 string unquote(string s)
238 {
239         float l = strlen(s);
240         for(float i = 0; i < l; ++i)
241         {
242                 string ch = substring(s, i, 1);
243                 if((ch != " ") && (ch != "\""))
244                 {
245                         for(float j = l - i - 1; j > 0; --j)
246                         {
247                                 ch = substring(s, i+j, 1);
248                                 if(ch != " ") if(ch != "\"")
249                                         return substring(s, i, j+1);
250                         }
251                         return substring(s, i, 1);
252                 }
253         }
254         return "";
255 }
256
257 float MapInfo_Get_ByID(float i)
258 {
259         if(MapInfo_Get_ByName(MapInfo_BSPName_ByID(i), 0, NULL))
260                 return 1;
261         return 0;
262 }
263
264 string _MapInfo_Map_worldspawn_music;
265
266 float _MapInfo_Generate(string pFilename) // 0: failure, 1: ok ent, 2: ok bsp
267 {
268         string fn;
269         float fh;
270         string s, k, v;
271         vector o;
272         float i;
273         float inWorldspawn;
274         float r;
275         float diameter, spawnpoints;
276         float spawnplaces;
277
278         vector mapMins, mapMaxs;
279
280         r = 1;
281         fn = strcat("maps/", pFilename, ".ent");
282         fh = fopen(fn, FILE_READ);
283         if(fh < 0)
284         {
285                 r = 2;
286                 fn = strcat("maps/", pFilename, ".bsp");
287                 fh = fopen(fn, FILE_READ);
288         }
289         if(fh < 0)
290                 return 0;
291         LOG_INFO("Analyzing ", fn, " to generate initial mapinfo");
292
293         inWorldspawn = 2;
294         MapInfo_Map_flags = 0;
295         MapInfo_Map_supportedGametypes = 0;
296         spawnpoints = 0;
297         spawnplaces = 0;
298         _MapInfo_Map_worldspawn_music = "";
299         mapMins = '0 0 0';
300         mapMaxs = '0 0 0';
301
302         for (;;)
303         {
304                 if (!((s = fgets(fh))))
305                         break;
306                 if(inWorldspawn == 1)
307                         if(startsWith(s, "}"))
308                                 inWorldspawn = 0;
309                 k = unquote(car(s));
310                 v = unquote(cdr(s));
311                 if(inWorldspawn)
312                 {
313                         if(k == "classname" && v == "worldspawn")
314                                 inWorldspawn = 1;
315                         else if(k == "author")
316                                 MapInfo_Map_author = v;
317                         else if(k == "_description")
318                                 MapInfo_Map_description = v;
319                         else if(k == "music")
320                                 _MapInfo_Map_worldspawn_music = v;
321                         else if(k == "noise")
322                                 _MapInfo_Map_worldspawn_music = v;
323                         else if(k == "message")
324                         {
325                                 i = strstrofs(v, " by ", 0);
326                                 if(MapInfo_Map_author == "<AUTHOR>" && i >= 0)
327                                 {
328                                         MapInfo_Map_title = substring(v, 0, i);
329                                         MapInfo_Map_author = substring(v, i + 4, strlen(v) - (i + 4));
330                                 }
331                                 else
332                                         MapInfo_Map_title = v;
333                         }
334                 }
335                 else
336                 {
337                         if(k == "origin")
338                         {
339                                 o = stov(strcat("'", v, "'"));
340                                 mapMins.x = min(mapMins.x, o.x);
341                                 mapMins.y = min(mapMins.y, o.y);
342                                 mapMins.z = min(mapMins.z, o.z);
343                                 mapMaxs.x = max(mapMaxs.x, o.x);
344                                 mapMaxs.y = max(mapMaxs.y, o.y);
345                                 mapMaxs.z = max(mapMaxs.z, o.z);
346                         }
347                         else if(k == "race_place")
348                         {
349                                 if(stof(v) > 0)
350                                         spawnplaces = 1;
351                         }
352                         else if(k == "classname")
353                         {
354                                 if(v == "info_player_team1")
355                                         ++spawnpoints;
356                                 else if(v == "info_player_team2")
357                                         ++spawnpoints;
358                                 else if(v == "info_player_start")
359                                         ++spawnpoints;
360                                 else if(v == "info_player_deathmatch")
361                                         ++spawnpoints;
362                                 else if(v == "weapon_nex")
363                                         { }
364                                 else if(v == "weapon_railgun")
365                                         { }
366                                 else if(startsWith(v, "weapon_"))
367                                         MapInfo_Map_supportedFeatures |= MAPINFO_FEATURE_WEAPONS;
368                                 else if(startsWith(v, "turret_"))
369                                         MapInfo_Map_supportedFeatures |= MAPINFO_FEATURE_TURRETS;
370                                 else if(startsWith(v, "vehicle_"))
371                                         MapInfo_Map_supportedFeatures |= MAPINFO_FEATURE_VEHICLES;
372                                 else if(startsWith(v, "monster_"))
373                                         MapInfo_Map_supportedFeatures |= MAPINFO_FEATURE_MONSTERS;
374                                 else if(v == "target_music" || v == "trigger_music")
375                                         _MapInfo_Map_worldspawn_music = string_null; // don't use regular BGM
376                                 else
377                                         FOREACH(Gametypes, true, it.m_generate_mapinfo(it, v));
378                         }
379                 }
380         }
381         if(inWorldspawn)
382         {
383                 LOG_WARN(fn, " ended still in worldspawn, BUG");
384                 return 0;
385         }
386         diameter = vlen(mapMaxs - mapMins);
387
388         int twoBaseModes = 0;
389         FOREACH(Gametypes, it.m_isTwoBaseMode(), twoBaseModes |= it.m_flags);
390         if(twoBaseModes && (twoBaseModes &= MapInfo_Map_supportedGametypes))
391         {
392                 // we have a symmetrical map, don't add the modes without bases
393         }
394         else
395         {
396                 FOREACH(Gametypes, it.m_isAlwaysSupported(it, spawnpoints, diameter), MapInfo_Map_supportedGametypes |= it.m_flags);
397         }
398
399         if(MapInfo_Map_supportedGametypes & MAPINFO_TYPE_RACE.m_flags)
400         if(!spawnplaces)
401         {
402                 MapInfo_Map_supportedGametypes &= ~MAPINFO_TYPE_RACE.m_flags;
403                 MapInfo_Map_supportedGametypes |= MAPINFO_TYPE_CTS.m_flags;
404         }
405
406         LOG_TRACE("-> diameter ",    ftos(diameter));
407         LOG_TRACE(";  spawnpoints ", ftos(spawnpoints));
408         LOG_TRACE(";  modes ",       ftos(MapInfo_Map_supportedGametypes));
409
410         fclose(fh);
411
412         return r;
413 }
414
415 void _MapInfo_Map_Reset()
416 {
417         MapInfo_Map_title = "<TITLE>";
418         MapInfo_Map_titlestring = "<TITLE>";
419         MapInfo_Map_description = "<DESCRIPTION>";
420         MapInfo_Map_author = "<AUTHOR>";
421         MapInfo_Map_supportedGametypes = 0;
422         MapInfo_Map_supportedFeatures = 0;
423         MapInfo_Map_flags = 0;
424         MapInfo_Map_clientstuff = "";
425         MapInfo_Map_fog = "";
426         MapInfo_Map_mins = '0 0 0';
427         MapInfo_Map_maxs = '0 0 0';
428 }
429
430 string _MapInfo_GetDefault(Gametype t)
431 {
432         return t.m_legacydefaults;
433 }
434
435 void _MapInfo_Map_ApplyGametype(string s, Gametype pWantedType, Gametype pThisType, int load_default)
436 {
437         string sa;
438         MapInfo_Map_supportedGametypes |= pThisType.m_flags;
439         if(!(pThisType.m_flags & pWantedType.m_flags))
440                 return;
441
442         if(load_default)
443                 _MapInfo_Map_ApplyGametype(_MapInfo_GetDefault(pThisType), pWantedType, pThisType, false);
444
445         if(!pWantedType.frags) // these modes don't use fraglimit
446         {
447                 cvar_set("fraglimit", "0");
448         }
449         else
450         {
451                 sa = car(s);
452                 if(sa != "")
453                         cvar_set("fraglimit", sa);
454                 s = cdr(s);
455         }
456
457         sa = car(s);
458         if(sa != "")
459                 cvar_set("timelimit", sa);
460         s = cdr(s);
461
462         if(pWantedType.m_setTeams)
463         {
464                 sa = car(s);
465                 if(sa != "")
466                         pWantedType.m_setTeams(sa);
467                 s = cdr(s);
468         }
469
470         // rc = timelimit timelimit_qualification laps laps_teamplay
471         if(pWantedType == MAPINFO_TYPE_RACE)
472         {
473                 cvar_set("fraglimit", "0"); // special case!
474
475                 sa = car(s); if(sa == "") sa = cvar_string("timelimit");
476                 cvar_set("g_race_qualifying_timelimit", sa);
477                 s = cdr(s);
478
479                 sa = car(s);
480                 if(sa != "")
481                         if(cvar("g_race_teams") < 2)
482                                 cvar_set("fraglimit", sa);
483                 s = cdr(s);
484
485                 sa = car(s);
486                 if(sa != "")
487                         if(cvar("g_race_teams") >= 2)
488                                 cvar_set("fraglimit", sa);
489                 s = cdr(s);
490         }
491
492         if(!pWantedType.frags) // these modes don't use fraglimit
493         {
494                 cvar_set("leadlimit", "0");
495         }
496         else
497         {
498                 sa = car(s);
499                 if(sa != "")
500                         cvar_set("leadlimit", sa);
501                 s = cdr(s);
502         }
503 }
504
505 string _MapInfo_GetDefaultEx(Gametype t)
506 {
507         return t ? t.model2 : "";
508 }
509
510 float _MapInfo_GetTeamPlayBool(Gametype t)
511 {
512         return t ? t.team : false;
513 }
514
515 void _MapInfo_Map_ApplyGametypeEx(string s, Gametype pWantedType, Gametype pThisType)
516 {
517         MapInfo_Map_supportedGametypes |= pThisType.m_flags;
518         if (!(pThisType.m_flags & pWantedType.m_flags))
519                 return;
520
521         // reset all the cvars to their defaults
522
523         cvar_set("timelimit", cvar_defstring("timelimit"));
524         cvar_set("leadlimit", cvar_defstring("leadlimit"));
525         cvar_set("fraglimit", cvar_defstring("fraglimit"));
526         FOREACH(Gametypes, true, it.m_parse_mapinfo(string_null, string_null));
527
528         string fraglimit_normal = string_null;
529         string fraglimit_teams = string_null;
530
531         for (s = strcat(_MapInfo_GetDefaultEx(pWantedType), " ", s); s != ""; s = cdr(s)) {
532                 string sa = car(s);
533                 if (sa == "") continue;
534                 int p = strstrofs(sa, "=", 0);
535                 if (p < 0) {
536                         if(WARN_COND)
537                                 LOG_WARNF("Invalid gametype setting in mapinfo for gametype %s: %s", MapInfo_Type_ToString(pWantedType), sa);
538                         continue;
539                 }
540                 string k = substring(sa, 0, p);
541                 string v = substring(sa, p + 1, -1);
542                 bool handled = true;
543                 switch (k) {
544                         case "timelimit":
545                         {
546                                 cvar_set("timelimit", v);
547                                 break;
548                         }
549                         case "leadlimit":
550                         {
551                                 cvar_set("leadlimit", v);
552                                 break;
553                         }
554                         case "pointlimit":
555                         case "fraglimit":
556                         case "lives":
557                         case "laplimit":
558                         case "caplimit":
559                         {
560                                 fraglimit_normal = v;
561                                 break;
562                         }
563                         case "teampointlimit":
564                         case "teamlaplimit":
565                         {
566                                 fraglimit_teams = v;
567                                 break;
568                         }
569                         default:
570                         {
571                             handled = false;
572                             break;
573                         }
574                 }
575                 FOREACH(Gametypes, true, handled |= it.m_parse_mapinfo(k, v));
576                 if (!handled && WARN_COND)
577             LOG_WARNF("Invalid gametype setting in mapinfo for gametype %s: %s", MapInfo_Type_ToString(pWantedType), sa);
578         }
579
580         if (pWantedType == MAPINFO_TYPE_RACE && cvar("g_race_teams") >= 2)
581         {
582                 if(fraglimit_teams)
583                         cvar_set("fraglimit", fraglimit_teams);
584         }
585         else
586         {
587                 if(fraglimit_normal)
588                         cvar_set("fraglimit", fraglimit_normal);
589         }
590 }
591
592 Gametype MapInfo_Type_FromString(string gtype)
593 {
594         string replacement = "";
595         bool do_warn = true;
596         switch (gtype)
597         {
598                 case "nexball":   replacement = "nb"; break;
599                 case "freezetag": replacement = "ft"; break;
600                 case "keepaway":  replacement = "ka"; break;
601                 case "invasion":  replacement = "inv"; break;
602                 case "assault":   replacement = "as"; break;
603                 case "race":      replacement = "rc"; break;
604                 // quake 3 compat
605                 case "ffa":       replacement = "dm"; do_warn = false; break;
606                 case "cctf":
607                 case "oneflag":
608                 case "ctf":       replacement = "ctf"; do_warn = false; break;
609                 case "team":      replacement = "tdm"; do_warn = false; break;
610                 case "tourney":   replacement = "duel"; do_warn = false; break;
611         }
612         if (replacement != "")
613         {
614                 if(do_warn && WARN_COND)
615                         LOG_WARNF("MapInfo_Type_FromString (probably %s): using deprecated name '%s'. Should use '%s'.", MapInfo_Map_bspname, gtype, replacement);
616                 gtype = replacement;
617         }
618         FOREACH(Gametypes, it.mdl == gtype, return it);
619         return NULL;
620 }
621
622 string MapInfo_Type_Description(Gametype t)
623 {
624         return t ? t.gametype_description : "";
625 }
626
627 string MapInfo_Type_ToString(Gametype t)
628 {
629         return t ? t.mdl : "";
630 }
631
632 string MapInfo_Type_ToText(Gametype t)
633 {
634         /* xgettext:no-c-format */
635         return t ? t.message : _("@!#%'n Tuba Throwing");
636 }
637
638 void _MapInfo_Parse_Settemp(string pFilename, string acl, float type, string s, float recurse)
639 {
640         string t;
641         float fh, o;
642         t = car(s); s = cdr(s);
643
644         // limited support of "" and comments
645         //   remove trailing and leading " of t
646         if(substring(t, 0, 1) == "\"")
647         {
648                 if(substring(t, -1, 1) == "\"")
649                         t = substring(t, 1, -2);
650         }
651
652         //   remove leading " of s
653         if(substring(s, 0, 1) == "\"")
654         {
655                 s = substring(s, 1, -1);
656         }
657         //   remove trailing " of s, and all that follows (cvar description)
658         o = strstrofs(s, "\"", 0);
659         if(o >= 0)
660                 s = substring(s, 0, o);
661
662         //   remove // comments
663         o = strstrofs(s, "//", 0);
664         if(o >= 0)
665                 s = substring(s, 0, o);
666
667         //   remove trailing spaces
668         while(substring(s, -1, 1) == " ")
669                 s = substring(s, 0, -2);
670
671         if(t == "#include")
672         {
673                 if(recurse > 0)
674                 {
675                         fh = fopen(s, FILE_READ);
676                         if(fh < 0)
677                         {
678                                 if(WARN_COND)
679                                         LOG_WARN("Map ", pFilename, " references not existing config file ", s);
680                         }
681                         else
682                         {
683                                 while((s = fgets(fh)))
684                                 {
685                                         // catch different sorts of comments
686                                         if(s == "")                    // empty lines
687                                                 continue;
688                                         if(substring(s, 0, 1) == "#")  // UNIX style
689                                                 continue;
690                                         if(substring(s, 0, 2) == "//") // C++ style
691                                                 continue;
692                                         if(substring(s, 0, 1) == "_")  // q3map style
693                                                 continue;
694
695                                         if(substring(s, 0, 4) == "set ")
696                                                 s = substring(s, 4, -1);
697                                         if(substring(s, 0, 5) == "seta ")
698                                                 s = substring(s, 5, -1);
699
700                                         _MapInfo_Parse_Settemp(pFilename, acl, type, s, recurse - 1);
701                                 }
702                                 fclose(fh);
703                         }
704                 }
705                 else if(WARN_COND)
706                         LOG_WARN("Map ", pFilename, " uses too many levels of inclusion");
707         }
708         else if(t == ""
709                 || !cvar_value_issafe(t)
710                 || !cvar_value_issafe(s)
711                 || matchacl(MAPINFO_SETTEMP_ACL_SYSTEM, t) <= 0)
712         {
713                 if (WARN_COND)
714                         LOG_WARN("Map ", pFilename, " contains a potentially harmful setting, ignored");
715         }
716         else if(matchacl(acl, t) <= 0)
717         {
718                 if (WARN_COND)
719                         LOG_WARN("Map ", pFilename, " contains a denied setting, ignored");
720         }
721         else
722         {
723                 if(type == 0) // server set
724                 {
725                         LOG_TRACE("Applying temporary setting ", t, " := ", s);
726                 #if 0
727                         if(cvar("g_campaign"))
728                                 cvar_set(t, s); // this is a wrapper and is always temporary anyway; no need to backup old values then
729                         else
730                 #endif
731                                 cvar_settemp(t, s);
732                 }
733                 else
734                 {
735                         LOG_TRACE("Applying temporary client setting ", t, " := ", s);
736                         MapInfo_Map_clientstuff = strcat(
737                                         MapInfo_Map_clientstuff, "cl_cmd settemp \"", t, "\" \"", s, "\"\n"
738                                         );
739                 }
740         }
741 }
742
743 float MapInfo_isRedundant(string fn, string t)
744 {
745         // normalize file name
746         fn = strreplace("_", "", fn);
747         fn = strreplace("-", "", fn);
748
749         // normalize visible title
750         t = strreplace(":", "", t);
751         t = strreplace(" ", "", t);
752         t = strreplace("_", "", t);
753         t = strreplace("-", "", t);
754         t = strreplace("'", "", t);
755         t = strdecolorize(t);
756
757         // we allow the visible title to have punctuation the file name does
758         // not, but not vice versa
759         if(!strcasecmp(fn, t))
760                 return true;
761
762         return false;
763 }
764
765 void _MapInfo_ParseArena(int fh, Gametype pGametypeToSet, bool isdefi)
766 {
767         string t, s;
768         for (;;)
769         {
770                 if (!((s = fgets(fh))))
771                         break;
772
773                 // catch different sorts of comments
774                 if(s == "")                    // empty lines
775                         continue;
776                 if(substring(s, 0, 1) == "#")  // UNIX style
777                         continue;
778                 if(substring(s, 0, 2) == "//") // C++ style
779                         continue;
780                 if(substring(s, 0, 1) == "_")  // q3map style
781                         continue;
782                 if(s == "{" || s == "}")       // opening/closing brackets TODO: make sure we're checking this map's brackets! Q3 can have multiple
783                         continue;
784
785                 float p = strstrofs(s, "//", 0);
786                 if(p >= 0)
787                         s = substring(s, 0, p);
788
789                 t = car(s); s = cdr(s);
790                 //   remove trailing spaces
791                 while(substring(s, -1, 1) == " ")
792                         s = substring(s, 0, -2);
793                 //   remove leading spaces
794                 while(substring(s, 0, 1) == " ")
795                         s = substring(s, 1, -1);
796                 // limited support of ""
797                 //   remove trailing and leading " of s
798                 if(substring(s, 0, 1) == "\"")
799                 {
800                         if(substring(s, -1, 1) == "\"")
801                                 s = substring(s, 1, -2);
802                 }
803                 if(t == "longname")
804                 {
805                         // in .defi files, this is the description, whereas in .arena files, this is generally the title
806                         if(isdefi)
807                                 MapInfo_Map_description = s;
808                         else
809                                 MapInfo_Map_title = s;
810                 }
811                 else if(t == "author")
812                         MapInfo_Map_author = s;
813                 else if(t == "type")
814                 {
815                         // if there is a valid gametype in this .arena file, include it in the menu
816                         MapInfo_Map_supportedFeatures |= MAPINFO_FEATURE_WEAPONS;
817                         // type in quake 3 holds all the supported gametypes, so we must loop through all of them
818                         FOREACH_WORD(s, true,
819                         {
820                                 Gametype f = MapInfo_Type_FromString(it);
821                                 if(f)
822                                         _MapInfo_Map_ApplyGametype ("", pGametypeToSet, f, true);
823                         });
824                 }
825                 else if(t == "style" && isdefi)
826                 {
827                         // we have a defrag map on our hands, add CTS!
828                         // TODO: styles
829                         _MapInfo_Map_ApplyGametype ("", pGametypeToSet, MAPINFO_TYPE_CTS, true);
830                 }
831                 // TODO: fraglimit
832         }
833 }
834
835 #if defined(CSQC) || defined(MENUQC)
836 string(string filename) whichpack = #503;
837 #endif
838 string _MapInfo_FindArenaFile(string pFilename, string extension)
839 {
840         string base_pack = whichpack(strcat("maps/", pFilename, ".bsp"));
841         string fallback = strcat("scripts/", pFilename, extension);
842         if(base_pack == "") // this map isn't packaged!
843                 return fallback;
844
845         int glob = search_begin(strcat("scripts/*", extension), true, true);
846         if(glob < 0)
847                 return fallback;
848         int n = search_getsize(glob);
849         for(int j = 0; j < n; ++j)
850         {
851                 string file = search_getfilename(glob, j);
852                 if(whichpack(file) != base_pack)
853                         continue; // not in the same pk3!
854
855                 int fh = fopen(file, FILE_READ);
856                 if(fh < 0)
857                         continue; // how?
858                 for(string s; (s = fgets(fh)); )
859                 {
860                         int offset = strstrofs(s, "map", 0);
861                         if(offset >= 0)
862                         {
863                                 if(strstrofs(strtolower(s), strcat("\"", strtolower(pFilename), "\""), offset) >= 0) // quake 3 is case insensitive
864                                 {
865                                         fclose(fh);
866                                         search_end(glob);
867                                         return file; // FOUND IT!
868                                 }
869                         }
870                 }
871                 fclose(fh);
872         }
873
874         search_end(glob);
875         return fallback; // if we get here, a valid .arena file could not be found
876 }
877
878 // load info about a map by name into the MapInfo_Map_* globals
879 float MapInfo_Get_ByName_NoFallbacks(string pFilename, int pAllowGenerate, Gametype pGametypeToSet)
880 {
881         string fn;
882         string s, t;
883         float fh;
884         int f, i;
885         float r, n;
886         string acl;
887
888         acl = MAPINFO_SETTEMP_ACL_USER;
889
890         if(strstrofs(pFilename, "/", 0) >= 0)
891         {
892                 LOG_WARN("Invalid character in map name, ignored");
893                 return 0;
894         }
895
896         if(pGametypeToSet == NULL)
897                 if(MapInfo_Cache_Retrieve(pFilename))
898                         return 1;
899
900         r = 1;
901
902         MapInfo_Map_bspname = pFilename;
903
904         // default all generic fields so they have "good" values in case something fails
905         fn = strcat("maps/", pFilename, ".mapinfo");
906         fh = fopen(fn, FILE_READ);
907         if(fh < 0)
908         {
909                 bool isdefi = false;
910                 // try for a .arena or .defi file if no .mapinfo exists
911                 fn = _MapInfo_FindArenaFile(pFilename, ".arena");
912                 fh = fopen(fn, FILE_READ);
913                 if(fh < 0)
914                 {
915                         isdefi = true;
916                         fn = _MapInfo_FindArenaFile(pFilename, ".defi");
917                         fh = fopen(fn, FILE_READ);
918                 }
919                 if(fh >= 0)
920                 {
921                         _MapInfo_Map_Reset();
922                         _MapInfo_ParseArena(fh, pGametypeToSet, isdefi);
923                         goto mapinfo_handled; // skip generation
924                 }
925
926                 fn = strcat("maps/autogenerated/", pFilename, ".mapinfo");
927                 fh = fopen(fn, FILE_READ);
928                 if(fh < 0)
929                 {
930                         if(!pAllowGenerate)
931                                 return 0;
932                         _MapInfo_Map_Reset();
933                         r = _MapInfo_Generate(pFilename);
934                         if(!r)
935                                 return 0;
936                         fh = fopen(fn, FILE_WRITE);
937                         fputs(fh, strcat("title ", MapInfo_Map_title, "\n"));
938                         fputs(fh, strcat("description ", MapInfo_Map_description, "\n"));
939                         fputs(fh, strcat("author ", MapInfo_Map_author, "\n"));
940                         if(_MapInfo_Map_worldspawn_music != "")
941                         {
942                                 if(
943                                         substring(_MapInfo_Map_worldspawn_music, strlen(_MapInfo_Map_worldspawn_music) - 4, 4) == ".wav"
944                                         ||
945                                         substring(_MapInfo_Map_worldspawn_music, strlen(_MapInfo_Map_worldspawn_music) - 4, 4) == ".ogg"
946                                 )
947                                         fputs(fh, strcat("cdtrack ", substring(_MapInfo_Map_worldspawn_music, 0, strlen(_MapInfo_Map_worldspawn_music) - 4), "\n"));
948                                 else
949                                         fputs(fh, strcat("cdtrack ", _MapInfo_Map_worldspawn_music, "\n"));
950                         }
951                         else
952                         {
953                                 n = tokenize_console(cvar_string("g_cdtracks_remaplist"));
954                                 s = strcat(" ", cvar_string("g_cdtracks_dontusebydefault"), " ");
955                                 for (;;)
956                                 {
957                                         i = floor(random() * n);
958                                         if(strstrofs(s, strcat(" ", argv(i), " "), 0) < 0)
959                                                 break;
960                                 }
961                                 fputs(fh, strcat("cdtrack ", ftos(i + 1), "\n"));
962                         }
963                         if(MapInfo_Map_supportedFeatures & MAPINFO_FEATURE_WEAPONS)
964                                 fputs(fh, "has weapons\n");
965                         else
966                                 fputs(fh, "// uncomment this if you added weapon pickups: has weapons\n");
967                         if(MapInfo_Map_supportedFeatures & MAPINFO_FEATURE_TURRETS)
968                                 fputs(fh, "has turrets\n");
969                         else
970                                 fputs(fh, "// uncomment this if you added turrets: has turrets\n");
971                         if(MapInfo_Map_supportedFeatures & MAPINFO_FEATURE_VEHICLES)
972                                 fputs(fh, "has vehicles\n");
973                         else
974                                 fputs(fh, "// uncomment this if you added vehicles: has vehicles\n");
975                         if(MapInfo_Map_flags & MAPINFO_FLAG_FRUSTRATING)
976                                 fputs(fh, "frustrating\n");
977
978                         FOREACH(Gametypes, MapInfo_Map_supportedGametypes & it.m_flags, {
979                                 fputs(fh, sprintf("gametype %s // defaults: %s\n", MapInfo_Type_ToString(it), _MapInfo_GetDefaultEx(it)));
980                         });
981
982                         fputs(fh, "// optional: fog density red green blue alpha mindist maxdist\n");
983                         fputs(fh, "// optional: settemp_for_type (all|gametypename) cvarname value\n");
984                         fputs(fh, "// optional: clientsettemp_for_type (all|gametypename) cvarname value\n");
985                         fputs(fh, "// optional: size mins_x mins_y mins_z maxs_x maxs_y maxs_z\n");
986                         fputs(fh, "// optional: hidden\n");
987
988                         fclose(fh);
989                         r = 2;
990                         // return r;
991                         fh = fopen(fn, FILE_READ);
992                         if(fh < 0)
993                                 error("... but I just wrote it!");
994                 }
995
996                 if(WARN_COND)
997                         LOG_WARN("autogenerated mapinfo file ", fn, " has been loaded; please edit that file and move it to maps/", pFilename, ".mapinfo");
998         }
999
1000         _MapInfo_Map_Reset();
1001         for (;;)
1002         {
1003                 if (!((s = fgets(fh))))
1004                         break;
1005
1006                 // catch different sorts of comments
1007                 if(s == "")                    // empty lines
1008                         continue;
1009                 if(substring(s, 0, 1) == "#")  // UNIX style
1010                         continue;
1011                 if(substring(s, 0, 2) == "//") // C++ style
1012                         continue;
1013                 if(substring(s, 0, 1) == "_")  // q3map style
1014                         continue;
1015
1016                 float p = strstrofs(s, "//", 0);
1017                 if(p >= 0)
1018                         s = substring(s, 0, p);
1019
1020                 t = car(s); s = cdr(s);
1021                 if(t == "title")
1022                         MapInfo_Map_title = s;
1023                 else if(t == "description")
1024                         MapInfo_Map_description = s;
1025                 else if(t == "author")
1026                         MapInfo_Map_author = s;
1027                 else if(t == "has")
1028                 {
1029                         t = car(s); // s = cdr(s);
1030                         if     (t == "weapons") MapInfo_Map_supportedFeatures |= MAPINFO_FEATURE_WEAPONS;
1031                         else if(t == "turrets") MapInfo_Map_supportedFeatures |= MAPINFO_FEATURE_TURRETS;
1032                         else if(t == "vehicles") MapInfo_Map_supportedFeatures |= MAPINFO_FEATURE_VEHICLES;
1033                         else if(t == "monsters") MapInfo_Map_supportedFeatures |= MAPINFO_FEATURE_MONSTERS;
1034                         else if(t == "new_toys") MapInfo_Map_supportedFeatures |= MAPINFO_FEATURE_WEAPONS;
1035                         else if(WARN_COND)
1036                                 LOG_WARN("Map ", pFilename, " supports unknown feature ", t, ", ignored");
1037                 }
1038                 else if(t == "hidden")
1039                 {
1040                         MapInfo_Map_flags |= MAPINFO_FLAG_HIDDEN;
1041                 }
1042                 else if(t == "forbidden")
1043                 {
1044                         MapInfo_Map_flags |= MAPINFO_FLAG_FORBIDDEN;
1045                 }
1046                 else if(t == "frustrating")
1047                 {
1048                         MapInfo_Map_flags |= MAPINFO_FLAG_FRUSTRATING;
1049                 }
1050                 else if(t == "noautomaplist")
1051                 {
1052                         MapInfo_Map_flags |= MAPINFO_FLAG_NOAUTOMAPLIST;
1053                 }
1054                 else if(t == "gameversion_min")
1055                 {
1056                         if (cvar("gameversion") < stof(s))
1057                                 MapInfo_Map_flags |= MAPINFO_FLAG_NOAUTOMAPLIST;
1058                 }
1059                 else if(t == "type")
1060                 {
1061                         t = car(s); s = cdr(s);
1062                         Gametype f = MapInfo_Type_FromString(t);
1063                         //if(WARN_COND)
1064                                 //LOG_WARN("Map ", pFilename, " contains the legacy 'type' keyword which is deprecated and will be removed in the future. Please migrate the mapinfo file to 'gametype'.");
1065                         if(f)
1066                                 _MapInfo_Map_ApplyGametype (s, pGametypeToSet, f, true);
1067                         else if(WARN_COND)
1068                                 LOG_DEBUG("Map ", pFilename, " supports unknown game type ", t, ", ignored");
1069                 }
1070                 else if(t == "gametype")
1071                 {
1072                         t = car(s); s = cdr(s);
1073                         Gametype f = MapInfo_Type_FromString(t);
1074                         if(f)
1075                                 _MapInfo_Map_ApplyGametypeEx (s, pGametypeToSet, f);
1076                         else if(WARN_COND)
1077                                 LOG_DEBUG("Map ", pFilename, " supports unknown game type ", t, ", ignored");
1078                 }
1079                 else if(t == "size")
1080                 {
1081                         float a, b, c, d, e;
1082                         t = car(s); s = cdr(s); a = stof(t);
1083                         t = car(s); s = cdr(s); b = stof(t);
1084                         t = car(s); s = cdr(s); c = stof(t);
1085                         t = car(s); s = cdr(s); d = stof(t);
1086                         t = car(s); s = cdr(s); e = stof(t);
1087                         if(s == "")
1088                         {
1089                                 if(WARN_COND)
1090                                         LOG_WARN("Map ", pFilename, " contains an incorrect size line (not enough params), syntax: size mins_x mins_y mins_z maxs_x maxs_y maxs_z");
1091                         }
1092                         else
1093                         {
1094                                 t = car(s); s = cdr(s); f = stof(t);
1095                                 if(s != "")
1096                                 {
1097                                         if(WARN_COND)
1098                                                 LOG_WARN("Map ", pFilename, " contains an incorrect size line (too many params), syntax: size mins_x mins_y mins_z maxs_x maxs_y maxs_z");
1099                                 }
1100                                 else
1101                                 {
1102                                         if(a >= d || b >= e || c >= f)
1103                                         {
1104                                                 if(WARN_COND)
1105                                                         LOG_WARN("Map ", pFilename, " contains an incorrect size line, mins have to be < maxs");
1106                                         }
1107                                         else
1108                                         {
1109                                                 MapInfo_Map_mins.x = a;
1110                                                 MapInfo_Map_mins.y = b;
1111                                                 MapInfo_Map_mins.z = c;
1112                                                 MapInfo_Map_maxs.x = d;
1113                                                 MapInfo_Map_maxs.y = e;
1114                                                 MapInfo_Map_maxs.z = f;
1115                                         }
1116                                 }
1117                         }
1118                 }
1119                 else if(t == "settemp_for_type")
1120                 {
1121                         t = car(s); s = cdr(s);
1122                         bool all = t == "all";
1123                         Gametype f = NULL;
1124                         if(all || (f = MapInfo_Type_FromString(t)))
1125                         {
1126                                 if((all ? MAPINFO_TYPE_ALL : f.m_flags) & pGametypeToSet.m_flags)
1127                                 {
1128                                         _MapInfo_Parse_Settemp(pFilename, acl, 0, s, 1);
1129                                 }
1130                         }
1131                         else
1132                         {
1133                                 LOG_DEBUG("Map ", pFilename, " has a setting for unknown game type ", t, ", ignored");
1134                         }
1135                 }
1136                 else if(t == "clientsettemp_for_type")
1137                 {
1138                         t = car(s); s = cdr(s);
1139                         bool all = t == "all";
1140                         Gametype f = NULL;
1141                         if(all || (f = MapInfo_Type_FromString(t)))
1142                         {
1143                                 if((all ? MAPINFO_TYPE_ALL : f.m_flags) & pGametypeToSet.m_flags)
1144                                 {
1145                                         _MapInfo_Parse_Settemp(pFilename, acl, 1, s, 1);
1146                                 }
1147                         }
1148                         else
1149                         {
1150                                 LOG_DEBUG("Map ", pFilename, " has a client setting for unknown game type ", t, ", ignored");
1151                         }
1152                 }
1153                 else if(t == "fog")
1154                 {
1155                         if (!cvar_value_issafe(s))
1156                         {
1157                                 if(WARN_COND)
1158                                         LOG_WARN("Map ", pFilename, " contains a potentially harmful fog setting, ignored");
1159                         }
1160                         else
1161                                 MapInfo_Map_fog = s;
1162                 }
1163                 else if(t == "cdtrack")
1164                 {
1165                         t = car(s); s = cdr(s);
1166                         // We do this only if pGametypeToSet even though this
1167                         // content is theoretically game type independent,
1168                         // because MapInfo_Map_clientstuff contains otherwise
1169                         // game type dependent stuff. That way this value stays
1170                         // empty when not setting a game type to not set any
1171                         // false expectations.
1172                         if(pGametypeToSet)
1173                         {
1174                                 if (!cvar_value_issafe(t))
1175                                 {
1176                                         if(WARN_COND)
1177                                                 LOG_WARN("Map ", pFilename, " contains a potentially harmful cdtrack, ignored");
1178                                 }
1179                                 else
1180                                         MapInfo_Map_clientstuff = strcat(
1181                                                 MapInfo_Map_clientstuff, "cd loop \"", t, "\"\n"
1182                                         );
1183                         }
1184                 }
1185                 else if(WARN_COND)
1186                         LOG_WARN("Map ", pFilename, " provides unknown info item ", t, ", ignored");
1187         }
1188         LABEL(mapinfo_handled)
1189         fclose(fh);
1190
1191         if(MapInfo_Map_title == "<TITLE>")
1192                 MapInfo_Map_titlestring = MapInfo_Map_bspname;
1193         else if(MapInfo_isRedundant(MapInfo_Map_bspname, MapInfo_Map_title))
1194                 MapInfo_Map_titlestring = MapInfo_Map_title;
1195         else
1196                 MapInfo_Map_titlestring = sprintf("%s: %s", MapInfo_Map_bspname, MapInfo_Map_title);
1197
1198         MapInfo_Cache_Store();
1199         if(MapInfo_Map_supportedGametypes != 0)
1200                 return r;
1201         if (WARN_COND)
1202                 LOG_WARN("Map ", pFilename, " supports no game types, ignored");
1203         return 0;
1204 }
1205 int MapInfo_Get_ByName(string pFilename, float pAllowGenerate, Gametype pGametypeToSet)
1206 {
1207         int r = MapInfo_Get_ByName_NoFallbacks(pFilename, pAllowGenerate, pGametypeToSet);
1208
1209         FOREACH(Gametypes, it.m_isForcedSupported(it), _MapInfo_Map_ApplyGametypeEx("", pGametypeToSet, it));
1210
1211         if(pGametypeToSet)
1212         {
1213                 if(!(MapInfo_Map_supportedGametypes & pGametypeToSet.m_flags))
1214                 {
1215                         error("Can't select the requested game type. This should never happen as the caller should prevent it!\n");
1216                         //_MapInfo_Map_ApplyGametypeEx("", pGametypeToSet, MAPINFO_TYPE_DEATHMATCH);
1217                         //return;
1218                 }
1219         }
1220
1221         return r;
1222 }
1223
1224 float MapInfo_FindName(string s)
1225 {
1226         // if there is exactly one map of prefix s, return it
1227         // if not, return the null string
1228         // note that DP sorts glob results... so I can use a binary search
1229         float l, r, m, cmp;
1230         l = 0;
1231         r = MapInfo_count;
1232         // invariants: r is behind s, l-1 is equal or before
1233         while(l != r)
1234         {
1235                 m = floor((l + r) / 2);
1236                 MapInfo_FindName_match = _MapInfo_GlobItem(MapInfo_FilterList_Lookup(m));
1237                 cmp = strcasecmp(MapInfo_FindName_match, s);
1238                 if(cmp == 0)
1239                         return m; // found and good
1240                 if(cmp < 0)
1241                         l = m + 1; // l-1 is before s
1242                 else
1243                         r = m; // behind s
1244         }
1245         MapInfo_FindName_match = _MapInfo_GlobItem(MapInfo_FilterList_Lookup(l));
1246         MapInfo_FindName_firstResult = l;
1247         // r == l, so: l is behind s, l-1 is before
1248         // SO: if there is any, l is the one with the right prefix
1249         //     and l+1 may be one too
1250         if(l == MapInfo_count)
1251         {
1252                 MapInfo_FindName_match = string_null;
1253                 MapInfo_FindName_firstResult = -1;
1254                 return -1; // no MapInfo_FindName_match, behind last item
1255         }
1256         if(!startsWithNocase(MapInfo_FindName_match, s))
1257         {
1258                 MapInfo_FindName_match = string_null;
1259                 MapInfo_FindName_firstResult = -1;
1260                 return -1; // wrong prefix
1261         }
1262         if(l == MapInfo_count - 1)
1263                 return l; // last one, nothing can follow => unique
1264         if(startsWithNocase(_MapInfo_GlobItem(MapInfo_FilterList_Lookup(l + 1)), s))
1265         {
1266                 MapInfo_FindName_match = string_null;
1267                 return -1; // ambigous MapInfo_FindName_match
1268         }
1269         return l;
1270 }
1271
1272 string MapInfo_FixName(string s)
1273 {
1274         MapInfo_FindName(s);
1275         return MapInfo_FindName_match;
1276 }
1277
1278 int MapInfo_CurrentFeatures()
1279 {
1280         int req = 0;
1281     // TODO: find a better way to check if weapons are required on the map
1282         if(!(cvar("g_instagib") || cvar("g_overkill") || cvar("g_nix") || cvar("g_weaponarena") || !cvar("g_pickup_items") 
1283                 || cvar("g_race") || cvar("g_cts") || cvar("g_nexball") || cvar("g_ca") || cvar("g_freezetag") || cvar("g_lms")))
1284                 req |= MAPINFO_FEATURE_WEAPONS;
1285         return req;
1286 }
1287
1288 Gametype MapInfo_CurrentGametype()
1289 {
1290         Gametype prev = REGISTRY_GET(Gametypes, cvar("gamecfg"));
1291         FOREACH(Gametypes, cvar(it.netname) && it != prev, return it);
1292         return prev ? prev : MAPINFO_TYPE_DEATHMATCH;
1293 }
1294
1295 float _MapInfo_CheckMap(string s, bool gametype_only) // returns 0 if the map can't be played with the current settings, 1 otherwise
1296 {
1297         if(!MapInfo_Get_ByName(s, 1, NULL))
1298                 return 0;
1299         if((MapInfo_Map_supportedGametypes & MapInfo_CurrentGametype().m_flags) == 0)
1300                 return 0;
1301         if (gametype_only)
1302                 return 1;
1303         if((MapInfo_Map_supportedFeatures & MapInfo_CurrentFeatures()) != MapInfo_CurrentFeatures())
1304                 return 0;
1305         return 1;
1306 }
1307
1308 float MapInfo_CheckMap(string s) // returns 0 if the map can't be played with the current settings, 1 otherwise
1309 {
1310         float r;
1311         r = _MapInfo_CheckMap(s, false);
1312         MapInfo_ClearTemps();
1313         return r;
1314 }
1315
1316 void MapInfo_SwitchGameType(Gametype t)
1317 {
1318         FOREACH(Gametypes, true, cvar_set(it.netname, (it == t) ? "1" : "0"));
1319 }
1320
1321 void MapInfo_LoadMap(string s, float reinit)
1322 {
1323         MapInfo_Map_supportedGametypes = 0;
1324         // we shouldn't need this, as LoadMapSettings already fixes the gametype
1325         //if(!MapInfo_CheckMap(s))
1326         //{
1327         //      print("EMERGENCY: can't play the selected map in the given game mode. Falling back to DM.\n");
1328         //      MapInfo_SwitchGameType(MAPINFO_TYPE_DEATHMATCH.m_flags);
1329         //}
1330
1331         LOG_INFO("Switching to map ", s);
1332
1333         cvar_settemp_restore();
1334         if(reinit)
1335                 localcmd(strcat("\nmap ", s, "\n"));
1336         else
1337                 localcmd(strcat("\nchangelevel ", s, "\n"));
1338 }
1339
1340 string MapInfo_ListAllowedMaps(Gametype type, float pRequiredFlags, float pForbiddenFlags)
1341 {
1342         string out;
1343
1344         // to make absolutely sure:
1345         MapInfo_Enumerate();
1346         MapInfo_FilterGametype(type, MapInfo_CurrentFeatures(), pRequiredFlags, pForbiddenFlags, 0);
1347
1348         out = "";
1349         for(float i = 0; i < MapInfo_count; ++i)
1350                 out = strcat(out, " ", _MapInfo_GlobItem(MapInfo_FilterList_Lookup(i)));
1351         return substring(out, 1, strlen(out) - 1);
1352 }
1353
1354 string MapInfo_ListAllAllowedMaps(float pRequiredFlags, float pForbiddenFlags)
1355 {
1356         string out;
1357
1358         // to make absolutely sure:
1359         MapInfo_Enumerate();
1360         _MapInfo_FilterGametype(MAPINFO_TYPE_ALL, 0, pRequiredFlags, pForbiddenFlags, 0);
1361
1362         out = "";
1363         for(float i = 0; i < MapInfo_count; ++i)
1364                 out = strcat(out, " ", _MapInfo_GlobItem(MapInfo_FilterList_Lookup(i)));
1365
1366         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), pRequiredFlags, pForbiddenFlags, 0);
1367
1368         return substring(out, 1, strlen(out) - 1);
1369 }
1370
1371 void MapInfo_LoadMapSettings_SaveGameType(Gametype t)
1372 {
1373         MapInfo_SwitchGameType(t);
1374         cvar_set("gamecfg", ftos(t.m_id));
1375         MapInfo_LoadedGametype = t;
1376 }
1377
1378 void MapInfo_LoadMapSettings(string s) // to be called from worldspawn
1379 {
1380         Gametype t = MapInfo_CurrentGametype();
1381         MapInfo_LoadMapSettings_SaveGameType(t);
1382
1383         if(!_MapInfo_CheckMap(s, true)) // with underscore, it keeps temps
1384         {
1385                 if(cvar("g_mapinfo_allow_unsupported_modes_and_let_stuff_break"))
1386                 {
1387                         LOG_SEVERE("can't play the selected map in the given game mode. Working with only the override settings.");
1388                         _MapInfo_Map_ApplyGametypeEx("", t, t);
1389                         return; // do not call Get_ByName!
1390                 }
1391
1392                 if(MapInfo_Map_supportedGametypes == 0)
1393                 {
1394                         LOG_SEVERE("Mapinfo system is not functional at all. Assuming deathmatch.");
1395                         MapInfo_Map_supportedGametypes = MAPINFO_TYPE_DEATHMATCH.m_flags;
1396                         MapInfo_LoadMapSettings_SaveGameType(MAPINFO_TYPE_DEATHMATCH);
1397                         _MapInfo_Map_ApplyGametypeEx("", MAPINFO_TYPE_DEATHMATCH, MAPINFO_TYPE_DEATHMATCH);
1398                         return; // do not call Get_ByName!
1399                 }
1400
1401                 int _t = 1;
1402                 while(!(MapInfo_Map_supportedGametypes & 1))
1403                 {
1404                         _t <<= 1;
1405                         MapInfo_Map_supportedGametypes = floor(MapInfo_Map_supportedGametypes >> 1);
1406                 }
1407                 Gametype t_prev = t;
1408                 FOREACH(Gametypes, it.m_flags == _t, { t = it; break; });
1409
1410                 // t is now a supported mode!
1411                 LOG_WARNF("can't play the selected map in the given game mode (%s). Falling back to a supported mode (%s).", t_prev.mdl, t.mdl);
1412                 MapInfo_LoadMapSettings_SaveGameType(t);
1413         }
1414         if(!_MapInfo_CheckMap(s, false)) { // with underscore, it keeps temps
1415                 LOG_WARNF("the selected map lacks features required by current settings; playing anyway.");
1416         }
1417         MapInfo_Get_ByName(s, 1, t);
1418 }
1419
1420 void MapInfo_ClearTemps()
1421 {
1422         MapInfo_Map_bspname = string_null;
1423         MapInfo_Map_title = string_null;
1424         MapInfo_Map_titlestring = string_null;
1425         MapInfo_Map_description = string_null;
1426         MapInfo_Map_author = string_null;
1427         MapInfo_Map_clientstuff = string_null;
1428         MapInfo_Map_supportedGametypes = 0;
1429         MapInfo_Map_supportedFeatures = 0;
1430 }
1431
1432 void MapInfo_Shutdown()
1433 {
1434         MapInfo_ClearTemps();
1435         MapInfo_Filter_Free();
1436         MapInfo_Cache_Destroy();
1437         if(_MapInfo_globopen)
1438         {
1439                 search_end(_MapInfo_globhandle);
1440                 _MapInfo_globhandle = -1;
1441                 _MapInfo_globopen = false;
1442         }
1443 }
1444
1445 int MapInfo_ForbiddenFlags()
1446 {
1447         int f = MAPINFO_FLAG_FORBIDDEN;
1448
1449 #ifdef GAMEQC
1450         if (!cvar("g_maplist_allow_hidden"))
1451 #endif
1452                 f |= MAPINFO_FLAG_HIDDEN;
1453
1454         if (!cvar("g_maplist_allow_frustrating"))
1455                 f |= MAPINFO_FLAG_FRUSTRATING;
1456
1457         return f;
1458 }
1459
1460 int MapInfo_RequiredFlags()
1461 {
1462         int f = 0;
1463
1464         if(cvar("g_maplist_allow_frustrating") > 1)
1465                 f |= MAPINFO_FLAG_FRUSTRATING;
1466
1467         return f;
1468 }