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