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