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