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