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