]> git.xonotic.org Git - xonotic/darkplaces.git/blob - cl_screen.c
Merge branch 'master' into Mario/wrath-darkplaces_extra
[xonotic/darkplaces.git] / cl_screen.c
1
2 #include "quakedef.h"
3 #include "cl_video.h"
4 #include "image.h"
5 #include "jpeg.h"
6 #include "image_png.h"
7 #include "cl_collision.h"
8 #include "libcurl.h"
9 #include "csprogs.h"
10 #include "r_stats.h"
11 #ifdef CONFIG_VIDEO_CAPTURE
12 #include "cap_avi.h"
13 #include "cap_ogg.h"
14 #endif
15
16 // we have to include snd_main.h here only to get access to snd_renderbuffer->format.speed when writing the AVI headers
17 #include "snd_main.h"
18
19 cvar_t scr_viewsize = {CF_CLIENT | CF_ARCHIVE, "viewsize","100", "how large the view should be, 110 disables inventory bar, 120 disables status bar"};
20 cvar_t scr_fov = {CF_CLIENT | CF_ARCHIVE, "fov","90", "field of vision, 1-170 degrees, default 90, some players use 110-130"};
21 cvar_t scr_conalpha = {CF_CLIENT | CF_ARCHIVE, "scr_conalpha", "1", "opacity of console background gfx/conback"};
22 cvar_t scr_conalphafactor = {CF_CLIENT | CF_ARCHIVE, "scr_conalphafactor", "1", "opacity of console background gfx/conback relative to scr_conalpha; when 0, gfx/conback is not drawn"};
23 cvar_t scr_conalpha2factor = {CF_CLIENT | CF_ARCHIVE, "scr_conalpha2factor", "0", "opacity of console background gfx/conback2 relative to scr_conalpha; when 0, gfx/conback2 is not drawn"};
24 cvar_t scr_conalpha3factor = {CF_CLIENT | CF_ARCHIVE, "scr_conalpha3factor", "0", "opacity of console background gfx/conback3 relative to scr_conalpha; when 0, gfx/conback3 is not drawn"};
25 cvar_t scr_conbrightness = {CF_CLIENT | CF_ARCHIVE, "scr_conbrightness", "1", "brightness of console background (0 = black, 1 = image)"};
26 cvar_t scr_conforcewhiledisconnected = {CF_CLIENT, "scr_conforcewhiledisconnected", "1", "forces fullscreen console while disconnected"};
27 cvar_t scr_conscroll_x = {CF_CLIENT | CF_ARCHIVE, "scr_conscroll_x", "0", "scroll speed of gfx/conback in x direction"};
28 cvar_t scr_conscroll_y = {CF_CLIENT | CF_ARCHIVE, "scr_conscroll_y", "0", "scroll speed of gfx/conback in y direction"};
29 cvar_t scr_conscroll2_x = {CF_CLIENT | CF_ARCHIVE, "scr_conscroll2_x", "0", "scroll speed of gfx/conback2 in x direction"};
30 cvar_t scr_conscroll2_y = {CF_CLIENT | CF_ARCHIVE, "scr_conscroll2_y", "0", "scroll speed of gfx/conback2 in y direction"};
31 cvar_t scr_conscroll3_x = {CF_CLIENT | CF_ARCHIVE, "scr_conscroll3_x", "0", "scroll speed of gfx/conback3 in x direction"};
32 cvar_t scr_conscroll3_y = {CF_CLIENT | CF_ARCHIVE, "scr_conscroll3_y", "0", "scroll speed of gfx/conback3 in y direction"};
33 #ifdef CONFIG_MENU
34 cvar_t scr_menuforcewhiledisconnected = {CF_CLIENT, "scr_menuforcewhiledisconnected", "0", "forces menu while disconnected"};
35 #endif
36 cvar_t scr_centertime = {CF_CLIENT, "scr_centertime","2", "how long centerprint messages show"};
37 cvar_t scr_showram = {CF_CLIENT | CF_ARCHIVE, "showram","1", "show ram icon if low on surface cache memory (not used)"};
38 cvar_t scr_showturtle = {CF_CLIENT | CF_ARCHIVE, "showturtle","0", "show turtle icon when framerate is too low"};
39 cvar_t scr_showpause = {CF_CLIENT | CF_ARCHIVE, "showpause","1", "show pause icon when game is paused"};
40 cvar_t scr_showbrand = {CF_CLIENT, "showbrand","0", "shows gfx/brand.tga in a corner of the screen (different values select different positions, including centered)"};
41 cvar_t scr_printspeed = {CF_CLIENT, "scr_printspeed","0", "speed of intermission printing (episode end texts), a value of 0 disables the slow printing"};
42 cvar_t scr_loadingscreen_background = {CF_CLIENT, "scr_loadingscreen_background","0", "show the last visible background during loading screen (costs one screenful of video memory)"};
43 cvar_t scr_loadingscreen_scale = {CF_CLIENT, "scr_loadingscreen_scale","1", "scale factor of the background"};
44 cvar_t scr_loadingscreen_scale_base = {CF_CLIENT, "scr_loadingscreen_scale_base","0", "0 = console pixels, 1 = video pixels"};
45 cvar_t scr_loadingscreen_scale_limit = {CF_CLIENT, "scr_loadingscreen_scale_limit","0", "0 = no limit, 1 = until first edge hits screen edge, 2 = until last edge hits screen edge, 3 = until width hits screen width, 4 = until height hits screen height"};
46 cvar_t scr_loadingscreen_picture = {CF_CLIENT, "scr_loadingscreen_picture", "gfx/loading", "picture shown during loading"};
47 cvar_t scr_loadingscreen_count = {CF_CLIENT, "scr_loadingscreen_count","1", "number of loading screen files to use randomly (named loading.tga, loading2.tga, loading3.tga, ...)"};
48 cvar_t scr_loadingscreen_firstforstartup = {CF_CLIENT, "scr_loadingscreen_firstforstartup","0", "remove loading.tga from random scr_loadingscreen_count selection and only display it on client startup, 0 = normal, 1 = firstforstartup"};
49 cvar_t scr_loadingscreen_barcolor = {CF_CLIENT, "scr_loadingscreen_barcolor", "0 0 1", "rgb color of loadingscreen progress bar"};
50 cvar_t scr_loadingscreen_barheight = {CF_CLIENT, "scr_loadingscreen_barheight", "8", "the height of the loadingscreen progress bar"};
51 cvar_t scr_loadingscreen_maxfps = {CF_CLIENT, "scr_loadingscreen_maxfps", "10", "restrict maximal FPS for loading screen so it will not update very often (this will make lesser loading times on a maps loading large number of models)"};
52 cvar_t scr_infobar_height = {CF_CLIENT, "scr_infobar_height", "8", "the height of the infobar items"};
53 cvar_t vid_conwidthauto = {CF_CLIENT | CF_ARCHIVE, "vid_conwidthauto", "1", "automatically update vid_conwidth to match aspect ratio"};
54 cvar_t vid_conwidth = {CF_CLIENT | CF_ARCHIVE, "vid_conwidth", "640", "virtual width of 2D graphics system (note: changes may be overwritten, see vid_conwidthauto)"};
55 cvar_t vid_conheight = {CF_CLIENT | CF_ARCHIVE, "vid_conheight", "480", "virtual height of 2D graphics system"};
56 cvar_t vid_pixelheight = {CF_CLIENT | CF_ARCHIVE, "vid_pixelheight", "1", "adjusts vertical field of vision to account for non-square pixels (1280x1024 on a CRT monitor for example)"};
57 cvar_t scr_aspectname = {CF_CLIENT, "scr_aspectname", "16-9", "string name for the current aspect ratio; use a dash instead of a colon, e. g. 16-9"};
58 cvar_t scr_screenshot_jpeg = {CF_CLIENT | CF_ARCHIVE, "scr_screenshot_jpeg","1", "save jpeg instead of targa"};
59 cvar_t scr_screenshot_jpeg_quality = {CF_CLIENT | CF_ARCHIVE, "scr_screenshot_jpeg_quality","0.9", "image quality of saved jpeg"};
60 cvar_t scr_screenshot_png = {CF_CLIENT | CF_ARCHIVE, "scr_screenshot_png","0", "save png instead of targa"};
61 cvar_t scr_screenshot_gammaboost = {CF_CLIENT | CF_ARCHIVE, "scr_screenshot_gammaboost","1", "gamma correction on saved screenshots and videos, 1.0 saves unmodified images"};
62 cvar_t scr_screenshot_alpha = {CF_CLIENT, "scr_screenshot_alpha","0", "try to write an alpha channel to screenshots (debugging feature)"};
63 cvar_t scr_screenshot_timestamp = {CF_CLIENT | CF_ARCHIVE, "scr_screenshot_timestamp", "1", "use a timestamp based number of the type YYYYMMDDHHMMSSsss instead of sequential numbering"};
64 // scr_screenshot_name is defined in fs.c
65 #ifdef CONFIG_VIDEO_CAPTURE
66 cvar_t cl_capturevideo = {CF_CLIENT, "cl_capturevideo", "0", "enables saving of video to a .avi file using uncompressed I420 colorspace and PCM audio, note that scr_screenshot_gammaboost affects the brightness of the output)"};
67 cvar_t cl_capturevideo_demo_stop = {CF_CLIENT | CF_ARCHIVE, "cl_capturevideo_demo_stop", "1", "automatically stops video recording when demo ends"};
68 cvar_t cl_capturevideo_printfps = {CF_CLIENT | CF_ARCHIVE, "cl_capturevideo_printfps", "1", "prints the frames per second captured in capturevideo (is only written to the log file, not to the console, as that would be visible on the video)"};
69 cvar_t cl_capturevideo_width = {CF_CLIENT | CF_ARCHIVE, "cl_capturevideo_width", "0", "scales all frames to this resolution before saving the video"};
70 cvar_t cl_capturevideo_height = {CF_CLIENT | CF_ARCHIVE, "cl_capturevideo_height", "0", "scales all frames to this resolution before saving the video"};
71 cvar_t cl_capturevideo_realtime = {CF_CLIENT, "cl_capturevideo_realtime", "0", "causes video saving to operate in realtime (mostly useful while playing, not while capturing demos), this can produce a much lower quality video due to poor sound/video sync and will abort saving if your machine stalls for over a minute"};
72 cvar_t cl_capturevideo_fps = {CF_CLIENT | CF_ARCHIVE, "cl_capturevideo_fps", "30", "how many frames per second to save (29.97 for NTSC, 30 for typical PC video, 15 can be useful)"};
73 cvar_t cl_capturevideo_nameformat = {CF_CLIENT | CF_ARCHIVE, "cl_capturevideo_nameformat", "dpvideo", "prefix for saved videos (the date is encoded using strftime escapes)"};
74 cvar_t cl_capturevideo_number = {CF_CLIENT | CF_ARCHIVE, "cl_capturevideo_number", "1", "number to append to video filename, incremented each time a capture begins"};
75 cvar_t cl_capturevideo_ogg = {CF_CLIENT | CF_ARCHIVE, "cl_capturevideo_ogg", "1", "save captured video data as Ogg/Vorbis/Theora streams"};
76 cvar_t cl_capturevideo_framestep = {CF_CLIENT | CF_ARCHIVE, "cl_capturevideo_framestep", "1", "when set to n >= 1, render n frames to capture one (useful for motion blur like effects)"};
77 #endif
78 cvar_t r_letterbox = {CF_CLIENT, "r_letterbox", "0", "reduces vertical height of view to simulate a letterboxed movie effect (can be used by mods for cutscenes)"};
79 cvar_t r_stereo_separation = {CF_CLIENT, "r_stereo_separation", "4", "separation distance of eyes in the world (negative values are only useful for cross-eyed viewing)"};
80 cvar_t r_stereo_sidebyside = {CF_CLIENT, "r_stereo_sidebyside", "0", "side by side views for those who can't afford glasses but can afford eye strain (note: use a negative r_stereo_separation if you want cross-eyed viewing)"};
81 cvar_t r_stereo_horizontal = {CF_CLIENT, "r_stereo_horizontal", "0", "aspect skewed side by side view for special decoder/display hardware"};
82 cvar_t r_stereo_vertical = {CF_CLIENT, "r_stereo_vertical", "0", "aspect skewed top and bottom view for special decoder/display hardware"};
83 cvar_t r_stereo_redblue = {CF_CLIENT, "r_stereo_redblue", "0", "red/blue anaglyph stereo glasses (note: most of these glasses are actually red/cyan, try that one too)"};
84 cvar_t r_stereo_redcyan = {CF_CLIENT, "r_stereo_redcyan", "0", "red/cyan anaglyph stereo glasses, the kind given away at drive-in movies like Creature From The Black Lagoon In 3D"};
85 cvar_t r_stereo_redgreen = {CF_CLIENT, "r_stereo_redgreen", "0", "red/green anaglyph stereo glasses (for those who don't mind yellow)"};
86 cvar_t r_stereo_angle = {CF_CLIENT, "r_stereo_angle", "0", "separation angle of eyes (makes the views look different directions, as an example, 90 gives a 90 degree separation where the views are 45 degrees left and 45 degrees right)"};
87 cvar_t scr_stipple = {CF_CLIENT, "scr_stipple", "0", "interlacing-like stippling of the display"};
88 cvar_t scr_refresh = {CF_CLIENT, "scr_refresh", "1", "allows you to completely shut off rendering for benchmarking purposes"};
89 cvar_t scr_screenshot_name_in_mapdir = {CF_CLIENT | CF_ARCHIVE, "scr_screenshot_name_in_mapdir", "0", "if set to 1, screenshots are placed in a subdirectory named like the map they are from"};
90 cvar_t net_graph = {CF_CLIENT | CF_ARCHIVE, "net_graph", "0", "shows a graph of packet sizes and other information, 0 = off, 1 = show client netgraph, 2 = show client and server netgraphs (when hosting a server)"};
91 cvar_t cl_demo_mousegrab = {CF_CLIENT, "cl_demo_mousegrab", "0", "Allows reading the mouse input while playing demos. Useful for camera mods developed in csqc. (0: never, 1: always)"};
92 cvar_t timedemo_screenshotframelist = {CF_CLIENT, "timedemo_screenshotframelist", "", "when performing a timedemo, take screenshots of each frame in this space-separated list - example: 1 201 401"};
93 cvar_t vid_touchscreen_outlinealpha = {CF_CLIENT, "vid_touchscreen_outlinealpha", "0", "opacity of touchscreen area outlines"};
94 cvar_t vid_touchscreen_overlayalpha = {CF_CLIENT, "vid_touchscreen_overlayalpha", "0.25", "opacity of touchscreen area icons"};
95
96 extern cvar_t sbar_info_pos;
97 extern cvar_t r_fog_clear;
98
99 int jpeg_supported = false;
100
101 qbool   scr_initialized;                // ready to draw
102
103 float           scr_con_current;
104 int                     scr_con_margin_bottom;
105
106 extern int      con_vislines;
107
108 extern int cl_punchangle_applied;
109
110 static void SCR_ScreenShot_f(cmd_state_t *cmd);
111 static void R_Envmap_f(cmd_state_t *cmd);
112
113 // backend
114 void R_ClearScreen(qbool fogcolor);
115
116 /*
117 ===============================================================================
118
119 CENTER PRINTING
120
121 ===============================================================================
122 */
123
124 char            scr_centerstring[MAX_INPUTLINE];
125 float           scr_centertime_start;   // for slow victory printing
126 float           scr_centertime_off;
127 int                     scr_center_lines;
128 int                     scr_erase_lines;
129 int                     scr_erase_center;
130 char        scr_infobarstring[MAX_INPUTLINE];
131 float       scr_infobartime_off;
132
133 /*
134 ==============
135 SCR_CenterPrint
136
137 Called for important messages that should stay in the center of the screen
138 for a few moments
139 ==============
140 */
141 void SCR_CenterPrint(const char *str)
142 {
143         strlcpy (scr_centerstring, str, sizeof (scr_centerstring));
144         scr_centertime_off = scr_centertime.value;
145         scr_centertime_start = cl.time;
146
147 // count the number of lines for centering
148         scr_center_lines = 1;
149         while (*str)
150         {
151                 if (*str == '\n')
152                         scr_center_lines++;
153                 str++;
154         }
155 }
156
157
158 static void SCR_DrawCenterString (void)
159 {
160         char    *start;
161         int             x, y;
162         int             remaining;
163         int             color;
164
165         if(cl.intermission == 2) // in finale,
166                 if(sb_showscores) // make TAB hide the finale message (sb_showscores overrides finale in sbar.c)
167                         return;
168
169         if(scr_centertime.value <= 0 && !cl.intermission)
170                 return;
171
172 // the finale prints the characters one at a time, except if printspeed is an absurdly high value
173         if (cl.intermission && scr_printspeed.value > 0 && scr_printspeed.value < 1000000)
174                 remaining = (int)(scr_printspeed.value * (cl.time - scr_centertime_start));
175         else
176                 remaining = 9999;
177
178         scr_erase_center = 0;
179         start = scr_centerstring;
180
181         if (remaining < 1)
182                 return;
183
184         if (scr_center_lines <= 4)
185                 y = (int)(vid_conheight.integer*0.35);
186         else
187                 y = 48;
188
189         color = -1;
190         do
191         {
192                 // scan the number of characters on the line, not counting color codes
193                 char *newline = strchr(start, '\n');
194                 int l = newline ? (newline - start) : (int)strlen(start);
195                 float width = DrawQ_TextWidth(start, l, 8, 8, false, FONT_CENTERPRINT);
196
197                 x = (int) (vid_conwidth.integer - width)/2;
198                 if (l > 0)
199                 {
200                         if (remaining < l)
201                                 l = remaining;
202                         DrawQ_String(x, y, start, l, 8, 8, 1, 1, 1, 1, 0, &color, false, FONT_CENTERPRINT);
203                         remaining -= l;
204                         if (remaining <= 0)
205                                 return;
206                 }
207                 y += 8;
208
209                 if (!newline)
210                         break;
211                 start = newline + 1; // skip the \n
212         } while (1);
213 }
214
215 static void SCR_CheckDrawCenterString (void)
216 {
217         if (scr_center_lines > scr_erase_lines)
218                 scr_erase_lines = scr_center_lines;
219
220         if (cl.time > cl.oldtime)
221                 scr_centertime_off -= cl.time - cl.oldtime;
222
223         // don't draw if this is a normal stats-screen intermission,
224         // only if it is not an intermission, or a finale intermission
225         if (cl.intermission == 1)
226                 return;
227         if (scr_centertime_off <= 0 && !cl.intermission)
228                 return;
229         if (key_dest != key_game)
230                 return;
231
232         SCR_DrawCenterString ();
233 }
234
235 static void SCR_DrawNetGraph_DrawGraph (int graphx, int graphy, int graphwidth, int graphheight, float graphscale, int graphlimit, const char *label, float textsize, int packetcounter, netgraphitem_t *netgraph)
236 {
237         netgraphitem_t *graph;
238         int j, x, y;
239         int totalbytes = 0;
240         char bytesstring[128];
241         float g[NETGRAPH_PACKETS][7];
242         float *a;
243         float *b;
244         DrawQ_Fill(graphx, graphy, graphwidth, graphheight + textsize * 2, 0, 0, 0, 0.5, 0);
245         // draw the bar graph itself
246         memset(g, 0, sizeof(g));
247         for (j = 0;j < NETGRAPH_PACKETS;j++)
248         {
249                 graph = netgraph + j;
250                 g[j][0] = 1.0f - 0.25f * (host.realtime - graph->time);
251                 g[j][1] = 1.0f;
252                 g[j][2] = 1.0f;
253                 g[j][3] = 1.0f;
254                 g[j][4] = 1.0f;
255                 g[j][5] = 1.0f;
256                 g[j][6] = 1.0f;
257                 if (graph->unreliablebytes == NETGRAPH_LOSTPACKET)
258                         g[j][1] = 0.00f;
259                 else if (graph->unreliablebytes == NETGRAPH_CHOKEDPACKET)
260                         g[j][2] = 0.90f;
261                 else
262                 {
263                         if(netgraph[j].time >= netgraph[(j+NETGRAPH_PACKETS-1)%NETGRAPH_PACKETS].time)
264                                 if(graph->unreliablebytes + graph->reliablebytes + graph->ackbytes >= graphlimit * (netgraph[j].time - netgraph[(j+NETGRAPH_PACKETS-1)%NETGRAPH_PACKETS].time))
265                                         g[j][2] = 0.98f;
266                         g[j][3] = 1.0f    - graph->unreliablebytes * graphscale;
267                         g[j][4] = g[j][3] - graph->reliablebytes   * graphscale;
268                         g[j][5] = g[j][4] - graph->ackbytes        * graphscale;
269                         // count bytes in the last second
270                         if (host.realtime - graph->time < 1.0f)
271                                 totalbytes += graph->unreliablebytes + graph->reliablebytes + graph->ackbytes;
272                 }
273                 if(graph->cleartime >= 0)
274                         g[j][6] = 0.5f + 0.5f * (2.0 / M_PI) * atan((M_PI / 2.0) * (graph->cleartime - graph->time));
275                 g[j][1] = bound(0.0f, g[j][1], 1.0f);
276                 g[j][2] = bound(0.0f, g[j][2], 1.0f);
277                 g[j][3] = bound(0.0f, g[j][3], 1.0f);
278                 g[j][4] = bound(0.0f, g[j][4], 1.0f);
279                 g[j][5] = bound(0.0f, g[j][5], 1.0f);
280                 g[j][6] = bound(0.0f, g[j][6], 1.0f);
281         }
282         // render the lines for the graph
283         for (j = 0;j < NETGRAPH_PACKETS;j++)
284         {
285                 a = g[j];
286                 b = g[(j+1)%NETGRAPH_PACKETS];
287                 if (a[0] < 0.0f || b[0] > 1.0f || b[0] < a[0])
288                         continue;
289                 DrawQ_Line(1, graphx + graphwidth * a[0], graphy + graphheight * a[2], graphx + graphwidth * b[0], graphy + graphheight * b[2], 1.0f, 1.0f, 1.0f, 1.0f, 0);
290                 DrawQ_Line(1, graphx + graphwidth * a[0], graphy + graphheight * a[1], graphx + graphwidth * b[0], graphy + graphheight * b[1], 1.0f, 0.0f, 0.0f, 1.0f, 0);
291                 DrawQ_Line(1, graphx + graphwidth * a[0], graphy + graphheight * a[5], graphx + graphwidth * b[0], graphy + graphheight * b[5], 0.0f, 1.0f, 0.0f, 1.0f, 0);
292                 DrawQ_Line(1, graphx + graphwidth * a[0], graphy + graphheight * a[4], graphx + graphwidth * b[0], graphy + graphheight * b[4], 1.0f, 1.0f, 1.0f, 1.0f, 0);
293                 DrawQ_Line(1, graphx + graphwidth * a[0], graphy + graphheight * a[3], graphx + graphwidth * b[0], graphy + graphheight * b[3], 1.0f, 0.5f, 0.0f, 1.0f, 0);
294                 DrawQ_Line(1, graphx + graphwidth * a[0], graphy + graphheight * a[6], graphx + graphwidth * b[0], graphy + graphheight * b[6], 0.0f, 0.0f, 1.0f, 1.0f, 0);
295         }
296         x = graphx;
297         y = graphy + graphheight;
298         dpsnprintf(bytesstring, sizeof(bytesstring), "%i", totalbytes);
299         DrawQ_String(x, y, label      , 0, textsize, textsize, 1.0f, 1.0f, 1.0f, 1.0f, 0, NULL, false, FONT_DEFAULT);y += textsize;
300         DrawQ_String(x, y, bytesstring, 0, textsize, textsize, 1.0f, 1.0f, 1.0f, 1.0f, 0, NULL, false, FONT_DEFAULT);y += textsize;
301 }
302
303 /*
304 ==============
305 SCR_DrawNetGraph
306 ==============
307 */
308 static void SCR_DrawNetGraph (void)
309 {
310         int i, separator1, separator2, graphwidth, graphheight, netgraph_x, netgraph_y, textsize, index, netgraphsperrow, graphlimit;
311         float graphscale;
312         netconn_t *c;
313         char vabuf[1024];
314
315         if (cls.state != ca_connected)
316                 return;
317         if (!cls.netcon)
318                 return;
319         if (!net_graph.integer)
320                 return;
321
322         separator1 = 2;
323         separator2 = 4;
324         textsize = 8;
325         graphwidth = 120;
326         graphheight = 70;
327         graphscale = 1.0f / 1500.0f;
328         graphlimit = cl_rate.integer;
329
330         netgraphsperrow = (vid_conwidth.integer + separator2) / (graphwidth * 2 + separator1 + separator2);
331         netgraphsperrow = max(netgraphsperrow, 1);
332
333         index = 0;
334         netgraph_x = (vid_conwidth.integer + separator2) - (1 + (index % netgraphsperrow)) * (graphwidth * 2 + separator1 + separator2);
335         netgraph_y = (vid_conheight.integer - 48 - sbar_info_pos.integer + separator2) - (1 + (index / netgraphsperrow)) * (graphheight + textsize + separator2);
336         c = cls.netcon;
337         SCR_DrawNetGraph_DrawGraph(netgraph_x                          , netgraph_y, graphwidth, graphheight, graphscale, graphlimit, "incoming", textsize, c->incoming_packetcounter, c->incoming_netgraph);
338         SCR_DrawNetGraph_DrawGraph(netgraph_x + graphwidth + separator1, netgraph_y, graphwidth, graphheight, graphscale, graphlimit, "outgoing", textsize, c->outgoing_packetcounter, c->outgoing_netgraph);
339         index++;
340
341         if (sv.active && net_graph.integer >= 2)
342         {
343                 for (i = 0;i < svs.maxclients;i++)
344                 {
345                         c = svs.clients[i].netconnection;
346                         if (!c)
347                                 continue;
348                         netgraph_x = (vid_conwidth.integer + separator2) - (1 + (index % netgraphsperrow)) * (graphwidth * 2 + separator1 + separator2);
349                         netgraph_y = (vid_conheight.integer - 48 + separator2) - (1 + (index / netgraphsperrow)) * (graphheight + textsize + separator2);
350                         SCR_DrawNetGraph_DrawGraph(netgraph_x                          , netgraph_y, graphwidth, graphheight, graphscale, graphlimit, va(vabuf, sizeof(vabuf), "%s", svs.clients[i].name), textsize, c->outgoing_packetcounter, c->outgoing_netgraph);
351                         SCR_DrawNetGraph_DrawGraph(netgraph_x + graphwidth + separator1, netgraph_y, graphwidth, graphheight, graphscale, graphlimit, ""                           , textsize, c->incoming_packetcounter, c->incoming_netgraph);
352                         index++;
353                 }
354         }
355 }
356
357 /*
358 ==============
359 SCR_DrawTurtle
360 ==============
361 */
362 static void SCR_DrawTurtle (void)
363 {
364         static int      count;
365
366         if (cls.state != ca_connected)
367                 return;
368
369         if (!scr_showturtle.integer)
370                 return;
371
372         if (cl.realframetime < 0.1)
373         {
374                 count = 0;
375                 return;
376         }
377
378         count++;
379         if (count < 3)
380                 return;
381
382         DrawQ_Pic (0, 0, Draw_CachePic ("gfx/turtle"), 0, 0, 1, 1, 1, 1, 0);
383 }
384
385 /*
386 ==============
387 SCR_DrawNet
388 ==============
389 */
390 static void SCR_DrawNet (void)
391 {
392         if (cls.state != ca_connected)
393                 return;
394         if (host.realtime - cl.last_received_message < 0.3)
395                 return;
396         if (cls.demoplayback)
397                 return;
398
399         DrawQ_Pic (64, 0, Draw_CachePic ("gfx/net"), 0, 0, 1, 1, 1, 1, 0);
400 }
401
402 /*
403 ==============
404 DrawPause
405 ==============
406 */
407 static void SCR_DrawPause (void)
408 {
409         cachepic_t      *pic;
410
411         if (cls.state != ca_connected)
412                 return;
413
414         if (!scr_showpause.integer)             // turn off for screenshots
415                 return;
416
417         if (!cl.paused)
418                 return;
419
420         pic = Draw_CachePic ("gfx/pause");
421         DrawQ_Pic ((vid_conwidth.integer - Draw_GetPicWidth(pic))/2, (vid_conheight.integer - Draw_GetPicHeight(pic))/2, pic, 0, 0, 1, 1, 1, 1, 0);
422 }
423
424 /*
425 ==============
426 SCR_DrawBrand
427 ==============
428 */
429 static void SCR_DrawBrand (void)
430 {
431         cachepic_t      *pic;
432         float           x, y;
433
434         if (!scr_showbrand.value)
435                 return;
436
437         pic = Draw_CachePic ("gfx/brand");
438
439         switch ((int)scr_showbrand.value)
440         {
441         case 1: // bottom left
442                 x = 0;
443                 y = vid_conheight.integer - Draw_GetPicHeight(pic);
444                 break;
445         case 2: // bottom centre
446                 x = (vid_conwidth.integer - Draw_GetPicWidth(pic)) / 2;
447                 y = vid_conheight.integer - Draw_GetPicHeight(pic);
448                 break;
449         case 3: // bottom right
450                 x = vid_conwidth.integer - Draw_GetPicWidth(pic);
451                 y = vid_conheight.integer - Draw_GetPicHeight(pic);
452                 break;
453         case 4: // centre right
454                 x = vid_conwidth.integer - Draw_GetPicWidth(pic);
455                 y = (vid_conheight.integer - Draw_GetPicHeight(pic)) / 2;
456                 break;
457         case 5: // top right
458                 x = vid_conwidth.integer - Draw_GetPicWidth(pic);
459                 y = 0;
460                 break;
461         case 6: // top centre
462                 x = (vid_conwidth.integer - Draw_GetPicWidth(pic)) / 2;
463                 y = 0;
464                 break;
465         case 7: // top left
466                 x = 0;
467                 y = 0;
468                 break;
469         case 8: // centre left
470                 x = 0;
471                 y = (vid_conheight.integer - Draw_GetPicHeight(pic)) / 2;
472                 break;
473         default:
474                 return;
475         }
476
477         DrawQ_Pic (x, y, pic, 0, 0, 1, 1, 1, 1, 0);
478 }
479
480 /*
481 ==============
482 SCR_DrawQWDownload
483 ==============
484 */
485 static int SCR_DrawQWDownload(int offset)
486 {
487         // sync with SCR_InfobarHeight
488         int len;
489         float x, y;
490         float size = scr_infobar_height.value;
491         char temp[256];
492
493         if (!cls.qw_downloadname[0])
494         {
495                 cls.qw_downloadspeedrate = 0;
496                 cls.qw_downloadspeedtime = host.realtime;
497                 cls.qw_downloadspeedcount = 0;
498                 return 0;
499         }
500         if (host.realtime >= cls.qw_downloadspeedtime + 1)
501         {
502                 cls.qw_downloadspeedrate = cls.qw_downloadspeedcount;
503                 cls.qw_downloadspeedtime = host.realtime;
504                 cls.qw_downloadspeedcount = 0;
505         }
506         if (cls.protocol == PROTOCOL_QUAKEWORLD)
507                 dpsnprintf(temp, sizeof(temp), "Downloading %s %3i%% (%i) at %i bytes/s", cls.qw_downloadname, cls.qw_downloadpercent, cls.qw_downloadmemorycursize, cls.qw_downloadspeedrate);
508         else
509                 dpsnprintf(temp, sizeof(temp), "Downloading %s %3i%% (%i/%i) at %i bytes/s", cls.qw_downloadname, cls.qw_downloadpercent, cls.qw_downloadmemorycursize, cls.qw_downloadmemorymaxsize, cls.qw_downloadspeedrate);
510         len = (int)strlen(temp);
511         x = (vid_conwidth.integer - DrawQ_TextWidth(temp, len, size, size, true, FONT_INFOBAR)) / 2;
512         y = vid_conheight.integer - size - offset;
513         DrawQ_Fill(0, y, vid_conwidth.integer, size, 0, 0, 0, cls.signon == SIGNONS ? 0.5 : 1, 0);
514         DrawQ_String(x, y, temp, len, size, size, 1, 1, 1, 1, 0, NULL, true, FONT_INFOBAR);
515         return size;
516 }
517 /*
518 ==============
519 SCR_DrawInfobarString
520 ==============
521 */
522 static int SCR_DrawInfobarString(int offset)
523 {
524         int len;
525         float x, y;
526         float size = scr_infobar_height.value;
527
528         len = (int)strlen(scr_infobarstring);
529         x = (vid_conwidth.integer - DrawQ_TextWidth(scr_infobarstring, len, size, size, false, FONT_INFOBAR)) / 2;
530         y = vid_conheight.integer - size - offset;
531         DrawQ_Fill(0, y, vid_conwidth.integer, size, 0, 0, 0, cls.signon == SIGNONS ? 0.5 : 1, 0);
532         DrawQ_String(x, y, scr_infobarstring, len, size, size, 1, 1, 1, 1, 0, NULL, false, FONT_INFOBAR);
533         return size;
534 }
535
536 /*
537 ==============
538 SCR_DrawCurlDownload
539 ==============
540 */
541 static int SCR_DrawCurlDownload(int offset)
542 {
543         // sync with SCR_InfobarHeight
544         int len;
545         int nDownloads;
546         int i;
547         float x, y;
548         float size = scr_infobar_height.value;
549         Curl_downloadinfo_t *downinfo;
550         char temp[256];
551         char addinfobuf[128];
552         const char *addinfo;
553
554         downinfo = Curl_GetDownloadInfo(&nDownloads, &addinfo, addinfobuf, sizeof(addinfobuf));
555         if(!downinfo)
556                 return 0;
557
558         y = vid_conheight.integer - size * nDownloads - offset;
559
560         if(addinfo)
561         {
562                 len = (int)strlen(addinfo);
563                 x = (vid_conwidth.integer - DrawQ_TextWidth(addinfo, len, size, size, true, FONT_INFOBAR)) / 2;
564                 DrawQ_Fill(0, y - size, vid_conwidth.integer, size, 1, 1, 1, cls.signon == SIGNONS ? 0.8 : 1, 0);
565                 DrawQ_String(x, y - size, addinfo, len, size, size, 0, 0, 0, 1, 0, NULL, true, FONT_INFOBAR);
566         }
567
568         for(i = 0; i != nDownloads; ++i)
569         {
570                 if(downinfo[i].queued)
571                         dpsnprintf(temp, sizeof(temp), "Still in queue: %s", downinfo[i].filename);
572                 else if(downinfo[i].progress <= 0)
573                         dpsnprintf(temp, sizeof(temp), "Downloading %s ...  ???.?%% @ %.1f KiB/s", downinfo[i].filename, downinfo[i].speed / 1024.0);
574                 else
575                         dpsnprintf(temp, sizeof(temp), "Downloading %s ...  %5.1f%% @ %.1f KiB/s", downinfo[i].filename, 100.0 * downinfo[i].progress, downinfo[i].speed / 1024.0);
576                 len = (int)strlen(temp);
577                 x = (vid_conwidth.integer - DrawQ_TextWidth(temp, len, size, size, true, FONT_INFOBAR)) / 2;
578                 DrawQ_Fill(0, y + i * size, vid_conwidth.integer, size, 0, 0, 0, cls.signon == SIGNONS ? 0.5 : 1, 0);
579                 DrawQ_String(x, y + i * size, temp, len, size, size, 1, 1, 1, 1, 0, NULL, true, FONT_INFOBAR);
580         }
581
582         Z_Free(downinfo);
583
584         return size * (nDownloads + (addinfo ? 1 : 0));
585 }
586
587 /*
588 ==============
589 SCR_DrawInfobar
590 ==============
591 */
592 static void SCR_DrawInfobar(void)
593 {
594         int offset = 0;
595         offset += SCR_DrawQWDownload(offset);
596         offset += SCR_DrawCurlDownload(offset);
597         if(scr_infobartime_off > 0)
598                 offset += SCR_DrawInfobarString(offset);
599         if(offset != scr_con_margin_bottom)
600                 Con_DPrintf("broken console margin calculation: %d != %d\n", offset, scr_con_margin_bottom);
601 }
602
603 static int SCR_InfobarHeight(void)
604 {
605         int offset = 0;
606         Curl_downloadinfo_t *downinfo;
607         const char *addinfo;
608         int nDownloads;
609         char addinfobuf[128];
610
611         if (cl.time > cl.oldtime)
612                 scr_infobartime_off -= cl.time - cl.oldtime;
613         if(scr_infobartime_off > 0)
614                 offset += 1;
615         if(cls.qw_downloadname[0])
616                 offset += 1;
617
618         downinfo = Curl_GetDownloadInfo(&nDownloads, &addinfo, addinfobuf, sizeof(addinfobuf));
619         if(downinfo)
620         {
621                 offset += (nDownloads + (addinfo ? 1 : 0));
622                 Z_Free(downinfo);
623         }
624         offset *= scr_infobar_height.value;
625
626         return offset;
627 }
628
629 /*
630 ==============
631 SCR_InfoBar_f
632 ==============
633 */
634 static void SCR_InfoBar_f(cmd_state_t *cmd)
635 {
636         if(Cmd_Argc(cmd) == 3)
637         {
638                 scr_infobartime_off = atof(Cmd_Argv(cmd, 1));
639                 strlcpy(scr_infobarstring, Cmd_Argv(cmd, 2), sizeof(scr_infobarstring));
640         }
641         else
642         {
643                 Con_Printf("usage:\ninfobar expiretime \"string\"\n");
644         }
645 }
646 //=============================================================================
647
648 /*
649 ==================
650 SCR_SetUpToDrawConsole
651 ==================
652 */
653 static void SCR_SetUpToDrawConsole (void)
654 {
655         // lines of console to display
656         float conlines;
657 #ifdef CONFIG_MENU
658         static int framecounter = 0;
659 #endif
660
661         Con_CheckResize ();
662
663 #ifdef CONFIG_MENU
664         if (scr_menuforcewhiledisconnected.integer && key_dest == key_game && cls.state == ca_disconnected)
665         {
666                 if (framecounter >= 2)
667                         MR_ToggleMenu(1);
668                 else
669                         framecounter++;
670         }
671         else
672                 framecounter = 0;
673 #endif
674
675         if (scr_conforcewhiledisconnected.integer >= 2 && key_dest == key_game && cls.signon != SIGNONS)
676                 key_consoleactive |= KEY_CONSOLEACTIVE_FORCED;
677         else if (scr_conforcewhiledisconnected.integer >= 1 && key_dest == key_game && cls.signon != SIGNONS && !sv.active)
678                 key_consoleactive |= KEY_CONSOLEACTIVE_FORCED;
679         else
680                 key_consoleactive &= ~KEY_CONSOLEACTIVE_FORCED;
681
682 // decide on the height of the console
683         if (key_consoleactive & KEY_CONSOLEACTIVE_USER)
684                 conlines = vid_conheight.integer/2;     // half screen
685         else
686                 conlines = 0;                           // none visible
687
688         scr_con_current = conlines;
689 }
690
691 /*
692 ==================
693 SCR_DrawConsole
694 ==================
695 */
696 void SCR_DrawConsole (void)
697 {
698         scr_con_margin_bottom = SCR_InfobarHeight();
699         if (key_consoleactive & KEY_CONSOLEACTIVE_FORCED)
700         {
701                 // full screen
702                 Con_DrawConsole (vid_conheight.integer - scr_con_margin_bottom);
703         }
704         else if (scr_con_current)
705                 Con_DrawConsole (min((int)scr_con_current, vid_conheight.integer - scr_con_margin_bottom));
706         else
707                 con_vislines = 0;
708 }
709
710 qbool scr_loading = false;
711
712 /*
713 ===============
714 SCR_BeginLoadingPlaque
715
716 ================
717 */
718 void SCR_BeginLoadingPlaque (qbool startup)
719 {
720         scr_loading = true;
721         SCR_UpdateLoadingScreen(false, startup);
722 }
723
724 void SCR_EndLoadingPlaque(void)
725 {
726         scr_loading = false;
727 }
728
729 //=============================================================================
730
731 /*
732 =================
733 SCR_SizeUp_f
734
735 Keybinding command
736 =================
737 */
738 static void SCR_SizeUp_f(cmd_state_t *cmd)
739 {
740         Cvar_SetValueQuick(&scr_viewsize, scr_viewsize.value + 10);
741 }
742
743
744 /*
745 =================
746 SCR_SizeDown_f
747
748 Keybinding command
749 =================
750 */
751 static void SCR_SizeDown_f(cmd_state_t *cmd)
752 {
753         Cvar_SetValueQuick(&scr_viewsize, scr_viewsize.value - 10);
754 }
755
756 #ifdef CONFIG_VIDEO_CAPTURE
757 void SCR_CaptureVideo_EndVideo(void);
758 #endif
759 void CL_Screen_Shutdown(void)
760 {
761 #ifdef CONFIG_VIDEO_CAPTURE
762         SCR_CaptureVideo_EndVideo();
763 #endif
764 }
765
766 void CL_Screen_Init(void)
767 {
768         int i;
769         Cvar_RegisterVariable (&scr_fov);
770         Cvar_RegisterVariable (&scr_viewsize);
771         Cvar_RegisterVariable (&scr_conalpha);
772         Cvar_RegisterVariable (&scr_conalphafactor);
773         Cvar_RegisterVariable (&scr_conalpha2factor);
774         Cvar_RegisterVariable (&scr_conalpha3factor);
775         Cvar_RegisterVariable (&scr_conscroll_x);
776         Cvar_RegisterVariable (&scr_conscroll_y);
777         Cvar_RegisterVariable (&scr_conscroll2_x);
778         Cvar_RegisterVariable (&scr_conscroll2_y);
779         Cvar_RegisterVariable (&scr_conscroll3_x);
780         Cvar_RegisterVariable (&scr_conscroll3_y);
781         Cvar_RegisterVariable (&scr_conbrightness);
782         Cvar_RegisterVariable (&scr_conforcewhiledisconnected);
783 #ifdef CONFIG_MENU
784         Cvar_RegisterVariable (&scr_menuforcewhiledisconnected);
785 #endif
786         Cvar_RegisterVariable (&scr_loadingscreen_background);
787         Cvar_RegisterVariable (&scr_loadingscreen_scale);
788         Cvar_RegisterVariable (&scr_loadingscreen_scale_base);
789         Cvar_RegisterVariable (&scr_loadingscreen_scale_limit);
790         Cvar_RegisterVariable (&scr_loadingscreen_picture);
791         Cvar_RegisterVariable (&scr_loadingscreen_count);
792         Cvar_RegisterVariable (&scr_loadingscreen_firstforstartup);
793         Cvar_RegisterVariable (&scr_loadingscreen_barcolor);
794         Cvar_RegisterVariable (&scr_loadingscreen_barheight);
795         Cvar_RegisterVariable (&scr_loadingscreen_maxfps);
796         Cvar_RegisterVariable (&scr_infobar_height);
797         Cvar_RegisterVariable (&scr_showram);
798         Cvar_RegisterVariable (&scr_showturtle);
799         Cvar_RegisterVariable (&scr_showpause);
800         Cvar_RegisterVariable (&scr_showbrand);
801         Cvar_RegisterVariable (&scr_centertime);
802         Cvar_RegisterVariable (&scr_printspeed);
803         Cvar_RegisterVariable (&vid_conwidth);
804         Cvar_RegisterVariable (&vid_conheight);
805         Cvar_RegisterVariable (&vid_pixelheight);
806         Cvar_RegisterVariable (&vid_conwidthauto);
807         Cvar_RegisterVariable (&scr_screenshot_jpeg);
808         Cvar_RegisterVariable (&scr_screenshot_jpeg_quality);
809         Cvar_RegisterVariable (&scr_screenshot_png);
810         Cvar_RegisterVariable (&scr_screenshot_gammaboost);
811         Cvar_RegisterVariable (&scr_screenshot_name_in_mapdir);
812         Cvar_RegisterVariable (&scr_screenshot_alpha);
813         Cvar_RegisterVariable (&scr_screenshot_timestamp);
814 #ifdef CONFIG_VIDEO_CAPTURE
815         Cvar_RegisterVariable (&cl_capturevideo);
816         Cvar_RegisterVariable (&cl_capturevideo_demo_stop);
817         Cvar_RegisterVariable (&cl_capturevideo_printfps);
818         Cvar_RegisterVariable (&cl_capturevideo_width);
819         Cvar_RegisterVariable (&cl_capturevideo_height);
820         Cvar_RegisterVariable (&cl_capturevideo_realtime);
821         Cvar_RegisterVariable (&cl_capturevideo_fps);
822         Cvar_RegisterVariable (&cl_capturevideo_nameformat);
823         Cvar_RegisterVariable (&cl_capturevideo_number);
824         Cvar_RegisterVariable (&cl_capturevideo_ogg);
825         Cvar_RegisterVariable (&cl_capturevideo_framestep);
826 #endif
827         Cvar_RegisterVariable (&r_letterbox);
828         Cvar_RegisterVariable(&r_stereo_separation);
829         Cvar_RegisterVariable(&r_stereo_sidebyside);
830         Cvar_RegisterVariable(&r_stereo_horizontal);
831         Cvar_RegisterVariable(&r_stereo_vertical);
832         Cvar_RegisterVariable(&r_stereo_redblue);
833         Cvar_RegisterVariable(&r_stereo_redcyan);
834         Cvar_RegisterVariable(&r_stereo_redgreen);
835         Cvar_RegisterVariable(&r_stereo_angle);
836         Cvar_RegisterVariable(&scr_stipple);
837         Cvar_RegisterVariable(&scr_refresh);
838         Cvar_RegisterVariable(&net_graph);
839         Cvar_RegisterAlias(&net_graph, "shownetgraph");
840         Cvar_RegisterVariable(&cl_demo_mousegrab);
841         Cvar_RegisterVariable(&timedemo_screenshotframelist);
842         Cvar_RegisterVariable(&vid_touchscreen_outlinealpha);
843         Cvar_RegisterVariable(&vid_touchscreen_overlayalpha);
844         Cvar_RegisterVariable(&r_speeds_graph);
845         for (i = 0;i < (int)(sizeof(r_speeds_graph_filter)/sizeof(r_speeds_graph_filter[0]));i++)
846                 Cvar_RegisterVariable(&r_speeds_graph_filter[i]);
847         Cvar_RegisterVariable(&r_speeds_graph_length);
848         Cvar_RegisterVariable(&r_speeds_graph_seconds);
849         Cvar_RegisterVariable(&r_speeds_graph_x);
850         Cvar_RegisterVariable(&r_speeds_graph_y);
851         Cvar_RegisterVariable(&r_speeds_graph_width);
852         Cvar_RegisterVariable(&r_speeds_graph_height);
853         Cvar_RegisterVariable(&r_speeds_graph_maxtimedelta);
854         Cvar_RegisterVariable(&r_speeds_graph_maxdefault);
855
856         // if we want no console, turn it off here too
857         if (Sys_CheckParm ("-noconsole"))
858                 Cvar_SetQuick(&scr_conforcewhiledisconnected, "0");
859
860         Cmd_AddCommand(CF_CLIENT, "sizeup",SCR_SizeUp_f, "increase view size (increases viewsize cvar)");
861         Cmd_AddCommand(CF_CLIENT, "sizedown",SCR_SizeDown_f, "decrease view size (decreases viewsize cvar)");
862         Cmd_AddCommand(CF_CLIENT, "screenshot",SCR_ScreenShot_f, "takes a screenshot of the next rendered frame");
863         Cmd_AddCommand(CF_CLIENT, "envmap", R_Envmap_f, "render a cubemap (skybox) of the current scene");
864         Cmd_AddCommand(CF_CLIENT, "infobar", SCR_InfoBar_f, "display a text in the infobar (usage: infobar expiretime string)");
865
866 #ifdef CONFIG_VIDEO_CAPTURE
867         SCR_CaptureVideo_Ogg_Init();
868 #endif
869
870         scr_initialized = true;
871 }
872
873 /*
874 ==================
875 SCR_ScreenShot_f
876 ==================
877 */
878 void SCR_ScreenShot_f(cmd_state_t *cmd)
879 {
880         static int shotnumber;
881         static char old_prefix_name[MAX_QPATH];
882         char prefix_name[MAX_QPATH];
883         char filename[MAX_QPATH];
884         unsigned char *buffer1;
885         unsigned char *buffer2;
886         qbool jpeg = (scr_screenshot_jpeg.integer != 0);
887         qbool png = (scr_screenshot_png.integer != 0) && !jpeg;
888         char vabuf[1024];
889
890         if (Cmd_Argc(cmd) == 2)
891         {
892                 const char *ext;
893                 strlcpy(filename, Cmd_Argv(cmd, 1), sizeof(filename));
894                 ext = FS_FileExtension(filename);
895                 if (!strcasecmp(ext, "jpg"))
896                 {
897                         jpeg = true;
898                         png = false;
899                 }
900                 else if (!strcasecmp(ext, "tga"))
901                 {
902                         jpeg = false;
903                         png = false;
904                 }
905                 else if (!strcasecmp(ext, "png"))
906                 {
907                         jpeg = false;
908                         png = true;
909                 }
910                 else
911                 {
912                         Con_Printf("screenshot: supplied filename must end in .jpg or .tga or .png\n");
913                         return;
914                 }
915         }
916         else if (scr_screenshot_timestamp.integer)
917         {
918                 int shotnumber100;
919
920                 // TODO maybe make capturevideo and screenshot use similar name patterns?
921                 if (scr_screenshot_name_in_mapdir.integer && cl.worldbasename[0])
922                         dpsnprintf(prefix_name, sizeof(prefix_name), "%s/%s%s", cl.worldbasename, scr_screenshot_name.string, Sys_TimeString("%Y%m%d%H%M%S"));
923                 else
924                         dpsnprintf(prefix_name, sizeof(prefix_name), "%s%s", scr_screenshot_name.string, Sys_TimeString("%Y%m%d%H%M%S"));
925
926                 // find a file name to save it to
927                 for (shotnumber100 = 0;shotnumber100 < 100;shotnumber100++)
928                         if (!FS_SysFileExists(va(vabuf, sizeof(vabuf), "%s/screenshots/%s-%02d.tga", fs_gamedir, prefix_name, shotnumber100))
929                          && !FS_SysFileExists(va(vabuf, sizeof(vabuf), "%s/screenshots/%s-%02d.jpg", fs_gamedir, prefix_name, shotnumber100))
930                          && !FS_SysFileExists(va(vabuf, sizeof(vabuf), "%s/screenshots/%s-%02d.png", fs_gamedir, prefix_name, shotnumber100)))
931                                 break;
932                 if (shotnumber100 >= 100)
933                 {
934                         Con_Print("Couldn't create the image file - already 100 shots taken this second!\n");
935                         return;
936                 }
937
938                 dpsnprintf(filename, sizeof(filename), "screenshots/%s-%02d.%s", prefix_name, shotnumber100, jpeg ? "jpg" : png ? "png" : "tga");
939         }
940         else
941         {
942                 // TODO maybe make capturevideo and screenshot use similar name patterns?
943                 if (scr_screenshot_name_in_mapdir.integer && cl.worldbasename[0])
944                         dpsnprintf(prefix_name, sizeof(prefix_name), "%s/%s", cl.worldbasename, Sys_TimeString(scr_screenshot_name.string));
945                 else
946                         dpsnprintf(prefix_name, sizeof(prefix_name), "%s", Sys_TimeString(scr_screenshot_name.string));
947
948                 // if prefix changed, gamedir or map changed, reset the shotnumber so
949                 // we scan again
950                 // FIXME: should probably do this whenever FS_Rescan or something like that occurs?
951                 if (strcmp(old_prefix_name, prefix_name))
952                 {
953                         dpsnprintf(old_prefix_name, sizeof(old_prefix_name), "%s", prefix_name );
954                         shotnumber = 0;
955                 }
956
957                 // find a file name to save it to
958                 for (;shotnumber < 1000000;shotnumber++)
959                         if (!FS_SysFileExists(va(vabuf, sizeof(vabuf), "%s/screenshots/%s%06d.tga", fs_gamedir, prefix_name, shotnumber))
960                          && !FS_SysFileExists(va(vabuf, sizeof(vabuf), "%s/screenshots/%s%06d.jpg", fs_gamedir, prefix_name, shotnumber))
961                          && !FS_SysFileExists(va(vabuf, sizeof(vabuf), "%s/screenshots/%s%06d.png", fs_gamedir, prefix_name, shotnumber)))
962                                 break;
963                 if (shotnumber >= 1000000)
964                 {
965                         Con_Print("Couldn't create the image file - you already have 1000000 screenshots!\n");
966                         return;
967                 }
968
969                 dpsnprintf(filename, sizeof(filename), "screenshots/%s%06d.%s", prefix_name, shotnumber, jpeg ? "jpg" : png ? "png" : "tga");
970
971                 shotnumber++;
972         }
973
974         buffer1 = (unsigned char *)Mem_Alloc(tempmempool, vid.width * vid.height * 4);
975         buffer2 = (unsigned char *)Mem_Alloc(tempmempool, vid.width * vid.height * (scr_screenshot_alpha.integer ? 4 : 3));
976
977         if (SCR_ScreenShot (filename, buffer1, buffer2, 0, 0, vid.width, vid.height, false, false, false, jpeg, png, true, scr_screenshot_alpha.integer != 0))
978                 Con_Printf("Wrote %s\n", filename);
979         else
980         {
981                 Con_Printf(CON_ERROR "Unable to write %s\n", filename);
982                 if(jpeg || png)
983                 {
984                         if(SCR_ScreenShot (filename, buffer1, buffer2, 0, 0, vid.width, vid.height, false, false, false, false, false, true, scr_screenshot_alpha.integer != 0))
985                         {
986                                 strlcpy(filename + strlen(filename) - 3, "tga", 4);
987                                 Con_Printf("Wrote %s\n", filename);
988                         }
989                 }
990         }
991
992         Mem_Free (buffer1);
993         Mem_Free (buffer2);
994 }
995
996 #ifdef CONFIG_VIDEO_CAPTURE
997 static void SCR_CaptureVideo_BeginVideo(void)
998 {
999         double r, g, b;
1000         unsigned int i;
1001         int width = cl_capturevideo_width.integer, height = cl_capturevideo_height.integer;
1002         if (cls.capturevideo.active)
1003                 return;
1004         memset(&cls.capturevideo, 0, sizeof(cls.capturevideo));
1005         // soundrate is figured out on the first SoundFrame
1006
1007         if(width == 0 && height != 0)
1008                 width = (int) (height * (double)vid.width / ((double)vid.height * vid_pixelheight.value)); // keep aspect
1009         if(width != 0 && height == 0)
1010                 height = (int) (width * ((double)vid.height * vid_pixelheight.value) / (double)vid.width); // keep aspect
1011
1012         if(width < 2 || width > vid.width) // can't scale up
1013                 width = vid.width;
1014         if(height < 2 || height > vid.height) // can't scale up
1015                 height = vid.height;
1016
1017         // ensure it's all even; if not, scale down a little
1018         if(width % 1)
1019                 --width;
1020         if(height % 1)
1021                 --height;
1022
1023         cls.capturevideo.width = width;
1024         cls.capturevideo.height = height;
1025         cls.capturevideo.active = true;
1026         cls.capturevideo.framerate = bound(1, cl_capturevideo_fps.value, 1001) * bound(1, cl_capturevideo_framestep.integer, 64);
1027         cls.capturevideo.framestep = cl_capturevideo_framestep.integer;
1028         cls.capturevideo.soundrate = S_GetSoundRate();
1029         cls.capturevideo.soundchannels = S_GetSoundChannels();
1030         cls.capturevideo.startrealtime = host.realtime;
1031         cls.capturevideo.frame = cls.capturevideo.lastfpsframe = 0;
1032         cls.capturevideo.starttime = cls.capturevideo.lastfpstime = host.realtime;
1033         cls.capturevideo.soundsampleframe = 0;
1034         cls.capturevideo.realtime = cl_capturevideo_realtime.integer != 0;
1035         cls.capturevideo.screenbuffer = (unsigned char *)Mem_Alloc(tempmempool, vid.width * vid.height * 4);
1036         cls.capturevideo.outbuffer = (unsigned char *)Mem_Alloc(tempmempool, width * height * (4+4) + 18);
1037         dpsnprintf(cls.capturevideo.basename, sizeof(cls.capturevideo.basename), "video/%s%03i", Sys_TimeString(cl_capturevideo_nameformat.string), cl_capturevideo_number.integer);
1038         Cvar_SetValueQuick(&cl_capturevideo_number, cl_capturevideo_number.integer + 1);
1039
1040         /*
1041         for (i = 0;i < 256;i++)
1042         {
1043                 unsigned char j = (unsigned char)bound(0, 255*pow(i/255.0, gamma), 255);
1044                 cls.capturevideo.rgbgammatable[0][i] = j;
1045                 cls.capturevideo.rgbgammatable[1][i] = j;
1046                 cls.capturevideo.rgbgammatable[2][i] = j;
1047         }
1048         */
1049 /*
1050 R = Y + 1.4075 * (Cr - 128);
1051 G = Y + -0.3455 * (Cb - 128) + -0.7169 * (Cr - 128);
1052 B = Y + 1.7790 * (Cb - 128);
1053 Y = R *  .299 + G *  .587 + B *  .114;
1054 Cb = R * -.169 + G * -.332 + B *  .500 + 128.;
1055 Cr = R *  .500 + G * -.419 + B * -.0813 + 128.;
1056 */
1057
1058         // identity gamma table
1059         BuildGammaTable16(1.0f, 1.0f, 1.0f, 0.0f, 1.0f, cls.capturevideo.vidramp, 256);
1060         BuildGammaTable16(1.0f, 1.0f, 1.0f, 0.0f, 1.0f, cls.capturevideo.vidramp + 256, 256);
1061         BuildGammaTable16(1.0f, 1.0f, 1.0f, 0.0f, 1.0f, cls.capturevideo.vidramp + 256*2, 256);
1062         if(scr_screenshot_gammaboost.value != 1)
1063         {
1064                 double igamma = 1 / scr_screenshot_gammaboost.value;
1065                 for (i = 0;i < 256 * 3;i++)
1066                         cls.capturevideo.vidramp[i] = (unsigned short) (0.5 + pow(cls.capturevideo.vidramp[i] * (1.0 / 65535.0), igamma) * 65535.0);
1067         }
1068
1069         for (i = 0;i < 256;i++)
1070         {
1071                 r = 255*cls.capturevideo.vidramp[i]/65535.0;
1072                 g = 255*cls.capturevideo.vidramp[i+256]/65535.0;
1073                 b = 255*cls.capturevideo.vidramp[i+512]/65535.0;
1074                 // NOTE: we have to round DOWN here, or integer overflows happen. Sorry for slightly wrong looking colors sometimes...
1075                 // Y weights from RGB
1076                 cls.capturevideo.rgbtoyuvscaletable[0][0][i] = (short)(r *  0.299);
1077                 cls.capturevideo.rgbtoyuvscaletable[0][1][i] = (short)(g *  0.587);
1078                 cls.capturevideo.rgbtoyuvscaletable[0][2][i] = (short)(b *  0.114);
1079                 // Cb weights from RGB
1080                 cls.capturevideo.rgbtoyuvscaletable[1][0][i] = (short)(r * -0.169);
1081                 cls.capturevideo.rgbtoyuvscaletable[1][1][i] = (short)(g * -0.332);
1082                 cls.capturevideo.rgbtoyuvscaletable[1][2][i] = (short)(b *  0.500);
1083                 // Cr weights from RGB
1084                 cls.capturevideo.rgbtoyuvscaletable[2][0][i] = (short)(r *  0.500);
1085                 cls.capturevideo.rgbtoyuvscaletable[2][1][i] = (short)(g * -0.419);
1086                 cls.capturevideo.rgbtoyuvscaletable[2][2][i] = (short)(b * -0.0813);
1087                 // range reduction of YCbCr to valid signal range
1088                 cls.capturevideo.yuvnormalizetable[0][i] = 16 + i * (236-16) / 256;
1089                 cls.capturevideo.yuvnormalizetable[1][i] = 16 + i * (240-16) / 256;
1090                 cls.capturevideo.yuvnormalizetable[2][i] = 16 + i * (240-16) / 256;
1091         }
1092
1093         if (cl_capturevideo_ogg.integer)
1094         {
1095                 if(SCR_CaptureVideo_Ogg_Available())
1096                 {
1097                         SCR_CaptureVideo_Ogg_BeginVideo();
1098                         return;
1099                 }
1100                 else
1101                         Con_Print("cl_capturevideo_ogg: libraries not available. Capturing in AVI instead.\n");
1102         }
1103
1104         SCR_CaptureVideo_Avi_BeginVideo();
1105 }
1106
1107 void SCR_CaptureVideo_EndVideo(void)
1108 {
1109         if (!cls.capturevideo.active)
1110                 return;
1111         cls.capturevideo.active = false;
1112
1113         Con_Printf("Finishing capture of %s.%s (%d frames, %d audio frames)\n", cls.capturevideo.basename, cls.capturevideo.formatextension, cls.capturevideo.frame, cls.capturevideo.soundsampleframe);
1114
1115         if (cls.capturevideo.videofile)
1116         {
1117                 cls.capturevideo.endvideo();
1118         }
1119
1120         if (cls.capturevideo.screenbuffer)
1121         {
1122                 Mem_Free (cls.capturevideo.screenbuffer);
1123                 cls.capturevideo.screenbuffer = NULL;
1124         }
1125
1126         if (cls.capturevideo.outbuffer)
1127         {
1128                 Mem_Free (cls.capturevideo.outbuffer);
1129                 cls.capturevideo.outbuffer = NULL;
1130         }
1131
1132         memset(&cls.capturevideo, 0, sizeof(cls.capturevideo));
1133 }
1134
1135 static void SCR_ScaleDownBGRA(unsigned char *in, int inw, int inh, unsigned char *out, int outw, int outh)
1136 {
1137         // TODO optimize this function
1138
1139         int x, y;
1140         float area;
1141
1142         // memcpy is faster than me
1143         if(inw == outw && inh == outh)
1144         {
1145                 memcpy(out, in, 4 * inw * inh);
1146                 return;
1147         }
1148
1149         // otherwise: a box filter
1150         area = (float)outw * (float)outh / (float)inw / (float)inh;
1151         for(y = 0; y < outh; ++y)
1152         {
1153                 float iny0 =  y    / (float)outh * inh; int iny0_i = (int) floor(iny0);
1154                 float iny1 = (y+1) / (float)outh * inh; int iny1_i = (int) ceil(iny1);
1155                 for(x = 0; x < outw; ++x)
1156                 {
1157                         float inx0 =  x    / (float)outw * inw; int inx0_i = (int) floor(inx0);
1158                         float inx1 = (x+1) / (float)outw * inw; int inx1_i = (int) ceil(inx1);
1159                         float r = 0, g = 0, b = 0, alpha = 0;
1160                         int xx, yy;
1161
1162                         for(yy = iny0_i; yy < iny1_i; ++yy)
1163                         {
1164                                 float ya = min(yy+1, iny1) - max(iny0, yy);
1165                                 for(xx = inx0_i; xx < inx1_i; ++xx)
1166                                 {
1167                                         float a = ya * (min(xx+1, inx1) - max(inx0, xx));
1168                                         r += a * in[4*(xx + inw * yy)+0];
1169                                         g += a * in[4*(xx + inw * yy)+1];
1170                                         b += a * in[4*(xx + inw * yy)+2];
1171                                         alpha += a * in[4*(xx + inw * yy)+3];
1172                                 }
1173                         }
1174
1175                         out[4*(x + outw * y)+0] = (unsigned char) (r * area);
1176                         out[4*(x + outw * y)+1] = (unsigned char) (g * area);
1177                         out[4*(x + outw * y)+2] = (unsigned char) (b * area);
1178                         out[4*(x + outw * y)+3] = (unsigned char) (alpha * area);
1179                 }
1180         }
1181 }
1182
1183 static void SCR_CaptureVideo_VideoFrame(int newframestepframenum)
1184 {
1185         int x = 0, y = 0;
1186         int width = cls.capturevideo.width, height = cls.capturevideo.height;
1187
1188         if(newframestepframenum == cls.capturevideo.framestepframe)
1189                 return;
1190
1191         CHECKGLERROR
1192         // speed is critical here, so do saving as directly as possible
1193
1194         GL_ReadPixelsBGRA(x, y, vid.width, vid.height, cls.capturevideo.screenbuffer);
1195
1196         SCR_ScaleDownBGRA (cls.capturevideo.screenbuffer, vid.width, vid.height, cls.capturevideo.outbuffer, width, height);
1197
1198         cls.capturevideo.videoframes(newframestepframenum - cls.capturevideo.framestepframe);
1199         cls.capturevideo.framestepframe = newframestepframenum;
1200
1201         if(cl_capturevideo_printfps.integer)
1202         {
1203                 char buf[80];
1204                 double t = host.realtime;
1205                 if(t > cls.capturevideo.lastfpstime + 1)
1206                 {
1207                         double fps1 = (cls.capturevideo.frame - cls.capturevideo.lastfpsframe) / (t - cls.capturevideo.lastfpstime + 0.0000001);
1208                         double fps  = (cls.capturevideo.frame                                ) / (t - cls.capturevideo.starttime   + 0.0000001);
1209                         dpsnprintf(buf, sizeof(buf), "capturevideo: (%.1fs) last second %.3ffps, total %.3ffps\n", cls.capturevideo.frame / cls.capturevideo.framerate, fps1, fps);
1210                         Sys_PrintToTerminal(buf);
1211                         cls.capturevideo.lastfpstime = t;
1212                         cls.capturevideo.lastfpsframe = cls.capturevideo.frame;
1213                 }
1214         }
1215 }
1216
1217 void SCR_CaptureVideo_SoundFrame(const portable_sampleframe_t *paintbuffer, size_t length)
1218 {
1219         cls.capturevideo.soundsampleframe += (int)length;
1220         cls.capturevideo.soundframe(paintbuffer, length);
1221 }
1222
1223 static void SCR_CaptureVideo(void)
1224 {
1225         int newframenum;
1226         if (cl_capturevideo.integer)
1227         {
1228                 if (!cls.capturevideo.active)
1229                         SCR_CaptureVideo_BeginVideo();
1230                 if (cls.capturevideo.framerate != cl_capturevideo_fps.value * cl_capturevideo_framestep.integer)
1231                 {
1232                         Con_Printf("You can not change the video framerate while recording a video.\n");
1233                         Cvar_SetValueQuick(&cl_capturevideo_fps, cls.capturevideo.framerate / (double) cl_capturevideo_framestep.integer);
1234                 }
1235                 // for AVI saving we have to make sure that sound is saved before video
1236                 if (cls.capturevideo.soundrate && !cls.capturevideo.soundsampleframe)
1237                         return;
1238                 if (cls.capturevideo.realtime)
1239                 {
1240                         // preserve sound sync by duplicating frames when running slow
1241                         newframenum = (int)((host.realtime - cls.capturevideo.startrealtime) * cls.capturevideo.framerate);
1242                 }
1243                 else
1244                         newframenum = cls.capturevideo.frame + 1;
1245                 // if falling behind more than one second, stop
1246                 if (newframenum - cls.capturevideo.frame > 60 * (int)ceil(cls.capturevideo.framerate))
1247                 {
1248                         Cvar_SetValueQuick(&cl_capturevideo, 0);
1249                         Con_Printf("video saving failed on frame %i, your machine is too slow for this capture speed.\n", cls.capturevideo.frame);
1250                         SCR_CaptureVideo_EndVideo();
1251                         return;
1252                 }
1253                 // write frames
1254                 SCR_CaptureVideo_VideoFrame(newframenum / cls.capturevideo.framestep);
1255                 cls.capturevideo.frame = newframenum;
1256                 if (cls.capturevideo.error)
1257                 {
1258                         Cvar_SetValueQuick(&cl_capturevideo, 0);
1259                         Con_Printf("video saving failed on frame %i, out of disk space? stopping video capture.\n", cls.capturevideo.frame);
1260                         SCR_CaptureVideo_EndVideo();
1261                 }
1262         }
1263         else if (cls.capturevideo.active)
1264                 SCR_CaptureVideo_EndVideo();
1265 }
1266 #endif
1267
1268 /*
1269 ===============
1270 R_Envmap_f
1271
1272 Grab six views for environment mapping tests
1273 ===============
1274 */
1275 struct envmapinfo_s
1276 {
1277         float angles[3];
1278         const char *name;
1279         qbool flipx, flipy, flipdiagonaly;
1280 }
1281 envmapinfo[12] =
1282 {
1283         {{  0,   0, 0}, "rt", false, false, false},
1284         {{  0, 270, 0}, "ft", false, false, false},
1285         {{  0, 180, 0}, "lf", false, false, false},
1286         {{  0,  90, 0}, "bk", false, false, false},
1287         {{-90, 180, 0}, "up",  true,  true, false},
1288         {{ 90, 180, 0}, "dn",  true,  true, false},
1289
1290         {{  0,   0, 0}, "px",  true,  true,  true},
1291         {{  0,  90, 0}, "py", false,  true, false},
1292         {{  0, 180, 0}, "nx", false, false,  true},
1293         {{  0, 270, 0}, "ny",  true, false, false},
1294         {{-90, 180, 0}, "pz", false, false,  true},
1295         {{ 90, 180, 0}, "nz", false, false,  true}
1296 };
1297
1298 static void R_Envmap_f(cmd_state_t *cmd)
1299 {
1300         int j, size;
1301         char filename[MAX_QPATH], basename[MAX_QPATH];
1302         unsigned char *buffer1;
1303         unsigned char *buffer2;
1304         r_rendertarget_t *rt;
1305
1306         if (Cmd_Argc(cmd) != 3)
1307         {
1308                 Con_Print("envmap <basename> <size>: save out 6 cubic environment map images, usable with loadsky, note that size must one of 128, 256, 512, or 1024 and can't be bigger than your current resolution\n");
1309                 return;
1310         }
1311
1312         if(cls.state != ca_connected) {
1313                 Con_Printf("envmap: No map loaded\n");
1314                 return;
1315         }
1316
1317         strlcpy (basename, Cmd_Argv(cmd, 1), sizeof (basename));
1318         size = atoi(Cmd_Argv(cmd, 2));
1319         if (size != 128 && size != 256 && size != 512 && size != 1024)
1320         {
1321                 Con_Print("envmap: size must be one of 128, 256, 512, or 1024\n");
1322                 return;
1323         }
1324         if (size > vid.width || size > vid.height)
1325         {
1326                 Con_Print("envmap: your resolution is not big enough to render that size\n");
1327                 return;
1328         }
1329
1330         r_refdef.envmap = true;
1331
1332         R_UpdateVariables();
1333
1334         r_refdef.view.x = 0;
1335         r_refdef.view.y = 0;
1336         r_refdef.view.z = 0;
1337         r_refdef.view.width = size;
1338         r_refdef.view.height = size;
1339         r_refdef.view.depth = 1;
1340         r_refdef.view.useperspective = true;
1341         r_refdef.view.isoverlay = false;
1342         r_refdef.view.ismain = true;
1343
1344         r_refdef.view.frustum_x = 1; // tan(45 * M_PI / 180.0);
1345         r_refdef.view.frustum_y = 1; // tan(45 * M_PI / 180.0);
1346         r_refdef.view.ortho_x = 90; // abused as angle by VM_CL_R_SetView
1347         r_refdef.view.ortho_y = 90; // abused as angle by VM_CL_R_SetView
1348
1349         buffer1 = (unsigned char *)Mem_Alloc(tempmempool, size * size * 4);
1350         buffer2 = (unsigned char *)Mem_Alloc(tempmempool, size * size * 3);
1351
1352         // TODO: use TEXTYPE_COLORBUFFER16F and output to .exr files as well?
1353         rt = R_RenderTarget_Get(size, size, TEXTYPE_DEPTHBUFFER24STENCIL8, true, TEXTYPE_COLORBUFFER, TEXTYPE_UNUSED, TEXTYPE_UNUSED, TEXTYPE_UNUSED);
1354         CL_UpdateEntityShading();
1355         for (j = 0;j < 12;j++)
1356         {
1357                 dpsnprintf(filename, sizeof(filename), "env/%s%s.tga", basename, envmapinfo[j].name);
1358                 Matrix4x4_CreateFromQuakeEntity(&r_refdef.view.matrix, r_refdef.view.origin[0], r_refdef.view.origin[1], r_refdef.view.origin[2], envmapinfo[j].angles[0], envmapinfo[j].angles[1], envmapinfo[j].angles[2], 1);
1359                 r_refdef.view.quality = 1;
1360                 r_refdef.view.clear = true;
1361                 R_Mesh_Start();
1362                 R_RenderView(rt->fbo, rt->depthtexture, rt->colortexture[0], 0, 0, size, size);
1363                 R_Mesh_Finish();
1364                 SCR_ScreenShot(filename, buffer1, buffer2, 0, vid.height - (r_refdef.view.y + r_refdef.view.height), size, size, envmapinfo[j].flipx, envmapinfo[j].flipy, envmapinfo[j].flipdiagonaly, false, false, false, false);
1365         }
1366
1367         Mem_Free (buffer1);
1368         Mem_Free (buffer2);
1369
1370         r_refdef.envmap = false;
1371 }
1372
1373 //=============================================================================
1374
1375 void SHOWLMP_decodehide(void)
1376 {
1377         int i;
1378         char *lmplabel;
1379         lmplabel = MSG_ReadString(&cl_message, cl_readstring, sizeof(cl_readstring));
1380         for (i = 0;i < cl.num_showlmps;i++)
1381                 if (cl.showlmps[i].isactive && strcmp(cl.showlmps[i].label, lmplabel) == 0)
1382                 {
1383                         cl.showlmps[i].isactive = false;
1384                         return;
1385                 }
1386 }
1387
1388 void SHOWLMP_decodeshow(void)
1389 {
1390         int k;
1391         char lmplabel[256], picname[256];
1392         float x, y;
1393         strlcpy (lmplabel,MSG_ReadString(&cl_message, cl_readstring, sizeof(cl_readstring)), sizeof (lmplabel));
1394         strlcpy (picname, MSG_ReadString(&cl_message, cl_readstring, sizeof(cl_readstring)), sizeof (picname));
1395         if (gamemode == GAME_NEHAHRA) // LadyHavoc: nasty old legacy junk
1396         {
1397                 x = MSG_ReadByte(&cl_message);
1398                 y = MSG_ReadByte(&cl_message);
1399         }
1400         else
1401         {
1402                 x = MSG_ReadShort(&cl_message);
1403                 y = MSG_ReadShort(&cl_message);
1404         }
1405         if (!cl.showlmps || cl.num_showlmps >= cl.max_showlmps)
1406         {
1407                 showlmp_t *oldshowlmps = cl.showlmps;
1408                 cl.max_showlmps += 16;
1409                 cl.showlmps = (showlmp_t *) Mem_Alloc(cls.levelmempool, cl.max_showlmps * sizeof(showlmp_t));
1410                 if (oldshowlmps)
1411                 {
1412                         if (cl.num_showlmps)
1413                                 memcpy(cl.showlmps, oldshowlmps, cl.num_showlmps * sizeof(showlmp_t));
1414                         Mem_Free(oldshowlmps);
1415                 }
1416         }
1417         for (k = 0;k < cl.max_showlmps;k++)
1418                 if (cl.showlmps[k].isactive && !strcmp(cl.showlmps[k].label, lmplabel))
1419                         break;
1420         if (k == cl.max_showlmps)
1421                 for (k = 0;k < cl.max_showlmps;k++)
1422                         if (!cl.showlmps[k].isactive)
1423                                 break;
1424         cl.showlmps[k].isactive = true;
1425         strlcpy (cl.showlmps[k].label, lmplabel, sizeof (cl.showlmps[k].label));
1426         strlcpy (cl.showlmps[k].pic, picname, sizeof (cl.showlmps[k].pic));
1427         cl.showlmps[k].x = x;
1428         cl.showlmps[k].y = y;
1429         cl.num_showlmps = max(cl.num_showlmps, k + 1);
1430 }
1431
1432 void SHOWLMP_drawall(void)
1433 {
1434         int i;
1435         for (i = 0;i < cl.num_showlmps;i++)
1436                 if (cl.showlmps[i].isactive)
1437                         DrawQ_Pic(cl.showlmps[i].x, cl.showlmps[i].y, Draw_CachePic_Flags (cl.showlmps[i].pic, CACHEPICFLAG_NOTPERSISTENT), 0, 0, 1, 1, 1, 1, 0);
1438 }
1439
1440 /*
1441 ==============================================================================
1442
1443                                                 SCREEN SHOTS
1444
1445 ==============================================================================
1446 */
1447
1448 // buffer1: 4*w*h
1449 // buffer2: 3*w*h (or 4*w*h if screenshotting alpha too)
1450 qbool SCR_ScreenShot(char *filename, unsigned char *buffer1, unsigned char *buffer2, int x, int y, int width, int height, qbool flipx, qbool flipy, qbool flipdiagonal, qbool jpeg, qbool png, qbool gammacorrect, qbool keep_alpha)
1451 {
1452         int     indices[4] = {0,1,2,3}; // BGRA
1453         qbool ret;
1454
1455         GL_ReadPixelsBGRA(x, y, width, height, buffer1);
1456
1457         if(gammacorrect && (scr_screenshot_gammaboost.value != 1))
1458         {
1459                 int i;
1460                 double igamma = 1.0 / scr_screenshot_gammaboost.value;
1461                 unsigned short vidramp[256 * 3];
1462                 // identity gamma table
1463                 BuildGammaTable16(1.0f, 1.0f, 1.0f, 0.0f, 1.0f, vidramp, 256);
1464                 BuildGammaTable16(1.0f, 1.0f, 1.0f, 0.0f, 1.0f, vidramp + 256, 256);
1465                 BuildGammaTable16(1.0f, 1.0f, 1.0f, 0.0f, 1.0f, vidramp + 256*2, 256);
1466                 if(scr_screenshot_gammaboost.value != 1)
1467                 {
1468                         for (i = 0;i < 256 * 3;i++)
1469                                 vidramp[i] = (unsigned short) (0.5 + pow(vidramp[i] * (1.0 / 65535.0), igamma) * 65535.0);
1470                 }
1471                 for (i = 0;i < width*height*4;i += 4)
1472                 {
1473                         buffer1[i] = (unsigned char) (vidramp[buffer1[i] + 512] * 255.0 / 65535.0 + 0.5); // B
1474                         buffer1[i+1] = (unsigned char) (vidramp[buffer1[i+1] + 256] * 255.0 / 65535.0 + 0.5); // G
1475                         buffer1[i+2] = (unsigned char) (vidramp[buffer1[i+2]] * 255.0 / 65535.0 + 0.5); // R
1476                         // A
1477                 }
1478         }
1479
1480         if(keep_alpha && !jpeg)
1481         {
1482                 if(!png)
1483                         flipy = !flipy; // TGA: not preflipped
1484                 Image_CopyMux (buffer2, buffer1, width, height, flipx, flipy, flipdiagonal, 4, 4, indices);
1485                 if (png)
1486                         ret = PNG_SaveImage_preflipped (filename, width, height, true, buffer2);
1487                 else
1488                         ret = Image_WriteTGABGRA(filename, width, height, buffer2);
1489         }
1490         else
1491         {
1492                 if(jpeg)
1493                 {
1494                         indices[0] = 2;
1495                         indices[2] = 0; // RGB
1496                 }
1497                 Image_CopyMux (buffer2, buffer1, width, height, flipx, flipy, flipdiagonal, 3, 4, indices);
1498                 if (jpeg)
1499                         ret = JPEG_SaveImage_preflipped (filename, width, height, buffer2);
1500                 else if (png)
1501                         ret = PNG_SaveImage_preflipped (filename, width, height, false, buffer2);
1502                 else
1503                         ret = Image_WriteTGABGR_preflipped (filename, width, height, buffer2);
1504         }
1505
1506         return ret;
1507 }
1508
1509 //=============================================================================
1510
1511 int scr_numtouchscreenareas;
1512 scr_touchscreenarea_t scr_touchscreenareas[128];
1513
1514 static void SCR_DrawTouchscreenOverlay(void)
1515 {
1516         int i;
1517         scr_touchscreenarea_t *a;
1518         cachepic_t *pic;
1519         for (i = 0, a = scr_touchscreenareas;i < scr_numtouchscreenareas;i++, a++)
1520         {
1521                 if (vid_touchscreen_outlinealpha.value > 0 && a->rect[0] >= 0 && a->rect[1] >= 0 && a->rect[2] >= 4 && a->rect[3] >= 4)
1522                 {
1523                         DrawQ_Fill(a->rect[0] +              2, a->rect[1]                 , a->rect[2] - 4,          1    , 1, 1, 1, vid_touchscreen_outlinealpha.value * (0.5f + 0.5f * a->active), 0);
1524                         DrawQ_Fill(a->rect[0] +              1, a->rect[1] +              1, a->rect[2] - 2,          1    , 1, 1, 1, vid_touchscreen_outlinealpha.value * (0.5f + 0.5f * a->active), 0);
1525                         DrawQ_Fill(a->rect[0]                 , a->rect[1] +              2,          2    , a->rect[3] - 2, 1, 1, 1, vid_touchscreen_outlinealpha.value * (0.5f + 0.5f * a->active), 0);
1526                         DrawQ_Fill(a->rect[0] + a->rect[2] - 2, a->rect[1] +              2,          2    , a->rect[3] - 2, 1, 1, 1, vid_touchscreen_outlinealpha.value * (0.5f + 0.5f * a->active), 0);
1527                         DrawQ_Fill(a->rect[0] +              1, a->rect[1] + a->rect[3] - 2, a->rect[2] - 2,          1    , 1, 1, 1, vid_touchscreen_outlinealpha.value * (0.5f + 0.5f * a->active), 0);
1528                         DrawQ_Fill(a->rect[0] +              2, a->rect[1] + a->rect[3] - 1, a->rect[2] - 4,          1    , 1, 1, 1, vid_touchscreen_outlinealpha.value * (0.5f + 0.5f * a->active), 0);
1529                 }
1530                 pic = a->pic ? Draw_CachePic_Flags(a->pic, CACHEPICFLAG_FAILONMISSING) : NULL;
1531                 if (Draw_IsPicLoaded(pic))
1532                         DrawQ_Pic(a->rect[0], a->rect[1], pic, a->rect[2], a->rect[3], 1, 1, 1, vid_touchscreen_overlayalpha.value * (0.5f + 0.5f * a->active), 0);
1533                 if (a->text && a->text[0])
1534                 {
1535                         int textwidth = DrawQ_TextWidth(a->text, 0, a->textheight, a->textheight, false, FONT_CHAT);
1536                         DrawQ_String(a->rect[0] + (a->rect[2] - textwidth) * 0.5f, a->rect[1] + (a->rect[3] - a->textheight) * 0.5f, a->text, 0, a->textheight, a->textheight, 1.0f, 1.0f, 1.0f, vid_touchscreen_overlayalpha.value, 0, NULL, false, FONT_CHAT);
1537                 }
1538         }
1539 }
1540
1541 void R_ClearScreen(qbool fogcolor)
1542 {
1543         float clearcolor[4];
1544         if (scr_screenshot_alpha.integer)
1545                 // clear to transparency (so png screenshots can contain alpha channel, useful for building model pictures)
1546                 Vector4Set(clearcolor, 0.0f, 0.0f, 0.0f, 0.0f);
1547         else
1548                 // clear to opaque black (if we're being composited it might otherwise render as transparent)
1549                 Vector4Set(clearcolor, 0.0f, 0.0f, 0.0f, 1.0f);
1550         if (fogcolor && r_fog_clear.integer)
1551         {
1552                 R_UpdateFog();
1553                 VectorCopy(r_refdef.fogcolor, clearcolor);
1554         }
1555         // clear depth is 1.0
1556         // clear the screen
1557         GL_Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | (vid.stencil ? GL_STENCIL_BUFFER_BIT : 0), clearcolor, 1.0f, 0);
1558 }
1559
1560 int r_stereo_side;
1561 extern cvar_t v_isometric;
1562 extern cvar_t v_isometric_verticalfov;
1563
1564 typedef struct loadingscreenstack_s
1565 {
1566         struct loadingscreenstack_s *prev;
1567         char msg[MAX_QPATH];
1568         float absolute_loading_amount_min; // this corresponds to relative completion 0 of this item
1569         float absolute_loading_amount_len; // this corresponds to relative completion 1 of this item
1570         float relative_completion; // 0 .. 1
1571 }
1572 loadingscreenstack_t;
1573 static loadingscreenstack_t *loadingscreenstack = NULL;
1574 static qbool loadingscreendone = false;
1575 static qbool loadingscreencleared = false;
1576 static float loadingscreenheight = 0;
1577 rtexture_t *loadingscreentexture = NULL;
1578 static float loadingscreentexture_vertex3f[12];
1579 static float loadingscreentexture_texcoord2f[8];
1580 static int loadingscreenpic_number = 0;
1581
1582 static void SCR_DrawLoadingScreen(void);
1583 static void SCR_DrawScreen (void)
1584 {
1585         Draw_Frame();
1586
1587         R_Mesh_Start();
1588
1589         R_UpdateVariables();
1590
1591         // this will be set back to 0 by R_RenderView during CL_VM_UpdateView
1592         r_refdef.draw2dstage = 1;
1593         R_ResetViewRendering2D_Common(0, NULL, NULL, 0, 0, vid.width, vid.height, vid_conwidth.integer, vid_conheight.integer);
1594
1595         // Quake uses clockwise winding, so these are swapped
1596         r_refdef.view.cullface_front = GL_BACK;
1597         r_refdef.view.cullface_back = GL_FRONT;
1598
1599         if (cls.signon == SIGNONS)
1600         {
1601                 float size;
1602
1603                 size = scr_viewsize.value * (1.0 / 100.0);
1604                 size = min(size, 1);
1605
1606                 if (r_stereo_sidebyside.integer)
1607                 {
1608                         r_refdef.view.width = (int)(vid.width * size / 2.5);
1609                         r_refdef.view.height = (int)(vid.height * size / 2.5 * (1 - bound(0, r_letterbox.value, 100) / 100));
1610                         r_refdef.view.depth = 1;
1611                         r_refdef.view.x = (int)((vid.width - r_refdef.view.width * 2.5) * 0.5);
1612                         r_refdef.view.y = (int)((vid.height - r_refdef.view.height)/2);
1613                         r_refdef.view.z = 0;
1614                         if (r_stereo_side)
1615                                 r_refdef.view.x += (int)(r_refdef.view.width * 1.5);
1616                 }
1617                 else if (r_stereo_horizontal.integer)
1618                 {
1619                         r_refdef.view.width = (int)(vid.width * size / 2);
1620                         r_refdef.view.height = (int)(vid.height * size * (1 - bound(0, r_letterbox.value, 100) / 100));
1621                         r_refdef.view.depth = 1;
1622                         r_refdef.view.x = (int)((vid.width - r_refdef.view.width * 2.0)/2);
1623                         r_refdef.view.y = (int)((vid.height - r_refdef.view.height)/2);
1624                         r_refdef.view.z = 0;
1625                         if (r_stereo_side)
1626                                 r_refdef.view.x += (int)(r_refdef.view.width);
1627                 }
1628                 else if (r_stereo_vertical.integer)
1629                 {
1630                         r_refdef.view.width = (int)(vid.width * size);
1631                         r_refdef.view.height = (int)(vid.height * size * (1 - bound(0, r_letterbox.value, 100) / 100) / 2);
1632                         r_refdef.view.depth = 1;
1633                         r_refdef.view.x = (int)((vid.width - r_refdef.view.width)/2);
1634                         r_refdef.view.y = (int)((vid.height - r_refdef.view.height * 2.0)/2);
1635                         r_refdef.view.z = 0;
1636                         if (r_stereo_side)
1637                                 r_refdef.view.y += (int)(r_refdef.view.height);
1638                 }
1639                 else
1640                 {
1641                         r_refdef.view.width = (int)(vid.width * size);
1642                         r_refdef.view.height = (int)(vid.height * size * (1 - bound(0, r_letterbox.value, 100) / 100));
1643                         r_refdef.view.depth = 1;
1644                         r_refdef.view.x = (int)((vid.width - r_refdef.view.width)/2);
1645                         r_refdef.view.y = (int)((vid.height - r_refdef.view.height)/2);
1646                         r_refdef.view.z = 0;
1647                 }
1648
1649                 // LadyHavoc: viewzoom (zoom in for sniper rifles, etc)
1650                 // LadyHavoc: this is designed to produce widescreen fov values
1651                 // when the screen is wider than 4/3 width/height aspect, to do
1652                 // this it simply assumes the requested fov is the vertical fov
1653                 // for a 4x3 display, if the ratio is not 4x3 this makes the fov
1654                 // higher/lower according to the ratio
1655                 r_refdef.view.useperspective = true;
1656                 r_refdef.view.frustum_y = tan(scr_fov.value * M_PI / 360.0) * (3.0 / 4.0) * cl.viewzoom;
1657                 r_refdef.view.frustum_x = r_refdef.view.frustum_y * (float)r_refdef.view.width / (float)r_refdef.view.height / vid_pixelheight.value;
1658
1659                 r_refdef.view.frustum_x *= r_refdef.frustumscale_x;
1660                 r_refdef.view.frustum_y *= r_refdef.frustumscale_y;
1661                 r_refdef.view.ortho_x = atan(r_refdef.view.frustum_x) * (360.0 / M_PI); // abused as angle by VM_CL_R_SetView
1662                 r_refdef.view.ortho_y = atan(r_refdef.view.frustum_y) * (360.0 / M_PI); // abused as angle by VM_CL_R_SetView
1663
1664                 r_refdef.view.ismain = true;
1665
1666                 // if CSQC is loaded, it is required to provide the CSQC_UpdateView function,
1667                 // and won't render a view if it does not call that.
1668                 if (cl.csqc_loaded)
1669                         CL_VM_UpdateView(r_stereo_side ? 0.0 : max(0.0, cl.time - cl.oldtime));
1670                 else
1671                 {
1672                         // Prepare the scene mesh for rendering - this is lightning beams and other effects rendered as normal surfaces
1673                         CL_MeshEntities_Scene_FinalizeRenderEntity();
1674
1675                         CL_UpdateEntityShading();
1676                         R_RenderView(0, NULL, NULL, r_refdef.view.x, r_refdef.view.y, r_refdef.view.width, r_refdef.view.height);
1677                 }
1678         }
1679         else if (key_dest == key_game && key_consoleactive == 0 && (cls.state == ca_connected || cls.connect_trying))
1680         {
1681                 // draw the loading screen for a while if we're still connecting and not forcing the console or menu to show up
1682                 char temp[64];
1683                 if (cls.signon > 0)
1684                         SCR_PushLoadingScreen(va(temp, sizeof(temp), "Connect: Signon stage %i of %i", cls.signon, SIGNONS), 1.0);
1685                 else if (cls.connect_remainingtries > 0)
1686                         SCR_PushLoadingScreen(va(temp, sizeof(temp), "Connect: Trying...  %i", cls.connect_remainingtries), 1.0);
1687                 else
1688                         SCR_PushLoadingScreen(va(temp, sizeof(temp), "Connect: Waiting %i seconds for reply", 10 + cls.connect_remainingtries), 1.0);
1689                 SCR_DrawLoadingScreen();
1690                 SCR_PopLoadingScreen(false);
1691         }
1692
1693         // Don't apply debugging stuff like r_showsurfaces to the UI
1694         r_refdef.view.showdebug = false;
1695
1696         if (!r_stereo_sidebyside.integer && !r_stereo_horizontal.integer && !r_stereo_vertical.integer)
1697         {
1698                 r_refdef.view.width = vid.width;
1699                 r_refdef.view.height = vid.height;
1700                 r_refdef.view.depth = 1;
1701                 r_refdef.view.x = 0;
1702                 r_refdef.view.y = 0;
1703                 r_refdef.view.z = 0;
1704                 r_refdef.view.useperspective = false;
1705         }
1706
1707         if (cls.timedemo && cls.td_frames > 0 && timedemo_screenshotframelist.string && timedemo_screenshotframelist.string[0])
1708         {
1709                 const char *t;
1710                 int framenum;
1711                 t = timedemo_screenshotframelist.string;
1712                 while (*t)
1713                 {
1714                         while (*t == ' ')
1715                                 t++;
1716                         if (!*t)
1717                                 break;
1718                         framenum = atof(t);
1719                         if (framenum == cls.td_frames)
1720                                 break;
1721                         while (*t && *t != ' ')
1722                                 t++;
1723                 }
1724                 if (*t)
1725                 {
1726                         // we need to take a screenshot of this frame...
1727                         char filename[MAX_QPATH];
1728                         unsigned char *buffer1;
1729                         unsigned char *buffer2;
1730                         dpsnprintf(filename, sizeof(filename), "timedemoscreenshots/%s%06d.tga", cls.demoname, cls.td_frames);
1731                         buffer1 = (unsigned char *)Mem_Alloc(tempmempool, vid.width * vid.height * 4);
1732                         buffer2 = (unsigned char *)Mem_Alloc(tempmempool, vid.width * vid.height * 3);
1733                         SCR_ScreenShot(filename, buffer1, buffer2, 0, 0, vid.width, vid.height, false, false, false, false, false, true, false);
1734                         Mem_Free(buffer1);
1735                         Mem_Free(buffer2);
1736                 }
1737         }
1738
1739         // draw 2D stuff
1740
1741         // Don't flicker when starting a local server.
1742         if(scr_loading && !loadingscreenstack && ((!cls.signon && !sv.active) || (cls.signon == SIGNONS)))
1743                 SCR_EndLoadingPlaque();
1744
1745         if(!scr_con_current && !(key_consoleactive & KEY_CONSOLEACTIVE_FORCED))
1746                 if ((key_dest == key_game || key_dest == key_message) && !r_letterbox.value && !scr_loading)
1747                         Con_DrawNotify ();      // only draw notify in game
1748
1749         if (cl.islocalgame && (key_dest != key_game || key_consoleactive))
1750                 host.paused = true;
1751         else
1752                 host.paused = false;
1753
1754         if (cls.signon == SIGNONS)
1755         {
1756                 SCR_DrawNet ();
1757                 SCR_DrawTurtle ();
1758                 SCR_DrawPause ();
1759                 if (!r_letterbox.value)
1760                         Sbar_Draw();
1761                 SHOWLMP_drawall();
1762                 SCR_CheckDrawCenterString();
1763         }
1764         SCR_DrawNetGraph ();
1765 #ifdef CONFIG_MENU
1766         if(!scr_loading)
1767                 MR_Draw();
1768 #endif
1769         CL_DrawVideo();
1770         R_Shadow_EditLights_DrawSelectedLightProperties();
1771
1772         SCR_DrawConsole();
1773         
1774         if(!scr_loading) {
1775                 SCR_DrawBrand();
1776
1777                 SCR_DrawInfobar();
1778
1779                 SCR_DrawTouchscreenOverlay();
1780         }
1781         if (r_timereport_active)
1782                 R_TimeReport("2d");
1783
1784         R_TimeReport_EndFrame();
1785         R_TimeReport_BeginFrame();
1786         
1787         if(!scr_loading)
1788                 Sbar_ShowFPS();
1789
1790         DrawQ_Finish();
1791
1792         R_Mesh_Finish();
1793         R_RenderTarget_FreeUnused(false);
1794 }
1795
1796 static void SCR_ClearLoadingScreenTexture(void)
1797 {
1798         if(loadingscreentexture)
1799                 R_FreeTexture(loadingscreentexture);
1800         loadingscreentexture = NULL;
1801 }
1802
1803 extern rtexturepool_t *r_main_texturepool;
1804 static void SCR_SetLoadingScreenTexture(void)
1805 {
1806         int w, h;
1807         float loadingscreentexture_w;
1808         float loadingscreentexture_h;
1809
1810         SCR_ClearLoadingScreenTexture();
1811
1812         w = vid.width; h = vid.height;
1813         loadingscreentexture_w = loadingscreentexture_h = 1;
1814
1815         loadingscreentexture = R_LoadTexture2D(r_main_texturepool, "loadingscreentexture", w, h, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_FORCENEAREST | TEXF_CLAMP, -1, NULL);
1816         R_Mesh_CopyToTexture(loadingscreentexture, 0, 0, 0, 0, vid.width, vid.height);
1817
1818         loadingscreentexture_vertex3f[2] = loadingscreentexture_vertex3f[5] = loadingscreentexture_vertex3f[8] = loadingscreentexture_vertex3f[11] = 0;
1819         loadingscreentexture_vertex3f[0] = loadingscreentexture_vertex3f[9] = 0;
1820         loadingscreentexture_vertex3f[1] = loadingscreentexture_vertex3f[4] = 0;
1821         loadingscreentexture_vertex3f[3] = loadingscreentexture_vertex3f[6] = vid_conwidth.integer;
1822         loadingscreentexture_vertex3f[7] = loadingscreentexture_vertex3f[10] = vid_conheight.integer;
1823         loadingscreentexture_texcoord2f[0] = 0;loadingscreentexture_texcoord2f[1] = loadingscreentexture_h;
1824         loadingscreentexture_texcoord2f[2] = loadingscreentexture_w;loadingscreentexture_texcoord2f[3] = loadingscreentexture_h;
1825         loadingscreentexture_texcoord2f[4] = loadingscreentexture_w;loadingscreentexture_texcoord2f[5] = 0;
1826         loadingscreentexture_texcoord2f[6] = 0;loadingscreentexture_texcoord2f[7] = 0;
1827 }
1828
1829 void SCR_UpdateLoadingScreenIfShown(void)
1830 {
1831         if(loadingscreendone)
1832                 SCR_UpdateLoadingScreen(loadingscreencleared, false);
1833 }
1834
1835 void SCR_PushLoadingScreen (const char *msg, float len_in_parent)
1836 {
1837         loadingscreenstack_t *s = (loadingscreenstack_t *) Z_Malloc(sizeof(loadingscreenstack_t));
1838         s->prev = loadingscreenstack;
1839         loadingscreenstack = s;
1840
1841         strlcpy(s->msg, msg, sizeof(s->msg));
1842         s->relative_completion = 0;
1843
1844         if(s->prev)
1845         {
1846                 s->absolute_loading_amount_min = s->prev->absolute_loading_amount_min + s->prev->absolute_loading_amount_len * s->prev->relative_completion;
1847                 s->absolute_loading_amount_len = s->prev->absolute_loading_amount_len * len_in_parent;
1848                 if(s->absolute_loading_amount_len > s->prev->absolute_loading_amount_min + s->prev->absolute_loading_amount_len - s->absolute_loading_amount_min)
1849                         s->absolute_loading_amount_len = s->prev->absolute_loading_amount_min + s->prev->absolute_loading_amount_len - s->absolute_loading_amount_min;
1850         }
1851         else
1852         {
1853                 s->absolute_loading_amount_min = 0;
1854                 s->absolute_loading_amount_len = 1;
1855         }
1856
1857                 SCR_UpdateLoadingScreenIfShown();
1858 }
1859
1860 void SCR_PopLoadingScreen (qbool redraw)
1861 {
1862         loadingscreenstack_t *s = loadingscreenstack;
1863
1864         if(!s)
1865         {
1866                 Con_DPrintf("Popping a loading screen item from an empty stack!\n");
1867                 return;
1868         }
1869
1870         loadingscreenstack = s->prev;
1871         if(s->prev)
1872                 s->prev->relative_completion = (s->absolute_loading_amount_min + s->absolute_loading_amount_len - s->prev->absolute_loading_amount_min) / s->prev->absolute_loading_amount_len;
1873         Z_Free(s);
1874
1875         if(redraw)
1876                 SCR_UpdateLoadingScreenIfShown();
1877 }
1878
1879 void SCR_ClearLoadingScreen (qbool redraw)
1880 {
1881         while(loadingscreenstack)
1882                 SCR_PopLoadingScreen(redraw && !loadingscreenstack->prev);
1883 }
1884
1885 static float SCR_DrawLoadingStack_r(loadingscreenstack_t *s, float y, float size)
1886 {
1887         float x;
1888         size_t len;
1889         float total;
1890
1891         total = 0;
1892 #if 0
1893         if(s)
1894         {
1895                 total += SCR_DrawLoadingStack_r(s->prev, y, 8);
1896                 y -= total;
1897                 if(!s->prev || strcmp(s->msg, s->prev->msg))
1898                 {
1899                         len = strlen(s->msg);
1900                         x = (vid_conwidth.integer - DrawQ_TextWidth(s->msg, len, size, size, true, FONT_INFOBAR)) / 2;
1901                         y -= size;
1902                         DrawQ_Fill(0, y, vid_conwidth.integer, size, 0, 0, 0, 1, 0);
1903                         DrawQ_String(x, y, s->msg, len, size, size, 1, 1, 1, 1, 0, NULL, true, FONT_INFOBAR);
1904                         total += size;
1905                 }
1906         }
1907 #else
1908         if(s)
1909         {
1910                 len = strlen(s->msg);
1911                 x = (vid_conwidth.integer - DrawQ_TextWidth(s->msg, len, size, size, true, FONT_INFOBAR)) / 2;
1912                 y -= size;
1913                 if (gamemode != GAME_WRATH)
1914                 {
1915                         DrawQ_Fill(0, y, vid_conwidth.integer, size, 0, 0, 0, 1, 0);
1916                         DrawQ_String(x, y, s->msg, len, size, size, 1, 1, 1, 1, 0, NULL, true, FONT_INFOBAR);
1917                 }
1918                 total += size;
1919         }
1920 #endif
1921         return total;
1922 }
1923
1924 static void SCR_DrawLoadingStack(void)
1925 {
1926         float verts[12];
1927         float colors[16];
1928
1929         loadingscreenheight = SCR_DrawLoadingStack_r(loadingscreenstack, vid_conheight.integer, scr_loadingscreen_barheight.value);
1930         if(gamemode != GAME_WRATH && loadingscreenstack)
1931         {
1932                 // height = 32; // sorry, using the actual one is ugly
1933                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
1934                 GL_DepthRange(0, 1);
1935                 GL_PolygonOffset(0, 0);
1936                 GL_DepthTest(false);
1937 //              R_Mesh_ResetTextureState();
1938                 verts[2] = verts[5] = verts[8] = verts[11] = 0;
1939                 verts[0] = verts[9] = 0;
1940                 verts[1] = verts[4] = vid_conheight.integer - scr_loadingscreen_barheight.value;
1941                 verts[3] = verts[6] = vid_conwidth.integer * loadingscreenstack->absolute_loading_amount_min;
1942                 verts[7] = verts[10] = vid_conheight.integer;
1943                 
1944 #if _MSC_VER >= 1400
1945 #define sscanf sscanf_s
1946 #endif
1947                 //                                        ^^^^^^^^^^ blue component
1948                 //                              ^^^^^^ bottom row
1949                 //          ^^^^^^^^^^^^ alpha is always on
1950                 colors[0] = 0; colors[1] = 0; colors[2] = 0; colors[3] = 1;
1951                 colors[4] = 0; colors[5] = 0; colors[6] = 0; colors[7] = 1;
1952                 sscanf(scr_loadingscreen_barcolor.string, "%f %f %f", &colors[8], &colors[9], &colors[10]); colors[11] = 1;
1953                 sscanf(scr_loadingscreen_barcolor.string, "%f %f %f", &colors[12], &colors[13], &colors[14]);  colors[15] = 1;
1954
1955                 R_Mesh_PrepareVertices_Generic_Arrays(4, verts, colors, NULL);
1956                 R_SetupShader_Generic_NoTexture(true, true);
1957                 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
1958
1959                 // make sure everything is cleared, including the progress indicator
1960                 if(loadingscreenheight < 8)
1961                         loadingscreenheight = 8;
1962         }
1963 }
1964
1965 static cachepic_t *loadingscreenpic;
1966 static cachepic_t *loadingscreenind;
1967 static float loadingscreenpic_vertex3f[12];
1968 static float loadingscreenpic_texcoord2f[8];
1969 static float loadingscreenind_vertex3f[12];
1970 static float loadingscreenind_texcoord2f[8];
1971 static float loadingscreenind_angle;
1972 static float loadingscreenind_pos[2];
1973 static qbool loadingscreenind_show;
1974
1975 void SCR_SetLoadingSplash (const char *mapname)
1976 {
1977         char vabuf[1024] = { 0 };
1978
1979         if (gamemode != GAME_WRATH)
1980                 return; // let god sort em out
1981
1982         // if we're connecting somewhere, the mapname is unknown until the server sends it to us,
1983         // so the pic is set once we get the server info,
1984         // otherwise the appropriate function just calls this with a known mapname.
1985         // to reset to black screen, just call this with NULL mapname
1986
1987         if (mapname && mapname[0]) {
1988                 // try the current aspect ratio
1989                 dpsnprintf(vabuf, sizeof(vabuf), "gfx/splashes/%s_%s", mapname, scr_aspectname.string);
1990                 if (!Draw_PicExists(vabuf)) {
1991                         // try the default aspect ratio (16:9)
1992                         dpsnprintf(vabuf, sizeof(vabuf), "gfx/splashes/%s_16-9", mapname);
1993                         if (!Draw_PicExists(vabuf)) {
1994                                 // try without aspect ratio
1995                                 dpsnprintf(vabuf, sizeof(vabuf), "gfx/splashes/%s", mapname);
1996                                 if (!Draw_PicExists(vabuf))
1997                                         vabuf[0] = 0; // give up
1998                         }
1999                 }
2000         }
2001
2002         if (!vabuf[0])
2003                 strlcpy(vabuf, "gfx/splashes/_blank", sizeof(vabuf));
2004
2005         Cvar_SetQuick(&scr_loadingscreen_picture, vabuf);
2006 }
2007
2008 static void SCR_DrawLoadingScreen_SharedSetup (qbool clear)
2009 {
2010         r_viewport_t viewport;
2011         float x, y, w, h, sw, sh, f;
2012         char vabuf[1024];
2013         // release mouse grab while loading
2014         if (!vid.fullscreen)
2015                 VID_SetMouse(false, false, false);
2016 //      CHECKGLERROR
2017         r_refdef.draw2dstage = true;
2018         R_Viewport_InitOrtho(&viewport, &identitymatrix, 0, 0, vid.width, vid.height, 0, 0, vid_conwidth.integer, vid_conheight.integer, -10, 100, NULL);
2019         R_Mesh_SetRenderTargets(0, NULL, NULL, NULL, NULL, NULL);
2020         R_SetViewport(&viewport);
2021         GL_ColorMask(1,1,1,1);
2022         // when starting up a new video mode, make sure the screen is cleared to black
2023         if (clear || loadingscreentexture)
2024                 GL_Clear(GL_COLOR_BUFFER_BIT, NULL, 1.0f, 0);
2025         R_Textures_Frame();
2026         R_Mesh_Start();
2027         R_EntityMatrix(&identitymatrix);
2028         
2029         if (gamemode == GAME_WRATH)
2030         {
2031                 // setup the splash
2032                 loadingscreenpic = Draw_CachePic_Flags(scr_loadingscreen_picture.string, 0);
2033                 loadingscreenpic_vertex3f[2] = loadingscreenpic_vertex3f[5] = loadingscreenpic_vertex3f[8] = loadingscreenpic_vertex3f[11] = 0;
2034                 loadingscreenpic_vertex3f[0] = loadingscreenpic_vertex3f[9] = 0;
2035                 loadingscreenpic_vertex3f[1] = loadingscreenpic_vertex3f[4] = 0;
2036                 loadingscreenpic_vertex3f[3] = loadingscreenpic_vertex3f[6] = vid_conwidth.integer;
2037                 loadingscreenpic_vertex3f[7] = loadingscreenpic_vertex3f[10] = vid_conheight.integer;
2038                 loadingscreenpic_texcoord2f[0] = 0;loadingscreenpic_texcoord2f[1] = 0;
2039                 loadingscreenpic_texcoord2f[2] = 1;loadingscreenpic_texcoord2f[3] = 0;
2040                 loadingscreenpic_texcoord2f[4] = 1;loadingscreenpic_texcoord2f[5] = 1;
2041                 loadingscreenpic_texcoord2f[6] = 0;loadingscreenpic_texcoord2f[7] = 1;
2042     
2043                 // spinning circle/arrow thing
2044                 if (SCR_LoadingScreenWaiting())
2045                 {
2046                         loadingscreenind = loadingscreenind_show ? Draw_CachePic_Flags ("gfx/splashes/arrow", 0) : NULL;
2047                         loadingscreenind_angle = 0.f;
2048                 }
2049                 else
2050                 {
2051                         loadingscreenind = Draw_CachePic_Flags ("gfx/splashes/loading_ring", 0);
2052                 }
2053
2054                 if (loadingscreenind)
2055                 {
2056                         loadingscreenind_pos[0] = vid_conwidth.integer - 20;
2057                         loadingscreenind_pos[1] = vid_conheight.integer - 20;
2058                         loadingscreenind_vertex3f[2] = loadingscreenind_vertex3f[5] = loadingscreenind_vertex3f[8] = loadingscreenind_vertex3f[11] = 0;
2059                         loadingscreenind_vertex3f[0] = loadingscreenind_vertex3f[9] = -Draw_GetPicWidth(loadingscreenind) / 2;
2060                         loadingscreenind_vertex3f[1] = loadingscreenind_vertex3f[4] = -Draw_GetPicHeight(loadingscreenind) / 2;
2061                         loadingscreenind_vertex3f[3] = loadingscreenind_vertex3f[6] = Draw_GetPicWidth(loadingscreenind) / 2;
2062                         loadingscreenind_vertex3f[7] = loadingscreenind_vertex3f[10] = Draw_GetPicHeight(loadingscreenind) / 2;
2063                         loadingscreenind_texcoord2f[0] = 0;loadingscreenind_texcoord2f[1] = 0;
2064                         loadingscreenind_texcoord2f[2] = 1;loadingscreenind_texcoord2f[3] = 0;
2065                         loadingscreenind_texcoord2f[4] = 1;loadingscreenind_texcoord2f[5] = 1;
2066                         loadingscreenind_texcoord2f[6] = 0;loadingscreenind_texcoord2f[7] = 1;
2067                 }
2068         }
2069         else
2070         {
2071                 // draw the loading plaque
2072                 loadingscreenpic = Draw_CachePic_Flags (loadingscreenpic_number ? va(vabuf, sizeof(vabuf), "%s%d", scr_loadingscreen_picture.string, loadingscreenpic_number+1) : scr_loadingscreen_picture.string, loadingscreenpic_number ? CACHEPICFLAG_NOTPERSISTENT : 0);
2073
2074                 w = Draw_GetPicWidth(loadingscreenpic);
2075                 h = Draw_GetPicHeight(loadingscreenpic);
2076
2077                 // apply scale
2078                 w *= scr_loadingscreen_scale.value;
2079                 h *= scr_loadingscreen_scale.value;
2080
2081                 // apply scale base
2082                 if(scr_loadingscreen_scale_base.integer)
2083                 {
2084                         w *= vid_conwidth.integer / (float) vid.width;
2085                         h *= vid_conheight.integer / (float) vid.height;
2086                 }
2087
2088                 // apply scale limit
2089                 sw = w / vid_conwidth.integer;
2090                 sh = h / vid_conheight.integer;
2091                 f = 1;
2092                 switch(scr_loadingscreen_scale_limit.integer)
2093                 {
2094                         case 1:
2095                                 f = max(sw, sh);
2096                                 break;
2097                         case 2:
2098                                 f = min(sw, sh);
2099                                 break;
2100                         case 3:
2101                                 f = sw;
2102                                 break;
2103                         case 4:
2104                                 f = sh;
2105                                 break;
2106                 }
2107                 if(f > 1)
2108                 {
2109                         w /= f;
2110                         h /= f;
2111                 }
2112
2113                 x = (vid_conwidth.integer - w)/2;
2114                 y = (vid_conheight.integer - h)/2;
2115                 loadingscreenpic_vertex3f[2] = loadingscreenpic_vertex3f[5] = loadingscreenpic_vertex3f[8] = loadingscreenpic_vertex3f[11] = 0;
2116                 loadingscreenpic_vertex3f[0] = loadingscreenpic_vertex3f[9] = x;
2117                 loadingscreenpic_vertex3f[1] = loadingscreenpic_vertex3f[4] = y;
2118                 loadingscreenpic_vertex3f[3] = loadingscreenpic_vertex3f[6] = x + w;
2119                 loadingscreenpic_vertex3f[7] = loadingscreenpic_vertex3f[10] = y + h;
2120                 loadingscreenpic_texcoord2f[0] = 0;loadingscreenpic_texcoord2f[1] = 0;
2121                 loadingscreenpic_texcoord2f[2] = 1;loadingscreenpic_texcoord2f[3] = 0;
2122                 loadingscreenpic_texcoord2f[4] = 1;loadingscreenpic_texcoord2f[5] = 1;
2123                 loadingscreenpic_texcoord2f[6] = 0;loadingscreenpic_texcoord2f[7] = 1;
2124         }
2125 }
2126
2127 static void SCR_DrawLoadingScreen (void)
2128 {
2129         // we only need to draw the image if it isn't already there
2130         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2131         GL_DepthRange(0, 1);
2132         GL_PolygonOffset(0, 0);
2133         GL_DepthTest(false);
2134 //      R_Mesh_ResetTextureState();
2135         GL_Color(1,1,1,1);
2136         if(loadingscreentexture)
2137         {
2138                 R_Mesh_PrepareVertices_Generic_Arrays(4, loadingscreentexture_vertex3f, NULL, loadingscreentexture_texcoord2f);
2139                 R_SetupShader_Generic(loadingscreentexture, false, true, true);
2140                 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
2141         }
2142         R_Mesh_PrepareVertices_Generic_Arrays(4, loadingscreenpic_vertex3f, NULL, loadingscreenpic_texcoord2f);
2143         R_SetupShader_Generic(Draw_GetPicTexture(loadingscreenpic), true, true, false);
2144         R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
2145         SCR_DrawLoadingStack();
2146 }
2147
2148 static double loadingscreen_lastupdate;
2149
2150 static void SCR_UpdateVars(void);
2151
2152 void SCR_UpdateLoadingScreen (qbool clear, qbool startup)
2153 {
2154         keydest_t       old_key_dest;
2155         int                     old_key_consoleactive;
2156
2157         // don't do anything if not initialized yet
2158         if (vid_hidden || cls.state == ca_dedicated)
2159                 return;
2160
2161         // limit update rate
2162         if (scr_loadingscreen_maxfps.value)
2163         {
2164                 double t = Sys_DirtyTime();
2165                 if ((t - loadingscreen_lastupdate) < 1.0f/scr_loadingscreen_maxfps.value)
2166                         return;
2167                 loadingscreen_lastupdate = t;
2168         }
2169
2170         // set up the r_texture_gammaramps texture which we need for rendering the loadingscreenpic
2171         R_UpdateVariables();
2172
2173         if(!scr_loadingscreen_background.integer)
2174                 clear = true;
2175         
2176         if(loadingscreendone)
2177                 clear |= loadingscreencleared;
2178
2179         if(!loadingscreendone)
2180         {
2181                 if(startup && scr_loadingscreen_firstforstartup.integer)
2182                         loadingscreenpic_number = 0;
2183                 else if(scr_loadingscreen_firstforstartup.integer)
2184                         if(scr_loadingscreen_count.integer > 1)
2185                                 loadingscreenpic_number = rand() % (scr_loadingscreen_count.integer - 1) + 1;
2186                         else
2187                                 loadingscreenpic_number = 0;
2188                 else
2189                         loadingscreenpic_number = rand() % (scr_loadingscreen_count.integer > 1 ? scr_loadingscreen_count.integer : 1);
2190         }
2191
2192         if(clear)
2193                 SCR_ClearLoadingScreenTexture();
2194         else if(!loadingscreendone)
2195                 SCR_SetLoadingScreenTexture();
2196
2197         if(!loadingscreendone)
2198         {
2199                 loadingscreendone = true;
2200                 loadingscreenheight = 0;
2201         }
2202         loadingscreencleared = clear;
2203
2204 #ifdef USE_GLES2
2205         SCR_DrawLoadingScreen_SharedSetup(clear);
2206         SCR_DrawLoadingScreen();
2207 #else
2208         SCR_DrawLoadingScreen_SharedSetup(clear);
2209         if (vid.stereobuffer)
2210         {
2211                 qglDrawBuffer(GL_BACK_LEFT);
2212                 SCR_DrawLoadingScreen();
2213                 qglDrawBuffer(GL_BACK_RIGHT);
2214                 SCR_DrawLoadingScreen();
2215         }
2216         else
2217         {
2218                 qglDrawBuffer(GL_BACK);
2219                 SCR_DrawLoadingScreen();
2220         }
2221 #endif
2222
2223         DrawQ_Finish();
2224         R_Mesh_Finish();
2225         // refresh
2226         VID_Finish();
2227
2228         // this goes into the event loop, and should prevent unresponsive cursor on vista
2229         old_key_dest = key_dest;
2230         old_key_consoleactive = key_consoleactive;
2231         key_dest = key_void;
2232         key_consoleactive = false;
2233         Key_EventQueue_Block(); Sys_SendKeyEvents();
2234         key_dest = old_key_dest;
2235         key_consoleactive = old_key_consoleactive;
2236 }
2237
2238 qbool SCR_LoadingScreenWaiting(void)
2239 {
2240         return cl.islocalgame && (loadingscreenstack && loadingscreenstack->msg[0] == '$' && loadingscreenstack->msg[1] == '\0');
2241 }
2242
2243 qbool R_Stereo_ColorMasking(void)
2244 {
2245         return r_stereo_redblue.integer || r_stereo_redgreen.integer || r_stereo_redcyan.integer;
2246 }
2247
2248 qbool R_Stereo_Active(void)
2249 {
2250         return (vid.stereobuffer || r_stereo_sidebyside.integer || r_stereo_horizontal.integer || r_stereo_vertical.integer || R_Stereo_ColorMasking());
2251 }
2252
2253 void SCR_UpdateVars(void)
2254 {
2255         float conwidth = bound(160, vid_conwidth.value, 32768);
2256         float conheight = bound(90, vid_conheight.value, 24576);
2257         if (vid_conwidthauto.integer)
2258                 conwidth = floor(conheight * vid.width / (vid.height * vid_pixelheight.value));
2259         if (vid_conwidth.value != conwidth)
2260                 Cvar_SetValueQuick(&vid_conwidth, conwidth);
2261         if (vid_conheight.value != conheight)
2262                 Cvar_SetValueQuick(&vid_conheight, conheight);
2263
2264         // bound viewsize
2265         if (scr_viewsize.value < 30)
2266                 Cvar_SetValueQuick(&scr_viewsize, 30);
2267         if (scr_viewsize.value > 120)
2268                 Cvar_SetValueQuick(&scr_viewsize, 120);
2269
2270         // bound field of view
2271         if (scr_fov.value < 1)
2272                 Cvar_SetValueQuick(&scr_fov, 1);
2273         if (scr_fov.value > 170)
2274                 Cvar_SetValueQuick(&scr_fov, 170);
2275
2276         // intermission is always full screen
2277         if (cl.intermission)
2278                 sb_lines = 0;
2279         else
2280         {
2281                 if (scr_viewsize.value >= 120)
2282                         sb_lines = 0;           // no status bar at all
2283                 else if (scr_viewsize.value >= 110)
2284                         sb_lines = 24;          // no inventory
2285                 else
2286                         sb_lines = 24 + 16 + 8;
2287         }
2288 }
2289
2290 extern cvar_t cl_minfps;
2291 extern cvar_t cl_minfps_fade;
2292 extern cvar_t cl_minfps_qualitymax;
2293 extern cvar_t cl_minfps_qualitymin;
2294 extern cvar_t cl_minfps_qualitymultiply;
2295 extern cvar_t cl_minfps_qualityhysteresis;
2296 extern cvar_t cl_minfps_qualitystepmax;
2297 extern cvar_t cl_minfps_force;
2298 static double cl_updatescreen_quality = 1;
2299 void CL_UpdateScreen(void)
2300 {
2301         vec3_t vieworigin;
2302         static double drawscreenstart = 0.0;
2303         double drawscreendelta;
2304         r_viewport_t viewport;
2305
2306         // TODO: Move to a better place.
2307         cl_punchangle_applied = 0;
2308
2309         if(drawscreenstart)
2310         {
2311                 drawscreendelta = Sys_DirtyTime() - drawscreenstart;
2312 #ifdef CONFIG_VIDEO_CAPTURE
2313                 if (cl_minfps.value > 0 && (cl_minfps_force.integer || !(cls.timedemo || (cls.capturevideo.active && !cls.capturevideo.realtime))) && drawscreendelta >= 0 && drawscreendelta < 60)
2314 #else
2315                 if (cl_minfps.value > 0 && (cl_minfps_force.integer || !cls.timedemo) && drawscreendelta >= 0 && drawscreendelta < 60)
2316 #endif
2317                 {
2318                         // quality adjustment according to render time
2319                         double actualframetime;
2320                         double targetframetime;
2321                         double adjust;
2322                         double f;
2323                         double h;
2324
2325                         // fade lastdrawscreentime
2326                         r_refdef.lastdrawscreentime += (drawscreendelta - r_refdef.lastdrawscreentime) * cl_minfps_fade.value;
2327
2328                         // find actual and target frame times
2329                         actualframetime = r_refdef.lastdrawscreentime;
2330                         targetframetime = (1.0 / cl_minfps.value);
2331
2332                         // we scale hysteresis by quality
2333                         h = cl_updatescreen_quality * cl_minfps_qualityhysteresis.value;
2334
2335                         // calculate adjustment assuming linearity
2336                         f = cl_updatescreen_quality / actualframetime * cl_minfps_qualitymultiply.value;
2337                         adjust = (targetframetime - actualframetime) * f;
2338
2339                         // one sided hysteresis
2340                         if(adjust > 0)
2341                                 adjust = max(0, adjust - h);
2342
2343                         // adjust > 0 if:
2344                         //   (targetframetime - actualframetime) * f > h
2345                         //   ((1.0 / cl_minfps.value) - actualframetime) * (cl_updatescreen_quality / actualframetime * cl_minfps_qualitymultiply.value) > (cl_updatescreen_quality * cl_minfps_qualityhysteresis.value)
2346                         //   ((1.0 / cl_minfps.value) - actualframetime) * (cl_minfps_qualitymultiply.value / actualframetime) > cl_minfps_qualityhysteresis.value
2347                         //   (1.0 / cl_minfps.value) * (cl_minfps_qualitymultiply.value / actualframetime) - cl_minfps_qualitymultiply.value > cl_minfps_qualityhysteresis.value
2348                         //   (1.0 / cl_minfps.value) * (cl_minfps_qualitymultiply.value / actualframetime) > cl_minfps_qualityhysteresis.value + cl_minfps_qualitymultiply.value
2349                         //   (1.0 / cl_minfps.value) / actualframetime > (cl_minfps_qualityhysteresis.value + cl_minfps_qualitymultiply.value) / cl_minfps_qualitymultiply.value
2350                         //   (1.0 / cl_minfps.value) / actualframetime > 1.0 + cl_minfps_qualityhysteresis.value / cl_minfps_qualitymultiply.value
2351                         //   cl_minfps.value * actualframetime < 1.0 / (1.0 + cl_minfps_qualityhysteresis.value / cl_minfps_qualitymultiply.value)
2352                         //   actualframetime < 1.0 / cl_minfps.value / (1.0 + cl_minfps_qualityhysteresis.value / cl_minfps_qualitymultiply.value)
2353                         //   actualfps > cl_minfps.value * (1.0 + cl_minfps_qualityhysteresis.value / cl_minfps_qualitymultiply.value)
2354
2355                         // adjust < 0 if:
2356                         //   (targetframetime - actualframetime) * f < 0
2357                         //   ((1.0 / cl_minfps.value) - actualframetime) * (cl_updatescreen_quality / actualframetime * cl_minfps_qualitymultiply.value) < 0
2358                         //   ((1.0 / cl_minfps.value) - actualframetime) < 0
2359                         //   -actualframetime) < -(1.0 / cl_minfps.value)
2360                         //   actualfps < cl_minfps.value
2361
2362                         /*
2363                         Con_Printf("adjust UP if fps > %f, adjust DOWN if fps < %f\n",
2364                                         cl_minfps.value * (1.0 + cl_minfps_qualityhysteresis.value / cl_minfps_qualitymultiply.value),
2365                                         cl_minfps.value);
2366                         */
2367
2368                         // don't adjust too much at once
2369                         adjust = bound(-cl_minfps_qualitystepmax.value, adjust, cl_minfps_qualitystepmax.value);
2370
2371                         // adjust!
2372                         cl_updatescreen_quality += adjust;
2373                         cl_updatescreen_quality = bound(max(0.01, cl_minfps_qualitymin.value), cl_updatescreen_quality, cl_minfps_qualitymax.value);
2374                 }
2375                 else
2376                 {
2377                         cl_updatescreen_quality = 1;
2378                         r_refdef.lastdrawscreentime = 0;
2379                 }
2380         }
2381
2382         drawscreenstart = Sys_DirtyTime();
2383
2384         Sbar_ShowFPS_Update();
2385
2386         if (!scr_initialized || !con_initialized || !scr_refresh.integer)
2387                 return;                         // not initialized yet
2388
2389         loadingscreendone = false;
2390
2391         if(IS_NEXUIZ_DERIVED(gamemode))
2392         {
2393                 // play a bit with the palette (experimental)
2394                 palette_rgb_pantscolormap[15][0] = (unsigned char) (128 + 127 * sin(cl.time / exp(1.0f) + 0.0f*M_PI/3.0f));
2395                 palette_rgb_pantscolormap[15][1] = (unsigned char) (128 + 127 * sin(cl.time / exp(1.0f) + 2.0f*M_PI/3.0f));
2396                 palette_rgb_pantscolormap[15][2] = (unsigned char) (128 + 127 * sin(cl.time / exp(1.0f) + 4.0f*M_PI/3.0f));
2397                 palette_rgb_shirtcolormap[15][0] = (unsigned char) (128 + 127 * sin(cl.time /  M_PI  + 5.0f*M_PI/3.0f));
2398                 palette_rgb_shirtcolormap[15][1] = (unsigned char) (128 + 127 * sin(cl.time /  M_PI  + 3.0f*M_PI/3.0f));
2399                 palette_rgb_shirtcolormap[15][2] = (unsigned char) (128 + 127 * sin(cl.time /  M_PI  + 1.0f*M_PI/3.0f));
2400                 memcpy(palette_rgb_pantsscoreboard[15], palette_rgb_pantscolormap[15], sizeof(*palette_rgb_pantscolormap));
2401                 memcpy(palette_rgb_shirtscoreboard[15], palette_rgb_shirtcolormap[15], sizeof(*palette_rgb_shirtcolormap));
2402         }
2403
2404 #ifdef CONFIG_VIDEO_CAPTURE
2405         if (vid_hidden && !cls.capturevideo.active && !cl_capturevideo.integer)
2406 #else
2407         if (vid_hidden)
2408 #endif
2409         {
2410                 VID_Finish();
2411                 return;
2412         }
2413
2414         SCR_UpdateVars();
2415
2416         R_FrameData_NewFrame();
2417         R_BufferData_NewFrame();
2418
2419         Matrix4x4_OriginFromMatrix(&r_refdef.view.matrix, vieworigin);
2420         R_HDR_UpdateIrisAdaptation(vieworigin);
2421
2422         r_refdef.view.colormask[0] = 1;
2423         r_refdef.view.colormask[1] = 1;
2424         r_refdef.view.colormask[2] = 1;
2425
2426         SCR_SetUpToDrawConsole();
2427
2428 #ifndef USE_GLES2
2429         CHECKGLERROR
2430         qglDrawBuffer(GL_BACK);CHECKGLERROR
2431 #endif
2432
2433         R_Viewport_InitOrtho(&viewport, &identitymatrix, 0, 0, vid.width, vid.height, 0, 0, vid_conwidth.integer, vid_conheight.integer, -10, 100, NULL);
2434         R_Mesh_SetRenderTargets(0, NULL, NULL, NULL, NULL, NULL);
2435         R_SetViewport(&viewport);
2436         GL_ScissorTest(false);
2437         GL_ColorMask(1,1,1,1);
2438         GL_DepthMask(true);
2439
2440         R_ClearScreen(false);
2441         r_refdef.view.clear = false;
2442         r_refdef.view.isoverlay = false;
2443
2444         // calculate r_refdef.view.quality
2445         r_refdef.view.quality = cl_updatescreen_quality;
2446
2447         if(scr_stipple.integer)
2448         {
2449                 Con_Print("FIXME: scr_stipple not implemented\n");
2450                 Cvar_SetValueQuick(&scr_stipple, 0);
2451         }
2452
2453 #ifndef USE_GLES2
2454         if (R_Stereo_Active())
2455         {
2456                 r_stereo_side = 0;
2457
2458                 if (r_stereo_redblue.integer || r_stereo_redgreen.integer || r_stereo_redcyan.integer)
2459                 {
2460                         r_refdef.view.colormask[0] = 1;
2461                         r_refdef.view.colormask[1] = 0;
2462                         r_refdef.view.colormask[2] = 0;
2463                 }
2464
2465                 if (vid.stereobuffer)
2466                         qglDrawBuffer(GL_BACK_RIGHT);
2467
2468                 SCR_DrawScreen();
2469
2470                 r_stereo_side = 1;
2471                 r_refdef.view.clear = true;
2472
2473                 if (r_stereo_redblue.integer || r_stereo_redgreen.integer || r_stereo_redcyan.integer)
2474                 {
2475                         r_refdef.view.colormask[0] = 0;
2476                         r_refdef.view.colormask[1] = r_stereo_redcyan.integer || r_stereo_redgreen.integer;
2477                         r_refdef.view.colormask[2] = r_stereo_redcyan.integer || r_stereo_redblue.integer;
2478                 }
2479
2480                 if (vid.stereobuffer)
2481                         qglDrawBuffer(GL_BACK_LEFT);
2482
2483                 SCR_DrawScreen();
2484                 r_stereo_side = 0;
2485         }
2486         else
2487 #endif
2488         {
2489                 r_stereo_side = 0;
2490                 SCR_DrawScreen();
2491         }
2492
2493 #ifdef CONFIG_VIDEO_CAPTURE
2494         SCR_CaptureVideo();
2495 #endif
2496
2497         qglFlush(); // ensure that the commands are submitted to the GPU before we do other things
2498
2499         if (!vid_activewindow)
2500                 VID_SetMouse(false, false, false);
2501         else if (key_consoleactive)
2502                 VID_SetMouse(vid.fullscreen, false, false);
2503         else if (key_dest == key_menu_grabbed)
2504                 VID_SetMouse(true, vid_mouse.integer && !in_client_mouse && !vid_touchscreen.integer, !vid_touchscreen.integer);
2505         else if (key_dest == key_menu)
2506                 VID_SetMouse(vid.fullscreen, vid_mouse.integer && !in_client_mouse && !vid_touchscreen.integer, !vid_touchscreen.integer);
2507         else
2508                 VID_SetMouse(vid.fullscreen, vid_mouse.integer && !cl.csqc_wantsmousemove && cl_prydoncursor.integer <= 0 && (!cls.demoplayback || cl_demo_mousegrab.integer) && !vid_touchscreen.integer, !vid_touchscreen.integer);
2509
2510         VID_Finish();
2511 }
2512
2513 void CL_Screen_NewMap(void)
2514 {
2515 }