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