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