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