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