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