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