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