]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/common/mapinfo.qc
Display map author in Welcome message, add more author fallback paths
[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>") && v != "")
343                                 MapInfo_Map_title = v;
344                 }
345                 else
346                 {
347                         if(k == "origin")
348                         {
349                                 o = stov(strcat("'", v, "'"));
350                                 mapMins.x = min(mapMins.x, o.x);
351                                 mapMins.y = min(mapMins.y, o.y);
352                                 mapMins.z = min(mapMins.z, o.z);
353                                 mapMaxs.x = max(mapMaxs.x, o.x);
354                                 mapMaxs.y = max(mapMaxs.y, o.y);
355                                 mapMaxs.z = max(mapMaxs.z, o.z);
356                         }
357                         else if(k == "race_place")
358                         {
359                                 if(stof(v) > 0)
360                                         spawnplaces = 1;
361                         }
362                         else if(k == "classname")
363                         {
364                                 if(v == "info_player_team1")
365                                         ++spawnpoints;
366                                 else if(v == "info_player_team2")
367                                         ++spawnpoints;
368                                 else if(v == "info_player_start")
369                                         ++spawnpoints;
370                                 else if(v == "info_player_deathmatch")
371                                         ++spawnpoints;
372                                 else if(v == "weapon_nex")
373                                         { }
374                                 else if(v == "weapon_railgun")
375                                         { }
376                                 else if(startsWith(v, "weapon_"))
377                                         MapInfo_Map_supportedFeatures |= MAPINFO_FEATURE_WEAPONS;
378                                 else if(startsWith(v, "turret_"))
379                                         MapInfo_Map_supportedFeatures |= MAPINFO_FEATURE_TURRETS;
380                                 else if(startsWith(v, "vehicle_"))
381                                         MapInfo_Map_supportedFeatures |= MAPINFO_FEATURE_VEHICLES;
382                                 else if(startsWith(v, "monster_"))
383                                         MapInfo_Map_supportedFeatures |= MAPINFO_FEATURE_MONSTERS;
384                                 else if(v == "target_music" || v == "trigger_music")
385                                         _MapInfo_Map_worldspawn_music = string_null; // don't use regular BGM
386                                 else if(v == "target_stopTimer")
387                                         is_q3df_map = true; // don't support standard gametypes UNLESS we found them in .arena
388                                 else
389                                         FOREACH(Gametypes, true, it.m_generate_mapinfo(it, v));
390                         }
391                 }
392         }
393         if(inWorldspawn)
394         {
395                 LOG_WARN(fn, " ended still in worldspawn, BUG");
396                 return 0;
397         }
398         diameter = vlen(mapMaxs - mapMins);
399
400         int twoBaseModes = 0;
401         FOREACH(Gametypes, it.m_isTwoBaseMode(), twoBaseModes |= it.m_flags);
402         if(twoBaseModes && (twoBaseModes &= MapInfo_Map_supportedGametypes))
403         {
404                 // we have a symmetrical map, don't add the modes without bases
405         }
406         else if(!is_q3df_map)
407         {
408                 FOREACH(Gametypes, it.m_isAlwaysSupported(it, spawnpoints, diameter), MapInfo_Map_supportedGametypes |= it.m_flags);
409         }
410
411         if(MapInfo_Map_supportedGametypes & MAPINFO_TYPE_RACE.m_flags)
412         if(!spawnplaces)
413         {
414                 MapInfo_Map_supportedGametypes &= ~MAPINFO_TYPE_RACE.m_flags;
415                 MapInfo_Map_supportedGametypes |= MAPINFO_TYPE_CTS.m_flags;
416         }
417
418         LOG_TRACE("-> diameter ",    ftos(diameter));
419         LOG_TRACE(";  spawnpoints ", ftos(spawnpoints));
420         LOG_TRACE(";  modes ",       ftos(MapInfo_Map_supportedGametypes));
421
422         fclose(fh);
423
424         return r;
425 }
426
427 void _MapInfo_Map_Reset()
428 {
429         MapInfo_Map_title = "<TITLE>";
430         MapInfo_Map_titlestring = "<TITLE>";
431         MapInfo_Map_description = "<DESCRIPTION>";
432         MapInfo_Map_author = "<AUTHOR>";
433         MapInfo_Map_supportedGametypes = 0;
434         MapInfo_Map_supportedFeatures = 0;
435         MapInfo_Map_flags = 0;
436         MapInfo_Map_clientstuff = "";
437         MapInfo_Map_fog = "";
438         MapInfo_Map_mins = '0 0 0';
439         MapInfo_Map_maxs = '0 0 0';
440 }
441
442 string _MapInfo_GetDefault(Gametype t)
443 {
444         return t.m_legacydefaults;
445 }
446
447 void _MapInfo_Map_ApplyGametype(string s, Gametype pWantedType, Gametype pThisType, int load_default)
448 {
449         string sa;
450         MapInfo_Map_supportedGametypes |= pThisType.m_flags;
451         if(!(pThisType.m_flags & pWantedType.m_flags))
452                 return;
453
454         if(load_default)
455                 _MapInfo_Map_ApplyGametype(_MapInfo_GetDefault(pThisType), pWantedType, pThisType, false);
456
457         if(!pWantedType.frags) // these modes don't use fraglimit
458         {
459                 cvar_set("fraglimit", "0");
460         }
461         else
462         {
463                 sa = car(s);
464                 if(sa != "")
465                         cvar_set("fraglimit", sa);
466                 s = cdr(s);
467         }
468
469         sa = car(s);
470         if(sa != "")
471                 cvar_set("timelimit", sa);
472         s = cdr(s);
473
474         if(pWantedType.m_setTeams)
475         {
476                 sa = car(s);
477                 if(sa != "")
478                         pWantedType.m_setTeams(sa);
479                 s = cdr(s);
480         }
481
482         // rc = timelimit timelimit_qualification laps laps_teamplay
483         if(pWantedType == MAPINFO_TYPE_RACE)
484         {
485                 cvar_set("fraglimit", "0"); // special case!
486
487                 sa = car(s); if(sa == "") sa = cvar_string("timelimit");
488                 cvar_set("g_race_qualifying_timelimit", sa);
489                 s = cdr(s);
490
491                 sa = car(s);
492                 if(sa != "")
493                         if(cvar("g_race_teams") < 2)
494                                 cvar_set("fraglimit", sa);
495                 s = cdr(s);
496
497                 sa = car(s);
498                 if(sa != "")
499                         if(cvar("g_race_teams") >= 2)
500                                 cvar_set("fraglimit", sa);
501                 s = cdr(s);
502         }
503
504         if(!pWantedType.frags) // these modes don't use fraglimit
505         {
506                 cvar_set("leadlimit", "0");
507         }
508         else
509         {
510                 sa = car(s);
511                 if(sa != "")
512                         cvar_set("leadlimit", sa);
513                 s = cdr(s);
514         }
515 }
516
517 string _MapInfo_GetDefaultEx(Gametype t)
518 {
519         return t ? t.model2 : "";
520 }
521
522 float _MapInfo_GetTeamPlayBool(Gametype t)
523 {
524         return t ? t.team : false;
525 }
526
527 void _MapInfo_Map_ApplyGametypeEx(string s, Gametype pWantedType, Gametype pThisType)
528 {
529         MapInfo_Map_supportedGametypes |= pThisType.m_flags;
530         if (!(pThisType.m_flags & pWantedType.m_flags))
531                 return;
532
533         // reset all the cvars to their defaults
534
535         cvar_set("timelimit", cvar_defstring("timelimit"));
536         cvar_set("leadlimit", cvar_defstring("leadlimit"));
537         cvar_set("fraglimit", cvar_defstring("fraglimit"));
538         FOREACH(Gametypes, true, it.m_parse_mapinfo(string_null, string_null));
539
540         string fraglimit_normal = string_null;
541         string fraglimit_teams = string_null;
542
543         for (s = strcat(_MapInfo_GetDefaultEx(pWantedType), " ", s); s != ""; s = cdr(s)) {
544                 string sa = car(s);
545                 if (sa == "") continue;
546                 int p = strstrofs(sa, "=", 0);
547                 if (p < 0) {
548                         if(WARN_COND)
549                                 LOG_WARNF("Invalid gametype setting in mapinfo for gametype %s: %s", MapInfo_Type_ToString(pWantedType), sa);
550                         continue;
551                 }
552                 string k = substring(sa, 0, p);
553                 string v = substring(sa, p + 1, -1);
554                 bool handled = true;
555                 switch (k) {
556                         case "timelimit":
557                         {
558                                 cvar_set("timelimit", v);
559                                 break;
560                         }
561                         case "leadlimit":
562                         {
563                                 cvar_set("leadlimit", v);
564                                 break;
565                         }
566                         case "pointlimit":
567                         case "fraglimit":
568                         case "lives":
569                         case "laplimit":
570                         case "caplimit":
571                         {
572                                 fraglimit_normal = v;
573                                 break;
574                         }
575                         case "teampointlimit":
576                         case "teamlaplimit":
577                         {
578                                 fraglimit_teams = v;
579                                 break;
580                         }
581                         default:
582                         {
583                             handled = false;
584                             break;
585                         }
586                 }
587                 FOREACH(Gametypes, true, handled |= it.m_parse_mapinfo(k, v));
588                 if (!handled && WARN_COND)
589             LOG_WARNF("Invalid gametype setting in mapinfo for gametype %s: %s", MapInfo_Type_ToString(pWantedType), sa);
590         }
591
592         if (pWantedType == MAPINFO_TYPE_RACE && cvar("g_race_teams") >= 2)
593         {
594                 if(fraglimit_teams)
595                         cvar_set("fraglimit", fraglimit_teams);
596         }
597         else
598         {
599                 if(fraglimit_normal)
600                         cvar_set("fraglimit", fraglimit_normal);
601         }
602 }
603
604 Gametype MapInfo_Type_FromString(string gtype, bool dowarn, bool is_q3compat)
605 {
606         string replacement = "";
607
608         switch (gtype)
609         {
610                 case "nexball":   replacement = "nb"; break;
611                 case "freezetag": replacement = "ft"; break;
612                 case "keepaway":  replacement = "ka"; break;
613                 case "invasion":  replacement = "inv"; break;
614                 case "assault":   replacement = "as"; break;
615                 case "race":      replacement = "rc"; break;
616                 // Q3/QL compat, see DoesQ3ARemoveThisEntity() in quake3.qc for complete lists
617                 case "ffa":       replacement = "dm"; break;
618                 case "cctf": // from ThreeWave, maps with this should all have "ctf" too
619                 case "oneflag":   replacement = "ctf"; break;
620                 case "tourney":   replacement = "duel"; break;
621                 case "arena": // which Q3 mod is this from? In Nexuiz it was 'duel with rounds'.
622                         if(is_q3compat) { replacement = "ca"; } break;
623         }
624         if (replacement != "")
625         {
626                 if (dowarn && WARN_COND)
627                         LOG_WARNF("MapInfo_Type_FromString (probably %s): using deprecated name '%s'. Should use '%s'.", MapInfo_Map_bspname, gtype, replacement);
628                 gtype = replacement;
629         }
630         FOREACH(Gametypes, it.mdl == gtype, return it);
631         return NULL;
632 }
633
634 string MapInfo_Type_Description(Gametype t)
635 {
636         return t ? t.gametype_description : "";
637 }
638
639 string MapInfo_Type_ToString(Gametype t)
640 {
641         return t ? t.mdl : "";
642 }
643
644 string MapInfo_Type_ToText(Gametype t)
645 {
646         /* xgettext:no-c-format */
647         return t ? t.message : _("@!#%'n Tuba Throwing");
648 }
649
650 void _MapInfo_Parse_Settemp(string pFilename, string acl, float type, string s, float recurse)
651 {
652         string t;
653         float o;
654         // tabs are invalid, treat them as "empty"
655         s = strreplace("\t", "", s);
656
657         t = car(s); s = cdr(s);
658
659         // limited support of "" and comments
660         //   remove trailing and leading " of t
661         if(substring(t, 0, 1) == "\"")
662         {
663                 if(substring(t, -1, 1) == "\"")
664                         t = substring(t, 1, -2);
665         }
666
667         //   remove leading " of s
668         if(substring(s, 0, 1) == "\"")
669         {
670                 s = substring(s, 1, -1);
671         }
672         //   remove trailing " of s, and all that follows (cvar description)
673         o = strstrofs(s, "\"", 0);
674         if(o >= 0)
675                 s = substring(s, 0, o);
676
677         //   remove // comments
678         o = strstrofs(s, "//", 0);
679         if(o >= 0)
680                 s = substring(s, 0, o);
681
682         //   remove trailing spaces
683         while(substring(s, -1, 1) == " ")
684                 s = substring(s, 0, -2);
685
686         if(t == "#include")
687         {
688                 if(recurse > 0)
689                 {
690                         float fh = fopen(s, FILE_READ);
691                         if(fh < 0)
692                         {
693                                 if(WARN_COND)
694                                         LOG_WARN("Map ", pFilename, " references not existing config file ", s);
695                         }
696                         else
697                         {
698                                 while((s = fgets(fh)))
699                                 {
700                                         s = strreplace("\t", "", s); // treat tabs as "empty", perform here first to ensure coments are detected
701                                         // catch different sorts of comments
702                                         if(s == "")                    // empty lines
703                                                 continue;
704                                         if(substring(s, 0, 1) == "#")  // UNIX style
705                                                 continue;
706                                         if(substring(s, 0, 2) == "//") // C++ style
707                                                 continue;
708                                         if(substring(s, 0, 1) == "_")  // q3map style
709                                                 continue;
710
711                                         if(substring(s, 0, 4) == "set ")
712                                                 s = substring(s, 4, -1);
713                                         if(substring(s, 0, 5) == "seta ")
714                                                 s = substring(s, 5, -1);
715
716                                         _MapInfo_Parse_Settemp(pFilename, acl, type, s, recurse - 1);
717                                 }
718                                 fclose(fh);
719                         }
720                 }
721                 else if(WARN_COND)
722                         LOG_WARN("Map ", pFilename, " uses too many levels of inclusion");
723         }
724         else if(t == ""
725                 || !cvar_value_issafe(t)
726                 || !cvar_value_issafe(s)
727                 || matchacl(MAPINFO_SETTEMP_ACL_SYSTEM, t) <= 0)
728         {
729                 if (WARN_COND)
730                         LOG_WARN("Map ", pFilename, " contains a potentially harmful setting, ignored");
731         }
732         else if(matchacl(acl, t) <= 0)
733         {
734                 if (WARN_COND)
735                         LOG_WARN("Map ", pFilename, " contains a denied setting, ignored");
736         }
737         else
738         {
739                 if(type == 0) // server set
740                 {
741                         LOG_TRACE("Applying temporary setting ", t, " := ", s);
742                 #if 0
743                         if(cvar("g_campaign"))
744                                 cvar_set(t, s); // this is a wrapper and is always temporary anyway; no need to backup old values then
745                         else
746                 #endif
747                                 cvar_settemp(t, s);
748                 }
749                 else
750                 {
751                         LOG_TRACE("Applying temporary client setting ", t, " := ", s);
752                         MapInfo_Map_clientstuff = strcat(
753                                         MapInfo_Map_clientstuff, "cl_cmd settemp \"", t, "\" \"", s, "\"\n"
754                                         );
755                 }
756         }
757 }
758
759 /// Removes author string from title (if found)
760 /// and copies it to MapInfo_Map_author if that wasn't set.
761 string MapInfo_title_sans_author(string title)
762 {
763         int offset;
764
765         if ((offset = strstrofs(title, " by ", 0)) >= 0)
766         {
767                 if (MapInfo_Map_author == "<AUTHOR>")
768                         MapInfo_Map_author = substring(title, offset + 4, strlen(title) - (offset + 4));
769                 title = substring(title, 0, offset);
770         }
771         else if ((offset = strstrofs(title, " (by ", 0)) >= 0 || (offset = strstrofs(title, " [by ", 0)) >= 0)
772         {
773                 if (MapInfo_Map_author == "<AUTHOR>")
774                         MapInfo_Map_author = substring(title, offset + 5, strlen(title) - (offset + 5) - 1);
775                 title = substring(title, 0, offset);
776         }
777         else if ((offset = strstrofs(title, "Made By ", 0)) >= 0) // often at the start of the string
778         {
779                 if (MapInfo_Map_author == "<AUTHOR>")
780                         MapInfo_Map_author = substring(title, offset + 8, strlen(title) - (offset + 8));
781                 title = substring(title, 0, offset);
782         }
783
784         return title != "" ? title : "<TITLE>";
785 }
786
787 bool MapInfo_isRedundant(string fn, string t)
788 {
789         // normalize file name
790         fn = strreplace("_", "", fn);
791         fn = strreplace("-", "", fn);
792
793         // normalize visible title
794         t = strreplace(":", "", t);
795         t = strreplace(" ", "", t);
796         t = strreplace("_", "", t);
797         t = strreplace("-", "", t);
798         t = strreplace("'", "", t);
799         t = strdecolorize(t);
800
801         // we allow the visible title to have punctuation the file name does
802         // not, but not vice versa
803         if(!strcasecmp(fn, t))
804                 return true;
805
806         return false;
807 }
808
809 bool _MapInfo_ParseArena(string arena_filename, int fh, string pFilename, Gametype pGametypeToSet, bool isdefi, bool isgenerator)
810 {
811         // NOTE: .arena files can hold more than 1 map's information!
812         // to handle this, we're going to store gathered information in local variables and save it if we encounter the correct map name
813         bool in_brackets = false; // testing a potential mapinfo section (within brackets)
814         bool dosave = false;
815         string stored_Map_description = "";
816         string stored_Map_title = "";
817         string stored_Map_author = "";
818         int stored_supportedGametypes = 0;
819         int stored_supportedFeatures = 0;
820         int stored_flags = 0;
821         string t, s;
822
823         if (isgenerator)
824                 LOG_INFO("Generating ", pFilename, ".mapinfo: analyzing ", arena_filename);
825
826         for (;;)
827         {
828                 if (!((s = fgets(fh))))
829                         break;
830
831                 // catch different sorts of comments
832                 if(s == "")                    // empty lines
833                         continue;
834                 if(substring(s, 0, 2) == "//") // C++ style
835                         continue;
836                 if(strstrofs(s, "{", 0) >= 0)
837                 {
838                         if(in_brackets)
839                                 return false; // edge case? already in a bracketed section!
840                         in_brackets = true;
841                         continue;
842                 }
843                 else if(!in_brackets)
844                 {
845                         // if we're not inside a bracket, don't process map info
846                         continue;
847                 }
848                 if(strstrofs(s, "}", 0) >= 0)
849                 {
850                         if(!in_brackets)
851                                 return false; // no starting bracket! let the mapinfo generation system handle it
852                         in_brackets = false;
853                         if(dosave)
854                         {
855                                 MapInfo_Map_description = stored_Map_description;
856                                 if(stored_Map_title != "")
857                                         MapInfo_Map_title = stored_Map_title;
858                                 if(stored_Map_author != "") // write the usual "<AUTHOR>" if we have nothing better
859                                         MapInfo_Map_author = stored_Map_author;
860                                 // might have .arena AND .defi for the same map so these bitfields are OR'd
861                                 if(isgenerator)
862                                         MapInfo_Map_supportedGametypes |= stored_supportedGametypes;
863                                 else
864                                 {
865                                         FOREACH(Gametypes, it.m_flags & stored_supportedGametypes,
866                                         {
867                                                 _MapInfo_Map_ApplyGametype ("", pGametypeToSet, it, true);
868                                         });
869                                 }
870                                 MapInfo_Map_supportedFeatures |= stored_supportedFeatures;
871                                 MapInfo_Map_flags |= stored_flags;
872                                 return true; // no need to continue through the file, we have our map!
873                         }
874                         else
875                         {
876                                 // discard any gathered locals, we're not using the correct map!
877                                 stored_Map_description = "";
878                                 stored_Map_title = "";
879                                 stored_Map_author = "";
880                                 stored_supportedGametypes = 0;
881                                 stored_supportedFeatures = 0;
882                                 stored_flags = 0;
883                                 continue;
884                         }
885                 }
886
887                 s = strreplace("\t", " ", s);
888
889                 float p = strstrofs(s, "//", 0);
890                 if(p >= 0)
891                         s = substring(s, 0, p);
892
893                 // perform an initial trim to ensure the first argument is properly obtained
894                 //   remove leading spaces
895                 while(substring(s, 0, 1) == " ")
896                         s = substring(s, 1, -1);
897
898                 t = car(s); s = cdr(s);
899                 t = strtolower(t); // apparently some q3 maps use capitalized parameters
900
901                 //   remove trailing spaces
902                 while(substring(t, -1, 1) == " ")
903                         t = substring(t, 0, -2);
904
905                 //   remove trailing spaces
906                 while(substring(s, -1, 1) == " ")
907                         s = substring(s, 0, -2);
908                 //   remove leading spaces
909                 while(substring(s, 0, 1) == " ")
910                         s = substring(s, 1, -1);
911                 // limited support of ""
912                 //   remove trailing and leading " of s
913                 if(substring(s, 0, 1) == "\"")
914                 {
915                         if(substring(s, -1, 1) == "\"")
916                                 s = substring(s, 1, -2);
917                 }
918                 if(t == "longname")
919                         stored_Map_title = s;
920                 else if(t == "author")
921                         stored_Map_author = s;
922                 else if(t == "type")
923                 {
924                         // if there is a valid gametype in this .arena file, include it in the menu
925                         stored_supportedFeatures |= MAPINFO_FEATURE_WEAPONS;
926                         // type in quake 3 holds all the supported gametypes, so we must loop through all of them
927                         // TODO: handle support here better to include more Xonotic teamplay modes
928                         string types = s;
929                         types = strreplace("team", "tdm ft", types);
930                         types = strreplace("ffa", "dm lms ka", types);
931                         types = strreplace("tourney", "duel", types); // QL used duel so the following check must support it
932                         if(strstrofs(types, "duel", 0) < 0 && strstrofs(types, "tdm", 0) >= 0) // larger team map, support additional gamemodes!
933                                 types = cons(types, "ca kh");
934                         FOREACH_WORD(types, true,
935                         {
936                                 Gametype f = MapInfo_Type_FromString(it, false, true);
937                                 if(f)
938                                         stored_supportedGametypes |= f.m_flags;
939                         });
940                 }
941                 else if(t == "style" && isdefi)
942                 {
943                         // we have a defrag map on our hands, add CTS!
944                         // TODO: styles
945                         stored_supportedGametypes |= MAPINFO_TYPE_CTS.m_flags;
946                 }
947                 else if(t == "map")
948                 {
949                         if(strtolower(s) == strtolower(pFilename))
950                                 dosave = true; // yay, found our map!
951                 }
952                 else if(t == "quote")
953                         stored_Map_description = s;
954                 // TODO: fraglimit
955         }
956
957         // if the map wasn't found in the .arena, fall back to generated .mapinfo
958         return false;
959 }
960
961 string _MapInfo_CheckArenaFile(string pFilename, string pMapname)
962 {
963         // returns the file name if valid, otherwise returns ""
964         // a string is returned to optimise the use cases where a filename is also returned
965         int fh = fopen(pFilename, FILE_READ);
966         if(fh < 0)
967                 return "";
968         for(string s; (s = fgets(fh)); )
969         {
970                 s = strreplace("\t", "", s);
971                 while(substring(s, 0, 1) == " ")
972                         s = substring(s, 1, -1);
973                 if(substring(s, 0, 2) == "//")
974                         continue;
975                 if(s == "")
976                         continue;
977                 int offset = strstrofs(s, "map", 0);
978                 if(offset >= 0)
979                 {
980                         if(strstrofs(strtolower(s), strcat("\"", strtolower(pMapname), "\""), offset) >= 0) // quake 3 is case insensitive
981                         {
982                                 fclose(fh);
983                                 return pFilename; // FOUND IT!
984                         }
985                 }
986         }
987         fclose(fh);
988         return ""; // file did not contain a "map" field matching our map name
989 }
990
991 string _MapInfo_FindArenaFile(string pFilename, string extension)
992 {
993         string fallback = strcat("scripts/", pFilename, extension);
994         if(!checkextension("DP_QC_FS_SEARCH_PACKFILE"))
995                 return _MapInfo_CheckArenaFile(fallback, pFilename);
996         string base_pack = whichpack(strcat("maps/", pFilename, ".bsp"));
997         if(base_pack == "") // this map isn't packaged!
998                 return _MapInfo_CheckArenaFile(fallback, pFilename);
999
1000         int glob = search_packfile_begin(strcat("scripts/*", extension), true, true, base_pack);
1001         if(glob < 0)
1002                 return _MapInfo_CheckArenaFile(fallback, pFilename);
1003         int n = search_getsize(glob);
1004         for(int j = 0; j < n; ++j)
1005         {
1006                 string file = search_getfilename(glob, j);
1007                 if(_MapInfo_CheckArenaFile(file, pFilename) != "")
1008                 {
1009                         search_end(glob);
1010                         return file;
1011                 }
1012         }
1013
1014         search_end(glob);
1015         return ""; // if we get here, a valid .arena file could not be found
1016 }
1017
1018 // load info about a map by name into the MapInfo_Map_* globals
1019 float MapInfo_Get_ByName_NoFallbacks(string pFilename, int pAllowGenerate, Gametype pGametypeToSet)
1020 {
1021         string fn;
1022         string s, t;
1023         float fh;
1024         int f, i;
1025         float r, n;
1026         string acl;
1027
1028         acl = MAPINFO_SETTEMP_ACL_USER;
1029
1030         if(strstrofs(pFilename, "/", 0) >= 0)
1031         {
1032                 LOG_WARN("Invalid character in map name, ignored");
1033                 return 0;
1034         }
1035
1036         if(pGametypeToSet == NULL)
1037                 if(MapInfo_Cache_Retrieve(pFilename))
1038                         return 1;
1039
1040         r = 1;
1041
1042         MapInfo_Map_bspname = pFilename;
1043
1044         // default all generic fields so they have "good" values in case something fails
1045         fn = strcat("maps/", pFilename, ".mapinfo");
1046         fh = fopen(fn, FILE_READ);
1047         if(fh < 0)
1048         {
1049                 if(autocvar_g_mapinfo_q3compat == 1) // use arena data instead of generating a mapinfo file
1050                 {
1051                         // supporting .arena AND .defi for the same map
1052                         bool success = false;
1053                         fn = _MapInfo_FindArenaFile(pFilename, ".arena");
1054                         if(fn != "" && (fh = fopen(fn, FILE_READ)) >= 0)
1055                         {
1056                                 _MapInfo_Map_Reset();
1057                                 success = _MapInfo_ParseArena(fn, fh, pFilename, pGametypeToSet, false, false);
1058                                 fclose(fh);
1059                         }
1060                         fn = _MapInfo_FindArenaFile(pFilename, ".defi");
1061                         if(fn != "" && (fh = fopen(fn, FILE_READ)) >= 0)
1062                         {
1063                                 if(!success)
1064                                         _MapInfo_Map_Reset();
1065                                 success |= _MapInfo_ParseArena(fn, fh, pFilename, pGametypeToSet, true, false);
1066                                 fclose(fh);
1067                         }
1068                         if(success)
1069                                 goto mapinfo_handled; // skip generation
1070                 }
1071
1072                 fn = strcat("maps/autogenerated/", pFilename, ".mapinfo");
1073                 fh = fopen(fn, FILE_READ);
1074                 if(fh < 0)
1075                 {
1076                         if(!pAllowGenerate)
1077                                 return 0;
1078                         _MapInfo_Map_Reset();
1079                         r = _MapInfo_Generate(pFilename);
1080                         if(!r)
1081                                 return 0;
1082                         MapInfo_Map_title = MapInfo_title_sans_author(MapInfo_Map_title);
1083                         fh = fopen(fn, FILE_WRITE);
1084                         fputs(fh, strcat("title ", MapInfo_Map_title, "\n"));
1085                         fputs(fh, strcat("description ", MapInfo_Map_description, "\n"));
1086                         fputs(fh, strcat("author ", MapInfo_Map_author, "\n"));
1087                         if(_MapInfo_Map_worldspawn_music != "")
1088                         {
1089                                 if(strcasecmp(substring(_MapInfo_Map_worldspawn_music, -4, 4), ".wav") == 0 || strcasecmp(substring(_MapInfo_Map_worldspawn_music, -4, 4), ".ogg") == 0)
1090                                         fputs(fh, strcat("cdtrack ", substring(_MapInfo_Map_worldspawn_music, 0, -4), "\n"));
1091                                 else
1092                                         fputs(fh, strcat("cdtrack ", _MapInfo_Map_worldspawn_music, "\n"));
1093                         }
1094                         else
1095                         {
1096                                 n = tokenize_console(cvar_string("g_cdtracks_remaplist"));
1097                                 s = strcat(" ", cvar_string("g_cdtracks_dontusebydefault"), " ");
1098                                 for (;;)
1099                                 {
1100                                         i = floor(random() * n);
1101                                         if(strstrofs(s, strcat(" ", argv(i), " "), 0) < 0)
1102                                                 break;
1103                                 }
1104                                 fputs(fh, strcat("cdtrack ", ftos(i + 1), "\n"));
1105                         }
1106                         if(MapInfo_Map_supportedFeatures & MAPINFO_FEATURE_WEAPONS)
1107                                 fputs(fh, "has weapons\n");
1108                         else
1109                                 fputs(fh, "// uncomment this if you added weapon pickups: has weapons\n");
1110                         if(MapInfo_Map_supportedFeatures & MAPINFO_FEATURE_TURRETS)
1111                                 fputs(fh, "has turrets\n");
1112                         else
1113                                 fputs(fh, "// uncomment this if you added turrets: has turrets\n");
1114                         if(MapInfo_Map_supportedFeatures & MAPINFO_FEATURE_VEHICLES)
1115                                 fputs(fh, "has vehicles\n");
1116                         else
1117                                 fputs(fh, "// uncomment this if you added vehicles: has vehicles\n");
1118                         if(MapInfo_Map_flags & MAPINFO_FLAG_FRUSTRATING)
1119                                 fputs(fh, "frustrating\n");
1120
1121                         FOREACH(Gametypes, MapInfo_Map_supportedGametypes & it.m_flags, {
1122                                 fputs(fh, sprintf("gametype %s // defaults: %s\n", MapInfo_Type_ToString(it), _MapInfo_GetDefaultEx(it)));
1123                         });
1124
1125                         fputs(fh, "// optional: fog density red green blue alpha mindist maxdist\n");
1126                         fputs(fh, "// optional: settemp_for_type (all|gametypename) cvarname value\n");
1127                         fputs(fh, "// optional: clientsettemp_for_type (all|gametypename) cvarname value\n");
1128                         fputs(fh, "// optional: size mins_x mins_y mins_z maxs_x maxs_y maxs_z\n");
1129                         fputs(fh, "// optional: hidden\n");
1130
1131                         fclose(fh);
1132                         r = 2;
1133                         // return r;
1134                         fh = fopen(fn, FILE_READ);
1135                         if(fh < 0)
1136                                 error("... but I just wrote it!");
1137                 }
1138
1139                 if(WARN_COND)
1140                         LOG_WARN("autogenerated mapinfo file ", fn, " has been loaded; please edit that file and move it to maps/", pFilename, ".mapinfo");
1141         }
1142
1143         _MapInfo_Map_Reset();
1144         for (;;)
1145         {
1146                 if (!((s = fgets(fh))))
1147                         break;
1148
1149                 // catch different sorts of comments
1150                 if(s == "")                    // empty lines
1151                         continue;
1152                 if(substring(s, 0, 1) == "#")  // UNIX style
1153                         continue;
1154                 if(substring(s, 0, 2) == "//") // C++ style
1155                         continue;
1156                 if(substring(s, 0, 1) == "_")  // q3map style
1157                         continue;
1158
1159                 float p = strstrofs(s, "//", 0);
1160                 if(p >= 0)
1161                         s = substring(s, 0, p);
1162
1163                 t = car(s); s = cdr(s);
1164                 if(t == "title")
1165                         MapInfo_Map_title = s;
1166                 else if(t == "description")
1167                         MapInfo_Map_description = s;
1168                 else if(t == "author")
1169                         MapInfo_Map_author = s;
1170                 else if(t == "has")
1171                 {
1172                         t = car(s); // s = cdr(s);
1173                         if     (t == "weapons") MapInfo_Map_supportedFeatures |= MAPINFO_FEATURE_WEAPONS;
1174                         else if(t == "turrets") MapInfo_Map_supportedFeatures |= MAPINFO_FEATURE_TURRETS;
1175                         else if(t == "vehicles") MapInfo_Map_supportedFeatures |= MAPINFO_FEATURE_VEHICLES;
1176                         else if(t == "monsters") MapInfo_Map_supportedFeatures |= MAPINFO_FEATURE_MONSTERS;
1177                         else if(t == "new_toys") MapInfo_Map_supportedFeatures |= MAPINFO_FEATURE_WEAPONS;
1178                         else if(WARN_COND)
1179                                 LOG_WARN("Map ", pFilename, " supports unknown feature ", t, ", ignored");
1180                 }
1181                 else if(t == "hidden")
1182                 {
1183                         MapInfo_Map_flags |= MAPINFO_FLAG_HIDDEN;
1184                 }
1185                 else if(t == "forbidden")
1186                 {
1187                         MapInfo_Map_flags |= MAPINFO_FLAG_FORBIDDEN;
1188                 }
1189                 else if(t == "frustrating")
1190                 {
1191                         MapInfo_Map_flags |= MAPINFO_FLAG_FRUSTRATING;
1192                 }
1193                 else if(t == "donotwant" || t == "noautomaplist")
1194                 {
1195                         MapInfo_Map_flags |= MAPINFO_FLAG_DONOTWANT;
1196                 }
1197                 else if(t == "gameversion_min")
1198                 {
1199                         if (cvar("gameversion") < stof(s))
1200                                 MapInfo_Map_flags |= MAPINFO_FLAG_DONOTWANT;
1201                 }
1202                 else if(t == "type")
1203                 {
1204                         t = car(s); s = cdr(s);
1205                         Gametype f = MapInfo_Type_FromString(t, true, false);
1206                         //if(WARN_COND)
1207                                 //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'.");
1208                         if(f)
1209                                 _MapInfo_Map_ApplyGametype (s, pGametypeToSet, f, true);
1210                         else if(WARN_COND)
1211                                 LOG_DEBUG("Map ", pFilename, " supports unknown game type ", t, ", ignored");
1212                 }
1213                 else if(t == "gametype")
1214                 {
1215                         t = car(s); s = cdr(s);
1216                         Gametype f = MapInfo_Type_FromString(t, true, false);
1217                         if(f)
1218                                 _MapInfo_Map_ApplyGametypeEx (s, pGametypeToSet, f);
1219                         else if(WARN_COND)
1220                                 LOG_DEBUG("Map ", pFilename, " supports unknown game type ", t, ", ignored");
1221                 }
1222                 else if(t == "size")
1223                 {
1224                         float a, b, c, d, e;
1225                         t = car(s); s = cdr(s); a = stof(t);
1226                         t = car(s); s = cdr(s); b = stof(t);
1227                         t = car(s); s = cdr(s); c = stof(t);
1228                         t = car(s); s = cdr(s); d = stof(t);
1229                         t = car(s); s = cdr(s); e = stof(t);
1230                         if(s == "")
1231                         {
1232                                 if(WARN_COND)
1233                                         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");
1234                         }
1235                         else
1236                         {
1237                                 t = car(s); s = cdr(s); f = stof(t);
1238                                 if(s != "")
1239                                 {
1240                                         if(WARN_COND)
1241                                                 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");
1242                                 }
1243                                 else
1244                                 {
1245                                         if(a >= d || b >= e || c >= f)
1246                                         {
1247                                                 if(WARN_COND)
1248                                                         LOG_WARN("Map ", pFilename, " contains an incorrect size line, mins have to be < maxs");
1249                                         }
1250                                         else
1251                                         {
1252                                                 MapInfo_Map_mins.x = a;
1253                                                 MapInfo_Map_mins.y = b;
1254                                                 MapInfo_Map_mins.z = c;
1255                                                 MapInfo_Map_maxs.x = d;
1256                                                 MapInfo_Map_maxs.y = e;
1257                                                 MapInfo_Map_maxs.z = f;
1258                                         }
1259                                 }
1260                         }
1261                 }
1262                 else if(t == "settemp_for_type")
1263                 {
1264                         t = car(s); s = cdr(s);
1265                         bool all = t == "all";
1266                         Gametype f = NULL;
1267                         if(all || (f = MapInfo_Type_FromString(t, true, false)))
1268                         {
1269                                 if((all ? MAPINFO_TYPE_ALL : f.m_flags) & pGametypeToSet.m_flags)
1270                                 {
1271                                         _MapInfo_Parse_Settemp(pFilename, acl, 0, s, 1);
1272                                 }
1273                         }
1274                         else
1275                         {
1276                                 LOG_DEBUG("Map ", pFilename, " has a setting for unknown game type ", t, ", ignored");
1277                         }
1278                 }
1279                 else if(t == "clientsettemp_for_type")
1280                 {
1281                         t = car(s); s = cdr(s);
1282                         bool all = t == "all";
1283                         Gametype f = NULL;
1284                         if(all || (f = MapInfo_Type_FromString(t, true, false)))
1285                         {
1286                                 if((all ? MAPINFO_TYPE_ALL : f.m_flags) & pGametypeToSet.m_flags)
1287                                 {
1288                                         _MapInfo_Parse_Settemp(pFilename, acl, 1, s, 1);
1289                                 }
1290                         }
1291                         else
1292                         {
1293                                 LOG_DEBUG("Map ", pFilename, " has a client setting for unknown game type ", t, ", ignored");
1294                         }
1295                 }
1296                 else if(t == "fog")
1297                 {
1298                         if (!cvar_value_issafe(s))
1299                         {
1300                                 if(WARN_COND)
1301                                         LOG_WARN("Map ", pFilename, " contains a potentially harmful fog setting, ignored");
1302                         }
1303                         else
1304                                 MapInfo_Map_fog = s;
1305                 }
1306                 else if(t == "cdtrack")
1307                 {
1308                         t = car(s); s = cdr(s);
1309                         // We do this only if pGametypeToSet even though this
1310                         // content is theoretically game type independent,
1311                         // because MapInfo_Map_clientstuff contains otherwise
1312                         // game type dependent stuff. That way this value stays
1313                         // empty when not setting a game type to not set any
1314                         // false expectations.
1315                         if(pGametypeToSet)
1316                         {
1317                                 if (!cvar_value_issafe(t))
1318                                 {
1319                                         if(WARN_COND)
1320                                                 LOG_WARN("Map ", pFilename, " contains a potentially harmful cdtrack, ignored");
1321                                 }
1322                                 else
1323                                         MapInfo_Map_clientstuff = strcat(
1324                                                 MapInfo_Map_clientstuff, "cd loop \"", t, "\"\n"
1325                                         );
1326                         }
1327                 }
1328                 else if(WARN_COND)
1329                         LOG_WARN("Map ", pFilename, " provides unknown info item ", t, ", ignored");
1330         }
1331         fclose(fh);
1332
1333 LABEL(mapinfo_handled)
1334 #ifdef SVQC
1335         // if the map is currently loaded we can read worldspawn fields directly
1336         if (pFilename == mi_shortname)
1337         {
1338                 if (MapInfo_Map_title == "<TITLE>")
1339                         if (world.message != "")
1340                                 MapInfo_Map_title = world.message;
1341                 if (MapInfo_Map_author == "<AUTHOR>")
1342                         if ((s = GetField_fullspawndata(world, "author")) != "")
1343                                 MapInfo_Map_author = s;
1344         }
1345 #endif
1346         // Could skip removing author from title when it's source is .mapinfo
1347         // but must always do it for world.message and .arena/.defi as VQ3 didn't support author
1348         // so mappers tended to put it in world.message and/or longname.
1349         MapInfo_Map_title = MapInfo_title_sans_author(MapInfo_Map_title); // may set author if not set
1350
1351         if(MapInfo_Map_title == "<TITLE>")
1352                 MapInfo_Map_titlestring = strcat("^2", MapInfo_Map_bspname);
1353         else if(MapInfo_isRedundant(MapInfo_Map_bspname, MapInfo_Map_title))
1354                 MapInfo_Map_titlestring = strcat("^2", MapInfo_Map_title);
1355         else
1356                 MapInfo_Map_titlestring = sprintf("^2%s ^7// ^2%s", MapInfo_Map_bspname, MapInfo_Map_title);
1357
1358         if (MapInfo_Map_author == "<AUTHOR>")
1359                 MapInfo_Map_author = ""; // don't display "<AUTHOR>" in the UI (we do write it to .mapinfo files)
1360
1361         MapInfo_Cache_Store();
1362         if(MapInfo_Map_supportedGametypes != 0)
1363                 return r;
1364         if (WARN_COND)
1365                 LOG_WARN("Map ", pFilename, " supports no game types, ignored");
1366         return 0;
1367 }
1368 int MapInfo_Get_ByName(string pFilename, float pAllowGenerate, Gametype pGametypeToSet)
1369 {
1370         int r = MapInfo_Get_ByName_NoFallbacks(pFilename, pAllowGenerate, pGametypeToSet);
1371
1372         FOREACH(Gametypes, it.m_isForcedSupported(it), _MapInfo_Map_ApplyGametypeEx("", pGametypeToSet, it));
1373
1374         if(pGametypeToSet)
1375         {
1376                 if(!(MapInfo_Map_supportedGametypes & pGametypeToSet.m_flags))
1377                 {
1378                         error("Can't select the requested game type. This should never happen as the caller should prevent it!\n");
1379                         //_MapInfo_Map_ApplyGametypeEx("", pGametypeToSet, MAPINFO_TYPE_DEATHMATCH);
1380                         //return;
1381                 }
1382         }
1383
1384         return r;
1385 }
1386
1387 bool MapReadSizes(string map)
1388 {
1389         // TODO: implement xonotic#28 / xonvote 172 (sizes in mapinfo)
1390         string readsize_msg = strcat("MapReadSizes ", map);
1391         float fh = fopen(strcat("maps/", map, ".sizes"), FILE_READ);
1392         if(fh >= 0)
1393         {
1394                 map_minplayers = stoi(fgets(fh));
1395                 map_maxplayers = stoi(fgets(fh));
1396                 fclose(fh);
1397                 LOG_TRACEF(readsize_msg, ": ok, min %d max %d", map_minplayers, map_maxplayers);
1398                 return true;
1399         }
1400         LOG_TRACE(readsize_msg, ": not found");
1401         return false;
1402 }
1403
1404 float MapInfo_FindName(string s)
1405 {
1406         // if there is exactly one map of prefix s, return it
1407         // if not, return the null string
1408         // note that DP sorts glob results... so I can use a binary search
1409         float l, r, m, cmp;
1410         l = 0;
1411         r = MapInfo_count;
1412         // invariants: r is behind s, l-1 is equal or before
1413         while(l != r)
1414         {
1415                 m = floor((l + r) / 2);
1416                 MapInfo_FindName_match = _MapInfo_GlobItem(MapInfo_FilterList_Lookup(m));
1417                 cmp = strcasecmp(MapInfo_FindName_match, s);
1418                 if(cmp == 0)
1419                         return m; // found and good
1420                 if(cmp < 0)
1421                         l = m + 1; // l-1 is before s
1422                 else
1423                         r = m; // behind s
1424         }
1425         MapInfo_FindName_match = _MapInfo_GlobItem(MapInfo_FilterList_Lookup(l));
1426         MapInfo_FindName_firstResult = l;
1427         // r == l, so: l is behind s, l-1 is before
1428         // SO: if there is any, l is the one with the right prefix
1429         //     and l+1 may be one too
1430         if(l == MapInfo_count)
1431         {
1432                 MapInfo_FindName_match = string_null;
1433                 MapInfo_FindName_firstResult = -1;
1434                 return -1; // no MapInfo_FindName_match, behind last item
1435         }
1436         if(!startsWithNocase(MapInfo_FindName_match, s))
1437         {
1438                 MapInfo_FindName_match = string_null;
1439                 MapInfo_FindName_firstResult = -1;
1440                 return -1; // wrong prefix
1441         }
1442         if(l == MapInfo_count - 1)
1443                 return l; // last one, nothing can follow => unique
1444         if(startsWithNocase(_MapInfo_GlobItem(MapInfo_FilterList_Lookup(l + 1)), s))
1445         {
1446                 MapInfo_FindName_match = string_null;
1447                 return -1; // ambigous MapInfo_FindName_match
1448         }
1449         return l;
1450 }
1451
1452 string MapInfo_FixName(string s)
1453 {
1454         MapInfo_FindName(s);
1455         return MapInfo_FindName_match;
1456 }
1457
1458 int MapInfo_CurrentFeatures()
1459 {
1460         int req = 0;
1461     // TODO: find a better way to check if weapons are required on the map
1462         if(!(cvar("g_instagib") || cvar("g_overkill") || cvar("g_nix") || cvar("g_weaponarena") || !cvar("g_pickup_items") || !cvar("g_melee_only") 
1463                 || cvar("g_race") || cvar("g_cts") || cvar("g_nexball") || cvar("g_ca") || cvar("g_freezetag") || cvar("g_lms")))
1464                 req |= MAPINFO_FEATURE_WEAPONS;
1465         return req;
1466 }
1467
1468 Gametype MapInfo_CurrentGametype()
1469 {
1470         Gametype prev = MapInfo_Type_FromString(cvar_string("gamecfg"), false, false);
1471         FOREACH(Gametypes, cvar(it.netname) && it != prev, return it);
1472         return prev ? prev : MAPINFO_TYPE_DEATHMATCH;
1473 }
1474
1475 float _MapInfo_CheckMap(string s, bool gametype_only) // returns 0 if the map can't be played with the current settings, 1 otherwise
1476 {
1477         if(!MapInfo_Get_ByName(s, 1, NULL))
1478                 return 0;
1479         if((MapInfo_Map_supportedGametypes & MapInfo_CurrentGametype().m_flags) == 0)
1480                 return 0;
1481         if (gametype_only)
1482                 return 1;
1483         if((MapInfo_Map_supportedFeatures & MapInfo_CurrentFeatures()) != MapInfo_CurrentFeatures())
1484                 return 0;
1485         return 1;
1486 }
1487
1488 float MapInfo_CheckMap(string s) // returns 0 if the map can't be played with the current settings, 1 otherwise
1489 {
1490         float r;
1491         r = _MapInfo_CheckMap(s, false);
1492         MapInfo_ClearTemps();
1493         return r;
1494 }
1495
1496 void MapInfo_SwitchGameType(Gametype t)
1497 {
1498         FOREACH(Gametypes, true, cvar_set(it.netname, (it == t) ? "1" : "0"));
1499 }
1500
1501 void MapInfo_LoadMap(string s, float reinit)
1502 {
1503         MapInfo_Map_supportedGametypes = 0;
1504         // we shouldn't need this, as LoadMapSettings already fixes the gametype
1505         //if(!MapInfo_CheckMap(s))
1506         //{
1507         //      print("EMERGENCY: can't play the selected map in the given game mode. Falling back to DM.\n");
1508         //      MapInfo_SwitchGameType(MAPINFO_TYPE_DEATHMATCH.m_flags);
1509         //}
1510
1511         LOG_INFO("Switching to map ", s);
1512
1513         cvar_settemp_restore();
1514         if(reinit)
1515                 localcmd(strcat("\nmap ", s, "\n"));
1516         else
1517                 localcmd(strcat("\nchangelevel ", s, "\n"));
1518 }
1519
1520 string MapInfo_ListAllowedMaps(Gametype type, float pRequiredFlags, float pForbiddenFlags)
1521 {
1522         string out;
1523
1524         // to make absolutely sure:
1525         MapInfo_Enumerate();
1526         MapInfo_FilterGametype(type, MapInfo_CurrentFeatures(), pRequiredFlags, pForbiddenFlags, 0);
1527
1528         out = "";
1529         for(float i = 0; i < MapInfo_count; ++i)
1530                 out = strcat(out, " ", _MapInfo_GlobItem(MapInfo_FilterList_Lookup(i)));
1531         return substring(out, 1, strlen(out) - 1);
1532 }
1533
1534 string MapInfo_ListAllAllowedMaps(float pRequiredFlags, float pForbiddenFlags)
1535 {
1536         string out;
1537
1538         // to make absolutely sure:
1539         MapInfo_Enumerate();
1540         _MapInfo_FilterGametype(MAPINFO_TYPE_ALL, 0, pRequiredFlags, pForbiddenFlags, 0);
1541
1542         out = "";
1543         for(float i = 0; i < MapInfo_count; ++i)
1544                 out = strcat(out, " ", _MapInfo_GlobItem(MapInfo_FilterList_Lookup(i)));
1545
1546         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), pRequiredFlags, pForbiddenFlags, 0);
1547
1548         return substring(out, 1, strlen(out) - 1);
1549 }
1550
1551 void MapInfo_LoadMapSettings_SaveGameType(Gametype t)
1552 {
1553         MapInfo_SwitchGameType(t);
1554         cvar_set("gamecfg", t.mdl);
1555         MapInfo_LoadedGametype = t;
1556 }
1557
1558 void MapInfo_LoadMapSettings(string s) // to be called from worldspawn
1559 {
1560         Gametype t = MapInfo_CurrentGametype();
1561         MapInfo_LoadMapSettings_SaveGameType(t);
1562
1563         if(!_MapInfo_CheckMap(s, true)) // with underscore, it keeps temps
1564         {
1565                 if(cvar("g_mapinfo_allow_unsupported_modes_and_let_stuff_break"))
1566                 {
1567                         LOG_SEVERE("can't play the selected map in the given game mode. Working with only the override settings.");
1568                         _MapInfo_Map_ApplyGametypeEx("", t, t);
1569                         return; // do not call Get_ByName!
1570                 }
1571
1572                 if(MapInfo_Map_supportedGametypes == 0)
1573                 {
1574                         RandomSelection_Init();
1575                         FOREACH(Gametypes, it.m_priority == 2, 
1576                         {
1577                                 MapInfo_Map_supportedGametypes |= it.m_flags;
1578                                 RandomSelection_AddEnt(it, 1, 1);
1579                         });
1580                         if(RandomSelection_chosen_ent)
1581                                 t = RandomSelection_chosen_ent;
1582                         LOG_SEVEREF("Mapinfo system is not functional at all. Falling back to a preferred mode (%s).", t.mdl);
1583                         MapInfo_LoadMapSettings_SaveGameType(t);
1584                         _MapInfo_Map_ApplyGametypeEx("", t, t);
1585                         return; // do not call Get_ByName!
1586                 }
1587
1588 #if 0
1589                 // find the lowest bit in the supported gametypes
1590                 // unnecessary now that we select one at random
1591                 int _t = 1;
1592                 while(!(MapInfo_Map_supportedGametypes & 1))
1593                 {
1594                         _t <<= 1;
1595                         MapInfo_Map_supportedGametypes = floor(MapInfo_Map_supportedGametypes >> 1);
1596                 }
1597 #endif
1598                 RandomSelection_Init();
1599                 Gametype t_prev = t;
1600                 FOREACH(Gametypes, MapInfo_Map_supportedGametypes & it.m_flags,
1601                 {
1602                         RandomSelection_AddEnt(it, 1, it.m_priority);
1603                 });
1604                 if(RandomSelection_chosen_ent)
1605                         t = RandomSelection_chosen_ent;
1606
1607                 // t is now a supported mode!
1608                 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);
1609                 MapInfo_LoadMapSettings_SaveGameType(t);
1610         }
1611         if(!_MapInfo_CheckMap(s, false)) { // with underscore, it keeps temps
1612                 LOG_WARNF("the selected map lacks features required by current settings; playing anyway.");
1613         }
1614         MapInfo_Get_ByName(s, 1, t);
1615 }
1616
1617 void MapInfo_ClearTemps()
1618 {
1619         MapInfo_Map_bspname = string_null;
1620         MapInfo_Map_title = string_null;
1621         MapInfo_Map_titlestring = string_null;
1622         MapInfo_Map_description = string_null;
1623         MapInfo_Map_author = string_null;
1624         MapInfo_Map_clientstuff = string_null;
1625         MapInfo_Map_supportedGametypes = 0;
1626         MapInfo_Map_supportedFeatures = 0;
1627 }
1628
1629 void MapInfo_Shutdown()
1630 {
1631         MapInfo_ClearTemps();
1632         MapInfo_Filter_Free();
1633         MapInfo_Cache_Destroy();
1634         if(_MapInfo_globopen)
1635         {
1636                 search_end(_MapInfo_globhandle);
1637                 _MapInfo_globhandle = -1;
1638                 _MapInfo_globopen = false;
1639         }
1640 }
1641
1642 int MapInfo_ForbiddenFlags()
1643 {
1644         int f = MAPINFO_FLAG_FORBIDDEN;
1645
1646 #ifdef GAMEQC
1647         if (!cvar("g_maplist_allow_hidden"))
1648 #endif
1649                 f |= MAPINFO_FLAG_HIDDEN;
1650
1651         if (!cvar("g_maplist_allow_frustrating"))
1652                 f |= MAPINFO_FLAG_FRUSTRATING;
1653
1654         return f;
1655 }
1656
1657 int MapInfo_RequiredFlags()
1658 {
1659         int f = 0;
1660
1661         if(cvar("g_maplist_allow_frustrating") > 1)
1662                 f |= MAPINFO_FLAG_FRUSTRATING;
1663
1664         return f;
1665 }