new cvar sys_useclockgettime (default 0) that makes DP use clock_gettime as time...
[divverent/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 "cl_collision.h"
7 #include "libcurl.h"
8 #include "csprogs.h"
9
10 // we have to include snd_main.h here only to get access to snd_renderbuffer->format.speed when writing the AVI headers
11 #include "snd_main.h"
12
13 cvar_t scr_viewsize = {CVAR_SAVE, "viewsize","100", "how large the view should be, 110 disables inventory bar, 120 disables status bar"};
14 cvar_t scr_fov = {CVAR_SAVE, "fov","90", "field of vision, 1-170 degrees, default 90, some players use 110-130"};
15 cvar_t scr_conalpha = {CVAR_SAVE, "scr_conalpha", "1", "opacity of console background"};
16 cvar_t scr_conbrightness = {CVAR_SAVE, "scr_conbrightness", "1", "brightness of console background (0 = black, 1 = image)"};
17 cvar_t scr_conforcewhiledisconnected = {0, "scr_conforcewhiledisconnected", "1", "forces fullscreen console while disconnected"};
18 cvar_t scr_menuforcewhiledisconnected = {0, "scr_menuforcewhiledisconnected", "0", "forces menu while disconnected"};
19 cvar_t scr_centertime = {0, "scr_centertime","2", "how long centerprint messages show"};
20 cvar_t scr_showram = {CVAR_SAVE, "showram","1", "show ram icon if low on surface cache memory (not used)"};
21 cvar_t scr_showturtle = {CVAR_SAVE, "showturtle","0", "show turtle icon when framerate is too low"};
22 cvar_t scr_showpause = {CVAR_SAVE, "showpause","1", "show pause icon when game is paused"};
23 cvar_t scr_showbrand = {0, "showbrand","0", "shows gfx/brand.tga in a corner of the screen (different values select different positions, including centered)"};
24 cvar_t scr_printspeed = {0, "scr_printspeed","0", "speed of intermission printing (episode end texts), a value of 0 disables the slow printing"};
25 cvar_t vid_conwidth = {CVAR_SAVE, "vid_conwidth", "640", "virtual width of 2D graphics system"};
26 cvar_t vid_conheight = {CVAR_SAVE, "vid_conheight", "480", "virtual height of 2D graphics system"};
27 cvar_t vid_pixelheight = {CVAR_SAVE, "vid_pixelheight", "1", "adjusts vertical field of vision to account for non-square pixels (1280x1024 on a CRT monitor for example)"};
28 cvar_t scr_screenshot_jpeg = {CVAR_SAVE, "scr_screenshot_jpeg","1", "save jpeg instead of targa"};
29 cvar_t scr_screenshot_jpeg_quality = {CVAR_SAVE, "scr_screenshot_jpeg_quality","0.9", "image quality of saved jpeg"};
30 cvar_t scr_screenshot_gammaboost = {CVAR_SAVE, "scr_screenshot_gammaboost","1", "gamma correction on saved screenshots and videos, 1.0 saves unmodified images"};
31 // scr_screenshot_name is defined in fs.c
32 cvar_t cl_capturevideo = {0, "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)"};
33 cvar_t cl_capturevideo_width = {0, "cl_capturevideo_width", "0", "scales all frames to this resolution before saving the video"};
34 cvar_t cl_capturevideo_height = {0, "cl_capturevideo_height", "0", "scales all frames to this resolution before saving the video"};
35 cvar_t cl_capturevideo_realtime = {0, "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"};
36 cvar_t cl_capturevideo_fps = {0, "cl_capturevideo_fps", "30", "how many frames per second to save (29.97 for NTSC, 30 for typical PC video, 15 can be useful)"};
37 cvar_t cl_capturevideo_number = {CVAR_SAVE, "cl_capturevideo_number", "1", "number to append to video filename, incremented each time a capture begins"};
38 cvar_t r_letterbox = {0, "r_letterbox", "0", "reduces vertical height of view to simulate a letterboxed movie effect (can be used by mods for cutscenes)"};
39 cvar_t r_stereo_separation = {0, "r_stereo_separation", "4", "separation distance of eyes in the world (negative values are only useful for cross-eyed viewing)"};
40 cvar_t r_stereo_sidebyside = {0, "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)"};
41 cvar_t r_stereo_redblue = {0, "r_stereo_redblue", "0", "red/blue anaglyph stereo glasses (note: most of these glasses are actually red/cyan, try that one too)"};
42 cvar_t r_stereo_redcyan = {0, "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"};
43 cvar_t r_stereo_redgreen = {0, "r_stereo_redgreen", "0", "red/green anaglyph stereo glasses (for those who don't mind yellow)"};
44 cvar_t r_stereo_angle = {0, "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)"};
45 cvar_t scr_zoomwindow = {CVAR_SAVE, "scr_zoomwindow", "0", "displays a zoomed in overlay window"};
46 cvar_t scr_zoomwindow_viewsizex = {CVAR_SAVE, "scr_zoomwindow_viewsizex", "20", "horizontal viewsize of zoom window"};
47 cvar_t scr_zoomwindow_viewsizey = {CVAR_SAVE, "scr_zoomwindow_viewsizey", "20", "vertical viewsize of zoom window"};
48 cvar_t scr_zoomwindow_fov = {CVAR_SAVE, "scr_zoomwindow_fov", "20", "fov of zoom window"};
49 cvar_t scr_stipple = {0, "scr_stipple", "0", "interlacing-like stippling of the display"};
50 cvar_t scr_refresh = {0, "scr_refresh", "1", "allows you to completely shut off rendering for benchmarking purposes"};
51 cvar_t shownetgraph = {CVAR_SAVE, "shownetgraph", "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)"};
52
53 #define AVI_MASTER_INDEX_SIZE 640 // GB ought to be enough for anyone
54
55 int jpeg_supported = false;
56
57 qboolean        scr_initialized;                // ready to draw
58
59 float           scr_con_current;
60 int                     scr_con_margin_bottom;
61
62 extern int      con_vislines;
63
64 static void SCR_ScreenShot_f (void);
65 static void R_Envmap_f (void);
66
67 // backend
68 void R_ClearScreen(qboolean fogcolor);
69
70 /*
71 ===============================================================================
72
73 CENTER PRINTING
74
75 ===============================================================================
76 */
77
78 char            scr_centerstring[MAX_INPUTLINE];
79 float           scr_centertime_start;   // for slow victory printing
80 float           scr_centertime_off;
81 int                     scr_center_lines;
82 int                     scr_erase_lines;
83 int                     scr_erase_center;
84
85 /*
86 ==============
87 SCR_CenterPrint
88
89 Called for important messages that should stay in the center of the screen
90 for a few moments
91 ==============
92 */
93 void SCR_CenterPrint(const char *str)
94 {
95         strlcpy (scr_centerstring, str, sizeof (scr_centerstring));
96         scr_centertime_off = scr_centertime.value;
97         scr_centertime_start = cl.time;
98
99 // count the number of lines for centering
100         scr_center_lines = 1;
101         while (*str)
102         {
103                 if (*str == '\n')
104                         scr_center_lines++;
105                 str++;
106         }
107 }
108
109
110 void SCR_DrawCenterString (void)
111 {
112         char    *start;
113         int             x, y;
114         int             remaining;
115         int             color;
116
117         if(cl.intermission == 2) // in finale,
118                 if(sb_showscores) // make TAB hide the finale message (sb_showscores overrides finale in sbar.c)
119                         return;
120
121         if(scr_centertime.value <= 0 && !cl.intermission)
122                 return;
123
124 // the finale prints the characters one at a time, except if printspeed is an absurdly high value
125         if (cl.intermission && scr_printspeed.value > 0 && scr_printspeed.value < 1000000)
126                 remaining = (int)(scr_printspeed.value * (cl.time - scr_centertime_start));
127         else
128                 remaining = 9999;
129
130         scr_erase_center = 0;
131         start = scr_centerstring;
132
133         if (remaining < 1)
134                 return;
135
136         if (scr_center_lines <= 4)
137                 y = (int)(vid_conheight.integer*0.35);
138         else
139                 y = 48;
140
141         color = -1;
142         do
143         {
144                 // scan the number of characters on the line, not counting color codes
145                 char *newline = strchr(start, '\n');
146                 int l = newline ? (newline - start) : (int)strlen(start);
147                 float width = DrawQ_TextWidth_Font(start, l, false, FONT_CENTERPRINT) * 8;
148
149                 x = (vid_conwidth.integer - width)/2;
150                 if (l > 0)
151                 {
152                         if (remaining < l)
153                                 l = remaining;
154                         DrawQ_String_Font(x, y, start, l, 8, 8, 1, 1, 1, 1, 0, &color, false, FONT_CENTERPRINT);
155                         remaining -= l;
156                         if (remaining <= 0)
157                                 return;
158                 }
159                 y += 8;
160
161                 if (!newline)
162                         break;
163                 start = newline + 1; // skip the \n
164         } while (1);
165 }
166
167 void SCR_CheckDrawCenterString (void)
168 {
169         if (scr_center_lines > scr_erase_lines)
170                 scr_erase_lines = scr_center_lines;
171
172         if (cl.time > cl.oldtime)
173                 scr_centertime_off -= cl.time - cl.oldtime;
174
175         // don't draw if this is a normal stats-screen intermission,
176         // only if it is not an intermission, or a finale intermission
177         if (cl.intermission == 1)
178                 return;
179         if (scr_centertime_off <= 0 && !cl.intermission)
180                 return;
181         if (key_dest != key_game)
182                 return;
183
184         SCR_DrawCenterString ();
185 }
186
187 void SCR_DrawNetGraph_DrawGraph (int graphx, int graphy, int barwidth, int barheight, int bardivide, const char *label, float textsize, int packetcounter, int numparameters, const int **parameters, const float parametercolors[][4])
188 {
189         int j, k, x, y, index, offset, height;
190         // draw the bar graph itself
191         // advance the packet counter because it is the latest packet column being
192         // built up and should come last
193         packetcounter = (packetcounter + 1) % NETGRAPH_PACKETS;
194         for (j = 0;j < NETGRAPH_PACKETS;j++)
195         {
196                 x = graphx + j * barwidth;
197                 y = graphy + barheight;
198                 index = (packetcounter + j) % NETGRAPH_PACKETS;
199                 if (parameters[0][index] == NETGRAPH_LOSTPACKET)
200                         DrawQ_Fill(x, y - barheight, barwidth, barheight, 1, 0, 0, 1, 0);
201                 else if (parameters[0][index] == NETGRAPH_CHOKEDPACKET)
202                         DrawQ_Fill(x, y - min(2, barheight), barwidth, min(2, barheight), 1, 1, 0, 1, 0);
203                 else
204                 {
205                         offset = 0;
206                         for (k = 0;k < numparameters;k++)
207                         {
208                                 height = (parameters[k][index] + bardivide - 1) / bardivide;
209                                 height = min(height, barheight - offset);
210                                 offset += height;
211                                 if (height)
212                                         DrawQ_Fill(x, y - offset, barwidth, height, parametercolors[k][0], parametercolors[k][1], parametercolors[k][2], parametercolors[k][3], 0);
213                         }
214                 }
215         }
216 }
217
218 const float netgraphcolors[3][4] =
219 {
220         {1  , 0.5, 0  , 1},
221         {1  , 1  , 1  , 1},
222         {0  , 1  , 0  , 1},
223 };
224
225 void SCR_DrawNetGraph_DrawConnection_Client (netconn_t *conn, int graphx, int graphy, int barwidth, int barheight, int bardivide, const char *labelincoming, int separator, const char *labeloutgoing, float textsize)
226 {
227         int numparameters;
228         const int *parameters[3];
229         // dim background
230         DrawQ_Fill(graphx                                          , graphy, barwidth * NETGRAPH_PACKETS, barheight + textsize, 0, 0, 0, 0.5, 0);
231         DrawQ_Fill(graphx + barwidth * NETGRAPH_PACKETS + separator, graphy, barwidth * NETGRAPH_PACKETS, barheight + textsize, 0, 0, 0, 0.5, 0);
232         // draw the bar graphs
233         numparameters = 3;
234         parameters[0] = conn->incoming_unreliablesize;
235         parameters[1] = conn->incoming_reliablesize;
236         parameters[2] = conn->incoming_acksize;
237         SCR_DrawNetGraph_DrawGraph(graphx, graphy, barwidth, barheight, bardivide, labelincoming, textsize, conn->incoming_packetcounter, numparameters, parameters, netgraphcolors);
238         parameters[0] = conn->outgoing_unreliablesize;
239         parameters[1] = conn->outgoing_reliablesize;
240         parameters[2] = conn->outgoing_acksize;
241         SCR_DrawNetGraph_DrawGraph(graphx + barwidth * NETGRAPH_PACKETS + separator, graphy, barwidth, barheight, bardivide, labeloutgoing, textsize, conn->outgoing_packetcounter, numparameters, parameters, netgraphcolors);
242         // draw labels
243         DrawQ_String(graphx                                          , graphy + barheight, labelincoming, 0, textsize, textsize, 1, 1, 1, 1, 0, NULL, false);
244         DrawQ_String(graphx + barwidth * NETGRAPH_PACKETS + separator, graphy + barheight, labeloutgoing, 0, textsize, textsize, 1, 1, 1, 1, 0, NULL, false);
245 }
246
247 void SCR_DrawNetGraph_DrawConnection_Server (netconn_t *conn, int graphx, int graphy, int barwidth, int barheight, int bardivide, const char *labeloutgoing, int separator, const char *labelincoming, float textsize)
248 {
249         int numparameters;
250         const int *parameters[3];
251         // dim background
252         DrawQ_Fill(graphx                                          , graphy, barwidth * NETGRAPH_PACKETS, barheight + textsize, 0, 0, 0, 0.5, 0);
253         DrawQ_Fill(graphx + barwidth * NETGRAPH_PACKETS + separator, graphy, barwidth * NETGRAPH_PACKETS, barheight + textsize, 0, 0, 0, 0.5, 0);
254         // draw the bar graphs
255         numparameters = 3;
256         parameters[0] = conn->outgoing_unreliablesize;
257         parameters[1] = conn->outgoing_reliablesize;
258         parameters[2] = conn->outgoing_acksize;
259         SCR_DrawNetGraph_DrawGraph(graphx                                          , graphy, barwidth, barheight, bardivide, labeloutgoing, textsize, conn->outgoing_packetcounter, numparameters, parameters, netgraphcolors);
260         parameters[0] = conn->incoming_unreliablesize;
261         parameters[1] = conn->incoming_reliablesize;
262         parameters[2] = conn->incoming_acksize;
263         SCR_DrawNetGraph_DrawGraph(graphx + barwidth * NETGRAPH_PACKETS + separator, graphy, barwidth, barheight, bardivide, labelincoming, textsize, conn->incoming_packetcounter, numparameters, parameters, netgraphcolors);
264         // draw labels
265         DrawQ_String(graphx                                          , graphy + barheight, labeloutgoing, 0, textsize, textsize, 1, 1, 1, 1, 0, NULL, false);
266         DrawQ_String(graphx + barwidth * NETGRAPH_PACKETS + separator, graphy + barheight, labelincoming, 0, textsize, textsize, 1, 1, 1, 1, 0, NULL, false);
267 }
268
269 /*
270 ==============
271 SCR_DrawNetGraph
272 ==============
273 */
274 void SCR_DrawNetGraph (void)
275 {
276         int i, separator1, separator2, barwidth, barheight, bardivide, netgraph_x, netgraph_y, textsize, index, netgraphsperrow;
277
278         if (cls.state != ca_connected)
279                 return;
280         if (!cls.netcon)
281                 return;
282         if (!shownetgraph.integer)
283                 return;
284
285         separator1 = 2;
286         separator2 = 4;
287         textsize = 8;
288         barwidth = 1;
289         barheight = 50;
290         bardivide = 20;
291
292         netgraphsperrow = (vid_conwidth.integer + separator2) / (barwidth * NETGRAPH_PACKETS * 2 + separator1 + separator2);
293         netgraphsperrow = max(netgraphsperrow, 1);
294
295         index = 0;
296         netgraph_x = (vid_conwidth.integer + separator2) - (1 + (index % netgraphsperrow)) * (barwidth * NETGRAPH_PACKETS * 2 + separator1 + separator2);
297         netgraph_y = (vid_conheight.integer - 48 + separator2) - (1 + (index / netgraphsperrow)) * (barheight + textsize + separator2);
298         SCR_DrawNetGraph_DrawConnection_Client(cls.netcon, netgraph_x, netgraph_y, barwidth, barheight, bardivide, "incoming", separator1, "outgoing", textsize);
299         index++;
300
301         if (sv.active && shownetgraph.integer >= 2)
302         {
303                 for (i = 0;i < svs.maxclients;i++)
304                 {
305                         if (!svs.clients[i].netconnection)
306                                 continue;
307                         netgraph_x = (vid_conwidth.integer + separator2) - (1 + (index % netgraphsperrow)) * (barwidth * NETGRAPH_PACKETS * 2 + separator1 + separator2);
308                         netgraph_y = (vid_conheight.integer - 48 + separator2) - (1 + (index / netgraphsperrow)) * (barheight + textsize + separator2);
309                         SCR_DrawNetGraph_DrawConnection_Server(svs.clients[i].netconnection, netgraph_x, netgraph_y, barwidth, barheight, bardivide, va("%s", svs.clients[i].name), separator1, "", textsize);
310                         index++;
311                 }
312         }
313 }
314
315 /*
316 ==============
317 SCR_DrawTurtle
318 ==============
319 */
320 void SCR_DrawTurtle (void)
321 {
322         static int      count;
323
324         if (cls.state != ca_connected)
325                 return;
326
327         if (!scr_showturtle.integer)
328                 return;
329
330         if (cl.realframetime < 0.1)
331         {
332                 count = 0;
333                 return;
334         }
335
336         count++;
337         if (count < 3)
338                 return;
339
340         DrawQ_Pic (0, 0, Draw_CachePic ("gfx/turtle"), 0, 0, 1, 1, 1, 1, 0);
341 }
342
343 /*
344 ==============
345 SCR_DrawNet
346 ==============
347 */
348 void SCR_DrawNet (void)
349 {
350         if (cls.state != ca_connected)
351                 return;
352         if (realtime - cl.last_received_message < 0.3)
353                 return;
354         if (cls.demoplayback)
355                 return;
356
357         DrawQ_Pic (64, 0, Draw_CachePic ("gfx/net"), 0, 0, 1, 1, 1, 1, 0);
358 }
359
360 /*
361 ==============
362 DrawPause
363 ==============
364 */
365 void SCR_DrawPause (void)
366 {
367         cachepic_t      *pic;
368
369         if (cls.state != ca_connected)
370                 return;
371
372         if (!scr_showpause.integer)             // turn off for screenshots
373                 return;
374
375         if (!cl.paused)
376                 return;
377
378         pic = Draw_CachePic ("gfx/pause");
379         DrawQ_Pic ((vid_conwidth.integer - pic->width)/2, (vid_conheight.integer - pic->height)/2, pic, 0, 0, 1, 1, 1, 1, 0);
380 }
381
382 /*
383 ==============
384 SCR_DrawBrand
385 ==============
386 */
387 void SCR_DrawBrand (void)
388 {
389         cachepic_t      *pic;
390         float           x, y;
391
392         if (!scr_showbrand.value)
393                 return;
394
395         pic = Draw_CachePic ("gfx/brand");
396
397         switch ((int)scr_showbrand.value)
398         {
399         case 1: // bottom left
400                 x = 0;
401                 y = vid_conheight.integer - pic->height;
402                 break;
403         case 2: // bottom centre
404                 x = (vid_conwidth.integer - pic->width) / 2;
405                 y = vid_conheight.integer - pic->height;
406                 break;
407         case 3: // bottom right
408                 x = vid_conwidth.integer - pic->width;
409                 y = vid_conheight.integer - pic->height;
410                 break;
411         case 4: // centre right
412                 x = vid_conwidth.integer - pic->width;
413                 y = (vid_conheight.integer - pic->height) / 2;
414                 break;
415         case 5: // top right
416                 x = vid_conwidth.integer - pic->width;
417                 y = 0;
418                 break;
419         case 6: // top centre
420                 x = (vid_conwidth.integer - pic->width) / 2;
421                 y = 0;
422                 break;
423         case 7: // top left
424                 x = 0;
425                 y = 0;
426                 break;
427         case 8: // centre left
428                 x = 0;
429                 y = (vid_conheight.integer - pic->height) / 2;
430                 break;
431         default:
432                 return;
433         }
434
435         DrawQ_Pic (x, y, pic, 0, 0, 1, 1, 1, 1, 0);
436 }
437
438 /*
439 ==============
440 SCR_DrawQWDownload
441 ==============
442 */
443 static int SCR_DrawQWDownload(int offset)
444 {
445         // sync with SCR_DownloadHeight
446         int len;
447         float x, y;
448         float size = 8;
449         char temp[256];
450
451         if (!cls.qw_downloadname[0])
452         {
453                 cls.qw_downloadspeedrate = 0;
454                 cls.qw_downloadspeedtime = realtime;
455                 cls.qw_downloadspeedcount = 0;
456                 return 0;
457         }
458         if (realtime >= cls.qw_downloadspeedtime + 1)
459         {
460                 cls.qw_downloadspeedrate = cls.qw_downloadspeedcount;
461                 cls.qw_downloadspeedtime = realtime;
462                 cls.qw_downloadspeedcount = 0;
463         }
464         if (cls.protocol == PROTOCOL_QUAKEWORLD)
465                 dpsnprintf(temp, sizeof(temp), "Downloading %s %3i%% (%i) at %i bytes/s\n", cls.qw_downloadname, cls.qw_downloadpercent, cls.qw_downloadmemorycursize, cls.qw_downloadspeedrate);
466         else
467                 dpsnprintf(temp, sizeof(temp), "Downloading %s %3i%% (%i/%i) at %i bytes/s\n", cls.qw_downloadname, cls.qw_downloadpercent, cls.qw_downloadmemorycursize, cls.qw_downloadmemorymaxsize, cls.qw_downloadspeedrate);
468         len = (int)strlen(temp);
469         x = (vid_conwidth.integer - DrawQ_TextWidth_Font(temp, len, 0, FONT_INFOBAR) * size) / 2;
470         y = vid_conheight.integer - size - offset;
471         DrawQ_Fill(0, y, vid_conwidth.integer, size, 0, 0, 0, cls.signon == SIGNONS ? 0.5 : 1, 0);
472         DrawQ_String_Font(x, y, temp, len, size, size, 1, 1, 1, 1, 0, NULL, true, FONT_INFOBAR);
473         return 8;
474 }
475
476 /*
477 ==============
478 SCR_DrawCurlDownload
479 ==============
480 */
481 static int SCR_DrawCurlDownload(int offset)
482 {
483         // sync with SCR_DownloadHeight
484         int len;
485         int nDownloads;
486         int i;
487         float x, y;
488         float size = 8;
489         Curl_downloadinfo_t *downinfo;
490         char temp[256];
491         const char *addinfo;
492
493         downinfo = Curl_GetDownloadInfo(&nDownloads, &addinfo);
494         if(!downinfo)
495                 return 0;
496
497         y = vid_conheight.integer - size * nDownloads - offset;
498
499         if(addinfo)
500         {
501                 len = (int)strlen(addinfo);
502                 x = (vid_conwidth.integer - DrawQ_TextWidth_Font(addinfo, len, false, FONT_INFOBAR) * size) / 2;
503                 DrawQ_Fill(0, y - size, vid_conwidth.integer, size, 1, 1, 1, cls.signon == SIGNONS ? 0.8 : 1, 0);
504                 DrawQ_String_Font(x, y - size, addinfo, len, size, size, 0, 0, 0, 1, 0, NULL, true, FONT_INFOBAR);
505         }
506
507         for(i = 0; i != nDownloads; ++i)
508         {
509                 if(downinfo[i].queued)
510                         dpsnprintf(temp, sizeof(temp), "Still in queue: %s\n", downinfo[i].filename);
511                 else if(downinfo[i].progress <= 0)
512                         dpsnprintf(temp, sizeof(temp), "Downloading %s ...  ???.?%% @ %.1f KiB/s\n", downinfo[i].filename, downinfo[i].speed / 1024.0);
513                 else
514                         dpsnprintf(temp, sizeof(temp), "Downloading %s ...  %5.1f%% @ %.1f KiB/s\n", downinfo[i].filename, 100.0 * downinfo[i].progress, downinfo[i].speed / 1024.0);
515                 len = (int)strlen(temp);
516                 x = (vid_conwidth.integer - DrawQ_TextWidth_Font(temp, len, false, FONT_INFOBAR) * size) / 2;
517                 DrawQ_Fill(0, y + i * size, vid_conwidth.integer, size, 0, 0, 0, cls.signon == SIGNONS ? 0.5 : 1, 0);
518                 DrawQ_String_Font(x, y + i * size, temp, len, size, size, 1, 1, 1, 1, 0, NULL, true, FONT_INFOBAR);
519         }
520
521         Z_Free(downinfo);
522
523         return 8 * (nDownloads + (addinfo ? 1 : 0));
524 }
525
526 /*
527 ==============
528 SCR_DrawDownload
529 ==============
530 */
531 static void SCR_DrawDownload()
532 {
533         int offset = 0;
534         offset += SCR_DrawQWDownload(offset);
535         offset += SCR_DrawCurlDownload(offset);
536         if(offset != scr_con_margin_bottom)
537                 Con_DPrintf("broken console margin calculation: %d != %d\n", offset, scr_con_margin_bottom);
538 }
539
540 static int SCR_DownloadHeight()
541 {
542         int offset = 0;
543         Curl_downloadinfo_t *downinfo;
544         const char *addinfo;
545         int nDownloads;
546
547         if(cls.qw_downloadname[0])
548                 offset += 0;
549
550         downinfo = Curl_GetDownloadInfo(&nDownloads, &addinfo);
551         if(downinfo)
552         {
553                 offset += 8 * (nDownloads + (addinfo ? 1 : 0));
554                 Z_Free(downinfo);
555         }
556
557         return offset;
558 }
559
560 //=============================================================================
561
562 /*
563 ==================
564 SCR_SetUpToDrawConsole
565 ==================
566 */
567 void SCR_SetUpToDrawConsole (void)
568 {
569         // lines of console to display
570         float conlines;
571         static int framecounter = 0;
572
573         Con_CheckResize ();
574
575         if (scr_menuforcewhiledisconnected.integer && key_dest == key_game && cls.state == ca_disconnected)
576         {
577                 if (framecounter >= 2)
578                         MR_ToggleMenu_f();
579                 else
580                         framecounter++;
581         }
582         else
583                 framecounter = 0;
584
585         if (scr_conforcewhiledisconnected.integer && key_dest == key_game && cls.signon != SIGNONS)
586                 key_consoleactive |= KEY_CONSOLEACTIVE_FORCED;
587         else
588                 key_consoleactive &= ~KEY_CONSOLEACTIVE_FORCED;
589
590 // decide on the height of the console
591         if (key_consoleactive & KEY_CONSOLEACTIVE_USER)
592                 conlines = vid_conheight.integer/2;     // half screen
593         else
594                 conlines = 0;                           // none visible
595
596         scr_con_current = conlines;
597 }
598
599 /*
600 ==================
601 SCR_DrawConsole
602 ==================
603 */
604 void SCR_DrawConsole (void)
605 {
606         scr_con_margin_bottom = SCR_DownloadHeight();
607         if (key_consoleactive & KEY_CONSOLEACTIVE_FORCED)
608         {
609                 // full screen
610                 Con_DrawConsole (vid_conheight.integer - scr_con_margin_bottom);
611         }
612         else if (scr_con_current)
613                 Con_DrawConsole (min((int)scr_con_current, vid_conheight.integer - scr_con_margin_bottom));
614         else
615                 con_vislines = 0;
616 }
617
618 /*
619 ===============
620 SCR_BeginLoadingPlaque
621
622 ================
623 */
624 void SCR_BeginLoadingPlaque (void)
625 {
626         // save console log up to this point to log_file if it was set by configs
627         Log_Start();
628
629         Host_StartVideo();
630         SCR_UpdateLoadingScreen(false);
631 }
632
633 //=============================================================================
634
635 char r_speeds_timestring[4096];
636 int speedstringcount, r_timereport_active;
637 double r_timereport_temp = 0, r_timereport_current = 0, r_timereport_start = 0;
638 int r_speeds_longestitem = 0;
639
640 void R_TimeReport(char *desc)
641 {
642         char tempbuf[256];
643         int length;
644         int t;
645
646         if (r_speeds.integer < 2 || !r_timereport_active)
647                 return;
648
649         CHECKGLERROR
650         if (r_speeds.integer == 2)
651                 qglFinish();
652         CHECKGLERROR
653         r_timereport_temp = r_timereport_current;
654         r_timereport_current = Sys_DoubleTime();
655         t = (int) ((r_timereport_current - r_timereport_temp) * 1000000.0 + 0.5);
656
657         length = dpsnprintf(tempbuf, sizeof(tempbuf), "%8i %s", t, desc);
658         length = min(length, (int)sizeof(tempbuf) - 1);
659         if (r_speeds_longestitem < length)
660                 r_speeds_longestitem = length;
661         for (;length < r_speeds_longestitem;length++)
662                 tempbuf[length] = ' ';
663         tempbuf[length] = 0;
664
665         if (speedstringcount + length > (vid_conwidth.integer / 8))
666         {
667                 strlcat(r_speeds_timestring, "\n", sizeof(r_speeds_timestring));
668                 speedstringcount = 0;
669         }
670         strlcat(r_speeds_timestring, tempbuf, sizeof(r_speeds_timestring));
671         speedstringcount += length;
672 }
673
674 void R_TimeReport_BeginFrame(void)
675 {
676         speedstringcount = 0;
677         r_speeds_timestring[0] = 0;
678         r_timereport_active = false;
679         memset(&r_refdef.stats, 0, sizeof(r_refdef.stats));
680
681         if (r_speeds.integer >= 2 && cls.signon == SIGNONS && cls.state == ca_connected)
682         {
683                 r_timereport_active = true;
684                 r_timereport_start = r_timereport_current = Sys_DoubleTime();
685         }
686 }
687
688 void R_TimeReport_EndFrame(void)
689 {
690         int i, j, lines, y;
691         cl_locnode_t *loc;
692         char string[1024+4096];
693
694         string[0] = 0;
695         if (r_speeds.integer && cls.signon == SIGNONS && cls.state == ca_connected)
696         {
697                 // put the location name in the r_speeds display as it greatly helps
698                 // when creating loc files
699                 loc = CL_Locs_FindNearest(cl.movement_origin);
700                 if (loc)
701                         sprintf(string + strlen(string), "Location: %s\n", loc->name);
702                 sprintf(string + strlen(string), "%3i renders org:'%+8.2f %+8.2f %+8.2f' dir:'%+2.3f %+2.3f %+2.3f'\n", r_refdef.stats.renders, r_refdef.view.origin[0], r_refdef.view.origin[1], r_refdef.view.origin[2], r_refdef.view.forward[0], r_refdef.view.forward[1], r_refdef.view.forward[2]);
703                 sprintf(string + strlen(string), "%7i surfaces%7i triangles %5i entities (%7i surfaces%7i triangles)\n", r_refdef.stats.world_surfaces, r_refdef.stats.world_triangles, r_refdef.stats.entities, r_refdef.stats.entities_surfaces, r_refdef.stats.entities_triangles);
704                 sprintf(string + strlen(string), "%5i leafs%5i portals%6i/%6i particles%6i/%6i decals %3i%% quality\n", r_refdef.stats.world_leafs, r_refdef.stats.world_portals, r_refdef.stats.particles, cl.num_particles, r_refdef.stats.decals, cl.num_decals, (int)(100 * r_refdef.view.quality));
705                 sprintf(string + strlen(string), "%7i lightmap updates (%7i pixels)\n", r_refdef.stats.lightmapupdates, r_refdef.stats.lightmapupdatepixels);
706                 sprintf(string + strlen(string), "%4i lights%4i clears%4i scissored%7i light%7i shadow%7i dynamic\n", r_refdef.stats.lights, r_refdef.stats.lights_clears, r_refdef.stats.lights_scissored, r_refdef.stats.lights_lighttriangles, r_refdef.stats.lights_shadowtriangles, r_refdef.stats.lights_dynamicshadowtriangles);
707                 if (r_refdef.stats.bloom)
708                         sprintf(string + strlen(string), "rendered%6i meshes%8i triangles bloompixels%8i copied%8i drawn\n", r_refdef.stats.meshes, r_refdef.stats.meshes_elements / 3, r_refdef.stats.bloom_copypixels, r_refdef.stats.bloom_drawpixels);
709                 else
710                         sprintf(string + strlen(string), "rendered%6i meshes%8i triangles\n", r_refdef.stats.meshes, r_refdef.stats.meshes_elements / 3);
711                 strlcat(string, r_speeds_timestring, sizeof(string));
712
713                 memset(&r_refdef.stats, 0, sizeof(r_refdef.stats));
714
715                 speedstringcount = 0;
716                 r_speeds_timestring[0] = 0;
717                 r_timereport_active = false;
718
719                 if (r_speeds.integer >= 2)
720                 {
721                         r_timereport_active = true;
722                         r_timereport_start = r_timereport_current = Sys_DoubleTime();
723                 }
724         }
725
726         if (string[0])
727         {
728                 if (string[strlen(string)-1] == '\n')
729                         string[strlen(string)-1] = 0;
730                 lines = 1;
731                 for (i = 0;string[i];i++)
732                         if (string[i] == '\n')
733                                 lines++;
734                 y = vid_conheight.integer - sb_lines - lines * 8;
735                 i = j = 0;
736                 DrawQ_Fill(0, y, vid_conwidth.integer, lines * 8, 0, 0, 0, 0.5, 0);
737                 while (string[i])
738                 {
739                         j = i;
740                         while (string[i] && string[i] != '\n')
741                                 i++;
742                         if (i - j > 0)
743                                 DrawQ_String(0, y, string + j, i - j, 8, 8, 1, 1, 1, 1, 0, NULL, true);
744                         if (string[i] == '\n')
745                                 i++;
746                         y += 8;
747                 }
748         }
749 }
750
751 /*
752 =================
753 SCR_SizeUp_f
754
755 Keybinding command
756 =================
757 */
758 void SCR_SizeUp_f (void)
759 {
760         Cvar_SetValue ("viewsize",scr_viewsize.value+10);
761 }
762
763
764 /*
765 =================
766 SCR_SizeDown_f
767
768 Keybinding command
769 =================
770 */
771 void SCR_SizeDown_f (void)
772 {
773         Cvar_SetValue ("viewsize",scr_viewsize.value-10);
774 }
775
776 void SCR_CaptureVideo_EndVideo(void);
777 void CL_Screen_Shutdown(void)
778 {
779         SCR_CaptureVideo_EndVideo();
780 }
781
782 void CL_Screen_Init(void)
783 {
784         Cvar_RegisterVariable (&scr_fov);
785         Cvar_RegisterVariable (&scr_viewsize);
786         Cvar_RegisterVariable (&scr_conalpha);
787         Cvar_RegisterVariable (&scr_conbrightness);
788         Cvar_RegisterVariable (&scr_conforcewhiledisconnected);
789         Cvar_RegisterVariable (&scr_menuforcewhiledisconnected);
790         Cvar_RegisterVariable (&scr_showram);
791         Cvar_RegisterVariable (&scr_showturtle);
792         Cvar_RegisterVariable (&scr_showpause);
793         Cvar_RegisterVariable (&scr_showbrand);
794         Cvar_RegisterVariable (&scr_centertime);
795         Cvar_RegisterVariable (&scr_printspeed);
796         Cvar_RegisterVariable (&vid_conwidth);
797         Cvar_RegisterVariable (&vid_conheight);
798         Cvar_RegisterVariable (&vid_pixelheight);
799         Cvar_RegisterVariable (&scr_screenshot_jpeg);
800         Cvar_RegisterVariable (&scr_screenshot_jpeg_quality);
801         Cvar_RegisterVariable (&scr_screenshot_gammaboost);
802         Cvar_RegisterVariable (&cl_capturevideo);
803         Cvar_RegisterVariable (&cl_capturevideo_width);
804         Cvar_RegisterVariable (&cl_capturevideo_height);
805         Cvar_RegisterVariable (&cl_capturevideo_realtime);
806         Cvar_RegisterVariable (&cl_capturevideo_fps);
807         Cvar_RegisterVariable (&cl_capturevideo_number);
808         Cvar_RegisterVariable (&r_letterbox);
809         Cvar_RegisterVariable(&r_stereo_separation);
810         Cvar_RegisterVariable(&r_stereo_sidebyside);
811         Cvar_RegisterVariable(&r_stereo_redblue);
812         Cvar_RegisterVariable(&r_stereo_redcyan);
813         Cvar_RegisterVariable(&r_stereo_redgreen);
814         Cvar_RegisterVariable(&r_stereo_angle);
815         Cvar_RegisterVariable(&scr_zoomwindow);
816         Cvar_RegisterVariable(&scr_zoomwindow_viewsizex);
817         Cvar_RegisterVariable(&scr_zoomwindow_viewsizey);
818         Cvar_RegisterVariable(&scr_zoomwindow_fov);
819         Cvar_RegisterVariable(&scr_stipple);
820         Cvar_RegisterVariable(&scr_refresh);
821         Cvar_RegisterVariable(&shownetgraph);
822
823         Cmd_AddCommand ("sizeup",SCR_SizeUp_f, "increase view size (increases viewsize cvar)");
824         Cmd_AddCommand ("sizedown",SCR_SizeDown_f, "decrease view size (decreases viewsize cvar)");
825         Cmd_AddCommand ("screenshot",SCR_ScreenShot_f, "takes a screenshot of the next rendered frame");
826         Cmd_AddCommand ("envmap", R_Envmap_f, "render a cubemap (skybox) of the current scene");
827
828         scr_initialized = true;
829 }
830
831 /*
832 ==================
833 SCR_ScreenShot_f
834 ==================
835 */
836 void SCR_ScreenShot_f (void)
837 {
838         static int shotnumber;
839         static char oldname[MAX_QPATH];
840         char base[MAX_QPATH];
841         char filename[MAX_QPATH];
842         unsigned char *buffer1;
843         unsigned char *buffer2;
844         unsigned char *buffer3;
845         qboolean jpeg = (scr_screenshot_jpeg.integer != 0);
846
847         sprintf (base, "screenshots/%s", scr_screenshot_name.string);
848
849         if (strcmp (oldname, scr_screenshot_name.string))
850         {
851                 sprintf(oldname, "%s", scr_screenshot_name.string);
852                 shotnumber = 0;
853         }
854
855         // find a file name to save it to
856         for (;shotnumber < 1000000;shotnumber++)
857                 if (!FS_SysFileExists(va("%s/%s%06d.tga", fs_gamedir, base, shotnumber)) && !FS_SysFileExists(va("%s/%s%06d.jpg", fs_gamedir, base, shotnumber)))
858                         break;
859         if (shotnumber >= 1000000)
860         {
861                 Con_Print("SCR_ScreenShot_f: Couldn't create the image file\n");
862                 return;
863         }
864
865         sprintf(filename, "%s%06d.%s", base, shotnumber, jpeg ? "jpg" : "tga");
866
867         buffer1 = (unsigned char *)Mem_Alloc(tempmempool, vid.width * vid.height * 3);
868         buffer2 = (unsigned char *)Mem_Alloc(tempmempool, vid.width * vid.height * 3);
869         buffer3 = (unsigned char *)Mem_Alloc(tempmempool, vid.width * vid.height * 3 + 18);
870
871         if (SCR_ScreenShot (filename, buffer1, buffer2, buffer3, 0, 0, vid.width, vid.height, false, false, false, jpeg, true))
872                 Con_Printf("Wrote %s\n", filename);
873         else
874                 Con_Printf("unable to write %s\n", filename);
875
876         Mem_Free (buffer1);
877         Mem_Free (buffer2);
878         Mem_Free (buffer3);
879
880         shotnumber++;
881 }
882
883 static void SCR_CaptureVideo_RIFF_Start(void)
884 {
885         memset(&cls.capturevideo.riffbuffer, 0, sizeof(sizebuf_t));
886         cls.capturevideo.riffbuffer.maxsize = sizeof(cls.capturevideo.riffbufferdata);
887         cls.capturevideo.riffbuffer.data = cls.capturevideo.riffbufferdata;
888 }
889
890 static void SCR_CaptureVideo_RIFF_Flush(void)
891 {
892         if (cls.capturevideo.riffbuffer.cursize > 0)
893         {
894                 if (!FS_Write(cls.capturevideo.videofile, cls.capturevideo.riffbuffer.data, cls.capturevideo.riffbuffer.cursize))
895                         cls.capturevideo.error = true;
896                 cls.capturevideo.riffbuffer.cursize = 0;
897                 cls.capturevideo.riffbuffer.overflowed = false;
898         }
899 }
900
901 static void SCR_CaptureVideo_RIFF_WriteBytes(const unsigned char *data, size_t size)
902 {
903         SCR_CaptureVideo_RIFF_Flush();
904         if (!FS_Write(cls.capturevideo.videofile, data, size))
905                 cls.capturevideo.error = true;
906 }
907
908 static void SCR_CaptureVideo_RIFF_Write32(int n)
909 {
910         if (cls.capturevideo.riffbuffer.cursize + 4 > cls.capturevideo.riffbuffer.maxsize)
911                 SCR_CaptureVideo_RIFF_Flush();
912         MSG_WriteLong(&cls.capturevideo.riffbuffer, n);
913 }
914
915 static void SCR_CaptureVideo_RIFF_Write16(int n)
916 {
917         if (cls.capturevideo.riffbuffer.cursize + 2 > cls.capturevideo.riffbuffer.maxsize)
918                 SCR_CaptureVideo_RIFF_Flush();
919         MSG_WriteShort(&cls.capturevideo.riffbuffer, n);
920 }
921
922 static void SCR_CaptureVideo_RIFF_WriteFourCC(const char *chunkfourcc)
923 {
924         if (cls.capturevideo.riffbuffer.cursize + (int)strlen(chunkfourcc) > cls.capturevideo.riffbuffer.maxsize)
925                 SCR_CaptureVideo_RIFF_Flush();
926         MSG_WriteUnterminatedString(&cls.capturevideo.riffbuffer, chunkfourcc);
927 }
928
929 static void SCR_CaptureVideo_RIFF_WriteTerminatedString(const char *string)
930 {
931         if (cls.capturevideo.riffbuffer.cursize + (int)strlen(string) > cls.capturevideo.riffbuffer.maxsize)
932                 SCR_CaptureVideo_RIFF_Flush();
933         MSG_WriteString(&cls.capturevideo.riffbuffer, string);
934 }
935
936 static fs_offset_t SCR_CaptureVideo_RIFF_GetPosition(void)
937 {
938         SCR_CaptureVideo_RIFF_Flush();
939         return FS_Tell(cls.capturevideo.videofile);
940 }
941
942 static void SCR_CaptureVideo_RIFF_Push(const char *chunkfourcc, const char *listtypefourcc)
943 {
944         SCR_CaptureVideo_RIFF_WriteFourCC(chunkfourcc);
945         SCR_CaptureVideo_RIFF_Write32(0);
946         SCR_CaptureVideo_RIFF_Flush();
947         cls.capturevideo.riffstackstartoffset[cls.capturevideo.riffstacklevel++] = SCR_CaptureVideo_RIFF_GetPosition();
948         if (listtypefourcc)
949                 SCR_CaptureVideo_RIFF_WriteFourCC(listtypefourcc);
950 }
951
952 static void SCR_CaptureVideo_RIFF_Pop(void)
953 {
954         fs_offset_t offset;
955         int x;
956         unsigned char sizebytes[4];
957         // write out the chunk size and then return to the current file position
958         cls.capturevideo.riffstacklevel--;
959         offset = SCR_CaptureVideo_RIFF_GetPosition();
960         x = (int)(offset - (cls.capturevideo.riffstackstartoffset[cls.capturevideo.riffstacklevel]));
961         sizebytes[0] = (x) & 0xff;sizebytes[1] = (x >> 8) & 0xff;sizebytes[2] = (x >> 16) & 0xff;sizebytes[3] = (x >> 24) & 0xff;
962         FS_Seek(cls.capturevideo.videofile, -(x + 4), SEEK_END);
963         FS_Write(cls.capturevideo.videofile, sizebytes, 4);
964         FS_Seek(cls.capturevideo.videofile, 0, SEEK_END);
965         if (offset & 1)
966         {
967                 unsigned char c = 0;
968                 FS_Write(cls.capturevideo.videofile, &c, 1);
969         }
970 }
971
972 static void GrowBuf(sizebuf_t *buf, int extralen)
973 {
974         if(buf->cursize + extralen > buf->maxsize)
975         {
976                 int oldsize = buf->maxsize;
977                 unsigned char *olddata;
978                 olddata = buf->data;
979                 buf->maxsize = max(buf->maxsize * 2, 4096);
980                 buf->data = Mem_Alloc(tempmempool, buf->maxsize);
981                 if(olddata)
982                 {
983                         memcpy(buf->data, olddata, oldsize);
984                         Mem_Free(olddata);
985                 }
986         }
987 }
988
989 static void SCR_CaptureVideo_RIFF_IndexEntry(const char *chunkfourcc, int chunksize, int flags)
990 {
991         if (cls.capturevideo.riffstacklevel != 2)
992                 Sys_Error("SCR_Capturevideo_RIFF_IndexEntry: RIFF stack level is %i (should be 2)\n", cls.capturevideo.riffstacklevel);
993         GrowBuf(&cls.capturevideo.riffindexbuffer, 16);
994         SCR_CaptureVideo_RIFF_Flush();
995         MSG_WriteUnterminatedString(&cls.capturevideo.riffindexbuffer, chunkfourcc);
996         MSG_WriteLong(&cls.capturevideo.riffindexbuffer, flags);
997         MSG_WriteLong(&cls.capturevideo.riffindexbuffer, (int)FS_Tell(cls.capturevideo.videofile) - cls.capturevideo.riffstackstartoffset[1]);
998         MSG_WriteLong(&cls.capturevideo.riffindexbuffer, chunksize);
999 }
1000
1001 static void SCR_CaptureVideo_RIFF_MakeIxChunk(const char *fcc, const char *dwChunkId, fs_offset_t masteridx_counter, int *masteridx_count, fs_offset_t masteridx_start)
1002 {
1003         int nMatching;
1004         int i;
1005         fs_offset_t ix = SCR_CaptureVideo_RIFF_GetPosition();
1006         fs_offset_t pos;
1007
1008         if(*masteridx_count >= AVI_MASTER_INDEX_SIZE)
1009                 return;
1010
1011         nMatching = 0; // go through index and enumerate them
1012         for(i = 0; i < cls.capturevideo.riffindexbuffer.cursize; i += 16)
1013                 if(!memcmp(cls.capturevideo.riffindexbuffer.data + i, dwChunkId, 4))
1014                         ++nMatching;
1015
1016         SCR_CaptureVideo_RIFF_Push(fcc, NULL);
1017         SCR_CaptureVideo_RIFF_Write16(2); // wLongsPerEntry
1018         SCR_CaptureVideo_RIFF_Write16(0x0100); // bIndexType=1, bIndexSubType=0
1019         SCR_CaptureVideo_RIFF_Write32(nMatching); // nEntriesInUse
1020         SCR_CaptureVideo_RIFF_WriteFourCC(dwChunkId); // dwChunkId
1021         SCR_CaptureVideo_RIFF_Write32(cls.capturevideo.videofile_ix_movistart & (fs_offset_t) 0xFFFFFFFFu);
1022         SCR_CaptureVideo_RIFF_Write32(((fs_offset_t) cls.capturevideo.videofile_ix_movistart) >> 32);
1023         SCR_CaptureVideo_RIFF_Write32(0); // dwReserved
1024
1025         for(i = 0; i < cls.capturevideo.riffindexbuffer.cursize; i += 16)
1026                 if(!memcmp(cls.capturevideo.riffindexbuffer.data + i, dwChunkId, 4))
1027                 {
1028                         unsigned int *p = (unsigned int *) (cls.capturevideo.riffindexbuffer.data + i);
1029                         unsigned int flags = p[1];
1030                         unsigned int rpos = p[2];
1031                         unsigned int size = p[3];
1032                         size &= ~0x80000000;
1033                         if(!(flags & 0x10)) // no keyframe?
1034                                 size |= 0x80000000;
1035                         SCR_CaptureVideo_RIFF_Write32(rpos + 8);
1036                         SCR_CaptureVideo_RIFF_Write32(size);
1037                 }
1038
1039         SCR_CaptureVideo_RIFF_Pop();
1040         pos = SCR_CaptureVideo_RIFF_GetPosition();
1041         SCR_CaptureVideo_RIFF_Flush();
1042
1043         FS_Seek(cls.capturevideo.videofile, masteridx_start + 16 * *masteridx_count, SEEK_SET);
1044         SCR_CaptureVideo_RIFF_Write32(ix & (fs_offset_t) 0xFFFFFFFFu);
1045         SCR_CaptureVideo_RIFF_Write32(((fs_offset_t) ix) >> 32);
1046         SCR_CaptureVideo_RIFF_Write32(pos - ix);
1047         SCR_CaptureVideo_RIFF_Write32(nMatching);
1048         SCR_CaptureVideo_RIFF_Flush();
1049
1050         FS_Seek(cls.capturevideo.videofile, masteridx_counter, SEEK_SET);
1051         SCR_CaptureVideo_RIFF_Write32(++*masteridx_count);
1052         SCR_CaptureVideo_RIFF_Flush();
1053
1054         FS_Seek(cls.capturevideo.videofile, 0, SEEK_END);
1055 }
1056
1057 static void SCR_CaptureVideo_RIFF_Finish(qboolean final)
1058 {
1059         // close the "movi" list
1060         SCR_CaptureVideo_RIFF_Pop();
1061         if(cls.capturevideo.videofile_ix_master_video_inuse_offset)
1062                 SCR_CaptureVideo_RIFF_MakeIxChunk("ix00", "00dc", cls.capturevideo.videofile_ix_master_video_inuse_offset, &cls.capturevideo.videofile_ix_master_video_inuse, cls.capturevideo.videofile_ix_master_video_start_offset);
1063         if(cls.capturevideo.videofile_ix_master_audio_inuse_offset)
1064                 SCR_CaptureVideo_RIFF_MakeIxChunk("ix01", "01wb", cls.capturevideo.videofile_ix_master_audio_inuse_offset, &cls.capturevideo.videofile_ix_master_audio_inuse, cls.capturevideo.videofile_ix_master_audio_start_offset);
1065         // write the idx1 chunk that we've been building while saving the frames (for old style players)
1066         if(final && cls.capturevideo.videofile_firstchunkframes_offset)
1067         // TODO replace index creating by OpenDML ix##/##ix/indx chunk so it works for more than one AVI part too
1068         {
1069                 SCR_CaptureVideo_RIFF_Push("idx1", NULL);
1070                 SCR_CaptureVideo_RIFF_WriteBytes(cls.capturevideo.riffindexbuffer.data, cls.capturevideo.riffindexbuffer.cursize);
1071                 SCR_CaptureVideo_RIFF_Pop();
1072         }
1073         cls.capturevideo.riffindexbuffer.cursize = 0;
1074         // pop the RIFF chunk itself
1075         while (cls.capturevideo.riffstacklevel > 0)
1076                 SCR_CaptureVideo_RIFF_Pop();
1077         SCR_CaptureVideo_RIFF_Flush();
1078         if(cls.capturevideo.videofile_firstchunkframes_offset)
1079         {
1080                 Con_DPrintf("Finishing first chunk (%d frames)\n", cls.capturevideo.frame);
1081                 FS_Seek(cls.capturevideo.videofile, cls.capturevideo.videofile_firstchunkframes_offset, SEEK_SET);
1082                 SCR_CaptureVideo_RIFF_Write32(cls.capturevideo.frame);
1083                 SCR_CaptureVideo_RIFF_Flush();
1084                 FS_Seek(cls.capturevideo.videofile, 0, SEEK_END);
1085                 cls.capturevideo.videofile_firstchunkframes_offset = 0;
1086         }
1087         else
1088                 Con_DPrintf("Finishing another chunk (%d frames)\n", cls.capturevideo.frame);
1089 }
1090
1091 static void SCR_CaptureVideo_RIFF_OverflowCheck(int framesize)
1092 {
1093         fs_offset_t cursize, curfilesize;
1094         if (cls.capturevideo.riffstacklevel != 2)
1095                 Sys_Error("SCR_CaptureVideo_RIFF_OverflowCheck: chunk stack leakage!\n");
1096         // check where we are in the file
1097         SCR_CaptureVideo_RIFF_Flush();
1098         cursize = SCR_CaptureVideo_RIFF_GetPosition() - cls.capturevideo.riffstackstartoffset[0];
1099         curfilesize = SCR_CaptureVideo_RIFF_GetPosition();
1100
1101         // if this would overflow the windows limit of 1GB per RIFF chunk, we need
1102         // to close the current RIFF chunk and open another for future frames
1103         if (8 + cursize + framesize + cls.capturevideo.riffindexbuffer.cursize + 8 + cls.capturevideo.riffindexbuffer.cursize + 64 > 1<<30) // note that the Ix buffer takes less space... I just don't dare to / 2 here now... sorry, maybe later
1104         {
1105                 SCR_CaptureVideo_RIFF_Finish(false);
1106                 // begin a new 1GB extended section of the AVI
1107                 SCR_CaptureVideo_RIFF_Push("RIFF", "AVIX");
1108                 SCR_CaptureVideo_RIFF_Push("LIST", "movi");
1109                 cls.capturevideo.videofile_ix_movistart = cls.capturevideo.riffstackstartoffset[1];
1110         }
1111 }
1112
1113 static void FindFraction(double val, int *num, int *denom, int denomMax)
1114 {
1115         int i;
1116         double bestdiff;
1117         // initialize
1118         bestdiff = fabs(val);
1119         *num = 0;
1120         *denom = 1;
1121
1122         for(i = 1; i <= denomMax; ++i)
1123         {
1124                 int inum = floor(0.5 + val * i);
1125                 double diff = fabs(val - inum / (double)i);
1126                 if(diff < bestdiff)
1127                 {
1128                         bestdiff = diff;
1129                         *num = inum;
1130                         *denom = i;
1131                 }
1132         }
1133 }
1134
1135 void SCR_CaptureVideo_BeginVideo(void)
1136 {
1137         double gamma, g, aspect;
1138         int width = cl_capturevideo_width.integer, height = cl_capturevideo_height.integer;
1139         int n, d;
1140         unsigned int i;
1141         if (cls.capturevideo.active)
1142                 return;
1143         memset(&cls.capturevideo, 0, sizeof(cls.capturevideo));
1144         // soundrate is figured out on the first SoundFrame
1145
1146         if(width == 0 && height != 0)
1147                 width = (int) (height * (double)vid.width / ((double)vid.height * vid_pixelheight.value)); // keep aspect
1148         if(width != 0 && height == 0)
1149                 height = (int) (width * ((double)vid.height * vid_pixelheight.value) / (double)vid.width); // keep aspect
1150
1151         if(width < 2 || width > vid.width) // can't scale up
1152                 width = vid.width;
1153         if(height < 2 || height > vid.height) // can't scale up
1154                 height = vid.height;
1155
1156         aspect = vid.width / (vid.height * vid_pixelheight.value);
1157
1158         // ensure it's all even; if not, scale down a little
1159         if(width % 1)
1160                 --width;
1161         if(height % 1)
1162                 --height;
1163
1164         cls.capturevideo.width = width;
1165         cls.capturevideo.height = height;
1166         cls.capturevideo.active = true;
1167         cls.capturevideo.starttime = realtime;
1168         cls.capturevideo.framerate = bound(1, cl_capturevideo_fps.value, 1000);
1169         cls.capturevideo.soundrate = S_GetSoundRate();
1170         cls.capturevideo.frame = 0;
1171         cls.capturevideo.soundsampleframe = 0;
1172         cls.capturevideo.realtime = cl_capturevideo_realtime.integer != 0;
1173         cls.capturevideo.screenbuffer = (unsigned char *)Mem_Alloc(tempmempool, vid.width * vid.height * 4);
1174         cls.capturevideo.outbuffer = (unsigned char *)Mem_Alloc(tempmempool, width * height * (4+4) + 18);
1175         gamma = 1.0/scr_screenshot_gammaboost.value;
1176         dpsnprintf(cls.capturevideo.basename, sizeof(cls.capturevideo.basename), "video/dpvideo%03i", cl_capturevideo_number.integer);
1177         Cvar_SetValueQuick(&cl_capturevideo_number, cl_capturevideo_number.integer + 1);
1178
1179         /*
1180         for (i = 0;i < 256;i++)
1181         {
1182                 unsigned char j = (unsigned char)bound(0, 255*pow(i/255.0, gamma), 255);
1183                 cls.capturevideo.rgbgammatable[0][i] = j;
1184                 cls.capturevideo.rgbgammatable[1][i] = j;
1185                 cls.capturevideo.rgbgammatable[2][i] = j;
1186         }
1187         */
1188 /*
1189 R = Y + 1.4075 * (Cr - 128);
1190 G = Y + -0.3455 * (Cb - 128) + -0.7169 * (Cr - 128);
1191 B = Y + 1.7790 * (Cb - 128);
1192 Y = R *  .299 + G *  .587 + B *  .114;
1193 Cb = R * -.169 + G * -.332 + B *  .500 + 128.;
1194 Cr = R *  .500 + G * -.419 + B * -.0813 + 128.;
1195 */
1196         for (i = 0;i < 256;i++)
1197         {
1198                 g = 255*pow(i/255.0, gamma);
1199                 // Y weights from RGB
1200                 cls.capturevideo.rgbtoyuvscaletable[0][0][i] = (short)(g *  0.299);
1201                 cls.capturevideo.rgbtoyuvscaletable[0][1][i] = (short)(g *  0.587);
1202                 cls.capturevideo.rgbtoyuvscaletable[0][2][i] = (short)(g *  0.114);
1203                 // Cb weights from RGB
1204                 cls.capturevideo.rgbtoyuvscaletable[1][0][i] = (short)(g * -0.169);
1205                 cls.capturevideo.rgbtoyuvscaletable[1][1][i] = (short)(g * -0.332);
1206                 cls.capturevideo.rgbtoyuvscaletable[1][2][i] = (short)(g *  0.500);
1207                 // Cr weights from RGB
1208                 cls.capturevideo.rgbtoyuvscaletable[2][0][i] = (short)(g *  0.500);
1209                 cls.capturevideo.rgbtoyuvscaletable[2][1][i] = (short)(g * -0.419);
1210                 cls.capturevideo.rgbtoyuvscaletable[2][2][i] = (short)(g * -0.0813);
1211                 // range reduction of YCbCr to valid signal range
1212                 cls.capturevideo.yuvnormalizetable[0][i] = 16 + i * (236-16) / 256;
1213                 cls.capturevideo.yuvnormalizetable[1][i] = 16 + i * (240-16) / 256;
1214                 cls.capturevideo.yuvnormalizetable[2][i] = 16 + i * (240-16) / 256;
1215         }
1216
1217         //if (cl_capturevideo_)
1218         //{
1219         //}
1220         //else
1221         {
1222                 cls.capturevideo.format = CAPTUREVIDEOFORMAT_AVI_I420;
1223                 cls.capturevideo.videofile = FS_Open (va("%s.avi", cls.capturevideo.basename), "wb", false, true);
1224                 SCR_CaptureVideo_RIFF_Start();
1225                 // enclosing RIFF chunk (there can be multiple of these in >1GB files, the later ones are "AVIX" instead of "AVI " and have no header/stream info)
1226                 SCR_CaptureVideo_RIFF_Push("RIFF", "AVI ");
1227                 // AVI main header
1228                 SCR_CaptureVideo_RIFF_Push("LIST", "hdrl");
1229                 SCR_CaptureVideo_RIFF_Push("avih", NULL);
1230                 SCR_CaptureVideo_RIFF_Write32((int)(1000000.0 / cls.capturevideo.framerate)); // microseconds per frame
1231                 SCR_CaptureVideo_RIFF_Write32(0); // max bytes per second
1232                 SCR_CaptureVideo_RIFF_Write32(0); // padding granularity
1233                 SCR_CaptureVideo_RIFF_Write32(0x910); // flags (AVIF_HASINDEX | AVIF_ISINTERLEAVED | AVIF_TRUSTCKTYPE)
1234                 cls.capturevideo.videofile_firstchunkframes_offset = SCR_CaptureVideo_RIFF_GetPosition();
1235                 SCR_CaptureVideo_RIFF_Write32(0); // total frames
1236                 SCR_CaptureVideo_RIFF_Write32(0); // initial frames
1237                 if (cls.capturevideo.soundrate)
1238                         SCR_CaptureVideo_RIFF_Write32(2); // number of streams
1239                 else
1240                         SCR_CaptureVideo_RIFF_Write32(1); // number of streams
1241                 SCR_CaptureVideo_RIFF_Write32(0); // suggested buffer size
1242                 SCR_CaptureVideo_RIFF_Write32(width); // width
1243                 SCR_CaptureVideo_RIFF_Write32(height); // height
1244                 SCR_CaptureVideo_RIFF_Write32(0); // reserved[0]
1245                 SCR_CaptureVideo_RIFF_Write32(0); // reserved[1]
1246                 SCR_CaptureVideo_RIFF_Write32(0); // reserved[2]
1247                 SCR_CaptureVideo_RIFF_Write32(0); // reserved[3]
1248                 SCR_CaptureVideo_RIFF_Pop();
1249                 // video stream info
1250                 SCR_CaptureVideo_RIFF_Push("LIST", "strl");
1251                 SCR_CaptureVideo_RIFF_Push("strh", "vids");
1252                 SCR_CaptureVideo_RIFF_WriteFourCC("I420"); // stream fourcc (I420 colorspace, uncompressed)
1253                 SCR_CaptureVideo_RIFF_Write32(0); // flags
1254                 SCR_CaptureVideo_RIFF_Write16(0); // priority
1255                 SCR_CaptureVideo_RIFF_Write16(0); // language
1256                 SCR_CaptureVideo_RIFF_Write32(0); // initial frames
1257                 // find an ideal divisor for the framerate
1258                 FindFraction(cls.capturevideo.framerate, &n, &d, 1000);
1259                 SCR_CaptureVideo_RIFF_Write32(d); // samples/second divisor
1260                 SCR_CaptureVideo_RIFF_Write32(n); // samples/second multiplied by divisor
1261                 SCR_CaptureVideo_RIFF_Write32(0); // start
1262                 cls.capturevideo.videofile_totalframes_offset1 = SCR_CaptureVideo_RIFF_GetPosition();
1263                 SCR_CaptureVideo_RIFF_Write32(0); // length
1264                 SCR_CaptureVideo_RIFF_Write32(width*height+(width/2)*(height/2)*2); // suggested buffer size
1265                 SCR_CaptureVideo_RIFF_Write32(0); // quality
1266                 SCR_CaptureVideo_RIFF_Write32(0); // sample size
1267                 SCR_CaptureVideo_RIFF_Write16(0); // frame left
1268                 SCR_CaptureVideo_RIFF_Write16(0); // frame top
1269                 SCR_CaptureVideo_RIFF_Write16(width); // frame right
1270                 SCR_CaptureVideo_RIFF_Write16(height); // frame bottom
1271                 SCR_CaptureVideo_RIFF_Pop();
1272                 // video stream format
1273                 SCR_CaptureVideo_RIFF_Push("strf", NULL);
1274                 SCR_CaptureVideo_RIFF_Write32(40); // BITMAPINFO struct size
1275                 SCR_CaptureVideo_RIFF_Write32(width); // width
1276                 SCR_CaptureVideo_RIFF_Write32(height); // height
1277                 SCR_CaptureVideo_RIFF_Write16(3); // planes
1278                 SCR_CaptureVideo_RIFF_Write16(12); // bitcount
1279                 SCR_CaptureVideo_RIFF_WriteFourCC("I420"); // compression
1280                 SCR_CaptureVideo_RIFF_Write32(width*height+(width/2)*(height/2)*2); // size of image
1281                 SCR_CaptureVideo_RIFF_Write32(0); // x pixels per meter
1282                 SCR_CaptureVideo_RIFF_Write32(0); // y pixels per meter
1283                 SCR_CaptureVideo_RIFF_Write32(0); // color used
1284                 SCR_CaptureVideo_RIFF_Write32(0); // color important
1285                 SCR_CaptureVideo_RIFF_Pop();
1286                 // master index
1287                 SCR_CaptureVideo_RIFF_Push("indx", NULL);
1288                 SCR_CaptureVideo_RIFF_Write16(4); // wLongsPerEntry
1289                 SCR_CaptureVideo_RIFF_Write16(0); // bIndexSubType=0, bIndexType=0
1290                 cls.capturevideo.videofile_ix_master_video_inuse_offset = SCR_CaptureVideo_RIFF_GetPosition();
1291                 SCR_CaptureVideo_RIFF_Write32(0); // nEntriesInUse
1292                 SCR_CaptureVideo_RIFF_WriteFourCC("00dc"); // dwChunkId
1293                 SCR_CaptureVideo_RIFF_Write32(0); // dwReserved1
1294                 SCR_CaptureVideo_RIFF_Write32(0); // dwReserved2
1295                 SCR_CaptureVideo_RIFF_Write32(0); // dwReserved3
1296                 cls.capturevideo.videofile_ix_master_video_start_offset = SCR_CaptureVideo_RIFF_GetPosition();
1297                 for(i = 0; i < AVI_MASTER_INDEX_SIZE * 4; ++i)
1298                         SCR_CaptureVideo_RIFF_Write32(0); // fill up later
1299                 SCR_CaptureVideo_RIFF_Pop();
1300                 // extended format (aspect!)
1301                 SCR_CaptureVideo_RIFF_Push("vprp", NULL);
1302                 SCR_CaptureVideo_RIFF_Write32(0); // VideoFormatToken
1303                 SCR_CaptureVideo_RIFF_Write32(0); // VideoStandard
1304                 SCR_CaptureVideo_RIFF_Write32((int)cls.capturevideo.framerate); // dwVerticalRefreshRate (bogus)
1305                 SCR_CaptureVideo_RIFF_Write32(width); // dwHTotalInT
1306                 SCR_CaptureVideo_RIFF_Write32(height); // dwVTotalInLines
1307                 FindFraction(aspect, &n, &d, 1000);
1308                 SCR_CaptureVideo_RIFF_Write32((n << 16) | d); // dwFrameAspectRatio // TODO a word
1309                 SCR_CaptureVideo_RIFF_Write32(width); // dwFrameWidthInPixels
1310                 SCR_CaptureVideo_RIFF_Write32(height); // dwFrameHeightInLines
1311                 SCR_CaptureVideo_RIFF_Write32(1); // nFieldPerFrame
1312                 SCR_CaptureVideo_RIFF_Write32(width); // CompressedBMWidth
1313                 SCR_CaptureVideo_RIFF_Write32(height); // CompressedBMHeight
1314                 SCR_CaptureVideo_RIFF_Write32(width); // ValidBMHeight
1315                 SCR_CaptureVideo_RIFF_Write32(height); // ValidBMWidth
1316                 SCR_CaptureVideo_RIFF_Write32(0); // ValidBMXOffset
1317                 SCR_CaptureVideo_RIFF_Write32(0); // ValidBMYOffset
1318                 SCR_CaptureVideo_RIFF_Write32(0); // ValidBMXOffsetInT
1319                 SCR_CaptureVideo_RIFF_Write32(0); // ValidBMYValidStartLine
1320                 SCR_CaptureVideo_RIFF_Pop();
1321                 SCR_CaptureVideo_RIFF_Pop();
1322                 if (cls.capturevideo.soundrate)
1323                 {
1324                         // audio stream info
1325                         SCR_CaptureVideo_RIFF_Push("LIST", "strl");
1326                         SCR_CaptureVideo_RIFF_Push("strh", "auds");
1327                         SCR_CaptureVideo_RIFF_Write32(1); // stream fourcc (PCM audio, uncompressed)
1328                         SCR_CaptureVideo_RIFF_Write32(0); // flags
1329                         SCR_CaptureVideo_RIFF_Write16(0); // priority
1330                         SCR_CaptureVideo_RIFF_Write16(0); // language
1331                         SCR_CaptureVideo_RIFF_Write32(0); // initial frames
1332                         SCR_CaptureVideo_RIFF_Write32(1); // samples/second divisor
1333                         SCR_CaptureVideo_RIFF_Write32((int)(cls.capturevideo.soundrate)); // samples/second multiplied by divisor
1334                         SCR_CaptureVideo_RIFF_Write32(0); // start
1335                         cls.capturevideo.videofile_totalsampleframes_offset = SCR_CaptureVideo_RIFF_GetPosition();
1336                         SCR_CaptureVideo_RIFF_Write32(0); // length
1337                         SCR_CaptureVideo_RIFF_Write32(cls.capturevideo.soundrate * 2); // suggested buffer size (this is a half second)
1338                         SCR_CaptureVideo_RIFF_Write32(0); // quality
1339                         SCR_CaptureVideo_RIFF_Write32(4); // sample size
1340                         SCR_CaptureVideo_RIFF_Write16(0); // frame left
1341                         SCR_CaptureVideo_RIFF_Write16(0); // frame top
1342                         SCR_CaptureVideo_RIFF_Write16(0); // frame right
1343                         SCR_CaptureVideo_RIFF_Write16(0); // frame bottom
1344                         SCR_CaptureVideo_RIFF_Pop();
1345                         // audio stream format
1346                         SCR_CaptureVideo_RIFF_Push("strf", NULL);
1347                         SCR_CaptureVideo_RIFF_Write16(1); // format (uncompressed PCM?)
1348                         SCR_CaptureVideo_RIFF_Write16(2); // channels (stereo)
1349                         SCR_CaptureVideo_RIFF_Write32(cls.capturevideo.soundrate); // sampleframes per second
1350                         SCR_CaptureVideo_RIFF_Write32(cls.capturevideo.soundrate * 4); // average bytes per second
1351                         SCR_CaptureVideo_RIFF_Write16(4); // block align
1352                         SCR_CaptureVideo_RIFF_Write16(16); // bits per sample
1353                         SCR_CaptureVideo_RIFF_Write16(0); // size
1354                         SCR_CaptureVideo_RIFF_Pop();
1355                         // master index
1356                         SCR_CaptureVideo_RIFF_Push("indx", NULL);
1357                         SCR_CaptureVideo_RIFF_Write16(4); // wLongsPerEntry
1358                         SCR_CaptureVideo_RIFF_Write16(0); // bIndexSubType=0, bIndexType=0
1359                         cls.capturevideo.videofile_ix_master_audio_inuse_offset = SCR_CaptureVideo_RIFF_GetPosition();
1360                         SCR_CaptureVideo_RIFF_Write32(0); // nEntriesInUse
1361                         SCR_CaptureVideo_RIFF_WriteFourCC("01wb"); // dwChunkId
1362                         SCR_CaptureVideo_RIFF_Write32(0); // dwReserved1
1363                         SCR_CaptureVideo_RIFF_Write32(0); // dwReserved2
1364                         SCR_CaptureVideo_RIFF_Write32(0); // dwReserved3
1365                         cls.capturevideo.videofile_ix_master_audio_start_offset = SCR_CaptureVideo_RIFF_GetPosition();
1366                         for(i = 0; i < AVI_MASTER_INDEX_SIZE * 4; ++i)
1367                                 SCR_CaptureVideo_RIFF_Write32(0); // fill up later
1368                         SCR_CaptureVideo_RIFF_Pop();
1369                         SCR_CaptureVideo_RIFF_Pop();
1370                 }
1371
1372                 cls.capturevideo.videofile_ix_master_audio_inuse = cls.capturevideo.videofile_ix_master_video_inuse = 0;
1373
1374                 // extended header (for total #frames)
1375                 SCR_CaptureVideo_RIFF_Push("LIST", "odml");
1376                 SCR_CaptureVideo_RIFF_Push("dmlh", NULL);
1377                 cls.capturevideo.videofile_totalframes_offset2 = SCR_CaptureVideo_RIFF_GetPosition();
1378                 SCR_CaptureVideo_RIFF_Write32(0);
1379                 SCR_CaptureVideo_RIFF_Pop();
1380                 SCR_CaptureVideo_RIFF_Pop();
1381
1382                 // close the AVI header list
1383                 SCR_CaptureVideo_RIFF_Pop();
1384                 // software that produced this AVI video file
1385                 SCR_CaptureVideo_RIFF_Push("LIST", "INFO");
1386                 SCR_CaptureVideo_RIFF_Push("ISFT", NULL);
1387                 SCR_CaptureVideo_RIFF_WriteTerminatedString(engineversion);
1388                 SCR_CaptureVideo_RIFF_Pop();
1389                 // enable this junk filler if you like the LIST movi to always begin at 4KB in the file (why?)
1390 #if 0
1391                 SCR_CaptureVideo_RIFF_Push("JUNK", NULL);
1392                 x = 4096 - SCR_CaptureVideo_RIFF_GetPosition();
1393                 while (x > 0)
1394                 {
1395                         const char *junkfiller = "[ DarkPlaces junk data ]";
1396                         int i = min(x, (int)strlen(junkfiller));
1397                         SCR_CaptureVideo_RIFF_WriteBytes((const unsigned char *)junkfiller, i);
1398                         x -= i;
1399                 }
1400                 SCR_CaptureVideo_RIFF_Pop();
1401 #endif
1402                 SCR_CaptureVideo_RIFF_Pop();
1403                 // begin the actual video section now
1404                 SCR_CaptureVideo_RIFF_Push("LIST", "movi");
1405                 cls.capturevideo.videofile_ix_movistart = cls.capturevideo.riffstackstartoffset[1];
1406                 // we're done with the headers now...
1407                 SCR_CaptureVideo_RIFF_Flush();
1408                 if (cls.capturevideo.riffstacklevel != 2)
1409                         Sys_Error("SCR_CaptureVideo_BeginVideo: broken AVI writing code (stack level is %i (should be 2) at end of headers)\n", cls.capturevideo.riffstacklevel);
1410         }
1411
1412         switch(cls.capturevideo.format)
1413         {
1414         case CAPTUREVIDEOFORMAT_AVI_I420:
1415                 break;
1416         default:
1417                 break;
1418         }
1419 }
1420
1421 void SCR_CaptureVideo_EndVideo(void)
1422 {
1423         if (!cls.capturevideo.active)
1424                 return;
1425         cls.capturevideo.active = false;
1426         if (cls.capturevideo.videofile)
1427         {
1428                 switch(cls.capturevideo.format)
1429                 {
1430                 case CAPTUREVIDEOFORMAT_AVI_I420:
1431                         // close any open chunks
1432                         SCR_CaptureVideo_RIFF_Finish(true);
1433                         // go back and fix the video frames and audio samples fields
1434                         Con_DPrintf("Finishing capture (%d frames, %d audio frames)\n", cls.capturevideo.frame, cls.capturevideo.soundsampleframe);
1435                         FS_Seek(cls.capturevideo.videofile, cls.capturevideo.videofile_totalframes_offset1, SEEK_SET);
1436                         SCR_CaptureVideo_RIFF_Write32(cls.capturevideo.frame);
1437                         SCR_CaptureVideo_RIFF_Flush();
1438                         FS_Seek(cls.capturevideo.videofile, cls.capturevideo.videofile_totalframes_offset2, SEEK_SET);
1439                         SCR_CaptureVideo_RIFF_Write32(cls.capturevideo.frame);
1440                         SCR_CaptureVideo_RIFF_Flush();
1441                         if (cls.capturevideo.soundrate)
1442                         {
1443                                 FS_Seek(cls.capturevideo.videofile, cls.capturevideo.videofile_totalsampleframes_offset, SEEK_SET);
1444                                 SCR_CaptureVideo_RIFF_Write32(cls.capturevideo.soundsampleframe);
1445                                 SCR_CaptureVideo_RIFF_Flush();
1446                         }
1447                         break;
1448                 default:
1449                         break;
1450                 }
1451                 FS_Close(cls.capturevideo.videofile);
1452                 cls.capturevideo.videofile = NULL;
1453         }
1454
1455         if (cls.capturevideo.screenbuffer)
1456         {
1457                 Mem_Free (cls.capturevideo.screenbuffer);
1458                 cls.capturevideo.screenbuffer = NULL;
1459         }
1460
1461         if (cls.capturevideo.outbuffer)
1462         {
1463                 Mem_Free (cls.capturevideo.outbuffer);
1464                 cls.capturevideo.outbuffer = NULL;
1465         }
1466
1467         if (cls.capturevideo.riffindexbuffer.data)
1468         {
1469                 Mem_Free(cls.capturevideo.riffindexbuffer.data);
1470                 cls.capturevideo.riffindexbuffer.data = NULL;
1471         }
1472
1473         memset(&cls.capturevideo, 0, sizeof(cls.capturevideo));
1474 }
1475
1476 // converts from BGRA32 to I420 colorspace (identical to YV12 except chroma plane order is reversed), this colorspace is handled by the Intel(r) 4:2:0 codec on Windows
1477 void SCR_CaptureVideo_ConvertFrame_BGRA_to_I420_flip(int width, int height, unsigned char *instart, unsigned char *outstart)
1478 {
1479         int x, y;
1480         int blockr, blockg, blockb;
1481         int outoffset = (width/2)*(height/2);
1482         unsigned char *b, *out;
1483         // process one line at a time, and CbCr every other line at 2 pixel intervals
1484         for (y = 0;y < height;y++)
1485         {
1486                 // 1x1 Y
1487                 for (b = instart + (height-1-y)*width*4, out = outstart + y*width, x = 0;x < width;x++, b += 4, out++)
1488                 {
1489                         blockr = b[2];
1490                         blockg = b[1];
1491                         blockb = b[0];
1492                         *out = cls.capturevideo.yuvnormalizetable[0][cls.capturevideo.rgbtoyuvscaletable[0][0][blockr] + cls.capturevideo.rgbtoyuvscaletable[0][1][blockg] + cls.capturevideo.rgbtoyuvscaletable[0][2][blockb]];
1493                 }
1494                 if ((y & 1) == 0)
1495                 {
1496                         // 2x2 Cr and Cb planes
1497                         int inpitch = width*4;
1498                         for (b = instart + (height-2-y)*width*4, out = outstart + width*height + (y/2)*(width/2), x = 0;x < width/2;x++, b += 8, out++)
1499                         {
1500                                 blockr = (b[2] + b[6] + b[inpitch+2] + b[inpitch+6]) >> 2;
1501                                 blockg = (b[1] + b[5] + b[inpitch+1] + b[inpitch+5]) >> 2;
1502                                 blockb = (b[0] + b[4] + b[inpitch+0] + b[inpitch+4]) >> 2;
1503                                 // Cr
1504                                 out[0        ] = cls.capturevideo.yuvnormalizetable[1][cls.capturevideo.rgbtoyuvscaletable[1][0][blockr] + cls.capturevideo.rgbtoyuvscaletable[1][1][blockg] + cls.capturevideo.rgbtoyuvscaletable[1][2][blockb] + 128];
1505                                 // Cb
1506                                 out[outoffset] = cls.capturevideo.yuvnormalizetable[2][cls.capturevideo.rgbtoyuvscaletable[2][0][blockr] + cls.capturevideo.rgbtoyuvscaletable[2][1][blockg] + cls.capturevideo.rgbtoyuvscaletable[2][2][blockb] + 128];
1507                         }
1508                 }
1509         }
1510 }
1511
1512 static void SCR_ScaleDownBGRA(unsigned char *in, int inw, int inh, unsigned char *out, int outw, int outh)
1513 {
1514         // TODO optimize this function
1515
1516         int x, y;
1517         float area;
1518
1519         // memcpy is faster than me
1520         if(inw == outw && inh == outh)
1521         {
1522                 memcpy(out, in, 4 * inw * inh);
1523                 return;
1524         }
1525
1526         // otherwise: a box filter
1527         area = (float)outw * (float)outh / (float)inw / (float)inh;
1528         for(y = 0; y < outh; ++y)
1529         {
1530                 float iny0 =  y    / (float)outh * inh; int iny0_i = floor(iny0);
1531                 float iny1 = (y+1) / (float)outh * inh; int iny1_i = ceil(iny1);
1532                 for(x = 0; x < outw; ++x)
1533                 {
1534                         float inx0 =  x    / (float)outw * inw; int inx0_i = floor(inx0);
1535                         float inx1 = (x+1) / (float)outw * inw; int inx1_i = ceil(inx1);
1536                         float r = 0, g = 0, b = 0, alpha = 0;
1537                         int xx, yy;
1538
1539                         for(yy = iny0_i; yy < iny1_i; ++yy)
1540                         {
1541                                 float ya = min(yy+1, iny1) - max(iny0, yy);
1542                                 for(xx = inx0_i; xx < inx1_i; ++xx)
1543                                 {
1544                                         float a = ya * (min(xx+1, inx1) - max(inx0, xx));
1545                                         r += a * in[4*(xx + inw * yy)+0];
1546                                         g += a * in[4*(xx + inw * yy)+1];
1547                                         b += a * in[4*(xx + inw * yy)+2];
1548                                         alpha += a * in[4*(xx + inw * yy)+3];
1549                                 }
1550                         }
1551
1552                         out[4*(x + outw * y)+0] = r * area;
1553                         out[4*(x + outw * y)+1] = g * area;
1554                         out[4*(x + outw * y)+2] = b * area;
1555                         out[4*(x + outw * y)+3] = alpha * area;
1556                 }
1557         }
1558 }
1559
1560 qboolean SCR_CaptureVideo_VideoFrame(int newframenum)
1561 {
1562         int x = 0, y = 0, width = cls.capturevideo.width, height = cls.capturevideo.height;
1563         unsigned char *in, *out;
1564         CHECKGLERROR
1565         //return SCR_ScreenShot(filename, cls.capturevideo.buffer, cls.capturevideo.buffer + vid.width * vid.height * 3, cls.capturevideo.buffer + vid.width * vid.height * 6, 0, 0, vid.width, vid.height, false, false, false, jpeg, true);
1566         // speed is critical here, so do saving as directly as possible
1567         switch (cls.capturevideo.format)
1568         {
1569         case CAPTUREVIDEOFORMAT_AVI_I420:
1570                 // if there's no videofile we have to just give up, and abort saving
1571                 if (!cls.capturevideo.videofile)
1572                         return false;
1573                 // FIXME: width/height must be multiple of 2, enforce this?
1574                 qglReadPixels (x, y, vid.width, vid.height, GL_BGRA, GL_UNSIGNED_BYTE, cls.capturevideo.screenbuffer);CHECKGLERROR
1575                 SCR_ScaleDownBGRA (cls.capturevideo.screenbuffer, vid.width, vid.height, cls.capturevideo.outbuffer, width, height);
1576                 in = cls.capturevideo.outbuffer;
1577                 out = cls.capturevideo.outbuffer + width*height*4;
1578                 SCR_CaptureVideo_ConvertFrame_BGRA_to_I420_flip(width, height, in, out);
1579                 x = width*height+(width/2)*(height/2)*2;
1580                 SCR_CaptureVideo_RIFF_OverflowCheck(8 + x);
1581                 for (;cls.capturevideo.frame < newframenum;cls.capturevideo.frame++)
1582                 {
1583                         SCR_CaptureVideo_RIFF_IndexEntry("00dc", x, 0x10); // AVIIF_KEYFRAME
1584                         SCR_CaptureVideo_RIFF_Push("00dc", NULL);
1585                         SCR_CaptureVideo_RIFF_WriteBytes(out, x);
1586                         SCR_CaptureVideo_RIFF_Pop();
1587                 }
1588                 return true;
1589         default:
1590                 return false;
1591         }
1592 }
1593
1594 void SCR_CaptureVideo_SoundFrame(unsigned char *bufstereo16le, size_t length, int rate)
1595 {
1596         int x;
1597         cls.capturevideo.soundrate = rate;
1598         cls.capturevideo.soundsampleframe += length;
1599         switch (cls.capturevideo.format)
1600         {
1601         case CAPTUREVIDEOFORMAT_AVI_I420:
1602                 x = length*4;
1603                 SCR_CaptureVideo_RIFF_OverflowCheck(8 + x);
1604                 SCR_CaptureVideo_RIFF_IndexEntry("01wb", x, 0x10); // AVIIF_KEYFRAME
1605                 SCR_CaptureVideo_RIFF_Push("01wb", NULL);
1606                 SCR_CaptureVideo_RIFF_WriteBytes(bufstereo16le, x);
1607                 SCR_CaptureVideo_RIFF_Pop();
1608                 break;
1609         default:
1610                 break;
1611         }
1612 }
1613
1614 void SCR_CaptureVideo(void)
1615 {
1616         int newframenum;
1617         if (cl_capturevideo.integer && r_render.integer)
1618         {
1619                 if (!cls.capturevideo.active)
1620                         SCR_CaptureVideo_BeginVideo();
1621                 if (cls.capturevideo.framerate != cl_capturevideo_fps.value)
1622                 {
1623                         Con_Printf("You can not change the video framerate while recording a video.\n");
1624                         Cvar_SetValueQuick(&cl_capturevideo_fps, cls.capturevideo.framerate);
1625                 }
1626                 // for AVI saving we have to make sure that sound is saved before video
1627                 if (cls.capturevideo.soundrate && !cls.capturevideo.soundsampleframe)
1628                         return;
1629                 if (cls.capturevideo.realtime)
1630                 {
1631                         // preserve sound sync by duplicating frames when running slow
1632                         newframenum = (int)((realtime - cls.capturevideo.starttime) * cls.capturevideo.framerate);
1633                 }
1634                 else
1635                         newframenum = cls.capturevideo.frame + 1;
1636                 // if falling behind more than one second, stop
1637                 if (newframenum - cls.capturevideo.frame > 60 * (int)ceil(cls.capturevideo.framerate))
1638                 {
1639                         Cvar_SetValueQuick(&cl_capturevideo, 0);
1640                         Con_Printf("video saving failed on frame %i, your machine is too slow for this capture speed.\n", cls.capturevideo.frame);
1641                         SCR_CaptureVideo_EndVideo();
1642                         return;
1643                 }
1644                 // write frames
1645                 SCR_CaptureVideo_VideoFrame(newframenum);
1646                 if (cls.capturevideo.error)
1647                 {
1648                         Cvar_SetValueQuick(&cl_capturevideo, 0);
1649                         Con_Printf("video saving failed on frame %i, out of disk space? stopping video capture.\n", cls.capturevideo.frame);
1650                         SCR_CaptureVideo_EndVideo();
1651                 }
1652         }
1653         else if (cls.capturevideo.active)
1654                 SCR_CaptureVideo_EndVideo();
1655 }
1656
1657 /*
1658 ===============
1659 R_Envmap_f
1660
1661 Grab six views for environment mapping tests
1662 ===============
1663 */
1664 struct envmapinfo_s
1665 {
1666         float angles[3];
1667         char *name;
1668         qboolean flipx, flipy, flipdiagonaly;
1669 }
1670 envmapinfo[12] =
1671 {
1672         {{  0,   0, 0}, "rt", false, false, false},
1673         {{  0, 270, 0}, "ft", false, false, false},
1674         {{  0, 180, 0}, "lf", false, false, false},
1675         {{  0,  90, 0}, "bk", false, false, false},
1676         {{-90, 180, 0}, "up",  true,  true, false},
1677         {{ 90, 180, 0}, "dn",  true,  true, false},
1678
1679         {{  0,   0, 0}, "px",  true,  true,  true},
1680         {{  0,  90, 0}, "py", false,  true, false},
1681         {{  0, 180, 0}, "nx", false, false,  true},
1682         {{  0, 270, 0}, "ny",  true, false, false},
1683         {{-90, 180, 0}, "pz", false, false,  true},
1684         {{ 90, 180, 0}, "nz", false, false,  true}
1685 };
1686
1687 static void R_Envmap_f (void)
1688 {
1689         int j, size;
1690         char filename[MAX_QPATH], basename[MAX_QPATH];
1691         unsigned char *buffer1;
1692         unsigned char *buffer2;
1693         unsigned char *buffer3;
1694
1695         if (Cmd_Argc() != 3)
1696         {
1697                 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");
1698                 return;
1699         }
1700
1701         strlcpy (basename, Cmd_Argv(1), sizeof (basename));
1702         size = atoi(Cmd_Argv(2));
1703         if (size != 128 && size != 256 && size != 512 && size != 1024)
1704         {
1705                 Con_Print("envmap: size must be one of 128, 256, 512, or 1024\n");
1706                 return;
1707         }
1708         if (size > vid.width || size > vid.height)
1709         {
1710                 Con_Print("envmap: your resolution is not big enough to render that size\n");
1711                 return;
1712         }
1713
1714         r_refdef.envmap = true;
1715
1716         R_UpdateVariables();
1717
1718         r_refdef.view.x = 0;
1719         r_refdef.view.y = 0;
1720         r_refdef.view.z = 0;
1721         r_refdef.view.width = size;
1722         r_refdef.view.height = size;
1723         r_refdef.view.depth = 1;
1724         r_refdef.view.useperspective = true;
1725         r_refdef.view.isoverlay = false;
1726
1727         r_refdef.view.frustum_x = tan(90 * M_PI / 360.0);
1728         r_refdef.view.frustum_y = tan(90 * M_PI / 360.0);
1729
1730         buffer1 = (unsigned char *)Mem_Alloc(tempmempool, size * size * 3);
1731         buffer2 = (unsigned char *)Mem_Alloc(tempmempool, size * size * 3);
1732         buffer3 = (unsigned char *)Mem_Alloc(tempmempool, size * size * 3 + 18);
1733
1734         for (j = 0;j < 12;j++)
1735         {
1736                 sprintf(filename, "env/%s%s.tga", basename, envmapinfo[j].name);
1737                 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);
1738                 r_refdef.view.quality = 1;
1739                 r_refdef.view.clear = true;
1740                 R_Mesh_Start();
1741                 R_RenderView();
1742                 R_Mesh_Finish();
1743                 SCR_ScreenShot(filename, buffer1, buffer2, buffer3, 0, vid.height - (r_refdef.view.y + r_refdef.view.height), size, size, envmapinfo[j].flipx, envmapinfo[j].flipy, envmapinfo[j].flipdiagonaly, false, false);
1744         }
1745
1746         Mem_Free (buffer1);
1747         Mem_Free (buffer2);
1748         Mem_Free (buffer3);
1749
1750         r_refdef.envmap = false;
1751 }
1752
1753 //=============================================================================
1754
1755 void SHOWLMP_decodehide(void)
1756 {
1757         int i;
1758         char *lmplabel;
1759         lmplabel = MSG_ReadString();
1760         for (i = 0;i < cl.num_showlmps;i++)
1761                 if (cl.showlmps[i].isactive && strcmp(cl.showlmps[i].label, lmplabel) == 0)
1762                 {
1763                         cl.showlmps[i].isactive = false;
1764                         return;
1765                 }
1766 }
1767
1768 void SHOWLMP_decodeshow(void)
1769 {
1770         int k;
1771         char lmplabel[256], picname[256];
1772         float x, y;
1773         strlcpy (lmplabel,MSG_ReadString(), sizeof (lmplabel));
1774         strlcpy (picname, MSG_ReadString(), sizeof (picname));
1775         if (gamemode == GAME_NEHAHRA) // LordHavoc: nasty old legacy junk
1776         {
1777                 x = MSG_ReadByte();
1778                 y = MSG_ReadByte();
1779         }
1780         else
1781         {
1782                 x = MSG_ReadShort();
1783                 y = MSG_ReadShort();
1784         }
1785         if (!cl.showlmps || cl.num_showlmps >= cl.max_showlmps)
1786         {
1787                 showlmp_t *oldshowlmps = cl.showlmps;
1788                 cl.max_showlmps += 16;
1789                 cl.showlmps = Mem_Alloc(cls.levelmempool, cl.max_showlmps * sizeof(showlmp_t));
1790                 if (cl.num_showlmps)
1791                         memcpy(cl.showlmps, oldshowlmps, cl.num_showlmps * sizeof(showlmp_t));
1792                 if (oldshowlmps)
1793                         Mem_Free(oldshowlmps);
1794         }
1795         for (k = 0;k < cl.max_showlmps;k++)
1796                 if (cl.showlmps[k].isactive && !strcmp(cl.showlmps[k].label, lmplabel))
1797                         break;
1798         if (k == cl.max_showlmps)
1799                 for (k = 0;k < cl.max_showlmps;k++)
1800                         if (!cl.showlmps[k].isactive)
1801                                 break;
1802         cl.showlmps[k].isactive = true;
1803         strlcpy (cl.showlmps[k].label, lmplabel, sizeof (cl.showlmps[k].label));
1804         strlcpy (cl.showlmps[k].pic, picname, sizeof (cl.showlmps[k].pic));
1805         cl.showlmps[k].x = x;
1806         cl.showlmps[k].y = y;
1807         cl.num_showlmps = max(cl.num_showlmps, k + 1);
1808 }
1809
1810 void SHOWLMP_drawall(void)
1811 {
1812         int i;
1813         for (i = 0;i < cl.num_showlmps;i++)
1814                 if (cl.showlmps[i].isactive)
1815                         DrawQ_Pic(cl.showlmps[i].x, cl.showlmps[i].y, Draw_CachePic (cl.showlmps[i].pic), 0, 0, 1, 1, 1, 1, 0);
1816 }
1817
1818 /*
1819 ==============================================================================
1820
1821                                                 SCREEN SHOTS
1822
1823 ==============================================================================
1824 */
1825
1826 qboolean SCR_ScreenShot(char *filename, unsigned char *buffer1, unsigned char *buffer2, unsigned char *buffer3, int x, int y, int width, int height, qboolean flipx, qboolean flipy, qboolean flipdiagonal, qboolean jpeg, qboolean gammacorrect)
1827 {
1828         int     indices[3] = {0,1,2};
1829         qboolean ret;
1830
1831         if (!r_render.integer)
1832                 return false;
1833
1834         CHECKGLERROR
1835         qglReadPixels (x, y, width, height, jpeg ? GL_RGB : GL_BGR, GL_UNSIGNED_BYTE, buffer1);CHECKGLERROR
1836
1837         if (scr_screenshot_gammaboost.value != 1 && gammacorrect)
1838         {
1839                 int i;
1840                 double igamma = 1.0 / scr_screenshot_gammaboost.value;
1841                 unsigned char ramp[256];
1842                 for (i = 0;i < 256;i++)
1843                         ramp[i] = (unsigned char) (pow(i * (1.0 / 255.0), igamma) * 255.0);
1844                 for (i = 0;i < width*height*3;i++)
1845                         buffer1[i] = ramp[buffer1[i]];
1846         }
1847
1848         Image_CopyMux (buffer2, buffer1, width, height, flipx, flipy, flipdiagonal, 3, 3, indices);
1849
1850         if (jpeg)
1851                 ret = JPEG_SaveImage_preflipped (filename, width, height, buffer2);
1852         else
1853                 ret = Image_WriteTGABGR_preflipped (filename, width, height, buffer2, buffer3);
1854
1855         return ret;
1856 }
1857
1858 //=============================================================================
1859
1860 extern void R_UpdateFogColor(void);
1861 void R_ClearScreen(qboolean fogcolor)
1862 {
1863         // clear to black
1864         CHECKGLERROR
1865         if (fogcolor)
1866         {
1867                 R_UpdateFogColor();
1868                 qglClearColor(r_refdef.fogcolor[0],r_refdef.fogcolor[1],r_refdef.fogcolor[2],0);CHECKGLERROR
1869         }
1870         else
1871         {
1872                 qglClearColor(0,0,0,0);CHECKGLERROR
1873         }
1874         qglClearDepth(1);CHECKGLERROR
1875         if (gl_stencil)
1876         {
1877                 // LordHavoc: we use a stencil centered around 128 instead of 0,
1878                 // to avoid clamping interfering with strange shadow volume
1879                 // drawing orders
1880                 qglClearStencil(128);CHECKGLERROR
1881         }
1882         // clear the screen
1883         if (r_render.integer)
1884                 GL_Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | (gl_stencil ? GL_STENCIL_BUFFER_BIT : 0));
1885         // set dithering mode
1886         if (gl_dither.integer)
1887         {
1888                 qglEnable(GL_DITHER);CHECKGLERROR
1889         }
1890         else
1891         {
1892                 qglDisable(GL_DITHER);CHECKGLERROR
1893         }
1894 }
1895
1896 qboolean CL_VM_UpdateView (void);
1897 void SCR_DrawConsole (void);
1898 void R_Shadow_EditLights_DrawSelectedLightProperties(void);
1899
1900 int r_stereo_side;
1901
1902 void SCR_DrawScreen (void)
1903 {
1904         R_Mesh_Start();
1905
1906         R_TimeReport_BeginFrame();
1907
1908         R_UpdateVariables();
1909
1910         // Quake uses clockwise winding, so these are swapped
1911         r_refdef.view.cullface_front = GL_BACK;
1912         r_refdef.view.cullface_back = GL_FRONT;
1913
1914         if (cls.signon == SIGNONS)
1915         {
1916                 float size;
1917
1918                 size = scr_viewsize.value * (1.0 / 100.0);
1919                 size = min(size, 1);
1920
1921                 if (r_stereo_sidebyside.integer)
1922                 {
1923                         r_refdef.view.width = (int)(vid.width * size / 2.5);
1924                         r_refdef.view.height = (int)(vid.height * size / 2.5 * (1 - bound(0, r_letterbox.value, 100) / 100));
1925                         r_refdef.view.depth = 1;
1926                         r_refdef.view.x = (int)((vid.width - r_refdef.view.width * 2.5) * 0.5);
1927                         r_refdef.view.y = (int)((vid.height - r_refdef.view.height)/2);
1928                         r_refdef.view.z = 0;
1929                         if (r_stereo_side)
1930                                 r_refdef.view.x += (int)(r_refdef.view.width * 1.5);
1931                 }
1932                 else
1933                 {
1934                         r_refdef.view.width = (int)(vid.width * size);
1935                         r_refdef.view.height = (int)(vid.height * size * (1 - bound(0, r_letterbox.value, 100) / 100));
1936                         r_refdef.view.depth = 1;
1937                         r_refdef.view.x = (int)((vid.width - r_refdef.view.width)/2);
1938                         r_refdef.view.y = (int)((vid.height - r_refdef.view.height)/2);
1939                         r_refdef.view.z = 0;
1940                 }
1941
1942                 // LordHavoc: viewzoom (zoom in for sniper rifles, etc)
1943                 // LordHavoc: this is designed to produce widescreen fov values
1944                 // when the screen is wider than 4/3 width/height aspect, to do
1945                 // this it simply assumes the requested fov is the vertical fov
1946                 // for a 4x3 display, if the ratio is not 4x3 this makes the fov
1947                 // higher/lower according to the ratio
1948                 r_refdef.view.useperspective = true;
1949                 r_refdef.view.frustum_y = tan(scr_fov.value * M_PI / 360.0) * (3.0/4.0) * cl.viewzoom;
1950                 r_refdef.view.frustum_x = r_refdef.view.frustum_y * (float)r_refdef.view.width / (float)r_refdef.view.height / vid_pixelheight.value;
1951
1952                 r_refdef.view.frustum_x *= r_refdef.frustumscale_x;
1953                 r_refdef.view.frustum_y *= r_refdef.frustumscale_y;
1954
1955                 if(!CL_VM_UpdateView())
1956                         R_RenderView();
1957
1958                 if (scr_zoomwindow.integer)
1959                 {
1960                         float sizex = bound(10, scr_zoomwindow_viewsizex.value, 100) / 100.0;
1961                         float sizey = bound(10, scr_zoomwindow_viewsizey.value, 100) / 100.0;
1962                         r_refdef.view.width = (int)(vid.width * sizex);
1963                         r_refdef.view.height = (int)(vid.height * sizey);
1964                         r_refdef.view.depth = 1;
1965                         r_refdef.view.x = (int)((vid.width - r_refdef.view.width)/2);
1966                         r_refdef.view.y = 0;
1967                         r_refdef.view.z = 0;
1968
1969                         r_refdef.view.useperspective = true;
1970                         r_refdef.view.frustum_y = tan(scr_zoomwindow_fov.value * M_PI / 360.0) * (3.0/4.0) * cl.viewzoom;
1971                         r_refdef.view.frustum_x = r_refdef.view.frustum_y * vid_pixelheight.value * (float)r_refdef.view.width / (float)r_refdef.view.height;
1972
1973                         r_refdef.view.frustum_x *= r_refdef.frustumscale_x;
1974                         r_refdef.view.frustum_y *= r_refdef.frustumscale_y;
1975
1976                         if(!CL_VM_UpdateView())
1977                                 R_RenderView();
1978                 }
1979         }
1980
1981         if (!r_stereo_sidebyside.integer)
1982         {
1983                 r_refdef.view.width = vid.width;
1984                 r_refdef.view.height = vid.height;
1985                 r_refdef.view.depth = 1;
1986                 r_refdef.view.x = 0;
1987                 r_refdef.view.y = 0;
1988                 r_refdef.view.z = 0;
1989                 r_refdef.view.useperspective = false;
1990         }
1991
1992         // draw 2D stuff
1993         if(!scr_con_current && !(key_consoleactive & KEY_CONSOLEACTIVE_FORCED))
1994                 if ((key_dest == key_game || key_dest == key_message) && !r_letterbox.value)
1995                         Con_DrawNotify ();      // only draw notify in game
1996
1997         if (cls.signon == SIGNONS)
1998         {
1999                 SCR_DrawNet ();
2000                 SCR_DrawTurtle ();
2001                 SCR_DrawPause ();
2002                 if (!r_letterbox.value)
2003                         Sbar_Draw();
2004                 SHOWLMP_drawall();
2005                 SCR_CheckDrawCenterString();
2006         }
2007         SCR_DrawNetGraph ();
2008         MR_Draw();
2009         CL_DrawVideo();
2010         R_Shadow_EditLights_DrawSelectedLightProperties();
2011
2012         SCR_DrawConsole();
2013
2014         SCR_DrawBrand();
2015
2016         SCR_DrawDownload();
2017
2018         if (r_timereport_active)
2019                 R_TimeReport("2d");
2020
2021         if (cls.signon == SIGNONS)
2022                 R_TimeReport_EndFrame();
2023
2024         DrawQ_Finish();
2025
2026         R_DrawGamma();
2027
2028         R_Mesh_Finish();
2029 }
2030
2031 void SCR_UpdateLoadingScreen (qboolean clear)
2032 {
2033         float x, y;
2034         cachepic_t *pic;
2035         float vertex3f[12];
2036         float texcoord2f[8];
2037         // don't do anything if not initialized yet
2038         if (vid_hidden || !scr_refresh.integer)
2039                 return;
2040         // release mouse grab while loading
2041         if (!vid.fullscreen)
2042                 VID_SetMouse(false, false, false);
2043         CHECKGLERROR
2044         qglViewport(0, 0, vid.width, vid.height);CHECKGLERROR
2045         //qglDisable(GL_SCISSOR_TEST);CHECKGLERROR
2046         //qglDepthMask(1);CHECKGLERROR
2047         qglColorMask(1,1,1,1);CHECKGLERROR
2048         qglClearColor(0,0,0,0);CHECKGLERROR
2049         // when starting up a new video mode, make sure the screen is cleared to black
2050         if (clear)
2051         {
2052                 qglClear(GL_COLOR_BUFFER_BIT);CHECKGLERROR
2053         }
2054         //qglDisable(GL_CULL_FACE);CHECKGLERROR
2055         //R_ClearScreen();
2056         R_Textures_Frame();
2057         GL_SetupView_Mode_Ortho(0, 0, vid_conwidth.integer, vid_conheight.integer, -10, 100);
2058         R_Mesh_Start();
2059         R_Mesh_Matrix(&identitymatrix);
2060         // draw the loading plaque
2061         pic = Draw_CachePic ("gfx/loading");
2062         x = (vid_conwidth.integer - pic->width)/2;
2063         y = (vid_conheight.integer - pic->height)/2;
2064         GL_Color(1,1,1,1);
2065         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2066         GL_DepthRange(0, 1);
2067         GL_PolygonOffset(0, 0);
2068         GL_DepthTest(false);
2069         R_Mesh_VertexPointer(vertex3f, 0, 0);
2070         R_Mesh_ColorPointer(NULL, 0, 0);
2071         R_Mesh_ResetTextureState();
2072         R_Mesh_TexBind(0, R_GetTexture(pic->tex));
2073         R_Mesh_TexCoordPointer(0, 2, texcoord2f, 0, 0);
2074         R_SetupGenericShader(true);
2075         vertex3f[2] = vertex3f[5] = vertex3f[8] = vertex3f[11] = 0;
2076         vertex3f[0] = vertex3f[9] = x;
2077         vertex3f[1] = vertex3f[4] = y;
2078         vertex3f[3] = vertex3f[6] = x + pic->width;
2079         vertex3f[7] = vertex3f[10] = y + pic->height;
2080         texcoord2f[0] = 0;texcoord2f[1] = 0;
2081         texcoord2f[2] = 1;texcoord2f[3] = 0;
2082         texcoord2f[4] = 1;texcoord2f[5] = 1;
2083         texcoord2f[6] = 0;texcoord2f[7] = 1;
2084         if (vid.stereobuffer)
2085         {
2086                 qglDrawBuffer(GL_FRONT_LEFT);
2087                 R_Mesh_Draw(0, 4, 0, 2, NULL, polygonelements, 0, 0);
2088                 qglDrawBuffer(GL_FRONT_RIGHT);
2089                 R_Mesh_Draw(0, 4, 0, 2, NULL, polygonelements, 0, 0);
2090         }
2091         else
2092         {
2093                 qglDrawBuffer(GL_FRONT);
2094                 R_Mesh_Draw(0, 4, 0, 2, NULL, polygonelements, 0, 0);
2095         }
2096         R_Mesh_Finish();
2097         // refresh
2098         // not necessary when rendering to GL_FRONT buffers
2099         //VID_Finish();
2100         // however this IS necessary on Windows Vista
2101         qglFinish();
2102 }
2103
2104 extern cvar_t cl_minfps;
2105 extern cvar_t cl_minfps_fade;
2106 extern cvar_t cl_minfps_qualitymax;
2107 extern cvar_t cl_minfps_qualitymin;
2108 extern cvar_t cl_minfps_qualitypower;
2109 extern cvar_t cl_minfps_qualityscale;
2110 static double cl_updatescreen_rendertime = 0;
2111 static double cl_updatescreen_quality = 1;
2112 void CL_UpdateScreen(void)
2113 {
2114         double rendertime1;
2115         float conwidth, conheight;
2116
2117         if (!scr_initialized || !con_initialized)
2118                 return;                         // not initialized yet
2119
2120         if(gamemode == GAME_NEXUIZ)
2121         {
2122                 // play a bit with the palette (experimental)
2123                 palette_rgb_pantscolormap[15][0] = 128 + 127 * sin(cl.time / exp(1) + 0*M_PI/3);
2124                 palette_rgb_pantscolormap[15][1] = 128 + 127 * sin(cl.time / exp(1) + 2*M_PI/3);
2125                 palette_rgb_pantscolormap[15][2] = 128 + 127 * sin(cl.time / exp(1) + 4*M_PI/3);
2126                 palette_rgb_shirtcolormap[15][0] = 128 + 127 * sin(cl.time /  M_PI  + 5*M_PI/3);
2127                 palette_rgb_shirtcolormap[15][1] = 128 + 127 * sin(cl.time /  M_PI  + 3*M_PI/3);
2128                 palette_rgb_shirtcolormap[15][2] = 128 + 127 * sin(cl.time /  M_PI  + 1*M_PI/3);
2129                 memcpy(palette_rgb_pantsscoreboard[15], palette_rgb_pantscolormap[15], sizeof(*palette_rgb_pantscolormap));
2130                 memcpy(palette_rgb_shirtscoreboard[15], palette_rgb_shirtcolormap[15], sizeof(*palette_rgb_shirtcolormap));
2131         }
2132
2133         if (vid_hidden || !scr_refresh.integer)
2134                 return;
2135
2136         rendertime1 = Sys_DoubleTime();
2137
2138         conwidth = bound(320, vid_conwidth.value, 2048);
2139         conheight = bound(200, vid_conheight.value, 1536);
2140         if (vid_conwidth.value != conwidth)
2141                 Cvar_SetValue("vid_conwidth", conwidth);
2142         if (vid_conheight.value != conheight)
2143                 Cvar_SetValue("vid_conheight", conheight);
2144
2145         // bound viewsize
2146         if (scr_viewsize.value < 30)
2147                 Cvar_Set ("viewsize","30");
2148         if (scr_viewsize.value > 120)
2149                 Cvar_Set ("viewsize","120");
2150
2151         // bound field of view
2152         if (scr_fov.value < 1)
2153                 Cvar_Set ("fov","1");
2154         if (scr_fov.value > 170)
2155                 Cvar_Set ("fov","170");
2156
2157         // validate r_textureunits cvar
2158         if (r_textureunits.integer > gl_textureunits)
2159                 Cvar_SetValueQuick(&r_textureunits, gl_textureunits);
2160         if (r_textureunits.integer < 1)
2161                 Cvar_SetValueQuick(&r_textureunits, 1);
2162
2163         // validate gl_combine cvar
2164         if (gl_combine.integer && !gl_combine_extension)
2165                 Cvar_SetValueQuick(&gl_combine, 0);
2166
2167         // intermission is always full screen
2168         if (cl.intermission)
2169                 sb_lines = 0;
2170         else
2171         {
2172                 if (scr_viewsize.value >= 120)
2173                         sb_lines = 0;           // no status bar at all
2174                 else if (scr_viewsize.value >= 110)
2175                         sb_lines = 24;          // no inventory
2176                 else
2177                         sb_lines = 24+16+8;
2178         }
2179
2180         r_refdef.view.colormask[0] = 1;
2181         r_refdef.view.colormask[1] = 1;
2182         r_refdef.view.colormask[2] = 1;
2183
2184         SCR_SetUpToDrawConsole();
2185
2186         CHECKGLERROR
2187         qglDrawBuffer(GL_BACK);CHECKGLERROR
2188         qglViewport(0, 0, vid.width, vid.height);CHECKGLERROR
2189         qglDisable(GL_SCISSOR_TEST);CHECKGLERROR
2190         qglDepthMask(1);CHECKGLERROR
2191         qglColorMask(1,1,1,1);CHECKGLERROR
2192         qglClearColor(0,0,0,0);CHECKGLERROR
2193         R_ClearScreen(false);
2194         r_refdef.view.clear = false;
2195         r_refdef.view.isoverlay = false;
2196         r_refdef.view.quality = bound(cl_minfps_qualitymin.value, pow(cl_updatescreen_quality, cl_minfps_qualitypower.value) * cl_minfps_qualityscale.value, cl_minfps_qualitymax.value);
2197
2198         if(scr_stipple.integer)
2199         {
2200                 GLubyte stipple[128];
2201                 int i, s, width, parts;
2202                 static int frame = 0;
2203                 ++frame;
2204
2205                 s = scr_stipple.integer;
2206                 parts = (s & 007);
2207                 width = (s & 070) >> 3;
2208
2209                 qglEnable(GL_POLYGON_STIPPLE); // 0x0B42
2210                 for(i = 0; i < 128; ++i)
2211                 {
2212                         int line = i/4;
2213                         stipple[i] = (((line >> width) + frame) & ((1 << parts) - 1)) ? 0x00 : 0xFF;
2214                 }
2215                 qglPolygonStipple(stipple);
2216         }
2217         else
2218                 qglDisable(GL_POLYGON_STIPPLE);
2219
2220         if (vid.stereobuffer || r_stereo_redblue.integer || r_stereo_redgreen.integer || r_stereo_redcyan.integer || r_stereo_sidebyside.integer)
2221         {
2222                 matrix4x4_t originalmatrix = r_refdef.view.matrix;
2223                 matrix4x4_t offsetmatrix;
2224                 Matrix4x4_CreateFromQuakeEntity(&offsetmatrix, 0, r_stereo_separation.value * 0.5f, 0, 0, r_stereo_angle.value * 0.5f, 0, 1);
2225                 Matrix4x4_Concat(&r_refdef.view.matrix, &originalmatrix, &offsetmatrix);
2226
2227                 if (r_stereo_sidebyside.integer)
2228                         r_stereo_side = 0;
2229
2230                 if (r_stereo_redblue.integer || r_stereo_redgreen.integer || r_stereo_redcyan.integer)
2231                 {
2232                         r_refdef.view.colormask[0] = 1;
2233                         r_refdef.view.colormask[1] = 0;
2234                         r_refdef.view.colormask[2] = 0;
2235                 }
2236
2237                 if (vid.stereobuffer)
2238                         qglDrawBuffer(GL_BACK_RIGHT);
2239
2240                 SCR_DrawScreen();
2241
2242                 Matrix4x4_CreateFromQuakeEntity(&offsetmatrix, 0, r_stereo_separation.value * -0.5f, 0, 0, r_stereo_angle.value * -0.5f, 0, 1);
2243                 Matrix4x4_Concat(&r_refdef.view.matrix, &originalmatrix, &offsetmatrix);
2244
2245                 if (r_stereo_sidebyside.integer)
2246                         r_stereo_side = 1;
2247
2248                 if (r_stereo_redblue.integer || r_stereo_redgreen.integer || r_stereo_redcyan.integer)
2249                 {
2250                         r_refdef.view.colormask[0] = 0;
2251                         r_refdef.view.colormask[1] = r_stereo_redcyan.integer || r_stereo_redgreen.integer;
2252                         r_refdef.view.colormask[2] = r_stereo_redcyan.integer || r_stereo_redblue.integer;
2253                 }
2254
2255                 if (vid.stereobuffer)
2256                         qglDrawBuffer(GL_BACK_LEFT);
2257
2258                 SCR_DrawScreen();
2259
2260                 r_refdef.view.matrix = originalmatrix;
2261         }
2262         else
2263                 SCR_DrawScreen();
2264
2265         SCR_CaptureVideo();
2266
2267         // quality adjustment according to render time
2268         qglFlush();
2269         cl_updatescreen_rendertime += ((Sys_DoubleTime() - rendertime1) - cl_updatescreen_rendertime) * bound(0, cl_minfps_fade.value, 1);
2270         if (cl_minfps.value > 0 && cl_updatescreen_rendertime > 0 && !cls.timedemo && (!cls.capturevideo.active || !cls.capturevideo.realtime))
2271                 cl_updatescreen_quality = 1 / (cl_updatescreen_rendertime * cl_minfps.value);
2272         else
2273                 cl_updatescreen_quality = 1;
2274
2275         if (!vid_activewindow)
2276                 VID_SetMouse(false, false, false);
2277         else if (key_consoleactive)
2278                 VID_SetMouse(vid.fullscreen, false, false);
2279         else if (key_dest == key_menu_grabbed)
2280                 VID_SetMouse(true, !in_client_mouse, true);
2281         else if (key_dest == key_menu)
2282                 VID_SetMouse(vid.fullscreen, !in_client_mouse, true);
2283         else
2284                 VID_SetMouse(vid.fullscreen, vid_mouse.integer && !cls.demoplayback && !cl.csqc_wantsmousemove, true);
2285
2286         VID_Finish();
2287 }
2288
2289 void CL_Screen_NewMap(void)
2290 {
2291 }